PluginProbe
Gutenberg / 16.2.0
Gutenberg v16.2.0
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 16.2.0, at build/data/index.js

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