PluginProbe
Gutenberg / 14.7.3
Gutenberg v14.7.3
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 14.7.3, at build/data/index.js

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