PluginProbe
Gutenberg / 13.0.0
Gutenberg v13.0.0
24.0.0 23.9.1 23.9.0 23.8.0 23.7.2 23.7.1 23.7.0 23.6.1 23.6.2 23.6.0 23.5.3 23.5.2 23.5.1 23.5.0 23.4.0 23.3.2 23.3.1 23.3.0 23.2.0 23.2.1 23.2.2 23.1.1 23.1.0 23.0.1 12.6.0 All 403 releases
gutenberg / build / data / index.js

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

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