PluginProbe
Gutenberg / 13.5.2
Gutenberg v13.5.2
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 13.5.2, at build/data/index.js

4,433 lines 137.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 /******/ (() => { // webpackBootstrap
2 /******/ var __webpack_modules__ = ({
3
4 /***/ 2167:
5 /***/ ((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 /***/ ((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 /******/ (() => {
407 /******/ // getDefaultExport function for compatibility with non-harmony modules
408 /******/ __webpack_require__.n = (module) => {
409 /******/ var getter = module && module.__esModule ?
410 /******/ () => (module['default']) :
411 /******/ () => (module);
412 /******/ __webpack_require__.d(getter, { a: getter });
413 /******/ return getter;
414 /******/ };
415 /******/ })();
416 /******/
417 /******/ /* webpack/runtime/define property getters */
418 /******/ (() => {
419 /******/ // define getter functions for harmony exports
420 /******/ __webpack_require__.d = (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 /******/ (() => {
431 /******/ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
432 /******/ })();
433 /******/
434 /******/ /* webpack/runtime/make namespace object */
435 /******/ (() => {
436 /******/ // define __esModule on exports
437 /******/ __webpack_require__.r = (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 (() => {
449 "use strict";
450 // ESM COMPAT FLAG
451 __webpack_require__.r(__webpack_exports__);
452
453 // EXPORTS
454 __webpack_require__.d(__webpack_exports__, {
455 "AsyncModeProvider": () => (/* reexport */ async_mode_provider_context),
456 "RegistryConsumer": () => (/* reexport */ RegistryConsumer),
457 "RegistryProvider": () => (/* reexport */ context),
458 "combineReducers": () => (/* reexport */ (turbo_combine_reducers_default())),
459 "controls": () => (/* reexport */ controls),
460 "createReduxStore": () => (/* reexport */ createReduxStore),
461 "createRegistry": () => (/* reexport */ createRegistry),
462 "createRegistryControl": () => (/* reexport */ createRegistryControl),
463 "createRegistrySelector": () => (/* reexport */ createRegistrySelector),
464 "dispatch": () => (/* binding */ build_module_dispatch),
465 "plugins": () => (/* reexport */ plugins_namespaceObject),
466 "register": () => (/* binding */ register),
467 "registerGenericStore": () => (/* binding */ registerGenericStore),
468 "registerStore": () => (/* binding */ registerStore),
469 "resolveSelect": () => (/* binding */ build_module_resolveSelect),
470 "select": () => (/* binding */ build_module_select),
471 "subscribe": () => (/* binding */ subscribe),
472 "suspendSelect": () => (/* binding */ suspendSelect),
473 "use": () => (/* binding */ use),
474 "useDispatch": () => (/* reexport */ use_dispatch),
475 "useRegistry": () => (/* reexport */ useRegistry),
476 "useSelect": () => (/* reexport */ useSelect),
477 "useSuspenseSelect": () => (/* reexport */ useSuspenseSelect),
478 "withDispatch": () => (/* reexport */ with_dispatch),
479 "withRegistry": () => (/* reexport */ with_registry),
480 "withSelect": () => (/* 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": () => (getCachedResolvers),
488 "getIsResolving": () => (getIsResolving),
489 "getResolutionError": () => (getResolutionError),
490 "getResolutionState": () => (getResolutionState),
491 "hasFinishedResolution": () => (hasFinishedResolution),
492 "hasResolutionFailed": () => (hasResolutionFailed),
493 "hasStartedResolution": () => (hasStartedResolution),
494 "isResolving": () => (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": () => (failResolution),
502 "failResolutions": () => (failResolutions),
503 "finishResolution": () => (finishResolution),
504 "finishResolutions": () => (finishResolutions),
505 "invalidateResolution": () => (invalidateResolution),
506 "invalidateResolutionForStore": () => (invalidateResolutionForStore),
507 "invalidateResolutionForStoreSelector": () => (invalidateResolutionForStoreSelector),
508 "startResolution": () => (startResolution),
509 "startResolutions": () => (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": () => (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 const external_lodash_namespaceObject = window["lodash"];
524 ;// CONCATENATED MODULE: external ["wp","deprecated"]
525 const 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 const external_wp_reduxRoutine_namespaceObject = window["wp"]["reduxRoutine"];
1257 var external_wp_reduxRoutine_default = /*#__PURE__*/__webpack_require__.n(external_wp_reduxRoutine_namespaceObject);
1258 ;// CONCATENATED MODULE: ./packages/data/build-module/factory.js
1259 /**
1260 * Creates a selector function that takes additional curried argument with the
1261 * registry `select` function. While a regular selector has signature
1262 * ```js
1263 * ( state, ...selectorArgs ) => ( result )
1264 * ```
1265 * that allows to select data from the store's `state`, a registry selector
1266 * has signature:
1267 * ```js
1268 * ( select ) => ( state, ...selectorArgs ) => ( result )
1269 * ```
1270 * that supports also selecting from other registered stores.
1271 *
1272 * @example
1273 * ```js
1274 * const getCurrentPostId = createRegistrySelector( ( select ) => ( state ) => {
1275 * return select( 'core/editor' ).getCurrentPostId();
1276 * } );
1277 *
1278 * const getPostEdits = createRegistrySelector( ( select ) => ( state ) => {
1279 * // calling another registry selector just like any other function
1280 * const postType = getCurrentPostType( state );
1281 * const postId = getCurrentPostId( state );
1282 * return select( 'core' ).getEntityRecordEdits( 'postType', postType, postId );
1283 * } );
1284 * ```
1285 *
1286 * Note how the `getCurrentPostId` selector can be called just like any other function,
1287 * (it works even inside a regular non-registry selector) and we don't need to pass the
1288 * registry as argument. The registry binding happens automatically when registering the selector
1289 * with a store.
1290 *
1291 * @param {Function} registrySelector Function receiving a registry `select`
1292 * function and returning a state selector.
1293 *
1294 * @return {Function} Registry selector that can be registered with a store.
1295 */
1296 function createRegistrySelector(registrySelector) {
1297 // Create a selector function that is bound to the registry referenced by `selector.registry`
1298 // and that has the same API as a regular selector. Binding it in such a way makes it
1299 // possible to call the selector directly from another selector.
1300 const selector = function () {
1301 return registrySelector(selector.registry.select)(...arguments);
1302 };
1303 /**
1304 * Flag indicating that the selector is a registry selector that needs the correct registry
1305 * reference to be assigned to `selecto.registry` to make it work correctly.
1306 * be mapped as a registry selector.
1307 *
1308 * @type {boolean}
1309 */
1310
1311
1312 selector.isRegistrySelector = true;
1313 return selector;
1314 }
1315 /**
1316 * Creates a control function that takes additional curried argument with the `registry` object.
1317 * While a regular control has signature
1318 * ```js
1319 * ( action ) => ( iteratorOrPromise )
1320 * ```
1321 * where the control works with the `action` that it's bound to, a registry control has signature:
1322 * ```js
1323 * ( registry ) => ( action ) => ( iteratorOrPromise )
1324 * ```
1325 * A registry control is typically used to select data or dispatch an action to a registered
1326 * store.
1327 *
1328 * When registering a control created with `createRegistryControl` with a store, the store
1329 * knows which calling convention to use when executing the control.
1330 *
1331 * @param {Function} registryControl Function receiving a registry object and returning a control.
1332 *
1333 * @return {Function} Registry control that can be registered with a store.
1334 */
1335
1336 function createRegistryControl(registryControl) {
1337 registryControl.isRegistryControl = true;
1338 return registryControl;
1339 }
1340
1341 ;// CONCATENATED MODULE: ./packages/data/build-module/controls.js
1342 /**
1343 * External dependencies
1344 */
1345
1346 /**
1347 * Internal dependencies
1348 */
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 * Dispatches a control action for triggering a synchronous registry select.
1358 *
1359 * Note: This control synchronously returns the current selector value, triggering the
1360 * resolution, but not waiting for it.
1361 *
1362 * @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
1363 * @param {string} selectorName The name of the selector.
1364 * @param {Array} args Arguments for the selector.
1365 *
1366 * @example
1367 * ```js
1368 * import { controls } from '@wordpress/data';
1369 *
1370 * // Action generator using `select`.
1371 * export function* myAction() {
1372 * const isEditorSideBarOpened = yield controls.select( 'core/edit-post', 'isEditorSideBarOpened' );
1373 * // Do stuff with the result from the `select`.
1374 * }
1375 * ```
1376 *
1377 * @return {Object} The control descriptor.
1378 */
1379
1380 function controls_select(storeNameOrDescriptor, selectorName) {
1381 for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
1382 args[_key - 2] = arguments[_key];
1383 }
1384
1385 return {
1386 type: SELECT,
1387 storeKey: (0,external_lodash_namespaceObject.isObject)(storeNameOrDescriptor) ? storeNameOrDescriptor.name : storeNameOrDescriptor,
1388 selectorName,
1389 args
1390 };
1391 }
1392 /**
1393 * Dispatches a control action for triggering and resolving a registry select.
1394 *
1395 * Note: when this control action is handled, it automatically considers
1396 * selectors that may have a resolver. In such case, it will return a `Promise` that resolves
1397 * after the selector finishes resolving, with the final result value.
1398 *
1399 * @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
1400 * @param {string} selectorName The name of the selector
1401 * @param {Array} args Arguments for the selector.
1402 *
1403 * @example
1404 * ```js
1405 * import { controls } from '@wordpress/data';
1406 *
1407 * // Action generator using resolveSelect
1408 * export function* myAction() {
1409 * const isSidebarOpened = yield controls.resolveSelect( 'core/edit-post', 'isEditorSideBarOpened' );
1410 * // do stuff with the result from the select.
1411 * }
1412 * ```
1413 *
1414 * @return {Object} The control descriptor.
1415 */
1416
1417
1418 function resolveSelect(storeNameOrDescriptor, selectorName) {
1419 for (var _len2 = arguments.length, args = new Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) {
1420 args[_key2 - 2] = arguments[_key2];
1421 }
1422
1423 return {
1424 type: RESOLVE_SELECT,
1425 storeKey: (0,external_lodash_namespaceObject.isObject)(storeNameOrDescriptor) ? storeNameOrDescriptor.name : storeNameOrDescriptor,
1426 selectorName,
1427 args
1428 };
1429 }
1430 /**
1431 * Dispatches a control action for triggering a registry dispatch.
1432 *
1433 * @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
1434 * @param {string} actionName The name of the action to dispatch
1435 * @param {Array} args Arguments for the dispatch action.
1436 *
1437 * @example
1438 * ```js
1439 * import { controls } from '@wordpress/data-controls';
1440 *
1441 * // Action generator using dispatch
1442 * export function* myAction() {
1443 * yield controls.dispatch( 'core/edit-post', 'togglePublishSidebar' );
1444 * // do some other things.
1445 * }
1446 * ```
1447 *
1448 * @return {Object} The control descriptor.
1449 */
1450
1451
1452 function dispatch(storeNameOrDescriptor, actionName) {
1453 for (var _len3 = arguments.length, args = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
1454 args[_key3 - 2] = arguments[_key3];
1455 }
1456
1457 return {
1458 type: DISPATCH,
1459 storeKey: (0,external_lodash_namespaceObject.isObject)(storeNameOrDescriptor) ? storeNameOrDescriptor.name : storeNameOrDescriptor,
1460 actionName,
1461 args
1462 };
1463 }
1464
1465 const controls = {
1466 select: controls_select,
1467 resolveSelect,
1468 dispatch
1469 };
1470 const builtinControls = {
1471 [SELECT]: createRegistryControl(registry => _ref => {
1472 let {
1473 storeKey,
1474 selectorName,
1475 args
1476 } = _ref;
1477 return registry.select(storeKey)[selectorName](...args);
1478 }),
1479 [RESOLVE_SELECT]: createRegistryControl(registry => _ref2 => {
1480 let {
1481 storeKey,
1482 selectorName,
1483 args
1484 } = _ref2;
1485 const method = registry.select(storeKey)[selectorName].hasResolver ? 'resolveSelect' : 'select';
1486 return registry[method](storeKey)[selectorName](...args);
1487 }),
1488 [DISPATCH]: createRegistryControl(registry => _ref3 => {
1489 let {
1490 storeKey,
1491 actionName,
1492 args
1493 } = _ref3;
1494 return registry.dispatch(storeKey)[actionName](...args);
1495 })
1496 };
1497
1498 ;// CONCATENATED MODULE: ./node_modules/is-promise/index.mjs
1499 function isPromise(obj) {
1500 return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';
1501 }
1502
1503 ;// CONCATENATED MODULE: ./packages/data/build-module/promise-middleware.js
1504 /**
1505 * External dependencies
1506 */
1507
1508 /**
1509 * Simplest possible promise redux middleware.
1510 *
1511 * @type {import('redux').Middleware}
1512 */
1513
1514 const promiseMiddleware = () => next => action => {
1515 if (isPromise(action)) {
1516 return action.then(resolvedAction => {
1517 if (resolvedAction) {
1518 return next(resolvedAction);
1519 }
1520 });
1521 }
1522
1523 return next(action);
1524 };
1525
1526 /* harmony default export */ const promise_middleware = (promiseMiddleware);
1527
1528 ;// CONCATENATED MODULE: ./packages/data/build-module/store/index.js
1529 const coreDataStore = {
1530 name: 'core/data',
1531
1532 instantiate(registry) {
1533 const getCoreDataSelector = selectorName => function (key) {
1534 for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
1535 args[_key - 1] = arguments[_key];
1536 }
1537
1538 return registry.select(key)[selectorName](...args);
1539 };
1540
1541 const getCoreDataAction = actionName => function (key) {
1542 for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
1543 args[_key2 - 1] = arguments[_key2];
1544 }
1545
1546 return registry.dispatch(key)[actionName](...args);
1547 };
1548
1549 return {
1550 getSelectors() {
1551 return Object.fromEntries(['getIsResolving', 'hasStartedResolution', 'hasFinishedResolution', 'isResolving', 'getCachedResolvers'].map(selectorName => [selectorName, getCoreDataSelector(selectorName)]));
1552 },
1553
1554 getActions() {
1555 return Object.fromEntries(['startResolution', 'finishResolution', 'invalidateResolution', 'invalidateResolutionForStore', 'invalidateResolutionForStoreSelector'].map(actionName => [actionName, getCoreDataAction(actionName)]));
1556 },
1557
1558 subscribe() {
1559 // There's no reasons to trigger any listener when we subscribe to this store
1560 // because there's no state stored in this store that need to retrigger selectors
1561 // if a change happens, the corresponding store where the tracking stated live
1562 // would have already triggered a "subscribe" call.
1563 return () => () => {};
1564 }
1565
1566 };
1567 }
1568
1569 };
1570 /* harmony default export */ const store = (coreDataStore);
1571
1572 ;// CONCATENATED MODULE: ./packages/data/build-module/resolvers-cache-middleware.js
1573 /**
1574 * External dependencies
1575 */
1576
1577 /**
1578 * Internal dependencies
1579 */
1580
1581
1582 /** @typedef {import('./registry').WPDataRegistry} WPDataRegistry */
1583
1584 /**
1585 * Creates a middleware handling resolvers cache invalidation.
1586 *
1587 * @param {WPDataRegistry} registry The registry reference for which to create
1588 * the middleware.
1589 * @param {string} reducerKey The namespace for which to create the
1590 * middleware.
1591 *
1592 * @return {Function} Middleware function.
1593 */
1594
1595 const createResolversCacheMiddleware = (registry, reducerKey) => () => next => action => {
1596 const resolvers = registry.select(store).getCachedResolvers(reducerKey);
1597 Object.entries(resolvers).forEach(_ref => {
1598 let [selectorName, resolversByArgs] = _ref;
1599 const resolver = (0,external_lodash_namespaceObject.get)(registry.stores, [reducerKey, 'resolvers', selectorName]);
1600
1601 if (!resolver || !resolver.shouldInvalidate) {
1602 return;
1603 }
1604
1605 resolversByArgs.forEach((value, args) => {
1606 // resolversByArgs is the map Map([ args ] => boolean) storing the cache resolution status for a given selector.
1607 // If the value is "finished" or "error" it means this resolver has finished its resolution which means we need
1608 // to invalidate it, if it's true it means it's inflight and the invalidation is not necessary.
1609 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)) {
1610 return;
1611 } // Trigger cache invalidation
1612
1613
1614 registry.dispatch(store).invalidateResolution(reducerKey, selectorName, args);
1615 });
1616 });
1617 return next(action);
1618 };
1619
1620 /* harmony default export */ const resolvers_cache_middleware = (createResolversCacheMiddleware);
1621
1622 ;// CONCATENATED MODULE: ./packages/data/build-module/redux-store/thunk-middleware.js
1623 function createThunkMiddleware(args) {
1624 return () => next => action => {
1625 if (typeof action === 'function') {
1626 return action(args);
1627 }
1628
1629 return next(action);
1630 };
1631 }
1632
1633 ;// CONCATENATED MODULE: ./packages/data/build-module/redux-store/metadata/utils.js
1634 /**
1635 * External dependencies
1636 */
1637
1638 /**
1639 * Higher-order reducer creator which creates a combined reducer object, keyed
1640 * by a property on the action object.
1641 *
1642 * @param actionProperty Action property by which to key object.
1643 * @return Higher-order reducer.
1644 */
1645 const onSubKey = actionProperty => reducer => function () {
1646 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1647 let action = arguments.length > 1 ? arguments[1] : undefined;
1648 // Retrieve subkey from action. Do not track if undefined; useful for cases
1649 // where reducer is scoped by action shape.
1650 const key = action[actionProperty];
1651
1652 if (key === undefined) {
1653 return state;
1654 } // Avoid updating state if unchanged. Note that this also accounts for a
1655 // reducer which returns undefined on a key which is not yet tracked.
1656
1657
1658 const nextKeyState = reducer(state[key], action);
1659
1660 if (nextKeyState === state[key]) {
1661 return state;
1662 }
1663
1664 return { ...state,
1665 [key]: nextKeyState
1666 };
1667 };
1668 /**
1669 * Normalize selector argument array by defaulting `undefined` value to an empty array
1670 * and removing trailing `undefined` values.
1671 *
1672 * @param args Selector argument array
1673 * @return Normalized state key array
1674 */
1675
1676 function selectorArgsToStateKey(args) {
1677 if (args === undefined || args === null) {
1678 return [];
1679 }
1680
1681 const len = args.length;
1682 let idx = len;
1683
1684 while (idx > 0 && args[idx - 1] === undefined) {
1685 idx--;
1686 }
1687
1688 return idx === len ? args : args.slice(0, idx);
1689 }
1690
1691 ;// CONCATENATED MODULE: ./packages/data/build-module/redux-store/metadata/reducer.js
1692 /**
1693 * External dependencies
1694 */
1695
1696
1697
1698 /**
1699 * Internal dependencies
1700 */
1701
1702
1703 /**
1704 * Reducer function returning next state for selector resolution of
1705 * subkeys, object form:
1706 *
1707 * selectorName -> EquivalentKeyMap<Array,boolean>
1708 */
1709 const subKeysIsResolved = onSubKey('selectorName')(function () {
1710 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : new (equivalent_key_map_default())();
1711 let action = arguments.length > 1 ? arguments[1] : undefined;
1712
1713 switch (action.type) {
1714 case 'START_RESOLUTION':
1715 {
1716 const nextState = new (equivalent_key_map_default())(state);
1717 nextState.set(selectorArgsToStateKey(action.args), {
1718 status: 'resolving'
1719 });
1720 return nextState;
1721 }
1722
1723 case 'FINISH_RESOLUTION':
1724 {
1725 const nextState = new (equivalent_key_map_default())(state);
1726 nextState.set(selectorArgsToStateKey(action.args), {
1727 status: 'finished'
1728 });
1729 return nextState;
1730 }
1731
1732 case 'FAIL_RESOLUTION':
1733 {
1734 const nextState = new (equivalent_key_map_default())(state);
1735 nextState.set(selectorArgsToStateKey(action.args), {
1736 status: 'error',
1737 error: action.error
1738 });
1739 return nextState;
1740 }
1741
1742 case 'START_RESOLUTIONS':
1743 {
1744 const nextState = new (equivalent_key_map_default())(state);
1745
1746 for (const resolutionArgs of action.args) {
1747 nextState.set(selectorArgsToStateKey(resolutionArgs), {
1748 status: 'resolving'
1749 });
1750 }
1751
1752 return nextState;
1753 }
1754
1755 case 'FINISH_RESOLUTIONS':
1756 {
1757 const nextState = new (equivalent_key_map_default())(state);
1758
1759 for (const resolutionArgs of action.args) {
1760 nextState.set(selectorArgsToStateKey(resolutionArgs), {
1761 status: 'finished'
1762 });
1763 }
1764
1765 return nextState;
1766 }
1767
1768 case 'FAIL_RESOLUTIONS':
1769 {
1770 const nextState = new (equivalent_key_map_default())(state);
1771 action.args.forEach((resolutionArgs, idx) => {
1772 const resolutionState = {
1773 status: 'error',
1774 error: undefined
1775 };
1776 const error = action.errors[idx];
1777
1778 if (error) {
1779 resolutionState.error = error;
1780 }
1781
1782 nextState.set(selectorArgsToStateKey(resolutionArgs), resolutionState);
1783 });
1784 return nextState;
1785 }
1786
1787 case 'INVALIDATE_RESOLUTION':
1788 {
1789 const nextState = new (equivalent_key_map_default())(state);
1790 nextState.delete(selectorArgsToStateKey(action.args));
1791 return nextState;
1792 }
1793 }
1794
1795 return state;
1796 });
1797 /**
1798 * Reducer function returning next state for selector resolution, object form:
1799 *
1800 * selectorName -> EquivalentKeyMap<Array, boolean>
1801 *
1802 * @param state Current state.
1803 * @param action Dispatched action.
1804 *
1805 * @return Next state.
1806 */
1807
1808 const isResolved = function () {
1809 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1810 let action = arguments.length > 1 ? arguments[1] : undefined;
1811
1812 switch (action.type) {
1813 case 'INVALIDATE_RESOLUTION_FOR_STORE':
1814 return {};
1815
1816 case 'INVALIDATE_RESOLUTION_FOR_STORE_SELECTOR':
1817 return (0,external_lodash_namespaceObject.has)(state, [action.selectorName]) ? (0,external_lodash_namespaceObject.omit)(state, [action.selectorName]) : state;
1818
1819 case 'START_RESOLUTION':
1820 case 'FINISH_RESOLUTION':
1821 case 'FAIL_RESOLUTION':
1822 case 'START_RESOLUTIONS':
1823 case 'FINISH_RESOLUTIONS':
1824 case 'FAIL_RESOLUTIONS':
1825 case 'INVALIDATE_RESOLUTION':
1826 return subKeysIsResolved(state, action);
1827 }
1828
1829 return state;
1830 };
1831
1832 /* harmony default export */ const metadata_reducer = (isResolved);
1833
1834 ;// CONCATENATED MODULE: ./packages/data/build-module/redux-store/metadata/selectors.js
1835 /**
1836 * External dependencies
1837 */
1838
1839 /**
1840 * Internal dependencies
1841 */
1842
1843
1844 /** @typedef {Record<string, import('./reducer').State>} State */
1845
1846 /** @typedef {import('./reducer').StateValue} StateValue */
1847
1848 /** @typedef {import('./reducer').Status} Status */
1849
1850 /**
1851 * Returns the raw resolution state value for a given selector name,
1852 * and arguments set. May be undefined if the selector has never been resolved
1853 * or not resolved for the given set of arguments, otherwise true or false for
1854 * resolution started and completed respectively.
1855 *
1856 * @param {State} state Data state.
1857 * @param {string} selectorName Selector name.
1858 * @param {unknown[]?} args Arguments passed to selector.
1859 *
1860 * @return {StateValue|undefined} isResolving value.
1861 */
1862
1863 function getResolutionState(state, selectorName, args) {
1864 const map = (0,external_lodash_namespaceObject.get)(state, [selectorName]);
1865
1866 if (!map) {
1867 return;
1868 }
1869
1870 return map.get(selectorArgsToStateKey(args));
1871 }
1872 /**
1873 * Returns the raw `isResolving` value for a given selector name,
1874 * and arguments set. May be undefined if the selector has never been resolved
1875 * or not resolved for the given set of arguments, otherwise true or false for
1876 * resolution started and completed respectively.
1877 *
1878 * @param {State} state Data state.
1879 * @param {string} selectorName Selector name.
1880 * @param {unknown[]?} args Arguments passed to selector.
1881 *
1882 * @return {boolean | undefined} isResolving value.
1883 */
1884
1885 function getIsResolving(state, selectorName, args) {
1886 const resolutionState = getResolutionState(state, selectorName, args);
1887 return resolutionState && resolutionState.status === 'resolving';
1888 }
1889 /**
1890 * Returns true if resolution has already been triggered for a given
1891 * selector name, and arguments set.
1892 *
1893 * @param {State} state Data state.
1894 * @param {string} selectorName Selector name.
1895 * @param {unknown[]?} args Arguments passed to selector.
1896 *
1897 * @return {boolean} Whether resolution has been triggered.
1898 */
1899
1900 function hasStartedResolution(state, selectorName, args) {
1901 return getResolutionState(state, selectorName, args) !== undefined;
1902 }
1903 /**
1904 * Returns true if resolution has completed for a given selector
1905 * 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 completed.
1912 */
1913
1914 function hasFinishedResolution(state, selectorName, args) {
1915 var _getResolutionState;
1916
1917 const status = (_getResolutionState = getResolutionState(state, selectorName, args)) === null || _getResolutionState === void 0 ? void 0 : _getResolutionState.status;
1918 return status === 'finished' || status === 'error';
1919 }
1920 /**
1921 * Returns true if resolution has failed for a given selector
1922 * name, and arguments set.
1923 *
1924 * @param {State} state Data state.
1925 * @param {string} selectorName Selector name.
1926 * @param {unknown[]?} args Arguments passed to selector.
1927 *
1928 * @return {boolean} Has resolution failed
1929 */
1930
1931 function hasResolutionFailed(state, selectorName, args) {
1932 var _getResolutionState2;
1933
1934 return ((_getResolutionState2 = getResolutionState(state, selectorName, args)) === null || _getResolutionState2 === void 0 ? void 0 : _getResolutionState2.status) === 'error';
1935 }
1936 /**
1937 * Returns the resolution error for a given selector name, and arguments set.
1938 * Note it may be of an Error type, but may also be null, undefined, or anything else
1939 * that can be `throw`-n.
1940 *
1941 * @param {State} state Data state.
1942 * @param {string} selectorName Selector name.
1943 * @param {unknown[]?} args Arguments passed to selector.
1944 *
1945 * @return {Error|unknown} Last resolution error
1946 */
1947
1948 function getResolutionError(state, selectorName, args) {
1949 const resolutionState = getResolutionState(state, selectorName, args);
1950 return (resolutionState === null || resolutionState === void 0 ? void 0 : resolutionState.status) === 'error' ? resolutionState.error : null;
1951 }
1952 /**
1953 * Returns true if resolution has been triggered but has not yet completed for
1954 * a given selector name, and arguments set.
1955 *
1956 * @param {State} state Data state.
1957 * @param {string} selectorName Selector name.
1958 * @param {unknown[]?} args Arguments passed to selector.
1959 *
1960 * @return {boolean} Whether resolution is in progress.
1961 */
1962
1963 function isResolving(state, selectorName, args) {
1964 var _getResolutionState3;
1965
1966 return ((_getResolutionState3 = getResolutionState(state, selectorName, args)) === null || _getResolutionState3 === void 0 ? void 0 : _getResolutionState3.status) === 'resolving';
1967 }
1968 /**
1969 * Returns the list of the cached resolvers.
1970 *
1971 * @param {State} state Data state.
1972 *
1973 * @return {State} Resolvers mapped by args and selectorName.
1974 */
1975
1976 function getCachedResolvers(state) {
1977 return state;
1978 }
1979
1980 ;// CONCATENATED MODULE: ./packages/data/build-module/redux-store/metadata/actions.js
1981 /**
1982 * Returns an action object used in signalling that selector resolution has
1983 * started.
1984 *
1985 * @param {string} selectorName Name of selector for which resolver triggered.
1986 * @param {unknown[]} args Arguments to associate for uniqueness.
1987 *
1988 * @return {{ type: 'START_RESOLUTION', selectorName: string, args: unknown[] }} Action object.
1989 */
1990 function startResolution(selectorName, args) {
1991 return {
1992 type: 'START_RESOLUTION',
1993 selectorName,
1994 args
1995 };
1996 }
1997 /**
1998 * Returns an action object used in signalling that selector resolution has
1999 * completed.
2000 *
2001 * @param {string} selectorName Name of selector for which resolver triggered.
2002 * @param {unknown[]} args Arguments to associate for uniqueness.
2003 *
2004 * @return {{ type: 'FINISH_RESOLUTION', selectorName: string, args: unknown[] }} Action object.
2005 */
2006
2007 function finishResolution(selectorName, args) {
2008 return {
2009 type: 'FINISH_RESOLUTION',
2010 selectorName,
2011 args
2012 };
2013 }
2014 /**
2015 * Returns an action object used in signalling that selector resolution has
2016 * failed.
2017 *
2018 * @param {string} selectorName Name of selector for which resolver triggered.
2019 * @param {unknown[]} args Arguments to associate for uniqueness.
2020 * @param {Error|unknown} error The error that caused the failure.
2021 *
2022 * @return {{ type: 'FAIL_RESOLUTION', selectorName: string, args: unknown[], error: Error|unknown }} Action object.
2023 */
2024
2025 function failResolution(selectorName, args, error) {
2026 return {
2027 type: 'FAIL_RESOLUTION',
2028 selectorName,
2029 args,
2030 error
2031 };
2032 }
2033 /**
2034 * Returns an action object used in signalling that a batch of selector resolutions has
2035 * started.
2036 *
2037 * @param {string} selectorName Name of selector for which resolver triggered.
2038 * @param {unknown[][]} args Array of arguments to associate for uniqueness, each item
2039 * is associated to a resolution.
2040 *
2041 * @return {{ type: 'START_RESOLUTIONS', selectorName: string, args: unknown[][] }} Action object.
2042 */
2043
2044 function startResolutions(selectorName, args) {
2045 return {
2046 type: 'START_RESOLUTIONS',
2047 selectorName,
2048 args
2049 };
2050 }
2051 /**
2052 * Returns an action object used in signalling that a batch of selector resolutions has
2053 * completed.
2054 *
2055 * @param {string} selectorName Name of selector for which resolver triggered.
2056 * @param {unknown[][]} args Array of arguments to associate for uniqueness, each item
2057 * is associated to a resolution.
2058 *
2059 * @return {{ type: 'FINISH_RESOLUTIONS', selectorName: string, args: unknown[][] }} Action object.
2060 */
2061
2062 function finishResolutions(selectorName, args) {
2063 return {
2064 type: 'FINISH_RESOLUTIONS',
2065 selectorName,
2066 args
2067 };
2068 }
2069 /**
2070 * Returns an action object used in signalling that a batch of selector resolutions has
2071 * completed and at least one of them has failed.
2072 *
2073 * @param {string} selectorName Name of selector for which resolver triggered.
2074 * @param {unknown[]} args Array of arguments to associate for uniqueness, each item
2075 * is associated to a resolution.
2076 * @param {(Error|unknown)[]} errors Array of errors to associate for uniqueness, each item
2077 * is associated to a resolution.
2078 * @return {{ type: 'FAIL_RESOLUTIONS', selectorName: string, args: unknown[], errors: Array<Error|unknown> }} Action object.
2079 */
2080
2081 function failResolutions(selectorName, args, errors) {
2082 return {
2083 type: 'FAIL_RESOLUTIONS',
2084 selectorName,
2085 args,
2086 errors
2087 };
2088 }
2089 /**
2090 * Returns an action object used in signalling that we should invalidate the resolution cache.
2091 *
2092 * @param {string} selectorName Name of selector for which resolver should be invalidated.
2093 * @param {unknown[]} args Arguments to associate for uniqueness.
2094 *
2095 * @return {{ type: 'INVALIDATE_RESOLUTION', selectorName: string, args: any[] }} Action object.
2096 */
2097
2098 function invalidateResolution(selectorName, args) {
2099 return {
2100 type: 'INVALIDATE_RESOLUTION',
2101 selectorName,
2102 args
2103 };
2104 }
2105 /**
2106 * Returns an action object used in signalling that the resolution
2107 * should be invalidated.
2108 *
2109 * @return {{ type: 'INVALIDATE_RESOLUTION_FOR_STORE' }} Action object.
2110 */
2111
2112 function invalidateResolutionForStore() {
2113 return {
2114 type: 'INVALIDATE_RESOLUTION_FOR_STORE'
2115 };
2116 }
2117 /**
2118 * Returns an action object used in signalling that the resolution cache for a
2119 * given selectorName should be invalidated.
2120 *
2121 * @param {string} selectorName Name of selector for which all resolvers should
2122 * be invalidated.
2123 *
2124 * @return {{ type: 'INVALIDATE_RESOLUTION_FOR_STORE_SELECTOR', selectorName: string }} Action object.
2125 */
2126
2127 function invalidateResolutionForStoreSelector(selectorName) {
2128 return {
2129 type: 'INVALIDATE_RESOLUTION_FOR_STORE_SELECTOR',
2130 selectorName
2131 };
2132 }
2133
2134 ;// CONCATENATED MODULE: ./packages/data/build-module/redux-store/index.js
2135 /**
2136 * External dependencies
2137 */
2138
2139
2140
2141
2142 /**
2143 * WordPress dependencies
2144 */
2145
2146
2147 /**
2148 * Internal dependencies
2149 */
2150
2151
2152
2153
2154
2155
2156
2157
2158 /** @typedef {import('../types').DataRegistry} DataRegistry */
2159
2160 /** @typedef {import('../types').StoreDescriptor} StoreDescriptor */
2161
2162 /** @typedef {import('../types').ReduxStoreConfig} ReduxStoreConfig */
2163
2164 const trimUndefinedValues = array => {
2165 const result = [...array];
2166
2167 for (let i = result.length - 1; i >= 0; i--) {
2168 if (result[i] === undefined) {
2169 result.splice(i, 1);
2170 }
2171 }
2172
2173 return result;
2174 };
2175 /**
2176 * Create a cache to track whether resolvers started running or not.
2177 *
2178 * @return {Object} Resolvers Cache.
2179 */
2180
2181
2182 function createResolversCache() {
2183 const cache = {};
2184 return {
2185 isRunning(selectorName, args) {
2186 return cache[selectorName] && cache[selectorName].get(trimUndefinedValues(args));
2187 },
2188
2189 clear(selectorName, args) {
2190 if (cache[selectorName]) {
2191 cache[selectorName].delete(trimUndefinedValues(args));
2192 }
2193 },
2194
2195 markAsRunning(selectorName, args) {
2196 if (!cache[selectorName]) {
2197 cache[selectorName] = new (equivalent_key_map_default())();
2198 }
2199
2200 cache[selectorName].set(trimUndefinedValues(args), true);
2201 }
2202
2203 };
2204 }
2205 /**
2206 * Creates a data store descriptor for the provided Redux store configuration containing
2207 * properties describing reducer, actions, selectors, controls and resolvers.
2208 *
2209 * @example
2210 * ```js
2211 * import { createReduxStore } from '@wordpress/data';
2212 *
2213 * const store = createReduxStore( 'demo', {
2214 * reducer: ( state = 'OK' ) => state,
2215 * selectors: {
2216 * getValue: ( state ) => state,
2217 * },
2218 * } );
2219 * ```
2220 *
2221 * @param {string} key Unique namespace identifier.
2222 * @param {ReduxStoreConfig} options Registered store options, with properties
2223 * describing reducer, actions, selectors,
2224 * and resolvers.
2225 *
2226 * @return {StoreDescriptor} Store Object.
2227 */
2228
2229
2230 function createReduxStore(key, options) {
2231 return {
2232 name: key,
2233 instantiate: registry => {
2234 const reducer = options.reducer;
2235 const thunkArgs = {
2236 registry,
2237
2238 get dispatch() {
2239 return Object.assign(action => store.dispatch(action), getActions());
2240 },
2241
2242 get select() {
2243 return Object.assign(selector => selector(store.__unstableOriginalGetState()), getSelectors());
2244 },
2245
2246 get resolveSelect() {
2247 return getResolveSelectors();
2248 }
2249
2250 };
2251 const store = instantiateReduxStore(key, options, registry, thunkArgs);
2252 const resolversCache = createResolversCache();
2253 let resolvers;
2254 const actions = mapActions({ ...actions_namespaceObject,
2255 ...options.actions
2256 }, store);
2257 let selectors = mapSelectors({ ...(0,external_lodash_namespaceObject.mapValues)(selectors_namespaceObject, selector => function (state) {
2258 for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
2259 args[_key - 1] = arguments[_key];
2260 }
2261
2262 return selector(state.metadata, ...args);
2263 }),
2264 ...(0,external_lodash_namespaceObject.mapValues)(options.selectors, selector => {
2265 if (selector.isRegistrySelector) {
2266 selector.registry = registry;
2267 }
2268
2269 return function (state) {
2270 for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
2271 args[_key2 - 1] = arguments[_key2];
2272 }
2273
2274 return selector(state.root, ...args);
2275 };
2276 })
2277 }, store);
2278
2279 if (options.resolvers) {
2280 const result = mapResolvers(options.resolvers, selectors, store, resolversCache);
2281 resolvers = result.resolvers;
2282 selectors = result.selectors;
2283 }
2284
2285 const resolveSelectors = mapResolveSelectors(selectors, store);
2286 const suspendSelectors = mapSuspendSelectors(selectors, store);
2287
2288 const getSelectors = () => selectors;
2289
2290 const getActions = () => actions;
2291
2292 const getResolveSelectors = () => resolveSelectors;
2293
2294 const getSuspendSelectors = () => suspendSelectors; // We have some modules monkey-patching the store object
2295 // It's wrong to do so but until we refactor all of our effects to controls
2296 // We need to keep the same "store" instance here.
2297
2298
2299 store.__unstableOriginalGetState = store.getState;
2300
2301 store.getState = () => store.__unstableOriginalGetState().root; // Customize subscribe behavior to call listeners only on effective change,
2302 // not on every dispatch.
2303
2304
2305 const subscribe = store && (listener => {
2306 let lastState = store.__unstableOriginalGetState();
2307
2308 return store.subscribe(() => {
2309 const state = store.__unstableOriginalGetState();
2310
2311 const hasChanged = state !== lastState;
2312 lastState = state;
2313
2314 if (hasChanged) {
2315 listener();
2316 }
2317 });
2318 }); // This can be simplified to just { subscribe, getSelectors, getActions }
2319 // Once we remove the use function.
2320
2321
2322 return {
2323 reducer,
2324 store,
2325 actions,
2326 selectors,
2327 resolvers,
2328 getSelectors,
2329 getResolveSelectors,
2330 getSuspendSelectors,
2331 getActions,
2332 subscribe
2333 };
2334 }
2335 };
2336 }
2337 /**
2338 * Creates a redux store for a namespace.
2339 *
2340 * @param {string} key Unique namespace identifier.
2341 * @param {Object} options Registered store options, with properties
2342 * describing reducer, actions, selectors,
2343 * and resolvers.
2344 * @param {DataRegistry} registry Registry reference.
2345 * @param {Object} thunkArgs Argument object for the thunk middleware.
2346 * @return {Object} Newly created redux store.
2347 */
2348
2349 function instantiateReduxStore(key, options, registry, thunkArgs) {
2350 const controls = { ...options.controls,
2351 ...builtinControls
2352 };
2353 const normalizedControls = (0,external_lodash_namespaceObject.mapValues)(controls, control => control.isRegistryControl ? control(registry) : control);
2354 const middlewares = [resolvers_cache_middleware(registry, key), promise_middleware, external_wp_reduxRoutine_default()(normalizedControls), createThunkMiddleware(thunkArgs)];
2355 const enhancers = [applyMiddleware(...middlewares)];
2356
2357 if (typeof window !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION__) {
2358 enhancers.push(window.__REDUX_DEVTOOLS_EXTENSION__({
2359 name: key,
2360 instanceId: key
2361 }));
2362 }
2363
2364 const {
2365 reducer,
2366 initialState
2367 } = options;
2368 const enhancedReducer = turbo_combine_reducers_default()({
2369 metadata: metadata_reducer,
2370 root: reducer
2371 });
2372 return createStore(enhancedReducer, {
2373 root: initialState
2374 }, (0,external_lodash_namespaceObject.flowRight)(enhancers));
2375 }
2376 /**
2377 * Maps selectors to a store.
2378 *
2379 * @param {Object} selectors Selectors to register. Keys will be used as the
2380 * public facing API. Selectors will get passed the
2381 * state as first argument.
2382 * @param {Object} store The store to which the selectors should be mapped.
2383 * @return {Object} Selectors mapped to the provided store.
2384 */
2385
2386
2387 function mapSelectors(selectors, store) {
2388 const createStateSelector = registrySelector => {
2389 const selector = function runSelector() {
2390 // This function is an optimized implementation of:
2391 //
2392 // selector( store.getState(), ...arguments )
2393 //
2394 // Where the above would incur an `Array#concat` in its application,
2395 // the logic here instead efficiently constructs an arguments array via
2396 // direct assignment.
2397 const argsLength = arguments.length;
2398 const args = new Array(argsLength + 1);
2399 args[0] = store.__unstableOriginalGetState();
2400
2401 for (let i = 0; i < argsLength; i++) {
2402 args[i + 1] = arguments[i];
2403 }
2404
2405 return registrySelector(...args);
2406 };
2407
2408 selector.hasResolver = false;
2409 return selector;
2410 };
2411
2412 return (0,external_lodash_namespaceObject.mapValues)(selectors, createStateSelector);
2413 }
2414 /**
2415 * Maps actions to dispatch from a given store.
2416 *
2417 * @param {Object} actions Actions to register.
2418 * @param {Object} store The redux store to which the actions should be mapped.
2419 *
2420 * @return {Object} Actions mapped to the redux store provided.
2421 */
2422
2423
2424 function mapActions(actions, store) {
2425 const createBoundAction = action => function () {
2426 return Promise.resolve(store.dispatch(action(...arguments)));
2427 };
2428
2429 return (0,external_lodash_namespaceObject.mapValues)(actions, createBoundAction);
2430 }
2431 /**
2432 * Maps selectors to functions that return a resolution promise for them
2433 *
2434 * @param {Object} selectors Selectors to map.
2435 * @param {Object} store The redux store the selectors select from.
2436 *
2437 * @return {Object} Selectors mapped to their resolution functions.
2438 */
2439
2440
2441 function mapResolveSelectors(selectors, store) {
2442 const storeSelectors = (0,external_lodash_namespaceObject.omit)(selectors, ['getIsResolving', 'hasStartedResolution', 'hasFinishedResolution', 'hasResolutionFailed', 'isResolving', 'getCachedResolvers', 'getResolutionState', 'getResolutionError']);
2443 return (0,external_lodash_namespaceObject.mapValues)(storeSelectors, (selector, selectorName) => {
2444 // If the selector doesn't have a resolver, just convert the return value
2445 // (including exceptions) to a Promise, no additional extra behavior is needed.
2446 if (!selector.hasResolver) {
2447 return async function () {
2448 for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
2449 args[_key3] = arguments[_key3];
2450 }
2451
2452 return selector.apply(null, args);
2453 };
2454 }
2455
2456 return function () {
2457 for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
2458 args[_key4] = arguments[_key4];
2459 }
2460
2461 return new Promise((resolve, reject) => {
2462 const hasFinished = () => selectors.hasFinishedResolution(selectorName, args);
2463
2464 const finalize = result => {
2465 const hasFailed = selectors.hasResolutionFailed(selectorName, args);
2466
2467 if (hasFailed) {
2468 const error = selectors.getResolutionError(selectorName, args);
2469 reject(error);
2470 } else {
2471 resolve(result);
2472 }
2473 };
2474
2475 const getResult = () => selector.apply(null, args); // Trigger the selector (to trigger the resolver)
2476
2477
2478 const result = getResult();
2479
2480 if (hasFinished()) {
2481 return finalize(result);
2482 }
2483
2484 const unsubscribe = store.subscribe(() => {
2485 if (hasFinished()) {
2486 unsubscribe();
2487 finalize(getResult());
2488 }
2489 });
2490 });
2491 };
2492 });
2493 }
2494 /**
2495 * Maps selectors to functions that throw a suspense promise if not yet resolved.
2496 *
2497 * @param {Object} selectors Selectors to map.
2498 * @param {Object} store The redux store the selectors select from.
2499 *
2500 * @return {Object} Selectors mapped to their suspense functions.
2501 */
2502
2503
2504 function mapSuspendSelectors(selectors, store) {
2505 return (0,external_lodash_namespaceObject.mapValues)(selectors, (selector, selectorName) => {
2506 // Selector without a resolver doesn't have any extra suspense behavior.
2507 if (!selector.hasResolver) {
2508 return selector;
2509 }
2510
2511 return function () {
2512 for (var _len5 = arguments.length, args = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
2513 args[_key5] = arguments[_key5];
2514 }
2515
2516 const result = selector.apply(null, args);
2517
2518 if (selectors.hasFinishedResolution(selectorName, args)) {
2519 if (selectors.hasResolutionFailed(selectorName, args)) {
2520 throw selectors.getResolutionError(selectorName, args);
2521 }
2522
2523 return result;
2524 }
2525
2526 throw new Promise(resolve => {
2527 const unsubscribe = store.subscribe(() => {
2528 if (selectors.hasFinishedResolution(selectorName, args)) {
2529 resolve();
2530 unsubscribe();
2531 }
2532 });
2533 });
2534 };
2535 });
2536 }
2537 /**
2538 * Returns resolvers with matched selectors for a given namespace.
2539 * Resolvers are side effects invoked once per argument set of a given selector call,
2540 * used in ensuring that the data needs for the selector are satisfied.
2541 *
2542 * @param {Object} resolvers Resolvers to register.
2543 * @param {Object} selectors The current selectors to be modified.
2544 * @param {Object} store The redux store to which the resolvers should be mapped.
2545 * @param {Object} resolversCache Resolvers Cache.
2546 */
2547
2548
2549 function mapResolvers(resolvers, selectors, store, resolversCache) {
2550 // The `resolver` can be either a function that does the resolution, or, in more advanced
2551 // cases, an object with a `fullfill` method and other optional methods like `isFulfilled`.
2552 // Here we normalize the `resolver` function to an object with `fulfill` method.
2553 const mappedResolvers = (0,external_lodash_namespaceObject.mapValues)(resolvers, resolver => {
2554 if (resolver.fulfill) {
2555 return resolver;
2556 }
2557
2558 return { ...resolver,
2559 // Copy the enumerable properties of the resolver function.
2560 fulfill: resolver // Add the fulfill method.
2561
2562 };
2563 });
2564
2565 const mapSelector = (selector, selectorName) => {
2566 const resolver = resolvers[selectorName];
2567
2568 if (!resolver) {
2569 selector.hasResolver = false;
2570 return selector;
2571 }
2572
2573 const selectorResolver = function () {
2574 for (var _len6 = arguments.length, args = new Array(_len6), _key6 = 0; _key6 < _len6; _key6++) {
2575 args[_key6] = arguments[_key6];
2576 }
2577
2578 async function fulfillSelector() {
2579 const state = store.getState();
2580
2581 if (resolversCache.isRunning(selectorName, args) || typeof resolver.isFulfilled === 'function' && resolver.isFulfilled(state, ...args)) {
2582 return;
2583 }
2584
2585 const {
2586 metadata
2587 } = store.__unstableOriginalGetState();
2588
2589 if (hasStartedResolution(metadata, selectorName, args)) {
2590 return;
2591 }
2592
2593 resolversCache.markAsRunning(selectorName, args);
2594 setTimeout(async () => {
2595 resolversCache.clear(selectorName, args);
2596 store.dispatch(startResolution(selectorName, args));
2597
2598 try {
2599 await fulfillResolver(store, mappedResolvers, selectorName, ...args);
2600 store.dispatch(finishResolution(selectorName, args));
2601 } catch (error) {
2602 store.dispatch(failResolution(selectorName, args, error));
2603 }
2604 });
2605 }
2606
2607 fulfillSelector(...args);
2608 return selector(...args);
2609 };
2610
2611 selectorResolver.hasResolver = true;
2612 return selectorResolver;
2613 };
2614
2615 return {
2616 resolvers: mappedResolvers,
2617 selectors: (0,external_lodash_namespaceObject.mapValues)(selectors, mapSelector)
2618 };
2619 }
2620 /**
2621 * Calls a resolver given arguments
2622 *
2623 * @param {Object} store Store reference, for fulfilling via resolvers
2624 * @param {Object} resolvers Store Resolvers
2625 * @param {string} selectorName Selector name to fulfill.
2626 * @param {Array} args Selector Arguments.
2627 */
2628
2629
2630 async function fulfillResolver(store, resolvers, selectorName) {
2631 const resolver = (0,external_lodash_namespaceObject.get)(resolvers, [selectorName]);
2632
2633 if (!resolver) {
2634 return;
2635 }
2636
2637 for (var _len7 = arguments.length, args = new Array(_len7 > 3 ? _len7 - 3 : 0), _key7 = 3; _key7 < _len7; _key7++) {
2638 args[_key7 - 3] = arguments[_key7];
2639 }
2640
2641 const action = resolver.fulfill(...args);
2642
2643 if (action) {
2644 await store.dispatch(action);
2645 }
2646 }
2647
2648 ;// CONCATENATED MODULE: ./packages/data/build-module/utils/emitter.js
2649 /**
2650 * Create an event emitter.
2651 *
2652 * @return {import("../types").DataEmitter} Emitter.
2653 */
2654 function createEmitter() {
2655 let isPaused = false;
2656 let isPending = false;
2657 const listeners = new Set();
2658
2659 const notifyListeners = () => // We use Array.from to clone the listeners Set
2660 // This ensures that we don't run a listener
2661 // that was added as a response to another listener.
2662 Array.from(listeners).forEach(listener => listener());
2663
2664 return {
2665 get isPaused() {
2666 return isPaused;
2667 },
2668
2669 subscribe(listener) {
2670 listeners.add(listener);
2671 return () => listeners.delete(listener);
2672 },
2673
2674 pause() {
2675 isPaused = true;
2676 },
2677
2678 resume() {
2679 isPaused = false;
2680
2681 if (isPending) {
2682 isPending = false;
2683 notifyListeners();
2684 }
2685 },
2686
2687 emit() {
2688 if (isPaused) {
2689 isPending = true;
2690 return;
2691 }
2692
2693 notifyListeners();
2694 }
2695
2696 };
2697 }
2698
2699 ;// CONCATENATED MODULE: ./packages/data/build-module/registry.js
2700 /**
2701 * External dependencies
2702 */
2703
2704 /**
2705 * WordPress dependencies
2706 */
2707
2708
2709 /**
2710 * Internal dependencies
2711 */
2712
2713
2714
2715
2716 /** @typedef {import('./types').StoreDescriptor} StoreDescriptor */
2717
2718 /**
2719 * @typedef {Object} WPDataRegistry An isolated orchestrator of store registrations.
2720 *
2721 * @property {Function} registerGenericStore Given a namespace key and settings
2722 * object, registers a new generic
2723 * store.
2724 * @property {Function} registerStore Given a namespace key and settings
2725 * object, registers a new namespace
2726 * store.
2727 * @property {Function} subscribe Given a function callback, invokes
2728 * the callback on any change to state
2729 * within any registered store.
2730 * @property {Function} select Given a namespace key, returns an
2731 * object of the store's registered
2732 * selectors.
2733 * @property {Function} dispatch Given a namespace key, returns an
2734 * object of the store's registered
2735 * action dispatchers.
2736 */
2737
2738 /**
2739 * @typedef {Object} WPDataPlugin An object of registry function overrides.
2740 *
2741 * @property {Function} registerStore registers store.
2742 */
2743
2744 /**
2745 * Creates a new store registry, given an optional object of initial store
2746 * configurations.
2747 *
2748 * @param {Object} storeConfigs Initial store configurations.
2749 * @param {Object?} parent Parent registry.
2750 *
2751 * @return {WPDataRegistry} Data registry.
2752 */
2753
2754 function createRegistry() {
2755 let storeConfigs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
2756 let parent = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
2757 const stores = {};
2758 const emitter = createEmitter();
2759 const listeningStores = new Set();
2760 /**
2761 * Global listener called for each store's update.
2762 */
2763
2764 function globalListener() {
2765 emitter.emit();
2766 }
2767 /**
2768 * Subscribe to changes to any data.
2769 *
2770 * @param {Function} listener Listener function.
2771 *
2772 * @return {Function} Unsubscribe function.
2773 */
2774
2775
2776 const subscribe = listener => {
2777 return emitter.subscribe(listener);
2778 };
2779 /**
2780 * Calls a selector given the current state and extra arguments.
2781 *
2782 * @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
2783 * or the store descriptor.
2784 *
2785 * @return {*} The selector's returned value.
2786 */
2787
2788
2789 function select(storeNameOrDescriptor) {
2790 const storeName = (0,external_lodash_namespaceObject.isObject)(storeNameOrDescriptor) ? storeNameOrDescriptor.name : storeNameOrDescriptor;
2791 listeningStores.add(storeName);
2792 const store = stores[storeName];
2793
2794 if (store) {
2795 return store.getSelectors();
2796 }
2797
2798 return parent === null || parent === void 0 ? void 0 : parent.select(storeName);
2799 }
2800
2801 function __unstableMarkListeningStores(callback, ref) {
2802 listeningStores.clear();
2803
2804 try {
2805 return callback.call(this);
2806 } finally {
2807 ref.current = Array.from(listeningStores);
2808 }
2809 }
2810 /**
2811 * Given the name of a registered store, returns an object containing the store's
2812 * selectors pre-bound to state so that you only need to supply additional arguments,
2813 * and modified so that they return promises that resolve to their eventual values,
2814 * after any resolvers have ran.
2815 *
2816 * @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
2817 * or the store descriptor.
2818 *
2819 * @return {Object} Each key of the object matches the name of a selector.
2820 */
2821
2822
2823 function resolveSelect(storeNameOrDescriptor) {
2824 const storeName = (0,external_lodash_namespaceObject.isObject)(storeNameOrDescriptor) ? storeNameOrDescriptor.name : storeNameOrDescriptor;
2825 listeningStores.add(storeName);
2826 const store = stores[storeName];
2827
2828 if (store) {
2829 return store.getResolveSelectors();
2830 }
2831
2832 return parent && parent.resolveSelect(storeName);
2833 }
2834 /**
2835 * Given the name of a registered store, returns an object containing the store's
2836 * selectors pre-bound to state so that you only need to supply additional arguments,
2837 * and modified so that they throw promises in case the selector is not resolved yet.
2838 *
2839 * @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
2840 * or the store descriptor.
2841 *
2842 * @return {Object} Object containing the store's suspense-wrapped selectors.
2843 */
2844
2845
2846 function suspendSelect(storeNameOrDescriptor) {
2847 const storeName = (0,external_lodash_namespaceObject.isObject)(storeNameOrDescriptor) ? storeNameOrDescriptor.name : storeNameOrDescriptor;
2848 listeningStores.add(storeName);
2849 const store = stores[storeName];
2850
2851 if (store) {
2852 return store.getSuspendSelectors();
2853 }
2854
2855 return parent && parent.suspendSelect(storeName);
2856 }
2857 /**
2858 * Returns the available actions for a part of the state.
2859 *
2860 * @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
2861 * or the store descriptor.
2862 *
2863 * @return {*} The action's returned value.
2864 */
2865
2866
2867 function dispatch(storeNameOrDescriptor) {
2868 const storeName = (0,external_lodash_namespaceObject.isObject)(storeNameOrDescriptor) ? storeNameOrDescriptor.name : storeNameOrDescriptor;
2869 const store = stores[storeName];
2870
2871 if (store) {
2872 return store.getActions();
2873 }
2874
2875 return parent && parent.dispatch(storeName);
2876 } //
2877 // Deprecated
2878 // TODO: Remove this after `use()` is removed.
2879
2880
2881 function withPlugins(attributes) {
2882 return (0,external_lodash_namespaceObject.mapValues)(attributes, (attribute, key) => {
2883 if (typeof attribute !== 'function') {
2884 return attribute;
2885 }
2886
2887 return function () {
2888 return registry[key].apply(null, arguments);
2889 };
2890 });
2891 }
2892 /**
2893 * Registers a store instance.
2894 *
2895 * @param {string} name Store registry name.
2896 * @param {Object} store Store instance object (getSelectors, getActions, subscribe).
2897 */
2898
2899
2900 function registerStoreInstance(name, store) {
2901 if (typeof store.getSelectors !== 'function') {
2902 throw new TypeError('store.getSelectors must be a function');
2903 }
2904
2905 if (typeof store.getActions !== 'function') {
2906 throw new TypeError('store.getActions must be a function');
2907 }
2908
2909 if (typeof store.subscribe !== 'function') {
2910 throw new TypeError('store.subscribe must be a function');
2911 } // The emitter is used to keep track of active listeners when the registry
2912 // get paused, that way, when resumed we should be able to call all these
2913 // pending listeners.
2914
2915
2916 store.emitter = createEmitter();
2917 const currentSubscribe = store.subscribe;
2918
2919 store.subscribe = listener => {
2920 const unsubscribeFromEmitter = store.emitter.subscribe(listener);
2921 const unsubscribeFromStore = currentSubscribe(() => {
2922 if (store.emitter.isPaused) {
2923 store.emitter.emit();
2924 return;
2925 }
2926
2927 listener();
2928 });
2929 return () => {
2930 unsubscribeFromStore === null || unsubscribeFromStore === void 0 ? void 0 : unsubscribeFromStore();
2931 unsubscribeFromEmitter === null || unsubscribeFromEmitter === void 0 ? void 0 : unsubscribeFromEmitter();
2932 };
2933 };
2934
2935 stores[name] = store;
2936 store.subscribe(globalListener);
2937 }
2938 /**
2939 * Registers a new store given a store descriptor.
2940 *
2941 * @param {StoreDescriptor} store Store descriptor.
2942 */
2943
2944
2945 function register(store) {
2946 registerStoreInstance(store.name, store.instantiate(registry));
2947 }
2948
2949 function registerGenericStore(name, store) {
2950 external_wp_deprecated_default()('wp.data.registerGenericStore', {
2951 since: '5.9',
2952 alternative: 'wp.data.register( storeDescriptor )'
2953 });
2954 registerStoreInstance(name, store);
2955 }
2956 /**
2957 * Registers a standard `@wordpress/data` store.
2958 *
2959 * @param {string} storeName Unique namespace identifier.
2960 * @param {Object} options Store description (reducer, actions, selectors, resolvers).
2961 *
2962 * @return {Object} Registered store object.
2963 */
2964
2965
2966 function registerStore(storeName, options) {
2967 if (!options.reducer) {
2968 throw new TypeError('Must specify store reducer');
2969 }
2970
2971 const store = createReduxStore(storeName, options).instantiate(registry);
2972 registerStoreInstance(storeName, store);
2973 return store.store;
2974 }
2975 /**
2976 * Subscribe handler to a store.
2977 *
2978 * @param {string[]} storeName The store name.
2979 * @param {Function} handler The function subscribed to the store.
2980 * @return {Function} A function to unsubscribe the handler.
2981 */
2982
2983
2984 function __unstableSubscribeStore(storeName, handler) {
2985 if (storeName in stores) {
2986 return stores[storeName].subscribe(handler);
2987 } // Trying to access a store that hasn't been registered,
2988 // this is a pattern rarely used but seen in some places.
2989 // We fallback to regular `subscribe` here for backward-compatibility for now.
2990 // See https://github.com/WordPress/gutenberg/pull/27466 for more info.
2991
2992
2993 if (!parent) {
2994 return subscribe(handler);
2995 }
2996
2997 return parent.__unstableSubscribeStore(storeName, handler);
2998 }
2999
3000 function batch(callback) {
3001 emitter.pause();
3002 (0,external_lodash_namespaceObject.forEach)(stores, store => store.emitter.pause());
3003 callback();
3004 emitter.resume();
3005 (0,external_lodash_namespaceObject.forEach)(stores, store => store.emitter.resume());
3006 }
3007
3008 let registry = {
3009 batch,
3010 stores,
3011 namespaces: stores,
3012 // TODO: Deprecate/remove this.
3013 subscribe,
3014 select,
3015 resolveSelect,
3016 suspendSelect,
3017 dispatch,
3018 use,
3019 register,
3020 registerGenericStore,
3021 registerStore,
3022 __unstableMarkListeningStores,
3023 __unstableSubscribeStore
3024 }; //
3025 // TODO:
3026 // This function will be deprecated as soon as it is no longer internally referenced.
3027
3028 function use(plugin, options) {
3029 if (!plugin) {
3030 return;
3031 }
3032
3033 registry = { ...registry,
3034 ...plugin(registry, options)
3035 };
3036 return registry;
3037 }
3038
3039 registry.register(store);
3040
3041 for (const [name, config] of Object.entries(storeConfigs)) {
3042 registry.register(createReduxStore(name, config));
3043 }
3044
3045 if (parent) {
3046 parent.subscribe(globalListener);
3047 }
3048
3049 return withPlugins(registry);
3050 }
3051
3052 ;// CONCATENATED MODULE: ./packages/data/build-module/default-registry.js
3053 /**
3054 * Internal dependencies
3055 */
3056
3057 /* harmony default export */ const default_registry = (createRegistry());
3058
3059 ;// CONCATENATED MODULE: ./packages/data/build-module/plugins/persistence/storage/object.js
3060 let objectStorage;
3061 const storage = {
3062 getItem(key) {
3063 if (!objectStorage || !objectStorage[key]) {
3064 return null;
3065 }
3066
3067 return objectStorage[key];
3068 },
3069
3070 setItem(key, value) {
3071 if (!objectStorage) {
3072 storage.clear();
3073 }
3074
3075 objectStorage[key] = String(value);
3076 },
3077
3078 clear() {
3079 objectStorage = Object.create(null);
3080 }
3081
3082 };
3083 /* harmony default export */ const object = (storage);
3084
3085 ;// CONCATENATED MODULE: ./packages/data/build-module/plugins/persistence/storage/default.js
3086 /**
3087 * Internal dependencies
3088 */
3089
3090 let default_storage;
3091
3092 try {
3093 // Private Browsing in Safari 10 and earlier will throw an error when
3094 // attempting to set into localStorage. The test here is intentional in
3095 // causing a thrown error as condition for using fallback object storage.
3096 default_storage = window.localStorage;
3097 default_storage.setItem('__wpDataTestLocalStorage', '');
3098 default_storage.removeItem('__wpDataTestLocalStorage');
3099 } catch (error) {
3100 default_storage = object;
3101 }
3102
3103 /* harmony default export */ const storage_default = (default_storage);
3104
3105 ;// CONCATENATED MODULE: ./packages/data/build-module/plugins/persistence/index.js
3106 /**
3107 * External dependencies
3108 */
3109
3110 /**
3111 * Internal dependencies
3112 */
3113
3114
3115
3116 /** @typedef {import('../../registry').WPDataRegistry} WPDataRegistry */
3117
3118 /** @typedef {import('../../registry').WPDataPlugin} WPDataPlugin */
3119
3120 /**
3121 * @typedef {Object} WPDataPersistencePluginOptions Persistence plugin options.
3122 *
3123 * @property {Storage} storage Persistent storage implementation. This must
3124 * at least implement `getItem` and `setItem` of
3125 * the Web Storage API.
3126 * @property {string} storageKey Key on which to set in persistent storage.
3127 *
3128 */
3129
3130 /**
3131 * Default plugin storage.
3132 *
3133 * @type {Storage}
3134 */
3135
3136 const DEFAULT_STORAGE = storage_default;
3137 /**
3138 * Default plugin storage key.
3139 *
3140 * @type {string}
3141 */
3142
3143 const DEFAULT_STORAGE_KEY = 'WP_DATA';
3144 /**
3145 * Higher-order reducer which invokes the original reducer only if state is
3146 * inequal from that of the action's `nextState` property, otherwise returning
3147 * the original state reference.
3148 *
3149 * @param {Function} reducer Original reducer.
3150 *
3151 * @return {Function} Enhanced reducer.
3152 */
3153
3154 const withLazySameState = reducer => (state, action) => {
3155 if (action.nextState === state) {
3156 return state;
3157 }
3158
3159 return reducer(state, action);
3160 };
3161 /**
3162 * Creates a persistence interface, exposing getter and setter methods (`get`
3163 * and `set` respectively).
3164 *
3165 * @param {WPDataPersistencePluginOptions} options Plugin options.
3166 *
3167 * @return {Object} Persistence interface.
3168 */
3169
3170 function createPersistenceInterface(options) {
3171 const {
3172 storage = DEFAULT_STORAGE,
3173 storageKey = DEFAULT_STORAGE_KEY
3174 } = options;
3175 let data;
3176 /**
3177 * Returns the persisted data as an object, defaulting to an empty object.
3178 *
3179 * @return {Object} Persisted data.
3180 */
3181
3182 function getData() {
3183 if (data === undefined) {
3184 // If unset, getItem is expected to return null. Fall back to
3185 // empty object.
3186 const persisted = storage.getItem(storageKey);
3187
3188 if (persisted === null) {
3189 data = {};
3190 } else {
3191 try {
3192 data = JSON.parse(persisted);
3193 } catch (error) {
3194 // Similarly, should any error be thrown during parse of
3195 // the string (malformed JSON), fall back to empty object.
3196 data = {};
3197 }
3198 }
3199 }
3200
3201 return data;
3202 }
3203 /**
3204 * Merges an updated reducer state into the persisted data.
3205 *
3206 * @param {string} key Key to update.
3207 * @param {*} value Updated value.
3208 */
3209
3210
3211 function setData(key, value) {
3212 data = { ...data,
3213 [key]: value
3214 };
3215 storage.setItem(storageKey, JSON.stringify(data));
3216 }
3217
3218 return {
3219 get: getData,
3220 set: setData
3221 };
3222 }
3223 /**
3224 * Data plugin to persist store state into a single storage key.
3225 *
3226 * @param {WPDataRegistry} registry Data registry.
3227 * @param {?WPDataPersistencePluginOptions} pluginOptions Plugin options.
3228 *
3229 * @return {WPDataPlugin} Data plugin.
3230 */
3231
3232 function persistencePlugin(registry, pluginOptions) {
3233 const persistence = createPersistenceInterface(pluginOptions);
3234 /**
3235 * Creates an enhanced store dispatch function, triggering the state of the
3236 * given store name to be persisted when changed.
3237 *
3238 * @param {Function} getState Function which returns current state.
3239 * @param {string} storeName Store name.
3240 * @param {?Array<string>} keys Optional subset of keys to save.
3241 *
3242 * @return {Function} Enhanced dispatch function.
3243 */
3244
3245 function createPersistOnChange(getState, storeName, keys) {
3246 let getPersistedState;
3247
3248 if (Array.isArray(keys)) {
3249 // Given keys, the persisted state should by produced as an object
3250 // of the subset of keys. This implementation uses combineReducers
3251 // to leverage its behavior of returning the same object when none
3252 // of the property values changes. This allows a strict reference
3253 // equality to bypass a persistence set on an unchanging state.
3254 const reducers = keys.reduce((accumulator, key) => Object.assign(accumulator, {
3255 [key]: (state, action) => action.nextState[key]
3256 }), {});
3257 getPersistedState = withLazySameState(turbo_combine_reducers_default()(reducers));
3258 } else {
3259 getPersistedState = (state, action) => action.nextState;
3260 }
3261
3262 let lastState = getPersistedState(undefined, {
3263 nextState: getState()
3264 });
3265 return () => {
3266 const state = getPersistedState(lastState, {
3267 nextState: getState()
3268 });
3269
3270 if (state !== lastState) {
3271 persistence.set(storeName, state);
3272 lastState = state;
3273 }
3274 };
3275 }
3276
3277 return {
3278 registerStore(storeName, options) {
3279 if (!options.persist) {
3280 return registry.registerStore(storeName, options);
3281 } // Load from persistence to use as initial state.
3282
3283
3284 const persistedState = persistence.get()[storeName];
3285
3286 if (persistedState !== undefined) {
3287 let initialState = options.reducer(options.initialState, {
3288 type: '@@WP/PERSISTENCE_RESTORE'
3289 });
3290
3291 if ((0,external_lodash_namespaceObject.isPlainObject)(initialState) && (0,external_lodash_namespaceObject.isPlainObject)(persistedState)) {
3292 // If state is an object, ensure that:
3293 // - Other keys are left intact when persisting only a
3294 // subset of keys.
3295 // - New keys in what would otherwise be used as initial
3296 // state are deeply merged as base for persisted value.
3297 initialState = (0,external_lodash_namespaceObject.merge)({}, initialState, persistedState);
3298 } else {
3299 // If there is a mismatch in object-likeness of default
3300 // initial or persisted state, defer to persisted value.
3301 initialState = persistedState;
3302 }
3303
3304 options = { ...options,
3305 initialState
3306 };
3307 }
3308
3309 const store = registry.registerStore(storeName, options);
3310 store.subscribe(createPersistOnChange(store.getState, storeName, options.persist));
3311 return store;
3312 }
3313
3314 };
3315 }
3316
3317 persistencePlugin.__unstableMigrate = () => {};
3318
3319 /* harmony default export */ const persistence = (persistencePlugin);
3320
3321 ;// CONCATENATED MODULE: ./packages/data/build-module/plugins/index.js
3322
3323
3324 ;// CONCATENATED MODULE: ./node_modules/@babel/runtime/helpers/esm/extends.js
3325 function _extends() {
3326 _extends = Object.assign || function (target) {
3327 for (var i = 1; i < arguments.length; i++) {
3328 var source = arguments[i];
3329
3330 for (var key in source) {
3331 if (Object.prototype.hasOwnProperty.call(source, key)) {
3332 target[key] = source[key];
3333 }
3334 }
3335 }
3336
3337 return target;
3338 };
3339
3340 return _extends.apply(this, arguments);
3341 }
3342 ;// CONCATENATED MODULE: external ["wp","element"]
3343 const external_wp_element_namespaceObject = window["wp"]["element"];
3344 ;// CONCATENATED MODULE: external ["wp","compose"]
3345 const external_wp_compose_namespaceObject = window["wp"]["compose"];
3346 ;// CONCATENATED MODULE: external "React"
3347 const external_React_namespaceObject = window["React"];
3348 ;// CONCATENATED MODULE: ./node_modules/use-memo-one/dist/use-memo-one.esm.js
3349
3350
3351 function areInputsEqual(newInputs, lastInputs) {
3352 if (newInputs.length !== lastInputs.length) {
3353 return false;
3354 }
3355
3356 for (var i = 0; i < newInputs.length; i++) {
3357 if (newInputs[i] !== lastInputs[i]) {
3358 return false;
3359 }
3360 }
3361
3362 return true;
3363 }
3364
3365 function useMemoOne(getResult, inputs) {
3366 var initial = (0,external_React_namespaceObject.useState)(function () {
3367 return {
3368 inputs: inputs,
3369 result: getResult()
3370 };
3371 })[0];
3372 var committed = (0,external_React_namespaceObject.useRef)(initial);
3373 var isInputMatch = Boolean(inputs && committed.current.inputs && areInputsEqual(inputs, committed.current.inputs));
3374 var cache = isInputMatch ? committed.current : {
3375 inputs: inputs,
3376 result: getResult()
3377 };
3378 (0,external_React_namespaceObject.useEffect)(function () {
3379 committed.current = cache;
3380 }, [cache]);
3381 return cache.result;
3382 }
3383 function useCallbackOne(callback, inputs) {
3384 return useMemoOne(function () {
3385 return callback;
3386 }, inputs);
3387 }
3388 var useMemo = (/* unused pure expression or super */ null && (useMemoOne));
3389 var useCallback = (/* unused pure expression or super */ null && (useCallbackOne));
3390
3391
3392
3393 ;// CONCATENATED MODULE: external ["wp","priorityQueue"]
3394 const external_wp_priorityQueue_namespaceObject = window["wp"]["priorityQueue"];
3395 ;// CONCATENATED MODULE: external ["wp","isShallowEqual"]
3396 const external_wp_isShallowEqual_namespaceObject = window["wp"]["isShallowEqual"];
3397 var external_wp_isShallowEqual_default = /*#__PURE__*/__webpack_require__.n(external_wp_isShallowEqual_namespaceObject);
3398 ;// CONCATENATED MODULE: ./packages/data/build-module/components/registry-provider/context.js
3399 /**
3400 * WordPress dependencies
3401 */
3402
3403 /**
3404 * Internal dependencies
3405 */
3406
3407
3408 const Context = (0,external_wp_element_namespaceObject.createContext)(default_registry);
3409 const {
3410 Consumer,
3411 Provider
3412 } = Context;
3413 /**
3414 * A custom react Context consumer exposing the provided `registry` to
3415 * children components. Used along with the RegistryProvider.
3416 *
3417 * You can read more about the react context api here:
3418 * https://reactjs.org/docs/context.html#contextprovider
3419 *
3420 * @example
3421 * ```js
3422 * import {
3423 * RegistryProvider,
3424 * RegistryConsumer,
3425 * createRegistry
3426 * } from '@wordpress/data';
3427 *
3428 * const registry = createRegistry( {} );
3429 *
3430 * const App = ( { props } ) => {
3431 * return <RegistryProvider value={ registry }>
3432 * <div>Hello There</div>
3433 * <RegistryConsumer>
3434 * { ( registry ) => (
3435 * <ComponentUsingRegistry
3436 * { ...props }
3437 * registry={ registry }
3438 * ) }
3439 * </RegistryConsumer>
3440 * </RegistryProvider>
3441 * }
3442 * ```
3443 */
3444
3445 const RegistryConsumer = Consumer;
3446 /**
3447 * A custom Context provider for exposing the provided `registry` to children
3448 * components via a consumer.
3449 *
3450 * See <a name="#RegistryConsumer">RegistryConsumer</a> documentation for
3451 * example.
3452 */
3453
3454 /* harmony default export */ const context = (Provider);
3455
3456 ;// CONCATENATED MODULE: ./packages/data/build-module/components/registry-provider/use-registry.js
3457 /**
3458 * WordPress dependencies
3459 */
3460
3461 /**
3462 * Internal dependencies
3463 */
3464
3465
3466 /**
3467 * A custom react hook exposing the registry context for use.
3468 *
3469 * This exposes the `registry` value provided via the
3470 * <a href="#RegistryProvider">Registry Provider</a> to a component implementing
3471 * this hook.
3472 *
3473 * It acts similarly to the `useContext` react hook.
3474 *
3475 * Note: Generally speaking, `useRegistry` is a low level hook that in most cases
3476 * won't be needed for implementation. Most interactions with the `@wordpress/data`
3477 * API can be performed via the `useSelect` hook, or the `withSelect` and
3478 * `withDispatch` higher order components.
3479 *
3480 * @example
3481 * ```js
3482 * import {
3483 * RegistryProvider,
3484 * createRegistry,
3485 * useRegistry,
3486 * } from '@wordpress/data';
3487 *
3488 * const registry = createRegistry( {} );
3489 *
3490 * const SomeChildUsingRegistry = ( props ) => {
3491 * const registry = useRegistry();
3492 * // ...logic implementing the registry in other react hooks.
3493 * };
3494 *
3495 *
3496 * const ParentProvidingRegistry = ( props ) => {
3497 * return <RegistryProvider value={ registry }>
3498 * <SomeChildUsingRegistry { ...props } />
3499 * </RegistryProvider>
3500 * };
3501 * ```
3502 *
3503 * @return {Function} A custom react hook exposing the registry context value.
3504 */
3505
3506 function useRegistry() {
3507 return (0,external_wp_element_namespaceObject.useContext)(Context);
3508 }
3509
3510 ;// CONCATENATED MODULE: ./packages/data/build-module/components/async-mode-provider/context.js
3511 /**
3512 * WordPress dependencies
3513 */
3514
3515 const context_Context = (0,external_wp_element_namespaceObject.createContext)(false);
3516 const {
3517 Consumer: context_Consumer,
3518 Provider: context_Provider
3519 } = context_Context;
3520 const AsyncModeConsumer = (/* unused pure expression or super */ null && (context_Consumer));
3521 /**
3522 * Context Provider Component used to switch the data module component rerendering
3523 * between Sync and Async modes.
3524 *
3525 * @example
3526 *
3527 * ```js
3528 * import { useSelect, AsyncModeProvider } from '@wordpress/data';
3529 *
3530 * function BlockCount() {
3531 * const count = useSelect( ( select ) => {
3532 * return select( 'core/block-editor' ).getBlockCount()
3533 * }, [] );
3534 *
3535 * return count;
3536 * }
3537 *
3538 * function App() {
3539 * return (
3540 * <AsyncModeProvider value={ true }>
3541 * <BlockCount />
3542 * </AsyncModeProvider>
3543 * );
3544 * }
3545 * ```
3546 *
3547 * In this example, the BlockCount component is rerendered asynchronously.
3548 * It means if a more critical task is being performed (like typing in an input),
3549 * the rerendering is delayed until the browser becomes IDLE.
3550 * It is possible to nest multiple levels of AsyncModeProvider to fine-tune the rendering behavior.
3551 *
3552 * @param {boolean} props.value Enable Async Mode.
3553 * @return {WPComponent} The component to be rendered.
3554 */
3555
3556 /* harmony default export */ const async_mode_provider_context = (context_Provider);
3557
3558 ;// CONCATENATED MODULE: ./packages/data/build-module/components/async-mode-provider/use-async-mode.js
3559 /**
3560 * WordPress dependencies
3561 */
3562
3563 /**
3564 * Internal dependencies
3565 */
3566
3567
3568 function useAsyncMode() {
3569 return (0,external_wp_element_namespaceObject.useContext)(context_Context);
3570 }
3571
3572 ;// CONCATENATED MODULE: ./packages/data/build-module/components/use-select/index.js
3573 /**
3574 * External dependencies
3575 */
3576
3577 /**
3578 * WordPress dependencies
3579 */
3580
3581
3582
3583
3584
3585 /**
3586 * Internal dependencies
3587 */
3588
3589
3590
3591
3592 const noop = () => {};
3593
3594 const renderQueue = (0,external_wp_priorityQueue_namespaceObject.createQueue)();
3595 /** @typedef {import('../../types').StoreDescriptor} StoreDescriptor */
3596
3597 /**
3598 * Custom react hook for retrieving props from registered selectors.
3599 *
3600 * In general, this custom React hook follows the
3601 * [rules of hooks](https://reactjs.org/docs/hooks-rules.html).
3602 *
3603 * @param {Function|StoreDescriptor|string} mapSelect Function called on every state change. The
3604 * returned value is exposed to the component
3605 * implementing this hook. The function receives
3606 * the `registry.select` method on the first
3607 * argument and the `registry` on the second
3608 * argument.
3609 * When a store key is passed, all selectors for
3610 * the store will be returned. This is only meant
3611 * for usage of these selectors in event
3612 * callbacks, not for data needed to create the
3613 * element tree.
3614 * @param {Array} deps If provided, this memoizes the mapSelect so the
3615 * same `mapSelect` is invoked on every state
3616 * change unless the dependencies change.
3617 *
3618 * @example
3619 * ```js
3620 * import { useSelect } from '@wordpress/data';
3621 *
3622 * function HammerPriceDisplay( { currency } ) {
3623 * const price = useSelect( ( select ) => {
3624 * return select( 'my-shop' ).getPrice( 'hammer', currency )
3625 * }, [ currency ] );
3626 * return new Intl.NumberFormat( 'en-US', {
3627 * style: 'currency',
3628 * currency,
3629 * } ).format( price );
3630 * }
3631 *
3632 * // Rendered in the application:
3633 * // <HammerPriceDisplay currency="USD" />
3634 * ```
3635 *
3636 * In the above example, when `HammerPriceDisplay` is rendered into an
3637 * application, the price will be retrieved from the store state using the
3638 * `mapSelect` callback on `useSelect`. If the currency prop changes then
3639 * any price in the state for that currency is retrieved. If the currency prop
3640 * doesn't change and other props are passed in that do change, the price will
3641 * not change because the dependency is just the currency.
3642 *
3643 * When data is only used in an event callback, the data should not be retrieved
3644 * on render, so it may be useful to get the selectors function instead.
3645 *
3646 * **Don't use `useSelect` this way when calling the selectors in the render
3647 * function because your component won't re-render on a data change.**
3648 *
3649 * ```js
3650 * import { useSelect } from '@wordpress/data';
3651 *
3652 * function Paste( { children } ) {
3653 * const { getSettings } = useSelect( 'my-shop' );
3654 * function onPaste() {
3655 * // Do something with the settings.
3656 * const settings = getSettings();
3657 * }
3658 * return <div onPaste={ onPaste }>{ children }</div>;
3659 * }
3660 * ```
3661 *
3662 * @return {Function} A custom react hook.
3663 */
3664
3665 function useSelect(mapSelect, deps) {
3666 const hasMappingFunction = 'function' === typeof mapSelect; // If we're recalling a store by its name or by
3667 // its descriptor then we won't be caching the
3668 // calls to `mapSelect` because we won't be calling it.
3669
3670 if (!hasMappingFunction) {
3671 deps = [];
3672 } // Because of the "rule of hooks" we have to call `useCallback`
3673 // on every invocation whether or not we have a real function
3674 // for `mapSelect`. we'll create this intermediate variable to
3675 // fulfill that need and then reference it with our "real"
3676 // `_mapSelect` if we can.
3677
3678
3679 const callbackMapper = (0,external_wp_element_namespaceObject.useCallback)(hasMappingFunction ? mapSelect : noop, deps);
3680
3681 const _mapSelect = hasMappingFunction ? callbackMapper : null;
3682
3683 const registry = useRegistry();
3684 const isAsync = useAsyncMode();
3685 const latestRegistry = (0,external_wp_element_namespaceObject.useRef)(registry);
3686 const latestMapSelect = (0,external_wp_element_namespaceObject.useRef)();
3687 const latestIsAsync = (0,external_wp_element_namespaceObject.useRef)(isAsync);
3688 const latestMapOutput = (0,external_wp_element_namespaceObject.useRef)();
3689 const latestMapOutputError = (0,external_wp_element_namespaceObject.useRef)(); // Keep track of the stores being selected in the _mapSelect function,
3690 // and only subscribe to those stores later.
3691
3692 const listeningStores = (0,external_wp_element_namespaceObject.useRef)([]);
3693 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.
3694 // It's different than just using `mapSelect` since deps could be undefined,
3695 // in that case, we would still want to memoize it.
3696
3697 const depsChangedFlag = (0,external_wp_element_namespaceObject.useMemo)(() => ({}), deps || []);
3698 let mapOutput;
3699
3700 if (_mapSelect) {
3701 mapOutput = latestMapOutput.current;
3702 const hasReplacedRegistry = latestRegistry.current !== registry;
3703 const hasReplacedMapSelect = latestMapSelect.current !== _mapSelect;
3704 const hasLeftAsyncMode = latestIsAsync.current && !isAsync;
3705 const lastMapSelectFailed = !!latestMapOutputError.current;
3706
3707 if (hasReplacedRegistry || hasReplacedMapSelect || hasLeftAsyncMode || lastMapSelectFailed) {
3708 try {
3709 mapOutput = wrapSelect(_mapSelect);
3710 } catch (error) {
3711 let errorMessage = `An error occurred while running 'mapSelect': ${error.message}`;
3712
3713 if (latestMapOutputError.current) {
3714 errorMessage += `\nThe error may be correlated with this previous error:\n`;
3715 errorMessage += `${latestMapOutputError.current.stack}\n\n`;
3716 errorMessage += 'Original stack trace:';
3717 } // eslint-disable-next-line no-console
3718
3719
3720 console.error(errorMessage);
3721 }
3722 }
3723 }
3724
3725 (0,external_wp_compose_namespaceObject.useIsomorphicLayoutEffect)(() => {
3726 if (!hasMappingFunction) {
3727 return;
3728 }
3729
3730 latestRegistry.current = registry;
3731 latestMapSelect.current = _mapSelect;
3732 latestIsAsync.current = isAsync;
3733 latestMapOutput.current = mapOutput;
3734 latestMapOutputError.current = undefined;
3735 }); // React can sometimes clear the `useMemo` cache.
3736 // We use the cache-stable `useMemoOne` to avoid
3737 // losing queues.
3738
3739 const queueContext = useMemoOne(() => ({
3740 queue: true
3741 }), [registry]);
3742 const [, forceRender] = (0,external_wp_element_namespaceObject.useReducer)(s => s + 1, 0);
3743 const isMounted = (0,external_wp_element_namespaceObject.useRef)(false);
3744 (0,external_wp_compose_namespaceObject.useIsomorphicLayoutEffect)(() => {
3745 if (!hasMappingFunction) {
3746 return;
3747 }
3748
3749 const onStoreChange = () => {
3750 try {
3751 const newMapOutput = wrapSelect(latestMapSelect.current);
3752
3753 if (external_wp_isShallowEqual_default()(latestMapOutput.current, newMapOutput)) {
3754 return;
3755 }
3756
3757 latestMapOutput.current = newMapOutput;
3758 } catch (error) {
3759 latestMapOutputError.current = error;
3760 }
3761
3762 forceRender();
3763 };
3764
3765 const onChange = () => {
3766 if (!isMounted.current) {
3767 return;
3768 }
3769
3770 if (latestIsAsync.current) {
3771 renderQueue.add(queueContext, onStoreChange);
3772 } else {
3773 onStoreChange();
3774 }
3775 }; // Catch any possible state changes during mount before the subscription
3776 // could be set.
3777
3778
3779 onStoreChange();
3780 const unsubscribers = listeningStores.current.map(storeName => registry.__unstableSubscribeStore(storeName, onChange));
3781 isMounted.current = true;
3782 return () => {
3783 // The return value of the subscribe function could be undefined if the store is a custom generic store.
3784 unsubscribers.forEach(unsubscribe => unsubscribe === null || unsubscribe === void 0 ? void 0 : unsubscribe());
3785 renderQueue.cancel(queueContext);
3786 isMounted.current = false;
3787 }; // If you're tempted to eliminate the spread dependencies below don't do it!
3788 // We're passing these in from the calling function and want to make sure we're
3789 // examining every individual value inside the `deps` array.
3790 }, [registry, wrapSelect, hasMappingFunction, depsChangedFlag]);
3791 return hasMappingFunction ? mapOutput : registry.select(mapSelect);
3792 }
3793 /**
3794 * A variant of the `useSelect` hook that has the same API, but will throw a
3795 * suspense Promise if any of the called selectors is in an unresolved state.
3796 *
3797 * @param {Function} mapSelect Function called on every state change. The
3798 * returned value is exposed to the component
3799 * using this hook. The function receives the
3800 * `registry.suspendSelect` method as the first
3801 * argument and the `registry` as the second one.
3802 * @param {Array} deps A dependency array used to memoize the `mapSelect`
3803 * so that the same `mapSelect` is invoked on every
3804 * state change unless the dependencies change.
3805 *
3806 * @return {Object} Data object returned by the `mapSelect` function.
3807 */
3808
3809 function useSuspenseSelect(mapSelect, deps) {
3810 const _mapSelect = (0,external_wp_element_namespaceObject.useCallback)(mapSelect, deps);
3811
3812 const registry = useRegistry();
3813 const isAsync = useAsyncMode();
3814 const latestRegistry = (0,external_wp_element_namespaceObject.useRef)(registry);
3815 const latestMapSelect = (0,external_wp_element_namespaceObject.useRef)();
3816 const latestIsAsync = (0,external_wp_element_namespaceObject.useRef)(isAsync);
3817 const latestMapOutput = (0,external_wp_element_namespaceObject.useRef)();
3818 const latestMapOutputError = (0,external_wp_element_namespaceObject.useRef)(); // Keep track of the stores being selected in the `mapSelect` function,
3819 // and only subscribe to those stores later.
3820
3821 const listeningStores = (0,external_wp_element_namespaceObject.useRef)([]);
3822 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.
3823 // It's different than just using `mapSelect` since deps could be undefined,
3824 // in that case, we would still want to memoize it.
3825
3826 const depsChangedFlag = (0,external_wp_element_namespaceObject.useMemo)(() => ({}), deps || []);
3827 let mapOutput = latestMapOutput.current;
3828 let mapOutputError = latestMapOutputError.current;
3829 const hasReplacedRegistry = latestRegistry.current !== registry;
3830 const hasReplacedMapSelect = latestMapSelect.current !== _mapSelect;
3831 const hasLeftAsyncMode = latestIsAsync.current && !isAsync;
3832
3833 if (hasReplacedRegistry || hasReplacedMapSelect || hasLeftAsyncMode) {
3834 try {
3835 mapOutput = wrapSelect(_mapSelect);
3836 } catch (error) {
3837 mapOutputError = error;
3838 }
3839 }
3840
3841 (0,external_wp_compose_namespaceObject.useIsomorphicLayoutEffect)(() => {
3842 latestRegistry.current = registry;
3843 latestMapSelect.current = _mapSelect;
3844 latestIsAsync.current = isAsync;
3845 latestMapOutput.current = mapOutput;
3846 latestMapOutputError.current = mapOutputError;
3847 }); // React can sometimes clear the `useMemo` cache.
3848 // We use the cache-stable `useMemoOne` to avoid
3849 // losing queues.
3850
3851 const queueContext = useMemoOne(() => ({
3852 queue: true
3853 }), [registry]);
3854 const [, forceRender] = (0,external_wp_element_namespaceObject.useReducer)(s => s + 1, 0);
3855 const isMounted = (0,external_wp_element_namespaceObject.useRef)(false);
3856 (0,external_wp_compose_namespaceObject.useIsomorphicLayoutEffect)(() => {
3857 const onStoreChange = () => {
3858 try {
3859 const newMapOutput = wrapSelect(latestMapSelect.current);
3860
3861 if (external_wp_isShallowEqual_default()(latestMapOutput.current, newMapOutput)) {
3862 return;
3863 }
3864
3865 latestMapOutput.current = newMapOutput;
3866 } catch (error) {
3867 latestMapOutputError.current = error;
3868 }
3869
3870 forceRender();
3871 };
3872
3873 const onChange = () => {
3874 if (!isMounted.current) {
3875 return;
3876 }
3877
3878 if (latestIsAsync.current) {
3879 renderQueue.add(queueContext, onStoreChange);
3880 } else {
3881 onStoreChange();
3882 }
3883 }; // catch any possible state changes during mount before the subscription
3884 // could be set.
3885
3886
3887 onStoreChange();
3888 const unsubscribers = listeningStores.current.map(storeName => registry.__unstableSubscribeStore(storeName, onChange));
3889 isMounted.current = true;
3890 return () => {
3891 // The return value of the subscribe function could be undefined if the store is a custom generic store.
3892 unsubscribers.forEach(unsubscribe => unsubscribe === null || unsubscribe === void 0 ? void 0 : unsubscribe());
3893 renderQueue.cancel(queueContext);
3894 isMounted.current = false;
3895 };
3896 }, [registry, wrapSelect, depsChangedFlag]);
3897
3898 if (mapOutputError) {
3899 throw mapOutputError;
3900 }
3901
3902 return mapOutput;
3903 }
3904
3905 ;// CONCATENATED MODULE: ./packages/data/build-module/components/with-select/index.js
3906
3907
3908
3909 /**
3910 * WordPress dependencies
3911 */
3912
3913 /**
3914 * Internal dependencies
3915 */
3916
3917
3918 /**
3919 * Higher-order component used to inject state-derived props using registered
3920 * selectors.
3921 *
3922 * @param {Function} mapSelectToProps Function called on every state change,
3923 * expected to return object of props to
3924 * merge with the component's own props.
3925 *
3926 * @example
3927 * ```js
3928 * import { withSelect } from '@wordpress/data';
3929 *
3930 * function PriceDisplay( { price, currency } ) {
3931 * return new Intl.NumberFormat( 'en-US', {
3932 * style: 'currency',
3933 * currency,
3934 * } ).format( price );
3935 * }
3936 *
3937 * const HammerPriceDisplay = withSelect( ( select, ownProps ) => {
3938 * const { getPrice } = select( 'my-shop' );
3939 * const { currency } = ownProps;
3940 *
3941 * return {
3942 * price: getPrice( 'hammer', currency ),
3943 * };
3944 * } )( PriceDisplay );
3945 *
3946 * // Rendered in the application:
3947 * //
3948 * // <HammerPriceDisplay currency="USD" />
3949 * ```
3950 * In the above example, when `HammerPriceDisplay` is rendered into an
3951 * application, it will pass the price into the underlying `PriceDisplay`
3952 * component and update automatically if the price of a hammer ever changes in
3953 * the store.
3954 *
3955 * @return {WPComponent} Enhanced component with merged state data props.
3956 */
3957
3958 const withSelect = mapSelectToProps => (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(WrappedComponent => (0,external_wp_compose_namespaceObject.pure)(ownProps => {
3959 const mapSelect = (select, registry) => mapSelectToProps(select, ownProps, registry);
3960
3961 const mergeProps = useSelect(mapSelect);
3962 return (0,external_wp_element_namespaceObject.createElement)(WrappedComponent, _extends({}, ownProps, mergeProps));
3963 }), 'withSelect');
3964
3965 /* harmony default export */ const with_select = (withSelect);
3966
3967 ;// CONCATENATED MODULE: ./packages/data/build-module/components/use-dispatch/use-dispatch-with-map.js
3968 /**
3969 * External dependencies
3970 */
3971
3972 /**
3973 * WordPress dependencies
3974 */
3975
3976
3977
3978 /**
3979 * Internal dependencies
3980 */
3981
3982
3983 /**
3984 * Custom react hook for returning aggregate dispatch actions using the provided
3985 * dispatchMap.
3986 *
3987 * Currently this is an internal api only and is implemented by `withDispatch`
3988 *
3989 * @param {Function} dispatchMap Receives the `registry.dispatch` function as
3990 * the first argument and the `registry` object
3991 * as the second argument. Should return an
3992 * object mapping props to functions.
3993 * @param {Array} deps An array of dependencies for the hook.
3994 * @return {Object} An object mapping props to functions created by the passed
3995 * in dispatchMap.
3996 */
3997
3998 const useDispatchWithMap = (dispatchMap, deps) => {
3999 const registry = useRegistry();
4000 const currentDispatchMap = (0,external_wp_element_namespaceObject.useRef)(dispatchMap);
4001 (0,external_wp_compose_namespaceObject.useIsomorphicLayoutEffect)(() => {
4002 currentDispatchMap.current = dispatchMap;
4003 });
4004 return (0,external_wp_element_namespaceObject.useMemo)(() => {
4005 const currentDispatchProps = currentDispatchMap.current(registry.dispatch, registry);
4006 return (0,external_lodash_namespaceObject.mapValues)(currentDispatchProps, (dispatcher, propName) => {
4007 if (typeof dispatcher !== 'function') {
4008 // eslint-disable-next-line no-console
4009 console.warn(`Property ${propName} returned from dispatchMap in useDispatchWithMap must be a function.`);
4010 }
4011
4012 return function () {
4013 return currentDispatchMap.current(registry.dispatch, registry)[propName](...arguments);
4014 };
4015 });
4016 }, [registry, ...deps]);
4017 };
4018
4019 /* harmony default export */ const use_dispatch_with_map = (useDispatchWithMap);
4020
4021 ;// CONCATENATED MODULE: ./packages/data/build-module/components/with-dispatch/index.js
4022
4023
4024
4025 /**
4026 * WordPress dependencies
4027 */
4028
4029 /**
4030 * Internal dependencies
4031 */
4032
4033
4034 /**
4035 * Higher-order component used to add dispatch props using registered action
4036 * creators.
4037 *
4038 * @param {Function} mapDispatchToProps A function of returning an object of
4039 * prop names where value is a
4040 * dispatch-bound action creator, or a
4041 * function to be called with the
4042 * component's props and returning an
4043 * action creator.
4044 *
4045 * @example
4046 * ```jsx
4047 * function Button( { onClick, children } ) {
4048 * return <button type="button" onClick={ onClick }>{ children }</button>;
4049 * }
4050 *
4051 * import { withDispatch } from '@wordpress/data';
4052 *
4053 * const SaleButton = withDispatch( ( dispatch, ownProps ) => {
4054 * const { startSale } = dispatch( 'my-shop' );
4055 * const { discountPercent } = ownProps;
4056 *
4057 * return {
4058 * onClick() {
4059 * startSale( discountPercent );
4060 * },
4061 * };
4062 * } )( Button );
4063 *
4064 * // Rendered in the application:
4065 * //
4066 * // <SaleButton discountPercent="20">Start Sale!</SaleButton>
4067 * ```
4068 *
4069 * @example
4070 * In the majority of cases, it will be sufficient to use only two first params
4071 * passed to `mapDispatchToProps` as illustrated in the previous example.
4072 * However, there might be some very advanced use cases where using the
4073 * `registry` object might be used as a tool to optimize the performance of
4074 * your component. Using `select` function from the registry might be useful
4075 * when you need to fetch some dynamic data from the store at the time when the
4076 * event is fired, but at the same time, you never use it to render your
4077 * component. In such scenario, you can avoid using the `withSelect` higher
4078 * order component to compute such prop, which might lead to unnecessary
4079 * re-renders of your component caused by its frequent value change.
4080 * Keep in mind, that `mapDispatchToProps` must return an object with functions
4081 * only.
4082 *
4083 * ```jsx
4084 * function Button( { onClick, children } ) {
4085 * return <button type="button" onClick={ onClick }>{ children }</button>;
4086 * }
4087 *
4088 * import { withDispatch } from '@wordpress/data';
4089 *
4090 * const SaleButton = withDispatch( ( dispatch, ownProps, { select } ) => {
4091 * // Stock number changes frequently.
4092 * const { getStockNumber } = select( 'my-shop' );
4093 * const { startSale } = dispatch( 'my-shop' );
4094 * return {
4095 * onClick() {
4096 * const discountPercent = getStockNumber() > 50 ? 10 : 20;
4097 * startSale( discountPercent );
4098 * },
4099 * };
4100 * } )( Button );
4101 *
4102 * // Rendered in the application:
4103 * //
4104 * // <SaleButton>Start Sale!</SaleButton>
4105 * ```
4106 *
4107 * _Note:_ It is important that the `mapDispatchToProps` function always
4108 * returns an object with the same keys. For example, it should not contain
4109 * conditions under which a different value would be returned.
4110 *
4111 * @return {WPComponent} Enhanced component with merged dispatcher props.
4112 */
4113
4114 const withDispatch = mapDispatchToProps => (0,external_wp_compose_namespaceObject.createHigherOrderComponent)(WrappedComponent => ownProps => {
4115 const mapDispatch = (dispatch, registry) => mapDispatchToProps(dispatch, ownProps, registry);
4116
4117 const dispatchProps = use_dispatch_with_map(mapDispatch, []);
4118 return (0,external_wp_element_namespaceObject.createElement)(WrappedComponent, _extends({}, ownProps, dispatchProps));
4119 }, 'withDispatch');
4120
4121 /* harmony default export */ const with_dispatch = (withDispatch);
4122
4123 ;// CONCATENATED MODULE: ./packages/data/build-module/components/with-registry/index.js
4124
4125
4126
4127 /**
4128 * WordPress dependencies
4129 */
4130
4131 /**
4132 * Internal dependencies
4133 */
4134
4135
4136 /**
4137 * Higher-order component which renders the original component with the current
4138 * registry context passed as its `registry` prop.
4139 *
4140 * @param {WPComponent} OriginalComponent Original component.
4141 *
4142 * @return {WPComponent} Enhanced component.
4143 */
4144
4145 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, {
4146 registry: registry
4147 }))), 'withRegistry');
4148 /* harmony default export */ const with_registry = (withRegistry);
4149
4150 ;// CONCATENATED MODULE: ./packages/data/build-module/components/use-dispatch/use-dispatch.js
4151 /**
4152 * Internal dependencies
4153 */
4154
4155 /** @typedef {import('../../types').StoreDescriptor} StoreDescriptor */
4156
4157 /**
4158 * A custom react hook returning the current registry dispatch actions creators.
4159 *
4160 * Note: The component using this hook must be within the context of a
4161 * RegistryProvider.
4162 *
4163 * @param {string|StoreDescriptor} [storeNameOrDescriptor] Optionally provide the name of the
4164 * store or its descriptor from which to
4165 * retrieve action creators. If not
4166 * provided, the registry.dispatch
4167 * function is returned instead.
4168 *
4169 * @example
4170 * This illustrates a pattern where you may need to retrieve dynamic data from
4171 * the server via the `useSelect` hook to use in combination with the dispatch
4172 * action.
4173 *
4174 * ```jsx
4175 * import { useDispatch, useSelect } from '@wordpress/data';
4176 * import { useCallback } from '@wordpress/element';
4177 *
4178 * function Button( { onClick, children } ) {
4179 * return <button type="button" onClick={ onClick }>{ children }</button>
4180 * }
4181 *
4182 * const SaleButton = ( { children } ) => {
4183 * const { stockNumber } = useSelect(
4184 * ( select ) => select( 'my-shop' ).getStockNumber(),
4185 * []
4186 * );
4187 * const { startSale } = useDispatch( 'my-shop' );
4188 * const onClick = useCallback( () => {
4189 * const discountPercent = stockNumber > 50 ? 10: 20;
4190 * startSale( discountPercent );
4191 * }, [ stockNumber ] );
4192 * return <Button onClick={ onClick }>{ children }</Button>
4193 * }
4194 *
4195 * // Rendered somewhere in the application:
4196 * //
4197 * // <SaleButton>Start Sale!</SaleButton>
4198 * ```
4199 * @return {Function} A custom react hook.
4200 */
4201
4202 const useDispatch = storeNameOrDescriptor => {
4203 const {
4204 dispatch
4205 } = useRegistry();
4206 return storeNameOrDescriptor === void 0 ? dispatch : dispatch(storeNameOrDescriptor);
4207 };
4208
4209 /* harmony default export */ const use_dispatch = (useDispatch);
4210
4211 ;// CONCATENATED MODULE: ./packages/data/build-module/index.js
4212 /**
4213 * External dependencies
4214 */
4215
4216 /**
4217 * Internal dependencies
4218 */
4219
4220
4221
4222 /** @typedef {import('./types').StoreDescriptor} StoreDescriptor */
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235 /**
4236 * Object of available plugins to use with a registry.
4237 *
4238 * @see [use](#use)
4239 *
4240 * @type {Object}
4241 */
4242
4243
4244 /**
4245 * The combineReducers helper function turns an object whose values are different
4246 * reducing functions into a single reducing function you can pass to registerReducer.
4247 *
4248 * @param {Object} reducers An object whose values correspond to different reducing
4249 * functions that need to be combined into one.
4250 *
4251 * @example
4252 * ```js
4253 * import { combineReducers, createReduxStore, register } from '@wordpress/data';
4254 *
4255 * const prices = ( state = {}, action ) => {
4256 * return action.type === 'SET_PRICE' ?
4257 * {
4258 * ...state,
4259 * [ action.item ]: action.price,
4260 * } :
4261 * state;
4262 * };
4263 *
4264 * const discountPercent = ( state = 0, action ) => {
4265 * return action.type === 'START_SALE' ?
4266 * action.discountPercent :
4267 * state;
4268 * };
4269 *
4270 * const store = createReduxStore( 'my-shop', {
4271 * reducer: combineReducers( {
4272 * prices,
4273 * discountPercent,
4274 * } ),
4275 * } );
4276 * register( store );
4277 * ```
4278 *
4279 * @return {Function} A reducer that invokes every reducer inside the reducers
4280 * object, and constructs a state object with the same shape.
4281 */
4282
4283
4284 /**
4285 * Given the name or descriptor of a registered store, returns an object of the store's selectors.
4286 * The selector functions are been pre-bound to pass the current state automatically.
4287 * As a consumer, you need only pass arguments of the selector, if applicable.
4288 *
4289 * @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
4290 * or the store descriptor.
4291 *
4292 * @example
4293 * ```js
4294 * import { select } from '@wordpress/data';
4295 *
4296 * select( 'my-shop' ).getPrice( 'hammer' );
4297 * ```
4298 *
4299 * @return {Object} Object containing the store's selectors.
4300 */
4301
4302 const build_module_select = default_registry.select;
4303 /**
4304 * Given the name of a registered store, returns an object containing the store's
4305 * selectors pre-bound to state so that you only need to supply additional arguments,
4306 * and modified so that they return promises that resolve to their eventual values,
4307 * after any resolvers have ran.
4308 *
4309 * @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
4310 * or the store descriptor.
4311 *
4312 * @example
4313 * ```js
4314 * import { resolveSelect } from '@wordpress/data';
4315 *
4316 * resolveSelect( 'my-shop' ).getPrice( 'hammer' ).then(console.log)
4317 * ```
4318 *
4319 * @return {Object} Object containing the store's promise-wrapped selectors.
4320 */
4321
4322 const build_module_resolveSelect = default_registry.resolveSelect;
4323 /**
4324 * Given the name of a registered store, returns an object containing the store's
4325 * selectors pre-bound to state so that you only need to supply additional arguments,
4326 * and modified so that they throw promises in case the selector is not resolved yet.
4327 *
4328 * @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
4329 * or the store descriptor.
4330 *
4331 * @return {Object} Object containing the store's suspense-wrapped selectors.
4332 */
4333
4334 const suspendSelect = default_registry.suspendSelect;
4335 /**
4336 * Given the name of a registered store, returns an object of the store's action creators.
4337 * Calling an action creator will cause it to be dispatched, updating the state value accordingly.
4338 *
4339 * Note: Action creators returned by the dispatch will return a promise when
4340 * they are called.
4341 *
4342 * @param {string|StoreDescriptor} storeNameOrDescriptor Unique namespace identifier for the store
4343 * or the store descriptor.
4344 *
4345 * @example
4346 * ```js
4347 * import { dispatch } from '@wordpress/data';
4348 *
4349 * dispatch( 'my-shop' ).setPrice( 'hammer', 9.75 );
4350 * ```
4351 * @return {Object} Object containing the action creators.
4352 */
4353
4354 const build_module_dispatch = default_registry.dispatch;
4355 /**
4356 * Given a listener function, the function will be called any time the state value
4357 * of one of the registered stores has changed. This function returns a `unsubscribe`
4358 * function used to stop the subscription.
4359 *
4360 * @param {Function} listener Callback function.
4361 *
4362 * @example
4363 * ```js
4364 * import { subscribe } from '@wordpress/data';
4365 *
4366 * const unsubscribe = subscribe( () => {
4367 * // You could use this opportunity to test whether the derived result of a
4368 * // selector has subsequently changed as the result of a state update.
4369 * } );
4370 *
4371 * // Later, if necessary...
4372 * unsubscribe();
4373 * ```
4374 */
4375
4376 const subscribe = default_registry.subscribe;
4377 /**
4378 * Registers a generic store instance.
4379 *
4380 * @deprecated Use `register( storeDescriptor )` instead.
4381 *
4382 * @param {string} name Store registry name.
4383 * @param {Object} store Store instance (`{ getSelectors, getActions, subscribe }`).
4384 */
4385
4386 const registerGenericStore = default_registry.registerGenericStore;
4387 /**
4388 * Registers a standard `@wordpress/data` store.
4389 *
4390 * @deprecated Use `register` instead.
4391 *
4392 * @param {string} storeName Unique namespace identifier for the store.
4393 * @param {Object} options Store description (reducer, actions, selectors, resolvers).
4394 *
4395 * @return {Object} Registered store object.
4396 */
4397
4398 const registerStore = default_registry.registerStore;
4399 /**
4400 * Extends a registry to inherit functionality provided by a given plugin. A
4401 * plugin is an object with properties aligning to that of a registry, merged
4402 * to extend the default registry behavior.
4403 *
4404 * @param {Object} plugin Plugin object.
4405 */
4406
4407 const use = default_registry.use;
4408 /**
4409 * Registers a standard `@wordpress/data` store descriptor.
4410 *
4411 * @example
4412 * ```js
4413 * import { createReduxStore, register } from '@wordpress/data';
4414 *
4415 * const store = createReduxStore( 'demo', {
4416 * reducer: ( state = 'OK' ) => state,
4417 * selectors: {
4418 * getValue: ( state ) => state,
4419 * },
4420 * } );
4421 * register( store );
4422 * ```
4423 *
4424 * @param {StoreDescriptor} store Store descriptor.
4425 */
4426
4427 const register = default_registry.register;
4428
4429 })();
4430
4431 (window.wp = window.wp || {}).data = __webpack_exports__;
4432 /******/ })()
4433 ;