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

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

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