PluginProbe
Gutenberg / 19.6.4
Gutenberg v19.6.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 19.6.4, at build/data/index.js

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