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

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