PluginProbe
Gutenberg / 20.2.0
Gutenberg v20.2.0
23.9.1 23.9.0 23.8.0 23.7.2 23.7.1 23.7.0 23.6.1 23.6.2 23.6.0 23.5.3 23.5.2 23.5.1 23.5.0 23.4.0 23.3.2 23.3.1 23.3.0 23.2.0 23.2.1 23.2.2 23.1.1 23.1.0 23.0.1 12.6.0 7.4.0 All 402 releases
gutenberg / build / data / index.js

index.js in Gutenberg 20.2.0, at build/data/index.js

4,471 lines 140.9 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 /******/ (() => { // webpackBootstrap
2 /******/ "use strict";
3 /******/ var __webpack_modules__ = ({
4
5 /***/ 66:
6 /***/ ((module) => {
7
8
9
10 var isMergeableObject = function isMergeableObject(value) {
11 return isNonNullObject(value)
12 && !isSpecial(value)
13 };
14
15 function isNonNullObject(value) {
16 return !!value && typeof value === 'object'
17 }
18
19 function isSpecial(value) {
20 var stringValue = Object.prototype.toString.call(value);
21
22 return stringValue === '[object RegExp]'
23 || stringValue === '[object Date]'
24 || isReactElement(value)
25 }
26
27 // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
28 var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
29 var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
30
31 function isReactElement(value) {
32 return value.$$typeof === REACT_ELEMENT_TYPE
33 }
34
35 function emptyTarget(val) {
36 return Array.isArray(val) ? [] : {}
37 }
38
39 function cloneUnlessOtherwiseSpecified(value, options) {
40 return (options.clone !== false && options.isMergeableObject(value))
41 ? deepmerge(emptyTarget(value), value, options)
42 : value
43 }
44
45 function defaultArrayMerge(target, source, options) {
46 return target.concat(source).map(function(element) {
47 return cloneUnlessOtherwiseSpecified(element, options)
48 })
49 }
50
51 function getMergeFunction(key, options) {
52 if (!options.customMerge) {
53 return deepmerge
54 }
55 var customMerge = options.customMerge(key);
56 return typeof customMerge === 'function' ? customMerge : deepmerge
57 }
58
59 function getEnumerableOwnPropertySymbols(target) {
60 return Object.getOwnPropertySymbols
61 ? Object.getOwnPropertySymbols(target).filter(function(symbol) {
62 return Object.propertyIsEnumerable.call(target, symbol)
63 })
64 : []
65 }
66
67 function getKeys(target) {
68 return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target))
69 }
70
71 function propertyIsOnObject(object, property) {
72 try {
73 return property in object
74 } catch(_) {
75 return false
76 }
77 }
78
79 // Protects from prototype poisoning and unexpected merging up the prototype chain.
80 function propertyIsUnsafe(target, key) {
81 return propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet,
82 && !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain,
83 && Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable.
84 }
85
86 function mergeObject(target, source, options) {
87 var destination = {};
88 if (options.isMergeableObject(target)) {
89 getKeys(target).forEach(function(key) {
90 destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);
91 });
92 }
93 getKeys(source).forEach(function(key) {
94 if (propertyIsUnsafe(target, key)) {
95 return
96 }
97
98 if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) {
99 destination[key] = getMergeFunction(key, options)(target[key], source[key], options);
100 } else {
101 destination[key] = cloneUnlessOtherwiseSpecified(source[key], options);
102 }
103 });
104 return destination
105 }
106
107 function deepmerge(target, source, options) {
108 options = options || {};
109 options.arrayMerge = options.arrayMerge || defaultArrayMerge;
110 options.isMergeableObject = options.isMergeableObject || isMergeableObject;
111 // cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge()
112 // implementations can use it. The caller may not replace it.
113 options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified;
114
115 var sourceIsArray = Array.isArray(source);
116 var targetIsArray = Array.isArray(target);
117 var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
118
119 if (!sourceAndTargetTypesMatch) {
120 return cloneUnlessOtherwiseSpecified(source, options)
121 } else if (sourceIsArray) {
122 return options.arrayMerge(target, source, options)
123 } else {
124 return mergeObject(target, source, options)
125 }
126 }
127
128 deepmerge.all = function deepmergeAll(array, options) {
129 if (!Array.isArray(array)) {
130 throw new Error('first argument should be an array')
131 }
132
133 return array.reduce(function(prev, next) {
134 return deepmerge(prev, next, options)
135 }, {})
136 };
137
138 var deepmerge_1 = deepmerge;
139
140 module.exports = deepmerge_1;
141
142
143 /***/ }),
144
145 /***/ 3249:
146 /***/ ((module) => {
147
148
149
150 function _typeof(obj) {
151 if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
152 _typeof = function (obj) {
153 return typeof obj;
154 };
155 } else {
156 _typeof = function (obj) {
157 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
158 };
159 }
160
161 return _typeof(obj);
162 }
163
164 function _classCallCheck(instance, Constructor) {
165 if (!(instance instanceof Constructor)) {
166 throw new TypeError("Cannot call a class as a function");
167 }
168 }
169
170 function _defineProperties(target, props) {
171 for (var i = 0; i < props.length; i++) {
172 var descriptor = props[i];
173 descriptor.enumerable = descriptor.enumerable || false;
174 descriptor.configurable = true;
175 if ("value" in descriptor) descriptor.writable = true;
176 Object.defineProperty(target, descriptor.key, descriptor);
177 }
178 }
179
180 function _createClass(Constructor, protoProps, staticProps) {
181 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
182 if (staticProps) _defineProperties(Constructor, staticProps);
183 return Constructor;
184 }
185
186 /**
187 * Given an instance of EquivalentKeyMap, returns its internal value pair tuple
188 * for a key, if one exists. The tuple members consist of the last reference
189 * value for the key (used in efficient subsequent lookups) and the value
190 * assigned for the key at the leaf node.
191 *
192 * @param {EquivalentKeyMap} instance EquivalentKeyMap instance.
193 * @param {*} key The key for which to return value pair.
194 *
195 * @return {?Array} Value pair, if exists.
196 */
197 function getValuePair(instance, key) {
198 var _map = instance._map,
199 _arrayTreeMap = instance._arrayTreeMap,
200 _objectTreeMap = instance._objectTreeMap; // Map keeps a reference to the last object-like key used to set the
201 // value, which can be used to shortcut immediately to the value.
202
203 if (_map.has(key)) {
204 return _map.get(key);
205 } // Sort keys to ensure stable retrieval from tree.
206
207
208 var properties = Object.keys(key).sort(); // Tree by type to avoid conflicts on numeric object keys, empty value.
209
210 var map = Array.isArray(key) ? _arrayTreeMap : _objectTreeMap;
211
212 for (var i = 0; i < properties.length; i++) {
213 var property = properties[i];
214 map = map.get(property);
215
216 if (map === undefined) {
217 return;
218 }
219
220 var propertyValue = key[property];
221 map = map.get(propertyValue);
222
223 if (map === undefined) {
224 return;
225 }
226 }
227
228 var valuePair = map.get('_ekm_value');
229
230 if (!valuePair) {
231 return;
232 } // If reached, it implies that an object-like key was set with another
233 // reference, so delete the reference and replace with the current.
234
235
236 _map.delete(valuePair[0]);
237
238 valuePair[0] = key;
239 map.set('_ekm_value', valuePair);
240
241 _map.set(key, valuePair);
242
243 return valuePair;
244 }
245 /**
246 * Variant of a Map object which enables lookup by equivalent (deeply equal)
247 * object and array keys.
248 */
249
250
251 var EquivalentKeyMap =
252 /*#__PURE__*/
253 function () {
254 /**
255 * Constructs a new instance of EquivalentKeyMap.
256 *
257 * @param {Iterable.<*>} iterable Initial pair of key, value for map.
258 */
259 function EquivalentKeyMap(iterable) {
260 _classCallCheck(this, EquivalentKeyMap);
261
262 this.clear();
263
264 if (iterable instanceof EquivalentKeyMap) {
265 // Map#forEach is only means of iterating with support for IE11.
266 var iterablePairs = [];
267 iterable.forEach(function (value, key) {
268 iterablePairs.push([key, value]);
269 });
270 iterable = iterablePairs;
271 }
272
273 if (iterable != null) {
274 for (var i = 0; i < iterable.length; i++) {
275 this.set(iterable[i][0], iterable[i][1]);
276 }
277 }
278 }
279 /**
280 * Accessor property returning the number of elements.
281 *
282 * @return {number} Number of elements.
283 */
284
285
286 _createClass(EquivalentKeyMap, [{
287 key: "set",
288
289 /**
290 * Add or update an element with a specified key and value.
291 *
292 * @param {*} key The key of the element to add.
293 * @param {*} value The value of the element to add.
294 *
295 * @return {EquivalentKeyMap} Map instance.
296 */
297 value: function set(key, value) {
298 // Shortcut non-object-like to set on internal Map.
299 if (key === null || _typeof(key) !== 'object') {
300 this._map.set(key, value);
301
302 return this;
303 } // Sort keys to ensure stable assignment into tree.
304
305
306 var properties = Object.keys(key).sort();
307 var valuePair = [key, value]; // Tree by type to avoid conflicts on numeric object keys, empty value.
308
309 var map = Array.isArray(key) ? this._arrayTreeMap : this._objectTreeMap;
310
311 for (var i = 0; i < properties.length; i++) {
312 var property = properties[i];
313
314 if (!map.has(property)) {
315 map.set(property, new EquivalentKeyMap());
316 }
317
318 map = map.get(property);
319 var propertyValue = key[property];
320
321 if (!map.has(propertyValue)) {
322 map.set(propertyValue, new EquivalentKeyMap());
323 }
324
325 map = map.get(propertyValue);
326 } // If an _ekm_value exists, there was already an equivalent key. Before
327 // overriding, ensure that the old key reference is removed from map to
328 // avoid memory leak of accumulating equivalent keys. This is, in a
329 // sense, a poor man's WeakMap, while still enabling iterability.
330
331
332 var previousValuePair = map.get('_ekm_value');
333
334 if (previousValuePair) {
335 this._map.delete(previousValuePair[0]);
336 }
337
338 map.set('_ekm_value', valuePair);
339
340 this._map.set(key, valuePair);
341
342 return this;
343 }
344 /**
345 * Returns a specified element.
346 *
347 * @param {*} key The key of the element to return.
348 *
349 * @return {?*} The element associated with the specified key or undefined
350 * if the key can't be found.
351 */
352
353 }, {
354 key: "get",
355 value: function get(key) {
356 // Shortcut non-object-like to get from internal Map.
357 if (key === null || _typeof(key) !== 'object') {
358 return this._map.get(key);
359 }
360
361 var valuePair = getValuePair(this, key);
362
363 if (valuePair) {
364 return valuePair[1];
365 }
366 }
367 /**
368 * Returns a boolean indicating whether an element with the specified key
369 * exists or not.
370 *
371 * @param {*} key The key of the element to test for presence.
372 *
373 * @return {boolean} Whether an element with the specified key exists.
374 */
375
376 }, {
377 key: "has",
378 value: function has(key) {
379 if (key === null || _typeof(key) !== 'object') {
380 return this._map.has(key);
381 } // Test on the _presence_ of the pair, not its value, as even undefined
382 // can be a valid member value for a key.
383
384
385 return getValuePair(this, key) !== undefined;
386 }
387 /**
388 * Removes the specified element.
389 *
390 * @param {*} key The key of the element to remove.
391 *
392 * @return {boolean} Returns true if an element existed and has been
393 * removed, or false if the element does not exist.
394 */
395
396 }, {
397 key: "delete",
398 value: function _delete(key) {
399 if (!this.has(key)) {
400 return false;
401 } // This naive implementation will leave orphaned child trees. A better
402 // implementation should traverse and remove orphans.
403
404
405 this.set(key, undefined);
406 return true;
407 }
408 /**
409 * Executes a provided function once per each key/value pair, in insertion
410 * order.
411 *
412 * @param {Function} callback Function to execute for each element.
413 * @param {*} thisArg Value to use as `this` when executing
414 * `callback`.
415 */
416
417 }, {
418 key: "forEach",
419 value: function forEach(callback) {
420 var _this = this;
421
422 var thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this;
423
424 this._map.forEach(function (value, key) {
425 // Unwrap value from object-like value pair.
426 if (key !== null && _typeof(key) === 'object') {
427 value = value[1];
428 }
429
430 callback.call(thisArg, value, key, _this);
431 });
432 }
433 /**
434 * Removes all elements.
435 */
436
437 }, {
438 key: "clear",
439 value: function clear() {
440 this._map = new Map();
441 this._arrayTreeMap = new Map();
442 this._objectTreeMap = new Map();
443 }
444 }, {
445 key: "size",
446 get: function get() {
447 return this._map.size;
448 }
449 }]);
450
451 return EquivalentKeyMap;
452 }();
453
454 module.exports = EquivalentKeyMap;
455
456
457 /***/ })
458
459 /******/ });
460 /************************************************************************/
461 /******/ // The module cache
462 /******/ var __webpack_module_cache__ = {};
463 /******/
464 /******/ // The require function
465 /******/ function __webpack_require__(moduleId) {
466 /******/ // Check if module is in cache
467 /******/ var cachedModule = __webpack_module_cache__[moduleId];
468 /******/ if (cachedModule !== undefined) {
469 /******/ return cachedModule.exports;
470 /******/ }
471 /******/ // Create a new module (and put it into the cache)
472 /******/ var module = __webpack_module_cache__[moduleId] = {
473 /******/ // no module.id needed
474 /******/ // no module.loaded needed
475 /******/ exports: {}
476 /******/ };
477 /******/
478 /******/ // Execute the module function
479 /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
480 /******/
481 /******/ // Return the exports of the module
482 /******/ return module.exports;
483 /******/ }
484 /******/
485 /************************************************************************/
486 /******/ /* webpack/runtime/compat get default export */
487 /******/ (() => {
488 /******/ // getDefaultExport function for compatibility with non-harmony modules
489 /******/ __webpack_require__.n = (module) => {
490 /******/ var getter = module && module.__esModule ?
491 /******/ () => (module['default']) :
492 /******/ () => (module);
493 /******/ __webpack_require__.d(getter, { a: getter });
494 /******/ return getter;
495 /******/ };
496 /******/ })();
497 /******/
498 /******/ /* webpack/runtime/define property getters */
499 /******/ (() => {
500 /******/ // define getter functions for harmony exports
501 /******/ __webpack_require__.d = (exports, definition) => {
502 /******/ for(var key in definition) {
503 /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
504 /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
505 /******/ }
506 /******/ }
507 /******/ };
508 /******/ })();
509 /******/
510 /******/ /* webpack/runtime/hasOwnProperty shorthand */
511 /******/ (() => {
512 /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
513 /******/ })();
514 /******/
515 /******/ /* webpack/runtime/make namespace object */
516 /******/ (() => {
517 /******/ // define __esModule on exports
518 /******/ __webpack_require__.r = (exports) => {
519 /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
520 /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
521 /******/ }
522 /******/ Object.defineProperty(exports, '__esModule', { value: true });
523 /******/ };
524 /******/ })();
525 /******/
526 /************************************************************************/
527 var __webpack_exports__ = {};
528 // ESM COMPAT FLAG
529 __webpack_require__.r(__webpack_exports__);
530
531 // EXPORTS
532 __webpack_require__.d(__webpack_exports__, {
533 AsyncModeProvider: () => (/* reexport */ async_mode_provider_context),
534 RegistryConsumer: () => (/* reexport */ RegistryConsumer),
535 RegistryProvider: () => (/* reexport */ context),
536 combineReducers: () => (/* binding */ build_module_combineReducers),
537 controls: () => (/* reexport */ controls),
538 createReduxStore: () => (/* reexport */ createReduxStore),
539 createRegistry: () => (/* reexport */ createRegistry),
540 createRegistryControl: () => (/* reexport */ createRegistryControl),
541 createRegistrySelector: () => (/* reexport */ createRegistrySelector),
542 createSelector: () => (/* reexport */ rememo),
543 dispatch: () => (/* reexport */ dispatch_dispatch),
544 plugins: () => (/* reexport */ plugins_namespaceObject),
545 register: () => (/* binding */ register),
546 registerGenericStore: () => (/* binding */ registerGenericStore),
547 registerStore: () => (/* binding */ registerStore),
548 resolveSelect: () => (/* binding */ build_module_resolveSelect),
549 select: () => (/* reexport */ select_select),
550 subscribe: () => (/* binding */ subscribe),
551 suspendSelect: () => (/* binding */ suspendSelect),
552 use: () => (/* binding */ use),
553 useDispatch: () => (/* reexport */ use_dispatch),
554 useRegistry: () => (/* reexport */ useRegistry),
555 useSelect: () => (/* reexport */ useSelect),
556 useSuspenseSelect: () => (/* reexport */ useSuspenseSelect),
557 withDispatch: () => (/* reexport */ with_dispatch),
558 withRegistry: () => (/* reexport */ with_registry),
559 withSelect: () => (/* reexport */ with_select)
560 });
561
562 // NAMESPACE OBJECT: ./packages/data/build-module/redux-store/metadata/selectors.js
563 var selectors_namespaceObject = {};
564 __webpack_require__.r(selectors_namespaceObject);
565 __webpack_require__.d(selectors_namespaceObject, {
566 countSelectorsByStatus: () => (countSelectorsByStatus),
567 getCachedResolvers: () => (getCachedResolvers),
568 getIsResolving: () => (getIsResolving),
569 getResolutionError: () => (getResolutionError),
570 getResolutionState: () => (getResolutionState),
571 hasFinishedResolution: () => (hasFinishedResolution),
572 hasResolutionFailed: () => (hasResolutionFailed),
573 hasResolvingSelectors: () => (hasResolvingSelectors),
574 hasStartedResolution: () => (hasStartedResolution),
575 isResolving: () => (isResolving)
576 });
577
578 // NAMESPACE OBJECT: ./packages/data/build-module/redux-store/metadata/actions.js
579 var actions_namespaceObject = {};
580 __webpack_require__.r(actions_namespaceObject);
581 __webpack_require__.d(actions_namespaceObject, {
582 failResolution: () => (failResolution),
583 failResolutions: () => (failResolutions),
584 finishResolution: () => (finishResolution),
585 finishResolutions: () => (finishResolutions),
586 invalidateResolution: () => (invalidateResolution),
587 invalidateResolutionForStore: () => (invalidateResolutionForStore),
588 invalidateResolutionForStoreSelector: () => (invalidateResolutionForStoreSelector),
589 startResolution: () => (startResolution),
590 startResolutions: () => (startResolutions)
591 });
592
593 // NAMESPACE OBJECT: ./packages/data/build-module/plugins/index.js
594 var plugins_namespaceObject = {};
595 __webpack_require__.r(plugins_namespaceObject);
596 __webpack_require__.d(plugins_namespaceObject, {
597 persistence: () => (persistence)
598 });
599
600 ;// external ["wp","deprecated"]
601 const external_wp_deprecated_namespaceObject = window["wp"]["deprecated"];
602 var external_wp_deprecated_default = /*#__PURE__*/__webpack_require__.n(external_wp_deprecated_namespaceObject);
603 ;// ./node_modules/redux/dist/redux.mjs
604 // src/utils/formatProdErrorMessage.ts
605 function formatProdErrorMessage(code) {
606 return `Minified Redux error #${code}; visit https://redux.js.org/Errors?code=${code} for the full message or use the non-minified dev environment for full errors. `;
607 }
608
609 // src/utils/symbol-observable.ts
610 var $$observable = /* @__PURE__ */ (() => typeof Symbol === "function" && Symbol.observable || "@@observable")();
611 var symbol_observable_default = $$observable;
612
613 // src/utils/actionTypes.ts
614 var randomString = () => Math.random().toString(36).substring(7).split("").join(".");
615 var ActionTypes = {
616 INIT: `@@redux/INIT${/* @__PURE__ */ randomString()}`,
617 REPLACE: `@@redux/REPLACE${/* @__PURE__ */ randomString()}`,
618 PROBE_UNKNOWN_ACTION: () => `@@redux/PROBE_UNKNOWN_ACTION${randomString()}`
619 };
620 var actionTypes_default = ActionTypes;
621
622 // src/utils/isPlainObject.ts
623 function isPlainObject(obj) {
624 if (typeof obj !== "object" || obj === null)
625 return false;
626 let proto = obj;
627 while (Object.getPrototypeOf(proto) !== null) {
628 proto = Object.getPrototypeOf(proto);
629 }
630 return Object.getPrototypeOf(obj) === proto || Object.getPrototypeOf(obj) === null;
631 }
632
633 // src/utils/kindOf.ts
634 function miniKindOf(val) {
635 if (val === void 0)
636 return "undefined";
637 if (val === null)
638 return "null";
639 const type = typeof val;
640 switch (type) {
641 case "boolean":
642 case "string":
643 case "number":
644 case "symbol":
645 case "function": {
646 return type;
647 }
648 }
649 if (Array.isArray(val))
650 return "array";
651 if (isDate(val))
652 return "date";
653 if (isError(val))
654 return "error";
655 const constructorName = ctorName(val);
656 switch (constructorName) {
657 case "Symbol":
658 case "Promise":
659 case "WeakMap":
660 case "WeakSet":
661 case "Map":
662 case "Set":
663 return constructorName;
664 }
665 return Object.prototype.toString.call(val).slice(8, -1).toLowerCase().replace(/\s/g, "");
666 }
667 function ctorName(val) {
668 return typeof val.constructor === "function" ? val.constructor.name : null;
669 }
670 function isError(val) {
671 return val instanceof Error || typeof val.message === "string" && val.constructor && typeof val.constructor.stackTraceLimit === "number";
672 }
673 function isDate(val) {
674 if (val instanceof Date)
675 return true;
676 return typeof val.toDateString === "function" && typeof val.getDate === "function" && typeof val.setDate === "function";
677 }
678 function kindOf(val) {
679 let typeOfVal = typeof val;
680 if (false) {}
681 return typeOfVal;
682 }
683
684 // src/createStore.ts
685 function createStore(reducer, preloadedState, enhancer) {
686 if (typeof reducer !== "function") {
687 throw new Error( true ? formatProdErrorMessage(2) : 0);
688 }
689 if (typeof preloadedState === "function" && typeof enhancer === "function" || typeof enhancer === "function" && typeof arguments[3] === "function") {
690 throw new Error( true ? formatProdErrorMessage(0) : 0);
691 }
692 if (typeof preloadedState === "function" && typeof enhancer === "undefined") {
693 enhancer = preloadedState;
694 preloadedState = void 0;
695 }
696 if (typeof enhancer !== "undefined") {
697 if (typeof enhancer !== "function") {
698 throw new Error( true ? formatProdErrorMessage(1) : 0);
699 }
700 return enhancer(createStore)(reducer, preloadedState);
701 }
702 let currentReducer = reducer;
703 let currentState = preloadedState;
704 let currentListeners = /* @__PURE__ */ new Map();
705 let nextListeners = currentListeners;
706 let listenerIdCounter = 0;
707 let isDispatching = false;
708 function ensureCanMutateNextListeners() {
709 if (nextListeners === currentListeners) {
710 nextListeners = /* @__PURE__ */ new Map();
711 currentListeners.forEach((listener, key) => {
712 nextListeners.set(key, listener);
713 });
714 }
715 }
716 function getState() {
717 if (isDispatching) {
718 throw new Error( true ? formatProdErrorMessage(3) : 0);
719 }
720 return currentState;
721 }
722 function subscribe(listener) {
723 if (typeof listener !== "function") {
724 throw new Error( true ? formatProdErrorMessage(4) : 0);
725 }
726 if (isDispatching) {
727 throw new Error( true ? formatProdErrorMessage(5) : 0);
728 }
729 let isSubscribed = true;
730 ensureCanMutateNextListeners();
731 const listenerId = listenerIdCounter++;
732 nextListeners.set(listenerId, listener);
733 return function unsubscribe() {
734 if (!isSubscribed) {
735 return;
736 }
737 if (isDispatching) {
738 throw new Error( true ? formatProdErrorMessage(6) : 0);
739 }
740 isSubscribed = false;
741 ensureCanMutateNextListeners();
742 nextListeners.delete(listenerId);
743 currentListeners = null;
744 };
745 }
746 function dispatch(action) {
747 if (!isPlainObject(action)) {
748 throw new Error( true ? formatProdErrorMessage(7) : 0);
749 }
750 if (typeof action.type === "undefined") {
751 throw new Error( true ? formatProdErrorMessage(8) : 0);
752 }
753 if (typeof action.type !== "string") {
754 throw new Error( true ? formatProdErrorMessage(17) : 0);
755 }
756 if (isDispatching) {
757 throw new Error( true ? formatProdErrorMessage(9) : 0);
758 }
759 try {
760 isDispatching = true;
761 currentState = currentReducer(currentState, action);
762 } finally {
763 isDispatching = false;
764 }
765 const listeners = currentListeners = nextListeners;
766 listeners.forEach((listener) => {
767 listener();
768 });
769 return action;
770 }
771 function replaceReducer(nextReducer) {
772 if (typeof nextReducer !== "function") {
773 throw new Error( true ? formatProdErrorMessage(10) : 0);
774 }
775 currentReducer = nextReducer;
776 dispatch({
777 type: actionTypes_default.REPLACE
778 });
779 }
780 function observable() {
781 const outerSubscribe = subscribe;
782 return {
783 /**
784 * The minimal observable subscription method.
785 * @param observer Any object that can be used as an observer.
786 * The observer object should have a `next` method.
787 * @returns An object with an `unsubscribe` method that can
788 * be used to unsubscribe the observable from the store, and prevent further
789 * emission of values from the observable.
790 */
791 subscribe(observer) {
792 if (typeof observer !== "object" || observer === null) {
793 throw new Error( true ? formatProdErrorMessage(11) : 0);
794 }
795 function observeState() {
796 const observerAsObserver = observer;
797 if (observerAsObserver.next) {
798 observerAsObserver.next(getState());
799 }
800 }
801 observeState();
802 const unsubscribe = outerSubscribe(observeState);
803 return {
804 unsubscribe
805 };
806 },
807 [symbol_observable_default]() {
808 return this;
809 }
810 };
811 }
812 dispatch({
813 type: actionTypes_default.INIT
814 });
815 const store = {
816 dispatch,
817 subscribe,
818 getState,
819 replaceReducer,
820 [symbol_observable_default]: observable
821 };
822 return store;
823 }
824 function legacy_createStore(reducer, preloadedState, enhancer) {
825 return createStore(reducer, preloadedState, enhancer);
826 }
827
828 // src/utils/warning.ts
829 function warning(message) {
830 if (typeof console !== "undefined" && typeof console.error === "function") {
831 console.error(message);
832 }
833 try {
834 throw new Error(message);
835 } catch (e) {
836 }
837 }
838
839 // src/combineReducers.ts
840 function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) {
841 const reducerKeys = Object.keys(reducers);
842 const argumentName = action && action.type === actionTypes_default.INIT ? "preloadedState argument passed to createStore" : "previous state received by the reducer";
843 if (reducerKeys.length === 0) {
844 return "Store does not have a valid reducer. Make sure the argument passed to combineReducers is an object whose values are reducers.";
845 }
846 if (!isPlainObject(inputState)) {
847 return `The ${argumentName} has unexpected type of "${kindOf(inputState)}". Expected argument to be an object with the following keys: "${reducerKeys.join('", "')}"`;
848 }
849 const unexpectedKeys = Object.keys(inputState).filter((key) => !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key]);
850 unexpectedKeys.forEach((key) => {
851 unexpectedKeyCache[key] = true;
852 });
853 if (action && action.type === actionTypes_default.REPLACE)
854 return;
855 if (unexpectedKeys.length > 0) {
856 return `Unexpected ${unexpectedKeys.length > 1 ? "keys" : "key"} "${unexpectedKeys.join('", "')}" found in ${argumentName}. Expected to find one of the known reducer keys instead: "${reducerKeys.join('", "')}". Unexpected keys will be ignored.`;
857 }
858 }
859 function assertReducerShape(reducers) {
860 Object.keys(reducers).forEach((key) => {
861 const reducer = reducers[key];
862 const initialState = reducer(void 0, {
863 type: actionTypes_default.INIT
864 });
865 if (typeof initialState === "undefined") {
866 throw new Error( true ? formatProdErrorMessage(12) : 0);
867 }
868 if (typeof reducer(void 0, {
869 type: actionTypes_default.PROBE_UNKNOWN_ACTION()
870 }) === "undefined") {
871 throw new Error( true ? formatProdErrorMessage(13) : 0);
872 }
873 });
874 }
875 function combineReducers(reducers) {
876 const reducerKeys = Object.keys(reducers);
877 const finalReducers = {};
878 for (let i = 0; i < reducerKeys.length; i++) {
879 const key = reducerKeys[i];
880 if (false) {}
881 if (typeof reducers[key] === "function") {
882 finalReducers[key] = reducers[key];
883 }
884 }
885 const finalReducerKeys = Object.keys(finalReducers);
886 let unexpectedKeyCache;
887 if (false) {}
888 let shapeAssertionError;
889 try {
890 assertReducerShape(finalReducers);
891 } catch (e) {
892 shapeAssertionError = e;
893 }
894 return function combination(state = {}, action) {
895 if (shapeAssertionError) {
896 throw shapeAssertionError;
897 }
898 if (false) {}
899 let hasChanged = false;
900 const nextState = {};
901 for (let i = 0; i < finalReducerKeys.length; i++) {
902 const key = finalReducerKeys[i];
903 const reducer = finalReducers[key];
904 const previousStateForKey = state[key];
905 const nextStateForKey = reducer(previousStateForKey, action);
906 if (typeof nextStateForKey === "undefined") {
907 const actionType = action && action.type;
908 throw new Error( true ? formatProdErrorMessage(14) : 0);
909 }
910 nextState[key] = nextStateForKey;
911 hasChanged = hasChanged || nextStateForKey !== previousStateForKey;
912 }
913 hasChanged = hasChanged || finalReducerKeys.length !== Object.keys(state).length;
914 return hasChanged ? nextState : state;
915 };
916 }
917
918 // src/bindActionCreators.ts
919 function bindActionCreator(actionCreator, dispatch) {
920 return function(...args) {
921 return dispatch(actionCreator.apply(this, args));
922 };
923 }
924 function bindActionCreators(actionCreators, dispatch) {
925 if (typeof actionCreators === "function") {
926 return bindActionCreator(actionCreators, dispatch);
927 }
928 if (typeof actionCreators !== "object" || actionCreators === null) {
929 throw new Error( true ? formatProdErrorMessage(16) : 0);
930 }
931 const boundActionCreators = {};
932 for (const key in actionCreators) {
933 const actionCreator = actionCreators[key];
934 if (typeof actionCreator === "function") {
935 boundActionCreators[key] = bindActionCreator(actionCreator, dispatch);
936 }
937 }
938 return boundActionCreators;
939 }
940
941 // src/compose.ts
942 function compose(...funcs) {
943 if (funcs.length === 0) {
944 return (arg) => arg;
945 }
946 if (funcs.length === 1) {
947 return funcs[0];
948 }
949 return funcs.reduce((a, b) => (...args) => a(b(...args)));
950 }
951
952 // src/applyMiddleware.ts
953 function applyMiddleware(...middlewares) {
954 return (createStore2) => (reducer, preloadedState) => {
955 const store = createStore2(reducer, preloadedState);
956 let dispatch = () => {
957 throw new Error( true ? formatProdErrorMessage(15) : 0);
958 };
959 const middlewareAPI = {
960 getState: store.getState,
961 dispatch: (action, ...args) => dispatch(action, ...args)
962 };
963 const chain = middlewares.map((middleware) => middleware(middlewareAPI));
964 dispatch = compose(...chain)(store.dispatch);
965 return {
966 ...store,
967 dispatch
968 };
969 };
970 }
971
972 // src/utils/isAction.ts
973 function isAction(action) {
974 return isPlainObject(action) && "type" in action && typeof action.type === "string";
975 }
976
977 //# sourceMappingURL=redux.mjs.map
978 // EXTERNAL MODULE: ./node_modules/equivalent-key-map/equivalent-key-map.js
979 var equivalent_key_map = __webpack_require__(3249);
980 var equivalent_key_map_default = /*#__PURE__*/__webpack_require__.n(equivalent_key_map);
981 ;// external ["wp","reduxRoutine"]
982 const external_wp_reduxRoutine_namespaceObject = window["wp"]["reduxRoutine"];
983 var external_wp_reduxRoutine_default = /*#__PURE__*/__webpack_require__.n(external_wp_reduxRoutine_namespaceObject);
984 ;// external ["wp","compose"]
985 const external_wp_compose_namespaceObject = window["wp"]["compose"];
986 ;// ./packages/data/build-module/redux-store/combine-reducers.js
987 function combine_reducers_combineReducers(reducers) {
988 const keys = Object.keys(reducers);
989 return function combinedReducer(state = {}, action) {
990 const nextState = {};
991 let hasChanged = false;
992 for (const key of keys) {
993 const reducer = reducers[key];
994 const prevStateForKey = state[key];
995 const nextStateForKey = reducer(prevStateForKey, action);
996 nextState[key] = nextStateForKey;
997 hasChanged = hasChanged || nextStateForKey !== prevStateForKey;
998 }
999 return hasChanged ? nextState : state;
1000 };
1001 }
1002
1003 ;// ./packages/data/build-module/factory.js
1004 /**
1005 * Internal dependencies
1006 */
1007
1008 /**
1009 * Creates a selector function that takes additional curried argument with the
1010 * registry `select` function. While a regular selector has signature
1011 * ```js
1012 * ( state, ...selectorArgs ) => ( result )
1013 * ```
1014 * that allows to select data from the store's `state`, a registry selector
1015 * has signature:
1016 * ```js
1017 * ( select ) => ( state, ...selectorArgs ) => ( result )
1018 * ```
1019 * that supports also selecting from other registered stores.
1020 *
1021 * @example
1022 * ```js
1023 * import { store as coreStore } from '@wordpress/core-data';
1024 * import { store as editorStore } from '@wordpress/editor';
1025 *
1026 * const getCurrentPostId = createRegistrySelector( ( select ) => ( state ) => {
1027 * return select( editorStore ).getCurrentPostId();
1028 * } );
1029 *
1030 * const getPostEdits = createRegistrySelector( ( select ) => ( state ) => {
1031 * // calling another registry selector just like any other function
1032 * const postType = getCurrentPostType( state );
1033 * const postId = getCurrentPostId( state );
1034 * return select( coreStore ).getEntityRecordEdits( 'postType', postType, postId );
1035 * } );
1036 * ```
1037 *
1038 * Note how the `getCurrentPostId` selector can be called just like any other function,
1039 * (it works even inside a regular non-registry selector) and we don't need to pass the
1040 * registry as argument. The registry binding happens automatically when registering the selector
1041 * with a store.
1042 *
1043 * @param registrySelector Function receiving a registry `select`
1044 * function and returning a state selector.
1045 *
1046 * @return Registry selector that can be registered with a store.
1047 */
1048 function createRegistrySelector(registrySelector) {
1049 const selectorsByRegistry = new WeakMap();
1050 // Create a selector function that is bound to the registry referenced by `selector.registry`
1051 // and that has the same API as a regular selector. Binding it in such a way makes it
1052 // possible to call the selector directly from another selector.
1053 const wrappedSelector = (...args) => {
1054 let selector = selectorsByRegistry.get(wrappedSelector.registry);
1055 // We want to make sure the cache persists even when new registry
1056 // instances are created. For example patterns create their own editors
1057 // with their own core/block-editor stores, so we should keep track of
1058 // the cache for each registry instance.
1059 if (!selector) {
1060 selector = registrySelector(wrappedSelector.registry.select);
1061 selectorsByRegistry.set(wrappedSelector.registry, selector);
1062 }
1063 return selector(...args);
1064 };
1065
1066 /**
1067 * Flag indicating that the selector is a registry selector that needs the correct registry
1068 * reference to be assigned to `selector.registry` to make it work correctly.
1069 * be mapped as a registry selector.
1070 */
1071 wrappedSelector.isRegistrySelector = true;
1072 return wrappedSelector;
1073 }
1074
1075 /**
1076 * Creates a control function that takes additional curried argument with the `registry` object.
1077 * While a regular control has signature
1078 * ```js
1079 * ( action ) => ( iteratorOrPromise )
1080 * ```
1081 * where the control works with the `action` that it's bound to, a registry control has signature:
1082 * ```js
1083 * ( registry ) => ( action ) => ( iteratorOrPromise )
1084 * ```
1085 * A registry control is typically used to select data or dispatch an action to a registered
1086 * store.
1087 *
1088 * When registering a control created with `createRegistryControl` with a store, the store
1089 * knows which calling convention to use when executing the control.
1090 *
1091 * @param registryControl Function receiving a registry object and returning a control.
1092 *
1093 * @return Registry control that can be registered with a store.
1094 */
1095 function createRegistryControl(registryControl) {
1096 registryControl.isRegistryControl = true;
1097 return registryControl;
1098 }
1099
1100 ;// ./packages/data/build-module/controls.js
1101 /**
1102 * Internal dependencies
1103 */
1104
1105
1106 /** @typedef {import('./types').StoreDescriptor} StoreDescriptor */
1107
1108 const SELECT = '@@data/SELECT';
1109 const RESOLVE_SELECT = '@@data/RESOLVE_SELECT';
1110 const DISPATCH = '@@data/DISPATCH';
1111 function isObject(object) {
1112 return object !== null && typeof object === 'object';
1113 }
1114
1115 /**
1116 * Dispatches a control action for triggering a synchronous registry select.
1117 *
1118 * Note: This control synchronously returns the current selector value, triggering the
1119 * resolution, but not waiting for it.
1120 *
1121 * @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
1122 * @param {string} selectorName The name of the selector.
1123 * @param {Array} args Arguments for the selector.
1124 *
1125 * @example
1126 * ```js
1127 * import { controls } from '@wordpress/data';
1128 *
1129 * // Action generator using `select`.
1130 * export function* myAction() {
1131 * const isEditorSideBarOpened = yield controls.select( 'core/edit-post', 'isEditorSideBarOpened' );
1132 * // Do stuff with the result from the `select`.
1133 * }
1134 * ```
1135 *
1136 * @return {Object} The control descriptor.
1137 */
1138 function controls_select(storeNameOrDescriptor, selectorName, ...args) {
1139 return {
1140 type: SELECT,
1141 storeKey: isObject(storeNameOrDescriptor) ? storeNameOrDescriptor.name : storeNameOrDescriptor,
1142 selectorName,
1143 args
1144 };
1145 }
1146
1147 /**
1148 * Dispatches a control action for triggering and resolving a registry select.
1149 *
1150 * Note: when this control action is handled, it automatically considers
1151 * selectors that may have a resolver. In such case, it will return a `Promise` that resolves
1152 * after the selector finishes resolving, with the final result value.
1153 *
1154 * @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
1155 * @param {string} selectorName The name of the selector
1156 * @param {Array} args Arguments for the selector.
1157 *
1158 * @example
1159 * ```js
1160 * import { controls } from '@wordpress/data';
1161 *
1162 * // Action generator using resolveSelect
1163 * export function* myAction() {
1164 * const isSidebarOpened = yield controls.resolveSelect( 'core/edit-post', 'isEditorSideBarOpened' );
1165 * // do stuff with the result from the select.
1166 * }
1167 * ```
1168 *
1169 * @return {Object} The control descriptor.
1170 */
1171 function resolveSelect(storeNameOrDescriptor, selectorName, ...args) {
1172 return {
1173 type: RESOLVE_SELECT,
1174 storeKey: isObject(storeNameOrDescriptor) ? storeNameOrDescriptor.name : storeNameOrDescriptor,
1175 selectorName,
1176 args
1177 };
1178 }
1179
1180 /**
1181 * Dispatches a control action for triggering a registry dispatch.
1182 *
1183 * @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
1184 * @param {string} actionName The name of the action to dispatch
1185 * @param {Array} args Arguments for the dispatch action.
1186 *
1187 * @example
1188 * ```js
1189 * import { controls } from '@wordpress/data-controls';
1190 *
1191 * // Action generator using dispatch
1192 * export function* myAction() {
1193 * yield controls.dispatch( 'core/editor', 'togglePublishSidebar' );
1194 * // do some other things.
1195 * }
1196 * ```
1197 *
1198 * @return {Object} The control descriptor.
1199 */
1200 function dispatch(storeNameOrDescriptor, actionName, ...args) {
1201 return {
1202 type: DISPATCH,
1203 storeKey: isObject(storeNameOrDescriptor) ? storeNameOrDescriptor.name : storeNameOrDescriptor,
1204 actionName,
1205 args
1206 };
1207 }
1208 const controls = {
1209 select: controls_select,
1210 resolveSelect,
1211 dispatch
1212 };
1213 const builtinControls = {
1214 [SELECT]: createRegistryControl(registry => ({
1215 storeKey,
1216 selectorName,
1217 args
1218 }) => registry.select(storeKey)[selectorName](...args)),
1219 [RESOLVE_SELECT]: createRegistryControl(registry => ({
1220 storeKey,
1221 selectorName,
1222 args
1223 }) => {
1224 const method = registry.select(storeKey)[selectorName].hasResolver ? 'resolveSelect' : 'select';
1225 return registry[method](storeKey)[selectorName](...args);
1226 }),
1227 [DISPATCH]: createRegistryControl(registry => ({
1228 storeKey,
1229 actionName,
1230 args
1231 }) => registry.dispatch(storeKey)[actionName](...args))
1232 };
1233
1234 ;// external ["wp","privateApis"]
1235 const external_wp_privateApis_namespaceObject = window["wp"]["privateApis"];
1236 ;// ./packages/data/build-module/lock-unlock.js
1237 /**
1238 * WordPress dependencies
1239 */
1240
1241 const {
1242 lock,
1243 unlock
1244 } = (0,external_wp_privateApis_namespaceObject.__dangerousOptInToUnstableAPIsOnlyForCoreModules)('I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.', '@wordpress/data');
1245
1246 ;// ./node_modules/is-promise/index.mjs
1247 function isPromise(obj) {
1248 return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
1249 }
1250
1251 ;// ./packages/data/build-module/promise-middleware.js
1252 /**
1253 * External dependencies
1254 */
1255
1256
1257 /**
1258 * Simplest possible promise redux middleware.
1259 *
1260 * @type {import('redux').Middleware}
1261 */
1262 const promiseMiddleware = () => next => action => {
1263 if (isPromise(action)) {
1264 return action.then(resolvedAction => {
1265 if (resolvedAction) {
1266 return next(resolvedAction);
1267 }
1268 });
1269 }
1270 return next(action);
1271 };
1272 /* harmony default export */ const promise_middleware = (promiseMiddleware);
1273
1274 ;// ./packages/data/build-module/resolvers-cache-middleware.js
1275 /* wp:polyfill */
1276 /** @typedef {import('./registry').WPDataRegistry} WPDataRegistry */
1277
1278 /**
1279 * Creates a middleware handling resolvers cache invalidation.
1280 *
1281 * @param {WPDataRegistry} registry Registry for which to create the middleware.
1282 * @param {string} storeName Name of the store for which to create the middleware.
1283 *
1284 * @return {Function} Middleware function.
1285 */
1286 const createResolversCacheMiddleware = (registry, storeName) => () => next => action => {
1287 const resolvers = registry.select(storeName).getCachedResolvers();
1288 const resolverEntries = Object.entries(resolvers);
1289 resolverEntries.forEach(([selectorName, resolversByArgs]) => {
1290 const resolver = registry.stores[storeName]?.resolvers?.[selectorName];
1291 if (!resolver || !resolver.shouldInvalidate) {
1292 return;
1293 }
1294 resolversByArgs.forEach((value, args) => {
1295 // Works around a bug in `EquivalentKeyMap` where `map.delete` merely sets an entry value
1296 // to `undefined` and `map.forEach` then iterates also over these orphaned entries.
1297 if (value === undefined) {
1298 return;
1299 }
1300
1301 // resolversByArgs is the map Map([ args ] => boolean) storing the cache resolution status for a given selector.
1302 // If the value is "finished" or "error" it means this resolver has finished its resolution which means we need
1303 // to invalidate it, if it's true it means it's inflight and the invalidation is not necessary.
1304 if (value.status !== 'finished' && value.status !== 'error') {
1305 return;
1306 }
1307 if (!resolver.shouldInvalidate(action, ...args)) {
1308 return;
1309 }
1310
1311 // Trigger cache invalidation
1312 registry.dispatch(storeName).invalidateResolution(selectorName, args);
1313 });
1314 });
1315 return next(action);
1316 };
1317 /* harmony default export */ const resolvers_cache_middleware = (createResolversCacheMiddleware);
1318
1319 ;// ./packages/data/build-module/redux-store/thunk-middleware.js
1320 function createThunkMiddleware(args) {
1321 return () => next => action => {
1322 if (typeof action === 'function') {
1323 return action(args);
1324 }
1325 return next(action);
1326 };
1327 }
1328
1329 ;// ./packages/data/build-module/redux-store/metadata/utils.js
1330 /**
1331 * External dependencies
1332 */
1333
1334 /**
1335 * Higher-order reducer creator which creates a combined reducer object, keyed
1336 * by a property on the action object.
1337 *
1338 * @param actionProperty Action property by which to key object.
1339 * @return Higher-order reducer.
1340 */
1341 const onSubKey = actionProperty => reducer => (state = {}, action) => {
1342 // Retrieve subkey from action. Do not track if undefined; useful for cases
1343 // where reducer is scoped by action shape.
1344 const key = action[actionProperty];
1345 if (key === undefined) {
1346 return state;
1347 }
1348
1349 // Avoid updating state if unchanged. Note that this also accounts for a
1350 // reducer which returns undefined on a key which is not yet tracked.
1351 const nextKeyState = reducer(state[key], action);
1352 if (nextKeyState === state[key]) {
1353 return state;
1354 }
1355 return {
1356 ...state,
1357 [key]: nextKeyState
1358 };
1359 };
1360
1361 /**
1362 * Normalize selector argument array by defaulting `undefined` value to an empty array
1363 * and removing trailing `undefined` values.
1364 *
1365 * @param args Selector argument array
1366 * @return Normalized state key array
1367 */
1368 function selectorArgsToStateKey(args) {
1369 if (args === undefined || args === null) {
1370 return [];
1371 }
1372 const len = args.length;
1373 let idx = len;
1374 while (idx > 0 && args[idx - 1] === undefined) {
1375 idx--;
1376 }
1377 return idx === len ? args : args.slice(0, idx);
1378 }
1379
1380 ;// ./packages/data/build-module/redux-store/metadata/reducer.js
1381 /* wp:polyfill */
1382 /**
1383 * External dependencies
1384 */
1385
1386 /**
1387 * Internal dependencies
1388 */
1389
1390 /**
1391 * Reducer function returning next state for selector resolution of
1392 * subkeys, object form:
1393 *
1394 * selectorName -> EquivalentKeyMap<Array,boolean>
1395 */
1396 const subKeysIsResolved = onSubKey('selectorName')((state = new (equivalent_key_map_default())(), action) => {
1397 switch (action.type) {
1398 case 'START_RESOLUTION':
1399 {
1400 const nextState = new (equivalent_key_map_default())(state);
1401 nextState.set(selectorArgsToStateKey(action.args), {
1402 status: 'resolving'
1403 });
1404 return nextState;
1405 }
1406 case 'FINISH_RESOLUTION':
1407 {
1408 const nextState = new (equivalent_key_map_default())(state);
1409 nextState.set(selectorArgsToStateKey(action.args), {
1410 status: 'finished'
1411 });
1412 return nextState;
1413 }
1414 case 'FAIL_RESOLUTION':
1415 {
1416 const nextState = new (equivalent_key_map_default())(state);
1417 nextState.set(selectorArgsToStateKey(action.args), {
1418 status: 'error',
1419 error: action.error
1420 });
1421 return nextState;
1422 }
1423 case 'START_RESOLUTIONS':
1424 {
1425 const nextState = new (equivalent_key_map_default())(state);
1426 for (const resolutionArgs of action.args) {
1427 nextState.set(selectorArgsToStateKey(resolutionArgs), {
1428 status: 'resolving'
1429 });
1430 }
1431 return nextState;
1432 }
1433 case 'FINISH_RESOLUTIONS':
1434 {
1435 const nextState = new (equivalent_key_map_default())(state);
1436 for (const resolutionArgs of action.args) {
1437 nextState.set(selectorArgsToStateKey(resolutionArgs), {
1438 status: 'finished'
1439 });
1440 }
1441 return nextState;
1442 }
1443 case 'FAIL_RESOLUTIONS':
1444 {
1445 const nextState = new (equivalent_key_map_default())(state);
1446 action.args.forEach((resolutionArgs, idx) => {
1447 const resolutionState = {
1448 status: 'error',
1449 error: undefined
1450 };
1451 const error = action.errors[idx];
1452 if (error) {
1453 resolutionState.error = error;
1454 }
1455 nextState.set(selectorArgsToStateKey(resolutionArgs), resolutionState);
1456 });
1457 return nextState;
1458 }
1459 case 'INVALIDATE_RESOLUTION':
1460 {
1461 const nextState = new (equivalent_key_map_default())(state);
1462 nextState.delete(selectorArgsToStateKey(action.args));
1463 return nextState;
1464 }
1465 }
1466 return state;
1467 });
1468
1469 /**
1470 * Reducer function returning next state for selector resolution, object form:
1471 *
1472 * selectorName -> EquivalentKeyMap<Array, boolean>
1473 *
1474 * @param state Current state.
1475 * @param action Dispatched action.
1476 *
1477 * @return Next state.
1478 */
1479 const isResolved = (state = {}, action) => {
1480 switch (action.type) {
1481 case 'INVALIDATE_RESOLUTION_FOR_STORE':
1482 return {};
1483 case 'INVALIDATE_RESOLUTION_FOR_STORE_SELECTOR':
1484 {
1485 if (action.selectorName in state) {
1486 const {
1487 [action.selectorName]: removedSelector,
1488 ...restState
1489 } = state;
1490 return restState;
1491 }
1492 return state;
1493 }
1494 case 'START_RESOLUTION':
1495 case 'FINISH_RESOLUTION':
1496 case 'FAIL_RESOLUTION':
1497 case 'START_RESOLUTIONS':
1498 case 'FINISH_RESOLUTIONS':
1499 case 'FAIL_RESOLUTIONS':
1500 case 'INVALIDATE_RESOLUTION':
1501 return subKeysIsResolved(state, action);
1502 }
1503 return state;
1504 };
1505 /* harmony default export */ const metadata_reducer = (isResolved);
1506
1507 ;// ./node_modules/rememo/rememo.js
1508
1509
1510 /** @typedef {(...args: any[]) => *[]} GetDependants */
1511
1512 /** @typedef {() => void} Clear */
1513
1514 /**
1515 * @typedef {{
1516 * getDependants: GetDependants,
1517 * clear: Clear
1518 * }} EnhancedSelector
1519 */
1520
1521 /**
1522 * Internal cache entry.
1523 *
1524 * @typedef CacheNode
1525 *
1526 * @property {?CacheNode|undefined} [prev] Previous node.
1527 * @property {?CacheNode|undefined} [next] Next node.
1528 * @property {*[]} args Function arguments for cache entry.
1529 * @property {*} val Function result.
1530 */
1531
1532 /**
1533 * @typedef Cache
1534 *
1535 * @property {Clear} clear Function to clear cache.
1536 * @property {boolean} [isUniqueByDependants] Whether dependants are valid in
1537 * considering cache uniqueness. A cache is unique if dependents are all arrays
1538 * or objects.
1539 * @property {CacheNode?} [head] Cache head.
1540 * @property {*[]} [lastDependants] Dependants from previous invocation.
1541 */
1542
1543 /**
1544 * Arbitrary value used as key for referencing cache object in WeakMap tree.
1545 *
1546 * @type {{}}
1547 */
1548 var LEAF_KEY = {};
1549
1550 /**
1551 * Returns the first argument as the sole entry in an array.
1552 *
1553 * @template T
1554 *
1555 * @param {T} value Value to return.
1556 *
1557 * @return {[T]} Value returned as entry in array.
1558 */
1559 function arrayOf(value) {
1560 return [value];
1561 }
1562
1563 /**
1564 * Returns true if the value passed is object-like, or false otherwise. A value
1565 * is object-like if it can support property assignment, e.g. object or array.
1566 *
1567 * @param {*} value Value to test.
1568 *
1569 * @return {boolean} Whether value is object-like.
1570 */
1571 function isObjectLike(value) {
1572 return !!value && 'object' === typeof value;
1573 }
1574
1575 /**
1576 * Creates and returns a new cache object.
1577 *
1578 * @return {Cache} Cache object.
1579 */
1580 function createCache() {
1581 /** @type {Cache} */
1582 var cache = {
1583 clear: function () {
1584 cache.head = null;
1585 },
1586 };
1587
1588 return cache;
1589 }
1590
1591 /**
1592 * Returns true if entries within the two arrays are strictly equal by
1593 * reference from a starting index.
1594 *
1595 * @param {*[]} a First array.
1596 * @param {*[]} b Second array.
1597 * @param {number} fromIndex Index from which to start comparison.
1598 *
1599 * @return {boolean} Whether arrays are shallowly equal.
1600 */
1601 function isShallowEqual(a, b, fromIndex) {
1602 var i;
1603
1604 if (a.length !== b.length) {
1605 return false;
1606 }
1607
1608 for (i = fromIndex; i < a.length; i++) {
1609 if (a[i] !== b[i]) {
1610 return false;
1611 }
1612 }
1613
1614 return true;
1615 }
1616
1617 /**
1618 * Returns a memoized selector function. The getDependants function argument is
1619 * called before the memoized selector and is expected to return an immutable
1620 * reference or array of references on which the selector depends for computing
1621 * its own return value. The memoize cache is preserved only as long as those
1622 * dependant references remain the same. If getDependants returns a different
1623 * reference(s), the cache is cleared and the selector value regenerated.
1624 *
1625 * @template {(...args: *[]) => *} S
1626 *
1627 * @param {S} selector Selector function.
1628 * @param {GetDependants=} getDependants Dependant getter returning an array of
1629 * references used in cache bust consideration.
1630 */
1631 /* harmony default export */ function rememo(selector, getDependants) {
1632 /** @type {WeakMap<*,*>} */
1633 var rootCache;
1634
1635 /** @type {GetDependants} */
1636 var normalizedGetDependants = getDependants ? getDependants : arrayOf;
1637
1638 /**
1639 * Returns the cache for a given dependants array. When possible, a WeakMap
1640 * will be used to create a unique cache for each set of dependants. This
1641 * is feasible due to the nature of WeakMap in allowing garbage collection
1642 * to occur on entries where the key object is no longer referenced. Since
1643 * WeakMap requires the key to be an object, this is only possible when the
1644 * dependant is object-like. The root cache is created as a hierarchy where
1645 * each top-level key is the first entry in a dependants set, the value a
1646 * WeakMap where each key is the next dependant, and so on. This continues
1647 * so long as the dependants are object-like. If no dependants are object-
1648 * like, then the cache is shared across all invocations.
1649 *
1650 * @see isObjectLike
1651 *
1652 * @param {*[]} dependants Selector dependants.
1653 *
1654 * @return {Cache} Cache object.
1655 */
1656 function getCache(dependants) {
1657 var caches = rootCache,
1658 isUniqueByDependants = true,
1659 i,
1660 dependant,
1661 map,
1662 cache;
1663
1664 for (i = 0; i < dependants.length; i++) {
1665 dependant = dependants[i];
1666
1667 // Can only compose WeakMap from object-like key.
1668 if (!isObjectLike(dependant)) {
1669 isUniqueByDependants = false;
1670 break;
1671 }
1672
1673 // Does current segment of cache already have a WeakMap?
1674 if (caches.has(dependant)) {
1675 // Traverse into nested WeakMap.
1676 caches = caches.get(dependant);
1677 } else {
1678 // Create, set, and traverse into a new one.
1679 map = new WeakMap();
1680 caches.set(dependant, map);
1681 caches = map;
1682 }
1683 }
1684
1685 // We use an arbitrary (but consistent) object as key for the last item
1686 // in the WeakMap to serve as our running cache.
1687 if (!caches.has(LEAF_KEY)) {
1688 cache = createCache();
1689 cache.isUniqueByDependants = isUniqueByDependants;
1690 caches.set(LEAF_KEY, cache);
1691 }
1692
1693 return caches.get(LEAF_KEY);
1694 }
1695
1696 /**
1697 * Resets root memoization cache.
1698 */
1699 function clear() {
1700 rootCache = new WeakMap();
1701 }
1702
1703 /* eslint-disable jsdoc/check-param-names */
1704 /**
1705 * The augmented selector call, considering first whether dependants have
1706 * changed before passing it to underlying memoize function.
1707 *
1708 * @param {*} source Source object for derivation.
1709 * @param {...*} extraArgs Additional arguments to pass to selector.
1710 *
1711 * @return {*} Selector result.
1712 */
1713 /* eslint-enable jsdoc/check-param-names */
1714 function callSelector(/* source, ...extraArgs */) {
1715 var len = arguments.length,
1716 cache,
1717 node,
1718 i,
1719 args,
1720 dependants;
1721
1722 // Create copy of arguments (avoid leaking deoptimization).
1723 args = new Array(len);
1724 for (i = 0; i < len; i++) {
1725 args[i] = arguments[i];
1726 }
1727
1728 dependants = normalizedGetDependants.apply(null, args);
1729 cache = getCache(dependants);
1730
1731 // If not guaranteed uniqueness by dependants (primitive type), shallow
1732 // compare against last dependants and, if references have changed,
1733 // destroy cache to recalculate result.
1734 if (!cache.isUniqueByDependants) {
1735 if (
1736 cache.lastDependants &&
1737 !isShallowEqual(dependants, cache.lastDependants, 0)
1738 ) {
1739 cache.clear();
1740 }
1741
1742 cache.lastDependants = dependants;
1743 }
1744
1745 node = cache.head;
1746 while (node) {
1747 // Check whether node arguments match arguments
1748 if (!isShallowEqual(node.args, args, 1)) {
1749 node = node.next;
1750 continue;
1751 }
1752
1753 // At this point we can assume we've found a match
1754
1755 // Surface matched node to head if not already
1756 if (node !== cache.head) {
1757 // Adjust siblings to point to each other.
1758 /** @type {CacheNode} */ (node.prev).next = node.next;
1759 if (node.next) {
1760 node.next.prev = node.prev;
1761 }
1762
1763 node.next = cache.head;
1764 node.prev = null;
1765 /** @type {CacheNode} */ (cache.head).prev = node;
1766 cache.head = node;
1767 }
1768
1769 // Return immediately
1770 return node.val;
1771 }
1772
1773 // No cached value found. Continue to insertion phase:
1774
1775 node = /** @type {CacheNode} */ ({
1776 // Generate the result from original function
1777 val: selector.apply(null, args),
1778 });
1779
1780 // Avoid including the source object in the cache.
1781 args[0] = null;
1782 node.args = args;
1783
1784 // Don't need to check whether node is already head, since it would
1785 // have been returned above already if it was
1786
1787 // Shift existing head down list
1788 if (cache.head) {
1789 cache.head.prev = node;
1790 node.next = cache.head;
1791 }
1792
1793 cache.head = node;
1794
1795 return node.val;
1796 }
1797
1798 callSelector.getDependants = normalizedGetDependants;
1799 callSelector.clear = clear;
1800 clear();
1801
1802 return /** @type {S & EnhancedSelector} */ (callSelector);
1803 }
1804
1805 ;// ./packages/data/build-module/redux-store/metadata/selectors.js
1806 /* wp:polyfill */
1807 /**
1808 * WordPress dependencies
1809 */
1810
1811
1812 /**
1813 * Internal dependencies
1814 */
1815
1816
1817
1818 /** @typedef {Record<string, import('./reducer').State>} State */
1819 /** @typedef {import('./reducer').StateValue} StateValue */
1820 /** @typedef {import('./reducer').Status} Status */
1821
1822 /**
1823 * Returns the raw resolution state value for a given selector name,
1824 * and arguments set. May be undefined if the selector has never been resolved
1825 * or not resolved for the given set of arguments, otherwise true or false for
1826 * resolution started and completed respectively.
1827 *
1828 * @param {State} state Data state.
1829 * @param {string} selectorName Selector name.
1830 * @param {unknown[]?} args Arguments passed to selector.
1831 *
1832 * @return {StateValue|undefined} isResolving value.
1833 */
1834 function getResolutionState(state, selectorName, args) {
1835 const map = state[selectorName];
1836 if (!map) {
1837 return;
1838 }
1839 return map.get(selectorArgsToStateKey(args));
1840 }
1841
1842 /**
1843 * Returns an `isResolving`-like value for a given selector name and arguments set.
1844 * Its value is either `undefined` if the selector has never been resolved or has been
1845 * invalidated, or a `true`/`false` boolean value if the resolution is in progress or
1846 * has finished, respectively.
1847 *
1848 * This is a legacy selector that was implemented when the "raw" internal data had
1849 * this `undefined | boolean` format. Nowadays the internal value is an object that
1850 * can be retrieved with `getResolutionState`.
1851 *
1852 * @deprecated
1853 *
1854 * @param {State} state Data state.
1855 * @param {string} selectorName Selector name.
1856 * @param {unknown[]?} args Arguments passed to selector.
1857 *
1858 * @return {boolean | undefined} isResolving value.
1859 */
1860 function getIsResolving(state, selectorName, args) {
1861 external_wp_deprecated_default()('wp.data.select( store ).getIsResolving', {
1862 since: '6.6',
1863 version: '6.8',
1864 alternative: 'wp.data.select( store ).getResolutionState'
1865 });
1866 const resolutionState = getResolutionState(state, selectorName, args);
1867 return resolutionState && resolutionState.status === 'resolving';
1868 }
1869
1870 /**
1871 * Returns true if resolution has already been triggered for a given
1872 * selector name, and arguments set.
1873 *
1874 * @param {State} state Data state.
1875 * @param {string} selectorName Selector name.
1876 * @param {unknown[]?} args Arguments passed to selector.
1877 *
1878 * @return {boolean} Whether resolution has been triggered.
1879 */
1880 function hasStartedResolution(state, selectorName, args) {
1881 return getResolutionState(state, selectorName, args) !== undefined;
1882 }
1883
1884 /**
1885 * Returns true if resolution has completed for a given selector
1886 * name, and arguments set.
1887 *
1888 * @param {State} state Data state.
1889 * @param {string} selectorName Selector name.
1890 * @param {unknown[]?} args Arguments passed to selector.
1891 *
1892 * @return {boolean} Whether resolution has completed.
1893 */
1894 function hasFinishedResolution(state, selectorName, args) {
1895 const status = getResolutionState(state, selectorName, args)?.status;
1896 return status === 'finished' || status === 'error';
1897 }
1898
1899 /**
1900 * Returns true if resolution has failed for a given selector
1901 * name, and arguments set.
1902 *
1903 * @param {State} state Data state.
1904 * @param {string} selectorName Selector name.
1905 * @param {unknown[]?} args Arguments passed to selector.
1906 *
1907 * @return {boolean} Has resolution failed
1908 */
1909 function hasResolutionFailed(state, selectorName, args) {
1910 return getResolutionState(state, selectorName, args)?.status === 'error';
1911 }
1912
1913 /**
1914 * Returns the resolution error for a given selector name, and arguments set.
1915 * Note it may be of an Error type, but may also be null, undefined, or anything else
1916 * that can be `throw`-n.
1917 *
1918 * @param {State} state Data state.
1919 * @param {string} selectorName Selector name.
1920 * @param {unknown[]?} args Arguments passed to selector.
1921 *
1922 * @return {Error|unknown} Last resolution error
1923 */
1924 function getResolutionError(state, selectorName, args) {
1925 const resolutionState = getResolutionState(state, selectorName, args);
1926 return resolutionState?.status === 'error' ? resolutionState.error : null;
1927 }
1928
1929 /**
1930 * Returns true if resolution has been triggered but has not yet completed for
1931 * a given selector name, and arguments set.
1932 *
1933 * @param {State} state Data state.
1934 * @param {string} selectorName Selector name.
1935 * @param {unknown[]?} args Arguments passed to selector.
1936 *
1937 * @return {boolean} Whether resolution is in progress.
1938 */
1939 function isResolving(state, selectorName, args) {
1940 return getResolutionState(state, selectorName, args)?.status === 'resolving';
1941 }
1942
1943 /**
1944 * Returns the list of the cached resolvers.
1945 *
1946 * @param {State} state Data state.
1947 *
1948 * @return {State} Resolvers mapped by args and selectorName.
1949 */
1950 function getCachedResolvers(state) {
1951 return state;
1952 }
1953
1954 /**
1955 * Whether the store has any currently resolving selectors.
1956 *
1957 * @param {State} state Data state.
1958 *
1959 * @return {boolean} True if one or more selectors are resolving, false otherwise.
1960 */
1961 function hasResolvingSelectors(state) {
1962 return Object.values(state).some(selectorState =>
1963 /**
1964 * This uses the internal `_map` property of `EquivalentKeyMap` for
1965 * optimization purposes, since the `EquivalentKeyMap` implementation
1966 * does not support a `.values()` implementation.
1967 *
1968 * @see https://github.com/aduth/equivalent-key-map
1969 */
1970 Array.from(selectorState._map.values()).some(resolution => resolution[1]?.status === 'resolving'));
1971 }
1972
1973 /**
1974 * Retrieves the total number of selectors, grouped per status.
1975 *
1976 * @param {State} state Data state.
1977 *
1978 * @return {Object} Object, containing selector totals by status.
1979 */
1980 const countSelectorsByStatus = rememo(state => {
1981 const selectorsByStatus = {};
1982 Object.values(state).forEach(selectorState =>
1983 /**
1984 * This uses the internal `_map` property of `EquivalentKeyMap` for
1985 * optimization purposes, since the `EquivalentKeyMap` implementation
1986 * does not support a `.values()` implementation.
1987 *
1988 * @see https://github.com/aduth/equivalent-key-map
1989 */
1990 Array.from(selectorState._map.values()).forEach(resolution => {
1991 var _resolution$1$status;
1992 const currentStatus = (_resolution$1$status = resolution[1]?.status) !== null && _resolution$1$status !== void 0 ? _resolution$1$status : 'error';
1993 if (!selectorsByStatus[currentStatus]) {
1994 selectorsByStatus[currentStatus] = 0;
1995 }
1996 selectorsByStatus[currentStatus]++;
1997 }));
1998 return selectorsByStatus;
1999 }, state => [state]);
2000
2001 ;// ./packages/data/build-module/redux-store/metadata/actions.js
2002 /**
2003 * Returns an action object used in signalling that selector resolution has
2004 * started.
2005 *
2006 * @param {string} selectorName Name of selector for which resolver triggered.
2007 * @param {unknown[]} args Arguments to associate for uniqueness.
2008 *
2009 * @return {{ type: 'START_RESOLUTION', selectorName: string, args: unknown[] }} Action object.
2010 */
2011 function startResolution(selectorName, args) {
2012 return {
2013 type: 'START_RESOLUTION',
2014 selectorName,
2015 args
2016 };
2017 }
2018
2019 /**
2020 * Returns an action object used in signalling that selector resolution has
2021 * completed.
2022 *
2023 * @param {string} selectorName Name of selector for which resolver triggered.
2024 * @param {unknown[]} args Arguments to associate for uniqueness.
2025 *
2026 * @return {{ type: 'FINISH_RESOLUTION', selectorName: string, args: unknown[] }} Action object.
2027 */
2028 function finishResolution(selectorName, args) {
2029 return {
2030 type: 'FINISH_RESOLUTION',
2031 selectorName,
2032 args
2033 };
2034 }
2035
2036 /**
2037 * Returns an action object used in signalling that selector resolution has
2038 * failed.
2039 *
2040 * @param {string} selectorName Name of selector for which resolver triggered.
2041 * @param {unknown[]} args Arguments to associate for uniqueness.
2042 * @param {Error|unknown} error The error that caused the failure.
2043 *
2044 * @return {{ type: 'FAIL_RESOLUTION', selectorName: string, args: unknown[], error: Error|unknown }} Action object.
2045 */
2046 function failResolution(selectorName, args, error) {
2047 return {
2048 type: 'FAIL_RESOLUTION',
2049 selectorName,
2050 args,
2051 error
2052 };
2053 }
2054
2055 /**
2056 * Returns an action object used in signalling that a batch of selector resolutions has
2057 * started.
2058 *
2059 * @param {string} selectorName Name of selector for which resolver triggered.
2060 * @param {unknown[][]} args Array of arguments to associate for uniqueness, each item
2061 * is associated to a resolution.
2062 *
2063 * @return {{ type: 'START_RESOLUTIONS', selectorName: string, args: unknown[][] }} Action object.
2064 */
2065 function startResolutions(selectorName, args) {
2066 return {
2067 type: 'START_RESOLUTIONS',
2068 selectorName,
2069 args
2070 };
2071 }
2072
2073 /**
2074 * Returns an action object used in signalling that a batch of selector resolutions has
2075 * completed.
2076 *
2077 * @param {string} selectorName Name of selector for which resolver triggered.
2078 * @param {unknown[][]} args Array of arguments to associate for uniqueness, each item
2079 * is associated to a resolution.
2080 *
2081 * @return {{ type: 'FINISH_RESOLUTIONS', selectorName: string, args: unknown[][] }} Action object.
2082 */
2083 function finishResolutions(selectorName, args) {
2084 return {
2085 type: 'FINISH_RESOLUTIONS',
2086 selectorName,
2087 args
2088 };
2089 }
2090
2091 /**
2092 * Returns an action object used in signalling that a batch of selector resolutions has
2093 * completed and at least one of them has failed.
2094 *
2095 * @param {string} selectorName Name of selector for which resolver triggered.
2096 * @param {unknown[]} args Array of arguments to associate for uniqueness, each item
2097 * is associated to a resolution.
2098 * @param {(Error|unknown)[]} errors Array of errors to associate for uniqueness, each item
2099 * is associated to a resolution.
2100 * @return {{ type: 'FAIL_RESOLUTIONS', selectorName: string, args: unknown[], errors: Array<Error|unknown> }} Action object.
2101 */
2102 function failResolutions(selectorName, args, errors) {
2103 return {
2104 type: 'FAIL_RESOLUTIONS',
2105 selectorName,
2106 args,
2107 errors
2108 };
2109 }
2110
2111 /**
2112 * Returns an action object used in signalling that we should invalidate the resolution cache.
2113 *
2114 * @param {string} selectorName Name of selector for which resolver should be invalidated.
2115 * @param {unknown[]} args Arguments to associate for uniqueness.
2116 *
2117 * @return {{ type: 'INVALIDATE_RESOLUTION', selectorName: string, args: any[] }} Action object.
2118 */
2119 function invalidateResolution(selectorName, args) {
2120 return {
2121 type: 'INVALIDATE_RESOLUTION',
2122 selectorName,
2123 args
2124 };
2125 }
2126
2127 /**
2128 * Returns an action object used in signalling that the resolution
2129 * should be invalidated.
2130 *
2131 * @return {{ type: 'INVALIDATE_RESOLUTION_FOR_STORE' }} Action object.
2132 */
2133 function invalidateResolutionForStore() {
2134 return {
2135 type: 'INVALIDATE_RESOLUTION_FOR_STORE'
2136 };
2137 }
2138
2139 /**
2140 * Returns an action object used in signalling that the resolution cache for a
2141 * given selectorName should be invalidated.
2142 *
2143 * @param {string} selectorName Name of selector for which all resolvers should
2144 * be invalidated.
2145 *
2146 * @return {{ type: 'INVALIDATE_RESOLUTION_FOR_STORE_SELECTOR', selectorName: string }} Action object.
2147 */
2148 function invalidateResolutionForStoreSelector(selectorName) {
2149 return {
2150 type: 'INVALIDATE_RESOLUTION_FOR_STORE_SELECTOR',
2151 selectorName
2152 };
2153 }
2154
2155 ;// ./packages/data/build-module/redux-store/index.js
2156 /* wp:polyfill */
2157 /**
2158 * External dependencies
2159 */
2160
2161
2162
2163 /**
2164 * WordPress dependencies
2165 */
2166
2167
2168
2169 /**
2170 * Internal dependencies
2171 */
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183 /** @typedef {import('../types').DataRegistry} DataRegistry */
2184 /** @typedef {import('../types').ListenerFunction} ListenerFunction */
2185 /**
2186 * @typedef {import('../types').StoreDescriptor<C>} StoreDescriptor
2187 * @template {import('../types').AnyConfig} C
2188 */
2189 /**
2190 * @typedef {import('../types').ReduxStoreConfig<State,Actions,Selectors>} ReduxStoreConfig
2191 * @template State
2192 * @template {Record<string,import('../types').ActionCreator>} Actions
2193 * @template Selectors
2194 */
2195
2196 const trimUndefinedValues = array => {
2197 const result = [...array];
2198 for (let i = result.length - 1; i >= 0; i--) {
2199 if (result[i] === undefined) {
2200 result.splice(i, 1);
2201 }
2202 }
2203 return result;
2204 };
2205
2206 /**
2207 * Creates a new object with the same keys, but with `callback()` called as
2208 * a transformer function on each of the values.
2209 *
2210 * @param {Object} obj The object to transform.
2211 * @param {Function} callback The function to transform each object value.
2212 * @return {Array} Transformed object.
2213 */
2214 const mapValues = (obj, callback) => Object.fromEntries(Object.entries(obj !== null && obj !== void 0 ? obj : {}).map(([key, value]) => [key, callback(value, key)]));
2215
2216 // Convert non serializable types to plain objects
2217 const devToolsReplacer = (key, state) => {
2218 if (state instanceof Map) {
2219 return Object.fromEntries(state);
2220 }
2221 if (state instanceof window.HTMLElement) {
2222 return null;
2223 }
2224 return state;
2225 };
2226
2227 /**
2228 * Create a cache to track whether resolvers started running or not.
2229 *
2230 * @return {Object} Resolvers Cache.
2231 */
2232 function createResolversCache() {
2233 const cache = {};
2234 return {
2235 isRunning(selectorName, args) {
2236 return cache[selectorName] && cache[selectorName].get(trimUndefinedValues(args));
2237 },
2238 clear(selectorName, args) {
2239 if (cache[selectorName]) {
2240 cache[selectorName].delete(trimUndefinedValues(args));
2241 }
2242 },
2243 markAsRunning(selectorName, args) {
2244 if (!cache[selectorName]) {
2245 cache[selectorName] = new (equivalent_key_map_default())();
2246 }
2247 cache[selectorName].set(trimUndefinedValues(args), true);
2248 }
2249 };
2250 }
2251 function createBindingCache(bind) {
2252 const cache = new WeakMap();
2253 return {
2254 get(item, itemName) {
2255 let boundItem = cache.get(item);
2256 if (!boundItem) {
2257 boundItem = bind(item, itemName);
2258 cache.set(item, boundItem);
2259 }
2260 return boundItem;
2261 }
2262 };
2263 }
2264
2265 /**
2266 * Creates a data store descriptor for the provided Redux store configuration containing
2267 * properties describing reducer, actions, selectors, controls and resolvers.
2268 *
2269 * @example
2270 * ```js
2271 * import { createReduxStore } from '@wordpress/data';
2272 *
2273 * const store = createReduxStore( 'demo', {
2274 * reducer: ( state = 'OK' ) => state,
2275 * selectors: {
2276 * getValue: ( state ) => state,
2277 * },
2278 * } );
2279 * ```
2280 *
2281 * @template State
2282 * @template {Record<string,import('../types').ActionCreator>} Actions
2283 * @template Selectors
2284 * @param {string} key Unique namespace identifier.
2285 * @param {ReduxStoreConfig<State,Actions,Selectors>} options Registered store options, with properties
2286 * describing reducer, actions, selectors,
2287 * and resolvers.
2288 *
2289 * @return {StoreDescriptor<ReduxStoreConfig<State,Actions,Selectors>>} Store Object.
2290 */
2291 function createReduxStore(key, options) {
2292 const privateActions = {};
2293 const privateSelectors = {};
2294 const privateRegistrationFunctions = {
2295 privateActions,
2296 registerPrivateActions: actions => {
2297 Object.assign(privateActions, actions);
2298 },
2299 privateSelectors,
2300 registerPrivateSelectors: selectors => {
2301 Object.assign(privateSelectors, selectors);
2302 }
2303 };
2304 const storeDescriptor = {
2305 name: key,
2306 instantiate: registry => {
2307 /**
2308 * Stores listener functions registered with `subscribe()`.
2309 *
2310 * When functions register to listen to store changes with
2311 * `subscribe()` they get added here. Although Redux offers
2312 * its own `subscribe()` function directly, by wrapping the
2313 * subscription in this store instance it's possible to
2314 * optimize checking if the state has changed before calling
2315 * each listener.
2316 *
2317 * @type {Set<ListenerFunction>}
2318 */
2319 const listeners = new Set();
2320 const reducer = options.reducer;
2321 const thunkArgs = {
2322 registry,
2323 get dispatch() {
2324 return thunkActions;
2325 },
2326 get select() {
2327 return thunkSelectors;
2328 },
2329 get resolveSelect() {
2330 return getResolveSelectors();
2331 }
2332 };
2333 const store = instantiateReduxStore(key, options, registry, thunkArgs);
2334 // Expose the private registration functions on the store
2335 // so they can be copied to a sub registry in registry.js.
2336 lock(store, privateRegistrationFunctions);
2337 const resolversCache = createResolversCache();
2338 function bindAction(action) {
2339 return (...args) => Promise.resolve(store.dispatch(action(...args)));
2340 }
2341 const actions = {
2342 ...mapValues(actions_namespaceObject, bindAction),
2343 ...mapValues(options.actions, bindAction)
2344 };
2345 const boundPrivateActions = createBindingCache(bindAction);
2346 const allActions = new Proxy(() => {}, {
2347 get: (target, prop) => {
2348 const privateAction = privateActions[prop];
2349 return privateAction ? boundPrivateActions.get(privateAction, prop) : actions[prop];
2350 }
2351 });
2352 const thunkActions = new Proxy(allActions, {
2353 apply: (target, thisArg, [action]) => store.dispatch(action)
2354 });
2355 lock(actions, allActions);
2356 const resolvers = options.resolvers ? mapResolvers(options.resolvers) : {};
2357 function bindSelector(selector, selectorName) {
2358 if (selector.isRegistrySelector) {
2359 selector.registry = registry;
2360 }
2361 const boundSelector = (...args) => {
2362 args = normalize(selector, args);
2363 const state = store.__unstableOriginalGetState();
2364 // Before calling the selector, switch to the correct
2365 // registry.
2366 if (selector.isRegistrySelector) {
2367 selector.registry = registry;
2368 }
2369 return selector(state.root, ...args);
2370 };
2371
2372 // Expose normalization method on the bound selector
2373 // in order that it can be called when fulfilling
2374 // the resolver.
2375 boundSelector.__unstableNormalizeArgs = selector.__unstableNormalizeArgs;
2376 const resolver = resolvers[selectorName];
2377 if (!resolver) {
2378 boundSelector.hasResolver = false;
2379 return boundSelector;
2380 }
2381 return mapSelectorWithResolver(boundSelector, selectorName, resolver, store, resolversCache);
2382 }
2383 function bindMetadataSelector(metaDataSelector) {
2384 const boundSelector = (...args) => {
2385 const state = store.__unstableOriginalGetState();
2386 const originalSelectorName = args && args[0];
2387 const originalSelectorArgs = args && args[1];
2388 const targetSelector = options?.selectors?.[originalSelectorName];
2389
2390 // Normalize the arguments passed to the target selector.
2391 if (originalSelectorName && targetSelector) {
2392 args[1] = normalize(targetSelector, originalSelectorArgs);
2393 }
2394 return metaDataSelector(state.metadata, ...args);
2395 };
2396 boundSelector.hasResolver = false;
2397 return boundSelector;
2398 }
2399 const selectors = {
2400 ...mapValues(selectors_namespaceObject, bindMetadataSelector),
2401 ...mapValues(options.selectors, bindSelector)
2402 };
2403 const boundPrivateSelectors = createBindingCache(bindSelector);
2404
2405 // Pre-bind the private selectors that have been registered by the time of
2406 // instantiation, so that registry selectors are bound to the registry.
2407 for (const [selectorName, selector] of Object.entries(privateSelectors)) {
2408 boundPrivateSelectors.get(selector, selectorName);
2409 }
2410 const allSelectors = new Proxy(() => {}, {
2411 get: (target, prop) => {
2412 const privateSelector = privateSelectors[prop];
2413 return privateSelector ? boundPrivateSelectors.get(privateSelector, prop) : selectors[prop];
2414 }
2415 });
2416 const thunkSelectors = new Proxy(allSelectors, {
2417 apply: (target, thisArg, [selector]) => selector(store.__unstableOriginalGetState())
2418 });
2419 lock(selectors, allSelectors);
2420 const resolveSelectors = mapResolveSelectors(selectors, store);
2421 const suspendSelectors = mapSuspendSelectors(selectors, store);
2422 const getSelectors = () => selectors;
2423 const getActions = () => actions;
2424 const getResolveSelectors = () => resolveSelectors;
2425 const getSuspendSelectors = () => suspendSelectors;
2426
2427 // We have some modules monkey-patching the store object
2428 // It's wrong to do so but until we refactor all of our effects to controls
2429 // We need to keep the same "store" instance here.
2430 store.__unstableOriginalGetState = store.getState;
2431 store.getState = () => store.__unstableOriginalGetState().root;
2432
2433 // Customize subscribe behavior to call listeners only on effective change,
2434 // not on every dispatch.
2435 const subscribe = store && (listener => {
2436 listeners.add(listener);
2437 return () => listeners.delete(listener);
2438 });
2439 let lastState = store.__unstableOriginalGetState();
2440 store.subscribe(() => {
2441 const state = store.__unstableOriginalGetState();
2442 const hasChanged = state !== lastState;
2443 lastState = state;
2444 if (hasChanged) {
2445 for (const listener of listeners) {
2446 listener();
2447 }
2448 }
2449 });
2450
2451 // This can be simplified to just { subscribe, getSelectors, getActions }
2452 // Once we remove the use function.
2453 return {
2454 reducer,
2455 store,
2456 actions,
2457 selectors,
2458 resolvers,
2459 getSelectors,
2460 getResolveSelectors,
2461 getSuspendSelectors,
2462 getActions,
2463 subscribe
2464 };
2465 }
2466 };
2467
2468 // Expose the private registration functions on the store
2469 // descriptor. That's a natural choice since that's where the
2470 // public actions and selectors are stored .
2471 lock(storeDescriptor, privateRegistrationFunctions);
2472 return storeDescriptor;
2473 }
2474
2475 /**
2476 * Creates a redux store for a namespace.
2477 *
2478 * @param {string} key Unique namespace identifier.
2479 * @param {Object} options Registered store options, with properties
2480 * describing reducer, actions, selectors,
2481 * and resolvers.
2482 * @param {DataRegistry} registry Registry reference.
2483 * @param {Object} thunkArgs Argument object for the thunk middleware.
2484 * @return {Object} Newly created redux store.
2485 */
2486 function instantiateReduxStore(key, options, registry, thunkArgs) {
2487 const controls = {
2488 ...options.controls,
2489 ...builtinControls
2490 };
2491 const normalizedControls = mapValues(controls, control => control.isRegistryControl ? control(registry) : control);
2492 const middlewares = [resolvers_cache_middleware(registry, key), promise_middleware, external_wp_reduxRoutine_default()(normalizedControls), createThunkMiddleware(thunkArgs)];
2493 const enhancers = [applyMiddleware(...middlewares)];
2494 if (typeof window !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION__) {
2495 enhancers.push(window.__REDUX_DEVTOOLS_EXTENSION__({
2496 name: key,
2497 instanceId: key,
2498 serialize: {
2499 replacer: devToolsReplacer
2500 }
2501 }));
2502 }
2503 const {
2504 reducer,
2505 initialState
2506 } = options;
2507 const enhancedReducer = combine_reducers_combineReducers({
2508 metadata: metadata_reducer,
2509 root: reducer
2510 });
2511 return createStore(enhancedReducer, {
2512 root: initialState
2513 }, (0,external_wp_compose_namespaceObject.compose)(enhancers));
2514 }
2515
2516 /**
2517 * Maps selectors to functions that return a resolution promise for them
2518 *
2519 * @param {Object} selectors Selectors to map.
2520 * @param {Object} store The redux store the selectors select from.
2521 *
2522 * @return {Object} Selectors mapped to their resolution functions.
2523 */
2524 function mapResolveSelectors(selectors, store) {
2525 const {
2526 getIsResolving,
2527 hasStartedResolution,
2528 hasFinishedResolution,
2529 hasResolutionFailed,
2530 isResolving,
2531 getCachedResolvers,
2532 getResolutionState,
2533 getResolutionError,
2534 hasResolvingSelectors,
2535 countSelectorsByStatus,
2536 ...storeSelectors
2537 } = selectors;
2538 return mapValues(storeSelectors, (selector, selectorName) => {
2539 // If the selector doesn't have a resolver, just convert the return value
2540 // (including exceptions) to a Promise, no additional extra behavior is needed.
2541 if (!selector.hasResolver) {
2542 return async (...args) => selector.apply(null, args);
2543 }
2544 return (...args) => {
2545 return new Promise((resolve, reject) => {
2546 const hasFinished = () => selectors.hasFinishedResolution(selectorName, args);
2547 const finalize = result => {
2548 const hasFailed = selectors.hasResolutionFailed(selectorName, args);
2549 if (hasFailed) {
2550 const error = selectors.getResolutionError(selectorName, args);
2551 reject(error);
2552 } else {
2553 resolve(result);
2554 }
2555 };
2556 const getResult = () => selector.apply(null, args);
2557 // Trigger the selector (to trigger the resolver)
2558 const result = getResult();
2559 if (hasFinished()) {
2560 return finalize(result);
2561 }
2562 const unsubscribe = store.subscribe(() => {
2563 if (hasFinished()) {
2564 unsubscribe();
2565 finalize(getResult());
2566 }
2567 });
2568 });
2569 };
2570 });
2571 }
2572
2573 /**
2574 * Maps selectors to functions that throw a suspense promise if not yet resolved.
2575 *
2576 * @param {Object} selectors Selectors to map.
2577 * @param {Object} store The redux store the selectors select from.
2578 *
2579 * @return {Object} Selectors mapped to their suspense functions.
2580 */
2581 function mapSuspendSelectors(selectors, store) {
2582 return mapValues(selectors, (selector, selectorName) => {
2583 // Selector without a resolver doesn't have any extra suspense behavior.
2584 if (!selector.hasResolver) {
2585 return selector;
2586 }
2587 return (...args) => {
2588 const result = selector.apply(null, args);
2589 if (selectors.hasFinishedResolution(selectorName, args)) {
2590 if (selectors.hasResolutionFailed(selectorName, args)) {
2591 throw selectors.getResolutionError(selectorName, args);
2592 }
2593 return result;
2594 }
2595 throw new Promise(resolve => {
2596 const unsubscribe = store.subscribe(() => {
2597 if (selectors.hasFinishedResolution(selectorName, args)) {
2598 resolve();
2599 unsubscribe();
2600 }
2601 });
2602 });
2603 };
2604 });
2605 }
2606
2607 /**
2608 * Convert resolvers to a normalized form, an object with `fulfill` method and
2609 * optional methods like `isFulfilled`.
2610 *
2611 * @param {Object} resolvers Resolver to convert
2612 */
2613 function mapResolvers(resolvers) {
2614 return mapValues(resolvers, resolver => {
2615 if (resolver.fulfill) {
2616 return resolver;
2617 }
2618 return {
2619 ...resolver,
2620 // Copy the enumerable properties of the resolver function.
2621 fulfill: resolver // Add the fulfill method.
2622 };
2623 });
2624 }
2625
2626 /**
2627 * Returns a selector with a matched resolver.
2628 * Resolvers are side effects invoked once per argument set of a given selector call,
2629 * used in ensuring that the data needs for the selector are satisfied.
2630 *
2631 * @param {Object} selector The selector function to be bound.
2632 * @param {string} selectorName The selector name.
2633 * @param {Object} resolver Resolver to call.
2634 * @param {Object} store The redux store to which the resolvers should be mapped.
2635 * @param {Object} resolversCache Resolvers Cache.
2636 */
2637 function mapSelectorWithResolver(selector, selectorName, resolver, store, resolversCache) {
2638 function fulfillSelector(args) {
2639 const state = store.getState();
2640 if (resolversCache.isRunning(selectorName, args) || typeof resolver.isFulfilled === 'function' && resolver.isFulfilled(state, ...args)) {
2641 return;
2642 }
2643 const {
2644 metadata
2645 } = store.__unstableOriginalGetState();
2646 if (hasStartedResolution(metadata, selectorName, args)) {
2647 return;
2648 }
2649 resolversCache.markAsRunning(selectorName, args);
2650 setTimeout(async () => {
2651 resolversCache.clear(selectorName, args);
2652 store.dispatch(startResolution(selectorName, args));
2653 try {
2654 const action = resolver.fulfill(...args);
2655 if (action) {
2656 await store.dispatch(action);
2657 }
2658 store.dispatch(finishResolution(selectorName, args));
2659 } catch (error) {
2660 store.dispatch(failResolution(selectorName, args, error));
2661 }
2662 }, 0);
2663 }
2664 const selectorResolver = (...args) => {
2665 args = normalize(selector, args);
2666 fulfillSelector(args);
2667 return selector(...args);
2668 };
2669 selectorResolver.hasResolver = true;
2670 return selectorResolver;
2671 }
2672
2673 /**
2674 * Applies selector's normalization function to the given arguments
2675 * if it exists.
2676 *
2677 * @param {Object} selector The selector potentially with a normalization method property.
2678 * @param {Array} args selector arguments to normalize.
2679 * @return {Array} Potentially normalized arguments.
2680 */
2681 function normalize(selector, args) {
2682 if (selector.__unstableNormalizeArgs && typeof selector.__unstableNormalizeArgs === 'function' && args?.length) {
2683 return selector.__unstableNormalizeArgs(args);
2684 }
2685 return args;
2686 }
2687
2688 ;// ./packages/data/build-module/store/index.js
2689 const coreDataStore = {
2690 name: 'core/data',
2691 instantiate(registry) {
2692 const getCoreDataSelector = selectorName => (key, ...args) => {
2693 return registry.select(key)[selectorName](...args);
2694 };
2695 const getCoreDataAction = actionName => (key, ...args) => {
2696 return registry.dispatch(key)[actionName](...args);
2697 };
2698 return {
2699 getSelectors() {
2700 return Object.fromEntries(['getIsResolving', 'hasStartedResolution', 'hasFinishedResolution', 'isResolving', 'getCachedResolvers'].map(selectorName => [selectorName, getCoreDataSelector(selectorName)]));
2701 },
2702 getActions() {
2703 return Object.fromEntries(['startResolution', 'finishResolution', 'invalidateResolution', 'invalidateResolutionForStore', 'invalidateResolutionForStoreSelector'].map(actionName => [actionName, getCoreDataAction(actionName)]));
2704 },
2705 subscribe() {
2706 // There's no reasons to trigger any listener when we subscribe to this store
2707 // because there's no state stored in this store that need to retrigger selectors
2708 // if a change happens, the corresponding store where the tracking stated live
2709 // would have already triggered a "subscribe" call.
2710 return () => () => {};
2711 }
2712 };
2713 }
2714 };
2715 /* harmony default export */ const store = (coreDataStore);
2716
2717 ;// ./packages/data/build-module/utils/emitter.js
2718 /* wp:polyfill */
2719 /**
2720 * Create an event emitter.
2721 *
2722 * @return The event emitter.
2723 */
2724 function createEmitter() {
2725 let isPaused = false;
2726 let isPending = false;
2727 const listeners = new Set();
2728 const notifyListeners = () =>
2729 // We use Array.from to clone the listeners Set
2730 // This ensures that we don't run a listener
2731 // that was added as a response to another listener.
2732 Array.from(listeners).forEach(listener => listener());
2733 return {
2734 get isPaused() {
2735 return isPaused;
2736 },
2737 subscribe(listener) {
2738 listeners.add(listener);
2739 return () => listeners.delete(listener);
2740 },
2741 pause() {
2742 isPaused = true;
2743 },
2744 resume() {
2745 isPaused = false;
2746 if (isPending) {
2747 isPending = false;
2748 notifyListeners();
2749 }
2750 },
2751 emit() {
2752 if (isPaused) {
2753 isPending = true;
2754 return;
2755 }
2756 notifyListeners();
2757 }
2758 };
2759 }
2760
2761 ;// ./packages/data/build-module/registry.js
2762 /* wp:polyfill */
2763 /**
2764 * WordPress dependencies
2765 */
2766
2767
2768 /**
2769 * Internal dependencies
2770 */
2771
2772
2773
2774
2775
2776 /** @typedef {import('./types').StoreDescriptor} StoreDescriptor */
2777
2778 /**
2779 * @typedef {Object} WPDataRegistry An isolated orchestrator of store registrations.
2780 *
2781 * @property {Function} registerGenericStore Given a namespace key and settings
2782 * object, registers a new generic
2783 * store.
2784 * @property {Function} registerStore Given a namespace key and settings
2785 * object, registers a new namespace
2786 * store.
2787 * @property {Function} subscribe Given a function callback, invokes
2788 * the callback on any change to state
2789 * within any registered store.
2790 * @property {Function} select Given a namespace key, returns an
2791 * object of the store's registered
2792 * selectors.
2793 * @property {Function} dispatch Given a namespace key, returns an
2794 * object of the store's registered
2795 * action dispatchers.
2796 */
2797
2798 /**
2799 * @typedef {Object} WPDataPlugin An object of registry function overrides.
2800 *
2801 * @property {Function} registerStore registers store.
2802 */
2803
2804 function getStoreName(storeNameOrDescriptor) {
2805 return typeof storeNameOrDescriptor === 'string' ? storeNameOrDescriptor : storeNameOrDescriptor.name;
2806 }
2807 /**
2808 * Creates a new store registry, given an optional object of initial store
2809 * configurations.
2810 *
2811 * @param {Object} storeConfigs Initial store configurations.
2812 * @param {?Object} parent Parent registry.
2813 *
2814 * @return {WPDataRegistry} Data registry.
2815 */
2816 function createRegistry(storeConfigs = {}, parent = null) {
2817 const stores = {};
2818 const emitter = createEmitter();
2819 let listeningStores = null;
2820
2821 /**
2822 * Global listener called for each store's update.
2823 */
2824 function globalListener() {
2825 emitter.emit();
2826 }
2827
2828 /**
2829 * Subscribe to changes to any data, either in all stores in registry, or
2830 * in one specific store.
2831 *
2832 * @param {Function} listener Listener function.
2833 * @param {string|StoreDescriptor?} storeNameOrDescriptor Optional store name.
2834 *
2835 * @return {Function} Unsubscribe function.
2836 */
2837 const subscribe = (listener, storeNameOrDescriptor) => {
2838 // subscribe to all stores
2839 if (!storeNameOrDescriptor) {
2840 return emitter.subscribe(listener);
2841 }
2842
2843 // subscribe to one store
2844 const storeName = getStoreName(storeNameOrDescriptor);
2845 const store = stores[storeName];
2846 if (store) {
2847 return store.subscribe(listener);
2848 }
2849
2850 // Trying to access a store that hasn't been registered,
2851 // this is a pattern rarely used but seen in some places.
2852 // We fallback to global `subscribe` here for backward-compatibility for now.
2853 // See https://github.com/WordPress/gutenberg/pull/27466 for more info.
2854 if (!parent) {
2855 return emitter.subscribe(listener);
2856 }
2857 return parent.subscribe(listener, storeNameOrDescriptor);
2858 };
2859
2860 /**
2861 * Calls a selector given the current state and extra arguments.
2862 *
2863 * @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
2864 * or the store descriptor.
2865 *
2866 * @return {*} The selector's returned value.
2867 */
2868 function select(storeNameOrDescriptor) {
2869 const storeName = getStoreName(storeNameOrDescriptor);
2870 listeningStores?.add(storeName);
2871 const store = stores[storeName];
2872 if (store) {
2873 return store.getSelectors();
2874 }
2875 return parent?.select(storeName);
2876 }
2877 function __unstableMarkListeningStores(callback, ref) {
2878 listeningStores = new Set();
2879 try {
2880 return callback.call(this);
2881 } finally {
2882 ref.current = Array.from(listeningStores);
2883 listeningStores = null;
2884 }
2885 }
2886
2887 /**
2888 * Given a store descriptor, returns an object containing the store's selectors pre-bound to
2889 * state so that you only need to supply additional arguments, and modified so that they return
2890 * promises that resolve to their eventual values, after any resolvers have ran.
2891 *
2892 * @param {StoreDescriptor|string} storeNameOrDescriptor The store descriptor. The legacy calling
2893 * convention of passing the store name is
2894 * also supported.
2895 *
2896 * @return {Object} Each key of the object matches the name of a selector.
2897 */
2898 function resolveSelect(storeNameOrDescriptor) {
2899 const storeName = getStoreName(storeNameOrDescriptor);
2900 listeningStores?.add(storeName);
2901 const store = stores[storeName];
2902 if (store) {
2903 return store.getResolveSelectors();
2904 }
2905 return parent && parent.resolveSelect(storeName);
2906 }
2907
2908 /**
2909 * Given a store descriptor, returns an object containing the store's selectors pre-bound to
2910 * state so that you only need to supply additional arguments, and modified so that they throw
2911 * promises in case the selector is not resolved yet.
2912 *
2913 * @param {StoreDescriptor|string} storeNameOrDescriptor The store descriptor. The legacy calling
2914 * convention of passing the store name is
2915 * also supported.
2916 *
2917 * @return {Object} Object containing the store's suspense-wrapped selectors.
2918 */
2919 function suspendSelect(storeNameOrDescriptor) {
2920 const storeName = getStoreName(storeNameOrDescriptor);
2921 listeningStores?.add(storeName);
2922 const store = stores[storeName];
2923 if (store) {
2924 return store.getSuspendSelectors();
2925 }
2926 return parent && parent.suspendSelect(storeName);
2927 }
2928
2929 /**
2930 * Returns the available actions for a part of the state.
2931 *
2932 * @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
2933 * or the store descriptor.
2934 *
2935 * @return {*} The action's returned value.
2936 */
2937 function dispatch(storeNameOrDescriptor) {
2938 const storeName = getStoreName(storeNameOrDescriptor);
2939 const store = stores[storeName];
2940 if (store) {
2941 return store.getActions();
2942 }
2943 return parent && parent.dispatch(storeName);
2944 }
2945
2946 //
2947 // Deprecated
2948 // TODO: Remove this after `use()` is removed.
2949 function withPlugins(attributes) {
2950 return Object.fromEntries(Object.entries(attributes).map(([key, attribute]) => {
2951 if (typeof attribute !== 'function') {
2952 return [key, attribute];
2953 }
2954 return [key, function () {
2955 return registry[key].apply(null, arguments);
2956 }];
2957 }));
2958 }
2959
2960 /**
2961 * Registers a store instance.
2962 *
2963 * @param {string} name Store registry name.
2964 * @param {Function} createStore Function that creates a store object (getSelectors, getActions, subscribe).
2965 */
2966 function registerStoreInstance(name, createStore) {
2967 if (stores[name]) {
2968 // eslint-disable-next-line no-console
2969 console.error('Store "' + name + '" is already registered.');
2970 return stores[name];
2971 }
2972 const store = createStore();
2973 if (typeof store.getSelectors !== 'function') {
2974 throw new TypeError('store.getSelectors must be a function');
2975 }
2976 if (typeof store.getActions !== 'function') {
2977 throw new TypeError('store.getActions must be a function');
2978 }
2979 if (typeof store.subscribe !== 'function') {
2980 throw new TypeError('store.subscribe must be a function');
2981 }
2982 // The emitter is used to keep track of active listeners when the registry
2983 // get paused, that way, when resumed we should be able to call all these
2984 // pending listeners.
2985 store.emitter = createEmitter();
2986 const currentSubscribe = store.subscribe;
2987 store.subscribe = listener => {
2988 const unsubscribeFromEmitter = store.emitter.subscribe(listener);
2989 const unsubscribeFromStore = currentSubscribe(() => {
2990 if (store.emitter.isPaused) {
2991 store.emitter.emit();
2992 return;
2993 }
2994 listener();
2995 });
2996 return () => {
2997 unsubscribeFromStore?.();
2998 unsubscribeFromEmitter?.();
2999 };
3000 };
3001 stores[name] = store;
3002 store.subscribe(globalListener);
3003
3004 // Copy private actions and selectors from the parent store.
3005 if (parent) {
3006 try {
3007 unlock(store.store).registerPrivateActions(unlock(parent).privateActionsOf(name));
3008 unlock(store.store).registerPrivateSelectors(unlock(parent).privateSelectorsOf(name));
3009 } catch (e) {
3010 // unlock() throws if store.store was not locked.
3011 // The error indicates there's nothing to do here so let's
3012 // ignore it.
3013 }
3014 }
3015 return store;
3016 }
3017
3018 /**
3019 * Registers a new store given a store descriptor.
3020 *
3021 * @param {StoreDescriptor} store Store descriptor.
3022 */
3023 function register(store) {
3024 registerStoreInstance(store.name, () => store.instantiate(registry));
3025 }
3026 function registerGenericStore(name, store) {
3027 external_wp_deprecated_default()('wp.data.registerGenericStore', {
3028 since: '5.9',
3029 alternative: 'wp.data.register( storeDescriptor )'
3030 });
3031 registerStoreInstance(name, () => store);
3032 }
3033
3034 /**
3035 * Registers a standard `@wordpress/data` store.
3036 *
3037 * @param {string} storeName Unique namespace identifier.
3038 * @param {Object} options Store description (reducer, actions, selectors, resolvers).
3039 *
3040 * @return {Object} Registered store object.
3041 */
3042 function registerStore(storeName, options) {
3043 if (!options.reducer) {
3044 throw new TypeError('Must specify store reducer');
3045 }
3046 const store = registerStoreInstance(storeName, () => createReduxStore(storeName, options).instantiate(registry));
3047 return store.store;
3048 }
3049 function batch(callback) {
3050 // If we're already batching, just call the callback.
3051 if (emitter.isPaused) {
3052 callback();
3053 return;
3054 }
3055 emitter.pause();
3056 Object.values(stores).forEach(store => store.emitter.pause());
3057 try {
3058 callback();
3059 } finally {
3060 emitter.resume();
3061 Object.values(stores).forEach(store => store.emitter.resume());
3062 }
3063 }
3064 let registry = {
3065 batch,
3066 stores,
3067 namespaces: stores,
3068 // TODO: Deprecate/remove this.
3069 subscribe,
3070 select,
3071 resolveSelect,
3072 suspendSelect,
3073 dispatch,
3074 use,
3075 register,
3076 registerGenericStore,
3077 registerStore,
3078 __unstableMarkListeningStores
3079 };
3080
3081 //
3082 // TODO:
3083 // This function will be deprecated as soon as it is no longer internally referenced.
3084 function use(plugin, options) {
3085 if (!plugin) {
3086 return;
3087 }
3088 registry = {
3089 ...registry,
3090 ...plugin(registry, options)
3091 };
3092 return registry;
3093 }
3094 registry.register(store);
3095 for (const [name, config] of Object.entries(storeConfigs)) {
3096 registry.register(createReduxStore(name, config));
3097 }
3098 if (parent) {
3099 parent.subscribe(globalListener);
3100 }
3101 const registryWithPlugins = withPlugins(registry);
3102 lock(registryWithPlugins, {
3103 privateActionsOf: name => {
3104 try {
3105 return unlock(stores[name].store).privateActions;
3106 } catch (e) {
3107 // unlock() throws an error the store was not locked – this means
3108 // there no private actions are available
3109 return {};
3110 }
3111 },
3112 privateSelectorsOf: name => {
3113 try {
3114 return unlock(stores[name].store).privateSelectors;
3115 } catch (e) {
3116 return {};
3117 }
3118 }
3119 });
3120 return registryWithPlugins;
3121 }
3122
3123 ;// ./packages/data/build-module/default-registry.js
3124 /**
3125 * Internal dependencies
3126 */
3127
3128 /* harmony default export */ const default_registry = (createRegistry());
3129
3130 ;// ./node_modules/is-plain-object/dist/is-plain-object.mjs
3131 /*!
3132 * is-plain-object <https://github.com/jonschlinkert/is-plain-object>
3133 *
3134 * Copyright (c) 2014-2017, Jon Schlinkert.
3135 * Released under the MIT License.
3136 */
3137
3138 function is_plain_object_isObject(o) {
3139 return Object.prototype.toString.call(o) === '[object Object]';
3140 }
3141
3142 function is_plain_object_isPlainObject(o) {
3143 var ctor,prot;
3144
3145 if (is_plain_object_isObject(o) === false) return false;
3146
3147 // If has modified constructor
3148 ctor = o.constructor;
3149 if (ctor === undefined) return true;
3150
3151 // If has modified prototype
3152 prot = ctor.prototype;
3153 if (is_plain_object_isObject(prot) === false) return false;
3154
3155 // If constructor does not have an Object-specific method
3156 if (prot.hasOwnProperty('isPrototypeOf') === false) {
3157 return false;
3158 }
3159
3160 // Most likely a plain Object
3161 return true;
3162 }
3163
3164
3165
3166 // EXTERNAL MODULE: ./node_modules/deepmerge/dist/cjs.js
3167 var cjs = __webpack_require__(66);
3168 var cjs_default = /*#__PURE__*/__webpack_require__.n(cjs);
3169 ;// ./packages/data/build-module/plugins/persistence/storage/object.js
3170 let objectStorage;
3171 const storage = {
3172 getItem(key) {
3173 if (!objectStorage || !objectStorage[key]) {
3174 return null;
3175 }
3176 return objectStorage[key];
3177 },
3178 setItem(key, value) {
3179 if (!objectStorage) {
3180 storage.clear();
3181 }
3182 objectStorage[key] = String(value);
3183 },
3184 clear() {
3185 objectStorage = Object.create(null);
3186 }
3187 };
3188 /* harmony default export */ const object = (storage);
3189
3190 ;// ./packages/data/build-module/plugins/persistence/storage/default.js
3191 /**
3192 * Internal dependencies
3193 */
3194
3195 let default_storage;
3196 try {
3197 // Private Browsing in Safari 10 and earlier will throw an error when
3198 // attempting to set into localStorage. The test here is intentional in
3199 // causing a thrown error as condition for using fallback object storage.
3200 default_storage = window.localStorage;
3201 default_storage.setItem('__wpDataTestLocalStorage', '');
3202 default_storage.removeItem('__wpDataTestLocalStorage');
3203 } catch (error) {
3204 default_storage = object;
3205 }
3206 /* harmony default export */ const storage_default = (default_storage);
3207
3208 ;// ./packages/data/build-module/plugins/persistence/index.js
3209 /* wp:polyfill */
3210 /**
3211 * External dependencies
3212 */
3213
3214
3215
3216 /**
3217 * Internal dependencies
3218 */
3219
3220
3221
3222 /** @typedef {import('../../registry').WPDataRegistry} WPDataRegistry */
3223
3224 /** @typedef {import('../../registry').WPDataPlugin} WPDataPlugin */
3225
3226 /**
3227 * @typedef {Object} WPDataPersistencePluginOptions Persistence plugin options.
3228 *
3229 * @property {Storage} storage Persistent storage implementation. This must
3230 * at least implement `getItem` and `setItem` of
3231 * the Web Storage API.
3232 * @property {string} storageKey Key on which to set in persistent storage.
3233 */
3234
3235 /**
3236 * Default plugin storage.
3237 *
3238 * @type {Storage}
3239 */
3240 const DEFAULT_STORAGE = storage_default;
3241
3242 /**
3243 * Default plugin storage key.
3244 *
3245 * @type {string}
3246 */
3247 const DEFAULT_STORAGE_KEY = 'WP_DATA';
3248
3249 /**
3250 * Higher-order reducer which invokes the original reducer only if state is
3251 * inequal from that of the action's `nextState` property, otherwise returning
3252 * the original state reference.
3253 *
3254 * @param {Function} reducer Original reducer.
3255 *
3256 * @return {Function} Enhanced reducer.
3257 */
3258 const withLazySameState = reducer => (state, action) => {
3259 if (action.nextState === state) {
3260 return state;
3261 }
3262 return reducer(state, action);
3263 };
3264
3265 /**
3266 * Creates a persistence interface, exposing getter and setter methods (`get`
3267 * and `set` respectively).
3268 *
3269 * @param {WPDataPersistencePluginOptions} options Plugin options.
3270 *
3271 * @return {Object} Persistence interface.
3272 */
3273 function createPersistenceInterface(options) {
3274 const {
3275 storage = DEFAULT_STORAGE,
3276 storageKey = DEFAULT_STORAGE_KEY
3277 } = options;
3278 let data;
3279
3280 /**
3281 * Returns the persisted data as an object, defaulting to an empty object.
3282 *
3283 * @return {Object} Persisted data.
3284 */
3285 function getData() {
3286 if (data === undefined) {
3287 // If unset, getItem is expected to return null. Fall back to
3288 // empty object.
3289 const persisted = storage.getItem(storageKey);
3290 if (persisted === null) {
3291 data = {};
3292 } else {
3293 try {
3294 data = JSON.parse(persisted);
3295 } catch (error) {
3296 // Similarly, should any error be thrown during parse of
3297 // the string (malformed JSON), fall back to empty object.
3298 data = {};
3299 }
3300 }
3301 }
3302 return data;
3303 }
3304
3305 /**
3306 * Merges an updated reducer state into the persisted data.
3307 *
3308 * @param {string} key Key to update.
3309 * @param {*} value Updated value.
3310 */
3311 function setData(key, value) {
3312 data = {
3313 ...data,
3314 [key]: value
3315 };
3316 storage.setItem(storageKey, JSON.stringify(data));
3317 }
3318 return {
3319 get: getData,
3320 set: setData
3321 };
3322 }
3323
3324 /**
3325 * Data plugin to persist store state into a single storage key.
3326 *
3327 * @param {WPDataRegistry} registry Data registry.
3328 * @param {?WPDataPersistencePluginOptions} pluginOptions Plugin options.
3329 *
3330 * @return {WPDataPlugin} Data plugin.
3331 */
3332 function persistencePlugin(registry, pluginOptions) {
3333 const persistence = createPersistenceInterface(pluginOptions);
3334
3335 /**
3336 * Creates an enhanced store dispatch function, triggering the state of the
3337 * given store name to be persisted when changed.
3338 *
3339 * @param {Function} getState Function which returns current state.
3340 * @param {string} storeName Store name.
3341 * @param {?Array<string>} keys Optional subset of keys to save.
3342 *
3343 * @return {Function} Enhanced dispatch function.
3344 */
3345 function createPersistOnChange(getState, storeName, keys) {
3346 let getPersistedState;
3347 if (Array.isArray(keys)) {
3348 // Given keys, the persisted state should by produced as an object
3349 // of the subset of keys. This implementation uses combineReducers
3350 // to leverage its behavior of returning the same object when none
3351 // of the property values changes. This allows a strict reference
3352 // equality to bypass a persistence set on an unchanging state.
3353 const reducers = keys.reduce((accumulator, key) => Object.assign(accumulator, {
3354 [key]: (state, action) => action.nextState[key]
3355 }), {});
3356 getPersistedState = withLazySameState(build_module_combineReducers(reducers));
3357 } else {
3358 getPersistedState = (state, action) => action.nextState;
3359 }
3360 let lastState = getPersistedState(undefined, {
3361 nextState: getState()
3362 });
3363 return () => {
3364 const state = getPersistedState(lastState, {
3365 nextState: getState()
3366 });
3367 if (state !== lastState) {
3368 persistence.set(storeName, state);
3369 lastState = state;
3370 }
3371 };
3372 }
3373 return {
3374 registerStore(storeName, options) {
3375 if (!options.persist) {
3376 return registry.registerStore(storeName, options);
3377 }
3378
3379 // Load from persistence to use as initial state.
3380 const persistedState = persistence.get()[storeName];
3381 if (persistedState !== undefined) {
3382 let initialState = options.reducer(options.initialState, {
3383 type: '@@WP/PERSISTENCE_RESTORE'
3384 });
3385 if (is_plain_object_isPlainObject(initialState) && is_plain_object_isPlainObject(persistedState)) {
3386 // If state is an object, ensure that:
3387 // - Other keys are left intact when persisting only a
3388 // subset of keys.
3389 // - New keys in what would otherwise be used as initial
3390 // state are deeply merged as base for persisted value.
3391 initialState = cjs_default()(initialState, persistedState, {
3392 isMergeableObject: is_plain_object_isPlainObject
3393 });
3394 } else {
3395 // If there is a mismatch in object-likeness of default
3396 // initial or persisted state, defer to persisted value.
3397 initialState = persistedState;
3398 }
3399 options = {
3400 ...options,
3401 initialState
3402 };
3403 }
3404 const store = registry.registerStore(storeName, options);
3405 store.subscribe(createPersistOnChange(store.getState, storeName, options.persist));
3406 return store;
3407 }
3408 };
3409 }
3410 persistencePlugin.__unstableMigrate = () => {};
3411 /* harmony default export */ const persistence = (persistencePlugin);
3412
3413 ;// ./packages/data/build-module/plugins/index.js
3414
3415
3416 ;// external ["wp","priorityQueue"]
3417 const external_wp_priorityQueue_namespaceObject = window["wp"]["priorityQueue"];
3418 ;// external ["wp","element"]
3419 const external_wp_element_namespaceObject = window["wp"]["element"];
3420 ;// external ["wp","isShallowEqual"]
3421 const external_wp_isShallowEqual_namespaceObject = window["wp"]["isShallowEqual"];
3422 var external_wp_isShallowEqual_default = /*#__PURE__*/__webpack_require__.n(external_wp_isShallowEqual_namespaceObject);
3423 ;// ./packages/data/build-module/components/registry-provider/context.js
3424 /**
3425 * WordPress dependencies
3426 */
3427
3428
3429 /**
3430 * Internal dependencies
3431 */
3432
3433 const Context = (0,external_wp_element_namespaceObject.createContext)(default_registry);
3434 const {
3435 Consumer,
3436 Provider
3437 } = Context;
3438
3439 /**
3440 * A custom react Context consumer exposing the provided `registry` to
3441 * children components. Used along with the RegistryProvider.
3442 *
3443 * You can read more about the react context api here:
3444 * https://react.dev/learn/passing-data-deeply-with-context#step-3-provide-the-context
3445 *
3446 * @example
3447 * ```js
3448 * import {
3449 * RegistryProvider,
3450 * RegistryConsumer,
3451 * createRegistry
3452 * } from '@wordpress/data';
3453 *
3454 * const registry = createRegistry( {} );
3455 *
3456 * const App = ( { props } ) => {
3457 * return <RegistryProvider value={ registry }>
3458 * <div>Hello There</div>
3459 * <RegistryConsumer>
3460 * { ( registry ) => (
3461 * <ComponentUsingRegistry
3462 * { ...props }
3463 * registry={ registry }
3464 * ) }
3465 * </RegistryConsumer>
3466 * </RegistryProvider>
3467 * }
3468 * ```
3469 */
3470 const RegistryConsumer = Consumer;
3471
3472 /**
3473 * A custom Context provider for exposing the provided `registry` to children
3474 * components via a consumer.
3475 *
3476 * See <a name="#RegistryConsumer">RegistryConsumer</a> documentation for
3477 * example.
3478 */
3479 /* harmony default export */ const context = (Provider);
3480
3481 ;// ./packages/data/build-module/components/registry-provider/use-registry.js
3482 /**
3483 * WordPress dependencies
3484 */
3485
3486
3487 /**
3488 * Internal dependencies
3489 */
3490
3491
3492 /**
3493 * A custom react hook exposing the registry context for use.
3494 *
3495 * This exposes the `registry` value provided via the
3496 * <a href="#RegistryProvider">Registry Provider</a> to a component implementing
3497 * this hook.
3498 *
3499 * It acts similarly to the `useContext` react hook.
3500 *
3501 * Note: Generally speaking, `useRegistry` is a low level hook that in most cases
3502 * won't be needed for implementation. Most interactions with the `@wordpress/data`
3503 * API can be performed via the `useSelect` hook, or the `withSelect` and
3504 * `withDispatch` higher order components.
3505 *
3506 * @example
3507 * ```js
3508 * import {
3509 * RegistryProvider,
3510 * createRegistry,
3511 * useRegistry,
3512 * } from '@wordpress/data';
3513 *
3514 * const registry = createRegistry( {} );
3515 *
3516 * const SomeChildUsingRegistry = ( props ) => {
3517 * const registry = useRegistry();
3518 * // ...logic implementing the registry in other react hooks.
3519 * };
3520 *
3521 *
3522 * const ParentProvidingRegistry = ( props ) => {
3523 * return <RegistryProvider value={ registry }>
3524 * <SomeChildUsingRegistry { ...props } />
3525 * </RegistryProvider>
3526 * };
3527 * ```
3528 *
3529 * @return {Function} A custom react hook exposing the registry context value.
3530 */
3531 function useRegistry() {
3532 return (0,external_wp_element_namespaceObject.useContext)(Context);
3533 }
3534
3535 ;// ./packages/data/build-module/components/async-mode-provider/context.js
3536 /**
3537 * WordPress dependencies
3538 */
3539
3540 const context_Context = (0,external_wp_element_namespaceObject.createContext)(false);
3541 const {
3542 Consumer: context_Consumer,
3543 Provider: context_Provider
3544 } = context_Context;
3545 const AsyncModeConsumer = (/* unused pure expression or super */ null && (context_Consumer));
3546
3547 /**
3548 * Context Provider Component used to switch the data module component rerendering
3549 * between Sync and Async modes.
3550 *
3551 * @example
3552 *
3553 * ```js
3554 * import { useSelect, AsyncModeProvider } from '@wordpress/data';
3555 * import { store as blockEditorStore } from '@wordpress/block-editor';
3556 *
3557 * function BlockCount() {
3558 * const count = useSelect( ( select ) => {
3559 * return select( blockEditorStore ).getBlockCount()
3560 * }, [] );
3561 *
3562 * return count;
3563 * }
3564 *
3565 * function App() {
3566 * return (
3567 * <AsyncModeProvider value={ true }>
3568 * <BlockCount />
3569 * </AsyncModeProvider>
3570 * );
3571 * }
3572 * ```
3573 *
3574 * In this example, the BlockCount component is rerendered asynchronously.
3575 * It means if a more critical task is being performed (like typing in an input),
3576 * the rerendering is delayed until the browser becomes IDLE.
3577 * It is possible to nest multiple levels of AsyncModeProvider to fine-tune the rendering behavior.
3578 *
3579 * @param {boolean} props.value Enable Async Mode.
3580 * @return {Component} The component to be rendered.
3581 */
3582 /* harmony default export */ const async_mode_provider_context = (context_Provider);
3583
3584 ;// ./packages/data/build-module/components/async-mode-provider/use-async-mode.js
3585 /**
3586 * WordPress dependencies
3587 */
3588
3589
3590 /**
3591 * Internal dependencies
3592 */
3593
3594 function useAsyncMode() {
3595 return (0,external_wp_element_namespaceObject.useContext)(context_Context);
3596 }
3597
3598 ;// ./packages/data/build-module/components/use-select/index.js
3599 /* wp:polyfill */
3600 /**
3601 * WordPress dependencies
3602 */
3603
3604
3605
3606
3607 /**
3608 * Internal dependencies
3609 */
3610
3611
3612 const renderQueue = (0,external_wp_priorityQueue_namespaceObject.createQueue)();
3613 function warnOnUnstableReference(a, b) {
3614 if (!a || !b) {
3615 return;
3616 }
3617 const keys = typeof a === 'object' && typeof b === 'object' ? Object.keys(a).filter(k => a[k] !== b[k]) : [];
3618
3619 // eslint-disable-next-line no-console
3620 console.warn('The `useSelect` hook returns different values when called with the same state and parameters.\n' + 'This can lead to unnecessary re-renders and performance issues if not fixed.\n\n' + 'Non-equal value keys: %s\n\n', keys.join(', '));
3621 }
3622
3623 /**
3624 * @typedef {import('../../types').StoreDescriptor<C>} StoreDescriptor
3625 * @template {import('../../types').AnyConfig} C
3626 */
3627 /**
3628 * @typedef {import('../../types').ReduxStoreConfig<State,Actions,Selectors>} ReduxStoreConfig
3629 * @template State
3630 * @template {Record<string,import('../../types').ActionCreator>} Actions
3631 * @template Selectors
3632 */
3633 /** @typedef {import('../../types').MapSelect} MapSelect */
3634 /**
3635 * @typedef {import('../../types').UseSelectReturn<T>} UseSelectReturn
3636 * @template {MapSelect|StoreDescriptor<any>} T
3637 */
3638
3639 function Store(registry, suspense) {
3640 const select = suspense ? registry.suspendSelect : registry.select;
3641 const queueContext = {};
3642 let lastMapSelect;
3643 let lastMapResult;
3644 let lastMapResultValid = false;
3645 let lastIsAsync;
3646 let subscriber;
3647 let didWarnUnstableReference;
3648 const storeStatesOnMount = new Map();
3649 function getStoreState(name) {
3650 var _registry$stores$name;
3651 // If there's no store property (custom generic store), return an empty
3652 // object. When comparing the state, the empty objects will cause the
3653 // equality check to fail, setting `lastMapResultValid` to false.
3654 return (_registry$stores$name = registry.stores[name]?.store?.getState?.()) !== null && _registry$stores$name !== void 0 ? _registry$stores$name : {};
3655 }
3656 const createSubscriber = stores => {
3657 // The set of stores the `subscribe` function is supposed to subscribe to. Here it is
3658 // initialized, and then the `updateStores` function can add new stores to it.
3659 const activeStores = [...stores];
3660
3661 // The `subscribe` function, which is passed to the `useSyncExternalStore` hook, could
3662 // be called multiple times to establish multiple subscriptions. That's why we need to
3663 // keep a set of active subscriptions;
3664 const activeSubscriptions = new Set();
3665 function subscribe(listener) {
3666 // Maybe invalidate the value right after subscription was created.
3667 // React will call `getValue` after subscribing, to detect store
3668 // updates that happened in the interval between the `getValue` call
3669 // during render and creating the subscription, which is slightly
3670 // delayed. We need to ensure that this second `getValue` call will
3671 // compute a fresh value only if any of the store states have
3672 // changed in the meantime.
3673 if (lastMapResultValid) {
3674 for (const name of activeStores) {
3675 if (storeStatesOnMount.get(name) !== getStoreState(name)) {
3676 lastMapResultValid = false;
3677 }
3678 }
3679 }
3680 storeStatesOnMount.clear();
3681 const onStoreChange = () => {
3682 // Invalidate the value on store update, so that a fresh value is computed.
3683 lastMapResultValid = false;
3684 listener();
3685 };
3686 const onChange = () => {
3687 if (lastIsAsync) {
3688 renderQueue.add(queueContext, onStoreChange);
3689 } else {
3690 onStoreChange();
3691 }
3692 };
3693 const unsubs = [];
3694 function subscribeStore(storeName) {
3695 unsubs.push(registry.subscribe(onChange, storeName));
3696 }
3697 for (const storeName of activeStores) {
3698 subscribeStore(storeName);
3699 }
3700 activeSubscriptions.add(subscribeStore);
3701 return () => {
3702 activeSubscriptions.delete(subscribeStore);
3703 for (const unsub of unsubs.values()) {
3704 // The return value of the subscribe function could be undefined if the store is a custom generic store.
3705 unsub?.();
3706 }
3707 // Cancel existing store updates that were already scheduled.
3708 renderQueue.cancel(queueContext);
3709 };
3710 }
3711
3712 // Check if `newStores` contains some stores we're not subscribed to yet, and add them.
3713 function updateStores(newStores) {
3714 for (const newStore of newStores) {
3715 if (activeStores.includes(newStore)) {
3716 continue;
3717 }
3718
3719 // New `subscribe` calls will subscribe to `newStore`, too.
3720 activeStores.push(newStore);
3721
3722 // Add `newStore` to existing subscriptions.
3723 for (const subscription of activeSubscriptions) {
3724 subscription(newStore);
3725 }
3726 }
3727 }
3728 return {
3729 subscribe,
3730 updateStores
3731 };
3732 };
3733 return (mapSelect, isAsync) => {
3734 function updateValue() {
3735 // If the last value is valid, and the `mapSelect` callback hasn't changed,
3736 // then we can safely return the cached value. The value can change only on
3737 // store update, and in that case value will be invalidated by the listener.
3738 if (lastMapResultValid && mapSelect === lastMapSelect) {
3739 return lastMapResult;
3740 }
3741 const listeningStores = {
3742 current: null
3743 };
3744 const mapResult = registry.__unstableMarkListeningStores(() => mapSelect(select, registry), listeningStores);
3745 if (false) {}
3746 if (!subscriber) {
3747 for (const name of listeningStores.current) {
3748 storeStatesOnMount.set(name, getStoreState(name));
3749 }
3750 subscriber = createSubscriber(listeningStores.current);
3751 } else {
3752 subscriber.updateStores(listeningStores.current);
3753 }
3754
3755 // If the new value is shallow-equal to the old one, keep the old one so
3756 // that we don't trigger unwanted updates that do a `===` check.
3757 if (!external_wp_isShallowEqual_default()(lastMapResult, mapResult)) {
3758 lastMapResult = mapResult;
3759 }
3760 lastMapSelect = mapSelect;
3761 lastMapResultValid = true;
3762 }
3763 function getValue() {
3764 // Update the value in case it's been invalidated or `mapSelect` has changed.
3765 updateValue();
3766 return lastMapResult;
3767 }
3768
3769 // When transitioning from async to sync mode, cancel existing store updates
3770 // that have been scheduled, and invalidate the value so that it's freshly
3771 // computed. It might have been changed by the update we just cancelled.
3772 if (lastIsAsync && !isAsync) {
3773 lastMapResultValid = false;
3774 renderQueue.cancel(queueContext);
3775 }
3776 updateValue();
3777 lastIsAsync = isAsync;
3778
3779 // Return a pair of functions that can be passed to `useSyncExternalStore`.
3780 return {
3781 subscribe: subscriber.subscribe,
3782 getValue
3783 };
3784 };
3785 }
3786 function _useStaticSelect(storeName) {
3787 return useRegistry().select(storeName);
3788 }
3789 function _useMappingSelect(suspense, mapSelect, deps) {
3790 const registry = useRegistry();
3791 const isAsync = useAsyncMode();
3792 const store = (0,external_wp_element_namespaceObject.useMemo)(() => Store(registry, suspense), [registry, suspense]);
3793
3794 // These are "pass-through" dependencies from the parent hook,
3795 // and the parent should catch any hook rule violations.
3796 const selector = (0,external_wp_element_namespaceObject.useCallback)(mapSelect, deps);
3797 const {
3798 subscribe,
3799 getValue
3800 } = store(selector, isAsync);
3801 const result = (0,external_wp_element_namespaceObject.useSyncExternalStore)(subscribe, getValue, getValue);
3802 (0,external_wp_element_namespaceObject.useDebugValue)(result);
3803 return result;
3804 }
3805
3806 /**
3807 * Custom react hook for retrieving props from registered selectors.
3808 *
3809 * In general, this custom React hook follows the
3810 * [rules of hooks](https://react.dev/reference/rules/rules-of-hooks).
3811 *
3812 * @template {MapSelect | StoreDescriptor<any>} T
3813 * @param {T} mapSelect Function called on every state change. The returned value is
3814 * exposed to the component implementing this hook. The function
3815 * receives the `registry.select` method on the first argument
3816 * and the `registry` on the second argument.
3817 * When a store key is passed, all selectors for the store will be
3818 * returned. This is only meant for usage of these selectors in event
3819 * callbacks, not for data needed to create the element tree.
3820 * @param {unknown[]} deps If provided, this memoizes the mapSelect so the same `mapSelect` is
3821 * invoked on every state change unless the dependencies change.
3822 *
3823 * @example
3824 * ```js
3825 * import { useSelect } from '@wordpress/data';
3826 * import { store as myCustomStore } from 'my-custom-store';
3827 *
3828 * function HammerPriceDisplay( { currency } ) {
3829 * const price = useSelect( ( select ) => {
3830 * return select( myCustomStore ).getPrice( 'hammer', currency );
3831 * }, [ currency ] );
3832 * return new Intl.NumberFormat( 'en-US', {
3833 * style: 'currency',
3834 * currency,
3835 * } ).format( price );
3836 * }
3837 *
3838 * // Rendered in the application:
3839 * // <HammerPriceDisplay currency="USD" />
3840 * ```
3841 *
3842 * In the above example, when `HammerPriceDisplay` is rendered into an
3843 * application, the price will be retrieved from the store state using the
3844 * `mapSelect` callback on `useSelect`. If the currency prop changes then
3845 * any price in the state for that currency is retrieved. If the currency prop
3846 * doesn't change and other props are passed in that do change, the price will
3847 * not change because the dependency is just the currency.
3848 *
3849 * When data is only used in an event callback, the data should not be retrieved
3850 * on render, so it may be useful to get the selectors function instead.
3851 *
3852 * **Don't use `useSelect` this way when calling the selectors in the render
3853 * function because your component won't re-render on a data change.**
3854 *
3855 * ```js
3856 * import { useSelect } from '@wordpress/data';
3857 * import { store as myCustomStore } from 'my-custom-store';
3858 *
3859 * function Paste( { children } ) {
3860 * const { getSettings } = useSelect( myCustomStore );
3861 * function onPaste() {
3862 * // Do something with the settings.
3863 * const settings = getSettings();
3864 * }
3865 * return <div onPaste={ onPaste }>{ children }</div>;
3866 * }
3867 * ```
3868 * @return {UseSelectReturn<T>} A custom react hook.
3869 */
3870 function useSelect(mapSelect, deps) {
3871 // On initial call, on mount, determine the mode of this `useSelect` call
3872 // and then never allow it to change on subsequent updates.
3873 const staticSelectMode = typeof mapSelect !== 'function';
3874 const staticSelectModeRef = (0,external_wp_element_namespaceObject.useRef)(staticSelectMode);
3875 if (staticSelectMode !== staticSelectModeRef.current) {
3876 const prevMode = staticSelectModeRef.current ? 'static' : 'mapping';
3877 const nextMode = staticSelectMode ? 'static' : 'mapping';
3878 throw new Error(`Switching useSelect from ${prevMode} to ${nextMode} is not allowed`);
3879 }
3880
3881 // `staticSelectMode` is not allowed to change during the hook instance's,
3882 // lifetime, so the rules of hooks are not really violated.
3883 return staticSelectMode ? _useStaticSelect(mapSelect) : _useMappingSelect(false, mapSelect, deps);
3884 }
3885
3886 /**
3887 * A variant of the `useSelect` hook that has the same API, but is a compatible
3888 * Suspense-enabled data source.
3889 *
3890 * @template {MapSelect} T
3891 * @param {T} mapSelect Function called on every state change. The
3892 * returned value is exposed to the component
3893 * using this hook. The function receives the
3894 * `registry.suspendSelect` method as the first
3895 * argument and the `registry` as the second one.
3896 * @param {Array} deps A dependency array used to memoize the `mapSelect`
3897 * so that the same `mapSelect` is invoked on every
3898 * state change unless the dependencies change.
3899 *
3900 * @throws {Promise} A suspense Promise that is thrown if any of the called
3901 * selectors is in an unresolved state.
3902 *
3903 * @return {ReturnType<T>} Data object returned by the `mapSelect` function.
3904 */
3905 function useSuspenseSelect(mapSelect, deps) {
3906 return _useMappingSelect(true, mapSelect, deps);
3907 }
3908
3909 ;// external "ReactJSXRuntime"
3910 const external_ReactJSXRuntime_namespaceObject = window["ReactJSXRuntime"];
3911 ;// ./packages/data/build-module/components/with-select/index.js
3912 /**
3913 * WordPress dependencies
3914 */
3915
3916
3917 /**
3918 * Internal dependencies
3919 */
3920
3921
3922 /** @typedef {import('react').ComponentType} ComponentType */
3923
3924 /**
3925 * Higher-order component used to inject state-derived props using registered
3926 * selectors.
3927 *
3928 * @param {Function} mapSelectToProps Function called on every state change,
3929 * expected to return object of props to
3930 * merge with the component's own props.
3931 *
3932 * @example
3933 * ```js
3934 * import { withSelect } from '@wordpress/data';
3935 * import { store as myCustomStore } from 'my-custom-store';
3936 *
3937 * function PriceDisplay( { price, currency } ) {
3938 * return new Intl.NumberFormat( 'en-US', {
3939 * style: 'currency',
3940 * currency,
3941 * } ).format( price );
3942 * }
3943 *
3944 * const HammerPriceDisplay = withSelect( ( select, ownProps ) => {
3945 * const { getPrice } = select( myCustomStore );
3946 * const { currency } = ownProps;
3947 *
3948 * return {
3949 * price: getPrice( 'hammer', currency ),
3950 * };
3951 * } )( PriceDisplay );
3952 *
3953 * // Rendered in the application:
3954 * //
3955 * // <HammerPriceDisplay currency="USD" />
3956 * ```
3957 * In the above example, when `HammerPriceDisplay` is rendered into an
3958 * application, it will pass the price into the underlying `PriceDisplay`
3959 * component and update automatically if the price of a hammer ever changes in
3960 * the store.
3961 *
3962 * @return {ComponentType} Enhanced component with merged state data props.
3963 */
3964
3965 const withSelect = mapSelectToProps => (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(WrappedComponent => (0,external_wp_compose_namespaceObject.pure)(ownProps => {
3966 const mapSelect = (select, registry) => mapSelectToProps(select, ownProps, registry);
3967 const mergeProps = useSelect(mapSelect);
3968 return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(WrappedComponent, {
3969 ...ownProps,
3970 ...mergeProps
3971 });
3972 }), 'withSelect');
3973 /* harmony default export */ const with_select = (withSelect);
3974
3975 ;// ./packages/data/build-module/components/use-dispatch/use-dispatch-with-map.js
3976 /* wp:polyfill */
3977 /**
3978 * WordPress dependencies
3979 */
3980
3981
3982
3983 /**
3984 * Internal dependencies
3985 */
3986
3987
3988 /**
3989 * Custom react hook for returning aggregate dispatch actions using the provided
3990 * dispatchMap.
3991 *
3992 * Currently this is an internal api only and is implemented by `withDispatch`
3993 *
3994 * @param {Function} dispatchMap Receives the `registry.dispatch` function as
3995 * the first argument and the `registry` object
3996 * as the second argument. Should return an
3997 * object mapping props to functions.
3998 * @param {Array} deps An array of dependencies for the hook.
3999 * @return {Object} An object mapping props to functions created by the passed
4000 * in dispatchMap.
4001 */
4002 const useDispatchWithMap = (dispatchMap, deps) => {
4003 const registry = useRegistry();
4004 const currentDispatchMapRef = (0,external_wp_element_namespaceObject.useRef)(dispatchMap);
4005 (0,external_wp_compose_namespaceObject.useIsomorphicLayoutEffect)(() => {
4006 currentDispatchMapRef.current = dispatchMap;
4007 });
4008 return (0,external_wp_element_namespaceObject.useMemo)(() => {
4009 const currentDispatchProps = currentDispatchMapRef.current(registry.dispatch, registry);
4010 return Object.fromEntries(Object.entries(currentDispatchProps).map(([propName, dispatcher]) => {
4011 if (typeof dispatcher !== 'function') {
4012 // eslint-disable-next-line no-console
4013 console.warn(`Property ${propName} returned from dispatchMap in useDispatchWithMap must be a function.`);
4014 }
4015 return [propName, (...args) => currentDispatchMapRef.current(registry.dispatch, registry)[propName](...args)];
4016 }));
4017 }, [registry, ...deps]);
4018 };
4019 /* harmony default export */ const use_dispatch_with_map = (useDispatchWithMap);
4020
4021 ;// ./packages/data/build-module/components/with-dispatch/index.js
4022 /**
4023 * WordPress dependencies
4024 */
4025
4026
4027 /**
4028 * Internal dependencies
4029 */
4030
4031
4032 /** @typedef {import('react').ComponentType} ComponentType */
4033
4034 /**
4035 * Higher-order component used to add dispatch props using registered action
4036 * creators.
4037 *
4038 * @param {Function} mapDispatchToProps A function of returning an object of
4039 * prop names where value is a
4040 * dispatch-bound action creator, or a
4041 * function to be called with the
4042 * component's props and returning an
4043 * action creator.
4044 *
4045 * @example
4046 * ```jsx
4047 * function Button( { onClick, children } ) {
4048 * return <button type="button" onClick={ onClick }>{ children }</button>;
4049 * }
4050 *
4051 * import { withDispatch } from '@wordpress/data';
4052 * import { store as myCustomStore } from 'my-custom-store';
4053 *
4054 * const SaleButton = withDispatch( ( dispatch, ownProps ) => {
4055 * const { startSale } = dispatch( myCustomStore );
4056 * const { discountPercent } = ownProps;
4057 *
4058 * return {
4059 * onClick() {
4060 * startSale( discountPercent );
4061 * },
4062 * };
4063 * } )( Button );
4064 *
4065 * // Rendered in the application:
4066 * //
4067 * // <SaleButton discountPercent="20">Start Sale!</SaleButton>
4068 * ```
4069 *
4070 * @example
4071 * In the majority of cases, it will be sufficient to use only two first params
4072 * passed to `mapDispatchToProps` as illustrated in the previous example.
4073 * However, there might be some very advanced use cases where using the
4074 * `registry` object might be used as a tool to optimize the performance of
4075 * your component. Using `select` function from the registry might be useful
4076 * when you need to fetch some dynamic data from the store at the time when the
4077 * event is fired, but at the same time, you never use it to render your
4078 * component. In such scenario, you can avoid using the `withSelect` higher
4079 * order component to compute such prop, which might lead to unnecessary
4080 * re-renders of your component caused by its frequent value change.
4081 * Keep in mind, that `mapDispatchToProps` must return an object with functions
4082 * only.
4083 *
4084 * ```jsx
4085 * function Button( { onClick, children } ) {
4086 * return <button type="button" onClick={ onClick }>{ children }</button>;
4087 * }
4088 *
4089 * import { withDispatch } from '@wordpress/data';
4090 * import { store as myCustomStore } from 'my-custom-store';
4091 *
4092 * const SaleButton = withDispatch( ( dispatch, ownProps, { select } ) => {
4093 * // Stock number changes frequently.
4094 * const { getStockNumber } = select( myCustomStore );
4095 * const { startSale } = dispatch( myCustomStore );
4096 * return {
4097 * onClick() {
4098 * const discountPercent = getStockNumber() > 50 ? 10 : 20;
4099 * startSale( discountPercent );
4100 * },
4101 * };
4102 * } )( Button );
4103 *
4104 * // Rendered in the application:
4105 * //
4106 * // <SaleButton>Start Sale!</SaleButton>
4107 * ```
4108 *
4109 * _Note:_ It is important that the `mapDispatchToProps` function always
4110 * returns an object with the same keys. For example, it should not contain
4111 * conditions under which a different value would be returned.
4112 *
4113 * @return {ComponentType} Enhanced component with merged dispatcher props.
4114 */
4115
4116 const withDispatch = mapDispatchToProps => (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(WrappedComponent => ownProps => {
4117 const mapDispatch = (dispatch, registry) => mapDispatchToProps(dispatch, ownProps, registry);
4118 const dispatchProps = use_dispatch_with_map(mapDispatch, []);
4119 return /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(WrappedComponent, {
4120 ...ownProps,
4121 ...dispatchProps
4122 });
4123 }, 'withDispatch');
4124 /* harmony default export */ const with_dispatch = (withDispatch);
4125
4126 ;// ./packages/data/build-module/components/with-registry/index.js
4127 /**
4128 * WordPress dependencies
4129 */
4130
4131
4132 /**
4133 * Internal dependencies
4134 */
4135
4136
4137 /**
4138 * Higher-order component which renders the original component with the current
4139 * registry context passed as its `registry` prop.
4140 *
4141 * @param {Component} OriginalComponent Original component.
4142 *
4143 * @return {Component} Enhanced component.
4144 */
4145
4146 const withRegistry = (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(OriginalComponent => props => /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(RegistryConsumer, {
4147 children: registry => /*#__PURE__*/(0,external_ReactJSXRuntime_namespaceObject.jsx)(OriginalComponent, {
4148 ...props,
4149 registry: registry
4150 })
4151 }), 'withRegistry');
4152 /* harmony default export */ const with_registry = (withRegistry);
4153
4154 ;// ./packages/data/build-module/components/use-dispatch/use-dispatch.js
4155 /**
4156 * Internal dependencies
4157 */
4158
4159
4160 /**
4161 * @typedef {import('../../types').StoreDescriptor<StoreConfig>} StoreDescriptor
4162 * @template {import('../../types').AnyConfig} StoreConfig
4163 */
4164 /**
4165 * @typedef {import('../../types').UseDispatchReturn<StoreNameOrDescriptor>} UseDispatchReturn
4166 * @template StoreNameOrDescriptor
4167 */
4168
4169 /**
4170 * A custom react hook returning the current registry dispatch actions creators.
4171 *
4172 * Note: The component using this hook must be within the context of a
4173 * RegistryProvider.
4174 *
4175 * @template {undefined | string | StoreDescriptor<any>} StoreNameOrDescriptor
4176 * @param {StoreNameOrDescriptor} [storeNameOrDescriptor] Optionally provide the name of the
4177 * store or its descriptor from which to
4178 * retrieve action creators. If not
4179 * provided, the registry.dispatch
4180 * function is returned instead.
4181 *
4182 * @example
4183 * This illustrates a pattern where you may need to retrieve dynamic data from
4184 * the server via the `useSelect` hook to use in combination with the dispatch
4185 * action.
4186 *
4187 * ```jsx
4188 * import { useCallback } from 'react';
4189 * import { useDispatch, useSelect } from '@wordpress/data';
4190 * import { store as myCustomStore } from 'my-custom-store';
4191 *
4192 * function Button( { onClick, children } ) {
4193 * return <button type="button" onClick={ onClick }>{ children }</button>
4194 * }
4195 *
4196 * const SaleButton = ( { children } ) => {
4197 * const { stockNumber } = useSelect(
4198 * ( select ) => select( myCustomStore ).getStockNumber(),
4199 * []
4200 * );
4201 * const { startSale } = useDispatch( myCustomStore );
4202 * const onClick = useCallback( () => {
4203 * const discountPercent = stockNumber > 50 ? 10: 20;
4204 * startSale( discountPercent );
4205 * }, [ stockNumber ] );
4206 * return <Button onClick={ onClick }>{ children }</Button>
4207 * }
4208 *
4209 * // Rendered somewhere in the application:
4210 * //
4211 * // <SaleButton>Start Sale!</SaleButton>
4212 * ```
4213 * @return {UseDispatchReturn<StoreNameOrDescriptor>} A custom react hook.
4214 */
4215 const useDispatch = storeNameOrDescriptor => {
4216 const {
4217 dispatch
4218 } = useRegistry();
4219 return storeNameOrDescriptor === void 0 ? dispatch : dispatch(storeNameOrDescriptor);
4220 };
4221 /* harmony default export */ const use_dispatch = (useDispatch);
4222
4223 ;// ./packages/data/build-module/dispatch.js
4224 /**
4225 * Internal dependencies
4226 */
4227
4228
4229
4230 /**
4231 * Given a store descriptor, returns an object of the store's action creators.
4232 * Calling an action creator will cause it to be dispatched, updating the state value accordingly.
4233 *
4234 * Note: Action creators returned by the dispatch will return a promise when
4235 * they are called.
4236 *
4237 * @param storeNameOrDescriptor The store descriptor. The legacy calling convention of passing
4238 * the store name is also supported.
4239 *
4240 * @example
4241 * ```js
4242 * import { dispatch } from '@wordpress/data';
4243 * import { store as myCustomStore } from 'my-custom-store';
4244 *
4245 * dispatch( myCustomStore ).setPrice( 'hammer', 9.75 );
4246 * ```
4247 * @return Object containing the action creators.
4248 */
4249 function dispatch_dispatch(storeNameOrDescriptor) {
4250 return default_registry.dispatch(storeNameOrDescriptor);
4251 }
4252
4253 ;// ./packages/data/build-module/select.js
4254 /**
4255 * Internal dependencies
4256 */
4257
4258
4259
4260 /**
4261 * Given a store descriptor, returns an object of the store's selectors.
4262 * The selector functions are been pre-bound to pass the current state automatically.
4263 * As a consumer, you need only pass arguments of the selector, if applicable.
4264 *
4265 *
4266 * @param storeNameOrDescriptor The store descriptor. The legacy calling convention
4267 * of passing the store name is also supported.
4268 *
4269 * @example
4270 * ```js
4271 * import { select } from '@wordpress/data';
4272 * import { store as myCustomStore } from 'my-custom-store';
4273 *
4274 * select( myCustomStore ).getPrice( 'hammer' );
4275 * ```
4276 *
4277 * @return Object containing the store's selectors.
4278 */
4279 function select_select(storeNameOrDescriptor) {
4280 return default_registry.select(storeNameOrDescriptor);
4281 }
4282
4283 ;// ./packages/data/build-module/index.js
4284 /**
4285 * Internal dependencies
4286 */
4287
4288
4289
4290
4291 /** @typedef {import('./types').StoreDescriptor} StoreDescriptor */
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308 /**
4309 * Object of available plugins to use with a registry.
4310 *
4311 * @see [use](#use)
4312 *
4313 * @type {Object}
4314 */
4315
4316
4317 /**
4318 * The combineReducers helper function turns an object whose values are different
4319 * reducing functions into a single reducing function you can pass to registerReducer.
4320 *
4321 * @type {import('./types').combineReducers}
4322 * @param {Object} reducers An object whose values correspond to different reducing
4323 * functions that need to be combined into one.
4324 *
4325 * @example
4326 * ```js
4327 * import { combineReducers, createReduxStore, register } from '@wordpress/data';
4328 *
4329 * const prices = ( state = {}, action ) => {
4330 * return action.type === 'SET_PRICE' ?
4331 * {
4332 * ...state,
4333 * [ action.item ]: action.price,
4334 * } :
4335 * state;
4336 * };
4337 *
4338 * const discountPercent = ( state = 0, action ) => {
4339 * return action.type === 'START_SALE' ?
4340 * action.discountPercent :
4341 * state;
4342 * };
4343 *
4344 * const store = createReduxStore( 'my-shop', {
4345 * reducer: combineReducers( {
4346 * prices,
4347 * discountPercent,
4348 * } ),
4349 * } );
4350 * register( store );
4351 * ```
4352 *
4353 * @return {Function} A reducer that invokes every reducer inside the reducers
4354 * object, and constructs a state object with the same shape.
4355 */
4356 const build_module_combineReducers = combine_reducers_combineReducers;
4357
4358 /**
4359 * Given a store descriptor, returns an object containing the store's selectors pre-bound to state
4360 * so that you only need to supply additional arguments, and modified so that they return promises
4361 * that resolve to their eventual values, after any resolvers have ran.
4362 *
4363 * @param {StoreDescriptor|string} storeNameOrDescriptor The store descriptor. The legacy calling
4364 * convention of passing the store name is
4365 * also supported.
4366 *
4367 * @example
4368 * ```js
4369 * import { resolveSelect } from '@wordpress/data';
4370 * import { store as myCustomStore } from 'my-custom-store';
4371 *
4372 * resolveSelect( myCustomStore ).getPrice( 'hammer' ).then(console.log)
4373 * ```
4374 *
4375 * @return {Object} Object containing the store's promise-wrapped selectors.
4376 */
4377 const build_module_resolveSelect = default_registry.resolveSelect;
4378
4379 /**
4380 * Given a store descriptor, returns an object containing the store's selectors pre-bound to state
4381 * so that you only need to supply additional arguments, and modified so that they throw promises
4382 * in case the selector is not resolved yet.
4383 *
4384 * @param {StoreDescriptor|string} storeNameOrDescriptor The store descriptor. The legacy calling
4385 * convention of passing the store name is
4386 * also supported.
4387 *
4388 * @return {Object} Object containing the store's suspense-wrapped selectors.
4389 */
4390 const suspendSelect = default_registry.suspendSelect;
4391
4392 /**
4393 * Given a listener function, the function will be called any time the state value
4394 * of one of the registered stores has changed. If you specify the optional
4395 * `storeNameOrDescriptor` parameter, the listener function will be called only
4396 * on updates on that one specific registered store.
4397 *
4398 * This function returns an `unsubscribe` function used to stop the subscription.
4399 *
4400 * @param {Function} listener Callback function.
4401 * @param {string|StoreDescriptor?} storeNameOrDescriptor Optional store name.
4402 *
4403 * @example
4404 * ```js
4405 * import { subscribe } from '@wordpress/data';
4406 *
4407 * const unsubscribe = subscribe( () => {
4408 * // You could use this opportunity to test whether the derived result of a
4409 * // selector has subsequently changed as the result of a state update.
4410 * } );
4411 *
4412 * // Later, if necessary...
4413 * unsubscribe();
4414 * ```
4415 */
4416 const subscribe = default_registry.subscribe;
4417
4418 /**
4419 * Registers a generic store instance.
4420 *
4421 * @deprecated Use `register( storeDescriptor )` instead.
4422 *
4423 * @param {string} name Store registry name.
4424 * @param {Object} store Store instance (`{ getSelectors, getActions, subscribe }`).
4425 */
4426 const registerGenericStore = default_registry.registerGenericStore;
4427
4428 /**
4429 * Registers a standard `@wordpress/data` store.
4430 *
4431 * @deprecated Use `register` instead.
4432 *
4433 * @param {string} storeName Unique namespace identifier for the store.
4434 * @param {Object} options Store description (reducer, actions, selectors, resolvers).
4435 *
4436 * @return {Object} Registered store object.
4437 */
4438 const registerStore = default_registry.registerStore;
4439
4440 /**
4441 * Extends a registry to inherit functionality provided by a given plugin. A
4442 * plugin is an object with properties aligning to that of a registry, merged
4443 * to extend the default registry behavior.
4444 *
4445 * @param {Object} plugin Plugin object.
4446 */
4447 const use = default_registry.use;
4448
4449 /**
4450 * Registers a standard `@wordpress/data` store descriptor.
4451 *
4452 * @example
4453 * ```js
4454 * import { createReduxStore, register } from '@wordpress/data';
4455 *
4456 * const store = createReduxStore( 'demo', {
4457 * reducer: ( state = 'OK' ) => state,
4458 * selectors: {
4459 * getValue: ( state ) => state,
4460 * },
4461 * } );
4462 * register( store );
4463 * ```
4464 *
4465 * @param {StoreDescriptor} store Store descriptor.
4466 */
4467 const register = default_registry.register;
4468
4469 (window.wp = window.wp || {}).data = __webpack_exports__;
4470 /******/ })()
4471 ;