PluginProbe
Gutenberg / 12.6.0
Gutenberg v12.6.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 7.4.0 All 402 releases
gutenberg / build / data / index.js

index.js in Gutenberg 12.6.0, at build/data/index.js

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