PluginProbe
Gutenberg / 17.2.4
Gutenberg v17.2.4
24.0.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 All 403 releases
gutenberg / build / data / index.js

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

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