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

index.js in Gutenberg 14.8.2, at build/core-data/index.js

7,208 lines 216.6 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 /******/ (function() { // webpackBootstrap
2 /******/ var __webpack_modules__ = ({
3
4 /***/ 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 /***/ 5619:
320 /***/ (function(module) {
321
322 "use strict";
323
324
325 // do not edit .js files directly - edit src/index.jst
326
327
328 var envHasBigInt64Array = typeof BigInt64Array !== 'undefined';
329
330
331 module.exports = function equal(a, b) {
332 if (a === b) return true;
333
334 if (a && b && typeof a == 'object' && typeof b == 'object') {
335 if (a.constructor !== b.constructor) return false;
336
337 var length, i, keys;
338 if (Array.isArray(a)) {
339 length = a.length;
340 if (length != b.length) return false;
341 for (i = length; i-- !== 0;)
342 if (!equal(a[i], b[i])) return false;
343 return true;
344 }
345
346
347 if ((a instanceof Map) && (b instanceof Map)) {
348 if (a.size !== b.size) return false;
349 for (i of a.entries())
350 if (!b.has(i[0])) return false;
351 for (i of a.entries())
352 if (!equal(i[1], b.get(i[0]))) return false;
353 return true;
354 }
355
356 if ((a instanceof Set) && (b instanceof Set)) {
357 if (a.size !== b.size) return false;
358 for (i of a.entries())
359 if (!b.has(i[0])) return false;
360 return true;
361 }
362
363 if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
364 length = a.length;
365 if (length != b.length) return false;
366 for (i = length; i-- !== 0;)
367 if (a[i] !== b[i]) return false;
368 return true;
369 }
370
371
372 if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
373 if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
374 if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
375
376 keys = Object.keys(a);
377 length = keys.length;
378 if (length !== Object.keys(b).length) return false;
379
380 for (i = length; i-- !== 0;)
381 if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
382
383 for (i = length; i-- !== 0;) {
384 var key = keys[i];
385
386 if (!equal(a[key], b[key])) return false;
387 }
388
389 return true;
390 }
391
392 // true if both NaN, false otherwise
393 return a!==a && b!==b;
394 };
395
396
397 /***/ }),
398
399 /***/ 9756:
400 /***/ (function(module) {
401
402 /**
403 * Memize options object.
404 *
405 * @typedef MemizeOptions
406 *
407 * @property {number} [maxSize] Maximum size of the cache.
408 */
409
410 /**
411 * Internal cache entry.
412 *
413 * @typedef MemizeCacheNode
414 *
415 * @property {?MemizeCacheNode|undefined} [prev] Previous node.
416 * @property {?MemizeCacheNode|undefined} [next] Next node.
417 * @property {Array<*>} args Function arguments for cache
418 * entry.
419 * @property {*} val Function result.
420 */
421
422 /**
423 * Properties of the enhanced function for controlling cache.
424 *
425 * @typedef MemizeMemoizedFunction
426 *
427 * @property {()=>void} clear Clear the cache.
428 */
429
430 /**
431 * Accepts a function to be memoized, and returns a new memoized function, with
432 * optional options.
433 *
434 * @template {Function} F
435 *
436 * @param {F} fn Function to memoize.
437 * @param {MemizeOptions} [options] Options object.
438 *
439 * @return {F & MemizeMemoizedFunction} Memoized function.
440 */
441 function memize( fn, options ) {
442 var size = 0;
443
444 /** @type {?MemizeCacheNode|undefined} */
445 var head;
446
447 /** @type {?MemizeCacheNode|undefined} */
448 var tail;
449
450 options = options || {};
451
452 function memoized( /* ...args */ ) {
453 var node = head,
454 len = arguments.length,
455 args, i;
456
457 searchCache: while ( node ) {
458 // Perform a shallow equality test to confirm that whether the node
459 // under test is a candidate for the arguments passed. Two arrays
460 // are shallowly equal if their length matches and each entry is
461 // strictly equal between the two sets. Avoid abstracting to a
462 // function which could incur an arguments leaking deoptimization.
463
464 // Check whether node arguments match arguments length
465 if ( node.args.length !== arguments.length ) {
466 node = node.next;
467 continue;
468 }
469
470 // Check whether node arguments match arguments values
471 for ( i = 0; i < len; i++ ) {
472 if ( node.args[ i ] !== arguments[ i ] ) {
473 node = node.next;
474 continue searchCache;
475 }
476 }
477
478 // At this point we can assume we've found a match
479
480 // Surface matched node to head if not already
481 if ( node !== head ) {
482 // As tail, shift to previous. Must only shift if not also
483 // head, since if both head and tail, there is no previous.
484 if ( node === tail ) {
485 tail = node.prev;
486 }
487
488 // Adjust siblings to point to each other. If node was tail,
489 // this also handles new tail's empty `next` assignment.
490 /** @type {MemizeCacheNode} */ ( node.prev ).next = node.next;
491 if ( node.next ) {
492 node.next.prev = node.prev;
493 }
494
495 node.next = head;
496 node.prev = null;
497 /** @type {MemizeCacheNode} */ ( head ).prev = node;
498 head = node;
499 }
500
501 // Return immediately
502 return node.val;
503 }
504
505 // No cached value found. Continue to insertion phase:
506
507 // Create a copy of arguments (avoid leaking deoptimization)
508 args = new Array( len );
509 for ( i = 0; i < len; i++ ) {
510 args[ i ] = arguments[ i ];
511 }
512
513 node = {
514 args: args,
515
516 // Generate the result from original function
517 val: fn.apply( null, args ),
518 };
519
520 // Don't need to check whether node is already head, since it would
521 // have been returned above already if it was
522
523 // Shift existing head down list
524 if ( head ) {
525 head.prev = node;
526 node.next = head;
527 } else {
528 // If no head, follows that there's no tail (at initial or reset)
529 tail = node;
530 }
531
532 // Trim tail if we're reached max size and are pending cache insertion
533 if ( size === /** @type {MemizeOptions} */ ( options ).maxSize ) {
534 tail = /** @type {MemizeCacheNode} */ ( tail ).prev;
535 /** @type {MemizeCacheNode} */ ( tail ).next = null;
536 } else {
537 size++;
538 }
539
540 head = node;
541
542 return node.val;
543 }
544
545 memoized.clear = function() {
546 head = null;
547 tail = null;
548 size = 0;
549 };
550
551 if ( false ) {}
552
553 // Ignore reason: There's not a clear solution to create an intersection of
554 // the function with additional properties, where the goal is to retain the
555 // function signature of the incoming argument and add control properties
556 // on the return value.
557
558 // @ts-ignore
559 return memoized;
560 }
561
562 module.exports = memize;
563
564
565 /***/ })
566
567 /******/ });
568 /************************************************************************/
569 /******/ // The module cache
570 /******/ var __webpack_module_cache__ = {};
571 /******/
572 /******/ // The require function
573 /******/ function __webpack_require__(moduleId) {
574 /******/ // Check if module is in cache
575 /******/ var cachedModule = __webpack_module_cache__[moduleId];
576 /******/ if (cachedModule !== undefined) {
577 /******/ return cachedModule.exports;
578 /******/ }
579 /******/ // Create a new module (and put it into the cache)
580 /******/ var module = __webpack_module_cache__[moduleId] = {
581 /******/ // no module.id needed
582 /******/ // no module.loaded needed
583 /******/ exports: {}
584 /******/ };
585 /******/
586 /******/ // Execute the module function
587 /******/ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
588 /******/
589 /******/ // Return the exports of the module
590 /******/ return module.exports;
591 /******/ }
592 /******/
593 /************************************************************************/
594 /******/ /* webpack/runtime/compat get default export */
595 /******/ !function() {
596 /******/ // getDefaultExport function for compatibility with non-harmony modules
597 /******/ __webpack_require__.n = function(module) {
598 /******/ var getter = module && module.__esModule ?
599 /******/ function() { return module['default']; } :
600 /******/ function() { return module; };
601 /******/ __webpack_require__.d(getter, { a: getter });
602 /******/ return getter;
603 /******/ };
604 /******/ }();
605 /******/
606 /******/ /* webpack/runtime/define property getters */
607 /******/ !function() {
608 /******/ // define getter functions for harmony exports
609 /******/ __webpack_require__.d = function(exports, definition) {
610 /******/ for(var key in definition) {
611 /******/ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
612 /******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
613 /******/ }
614 /******/ }
615 /******/ };
616 /******/ }();
617 /******/
618 /******/ /* webpack/runtime/hasOwnProperty shorthand */
619 /******/ !function() {
620 /******/ __webpack_require__.o = function(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }
621 /******/ }();
622 /******/
623 /******/ /* webpack/runtime/make namespace object */
624 /******/ !function() {
625 /******/ // define __esModule on exports
626 /******/ __webpack_require__.r = function(exports) {
627 /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
628 /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
629 /******/ }
630 /******/ Object.defineProperty(exports, '__esModule', { value: true });
631 /******/ };
632 /******/ }();
633 /******/
634 /************************************************************************/
635 var __webpack_exports__ = {};
636 // This entry need to be wrapped in an IIFE because it need to be in strict mode.
637 !function() {
638 "use strict";
639 // ESM COMPAT FLAG
640 __webpack_require__.r(__webpack_exports__);
641
642 // EXPORTS
643 __webpack_require__.d(__webpack_exports__, {
644 "EntityProvider": function() { return /* reexport */ EntityProvider; },
645 "__experimentalFetchLinkSuggestions": function() { return /* reexport */ _experimental_fetch_link_suggestions; },
646 "__experimentalFetchMedia": function() { return /* reexport */ fetchMedia; },
647 "__experimentalFetchUrlData": function() { return /* reexport */ _experimental_fetch_url_data; },
648 "__experimentalUseEntityRecord": function() { return /* reexport */ __experimentalUseEntityRecord; },
649 "__experimentalUseEntityRecords": function() { return /* reexport */ __experimentalUseEntityRecords; },
650 "__experimentalUseResourcePermissions": function() { return /* reexport */ __experimentalUseResourcePermissions; },
651 "store": function() { return /* binding */ store; },
652 "useEntityBlockEditor": function() { return /* reexport */ useEntityBlockEditor; },
653 "useEntityId": function() { return /* reexport */ useEntityId; },
654 "useEntityProp": function() { return /* reexport */ useEntityProp; },
655 "useEntityRecord": function() { return /* reexport */ useEntityRecord; },
656 "useEntityRecords": function() { return /* reexport */ useEntityRecords; },
657 "useResourcePermissions": function() { return /* reexport */ useResourcePermissions; }
658 });
659
660 // NAMESPACE OBJECT: ./packages/core-data/build-module/actions.js
661 var build_module_actions_namespaceObject = {};
662 __webpack_require__.r(build_module_actions_namespaceObject);
663 __webpack_require__.d(build_module_actions_namespaceObject, {
664 "__experimentalBatch": function() { return __experimentalBatch; },
665 "__experimentalReceiveCurrentGlobalStylesId": function() { return __experimentalReceiveCurrentGlobalStylesId; },
666 "__experimentalReceiveThemeBaseGlobalStyles": function() { return __experimentalReceiveThemeBaseGlobalStyles; },
667 "__experimentalReceiveThemeGlobalStyleVariations": function() { return __experimentalReceiveThemeGlobalStyleVariations; },
668 "__experimentalSaveSpecifiedEntityEdits": function() { return __experimentalSaveSpecifiedEntityEdits; },
669 "__unstableCreateUndoLevel": function() { return __unstableCreateUndoLevel; },
670 "addEntities": function() { return addEntities; },
671 "deleteEntityRecord": function() { return deleteEntityRecord; },
672 "editEntityRecord": function() { return editEntityRecord; },
673 "receiveAutosaves": function() { return receiveAutosaves; },
674 "receiveCurrentTheme": function() { return receiveCurrentTheme; },
675 "receiveCurrentUser": function() { return receiveCurrentUser; },
676 "receiveEmbedPreview": function() { return receiveEmbedPreview; },
677 "receiveEntityRecords": function() { return receiveEntityRecords; },
678 "receiveThemeSupports": function() { return receiveThemeSupports; },
679 "receiveUploadPermissions": function() { return receiveUploadPermissions; },
680 "receiveUserPermission": function() { return receiveUserPermission; },
681 "receiveUserQuery": function() { return receiveUserQuery; },
682 "redo": function() { return redo; },
683 "saveEditedEntityRecord": function() { return saveEditedEntityRecord; },
684 "saveEntityRecord": function() { return saveEntityRecord; },
685 "undo": function() { return undo; }
686 });
687
688 // NAMESPACE OBJECT: ./packages/core-data/build-module/selectors.js
689 var build_module_selectors_namespaceObject = {};
690 __webpack_require__.r(build_module_selectors_namespaceObject);
691 __webpack_require__.d(build_module_selectors_namespaceObject, {
692 "__experimentalGetCurrentGlobalStylesId": function() { return __experimentalGetCurrentGlobalStylesId; },
693 "__experimentalGetCurrentThemeBaseGlobalStyles": function() { return __experimentalGetCurrentThemeBaseGlobalStyles; },
694 "__experimentalGetCurrentThemeGlobalStylesVariations": function() { return __experimentalGetCurrentThemeGlobalStylesVariations; },
695 "__experimentalGetDirtyEntityRecords": function() { return __experimentalGetDirtyEntityRecords; },
696 "__experimentalGetEntitiesBeingSaved": function() { return __experimentalGetEntitiesBeingSaved; },
697 "__experimentalGetEntityRecordNoResolver": function() { return __experimentalGetEntityRecordNoResolver; },
698 "__experimentalGetTemplateForLink": function() { return __experimentalGetTemplateForLink; },
699 "canUser": function() { return canUser; },
700 "canUserEditEntityRecord": function() { return canUserEditEntityRecord; },
701 "getAuthors": function() { return getAuthors; },
702 "getAutosave": function() { return getAutosave; },
703 "getAutosaves": function() { return getAutosaves; },
704 "getBlockPatternCategories": function() { return getBlockPatternCategories; },
705 "getBlockPatterns": function() { return getBlockPatterns; },
706 "getCurrentTheme": function() { return getCurrentTheme; },
707 "getCurrentUser": function() { return getCurrentUser; },
708 "getEditedEntityRecord": function() { return getEditedEntityRecord; },
709 "getEmbedPreview": function() { return getEmbedPreview; },
710 "getEntitiesByKind": function() { return getEntitiesByKind; },
711 "getEntitiesConfig": function() { return getEntitiesConfig; },
712 "getEntity": function() { return getEntity; },
713 "getEntityConfig": function() { return getEntityConfig; },
714 "getEntityRecord": function() { return getEntityRecord; },
715 "getEntityRecordEdits": function() { return getEntityRecordEdits; },
716 "getEntityRecordNonTransientEdits": function() { return getEntityRecordNonTransientEdits; },
717 "getEntityRecords": function() { return getEntityRecords; },
718 "getLastEntityDeleteError": function() { return getLastEntityDeleteError; },
719 "getLastEntitySaveError": function() { return getLastEntitySaveError; },
720 "getRawEntityRecord": function() { return getRawEntityRecord; },
721 "getRedoEdit": function() { return getRedoEdit; },
722 "getReferenceByDistinctEdits": function() { return getReferenceByDistinctEdits; },
723 "getThemeSupports": function() { return getThemeSupports; },
724 "getUndoEdit": function() { return getUndoEdit; },
725 "getUserQueryResults": function() { return getUserQueryResults; },
726 "hasEditsForEntityRecord": function() { return hasEditsForEntityRecord; },
727 "hasEntityRecords": function() { return hasEntityRecords; },
728 "hasFetchedAutosaves": function() { return hasFetchedAutosaves; },
729 "hasRedo": function() { return hasRedo; },
730 "hasUndo": function() { return hasUndo; },
731 "isAutosavingEntityRecord": function() { return isAutosavingEntityRecord; },
732 "isDeletingEntityRecord": function() { return isDeletingEntityRecord; },
733 "isPreviewEmbedFallback": function() { return isPreviewEmbedFallback; },
734 "isRequestingEmbedPreview": function() { return isRequestingEmbedPreview; },
735 "isSavingEntityRecord": function() { return isSavingEntityRecord; }
736 });
737
738 // NAMESPACE OBJECT: ./packages/core-data/build-module/resolvers.js
739 var resolvers_namespaceObject = {};
740 __webpack_require__.r(resolvers_namespaceObject);
741 __webpack_require__.d(resolvers_namespaceObject, {
742 "__experimentalGetCurrentGlobalStylesId": function() { return resolvers_experimentalGetCurrentGlobalStylesId; },
743 "__experimentalGetCurrentThemeBaseGlobalStyles": function() { return resolvers_experimentalGetCurrentThemeBaseGlobalStyles; },
744 "__experimentalGetCurrentThemeGlobalStylesVariations": function() { return resolvers_experimentalGetCurrentThemeGlobalStylesVariations; },
745 "__experimentalGetTemplateForLink": function() { return resolvers_experimentalGetTemplateForLink; },
746 "canUser": function() { return resolvers_canUser; },
747 "canUserEditEntityRecord": function() { return resolvers_canUserEditEntityRecord; },
748 "getAuthors": function() { return resolvers_getAuthors; },
749 "getAutosave": function() { return resolvers_getAutosave; },
750 "getAutosaves": function() { return resolvers_getAutosaves; },
751 "getBlockPatternCategories": function() { return resolvers_getBlockPatternCategories; },
752 "getBlockPatterns": function() { return resolvers_getBlockPatterns; },
753 "getCurrentTheme": function() { return resolvers_getCurrentTheme; },
754 "getCurrentUser": function() { return resolvers_getCurrentUser; },
755 "getEditedEntityRecord": function() { return resolvers_getEditedEntityRecord; },
756 "getEmbedPreview": function() { return resolvers_getEmbedPreview; },
757 "getEntityRecord": function() { return resolvers_getEntityRecord; },
758 "getEntityRecords": function() { return resolvers_getEntityRecords; },
759 "getRawEntityRecord": function() { return resolvers_getRawEntityRecord; },
760 "getThemeSupports": function() { return resolvers_getThemeSupports; }
761 });
762
763 ;// CONCATENATED MODULE: external ["wp","data"]
764 var external_wp_data_namespaceObject = window["wp"]["data"];
765 // EXTERNAL MODULE: ./node_modules/fast-deep-equal/es6/index.js
766 var es6 = __webpack_require__(5619);
767 var es6_default = /*#__PURE__*/__webpack_require__.n(es6);
768 ;// CONCATENATED MODULE: external "lodash"
769 var external_lodash_namespaceObject = window["lodash"];
770 ;// CONCATENATED MODULE: external ["wp","compose"]
771 var external_wp_compose_namespaceObject = window["wp"]["compose"];
772 ;// CONCATENATED MODULE: external ["wp","isShallowEqual"]
773 var external_wp_isShallowEqual_namespaceObject = window["wp"]["isShallowEqual"];
774 var external_wp_isShallowEqual_default = /*#__PURE__*/__webpack_require__.n(external_wp_isShallowEqual_namespaceObject);
775 ;// CONCATENATED MODULE: ./packages/core-data/build-module/utils/if-matching-action.js
776 /** @typedef {import('../types').AnyFunction} AnyFunction */
777
778 /**
779 * A higher-order reducer creator which invokes the original reducer only if
780 * the dispatching action matches the given predicate, **OR** if state is
781 * initializing (undefined).
782 *
783 * @param {AnyFunction} isMatch Function predicate for allowing reducer call.
784 *
785 * @return {AnyFunction} Higher-order reducer.
786 */
787 const ifMatchingAction = isMatch => reducer => (state, action) => {
788 if (state === undefined || isMatch(action)) {
789 return reducer(state, action);
790 }
791
792 return state;
793 };
794
795 /* harmony default export */ var if_matching_action = (ifMatchingAction);
796
797 ;// CONCATENATED MODULE: ./packages/core-data/build-module/utils/replace-action.js
798 /** @typedef {import('../types').AnyFunction} AnyFunction */
799
800 /**
801 * Higher-order reducer creator which substitutes the action object before
802 * passing to the original reducer.
803 *
804 * @param {AnyFunction} replacer Function mapping original action to replacement.
805 *
806 * @return {AnyFunction} Higher-order reducer.
807 */
808 const replaceAction = replacer => reducer => (state, action) => {
809 return reducer(state, replacer(action));
810 };
811
812 /* harmony default export */ var replace_action = (replaceAction);
813
814 ;// CONCATENATED MODULE: ./packages/core-data/build-module/utils/conservative-map-item.js
815 /**
816 * External dependencies
817 */
818
819 /**
820 * Given the current and next item entity record, returns the minimally "modified"
821 * result of the next item, preferring value references from the original item
822 * if equal. If all values match, the original item is returned.
823 *
824 * @param {Object} item Original item.
825 * @param {Object} nextItem Next item.
826 *
827 * @return {Object} Minimally modified merged item.
828 */
829
830 function conservativeMapItem(item, nextItem) {
831 // Return next item in its entirety if there is no original item.
832 if (!item) {
833 return nextItem;
834 }
835
836 let hasChanges = false;
837 const result = {};
838
839 for (const key in nextItem) {
840 if (es6_default()(item[key], nextItem[key])) {
841 result[key] = item[key];
842 } else {
843 hasChanges = true;
844 result[key] = nextItem[key];
845 }
846 }
847
848 if (!hasChanges) {
849 return item;
850 } // Only at this point, backfill properties from the original item which
851 // weren't explicitly set into the result above. This is an optimization
852 // to allow `hasChanges` to return early.
853
854
855 for (const key in item) {
856 if (!result.hasOwnProperty(key)) {
857 result[key] = item[key];
858 }
859 }
860
861 return result;
862 }
863
864 ;// CONCATENATED MODULE: ./packages/core-data/build-module/utils/on-sub-key.js
865 /** @typedef {import('../types').AnyFunction} AnyFunction */
866
867 /**
868 * Higher-order reducer creator which creates a combined reducer object, keyed
869 * by a property on the action object.
870 *
871 * @param {string} actionProperty Action property by which to key object.
872 *
873 * @return {AnyFunction} Higher-order reducer.
874 */
875 const onSubKey = actionProperty => reducer => function () {
876 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
877 let action = arguments.length > 1 ? arguments[1] : undefined;
878 // Retrieve subkey from action. Do not track if undefined; useful for cases
879 // where reducer is scoped by action shape.
880 const key = action[actionProperty];
881
882 if (key === undefined) {
883 return state;
884 } // Avoid updating state if unchanged. Note that this also accounts for a
885 // reducer which returns undefined on a key which is not yet tracked.
886
887
888 const nextKeyState = reducer(state[key], action);
889
890 if (nextKeyState === state[key]) {
891 return state;
892 }
893
894 return { ...state,
895 [key]: nextKeyState
896 };
897 };
898 /* harmony default export */ var on_sub_key = (onSubKey);
899
900 ;// CONCATENATED MODULE: ./node_modules/tslib/tslib.es6.js
901 /*! *****************************************************************************
902 Copyright (c) Microsoft Corporation.
903
904 Permission to use, copy, modify, and/or distribute this software for any
905 purpose with or without fee is hereby granted.
906
907 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
908 REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
909 AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
910 INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
911 LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
912 OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
913 PERFORMANCE OF THIS SOFTWARE.
914 ***************************************************************************** */
915 /* global Reflect, Promise */
916
917 var extendStatics = function(d, b) {
918 extendStatics = Object.setPrototypeOf ||
919 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
920 function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
921 return extendStatics(d, b);
922 };
923
924 function __extends(d, b) {
925 if (typeof b !== "function" && b !== null)
926 throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
927 extendStatics(d, b);
928 function __() { this.constructor = d; }
929 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
930 }
931
932 var __assign = function() {
933 __assign = Object.assign || function __assign(t) {
934 for (var s, i = 1, n = arguments.length; i < n; i++) {
935 s = arguments[i];
936 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
937 }
938 return t;
939 }
940 return __assign.apply(this, arguments);
941 }
942
943 function __rest(s, e) {
944 var t = {};
945 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
946 t[p] = s[p];
947 if (s != null && typeof Object.getOwnPropertySymbols === "function")
948 for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
949 if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
950 t[p[i]] = s[p[i]];
951 }
952 return t;
953 }
954
955 function __decorate(decorators, target, key, desc) {
956 var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
957 if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
958 else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
959 return c > 3 && r && Object.defineProperty(target, key, r), r;
960 }
961
962 function __param(paramIndex, decorator) {
963 return function (target, key) { decorator(target, key, paramIndex); }
964 }
965
966 function __metadata(metadataKey, metadataValue) {
967 if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue);
968 }
969
970 function __awaiter(thisArg, _arguments, P, generator) {
971 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
972 return new (P || (P = Promise))(function (resolve, reject) {
973 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
974 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
975 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
976 step((generator = generator.apply(thisArg, _arguments || [])).next());
977 });
978 }
979
980 function __generator(thisArg, body) {
981 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
982 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
983 function verb(n) { return function (v) { return step([n, v]); }; }
984 function step(op) {
985 if (f) throw new TypeError("Generator is already executing.");
986 while (_) try {
987 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
988 if (y = 0, t) op = [op[0] & 2, t.value];
989 switch (op[0]) {
990 case 0: case 1: t = op; break;
991 case 4: _.label++; return { value: op[1], done: false };
992 case 5: _.label++; y = op[1]; op = [0]; continue;
993 case 7: op = _.ops.pop(); _.trys.pop(); continue;
994 default:
995 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
996 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
997 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
998 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
999 if (t[2]) _.ops.pop();
1000 _.trys.pop(); continue;
1001 }
1002 op = body.call(thisArg, _);
1003 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
1004 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
1005 }
1006 }
1007
1008 var __createBinding = Object.create ? (function(o, m, k, k2) {
1009 if (k2 === undefined) k2 = k;
1010 Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
1011 }) : (function(o, m, k, k2) {
1012 if (k2 === undefined) k2 = k;
1013 o[k2] = m[k];
1014 });
1015
1016 function __exportStar(m, o) {
1017 for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);
1018 }
1019
1020 function __values(o) {
1021 var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
1022 if (m) return m.call(o);
1023 if (o && typeof o.length === "number") return {
1024 next: function () {
1025 if (o && i >= o.length) o = void 0;
1026 return { value: o && o[i++], done: !o };
1027 }
1028 };
1029 throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
1030 }
1031
1032 function __read(o, n) {
1033 var m = typeof Symbol === "function" && o[Symbol.iterator];
1034 if (!m) return o;
1035 var i = m.call(o), r, ar = [], e;
1036 try {
1037 while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
1038 }
1039 catch (error) { e = { error: error }; }
1040 finally {
1041 try {
1042 if (r && !r.done && (m = i["return"])) m.call(i);
1043 }
1044 finally { if (e) throw e.error; }
1045 }
1046 return ar;
1047 }
1048
1049 /** @deprecated */
1050 function __spread() {
1051 for (var ar = [], i = 0; i < arguments.length; i++)
1052 ar = ar.concat(__read(arguments[i]));
1053 return ar;
1054 }
1055
1056 /** @deprecated */
1057 function __spreadArrays() {
1058 for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
1059 for (var r = Array(s), k = 0, i = 0; i < il; i++)
1060 for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
1061 r[k] = a[j];
1062 return r;
1063 }
1064
1065 function __spreadArray(to, from, pack) {
1066 if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
1067 if (ar || !(i in from)) {
1068 if (!ar) ar = Array.prototype.slice.call(from, 0, i);
1069 ar[i] = from[i];
1070 }
1071 }
1072 return to.concat(ar || from);
1073 }
1074
1075 function __await(v) {
1076 return this instanceof __await ? (this.v = v, this) : new __await(v);
1077 }
1078
1079 function __asyncGenerator(thisArg, _arguments, generator) {
1080 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
1081 var g = generator.apply(thisArg, _arguments || []), i, q = [];
1082 return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
1083 function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
1084 function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
1085 function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
1086 function fulfill(value) { resume("next", value); }
1087 function reject(value) { resume("throw", value); }
1088 function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
1089 }
1090
1091 function __asyncDelegator(o) {
1092 var i, p;
1093 return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
1094 function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
1095 }
1096
1097 function __asyncValues(o) {
1098 if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
1099 var m = o[Symbol.asyncIterator], i;
1100 return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
1101 function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
1102 function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
1103 }
1104
1105 function __makeTemplateObject(cooked, raw) {
1106 if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
1107 return cooked;
1108 };
1109
1110 var __setModuleDefault = Object.create ? (function(o, v) {
1111 Object.defineProperty(o, "default", { enumerable: true, value: v });
1112 }) : function(o, v) {
1113 o["default"] = v;
1114 };
1115
1116 function __importStar(mod) {
1117 if (mod && mod.__esModule) return mod;
1118 var result = {};
1119 if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
1120 __setModuleDefault(result, mod);
1121 return result;
1122 }
1123
1124 function __importDefault(mod) {
1125 return (mod && mod.__esModule) ? mod : { default: mod };
1126 }
1127
1128 function __classPrivateFieldGet(receiver, state, kind, f) {
1129 if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
1130 if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
1131 return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
1132 }
1133
1134 function __classPrivateFieldSet(receiver, state, value, kind, f) {
1135 if (kind === "m") throw new TypeError("Private method is not writable");
1136 if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
1137 if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
1138 return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
1139 }
1140
1141 ;// CONCATENATED MODULE: ./node_modules/lower-case/dist.es2015/index.js
1142 /**
1143 * Source: ftp://ftp.unicode.org/Public/UCD/latest/ucd/SpecialCasing.txt
1144 */
1145 var SUPPORTED_LOCALE = {
1146 tr: {
1147 regexp: /\u0130|\u0049|\u0049\u0307/g,
1148 map: {
1149 İ: "\u0069",
1150 I: "\u0131",
1151 : "\u0069",
1152 },
1153 },
1154 az: {
1155 regexp: /\u0130/g,
1156 map: {
1157 İ: "\u0069",
1158 I: "\u0131",
1159 : "\u0069",
1160 },
1161 },
1162 lt: {
1163 regexp: /\u0049|\u004A|\u012E|\u00CC|\u00CD|\u0128/g,
1164 map: {
1165 I: "\u0069\u0307",
1166 J: "\u006A\u0307",
1167 Į: "\u012F\u0307",
1168 Ì: "\u0069\u0307\u0300",
1169 Í: "\u0069\u0307\u0301",
1170 Ĩ: "\u0069\u0307\u0303",
1171 },
1172 },
1173 };
1174 /**
1175 * Localized lower case.
1176 */
1177 function localeLowerCase(str, locale) {
1178 var lang = SUPPORTED_LOCALE[locale.toLowerCase()];
1179 if (lang)
1180 return lowerCase(str.replace(lang.regexp, function (m) { return lang.map[m]; }));
1181 return lowerCase(str);
1182 }
1183 /**
1184 * Lower case as a function.
1185 */
1186 function lowerCase(str) {
1187 return str.toLowerCase();
1188 }
1189
1190 ;// CONCATENATED MODULE: ./node_modules/no-case/dist.es2015/index.js
1191
1192 // Support camel case ("camelCase" -> "camel Case" and "CAMELCase" -> "CAMEL Case").
1193 var DEFAULT_SPLIT_REGEXP = [/([a-z0-9])([A-Z])/g, /([A-Z])([A-Z][a-z])/g];
1194 // Remove all non-word characters.
1195 var DEFAULT_STRIP_REGEXP = /[^A-Z0-9]+/gi;
1196 /**
1197 * Normalize the string into something other libraries can manipulate easier.
1198 */
1199 function noCase(input, options) {
1200 if (options === void 0) { options = {}; }
1201 var _a = options.splitRegexp, splitRegexp = _a === void 0 ? DEFAULT_SPLIT_REGEXP : _a, _b = options.stripRegexp, stripRegexp = _b === void 0 ? DEFAULT_STRIP_REGEXP : _b, _c = options.transform, transform = _c === void 0 ? lowerCase : _c, _d = options.delimiter, delimiter = _d === void 0 ? " " : _d;
1202 var result = replace(replace(input, splitRegexp, "$1\0$2"), stripRegexp, "\0");
1203 var start = 0;
1204 var end = result.length;
1205 // Trim the delimiter from around the output string.
1206 while (result.charAt(start) === "\0")
1207 start++;
1208 while (result.charAt(end - 1) === "\0")
1209 end--;
1210 // Transform each token independently.
1211 return result.slice(start, end).split("\0").map(transform).join(delimiter);
1212 }
1213 /**
1214 * Replace `re` in the input string with the replacement value.
1215 */
1216 function replace(input, re, value) {
1217 if (re instanceof RegExp)
1218 return input.replace(re, value);
1219 return re.reduce(function (input, re) { return input.replace(re, value); }, input);
1220 }
1221
1222 ;// CONCATENATED MODULE: ./node_modules/upper-case-first/dist.es2015/index.js
1223 /**
1224 * Upper case the first character of an input string.
1225 */
1226 function upperCaseFirst(input) {
1227 return input.charAt(0).toUpperCase() + input.substr(1);
1228 }
1229
1230 ;// CONCATENATED MODULE: ./node_modules/capital-case/dist.es2015/index.js
1231
1232
1233
1234 function capitalCaseTransform(input) {
1235 return upperCaseFirst(input.toLowerCase());
1236 }
1237 function capitalCase(input, options) {
1238 if (options === void 0) { options = {}; }
1239 return noCase(input, __assign({ delimiter: " ", transform: capitalCaseTransform }, options));
1240 }
1241
1242 ;// CONCATENATED MODULE: ./node_modules/pascal-case/dist.es2015/index.js
1243
1244
1245 function pascalCaseTransform(input, index) {
1246 var firstChar = input.charAt(0);
1247 var lowerChars = input.substr(1).toLowerCase();
1248 if (index > 0 && firstChar >= "0" && firstChar <= "9") {
1249 return "_" + firstChar + lowerChars;
1250 }
1251 return "" + firstChar.toUpperCase() + lowerChars;
1252 }
1253 function dist_es2015_pascalCaseTransformMerge(input) {
1254 return input.charAt(0).toUpperCase() + input.slice(1).toLowerCase();
1255 }
1256 function pascalCase(input, options) {
1257 if (options === void 0) { options = {}; }
1258 return noCase(input, __assign({ delimiter: "", transform: pascalCaseTransform }, options));
1259 }
1260
1261 ;// CONCATENATED MODULE: external ["wp","apiFetch"]
1262 var external_wp_apiFetch_namespaceObject = window["wp"]["apiFetch"];
1263 var external_wp_apiFetch_default = /*#__PURE__*/__webpack_require__.n(external_wp_apiFetch_namespaceObject);
1264 ;// CONCATENATED MODULE: external ["wp","i18n"]
1265 var external_wp_i18n_namespaceObject = window["wp"]["i18n"];
1266 ;// CONCATENATED MODULE: ./node_modules/uuid/dist/esm-browser/rng.js
1267 // Unique ID creation requires a high quality random # generator. In the browser we therefore
1268 // require the crypto API and do not support built-in fallback to lower quality random number
1269 // generators (like Math.random()).
1270 // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
1271 // find the complete implementation of crypto (msCrypto) on IE11.
1272 var getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);
1273 var rnds8 = new Uint8Array(16);
1274 function rng() {
1275 if (!getRandomValues) {
1276 throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
1277 }
1278
1279 return getRandomValues(rnds8);
1280 }
1281 ;// CONCATENATED MODULE: ./node_modules/uuid/dist/esm-browser/regex.js
1282 /* harmony default export */ var regex = (/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i);
1283 ;// CONCATENATED MODULE: ./node_modules/uuid/dist/esm-browser/validate.js
1284
1285
1286 function validate(uuid) {
1287 return typeof uuid === 'string' && regex.test(uuid);
1288 }
1289
1290 /* harmony default export */ var esm_browser_validate = (validate);
1291 ;// CONCATENATED MODULE: ./node_modules/uuid/dist/esm-browser/stringify.js
1292
1293 /**
1294 * Convert array of 16 byte values to UUID string format of the form:
1295 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
1296 */
1297
1298 var byteToHex = [];
1299
1300 for (var i = 0; i < 256; ++i) {
1301 byteToHex.push((i + 0x100).toString(16).substr(1));
1302 }
1303
1304 function stringify(arr) {
1305 var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
1306 // Note: Be careful editing this code! It's been tuned for performance
1307 // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
1308 var uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one
1309 // of the following:
1310 // - One or more input array values don't map to a hex octet (leading to
1311 // "undefined" in the uuid)
1312 // - Invalid input values for the RFC `version` or `variant` fields
1313
1314 if (!esm_browser_validate(uuid)) {
1315 throw TypeError('Stringified UUID is invalid');
1316 }
1317
1318 return uuid;
1319 }
1320
1321 /* harmony default export */ var esm_browser_stringify = (stringify);
1322 ;// CONCATENATED MODULE: ./node_modules/uuid/dist/esm-browser/v4.js
1323
1324
1325
1326 function v4(options, buf, offset) {
1327 options = options || {};
1328 var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
1329
1330 rnds[6] = rnds[6] & 0x0f | 0x40;
1331 rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
1332
1333 if (buf) {
1334 offset = offset || 0;
1335
1336 for (var i = 0; i < 16; ++i) {
1337 buf[offset + i] = rnds[i];
1338 }
1339
1340 return buf;
1341 }
1342
1343 return esm_browser_stringify(rnds);
1344 }
1345
1346 /* harmony default export */ var esm_browser_v4 = (v4);
1347 ;// CONCATENATED MODULE: external ["wp","url"]
1348 var external_wp_url_namespaceObject = window["wp"]["url"];
1349 ;// CONCATENATED MODULE: external ["wp","deprecated"]
1350 var external_wp_deprecated_namespaceObject = window["wp"]["deprecated"];
1351 var external_wp_deprecated_default = /*#__PURE__*/__webpack_require__.n(external_wp_deprecated_namespaceObject);
1352 ;// CONCATENATED MODULE: ./packages/core-data/build-module/queried-data/actions.js
1353 /**
1354 * Returns an action object used in signalling that items have been received.
1355 *
1356 * @param {Array} items Items received.
1357 * @param {?Object} edits Optional edits to reset.
1358 *
1359 * @return {Object} Action object.
1360 */
1361 function receiveItems(items, edits) {
1362 return {
1363 type: 'RECEIVE_ITEMS',
1364 items: Array.isArray(items) ? items : [items],
1365 persistedEdits: edits
1366 };
1367 }
1368 /**
1369 * Returns an action object used in signalling that entity records have been
1370 * deleted and they need to be removed from entities state.
1371 *
1372 * @param {string} kind Kind of the removed entities.
1373 * @param {string} name Name of the removed entities.
1374 * @param {Array|number|string} records Record IDs of the removed entities.
1375 * @param {boolean} invalidateCache Controls whether we want to invalidate the cache.
1376 * @return {Object} Action object.
1377 */
1378
1379 function removeItems(kind, name, records) {
1380 let invalidateCache = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
1381 return {
1382 type: 'REMOVE_ITEMS',
1383 itemIds: Array.isArray(records) ? records : [records],
1384 kind,
1385 name,
1386 invalidateCache
1387 };
1388 }
1389 /**
1390 * Returns an action object used in signalling that queried data has been
1391 * received.
1392 *
1393 * @param {Array} items Queried items received.
1394 * @param {?Object} query Optional query object.
1395 * @param {?Object} edits Optional edits to reset.
1396 *
1397 * @return {Object} Action object.
1398 */
1399
1400 function receiveQueriedItems(items) {
1401 let query = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1402 let edits = arguments.length > 2 ? arguments[2] : undefined;
1403 return { ...receiveItems(items, edits),
1404 query
1405 };
1406 }
1407
1408 ;// CONCATENATED MODULE: ./packages/core-data/build-module/batch/default-processor.js
1409 /**
1410 * WordPress dependencies
1411 */
1412
1413 /**
1414 * Maximum number of requests to place in a single batch request. Obtained by
1415 * sending a preflight OPTIONS request to /batch/v1/.
1416 *
1417 * @type {number?}
1418 */
1419
1420 let maxItems = null;
1421
1422 function chunk(arr, chunkSize) {
1423 const tmp = [...arr];
1424 const cache = [];
1425
1426 while (tmp.length) {
1427 cache.push(tmp.splice(0, chunkSize));
1428 }
1429
1430 return cache;
1431 }
1432 /**
1433 * Default batch processor. Sends its input requests to /batch/v1.
1434 *
1435 * @param {Array} requests List of API requests to perform at once.
1436 *
1437 * @return {Promise} Promise that resolves to a list of objects containing
1438 * either `output` (if that request was successful) or `error`
1439 * (if not ).
1440 */
1441
1442
1443 async function defaultProcessor(requests) {
1444 if (maxItems === null) {
1445 const preflightResponse = await external_wp_apiFetch_default()({
1446 path: '/batch/v1',
1447 method: 'OPTIONS'
1448 });
1449 maxItems = preflightResponse.endpoints[0].args.requests.maxItems;
1450 }
1451
1452 const results = []; // @ts-ignore We would have crashed or never gotten to this point if we hadn't received the maxItems count.
1453
1454 for (const batchRequests of chunk(requests, maxItems)) {
1455 const batchResponse = await external_wp_apiFetch_default()({
1456 path: '/batch/v1',
1457 method: 'POST',
1458 data: {
1459 validation: 'require-all-validate',
1460 requests: batchRequests.map(request => ({
1461 path: request.path,
1462 body: request.data,
1463 // Rename 'data' to 'body'.
1464 method: request.method,
1465 headers: request.headers
1466 }))
1467 }
1468 });
1469 let batchResults;
1470
1471 if (batchResponse.failed) {
1472 batchResults = batchResponse.responses.map(response => ({
1473 error: response === null || response === void 0 ? void 0 : response.body
1474 }));
1475 } else {
1476 batchResults = batchResponse.responses.map(response => {
1477 const result = {};
1478
1479 if (response.status >= 200 && response.status < 300) {
1480 result.output = response.body;
1481 } else {
1482 result.error = response.body;
1483 }
1484
1485 return result;
1486 });
1487 }
1488
1489 results.push(...batchResults);
1490 }
1491
1492 return results;
1493 }
1494
1495 ;// CONCATENATED MODULE: ./packages/core-data/build-module/batch/create-batch.js
1496 /**
1497 * Internal dependencies
1498 */
1499
1500 /**
1501 * Creates a batch, which can be used to combine multiple API requests into one
1502 * API request using the WordPress batch processing API (/v1/batch).
1503 *
1504 * ```
1505 * const batch = createBatch();
1506 * const dunePromise = batch.add( {
1507 * path: '/v1/books',
1508 * method: 'POST',
1509 * data: { title: 'Dune' }
1510 * } );
1511 * const lotrPromise = batch.add( {
1512 * path: '/v1/books',
1513 * method: 'POST',
1514 * data: { title: 'Lord of the Rings' }
1515 * } );
1516 * const isSuccess = await batch.run(); // Sends one POST to /v1/batch.
1517 * if ( isSuccess ) {
1518 * console.log(
1519 * 'Saved two books:',
1520 * await dunePromise,
1521 * await lotrPromise
1522 * );
1523 * }
1524 * ```
1525 *
1526 * @param {Function} [processor] Processor function. Can be used to replace the
1527 * default functionality which is to send an API
1528 * request to /v1/batch. Is given an array of
1529 * inputs and must return a promise that
1530 * resolves to an array of objects containing
1531 * either `output` or `error`.
1532 */
1533
1534 function createBatch() {
1535 let processor = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : defaultProcessor;
1536 let lastId = 0;
1537 /** @type {Array<{ input: any; resolve: ( value: any ) => void; reject: ( error: any ) => void }>} */
1538
1539 let queue = [];
1540 const pending = new ObservableSet();
1541 return {
1542 /**
1543 * Adds an input to the batch and returns a promise that is resolved or
1544 * rejected when the input is processed by `batch.run()`.
1545 *
1546 * You may also pass a thunk which allows inputs to be added
1547 * asychronously.
1548 *
1549 * ```
1550 * // Both are allowed:
1551 * batch.add( { path: '/v1/books', ... } );
1552 * batch.add( ( add ) => add( { path: '/v1/books', ... } ) );
1553 * ```
1554 *
1555 * If a thunk is passed, `batch.run()` will pause until either:
1556 *
1557 * - The thunk calls its `add` argument, or;
1558 * - The thunk returns a promise and that promise resolves, or;
1559 * - The thunk returns a non-promise.
1560 *
1561 * @param {any|Function} inputOrThunk Input to add or thunk to execute.
1562 *
1563 * @return {Promise|any} If given an input, returns a promise that
1564 * is resolved or rejected when the batch is
1565 * processed. If given a thunk, returns the return
1566 * value of that thunk.
1567 */
1568 add(inputOrThunk) {
1569 const id = ++lastId;
1570 pending.add(id);
1571
1572 const add = input => new Promise((resolve, reject) => {
1573 queue.push({
1574 input,
1575 resolve,
1576 reject
1577 });
1578 pending.delete(id);
1579 });
1580
1581 if (typeof inputOrThunk === 'function') {
1582 return Promise.resolve(inputOrThunk(add)).finally(() => {
1583 pending.delete(id);
1584 });
1585 }
1586
1587 return add(inputOrThunk);
1588 },
1589
1590 /**
1591 * Runs the batch. This calls `batchProcessor` and resolves or rejects
1592 * all promises returned by `add()`.
1593 *
1594 * @return {Promise<boolean>} A promise that resolves to a boolean that is true
1595 * if the processor returned no errors.
1596 */
1597 async run() {
1598 if (pending.size) {
1599 await new Promise(resolve => {
1600 const unsubscribe = pending.subscribe(() => {
1601 if (!pending.size) {
1602 unsubscribe();
1603 resolve(undefined);
1604 }
1605 });
1606 });
1607 }
1608
1609 let results;
1610
1611 try {
1612 results = await processor(queue.map(_ref => {
1613 let {
1614 input
1615 } = _ref;
1616 return input;
1617 }));
1618
1619 if (results.length !== queue.length) {
1620 throw new Error('run: Array returned by processor must be same size as input array.');
1621 }
1622 } catch (error) {
1623 for (const {
1624 reject
1625 } of queue) {
1626 reject(error);
1627 }
1628
1629 throw error;
1630 }
1631
1632 let isSuccess = true;
1633 results.forEach((result, key) => {
1634 const queueItem = queue[key];
1635
1636 if (result !== null && result !== void 0 && result.error) {
1637 queueItem === null || queueItem === void 0 ? void 0 : queueItem.reject(result.error);
1638 isSuccess = false;
1639 } else {
1640 var _result$output;
1641
1642 queueItem === null || queueItem === void 0 ? void 0 : queueItem.resolve((_result$output = result === null || result === void 0 ? void 0 : result.output) !== null && _result$output !== void 0 ? _result$output : result);
1643 }
1644 });
1645 queue = [];
1646 return isSuccess;
1647 }
1648
1649 };
1650 }
1651
1652 class ObservableSet {
1653 constructor() {
1654 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
1655 args[_key] = arguments[_key];
1656 }
1657
1658 this.set = new Set(...args);
1659 this.subscribers = new Set();
1660 }
1661
1662 get size() {
1663 return this.set.size;
1664 }
1665
1666 add(value) {
1667 this.set.add(value);
1668 this.subscribers.forEach(subscriber => subscriber());
1669 return this;
1670 }
1671
1672 delete(value) {
1673 const isSuccess = this.set.delete(value);
1674 this.subscribers.forEach(subscriber => subscriber());
1675 return isSuccess;
1676 }
1677
1678 subscribe(subscriber) {
1679 this.subscribers.add(subscriber);
1680 return () => {
1681 this.subscribers.delete(subscriber);
1682 };
1683 }
1684
1685 }
1686
1687 ;// CONCATENATED MODULE: ./packages/core-data/build-module/name.js
1688 /**
1689 * The reducer key used by core data in store registration.
1690 * This is defined in a separate file to avoid cycle-dependency
1691 *
1692 * @type {string}
1693 */
1694 const STORE_NAME = 'core';
1695
1696 ;// CONCATENATED MODULE: ./packages/core-data/build-module/actions.js
1697 /**
1698 * External dependencies
1699 */
1700
1701
1702 /**
1703 * WordPress dependencies
1704 */
1705
1706
1707
1708
1709 /**
1710 * Internal dependencies
1711 */
1712
1713
1714
1715
1716
1717 /**
1718 * Returns an action object used in signalling that authors have been received.
1719 * Ignored from documentation as it's internal to the data store.
1720 *
1721 * @ignore
1722 *
1723 * @param {string} queryID Query ID.
1724 * @param {Array|Object} users Users received.
1725 *
1726 * @return {Object} Action object.
1727 */
1728
1729 function receiveUserQuery(queryID, users) {
1730 return {
1731 type: 'RECEIVE_USER_QUERY',
1732 users: Array.isArray(users) ? users : [users],
1733 queryID
1734 };
1735 }
1736 /**
1737 * Returns an action used in signalling that the current user has been received.
1738 * Ignored from documentation as it's internal to the data store.
1739 *
1740 * @ignore
1741 *
1742 * @param {Object} currentUser Current user object.
1743 *
1744 * @return {Object} Action object.
1745 */
1746
1747 function receiveCurrentUser(currentUser) {
1748 return {
1749 type: 'RECEIVE_CURRENT_USER',
1750 currentUser
1751 };
1752 }
1753 /**
1754 * Returns an action object used in adding new entities.
1755 *
1756 * @param {Array} entities Entities received.
1757 *
1758 * @return {Object} Action object.
1759 */
1760
1761 function addEntities(entities) {
1762 return {
1763 type: 'ADD_ENTITIES',
1764 entities
1765 };
1766 }
1767 /**
1768 * Returns an action object used in signalling that entity records have been received.
1769 *
1770 * @param {string} kind Kind of the received entity record.
1771 * @param {string} name Name of the received entity record.
1772 * @param {Array|Object} records Records received.
1773 * @param {?Object} query Query Object.
1774 * @param {?boolean} invalidateCache Should invalidate query caches.
1775 * @param {?Object} edits Edits to reset.
1776 * @return {Object} Action object.
1777 */
1778
1779 function receiveEntityRecords(kind, name, records, query) {
1780 let invalidateCache = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false;
1781 let edits = arguments.length > 5 ? arguments[5] : undefined;
1782
1783 // Auto drafts should not have titles, but some plugins rely on them so we can't filter this
1784 // on the server.
1785 if (kind === 'postType') {
1786 records = (Array.isArray(records) ? records : [records]).map(record => record.status === 'auto-draft' ? { ...record,
1787 title: ''
1788 } : record);
1789 }
1790
1791 let action;
1792
1793 if (query) {
1794 action = receiveQueriedItems(records, query, edits);
1795 } else {
1796 action = receiveItems(records, edits);
1797 }
1798
1799 return { ...action,
1800 kind,
1801 name,
1802 invalidateCache
1803 };
1804 }
1805 /**
1806 * Returns an action object used in signalling that the current theme has been received.
1807 * Ignored from documentation as it's internal to the data store.
1808 *
1809 * @ignore
1810 *
1811 * @param {Object} currentTheme The current theme.
1812 *
1813 * @return {Object} Action object.
1814 */
1815
1816 function receiveCurrentTheme(currentTheme) {
1817 return {
1818 type: 'RECEIVE_CURRENT_THEME',
1819 currentTheme
1820 };
1821 }
1822 /**
1823 * Returns an action object used in signalling that the current global styles id has been received.
1824 * Ignored from documentation as it's internal to the data store.
1825 *
1826 * @ignore
1827 *
1828 * @param {string} currentGlobalStylesId The current global styles id.
1829 *
1830 * @return {Object} Action object.
1831 */
1832
1833 function __experimentalReceiveCurrentGlobalStylesId(currentGlobalStylesId) {
1834 return {
1835 type: 'RECEIVE_CURRENT_GLOBAL_STYLES_ID',
1836 id: currentGlobalStylesId
1837 };
1838 }
1839 /**
1840 * Returns an action object used in signalling that the theme base global styles have been received
1841 * Ignored from documentation as it's internal to the data store.
1842 *
1843 * @ignore
1844 *
1845 * @param {string} stylesheet The theme's identifier
1846 * @param {Object} globalStyles The global styles object.
1847 *
1848 * @return {Object} Action object.
1849 */
1850
1851 function __experimentalReceiveThemeBaseGlobalStyles(stylesheet, globalStyles) {
1852 return {
1853 type: 'RECEIVE_THEME_GLOBAL_STYLES',
1854 stylesheet,
1855 globalStyles
1856 };
1857 }
1858 /**
1859 * Returns an action object used in signalling that the theme global styles variations have been received.
1860 * Ignored from documentation as it's internal to the data store.
1861 *
1862 * @ignore
1863 *
1864 * @param {string} stylesheet The theme's identifier
1865 * @param {Array} variations The global styles variations.
1866 *
1867 * @return {Object} Action object.
1868 */
1869
1870 function __experimentalReceiveThemeGlobalStyleVariations(stylesheet, variations) {
1871 return {
1872 type: 'RECEIVE_THEME_GLOBAL_STYLE_VARIATIONS',
1873 stylesheet,
1874 variations
1875 };
1876 }
1877 /**
1878 * Returns an action object used in signalling that the index has been received.
1879 *
1880 * @deprecated since WP 5.9, this is not useful anymore, use the selector direclty.
1881 *
1882 * @return {Object} Action object.
1883 */
1884
1885 function receiveThemeSupports() {
1886 external_wp_deprecated_default()("wp.data.dispatch( 'core' ).receiveThemeSupports", {
1887 since: '5.9'
1888 });
1889 return {
1890 type: 'DO_NOTHING'
1891 };
1892 }
1893 /**
1894 * Returns an action object used in signalling that the preview data for
1895 * a given URl has been received.
1896 * Ignored from documentation as it's internal to the data store.
1897 *
1898 * @ignore
1899 *
1900 * @param {string} url URL to preview the embed for.
1901 * @param {*} preview Preview data.
1902 *
1903 * @return {Object} Action object.
1904 */
1905
1906 function receiveEmbedPreview(url, preview) {
1907 return {
1908 type: 'RECEIVE_EMBED_PREVIEW',
1909 url,
1910 preview
1911 };
1912 }
1913 /**
1914 * Action triggered to delete an entity record.
1915 *
1916 * @param {string} kind Kind of the deleted entity.
1917 * @param {string} name Name of the deleted entity.
1918 * @param {string} recordId Record ID of the deleted entity.
1919 * @param {?Object} query Special query parameters for the
1920 * DELETE API call.
1921 * @param {Object} [options] Delete options.
1922 * @param {Function} [options.__unstableFetch] Internal use only. Function to
1923 * call instead of `apiFetch()`.
1924 * Must return a promise.
1925 * @param {boolean} [options.throwOnError=false] If false, this action suppresses all
1926 * the exceptions. Defaults to false.
1927 */
1928
1929 const deleteEntityRecord = function (kind, name, recordId, query) {
1930 let {
1931 __unstableFetch = (external_wp_apiFetch_default()),
1932 throwOnError = false
1933 } = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
1934 return async _ref => {
1935 let {
1936 dispatch
1937 } = _ref;
1938 const configs = await dispatch(getOrLoadEntitiesConfig(kind));
1939 const entityConfig = configs.find(config => config.kind === kind && config.name === name);
1940 let error;
1941 let deletedRecord = false;
1942
1943 if (!entityConfig || entityConfig !== null && entityConfig !== void 0 && entityConfig.__experimentalNoFetch) {
1944 return;
1945 }
1946
1947 const lock = await dispatch.__unstableAcquireStoreLock(STORE_NAME, ['entities', 'records', kind, name, recordId], {
1948 exclusive: true
1949 });
1950
1951 try {
1952 dispatch({
1953 type: 'DELETE_ENTITY_RECORD_START',
1954 kind,
1955 name,
1956 recordId
1957 });
1958 let hasError = false;
1959
1960 try {
1961 let path = `${entityConfig.baseURL}/${recordId}`;
1962
1963 if (query) {
1964 path = (0,external_wp_url_namespaceObject.addQueryArgs)(path, query);
1965 }
1966
1967 deletedRecord = await __unstableFetch({
1968 path,
1969 method: 'DELETE'
1970 });
1971 await dispatch(removeItems(kind, name, recordId, true));
1972 } catch (_error) {
1973 hasError = true;
1974 error = _error;
1975 }
1976
1977 dispatch({
1978 type: 'DELETE_ENTITY_RECORD_FINISH',
1979 kind,
1980 name,
1981 recordId,
1982 error
1983 });
1984
1985 if (hasError && throwOnError) {
1986 throw error;
1987 }
1988
1989 return deletedRecord;
1990 } finally {
1991 dispatch.__unstableReleaseStoreLock(lock);
1992 }
1993 };
1994 };
1995 /**
1996 * Returns an action object that triggers an
1997 * edit to an entity record.
1998 *
1999 * @param {string} kind Kind of the edited entity record.
2000 * @param {string} name Name of the edited entity record.
2001 * @param {number} recordId Record ID of the edited entity record.
2002 * @param {Object} edits The edits.
2003 * @param {Object} options Options for the edit.
2004 * @param {boolean} [options.undoIgnore] Whether to ignore the edit in undo history or not.
2005 *
2006 * @return {Object} Action object.
2007 */
2008
2009 const editEntityRecord = function (kind, name, recordId, edits) {
2010 let options = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {};
2011 return _ref2 => {
2012 let {
2013 select,
2014 dispatch
2015 } = _ref2;
2016 const entityConfig = select.getEntityConfig(kind, name);
2017
2018 if (!entityConfig) {
2019 throw new Error(`The entity being edited (${kind}, ${name}) does not have a loaded config.`);
2020 }
2021
2022 const {
2023 transientEdits = {},
2024 mergedEdits = {}
2025 } = entityConfig;
2026 const record = select.getRawEntityRecord(kind, name, recordId);
2027 const editedRecord = select.getEditedEntityRecord(kind, name, recordId);
2028 const edit = {
2029 kind,
2030 name,
2031 recordId,
2032 // Clear edits when they are equal to their persisted counterparts
2033 // so that the property is not considered dirty.
2034 edits: Object.keys(edits).reduce((acc, key) => {
2035 const recordValue = record[key];
2036 const editedRecordValue = editedRecord[key];
2037 const value = mergedEdits[key] ? { ...editedRecordValue,
2038 ...edits[key]
2039 } : edits[key];
2040 acc[key] = es6_default()(recordValue, value) ? undefined : value;
2041 return acc;
2042 }, {}),
2043 transientEdits
2044 };
2045 dispatch({
2046 type: 'EDIT_ENTITY_RECORD',
2047 ...edit,
2048 meta: {
2049 undo: !options.undoIgnore && { ...edit,
2050 // Send the current values for things like the first undo stack entry.
2051 edits: Object.keys(edits).reduce((acc, key) => {
2052 acc[key] = editedRecord[key];
2053 return acc;
2054 }, {})
2055 }
2056 }
2057 });
2058 };
2059 };
2060 /**
2061 * Action triggered to undo the last edit to
2062 * an entity record, if any.
2063 */
2064
2065 const undo = () => _ref3 => {
2066 let {
2067 select,
2068 dispatch
2069 } = _ref3;
2070 const undoEdit = select.getUndoEdit();
2071
2072 if (!undoEdit) {
2073 return;
2074 }
2075
2076 dispatch({
2077 type: 'EDIT_ENTITY_RECORD',
2078 ...undoEdit,
2079 meta: {
2080 isUndo: true
2081 }
2082 });
2083 };
2084 /**
2085 * Action triggered to redo the last undoed
2086 * edit to an entity record, if any.
2087 */
2088
2089 const redo = () => _ref4 => {
2090 let {
2091 select,
2092 dispatch
2093 } = _ref4;
2094 const redoEdit = select.getRedoEdit();
2095
2096 if (!redoEdit) {
2097 return;
2098 }
2099
2100 dispatch({
2101 type: 'EDIT_ENTITY_RECORD',
2102 ...redoEdit,
2103 meta: {
2104 isRedo: true
2105 }
2106 });
2107 };
2108 /**
2109 * Forces the creation of a new undo level.
2110 *
2111 * @return {Object} Action object.
2112 */
2113
2114 function __unstableCreateUndoLevel() {
2115 return {
2116 type: 'CREATE_UNDO_LEVEL'
2117 };
2118 }
2119 /**
2120 * Action triggered to save an entity record.
2121 *
2122 * @param {string} kind Kind of the received entity.
2123 * @param {string} name Name of the received entity.
2124 * @param {Object} record Record to be saved.
2125 * @param {Object} options Saving options.
2126 * @param {boolean} [options.isAutosave=false] Whether this is an autosave.
2127 * @param {Function} [options.__unstableFetch] Internal use only. Function to
2128 * call instead of `apiFetch()`.
2129 * Must return a promise.
2130 * @param {boolean} [options.throwOnError=false] If false, this action suppresses all
2131 * the exceptions. Defaults to false.
2132 */
2133
2134 const saveEntityRecord = function (kind, name, record) {
2135 let {
2136 isAutosave = false,
2137 __unstableFetch = (external_wp_apiFetch_default()),
2138 throwOnError = false
2139 } = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
2140 return async _ref5 => {
2141 let {
2142 select,
2143 resolveSelect,
2144 dispatch
2145 } = _ref5;
2146 const configs = await dispatch(getOrLoadEntitiesConfig(kind));
2147 const entityConfig = configs.find(config => config.kind === kind && config.name === name);
2148
2149 if (!entityConfig || entityConfig !== null && entityConfig !== void 0 && entityConfig.__experimentalNoFetch) {
2150 return;
2151 }
2152
2153 const entityIdKey = entityConfig.key || DEFAULT_ENTITY_KEY;
2154 const recordId = record[entityIdKey];
2155 const lock = await dispatch.__unstableAcquireStoreLock(STORE_NAME, ['entities', 'records', kind, name, recordId || esm_browser_v4()], {
2156 exclusive: true
2157 });
2158
2159 try {
2160 // Evaluate optimized edits.
2161 // (Function edits that should be evaluated on save to avoid expensive computations on every edit.)
2162 for (const [key, value] of Object.entries(record)) {
2163 if (typeof value === 'function') {
2164 const evaluatedValue = value(select.getEditedEntityRecord(kind, name, recordId));
2165 dispatch.editEntityRecord(kind, name, recordId, {
2166 [key]: evaluatedValue
2167 }, {
2168 undoIgnore: true
2169 });
2170 record[key] = evaluatedValue;
2171 }
2172 }
2173
2174 dispatch({
2175 type: 'SAVE_ENTITY_RECORD_START',
2176 kind,
2177 name,
2178 recordId,
2179 isAutosave
2180 });
2181 let updatedRecord;
2182 let error;
2183 let hasError = false;
2184
2185 try {
2186 const path = `${entityConfig.baseURL}${recordId ? '/' + recordId : ''}`;
2187 const persistedRecord = select.getRawEntityRecord(kind, name, recordId);
2188
2189 if (isAutosave) {
2190 // Most of this autosave logic is very specific to posts.
2191 // This is fine for now as it is the only supported autosave,
2192 // but ideally this should all be handled in the back end,
2193 // so the client just sends and receives objects.
2194 const currentUser = select.getCurrentUser();
2195 const currentUserId = currentUser ? currentUser.id : undefined;
2196 const autosavePost = await resolveSelect.getAutosave(persistedRecord.type, persistedRecord.id, currentUserId); // Autosaves need all expected fields to be present.
2197 // So we fallback to the previous autosave and then
2198 // to the actual persisted entity if the edits don't
2199 // have a value.
2200
2201 let data = { ...persistedRecord,
2202 ...autosavePost,
2203 ...record
2204 };
2205 data = Object.keys(data).reduce((acc, key) => {
2206 if (['title', 'excerpt', 'content'].includes(key)) {
2207 acc[key] = data[key];
2208 }
2209
2210 return acc;
2211 }, {
2212 status: data.status === 'auto-draft' ? 'draft' : data.status
2213 });
2214 updatedRecord = await __unstableFetch({
2215 path: `${path}/autosaves`,
2216 method: 'POST',
2217 data
2218 }); // An autosave may be processed by the server as a regular save
2219 // when its update is requested by the author and the post had
2220 // draft or auto-draft status.
2221
2222 if (persistedRecord.id === updatedRecord.id) {
2223 let newRecord = { ...persistedRecord,
2224 ...data,
2225 ...updatedRecord
2226 };
2227 newRecord = Object.keys(newRecord).reduce((acc, key) => {
2228 // These properties are persisted in autosaves.
2229 if (['title', 'excerpt', 'content'].includes(key)) {
2230 acc[key] = newRecord[key];
2231 } else if (key === 'status') {
2232 // Status is only persisted in autosaves when going from
2233 // "auto-draft" to "draft".
2234 acc[key] = persistedRecord.status === 'auto-draft' && newRecord.status === 'draft' ? newRecord.status : persistedRecord.status;
2235 } else {
2236 // These properties are not persisted in autosaves.
2237 acc[key] = persistedRecord[key];
2238 }
2239
2240 return acc;
2241 }, {});
2242 dispatch.receiveEntityRecords(kind, name, newRecord, undefined, true);
2243 } else {
2244 dispatch.receiveAutosaves(persistedRecord.id, updatedRecord);
2245 }
2246 } else {
2247 let edits = record;
2248
2249 if (entityConfig.__unstablePrePersist) {
2250 edits = { ...edits,
2251 ...entityConfig.__unstablePrePersist(persistedRecord, edits)
2252 };
2253 }
2254
2255 updatedRecord = await __unstableFetch({
2256 path,
2257 method: recordId ? 'PUT' : 'POST',
2258 data: edits
2259 });
2260 dispatch.receiveEntityRecords(kind, name, updatedRecord, undefined, true, edits);
2261 }
2262 } catch (_error) {
2263 hasError = true;
2264 error = _error;
2265 }
2266
2267 dispatch({
2268 type: 'SAVE_ENTITY_RECORD_FINISH',
2269 kind,
2270 name,
2271 recordId,
2272 error,
2273 isAutosave
2274 });
2275
2276 if (hasError && throwOnError) {
2277 throw error;
2278 }
2279
2280 return updatedRecord;
2281 } finally {
2282 dispatch.__unstableReleaseStoreLock(lock);
2283 }
2284 };
2285 };
2286 /**
2287 * Runs multiple core-data actions at the same time using one API request.
2288 *
2289 * Example:
2290 *
2291 * ```
2292 * const [ savedRecord, updatedRecord, deletedRecord ] =
2293 * await dispatch( 'core' ).__experimentalBatch( [
2294 * ( { saveEntityRecord } ) => saveEntityRecord( 'root', 'widget', widget ),
2295 * ( { saveEditedEntityRecord } ) => saveEntityRecord( 'root', 'widget', 123 ),
2296 * ( { deleteEntityRecord } ) => deleteEntityRecord( 'root', 'widget', 123, null ),
2297 * ] );
2298 * ```
2299 *
2300 * @param {Array} requests Array of functions which are invoked simultaneously.
2301 * Each function is passed an object containing
2302 * `saveEntityRecord`, `saveEditedEntityRecord`, and
2303 * `deleteEntityRecord`.
2304 *
2305 * @return {(thunkArgs: Object) => Promise} A promise that resolves to an array containing the return
2306 * values of each function given in `requests`.
2307 */
2308
2309 const __experimentalBatch = requests => async _ref6 => {
2310 let {
2311 dispatch
2312 } = _ref6;
2313 const batch = createBatch();
2314 const api = {
2315 saveEntityRecord(kind, name, record, options) {
2316 return batch.add(add => dispatch.saveEntityRecord(kind, name, record, { ...options,
2317 __unstableFetch: add
2318 }));
2319 },
2320
2321 saveEditedEntityRecord(kind, name, recordId, options) {
2322 return batch.add(add => dispatch.saveEditedEntityRecord(kind, name, recordId, { ...options,
2323 __unstableFetch: add
2324 }));
2325 },
2326
2327 deleteEntityRecord(kind, name, recordId, query, options) {
2328 return batch.add(add => dispatch.deleteEntityRecord(kind, name, recordId, query, { ...options,
2329 __unstableFetch: add
2330 }));
2331 }
2332
2333 };
2334 const resultPromises = requests.map(request => request(api));
2335 const [, ...results] = await Promise.all([batch.run(), ...resultPromises]);
2336 return results;
2337 };
2338 /**
2339 * Action triggered to save an entity record's edits.
2340 *
2341 * @param {string} kind Kind of the entity.
2342 * @param {string} name Name of the entity.
2343 * @param {Object} recordId ID of the record.
2344 * @param {Object} options Saving options.
2345 */
2346
2347 const saveEditedEntityRecord = (kind, name, recordId, options) => async _ref7 => {
2348 let {
2349 select,
2350 dispatch
2351 } = _ref7;
2352
2353 if (!select.hasEditsForEntityRecord(kind, name, recordId)) {
2354 return;
2355 }
2356
2357 const configs = await dispatch(getOrLoadEntitiesConfig(kind));
2358 const entityConfig = configs.find(config => config.kind === kind && config.name === name);
2359
2360 if (!entityConfig) {
2361 return;
2362 }
2363
2364 const entityIdKey = entityConfig.key || DEFAULT_ENTITY_KEY;
2365 const edits = select.getEntityRecordNonTransientEdits(kind, name, recordId);
2366 const record = {
2367 [entityIdKey]: recordId,
2368 ...edits
2369 };
2370 return await dispatch.saveEntityRecord(kind, name, record, options);
2371 };
2372 /**
2373 * Action triggered to save only specified properties for the entity.
2374 *
2375 * @param {string} kind Kind of the entity.
2376 * @param {string} name Name of the entity.
2377 * @param {Object} recordId ID of the record.
2378 * @param {Array} itemsToSave List of entity properties to save.
2379 * @param {Object} options Saving options.
2380 */
2381
2382 const __experimentalSaveSpecifiedEntityEdits = (kind, name, recordId, itemsToSave, options) => async _ref8 => {
2383 let {
2384 select,
2385 dispatch
2386 } = _ref8;
2387
2388 if (!select.hasEditsForEntityRecord(kind, name, recordId)) {
2389 return;
2390 }
2391
2392 const edits = select.getEntityRecordNonTransientEdits(kind, name, recordId);
2393 const editsToSave = {};
2394
2395 for (const edit in edits) {
2396 if (itemsToSave.some(item => item === edit)) {
2397 editsToSave[edit] = edits[edit];
2398 }
2399 }
2400
2401 return await dispatch.saveEntityRecord(kind, name, editsToSave, options);
2402 };
2403 /**
2404 * Returns an action object used in signalling that Upload permissions have been received.
2405 *
2406 * @deprecated since WP 5.9, use receiveUserPermission instead.
2407 *
2408 * @param {boolean} hasUploadPermissions Does the user have permission to upload files?
2409 *
2410 * @return {Object} Action object.
2411 */
2412
2413 function receiveUploadPermissions(hasUploadPermissions) {
2414 external_wp_deprecated_default()("wp.data.dispatch( 'core' ).receiveUploadPermissions", {
2415 since: '5.9',
2416 alternative: 'receiveUserPermission'
2417 });
2418 return receiveUserPermission('create/media', hasUploadPermissions);
2419 }
2420 /**
2421 * Returns an action object used in signalling that the current user has
2422 * permission to perform an action on a REST resource.
2423 * Ignored from documentation as it's internal to the data store.
2424 *
2425 * @ignore
2426 *
2427 * @param {string} key A key that represents the action and REST resource.
2428 * @param {boolean} isAllowed Whether or not the user can perform the action.
2429 *
2430 * @return {Object} Action object.
2431 */
2432
2433 function receiveUserPermission(key, isAllowed) {
2434 return {
2435 type: 'RECEIVE_USER_PERMISSION',
2436 key,
2437 isAllowed
2438 };
2439 }
2440 /**
2441 * Returns an action object used in signalling that the autosaves for a
2442 * post have been received.
2443 * Ignored from documentation as it's internal to the data store.
2444 *
2445 * @ignore
2446 *
2447 * @param {number} postId The id of the post that is parent to the autosave.
2448 * @param {Array|Object} autosaves An array of autosaves or singular autosave object.
2449 *
2450 * @return {Object} Action object.
2451 */
2452
2453 function receiveAutosaves(postId, autosaves) {
2454 return {
2455 type: 'RECEIVE_AUTOSAVES',
2456 postId,
2457 autosaves: Array.isArray(autosaves) ? autosaves : [autosaves]
2458 };
2459 }
2460
2461 ;// CONCATENATED MODULE: ./packages/core-data/build-module/entities.js
2462 /**
2463 * External dependencies
2464 */
2465
2466
2467 /**
2468 * WordPress dependencies
2469 */
2470
2471
2472
2473 /**
2474 * Internal dependencies
2475 */
2476
2477
2478 const DEFAULT_ENTITY_KEY = 'id';
2479 const POST_RAW_ATTRIBUTES = ['title', 'excerpt', 'content'];
2480 const rootEntitiesConfig = [{
2481 label: (0,external_wp_i18n_namespaceObject.__)('Base'),
2482 kind: 'root',
2483 name: '__unstableBase',
2484 baseURL: '/',
2485 baseURLParams: {
2486 _fields: ['description', 'gmt_offset', 'home', 'name', 'site_icon', 'site_icon_url', 'site_logo', 'timezone_string', 'url'].join(',')
2487 }
2488 }, {
2489 label: (0,external_wp_i18n_namespaceObject.__)('Site'),
2490 name: 'site',
2491 kind: 'root',
2492 baseURL: '/wp/v2/settings',
2493 getTitle: record => {
2494 return (0,external_lodash_namespaceObject.get)(record, ['title'], (0,external_wp_i18n_namespaceObject.__)('Site Title'));
2495 }
2496 }, {
2497 label: (0,external_wp_i18n_namespaceObject.__)('Post Type'),
2498 name: 'postType',
2499 kind: 'root',
2500 key: 'slug',
2501 baseURL: '/wp/v2/types',
2502 baseURLParams: {
2503 context: 'edit'
2504 }
2505 }, {
2506 name: 'media',
2507 kind: 'root',
2508 baseURL: '/wp/v2/media',
2509 baseURLParams: {
2510 context: 'edit'
2511 },
2512 plural: 'mediaItems',
2513 label: (0,external_wp_i18n_namespaceObject.__)('Media'),
2514 rawAttributes: ['caption', 'title', 'description']
2515 }, {
2516 name: 'taxonomy',
2517 kind: 'root',
2518 key: 'slug',
2519 baseURL: '/wp/v2/taxonomies',
2520 baseURLParams: {
2521 context: 'edit'
2522 },
2523 plural: 'taxonomies',
2524 label: (0,external_wp_i18n_namespaceObject.__)('Taxonomy')
2525 }, {
2526 name: 'sidebar',
2527 kind: 'root',
2528 baseURL: '/wp/v2/sidebars',
2529 baseURLParams: {
2530 context: 'edit'
2531 },
2532 plural: 'sidebars',
2533 transientEdits: {
2534 blocks: true
2535 },
2536 label: (0,external_wp_i18n_namespaceObject.__)('Widget areas')
2537 }, {
2538 name: 'widget',
2539 kind: 'root',
2540 baseURL: '/wp/v2/widgets',
2541 baseURLParams: {
2542 context: 'edit'
2543 },
2544 plural: 'widgets',
2545 transientEdits: {
2546 blocks: true
2547 },
2548 label: (0,external_wp_i18n_namespaceObject.__)('Widgets')
2549 }, {
2550 name: 'widgetType',
2551 kind: 'root',
2552 baseURL: '/wp/v2/widget-types',
2553 baseURLParams: {
2554 context: 'edit'
2555 },
2556 plural: 'widgetTypes',
2557 label: (0,external_wp_i18n_namespaceObject.__)('Widget types')
2558 }, {
2559 label: (0,external_wp_i18n_namespaceObject.__)('User'),
2560 name: 'user',
2561 kind: 'root',
2562 baseURL: '/wp/v2/users',
2563 baseURLParams: {
2564 context: 'edit'
2565 },
2566 plural: 'users'
2567 }, {
2568 name: 'comment',
2569 kind: 'root',
2570 baseURL: '/wp/v2/comments',
2571 baseURLParams: {
2572 context: 'edit'
2573 },
2574 plural: 'comments',
2575 label: (0,external_wp_i18n_namespaceObject.__)('Comment')
2576 }, {
2577 name: 'menu',
2578 kind: 'root',
2579 baseURL: '/wp/v2/menus',
2580 baseURLParams: {
2581 context: 'edit'
2582 },
2583 plural: 'menus',
2584 label: (0,external_wp_i18n_namespaceObject.__)('Menu')
2585 }, {
2586 name: 'menuItem',
2587 kind: 'root',
2588 baseURL: '/wp/v2/menu-items',
2589 baseURLParams: {
2590 context: 'edit'
2591 },
2592 plural: 'menuItems',
2593 label: (0,external_wp_i18n_namespaceObject.__)('Menu Item'),
2594 rawAttributes: ['title']
2595 }, {
2596 name: 'menuLocation',
2597 kind: 'root',
2598 baseURL: '/wp/v2/menu-locations',
2599 baseURLParams: {
2600 context: 'edit'
2601 },
2602 plural: 'menuLocations',
2603 label: (0,external_wp_i18n_namespaceObject.__)('Menu Location'),
2604 key: 'name'
2605 }, {
2606 label: (0,external_wp_i18n_namespaceObject.__)('Global Styles'),
2607 name: 'globalStyles',
2608 kind: 'root',
2609 baseURL: '/wp/v2/global-styles',
2610 baseURLParams: {
2611 context: 'edit'
2612 },
2613 plural: 'globalStylesVariations',
2614 // Should be different than name.
2615 getTitle: record => {
2616 var _record$title;
2617
2618 return (record === null || record === void 0 ? void 0 : (_record$title = record.title) === null || _record$title === void 0 ? void 0 : _record$title.rendered) || (record === null || record === void 0 ? void 0 : record.title);
2619 }
2620 }, {
2621 label: (0,external_wp_i18n_namespaceObject.__)('Themes'),
2622 name: 'theme',
2623 kind: 'root',
2624 baseURL: '/wp/v2/themes',
2625 baseURLParams: {
2626 context: 'edit'
2627 },
2628 key: 'stylesheet'
2629 }, {
2630 label: (0,external_wp_i18n_namespaceObject.__)('Plugins'),
2631 name: 'plugin',
2632 kind: 'root',
2633 baseURL: '/wp/v2/plugins',
2634 baseURLParams: {
2635 context: 'edit'
2636 },
2637 key: 'plugin'
2638 }];
2639 const additionalEntityConfigLoaders = [{
2640 kind: 'postType',
2641 loadEntities: loadPostTypeEntities
2642 }, {
2643 kind: 'taxonomy',
2644 loadEntities: loadTaxonomyEntities
2645 }];
2646 /**
2647 * Returns a function to be used to retrieve extra edits to apply before persisting a post type.
2648 *
2649 * @param {Object} persistedRecord Already persisted Post
2650 * @param {Object} edits Edits.
2651 * @return {Object} Updated edits.
2652 */
2653
2654 const prePersistPostType = (persistedRecord, edits) => {
2655 const newEdits = {};
2656
2657 if ((persistedRecord === null || persistedRecord === void 0 ? void 0 : persistedRecord.status) === 'auto-draft') {
2658 // Saving an auto-draft should create a draft by default.
2659 if (!edits.status && !newEdits.status) {
2660 newEdits.status = 'draft';
2661 } // Fix the auto-draft default title.
2662
2663
2664 if ((!edits.title || edits.title === 'Auto Draft') && !newEdits.title && (!(persistedRecord !== null && persistedRecord !== void 0 && persistedRecord.title) || (persistedRecord === null || persistedRecord === void 0 ? void 0 : persistedRecord.title) === 'Auto Draft')) {
2665 newEdits.title = '';
2666 }
2667 }
2668
2669 return newEdits;
2670 };
2671 /**
2672 * Returns the list of post type entities.
2673 *
2674 * @return {Promise} Entities promise
2675 */
2676
2677 async function loadPostTypeEntities() {
2678 const postTypes = await external_wp_apiFetch_default()({
2679 path: '/wp/v2/types?context=view'
2680 });
2681 return (0,external_lodash_namespaceObject.map)(postTypes, (postType, name) => {
2682 var _postType$rest_namesp;
2683
2684 const isTemplate = ['wp_template', 'wp_template_part'].includes(name);
2685 const namespace = (_postType$rest_namesp = postType === null || postType === void 0 ? void 0 : postType.rest_namespace) !== null && _postType$rest_namesp !== void 0 ? _postType$rest_namesp : 'wp/v2';
2686 return {
2687 kind: 'postType',
2688 baseURL: `/${namespace}/${postType.rest_base}`,
2689 baseURLParams: {
2690 context: 'edit'
2691 },
2692 name,
2693 label: postType.name,
2694 transientEdits: {
2695 blocks: true,
2696 selection: true
2697 },
2698 mergedEdits: {
2699 meta: true
2700 },
2701 rawAttributes: POST_RAW_ATTRIBUTES,
2702 getTitle: record => {
2703 var _record$title2, _record$slug;
2704
2705 return (record === null || record === void 0 ? void 0 : (_record$title2 = record.title) === null || _record$title2 === void 0 ? void 0 : _record$title2.rendered) || (record === null || record === void 0 ? void 0 : record.title) || (isTemplate ? capitalCase((_record$slug = record.slug) !== null && _record$slug !== void 0 ? _record$slug : '') : String(record.id));
2706 },
2707 __unstablePrePersist: isTemplate ? undefined : prePersistPostType,
2708 __unstable_rest_base: postType.rest_base
2709 };
2710 });
2711 }
2712 /**
2713 * Returns the list of the taxonomies entities.
2714 *
2715 * @return {Promise} Entities promise
2716 */
2717
2718
2719 async function loadTaxonomyEntities() {
2720 const taxonomies = await external_wp_apiFetch_default()({
2721 path: '/wp/v2/taxonomies?context=view'
2722 });
2723 return (0,external_lodash_namespaceObject.map)(taxonomies, (taxonomy, name) => {
2724 var _taxonomy$rest_namesp;
2725
2726 const namespace = (_taxonomy$rest_namesp = taxonomy === null || taxonomy === void 0 ? void 0 : taxonomy.rest_namespace) !== null && _taxonomy$rest_namesp !== void 0 ? _taxonomy$rest_namesp : 'wp/v2';
2727 return {
2728 kind: 'taxonomy',
2729 baseURL: `/${namespace}/${taxonomy.rest_base}`,
2730 baseURLParams: {
2731 context: 'edit'
2732 },
2733 name,
2734 label: taxonomy.name
2735 };
2736 });
2737 }
2738 /**
2739 * Returns the entity's getter method name given its kind and name.
2740 *
2741 * @example
2742 * ```js
2743 * const nameSingular = getMethodName( 'root', 'theme', 'get' );
2744 * // nameSingular is getRootTheme
2745 *
2746 * const namePlural = getMethodName( 'root', 'theme', 'set' );
2747 * // namePlural is setRootThemes
2748 * ```
2749 *
2750 * @param {string} kind Entity kind.
2751 * @param {string} name Entity name.
2752 * @param {string} prefix Function prefix.
2753 * @param {boolean} usePlural Whether to use the plural form or not.
2754 *
2755 * @return {string} Method name
2756 */
2757
2758
2759 const getMethodName = function (kind, name) {
2760 let prefix = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'get';
2761 let usePlural = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
2762 const entityConfig = rootEntitiesConfig.find(config => config.kind === kind && config.name === name);
2763 const kindPrefix = kind === 'root' ? '' : pascalCase(kind);
2764 const nameSuffix = pascalCase(name) + (usePlural ? 's' : '');
2765 const suffix = usePlural && 'plural' in entityConfig && entityConfig !== null && entityConfig !== void 0 && entityConfig.plural ? pascalCase(entityConfig.plural) : nameSuffix;
2766 return `${prefix}${kindPrefix}${suffix}`;
2767 };
2768 /**
2769 * Loads the kind entities into the store.
2770 *
2771 * @param {string} kind Kind
2772 *
2773 * @return {(thunkArgs: object) => Promise<Array>} Entities
2774 */
2775
2776 const getOrLoadEntitiesConfig = kind => async _ref => {
2777 let {
2778 select,
2779 dispatch
2780 } = _ref;
2781 let configs = select.getEntitiesConfig(kind);
2782
2783 if (configs && configs.length !== 0) {
2784 return configs;
2785 }
2786
2787 const loader = additionalEntityConfigLoaders.find(l => l.kind === kind);
2788
2789 if (!loader) {
2790 return [];
2791 }
2792
2793 configs = await loader.loadEntities();
2794 dispatch(addEntities(configs));
2795 return configs;
2796 };
2797
2798 ;// CONCATENATED MODULE: ./packages/core-data/build-module/utils/get-normalized-comma-separable.js
2799 /**
2800 * Given a value which can be specified as one or the other of a comma-separated
2801 * string or an array, returns a value normalized to an array of strings, or
2802 * null if the value cannot be interpreted as either.
2803 *
2804 * @param {string|string[]|*} value
2805 *
2806 * @return {?(string[])} Normalized field value.
2807 */
2808 function getNormalizedCommaSeparable(value) {
2809 if (typeof value === 'string') {
2810 return value.split(',');
2811 } else if (Array.isArray(value)) {
2812 return value;
2813 }
2814
2815 return null;
2816 }
2817
2818 /* harmony default export */ var get_normalized_comma_separable = (getNormalizedCommaSeparable);
2819
2820 ;// CONCATENATED MODULE: ./packages/core-data/build-module/utils/with-weak-map-cache.js
2821 /**
2822 * Given a function, returns an enhanced function which caches the result and
2823 * tracks in WeakMap. The result is only cached if the original function is
2824 * passed a valid object-like argument (requirement for WeakMap key).
2825 *
2826 * @param {Function} fn Original function.
2827 *
2828 * @return {Function} Enhanced caching function.
2829 */
2830 function withWeakMapCache(fn) {
2831 const cache = new WeakMap();
2832 return key => {
2833 let value;
2834
2835 if (cache.has(key)) {
2836 value = cache.get(key);
2837 } else {
2838 value = fn(key); // Can reach here if key is not valid for WeakMap, since `has`
2839 // will return false for invalid key. Since `set` will throw,
2840 // ensure that key is valid before setting into cache.
2841
2842 if (key !== null && typeof key === 'object') {
2843 cache.set(key, value);
2844 }
2845 }
2846
2847 return value;
2848 };
2849 }
2850
2851 /* harmony default export */ var with_weak_map_cache = (withWeakMapCache);
2852
2853 ;// CONCATENATED MODULE: ./packages/core-data/build-module/queried-data/get-query-parts.js
2854 /**
2855 * WordPress dependencies
2856 */
2857
2858 /**
2859 * Internal dependencies
2860 */
2861
2862
2863 /**
2864 * An object of properties describing a specific query.
2865 *
2866 * @typedef {Object} WPQueriedDataQueryParts
2867 *
2868 * @property {number} page The query page (1-based index, default 1).
2869 * @property {number} perPage Items per page for query (default 10).
2870 * @property {string} stableKey An encoded stable string of all non-
2871 * pagination, non-fields query parameters.
2872 * @property {?(string[])} fields Target subset of fields to derive from
2873 * item objects.
2874 * @property {?(number[])} include Specific item IDs to include.
2875 * @property {string} context Scope under which the request is made;
2876 * determines returned fields in response.
2877 */
2878
2879 /**
2880 * Given a query object, returns an object of parts, including pagination
2881 * details (`page` and `perPage`, or default values). All other properties are
2882 * encoded into a stable (idempotent) `stableKey` value.
2883 *
2884 * @param {Object} query Optional query object.
2885 *
2886 * @return {WPQueriedDataQueryParts} Query parts.
2887 */
2888
2889 function getQueryParts(query) {
2890 /**
2891 * @type {WPQueriedDataQueryParts}
2892 */
2893 const parts = {
2894 stableKey: '',
2895 page: 1,
2896 perPage: 10,
2897 fields: null,
2898 include: null,
2899 context: 'default'
2900 }; // Ensure stable key by sorting keys. Also more efficient for iterating.
2901
2902 const keys = Object.keys(query).sort();
2903
2904 for (let i = 0; i < keys.length; i++) {
2905 const key = keys[i];
2906 let value = query[key];
2907
2908 switch (key) {
2909 case 'page':
2910 parts[key] = Number(value);
2911 break;
2912
2913 case 'per_page':
2914 parts.perPage = Number(value);
2915 break;
2916
2917 case 'context':
2918 parts.context = value;
2919 break;
2920
2921 default:
2922 // While in theory, we could exclude "_fields" from the stableKey
2923 // because two request with different fields have the same results
2924 // We're not able to ensure that because the server can decide to omit
2925 // fields from the response even if we explicitly asked for it.
2926 // Example: Asking for titles in posts without title support.
2927 if (key === '_fields') {
2928 var _getNormalizedCommaSe;
2929
2930 parts.fields = (_getNormalizedCommaSe = get_normalized_comma_separable(value)) !== null && _getNormalizedCommaSe !== void 0 ? _getNormalizedCommaSe : []; // Make sure to normalize value for `stableKey`
2931
2932 value = parts.fields.join();
2933 } // Two requests with different include values cannot have same results.
2934
2935
2936 if (key === 'include') {
2937 var _getNormalizedCommaSe2;
2938
2939 if (typeof value === 'number') {
2940 value = value.toString();
2941 }
2942
2943 parts.include = ((_getNormalizedCommaSe2 = get_normalized_comma_separable(value)) !== null && _getNormalizedCommaSe2 !== void 0 ? _getNormalizedCommaSe2 : []).map(Number); // Normalize value for `stableKey`.
2944
2945 value = parts.include.join();
2946 } // While it could be any deterministic string, for simplicity's
2947 // sake mimic querystring encoding for stable key.
2948 //
2949 // TODO: For consistency with PHP implementation, addQueryArgs
2950 // should accept a key value pair, which may optimize its
2951 // implementation for our use here, vs. iterating an object
2952 // with only a single key.
2953
2954
2955 parts.stableKey += (parts.stableKey ? '&' : '') + (0,external_wp_url_namespaceObject.addQueryArgs)('', {
2956 [key]: value
2957 }).slice(1);
2958 }
2959 }
2960
2961 return parts;
2962 }
2963 /* harmony default export */ var get_query_parts = (with_weak_map_cache(getQueryParts));
2964
2965 ;// CONCATENATED MODULE: ./packages/core-data/build-module/queried-data/reducer.js
2966 /**
2967 * External dependencies
2968 */
2969
2970 /**
2971 * WordPress dependencies
2972 */
2973
2974
2975
2976 /**
2977 * Internal dependencies
2978 */
2979
2980
2981
2982
2983
2984 function getContextFromAction(action) {
2985 const {
2986 query
2987 } = action;
2988
2989 if (!query) {
2990 return 'default';
2991 }
2992
2993 const queryParts = get_query_parts(query);
2994 return queryParts.context;
2995 }
2996 /**
2997 * Returns a merged array of item IDs, given details of the received paginated
2998 * items. The array is sparse-like with `undefined` entries where holes exist.
2999 *
3000 * @param {?Array<number>} itemIds Original item IDs (default empty array).
3001 * @param {number[]} nextItemIds Item IDs to merge.
3002 * @param {number} page Page of items merged.
3003 * @param {number} perPage Number of items per page.
3004 *
3005 * @return {number[]} Merged array of item IDs.
3006 */
3007
3008
3009 function getMergedItemIds(itemIds, nextItemIds, page, perPage) {
3010 var _itemIds$length;
3011
3012 const receivedAllIds = page === 1 && perPage === -1;
3013
3014 if (receivedAllIds) {
3015 return nextItemIds;
3016 }
3017
3018 const nextItemIdsStartIndex = (page - 1) * perPage; // If later page has already been received, default to the larger known
3019 // size of the existing array, else calculate as extending the existing.
3020
3021 const size = Math.max((_itemIds$length = itemIds === null || itemIds === void 0 ? void 0 : itemIds.length) !== null && _itemIds$length !== void 0 ? _itemIds$length : 0, nextItemIdsStartIndex + nextItemIds.length); // Preallocate array since size is known.
3022
3023 const mergedItemIds = new Array(size);
3024
3025 for (let i = 0; i < size; i++) {
3026 // Preserve existing item ID except for subset of range of next items.
3027 const isInNextItemsRange = i >= nextItemIdsStartIndex && i < nextItemIdsStartIndex + nextItemIds.length;
3028 mergedItemIds[i] = isInNextItemsRange ? nextItemIds[i - nextItemIdsStartIndex] : itemIds === null || itemIds === void 0 ? void 0 : itemIds[i];
3029 }
3030
3031 return mergedItemIds;
3032 }
3033 /**
3034 * Reducer tracking items state, keyed by ID. Items are assumed to be normal,
3035 * where identifiers are common across all queries.
3036 *
3037 * @param {Object} state Current state.
3038 * @param {Object} action Dispatched action.
3039 *
3040 * @return {Object} Next state.
3041 */
3042
3043 function items() {
3044 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3045 let action = arguments.length > 1 ? arguments[1] : undefined;
3046
3047 switch (action.type) {
3048 case 'RECEIVE_ITEMS':
3049 {
3050 const context = getContextFromAction(action);
3051 const key = action.key || DEFAULT_ENTITY_KEY;
3052 return { ...state,
3053 [context]: { ...state[context],
3054 ...action.items.reduce((accumulator, value) => {
3055 var _state$context;
3056
3057 const itemId = value[key];
3058 accumulator[itemId] = conservativeMapItem(state === null || state === void 0 ? void 0 : (_state$context = state[context]) === null || _state$context === void 0 ? void 0 : _state$context[itemId], value);
3059 return accumulator;
3060 }, {})
3061 }
3062 };
3063 }
3064
3065 case 'REMOVE_ITEMS':
3066 return (0,external_lodash_namespaceObject.mapValues)(state, contextState => (0,external_lodash_namespaceObject.omit)(contextState, action.itemIds));
3067 }
3068
3069 return state;
3070 }
3071 /**
3072 * Reducer tracking item completeness, keyed by ID. A complete item is one for
3073 * which all fields are known. This is used in supporting `_fields` queries,
3074 * where not all properties associated with an entity are necessarily returned.
3075 * In such cases, completeness is used as an indication of whether it would be
3076 * safe to use queried data for a non-`_fields`-limited request.
3077 *
3078 * @param {Object<string,Object<string,boolean>>} state Current state.
3079 * @param {Object} action Dispatched action.
3080 *
3081 * @return {Object<string,Object<string,boolean>>} Next state.
3082 */
3083
3084 function itemIsComplete() {
3085 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3086 let action = arguments.length > 1 ? arguments[1] : undefined;
3087
3088 switch (action.type) {
3089 case 'RECEIVE_ITEMS':
3090 {
3091 const context = getContextFromAction(action);
3092 const {
3093 query,
3094 key = DEFAULT_ENTITY_KEY
3095 } = action; // An item is considered complete if it is received without an associated
3096 // fields query. Ideally, this would be implemented in such a way where the
3097 // complete aggregate of all fields would satisfy completeness. Since the
3098 // fields are not consistent across all entities, this would require
3099 // introspection on the REST schema for each entity to know which fields
3100 // compose a complete item for that entity.
3101
3102 const queryParts = query ? get_query_parts(query) : {};
3103 const isCompleteQuery = !query || !Array.isArray(queryParts.fields);
3104 return { ...state,
3105 [context]: { ...state[context],
3106 ...action.items.reduce((result, item) => {
3107 var _state$context2;
3108
3109 const itemId = item[key]; // Defer to completeness if already assigned. Technically the
3110 // data may be outdated if receiving items for a field subset.
3111
3112 result[itemId] = (state === null || state === void 0 ? void 0 : (_state$context2 = state[context]) === null || _state$context2 === void 0 ? void 0 : _state$context2[itemId]) || isCompleteQuery;
3113 return result;
3114 }, {})
3115 }
3116 };
3117 }
3118
3119 case 'REMOVE_ITEMS':
3120 return (0,external_lodash_namespaceObject.mapValues)(state, contextState => (0,external_lodash_namespaceObject.omit)(contextState, action.itemIds));
3121 }
3122
3123 return state;
3124 }
3125 /**
3126 * Reducer tracking queries state, keyed by stable query key. Each reducer
3127 * query object includes `itemIds` and `requestingPageByPerPage`.
3128 *
3129 * @param {Object} state Current state.
3130 * @param {Object} action Dispatched action.
3131 *
3132 * @return {Object} Next state.
3133 */
3134
3135 const receiveQueries = (0,external_wp_compose_namespaceObject.compose)([// Limit to matching action type so we don't attempt to replace action on
3136 // an unhandled action.
3137 if_matching_action(action => 'query' in action), // Inject query parts into action for use both in `onSubKey` and reducer.
3138 replace_action(action => {
3139 // `ifMatchingAction` still passes on initialization, where state is
3140 // undefined and a query is not assigned. Avoid attempting to parse
3141 // parts. `onSubKey` will omit by lack of `stableKey`.
3142 if (action.query) {
3143 return { ...action,
3144 ...get_query_parts(action.query)
3145 };
3146 }
3147
3148 return action;
3149 }), on_sub_key('context'), // Queries shape is shared, but keyed by query `stableKey` part. Original
3150 // reducer tracks only a single query object.
3151 on_sub_key('stableKey')])(function () {
3152 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null;
3153 let action = arguments.length > 1 ? arguments[1] : undefined;
3154 const {
3155 type,
3156 page,
3157 perPage,
3158 key = DEFAULT_ENTITY_KEY
3159 } = action;
3160
3161 if (type !== 'RECEIVE_ITEMS') {
3162 return state;
3163 }
3164
3165 return getMergedItemIds(state || [], (0,external_lodash_namespaceObject.map)(action.items, key), page, perPage);
3166 });
3167 /**
3168 * Reducer tracking queries state.
3169 *
3170 * @param {Object} state Current state.
3171 * @param {Object} action Dispatched action.
3172 *
3173 * @return {Object} Next state.
3174 */
3175
3176 const queries = function () {
3177 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3178 let action = arguments.length > 1 ? arguments[1] : undefined;
3179
3180 switch (action.type) {
3181 case 'RECEIVE_ITEMS':
3182 return receiveQueries(state, action);
3183
3184 case 'REMOVE_ITEMS':
3185 const removedItems = action.itemIds.reduce((result, itemId) => {
3186 result[itemId] = true;
3187 return result;
3188 }, {});
3189 return (0,external_lodash_namespaceObject.mapValues)(state, contextQueries => {
3190 return (0,external_lodash_namespaceObject.mapValues)(contextQueries, queryItems => {
3191 return queryItems.filter(queryId => {
3192 return !removedItems[queryId];
3193 });
3194 });
3195 });
3196
3197 default:
3198 return state;
3199 }
3200 };
3201
3202 /* harmony default export */ var reducer = ((0,external_wp_data_namespaceObject.combineReducers)({
3203 items,
3204 itemIsComplete,
3205 queries
3206 }));
3207
3208 ;// CONCATENATED MODULE: ./packages/core-data/build-module/reducer.js
3209 /**
3210 * External dependencies
3211 */
3212
3213
3214 /**
3215 * WordPress dependencies
3216 */
3217
3218
3219
3220
3221 /**
3222 * Internal dependencies
3223 */
3224
3225
3226
3227
3228 /** @typedef {import('./types').AnyFunction} AnyFunction */
3229
3230 /**
3231 * Reducer managing terms state. Keyed by taxonomy slug, the value is either
3232 * undefined (if no request has been made for given taxonomy), null (if a
3233 * request is in-flight for given taxonomy), or the array of terms for the
3234 * taxonomy.
3235 *
3236 * @param {Object} state Current state.
3237 * @param {Object} action Dispatched action.
3238 *
3239 * @return {Object} Updated state.
3240 */
3241
3242 function terms() {
3243 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3244 let action = arguments.length > 1 ? arguments[1] : undefined;
3245
3246 switch (action.type) {
3247 case 'RECEIVE_TERMS':
3248 return { ...state,
3249 [action.taxonomy]: action.terms
3250 };
3251 }
3252
3253 return state;
3254 }
3255 /**
3256 * Reducer managing authors state. Keyed by id.
3257 *
3258 * @param {Object} state Current state.
3259 * @param {Object} action Dispatched action.
3260 *
3261 * @return {Object} Updated state.
3262 */
3263
3264 function users() {
3265 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
3266 byId: {},
3267 queries: {}
3268 };
3269 let action = arguments.length > 1 ? arguments[1] : undefined;
3270
3271 switch (action.type) {
3272 case 'RECEIVE_USER_QUERY':
3273 return {
3274 byId: { ...state.byId,
3275 // Key users by their ID.
3276 ...action.users.reduce((newUsers, user) => ({ ...newUsers,
3277 [user.id]: user
3278 }), {})
3279 },
3280 queries: { ...state.queries,
3281 [action.queryID]: (0,external_lodash_namespaceObject.map)(action.users, user => user.id)
3282 }
3283 };
3284 }
3285
3286 return state;
3287 }
3288 /**
3289 * Reducer managing current user state.
3290 *
3291 * @param {Object} state Current state.
3292 * @param {Object} action Dispatched action.
3293 *
3294 * @return {Object} Updated state.
3295 */
3296
3297 function currentUser() {
3298 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3299 let action = arguments.length > 1 ? arguments[1] : undefined;
3300
3301 switch (action.type) {
3302 case 'RECEIVE_CURRENT_USER':
3303 return action.currentUser;
3304 }
3305
3306 return state;
3307 }
3308 /**
3309 * Reducer managing taxonomies.
3310 *
3311 * @param {Object} state Current state.
3312 * @param {Object} action Dispatched action.
3313 *
3314 * @return {Object} Updated state.
3315 */
3316
3317 function taxonomies() {
3318 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
3319 let action = arguments.length > 1 ? arguments[1] : undefined;
3320
3321 switch (action.type) {
3322 case 'RECEIVE_TAXONOMIES':
3323 return action.taxonomies;
3324 }
3325
3326 return state;
3327 }
3328 /**
3329 * Reducer managing the current theme.
3330 *
3331 * @param {string|undefined} state Current state.
3332 * @param {Object} action Dispatched action.
3333 *
3334 * @return {string|undefined} Updated state.
3335 */
3336
3337 function currentTheme() {
3338 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;
3339 let action = arguments.length > 1 ? arguments[1] : undefined;
3340
3341 switch (action.type) {
3342 case 'RECEIVE_CURRENT_THEME':
3343 return action.currentTheme.stylesheet;
3344 }
3345
3346 return state;
3347 }
3348 /**
3349 * Reducer managing the current global styles id.
3350 *
3351 * @param {string|undefined} state Current state.
3352 * @param {Object} action Dispatched action.
3353 *
3354 * @return {string|undefined} Updated state.
3355 */
3356
3357 function currentGlobalStylesId() {
3358 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined;
3359 let action = arguments.length > 1 ? arguments[1] : undefined;
3360
3361 switch (action.type) {
3362 case 'RECEIVE_CURRENT_GLOBAL_STYLES_ID':
3363 return action.id;
3364 }
3365
3366 return state;
3367 }
3368 /**
3369 * Reducer managing the theme base global styles.
3370 *
3371 * @param {Record<string, object>} state Current state.
3372 * @param {Object} action Dispatched action.
3373 *
3374 * @return {Record<string, object>} Updated state.
3375 */
3376
3377 function themeBaseGlobalStyles() {
3378 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3379 let action = arguments.length > 1 ? arguments[1] : undefined;
3380
3381 switch (action.type) {
3382 case 'RECEIVE_THEME_GLOBAL_STYLES':
3383 return { ...state,
3384 [action.stylesheet]: action.globalStyles
3385 };
3386 }
3387
3388 return state;
3389 }
3390 /**
3391 * Reducer managing the theme global styles variations.
3392 *
3393 * @param {Record<string, object>} state Current state.
3394 * @param {Object} action Dispatched action.
3395 *
3396 * @return {Record<string, object>} Updated state.
3397 */
3398
3399 function themeGlobalStyleVariations() {
3400 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3401 let action = arguments.length > 1 ? arguments[1] : undefined;
3402
3403 switch (action.type) {
3404 case 'RECEIVE_THEME_GLOBAL_STYLE_VARIATIONS':
3405 return { ...state,
3406 [action.stylesheet]: action.variations
3407 };
3408 }
3409
3410 return state;
3411 }
3412 /**
3413 * Higher Order Reducer for a given entity config. It supports:
3414 *
3415 * - Fetching
3416 * - Editing
3417 * - Saving
3418 *
3419 * @param {Object} entityConfig Entity config.
3420 *
3421 * @return {AnyFunction} Reducer.
3422 */
3423
3424 function entity(entityConfig) {
3425 return (0,external_wp_compose_namespaceObject.compose)([// Limit to matching action type so we don't attempt to replace action on
3426 // an unhandled action.
3427 if_matching_action(action => action.name && action.kind && action.name === entityConfig.name && action.kind === entityConfig.kind), // Inject the entity config into the action.
3428 replace_action(action => {
3429 return { ...action,
3430 key: entityConfig.key || DEFAULT_ENTITY_KEY
3431 };
3432 })])((0,external_wp_data_namespaceObject.combineReducers)({
3433 queriedData: reducer,
3434 edits: function () {
3435 var _action$query$context, _action$query;
3436
3437 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3438 let action = arguments.length > 1 ? arguments[1] : undefined;
3439
3440 switch (action.type) {
3441 case 'RECEIVE_ITEMS':
3442 const context = (_action$query$context = action === null || action === void 0 ? void 0 : (_action$query = action.query) === null || _action$query === void 0 ? void 0 : _action$query.context) !== null && _action$query$context !== void 0 ? _action$query$context : 'default';
3443
3444 if (context !== 'default') {
3445 return state;
3446 }
3447
3448 const nextState = { ...state
3449 };
3450
3451 for (const record of action.items) {
3452 const recordId = record[action.key];
3453 const edits = nextState[recordId];
3454
3455 if (!edits) {
3456 continue;
3457 }
3458
3459 const nextEdits = Object.keys(edits).reduce((acc, key) => {
3460 // If the edited value is still different to the persisted value,
3461 // keep the edited value in edits.
3462 if ( // Edits are the "raw" attribute values, but records may have
3463 // objects with more properties, so we use `get` here for the
3464 // comparison.
3465 !es6_default()(edits[key], (0,external_lodash_namespaceObject.get)(record[key], 'raw', record[key])) && ( // Sometimes the server alters the sent value which means
3466 // we need to also remove the edits before the api request.
3467 !action.persistedEdits || !es6_default()(edits[key], action.persistedEdits[key]))) {
3468 acc[key] = edits[key];
3469 }
3470
3471 return acc;
3472 }, {});
3473
3474 if (Object.keys(nextEdits).length) {
3475 nextState[recordId] = nextEdits;
3476 } else {
3477 delete nextState[recordId];
3478 }
3479 }
3480
3481 return nextState;
3482
3483 case 'EDIT_ENTITY_RECORD':
3484 const nextEdits = { ...state[action.recordId],
3485 ...action.edits
3486 };
3487 Object.keys(nextEdits).forEach(key => {
3488 // Delete cleared edits so that the properties
3489 // are not considered dirty.
3490 if (nextEdits[key] === undefined) {
3491 delete nextEdits[key];
3492 }
3493 });
3494 return { ...state,
3495 [action.recordId]: nextEdits
3496 };
3497 }
3498
3499 return state;
3500 },
3501 saving: function () {
3502 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3503 let action = arguments.length > 1 ? arguments[1] : undefined;
3504
3505 switch (action.type) {
3506 case 'SAVE_ENTITY_RECORD_START':
3507 case 'SAVE_ENTITY_RECORD_FINISH':
3508 return { ...state,
3509 [action.recordId]: {
3510 pending: action.type === 'SAVE_ENTITY_RECORD_START',
3511 error: action.error,
3512 isAutosave: action.isAutosave
3513 }
3514 };
3515 }
3516
3517 return state;
3518 },
3519 deleting: function () {
3520 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3521 let action = arguments.length > 1 ? arguments[1] : undefined;
3522
3523 switch (action.type) {
3524 case 'DELETE_ENTITY_RECORD_START':
3525 case 'DELETE_ENTITY_RECORD_FINISH':
3526 return { ...state,
3527 [action.recordId]: {
3528 pending: action.type === 'DELETE_ENTITY_RECORD_START',
3529 error: action.error
3530 }
3531 };
3532 }
3533
3534 return state;
3535 }
3536 }));
3537 }
3538 /**
3539 * Reducer keeping track of the registered entities.
3540 *
3541 * @param {Object} state Current state.
3542 * @param {Object} action Dispatched action.
3543 *
3544 * @return {Object} Updated state.
3545 */
3546
3547
3548 function entitiesConfig() {
3549 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : rootEntitiesConfig;
3550 let action = arguments.length > 1 ? arguments[1] : undefined;
3551
3552 switch (action.type) {
3553 case 'ADD_ENTITIES':
3554 return [...state, ...action.entities];
3555 }
3556
3557 return state;
3558 }
3559 /**
3560 * Reducer keeping track of the registered entities config and data.
3561 *
3562 * @param {Object} state Current state.
3563 * @param {Object} action Dispatched action.
3564 *
3565 * @return {Object} Updated state.
3566 */
3567
3568 const entities = function () {
3569 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3570 let action = arguments.length > 1 ? arguments[1] : undefined;
3571 const newConfig = entitiesConfig(state.config, action); // Generates a dynamic reducer for the entities.
3572
3573 let entitiesDataReducer = state.reducer;
3574
3575 if (!entitiesDataReducer || newConfig !== state.config) {
3576 const entitiesByKind = (0,external_lodash_namespaceObject.groupBy)(newConfig, 'kind');
3577 entitiesDataReducer = (0,external_wp_data_namespaceObject.combineReducers)(Object.entries(entitiesByKind).reduce((memo, _ref) => {
3578 let [kind, subEntities] = _ref;
3579 const kindReducer = (0,external_wp_data_namespaceObject.combineReducers)(subEntities.reduce((kindMemo, entityConfig) => ({ ...kindMemo,
3580 [entityConfig.name]: entity(entityConfig)
3581 }), {}));
3582 memo[kind] = kindReducer;
3583 return memo;
3584 }, {}));
3585 }
3586
3587 const newData = entitiesDataReducer(state.records, action);
3588
3589 if (newData === state.records && newConfig === state.config && entitiesDataReducer === state.reducer) {
3590 return state;
3591 }
3592
3593 return {
3594 reducer: entitiesDataReducer,
3595 records: newData,
3596 config: newConfig
3597 };
3598 };
3599 /**
3600 * @typedef {Object} UndoStateMeta
3601 *
3602 * @property {number} offset Where in the undo stack we are.
3603 * @property {Object} [flattenedUndo] Flattened form of undo stack.
3604 */
3605
3606 /** @typedef {Array<Object> & UndoStateMeta} UndoState */
3607
3608 /**
3609 * @type {UndoState}
3610 *
3611 * @todo Given how we use this we might want to make a custom class for it.
3612 */
3613
3614 const UNDO_INITIAL_STATE = Object.assign([], {
3615 offset: 0
3616 });
3617 /** @type {Object} */
3618
3619 let lastEditAction;
3620 /**
3621 * Reducer keeping track of entity edit undo history.
3622 *
3623 * @param {UndoState} state Current state.
3624 * @param {Object} action Dispatched action.
3625 *
3626 * @return {UndoState} Updated state.
3627 */
3628
3629 function reducer_undo() {
3630 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : UNDO_INITIAL_STATE;
3631 let action = arguments.length > 1 ? arguments[1] : undefined;
3632
3633 switch (action.type) {
3634 case 'EDIT_ENTITY_RECORD':
3635 case 'CREATE_UNDO_LEVEL':
3636 let isCreateUndoLevel = action.type === 'CREATE_UNDO_LEVEL';
3637 const isUndoOrRedo = !isCreateUndoLevel && (action.meta.isUndo || action.meta.isRedo);
3638
3639 if (isCreateUndoLevel) {
3640 action = lastEditAction;
3641 } else if (!isUndoOrRedo) {
3642 // Don't lose the last edit cache if the new one only has transient edits.
3643 // Transient edits don't create new levels so updating the cache would make
3644 // us skip an edit later when creating levels explicitly.
3645 if (Object.keys(action.edits).some(key => !action.transientEdits[key])) {
3646 lastEditAction = action;
3647 } else {
3648 lastEditAction = { ...action,
3649 edits: { ...(lastEditAction && lastEditAction.edits),
3650 ...action.edits
3651 }
3652 };
3653 }
3654 }
3655 /** @type {UndoState} */
3656
3657
3658 let nextState;
3659
3660 if (isUndoOrRedo) {
3661 // @ts-ignore we might consider using Object.assign({}, state)
3662 nextState = [...state];
3663 nextState.offset = state.offset + (action.meta.isUndo ? -1 : 1);
3664
3665 if (state.flattenedUndo) {
3666 // The first undo in a sequence of undos might happen while we have
3667 // flattened undos in state. If this is the case, we want execution
3668 // to continue as if we were creating an explicit undo level. This
3669 // will result in an extra undo level being appended with the flattened
3670 // undo values.
3671 // We also have to take into account if the `lastEditAction` had opted out
3672 // of being tracked in undo history, like the action that persists the latest
3673 // content right before saving. In that case we have to update the `lastEditAction`
3674 // to avoid returning early before applying the existing flattened undos.
3675 isCreateUndoLevel = true;
3676
3677 if (!lastEditAction.meta.undo) {
3678 lastEditAction.meta.undo = {
3679 edits: {}
3680 };
3681 }
3682
3683 action = lastEditAction;
3684 } else {
3685 return nextState;
3686 }
3687 }
3688
3689 if (!action.meta.undo) {
3690 return state;
3691 } // Transient edits don't create an undo level, but are
3692 // reachable in the next meaningful edit to which they
3693 // are merged. They are defined in the entity's config.
3694
3695
3696 if (!isCreateUndoLevel && !Object.keys(action.edits).some(key => !action.transientEdits[key])) {
3697 // @ts-ignore we might consider using Object.assign({}, state)
3698 nextState = [...state];
3699 nextState.flattenedUndo = { ...state.flattenedUndo,
3700 ...action.edits
3701 };
3702 nextState.offset = state.offset;
3703 return nextState;
3704 } // Clear potential redos, because this only supports linear history.
3705
3706
3707 nextState = // @ts-ignore this needs additional cleanup, probably involving code-level changes
3708 nextState || state.slice(0, state.offset || undefined);
3709 nextState.offset = nextState.offset || 0;
3710 nextState.pop();
3711
3712 if (!isCreateUndoLevel) {
3713 nextState.push({
3714 kind: action.meta.undo.kind,
3715 name: action.meta.undo.name,
3716 recordId: action.meta.undo.recordId,
3717 edits: { ...state.flattenedUndo,
3718 ...action.meta.undo.edits
3719 }
3720 });
3721 } // When an edit is a function it's an optimization to avoid running some expensive operation.
3722 // We can't rely on the function references being the same so we opt out of comparing them here.
3723
3724
3725 const comparisonUndoEdits = Object.values(action.meta.undo.edits).filter(edit => typeof edit !== 'function');
3726 const comparisonEdits = Object.values(action.edits).filter(edit => typeof edit !== 'function');
3727
3728 if (!external_wp_isShallowEqual_default()(comparisonUndoEdits, comparisonEdits)) {
3729 nextState.push({
3730 kind: action.kind,
3731 name: action.name,
3732 recordId: action.recordId,
3733 edits: isCreateUndoLevel ? { ...state.flattenedUndo,
3734 ...action.edits
3735 } : action.edits
3736 });
3737 }
3738
3739 return nextState;
3740 }
3741
3742 return state;
3743 }
3744 /**
3745 * Reducer managing embed preview data.
3746 *
3747 * @param {Object} state Current state.
3748 * @param {Object} action Dispatched action.
3749 *
3750 * @return {Object} Updated state.
3751 */
3752
3753 function embedPreviews() {
3754 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3755 let action = arguments.length > 1 ? arguments[1] : undefined;
3756
3757 switch (action.type) {
3758 case 'RECEIVE_EMBED_PREVIEW':
3759 const {
3760 url,
3761 preview
3762 } = action;
3763 return { ...state,
3764 [url]: preview
3765 };
3766 }
3767
3768 return state;
3769 }
3770 /**
3771 * State which tracks whether the user can perform an action on a REST
3772 * resource.
3773 *
3774 * @param {Object} state Current state.
3775 * @param {Object} action Dispatched action.
3776 *
3777 * @return {Object} Updated state.
3778 */
3779
3780 function userPermissions() {
3781 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3782 let action = arguments.length > 1 ? arguments[1] : undefined;
3783
3784 switch (action.type) {
3785 case 'RECEIVE_USER_PERMISSION':
3786 return { ...state,
3787 [action.key]: action.isAllowed
3788 };
3789 }
3790
3791 return state;
3792 }
3793 /**
3794 * Reducer returning autosaves keyed by their parent's post id.
3795 *
3796 * @param {Object} state Current state.
3797 * @param {Object} action Dispatched action.
3798 *
3799 * @return {Object} Updated state.
3800 */
3801
3802 function autosaves() {
3803 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
3804 let action = arguments.length > 1 ? arguments[1] : undefined;
3805
3806 switch (action.type) {
3807 case 'RECEIVE_AUTOSAVES':
3808 const {
3809 postId,
3810 autosaves: autosavesData
3811 } = action;
3812 return { ...state,
3813 [postId]: autosavesData
3814 };
3815 }
3816
3817 return state;
3818 }
3819 function blockPatterns() {
3820 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
3821 let action = arguments.length > 1 ? arguments[1] : undefined;
3822
3823 switch (action.type) {
3824 case 'RECEIVE_BLOCK_PATTERNS':
3825 return action.patterns;
3826 }
3827
3828 return state;
3829 }
3830 function blockPatternCategories() {
3831 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
3832 let action = arguments.length > 1 ? arguments[1] : undefined;
3833
3834 switch (action.type) {
3835 case 'RECEIVE_BLOCK_PATTERN_CATEGORIES':
3836 return action.categories;
3837 }
3838
3839 return state;
3840 }
3841 /* harmony default export */ var build_module_reducer = ((0,external_wp_data_namespaceObject.combineReducers)({
3842 terms,
3843 users,
3844 currentTheme,
3845 currentGlobalStylesId,
3846 currentUser,
3847 themeGlobalStyleVariations,
3848 themeBaseGlobalStyles,
3849 taxonomies,
3850 entities,
3851 undo: reducer_undo,
3852 embedPreviews,
3853 userPermissions,
3854 autosaves,
3855 blockPatterns,
3856 blockPatternCategories
3857 }));
3858
3859 ;// CONCATENATED MODULE: ./node_modules/rememo/es/rememo.js
3860
3861
3862 /** @typedef {(...args: any[]) => *[]} GetDependants */
3863
3864 /** @typedef {() => void} Clear */
3865
3866 /**
3867 * @typedef {{
3868 * getDependants: GetDependants,
3869 * clear: Clear
3870 * }} EnhancedSelector
3871 */
3872
3873 /**
3874 * Internal cache entry.
3875 *
3876 * @typedef CacheNode
3877 *
3878 * @property {?CacheNode|undefined} [prev] Previous node.
3879 * @property {?CacheNode|undefined} [next] Next node.
3880 * @property {*[]} args Function arguments for cache entry.
3881 * @property {*} val Function result.
3882 */
3883
3884 /**
3885 * @typedef Cache
3886 *
3887 * @property {Clear} clear Function to clear cache.
3888 * @property {boolean} [isUniqueByDependants] Whether dependants are valid in
3889 * considering cache uniqueness. A cache is unique if dependents are all arrays
3890 * or objects.
3891 * @property {CacheNode?} [head] Cache head.
3892 * @property {*[]} [lastDependants] Dependants from previous invocation.
3893 */
3894
3895 /**
3896 * Arbitrary value used as key for referencing cache object in WeakMap tree.
3897 *
3898 * @type {{}}
3899 */
3900 var LEAF_KEY = {};
3901
3902 /**
3903 * Returns the first argument as the sole entry in an array.
3904 *
3905 * @template T
3906 *
3907 * @param {T} value Value to return.
3908 *
3909 * @return {[T]} Value returned as entry in array.
3910 */
3911 function arrayOf(value) {
3912 return [value];
3913 }
3914
3915 /**
3916 * Returns true if the value passed is object-like, or false otherwise. A value
3917 * is object-like if it can support property assignment, e.g. object or array.
3918 *
3919 * @param {*} value Value to test.
3920 *
3921 * @return {boolean} Whether value is object-like.
3922 */
3923 function isObjectLike(value) {
3924 return !!value && 'object' === typeof value;
3925 }
3926
3927 /**
3928 * Creates and returns a new cache object.
3929 *
3930 * @return {Cache} Cache object.
3931 */
3932 function createCache() {
3933 /** @type {Cache} */
3934 var cache = {
3935 clear: function () {
3936 cache.head = null;
3937 },
3938 };
3939
3940 return cache;
3941 }
3942
3943 /**
3944 * Returns true if entries within the two arrays are strictly equal by
3945 * reference from a starting index.
3946 *
3947 * @param {*[]} a First array.
3948 * @param {*[]} b Second array.
3949 * @param {number} fromIndex Index from which to start comparison.
3950 *
3951 * @return {boolean} Whether arrays are shallowly equal.
3952 */
3953 function isShallowEqual(a, b, fromIndex) {
3954 var i;
3955
3956 if (a.length !== b.length) {
3957 return false;
3958 }
3959
3960 for (i = fromIndex; i < a.length; i++) {
3961 if (a[i] !== b[i]) {
3962 return false;
3963 }
3964 }
3965
3966 return true;
3967 }
3968
3969 /**
3970 * Returns a memoized selector function. The getDependants function argument is
3971 * called before the memoized selector and is expected to return an immutable
3972 * reference or array of references on which the selector depends for computing
3973 * its own return value. The memoize cache is preserved only as long as those
3974 * dependant references remain the same. If getDependants returns a different
3975 * reference(s), the cache is cleared and the selector value regenerated.
3976 *
3977 * @template {(...args: *[]) => *} S
3978 *
3979 * @param {S} selector Selector function.
3980 * @param {GetDependants=} getDependants Dependant getter returning an array of
3981 * references used in cache bust consideration.
3982 */
3983 /* harmony default export */ function rememo(selector, getDependants) {
3984 /** @type {WeakMap<*,*>} */
3985 var rootCache;
3986
3987 /** @type {GetDependants} */
3988 var normalizedGetDependants = getDependants ? getDependants : arrayOf;
3989
3990 /**
3991 * Returns the cache for a given dependants array. When possible, a WeakMap
3992 * will be used to create a unique cache for each set of dependants. This
3993 * is feasible due to the nature of WeakMap in allowing garbage collection
3994 * to occur on entries where the key object is no longer referenced. Since
3995 * WeakMap requires the key to be an object, this is only possible when the
3996 * dependant is object-like. The root cache is created as a hierarchy where
3997 * each top-level key is the first entry in a dependants set, the value a
3998 * WeakMap where each key is the next dependant, and so on. This continues
3999 * so long as the dependants are object-like. If no dependants are object-
4000 * like, then the cache is shared across all invocations.
4001 *
4002 * @see isObjectLike
4003 *
4004 * @param {*[]} dependants Selector dependants.
4005 *
4006 * @return {Cache} Cache object.
4007 */
4008 function getCache(dependants) {
4009 var caches = rootCache,
4010 isUniqueByDependants = true,
4011 i,
4012 dependant,
4013 map,
4014 cache;
4015
4016 for (i = 0; i < dependants.length; i++) {
4017 dependant = dependants[i];
4018
4019 // Can only compose WeakMap from object-like key.
4020 if (!isObjectLike(dependant)) {
4021 isUniqueByDependants = false;
4022 break;
4023 }
4024
4025 // Does current segment of cache already have a WeakMap?
4026 if (caches.has(dependant)) {
4027 // Traverse into nested WeakMap.
4028 caches = caches.get(dependant);
4029 } else {
4030 // Create, set, and traverse into a new one.
4031 map = new WeakMap();
4032 caches.set(dependant, map);
4033 caches = map;
4034 }
4035 }
4036
4037 // We use an arbitrary (but consistent) object as key for the last item
4038 // in the WeakMap to serve as our running cache.
4039 if (!caches.has(LEAF_KEY)) {
4040 cache = createCache();
4041 cache.isUniqueByDependants = isUniqueByDependants;
4042 caches.set(LEAF_KEY, cache);
4043 }
4044
4045 return caches.get(LEAF_KEY);
4046 }
4047
4048 /**
4049 * Resets root memoization cache.
4050 */
4051 function clear() {
4052 rootCache = new WeakMap();
4053 }
4054
4055 /* eslint-disable jsdoc/check-param-names */
4056 /**
4057 * The augmented selector call, considering first whether dependants have
4058 * changed before passing it to underlying memoize function.
4059 *
4060 * @param {*} source Source object for derivation.
4061 * @param {...*} extraArgs Additional arguments to pass to selector.
4062 *
4063 * @return {*} Selector result.
4064 */
4065 /* eslint-enable jsdoc/check-param-names */
4066 function callSelector(/* source, ...extraArgs */) {
4067 var len = arguments.length,
4068 cache,
4069 node,
4070 i,
4071 args,
4072 dependants;
4073
4074 // Create copy of arguments (avoid leaking deoptimization).
4075 args = new Array(len);
4076 for (i = 0; i < len; i++) {
4077 args[i] = arguments[i];
4078 }
4079
4080 dependants = normalizedGetDependants.apply(null, args);
4081 cache = getCache(dependants);
4082
4083 // If not guaranteed uniqueness by dependants (primitive type), shallow
4084 // compare against last dependants and, if references have changed,
4085 // destroy cache to recalculate result.
4086 if (!cache.isUniqueByDependants) {
4087 if (
4088 cache.lastDependants &&
4089 !isShallowEqual(dependants, cache.lastDependants, 0)
4090 ) {
4091 cache.clear();
4092 }
4093
4094 cache.lastDependants = dependants;
4095 }
4096
4097 node = cache.head;
4098 while (node) {
4099 // Check whether node arguments match arguments
4100 if (!isShallowEqual(node.args, args, 1)) {
4101 node = node.next;
4102 continue;
4103 }
4104
4105 // At this point we can assume we've found a match
4106
4107 // Surface matched node to head if not already
4108 if (node !== cache.head) {
4109 // Adjust siblings to point to each other.
4110 /** @type {CacheNode} */ (node.prev).next = node.next;
4111 if (node.next) {
4112 node.next.prev = node.prev;
4113 }
4114
4115 node.next = cache.head;
4116 node.prev = null;
4117 /** @type {CacheNode} */ (cache.head).prev = node;
4118 cache.head = node;
4119 }
4120
4121 // Return immediately
4122 return node.val;
4123 }
4124
4125 // No cached value found. Continue to insertion phase:
4126
4127 node = /** @type {CacheNode} */ ({
4128 // Generate the result from original function
4129 val: selector.apply(null, args),
4130 });
4131
4132 // Avoid including the source object in the cache.
4133 args[0] = null;
4134 node.args = args;
4135
4136 // Don't need to check whether node is already head, since it would
4137 // have been returned above already if it was
4138
4139 // Shift existing head down list
4140 if (cache.head) {
4141 cache.head.prev = node;
4142 node.next = cache.head;
4143 }
4144
4145 cache.head = node;
4146
4147 return node.val;
4148 }
4149
4150 callSelector.getDependants = normalizedGetDependants;
4151 callSelector.clear = clear;
4152 clear();
4153
4154 return /** @type {S & EnhancedSelector} */ (callSelector);
4155 }
4156
4157 // EXTERNAL MODULE: ./node_modules/equivalent-key-map/equivalent-key-map.js
4158 var equivalent_key_map = __webpack_require__(2167);
4159 var equivalent_key_map_default = /*#__PURE__*/__webpack_require__.n(equivalent_key_map);
4160 ;// CONCATENATED MODULE: ./packages/core-data/build-module/queried-data/selectors.js
4161 /**
4162 * External dependencies
4163 */
4164
4165
4166
4167 /**
4168 * Internal dependencies
4169 */
4170
4171
4172 /**
4173 * Cache of state keys to EquivalentKeyMap where the inner map tracks queries
4174 * to their resulting items set. WeakMap allows garbage collection on expired
4175 * state references.
4176 *
4177 * @type {WeakMap<Object,EquivalentKeyMap>}
4178 */
4179
4180 const queriedItemsCacheByState = new WeakMap();
4181 /**
4182 * Returns items for a given query, or null if the items are not known.
4183 *
4184 * @param {Object} state State object.
4185 * @param {?Object} query Optional query.
4186 *
4187 * @return {?Array} Query items.
4188 */
4189
4190 function getQueriedItemsUncached(state, query) {
4191 var _state$queries, _state$queries$contex;
4192
4193 const {
4194 stableKey,
4195 page,
4196 perPage,
4197 include,
4198 fields,
4199 context
4200 } = get_query_parts(query);
4201 let itemIds;
4202
4203 if ((_state$queries = state.queries) !== null && _state$queries !== void 0 && (_state$queries$contex = _state$queries[context]) !== null && _state$queries$contex !== void 0 && _state$queries$contex[stableKey]) {
4204 itemIds = state.queries[context][stableKey];
4205 }
4206
4207 if (!itemIds) {
4208 return null;
4209 }
4210
4211 const startOffset = perPage === -1 ? 0 : (page - 1) * perPage;
4212 const endOffset = perPage === -1 ? itemIds.length : Math.min(startOffset + perPage, itemIds.length);
4213 const items = [];
4214
4215 for (let i = startOffset; i < endOffset; i++) {
4216 var _state$items$context;
4217
4218 const itemId = itemIds[i];
4219
4220 if (Array.isArray(include) && !include.includes(itemId)) {
4221 continue;
4222 } // Having a target item ID doesn't guarantee that this object has been queried.
4223
4224
4225 if (!((_state$items$context = state.items[context]) !== null && _state$items$context !== void 0 && _state$items$context.hasOwnProperty(itemId))) {
4226 return null;
4227 }
4228
4229 const item = state.items[context][itemId];
4230 let filteredItem;
4231
4232 if (Array.isArray(fields)) {
4233 filteredItem = {};
4234
4235 for (let f = 0; f < fields.length; f++) {
4236 const field = fields[f].split('.');
4237 const value = (0,external_lodash_namespaceObject.get)(item, field);
4238 (0,external_lodash_namespaceObject.set)(filteredItem, field, value);
4239 }
4240 } else {
4241 var _state$itemIsComplete;
4242
4243 // If expecting a complete item, validate that completeness, or
4244 // otherwise abort.
4245 if (!((_state$itemIsComplete = state.itemIsComplete[context]) !== null && _state$itemIsComplete !== void 0 && _state$itemIsComplete[itemId])) {
4246 return null;
4247 }
4248
4249 filteredItem = item;
4250 }
4251
4252 items.push(filteredItem);
4253 }
4254
4255 return items;
4256 }
4257 /**
4258 * Returns items for a given query, or null if the items are not known. Caches
4259 * result both per state (by reference) and per query (by deep equality).
4260 * The caching approach is intended to be durable to query objects which are
4261 * deeply but not referentially equal, since otherwise:
4262 *
4263 * `getQueriedItems( state, {} ) !== getQueriedItems( state, {} )`
4264 *
4265 * @param {Object} state State object.
4266 * @param {?Object} query Optional query.
4267 *
4268 * @return {?Array} Query items.
4269 */
4270
4271
4272 const getQueriedItems = rememo(function (state) {
4273 let query = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
4274 let queriedItemsCache = queriedItemsCacheByState.get(state);
4275
4276 if (queriedItemsCache) {
4277 const queriedItems = queriedItemsCache.get(query);
4278
4279 if (queriedItems !== undefined) {
4280 return queriedItems;
4281 }
4282 } else {
4283 queriedItemsCache = new (equivalent_key_map_default())();
4284 queriedItemsCacheByState.set(state, queriedItemsCache);
4285 }
4286
4287 const items = getQueriedItemsUncached(state, query);
4288 queriedItemsCache.set(query, items);
4289 return items;
4290 });
4291
4292 ;// CONCATENATED MODULE: ./packages/core-data/build-module/utils/is-raw-attribute.js
4293 /**
4294 * Checks whether the attribute is a "raw" attribute or not.
4295 *
4296 * @param {Object} entity Entity record.
4297 * @param {string} attribute Attribute name.
4298 *
4299 * @return {boolean} Is the attribute raw
4300 */
4301 function isRawAttribute(entity, attribute) {
4302 return (entity.rawAttributes || []).includes(attribute);
4303 }
4304
4305 ;// CONCATENATED MODULE: ./packages/core-data/build-module/selectors.js
4306 /**
4307 * External dependencies
4308 */
4309
4310
4311 /**
4312 * WordPress dependencies
4313 */
4314
4315
4316
4317
4318 /**
4319 * Internal dependencies
4320 */
4321
4322
4323
4324
4325
4326
4327 /**
4328 * Shared reference to an empty object for cases where it is important to avoid
4329 * returning a new object reference on every invocation, as in a connected or
4330 * other pure component which performs `shouldComponentUpdate` check on props.
4331 * This should be used as a last resort, since the normalized data should be
4332 * maintained by the reducer result in state.
4333 */
4334 const EMPTY_OBJECT = {};
4335 /**
4336 * Returns true if a request is in progress for embed preview data, or false
4337 * otherwise.
4338 *
4339 * @param state Data state.
4340 * @param url URL the preview would be for.
4341 *
4342 * @return Whether a request is in progress for an embed preview.
4343 */
4344
4345 const isRequestingEmbedPreview = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => (state, url) => {
4346 return select(STORE_NAME).isResolving('getEmbedPreview', [url]);
4347 });
4348 /**
4349 * Returns all available authors.
4350 *
4351 * @deprecated since 11.3. Callers should use `select( 'core' ).getUsers({ who: 'authors' })` instead.
4352 *
4353 * @param state Data state.
4354 * @param query Optional object of query parameters to
4355 * include with request.
4356 * @return Authors list.
4357 */
4358
4359 function getAuthors(state, query) {
4360 external_wp_deprecated_default()("select( 'core' ).getAuthors()", {
4361 since: '5.9',
4362 alternative: "select( 'core' ).getUsers({ who: 'authors' })"
4363 });
4364 const path = (0,external_wp_url_namespaceObject.addQueryArgs)('/wp/v2/users/?who=authors&per_page=100', query);
4365 return getUserQueryResults(state, path);
4366 }
4367 /**
4368 * Returns the current user.
4369 *
4370 * @param state Data state.
4371 *
4372 * @return Current user object.
4373 */
4374
4375 function getCurrentUser(state) {
4376 return state.currentUser;
4377 }
4378 /**
4379 * Returns all the users returned by a query ID.
4380 *
4381 * @param state Data state.
4382 * @param queryID Query ID.
4383 *
4384 * @return Users list.
4385 */
4386
4387 const getUserQueryResults = rememo((state, queryID) => {
4388 const queryResults = state.users.queries[queryID];
4389 return (0,external_lodash_namespaceObject.map)(queryResults, id => state.users.byId[id]);
4390 }, (state, queryID) => [state.users.queries[queryID], state.users.byId]);
4391 /**
4392 * Returns the loaded entities for the given kind.
4393 *
4394 * @deprecated since WordPress 6.0. Use getEntitiesConfig instead
4395 * @param state Data state.
4396 * @param kind Entity kind.
4397 *
4398 * @return Array of entities with config matching kind.
4399 */
4400
4401 function getEntitiesByKind(state, kind) {
4402 external_wp_deprecated_default()("wp.data.select( 'core' ).getEntitiesByKind()", {
4403 since: '6.0',
4404 alternative: "wp.data.select( 'core' ).getEntitiesConfig()"
4405 });
4406 return getEntitiesConfig(state, kind);
4407 }
4408 /**
4409 * Returns the loaded entities for the given kind.
4410 *
4411 * @param state Data state.
4412 * @param kind Entity kind.
4413 *
4414 * @return Array of entities with config matching kind.
4415 */
4416
4417 function getEntitiesConfig(state, kind) {
4418 return state.entities.config.filter(entity => entity.kind === kind);
4419 }
4420 /**
4421 * Returns the entity config given its kind and name.
4422 *
4423 * @deprecated since WordPress 6.0. Use getEntityConfig instead
4424 * @param state Data state.
4425 * @param kind Entity kind.
4426 * @param name Entity name.
4427 *
4428 * @return Entity config
4429 */
4430
4431 function getEntity(state, kind, name) {
4432 external_wp_deprecated_default()("wp.data.select( 'core' ).getEntity()", {
4433 since: '6.0',
4434 alternative: "wp.data.select( 'core' ).getEntityConfig()"
4435 });
4436 return getEntityConfig(state, kind, name);
4437 }
4438 /**
4439 * Returns the entity config given its kind and name.
4440 *
4441 * @param state Data state.
4442 * @param kind Entity kind.
4443 * @param name Entity name.
4444 *
4445 * @return Entity config
4446 */
4447
4448 function getEntityConfig(state, kind, name) {
4449 var _state$entities$confi;
4450
4451 return (_state$entities$confi = state.entities.config) === null || _state$entities$confi === void 0 ? void 0 : _state$entities$confi.find(config => config.kind === kind && config.name === name);
4452 }
4453 /**
4454 * GetEntityRecord is declared as a *callable interface* with
4455 * two signatures to work around the fact that TypeScript doesn't
4456 * allow currying generic functions:
4457 *
4458 * ```ts
4459 * type CurriedState = F extends ( state: any, ...args: infer P ) => infer R
4460 * ? ( ...args: P ) => R
4461 * : F;
4462 * type Selector = <K extends string | number>(
4463 * state: any,
4464 * kind: K,
4465 * key: K extends string ? 'string value' : false
4466 * ) => K;
4467 * type BadlyInferredSignature = CurriedState< Selector >
4468 * // BadlyInferredSignature evaluates to:
4469 * // (kind: string number, key: false | "string value") => string number
4470 * ```
4471 *
4472 * The signature without the state parameter shipped as CurriedSignature
4473 * is used in the return value of `select( coreStore )`.
4474 *
4475 * See https://github.com/WordPress/gutenberg/pull/41578 for more details.
4476 */
4477
4478 /**
4479 * Returns the Entity's record object by key. Returns `null` if the value is not
4480 * yet received, undefined if the value entity is known to not exist, or the
4481 * entity object if it exists and is received.
4482 *
4483 * @param state State tree
4484 * @param kind Entity kind.
4485 * @param name Entity name.
4486 * @param key Record's key
4487 * @param query Optional query. If requesting specific
4488 * fields, fields must always include the ID.
4489 *
4490 * @return Record.
4491 */
4492 const getEntityRecord = rememo((state, kind, name, key, query) => {
4493 var _query$context, _queriedState$items$c;
4494
4495 const queriedState = (0,external_lodash_namespaceObject.get)(state.entities.records, [kind, name, 'queriedData']);
4496
4497 if (!queriedState) {
4498 return undefined;
4499 }
4500
4501 const context = (_query$context = query === null || query === void 0 ? void 0 : query.context) !== null && _query$context !== void 0 ? _query$context : 'default';
4502
4503 if (query === undefined) {
4504 var _queriedState$itemIsC;
4505
4506 // If expecting a complete item, validate that completeness.
4507 if (!((_queriedState$itemIsC = queriedState.itemIsComplete[context]) !== null && _queriedState$itemIsC !== void 0 && _queriedState$itemIsC[key])) {
4508 return undefined;
4509 }
4510
4511 return queriedState.items[context][key];
4512 }
4513
4514 const item = (_queriedState$items$c = queriedState.items[context]) === null || _queriedState$items$c === void 0 ? void 0 : _queriedState$items$c[key];
4515
4516 if (item && query._fields) {
4517 var _getNormalizedCommaSe;
4518
4519 const filteredItem = {};
4520 const fields = (_getNormalizedCommaSe = get_normalized_comma_separable(query._fields)) !== null && _getNormalizedCommaSe !== void 0 ? _getNormalizedCommaSe : [];
4521
4522 for (let f = 0; f < fields.length; f++) {
4523 const field = fields[f].split('.');
4524 const value = (0,external_lodash_namespaceObject.get)(item, field);
4525 (0,external_lodash_namespaceObject.set)(filteredItem, field, value);
4526 }
4527
4528 return filteredItem;
4529 }
4530
4531 return item;
4532 }, (state, kind, name, recordId, query) => {
4533 var _query$context2;
4534
4535 const context = (_query$context2 = query === null || query === void 0 ? void 0 : query.context) !== null && _query$context2 !== void 0 ? _query$context2 : 'default';
4536 return [(0,external_lodash_namespaceObject.get)(state.entities.records, [kind, name, 'queriedData', 'items', context, recordId]), (0,external_lodash_namespaceObject.get)(state.entities.records, [kind, name, 'queriedData', 'itemIsComplete', context, recordId])];
4537 });
4538 /**
4539 * Returns the Entity's record object by key. Doesn't trigger a resolver nor requests the entity records from the API if the entity record isn't available in the local state.
4540 *
4541 * @param state State tree
4542 * @param kind Entity kind.
4543 * @param name Entity name.
4544 * @param key Record's key
4545 *
4546 * @return Record.
4547 */
4548
4549 function __experimentalGetEntityRecordNoResolver(state, kind, name, key) {
4550 return getEntityRecord(state, kind, name, key);
4551 }
4552 /**
4553 * Returns the entity's record object by key,
4554 * with its attributes mapped to their raw values.
4555 *
4556 * @param state State tree.
4557 * @param kind Entity kind.
4558 * @param name Entity name.
4559 * @param key Record's key.
4560 *
4561 * @return Object with the entity's raw attributes.
4562 */
4563
4564 const getRawEntityRecord = rememo((state, kind, name, key) => {
4565 const record = getEntityRecord(state, kind, name, key);
4566 return record && Object.keys(record).reduce((accumulator, _key) => {
4567 if (isRawAttribute(getEntityConfig(state, kind, name), _key)) {
4568 // Because edits are the "raw" attribute values,
4569 // we return those from record selectors to make rendering,
4570 // comparisons, and joins with edits easier.
4571 accumulator[_key] = (0,external_lodash_namespaceObject.get)(record[_key], 'raw', record[_key]);
4572 } else {
4573 accumulator[_key] = record[_key];
4574 }
4575
4576 return accumulator;
4577 }, {});
4578 }, (state, kind, name, recordId, query) => {
4579 var _query$context3;
4580
4581 const context = (_query$context3 = query === null || query === void 0 ? void 0 : query.context) !== null && _query$context3 !== void 0 ? _query$context3 : 'default';
4582 return [state.entities.config, (0,external_lodash_namespaceObject.get)(state.entities.records, [kind, name, 'queriedData', 'items', context, recordId]), (0,external_lodash_namespaceObject.get)(state.entities.records, [kind, name, 'queriedData', 'itemIsComplete', context, recordId])];
4583 });
4584 /**
4585 * Returns true if records have been received for the given set of parameters,
4586 * or false otherwise.
4587 *
4588 * @param state State tree
4589 * @param kind Entity kind.
4590 * @param name Entity name.
4591 * @param query Optional terms query.
4592 *
4593 * @return Whether entity records have been received.
4594 */
4595
4596 function hasEntityRecords(state, kind, name, query) {
4597 return Array.isArray(getEntityRecords(state, kind, name, query));
4598 }
4599 /**
4600 * GetEntityRecord is declared as a *callable interface* with
4601 * two signatures to work around the fact that TypeScript doesn't
4602 * allow currying generic functions.
4603 *
4604 * @see GetEntityRecord
4605 * @see https://github.com/WordPress/gutenberg/pull/41578
4606 */
4607
4608 /**
4609 * Returns the Entity's records.
4610 *
4611 * @param state State tree
4612 * @param kind Entity kind.
4613 * @param name Entity name.
4614 * @param query Optional terms query. If requesting specific
4615 * fields, fields must always include the ID.
4616 *
4617 * @return Records.
4618 */
4619 const getEntityRecords = (state, kind, name, query) => {
4620 // Queried data state is prepopulated for all known entities. If this is not
4621 // assigned for the given parameters, then it is known to not exist.
4622 const queriedState = (0,external_lodash_namespaceObject.get)(state.entities.records, [kind, name, 'queriedData']);
4623
4624 if (!queriedState) {
4625 return null;
4626 }
4627
4628 return getQueriedItems(queriedState, query);
4629 };
4630
4631 /**
4632 * Returns the list of dirty entity records.
4633 *
4634 * @param state State tree.
4635 *
4636 * @return The list of updated records
4637 */
4638 const __experimentalGetDirtyEntityRecords = rememo(state => {
4639 const {
4640 entities: {
4641 records
4642 }
4643 } = state;
4644 const dirtyRecords = [];
4645 Object.keys(records).forEach(kind => {
4646 Object.keys(records[kind]).forEach(name => {
4647 const primaryKeys = Object.keys(records[kind][name].edits).filter(primaryKey => // The entity record must exist (not be deleted),
4648 // and it must have edits.
4649 getEntityRecord(state, kind, name, primaryKey) && hasEditsForEntityRecord(state, kind, name, primaryKey));
4650
4651 if (primaryKeys.length) {
4652 const entityConfig = getEntityConfig(state, kind, name);
4653 primaryKeys.forEach(primaryKey => {
4654 var _entityConfig$getTitl;
4655
4656 const entityRecord = getEditedEntityRecord(state, kind, name, primaryKey);
4657 dirtyRecords.push({
4658 // We avoid using primaryKey because it's transformed into a string
4659 // when it's used as an object key.
4660 key: entityRecord ? entityRecord[entityConfig.key || DEFAULT_ENTITY_KEY] : undefined,
4661 title: (entityConfig === null || entityConfig === void 0 ? void 0 : (_entityConfig$getTitl = entityConfig.getTitle) === null || _entityConfig$getTitl === void 0 ? void 0 : _entityConfig$getTitl.call(entityConfig, entityRecord)) || '',
4662 name,
4663 kind
4664 });
4665 });
4666 }
4667 });
4668 });
4669 return dirtyRecords;
4670 }, state => [state.entities.records]);
4671 /**
4672 * Returns the list of entities currently being saved.
4673 *
4674 * @param state State tree.
4675 *
4676 * @return The list of records being saved.
4677 */
4678
4679 const __experimentalGetEntitiesBeingSaved = rememo(state => {
4680 const {
4681 entities: {
4682 records
4683 }
4684 } = state;
4685 const recordsBeingSaved = [];
4686 Object.keys(records).forEach(kind => {
4687 Object.keys(records[kind]).forEach(name => {
4688 const primaryKeys = Object.keys(records[kind][name].saving).filter(primaryKey => isSavingEntityRecord(state, kind, name, primaryKey));
4689
4690 if (primaryKeys.length) {
4691 const entityConfig = getEntityConfig(state, kind, name);
4692 primaryKeys.forEach(primaryKey => {
4693 var _entityConfig$getTitl2;
4694
4695 const entityRecord = getEditedEntityRecord(state, kind, name, primaryKey);
4696 recordsBeingSaved.push({
4697 // We avoid using primaryKey because it's transformed into a string
4698 // when it's used as an object key.
4699 key: entityRecord ? entityRecord[entityConfig.key || DEFAULT_ENTITY_KEY] : undefined,
4700 title: (entityConfig === null || entityConfig === void 0 ? void 0 : (_entityConfig$getTitl2 = entityConfig.getTitle) === null || _entityConfig$getTitl2 === void 0 ? void 0 : _entityConfig$getTitl2.call(entityConfig, entityRecord)) || '',
4701 name,
4702 kind
4703 });
4704 });
4705 }
4706 });
4707 });
4708 return recordsBeingSaved;
4709 }, state => [state.entities.records]);
4710 /**
4711 * Returns the specified entity record's edits.
4712 *
4713 * @param state State tree.
4714 * @param kind Entity kind.
4715 * @param name Entity name.
4716 * @param recordId Record ID.
4717 *
4718 * @return The entity record's edits.
4719 */
4720
4721 function getEntityRecordEdits(state, kind, name, recordId) {
4722 return (0,external_lodash_namespaceObject.get)(state.entities.records, [kind, name, 'edits', recordId]);
4723 }
4724 /**
4725 * Returns the specified entity record's non transient edits.
4726 *
4727 * Transient edits don't create an undo level, and
4728 * are not considered for change detection.
4729 * They are defined in the entity's config.
4730 *
4731 * @param state State tree.
4732 * @param kind Entity kind.
4733 * @param name Entity name.
4734 * @param recordId Record ID.
4735 *
4736 * @return The entity record's non transient edits.
4737 */
4738
4739 const getEntityRecordNonTransientEdits = rememo((state, kind, name, recordId) => {
4740 const {
4741 transientEdits
4742 } = getEntityConfig(state, kind, name) || {};
4743 const edits = getEntityRecordEdits(state, kind, name, recordId) || {};
4744
4745 if (!transientEdits) {
4746 return edits;
4747 }
4748
4749 return Object.keys(edits).reduce((acc, key) => {
4750 if (!transientEdits[key]) {
4751 acc[key] = edits[key];
4752 }
4753
4754 return acc;
4755 }, {});
4756 }, (state, kind, name, recordId) => [state.entities.config, (0,external_lodash_namespaceObject.get)(state.entities.records, [kind, name, 'edits', recordId])]);
4757 /**
4758 * Returns true if the specified entity record has edits,
4759 * and false otherwise.
4760 *
4761 * @param state State tree.
4762 * @param kind Entity kind.
4763 * @param name Entity name.
4764 * @param recordId Record ID.
4765 *
4766 * @return Whether the entity record has edits or not.
4767 */
4768
4769 function hasEditsForEntityRecord(state, kind, name, recordId) {
4770 return isSavingEntityRecord(state, kind, name, recordId) || Object.keys(getEntityRecordNonTransientEdits(state, kind, name, recordId)).length > 0;
4771 }
4772 /**
4773 * Returns the specified entity record, merged with its edits.
4774 *
4775 * @param state State tree.
4776 * @param kind Entity kind.
4777 * @param name Entity name.
4778 * @param recordId Record ID.
4779 *
4780 * @return The entity record, merged with its edits.
4781 */
4782
4783 const getEditedEntityRecord = rememo((state, kind, name, recordId) => ({ ...getRawEntityRecord(state, kind, name, recordId),
4784 ...getEntityRecordEdits(state, kind, name, recordId)
4785 }), (state, kind, name, recordId, query) => {
4786 var _query$context4;
4787
4788 const context = (_query$context4 = query === null || query === void 0 ? void 0 : query.context) !== null && _query$context4 !== void 0 ? _query$context4 : 'default';
4789 return [state.entities.config, (0,external_lodash_namespaceObject.get)(state.entities.records, [kind, name, 'queriedData', 'items', context, recordId]), (0,external_lodash_namespaceObject.get)(state.entities.records, [kind, name, 'queriedData', 'itemIsComplete', context, recordId]), (0,external_lodash_namespaceObject.get)(state.entities.records, [kind, name, 'edits', recordId])];
4790 });
4791 /**
4792 * Returns true if the specified entity record is autosaving, and false otherwise.
4793 *
4794 * @param state State tree.
4795 * @param kind Entity kind.
4796 * @param name Entity name.
4797 * @param recordId Record ID.
4798 *
4799 * @return Whether the entity record is autosaving or not.
4800 */
4801
4802 function isAutosavingEntityRecord(state, kind, name, recordId) {
4803 const {
4804 pending,
4805 isAutosave
4806 } = (0,external_lodash_namespaceObject.get)(state.entities.records, [kind, name, 'saving', recordId], {});
4807 return Boolean(pending && isAutosave);
4808 }
4809 /**
4810 * Returns true if the specified entity record is saving, and false otherwise.
4811 *
4812 * @param state State tree.
4813 * @param kind Entity kind.
4814 * @param name Entity name.
4815 * @param recordId Record ID.
4816 *
4817 * @return Whether the entity record is saving or not.
4818 */
4819
4820 function isSavingEntityRecord(state, kind, name, recordId) {
4821 return (0,external_lodash_namespaceObject.get)(state.entities.records, [kind, name, 'saving', recordId, 'pending'], false);
4822 }
4823 /**
4824 * Returns true if the specified entity record is deleting, and false otherwise.
4825 *
4826 * @param state State tree.
4827 * @param kind Entity kind.
4828 * @param name Entity name.
4829 * @param recordId Record ID.
4830 *
4831 * @return Whether the entity record is deleting or not.
4832 */
4833
4834 function isDeletingEntityRecord(state, kind, name, recordId) {
4835 return (0,external_lodash_namespaceObject.get)(state.entities.records, [kind, name, 'deleting', recordId, 'pending'], false);
4836 }
4837 /**
4838 * Returns the specified entity record's last save error.
4839 *
4840 * @param state State tree.
4841 * @param kind Entity kind.
4842 * @param name Entity name.
4843 * @param recordId Record ID.
4844 *
4845 * @return The entity record's save error.
4846 */
4847
4848 function getLastEntitySaveError(state, kind, name, recordId) {
4849 return (0,external_lodash_namespaceObject.get)(state.entities.records, [kind, name, 'saving', recordId, 'error']);
4850 }
4851 /**
4852 * Returns the specified entity record's last delete error.
4853 *
4854 * @param state State tree.
4855 * @param kind Entity kind.
4856 * @param name Entity name.
4857 * @param recordId Record ID.
4858 *
4859 * @return The entity record's save error.
4860 */
4861
4862 function getLastEntityDeleteError(state, kind, name, recordId) {
4863 return (0,external_lodash_namespaceObject.get)(state.entities.records, [kind, name, 'deleting', recordId, 'error']);
4864 }
4865 /**
4866 * Returns the current undo offset for the
4867 * entity records edits history. The offset
4868 * represents how many items from the end
4869 * of the history stack we are at. 0 is the
4870 * last edit, -1 is the second last, and so on.
4871 *
4872 * @param state State tree.
4873 *
4874 * @return The current undo offset.
4875 */
4876
4877 function getCurrentUndoOffset(state) {
4878 return state.undo.offset;
4879 }
4880 /**
4881 * Returns the previous edit from the current undo offset
4882 * for the entity records edits history, if any.
4883 *
4884 * @param state State tree.
4885 *
4886 * @return The edit.
4887 */
4888
4889
4890 function getUndoEdit(state) {
4891 return state.undo[state.undo.length - 2 + getCurrentUndoOffset(state)];
4892 }
4893 /**
4894 * Returns the next edit from the current undo offset
4895 * for the entity records edits history, if any.
4896 *
4897 * @param state State tree.
4898 *
4899 * @return The edit.
4900 */
4901
4902 function getRedoEdit(state) {
4903 return state.undo[state.undo.length + getCurrentUndoOffset(state)];
4904 }
4905 /**
4906 * Returns true if there is a previous edit from the current undo offset
4907 * for the entity records edits history, and false otherwise.
4908 *
4909 * @param state State tree.
4910 *
4911 * @return Whether there is a previous edit or not.
4912 */
4913
4914 function hasUndo(state) {
4915 return Boolean(getUndoEdit(state));
4916 }
4917 /**
4918 * Returns true if there is a next edit from the current undo offset
4919 * for the entity records edits history, and false otherwise.
4920 *
4921 * @param state State tree.
4922 *
4923 * @return Whether there is a next edit or not.
4924 */
4925
4926 function hasRedo(state) {
4927 return Boolean(getRedoEdit(state));
4928 }
4929 /**
4930 * Return the current theme.
4931 *
4932 * @param state Data state.
4933 *
4934 * @return The current theme.
4935 */
4936
4937 function getCurrentTheme(state) {
4938 return getEntityRecord(state, 'root', 'theme', state.currentTheme);
4939 }
4940 /**
4941 * Return the ID of the current global styles object.
4942 *
4943 * @param state Data state.
4944 *
4945 * @return The current global styles ID.
4946 */
4947
4948 function __experimentalGetCurrentGlobalStylesId(state) {
4949 return state.currentGlobalStylesId;
4950 }
4951 /**
4952 * Return theme supports data in the index.
4953 *
4954 * @param state Data state.
4955 *
4956 * @return Index data.
4957 */
4958
4959 function getThemeSupports(state) {
4960 var _getCurrentTheme$them, _getCurrentTheme;
4961
4962 return (_getCurrentTheme$them = (_getCurrentTheme = getCurrentTheme(state)) === null || _getCurrentTheme === void 0 ? void 0 : _getCurrentTheme.theme_supports) !== null && _getCurrentTheme$them !== void 0 ? _getCurrentTheme$them : EMPTY_OBJECT;
4963 }
4964 /**
4965 * Returns the embed preview for the given URL.
4966 *
4967 * @param state Data state.
4968 * @param url Embedded URL.
4969 *
4970 * @return Undefined if the preview has not been fetched, otherwise, the preview fetched from the embed preview API.
4971 */
4972
4973 function getEmbedPreview(state, url) {
4974 return state.embedPreviews[url];
4975 }
4976 /**
4977 * Determines if the returned preview is an oEmbed link fallback.
4978 *
4979 * WordPress can be configured to return a simple link to a URL if it is not embeddable.
4980 * We need to be able to determine if a URL is embeddable or not, based on what we
4981 * get back from the oEmbed preview API.
4982 *
4983 * @param state Data state.
4984 * @param url Embedded URL.
4985 *
4986 * @return Is the preview for the URL an oEmbed link fallback.
4987 */
4988
4989 function isPreviewEmbedFallback(state, url) {
4990 const preview = state.embedPreviews[url];
4991 const oEmbedLinkCheck = '<a href="' + url + '">' + url + '</a>';
4992
4993 if (!preview) {
4994 return false;
4995 }
4996
4997 return preview.html === oEmbedLinkCheck;
4998 }
4999 /**
5000 * Returns whether the current user can perform the given action on the given
5001 * REST resource.
5002 *
5003 * Calling this may trigger an OPTIONS request to the REST API via the
5004 * `canUser()` resolver.
5005 *
5006 * https://developer.wordpress.org/rest-api/reference/
5007 *
5008 * @param state Data state.
5009 * @param action Action to check. One of: 'create', 'read', 'update', 'delete'.
5010 * @param resource REST resource to check, e.g. 'media' or 'posts'.
5011 * @param id Optional ID of the rest resource to check.
5012 *
5013 * @return Whether or not the user can perform the action,
5014 * or `undefined` if the OPTIONS request is still being made.
5015 */
5016
5017 function canUser(state, action, resource, id) {
5018 const key = [action, resource, id].filter(Boolean).join('/');
5019 return (0,external_lodash_namespaceObject.get)(state, ['userPermissions', key]);
5020 }
5021 /**
5022 * Returns whether the current user can edit the given entity.
5023 *
5024 * Calling this may trigger an OPTIONS request to the REST API via the
5025 * `canUser()` resolver.
5026 *
5027 * https://developer.wordpress.org/rest-api/reference/
5028 *
5029 * @param state Data state.
5030 * @param kind Entity kind.
5031 * @param name Entity name.
5032 * @param recordId Record's id.
5033 * @return Whether or not the user can edit,
5034 * or `undefined` if the OPTIONS request is still being made.
5035 */
5036
5037 function canUserEditEntityRecord(state, kind, name, recordId) {
5038 const entityConfig = getEntityConfig(state, kind, name);
5039
5040 if (!entityConfig) {
5041 return false;
5042 }
5043
5044 const resource = entityConfig.__unstable_rest_base;
5045 return canUser(state, 'update', resource, recordId);
5046 }
5047 /**
5048 * Returns the latest autosaves for the post.
5049 *
5050 * May return multiple autosaves since the backend stores one autosave per
5051 * author for each post.
5052 *
5053 * @param state State tree.
5054 * @param postType The type of the parent post.
5055 * @param postId The id of the parent post.
5056 *
5057 * @return An array of autosaves for the post, or undefined if there is none.
5058 */
5059
5060 function getAutosaves(state, postType, postId) {
5061 return state.autosaves[postId];
5062 }
5063 /**
5064 * Returns the autosave for the post and author.
5065 *
5066 * @param state State tree.
5067 * @param postType The type of the parent post.
5068 * @param postId The id of the parent post.
5069 * @param authorId The id of the author.
5070 *
5071 * @return The autosave for the post and author.
5072 */
5073
5074 function getAutosave(state, postType, postId, authorId) {
5075 if (authorId === undefined) {
5076 return;
5077 }
5078
5079 const autosaves = state.autosaves[postId];
5080 return autosaves === null || autosaves === void 0 ? void 0 : autosaves.find(autosave => autosave.author === authorId);
5081 }
5082 /**
5083 * Returns true if the REST request for autosaves has completed.
5084 *
5085 * @param state State tree.
5086 * @param postType The type of the parent post.
5087 * @param postId The id of the parent post.
5088 *
5089 * @return True if the REST request was completed. False otherwise.
5090 */
5091
5092 const hasFetchedAutosaves = (0,external_wp_data_namespaceObject.createRegistrySelector)(select => (state, postType, postId) => {
5093 return select(STORE_NAME).hasFinishedResolution('getAutosaves', [postType, postId]);
5094 });
5095 /**
5096 * Returns a new reference when edited values have changed. This is useful in
5097 * inferring where an edit has been made between states by comparison of the
5098 * return values using strict equality.
5099 *
5100 * @example
5101 *
5102 * ```
5103 * const hasEditOccurred = (
5104 * getReferenceByDistinctEdits( beforeState ) !==
5105 * getReferenceByDistinctEdits( afterState )
5106 * );
5107 * ```
5108 *
5109 * @param state Editor state.
5110 *
5111 * @return A value whose reference will change only when an edit occurs.
5112 */
5113
5114 const getReferenceByDistinctEdits = rememo( // This unused state argument is listed here for the documentation generating tool (docgen).
5115 state => [], state => [state.undo.length, state.undo.offset, state.undo.flattenedUndo]);
5116 /**
5117 * Retrieve the frontend template used for a given link.
5118 *
5119 * @param state Editor state.
5120 * @param link Link.
5121 *
5122 * @return The template record.
5123 */
5124
5125 function __experimentalGetTemplateForLink(state, link) {
5126 const records = getEntityRecords(state, 'postType', 'wp_template', {
5127 'find-template': link
5128 });
5129
5130 if (records !== null && records !== void 0 && records.length) {
5131 return getEditedEntityRecord(state, 'postType', 'wp_template', records[0].id);
5132 }
5133
5134 return null;
5135 }
5136 /**
5137 * Retrieve the current theme's base global styles
5138 *
5139 * @param state Editor state.
5140 *
5141 * @return The Global Styles object.
5142 */
5143
5144 function __experimentalGetCurrentThemeBaseGlobalStyles(state) {
5145 const currentTheme = getCurrentTheme(state);
5146
5147 if (!currentTheme) {
5148 return null;
5149 }
5150
5151 return state.themeBaseGlobalStyles[currentTheme.stylesheet];
5152 }
5153 /**
5154 * Return the ID of the current global styles object.
5155 *
5156 * @param state Data state.
5157 *
5158 * @return The current global styles ID.
5159 */
5160
5161 function __experimentalGetCurrentThemeGlobalStylesVariations(state) {
5162 const currentTheme = getCurrentTheme(state);
5163
5164 if (!currentTheme) {
5165 return null;
5166 }
5167
5168 return state.themeGlobalStyleVariations[currentTheme.stylesheet];
5169 }
5170 /**
5171 * Retrieve the list of registered block patterns.
5172 *
5173 * @param state Data state.
5174 *
5175 * @return Block pattern list.
5176 */
5177
5178 function getBlockPatterns(state) {
5179 return state.blockPatterns;
5180 }
5181 /**
5182 * Retrieve the list of registered block pattern categories.
5183 *
5184 * @param state Data state.
5185 *
5186 * @return Block pattern category list.
5187 */
5188
5189 function getBlockPatternCategories(state) {
5190 return state.blockPatternCategories;
5191 }
5192
5193 ;// CONCATENATED MODULE: ./node_modules/camel-case/dist.es2015/index.js
5194
5195
5196 function camelCaseTransform(input, index) {
5197 if (index === 0)
5198 return input.toLowerCase();
5199 return pascalCaseTransform(input, index);
5200 }
5201 function camelCaseTransformMerge(input, index) {
5202 if (index === 0)
5203 return input.toLowerCase();
5204 return pascalCaseTransformMerge(input);
5205 }
5206 function camelCase(input, options) {
5207 if (options === void 0) { options = {}; }
5208 return pascalCase(input, __assign({ transform: camelCaseTransform }, options));
5209 }
5210
5211 ;// CONCATENATED MODULE: ./packages/core-data/build-module/utils/forward-resolver.js
5212 /**
5213 * Higher-order function which forward the resolution to another resolver with the same arguments.
5214 *
5215 * @param {string} resolverName forwarded resolver.
5216 *
5217 * @return {Function} Enhanced resolver.
5218 */
5219 const forwardResolver = resolverName => function () {
5220 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
5221 args[_key] = arguments[_key];
5222 }
5223
5224 return async _ref => {
5225 let {
5226 resolveSelect
5227 } = _ref;
5228 await resolveSelect[resolverName](...args);
5229 };
5230 };
5231
5232 /* harmony default export */ var forward_resolver = (forwardResolver);
5233
5234 ;// CONCATENATED MODULE: ./packages/core-data/build-module/resolvers.js
5235 /**
5236 * External dependencies
5237 */
5238
5239 /**
5240 * WordPress dependencies
5241 */
5242
5243
5244
5245 /**
5246 * Internal dependencies
5247 */
5248
5249
5250
5251
5252 /**
5253 * Requests authors from the REST API.
5254 *
5255 * @param {Object|undefined} query Optional object of query parameters to
5256 * include with request.
5257 */
5258
5259 const resolvers_getAuthors = query => async _ref => {
5260 let {
5261 dispatch
5262 } = _ref;
5263 const path = (0,external_wp_url_namespaceObject.addQueryArgs)('/wp/v2/users/?who=authors&per_page=100', query);
5264 const users = await external_wp_apiFetch_default()({
5265 path
5266 });
5267 dispatch.receiveUserQuery(path, users);
5268 };
5269 /**
5270 * Requests the current user from the REST API.
5271 */
5272
5273 const resolvers_getCurrentUser = () => async _ref2 => {
5274 let {
5275 dispatch
5276 } = _ref2;
5277 const currentUser = await external_wp_apiFetch_default()({
5278 path: '/wp/v2/users/me'
5279 });
5280 dispatch.receiveCurrentUser(currentUser);
5281 };
5282 /**
5283 * Requests an entity's record from the REST API.
5284 *
5285 * @param {string} kind Entity kind.
5286 * @param {string} name Entity name.
5287 * @param {number|string} key Record's key
5288 * @param {Object|undefined} query Optional object of query parameters to
5289 * include with request. If requesting specific
5290 * fields, fields must always include the ID.
5291 */
5292
5293 const resolvers_getEntityRecord = function (kind, name) {
5294 let key = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : '';
5295 let query = arguments.length > 3 ? arguments[3] : undefined;
5296 return async _ref3 => {
5297 let {
5298 select,
5299 dispatch
5300 } = _ref3;
5301 const configs = await dispatch(getOrLoadEntitiesConfig(kind));
5302 const entityConfig = configs.find(config => config.name === name && config.kind === kind);
5303
5304 if (!entityConfig || entityConfig !== null && entityConfig !== void 0 && entityConfig.__experimentalNoFetch) {
5305 return;
5306 }
5307
5308 const lock = await dispatch.__unstableAcquireStoreLock(STORE_NAME, ['entities', 'records', kind, name, key], {
5309 exclusive: false
5310 });
5311
5312 try {
5313 if (query !== undefined && query._fields) {
5314 // If requesting specific fields, items and query association to said
5315 // records are stored by ID reference. Thus, fields must always include
5316 // the ID.
5317 query = { ...query,
5318 _fields: [...new Set([...(get_normalized_comma_separable(query._fields) || []), entityConfig.key || DEFAULT_ENTITY_KEY])].join()
5319 };
5320 } // Disable reason: While true that an early return could leave `path`
5321 // unused, it's important that path is derived using the query prior to
5322 // additional query modifications in the condition below, since those
5323 // modifications are relevant to how the data is tracked in state, and not
5324 // for how the request is made to the REST API.
5325 // eslint-disable-next-line @wordpress/no-unused-vars-before-return
5326
5327
5328 const path = (0,external_wp_url_namespaceObject.addQueryArgs)(entityConfig.baseURL + (key ? '/' + key : ''), { ...entityConfig.baseURLParams,
5329 ...query
5330 });
5331
5332 if (query !== undefined) {
5333 query = { ...query,
5334 include: [key]
5335 }; // The resolution cache won't consider query as reusable based on the
5336 // fields, so it's tested here, prior to initiating the REST request,
5337 // and without causing `getEntityRecords` resolution to occur.
5338
5339 const hasRecords = select.hasEntityRecords(kind, name, query);
5340
5341 if (hasRecords) {
5342 return;
5343 }
5344 }
5345
5346 const record = await external_wp_apiFetch_default()({
5347 path
5348 });
5349 dispatch.receiveEntityRecords(kind, name, record, query);
5350 } finally {
5351 dispatch.__unstableReleaseStoreLock(lock);
5352 }
5353 };
5354 };
5355 /**
5356 * Requests an entity's record from the REST API.
5357 */
5358
5359 const resolvers_getRawEntityRecord = forward_resolver('getEntityRecord');
5360 /**
5361 * Requests an entity's record from the REST API.
5362 */
5363
5364 const resolvers_getEditedEntityRecord = forward_resolver('getEntityRecord');
5365 /**
5366 * Requests the entity's records from the REST API.
5367 *
5368 * @param {string} kind Entity kind.
5369 * @param {string} name Entity name.
5370 * @param {Object?} query Query Object. If requesting specific fields, fields
5371 * must always include the ID.
5372 */
5373
5374 const resolvers_getEntityRecords = function (kind, name) {
5375 let query = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
5376 return async _ref4 => {
5377 let {
5378 dispatch
5379 } = _ref4;
5380 const configs = await dispatch(getOrLoadEntitiesConfig(kind));
5381 const entityConfig = configs.find(config => config.name === name && config.kind === kind);
5382
5383 if (!entityConfig || entityConfig !== null && entityConfig !== void 0 && entityConfig.__experimentalNoFetch) {
5384 return;
5385 }
5386
5387 const lock = await dispatch.__unstableAcquireStoreLock(STORE_NAME, ['entities', 'records', kind, name], {
5388 exclusive: false
5389 });
5390
5391 try {
5392 var _query;
5393
5394 if (query._fields) {
5395 // If requesting specific fields, items and query association to said
5396 // records are stored by ID reference. Thus, fields must always include
5397 // the ID.
5398 query = { ...query,
5399 _fields: [...new Set([...(get_normalized_comma_separable(query._fields) || []), entityConfig.key || DEFAULT_ENTITY_KEY])].join()
5400 };
5401 }
5402
5403 const path = (0,external_wp_url_namespaceObject.addQueryArgs)(entityConfig.baseURL, { ...entityConfig.baseURLParams,
5404 ...query
5405 });
5406 let records = Object.values(await external_wp_apiFetch_default()({
5407 path
5408 })); // If we request fields but the result doesn't contain the fields,
5409 // explicitely set these fields as "undefined"
5410 // that way we consider the query "fullfilled".
5411
5412 if (query._fields) {
5413 records = records.map(record => {
5414 query._fields.split(',').forEach(field => {
5415 if (!record.hasOwnProperty(field)) {
5416 record[field] = undefined;
5417 }
5418 });
5419
5420 return record;
5421 });
5422 }
5423
5424 dispatch.receiveEntityRecords(kind, name, records, query); // When requesting all fields, the list of results can be used to
5425 // resolve the `getEntityRecord` selector in addition to `getEntityRecords`.
5426 // See https://github.com/WordPress/gutenberg/pull/26575
5427
5428 if (!((_query = query) !== null && _query !== void 0 && _query._fields) && !query.context) {
5429 const key = entityConfig.key || DEFAULT_ENTITY_KEY;
5430 const resolutionsArgs = records.filter(record => record[key]).map(record => [kind, name, record[key]]);
5431 dispatch({
5432 type: 'START_RESOLUTIONS',
5433 selectorName: 'getEntityRecord',
5434 args: resolutionsArgs
5435 });
5436 dispatch({
5437 type: 'FINISH_RESOLUTIONS',
5438 selectorName: 'getEntityRecord',
5439 args: resolutionsArgs
5440 });
5441 }
5442 } finally {
5443 dispatch.__unstableReleaseStoreLock(lock);
5444 }
5445 };
5446 };
5447
5448 resolvers_getEntityRecords.shouldInvalidate = (action, kind, name) => {
5449 return (action.type === 'RECEIVE_ITEMS' || action.type === 'REMOVE_ITEMS') && action.invalidateCache && kind === action.kind && name === action.name;
5450 };
5451 /**
5452 * Requests the current theme.
5453 */
5454
5455
5456 const resolvers_getCurrentTheme = () => async _ref5 => {
5457 let {
5458 dispatch,
5459 resolveSelect
5460 } = _ref5;
5461 const activeThemes = await resolveSelect.getEntityRecords('root', 'theme', {
5462 status: 'active'
5463 });
5464 dispatch.receiveCurrentTheme(activeThemes[0]);
5465 };
5466 /**
5467 * Requests theme supports data from the index.
5468 */
5469
5470 const resolvers_getThemeSupports = forward_resolver('getCurrentTheme');
5471 /**
5472 * Requests a preview from the from the Embed API.
5473 *
5474 * @param {string} url URL to get the preview for.
5475 */
5476
5477 const resolvers_getEmbedPreview = url => async _ref6 => {
5478 let {
5479 dispatch
5480 } = _ref6;
5481
5482 try {
5483 const embedProxyResponse = await external_wp_apiFetch_default()({
5484 path: (0,external_wp_url_namespaceObject.addQueryArgs)('/oembed/1.0/proxy', {
5485 url
5486 })
5487 });
5488 dispatch.receiveEmbedPreview(url, embedProxyResponse);
5489 } catch (error) {
5490 // Embed API 404s if the URL cannot be embedded, so we have to catch the error from the apiRequest here.
5491 dispatch.receiveEmbedPreview(url, false);
5492 }
5493 };
5494 /**
5495 * Checks whether the current user can perform the given action on the given
5496 * REST resource.
5497 *
5498 * @param {string} requestedAction Action to check. One of: 'create', 'read', 'update',
5499 * 'delete'.
5500 * @param {string} resource REST resource to check, e.g. 'media' or 'posts'.
5501 * @param {?string} id ID of the rest resource to check.
5502 */
5503
5504 const resolvers_canUser = (requestedAction, resource, id) => async _ref7 => {
5505 var _response$headers;
5506
5507 let {
5508 dispatch,
5509 registry
5510 } = _ref7;
5511 const {
5512 hasStartedResolution
5513 } = registry.select(STORE_NAME);
5514 const resourcePath = id ? `${resource}/${id}` : resource;
5515 const retrievedActions = ['create', 'read', 'update', 'delete'];
5516
5517 if (!retrievedActions.includes(requestedAction)) {
5518 throw new Error(`'${requestedAction}' is not a valid action.`);
5519 } // Prevent resolving the same resource twice.
5520
5521
5522 for (const relatedAction of retrievedActions) {
5523 if (relatedAction === requestedAction) {
5524 continue;
5525 }
5526
5527 const isAlreadyResolving = hasStartedResolution('canUser', [relatedAction, resource, id]);
5528
5529 if (isAlreadyResolving) {
5530 return;
5531 }
5532 }
5533
5534 let response;
5535
5536 try {
5537 response = await external_wp_apiFetch_default()({
5538 path: `/wp/v2/${resourcePath}`,
5539 method: 'OPTIONS',
5540 parse: false
5541 });
5542 } catch (error) {
5543 // Do nothing if our OPTIONS request comes back with an API error (4xx or
5544 // 5xx). The previously determined isAllowed value will remain in the store.
5545 return;
5546 } // Optional chaining operator is used here because the API requests don't
5547 // return the expected result in the native version. Instead, API requests
5548 // only return the result, without including response properties like the headers.
5549
5550
5551 const allowHeader = (_response$headers = response.headers) === null || _response$headers === void 0 ? void 0 : _response$headers.get('allow');
5552 const allowedMethods = (allowHeader === null || allowHeader === void 0 ? void 0 : allowHeader.allow) || allowHeader || '';
5553 const permissions = {};
5554 const methods = {
5555 create: 'POST',
5556 read: 'GET',
5557 update: 'PUT',
5558 delete: 'DELETE'
5559 };
5560
5561 for (const [actionName, methodName] of Object.entries(methods)) {
5562 permissions[actionName] = allowedMethods.includes(methodName);
5563 }
5564
5565 for (const action of retrievedActions) {
5566 dispatch.receiveUserPermission(`${action}/${resourcePath}`, permissions[action]);
5567 }
5568 };
5569 /**
5570 * Checks whether the current user can perform the given action on the given
5571 * REST resource.
5572 *
5573 * @param {string} kind Entity kind.
5574 * @param {string} name Entity name.
5575 * @param {string} recordId Record's id.
5576 */
5577
5578 const resolvers_canUserEditEntityRecord = (kind, name, recordId) => async _ref8 => {
5579 let {
5580 dispatch
5581 } = _ref8;
5582 const configs = await dispatch(getOrLoadEntitiesConfig(kind));
5583 const entityConfig = configs.find(config => config.name === name && config.kind === kind);
5584
5585 if (!entityConfig) {
5586 return;
5587 }
5588
5589 const resource = entityConfig.__unstable_rest_base;
5590 await dispatch(resolvers_canUser('update', resource, recordId));
5591 };
5592 /**
5593 * Request autosave data from the REST API.
5594 *
5595 * @param {string} postType The type of the parent post.
5596 * @param {number} postId The id of the parent post.
5597 */
5598
5599 const resolvers_getAutosaves = (postType, postId) => async _ref9 => {
5600 let {
5601 dispatch,
5602 resolveSelect
5603 } = _ref9;
5604 const {
5605 rest_base: restBase,
5606 rest_namespace: restNamespace = 'wp/v2'
5607 } = await resolveSelect.getPostType(postType);
5608 const autosaves = await external_wp_apiFetch_default()({
5609 path: `/${restNamespace}/${restBase}/${postId}/autosaves?context=edit`
5610 });
5611
5612 if (autosaves && autosaves.length) {
5613 dispatch.receiveAutosaves(postId, autosaves);
5614 }
5615 };
5616 /**
5617 * Request autosave data from the REST API.
5618 *
5619 * This resolver exists to ensure the underlying autosaves are fetched via
5620 * `getAutosaves` when a call to the `getAutosave` selector is made.
5621 *
5622 * @param {string} postType The type of the parent post.
5623 * @param {number} postId The id of the parent post.
5624 */
5625
5626 const resolvers_getAutosave = (postType, postId) => async _ref10 => {
5627 let {
5628 resolveSelect
5629 } = _ref10;
5630 await resolveSelect.getAutosaves(postType, postId);
5631 };
5632 /**
5633 * Retrieve the frontend template used for a given link.
5634 *
5635 * @param {string} link Link.
5636 */
5637
5638 const resolvers_experimentalGetTemplateForLink = link => async _ref11 => {
5639 let {
5640 dispatch,
5641 resolveSelect
5642 } = _ref11;
5643 // Ideally this should be using an apiFetch call
5644 // We could potentially do so by adding a "filter" to the `wp_template` end point.
5645 // Also it seems the returned object is not a regular REST API post type.
5646 let template;
5647
5648 try {
5649 template = await window.fetch((0,external_wp_url_namespaceObject.addQueryArgs)(link, {
5650 '_wp-find-template': true
5651 })).then(res => res.json()).then(_ref12 => {
5652 let {
5653 data
5654 } = _ref12;
5655 return data;
5656 });
5657 } catch (e) {// For non-FSE themes, it is possible that this request returns an error.
5658 }
5659
5660 if (!template) {
5661 return;
5662 }
5663
5664 const record = await resolveSelect.getEntityRecord('postType', 'wp_template', template.id);
5665
5666 if (record) {
5667 dispatch.receiveEntityRecords('postType', 'wp_template', [record], {
5668 'find-template': link
5669 });
5670 }
5671 };
5672
5673 resolvers_experimentalGetTemplateForLink.shouldInvalidate = action => {
5674 return (action.type === 'RECEIVE_ITEMS' || action.type === 'REMOVE_ITEMS') && action.invalidateCache && action.kind === 'postType' && action.name === 'wp_template';
5675 };
5676
5677 const resolvers_experimentalGetCurrentGlobalStylesId = () => async _ref13 => {
5678 var _activeThemes$, _activeThemes$$_links, _activeThemes$$_links2, _activeThemes$$_links3;
5679
5680 let {
5681 dispatch,
5682 resolveSelect
5683 } = _ref13;
5684 const activeThemes = await resolveSelect.getEntityRecords('root', 'theme', {
5685 status: 'active'
5686 });
5687 const globalStylesURL = activeThemes === null || activeThemes === void 0 ? void 0 : (_activeThemes$ = activeThemes[0]) === null || _activeThemes$ === void 0 ? void 0 : (_activeThemes$$_links = _activeThemes$._links) === null || _activeThemes$$_links === void 0 ? void 0 : (_activeThemes$$_links2 = _activeThemes$$_links['wp:user-global-styles']) === null || _activeThemes$$_links2 === void 0 ? void 0 : (_activeThemes$$_links3 = _activeThemes$$_links2[0]) === null || _activeThemes$$_links3 === void 0 ? void 0 : _activeThemes$$_links3.href;
5688
5689 if (globalStylesURL) {
5690 const globalStylesObject = await external_wp_apiFetch_default()({
5691 url: globalStylesURL
5692 });
5693
5694 dispatch.__experimentalReceiveCurrentGlobalStylesId(globalStylesObject.id);
5695 }
5696 };
5697 const resolvers_experimentalGetCurrentThemeBaseGlobalStyles = () => async _ref14 => {
5698 let {
5699 resolveSelect,
5700 dispatch
5701 } = _ref14;
5702 const currentTheme = await resolveSelect.getCurrentTheme();
5703 const themeGlobalStyles = await external_wp_apiFetch_default()({
5704 path: `/wp/v2/global-styles/themes/${currentTheme.stylesheet}`
5705 });
5706
5707 dispatch.__experimentalReceiveThemeBaseGlobalStyles(currentTheme.stylesheet, themeGlobalStyles);
5708 };
5709 const resolvers_experimentalGetCurrentThemeGlobalStylesVariations = () => async _ref15 => {
5710 let {
5711 resolveSelect,
5712 dispatch
5713 } = _ref15;
5714 const currentTheme = await resolveSelect.getCurrentTheme();
5715 const variations = await external_wp_apiFetch_default()({
5716 path: `/wp/v2/global-styles/themes/${currentTheme.stylesheet}/variations`
5717 });
5718
5719 dispatch.__experimentalReceiveThemeGlobalStyleVariations(currentTheme.stylesheet, variations);
5720 };
5721 const resolvers_getBlockPatterns = () => async _ref16 => {
5722 let {
5723 dispatch
5724 } = _ref16;
5725 const restPatterns = await external_wp_apiFetch_default()({
5726 path: '/wp/v2/block-patterns/patterns'
5727 });
5728 const patterns = restPatterns === null || restPatterns === void 0 ? void 0 : restPatterns.map(pattern => Object.fromEntries(Object.entries(pattern).map(_ref17 => {
5729 let [key, value] = _ref17;
5730 return [camelCase(key), value];
5731 })));
5732 dispatch({
5733 type: 'RECEIVE_BLOCK_PATTERNS',
5734 patterns
5735 });
5736 };
5737 const resolvers_getBlockPatternCategories = () => async _ref18 => {
5738 let {
5739 dispatch
5740 } = _ref18;
5741 const categories = await external_wp_apiFetch_default()({
5742 path: '/wp/v2/block-patterns/categories'
5743 });
5744 dispatch({
5745 type: 'RECEIVE_BLOCK_PATTERN_CATEGORIES',
5746 categories
5747 });
5748 };
5749
5750 ;// CONCATENATED MODULE: ./packages/core-data/build-module/locks/utils.js
5751 function deepCopyLocksTreePath(tree, path) {
5752 const newTree = { ...tree
5753 };
5754 let currentNode = newTree;
5755
5756 for (const branchName of path) {
5757 currentNode.children = { ...currentNode.children,
5758 [branchName]: {
5759 locks: [],
5760 children: {},
5761 ...currentNode.children[branchName]
5762 }
5763 };
5764 currentNode = currentNode.children[branchName];
5765 }
5766
5767 return newTree;
5768 }
5769 function getNode(tree, path) {
5770 let currentNode = tree;
5771
5772 for (const branchName of path) {
5773 const nextNode = currentNode.children[branchName];
5774
5775 if (!nextNode) {
5776 return null;
5777 }
5778
5779 currentNode = nextNode;
5780 }
5781
5782 return currentNode;
5783 }
5784 function* iteratePath(tree, path) {
5785 let currentNode = tree;
5786 yield currentNode;
5787
5788 for (const branchName of path) {
5789 const nextNode = currentNode.children[branchName];
5790
5791 if (!nextNode) {
5792 break;
5793 }
5794
5795 yield nextNode;
5796 currentNode = nextNode;
5797 }
5798 }
5799 function* iterateDescendants(node) {
5800 const stack = Object.values(node.children);
5801
5802 while (stack.length) {
5803 const childNode = stack.pop();
5804 yield childNode;
5805 stack.push(...Object.values(childNode.children));
5806 }
5807 }
5808 function hasConflictingLock(_ref, locks) {
5809 let {
5810 exclusive
5811 } = _ref;
5812
5813 if (exclusive && locks.length) {
5814 return true;
5815 }
5816
5817 if (!exclusive && locks.filter(lock => lock.exclusive).length) {
5818 return true;
5819 }
5820
5821 return false;
5822 }
5823
5824 ;// CONCATENATED MODULE: ./packages/core-data/build-module/locks/reducer.js
5825 /**
5826 * Internal dependencies
5827 */
5828
5829 const DEFAULT_STATE = {
5830 requests: [],
5831 tree: {
5832 locks: [],
5833 children: {}
5834 }
5835 };
5836 /**
5837 * Reducer returning locks.
5838 *
5839 * @param {Object} state Current state.
5840 * @param {Object} action Dispatched action.
5841 *
5842 * @return {Object} Updated state.
5843 */
5844
5845 function locks() {
5846 let state = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : DEFAULT_STATE;
5847 let action = arguments.length > 1 ? arguments[1] : undefined;
5848
5849 switch (action.type) {
5850 case 'ENQUEUE_LOCK_REQUEST':
5851 {
5852 const {
5853 request
5854 } = action;
5855 return { ...state,
5856 requests: [request, ...state.requests]
5857 };
5858 }
5859
5860 case 'GRANT_LOCK_REQUEST':
5861 {
5862 const {
5863 lock,
5864 request
5865 } = action;
5866 const {
5867 store,
5868 path
5869 } = request;
5870 const storePath = [store, ...path];
5871 const newTree = deepCopyLocksTreePath(state.tree, storePath);
5872 const node = getNode(newTree, storePath);
5873 node.locks = [...node.locks, lock];
5874 return { ...state,
5875 requests: state.requests.filter(r => r !== request),
5876 tree: newTree
5877 };
5878 }
5879
5880 case 'RELEASE_LOCK':
5881 {
5882 const {
5883 lock
5884 } = action;
5885 const storePath = [lock.store, ...lock.path];
5886 const newTree = deepCopyLocksTreePath(state.tree, storePath);
5887 const node = getNode(newTree, storePath);
5888 node.locks = node.locks.filter(l => l !== lock);
5889 return { ...state,
5890 tree: newTree
5891 };
5892 }
5893 }
5894
5895 return state;
5896 }
5897
5898 ;// CONCATENATED MODULE: ./packages/core-data/build-module/locks/selectors.js
5899 /**
5900 * Internal dependencies
5901 */
5902
5903 function getPendingLockRequests(state) {
5904 return state.requests;
5905 }
5906 function isLockAvailable(state, store, path, _ref) {
5907 let {
5908 exclusive
5909 } = _ref;
5910 const storePath = [store, ...path];
5911 const locks = state.tree; // Validate all parents and the node itself
5912
5913 for (const node of iteratePath(locks, storePath)) {
5914 if (hasConflictingLock({
5915 exclusive
5916 }, node.locks)) {
5917 return false;
5918 }
5919 } // iteratePath terminates early if path is unreachable, let's
5920 // re-fetch the node and check it exists in the tree.
5921
5922
5923 const node = getNode(locks, storePath);
5924
5925 if (!node) {
5926 return true;
5927 } // Validate all nested nodes
5928
5929
5930 for (const descendant of iterateDescendants(node)) {
5931 if (hasConflictingLock({
5932 exclusive
5933 }, descendant.locks)) {
5934 return false;
5935 }
5936 }
5937
5938 return true;
5939 }
5940
5941 ;// CONCATENATED MODULE: ./packages/core-data/build-module/locks/engine.js
5942 /**
5943 * Internal dependencies
5944 */
5945
5946
5947 function createLocks() {
5948 let state = locks(undefined, {
5949 type: '@@INIT'
5950 });
5951
5952 function processPendingLockRequests() {
5953 for (const request of getPendingLockRequests(state)) {
5954 const {
5955 store,
5956 path,
5957 exclusive,
5958 notifyAcquired
5959 } = request;
5960
5961 if (isLockAvailable(state, store, path, {
5962 exclusive
5963 })) {
5964 const lock = {
5965 store,
5966 path,
5967 exclusive
5968 };
5969 state = locks(state, {
5970 type: 'GRANT_LOCK_REQUEST',
5971 lock,
5972 request
5973 });
5974 notifyAcquired(lock);
5975 }
5976 }
5977 }
5978
5979 function acquire(store, path, exclusive) {
5980 return new Promise(resolve => {
5981 state = locks(state, {
5982 type: 'ENQUEUE_LOCK_REQUEST',
5983 request: {
5984 store,
5985 path,
5986 exclusive,
5987 notifyAcquired: resolve
5988 }
5989 });
5990 processPendingLockRequests();
5991 });
5992 }
5993
5994 function release(lock) {
5995 state = locks(state, {
5996 type: 'RELEASE_LOCK',
5997 lock
5998 });
5999 processPendingLockRequests();
6000 }
6001
6002 return {
6003 acquire,
6004 release
6005 };
6006 }
6007
6008 ;// CONCATENATED MODULE: ./packages/core-data/build-module/locks/actions.js
6009 /**
6010 * Internal dependencies
6011 */
6012
6013 function createLocksActions() {
6014 const locks = createLocks();
6015
6016 function __unstableAcquireStoreLock(store, path, _ref) {
6017 let {
6018 exclusive
6019 } = _ref;
6020 return () => locks.acquire(store, path, exclusive);
6021 }
6022
6023 function __unstableReleaseStoreLock(lock) {
6024 return () => locks.release(lock);
6025 }
6026
6027 return {
6028 __unstableAcquireStoreLock,
6029 __unstableReleaseStoreLock
6030 };
6031 }
6032
6033 ;// CONCATENATED MODULE: external ["wp","element"]
6034 var external_wp_element_namespaceObject = window["wp"]["element"];
6035 ;// CONCATENATED MODULE: external ["wp","blocks"]
6036 var external_wp_blocks_namespaceObject = window["wp"]["blocks"];
6037 ;// CONCATENATED MODULE: ./packages/core-data/build-module/entity-provider.js
6038
6039
6040 /**
6041 * WordPress dependencies
6042 */
6043
6044
6045
6046 /**
6047 * Internal dependencies
6048 */
6049
6050
6051 /** @typedef {import('@wordpress/blocks').WPBlock} WPBlock */
6052
6053 const EMPTY_ARRAY = [];
6054 /**
6055 * Internal dependencies
6056 */
6057
6058
6059 const entityContexts = { ...rootEntitiesConfig.reduce((acc, loader) => {
6060 if (!acc[loader.kind]) {
6061 acc[loader.kind] = {};
6062 }
6063
6064 acc[loader.kind][loader.name] = {
6065 context: (0,external_wp_element_namespaceObject.createContext)(undefined)
6066 };
6067 return acc;
6068 }, {}),
6069 ...additionalEntityConfigLoaders.reduce((acc, loader) => {
6070 acc[loader.kind] = {};
6071 return acc;
6072 }, {})
6073 };
6074
6075 const getEntityContext = (kind, name) => {
6076 if (!entityContexts[kind]) {
6077 throw new Error(`Missing entity config for kind: ${kind}.`);
6078 }
6079
6080 if (!entityContexts[kind][name]) {
6081 entityContexts[kind][name] = {
6082 context: (0,external_wp_element_namespaceObject.createContext)(undefined)
6083 };
6084 }
6085
6086 return entityContexts[kind][name].context;
6087 };
6088 /**
6089 * Context provider component for providing
6090 * an entity for a specific entity.
6091 *
6092 * @param {Object} props The component's props.
6093 * @param {string} props.kind The entity kind.
6094 * @param {string} props.type The entity name.
6095 * @param {number} props.id The entity ID.
6096 * @param {*} props.children The children to wrap.
6097 *
6098 * @return {Object} The provided children, wrapped with
6099 * the entity's context provider.
6100 */
6101
6102
6103 function EntityProvider(_ref) {
6104 let {
6105 kind,
6106 type: name,
6107 id,
6108 children
6109 } = _ref;
6110 const Provider = getEntityContext(kind, name).Provider;
6111 return (0,external_wp_element_namespaceObject.createElement)(Provider, {
6112 value: id
6113 }, children);
6114 }
6115 /**
6116 * Hook that returns the ID for the nearest
6117 * provided entity of the specified type.
6118 *
6119 * @param {string} kind The entity kind.
6120 * @param {string} name The entity name.
6121 */
6122
6123 function useEntityId(kind, name) {
6124 return (0,external_wp_element_namespaceObject.useContext)(getEntityContext(kind, name));
6125 }
6126 /**
6127 * Hook that returns the value and a setter for the
6128 * specified property of the nearest provided
6129 * entity of the specified type.
6130 *
6131 * @param {string} kind The entity kind.
6132 * @param {string} name The entity name.
6133 * @param {string} prop The property name.
6134 * @param {string} [_id] An entity ID to use instead of the context-provided one.
6135 *
6136 * @return {[*, Function, *]} An array where the first item is the
6137 * property value, the second is the
6138 * setter and the third is the full value
6139 * object from REST API containing more
6140 * information like `raw`, `rendered` and
6141 * `protected` props.
6142 */
6143
6144 function useEntityProp(kind, name, prop, _id) {
6145 const providerId = useEntityId(kind, name);
6146 const id = _id !== null && _id !== void 0 ? _id : providerId;
6147 const {
6148 value,
6149 fullValue
6150 } = (0,external_wp_data_namespaceObject.useSelect)(select => {
6151 const {
6152 getEntityRecord,
6153 getEditedEntityRecord
6154 } = select(STORE_NAME);
6155 const record = getEntityRecord(kind, name, id); // Trigger resolver.
6156
6157 const editedRecord = getEditedEntityRecord(kind, name, id);
6158 return record && editedRecord ? {
6159 value: editedRecord[prop],
6160 fullValue: record[prop]
6161 } : {};
6162 }, [kind, name, id, prop]);
6163 const {
6164 editEntityRecord
6165 } = (0,external_wp_data_namespaceObject.useDispatch)(STORE_NAME);
6166 const setValue = (0,external_wp_element_namespaceObject.useCallback)(newValue => {
6167 editEntityRecord(kind, name, id, {
6168 [prop]: newValue
6169 });
6170 }, [kind, name, id, prop]);
6171 return [value, setValue, fullValue];
6172 }
6173 /**
6174 * Hook that returns block content getters and setters for
6175 * the nearest provided entity of the specified type.
6176 *
6177 * The return value has the shape `[ blocks, onInput, onChange ]`.
6178 * `onInput` is for block changes that don't create undo levels
6179 * or dirty the post, non-persistent changes, and `onChange` is for
6180 * peristent changes. They map directly to the props of a
6181 * `BlockEditorProvider` and are intended to be used with it,
6182 * or similar components or hooks.
6183 *
6184 * @param {string} kind The entity kind.
6185 * @param {string} name The entity name.
6186 * @param {Object} options
6187 * @param {string} [options.id] An entity ID to use instead of the context-provided one.
6188 *
6189 * @return {[WPBlock[], Function, Function]} The block array and setters.
6190 */
6191
6192 function useEntityBlockEditor(kind, name) {
6193 let {
6194 id: _id
6195 } = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
6196 const providerId = useEntityId(kind, name);
6197 const id = _id !== null && _id !== void 0 ? _id : providerId;
6198 const {
6199 content,
6200 blocks
6201 } = (0,external_wp_data_namespaceObject.useSelect)(select => {
6202 const {
6203 getEditedEntityRecord
6204 } = select(STORE_NAME);
6205 const editedRecord = getEditedEntityRecord(kind, name, id);
6206 return {
6207 blocks: editedRecord.blocks,
6208 content: editedRecord.content
6209 };
6210 }, [kind, name, id]);
6211 const {
6212 __unstableCreateUndoLevel,
6213 editEntityRecord
6214 } = (0,external_wp_data_namespaceObject.useDispatch)(STORE_NAME);
6215 (0,external_wp_element_namespaceObject.useEffect)(() => {
6216 // Load the blocks from the content if not already in state
6217 // Guard against other instances that might have
6218 // set content to a function already or the blocks are already in state.
6219 if (content && typeof content !== 'function' && !blocks) {
6220 const parsedContent = (0,external_wp_blocks_namespaceObject.parse)(content);
6221 editEntityRecord(kind, name, id, {
6222 blocks: parsedContent
6223 }, {
6224 undoIgnore: true
6225 });
6226 }
6227 }, [content]);
6228 const onChange = (0,external_wp_element_namespaceObject.useCallback)((newBlocks, options) => {
6229 const {
6230 selection
6231 } = options;
6232 const edits = {
6233 blocks: newBlocks,
6234 selection
6235 };
6236 const noChange = blocks === edits.blocks;
6237
6238 if (noChange) {
6239 return __unstableCreateUndoLevel(kind, name, id);
6240 } // We create a new function here on every persistent edit
6241 // to make sure the edit makes the post dirty and creates
6242 // a new undo level.
6243
6244
6245 edits.content = _ref2 => {
6246 let {
6247 blocks: blocksForSerialization = []
6248 } = _ref2;
6249 return (0,external_wp_blocks_namespaceObject.__unstableSerializeAndClean)(blocksForSerialization);
6250 };
6251
6252 editEntityRecord(kind, name, id, edits);
6253 }, [kind, name, id, blocks]);
6254 const onInput = (0,external_wp_element_namespaceObject.useCallback)((newBlocks, options) => {
6255 const {
6256 selection
6257 } = options;
6258 const edits = {
6259 blocks: newBlocks,
6260 selection
6261 };
6262 editEntityRecord(kind, name, id, edits);
6263 }, [kind, name, id]);
6264 return [blocks !== null && blocks !== void 0 ? blocks : EMPTY_ARRAY, onInput, onChange];
6265 }
6266
6267 ;// CONCATENATED MODULE: external ["wp","htmlEntities"]
6268 var external_wp_htmlEntities_namespaceObject = window["wp"]["htmlEntities"];
6269 ;// CONCATENATED MODULE: ./packages/core-data/build-module/fetch/__experimental-fetch-link-suggestions.js
6270 /**
6271 * WordPress dependencies
6272 */
6273
6274
6275
6276
6277 /**
6278 * Filters the search by type
6279 *
6280 * @typedef { 'attachment' | 'post' | 'term' | 'post-format' } WPLinkSearchType
6281 */
6282
6283 /**
6284 * A link with an id may be of kind post-type or taxonomy
6285 *
6286 * @typedef { 'post-type' | 'taxonomy' } WPKind
6287 */
6288
6289 /**
6290 * @typedef WPLinkSearchOptions
6291 *
6292 * @property {boolean} [isInitialSuggestions] Displays initial search suggestions, when true.
6293 * @property {WPLinkSearchType} [type] Filters by search type.
6294 * @property {string} [subtype] Slug of the post-type or taxonomy.
6295 * @property {number} [page] Which page of results to return.
6296 * @property {number} [perPage] Search results per page.
6297 */
6298
6299 /**
6300 * @typedef WPLinkSearchResult
6301 *
6302 * @property {number} id Post or term id.
6303 * @property {string} url Link url.
6304 * @property {string} title Title of the link.
6305 * @property {string} type The taxonomy or post type slug or type URL.
6306 * @property {WPKind} [kind] Link kind of post-type or taxonomy
6307 */
6308
6309 /**
6310 * @typedef WPLinkSearchResultAugments
6311 *
6312 * @property {{kind: WPKind}} [meta] Contains kind information.
6313 * @property {WPKind} [subtype] Optional subtype if it exists.
6314 */
6315
6316 /**
6317 * @typedef {WPLinkSearchResult & WPLinkSearchResultAugments} WPLinkSearchResultAugmented
6318 */
6319
6320 /**
6321 * @typedef WPEditorSettings
6322 *
6323 * @property {boolean} [ disablePostFormats ] Disables post formats, when true.
6324 */
6325
6326 /**
6327 * Fetches link suggestions from the API.
6328 *
6329 * @async
6330 * @param {string} search
6331 * @param {WPLinkSearchOptions} [searchOptions]
6332 * @param {WPEditorSettings} [settings]
6333 *
6334 * @example
6335 * ```js
6336 * import { __experimentalFetchLinkSuggestions as fetchLinkSuggestions } from '@wordpress/core-data';
6337 *
6338 * //...
6339 *
6340 * export function initialize( id, settings ) {
6341 *
6342 * settings.__experimentalFetchLinkSuggestions = (
6343 * search,
6344 * searchOptions
6345 * ) => fetchLinkSuggestions( search, searchOptions, settings );
6346 * ```
6347 * @return {Promise< WPLinkSearchResult[] >} List of search suggestions
6348 */
6349
6350 const fetchLinkSuggestions = async function (search) {
6351 let searchOptions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
6352 let settings = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
6353 const {
6354 isInitialSuggestions = false,
6355 type = undefined,
6356 subtype = undefined,
6357 page = undefined,
6358 perPage = isInitialSuggestions ? 3 : 20
6359 } = searchOptions;
6360 const {
6361 disablePostFormats = false
6362 } = settings;
6363 /** @type {Promise<WPLinkSearchResult>[]} */
6364
6365 const queries = [];
6366
6367 if (!type || type === 'post') {
6368 queries.push(external_wp_apiFetch_default()({
6369 path: (0,external_wp_url_namespaceObject.addQueryArgs)('/wp/v2/search', {
6370 search,
6371 page,
6372 per_page: perPage,
6373 type: 'post',
6374 subtype
6375 })
6376 }).then(results => {
6377 return results.map(result => {
6378 return { ...result,
6379 meta: {
6380 kind: 'post-type',
6381 subtype
6382 }
6383 };
6384 });
6385 }).catch(() => []) // Fail by returning no results.
6386 );
6387 }
6388
6389 if (!type || type === 'term') {
6390 queries.push(external_wp_apiFetch_default()({
6391 path: (0,external_wp_url_namespaceObject.addQueryArgs)('/wp/v2/search', {
6392 search,
6393 page,
6394 per_page: perPage,
6395 type: 'term',
6396 subtype
6397 })
6398 }).then(results => {
6399 return results.map(result => {
6400 return { ...result,
6401 meta: {
6402 kind: 'taxonomy',
6403 subtype
6404 }
6405 };
6406 });
6407 }).catch(() => []) // Fail by returning no results.
6408 );
6409 }
6410
6411 if (!disablePostFormats && (!type || type === 'post-format')) {
6412 queries.push(external_wp_apiFetch_default()({
6413 path: (0,external_wp_url_namespaceObject.addQueryArgs)('/wp/v2/search', {
6414 search,
6415 page,
6416 per_page: perPage,
6417 type: 'post-format',
6418 subtype
6419 })
6420 }).then(results => {
6421 return results.map(result => {
6422 return { ...result,
6423 meta: {
6424 kind: 'taxonomy',
6425 subtype
6426 }
6427 };
6428 });
6429 }).catch(() => []) // Fail by returning no results.
6430 );
6431 }
6432
6433 if (!type || type === 'attachment') {
6434 queries.push(external_wp_apiFetch_default()({
6435 path: (0,external_wp_url_namespaceObject.addQueryArgs)('/wp/v2/media', {
6436 search,
6437 page,
6438 per_page: perPage
6439 })
6440 }).then(results => {
6441 return results.map(result => {
6442 return { ...result,
6443 meta: {
6444 kind: 'media'
6445 }
6446 };
6447 });
6448 }).catch(() => []) // Fail by returning no results.
6449 );
6450 }
6451
6452 return Promise.all(queries).then(results => {
6453 return results.reduce((
6454 /** @type {WPLinkSearchResult[]} */
6455 accumulator, current) => accumulator.concat(current), // Flatten list.
6456 []).filter(
6457 /**
6458 * @param {{ id: number }} result
6459 */
6460 result => {
6461 return !!result.id;
6462 }).slice(0, perPage).map((
6463 /** @type {WPLinkSearchResultAugmented} */
6464 result) => {
6465 var _result$meta;
6466
6467 const isMedia = result.type === 'attachment';
6468 return {
6469 id: result.id,
6470 // @ts-ignore fix when we make this a TS file
6471 url: isMedia ? result.source_url : result.url,
6472 title: (0,external_wp_htmlEntities_namespaceObject.decodeEntities)(isMedia ? // @ts-ignore fix when we make this a TS file
6473 result.title.rendered : result.title || '') || (0,external_wp_i18n_namespaceObject.__)('(no title)'),
6474 type: result.subtype || result.type,
6475 kind: result === null || result === void 0 ? void 0 : (_result$meta = result.meta) === null || _result$meta === void 0 ? void 0 : _result$meta.kind
6476 };
6477 });
6478 });
6479 };
6480
6481 /* harmony default export */ var _experimental_fetch_link_suggestions = (fetchLinkSuggestions);
6482
6483 ;// CONCATENATED MODULE: ./packages/core-data/build-module/fetch/__experimental-fetch-url-data.js
6484 /**
6485 * WordPress dependencies
6486 */
6487
6488
6489 /**
6490 * A simple in-memory cache for requests.
6491 * This avoids repeat HTTP requests which may be beneficial
6492 * for those wishing to preserve low-bandwidth.
6493 */
6494
6495 const CACHE = new Map();
6496 /**
6497 * @typedef WPRemoteUrlData
6498 *
6499 * @property {string} title contents of the remote URL's `<title>` tag.
6500 */
6501
6502 /**
6503 * Fetches data about a remote URL.
6504 * eg: <title> tag, favicon...etc.
6505 *
6506 * @async
6507 * @param {string} url the URL to request details from.
6508 * @param {Object?} options any options to pass to the underlying fetch.
6509 * @example
6510 * ```js
6511 * import { __experimentalFetchUrlData as fetchUrlData } from '@wordpress/core-data';
6512 *
6513 * //...
6514 *
6515 * export function initialize( id, settings ) {
6516 *
6517 * settings.__experimentalFetchUrlData = (
6518 * url
6519 * ) => fetchUrlData( url );
6520 * ```
6521 * @return {Promise< WPRemoteUrlData[] >} Remote URL data.
6522 */
6523
6524 const fetchUrlData = async function (url) {
6525 let options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
6526 const endpoint = '/wp-block-editor/v1/url-details';
6527 const args = {
6528 url: (0,external_wp_url_namespaceObject.prependHTTP)(url)
6529 };
6530
6531 if (!(0,external_wp_url_namespaceObject.isURL)(url)) {
6532 return Promise.reject(`${url} is not a valid URL.`);
6533 } // Test for "http" based URL as it is possible for valid
6534 // yet unusable URLs such as `tel:123456` to be passed.
6535
6536
6537 const protocol = (0,external_wp_url_namespaceObject.getProtocol)(url);
6538
6539 if (!protocol || !(0,external_wp_url_namespaceObject.isValidProtocol)(protocol) || !protocol.startsWith('http') || !/^https?:\/\/[^\/\s]/i.test(url)) {
6540 return Promise.reject(`${url} does not have a valid protocol. URLs must be "http" based`);
6541 }
6542
6543 if (CACHE.has(url)) {
6544 return CACHE.get(url);
6545 }
6546
6547 return external_wp_apiFetch_default()({
6548 path: (0,external_wp_url_namespaceObject.addQueryArgs)(endpoint, args),
6549 ...options
6550 }).then(res => {
6551 CACHE.set(url, res);
6552 return res;
6553 });
6554 };
6555
6556 /* harmony default export */ var _experimental_fetch_url_data = (fetchUrlData);
6557
6558 ;// CONCATENATED MODULE: ./packages/core-data/build-module/fetch/fetch-media.js
6559 /**
6560 * WordPress dependencies
6561 */
6562
6563 /**
6564 * Internal dependencies
6565 */
6566
6567
6568 async function fetchMedia() {
6569 let settings = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
6570 return (0,external_wp_data_namespaceObject.resolveSelect)(STORE_NAME).getMediaItems(settings);
6571 }
6572
6573 ;// CONCATENATED MODULE: ./packages/core-data/build-module/fetch/index.js
6574
6575
6576
6577
6578 // EXTERNAL MODULE: ./node_modules/memize/index.js
6579 var memize = __webpack_require__(9756);
6580 var memize_default = /*#__PURE__*/__webpack_require__.n(memize);
6581 ;// CONCATENATED MODULE: ./packages/core-data/build-module/hooks/memoize.js
6582 /**
6583 * External dependencies
6584 */
6585 // re-export due to restrictive esModuleInterop setting
6586
6587 /* harmony default export */ var memoize = ((memize_default()));
6588
6589 ;// CONCATENATED MODULE: ./packages/core-data/build-module/hooks/constants.js
6590 let Status;
6591
6592 (function (Status) {
6593 Status["Idle"] = "IDLE";
6594 Status["Resolving"] = "RESOLVING";
6595 Status["Error"] = "ERROR";
6596 Status["Success"] = "SUCCESS";
6597 })(Status || (Status = {}));
6598
6599 ;// CONCATENATED MODULE: ./packages/core-data/build-module/hooks/use-query-select.js
6600 /**
6601 * WordPress dependencies
6602 */
6603
6604 /**
6605 * Internal dependencies
6606 */
6607
6608
6609
6610 const META_SELECTORS = ['getIsResolving', 'hasStartedResolution', 'hasFinishedResolution', 'isResolving', 'getCachedResolvers'];
6611
6612 /**
6613 * Like useSelect, but the selectors return objects containing
6614 * both the original data AND the resolution info.
6615 *
6616 * @since 6.1.0 Introduced in WordPress core.
6617 * @private
6618 *
6619 * @param {Function} mapQuerySelect see useSelect
6620 * @param {Array} deps see useSelect
6621 *
6622 * @example
6623 * ```js
6624 * import { useQuerySelect } from '@wordpress/data';
6625 * import { store as coreDataStore } from '@wordpress/core-data';
6626 *
6627 * function PageTitleDisplay( { id } ) {
6628 * const { data: page, isResolving } = useQuerySelect( ( query ) => {
6629 * return query( coreDataStore ).getEntityRecord( 'postType', 'page', id )
6630 * }, [ id ] );
6631 *
6632 * if ( isResolving ) {
6633 * return 'Loading...';
6634 * }
6635 *
6636 * return page.title;
6637 * }
6638 *
6639 * // Rendered in the application:
6640 * // <PageTitleDisplay id={ 10 } />
6641 * ```
6642 *
6643 * In the above example, when `PageTitleDisplay` is rendered into an
6644 * application, the page and the resolution details will be retrieved from
6645 * the store state using the `mapSelect` callback on `useQuerySelect`.
6646 *
6647 * If the id prop changes then any page in the state for that id is
6648 * retrieved. If the id prop doesn't change and other props are passed in
6649 * that do change, the title will not change because the dependency is just
6650 * the id.
6651 * @see useSelect
6652 *
6653 * @return {QuerySelectResponse} Queried data.
6654 */
6655 function useQuerySelect(mapQuerySelect, deps) {
6656 return (0,external_wp_data_namespaceObject.useSelect)((select, registry) => {
6657 const resolve = store => enrichSelectors(select(store));
6658
6659 return mapQuerySelect(resolve, registry);
6660 }, deps);
6661 }
6662
6663 /**
6664 * Transform simple selectors into ones that return an object with the
6665 * original return value AND the resolution info.
6666 *
6667 * @param {Object} selectors Selectors to enrich
6668 * @return {EnrichedSelectors} Enriched selectors
6669 */
6670 const enrichSelectors = memoize(selectors => {
6671 const resolvers = {};
6672
6673 for (const selectorName in selectors) {
6674 if (META_SELECTORS.includes(selectorName)) {
6675 continue;
6676 }
6677
6678 Object.defineProperty(resolvers, selectorName, {
6679 get: () => function () {
6680 const {
6681 getIsResolving,
6682 hasFinishedResolution
6683 } = selectors;
6684
6685 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
6686 args[_key] = arguments[_key];
6687 }
6688
6689 const isResolving = !!getIsResolving(selectorName, args);
6690 const hasResolved = !isResolving && hasFinishedResolution(selectorName, args);
6691 const data = selectors[selectorName](...args);
6692 let status;
6693
6694 if (isResolving) {
6695 status = Status.Resolving;
6696 } else if (hasResolved) {
6697 if (data) {
6698 status = Status.Success;
6699 } else {
6700 status = Status.Error;
6701 }
6702 } else {
6703 status = Status.Idle;
6704 }
6705
6706 return {
6707 data,
6708 status,
6709 isResolving,
6710 hasResolved
6711 };
6712 }
6713 });
6714 }
6715
6716 return resolvers;
6717 });
6718
6719 ;// CONCATENATED MODULE: ./packages/core-data/build-module/hooks/use-entity-record.js
6720 /**
6721 * WordPress dependencies
6722 */
6723
6724
6725
6726 /**
6727 * Internal dependencies
6728 */
6729
6730
6731
6732
6733 /**
6734 * Resolves the specified entity record.
6735 *
6736 * @since 6.1.0 Introduced in WordPress core.
6737 *
6738 * @param kind Kind of the entity, e.g. `root` or a `postType`. See rootEntitiesConfig in ../entities.ts for a list of available kinds.
6739 * @param name Name of the entity, e.g. `plugin` or a `post`. See rootEntitiesConfig in ../entities.ts for a list of available names.
6740 * @param recordId ID of the requested entity record.
6741 * @param options Optional hook options.
6742 * @example
6743 * ```js
6744 * import { useEntityRecord } from '@wordpress/core-data';
6745 *
6746 * function PageTitleDisplay( { id } ) {
6747 * const { record, isResolving } = useEntityRecord( 'postType', 'page', id );
6748 *
6749 * if ( isResolving ) {
6750 * return 'Loading...';
6751 * }
6752 *
6753 * return record.title;
6754 * }
6755 *
6756 * // Rendered in the application:
6757 * // <PageTitleDisplay id={ 1 } />
6758 * ```
6759 *
6760 * In the above example, when `PageTitleDisplay` is rendered into an
6761 * application, the page and the resolution details will be retrieved from
6762 * the store state using `getEntityRecord()`, or resolved if missing.
6763 *
6764 * @example
6765 * ```js
6766 * import { useDispatch } from '@wordpress/data';
6767 * import { useCallback } from '@wordpress/element';
6768 * import { __ } from '@wordpress/i18n';
6769 * import { TextControl } from '@wordpress/components';
6770 * import { store as noticeStore } from '@wordpress/notices';
6771 * import { useEntityRecord } from '@wordpress/core-data';
6772 *
6773 * function PageRenameForm( { id } ) {
6774 * const page = useEntityRecord( 'postType', 'page', id );
6775 * const { createSuccessNotice, createErrorNotice } =
6776 * useDispatch( noticeStore );
6777 *
6778 * const setTitle = useCallback( ( title ) => {
6779 * page.edit( { title } );
6780 * }, [ page.edit ] );
6781 *
6782 * if ( page.isResolving ) {
6783 * return 'Loading...';
6784 * }
6785 *
6786 * async function onRename( event ) {
6787 * event.preventDefault();
6788 * try {
6789 * await page.save();
6790 * createSuccessNotice( __( 'Page renamed.' ), {
6791 * type: 'snackbar',
6792 * } );
6793 * } catch ( error ) {
6794 * createErrorNotice( error.message, { type: 'snackbar' } );
6795 * }
6796 * }
6797 *
6798 * return (
6799 * <form onSubmit={ onRename }>
6800 * <TextControl
6801 * label={ __( 'Name' ) }
6802 * value={ page.editedRecord.title }
6803 * onChange={ setTitle }
6804 * />
6805 * <button type="submit">{ __( 'Save' ) }</button>
6806 * </form>
6807 * );
6808 * }
6809 *
6810 * // Rendered in the application:
6811 * // <PageRenameForm id={ 1 } />
6812 * ```
6813 *
6814 * In the above example, updating and saving the page title is handled
6815 * via the `edit()` and `save()` mutation helpers provided by
6816 * `useEntityRecord()`;
6817 *
6818 * @return Entity record data.
6819 * @template RecordType
6820 */
6821 function useEntityRecord(kind, name, recordId) {
6822 let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {
6823 enabled: true
6824 };
6825 const {
6826 editEntityRecord,
6827 saveEditedEntityRecord
6828 } = (0,external_wp_data_namespaceObject.useDispatch)(store);
6829 const mutations = (0,external_wp_element_namespaceObject.useMemo)(() => ({
6830 edit: record => editEntityRecord(kind, name, recordId, record),
6831 save: function () {
6832 let saveOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
6833 return saveEditedEntityRecord(kind, name, recordId, {
6834 throwOnError: true,
6835 ...saveOptions
6836 });
6837 }
6838 }), [recordId]);
6839 const {
6840 editedRecord,
6841 hasEdits
6842 } = (0,external_wp_data_namespaceObject.useSelect)(select => ({
6843 editedRecord: select(store).getEditedEntityRecord(kind, name, recordId),
6844 hasEdits: select(store).hasEditsForEntityRecord(kind, name, recordId)
6845 }), [kind, name, recordId]);
6846 const {
6847 data: record,
6848 ...querySelectRest
6849 } = useQuerySelect(query => {
6850 if (!options.enabled) {
6851 return null;
6852 }
6853
6854 return query(store).getEntityRecord(kind, name, recordId);
6855 }, [kind, name, recordId, options.enabled]);
6856 return {
6857 record,
6858 editedRecord,
6859 hasEdits,
6860 ...querySelectRest,
6861 ...mutations
6862 };
6863 }
6864 function __experimentalUseEntityRecord(kind, name, recordId, options) {
6865 external_wp_deprecated_default()(`wp.data.__experimentalUseEntityRecord`, {
6866 alternative: 'wp.data.useEntityRecord',
6867 since: '6.1'
6868 });
6869 return useEntityRecord(kind, name, recordId, options);
6870 }
6871
6872 ;// CONCATENATED MODULE: ./packages/core-data/build-module/hooks/use-entity-records.js
6873 /**
6874 * WordPress dependencies
6875 */
6876
6877
6878 /**
6879 * Internal dependencies
6880 */
6881
6882
6883
6884 const use_entity_records_EMPTY_ARRAY = [];
6885 /**
6886 * Resolves the specified entity records.
6887 *
6888 * @since 6.1.0 Introduced in WordPress core.
6889 *
6890 * @param kind Kind of the entity, e.g. `root` or a `postType`. See rootEntitiesConfig in ../entities.ts for a list of available kinds.
6891 * @param name Name of the entity, e.g. `plugin` or a `post`. See rootEntitiesConfig in ../entities.ts for a list of available names.
6892 * @param queryArgs Optional HTTP query description for how to fetch the data, passed to the requested API endpoint.
6893 * @param options Optional hook options.
6894 * @example
6895 * ```js
6896 * import { useEntityRecord } from '@wordpress/core-data';
6897 *
6898 * function PageTitlesList() {
6899 * const { records, isResolving } = useEntityRecords( 'postType', 'page' );
6900 *
6901 * if ( isResolving ) {
6902 * return 'Loading...';
6903 * }
6904 *
6905 * return (
6906 * <ul>
6907 * {records.map(( page ) => (
6908 * <li>{ page.title }</li>
6909 * ))}
6910 * </ul>
6911 * );
6912 * }
6913 *
6914 * // Rendered in the application:
6915 * // <PageTitlesList />
6916 * ```
6917 *
6918 * In the above example, when `PageTitlesList` is rendered into an
6919 * application, the list of records and the resolution details will be retrieved from
6920 * the store state using `getEntityRecords()`, or resolved if missing.
6921 *
6922 * @return Entity records data.
6923 * @template RecordType
6924 */
6925
6926 function useEntityRecords(kind, name) {
6927 let queryArgs = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
6928 let options = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {
6929 enabled: true
6930 };
6931 // Serialize queryArgs to a string that can be safely used as a React dep.
6932 // We can't just pass queryArgs as one of the deps, because if it is passed
6933 // as an object literal, then it will be a different object on each call even
6934 // if the values remain the same.
6935 const queryAsString = (0,external_wp_url_namespaceObject.addQueryArgs)('', queryArgs);
6936 const {
6937 data: records,
6938 ...rest
6939 } = useQuerySelect(query => {
6940 if (!options.enabled) {
6941 return {
6942 // Avoiding returning a new reference on every execution.
6943 data: use_entity_records_EMPTY_ARRAY
6944 };
6945 }
6946
6947 return query(store).getEntityRecords(kind, name, queryArgs);
6948 }, [kind, name, queryAsString, options.enabled]);
6949 return {
6950 records,
6951 ...rest
6952 };
6953 }
6954 function __experimentalUseEntityRecords(kind, name, queryArgs, options) {
6955 external_wp_deprecated_default()(`wp.data.__experimentalUseEntityRecords`, {
6956 alternative: 'wp.data.useEntityRecords',
6957 since: '6.1'
6958 });
6959 return useEntityRecords(kind, name, queryArgs, options);
6960 }
6961
6962 ;// CONCATENATED MODULE: ./packages/core-data/build-module/hooks/use-resource-permissions.js
6963 /**
6964 * WordPress dependencies
6965 */
6966
6967 /**
6968 * Internal dependencies
6969 */
6970
6971
6972
6973
6974
6975 /**
6976 * Resolves resource permissions.
6977 *
6978 * @since 6.1.0 Introduced in WordPress core.
6979 *
6980 * @param resource The resource in question, e.g. media.
6981 * @param id ID of a specific resource entry, if needed, e.g. 10.
6982 *
6983 * @example
6984 * ```js
6985 * import { useResourcePermissions } from '@wordpress/core-data';
6986 *
6987 * function PagesList() {
6988 * const { canCreate, isResolving } = useResourcePermissions( 'pages' );
6989 *
6990 * if ( isResolving ) {
6991 * return 'Loading ...';
6992 * }
6993 *
6994 * return (
6995 * <div>
6996 * {canCreate ? (<button>+ Create a new page</button>) : false}
6997 * // ...
6998 * </div>
6999 * );
7000 * }
7001 *
7002 * // Rendered in the application:
7003 * // <PagesList />
7004 * ```
7005 *
7006 * @example
7007 * ```js
7008 * import { useResourcePermissions } from '@wordpress/core-data';
7009 *
7010 * function Page({ pageId }) {
7011 * const {
7012 * canCreate,
7013 * canUpdate,
7014 * canDelete,
7015 * isResolving
7016 * } = useResourcePermissions( 'pages', pageId );
7017 *
7018 * if ( isResolving ) {
7019 * return 'Loading ...';
7020 * }
7021 *
7022 * return (
7023 * <div>
7024 * {canCreate ? (<button>+ Create a new page</button>) : false}
7025 * {canUpdate ? (<button>Edit page</button>) : false}
7026 * {canDelete ? (<button>Delete page</button>) : false}
7027 * // ...
7028 * </div>
7029 * );
7030 * }
7031 *
7032 * // Rendered in the application:
7033 * // <Page pageId={ 15 } />
7034 * ```
7035 *
7036 * In the above example, when `PagesList` is rendered into an
7037 * application, the appropriate permissions and the resolution details will be retrieved from
7038 * the store state using `canUser()`, or resolved if missing.
7039 *
7040 * @return Entity records data.
7041 * @template IdType
7042 */
7043 function useResourcePermissions(resource, id) {
7044 return useQuerySelect(resolve => {
7045 const {
7046 canUser
7047 } = resolve(store);
7048 const create = canUser('create', resource);
7049
7050 if (!id) {
7051 const read = canUser('read', resource);
7052 const isResolving = create.isResolving || read.isResolving;
7053 const hasResolved = create.hasResolved && read.hasResolved;
7054 let status = Status.Idle;
7055
7056 if (isResolving) {
7057 status = Status.Resolving;
7058 } else if (hasResolved) {
7059 status = Status.Success;
7060 }
7061
7062 return {
7063 status,
7064 isResolving,
7065 hasResolved,
7066 canCreate: create.hasResolved && create.data,
7067 canRead: read.hasResolved && read.data
7068 };
7069 }
7070
7071 const read = canUser('read', resource, id);
7072 const update = canUser('update', resource, id);
7073
7074 const _delete = canUser('delete', resource, id);
7075
7076 const isResolving = read.isResolving || create.isResolving || update.isResolving || _delete.isResolving;
7077 const hasResolved = read.hasResolved && create.hasResolved && update.hasResolved && _delete.hasResolved;
7078 let status = Status.Idle;
7079
7080 if (isResolving) {
7081 status = Status.Resolving;
7082 } else if (hasResolved) {
7083 status = Status.Success;
7084 }
7085
7086 return {
7087 status,
7088 isResolving,
7089 hasResolved,
7090 canRead: hasResolved && read.data,
7091 canCreate: hasResolved && create.data,
7092 canUpdate: hasResolved && update.data,
7093 canDelete: hasResolved && _delete.data
7094 };
7095 }, [resource, id]);
7096 }
7097 function __experimentalUseResourcePermissions(resource, id) {
7098 external_wp_deprecated_default()(`wp.data.__experimentalUseResourcePermissions`, {
7099 alternative: 'wp.data.useResourcePermissions',
7100 since: '6.1'
7101 });
7102 return useResourcePermissions(resource, id);
7103 }
7104
7105 ;// CONCATENATED MODULE: ./packages/core-data/build-module/hooks/index.js
7106
7107
7108
7109
7110 ;// CONCATENATED MODULE: ./packages/core-data/build-module/index.js
7111 /**
7112 * WordPress dependencies
7113 */
7114
7115 /**
7116 * Internal dependencies
7117 */
7118
7119
7120
7121
7122
7123
7124
7125 // The entity selectors/resolvers and actions are shortcuts to their generic equivalents
7126 // (getEntityRecord, getEntityRecords, updateEntityRecord, updateEntityRecords)
7127 // Instead of getEntityRecord, the consumer could use more user-friendly named selector: getPostType, getTaxonomy...
7128 // The "kind" and the "name" of the entity are combined to generate these shortcuts.
7129
7130 const entitySelectors = rootEntitiesConfig.reduce((result, entity) => {
7131 const {
7132 kind,
7133 name
7134 } = entity;
7135
7136 result[getMethodName(kind, name)] = (state, key, query) => getEntityRecord(state, kind, name, key, query);
7137
7138 result[getMethodName(kind, name, 'get', true)] = (state, query) => getEntityRecords(state, kind, name, query);
7139
7140 return result;
7141 }, {});
7142 const entityResolvers = rootEntitiesConfig.reduce((result, entity) => {
7143 const {
7144 kind,
7145 name
7146 } = entity;
7147
7148 result[getMethodName(kind, name)] = (key, query) => resolvers_getEntityRecord(kind, name, key, query);
7149
7150 const pluralMethodName = getMethodName(kind, name, 'get', true);
7151
7152 result[pluralMethodName] = function () {
7153 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
7154 args[_key] = arguments[_key];
7155 }
7156
7157 return resolvers_getEntityRecords(kind, name, ...args);
7158 };
7159
7160 result[pluralMethodName].shouldInvalidate = action => resolvers_getEntityRecords.shouldInvalidate(action, kind, name);
7161
7162 return result;
7163 }, {});
7164 const entityActions = rootEntitiesConfig.reduce((result, entity) => {
7165 const {
7166 kind,
7167 name
7168 } = entity;
7169
7170 result[getMethodName(kind, name, 'save')] = key => saveEntityRecord(kind, name, key);
7171
7172 result[getMethodName(kind, name, 'delete')] = (key, query) => deleteEntityRecord(kind, name, key, query);
7173
7174 return result;
7175 }, {});
7176
7177 const storeConfig = () => ({
7178 reducer: build_module_reducer,
7179 actions: { ...build_module_actions_namespaceObject,
7180 ...entityActions,
7181 ...createLocksActions()
7182 },
7183 selectors: { ...build_module_selectors_namespaceObject,
7184 ...entitySelectors
7185 },
7186 resolvers: { ...resolvers_namespaceObject,
7187 ...entityResolvers
7188 }
7189 });
7190 /**
7191 * Store definition for the code data namespace.
7192 *
7193 * @see https://github.com/WordPress/gutenberg/blob/HEAD/packages/data/README.md#createReduxStore
7194 */
7195
7196
7197 const store = (0,external_wp_data_namespaceObject.createReduxStore)(STORE_NAME, storeConfig());
7198 (0,external_wp_data_namespaceObject.register)(store);
7199
7200
7201
7202
7203
7204
7205 }();
7206 (window.wp = window.wp || {}).coreData = __webpack_exports__;
7207 /******/ })()
7208 ;