PluginProbe
Gutenberg / 23.4.0
Gutenberg v23.4.0
23.9.1 23.9.0 23.8.0 23.7.2 23.7.1 23.7.0 23.6.1 23.6.2 23.6.0 23.5.3 23.5.2 23.5.1 23.5.0 23.4.0 23.3.2 23.3.1 23.3.0 23.2.0 23.2.1 23.2.2 23.1.1 23.1.0 23.0.1 12.6.0 7.4.0 All 402 releases
gutenberg / build / scripts / core-data / index.js

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

8,202 lines 269.2 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 "use strict";
2 var wp;
3 (wp ||= {}).coreData = (() => {
4 var __create = Object.create;
5 var __defProp = Object.defineProperty;
6 var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7 var __getOwnPropNames = Object.getOwnPropertyNames;
8 var __getProtoOf = Object.getPrototypeOf;
9 var __hasOwnProp = Object.prototype.hasOwnProperty;
10 var __commonJS = (cb, mod) => function __require() {
11 return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
12 };
13 var __export = (target, all) => {
14 for (var name in all)
15 __defProp(target, name, { get: all[name], enumerable: true });
16 };
17 var __copyProps = (to, from, except, desc) => {
18 if (from && typeof from === "object" || typeof from === "function") {
19 for (let key of __getOwnPropNames(from))
20 if (!__hasOwnProp.call(to, key) && key !== except)
21 __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
22 }
23 return to;
24 };
25 var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
26 // If the importer is in node compatibility mode or this is not an ESM
27 // file that has been converted to a CommonJS file using a Babel-
28 // compatible transform (i.e. "__esModule" has not been set), then set
29 // "default" to the CommonJS "module.exports" for node compatibility.
30 isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
31 mod
32 ));
33 var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
34
35 // package-external:@wordpress/data
36 var require_data = __commonJS({
37 "package-external:@wordpress/data"(exports, module) {
38 module.exports = window.wp.data;
39 }
40 });
41
42 // node_modules/fast-deep-equal/es6/index.js
43 var require_es6 = __commonJS({
44 "node_modules/fast-deep-equal/es6/index.js"(exports, module) {
45 "use strict";
46 module.exports = function equal(a, b) {
47 if (a === b) return true;
48 if (a && b && typeof a == "object" && typeof b == "object") {
49 if (a.constructor !== b.constructor) return false;
50 var length, i, keys;
51 if (Array.isArray(a)) {
52 length = a.length;
53 if (length != b.length) return false;
54 for (i = length; i-- !== 0; )
55 if (!equal(a[i], b[i])) return false;
56 return true;
57 }
58 if (a instanceof Map && b instanceof Map) {
59 if (a.size !== b.size) return false;
60 for (i of a.entries())
61 if (!b.has(i[0])) return false;
62 for (i of a.entries())
63 if (!equal(i[1], b.get(i[0]))) return false;
64 return true;
65 }
66 if (a instanceof Set && b instanceof Set) {
67 if (a.size !== b.size) return false;
68 for (i of a.entries())
69 if (!b.has(i[0])) return false;
70 return true;
71 }
72 if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
73 length = a.length;
74 if (length != b.length) return false;
75 for (i = length; i-- !== 0; )
76 if (a[i] !== b[i]) return false;
77 return true;
78 }
79 if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
80 if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
81 if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
82 keys = Object.keys(a);
83 length = keys.length;
84 if (length !== Object.keys(b).length) return false;
85 for (i = length; i-- !== 0; )
86 if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
87 for (i = length; i-- !== 0; ) {
88 var key = keys[i];
89 if (!equal(a[key], b[key])) return false;
90 }
91 return true;
92 }
93 return a !== a && b !== b;
94 };
95 }
96 });
97
98 // package-external:@wordpress/compose
99 var require_compose = __commonJS({
100 "package-external:@wordpress/compose"(exports, module) {
101 module.exports = window.wp.compose;
102 }
103 });
104
105 // package-external:@wordpress/undo-manager
106 var require_undo_manager = __commonJS({
107 "package-external:@wordpress/undo-manager"(exports, module) {
108 module.exports = window.wp.undoManager;
109 }
110 });
111
112 // package-external:@wordpress/api-fetch
113 var require_api_fetch = __commonJS({
114 "package-external:@wordpress/api-fetch"(exports, module) {
115 module.exports = window.wp.apiFetch;
116 }
117 });
118
119 // package-external:@wordpress/sync
120 var require_sync = __commonJS({
121 "package-external:@wordpress/sync"(exports, module) {
122 module.exports = window.wp.sync;
123 }
124 });
125
126 // package-external:@wordpress/private-apis
127 var require_private_apis = __commonJS({
128 "package-external:@wordpress/private-apis"(exports, module) {
129 module.exports = window.wp.privateApis;
130 }
131 });
132
133 // node_modules/equivalent-key-map/equivalent-key-map.js
134 var require_equivalent_key_map = __commonJS({
135 "node_modules/equivalent-key-map/equivalent-key-map.js"(exports, module) {
136 "use strict";
137 function _typeof(obj) {
138 if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
139 _typeof = function(obj2) {
140 return typeof obj2;
141 };
142 } else {
143 _typeof = function(obj2) {
144 return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
145 };
146 }
147 return _typeof(obj);
148 }
149 function _classCallCheck(instance, Constructor) {
150 if (!(instance instanceof Constructor)) {
151 throw new TypeError("Cannot call a class as a function");
152 }
153 }
154 function _defineProperties(target, props) {
155 for (var i = 0; i < props.length; i++) {
156 var descriptor = props[i];
157 descriptor.enumerable = descriptor.enumerable || false;
158 descriptor.configurable = true;
159 if ("value" in descriptor) descriptor.writable = true;
160 Object.defineProperty(target, descriptor.key, descriptor);
161 }
162 }
163 function _createClass(Constructor, protoProps, staticProps) {
164 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
165 if (staticProps) _defineProperties(Constructor, staticProps);
166 return Constructor;
167 }
168 function getValuePair(instance, key) {
169 var _map = instance._map, _arrayTreeMap = instance._arrayTreeMap, _objectTreeMap = instance._objectTreeMap;
170 if (_map.has(key)) {
171 return _map.get(key);
172 }
173 var properties = Object.keys(key).sort();
174 var map = Array.isArray(key) ? _arrayTreeMap : _objectTreeMap;
175 for (var i = 0; i < properties.length; i++) {
176 var property = properties[i];
177 map = map.get(property);
178 if (map === void 0) {
179 return;
180 }
181 var propertyValue = key[property];
182 map = map.get(propertyValue);
183 if (map === void 0) {
184 return;
185 }
186 }
187 var valuePair = map.get("_ekm_value");
188 if (!valuePair) {
189 return;
190 }
191 _map.delete(valuePair[0]);
192 valuePair[0] = key;
193 map.set("_ekm_value", valuePair);
194 _map.set(key, valuePair);
195 return valuePair;
196 }
197 var EquivalentKeyMap2 = /* @__PURE__ */ (function() {
198 function EquivalentKeyMap3(iterable) {
199 _classCallCheck(this, EquivalentKeyMap3);
200 this.clear();
201 if (iterable instanceof EquivalentKeyMap3) {
202 var iterablePairs = [];
203 iterable.forEach(function(value, key) {
204 iterablePairs.push([key, value]);
205 });
206 iterable = iterablePairs;
207 }
208 if (iterable != null) {
209 for (var i = 0; i < iterable.length; i++) {
210 this.set(iterable[i][0], iterable[i][1]);
211 }
212 }
213 }
214 _createClass(EquivalentKeyMap3, [{
215 key: "set",
216 /**
217 * Add or update an element with a specified key and value.
218 *
219 * @param {*} key The key of the element to add.
220 * @param {*} value The value of the element to add.
221 *
222 * @return {EquivalentKeyMap} Map instance.
223 */
224 value: function set(key, value) {
225 if (key === null || _typeof(key) !== "object") {
226 this._map.set(key, value);
227 return this;
228 }
229 var properties = Object.keys(key).sort();
230 var valuePair = [key, value];
231 var map = Array.isArray(key) ? this._arrayTreeMap : this._objectTreeMap;
232 for (var i = 0; i < properties.length; i++) {
233 var property = properties[i];
234 if (!map.has(property)) {
235 map.set(property, new EquivalentKeyMap3());
236 }
237 map = map.get(property);
238 var propertyValue = key[property];
239 if (!map.has(propertyValue)) {
240 map.set(propertyValue, new EquivalentKeyMap3());
241 }
242 map = map.get(propertyValue);
243 }
244 var previousValuePair = map.get("_ekm_value");
245 if (previousValuePair) {
246 this._map.delete(previousValuePair[0]);
247 }
248 map.set("_ekm_value", valuePair);
249 this._map.set(key, valuePair);
250 return this;
251 }
252 /**
253 * Returns a specified element.
254 *
255 * @param {*} key The key of the element to return.
256 *
257 * @return {?*} The element associated with the specified key or undefined
258 * if the key can't be found.
259 */
260 }, {
261 key: "get",
262 value: function get(key) {
263 if (key === null || _typeof(key) !== "object") {
264 return this._map.get(key);
265 }
266 var valuePair = getValuePair(this, key);
267 if (valuePair) {
268 return valuePair[1];
269 }
270 }
271 /**
272 * Returns a boolean indicating whether an element with the specified key
273 * exists or not.
274 *
275 * @param {*} key The key of the element to test for presence.
276 *
277 * @return {boolean} Whether an element with the specified key exists.
278 */
279 }, {
280 key: "has",
281 value: function has(key) {
282 if (key === null || _typeof(key) !== "object") {
283 return this._map.has(key);
284 }
285 return getValuePair(this, key) !== void 0;
286 }
287 /**
288 * Removes the specified element.
289 *
290 * @param {*} key The key of the element to remove.
291 *
292 * @return {boolean} Returns true if an element existed and has been
293 * removed, or false if the element does not exist.
294 */
295 }, {
296 key: "delete",
297 value: function _delete(key) {
298 if (!this.has(key)) {
299 return false;
300 }
301 this.set(key, void 0);
302 return true;
303 }
304 /**
305 * Executes a provided function once per each key/value pair, in insertion
306 * order.
307 *
308 * @param {Function} callback Function to execute for each element.
309 * @param {*} thisArg Value to use as `this` when executing
310 * `callback`.
311 */
312 }, {
313 key: "forEach",
314 value: function forEach(callback) {
315 var _this = this;
316 var thisArg = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : this;
317 this._map.forEach(function(value, key) {
318 if (key !== null && _typeof(key) === "object") {
319 value = value[1];
320 }
321 callback.call(thisArg, value, key, _this);
322 });
323 }
324 /**
325 * Removes all elements.
326 */
327 }, {
328 key: "clear",
329 value: function clear() {
330 this._map = /* @__PURE__ */ new Map();
331 this._arrayTreeMap = /* @__PURE__ */ new Map();
332 this._objectTreeMap = /* @__PURE__ */ new Map();
333 }
334 }, {
335 key: "size",
336 get: function get() {
337 return this._map.size;
338 }
339 }]);
340 return EquivalentKeyMap3;
341 })();
342 module.exports = EquivalentKeyMap2;
343 }
344 });
345
346 // package-external:@wordpress/url
347 var require_url = __commonJS({
348 "package-external:@wordpress/url"(exports, module) {
349 module.exports = window.wp.url;
350 }
351 });
352
353 // package-external:@wordpress/blocks
354 var require_blocks = __commonJS({
355 "package-external:@wordpress/blocks"(exports, module) {
356 module.exports = window.wp.blocks;
357 }
358 });
359
360 // package-external:@wordpress/i18n
361 var require_i18n = __commonJS({
362 "package-external:@wordpress/i18n"(exports, module) {
363 module.exports = window.wp.i18n;
364 }
365 });
366
367 // package-external:@wordpress/block-editor
368 var require_block_editor = __commonJS({
369 "package-external:@wordpress/block-editor"(exports, module) {
370 module.exports = window.wp.blockEditor;
371 }
372 });
373
374 // package-external:@wordpress/rich-text
375 var require_rich_text = __commonJS({
376 "package-external:@wordpress/rich-text"(exports, module) {
377 module.exports = window.wp.richText;
378 }
379 });
380
381 // package-external:@wordpress/deprecated
382 var require_deprecated = __commonJS({
383 "package-external:@wordpress/deprecated"(exports, module) {
384 module.exports = window.wp.deprecated;
385 }
386 });
387
388 // package-external:@wordpress/html-entities
389 var require_html_entities = __commonJS({
390 "package-external:@wordpress/html-entities"(exports, module) {
391 module.exports = window.wp.htmlEntities;
392 }
393 });
394
395 // package-external:@wordpress/element
396 var require_element = __commonJS({
397 "package-external:@wordpress/element"(exports, module) {
398 module.exports = window.wp.element;
399 }
400 });
401
402 // vendor-external:react/jsx-runtime
403 var require_jsx_runtime = __commonJS({
404 "vendor-external:react/jsx-runtime"(exports, module) {
405 module.exports = window.ReactJSXRuntime;
406 }
407 });
408
409 // package-external:@wordpress/warning
410 var require_warning = __commonJS({
411 "package-external:@wordpress/warning"(exports, module) {
412 module.exports = window.wp.warning;
413 }
414 });
415
416 // packages/core-data/build-module/index.mjs
417 var index_exports = {};
418 __export(index_exports, {
419 EntityProvider: () => EntityProvider,
420 __experimentalFetchLinkSuggestions: () => fetchLinkSuggestions,
421 __experimentalFetchUrlData: () => experimental_fetch_url_data_default,
422 __experimentalUseEntityRecord: () => useDeprecatedEntityRecord,
423 __experimentalUseEntityRecords: () => useDeprecatedEntityRecords,
424 __experimentalUseResourcePermissions: () => useDeprecatedResourcePermissions,
425 fetchBlockPatterns: () => fetchBlockPatterns,
426 privateApis: () => privateApis,
427 store: () => store,
428 useEntityBlockEditor: () => useEntityBlockEditor,
429 useEntityId: () => useEntityId,
430 useEntityProp: () => useEntityProp,
431 useEntityRecord: () => useEntityRecord,
432 useEntityRecords: () => useEntityRecords,
433 useResourcePermissions: () => use_resource_permissions_default
434 });
435 var import_data15 = __toESM(require_data(), 1);
436
437 // packages/core-data/build-module/reducer.mjs
438 var import_es64 = __toESM(require_es6(), 1);
439 var import_compose2 = __toESM(require_compose(), 1);
440 var import_data7 = __toESM(require_data(), 1);
441 var import_undo_manager = __toESM(require_undo_manager(), 1);
442
443 // packages/core-data/build-module/utils/conservative-map-item.mjs
444 var import_es6 = __toESM(require_es6(), 1);
445 function conservativeMapItem(item, nextItem) {
446 if (!item) {
447 return nextItem;
448 }
449 let hasChanges = false;
450 const result = {};
451 for (const key in nextItem) {
452 if ((0, import_es6.default)(item[key], nextItem[key])) {
453 result[key] = item[key];
454 } else {
455 hasChanges = true;
456 result[key] = nextItem[key];
457 }
458 }
459 if (!hasChanges) {
460 return item;
461 }
462 for (const key in item) {
463 if (!result.hasOwnProperty(key)) {
464 result[key] = item[key];
465 }
466 }
467 return result;
468 }
469
470 // packages/core-data/build-module/utils/get-normalized-comma-separable.mjs
471 function getNormalizedCommaSeparable(value) {
472 if (typeof value === "string") {
473 return value.split(",");
474 } else if (Array.isArray(value)) {
475 return value;
476 }
477 return null;
478 }
479 var get_normalized_comma_separable_default = getNormalizedCommaSeparable;
480
481 // packages/core-data/build-module/utils/if-matching-action.mjs
482 var ifMatchingAction = (isMatch) => (reducer) => (state, action) => {
483 if (state === void 0 || isMatch(action)) {
484 return reducer(state, action);
485 }
486 return state;
487 };
488 var if_matching_action_default = ifMatchingAction;
489
490 // packages/core-data/build-module/utils/forward-resolver.mjs
491 var forwardResolver = (resolverName) => (...args) => async ({ resolveSelect: resolveSelect2 }) => {
492 await resolveSelect2[resolverName](...args);
493 };
494 var forward_resolver_default = forwardResolver;
495
496 // packages/core-data/build-module/utils/replace-action.mjs
497 var replaceAction = (replacer) => (reducer) => (state, action) => {
498 return reducer(state, replacer(action));
499 };
500 var replace_action_default = replaceAction;
501
502 // packages/core-data/build-module/utils/with-weak-map-cache.mjs
503 function withWeakMapCache(fn) {
504 const cache3 = /* @__PURE__ */ new WeakMap();
505 return (key) => {
506 let value;
507 if (cache3.has(key)) {
508 value = cache3.get(key);
509 } else {
510 value = fn(key);
511 if (key !== null && typeof key === "object") {
512 cache3.set(key, value);
513 }
514 }
515 return value;
516 };
517 }
518 var with_weak_map_cache_default = withWeakMapCache;
519
520 // packages/core-data/build-module/utils/set-nested-value.mjs
521 function setNestedValue(object, path, value) {
522 if (!object || typeof object !== "object") {
523 return object;
524 }
525 const normalizedPath = Array.isArray(path) ? path : path.split(".");
526 normalizedPath.reduce((acc, key, idx) => {
527 if (acc[key] === void 0) {
528 if (Number.isInteger(normalizedPath[idx + 1])) {
529 acc[key] = [];
530 } else {
531 acc[key] = {};
532 }
533 }
534 if (idx === normalizedPath.length - 1) {
535 acc[key] = value;
536 }
537 return acc[key];
538 }, object);
539 return object;
540 }
541
542 // packages/core-data/build-module/utils/get-nested-value.mjs
543 function getNestedValue(object, path, defaultValue) {
544 if (!object || typeof object !== "object" || typeof path !== "string" && !Array.isArray(path)) {
545 return object;
546 }
547 const normalizedPath = Array.isArray(path) ? path : path.split(".");
548 let value = object;
549 normalizedPath.forEach((fieldName) => {
550 value = value?.[fieldName];
551 });
552 return value !== void 0 ? value : defaultValue;
553 }
554
555 // packages/core-data/build-module/utils/is-numeric-id.mjs
556 function isNumericID(id) {
557 return /^\s*\d+\s*$/.test(id);
558 }
559
560 // packages/core-data/build-module/utils/user-permissions.mjs
561 var ALLOWED_RESOURCE_ACTIONS = [
562 "create",
563 "read",
564 "update",
565 "delete"
566 ];
567 function getUserPermissionsFromAllowHeader(allowedMethods) {
568 const permissions = {};
569 const methods = {
570 create: "POST",
571 read: "GET",
572 update: "PUT",
573 delete: "DELETE"
574 };
575 for (const [actionName, methodName] of Object.entries(methods)) {
576 permissions[actionName] = allowedMethods ? allowedMethods.includes(methodName) : false;
577 }
578 return permissions;
579 }
580 function getUserPermissionCacheKey(action, resource, id) {
581 const key = (typeof resource === "object" ? [action, resource.kind, resource.name, resource.id] : [action, resource, id]).filter(Boolean).join("/");
582 return key;
583 }
584
585 // packages/core-data/build-module/utils/receive-intermediate-results.mjs
586 var RECEIVE_INTERMEDIATE_RESULTS = /* @__PURE__ */ Symbol(
587 "RECEIVE_INTERMEDIATE_RESULTS"
588 );
589
590 // packages/core-data/build-module/utils/normalize-query-for-resolution.mjs
591 function normalizeQueryForResolution(query) {
592 if (!query) {
593 return void 0;
594 }
595 const entries = Object.entries(query).filter(
596 ([k, v]) => (k === "context" || k === "_fields") && v !== void 0 && v !== null
597 );
598 return entries.length > 0 ? Object.fromEntries(entries) : void 0;
599 }
600
601 // packages/core-data/build-module/utils/save-crdt-doc.mjs
602 var import_api_fetch = __toESM(require_api_fetch(), 1);
603
604 // packages/core-data/build-module/sync.mjs
605 var import_sync = __toESM(require_sync(), 1);
606
607 // packages/core-data/build-module/lock-unlock.mjs
608 var import_private_apis = __toESM(require_private_apis(), 1);
609 var { lock, unlock } = (0, import_private_apis.__dangerousOptInToUnstableAPIsOnlyForCoreModules)(
610 "I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.",
611 "@wordpress/core-data"
612 );
613
614 // packages/core-data/build-module/sync.mjs
615 var {
616 ConnectionErrorCode,
617 createSyncManager,
618 Delta,
619 CRDT_DOC_META_PERSISTENCE_KEY,
620 CRDT_RECORD_MAP_KEY,
621 LOCAL_EDITOR_ORIGIN,
622 LOCAL_UNDO_IGNORED_ORIGIN,
623 retrySyncConnection
624 } = unlock(import_sync.privateApis);
625 var syncManager;
626 function getSyncManager() {
627 if (syncManager) {
628 return syncManager;
629 }
630 syncManager = createSyncManager();
631 return syncManager;
632 }
633 function hasSyncManager() {
634 return Boolean(syncManager);
635 }
636
637 // packages/core-data/build-module/utils/save-crdt-doc.mjs
638 var SYNC_SAVE_API_PATH = "/wp-sync/v1/save";
639 var saveCRDTDocQueues = /* @__PURE__ */ new Map();
640 async function serializeAndSaveCRDTDoc(objectType, objectId, room) {
641 const serializedDoc = await getSyncManager()?.createPersistedCRDTDoc(
642 objectType,
643 objectId
644 );
645 if (!serializedDoc) {
646 return;
647 }
648 await (0, import_api_fetch.default)({
649 path: SYNC_SAVE_API_PATH,
650 method: "POST",
651 data: {
652 room,
653 doc: serializedDoc
654 }
655 });
656 }
657 async function saveCRDTDoc(objectType, objectId) {
658 const room = `${objectType}:${objectId}`;
659 const previousSave = saveCRDTDocQueues.get(room) || Promise.resolve();
660 const currentSave = previousSave.catch(() => {
661 }).then(() => serializeAndSaveCRDTDoc(objectType, objectId, room));
662 saveCRDTDocQueues.set(room, currentSave);
663 try {
664 await currentSave;
665 } finally {
666 if (saveCRDTDocQueues.get(room) === currentSave) {
667 saveCRDTDocQueues.delete(room);
668 }
669 }
670 }
671
672 // packages/core-data/build-module/queried-data/actions.mjs
673 function receiveItems(items2, edits, meta) {
674 return {
675 type: "RECEIVE_ITEMS",
676 items: items2,
677 persistedEdits: edits,
678 meta
679 };
680 }
681 function removeItems(kind, name, records, invalidateCache = false) {
682 return {
683 type: "REMOVE_ITEMS",
684 itemIds: Array.isArray(records) ? records : [records],
685 kind,
686 name,
687 invalidateCache
688 };
689 }
690 function receiveQueriedItems(items2, query = {}, edits, meta) {
691 return {
692 ...receiveItems(items2, edits, meta),
693 query
694 };
695 }
696
697 // packages/core-data/build-module/queried-data/selectors.mjs
698 var import_equivalent_key_map = __toESM(require_equivalent_key_map(), 1);
699
700 // packages/core-data/build-module/queried-data/get-query-parts.mjs
701 var import_url = __toESM(require_url(), 1);
702 function getQueryParts(query) {
703 const parts = {
704 stableKey: "",
705 page: 1,
706 perPage: 10,
707 offset: null,
708 fields: null,
709 include: null,
710 context: "default"
711 };
712 const keys = Object.keys(query).sort();
713 for (let i = 0; i < keys.length; i++) {
714 const key = keys[i];
715 let value = query[key];
716 switch (key) {
717 case "page":
718 parts[key] = Number(value);
719 break;
720 case "per_page":
721 parts.perPage = Number(value);
722 break;
723 case "offset": {
724 const numericOffset = Number(value);
725 if (Number.isFinite(numericOffset)) {
726 parts.offset = numericOffset;
727 }
728 break;
729 }
730 case "context":
731 parts.context = value;
732 break;
733 default:
734 if (key === "_fields") {
735 parts.fields = get_normalized_comma_separable_default(value) ?? [];
736 value = parts.fields.join();
737 }
738 if (key === "include") {
739 if (typeof value === "number") {
740 value = value.toString();
741 }
742 parts.include = (get_normalized_comma_separable_default(value) ?? []).map(Number);
743 value = parts.include.join();
744 }
745 parts.stableKey += (parts.stableKey ? "&" : "") + (0, import_url.addQueryArgs)("", { [key]: value }).slice(1);
746 }
747 }
748 return parts;
749 }
750 var get_query_parts_default = with_weak_map_cache_default(getQueryParts);
751
752 // packages/core-data/build-module/queried-data/selectors.mjs
753 var queriedItemsCacheByState = /* @__PURE__ */ new WeakMap();
754 function getQueriedItemsUncached(state, query, options = {}) {
755 const { supportsPagination = true } = options;
756 const {
757 stableKey,
758 page,
759 perPage,
760 offset: queryOffset,
761 include,
762 fields,
763 context
764 } = get_query_parts_default(query);
765 const itemIds = state.queries?.[context]?.[stableKey]?.itemIds;
766 if (!itemIds) {
767 return null;
768 }
769 const isPaginated = supportsPagination && perPage !== -1;
770 const startOffset = isPaginated ? queryOffset ?? (page - 1) * perPage : 0;
771 const endOffset = isPaginated ? Math.min(startOffset + perPage, itemIds.length) : itemIds.length;
772 if (isPaginated && itemIds.length < startOffset + perPage) {
773 const totalItems = state.queries[context][stableKey].meta?.totalItems;
774 if (Number.isFinite(totalItems) && itemIds.length < totalItems) {
775 return null;
776 }
777 }
778 const items2 = [];
779 for (let i = startOffset; i < endOffset; i++) {
780 const itemId = itemIds[i];
781 if (Array.isArray(include) && !include.includes(itemId)) {
782 continue;
783 }
784 if (itemId === void 0) {
785 continue;
786 }
787 if (!state.items[context]?.hasOwnProperty(itemId)) {
788 return null;
789 }
790 const item = state.items[context][itemId];
791 let filteredItem;
792 if (Array.isArray(fields)) {
793 filteredItem = {};
794 for (let f = 0; f < fields.length; f++) {
795 const field = fields[f].split(".");
796 let value = item;
797 field.forEach((fieldName) => {
798 value = value?.[fieldName];
799 });
800 setNestedValue(filteredItem, field, value);
801 }
802 } else {
803 if (!state.itemIsComplete[context]?.[itemId]) {
804 return null;
805 }
806 filteredItem = item;
807 }
808 items2.push(filteredItem);
809 }
810 return items2;
811 }
812 function getQueriedItems(state, query = {}, options = {}) {
813 let queriedItemsCache = queriedItemsCacheByState.get(state);
814 if (queriedItemsCache) {
815 const queriedItems = queriedItemsCache.get(query);
816 if (queriedItems !== void 0) {
817 return queriedItems;
818 }
819 } else {
820 queriedItemsCache = new import_equivalent_key_map.default();
821 queriedItemsCacheByState.set(state, queriedItemsCache);
822 }
823 const items2 = getQueriedItemsUncached(state, query, options);
824 queriedItemsCache.set(query, items2);
825 return items2;
826 }
827 function getQueriedTotalItems(state, query = {}) {
828 const { stableKey, context } = get_query_parts_default(query);
829 return state.queries?.[context]?.[stableKey]?.meta?.totalItems ?? null;
830 }
831 function getQueriedTotalPages(state, query = {}) {
832 const { stableKey, context } = get_query_parts_default(query);
833 return state.queries?.[context]?.[stableKey]?.meta?.totalPages ?? null;
834 }
835
836 // packages/core-data/build-module/queried-data/reducer.mjs
837 var import_data6 = __toESM(require_data(), 1);
838 var import_compose = __toESM(require_compose(), 1);
839
840 // node_modules/tslib/tslib.es6.mjs
841 var __assign = function() {
842 __assign = Object.assign || function __assign2(t) {
843 for (var s, i = 1, n = arguments.length; i < n; i++) {
844 s = arguments[i];
845 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
846 }
847 return t;
848 };
849 return __assign.apply(this, arguments);
850 };
851
852 // node_modules/lower-case/dist.es2015/index.js
853 function lowerCase(str) {
854 return str.toLowerCase();
855 }
856
857 // node_modules/no-case/dist.es2015/index.js
858 var DEFAULT_SPLIT_REGEXP = [/([a-z0-9])([A-Z])/g, /([A-Z])([A-Z][a-z])/g];
859 var DEFAULT_STRIP_REGEXP = /[^A-Z0-9]+/gi;
860 function noCase(input, options) {
861 if (options === void 0) {
862 options = {};
863 }
864 var _a = options.splitRegexp, splitRegexp = _a === void 0 ? DEFAULT_SPLIT_REGEXP : _a, _b = options.stripRegexp, stripRegexp = _b === void 0 ? DEFAULT_STRIP_REGEXP : _b, _c = options.transform, transform = _c === void 0 ? lowerCase : _c, _d = options.delimiter, delimiter = _d === void 0 ? " " : _d;
865 var result = replace(replace(input, splitRegexp, "$1\0$2"), stripRegexp, "\0");
866 var start = 0;
867 var end = result.length;
868 while (result.charAt(start) === "\0")
869 start++;
870 while (result.charAt(end - 1) === "\0")
871 end--;
872 return result.slice(start, end).split("\0").map(transform).join(delimiter);
873 }
874 function replace(input, re, value) {
875 if (re instanceof RegExp)
876 return input.replace(re, value);
877 return re.reduce(function(input2, re2) {
878 return input2.replace(re2, value);
879 }, input);
880 }
881
882 // node_modules/pascal-case/dist.es2015/index.js
883 function pascalCaseTransform(input, index) {
884 var firstChar = input.charAt(0);
885 var lowerChars = input.substr(1).toLowerCase();
886 if (index > 0 && firstChar >= "0" && firstChar <= "9") {
887 return "_" + firstChar + lowerChars;
888 }
889 return "" + firstChar.toUpperCase() + lowerChars;
890 }
891 function pascalCase(input, options) {
892 if (options === void 0) {
893 options = {};
894 }
895 return noCase(input, __assign({ delimiter: "", transform: pascalCaseTransform }, options));
896 }
897
898 // node_modules/camel-case/dist.es2015/index.js
899 function camelCaseTransform(input, index) {
900 if (index === 0)
901 return input.toLowerCase();
902 return pascalCaseTransform(input, index);
903 }
904 function camelCase(input, options) {
905 if (options === void 0) {
906 options = {};
907 }
908 return pascalCase(input, __assign({ transform: camelCaseTransform }, options));
909 }
910
911 // node_modules/upper-case-first/dist.es2015/index.js
912 function upperCaseFirst(input) {
913 return input.charAt(0).toUpperCase() + input.substr(1);
914 }
915
916 // node_modules/capital-case/dist.es2015/index.js
917 function capitalCaseTransform(input) {
918 return upperCaseFirst(input.toLowerCase());
919 }
920 function capitalCase(input, options) {
921 if (options === void 0) {
922 options = {};
923 }
924 return noCase(input, __assign({ delimiter: " ", transform: capitalCaseTransform }, options));
925 }
926
927 // packages/core-data/build-module/entities.mjs
928 var import_api_fetch2 = __toESM(require_api_fetch(), 1);
929 var import_blocks4 = __toESM(require_blocks(), 1);
930 var import_i18n = __toESM(require_i18n(), 1);
931
932 // packages/core-data/build-module/awareness/post-editor-awareness.mjs
933 var import_data4 = __toESM(require_data(), 1);
934 var import_sync9 = __toESM(require_sync(), 1);
935 var import_block_editor3 = __toESM(require_block_editor(), 1);
936
937 // packages/core-data/build-module/awareness/base-awareness.mjs
938 var import_data = __toESM(require_data(), 1);
939
940 // packages/core-data/build-module/awareness/config.mjs
941 var AWARENESS_CURSOR_UPDATE_THROTTLE_IN_MS = 100;
942 var LOCAL_CURSOR_UPDATE_DEBOUNCE_IN_MS = 5;
943 var REMOVAL_DELAY_IN_MS = 5e3;
944
945 // packages/core-data/build-module/awareness/typed-awareness.mjs
946 var import_sync3 = __toESM(require_sync(), 1);
947
948 // packages/core-data/build-module/awareness/utils.mjs
949 function getBrowserName() {
950 const userAgent = window.navigator.userAgent;
951 let browserName = "Unknown";
952 if (userAgent.includes("Firefox")) {
953 browserName = "Firefox";
954 } else if (userAgent.includes("Edg")) {
955 browserName = "Microsoft Edge";
956 } else if (userAgent.includes("Chrome") && !userAgent.includes("Edg")) {
957 browserName = "Chrome";
958 } else if (userAgent.includes("Safari") && !userAgent.includes("Chrome")) {
959 browserName = "Safari";
960 } else if (userAgent.includes("MSIE") || userAgent.includes("Trident")) {
961 browserName = "Internet Explorer";
962 } else if (userAgent.includes("Opera") || userAgent.includes("OPR")) {
963 browserName = "Opera";
964 }
965 return browserName;
966 }
967 function areMapsEqual(map1, map2, comparatorFn) {
968 if (map1.size !== map2.size) {
969 return false;
970 }
971 for (const [key, value1] of map1.entries()) {
972 if (!map2.has(key)) {
973 return false;
974 }
975 if (!comparatorFn(value1, map2.get(key))) {
976 return false;
977 }
978 }
979 return true;
980 }
981 function areCollaboratorInfosEqual(collaboratorInfo1, collaboratorInfo2) {
982 if (!collaboratorInfo1 || !collaboratorInfo2) {
983 return collaboratorInfo1 === collaboratorInfo2;
984 }
985 if (Object.keys(collaboratorInfo1).length !== Object.keys(collaboratorInfo2).length) {
986 return false;
987 }
988 return Object.entries(collaboratorInfo1).every(([key, value]) => {
989 return value === collaboratorInfo2[key];
990 });
991 }
992 function generateCollaboratorInfo(currentCollaborator) {
993 const { avatar_urls, id, name, slug } = currentCollaborator;
994 return {
995 avatar_urls,
996 // eslint-disable-line camelcase
997 browserType: getBrowserName(),
998 enteredAt: Date.now(),
999 id,
1000 name,
1001 slug
1002 };
1003 }
1004 function getRecordValue(obj, key) {
1005 if ("object" === typeof obj && null !== obj && key in obj) {
1006 return obj[key];
1007 }
1008 return null;
1009 }
1010 function getTypedKeys(obj) {
1011 return Object.keys(obj);
1012 }
1013
1014 // packages/core-data/build-module/awareness/typed-awareness.mjs
1015 var TypedAwareness = class extends import_sync3.Awareness {
1016 /**
1017 * Get the states from an awareness document.
1018 */
1019 getStates() {
1020 return super.getStates();
1021 }
1022 /**
1023 * Get a local state field from an awareness document.
1024 * @param field
1025 */
1026 getLocalStateField(field) {
1027 const state = this.getLocalState();
1028 return getRecordValue(state, field);
1029 }
1030 /**
1031 * Set a local state field on an awareness document.
1032 * @param field
1033 * @param value
1034 */
1035 setLocalStateField(field, value) {
1036 super.setLocalStateField(field, value);
1037 }
1038 };
1039
1040 // packages/core-data/build-module/awareness/awareness-state.mjs
1041 var AwarenessWithEqualityChecks = class extends TypedAwareness {
1042 /** OVERRIDDEN METHODS */
1043 /**
1044 * Set a local state field on an awareness document. Calling this method may
1045 * trigger rerenders of any subscribed components.
1046 *
1047 * Equality checks are provided by the abstract `equalityFieldChecks` property.
1048 * @param field - The field to set.
1049 * @param value - The value to set.
1050 */
1051 setLocalStateField(field, value) {
1052 if (this.isFieldEqual(
1053 field,
1054 value,
1055 this.getLocalStateField(field) ?? void 0
1056 )) {
1057 return;
1058 }
1059 super.setLocalStateField(field, value);
1060 }
1061 /** CUSTOM METHODS */
1062 /**
1063 * Determine if a field value has changed using the provided equality checks.
1064 * @param field - The field to check.
1065 * @param value1 - The first value to compare.
1066 * @param value2 - The second value to compare.
1067 */
1068 isFieldEqual(field, value1, value2) {
1069 if (["clientId", "isConnected", "isMe"].includes(field)) {
1070 return value1 === value2;
1071 }
1072 if (field in this.equalityFieldChecks) {
1073 const fn = this.equalityFieldChecks[field];
1074 return fn(value1, value2);
1075 }
1076 throw new Error(
1077 `No equality check implemented for awareness state field "${field.toString()}".`
1078 );
1079 }
1080 /**
1081 * Determine if two states are equal by comparing each field using the
1082 * provided equality checks.
1083 * @param state1 - The first state to compare.
1084 * @param state2 - The second state to compare.
1085 */
1086 isStateEqual(state1, state2) {
1087 return [
1088 .../* @__PURE__ */ new Set([
1089 ...getTypedKeys(state1),
1090 ...getTypedKeys(state2)
1091 ])
1092 ].every((field) => {
1093 const value1 = state1[field];
1094 const value2 = state2[field];
1095 return this.isFieldEqual(field, value1, value2);
1096 });
1097 }
1098 };
1099 var AwarenessState = class extends AwarenessWithEqualityChecks {
1100 /** CUSTOM PROPERTIES */
1101 /**
1102 * Whether the setUp method has been called, to avoid running it multiple
1103 * times.
1104 */
1105 hasSetupRun = false;
1106 /**
1107 * We keep track of all seen states during the current session for two reasons:
1108 *
1109 * 1. So that we can represent recently disconnected collaborators in our UI, even
1110 * after they have been removed from the awareness document.
1111 * 2. So that we can provide debug information about all collaborators seen during
1112 * the session.
1113 */
1114 disconnectedCollaborators = /* @__PURE__ */ new Set();
1115 seenStates = /* @__PURE__ */ new Map();
1116 /**
1117 * Hold a snapshot of the previous awareness state allows us to compare the
1118 * state values and avoid unnecessary updates to subscribers.
1119 */
1120 previousSnapshot = /* @__PURE__ */ new Map();
1121 stateSubscriptions = [];
1122 /**
1123 * In some cases, we may want to throttle setting local state fields to avoid
1124 * overwhelming the awareness document with rapid updates. At the same time, we
1125 * want to ensure that when we read our own state locally, we get the latest
1126 * value -- even if it hasn't yet been set on the awareness instance.
1127 */
1128 myThrottledState = {};
1129 throttleTimeouts = /* @__PURE__ */ new Map();
1130 /** CUSTOM METHODS */
1131 /**
1132 * Set up the awareness state. This method is idempotent and will only run
1133 * once. Subclasses should override `onSetUp()` instead of this method to
1134 * add their own setup logic.
1135 *
1136 * This is defined as a readonly arrow function property to prevent
1137 * subclasses from overriding it.
1138 */
1139 setUp = () => {
1140 if (this.hasSetupRun) {
1141 return;
1142 }
1143 this.hasSetupRun = true;
1144 this.onSetUp();
1145 this.on(
1146 "change",
1147 ({ added, removed, updated }) => {
1148 [...added, ...updated].forEach((id) => {
1149 this.disconnectedCollaborators.delete(id);
1150 });
1151 removed.forEach((id) => {
1152 this.disconnectedCollaborators.add(id);
1153 setTimeout(() => {
1154 this.disconnectedCollaborators.delete(id);
1155 this.updateSubscribers(
1156 true
1157 /* force update */
1158 );
1159 }, REMOVAL_DELAY_IN_MS);
1160 });
1161 this.updateSubscribers();
1162 }
1163 );
1164 };
1165 /**
1166 * Get the most recent state from the last processed change event.
1167 *
1168 * @return An array of EnhancedState< State >.
1169 */
1170 getCurrentState() {
1171 return Array.from(this.previousSnapshot.values());
1172 }
1173 /**
1174 * Get all seen states in this session to enable debug reporting.
1175 */
1176 getSeenStates() {
1177 return this.seenStates;
1178 }
1179 /**
1180 * Allow external code to subscribe to awareness state changes.
1181 * @param callback - The callback to subscribe to.
1182 */
1183 onStateChange(callback) {
1184 this.stateSubscriptions.push(callback);
1185 return () => {
1186 this.stateSubscriptions = this.stateSubscriptions.filter(
1187 (cb) => cb !== callback
1188 );
1189 };
1190 }
1191 /**
1192 * Set a local state field on an awareness document with throttle. See caveats
1193 * of this.setLocalStateField.
1194 * @param field - The field to set.
1195 * @param value - The value to set.
1196 * @param wait - The wait time in milliseconds.
1197 */
1198 setThrottledLocalStateField(field, value, wait) {
1199 this.setLocalStateField(field, value);
1200 this.throttleTimeouts.set(
1201 field,
1202 setTimeout(() => {
1203 this.throttleTimeouts.delete(field);
1204 if (this.myThrottledState[field]) {
1205 this.setLocalStateField(
1206 field,
1207 this.myThrottledState[field]
1208 );
1209 delete this.myThrottledState[field];
1210 }
1211 }, wait)
1212 );
1213 }
1214 /**
1215 * Set the current collaborator's connection status as awareness state.
1216 * @param isConnected - The connection status.
1217 */
1218 setConnectionStatus(isConnected) {
1219 if (isConnected) {
1220 this.disconnectedCollaborators.delete(this.clientID);
1221 } else {
1222 this.disconnectedCollaborators.add(this.clientID);
1223 }
1224 this.updateSubscribers(
1225 true
1226 /* force update */
1227 );
1228 }
1229 /**
1230 * Update all subscribed listeners with the latest awareness state.
1231 * @param forceUpdate - Whether to force an update.
1232 */
1233 updateSubscribers(forceUpdate = false) {
1234 if (!this.stateSubscriptions.length) {
1235 return;
1236 }
1237 const states = this.getStates();
1238 this.seenStates = new Map([
1239 ...this.seenStates.entries(),
1240 ...states.entries()
1241 ]);
1242 const updatedStates = new Map(
1243 [...this.disconnectedCollaborators, ...states.keys()].filter((clientId) => {
1244 return Object.keys(this.seenStates.get(clientId) ?? {}).length > 0;
1245 }).map((clientId) => {
1246 const rawState = this.seenStates.get(clientId);
1247 const isConnected = !this.disconnectedCollaborators.has(clientId);
1248 const isMe = clientId === this.clientID;
1249 const myState = isMe ? this.myThrottledState : {};
1250 const state = {
1251 ...rawState,
1252 ...myState,
1253 clientId,
1254 isConnected,
1255 isMe
1256 };
1257 return [clientId, state];
1258 })
1259 );
1260 if (!forceUpdate) {
1261 if (areMapsEqual(
1262 this.previousSnapshot,
1263 updatedStates,
1264 this.isStateEqual.bind(this)
1265 )) {
1266 return;
1267 }
1268 }
1269 this.previousSnapshot = updatedStates;
1270 this.stateSubscriptions.forEach((callback) => {
1271 callback(Array.from(updatedStates.values()));
1272 });
1273 }
1274 };
1275
1276 // packages/core-data/build-module/name.mjs
1277 var STORE_NAME = "core";
1278
1279 // packages/core-data/build-module/awareness/base-awareness.mjs
1280 var BaseAwarenessState = class extends AwarenessState {
1281 onSetUp() {
1282 void this.setCurrentCollaboratorInfo();
1283 }
1284 /**
1285 * Set the current collaborator info in the local state.
1286 */
1287 async setCurrentCollaboratorInfo() {
1288 const currentUser2 = await (0, import_data.resolveSelect)(STORE_NAME).getCurrentUser();
1289 const collaboratorInfo = generateCollaboratorInfo(currentUser2);
1290 this.setLocalStateField("collaboratorInfo", collaboratorInfo);
1291 }
1292 };
1293 var baseEqualityFieldChecks = {
1294 collaboratorInfo: areCollaboratorInfosEqual
1295 };
1296 var BaseAwareness = class extends BaseAwarenessState {
1297 equalityFieldChecks = baseEqualityFieldChecks;
1298 };
1299
1300 // packages/core-data/build-module/awareness/block-lookup.mjs
1301 var import_data2 = __toESM(require_data(), 1);
1302 var import_sync4 = __toESM(require_sync(), 1);
1303 var import_block_editor = __toESM(require_block_editor(), 1);
1304 function getContainingBlockYMap(yType) {
1305 let current = yType;
1306 while (current) {
1307 const parent = current.parent;
1308 if (parent instanceof import_sync4.Y.Map && parent.parent instanceof import_sync4.Y.Array && parent.get("clientId") !== void 0 && parent.get("innerBlocks") instanceof import_sync4.Y.Array) {
1309 return parent;
1310 }
1311 current = parent instanceof import_sync4.Y.AbstractType ? parent : null;
1312 }
1313 return null;
1314 }
1315 function getBlockPathInYdoc(yType) {
1316 const path = [];
1317 let current = yType;
1318 while (current) {
1319 const parentArray = current.parent;
1320 if (!parentArray || !(parentArray instanceof import_sync4.Y.Array)) {
1321 return null;
1322 }
1323 let index = -1;
1324 for (let i = 0; i < parentArray.length; i++) {
1325 if (parentArray.get(i) === current) {
1326 index = i;
1327 break;
1328 }
1329 }
1330 if (index === -1) {
1331 return null;
1332 }
1333 path.unshift(index);
1334 const grandparent = parentArray.parent;
1335 if (grandparent instanceof import_sync4.Y.Map && grandparent.get("clientId") !== void 0) {
1336 current = grandparent;
1337 } else {
1338 break;
1339 }
1340 }
1341 return path;
1342 }
1343 function resolveBlockClientIdByPath(path, blocks) {
1344 if (path.length === 0) {
1345 return null;
1346 }
1347 for (let i = 0; i < path.length; i++) {
1348 const block = blocks[path[i]];
1349 if (!block) {
1350 return null;
1351 }
1352 if (i === path.length - 1) {
1353 return block.clientId;
1354 }
1355 blocks = block.innerBlocks;
1356 }
1357 return null;
1358 }
1359 function usePostContentBlocks() {
1360 return (0, import_data2.useSelect)((select4) => {
1361 const { getBlocksByName, getClientIdsTree } = unlock(
1362 select4(import_block_editor.store)
1363 );
1364 const [postContentClientId] = getBlocksByName("core/post-content");
1365 return getClientIdsTree(postContentClientId ?? "");
1366 }, []);
1367 }
1368
1369 // packages/core-data/build-module/utils/crdt-utils.mjs
1370 var import_sync5 = __toESM(require_sync(), 1);
1371 var import_rich_text = __toESM(require_rich_text(), 1);
1372 function getRootMap(doc, key) {
1373 return doc.getMap(key);
1374 }
1375 function createYMap(partial = {}) {
1376 return new import_sync5.Y.Map(Object.entries(partial));
1377 }
1378 function isYMap(value) {
1379 return value instanceof import_sync5.Y.Map;
1380 }
1381 function asRichTextOffset(offset) {
1382 return offset;
1383 }
1384 function asHtmlStringIndex(index) {
1385 return index;
1386 }
1387 function getYTextByAttributeKey(attributes, attributeKey) {
1388 const directValue = attributes.get(attributeKey);
1389 if (directValue instanceof import_sync5.Y.Text) {
1390 return directValue;
1391 }
1392 let value = attributes;
1393 for (const pathPart of attributeKey.split(".")) {
1394 if (value instanceof import_sync5.Y.Map) {
1395 value = value.get(pathPart);
1396 } else if (value instanceof import_sync5.Y.Array) {
1397 const index = Number.parseInt(pathPart, 10);
1398 if (!Number.isSafeInteger(index) || index < 0 || index.toString() !== pathPart) {
1399 return null;
1400 }
1401 value = value.get(index);
1402 } else {
1403 return null;
1404 }
1405 }
1406 return value instanceof import_sync5.Y.Text ? value : null;
1407 }
1408 function findBlockByClientIdInDoc(blockId, ydoc) {
1409 const ymap = getRootMap(ydoc, CRDT_RECORD_MAP_KEY);
1410 const blocks = ymap.get("blocks");
1411 if (!(blocks instanceof import_sync5.Y.Array)) {
1412 return null;
1413 }
1414 return findBlockByClientIdInBlocks(blockId, blocks);
1415 }
1416 var MARKER_START = 57344;
1417 function pickMarker(text) {
1418 const tryCount = 16;
1419 for (let code = MARKER_START; code < MARKER_START + tryCount; code++) {
1420 const candidate = String.fromCharCode(code);
1421 if (!text.includes(candidate)) {
1422 return candidate;
1423 }
1424 }
1425 return null;
1426 }
1427 function htmlIndexToRichTextOffset(html, htmlIndex) {
1428 if (!html.includes("<") && !html.includes("&")) {
1429 return asRichTextOffset(htmlIndex);
1430 }
1431 const marker = pickMarker(html);
1432 if (!marker) {
1433 return asRichTextOffset(htmlIndex);
1434 }
1435 const withMarker = html.slice(0, htmlIndex) + marker + html.slice(htmlIndex);
1436 const value = (0, import_rich_text.create)({ html: withMarker });
1437 const markerPos = value.text.indexOf(marker);
1438 return asRichTextOffset(markerPos === -1 ? htmlIndex : markerPos);
1439 }
1440 function richTextOffsetToHtmlIndex(html, richTextOffset) {
1441 if (!html.includes("<") && !html.includes("&")) {
1442 return asHtmlStringIndex(richTextOffset);
1443 }
1444 const marker = pickMarker(html);
1445 if (!marker) {
1446 return asHtmlStringIndex(richTextOffset);
1447 }
1448 const value = (0, import_rich_text.create)({ html });
1449 const markerValue = (0, import_rich_text.create)({ text: marker });
1450 if (value.formats[richTextOffset]) {
1451 markerValue.formats[0] = value.formats[richTextOffset];
1452 }
1453 const withMarker = (0, import_rich_text.insert)(
1454 value,
1455 markerValue,
1456 richTextOffset,
1457 richTextOffset
1458 );
1459 const htmlWithMarker = (0, import_rich_text.toHTMLString)({ value: withMarker });
1460 const markerIndex = htmlWithMarker.indexOf(marker);
1461 return asHtmlStringIndex(
1462 markerIndex === -1 ? richTextOffset : markerIndex
1463 );
1464 }
1465 function findBlockByClientIdInBlocks(blockId, blocks) {
1466 for (const block of blocks) {
1467 if (block.get("clientId") === blockId) {
1468 return block;
1469 }
1470 const innerBlocks = block.get("innerBlocks");
1471 if (innerBlocks && innerBlocks.length > 0) {
1472 const innerBlock = findBlockByClientIdInBlocks(
1473 blockId,
1474 innerBlocks
1475 );
1476 if (innerBlock) {
1477 return innerBlock;
1478 }
1479 }
1480 }
1481 return null;
1482 }
1483
1484 // packages/core-data/build-module/utils/crdt-user-selections.mjs
1485 var import_data3 = __toESM(require_data(), 1);
1486 var import_sync7 = __toESM(require_sync(), 1);
1487 var import_block_editor2 = __toESM(require_block_editor(), 1);
1488 var SelectionType = /* @__PURE__ */ ((SelectionType2) => {
1489 SelectionType2["None"] = "none";
1490 SelectionType2["Cursor"] = "cursor";
1491 SelectionType2["SelectionInOneBlock"] = "selection-in-one-block";
1492 SelectionType2["SelectionInMultipleBlocks"] = "selection-in-multiple-blocks";
1493 SelectionType2["WholeBlock"] = "whole-block";
1494 return SelectionType2;
1495 })(SelectionType || {});
1496 var SelectionDirection = /* @__PURE__ */ ((SelectionDirection2) => {
1497 SelectionDirection2["Forward"] = "f";
1498 SelectionDirection2["Backward"] = "b";
1499 return SelectionDirection2;
1500 })(SelectionDirection || {});
1501 function getSelectionState(selectionStart, selectionEnd, yDoc, options) {
1502 const { selectionDirection } = options ?? {};
1503 const ymap = getRootMap(yDoc, CRDT_RECORD_MAP_KEY);
1504 const yBlocks = ymap.get("blocks");
1505 const isSelectionEmpty = Object.keys(selectionStart).length === 0;
1506 const noSelection = {
1507 type: "none"
1508 /* None */
1509 };
1510 if (isSelectionEmpty || !yBlocks) {
1511 return noSelection;
1512 }
1513 const isSelectionInOneBlock = selectionStart.clientId === selectionEnd.clientId;
1514 const isCursorOnly = isSelectionInOneBlock && selectionStart.offset === selectionEnd.offset;
1515 const isSelectionAWholeBlock = isSelectionInOneBlock && selectionStart.offset === void 0 && selectionEnd.offset === void 0;
1516 if (isSelectionAWholeBlock) {
1517 const path = getBlockPathForLocalClientId(selectionStart.clientId);
1518 const blockPosition = path ? createRelativePositionForBlockPath(path, yBlocks) : null;
1519 if (!blockPosition) {
1520 return noSelection;
1521 }
1522 return {
1523 type: "whole-block",
1524 blockPosition
1525 };
1526 } else if (isCursorOnly) {
1527 const cursorPosition = getCursorPosition(selectionStart, yBlocks);
1528 if (!cursorPosition) {
1529 return noSelection;
1530 }
1531 return {
1532 type: "cursor",
1533 cursorPosition
1534 };
1535 } else if (isSelectionInOneBlock) {
1536 const cursorStartPosition2 = getCursorPosition(
1537 selectionStart,
1538 yBlocks
1539 );
1540 const cursorEndPosition2 = getCursorPosition(selectionEnd, yBlocks);
1541 if (!cursorStartPosition2 || !cursorEndPosition2) {
1542 return noSelection;
1543 }
1544 return {
1545 type: "selection-in-one-block",
1546 cursorStartPosition: cursorStartPosition2,
1547 cursorEndPosition: cursorEndPosition2,
1548 selectionDirection
1549 };
1550 }
1551 const cursorStartPosition = getCursorPosition(selectionStart, yBlocks);
1552 const cursorEndPosition = getCursorPosition(selectionEnd, yBlocks);
1553 if (!cursorStartPosition || !cursorEndPosition) {
1554 return noSelection;
1555 }
1556 return {
1557 type: "selection-in-multiple-blocks",
1558 cursorStartPosition,
1559 cursorEndPosition,
1560 selectionDirection
1561 };
1562 }
1563 function getCursorPosition(selection, blocks) {
1564 const path = getBlockPathForLocalClientId(selection.clientId);
1565 const block = path ? findBlockByPath(path, blocks) : null;
1566 if (!block || !selection.attributeKey || void 0 === selection.offset) {
1567 return null;
1568 }
1569 const attributes = block.get("attributes");
1570 const currentYText = attributes ? getYTextByAttributeKey(attributes, selection.attributeKey) : null;
1571 if (!(currentYText instanceof import_sync7.Y.Text)) {
1572 return null;
1573 }
1574 const relativePosition = import_sync7.Y.createRelativePositionFromTypeIndex(
1575 currentYText,
1576 richTextOffsetToHtmlIndex(
1577 currentYText.toString(),
1578 asRichTextOffset(selection.offset)
1579 )
1580 );
1581 return {
1582 relativePosition,
1583 absoluteOffset: selection.offset,
1584 attributeKey: selection.attributeKey
1585 };
1586 }
1587 function getBlockPathForLocalClientId(clientId) {
1588 const { getBlockIndex, getBlockRootClientId, getBlockName } = (0, import_data3.select)(import_block_editor2.store);
1589 const path = [];
1590 let current = clientId;
1591 while (current) {
1592 const index = getBlockIndex(current);
1593 if (index === -1) {
1594 return null;
1595 }
1596 path.unshift(index);
1597 const parent = getBlockRootClientId(current);
1598 if (!parent) {
1599 break;
1600 }
1601 const parentName = getBlockName(parent);
1602 if (parentName === "core/post-content") {
1603 break;
1604 }
1605 current = parent;
1606 }
1607 return path.length > 0 ? path : null;
1608 }
1609 function findBlockByPath(path, blocks) {
1610 let currentBlocks = blocks;
1611 for (let i = 0; i < path.length; i++) {
1612 if (path[i] >= currentBlocks.length) {
1613 return null;
1614 }
1615 const block = currentBlocks.get(path[i]);
1616 if (!block) {
1617 return null;
1618 }
1619 if (i === path.length - 1) {
1620 return block;
1621 }
1622 currentBlocks = block.get("innerBlocks") ?? new import_sync7.Y.Array();
1623 }
1624 return null;
1625 }
1626 function createRelativePositionForBlockPath(path, blocks) {
1627 let currentBlocks = blocks;
1628 for (let i = 0; i < path.length; i++) {
1629 if (path[i] >= currentBlocks.length) {
1630 return null;
1631 }
1632 if (i === path.length - 1) {
1633 return import_sync7.Y.createRelativePositionFromTypeIndex(
1634 currentBlocks,
1635 path[i]
1636 );
1637 }
1638 const block = currentBlocks.get(path[i]);
1639 currentBlocks = block?.get("innerBlocks") ?? new import_sync7.Y.Array();
1640 }
1641 return null;
1642 }
1643 function areSelectionsStatesEqual(selection1, selection2) {
1644 if (selection1.type !== selection2.type) {
1645 return false;
1646 }
1647 switch (selection1.type) {
1648 case "none":
1649 return true;
1650 case "cursor":
1651 return areCursorPositionsEqual(
1652 selection1.cursorPosition,
1653 selection2.cursorPosition
1654 );
1655 case "selection-in-one-block":
1656 return areCursorPositionsEqual(
1657 selection1.cursorStartPosition,
1658 selection2.cursorStartPosition
1659 ) && areCursorPositionsEqual(
1660 selection1.cursorEndPosition,
1661 selection2.cursorEndPosition
1662 ) && selection1.selectionDirection === selection2.selectionDirection;
1663 case "selection-in-multiple-blocks":
1664 return areCursorPositionsEqual(
1665 selection1.cursorStartPosition,
1666 selection2.cursorStartPosition
1667 ) && areCursorPositionsEqual(
1668 selection1.cursorEndPosition,
1669 selection2.cursorEndPosition
1670 ) && selection1.selectionDirection === selection2.selectionDirection;
1671 case "whole-block":
1672 return import_sync7.Y.compareRelativePositions(
1673 selection1.blockPosition,
1674 selection2.blockPosition
1675 );
1676 default:
1677 return false;
1678 }
1679 }
1680 function areCursorPositionsEqual(cursorPosition1, cursorPosition2) {
1681 const isRelativePositionEqual = import_sync7.Y.compareRelativePositions(
1682 cursorPosition1.relativePosition,
1683 cursorPosition2.relativePosition
1684 );
1685 const isAbsoluteOffsetEqual = cursorPosition1.absoluteOffset === cursorPosition2.absoluteOffset;
1686 return isRelativePositionEqual && isAbsoluteOffsetEqual;
1687 }
1688
1689 // packages/core-data/build-module/awareness/post-editor-awareness.mjs
1690 var PostEditorAwareness = class extends BaseAwarenessState {
1691 constructor(doc, kind, name, postId) {
1692 super(doc);
1693 this.kind = kind;
1694 this.name = name;
1695 this.postId = postId;
1696 }
1697 equalityFieldChecks = {
1698 ...baseEqualityFieldChecks,
1699 editorState: this.areEditorStatesEqual
1700 };
1701 onSetUp() {
1702 super.onSetUp();
1703 this.subscribeToCollaboratorSelectionChanges();
1704 }
1705 /**
1706 * Subscribe to collaborator selection changes and update the selection state.
1707 */
1708 subscribeToCollaboratorSelectionChanges() {
1709 const {
1710 getSelectionStart,
1711 getSelectionEnd,
1712 getSelectedBlocksInitialCaretPosition
1713 } = (0, import_data4.select)(import_block_editor3.store);
1714 let selectionStart = getSelectionStart();
1715 let selectionEnd = getSelectionEnd();
1716 let localCursorTimeout = null;
1717 let selectionBeforeDebounce = null;
1718 (0, import_data4.subscribe)(() => {
1719 const newSelectionStart = getSelectionStart();
1720 const newSelectionEnd = getSelectionEnd();
1721 if (newSelectionStart === selectionStart && newSelectionEnd === selectionEnd) {
1722 return;
1723 }
1724 if (!selectionBeforeDebounce) {
1725 selectionBeforeDebounce = {
1726 start: selectionStart,
1727 end: selectionEnd
1728 };
1729 }
1730 selectionStart = newSelectionStart;
1731 selectionEnd = newSelectionEnd;
1732 const initialPosition = getSelectedBlocksInitialCaretPosition();
1733 void this.updateSelectionInEntityRecord(
1734 selectionStart,
1735 selectionEnd,
1736 initialPosition
1737 );
1738 if (localCursorTimeout) {
1739 clearTimeout(localCursorTimeout);
1740 }
1741 localCursorTimeout = setTimeout(() => {
1742 const selectionStateOptions = {};
1743 if (selectionBeforeDebounce) {
1744 selectionStateOptions.selectionDirection = detectSelectionDirection(
1745 selectionBeforeDebounce.start,
1746 selectionBeforeDebounce.end,
1747 selectionStart,
1748 selectionEnd
1749 );
1750 selectionBeforeDebounce = null;
1751 }
1752 const selectionState = getSelectionState(
1753 selectionStart,
1754 selectionEnd,
1755 this.doc,
1756 selectionStateOptions
1757 );
1758 this.setThrottledLocalStateField(
1759 "editorState",
1760 { selection: selectionState },
1761 AWARENESS_CURSOR_UPDATE_THROTTLE_IN_MS
1762 );
1763 }, LOCAL_CURSOR_UPDATE_DEBOUNCE_IN_MS);
1764 });
1765 }
1766 /**
1767 * Update the entity record with the current collaborator's selection.
1768 *
1769 * @param selectionStart - The start position of the selection.
1770 * @param selectionEnd - The end position of the selection.
1771 * @param initialPosition - The initial position of the selection.
1772 */
1773 async updateSelectionInEntityRecord(selectionStart, selectionEnd, initialPosition) {
1774 const edits = {
1775 selection: { selectionStart, selectionEnd, initialPosition }
1776 };
1777 const options = {
1778 undoIgnore: true
1779 };
1780 (0, import_data4.dispatch)(STORE_NAME).editEntityRecord(
1781 this.kind,
1782 this.name,
1783 this.postId,
1784 edits,
1785 options
1786 );
1787 }
1788 /**
1789 * Check if two editor states are equal.
1790 *
1791 * @param state1 - The first editor state.
1792 * @param state2 - The second editor state.
1793 * @return True if the editor states are equal, false otherwise.
1794 */
1795 areEditorStatesEqual(state1, state2) {
1796 if (!state1 || !state2) {
1797 return state1 === state2;
1798 }
1799 if (!state1.selection || !state2.selection) {
1800 return state1.selection === state2.selection;
1801 }
1802 return areSelectionsStatesEqual(state1.selection, state2.selection);
1803 }
1804 /**
1805 * Resolve a selection state to a text index and block client ID.
1806 *
1807 * For text-based selections, navigates up from the resolved Y.Text via
1808 * AbstractType.parent to find the containing block, then resolves the
1809 * local clientId via the block's tree path.
1810 * For WholeBlock selections, resolves the block's relative position and
1811 * then finds the local clientId via tree path.
1812 *
1813 * Tree-path resolution is used instead of reading the clientId directly
1814 * from the Yjs block because the local block-editor store may use different
1815 * clientIds (e.g. in "Show Template" mode where blocks are cloned).
1816 *
1817 * @param selection - The selection state.
1818 * @param blocks - The tree of block-editor store post content blocks.
1819 * @return The rich-text offset and block client ID, or nulls if not resolvable.
1820 */
1821 convertSelectionStateToAbsolute(selection, blocks) {
1822 if (selection.type === SelectionType.None) {
1823 return {
1824 richTextOffset: null,
1825 localClientId: null,
1826 attributeKey: null
1827 };
1828 }
1829 if (selection.type === SelectionType.WholeBlock) {
1830 const absolutePos = import_sync9.Y.createAbsolutePositionFromRelativePosition(
1831 selection.blockPosition,
1832 this.doc
1833 );
1834 let localClientId2 = null;
1835 if (absolutePos && absolutePos.type instanceof import_sync9.Y.Array) {
1836 const parentArray = absolutePos.type;
1837 const block = parentArray.get(absolutePos.index);
1838 if (block instanceof import_sync9.Y.Map) {
1839 const path2 = getBlockPathInYdoc(block);
1840 localClientId2 = path2 ? resolveBlockClientIdByPath(path2, blocks) : null;
1841 }
1842 }
1843 return {
1844 richTextOffset: null,
1845 localClientId: localClientId2,
1846 attributeKey: null
1847 };
1848 }
1849 const cursorPos = "cursorPosition" in selection ? selection.cursorPosition : selection.cursorStartPosition;
1850 const absolutePosition = import_sync9.Y.createAbsolutePositionFromRelativePosition(
1851 cursorPos.relativePosition,
1852 this.doc
1853 );
1854 if (!absolutePosition) {
1855 return {
1856 richTextOffset: null,
1857 localClientId: null,
1858 attributeKey: null
1859 };
1860 }
1861 const yType = getContainingBlockYMap(absolutePosition.type);
1862 const path = yType ? getBlockPathInYdoc(yType) : null;
1863 const localClientId = path ? resolveBlockClientIdByPath(path, blocks) : null;
1864 return {
1865 richTextOffset: htmlIndexToRichTextOffset(
1866 absolutePosition.type.toString(),
1867 asHtmlStringIndex(absolutePosition.index)
1868 ),
1869 localClientId,
1870 attributeKey: cursorPos.attributeKey ?? null
1871 };
1872 }
1873 /**
1874 * Type guard to check if a struct is a Y.Item (not Y.GC)
1875 * @param struct - The struct to check.
1876 * @return True if the struct is a Y.Item, false otherwise.
1877 */
1878 isYItem(struct) {
1879 return "content" in struct;
1880 }
1881 /**
1882 * Get data for debugging, using the awareness state.
1883 *
1884 * @return {YDocDebugData} The debug data.
1885 */
1886 getDebugData() {
1887 const ydoc = this.doc;
1888 const docData = Object.fromEntries(
1889 Array.from(ydoc.share, ([key, value]) => [
1890 key,
1891 value.toJSON()
1892 ])
1893 );
1894 const collaboratorMapData = new Map(
1895 Array.from(this.getSeenStates().entries()).map(
1896 ([clientId, collaboratorState]) => [
1897 String(clientId),
1898 {
1899 name: collaboratorState.collaboratorInfo.name,
1900 wpUserId: collaboratorState.collaboratorInfo.id
1901 }
1902 ]
1903 )
1904 );
1905 const serializableClientItems = {};
1906 ydoc.store.clients.forEach((structs, clientId) => {
1907 const items2 = structs.filter(this.isYItem);
1908 serializableClientItems[clientId] = items2.map((item) => {
1909 const { left, right, ...rest } = item;
1910 return {
1911 ...rest,
1912 left: left ? {
1913 id: left.id,
1914 length: left.length,
1915 origin: left.origin,
1916 content: left.content
1917 } : null,
1918 right: right ? {
1919 id: right.id,
1920 length: right.length,
1921 origin: right.origin,
1922 content: right.content
1923 } : null
1924 };
1925 });
1926 });
1927 return {
1928 doc: docData,
1929 clients: serializableClientItems,
1930 collaboratorMap: Object.fromEntries(collaboratorMapData)
1931 };
1932 }
1933 };
1934 function detectSelectionDirection(prevStart, prevEnd, newStart, newEnd) {
1935 const startMoved = !areBlockSelectionsEqual(prevStart, newStart);
1936 const endMoved = !areBlockSelectionsEqual(prevEnd, newEnd);
1937 if (startMoved && !endMoved) {
1938 return SelectionDirection.Backward;
1939 }
1940 return SelectionDirection.Forward;
1941 }
1942 function areBlockSelectionsEqual(a, b) {
1943 return a.clientId === b.clientId && a.attributeKey === b.attributeKey && a.offset === b.offset;
1944 }
1945
1946 // packages/core-data/build-module/utils/crdt.mjs
1947 var import_es63 = __toESM(require_es6(), 1);
1948 var import_blocks3 = __toESM(require_blocks(), 1);
1949 var import_sync14 = __toESM(require_sync(), 1);
1950
1951 // node_modules/uuid/dist/stringify.js
1952 var byteToHex = [];
1953 for (let i = 0; i < 256; ++i) {
1954 byteToHex.push((i + 256).toString(16).slice(1));
1955 }
1956 function unsafeStringify(arr, offset = 0) {
1957 return (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();
1958 }
1959
1960 // node_modules/uuid/dist/rng.js
1961 var rnds8 = new Uint8Array(16);
1962 function rng() {
1963 return crypto.getRandomValues(rnds8);
1964 }
1965
1966 // node_modules/uuid/dist/v4.js
1967 function v4(options, buf, offset) {
1968 if (!buf && !options && crypto.randomUUID) {
1969 return crypto.randomUUID();
1970 }
1971 return _v4(options, buf, offset);
1972 }
1973 function _v4(options, buf, offset) {
1974 options = options || {};
1975 const rnds = options.random ?? options.rng?.() ?? rng();
1976 if (rnds.length < 16) {
1977 throw new Error("Random bytes length must be >= 16");
1978 }
1979 rnds[6] = rnds[6] & 15 | 64;
1980 rnds[8] = rnds[8] & 63 | 128;
1981 if (buf) {
1982 offset = offset || 0;
1983 if (offset < 0 || offset + 16 > buf.length) {
1984 throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);
1985 }
1986 for (let i = 0; i < 16; ++i) {
1987 buf[offset + i] = rnds[i];
1988 }
1989 return buf;
1990 }
1991 return unsafeStringify(rnds);
1992 }
1993 var v4_default = v4;
1994
1995 // packages/core-data/build-module/utils/crdt-blocks.mjs
1996 var import_es62 = __toESM(require_es6(), 1);
1997 var import_blocks = __toESM(require_blocks(), 1);
1998 var import_rich_text3 = __toESM(require_rich_text(), 1);
1999 var import_sync10 = __toESM(require_sync(), 1);
2000
2001 // packages/core-data/build-module/utils/crdt-text.mjs
2002 var import_rich_text2 = __toESM(require_rich_text(), 1);
2003 var RICH_TEXT_CACHE_MAX_SIZE = 500;
2004 function createRichTextDataCache(maxSize) {
2005 const cache3 = /* @__PURE__ */ new Map();
2006 return function(value) {
2007 const cached = cache3.get(value);
2008 if (cached) {
2009 return cached;
2010 }
2011 const result = import_rich_text2.RichTextData.fromHTMLString(value);
2012 if (cache3.size >= maxSize) {
2013 cache3.delete(cache3.keys().next().value);
2014 }
2015 cache3.set(value, result);
2016 return result;
2017 };
2018 }
2019 var getCachedRichTextData = createRichTextDataCache(
2020 RICH_TEXT_CACHE_MAX_SIZE
2021 );
2022
2023 // packages/core-data/build-module/utils/crdt-blocks.mjs
2024 var serializableBlocksCache = /* @__PURE__ */ new WeakMap();
2025 function serializeAttributeValue(value) {
2026 if (value instanceof import_rich_text3.RichTextData) {
2027 return value.valueOf();
2028 }
2029 if (Array.isArray(value)) {
2030 return value.map(serializeAttributeValue);
2031 }
2032 if (value && typeof value === "object") {
2033 const result = {};
2034 for (const [k, v] of Object.entries(value)) {
2035 result[k] = serializeAttributeValue(v);
2036 }
2037 return result;
2038 }
2039 return value;
2040 }
2041 function makeBlockAttributesSerializable(blockName, attributes) {
2042 const newAttributes = { ...attributes };
2043 for (const [key, value] of Object.entries(attributes)) {
2044 if (isLocalAttribute(blockName, key)) {
2045 delete newAttributes[key];
2046 continue;
2047 }
2048 newAttributes[key] = serializeAttributeValue(value);
2049 }
2050 return newAttributes;
2051 }
2052 function makeBlocksSerializable(blocks) {
2053 return blocks.map((block) => {
2054 const {
2055 name,
2056 innerBlocks,
2057 attributes,
2058 /*
2059 * Any validation issues discovered when loading a block are appended
2060 * to the block node with a logging function, which cannot be serialized.
2061 *
2062 * @see import("@wordpress/blocks/src/api/parser").parseRawBlock()
2063 */
2064 validationIssues,
2065 ...rest
2066 } = block;
2067 return {
2068 ...rest,
2069 name,
2070 attributes: makeBlockAttributesSerializable(name, attributes),
2071 innerBlocks: makeBlocksSerializable(innerBlocks)
2072 };
2073 });
2074 }
2075 function deserializeAttributeValue(schema, value) {
2076 if (schema?.type === "rich-text" && typeof value === "string") {
2077 return getCachedRichTextData(value);
2078 }
2079 if (Array.isArray(value)) {
2080 return value.map(
2081 (item) => deserializeAttributeValue(schema, item)
2082 );
2083 }
2084 if (value && typeof value === "object") {
2085 const result = {};
2086 for (const [key, innerValue] of Object.entries(
2087 value
2088 )) {
2089 result[key] = deserializeAttributeValue(
2090 schema?.query?.[key],
2091 innerValue
2092 );
2093 }
2094 return result;
2095 }
2096 return value;
2097 }
2098 function deserializeBlockAttributes(blocks) {
2099 return blocks.map((block) => {
2100 const { name, innerBlocks, attributes, ...rest } = block;
2101 const newAttributes = { ...attributes };
2102 for (const [key, value] of Object.entries(attributes)) {
2103 const schema = getBlockAttributeSchema(name, key);
2104 if (schema) {
2105 newAttributes[key] = deserializeAttributeValue(
2106 schema,
2107 value
2108 );
2109 }
2110 }
2111 return {
2112 ...rest,
2113 name,
2114 attributes: newAttributes,
2115 innerBlocks: deserializeBlockAttributes(innerBlocks ?? [])
2116 };
2117 });
2118 }
2119 function areBlocksEqual(gblock, yblock) {
2120 const yblockAsJson = yblock.toJSON();
2121 const overwrites = {
2122 innerBlocks: null,
2123 clientId: null
2124 };
2125 const res = (0, import_es62.default)(
2126 Object.assign({}, gblock, overwrites),
2127 Object.assign({}, yblockAsJson, overwrites)
2128 );
2129 const inners = gblock.innerBlocks || [];
2130 const yinners = yblock.get("innerBlocks");
2131 return res && inners.length === yinners?.length && inners.every(
2132 (block, i) => areBlocksEqual(block, yinners.get(i))
2133 );
2134 }
2135 function createNewYAttributeMap(blockName, attributes) {
2136 return new import_sync10.Y.Map(
2137 Object.entries(attributes).map(
2138 ([attributeName, attributeValue]) => {
2139 return [
2140 attributeName,
2141 createNewYAttributeValue(
2142 blockName,
2143 attributeName,
2144 attributeValue
2145 )
2146 ];
2147 }
2148 )
2149 );
2150 }
2151 function createNewYAttributeValue(blockName, attributeName, attributeValue) {
2152 const schema = getBlockAttributeSchema(blockName, attributeName);
2153 return createYValueFromSchema(schema, attributeValue);
2154 }
2155 function createYValueFromSchema(schema, value) {
2156 if (!schema) {
2157 return value;
2158 }
2159 if (schema.type === "rich-text") {
2160 return new import_sync10.Y.Text(value?.toString() ?? "");
2161 }
2162 if (schema.type === "array" && schema.query && Array.isArray(value)) {
2163 const query = schema.query;
2164 const yArray = new import_sync10.Y.Array();
2165 yArray.insert(
2166 0,
2167 value.map((item) => createYMapFromQuery(query, item))
2168 );
2169 return yArray;
2170 }
2171 if (schema.type === "object" && schema.query && isRecord(value)) {
2172 return createYMapFromQuery(schema.query, value);
2173 }
2174 return value;
2175 }
2176 function isRecord(value) {
2177 return !!value && typeof value === "object" && !Array.isArray(value);
2178 }
2179 function createYMapFromQuery(query, obj) {
2180 if (!isRecord(obj)) {
2181 return new import_sync10.Y.Map();
2182 }
2183 const entries = Object.entries(obj).map(
2184 ([key, val]) => {
2185 const subSchema = query[key];
2186 return [key, createYValueFromSchema(subSchema, val)];
2187 }
2188 );
2189 return new import_sync10.Y.Map(entries);
2190 }
2191 function createNewYBlock(block) {
2192 return createYMap(
2193 Object.fromEntries(
2194 Object.entries(block).map(([key, value]) => {
2195 switch (key) {
2196 case "attributes": {
2197 return [
2198 key,
2199 createNewYAttributeMap(block.name, value)
2200 ];
2201 }
2202 case "innerBlocks": {
2203 const innerBlocks = new import_sync10.Y.Array();
2204 if (!Array.isArray(value)) {
2205 return [key, innerBlocks];
2206 }
2207 innerBlocks.insert(
2208 0,
2209 value.map(
2210 (innerBlock) => createNewYBlock(innerBlock)
2211 )
2212 );
2213 return [key, innerBlocks];
2214 }
2215 default:
2216 return [key, value];
2217 }
2218 })
2219 )
2220 );
2221 }
2222 function mergeCrdtBlocks(yblocks, incomingBlocks, attributeCursor, options = {}) {
2223 if (!serializableBlocksCache.has(incomingBlocks)) {
2224 serializableBlocksCache.set(
2225 incomingBlocks,
2226 makeBlocksSerializable(incomingBlocks)
2227 );
2228 }
2229 const incomingBlocksToSync = serializableBlocksCache.get(incomingBlocks) ?? [];
2230 const numOfCommonEntries = Math.min(
2231 incomingBlocksToSync.length ?? 0,
2232 yblocks.length
2233 );
2234 let left = 0;
2235 let right = 0;
2236 for (; left < numOfCommonEntries && areBlocksEqual(incomingBlocksToSync[left], yblocks.get(left)); left++) {
2237 }
2238 for (; right < numOfCommonEntries - left && areBlocksEqual(
2239 incomingBlocksToSync[incomingBlocksToSync.length - right - 1],
2240 yblocks.get(yblocks.length - right - 1)
2241 ); right++) {
2242 }
2243 const numOfUpdatesNeeded = numOfCommonEntries - left - right;
2244 const numOfInsertionsNeeded = Math.max(
2245 0,
2246 incomingBlocksToSync.length - yblocks.length
2247 );
2248 const numOfDeletionsNeeded = Math.max(
2249 0,
2250 yblocks.length - incomingBlocksToSync.length
2251 );
2252 for (let i = 0; i < numOfUpdatesNeeded; i++, left++) {
2253 const incomingYBlock = incomingBlocksToSync[left];
2254 const localYBlock = yblocks.get(left);
2255 Object.entries(incomingYBlock).forEach(
2256 ([incomingBlockProperty, incomingBlockPropertyValue]) => {
2257 switch (incomingBlockProperty) {
2258 case "attributes": {
2259 const localAttributes = localYBlock.get(
2260 incomingBlockProperty
2261 );
2262 const incomingAttributes = incomingBlockPropertyValue;
2263 if (!localAttributes) {
2264 localYBlock.set(
2265 incomingBlockProperty,
2266 createNewYAttributeMap(
2267 incomingYBlock.name,
2268 incomingAttributes
2269 )
2270 );
2271 break;
2272 }
2273 Object.entries(incomingAttributes).forEach(
2274 ([
2275 incomingAttributeName,
2276 incomingAttributeValue
2277 ]) => {
2278 const currentAttribute = localAttributes?.get(
2279 incomingAttributeName
2280 );
2281 const isExpectedType = isExpectedAttributeType(
2282 incomingYBlock.name,
2283 incomingAttributeName,
2284 currentAttribute
2285 );
2286 const isYType = currentAttribute instanceof import_sync10.Y.AbstractType;
2287 const isAttributeChanged = !isExpectedType || isYType || !(0, import_es62.default)(
2288 currentAttribute,
2289 incomingAttributeValue
2290 );
2291 if (isAttributeChanged) {
2292 updateYBlockAttribute(
2293 incomingYBlock.name,
2294 incomingYBlock.clientId,
2295 incomingAttributeName,
2296 incomingAttributeValue,
2297 localAttributes,
2298 attributeCursor
2299 );
2300 }
2301 }
2302 );
2303 localAttributes.forEach(
2304 (_attrValue, attrName) => {
2305 if (!incomingBlockPropertyValue.hasOwnProperty(
2306 attrName
2307 )) {
2308 localAttributes.delete(attrName);
2309 }
2310 }
2311 );
2312 break;
2313 }
2314 case "innerBlocks": {
2315 let yInnerBlocks = localYBlock.get(
2316 incomingBlockProperty
2317 );
2318 if (!(yInnerBlocks instanceof import_sync10.Y.Array)) {
2319 yInnerBlocks = new import_sync10.Y.Array();
2320 localYBlock.set(
2321 incomingBlockProperty,
2322 yInnerBlocks
2323 );
2324 }
2325 mergeCrdtBlocks(
2326 yInnerBlocks,
2327 incomingBlockPropertyValue ?? [],
2328 attributeCursor,
2329 options
2330 );
2331 break;
2332 }
2333 case "clientId": {
2334 if (options.preserveClientIds) {
2335 break;
2336 }
2337 if (incomingBlockPropertyValue !== localYBlock.get(incomingBlockProperty)) {
2338 localYBlock.set(
2339 incomingBlockProperty,
2340 incomingBlockPropertyValue
2341 );
2342 }
2343 break;
2344 }
2345 default:
2346 if (!(0, import_es62.default)(
2347 incomingYBlock[incomingBlockProperty],
2348 localYBlock.get(incomingBlockProperty)
2349 )) {
2350 localYBlock.set(
2351 incomingBlockProperty,
2352 incomingBlockPropertyValue
2353 );
2354 }
2355 }
2356 }
2357 );
2358 localYBlock.forEach((_v, k) => {
2359 if (!incomingYBlock.hasOwnProperty(k)) {
2360 localYBlock.delete(k);
2361 }
2362 });
2363 }
2364 yblocks.delete(left, numOfDeletionsNeeded);
2365 for (let i = 0; i < numOfInsertionsNeeded; i++, left++) {
2366 const newBlock = [createNewYBlock(incomingBlocksToSync[left])];
2367 yblocks.insert(left, newBlock);
2368 }
2369 const knownClientIds = /* @__PURE__ */ new Set();
2370 for (let j = 0; j < yblocks.length; j++) {
2371 const yblock = yblocks.get(j);
2372 let clientId = yblock.get("clientId");
2373 if (!clientId) {
2374 continue;
2375 }
2376 if (knownClientIds.has(clientId)) {
2377 clientId = v4_default();
2378 yblock.set("clientId", clientId);
2379 }
2380 knownClientIds.add(clientId);
2381 }
2382 }
2383 function areArrayElementsEqual(newElement, yElement) {
2384 if (yElement instanceof import_sync10.Y.Map && isRecord(newElement)) {
2385 return (0, import_es62.default)(newElement, yElement.toJSON());
2386 }
2387 return (0, import_es62.default)(newElement, yElement);
2388 }
2389 function mergeYArray(yArray, newValue, schema, cursorPosition, cursorScope) {
2390 if (!schema.query) {
2391 return;
2392 }
2393 const query = schema.query;
2394 const numOfCommonEntries = Math.min(newValue.length, yArray.length);
2395 let left = 0;
2396 let right = 0;
2397 for (; left < numOfCommonEntries && areArrayElementsEqual(newValue[left], yArray.get(left)); left++) {
2398 }
2399 for (; right < numOfCommonEntries - left && areArrayElementsEqual(
2400 newValue[newValue.length - right - 1],
2401 yArray.get(yArray.length - right - 1)
2402 ); right++) {
2403 }
2404 const numOfUpdatesNeeded = numOfCommonEntries - left - right;
2405 for (let i = 0; i < numOfUpdatesNeeded; i++) {
2406 const currentElement = yArray.get(left + i);
2407 const newElement = newValue[left + i];
2408 if (currentElement instanceof import_sync10.Y.Map && isRecord(newElement)) {
2409 mergeYMapValues(
2410 currentElement,
2411 newElement,
2412 query,
2413 cursorPosition,
2414 cursorScope
2415 );
2416 } else {
2417 yArray.delete(0, yArray.length);
2418 yArray.insert(
2419 0,
2420 newValue.map((item) => createYMapFromQuery(query, item))
2421 );
2422 return;
2423 }
2424 }
2425 const numOfDeletionsNeeded = Math.max(0, yArray.length - newValue.length);
2426 if (numOfDeletionsNeeded > 0) {
2427 yArray.delete(left + numOfUpdatesNeeded, numOfDeletionsNeeded);
2428 }
2429 const numOfInsertionsNeeded = Math.max(
2430 0,
2431 newValue.length - yArray.length
2432 );
2433 if (numOfInsertionsNeeded > 0) {
2434 const insertAt = left + numOfUpdatesNeeded;
2435 const itemsToInsert = new Array(
2436 numOfInsertionsNeeded
2437 );
2438 for (let i = 0; i < numOfInsertionsNeeded; i++) {
2439 itemsToInsert[i] = createYMapFromQuery(
2440 query,
2441 newValue[insertAt + i]
2442 );
2443 }
2444 yArray.insert(insertAt, itemsToInsert);
2445 }
2446 }
2447 function mergeYValue(schema, newVal, yMap, key, cursorPosition, cursorScope) {
2448 const currentVal = yMap.get(key);
2449 if (schema?.type === "rich-text" && typeof newVal === "string" && currentVal instanceof import_sync10.Y.Text) {
2450 mergeRichTextUpdate(
2451 currentVal,
2452 newVal,
2453 resolveRichTextCursorPosition(cursorPosition, cursorScope, newVal)
2454 );
2455 } else if (schema?.type === "array" && schema.query && Array.isArray(newVal) && currentVal instanceof import_sync10.Y.Array) {
2456 mergeYArray(currentVal, newVal, schema, cursorPosition, cursorScope);
2457 } else if (schema?.type === "object" && schema.query && isRecord(newVal) && currentVal instanceof import_sync10.Y.Map) {
2458 mergeYMapValues(
2459 currentVal,
2460 newVal,
2461 schema.query,
2462 cursorPosition,
2463 cursorScope
2464 );
2465 } else {
2466 const newYValue = createYValueFromSchema(schema, newVal);
2467 if (newYValue !== newVal || !(0, import_es62.default)(currentVal, newVal)) {
2468 yMap.set(key, newYValue);
2469 }
2470 }
2471 }
2472 function mergeYMapValues(yMap, newObj, query, cursorPosition, cursorScope) {
2473 for (const [key, newVal] of Object.entries(newObj)) {
2474 mergeYValue(
2475 query[key],
2476 newVal,
2477 yMap,
2478 key,
2479 cursorPosition,
2480 cursorScope
2481 );
2482 }
2483 for (const key of yMap.keys()) {
2484 if (!Object.hasOwn(newObj, key)) {
2485 yMap.delete(key);
2486 }
2487 }
2488 }
2489 function updateYBlockAttribute(blockName, clientId, attributeName, attributeValue, currentAttributes, newCursorPosition) {
2490 const schema = getBlockAttributeSchema(blockName, attributeName);
2491 mergeYValue(
2492 schema,
2493 attributeValue,
2494 currentAttributes,
2495 attributeName,
2496 newCursorPosition,
2497 { attributeKey: attributeName, clientId }
2498 );
2499 }
2500 function resolveRichTextCursorPosition(cursorPosition, cursorScope, updatedValue) {
2501 return cursorPosition && cursorPosition.clientId === cursorScope.clientId && cursorPosition.attributeKey === cursorScope.attributeKey && "number" === typeof cursorPosition.offset && Number.isInteger(cursorPosition.offset) ? richTextOffsetToHtmlIndex(
2502 updatedValue,
2503 asRichTextOffset(cursorPosition.offset)
2504 ) : null;
2505 }
2506 var cachedBlockAttributeSchemas;
2507 function getBlockAttributeSchema(blockName, attributeName) {
2508 if (!cachedBlockAttributeSchemas) {
2509 cachedBlockAttributeSchemas = /* @__PURE__ */ new Map();
2510 for (const blockType of (0, import_blocks.getBlockTypes)()) {
2511 cachedBlockAttributeSchemas.set(
2512 blockType.name,
2513 new Map(
2514 Object.entries(blockType.attributes ?? {}).map(
2515 ([name, definition]) => {
2516 const { role, type, query } = definition;
2517 return [name, { role, type, query }];
2518 }
2519 )
2520 )
2521 );
2522 }
2523 }
2524 return cachedBlockAttributeSchemas.get(blockName)?.get(attributeName);
2525 }
2526 function isExpectedAttributeType(blockName, attributeName, attributeValue) {
2527 const schema = getBlockAttributeSchema(blockName, attributeName);
2528 if (schema?.type === "rich-text") {
2529 return attributeValue instanceof import_sync10.Y.Text;
2530 }
2531 if (schema?.type === "string") {
2532 return typeof attributeValue === "string";
2533 }
2534 if (schema?.type === "array" && schema.query) {
2535 return attributeValue instanceof import_sync10.Y.Array;
2536 }
2537 if (schema?.type === "object" && schema.query) {
2538 return attributeValue instanceof import_sync10.Y.Map;
2539 }
2540 return true;
2541 }
2542 function isLocalAttribute(blockName, attributeName) {
2543 return "local" === getBlockAttributeSchema(blockName, attributeName)?.role;
2544 }
2545 var localDoc;
2546 function mergeRichTextUpdate(blockYText, updatedValue, htmlCursorIndex = null) {
2547 const currentValueAsDelta = new Delta(blockYText.toDelta());
2548 const updatedValueAsDelta = new Delta([{ insert: updatedValue }]);
2549 const deltaDiff = currentValueAsDelta.diffWithCursor(
2550 updatedValueAsDelta,
2551 htmlCursorIndex
2552 );
2553 const safeDiff = htmlCursorIndex === null || isDeltaVerificationMatch(blockYText, deltaDiff, updatedValue) ? deltaDiff : currentValueAsDelta.diff(updatedValueAsDelta);
2554 blockYText.applyDelta(safeDiff.ops);
2555 }
2556 function isDeltaVerificationMatch(blockYText, delta, expectedValue) {
2557 if (!localDoc) {
2558 localDoc = new import_sync10.Y.Doc();
2559 }
2560 const verificationYText = localDoc.getText("verification-text");
2561 verificationYText.delete(0, verificationYText.length);
2562 verificationYText.insert(0, blockYText.toString());
2563 verificationYText.applyDelta(delta.ops);
2564 return verificationYText.toString() === expectedValue;
2565 }
2566
2567 // packages/core-data/build-module/utils/crdt-selection.mjs
2568 var import_data5 = __toESM(require_data(), 1);
2569 var import_block_editor4 = __toESM(require_block_editor(), 1);
2570 var import_blocks2 = __toESM(require_blocks(), 1);
2571 var import_sync13 = __toESM(require_sync(), 1);
2572
2573 // packages/core-data/build-module/utils/block-selection-history.mjs
2574 var import_sync12 = __toESM(require_sync(), 1);
2575 var SELECTION_HISTORY_DEFAULT_SIZE = 5;
2576 var YSelectionType = /* @__PURE__ */ ((YSelectionType2) => {
2577 YSelectionType2["RelativeSelection"] = "RelativeSelection";
2578 YSelectionType2["BlockSelection"] = "BlockSelection";
2579 return YSelectionType2;
2580 })(YSelectionType || {});
2581 function createBlockSelectionHistory(ydoc, historySize = SELECTION_HISTORY_DEFAULT_SIZE) {
2582 let history = [];
2583 const getSelectionHistory2 = () => {
2584 return history.slice(0);
2585 };
2586 const updateSelection = (newSelection) => {
2587 if (!newSelection?.selectionStart?.clientId || !newSelection?.selectionEnd?.clientId) {
2588 return;
2589 }
2590 const { selectionStart, selectionEnd } = newSelection;
2591 const start = convertWPBlockSelectionToSelection(
2592 selectionStart,
2593 ydoc
2594 );
2595 const end = convertWPBlockSelectionToSelection(selectionEnd, ydoc);
2596 addToHistory({ start, end });
2597 };
2598 const addToHistory = (yFullSelection) => {
2599 const startClientId = yFullSelection.start.clientId;
2600 const endClientId = yFullSelection.end.clientId;
2601 history = history.filter((entry) => {
2602 const isSameBlockCombination = entry.start.clientId === startClientId && entry.end.clientId === endClientId;
2603 return !isSameBlockCombination;
2604 });
2605 history.unshift(yFullSelection);
2606 if (history.length > historySize + 1) {
2607 history = history.slice(0, historySize + 1);
2608 }
2609 };
2610 return {
2611 getSelectionHistory: getSelectionHistory2,
2612 updateSelection
2613 };
2614 }
2615 function convertWPBlockSelectionToSelection(selection, ydoc) {
2616 const clientId = selection.clientId;
2617 const block = findBlockByClientIdInDoc(clientId, ydoc);
2618 const attributes = block?.get("attributes");
2619 const attributeKey = selection.attributeKey;
2620 let changedYText = null;
2621 if (attributeKey && attributes) {
2622 changedYText = getYTextByAttributeKey(attributes, attributeKey);
2623 }
2624 if (!(changedYText instanceof import_sync12.Y.Text) || !attributeKey || !clientId) {
2625 return {
2626 type: "BlockSelection",
2627 clientId
2628 };
2629 }
2630 const offset = selection.offset ?? 0;
2631 const relativePosition = import_sync12.Y.createRelativePositionFromTypeIndex(
2632 changedYText,
2633 richTextOffsetToHtmlIndex(
2634 changedYText.toString(),
2635 asRichTextOffset(offset)
2636 )
2637 );
2638 return {
2639 type: "RelativeSelection",
2640 attributeKey,
2641 relativePosition,
2642 clientId,
2643 offset
2644 };
2645 }
2646
2647 // packages/core-data/build-module/utils/crdt-selection.mjs
2648 var selectionHistoryMap = /* @__PURE__ */ new WeakMap();
2649 function getBlockSelectionHistory(ydoc) {
2650 let history = selectionHistoryMap.get(ydoc);
2651 if (!history) {
2652 history = createBlockSelectionHistory(ydoc);
2653 selectionHistoryMap.set(ydoc, history);
2654 }
2655 return history;
2656 }
2657 function getSelectionHistory(ydoc) {
2658 return getBlockSelectionHistory(ydoc).getSelectionHistory();
2659 }
2660 function updateSelectionHistory(ydoc, wpSelection) {
2661 return getBlockSelectionHistory(ydoc).updateSelection(wpSelection);
2662 }
2663 function convertYSelectionToBlockSelection(ySelection, ydoc) {
2664 if (ySelection.type === YSelectionType.RelativeSelection) {
2665 const { relativePosition, attributeKey, clientId } = ySelection;
2666 const absolutePosition = import_sync13.Y.createAbsolutePositionFromRelativePosition(
2667 relativePosition,
2668 ydoc
2669 );
2670 if (absolutePosition) {
2671 return {
2672 clientId,
2673 attributeKey,
2674 offset: htmlIndexToRichTextOffset(
2675 absolutePosition.type.toString(),
2676 asHtmlStringIndex(absolutePosition.index)
2677 )
2678 };
2679 }
2680 } else if (ySelection.type === YSelectionType.BlockSelection) {
2681 return {
2682 clientId: ySelection.clientId,
2683 attributeKey: void 0,
2684 offset: void 0
2685 };
2686 }
2687 return null;
2688 }
2689 function convertYFullSelectionToWPSelection(yFullSelection, ydoc) {
2690 const { start, end } = yFullSelection;
2691 const startBlock = findBlockByClientIdInDoc(start.clientId, ydoc);
2692 const endBlock = findBlockByClientIdInDoc(end.clientId, ydoc);
2693 if (!startBlock || !endBlock) {
2694 return null;
2695 }
2696 const startBlockSelection = convertYSelectionToBlockSelection(
2697 start,
2698 ydoc
2699 );
2700 const endBlockSelection = convertYSelectionToBlockSelection(end, ydoc);
2701 if (startBlockSelection === null || endBlockSelection === null) {
2702 return null;
2703 }
2704 return {
2705 selectionStart: startBlockSelection,
2706 selectionEnd: endBlockSelection
2707 };
2708 }
2709 function findSelectionFromHistory(ydoc, selectionHistory) {
2710 for (const positionToTry of selectionHistory) {
2711 const result = convertYFullSelectionToWPSelection(
2712 positionToTry,
2713 ydoc
2714 );
2715 if (result !== null) {
2716 return result;
2717 }
2718 }
2719 return null;
2720 }
2721 function restoreSelection(selectionHistory, ydoc) {
2722 const selectionToRestore = findSelectionFromHistory(
2723 ydoc,
2724 selectionHistory
2725 );
2726 if (selectionToRestore === null) {
2727 return;
2728 }
2729 const { getBlock } = (0, import_data5.select)(import_block_editor4.store);
2730 const { resetSelection } = (0, import_data5.dispatch)(import_block_editor4.store);
2731 const { selectionStart, selectionEnd } = selectionToRestore;
2732 const isSelectionInSameBlock = selectionStart.clientId === selectionEnd.clientId;
2733 if (isSelectionInSameBlock) {
2734 const block = getBlock(selectionStart.clientId);
2735 const isBlockEmpty = block && (0, import_blocks2.isUnmodifiedBlock)(block);
2736 const isBeginningOfEmptyBlock = 0 === selectionStart.offset && 0 === selectionEnd.offset && isBlockEmpty && !selectionStart.attributeKey && !selectionEnd.attributeKey;
2737 if (isBeginningOfEmptyBlock) {
2738 const selectionStartWithoutOffset = {
2739 clientId: selectionStart.clientId
2740 };
2741 const selectionEndWithoutOffset = {
2742 clientId: selectionEnd.clientId
2743 };
2744 resetSelection(
2745 selectionStartWithoutOffset,
2746 selectionEndWithoutOffset,
2747 0
2748 );
2749 } else {
2750 resetSelection(selectionStart, selectionEnd, 0);
2751 }
2752 } else {
2753 resetSelection(selectionEnd, selectionEnd, 0);
2754 }
2755 }
2756 function getShiftedSelection(ydoc, selectionHistory) {
2757 if (selectionHistory.length === 0) {
2758 return null;
2759 }
2760 const { start, end } = selectionHistory[0];
2761 if (start.type === YSelectionType.BlockSelection || end.type === YSelectionType.BlockSelection) {
2762 return null;
2763 }
2764 const selectionStart = convertYSelectionToBlockSelection(start, ydoc);
2765 const selectionEnd = convertYSelectionToBlockSelection(end, ydoc);
2766 if (!selectionStart || !selectionEnd) {
2767 return null;
2768 }
2769 const startShifted = selectionStart.offset !== start.offset;
2770 const endShifted = selectionEnd.offset !== end.offset;
2771 if (!startShifted && !endShifted) {
2772 return null;
2773 }
2774 return { selectionStart, selectionEnd };
2775 }
2776
2777 // packages/core-data/build-module/utils/crdt.mjs
2778 var POST_META_KEY_FOR_CRDT_DOC_PERSISTENCE = "_crdt_document";
2779 var disallowedPostMetaKeys = /* @__PURE__ */ new Set([
2780 POST_META_KEY_FOR_CRDT_DOC_PERSISTENCE
2781 ]);
2782 function defaultApplyChangesToCRDTDoc(ydoc, changes) {
2783 const ymap = getRootMap(ydoc, CRDT_RECORD_MAP_KEY);
2784 Object.entries(changes).forEach(([key, newValue]) => {
2785 if ("function" === typeof newValue) {
2786 return;
2787 }
2788 switch (key) {
2789 // Add support for additional data types here.
2790 default: {
2791 const currentValue = ymap.get(key);
2792 updateMapValue(ymap, key, currentValue, newValue);
2793 }
2794 }
2795 });
2796 }
2797 function applyPostChangesToCRDTDoc(ydoc, changes, syncedProperties) {
2798 const ymap = getRootMap(ydoc, CRDT_RECORD_MAP_KEY);
2799 Object.keys(changes).forEach((key) => {
2800 if (!syncedProperties.has(key)) {
2801 return;
2802 }
2803 const newValue = changes[key];
2804 if ("function" === typeof newValue) {
2805 return;
2806 }
2807 switch (key) {
2808 case "blocks": {
2809 const newCursorPosition = parseCursorSelection(
2810 changes.selection
2811 );
2812 const rawContent = getRawValue(changes.content);
2813 if (!newValue && typeof rawContent === "string") {
2814 mergeContentWithoutBlocks(
2815 ymap,
2816 rawContent,
2817 newCursorPosition
2818 );
2819 break;
2820 } else if (!newValue) {
2821 ymap.set(key, void 0);
2822 break;
2823 }
2824 let currentBlocks = ymap.get(key);
2825 if (!(currentBlocks instanceof import_sync14.Y.Array)) {
2826 currentBlocks = new import_sync14.Y.Array();
2827 ymap.set(key, currentBlocks);
2828 }
2829 mergeCrdtBlocks(currentBlocks, newValue, newCursorPosition);
2830 break;
2831 }
2832 case "content":
2833 case "excerpt":
2834 case "title": {
2835 const currentValue = ymap.get(key);
2836 let rawValue = getRawValue(newValue);
2837 if (key === "title" && !currentValue?.toString() && "Auto Draft" === rawValue) {
2838 rawValue = "";
2839 }
2840 if (currentValue instanceof import_sync14.Y.Text) {
2841 mergeRichTextUpdate(currentValue, rawValue ?? "");
2842 } else {
2843 const newYText = new import_sync14.Y.Text(rawValue ?? "");
2844 ymap.set(key, newYText);
2845 }
2846 break;
2847 }
2848 // "Meta" is overloaded term; here, it refers to post meta.
2849 case "meta": {
2850 let metaMap = ymap.get("meta");
2851 if (!isYMap(metaMap)) {
2852 metaMap = createYMap();
2853 ymap.set("meta", metaMap);
2854 }
2855 Object.entries(newValue ?? {}).forEach(
2856 ([metaKey, metaValue]) => {
2857 if (disallowedPostMetaKeys.has(metaKey)) {
2858 return;
2859 }
2860 updateMapValue(
2861 metaMap,
2862 metaKey,
2863 metaMap.get(metaKey),
2864 // current value in CRDT
2865 metaValue
2866 // new value from changes
2867 );
2868 }
2869 );
2870 break;
2871 }
2872 case "slug": {
2873 if (!newValue) {
2874 break;
2875 }
2876 const currentValue = ymap.get(key);
2877 updateMapValue(ymap, key, currentValue, newValue);
2878 break;
2879 }
2880 // Add support for additional properties here.
2881 default: {
2882 const currentValue = ymap.get(key);
2883 updateMapValue(ymap, key, currentValue, newValue);
2884 }
2885 }
2886 });
2887 if (changes.selection) {
2888 const selection = changes.selection;
2889 setTimeout(() => {
2890 updateSelectionHistory(ydoc, selection);
2891 }, 0);
2892 }
2893 }
2894 function mergeContentWithoutBlocks(ymap, rawContent, cursorPosition) {
2895 let currentBlocks = ymap.get("blocks");
2896 if (!(currentBlocks instanceof import_sync14.Y.Array)) {
2897 currentBlocks = new import_sync14.Y.Array();
2898 ymap.set("blocks", currentBlocks);
2899 }
2900 mergeCrdtBlocks(
2901 currentBlocks,
2902 (0, import_blocks3.parse)(rawContent),
2903 cursorPosition,
2904 { preserveClientIds: true }
2905 );
2906 }
2907 function parseCursorSelection(selection) {
2908 const selectionStart = selection?.selectionStart;
2909 return selectionStart?.clientId && selectionStart.attributeKey && "number" === typeof selectionStart.offset && Number.isInteger(selectionStart.offset) ? {
2910 attributeKey: selectionStart.attributeKey,
2911 clientId: selectionStart.clientId,
2912 offset: asRichTextOffset(selectionStart.offset)
2913 } : null;
2914 }
2915 function defaultGetChangesFromCRDTDoc(crdtDoc) {
2916 return getRootMap(crdtDoc, CRDT_RECORD_MAP_KEY).toJSON();
2917 }
2918 function getPostChangesFromCRDTDoc(ydoc, editedRecord, syncedProperties) {
2919 const ymap = getRootMap(ydoc, CRDT_RECORD_MAP_KEY);
2920 let allowedMetaChanges = {};
2921 const changes = Object.fromEntries(
2922 Object.entries(ymap.toJSON()).filter(([key, newValue]) => {
2923 if (!syncedProperties.has(key)) {
2924 return false;
2925 }
2926 const currentValue = editedRecord[key];
2927 switch (key) {
2928 case "blocks": {
2929 if (ydoc.meta?.get(CRDT_DOC_META_PERSISTENCE_KEY) && editedRecord.content) {
2930 const blocksJson = ymap.get("blocks")?.toJSON() ?? [];
2931 return (0, import_blocks3.__unstableSerializeAndClean)(blocksJson).trim() !== getRawValue(editedRecord.content);
2932 }
2933 return true;
2934 }
2935 case "date": {
2936 const currentDateIsFloating = null === currentValue || editedRecord.modified === currentValue;
2937 if (currentDateIsFloating) {
2938 return false;
2939 }
2940 return haveValuesChanged(currentValue, newValue);
2941 }
2942 case "meta": {
2943 const currentMeta = currentValue ?? {};
2944 allowedMetaChanges = Object.fromEntries(
2945 Object.entries(newValue ?? {}).filter(
2946 ([metaKey]) => {
2947 if (disallowedPostMetaKeys.has(metaKey)) {
2948 return false;
2949 }
2950 return metaKey in currentMeta;
2951 }
2952 )
2953 );
2954 const mergedValue = {
2955 ...currentMeta,
2956 ...allowedMetaChanges
2957 };
2958 return haveValuesChanged(currentValue, mergedValue);
2959 }
2960 case "status": {
2961 if ("auto-draft" === newValue) {
2962 return false;
2963 }
2964 return haveValuesChanged(currentValue, newValue);
2965 }
2966 case "content":
2967 case "excerpt":
2968 case "title": {
2969 return haveValuesChanged(
2970 getRawValue(currentValue),
2971 newValue
2972 );
2973 }
2974 // Add support for additional data types here.
2975 default: {
2976 return haveValuesChanged(currentValue, newValue);
2977 }
2978 }
2979 })
2980 );
2981 if (changes.blocks) {
2982 changes.blocks = deserializeBlockAttributes(
2983 changes.blocks
2984 );
2985 }
2986 if (changes.blocks && !changes.content) {
2987 const capturedBlocks = changes.blocks;
2988 changes.content = () => (0, import_blocks3.__unstableSerializeAndClean)(capturedBlocks);
2989 }
2990 if ("object" === typeof changes.meta) {
2991 changes.meta = {
2992 ...editedRecord.meta,
2993 ...allowedMetaChanges
2994 };
2995 }
2996 const selectionHistory = getSelectionHistory(ydoc);
2997 const shiftedSelection = getShiftedSelection(ydoc, selectionHistory);
2998 if (shiftedSelection) {
2999 changes.selection = {
3000 ...shiftedSelection,
3001 initialPosition: 0
3002 };
3003 }
3004 return changes;
3005 }
3006 var defaultSyncConfig = {
3007 applyChangesToCRDTDoc: defaultApplyChangesToCRDTDoc,
3008 createAwareness: (ydoc) => new BaseAwareness(ydoc),
3009 getChangesFromCRDTDoc: defaultGetChangesFromCRDTDoc
3010 };
3011 var defaultCollectionSyncConfig = {
3012 applyChangesToCRDTDoc: () => {
3013 },
3014 getChangesFromCRDTDoc: () => ({}),
3015 shouldSync: (_, objectId) => null === objectId
3016 };
3017 function getRawValue(value) {
3018 if ("string" === typeof value) {
3019 return value;
3020 }
3021 if (value && "object" === typeof value && "raw" in value && "string" === typeof value.raw) {
3022 return value.raw;
3023 }
3024 return void 0;
3025 }
3026 function haveValuesChanged(currentValue, newValue) {
3027 return !(0, import_es63.default)(currentValue, newValue);
3028 }
3029 function updateMapValue(map, key, currentValue, newValue) {
3030 if (void 0 === newValue) {
3031 map.delete(key);
3032 return;
3033 }
3034 if (haveValuesChanged(currentValue, newValue)) {
3035 map.set(key, newValue);
3036 }
3037 }
3038
3039 // packages/core-data/build-module/entities.mjs
3040 var DEFAULT_ENTITY_KEY = "id";
3041 var POST_RAW_ATTRIBUTES = ["title", "excerpt", "content"];
3042 var blocksTransientEdits = {
3043 blocks: {
3044 read: (record) => (0, import_blocks4.parse)(record.content?.raw ?? ""),
3045 write: (record) => ({
3046 content: (0, import_blocks4.__unstableSerializeAndClean)(record.blocks)
3047 })
3048 }
3049 };
3050 var rootEntitiesConfig = [
3051 {
3052 label: (0, import_i18n.__)("Base"),
3053 kind: "root",
3054 key: false,
3055 name: "__unstableBase",
3056 baseURL: "/",
3057 baseURLParams: {
3058 // Please also change the preload path when changing this.
3059 // @see lib/compat/wordpress-7.1/preload.php
3060 _fields: [
3061 "description",
3062 "gmt_offset",
3063 "home",
3064 "image_sizes",
3065 "image_size_threshold",
3066 "name",
3067 "site_icon",
3068 "site_icon_url",
3069 "site_logo",
3070 "timezone_string",
3071 "url",
3072 "page_for_posts",
3073 "page_on_front",
3074 "show_on_front"
3075 ].join(",")
3076 },
3077 // The entity doesn't support selecting multiple records.
3078 // The property is maintained for backward compatibility.
3079 plural: "__unstableBases",
3080 supportsPagination: false
3081 },
3082 {
3083 label: (0, import_i18n.__)("Post Type"),
3084 name: "postType",
3085 kind: "root",
3086 key: "slug",
3087 baseURL: "/wp/v2/types",
3088 baseURLParams: { context: "edit" },
3089 plural: "postTypes",
3090 supportsPagination: false
3091 },
3092 {
3093 name: "media",
3094 kind: "root",
3095 baseURL: "/wp/v2/media",
3096 baseURLParams: { context: "edit" },
3097 plural: "mediaItems",
3098 label: (0, import_i18n.__)("Media"),
3099 rawAttributes: ["caption", "title", "description"],
3100 supportsPagination: true
3101 },
3102 {
3103 name: "taxonomy",
3104 kind: "root",
3105 key: "slug",
3106 baseURL: "/wp/v2/taxonomies",
3107 baseURLParams: { context: "edit" },
3108 plural: "taxonomies",
3109 label: (0, import_i18n.__)("Taxonomy"),
3110 supportsPagination: false
3111 },
3112 {
3113 name: "sidebar",
3114 kind: "root",
3115 baseURL: "/wp/v2/sidebars",
3116 baseURLParams: { context: "edit" },
3117 plural: "sidebars",
3118 transientEdits: { blocks: true },
3119 label: (0, import_i18n.__)("Widget areas"),
3120 supportsPagination: false
3121 },
3122 {
3123 name: "widget",
3124 kind: "root",
3125 baseURL: "/wp/v2/widgets",
3126 baseURLParams: { context: "edit" },
3127 plural: "widgets",
3128 transientEdits: { blocks: true },
3129 label: (0, import_i18n.__)("Widgets"),
3130 supportsPagination: false
3131 },
3132 {
3133 name: "widgetType",
3134 kind: "root",
3135 baseURL: "/wp/v2/widget-types",
3136 baseURLParams: { context: "edit" },
3137 plural: "widgetTypes",
3138 label: (0, import_i18n.__)("Widget types"),
3139 supportsPagination: false
3140 },
3141 {
3142 label: (0, import_i18n.__)("User"),
3143 name: "user",
3144 kind: "root",
3145 baseURL: "/wp/v2/users",
3146 getTitle: (record) => record?.name || record?.slug,
3147 baseURLParams: { context: "edit" },
3148 plural: "users",
3149 supportsPagination: true
3150 },
3151 {
3152 name: "comment",
3153 kind: "root",
3154 baseURL: "/wp/v2/comments",
3155 baseURLParams: { context: "edit" },
3156 plural: "comments",
3157 label: (0, import_i18n.__)("Comment"),
3158 supportsPagination: true,
3159 syncConfig: defaultCollectionSyncConfig
3160 },
3161 {
3162 name: "menu",
3163 kind: "root",
3164 baseURL: "/wp/v2/menus",
3165 baseURLParams: { context: "edit" },
3166 plural: "menus",
3167 label: (0, import_i18n.__)("Menu"),
3168 supportsPagination: true
3169 },
3170 {
3171 name: "menuItem",
3172 kind: "root",
3173 baseURL: "/wp/v2/menu-items",
3174 baseURLParams: { context: "edit" },
3175 plural: "menuItems",
3176 label: (0, import_i18n.__)("Menu Item"),
3177 rawAttributes: ["title"],
3178 supportsPagination: true
3179 },
3180 {
3181 name: "menuLocation",
3182 kind: "root",
3183 baseURL: "/wp/v2/menu-locations",
3184 baseURLParams: { context: "edit" },
3185 plural: "menuLocations",
3186 label: (0, import_i18n.__)("Menu Location"),
3187 key: "name",
3188 supportsPagination: false
3189 },
3190 {
3191 label: (0, import_i18n.__)("Global Styles"),
3192 name: "globalStyles",
3193 kind: "root",
3194 baseURL: "/wp/v2/global-styles",
3195 baseURLParams: { context: "edit" },
3196 plural: "globalStylesVariations",
3197 // Should be different from name.
3198 getTitle: () => (0, import_i18n.__)("Custom Styles"),
3199 getRevisionsUrl: (parentId, revisionId) => `/wp/v2/global-styles/${parentId}/revisions${revisionId ? "/" + revisionId : ""}`,
3200 supportsPagination: true
3201 },
3202 {
3203 label: (0, import_i18n.__)("Themes"),
3204 name: "theme",
3205 kind: "root",
3206 baseURL: "/wp/v2/themes",
3207 baseURLParams: { context: "edit" },
3208 plural: "themes",
3209 key: "stylesheet",
3210 supportsPagination: false
3211 },
3212 {
3213 label: (0, import_i18n.__)("Plugins"),
3214 name: "plugin",
3215 kind: "root",
3216 baseURL: "/wp/v2/plugins",
3217 baseURLParams: { context: "edit" },
3218 plural: "plugins",
3219 key: "plugin",
3220 supportsPagination: false
3221 },
3222 {
3223 label: (0, import_i18n.__)("Status"),
3224 name: "status",
3225 kind: "root",
3226 baseURL: "/wp/v2/statuses",
3227 baseURLParams: { context: "edit" },
3228 plural: "statuses",
3229 key: "slug",
3230 supportsPagination: false
3231 },
3232 {
3233 label: (0, import_i18n.__)("Registered Templates"),
3234 name: "registeredTemplate",
3235 kind: "root",
3236 baseURL: "/wp/v2/registered-templates",
3237 key: "id",
3238 supportsPagination: false
3239 },
3240 {
3241 label: (0, import_i18n.__)("Font Collections"),
3242 name: "fontCollection",
3243 kind: "root",
3244 baseURL: "/wp/v2/font-collections",
3245 baseURLParams: { context: "view" },
3246 plural: "fontCollections",
3247 key: "slug",
3248 supportsPagination: true
3249 },
3250 {
3251 label: (0, import_i18n.__)("Icons"),
3252 name: "icon",
3253 kind: "root",
3254 baseURL: "/wp/v2/icons",
3255 baseURLParams: { context: "view" },
3256 plural: "icons",
3257 key: "name",
3258 supportsPagination: false
3259 }
3260 ];
3261 var deprecatedEntities = {
3262 root: {
3263 media: {
3264 since: "6.9",
3265 alternative: {
3266 kind: "postType",
3267 name: "attachment"
3268 }
3269 }
3270 }
3271 };
3272 var additionalEntityConfigLoaders = [
3273 { kind: "postType", loadEntities: loadPostTypeEntities },
3274 { kind: "taxonomy", loadEntities: loadTaxonomyEntities },
3275 {
3276 kind: "root",
3277 name: "site",
3278 plural: "sites",
3279 loadEntities: loadSiteEntity
3280 }
3281 ];
3282 var prePersistPostType = async (persistedRecord, edits, name, isTemplate) => {
3283 const newEdits = {};
3284 if (!isTemplate && persistedRecord?.status === "auto-draft") {
3285 if (!edits.status && !newEdits.status) {
3286 newEdits.status = "draft";
3287 }
3288 if ((!edits.title || edits.title === "Auto Draft") && !newEdits.title && (!persistedRecord?.title || persistedRecord?.title === "Auto Draft")) {
3289 newEdits.title = "";
3290 }
3291 }
3292 if (persistedRecord) {
3293 const objectType = `postType/${name}`;
3294 const objectId = persistedRecord.id;
3295 const serializedDoc = getSyncManager()?.createPersistedCRDTDoc(
3296 objectType,
3297 objectId
3298 );
3299 if (serializedDoc) {
3300 newEdits.meta = {
3301 ...edits.meta,
3302 [POST_META_KEY_FOR_CRDT_DOC_PERSISTENCE]: serializedDoc
3303 };
3304 }
3305 }
3306 return newEdits;
3307 };
3308 async function loadPostTypeEntities() {
3309 const postTypesPromise = (0, import_api_fetch2.default)({ path: "/wp/v2/types?context=view" });
3310 const taxonomiesPromise = window._wpCollaborationEnabled ? (0, import_api_fetch2.default)({ path: "/wp/v2/taxonomies?context=view" }) : Promise.resolve({});
3311 const [postTypes, taxonomies] = await Promise.all([
3312 postTypesPromise,
3313 taxonomiesPromise
3314 ]);
3315 return Object.entries(postTypes ?? {}).map(([name, postType]) => {
3316 const isTemplate = ["wp_template", "wp_template_part"].includes(
3317 name
3318 );
3319 const namespace = postType?.rest_namespace ?? "wp/v2";
3320 const syncedProperties = /* @__PURE__ */ new Set([
3321 "author",
3322 "blocks",
3323 "content",
3324 "comment_status",
3325 "date",
3326 "excerpt",
3327 "featured_media",
3328 "format",
3329 "meta",
3330 "ping_status",
3331 "slug",
3332 "status",
3333 "sticky",
3334 "template",
3335 "title",
3336 ...postType.taxonomies?.map((taxonomy) => taxonomies?.[taxonomy]?.rest_base)?.filter(Boolean) ?? []
3337 ]);
3338 const entity2 = {
3339 kind: "postType",
3340 baseURL: `/${namespace}/${postType.rest_base}`,
3341 baseURLParams: { context: "edit" },
3342 name,
3343 label: postType.name,
3344 transientEdits: {
3345 ...blocksTransientEdits,
3346 selection: true
3347 },
3348 mergedEdits: { meta: true },
3349 rawAttributes: POST_RAW_ATTRIBUTES,
3350 getTitle: (record) => record?.title?.rendered || record?.title || (isTemplate ? capitalCase(record.slug ?? "") : String(record.id)),
3351 __unstablePrePersist: (persistedRecord, edits) => prePersistPostType(persistedRecord, edits, name, isTemplate),
3352 __unstable_rest_base: postType.rest_base,
3353 supportsPagination: true,
3354 getRevisionsUrl: (parentId, revisionId) => `/${namespace}/${postType.rest_base}/${parentId}/revisions${revisionId ? "/" + revisionId : ""}`,
3355 revisionKey: isTemplate && !window?.__experimentalTemplateActivate ? "wp_id" : DEFAULT_ENTITY_KEY
3356 };
3357 entity2.syncConfig = {
3358 // Save a CRDT document with this entity
3359 supportsPersistence: true,
3360 /**
3361 * Apply changes from the local editor to the local CRDT document so
3362 * that those changes can be synced to other peers (via the provider).
3363 *
3364 * @param {import('@wordpress/sync').CRDTDoc} crdtDoc
3365 * @param {Partial< import('@wordpress/sync').ObjectData >} changes
3366 * @return {void}
3367 */
3368 applyChangesToCRDTDoc: (crdtDoc, changes) => applyPostChangesToCRDTDoc(crdtDoc, changes, syncedProperties),
3369 /**
3370 * Create the awareness instance for the entity's CRDT document.
3371 *
3372 * @param {import('@wordpress/sync').CRDTDoc} ydoc
3373 * @param {import('@wordpress/sync').ObjectID} objectId
3374 * @return {import('@wordpress/sync').Awareness} Awareness instance
3375 */
3376 createAwareness: (ydoc, objectId) => {
3377 const kind = "postType";
3378 const id = parseInt(objectId, 10);
3379 return new PostEditorAwareness(ydoc, kind, name, id);
3380 },
3381 /**
3382 * Extract changes from a CRDT document that can be used to update the
3383 * local editor state.
3384 *
3385 * @param {import('@wordpress/sync').CRDTDoc} crdtDoc
3386 * @param {import('@wordpress/sync').ObjectData} editedRecord
3387 * @return {Partial< import('@wordpress/sync').ObjectData >} Changes to record
3388 */
3389 getChangesFromCRDTDoc: (crdtDoc, editedRecord) => getPostChangesFromCRDTDoc(
3390 crdtDoc,
3391 editedRecord,
3392 syncedProperties
3393 ),
3394 /**
3395 * Extract changes from a CRDT document that can be used to update the
3396 * local editor state.
3397 *
3398 * @param {import('@wordpress/sync').ObjectData} record
3399 * @return {Partial< import('@wordpress/sync').ObjectData >} Changes to record
3400 */
3401 getPersistedCRDTDoc: (record) => {
3402 return record?.meta?.[POST_META_KEY_FOR_CRDT_DOC_PERSISTENCE] || null;
3403 }
3404 };
3405 return entity2;
3406 });
3407 }
3408 async function loadTaxonomyEntities() {
3409 const taxonomies = await (0, import_api_fetch2.default)({
3410 path: "/wp/v2/taxonomies?context=view"
3411 });
3412 return Object.entries(taxonomies ?? {}).map(([name, taxonomy]) => {
3413 const namespace = taxonomy?.rest_namespace ?? "wp/v2";
3414 const entity2 = {
3415 kind: "taxonomy",
3416 baseURL: `/${namespace}/${taxonomy.rest_base}`,
3417 baseURLParams: { context: "edit" },
3418 name,
3419 label: taxonomy.name,
3420 getTitle: (record) => record?.name,
3421 supportsPagination: true
3422 };
3423 entity2.syncConfig = defaultSyncConfig;
3424 return entity2;
3425 });
3426 }
3427 async function loadSiteEntity() {
3428 const entity2 = {
3429 label: (0, import_i18n.__)("Site"),
3430 name: "site",
3431 kind: "root",
3432 key: false,
3433 baseURL: "/wp/v2/settings",
3434 supportsPagination: false,
3435 meta: {}
3436 };
3437 const site = await (0, import_api_fetch2.default)({
3438 path: entity2.baseURL,
3439 method: "OPTIONS"
3440 });
3441 const labels = {};
3442 Object.entries(site?.schema?.properties ?? {}).forEach(
3443 ([key, value]) => {
3444 if (typeof value === "object" && value.title) {
3445 labels[key] = value.title;
3446 }
3447 }
3448 );
3449 return [{ ...entity2, meta: { labels } }];
3450 }
3451 var getMethodName = (kind, name, prefix = "get") => {
3452 const kindPrefix = kind === "root" ? "" : pascalCase(kind);
3453 const suffix = pascalCase(name);
3454 return `${prefix}${kindPrefix}${suffix}`;
3455 };
3456
3457 // packages/core-data/build-module/queried-data/reducer.mjs
3458 function getContextFromAction(action) {
3459 const { query } = action;
3460 if (!query) {
3461 return "default";
3462 }
3463 const queryParts = get_query_parts_default(query);
3464 return queryParts.context;
3465 }
3466 function getMergedItemIds(itemIds = [], nextItemIds, { page = 1, offset, perPage = 10 } = {}) {
3467 if (perPage === -1) {
3468 return nextItemIds;
3469 }
3470 const nextItemIdsStartIndex = offset ?? (page - 1) * perPage;
3471 const nextItemIdsRange = Math.max(perPage, nextItemIds.length);
3472 const size = Math.max(
3473 itemIds.length,
3474 nextItemIdsStartIndex + nextItemIds.length
3475 );
3476 const mergedItemIds = new Array(size);
3477 for (let i = 0; i < size; i++) {
3478 const isInNextItemsRange = i >= nextItemIdsStartIndex && i < nextItemIdsStartIndex + nextItemIdsRange;
3479 if (isInNextItemsRange) {
3480 mergedItemIds[i] = nextItemIds[i - nextItemIdsStartIndex];
3481 } else {
3482 mergedItemIds[i] = itemIds[i];
3483 }
3484 }
3485 return mergedItemIds;
3486 }
3487 function removeEntitiesById(entities2, ids) {
3488 return Object.fromEntries(
3489 Object.entries(entities2).filter(
3490 ([id]) => !ids.some((itemId) => {
3491 if (Number.isInteger(itemId)) {
3492 return itemId === +id;
3493 }
3494 return itemId === id;
3495 })
3496 )
3497 );
3498 }
3499 function items(state = {}, action) {
3500 switch (action.type) {
3501 case "RECEIVE_ITEMS": {
3502 const context = getContextFromAction(action);
3503 const key = action.key || DEFAULT_ENTITY_KEY;
3504 const itemsList = Array.isArray(action.items) ? action.items : [action.items];
3505 return {
3506 ...state,
3507 [context]: {
3508 ...state[context],
3509 ...Object.fromEntries(
3510 itemsList.map((item) => [
3511 item?.[key],
3512 conservativeMapItem(
3513 state?.[context]?.[item?.[key]],
3514 item
3515 )
3516 ])
3517 )
3518 }
3519 };
3520 }
3521 case "REMOVE_ITEMS":
3522 return Object.fromEntries(
3523 Object.entries(state).map(([itemId, contextState]) => [
3524 itemId,
3525 removeEntitiesById(contextState, action.itemIds)
3526 ])
3527 );
3528 }
3529 return state;
3530 }
3531 function itemIsComplete(state = {}, action) {
3532 switch (action.type) {
3533 case "RECEIVE_ITEMS": {
3534 const context = getContextFromAction(action);
3535 const { query, key = DEFAULT_ENTITY_KEY } = action;
3536 const itemsList = Array.isArray(action.items) ? action.items : [action.items];
3537 const queryParts = query ? get_query_parts_default(query) : {};
3538 const isCompleteQuery = !query || !Array.isArray(queryParts.fields);
3539 return {
3540 ...state,
3541 [context]: {
3542 ...state[context],
3543 ...itemsList.reduce((result, item) => {
3544 const itemId = item?.[key];
3545 result[itemId] = state?.[context]?.[itemId] || isCompleteQuery;
3546 return result;
3547 }, {})
3548 }
3549 };
3550 }
3551 case "REMOVE_ITEMS":
3552 return Object.fromEntries(
3553 Object.entries(state).map(([itemId, contextState]) => [
3554 itemId,
3555 removeEntitiesById(contextState, action.itemIds)
3556 ])
3557 );
3558 }
3559 return state;
3560 }
3561 var receiveQueries = (0, import_compose.compose)([
3562 // Limit to matching action type so we don't attempt to replace action on
3563 // an unhandled action.
3564 if_matching_action_default((action) => "query" in action),
3565 // Inject query parts into action for use both in `keyedReducer` and reducer.
3566 replace_action_default((action) => {
3567 if (action.query) {
3568 return {
3569 ...action,
3570 ...get_query_parts_default(action.query)
3571 };
3572 }
3573 return action;
3574 }),
3575 (0, import_data6.keyedReducer)("context"),
3576 // Queries shape is shared, but keyed by query `stableKey` part. Original
3577 // reducer tracks only a single query object.
3578 (0, import_data6.keyedReducer)("stableKey")
3579 ])((state = {}, action) => {
3580 if (action.type !== "RECEIVE_ITEMS") {
3581 return state;
3582 }
3583 if (!Array.isArray(action.items)) {
3584 return state;
3585 }
3586 const key = action.key ?? DEFAULT_ENTITY_KEY;
3587 return {
3588 itemIds: getMergedItemIds(
3589 state.itemIds,
3590 action.items.map((item) => item?.[key]).filter(Boolean),
3591 {
3592 page: action.page,
3593 offset: action.offset,
3594 perPage: action.perPage
3595 }
3596 ),
3597 meta: action.meta
3598 };
3599 });
3600 var queries = (state = {}, action) => {
3601 switch (action.type) {
3602 case "RECEIVE_ITEMS":
3603 return receiveQueries(state, action);
3604 case "REMOVE_ITEMS":
3605 const removedItems = action.itemIds.reduce((result, itemId) => {
3606 result[itemId] = true;
3607 return result;
3608 }, {});
3609 return Object.fromEntries(
3610 Object.entries(state).map(
3611 ([queryGroup, contextQueries]) => [
3612 queryGroup,
3613 Object.fromEntries(
3614 Object.entries(contextQueries).map(
3615 ([query, queryItems]) => [
3616 query,
3617 {
3618 ...queryItems,
3619 itemIds: queryItems.itemIds.filter(
3620 (queryId) => !removedItems[queryId]
3621 )
3622 }
3623 ]
3624 )
3625 )
3626 ]
3627 )
3628 );
3629 default:
3630 return state;
3631 }
3632 };
3633 var reducer_default = (0, import_data6.combineReducers)({
3634 items,
3635 itemIsComplete,
3636 queries
3637 });
3638
3639 // packages/core-data/build-module/reducer.mjs
3640 function users(state = { byId: {}, queries: {} }, action) {
3641 switch (action.type) {
3642 case "RECEIVE_USER_QUERY":
3643 return {
3644 byId: {
3645 ...state.byId,
3646 // Key users by their ID.
3647 ...action.users.reduce(
3648 (newUsers, user) => ({
3649 ...newUsers,
3650 [user.id]: user
3651 }),
3652 {}
3653 )
3654 },
3655 queries: {
3656 ...state.queries,
3657 [action.queryID]: action.users.map((user) => user.id)
3658 }
3659 };
3660 }
3661 return state;
3662 }
3663 function currentUser(state = {}, action) {
3664 switch (action.type) {
3665 case "RECEIVE_CURRENT_USER":
3666 return action.currentUser;
3667 }
3668 return state;
3669 }
3670 function currentTheme(state = void 0, action) {
3671 switch (action.type) {
3672 case "RECEIVE_CURRENT_THEME":
3673 return action.currentTheme.stylesheet;
3674 }
3675 return state;
3676 }
3677 function currentGlobalStylesId(state = void 0, action) {
3678 switch (action.type) {
3679 case "RECEIVE_CURRENT_GLOBAL_STYLES_ID":
3680 return action.id;
3681 }
3682 return state;
3683 }
3684 function themeBaseGlobalStyles(state = {}, action) {
3685 switch (action.type) {
3686 case "RECEIVE_THEME_GLOBAL_STYLES":
3687 return {
3688 ...state,
3689 [action.stylesheet]: action.globalStyles
3690 };
3691 }
3692 return state;
3693 }
3694 function themeGlobalStyleVariations(state = {}, action) {
3695 switch (action.type) {
3696 case "RECEIVE_THEME_GLOBAL_STYLE_VARIATIONS":
3697 return {
3698 ...state,
3699 [action.stylesheet]: action.variations
3700 };
3701 }
3702 return state;
3703 }
3704 var withMultiEntityRecordEdits = (reducer) => (state, action) => {
3705 if (action.type === "UNDO" || action.type === "REDO") {
3706 const { record } = action;
3707 let newState = state;
3708 record.forEach(({ id: { kind, name, recordId }, changes }) => {
3709 newState = reducer(newState, {
3710 type: "EDIT_ENTITY_RECORD",
3711 kind,
3712 name,
3713 recordId,
3714 edits: Object.entries(changes).reduce(
3715 (acc, [key, value]) => {
3716 acc[key] = action.type === "UNDO" ? value.from : value.to;
3717 return acc;
3718 },
3719 {}
3720 )
3721 });
3722 });
3723 return newState;
3724 }
3725 return reducer(state, action);
3726 };
3727 function entity(entityConfig) {
3728 return (0, import_compose2.compose)([
3729 withMultiEntityRecordEdits,
3730 // Limit to matching action type so we don't attempt to replace action on
3731 // an unhandled action.
3732 if_matching_action_default(
3733 (action) => action.name && action.kind && action.name === entityConfig.name && action.kind === entityConfig.kind
3734 ),
3735 // Inject the entity config into the action.
3736 replace_action_default((action) => {
3737 return {
3738 key: entityConfig.key || DEFAULT_ENTITY_KEY,
3739 ...action
3740 };
3741 })
3742 ])(
3743 (0, import_data7.combineReducers)({
3744 queriedData: reducer_default,
3745 edits: (state = {}, action) => {
3746 switch (action.type) {
3747 case "RECEIVE_ITEMS":
3748 const context = action?.query?.context ?? "default";
3749 if (context !== "default") {
3750 return state;
3751 }
3752 const nextState = { ...state };
3753 const itemsList = Array.isArray(action.items) ? action.items : [action.items];
3754 for (const record of itemsList) {
3755 const recordId = record?.[action.key];
3756 const edits = nextState[recordId];
3757 if (!edits) {
3758 continue;
3759 }
3760 const nextEdits2 = Object.keys(edits).reduce(
3761 (acc, key) => {
3762 if (
3763 // Edits are the "raw" attribute values, but records may have
3764 // objects with more properties, so we use `get` here for the
3765 // comparison.
3766 !(0, import_es64.default)(
3767 edits[key],
3768 record[key]?.raw ?? record[key]
3769 ) && // Sometimes the server alters the sent value which means
3770 // we need to also remove the edits before the api request.
3771 (!action.persistedEdits || !(0, import_es64.default)(
3772 edits[key],
3773 action.persistedEdits[key]
3774 ))
3775 ) {
3776 acc[key] = edits[key];
3777 }
3778 return acc;
3779 },
3780 {}
3781 );
3782 if (Object.keys(nextEdits2).length) {
3783 nextState[recordId] = nextEdits2;
3784 } else {
3785 delete nextState[recordId];
3786 }
3787 }
3788 return nextState;
3789 case "EDIT_ENTITY_RECORD":
3790 const nextEdits = {
3791 ...state[action.recordId],
3792 ...action.edits
3793 };
3794 Object.keys(nextEdits).forEach((key) => {
3795 if (nextEdits[key] === void 0) {
3796 delete nextEdits[key];
3797 }
3798 });
3799 return {
3800 ...state,
3801 [action.recordId]: nextEdits
3802 };
3803 }
3804 return state;
3805 },
3806 saving: (state = {}, action) => {
3807 switch (action.type) {
3808 case "SAVE_ENTITY_RECORD_START":
3809 case "SAVE_ENTITY_RECORD_FINISH":
3810 return {
3811 ...state,
3812 [action.recordId]: {
3813 pending: action.type === "SAVE_ENTITY_RECORD_START",
3814 error: action.error,
3815 isAutosave: action.isAutosave
3816 }
3817 };
3818 }
3819 return state;
3820 },
3821 deleting: (state = {}, action) => {
3822 switch (action.type) {
3823 case "DELETE_ENTITY_RECORD_START":
3824 case "DELETE_ENTITY_RECORD_FINISH":
3825 return {
3826 ...state,
3827 [action.recordId]: {
3828 pending: action.type === "DELETE_ENTITY_RECORD_START",
3829 error: action.error
3830 }
3831 };
3832 }
3833 return state;
3834 },
3835 revisions: (state = {}, action) => {
3836 if (action.type === "RECEIVE_ITEM_REVISIONS") {
3837 const recordKey = action.recordKey;
3838 delete action.recordKey;
3839 const newState = reducer_default(state[recordKey], {
3840 ...action,
3841 type: "RECEIVE_ITEMS"
3842 });
3843 return {
3844 ...state,
3845 [recordKey]: newState
3846 };
3847 }
3848 if (action.type === "REMOVE_ITEMS") {
3849 return Object.fromEntries(
3850 Object.entries(state).filter(
3851 ([id]) => !action.itemIds.some((itemId) => {
3852 if (Number.isInteger(itemId)) {
3853 return itemId === +id;
3854 }
3855 return itemId === id;
3856 })
3857 )
3858 );
3859 }
3860 return state;
3861 }
3862 })
3863 );
3864 }
3865 function entitiesConfig(state = rootEntitiesConfig, action) {
3866 switch (action.type) {
3867 case "ADD_ENTITIES":
3868 return [...state, ...action.entities];
3869 }
3870 return state;
3871 }
3872 var entities = (state = {}, action) => {
3873 const newConfig = entitiesConfig(state.config, action);
3874 let entitiesDataReducer = state.reducer;
3875 if (!entitiesDataReducer || newConfig !== state.config) {
3876 const entitiesByKind = newConfig.reduce((acc, record) => {
3877 const { kind } = record;
3878 if (!acc[kind]) {
3879 acc[kind] = [];
3880 }
3881 acc[kind].push(record);
3882 return acc;
3883 }, {});
3884 entitiesDataReducer = (0, import_data7.combineReducers)(
3885 Object.fromEntries(
3886 Object.entries(entitiesByKind).map(
3887 ([kind, subEntities]) => {
3888 const kindReducer = (0, import_data7.combineReducers)(
3889 Object.fromEntries(
3890 subEntities.map((entityConfig) => [
3891 entityConfig.name,
3892 entity(entityConfig)
3893 ])
3894 )
3895 );
3896 return [kind, kindReducer];
3897 }
3898 )
3899 )
3900 );
3901 }
3902 const newData = entitiesDataReducer(state.records, action);
3903 if (newData === state.records && newConfig === state.config && entitiesDataReducer === state.reducer) {
3904 return state;
3905 }
3906 return {
3907 reducer: entitiesDataReducer,
3908 records: newData,
3909 config: newConfig
3910 };
3911 };
3912 function undoManager(state = (0, import_undo_manager.createUndoManager)()) {
3913 return state;
3914 }
3915 function syncUndoManagerState(state = { hasRedo: false, hasUndo: false }, action) {
3916 switch (action.type) {
3917 case "SYNC_UNDO_MANAGER_CHANGE":
3918 return {
3919 hasRedo: action.hasRedo,
3920 hasUndo: action.hasUndo
3921 };
3922 }
3923 return state;
3924 }
3925 function editsReference(state = {}, action) {
3926 switch (action.type) {
3927 case "EDIT_ENTITY_RECORD":
3928 case "UNDO":
3929 case "REDO":
3930 return {};
3931 }
3932 return state;
3933 }
3934 function embedPreviews(state = {}, action) {
3935 switch (action.type) {
3936 case "RECEIVE_EMBED_PREVIEW":
3937 const { url, preview } = action;
3938 return {
3939 ...state,
3940 [url]: preview
3941 };
3942 }
3943 return state;
3944 }
3945 function userPermissions(state = {}, action) {
3946 switch (action.type) {
3947 case "RECEIVE_USER_PERMISSION":
3948 return {
3949 ...state,
3950 [action.key]: action.isAllowed
3951 };
3952 case "RECEIVE_USER_PERMISSIONS":
3953 return {
3954 ...state,
3955 ...action.permissions
3956 };
3957 }
3958 return state;
3959 }
3960 function autosaves(state = {}, action) {
3961 switch (action.type) {
3962 case "RECEIVE_AUTOSAVES":
3963 const { postId, autosaves: autosavesData } = action;
3964 return {
3965 ...state,
3966 [postId]: autosavesData
3967 };
3968 }
3969 return state;
3970 }
3971 function blockPatterns(state = [], action) {
3972 switch (action.type) {
3973 case "RECEIVE_BLOCK_PATTERNS":
3974 return action.patterns;
3975 }
3976 return state;
3977 }
3978 function blockPatternCategories(state = [], action) {
3979 switch (action.type) {
3980 case "RECEIVE_BLOCK_PATTERN_CATEGORIES":
3981 return action.categories;
3982 }
3983 return state;
3984 }
3985 function userPatternCategories(state = [], action) {
3986 switch (action.type) {
3987 case "RECEIVE_USER_PATTERN_CATEGORIES":
3988 return action.patternCategories;
3989 }
3990 return state;
3991 }
3992 function navigationFallbackId(state = null, action) {
3993 switch (action.type) {
3994 case "RECEIVE_NAVIGATION_FALLBACK_ID":
3995 return action.fallbackId;
3996 }
3997 return state;
3998 }
3999 function themeGlobalStyleRevisions(state = {}, action) {
4000 switch (action.type) {
4001 case "RECEIVE_THEME_GLOBAL_STYLE_REVISIONS":
4002 return {
4003 ...state,
4004 [action.currentId]: action.revisions
4005 };
4006 }
4007 return state;
4008 }
4009 function defaultTemplates(state = {}, action) {
4010 switch (action.type) {
4011 case "RECEIVE_DEFAULT_TEMPLATE":
4012 return {
4013 ...state,
4014 [JSON.stringify(action.query)]: action.templateId
4015 };
4016 }
4017 return state;
4018 }
4019 function registeredPostMeta(state = {}, action) {
4020 switch (action.type) {
4021 case "RECEIVE_REGISTERED_POST_META":
4022 return {
4023 ...state,
4024 [action.postType]: action.registeredPostMeta
4025 };
4026 }
4027 return state;
4028 }
4029 function editorSettings(state = null, action) {
4030 switch (action.type) {
4031 case "RECEIVE_EDITOR_SETTINGS":
4032 return action.settings;
4033 }
4034 return state;
4035 }
4036 function editorAssets(state = null, action) {
4037 switch (action.type) {
4038 case "RECEIVE_EDITOR_ASSETS":
4039 return action.assets;
4040 }
4041 return state;
4042 }
4043 function syncConnectionStatuses(state = {}, action) {
4044 switch (action.type) {
4045 case "SET_SYNC_CONNECTION_STATUS": {
4046 const key = `${action.kind}/${action.name}:${action.key}`;
4047 return {
4048 ...state,
4049 [key]: action.status
4050 };
4051 }
4052 case "CLEAR_SYNC_CONNECTION_STATUS": {
4053 const key = `${action.kind}/${action.name}:${action.key}`;
4054 const { [key]: _, ...rest } = state;
4055 return rest;
4056 }
4057 }
4058 return state;
4059 }
4060 function collaborationSupported(state = true, action) {
4061 switch (action.type) {
4062 case "SET_COLLABORATION_SUPPORTED":
4063 return action.supported;
4064 case "SET_SYNC_CONNECTION_STATUS":
4065 if (ConnectionErrorCode.DOCUMENT_SIZE_LIMIT_EXCEEDED === action.status?.error?.code) {
4066 return false;
4067 }
4068 return state;
4069 }
4070 return state;
4071 }
4072 function viewConfigs(state = {}, action) {
4073 switch (action.type) {
4074 case "RECEIVE_VIEW_CONFIG":
4075 return {
4076 ...state,
4077 [`${action.kind}/${action.name}`]: action.config
4078 };
4079 }
4080 return state;
4081 }
4082 var reducer_default2 = (0, import_data7.combineReducers)({
4083 users,
4084 currentTheme,
4085 currentGlobalStylesId,
4086 currentUser,
4087 themeGlobalStyleVariations,
4088 themeBaseGlobalStyles,
4089 themeGlobalStyleRevisions,
4090 entities,
4091 editsReference,
4092 syncUndoManagerState,
4093 undoManager,
4094 embedPreviews,
4095 userPermissions,
4096 autosaves,
4097 blockPatterns,
4098 blockPatternCategories,
4099 userPatternCategories,
4100 navigationFallbackId,
4101 defaultTemplates,
4102 registeredPostMeta,
4103 editorSettings,
4104 editorAssets,
4105 syncConnectionStatuses,
4106 collaborationSupported,
4107 viewConfigs
4108 });
4109
4110 // packages/core-data/build-module/selectors.mjs
4111 var selectors_exports = {};
4112 __export(selectors_exports, {
4113 __experimentalGetCurrentGlobalStylesId: () => __experimentalGetCurrentGlobalStylesId,
4114 __experimentalGetCurrentThemeBaseGlobalStyles: () => __experimentalGetCurrentThemeBaseGlobalStyles,
4115 __experimentalGetCurrentThemeGlobalStylesVariations: () => __experimentalGetCurrentThemeGlobalStylesVariations,
4116 __experimentalGetDirtyEntityRecords: () => __experimentalGetDirtyEntityRecords,
4117 __experimentalGetEntitiesBeingSaved: () => __experimentalGetEntitiesBeingSaved,
4118 __experimentalGetEntityRecordNoResolver: () => __experimentalGetEntityRecordNoResolver,
4119 canUser: () => canUser,
4120 canUserEditEntityRecord: () => canUserEditEntityRecord,
4121 getAuthors: () => getAuthors,
4122 getAutosave: () => getAutosave,
4123 getAutosaves: () => getAutosaves,
4124 getBlockPatternCategories: () => getBlockPatternCategories,
4125 getBlockPatterns: () => getBlockPatterns,
4126 getCurrentTheme: () => getCurrentTheme,
4127 getCurrentThemeGlobalStylesRevisions: () => getCurrentThemeGlobalStylesRevisions,
4128 getCurrentUser: () => getCurrentUser,
4129 getDefaultTemplateId: () => getDefaultTemplateId,
4130 getEditedEntityRecord: () => getEditedEntityRecord,
4131 getEmbedPreview: () => getEmbedPreview,
4132 getEntitiesByKind: () => getEntitiesByKind,
4133 getEntitiesConfig: () => getEntitiesConfig,
4134 getEntity: () => getEntity,
4135 getEntityConfig: () => getEntityConfig,
4136 getEntityRecord: () => getEntityRecord,
4137 getEntityRecordEdits: () => getEntityRecordEdits,
4138 getEntityRecordNonTransientEdits: () => getEntityRecordNonTransientEdits,
4139 getEntityRecords: () => getEntityRecords,
4140 getEntityRecordsTotalItems: () => getEntityRecordsTotalItems,
4141 getEntityRecordsTotalPages: () => getEntityRecordsTotalPages,
4142 getLastEntityDeleteError: () => getLastEntityDeleteError,
4143 getLastEntitySaveError: () => getLastEntitySaveError,
4144 getRawEntityRecord: () => getRawEntityRecord,
4145 getRedoEdit: () => getRedoEdit,
4146 getReferenceByDistinctEdits: () => getReferenceByDistinctEdits,
4147 getRevision: () => getRevision,
4148 getRevisions: () => getRevisions,
4149 getThemeSupports: () => getThemeSupports,
4150 getUndoEdit: () => getUndoEdit,
4151 getUserPatternCategories: () => getUserPatternCategories,
4152 getUserQueryResults: () => getUserQueryResults,
4153 hasEditsForEntityRecord: () => hasEditsForEntityRecord,
4154 hasEntityRecord: () => hasEntityRecord,
4155 hasEntityRecords: () => hasEntityRecords,
4156 hasFetchedAutosaves: () => hasFetchedAutosaves,
4157 hasRedo: () => hasRedo,
4158 hasRevision: () => hasRevision,
4159 hasUndo: () => hasUndo,
4160 isAutosavingEntityRecord: () => isAutosavingEntityRecord,
4161 isDeletingEntityRecord: () => isDeletingEntityRecord,
4162 isPreviewEmbedFallback: () => isPreviewEmbedFallback,
4163 isRequestingEmbedPreview: () => isRequestingEmbedPreview,
4164 isSavingEntityRecord: () => isSavingEntityRecord
4165 });
4166 var import_data9 = __toESM(require_data(), 1);
4167 var import_url2 = __toESM(require_url(), 1);
4168 var import_deprecated2 = __toESM(require_deprecated(), 1);
4169
4170 // packages/core-data/build-module/private-selectors.mjs
4171 var private_selectors_exports = {};
4172 __export(private_selectors_exports, {
4173 getBlockPatternsForPostType: () => getBlockPatternsForPostType,
4174 getEditorAssets: () => getEditorAssets,
4175 getEditorSettings: () => getEditorSettings,
4176 getEntityRecordPermissions: () => getEntityRecordPermissions,
4177 getEntityRecordsPermissions: () => getEntityRecordsPermissions,
4178 getHomePage: () => getHomePage,
4179 getNavigationFallbackId: () => getNavigationFallbackId,
4180 getPostsPageId: () => getPostsPageId,
4181 getRegisteredPostMeta: () => getRegisteredPostMeta,
4182 getSyncConnectionStatus: () => getSyncConnectionStatus,
4183 getTemplateId: () => getTemplateId,
4184 getUndoManager: () => getUndoManager,
4185 getViewConfig: () => getViewConfig,
4186 isCollaborationSupported: () => isCollaborationSupported
4187 });
4188 var import_data8 = __toESM(require_data(), 1);
4189
4190 // packages/core-data/build-module/utils/log-entity-deprecation.mjs
4191 var import_deprecated = __toESM(require_deprecated(), 1);
4192 var loggedAlready = false;
4193 function logEntityDeprecation(kind, name, functionName, {
4194 alternativeFunctionName,
4195 isShorthandSelector = false
4196 } = {}) {
4197 const deprecation = deprecatedEntities[kind]?.[name];
4198 if (!deprecation) {
4199 return;
4200 }
4201 if (!loggedAlready) {
4202 const { alternative } = deprecation;
4203 const message = isShorthandSelector ? `'${functionName}'` : `The '${kind}', '${name}' entity (used via '${functionName}')`;
4204 let alternativeMessage = `the '${alternative.kind}', '${alternative.name}' entity`;
4205 if (alternativeFunctionName) {
4206 alternativeMessage += ` via the '${alternativeFunctionName}' function`;
4207 }
4208 (0, import_deprecated.default)(message, {
4209 ...deprecation,
4210 alternative: alternativeMessage
4211 });
4212 }
4213 loggedAlready = true;
4214 setTimeout(() => {
4215 loggedAlready = false;
4216 }, 0);
4217 }
4218
4219 // packages/core-data/build-module/private-selectors.mjs
4220 var EMPTY_OBJECT = {};
4221 function getUndoManager(state) {
4222 return getSyncManager()?.undoManager ?? state.undoManager;
4223 }
4224 function getNavigationFallbackId(state) {
4225 return state.navigationFallbackId;
4226 }
4227 var getBlockPatternsForPostType = (0, import_data8.createRegistrySelector)(
4228 (select4) => (0, import_data8.createSelector)(
4229 (state, postType) => select4(STORE_NAME).getBlockPatterns().filter(
4230 ({ postTypes }) => !postTypes || Array.isArray(postTypes) && postTypes.includes(postType)
4231 ),
4232 () => [select4(STORE_NAME).getBlockPatterns()]
4233 )
4234 );
4235 var getEntityRecordsPermissions = (0, import_data8.createRegistrySelector)(
4236 (select4) => (0, import_data8.createSelector)(
4237 (state, kind, name, ids) => {
4238 const normalizedIds = Array.isArray(ids) ? ids : [ids];
4239 return normalizedIds.map((id) => ({
4240 delete: select4(STORE_NAME).canUser("delete", {
4241 kind,
4242 name,
4243 id
4244 }),
4245 update: select4(STORE_NAME).canUser("update", {
4246 kind,
4247 name,
4248 id
4249 })
4250 }));
4251 },
4252 (state) => [state.userPermissions]
4253 )
4254 );
4255 function getEntityRecordPermissions(state, kind, name, id) {
4256 logEntityDeprecation(kind, name, "getEntityRecordPermissions");
4257 return getEntityRecordsPermissions(state, kind, name, id)[0];
4258 }
4259 function getRegisteredPostMeta(state, postType) {
4260 return state.registeredPostMeta?.[postType] ?? {};
4261 }
4262 function normalizePageId(value) {
4263 if (!value || !["number", "string"].includes(typeof value)) {
4264 return null;
4265 }
4266 if (Number(value) === 0) {
4267 return null;
4268 }
4269 return value.toString();
4270 }
4271 var getHomePage = (0, import_data8.createRegistrySelector)(
4272 (select4) => (0, import_data8.createSelector)(
4273 () => {
4274 const siteData = select4(STORE_NAME).getEntityRecord(
4275 "root",
4276 "__unstableBase"
4277 );
4278 if (!siteData) {
4279 return null;
4280 }
4281 const homepageId = siteData?.show_on_front === "page" ? normalizePageId(siteData.page_on_front) : null;
4282 if (homepageId) {
4283 return { postType: "page", postId: homepageId };
4284 }
4285 const frontPageTemplateId = select4(
4286 STORE_NAME
4287 ).getDefaultTemplateId({
4288 slug: "front-page"
4289 });
4290 if (frontPageTemplateId) {
4291 return {
4292 postType: "wp_template",
4293 postId: frontPageTemplateId
4294 };
4295 }
4296 if (frontPageTemplateId === "") {
4297 return EMPTY_OBJECT;
4298 }
4299 return null;
4300 },
4301 (state) => [
4302 // Even though getDefaultTemplateId.shouldInvalidate returns true when root/site changes,
4303 // it doesn't seem to invalidate this cache, I'm not sure why.
4304 getEntityRecord(state, "root", "site"),
4305 getEntityRecord(state, "root", "__unstableBase"),
4306 getDefaultTemplateId(state, {
4307 slug: "front-page"
4308 })
4309 ]
4310 )
4311 );
4312 var getPostsPageId = (0, import_data8.createRegistrySelector)((select4) => () => {
4313 const siteData = select4(STORE_NAME).getEntityRecord(
4314 "root",
4315 "__unstableBase"
4316 );
4317 return siteData?.show_on_front === "page" ? normalizePageId(siteData.page_for_posts) : null;
4318 });
4319 var getTemplateId = (0, import_data8.createRegistrySelector)(
4320 (select4) => (state, postType, postId) => {
4321 const homepage = unlock(select4(STORE_NAME)).getHomePage();
4322 if (!homepage) {
4323 return;
4324 }
4325 if (postType === "page" && postType === homepage?.postType && postId.toString() === homepage?.postId) {
4326 const templates = select4(STORE_NAME).getEntityRecords(
4327 "postType",
4328 "wp_template",
4329 {
4330 per_page: -1
4331 }
4332 );
4333 if (!templates) {
4334 return;
4335 }
4336 const id = templates.find(({ slug }) => slug === "front-page")?.id;
4337 if (id) {
4338 return id;
4339 }
4340 }
4341 const editedEntity = select4(STORE_NAME).getEditedEntityRecord(
4342 "postType",
4343 postType,
4344 postId
4345 );
4346 if (!editedEntity) {
4347 return;
4348 }
4349 const postsPageId = unlock(select4(STORE_NAME)).getPostsPageId();
4350 if (postType === "page" && postsPageId === postId.toString()) {
4351 return select4(STORE_NAME).getDefaultTemplateId({
4352 slug: "home"
4353 });
4354 }
4355 const currentTemplateSlug = editedEntity.template;
4356 if (currentTemplateSlug) {
4357 const currentTemplate = select4(STORE_NAME).getEntityRecords("postType", "wp_template", {
4358 per_page: -1
4359 })?.find(({ slug }) => slug === currentTemplateSlug);
4360 if (currentTemplate) {
4361 return currentTemplate.id;
4362 }
4363 }
4364 let slugToCheck;
4365 if (editedEntity.slug) {
4366 slugToCheck = postType === "page" ? `${postType}-${editedEntity.slug}` : `single-${postType}-${editedEntity.slug}`;
4367 } else {
4368 slugToCheck = postType === "page" ? "page" : `single-${postType}`;
4369 }
4370 return select4(STORE_NAME).getDefaultTemplateId({
4371 slug: slugToCheck
4372 });
4373 }
4374 );
4375 function getEditorSettings(state) {
4376 return state.editorSettings;
4377 }
4378 function getEditorAssets(state) {
4379 return state.editorAssets;
4380 }
4381 function isCollaborationSupported(state) {
4382 return state.collaborationSupported;
4383 }
4384 function getViewConfig(state, kind, name) {
4385 return state.viewConfigs?.[`${kind}/${name}`] ?? {
4386 default_view: void 0,
4387 default_layouts: void 0,
4388 view_list: void 0,
4389 form: void 0
4390 };
4391 }
4392 function getSyncConnectionStatus(state) {
4393 if (!state.syncConnectionStatuses) {
4394 return void 0;
4395 }
4396 const PRIORITIZED_STATUSES = ["disconnected", "connecting", "connected"];
4397 let coalesced;
4398 for (const status of Object.values(state.syncConnectionStatuses)) {
4399 if (!coalesced || PRIORITIZED_STATUSES.indexOf(status.status) < PRIORITIZED_STATUSES.indexOf(coalesced.status)) {
4400 coalesced = status;
4401 }
4402 }
4403 return coalesced;
4404 }
4405
4406 // packages/core-data/build-module/selectors.mjs
4407 var EMPTY_OBJECT2 = {};
4408 var isRequestingEmbedPreview = (0, import_data9.createRegistrySelector)(
4409 (select4) => (state, url) => {
4410 return select4(STORE_NAME).isResolving("getEmbedPreview", [
4411 url
4412 ]);
4413 }
4414 );
4415 function getAuthors(state, query) {
4416 (0, import_deprecated2.default)("select( 'core' ).getAuthors()", {
4417 since: "5.9",
4418 alternative: "select( 'core' ).getUsers({ who: 'authors' })"
4419 });
4420 const path = (0, import_url2.addQueryArgs)(
4421 "/wp/v2/users/?who=authors&per_page=100",
4422 query
4423 );
4424 return getUserQueryResults(state, path);
4425 }
4426 function getCurrentUser(state) {
4427 return state.currentUser;
4428 }
4429 var getUserQueryResults = (0, import_data9.createSelector)(
4430 (state, queryID) => {
4431 const queryResults = state.users.queries[queryID] ?? [];
4432 return queryResults.map((id) => state.users.byId[id]);
4433 },
4434 (state, queryID) => [
4435 state.users.queries[queryID],
4436 state.users.byId
4437 ]
4438 );
4439 function getEntitiesByKind(state, kind) {
4440 (0, import_deprecated2.default)("wp.data.select( 'core' ).getEntitiesByKind()", {
4441 since: "6.0",
4442 alternative: "wp.data.select( 'core' ).getEntitiesConfig()"
4443 });
4444 return getEntitiesConfig(state, kind);
4445 }
4446 var getEntitiesConfig = (0, import_data9.createSelector)(
4447 (state, kind) => state.entities.config.filter((entity2) => entity2.kind === kind),
4448 /* eslint-disable @typescript-eslint/no-unused-vars */
4449 (state, kind) => state.entities.config
4450 /* eslint-enable @typescript-eslint/no-unused-vars */
4451 );
4452 function getEntity(state, kind, name) {
4453 (0, import_deprecated2.default)("wp.data.select( 'core' ).getEntity()", {
4454 since: "6.0",
4455 alternative: "wp.data.select( 'core' ).getEntityConfig()"
4456 });
4457 return getEntityConfig(state, kind, name);
4458 }
4459 function getEntityConfig(state, kind, name) {
4460 logEntityDeprecation(kind, name, "getEntityConfig");
4461 return state.entities.config?.find(
4462 (config) => config.kind === kind && config.name === name
4463 );
4464 }
4465 var getEntityRecord = (0, import_data9.createSelector)(
4466 ((state, kind, name, key, query) => {
4467 logEntityDeprecation(kind, name, "getEntityRecord");
4468 const queriedState = state.entities.records?.[kind]?.[name]?.queriedData;
4469 if (!queriedState) {
4470 return void 0;
4471 }
4472 const context = query?.context ?? "default";
4473 if (!query || !query._fields) {
4474 if (!queriedState.itemIsComplete[context]?.[key]) {
4475 return void 0;
4476 }
4477 return queriedState.items[context][key];
4478 }
4479 const item = queriedState.items[context]?.[key];
4480 if (!item) {
4481 return item;
4482 }
4483 const filteredItem = {};
4484 const fields = get_normalized_comma_separable_default(query._fields) ?? [];
4485 for (let f = 0; f < fields.length; f++) {
4486 const field = fields[f].split(".");
4487 let value = item;
4488 field.forEach((fieldName) => {
4489 value = value?.[fieldName];
4490 });
4491 setNestedValue(filteredItem, field, value);
4492 }
4493 return filteredItem;
4494 }),
4495 (state, kind, name, recordId, query) => {
4496 const context = query?.context ?? "default";
4497 const queriedState = state.entities.records?.[kind]?.[name]?.queriedData;
4498 return [
4499 queriedState?.items[context]?.[recordId],
4500 queriedState?.itemIsComplete[context]?.[recordId]
4501 ];
4502 }
4503 );
4504 getEntityRecord.__unstableNormalizeArgs = (args) => {
4505 const newArgs = [...args];
4506 const recordKey = newArgs?.[2];
4507 newArgs[2] = isNumericID(recordKey) ? Number(recordKey) : recordKey;
4508 return newArgs;
4509 };
4510 function hasEntityRecord(state, kind, name, key, query) {
4511 const queriedState = state.entities.records?.[kind]?.[name]?.queriedData;
4512 if (!queriedState) {
4513 return false;
4514 }
4515 const context = query?.context ?? "default";
4516 if (!query || !query._fields) {
4517 return !!queriedState.itemIsComplete[context]?.[key];
4518 }
4519 const item = queriedState.items[context]?.[key];
4520 if (!item) {
4521 return false;
4522 }
4523 const fields = get_normalized_comma_separable_default(query._fields) ?? [];
4524 for (let i = 0; i < fields.length; i++) {
4525 const path = fields[i].split(".");
4526 let value = item;
4527 for (let p = 0; p < path.length; p++) {
4528 const part = path[p];
4529 if (!value || !Object.hasOwn(value, part)) {
4530 return false;
4531 }
4532 value = value[part];
4533 }
4534 }
4535 return true;
4536 }
4537 function __experimentalGetEntityRecordNoResolver(state, kind, name, key) {
4538 return getEntityRecord(state, kind, name, key);
4539 }
4540 var getRawEntityRecord = (0, import_data9.createSelector)(
4541 (state, kind, name, key) => {
4542 logEntityDeprecation(kind, name, "getRawEntityRecord");
4543 const record = getEntityRecord(
4544 state,
4545 kind,
4546 name,
4547 key
4548 );
4549 const config = getEntityConfig(state, kind, name);
4550 if (!record || !config?.rawAttributes?.length) {
4551 return record;
4552 }
4553 return Object.fromEntries(
4554 Object.keys(record).map((_key) => {
4555 if (config.rawAttributes.includes(_key)) {
4556 const rawValue = record[_key]?.raw;
4557 return [
4558 _key,
4559 rawValue !== void 0 ? rawValue : record[_key]
4560 ];
4561 }
4562 return [_key, record[_key]];
4563 })
4564 );
4565 },
4566 (state, kind, name, recordId, query) => {
4567 const context = query?.context ?? "default";
4568 return [
4569 state.entities.config,
4570 state.entities.records?.[kind]?.[name]?.queriedData?.items[context]?.[recordId],
4571 state.entities.records?.[kind]?.[name]?.queriedData?.itemIsComplete[context]?.[recordId]
4572 ];
4573 }
4574 );
4575 function hasEntityRecords(state, kind, name, query) {
4576 logEntityDeprecation(kind, name, "hasEntityRecords");
4577 return Array.isArray(getEntityRecords(state, kind, name, query));
4578 }
4579 var getEntityRecords = ((state, kind, name, query) => {
4580 logEntityDeprecation(kind, name, "getEntityRecords");
4581 const queriedState = state.entities.records?.[kind]?.[name]?.queriedData;
4582 if (!queriedState) {
4583 return null;
4584 }
4585 return getQueriedItems(queriedState, query, {
4586 supportsPagination: !!getEntityConfig(state, kind, name)?.supportsPagination
4587 });
4588 });
4589 var getEntityRecordsTotalItems = (state, kind, name, query) => {
4590 logEntityDeprecation(kind, name, "getEntityRecordsTotalItems");
4591 const queriedState = state.entities.records?.[kind]?.[name]?.queriedData;
4592 if (!queriedState) {
4593 return null;
4594 }
4595 return getQueriedTotalItems(queriedState, query);
4596 };
4597 var getEntityRecordsTotalPages = (state, kind, name, query) => {
4598 logEntityDeprecation(kind, name, "getEntityRecordsTotalPages");
4599 const queriedState = state.entities.records?.[kind]?.[name]?.queriedData;
4600 if (!queriedState) {
4601 return null;
4602 }
4603 if (!getEntityConfig(state, kind, name)?.supportsPagination || query?.per_page === -1) {
4604 return 1;
4605 }
4606 const totalItems = getQueriedTotalItems(queriedState, query);
4607 if (!totalItems) {
4608 return totalItems;
4609 }
4610 if (!query?.per_page) {
4611 return getQueriedTotalPages(queriedState, query);
4612 }
4613 return Math.ceil(totalItems / query.per_page);
4614 };
4615 var __experimentalGetDirtyEntityRecords = (0, import_data9.createSelector)(
4616 (state) => {
4617 const {
4618 entities: { records }
4619 } = state;
4620 const dirtyRecords = [];
4621 Object.keys(records).forEach((kind) => {
4622 Object.keys(records[kind]).forEach((name) => {
4623 const primaryKeys = Object.keys(records[kind][name].edits).filter(
4624 (primaryKey) => (
4625 // The entity record must exist (not be deleted),
4626 // and it must have edits.
4627 getEntityRecord(state, kind, name, primaryKey) && hasEditsForEntityRecord(state, kind, name, primaryKey)
4628 )
4629 );
4630 if (primaryKeys.length) {
4631 const entityConfig = getEntityConfig(state, kind, name);
4632 primaryKeys.forEach((primaryKey) => {
4633 const entityRecord = getEditedEntityRecord(
4634 state,
4635 kind,
4636 name,
4637 primaryKey
4638 );
4639 dirtyRecords.push({
4640 // We avoid using primaryKey because it's transformed into a string
4641 // when it's used as an object key.
4642 key: entityRecord ? entityRecord[entityConfig.key || DEFAULT_ENTITY_KEY] : void 0,
4643 title: entityConfig?.getTitle?.(entityRecord) || "",
4644 name,
4645 kind
4646 });
4647 });
4648 }
4649 });
4650 });
4651 return dirtyRecords;
4652 },
4653 (state) => [state.entities.records]
4654 );
4655 var __experimentalGetEntitiesBeingSaved = (0, import_data9.createSelector)(
4656 (state) => {
4657 const {
4658 entities: { records }
4659 } = state;
4660 const recordsBeingSaved = [];
4661 Object.keys(records).forEach((kind) => {
4662 Object.keys(records[kind]).forEach((name) => {
4663 const primaryKeys = Object.keys(records[kind][name].saving).filter(
4664 (primaryKey) => isSavingEntityRecord(state, kind, name, primaryKey)
4665 );
4666 if (primaryKeys.length) {
4667 const entityConfig = getEntityConfig(state, kind, name);
4668 primaryKeys.forEach((primaryKey) => {
4669 const entityRecord = getEditedEntityRecord(
4670 state,
4671 kind,
4672 name,
4673 primaryKey
4674 );
4675 recordsBeingSaved.push({
4676 // We avoid using primaryKey because it's transformed into a string
4677 // when it's used as an object key.
4678 key: entityRecord ? entityRecord[entityConfig.key || DEFAULT_ENTITY_KEY] : void 0,
4679 title: entityConfig?.getTitle?.(entityRecord) || "",
4680 name,
4681 kind
4682 });
4683 });
4684 }
4685 });
4686 });
4687 return recordsBeingSaved;
4688 },
4689 (state) => [state.entities.records]
4690 );
4691 function getEntityRecordEdits(state, kind, name, recordId) {
4692 logEntityDeprecation(kind, name, "getEntityRecordEdits");
4693 return state.entities.records?.[kind]?.[name]?.edits?.[recordId];
4694 }
4695 var getEntityRecordNonTransientEdits = (0, import_data9.createSelector)(
4696 (state, kind, name, recordId) => {
4697 logEntityDeprecation(kind, name, "getEntityRecordNonTransientEdits");
4698 const { transientEdits } = getEntityConfig(state, kind, name) || {};
4699 const edits = getEntityRecordEdits(state, kind, name, recordId) || {};
4700 if (!transientEdits) {
4701 return edits;
4702 }
4703 return Object.keys(edits).reduce((acc, key) => {
4704 if (!transientEdits[key]) {
4705 acc[key] = edits[key];
4706 }
4707 return acc;
4708 }, {});
4709 },
4710 (state, kind, name, recordId) => [
4711 state.entities.config,
4712 state.entities.records?.[kind]?.[name]?.edits?.[recordId]
4713 ]
4714 );
4715 function hasEditsForEntityRecord(state, kind, name, recordId) {
4716 logEntityDeprecation(kind, name, "hasEditsForEntityRecord");
4717 return isSavingEntityRecord(state, kind, name, recordId) || Object.keys(
4718 getEntityRecordNonTransientEdits(state, kind, name, recordId)
4719 ).length > 0;
4720 }
4721 var getEditedEntityRecord = (0, import_data9.createSelector)(
4722 (state, kind, name, recordId) => {
4723 logEntityDeprecation(kind, name, "getEditedEntityRecord");
4724 const raw = getRawEntityRecord(state, kind, name, recordId);
4725 const edited = getEntityRecordEdits(state, kind, name, recordId);
4726 if (!raw && !edited) {
4727 return false;
4728 }
4729 return {
4730 ...raw,
4731 ...edited
4732 };
4733 },
4734 (state, kind, name, recordId, query) => {
4735 const context = query?.context ?? "default";
4736 return [
4737 state.entities.config,
4738 state.entities.records?.[kind]?.[name]?.queriedData.items[context]?.[recordId],
4739 state.entities.records?.[kind]?.[name]?.queriedData.itemIsComplete[context]?.[recordId],
4740 state.entities.records?.[kind]?.[name]?.edits?.[recordId]
4741 ];
4742 }
4743 );
4744 function isAutosavingEntityRecord(state, kind, name, recordId) {
4745 logEntityDeprecation(kind, name, "isAutosavingEntityRecord");
4746 const { pending, isAutosave } = state.entities.records?.[kind]?.[name]?.saving?.[recordId] ?? {};
4747 return Boolean(pending && isAutosave);
4748 }
4749 function isSavingEntityRecord(state, kind, name, recordId) {
4750 logEntityDeprecation(kind, name, "isSavingEntityRecord");
4751 return state.entities.records?.[kind]?.[name]?.saving?.[recordId]?.pending ?? false;
4752 }
4753 function isDeletingEntityRecord(state, kind, name, recordId) {
4754 logEntityDeprecation(kind, name, "isDeletingEntityRecord");
4755 return state.entities.records?.[kind]?.[name]?.deleting?.[recordId]?.pending ?? false;
4756 }
4757 function getLastEntitySaveError(state, kind, name, recordId) {
4758 logEntityDeprecation(kind, name, "getLastEntitySaveError");
4759 return state.entities.records?.[kind]?.[name]?.saving?.[recordId]?.error;
4760 }
4761 function getLastEntityDeleteError(state, kind, name, recordId) {
4762 logEntityDeprecation(kind, name, "getLastEntityDeleteError");
4763 return state.entities.records?.[kind]?.[name]?.deleting?.[recordId]?.error;
4764 }
4765 function getUndoEdit(state) {
4766 (0, import_deprecated2.default)("select( 'core' ).getUndoEdit()", {
4767 since: "6.3"
4768 });
4769 return void 0;
4770 }
4771 function getRedoEdit(state) {
4772 (0, import_deprecated2.default)("select( 'core' ).getRedoEdit()", {
4773 since: "6.3"
4774 });
4775 return void 0;
4776 }
4777 function hasUndo(state) {
4778 if (getSyncManager()?.undoManager) {
4779 return state.syncUndoManagerState.hasUndo;
4780 }
4781 return getUndoManager(state).hasUndo();
4782 }
4783 function hasRedo(state) {
4784 if (getSyncManager()?.undoManager) {
4785 return state.syncUndoManagerState.hasRedo;
4786 }
4787 return getUndoManager(state).hasRedo();
4788 }
4789 function getCurrentTheme(state) {
4790 if (!state.currentTheme) {
4791 return null;
4792 }
4793 return getEntityRecord(state, "root", "theme", state.currentTheme);
4794 }
4795 function __experimentalGetCurrentGlobalStylesId(state) {
4796 return state.currentGlobalStylesId;
4797 }
4798 function getThemeSupports(state) {
4799 return getCurrentTheme(state)?.theme_supports ?? EMPTY_OBJECT2;
4800 }
4801 function getEmbedPreview(state, url) {
4802 return state.embedPreviews[url];
4803 }
4804 function isPreviewEmbedFallback(state, url) {
4805 const preview = state.embedPreviews[url];
4806 const oEmbedLinkCheck = '<a href="' + url + '">' + url + "</a>";
4807 if (!preview) {
4808 return false;
4809 }
4810 return preview.html === oEmbedLinkCheck;
4811 }
4812 function canUser(state, action, resource, id) {
4813 const isEntity = typeof resource === "object";
4814 if (isEntity && (!resource.kind || !resource.name)) {
4815 return false;
4816 }
4817 if (isEntity) {
4818 logEntityDeprecation(resource.kind, resource.name, "canUser");
4819 }
4820 const key = getUserPermissionCacheKey(action, resource, id);
4821 return state.userPermissions[key];
4822 }
4823 function canUserEditEntityRecord(state, kind, name, recordId) {
4824 (0, import_deprecated2.default)(`wp.data.select( 'core' ).canUserEditEntityRecord()`, {
4825 since: "6.7",
4826 alternative: `wp.data.select( 'core' ).canUser( 'update', { kind, name, id } )`
4827 });
4828 return canUser(state, "update", { kind, name, id: recordId });
4829 }
4830 function getAutosaves(state, postType, postId) {
4831 return state.autosaves[postId];
4832 }
4833 function getAutosave(state, postType, postId, authorId) {
4834 if (authorId === void 0) {
4835 return;
4836 }
4837 const autosaves2 = state.autosaves[postId];
4838 return autosaves2?.find(
4839 (autosave) => autosave.author === authorId
4840 );
4841 }
4842 var hasFetchedAutosaves = (0, import_data9.createRegistrySelector)(
4843 (select4) => (state, postType, postId) => {
4844 return select4(STORE_NAME).hasFinishedResolution("getAutosaves", [
4845 postType,
4846 postId
4847 ]);
4848 }
4849 );
4850 function getReferenceByDistinctEdits(state) {
4851 return state.editsReference;
4852 }
4853 function __experimentalGetCurrentThemeBaseGlobalStyles(state) {
4854 const currentTheme2 = getCurrentTheme(state);
4855 if (!currentTheme2) {
4856 return null;
4857 }
4858 return state.themeBaseGlobalStyles[currentTheme2.stylesheet];
4859 }
4860 function __experimentalGetCurrentThemeGlobalStylesVariations(state) {
4861 const currentTheme2 = getCurrentTheme(state);
4862 if (!currentTheme2) {
4863 return null;
4864 }
4865 return state.themeGlobalStyleVariations[currentTheme2.stylesheet];
4866 }
4867 function getBlockPatterns(state) {
4868 return state.blockPatterns;
4869 }
4870 function getBlockPatternCategories(state) {
4871 return state.blockPatternCategories;
4872 }
4873 function getUserPatternCategories(state) {
4874 return state.userPatternCategories;
4875 }
4876 function getCurrentThemeGlobalStylesRevisions(state) {
4877 (0, import_deprecated2.default)("select( 'core' ).getCurrentThemeGlobalStylesRevisions()", {
4878 since: "6.5.0",
4879 alternative: "select( 'core' ).getRevisions( 'root', 'globalStyles', ${ recordKey } )"
4880 });
4881 const currentGlobalStylesId2 = __experimentalGetCurrentGlobalStylesId(state);
4882 if (!currentGlobalStylesId2) {
4883 return null;
4884 }
4885 return state.themeGlobalStyleRevisions[currentGlobalStylesId2];
4886 }
4887 function getDefaultTemplateId(state, query) {
4888 return state.defaultTemplates[JSON.stringify(query)];
4889 }
4890 var getRevisions = (state, kind, name, recordKey, query) => {
4891 logEntityDeprecation(kind, name, "getRevisions");
4892 const queriedStateRevisions = state.entities.records?.[kind]?.[name]?.revisions?.[recordKey];
4893 if (!queriedStateRevisions) {
4894 return null;
4895 }
4896 return getQueriedItems(queriedStateRevisions, query);
4897 };
4898 function hasRevision(state, kind, name, recordKey, revisionKey, query) {
4899 const queriedState = state.entities.records?.[kind]?.[name]?.revisions?.[recordKey];
4900 if (!queriedState) {
4901 return false;
4902 }
4903 const context = query?.context ?? "default";
4904 if (!query || !query._fields) {
4905 return !!queriedState.itemIsComplete[context]?.[revisionKey];
4906 }
4907 const item = queriedState.items[context]?.[revisionKey];
4908 if (!item) {
4909 return false;
4910 }
4911 const fields = get_normalized_comma_separable_default(query._fields) ?? [];
4912 for (let i = 0; i < fields.length; i++) {
4913 const path = fields[i].split(".");
4914 let value = item;
4915 for (let p = 0; p < path.length; p++) {
4916 const part = path[p];
4917 if (!value || !Object.hasOwn(value, part)) {
4918 return false;
4919 }
4920 value = value[part];
4921 }
4922 }
4923 return true;
4924 }
4925 var getRevision = (0, import_data9.createSelector)(
4926 (state, kind, name, recordKey, revisionKey, query) => {
4927 logEntityDeprecation(kind, name, "getRevision");
4928 const queriedState = state.entities.records?.[kind]?.[name]?.revisions?.[recordKey];
4929 if (!queriedState) {
4930 return void 0;
4931 }
4932 const context = query?.context ?? "default";
4933 if (!query || !query._fields) {
4934 if (!queriedState.itemIsComplete[context]?.[revisionKey]) {
4935 return void 0;
4936 }
4937 return queriedState.items[context][revisionKey];
4938 }
4939 const item = queriedState.items[context]?.[revisionKey];
4940 if (!item) {
4941 return item;
4942 }
4943 const filteredItem = {};
4944 const fields = get_normalized_comma_separable_default(query._fields) ?? [];
4945 for (let f = 0; f < fields.length; f++) {
4946 const field = fields[f].split(".");
4947 let value = item;
4948 field.forEach((fieldName) => {
4949 value = value?.[fieldName];
4950 });
4951 setNestedValue(filteredItem, field, value);
4952 }
4953 return filteredItem;
4954 },
4955 (state, kind, name, recordKey, revisionKey, query) => {
4956 const context = query?.context ?? "default";
4957 const queriedState = state.entities.records?.[kind]?.[name]?.revisions?.[recordKey];
4958 return [
4959 queriedState?.items?.[context]?.[revisionKey],
4960 queriedState?.itemIsComplete?.[context]?.[revisionKey]
4961 ];
4962 }
4963 );
4964
4965 // packages/core-data/build-module/actions.mjs
4966 var actions_exports = {};
4967 __export(actions_exports, {
4968 __experimentalBatch: () => __experimentalBatch,
4969 __experimentalReceiveCurrentGlobalStylesId: () => __experimentalReceiveCurrentGlobalStylesId,
4970 __experimentalReceiveThemeBaseGlobalStyles: () => __experimentalReceiveThemeBaseGlobalStyles,
4971 __experimentalReceiveThemeGlobalStyleVariations: () => __experimentalReceiveThemeGlobalStyleVariations,
4972 __experimentalSaveSpecifiedEntityEdits: () => __experimentalSaveSpecifiedEntityEdits,
4973 __unstableCreateUndoLevel: () => __unstableCreateUndoLevel,
4974 addEntities: () => addEntities,
4975 clearEntityRecordEdits: () => clearEntityRecordEdits,
4976 deleteEntityRecord: () => deleteEntityRecord,
4977 editEntityRecord: () => editEntityRecord,
4978 receiveAutosaves: () => receiveAutosaves,
4979 receiveCurrentTheme: () => receiveCurrentTheme,
4980 receiveCurrentUser: () => receiveCurrentUser,
4981 receiveDefaultTemplateId: () => receiveDefaultTemplateId,
4982 receiveEmbedPreview: () => receiveEmbedPreview,
4983 receiveEntityRecords: () => receiveEntityRecords,
4984 receiveNavigationFallbackId: () => receiveNavigationFallbackId,
4985 receiveRevisions: () => receiveRevisions,
4986 receiveThemeGlobalStyleRevisions: () => receiveThemeGlobalStyleRevisions,
4987 receiveThemeSupports: () => receiveThemeSupports,
4988 receiveUploadPermissions: () => receiveUploadPermissions,
4989 receiveUserPermission: () => receiveUserPermission,
4990 receiveUserPermissions: () => receiveUserPermissions,
4991 receiveUserQuery: () => receiveUserQuery,
4992 redo: () => redo,
4993 saveEditedEntityRecord: () => saveEditedEntityRecord,
4994 saveEntityRecord: () => saveEntityRecord,
4995 undo: () => undo
4996 });
4997 var import_es65 = __toESM(require_es6(), 1);
4998 var import_api_fetch4 = __toESM(require_api_fetch(), 1);
4999 var import_url3 = __toESM(require_url(), 1);
5000 var import_deprecated3 = __toESM(require_deprecated(), 1);
5001
5002 // packages/core-data/build-module/batch/default-processor.mjs
5003 var import_api_fetch3 = __toESM(require_api_fetch(), 1);
5004 var maxItems = null;
5005 function chunk(arr, chunkSize) {
5006 const tmp = [...arr];
5007 const cache3 = [];
5008 while (tmp.length) {
5009 cache3.push(tmp.splice(0, chunkSize));
5010 }
5011 return cache3;
5012 }
5013 async function defaultProcessor(requests) {
5014 if (maxItems === null) {
5015 const preflightResponse = await (0, import_api_fetch3.default)({
5016 path: "/batch/v1",
5017 method: "OPTIONS"
5018 });
5019 maxItems = preflightResponse.endpoints[0].args.requests.maxItems;
5020 }
5021 const results = [];
5022 for (const batchRequests of chunk(requests, maxItems)) {
5023 const batchResponse = await (0, import_api_fetch3.default)({
5024 path: "/batch/v1",
5025 method: "POST",
5026 data: {
5027 validation: "require-all-validate",
5028 requests: batchRequests.map((request) => ({
5029 path: request.path,
5030 body: request.data,
5031 // Rename 'data' to 'body'.
5032 method: request.method,
5033 headers: request.headers
5034 }))
5035 }
5036 });
5037 let batchResults;
5038 if (batchResponse.failed) {
5039 batchResults = batchResponse.responses.map((response) => ({
5040 error: response?.body
5041 }));
5042 } else {
5043 batchResults = batchResponse.responses.map((response) => {
5044 const result = {};
5045 if (response.status >= 200 && response.status < 300) {
5046 result.output = response.body;
5047 } else {
5048 result.error = response.body;
5049 }
5050 return result;
5051 });
5052 }
5053 results.push(...batchResults);
5054 }
5055 return results;
5056 }
5057
5058 // packages/core-data/build-module/batch/create-batch.mjs
5059 function createBatch(processor = defaultProcessor) {
5060 let lastId = 0;
5061 let queue = [];
5062 const pending = new ObservableSet();
5063 return {
5064 /**
5065 * Adds an input to the batch and returns a promise that is resolved or
5066 * rejected when the input is processed by `batch.run()`.
5067 *
5068 * You may also pass a thunk which allows inputs to be added
5069 * asynchronously.
5070 *
5071 * ```
5072 * // Both are allowed:
5073 * batch.add( { path: '/v1/books', ... } );
5074 * batch.add( ( add ) => add( { path: '/v1/books', ... } ) );
5075 * ```
5076 *
5077 * If a thunk is passed, `batch.run()` will pause until either:
5078 *
5079 * - The thunk calls its `add` argument, or;
5080 * - The thunk returns a promise and that promise resolves, or;
5081 * - The thunk returns a non-promise.
5082 *
5083 * @param {any|Function} inputOrThunk Input to add or thunk to execute.
5084 *
5085 * @return {Promise|any} If given an input, returns a promise that
5086 * is resolved or rejected when the batch is
5087 * processed. If given a thunk, returns the return
5088 * value of that thunk.
5089 */
5090 add(inputOrThunk) {
5091 const id = ++lastId;
5092 pending.add(id);
5093 const add = (input) => new Promise((resolve, reject) => {
5094 queue.push({
5095 input,
5096 resolve,
5097 reject
5098 });
5099 pending.delete(id);
5100 });
5101 if (typeof inputOrThunk === "function") {
5102 return Promise.resolve(inputOrThunk(add)).finally(() => {
5103 pending.delete(id);
5104 });
5105 }
5106 return add(inputOrThunk);
5107 },
5108 /**
5109 * Runs the batch. This calls `batchProcessor` and resolves or rejects
5110 * all promises returned by `add()`.
5111 *
5112 * @return {Promise<boolean>} A promise that resolves to a boolean that is true
5113 * if the processor returned no errors.
5114 */
5115 async run() {
5116 if (pending.size) {
5117 await new Promise((resolve) => {
5118 const unsubscribe = pending.subscribe(() => {
5119 if (!pending.size) {
5120 unsubscribe();
5121 resolve(void 0);
5122 }
5123 });
5124 });
5125 }
5126 let results;
5127 try {
5128 results = await processor(
5129 queue.map(({ input }) => input)
5130 );
5131 if (results.length !== queue.length) {
5132 throw new Error(
5133 "run: Array returned by processor must be same size as input array."
5134 );
5135 }
5136 } catch (error) {
5137 for (const { reject } of queue) {
5138 reject(error);
5139 }
5140 throw error;
5141 }
5142 let isSuccess = true;
5143 results.forEach((result, key) => {
5144 const queueItem = queue[key];
5145 if (result?.error) {
5146 queueItem?.reject(result.error);
5147 isSuccess = false;
5148 } else {
5149 queueItem?.resolve(result?.output ?? result);
5150 }
5151 });
5152 queue = [];
5153 return isSuccess;
5154 }
5155 };
5156 }
5157 var ObservableSet = class {
5158 constructor(...args) {
5159 this.set = new Set(...args);
5160 this.subscribers = /* @__PURE__ */ new Set();
5161 }
5162 get size() {
5163 return this.set.size;
5164 }
5165 add(value) {
5166 this.set.add(value);
5167 this.subscribers.forEach((subscriber) => subscriber());
5168 return this;
5169 }
5170 delete(value) {
5171 const isSuccess = this.set.delete(value);
5172 this.subscribers.forEach((subscriber) => subscriber());
5173 return isSuccess;
5174 }
5175 subscribe(subscriber) {
5176 this.subscribers.add(subscriber);
5177 return () => {
5178 this.subscribers.delete(subscriber);
5179 };
5180 }
5181 };
5182
5183 // packages/core-data/build-module/actions.mjs
5184 function addTitleToAutoDraft(record) {
5185 return record.status === "auto-draft" ? { ...record, title: "" } : record;
5186 }
5187 function receiveUserQuery(queryID, users2) {
5188 return {
5189 type: "RECEIVE_USER_QUERY",
5190 users: Array.isArray(users2) ? users2 : [users2],
5191 queryID
5192 };
5193 }
5194 function receiveCurrentUser(currentUser2) {
5195 return {
5196 type: "RECEIVE_CURRENT_USER",
5197 currentUser: currentUser2
5198 };
5199 }
5200 function addEntities(entities2) {
5201 return {
5202 type: "ADD_ENTITIES",
5203 entities: entities2
5204 };
5205 }
5206 function receiveEntityRecords(kind, name, records, query = void 0, invalidateCache = false, edits = void 0, meta = void 0) {
5207 if (kind === "postType") {
5208 records = Array.isArray(records) ? records.map(addTitleToAutoDraft) : addTitleToAutoDraft(records);
5209 }
5210 let action;
5211 if (query) {
5212 action = receiveQueriedItems(records, query, edits, meta);
5213 } else {
5214 action = receiveItems(records, edits, meta);
5215 }
5216 return {
5217 ...action,
5218 kind,
5219 name,
5220 invalidateCache
5221 };
5222 }
5223 function receiveCurrentTheme(currentTheme2) {
5224 return {
5225 type: "RECEIVE_CURRENT_THEME",
5226 currentTheme: currentTheme2
5227 };
5228 }
5229 function __experimentalReceiveCurrentGlobalStylesId(currentGlobalStylesId2) {
5230 return {
5231 type: "RECEIVE_CURRENT_GLOBAL_STYLES_ID",
5232 id: currentGlobalStylesId2
5233 };
5234 }
5235 function __experimentalReceiveThemeBaseGlobalStyles(stylesheet, globalStyles) {
5236 return {
5237 type: "RECEIVE_THEME_GLOBAL_STYLES",
5238 stylesheet,
5239 globalStyles
5240 };
5241 }
5242 function __experimentalReceiveThemeGlobalStyleVariations(stylesheet, variations) {
5243 return {
5244 type: "RECEIVE_THEME_GLOBAL_STYLE_VARIATIONS",
5245 stylesheet,
5246 variations
5247 };
5248 }
5249 function receiveThemeSupports() {
5250 (0, import_deprecated3.default)("wp.data.dispatch( 'core' ).receiveThemeSupports", {
5251 since: "5.9"
5252 });
5253 return {
5254 type: "DO_NOTHING"
5255 };
5256 }
5257 function receiveThemeGlobalStyleRevisions(currentId, revisions) {
5258 (0, import_deprecated3.default)(
5259 "wp.data.dispatch( 'core' ).receiveThemeGlobalStyleRevisions()",
5260 {
5261 since: "6.5.0",
5262 alternative: "wp.data.dispatch( 'core' ).receiveRevisions"
5263 }
5264 );
5265 return {
5266 type: "RECEIVE_THEME_GLOBAL_STYLE_REVISIONS",
5267 currentId,
5268 revisions
5269 };
5270 }
5271 function receiveEmbedPreview(url, preview) {
5272 return {
5273 type: "RECEIVE_EMBED_PREVIEW",
5274 url,
5275 preview
5276 };
5277 }
5278 var deleteEntityRecord = (kind, name, recordId, query, { __unstableFetch = import_api_fetch4.default, throwOnError = false } = {}) => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
5279 logEntityDeprecation(kind, name, "deleteEntityRecord");
5280 const configs = await resolveSelect2.getEntitiesConfig(kind);
5281 const entityConfig = configs.find(
5282 (config) => config.kind === kind && config.name === name
5283 );
5284 let error;
5285 let deletedRecord = false;
5286 if (!entityConfig) {
5287 return;
5288 }
5289 const lock2 = await dispatch3.__unstableAcquireStoreLock(
5290 STORE_NAME,
5291 ["entities", "records", kind, name, recordId],
5292 { exclusive: true }
5293 );
5294 try {
5295 dispatch3({
5296 type: "DELETE_ENTITY_RECORD_START",
5297 kind,
5298 name,
5299 recordId
5300 });
5301 let hasError = false;
5302 let { baseURL } = entityConfig;
5303 if (kind === "postType" && name === "wp_template" && (recordId && typeof recordId === "string" && !/^\d+$/.test(recordId) || !window?.__experimentalTemplateActivate)) {
5304 baseURL = baseURL.slice(0, baseURL.lastIndexOf("/")) + "/templates";
5305 }
5306 try {
5307 let path = `${baseURL}/${recordId}`;
5308 if (query) {
5309 path = (0, import_url3.addQueryArgs)(path, query);
5310 }
5311 deletedRecord = await __unstableFetch({
5312 path,
5313 method: "DELETE"
5314 });
5315 await dispatch3(removeItems(kind, name, recordId, true));
5316 if (entityConfig.syncConfig) {
5317 const objectType = `${kind}/${name}`;
5318 const objectId = recordId;
5319 getSyncManager()?.unload(objectType, objectId);
5320 }
5321 } catch (_error) {
5322 hasError = true;
5323 error = _error;
5324 }
5325 dispatch3({
5326 type: "DELETE_ENTITY_RECORD_FINISH",
5327 kind,
5328 name,
5329 recordId,
5330 error
5331 });
5332 if (hasError && throwOnError) {
5333 throw error;
5334 }
5335 return deletedRecord;
5336 } finally {
5337 dispatch3.__unstableReleaseStoreLock(lock2);
5338 }
5339 };
5340 var editEntityRecord = (kind, name, recordId, edits, options = {}) => ({ select: select4, dispatch: dispatch3 }) => {
5341 logEntityDeprecation(kind, name, "editEntityRecord");
5342 const entityConfig = select4.getEntityConfig(kind, name);
5343 if (!entityConfig) {
5344 throw new Error(
5345 `The entity being edited (${kind}, ${name}) does not have a loaded config.`
5346 );
5347 }
5348 const { mergedEdits = {} } = entityConfig;
5349 const record = select4.getRawEntityRecord(kind, name, recordId);
5350 const editedRecord = select4.getEditedEntityRecord(
5351 kind,
5352 name,
5353 recordId
5354 );
5355 const editsWithMerges = Object.keys(edits).reduce((acc, key) => {
5356 acc[key] = mergedEdits[key] ? { ...editedRecord[key], ...edits[key] } : edits[key];
5357 return acc;
5358 }, {});
5359 const edit = {
5360 kind,
5361 name,
5362 recordId,
5363 // Clear edits when they are equal to their persisted counterparts
5364 // so that the property is not considered dirty.
5365 edits: Object.keys(edits).reduce((acc, key) => {
5366 const recordValue = record[key];
5367 const value = editsWithMerges[key];
5368 acc[key] = (0, import_es65.default)(recordValue, value) ? void 0 : value;
5369 return acc;
5370 }, {})
5371 };
5372 if (entityConfig.syncConfig) {
5373 const objectType = `${kind}/${name}`;
5374 const objectId = recordId;
5375 const isNewUndoLevel = options.undoIgnore ? false : !options.isCached;
5376 const origin = options.undoIgnore ? LOCAL_UNDO_IGNORED_ORIGIN : LOCAL_EDITOR_ORIGIN;
5377 getSyncManager()?.update(
5378 objectType,
5379 objectId,
5380 editsWithMerges,
5381 origin,
5382 { isNewUndoLevel }
5383 );
5384 }
5385 if (!options.undoIgnore) {
5386 select4.getUndoManager().addRecord(
5387 [
5388 {
5389 id: { kind, name, recordId },
5390 changes: Object.keys(edits).reduce((acc, key) => {
5391 acc[key] = {
5392 from: editedRecord[key],
5393 to: edits[key]
5394 };
5395 return acc;
5396 }, {})
5397 }
5398 ],
5399 options.isCached
5400 );
5401 }
5402 dispatch3({
5403 type: "EDIT_ENTITY_RECORD",
5404 ...edit
5405 });
5406 };
5407 var clearEntityRecordEdits = (kind, name, recordId) => ({ select: select4, dispatch: dispatch3 }) => {
5408 const entityConfig = select4.getEntityConfig(kind, name);
5409 logEntityDeprecation(kind, name, "clearEntityRecordEdits");
5410 if (!entityConfig) {
5411 throw new Error(
5412 `The entity being edited (${kind}, ${name}) does not have a loaded config.`
5413 );
5414 }
5415 const currentEdits = select4.getEntityRecordEdits(
5416 kind,
5417 name,
5418 recordId
5419 );
5420 if (!currentEdits) {
5421 return;
5422 }
5423 const clearedEdits = Object.keys(currentEdits).reduce(
5424 (acc, key) => {
5425 acc[key] = void 0;
5426 return acc;
5427 },
5428 {}
5429 );
5430 dispatch3({
5431 type: "EDIT_ENTITY_RECORD",
5432 kind,
5433 name,
5434 recordId,
5435 edits: clearedEdits
5436 });
5437 };
5438 var undo = () => ({ select: select4, dispatch: dispatch3 }) => {
5439 const undoRecord = select4.getUndoManager().undo();
5440 if (!undoRecord) {
5441 return;
5442 }
5443 dispatch3({
5444 type: "UNDO",
5445 record: undoRecord
5446 });
5447 };
5448 var redo = () => ({ select: select4, dispatch: dispatch3 }) => {
5449 const redoRecord = select4.getUndoManager().redo();
5450 if (!redoRecord) {
5451 return;
5452 }
5453 dispatch3({
5454 type: "REDO",
5455 record: redoRecord
5456 });
5457 };
5458 var __unstableCreateUndoLevel = () => ({ select: select4 }) => {
5459 select4.getUndoManager().addRecord();
5460 };
5461 var saveEntityRecord = (kind, name, record, options = {}) => async ({ select: select4, resolveSelect: resolveSelect2, dispatch: dispatch3 }) => {
5462 const {
5463 isAutosave = false,
5464 __unstableFetch = import_api_fetch4.default,
5465 __unstableSkipSyncUpdate = false,
5466 throwOnError = false
5467 } = options;
5468 logEntityDeprecation(kind, name, "saveEntityRecord");
5469 const configs = await resolveSelect2.getEntitiesConfig(kind);
5470 const entityConfig = configs.find(
5471 (config) => config.kind === kind && config.name === name
5472 );
5473 if (!entityConfig) {
5474 return;
5475 }
5476 const entityIdKey = entityConfig.key ?? DEFAULT_ENTITY_KEY;
5477 const recordId = record[entityIdKey];
5478 const isNewRecord = !!entityIdKey && !recordId;
5479 const lock2 = await dispatch3.__unstableAcquireStoreLock(
5480 STORE_NAME,
5481 ["entities", "records", kind, name, recordId || v4_default()],
5482 { exclusive: true }
5483 );
5484 try {
5485 for (const [key, value] of Object.entries(record)) {
5486 if (typeof value === "function") {
5487 const evaluatedValue = value(
5488 select4.getEditedEntityRecord(kind, name, recordId)
5489 );
5490 dispatch3.editEntityRecord(
5491 kind,
5492 name,
5493 recordId,
5494 {
5495 [key]: evaluatedValue
5496 },
5497 { undoIgnore: true }
5498 );
5499 record[key] = evaluatedValue;
5500 }
5501 }
5502 dispatch3({
5503 type: "SAVE_ENTITY_RECORD_START",
5504 kind,
5505 name,
5506 recordId,
5507 isAutosave
5508 });
5509 let updatedRecord;
5510 let error;
5511 let hasError = false;
5512 let { baseURL } = entityConfig;
5513 if (kind === "postType" && name === "wp_template" && (recordId && typeof recordId === "string" && !/^\d+$/.test(recordId) || !window?.__experimentalTemplateActivate)) {
5514 baseURL = baseURL.slice(0, baseURL.lastIndexOf("/")) + "/templates";
5515 }
5516 try {
5517 const path = `${baseURL}${recordId ? "/" + recordId : ""}`;
5518 const persistedRecord = !isNewRecord ? select4.getRawEntityRecord(kind, name, recordId) : {};
5519 if (isAutosave) {
5520 const merged = { ...persistedRecord, ...record };
5521 const data = [
5522 "title",
5523 "excerpt",
5524 "content",
5525 "meta"
5526 ].reduce(
5527 (acc, key) => {
5528 if (key in merged) {
5529 acc[key] = merged[key];
5530 }
5531 return acc;
5532 },
5533 {
5534 // Do not update the `status` if we have edited it when auto saving.
5535 // It's very important to let the user explicitly save this change,
5536 // because it can lead to unexpected results. An example would be to
5537 // have a draft post and change the status to publish.
5538 status: merged.status === "auto-draft" ? "draft" : void 0
5539 }
5540 );
5541 updatedRecord = await __unstableFetch({
5542 path: `${path}/autosaves`,
5543 method: "POST",
5544 data
5545 });
5546 if (persistedRecord.id === updatedRecord.id) {
5547 let newRecord = {
5548 ...persistedRecord,
5549 ...data,
5550 ...updatedRecord
5551 };
5552 newRecord = Object.keys(newRecord).reduce(
5553 (acc, key) => {
5554 if ([
5555 "title",
5556 "excerpt",
5557 "content",
5558 "meta"
5559 ].includes(key)) {
5560 acc[key] = newRecord[key];
5561 } else if (key === "status") {
5562 acc[key] = persistedRecord.status === "auto-draft" && newRecord.status === "draft" ? newRecord.status : persistedRecord.status;
5563 } else {
5564 acc[key] = persistedRecord[key];
5565 }
5566 return acc;
5567 },
5568 {}
5569 );
5570 dispatch3.receiveEntityRecords(
5571 kind,
5572 name,
5573 newRecord,
5574 void 0,
5575 true
5576 );
5577 } else {
5578 dispatch3.receiveAutosaves(
5579 persistedRecord.id,
5580 updatedRecord
5581 );
5582 }
5583 } else {
5584 let edits = record;
5585 if (entityConfig.__unstablePrePersist) {
5586 edits = {
5587 ...edits,
5588 ...await entityConfig.__unstablePrePersist(
5589 persistedRecord,
5590 edits
5591 )
5592 };
5593 }
5594 updatedRecord = await __unstableFetch({
5595 path,
5596 method: recordId ? "PUT" : "POST",
5597 data: edits
5598 });
5599 dispatch3.receiveEntityRecords(
5600 kind,
5601 name,
5602 updatedRecord,
5603 void 0,
5604 true,
5605 edits
5606 );
5607 if (entityConfig.syncConfig) {
5608 getSyncManager()?.update(
5609 `${kind}/${name}`,
5610 recordId,
5611 __unstableSkipSyncUpdate ? {} : updatedRecord,
5612 LOCAL_UNDO_IGNORED_ORIGIN,
5613 { isSave: true }
5614 );
5615 }
5616 }
5617 } catch (_error) {
5618 hasError = true;
5619 error = _error;
5620 }
5621 dispatch3({
5622 type: "SAVE_ENTITY_RECORD_FINISH",
5623 kind,
5624 name,
5625 recordId,
5626 error,
5627 isAutosave
5628 });
5629 if (hasError && throwOnError) {
5630 throw error;
5631 }
5632 return updatedRecord;
5633 } finally {
5634 dispatch3.__unstableReleaseStoreLock(lock2);
5635 }
5636 };
5637 var __experimentalBatch = (requests) => async ({ dispatch: dispatch3 }) => {
5638 const batch = createBatch();
5639 const api = {
5640 saveEntityRecord(kind, name, record, options) {
5641 return batch.add(
5642 (add) => dispatch3.saveEntityRecord(kind, name, record, {
5643 ...options,
5644 __unstableFetch: add
5645 })
5646 );
5647 },
5648 saveEditedEntityRecord(kind, name, recordId, options) {
5649 return batch.add(
5650 (add) => dispatch3.saveEditedEntityRecord(kind, name, recordId, {
5651 ...options,
5652 __unstableFetch: add
5653 })
5654 );
5655 },
5656 deleteEntityRecord(kind, name, recordId, query, options) {
5657 return batch.add(
5658 (add) => dispatch3.deleteEntityRecord(kind, name, recordId, query, {
5659 ...options,
5660 __unstableFetch: add
5661 })
5662 );
5663 }
5664 };
5665 const resultPromises = requests.map((request) => request(api));
5666 const [, ...results] = await Promise.all([
5667 batch.run(),
5668 ...resultPromises
5669 ]);
5670 return results;
5671 };
5672 var saveEditedEntityRecord = (kind, name, recordId, options) => async ({ select: select4, dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
5673 logEntityDeprecation(kind, name, "saveEditedEntityRecord");
5674 if (!select4.hasEditsForEntityRecord(kind, name, recordId)) {
5675 return;
5676 }
5677 const configs = await resolveSelect2.getEntitiesConfig(kind);
5678 const entityConfig = configs.find(
5679 (config) => config.kind === kind && config.name === name
5680 );
5681 if (!entityConfig) {
5682 return;
5683 }
5684 const entityIdKey = entityConfig.key || DEFAULT_ENTITY_KEY;
5685 const edits = select4.getEntityRecordNonTransientEdits(
5686 kind,
5687 name,
5688 recordId
5689 );
5690 const record = { [entityIdKey]: recordId, ...edits };
5691 return await dispatch3.saveEntityRecord(kind, name, record, options);
5692 };
5693 var __experimentalSaveSpecifiedEntityEdits = (kind, name, recordId, itemsToSave, options) => async ({ select: select4, dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
5694 logEntityDeprecation(
5695 kind,
5696 name,
5697 "__experimentalSaveSpecifiedEntityEdits"
5698 );
5699 if (!select4.hasEditsForEntityRecord(kind, name, recordId)) {
5700 return;
5701 }
5702 const edits = select4.getEntityRecordNonTransientEdits(
5703 kind,
5704 name,
5705 recordId
5706 );
5707 const editsToSave = {};
5708 for (const item of itemsToSave) {
5709 setNestedValue(editsToSave, item, getNestedValue(edits, item));
5710 }
5711 const configs = await resolveSelect2.getEntitiesConfig(kind);
5712 const entityConfig = configs.find(
5713 (config) => config.kind === kind && config.name === name
5714 );
5715 const entityIdKey = entityConfig?.key || DEFAULT_ENTITY_KEY;
5716 if (recordId) {
5717 editsToSave[entityIdKey] = recordId;
5718 }
5719 return await dispatch3.saveEntityRecord(
5720 kind,
5721 name,
5722 editsToSave,
5723 options
5724 );
5725 };
5726 function receiveUploadPermissions(hasUploadPermissions) {
5727 (0, import_deprecated3.default)("wp.data.dispatch( 'core' ).receiveUploadPermissions", {
5728 since: "5.9",
5729 alternative: "receiveUserPermission"
5730 });
5731 return receiveUserPermission("create/media", hasUploadPermissions);
5732 }
5733 function receiveUserPermission(key, isAllowed) {
5734 return {
5735 type: "RECEIVE_USER_PERMISSION",
5736 key,
5737 isAllowed
5738 };
5739 }
5740 function receiveUserPermissions(permissions) {
5741 return {
5742 type: "RECEIVE_USER_PERMISSIONS",
5743 permissions
5744 };
5745 }
5746 function receiveAutosaves(postId, autosaves2) {
5747 return {
5748 type: "RECEIVE_AUTOSAVES",
5749 postId,
5750 autosaves: Array.isArray(autosaves2) ? autosaves2 : [autosaves2]
5751 };
5752 }
5753 function receiveNavigationFallbackId(fallbackId) {
5754 return {
5755 type: "RECEIVE_NAVIGATION_FALLBACK_ID",
5756 fallbackId
5757 };
5758 }
5759 function receiveDefaultTemplateId(query, templateId) {
5760 return {
5761 type: "RECEIVE_DEFAULT_TEMPLATE",
5762 query,
5763 templateId
5764 };
5765 }
5766 var receiveRevisions = (kind, name, recordKey, records, query, invalidateCache = false, meta) => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
5767 logEntityDeprecation(kind, name, "receiveRevisions");
5768 const configs = await resolveSelect2.getEntitiesConfig(kind);
5769 const entityConfig = configs.find(
5770 (config) => config.kind === kind && config.name === name
5771 );
5772 const key = entityConfig?.revisionKey ?? DEFAULT_ENTITY_KEY;
5773 dispatch3({
5774 type: "RECEIVE_ITEM_REVISIONS",
5775 key,
5776 items: records,
5777 recordKey,
5778 meta,
5779 query,
5780 kind,
5781 name,
5782 invalidateCache
5783 });
5784 };
5785
5786 // packages/core-data/build-module/private-actions.mjs
5787 var private_actions_exports = {};
5788 __export(private_actions_exports, {
5789 __unstableNotifySyncUndoManagerChange: () => __unstableNotifySyncUndoManagerChange,
5790 editMediaEntity: () => editMediaEntity,
5791 receiveEditorAssets: () => receiveEditorAssets,
5792 receiveEditorSettings: () => receiveEditorSettings,
5793 receiveRegisteredPostMeta: () => receiveRegisteredPostMeta,
5794 receiveViewConfig: () => receiveViewConfig,
5795 setCollaborationSupported: () => setCollaborationSupported,
5796 setSyncConnectionStatus: () => setSyncConnectionStatus
5797 });
5798 var import_api_fetch5 = __toESM(require_api_fetch(), 1);
5799 function receiveRegisteredPostMeta(postType, registeredPostMeta2) {
5800 return {
5801 type: "RECEIVE_REGISTERED_POST_META",
5802 postType,
5803 registeredPostMeta: registeredPostMeta2
5804 };
5805 }
5806 var editMediaEntity = (recordId, edits = {}, { __unstableFetch = import_api_fetch5.default, throwOnError = false } = {}) => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
5807 if (!recordId) {
5808 return;
5809 }
5810 const kind = "postType";
5811 const name = "attachment";
5812 const configs = await resolveSelect2.getEntitiesConfig(kind);
5813 const entityConfig = configs.find(
5814 (config) => config.kind === kind && config.name === name
5815 );
5816 if (!entityConfig) {
5817 return;
5818 }
5819 const lock2 = await dispatch3.__unstableAcquireStoreLock(
5820 STORE_NAME,
5821 ["entities", "records", kind, name, recordId],
5822 { exclusive: true }
5823 );
5824 let updatedRecord;
5825 let error;
5826 let hasError = false;
5827 try {
5828 dispatch3({
5829 type: "SAVE_ENTITY_RECORD_START",
5830 kind,
5831 name,
5832 recordId
5833 });
5834 try {
5835 const path = `${entityConfig.baseURL}/${recordId}/edit`;
5836 const newRecord = await __unstableFetch({
5837 path,
5838 method: "POST",
5839 data: {
5840 ...edits
5841 }
5842 });
5843 if (newRecord) {
5844 dispatch3.receiveEntityRecords(
5845 kind,
5846 name,
5847 newRecord,
5848 void 0,
5849 true,
5850 void 0,
5851 void 0
5852 );
5853 updatedRecord = newRecord;
5854 }
5855 } catch (e) {
5856 error = e;
5857 hasError = true;
5858 }
5859 dispatch3({
5860 type: "SAVE_ENTITY_RECORD_FINISH",
5861 kind,
5862 name,
5863 recordId,
5864 error
5865 });
5866 if (hasError && throwOnError) {
5867 throw error;
5868 }
5869 return updatedRecord;
5870 } finally {
5871 dispatch3.__unstableReleaseStoreLock(lock2);
5872 }
5873 };
5874 function receiveEditorSettings(settings) {
5875 return {
5876 type: "RECEIVE_EDITOR_SETTINGS",
5877 settings
5878 };
5879 }
5880 function receiveEditorAssets(assets) {
5881 return {
5882 type: "RECEIVE_EDITOR_ASSETS",
5883 assets
5884 };
5885 }
5886 var setCollaborationSupported = (supported) => ({ dispatch: dispatch3 }) => {
5887 dispatch3({ type: "SET_COLLABORATION_SUPPORTED", supported });
5888 if (!supported && hasSyncManager()) {
5889 getSyncManager().unloadAll();
5890 }
5891 };
5892 function receiveViewConfig(kind, name, config) {
5893 return {
5894 type: "RECEIVE_VIEW_CONFIG",
5895 kind,
5896 name,
5897 config
5898 };
5899 }
5900 function __unstableNotifySyncUndoManagerChange(state) {
5901 return {
5902 type: "SYNC_UNDO_MANAGER_CHANGE",
5903 ...state
5904 };
5905 }
5906 function setSyncConnectionStatus(kind, name, key, status) {
5907 if (!status) {
5908 return {
5909 type: "CLEAR_SYNC_CONNECTION_STATUS",
5910 kind,
5911 name,
5912 key
5913 };
5914 }
5915 return {
5916 type: "SET_SYNC_CONNECTION_STATUS",
5917 kind,
5918 name,
5919 key,
5920 status
5921 };
5922 }
5923
5924 // packages/core-data/build-module/resolvers.mjs
5925 var resolvers_exports = {};
5926 __export(resolvers_exports, {
5927 __experimentalGetCurrentGlobalStylesId: () => __experimentalGetCurrentGlobalStylesId2,
5928 __experimentalGetCurrentThemeBaseGlobalStyles: () => __experimentalGetCurrentThemeBaseGlobalStyles2,
5929 __experimentalGetCurrentThemeGlobalStylesVariations: () => __experimentalGetCurrentThemeGlobalStylesVariations2,
5930 canUser: () => canUser2,
5931 canUserEditEntityRecord: () => canUserEditEntityRecord2,
5932 getAuthors: () => getAuthors2,
5933 getAutosave: () => getAutosave2,
5934 getAutosaves: () => getAutosaves2,
5935 getBlockPatternCategories: () => getBlockPatternCategories2,
5936 getBlockPatterns: () => getBlockPatterns2,
5937 getCurrentTheme: () => getCurrentTheme2,
5938 getCurrentThemeGlobalStylesRevisions: () => getCurrentThemeGlobalStylesRevisions2,
5939 getCurrentUser: () => getCurrentUser2,
5940 getDefaultTemplateId: () => getDefaultTemplateId2,
5941 getEditedEntityRecord: () => getEditedEntityRecord2,
5942 getEditorAssets: () => getEditorAssets2,
5943 getEditorSettings: () => getEditorSettings2,
5944 getEmbedPreview: () => getEmbedPreview2,
5945 getEntitiesConfig: () => getEntitiesConfig2,
5946 getEntityRecord: () => getEntityRecord2,
5947 getEntityRecords: () => getEntityRecords2,
5948 getEntityRecordsTotalItems: () => getEntityRecordsTotalItems2,
5949 getEntityRecordsTotalPages: () => getEntityRecordsTotalPages2,
5950 getNavigationFallbackId: () => getNavigationFallbackId2,
5951 getRawEntityRecord: () => getRawEntityRecord2,
5952 getRegisteredPostMeta: () => getRegisteredPostMeta2,
5953 getRevision: () => getRevision2,
5954 getRevisions: () => getRevisions2,
5955 getThemeSupports: () => getThemeSupports2,
5956 getUserPatternCategories: () => getUserPatternCategories2,
5957 getViewConfig: () => getViewConfig2
5958 });
5959 var import_url6 = __toESM(require_url(), 1);
5960 var import_html_entities2 = __toESM(require_html_entities(), 1);
5961 var import_api_fetch9 = __toESM(require_api_fetch(), 1);
5962
5963 // packages/core-data/build-module/fetch/index.mjs
5964 var import_api_fetch8 = __toESM(require_api_fetch(), 1);
5965
5966 // packages/core-data/build-module/fetch/__experimental-fetch-link-suggestions.mjs
5967 var import_api_fetch6 = __toESM(require_api_fetch(), 1);
5968 var import_url4 = __toESM(require_url(), 1);
5969 var import_html_entities = __toESM(require_html_entities(), 1);
5970 var import_i18n2 = __toESM(require_i18n(), 1);
5971 async function fetchLinkSuggestions(search, searchOptions = {}, editorSettings2 = {}) {
5972 const searchOptionsToUse = searchOptions.isInitialSuggestions && searchOptions.initialSuggestionsSearchOptions ? {
5973 ...searchOptions,
5974 ...searchOptions.initialSuggestionsSearchOptions
5975 } : searchOptions;
5976 const {
5977 type,
5978 subtype,
5979 page,
5980 perPage = searchOptions.isInitialSuggestions ? 3 : 20
5981 } = searchOptionsToUse;
5982 const { disablePostFormats = false } = editorSettings2;
5983 const queries2 = [];
5984 if (!type || type === "post") {
5985 queries2.push(
5986 (0, import_api_fetch6.default)({
5987 path: (0, import_url4.addQueryArgs)("/wp/v2/search", {
5988 search,
5989 page,
5990 per_page: perPage,
5991 type: "post",
5992 subtype
5993 })
5994 }).then((results2) => {
5995 return results2.map((result) => {
5996 return {
5997 id: result.id,
5998 url: result.url,
5999 title: (0, import_html_entities.decodeEntities)(result.title || "") || (0, import_i18n2.__)("(no title)"),
6000 type: result.subtype || result.type,
6001 kind: "post-type"
6002 };
6003 });
6004 }).catch(() => [])
6005 // Fail by returning no results.
6006 );
6007 }
6008 if (!type || type === "term") {
6009 queries2.push(
6010 (0, import_api_fetch6.default)({
6011 path: (0, import_url4.addQueryArgs)("/wp/v2/search", {
6012 search,
6013 page,
6014 per_page: perPage,
6015 type: "term",
6016 subtype
6017 })
6018 }).then((results2) => {
6019 return results2.map((result) => {
6020 return {
6021 id: result.id,
6022 url: result.url,
6023 title: (0, import_html_entities.decodeEntities)(result.title || "") || (0, import_i18n2.__)("(no title)"),
6024 type: result.subtype || result.type,
6025 kind: "taxonomy"
6026 };
6027 });
6028 }).catch(() => [])
6029 // Fail by returning no results.
6030 );
6031 }
6032 if (!disablePostFormats && (!type || type === "post-format")) {
6033 queries2.push(
6034 (0, import_api_fetch6.default)({
6035 path: (0, import_url4.addQueryArgs)("/wp/v2/search", {
6036 search,
6037 page,
6038 per_page: perPage,
6039 type: "post-format",
6040 subtype
6041 })
6042 }).then((results2) => {
6043 return results2.map((result) => {
6044 return {
6045 id: result.id,
6046 url: result.url,
6047 title: (0, import_html_entities.decodeEntities)(result.title || "") || (0, import_i18n2.__)("(no title)"),
6048 type: result.subtype || result.type,
6049 kind: "taxonomy"
6050 };
6051 });
6052 }).catch(() => [])
6053 // Fail by returning no results.
6054 );
6055 }
6056 if (!type || type === "attachment") {
6057 queries2.push(
6058 (0, import_api_fetch6.default)({
6059 path: (0, import_url4.addQueryArgs)("/wp/v2/media", {
6060 search,
6061 page,
6062 per_page: perPage
6063 })
6064 }).then((results2) => {
6065 return results2.map((result) => {
6066 return {
6067 id: result.id,
6068 url: result.source_url,
6069 title: (0, import_html_entities.decodeEntities)(result.title.rendered || "") || (0, import_i18n2.__)("(no title)"),
6070 type: result.type,
6071 kind: "media"
6072 };
6073 });
6074 }).catch(() => [])
6075 // Fail by returning no results.
6076 );
6077 }
6078 const responses = await Promise.all(queries2);
6079 let results = responses.flat();
6080 results = results.filter((result) => !!result.id);
6081 results = sortResults(results, search);
6082 results = results.slice(0, perPage);
6083 return results;
6084 }
6085 function sortResults(results, search) {
6086 const searchTokens = tokenize(search);
6087 const scores = {};
6088 for (const result of results) {
6089 if (result.title) {
6090 const titleTokens = tokenize(result.title);
6091 const exactMatchingTokens = titleTokens.filter(
6092 (titleToken) => searchTokens.some(
6093 (searchToken) => titleToken === searchToken
6094 )
6095 );
6096 const subMatchingTokens = titleTokens.filter(
6097 (titleToken) => searchTokens.some(
6098 (searchToken) => titleToken !== searchToken && titleToken.includes(searchToken)
6099 )
6100 );
6101 const exactMatchScore = exactMatchingTokens.length / titleTokens.length * 10;
6102 const subMatchScore = subMatchingTokens.length / titleTokens.length;
6103 scores[result.id] = exactMatchScore + subMatchScore;
6104 } else {
6105 scores[result.id] = 0;
6106 }
6107 }
6108 return results.sort((a, b) => scores[b.id] - scores[a.id]);
6109 }
6110 function tokenize(text) {
6111 return text.toLowerCase().match(/[\p{L}\p{N}]+/gu) || [];
6112 }
6113
6114 // packages/core-data/build-module/fetch/__experimental-fetch-url-data.mjs
6115 var import_api_fetch7 = __toESM(require_api_fetch(), 1);
6116 var import_url5 = __toESM(require_url(), 1);
6117 var CACHE = /* @__PURE__ */ new Map();
6118 var fetchUrlData = async (url, options = {}) => {
6119 const endpoint = "/wp-block-editor/v1/url-details";
6120 const args = {
6121 url: (0, import_url5.prependHTTP)(url)
6122 };
6123 if (!(0, import_url5.isURL)(url)) {
6124 return Promise.reject(`${url} is not a valid URL.`);
6125 }
6126 const protocol = (0, import_url5.getProtocol)(url);
6127 if (!protocol || !(0, import_url5.isValidProtocol)(protocol) || !protocol.startsWith("http") || !/^https?:\/\/[^\/\s]/i.test(url)) {
6128 return Promise.reject(
6129 `${url} does not have a valid protocol. URLs must be "http" based`
6130 );
6131 }
6132 if (CACHE.has(url)) {
6133 return CACHE.get(url);
6134 }
6135 return (0, import_api_fetch7.default)({
6136 path: (0, import_url5.addQueryArgs)(endpoint, args),
6137 ...options
6138 }).then((res) => {
6139 CACHE.set(url, res);
6140 return res;
6141 });
6142 };
6143 var experimental_fetch_url_data_default = fetchUrlData;
6144
6145 // packages/core-data/build-module/fetch/index.mjs
6146 async function fetchBlockPatterns() {
6147 const restPatterns = await (0, import_api_fetch8.default)({
6148 path: "/wp/v2/block-patterns/patterns"
6149 });
6150 if (!restPatterns) {
6151 return [];
6152 }
6153 return restPatterns.map(
6154 (pattern) => Object.fromEntries(
6155 Object.entries(pattern).map(([key, value]) => [
6156 camelCase(key),
6157 value
6158 ])
6159 )
6160 );
6161 }
6162
6163 // packages/core-data/build-module/parsed-blocks-cache.mjs
6164 var parsedBlocksCache = /* @__PURE__ */ new Map();
6165 function getCacheKey(kind, name, id) {
6166 return `${kind}:${name}:${id}`;
6167 }
6168
6169 // packages/core-data/build-module/resolvers.mjs
6170 var getAuthors2 = (query) => async ({ dispatch: dispatch3 }) => {
6171 const path = (0, import_url6.addQueryArgs)(
6172 "/wp/v2/users/?who=authors&per_page=100",
6173 query
6174 );
6175 const users2 = await (0, import_api_fetch9.default)({ path });
6176 dispatch3.receiveUserQuery(path, users2);
6177 };
6178 var getCurrentUser2 = () => async ({ dispatch: dispatch3 }) => {
6179 const currentUser2 = await (0, import_api_fetch9.default)({ path: "/wp/v2/users/me" });
6180 dispatch3.receiveCurrentUser(currentUser2);
6181 };
6182 var getEntityRecord2 = (kind, name, key = "", query) => async ({ select: select4, dispatch: dispatch3, registry, resolveSelect: resolveSelect2 }) => {
6183 const configs = await resolveSelect2.getEntitiesConfig(kind);
6184 const entityConfig = configs.find(
6185 (config) => config.name === name && config.kind === kind
6186 );
6187 if (!entityConfig) {
6188 return;
6189 }
6190 const lock2 = await dispatch3.__unstableAcquireStoreLock(
6191 STORE_NAME,
6192 ["entities", "records", kind, name, key],
6193 { exclusive: false }
6194 );
6195 try {
6196 if (query !== void 0 && query._fields) {
6197 query = {
6198 ...query,
6199 _fields: [
6200 .../* @__PURE__ */ new Set([
6201 ...get_normalized_comma_separable_default(query._fields) || [],
6202 entityConfig.key || DEFAULT_ENTITY_KEY
6203 ])
6204 ].join()
6205 };
6206 }
6207 if (query !== void 0 && query._fields) {
6208 const hasRecord = select4.hasEntityRecord(
6209 kind,
6210 name,
6211 key,
6212 query
6213 );
6214 if (hasRecord) {
6215 return;
6216 }
6217 }
6218 let { baseURL } = entityConfig;
6219 if (kind === "postType" && name === "wp_template" && (key && typeof key === "string" && !/^\d+$/.test(key) || !window?.__experimentalTemplateActivate)) {
6220 baseURL = baseURL.slice(0, baseURL.lastIndexOf("/")) + "/templates";
6221 }
6222 const path = (0, import_url6.addQueryArgs)(baseURL + (key ? "/" + key : ""), {
6223 ...entityConfig.baseURLParams,
6224 ...query
6225 });
6226 const response = await (0, import_api_fetch9.default)({ path, parse: false });
6227 const record = await response.json();
6228 const permissions = getUserPermissionsFromAllowHeader(
6229 response.headers?.get("allow")
6230 );
6231 const canUserResolutionsArgs = [];
6232 const receiveUserPermissionArgs = {};
6233 for (const action of ALLOWED_RESOURCE_ACTIONS) {
6234 receiveUserPermissionArgs[getUserPermissionCacheKey(action, {
6235 kind,
6236 name,
6237 id: key
6238 })] = permissions[action];
6239 canUserResolutionsArgs.push([
6240 action,
6241 { kind, name, id: key }
6242 ]);
6243 }
6244 if (entityConfig.syncConfig && isNumericID(key) && !query) {
6245 const objectType = `${kind}/${name}`;
6246 const objectId = key;
6247 const recordWithTransients = { ...record };
6248 Object.entries(entityConfig.transientEdits ?? {}).filter(
6249 ([propName, transientConfig]) => void 0 === recordWithTransients[propName] && transientConfig && "object" === typeof transientConfig && "read" in transientConfig && "function" === typeof transientConfig.read
6250 ).forEach(([propName, transientConfig]) => {
6251 recordWithTransients[propName] = transientConfig.read(recordWithTransients);
6252 });
6253 if (recordWithTransients.blocks && typeof recordWithTransients.content?.raw === "string") {
6254 parsedBlocksCache.set(getCacheKey(kind, name, key), {
6255 content: recordWithTransients.content.raw,
6256 blocks: recordWithTransients.blocks
6257 });
6258 }
6259 void getSyncManager()?.load(
6260 entityConfig.syncConfig,
6261 objectType,
6262 objectId,
6263 recordWithTransients,
6264 {
6265 // Handle edits sourced from the sync manager.
6266 editRecord: (edits, options = {}) => {
6267 if (!Object.keys(edits).length) {
6268 return;
6269 }
6270 dispatch3({
6271 type: "EDIT_ENTITY_RECORD",
6272 kind,
6273 name,
6274 recordId: key,
6275 edits,
6276 meta: {
6277 undo: void 0
6278 },
6279 options
6280 });
6281 },
6282 // Get the current entity record (with edits)
6283 getEditedRecord: async () => await resolveSelect2.getEditedEntityRecord(
6284 kind,
6285 name,
6286 key
6287 ),
6288 // Handle sync connection status changes.
6289 onStatusChange: (status) => {
6290 dispatch3.setSyncConnectionStatus(
6291 kind,
6292 name,
6293 key,
6294 status
6295 );
6296 },
6297 // Refetch the current entity record from the database.
6298 refetchRecord: async () => {
6299 dispatch3.receiveEntityRecords(
6300 kind,
6301 name,
6302 await (0, import_api_fetch9.default)({ path, parse: true }),
6303 query
6304 );
6305 },
6306 // Persist the CRDT document.
6307 //
6308 // TODO: Currently, persisted CRDT documents are stored in post meta.
6309 // This effectively means that only post entities support CRDT
6310 // persistence. As we add support for syncing additional entity,
6311 // we'll need to revisit where persisted CRDT documents are stored.
6312 persistCRDTDoc: () => {
6313 if (!entityConfig.syncConfig?.supportsPersistence) {
6314 return;
6315 }
6316 return resolveSelect2.getEditedEntityRecord(kind, name, key).then(async (editedRecord) => {
6317 const { meta, status } = editedRecord;
6318 if ("auto-draft" === status || !meta) {
6319 return;
6320 }
6321 const entityIdKey = entityConfig.key || DEFAULT_ENTITY_KEY;
6322 const entityId = editedRecord[entityIdKey];
6323 await saveCRDTDoc(
6324 `${kind}/${name}`,
6325 entityId
6326 );
6327 });
6328 },
6329 addUndoMeta: (ydoc, meta) => {
6330 const selectionHistory = getSelectionHistory(ydoc);
6331 if (selectionHistory) {
6332 meta.set(
6333 "selectionHistory",
6334 selectionHistory
6335 );
6336 }
6337 },
6338 onUndoStackChange: (undoState) => {
6339 dispatch3.__unstableNotifySyncUndoManagerChange(
6340 undoState
6341 );
6342 },
6343 restoreUndoMeta: (ydoc, meta) => {
6344 const selectionHistory = meta.get("selectionHistory");
6345 if (selectionHistory) {
6346 setTimeout(() => {
6347 restoreSelection(selectionHistory, ydoc);
6348 }, 0);
6349 }
6350 }
6351 }
6352 );
6353 }
6354 registry.batch(() => {
6355 dispatch3.receiveEntityRecords(kind, name, record, query);
6356 dispatch3.receiveUserPermissions(receiveUserPermissionArgs);
6357 dispatch3.finishResolutions("canUser", canUserResolutionsArgs);
6358 });
6359 } finally {
6360 dispatch3.__unstableReleaseStoreLock(lock2);
6361 }
6362 };
6363 getEntityRecord2.shouldInvalidate = (action, kind, name) => {
6364 return kind === "root" && name === "site" && (action.type === "RECEIVE_ITEMS" && // Making sure persistedEdits is set seems to be the only way of
6365 // knowing whether it's an update or fetch. Only an update would
6366 // have persistedEdits.
6367 action.persistedEdits && action.persistedEdits.status !== "auto-draft" || action.type === "REMOVE_ITEMS") && action.kind === "postType" && action.name === "wp_template";
6368 };
6369 var getRawEntityRecord2 = forward_resolver_default("getEntityRecord");
6370 var getEditedEntityRecord2 = forward_resolver_default("getEntityRecord");
6371 var getEntityRecords2 = (kind, name, query = {}) => async ({ dispatch: dispatch3, registry, resolveSelect: resolveSelect2 }) => {
6372 const configs = await resolveSelect2.getEntitiesConfig(kind);
6373 const entityConfig = configs.find(
6374 (config) => config.name === name && config.kind === kind
6375 );
6376 if (!entityConfig) {
6377 return;
6378 }
6379 const lock2 = await dispatch3.__unstableAcquireStoreLock(
6380 STORE_NAME,
6381 ["entities", "records", kind, name],
6382 { exclusive: false }
6383 );
6384 const rawQuery = { ...query };
6385 const key = entityConfig.key || DEFAULT_ENTITY_KEY;
6386 function getResolutionsArgs(records, recordsQuery) {
6387 const normalizedQuery = normalizeQueryForResolution(recordsQuery);
6388 return records.filter((record) => record?.[key]).map((record) => [
6389 kind,
6390 name,
6391 record[key],
6392 normalizedQuery
6393 ]);
6394 }
6395 try {
6396 if (query._fields) {
6397 query = {
6398 ...query,
6399 _fields: [
6400 .../* @__PURE__ */ new Set([
6401 ...get_normalized_comma_separable_default(query._fields) || [],
6402 key
6403 ])
6404 ].join()
6405 };
6406 }
6407 let { baseURL } = entityConfig;
6408 const { combinedTemplates = true } = query;
6409 if (kind === "postType" && name === "wp_template" && combinedTemplates) {
6410 baseURL = baseURL.slice(0, baseURL.lastIndexOf("/")) + "/templates";
6411 }
6412 const path = (0, import_url6.addQueryArgs)(baseURL, {
6413 ...entityConfig.baseURLParams,
6414 ...query
6415 });
6416 let records = [], meta;
6417 if (entityConfig.supportsPagination && query.per_page !== -1) {
6418 const response = await (0, import_api_fetch9.default)({ path, parse: false });
6419 records = Object.values(await response.json());
6420 meta = {
6421 totalItems: parseInt(
6422 response.headers.get("X-WP-Total")
6423 ),
6424 totalPages: parseInt(
6425 response.headers.get("X-WP-TotalPages")
6426 )
6427 };
6428 } else if (query.per_page === -1 && query[RECEIVE_INTERMEDIATE_RESULTS] === true) {
6429 let page = 1;
6430 let totalPages;
6431 do {
6432 const response = await (0, import_api_fetch9.default)({
6433 path: (0, import_url6.addQueryArgs)(path, { page, per_page: 100 }),
6434 parse: false
6435 });
6436 const pageRecords = Object.values(await response.json());
6437 totalPages = parseInt(
6438 response.headers.get("X-WP-TotalPages")
6439 );
6440 if (!meta) {
6441 meta = {
6442 totalItems: parseInt(
6443 response.headers.get("X-WP-Total")
6444 ),
6445 totalPages: 1
6446 };
6447 }
6448 records.push(...pageRecords);
6449 registry.batch(() => {
6450 dispatch3.receiveEntityRecords(
6451 kind,
6452 name,
6453 records,
6454 query,
6455 false,
6456 void 0,
6457 meta
6458 );
6459 dispatch3.finishResolutions(
6460 "getEntityRecord",
6461 getResolutionsArgs(pageRecords, rawQuery)
6462 );
6463 });
6464 page++;
6465 } while (page <= totalPages);
6466 } else {
6467 records = Object.values(await (0, import_api_fetch9.default)({ path }));
6468 meta = {
6469 totalItems: records.length,
6470 totalPages: 1
6471 };
6472 }
6473 if (entityConfig.syncConfig && -1 === query.per_page) {
6474 const objectType = `${kind}/${name}`;
6475 getSyncManager()?.loadCollection(
6476 entityConfig.syncConfig,
6477 objectType,
6478 {
6479 onStatusChange: (status) => {
6480 dispatch3.setSyncConnectionStatus(
6481 kind,
6482 name,
6483 null,
6484 status
6485 );
6486 },
6487 refetchRecords: async () => {
6488 dispatch3.receiveEntityRecords(
6489 kind,
6490 name,
6491 await (0, import_api_fetch9.default)({ path, parse: true }),
6492 query
6493 );
6494 }
6495 }
6496 );
6497 }
6498 if (query._fields) {
6499 records = records.map((record) => {
6500 query._fields.split(",").forEach((field) => {
6501 if (!record.hasOwnProperty(field)) {
6502 record[field] = void 0;
6503 }
6504 });
6505 return record;
6506 });
6507 }
6508 registry.batch(() => {
6509 dispatch3.receiveEntityRecords(
6510 kind,
6511 name,
6512 records,
6513 query,
6514 false,
6515 void 0,
6516 meta
6517 );
6518 const targetHints = records.filter(
6519 (record) => !!record?.[key] && !!record?._links?.self?.[0]?.targetHints?.allow
6520 ).map((record) => ({
6521 id: record[key],
6522 permissions: getUserPermissionsFromAllowHeader(
6523 record._links.self[0].targetHints.allow
6524 )
6525 }));
6526 const canUserResolutionsArgs = [];
6527 const receiveUserPermissionArgs = {};
6528 for (const targetHint of targetHints) {
6529 for (const action of ALLOWED_RESOURCE_ACTIONS) {
6530 canUserResolutionsArgs.push([
6531 action,
6532 { kind, name, id: targetHint.id }
6533 ]);
6534 receiveUserPermissionArgs[getUserPermissionCacheKey(action, {
6535 kind,
6536 name,
6537 id: targetHint.id
6538 })] = targetHint.permissions[action];
6539 }
6540 }
6541 if (targetHints.length > 0) {
6542 dispatch3.receiveUserPermissions(
6543 receiveUserPermissionArgs
6544 );
6545 dispatch3.finishResolutions(
6546 "canUser",
6547 canUserResolutionsArgs
6548 );
6549 }
6550 dispatch3.finishResolutions(
6551 "getEntityRecord",
6552 getResolutionsArgs(records, rawQuery)
6553 );
6554 dispatch3.__unstableReleaseStoreLock(lock2);
6555 });
6556 } catch {
6557 dispatch3.__unstableReleaseStoreLock(lock2);
6558 }
6559 };
6560 getEntityRecords2.shouldInvalidate = (action, kind, name) => {
6561 return (action.type === "RECEIVE_ITEMS" || action.type === "REMOVE_ITEMS") && action.invalidateCache && kind === action.kind && name === action.name;
6562 };
6563 var getEntityRecordsTotalItems2 = forward_resolver_default("getEntityRecords");
6564 var getEntityRecordsTotalPages2 = forward_resolver_default("getEntityRecords");
6565 var getCurrentTheme2 = () => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
6566 const activeThemes = await resolveSelect2.getEntityRecords(
6567 "root",
6568 "theme",
6569 { status: "active" }
6570 );
6571 dispatch3.receiveCurrentTheme(activeThemes[0]);
6572 };
6573 var getThemeSupports2 = forward_resolver_default("getCurrentTheme");
6574 var getEmbedPreview2 = (url) => async ({ dispatch: dispatch3 }) => {
6575 try {
6576 const embedProxyResponse = await (0, import_api_fetch9.default)({
6577 path: (0, import_url6.addQueryArgs)("/oembed/1.0/proxy", { url })
6578 });
6579 dispatch3.receiveEmbedPreview(url, embedProxyResponse);
6580 } catch {
6581 dispatch3.receiveEmbedPreview(url, false);
6582 }
6583 };
6584 var canUser2 = (requestedAction, resource, id) => async ({ dispatch: dispatch3, registry, resolveSelect: resolveSelect2 }) => {
6585 if (!ALLOWED_RESOURCE_ACTIONS.includes(requestedAction)) {
6586 throw new Error(`'${requestedAction}' is not a valid action.`);
6587 }
6588 const { hasStartedResolution } = registry.select(STORE_NAME);
6589 for (const relatedAction of ALLOWED_RESOURCE_ACTIONS) {
6590 if (relatedAction === requestedAction) {
6591 continue;
6592 }
6593 const isAlreadyResolving = hasStartedResolution("canUser", [
6594 relatedAction,
6595 resource,
6596 id
6597 ]);
6598 if (isAlreadyResolving) {
6599 return;
6600 }
6601 }
6602 let resourcePath = null;
6603 if (typeof resource === "object") {
6604 if (!resource.kind || !resource.name) {
6605 throw new Error("The entity resource object is not valid.");
6606 }
6607 const configs = await resolveSelect2.getEntitiesConfig(
6608 resource.kind
6609 );
6610 const entityConfig = configs.find(
6611 (config) => config.name === resource.name && config.kind === resource.kind
6612 );
6613 if (!entityConfig) {
6614 return;
6615 }
6616 resourcePath = entityConfig.baseURL + (resource.id ? "/" + resource.id : "");
6617 } else {
6618 resourcePath = `/wp/v2/${resource}` + (id ? "/" + id : "");
6619 }
6620 let response;
6621 try {
6622 response = await (0, import_api_fetch9.default)({
6623 path: resourcePath,
6624 method: "OPTIONS",
6625 parse: false
6626 });
6627 } catch {
6628 return;
6629 }
6630 const permissions = getUserPermissionsFromAllowHeader(
6631 response.headers?.get("allow")
6632 );
6633 const receiveUserPermissionArgs = {};
6634 const canUserResolutionsArgs = [];
6635 for (const action of ALLOWED_RESOURCE_ACTIONS) {
6636 receiveUserPermissionArgs[getUserPermissionCacheKey(action, resource, id)] = permissions[action];
6637 if (action !== requestedAction) {
6638 canUserResolutionsArgs.push([action, resource, id]);
6639 }
6640 }
6641 registry.batch(() => {
6642 dispatch3.receiveUserPermissions(receiveUserPermissionArgs);
6643 dispatch3.finishResolutions("canUser", canUserResolutionsArgs);
6644 });
6645 };
6646 var canUserEditEntityRecord2 = (kind, name, recordId) => async ({ dispatch: dispatch3 }) => {
6647 await dispatch3(canUser2("update", { kind, name, id: recordId }));
6648 };
6649 var getAutosaves2 = (postType, postId) => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
6650 const {
6651 rest_base: restBase,
6652 rest_namespace: restNamespace = "wp/v2",
6653 supports
6654 } = await resolveSelect2.getPostType(postType);
6655 if (!supports?.autosave) {
6656 return;
6657 }
6658 const autosaves2 = await (0, import_api_fetch9.default)({
6659 path: `/${restNamespace}/${restBase}/${postId}/autosaves?context=edit`
6660 });
6661 if (autosaves2 && autosaves2.length) {
6662 dispatch3.receiveAutosaves(postId, autosaves2);
6663 }
6664 };
6665 var getAutosave2 = (postType, postId) => async ({ resolveSelect: resolveSelect2 }) => {
6666 await resolveSelect2.getAutosaves(postType, postId);
6667 };
6668 var __experimentalGetCurrentGlobalStylesId2 = () => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
6669 const activeThemes = await resolveSelect2.getEntityRecords(
6670 "root",
6671 "theme",
6672 { status: "active" }
6673 );
6674 const globalStylesURL = activeThemes?.[0]?._links?.["wp:user-global-styles"]?.[0]?.href;
6675 if (!globalStylesURL) {
6676 return;
6677 }
6678 const matches = globalStylesURL.match(/\/(\d+)(?:\?|$)/);
6679 const id = matches ? Number(matches[1]) : null;
6680 if (id) {
6681 dispatch3.__experimentalReceiveCurrentGlobalStylesId(id);
6682 }
6683 };
6684 var __experimentalGetCurrentThemeBaseGlobalStyles2 = () => async ({ resolveSelect: resolveSelect2, dispatch: dispatch3 }) => {
6685 const currentTheme2 = await resolveSelect2.getCurrentTheme();
6686 const themeGlobalStyles = await (0, import_api_fetch9.default)({
6687 path: `/wp/v2/global-styles/themes/${currentTheme2.stylesheet}?context=view`
6688 });
6689 dispatch3.__experimentalReceiveThemeBaseGlobalStyles(
6690 currentTheme2.stylesheet,
6691 themeGlobalStyles
6692 );
6693 };
6694 var __experimentalGetCurrentThemeGlobalStylesVariations2 = () => async ({ resolveSelect: resolveSelect2, dispatch: dispatch3 }) => {
6695 const currentTheme2 = await resolveSelect2.getCurrentTheme();
6696 const variations = await (0, import_api_fetch9.default)({
6697 path: `/wp/v2/global-styles/themes/${currentTheme2.stylesheet}/variations?context=view`
6698 });
6699 dispatch3.__experimentalReceiveThemeGlobalStyleVariations(
6700 currentTheme2.stylesheet,
6701 variations
6702 );
6703 };
6704 var getCurrentThemeGlobalStylesRevisions2 = () => async ({ resolveSelect: resolveSelect2, dispatch: dispatch3 }) => {
6705 const globalStylesId = await resolveSelect2.__experimentalGetCurrentGlobalStylesId();
6706 const record = globalStylesId ? await resolveSelect2.getEntityRecord(
6707 "root",
6708 "globalStyles",
6709 globalStylesId
6710 ) : void 0;
6711 const revisionsURL = record?._links?.["version-history"]?.[0]?.href;
6712 if (revisionsURL) {
6713 const resetRevisions = await (0, import_api_fetch9.default)({
6714 url: revisionsURL
6715 });
6716 const revisions = resetRevisions?.map(
6717 (revision) => Object.fromEntries(
6718 Object.entries(revision).map(([key, value]) => [
6719 camelCase(key),
6720 value
6721 ])
6722 )
6723 );
6724 dispatch3.receiveThemeGlobalStyleRevisions(
6725 globalStylesId,
6726 revisions
6727 );
6728 }
6729 };
6730 getCurrentThemeGlobalStylesRevisions2.shouldInvalidate = (action) => {
6731 return action.type === "SAVE_ENTITY_RECORD_FINISH" && action.kind === "root" && !action.error && action.name === "globalStyles";
6732 };
6733 var getBlockPatterns2 = () => async ({ dispatch: dispatch3 }) => {
6734 const patterns = await fetchBlockPatterns();
6735 dispatch3({ type: "RECEIVE_BLOCK_PATTERNS", patterns });
6736 };
6737 var getBlockPatternCategories2 = () => async ({ dispatch: dispatch3 }) => {
6738 const categories = await (0, import_api_fetch9.default)({
6739 path: "/wp/v2/block-patterns/categories"
6740 });
6741 dispatch3({ type: "RECEIVE_BLOCK_PATTERN_CATEGORIES", categories });
6742 };
6743 var getUserPatternCategories2 = () => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
6744 const patternCategories = await resolveSelect2.getEntityRecords(
6745 "taxonomy",
6746 "wp_pattern_category",
6747 {
6748 per_page: -1,
6749 _fields: "id,name,description,slug",
6750 context: "view"
6751 }
6752 );
6753 const mappedPatternCategories = patternCategories?.map((userCategory) => ({
6754 ...userCategory,
6755 label: (0, import_html_entities2.decodeEntities)(userCategory.name),
6756 name: userCategory.slug
6757 })) || [];
6758 dispatch3({
6759 type: "RECEIVE_USER_PATTERN_CATEGORIES",
6760 patternCategories: mappedPatternCategories
6761 });
6762 };
6763 var getNavigationFallbackId2 = () => async ({ dispatch: dispatch3, select: select4, registry }) => {
6764 const fallback = await (0, import_api_fetch9.default)({
6765 path: (0, import_url6.addQueryArgs)("/wp-block-editor/v1/navigation-fallback", {
6766 _embed: true
6767 })
6768 });
6769 const record = fallback?._embedded?.self;
6770 registry.batch(() => {
6771 dispatch3.receiveNavigationFallbackId(fallback?.id);
6772 if (!record) {
6773 return;
6774 }
6775 const existingFallbackEntityRecord = select4.getEntityRecord(
6776 "postType",
6777 "wp_navigation",
6778 fallback.id
6779 );
6780 const invalidateNavigationQueries = !existingFallbackEntityRecord;
6781 dispatch3.receiveEntityRecords(
6782 "postType",
6783 "wp_navigation",
6784 record,
6785 void 0,
6786 invalidateNavigationQueries
6787 );
6788 dispatch3.finishResolution("getEntityRecord", [
6789 "postType",
6790 "wp_navigation",
6791 fallback.id
6792 ]);
6793 });
6794 };
6795 var getDefaultTemplateId2 = (query) => async ({ dispatch: dispatch3, registry, resolveSelect: resolveSelect2 }) => {
6796 const template = await (0, import_api_fetch9.default)({
6797 path: (0, import_url6.addQueryArgs)("/wp/v2/templates/lookup", query)
6798 });
6799 await resolveSelect2.getEntitiesConfig("postType");
6800 const id = window?.__experimentalTemplateActivate ? template?.wp_id || template?.id : template?.id;
6801 registry.batch(() => {
6802 dispatch3.receiveDefaultTemplateId(query, id || "");
6803 if (id) {
6804 template.id = id;
6805 dispatch3.receiveEntityRecords(
6806 "postType",
6807 template.type,
6808 template
6809 );
6810 dispatch3.finishResolution("getEntityRecord", [
6811 "postType",
6812 template.type,
6813 id
6814 ]);
6815 }
6816 });
6817 };
6818 getDefaultTemplateId2.shouldInvalidate = (action) => {
6819 return action.type === "RECEIVE_ITEMS" && action.kind === "root" && action.name === "site" && !!action.persistedEdits;
6820 };
6821 var getRevisions2 = (kind, name, recordKey, query = {}) => async ({ dispatch: dispatch3, registry, resolveSelect: resolveSelect2 }) => {
6822 const configs = await resolveSelect2.getEntitiesConfig(kind);
6823 const entityConfig = configs.find(
6824 (config) => config.name === name && config.kind === kind
6825 );
6826 if (!entityConfig) {
6827 return;
6828 }
6829 const rawQuery = { ...query };
6830 const lock2 = await dispatch3.__unstableAcquireStoreLock(
6831 STORE_NAME,
6832 ["entities", "records", kind, name, recordKey, "revisions"],
6833 { exclusive: false }
6834 );
6835 try {
6836 if (query._fields) {
6837 query = {
6838 ...query,
6839 _fields: [
6840 .../* @__PURE__ */ new Set([
6841 ...get_normalized_comma_separable_default(query._fields) || [],
6842 entityConfig.revisionKey || DEFAULT_ENTITY_KEY
6843 ])
6844 ].join()
6845 };
6846 }
6847 const path = (0, import_url6.addQueryArgs)(
6848 entityConfig.getRevisionsUrl(recordKey),
6849 query
6850 );
6851 let records, response;
6852 const meta = {};
6853 const isPaginated = entityConfig.supportsPagination && query.per_page !== -1;
6854 try {
6855 response = await (0, import_api_fetch9.default)({ path, parse: !isPaginated });
6856 } catch {
6857 return;
6858 }
6859 if (response) {
6860 if (isPaginated) {
6861 records = Object.values(await response.json());
6862 meta.totalItems = parseInt(
6863 response.headers.get("X-WP-Total")
6864 );
6865 } else {
6866 records = Object.values(response);
6867 }
6868 if (query._fields) {
6869 records = records.map((record) => {
6870 query._fields.split(",").forEach((field) => {
6871 if (!record.hasOwnProperty(field)) {
6872 record[field] = void 0;
6873 }
6874 });
6875 return record;
6876 });
6877 }
6878 registry.batch(() => {
6879 dispatch3.receiveRevisions(
6880 kind,
6881 name,
6882 recordKey,
6883 records,
6884 query,
6885 false,
6886 meta
6887 );
6888 const key = entityConfig.revisionKey || DEFAULT_ENTITY_KEY;
6889 const normalizedQuery = normalizeQueryForResolution(rawQuery);
6890 const resolutionsArgs = records.filter((record) => record[key]).map((record) => [
6891 kind,
6892 name,
6893 recordKey,
6894 record[key],
6895 normalizedQuery
6896 ]);
6897 dispatch3.finishResolutions(
6898 "getRevision",
6899 resolutionsArgs
6900 );
6901 });
6902 }
6903 } finally {
6904 dispatch3.__unstableReleaseStoreLock(lock2);
6905 }
6906 };
6907 getRevisions2.shouldInvalidate = (action, kind, name, recordKey) => action.type === "SAVE_ENTITY_RECORD_FINISH" && name === action.name && kind === action.kind && !action.error && recordKey === action.recordId;
6908 var getRevision2 = (kind, name, recordKey, revisionKey, query) => async ({ select: select4, dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
6909 const configs = await resolveSelect2.getEntitiesConfig(kind);
6910 const entityConfig = configs.find(
6911 (config) => config.name === name && config.kind === kind
6912 );
6913 if (!entityConfig) {
6914 return;
6915 }
6916 if (query !== void 0 && query._fields) {
6917 query = {
6918 ...query,
6919 _fields: [
6920 .../* @__PURE__ */ new Set([
6921 ...get_normalized_comma_separable_default(query._fields) || [],
6922 entityConfig.revisionKey || DEFAULT_ENTITY_KEY
6923 ])
6924 ].join()
6925 };
6926 }
6927 const lock2 = await dispatch3.__unstableAcquireStoreLock(
6928 STORE_NAME,
6929 [
6930 "entities",
6931 "records",
6932 kind,
6933 name,
6934 recordKey,
6935 "revisions",
6936 revisionKey
6937 ],
6938 { exclusive: false }
6939 );
6940 try {
6941 if (select4.hasRevision(kind, name, recordKey, revisionKey, query)) {
6942 return;
6943 }
6944 const path = (0, import_url6.addQueryArgs)(
6945 entityConfig.getRevisionsUrl(recordKey, revisionKey),
6946 query
6947 );
6948 let record;
6949 try {
6950 record = await (0, import_api_fetch9.default)({ path });
6951 } catch {
6952 return;
6953 }
6954 if (record) {
6955 dispatch3.receiveRevisions(
6956 kind,
6957 name,
6958 recordKey,
6959 record,
6960 query
6961 );
6962 }
6963 } finally {
6964 dispatch3.__unstableReleaseStoreLock(lock2);
6965 }
6966 };
6967 var getRegisteredPostMeta2 = (postType) => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
6968 let options;
6969 try {
6970 const {
6971 rest_namespace: restNamespace = "wp/v2",
6972 rest_base: restBase
6973 } = await resolveSelect2.getPostType(postType) || {};
6974 options = await (0, import_api_fetch9.default)({
6975 path: `${restNamespace}/${restBase}/?context=edit`,
6976 method: "OPTIONS"
6977 });
6978 } catch {
6979 return;
6980 }
6981 if (options) {
6982 dispatch3.receiveRegisteredPostMeta(
6983 postType,
6984 options?.schema?.properties?.meta?.properties
6985 );
6986 }
6987 };
6988 var getEntitiesConfig2 = (kind) => async ({ dispatch: dispatch3 }) => {
6989 const loader = additionalEntityConfigLoaders.find(
6990 (l) => l.kind === kind
6991 );
6992 if (!loader) {
6993 return;
6994 }
6995 try {
6996 const configs = await loader.loadEntities();
6997 if (!configs.length) {
6998 return;
6999 }
7000 dispatch3.addEntities(configs);
7001 } catch {
7002 }
7003 };
7004 var getEditorSettings2 = () => async ({ dispatch: dispatch3 }) => {
7005 const settings = await (0, import_api_fetch9.default)({
7006 path: "/wp-block-editor/v1/settings"
7007 });
7008 dispatch3.receiveEditorSettings(settings);
7009 };
7010 var getEditorAssets2 = () => async ({ dispatch: dispatch3 }) => {
7011 const assets = await (0, import_api_fetch9.default)({
7012 path: "/wp-block-editor/v1/assets"
7013 });
7014 dispatch3.receiveEditorAssets(assets);
7015 };
7016 var getViewConfig2 = (kind, name) => async ({ dispatch: dispatch3 }) => {
7017 const config = await (0, import_api_fetch9.default)({
7018 path: (0, import_url6.addQueryArgs)("/wp/v2/view-config", { kind, name })
7019 });
7020 dispatch3.receiveViewConfig(kind, name, config);
7021 };
7022
7023 // packages/core-data/build-module/locks/utils.mjs
7024 function deepCopyLocksTreePath(tree, path) {
7025 const newTree = { ...tree };
7026 let currentNode = newTree;
7027 for (const branchName of path) {
7028 currentNode.children = {
7029 ...currentNode.children,
7030 [branchName]: {
7031 locks: [],
7032 children: {},
7033 ...currentNode.children[branchName]
7034 }
7035 };
7036 currentNode = currentNode.children[branchName];
7037 }
7038 return newTree;
7039 }
7040 function getNode(tree, path) {
7041 let currentNode = tree;
7042 for (const branchName of path) {
7043 const nextNode = currentNode.children[branchName];
7044 if (!nextNode) {
7045 return null;
7046 }
7047 currentNode = nextNode;
7048 }
7049 return currentNode;
7050 }
7051 function* iteratePath(tree, path) {
7052 let currentNode = tree;
7053 yield currentNode;
7054 for (const branchName of path) {
7055 const nextNode = currentNode.children[branchName];
7056 if (!nextNode) {
7057 break;
7058 }
7059 yield nextNode;
7060 currentNode = nextNode;
7061 }
7062 }
7063 function* iterateDescendants(node) {
7064 const stack = Object.values(node.children);
7065 while (stack.length) {
7066 const childNode = stack.pop();
7067 yield childNode;
7068 stack.push(...Object.values(childNode.children));
7069 }
7070 }
7071 function hasConflictingLock({ exclusive }, locks2) {
7072 if (exclusive && locks2.length) {
7073 return true;
7074 }
7075 if (!exclusive && locks2.filter((lock2) => lock2.exclusive).length) {
7076 return true;
7077 }
7078 return false;
7079 }
7080
7081 // packages/core-data/build-module/locks/reducer.mjs
7082 var DEFAULT_STATE = {
7083 requests: [],
7084 tree: {
7085 locks: [],
7086 children: {}
7087 }
7088 };
7089 function locks(state = DEFAULT_STATE, action) {
7090 switch (action.type) {
7091 case "ENQUEUE_LOCK_REQUEST": {
7092 const { request } = action;
7093 return {
7094 ...state,
7095 requests: [request, ...state.requests]
7096 };
7097 }
7098 case "GRANT_LOCK_REQUEST": {
7099 const { lock: lock2, request } = action;
7100 const { store: store2, path } = request;
7101 const storePath = [store2, ...path];
7102 const newTree = deepCopyLocksTreePath(state.tree, storePath);
7103 const node = getNode(newTree, storePath);
7104 node.locks = [...node.locks, lock2];
7105 return {
7106 ...state,
7107 requests: state.requests.filter((r) => r !== request),
7108 tree: newTree
7109 };
7110 }
7111 case "RELEASE_LOCK": {
7112 const { lock: lock2 } = action;
7113 const storePath = [lock2.store, ...lock2.path];
7114 const newTree = deepCopyLocksTreePath(state.tree, storePath);
7115 const node = getNode(newTree, storePath);
7116 node.locks = node.locks.filter((l) => l !== lock2);
7117 return {
7118 ...state,
7119 tree: newTree
7120 };
7121 }
7122 }
7123 return state;
7124 }
7125
7126 // packages/core-data/build-module/locks/selectors.mjs
7127 function getPendingLockRequests(state) {
7128 return state.requests;
7129 }
7130 function isLockAvailable(state, store2, path, { exclusive }) {
7131 const storePath = [store2, ...path];
7132 const locks2 = state.tree;
7133 for (const node2 of iteratePath(locks2, storePath)) {
7134 if (hasConflictingLock({ exclusive }, node2.locks)) {
7135 return false;
7136 }
7137 }
7138 const node = getNode(locks2, storePath);
7139 if (!node) {
7140 return true;
7141 }
7142 for (const descendant of iterateDescendants(node)) {
7143 if (hasConflictingLock({ exclusive }, descendant.locks)) {
7144 return false;
7145 }
7146 }
7147 return true;
7148 }
7149
7150 // packages/core-data/build-module/locks/engine.mjs
7151 function createLocks() {
7152 let state = locks(void 0, { type: "@@INIT" });
7153 function processPendingLockRequests() {
7154 for (const request of getPendingLockRequests(state)) {
7155 const { store: store2, path, exclusive, notifyAcquired } = request;
7156 if (isLockAvailable(state, store2, path, { exclusive })) {
7157 const lock2 = { store: store2, path, exclusive };
7158 state = locks(state, {
7159 type: "GRANT_LOCK_REQUEST",
7160 lock: lock2,
7161 request
7162 });
7163 notifyAcquired(lock2);
7164 }
7165 }
7166 }
7167 function acquire(store2, path, exclusive) {
7168 return new Promise((resolve) => {
7169 state = locks(state, {
7170 type: "ENQUEUE_LOCK_REQUEST",
7171 request: { store: store2, path, exclusive, notifyAcquired: resolve }
7172 });
7173 processPendingLockRequests();
7174 });
7175 }
7176 function release(lock2) {
7177 state = locks(state, {
7178 type: "RELEASE_LOCK",
7179 lock: lock2
7180 });
7181 processPendingLockRequests();
7182 }
7183 return { acquire, release };
7184 }
7185
7186 // packages/core-data/build-module/locks/actions.mjs
7187 function createLocksActions() {
7188 const locks2 = createLocks();
7189 function __unstableAcquireStoreLock(store2, path, { exclusive }) {
7190 return () => locks2.acquire(store2, path, exclusive);
7191 }
7192 function __unstableReleaseStoreLock(lock2) {
7193 return () => locks2.release(lock2);
7194 }
7195 return { __unstableAcquireStoreLock, __unstableReleaseStoreLock };
7196 }
7197
7198 // packages/core-data/build-module/dynamic-entities.mjs
7199 var dynamicActions;
7200 var dynamicSelectors;
7201
7202 // packages/core-data/build-module/entity-provider.mjs
7203 var import_element2 = __toESM(require_element(), 1);
7204
7205 // packages/core-data/build-module/entity-context.mjs
7206 var import_element = __toESM(require_element(), 1);
7207 var EntityContext = (0, import_element.createContext)({});
7208 EntityContext.displayName = "EntityContext";
7209
7210 // packages/core-data/build-module/entity-provider.mjs
7211 var import_jsx_runtime = __toESM(require_jsx_runtime(), 1);
7212 function EntityProvider({
7213 kind,
7214 type: name,
7215 id,
7216 revisionId,
7217 children
7218 }) {
7219 const parent = (0, import_element2.useContext)(EntityContext);
7220 const childContext = (0, import_element2.useMemo)(
7221 () => ({
7222 ...parent,
7223 ...kind && {
7224 [kind]: {
7225 ...parent?.[kind],
7226 [name]: id
7227 }
7228 },
7229 ...revisionId !== void 0 && { revisionId }
7230 }),
7231 [parent, kind, name, id, revisionId]
7232 );
7233 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EntityContext.Provider, { value: childContext, children });
7234 }
7235
7236 // packages/core-data/build-module/hooks/use-entity-record.mjs
7237 var import_data11 = __toESM(require_data(), 1);
7238 var import_deprecated4 = __toESM(require_deprecated(), 1);
7239 var import_element3 = __toESM(require_element(), 1);
7240
7241 // packages/core-data/build-module/hooks/use-query-select.mjs
7242 var import_data10 = __toESM(require_data(), 1);
7243
7244 // node_modules/memize/dist/index.js
7245 function memize(fn, options) {
7246 var size = 0;
7247 var head;
7248 var tail;
7249 options = options || {};
7250 function memoized() {
7251 var node = head, len = arguments.length, args, i;
7252 searchCache: while (node) {
7253 if (node.args.length !== arguments.length) {
7254 node = node.next;
7255 continue;
7256 }
7257 for (i = 0; i < len; i++) {
7258 if (node.args[i] !== arguments[i]) {
7259 node = node.next;
7260 continue searchCache;
7261 }
7262 }
7263 if (node !== head) {
7264 if (node === tail) {
7265 tail = node.prev;
7266 }
7267 node.prev.next = node.next;
7268 if (node.next) {
7269 node.next.prev = node.prev;
7270 }
7271 node.next = head;
7272 node.prev = null;
7273 head.prev = node;
7274 head = node;
7275 }
7276 return node.val;
7277 }
7278 args = new Array(len);
7279 for (i = 0; i < len; i++) {
7280 args[i] = arguments[i];
7281 }
7282 node = {
7283 args,
7284 // Generate the result from original function
7285 val: fn.apply(null, args)
7286 };
7287 if (head) {
7288 head.prev = node;
7289 node.next = head;
7290 } else {
7291 tail = node;
7292 }
7293 if (size === /** @type {MemizeOptions} */
7294 options.maxSize) {
7295 tail = /** @type {MemizeCacheNode} */
7296 tail.prev;
7297 tail.next = null;
7298 } else {
7299 size++;
7300 }
7301 head = node;
7302 return node.val;
7303 }
7304 memoized.clear = function() {
7305 head = null;
7306 tail = null;
7307 size = 0;
7308 };
7309 return memoized;
7310 }
7311
7312 // packages/core-data/build-module/hooks/constants.mjs
7313 var Status = /* @__PURE__ */ ((Status2) => {
7314 Status2["Idle"] = "IDLE";
7315 Status2["Resolving"] = "RESOLVING";
7316 Status2["Error"] = "ERROR";
7317 Status2["Success"] = "SUCCESS";
7318 return Status2;
7319 })(Status || {});
7320
7321 // packages/core-data/build-module/hooks/use-query-select.mjs
7322 var META_SELECTORS = [
7323 "getIsResolving",
7324 "hasStartedResolution",
7325 "hasFinishedResolution",
7326 "isResolving",
7327 "getCachedResolvers"
7328 ];
7329 function useQuerySelect(mapQuerySelect, deps) {
7330 return (0, import_data10.useSelect)((select4, registry) => {
7331 const resolve = (store2) => enrichSelectors(select4(store2));
7332 return mapQuerySelect(resolve, registry);
7333 }, deps);
7334 }
7335 var enrichSelectors = memize(((selectors) => {
7336 const resolvers = {};
7337 for (const selectorName in selectors) {
7338 if (META_SELECTORS.includes(selectorName)) {
7339 continue;
7340 }
7341 Object.defineProperty(resolvers, selectorName, {
7342 get: () => (...args) => {
7343 const data = selectors[selectorName](...args);
7344 const resolutionStatus = selectors.getResolutionState(
7345 selectorName,
7346 args
7347 )?.status;
7348 let status;
7349 switch (resolutionStatus) {
7350 case "resolving":
7351 status = Status.Resolving;
7352 break;
7353 case "finished":
7354 status = Status.Success;
7355 break;
7356 case "error":
7357 status = Status.Error;
7358 break;
7359 case void 0:
7360 status = Status.Idle;
7361 break;
7362 }
7363 return {
7364 data,
7365 status,
7366 isResolving: status === Status.Resolving,
7367 hasStarted: status !== Status.Idle,
7368 hasResolved: status === Status.Success || status === Status.Error
7369 };
7370 }
7371 });
7372 }
7373 return resolvers;
7374 }));
7375
7376 // packages/core-data/build-module/hooks/use-entity-record.mjs
7377 var EMPTY_OBJECT3 = {};
7378 function useEntityRecord(kind, name, recordId, options = { enabled: true }) {
7379 const { editEntityRecord: editEntityRecord2, saveEditedEntityRecord: saveEditedEntityRecord2 } = (0, import_data11.useDispatch)(store);
7380 const mutations = (0, import_element3.useMemo)(
7381 () => ({
7382 edit: (record2, editOptions = {}) => editEntityRecord2(kind, name, recordId, record2, editOptions),
7383 save: (saveOptions = {}) => saveEditedEntityRecord2(kind, name, recordId, {
7384 throwOnError: true,
7385 ...saveOptions
7386 })
7387 }),
7388 [editEntityRecord2, kind, name, recordId, saveEditedEntityRecord2]
7389 );
7390 const { editedRecord, hasEdits, edits } = (0, import_data11.useSelect)(
7391 (select4) => {
7392 if (!options.enabled) {
7393 return {
7394 editedRecord: EMPTY_OBJECT3,
7395 hasEdits: false,
7396 edits: EMPTY_OBJECT3
7397 };
7398 }
7399 return {
7400 editedRecord: select4(store).getEditedEntityRecord(
7401 kind,
7402 name,
7403 recordId
7404 ),
7405 hasEdits: select4(store).hasEditsForEntityRecord(
7406 kind,
7407 name,
7408 recordId
7409 ),
7410 edits: select4(store).getEntityRecordNonTransientEdits(
7411 kind,
7412 name,
7413 recordId
7414 )
7415 };
7416 },
7417 [kind, name, recordId, options.enabled]
7418 );
7419 const { data: record, ...querySelectRest } = useQuerySelect(
7420 (query) => {
7421 if (!options.enabled) {
7422 return {
7423 data: null
7424 };
7425 }
7426 return query(store).getEntityRecord(kind, name, recordId);
7427 },
7428 [kind, name, recordId, options.enabled]
7429 );
7430 return {
7431 record,
7432 editedRecord,
7433 hasEdits,
7434 edits,
7435 ...querySelectRest,
7436 ...mutations
7437 };
7438 }
7439 function useDeprecatedEntityRecord(kind, name, recordId, options) {
7440 (0, import_deprecated4.default)(`wp.data.__experimentalUseEntityRecord`, {
7441 alternative: "wp.data.useEntityRecord",
7442 since: "6.1"
7443 });
7444 return useEntityRecord(kind, name, recordId, options);
7445 }
7446
7447 // packages/core-data/build-module/hooks/use-entity-records.mjs
7448 var import_url7 = __toESM(require_url(), 1);
7449 var import_deprecated5 = __toESM(require_deprecated(), 1);
7450 var import_data12 = __toESM(require_data(), 1);
7451 var import_element4 = __toESM(require_element(), 1);
7452 var EMPTY_ARRAY = [];
7453 function useEntityRecords(kind, name, queryArgs = {}, options = { enabled: true }) {
7454 const queryAsString = (0, import_url7.addQueryArgs)("", queryArgs);
7455 const { data: records, ...rest } = useQuerySelect(
7456 (query) => {
7457 if (!options.enabled) {
7458 return {
7459 // Avoiding returning a new reference on every execution.
7460 data: EMPTY_ARRAY
7461 };
7462 }
7463 return query(store).getEntityRecords(kind, name, queryArgs);
7464 },
7465 [kind, name, queryAsString, options.enabled]
7466 );
7467 const { totalItems, totalPages } = (0, import_data12.useSelect)(
7468 (select4) => {
7469 if (!options.enabled) {
7470 return {
7471 totalItems: null,
7472 totalPages: null
7473 };
7474 }
7475 return {
7476 totalItems: select4(store).getEntityRecordsTotalItems(
7477 kind,
7478 name,
7479 queryArgs
7480 ),
7481 totalPages: select4(store).getEntityRecordsTotalPages(
7482 kind,
7483 name,
7484 queryArgs
7485 )
7486 };
7487 },
7488 [kind, name, queryAsString, options.enabled]
7489 );
7490 return {
7491 records,
7492 totalItems,
7493 totalPages,
7494 ...rest
7495 };
7496 }
7497 function useDeprecatedEntityRecords(kind, name, queryArgs, options) {
7498 (0, import_deprecated5.default)(`wp.data.__experimentalUseEntityRecords`, {
7499 alternative: "wp.data.useEntityRecords",
7500 since: "6.1"
7501 });
7502 return useEntityRecords(kind, name, queryArgs, options);
7503 }
7504 function useEntityRecordsWithPermissions(kind, name, queryArgs = {}, options = { enabled: true }) {
7505 const entityConfig = (0, import_data12.useSelect)(
7506 (select4) => select4(store).getEntityConfig(kind, name),
7507 [kind, name]
7508 );
7509 const { records: data, ...ret } = useEntityRecords(
7510 kind,
7511 name,
7512 {
7513 ...queryArgs,
7514 // If _fields is provided, we need to include _links in the request for permission caching to work.
7515 ...queryArgs._fields ? {
7516 _fields: [
7517 .../* @__PURE__ */ new Set([
7518 ...get_normalized_comma_separable_default(
7519 queryArgs._fields
7520 ) || [],
7521 "_links"
7522 ])
7523 ].join()
7524 } : {}
7525 },
7526 options
7527 );
7528 const ids = (0, import_element4.useMemo)(
7529 () => data?.map(
7530 // @ts-ignore
7531 (record) => record[entityConfig?.key ?? "id"]
7532 ) ?? [],
7533 [data, entityConfig?.key]
7534 );
7535 const permissions = (0, import_data12.useSelect)(
7536 (select4) => {
7537 const { getEntityRecordsPermissions: getEntityRecordsPermissions2 } = unlock(
7538 select4(store)
7539 );
7540 return getEntityRecordsPermissions2(kind, name, ids);
7541 },
7542 [ids, kind, name]
7543 );
7544 const dataWithPermissions = (0, import_element4.useMemo)(
7545 () => data?.map((record, index) => ({
7546 // @ts-ignore
7547 ...record,
7548 permissions: permissions[index]
7549 })) ?? [],
7550 [data, permissions]
7551 );
7552 return { records: dataWithPermissions, ...ret };
7553 }
7554
7555 // packages/core-data/build-module/hooks/use-resource-permissions.mjs
7556 var import_deprecated6 = __toESM(require_deprecated(), 1);
7557 var import_warning = __toESM(require_warning(), 1);
7558 function useResourcePermissions(resource, id) {
7559 const isEntity = typeof resource === "object";
7560 const resourceAsString = isEntity ? JSON.stringify(resource) : resource;
7561 if (isEntity && typeof id !== "undefined") {
7562 (0, import_warning.default)(
7563 `When 'resource' is an entity object, passing 'id' as a separate argument isn't supported.`
7564 );
7565 }
7566 return useQuerySelect(
7567 (resolve) => {
7568 const hasId = isEntity ? !!resource.id : !!id;
7569 const { canUser: canUser3 } = resolve(store);
7570 const collectionResource = isEntity ? { kind: resource.kind, name: resource.name } : resource;
7571 const create3 = canUser3("create", collectionResource);
7572 if (!hasId) {
7573 const read2 = canUser3("read", collectionResource);
7574 const isResolving2 = create3.isResolving || read2.isResolving;
7575 const hasResolved2 = create3.hasResolved && read2.hasResolved;
7576 let status2 = Status.Idle;
7577 if (isResolving2) {
7578 status2 = Status.Resolving;
7579 } else if (hasResolved2) {
7580 status2 = Status.Success;
7581 }
7582 return {
7583 status: status2,
7584 isResolving: isResolving2,
7585 hasResolved: hasResolved2,
7586 canCreate: create3.hasResolved && create3.data,
7587 canRead: read2.hasResolved && read2.data
7588 };
7589 }
7590 const read = canUser3("read", resource, id);
7591 const update = canUser3("update", resource, id);
7592 const _delete = canUser3("delete", resource, id);
7593 const isResolving = read.isResolving || create3.isResolving || update.isResolving || _delete.isResolving;
7594 const hasResolved = read.hasResolved && create3.hasResolved && update.hasResolved && _delete.hasResolved;
7595 let status = Status.Idle;
7596 if (isResolving) {
7597 status = Status.Resolving;
7598 } else if (hasResolved) {
7599 status = Status.Success;
7600 }
7601 return {
7602 status,
7603 isResolving,
7604 hasResolved,
7605 canRead: hasResolved && read.data,
7606 canCreate: hasResolved && create3.data,
7607 canUpdate: hasResolved && update.data,
7608 canDelete: hasResolved && _delete.data
7609 };
7610 },
7611 [resourceAsString, id]
7612 );
7613 }
7614 var use_resource_permissions_default = useResourcePermissions;
7615 function useDeprecatedResourcePermissions(resource, id) {
7616 (0, import_deprecated6.default)(`wp.data.__experimentalUseResourcePermissions`, {
7617 alternative: "wp.data.useResourcePermissions",
7618 since: "6.1"
7619 });
7620 return useResourcePermissions(resource, id);
7621 }
7622
7623 // packages/core-data/build-module/hooks/use-entity-block-editor.mjs
7624 var import_element6 = __toESM(require_element(), 1);
7625 var import_data13 = __toESM(require_data(), 1);
7626 var import_blocks5 = __toESM(require_blocks(), 1);
7627
7628 // packages/core-data/build-module/hooks/use-entity-id.mjs
7629 var import_element5 = __toESM(require_element(), 1);
7630 function useEntityId(kind, name) {
7631 const context = (0, import_element5.useContext)(EntityContext);
7632 return context?.[kind]?.[name];
7633 }
7634
7635 // packages/core-data/build-module/footnotes/index.mjs
7636 var import_rich_text4 = __toESM(require_rich_text(), 1);
7637
7638 // packages/core-data/build-module/footnotes/get-rich-text-values-cached.mjs
7639 var import_block_editor5 = __toESM(require_block_editor(), 1);
7640 var unlockedApis;
7641 var cache = /* @__PURE__ */ new WeakMap();
7642 function getRichTextValuesCached(block) {
7643 if (!unlockedApis) {
7644 unlockedApis = unlock(import_block_editor5.privateApis);
7645 }
7646 if (!cache.has(block)) {
7647 const values = unlockedApis.getRichTextValues([block]);
7648 cache.set(block, values);
7649 }
7650 return cache.get(block);
7651 }
7652
7653 // packages/core-data/build-module/footnotes/get-footnotes-order.mjs
7654 var cache2 = /* @__PURE__ */ new WeakMap();
7655 function getBlockFootnotesOrder(block) {
7656 if (!cache2.has(block)) {
7657 const order = [];
7658 for (const value of getRichTextValuesCached(block)) {
7659 if (!value) {
7660 continue;
7661 }
7662 value.replacements.forEach(({ type, attributes }) => {
7663 if (type === "core/footnote") {
7664 order.push(attributes["data-fn"]);
7665 }
7666 });
7667 }
7668 cache2.set(block, order);
7669 }
7670 return cache2.get(block);
7671 }
7672 function getFootnotesOrder(blocks) {
7673 return blocks.flatMap(getBlockFootnotesOrder);
7674 }
7675
7676 // packages/core-data/build-module/footnotes/index.mjs
7677 var oldFootnotes = {};
7678 function updateFootnotesFromMeta(blocks, meta) {
7679 const output = { blocks };
7680 if (!meta) {
7681 return output;
7682 }
7683 if (meta.footnotes === void 0) {
7684 return output;
7685 }
7686 const newOrder = getFootnotesOrder(blocks);
7687 const footnotes = meta.footnotes ? JSON.parse(meta.footnotes) : [];
7688 const currentOrder = footnotes.map((fn) => fn.id);
7689 if (currentOrder.join("") === newOrder.join("")) {
7690 return output;
7691 }
7692 const newFootnotes = newOrder.map(
7693 (fnId) => footnotes.find((fn) => fn.id === fnId) || oldFootnotes[fnId] || {
7694 id: fnId,
7695 content: ""
7696 }
7697 );
7698 function updateAttributes(attributes) {
7699 if (!attributes || Array.isArray(attributes) || typeof attributes !== "object") {
7700 return attributes;
7701 }
7702 attributes = { ...attributes };
7703 for (const key in attributes) {
7704 const value = attributes[key];
7705 if (Array.isArray(value)) {
7706 attributes[key] = value.map(updateAttributes);
7707 continue;
7708 }
7709 if (typeof value !== "string" && !(value instanceof import_rich_text4.RichTextData)) {
7710 continue;
7711 }
7712 const richTextValue = typeof value === "string" ? import_rich_text4.RichTextData.fromHTMLString(value) : new import_rich_text4.RichTextData(value);
7713 let hasFootnotes = false;
7714 richTextValue.replacements.forEach((replacement) => {
7715 if (replacement.type === "core/footnote") {
7716 const id = replacement.attributes["data-fn"];
7717 const index = newOrder.indexOf(id);
7718 const countValue = (0, import_rich_text4.create)({
7719 html: replacement.innerHTML
7720 });
7721 countValue.text = String(index + 1);
7722 countValue.formats = Array.from(
7723 { length: countValue.text.length },
7724 () => countValue.formats[0]
7725 );
7726 countValue.replacements = Array.from(
7727 { length: countValue.text.length },
7728 () => countValue.replacements[0]
7729 );
7730 replacement.innerHTML = (0, import_rich_text4.toHTMLString)({
7731 value: countValue
7732 });
7733 hasFootnotes = true;
7734 }
7735 });
7736 if (hasFootnotes) {
7737 attributes[key] = typeof value === "string" ? richTextValue.toHTMLString() : richTextValue;
7738 }
7739 }
7740 return attributes;
7741 }
7742 function updateBlocksAttributes(__blocks) {
7743 return __blocks.map((block) => {
7744 return {
7745 ...block,
7746 attributes: updateAttributes(block.attributes),
7747 innerBlocks: updateBlocksAttributes(block.innerBlocks)
7748 };
7749 });
7750 }
7751 const newBlocks = updateBlocksAttributes(blocks);
7752 oldFootnotes = {
7753 ...oldFootnotes,
7754 ...footnotes.reduce((acc, fn) => {
7755 if (!newOrder.includes(fn.id)) {
7756 acc[fn.id] = fn;
7757 }
7758 return acc;
7759 }, {})
7760 };
7761 return {
7762 meta: {
7763 ...meta,
7764 footnotes: JSON.stringify(newFootnotes)
7765 },
7766 blocks: newBlocks
7767 };
7768 }
7769
7770 // packages/core-data/build-module/hooks/use-entity-block-editor.mjs
7771 var EMPTY_ARRAY2 = [];
7772 function useEntityBlockEditor(kind, name, { id: _id } = {}) {
7773 const providerId = useEntityId(kind, name);
7774 const id = _id ?? providerId;
7775 const { content, editedBlocks, meta } = (0, import_data13.useSelect)(
7776 (select4) => {
7777 if (!id) {
7778 return {};
7779 }
7780 const { getEditedEntityRecord: getEditedEntityRecord3 } = select4(STORE_NAME);
7781 const editedRecord = getEditedEntityRecord3(kind, name, id);
7782 return {
7783 editedBlocks: editedRecord.blocks,
7784 content: editedRecord.content,
7785 meta: editedRecord.meta
7786 };
7787 },
7788 [kind, name, id]
7789 );
7790 const { __unstableCreateUndoLevel: __unstableCreateUndoLevel2, editEntityRecord: editEntityRecord2 } = (0, import_data13.useDispatch)(STORE_NAME);
7791 const blocks = (0, import_element6.useMemo)(() => {
7792 if (!id) {
7793 return void 0;
7794 }
7795 if (editedBlocks) {
7796 return editedBlocks;
7797 }
7798 if (!content || typeof content !== "string") {
7799 return EMPTY_ARRAY2;
7800 }
7801 const cacheKey = getCacheKey(kind, name, id);
7802 const cached = parsedBlocksCache.get(cacheKey);
7803 let _blocks;
7804 if (cached && cached.content === content) {
7805 _blocks = cached.blocks;
7806 } else {
7807 _blocks = (0, import_blocks5.parse)(content);
7808 parsedBlocksCache.set(cacheKey, { content, blocks: _blocks });
7809 }
7810 return _blocks;
7811 }, [kind, name, id, editedBlocks, content]);
7812 const onChange = (0, import_element6.useCallback)(
7813 (newBlocks, options) => {
7814 const noChange = blocks === newBlocks;
7815 if (noChange) {
7816 return __unstableCreateUndoLevel2(kind, name, id);
7817 }
7818 const { selection, ...rest } = options;
7819 const edits = {
7820 selection,
7821 content: ({ blocks: blocksForSerialization = [] }) => (0, import_blocks5.__unstableSerializeAndClean)(blocksForSerialization),
7822 ...updateFootnotesFromMeta(newBlocks, meta)
7823 };
7824 editEntityRecord2(kind, name, id, edits, {
7825 isCached: false,
7826 ...rest
7827 });
7828 },
7829 [
7830 kind,
7831 name,
7832 id,
7833 blocks,
7834 meta,
7835 __unstableCreateUndoLevel2,
7836 editEntityRecord2
7837 ]
7838 );
7839 const onInput = (0, import_element6.useCallback)(
7840 (newBlocks, options) => {
7841 const { selection, ...rest } = options;
7842 const edits = {
7843 selection,
7844 ...updateFootnotesFromMeta(newBlocks, meta)
7845 };
7846 editEntityRecord2(kind, name, id, edits, {
7847 isCached: true,
7848 ...rest
7849 });
7850 },
7851 [kind, name, id, meta, editEntityRecord2]
7852 );
7853 return [blocks, onInput, onChange];
7854 }
7855
7856 // packages/core-data/build-module/hooks/use-entity-prop.mjs
7857 var import_element7 = __toESM(require_element(), 1);
7858 var import_data14 = __toESM(require_data(), 1);
7859 function useEntityProp(kind, name, prop, _id) {
7860 const providerId = useEntityId(kind, name);
7861 const id = _id ?? providerId;
7862 const context = (0, import_element7.useContext)(EntityContext);
7863 const revisionId = context?.revisionId;
7864 const { value, fullValue } = (0, import_data14.useSelect)(
7865 (select4) => {
7866 if (revisionId) {
7867 const revisions = select4(STORE_NAME).getRevisions(
7868 kind,
7869 name,
7870 id,
7871 {
7872 per_page: -1,
7873 context: "edit",
7874 _fields: "id,date,author,meta,title.raw,excerpt.raw,content.raw"
7875 }
7876 );
7877 const entityConfig = select4(STORE_NAME).getEntityConfig(
7878 kind,
7879 name
7880 );
7881 const revKey = entityConfig?.revisionKey || DEFAULT_ENTITY_KEY;
7882 const revision = revisions?.find(
7883 (r) => r[revKey] === revisionId
7884 );
7885 return revision ? {
7886 value: revision[prop]?.raw ?? revision[prop],
7887 fullValue: revision[prop]
7888 } : {};
7889 }
7890 const { getEntityRecord: getEntityRecord3, getEditedEntityRecord: getEditedEntityRecord3 } = select4(STORE_NAME);
7891 const record = getEntityRecord3(kind, name, id);
7892 const editedRecord = getEditedEntityRecord3(kind, name, id);
7893 return record && editedRecord ? {
7894 value: editedRecord[prop],
7895 fullValue: record[prop]
7896 } : {};
7897 },
7898 [kind, name, id, prop, revisionId]
7899 );
7900 const { editEntityRecord: editEntityRecord2 } = (0, import_data14.useDispatch)(STORE_NAME);
7901 const setValue = (0, import_element7.useCallback)(
7902 (newValue) => {
7903 if (revisionId) {
7904 return;
7905 }
7906 editEntityRecord2(kind, name, id, {
7907 [prop]: newValue
7908 });
7909 },
7910 [editEntityRecord2, kind, name, id, prop, revisionId]
7911 );
7912 return [value, setValue, fullValue];
7913 }
7914
7915 // packages/core-data/build-module/hooks/use-post-editor-awareness-state.mjs
7916 var import_compose3 = __toESM(require_compose(), 1);
7917 var import_element8 = __toESM(require_element(), 1);
7918 var defaultResolvedSelection = {
7919 richTextOffset: null,
7920 localClientId: null,
7921 attributeKey: null
7922 };
7923 var defaultState = {
7924 activeCollaborators: [],
7925 resolveSelection: () => defaultResolvedSelection,
7926 getDebugData: () => ({
7927 doc: {},
7928 clients: {},
7929 collaboratorMap: {}
7930 }),
7931 isCurrentCollaboratorDisconnected: false
7932 };
7933 function getAwarenessState(awareness, newState) {
7934 const activeCollaborators = newState ?? awareness.getCurrentState();
7935 return {
7936 activeCollaborators,
7937 resolveSelection: (selection, blocks) => awareness.convertSelectionStateToAbsolute(selection, blocks),
7938 getDebugData: () => awareness.getDebugData(),
7939 isCurrentCollaboratorDisconnected: activeCollaborators.find((collaborator) => collaborator.isMe)?.isConnected === false
7940 };
7941 }
7942 function usePostEditorAwarenessState(postId, postType) {
7943 const [state, setState] = (0, import_element8.useState)(defaultState);
7944 (0, import_element8.useEffect)(() => {
7945 if (null === postId || null === postType) {
7946 setState(defaultState);
7947 return;
7948 }
7949 const objectType = `postType/${postType}`;
7950 const objectId = postId.toString();
7951 const awareness = getSyncManager()?.getAwareness(
7952 objectType,
7953 objectId
7954 );
7955 if (!awareness) {
7956 setState(defaultState);
7957 return;
7958 }
7959 awareness.setUp();
7960 setState(getAwarenessState(awareness));
7961 const unsubscribe = awareness?.onStateChange(
7962 (newState) => {
7963 setState(getAwarenessState(awareness, newState));
7964 }
7965 );
7966 return unsubscribe;
7967 }, [postId, postType]);
7968 return state;
7969 }
7970 function useActiveCollaborators(postId, postType) {
7971 return usePostEditorAwarenessState(postId, postType).activeCollaborators;
7972 }
7973 function useResolvedSelection(postId, postType) {
7974 const blocks = usePostContentBlocks();
7975 const awarenessState = usePostEditorAwarenessState(postId, postType);
7976 return (0, import_element8.useCallback)(
7977 (selection) => awarenessState.resolveSelection(selection, blocks),
7978 [blocks, awarenessState]
7979 );
7980 }
7981 function useLastPostSave(postId, postType) {
7982 const [lastSave, setLastSave] = (0, import_element8.useState)(null);
7983 (0, import_element8.useEffect)(() => {
7984 if (null === postId || null === postType) {
7985 setLastSave(null);
7986 return;
7987 }
7988 const awareness = getSyncManager()?.getAwareness(
7989 `postType/${postType}`,
7990 postId.toString()
7991 );
7992 if (!awareness) {
7993 setLastSave(null);
7994 return;
7995 }
7996 awareness.setUp();
7997 const stateMap = awareness.doc.getMap("state");
7998 const recordMap = awareness.doc.getMap("document");
7999 const setupTime = Date.now();
8000 const observer = (event) => {
8001 if (event.keysChanged.has("savedAt")) {
8002 const savedAt = stateMap.get("savedAt");
8003 const savedByClientId = stateMap.get("savedBy");
8004 if (typeof savedAt === "number" && typeof savedByClientId === "number" && savedAt > setupTime) {
8005 const postStatus = recordMap.get("status");
8006 setLastSave({ savedAt, savedByClientId, postStatus });
8007 }
8008 }
8009 };
8010 stateMap.observe(observer);
8011 return () => {
8012 stateMap.unobserve(observer);
8013 };
8014 }, [postId, postType]);
8015 return lastSave;
8016 }
8017 function useOnCollaboratorJoin(postId, postType, callback) {
8018 const { activeCollaborators } = usePostEditorAwarenessState(
8019 postId,
8020 postType
8021 );
8022 const prevCollaborators = (0, import_compose3.usePrevious)(activeCollaborators);
8023 (0, import_element8.useEffect)(() => {
8024 if (!prevCollaborators || prevCollaborators.length === 0) {
8025 return;
8026 }
8027 const prevMap = new Map(
8028 prevCollaborators.map((collaborator) => [
8029 collaborator.clientId,
8030 collaborator
8031 ])
8032 );
8033 const me = activeCollaborators.find(
8034 (collaborator) => collaborator.isMe
8035 );
8036 for (const collaborator of activeCollaborators) {
8037 if (!prevMap.has(collaborator.clientId) && !collaborator.isMe) {
8038 callback(collaborator, me);
8039 }
8040 }
8041 }, [activeCollaborators, prevCollaborators, callback]);
8042 }
8043 function useOnCollaboratorLeave(postId, postType, callback) {
8044 const { activeCollaborators } = usePostEditorAwarenessState(
8045 postId,
8046 postType
8047 );
8048 const prevCollaborators = (0, import_compose3.usePrevious)(activeCollaborators);
8049 (0, import_element8.useEffect)(() => {
8050 if (!prevCollaborators || prevCollaborators.length === 0) {
8051 return;
8052 }
8053 const newMap = new Map(
8054 activeCollaborators.map((collaborator) => [
8055 collaborator.clientId,
8056 collaborator
8057 ])
8058 );
8059 for (const prevCollab of prevCollaborators) {
8060 if (prevCollab.isMe || !prevCollab.isConnected) {
8061 continue;
8062 }
8063 const newCollab = newMap.get(prevCollab.clientId);
8064 if (!newCollab?.isConnected) {
8065 callback(prevCollab);
8066 }
8067 }
8068 }, [activeCollaborators, prevCollaborators, callback]);
8069 }
8070 function useOnPostSave(postId, postType, callback) {
8071 const { activeCollaborators } = usePostEditorAwarenessState(
8072 postId,
8073 postType
8074 );
8075 const lastPostSave = useLastPostSave(postId, postType);
8076 const prevPostSave = (0, import_compose3.usePrevious)(lastPostSave);
8077 (0, import_element8.useEffect)(() => {
8078 if (!lastPostSave) {
8079 return;
8080 }
8081 if (prevPostSave && lastPostSave.savedAt === prevPostSave.savedAt) {
8082 return;
8083 }
8084 const saver = activeCollaborators.find(
8085 (collaborator) => collaborator.clientId === lastPostSave.savedByClientId && !collaborator.isMe
8086 );
8087 if (!saver) {
8088 return;
8089 }
8090 callback(lastPostSave, saver, prevPostSave ?? null);
8091 }, [lastPostSave, prevPostSave, activeCollaborators, callback]);
8092 }
8093
8094 // packages/core-data/build-module/private-apis.mjs
8095 var lockedApis = {
8096 useEntityRecordsWithPermissions,
8097 RECEIVE_INTERMEDIATE_RESULTS,
8098 retrySyncConnection,
8099 useActiveCollaborators,
8100 useResolvedSelection,
8101 useOnCollaboratorJoin,
8102 useOnCollaboratorLeave,
8103 useOnPostSave,
8104 SelectionType,
8105 SelectionDirection
8106 };
8107 var privateApis = {};
8108 lock(privateApis, lockedApis);
8109
8110 // packages/core-data/build-module/index.mjs
8111 var entitiesConfig2 = [
8112 ...rootEntitiesConfig,
8113 ...additionalEntityConfigLoaders.filter((config) => !!config.name)
8114 ];
8115 var entitySelectors = entitiesConfig2.reduce((result, entity2) => {
8116 const { kind, name, plural } = entity2;
8117 const getEntityRecordMethodName = getMethodName(kind, name);
8118 result[getEntityRecordMethodName] = (state, key, query) => {
8119 logEntityDeprecation(kind, name, getEntityRecordMethodName, {
8120 isShorthandSelector: true,
8121 alternativeFunctionName: "getEntityRecord"
8122 });
8123 return getEntityRecord(state, kind, name, key, query);
8124 };
8125 if (plural) {
8126 const getEntityRecordsMethodName = getMethodName(kind, plural, "get");
8127 result[getEntityRecordsMethodName] = (state, query) => {
8128 logEntityDeprecation(kind, name, getEntityRecordsMethodName, {
8129 isShorthandSelector: true,
8130 alternativeFunctionName: "getEntityRecords"
8131 });
8132 return getEntityRecords(state, kind, name, query);
8133 };
8134 }
8135 return result;
8136 }, {});
8137 var entityResolvers = entitiesConfig2.reduce((result, entity2) => {
8138 const { kind, name, plural } = entity2;
8139 const getEntityRecordMethodName = getMethodName(kind, name);
8140 result[getEntityRecordMethodName] = (key, query) => {
8141 logEntityDeprecation(kind, name, getEntityRecordMethodName, {
8142 isShorthandSelector: true,
8143 alternativeFunctionName: "getEntityRecord"
8144 });
8145 return getEntityRecord2(kind, name, key, query);
8146 };
8147 if (plural) {
8148 const getEntityRecordsMethodName = getMethodName(kind, plural, "get");
8149 result[getEntityRecordsMethodName] = (...args) => {
8150 logEntityDeprecation(kind, plural, getEntityRecordsMethodName, {
8151 isShorthandSelector: true,
8152 alternativeFunctionName: "getEntityRecords"
8153 });
8154 return getEntityRecords2(kind, name, ...args);
8155 };
8156 result[getEntityRecordsMethodName].shouldInvalidate = (action) => getEntityRecords2.shouldInvalidate(action, kind, name);
8157 }
8158 return result;
8159 }, {});
8160 var entityActions = entitiesConfig2.reduce((result, entity2) => {
8161 const { kind, name } = entity2;
8162 const saveEntityRecordMethodName = getMethodName(kind, name, "save");
8163 result[saveEntityRecordMethodName] = (record, options) => {
8164 logEntityDeprecation(kind, name, saveEntityRecordMethodName, {
8165 isShorthandSelector: true,
8166 alternativeFunctionName: "saveEntityRecord"
8167 });
8168 return saveEntityRecord(kind, name, record, options);
8169 };
8170 const deleteEntityRecordMethodName = getMethodName(kind, name, "delete");
8171 result[deleteEntityRecordMethodName] = (key, query, options) => {
8172 logEntityDeprecation(kind, name, deleteEntityRecordMethodName, {
8173 isShorthandSelector: true,
8174 alternativeFunctionName: "deleteEntityRecord"
8175 });
8176 return deleteEntityRecord(kind, name, key, query, options);
8177 };
8178 return result;
8179 }, {});
8180 var storeConfig = () => ({
8181 reducer: reducer_default2,
8182 actions: {
8183 ...dynamicActions,
8184 ...actions_exports,
8185 ...entityActions,
8186 ...createLocksActions()
8187 },
8188 selectors: {
8189 ...dynamicSelectors,
8190 ...selectors_exports,
8191 ...entitySelectors
8192 },
8193 resolvers: { ...resolvers_exports, ...entityResolvers }
8194 });
8195 var store = (0, import_data15.createReduxStore)(STORE_NAME, storeConfig());
8196 unlock(store).registerPrivateSelectors(private_selectors_exports);
8197 unlock(store).registerPrivateActions(private_actions_exports);
8198 (0, import_data15.register)(store);
8199 return __toCommonJS(index_exports);
8200 })();
8201 //# sourceMappingURL=index.js.map
8202