PluginProbe
Gutenberg / 23.5.0
Gutenberg v23.5.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.5.0, at build/scripts/core-data/index.js

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