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

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

19,382 lines 677.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 "use strict";
2 var wp;
3 (wp ||= {}).coreData = (() => {
4 var __create = Object.create;
5 var __defProp = Object.defineProperty;
6 var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
7 var __getOwnPropNames = Object.getOwnPropertyNames;
8 var __getProtoOf = Object.getPrototypeOf;
9 var __hasOwnProp = Object.prototype.hasOwnProperty;
10 var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
11 get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
12 }) : x)(function(x) {
13 if (typeof require !== "undefined") return require.apply(this, arguments);
14 throw Error('Dynamic require of "' + x + '" is not supported');
15 });
16 var __commonJS = (cb, mod) => function __require2() {
17 return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
18 };
19 var __export = (target, all2) => {
20 for (var name in all2)
21 __defProp(target, name, { get: all2[name], enumerable: true });
22 };
23 var __copyProps = (to, from2, except, desc) => {
24 if (from2 && typeof from2 === "object" || typeof from2 === "function") {
25 for (let key of __getOwnPropNames(from2))
26 if (!__hasOwnProp.call(to, key) && key !== except)
27 __defProp(to, key, { get: () => from2[key], enumerable: !(desc = __getOwnPropDesc(from2, key)) || desc.enumerable });
28 }
29 return to;
30 };
31 var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
32 // If the importer is in node compatibility mode or this is not an ESM
33 // file that has been converted to a CommonJS file using a Babel-
34 // compatible transform (i.e. "__esModule" has not been set), then set
35 // "default" to the CommonJS "module.exports" for node compatibility.
36 isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
37 mod
38 ));
39 var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
40
41 // package-external:@wordpress/data
42 var require_data = __commonJS({
43 "package-external:@wordpress/data"(exports, module) {
44 module.exports = window.wp.data;
45 }
46 });
47
48 // node_modules/fast-deep-equal/es6/index.js
49 var require_es6 = __commonJS({
50 "node_modules/fast-deep-equal/es6/index.js"(exports, module) {
51 "use strict";
52 module.exports = function equal(a, b) {
53 if (a === b) return true;
54 if (a && b && typeof a == "object" && typeof b == "object") {
55 if (a.constructor !== b.constructor) return false;
56 var length3, i, keys2;
57 if (Array.isArray(a)) {
58 length3 = a.length;
59 if (length3 != b.length) return false;
60 for (i = length3; i-- !== 0; )
61 if (!equal(a[i], b[i])) return false;
62 return true;
63 }
64 if (a instanceof Map && b instanceof Map) {
65 if (a.size !== b.size) return false;
66 for (i of a.entries())
67 if (!b.has(i[0])) return false;
68 for (i of a.entries())
69 if (!equal(i[1], b.get(i[0]))) return false;
70 return true;
71 }
72 if (a instanceof Set && b instanceof Set) {
73 if (a.size !== b.size) return false;
74 for (i of a.entries())
75 if (!b.has(i[0])) return false;
76 return true;
77 }
78 if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) {
79 length3 = a.length;
80 if (length3 != b.length) return false;
81 for (i = length3; i-- !== 0; )
82 if (a[i] !== b[i]) return false;
83 return true;
84 }
85 if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags;
86 if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf();
87 if (a.toString !== Object.prototype.toString) return a.toString() === b.toString();
88 keys2 = Object.keys(a);
89 length3 = keys2.length;
90 if (length3 !== Object.keys(b).length) return false;
91 for (i = length3; i-- !== 0; )
92 if (!Object.prototype.hasOwnProperty.call(b, keys2[i])) return false;
93 for (i = length3; i-- !== 0; ) {
94 var key = keys2[i];
95 if (!equal(a[key], b[key])) return false;
96 }
97 return true;
98 }
99 return a !== a && b !== b;
100 };
101 }
102 });
103
104 // package-external:@wordpress/compose
105 var require_compose = __commonJS({
106 "package-external:@wordpress/compose"(exports, module) {
107 module.exports = window.wp.compose;
108 }
109 });
110
111 // package-external:@wordpress/undo-manager
112 var require_undo_manager = __commonJS({
113 "package-external:@wordpress/undo-manager"(exports, module) {
114 module.exports = window.wp.undoManager;
115 }
116 });
117
118 // node_modules/equivalent-key-map/equivalent-key-map.js
119 var require_equivalent_key_map = __commonJS({
120 "node_modules/equivalent-key-map/equivalent-key-map.js"(exports, module) {
121 "use strict";
122 function _typeof(obj) {
123 if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
124 _typeof = function(obj2) {
125 return typeof obj2;
126 };
127 } else {
128 _typeof = function(obj2) {
129 return obj2 && typeof Symbol === "function" && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2;
130 };
131 }
132 return _typeof(obj);
133 }
134 function _classCallCheck(instance, Constructor) {
135 if (!(instance instanceof Constructor)) {
136 throw new TypeError("Cannot call a class as a function");
137 }
138 }
139 function _defineProperties(target, props) {
140 for (var i = 0; i < props.length; i++) {
141 var descriptor = props[i];
142 descriptor.enumerable = descriptor.enumerable || false;
143 descriptor.configurable = true;
144 if ("value" in descriptor) descriptor.writable = true;
145 Object.defineProperty(target, descriptor.key, descriptor);
146 }
147 }
148 function _createClass(Constructor, protoProps, staticProps) {
149 if (protoProps) _defineProperties(Constructor.prototype, protoProps);
150 if (staticProps) _defineProperties(Constructor, staticProps);
151 return Constructor;
152 }
153 function getValuePair(instance, key) {
154 var _map = instance._map, _arrayTreeMap = instance._arrayTreeMap, _objectTreeMap = instance._objectTreeMap;
155 if (_map.has(key)) {
156 return _map.get(key);
157 }
158 var properties = Object.keys(key).sort();
159 var map2 = Array.isArray(key) ? _arrayTreeMap : _objectTreeMap;
160 for (var i = 0; i < properties.length; i++) {
161 var property = properties[i];
162 map2 = map2.get(property);
163 if (map2 === void 0) {
164 return;
165 }
166 var propertyValue = key[property];
167 map2 = map2.get(propertyValue);
168 if (map2 === void 0) {
169 return;
170 }
171 }
172 var valuePair = map2.get("_ekm_value");
173 if (!valuePair) {
174 return;
175 }
176 _map.delete(valuePair[0]);
177 valuePair[0] = key;
178 map2.set("_ekm_value", valuePair);
179 _map.set(key, valuePair);
180 return valuePair;
181 }
182 var EquivalentKeyMap2 = /* @__PURE__ */ (function() {
183 function EquivalentKeyMap3(iterable) {
184 _classCallCheck(this, EquivalentKeyMap3);
185 this.clear();
186 if (iterable instanceof EquivalentKeyMap3) {
187 var iterablePairs = [];
188 iterable.forEach(function(value, key) {
189 iterablePairs.push([key, value]);
190 });
191 iterable = iterablePairs;
192 }
193 if (iterable != null) {
194 for (var i = 0; i < iterable.length; i++) {
195 this.set(iterable[i][0], iterable[i][1]);
196 }
197 }
198 }
199 _createClass(EquivalentKeyMap3, [{
200 key: "set",
201 /**
202 * Add or update an element with a specified key and value.
203 *
204 * @param {*} key The key of the element to add.
205 * @param {*} value The value of the element to add.
206 *
207 * @return {EquivalentKeyMap} Map instance.
208 */
209 value: function set(key, value) {
210 if (key === null || _typeof(key) !== "object") {
211 this._map.set(key, value);
212 return this;
213 }
214 var properties = Object.keys(key).sort();
215 var valuePair = [key, value];
216 var map2 = Array.isArray(key) ? this._arrayTreeMap : this._objectTreeMap;
217 for (var i = 0; i < properties.length; i++) {
218 var property = properties[i];
219 if (!map2.has(property)) {
220 map2.set(property, new EquivalentKeyMap3());
221 }
222 map2 = map2.get(property);
223 var propertyValue = key[property];
224 if (!map2.has(propertyValue)) {
225 map2.set(propertyValue, new EquivalentKeyMap3());
226 }
227 map2 = map2.get(propertyValue);
228 }
229 var previousValuePair = map2.get("_ekm_value");
230 if (previousValuePair) {
231 this._map.delete(previousValuePair[0]);
232 }
233 map2.set("_ekm_value", valuePair);
234 this._map.set(key, valuePair);
235 return this;
236 }
237 /**
238 * Returns a specified element.
239 *
240 * @param {*} key The key of the element to return.
241 *
242 * @return {?*} The element associated with the specified key or undefined
243 * if the key can't be found.
244 */
245 }, {
246 key: "get",
247 value: function get2(key) {
248 if (key === null || _typeof(key) !== "object") {
249 return this._map.get(key);
250 }
251 var valuePair = getValuePair(this, key);
252 if (valuePair) {
253 return valuePair[1];
254 }
255 }
256 /**
257 * Returns a boolean indicating whether an element with the specified key
258 * exists or not.
259 *
260 * @param {*} key The key of the element to test for presence.
261 *
262 * @return {boolean} Whether an element with the specified key exists.
263 */
264 }, {
265 key: "has",
266 value: function has(key) {
267 if (key === null || _typeof(key) !== "object") {
268 return this._map.has(key);
269 }
270 return getValuePair(this, key) !== void 0;
271 }
272 /**
273 * Removes the specified element.
274 *
275 * @param {*} key The key of the element to remove.
276 *
277 * @return {boolean} Returns true if an element existed and has been
278 * removed, or false if the element does not exist.
279 */
280 }, {
281 key: "delete",
282 value: function _delete(key) {
283 if (!this.has(key)) {
284 return false;
285 }
286 this.set(key, void 0);
287 return true;
288 }
289 /**
290 * Executes a provided function once per each key/value pair, in insertion
291 * order.
292 *
293 * @param {Function} callback Function to execute for each element.
294 * @param {*} thisArg Value to use as `this` when executing
295 * `callback`.
296 */
297 }, {
298 key: "forEach",
299 value: function forEach2(callback) {
300 var _this = this;
301 var thisArg = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : this;
302 this._map.forEach(function(value, key) {
303 if (key !== null && _typeof(key) === "object") {
304 value = value[1];
305 }
306 callback.call(thisArg, value, key, _this);
307 });
308 }
309 /**
310 * Removes all elements.
311 */
312 }, {
313 key: "clear",
314 value: function clear() {
315 this._map = /* @__PURE__ */ new Map();
316 this._arrayTreeMap = /* @__PURE__ */ new Map();
317 this._objectTreeMap = /* @__PURE__ */ new Map();
318 }
319 }, {
320 key: "size",
321 get: function get2() {
322 return this._map.size;
323 }
324 }]);
325 return EquivalentKeyMap3;
326 })();
327 module.exports = EquivalentKeyMap2;
328 }
329 });
330
331 // package-external:@wordpress/url
332 var require_url = __commonJS({
333 "package-external:@wordpress/url"(exports, module) {
334 module.exports = window.wp.url;
335 }
336 });
337
338 // package-external:@wordpress/api-fetch
339 var require_api_fetch = __commonJS({
340 "package-external:@wordpress/api-fetch"(exports, module) {
341 module.exports = window.wp.apiFetch;
342 }
343 });
344
345 // package-external:@wordpress/blocks
346 var require_blocks = __commonJS({
347 "package-external:@wordpress/blocks"(exports, module) {
348 module.exports = window.wp.blocks;
349 }
350 });
351
352 // package-external:@wordpress/i18n
353 var require_i18n = __commonJS({
354 "package-external:@wordpress/i18n"(exports, module) {
355 module.exports = window.wp.i18n;
356 }
357 });
358
359 // package-external:@wordpress/hooks
360 var require_hooks = __commonJS({
361 "package-external:@wordpress/hooks"(exports, module) {
362 module.exports = window.wp.hooks;
363 }
364 });
365
366 // node_modules/simple-peer/simplepeer.min.js
367 var require_simplepeer_min = __commonJS({
368 "node_modules/simple-peer/simplepeer.min.js"(exports, module) {
369 (function(e) {
370 if ("object" == typeof exports && "undefined" != typeof module) module.exports = e();
371 else if ("function" == typeof define && define.amd) define([], e);
372 else {
373 var t;
374 t = "undefined" == typeof window ? "undefined" == typeof global ? "undefined" == typeof self ? this : self : global : window, t.SimplePeer = e();
375 }
376 })(function() {
377 var t = Math.floor, n = Math.abs, r = Math.pow;
378 return (/* @__PURE__ */ (function() {
379 function d(s, e, n2) {
380 function t2(o, i) {
381 if (!e[o]) {
382 if (!s[o]) {
383 var l = "function" == typeof __require && __require;
384 if (!i && l) return l(o, true);
385 if (r2) return r2(o, true);
386 var c = new Error("Cannot find module '" + o + "'");
387 throw c.code = "MODULE_NOT_FOUND", c;
388 }
389 var a2 = e[o] = { exports: {} };
390 s[o][0].call(a2.exports, function(e2) {
391 var r3 = s[o][1][e2];
392 return t2(r3 || e2);
393 }, a2, a2.exports, d, s, e, n2);
394 }
395 return e[o].exports;
396 }
397 for (var r2 = "function" == typeof __require && __require, a = 0; a < n2.length; a++) t2(n2[a]);
398 return t2;
399 }
400 return d;
401 })())({ 1: [function(e, t2, n2) {
402 "use strict";
403 function r2(e2) {
404 var t3 = e2.length;
405 if (0 < t3 % 4) throw new Error("Invalid string. Length must be a multiple of 4");
406 var n3 = e2.indexOf("=");
407 -1 === n3 && (n3 = t3);
408 var r3 = n3 === t3 ? 0 : 4 - n3 % 4;
409 return [n3, r3];
410 }
411 function a(e2, t3, n3) {
412 return 3 * (t3 + n3) / 4 - n3;
413 }
414 function o(e2) {
415 var t3, n3, o2 = r2(e2), d2 = o2[0], s2 = o2[1], l2 = new p(a(e2, d2, s2)), c2 = 0, f2 = 0 < s2 ? d2 - 4 : d2;
416 for (n3 = 0; n3 < f2; n3 += 4) t3 = u[e2.charCodeAt(n3)] << 18 | u[e2.charCodeAt(n3 + 1)] << 12 | u[e2.charCodeAt(n3 + 2)] << 6 | u[e2.charCodeAt(n3 + 3)], l2[c2++] = 255 & t3 >> 16, l2[c2++] = 255 & t3 >> 8, l2[c2++] = 255 & t3;
417 return 2 === s2 && (t3 = u[e2.charCodeAt(n3)] << 2 | u[e2.charCodeAt(n3 + 1)] >> 4, l2[c2++] = 255 & t3), 1 === s2 && (t3 = u[e2.charCodeAt(n3)] << 10 | u[e2.charCodeAt(n3 + 1)] << 4 | u[e2.charCodeAt(n3 + 2)] >> 2, l2[c2++] = 255 & t3 >> 8, l2[c2++] = 255 & t3), l2;
418 }
419 function d(e2) {
420 return c[63 & e2 >> 18] + c[63 & e2 >> 12] + c[63 & e2 >> 6] + c[63 & e2];
421 }
422 function s(e2, t3, n3) {
423 for (var r3, a2 = [], o2 = t3; o2 < n3; o2 += 3) r3 = (16711680 & e2[o2] << 16) + (65280 & e2[o2 + 1] << 8) + (255 & e2[o2 + 2]), a2.push(d(r3));
424 return a2.join("");
425 }
426 function l(e2) {
427 for (var t3, n3 = e2.length, r3 = n3 % 3, a2 = [], o2 = 16383, d2 = 0, l2 = n3 - r3; d2 < l2; d2 += o2) a2.push(s(e2, d2, d2 + o2 > l2 ? l2 : d2 + o2));
428 return 1 === r3 ? (t3 = e2[n3 - 1], a2.push(c[t3 >> 2] + c[63 & t3 << 4] + "==")) : 2 === r3 && (t3 = (e2[n3 - 2] << 8) + e2[n3 - 1], a2.push(c[t3 >> 10] + c[63 & t3 >> 4] + c[63 & t3 << 2] + "=")), a2.join("");
429 }
430 n2.byteLength = function(e2) {
431 var t3 = r2(e2), n3 = t3[0], a2 = t3[1];
432 return 3 * (n3 + a2) / 4 - a2;
433 }, n2.toByteArray = o, n2.fromByteArray = l;
434 for (var c = [], u = [], p = "undefined" == typeof Uint8Array ? Array : Uint8Array, f = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", g = 0, _ = f.length; g < _; ++g) c[g] = f[g], u[f.charCodeAt(g)] = g;
435 u[45] = 62, u[95] = 63;
436 }, {}], 2: [function() {
437 }, {}], 3: [function(e, t2, n2) {
438 (function() {
439 (function() {
440 "use strict";
441 var t3 = String.fromCharCode, o = Math.min;
442 function d(e2) {
443 if (2147483647 < e2) throw new RangeError('The value "' + e2 + '" is invalid for option "size"');
444 var t4 = new Uint8Array(e2);
445 return t4.__proto__ = s.prototype, t4;
446 }
447 function s(e2, t4, n3) {
448 if ("number" == typeof e2) {
449 if ("string" == typeof t4) throw new TypeError('The "string" argument must be of type string. Received type number');
450 return p(e2);
451 }
452 return l(e2, t4, n3);
453 }
454 function l(e2, t4, n3) {
455 if ("string" == typeof e2) return f(e2, t4);
456 if (ArrayBuffer.isView(e2)) return g(e2);
457 if (null == e2) throw TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof e2);
458 if (K(e2, ArrayBuffer) || e2 && K(e2.buffer, ArrayBuffer)) return _(e2, t4, n3);
459 if ("number" == typeof e2) throw new TypeError('The "value" argument must not be of type number. Received type number');
460 var r2 = e2.valueOf && e2.valueOf();
461 if (null != r2 && r2 !== e2) return s.from(r2, t4, n3);
462 var a = h(e2);
463 if (a) return a;
464 if ("undefined" != typeof Symbol && null != Symbol.toPrimitive && "function" == typeof e2[Symbol.toPrimitive]) return s.from(e2[Symbol.toPrimitive]("string"), t4, n3);
465 throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof e2);
466 }
467 function c(e2) {
468 if ("number" != typeof e2) throw new TypeError('"size" argument must be of type number');
469 else if (0 > e2) throw new RangeError('The value "' + e2 + '" is invalid for option "size"');
470 }
471 function u(e2, t4, n3) {
472 return c(e2), 0 >= e2 ? d(e2) : void 0 === t4 ? d(e2) : "string" == typeof n3 ? d(e2).fill(t4, n3) : d(e2).fill(t4);
473 }
474 function p(e2) {
475 return c(e2), d(0 > e2 ? 0 : 0 | m(e2));
476 }
477 function f(e2, t4) {
478 if (("string" != typeof t4 || "" === t4) && (t4 = "utf8"), !s.isEncoding(t4)) throw new TypeError("Unknown encoding: " + t4);
479 var n3 = 0 | b(e2, t4), r2 = d(n3), a = r2.write(e2, t4);
480 return a !== n3 && (r2 = r2.slice(0, a)), r2;
481 }
482 function g(e2) {
483 for (var t4 = 0 > e2.length ? 0 : 0 | m(e2.length), n3 = d(t4), r2 = 0; r2 < t4; r2 += 1) n3[r2] = 255 & e2[r2];
484 return n3;
485 }
486 function _(e2, t4, n3) {
487 if (0 > t4 || e2.byteLength < t4) throw new RangeError('"offset" is outside of buffer bounds');
488 if (e2.byteLength < t4 + (n3 || 0)) throw new RangeError('"length" is outside of buffer bounds');
489 var r2;
490 return r2 = void 0 === t4 && void 0 === n3 ? new Uint8Array(e2) : void 0 === n3 ? new Uint8Array(e2, t4) : new Uint8Array(e2, t4, n3), r2.__proto__ = s.prototype, r2;
491 }
492 function h(e2) {
493 if (s.isBuffer(e2)) {
494 var t4 = 0 | m(e2.length), n3 = d(t4);
495 return 0 === n3.length ? n3 : (e2.copy(n3, 0, 0, t4), n3);
496 }
497 return void 0 === e2.length ? "Buffer" === e2.type && Array.isArray(e2.data) ? g(e2.data) : void 0 : "number" != typeof e2.length || X(e2.length) ? d(0) : g(e2);
498 }
499 function m(e2) {
500 if (e2 >= 2147483647) throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + 2147483647 .toString(16) + " bytes");
501 return 0 | e2;
502 }
503 function b(e2, t4) {
504 if (s.isBuffer(e2)) return e2.length;
505 if (ArrayBuffer.isView(e2) || K(e2, ArrayBuffer)) return e2.byteLength;
506 if ("string" != typeof e2) throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof e2);
507 var n3 = e2.length, r2 = 2 < arguments.length && true === arguments[2];
508 if (!r2 && 0 === n3) return 0;
509 for (var a = false; ; ) switch (t4) {
510 case "ascii":
511 case "latin1":
512 case "binary":
513 return n3;
514 case "utf8":
515 case "utf-8":
516 return H(e2).length;
517 case "ucs2":
518 case "ucs-2":
519 case "utf16le":
520 case "utf-16le":
521 return 2 * n3;
522 case "hex":
523 return n3 >>> 1;
524 case "base64":
525 return z(e2).length;
526 default:
527 if (a) return r2 ? -1 : H(e2).length;
528 t4 = ("" + t4).toLowerCase(), a = true;
529 }
530 }
531 function y(e2, t4, n3) {
532 var r2 = false;
533 if ((void 0 === t4 || 0 > t4) && (t4 = 0), t4 > this.length) return "";
534 if ((void 0 === n3 || n3 > this.length) && (n3 = this.length), 0 >= n3) return "";
535 if (n3 >>>= 0, t4 >>>= 0, n3 <= t4) return "";
536 for (e2 || (e2 = "utf8"); ; ) switch (e2) {
537 case "hex":
538 return P(this, t4, n3);
539 case "utf8":
540 case "utf-8":
541 return x(this, t4, n3);
542 case "ascii":
543 return D(this, t4, n3);
544 case "latin1":
545 case "binary":
546 return I(this, t4, n3);
547 case "base64":
548 return A(this, t4, n3);
549 case "ucs2":
550 case "ucs-2":
551 case "utf16le":
552 case "utf-16le":
553 return M(this, t4, n3);
554 default:
555 if (r2) throw new TypeError("Unknown encoding: " + e2);
556 e2 = (e2 + "").toLowerCase(), r2 = true;
557 }
558 }
559 function C(e2, t4, n3) {
560 var r2 = e2[t4];
561 e2[t4] = e2[n3], e2[n3] = r2;
562 }
563 function R(e2, t4, n3, r2, a) {
564 if (0 === e2.length) return -1;
565 if ("string" == typeof n3 ? (r2 = n3, n3 = 0) : 2147483647 < n3 ? n3 = 2147483647 : -2147483648 > n3 && (n3 = -2147483648), n3 = +n3, X(n3) && (n3 = a ? 0 : e2.length - 1), 0 > n3 && (n3 = e2.length + n3), n3 >= e2.length) {
566 if (a) return -1;
567 n3 = e2.length - 1;
568 } else if (0 > n3) if (a) n3 = 0;
569 else return -1;
570 if ("string" == typeof t4 && (t4 = s.from(t4, r2)), s.isBuffer(t4)) return 0 === t4.length ? -1 : E(e2, t4, n3, r2, a);
571 if ("number" == typeof t4) return t4 &= 255, "function" == typeof Uint8Array.prototype.indexOf ? a ? Uint8Array.prototype.indexOf.call(e2, t4, n3) : Uint8Array.prototype.lastIndexOf.call(e2, t4, n3) : E(e2, [t4], n3, r2, a);
572 throw new TypeError("val must be string, number or Buffer");
573 }
574 function E(e2, t4, n3, r2, a) {
575 function o2(e3, t5) {
576 return 1 === d2 ? e3[t5] : e3.readUInt16BE(t5 * d2);
577 }
578 var d2 = 1, s2 = e2.length, l2 = t4.length;
579 if (void 0 !== r2 && (r2 = (r2 + "").toLowerCase(), "ucs2" === r2 || "ucs-2" === r2 || "utf16le" === r2 || "utf-16le" === r2)) {
580 if (2 > e2.length || 2 > t4.length) return -1;
581 d2 = 2, s2 /= 2, l2 /= 2, n3 /= 2;
582 }
583 var c2;
584 if (a) {
585 var u2 = -1;
586 for (c2 = n3; c2 < s2; c2++) if (o2(e2, c2) !== o2(t4, -1 === u2 ? 0 : c2 - u2)) -1 !== u2 && (c2 -= c2 - u2), u2 = -1;
587 else if (-1 === u2 && (u2 = c2), c2 - u2 + 1 === l2) return u2 * d2;
588 } else for (n3 + l2 > s2 && (n3 = s2 - l2), c2 = n3; 0 <= c2; c2--) {
589 for (var p2 = true, f2 = 0; f2 < l2; f2++) if (o2(e2, c2 + f2) !== o2(t4, f2)) {
590 p2 = false;
591 break;
592 }
593 if (p2) return c2;
594 }
595 return -1;
596 }
597 function w(e2, t4, n3, r2) {
598 n3 = +n3 || 0;
599 var a = e2.length - n3;
600 r2 ? (r2 = +r2, r2 > a && (r2 = a)) : r2 = a;
601 var o2 = t4.length;
602 r2 > o2 / 2 && (r2 = o2 / 2);
603 for (var d2, s2 = 0; s2 < r2; ++s2) {
604 if (d2 = parseInt(t4.substr(2 * s2, 2), 16), X(d2)) return s2;
605 e2[n3 + s2] = d2;
606 }
607 return s2;
608 }
609 function S(e2, t4, n3, r2) {
610 return G(H(t4, e2.length - n3), e2, n3, r2);
611 }
612 function T(e2, t4, n3, r2) {
613 return G(Y(t4), e2, n3, r2);
614 }
615 function v(e2, t4, n3, r2) {
616 return T(e2, t4, n3, r2);
617 }
618 function k(e2, t4, n3, r2) {
619 return G(z(t4), e2, n3, r2);
620 }
621 function L(e2, t4, n3, r2) {
622 return G(V(t4, e2.length - n3), e2, n3, r2);
623 }
624 function A(e2, t4, n3) {
625 return 0 === t4 && n3 === e2.length ? $.fromByteArray(e2) : $.fromByteArray(e2.slice(t4, n3));
626 }
627 function x(e2, t4, n3) {
628 n3 = o(e2.length, n3);
629 for (var r2 = [], a = t4; a < n3; ) {
630 var d2 = e2[a], s2 = null, l2 = 239 < d2 ? 4 : 223 < d2 ? 3 : 191 < d2 ? 2 : 1;
631 if (a + l2 <= n3) {
632 var c2, u2, p2, f2;
633 1 === l2 ? 128 > d2 && (s2 = d2) : 2 === l2 ? (c2 = e2[a + 1], 128 == (192 & c2) && (f2 = (31 & d2) << 6 | 63 & c2, 127 < f2 && (s2 = f2))) : 3 === l2 ? (c2 = e2[a + 1], u2 = e2[a + 2], 128 == (192 & c2) && 128 == (192 & u2) && (f2 = (15 & d2) << 12 | (63 & c2) << 6 | 63 & u2, 2047 < f2 && (55296 > f2 || 57343 < f2) && (s2 = f2))) : 4 === l2 ? (c2 = e2[a + 1], u2 = e2[a + 2], p2 = e2[a + 3], 128 == (192 & c2) && 128 == (192 & u2) && 128 == (192 & p2) && (f2 = (15 & d2) << 18 | (63 & c2) << 12 | (63 & u2) << 6 | 63 & p2, 65535 < f2 && 1114112 > f2 && (s2 = f2))) : void 0;
634 }
635 null === s2 ? (s2 = 65533, l2 = 1) : 65535 < s2 && (s2 -= 65536, r2.push(55296 | 1023 & s2 >>> 10), s2 = 56320 | 1023 & s2), r2.push(s2), a += l2;
636 }
637 return N(r2);
638 }
639 function N(e2) {
640 var n3 = e2.length;
641 if (n3 <= 4096) return t3.apply(String, e2);
642 for (var r2 = "", a = 0; a < n3; ) r2 += t3.apply(String, e2.slice(a, a += 4096));
643 return r2;
644 }
645 function D(e2, n3, r2) {
646 var a = "";
647 r2 = o(e2.length, r2);
648 for (var d2 = n3; d2 < r2; ++d2) a += t3(127 & e2[d2]);
649 return a;
650 }
651 function I(e2, n3, r2) {
652 var a = "";
653 r2 = o(e2.length, r2);
654 for (var d2 = n3; d2 < r2; ++d2) a += t3(e2[d2]);
655 return a;
656 }
657 function P(e2, t4, n3) {
658 var r2 = e2.length;
659 (!t4 || 0 > t4) && (t4 = 0), (!n3 || 0 > n3 || n3 > r2) && (n3 = r2);
660 for (var a = "", o2 = t4; o2 < n3; ++o2) a += W(e2[o2]);
661 return a;
662 }
663 function M(e2, n3, r2) {
664 for (var a = e2.slice(n3, r2), o2 = "", d2 = 0; d2 < a.length; d2 += 2) o2 += t3(a[d2] + 256 * a[d2 + 1]);
665 return o2;
666 }
667 function O(e2, t4, n3) {
668 if (0 != e2 % 1 || 0 > e2) throw new RangeError("offset is not uint");
669 if (e2 + t4 > n3) throw new RangeError("Trying to access beyond buffer length");
670 }
671 function F(e2, t4, n3, r2, a, o2) {
672 if (!s.isBuffer(e2)) throw new TypeError('"buffer" argument must be a Buffer instance');
673 if (t4 > a || t4 < o2) throw new RangeError('"value" argument is out of bounds');
674 if (n3 + r2 > e2.length) throw new RangeError("Index out of range");
675 }
676 function B(e2, t4, n3, r2) {
677 if (n3 + r2 > e2.length) throw new RangeError("Index out of range");
678 if (0 > n3) throw new RangeError("Index out of range");
679 }
680 function U(e2, t4, n3, r2, a) {
681 return t4 = +t4, n3 >>>= 0, a || B(e2, t4, n3, 4, 34028234663852886e22, -34028234663852886e22), J.write(e2, t4, n3, r2, 23, 4), n3 + 4;
682 }
683 function j(e2, t4, n3, r2, a) {
684 return t4 = +t4, n3 >>>= 0, a || B(e2, t4, n3, 8, 17976931348623157e292, -17976931348623157e292), J.write(e2, t4, n3, r2, 52, 8), n3 + 8;
685 }
686 function q(e2) {
687 if (e2 = e2.split("=")[0], e2 = e2.trim().replace(Q, ""), 2 > e2.length) return "";
688 for (; 0 != e2.length % 4; ) e2 += "=";
689 return e2;
690 }
691 function W(e2) {
692 return 16 > e2 ? "0" + e2.toString(16) : e2.toString(16);
693 }
694 function H(e2, t4) {
695 t4 = t4 || 1 / 0;
696 for (var n3, r2 = e2.length, a = null, o2 = [], d2 = 0; d2 < r2; ++d2) {
697 if (n3 = e2.charCodeAt(d2), 55295 < n3 && 57344 > n3) {
698 if (!a) {
699 if (56319 < n3) {
700 -1 < (t4 -= 3) && o2.push(239, 191, 189);
701 continue;
702 } else if (d2 + 1 === r2) {
703 -1 < (t4 -= 3) && o2.push(239, 191, 189);
704 continue;
705 }
706 a = n3;
707 continue;
708 }
709 if (56320 > n3) {
710 -1 < (t4 -= 3) && o2.push(239, 191, 189), a = n3;
711 continue;
712 }
713 n3 = (a - 55296 << 10 | n3 - 56320) + 65536;
714 } else a && -1 < (t4 -= 3) && o2.push(239, 191, 189);
715 if (a = null, 128 > n3) {
716 if (0 > (t4 -= 1)) break;
717 o2.push(n3);
718 } else if (2048 > n3) {
719 if (0 > (t4 -= 2)) break;
720 o2.push(192 | n3 >> 6, 128 | 63 & n3);
721 } else if (65536 > n3) {
722 if (0 > (t4 -= 3)) break;
723 o2.push(224 | n3 >> 12, 128 | 63 & n3 >> 6, 128 | 63 & n3);
724 } else if (1114112 > n3) {
725 if (0 > (t4 -= 4)) break;
726 o2.push(240 | n3 >> 18, 128 | 63 & n3 >> 12, 128 | 63 & n3 >> 6, 128 | 63 & n3);
727 } else throw new Error("Invalid code point");
728 }
729 return o2;
730 }
731 function Y(e2) {
732 for (var t4 = [], n3 = 0; n3 < e2.length; ++n3) t4.push(255 & e2.charCodeAt(n3));
733 return t4;
734 }
735 function V(e2, t4) {
736 for (var n3, r2, a, o2 = [], d2 = 0; d2 < e2.length && !(0 > (t4 -= 2)); ++d2) n3 = e2.charCodeAt(d2), r2 = n3 >> 8, a = n3 % 256, o2.push(a), o2.push(r2);
737 return o2;
738 }
739 function z(e2) {
740 return $.toByteArray(q(e2));
741 }
742 function G(e2, t4, n3, r2) {
743 for (var a = 0; a < r2 && !(a + n3 >= t4.length || a >= e2.length); ++a) t4[a + n3] = e2[a];
744 return a;
745 }
746 function K(e2, t4) {
747 return e2 instanceof t4 || null != e2 && null != e2.constructor && null != e2.constructor.name && e2.constructor.name === t4.name;
748 }
749 function X(e2) {
750 return e2 !== e2;
751 }
752 var $ = e("base64-js"), J = e("ieee754");
753 n2.Buffer = s, n2.SlowBuffer = function(e2) {
754 return +e2 != e2 && (e2 = 0), s.alloc(+e2);
755 }, n2.INSPECT_MAX_BYTES = 50;
756 n2.kMaxLength = 2147483647, s.TYPED_ARRAY_SUPPORT = (function() {
757 try {
758 var e2 = new Uint8Array(1);
759 return e2.__proto__ = { __proto__: Uint8Array.prototype, foo: function() {
760 return 42;
761 } }, 42 === e2.foo();
762 } catch (t4) {
763 return false;
764 }
765 })(), s.TYPED_ARRAY_SUPPORT || "undefined" == typeof console || "function" != typeof console.error || console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."), Object.defineProperty(s.prototype, "parent", { enumerable: true, get: function() {
766 return s.isBuffer(this) ? this.buffer : void 0;
767 } }), Object.defineProperty(s.prototype, "offset", { enumerable: true, get: function() {
768 return s.isBuffer(this) ? this.byteOffset : void 0;
769 } }), "undefined" != typeof Symbol && null != Symbol.species && s[Symbol.species] === s && Object.defineProperty(s, Symbol.species, { value: null, configurable: true, enumerable: false, writable: false }), s.poolSize = 8192, s.from = function(e2, t4, n3) {
770 return l(e2, t4, n3);
771 }, s.prototype.__proto__ = Uint8Array.prototype, s.__proto__ = Uint8Array, s.alloc = function(e2, t4, n3) {
772 return u(e2, t4, n3);
773 }, s.allocUnsafe = function(e2) {
774 return p(e2);
775 }, s.allocUnsafeSlow = function(e2) {
776 return p(e2);
777 }, s.isBuffer = function(e2) {
778 return null != e2 && true === e2._isBuffer && e2 !== s.prototype;
779 }, s.compare = function(e2, t4) {
780 if (K(e2, Uint8Array) && (e2 = s.from(e2, e2.offset, e2.byteLength)), K(t4, Uint8Array) && (t4 = s.from(t4, t4.offset, t4.byteLength)), !s.isBuffer(e2) || !s.isBuffer(t4)) throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');
781 if (e2 === t4) return 0;
782 for (var n3 = e2.length, r2 = t4.length, d2 = 0, l2 = o(n3, r2); d2 < l2; ++d2) if (e2[d2] !== t4[d2]) {
783 n3 = e2[d2], r2 = t4[d2];
784 break;
785 }
786 return n3 < r2 ? -1 : r2 < n3 ? 1 : 0;
787 }, s.isEncoding = function(e2) {
788 switch ((e2 + "").toLowerCase()) {
789 case "hex":
790 case "utf8":
791 case "utf-8":
792 case "ascii":
793 case "latin1":
794 case "binary":
795 case "base64":
796 case "ucs2":
797 case "ucs-2":
798 case "utf16le":
799 case "utf-16le":
800 return true;
801 default:
802 return false;
803 }
804 }, s.concat = function(e2, t4) {
805 if (!Array.isArray(e2)) throw new TypeError('"list" argument must be an Array of Buffers');
806 if (0 === e2.length) return s.alloc(0);
807 var n3;
808 if (t4 === void 0) for (t4 = 0, n3 = 0; n3 < e2.length; ++n3) t4 += e2[n3].length;
809 var r2 = s.allocUnsafe(t4), a = 0;
810 for (n3 = 0; n3 < e2.length; ++n3) {
811 var o2 = e2[n3];
812 if (K(o2, Uint8Array) && (o2 = s.from(o2)), !s.isBuffer(o2)) throw new TypeError('"list" argument must be an Array of Buffers');
813 o2.copy(r2, a), a += o2.length;
814 }
815 return r2;
816 }, s.byteLength = b, s.prototype._isBuffer = true, s.prototype.swap16 = function() {
817 var e2 = this.length;
818 if (0 != e2 % 2) throw new RangeError("Buffer size must be a multiple of 16-bits");
819 for (var t4 = 0; t4 < e2; t4 += 2) C(this, t4, t4 + 1);
820 return this;
821 }, s.prototype.swap32 = function() {
822 var e2 = this.length;
823 if (0 != e2 % 4) throw new RangeError("Buffer size must be a multiple of 32-bits");
824 for (var t4 = 0; t4 < e2; t4 += 4) C(this, t4, t4 + 3), C(this, t4 + 1, t4 + 2);
825 return this;
826 }, s.prototype.swap64 = function() {
827 var e2 = this.length;
828 if (0 != e2 % 8) throw new RangeError("Buffer size must be a multiple of 64-bits");
829 for (var t4 = 0; t4 < e2; t4 += 8) C(this, t4, t4 + 7), C(this, t4 + 1, t4 + 6), C(this, t4 + 2, t4 + 5), C(this, t4 + 3, t4 + 4);
830 return this;
831 }, s.prototype.toString = function() {
832 var e2 = this.length;
833 return 0 === e2 ? "" : 0 === arguments.length ? x(this, 0, e2) : y.apply(this, arguments);
834 }, s.prototype.toLocaleString = s.prototype.toString, s.prototype.equals = function(e2) {
835 if (!s.isBuffer(e2)) throw new TypeError("Argument must be a Buffer");
836 return this === e2 || 0 === s.compare(this, e2);
837 }, s.prototype.inspect = function() {
838 var e2 = "", t4 = n2.INSPECT_MAX_BYTES;
839 return e2 = this.toString("hex", 0, t4).replace(/(.{2})/g, "$1 ").trim(), this.length > t4 && (e2 += " ... "), "<Buffer " + e2 + ">";
840 }, s.prototype.compare = function(e2, t4, n3, r2, a) {
841 if (K(e2, Uint8Array) && (e2 = s.from(e2, e2.offset, e2.byteLength)), !s.isBuffer(e2)) throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof e2);
842 if (void 0 === t4 && (t4 = 0), void 0 === n3 && (n3 = e2 ? e2.length : 0), void 0 === r2 && (r2 = 0), void 0 === a && (a = this.length), 0 > t4 || n3 > e2.length || 0 > r2 || a > this.length) throw new RangeError("out of range index");
843 if (r2 >= a && t4 >= n3) return 0;
844 if (r2 >= a) return -1;
845 if (t4 >= n3) return 1;
846 if (t4 >>>= 0, n3 >>>= 0, r2 >>>= 0, a >>>= 0, this === e2) return 0;
847 for (var d2 = a - r2, l2 = n3 - t4, c2 = o(d2, l2), u2 = this.slice(r2, a), p2 = e2.slice(t4, n3), f2 = 0; f2 < c2; ++f2) if (u2[f2] !== p2[f2]) {
848 d2 = u2[f2], l2 = p2[f2];
849 break;
850 }
851 return d2 < l2 ? -1 : l2 < d2 ? 1 : 0;
852 }, s.prototype.includes = function(e2, t4, n3) {
853 return -1 !== this.indexOf(e2, t4, n3);
854 }, s.prototype.indexOf = function(e2, t4, n3) {
855 return R(this, e2, t4, n3, true);
856 }, s.prototype.lastIndexOf = function(e2, t4, n3) {
857 return R(this, e2, t4, n3, false);
858 }, s.prototype.write = function(e2, t4, n3, r2) {
859 if (void 0 === t4) r2 = "utf8", n3 = this.length, t4 = 0;
860 else if (void 0 === n3 && "string" == typeof t4) r2 = t4, n3 = this.length, t4 = 0;
861 else if (isFinite(t4)) t4 >>>= 0, isFinite(n3) ? (n3 >>>= 0, void 0 === r2 && (r2 = "utf8")) : (r2 = n3, n3 = void 0);
862 else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");
863 var a = this.length - t4;
864 if ((void 0 === n3 || n3 > a) && (n3 = a), 0 < e2.length && (0 > n3 || 0 > t4) || t4 > this.length) throw new RangeError("Attempt to write outside buffer bounds");
865 r2 || (r2 = "utf8");
866 for (var o2 = false; ; ) switch (r2) {
867 case "hex":
868 return w(this, e2, t4, n3);
869 case "utf8":
870 case "utf-8":
871 return S(this, e2, t4, n3);
872 case "ascii":
873 return T(this, e2, t4, n3);
874 case "latin1":
875 case "binary":
876 return v(this, e2, t4, n3);
877 case "base64":
878 return k(this, e2, t4, n3);
879 case "ucs2":
880 case "ucs-2":
881 case "utf16le":
882 case "utf-16le":
883 return L(this, e2, t4, n3);
884 default:
885 if (o2) throw new TypeError("Unknown encoding: " + r2);
886 r2 = ("" + r2).toLowerCase(), o2 = true;
887 }
888 }, s.prototype.toJSON = function() {
889 return { type: "Buffer", data: Array.prototype.slice.call(this._arr || this, 0) };
890 };
891 s.prototype.slice = function(e2, t4) {
892 var n3 = this.length;
893 e2 = ~~e2, t4 = t4 === void 0 ? n3 : ~~t4, 0 > e2 ? (e2 += n3, 0 > e2 && (e2 = 0)) : e2 > n3 && (e2 = n3), 0 > t4 ? (t4 += n3, 0 > t4 && (t4 = 0)) : t4 > n3 && (t4 = n3), t4 < e2 && (t4 = e2);
894 var r2 = this.subarray(e2, t4);
895 return r2.__proto__ = s.prototype, r2;
896 }, s.prototype.readUIntLE = function(e2, t4, n3) {
897 e2 >>>= 0, t4 >>>= 0, n3 || O(e2, t4, this.length);
898 for (var r2 = this[e2], a = 1, o2 = 0; ++o2 < t4 && (a *= 256); ) r2 += this[e2 + o2] * a;
899 return r2;
900 }, s.prototype.readUIntBE = function(e2, t4, n3) {
901 e2 >>>= 0, t4 >>>= 0, n3 || O(e2, t4, this.length);
902 for (var r2 = this[e2 + --t4], a = 1; 0 < t4 && (a *= 256); ) r2 += this[e2 + --t4] * a;
903 return r2;
904 }, s.prototype.readUInt8 = function(e2, t4) {
905 return e2 >>>= 0, t4 || O(e2, 1, this.length), this[e2];
906 }, s.prototype.readUInt16LE = function(e2, t4) {
907 return e2 >>>= 0, t4 || O(e2, 2, this.length), this[e2] | this[e2 + 1] << 8;
908 }, s.prototype.readUInt16BE = function(e2, t4) {
909 return e2 >>>= 0, t4 || O(e2, 2, this.length), this[e2] << 8 | this[e2 + 1];
910 }, s.prototype.readUInt32LE = function(e2, t4) {
911 return e2 >>>= 0, t4 || O(e2, 4, this.length), (this[e2] | this[e2 + 1] << 8 | this[e2 + 2] << 16) + 16777216 * this[e2 + 3];
912 }, s.prototype.readUInt32BE = function(e2, t4) {
913 return e2 >>>= 0, t4 || O(e2, 4, this.length), 16777216 * this[e2] + (this[e2 + 1] << 16 | this[e2 + 2] << 8 | this[e2 + 3]);
914 }, s.prototype.readIntLE = function(e2, t4, n3) {
915 e2 >>>= 0, t4 >>>= 0, n3 || O(e2, t4, this.length);
916 for (var a = this[e2], o2 = 1, d2 = 0; ++d2 < t4 && (o2 *= 256); ) a += this[e2 + d2] * o2;
917 return o2 *= 128, a >= o2 && (a -= r(2, 8 * t4)), a;
918 }, s.prototype.readIntBE = function(e2, t4, n3) {
919 e2 >>>= 0, t4 >>>= 0, n3 || O(e2, t4, this.length);
920 for (var a = t4, o2 = 1, d2 = this[e2 + --a]; 0 < a && (o2 *= 256); ) d2 += this[e2 + --a] * o2;
921 return o2 *= 128, d2 >= o2 && (d2 -= r(2, 8 * t4)), d2;
922 }, s.prototype.readInt8 = function(e2, t4) {
923 return e2 >>>= 0, t4 || O(e2, 1, this.length), 128 & this[e2] ? -1 * (255 - this[e2] + 1) : this[e2];
924 }, s.prototype.readInt16LE = function(e2, t4) {
925 e2 >>>= 0, t4 || O(e2, 2, this.length);
926 var n3 = this[e2] | this[e2 + 1] << 8;
927 return 32768 & n3 ? 4294901760 | n3 : n3;
928 }, s.prototype.readInt16BE = function(e2, t4) {
929 e2 >>>= 0, t4 || O(e2, 2, this.length);
930 var n3 = this[e2 + 1] | this[e2] << 8;
931 return 32768 & n3 ? 4294901760 | n3 : n3;
932 }, s.prototype.readInt32LE = function(e2, t4) {
933 return e2 >>>= 0, t4 || O(e2, 4, this.length), this[e2] | this[e2 + 1] << 8 | this[e2 + 2] << 16 | this[e2 + 3] << 24;
934 }, s.prototype.readInt32BE = function(e2, t4) {
935 return e2 >>>= 0, t4 || O(e2, 4, this.length), this[e2] << 24 | this[e2 + 1] << 16 | this[e2 + 2] << 8 | this[e2 + 3];
936 }, s.prototype.readFloatLE = function(e2, t4) {
937 return e2 >>>= 0, t4 || O(e2, 4, this.length), J.read(this, e2, true, 23, 4);
938 }, s.prototype.readFloatBE = function(e2, t4) {
939 return e2 >>>= 0, t4 || O(e2, 4, this.length), J.read(this, e2, false, 23, 4);
940 }, s.prototype.readDoubleLE = function(e2, t4) {
941 return e2 >>>= 0, t4 || O(e2, 8, this.length), J.read(this, e2, true, 52, 8);
942 }, s.prototype.readDoubleBE = function(e2, t4) {
943 return e2 >>>= 0, t4 || O(e2, 8, this.length), J.read(this, e2, false, 52, 8);
944 }, s.prototype.writeUIntLE = function(e2, t4, n3, a) {
945 if (e2 = +e2, t4 >>>= 0, n3 >>>= 0, !a) {
946 var o2 = r(2, 8 * n3) - 1;
947 F(this, e2, t4, n3, o2, 0);
948 }
949 var d2 = 1, s2 = 0;
950 for (this[t4] = 255 & e2; ++s2 < n3 && (d2 *= 256); ) this[t4 + s2] = 255 & e2 / d2;
951 return t4 + n3;
952 }, s.prototype.writeUIntBE = function(e2, t4, n3, a) {
953 if (e2 = +e2, t4 >>>= 0, n3 >>>= 0, !a) {
954 var o2 = r(2, 8 * n3) - 1;
955 F(this, e2, t4, n3, o2, 0);
956 }
957 var d2 = n3 - 1, s2 = 1;
958 for (this[t4 + d2] = 255 & e2; 0 <= --d2 && (s2 *= 256); ) this[t4 + d2] = 255 & e2 / s2;
959 return t4 + n3;
960 }, s.prototype.writeUInt8 = function(e2, t4, n3) {
961 return e2 = +e2, t4 >>>= 0, n3 || F(this, e2, t4, 1, 255, 0), this[t4] = 255 & e2, t4 + 1;
962 }, s.prototype.writeUInt16LE = function(e2, t4, n3) {
963 return e2 = +e2, t4 >>>= 0, n3 || F(this, e2, t4, 2, 65535, 0), this[t4] = 255 & e2, this[t4 + 1] = e2 >>> 8, t4 + 2;
964 }, s.prototype.writeUInt16BE = function(e2, t4, n3) {
965 return e2 = +e2, t4 >>>= 0, n3 || F(this, e2, t4, 2, 65535, 0), this[t4] = e2 >>> 8, this[t4 + 1] = 255 & e2, t4 + 2;
966 }, s.prototype.writeUInt32LE = function(e2, t4, n3) {
967 return e2 = +e2, t4 >>>= 0, n3 || F(this, e2, t4, 4, 4294967295, 0), this[t4 + 3] = e2 >>> 24, this[t4 + 2] = e2 >>> 16, this[t4 + 1] = e2 >>> 8, this[t4] = 255 & e2, t4 + 4;
968 }, s.prototype.writeUInt32BE = function(e2, t4, n3) {
969 return e2 = +e2, t4 >>>= 0, n3 || F(this, e2, t4, 4, 4294967295, 0), this[t4] = e2 >>> 24, this[t4 + 1] = e2 >>> 16, this[t4 + 2] = e2 >>> 8, this[t4 + 3] = 255 & e2, t4 + 4;
970 }, s.prototype.writeIntLE = function(e2, t4, n3, a) {
971 if (e2 = +e2, t4 >>>= 0, !a) {
972 var o2 = r(2, 8 * n3 - 1);
973 F(this, e2, t4, n3, o2 - 1, -o2);
974 }
975 var d2 = 0, s2 = 1, l2 = 0;
976 for (this[t4] = 255 & e2; ++d2 < n3 && (s2 *= 256); ) 0 > e2 && 0 === l2 && 0 !== this[t4 + d2 - 1] && (l2 = 1), this[t4 + d2] = 255 & (e2 / s2 >> 0) - l2;
977 return t4 + n3;
978 }, s.prototype.writeIntBE = function(e2, t4, n3, a) {
979 if (e2 = +e2, t4 >>>= 0, !a) {
980 var o2 = r(2, 8 * n3 - 1);
981 F(this, e2, t4, n3, o2 - 1, -o2);
982 }
983 var d2 = n3 - 1, s2 = 1, l2 = 0;
984 for (this[t4 + d2] = 255 & e2; 0 <= --d2 && (s2 *= 256); ) 0 > e2 && 0 === l2 && 0 !== this[t4 + d2 + 1] && (l2 = 1), this[t4 + d2] = 255 & (e2 / s2 >> 0) - l2;
985 return t4 + n3;
986 }, s.prototype.writeInt8 = function(e2, t4, n3) {
987 return e2 = +e2, t4 >>>= 0, n3 || F(this, e2, t4, 1, 127, -128), 0 > e2 && (e2 = 255 + e2 + 1), this[t4] = 255 & e2, t4 + 1;
988 }, s.prototype.writeInt16LE = function(e2, t4, n3) {
989 return e2 = +e2, t4 >>>= 0, n3 || F(this, e2, t4, 2, 32767, -32768), this[t4] = 255 & e2, this[t4 + 1] = e2 >>> 8, t4 + 2;
990 }, s.prototype.writeInt16BE = function(e2, t4, n3) {
991 return e2 = +e2, t4 >>>= 0, n3 || F(this, e2, t4, 2, 32767, -32768), this[t4] = e2 >>> 8, this[t4 + 1] = 255 & e2, t4 + 2;
992 }, s.prototype.writeInt32LE = function(e2, t4, n3) {
993 return e2 = +e2, t4 >>>= 0, n3 || F(this, e2, t4, 4, 2147483647, -2147483648), this[t4] = 255 & e2, this[t4 + 1] = e2 >>> 8, this[t4 + 2] = e2 >>> 16, this[t4 + 3] = e2 >>> 24, t4 + 4;
994 }, s.prototype.writeInt32BE = function(e2, t4, n3) {
995 return e2 = +e2, t4 >>>= 0, n3 || F(this, e2, t4, 4, 2147483647, -2147483648), 0 > e2 && (e2 = 4294967295 + e2 + 1), this[t4] = e2 >>> 24, this[t4 + 1] = e2 >>> 16, this[t4 + 2] = e2 >>> 8, this[t4 + 3] = 255 & e2, t4 + 4;
996 }, s.prototype.writeFloatLE = function(e2, t4, n3) {
997 return U(this, e2, t4, true, n3);
998 }, s.prototype.writeFloatBE = function(e2, t4, n3) {
999 return U(this, e2, t4, false, n3);
1000 }, s.prototype.writeDoubleLE = function(e2, t4, n3) {
1001 return j(this, e2, t4, true, n3);
1002 }, s.prototype.writeDoubleBE = function(e2, t4, n3) {
1003 return j(this, e2, t4, false, n3);
1004 }, s.prototype.copy = function(e2, t4, n3, r2) {
1005 if (!s.isBuffer(e2)) throw new TypeError("argument should be a Buffer");
1006 if (n3 || (n3 = 0), r2 || 0 === r2 || (r2 = this.length), t4 >= e2.length && (t4 = e2.length), t4 || (t4 = 0), 0 < r2 && r2 < n3 && (r2 = n3), r2 === n3) return 0;
1007 if (0 === e2.length || 0 === this.length) return 0;
1008 if (0 > t4) throw new RangeError("targetStart out of bounds");
1009 if (0 > n3 || n3 >= this.length) throw new RangeError("Index out of range");
1010 if (0 > r2) throw new RangeError("sourceEnd out of bounds");
1011 r2 > this.length && (r2 = this.length), e2.length - t4 < r2 - n3 && (r2 = e2.length - t4 + n3);
1012 var a = r2 - n3;
1013 if (this === e2 && "function" == typeof Uint8Array.prototype.copyWithin) this.copyWithin(t4, n3, r2);
1014 else if (this === e2 && n3 < t4 && t4 < r2) for (var o2 = a - 1; 0 <= o2; --o2) e2[o2 + t4] = this[o2 + n3];
1015 else Uint8Array.prototype.set.call(e2, this.subarray(n3, r2), t4);
1016 return a;
1017 }, s.prototype.fill = function(e2, t4, n3, r2) {
1018 if ("string" == typeof e2) {
1019 if ("string" == typeof t4 ? (r2 = t4, t4 = 0, n3 = this.length) : "string" == typeof n3 && (r2 = n3, n3 = this.length), void 0 !== r2 && "string" != typeof r2) throw new TypeError("encoding must be a string");
1020 if ("string" == typeof r2 && !s.isEncoding(r2)) throw new TypeError("Unknown encoding: " + r2);
1021 if (1 === e2.length) {
1022 var a = e2.charCodeAt(0);
1023 ("utf8" === r2 && 128 > a || "latin1" === r2) && (e2 = a);
1024 }
1025 } else "number" == typeof e2 && (e2 &= 255);
1026 if (0 > t4 || this.length < t4 || this.length < n3) throw new RangeError("Out of range index");
1027 if (n3 <= t4) return this;
1028 t4 >>>= 0, n3 = n3 === void 0 ? this.length : n3 >>> 0, e2 || (e2 = 0);
1029 var o2;
1030 if ("number" == typeof e2) for (o2 = t4; o2 < n3; ++o2) this[o2] = e2;
1031 else {
1032 var d2 = s.isBuffer(e2) ? e2 : s.from(e2, r2), l2 = d2.length;
1033 if (0 === l2) throw new TypeError('The value "' + e2 + '" is invalid for argument "value"');
1034 for (o2 = 0; o2 < n3 - t4; ++o2) this[o2 + t4] = d2[o2 % l2];
1035 }
1036 return this;
1037 };
1038 var Q = /[^+/0-9A-Za-z-_]/g;
1039 }).call(this);
1040 }).call(this, e("buffer").Buffer);
1041 }, { "base64-js": 1, buffer: 3, ieee754: 9 }], 4: [function(e, t2, n2) {
1042 (function(a) {
1043 (function() {
1044 function r2() {
1045 let e2;
1046 try {
1047 e2 = n2.storage.getItem("debug");
1048 } catch (e3) {
1049 }
1050 return !e2 && "undefined" != typeof a && "env" in a && (e2 = a.env.DEBUG), e2;
1051 }
1052 n2.formatArgs = function(e2) {
1053 if (e2[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + e2[0] + (this.useColors ? "%c " : " ") + "+" + t2.exports.humanize(this.diff), !this.useColors) return;
1054 const n3 = "color: " + this.color;
1055 e2.splice(1, 0, n3, "color: inherit");
1056 let r3 = 0, a2 = 0;
1057 e2[0].replace(/%[a-zA-Z%]/g, (e3) => {
1058 "%%" === e3 || (r3++, "%c" === e3 && (a2 = r3));
1059 }), e2.splice(a2, 0, n3);
1060 }, n2.save = function(e2) {
1061 try {
1062 e2 ? n2.storage.setItem("debug", e2) : n2.storage.removeItem("debug");
1063 } catch (e3) {
1064 }
1065 }, n2.load = r2, n2.useColors = function() {
1066 return !!("undefined" != typeof window && window.process && ("renderer" === window.process.type || window.process.__nwjs)) || !("undefined" != typeof navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) && ("undefined" != typeof document && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || "undefined" != typeof window && window.console && (window.console.firebug || window.console.exception && window.console.table) || "undefined" != typeof navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && 31 <= parseInt(RegExp.$1, 10) || "undefined" != typeof navigator && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
1067 }, n2.storage = (function() {
1068 try {
1069 return localStorage;
1070 } catch (e2) {
1071 }
1072 })(), n2.destroy = /* @__PURE__ */ (() => {
1073 let e2 = false;
1074 return () => {
1075 e2 || (e2 = true, console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."));
1076 };
1077 })(), n2.colors = ["#0000CC", "#0000FF", "#0033CC", "#0033FF", "#0066CC", "#0066FF", "#0099CC", "#0099FF", "#00CC00", "#00CC33", "#00CC66", "#00CC99", "#00CCCC", "#00CCFF", "#3300CC", "#3300FF", "#3333CC", "#3333FF", "#3366CC", "#3366FF", "#3399CC", "#3399FF", "#33CC00", "#33CC33", "#33CC66", "#33CC99", "#33CCCC", "#33CCFF", "#6600CC", "#6600FF", "#6633CC", "#6633FF", "#66CC00", "#66CC33", "#9900CC", "#9900FF", "#9933CC", "#9933FF", "#99CC00", "#99CC33", "#CC0000", "#CC0033", "#CC0066", "#CC0099", "#CC00CC", "#CC00FF", "#CC3300", "#CC3333", "#CC3366", "#CC3399", "#CC33CC", "#CC33FF", "#CC6600", "#CC6633", "#CC9900", "#CC9933", "#CCCC00", "#CCCC33", "#FF0000", "#FF0033", "#FF0066", "#FF0099", "#FF00CC", "#FF00FF", "#FF3300", "#FF3333", "#FF3366", "#FF3399", "#FF33CC", "#FF33FF", "#FF6600", "#FF6633", "#FF9900", "#FF9933", "#FFCC00", "#FFCC33"], n2.log = console.debug || console.log || (() => {
1078 }), t2.exports = e("./common")(n2);
1079 const { formatters: o } = t2.exports;
1080 o.j = function(e2) {
1081 try {
1082 return JSON.stringify(e2);
1083 } catch (e3) {
1084 return "[UnexpectedJSONParseError]: " + e3.message;
1085 }
1086 };
1087 }).call(this);
1088 }).call(this, e("_process"));
1089 }, { "./common": 5, _process: 12 }], 5: [function(e, t2) {
1090 t2.exports = function(t3) {
1091 function r2(e2) {
1092 function t4(...e3) {
1093 if (!t4.enabled) return;
1094 const a2 = t4, o3 = +/* @__PURE__ */ new Date(), i = o3 - (n2 || o3);
1095 a2.diff = i, a2.prev = n2, a2.curr = o3, n2 = o3, e3[0] = r2.coerce(e3[0]), "string" != typeof e3[0] && e3.unshift("%O");
1096 let d = 0;
1097 e3[0] = e3[0].replace(/%([a-zA-Z%])/g, (t5, n3) => {
1098 if ("%%" === t5) return "%";
1099 d++;
1100 const o4 = r2.formatters[n3];
1101 if ("function" == typeof o4) {
1102 const n4 = e3[d];
1103 t5 = o4.call(a2, n4), e3.splice(d, 1), d--;
1104 }
1105 return t5;
1106 }), r2.formatArgs.call(a2, e3);
1107 const s = a2.log || r2.log;
1108 s.apply(a2, e3);
1109 }
1110 let n2, o2 = null;
1111 return t4.namespace = e2, t4.useColors = r2.useColors(), t4.color = r2.selectColor(e2), t4.extend = a, t4.destroy = r2.destroy, Object.defineProperty(t4, "enabled", { enumerable: true, configurable: false, get: () => null === o2 ? r2.enabled(e2) : o2, set: (e3) => {
1112 o2 = e3;
1113 } }), "function" == typeof r2.init && r2.init(t4), t4;
1114 }
1115 function a(e2, t4) {
1116 const n2 = r2(this.namespace + ("undefined" == typeof t4 ? ":" : t4) + e2);
1117 return n2.log = this.log, n2;
1118 }
1119 function o(e2) {
1120 return e2.toString().substring(2, e2.toString().length - 2).replace(/\.\*\?$/, "*");
1121 }
1122 return r2.debug = r2, r2.default = r2, r2.coerce = function(e2) {
1123 return e2 instanceof Error ? e2.stack || e2.message : e2;
1124 }, r2.disable = function() {
1125 const e2 = [...r2.names.map(o), ...r2.skips.map(o).map((e3) => "-" + e3)].join(",");
1126 return r2.enable(""), e2;
1127 }, r2.enable = function(e2) {
1128 r2.save(e2), r2.names = [], r2.skips = [];
1129 let t4;
1130 const n2 = ("string" == typeof e2 ? e2 : "").split(/[\s,]+/), a2 = n2.length;
1131 for (t4 = 0; t4 < a2; t4++) n2[t4] && (e2 = n2[t4].replace(/\*/g, ".*?"), "-" === e2[0] ? r2.skips.push(new RegExp("^" + e2.substr(1) + "$")) : r2.names.push(new RegExp("^" + e2 + "$")));
1132 }, r2.enabled = function(e2) {
1133 if ("*" === e2[e2.length - 1]) return true;
1134 let t4, n2;
1135 for (t4 = 0, n2 = r2.skips.length; t4 < n2; t4++) if (r2.skips[t4].test(e2)) return false;
1136 for (t4 = 0, n2 = r2.names.length; t4 < n2; t4++) if (r2.names[t4].test(e2)) return true;
1137 return false;
1138 }, r2.humanize = e("ms"), r2.destroy = function() {
1139 console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");
1140 }, Object.keys(t3).forEach((e2) => {
1141 r2[e2] = t3[e2];
1142 }), r2.names = [], r2.skips = [], r2.formatters = {}, r2.selectColor = function(e2) {
1143 let t4 = 0;
1144 for (let n2 = 0; n2 < e2.length; n2++) t4 = (t4 << 5) - t4 + e2.charCodeAt(n2), t4 |= 0;
1145 return r2.colors[n(t4) % r2.colors.length];
1146 }, r2.enable(r2.load()), r2;
1147 };
1148 }, { ms: 11 }], 6: [function(e, t2) {
1149 "use strict";
1150 function n2(e2, t3) {
1151 for (const n3 in t3) Object.defineProperty(e2, n3, { value: t3[n3], enumerable: true, configurable: true });
1152 return e2;
1153 }
1154 t2.exports = function(e2, t3, r2) {
1155 if (!e2 || "string" == typeof e2) throw new TypeError("Please pass an Error to err-code");
1156 r2 || (r2 = {}), "object" == typeof t3 && (r2 = t3, t3 = ""), t3 && (r2.code = t3);
1157 try {
1158 return n2(e2, r2);
1159 } catch (t4) {
1160 r2.message = e2.message, r2.stack = e2.stack;
1161 const a = function() {
1162 };
1163 a.prototype = Object.create(Object.getPrototypeOf(e2));
1164 const o = n2(new a(), r2);
1165 return o;
1166 }
1167 };
1168 }, {}], 7: [function(e, t2) {
1169 "use strict";
1170 function n2(e2) {
1171 console && console.warn && console.warn(e2);
1172 }
1173 function r2() {
1174 r2.init.call(this);
1175 }
1176 function a(e2) {
1177 if ("function" != typeof e2) throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof e2);
1178 }
1179 function o(e2) {
1180 return void 0 === e2._maxListeners ? r2.defaultMaxListeners : e2._maxListeners;
1181 }
1182 function i(e2, t3, r3, i2) {
1183 var d2, s2, l2;
1184 if (a(r3), s2 = e2._events, void 0 === s2 ? (s2 = e2._events = /* @__PURE__ */ Object.create(null), e2._eventsCount = 0) : (void 0 !== s2.newListener && (e2.emit("newListener", t3, r3.listener ? r3.listener : r3), s2 = e2._events), l2 = s2[t3]), void 0 === l2) l2 = s2[t3] = r3, ++e2._eventsCount;
1185 else if ("function" == typeof l2 ? l2 = s2[t3] = i2 ? [r3, l2] : [l2, r3] : i2 ? l2.unshift(r3) : l2.push(r3), d2 = o(e2), 0 < d2 && l2.length > d2 && !l2.warned) {
1186 l2.warned = true;
1187 var c2 = new Error("Possible EventEmitter memory leak detected. " + l2.length + " " + (t3 + " listeners added. Use emitter.setMaxListeners() to increase limit"));
1188 c2.name = "MaxListenersExceededWarning", c2.emitter = e2, c2.type = t3, c2.count = l2.length, n2(c2);
1189 }
1190 return e2;
1191 }
1192 function d() {
1193 if (!this.fired) return this.target.removeListener(this.type, this.wrapFn), this.fired = true, 0 === arguments.length ? this.listener.call(this.target) : this.listener.apply(this.target, arguments);
1194 }
1195 function s(e2, t3, n3) {
1196 var r3 = { fired: false, wrapFn: void 0, target: e2, type: t3, listener: n3 }, a2 = d.bind(r3);
1197 return a2.listener = n3, r3.wrapFn = a2, a2;
1198 }
1199 function l(e2, t3, n3) {
1200 var r3 = e2._events;
1201 if (r3 === void 0) return [];
1202 var a2 = r3[t3];
1203 return void 0 === a2 ? [] : "function" == typeof a2 ? n3 ? [a2.listener || a2] : [a2] : n3 ? f(a2) : u(a2, a2.length);
1204 }
1205 function c(e2) {
1206 var t3 = this._events;
1207 if (t3 !== void 0) {
1208 var n3 = t3[e2];
1209 if ("function" == typeof n3) return 1;
1210 if (void 0 !== n3) return n3.length;
1211 }
1212 return 0;
1213 }
1214 function u(e2, t3) {
1215 for (var n3 = Array(t3), r3 = 0; r3 < t3; ++r3) n3[r3] = e2[r3];
1216 return n3;
1217 }
1218 function p(e2, t3) {
1219 for (; t3 + 1 < e2.length; t3++) e2[t3] = e2[t3 + 1];
1220 e2.pop();
1221 }
1222 function f(e2) {
1223 for (var t3 = Array(e2.length), n3 = 0; n3 < t3.length; ++n3) t3[n3] = e2[n3].listener || e2[n3];
1224 return t3;
1225 }
1226 function g(e2, t3, n3) {
1227 "function" == typeof e2.on && _(e2, "error", t3, n3);
1228 }
1229 function _(e2, t3, n3, r3) {
1230 if ("function" == typeof e2.on) r3.once ? e2.once(t3, n3) : e2.on(t3, n3);
1231 else if ("function" == typeof e2.addEventListener) e2.addEventListener(t3, function a2(o2) {
1232 r3.once && e2.removeEventListener(t3, a2), n3(o2);
1233 });
1234 else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof e2);
1235 }
1236 var h, m = "object" == typeof Reflect ? Reflect : null, b = m && "function" == typeof m.apply ? m.apply : function(e2, t3, n3) {
1237 return Function.prototype.apply.call(e2, t3, n3);
1238 };
1239 h = m && "function" == typeof m.ownKeys ? m.ownKeys : Object.getOwnPropertySymbols ? function(e2) {
1240 return Object.getOwnPropertyNames(e2).concat(Object.getOwnPropertySymbols(e2));
1241 } : function(e2) {
1242 return Object.getOwnPropertyNames(e2);
1243 };
1244 var y = Number.isNaN || function(e2) {
1245 return e2 !== e2;
1246 };
1247 t2.exports = r2, t2.exports.once = function(e2, t3) {
1248 return new Promise(function(n3, r3) {
1249 function a2(n4) {
1250 e2.removeListener(t3, o2), r3(n4);
1251 }
1252 function o2() {
1253 "function" == typeof e2.removeListener && e2.removeListener("error", a2), n3([].slice.call(arguments));
1254 }
1255 _(e2, t3, o2, { once: true }), "error" !== t3 && g(e2, a2, { once: true });
1256 });
1257 }, r2.EventEmitter = r2, r2.prototype._events = void 0, r2.prototype._eventsCount = 0, r2.prototype._maxListeners = void 0;
1258 var C = 10;
1259 Object.defineProperty(r2, "defaultMaxListeners", { enumerable: true, get: function() {
1260 return C;
1261 }, set: function(e2) {
1262 if ("number" != typeof e2 || 0 > e2 || y(e2)) throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + e2 + ".");
1263 C = e2;
1264 } }), r2.init = function() {
1265 (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) && (this._events = /* @__PURE__ */ Object.create(null), this._eventsCount = 0), this._maxListeners = this._maxListeners || void 0;
1266 }, r2.prototype.setMaxListeners = function(e2) {
1267 if ("number" != typeof e2 || 0 > e2 || y(e2)) throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + e2 + ".");
1268 return this._maxListeners = e2, this;
1269 }, r2.prototype.getMaxListeners = function() {
1270 return o(this);
1271 }, r2.prototype.emit = function(e2) {
1272 for (var t3 = [], n3 = 1; n3 < arguments.length; n3++) t3.push(arguments[n3]);
1273 var r3 = "error" === e2, a2 = this._events;
1274 if (a2 !== void 0) r3 = r3 && a2.error === void 0;
1275 else if (!r3) return false;
1276 if (r3) {
1277 var o2;
1278 if (0 < t3.length && (o2 = t3[0]), o2 instanceof Error) throw o2;
1279 var d2 = new Error("Unhandled error." + (o2 ? " (" + o2.message + ")" : ""));
1280 throw d2.context = o2, d2;
1281 }
1282 var s2 = a2[e2];
1283 if (s2 === void 0) return false;
1284 if ("function" == typeof s2) b(s2, this, t3);
1285 else for (var l2 = s2.length, c2 = u(s2, l2), n3 = 0; n3 < l2; ++n3) b(c2[n3], this, t3);
1286 return true;
1287 }, r2.prototype.addListener = function(e2, t3) {
1288 return i(this, e2, t3, false);
1289 }, r2.prototype.on = r2.prototype.addListener, r2.prototype.prependListener = function(e2, t3) {
1290 return i(this, e2, t3, true);
1291 }, r2.prototype.once = function(e2, t3) {
1292 return a(t3), this.on(e2, s(this, e2, t3)), this;
1293 }, r2.prototype.prependOnceListener = function(e2, t3) {
1294 return a(t3), this.prependListener(e2, s(this, e2, t3)), this;
1295 }, r2.prototype.removeListener = function(e2, t3) {
1296 var n3, r3, o2, d2, s2;
1297 if (a(t3), r3 = this._events, void 0 === r3) return this;
1298 if (n3 = r3[e2], void 0 === n3) return this;
1299 if (n3 === t3 || n3.listener === t3) 0 == --this._eventsCount ? this._events = /* @__PURE__ */ Object.create(null) : (delete r3[e2], r3.removeListener && this.emit("removeListener", e2, n3.listener || t3));
1300 else if ("function" != typeof n3) {
1301 for (o2 = -1, d2 = n3.length - 1; 0 <= d2; d2--) if (n3[d2] === t3 || n3[d2].listener === t3) {
1302 s2 = n3[d2].listener, o2 = d2;
1303 break;
1304 }
1305 if (0 > o2) return this;
1306 0 === o2 ? n3.shift() : p(n3, o2), 1 === n3.length && (r3[e2] = n3[0]), void 0 !== r3.removeListener && this.emit("removeListener", e2, s2 || t3);
1307 }
1308 return this;
1309 }, r2.prototype.off = r2.prototype.removeListener, r2.prototype.removeAllListeners = function(e2) {
1310 var t3, n3, r3;
1311 if (n3 = this._events, void 0 === n3) return this;
1312 if (void 0 === n3.removeListener) return 0 === arguments.length ? (this._events = /* @__PURE__ */ Object.create(null), this._eventsCount = 0) : void 0 !== n3[e2] && (0 == --this._eventsCount ? this._events = /* @__PURE__ */ Object.create(null) : delete n3[e2]), this;
1313 if (0 === arguments.length) {
1314 var a2, o2 = Object.keys(n3);
1315 for (r3 = 0; r3 < o2.length; ++r3) a2 = o2[r3], "removeListener" !== a2 && this.removeAllListeners(a2);
1316 return this.removeAllListeners("removeListener"), this._events = /* @__PURE__ */ Object.create(null), this._eventsCount = 0, this;
1317 }
1318 if (t3 = n3[e2], "function" == typeof t3) this.removeListener(e2, t3);
1319 else if (void 0 !== t3) for (r3 = t3.length - 1; 0 <= r3; r3--) this.removeListener(e2, t3[r3]);
1320 return this;
1321 }, r2.prototype.listeners = function(e2) {
1322 return l(this, e2, true);
1323 }, r2.prototype.rawListeners = function(e2) {
1324 return l(this, e2, false);
1325 }, r2.listenerCount = function(e2, t3) {
1326 return "function" == typeof e2.listenerCount ? e2.listenerCount(t3) : c.call(e2, t3);
1327 }, r2.prototype.listenerCount = c, r2.prototype.eventNames = function() {
1328 return 0 < this._eventsCount ? h(this._events) : [];
1329 };
1330 }, {}], 8: [function(e, t2) {
1331 t2.exports = function() {
1332 if ("undefined" == typeof globalThis) return null;
1333 var e2 = { RTCPeerConnection: globalThis.RTCPeerConnection || globalThis.mozRTCPeerConnection || globalThis.webkitRTCPeerConnection, RTCSessionDescription: globalThis.RTCSessionDescription || globalThis.mozRTCSessionDescription || globalThis.webkitRTCSessionDescription, RTCIceCandidate: globalThis.RTCIceCandidate || globalThis.mozRTCIceCandidate || globalThis.webkitRTCIceCandidate };
1334 return e2.RTCPeerConnection ? e2 : null;
1335 };
1336 }, {}], 9: [function(e, a, o) {
1337 o.read = function(t2, n2, a2, o2, l) {
1338 var c, u, p = 8 * l - o2 - 1, f = (1 << p) - 1, g = f >> 1, _ = -7, h = a2 ? l - 1 : 0, b = a2 ? -1 : 1, d = t2[n2 + h];
1339 for (h += b, c = d & (1 << -_) - 1, d >>= -_, _ += p; 0 < _; c = 256 * c + t2[n2 + h], h += b, _ -= 8) ;
1340 for (u = c & (1 << -_) - 1, c >>= -_, _ += o2; 0 < _; u = 256 * u + t2[n2 + h], h += b, _ -= 8) ;
1341 if (0 === c) c = 1 - g;
1342 else {
1343 if (c === f) return u ? NaN : (d ? -1 : 1) * (1 / 0);
1344 u += r(2, o2), c -= g;
1345 }
1346 return (d ? -1 : 1) * u * r(2, c - o2);
1347 }, o.write = function(a2, o2, l, u, p, f) {
1348 var h, b, y, g = Math.LN2, _ = Math.log, C = 8 * f - p - 1, R = (1 << C) - 1, E = R >> 1, w = 23 === p ? r(2, -24) - r(2, -77) : 0, S = u ? 0 : f - 1, T = u ? 1 : -1, d = 0 > o2 || 0 === o2 && 0 > 1 / o2 ? 1 : 0;
1349 for (o2 = n(o2), isNaN(o2) || o2 === 1 / 0 ? (b = isNaN(o2) ? 1 : 0, h = R) : (h = t(_(o2) / g), 1 > o2 * (y = r(2, -h)) && (h--, y *= 2), o2 += 1 <= h + E ? w / y : w * r(2, 1 - E), 2 <= o2 * y && (h++, y /= 2), h + E >= R ? (b = 0, h = R) : 1 <= h + E ? (b = (o2 * y - 1) * r(2, p), h += E) : (b = o2 * r(2, E - 1) * r(2, p), h = 0)); 8 <= p; a2[l + S] = 255 & b, S += T, b /= 256, p -= 8) ;
1350 for (h = h << p | b, C += p; 0 < C; a2[l + S] = 255 & h, S += T, h /= 256, C -= 8) ;
1351 a2[l + S - T] |= 128 * d;
1352 };
1353 }, {}], 10: [function(e, t2) {
1354 t2.exports = "function" == typeof Object.create ? function(e2, t3) {
1355 t3 && (e2.super_ = t3, e2.prototype = Object.create(t3.prototype, { constructor: { value: e2, enumerable: false, writable: true, configurable: true } }));
1356 } : function(e2, t3) {
1357 if (t3) {
1358 e2.super_ = t3;
1359 var n2 = function() {
1360 };
1361 n2.prototype = t3.prototype, e2.prototype = new n2(), e2.prototype.constructor = e2;
1362 }
1363 };
1364 }, {}], 11: [function(e, t2) {
1365 var r2 = Math.round;
1366 function a(e2) {
1367 if (e2 += "", !(100 < e2.length)) {
1368 var t3 = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e2);
1369 if (t3) {
1370 var r3 = parseFloat(t3[1]), n2 = (t3[2] || "ms").toLowerCase();
1371 return "years" === n2 || "year" === n2 || "yrs" === n2 || "yr" === n2 || "y" === n2 ? 315576e5 * r3 : "weeks" === n2 || "week" === n2 || "w" === n2 ? 6048e5 * r3 : "days" === n2 || "day" === n2 || "d" === n2 ? 864e5 * r3 : "hours" === n2 || "hour" === n2 || "hrs" === n2 || "hr" === n2 || "h" === n2 ? 36e5 * r3 : "minutes" === n2 || "minute" === n2 || "mins" === n2 || "min" === n2 || "m" === n2 ? 6e4 * r3 : "seconds" === n2 || "second" === n2 || "secs" === n2 || "sec" === n2 || "s" === n2 ? 1e3 * r3 : "milliseconds" === n2 || "millisecond" === n2 || "msecs" === n2 || "msec" === n2 || "ms" === n2 ? r3 : void 0;
1372 }
1373 }
1374 }
1375 function o(e2) {
1376 var t3 = n(e2);
1377 return 864e5 <= t3 ? r2(e2 / 864e5) + "d" : 36e5 <= t3 ? r2(e2 / 36e5) + "h" : 6e4 <= t3 ? r2(e2 / 6e4) + "m" : 1e3 <= t3 ? r2(e2 / 1e3) + "s" : e2 + "ms";
1378 }
1379 function i(e2) {
1380 var t3 = n(e2);
1381 return 864e5 <= t3 ? s(e2, t3, 864e5, "day") : 36e5 <= t3 ? s(e2, t3, 36e5, "hour") : 6e4 <= t3 ? s(e2, t3, 6e4, "minute") : 1e3 <= t3 ? s(e2, t3, 1e3, "second") : e2 + " ms";
1382 }
1383 function s(e2, t3, a2, n2) {
1384 return r2(e2 / a2) + " " + n2 + (t3 >= 1.5 * a2 ? "s" : "");
1385 }
1386 var l = 24 * (60 * 6e4);
1387 t2.exports = function(e2, t3) {
1388 t3 = t3 || {};
1389 var n2 = typeof e2;
1390 if ("string" == n2 && 0 < e2.length) return a(e2);
1391 if ("number" === n2 && isFinite(e2)) return t3.long ? i(e2) : o(e2);
1392 throw new Error("val is not a non-empty string or a valid number. val=" + JSON.stringify(e2));
1393 };
1394 }, {}], 12: [function(e, t2) {
1395 function n2() {
1396 throw new Error("setTimeout has not been defined");
1397 }
1398 function r2() {
1399 throw new Error("clearTimeout has not been defined");
1400 }
1401 function a(t3) {
1402 if (c === setTimeout) return setTimeout(t3, 0);
1403 if ((c === n2 || !c) && setTimeout) return c = setTimeout, setTimeout(t3, 0);
1404 try {
1405 return c(t3, 0);
1406 } catch (n3) {
1407 try {
1408 return c.call(null, t3, 0);
1409 } catch (n4) {
1410 return c.call(this, t3, 0);
1411 }
1412 }
1413 }
1414 function o(t3) {
1415 if (u === clearTimeout) return clearTimeout(t3);
1416 if ((u === r2 || !u) && clearTimeout) return u = clearTimeout, clearTimeout(t3);
1417 try {
1418 return u(t3);
1419 } catch (n3) {
1420 try {
1421 return u.call(null, t3);
1422 } catch (n4) {
1423 return u.call(this, t3);
1424 }
1425 }
1426 }
1427 function i() {
1428 _ && f && (_ = false, f.length ? g = f.concat(g) : h = -1, g.length && d());
1429 }
1430 function d() {
1431 if (!_) {
1432 var e2 = a(i);
1433 _ = true;
1434 for (var t3 = g.length; t3; ) {
1435 for (f = g, g = []; ++h < t3; ) f && f[h].run();
1436 h = -1, t3 = g.length;
1437 }
1438 f = null, _ = false, o(e2);
1439 }
1440 }
1441 function s(e2, t3) {
1442 this.fun = e2, this.array = t3;
1443 }
1444 function l() {
1445 }
1446 var c, u, p = t2.exports = {};
1447 (function() {
1448 try {
1449 c = "function" == typeof setTimeout ? setTimeout : n2;
1450 } catch (t3) {
1451 c = n2;
1452 }
1453 try {
1454 u = "function" == typeof clearTimeout ? clearTimeout : r2;
1455 } catch (t3) {
1456 u = r2;
1457 }
1458 })();
1459 var f, g = [], _ = false, h = -1;
1460 p.nextTick = function(e2) {
1461 var t3 = Array(arguments.length - 1);
1462 if (1 < arguments.length) for (var n3 = 1; n3 < arguments.length; n3++) t3[n3 - 1] = arguments[n3];
1463 g.push(new s(e2, t3)), 1 !== g.length || _ || a(d);
1464 }, s.prototype.run = function() {
1465 this.fun.apply(null, this.array);
1466 }, p.title = "browser", p.browser = true, p.env = {}, p.argv = [], p.version = "", p.versions = {}, p.on = l, p.addListener = l, p.once = l, p.off = l, p.removeListener = l, p.removeAllListeners = l, p.emit = l, p.prependListener = l, p.prependOnceListener = l, p.listeners = function() {
1467 return [];
1468 }, p.binding = function() {
1469 throw new Error("process.binding is not supported");
1470 }, p.cwd = function() {
1471 return "/";
1472 }, p.chdir = function() {
1473 throw new Error("process.chdir is not supported");
1474 }, p.umask = function() {
1475 return 0;
1476 };
1477 }, {}], 13: [function(e, t2) {
1478 (function(e2) {
1479 (function() {
1480 let n2;
1481 t2.exports = "function" == typeof queueMicrotask ? queueMicrotask.bind("undefined" == typeof window ? e2 : window) : (e3) => (n2 || (n2 = Promise.resolve())).then(e3).catch((e4) => setTimeout(() => {
1482 throw e4;
1483 }, 0));
1484 }).call(this);
1485 }).call(this, "undefined" == typeof global ? "undefined" == typeof self ? "undefined" == typeof window ? {} : window : self : global);
1486 }, {}], 14: [function(e, t2) {
1487 (function(n2, r2) {
1488 (function() {
1489 "use strict";
1490 var a = e("safe-buffer").Buffer, o = r2.crypto || r2.msCrypto;
1491 t2.exports = o && o.getRandomValues ? function(e2, t3) {
1492 if (e2 > 4294967295) throw new RangeError("requested too many random bytes");
1493 var r3 = a.allocUnsafe(e2);
1494 if (0 < e2) if (65536 < e2) for (var i = 0; i < e2; i += 65536) o.getRandomValues(r3.slice(i, i + 65536));
1495 else o.getRandomValues(r3);
1496 return "function" == typeof t3 ? n2.nextTick(function() {
1497 t3(null, r3);
1498 }) : r3;
1499 } : function() {
1500 throw new Error("Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11");
1501 };
1502 }).call(this);
1503 }).call(this, e("_process"), "undefined" == typeof global ? "undefined" == typeof self ? "undefined" == typeof window ? {} : window : self : global);
1504 }, { _process: 12, "safe-buffer": 30 }], 15: [function(e, t2) {
1505 "use strict";
1506 function n2(e2, t3) {
1507 e2.prototype = Object.create(t3.prototype), e2.prototype.constructor = e2, e2.__proto__ = t3;
1508 }
1509 function r2(e2, t3, r3) {
1510 function a2(e3, n3, r4) {
1511 return "string" == typeof t3 ? t3 : t3(e3, n3, r4);
1512 }
1513 r3 || (r3 = Error);
1514 var o2 = (function(e3) {
1515 function t4(t5, n3, r4) {
1516 return e3.call(this, a2(t5, n3, r4)) || this;
1517 }
1518 return n2(t4, e3), t4;
1519 })(r3);
1520 o2.prototype.name = r3.name, o2.prototype.code = e2, s[e2] = o2;
1521 }
1522 function a(e2, t3) {
1523 if (Array.isArray(e2)) {
1524 var n3 = e2.length;
1525 return e2 = e2.map(function(e3) {
1526 return e3 + "";
1527 }), 2 < n3 ? "one of ".concat(t3, " ").concat(e2.slice(0, n3 - 1).join(", "), ", or ") + e2[n3 - 1] : 2 === n3 ? "one of ".concat(t3, " ").concat(e2[0], " or ").concat(e2[1]) : "of ".concat(t3, " ").concat(e2[0]);
1528 }
1529 return "of ".concat(t3, " ").concat(e2 + "");
1530 }
1531 function o(e2, t3, n3) {
1532 return e2.substr(!n3 || 0 > n3 ? 0 : +n3, t3.length) === t3;
1533 }
1534 function i(e2, t3, n3) {
1535 return (void 0 === n3 || n3 > e2.length) && (n3 = e2.length), e2.substring(n3 - t3.length, n3) === t3;
1536 }
1537 function d(e2, t3, n3) {
1538 return "number" != typeof n3 && (n3 = 0), !(n3 + t3.length > e2.length) && -1 !== e2.indexOf(t3, n3);
1539 }
1540 var s = {};
1541 r2("ERR_INVALID_OPT_VALUE", function(e2, t3) {
1542 return 'The value "' + t3 + '" is invalid for option "' + e2 + '"';
1543 }, TypeError), r2("ERR_INVALID_ARG_TYPE", function(e2, t3, n3) {
1544 var r3;
1545 "string" == typeof t3 && o(t3, "not ") ? (r3 = "must not be", t3 = t3.replace(/^not /, "")) : r3 = "must be";
1546 var s2;
1547 if (i(e2, " argument")) s2 = "The ".concat(e2, " ").concat(r3, " ").concat(a(t3, "type"));
1548 else {
1549 var l = d(e2, ".") ? "property" : "argument";
1550 s2 = 'The "'.concat(e2, '" ').concat(l, " ").concat(r3, " ").concat(a(t3, "type"));
1551 }
1552 return s2 += ". Received type ".concat(typeof n3), s2;
1553 }, TypeError), r2("ERR_STREAM_PUSH_AFTER_EOF", "stream.push() after EOF"), r2("ERR_METHOD_NOT_IMPLEMENTED", function(e2) {
1554 return "The " + e2 + " method is not implemented";
1555 }), r2("ERR_STREAM_PREMATURE_CLOSE", "Premature close"), r2("ERR_STREAM_DESTROYED", function(e2) {
1556 return "Cannot call " + e2 + " after a stream was destroyed";
1557 }), r2("ERR_MULTIPLE_CALLBACK", "Callback called multiple times"), r2("ERR_STREAM_CANNOT_PIPE", "Cannot pipe, not readable"), r2("ERR_STREAM_WRITE_AFTER_END", "write after end"), r2("ERR_STREAM_NULL_VALUES", "May not write null values to stream", TypeError), r2("ERR_UNKNOWN_ENCODING", function(e2) {
1558 return "Unknown encoding: " + e2;
1559 }, TypeError), r2("ERR_STREAM_UNSHIFT_AFTER_END_EVENT", "stream.unshift() after end event"), t2.exports.codes = s;
1560 }, {}], 16: [function(e, t2) {
1561 (function(n2) {
1562 (function() {
1563 "use strict";
1564 function r2(e2) {
1565 return this instanceof r2 ? void (d.call(this, e2), s.call(this, e2), this.allowHalfOpen = true, e2 && (false === e2.readable && (this.readable = false), false === e2.writable && (this.writable = false), false === e2.allowHalfOpen && (this.allowHalfOpen = false, this.once("end", a)))) : new r2(e2);
1566 }
1567 function a() {
1568 this._writableState.ended || n2.nextTick(o, this);
1569 }
1570 function o(e2) {
1571 e2.end();
1572 }
1573 var i = Object.keys || function(e2) {
1574 var t3 = [];
1575 for (var n3 in e2) t3.push(n3);
1576 return t3;
1577 };
1578 t2.exports = r2;
1579 var d = e("./_stream_readable"), s = e("./_stream_writable");
1580 e("inherits")(r2, d);
1581 for (var l, c = i(s.prototype), u = 0; u < c.length; u++) l = c[u], r2.prototype[l] || (r2.prototype[l] = s.prototype[l]);
1582 Object.defineProperty(r2.prototype, "writableHighWaterMark", { enumerable: false, get: function() {
1583 return this._writableState.highWaterMark;
1584 } }), Object.defineProperty(r2.prototype, "writableBuffer", { enumerable: false, get: function() {
1585 return this._writableState && this._writableState.getBuffer();
1586 } }), Object.defineProperty(r2.prototype, "writableLength", { enumerable: false, get: function() {
1587 return this._writableState.length;
1588 } }), Object.defineProperty(r2.prototype, "destroyed", { enumerable: false, get: function() {
1589 return void 0 !== this._readableState && void 0 !== this._writableState && this._readableState.destroyed && this._writableState.destroyed;
1590 }, set: function(e2) {
1591 void 0 === this._readableState || void 0 === this._writableState || (this._readableState.destroyed = e2, this._writableState.destroyed = e2);
1592 } });
1593 }).call(this);
1594 }).call(this, e("_process"));
1595 }, { "./_stream_readable": 18, "./_stream_writable": 20, _process: 12, inherits: 10 }], 17: [function(e, t2) {
1596 "use strict";
1597 function n2(e2) {
1598 return this instanceof n2 ? void r2.call(this, e2) : new n2(e2);
1599 }
1600 t2.exports = n2;
1601 var r2 = e("./_stream_transform");
1602 e("inherits")(n2, r2), n2.prototype._transform = function(e2, t3, n3) {
1603 n3(null, e2);
1604 };
1605 }, { "./_stream_transform": 19, inherits: 10 }], 18: [function(e, t2) {
1606 (function(n2, r2) {
1607 (function() {
1608 "use strict";
1609 function a(e2) {
1610 return P.from(e2);
1611 }
1612 function o(e2) {
1613 return P.isBuffer(e2) || e2 instanceof M;
1614 }
1615 function i(e2, t3, n3) {
1616 return "function" == typeof e2.prependListener ? e2.prependListener(t3, n3) : void (e2._events && e2._events[t3] ? Array.isArray(e2._events[t3]) ? e2._events[t3].unshift(n3) : e2._events[t3] = [n3, e2._events[t3]] : e2.on(t3, n3));
1617 }
1618 function d(t3, n3, r3) {
1619 A = A || e("./_stream_duplex"), t3 = t3 || {}, "boolean" != typeof r3 && (r3 = n3 instanceof A), this.objectMode = !!t3.objectMode, r3 && (this.objectMode = this.objectMode || !!t3.readableObjectMode), this.highWaterMark = H(this, t3, "readableHighWaterMark", r3), this.buffer = new j(), this.length = 0, this.pipes = null, this.pipesCount = 0, this.flowing = null, this.ended = false, this.endEmitted = false, this.reading = false, this.sync = true, this.needReadable = false, this.emittedReadable = false, this.readableListening = false, this.resumeScheduled = false, this.paused = true, this.emitClose = false !== t3.emitClose, this.autoDestroy = !!t3.autoDestroy, this.destroyed = false, this.defaultEncoding = t3.defaultEncoding || "utf8", this.awaitDrain = 0, this.readingMore = false, this.decoder = null, this.encoding = null, t3.encoding && (!F && (F = e("string_decoder/").StringDecoder), this.decoder = new F(t3.encoding), this.encoding = t3.encoding);
1620 }
1621 function s(t3) {
1622 if (A = A || e("./_stream_duplex"), !(this instanceof s)) return new s(t3);
1623 var n3 = this instanceof A;
1624 this._readableState = new d(t3, this, n3), this.readable = true, t3 && ("function" == typeof t3.read && (this._read = t3.read), "function" == typeof t3.destroy && (this._destroy = t3.destroy)), I.call(this);
1625 }
1626 function l(e2, t3, n3, r3, o2) {
1627 x("readableAddChunk", t3);
1628 var i2 = e2._readableState;
1629 if (null === t3) i2.reading = false, g(e2, i2);
1630 else {
1631 var d2;
1632 if (o2 || (d2 = u(i2, t3)), d2) X(e2, d2);
1633 else if (!(i2.objectMode || t3 && 0 < t3.length)) r3 || (i2.reading = false, m(e2, i2));
1634 else if ("string" == typeof t3 || i2.objectMode || Object.getPrototypeOf(t3) === P.prototype || (t3 = a(t3)), r3) i2.endEmitted ? X(e2, new K()) : c(e2, i2, t3, true);
1635 else if (i2.ended) X(e2, new z());
1636 else {
1637 if (i2.destroyed) return false;
1638 i2.reading = false, i2.decoder && !n3 ? (t3 = i2.decoder.write(t3), i2.objectMode || 0 !== t3.length ? c(e2, i2, t3, false) : m(e2, i2)) : c(e2, i2, t3, false);
1639 }
1640 }
1641 return !i2.ended && (i2.length < i2.highWaterMark || 0 === i2.length);
1642 }
1643 function c(e2, t3, n3, r3) {
1644 t3.flowing && 0 === t3.length && !t3.sync ? (t3.awaitDrain = 0, e2.emit("data", n3)) : (t3.length += t3.objectMode ? 1 : n3.length, r3 ? t3.buffer.unshift(n3) : t3.buffer.push(n3), t3.needReadable && _(e2)), m(e2, t3);
1645 }
1646 function u(e2, t3) {
1647 var n3;
1648 return o(t3) || "string" == typeof t3 || void 0 === t3 || e2.objectMode || (n3 = new V("chunk", ["string", "Buffer", "Uint8Array"], t3)), n3;
1649 }
1650 function p(e2) {
1651 return 1073741824 <= e2 ? e2 = 1073741824 : (e2--, e2 |= e2 >>> 1, e2 |= e2 >>> 2, e2 |= e2 >>> 4, e2 |= e2 >>> 8, e2 |= e2 >>> 16, e2++), e2;
1652 }
1653 function f(e2, t3) {
1654 return 0 >= e2 || 0 === t3.length && t3.ended ? 0 : t3.objectMode ? 1 : e2 === e2 ? (e2 > t3.highWaterMark && (t3.highWaterMark = p(e2)), e2 <= t3.length ? e2 : t3.ended ? t3.length : (t3.needReadable = true, 0)) : t3.flowing && t3.length ? t3.buffer.head.data.length : t3.length;
1655 }
1656 function g(e2, t3) {
1657 if (x("onEofChunk"), !t3.ended) {
1658 if (t3.decoder) {
1659 var n3 = t3.decoder.end();
1660 n3 && n3.length && (t3.buffer.push(n3), t3.length += t3.objectMode ? 1 : n3.length);
1661 }
1662 t3.ended = true, t3.sync ? _(e2) : (t3.needReadable = false, !t3.emittedReadable && (t3.emittedReadable = true, h(e2)));
1663 }
1664 }
1665 function _(e2) {
1666 var t3 = e2._readableState;
1667 x("emitReadable", t3.needReadable, t3.emittedReadable), t3.needReadable = false, t3.emittedReadable || (x("emitReadable", t3.flowing), t3.emittedReadable = true, n2.nextTick(h, e2));
1668 }
1669 function h(e2) {
1670 var t3 = e2._readableState;
1671 x("emitReadable_", t3.destroyed, t3.length, t3.ended), !t3.destroyed && (t3.length || t3.ended) && (e2.emit("readable"), t3.emittedReadable = false), t3.needReadable = !t3.flowing && !t3.ended && t3.length <= t3.highWaterMark, S(e2);
1672 }
1673 function m(e2, t3) {
1674 t3.readingMore || (t3.readingMore = true, n2.nextTick(b, e2, t3));
1675 }
1676 function b(e2, t3) {
1677 for (; !t3.reading && !t3.ended && (t3.length < t3.highWaterMark || t3.flowing && 0 === t3.length); ) {
1678 var n3 = t3.length;
1679 if (x("maybeReadMore read 0"), e2.read(0), n3 === t3.length) break;
1680 }
1681 t3.readingMore = false;
1682 }
1683 function y(e2) {
1684 return function() {
1685 var t3 = e2._readableState;
1686 x("pipeOnDrain", t3.awaitDrain), t3.awaitDrain && t3.awaitDrain--, 0 === t3.awaitDrain && D(e2, "data") && (t3.flowing = true, S(e2));
1687 };
1688 }
1689 function C(e2) {
1690 var t3 = e2._readableState;
1691 t3.readableListening = 0 < e2.listenerCount("readable"), t3.resumeScheduled && !t3.paused ? t3.flowing = true : 0 < e2.listenerCount("data") && e2.resume();
1692 }
1693 function R(e2) {
1694 x("readable nexttick read 0"), e2.read(0);
1695 }
1696 function E(e2, t3) {
1697 t3.resumeScheduled || (t3.resumeScheduled = true, n2.nextTick(w, e2, t3));
1698 }
1699 function w(e2, t3) {
1700 x("resume", t3.reading), t3.reading || e2.read(0), t3.resumeScheduled = false, e2.emit("resume"), S(e2), t3.flowing && !t3.reading && e2.read(0);
1701 }
1702 function S(e2) {
1703 var t3 = e2._readableState;
1704 for (x("flow", t3.flowing); t3.flowing && null !== e2.read(); ) ;
1705 }
1706 function T(e2, t3) {
1707 if (0 === t3.length) return null;
1708 var n3;
1709 return t3.objectMode ? n3 = t3.buffer.shift() : !e2 || e2 >= t3.length ? (n3 = t3.decoder ? t3.buffer.join("") : 1 === t3.buffer.length ? t3.buffer.first() : t3.buffer.concat(t3.length), t3.buffer.clear()) : n3 = t3.buffer.consume(e2, t3.decoder), n3;
1710 }
1711 function v(e2) {
1712 var t3 = e2._readableState;
1713 x("endReadable", t3.endEmitted), t3.endEmitted || (t3.ended = true, n2.nextTick(k, t3, e2));
1714 }
1715 function k(e2, t3) {
1716 if (x("endReadableNT", e2.endEmitted, e2.length), !e2.endEmitted && 0 === e2.length && (e2.endEmitted = true, t3.readable = false, t3.emit("end"), e2.autoDestroy)) {
1717 var n3 = t3._writableState;
1718 (!n3 || n3.autoDestroy && n3.finished) && t3.destroy();
1719 }
1720 }
1721 function L(e2, t3) {
1722 for (var n3 = 0, r3 = e2.length; n3 < r3; n3++) if (e2[n3] === t3) return n3;
1723 return -1;
1724 }
1725 t2.exports = s;
1726 var A;
1727 s.ReadableState = d;
1728 var x, N = e("events").EventEmitter, D = function(e2, t3) {
1729 return e2.listeners(t3).length;
1730 }, I = e("./internal/streams/stream"), P = e("buffer").Buffer, M = r2.Uint8Array || function() {
1731 }, O = e("util");
1732 x = O && O.debuglog ? O.debuglog("stream") : function() {
1733 };
1734 var F, B, U, j = e("./internal/streams/buffer_list"), q = e("./internal/streams/destroy"), W = e("./internal/streams/state"), H = W.getHighWaterMark, Y = e("../errors").codes, V = Y.ERR_INVALID_ARG_TYPE, z = Y.ERR_STREAM_PUSH_AFTER_EOF, G = Y.ERR_METHOD_NOT_IMPLEMENTED, K = Y.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;
1735 e("inherits")(s, I);
1736 var X = q.errorOrDestroy, $ = ["error", "close", "destroy", "pause", "resume"];
1737 Object.defineProperty(s.prototype, "destroyed", { enumerable: false, get: function() {
1738 return void 0 !== this._readableState && this._readableState.destroyed;
1739 }, set: function(e2) {
1740 this._readableState && (this._readableState.destroyed = e2);
1741 } }), s.prototype.destroy = q.destroy, s.prototype._undestroy = q.undestroy, s.prototype._destroy = function(e2, t3) {
1742 t3(e2);
1743 }, s.prototype.push = function(e2, t3) {
1744 var n3, r3 = this._readableState;
1745 return r3.objectMode ? n3 = true : "string" == typeof e2 && (t3 = t3 || r3.defaultEncoding, t3 !== r3.encoding && (e2 = P.from(e2, t3), t3 = ""), n3 = true), l(this, e2, t3, false, n3);
1746 }, s.prototype.unshift = function(e2) {
1747 return l(this, e2, null, true, false);
1748 }, s.prototype.isPaused = function() {
1749 return false === this._readableState.flowing;
1750 }, s.prototype.setEncoding = function(t3) {
1751 F || (F = e("string_decoder/").StringDecoder);
1752 var n3 = new F(t3);
1753 this._readableState.decoder = n3, this._readableState.encoding = this._readableState.decoder.encoding;
1754 for (var r3 = this._readableState.buffer.head, a2 = ""; null !== r3; ) a2 += n3.write(r3.data), r3 = r3.next;
1755 return this._readableState.buffer.clear(), "" !== a2 && this._readableState.buffer.push(a2), this._readableState.length = a2.length, this;
1756 };
1757 s.prototype.read = function(e2) {
1758 x("read", e2), e2 = parseInt(e2, 10);
1759 var t3 = this._readableState, r3 = e2;
1760 if (0 !== e2 && (t3.emittedReadable = false), 0 === e2 && t3.needReadable && ((0 === t3.highWaterMark ? 0 < t3.length : t3.length >= t3.highWaterMark) || t3.ended)) return x("read: emitReadable", t3.length, t3.ended), 0 === t3.length && t3.ended ? v(this) : _(this), null;
1761 if (e2 = f(e2, t3), 0 === e2 && t3.ended) return 0 === t3.length && v(this), null;
1762 var a2 = t3.needReadable;
1763 x("need readable", a2), (0 === t3.length || t3.length - e2 < t3.highWaterMark) && (a2 = true, x("length less than watermark", a2)), t3.ended || t3.reading ? (a2 = false, x("reading or ended", a2)) : a2 && (x("do read"), t3.reading = true, t3.sync = true, 0 === t3.length && (t3.needReadable = true), this._read(t3.highWaterMark), t3.sync = false, !t3.reading && (e2 = f(r3, t3)));
1764 var o2;
1765 return o2 = 0 < e2 ? T(e2, t3) : null, null === o2 ? (t3.needReadable = t3.length <= t3.highWaterMark, e2 = 0) : (t3.length -= e2, t3.awaitDrain = 0), 0 === t3.length && (!t3.ended && (t3.needReadable = true), r3 !== e2 && t3.ended && v(this)), null !== o2 && this.emit("data", o2), o2;
1766 }, s.prototype._read = function() {
1767 X(this, new G("_read()"));
1768 }, s.prototype.pipe = function(e2, t3) {
1769 function r3(e3, t4) {
1770 x("onunpipe"), e3 === p2 && t4 && false === t4.hasUnpiped && (t4.hasUnpiped = true, o2());
1771 }
1772 function a2() {
1773 x("onend"), e2.end();
1774 }
1775 function o2() {
1776 x("cleanup"), e2.removeListener("close", l2), e2.removeListener("finish", c2), e2.removeListener("drain", h2), e2.removeListener("error", s2), e2.removeListener("unpipe", r3), p2.removeListener("end", a2), p2.removeListener("end", u2), p2.removeListener("data", d2), m2 = true, f2.awaitDrain && (!e2._writableState || e2._writableState.needDrain) && h2();
1777 }
1778 function d2(t4) {
1779 x("ondata");
1780 var n3 = e2.write(t4);
1781 x("dest.write", n3), false === n3 && ((1 === f2.pipesCount && f2.pipes === e2 || 1 < f2.pipesCount && -1 !== L(f2.pipes, e2)) && !m2 && (x("false write response, pause", f2.awaitDrain), f2.awaitDrain++), p2.pause());
1782 }
1783 function s2(t4) {
1784 x("onerror", t4), u2(), e2.removeListener("error", s2), 0 === D(e2, "error") && X(e2, t4);
1785 }
1786 function l2() {
1787 e2.removeListener("finish", c2), u2();
1788 }
1789 function c2() {
1790 x("onfinish"), e2.removeListener("close", l2), u2();
1791 }
1792 function u2() {
1793 x("unpipe"), p2.unpipe(e2);
1794 }
1795 var p2 = this, f2 = this._readableState;
1796 switch (f2.pipesCount) {
1797 case 0:
1798 f2.pipes = e2;
1799 break;
1800 case 1:
1801 f2.pipes = [f2.pipes, e2];
1802 break;
1803 default:
1804 f2.pipes.push(e2);
1805 }
1806 f2.pipesCount += 1, x("pipe count=%d opts=%j", f2.pipesCount, t3);
1807 var g2 = (!t3 || false !== t3.end) && e2 !== n2.stdout && e2 !== n2.stderr, _2 = g2 ? a2 : u2;
1808 f2.endEmitted ? n2.nextTick(_2) : p2.once("end", _2), e2.on("unpipe", r3);
1809 var h2 = y(p2);
1810 e2.on("drain", h2);
1811 var m2 = false;
1812 return p2.on("data", d2), i(e2, "error", s2), e2.once("close", l2), e2.once("finish", c2), e2.emit("pipe", p2), f2.flowing || (x("pipe resume"), p2.resume()), e2;
1813 }, s.prototype.unpipe = function(e2) {
1814 var t3 = this._readableState, n3 = { hasUnpiped: false };
1815 if (0 === t3.pipesCount) return this;
1816 if (1 === t3.pipesCount) return e2 && e2 !== t3.pipes ? this : (e2 || (e2 = t3.pipes), t3.pipes = null, t3.pipesCount = 0, t3.flowing = false, e2 && e2.emit("unpipe", this, n3), this);
1817 if (!e2) {
1818 var r3 = t3.pipes, a2 = t3.pipesCount;
1819 t3.pipes = null, t3.pipesCount = 0, t3.flowing = false;
1820 for (var o2 = 0; o2 < a2; o2++) r3[o2].emit("unpipe", this, { hasUnpiped: false });
1821 return this;
1822 }
1823 var d2 = L(t3.pipes, e2);
1824 return -1 === d2 ? this : (t3.pipes.splice(d2, 1), t3.pipesCount -= 1, 1 === t3.pipesCount && (t3.pipes = t3.pipes[0]), e2.emit("unpipe", this, n3), this);
1825 }, s.prototype.on = function(e2, t3) {
1826 var r3 = I.prototype.on.call(this, e2, t3), a2 = this._readableState;
1827 return "data" === e2 ? (a2.readableListening = 0 < this.listenerCount("readable"), false !== a2.flowing && this.resume()) : "readable" == e2 && !a2.endEmitted && !a2.readableListening && (a2.readableListening = a2.needReadable = true, a2.flowing = false, a2.emittedReadable = false, x("on readable", a2.length, a2.reading), a2.length ? _(this) : !a2.reading && n2.nextTick(R, this)), r3;
1828 }, s.prototype.addListener = s.prototype.on, s.prototype.removeListener = function(e2, t3) {
1829 var r3 = I.prototype.removeListener.call(this, e2, t3);
1830 return "readable" === e2 && n2.nextTick(C, this), r3;
1831 }, s.prototype.removeAllListeners = function(e2) {
1832 var t3 = I.prototype.removeAllListeners.apply(this, arguments);
1833 return ("readable" === e2 || void 0 === e2) && n2.nextTick(C, this), t3;
1834 }, s.prototype.resume = function() {
1835 var e2 = this._readableState;
1836 return e2.flowing || (x("resume"), e2.flowing = !e2.readableListening, E(this, e2)), e2.paused = false, this;
1837 }, s.prototype.pause = function() {
1838 return x("call pause flowing=%j", this._readableState.flowing), false !== this._readableState.flowing && (x("pause"), this._readableState.flowing = false, this.emit("pause")), this._readableState.paused = true, this;
1839 }, s.prototype.wrap = function(e2) {
1840 var t3 = this, r3 = this._readableState, a2 = false;
1841 for (var o2 in e2.on("end", function() {
1842 if (x("wrapped end"), r3.decoder && !r3.ended) {
1843 var e3 = r3.decoder.end();
1844 e3 && e3.length && t3.push(e3);
1845 }
1846 t3.push(null);
1847 }), e2.on("data", function(n3) {
1848 if ((x("wrapped data"), r3.decoder && (n3 = r3.decoder.write(n3)), !(r3.objectMode && (null === n3 || void 0 === n3))) && (r3.objectMode || n3 && n3.length)) {
1849 var o3 = t3.push(n3);
1850 o3 || (a2 = true, e2.pause());
1851 }
1852 }), e2) void 0 === this[o2] && "function" == typeof e2[o2] && (this[o2] = /* @__PURE__ */ (function(t4) {
1853 return function() {
1854 return e2[t4].apply(e2, arguments);
1855 };
1856 })(o2));
1857 for (var i2 = 0; i2 < $.length; i2++) e2.on($[i2], this.emit.bind(this, $[i2]));
1858 return this._read = function(t4) {
1859 x("wrapped _read", t4), a2 && (a2 = false, e2.resume());
1860 }, this;
1861 }, "function" == typeof Symbol && (s.prototype[Symbol.asyncIterator] = function() {
1862 return void 0 === B && (B = e("./internal/streams/async_iterator")), B(this);
1863 }), Object.defineProperty(s.prototype, "readableHighWaterMark", { enumerable: false, get: function() {
1864 return this._readableState.highWaterMark;
1865 } }), Object.defineProperty(s.prototype, "readableBuffer", { enumerable: false, get: function() {
1866 return this._readableState && this._readableState.buffer;
1867 } }), Object.defineProperty(s.prototype, "readableFlowing", { enumerable: false, get: function() {
1868 return this._readableState.flowing;
1869 }, set: function(e2) {
1870 this._readableState && (this._readableState.flowing = e2);
1871 } }), s._fromList = T, Object.defineProperty(s.prototype, "readableLength", { enumerable: false, get: function() {
1872 return this._readableState.length;
1873 } }), "function" == typeof Symbol && (s.from = function(t3, n3) {
1874 return void 0 === U && (U = e("./internal/streams/from")), U(s, t3, n3);
1875 });
1876 }).call(this);
1877 }).call(this, e("_process"), "undefined" == typeof global ? "undefined" == typeof self ? "undefined" == typeof window ? {} : window : self : global);
1878 }, { "../errors": 15, "./_stream_duplex": 16, "./internal/streams/async_iterator": 21, "./internal/streams/buffer_list": 22, "./internal/streams/destroy": 23, "./internal/streams/from": 25, "./internal/streams/state": 27, "./internal/streams/stream": 28, _process: 12, buffer: 3, events: 7, inherits: 10, "string_decoder/": 31, util: 2 }], 19: [function(e, t2) {
1879 "use strict";
1880 function n2(e2, t3) {
1881 var n3 = this._transformState;
1882 n3.transforming = false;
1883 var r3 = n3.writecb;
1884 if (null === r3) return this.emit("error", new s());
1885 n3.writechunk = null, n3.writecb = null, null != t3 && this.push(t3), r3(e2);
1886 var a2 = this._readableState;
1887 a2.reading = false, (a2.needReadable || a2.length < a2.highWaterMark) && this._read(a2.highWaterMark);
1888 }
1889 function r2(e2) {
1890 return this instanceof r2 ? void (u.call(this, e2), this._transformState = { afterTransform: n2.bind(this), needTransform: false, transforming: false, writecb: null, writechunk: null, writeencoding: null }, this._readableState.needReadable = true, this._readableState.sync = false, e2 && ("function" == typeof e2.transform && (this._transform = e2.transform), "function" == typeof e2.flush && (this._flush = e2.flush)), this.on("prefinish", a)) : new r2(e2);
1891 }
1892 function a() {
1893 var e2 = this;
1894 "function" != typeof this._flush || this._readableState.destroyed ? o(this, null, null) : this._flush(function(t3, n3) {
1895 o(e2, t3, n3);
1896 });
1897 }
1898 function o(e2, t3, n3) {
1899 if (t3) return e2.emit("error", t3);
1900 if (null != n3 && e2.push(n3), e2._writableState.length) throw new c();
1901 if (e2._transformState.transforming) throw new l();
1902 return e2.push(null);
1903 }
1904 t2.exports = r2;
1905 var i = e("../errors").codes, d = i.ERR_METHOD_NOT_IMPLEMENTED, s = i.ERR_MULTIPLE_CALLBACK, l = i.ERR_TRANSFORM_ALREADY_TRANSFORMING, c = i.ERR_TRANSFORM_WITH_LENGTH_0, u = e("./_stream_duplex");
1906 e("inherits")(r2, u), r2.prototype.push = function(e2, t3) {
1907 return this._transformState.needTransform = false, u.prototype.push.call(this, e2, t3);
1908 }, r2.prototype._transform = function(e2, t3, n3) {
1909 n3(new d("_transform()"));
1910 }, r2.prototype._write = function(e2, t3, n3) {
1911 var r3 = this._transformState;
1912 if (r3.writecb = n3, r3.writechunk = e2, r3.writeencoding = t3, !r3.transforming) {
1913 var a2 = this._readableState;
1914 (r3.needTransform || a2.needReadable || a2.length < a2.highWaterMark) && this._read(a2.highWaterMark);
1915 }
1916 }, r2.prototype._read = function() {
1917 var e2 = this._transformState;
1918 null === e2.writechunk || e2.transforming ? e2.needTransform = true : (e2.transforming = true, this._transform(e2.writechunk, e2.writeencoding, e2.afterTransform));
1919 }, r2.prototype._destroy = function(e2, t3) {
1920 u.prototype._destroy.call(this, e2, function(e3) {
1921 t3(e3);
1922 });
1923 };
1924 }, { "../errors": 15, "./_stream_duplex": 16, inherits: 10 }], 20: [function(e, t2) {
1925 (function(n2, r2) {
1926 (function() {
1927 "use strict";
1928 function a(e2) {
1929 var t3 = this;
1930 this.next = null, this.entry = null, this.finish = function() {
1931 v(t3, e2);
1932 };
1933 }
1934 function o(e2) {
1935 return x.from(e2);
1936 }
1937 function i(e2) {
1938 return x.isBuffer(e2) || e2 instanceof N;
1939 }
1940 function d() {
1941 }
1942 function s(t3, n3, r3) {
1943 k = k || e("./_stream_duplex"), t3 = t3 || {}, "boolean" != typeof r3 && (r3 = n3 instanceof k), this.objectMode = !!t3.objectMode, r3 && (this.objectMode = this.objectMode || !!t3.writableObjectMode), this.highWaterMark = P(this, t3, "writableHighWaterMark", r3), this.finalCalled = false, this.needDrain = false, this.ending = false, this.ended = false, this.finished = false, this.destroyed = false;
1944 var o2 = false === t3.decodeStrings;
1945 this.decodeStrings = !o2, this.defaultEncoding = t3.defaultEncoding || "utf8", this.length = 0, this.writing = false, this.corked = 0, this.sync = true, this.bufferProcessing = false, this.onwrite = function(e2) {
1946 m(n3, e2);
1947 }, this.writecb = null, this.writelen = 0, this.bufferedRequest = null, this.lastBufferedRequest = null, this.pendingcb = 0, this.prefinished = false, this.errorEmitted = false, this.emitClose = false !== t3.emitClose, this.autoDestroy = !!t3.autoDestroy, this.bufferedRequestCount = 0, this.corkedRequestsFree = new a(this);
1948 }
1949 function l(t3) {
1950 k = k || e("./_stream_duplex");
1951 var n3 = this instanceof k;
1952 return n3 || V.call(l, this) ? void (this._writableState = new s(t3, this, n3), this.writable = true, t3 && ("function" == typeof t3.write && (this._write = t3.write), "function" == typeof t3.writev && (this._writev = t3.writev), "function" == typeof t3.destroy && (this._destroy = t3.destroy), "function" == typeof t3.final && (this._final = t3.final)), A.call(this)) : new l(t3);
1953 }
1954 function c(e2, t3) {
1955 var r3 = new W();
1956 Y(e2, r3), n2.nextTick(t3, r3);
1957 }
1958 function u(e2, t3, r3, a2) {
1959 var o2;
1960 return null === r3 ? o2 = new q() : "string" != typeof r3 && !t3.objectMode && (o2 = new O("chunk", ["string", "Buffer"], r3)), !o2 || (Y(e2, o2), n2.nextTick(a2, o2), false);
1961 }
1962 function p(e2, t3, n3) {
1963 return e2.objectMode || false === e2.decodeStrings || "string" != typeof t3 || (t3 = x.from(t3, n3)), t3;
1964 }
1965 function f(e2, t3, n3, r3, a2, o2) {
1966 if (!n3) {
1967 var i2 = p(t3, r3, a2);
1968 r3 !== i2 && (n3 = true, a2 = "buffer", r3 = i2);
1969 }
1970 var d2 = t3.objectMode ? 1 : r3.length;
1971 t3.length += d2;
1972 var s2 = t3.length < t3.highWaterMark;
1973 if (s2 || (t3.needDrain = true), t3.writing || t3.corked) {
1974 var l2 = t3.lastBufferedRequest;
1975 t3.lastBufferedRequest = { chunk: r3, encoding: a2, isBuf: n3, callback: o2, next: null }, l2 ? l2.next = t3.lastBufferedRequest : t3.bufferedRequest = t3.lastBufferedRequest, t3.bufferedRequestCount += 1;
1976 } else g(e2, t3, false, d2, r3, a2, o2);
1977 return s2;
1978 }
1979 function g(e2, t3, n3, r3, a2, o2, i2) {
1980 t3.writelen = r3, t3.writecb = i2, t3.writing = true, t3.sync = true, t3.destroyed ? t3.onwrite(new j("write")) : n3 ? e2._writev(a2, t3.onwrite) : e2._write(a2, o2, t3.onwrite), t3.sync = false;
1981 }
1982 function _(e2, t3, r3, a2, o2) {
1983 --t3.pendingcb, r3 ? (n2.nextTick(o2, a2), n2.nextTick(S, e2, t3), e2._writableState.errorEmitted = true, Y(e2, a2)) : (o2(a2), e2._writableState.errorEmitted = true, Y(e2, a2), S(e2, t3));
1984 }
1985 function h(e2) {
1986 e2.writing = false, e2.writecb = null, e2.length -= e2.writelen, e2.writelen = 0;
1987 }
1988 function m(e2, t3) {
1989 var r3 = e2._writableState, a2 = r3.sync, o2 = r3.writecb;
1990 if ("function" != typeof o2) throw new B();
1991 if (h(r3), t3) _(e2, r3, a2, t3, o2);
1992 else {
1993 var i2 = R(r3) || e2.destroyed;
1994 i2 || r3.corked || r3.bufferProcessing || !r3.bufferedRequest || C(e2, r3), a2 ? n2.nextTick(b, e2, r3, i2, o2) : b(e2, r3, i2, o2);
1995 }
1996 }
1997 function b(e2, t3, n3, r3) {
1998 n3 || y(e2, t3), t3.pendingcb--, r3(), S(e2, t3);
1999 }
2000 function y(e2, t3) {
2001 0 === t3.length && t3.needDrain && (t3.needDrain = false, e2.emit("drain"));
2002 }
2003 function C(e2, t3) {
2004 t3.bufferProcessing = true;
2005 var n3 = t3.bufferedRequest;
2006 if (e2._writev && n3 && n3.next) {
2007 var r3 = t3.bufferedRequestCount, o2 = Array(r3), i2 = t3.corkedRequestsFree;
2008 i2.entry = n3;
2009 for (var d2 = 0, s2 = true; n3; ) o2[d2] = n3, n3.isBuf || (s2 = false), n3 = n3.next, d2 += 1;
2010 o2.allBuffers = s2, g(e2, t3, true, t3.length, o2, "", i2.finish), t3.pendingcb++, t3.lastBufferedRequest = null, i2.next ? (t3.corkedRequestsFree = i2.next, i2.next = null) : t3.corkedRequestsFree = new a(t3), t3.bufferedRequestCount = 0;
2011 } else {
2012 for (; n3; ) {
2013 var l2 = n3.chunk, c2 = n3.encoding, u2 = n3.callback, p2 = t3.objectMode ? 1 : l2.length;
2014 if (g(e2, t3, false, p2, l2, c2, u2), n3 = n3.next, t3.bufferedRequestCount--, t3.writing) break;
2015 }
2016 null === n3 && (t3.lastBufferedRequest = null);
2017 }
2018 t3.bufferedRequest = n3, t3.bufferProcessing = false;
2019 }
2020 function R(e2) {
2021 return e2.ending && 0 === e2.length && null === e2.bufferedRequest && !e2.finished && !e2.writing;
2022 }
2023 function E(e2, t3) {
2024 e2._final(function(n3) {
2025 t3.pendingcb--, n3 && Y(e2, n3), t3.prefinished = true, e2.emit("prefinish"), S(e2, t3);
2026 });
2027 }
2028 function w(e2, t3) {
2029 t3.prefinished || t3.finalCalled || ("function" != typeof e2._final || t3.destroyed ? (t3.prefinished = true, e2.emit("prefinish")) : (t3.pendingcb++, t3.finalCalled = true, n2.nextTick(E, e2, t3)));
2030 }
2031 function S(e2, t3) {
2032 var n3 = R(t3);
2033 if (n3 && (w(e2, t3), 0 === t3.pendingcb && (t3.finished = true, e2.emit("finish"), t3.autoDestroy))) {
2034 var r3 = e2._readableState;
2035 (!r3 || r3.autoDestroy && r3.endEmitted) && e2.destroy();
2036 }
2037 return n3;
2038 }
2039 function T(e2, t3, r3) {
2040 t3.ending = true, S(e2, t3), r3 && (t3.finished ? n2.nextTick(r3) : e2.once("finish", r3)), t3.ended = true, e2.writable = false;
2041 }
2042 function v(e2, t3, n3) {
2043 var r3 = e2.entry;
2044 for (e2.entry = null; r3; ) {
2045 var a2 = r3.callback;
2046 t3.pendingcb--, a2(n3), r3 = r3.next;
2047 }
2048 t3.corkedRequestsFree.next = e2;
2049 }
2050 t2.exports = l;
2051 var k;
2052 l.WritableState = s;
2053 var L = { deprecate: e("util-deprecate") }, A = e("./internal/streams/stream"), x = e("buffer").Buffer, N = r2.Uint8Array || function() {
2054 }, D = e("./internal/streams/destroy"), I = e("./internal/streams/state"), P = I.getHighWaterMark, M = e("../errors").codes, O = M.ERR_INVALID_ARG_TYPE, F = M.ERR_METHOD_NOT_IMPLEMENTED, B = M.ERR_MULTIPLE_CALLBACK, U = M.ERR_STREAM_CANNOT_PIPE, j = M.ERR_STREAM_DESTROYED, q = M.ERR_STREAM_NULL_VALUES, W = M.ERR_STREAM_WRITE_AFTER_END, H = M.ERR_UNKNOWN_ENCODING, Y = D.errorOrDestroy;
2055 e("inherits")(l, A), s.prototype.getBuffer = function() {
2056 for (var e2 = this.bufferedRequest, t3 = []; e2; ) t3.push(e2), e2 = e2.next;
2057 return t3;
2058 }, (function() {
2059 try {
2060 Object.defineProperty(s.prototype, "buffer", { get: L.deprecate(function() {
2061 return this.getBuffer();
2062 }, "_writableState.buffer is deprecated. Use _writableState.getBuffer instead.", "DEP0003") });
2063 } catch (e2) {
2064 }
2065 })();
2066 var V;
2067 "function" == typeof Symbol && Symbol.hasInstance && "function" == typeof Function.prototype[Symbol.hasInstance] ? (V = Function.prototype[Symbol.hasInstance], Object.defineProperty(l, Symbol.hasInstance, { value: function(e2) {
2068 return !!V.call(this, e2) || !(this !== l) && e2 && e2._writableState instanceof s;
2069 } })) : V = function(e2) {
2070 return e2 instanceof this;
2071 }, l.prototype.pipe = function() {
2072 Y(this, new U());
2073 }, l.prototype.write = function(e2, t3, n3) {
2074 var r3 = this._writableState, a2 = false, s2 = !r3.objectMode && i(e2);
2075 return s2 && !x.isBuffer(e2) && (e2 = o(e2)), "function" == typeof t3 && (n3 = t3, t3 = null), s2 ? t3 = "buffer" : !t3 && (t3 = r3.defaultEncoding), "function" != typeof n3 && (n3 = d), r3.ending ? c(this, n3) : (s2 || u(this, r3, e2, n3)) && (r3.pendingcb++, a2 = f(this, r3, s2, e2, t3, n3)), a2;
2076 }, l.prototype.cork = function() {
2077 this._writableState.corked++;
2078 }, l.prototype.uncork = function() {
2079 var e2 = this._writableState;
2080 e2.corked && (e2.corked--, !e2.writing && !e2.corked && !e2.bufferProcessing && e2.bufferedRequest && C(this, e2));
2081 }, l.prototype.setDefaultEncoding = function(e2) {
2082 if ("string" == typeof e2 && (e2 = e2.toLowerCase()), !(-1 < ["hex", "utf8", "utf-8", "ascii", "binary", "base64", "ucs2", "ucs-2", "utf16le", "utf-16le", "raw"].indexOf((e2 + "").toLowerCase()))) throw new H(e2);
2083 return this._writableState.defaultEncoding = e2, this;
2084 }, Object.defineProperty(l.prototype, "writableBuffer", { enumerable: false, get: function() {
2085 return this._writableState && this._writableState.getBuffer();
2086 } }), Object.defineProperty(l.prototype, "writableHighWaterMark", { enumerable: false, get: function() {
2087 return this._writableState.highWaterMark;
2088 } }), l.prototype._write = function(e2, t3, n3) {
2089 n3(new F("_write()"));
2090 }, l.prototype._writev = null, l.prototype.end = function(e2, t3, n3) {
2091 var r3 = this._writableState;
2092 return "function" == typeof e2 ? (n3 = e2, e2 = null, t3 = null) : "function" == typeof t3 && (n3 = t3, t3 = null), null !== e2 && void 0 !== e2 && this.write(e2, t3), r3.corked && (r3.corked = 1, this.uncork()), r3.ending || T(this, r3, n3), this;
2093 }, Object.defineProperty(l.prototype, "writableLength", { enumerable: false, get: function() {
2094 return this._writableState.length;
2095 } }), Object.defineProperty(l.prototype, "destroyed", { enumerable: false, get: function() {
2096 return void 0 !== this._writableState && this._writableState.destroyed;
2097 }, set: function(e2) {
2098 this._writableState && (this._writableState.destroyed = e2);
2099 } }), l.prototype.destroy = D.destroy, l.prototype._undestroy = D.undestroy, l.prototype._destroy = function(e2, t3) {
2100 t3(e2);
2101 };
2102 }).call(this);
2103 }).call(this, e("_process"), "undefined" == typeof global ? "undefined" == typeof self ? "undefined" == typeof window ? {} : window : self : global);
2104 }, { "../errors": 15, "./_stream_duplex": 16, "./internal/streams/destroy": 23, "./internal/streams/state": 27, "./internal/streams/stream": 28, _process: 12, buffer: 3, inherits: 10, "util-deprecate": 32 }], 21: [function(e, t2) {
2105 (function(n2) {
2106 (function() {
2107 "use strict";
2108 function r2(e2, t3, n3) {
2109 return t3 in e2 ? Object.defineProperty(e2, t3, { value: n3, enumerable: true, configurable: true, writable: true }) : e2[t3] = n3, e2;
2110 }
2111 function a(e2, t3) {
2112 return { value: e2, done: t3 };
2113 }
2114 function o(e2) {
2115 var t3 = e2[c];
2116 if (null !== t3) {
2117 var n3 = e2[h].read();
2118 null !== n3 && (e2[g] = null, e2[c] = null, e2[u] = null, t3(a(n3, false)));
2119 }
2120 }
2121 function i(e2) {
2122 n2.nextTick(o, e2);
2123 }
2124 function d(e2, t3) {
2125 return function(n3, r3) {
2126 e2.then(function() {
2127 return t3[f] ? void n3(a(void 0, true)) : void t3[_](n3, r3);
2128 }, r3);
2129 };
2130 }
2131 var s, l = e("./end-of-stream"), c = Symbol("lastResolve"), u = Symbol("lastReject"), p = Symbol("error"), f = Symbol("ended"), g = Symbol("lastPromise"), _ = Symbol("handlePromise"), h = Symbol("stream"), m = Object.getPrototypeOf(function() {
2132 }), b = Object.setPrototypeOf((s = { get stream() {
2133 return this[h];
2134 }, next: function() {
2135 var e2 = this, t3 = this[p];
2136 if (null !== t3) return Promise.reject(t3);
2137 if (this[f]) return Promise.resolve(a(void 0, true));
2138 if (this[h].destroyed) return new Promise(function(t4, r4) {
2139 n2.nextTick(function() {
2140 e2[p] ? r4(e2[p]) : t4(a(void 0, true));
2141 });
2142 });
2143 var r3, o2 = this[g];
2144 if (o2) r3 = new Promise(d(o2, this));
2145 else {
2146 var i2 = this[h].read();
2147 if (null !== i2) return Promise.resolve(a(i2, false));
2148 r3 = new Promise(this[_]);
2149 }
2150 return this[g] = r3, r3;
2151 } }, r2(s, Symbol.asyncIterator, function() {
2152 return this;
2153 }), r2(s, "return", function() {
2154 var e2 = this;
2155 return new Promise(function(t3, n3) {
2156 e2[h].destroy(null, function(e3) {
2157 return e3 ? void n3(e3) : void t3(a(void 0, true));
2158 });
2159 });
2160 }), s), m);
2161 t2.exports = function(e2) {
2162 var t3, n3 = Object.create(b, (t3 = {}, r2(t3, h, { value: e2, writable: true }), r2(t3, c, { value: null, writable: true }), r2(t3, u, { value: null, writable: true }), r2(t3, p, { value: null, writable: true }), r2(t3, f, { value: e2._readableState.endEmitted, writable: true }), r2(t3, _, { value: function(e3, t4) {
2163 var r3 = n3[h].read();
2164 r3 ? (n3[g] = null, n3[c] = null, n3[u] = null, e3(a(r3, false))) : (n3[c] = e3, n3[u] = t4);
2165 }, writable: true }), t3));
2166 return n3[g] = null, l(e2, function(e3) {
2167 if (e3 && "ERR_STREAM_PREMATURE_CLOSE" !== e3.code) {
2168 var t4 = n3[u];
2169 return null !== t4 && (n3[g] = null, n3[c] = null, n3[u] = null, t4(e3)), void (n3[p] = e3);
2170 }
2171 var r3 = n3[c];
2172 null !== r3 && (n3[g] = null, n3[c] = null, n3[u] = null, r3(a(void 0, true))), n3[f] = true;
2173 }), e2.on("readable", i.bind(null, n3)), n3;
2174 };
2175 }).call(this);
2176 }).call(this, e("_process"));
2177 }, { "./end-of-stream": 24, _process: 12 }], 22: [function(e, t2) {
2178 "use strict";
2179 function n2(e2, t3) {
2180 var n3 = Object.keys(e2);
2181 if (Object.getOwnPropertySymbols) {
2182 var r3 = Object.getOwnPropertySymbols(e2);
2183 t3 && (r3 = r3.filter(function(t4) {
2184 return Object.getOwnPropertyDescriptor(e2, t4).enumerable;
2185 })), n3.push.apply(n3, r3);
2186 }
2187 return n3;
2188 }
2189 function r2(e2) {
2190 for (var t3, r3 = 1; r3 < arguments.length; r3++) t3 = null == arguments[r3] ? {} : arguments[r3], r3 % 2 ? n2(Object(t3), true).forEach(function(n3) {
2191 a(e2, n3, t3[n3]);
2192 }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e2, Object.getOwnPropertyDescriptors(t3)) : n2(Object(t3)).forEach(function(n3) {
2193 Object.defineProperty(e2, n3, Object.getOwnPropertyDescriptor(t3, n3));
2194 });
2195 return e2;
2196 }
2197 function a(e2, t3, n3) {
2198 return t3 in e2 ? Object.defineProperty(e2, t3, { value: n3, enumerable: true, configurable: true, writable: true }) : e2[t3] = n3, e2;
2199 }
2200 function o(e2, t3) {
2201 if (!(e2 instanceof t3)) throw new TypeError("Cannot call a class as a function");
2202 }
2203 function i(e2, t3) {
2204 for (var n3, r3 = 0; r3 < t3.length; r3++) n3 = t3[r3], n3.enumerable = n3.enumerable || false, n3.configurable = true, "value" in n3 && (n3.writable = true), Object.defineProperty(e2, n3.key, n3);
2205 }
2206 function d(e2, t3, n3) {
2207 return t3 && i(e2.prototype, t3), n3 && i(e2, n3), e2;
2208 }
2209 function s(e2, t3, n3) {
2210 u.prototype.copy.call(e2, t3, n3);
2211 }
2212 var l = e("buffer"), u = l.Buffer, p = e("util"), f = p.inspect, g = f && f.custom || "inspect";
2213 t2.exports = (function() {
2214 function e2() {
2215 o(this, e2), this.head = null, this.tail = null, this.length = 0;
2216 }
2217 return d(e2, [{ key: "push", value: function(e3) {
2218 var t3 = { data: e3, next: null };
2219 0 < this.length ? this.tail.next = t3 : this.head = t3, this.tail = t3, ++this.length;
2220 } }, { key: "unshift", value: function(e3) {
2221 var t3 = { data: e3, next: this.head };
2222 0 === this.length && (this.tail = t3), this.head = t3, ++this.length;
2223 } }, { key: "shift", value: function() {
2224 if (0 !== this.length) {
2225 var e3 = this.head.data;
2226 return this.head = 1 === this.length ? this.tail = null : this.head.next, --this.length, e3;
2227 }
2228 } }, { key: "clear", value: function() {
2229 this.head = this.tail = null, this.length = 0;
2230 } }, { key: "join", value: function(e3) {
2231 if (0 === this.length) return "";
2232 for (var t3 = this.head, n3 = "" + t3.data; t3 = t3.next; ) n3 += e3 + t3.data;
2233 return n3;
2234 } }, { key: "concat", value: function(e3) {
2235 if (0 === this.length) return u.alloc(0);
2236 for (var t3 = u.allocUnsafe(e3 >>> 0), n3 = this.head, r3 = 0; n3; ) s(n3.data, t3, r3), r3 += n3.data.length, n3 = n3.next;
2237 return t3;
2238 } }, { key: "consume", value: function(e3, t3) {
2239 var n3;
2240 return e3 < this.head.data.length ? (n3 = this.head.data.slice(0, e3), this.head.data = this.head.data.slice(e3)) : e3 === this.head.data.length ? n3 = this.shift() : n3 = t3 ? this._getString(e3) : this._getBuffer(e3), n3;
2241 } }, { key: "first", value: function() {
2242 return this.head.data;
2243 } }, { key: "_getString", value: function(e3) {
2244 var t3 = this.head, r3 = 1, a2 = t3.data;
2245 for (e3 -= a2.length; t3 = t3.next; ) {
2246 var o2 = t3.data, i2 = e3 > o2.length ? o2.length : e3;
2247 if (a2 += i2 === o2.length ? o2 : o2.slice(0, e3), e3 -= i2, 0 === e3) {
2248 i2 === o2.length ? (++r3, this.head = t3.next ? t3.next : this.tail = null) : (this.head = t3, t3.data = o2.slice(i2));
2249 break;
2250 }
2251 ++r3;
2252 }
2253 return this.length -= r3, a2;
2254 } }, { key: "_getBuffer", value: function(e3) {
2255 var t3 = u.allocUnsafe(e3), r3 = this.head, a2 = 1;
2256 for (r3.data.copy(t3), e3 -= r3.data.length; r3 = r3.next; ) {
2257 var o2 = r3.data, i2 = e3 > o2.length ? o2.length : e3;
2258 if (o2.copy(t3, t3.length - e3, 0, i2), e3 -= i2, 0 === e3) {
2259 i2 === o2.length ? (++a2, this.head = r3.next ? r3.next : this.tail = null) : (this.head = r3, r3.data = o2.slice(i2));
2260 break;
2261 }
2262 ++a2;
2263 }
2264 return this.length -= a2, t3;
2265 } }, { key: g, value: function(e3, t3) {
2266 return f(this, r2({}, t3, { depth: 0, customInspect: false }));
2267 } }]), e2;
2268 })();
2269 }, { buffer: 3, util: 2 }], 23: [function(e, t2) {
2270 (function(e2) {
2271 (function() {
2272 "use strict";
2273 function n2(e3, t3) {
2274 a(e3, t3), r2(e3);
2275 }
2276 function r2(e3) {
2277 e3._writableState && !e3._writableState.emitClose || e3._readableState && !e3._readableState.emitClose || e3.emit("close");
2278 }
2279 function a(e3, t3) {
2280 e3.emit("error", t3);
2281 }
2282 t2.exports = { destroy: function(t3, o) {
2283 var i = this, d = this._readableState && this._readableState.destroyed, s = this._writableState && this._writableState.destroyed;
2284 return d || s ? (o ? o(t3) : t3 && (this._writableState ? !this._writableState.errorEmitted && (this._writableState.errorEmitted = true, e2.nextTick(a, this, t3)) : e2.nextTick(a, this, t3)), this) : (this._readableState && (this._readableState.destroyed = true), this._writableState && (this._writableState.destroyed = true), this._destroy(t3 || null, function(t4) {
2285 !o && t4 ? i._writableState ? i._writableState.errorEmitted ? e2.nextTick(r2, i) : (i._writableState.errorEmitted = true, e2.nextTick(n2, i, t4)) : e2.nextTick(n2, i, t4) : o ? (e2.nextTick(r2, i), o(t4)) : e2.nextTick(r2, i);
2286 }), this);
2287 }, undestroy: function() {
2288 this._readableState && (this._readableState.destroyed = false, this._readableState.reading = false, this._readableState.ended = false, this._readableState.endEmitted = false), this._writableState && (this._writableState.destroyed = false, this._writableState.ended = false, this._writableState.ending = false, this._writableState.finalCalled = false, this._writableState.prefinished = false, this._writableState.finished = false, this._writableState.errorEmitted = false);
2289 }, errorOrDestroy: function(e3, t3) {
2290 var n3 = e3._readableState, r3 = e3._writableState;
2291 n3 && n3.autoDestroy || r3 && r3.autoDestroy ? e3.destroy(t3) : e3.emit("error", t3);
2292 } };
2293 }).call(this);
2294 }).call(this, e("_process"));
2295 }, { _process: 12 }], 24: [function(e, t2) {
2296 "use strict";
2297 function n2(e2) {
2298 var t3 = false;
2299 return function() {
2300 if (!t3) {
2301 t3 = true;
2302 for (var n3 = arguments.length, r3 = Array(n3), a2 = 0; a2 < n3; a2++) r3[a2] = arguments[a2];
2303 e2.apply(this, r3);
2304 }
2305 };
2306 }
2307 function r2() {
2308 }
2309 function a(e2) {
2310 return e2.setHeader && "function" == typeof e2.abort;
2311 }
2312 function o(e2, t3, d) {
2313 if ("function" == typeof t3) return o(e2, null, t3);
2314 t3 || (t3 = {}), d = n2(d || r2);
2315 var s = t3.readable || false !== t3.readable && e2.readable, l = t3.writable || false !== t3.writable && e2.writable, c = function() {
2316 e2.writable || p();
2317 }, u = e2._writableState && e2._writableState.finished, p = function() {
2318 l = false, u = true, s || d.call(e2);
2319 }, f = e2._readableState && e2._readableState.endEmitted, g = function() {
2320 s = false, f = true, l || d.call(e2);
2321 }, _ = function(t4) {
2322 d.call(e2, t4);
2323 }, h = function() {
2324 var t4;
2325 return s && !f ? (e2._readableState && e2._readableState.ended || (t4 = new i()), d.call(e2, t4)) : l && !u ? (e2._writableState && e2._writableState.ended || (t4 = new i()), d.call(e2, t4)) : void 0;
2326 }, m = function() {
2327 e2.req.on("finish", p);
2328 };
2329 return a(e2) ? (e2.on("complete", p), e2.on("abort", h), e2.req ? m() : e2.on("request", m)) : l && !e2._writableState && (e2.on("end", c), e2.on("close", c)), e2.on("end", g), e2.on("finish", p), false !== t3.error && e2.on("error", _), e2.on("close", h), function() {
2330 e2.removeListener("complete", p), e2.removeListener("abort", h), e2.removeListener("request", m), e2.req && e2.req.removeListener("finish", p), e2.removeListener("end", c), e2.removeListener("close", c), e2.removeListener("finish", p), e2.removeListener("end", g), e2.removeListener("error", _), e2.removeListener("close", h);
2331 };
2332 }
2333 var i = e("../../../errors").codes.ERR_STREAM_PREMATURE_CLOSE;
2334 t2.exports = o;
2335 }, { "../../../errors": 15 }], 25: [function(e, t2) {
2336 t2.exports = function() {
2337 throw new Error("Readable.from is not available in the browser");
2338 };
2339 }, {}], 26: [function(e, t2) {
2340 "use strict";
2341 function n2(e2) {
2342 var t3 = false;
2343 return function() {
2344 t3 || (t3 = true, e2.apply(void 0, arguments));
2345 };
2346 }
2347 function r2(e2) {
2348 if (e2) throw e2;
2349 }
2350 function a(e2) {
2351 return e2.setHeader && "function" == typeof e2.abort;
2352 }
2353 function o(t3, r3, o2, i2) {
2354 i2 = n2(i2);
2355 var d2 = false;
2356 t3.on("close", function() {
2357 d2 = true;
2358 }), l === void 0 && (l = e("./end-of-stream")), l(t3, { readable: r3, writable: o2 }, function(e2) {
2359 return e2 ? i2(e2) : void (d2 = true, i2());
2360 });
2361 var s2 = false;
2362 return function(e2) {
2363 if (!d2) return s2 ? void 0 : (s2 = true, a(t3) ? t3.abort() : "function" == typeof t3.destroy ? t3.destroy() : void i2(e2 || new p("pipe")));
2364 };
2365 }
2366 function i(e2) {
2367 e2();
2368 }
2369 function d(e2, t3) {
2370 return e2.pipe(t3);
2371 }
2372 function s(e2) {
2373 return e2.length ? "function" == typeof e2[e2.length - 1] ? e2.pop() : r2 : r2;
2374 }
2375 var l, c = e("../../../errors").codes, u = c.ERR_MISSING_ARGS, p = c.ERR_STREAM_DESTROYED;
2376 t2.exports = function() {
2377 for (var e2 = arguments.length, t3 = Array(e2), n3 = 0; n3 < e2; n3++) t3[n3] = arguments[n3];
2378 var r3 = s(t3);
2379 if (Array.isArray(t3[0]) && (t3 = t3[0]), 2 > t3.length) throw new u("streams");
2380 var a2, l2 = t3.map(function(e3, n4) {
2381 var d2 = n4 < t3.length - 1;
2382 return o(e3, d2, 0 < n4, function(e4) {
2383 a2 || (a2 = e4), e4 && l2.forEach(i), d2 || (l2.forEach(i), r3(a2));
2384 });
2385 });
2386 return t3.reduce(d);
2387 };
2388 }, { "../../../errors": 15, "./end-of-stream": 24 }], 27: [function(e, n2) {
2389 "use strict";
2390 function r2(e2, t2, n3) {
2391 return null == e2.highWaterMark ? t2 ? e2[n3] : null : e2.highWaterMark;
2392 }
2393 var a = e("../../../errors").codes.ERR_INVALID_OPT_VALUE;
2394 n2.exports = { getHighWaterMark: function(e2, n3, o, i) {
2395 var d = r2(n3, i, o);
2396 if (null != d) {
2397 if (!(isFinite(d) && t(d) === d) || 0 > d) {
2398 var s = i ? o : "highWaterMark";
2399 throw new a(s, d);
2400 }
2401 return t(d);
2402 }
2403 return e2.objectMode ? 16 : 16384;
2404 } };
2405 }, { "../../../errors": 15 }], 28: [function(e, t2) {
2406 t2.exports = e("events").EventEmitter;
2407 }, { events: 7 }], 29: [function(e, t2, n2) {
2408 n2 = t2.exports = e("./lib/_stream_readable.js"), n2.Stream = n2, n2.Readable = n2, n2.Writable = e("./lib/_stream_writable.js"), n2.Duplex = e("./lib/_stream_duplex.js"), n2.Transform = e("./lib/_stream_transform.js"), n2.PassThrough = e("./lib/_stream_passthrough.js"), n2.finished = e("./lib/internal/streams/end-of-stream.js"), n2.pipeline = e("./lib/internal/streams/pipeline.js");
2409 }, { "./lib/_stream_duplex.js": 16, "./lib/_stream_passthrough.js": 17, "./lib/_stream_readable.js": 18, "./lib/_stream_transform.js": 19, "./lib/_stream_writable.js": 20, "./lib/internal/streams/end-of-stream.js": 24, "./lib/internal/streams/pipeline.js": 26 }], 30: [function(e, t2, n2) {
2410 function r2(e2, t3) {
2411 for (var n3 in e2) t3[n3] = e2[n3];
2412 }
2413 function a(e2, t3, n3) {
2414 return i(e2, t3, n3);
2415 }
2416 var o = e("buffer"), i = o.Buffer;
2417 i.from && i.alloc && i.allocUnsafe && i.allocUnsafeSlow ? t2.exports = o : (r2(o, n2), n2.Buffer = a), a.prototype = Object.create(i.prototype), r2(i, a), a.from = function(e2, t3, n3) {
2418 if ("number" == typeof e2) throw new TypeError("Argument must not be a number");
2419 return i(e2, t3, n3);
2420 }, a.alloc = function(e2, t3, n3) {
2421 if ("number" != typeof e2) throw new TypeError("Argument must be a number");
2422 var r3 = i(e2);
2423 return void 0 === t3 ? r3.fill(0) : "string" == typeof n3 ? r3.fill(t3, n3) : r3.fill(t3), r3;
2424 }, a.allocUnsafe = function(e2) {
2425 if ("number" != typeof e2) throw new TypeError("Argument must be a number");
2426 return i(e2);
2427 }, a.allocUnsafeSlow = function(e2) {
2428 if ("number" != typeof e2) throw new TypeError("Argument must be a number");
2429 return o.SlowBuffer(e2);
2430 };
2431 }, { buffer: 3 }], 31: [function(e, t2, n2) {
2432 "use strict";
2433 function r2(e2) {
2434 if (!e2) return "utf8";
2435 for (var t3; ; ) switch (e2) {
2436 case "utf8":
2437 case "utf-8":
2438 return "utf8";
2439 case "ucs2":
2440 case "ucs-2":
2441 case "utf16le":
2442 case "utf-16le":
2443 return "utf16le";
2444 case "latin1":
2445 case "binary":
2446 return "latin1";
2447 case "base64":
2448 case "ascii":
2449 case "hex":
2450 return e2;
2451 default:
2452 if (t3) return;
2453 e2 = ("" + e2).toLowerCase(), t3 = true;
2454 }
2455 }
2456 function a(e2) {
2457 var t3 = r2(e2);
2458 if ("string" != typeof t3 && (m.isEncoding === b || !b(e2))) throw new Error("Unknown encoding: " + e2);
2459 return t3 || e2;
2460 }
2461 function o(e2) {
2462 this.encoding = a(e2);
2463 var t3;
2464 switch (this.encoding) {
2465 case "utf16le":
2466 this.text = u, this.end = p, t3 = 4;
2467 break;
2468 case "utf8":
2469 this.fillLast = c, t3 = 4;
2470 break;
2471 case "base64":
2472 this.text = f, this.end = g, t3 = 3;
2473 break;
2474 default:
2475 return this.write = _, void (this.end = h);
2476 }
2477 this.lastNeed = 0, this.lastTotal = 0, this.lastChar = m.allocUnsafe(t3);
2478 }
2479 function d(e2) {
2480 if (127 >= e2) return 0;
2481 return 6 == e2 >> 5 ? 2 : 14 == e2 >> 4 ? 3 : 30 == e2 >> 3 ? 4 : 2 == e2 >> 6 ? -1 : -2;
2482 }
2483 function s(e2, t3, n3) {
2484 var r3 = t3.length - 1;
2485 if (r3 < n3) return 0;
2486 var a2 = d(t3[r3]);
2487 return 0 <= a2 ? (0 < a2 && (e2.lastNeed = a2 - 1), a2) : --r3 < n3 || -2 === a2 ? 0 : (a2 = d(t3[r3]), 0 <= a2) ? (0 < a2 && (e2.lastNeed = a2 - 2), a2) : --r3 < n3 || -2 === a2 ? 0 : (a2 = d(t3[r3]), 0 <= a2 ? (0 < a2 && (2 === a2 ? a2 = 0 : e2.lastNeed = a2 - 3), a2) : 0);
2488 }
2489 function l(e2, t3) {
2490 if (128 != (192 & t3[0])) return e2.lastNeed = 0, "\uFFFD";
2491 if (1 < e2.lastNeed && 1 < t3.length) {
2492 if (128 != (192 & t3[1])) return e2.lastNeed = 1, "\uFFFD";
2493 if (2 < e2.lastNeed && 2 < t3.length && 128 != (192 & t3[2])) return e2.lastNeed = 2, "\uFFFD";
2494 }
2495 }
2496 function c(e2) {
2497 var t3 = this.lastTotal - this.lastNeed, n3 = l(this, e2, t3);
2498 return void 0 === n3 ? this.lastNeed <= e2.length ? (e2.copy(this.lastChar, t3, 0, this.lastNeed), this.lastChar.toString(this.encoding, 0, this.lastTotal)) : void (e2.copy(this.lastChar, t3, 0, e2.length), this.lastNeed -= e2.length) : n3;
2499 }
2500 function u(e2, t3) {
2501 if (0 == (e2.length - t3) % 2) {
2502 var n3 = e2.toString("utf16le", t3);
2503 if (n3) {
2504 var r3 = n3.charCodeAt(n3.length - 1);
2505 if (55296 <= r3 && 56319 >= r3) return this.lastNeed = 2, this.lastTotal = 4, this.lastChar[0] = e2[e2.length - 2], this.lastChar[1] = e2[e2.length - 1], n3.slice(0, -1);
2506 }
2507 return n3;
2508 }
2509 return this.lastNeed = 1, this.lastTotal = 2, this.lastChar[0] = e2[e2.length - 1], e2.toString("utf16le", t3, e2.length - 1);
2510 }
2511 function p(e2) {
2512 var t3 = e2 && e2.length ? this.write(e2) : "";
2513 if (this.lastNeed) {
2514 var n3 = this.lastTotal - this.lastNeed;
2515 return t3 + this.lastChar.toString("utf16le", 0, n3);
2516 }
2517 return t3;
2518 }
2519 function f(e2, t3) {
2520 var r3 = (e2.length - t3) % 3;
2521 return 0 == r3 ? e2.toString("base64", t3) : (this.lastNeed = 3 - r3, this.lastTotal = 3, 1 == r3 ? this.lastChar[0] = e2[e2.length - 1] : (this.lastChar[0] = e2[e2.length - 2], this.lastChar[1] = e2[e2.length - 1]), e2.toString("base64", t3, e2.length - r3));
2522 }
2523 function g(e2) {
2524 var t3 = e2 && e2.length ? this.write(e2) : "";
2525 return this.lastNeed ? t3 + this.lastChar.toString("base64", 0, 3 - this.lastNeed) : t3;
2526 }
2527 function _(e2) {
2528 return e2.toString(this.encoding);
2529 }
2530 function h(e2) {
2531 return e2 && e2.length ? this.write(e2) : "";
2532 }
2533 var m = e("safe-buffer").Buffer, b = m.isEncoding || function(e2) {
2534 switch (e2 = "" + e2, e2 && e2.toLowerCase()) {
2535 case "hex":
2536 case "utf8":
2537 case "utf-8":
2538 case "ascii":
2539 case "binary":
2540 case "base64":
2541 case "ucs2":
2542 case "ucs-2":
2543 case "utf16le":
2544 case "utf-16le":
2545 case "raw":
2546 return true;
2547 default:
2548 return false;
2549 }
2550 };
2551 n2.StringDecoder = o, o.prototype.write = function(e2) {
2552 if (0 === e2.length) return "";
2553 var t3, n3;
2554 if (this.lastNeed) {
2555 if (t3 = this.fillLast(e2), void 0 === t3) return "";
2556 n3 = this.lastNeed, this.lastNeed = 0;
2557 } else n3 = 0;
2558 return n3 < e2.length ? t3 ? t3 + this.text(e2, n3) : this.text(e2, n3) : t3 || "";
2559 }, o.prototype.end = function(e2) {
2560 var t3 = e2 && e2.length ? this.write(e2) : "";
2561 return this.lastNeed ? t3 + "\uFFFD" : t3;
2562 }, o.prototype.text = function(e2, t3) {
2563 var n3 = s(this, e2, t3);
2564 if (!this.lastNeed) return e2.toString("utf8", t3);
2565 this.lastTotal = n3;
2566 var r3 = e2.length - (n3 - this.lastNeed);
2567 return e2.copy(this.lastChar, 0, r3), e2.toString("utf8", t3, r3);
2568 }, o.prototype.fillLast = function(e2) {
2569 return this.lastNeed <= e2.length ? (e2.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed), this.lastChar.toString(this.encoding, 0, this.lastTotal)) : void (e2.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, e2.length), this.lastNeed -= e2.length);
2570 };
2571 }, { "safe-buffer": 30 }], 32: [function(e, t2) {
2572 (function(e2) {
2573 (function() {
2574 function n2(t3) {
2575 try {
2576 if (!e2.localStorage) return false;
2577 } catch (e3) {
2578 return false;
2579 }
2580 var n3 = e2.localStorage[t3];
2581 return null != n3 && "true" === (n3 + "").toLowerCase();
2582 }
2583 t2.exports = function(e3, t3) {
2584 function r2() {
2585 if (!a) {
2586 if (n2("throwDeprecation")) throw new Error(t3);
2587 else n2("traceDeprecation") ? console.trace(t3) : console.warn(t3);
2588 a = true;
2589 }
2590 return e3.apply(this, arguments);
2591 }
2592 if (n2("noDeprecation")) return e3;
2593 var a = false;
2594 return r2;
2595 };
2596 }).call(this);
2597 }).call(this, "undefined" == typeof global ? "undefined" == typeof self ? "undefined" == typeof window ? {} : window : self : global);
2598 }, {}], "/": [function(e, t2) {
2599 function n2(e2) {
2600 return e2.replace(/a=ice-options:trickle\s\n/g, "");
2601 }
2602 function r2(e2) {
2603 console.warn(e2);
2604 }
2605 const a = e("debug")("simple-peer"), o = e("get-browser-rtc"), i = e("randombytes"), d = e("readable-stream"), s = e("queue-microtask"), l = e("err-code"), { Buffer: c } = e("buffer"), u = 65536;
2606 class p extends d.Duplex {
2607 constructor(e2) {
2608 if (e2 = Object.assign({ allowHalfOpen: false }, e2), super(e2), this._id = i(4).toString("hex").slice(0, 7), this._debug("new peer %o", e2), this.channelName = e2.initiator ? e2.channelName || i(20).toString("hex") : null, this.initiator = e2.initiator || false, this.channelConfig = e2.channelConfig || p.channelConfig, this.channelNegotiated = this.channelConfig.negotiated, this.config = Object.assign({}, p.config, e2.config), this.offerOptions = e2.offerOptions || {}, this.answerOptions = e2.answerOptions || {}, this.sdpTransform = e2.sdpTransform || ((e3) => e3), this.streams = e2.streams || (e2.stream ? [e2.stream] : []), this.trickle = void 0 === e2.trickle || e2.trickle, this.allowHalfTrickle = void 0 !== e2.allowHalfTrickle && e2.allowHalfTrickle, this.iceCompleteTimeout = e2.iceCompleteTimeout || 5e3, this.destroyed = false, this.destroying = false, this._connected = false, this.remoteAddress = void 0, this.remoteFamily = void 0, this.remotePort = void 0, this.localAddress = void 0, this.localFamily = void 0, this.localPort = void 0, this._wrtc = e2.wrtc && "object" == typeof e2.wrtc ? e2.wrtc : o(), !this._wrtc) if ("undefined" == typeof window) throw l(new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"), "ERR_WEBRTC_SUPPORT");
2609 else throw l(new Error("No WebRTC support: Not a supported browser"), "ERR_WEBRTC_SUPPORT");
2610 this._pcReady = false, this._channelReady = false, this._iceComplete = false, this._iceCompleteTimer = null, this._channel = null, this._pendingCandidates = [], this._isNegotiating = false, this._firstNegotiation = true, this._batchedNegotiation = false, this._queuedNegotiation = false, this._sendersAwaitingStable = [], this._senderMap = /* @__PURE__ */ new Map(), this._closingInterval = null, this._remoteTracks = [], this._remoteStreams = [], this._chunk = null, this._cb = null, this._interval = null;
2611 try {
2612 this._pc = new this._wrtc.RTCPeerConnection(this.config);
2613 } catch (e3) {
2614 return void this.destroy(l(e3, "ERR_PC_CONSTRUCTOR"));
2615 }
2616 this._isReactNativeWebrtc = "number" == typeof this._pc._peerConnectionId, this._pc.oniceconnectionstatechange = () => {
2617 this._onIceStateChange();
2618 }, this._pc.onicegatheringstatechange = () => {
2619 this._onIceStateChange();
2620 }, this._pc.onconnectionstatechange = () => {
2621 this._onConnectionStateChange();
2622 }, this._pc.onsignalingstatechange = () => {
2623 this._onSignalingStateChange();
2624 }, this._pc.onicecandidate = (e3) => {
2625 this._onIceCandidate(e3);
2626 }, "object" == typeof this._pc.peerIdentity && this._pc.peerIdentity.catch((e3) => {
2627 this.destroy(l(e3, "ERR_PC_PEER_IDENTITY"));
2628 }), this.initiator || this.channelNegotiated ? this._setupData({ channel: this._pc.createDataChannel(this.channelName, this.channelConfig) }) : this._pc.ondatachannel = (e3) => {
2629 this._setupData(e3);
2630 }, this.streams && this.streams.forEach((e3) => {
2631 this.addStream(e3);
2632 }), this._pc.ontrack = (e3) => {
2633 this._onTrack(e3);
2634 }, this._debug("initial negotiation"), this._needsNegotiation(), this._onFinishBound = () => {
2635 this._onFinish();
2636 }, this.once("finish", this._onFinishBound);
2637 }
2638 get bufferSize() {
2639 return this._channel && this._channel.bufferedAmount || 0;
2640 }
2641 get connected() {
2642 return this._connected && "open" === this._channel.readyState;
2643 }
2644 address() {
2645 return { port: this.localPort, family: this.localFamily, address: this.localAddress };
2646 }
2647 signal(e2) {
2648 if (!this.destroying) {
2649 if (this.destroyed) throw l(new Error("cannot signal after peer is destroyed"), "ERR_DESTROYED");
2650 if ("string" == typeof e2) try {
2651 e2 = JSON.parse(e2);
2652 } catch (t3) {
2653 e2 = {};
2654 }
2655 this._debug("signal()"), e2.renegotiate && this.initiator && (this._debug("got request to renegotiate"), this._needsNegotiation()), e2.transceiverRequest && this.initiator && (this._debug("got request for transceiver"), this.addTransceiver(e2.transceiverRequest.kind, e2.transceiverRequest.init)), e2.candidate && (this._pc.remoteDescription && this._pc.remoteDescription.type ? this._addIceCandidate(e2.candidate) : this._pendingCandidates.push(e2.candidate)), e2.sdp && this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(e2)).then(() => {
2656 this.destroyed || (this._pendingCandidates.forEach((e3) => {
2657 this._addIceCandidate(e3);
2658 }), this._pendingCandidates = [], "offer" === this._pc.remoteDescription.type && this._createAnswer());
2659 }).catch((e3) => {
2660 this.destroy(l(e3, "ERR_SET_REMOTE_DESCRIPTION"));
2661 }), e2.sdp || e2.candidate || e2.renegotiate || e2.transceiverRequest || this.destroy(l(new Error("signal() called with invalid signal data"), "ERR_SIGNALING"));
2662 }
2663 }
2664 _addIceCandidate(e2) {
2665 const t3 = new this._wrtc.RTCIceCandidate(e2);
2666 this._pc.addIceCandidate(t3).catch((e3) => {
2667 !t3.address || t3.address.endsWith(".local") ? r2("Ignoring unsupported ICE candidate.") : this.destroy(l(e3, "ERR_ADD_ICE_CANDIDATE"));
2668 });
2669 }
2670 send(e2) {
2671 if (!this.destroying) {
2672 if (this.destroyed) throw l(new Error("cannot send after peer is destroyed"), "ERR_DESTROYED");
2673 this._channel.send(e2);
2674 }
2675 }
2676 addTransceiver(e2, t3) {
2677 if (!this.destroying) {
2678 if (this.destroyed) throw l(new Error("cannot addTransceiver after peer is destroyed"), "ERR_DESTROYED");
2679 if (this._debug("addTransceiver()"), this.initiator) try {
2680 this._pc.addTransceiver(e2, t3), this._needsNegotiation();
2681 } catch (e3) {
2682 this.destroy(l(e3, "ERR_ADD_TRANSCEIVER"));
2683 }
2684 else this.emit("signal", { type: "transceiverRequest", transceiverRequest: { kind: e2, init: t3 } });
2685 }
2686 }
2687 addStream(e2) {
2688 if (!this.destroying) {
2689 if (this.destroyed) throw l(new Error("cannot addStream after peer is destroyed"), "ERR_DESTROYED");
2690 this._debug("addStream()"), e2.getTracks().forEach((t3) => {
2691 this.addTrack(t3, e2);
2692 });
2693 }
2694 }
2695 addTrack(e2, t3) {
2696 if (this.destroying) return;
2697 if (this.destroyed) throw l(new Error("cannot addTrack after peer is destroyed"), "ERR_DESTROYED");
2698 this._debug("addTrack()");
2699 const n3 = this._senderMap.get(e2) || /* @__PURE__ */ new Map();
2700 let r3 = n3.get(t3);
2701 if (!r3) r3 = this._pc.addTrack(e2, t3), n3.set(t3, r3), this._senderMap.set(e2, n3), this._needsNegotiation();
2702 else if (r3.removed) throw l(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."), "ERR_SENDER_REMOVED");
2703 else throw l(new Error("Track has already been added to that stream."), "ERR_SENDER_ALREADY_ADDED");
2704 }
2705 replaceTrack(e2, t3, n3) {
2706 if (this.destroying) return;
2707 if (this.destroyed) throw l(new Error("cannot replaceTrack after peer is destroyed"), "ERR_DESTROYED");
2708 this._debug("replaceTrack()");
2709 const r3 = this._senderMap.get(e2), a2 = r3 ? r3.get(n3) : null;
2710 if (!a2) throw l(new Error("Cannot replace track that was never added."), "ERR_TRACK_NOT_ADDED");
2711 t3 && this._senderMap.set(t3, r3), null == a2.replaceTrack ? this.destroy(l(new Error("replaceTrack is not supported in this browser"), "ERR_UNSUPPORTED_REPLACETRACK")) : a2.replaceTrack(t3);
2712 }
2713 removeTrack(e2, t3) {
2714 if (this.destroying) return;
2715 if (this.destroyed) throw l(new Error("cannot removeTrack after peer is destroyed"), "ERR_DESTROYED");
2716 this._debug("removeSender()");
2717 const n3 = this._senderMap.get(e2), r3 = n3 ? n3.get(t3) : null;
2718 if (!r3) throw l(new Error("Cannot remove track that was never added."), "ERR_TRACK_NOT_ADDED");
2719 try {
2720 r3.removed = true, this._pc.removeTrack(r3);
2721 } catch (e3) {
2722 "NS_ERROR_UNEXPECTED" === e3.name ? this._sendersAwaitingStable.push(r3) : this.destroy(l(e3, "ERR_REMOVE_TRACK"));
2723 }
2724 this._needsNegotiation();
2725 }
2726 removeStream(e2) {
2727 if (!this.destroying) {
2728 if (this.destroyed) throw l(new Error("cannot removeStream after peer is destroyed"), "ERR_DESTROYED");
2729 this._debug("removeSenders()"), e2.getTracks().forEach((t3) => {
2730 this.removeTrack(t3, e2);
2731 });
2732 }
2733 }
2734 _needsNegotiation() {
2735 this._debug("_needsNegotiation"), this._batchedNegotiation || (this._batchedNegotiation = true, s(() => {
2736 this._batchedNegotiation = false, this.initiator || !this._firstNegotiation ? (this._debug("starting batched negotiation"), this.negotiate()) : this._debug("non-initiator initial negotiation request discarded"), this._firstNegotiation = false;
2737 }));
2738 }
2739 negotiate() {
2740 if (!this.destroying) {
2741 if (this.destroyed) throw l(new Error("cannot negotiate after peer is destroyed"), "ERR_DESTROYED");
2742 this.initiator ? this._isNegotiating ? (this._queuedNegotiation = true, this._debug("already negotiating, queueing")) : (this._debug("start negotiation"), setTimeout(() => {
2743 this._createOffer();
2744 }, 0)) : this._isNegotiating ? (this._queuedNegotiation = true, this._debug("already negotiating, queueing")) : (this._debug("requesting negotiation from initiator"), this.emit("signal", { type: "renegotiate", renegotiate: true })), this._isNegotiating = true;
2745 }
2746 }
2747 destroy(e2) {
2748 this._destroy(e2, () => {
2749 });
2750 }
2751 _destroy(e2, t3) {
2752 this.destroyed || this.destroying || (this.destroying = true, this._debug("destroying (error: %s)", e2 && (e2.message || e2)), s(() => {
2753 if (this.destroyed = true, this.destroying = false, this._debug("destroy (error: %s)", e2 && (e2.message || e2)), this.readable = this.writable = false, this._readableState.ended || this.push(null), this._writableState.finished || this.end(), this._connected = false, this._pcReady = false, this._channelReady = false, this._remoteTracks = null, this._remoteStreams = null, this._senderMap = null, clearInterval(this._closingInterval), this._closingInterval = null, clearInterval(this._interval), this._interval = null, this._chunk = null, this._cb = null, this._onFinishBound && this.removeListener("finish", this._onFinishBound), this._onFinishBound = null, this._channel) {
2754 try {
2755 this._channel.close();
2756 } catch (e3) {
2757 }
2758 this._channel.onmessage = null, this._channel.onopen = null, this._channel.onclose = null, this._channel.onerror = null;
2759 }
2760 if (this._pc) {
2761 try {
2762 this._pc.close();
2763 } catch (e3) {
2764 }
2765 this._pc.oniceconnectionstatechange = null, this._pc.onicegatheringstatechange = null, this._pc.onsignalingstatechange = null, this._pc.onicecandidate = null, this._pc.ontrack = null, this._pc.ondatachannel = null;
2766 }
2767 this._pc = null, this._channel = null, e2 && this.emit("error", e2), this.emit("close"), t3();
2768 }));
2769 }
2770 _setupData(e2) {
2771 if (!e2.channel) return this.destroy(l(new Error("Data channel event is missing `channel` property"), "ERR_DATA_CHANNEL"));
2772 this._channel = e2.channel, this._channel.binaryType = "arraybuffer", "number" == typeof this._channel.bufferedAmountLowThreshold && (this._channel.bufferedAmountLowThreshold = u), this.channelName = this._channel.label, this._channel.onmessage = (e3) => {
2773 this._onChannelMessage(e3);
2774 }, this._channel.onbufferedamountlow = () => {
2775 this._onChannelBufferedAmountLow();
2776 }, this._channel.onopen = () => {
2777 this._onChannelOpen();
2778 }, this._channel.onclose = () => {
2779 this._onChannelClose();
2780 }, this._channel.onerror = (e3) => {
2781 const t4 = e3.error instanceof Error ? e3.error : new Error(`Datachannel error: ${e3.message} ${e3.filename}:${e3.lineno}:${e3.colno}`);
2782 this.destroy(l(t4, "ERR_DATA_CHANNEL"));
2783 };
2784 let t3 = false;
2785 this._closingInterval = setInterval(() => {
2786 this._channel && "closing" === this._channel.readyState ? (t3 && this._onChannelClose(), t3 = true) : t3 = false;
2787 }, 5e3);
2788 }
2789 _read() {
2790 }
2791 _write(e2, t3, n3) {
2792 if (this.destroyed) return n3(l(new Error("cannot write after peer is destroyed"), "ERR_DATA_CHANNEL"));
2793 if (this._connected) {
2794 try {
2795 this.send(e2);
2796 } catch (e3) {
2797 return this.destroy(l(e3, "ERR_DATA_CHANNEL"));
2798 }
2799 this._channel.bufferedAmount > u ? (this._debug("start backpressure: bufferedAmount %d", this._channel.bufferedAmount), this._cb = n3) : n3(null);
2800 } else this._debug("write before connect"), this._chunk = e2, this._cb = n3;
2801 }
2802 _onFinish() {
2803 if (!this.destroyed) {
2804 const e2 = () => {
2805 setTimeout(() => this.destroy(), 1e3);
2806 };
2807 this._connected ? e2() : this.once("connect", e2);
2808 }
2809 }
2810 _startIceCompleteTimeout() {
2811 this.destroyed || this._iceCompleteTimer || (this._debug("started iceComplete timeout"), this._iceCompleteTimer = setTimeout(() => {
2812 this._iceComplete || (this._iceComplete = true, this._debug("iceComplete timeout completed"), this.emit("iceTimeout"), this.emit("_iceComplete"));
2813 }, this.iceCompleteTimeout));
2814 }
2815 _createOffer() {
2816 this.destroyed || this._pc.createOffer(this.offerOptions).then((e2) => {
2817 if (this.destroyed) return;
2818 this.trickle || this.allowHalfTrickle || (e2.sdp = n2(e2.sdp)), e2.sdp = this.sdpTransform(e2.sdp);
2819 const t3 = () => {
2820 if (!this.destroyed) {
2821 const t4 = this._pc.localDescription || e2;
2822 this._debug("signal"), this.emit("signal", { type: t4.type, sdp: t4.sdp });
2823 }
2824 };
2825 this._pc.setLocalDescription(e2).then(() => {
2826 this._debug("createOffer success"), this.destroyed || (this.trickle || this._iceComplete ? t3() : this.once("_iceComplete", t3));
2827 }).catch((e3) => {
2828 this.destroy(l(e3, "ERR_SET_LOCAL_DESCRIPTION"));
2829 });
2830 }).catch((e2) => {
2831 this.destroy(l(e2, "ERR_CREATE_OFFER"));
2832 });
2833 }
2834 _requestMissingTransceivers() {
2835 this._pc.getTransceivers && this._pc.getTransceivers().forEach((e2) => {
2836 e2.mid || !e2.sender.track || e2.requested || (e2.requested = true, this.addTransceiver(e2.sender.track.kind));
2837 });
2838 }
2839 _createAnswer() {
2840 this.destroyed || this._pc.createAnswer(this.answerOptions).then((e2) => {
2841 if (this.destroyed) return;
2842 this.trickle || this.allowHalfTrickle || (e2.sdp = n2(e2.sdp)), e2.sdp = this.sdpTransform(e2.sdp);
2843 const t3 = () => {
2844 if (!this.destroyed) {
2845 const t4 = this._pc.localDescription || e2;
2846 this._debug("signal"), this.emit("signal", { type: t4.type, sdp: t4.sdp }), this.initiator || this._requestMissingTransceivers();
2847 }
2848 };
2849 this._pc.setLocalDescription(e2).then(() => {
2850 this.destroyed || (this.trickle || this._iceComplete ? t3() : this.once("_iceComplete", t3));
2851 }).catch((e3) => {
2852 this.destroy(l(e3, "ERR_SET_LOCAL_DESCRIPTION"));
2853 });
2854 }).catch((e2) => {
2855 this.destroy(l(e2, "ERR_CREATE_ANSWER"));
2856 });
2857 }
2858 _onConnectionStateChange() {
2859 this.destroyed || "failed" === this._pc.connectionState && this.destroy(l(new Error("Connection failed."), "ERR_CONNECTION_FAILURE"));
2860 }
2861 _onIceStateChange() {
2862 if (this.destroyed) return;
2863 const e2 = this._pc.iceConnectionState, t3 = this._pc.iceGatheringState;
2864 this._debug("iceStateChange (connection: %s) (gathering: %s)", e2, t3), this.emit("iceStateChange", e2, t3), ("connected" === e2 || "completed" === e2) && (this._pcReady = true, this._maybeReady()), "failed" === e2 && this.destroy(l(new Error("Ice connection failed."), "ERR_ICE_CONNECTION_FAILURE")), "closed" === e2 && this.destroy(l(new Error("Ice connection closed."), "ERR_ICE_CONNECTION_CLOSED"));
2865 }
2866 getStats(e2) {
2867 const t3 = (e3) => ("[object Array]" === Object.prototype.toString.call(e3.values) && e3.values.forEach((t4) => {
2868 Object.assign(e3, t4);
2869 }), e3);
2870 0 === this._pc.getStats.length || this._isReactNativeWebrtc ? this._pc.getStats().then((n3) => {
2871 const r3 = [];
2872 n3.forEach((e3) => {
2873 r3.push(t3(e3));
2874 }), e2(null, r3);
2875 }, (t4) => e2(t4)) : 0 < this._pc.getStats.length ? this._pc.getStats((n3) => {
2876 if (this.destroyed) return;
2877 const r3 = [];
2878 n3.result().forEach((e3) => {
2879 const n4 = {};
2880 e3.names().forEach((t4) => {
2881 n4[t4] = e3.stat(t4);
2882 }), n4.id = e3.id, n4.type = e3.type, n4.timestamp = e3.timestamp, r3.push(t3(n4));
2883 }), e2(null, r3);
2884 }, (t4) => e2(t4)) : e2(null, []);
2885 }
2886 _maybeReady() {
2887 if (this._debug("maybeReady pc %s channel %s", this._pcReady, this._channelReady), this._connected || this._connecting || !this._pcReady || !this._channelReady) return;
2888 this._connecting = true;
2889 const e2 = () => {
2890 this.destroyed || this.getStats((t3, n3) => {
2891 if (this.destroyed) return;
2892 t3 && (n3 = []);
2893 const r3 = {}, a2 = {}, o2 = {};
2894 let i2 = false;
2895 n3.forEach((e3) => {
2896 ("remotecandidate" === e3.type || "remote-candidate" === e3.type) && (r3[e3.id] = e3), ("localcandidate" === e3.type || "local-candidate" === e3.type) && (a2[e3.id] = e3), ("candidatepair" === e3.type || "candidate-pair" === e3.type) && (o2[e3.id] = e3);
2897 });
2898 const d2 = (e3) => {
2899 i2 = true;
2900 let t4 = a2[e3.localCandidateId];
2901 t4 && (t4.ip || t4.address) ? (this.localAddress = t4.ip || t4.address, this.localPort = +t4.port) : t4 && t4.ipAddress ? (this.localAddress = t4.ipAddress, this.localPort = +t4.portNumber) : "string" == typeof e3.googLocalAddress && (t4 = e3.googLocalAddress.split(":"), this.localAddress = t4[0], this.localPort = +t4[1]), this.localAddress && (this.localFamily = this.localAddress.includes(":") ? "IPv6" : "IPv4");
2902 let n4 = r3[e3.remoteCandidateId];
2903 n4 && (n4.ip || n4.address) ? (this.remoteAddress = n4.ip || n4.address, this.remotePort = +n4.port) : n4 && n4.ipAddress ? (this.remoteAddress = n4.ipAddress, this.remotePort = +n4.portNumber) : "string" == typeof e3.googRemoteAddress && (n4 = e3.googRemoteAddress.split(":"), this.remoteAddress = n4[0], this.remotePort = +n4[1]), this.remoteAddress && (this.remoteFamily = this.remoteAddress.includes(":") ? "IPv6" : "IPv4"), this._debug("connect local: %s:%s remote: %s:%s", this.localAddress, this.localPort, this.remoteAddress, this.remotePort);
2904 };
2905 if (n3.forEach((e3) => {
2906 "transport" === e3.type && e3.selectedCandidatePairId && d2(o2[e3.selectedCandidatePairId]), ("googCandidatePair" === e3.type && "true" === e3.googActiveConnection || ("candidatepair" === e3.type || "candidate-pair" === e3.type) && e3.selected) && d2(e3);
2907 }), !i2 && (!Object.keys(o2).length || Object.keys(a2).length)) return void setTimeout(e2, 100);
2908 if (this._connecting = false, this._connected = true, this._chunk) {
2909 try {
2910 this.send(this._chunk);
2911 } catch (e4) {
2912 return this.destroy(l(e4, "ERR_DATA_CHANNEL"));
2913 }
2914 this._chunk = null, this._debug('sent chunk from "write before connect"');
2915 const e3 = this._cb;
2916 this._cb = null, e3(null);
2917 }
2918 "number" != typeof this._channel.bufferedAmountLowThreshold && (this._interval = setInterval(() => this._onInterval(), 150), this._interval.unref && this._interval.unref()), this._debug("connect"), this.emit("connect");
2919 });
2920 };
2921 e2();
2922 }
2923 _onInterval() {
2924 this._cb && this._channel && !(this._channel.bufferedAmount > u) && this._onChannelBufferedAmountLow();
2925 }
2926 _onSignalingStateChange() {
2927 this.destroyed || ("stable" === this._pc.signalingState && (this._isNegotiating = false, this._debug("flushing sender queue", this._sendersAwaitingStable), this._sendersAwaitingStable.forEach((e2) => {
2928 this._pc.removeTrack(e2), this._queuedNegotiation = true;
2929 }), this._sendersAwaitingStable = [], this._queuedNegotiation ? (this._debug("flushing negotiation queue"), this._queuedNegotiation = false, this._needsNegotiation()) : (this._debug("negotiated"), this.emit("negotiated"))), this._debug("signalingStateChange %s", this._pc.signalingState), this.emit("signalingStateChange", this._pc.signalingState));
2930 }
2931 _onIceCandidate(e2) {
2932 this.destroyed || (e2.candidate && this.trickle ? this.emit("signal", { type: "candidate", candidate: { candidate: e2.candidate.candidate, sdpMLineIndex: e2.candidate.sdpMLineIndex, sdpMid: e2.candidate.sdpMid } }) : !e2.candidate && !this._iceComplete && (this._iceComplete = true, this.emit("_iceComplete")), e2.candidate && this._startIceCompleteTimeout());
2933 }
2934 _onChannelMessage(e2) {
2935 if (this.destroyed) return;
2936 let t3 = e2.data;
2937 t3 instanceof ArrayBuffer && (t3 = c.from(t3)), this.push(t3);
2938 }
2939 _onChannelBufferedAmountLow() {
2940 if (!this.destroyed && this._cb) {
2941 this._debug("ending backpressure: bufferedAmount %d", this._channel.bufferedAmount);
2942 const e2 = this._cb;
2943 this._cb = null, e2(null);
2944 }
2945 }
2946 _onChannelOpen() {
2947 this._connected || this.destroyed || (this._debug("on channel open"), this._channelReady = true, this._maybeReady());
2948 }
2949 _onChannelClose() {
2950 this.destroyed || (this._debug("on channel close"), this.destroy());
2951 }
2952 _onTrack(e2) {
2953 this.destroyed || e2.streams.forEach((t3) => {
2954 this._debug("on track"), this.emit("track", e2.track, t3), this._remoteTracks.push({ track: e2.track, stream: t3 }), this._remoteStreams.some((e3) => e3.id === t3.id) || (this._remoteStreams.push(t3), s(() => {
2955 this._debug("on stream"), this.emit("stream", t3);
2956 }));
2957 });
2958 }
2959 _debug() {
2960 const e2 = [].slice.call(arguments);
2961 e2[0] = "[" + this._id + "] " + e2[0], a.apply(null, e2);
2962 }
2963 }
2964 p.WEBRTC_SUPPORT = !!o(), p.config = { iceServers: [{ urls: ["stun:stun.l.google.com:19302", "stun:global.stun.twilio.com:3478"] }], sdpSemantics: "unified-plan" }, p.channelConfig = {}, t2.exports = p;
2965 }, { buffer: 3, debug: 4, "err-code": 6, "get-browser-rtc": 8, "queue-microtask": 13, randombytes: 14, "readable-stream": 29 }] }, {}, [])("/");
2966 });
2967 }
2968 });
2969
2970 // package-external:@wordpress/rich-text
2971 var require_rich_text = __commonJS({
2972 "package-external:@wordpress/rich-text"(exports, module) {
2973 module.exports = window.wp.richText;
2974 }
2975 });
2976
2977 // package-external:@wordpress/deprecated
2978 var require_deprecated = __commonJS({
2979 "package-external:@wordpress/deprecated"(exports, module) {
2980 module.exports = window.wp.deprecated;
2981 }
2982 });
2983
2984 // package-external:@wordpress/private-apis
2985 var require_private_apis = __commonJS({
2986 "package-external:@wordpress/private-apis"(exports, module) {
2987 module.exports = window.wp.privateApis;
2988 }
2989 });
2990
2991 // package-external:@wordpress/html-entities
2992 var require_html_entities = __commonJS({
2993 "package-external:@wordpress/html-entities"(exports, module) {
2994 module.exports = window.wp.htmlEntities;
2995 }
2996 });
2997
2998 // package-external:@wordpress/element
2999 var require_element = __commonJS({
3000 "package-external:@wordpress/element"(exports, module) {
3001 module.exports = window.wp.element;
3002 }
3003 });
3004
3005 // vendor-external:react/jsx-runtime
3006 var require_jsx_runtime = __commonJS({
3007 "vendor-external:react/jsx-runtime"(exports, module) {
3008 module.exports = window.ReactJSXRuntime;
3009 }
3010 });
3011
3012 // package-external:@wordpress/warning
3013 var require_warning = __commonJS({
3014 "package-external:@wordpress/warning"(exports, module) {
3015 module.exports = window.wp.warning;
3016 }
3017 });
3018
3019 // package-external:@wordpress/block-editor
3020 var require_block_editor = __commonJS({
3021 "package-external:@wordpress/block-editor"(exports, module) {
3022 module.exports = window.wp.blockEditor;
3023 }
3024 });
3025
3026 // packages/core-data/build-module/index.js
3027 var index_exports = {};
3028 __export(index_exports, {
3029 EntityProvider: () => EntityProvider,
3030 __experimentalFetchLinkSuggestions: () => fetchLinkSuggestions,
3031 __experimentalFetchUrlData: () => experimental_fetch_url_data_default,
3032 __experimentalUseEntityRecord: () => __experimentalUseEntityRecord,
3033 __experimentalUseEntityRecords: () => __experimentalUseEntityRecords,
3034 __experimentalUseResourcePermissions: () => __experimentalUseResourcePermissions,
3035 fetchBlockPatterns: () => fetchBlockPatterns,
3036 privateApis: () => privateApis,
3037 store: () => store,
3038 useEntityBlockEditor: () => useEntityBlockEditor,
3039 useEntityId: () => useEntityId,
3040 useEntityProp: () => useEntityProp,
3041 useEntityRecord: () => useEntityRecord,
3042 useEntityRecords: () => useEntityRecords,
3043 useResourcePermissions: () => use_resource_permissions_default
3044 });
3045 var import_data11 = __toESM(require_data());
3046
3047 // packages/core-data/build-module/reducer.js
3048 var import_es64 = __toESM(require_es6());
3049 var import_compose2 = __toESM(require_compose());
3050 var import_data3 = __toESM(require_data());
3051 var import_undo_manager2 = __toESM(require_undo_manager());
3052
3053 // packages/core-data/build-module/utils/conservative-map-item.js
3054 var import_es6 = __toESM(require_es6());
3055 function conservativeMapItem(item, nextItem) {
3056 if (!item) {
3057 return nextItem;
3058 }
3059 let hasChanges = false;
3060 const result = {};
3061 for (const key in nextItem) {
3062 if ((0, import_es6.default)(item[key], nextItem[key])) {
3063 result[key] = item[key];
3064 } else {
3065 hasChanges = true;
3066 result[key] = nextItem[key];
3067 }
3068 }
3069 if (!hasChanges) {
3070 return item;
3071 }
3072 for (const key in item) {
3073 if (!result.hasOwnProperty(key)) {
3074 result[key] = item[key];
3075 }
3076 }
3077 return result;
3078 }
3079
3080 // packages/core-data/build-module/utils/get-normalized-comma-separable.js
3081 function getNormalizedCommaSeparable(value) {
3082 if (typeof value === "string") {
3083 return value.split(",");
3084 } else if (Array.isArray(value)) {
3085 return value;
3086 }
3087 return null;
3088 }
3089 var get_normalized_comma_separable_default = getNormalizedCommaSeparable;
3090
3091 // packages/core-data/build-module/utils/if-matching-action.js
3092 var ifMatchingAction = (isMatch) => (reducer) => (state, action) => {
3093 if (state === void 0 || isMatch(action)) {
3094 return reducer(state, action);
3095 }
3096 return state;
3097 };
3098 var if_matching_action_default = ifMatchingAction;
3099
3100 // packages/core-data/build-module/utils/forward-resolver.js
3101 var forwardResolver = (resolverName) => (...args2) => async ({ resolveSelect }) => {
3102 await resolveSelect[resolverName](...args2);
3103 };
3104 var forward_resolver_default = forwardResolver;
3105
3106 // packages/core-data/build-module/utils/on-sub-key.js
3107 var onSubKey = (actionProperty) => (reducer) => (state = {}, action) => {
3108 const key = action[actionProperty];
3109 if (key === void 0) {
3110 return state;
3111 }
3112 const nextKeyState = reducer(state[key], action);
3113 if (nextKeyState === state[key]) {
3114 return state;
3115 }
3116 return {
3117 ...state,
3118 [key]: nextKeyState
3119 };
3120 };
3121 var on_sub_key_default = onSubKey;
3122
3123 // packages/core-data/build-module/utils/replace-action.js
3124 var replaceAction = (replacer) => (reducer) => (state, action) => {
3125 return reducer(state, replacer(action));
3126 };
3127 var replace_action_default = replaceAction;
3128
3129 // packages/core-data/build-module/utils/with-weak-map-cache.js
3130 function withWeakMapCache(fn) {
3131 const cache3 = /* @__PURE__ */ new WeakMap();
3132 return (key) => {
3133 let value;
3134 if (cache3.has(key)) {
3135 value = cache3.get(key);
3136 } else {
3137 value = fn(key);
3138 if (key !== null && typeof key === "object") {
3139 cache3.set(key, value);
3140 }
3141 }
3142 return value;
3143 };
3144 }
3145 var with_weak_map_cache_default = withWeakMapCache;
3146
3147 // packages/core-data/build-module/utils/is-raw-attribute.js
3148 function isRawAttribute(entity2, attribute) {
3149 return (entity2.rawAttributes || []).includes(attribute);
3150 }
3151
3152 // packages/core-data/build-module/utils/set-nested-value.js
3153 function setNestedValue(object, path, value) {
3154 if (!object || typeof object !== "object") {
3155 return object;
3156 }
3157 const normalizedPath = Array.isArray(path) ? path : path.split(".");
3158 normalizedPath.reduce((acc, key, idx) => {
3159 if (acc[key] === void 0) {
3160 if (Number.isInteger(normalizedPath[idx + 1])) {
3161 acc[key] = [];
3162 } else {
3163 acc[key] = {};
3164 }
3165 }
3166 if (idx === normalizedPath.length - 1) {
3167 acc[key] = value;
3168 }
3169 return acc[key];
3170 }, object);
3171 return object;
3172 }
3173
3174 // packages/core-data/build-module/utils/get-nested-value.js
3175 function getNestedValue(object, path, defaultValue) {
3176 if (!object || typeof object !== "object" || typeof path !== "string" && !Array.isArray(path)) {
3177 return object;
3178 }
3179 const normalizedPath = Array.isArray(path) ? path : path.split(".");
3180 let value = object;
3181 normalizedPath.forEach((fieldName) => {
3182 value = value?.[fieldName];
3183 });
3184 return value !== void 0 ? value : defaultValue;
3185 }
3186
3187 // packages/core-data/build-module/utils/is-numeric-id.js
3188 function isNumericID(id2) {
3189 return /^\s*\d+\s*$/.test(id2);
3190 }
3191
3192 // packages/core-data/build-module/utils/user-permissions.js
3193 var ALLOWED_RESOURCE_ACTIONS = [
3194 "create",
3195 "read",
3196 "update",
3197 "delete"
3198 ];
3199 function getUserPermissionsFromAllowHeader(allowedMethods) {
3200 const permissions = {};
3201 if (!allowedMethods) {
3202 return permissions;
3203 }
3204 const methods = {
3205 create: "POST",
3206 read: "GET",
3207 update: "PUT",
3208 delete: "DELETE"
3209 };
3210 for (const [actionName, methodName] of Object.entries(methods)) {
3211 permissions[actionName] = allowedMethods.includes(methodName);
3212 }
3213 return permissions;
3214 }
3215 function getUserPermissionCacheKey(action, resource, id2) {
3216 const key = (typeof resource === "object" ? [action, resource.kind, resource.name, resource.id] : [action, resource, id2]).filter(Boolean).join("/");
3217 return key;
3218 }
3219
3220 // packages/core-data/build-module/utils/receive-intermediate-results.js
3221 var RECEIVE_INTERMEDIATE_RESULTS = Symbol(
3222 "RECEIVE_INTERMEDIATE_RESULTS"
3223 );
3224
3225 // packages/core-data/build-module/queried-data/actions.js
3226 function receiveItems(items2, edits, meta) {
3227 return {
3228 type: "RECEIVE_ITEMS",
3229 items: Array.isArray(items2) ? items2 : [items2],
3230 persistedEdits: edits,
3231 meta
3232 };
3233 }
3234 function removeItems(kind, name, records, invalidateCache = false) {
3235 return {
3236 type: "REMOVE_ITEMS",
3237 itemIds: Array.isArray(records) ? records : [records],
3238 kind,
3239 name,
3240 invalidateCache
3241 };
3242 }
3243 function receiveQueriedItems(items2, query = {}, edits, meta) {
3244 return {
3245 ...receiveItems(items2, edits, meta),
3246 query
3247 };
3248 }
3249
3250 // packages/core-data/build-module/queried-data/selectors.js
3251 var import_equivalent_key_map = __toESM(require_equivalent_key_map());
3252 var import_data = __toESM(require_data());
3253
3254 // packages/core-data/build-module/queried-data/get-query-parts.js
3255 var import_url = __toESM(require_url());
3256 function getQueryParts(query) {
3257 const parts = {
3258 stableKey: "",
3259 page: 1,
3260 perPage: 10,
3261 fields: null,
3262 include: null,
3263 context: "default"
3264 };
3265 const keys2 = Object.keys(query).sort();
3266 for (let i = 0; i < keys2.length; i++) {
3267 const key = keys2[i];
3268 let value = query[key];
3269 switch (key) {
3270 case "page":
3271 parts[key] = Number(value);
3272 break;
3273 case "per_page":
3274 parts.perPage = Number(value);
3275 break;
3276 case "context":
3277 parts.context = value;
3278 break;
3279 default:
3280 if (key === "_fields") {
3281 parts.fields = get_normalized_comma_separable_default(value) ?? [];
3282 value = parts.fields.join();
3283 }
3284 if (key === "include") {
3285 if (typeof value === "number") {
3286 value = value.toString();
3287 }
3288 parts.include = (get_normalized_comma_separable_default(value) ?? []).map(Number);
3289 value = parts.include.join();
3290 }
3291 parts.stableKey += (parts.stableKey ? "&" : "") + (0, import_url.addQueryArgs)("", { [key]: value }).slice(1);
3292 }
3293 }
3294 return parts;
3295 }
3296 var get_query_parts_default = with_weak_map_cache_default(getQueryParts);
3297
3298 // packages/core-data/build-module/queried-data/selectors.js
3299 var queriedItemsCacheByState = /* @__PURE__ */ new WeakMap();
3300 function getQueriedItemsUncached(state, query) {
3301 const { stableKey, page, perPage, include, fields, context } = get_query_parts_default(query);
3302 let itemIds;
3303 if (state.queries?.[context]?.[stableKey]) {
3304 itemIds = state.queries[context][stableKey].itemIds;
3305 }
3306 if (!itemIds) {
3307 return null;
3308 }
3309 const startOffset = perPage === -1 ? 0 : (page - 1) * perPage;
3310 const endOffset = perPage === -1 ? itemIds.length : Math.min(startOffset + perPage, itemIds.length);
3311 const items2 = [];
3312 for (let i = startOffset; i < endOffset; i++) {
3313 const itemId = itemIds[i];
3314 if (Array.isArray(include) && !include.includes(itemId)) {
3315 continue;
3316 }
3317 if (itemId === void 0) {
3318 continue;
3319 }
3320 if (!state.items[context]?.hasOwnProperty(itemId)) {
3321 return null;
3322 }
3323 const item = state.items[context][itemId];
3324 let filteredItem;
3325 if (Array.isArray(fields)) {
3326 filteredItem = {};
3327 for (let f = 0; f < fields.length; f++) {
3328 const field = fields[f].split(".");
3329 let value = item;
3330 field.forEach((fieldName) => {
3331 value = value?.[fieldName];
3332 });
3333 setNestedValue(filteredItem, field, value);
3334 }
3335 } else {
3336 if (!state.itemIsComplete[context]?.[itemId]) {
3337 return null;
3338 }
3339 filteredItem = item;
3340 }
3341 items2.push(filteredItem);
3342 }
3343 return items2;
3344 }
3345 var getQueriedItems = (0, import_data.createSelector)((state, query = {}) => {
3346 let queriedItemsCache = queriedItemsCacheByState.get(state);
3347 if (queriedItemsCache) {
3348 const queriedItems = queriedItemsCache.get(query);
3349 if (queriedItems !== void 0) {
3350 return queriedItems;
3351 }
3352 } else {
3353 queriedItemsCache = new import_equivalent_key_map.default();
3354 queriedItemsCacheByState.set(state, queriedItemsCache);
3355 }
3356 const items2 = getQueriedItemsUncached(state, query);
3357 queriedItemsCache.set(query, items2);
3358 return items2;
3359 });
3360 function getQueriedTotalItems(state, query = {}) {
3361 const { stableKey, context } = get_query_parts_default(query);
3362 return state.queries?.[context]?.[stableKey]?.meta?.totalItems ?? null;
3363 }
3364 function getQueriedTotalPages(state, query = {}) {
3365 const { stableKey, context } = get_query_parts_default(query);
3366 return state.queries?.[context]?.[stableKey]?.meta?.totalPages ?? null;
3367 }
3368
3369 // packages/core-data/build-module/queried-data/reducer.js
3370 var import_data2 = __toESM(require_data());
3371 var import_compose = __toESM(require_compose());
3372
3373 // node_modules/tslib/tslib.es6.mjs
3374 var __assign = function() {
3375 __assign = Object.assign || function __assign2(t) {
3376 for (var s, i = 1, n = arguments.length; i < n; i++) {
3377 s = arguments[i];
3378 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
3379 }
3380 return t;
3381 };
3382 return __assign.apply(this, arguments);
3383 };
3384
3385 // node_modules/lower-case/dist.es2015/index.js
3386 function lowerCase(str) {
3387 return str.toLowerCase();
3388 }
3389
3390 // node_modules/no-case/dist.es2015/index.js
3391 var DEFAULT_SPLIT_REGEXP = [/([a-z0-9])([A-Z])/g, /([A-Z])([A-Z][a-z])/g];
3392 var DEFAULT_STRIP_REGEXP = /[^A-Z0-9]+/gi;
3393 function noCase(input, options) {
3394 if (options === void 0) {
3395 options = {};
3396 }
3397 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;
3398 var result = replace(replace(input, splitRegexp, "$1\0$2"), stripRegexp, "\0");
3399 var start = 0;
3400 var end = result.length;
3401 while (result.charAt(start) === "\0")
3402 start++;
3403 while (result.charAt(end - 1) === "\0")
3404 end--;
3405 return result.slice(start, end).split("\0").map(transform).join(delimiter);
3406 }
3407 function replace(input, re, value) {
3408 if (re instanceof RegExp)
3409 return input.replace(re, value);
3410 return re.reduce(function(input2, re2) {
3411 return input2.replace(re2, value);
3412 }, input);
3413 }
3414
3415 // node_modules/pascal-case/dist.es2015/index.js
3416 function pascalCaseTransform(input, index) {
3417 var firstChar = input.charAt(0);
3418 var lowerChars = input.substr(1).toLowerCase();
3419 if (index > 0 && firstChar >= "0" && firstChar <= "9") {
3420 return "_" + firstChar + lowerChars;
3421 }
3422 return "" + firstChar.toUpperCase() + lowerChars;
3423 }
3424 function pascalCase(input, options) {
3425 if (options === void 0) {
3426 options = {};
3427 }
3428 return noCase(input, __assign({ delimiter: "", transform: pascalCaseTransform }, options));
3429 }
3430
3431 // node_modules/camel-case/dist.es2015/index.js
3432 function camelCaseTransform(input, index) {
3433 if (index === 0)
3434 return input.toLowerCase();
3435 return pascalCaseTransform(input, index);
3436 }
3437 function camelCase(input, options) {
3438 if (options === void 0) {
3439 options = {};
3440 }
3441 return pascalCase(input, __assign({ transform: camelCaseTransform }, options));
3442 }
3443
3444 // node_modules/upper-case-first/dist.es2015/index.js
3445 function upperCaseFirst(input) {
3446 return input.charAt(0).toUpperCase() + input.substr(1);
3447 }
3448
3449 // node_modules/capital-case/dist.es2015/index.js
3450 function capitalCaseTransform(input) {
3451 return upperCaseFirst(input.toLowerCase());
3452 }
3453 function capitalCase(input, options) {
3454 if (options === void 0) {
3455 options = {};
3456 }
3457 return noCase(input, __assign({ delimiter: " ", transform: capitalCaseTransform }, options));
3458 }
3459
3460 // packages/core-data/build-module/entities.js
3461 var import_api_fetch = __toESM(require_api_fetch());
3462 var import_blocks3 = __toESM(require_blocks());
3463 var import_i18n = __toESM(require_i18n());
3464
3465 // node_modules/yjs/dist/yjs.mjs
3466 var yjs_exports = {};
3467 __export(yjs_exports, {
3468 AbsolutePosition: () => AbsolutePosition,
3469 AbstractConnector: () => AbstractConnector,
3470 AbstractStruct: () => AbstractStruct,
3471 AbstractType: () => AbstractType,
3472 Array: () => YArray,
3473 ContentAny: () => ContentAny,
3474 ContentBinary: () => ContentBinary,
3475 ContentDeleted: () => ContentDeleted,
3476 ContentEmbed: () => ContentEmbed,
3477 ContentFormat: () => ContentFormat,
3478 ContentJSON: () => ContentJSON,
3479 ContentString: () => ContentString,
3480 ContentType: () => ContentType,
3481 Doc: () => Doc,
3482 GC: () => GC,
3483 ID: () => ID,
3484 Item: () => Item,
3485 Map: () => YMap,
3486 PermanentUserData: () => PermanentUserData,
3487 RelativePosition: () => RelativePosition,
3488 Snapshot: () => Snapshot,
3489 Text: () => YText,
3490 Transaction: () => Transaction,
3491 UndoManager: () => UndoManager,
3492 UpdateEncoderV1: () => UpdateEncoderV1,
3493 XmlElement: () => YXmlElement,
3494 XmlFragment: () => YXmlFragment,
3495 XmlHook: () => YXmlHook,
3496 XmlText: () => YXmlText,
3497 YArrayEvent: () => YArrayEvent,
3498 YEvent: () => YEvent,
3499 YMapEvent: () => YMapEvent,
3500 YTextEvent: () => YTextEvent,
3501 YXmlEvent: () => YXmlEvent,
3502 applyUpdate: () => applyUpdate,
3503 applyUpdateV2: () => applyUpdateV2,
3504 cleanupYTextFormatting: () => cleanupYTextFormatting,
3505 compareIDs: () => compareIDs,
3506 compareRelativePositions: () => compareRelativePositions,
3507 convertUpdateFormatV1ToV2: () => convertUpdateFormatV1ToV2,
3508 convertUpdateFormatV2ToV1: () => convertUpdateFormatV2ToV1,
3509 createAbsolutePositionFromRelativePosition: () => createAbsolutePositionFromRelativePosition,
3510 createDeleteSet: () => createDeleteSet,
3511 createDeleteSetFromStructStore: () => createDeleteSetFromStructStore,
3512 createDocFromSnapshot: () => createDocFromSnapshot,
3513 createID: () => createID,
3514 createRelativePositionFromJSON: () => createRelativePositionFromJSON,
3515 createRelativePositionFromTypeIndex: () => createRelativePositionFromTypeIndex,
3516 createSnapshot: () => createSnapshot,
3517 decodeRelativePosition: () => decodeRelativePosition,
3518 decodeSnapshot: () => decodeSnapshot,
3519 decodeSnapshotV2: () => decodeSnapshotV2,
3520 decodeStateVector: () => decodeStateVector,
3521 decodeUpdate: () => decodeUpdate,
3522 decodeUpdateV2: () => decodeUpdateV2,
3523 diffUpdate: () => diffUpdate,
3524 diffUpdateV2: () => diffUpdateV2,
3525 emptySnapshot: () => emptySnapshot,
3526 encodeRelativePosition: () => encodeRelativePosition,
3527 encodeSnapshot: () => encodeSnapshot,
3528 encodeSnapshotV2: () => encodeSnapshotV2,
3529 encodeStateAsUpdate: () => encodeStateAsUpdate,
3530 encodeStateAsUpdateV2: () => encodeStateAsUpdateV2,
3531 encodeStateVector: () => encodeStateVector,
3532 encodeStateVectorFromUpdate: () => encodeStateVectorFromUpdate,
3533 encodeStateVectorFromUpdateV2: () => encodeStateVectorFromUpdateV2,
3534 equalDeleteSets: () => equalDeleteSets,
3535 equalSnapshots: () => equalSnapshots,
3536 findIndexSS: () => findIndexSS,
3537 findRootTypeKey: () => findRootTypeKey,
3538 getItem: () => getItem,
3539 getState: () => getState,
3540 getTypeChildren: () => getTypeChildren,
3541 isDeleted: () => isDeleted,
3542 isParentOf: () => isParentOf,
3543 iterateDeletedStructs: () => iterateDeletedStructs,
3544 logType: () => logType,
3545 logUpdate: () => logUpdate,
3546 logUpdateV2: () => logUpdateV2,
3547 mergeUpdates: () => mergeUpdates,
3548 mergeUpdatesV2: () => mergeUpdatesV2,
3549 obfuscateUpdate: () => obfuscateUpdate,
3550 obfuscateUpdateV2: () => obfuscateUpdateV2,
3551 parseUpdateMeta: () => parseUpdateMeta,
3552 parseUpdateMetaV2: () => parseUpdateMetaV2,
3553 readUpdate: () => readUpdate,
3554 readUpdateV2: () => readUpdateV2,
3555 relativePositionToJSON: () => relativePositionToJSON,
3556 snapshot: () => snapshot,
3557 snapshotContainsUpdate: () => snapshotContainsUpdate,
3558 transact: () => transact,
3559 tryGc: () => tryGc,
3560 typeListToArraySnapshot: () => typeListToArraySnapshot,
3561 typeMapGetSnapshot: () => typeMapGetSnapshot
3562 });
3563
3564 // node_modules/lib0/map.js
3565 var create = () => /* @__PURE__ */ new Map();
3566 var copy = (m) => {
3567 const r = create();
3568 m.forEach((v, k) => {
3569 r.set(k, v);
3570 });
3571 return r;
3572 };
3573 var setIfUndefined = (map2, key, createT) => {
3574 let set = map2.get(key);
3575 if (set === void 0) {
3576 map2.set(key, set = createT());
3577 }
3578 return set;
3579 };
3580 var map = (m, f) => {
3581 const res = [];
3582 for (const [key, value] of m) {
3583 res.push(f(value, key));
3584 }
3585 return res;
3586 };
3587 var any = (m, f) => {
3588 for (const [key, value] of m) {
3589 if (f(value, key)) {
3590 return true;
3591 }
3592 }
3593 return false;
3594 };
3595
3596 // node_modules/lib0/set.js
3597 var create2 = () => /* @__PURE__ */ new Set();
3598
3599 // node_modules/lib0/array.js
3600 var last = (arr) => arr[arr.length - 1];
3601 var appendTo = (dest, src) => {
3602 for (let i = 0; i < src.length; i++) {
3603 dest.push(src[i]);
3604 }
3605 };
3606 var from = Array.from;
3607 var some = (arr, f) => {
3608 for (let i = 0; i < arr.length; i++) {
3609 if (f(arr[i], i, arr)) {
3610 return true;
3611 }
3612 }
3613 return false;
3614 };
3615 var unfold = (len, f) => {
3616 const array = new Array(len);
3617 for (let i = 0; i < len; i++) {
3618 array[i] = f(i, array);
3619 }
3620 return array;
3621 };
3622 var isArray = Array.isArray;
3623
3624 // node_modules/lib0/observable.js
3625 var Observable = class {
3626 constructor() {
3627 this._observers = create();
3628 }
3629 /**
3630 * @param {N} name
3631 * @param {function} f
3632 */
3633 on(name, f) {
3634 setIfUndefined(this._observers, name, create2).add(f);
3635 }
3636 /**
3637 * @param {N} name
3638 * @param {function} f
3639 */
3640 once(name, f) {
3641 const _f = (...args2) => {
3642 this.off(name, _f);
3643 f(...args2);
3644 };
3645 this.on(name, _f);
3646 }
3647 /**
3648 * @param {N} name
3649 * @param {function} f
3650 */
3651 off(name, f) {
3652 const observers = this._observers.get(name);
3653 if (observers !== void 0) {
3654 observers.delete(f);
3655 if (observers.size === 0) {
3656 this._observers.delete(name);
3657 }
3658 }
3659 }
3660 /**
3661 * Emit a named event. All registered event listeners that listen to the
3662 * specified name will receive the event.
3663 *
3664 * @todo This should catch exceptions
3665 *
3666 * @param {N} name The event name.
3667 * @param {Array<any>} args The arguments that are applied to the event listener.
3668 */
3669 emit(name, args2) {
3670 return from((this._observers.get(name) || create()).values()).forEach((f) => f(...args2));
3671 }
3672 destroy() {
3673 this._observers = create();
3674 }
3675 };
3676
3677 // node_modules/lib0/math.js
3678 var floor = Math.floor;
3679 var abs = Math.abs;
3680 var log10 = Math.log10;
3681 var min = (a, b) => a < b ? a : b;
3682 var max = (a, b) => a > b ? a : b;
3683 var isNaN2 = Number.isNaN;
3684 var isNegativeZero = (n) => n !== 0 ? n < 0 : 1 / n < 0;
3685
3686 // node_modules/lib0/string.js
3687 var fromCharCode = String.fromCharCode;
3688 var fromCodePoint = String.fromCodePoint;
3689 var MAX_UTF16_CHARACTER = fromCharCode(65535);
3690 var toLowerCase = (s) => s.toLowerCase();
3691 var trimLeftRegex = /^\s*/g;
3692 var trimLeft = (s) => s.replace(trimLeftRegex, "");
3693 var fromCamelCaseRegex = /([A-Z])/g;
3694 var fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, (match) => `${separator}${toLowerCase(match)}`));
3695 var _encodeUtf8Polyfill = (str) => {
3696 const encodedString = unescape(encodeURIComponent(str));
3697 const len = encodedString.length;
3698 const buf = new Uint8Array(len);
3699 for (let i = 0; i < len; i++) {
3700 buf[i] = /** @type {number} */
3701 encodedString.codePointAt(i);
3702 }
3703 return buf;
3704 };
3705 var utf8TextEncoder = (
3706 /** @type {TextEncoder} */
3707 typeof TextEncoder !== "undefined" ? new TextEncoder() : null
3708 );
3709 var _encodeUtf8Native = (str) => utf8TextEncoder.encode(str);
3710 var encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill;
3711 var utf8TextDecoder = typeof TextDecoder === "undefined" ? null : new TextDecoder("utf-8", { fatal: true, ignoreBOM: true });
3712 if (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) {
3713 utf8TextDecoder = null;
3714 }
3715 var repeat = (source, n) => unfold(n, () => source).join("");
3716
3717 // node_modules/lib0/conditions.js
3718 var undefinedToNull = (v) => v === void 0 ? null : v;
3719
3720 // node_modules/lib0/storage.js
3721 var VarStoragePolyfill = class {
3722 constructor() {
3723 this.map = /* @__PURE__ */ new Map();
3724 }
3725 /**
3726 * @param {string} key
3727 * @param {any} newValue
3728 */
3729 setItem(key, newValue) {
3730 this.map.set(key, newValue);
3731 }
3732 /**
3733 * @param {string} key
3734 */
3735 getItem(key) {
3736 return this.map.get(key);
3737 }
3738 };
3739 var _localStorage = new VarStoragePolyfill();
3740 var usePolyfill = true;
3741 try {
3742 if (typeof localStorage !== "undefined") {
3743 _localStorage = localStorage;
3744 usePolyfill = false;
3745 }
3746 } catch (e) {
3747 }
3748 var varStorage = _localStorage;
3749 var onChange = (eventHandler) => usePolyfill || addEventListener(
3750 "storage",
3751 /** @type {any} */
3752 eventHandler
3753 );
3754 var offChange = (eventHandler) => usePolyfill || removeEventListener(
3755 "storage",
3756 /** @type {any} */
3757 eventHandler
3758 );
3759
3760 // node_modules/lib0/object.js
3761 var assign = Object.assign;
3762 var keys = Object.keys;
3763 var forEach = (obj, f) => {
3764 for (const key in obj) {
3765 f(obj[key], key);
3766 }
3767 };
3768 var length = (obj) => keys(obj).length;
3769 var isEmpty = (obj) => {
3770 for (const _k in obj) {
3771 return false;
3772 }
3773 return true;
3774 };
3775 var every = (obj, f) => {
3776 for (const key in obj) {
3777 if (!f(obj[key], key)) {
3778 return false;
3779 }
3780 }
3781 return true;
3782 };
3783 var hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
3784 var equalFlat = (a, b) => a === b || length(a) === length(b) && every(a, (val, key) => (val !== void 0 || hasProperty(b, key)) && b[key] === val);
3785
3786 // node_modules/lib0/function.js
3787 var callAll = (fs, args2, i = 0) => {
3788 try {
3789 for (; i < fs.length; i++) {
3790 fs[i](...args2);
3791 }
3792 } finally {
3793 if (i < fs.length) {
3794 callAll(fs, args2, i + 1);
3795 }
3796 }
3797 };
3798 var nop = () => {
3799 };
3800 var id = (a) => a;
3801 var equalityStrict = (a, b) => a === b;
3802 var equalityDeep = (a, b) => {
3803 if (a == null || b == null) {
3804 return equalityStrict(a, b);
3805 }
3806 if (a.constructor !== b.constructor) {
3807 return false;
3808 }
3809 if (a === b) {
3810 return true;
3811 }
3812 switch (a.constructor) {
3813 case ArrayBuffer:
3814 a = new Uint8Array(a);
3815 b = new Uint8Array(b);
3816 // eslint-disable-next-line no-fallthrough
3817 case Uint8Array: {
3818 if (a.byteLength !== b.byteLength) {
3819 return false;
3820 }
3821 for (let i = 0; i < a.length; i++) {
3822 if (a[i] !== b[i]) {
3823 return false;
3824 }
3825 }
3826 break;
3827 }
3828 case Set: {
3829 if (a.size !== b.size) {
3830 return false;
3831 }
3832 for (const value of a) {
3833 if (!b.has(value)) {
3834 return false;
3835 }
3836 }
3837 break;
3838 }
3839 case Map: {
3840 if (a.size !== b.size) {
3841 return false;
3842 }
3843 for (const key of a.keys()) {
3844 if (!b.has(key) || !equalityDeep(a.get(key), b.get(key))) {
3845 return false;
3846 }
3847 }
3848 break;
3849 }
3850 case Object:
3851 if (length(a) !== length(b)) {
3852 return false;
3853 }
3854 for (const key in a) {
3855 if (!hasProperty(a, key) || !equalityDeep(a[key], b[key])) {
3856 return false;
3857 }
3858 }
3859 break;
3860 case Array:
3861 if (a.length !== b.length) {
3862 return false;
3863 }
3864 for (let i = 0; i < a.length; i++) {
3865 if (!equalityDeep(a[i], b[i])) {
3866 return false;
3867 }
3868 }
3869 break;
3870 default:
3871 return false;
3872 }
3873 return true;
3874 };
3875 var isOneOf = (value, options) => options.includes(value);
3876
3877 // node_modules/lib0/environment.js
3878 var isNode = typeof process !== "undefined" && process.release && /node|io\.js/.test(process.release.name);
3879 var isBrowser = typeof window !== "undefined" && typeof document !== "undefined" && !isNode;
3880 var isMac = typeof navigator !== "undefined" ? /Mac/.test(navigator.platform) : false;
3881 var params;
3882 var args = [];
3883 var computeParams = () => {
3884 if (params === void 0) {
3885 if (isNode) {
3886 params = create();
3887 const pargs = process.argv;
3888 let currParamName = null;
3889 for (let i = 0; i < pargs.length; i++) {
3890 const parg = pargs[i];
3891 if (parg[0] === "-") {
3892 if (currParamName !== null) {
3893 params.set(currParamName, "");
3894 }
3895 currParamName = parg;
3896 } else {
3897 if (currParamName !== null) {
3898 params.set(currParamName, parg);
3899 currParamName = null;
3900 } else {
3901 args.push(parg);
3902 }
3903 }
3904 }
3905 if (currParamName !== null) {
3906 params.set(currParamName, "");
3907 }
3908 } else if (typeof location === "object") {
3909 params = create();
3910 (location.search || "?").slice(1).split("&").forEach((kv) => {
3911 if (kv.length !== 0) {
3912 const [key, value] = kv.split("=");
3913 params.set(`--${fromCamelCase(key, "-")}`, value);
3914 params.set(`-${fromCamelCase(key, "-")}`, value);
3915 }
3916 });
3917 } else {
3918 params = create();
3919 }
3920 }
3921 return params;
3922 };
3923 var hasParam = (name) => computeParams().has(name);
3924 var getVariable = (name) => isNode ? undefinedToNull(process.env[name.toUpperCase()]) : undefinedToNull(varStorage.getItem(name));
3925 var hasConf = (name) => hasParam("--" + name) || getVariable(name) !== null;
3926 var production = hasConf("production");
3927 var forceColor = isNode && isOneOf(process.env.FORCE_COLOR, ["true", "1", "2"]);
3928 var supportsColor = !hasParam("no-colors") && (!isNode || process.stdout.isTTY || forceColor) && (!isNode || hasParam("color") || forceColor || getVariable("COLORTERM") !== null || (getVariable("TERM") || "").includes("color"));
3929
3930 // node_modules/lib0/binary.js
3931 var BIT1 = 1;
3932 var BIT2 = 2;
3933 var BIT3 = 4;
3934 var BIT4 = 8;
3935 var BIT6 = 32;
3936 var BIT7 = 64;
3937 var BIT8 = 128;
3938 var BIT18 = 1 << 17;
3939 var BIT19 = 1 << 18;
3940 var BIT20 = 1 << 19;
3941 var BIT21 = 1 << 20;
3942 var BIT22 = 1 << 21;
3943 var BIT23 = 1 << 22;
3944 var BIT24 = 1 << 23;
3945 var BIT25 = 1 << 24;
3946 var BIT26 = 1 << 25;
3947 var BIT27 = 1 << 26;
3948 var BIT28 = 1 << 27;
3949 var BIT29 = 1 << 28;
3950 var BIT30 = 1 << 29;
3951 var BIT31 = 1 << 30;
3952 var BIT32 = 1 << 31;
3953 var BITS5 = 31;
3954 var BITS6 = 63;
3955 var BITS7 = 127;
3956 var BITS17 = BIT18 - 1;
3957 var BITS18 = BIT19 - 1;
3958 var BITS19 = BIT20 - 1;
3959 var BITS20 = BIT21 - 1;
3960 var BITS21 = BIT22 - 1;
3961 var BITS22 = BIT23 - 1;
3962 var BITS23 = BIT24 - 1;
3963 var BITS24 = BIT25 - 1;
3964 var BITS25 = BIT26 - 1;
3965 var BITS26 = BIT27 - 1;
3966 var BITS27 = BIT28 - 1;
3967 var BITS28 = BIT29 - 1;
3968 var BITS29 = BIT30 - 1;
3969 var BITS30 = BIT31 - 1;
3970 var BITS31 = 2147483647;
3971
3972 // node_modules/lib0/number.js
3973 var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER;
3974 var MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER;
3975 var LOWEST_INT32 = 1 << 31;
3976 var isInteger = Number.isInteger || ((num) => typeof num === "number" && isFinite(num) && floor(num) === num);
3977 var isNaN3 = Number.isNaN;
3978 var parseInt2 = Number.parseInt;
3979
3980 // node_modules/lib0/error.js
3981 var create3 = (s) => new Error(s);
3982 var methodUnimplemented = () => {
3983 throw create3("Method unimplemented");
3984 };
3985 var unexpectedCase = () => {
3986 throw create3("Unexpected case");
3987 };
3988
3989 // node_modules/lib0/decoding.js
3990 var errorUnexpectedEndOfArray = create3("Unexpected end of array");
3991 var errorIntegerOutOfRange = create3("Integer out of Range");
3992 var Decoder = class {
3993 /**
3994 * @param {Uint8Array} uint8Array Binary data to decode
3995 */
3996 constructor(uint8Array) {
3997 this.arr = uint8Array;
3998 this.pos = 0;
3999 }
4000 };
4001 var createDecoder = (uint8Array) => new Decoder(uint8Array);
4002 var hasContent = (decoder) => decoder.pos !== decoder.arr.length;
4003 var readUint8Array = (decoder, len) => {
4004 const view = createUint8ArrayViewFromArrayBuffer(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len);
4005 decoder.pos += len;
4006 return view;
4007 };
4008 var readVarUint8Array = (decoder) => readUint8Array(decoder, readVarUint(decoder));
4009 var readUint8 = (decoder) => decoder.arr[decoder.pos++];
4010 var readVarUint = (decoder) => {
4011 let num = 0;
4012 let mult = 1;
4013 const len = decoder.arr.length;
4014 while (decoder.pos < len) {
4015 const r = decoder.arr[decoder.pos++];
4016 num = num + (r & BITS7) * mult;
4017 mult *= 128;
4018 if (r < BIT8) {
4019 return num;
4020 }
4021 if (num > MAX_SAFE_INTEGER) {
4022 throw errorIntegerOutOfRange;
4023 }
4024 }
4025 throw errorUnexpectedEndOfArray;
4026 };
4027 var readVarInt = (decoder) => {
4028 let r = decoder.arr[decoder.pos++];
4029 let num = r & BITS6;
4030 let mult = 64;
4031 const sign = (r & BIT7) > 0 ? -1 : 1;
4032 if ((r & BIT8) === 0) {
4033 return sign * num;
4034 }
4035 const len = decoder.arr.length;
4036 while (decoder.pos < len) {
4037 r = decoder.arr[decoder.pos++];
4038 num = num + (r & BITS7) * mult;
4039 mult *= 128;
4040 if (r < BIT8) {
4041 return sign * num;
4042 }
4043 if (num > MAX_SAFE_INTEGER) {
4044 throw errorIntegerOutOfRange;
4045 }
4046 }
4047 throw errorUnexpectedEndOfArray;
4048 };
4049 var _readVarStringPolyfill = (decoder) => {
4050 let remainingLen = readVarUint(decoder);
4051 if (remainingLen === 0) {
4052 return "";
4053 } else {
4054 let encodedString = String.fromCodePoint(readUint8(decoder));
4055 if (--remainingLen < 100) {
4056 while (remainingLen--) {
4057 encodedString += String.fromCodePoint(readUint8(decoder));
4058 }
4059 } else {
4060 while (remainingLen > 0) {
4061 const nextLen = remainingLen < 1e4 ? remainingLen : 1e4;
4062 const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen);
4063 decoder.pos += nextLen;
4064 encodedString += String.fromCodePoint.apply(
4065 null,
4066 /** @type {any} */
4067 bytes
4068 );
4069 remainingLen -= nextLen;
4070 }
4071 }
4072 return decodeURIComponent(escape(encodedString));
4073 }
4074 };
4075 var _readVarStringNative = (decoder) => (
4076 /** @type any */
4077 utf8TextDecoder.decode(readVarUint8Array(decoder))
4078 );
4079 var readVarString = utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill;
4080 var readFromDataView = (decoder, len) => {
4081 const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len);
4082 decoder.pos += len;
4083 return dv;
4084 };
4085 var readFloat32 = (decoder) => readFromDataView(decoder, 4).getFloat32(0, false);
4086 var readFloat64 = (decoder) => readFromDataView(decoder, 8).getFloat64(0, false);
4087 var readBigInt64 = (decoder) => (
4088 /** @type {any} */
4089 readFromDataView(decoder, 8).getBigInt64(0, false)
4090 );
4091 var readAnyLookupTable = [
4092 (decoder) => void 0,
4093 // CASE 127: undefined
4094 (decoder) => null,
4095 // CASE 126: null
4096 readVarInt,
4097 // CASE 125: integer
4098 readFloat32,
4099 // CASE 124: float32
4100 readFloat64,
4101 // CASE 123: float64
4102 readBigInt64,
4103 // CASE 122: bigint
4104 (decoder) => false,
4105 // CASE 121: boolean (false)
4106 (decoder) => true,
4107 // CASE 120: boolean (true)
4108 readVarString,
4109 // CASE 119: string
4110 (decoder) => {
4111 const len = readVarUint(decoder);
4112 const obj = {};
4113 for (let i = 0; i < len; i++) {
4114 const key = readVarString(decoder);
4115 obj[key] = readAny(decoder);
4116 }
4117 return obj;
4118 },
4119 (decoder) => {
4120 const len = readVarUint(decoder);
4121 const arr = [];
4122 for (let i = 0; i < len; i++) {
4123 arr.push(readAny(decoder));
4124 }
4125 return arr;
4126 },
4127 readVarUint8Array
4128 // CASE 116: Uint8Array
4129 ];
4130 var readAny = (decoder) => readAnyLookupTable[127 - readUint8(decoder)](decoder);
4131 var RleDecoder = class extends Decoder {
4132 /**
4133 * @param {Uint8Array} uint8Array
4134 * @param {function(Decoder):T} reader
4135 */
4136 constructor(uint8Array, reader) {
4137 super(uint8Array);
4138 this.reader = reader;
4139 this.s = null;
4140 this.count = 0;
4141 }
4142 read() {
4143 if (this.count === 0) {
4144 this.s = this.reader(this);
4145 if (hasContent(this)) {
4146 this.count = readVarUint(this) + 1;
4147 } else {
4148 this.count = -1;
4149 }
4150 }
4151 this.count--;
4152 return (
4153 /** @type {T} */
4154 this.s
4155 );
4156 }
4157 };
4158 var UintOptRleDecoder = class extends Decoder {
4159 /**
4160 * @param {Uint8Array} uint8Array
4161 */
4162 constructor(uint8Array) {
4163 super(uint8Array);
4164 this.s = 0;
4165 this.count = 0;
4166 }
4167 read() {
4168 if (this.count === 0) {
4169 this.s = readVarInt(this);
4170 const isNegative = isNegativeZero(this.s);
4171 this.count = 1;
4172 if (isNegative) {
4173 this.s = -this.s;
4174 this.count = readVarUint(this) + 2;
4175 }
4176 }
4177 this.count--;
4178 return (
4179 /** @type {number} */
4180 this.s
4181 );
4182 }
4183 };
4184 var IntDiffOptRleDecoder = class extends Decoder {
4185 /**
4186 * @param {Uint8Array} uint8Array
4187 */
4188 constructor(uint8Array) {
4189 super(uint8Array);
4190 this.s = 0;
4191 this.count = 0;
4192 this.diff = 0;
4193 }
4194 /**
4195 * @return {number}
4196 */
4197 read() {
4198 if (this.count === 0) {
4199 const diff = readVarInt(this);
4200 const hasCount = diff & 1;
4201 this.diff = floor(diff / 2);
4202 this.count = 1;
4203 if (hasCount) {
4204 this.count = readVarUint(this) + 2;
4205 }
4206 }
4207 this.s += this.diff;
4208 this.count--;
4209 return this.s;
4210 }
4211 };
4212 var StringDecoder = class {
4213 /**
4214 * @param {Uint8Array} uint8Array
4215 */
4216 constructor(uint8Array) {
4217 this.decoder = new UintOptRleDecoder(uint8Array);
4218 this.str = readVarString(this.decoder);
4219 this.spos = 0;
4220 }
4221 /**
4222 * @return {string}
4223 */
4224 read() {
4225 const end = this.spos + this.decoder.read();
4226 const res = this.str.slice(this.spos, end);
4227 this.spos = end;
4228 return res;
4229 }
4230 };
4231
4232 // node_modules/lib0/buffer.js
4233 var createUint8ArrayFromLen = (len) => new Uint8Array(len);
4234 var createUint8ArrayViewFromArrayBuffer = (buffer, byteOffset, length3) => new Uint8Array(buffer, byteOffset, length3);
4235 var createUint8ArrayFromArrayBuffer = (buffer) => new Uint8Array(buffer);
4236 var toBase64Browser = (bytes) => {
4237 let s = "";
4238 for (let i = 0; i < bytes.byteLength; i++) {
4239 s += fromCharCode(bytes[i]);
4240 }
4241 return btoa(s);
4242 };
4243 var toBase64Node = (bytes) => Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("base64");
4244 var fromBase64Browser = (s) => {
4245 const a = atob(s);
4246 const bytes = createUint8ArrayFromLen(a.length);
4247 for (let i = 0; i < a.length; i++) {
4248 bytes[i] = a.charCodeAt(i);
4249 }
4250 return bytes;
4251 };
4252 var fromBase64Node = (s) => {
4253 const buf = Buffer.from(s, "base64");
4254 return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
4255 };
4256 var toBase64 = isBrowser ? toBase64Browser : toBase64Node;
4257 var fromBase64 = isBrowser ? fromBase64Browser : fromBase64Node;
4258 var copyUint8Array = (uint8Array) => {
4259 const newBuf = createUint8ArrayFromLen(uint8Array.byteLength);
4260 newBuf.set(uint8Array);
4261 return newBuf;
4262 };
4263
4264 // node_modules/lib0/encoding.js
4265 var Encoder = class {
4266 constructor() {
4267 this.cpos = 0;
4268 this.cbuf = new Uint8Array(100);
4269 this.bufs = [];
4270 }
4271 };
4272 var createEncoder = () => new Encoder();
4273 var length2 = (encoder) => {
4274 let len = encoder.cpos;
4275 for (let i = 0; i < encoder.bufs.length; i++) {
4276 len += encoder.bufs[i].length;
4277 }
4278 return len;
4279 };
4280 var toUint8Array = (encoder) => {
4281 const uint8arr = new Uint8Array(length2(encoder));
4282 let curPos = 0;
4283 for (let i = 0; i < encoder.bufs.length; i++) {
4284 const d = encoder.bufs[i];
4285 uint8arr.set(d, curPos);
4286 curPos += d.length;
4287 }
4288 uint8arr.set(createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos), curPos);
4289 return uint8arr;
4290 };
4291 var verifyLen = (encoder, len) => {
4292 const bufferLen = encoder.cbuf.length;
4293 if (bufferLen - encoder.cpos < len) {
4294 encoder.bufs.push(createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos));
4295 encoder.cbuf = new Uint8Array(max(bufferLen, len) * 2);
4296 encoder.cpos = 0;
4297 }
4298 };
4299 var write = (encoder, num) => {
4300 const bufferLen = encoder.cbuf.length;
4301 if (encoder.cpos === bufferLen) {
4302 encoder.bufs.push(encoder.cbuf);
4303 encoder.cbuf = new Uint8Array(bufferLen * 2);
4304 encoder.cpos = 0;
4305 }
4306 encoder.cbuf[encoder.cpos++] = num;
4307 };
4308 var writeUint8 = write;
4309 var writeVarUint = (encoder, num) => {
4310 while (num > BITS7) {
4311 write(encoder, BIT8 | BITS7 & num);
4312 num = floor(num / 128);
4313 }
4314 write(encoder, BITS7 & num);
4315 };
4316 var writeVarInt = (encoder, num) => {
4317 const isNegative = isNegativeZero(num);
4318 if (isNegative) {
4319 num = -num;
4320 }
4321 write(encoder, (num > BITS6 ? BIT8 : 0) | (isNegative ? BIT7 : 0) | BITS6 & num);
4322 num = floor(num / 64);
4323 while (num > 0) {
4324 write(encoder, (num > BITS7 ? BIT8 : 0) | BITS7 & num);
4325 num = floor(num / 128);
4326 }
4327 };
4328 var _strBuffer = new Uint8Array(3e4);
4329 var _maxStrBSize = _strBuffer.length / 3;
4330 var _writeVarStringNative = (encoder, str) => {
4331 if (str.length < _maxStrBSize) {
4332 const written = utf8TextEncoder.encodeInto(str, _strBuffer).written || 0;
4333 writeVarUint(encoder, written);
4334 for (let i = 0; i < written; i++) {
4335 write(encoder, _strBuffer[i]);
4336 }
4337 } else {
4338 writeVarUint8Array(encoder, encodeUtf8(str));
4339 }
4340 };
4341 var _writeVarStringPolyfill = (encoder, str) => {
4342 const encodedString = unescape(encodeURIComponent(str));
4343 const len = encodedString.length;
4344 writeVarUint(encoder, len);
4345 for (let i = 0; i < len; i++) {
4346 write(
4347 encoder,
4348 /** @type {number} */
4349 encodedString.codePointAt(i)
4350 );
4351 }
4352 };
4353 var writeVarString = utf8TextEncoder && /** @type {any} */
4354 utf8TextEncoder.encodeInto ? _writeVarStringNative : _writeVarStringPolyfill;
4355 var writeBinaryEncoder = (encoder, append2) => writeUint8Array(encoder, toUint8Array(append2));
4356 var writeUint8Array = (encoder, uint8Array) => {
4357 const bufferLen = encoder.cbuf.length;
4358 const cpos = encoder.cpos;
4359 const leftCopyLen = min(bufferLen - cpos, uint8Array.length);
4360 const rightCopyLen = uint8Array.length - leftCopyLen;
4361 encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos);
4362 encoder.cpos += leftCopyLen;
4363 if (rightCopyLen > 0) {
4364 encoder.bufs.push(encoder.cbuf);
4365 encoder.cbuf = new Uint8Array(max(bufferLen * 2, rightCopyLen));
4366 encoder.cbuf.set(uint8Array.subarray(leftCopyLen));
4367 encoder.cpos = rightCopyLen;
4368 }
4369 };
4370 var writeVarUint8Array = (encoder, uint8Array) => {
4371 writeVarUint(encoder, uint8Array.byteLength);
4372 writeUint8Array(encoder, uint8Array);
4373 };
4374 var writeOnDataView = (encoder, len) => {
4375 verifyLen(encoder, len);
4376 const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len);
4377 encoder.cpos += len;
4378 return dview;
4379 };
4380 var writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num, false);
4381 var writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num, false);
4382 var writeBigInt64 = (encoder, num) => (
4383 /** @type {any} */
4384 writeOnDataView(encoder, 8).setBigInt64(0, num, false)
4385 );
4386 var floatTestBed = new DataView(new ArrayBuffer(4));
4387 var isFloat32 = (num) => {
4388 floatTestBed.setFloat32(0, num);
4389 return floatTestBed.getFloat32(0) === num;
4390 };
4391 var writeAny = (encoder, data) => {
4392 switch (typeof data) {
4393 case "string":
4394 write(encoder, 119);
4395 writeVarString(encoder, data);
4396 break;
4397 case "number":
4398 if (isInteger(data) && abs(data) <= BITS31) {
4399 write(encoder, 125);
4400 writeVarInt(encoder, data);
4401 } else if (isFloat32(data)) {
4402 write(encoder, 124);
4403 writeFloat32(encoder, data);
4404 } else {
4405 write(encoder, 123);
4406 writeFloat64(encoder, data);
4407 }
4408 break;
4409 case "bigint":
4410 write(encoder, 122);
4411 writeBigInt64(encoder, data);
4412 break;
4413 case "object":
4414 if (data === null) {
4415 write(encoder, 126);
4416 } else if (isArray(data)) {
4417 write(encoder, 117);
4418 writeVarUint(encoder, data.length);
4419 for (let i = 0; i < data.length; i++) {
4420 writeAny(encoder, data[i]);
4421 }
4422 } else if (data instanceof Uint8Array) {
4423 write(encoder, 116);
4424 writeVarUint8Array(encoder, data);
4425 } else {
4426 write(encoder, 118);
4427 const keys2 = Object.keys(data);
4428 writeVarUint(encoder, keys2.length);
4429 for (let i = 0; i < keys2.length; i++) {
4430 const key = keys2[i];
4431 writeVarString(encoder, key);
4432 writeAny(encoder, data[key]);
4433 }
4434 }
4435 break;
4436 case "boolean":
4437 write(encoder, data ? 120 : 121);
4438 break;
4439 default:
4440 write(encoder, 127);
4441 }
4442 };
4443 var RleEncoder = class extends Encoder {
4444 /**
4445 * @param {function(Encoder, T):void} writer
4446 */
4447 constructor(writer) {
4448 super();
4449 this.w = writer;
4450 this.s = null;
4451 this.count = 0;
4452 }
4453 /**
4454 * @param {T} v
4455 */
4456 write(v) {
4457 if (this.s === v) {
4458 this.count++;
4459 } else {
4460 if (this.count > 0) {
4461 writeVarUint(this, this.count - 1);
4462 }
4463 this.count = 1;
4464 this.w(this, v);
4465 this.s = v;
4466 }
4467 }
4468 };
4469 var flushUintOptRleEncoder = (encoder) => {
4470 if (encoder.count > 0) {
4471 writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s);
4472 if (encoder.count > 1) {
4473 writeVarUint(encoder.encoder, encoder.count - 2);
4474 }
4475 }
4476 };
4477 var UintOptRleEncoder = class {
4478 constructor() {
4479 this.encoder = new Encoder();
4480 this.s = 0;
4481 this.count = 0;
4482 }
4483 /**
4484 * @param {number} v
4485 */
4486 write(v) {
4487 if (this.s === v) {
4488 this.count++;
4489 } else {
4490 flushUintOptRleEncoder(this);
4491 this.count = 1;
4492 this.s = v;
4493 }
4494 }
4495 toUint8Array() {
4496 flushUintOptRleEncoder(this);
4497 return toUint8Array(this.encoder);
4498 }
4499 };
4500 var flushIntDiffOptRleEncoder = (encoder) => {
4501 if (encoder.count > 0) {
4502 const encodedDiff = encoder.diff * 2 + (encoder.count === 1 ? 0 : 1);
4503 writeVarInt(encoder.encoder, encodedDiff);
4504 if (encoder.count > 1) {
4505 writeVarUint(encoder.encoder, encoder.count - 2);
4506 }
4507 }
4508 };
4509 var IntDiffOptRleEncoder = class {
4510 constructor() {
4511 this.encoder = new Encoder();
4512 this.s = 0;
4513 this.count = 0;
4514 this.diff = 0;
4515 }
4516 /**
4517 * @param {number} v
4518 */
4519 write(v) {
4520 if (this.diff === v - this.s) {
4521 this.s = v;
4522 this.count++;
4523 } else {
4524 flushIntDiffOptRleEncoder(this);
4525 this.count = 1;
4526 this.diff = v - this.s;
4527 this.s = v;
4528 }
4529 }
4530 toUint8Array() {
4531 flushIntDiffOptRleEncoder(this);
4532 return toUint8Array(this.encoder);
4533 }
4534 };
4535 var StringEncoder = class {
4536 constructor() {
4537 this.sarr = [];
4538 this.s = "";
4539 this.lensE = new UintOptRleEncoder();
4540 }
4541 /**
4542 * @param {string} string
4543 */
4544 write(string) {
4545 this.s += string;
4546 if (this.s.length > 19) {
4547 this.sarr.push(this.s);
4548 this.s = "";
4549 }
4550 this.lensE.write(string.length);
4551 }
4552 toUint8Array() {
4553 const encoder = new Encoder();
4554 this.sarr.push(this.s);
4555 this.s = "";
4556 writeVarString(encoder, this.sarr.join(""));
4557 writeUint8Array(encoder, this.lensE.toUint8Array());
4558 return toUint8Array(encoder);
4559 }
4560 };
4561
4562 // node_modules/lib0/webcrypto.js
4563 var subtle = crypto.subtle;
4564 var getRandomValues = crypto.getRandomValues.bind(crypto);
4565
4566 // node_modules/lib0/random.js
4567 var rand = Math.random;
4568 var uint32 = () => getRandomValues(new Uint32Array(1))[0];
4569 var uuidv4Template = "10000000-1000-4000-8000" + -1e11;
4570 var uuidv4 = () => uuidv4Template.replace(
4571 /[018]/g,
4572 /** @param {number} c */
4573 (c) => (c ^ uint32() & 15 >> c / 4).toString(16)
4574 );
4575
4576 // node_modules/lib0/time.js
4577 var getUnixTime = Date.now;
4578
4579 // node_modules/lib0/promise.js
4580 var create4 = (f) => (
4581 /** @type {Promise<T>} */
4582 new Promise(f)
4583 );
4584 var all = Promise.all.bind(Promise);
4585 var reject = (reason) => Promise.reject(reason);
4586 var resolve = (res) => Promise.resolve(res);
4587
4588 // node_modules/lib0/pair.js
4589 var Pair = class {
4590 /**
4591 * @param {L} left
4592 * @param {R} right
4593 */
4594 constructor(left, right) {
4595 this.left = left;
4596 this.right = right;
4597 }
4598 };
4599 var create5 = (left, right) => new Pair(left, right);
4600
4601 // node_modules/lib0/dom.js
4602 var doc = (
4603 /** @type {Document} */
4604 typeof document !== "undefined" ? document : {}
4605 );
4606 var domParser = (
4607 /** @type {DOMParser} */
4608 typeof DOMParser !== "undefined" ? new DOMParser() : null
4609 );
4610 var mapToStyleString = (m) => map(m, (value, key) => `${key}:${value};`).join("");
4611 var ELEMENT_NODE = doc.ELEMENT_NODE;
4612 var TEXT_NODE = doc.TEXT_NODE;
4613 var CDATA_SECTION_NODE = doc.CDATA_SECTION_NODE;
4614 var COMMENT_NODE = doc.COMMENT_NODE;
4615 var DOCUMENT_NODE = doc.DOCUMENT_NODE;
4616 var DOCUMENT_TYPE_NODE = doc.DOCUMENT_TYPE_NODE;
4617 var DOCUMENT_FRAGMENT_NODE = doc.DOCUMENT_FRAGMENT_NODE;
4618
4619 // node_modules/lib0/symbol.js
4620 var create6 = Symbol;
4621
4622 // node_modules/lib0/logging.common.js
4623 var BOLD = create6();
4624 var UNBOLD = create6();
4625 var BLUE = create6();
4626 var GREY = create6();
4627 var GREEN = create6();
4628 var RED = create6();
4629 var PURPLE = create6();
4630 var ORANGE = create6();
4631 var UNCOLOR = create6();
4632 var computeNoColorLoggingArgs = (args2) => {
4633 const strBuilder = [];
4634 const logArgs = [];
4635 let i = 0;
4636 for (; i < args2.length; i++) {
4637 const arg = args2[i];
4638 if (arg.constructor === String || arg.constructor === Number) {
4639 strBuilder.push(arg);
4640 } else if (arg.constructor === Object) {
4641 logArgs.push(JSON.stringify(arg));
4642 }
4643 }
4644 return logArgs;
4645 };
4646 var loggingColors = [GREEN, PURPLE, ORANGE, BLUE];
4647 var nextColor = 0;
4648 var lastLoggingTime = getUnixTime();
4649 var createModuleLogger = (_print, moduleName) => {
4650 const color = loggingColors[nextColor];
4651 const debugRegexVar = getVariable("log");
4652 const doLogging = debugRegexVar !== null && (debugRegexVar === "*" || debugRegexVar === "true" || new RegExp(debugRegexVar, "gi").test(moduleName));
4653 nextColor = (nextColor + 1) % loggingColors.length;
4654 moduleName += ": ";
4655 return !doLogging ? nop : (...args2) => {
4656 const timeNow = getUnixTime();
4657 const timeDiff = timeNow - lastLoggingTime;
4658 lastLoggingTime = timeNow;
4659 _print(
4660 color,
4661 moduleName,
4662 UNCOLOR,
4663 ...args2.map(
4664 (arg) => typeof arg === "string" || typeof arg === "symbol" ? arg : JSON.stringify(arg)
4665 ),
4666 color,
4667 " +" + timeDiff + "ms"
4668 );
4669 };
4670 };
4671
4672 // node_modules/lib0/logging.js
4673 var _browserStyleMap = {
4674 [BOLD]: create5("font-weight", "bold"),
4675 [UNBOLD]: create5("font-weight", "normal"),
4676 [BLUE]: create5("color", "blue"),
4677 [GREEN]: create5("color", "green"),
4678 [GREY]: create5("color", "grey"),
4679 [RED]: create5("color", "red"),
4680 [PURPLE]: create5("color", "purple"),
4681 [ORANGE]: create5("color", "orange"),
4682 // not well supported in chrome when debugging node with inspector - TODO: deprecate
4683 [UNCOLOR]: create5("color", "black")
4684 };
4685 var computeBrowserLoggingArgs = (args2) => {
4686 const strBuilder = [];
4687 const styles = [];
4688 const currentStyle = create();
4689 let logArgs = [];
4690 let i = 0;
4691 for (; i < args2.length; i++) {
4692 const arg = args2[i];
4693 const style = _browserStyleMap[arg];
4694 if (style !== void 0) {
4695 currentStyle.set(style.left, style.right);
4696 } else {
4697 if (arg.constructor === String || arg.constructor === Number) {
4698 const style2 = mapToStyleString(currentStyle);
4699 if (i > 0 || style2.length > 0) {
4700 strBuilder.push("%c" + arg);
4701 styles.push(style2);
4702 } else {
4703 strBuilder.push(arg);
4704 }
4705 } else {
4706 break;
4707 }
4708 }
4709 }
4710 if (i > 0) {
4711 logArgs = styles;
4712 logArgs.unshift(strBuilder.join(""));
4713 }
4714 for (; i < args2.length; i++) {
4715 const arg = args2[i];
4716 if (!(arg instanceof Symbol)) {
4717 logArgs.push(arg);
4718 }
4719 }
4720 return logArgs;
4721 };
4722 var computeLoggingArgs = supportsColor ? computeBrowserLoggingArgs : computeNoColorLoggingArgs;
4723 var print = (...args2) => {
4724 console.log(...computeLoggingArgs(args2));
4725 vconsoles.forEach((vc) => vc.print(args2));
4726 };
4727 var vconsoles = create2();
4728 var createModuleLogger2 = (moduleName) => createModuleLogger(print, moduleName);
4729
4730 // node_modules/lib0/iterator.js
4731 var createIterator = (next) => ({
4732 /**
4733 * @return {IterableIterator<T>}
4734 */
4735 [Symbol.iterator]() {
4736 return this;
4737 },
4738 // @ts-ignore
4739 next
4740 });
4741 var iteratorFilter = (iterator, filter) => createIterator(() => {
4742 let res;
4743 do {
4744 res = iterator.next();
4745 } while (!res.done && !filter(res.value));
4746 return res;
4747 });
4748 var iteratorMap = (iterator, fmap) => createIterator(() => {
4749 const { done, value } = iterator.next();
4750 return { done, value: done ? void 0 : fmap(value) };
4751 });
4752
4753 // node_modules/yjs/dist/yjs.mjs
4754 var AbstractConnector = class extends Observable {
4755 /**
4756 * @param {Doc} ydoc
4757 * @param {any} awareness
4758 */
4759 constructor(ydoc, awareness) {
4760 super();
4761 this.doc = ydoc;
4762 this.awareness = awareness;
4763 }
4764 };
4765 var DeleteItem = class {
4766 /**
4767 * @param {number} clock
4768 * @param {number} len
4769 */
4770 constructor(clock, len) {
4771 this.clock = clock;
4772 this.len = len;
4773 }
4774 };
4775 var DeleteSet = class {
4776 constructor() {
4777 this.clients = /* @__PURE__ */ new Map();
4778 }
4779 };
4780 var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes, clientid) => {
4781 const structs = (
4782 /** @type {Array<GC|Item>} */
4783 transaction.doc.store.clients.get(clientid)
4784 );
4785 for (let i = 0; i < deletes.length; i++) {
4786 const del2 = deletes[i];
4787 iterateStructs(transaction, structs, del2.clock, del2.len, f);
4788 }
4789 });
4790 var findIndexDS = (dis, clock) => {
4791 let left = 0;
4792 let right = dis.length - 1;
4793 while (left <= right) {
4794 const midindex = floor((left + right) / 2);
4795 const mid = dis[midindex];
4796 const midclock = mid.clock;
4797 if (midclock <= clock) {
4798 if (clock < midclock + mid.len) {
4799 return midindex;
4800 }
4801 left = midindex + 1;
4802 } else {
4803 right = midindex - 1;
4804 }
4805 }
4806 return null;
4807 };
4808 var isDeleted = (ds, id2) => {
4809 const dis = ds.clients.get(id2.client);
4810 return dis !== void 0 && findIndexDS(dis, id2.clock) !== null;
4811 };
4812 var sortAndMergeDeleteSet = (ds) => {
4813 ds.clients.forEach((dels) => {
4814 dels.sort((a, b) => a.clock - b.clock);
4815 let i, j;
4816 for (i = 1, j = 1; i < dels.length; i++) {
4817 const left = dels[j - 1];
4818 const right = dels[i];
4819 if (left.clock + left.len >= right.clock) {
4820 left.len = max(left.len, right.clock + right.len - left.clock);
4821 } else {
4822 if (j < i) {
4823 dels[j] = right;
4824 }
4825 j++;
4826 }
4827 }
4828 dels.length = j;
4829 });
4830 };
4831 var mergeDeleteSets = (dss) => {
4832 const merged = new DeleteSet();
4833 for (let dssI = 0; dssI < dss.length; dssI++) {
4834 dss[dssI].clients.forEach((delsLeft, client) => {
4835 if (!merged.clients.has(client)) {
4836 const dels = delsLeft.slice();
4837 for (let i = dssI + 1; i < dss.length; i++) {
4838 appendTo(dels, dss[i].clients.get(client) || []);
4839 }
4840 merged.clients.set(client, dels);
4841 }
4842 });
4843 }
4844 sortAndMergeDeleteSet(merged);
4845 return merged;
4846 };
4847 var addToDeleteSet = (ds, client, clock, length3) => {
4848 setIfUndefined(ds.clients, client, () => (
4849 /** @type {Array<DeleteItem>} */
4850 []
4851 )).push(new DeleteItem(clock, length3));
4852 };
4853 var createDeleteSet = () => new DeleteSet();
4854 var createDeleteSetFromStructStore = (ss) => {
4855 const ds = createDeleteSet();
4856 ss.clients.forEach((structs, client) => {
4857 const dsitems = [];
4858 for (let i = 0; i < structs.length; i++) {
4859 const struct = structs[i];
4860 if (struct.deleted) {
4861 const clock = struct.id.clock;
4862 let len = struct.length;
4863 if (i + 1 < structs.length) {
4864 for (let next = structs[i + 1]; i + 1 < structs.length && next.deleted; next = structs[++i + 1]) {
4865 len += next.length;
4866 }
4867 }
4868 dsitems.push(new DeleteItem(clock, len));
4869 }
4870 }
4871 if (dsitems.length > 0) {
4872 ds.clients.set(client, dsitems);
4873 }
4874 });
4875 return ds;
4876 };
4877 var writeDeleteSet = (encoder, ds) => {
4878 writeVarUint(encoder.restEncoder, ds.clients.size);
4879 from(ds.clients.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, dsitems]) => {
4880 encoder.resetDsCurVal();
4881 writeVarUint(encoder.restEncoder, client);
4882 const len = dsitems.length;
4883 writeVarUint(encoder.restEncoder, len);
4884 for (let i = 0; i < len; i++) {
4885 const item = dsitems[i];
4886 encoder.writeDsClock(item.clock);
4887 encoder.writeDsLen(item.len);
4888 }
4889 });
4890 };
4891 var readDeleteSet = (decoder) => {
4892 const ds = new DeleteSet();
4893 const numClients = readVarUint(decoder.restDecoder);
4894 for (let i = 0; i < numClients; i++) {
4895 decoder.resetDsCurVal();
4896 const client = readVarUint(decoder.restDecoder);
4897 const numberOfDeletes = readVarUint(decoder.restDecoder);
4898 if (numberOfDeletes > 0) {
4899 const dsField = setIfUndefined(ds.clients, client, () => (
4900 /** @type {Array<DeleteItem>} */
4901 []
4902 ));
4903 for (let i2 = 0; i2 < numberOfDeletes; i2++) {
4904 dsField.push(new DeleteItem(decoder.readDsClock(), decoder.readDsLen()));
4905 }
4906 }
4907 }
4908 return ds;
4909 };
4910 var readAndApplyDeleteSet = (decoder, transaction, store2) => {
4911 const unappliedDS = new DeleteSet();
4912 const numClients = readVarUint(decoder.restDecoder);
4913 for (let i = 0; i < numClients; i++) {
4914 decoder.resetDsCurVal();
4915 const client = readVarUint(decoder.restDecoder);
4916 const numberOfDeletes = readVarUint(decoder.restDecoder);
4917 const structs = store2.clients.get(client) || [];
4918 const state = getState(store2, client);
4919 for (let i2 = 0; i2 < numberOfDeletes; i2++) {
4920 const clock = decoder.readDsClock();
4921 const clockEnd = clock + decoder.readDsLen();
4922 if (clock < state) {
4923 if (state < clockEnd) {
4924 addToDeleteSet(unappliedDS, client, state, clockEnd - state);
4925 }
4926 let index = findIndexSS(structs, clock);
4927 let struct = structs[index];
4928 if (!struct.deleted && struct.id.clock < clock) {
4929 structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock));
4930 index++;
4931 }
4932 while (index < structs.length) {
4933 struct = structs[index++];
4934 if (struct.id.clock < clockEnd) {
4935 if (!struct.deleted) {
4936 if (clockEnd < struct.id.clock + struct.length) {
4937 structs.splice(index, 0, splitItem(transaction, struct, clockEnd - struct.id.clock));
4938 }
4939 struct.delete(transaction);
4940 }
4941 } else {
4942 break;
4943 }
4944 }
4945 } else {
4946 addToDeleteSet(unappliedDS, client, clock, clockEnd - clock);
4947 }
4948 }
4949 }
4950 if (unappliedDS.clients.size > 0) {
4951 const ds = new UpdateEncoderV2();
4952 writeVarUint(ds.restEncoder, 0);
4953 writeDeleteSet(ds, unappliedDS);
4954 return ds.toUint8Array();
4955 }
4956 return null;
4957 };
4958 var equalDeleteSets = (ds1, ds2) => {
4959 if (ds1.clients.size !== ds2.clients.size) return false;
4960 for (const [client, deleteItems1] of ds1.clients.entries()) {
4961 const deleteItems2 = (
4962 /** @type {Array<import('../internals.js').DeleteItem>} */
4963 ds2.clients.get(client)
4964 );
4965 if (deleteItems2 === void 0 || deleteItems1.length !== deleteItems2.length) return false;
4966 for (let i = 0; i < deleteItems1.length; i++) {
4967 const di1 = deleteItems1[i];
4968 const di2 = deleteItems2[i];
4969 if (di1.clock !== di2.clock || di1.len !== di2.len) {
4970 return false;
4971 }
4972 }
4973 }
4974 return true;
4975 };
4976 var generateNewClientId = uint32;
4977 var Doc = class _Doc extends Observable {
4978 /**
4979 * @param {DocOpts} opts configuration
4980 */
4981 constructor({ guid = uuidv4(), collectionid = null, gc = true, gcFilter = () => true, meta = null, autoLoad = false, shouldLoad = true } = {}) {
4982 super();
4983 this.gc = gc;
4984 this.gcFilter = gcFilter;
4985 this.clientID = generateNewClientId();
4986 this.guid = guid;
4987 this.collectionid = collectionid;
4988 this.share = /* @__PURE__ */ new Map();
4989 this.store = new StructStore();
4990 this._transaction = null;
4991 this._transactionCleanups = [];
4992 this.subdocs = /* @__PURE__ */ new Set();
4993 this._item = null;
4994 this.shouldLoad = shouldLoad;
4995 this.autoLoad = autoLoad;
4996 this.meta = meta;
4997 this.isLoaded = false;
4998 this.isSynced = false;
4999 this.whenLoaded = create4((resolve2) => {
5000 this.on("load", () => {
5001 this.isLoaded = true;
5002 resolve2(this);
5003 });
5004 });
5005 const provideSyncedPromise = () => create4((resolve2) => {
5006 const eventHandler = (isSynced) => {
5007 if (isSynced === void 0 || isSynced === true) {
5008 this.off("sync", eventHandler);
5009 resolve2();
5010 }
5011 };
5012 this.on("sync", eventHandler);
5013 });
5014 this.on("sync", (isSynced) => {
5015 if (isSynced === false && this.isSynced) {
5016 this.whenSynced = provideSyncedPromise();
5017 }
5018 this.isSynced = isSynced === void 0 || isSynced === true;
5019 if (!this.isLoaded) {
5020 this.emit("load", []);
5021 }
5022 });
5023 this.whenSynced = provideSyncedPromise();
5024 }
5025 /**
5026 * Notify the parent document that you request to load data into this subdocument (if it is a subdocument).
5027 *
5028 * `load()` might be used in the future to request any provider to load the most current data.
5029 *
5030 * It is safe to call `load()` multiple times.
5031 */
5032 load() {
5033 const item = this._item;
5034 if (item !== null && !this.shouldLoad) {
5035 transact(
5036 /** @type {any} */
5037 item.parent.doc,
5038 (transaction) => {
5039 transaction.subdocsLoaded.add(this);
5040 },
5041 null,
5042 true
5043 );
5044 }
5045 this.shouldLoad = true;
5046 }
5047 getSubdocs() {
5048 return this.subdocs;
5049 }
5050 getSubdocGuids() {
5051 return new Set(from(this.subdocs).map((doc2) => doc2.guid));
5052 }
5053 /**
5054 * Changes that happen inside of a transaction are bundled. This means that
5055 * the observer fires _after_ the transaction is finished and that all changes
5056 * that happened inside of the transaction are sent as one message to the
5057 * other peers.
5058 *
5059 * @template T
5060 * @param {function(Transaction):T} f The function that should be executed as a transaction
5061 * @param {any} [origin] Origin of who started the transaction. Will be stored on transaction.origin
5062 * @return T
5063 *
5064 * @public
5065 */
5066 transact(f, origin = null) {
5067 return transact(this, f, origin);
5068 }
5069 /**
5070 * Define a shared data type.
5071 *
5072 * Multiple calls of `y.get(name, TypeConstructor)` yield the same result
5073 * and do not overwrite each other. I.e.
5074 * `y.define(name, Y.Array) === y.define(name, Y.Array)`
5075 *
5076 * After this method is called, the type is also available on `y.share.get(name)`.
5077 *
5078 * *Best Practices:*
5079 * Define all types right after the Yjs instance is created and store them in a separate object.
5080 * Also use the typed methods `getText(name)`, `getArray(name)`, ..
5081 *
5082 * @example
5083 * const y = new Y(..)
5084 * const appState = {
5085 * document: y.getText('document')
5086 * comments: y.getArray('comments')
5087 * }
5088 *
5089 * @param {string} name
5090 * @param {Function} TypeConstructor The constructor of the type definition. E.g. Y.Text, Y.Array, Y.Map, ...
5091 * @return {AbstractType<any>} The created type. Constructed with TypeConstructor
5092 *
5093 * @public
5094 */
5095 get(name, TypeConstructor = AbstractType) {
5096 const type = setIfUndefined(this.share, name, () => {
5097 const t = new TypeConstructor();
5098 t._integrate(this, null);
5099 return t;
5100 });
5101 const Constr = type.constructor;
5102 if (TypeConstructor !== AbstractType && Constr !== TypeConstructor) {
5103 if (Constr === AbstractType) {
5104 const t = new TypeConstructor();
5105 t._map = type._map;
5106 type._map.forEach(
5107 /** @param {Item?} n */
5108 (n) => {
5109 for (; n !== null; n = n.left) {
5110 n.parent = t;
5111 }
5112 }
5113 );
5114 t._start = type._start;
5115 for (let n = t._start; n !== null; n = n.right) {
5116 n.parent = t;
5117 }
5118 t._length = type._length;
5119 this.share.set(name, t);
5120 t._integrate(this, null);
5121 return t;
5122 } else {
5123 throw new Error(`Type with the name ${name} has already been defined with a different constructor`);
5124 }
5125 }
5126 return type;
5127 }
5128 /**
5129 * @template T
5130 * @param {string} [name]
5131 * @return {YArray<T>}
5132 *
5133 * @public
5134 */
5135 getArray(name = "") {
5136 return this.get(name, YArray);
5137 }
5138 /**
5139 * @param {string} [name]
5140 * @return {YText}
5141 *
5142 * @public
5143 */
5144 getText(name = "") {
5145 return this.get(name, YText);
5146 }
5147 /**
5148 * @template T
5149 * @param {string} [name]
5150 * @return {YMap<T>}
5151 *
5152 * @public
5153 */
5154 getMap(name = "") {
5155 return this.get(name, YMap);
5156 }
5157 /**
5158 * @param {string} [name]
5159 * @return {YXmlFragment}
5160 *
5161 * @public
5162 */
5163 getXmlFragment(name = "") {
5164 return this.get(name, YXmlFragment);
5165 }
5166 /**
5167 * Converts the entire document into a js object, recursively traversing each yjs type
5168 * Doesn't log types that have not been defined (using ydoc.getType(..)).
5169 *
5170 * @deprecated Do not use this method and rather call toJSON directly on the shared types.
5171 *
5172 * @return {Object<string, any>}
5173 */
5174 toJSON() {
5175 const doc2 = {};
5176 this.share.forEach((value, key) => {
5177 doc2[key] = value.toJSON();
5178 });
5179 return doc2;
5180 }
5181 /**
5182 * Emit `destroy` event and unregister all event handlers.
5183 */
5184 destroy() {
5185 from(this.subdocs).forEach((subdoc) => subdoc.destroy());
5186 const item = this._item;
5187 if (item !== null) {
5188 this._item = null;
5189 const content = (
5190 /** @type {ContentDoc} */
5191 item.content
5192 );
5193 content.doc = new _Doc({ guid: this.guid, ...content.opts, shouldLoad: false });
5194 content.doc._item = item;
5195 transact(
5196 /** @type {any} */
5197 item.parent.doc,
5198 (transaction) => {
5199 const doc2 = content.doc;
5200 if (!item.deleted) {
5201 transaction.subdocsAdded.add(doc2);
5202 }
5203 transaction.subdocsRemoved.add(this);
5204 },
5205 null,
5206 true
5207 );
5208 }
5209 this.emit("destroyed", [true]);
5210 this.emit("destroy", [this]);
5211 super.destroy();
5212 }
5213 /**
5214 * @param {string} eventName
5215 * @param {function(...any):any} f
5216 */
5217 on(eventName, f) {
5218 super.on(eventName, f);
5219 }
5220 /**
5221 * @param {string} eventName
5222 * @param {function} f
5223 */
5224 off(eventName, f) {
5225 super.off(eventName, f);
5226 }
5227 };
5228 var DSDecoderV1 = class {
5229 /**
5230 * @param {decoding.Decoder} decoder
5231 */
5232 constructor(decoder) {
5233 this.restDecoder = decoder;
5234 }
5235 resetDsCurVal() {
5236 }
5237 /**
5238 * @return {number}
5239 */
5240 readDsClock() {
5241 return readVarUint(this.restDecoder);
5242 }
5243 /**
5244 * @return {number}
5245 */
5246 readDsLen() {
5247 return readVarUint(this.restDecoder);
5248 }
5249 };
5250 var UpdateDecoderV1 = class extends DSDecoderV1 {
5251 /**
5252 * @return {ID}
5253 */
5254 readLeftID() {
5255 return createID(readVarUint(this.restDecoder), readVarUint(this.restDecoder));
5256 }
5257 /**
5258 * @return {ID}
5259 */
5260 readRightID() {
5261 return createID(readVarUint(this.restDecoder), readVarUint(this.restDecoder));
5262 }
5263 /**
5264 * Read the next client id.
5265 * Use this in favor of readID whenever possible to reduce the number of objects created.
5266 */
5267 readClient() {
5268 return readVarUint(this.restDecoder);
5269 }
5270 /**
5271 * @return {number} info An unsigned 8-bit integer
5272 */
5273 readInfo() {
5274 return readUint8(this.restDecoder);
5275 }
5276 /**
5277 * @return {string}
5278 */
5279 readString() {
5280 return readVarString(this.restDecoder);
5281 }
5282 /**
5283 * @return {boolean} isKey
5284 */
5285 readParentInfo() {
5286 return readVarUint(this.restDecoder) === 1;
5287 }
5288 /**
5289 * @return {number} info An unsigned 8-bit integer
5290 */
5291 readTypeRef() {
5292 return readVarUint(this.restDecoder);
5293 }
5294 /**
5295 * Write len of a struct - well suited for Opt RLE encoder.
5296 *
5297 * @return {number} len
5298 */
5299 readLen() {
5300 return readVarUint(this.restDecoder);
5301 }
5302 /**
5303 * @return {any}
5304 */
5305 readAny() {
5306 return readAny(this.restDecoder);
5307 }
5308 /**
5309 * @return {Uint8Array}
5310 */
5311 readBuf() {
5312 return copyUint8Array(readVarUint8Array(this.restDecoder));
5313 }
5314 /**
5315 * Legacy implementation uses JSON parse. We use any-decoding in v2.
5316 *
5317 * @return {any}
5318 */
5319 readJSON() {
5320 return JSON.parse(readVarString(this.restDecoder));
5321 }
5322 /**
5323 * @return {string}
5324 */
5325 readKey() {
5326 return readVarString(this.restDecoder);
5327 }
5328 };
5329 var DSDecoderV2 = class {
5330 /**
5331 * @param {decoding.Decoder} decoder
5332 */
5333 constructor(decoder) {
5334 this.dsCurrVal = 0;
5335 this.restDecoder = decoder;
5336 }
5337 resetDsCurVal() {
5338 this.dsCurrVal = 0;
5339 }
5340 /**
5341 * @return {number}
5342 */
5343 readDsClock() {
5344 this.dsCurrVal += readVarUint(this.restDecoder);
5345 return this.dsCurrVal;
5346 }
5347 /**
5348 * @return {number}
5349 */
5350 readDsLen() {
5351 const diff = readVarUint(this.restDecoder) + 1;
5352 this.dsCurrVal += diff;
5353 return diff;
5354 }
5355 };
5356 var UpdateDecoderV2 = class extends DSDecoderV2 {
5357 /**
5358 * @param {decoding.Decoder} decoder
5359 */
5360 constructor(decoder) {
5361 super(decoder);
5362 this.keys = [];
5363 readVarUint(decoder);
5364 this.keyClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder));
5365 this.clientDecoder = new UintOptRleDecoder(readVarUint8Array(decoder));
5366 this.leftClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder));
5367 this.rightClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder));
5368 this.infoDecoder = new RleDecoder(readVarUint8Array(decoder), readUint8);
5369 this.stringDecoder = new StringDecoder(readVarUint8Array(decoder));
5370 this.parentInfoDecoder = new RleDecoder(readVarUint8Array(decoder), readUint8);
5371 this.typeRefDecoder = new UintOptRleDecoder(readVarUint8Array(decoder));
5372 this.lenDecoder = new UintOptRleDecoder(readVarUint8Array(decoder));
5373 }
5374 /**
5375 * @return {ID}
5376 */
5377 readLeftID() {
5378 return new ID(this.clientDecoder.read(), this.leftClockDecoder.read());
5379 }
5380 /**
5381 * @return {ID}
5382 */
5383 readRightID() {
5384 return new ID(this.clientDecoder.read(), this.rightClockDecoder.read());
5385 }
5386 /**
5387 * Read the next client id.
5388 * Use this in favor of readID whenever possible to reduce the number of objects created.
5389 */
5390 readClient() {
5391 return this.clientDecoder.read();
5392 }
5393 /**
5394 * @return {number} info An unsigned 8-bit integer
5395 */
5396 readInfo() {
5397 return (
5398 /** @type {number} */
5399 this.infoDecoder.read()
5400 );
5401 }
5402 /**
5403 * @return {string}
5404 */
5405 readString() {
5406 return this.stringDecoder.read();
5407 }
5408 /**
5409 * @return {boolean}
5410 */
5411 readParentInfo() {
5412 return this.parentInfoDecoder.read() === 1;
5413 }
5414 /**
5415 * @return {number} An unsigned 8-bit integer
5416 */
5417 readTypeRef() {
5418 return this.typeRefDecoder.read();
5419 }
5420 /**
5421 * Write len of a struct - well suited for Opt RLE encoder.
5422 *
5423 * @return {number}
5424 */
5425 readLen() {
5426 return this.lenDecoder.read();
5427 }
5428 /**
5429 * @return {any}
5430 */
5431 readAny() {
5432 return readAny(this.restDecoder);
5433 }
5434 /**
5435 * @return {Uint8Array}
5436 */
5437 readBuf() {
5438 return readVarUint8Array(this.restDecoder);
5439 }
5440 /**
5441 * This is mainly here for legacy purposes.
5442 *
5443 * 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.
5444 *
5445 * @return {any}
5446 */
5447 readJSON() {
5448 return readAny(this.restDecoder);
5449 }
5450 /**
5451 * @return {string}
5452 */
5453 readKey() {
5454 const keyClock = this.keyClockDecoder.read();
5455 if (keyClock < this.keys.length) {
5456 return this.keys[keyClock];
5457 } else {
5458 const key = this.stringDecoder.read();
5459 this.keys.push(key);
5460 return key;
5461 }
5462 }
5463 };
5464 var DSEncoderV1 = class {
5465 constructor() {
5466 this.restEncoder = createEncoder();
5467 }
5468 toUint8Array() {
5469 return toUint8Array(this.restEncoder);
5470 }
5471 resetDsCurVal() {
5472 }
5473 /**
5474 * @param {number} clock
5475 */
5476 writeDsClock(clock) {
5477 writeVarUint(this.restEncoder, clock);
5478 }
5479 /**
5480 * @param {number} len
5481 */
5482 writeDsLen(len) {
5483 writeVarUint(this.restEncoder, len);
5484 }
5485 };
5486 var UpdateEncoderV1 = class extends DSEncoderV1 {
5487 /**
5488 * @param {ID} id
5489 */
5490 writeLeftID(id2) {
5491 writeVarUint(this.restEncoder, id2.client);
5492 writeVarUint(this.restEncoder, id2.clock);
5493 }
5494 /**
5495 * @param {ID} id
5496 */
5497 writeRightID(id2) {
5498 writeVarUint(this.restEncoder, id2.client);
5499 writeVarUint(this.restEncoder, id2.clock);
5500 }
5501 /**
5502 * Use writeClient and writeClock instead of writeID if possible.
5503 * @param {number} client
5504 */
5505 writeClient(client) {
5506 writeVarUint(this.restEncoder, client);
5507 }
5508 /**
5509 * @param {number} info An unsigned 8-bit integer
5510 */
5511 writeInfo(info) {
5512 writeUint8(this.restEncoder, info);
5513 }
5514 /**
5515 * @param {string} s
5516 */
5517 writeString(s) {
5518 writeVarString(this.restEncoder, s);
5519 }
5520 /**
5521 * @param {boolean} isYKey
5522 */
5523 writeParentInfo(isYKey) {
5524 writeVarUint(this.restEncoder, isYKey ? 1 : 0);
5525 }
5526 /**
5527 * @param {number} info An unsigned 8-bit integer
5528 */
5529 writeTypeRef(info) {
5530 writeVarUint(this.restEncoder, info);
5531 }
5532 /**
5533 * Write len of a struct - well suited for Opt RLE encoder.
5534 *
5535 * @param {number} len
5536 */
5537 writeLen(len) {
5538 writeVarUint(this.restEncoder, len);
5539 }
5540 /**
5541 * @param {any} any
5542 */
5543 writeAny(any2) {
5544 writeAny(this.restEncoder, any2);
5545 }
5546 /**
5547 * @param {Uint8Array} buf
5548 */
5549 writeBuf(buf) {
5550 writeVarUint8Array(this.restEncoder, buf);
5551 }
5552 /**
5553 * @param {any} embed
5554 */
5555 writeJSON(embed) {
5556 writeVarString(this.restEncoder, JSON.stringify(embed));
5557 }
5558 /**
5559 * @param {string} key
5560 */
5561 writeKey(key) {
5562 writeVarString(this.restEncoder, key);
5563 }
5564 };
5565 var DSEncoderV2 = class {
5566 constructor() {
5567 this.restEncoder = createEncoder();
5568 this.dsCurrVal = 0;
5569 }
5570 toUint8Array() {
5571 return toUint8Array(this.restEncoder);
5572 }
5573 resetDsCurVal() {
5574 this.dsCurrVal = 0;
5575 }
5576 /**
5577 * @param {number} clock
5578 */
5579 writeDsClock(clock) {
5580 const diff = clock - this.dsCurrVal;
5581 this.dsCurrVal = clock;
5582 writeVarUint(this.restEncoder, diff);
5583 }
5584 /**
5585 * @param {number} len
5586 */
5587 writeDsLen(len) {
5588 if (len === 0) {
5589 unexpectedCase();
5590 }
5591 writeVarUint(this.restEncoder, len - 1);
5592 this.dsCurrVal += len;
5593 }
5594 };
5595 var UpdateEncoderV2 = class extends DSEncoderV2 {
5596 constructor() {
5597 super();
5598 this.keyMap = /* @__PURE__ */ new Map();
5599 this.keyClock = 0;
5600 this.keyClockEncoder = new IntDiffOptRleEncoder();
5601 this.clientEncoder = new UintOptRleEncoder();
5602 this.leftClockEncoder = new IntDiffOptRleEncoder();
5603 this.rightClockEncoder = new IntDiffOptRleEncoder();
5604 this.infoEncoder = new RleEncoder(writeUint8);
5605 this.stringEncoder = new StringEncoder();
5606 this.parentInfoEncoder = new RleEncoder(writeUint8);
5607 this.typeRefEncoder = new UintOptRleEncoder();
5608 this.lenEncoder = new UintOptRleEncoder();
5609 }
5610 toUint8Array() {
5611 const encoder = createEncoder();
5612 writeVarUint(encoder, 0);
5613 writeVarUint8Array(encoder, this.keyClockEncoder.toUint8Array());
5614 writeVarUint8Array(encoder, this.clientEncoder.toUint8Array());
5615 writeVarUint8Array(encoder, this.leftClockEncoder.toUint8Array());
5616 writeVarUint8Array(encoder, this.rightClockEncoder.toUint8Array());
5617 writeVarUint8Array(encoder, toUint8Array(this.infoEncoder));
5618 writeVarUint8Array(encoder, this.stringEncoder.toUint8Array());
5619 writeVarUint8Array(encoder, toUint8Array(this.parentInfoEncoder));
5620 writeVarUint8Array(encoder, this.typeRefEncoder.toUint8Array());
5621 writeVarUint8Array(encoder, this.lenEncoder.toUint8Array());
5622 writeUint8Array(encoder, toUint8Array(this.restEncoder));
5623 return toUint8Array(encoder);
5624 }
5625 /**
5626 * @param {ID} id
5627 */
5628 writeLeftID(id2) {
5629 this.clientEncoder.write(id2.client);
5630 this.leftClockEncoder.write(id2.clock);
5631 }
5632 /**
5633 * @param {ID} id
5634 */
5635 writeRightID(id2) {
5636 this.clientEncoder.write(id2.client);
5637 this.rightClockEncoder.write(id2.clock);
5638 }
5639 /**
5640 * @param {number} client
5641 */
5642 writeClient(client) {
5643 this.clientEncoder.write(client);
5644 }
5645 /**
5646 * @param {number} info An unsigned 8-bit integer
5647 */
5648 writeInfo(info) {
5649 this.infoEncoder.write(info);
5650 }
5651 /**
5652 * @param {string} s
5653 */
5654 writeString(s) {
5655 this.stringEncoder.write(s);
5656 }
5657 /**
5658 * @param {boolean} isYKey
5659 */
5660 writeParentInfo(isYKey) {
5661 this.parentInfoEncoder.write(isYKey ? 1 : 0);
5662 }
5663 /**
5664 * @param {number} info An unsigned 8-bit integer
5665 */
5666 writeTypeRef(info) {
5667 this.typeRefEncoder.write(info);
5668 }
5669 /**
5670 * Write len of a struct - well suited for Opt RLE encoder.
5671 *
5672 * @param {number} len
5673 */
5674 writeLen(len) {
5675 this.lenEncoder.write(len);
5676 }
5677 /**
5678 * @param {any} any
5679 */
5680 writeAny(any2) {
5681 writeAny(this.restEncoder, any2);
5682 }
5683 /**
5684 * @param {Uint8Array} buf
5685 */
5686 writeBuf(buf) {
5687 writeVarUint8Array(this.restEncoder, buf);
5688 }
5689 /**
5690 * This is mainly here for legacy purposes.
5691 *
5692 * 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.
5693 *
5694 * @param {any} embed
5695 */
5696 writeJSON(embed) {
5697 writeAny(this.restEncoder, embed);
5698 }
5699 /**
5700 * Property keys are often reused. For example, in y-prosemirror the key `bold` might
5701 * occur very often. For a 3d application, the key `position` might occur very often.
5702 *
5703 * We cache these keys in a Map and refer to them via a unique number.
5704 *
5705 * @param {string} key
5706 */
5707 writeKey(key) {
5708 const clock = this.keyMap.get(key);
5709 if (clock === void 0) {
5710 this.keyClockEncoder.write(this.keyClock++);
5711 this.stringEncoder.write(key);
5712 } else {
5713 this.keyClockEncoder.write(clock);
5714 }
5715 }
5716 };
5717 var writeStructs = (encoder, structs, client, clock) => {
5718 clock = max(clock, structs[0].id.clock);
5719 const startNewStructs = findIndexSS(structs, clock);
5720 writeVarUint(encoder.restEncoder, structs.length - startNewStructs);
5721 encoder.writeClient(client);
5722 writeVarUint(encoder.restEncoder, clock);
5723 const firstStruct = structs[startNewStructs];
5724 firstStruct.write(encoder, clock - firstStruct.id.clock);
5725 for (let i = startNewStructs + 1; i < structs.length; i++) {
5726 structs[i].write(encoder, 0);
5727 }
5728 };
5729 var writeClientsStructs = (encoder, store2, _sm) => {
5730 const sm = /* @__PURE__ */ new Map();
5731 _sm.forEach((clock, client) => {
5732 if (getState(store2, client) > clock) {
5733 sm.set(client, clock);
5734 }
5735 });
5736 getStateVector(store2).forEach((_clock, client) => {
5737 if (!_sm.has(client)) {
5738 sm.set(client, 0);
5739 }
5740 });
5741 writeVarUint(encoder.restEncoder, sm.size);
5742 from(sm.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, clock]) => {
5743 writeStructs(
5744 encoder,
5745 /** @type {Array<GC|Item>} */
5746 store2.clients.get(client),
5747 client,
5748 clock
5749 );
5750 });
5751 };
5752 var readClientsStructRefs = (decoder, doc2) => {
5753 const clientRefs = create();
5754 const numOfStateUpdates = readVarUint(decoder.restDecoder);
5755 for (let i = 0; i < numOfStateUpdates; i++) {
5756 const numberOfStructs = readVarUint(decoder.restDecoder);
5757 const refs = new Array(numberOfStructs);
5758 const client = decoder.readClient();
5759 let clock = readVarUint(decoder.restDecoder);
5760 clientRefs.set(client, { i: 0, refs });
5761 for (let i2 = 0; i2 < numberOfStructs; i2++) {
5762 const info = decoder.readInfo();
5763 switch (BITS5 & info) {
5764 case 0: {
5765 const len = decoder.readLen();
5766 refs[i2] = new GC(createID(client, clock), len);
5767 clock += len;
5768 break;
5769 }
5770 case 10: {
5771 const len = readVarUint(decoder.restDecoder);
5772 refs[i2] = new Skip(createID(client, clock), len);
5773 clock += len;
5774 break;
5775 }
5776 default: {
5777 const cantCopyParentInfo = (info & (BIT7 | BIT8)) === 0;
5778 const struct = new Item(
5779 createID(client, clock),
5780 null,
5781 // leftd
5782 (info & BIT8) === BIT8 ? decoder.readLeftID() : null,
5783 // origin
5784 null,
5785 // right
5786 (info & BIT7) === BIT7 ? decoder.readRightID() : null,
5787 // right origin
5788 cantCopyParentInfo ? decoder.readParentInfo() ? doc2.get(decoder.readString()) : decoder.readLeftID() : null,
5789 // parent
5790 cantCopyParentInfo && (info & BIT6) === BIT6 ? decoder.readString() : null,
5791 // parentSub
5792 readItemContent(decoder, info)
5793 // item content
5794 );
5795 refs[i2] = struct;
5796 clock += struct.length;
5797 }
5798 }
5799 }
5800 }
5801 return clientRefs;
5802 };
5803 var integrateStructs = (transaction, store2, clientsStructRefs) => {
5804 const stack = [];
5805 let clientsStructRefsIds = from(clientsStructRefs.keys()).sort((a, b) => a - b);
5806 if (clientsStructRefsIds.length === 0) {
5807 return null;
5808 }
5809 const getNextStructTarget = () => {
5810 if (clientsStructRefsIds.length === 0) {
5811 return null;
5812 }
5813 let nextStructsTarget = (
5814 /** @type {{i:number,refs:Array<GC|Item>}} */
5815 clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1])
5816 );
5817 while (nextStructsTarget.refs.length === nextStructsTarget.i) {
5818 clientsStructRefsIds.pop();
5819 if (clientsStructRefsIds.length > 0) {
5820 nextStructsTarget = /** @type {{i:number,refs:Array<GC|Item>}} */
5821 clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1]);
5822 } else {
5823 return null;
5824 }
5825 }
5826 return nextStructsTarget;
5827 };
5828 let curStructsTarget = getNextStructTarget();
5829 if (curStructsTarget === null && stack.length === 0) {
5830 return null;
5831 }
5832 const restStructs = new StructStore();
5833 const missingSV = /* @__PURE__ */ new Map();
5834 const updateMissingSv = (client, clock) => {
5835 const mclock = missingSV.get(client);
5836 if (mclock == null || mclock > clock) {
5837 missingSV.set(client, clock);
5838 }
5839 };
5840 let stackHead = (
5841 /** @type {any} */
5842 curStructsTarget.refs[
5843 /** @type {any} */
5844 curStructsTarget.i++
5845 ]
5846 );
5847 const state = /* @__PURE__ */ new Map();
5848 const addStackToRestSS = () => {
5849 for (const item of stack) {
5850 const client = item.id.client;
5851 const unapplicableItems = clientsStructRefs.get(client);
5852 if (unapplicableItems) {
5853 unapplicableItems.i--;
5854 restStructs.clients.set(client, unapplicableItems.refs.slice(unapplicableItems.i));
5855 clientsStructRefs.delete(client);
5856 unapplicableItems.i = 0;
5857 unapplicableItems.refs = [];
5858 } else {
5859 restStructs.clients.set(client, [item]);
5860 }
5861 clientsStructRefsIds = clientsStructRefsIds.filter((c) => c !== client);
5862 }
5863 stack.length = 0;
5864 };
5865 while (true) {
5866 if (stackHead.constructor !== Skip) {
5867 const localClock = setIfUndefined(state, stackHead.id.client, () => getState(store2, stackHead.id.client));
5868 const offset = localClock - stackHead.id.clock;
5869 if (offset < 0) {
5870 stack.push(stackHead);
5871 updateMissingSv(stackHead.id.client, stackHead.id.clock - 1);
5872 addStackToRestSS();
5873 } else {
5874 const missing = stackHead.getMissing(transaction, store2);
5875 if (missing !== null) {
5876 stack.push(stackHead);
5877 const structRefs = clientsStructRefs.get(
5878 /** @type {number} */
5879 missing
5880 ) || { refs: [], i: 0 };
5881 if (structRefs.refs.length === structRefs.i) {
5882 updateMissingSv(
5883 /** @type {number} */
5884 missing,
5885 getState(store2, missing)
5886 );
5887 addStackToRestSS();
5888 } else {
5889 stackHead = structRefs.refs[structRefs.i++];
5890 continue;
5891 }
5892 } else if (offset === 0 || offset < stackHead.length) {
5893 stackHead.integrate(transaction, offset);
5894 state.set(stackHead.id.client, stackHead.id.clock + stackHead.length);
5895 }
5896 }
5897 }
5898 if (stack.length > 0) {
5899 stackHead = /** @type {GC|Item} */
5900 stack.pop();
5901 } else if (curStructsTarget !== null && curStructsTarget.i < curStructsTarget.refs.length) {
5902 stackHead = /** @type {GC|Item} */
5903 curStructsTarget.refs[curStructsTarget.i++];
5904 } else {
5905 curStructsTarget = getNextStructTarget();
5906 if (curStructsTarget === null) {
5907 break;
5908 } else {
5909 stackHead = /** @type {GC|Item} */
5910 curStructsTarget.refs[curStructsTarget.i++];
5911 }
5912 }
5913 }
5914 if (restStructs.clients.size > 0) {
5915 const encoder = new UpdateEncoderV2();
5916 writeClientsStructs(encoder, restStructs, /* @__PURE__ */ new Map());
5917 writeVarUint(encoder.restEncoder, 0);
5918 return { missing: missingSV, update: encoder.toUint8Array() };
5919 }
5920 return null;
5921 };
5922 var writeStructsFromTransaction = (encoder, transaction) => writeClientsStructs(encoder, transaction.doc.store, transaction.beforeState);
5923 var readUpdateV2 = (decoder, ydoc, transactionOrigin, structDecoder = new UpdateDecoderV2(decoder)) => transact(ydoc, (transaction) => {
5924 transaction.local = false;
5925 let retry = false;
5926 const doc2 = transaction.doc;
5927 const store2 = doc2.store;
5928 const ss = readClientsStructRefs(structDecoder, doc2);
5929 const restStructs = integrateStructs(transaction, store2, ss);
5930 const pending = store2.pendingStructs;
5931 if (pending) {
5932 for (const [client, clock] of pending.missing) {
5933 if (clock < getState(store2, client)) {
5934 retry = true;
5935 break;
5936 }
5937 }
5938 if (restStructs) {
5939 for (const [client, clock] of restStructs.missing) {
5940 const mclock = pending.missing.get(client);
5941 if (mclock == null || mclock > clock) {
5942 pending.missing.set(client, clock);
5943 }
5944 }
5945 pending.update = mergeUpdatesV2([pending.update, restStructs.update]);
5946 }
5947 } else {
5948 store2.pendingStructs = restStructs;
5949 }
5950 const dsRest = readAndApplyDeleteSet(structDecoder, transaction, store2);
5951 if (store2.pendingDs) {
5952 const pendingDSUpdate = new UpdateDecoderV2(createDecoder(store2.pendingDs));
5953 readVarUint(pendingDSUpdate.restDecoder);
5954 const dsRest2 = readAndApplyDeleteSet(pendingDSUpdate, transaction, store2);
5955 if (dsRest && dsRest2) {
5956 store2.pendingDs = mergeUpdatesV2([dsRest, dsRest2]);
5957 } else {
5958 store2.pendingDs = dsRest || dsRest2;
5959 }
5960 } else {
5961 store2.pendingDs = dsRest;
5962 }
5963 if (retry) {
5964 const update = (
5965 /** @type {{update: Uint8Array}} */
5966 store2.pendingStructs.update
5967 );
5968 store2.pendingStructs = null;
5969 applyUpdateV2(transaction.doc, update);
5970 }
5971 }, transactionOrigin, false);
5972 var readUpdate = (decoder, ydoc, transactionOrigin) => readUpdateV2(decoder, ydoc, transactionOrigin, new UpdateDecoderV1(decoder));
5973 var applyUpdateV2 = (ydoc, update, transactionOrigin, YDecoder = UpdateDecoderV2) => {
5974 const decoder = createDecoder(update);
5975 readUpdateV2(decoder, ydoc, transactionOrigin, new YDecoder(decoder));
5976 };
5977 var applyUpdate = (ydoc, update, transactionOrigin) => applyUpdateV2(ydoc, update, transactionOrigin, UpdateDecoderV1);
5978 var writeStateAsUpdate = (encoder, doc2, targetStateVector = /* @__PURE__ */ new Map()) => {
5979 writeClientsStructs(encoder, doc2.store, targetStateVector);
5980 writeDeleteSet(encoder, createDeleteSetFromStructStore(doc2.store));
5981 };
5982 var encodeStateAsUpdateV2 = (doc2, encodedTargetStateVector = new Uint8Array([0]), encoder = new UpdateEncoderV2()) => {
5983 const targetStateVector = decodeStateVector(encodedTargetStateVector);
5984 writeStateAsUpdate(encoder, doc2, targetStateVector);
5985 const updates = [encoder.toUint8Array()];
5986 if (doc2.store.pendingDs) {
5987 updates.push(doc2.store.pendingDs);
5988 }
5989 if (doc2.store.pendingStructs) {
5990 updates.push(diffUpdateV2(doc2.store.pendingStructs.update, encodedTargetStateVector));
5991 }
5992 if (updates.length > 1) {
5993 if (encoder.constructor === UpdateEncoderV1) {
5994 return mergeUpdates(updates.map((update, i) => i === 0 ? update : convertUpdateFormatV2ToV1(update)));
5995 } else if (encoder.constructor === UpdateEncoderV2) {
5996 return mergeUpdatesV2(updates);
5997 }
5998 }
5999 return updates[0];
6000 };
6001 var encodeStateAsUpdate = (doc2, encodedTargetStateVector) => encodeStateAsUpdateV2(doc2, encodedTargetStateVector, new UpdateEncoderV1());
6002 var readStateVector = (decoder) => {
6003 const ss = /* @__PURE__ */ new Map();
6004 const ssLength = readVarUint(decoder.restDecoder);
6005 for (let i = 0; i < ssLength; i++) {
6006 const client = readVarUint(decoder.restDecoder);
6007 const clock = readVarUint(decoder.restDecoder);
6008 ss.set(client, clock);
6009 }
6010 return ss;
6011 };
6012 var decodeStateVector = (decodedState) => readStateVector(new DSDecoderV1(createDecoder(decodedState)));
6013 var writeStateVector = (encoder, sv) => {
6014 writeVarUint(encoder.restEncoder, sv.size);
6015 from(sv.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, clock]) => {
6016 writeVarUint(encoder.restEncoder, client);
6017 writeVarUint(encoder.restEncoder, clock);
6018 });
6019 return encoder;
6020 };
6021 var writeDocumentStateVector = (encoder, doc2) => writeStateVector(encoder, getStateVector(doc2.store));
6022 var encodeStateVectorV2 = (doc2, encoder = new DSEncoderV2()) => {
6023 if (doc2 instanceof Map) {
6024 writeStateVector(encoder, doc2);
6025 } else {
6026 writeDocumentStateVector(encoder, doc2);
6027 }
6028 return encoder.toUint8Array();
6029 };
6030 var encodeStateVector = (doc2) => encodeStateVectorV2(doc2, new DSEncoderV1());
6031 var EventHandler = class {
6032 constructor() {
6033 this.l = [];
6034 }
6035 };
6036 var createEventHandler = () => new EventHandler();
6037 var addEventHandlerListener = (eventHandler, f) => eventHandler.l.push(f);
6038 var removeEventHandlerListener = (eventHandler, f) => {
6039 const l = eventHandler.l;
6040 const len = l.length;
6041 eventHandler.l = l.filter((g) => f !== g);
6042 if (len === eventHandler.l.length) {
6043 console.error("[yjs] Tried to remove event handler that doesn't exist.");
6044 }
6045 };
6046 var callEventHandlerListeners = (eventHandler, arg0, arg1) => callAll(eventHandler.l, [arg0, arg1]);
6047 var ID = class {
6048 /**
6049 * @param {number} client client id
6050 * @param {number} clock unique per client id, continuous number
6051 */
6052 constructor(client, clock) {
6053 this.client = client;
6054 this.clock = clock;
6055 }
6056 };
6057 var compareIDs = (a, b) => a === b || a !== null && b !== null && a.client === b.client && a.clock === b.clock;
6058 var createID = (client, clock) => new ID(client, clock);
6059 var writeID = (encoder, id2) => {
6060 writeVarUint(encoder, id2.client);
6061 writeVarUint(encoder, id2.clock);
6062 };
6063 var readID = (decoder) => createID(readVarUint(decoder), readVarUint(decoder));
6064 var findRootTypeKey = (type) => {
6065 for (const [key, value] of type.doc.share.entries()) {
6066 if (value === type) {
6067 return key;
6068 }
6069 }
6070 throw unexpectedCase();
6071 };
6072 var isParentOf = (parent, child) => {
6073 while (child !== null) {
6074 if (child.parent === parent) {
6075 return true;
6076 }
6077 child = /** @type {AbstractType<any>} */
6078 child.parent._item;
6079 }
6080 return false;
6081 };
6082 var logType = (type) => {
6083 const res = [];
6084 let n = type._start;
6085 while (n) {
6086 res.push(n);
6087 n = n.right;
6088 }
6089 console.log("Children: ", res);
6090 console.log("Children content: ", res.filter((m) => !m.deleted).map((m) => m.content));
6091 };
6092 var PermanentUserData = class {
6093 /**
6094 * @param {Doc} doc
6095 * @param {YMap<any>} [storeType]
6096 */
6097 constructor(doc2, storeType = doc2.getMap("users")) {
6098 const dss = /* @__PURE__ */ new Map();
6099 this.yusers = storeType;
6100 this.doc = doc2;
6101 this.clients = /* @__PURE__ */ new Map();
6102 this.dss = dss;
6103 const initUser = (user, userDescription) => {
6104 const ds = user.get("ds");
6105 const ids = user.get("ids");
6106 const addClientId = (
6107 /** @param {number} clientid */
6108 (clientid) => this.clients.set(clientid, userDescription)
6109 );
6110 ds.observe(
6111 /** @param {YArrayEvent<any>} event */
6112 (event) => {
6113 event.changes.added.forEach((item) => {
6114 item.content.getContent().forEach((encodedDs) => {
6115 if (encodedDs instanceof Uint8Array) {
6116 this.dss.set(userDescription, mergeDeleteSets([this.dss.get(userDescription) || createDeleteSet(), readDeleteSet(new DSDecoderV1(createDecoder(encodedDs)))]));
6117 }
6118 });
6119 });
6120 }
6121 );
6122 this.dss.set(userDescription, mergeDeleteSets(ds.map((encodedDs) => readDeleteSet(new DSDecoderV1(createDecoder(encodedDs))))));
6123 ids.observe(
6124 /** @param {YArrayEvent<any>} event */
6125 (event) => event.changes.added.forEach((item) => item.content.getContent().forEach(addClientId))
6126 );
6127 ids.forEach(addClientId);
6128 };
6129 storeType.observe((event) => {
6130 event.keysChanged.forEach(
6131 (userDescription) => initUser(storeType.get(userDescription), userDescription)
6132 );
6133 });
6134 storeType.forEach(initUser);
6135 }
6136 /**
6137 * @param {Doc} doc
6138 * @param {number} clientid
6139 * @param {string} userDescription
6140 * @param {Object} conf
6141 * @param {function(Transaction, DeleteSet):boolean} [conf.filter]
6142 */
6143 setUserMapping(doc2, clientid, userDescription, { filter = () => true } = {}) {
6144 const users2 = this.yusers;
6145 let user = users2.get(userDescription);
6146 if (!user) {
6147 user = new YMap();
6148 user.set("ids", new YArray());
6149 user.set("ds", new YArray());
6150 users2.set(userDescription, user);
6151 }
6152 user.get("ids").push([clientid]);
6153 users2.observe((_event) => {
6154 setTimeout(() => {
6155 const userOverwrite = users2.get(userDescription);
6156 if (userOverwrite !== user) {
6157 user = userOverwrite;
6158 this.clients.forEach((_userDescription, clientid2) => {
6159 if (userDescription === _userDescription) {
6160 user.get("ids").push([clientid2]);
6161 }
6162 });
6163 const encoder = new DSEncoderV1();
6164 const ds = this.dss.get(userDescription);
6165 if (ds) {
6166 writeDeleteSet(encoder, ds);
6167 user.get("ds").push([encoder.toUint8Array()]);
6168 }
6169 }
6170 }, 0);
6171 });
6172 doc2.on(
6173 "afterTransaction",
6174 /** @param {Transaction} transaction */
6175 (transaction) => {
6176 setTimeout(() => {
6177 const yds = user.get("ds");
6178 const ds = transaction.deleteSet;
6179 if (transaction.local && ds.clients.size > 0 && filter(transaction, ds)) {
6180 const encoder = new DSEncoderV1();
6181 writeDeleteSet(encoder, ds);
6182 yds.push([encoder.toUint8Array()]);
6183 }
6184 });
6185 }
6186 );
6187 }
6188 /**
6189 * @param {number} clientid
6190 * @return {any}
6191 */
6192 getUserByClientId(clientid) {
6193 return this.clients.get(clientid) || null;
6194 }
6195 /**
6196 * @param {ID} id
6197 * @return {string | null}
6198 */
6199 getUserByDeletedId(id2) {
6200 for (const [userDescription, ds] of this.dss.entries()) {
6201 if (isDeleted(ds, id2)) {
6202 return userDescription;
6203 }
6204 }
6205 return null;
6206 }
6207 };
6208 var RelativePosition = class {
6209 /**
6210 * @param {ID|null} type
6211 * @param {string|null} tname
6212 * @param {ID|null} item
6213 * @param {number} assoc
6214 */
6215 constructor(type, tname, item, assoc = 0) {
6216 this.type = type;
6217 this.tname = tname;
6218 this.item = item;
6219 this.assoc = assoc;
6220 }
6221 };
6222 var relativePositionToJSON = (rpos) => {
6223 const json = {};
6224 if (rpos.type) {
6225 json.type = rpos.type;
6226 }
6227 if (rpos.tname) {
6228 json.tname = rpos.tname;
6229 }
6230 if (rpos.item) {
6231 json.item = rpos.item;
6232 }
6233 if (rpos.assoc != null) {
6234 json.assoc = rpos.assoc;
6235 }
6236 return json;
6237 };
6238 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);
6239 var AbsolutePosition = class {
6240 /**
6241 * @param {AbstractType<any>} type
6242 * @param {number} index
6243 * @param {number} [assoc]
6244 */
6245 constructor(type, index, assoc = 0) {
6246 this.type = type;
6247 this.index = index;
6248 this.assoc = assoc;
6249 }
6250 };
6251 var createAbsolutePosition = (type, index, assoc = 0) => new AbsolutePosition(type, index, assoc);
6252 var createRelativePosition = (type, item, assoc) => {
6253 let typeid = null;
6254 let tname = null;
6255 if (type._item === null) {
6256 tname = findRootTypeKey(type);
6257 } else {
6258 typeid = createID(type._item.id.client, type._item.id.clock);
6259 }
6260 return new RelativePosition(typeid, tname, item, assoc);
6261 };
6262 var createRelativePositionFromTypeIndex = (type, index, assoc = 0) => {
6263 let t = type._start;
6264 if (assoc < 0) {
6265 if (index === 0) {
6266 return createRelativePosition(type, null, assoc);
6267 }
6268 index--;
6269 }
6270 while (t !== null) {
6271 if (!t.deleted && t.countable) {
6272 if (t.length > index) {
6273 return createRelativePosition(type, createID(t.id.client, t.id.clock + index), assoc);
6274 }
6275 index -= t.length;
6276 }
6277 if (t.right === null && assoc < 0) {
6278 return createRelativePosition(type, t.lastId, assoc);
6279 }
6280 t = t.right;
6281 }
6282 return createRelativePosition(type, null, assoc);
6283 };
6284 var writeRelativePosition = (encoder, rpos) => {
6285 const { type, tname, item, assoc } = rpos;
6286 if (item !== null) {
6287 writeVarUint(encoder, 0);
6288 writeID(encoder, item);
6289 } else if (tname !== null) {
6290 writeUint8(encoder, 1);
6291 writeVarString(encoder, tname);
6292 } else if (type !== null) {
6293 writeUint8(encoder, 2);
6294 writeID(encoder, type);
6295 } else {
6296 throw unexpectedCase();
6297 }
6298 writeVarInt(encoder, assoc);
6299 return encoder;
6300 };
6301 var encodeRelativePosition = (rpos) => {
6302 const encoder = createEncoder();
6303 writeRelativePosition(encoder, rpos);
6304 return toUint8Array(encoder);
6305 };
6306 var readRelativePosition = (decoder) => {
6307 let type = null;
6308 let tname = null;
6309 let itemID = null;
6310 switch (readVarUint(decoder)) {
6311 case 0:
6312 itemID = readID(decoder);
6313 break;
6314 case 1:
6315 tname = readVarString(decoder);
6316 break;
6317 case 2: {
6318 type = readID(decoder);
6319 }
6320 }
6321 const assoc = hasContent(decoder) ? readVarInt(decoder) : 0;
6322 return new RelativePosition(type, tname, itemID, assoc);
6323 };
6324 var decodeRelativePosition = (uint8Array) => readRelativePosition(createDecoder(uint8Array));
6325 var createAbsolutePositionFromRelativePosition = (rpos, doc2) => {
6326 const store2 = doc2.store;
6327 const rightID = rpos.item;
6328 const typeID = rpos.type;
6329 const tname = rpos.tname;
6330 const assoc = rpos.assoc;
6331 let type = null;
6332 let index = 0;
6333 if (rightID !== null) {
6334 if (getState(store2, rightID.client) <= rightID.clock) {
6335 return null;
6336 }
6337 const res = followRedone(store2, rightID);
6338 const right = res.item;
6339 if (!(right instanceof Item)) {
6340 return null;
6341 }
6342 type = /** @type {AbstractType<any>} */
6343 right.parent;
6344 if (type._item === null || !type._item.deleted) {
6345 index = right.deleted || !right.countable ? 0 : res.diff + (assoc >= 0 ? 0 : 1);
6346 let n = right.left;
6347 while (n !== null) {
6348 if (!n.deleted && n.countable) {
6349 index += n.length;
6350 }
6351 n = n.left;
6352 }
6353 }
6354 } else {
6355 if (tname !== null) {
6356 type = doc2.get(tname);
6357 } else if (typeID !== null) {
6358 if (getState(store2, typeID.client) <= typeID.clock) {
6359 return null;
6360 }
6361 const { item } = followRedone(store2, typeID);
6362 if (item instanceof Item && item.content instanceof ContentType) {
6363 type = item.content.type;
6364 } else {
6365 return null;
6366 }
6367 } else {
6368 throw unexpectedCase();
6369 }
6370 if (assoc >= 0) {
6371 index = type._length;
6372 } else {
6373 index = 0;
6374 }
6375 }
6376 return createAbsolutePosition(type, index, rpos.assoc);
6377 };
6378 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;
6379 var Snapshot = class {
6380 /**
6381 * @param {DeleteSet} ds
6382 * @param {Map<number,number>} sv state map
6383 */
6384 constructor(ds, sv) {
6385 this.ds = ds;
6386 this.sv = sv;
6387 }
6388 };
6389 var equalSnapshots = (snap1, snap2) => {
6390 const ds1 = snap1.ds.clients;
6391 const ds2 = snap2.ds.clients;
6392 const sv1 = snap1.sv;
6393 const sv2 = snap2.sv;
6394 if (sv1.size !== sv2.size || ds1.size !== ds2.size) {
6395 return false;
6396 }
6397 for (const [key, value] of sv1.entries()) {
6398 if (sv2.get(key) !== value) {
6399 return false;
6400 }
6401 }
6402 for (const [client, dsitems1] of ds1.entries()) {
6403 const dsitems2 = ds2.get(client) || [];
6404 if (dsitems1.length !== dsitems2.length) {
6405 return false;
6406 }
6407 for (let i = 0; i < dsitems1.length; i++) {
6408 const dsitem1 = dsitems1[i];
6409 const dsitem2 = dsitems2[i];
6410 if (dsitem1.clock !== dsitem2.clock || dsitem1.len !== dsitem2.len) {
6411 return false;
6412 }
6413 }
6414 }
6415 return true;
6416 };
6417 var encodeSnapshotV2 = (snapshot2, encoder = new DSEncoderV2()) => {
6418 writeDeleteSet(encoder, snapshot2.ds);
6419 writeStateVector(encoder, snapshot2.sv);
6420 return encoder.toUint8Array();
6421 };
6422 var encodeSnapshot = (snapshot2) => encodeSnapshotV2(snapshot2, new DSEncoderV1());
6423 var decodeSnapshotV2 = (buf, decoder = new DSDecoderV2(createDecoder(buf))) => {
6424 return new Snapshot(readDeleteSet(decoder), readStateVector(decoder));
6425 };
6426 var decodeSnapshot = (buf) => decodeSnapshotV2(buf, new DSDecoderV1(createDecoder(buf)));
6427 var createSnapshot = (ds, sm) => new Snapshot(ds, sm);
6428 var emptySnapshot = createSnapshot(createDeleteSet(), /* @__PURE__ */ new Map());
6429 var snapshot = (doc2) => createSnapshot(createDeleteSetFromStructStore(doc2.store), getStateVector(doc2.store));
6430 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);
6431 var splitSnapshotAffectedStructs = (transaction, snapshot2) => {
6432 const meta = setIfUndefined(transaction.meta, splitSnapshotAffectedStructs, create2);
6433 const store2 = transaction.doc.store;
6434 if (!meta.has(snapshot2)) {
6435 snapshot2.sv.forEach((clock, client) => {
6436 if (clock < getState(store2, client)) {
6437 getItemCleanStart(transaction, createID(client, clock));
6438 }
6439 });
6440 iterateDeletedStructs(transaction, snapshot2.ds, (_item) => {
6441 });
6442 meta.add(snapshot2);
6443 }
6444 };
6445 var createDocFromSnapshot = (originDoc, snapshot2, newDoc = new Doc()) => {
6446 if (originDoc.gc) {
6447 throw new Error("Garbage-collection must be disabled in `originDoc`!");
6448 }
6449 const { sv, ds } = snapshot2;
6450 const encoder = new UpdateEncoderV2();
6451 originDoc.transact((transaction) => {
6452 let size = 0;
6453 sv.forEach((clock) => {
6454 if (clock > 0) {
6455 size++;
6456 }
6457 });
6458 writeVarUint(encoder.restEncoder, size);
6459 for (const [client, clock] of sv) {
6460 if (clock === 0) {
6461 continue;
6462 }
6463 if (clock < getState(originDoc.store, client)) {
6464 getItemCleanStart(transaction, createID(client, clock));
6465 }
6466 const structs = originDoc.store.clients.get(client) || [];
6467 const lastStructIndex = findIndexSS(structs, clock - 1);
6468 writeVarUint(encoder.restEncoder, lastStructIndex + 1);
6469 encoder.writeClient(client);
6470 writeVarUint(encoder.restEncoder, 0);
6471 for (let i = 0; i <= lastStructIndex; i++) {
6472 structs[i].write(encoder, 0);
6473 }
6474 }
6475 writeDeleteSet(encoder, ds);
6476 });
6477 applyUpdateV2(newDoc, encoder.toUint8Array(), "snapshot");
6478 return newDoc;
6479 };
6480 var snapshotContainsUpdateV2 = (snapshot2, update, YDecoder = UpdateDecoderV2) => {
6481 const updateDecoder = new YDecoder(createDecoder(update));
6482 const lazyDecoder = new LazyStructReader(updateDecoder, false);
6483 for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) {
6484 if ((snapshot2.sv.get(curr.id.client) || 0) < curr.id.clock + curr.length) {
6485 return false;
6486 }
6487 }
6488 const mergedDS = mergeDeleteSets([snapshot2.ds, readDeleteSet(updateDecoder)]);
6489 return equalDeleteSets(snapshot2.ds, mergedDS);
6490 };
6491 var snapshotContainsUpdate = (snapshot2, update) => snapshotContainsUpdateV2(snapshot2, update, UpdateDecoderV1);
6492 var StructStore = class {
6493 constructor() {
6494 this.clients = /* @__PURE__ */ new Map();
6495 this.pendingStructs = null;
6496 this.pendingDs = null;
6497 }
6498 };
6499 var getStateVector = (store2) => {
6500 const sm = /* @__PURE__ */ new Map();
6501 store2.clients.forEach((structs, client) => {
6502 const struct = structs[structs.length - 1];
6503 sm.set(client, struct.id.clock + struct.length);
6504 });
6505 return sm;
6506 };
6507 var getState = (store2, client) => {
6508 const structs = store2.clients.get(client);
6509 if (structs === void 0) {
6510 return 0;
6511 }
6512 const lastStruct = structs[structs.length - 1];
6513 return lastStruct.id.clock + lastStruct.length;
6514 };
6515 var addStruct = (store2, struct) => {
6516 let structs = store2.clients.get(struct.id.client);
6517 if (structs === void 0) {
6518 structs = [];
6519 store2.clients.set(struct.id.client, structs);
6520 } else {
6521 const lastStruct = structs[structs.length - 1];
6522 if (lastStruct.id.clock + lastStruct.length !== struct.id.clock) {
6523 throw unexpectedCase();
6524 }
6525 }
6526 structs.push(struct);
6527 };
6528 var findIndexSS = (structs, clock) => {
6529 let left = 0;
6530 let right = structs.length - 1;
6531 let mid = structs[right];
6532 let midclock = mid.id.clock;
6533 if (midclock === clock) {
6534 return right;
6535 }
6536 let midindex = floor(clock / (midclock + mid.length - 1) * right);
6537 while (left <= right) {
6538 mid = structs[midindex];
6539 midclock = mid.id.clock;
6540 if (midclock <= clock) {
6541 if (clock < midclock + mid.length) {
6542 return midindex;
6543 }
6544 left = midindex + 1;
6545 } else {
6546 right = midindex - 1;
6547 }
6548 midindex = floor((left + right) / 2);
6549 }
6550 throw unexpectedCase();
6551 };
6552 var find = (store2, id2) => {
6553 const structs = store2.clients.get(id2.client);
6554 return structs[findIndexSS(structs, id2.clock)];
6555 };
6556 var getItem = (
6557 /** @type {function(StructStore,ID):Item} */
6558 find
6559 );
6560 var findIndexCleanStart = (transaction, structs, clock) => {
6561 const index = findIndexSS(structs, clock);
6562 const struct = structs[index];
6563 if (struct.id.clock < clock && struct instanceof Item) {
6564 structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock));
6565 return index + 1;
6566 }
6567 return index;
6568 };
6569 var getItemCleanStart = (transaction, id2) => {
6570 const structs = (
6571 /** @type {Array<Item>} */
6572 transaction.doc.store.clients.get(id2.client)
6573 );
6574 return structs[findIndexCleanStart(transaction, structs, id2.clock)];
6575 };
6576 var getItemCleanEnd = (transaction, store2, id2) => {
6577 const structs = store2.clients.get(id2.client);
6578 const index = findIndexSS(structs, id2.clock);
6579 const struct = structs[index];
6580 if (id2.clock !== struct.id.clock + struct.length - 1 && struct.constructor !== GC) {
6581 structs.splice(index + 1, 0, splitItem(transaction, struct, id2.clock - struct.id.clock + 1));
6582 }
6583 return struct;
6584 };
6585 var replaceStruct = (store2, struct, newStruct) => {
6586 const structs = (
6587 /** @type {Array<GC|Item>} */
6588 store2.clients.get(struct.id.client)
6589 );
6590 structs[findIndexSS(structs, struct.id.clock)] = newStruct;
6591 };
6592 var iterateStructs = (transaction, structs, clockStart, len, f) => {
6593 if (len === 0) {
6594 return;
6595 }
6596 const clockEnd = clockStart + len;
6597 let index = findIndexCleanStart(transaction, structs, clockStart);
6598 let struct;
6599 do {
6600 struct = structs[index++];
6601 if (clockEnd < struct.id.clock + struct.length) {
6602 findIndexCleanStart(transaction, structs, clockEnd);
6603 }
6604 f(struct);
6605 } while (index < structs.length && structs[index].id.clock < clockEnd);
6606 };
6607 var Transaction = class {
6608 /**
6609 * @param {Doc} doc
6610 * @param {any} origin
6611 * @param {boolean} local
6612 */
6613 constructor(doc2, origin, local) {
6614 this.doc = doc2;
6615 this.deleteSet = new DeleteSet();
6616 this.beforeState = getStateVector(doc2.store);
6617 this.afterState = /* @__PURE__ */ new Map();
6618 this.changed = /* @__PURE__ */ new Map();
6619 this.changedParentTypes = /* @__PURE__ */ new Map();
6620 this._mergeStructs = [];
6621 this.origin = origin;
6622 this.meta = /* @__PURE__ */ new Map();
6623 this.local = local;
6624 this.subdocsAdded = /* @__PURE__ */ new Set();
6625 this.subdocsRemoved = /* @__PURE__ */ new Set();
6626 this.subdocsLoaded = /* @__PURE__ */ new Set();
6627 this._needFormattingCleanup = false;
6628 }
6629 };
6630 var writeUpdateMessageFromTransaction = (encoder, transaction) => {
6631 if (transaction.deleteSet.clients.size === 0 && !any(transaction.afterState, (clock, client) => transaction.beforeState.get(client) !== clock)) {
6632 return false;
6633 }
6634 sortAndMergeDeleteSet(transaction.deleteSet);
6635 writeStructsFromTransaction(encoder, transaction);
6636 writeDeleteSet(encoder, transaction.deleteSet);
6637 return true;
6638 };
6639 var addChangedTypeToTransaction = (transaction, type, parentSub) => {
6640 const item = type._item;
6641 if (item === null || item.id.clock < (transaction.beforeState.get(item.id.client) || 0) && !item.deleted) {
6642 setIfUndefined(transaction.changed, type, create2).add(parentSub);
6643 }
6644 };
6645 var tryToMergeWithLefts = (structs, pos) => {
6646 let right = structs[pos];
6647 let left = structs[pos - 1];
6648 let i = pos;
6649 for (; i > 0; right = left, left = structs[--i - 1]) {
6650 if (left.deleted === right.deleted && left.constructor === right.constructor) {
6651 if (left.mergeWith(right)) {
6652 if (right instanceof Item && right.parentSub !== null && /** @type {AbstractType<any>} */
6653 right.parent._map.get(right.parentSub) === right) {
6654 right.parent._map.set(
6655 right.parentSub,
6656 /** @type {Item} */
6657 left
6658 );
6659 }
6660 continue;
6661 }
6662 }
6663 break;
6664 }
6665 const merged = pos - i;
6666 if (merged) {
6667 structs.splice(pos + 1 - merged, merged);
6668 }
6669 return merged;
6670 };
6671 var tryGcDeleteSet = (ds, store2, gcFilter) => {
6672 for (const [client, deleteItems] of ds.clients.entries()) {
6673 const structs = (
6674 /** @type {Array<GC|Item>} */
6675 store2.clients.get(client)
6676 );
6677 for (let di = deleteItems.length - 1; di >= 0; di--) {
6678 const deleteItem = deleteItems[di];
6679 const endDeleteItemClock = deleteItem.clock + deleteItem.len;
6680 for (let si = findIndexSS(structs, deleteItem.clock), struct = structs[si]; si < structs.length && struct.id.clock < endDeleteItemClock; struct = structs[++si]) {
6681 const struct2 = structs[si];
6682 if (deleteItem.clock + deleteItem.len <= struct2.id.clock) {
6683 break;
6684 }
6685 if (struct2 instanceof Item && struct2.deleted && !struct2.keep && gcFilter(struct2)) {
6686 struct2.gc(store2, false);
6687 }
6688 }
6689 }
6690 }
6691 };
6692 var tryMergeDeleteSet = (ds, store2) => {
6693 ds.clients.forEach((deleteItems, client) => {
6694 const structs = (
6695 /** @type {Array<GC|Item>} */
6696 store2.clients.get(client)
6697 );
6698 for (let di = deleteItems.length - 1; di >= 0; di--) {
6699 const deleteItem = deleteItems[di];
6700 const mostRightIndexToCheck = min(structs.length - 1, 1 + findIndexSS(structs, deleteItem.clock + deleteItem.len - 1));
6701 for (let si = mostRightIndexToCheck, struct = structs[si]; si > 0 && struct.id.clock >= deleteItem.clock; struct = structs[si]) {
6702 si -= 1 + tryToMergeWithLefts(structs, si);
6703 }
6704 }
6705 });
6706 };
6707 var tryGc = (ds, store2, gcFilter) => {
6708 tryGcDeleteSet(ds, store2, gcFilter);
6709 tryMergeDeleteSet(ds, store2);
6710 };
6711 var cleanupTransactions = (transactionCleanups, i) => {
6712 if (i < transactionCleanups.length) {
6713 const transaction = transactionCleanups[i];
6714 const doc2 = transaction.doc;
6715 const store2 = doc2.store;
6716 const ds = transaction.deleteSet;
6717 const mergeStructs = transaction._mergeStructs;
6718 try {
6719 sortAndMergeDeleteSet(ds);
6720 transaction.afterState = getStateVector(transaction.doc.store);
6721 doc2.emit("beforeObserverCalls", [transaction, doc2]);
6722 const fs = [];
6723 transaction.changed.forEach(
6724 (subs, itemtype) => fs.push(() => {
6725 if (itemtype._item === null || !itemtype._item.deleted) {
6726 itemtype._callObserver(transaction, subs);
6727 }
6728 })
6729 );
6730 fs.push(() => {
6731 transaction.changedParentTypes.forEach((events, type) => {
6732 if (type._dEH.l.length > 0 && (type._item === null || !type._item.deleted)) {
6733 events = events.filter(
6734 (event) => event.target._item === null || !event.target._item.deleted
6735 );
6736 events.forEach((event) => {
6737 event.currentTarget = type;
6738 event._path = null;
6739 });
6740 events.sort((event1, event2) => event1.path.length - event2.path.length);
6741 callEventHandlerListeners(type._dEH, events, transaction);
6742 }
6743 });
6744 });
6745 fs.push(() => doc2.emit("afterTransaction", [transaction, doc2]));
6746 callAll(fs, []);
6747 if (transaction._needFormattingCleanup) {
6748 cleanupYTextAfterTransaction(transaction);
6749 }
6750 } finally {
6751 if (doc2.gc) {
6752 tryGcDeleteSet(ds, store2, doc2.gcFilter);
6753 }
6754 tryMergeDeleteSet(ds, store2);
6755 transaction.afterState.forEach((clock, client) => {
6756 const beforeClock = transaction.beforeState.get(client) || 0;
6757 if (beforeClock !== clock) {
6758 const structs = (
6759 /** @type {Array<GC|Item>} */
6760 store2.clients.get(client)
6761 );
6762 const firstChangePos = max(findIndexSS(structs, beforeClock), 1);
6763 for (let i2 = structs.length - 1; i2 >= firstChangePos; ) {
6764 i2 -= 1 + tryToMergeWithLefts(structs, i2);
6765 }
6766 }
6767 });
6768 for (let i2 = mergeStructs.length - 1; i2 >= 0; i2--) {
6769 const { client, clock } = mergeStructs[i2].id;
6770 const structs = (
6771 /** @type {Array<GC|Item>} */
6772 store2.clients.get(client)
6773 );
6774 const replacedStructPos = findIndexSS(structs, clock);
6775 if (replacedStructPos + 1 < structs.length) {
6776 if (tryToMergeWithLefts(structs, replacedStructPos + 1) > 1) {
6777 continue;
6778 }
6779 }
6780 if (replacedStructPos > 0) {
6781 tryToMergeWithLefts(structs, replacedStructPos);
6782 }
6783 }
6784 if (!transaction.local && transaction.afterState.get(doc2.clientID) !== transaction.beforeState.get(doc2.clientID)) {
6785 print(ORANGE, BOLD, "[yjs] ", UNBOLD, RED, "Changed the client-id because another client seems to be using it.");
6786 doc2.clientID = generateNewClientId();
6787 }
6788 doc2.emit("afterTransactionCleanup", [transaction, doc2]);
6789 if (doc2._observers.has("update")) {
6790 const encoder = new UpdateEncoderV1();
6791 const hasContent2 = writeUpdateMessageFromTransaction(encoder, transaction);
6792 if (hasContent2) {
6793 doc2.emit("update", [encoder.toUint8Array(), transaction.origin, doc2, transaction]);
6794 }
6795 }
6796 if (doc2._observers.has("updateV2")) {
6797 const encoder = new UpdateEncoderV2();
6798 const hasContent2 = writeUpdateMessageFromTransaction(encoder, transaction);
6799 if (hasContent2) {
6800 doc2.emit("updateV2", [encoder.toUint8Array(), transaction.origin, doc2, transaction]);
6801 }
6802 }
6803 const { subdocsAdded, subdocsLoaded, subdocsRemoved } = transaction;
6804 if (subdocsAdded.size > 0 || subdocsRemoved.size > 0 || subdocsLoaded.size > 0) {
6805 subdocsAdded.forEach((subdoc) => {
6806 subdoc.clientID = doc2.clientID;
6807 if (subdoc.collectionid == null) {
6808 subdoc.collectionid = doc2.collectionid;
6809 }
6810 doc2.subdocs.add(subdoc);
6811 });
6812 subdocsRemoved.forEach((subdoc) => doc2.subdocs.delete(subdoc));
6813 doc2.emit("subdocs", [{ loaded: subdocsLoaded, added: subdocsAdded, removed: subdocsRemoved }, doc2, transaction]);
6814 subdocsRemoved.forEach((subdoc) => subdoc.destroy());
6815 }
6816 if (transactionCleanups.length <= i + 1) {
6817 doc2._transactionCleanups = [];
6818 doc2.emit("afterAllTransactions", [doc2, transactionCleanups]);
6819 } else {
6820 cleanupTransactions(transactionCleanups, i + 1);
6821 }
6822 }
6823 }
6824 };
6825 var transact = (doc2, f, origin = null, local = true) => {
6826 const transactionCleanups = doc2._transactionCleanups;
6827 let initialCall = false;
6828 let result = null;
6829 if (doc2._transaction === null) {
6830 initialCall = true;
6831 doc2._transaction = new Transaction(doc2, origin, local);
6832 transactionCleanups.push(doc2._transaction);
6833 if (transactionCleanups.length === 1) {
6834 doc2.emit("beforeAllTransactions", [doc2]);
6835 }
6836 doc2.emit("beforeTransaction", [doc2._transaction, doc2]);
6837 }
6838 try {
6839 result = f(doc2._transaction);
6840 } finally {
6841 if (initialCall) {
6842 const finishCleanup = doc2._transaction === transactionCleanups[0];
6843 doc2._transaction = null;
6844 if (finishCleanup) {
6845 cleanupTransactions(transactionCleanups, 0);
6846 }
6847 }
6848 }
6849 return result;
6850 };
6851 var StackItem = class {
6852 /**
6853 * @param {DeleteSet} deletions
6854 * @param {DeleteSet} insertions
6855 */
6856 constructor(deletions, insertions) {
6857 this.insertions = insertions;
6858 this.deletions = deletions;
6859 this.meta = /* @__PURE__ */ new Map();
6860 }
6861 };
6862 var clearUndoManagerStackItem = (tr, um, stackItem) => {
6863 iterateDeletedStructs(tr, stackItem.deletions, (item) => {
6864 if (item instanceof Item && um.scope.some((type) => isParentOf(type, item))) {
6865 keepItem(item, false);
6866 }
6867 });
6868 };
6869 var popStackItem = (undoManager2, stack, eventType) => {
6870 let result = null;
6871 let _tr = null;
6872 const doc2 = undoManager2.doc;
6873 const scope = undoManager2.scope;
6874 transact(doc2, (transaction) => {
6875 while (stack.length > 0 && result === null) {
6876 const store2 = doc2.store;
6877 const stackItem = (
6878 /** @type {StackItem} */
6879 stack.pop()
6880 );
6881 const itemsToRedo = /* @__PURE__ */ new Set();
6882 const itemsToDelete = [];
6883 let performedChange = false;
6884 iterateDeletedStructs(transaction, stackItem.insertions, (struct) => {
6885 if (struct instanceof Item) {
6886 if (struct.redone !== null) {
6887 let { item, diff } = followRedone(store2, struct.id);
6888 if (diff > 0) {
6889 item = getItemCleanStart(transaction, createID(item.id.client, item.id.clock + diff));
6890 }
6891 struct = item;
6892 }
6893 if (!struct.deleted && scope.some((type) => isParentOf(
6894 type,
6895 /** @type {Item} */
6896 struct
6897 ))) {
6898 itemsToDelete.push(struct);
6899 }
6900 }
6901 });
6902 iterateDeletedStructs(transaction, stackItem.deletions, (struct) => {
6903 if (struct instanceof Item && scope.some((type) => isParentOf(type, struct)) && // Never redo structs in stackItem.insertions because they were created and deleted in the same capture interval.
6904 !isDeleted(stackItem.insertions, struct.id)) {
6905 itemsToRedo.add(struct);
6906 }
6907 });
6908 itemsToRedo.forEach((struct) => {
6909 performedChange = redoItem(transaction, struct, itemsToRedo, stackItem.insertions, undoManager2.ignoreRemoteMapChanges, undoManager2) !== null || performedChange;
6910 });
6911 for (let i = itemsToDelete.length - 1; i >= 0; i--) {
6912 const item = itemsToDelete[i];
6913 if (undoManager2.deleteFilter(item)) {
6914 item.delete(transaction);
6915 performedChange = true;
6916 }
6917 }
6918 result = performedChange ? stackItem : null;
6919 }
6920 transaction.changed.forEach((subProps, type) => {
6921 if (subProps.has(null) && type._searchMarker) {
6922 type._searchMarker.length = 0;
6923 }
6924 });
6925 _tr = transaction;
6926 }, undoManager2);
6927 if (result != null) {
6928 const changedParentTypes = _tr.changedParentTypes;
6929 undoManager2.emit("stack-item-popped", [{ stackItem: result, type: eventType, changedParentTypes }, undoManager2]);
6930 }
6931 return result;
6932 };
6933 var UndoManager = class extends Observable {
6934 /**
6935 * @param {AbstractType<any>|Array<AbstractType<any>>} typeScope Accepts either a single type, or an array of types
6936 * @param {UndoManagerOptions} options
6937 */
6938 constructor(typeScope, {
6939 captureTimeout = 500,
6940 captureTransaction = (_tr) => true,
6941 deleteFilter = () => true,
6942 trackedOrigins = /* @__PURE__ */ new Set([null]),
6943 ignoreRemoteMapChanges = false,
6944 doc: doc2 = (
6945 /** @type {Doc} */
6946 isArray(typeScope) ? typeScope[0].doc : typeScope.doc
6947 )
6948 } = {}) {
6949 super();
6950 this.scope = [];
6951 this.addToScope(typeScope);
6952 this.deleteFilter = deleteFilter;
6953 trackedOrigins.add(this);
6954 this.trackedOrigins = trackedOrigins;
6955 this.captureTransaction = captureTransaction;
6956 this.undoStack = [];
6957 this.redoStack = [];
6958 this.undoing = false;
6959 this.redoing = false;
6960 this.doc = doc2;
6961 this.lastChange = 0;
6962 this.ignoreRemoteMapChanges = ignoreRemoteMapChanges;
6963 this.captureTimeout = captureTimeout;
6964 this.afterTransactionHandler = (transaction) => {
6965 if (!this.captureTransaction(transaction) || !this.scope.some((type) => transaction.changedParentTypes.has(type)) || !this.trackedOrigins.has(transaction.origin) && (!transaction.origin || !this.trackedOrigins.has(transaction.origin.constructor))) {
6966 return;
6967 }
6968 const undoing = this.undoing;
6969 const redoing = this.redoing;
6970 const stack = undoing ? this.redoStack : this.undoStack;
6971 if (undoing) {
6972 this.stopCapturing();
6973 } else if (!redoing) {
6974 this.clear(false, true);
6975 }
6976 const insertions = new DeleteSet();
6977 transaction.afterState.forEach((endClock, client) => {
6978 const startClock = transaction.beforeState.get(client) || 0;
6979 const len = endClock - startClock;
6980 if (len > 0) {
6981 addToDeleteSet(insertions, client, startClock, len);
6982 }
6983 });
6984 const now = getUnixTime();
6985 let didAdd = false;
6986 if (this.lastChange > 0 && now - this.lastChange < this.captureTimeout && stack.length > 0 && !undoing && !redoing) {
6987 const lastOp = stack[stack.length - 1];
6988 lastOp.deletions = mergeDeleteSets([lastOp.deletions, transaction.deleteSet]);
6989 lastOp.insertions = mergeDeleteSets([lastOp.insertions, insertions]);
6990 } else {
6991 stack.push(new StackItem(transaction.deleteSet, insertions));
6992 didAdd = true;
6993 }
6994 if (!undoing && !redoing) {
6995 this.lastChange = now;
6996 }
6997 iterateDeletedStructs(
6998 transaction,
6999 transaction.deleteSet,
7000 /** @param {Item|GC} item */
7001 (item) => {
7002 if (item instanceof Item && this.scope.some((type) => isParentOf(type, item))) {
7003 keepItem(item, true);
7004 }
7005 }
7006 );
7007 const changeEvent = [{ stackItem: stack[stack.length - 1], origin: transaction.origin, type: undoing ? "redo" : "undo", changedParentTypes: transaction.changedParentTypes }, this];
7008 if (didAdd) {
7009 this.emit("stack-item-added", changeEvent);
7010 } else {
7011 this.emit("stack-item-updated", changeEvent);
7012 }
7013 };
7014 this.doc.on("afterTransaction", this.afterTransactionHandler);
7015 this.doc.on("destroy", () => {
7016 this.destroy();
7017 });
7018 }
7019 /**
7020 * @param {Array<AbstractType<any>> | AbstractType<any>} ytypes
7021 */
7022 addToScope(ytypes) {
7023 ytypes = isArray(ytypes) ? ytypes : [ytypes];
7024 ytypes.forEach((ytype) => {
7025 if (this.scope.every((yt) => yt !== ytype)) {
7026 this.scope.push(ytype);
7027 }
7028 });
7029 }
7030 /**
7031 * @param {any} origin
7032 */
7033 addTrackedOrigin(origin) {
7034 this.trackedOrigins.add(origin);
7035 }
7036 /**
7037 * @param {any} origin
7038 */
7039 removeTrackedOrigin(origin) {
7040 this.trackedOrigins.delete(origin);
7041 }
7042 clear(clearUndoStack = true, clearRedoStack = true) {
7043 if (clearUndoStack && this.canUndo() || clearRedoStack && this.canRedo()) {
7044 this.doc.transact((tr) => {
7045 if (clearUndoStack) {
7046 this.undoStack.forEach((item) => clearUndoManagerStackItem(tr, this, item));
7047 this.undoStack = [];
7048 }
7049 if (clearRedoStack) {
7050 this.redoStack.forEach((item) => clearUndoManagerStackItem(tr, this, item));
7051 this.redoStack = [];
7052 }
7053 this.emit("stack-cleared", [{ undoStackCleared: clearUndoStack, redoStackCleared: clearRedoStack }]);
7054 });
7055 }
7056 }
7057 /**
7058 * UndoManager merges Undo-StackItem if they are created within time-gap
7059 * smaller than `options.captureTimeout`. Call `um.stopCapturing()` so that the next
7060 * StackItem won't be merged.
7061 *
7062 *
7063 * @example
7064 * // without stopCapturing
7065 * ytext.insert(0, 'a')
7066 * ytext.insert(1, 'b')
7067 * um.undo()
7068 * ytext.toString() // => '' (note that 'ab' was removed)
7069 * // with stopCapturing
7070 * ytext.insert(0, 'a')
7071 * um.stopCapturing()
7072 * ytext.insert(0, 'b')
7073 * um.undo()
7074 * ytext.toString() // => 'a' (note that only 'b' was removed)
7075 *
7076 */
7077 stopCapturing() {
7078 this.lastChange = 0;
7079 }
7080 /**
7081 * Undo last changes on type.
7082 *
7083 * @return {StackItem?} Returns StackItem if a change was applied
7084 */
7085 undo() {
7086 this.undoing = true;
7087 let res;
7088 try {
7089 res = popStackItem(this, this.undoStack, "undo");
7090 } finally {
7091 this.undoing = false;
7092 }
7093 return res;
7094 }
7095 /**
7096 * Redo last undo operation.
7097 *
7098 * @return {StackItem?} Returns StackItem if a change was applied
7099 */
7100 redo() {
7101 this.redoing = true;
7102 let res;
7103 try {
7104 res = popStackItem(this, this.redoStack, "redo");
7105 } finally {
7106 this.redoing = false;
7107 }
7108 return res;
7109 }
7110 /**
7111 * Are undo steps available?
7112 *
7113 * @return {boolean} `true` if undo is possible
7114 */
7115 canUndo() {
7116 return this.undoStack.length > 0;
7117 }
7118 /**
7119 * Are redo steps available?
7120 *
7121 * @return {boolean} `true` if redo is possible
7122 */
7123 canRedo() {
7124 return this.redoStack.length > 0;
7125 }
7126 destroy() {
7127 this.trackedOrigins.delete(this);
7128 this.doc.off("afterTransaction", this.afterTransactionHandler);
7129 super.destroy();
7130 }
7131 };
7132 function* lazyStructReaderGenerator(decoder) {
7133 const numOfStateUpdates = readVarUint(decoder.restDecoder);
7134 for (let i = 0; i < numOfStateUpdates; i++) {
7135 const numberOfStructs = readVarUint(decoder.restDecoder);
7136 const client = decoder.readClient();
7137 let clock = readVarUint(decoder.restDecoder);
7138 for (let i2 = 0; i2 < numberOfStructs; i2++) {
7139 const info = decoder.readInfo();
7140 if (info === 10) {
7141 const len = readVarUint(decoder.restDecoder);
7142 yield new Skip(createID(client, clock), len);
7143 clock += len;
7144 } else if ((BITS5 & info) !== 0) {
7145 const cantCopyParentInfo = (info & (BIT7 | BIT8)) === 0;
7146 const struct = new Item(
7147 createID(client, clock),
7148 null,
7149 // left
7150 (info & BIT8) === BIT8 ? decoder.readLeftID() : null,
7151 // origin
7152 null,
7153 // right
7154 (info & BIT7) === BIT7 ? decoder.readRightID() : null,
7155 // right origin
7156 // @ts-ignore Force writing a string here.
7157 cantCopyParentInfo ? decoder.readParentInfo() ? decoder.readString() : decoder.readLeftID() : null,
7158 // parent
7159 cantCopyParentInfo && (info & BIT6) === BIT6 ? decoder.readString() : null,
7160 // parentSub
7161 readItemContent(decoder, info)
7162 // item content
7163 );
7164 yield struct;
7165 clock += struct.length;
7166 } else {
7167 const len = decoder.readLen();
7168 yield new GC(createID(client, clock), len);
7169 clock += len;
7170 }
7171 }
7172 }
7173 }
7174 var LazyStructReader = class {
7175 /**
7176 * @param {UpdateDecoderV1 | UpdateDecoderV2} decoder
7177 * @param {boolean} filterSkips
7178 */
7179 constructor(decoder, filterSkips) {
7180 this.gen = lazyStructReaderGenerator(decoder);
7181 this.curr = null;
7182 this.done = false;
7183 this.filterSkips = filterSkips;
7184 this.next();
7185 }
7186 /**
7187 * @return {Item | GC | Skip |null}
7188 */
7189 next() {
7190 do {
7191 this.curr = this.gen.next().value || null;
7192 } while (this.filterSkips && this.curr !== null && this.curr.constructor === Skip);
7193 return this.curr;
7194 }
7195 };
7196 var logUpdate = (update) => logUpdateV2(update, UpdateDecoderV1);
7197 var logUpdateV2 = (update, YDecoder = UpdateDecoderV2) => {
7198 const structs = [];
7199 const updateDecoder = new YDecoder(createDecoder(update));
7200 const lazyDecoder = new LazyStructReader(updateDecoder, false);
7201 for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) {
7202 structs.push(curr);
7203 }
7204 print("Structs: ", structs);
7205 const ds = readDeleteSet(updateDecoder);
7206 print("DeleteSet: ", ds);
7207 };
7208 var decodeUpdate = (update) => decodeUpdateV2(update, UpdateDecoderV1);
7209 var decodeUpdateV2 = (update, YDecoder = UpdateDecoderV2) => {
7210 const structs = [];
7211 const updateDecoder = new YDecoder(createDecoder(update));
7212 const lazyDecoder = new LazyStructReader(updateDecoder, false);
7213 for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) {
7214 structs.push(curr);
7215 }
7216 return {
7217 structs,
7218 ds: readDeleteSet(updateDecoder)
7219 };
7220 };
7221 var LazyStructWriter = class {
7222 /**
7223 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
7224 */
7225 constructor(encoder) {
7226 this.currClient = 0;
7227 this.startClock = 0;
7228 this.written = 0;
7229 this.encoder = encoder;
7230 this.clientStructs = [];
7231 }
7232 };
7233 var mergeUpdates = (updates) => mergeUpdatesV2(updates, UpdateDecoderV1, UpdateEncoderV1);
7234 var encodeStateVectorFromUpdateV2 = (update, YEncoder = DSEncoderV2, YDecoder = UpdateDecoderV2) => {
7235 const encoder = new YEncoder();
7236 const updateDecoder = new LazyStructReader(new YDecoder(createDecoder(update)), false);
7237 let curr = updateDecoder.curr;
7238 if (curr !== null) {
7239 let size = 0;
7240 let currClient = curr.id.client;
7241 let stopCounting = curr.id.clock !== 0;
7242 let currClock = stopCounting ? 0 : curr.id.clock + curr.length;
7243 for (; curr !== null; curr = updateDecoder.next()) {
7244 if (currClient !== curr.id.client) {
7245 if (currClock !== 0) {
7246 size++;
7247 writeVarUint(encoder.restEncoder, currClient);
7248 writeVarUint(encoder.restEncoder, currClock);
7249 }
7250 currClient = curr.id.client;
7251 currClock = 0;
7252 stopCounting = curr.id.clock !== 0;
7253 }
7254 if (curr.constructor === Skip) {
7255 stopCounting = true;
7256 }
7257 if (!stopCounting) {
7258 currClock = curr.id.clock + curr.length;
7259 }
7260 }
7261 if (currClock !== 0) {
7262 size++;
7263 writeVarUint(encoder.restEncoder, currClient);
7264 writeVarUint(encoder.restEncoder, currClock);
7265 }
7266 const enc = createEncoder();
7267 writeVarUint(enc, size);
7268 writeBinaryEncoder(enc, encoder.restEncoder);
7269 encoder.restEncoder = enc;
7270 return encoder.toUint8Array();
7271 } else {
7272 writeVarUint(encoder.restEncoder, 0);
7273 return encoder.toUint8Array();
7274 }
7275 };
7276 var encodeStateVectorFromUpdate = (update) => encodeStateVectorFromUpdateV2(update, DSEncoderV1, UpdateDecoderV1);
7277 var parseUpdateMetaV2 = (update, YDecoder = UpdateDecoderV2) => {
7278 const from2 = /* @__PURE__ */ new Map();
7279 const to = /* @__PURE__ */ new Map();
7280 const updateDecoder = new LazyStructReader(new YDecoder(createDecoder(update)), false);
7281 let curr = updateDecoder.curr;
7282 if (curr !== null) {
7283 let currClient = curr.id.client;
7284 let currClock = curr.id.clock;
7285 from2.set(currClient, currClock);
7286 for (; curr !== null; curr = updateDecoder.next()) {
7287 if (currClient !== curr.id.client) {
7288 to.set(currClient, currClock);
7289 from2.set(curr.id.client, curr.id.clock);
7290 currClient = curr.id.client;
7291 }
7292 currClock = curr.id.clock + curr.length;
7293 }
7294 to.set(currClient, currClock);
7295 }
7296 return { from: from2, to };
7297 };
7298 var parseUpdateMeta = (update) => parseUpdateMetaV2(update, UpdateDecoderV1);
7299 var sliceStruct = (left, diff) => {
7300 if (left.constructor === GC) {
7301 const { client, clock } = left.id;
7302 return new GC(createID(client, clock + diff), left.length - diff);
7303 } else if (left.constructor === Skip) {
7304 const { client, clock } = left.id;
7305 return new Skip(createID(client, clock + diff), left.length - diff);
7306 } else {
7307 const leftItem = (
7308 /** @type {Item} */
7309 left
7310 );
7311 const { client, clock } = leftItem.id;
7312 return new Item(
7313 createID(client, clock + diff),
7314 null,
7315 createID(client, clock + diff - 1),
7316 null,
7317 leftItem.rightOrigin,
7318 leftItem.parent,
7319 leftItem.parentSub,
7320 leftItem.content.splice(diff)
7321 );
7322 }
7323 };
7324 var mergeUpdatesV2 = (updates, YDecoder = UpdateDecoderV2, YEncoder = UpdateEncoderV2) => {
7325 if (updates.length === 1) {
7326 return updates[0];
7327 }
7328 const updateDecoders = updates.map((update) => new YDecoder(createDecoder(update)));
7329 let lazyStructDecoders = updateDecoders.map((decoder) => new LazyStructReader(decoder, true));
7330 let currWrite = null;
7331 const updateEncoder = new YEncoder();
7332 const lazyStructEncoder = new LazyStructWriter(updateEncoder);
7333 while (true) {
7334 lazyStructDecoders = lazyStructDecoders.filter((dec) => dec.curr !== null);
7335 lazyStructDecoders.sort(
7336 /** @type {function(any,any):number} */
7337 (dec1, dec2) => {
7338 if (dec1.curr.id.client === dec2.curr.id.client) {
7339 const clockDiff = dec1.curr.id.clock - dec2.curr.id.clock;
7340 if (clockDiff === 0) {
7341 return dec1.curr.constructor === dec2.curr.constructor ? 0 : dec1.curr.constructor === Skip ? 1 : -1;
7342 } else {
7343 return clockDiff;
7344 }
7345 } else {
7346 return dec2.curr.id.client - dec1.curr.id.client;
7347 }
7348 }
7349 );
7350 if (lazyStructDecoders.length === 0) {
7351 break;
7352 }
7353 const currDecoder = lazyStructDecoders[0];
7354 const firstClient = (
7355 /** @type {Item | GC} */
7356 currDecoder.curr.id.client
7357 );
7358 if (currWrite !== null) {
7359 let curr = (
7360 /** @type {Item | GC | null} */
7361 currDecoder.curr
7362 );
7363 let iterated = false;
7364 while (curr !== null && curr.id.clock + curr.length <= currWrite.struct.id.clock + currWrite.struct.length && curr.id.client >= currWrite.struct.id.client) {
7365 curr = currDecoder.next();
7366 iterated = true;
7367 }
7368 if (curr === null || // current decoder is empty
7369 curr.id.client !== firstClient || // check whether there is another decoder that has has updates from `firstClient`
7370 iterated && curr.id.clock > currWrite.struct.id.clock + currWrite.struct.length) {
7371 continue;
7372 }
7373 if (firstClient !== currWrite.struct.id.client) {
7374 writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset);
7375 currWrite = { struct: curr, offset: 0 };
7376 currDecoder.next();
7377 } else {
7378 if (currWrite.struct.id.clock + currWrite.struct.length < curr.id.clock) {
7379 if (currWrite.struct.constructor === Skip) {
7380 currWrite.struct.length = curr.id.clock + curr.length - currWrite.struct.id.clock;
7381 } else {
7382 writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset);
7383 const diff = curr.id.clock - currWrite.struct.id.clock - currWrite.struct.length;
7384 const struct = new Skip(createID(firstClient, currWrite.struct.id.clock + currWrite.struct.length), diff);
7385 currWrite = { struct, offset: 0 };
7386 }
7387 } else {
7388 const diff = currWrite.struct.id.clock + currWrite.struct.length - curr.id.clock;
7389 if (diff > 0) {
7390 if (currWrite.struct.constructor === Skip) {
7391 currWrite.struct.length -= diff;
7392 } else {
7393 curr = sliceStruct(curr, diff);
7394 }
7395 }
7396 if (!currWrite.struct.mergeWith(
7397 /** @type {any} */
7398 curr
7399 )) {
7400 writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset);
7401 currWrite = { struct: curr, offset: 0 };
7402 currDecoder.next();
7403 }
7404 }
7405 }
7406 } else {
7407 currWrite = { struct: (
7408 /** @type {Item | GC} */
7409 currDecoder.curr
7410 ), offset: 0 };
7411 currDecoder.next();
7412 }
7413 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()) {
7414 writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset);
7415 currWrite = { struct: next, offset: 0 };
7416 }
7417 }
7418 if (currWrite !== null) {
7419 writeStructToLazyStructWriter(lazyStructEncoder, currWrite.struct, currWrite.offset);
7420 currWrite = null;
7421 }
7422 finishLazyStructWriting(lazyStructEncoder);
7423 const dss = updateDecoders.map((decoder) => readDeleteSet(decoder));
7424 const ds = mergeDeleteSets(dss);
7425 writeDeleteSet(updateEncoder, ds);
7426 return updateEncoder.toUint8Array();
7427 };
7428 var diffUpdateV2 = (update, sv, YDecoder = UpdateDecoderV2, YEncoder = UpdateEncoderV2) => {
7429 const state = decodeStateVector(sv);
7430 const encoder = new YEncoder();
7431 const lazyStructWriter = new LazyStructWriter(encoder);
7432 const decoder = new YDecoder(createDecoder(update));
7433 const reader = new LazyStructReader(decoder, false);
7434 while (reader.curr) {
7435 const curr = reader.curr;
7436 const currClient = curr.id.client;
7437 const svClock = state.get(currClient) || 0;
7438 if (reader.curr.constructor === Skip) {
7439 reader.next();
7440 continue;
7441 }
7442 if (curr.id.clock + curr.length > svClock) {
7443 writeStructToLazyStructWriter(lazyStructWriter, curr, max(svClock - curr.id.clock, 0));
7444 reader.next();
7445 while (reader.curr && reader.curr.id.client === currClient) {
7446 writeStructToLazyStructWriter(lazyStructWriter, reader.curr, 0);
7447 reader.next();
7448 }
7449 } else {
7450 while (reader.curr && reader.curr.id.client === currClient && reader.curr.id.clock + reader.curr.length <= svClock) {
7451 reader.next();
7452 }
7453 }
7454 }
7455 finishLazyStructWriting(lazyStructWriter);
7456 const ds = readDeleteSet(decoder);
7457 writeDeleteSet(encoder, ds);
7458 return encoder.toUint8Array();
7459 };
7460 var diffUpdate = (update, sv) => diffUpdateV2(update, sv, UpdateDecoderV1, UpdateEncoderV1);
7461 var flushLazyStructWriter = (lazyWriter) => {
7462 if (lazyWriter.written > 0) {
7463 lazyWriter.clientStructs.push({ written: lazyWriter.written, restEncoder: toUint8Array(lazyWriter.encoder.restEncoder) });
7464 lazyWriter.encoder.restEncoder = createEncoder();
7465 lazyWriter.written = 0;
7466 }
7467 };
7468 var writeStructToLazyStructWriter = (lazyWriter, struct, offset) => {
7469 if (lazyWriter.written > 0 && lazyWriter.currClient !== struct.id.client) {
7470 flushLazyStructWriter(lazyWriter);
7471 }
7472 if (lazyWriter.written === 0) {
7473 lazyWriter.currClient = struct.id.client;
7474 lazyWriter.encoder.writeClient(struct.id.client);
7475 writeVarUint(lazyWriter.encoder.restEncoder, struct.id.clock + offset);
7476 }
7477 struct.write(lazyWriter.encoder, offset);
7478 lazyWriter.written++;
7479 };
7480 var finishLazyStructWriting = (lazyWriter) => {
7481 flushLazyStructWriter(lazyWriter);
7482 const restEncoder = lazyWriter.encoder.restEncoder;
7483 writeVarUint(restEncoder, lazyWriter.clientStructs.length);
7484 for (let i = 0; i < lazyWriter.clientStructs.length; i++) {
7485 const partStructs = lazyWriter.clientStructs[i];
7486 writeVarUint(restEncoder, partStructs.written);
7487 writeUint8Array(restEncoder, partStructs.restEncoder);
7488 }
7489 };
7490 var convertUpdateFormat = (update, blockTransformer, YDecoder, YEncoder) => {
7491 const updateDecoder = new YDecoder(createDecoder(update));
7492 const lazyDecoder = new LazyStructReader(updateDecoder, false);
7493 const updateEncoder = new YEncoder();
7494 const lazyWriter = new LazyStructWriter(updateEncoder);
7495 for (let curr = lazyDecoder.curr; curr !== null; curr = lazyDecoder.next()) {
7496 writeStructToLazyStructWriter(lazyWriter, blockTransformer(curr), 0);
7497 }
7498 finishLazyStructWriting(lazyWriter);
7499 const ds = readDeleteSet(updateDecoder);
7500 writeDeleteSet(updateEncoder, ds);
7501 return updateEncoder.toUint8Array();
7502 };
7503 var createObfuscator = ({ formatting = true, subdocs = true, yxml = true } = {}) => {
7504 let i = 0;
7505 const mapKeyCache = create();
7506 const nodeNameCache = create();
7507 const formattingKeyCache = create();
7508 const formattingValueCache = create();
7509 formattingValueCache.set(null, null);
7510 return (block) => {
7511 switch (block.constructor) {
7512 case GC:
7513 case Skip:
7514 return block;
7515 case Item: {
7516 const item = (
7517 /** @type {Item} */
7518 block
7519 );
7520 const content = item.content;
7521 switch (content.constructor) {
7522 case ContentDeleted:
7523 break;
7524 case ContentType: {
7525 if (yxml) {
7526 const type = (
7527 /** @type {ContentType} */
7528 content.type
7529 );
7530 if (type instanceof YXmlElement) {
7531 type.nodeName = setIfUndefined(nodeNameCache, type.nodeName, () => "node-" + i);
7532 }
7533 if (type instanceof YXmlHook) {
7534 type.hookName = setIfUndefined(nodeNameCache, type.hookName, () => "hook-" + i);
7535 }
7536 }
7537 break;
7538 }
7539 case ContentAny: {
7540 const c = (
7541 /** @type {ContentAny} */
7542 content
7543 );
7544 c.arr = c.arr.map(() => i);
7545 break;
7546 }
7547 case ContentBinary: {
7548 const c = (
7549 /** @type {ContentBinary} */
7550 content
7551 );
7552 c.content = new Uint8Array([i]);
7553 break;
7554 }
7555 case ContentDoc: {
7556 const c = (
7557 /** @type {ContentDoc} */
7558 content
7559 );
7560 if (subdocs) {
7561 c.opts = {};
7562 c.doc.guid = i + "";
7563 }
7564 break;
7565 }
7566 case ContentEmbed: {
7567 const c = (
7568 /** @type {ContentEmbed} */
7569 content
7570 );
7571 c.embed = {};
7572 break;
7573 }
7574 case ContentFormat: {
7575 const c = (
7576 /** @type {ContentFormat} */
7577 content
7578 );
7579 if (formatting) {
7580 c.key = setIfUndefined(formattingKeyCache, c.key, () => i + "");
7581 c.value = setIfUndefined(formattingValueCache, c.value, () => ({ i }));
7582 }
7583 break;
7584 }
7585 case ContentJSON: {
7586 const c = (
7587 /** @type {ContentJSON} */
7588 content
7589 );
7590 c.arr = c.arr.map(() => i);
7591 break;
7592 }
7593 case ContentString: {
7594 const c = (
7595 /** @type {ContentString} */
7596 content
7597 );
7598 c.str = repeat(i % 10 + "", c.str.length);
7599 break;
7600 }
7601 default:
7602 unexpectedCase();
7603 }
7604 if (item.parentSub) {
7605 item.parentSub = setIfUndefined(mapKeyCache, item.parentSub, () => i + "");
7606 }
7607 i++;
7608 return block;
7609 }
7610 default:
7611 unexpectedCase();
7612 }
7613 };
7614 };
7615 var obfuscateUpdate = (update, opts) => convertUpdateFormat(update, createObfuscator(opts), UpdateDecoderV1, UpdateEncoderV1);
7616 var obfuscateUpdateV2 = (update, opts) => convertUpdateFormat(update, createObfuscator(opts), UpdateDecoderV2, UpdateEncoderV2);
7617 var convertUpdateFormatV1ToV2 = (update) => convertUpdateFormat(update, id, UpdateDecoderV1, UpdateEncoderV2);
7618 var convertUpdateFormatV2ToV1 = (update) => convertUpdateFormat(update, id, UpdateDecoderV2, UpdateEncoderV1);
7619 var errorComputeChanges = "You must not compute changes after the event-handler fired.";
7620 var YEvent = class {
7621 /**
7622 * @param {T} target The changed type.
7623 * @param {Transaction} transaction
7624 */
7625 constructor(target, transaction) {
7626 this.target = target;
7627 this.currentTarget = target;
7628 this.transaction = transaction;
7629 this._changes = null;
7630 this._keys = null;
7631 this._delta = null;
7632 this._path = null;
7633 }
7634 /**
7635 * Computes the path from `y` to the changed type.
7636 *
7637 * @todo v14 should standardize on path: Array<{parent, index}> because that is easier to work with.
7638 *
7639 * The following property holds:
7640 * @example
7641 * let type = y
7642 * event.path.forEach(dir => {
7643 * type = type.get(dir)
7644 * })
7645 * type === event.target // => true
7646 */
7647 get path() {
7648 return this._path || (this._path = getPathTo(this.currentTarget, this.target));
7649 }
7650 /**
7651 * Check if a struct is deleted by this event.
7652 *
7653 * In contrast to change.deleted, this method also returns true if the struct was added and then deleted.
7654 *
7655 * @param {AbstractStruct} struct
7656 * @return {boolean}
7657 */
7658 deletes(struct) {
7659 return isDeleted(this.transaction.deleteSet, struct.id);
7660 }
7661 /**
7662 * @type {Map<string, { action: 'add' | 'update' | 'delete', oldValue: any, newValue: any }>}
7663 */
7664 get keys() {
7665 if (this._keys === null) {
7666 if (this.transaction.doc._transactionCleanups.length === 0) {
7667 throw create3(errorComputeChanges);
7668 }
7669 const keys2 = /* @__PURE__ */ new Map();
7670 const target = this.target;
7671 const changed = (
7672 /** @type Set<string|null> */
7673 this.transaction.changed.get(target)
7674 );
7675 changed.forEach((key) => {
7676 if (key !== null) {
7677 const item = (
7678 /** @type {Item} */
7679 target._map.get(key)
7680 );
7681 let action;
7682 let oldValue;
7683 if (this.adds(item)) {
7684 let prev = item.left;
7685 while (prev !== null && this.adds(prev)) {
7686 prev = prev.left;
7687 }
7688 if (this.deletes(item)) {
7689 if (prev !== null && this.deletes(prev)) {
7690 action = "delete";
7691 oldValue = last(prev.content.getContent());
7692 } else {
7693 return;
7694 }
7695 } else {
7696 if (prev !== null && this.deletes(prev)) {
7697 action = "update";
7698 oldValue = last(prev.content.getContent());
7699 } else {
7700 action = "add";
7701 oldValue = void 0;
7702 }
7703 }
7704 } else {
7705 if (this.deletes(item)) {
7706 action = "delete";
7707 oldValue = last(
7708 /** @type {Item} */
7709 item.content.getContent()
7710 );
7711 } else {
7712 return;
7713 }
7714 }
7715 keys2.set(key, { action, oldValue });
7716 }
7717 });
7718 this._keys = keys2;
7719 }
7720 return this._keys;
7721 }
7722 /**
7723 * This is a computed property. Note that this can only be safely computed during the
7724 * event call. Computing this property after other changes happened might result in
7725 * unexpected behavior (incorrect computation of deltas). A safe way to collect changes
7726 * is to store the `changes` or the `delta` object. Avoid storing the `transaction` object.
7727 *
7728 * @type {Array<{insert?: string | Array<any> | object | AbstractType<any>, retain?: number, delete?: number, attributes?: Object<string, any>}>}
7729 */
7730 get delta() {
7731 return this.changes.delta;
7732 }
7733 /**
7734 * Check if a struct is added by this event.
7735 *
7736 * In contrast to change.deleted, this method also returns true if the struct was added and then deleted.
7737 *
7738 * @param {AbstractStruct} struct
7739 * @return {boolean}
7740 */
7741 adds(struct) {
7742 return struct.id.clock >= (this.transaction.beforeState.get(struct.id.client) || 0);
7743 }
7744 /**
7745 * This is a computed property. Note that this can only be safely computed during the
7746 * event call. Computing this property after other changes happened might result in
7747 * unexpected behavior (incorrect computation of deltas). A safe way to collect changes
7748 * is to store the `changes` or the `delta` object. Avoid storing the `transaction` object.
7749 *
7750 * @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}>}}
7751 */
7752 get changes() {
7753 let changes = this._changes;
7754 if (changes === null) {
7755 if (this.transaction.doc._transactionCleanups.length === 0) {
7756 throw create3(errorComputeChanges);
7757 }
7758 const target = this.target;
7759 const added = create2();
7760 const deleted = create2();
7761 const delta = [];
7762 changes = {
7763 added,
7764 deleted,
7765 delta,
7766 keys: this.keys
7767 };
7768 const changed = (
7769 /** @type Set<string|null> */
7770 this.transaction.changed.get(target)
7771 );
7772 if (changed.has(null)) {
7773 let lastOp = null;
7774 const packOp = () => {
7775 if (lastOp) {
7776 delta.push(lastOp);
7777 }
7778 };
7779 for (let item = target._start; item !== null; item = item.right) {
7780 if (item.deleted) {
7781 if (this.deletes(item) && !this.adds(item)) {
7782 if (lastOp === null || lastOp.delete === void 0) {
7783 packOp();
7784 lastOp = { delete: 0 };
7785 }
7786 lastOp.delete += item.length;
7787 deleted.add(item);
7788 }
7789 } else {
7790 if (this.adds(item)) {
7791 if (lastOp === null || lastOp.insert === void 0) {
7792 packOp();
7793 lastOp = { insert: [] };
7794 }
7795 lastOp.insert = lastOp.insert.concat(item.content.getContent());
7796 added.add(item);
7797 } else {
7798 if (lastOp === null || lastOp.retain === void 0) {
7799 packOp();
7800 lastOp = { retain: 0 };
7801 }
7802 lastOp.retain += item.length;
7803 }
7804 }
7805 }
7806 if (lastOp !== null && lastOp.retain === void 0) {
7807 packOp();
7808 }
7809 }
7810 this._changes = changes;
7811 }
7812 return (
7813 /** @type {any} */
7814 changes
7815 );
7816 }
7817 };
7818 var getPathTo = (parent, child) => {
7819 const path = [];
7820 while (child._item !== null && child !== parent) {
7821 if (child._item.parentSub !== null) {
7822 path.unshift(child._item.parentSub);
7823 } else {
7824 let i = 0;
7825 let c = (
7826 /** @type {AbstractType<any>} */
7827 child._item.parent._start
7828 );
7829 while (c !== child._item && c !== null) {
7830 if (!c.deleted) {
7831 i++;
7832 }
7833 c = c.right;
7834 }
7835 path.unshift(i);
7836 }
7837 child = /** @type {AbstractType<any>} */
7838 child._item.parent;
7839 }
7840 return path;
7841 };
7842 var maxSearchMarker = 80;
7843 var globalSearchMarkerTimestamp = 0;
7844 var ArraySearchMarker = class {
7845 /**
7846 * @param {Item} p
7847 * @param {number} index
7848 */
7849 constructor(p, index) {
7850 p.marker = true;
7851 this.p = p;
7852 this.index = index;
7853 this.timestamp = globalSearchMarkerTimestamp++;
7854 }
7855 };
7856 var refreshMarkerTimestamp = (marker) => {
7857 marker.timestamp = globalSearchMarkerTimestamp++;
7858 };
7859 var overwriteMarker = (marker, p, index) => {
7860 marker.p.marker = false;
7861 marker.p = p;
7862 p.marker = true;
7863 marker.index = index;
7864 marker.timestamp = globalSearchMarkerTimestamp++;
7865 };
7866 var markPosition = (searchMarker, p, index) => {
7867 if (searchMarker.length >= maxSearchMarker) {
7868 const marker = searchMarker.reduce((a, b) => a.timestamp < b.timestamp ? a : b);
7869 overwriteMarker(marker, p, index);
7870 return marker;
7871 } else {
7872 const pm = new ArraySearchMarker(p, index);
7873 searchMarker.push(pm);
7874 return pm;
7875 }
7876 };
7877 var findMarker = (yarray, index) => {
7878 if (yarray._start === null || index === 0 || yarray._searchMarker === null) {
7879 return null;
7880 }
7881 const marker = yarray._searchMarker.length === 0 ? null : yarray._searchMarker.reduce((a, b) => abs(index - a.index) < abs(index - b.index) ? a : b);
7882 let p = yarray._start;
7883 let pindex = 0;
7884 if (marker !== null) {
7885 p = marker.p;
7886 pindex = marker.index;
7887 refreshMarkerTimestamp(marker);
7888 }
7889 while (p.right !== null && pindex < index) {
7890 if (!p.deleted && p.countable) {
7891 if (index < pindex + p.length) {
7892 break;
7893 }
7894 pindex += p.length;
7895 }
7896 p = p.right;
7897 }
7898 while (p.left !== null && pindex > index) {
7899 p = p.left;
7900 if (!p.deleted && p.countable) {
7901 pindex -= p.length;
7902 }
7903 }
7904 while (p.left !== null && p.left.id.client === p.id.client && p.left.id.clock + p.left.length === p.id.clock) {
7905 p = p.left;
7906 if (!p.deleted && p.countable) {
7907 pindex -= p.length;
7908 }
7909 }
7910 if (marker !== null && abs(marker.index - pindex) < /** @type {YText|YArray<any>} */
7911 p.parent.length / maxSearchMarker) {
7912 overwriteMarker(marker, p, pindex);
7913 return marker;
7914 } else {
7915 return markPosition(yarray._searchMarker, p, pindex);
7916 }
7917 };
7918 var updateMarkerChanges = (searchMarker, index, len) => {
7919 for (let i = searchMarker.length - 1; i >= 0; i--) {
7920 const m = searchMarker[i];
7921 if (len > 0) {
7922 let p = m.p;
7923 p.marker = false;
7924 while (p && (p.deleted || !p.countable)) {
7925 p = p.left;
7926 if (p && !p.deleted && p.countable) {
7927 m.index -= p.length;
7928 }
7929 }
7930 if (p === null || p.marker === true) {
7931 searchMarker.splice(i, 1);
7932 continue;
7933 }
7934 m.p = p;
7935 p.marker = true;
7936 }
7937 if (index < m.index || len > 0 && index === m.index) {
7938 m.index = max(index, m.index + len);
7939 }
7940 }
7941 };
7942 var getTypeChildren = (t) => {
7943 let s = t._start;
7944 const arr = [];
7945 while (s) {
7946 arr.push(s);
7947 s = s.right;
7948 }
7949 return arr;
7950 };
7951 var callTypeObservers = (type, transaction, event) => {
7952 const changedType = type;
7953 const changedParentTypes = transaction.changedParentTypes;
7954 while (true) {
7955 setIfUndefined(changedParentTypes, type, () => []).push(event);
7956 if (type._item === null) {
7957 break;
7958 }
7959 type = /** @type {AbstractType<any>} */
7960 type._item.parent;
7961 }
7962 callEventHandlerListeners(changedType._eH, event, transaction);
7963 };
7964 var AbstractType = class {
7965 constructor() {
7966 this._item = null;
7967 this._map = /* @__PURE__ */ new Map();
7968 this._start = null;
7969 this.doc = null;
7970 this._length = 0;
7971 this._eH = createEventHandler();
7972 this._dEH = createEventHandler();
7973 this._searchMarker = null;
7974 }
7975 /**
7976 * @return {AbstractType<any>|null}
7977 */
7978 get parent() {
7979 return this._item ? (
7980 /** @type {AbstractType<any>} */
7981 this._item.parent
7982 ) : null;
7983 }
7984 /**
7985 * Integrate this type into the Yjs instance.
7986 *
7987 * * Save this struct in the os
7988 * * This type is sent to other client
7989 * * Observer functions are fired
7990 *
7991 * @param {Doc} y The Yjs instance
7992 * @param {Item|null} item
7993 */
7994 _integrate(y, item) {
7995 this.doc = y;
7996 this._item = item;
7997 }
7998 /**
7999 * @return {AbstractType<EventType>}
8000 */
8001 _copy() {
8002 throw methodUnimplemented();
8003 }
8004 /**
8005 * @return {AbstractType<EventType>}
8006 */
8007 clone() {
8008 throw methodUnimplemented();
8009 }
8010 /**
8011 * @param {UpdateEncoderV1 | UpdateEncoderV2} _encoder
8012 */
8013 _write(_encoder) {
8014 }
8015 /**
8016 * The first non-deleted item
8017 */
8018 get _first() {
8019 let n = this._start;
8020 while (n !== null && n.deleted) {
8021 n = n.right;
8022 }
8023 return n;
8024 }
8025 /**
8026 * Creates YEvent and calls all type observers.
8027 * Must be implemented by each type.
8028 *
8029 * @param {Transaction} transaction
8030 * @param {Set<null|string>} _parentSubs Keys changed on this type. `null` if list was modified.
8031 */
8032 _callObserver(transaction, _parentSubs) {
8033 if (!transaction.local && this._searchMarker) {
8034 this._searchMarker.length = 0;
8035 }
8036 }
8037 /**
8038 * Observe all events that are created on this type.
8039 *
8040 * @param {function(EventType, Transaction):void} f Observer function
8041 */
8042 observe(f) {
8043 addEventHandlerListener(this._eH, f);
8044 }
8045 /**
8046 * Observe all events that are created by this type and its children.
8047 *
8048 * @param {function(Array<YEvent<any>>,Transaction):void} f Observer function
8049 */
8050 observeDeep(f) {
8051 addEventHandlerListener(this._dEH, f);
8052 }
8053 /**
8054 * Unregister an observer function.
8055 *
8056 * @param {function(EventType,Transaction):void} f Observer function
8057 */
8058 unobserve(f) {
8059 removeEventHandlerListener(this._eH, f);
8060 }
8061 /**
8062 * Unregister an observer function.
8063 *
8064 * @param {function(Array<YEvent<any>>,Transaction):void} f Observer function
8065 */
8066 unobserveDeep(f) {
8067 removeEventHandlerListener(this._dEH, f);
8068 }
8069 /**
8070 * @abstract
8071 * @return {any}
8072 */
8073 toJSON() {
8074 }
8075 };
8076 var typeListSlice = (type, start, end) => {
8077 if (start < 0) {
8078 start = type._length + start;
8079 }
8080 if (end < 0) {
8081 end = type._length + end;
8082 }
8083 let len = end - start;
8084 const cs = [];
8085 let n = type._start;
8086 while (n !== null && len > 0) {
8087 if (n.countable && !n.deleted) {
8088 const c = n.content.getContent();
8089 if (c.length <= start) {
8090 start -= c.length;
8091 } else {
8092 for (let i = start; i < c.length && len > 0; i++) {
8093 cs.push(c[i]);
8094 len--;
8095 }
8096 start = 0;
8097 }
8098 }
8099 n = n.right;
8100 }
8101 return cs;
8102 };
8103 var typeListToArray = (type) => {
8104 const cs = [];
8105 let n = type._start;
8106 while (n !== null) {
8107 if (n.countable && !n.deleted) {
8108 const c = n.content.getContent();
8109 for (let i = 0; i < c.length; i++) {
8110 cs.push(c[i]);
8111 }
8112 }
8113 n = n.right;
8114 }
8115 return cs;
8116 };
8117 var typeListToArraySnapshot = (type, snapshot2) => {
8118 const cs = [];
8119 let n = type._start;
8120 while (n !== null) {
8121 if (n.countable && isVisible(n, snapshot2)) {
8122 const c = n.content.getContent();
8123 for (let i = 0; i < c.length; i++) {
8124 cs.push(c[i]);
8125 }
8126 }
8127 n = n.right;
8128 }
8129 return cs;
8130 };
8131 var typeListForEach = (type, f) => {
8132 let index = 0;
8133 let n = type._start;
8134 while (n !== null) {
8135 if (n.countable && !n.deleted) {
8136 const c = n.content.getContent();
8137 for (let i = 0; i < c.length; i++) {
8138 f(c[i], index++, type);
8139 }
8140 }
8141 n = n.right;
8142 }
8143 };
8144 var typeListMap = (type, f) => {
8145 const result = [];
8146 typeListForEach(type, (c, i) => {
8147 result.push(f(c, i, type));
8148 });
8149 return result;
8150 };
8151 var typeListCreateIterator = (type) => {
8152 let n = type._start;
8153 let currentContent = null;
8154 let currentContentIndex = 0;
8155 return {
8156 [Symbol.iterator]() {
8157 return this;
8158 },
8159 next: () => {
8160 if (currentContent === null) {
8161 while (n !== null && n.deleted) {
8162 n = n.right;
8163 }
8164 if (n === null) {
8165 return {
8166 done: true,
8167 value: void 0
8168 };
8169 }
8170 currentContent = n.content.getContent();
8171 currentContentIndex = 0;
8172 n = n.right;
8173 }
8174 const value = currentContent[currentContentIndex++];
8175 if (currentContent.length <= currentContentIndex) {
8176 currentContent = null;
8177 }
8178 return {
8179 done: false,
8180 value
8181 };
8182 }
8183 };
8184 };
8185 var typeListGet = (type, index) => {
8186 const marker = findMarker(type, index);
8187 let n = type._start;
8188 if (marker !== null) {
8189 n = marker.p;
8190 index -= marker.index;
8191 }
8192 for (; n !== null; n = n.right) {
8193 if (!n.deleted && n.countable) {
8194 if (index < n.length) {
8195 return n.content.getContent()[index];
8196 }
8197 index -= n.length;
8198 }
8199 }
8200 };
8201 var typeListInsertGenericsAfter = (transaction, parent, referenceItem, content) => {
8202 let left = referenceItem;
8203 const doc2 = transaction.doc;
8204 const ownClientId = doc2.clientID;
8205 const store2 = doc2.store;
8206 const right = referenceItem === null ? parent._start : referenceItem.right;
8207 let jsonContent = [];
8208 const packJsonContent = () => {
8209 if (jsonContent.length > 0) {
8210 left = new Item(createID(ownClientId, getState(store2, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentAny(jsonContent));
8211 left.integrate(transaction, 0);
8212 jsonContent = [];
8213 }
8214 };
8215 content.forEach((c) => {
8216 if (c === null) {
8217 jsonContent.push(c);
8218 } else {
8219 switch (c.constructor) {
8220 case Number:
8221 case Object:
8222 case Boolean:
8223 case Array:
8224 case String:
8225 jsonContent.push(c);
8226 break;
8227 default:
8228 packJsonContent();
8229 switch (c.constructor) {
8230 case Uint8Array:
8231 case ArrayBuffer:
8232 left = new Item(createID(ownClientId, getState(store2, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentBinary(new Uint8Array(
8233 /** @type {Uint8Array} */
8234 c
8235 )));
8236 left.integrate(transaction, 0);
8237 break;
8238 case Doc:
8239 left = new Item(createID(ownClientId, getState(store2, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentDoc(
8240 /** @type {Doc} */
8241 c
8242 ));
8243 left.integrate(transaction, 0);
8244 break;
8245 default:
8246 if (c instanceof AbstractType) {
8247 left = new Item(createID(ownClientId, getState(store2, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentType(c));
8248 left.integrate(transaction, 0);
8249 } else {
8250 throw new Error("Unexpected content type in insert operation");
8251 }
8252 }
8253 }
8254 }
8255 });
8256 packJsonContent();
8257 };
8258 var lengthExceeded = create3("Length exceeded!");
8259 var typeListInsertGenerics = (transaction, parent, index, content) => {
8260 if (index > parent._length) {
8261 throw lengthExceeded;
8262 }
8263 if (index === 0) {
8264 if (parent._searchMarker) {
8265 updateMarkerChanges(parent._searchMarker, index, content.length);
8266 }
8267 return typeListInsertGenericsAfter(transaction, parent, null, content);
8268 }
8269 const startIndex = index;
8270 const marker = findMarker(parent, index);
8271 let n = parent._start;
8272 if (marker !== null) {
8273 n = marker.p;
8274 index -= marker.index;
8275 if (index === 0) {
8276 n = n.prev;
8277 index += n && n.countable && !n.deleted ? n.length : 0;
8278 }
8279 }
8280 for (; n !== null; n = n.right) {
8281 if (!n.deleted && n.countable) {
8282 if (index <= n.length) {
8283 if (index < n.length) {
8284 getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index));
8285 }
8286 break;
8287 }
8288 index -= n.length;
8289 }
8290 }
8291 if (parent._searchMarker) {
8292 updateMarkerChanges(parent._searchMarker, startIndex, content.length);
8293 }
8294 return typeListInsertGenericsAfter(transaction, parent, n, content);
8295 };
8296 var typeListPushGenerics = (transaction, parent, content) => {
8297 const marker = (parent._searchMarker || []).reduce((maxMarker, currMarker) => currMarker.index > maxMarker.index ? currMarker : maxMarker, { index: 0, p: parent._start });
8298 let n = marker.p;
8299 if (n) {
8300 while (n.right) {
8301 n = n.right;
8302 }
8303 }
8304 return typeListInsertGenericsAfter(transaction, parent, n, content);
8305 };
8306 var typeListDelete = (transaction, parent, index, length3) => {
8307 if (length3 === 0) {
8308 return;
8309 }
8310 const startIndex = index;
8311 const startLength = length3;
8312 const marker = findMarker(parent, index);
8313 let n = parent._start;
8314 if (marker !== null) {
8315 n = marker.p;
8316 index -= marker.index;
8317 }
8318 for (; n !== null && index > 0; n = n.right) {
8319 if (!n.deleted && n.countable) {
8320 if (index < n.length) {
8321 getItemCleanStart(transaction, createID(n.id.client, n.id.clock + index));
8322 }
8323 index -= n.length;
8324 }
8325 }
8326 while (length3 > 0 && n !== null) {
8327 if (!n.deleted) {
8328 if (length3 < n.length) {
8329 getItemCleanStart(transaction, createID(n.id.client, n.id.clock + length3));
8330 }
8331 n.delete(transaction);
8332 length3 -= n.length;
8333 }
8334 n = n.right;
8335 }
8336 if (length3 > 0) {
8337 throw lengthExceeded;
8338 }
8339 if (parent._searchMarker) {
8340 updateMarkerChanges(
8341 parent._searchMarker,
8342 startIndex,
8343 -startLength + length3
8344 /* in case we remove the above exception */
8345 );
8346 }
8347 };
8348 var typeMapDelete = (transaction, parent, key) => {
8349 const c = parent._map.get(key);
8350 if (c !== void 0) {
8351 c.delete(transaction);
8352 }
8353 };
8354 var typeMapSet = (transaction, parent, key, value) => {
8355 const left = parent._map.get(key) || null;
8356 const doc2 = transaction.doc;
8357 const ownClientId = doc2.clientID;
8358 let content;
8359 if (value == null) {
8360 content = new ContentAny([value]);
8361 } else {
8362 switch (value.constructor) {
8363 case Number:
8364 case Object:
8365 case Boolean:
8366 case Array:
8367 case String:
8368 content = new ContentAny([value]);
8369 break;
8370 case Uint8Array:
8371 content = new ContentBinary(
8372 /** @type {Uint8Array} */
8373 value
8374 );
8375 break;
8376 case Doc:
8377 content = new ContentDoc(
8378 /** @type {Doc} */
8379 value
8380 );
8381 break;
8382 default:
8383 if (value instanceof AbstractType) {
8384 content = new ContentType(value);
8385 } else {
8386 throw new Error("Unexpected content type");
8387 }
8388 }
8389 }
8390 new Item(createID(ownClientId, getState(doc2.store, ownClientId)), left, left && left.lastId, null, null, parent, key, content).integrate(transaction, 0);
8391 };
8392 var typeMapGet = (parent, key) => {
8393 const val = parent._map.get(key);
8394 return val !== void 0 && !val.deleted ? val.content.getContent()[val.length - 1] : void 0;
8395 };
8396 var typeMapGetAll = (parent) => {
8397 const res = {};
8398 parent._map.forEach((value, key) => {
8399 if (!value.deleted) {
8400 res[key] = value.content.getContent()[value.length - 1];
8401 }
8402 });
8403 return res;
8404 };
8405 var typeMapHas = (parent, key) => {
8406 const val = parent._map.get(key);
8407 return val !== void 0 && !val.deleted;
8408 };
8409 var typeMapGetSnapshot = (parent, key, snapshot2) => {
8410 let v = parent._map.get(key) || null;
8411 while (v !== null && (!snapshot2.sv.has(v.id.client) || v.id.clock >= (snapshot2.sv.get(v.id.client) || 0))) {
8412 v = v.left;
8413 }
8414 return v !== null && isVisible(v, snapshot2) ? v.content.getContent()[v.length - 1] : void 0;
8415 };
8416 var createMapIterator = (map2) => iteratorFilter(
8417 map2.entries(),
8418 /** @param {any} entry */
8419 (entry) => !entry[1].deleted
8420 );
8421 var YArrayEvent = class extends YEvent {
8422 /**
8423 * @param {YArray<T>} yarray The changed type
8424 * @param {Transaction} transaction The transaction object
8425 */
8426 constructor(yarray, transaction) {
8427 super(yarray, transaction);
8428 this._transaction = transaction;
8429 }
8430 };
8431 var YArray = class _YArray extends AbstractType {
8432 constructor() {
8433 super();
8434 this._prelimContent = [];
8435 this._searchMarker = [];
8436 }
8437 /**
8438 * Construct a new YArray containing the specified items.
8439 * @template {Object<string,any>|Array<any>|number|null|string|Uint8Array} T
8440 * @param {Array<T>} items
8441 * @return {YArray<T>}
8442 */
8443 static from(items2) {
8444 const a = new _YArray();
8445 a.push(items2);
8446 return a;
8447 }
8448 /**
8449 * Integrate this type into the Yjs instance.
8450 *
8451 * * Save this struct in the os
8452 * * This type is sent to other client
8453 * * Observer functions are fired
8454 *
8455 * @param {Doc} y The Yjs instance
8456 * @param {Item} item
8457 */
8458 _integrate(y, item) {
8459 super._integrate(y, item);
8460 this.insert(
8461 0,
8462 /** @type {Array<any>} */
8463 this._prelimContent
8464 );
8465 this._prelimContent = null;
8466 }
8467 /**
8468 * @return {YArray<T>}
8469 */
8470 _copy() {
8471 return new _YArray();
8472 }
8473 /**
8474 * @return {YArray<T>}
8475 */
8476 clone() {
8477 const arr = new _YArray();
8478 arr.insert(0, this.toArray().map(
8479 (el) => el instanceof AbstractType ? (
8480 /** @type {typeof el} */
8481 el.clone()
8482 ) : el
8483 ));
8484 return arr;
8485 }
8486 get length() {
8487 return this._prelimContent === null ? this._length : this._prelimContent.length;
8488 }
8489 /**
8490 * Creates YArrayEvent and calls observers.
8491 *
8492 * @param {Transaction} transaction
8493 * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified.
8494 */
8495 _callObserver(transaction, parentSubs) {
8496 super._callObserver(transaction, parentSubs);
8497 callTypeObservers(this, transaction, new YArrayEvent(this, transaction));
8498 }
8499 /**
8500 * Inserts new content at an index.
8501 *
8502 * Important: This function expects an array of content. Not just a content
8503 * object. The reason for this "weirdness" is that inserting several elements
8504 * is very efficient when it is done as a single operation.
8505 *
8506 * @example
8507 * // Insert character 'a' at position 0
8508 * yarray.insert(0, ['a'])
8509 * // Insert numbers 1, 2 at position 1
8510 * yarray.insert(1, [1, 2])
8511 *
8512 * @param {number} index The index to insert content at.
8513 * @param {Array<T>} content The array of content
8514 */
8515 insert(index, content) {
8516 if (this.doc !== null) {
8517 transact(this.doc, (transaction) => {
8518 typeListInsertGenerics(
8519 transaction,
8520 this,
8521 index,
8522 /** @type {any} */
8523 content
8524 );
8525 });
8526 } else {
8527 this._prelimContent.splice(index, 0, ...content);
8528 }
8529 }
8530 /**
8531 * Appends content to this YArray.
8532 *
8533 * @param {Array<T>} content Array of content to append.
8534 *
8535 * @todo Use the following implementation in all types.
8536 */
8537 push(content) {
8538 if (this.doc !== null) {
8539 transact(this.doc, (transaction) => {
8540 typeListPushGenerics(
8541 transaction,
8542 this,
8543 /** @type {any} */
8544 content
8545 );
8546 });
8547 } else {
8548 this._prelimContent.push(...content);
8549 }
8550 }
8551 /**
8552 * Preppends content to this YArray.
8553 *
8554 * @param {Array<T>} content Array of content to preppend.
8555 */
8556 unshift(content) {
8557 this.insert(0, content);
8558 }
8559 /**
8560 * Deletes elements starting from an index.
8561 *
8562 * @param {number} index Index at which to start deleting elements
8563 * @param {number} length The number of elements to remove. Defaults to 1.
8564 */
8565 delete(index, length3 = 1) {
8566 if (this.doc !== null) {
8567 transact(this.doc, (transaction) => {
8568 typeListDelete(transaction, this, index, length3);
8569 });
8570 } else {
8571 this._prelimContent.splice(index, length3);
8572 }
8573 }
8574 /**
8575 * Returns the i-th element from a YArray.
8576 *
8577 * @param {number} index The index of the element to return from the YArray
8578 * @return {T}
8579 */
8580 get(index) {
8581 return typeListGet(this, index);
8582 }
8583 /**
8584 * Transforms this YArray to a JavaScript Array.
8585 *
8586 * @return {Array<T>}
8587 */
8588 toArray() {
8589 return typeListToArray(this);
8590 }
8591 /**
8592 * Transforms this YArray to a JavaScript Array.
8593 *
8594 * @param {number} [start]
8595 * @param {number} [end]
8596 * @return {Array<T>}
8597 */
8598 slice(start = 0, end = this.length) {
8599 return typeListSlice(this, start, end);
8600 }
8601 /**
8602 * Transforms this Shared Type to a JSON object.
8603 *
8604 * @return {Array<any>}
8605 */
8606 toJSON() {
8607 return this.map((c) => c instanceof AbstractType ? c.toJSON() : c);
8608 }
8609 /**
8610 * Returns an Array with the result of calling a provided function on every
8611 * element of this YArray.
8612 *
8613 * @template M
8614 * @param {function(T,number,YArray<T>):M} f Function that produces an element of the new Array
8615 * @return {Array<M>} A new array with each element being the result of the
8616 * callback function
8617 */
8618 map(f) {
8619 return typeListMap(
8620 this,
8621 /** @type {any} */
8622 f
8623 );
8624 }
8625 /**
8626 * Executes a provided function once on overy element of this YArray.
8627 *
8628 * @param {function(T,number,YArray<T>):void} f A function to execute on every element of this YArray.
8629 */
8630 forEach(f) {
8631 typeListForEach(this, f);
8632 }
8633 /**
8634 * @return {IterableIterator<T>}
8635 */
8636 [Symbol.iterator]() {
8637 return typeListCreateIterator(this);
8638 }
8639 /**
8640 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
8641 */
8642 _write(encoder) {
8643 encoder.writeTypeRef(YArrayRefID);
8644 }
8645 };
8646 var readYArray = (_decoder) => new YArray();
8647 var YMapEvent = class extends YEvent {
8648 /**
8649 * @param {YMap<T>} ymap The YArray that changed.
8650 * @param {Transaction} transaction
8651 * @param {Set<any>} subs The keys that changed.
8652 */
8653 constructor(ymap, transaction, subs) {
8654 super(ymap, transaction);
8655 this.keysChanged = subs;
8656 }
8657 };
8658 var YMap = class _YMap extends AbstractType {
8659 /**
8660 *
8661 * @param {Iterable<readonly [string, any]>=} entries - an optional iterable to initialize the YMap
8662 */
8663 constructor(entries) {
8664 super();
8665 this._prelimContent = null;
8666 if (entries === void 0) {
8667 this._prelimContent = /* @__PURE__ */ new Map();
8668 } else {
8669 this._prelimContent = new Map(entries);
8670 }
8671 }
8672 /**
8673 * Integrate this type into the Yjs instance.
8674 *
8675 * * Save this struct in the os
8676 * * This type is sent to other client
8677 * * Observer functions are fired
8678 *
8679 * @param {Doc} y The Yjs instance
8680 * @param {Item} item
8681 */
8682 _integrate(y, item) {
8683 super._integrate(y, item);
8684 this._prelimContent.forEach((value, key) => {
8685 this.set(key, value);
8686 });
8687 this._prelimContent = null;
8688 }
8689 /**
8690 * @return {YMap<MapType>}
8691 */
8692 _copy() {
8693 return new _YMap();
8694 }
8695 /**
8696 * @return {YMap<MapType>}
8697 */
8698 clone() {
8699 const map2 = new _YMap();
8700 this.forEach((value, key) => {
8701 map2.set(key, value instanceof AbstractType ? (
8702 /** @type {typeof value} */
8703 value.clone()
8704 ) : value);
8705 });
8706 return map2;
8707 }
8708 /**
8709 * Creates YMapEvent and calls observers.
8710 *
8711 * @param {Transaction} transaction
8712 * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified.
8713 */
8714 _callObserver(transaction, parentSubs) {
8715 callTypeObservers(this, transaction, new YMapEvent(this, transaction, parentSubs));
8716 }
8717 /**
8718 * Transforms this Shared Type to a JSON object.
8719 *
8720 * @return {Object<string,any>}
8721 */
8722 toJSON() {
8723 const map2 = {};
8724 this._map.forEach((item, key) => {
8725 if (!item.deleted) {
8726 const v = item.content.getContent()[item.length - 1];
8727 map2[key] = v instanceof AbstractType ? v.toJSON() : v;
8728 }
8729 });
8730 return map2;
8731 }
8732 /**
8733 * Returns the size of the YMap (count of key/value pairs)
8734 *
8735 * @return {number}
8736 */
8737 get size() {
8738 return [...createMapIterator(this._map)].length;
8739 }
8740 /**
8741 * Returns the keys for each element in the YMap Type.
8742 *
8743 * @return {IterableIterator<string>}
8744 */
8745 keys() {
8746 return iteratorMap(
8747 createMapIterator(this._map),
8748 /** @param {any} v */
8749 (v) => v[0]
8750 );
8751 }
8752 /**
8753 * Returns the values for each element in the YMap Type.
8754 *
8755 * @return {IterableIterator<any>}
8756 */
8757 values() {
8758 return iteratorMap(
8759 createMapIterator(this._map),
8760 /** @param {any} v */
8761 (v) => v[1].content.getContent()[v[1].length - 1]
8762 );
8763 }
8764 /**
8765 * Returns an Iterator of [key, value] pairs
8766 *
8767 * @return {IterableIterator<any>}
8768 */
8769 entries() {
8770 return iteratorMap(
8771 createMapIterator(this._map),
8772 /** @param {any} v */
8773 (v) => [v[0], v[1].content.getContent()[v[1].length - 1]]
8774 );
8775 }
8776 /**
8777 * Executes a provided function on once on every key-value pair.
8778 *
8779 * @param {function(MapType,string,YMap<MapType>):void} f A function to execute on every element of this YArray.
8780 */
8781 forEach(f) {
8782 this._map.forEach((item, key) => {
8783 if (!item.deleted) {
8784 f(item.content.getContent()[item.length - 1], key, this);
8785 }
8786 });
8787 }
8788 /**
8789 * Returns an Iterator of [key, value] pairs
8790 *
8791 * @return {IterableIterator<any>}
8792 */
8793 [Symbol.iterator]() {
8794 return this.entries();
8795 }
8796 /**
8797 * Remove a specified element from this YMap.
8798 *
8799 * @param {string} key The key of the element to remove.
8800 */
8801 delete(key) {
8802 if (this.doc !== null) {
8803 transact(this.doc, (transaction) => {
8804 typeMapDelete(transaction, this, key);
8805 });
8806 } else {
8807 this._prelimContent.delete(key);
8808 }
8809 }
8810 /**
8811 * Adds or updates an element with a specified key and value.
8812 * @template {MapType} VAL
8813 *
8814 * @param {string} key The key of the element to add to this YMap
8815 * @param {VAL} value The value of the element to add
8816 * @return {VAL}
8817 */
8818 set(key, value) {
8819 if (this.doc !== null) {
8820 transact(this.doc, (transaction) => {
8821 typeMapSet(
8822 transaction,
8823 this,
8824 key,
8825 /** @type {any} */
8826 value
8827 );
8828 });
8829 } else {
8830 this._prelimContent.set(key, value);
8831 }
8832 return value;
8833 }
8834 /**
8835 * Returns a specified element from this YMap.
8836 *
8837 * @param {string} key
8838 * @return {MapType|undefined}
8839 */
8840 get(key) {
8841 return (
8842 /** @type {any} */
8843 typeMapGet(this, key)
8844 );
8845 }
8846 /**
8847 * Returns a boolean indicating whether the specified key exists or not.
8848 *
8849 * @param {string} key The key to test.
8850 * @return {boolean}
8851 */
8852 has(key) {
8853 return typeMapHas(this, key);
8854 }
8855 /**
8856 * Removes all elements from this YMap.
8857 */
8858 clear() {
8859 if (this.doc !== null) {
8860 transact(this.doc, (transaction) => {
8861 this.forEach(function(_value, key, map2) {
8862 typeMapDelete(transaction, map2, key);
8863 });
8864 });
8865 } else {
8866 this._prelimContent.clear();
8867 }
8868 }
8869 /**
8870 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
8871 */
8872 _write(encoder) {
8873 encoder.writeTypeRef(YMapRefID);
8874 }
8875 };
8876 var readYMap = (_decoder) => new YMap();
8877 var equalAttrs = (a, b) => a === b || typeof a === "object" && typeof b === "object" && a && b && equalFlat(a, b);
8878 var ItemTextListPosition = class {
8879 /**
8880 * @param {Item|null} left
8881 * @param {Item|null} right
8882 * @param {number} index
8883 * @param {Map<string,any>} currentAttributes
8884 */
8885 constructor(left, right, index, currentAttributes) {
8886 this.left = left;
8887 this.right = right;
8888 this.index = index;
8889 this.currentAttributes = currentAttributes;
8890 }
8891 /**
8892 * Only call this if you know that this.right is defined
8893 */
8894 forward() {
8895 if (this.right === null) {
8896 unexpectedCase();
8897 }
8898 switch (this.right.content.constructor) {
8899 case ContentFormat:
8900 if (!this.right.deleted) {
8901 updateCurrentAttributes(
8902 this.currentAttributes,
8903 /** @type {ContentFormat} */
8904 this.right.content
8905 );
8906 }
8907 break;
8908 default:
8909 if (!this.right.deleted) {
8910 this.index += this.right.length;
8911 }
8912 break;
8913 }
8914 this.left = this.right;
8915 this.right = this.right.right;
8916 }
8917 };
8918 var findNextPosition = (transaction, pos, count2) => {
8919 while (pos.right !== null && count2 > 0) {
8920 switch (pos.right.content.constructor) {
8921 case ContentFormat:
8922 if (!pos.right.deleted) {
8923 updateCurrentAttributes(
8924 pos.currentAttributes,
8925 /** @type {ContentFormat} */
8926 pos.right.content
8927 );
8928 }
8929 break;
8930 default:
8931 if (!pos.right.deleted) {
8932 if (count2 < pos.right.length) {
8933 getItemCleanStart(transaction, createID(pos.right.id.client, pos.right.id.clock + count2));
8934 }
8935 pos.index += pos.right.length;
8936 count2 -= pos.right.length;
8937 }
8938 break;
8939 }
8940 pos.left = pos.right;
8941 pos.right = pos.right.right;
8942 }
8943 return pos;
8944 };
8945 var findPosition = (transaction, parent, index) => {
8946 const currentAttributes = /* @__PURE__ */ new Map();
8947 const marker = findMarker(parent, index);
8948 if (marker) {
8949 const pos = new ItemTextListPosition(marker.p.left, marker.p, marker.index, currentAttributes);
8950 return findNextPosition(transaction, pos, index - marker.index);
8951 } else {
8952 const pos = new ItemTextListPosition(null, parent._start, 0, currentAttributes);
8953 return findNextPosition(transaction, pos, index);
8954 }
8955 };
8956 var insertNegatedAttributes = (transaction, parent, currPos, negatedAttributes) => {
8957 while (currPos.right !== null && (currPos.right.deleted === true || currPos.right.content.constructor === ContentFormat && equalAttrs(
8958 negatedAttributes.get(
8959 /** @type {ContentFormat} */
8960 currPos.right.content.key
8961 ),
8962 /** @type {ContentFormat} */
8963 currPos.right.content.value
8964 ))) {
8965 if (!currPos.right.deleted) {
8966 negatedAttributes.delete(
8967 /** @type {ContentFormat} */
8968 currPos.right.content.key
8969 );
8970 }
8971 currPos.forward();
8972 }
8973 const doc2 = transaction.doc;
8974 const ownClientId = doc2.clientID;
8975 negatedAttributes.forEach((val, key) => {
8976 const left = currPos.left;
8977 const right = currPos.right;
8978 const nextFormat = new Item(createID(ownClientId, getState(doc2.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key, val));
8979 nextFormat.integrate(transaction, 0);
8980 currPos.right = nextFormat;
8981 currPos.forward();
8982 });
8983 };
8984 var updateCurrentAttributes = (currentAttributes, format) => {
8985 const { key, value } = format;
8986 if (value === null) {
8987 currentAttributes.delete(key);
8988 } else {
8989 currentAttributes.set(key, value);
8990 }
8991 };
8992 var minimizeAttributeChanges = (currPos, attributes) => {
8993 while (true) {
8994 if (currPos.right === null) {
8995 break;
8996 } else if (currPos.right.deleted || currPos.right.content.constructor === ContentFormat && equalAttrs(
8997 attributes[
8998 /** @type {ContentFormat} */
8999 currPos.right.content.key
9000 ] || null,
9001 /** @type {ContentFormat} */
9002 currPos.right.content.value
9003 )) ;
9004 else {
9005 break;
9006 }
9007 currPos.forward();
9008 }
9009 };
9010 var insertAttributes = (transaction, parent, currPos, attributes) => {
9011 const doc2 = transaction.doc;
9012 const ownClientId = doc2.clientID;
9013 const negatedAttributes = /* @__PURE__ */ new Map();
9014 for (const key in attributes) {
9015 const val = attributes[key];
9016 const currentVal = currPos.currentAttributes.get(key) || null;
9017 if (!equalAttrs(currentVal, val)) {
9018 negatedAttributes.set(key, currentVal);
9019 const { left, right } = currPos;
9020 currPos.right = new Item(createID(ownClientId, getState(doc2.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, new ContentFormat(key, val));
9021 currPos.right.integrate(transaction, 0);
9022 currPos.forward();
9023 }
9024 }
9025 return negatedAttributes;
9026 };
9027 var insertText = (transaction, parent, currPos, text2, attributes) => {
9028 currPos.currentAttributes.forEach((_val, key) => {
9029 if (attributes[key] === void 0) {
9030 attributes[key] = null;
9031 }
9032 });
9033 const doc2 = transaction.doc;
9034 const ownClientId = doc2.clientID;
9035 minimizeAttributeChanges(currPos, attributes);
9036 const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes);
9037 const content = text2.constructor === String ? new ContentString(
9038 /** @type {string} */
9039 text2
9040 ) : text2 instanceof AbstractType ? new ContentType(text2) : new ContentEmbed(text2);
9041 let { left, right, index } = currPos;
9042 if (parent._searchMarker) {
9043 updateMarkerChanges(parent._searchMarker, currPos.index, content.getLength());
9044 }
9045 right = new Item(createID(ownClientId, getState(doc2.store, ownClientId)), left, left && left.lastId, right, right && right.id, parent, null, content);
9046 right.integrate(transaction, 0);
9047 currPos.right = right;
9048 currPos.index = index;
9049 currPos.forward();
9050 insertNegatedAttributes(transaction, parent, currPos, negatedAttributes);
9051 };
9052 var formatText = (transaction, parent, currPos, length3, attributes) => {
9053 const doc2 = transaction.doc;
9054 const ownClientId = doc2.clientID;
9055 minimizeAttributeChanges(currPos, attributes);
9056 const negatedAttributes = insertAttributes(transaction, parent, currPos, attributes);
9057 iterationLoop: while (currPos.right !== null && (length3 > 0 || negatedAttributes.size > 0 && (currPos.right.deleted || currPos.right.content.constructor === ContentFormat))) {
9058 if (!currPos.right.deleted) {
9059 switch (currPos.right.content.constructor) {
9060 case ContentFormat: {
9061 const { key, value } = (
9062 /** @type {ContentFormat} */
9063 currPos.right.content
9064 );
9065 const attr = attributes[key];
9066 if (attr !== void 0) {
9067 if (equalAttrs(attr, value)) {
9068 negatedAttributes.delete(key);
9069 } else {
9070 if (length3 === 0) {
9071 break iterationLoop;
9072 }
9073 negatedAttributes.set(key, value);
9074 }
9075 currPos.right.delete(transaction);
9076 } else {
9077 currPos.currentAttributes.set(key, value);
9078 }
9079 break;
9080 }
9081 default:
9082 if (length3 < currPos.right.length) {
9083 getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length3));
9084 }
9085 length3 -= currPos.right.length;
9086 break;
9087 }
9088 }
9089 currPos.forward();
9090 }
9091 if (length3 > 0) {
9092 let newlines = "";
9093 for (; length3 > 0; length3--) {
9094 newlines += "\n";
9095 }
9096 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));
9097 currPos.right.integrate(transaction, 0);
9098 currPos.forward();
9099 }
9100 insertNegatedAttributes(transaction, parent, currPos, negatedAttributes);
9101 };
9102 var cleanupFormattingGap = (transaction, start, curr, startAttributes, currAttributes) => {
9103 let end = start;
9104 const endFormats = create();
9105 while (end && (!end.countable || end.deleted)) {
9106 if (!end.deleted && end.content.constructor === ContentFormat) {
9107 const cf = (
9108 /** @type {ContentFormat} */
9109 end.content
9110 );
9111 endFormats.set(cf.key, cf);
9112 }
9113 end = end.right;
9114 }
9115 let cleanups = 0;
9116 let reachedCurr = false;
9117 while (start !== end) {
9118 if (curr === start) {
9119 reachedCurr = true;
9120 }
9121 if (!start.deleted) {
9122 const content = start.content;
9123 switch (content.constructor) {
9124 case ContentFormat: {
9125 const { key, value } = (
9126 /** @type {ContentFormat} */
9127 content
9128 );
9129 const startAttrValue = startAttributes.get(key) || null;
9130 if (endFormats.get(key) !== content || startAttrValue === value) {
9131 start.delete(transaction);
9132 cleanups++;
9133 if (!reachedCurr && (currAttributes.get(key) || null) === value && startAttrValue !== value) {
9134 if (startAttrValue === null) {
9135 currAttributes.delete(key);
9136 } else {
9137 currAttributes.set(key, startAttrValue);
9138 }
9139 }
9140 }
9141 if (!reachedCurr && !start.deleted) {
9142 updateCurrentAttributes(
9143 currAttributes,
9144 /** @type {ContentFormat} */
9145 content
9146 );
9147 }
9148 break;
9149 }
9150 }
9151 }
9152 start = /** @type {Item} */
9153 start.right;
9154 }
9155 return cleanups;
9156 };
9157 var cleanupContextlessFormattingGap = (transaction, item) => {
9158 while (item && item.right && (item.right.deleted || !item.right.countable)) {
9159 item = item.right;
9160 }
9161 const attrs = /* @__PURE__ */ new Set();
9162 while (item && (item.deleted || !item.countable)) {
9163 if (!item.deleted && item.content.constructor === ContentFormat) {
9164 const key = (
9165 /** @type {ContentFormat} */
9166 item.content.key
9167 );
9168 if (attrs.has(key)) {
9169 item.delete(transaction);
9170 } else {
9171 attrs.add(key);
9172 }
9173 }
9174 item = item.left;
9175 }
9176 };
9177 var cleanupYTextFormatting = (type) => {
9178 let res = 0;
9179 transact(
9180 /** @type {Doc} */
9181 type.doc,
9182 (transaction) => {
9183 let start = (
9184 /** @type {Item} */
9185 type._start
9186 );
9187 let end = type._start;
9188 let startAttributes = create();
9189 const currentAttributes = copy(startAttributes);
9190 while (end) {
9191 if (end.deleted === false) {
9192 switch (end.content.constructor) {
9193 case ContentFormat:
9194 updateCurrentAttributes(
9195 currentAttributes,
9196 /** @type {ContentFormat} */
9197 end.content
9198 );
9199 break;
9200 default:
9201 res += cleanupFormattingGap(transaction, start, end, startAttributes, currentAttributes);
9202 startAttributes = copy(currentAttributes);
9203 start = end;
9204 break;
9205 }
9206 }
9207 end = end.right;
9208 }
9209 }
9210 );
9211 return res;
9212 };
9213 var cleanupYTextAfterTransaction = (transaction) => {
9214 const needFullCleanup = /* @__PURE__ */ new Set();
9215 const doc2 = transaction.doc;
9216 for (const [client, afterClock] of transaction.afterState.entries()) {
9217 const clock = transaction.beforeState.get(client) || 0;
9218 if (afterClock === clock) {
9219 continue;
9220 }
9221 iterateStructs(
9222 transaction,
9223 /** @type {Array<Item|GC>} */
9224 doc2.store.clients.get(client),
9225 clock,
9226 afterClock,
9227 (item) => {
9228 if (!item.deleted && /** @type {Item} */
9229 item.content.constructor === ContentFormat && item.constructor !== GC) {
9230 needFullCleanup.add(
9231 /** @type {any} */
9232 item.parent
9233 );
9234 }
9235 }
9236 );
9237 }
9238 transact(doc2, (t) => {
9239 iterateDeletedStructs(transaction, transaction.deleteSet, (item) => {
9240 if (item instanceof GC || !/** @type {YText} */
9241 item.parent._hasFormatting || needFullCleanup.has(
9242 /** @type {YText} */
9243 item.parent
9244 )) {
9245 return;
9246 }
9247 const parent = (
9248 /** @type {YText} */
9249 item.parent
9250 );
9251 if (item.content.constructor === ContentFormat) {
9252 needFullCleanup.add(parent);
9253 } else {
9254 cleanupContextlessFormattingGap(t, item);
9255 }
9256 });
9257 for (const yText of needFullCleanup) {
9258 cleanupYTextFormatting(yText);
9259 }
9260 });
9261 };
9262 var deleteText = (transaction, currPos, length3) => {
9263 const startLength = length3;
9264 const startAttrs = copy(currPos.currentAttributes);
9265 const start = currPos.right;
9266 while (length3 > 0 && currPos.right !== null) {
9267 if (currPos.right.deleted === false) {
9268 switch (currPos.right.content.constructor) {
9269 case ContentType:
9270 case ContentEmbed:
9271 case ContentString:
9272 if (length3 < currPos.right.length) {
9273 getItemCleanStart(transaction, createID(currPos.right.id.client, currPos.right.id.clock + length3));
9274 }
9275 length3 -= currPos.right.length;
9276 currPos.right.delete(transaction);
9277 break;
9278 }
9279 }
9280 currPos.forward();
9281 }
9282 if (start) {
9283 cleanupFormattingGap(transaction, start, currPos.right, startAttrs, currPos.currentAttributes);
9284 }
9285 const parent = (
9286 /** @type {AbstractType<any>} */
9287 /** @type {Item} */
9288 (currPos.left || currPos.right).parent
9289 );
9290 if (parent._searchMarker) {
9291 updateMarkerChanges(parent._searchMarker, currPos.index, -startLength + length3);
9292 }
9293 return currPos;
9294 };
9295 var YTextEvent = class extends YEvent {
9296 /**
9297 * @param {YText} ytext
9298 * @param {Transaction} transaction
9299 * @param {Set<any>} subs The keys that changed
9300 */
9301 constructor(ytext, transaction, subs) {
9302 super(ytext, transaction);
9303 this.childListChanged = false;
9304 this.keysChanged = /* @__PURE__ */ new Set();
9305 subs.forEach((sub) => {
9306 if (sub === null) {
9307 this.childListChanged = true;
9308 } else {
9309 this.keysChanged.add(sub);
9310 }
9311 });
9312 }
9313 /**
9314 * @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}>}}
9315 */
9316 get changes() {
9317 if (this._changes === null) {
9318 const changes = {
9319 keys: this.keys,
9320 delta: this.delta,
9321 added: /* @__PURE__ */ new Set(),
9322 deleted: /* @__PURE__ */ new Set()
9323 };
9324 this._changes = changes;
9325 }
9326 return (
9327 /** @type {any} */
9328 this._changes
9329 );
9330 }
9331 /**
9332 * Compute the changes in the delta format.
9333 * A {@link https://quilljs.com/docs/delta/|Quill Delta}) that represents the changes on the document.
9334 *
9335 * @type {Array<{insert?:string|object|AbstractType<any>, delete?:number, retain?:number, attributes?: Object<string,any>}>}
9336 *
9337 * @public
9338 */
9339 get delta() {
9340 if (this._delta === null) {
9341 const y = (
9342 /** @type {Doc} */
9343 this.target.doc
9344 );
9345 const delta = [];
9346 transact(y, (transaction) => {
9347 const currentAttributes = /* @__PURE__ */ new Map();
9348 const oldAttributes = /* @__PURE__ */ new Map();
9349 let item = this.target._start;
9350 let action = null;
9351 const attributes = {};
9352 let insert = "";
9353 let retain = 0;
9354 let deleteLen = 0;
9355 const addOp = () => {
9356 if (action !== null) {
9357 let op = null;
9358 switch (action) {
9359 case "delete":
9360 if (deleteLen > 0) {
9361 op = { delete: deleteLen };
9362 }
9363 deleteLen = 0;
9364 break;
9365 case "insert":
9366 if (typeof insert === "object" || insert.length > 0) {
9367 op = { insert };
9368 if (currentAttributes.size > 0) {
9369 op.attributes = {};
9370 currentAttributes.forEach((value, key) => {
9371 if (value !== null) {
9372 op.attributes[key] = value;
9373 }
9374 });
9375 }
9376 }
9377 insert = "";
9378 break;
9379 case "retain":
9380 if (retain > 0) {
9381 op = { retain };
9382 if (!isEmpty(attributes)) {
9383 op.attributes = assign({}, attributes);
9384 }
9385 }
9386 retain = 0;
9387 break;
9388 }
9389 if (op) delta.push(op);
9390 action = null;
9391 }
9392 };
9393 while (item !== null) {
9394 switch (item.content.constructor) {
9395 case ContentType:
9396 case ContentEmbed:
9397 if (this.adds(item)) {
9398 if (!this.deletes(item)) {
9399 addOp();
9400 action = "insert";
9401 insert = item.content.getContent()[0];
9402 addOp();
9403 }
9404 } else if (this.deletes(item)) {
9405 if (action !== "delete") {
9406 addOp();
9407 action = "delete";
9408 }
9409 deleteLen += 1;
9410 } else if (!item.deleted) {
9411 if (action !== "retain") {
9412 addOp();
9413 action = "retain";
9414 }
9415 retain += 1;
9416 }
9417 break;
9418 case ContentString:
9419 if (this.adds(item)) {
9420 if (!this.deletes(item)) {
9421 if (action !== "insert") {
9422 addOp();
9423 action = "insert";
9424 }
9425 insert += /** @type {ContentString} */
9426 item.content.str;
9427 }
9428 } else if (this.deletes(item)) {
9429 if (action !== "delete") {
9430 addOp();
9431 action = "delete";
9432 }
9433 deleteLen += item.length;
9434 } else if (!item.deleted) {
9435 if (action !== "retain") {
9436 addOp();
9437 action = "retain";
9438 }
9439 retain += item.length;
9440 }
9441 break;
9442 case ContentFormat: {
9443 const { key, value } = (
9444 /** @type {ContentFormat} */
9445 item.content
9446 );
9447 if (this.adds(item)) {
9448 if (!this.deletes(item)) {
9449 const curVal = currentAttributes.get(key) || null;
9450 if (!equalAttrs(curVal, value)) {
9451 if (action === "retain") {
9452 addOp();
9453 }
9454 if (equalAttrs(value, oldAttributes.get(key) || null)) {
9455 delete attributes[key];
9456 } else {
9457 attributes[key] = value;
9458 }
9459 } else if (value !== null) {
9460 item.delete(transaction);
9461 }
9462 }
9463 } else if (this.deletes(item)) {
9464 oldAttributes.set(key, value);
9465 const curVal = currentAttributes.get(key) || null;
9466 if (!equalAttrs(curVal, value)) {
9467 if (action === "retain") {
9468 addOp();
9469 }
9470 attributes[key] = curVal;
9471 }
9472 } else if (!item.deleted) {
9473 oldAttributes.set(key, value);
9474 const attr = attributes[key];
9475 if (attr !== void 0) {
9476 if (!equalAttrs(attr, value)) {
9477 if (action === "retain") {
9478 addOp();
9479 }
9480 if (value === null) {
9481 delete attributes[key];
9482 } else {
9483 attributes[key] = value;
9484 }
9485 } else if (attr !== null) {
9486 item.delete(transaction);
9487 }
9488 }
9489 }
9490 if (!item.deleted) {
9491 if (action === "insert") {
9492 addOp();
9493 }
9494 updateCurrentAttributes(
9495 currentAttributes,
9496 /** @type {ContentFormat} */
9497 item.content
9498 );
9499 }
9500 break;
9501 }
9502 }
9503 item = item.right;
9504 }
9505 addOp();
9506 while (delta.length > 0) {
9507 const lastOp = delta[delta.length - 1];
9508 if (lastOp.retain !== void 0 && lastOp.attributes === void 0) {
9509 delta.pop();
9510 } else {
9511 break;
9512 }
9513 }
9514 });
9515 this._delta = delta;
9516 }
9517 return (
9518 /** @type {any} */
9519 this._delta
9520 );
9521 }
9522 };
9523 var YText = class _YText extends AbstractType {
9524 /**
9525 * @param {String} [string] The initial value of the YText.
9526 */
9527 constructor(string) {
9528 super();
9529 this._pending = string !== void 0 ? [() => this.insert(0, string)] : [];
9530 this._searchMarker = [];
9531 this._hasFormatting = false;
9532 }
9533 /**
9534 * Number of characters of this text type.
9535 *
9536 * @type {number}
9537 */
9538 get length() {
9539 return this._length;
9540 }
9541 /**
9542 * @param {Doc} y
9543 * @param {Item} item
9544 */
9545 _integrate(y, item) {
9546 super._integrate(y, item);
9547 try {
9548 this._pending.forEach((f) => f());
9549 } catch (e) {
9550 console.error(e);
9551 }
9552 this._pending = null;
9553 }
9554 _copy() {
9555 return new _YText();
9556 }
9557 /**
9558 * @return {YText}
9559 */
9560 clone() {
9561 const text2 = new _YText();
9562 text2.applyDelta(this.toDelta());
9563 return text2;
9564 }
9565 /**
9566 * Creates YTextEvent and calls observers.
9567 *
9568 * @param {Transaction} transaction
9569 * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified.
9570 */
9571 _callObserver(transaction, parentSubs) {
9572 super._callObserver(transaction, parentSubs);
9573 const event = new YTextEvent(this, transaction, parentSubs);
9574 callTypeObservers(this, transaction, event);
9575 if (!transaction.local && this._hasFormatting) {
9576 transaction._needFormattingCleanup = true;
9577 }
9578 }
9579 /**
9580 * Returns the unformatted string representation of this YText type.
9581 *
9582 * @public
9583 */
9584 toString() {
9585 let str = "";
9586 let n = this._start;
9587 while (n !== null) {
9588 if (!n.deleted && n.countable && n.content.constructor === ContentString) {
9589 str += /** @type {ContentString} */
9590 n.content.str;
9591 }
9592 n = n.right;
9593 }
9594 return str;
9595 }
9596 /**
9597 * Returns the unformatted string representation of this YText type.
9598 *
9599 * @return {string}
9600 * @public
9601 */
9602 toJSON() {
9603 return this.toString();
9604 }
9605 /**
9606 * Apply a {@link Delta} on this shared YText type.
9607 *
9608 * @param {any} delta The changes to apply on this element.
9609 * @param {object} opts
9610 * @param {boolean} [opts.sanitize] Sanitize input delta. Removes ending newlines if set to true.
9611 *
9612 *
9613 * @public
9614 */
9615 applyDelta(delta, { sanitize = true } = {}) {
9616 if (this.doc !== null) {
9617 transact(this.doc, (transaction) => {
9618 const currPos = new ItemTextListPosition(null, this._start, 0, /* @__PURE__ */ new Map());
9619 for (let i = 0; i < delta.length; i++) {
9620 const op = delta[i];
9621 if (op.insert !== void 0) {
9622 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;
9623 if (typeof ins !== "string" || ins.length > 0) {
9624 insertText(transaction, this, currPos, ins, op.attributes || {});
9625 }
9626 } else if (op.retain !== void 0) {
9627 formatText(transaction, this, currPos, op.retain, op.attributes || {});
9628 } else if (op.delete !== void 0) {
9629 deleteText(transaction, currPos, op.delete);
9630 }
9631 }
9632 });
9633 } else {
9634 this._pending.push(() => this.applyDelta(delta));
9635 }
9636 }
9637 /**
9638 * Returns the Delta representation of this YText type.
9639 *
9640 * @param {Snapshot} [snapshot]
9641 * @param {Snapshot} [prevSnapshot]
9642 * @param {function('removed' | 'added', ID):any} [computeYChange]
9643 * @return {any} The Delta representation of this type.
9644 *
9645 * @public
9646 */
9647 toDelta(snapshot2, prevSnapshot, computeYChange) {
9648 const ops = [];
9649 const currentAttributes = /* @__PURE__ */ new Map();
9650 const doc2 = (
9651 /** @type {Doc} */
9652 this.doc
9653 );
9654 let str = "";
9655 let n = this._start;
9656 function packStr() {
9657 if (str.length > 0) {
9658 const attributes = {};
9659 let addAttributes = false;
9660 currentAttributes.forEach((value, key) => {
9661 addAttributes = true;
9662 attributes[key] = value;
9663 });
9664 const op = { insert: str };
9665 if (addAttributes) {
9666 op.attributes = attributes;
9667 }
9668 ops.push(op);
9669 str = "";
9670 }
9671 }
9672 const computeDelta = () => {
9673 while (n !== null) {
9674 if (isVisible(n, snapshot2) || prevSnapshot !== void 0 && isVisible(n, prevSnapshot)) {
9675 switch (n.content.constructor) {
9676 case ContentString: {
9677 const cur = currentAttributes.get("ychange");
9678 if (snapshot2 !== void 0 && !isVisible(n, snapshot2)) {
9679 if (cur === void 0 || cur.user !== n.id.client || cur.type !== "removed") {
9680 packStr();
9681 currentAttributes.set("ychange", computeYChange ? computeYChange("removed", n.id) : { type: "removed" });
9682 }
9683 } else if (prevSnapshot !== void 0 && !isVisible(n, prevSnapshot)) {
9684 if (cur === void 0 || cur.user !== n.id.client || cur.type !== "added") {
9685 packStr();
9686 currentAttributes.set("ychange", computeYChange ? computeYChange("added", n.id) : { type: "added" });
9687 }
9688 } else if (cur !== void 0) {
9689 packStr();
9690 currentAttributes.delete("ychange");
9691 }
9692 str += /** @type {ContentString} */
9693 n.content.str;
9694 break;
9695 }
9696 case ContentType:
9697 case ContentEmbed: {
9698 packStr();
9699 const op = {
9700 insert: n.content.getContent()[0]
9701 };
9702 if (currentAttributes.size > 0) {
9703 const attrs = (
9704 /** @type {Object<string,any>} */
9705 {}
9706 );
9707 op.attributes = attrs;
9708 currentAttributes.forEach((value, key) => {
9709 attrs[key] = value;
9710 });
9711 }
9712 ops.push(op);
9713 break;
9714 }
9715 case ContentFormat:
9716 if (isVisible(n, snapshot2)) {
9717 packStr();
9718 updateCurrentAttributes(
9719 currentAttributes,
9720 /** @type {ContentFormat} */
9721 n.content
9722 );
9723 }
9724 break;
9725 }
9726 }
9727 n = n.right;
9728 }
9729 packStr();
9730 };
9731 if (snapshot2 || prevSnapshot) {
9732 transact(doc2, (transaction) => {
9733 if (snapshot2) {
9734 splitSnapshotAffectedStructs(transaction, snapshot2);
9735 }
9736 if (prevSnapshot) {
9737 splitSnapshotAffectedStructs(transaction, prevSnapshot);
9738 }
9739 computeDelta();
9740 }, "cleanup");
9741 } else {
9742 computeDelta();
9743 }
9744 return ops;
9745 }
9746 /**
9747 * Insert text at a given index.
9748 *
9749 * @param {number} index The index at which to start inserting.
9750 * @param {String} text The text to insert at the specified position.
9751 * @param {TextAttributes} [attributes] Optionally define some formatting
9752 * information to apply on the inserted
9753 * Text.
9754 * @public
9755 */
9756 insert(index, text2, attributes) {
9757 if (text2.length <= 0) {
9758 return;
9759 }
9760 const y = this.doc;
9761 if (y !== null) {
9762 transact(y, (transaction) => {
9763 const pos = findPosition(transaction, this, index);
9764 if (!attributes) {
9765 attributes = {};
9766 pos.currentAttributes.forEach((v, k) => {
9767 attributes[k] = v;
9768 });
9769 }
9770 insertText(transaction, this, pos, text2, attributes);
9771 });
9772 } else {
9773 this._pending.push(() => this.insert(index, text2, attributes));
9774 }
9775 }
9776 /**
9777 * Inserts an embed at a index.
9778 *
9779 * @param {number} index The index to insert the embed at.
9780 * @param {Object | AbstractType<any>} embed The Object that represents the embed.
9781 * @param {TextAttributes} attributes Attribute information to apply on the
9782 * embed
9783 *
9784 * @public
9785 */
9786 insertEmbed(index, embed, attributes = {}) {
9787 const y = this.doc;
9788 if (y !== null) {
9789 transact(y, (transaction) => {
9790 const pos = findPosition(transaction, this, index);
9791 insertText(transaction, this, pos, embed, attributes);
9792 });
9793 } else {
9794 this._pending.push(() => this.insertEmbed(index, embed, attributes));
9795 }
9796 }
9797 /**
9798 * Deletes text starting from an index.
9799 *
9800 * @param {number} index Index at which to start deleting.
9801 * @param {number} length The number of characters to remove. Defaults to 1.
9802 *
9803 * @public
9804 */
9805 delete(index, length3) {
9806 if (length3 === 0) {
9807 return;
9808 }
9809 const y = this.doc;
9810 if (y !== null) {
9811 transact(y, (transaction) => {
9812 deleteText(transaction, findPosition(transaction, this, index), length3);
9813 });
9814 } else {
9815 this._pending.push(() => this.delete(index, length3));
9816 }
9817 }
9818 /**
9819 * Assigns properties to a range of text.
9820 *
9821 * @param {number} index The position where to start formatting.
9822 * @param {number} length The amount of characters to assign properties to.
9823 * @param {TextAttributes} attributes Attribute information to apply on the
9824 * text.
9825 *
9826 * @public
9827 */
9828 format(index, length3, attributes) {
9829 if (length3 === 0) {
9830 return;
9831 }
9832 const y = this.doc;
9833 if (y !== null) {
9834 transact(y, (transaction) => {
9835 const pos = findPosition(transaction, this, index);
9836 if (pos.right === null) {
9837 return;
9838 }
9839 formatText(transaction, this, pos, length3, attributes);
9840 });
9841 } else {
9842 this._pending.push(() => this.format(index, length3, attributes));
9843 }
9844 }
9845 /**
9846 * Removes an attribute.
9847 *
9848 * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks.
9849 *
9850 * @param {String} attributeName The attribute name that is to be removed.
9851 *
9852 * @public
9853 */
9854 removeAttribute(attributeName) {
9855 if (this.doc !== null) {
9856 transact(this.doc, (transaction) => {
9857 typeMapDelete(transaction, this, attributeName);
9858 });
9859 } else {
9860 this._pending.push(() => this.removeAttribute(attributeName));
9861 }
9862 }
9863 /**
9864 * Sets or updates an attribute.
9865 *
9866 * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks.
9867 *
9868 * @param {String} attributeName The attribute name that is to be set.
9869 * @param {any} attributeValue The attribute value that is to be set.
9870 *
9871 * @public
9872 */
9873 setAttribute(attributeName, attributeValue) {
9874 if (this.doc !== null) {
9875 transact(this.doc, (transaction) => {
9876 typeMapSet(transaction, this, attributeName, attributeValue);
9877 });
9878 } else {
9879 this._pending.push(() => this.setAttribute(attributeName, attributeValue));
9880 }
9881 }
9882 /**
9883 * Returns an attribute value that belongs to the attribute name.
9884 *
9885 * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks.
9886 *
9887 * @param {String} attributeName The attribute name that identifies the
9888 * queried value.
9889 * @return {any} The queried attribute value.
9890 *
9891 * @public
9892 */
9893 getAttribute(attributeName) {
9894 return (
9895 /** @type {any} */
9896 typeMapGet(this, attributeName)
9897 );
9898 }
9899 /**
9900 * Returns all attribute name/value pairs in a JSON Object.
9901 *
9902 * @note Xml-Text nodes don't have attributes. You can use this feature to assign properties to complete text-blocks.
9903 *
9904 * @return {Object<string, any>} A JSON Object that describes the attributes.
9905 *
9906 * @public
9907 */
9908 getAttributes() {
9909 return typeMapGetAll(this);
9910 }
9911 /**
9912 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
9913 */
9914 _write(encoder) {
9915 encoder.writeTypeRef(YTextRefID);
9916 }
9917 };
9918 var readYText = (_decoder) => new YText();
9919 var YXmlTreeWalker = class {
9920 /**
9921 * @param {YXmlFragment | YXmlElement} root
9922 * @param {function(AbstractType<any>):boolean} [f]
9923 */
9924 constructor(root, f = () => true) {
9925 this._filter = f;
9926 this._root = root;
9927 this._currentNode = /** @type {Item} */
9928 root._start;
9929 this._firstCall = true;
9930 }
9931 [Symbol.iterator]() {
9932 return this;
9933 }
9934 /**
9935 * Get the next node.
9936 *
9937 * @return {IteratorResult<YXmlElement|YXmlText|YXmlHook>} The next node.
9938 *
9939 * @public
9940 */
9941 next() {
9942 let n = this._currentNode;
9943 let type = n && n.content && /** @type {any} */
9944 n.content.type;
9945 if (n !== null && (!this._firstCall || n.deleted || !this._filter(type))) {
9946 do {
9947 type = /** @type {any} */
9948 n.content.type;
9949 if (!n.deleted && (type.constructor === YXmlElement || type.constructor === YXmlFragment) && type._start !== null) {
9950 n = type._start;
9951 } else {
9952 while (n !== null) {
9953 if (n.right !== null) {
9954 n = n.right;
9955 break;
9956 } else if (n.parent === this._root) {
9957 n = null;
9958 } else {
9959 n = /** @type {AbstractType<any>} */
9960 n.parent._item;
9961 }
9962 }
9963 }
9964 } while (n !== null && (n.deleted || !this._filter(
9965 /** @type {ContentType} */
9966 n.content.type
9967 )));
9968 }
9969 this._firstCall = false;
9970 if (n === null) {
9971 return { value: void 0, done: true };
9972 }
9973 this._currentNode = n;
9974 return { value: (
9975 /** @type {any} */
9976 n.content.type
9977 ), done: false };
9978 }
9979 };
9980 var YXmlFragment = class _YXmlFragment extends AbstractType {
9981 constructor() {
9982 super();
9983 this._prelimContent = [];
9984 }
9985 /**
9986 * @type {YXmlElement|YXmlText|null}
9987 */
9988 get firstChild() {
9989 const first = this._first;
9990 return first ? first.content.getContent()[0] : null;
9991 }
9992 /**
9993 * Integrate this type into the Yjs instance.
9994 *
9995 * * Save this struct in the os
9996 * * This type is sent to other client
9997 * * Observer functions are fired
9998 *
9999 * @param {Doc} y The Yjs instance
10000 * @param {Item} item
10001 */
10002 _integrate(y, item) {
10003 super._integrate(y, item);
10004 this.insert(
10005 0,
10006 /** @type {Array<any>} */
10007 this._prelimContent
10008 );
10009 this._prelimContent = null;
10010 }
10011 _copy() {
10012 return new _YXmlFragment();
10013 }
10014 /**
10015 * @return {YXmlFragment}
10016 */
10017 clone() {
10018 const el = new _YXmlFragment();
10019 el.insert(0, this.toArray().map((item) => item instanceof AbstractType ? item.clone() : item));
10020 return el;
10021 }
10022 get length() {
10023 return this._prelimContent === null ? this._length : this._prelimContent.length;
10024 }
10025 /**
10026 * Create a subtree of childNodes.
10027 *
10028 * @example
10029 * const walker = elem.createTreeWalker(dom => dom.nodeName === 'div')
10030 * for (let node in walker) {
10031 * // `node` is a div node
10032 * nop(node)
10033 * }
10034 *
10035 * @param {function(AbstractType<any>):boolean} filter Function that is called on each child element and
10036 * returns a Boolean indicating whether the child
10037 * is to be included in the subtree.
10038 * @return {YXmlTreeWalker} A subtree and a position within it.
10039 *
10040 * @public
10041 */
10042 createTreeWalker(filter) {
10043 return new YXmlTreeWalker(this, filter);
10044 }
10045 /**
10046 * Returns the first YXmlElement that matches the query.
10047 * Similar to DOM's {@link querySelector}.
10048 *
10049 * Query support:
10050 * - tagname
10051 * TODO:
10052 * - id
10053 * - attribute
10054 *
10055 * @param {CSS_Selector} query The query on the children.
10056 * @return {YXmlElement|YXmlText|YXmlHook|null} The first element that matches the query or null.
10057 *
10058 * @public
10059 */
10060 querySelector(query) {
10061 query = query.toUpperCase();
10062 const iterator = new YXmlTreeWalker(this, (element2) => element2.nodeName && element2.nodeName.toUpperCase() === query);
10063 const next = iterator.next();
10064 if (next.done) {
10065 return null;
10066 } else {
10067 return next.value;
10068 }
10069 }
10070 /**
10071 * Returns all YXmlElements that match the query.
10072 * Similar to Dom's {@link querySelectorAll}.
10073 *
10074 * @todo Does not yet support all queries. Currently only query by tagName.
10075 *
10076 * @param {CSS_Selector} query The query on the children
10077 * @return {Array<YXmlElement|YXmlText|YXmlHook|null>} The elements that match this query.
10078 *
10079 * @public
10080 */
10081 querySelectorAll(query) {
10082 query = query.toUpperCase();
10083 return from(new YXmlTreeWalker(this, (element2) => element2.nodeName && element2.nodeName.toUpperCase() === query));
10084 }
10085 /**
10086 * Creates YXmlEvent and calls observers.
10087 *
10088 * @param {Transaction} transaction
10089 * @param {Set<null|string>} parentSubs Keys changed on this type. `null` if list was modified.
10090 */
10091 _callObserver(transaction, parentSubs) {
10092 callTypeObservers(this, transaction, new YXmlEvent(this, parentSubs, transaction));
10093 }
10094 /**
10095 * Get the string representation of all the children of this YXmlFragment.
10096 *
10097 * @return {string} The string representation of all children.
10098 */
10099 toString() {
10100 return typeListMap(this, (xml) => xml.toString()).join("");
10101 }
10102 /**
10103 * @return {string}
10104 */
10105 toJSON() {
10106 return this.toString();
10107 }
10108 /**
10109 * Creates a Dom Element that mirrors this YXmlElement.
10110 *
10111 * @param {Document} [_document=document] The document object (you must define
10112 * this when calling this method in
10113 * nodejs)
10114 * @param {Object<string, any>} [hooks={}] Optional property to customize how hooks
10115 * are presented in the DOM
10116 * @param {any} [binding] You should not set this property. This is
10117 * used if DomBinding wants to create a
10118 * association to the created DOM type.
10119 * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}
10120 *
10121 * @public
10122 */
10123 toDOM(_document = document, hooks = {}, binding) {
10124 const fragment = _document.createDocumentFragment();
10125 if (binding !== void 0) {
10126 binding._createAssociation(fragment, this);
10127 }
10128 typeListForEach(this, (xmlType) => {
10129 fragment.insertBefore(xmlType.toDOM(_document, hooks, binding), null);
10130 });
10131 return fragment;
10132 }
10133 /**
10134 * Inserts new content at an index.
10135 *
10136 * @example
10137 * // Insert character 'a' at position 0
10138 * xml.insert(0, [new Y.XmlText('text')])
10139 *
10140 * @param {number} index The index to insert content at
10141 * @param {Array<YXmlElement|YXmlText>} content The array of content
10142 */
10143 insert(index, content) {
10144 if (this.doc !== null) {
10145 transact(this.doc, (transaction) => {
10146 typeListInsertGenerics(transaction, this, index, content);
10147 });
10148 } else {
10149 this._prelimContent.splice(index, 0, ...content);
10150 }
10151 }
10152 /**
10153 * Inserts new content at an index.
10154 *
10155 * @example
10156 * // Insert character 'a' at position 0
10157 * xml.insert(0, [new Y.XmlText('text')])
10158 *
10159 * @param {null|Item|YXmlElement|YXmlText} ref The index to insert content at
10160 * @param {Array<YXmlElement|YXmlText>} content The array of content
10161 */
10162 insertAfter(ref, content) {
10163 if (this.doc !== null) {
10164 transact(this.doc, (transaction) => {
10165 const refItem = ref && ref instanceof AbstractType ? ref._item : ref;
10166 typeListInsertGenericsAfter(transaction, this, refItem, content);
10167 });
10168 } else {
10169 const pc = (
10170 /** @type {Array<any>} */
10171 this._prelimContent
10172 );
10173 const index = ref === null ? 0 : pc.findIndex((el) => el === ref) + 1;
10174 if (index === 0 && ref !== null) {
10175 throw create3("Reference item not found");
10176 }
10177 pc.splice(index, 0, ...content);
10178 }
10179 }
10180 /**
10181 * Deletes elements starting from an index.
10182 *
10183 * @param {number} index Index at which to start deleting elements
10184 * @param {number} [length=1] The number of elements to remove. Defaults to 1.
10185 */
10186 delete(index, length3 = 1) {
10187 if (this.doc !== null) {
10188 transact(this.doc, (transaction) => {
10189 typeListDelete(transaction, this, index, length3);
10190 });
10191 } else {
10192 this._prelimContent.splice(index, length3);
10193 }
10194 }
10195 /**
10196 * Transforms this YArray to a JavaScript Array.
10197 *
10198 * @return {Array<YXmlElement|YXmlText|YXmlHook>}
10199 */
10200 toArray() {
10201 return typeListToArray(this);
10202 }
10203 /**
10204 * Appends content to this YArray.
10205 *
10206 * @param {Array<YXmlElement|YXmlText>} content Array of content to append.
10207 */
10208 push(content) {
10209 this.insert(this.length, content);
10210 }
10211 /**
10212 * Preppends content to this YArray.
10213 *
10214 * @param {Array<YXmlElement|YXmlText>} content Array of content to preppend.
10215 */
10216 unshift(content) {
10217 this.insert(0, content);
10218 }
10219 /**
10220 * Returns the i-th element from a YArray.
10221 *
10222 * @param {number} index The index of the element to return from the YArray
10223 * @return {YXmlElement|YXmlText}
10224 */
10225 get(index) {
10226 return typeListGet(this, index);
10227 }
10228 /**
10229 * Transforms this YArray to a JavaScript Array.
10230 *
10231 * @param {number} [start]
10232 * @param {number} [end]
10233 * @return {Array<YXmlElement|YXmlText>}
10234 */
10235 slice(start = 0, end = this.length) {
10236 return typeListSlice(this, start, end);
10237 }
10238 /**
10239 * Executes a provided function on once on overy child element.
10240 *
10241 * @param {function(YXmlElement|YXmlText,number, typeof self):void} f A function to execute on every element of this YArray.
10242 */
10243 forEach(f) {
10244 typeListForEach(this, f);
10245 }
10246 /**
10247 * Transform the properties of this type to binary and write it to an
10248 * BinaryEncoder.
10249 *
10250 * This is called when this Item is sent to a remote peer.
10251 *
10252 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.
10253 */
10254 _write(encoder) {
10255 encoder.writeTypeRef(YXmlFragmentRefID);
10256 }
10257 };
10258 var readYXmlFragment = (_decoder) => new YXmlFragment();
10259 var YXmlElement = class _YXmlElement extends YXmlFragment {
10260 constructor(nodeName = "UNDEFINED") {
10261 super();
10262 this.nodeName = nodeName;
10263 this._prelimAttrs = /* @__PURE__ */ new Map();
10264 }
10265 /**
10266 * @type {YXmlElement|YXmlText|null}
10267 */
10268 get nextSibling() {
10269 const n = this._item ? this._item.next : null;
10270 return n ? (
10271 /** @type {YXmlElement|YXmlText} */
10272 /** @type {ContentType} */
10273 n.content.type
10274 ) : null;
10275 }
10276 /**
10277 * @type {YXmlElement|YXmlText|null}
10278 */
10279 get prevSibling() {
10280 const n = this._item ? this._item.prev : null;
10281 return n ? (
10282 /** @type {YXmlElement|YXmlText} */
10283 /** @type {ContentType} */
10284 n.content.type
10285 ) : null;
10286 }
10287 /**
10288 * Integrate this type into the Yjs instance.
10289 *
10290 * * Save this struct in the os
10291 * * This type is sent to other client
10292 * * Observer functions are fired
10293 *
10294 * @param {Doc} y The Yjs instance
10295 * @param {Item} item
10296 */
10297 _integrate(y, item) {
10298 super._integrate(y, item);
10299 /** @type {Map<string, any>} */
10300 this._prelimAttrs.forEach((value, key) => {
10301 this.setAttribute(key, value);
10302 });
10303 this._prelimAttrs = null;
10304 }
10305 /**
10306 * Creates an Item with the same effect as this Item (without position effect)
10307 *
10308 * @return {YXmlElement}
10309 */
10310 _copy() {
10311 return new _YXmlElement(this.nodeName);
10312 }
10313 /**
10314 * @return {YXmlElement<KV>}
10315 */
10316 clone() {
10317 const el = new _YXmlElement(this.nodeName);
10318 const attrs = this.getAttributes();
10319 forEach(attrs, (value, key) => {
10320 if (typeof value === "string") {
10321 el.setAttribute(key, value);
10322 }
10323 });
10324 el.insert(0, this.toArray().map((item) => item instanceof AbstractType ? item.clone() : item));
10325 return el;
10326 }
10327 /**
10328 * Returns the XML serialization of this YXmlElement.
10329 * The attributes are ordered by attribute-name, so you can easily use this
10330 * method to compare YXmlElements
10331 *
10332 * @return {string} The string representation of this type.
10333 *
10334 * @public
10335 */
10336 toString() {
10337 const attrs = this.getAttributes();
10338 const stringBuilder = [];
10339 const keys2 = [];
10340 for (const key in attrs) {
10341 keys2.push(key);
10342 }
10343 keys2.sort();
10344 const keysLen = keys2.length;
10345 for (let i = 0; i < keysLen; i++) {
10346 const key = keys2[i];
10347 stringBuilder.push(key + '="' + attrs[key] + '"');
10348 }
10349 const nodeName = this.nodeName.toLocaleLowerCase();
10350 const attrsString = stringBuilder.length > 0 ? " " + stringBuilder.join(" ") : "";
10351 return `<${nodeName}${attrsString}>${super.toString()}</${nodeName}>`;
10352 }
10353 /**
10354 * Removes an attribute from this YXmlElement.
10355 *
10356 * @param {string} attributeName The attribute name that is to be removed.
10357 *
10358 * @public
10359 */
10360 removeAttribute(attributeName) {
10361 if (this.doc !== null) {
10362 transact(this.doc, (transaction) => {
10363 typeMapDelete(transaction, this, attributeName);
10364 });
10365 } else {
10366 this._prelimAttrs.delete(attributeName);
10367 }
10368 }
10369 /**
10370 * Sets or updates an attribute.
10371 *
10372 * @template {keyof KV & string} KEY
10373 *
10374 * @param {KEY} attributeName The attribute name that is to be set.
10375 * @param {KV[KEY]} attributeValue The attribute value that is to be set.
10376 *
10377 * @public
10378 */
10379 setAttribute(attributeName, attributeValue) {
10380 if (this.doc !== null) {
10381 transact(this.doc, (transaction) => {
10382 typeMapSet(transaction, this, attributeName, attributeValue);
10383 });
10384 } else {
10385 this._prelimAttrs.set(attributeName, attributeValue);
10386 }
10387 }
10388 /**
10389 * Returns an attribute value that belongs to the attribute name.
10390 *
10391 * @template {keyof KV & string} KEY
10392 *
10393 * @param {KEY} attributeName The attribute name that identifies the
10394 * queried value.
10395 * @return {KV[KEY]|undefined} The queried attribute value.
10396 *
10397 * @public
10398 */
10399 getAttribute(attributeName) {
10400 return (
10401 /** @type {any} */
10402 typeMapGet(this, attributeName)
10403 );
10404 }
10405 /**
10406 * Returns whether an attribute exists
10407 *
10408 * @param {string} attributeName The attribute name to check for existence.
10409 * @return {boolean} whether the attribute exists.
10410 *
10411 * @public
10412 */
10413 hasAttribute(attributeName) {
10414 return (
10415 /** @type {any} */
10416 typeMapHas(this, attributeName)
10417 );
10418 }
10419 /**
10420 * Returns all attribute name/value pairs in a JSON Object.
10421 *
10422 * @return {{ [Key in Extract<keyof KV,string>]?: KV[Key]}} A JSON Object that describes the attributes.
10423 *
10424 * @public
10425 */
10426 getAttributes() {
10427 return (
10428 /** @type {any} */
10429 typeMapGetAll(this)
10430 );
10431 }
10432 /**
10433 * Creates a Dom Element that mirrors this YXmlElement.
10434 *
10435 * @param {Document} [_document=document] The document object (you must define
10436 * this when calling this method in
10437 * nodejs)
10438 * @param {Object<string, any>} [hooks={}] Optional property to customize how hooks
10439 * are presented in the DOM
10440 * @param {any} [binding] You should not set this property. This is
10441 * used if DomBinding wants to create a
10442 * association to the created DOM type.
10443 * @return {Node} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}
10444 *
10445 * @public
10446 */
10447 toDOM(_document = document, hooks = {}, binding) {
10448 const dom = _document.createElement(this.nodeName);
10449 const attrs = this.getAttributes();
10450 for (const key in attrs) {
10451 const value = attrs[key];
10452 if (typeof value === "string") {
10453 dom.setAttribute(key, value);
10454 }
10455 }
10456 typeListForEach(this, (yxml) => {
10457 dom.appendChild(yxml.toDOM(_document, hooks, binding));
10458 });
10459 if (binding !== void 0) {
10460 binding._createAssociation(dom, this);
10461 }
10462 return dom;
10463 }
10464 /**
10465 * Transform the properties of this type to binary and write it to an
10466 * BinaryEncoder.
10467 *
10468 * This is called when this Item is sent to a remote peer.
10469 *
10470 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.
10471 */
10472 _write(encoder) {
10473 encoder.writeTypeRef(YXmlElementRefID);
10474 encoder.writeKey(this.nodeName);
10475 }
10476 };
10477 var readYXmlElement = (decoder) => new YXmlElement(decoder.readKey());
10478 var YXmlEvent = class extends YEvent {
10479 /**
10480 * @param {YXmlElement|YXmlText|YXmlFragment} target The target on which the event is created.
10481 * @param {Set<string|null>} subs The set of changed attributes. `null` is included if the
10482 * child list changed.
10483 * @param {Transaction} transaction The transaction instance with wich the
10484 * change was created.
10485 */
10486 constructor(target, subs, transaction) {
10487 super(target, transaction);
10488 this.childListChanged = false;
10489 this.attributesChanged = /* @__PURE__ */ new Set();
10490 subs.forEach((sub) => {
10491 if (sub === null) {
10492 this.childListChanged = true;
10493 } else {
10494 this.attributesChanged.add(sub);
10495 }
10496 });
10497 }
10498 };
10499 var YXmlHook = class _YXmlHook extends YMap {
10500 /**
10501 * @param {string} hookName nodeName of the Dom Node.
10502 */
10503 constructor(hookName) {
10504 super();
10505 this.hookName = hookName;
10506 }
10507 /**
10508 * Creates an Item with the same effect as this Item (without position effect)
10509 */
10510 _copy() {
10511 return new _YXmlHook(this.hookName);
10512 }
10513 /**
10514 * @return {YXmlHook}
10515 */
10516 clone() {
10517 const el = new _YXmlHook(this.hookName);
10518 this.forEach((value, key) => {
10519 el.set(key, value);
10520 });
10521 return el;
10522 }
10523 /**
10524 * Creates a Dom Element that mirrors this YXmlElement.
10525 *
10526 * @param {Document} [_document=document] The document object (you must define
10527 * this when calling this method in
10528 * nodejs)
10529 * @param {Object.<string, any>} [hooks] Optional property to customize how hooks
10530 * are presented in the DOM
10531 * @param {any} [binding] You should not set this property. This is
10532 * used if DomBinding wants to create a
10533 * association to the created DOM type
10534 * @return {Element} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}
10535 *
10536 * @public
10537 */
10538 toDOM(_document = document, hooks = {}, binding) {
10539 const hook = hooks[this.hookName];
10540 let dom;
10541 if (hook !== void 0) {
10542 dom = hook.createDom(this);
10543 } else {
10544 dom = document.createElement(this.hookName);
10545 }
10546 dom.setAttribute("data-yjs-hook", this.hookName);
10547 if (binding !== void 0) {
10548 binding._createAssociation(dom, this);
10549 }
10550 return dom;
10551 }
10552 /**
10553 * Transform the properties of this type to binary and write it to an
10554 * BinaryEncoder.
10555 *
10556 * This is called when this Item is sent to a remote peer.
10557 *
10558 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.
10559 */
10560 _write(encoder) {
10561 encoder.writeTypeRef(YXmlHookRefID);
10562 encoder.writeKey(this.hookName);
10563 }
10564 };
10565 var readYXmlHook = (decoder) => new YXmlHook(decoder.readKey());
10566 var YXmlText = class _YXmlText extends YText {
10567 /**
10568 * @type {YXmlElement|YXmlText|null}
10569 */
10570 get nextSibling() {
10571 const n = this._item ? this._item.next : null;
10572 return n ? (
10573 /** @type {YXmlElement|YXmlText} */
10574 /** @type {ContentType} */
10575 n.content.type
10576 ) : null;
10577 }
10578 /**
10579 * @type {YXmlElement|YXmlText|null}
10580 */
10581 get prevSibling() {
10582 const n = this._item ? this._item.prev : null;
10583 return n ? (
10584 /** @type {YXmlElement|YXmlText} */
10585 /** @type {ContentType} */
10586 n.content.type
10587 ) : null;
10588 }
10589 _copy() {
10590 return new _YXmlText();
10591 }
10592 /**
10593 * @return {YXmlText}
10594 */
10595 clone() {
10596 const text2 = new _YXmlText();
10597 text2.applyDelta(this.toDelta());
10598 return text2;
10599 }
10600 /**
10601 * Creates a Dom Element that mirrors this YXmlText.
10602 *
10603 * @param {Document} [_document=document] The document object (you must define
10604 * this when calling this method in
10605 * nodejs)
10606 * @param {Object<string, any>} [hooks] Optional property to customize how hooks
10607 * are presented in the DOM
10608 * @param {any} [binding] You should not set this property. This is
10609 * used if DomBinding wants to create a
10610 * association to the created DOM type.
10611 * @return {Text} The {@link https://developer.mozilla.org/en-US/docs/Web/API/Element|Dom Element}
10612 *
10613 * @public
10614 */
10615 toDOM(_document = document, hooks, binding) {
10616 const dom = _document.createTextNode(this.toString());
10617 if (binding !== void 0) {
10618 binding._createAssociation(dom, this);
10619 }
10620 return dom;
10621 }
10622 toString() {
10623 return this.toDelta().map((delta) => {
10624 const nestedNodes = [];
10625 for (const nodeName in delta.attributes) {
10626 const attrs = [];
10627 for (const key in delta.attributes[nodeName]) {
10628 attrs.push({ key, value: delta.attributes[nodeName][key] });
10629 }
10630 attrs.sort((a, b) => a.key < b.key ? -1 : 1);
10631 nestedNodes.push({ nodeName, attrs });
10632 }
10633 nestedNodes.sort((a, b) => a.nodeName < b.nodeName ? -1 : 1);
10634 let str = "";
10635 for (let i = 0; i < nestedNodes.length; i++) {
10636 const node = nestedNodes[i];
10637 str += `<${node.nodeName}`;
10638 for (let j = 0; j < node.attrs.length; j++) {
10639 const attr = node.attrs[j];
10640 str += ` ${attr.key}="${attr.value}"`;
10641 }
10642 str += ">";
10643 }
10644 str += delta.insert;
10645 for (let i = nestedNodes.length - 1; i >= 0; i--) {
10646 str += `</${nestedNodes[i].nodeName}>`;
10647 }
10648 return str;
10649 }).join("");
10650 }
10651 /**
10652 * @return {string}
10653 */
10654 toJSON() {
10655 return this.toString();
10656 }
10657 /**
10658 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
10659 */
10660 _write(encoder) {
10661 encoder.writeTypeRef(YXmlTextRefID);
10662 }
10663 };
10664 var readYXmlText = (decoder) => new YXmlText();
10665 var AbstractStruct = class {
10666 /**
10667 * @param {ID} id
10668 * @param {number} length
10669 */
10670 constructor(id2, length3) {
10671 this.id = id2;
10672 this.length = length3;
10673 }
10674 /**
10675 * @type {boolean}
10676 */
10677 get deleted() {
10678 throw methodUnimplemented();
10679 }
10680 /**
10681 * Merge this struct with the item to the right.
10682 * This method is already assuming that `this.id.clock + this.length === this.id.clock`.
10683 * Also this method does *not* remove right from StructStore!
10684 * @param {AbstractStruct} right
10685 * @return {boolean} wether this merged with right
10686 */
10687 mergeWith(right) {
10688 return false;
10689 }
10690 /**
10691 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.
10692 * @param {number} offset
10693 * @param {number} encodingRef
10694 */
10695 write(encoder, offset, encodingRef) {
10696 throw methodUnimplemented();
10697 }
10698 /**
10699 * @param {Transaction} transaction
10700 * @param {number} offset
10701 */
10702 integrate(transaction, offset) {
10703 throw methodUnimplemented();
10704 }
10705 };
10706 var structGCRefNumber = 0;
10707 var GC = class extends AbstractStruct {
10708 get deleted() {
10709 return true;
10710 }
10711 delete() {
10712 }
10713 /**
10714 * @param {GC} right
10715 * @return {boolean}
10716 */
10717 mergeWith(right) {
10718 if (this.constructor !== right.constructor) {
10719 return false;
10720 }
10721 this.length += right.length;
10722 return true;
10723 }
10724 /**
10725 * @param {Transaction} transaction
10726 * @param {number} offset
10727 */
10728 integrate(transaction, offset) {
10729 if (offset > 0) {
10730 this.id.clock += offset;
10731 this.length -= offset;
10732 }
10733 addStruct(transaction.doc.store, this);
10734 }
10735 /**
10736 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
10737 * @param {number} offset
10738 */
10739 write(encoder, offset) {
10740 encoder.writeInfo(structGCRefNumber);
10741 encoder.writeLen(this.length - offset);
10742 }
10743 /**
10744 * @param {Transaction} transaction
10745 * @param {StructStore} store
10746 * @return {null | number}
10747 */
10748 getMissing(transaction, store2) {
10749 return null;
10750 }
10751 };
10752 var ContentBinary = class _ContentBinary {
10753 /**
10754 * @param {Uint8Array} content
10755 */
10756 constructor(content) {
10757 this.content = content;
10758 }
10759 /**
10760 * @return {number}
10761 */
10762 getLength() {
10763 return 1;
10764 }
10765 /**
10766 * @return {Array<any>}
10767 */
10768 getContent() {
10769 return [this.content];
10770 }
10771 /**
10772 * @return {boolean}
10773 */
10774 isCountable() {
10775 return true;
10776 }
10777 /**
10778 * @return {ContentBinary}
10779 */
10780 copy() {
10781 return new _ContentBinary(this.content);
10782 }
10783 /**
10784 * @param {number} offset
10785 * @return {ContentBinary}
10786 */
10787 splice(offset) {
10788 throw methodUnimplemented();
10789 }
10790 /**
10791 * @param {ContentBinary} right
10792 * @return {boolean}
10793 */
10794 mergeWith(right) {
10795 return false;
10796 }
10797 /**
10798 * @param {Transaction} transaction
10799 * @param {Item} item
10800 */
10801 integrate(transaction, item) {
10802 }
10803 /**
10804 * @param {Transaction} transaction
10805 */
10806 delete(transaction) {
10807 }
10808 /**
10809 * @param {StructStore} store
10810 */
10811 gc(store2) {
10812 }
10813 /**
10814 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
10815 * @param {number} offset
10816 */
10817 write(encoder, offset) {
10818 encoder.writeBuf(this.content);
10819 }
10820 /**
10821 * @return {number}
10822 */
10823 getRef() {
10824 return 3;
10825 }
10826 };
10827 var readContentBinary = (decoder) => new ContentBinary(decoder.readBuf());
10828 var ContentDeleted = class _ContentDeleted {
10829 /**
10830 * @param {number} len
10831 */
10832 constructor(len) {
10833 this.len = len;
10834 }
10835 /**
10836 * @return {number}
10837 */
10838 getLength() {
10839 return this.len;
10840 }
10841 /**
10842 * @return {Array<any>}
10843 */
10844 getContent() {
10845 return [];
10846 }
10847 /**
10848 * @return {boolean}
10849 */
10850 isCountable() {
10851 return false;
10852 }
10853 /**
10854 * @return {ContentDeleted}
10855 */
10856 copy() {
10857 return new _ContentDeleted(this.len);
10858 }
10859 /**
10860 * @param {number} offset
10861 * @return {ContentDeleted}
10862 */
10863 splice(offset) {
10864 const right = new _ContentDeleted(this.len - offset);
10865 this.len = offset;
10866 return right;
10867 }
10868 /**
10869 * @param {ContentDeleted} right
10870 * @return {boolean}
10871 */
10872 mergeWith(right) {
10873 this.len += right.len;
10874 return true;
10875 }
10876 /**
10877 * @param {Transaction} transaction
10878 * @param {Item} item
10879 */
10880 integrate(transaction, item) {
10881 addToDeleteSet(transaction.deleteSet, item.id.client, item.id.clock, this.len);
10882 item.markDeleted();
10883 }
10884 /**
10885 * @param {Transaction} transaction
10886 */
10887 delete(transaction) {
10888 }
10889 /**
10890 * @param {StructStore} store
10891 */
10892 gc(store2) {
10893 }
10894 /**
10895 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
10896 * @param {number} offset
10897 */
10898 write(encoder, offset) {
10899 encoder.writeLen(this.len - offset);
10900 }
10901 /**
10902 * @return {number}
10903 */
10904 getRef() {
10905 return 1;
10906 }
10907 };
10908 var readContentDeleted = (decoder) => new ContentDeleted(decoder.readLen());
10909 var createDocFromOpts = (guid, opts) => new Doc({ guid, ...opts, shouldLoad: opts.shouldLoad || opts.autoLoad || false });
10910 var ContentDoc = class _ContentDoc {
10911 /**
10912 * @param {Doc} doc
10913 */
10914 constructor(doc2) {
10915 if (doc2._item) {
10916 console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid.");
10917 }
10918 this.doc = doc2;
10919 const opts = {};
10920 this.opts = opts;
10921 if (!doc2.gc) {
10922 opts.gc = false;
10923 }
10924 if (doc2.autoLoad) {
10925 opts.autoLoad = true;
10926 }
10927 if (doc2.meta !== null) {
10928 opts.meta = doc2.meta;
10929 }
10930 }
10931 /**
10932 * @return {number}
10933 */
10934 getLength() {
10935 return 1;
10936 }
10937 /**
10938 * @return {Array<any>}
10939 */
10940 getContent() {
10941 return [this.doc];
10942 }
10943 /**
10944 * @return {boolean}
10945 */
10946 isCountable() {
10947 return true;
10948 }
10949 /**
10950 * @return {ContentDoc}
10951 */
10952 copy() {
10953 return new _ContentDoc(createDocFromOpts(this.doc.guid, this.opts));
10954 }
10955 /**
10956 * @param {number} offset
10957 * @return {ContentDoc}
10958 */
10959 splice(offset) {
10960 throw methodUnimplemented();
10961 }
10962 /**
10963 * @param {ContentDoc} right
10964 * @return {boolean}
10965 */
10966 mergeWith(right) {
10967 return false;
10968 }
10969 /**
10970 * @param {Transaction} transaction
10971 * @param {Item} item
10972 */
10973 integrate(transaction, item) {
10974 this.doc._item = item;
10975 transaction.subdocsAdded.add(this.doc);
10976 if (this.doc.shouldLoad) {
10977 transaction.subdocsLoaded.add(this.doc);
10978 }
10979 }
10980 /**
10981 * @param {Transaction} transaction
10982 */
10983 delete(transaction) {
10984 if (transaction.subdocsAdded.has(this.doc)) {
10985 transaction.subdocsAdded.delete(this.doc);
10986 } else {
10987 transaction.subdocsRemoved.add(this.doc);
10988 }
10989 }
10990 /**
10991 * @param {StructStore} store
10992 */
10993 gc(store2) {
10994 }
10995 /**
10996 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
10997 * @param {number} offset
10998 */
10999 write(encoder, offset) {
11000 encoder.writeString(this.doc.guid);
11001 encoder.writeAny(this.opts);
11002 }
11003 /**
11004 * @return {number}
11005 */
11006 getRef() {
11007 return 9;
11008 }
11009 };
11010 var readContentDoc = (decoder) => new ContentDoc(createDocFromOpts(decoder.readString(), decoder.readAny()));
11011 var ContentEmbed = class _ContentEmbed {
11012 /**
11013 * @param {Object} embed
11014 */
11015 constructor(embed) {
11016 this.embed = embed;
11017 }
11018 /**
11019 * @return {number}
11020 */
11021 getLength() {
11022 return 1;
11023 }
11024 /**
11025 * @return {Array<any>}
11026 */
11027 getContent() {
11028 return [this.embed];
11029 }
11030 /**
11031 * @return {boolean}
11032 */
11033 isCountable() {
11034 return true;
11035 }
11036 /**
11037 * @return {ContentEmbed}
11038 */
11039 copy() {
11040 return new _ContentEmbed(this.embed);
11041 }
11042 /**
11043 * @param {number} offset
11044 * @return {ContentEmbed}
11045 */
11046 splice(offset) {
11047 throw methodUnimplemented();
11048 }
11049 /**
11050 * @param {ContentEmbed} right
11051 * @return {boolean}
11052 */
11053 mergeWith(right) {
11054 return false;
11055 }
11056 /**
11057 * @param {Transaction} transaction
11058 * @param {Item} item
11059 */
11060 integrate(transaction, item) {
11061 }
11062 /**
11063 * @param {Transaction} transaction
11064 */
11065 delete(transaction) {
11066 }
11067 /**
11068 * @param {StructStore} store
11069 */
11070 gc(store2) {
11071 }
11072 /**
11073 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
11074 * @param {number} offset
11075 */
11076 write(encoder, offset) {
11077 encoder.writeJSON(this.embed);
11078 }
11079 /**
11080 * @return {number}
11081 */
11082 getRef() {
11083 return 5;
11084 }
11085 };
11086 var readContentEmbed = (decoder) => new ContentEmbed(decoder.readJSON());
11087 var ContentFormat = class _ContentFormat {
11088 /**
11089 * @param {string} key
11090 * @param {Object} value
11091 */
11092 constructor(key, value) {
11093 this.key = key;
11094 this.value = value;
11095 }
11096 /**
11097 * @return {number}
11098 */
11099 getLength() {
11100 return 1;
11101 }
11102 /**
11103 * @return {Array<any>}
11104 */
11105 getContent() {
11106 return [];
11107 }
11108 /**
11109 * @return {boolean}
11110 */
11111 isCountable() {
11112 return false;
11113 }
11114 /**
11115 * @return {ContentFormat}
11116 */
11117 copy() {
11118 return new _ContentFormat(this.key, this.value);
11119 }
11120 /**
11121 * @param {number} _offset
11122 * @return {ContentFormat}
11123 */
11124 splice(_offset) {
11125 throw methodUnimplemented();
11126 }
11127 /**
11128 * @param {ContentFormat} _right
11129 * @return {boolean}
11130 */
11131 mergeWith(_right) {
11132 return false;
11133 }
11134 /**
11135 * @param {Transaction} _transaction
11136 * @param {Item} item
11137 */
11138 integrate(_transaction, item) {
11139 const p = (
11140 /** @type {YText} */
11141 item.parent
11142 );
11143 p._searchMarker = null;
11144 p._hasFormatting = true;
11145 }
11146 /**
11147 * @param {Transaction} transaction
11148 */
11149 delete(transaction) {
11150 }
11151 /**
11152 * @param {StructStore} store
11153 */
11154 gc(store2) {
11155 }
11156 /**
11157 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
11158 * @param {number} offset
11159 */
11160 write(encoder, offset) {
11161 encoder.writeKey(this.key);
11162 encoder.writeJSON(this.value);
11163 }
11164 /**
11165 * @return {number}
11166 */
11167 getRef() {
11168 return 6;
11169 }
11170 };
11171 var readContentFormat = (decoder) => new ContentFormat(decoder.readKey(), decoder.readJSON());
11172 var ContentJSON = class _ContentJSON {
11173 /**
11174 * @param {Array<any>} arr
11175 */
11176 constructor(arr) {
11177 this.arr = arr;
11178 }
11179 /**
11180 * @return {number}
11181 */
11182 getLength() {
11183 return this.arr.length;
11184 }
11185 /**
11186 * @return {Array<any>}
11187 */
11188 getContent() {
11189 return this.arr;
11190 }
11191 /**
11192 * @return {boolean}
11193 */
11194 isCountable() {
11195 return true;
11196 }
11197 /**
11198 * @return {ContentJSON}
11199 */
11200 copy() {
11201 return new _ContentJSON(this.arr);
11202 }
11203 /**
11204 * @param {number} offset
11205 * @return {ContentJSON}
11206 */
11207 splice(offset) {
11208 const right = new _ContentJSON(this.arr.slice(offset));
11209 this.arr = this.arr.slice(0, offset);
11210 return right;
11211 }
11212 /**
11213 * @param {ContentJSON} right
11214 * @return {boolean}
11215 */
11216 mergeWith(right) {
11217 this.arr = this.arr.concat(right.arr);
11218 return true;
11219 }
11220 /**
11221 * @param {Transaction} transaction
11222 * @param {Item} item
11223 */
11224 integrate(transaction, item) {
11225 }
11226 /**
11227 * @param {Transaction} transaction
11228 */
11229 delete(transaction) {
11230 }
11231 /**
11232 * @param {StructStore} store
11233 */
11234 gc(store2) {
11235 }
11236 /**
11237 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
11238 * @param {number} offset
11239 */
11240 write(encoder, offset) {
11241 const len = this.arr.length;
11242 encoder.writeLen(len - offset);
11243 for (let i = offset; i < len; i++) {
11244 const c = this.arr[i];
11245 encoder.writeString(c === void 0 ? "undefined" : JSON.stringify(c));
11246 }
11247 }
11248 /**
11249 * @return {number}
11250 */
11251 getRef() {
11252 return 2;
11253 }
11254 };
11255 var readContentJSON = (decoder) => {
11256 const len = decoder.readLen();
11257 const cs = [];
11258 for (let i = 0; i < len; i++) {
11259 const c = decoder.readString();
11260 if (c === "undefined") {
11261 cs.push(void 0);
11262 } else {
11263 cs.push(JSON.parse(c));
11264 }
11265 }
11266 return new ContentJSON(cs);
11267 };
11268 var ContentAny = class _ContentAny {
11269 /**
11270 * @param {Array<any>} arr
11271 */
11272 constructor(arr) {
11273 this.arr = arr;
11274 }
11275 /**
11276 * @return {number}
11277 */
11278 getLength() {
11279 return this.arr.length;
11280 }
11281 /**
11282 * @return {Array<any>}
11283 */
11284 getContent() {
11285 return this.arr;
11286 }
11287 /**
11288 * @return {boolean}
11289 */
11290 isCountable() {
11291 return true;
11292 }
11293 /**
11294 * @return {ContentAny}
11295 */
11296 copy() {
11297 return new _ContentAny(this.arr);
11298 }
11299 /**
11300 * @param {number} offset
11301 * @return {ContentAny}
11302 */
11303 splice(offset) {
11304 const right = new _ContentAny(this.arr.slice(offset));
11305 this.arr = this.arr.slice(0, offset);
11306 return right;
11307 }
11308 /**
11309 * @param {ContentAny} right
11310 * @return {boolean}
11311 */
11312 mergeWith(right) {
11313 this.arr = this.arr.concat(right.arr);
11314 return true;
11315 }
11316 /**
11317 * @param {Transaction} transaction
11318 * @param {Item} item
11319 */
11320 integrate(transaction, item) {
11321 }
11322 /**
11323 * @param {Transaction} transaction
11324 */
11325 delete(transaction) {
11326 }
11327 /**
11328 * @param {StructStore} store
11329 */
11330 gc(store2) {
11331 }
11332 /**
11333 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
11334 * @param {number} offset
11335 */
11336 write(encoder, offset) {
11337 const len = this.arr.length;
11338 encoder.writeLen(len - offset);
11339 for (let i = offset; i < len; i++) {
11340 const c = this.arr[i];
11341 encoder.writeAny(c);
11342 }
11343 }
11344 /**
11345 * @return {number}
11346 */
11347 getRef() {
11348 return 8;
11349 }
11350 };
11351 var readContentAny = (decoder) => {
11352 const len = decoder.readLen();
11353 const cs = [];
11354 for (let i = 0; i < len; i++) {
11355 cs.push(decoder.readAny());
11356 }
11357 return new ContentAny(cs);
11358 };
11359 var ContentString = class _ContentString {
11360 /**
11361 * @param {string} str
11362 */
11363 constructor(str) {
11364 this.str = str;
11365 }
11366 /**
11367 * @return {number}
11368 */
11369 getLength() {
11370 return this.str.length;
11371 }
11372 /**
11373 * @return {Array<any>}
11374 */
11375 getContent() {
11376 return this.str.split("");
11377 }
11378 /**
11379 * @return {boolean}
11380 */
11381 isCountable() {
11382 return true;
11383 }
11384 /**
11385 * @return {ContentString}
11386 */
11387 copy() {
11388 return new _ContentString(this.str);
11389 }
11390 /**
11391 * @param {number} offset
11392 * @return {ContentString}
11393 */
11394 splice(offset) {
11395 const right = new _ContentString(this.str.slice(offset));
11396 this.str = this.str.slice(0, offset);
11397 const firstCharCode = this.str.charCodeAt(offset - 1);
11398 if (firstCharCode >= 55296 && firstCharCode <= 56319) {
11399 this.str = this.str.slice(0, offset - 1) + "\uFFFD";
11400 right.str = "\uFFFD" + right.str.slice(1);
11401 }
11402 return right;
11403 }
11404 /**
11405 * @param {ContentString} right
11406 * @return {boolean}
11407 */
11408 mergeWith(right) {
11409 this.str += right.str;
11410 return true;
11411 }
11412 /**
11413 * @param {Transaction} transaction
11414 * @param {Item} item
11415 */
11416 integrate(transaction, item) {
11417 }
11418 /**
11419 * @param {Transaction} transaction
11420 */
11421 delete(transaction) {
11422 }
11423 /**
11424 * @param {StructStore} store
11425 */
11426 gc(store2) {
11427 }
11428 /**
11429 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
11430 * @param {number} offset
11431 */
11432 write(encoder, offset) {
11433 encoder.writeString(offset === 0 ? this.str : this.str.slice(offset));
11434 }
11435 /**
11436 * @return {number}
11437 */
11438 getRef() {
11439 return 4;
11440 }
11441 };
11442 var readContentString = (decoder) => new ContentString(decoder.readString());
11443 var typeRefs = [
11444 readYArray,
11445 readYMap,
11446 readYText,
11447 readYXmlElement,
11448 readYXmlFragment,
11449 readYXmlHook,
11450 readYXmlText
11451 ];
11452 var YArrayRefID = 0;
11453 var YMapRefID = 1;
11454 var YTextRefID = 2;
11455 var YXmlElementRefID = 3;
11456 var YXmlFragmentRefID = 4;
11457 var YXmlHookRefID = 5;
11458 var YXmlTextRefID = 6;
11459 var ContentType = class _ContentType {
11460 /**
11461 * @param {AbstractType<any>} type
11462 */
11463 constructor(type) {
11464 this.type = type;
11465 }
11466 /**
11467 * @return {number}
11468 */
11469 getLength() {
11470 return 1;
11471 }
11472 /**
11473 * @return {Array<any>}
11474 */
11475 getContent() {
11476 return [this.type];
11477 }
11478 /**
11479 * @return {boolean}
11480 */
11481 isCountable() {
11482 return true;
11483 }
11484 /**
11485 * @return {ContentType}
11486 */
11487 copy() {
11488 return new _ContentType(this.type._copy());
11489 }
11490 /**
11491 * @param {number} offset
11492 * @return {ContentType}
11493 */
11494 splice(offset) {
11495 throw methodUnimplemented();
11496 }
11497 /**
11498 * @param {ContentType} right
11499 * @return {boolean}
11500 */
11501 mergeWith(right) {
11502 return false;
11503 }
11504 /**
11505 * @param {Transaction} transaction
11506 * @param {Item} item
11507 */
11508 integrate(transaction, item) {
11509 this.type._integrate(transaction.doc, item);
11510 }
11511 /**
11512 * @param {Transaction} transaction
11513 */
11514 delete(transaction) {
11515 let item = this.type._start;
11516 while (item !== null) {
11517 if (!item.deleted) {
11518 item.delete(transaction);
11519 } else if (item.id.clock < (transaction.beforeState.get(item.id.client) || 0)) {
11520 transaction._mergeStructs.push(item);
11521 }
11522 item = item.right;
11523 }
11524 this.type._map.forEach((item2) => {
11525 if (!item2.deleted) {
11526 item2.delete(transaction);
11527 } else if (item2.id.clock < (transaction.beforeState.get(item2.id.client) || 0)) {
11528 transaction._mergeStructs.push(item2);
11529 }
11530 });
11531 transaction.changed.delete(this.type);
11532 }
11533 /**
11534 * @param {StructStore} store
11535 */
11536 gc(store2) {
11537 let item = this.type._start;
11538 while (item !== null) {
11539 item.gc(store2, true);
11540 item = item.right;
11541 }
11542 this.type._start = null;
11543 this.type._map.forEach(
11544 /** @param {Item | null} item */
11545 (item2) => {
11546 while (item2 !== null) {
11547 item2.gc(store2, true);
11548 item2 = item2.left;
11549 }
11550 }
11551 );
11552 this.type._map = /* @__PURE__ */ new Map();
11553 }
11554 /**
11555 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
11556 * @param {number} offset
11557 */
11558 write(encoder, offset) {
11559 this.type._write(encoder);
11560 }
11561 /**
11562 * @return {number}
11563 */
11564 getRef() {
11565 return 7;
11566 }
11567 };
11568 var readContentType = (decoder) => new ContentType(typeRefs[decoder.readTypeRef()](decoder));
11569 var followRedone = (store2, id2) => {
11570 let nextID = id2;
11571 let diff = 0;
11572 let item;
11573 do {
11574 if (diff > 0) {
11575 nextID = createID(nextID.client, nextID.clock + diff);
11576 }
11577 item = getItem(store2, nextID);
11578 diff = nextID.clock - item.id.clock;
11579 nextID = item.redone;
11580 } while (nextID !== null && item instanceof Item);
11581 return {
11582 item,
11583 diff
11584 };
11585 };
11586 var keepItem = (item, keep) => {
11587 while (item !== null && item.keep !== keep) {
11588 item.keep = keep;
11589 item = /** @type {AbstractType<any>} */
11590 item.parent._item;
11591 }
11592 };
11593 var splitItem = (transaction, leftItem, diff) => {
11594 const { client, clock } = leftItem.id;
11595 const rightItem = new Item(
11596 createID(client, clock + diff),
11597 leftItem,
11598 createID(client, clock + diff - 1),
11599 leftItem.right,
11600 leftItem.rightOrigin,
11601 leftItem.parent,
11602 leftItem.parentSub,
11603 leftItem.content.splice(diff)
11604 );
11605 if (leftItem.deleted) {
11606 rightItem.markDeleted();
11607 }
11608 if (leftItem.keep) {
11609 rightItem.keep = true;
11610 }
11611 if (leftItem.redone !== null) {
11612 rightItem.redone = createID(leftItem.redone.client, leftItem.redone.clock + diff);
11613 }
11614 leftItem.right = rightItem;
11615 if (rightItem.right !== null) {
11616 rightItem.right.left = rightItem;
11617 }
11618 transaction._mergeStructs.push(rightItem);
11619 if (rightItem.parentSub !== null && rightItem.right === null) {
11620 rightItem.parent._map.set(rightItem.parentSub, rightItem);
11621 }
11622 leftItem.length = diff;
11623 return rightItem;
11624 };
11625 var isDeletedByUndoStack = (stack, id2) => some(
11626 stack,
11627 /** @param {StackItem} s */
11628 (s) => isDeleted(s.deletions, id2)
11629 );
11630 var redoItem = (transaction, item, redoitems, itemsToDelete, ignoreRemoteMapChanges, um) => {
11631 const doc2 = transaction.doc;
11632 const store2 = doc2.store;
11633 const ownClientID = doc2.clientID;
11634 const redone = item.redone;
11635 if (redone !== null) {
11636 return getItemCleanStart(transaction, redone);
11637 }
11638 let parentItem = (
11639 /** @type {AbstractType<any>} */
11640 item.parent._item
11641 );
11642 let left = null;
11643 let right;
11644 if (parentItem !== null && parentItem.deleted === true) {
11645 if (parentItem.redone === null && (!redoitems.has(parentItem) || redoItem(transaction, parentItem, redoitems, itemsToDelete, ignoreRemoteMapChanges, um) === null)) {
11646 return null;
11647 }
11648 while (parentItem.redone !== null) {
11649 parentItem = getItemCleanStart(transaction, parentItem.redone);
11650 }
11651 }
11652 const parentType = parentItem === null ? (
11653 /** @type {AbstractType<any>} */
11654 item.parent
11655 ) : (
11656 /** @type {ContentType} */
11657 parentItem.content.type
11658 );
11659 if (item.parentSub === null) {
11660 left = item.left;
11661 right = item;
11662 while (left !== null) {
11663 let leftTrace = left;
11664 while (leftTrace !== null && /** @type {AbstractType<any>} */
11665 leftTrace.parent._item !== parentItem) {
11666 leftTrace = leftTrace.redone === null ? null : getItemCleanStart(transaction, leftTrace.redone);
11667 }
11668 if (leftTrace !== null && /** @type {AbstractType<any>} */
11669 leftTrace.parent._item === parentItem) {
11670 left = leftTrace;
11671 break;
11672 }
11673 left = left.left;
11674 }
11675 while (right !== null) {
11676 let rightTrace = right;
11677 while (rightTrace !== null && /** @type {AbstractType<any>} */
11678 rightTrace.parent._item !== parentItem) {
11679 rightTrace = rightTrace.redone === null ? null : getItemCleanStart(transaction, rightTrace.redone);
11680 }
11681 if (rightTrace !== null && /** @type {AbstractType<any>} */
11682 rightTrace.parent._item === parentItem) {
11683 right = rightTrace;
11684 break;
11685 }
11686 right = right.right;
11687 }
11688 } else {
11689 right = null;
11690 if (item.right && !ignoreRemoteMapChanges) {
11691 left = item;
11692 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))) {
11693 left = left.right;
11694 while (left.redone) left = getItemCleanStart(transaction, left.redone);
11695 }
11696 if (left && left.right !== null) {
11697 return null;
11698 }
11699 } else {
11700 left = parentType._map.get(item.parentSub) || null;
11701 }
11702 }
11703 const nextClock = getState(store2, ownClientID);
11704 const nextId = createID(ownClientID, nextClock);
11705 const redoneItem = new Item(
11706 nextId,
11707 left,
11708 left && left.lastId,
11709 right,
11710 right && right.id,
11711 parentType,
11712 item.parentSub,
11713 item.content.copy()
11714 );
11715 item.redone = nextId;
11716 keepItem(redoneItem, true);
11717 redoneItem.integrate(transaction, 0);
11718 return redoneItem;
11719 };
11720 var Item = class _Item extends AbstractStruct {
11721 /**
11722 * @param {ID} id
11723 * @param {Item | null} left
11724 * @param {ID | null} origin
11725 * @param {Item | null} right
11726 * @param {ID | null} rightOrigin
11727 * @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.
11728 * @param {string | null} parentSub
11729 * @param {AbstractContent} content
11730 */
11731 constructor(id2, left, origin, right, rightOrigin, parent, parentSub, content) {
11732 super(id2, content.getLength());
11733 this.origin = origin;
11734 this.left = left;
11735 this.right = right;
11736 this.rightOrigin = rightOrigin;
11737 this.parent = parent;
11738 this.parentSub = parentSub;
11739 this.redone = null;
11740 this.content = content;
11741 this.info = this.content.isCountable() ? BIT2 : 0;
11742 }
11743 /**
11744 * This is used to mark the item as an indexed fast-search marker
11745 *
11746 * @type {boolean}
11747 */
11748 set marker(isMarked) {
11749 if ((this.info & BIT4) > 0 !== isMarked) {
11750 this.info ^= BIT4;
11751 }
11752 }
11753 get marker() {
11754 return (this.info & BIT4) > 0;
11755 }
11756 /**
11757 * If true, do not garbage collect this Item.
11758 */
11759 get keep() {
11760 return (this.info & BIT1) > 0;
11761 }
11762 set keep(doKeep) {
11763 if (this.keep !== doKeep) {
11764 this.info ^= BIT1;
11765 }
11766 }
11767 get countable() {
11768 return (this.info & BIT2) > 0;
11769 }
11770 /**
11771 * Whether this item was deleted or not.
11772 * @type {Boolean}
11773 */
11774 get deleted() {
11775 return (this.info & BIT3) > 0;
11776 }
11777 set deleted(doDelete) {
11778 if (this.deleted !== doDelete) {
11779 this.info ^= BIT3;
11780 }
11781 }
11782 markDeleted() {
11783 this.info |= BIT3;
11784 }
11785 /**
11786 * Return the creator clientID of the missing op or define missing items and return null.
11787 *
11788 * @param {Transaction} transaction
11789 * @param {StructStore} store
11790 * @return {null | number}
11791 */
11792 getMissing(transaction, store2) {
11793 if (this.origin && this.origin.client !== this.id.client && this.origin.clock >= getState(store2, this.origin.client)) {
11794 return this.origin.client;
11795 }
11796 if (this.rightOrigin && this.rightOrigin.client !== this.id.client && this.rightOrigin.clock >= getState(store2, this.rightOrigin.client)) {
11797 return this.rightOrigin.client;
11798 }
11799 if (this.parent && this.parent.constructor === ID && this.id.client !== this.parent.client && this.parent.clock >= getState(store2, this.parent.client)) {
11800 return this.parent.client;
11801 }
11802 if (this.origin) {
11803 this.left = getItemCleanEnd(transaction, store2, this.origin);
11804 this.origin = this.left.lastId;
11805 }
11806 if (this.rightOrigin) {
11807 this.right = getItemCleanStart(transaction, this.rightOrigin);
11808 this.rightOrigin = this.right.id;
11809 }
11810 if (this.left && this.left.constructor === GC || this.right && this.right.constructor === GC) {
11811 this.parent = null;
11812 }
11813 if (!this.parent) {
11814 if (this.left && this.left.constructor === _Item) {
11815 this.parent = this.left.parent;
11816 this.parentSub = this.left.parentSub;
11817 }
11818 if (this.right && this.right.constructor === _Item) {
11819 this.parent = this.right.parent;
11820 this.parentSub = this.right.parentSub;
11821 }
11822 } else if (this.parent.constructor === ID) {
11823 const parentItem = getItem(store2, this.parent);
11824 if (parentItem.constructor === GC) {
11825 this.parent = null;
11826 } else {
11827 this.parent = /** @type {ContentType} */
11828 parentItem.content.type;
11829 }
11830 }
11831 return null;
11832 }
11833 /**
11834 * @param {Transaction} transaction
11835 * @param {number} offset
11836 */
11837 integrate(transaction, offset) {
11838 if (offset > 0) {
11839 this.id.clock += offset;
11840 this.left = getItemCleanEnd(transaction, transaction.doc.store, createID(this.id.client, this.id.clock - 1));
11841 this.origin = this.left.lastId;
11842 this.content = this.content.splice(offset);
11843 this.length -= offset;
11844 }
11845 if (this.parent) {
11846 if (!this.left && (!this.right || this.right.left !== null) || this.left && this.left.right !== this.right) {
11847 let left = this.left;
11848 let o;
11849 if (left !== null) {
11850 o = left.right;
11851 } else if (this.parentSub !== null) {
11852 o = /** @type {AbstractType<any>} */
11853 this.parent._map.get(this.parentSub) || null;
11854 while (o !== null && o.left !== null) {
11855 o = o.left;
11856 }
11857 } else {
11858 o = /** @type {AbstractType<any>} */
11859 this.parent._start;
11860 }
11861 const conflictingItems = /* @__PURE__ */ new Set();
11862 const itemsBeforeOrigin = /* @__PURE__ */ new Set();
11863 while (o !== null && o !== this.right) {
11864 itemsBeforeOrigin.add(o);
11865 conflictingItems.add(o);
11866 if (compareIDs(this.origin, o.origin)) {
11867 if (o.id.client < this.id.client) {
11868 left = o;
11869 conflictingItems.clear();
11870 } else if (compareIDs(this.rightOrigin, o.rightOrigin)) {
11871 break;
11872 }
11873 } else if (o.origin !== null && itemsBeforeOrigin.has(getItem(transaction.doc.store, o.origin))) {
11874 if (!conflictingItems.has(getItem(transaction.doc.store, o.origin))) {
11875 left = o;
11876 conflictingItems.clear();
11877 }
11878 } else {
11879 break;
11880 }
11881 o = o.right;
11882 }
11883 this.left = left;
11884 }
11885 if (this.left !== null) {
11886 const right = this.left.right;
11887 this.right = right;
11888 this.left.right = this;
11889 } else {
11890 let r;
11891 if (this.parentSub !== null) {
11892 r = /** @type {AbstractType<any>} */
11893 this.parent._map.get(this.parentSub) || null;
11894 while (r !== null && r.left !== null) {
11895 r = r.left;
11896 }
11897 } else {
11898 r = /** @type {AbstractType<any>} */
11899 this.parent._start;
11900 this.parent._start = this;
11901 }
11902 this.right = r;
11903 }
11904 if (this.right !== null) {
11905 this.right.left = this;
11906 } else if (this.parentSub !== null) {
11907 this.parent._map.set(this.parentSub, this);
11908 if (this.left !== null) {
11909 this.left.delete(transaction);
11910 }
11911 }
11912 if (this.parentSub === null && this.countable && !this.deleted) {
11913 this.parent._length += this.length;
11914 }
11915 addStruct(transaction.doc.store, this);
11916 this.content.integrate(transaction, this);
11917 addChangedTypeToTransaction(
11918 transaction,
11919 /** @type {AbstractType<any>} */
11920 this.parent,
11921 this.parentSub
11922 );
11923 if (
11924 /** @type {AbstractType<any>} */
11925 this.parent._item !== null && /** @type {AbstractType<any>} */
11926 this.parent._item.deleted || this.parentSub !== null && this.right !== null
11927 ) {
11928 this.delete(transaction);
11929 }
11930 } else {
11931 new GC(this.id, this.length).integrate(transaction, 0);
11932 }
11933 }
11934 /**
11935 * Returns the next non-deleted item
11936 */
11937 get next() {
11938 let n = this.right;
11939 while (n !== null && n.deleted) {
11940 n = n.right;
11941 }
11942 return n;
11943 }
11944 /**
11945 * Returns the previous non-deleted item
11946 */
11947 get prev() {
11948 let n = this.left;
11949 while (n !== null && n.deleted) {
11950 n = n.left;
11951 }
11952 return n;
11953 }
11954 /**
11955 * Computes the last content address of this Item.
11956 */
11957 get lastId() {
11958 return this.length === 1 ? this.id : createID(this.id.client, this.id.clock + this.length - 1);
11959 }
11960 /**
11961 * Try to merge two items
11962 *
11963 * @param {Item} right
11964 * @return {boolean}
11965 */
11966 mergeWith(right) {
11967 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)) {
11968 const searchMarker = (
11969 /** @type {AbstractType<any>} */
11970 this.parent._searchMarker
11971 );
11972 if (searchMarker) {
11973 searchMarker.forEach((marker) => {
11974 if (marker.p === right) {
11975 marker.p = this;
11976 if (!this.deleted && this.countable) {
11977 marker.index -= this.length;
11978 }
11979 }
11980 });
11981 }
11982 if (right.keep) {
11983 this.keep = true;
11984 }
11985 this.right = right.right;
11986 if (this.right !== null) {
11987 this.right.left = this;
11988 }
11989 this.length += right.length;
11990 return true;
11991 }
11992 return false;
11993 }
11994 /**
11995 * Mark this Item as deleted.
11996 *
11997 * @param {Transaction} transaction
11998 */
11999 delete(transaction) {
12000 if (!this.deleted) {
12001 const parent = (
12002 /** @type {AbstractType<any>} */
12003 this.parent
12004 );
12005 if (this.countable && this.parentSub === null) {
12006 parent._length -= this.length;
12007 }
12008 this.markDeleted();
12009 addToDeleteSet(transaction.deleteSet, this.id.client, this.id.clock, this.length);
12010 addChangedTypeToTransaction(transaction, parent, this.parentSub);
12011 this.content.delete(transaction);
12012 }
12013 }
12014 /**
12015 * @param {StructStore} store
12016 * @param {boolean} parentGCd
12017 */
12018 gc(store2, parentGCd) {
12019 if (!this.deleted) {
12020 throw unexpectedCase();
12021 }
12022 this.content.gc(store2);
12023 if (parentGCd) {
12024 replaceStruct(store2, this, new GC(this.id, this.length));
12025 } else {
12026 this.content = new ContentDeleted(this.length);
12027 }
12028 }
12029 /**
12030 * Transform the properties of this type to binary and write it to an
12031 * BinaryEncoder.
12032 *
12033 * This is called when this Item is sent to a remote peer.
12034 *
12035 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder The encoder to write data to.
12036 * @param {number} offset
12037 */
12038 write(encoder, offset) {
12039 const origin = offset > 0 ? createID(this.id.client, this.id.clock + offset - 1) : this.origin;
12040 const rightOrigin = this.rightOrigin;
12041 const parentSub = this.parentSub;
12042 const info = this.content.getRef() & BITS5 | (origin === null ? 0 : BIT8) | // origin is defined
12043 (rightOrigin === null ? 0 : BIT7) | // right origin is defined
12044 (parentSub === null ? 0 : BIT6);
12045 encoder.writeInfo(info);
12046 if (origin !== null) {
12047 encoder.writeLeftID(origin);
12048 }
12049 if (rightOrigin !== null) {
12050 encoder.writeRightID(rightOrigin);
12051 }
12052 if (origin === null && rightOrigin === null) {
12053 const parent = (
12054 /** @type {AbstractType<any>} */
12055 this.parent
12056 );
12057 if (parent._item !== void 0) {
12058 const parentItem = parent._item;
12059 if (parentItem === null) {
12060 const ykey = findRootTypeKey(parent);
12061 encoder.writeParentInfo(true);
12062 encoder.writeString(ykey);
12063 } else {
12064 encoder.writeParentInfo(false);
12065 encoder.writeLeftID(parentItem.id);
12066 }
12067 } else if (parent.constructor === String) {
12068 encoder.writeParentInfo(true);
12069 encoder.writeString(parent);
12070 } else if (parent.constructor === ID) {
12071 encoder.writeParentInfo(false);
12072 encoder.writeLeftID(parent);
12073 } else {
12074 unexpectedCase();
12075 }
12076 if (parentSub !== null) {
12077 encoder.writeString(parentSub);
12078 }
12079 }
12080 this.content.write(encoder, offset);
12081 }
12082 };
12083 var readItemContent = (decoder, info) => contentRefs[info & BITS5](decoder);
12084 var contentRefs = [
12085 () => {
12086 unexpectedCase();
12087 },
12088 // GC is not ItemContent
12089 readContentDeleted,
12090 // 1
12091 readContentJSON,
12092 // 2
12093 readContentBinary,
12094 // 3
12095 readContentString,
12096 // 4
12097 readContentEmbed,
12098 // 5
12099 readContentFormat,
12100 // 6
12101 readContentType,
12102 // 7
12103 readContentAny,
12104 // 8
12105 readContentDoc,
12106 // 9
12107 () => {
12108 unexpectedCase();
12109 }
12110 // 10 - Skip is not ItemContent
12111 ];
12112 var structSkipRefNumber = 10;
12113 var Skip = class extends AbstractStruct {
12114 get deleted() {
12115 return true;
12116 }
12117 delete() {
12118 }
12119 /**
12120 * @param {Skip} right
12121 * @return {boolean}
12122 */
12123 mergeWith(right) {
12124 if (this.constructor !== right.constructor) {
12125 return false;
12126 }
12127 this.length += right.length;
12128 return true;
12129 }
12130 /**
12131 * @param {Transaction} transaction
12132 * @param {number} offset
12133 */
12134 integrate(transaction, offset) {
12135 unexpectedCase();
12136 }
12137 /**
12138 * @param {UpdateEncoderV1 | UpdateEncoderV2} encoder
12139 * @param {number} offset
12140 */
12141 write(encoder, offset) {
12142 encoder.writeInfo(structSkipRefNumber);
12143 writeVarUint(encoder.restEncoder, this.length - offset);
12144 }
12145 /**
12146 * @param {Transaction} transaction
12147 * @param {StructStore} store
12148 * @return {null | number}
12149 */
12150 getMissing(transaction, store2) {
12151 return null;
12152 }
12153 };
12154 var glo = (
12155 /** @type {any} */
12156 typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : {}
12157 );
12158 var importIdentifier = "__ $YJS$ __";
12159 if (glo[importIdentifier] === true) {
12160 console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438");
12161 }
12162 glo[importIdentifier] = true;
12163
12164 // packages/sync/build-module/config.js
12165 var CRDT_DOC_VERSION = 1;
12166 var CRDT_DOC_META_PERSISTENCE_KEY = "fromPersistence";
12167 var CRDT_RECORD_MAP_KEY = "document";
12168 var CRDT_STATE_MAP_KEY = "state";
12169 var CRDT_STATE_VERSION_KEY = "version";
12170 var LOCAL_EDITOR_ORIGIN = "gutenberg";
12171 var LOCAL_SYNC_MANAGER_ORIGIN = "syncManager";
12172 var WORDPRESS_META_KEY_FOR_CRDT_DOC_PERSISTENCE = "_crdt_document";
12173
12174 // packages/sync/build-module/utils.js
12175 function createYjsDoc(documentMeta) {
12176 const metaMap = new Map(
12177 Object.entries(documentMeta)
12178 );
12179 const ydoc = new Doc({ meta: metaMap });
12180 const stateMap = ydoc.getMap(CRDT_STATE_MAP_KEY);
12181 stateMap.set(CRDT_STATE_VERSION_KEY, CRDT_DOC_VERSION);
12182 return ydoc;
12183 }
12184 function serializeCrdtDoc(crdtDoc) {
12185 return JSON.stringify({
12186 document: toBase64(encodeStateAsUpdateV2(crdtDoc))
12187 });
12188 }
12189 function deserializeCrdtDoc(serializedCrdtDoc) {
12190 try {
12191 const { document: document2 } = JSON.parse(serializedCrdtDoc);
12192 const docMetaMap = /* @__PURE__ */ new Map();
12193 docMetaMap.set(CRDT_DOC_META_PERSISTENCE_KEY, true);
12194 const ydoc = createYjsDoc({ meta: docMetaMap });
12195 const yupdate = fromBase64(document2);
12196 applyUpdateV2(ydoc, yupdate);
12197 ydoc.clientID = Math.floor(Math.random() * 1e9);
12198 return ydoc;
12199 } catch (e) {
12200 return null;
12201 }
12202 }
12203
12204 // packages/sync/build-module/persistence.js
12205 function getPersistedCrdtDoc(record) {
12206 const serializedCrdtDoc = record.meta?.[WORDPRESS_META_KEY_FOR_CRDT_DOC_PERSISTENCE];
12207 if (serializedCrdtDoc) {
12208 return deserializeCrdtDoc(serializedCrdtDoc);
12209 }
12210 return null;
12211 }
12212 function createPersistedCRDTDoc(ydoc) {
12213 return {
12214 [WORDPRESS_META_KEY_FOR_CRDT_DOC_PERSISTENCE]: serializeCrdtDoc(ydoc)
12215 };
12216 }
12217
12218 // packages/sync/build-module/providers/index.js
12219 var import_hooks = __toESM(require_hooks());
12220
12221 // node_modules/lib0/indexeddb.js
12222 var rtop = (request) => create4((resolve2, reject2) => {
12223 request.onerror = (event) => reject2(new Error(event.target.error));
12224 request.onsuccess = (event) => resolve2(event.target.result);
12225 });
12226 var openDB = (name, initDB) => create4((resolve2, reject2) => {
12227 const request = indexedDB.open(name);
12228 request.onupgradeneeded = (event) => initDB(event.target.result);
12229 request.onerror = (event) => reject2(create3(event.target.error));
12230 request.onsuccess = (event) => {
12231 const db = event.target.result;
12232 db.onversionchange = () => {
12233 db.close();
12234 };
12235 if (typeof addEventListener !== "undefined") {
12236 addEventListener("unload", () => db.close());
12237 }
12238 resolve2(db);
12239 };
12240 });
12241 var deleteDB = (name) => rtop(indexedDB.deleteDatabase(name));
12242 var createStores = (db, definitions) => definitions.forEach(
12243 (d) => (
12244 // @ts-ignore
12245 db.createObjectStore.apply(db, d)
12246 )
12247 );
12248 var transact2 = (db, stores, access = "readwrite") => {
12249 const transaction = db.transaction(stores, access);
12250 return stores.map((store2) => getStore(transaction, store2));
12251 };
12252 var count = (store2, range) => rtop(store2.count(range));
12253 var get = (store2, key) => rtop(store2.get(key));
12254 var del = (store2, key) => rtop(store2.delete(key));
12255 var put = (store2, item, key) => rtop(store2.put(item, key));
12256 var addAutoKey = (store2, item) => rtop(store2.add(item));
12257 var getAll = (store2, range, limit) => rtop(store2.getAll(range, limit));
12258 var queryFirst = (store2, query, direction) => {
12259 let first = null;
12260 return iterateKeys(store2, query, (key) => {
12261 first = key;
12262 return false;
12263 }, direction).then(() => first);
12264 };
12265 var getLastKey = (store2, range = null) => queryFirst(store2, range, "prev");
12266 var iterateOnRequest = (request, f) => create4((resolve2, reject2) => {
12267 request.onerror = reject2;
12268 request.onsuccess = async (event) => {
12269 const cursor = event.target.result;
12270 if (cursor === null || await f(cursor) === false) {
12271 return resolve2();
12272 }
12273 cursor.continue();
12274 };
12275 });
12276 var iterateKeys = (store2, keyrange, f, direction = "next") => iterateOnRequest(store2.openKeyCursor(keyrange, direction), (cursor) => f(cursor.key));
12277 var getStore = (t, store2) => t.objectStore(store2);
12278 var createIDBKeyRangeUpperBound = (upper, upperOpen) => IDBKeyRange.upperBound(upper, upperOpen);
12279 var createIDBKeyRangeLowerBound = (lower, lowerOpen) => IDBKeyRange.lowerBound(lower, lowerOpen);
12280
12281 // node_modules/y-indexeddb/src/y-indexeddb.js
12282 var customStoreName = "custom";
12283 var updatesStoreName = "updates";
12284 var PREFERRED_TRIM_SIZE = 500;
12285 var fetchUpdates = (idbPersistence, beforeApplyUpdatesCallback = () => {
12286 }, afterApplyUpdatesCallback = () => {
12287 }) => {
12288 const [updatesStore] = transact2(
12289 /** @type {IDBDatabase} */
12290 idbPersistence.db,
12291 [updatesStoreName]
12292 );
12293 return getAll(updatesStore, createIDBKeyRangeLowerBound(idbPersistence._dbref, false)).then((updates) => {
12294 if (!idbPersistence._destroyed) {
12295 beforeApplyUpdatesCallback(updatesStore);
12296 transact(idbPersistence.doc, () => {
12297 updates.forEach((val) => applyUpdate(idbPersistence.doc, val));
12298 }, idbPersistence, false);
12299 afterApplyUpdatesCallback(updatesStore);
12300 }
12301 }).then(() => getLastKey(updatesStore).then((lastKey) => {
12302 idbPersistence._dbref = lastKey + 1;
12303 })).then(() => count(updatesStore).then((cnt) => {
12304 idbPersistence._dbsize = cnt;
12305 })).then(() => updatesStore);
12306 };
12307 var storeState = (idbPersistence, forceStore = true) => fetchUpdates(idbPersistence).then((updatesStore) => {
12308 if (forceStore || idbPersistence._dbsize >= PREFERRED_TRIM_SIZE) {
12309 addAutoKey(updatesStore, encodeStateAsUpdate(idbPersistence.doc)).then(() => del(updatesStore, createIDBKeyRangeUpperBound(idbPersistence._dbref, true))).then(() => count(updatesStore).then((cnt) => {
12310 idbPersistence._dbsize = cnt;
12311 }));
12312 }
12313 });
12314 var IndexeddbPersistence = class extends Observable {
12315 /**
12316 * @param {string} name
12317 * @param {Y.Doc} doc
12318 */
12319 constructor(name, doc2) {
12320 super();
12321 this.doc = doc2;
12322 this.name = name;
12323 this._dbref = 0;
12324 this._dbsize = 0;
12325 this._destroyed = false;
12326 this.db = null;
12327 this.synced = false;
12328 this._db = openDB(
12329 name,
12330 (db) => createStores(db, [
12331 ["updates", { autoIncrement: true }],
12332 ["custom"]
12333 ])
12334 );
12335 this.whenSynced = create4((resolve2) => this.on("synced", () => resolve2(this)));
12336 this._db.then((db) => {
12337 this.db = db;
12338 const beforeApplyUpdatesCallback = (updatesStore) => addAutoKey(updatesStore, encodeStateAsUpdate(doc2));
12339 const afterApplyUpdatesCallback = () => {
12340 if (this._destroyed) return this;
12341 this.synced = true;
12342 this.emit("synced", [this]);
12343 };
12344 fetchUpdates(this, beforeApplyUpdatesCallback, afterApplyUpdatesCallback);
12345 });
12346 this._storeTimeout = 1e3;
12347 this._storeTimeoutId = null;
12348 this._storeUpdate = (update, origin) => {
12349 if (this.db && origin !== this) {
12350 const [updatesStore] = transact2(
12351 /** @type {IDBDatabase} */
12352 this.db,
12353 [updatesStoreName]
12354 );
12355 addAutoKey(updatesStore, update);
12356 if (++this._dbsize >= PREFERRED_TRIM_SIZE) {
12357 if (this._storeTimeoutId !== null) {
12358 clearTimeout(this._storeTimeoutId);
12359 }
12360 this._storeTimeoutId = setTimeout(() => {
12361 storeState(this, false);
12362 this._storeTimeoutId = null;
12363 }, this._storeTimeout);
12364 }
12365 }
12366 };
12367 doc2.on("update", this._storeUpdate);
12368 this.destroy = this.destroy.bind(this);
12369 doc2.on("destroy", this.destroy);
12370 }
12371 destroy() {
12372 if (this._storeTimeoutId) {
12373 clearTimeout(this._storeTimeoutId);
12374 }
12375 this.doc.off("update", this._storeUpdate);
12376 this.doc.off("destroy", this.destroy);
12377 this._destroyed = true;
12378 return this._db.then((db) => {
12379 db.close();
12380 });
12381 }
12382 /**
12383 * Destroys this instance and removes all data from indexeddb.
12384 *
12385 * @return {Promise<void>}
12386 */
12387 clearData() {
12388 return this.destroy().then(() => {
12389 deleteDB(this.name);
12390 });
12391 }
12392 /**
12393 * @param {String | number | ArrayBuffer | Date} key
12394 * @return {Promise<String | number | ArrayBuffer | Date | any>}
12395 */
12396 get(key) {
12397 return this._db.then((db) => {
12398 const [custom] = transact2(db, [customStoreName], "readonly");
12399 return get(custom, key);
12400 });
12401 }
12402 /**
12403 * @param {String | number | ArrayBuffer | Date} key
12404 * @param {String | number | ArrayBuffer | Date} value
12405 * @return {Promise<String | number | ArrayBuffer | Date>}
12406 */
12407 set(key, value) {
12408 return this._db.then((db) => {
12409 const [custom] = transact2(db, [customStoreName]);
12410 return put(custom, value, key);
12411 });
12412 }
12413 /**
12414 * @param {String | number | ArrayBuffer | Date} key
12415 * @return {Promise<undefined>}
12416 */
12417 del(key) {
12418 return this._db.then((db) => {
12419 const [custom] = transact2(db, [customStoreName]);
12420 return del(custom, key);
12421 });
12422 }
12423 };
12424
12425 // packages/sync/build-module/providers/indexeddb-provider.js
12426 function createIndexedDbProvider(objectType, objectId, doc2) {
12427 const roomName = `${objectType}-${objectId}`;
12428 const provider = new IndexeddbPersistence(roomName, doc2);
12429 return Promise.resolve({
12430 destroy: () => provider.destroy()
12431 });
12432 }
12433
12434 // node_modules/lib0/websocket.js
12435 var reconnectTimeoutBase = 1200;
12436 var maxReconnectTimeout = 2500;
12437 var messageReconnectTimeout = 3e4;
12438 var setupWS = (wsclient) => {
12439 if (wsclient.shouldConnect && wsclient.ws === null) {
12440 const websocket = new WebSocket(wsclient.url);
12441 const binaryType = wsclient.binaryType;
12442 let pingTimeout = null;
12443 if (binaryType) {
12444 websocket.binaryType = binaryType;
12445 }
12446 wsclient.ws = websocket;
12447 wsclient.connecting = true;
12448 wsclient.connected = false;
12449 websocket.onmessage = (event) => {
12450 wsclient.lastMessageReceived = getUnixTime();
12451 const data = event.data;
12452 const message = typeof data === "string" ? JSON.parse(data) : data;
12453 if (message && message.type === "pong") {
12454 clearTimeout(pingTimeout);
12455 pingTimeout = setTimeout(sendPing, messageReconnectTimeout / 2);
12456 }
12457 wsclient.emit("message", [message, wsclient]);
12458 };
12459 const onclose = (error) => {
12460 if (wsclient.ws !== null) {
12461 wsclient.ws = null;
12462 wsclient.connecting = false;
12463 if (wsclient.connected) {
12464 wsclient.connected = false;
12465 wsclient.emit("disconnect", [{ type: "disconnect", error }, wsclient]);
12466 } else {
12467 wsclient.unsuccessfulReconnects++;
12468 }
12469 setTimeout(setupWS, min(log10(wsclient.unsuccessfulReconnects + 1) * reconnectTimeoutBase, maxReconnectTimeout), wsclient);
12470 }
12471 clearTimeout(pingTimeout);
12472 };
12473 const sendPing = () => {
12474 if (wsclient.ws === websocket) {
12475 wsclient.send({
12476 type: "ping"
12477 });
12478 }
12479 };
12480 websocket.onclose = () => onclose(null);
12481 websocket.onerror = (error) => onclose(error);
12482 websocket.onopen = () => {
12483 wsclient.lastMessageReceived = getUnixTime();
12484 wsclient.connecting = false;
12485 wsclient.connected = true;
12486 wsclient.unsuccessfulReconnects = 0;
12487 wsclient.emit("connect", [{ type: "connect" }, wsclient]);
12488 pingTimeout = setTimeout(sendPing, messageReconnectTimeout / 2);
12489 };
12490 }
12491 };
12492 var WebsocketClient = class extends Observable {
12493 /**
12494 * @param {string} url
12495 * @param {object} opts
12496 * @param {'arraybuffer' | 'blob' | null} [opts.binaryType] Set `ws.binaryType`
12497 */
12498 constructor(url, { binaryType } = {}) {
12499 super();
12500 this.url = url;
12501 this.ws = null;
12502 this.binaryType = binaryType || null;
12503 this.connected = false;
12504 this.connecting = false;
12505 this.unsuccessfulReconnects = 0;
12506 this.lastMessageReceived = 0;
12507 this.shouldConnect = true;
12508 this._checkInterval = setInterval(() => {
12509 if (this.connected && messageReconnectTimeout < getUnixTime() - this.lastMessageReceived) {
12510 this.ws.close();
12511 }
12512 }, messageReconnectTimeout / 2);
12513 setupWS(this);
12514 }
12515 /**
12516 * @param {any} message
12517 */
12518 send(message) {
12519 if (this.ws) {
12520 this.ws.send(JSON.stringify(message));
12521 }
12522 }
12523 destroy() {
12524 clearInterval(this._checkInterval);
12525 this.disconnect();
12526 super.destroy();
12527 }
12528 disconnect() {
12529 this.shouldConnect = false;
12530 if (this.ws !== null) {
12531 this.ws.close();
12532 }
12533 }
12534 connect() {
12535 this.shouldConnect = true;
12536 if (!this.connected && this.ws === null) {
12537 setupWS(this);
12538 }
12539 }
12540 };
12541
12542 // node_modules/lib0/broadcastchannel.js
12543 var channels = /* @__PURE__ */ new Map();
12544 var LocalStoragePolyfill = class {
12545 /**
12546 * @param {string} room
12547 */
12548 constructor(room) {
12549 this.room = room;
12550 this.onmessage = null;
12551 this._onChange = (e) => e.key === room && this.onmessage !== null && this.onmessage({ data: fromBase64(e.newValue || "") });
12552 onChange(this._onChange);
12553 }
12554 /**
12555 * @param {ArrayBuffer} buf
12556 */
12557 postMessage(buf) {
12558 varStorage.setItem(this.room, toBase64(createUint8ArrayFromArrayBuffer(buf)));
12559 }
12560 close() {
12561 offChange(this._onChange);
12562 }
12563 };
12564 var BC = typeof BroadcastChannel === "undefined" ? LocalStoragePolyfill : BroadcastChannel;
12565 var getChannel = (room) => setIfUndefined(channels, room, () => {
12566 const subs = create2();
12567 const bc = new BC(room);
12568 bc.onmessage = (e) => subs.forEach((sub) => sub(e.data, "broadcastchannel"));
12569 return {
12570 bc,
12571 subs
12572 };
12573 });
12574 var subscribe = (room, f) => {
12575 getChannel(room).subs.add(f);
12576 return f;
12577 };
12578 var unsubscribe = (room, f) => {
12579 const channel = getChannel(room);
12580 const unsubscribed = channel.subs.delete(f);
12581 if (unsubscribed && channel.subs.size === 0) {
12582 channel.bc.close();
12583 channels.delete(room);
12584 }
12585 return unsubscribed;
12586 };
12587 var publish = (room, data, origin = null) => {
12588 const c = getChannel(room);
12589 c.bc.postMessage(data);
12590 c.subs.forEach((sub) => sub(data, origin));
12591 };
12592
12593 // node_modules/lib0/mutex.js
12594 var createMutex = () => {
12595 let token = true;
12596 return (f, g) => {
12597 if (token) {
12598 token = false;
12599 try {
12600 f();
12601 } finally {
12602 token = true;
12603 }
12604 } else if (g !== void 0) {
12605 g();
12606 }
12607 };
12608 };
12609
12610 // packages/sync/build-module/providers/y-webrtc/y-webrtc.js
12611 var import_simplepeer_min = __toESM(require_simplepeer_min());
12612
12613 // node_modules/y-protocols/sync.js
12614 var messageYjsSyncStep1 = 0;
12615 var messageYjsSyncStep2 = 1;
12616 var messageYjsUpdate = 2;
12617 var writeSyncStep1 = (encoder, doc2) => {
12618 writeVarUint(encoder, messageYjsSyncStep1);
12619 const sv = encodeStateVector(doc2);
12620 writeVarUint8Array(encoder, sv);
12621 };
12622 var writeSyncStep2 = (encoder, doc2, encodedStateVector) => {
12623 writeVarUint(encoder, messageYjsSyncStep2);
12624 writeVarUint8Array(encoder, encodeStateAsUpdate(doc2, encodedStateVector));
12625 };
12626 var readSyncStep1 = (decoder, encoder, doc2) => writeSyncStep2(encoder, doc2, readVarUint8Array(decoder));
12627 var readSyncStep2 = (decoder, doc2, transactionOrigin) => {
12628 try {
12629 applyUpdate(doc2, readVarUint8Array(decoder), transactionOrigin);
12630 } catch (error) {
12631 console.error("Caught error while handling a Yjs update", error);
12632 }
12633 };
12634 var writeUpdate = (encoder, update) => {
12635 writeVarUint(encoder, messageYjsUpdate);
12636 writeVarUint8Array(encoder, update);
12637 };
12638 var readUpdate2 = readSyncStep2;
12639 var readSyncMessage = (decoder, encoder, doc2, transactionOrigin) => {
12640 const messageType = readVarUint(decoder);
12641 switch (messageType) {
12642 case messageYjsSyncStep1:
12643 readSyncStep1(decoder, encoder, doc2);
12644 break;
12645 case messageYjsSyncStep2:
12646 readSyncStep2(decoder, doc2, transactionOrigin);
12647 break;
12648 case messageYjsUpdate:
12649 readUpdate2(decoder, doc2, transactionOrigin);
12650 break;
12651 default:
12652 throw new Error("Unknown message type");
12653 }
12654 return messageType;
12655 };
12656
12657 // node_modules/y-protocols/awareness.js
12658 var outdatedTimeout = 3e4;
12659 var Awareness = class extends Observable {
12660 /**
12661 * @param {Y.Doc} doc
12662 */
12663 constructor(doc2) {
12664 super();
12665 this.doc = doc2;
12666 this.clientID = doc2.clientID;
12667 this.states = /* @__PURE__ */ new Map();
12668 this.meta = /* @__PURE__ */ new Map();
12669 this._checkInterval = /** @type {any} */
12670 setInterval(() => {
12671 const now = getUnixTime();
12672 if (this.getLocalState() !== null && outdatedTimeout / 2 <= now - /** @type {{lastUpdated:number}} */
12673 this.meta.get(this.clientID).lastUpdated) {
12674 this.setLocalState(this.getLocalState());
12675 }
12676 const remove = [];
12677 this.meta.forEach((meta, clientid) => {
12678 if (clientid !== this.clientID && outdatedTimeout <= now - meta.lastUpdated && this.states.has(clientid)) {
12679 remove.push(clientid);
12680 }
12681 });
12682 if (remove.length > 0) {
12683 removeAwarenessStates(this, remove, "timeout");
12684 }
12685 }, floor(outdatedTimeout / 10));
12686 doc2.on("destroy", () => {
12687 this.destroy();
12688 });
12689 this.setLocalState({});
12690 }
12691 destroy() {
12692 this.emit("destroy", [this]);
12693 this.setLocalState(null);
12694 super.destroy();
12695 clearInterval(this._checkInterval);
12696 }
12697 /**
12698 * @return {Object<string,any>|null}
12699 */
12700 getLocalState() {
12701 return this.states.get(this.clientID) || null;
12702 }
12703 /**
12704 * @param {Object<string,any>|null} state
12705 */
12706 setLocalState(state) {
12707 const clientID = this.clientID;
12708 const currLocalMeta = this.meta.get(clientID);
12709 const clock = currLocalMeta === void 0 ? 0 : currLocalMeta.clock + 1;
12710 const prevState = this.states.get(clientID);
12711 if (state === null) {
12712 this.states.delete(clientID);
12713 } else {
12714 this.states.set(clientID, state);
12715 }
12716 this.meta.set(clientID, {
12717 clock,
12718 lastUpdated: getUnixTime()
12719 });
12720 const added = [];
12721 const updated = [];
12722 const filteredUpdated = [];
12723 const removed = [];
12724 if (state === null) {
12725 removed.push(clientID);
12726 } else if (prevState == null) {
12727 if (state != null) {
12728 added.push(clientID);
12729 }
12730 } else {
12731 updated.push(clientID);
12732 if (!equalityDeep(prevState, state)) {
12733 filteredUpdated.push(clientID);
12734 }
12735 }
12736 if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) {
12737 this.emit("change", [{ added, updated: filteredUpdated, removed }, "local"]);
12738 }
12739 this.emit("update", [{ added, updated, removed }, "local"]);
12740 }
12741 /**
12742 * @param {string} field
12743 * @param {any} value
12744 */
12745 setLocalStateField(field, value) {
12746 const state = this.getLocalState();
12747 if (state !== null) {
12748 this.setLocalState({
12749 ...state,
12750 [field]: value
12751 });
12752 }
12753 }
12754 /**
12755 * @return {Map<number,Object<string,any>>}
12756 */
12757 getStates() {
12758 return this.states;
12759 }
12760 };
12761 var removeAwarenessStates = (awareness, clients, origin) => {
12762 const removed = [];
12763 for (let i = 0; i < clients.length; i++) {
12764 const clientID = clients[i];
12765 if (awareness.states.has(clientID)) {
12766 awareness.states.delete(clientID);
12767 if (clientID === awareness.clientID) {
12768 const curMeta = (
12769 /** @type {MetaClientState} */
12770 awareness.meta.get(clientID)
12771 );
12772 awareness.meta.set(clientID, {
12773 clock: curMeta.clock + 1,
12774 lastUpdated: getUnixTime()
12775 });
12776 }
12777 removed.push(clientID);
12778 }
12779 }
12780 if (removed.length > 0) {
12781 awareness.emit("change", [{ added: [], updated: [], removed }, origin]);
12782 awareness.emit("update", [{ added: [], updated: [], removed }, origin]);
12783 }
12784 };
12785 var encodeAwarenessUpdate = (awareness, clients, states = awareness.states) => {
12786 const len = clients.length;
12787 const encoder = createEncoder();
12788 writeVarUint(encoder, len);
12789 for (let i = 0; i < len; i++) {
12790 const clientID = clients[i];
12791 const state = states.get(clientID) || null;
12792 const clock = (
12793 /** @type {MetaClientState} */
12794 awareness.meta.get(clientID).clock
12795 );
12796 writeVarUint(encoder, clientID);
12797 writeVarUint(encoder, clock);
12798 writeVarString(encoder, JSON.stringify(state));
12799 }
12800 return toUint8Array(encoder);
12801 };
12802 var applyAwarenessUpdate = (awareness, update, origin) => {
12803 const decoder = createDecoder(update);
12804 const timestamp = getUnixTime();
12805 const added = [];
12806 const updated = [];
12807 const filteredUpdated = [];
12808 const removed = [];
12809 const len = readVarUint(decoder);
12810 for (let i = 0; i < len; i++) {
12811 const clientID = readVarUint(decoder);
12812 let clock = readVarUint(decoder);
12813 const state = JSON.parse(readVarString(decoder));
12814 const clientMeta = awareness.meta.get(clientID);
12815 const prevState = awareness.states.get(clientID);
12816 const currClock = clientMeta === void 0 ? 0 : clientMeta.clock;
12817 if (currClock < clock || currClock === clock && state === null && awareness.states.has(clientID)) {
12818 if (state === null) {
12819 if (clientID === awareness.clientID && awareness.getLocalState() != null) {
12820 clock++;
12821 } else {
12822 awareness.states.delete(clientID);
12823 }
12824 } else {
12825 awareness.states.set(clientID, state);
12826 }
12827 awareness.meta.set(clientID, {
12828 clock,
12829 lastUpdated: timestamp
12830 });
12831 if (clientMeta === void 0 && state !== null) {
12832 added.push(clientID);
12833 } else if (clientMeta !== void 0 && state === null) {
12834 removed.push(clientID);
12835 } else if (state !== null) {
12836 if (!equalityDeep(state, prevState)) {
12837 filteredUpdated.push(clientID);
12838 }
12839 updated.push(clientID);
12840 }
12841 }
12842 }
12843 if (added.length > 0 || filteredUpdated.length > 0 || removed.length > 0) {
12844 awareness.emit("change", [{
12845 added,
12846 updated: filteredUpdated,
12847 removed
12848 }, origin]);
12849 }
12850 if (added.length > 0 || updated.length > 0 || removed.length > 0) {
12851 awareness.emit("update", [{
12852 added,
12853 updated,
12854 removed
12855 }, origin]);
12856 }
12857 };
12858
12859 // packages/sync/build-module/providers/y-webrtc/crypto.js
12860 var deriveKey = (secret, roomName) => {
12861 const secretBuffer = encodeUtf8(secret).buffer;
12862 const salt = encodeUtf8(roomName).buffer;
12863 return crypto.subtle.importKey("raw", secretBuffer, "PBKDF2", false, ["deriveKey"]).then(
12864 (keyMaterial) => crypto.subtle.deriveKey(
12865 {
12866 name: "PBKDF2",
12867 salt,
12868 iterations: 1e5,
12869 hash: "SHA-256"
12870 },
12871 keyMaterial,
12872 {
12873 name: "AES-GCM",
12874 length: 256
12875 },
12876 true,
12877 ["encrypt", "decrypt"]
12878 )
12879 );
12880 };
12881 var encrypt = (data, key) => {
12882 if (!key) {
12883 return (
12884 /** @type {PromiseLike<Uint8Array>} */
12885 resolve(data)
12886 );
12887 }
12888 const iv = crypto.getRandomValues(new Uint8Array(12));
12889 return crypto.subtle.encrypt(
12890 {
12891 name: "AES-GCM",
12892 iv
12893 },
12894 key,
12895 data
12896 ).then((cipher) => {
12897 const encryptedDataEncoder = createEncoder();
12898 writeVarString(encryptedDataEncoder, "AES-GCM");
12899 writeVarUint8Array(encryptedDataEncoder, iv);
12900 writeVarUint8Array(
12901 encryptedDataEncoder,
12902 new Uint8Array(cipher)
12903 );
12904 return toUint8Array(encryptedDataEncoder);
12905 });
12906 };
12907 var encryptJson = (data, key) => {
12908 const dataEncoder = createEncoder();
12909 writeAny(dataEncoder, data);
12910 return encrypt(toUint8Array(dataEncoder), key);
12911 };
12912 var decrypt = (data, key) => {
12913 if (!key) {
12914 return (
12915 /** @type {PromiseLike<Uint8Array>} */
12916 resolve(data)
12917 );
12918 }
12919 const dataDecoder = createDecoder(data);
12920 const algorithm = readVarString(dataDecoder);
12921 if (algorithm !== "AES-GCM") {
12922 reject(create3("Unknown encryption algorithm"));
12923 }
12924 const iv = readVarUint8Array(dataDecoder);
12925 const cipher = readVarUint8Array(dataDecoder);
12926 return crypto.subtle.decrypt(
12927 {
12928 name: "AES-GCM",
12929 iv
12930 },
12931 key,
12932 cipher
12933 ).then((data2) => new Uint8Array(data2));
12934 };
12935 var decryptJson = (data, key) => decrypt(data, key).then(
12936 (decryptedValue) => readAny(
12937 createDecoder(new Uint8Array(decryptedValue))
12938 )
12939 );
12940
12941 // packages/sync/build-module/providers/y-webrtc/y-webrtc.js
12942 var log = createModuleLogger2("y-webrtc");
12943 var messageSync = 0;
12944 var messageQueryAwareness = 3;
12945 var messageAwareness = 1;
12946 var messageBcPeerId = 4;
12947 var signalingConns = /* @__PURE__ */ new Map();
12948 var rooms = /* @__PURE__ */ new Map();
12949 var checkIsSynced = (room) => {
12950 let synced = true;
12951 room.webrtcConns.forEach((peer) => {
12952 if (!peer.synced) {
12953 synced = false;
12954 }
12955 });
12956 if (!synced && room.synced || synced && !room.synced) {
12957 room.synced = synced;
12958 room.provider.emit("synced", [{ synced }]);
12959 log(
12960 "synced ",
12961 BOLD,
12962 room.name,
12963 UNBOLD,
12964 " with all peers"
12965 );
12966 }
12967 };
12968 var readMessage = (room, buf, syncedCallback) => {
12969 const decoder = createDecoder(buf);
12970 const encoder = createEncoder();
12971 const messageType = readVarUint(decoder);
12972 if (room === void 0) {
12973 return null;
12974 }
12975 const awareness = room.awareness;
12976 const doc2 = room.doc;
12977 let sendReply = false;
12978 switch (messageType) {
12979 case messageSync: {
12980 writeVarUint(encoder, messageSync);
12981 const syncMessageType = readSyncMessage(
12982 decoder,
12983 encoder,
12984 doc2,
12985 room
12986 );
12987 if (syncMessageType === messageYjsSyncStep2 && !room.synced) {
12988 syncedCallback();
12989 }
12990 if (syncMessageType === messageYjsSyncStep1) {
12991 sendReply = true;
12992 }
12993 break;
12994 }
12995 case messageQueryAwareness:
12996 writeVarUint(encoder, messageAwareness);
12997 writeVarUint8Array(
12998 encoder,
12999 encodeAwarenessUpdate(
13000 awareness,
13001 Array.from(awareness.getStates().keys())
13002 )
13003 );
13004 sendReply = true;
13005 break;
13006 case messageAwareness:
13007 applyAwarenessUpdate(
13008 awareness,
13009 readVarUint8Array(decoder),
13010 room
13011 );
13012 break;
13013 case messageBcPeerId: {
13014 const add = readUint8(decoder) === 1;
13015 const peerName = readVarString(decoder);
13016 if (peerName !== room.peerId && (room.bcConns.has(peerName) && !add || !room.bcConns.has(peerName) && add)) {
13017 const removed = [];
13018 const added = [];
13019 if (add) {
13020 room.bcConns.add(peerName);
13021 added.push(peerName);
13022 } else {
13023 room.bcConns.delete(peerName);
13024 removed.push(peerName);
13025 }
13026 room.provider.emit("peers", [
13027 {
13028 added,
13029 removed,
13030 webrtcPeers: Array.from(room.webrtcConns.keys()),
13031 bcPeers: Array.from(room.bcConns)
13032 }
13033 ]);
13034 broadcastBcPeerId(room);
13035 }
13036 break;
13037 }
13038 default:
13039 console.error("Unable to compute message");
13040 return encoder;
13041 }
13042 if (!sendReply) {
13043 return null;
13044 }
13045 return encoder;
13046 };
13047 var readPeerMessage = (peerConn, buf) => {
13048 const room = peerConn.room;
13049 log(
13050 "received message from ",
13051 BOLD,
13052 peerConn.remotePeerId,
13053 GREY,
13054 " (",
13055 room.name,
13056 ")",
13057 UNBOLD,
13058 UNCOLOR
13059 );
13060 return readMessage(room, buf, () => {
13061 peerConn.synced = true;
13062 log(
13063 "synced ",
13064 BOLD,
13065 room.name,
13066 UNBOLD,
13067 " with ",
13068 BOLD,
13069 peerConn.remotePeerId
13070 );
13071 checkIsSynced(room);
13072 });
13073 };
13074 var sendWebrtcConn = (webrtcConn, encoder) => {
13075 log(
13076 "send message to ",
13077 BOLD,
13078 webrtcConn.remotePeerId,
13079 UNBOLD,
13080 GREY,
13081 " (",
13082 webrtcConn.room.name,
13083 ")",
13084 UNCOLOR
13085 );
13086 try {
13087 webrtcConn.peer.send(toUint8Array(encoder));
13088 } catch (e) {
13089 }
13090 };
13091 var broadcastWebrtcConn = (room, m) => {
13092 log("broadcast message in ", BOLD, room.name, UNBOLD);
13093 room.webrtcConns.forEach((conn) => {
13094 try {
13095 conn.peer.send(m);
13096 } catch (e) {
13097 }
13098 });
13099 };
13100 var WebrtcConn = class {
13101 /**
13102 * @param {SignalingConn} signalingConn
13103 * @param {boolean} initiator
13104 * @param {string} remotePeerId
13105 * @param {Room} room
13106 */
13107 constructor(signalingConn, initiator, remotePeerId, room) {
13108 log("establishing connection to ", BOLD, remotePeerId);
13109 this.room = room;
13110 this.remotePeerId = remotePeerId;
13111 this.glareToken = void 0;
13112 this.closed = false;
13113 this.connected = false;
13114 this.synced = false;
13115 this.peer = new import_simplepeer_min.default({ initiator, ...room.provider.peerOpts });
13116 this.peer.on("signal", (signal) => {
13117 if (this.glareToken === void 0) {
13118 this.glareToken = Date.now() + Math.random();
13119 }
13120 publishSignalingMessage(signalingConn, room, {
13121 to: remotePeerId,
13122 from: room.peerId,
13123 type: "signal",
13124 token: this.glareToken,
13125 signal
13126 });
13127 });
13128 this.peer.on("connect", () => {
13129 log("connected to ", BOLD, remotePeerId);
13130 this.connected = true;
13131 const provider = room.provider;
13132 const doc2 = provider.doc;
13133 const awareness = room.awareness;
13134 const encoder = createEncoder();
13135 writeVarUint(encoder, messageSync);
13136 writeSyncStep1(encoder, doc2);
13137 sendWebrtcConn(this, encoder);
13138 const awarenessStates = awareness.getStates();
13139 if (awarenessStates.size > 0) {
13140 const encoder2 = createEncoder();
13141 writeVarUint(encoder2, messageAwareness);
13142 writeVarUint8Array(
13143 encoder2,
13144 encodeAwarenessUpdate(
13145 awareness,
13146 Array.from(awarenessStates.keys())
13147 )
13148 );
13149 sendWebrtcConn(this, encoder2);
13150 }
13151 });
13152 this.peer.on("close", () => {
13153 this.connected = false;
13154 this.closed = true;
13155 if (room.webrtcConns.has(this.remotePeerId)) {
13156 room.webrtcConns.delete(this.remotePeerId);
13157 room.provider.emit("peers", [
13158 {
13159 removed: [this.remotePeerId],
13160 added: [],
13161 webrtcPeers: Array.from(room.webrtcConns.keys()),
13162 bcPeers: Array.from(room.bcConns)
13163 }
13164 ]);
13165 }
13166 checkIsSynced(room);
13167 this.peer.destroy();
13168 log("closed connection to ", BOLD, remotePeerId);
13169 announceSignalingInfo(room);
13170 });
13171 this.peer.on("error", (err) => {
13172 log(
13173 "Error in connection to ",
13174 BOLD,
13175 remotePeerId,
13176 ": ",
13177 err
13178 );
13179 announceSignalingInfo(room);
13180 });
13181 this.peer.on("data", (data) => {
13182 const answer = readPeerMessage(this, data);
13183 if (answer !== null) {
13184 sendWebrtcConn(this, answer);
13185 }
13186 });
13187 }
13188 destroy() {
13189 this.peer.destroy();
13190 }
13191 };
13192 var broadcastBcMessage = (room, m) => encrypt(m, room.key).then((data) => room.mux(() => publish(room.name, data)));
13193 var broadcastRoomMessage = (room, m) => {
13194 if (room.bcconnected) {
13195 broadcastBcMessage(room, m);
13196 }
13197 broadcastWebrtcConn(room, m);
13198 };
13199 var announceSignalingInfo = (room) => {
13200 signalingConns.forEach((conn) => {
13201 if (conn.connected) {
13202 conn.send({ type: "subscribe", topics: [room.name] });
13203 if (room.webrtcConns.size < room.provider.maxConns) {
13204 publishSignalingMessage(conn, room, {
13205 type: "announce",
13206 from: room.peerId
13207 });
13208 }
13209 }
13210 });
13211 };
13212 var broadcastBcPeerId = (room) => {
13213 if (room.provider.filterBcConns) {
13214 const encoderPeerIdBc = createEncoder();
13215 writeVarUint(encoderPeerIdBc, messageBcPeerId);
13216 writeUint8(encoderPeerIdBc, 1);
13217 writeVarString(encoderPeerIdBc, room.peerId);
13218 broadcastBcMessage(room, toUint8Array(encoderPeerIdBc));
13219 }
13220 };
13221 var Room = class {
13222 /**
13223 * @param {Y.Doc} doc
13224 * @param {WebrtcProvider} provider
13225 * @param {string} name
13226 * @param {CryptoKey|null} key
13227 */
13228 constructor(doc2, provider, name, key) {
13229 this.peerId = uuidv4();
13230 this.doc = doc2;
13231 this.awareness = provider.awareness;
13232 this.provider = provider;
13233 this.synced = false;
13234 this.name = name;
13235 this.key = key;
13236 this.webrtcConns = /* @__PURE__ */ new Map();
13237 this.bcConns = /* @__PURE__ */ new Set();
13238 this.mux = createMutex();
13239 this.bcconnected = false;
13240 this._bcSubscriber = (data) => decrypt(new Uint8Array(data), key).then(
13241 (m) => this.mux(() => {
13242 const reply = readMessage(this, m, () => {
13243 });
13244 if (reply) {
13245 broadcastBcMessage(
13246 this,
13247 toUint8Array(reply)
13248 );
13249 }
13250 })
13251 );
13252 this._docUpdateHandler = (update, origin) => {
13253 const encoder = createEncoder();
13254 writeVarUint(encoder, messageSync);
13255 writeUpdate(encoder, update);
13256 broadcastRoomMessage(this, toUint8Array(encoder));
13257 };
13258 this._awarenessUpdateHandler = ({ added, updated, removed }, origin) => {
13259 const changedClients = added.concat(updated).concat(removed);
13260 const encoderAwareness = createEncoder();
13261 writeVarUint(encoderAwareness, messageAwareness);
13262 writeVarUint8Array(
13263 encoderAwareness,
13264 encodeAwarenessUpdate(
13265 this.awareness,
13266 changedClients
13267 )
13268 );
13269 broadcastRoomMessage(
13270 this,
13271 toUint8Array(encoderAwareness)
13272 );
13273 };
13274 this._beforeUnloadHandler = () => {
13275 removeAwarenessStates(
13276 this.awareness,
13277 [doc2.clientID],
13278 "window unload"
13279 );
13280 rooms.forEach((room) => {
13281 room.disconnect();
13282 });
13283 };
13284 if (typeof window !== "undefined") {
13285 window.addEventListener(
13286 "beforeunload",
13287 this._beforeUnloadHandler
13288 );
13289 } else if (typeof process !== "undefined") {
13290 process.on("exit", this._beforeUnloadHandler);
13291 }
13292 }
13293 connect() {
13294 this.doc.on("update", this._docUpdateHandler);
13295 this.awareness.on("update", this._awarenessUpdateHandler);
13296 announceSignalingInfo(this);
13297 const roomName = this.name;
13298 subscribe(roomName, this._bcSubscriber);
13299 this.bcconnected = true;
13300 broadcastBcPeerId(this);
13301 const encoderSync = createEncoder();
13302 writeVarUint(encoderSync, messageSync);
13303 writeSyncStep1(encoderSync, this.doc);
13304 broadcastBcMessage(this, toUint8Array(encoderSync));
13305 const encoderState = createEncoder();
13306 writeVarUint(encoderState, messageSync);
13307 writeSyncStep2(encoderState, this.doc);
13308 broadcastBcMessage(this, toUint8Array(encoderState));
13309 const encoderAwarenessQuery = createEncoder();
13310 writeVarUint(encoderAwarenessQuery, messageQueryAwareness);
13311 broadcastBcMessage(
13312 this,
13313 toUint8Array(encoderAwarenessQuery)
13314 );
13315 const encoderAwarenessState = createEncoder();
13316 writeVarUint(encoderAwarenessState, messageAwareness);
13317 writeVarUint8Array(
13318 encoderAwarenessState,
13319 encodeAwarenessUpdate(this.awareness, [
13320 this.doc.clientID
13321 ])
13322 );
13323 broadcastBcMessage(
13324 this,
13325 toUint8Array(encoderAwarenessState)
13326 );
13327 }
13328 disconnect() {
13329 signalingConns.forEach((conn) => {
13330 if (conn.connected) {
13331 conn.send({ type: "unsubscribe", topics: [this.name] });
13332 }
13333 });
13334 removeAwarenessStates(
13335 this.awareness,
13336 [this.doc.clientID],
13337 "disconnect"
13338 );
13339 const encoderPeerIdBc = createEncoder();
13340 writeVarUint(encoderPeerIdBc, messageBcPeerId);
13341 writeUint8(encoderPeerIdBc, 0);
13342 writeVarString(encoderPeerIdBc, this.peerId);
13343 broadcastBcMessage(this, toUint8Array(encoderPeerIdBc));
13344 unsubscribe(this.name, this._bcSubscriber);
13345 this.bcconnected = false;
13346 this.doc.off("update", this._docUpdateHandler);
13347 this.awareness.off("update", this._awarenessUpdateHandler);
13348 this.webrtcConns.forEach((conn) => conn.destroy());
13349 }
13350 destroy() {
13351 this.disconnect();
13352 if (typeof window !== "undefined") {
13353 window.removeEventListener(
13354 "beforeunload",
13355 this._beforeUnloadHandler
13356 );
13357 } else if (typeof process !== "undefined") {
13358 process.off("exit", this._beforeUnloadHandler);
13359 }
13360 }
13361 };
13362 var openRoom = (doc2, provider, name, key) => {
13363 if (rooms.has(name)) {
13364 throw create3(
13365 `A Yjs Doc connected to room "${name}" already exists!`
13366 );
13367 }
13368 const room = new Room(doc2, provider, name, key);
13369 rooms.set(
13370 name,
13371 /** @type {Room} */
13372 room
13373 );
13374 return room;
13375 };
13376 var publishSignalingMessage = (conn, room, data) => {
13377 if (room.key) {
13378 encryptJson(data, room.key).then((data2) => {
13379 conn.send({
13380 type: "publish",
13381 topic: room.name,
13382 data: toBase64(data2)
13383 });
13384 });
13385 } else {
13386 conn.send({ type: "publish", topic: room.name, data });
13387 }
13388 };
13389 var SignalingConn = class extends WebsocketClient {
13390 constructor(url) {
13391 super(url);
13392 this.providers = /* @__PURE__ */ new Set();
13393 this.on("connect", () => {
13394 log(`connected (${url})`);
13395 const topics = Array.from(rooms.keys());
13396 this.send({ type: "subscribe", topics });
13397 rooms.forEach(
13398 (room) => publishSignalingMessage(this, room, {
13399 type: "announce",
13400 from: room.peerId
13401 })
13402 );
13403 });
13404 this.on("message", (m) => {
13405 switch (m.type) {
13406 case "publish": {
13407 const roomName = m.topic;
13408 const room = rooms.get(roomName);
13409 if (room == null || typeof roomName !== "string") {
13410 return;
13411 }
13412 const execMessage = (data) => {
13413 const webrtcConns = room.webrtcConns;
13414 const peerId = room.peerId;
13415 if (data == null || data.from === peerId || data.to !== void 0 && data.to !== peerId || room.bcConns.has(data.from)) {
13416 return;
13417 }
13418 const emitPeerChange = webrtcConns.has(data.from) ? () => {
13419 } : () => room.provider.emit("peers", [
13420 {
13421 removed: [],
13422 added: [data.from],
13423 webrtcPeers: Array.from(
13424 room.webrtcConns.keys()
13425 ),
13426 bcPeers: Array.from(room.bcConns)
13427 }
13428 ]);
13429 switch (data.type) {
13430 case "announce":
13431 if (webrtcConns.size < room.provider.maxConns) {
13432 setIfUndefined(
13433 webrtcConns,
13434 data.from,
13435 () => new WebrtcConn(
13436 this,
13437 true,
13438 data.from,
13439 room
13440 )
13441 );
13442 emitPeerChange();
13443 }
13444 break;
13445 case "signal":
13446 if (data.signal.type === "offer") {
13447 const existingConn = webrtcConns.get(
13448 data.from
13449 );
13450 if (existingConn) {
13451 const remoteToken = data.token;
13452 const localToken = existingConn.glareToken;
13453 if (localToken && localToken > remoteToken) {
13454 log(
13455 "offer rejected: ",
13456 data.from
13457 );
13458 return;
13459 }
13460 existingConn.glareToken = void 0;
13461 }
13462 }
13463 if (data.signal.type === "answer") {
13464 log("offer answered by: ", data.from);
13465 const existingConn = webrtcConns.get(
13466 data.from
13467 );
13468 existingConn.glareToken = void 0;
13469 }
13470 if (data.to === peerId) {
13471 setIfUndefined(
13472 webrtcConns,
13473 data.from,
13474 () => new WebrtcConn(
13475 this,
13476 false,
13477 data.from,
13478 room
13479 )
13480 ).peer.signal(data.signal);
13481 emitPeerChange();
13482 }
13483 break;
13484 }
13485 };
13486 if (room.key) {
13487 if (typeof m.data === "string") {
13488 decryptJson(
13489 fromBase64(m.data),
13490 room.key
13491 ).then(execMessage);
13492 }
13493 } else {
13494 execMessage(m.data);
13495 }
13496 }
13497 }
13498 });
13499 this.on("disconnect", () => log(`disconnect (${url})`));
13500 }
13501 };
13502 var WebrtcProvider = class extends Observable {
13503 /**
13504 * @param {string} roomName
13505 * @param {Y.Doc} doc
13506 * @param {ProviderOptions?} opts
13507 */
13508 constructor(roomName, doc2, {
13509 signaling = ["wss://y-webrtc-eu.fly.dev"],
13510 password = null,
13511 awareness = new Awareness(doc2),
13512 maxConns = 20 + floor(rand() * 15),
13513 // the random factor reduces the chance that n clients form a cluster
13514 filterBcConns = true,
13515 peerOpts = {}
13516 // simple-peer options. See https://github.com/feross/simple-peer#peer--new-peeropts
13517 } = {}) {
13518 super();
13519 this.roomName = roomName;
13520 this.doc = doc2;
13521 this.filterBcConns = filterBcConns;
13522 this.awareness = awareness;
13523 this.shouldConnect = false;
13524 this.signalingUrls = signaling;
13525 this.signalingConns = [];
13526 this.maxConns = maxConns;
13527 this.peerOpts = peerOpts;
13528 this.key = password ? deriveKey(password, roomName) : (
13529 /** @type {PromiseLike<null>} */
13530 resolve(null)
13531 );
13532 this.room = null;
13533 this.key.then((key) => {
13534 this.room = openRoom(doc2, this, roomName, key);
13535 if (this.shouldConnect) {
13536 this.room.connect();
13537 } else {
13538 this.room.disconnect();
13539 }
13540 });
13541 this.connect();
13542 this.destroy = this.destroy.bind(this);
13543 doc2.on("destroy", this.destroy);
13544 }
13545 /**
13546 * @type {boolean}
13547 */
13548 get connected() {
13549 return this.room !== null && this.shouldConnect;
13550 }
13551 connect() {
13552 this.shouldConnect = true;
13553 this.signalingUrls.forEach((url) => {
13554 const signalingConn = setIfUndefined(
13555 signalingConns,
13556 url,
13557 () => new SignalingConn(url)
13558 );
13559 this.signalingConns.push(signalingConn);
13560 signalingConn.providers.add(this);
13561 });
13562 if (this.room) {
13563 this.room.connect();
13564 }
13565 }
13566 disconnect() {
13567 this.shouldConnect = false;
13568 this.signalingConns.forEach((conn) => {
13569 conn.providers.delete(this);
13570 if (conn.providers.size === 0) {
13571 conn.destroy();
13572 signalingConns.delete(conn.url);
13573 }
13574 });
13575 if (this.room) {
13576 this.room.disconnect();
13577 }
13578 }
13579 destroy() {
13580 this.doc.off("destroy", this.destroy);
13581 this.key.then(() => {
13582 this.room.destroy();
13583 rooms.delete(this.roomName);
13584 });
13585 super.destroy();
13586 }
13587 };
13588
13589 // packages/sync/build-module/providers/webrtc-http-stream-signaling.js
13590 var import_url2 = __toESM(require_url());
13591 function setupSignalEventHandlers(signalCon, url) {
13592 signalCon.on("connect", () => {
13593 log(`connected (${url})`);
13594 const topics = Array.from(rooms.keys());
13595 signalCon.send({ type: "subscribe", topics });
13596 rooms.forEach(
13597 (room) => publishSignalingMessage(signalCon, room, {
13598 type: "announce",
13599 from: room.peerId
13600 })
13601 );
13602 });
13603 signalCon.on(
13604 "message",
13605 (m) => {
13606 switch (m.type) {
13607 case "publish": {
13608 const roomName = m.topic;
13609 const room = rooms.get(roomName);
13610 if (room === null || typeof roomName !== "string" || room === void 0) {
13611 return;
13612 }
13613 const execMessage = (data) => {
13614 const webrtcConns = room.webrtcConns;
13615 const peerId = room.peerId;
13616 if (data === null || data.from === peerId || data.to !== void 0 && data.to !== peerId || room.bcConns.has(data.from)) {
13617 return;
13618 }
13619 const emitPeerChange = webrtcConns.has(data.from) ? () => {
13620 } : () => room.provider.emit("peers", [
13621 {
13622 removed: [],
13623 added: [data.from],
13624 webrtcPeers: Array.from(
13625 room.webrtcConns.keys()
13626 ),
13627 bcPeers: Array.from(room.bcConns)
13628 }
13629 ]);
13630 switch (data.type) {
13631 case "announce":
13632 if (webrtcConns.size < room.provider.maxConns) {
13633 setIfUndefined(
13634 webrtcConns,
13635 data.from,
13636 () => new WebrtcConn(
13637 signalCon,
13638 true,
13639 data.from,
13640 room
13641 )
13642 );
13643 emitPeerChange();
13644 }
13645 break;
13646 case "signal":
13647 if (data.signal.type === "offer") {
13648 const existingConn = webrtcConns.get(
13649 data.from
13650 );
13651 if (existingConn) {
13652 const remoteToken = data.token;
13653 const localToken = existingConn.glareToken;
13654 if (localToken && localToken > remoteToken) {
13655 log(
13656 "offer rejected: ",
13657 data.from
13658 );
13659 return;
13660 }
13661 existingConn.glareToken = void 0;
13662 }
13663 }
13664 if (data.signal.type === "answer") {
13665 log("offer answered by: ", data.from);
13666 const existingConn = webrtcConns.get(
13667 data.from
13668 );
13669 if (existingConn) {
13670 existingConn.glareToken = void 0;
13671 }
13672 }
13673 if (data.to === peerId) {
13674 setIfUndefined(
13675 webrtcConns,
13676 data.from,
13677 () => new WebrtcConn(
13678 signalCon,
13679 false,
13680 data.from,
13681 room
13682 )
13683 ).peer.signal(data.signal);
13684 emitPeerChange();
13685 }
13686 break;
13687 }
13688 };
13689 if (room.key) {
13690 if (typeof m.data === "string") {
13691 decryptJson(
13692 fromBase64(m.data),
13693 room.key
13694 ).then(execMessage);
13695 }
13696 } else {
13697 execMessage(m.data);
13698 }
13699 }
13700 }
13701 }
13702 );
13703 signalCon.on("disconnect", () => log(`disconnect (${url})`));
13704 }
13705 function setupHttpSignal(httpClient) {
13706 if (httpClient.shouldConnect && httpClient.ws === null) {
13707 const subscriberId = Math.floor(1e5 + Math.random() * 9e5);
13708 const url = httpClient.url;
13709 const eventSource = new window.EventSource(
13710 (0, import_url2.addQueryArgs)(url, {
13711 subscriber_id: subscriberId,
13712 action: "gutenberg_signaling_server"
13713 })
13714 );
13715 let pingTimeout = null;
13716 eventSource.onmessage = (event) => {
13717 httpClient.lastMessageReceived = Date.now();
13718 const data = event.data;
13719 if (data) {
13720 const messages = JSON.parse(data);
13721 if (Array.isArray(messages)) {
13722 messages.forEach(onSingleMessage);
13723 }
13724 }
13725 };
13726 httpClient.ws = eventSource;
13727 httpClient.connecting = true;
13728 httpClient.connected = false;
13729 const onSingleMessage = (message) => {
13730 if (message && message.type === "pong") {
13731 clearTimeout(pingTimeout);
13732 pingTimeout = setTimeout(
13733 sendPing,
13734 messageReconnectTimeout2 / 2
13735 );
13736 }
13737 httpClient.emit("message", [message, httpClient]);
13738 };
13739 const onclose = (error) => {
13740 if (httpClient.ws !== null) {
13741 httpClient.ws.close();
13742 httpClient.ws = null;
13743 httpClient.connecting = false;
13744 if (httpClient.connected) {
13745 httpClient.connected = false;
13746 httpClient.emit("disconnect", [
13747 { type: "disconnect", error },
13748 httpClient
13749 ]);
13750 } else {
13751 httpClient.unsuccessfulReconnects++;
13752 }
13753 }
13754 clearTimeout(pingTimeout);
13755 };
13756 const sendPing = () => {
13757 if (httpClient.ws && httpClient.ws.readyState === window.EventSource.OPEN) {
13758 httpClient.send({
13759 type: "ping"
13760 });
13761 }
13762 };
13763 if (httpClient.ws) {
13764 httpClient.ws.onclose = () => {
13765 onclose(null);
13766 };
13767 httpClient.ws.send = function send(message) {
13768 window.fetch(url, {
13769 body: new URLSearchParams({
13770 subscriber_id: subscriberId.toString(),
13771 action: "gutenberg_signaling_server",
13772 message
13773 }),
13774 method: "POST"
13775 }).catch(() => {
13776 log(
13777 "Error sending to server with message: " + message
13778 );
13779 });
13780 };
13781 }
13782 eventSource.onerror = () => {
13783 };
13784 eventSource.onopen = () => {
13785 if (httpClient.connected) {
13786 return;
13787 }
13788 if (eventSource.readyState === window.EventSource.OPEN) {
13789 httpClient.lastMessageReceived = Date.now();
13790 httpClient.connecting = false;
13791 httpClient.connected = true;
13792 httpClient.unsuccessfulReconnects = 0;
13793 httpClient.emit("connect", [
13794 { type: "connect" },
13795 httpClient
13796 ]);
13797 pingTimeout = setTimeout(
13798 sendPing,
13799 messageReconnectTimeout2 / 2
13800 );
13801 }
13802 };
13803 }
13804 }
13805 var messageReconnectTimeout2 = 3e4;
13806 var HttpSignalingConn = class extends Observable {
13807 /**
13808 * @param {string} url
13809 */
13810 constructor(url) {
13811 super();
13812 this.url = url;
13813 this.ws = null;
13814 this.binaryType = null;
13815 this.connected = false;
13816 this.connecting = false;
13817 this.unsuccessfulReconnects = 0;
13818 this.lastMessageReceived = 0;
13819 this.shouldConnect = true;
13820 this._checkInterval = setInterval(() => {
13821 if (this.connected && messageReconnectTimeout2 < Date.now() - this.lastMessageReceived && this.ws) {
13822 this.ws.close();
13823 }
13824 }, messageReconnectTimeout2 / 2);
13825 setupHttpSignal(this);
13826 this.providers = /* @__PURE__ */ new Set();
13827 setupSignalEventHandlers(this, url);
13828 }
13829 /**
13830 * @param {any} message
13831 */
13832 send(message) {
13833 if (this.ws) {
13834 this.ws.send(JSON.stringify(message));
13835 }
13836 }
13837 destroy() {
13838 clearInterval(this._checkInterval);
13839 this.disconnect();
13840 super.destroy();
13841 }
13842 disconnect() {
13843 this.shouldConnect = false;
13844 if (this.ws !== null) {
13845 this.ws.close();
13846 }
13847 }
13848 connect() {
13849 this.shouldConnect = true;
13850 if (!this.connected && this.ws === null) {
13851 setupHttpSignal(this);
13852 }
13853 }
13854 };
13855 var WebrtcProviderWithHttpSignaling = class extends WebrtcProvider {
13856 connect() {
13857 this.shouldConnect = true;
13858 this.signalingUrls.forEach((url) => {
13859 const signalingConn = setIfUndefined(
13860 signalingConns,
13861 url,
13862 // Only this conditional logic to create a normal websocket connection or
13863 // an http signaling connection was added to the constructor when compared
13864 // with the base class.
13865 url.startsWith("ws://") || url.startsWith("wss://") ? () => new SignalingConn(url) : () => new HttpSignalingConn(url)
13866 );
13867 this.signalingConns.push(signalingConn);
13868 signalingConn.providers.add(this);
13869 });
13870 if (this.room) {
13871 this.room.connect();
13872 }
13873 }
13874 };
13875
13876 // packages/sync/build-module/providers/webrtc-provider.js
13877 function createWebRTCProvider({ signaling, password }) {
13878 return function(objectType, objectId, doc2) {
13879 const roomName = `${objectType}-${objectId}`;
13880 const provider = new WebrtcProviderWithHttpSignaling(roomName, doc2, {
13881 signaling,
13882 password
13883 });
13884 return Promise.resolve({
13885 destroy: () => provider.destroy()
13886 });
13887 };
13888 }
13889
13890 // packages/sync/build-module/providers/index.js
13891 var providerCreators = null;
13892 function getDefaultProviderCreators() {
13893 const signalingUrl = window?.wp?.ajax?.settings?.url;
13894 if (!signalingUrl) {
13895 return [];
13896 }
13897 return [
13898 createIndexedDbProvider,
13899 createWebRTCProvider({
13900 password: window?.__experimentalCollaborativeEditingSecret,
13901 signaling: [signalingUrl]
13902 })
13903 ];
13904 }
13905 function isProviderCreator(creator) {
13906 return "function" === typeof creator;
13907 }
13908 function getProviderCreators() {
13909 if (providerCreators) {
13910 return providerCreators;
13911 }
13912 const filteredProviderCreators = (0, import_hooks.applyFilters)(
13913 "sync.providers",
13914 getDefaultProviderCreators()
13915 );
13916 if (!Array.isArray(filteredProviderCreators)) {
13917 providerCreators = [];
13918 return providerCreators;
13919 }
13920 providerCreators = filteredProviderCreators.filter(isProviderCreator);
13921 return providerCreators;
13922 }
13923
13924 // packages/sync/build-module/y-utilities/y-multidoc-undomanager.js
13925 var popStackItem2 = (mum, type) => {
13926 const stack = type === "undo" ? mum.undoStack : mum.redoStack;
13927 while (stack.length > 0) {
13928 const um = (
13929 /** @type {Y.UndoManager} */
13930 stack.pop()
13931 );
13932 const prevUmStack = type === "undo" ? um.undoStack : um.redoStack;
13933 const stackItem = (
13934 /** @type {any} */
13935 prevUmStack.pop()
13936 );
13937 let actionPerformed = false;
13938 if (type === "undo") {
13939 um.undoStack = [stackItem];
13940 actionPerformed = um.undo() !== null;
13941 um.undoStack = prevUmStack;
13942 } else {
13943 um.redoStack = [stackItem];
13944 actionPerformed = um.redo() !== null;
13945 um.redoStack = prevUmStack;
13946 }
13947 if (actionPerformed) {
13948 return stackItem;
13949 }
13950 }
13951 return null;
13952 };
13953 var YMultiDocUndoManager = class extends Observable {
13954 /**
13955 * @param {Y.AbstractType<any>|Array<Y.AbstractType<any>>} typeScope Accepts either a single type, or an array of types
13956 * @param {ConstructorParameters<typeof Y.UndoManager>[1]} opts
13957 */
13958 constructor(typeScope = [], opts = {}) {
13959 super();
13960 this.docs = /* @__PURE__ */ new Map();
13961 this.trackedOrigins = opts.trackedOrigins || /* @__PURE__ */ new Set([null]);
13962 opts.trackedOrigins = this.trackedOrigins;
13963 this._defaultOpts = opts;
13964 this.undoStack = [];
13965 this.redoStack = [];
13966 this.addToScope(typeScope);
13967 }
13968 /**
13969 * @param {Array<Y.AbstractType<any>> | Y.AbstractType<any>} ytypes
13970 */
13971 addToScope(ytypes) {
13972 ytypes = isArray(ytypes) ? ytypes : [ytypes];
13973 ytypes.forEach((ytype) => {
13974 const ydoc = (
13975 /** @type {Y.Doc} */
13976 ytype.doc
13977 );
13978 const um = setIfUndefined(this.docs, ydoc, () => {
13979 const um2 = new UndoManager([ytype], this._defaultOpts);
13980 um2.on(
13981 "stack-cleared",
13982 /** @param {any} opts */
13983 ({
13984 undoStackCleared,
13985 redoStackCleared
13986 }) => {
13987 this.clear(undoStackCleared, redoStackCleared);
13988 }
13989 );
13990 ydoc.on("destroy", () => {
13991 this.docs.delete(ydoc);
13992 this.undoStack = this.undoStack.filter(
13993 (um3) => um3.doc !== ydoc
13994 );
13995 this.redoStack = this.redoStack.filter(
13996 (um3) => um3.doc !== ydoc
13997 );
13998 });
13999 um2.on(
14000 "stack-item-added",
14001 /** @param {any} change */
14002 (change) => {
14003 const stack = change.type === "undo" ? this.undoStack : this.redoStack;
14004 stack.push(um2);
14005 this.emit("stack-item-added", [
14006 { ...change, ydoc },
14007 this
14008 ]);
14009 }
14010 );
14011 um2.on(
14012 "stack-item-updated",
14013 /** @param {any} change */
14014 (change) => {
14015 this.emit("stack-item-updated", [
14016 { ...change, ydoc },
14017 this
14018 ]);
14019 }
14020 );
14021 um2.on(
14022 "stack-item-popped",
14023 /** @param {any} change */
14024 (change) => {
14025 this.emit("stack-item-popped", [
14026 { ...change, ydoc },
14027 this
14028 ]);
14029 }
14030 );
14031 return um2;
14032 });
14033 if (um.scope.every((yt) => yt !== ytype)) {
14034 um.scope.push(ytype);
14035 }
14036 });
14037 }
14038 /**
14039 * @param {any} origin
14040 */
14041 /* c8 ignore next 3 */
14042 addTrackedOrigin(origin) {
14043 this.trackedOrigins.add(origin);
14044 }
14045 /**
14046 * @param {any} origin
14047 */
14048 /* c8 ignore next 3 */
14049 removeTrackedOrigin(origin) {
14050 this.trackedOrigins.delete(origin);
14051 }
14052 /**
14053 * Undo last changes on type.
14054 *
14055 * @return {any?} Returns StackItem if a change was applied
14056 */
14057 undo() {
14058 return popStackItem2(this, "undo");
14059 }
14060 /**
14061 * Redo last undo operation.
14062 *
14063 * @return {any?} Returns StackItem if a change was applied
14064 */
14065 redo() {
14066 return popStackItem2(this, "redo");
14067 }
14068 clear(clearUndoStack = true, clearRedoStack = true) {
14069 if (clearUndoStack && this.canUndo() || clearRedoStack && this.canRedo()) {
14070 this.docs.forEach((um) => {
14071 clearUndoStack && (this.undoStack = []);
14072 clearRedoStack && (this.redoStack = []);
14073 um.clear(clearUndoStack, clearRedoStack);
14074 });
14075 this.emit("stack-cleared", [
14076 {
14077 undoStackCleared: clearUndoStack,
14078 redoStackCleared: clearRedoStack
14079 }
14080 ]);
14081 }
14082 }
14083 /* c8 ignore next 5 */
14084 stopCapturing() {
14085 this.docs.forEach((um) => {
14086 um.stopCapturing();
14087 });
14088 }
14089 /**
14090 * Are undo steps available?
14091 *
14092 * @return {boolean} `true` if undo is possible
14093 */
14094 canUndo() {
14095 return this.undoStack.length > 0;
14096 }
14097 /**
14098 * Are redo steps available?
14099 *
14100 * @return {boolean} `true` if redo is possible
14101 */
14102 canRedo() {
14103 return this.redoStack.length > 0;
14104 }
14105 destroy() {
14106 this.docs.forEach((um) => um.destroy());
14107 super.destroy();
14108 }
14109 };
14110
14111 // packages/sync/build-module/undo-manager.js
14112 function createUndoManager() {
14113 const yUndoManager = new YMultiDocUndoManager([], {
14114 // Throttle undo/redo captures. (default: 500ms)
14115 captureTimeout: 200,
14116 // Ensure that we only scope the undo/redo to the current editor.
14117 // The yjs document's clientID is added once it's available.
14118 trackedOrigins: /* @__PURE__ */ new Set([LOCAL_EDITOR_ORIGIN])
14119 });
14120 return {
14121 /**
14122 * Record changes into the history.
14123 * Since Yjs automatically tracks changes, this method translates the WordPress
14124 * HistoryRecord format into Yjs operations.
14125 *
14126 * @param _record A record of changes to record.
14127 * @param _isStaged Whether to immediately create an undo point or not.
14128 */
14129 addRecord(_record, _isStaged = false) {
14130 },
14131 /**
14132 * Add a Yjs map to the scope of the undo manager.
14133 *
14134 * @param {Y.Map< any >} ymap The Yjs map to add to the scope.
14135 */
14136 addToScope(ymap) {
14137 yUndoManager.addToScope(ymap);
14138 },
14139 /**
14140 * Undo the last recorded changes.
14141 *
14142 */
14143 undo() {
14144 if (!yUndoManager.canUndo()) {
14145 return;
14146 }
14147 yUndoManager.undo();
14148 return [];
14149 },
14150 /**
14151 * Redo the last undone changes.
14152 */
14153 redo() {
14154 if (!yUndoManager.canRedo()) {
14155 return;
14156 }
14157 yUndoManager.redo();
14158 return [];
14159 },
14160 /**
14161 * Check if there are changes that can be undone.
14162 *
14163 * @return {boolean} Whether there are changes to undo.
14164 */
14165 hasUndo() {
14166 return yUndoManager.canUndo();
14167 },
14168 /**
14169 * Check if there are changes that can be redone.
14170 *
14171 * @return {boolean} Whether there are changes to redo.
14172 */
14173 hasRedo() {
14174 return yUndoManager.canRedo();
14175 }
14176 };
14177 }
14178
14179 // packages/sync/build-module/manager.js
14180 function createSyncManager() {
14181 const entityStates = /* @__PURE__ */ new Map();
14182 const undoManager2 = createUndoManager();
14183 async function loadEntity(syncConfig, objectType, objectId, record, handlers) {
14184 const providerCreators2 = getProviderCreators();
14185 if (0 === providerCreators2.length) {
14186 return;
14187 }
14188 const entityId = getEntityId(objectType, objectId);
14189 if (entityStates.has(entityId)) {
14190 return;
14191 }
14192 const ydoc = createYjsDoc({ objectType });
14193 const recordMap = ydoc.getMap(CRDT_RECORD_MAP_KEY);
14194 const unload = () => {
14195 providerResults.forEach((result) => result.destroy());
14196 recordMap.unobserveDeep(onRecordUpdate);
14197 ydoc.destroy();
14198 entityStates.delete(entityId);
14199 };
14200 const onRecordUpdate = (_events, transaction) => {
14201 if (transaction.local && !(transaction.origin instanceof UndoManager)) {
14202 return;
14203 }
14204 void updateEntityRecord(objectType, objectId);
14205 };
14206 undoManager2.addToScope(recordMap);
14207 const entityState = {
14208 handlers,
14209 objectId,
14210 objectType,
14211 syncConfig,
14212 unload,
14213 ydoc
14214 };
14215 entityStates.set(entityId, entityState);
14216 const providerResults = await Promise.all(
14217 providerCreators2.map(
14218 (create8) => create8(objectType, objectId, ydoc)
14219 )
14220 );
14221 recordMap.observeDeep(onRecordUpdate);
14222 const isInvalid = applyPersistedCrdtDoc(syncConfig, ydoc, record);
14223 if (isInvalid) {
14224 ydoc.transact(() => {
14225 syncConfig.applyChangesToCRDTDoc(ydoc, record);
14226 }, LOCAL_SYNC_MANAGER_ORIGIN);
14227 const meta = createEntityMeta(objectType, objectId);
14228 handlers.editRecord({ meta });
14229 handlers.saveRecord();
14230 }
14231 }
14232 function unloadEntity(objectType, objectId) {
14233 entityStates.get(getEntityId(objectType, objectId))?.unload();
14234 }
14235 function getEntityId(objectType, objectId) {
14236 return `${objectType}_${objectId}`;
14237 }
14238 function applyPersistedCrdtDoc(syncConfig, targetDoc, record) {
14239 if (!syncConfig.supports?.crdtPersistence) {
14240 return true;
14241 }
14242 const tempDoc = getPersistedCrdtDoc(record);
14243 if (!tempDoc) {
14244 return true;
14245 }
14246 const update = encodeStateAsUpdateV2(tempDoc);
14247 targetDoc.transact(() => {
14248 applyUpdateV2(targetDoc, update);
14249 }, LOCAL_SYNC_MANAGER_ORIGIN);
14250 const changes = syncConfig.getChangesFromCRDTDoc(tempDoc, record);
14251 tempDoc.destroy();
14252 return Object.keys(changes).length > 0;
14253 }
14254 function updateCRDTDoc(objectType, objectId, changes, origin) {
14255 const entityId = getEntityId(objectType, objectId);
14256 const entityState = entityStates.get(entityId);
14257 if (!entityState) {
14258 return;
14259 }
14260 const { syncConfig, ydoc } = entityState;
14261 ydoc.transact(() => {
14262 syncConfig.applyChangesToCRDTDoc(ydoc, changes);
14263 }, origin);
14264 }
14265 async function updateEntityRecord(objectType, objectId) {
14266 const entityId = getEntityId(objectType, objectId);
14267 const entityState = entityStates.get(entityId);
14268 if (!entityState) {
14269 return;
14270 }
14271 const { handlers, syncConfig, ydoc } = entityState;
14272 const changes = syncConfig.getChangesFromCRDTDoc(
14273 ydoc,
14274 await handlers.getEditedRecord()
14275 );
14276 if (0 === Object.keys(changes).length) {
14277 return;
14278 }
14279 handlers.editRecord(changes);
14280 }
14281 function createEntityMeta(objectType, objectId) {
14282 const entityId = getEntityId(objectType, objectId);
14283 const entityState = entityStates.get(entityId);
14284 if (!entityState?.syncConfig.supports?.crdtPersistence) {
14285 return {};
14286 }
14287 return createPersistedCRDTDoc(entityState.ydoc);
14288 }
14289 return {
14290 createMeta: createEntityMeta,
14291 load: loadEntity,
14292 undoManager: undoManager2,
14293 unload: unloadEntity,
14294 update: updateCRDTDoc
14295 };
14296 }
14297
14298 // packages/core-data/build-module/sync.js
14299 var syncManager;
14300 function getSyncManager() {
14301 if (syncManager) {
14302 return syncManager;
14303 }
14304 syncManager = createSyncManager();
14305 return syncManager;
14306 }
14307
14308 // packages/core-data/build-module/utils/crdt.js
14309 var import_es63 = __toESM(require_es6());
14310 var import_blocks2 = __toESM(require_blocks());
14311
14312 // node_modules/uuid/dist/esm-browser/rng.js
14313 var getRandomValues2;
14314 var rnds8 = new Uint8Array(16);
14315 function rng() {
14316 if (!getRandomValues2) {
14317 getRandomValues2 = typeof crypto !== "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
14318 if (!getRandomValues2) {
14319 throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
14320 }
14321 }
14322 return getRandomValues2(rnds8);
14323 }
14324
14325 // node_modules/uuid/dist/esm-browser/stringify.js
14326 var byteToHex = [];
14327 for (let i = 0; i < 256; ++i) {
14328 byteToHex.push((i + 256).toString(16).slice(1));
14329 }
14330 function unsafeStringify(arr, offset = 0) {
14331 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]];
14332 }
14333
14334 // node_modules/uuid/dist/esm-browser/native.js
14335 var randomUUID = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto);
14336 var native_default = {
14337 randomUUID
14338 };
14339
14340 // node_modules/uuid/dist/esm-browser/v4.js
14341 function v4(options, buf, offset) {
14342 if (native_default.randomUUID && !buf && !options) {
14343 return native_default.randomUUID();
14344 }
14345 options = options || {};
14346 const rnds = options.random || (options.rng || rng)();
14347 rnds[6] = rnds[6] & 15 | 64;
14348 rnds[8] = rnds[8] & 63 | 128;
14349 if (buf) {
14350 offset = offset || 0;
14351 for (let i = 0; i < 16; ++i) {
14352 buf[offset + i] = rnds[i];
14353 }
14354 return buf;
14355 }
14356 return unsafeStringify(rnds);
14357 }
14358 var v4_default = v4;
14359
14360 // packages/core-data/build-module/utils/crdt-blocks.js
14361 var import_es62 = __toESM(require_es6());
14362 var import_rich_text = __toESM(require_rich_text());
14363 var import_blocks = __toESM(require_blocks());
14364 var serializableBlocksCache = /* @__PURE__ */ new WeakMap();
14365 function makeBlockAttributesSerializable(attributes) {
14366 const newAttributes = { ...attributes };
14367 for (const [key, value] of Object.entries(attributes)) {
14368 if (value instanceof import_rich_text.RichTextData) {
14369 newAttributes[key] = value.valueOf();
14370 }
14371 }
14372 return newAttributes;
14373 }
14374 function makeBlocksSerializable(blocks) {
14375 return blocks.map((block) => {
14376 const blockAsJson = block instanceof yjs_exports.Map ? block.toJSON() : block;
14377 const { name, innerBlocks, attributes, ...rest } = blockAsJson;
14378 delete rest.validationIssues;
14379 delete rest.originalContent;
14380 return {
14381 ...rest,
14382 name,
14383 attributes: makeBlockAttributesSerializable(attributes),
14384 innerBlocks: makeBlocksSerializable(innerBlocks)
14385 };
14386 });
14387 }
14388 function areBlocksEqual(gblock, yblock) {
14389 const yblockAsJson = yblock.toJSON();
14390 const overwrites = {
14391 innerBlocks: null,
14392 clientId: null
14393 };
14394 const res = (0, import_es62.default)(
14395 Object.assign({}, gblock, overwrites),
14396 Object.assign({}, yblockAsJson, overwrites)
14397 );
14398 const inners = gblock.innerBlocks || [];
14399 const yinners = yblock.get("innerBlocks");
14400 return res && inners.length === yinners.length && inners.every(
14401 (block, i) => areBlocksEqual(block, yinners.get(i))
14402 );
14403 }
14404 function createNewYAttributeMap(blockName, attributes) {
14405 return new yjs_exports.Map(
14406 Object.entries(attributes).map(
14407 ([attributeName, attributeValue]) => {
14408 return [
14409 attributeName,
14410 createNewYAttributeValue(
14411 blockName,
14412 attributeName,
14413 attributeValue
14414 )
14415 ];
14416 }
14417 )
14418 );
14419 }
14420 function createNewYAttributeValue(blockName, attributeName, attributeValue) {
14421 const isRichText = isRichTextAttribute(blockName, attributeName);
14422 if (isRichText) {
14423 return new yjs_exports.Text(attributeValue?.toString() ?? "");
14424 }
14425 return attributeValue;
14426 }
14427 function createNewYBlock(block) {
14428 return new yjs_exports.Map(
14429 Object.entries(block).map(([key, value]) => {
14430 switch (key) {
14431 case "attributes": {
14432 return [key, createNewYAttributeMap(block.name, value)];
14433 }
14434 case "innerBlocks": {
14435 const innerBlocks = new yjs_exports.Array();
14436 if (!Array.isArray(value)) {
14437 return [key, innerBlocks];
14438 }
14439 innerBlocks.insert(
14440 0,
14441 value.map(
14442 (innerBlock) => createNewYBlock(innerBlock)
14443 )
14444 );
14445 return [key, innerBlocks];
14446 }
14447 default:
14448 return [key, value];
14449 }
14450 })
14451 );
14452 }
14453 function mergeCrdtBlocks(yblocks, incomingBlocks, lastSelection2) {
14454 if (!serializableBlocksCache.has(incomingBlocks)) {
14455 serializableBlocksCache.set(
14456 incomingBlocks,
14457 makeBlocksSerializable(incomingBlocks)
14458 );
14459 }
14460 const allBlocks = serializableBlocksCache.get(incomingBlocks) ?? [];
14461 const blocksToSync = allBlocks.filter(
14462 (block) => shouldBlockBeSynced(block)
14463 );
14464 const numOfCommonEntries = Math.min(
14465 blocksToSync.length ?? 0,
14466 yblocks.length
14467 );
14468 let left = 0;
14469 let right = 0;
14470 for (; left < numOfCommonEntries && areBlocksEqual(blocksToSync[left], yblocks.get(left)); left++) {
14471 }
14472 for (; right < numOfCommonEntries - left && areBlocksEqual(
14473 blocksToSync[blocksToSync.length - right - 1],
14474 yblocks.get(yblocks.length - right - 1)
14475 ); right++) {
14476 }
14477 const numOfUpdatesNeeded = numOfCommonEntries - left - right;
14478 const numOfInsertionsNeeded = Math.max(
14479 0,
14480 blocksToSync.length - yblocks.length
14481 );
14482 const numOfDeletionsNeeded = Math.max(
14483 0,
14484 yblocks.length - blocksToSync.length
14485 );
14486 for (let i = 0; i < numOfUpdatesNeeded; i++, left++) {
14487 const block = blocksToSync[left];
14488 const yblock = yblocks.get(left);
14489 Object.entries(block).forEach(([key, value]) => {
14490 switch (key) {
14491 case "attributes": {
14492 const currentAttributes = yblock.get(
14493 key
14494 );
14495 if (!currentAttributes) {
14496 yblock.set(
14497 key,
14498 createNewYAttributeMap(block.name, value)
14499 );
14500 break;
14501 }
14502 Object.entries(value).forEach(
14503 ([attributeName, attributeValue]) => {
14504 if ((0, import_es62.default)(
14505 currentAttributes?.get(attributeName),
14506 attributeValue
14507 )) {
14508 return;
14509 }
14510 const isRichText = isRichTextAttribute(
14511 block.name,
14512 attributeName
14513 );
14514 if (isRichText && "string" === typeof attributeValue) {
14515 const blockYText = currentAttributes.get(
14516 attributeName
14517 );
14518 mergeRichTextUpdate(
14519 blockYText,
14520 attributeValue,
14521 lastSelection2
14522 );
14523 } else {
14524 currentAttributes.set(
14525 attributeName,
14526 createNewYAttributeValue(
14527 block.name,
14528 attributeName,
14529 attributeValue
14530 )
14531 );
14532 }
14533 }
14534 );
14535 currentAttributes.forEach(
14536 (_attrValue, attrName) => {
14537 if (!value.hasOwnProperty(attrName)) {
14538 currentAttributes.delete(attrName);
14539 }
14540 }
14541 );
14542 break;
14543 }
14544 case "innerBlocks": {
14545 const yInnerBlocks = yblock.get(key);
14546 mergeCrdtBlocks(yInnerBlocks, value ?? [], lastSelection2);
14547 break;
14548 }
14549 default:
14550 if (!(0, import_es62.default)(block[key], yblock.get(key))) {
14551 yblock.set(key, value);
14552 }
14553 }
14554 });
14555 yblock.forEach((_v, k) => {
14556 if (!block.hasOwnProperty(k)) {
14557 yblock.delete(k);
14558 }
14559 });
14560 }
14561 yblocks.delete(left, numOfDeletionsNeeded);
14562 for (let i = 0; i < numOfInsertionsNeeded; i++, left++) {
14563 const newBlock = [createNewYBlock(blocksToSync[left])];
14564 yblocks.insert(left, newBlock);
14565 }
14566 const knownClientIds = /* @__PURE__ */ new Set();
14567 for (let j = 0; j < yblocks.length; j++) {
14568 const yblock = yblocks.get(j);
14569 let clientId = yblock.get("clientId");
14570 if (knownClientIds.has(clientId)) {
14571 clientId = v4_default();
14572 yblock.set("clientId", clientId);
14573 }
14574 knownClientIds.add(clientId);
14575 }
14576 }
14577 function shouldBlockBeSynced(block) {
14578 if ("core/gallery" === block.name) {
14579 return !block.innerBlocks.some(
14580 (innerBlock) => innerBlock.attributes && innerBlock.attributes.blob
14581 );
14582 }
14583 return true;
14584 }
14585 var cachedRichTextAttributes;
14586 function isRichTextAttribute(blockName, attributeName) {
14587 if (!cachedRichTextAttributes) {
14588 cachedRichTextAttributes = /* @__PURE__ */ new Map();
14589 for (const blockType of (0, import_blocks.getBlockTypes)()) {
14590 const richTextAttributeMap = /* @__PURE__ */ new Map();
14591 for (const [name, definition] of Object.entries(
14592 blockType.attributes ?? {}
14593 )) {
14594 if ("rich-text" === definition.type) {
14595 richTextAttributeMap.set(name, true);
14596 }
14597 }
14598 cachedRichTextAttributes.set(
14599 blockType.name,
14600 richTextAttributeMap
14601 );
14602 }
14603 }
14604 return cachedRichTextAttributes.get(blockName)?.has(attributeName) ?? false;
14605 }
14606 function mergeRichTextUpdate(blockYText, updatedValue, lastSelection2) {
14607 blockYText.delete(0, blockYText.toString().length);
14608 blockYText.insert(0, updatedValue);
14609 }
14610
14611 // packages/core-data/build-module/utils/crdt.js
14612 var lastSelection = null;
14613 var allowedPostProperties = /* @__PURE__ */ new Set([
14614 "author",
14615 "blocks",
14616 "comment_status",
14617 "date",
14618 "excerpt",
14619 "featured_media",
14620 "format",
14621 "ping_status",
14622 "meta",
14623 "slug",
14624 "status",
14625 "sticky",
14626 "tags",
14627 "template",
14628 "title"
14629 ]);
14630 var disallowedPostMetaKeys = /* @__PURE__ */ new Set([
14631 WORDPRESS_META_KEY_FOR_CRDT_DOC_PERSISTENCE
14632 ]);
14633 function defaultApplyChangesToCRDTDoc(ydoc, changes) {
14634 const ymap = ydoc.getMap(CRDT_RECORD_MAP_KEY);
14635 Object.entries(changes).forEach(([key, newValue]) => {
14636 if ("function" === typeof newValue) {
14637 return;
14638 }
14639 function setValue(updatedValue) {
14640 ymap.set(key, updatedValue);
14641 }
14642 switch (key) {
14643 // Add support for additional data types here.
14644 default: {
14645 const currentValue = ymap.get(key);
14646 mergeValue(currentValue, newValue, setValue);
14647 }
14648 }
14649 });
14650 }
14651 function applyPostChangesToCRDTDoc(ydoc, changes, _postType) {
14652 const ymap = ydoc.getMap(CRDT_RECORD_MAP_KEY);
14653 Object.entries(changes).forEach(([key, newValue]) => {
14654 if (!allowedPostProperties.has(key)) {
14655 return;
14656 }
14657 if ("function" === typeof newValue) {
14658 return;
14659 }
14660 function setValue(updatedValue) {
14661 ymap.set(key, updatedValue);
14662 }
14663 switch (key) {
14664 case "blocks": {
14665 let currentBlocks = ymap.get("blocks");
14666 if (!(currentBlocks instanceof yjs_exports.Array)) {
14667 currentBlocks = new yjs_exports.Array();
14668 setValue(currentBlocks);
14669 }
14670 const newBlocks = newValue ?? [];
14671 mergeCrdtBlocks(currentBlocks, newBlocks, lastSelection);
14672 break;
14673 }
14674 case "excerpt": {
14675 const currentValue = ymap.get("excerpt");
14676 const rawNewValue = getRawValue(newValue);
14677 mergeValue(currentValue, rawNewValue, setValue);
14678 break;
14679 }
14680 // "Meta" is overloaded term; here, it refers to post meta.
14681 case "meta": {
14682 let metaMap = ymap.get("meta");
14683 if (!(metaMap instanceof yjs_exports.Map)) {
14684 metaMap = new yjs_exports.Map();
14685 setValue(metaMap);
14686 }
14687 Object.entries(newValue ?? {}).forEach(
14688 ([metaKey, metaValue]) => {
14689 if (disallowedPostMetaKeys.has(metaKey)) {
14690 return;
14691 }
14692 mergeValue(
14693 metaMap.get(metaKey),
14694 // current value in CRDT
14695 metaValue,
14696 // new value from changes
14697 (updatedMetaValue) => {
14698 metaMap.set(metaKey, updatedMetaValue);
14699 }
14700 );
14701 }
14702 );
14703 break;
14704 }
14705 case "slug": {
14706 if (!newValue) {
14707 break;
14708 }
14709 const currentValue = ymap.get("slug");
14710 mergeValue(currentValue, newValue, setValue);
14711 break;
14712 }
14713 case "title": {
14714 const currentValue = ymap.get("title");
14715 let rawNewValue = getRawValue(newValue);
14716 if (!currentValue && "Auto Draft" === rawNewValue) {
14717 rawNewValue = "";
14718 }
14719 mergeValue(currentValue, rawNewValue, setValue);
14720 break;
14721 }
14722 // Add support for additional data types here.
14723 default: {
14724 const currentValue = ymap.get(key);
14725 mergeValue(currentValue, newValue, setValue);
14726 }
14727 }
14728 });
14729 if ("selection" in changes) {
14730 lastSelection = changes.selection?.selectionStart ?? null;
14731 }
14732 }
14733 function defaultGetChangesFromCRDTDoc(crdtDoc) {
14734 return crdtDoc.getMap(CRDT_RECORD_MAP_KEY).toJSON();
14735 }
14736 function getPostChangesFromCRDTDoc(ydoc, editedRecord, _postType) {
14737 const ymap = ydoc.getMap(CRDT_RECORD_MAP_KEY);
14738 let allowedMetaChanges = {};
14739 const changes = Object.fromEntries(
14740 Object.entries(ymap.toJSON()).filter(([key, newValue]) => {
14741 if (!allowedPostProperties.has(key)) {
14742 return false;
14743 }
14744 const currentValue = editedRecord[key];
14745 switch (key) {
14746 case "blocks": {
14747 if (ydoc.meta?.get(CRDT_DOC_META_PERSISTENCE_KEY) && editedRecord.content) {
14748 const blocks = ymap.get("blocks");
14749 return (0, import_blocks2.__unstableSerializeAndClean)(
14750 blocks.toJSON()
14751 ).trim() !== editedRecord.content.raw.trim();
14752 }
14753 return true;
14754 }
14755 case "date": {
14756 const currentDateIsFloating = ["draft", "auto-draft", "pending"].includes(
14757 ymap.get("status")
14758 ) && (null === currentValue || editedRecord.modified === currentValue);
14759 if (!newValue && currentDateIsFloating) {
14760 return false;
14761 }
14762 return haveValuesChanged(currentValue, newValue);
14763 }
14764 case "meta": {
14765 allowedMetaChanges = Object.fromEntries(
14766 Object.entries(newValue ?? {}).filter(
14767 ([metaKey]) => !disallowedPostMetaKeys.has(metaKey)
14768 )
14769 );
14770 const mergedValue = {
14771 ...currentValue,
14772 ...allowedMetaChanges
14773 };
14774 return haveValuesChanged(currentValue, mergedValue);
14775 }
14776 case "status": {
14777 if ("auto-draft" === newValue) {
14778 return false;
14779 }
14780 return haveValuesChanged(currentValue, newValue);
14781 }
14782 case "excerpt":
14783 case "title": {
14784 return haveValuesChanged(
14785 getRawValue(currentValue),
14786 newValue
14787 );
14788 }
14789 // Add support for additional data types here.
14790 default: {
14791 return haveValuesChanged(currentValue, newValue);
14792 }
14793 }
14794 })
14795 );
14796 if ("object" === typeof changes.meta) {
14797 changes.meta = {
14798 ...editedRecord.meta,
14799 ...allowedMetaChanges
14800 };
14801 }
14802 return changes;
14803 }
14804 function getRawValue(value) {
14805 if ("string" === typeof value) {
14806 return value;
14807 }
14808 if (value && "object" === typeof value && "raw" in value && "string" === typeof value.raw) {
14809 return value.raw;
14810 }
14811 return void 0;
14812 }
14813 function haveValuesChanged(currentValue, newValue) {
14814 return !(0, import_es63.default)(currentValue, newValue);
14815 }
14816 function mergeValue(currentValue, newValue, setValue) {
14817 if (haveValuesChanged(currentValue, newValue)) {
14818 setValue(newValue);
14819 }
14820 }
14821
14822 // packages/core-data/build-module/entities.js
14823 var DEFAULT_ENTITY_KEY = "id";
14824 var POST_RAW_ATTRIBUTES = ["title", "excerpt", "content"];
14825 var blocksTransientEdits = {
14826 blocks: {
14827 read: (record) => (0, import_blocks3.parse)(record.content?.raw ?? ""),
14828 write: (record) => ({
14829 content: (0, import_blocks3.__unstableSerializeAndClean)(record.blocks)
14830 })
14831 }
14832 };
14833 var rootEntitiesConfig = [
14834 {
14835 label: (0, import_i18n.__)("Base"),
14836 kind: "root",
14837 key: false,
14838 name: "__unstableBase",
14839 baseURL: "/",
14840 baseURLParams: {
14841 // Please also change the preload path when changing this.
14842 // @see lib/compat/wordpress-6.8/preload.php
14843 _fields: [
14844 "description",
14845 "gmt_offset",
14846 "home",
14847 "name",
14848 "site_icon",
14849 "site_icon_url",
14850 "site_logo",
14851 "timezone_string",
14852 "url",
14853 "page_for_posts",
14854 "page_on_front",
14855 "show_on_front"
14856 ].join(",")
14857 },
14858 // The entity doesn't support selecting multiple records.
14859 // The property is maintained for backward compatibility.
14860 plural: "__unstableBases"
14861 },
14862 {
14863 label: (0, import_i18n.__)("Post Type"),
14864 name: "postType",
14865 kind: "root",
14866 key: "slug",
14867 baseURL: "/wp/v2/types",
14868 baseURLParams: { context: "edit" },
14869 plural: "postTypes"
14870 },
14871 {
14872 name: "media",
14873 kind: "root",
14874 baseURL: "/wp/v2/media",
14875 baseURLParams: { context: "edit" },
14876 plural: "mediaItems",
14877 label: (0, import_i18n.__)("Media"),
14878 rawAttributes: ["caption", "title", "description"],
14879 supportsPagination: true
14880 },
14881 {
14882 name: "taxonomy",
14883 kind: "root",
14884 key: "slug",
14885 baseURL: "/wp/v2/taxonomies",
14886 baseURLParams: { context: "edit" },
14887 plural: "taxonomies",
14888 label: (0, import_i18n.__)("Taxonomy")
14889 },
14890 {
14891 name: "sidebar",
14892 kind: "root",
14893 baseURL: "/wp/v2/sidebars",
14894 baseURLParams: { context: "edit" },
14895 plural: "sidebars",
14896 transientEdits: { blocks: true },
14897 label: (0, import_i18n.__)("Widget areas")
14898 },
14899 {
14900 name: "widget",
14901 kind: "root",
14902 baseURL: "/wp/v2/widgets",
14903 baseURLParams: { context: "edit" },
14904 plural: "widgets",
14905 transientEdits: { blocks: true },
14906 label: (0, import_i18n.__)("Widgets")
14907 },
14908 {
14909 name: "widgetType",
14910 kind: "root",
14911 baseURL: "/wp/v2/widget-types",
14912 baseURLParams: { context: "edit" },
14913 plural: "widgetTypes",
14914 label: (0, import_i18n.__)("Widget types")
14915 },
14916 {
14917 label: (0, import_i18n.__)("User"),
14918 name: "user",
14919 kind: "root",
14920 baseURL: "/wp/v2/users",
14921 getTitle: (record) => record?.name || record?.slug,
14922 baseURLParams: { context: "edit" },
14923 plural: "users",
14924 supportsPagination: true
14925 },
14926 {
14927 name: "comment",
14928 kind: "root",
14929 baseURL: "/wp/v2/comments",
14930 baseURLParams: { context: "edit" },
14931 plural: "comments",
14932 label: (0, import_i18n.__)("Comment"),
14933 supportsPagination: true
14934 },
14935 {
14936 name: "menu",
14937 kind: "root",
14938 baseURL: "/wp/v2/menus",
14939 baseURLParams: { context: "edit" },
14940 plural: "menus",
14941 label: (0, import_i18n.__)("Menu"),
14942 supportsPagination: true
14943 },
14944 {
14945 name: "menuItem",
14946 kind: "root",
14947 baseURL: "/wp/v2/menu-items",
14948 baseURLParams: { context: "edit" },
14949 plural: "menuItems",
14950 label: (0, import_i18n.__)("Menu Item"),
14951 rawAttributes: ["title"],
14952 supportsPagination: true
14953 },
14954 {
14955 name: "menuLocation",
14956 kind: "root",
14957 baseURL: "/wp/v2/menu-locations",
14958 baseURLParams: { context: "edit" },
14959 plural: "menuLocations",
14960 label: (0, import_i18n.__)("Menu Location"),
14961 key: "name"
14962 },
14963 {
14964 label: (0, import_i18n.__)("Global Styles"),
14965 name: "globalStyles",
14966 kind: "root",
14967 baseURL: "/wp/v2/global-styles",
14968 baseURLParams: { context: "edit" },
14969 plural: "globalStylesVariations",
14970 // Should be different from name.
14971 getTitle: () => (0, import_i18n.__)("Custom Styles"),
14972 getRevisionsUrl: (parentId, revisionId) => `/wp/v2/global-styles/${parentId}/revisions${revisionId ? "/" + revisionId : ""}`,
14973 supportsPagination: true
14974 },
14975 {
14976 label: (0, import_i18n.__)("Themes"),
14977 name: "theme",
14978 kind: "root",
14979 baseURL: "/wp/v2/themes",
14980 baseURLParams: { context: "edit" },
14981 plural: "themes",
14982 key: "stylesheet"
14983 },
14984 {
14985 label: (0, import_i18n.__)("Plugins"),
14986 name: "plugin",
14987 kind: "root",
14988 baseURL: "/wp/v2/plugins",
14989 baseURLParams: { context: "edit" },
14990 plural: "plugins",
14991 key: "plugin"
14992 },
14993 {
14994 label: (0, import_i18n.__)("Status"),
14995 name: "status",
14996 kind: "root",
14997 baseURL: "/wp/v2/statuses",
14998 baseURLParams: { context: "edit" },
14999 plural: "statuses",
15000 key: "slug"
15001 },
15002 {
15003 label: (0, import_i18n.__)("Registered Templates"),
15004 name: "registeredTemplate",
15005 kind: "root",
15006 baseURL: "/wp/v2/registered-templates",
15007 key: "id"
15008 },
15009 {
15010 label: (0, import_i18n.__)("Font Collections"),
15011 name: "fontCollection",
15012 kind: "root",
15013 baseURL: "/wp/v2/font-collections",
15014 baseURLParams: { context: "view" },
15015 plural: "fontCollections",
15016 key: "slug"
15017 }
15018 ];
15019 var deprecatedEntities = {
15020 root: {
15021 media: {
15022 since: "6.9",
15023 alternative: {
15024 kind: "postType",
15025 name: "attachment"
15026 }
15027 }
15028 }
15029 };
15030 var additionalEntityConfigLoaders = [
15031 { kind: "postType", loadEntities: loadPostTypeEntities },
15032 { kind: "taxonomy", loadEntities: loadTaxonomyEntities },
15033 {
15034 kind: "root",
15035 name: "site",
15036 plural: "sites",
15037 loadEntities: loadSiteEntity
15038 }
15039 ];
15040 var prePersistPostType = (persistedRecord, edits, name, isTemplate) => {
15041 const newEdits = {};
15042 if (!isTemplate && persistedRecord?.status === "auto-draft") {
15043 if (!edits.status && !newEdits.status) {
15044 newEdits.status = "draft";
15045 }
15046 if ((!edits.title || edits.title === "Auto Draft") && !newEdits.title && (!persistedRecord?.title || persistedRecord?.title === "Auto Draft")) {
15047 newEdits.title = "";
15048 }
15049 }
15050 if (persistedRecord && window.__experimentalEnableSync) {
15051 if (true) {
15052 const objectType = `postType/${name}`;
15053 const objectId = persistedRecord.id;
15054 const meta = getSyncManager()?.createMeta(objectType, objectId);
15055 newEdits.meta = {
15056 ...edits.meta,
15057 ...meta
15058 };
15059 }
15060 }
15061 return newEdits;
15062 };
15063 async function loadPostTypeEntities() {
15064 const postTypes = await (0, import_api_fetch.default)({
15065 path: "/wp/v2/types?context=view"
15066 });
15067 return Object.entries(postTypes ?? {}).map(([name, postType]) => {
15068 const isTemplate = ["wp_template", "wp_template_part"].includes(
15069 name
15070 );
15071 const namespace = postType?.rest_namespace ?? "wp/v2";
15072 const entity2 = {
15073 kind: "postType",
15074 baseURL: `/${namespace}/${postType.rest_base}`,
15075 baseURLParams: { context: "edit" },
15076 name,
15077 label: postType.name,
15078 transientEdits: {
15079 ...blocksTransientEdits,
15080 selection: true
15081 },
15082 mergedEdits: { meta: true },
15083 rawAttributes: POST_RAW_ATTRIBUTES,
15084 getTitle: (record) => record?.title?.rendered || record?.title || (isTemplate ? capitalCase(record.slug ?? "") : String(record.id)),
15085 __unstablePrePersist: (persistedRecord, edits) => prePersistPostType(persistedRecord, edits, name, isTemplate),
15086 __unstable_rest_base: postType.rest_base,
15087 supportsPagination: true,
15088 getRevisionsUrl: (parentId, revisionId) => `/${namespace}/${postType.rest_base}/${parentId}/revisions${revisionId ? "/" + revisionId : ""}`,
15089 revisionKey: isTemplate && !window?.__experimentalTemplateActivate ? "wp_id" : DEFAULT_ENTITY_KEY
15090 };
15091 if (window.__experimentalEnableSync) {
15092 if (true) {
15093 entity2.syncConfig = {
15094 /**
15095 * Apply changes from the local editor to the local CRDT document so
15096 * that those changes can be synced to other peers (via the provider).
15097 *
15098 * @param {import('@wordpress/sync').CRDTDoc} crdtDoc
15099 * @param {Partial< import('@wordpress/sync').ObjectData >} changes
15100 * @return {void}
15101 */
15102 applyChangesToCRDTDoc: (crdtDoc, changes) => applyPostChangesToCRDTDoc(crdtDoc, changes, postType),
15103 /**
15104 * Extract changes from a CRDT document that can be used to update the
15105 * local editor state.
15106 *
15107 * @param {import('@wordpress/sync').CRDTDoc} crdtDoc
15108 * @param {import('@wordpress/sync').ObjectData} editedRecord
15109 * @return {Partial< import('@wordpress/sync').ObjectData >} Changes to record
15110 */
15111 getChangesFromCRDTDoc: (crdtDoc, editedRecord) => getPostChangesFromCRDTDoc(
15112 crdtDoc,
15113 editedRecord,
15114 postType
15115 ),
15116 /**
15117 * Sync features supported by the entity.
15118 *
15119 * @type {Record< string, boolean >}
15120 */
15121 supports: {
15122 crdtPersistence: true
15123 }
15124 };
15125 }
15126 }
15127 return entity2;
15128 });
15129 }
15130 async function loadTaxonomyEntities() {
15131 const taxonomies = await (0, import_api_fetch.default)({
15132 path: "/wp/v2/taxonomies?context=view"
15133 });
15134 return Object.entries(taxonomies ?? {}).map(([name, taxonomy]) => {
15135 const namespace = taxonomy?.rest_namespace ?? "wp/v2";
15136 return {
15137 kind: "taxonomy",
15138 baseURL: `/${namespace}/${taxonomy.rest_base}`,
15139 baseURLParams: { context: "edit" },
15140 name,
15141 label: taxonomy.name,
15142 getTitle: (record) => record?.name,
15143 supportsPagination: true
15144 };
15145 });
15146 }
15147 async function loadSiteEntity() {
15148 const entity2 = {
15149 label: (0, import_i18n.__)("Site"),
15150 name: "site",
15151 kind: "root",
15152 key: false,
15153 baseURL: "/wp/v2/settings",
15154 meta: {}
15155 };
15156 if (window.__experimentalEnableSync) {
15157 if (true) {
15158 entity2.syncConfig = {
15159 applyChangesToCRDTDoc: defaultApplyChangesToCRDTDoc,
15160 getChangesFromCRDTDoc: defaultGetChangesFromCRDTDoc
15161 };
15162 }
15163 }
15164 const site = await (0, import_api_fetch.default)({
15165 path: entity2.baseURL,
15166 method: "OPTIONS"
15167 });
15168 const labels = {};
15169 Object.entries(site?.schema?.properties ?? {}).forEach(
15170 ([key, value]) => {
15171 if (typeof value === "object" && value.title) {
15172 labels[key] = value.title;
15173 }
15174 }
15175 );
15176 return [{ ...entity2, meta: { labels } }];
15177 }
15178 var getMethodName = (kind, name, prefix = "get") => {
15179 const kindPrefix = kind === "root" ? "" : pascalCase(kind);
15180 const suffix = pascalCase(name);
15181 return `${prefix}${kindPrefix}${suffix}`;
15182 };
15183
15184 // packages/core-data/build-module/queried-data/reducer.js
15185 function getContextFromAction(action) {
15186 const { query } = action;
15187 if (!query) {
15188 return "default";
15189 }
15190 const queryParts = get_query_parts_default(query);
15191 return queryParts.context;
15192 }
15193 function getMergedItemIds(itemIds, nextItemIds, page, perPage) {
15194 const receivedAllIds = page === 1 && perPage === -1;
15195 if (receivedAllIds) {
15196 return nextItemIds;
15197 }
15198 const nextItemIdsStartIndex = (page - 1) * perPage;
15199 const size = Math.max(
15200 itemIds?.length ?? 0,
15201 nextItemIdsStartIndex + nextItemIds.length
15202 );
15203 const mergedItemIds = new Array(size);
15204 for (let i = 0; i < size; i++) {
15205 const isInNextItemsRange = i >= nextItemIdsStartIndex && i < nextItemIdsStartIndex + perPage;
15206 mergedItemIds[i] = isInNextItemsRange ? nextItemIds[i - nextItemIdsStartIndex] : itemIds?.[i];
15207 }
15208 return mergedItemIds;
15209 }
15210 function removeEntitiesById(entities2, ids) {
15211 return Object.fromEntries(
15212 Object.entries(entities2).filter(
15213 ([id2]) => !ids.some((itemId) => {
15214 if (Number.isInteger(itemId)) {
15215 return itemId === +id2;
15216 }
15217 return itemId === id2;
15218 })
15219 )
15220 );
15221 }
15222 function items(state = {}, action) {
15223 switch (action.type) {
15224 case "RECEIVE_ITEMS": {
15225 const context = getContextFromAction(action);
15226 const key = action.key || DEFAULT_ENTITY_KEY;
15227 return {
15228 ...state,
15229 [context]: {
15230 ...state[context],
15231 ...action.items.reduce((accumulator, value) => {
15232 const itemId = value?.[key];
15233 accumulator[itemId] = conservativeMapItem(
15234 state?.[context]?.[itemId],
15235 value
15236 );
15237 return accumulator;
15238 }, {})
15239 }
15240 };
15241 }
15242 case "REMOVE_ITEMS":
15243 return Object.fromEntries(
15244 Object.entries(state).map(([itemId, contextState]) => [
15245 itemId,
15246 removeEntitiesById(contextState, action.itemIds)
15247 ])
15248 );
15249 }
15250 return state;
15251 }
15252 function itemIsComplete(state = {}, action) {
15253 switch (action.type) {
15254 case "RECEIVE_ITEMS": {
15255 const context = getContextFromAction(action);
15256 const { query, key = DEFAULT_ENTITY_KEY } = action;
15257 const queryParts = query ? get_query_parts_default(query) : {};
15258 const isCompleteQuery = !query || !Array.isArray(queryParts.fields);
15259 return {
15260 ...state,
15261 [context]: {
15262 ...state[context],
15263 ...action.items.reduce((result, item) => {
15264 const itemId = item?.[key];
15265 result[itemId] = state?.[context]?.[itemId] || isCompleteQuery;
15266 return result;
15267 }, {})
15268 }
15269 };
15270 }
15271 case "REMOVE_ITEMS":
15272 return Object.fromEntries(
15273 Object.entries(state).map(([itemId, contextState]) => [
15274 itemId,
15275 removeEntitiesById(contextState, action.itemIds)
15276 ])
15277 );
15278 }
15279 return state;
15280 }
15281 var receiveQueries = (0, import_compose.compose)([
15282 // Limit to matching action type so we don't attempt to replace action on
15283 // an unhandled action.
15284 if_matching_action_default((action) => "query" in action),
15285 // Inject query parts into action for use both in `onSubKey` and reducer.
15286 replace_action_default((action) => {
15287 if (action.query) {
15288 return {
15289 ...action,
15290 ...get_query_parts_default(action.query)
15291 };
15292 }
15293 return action;
15294 }),
15295 on_sub_key_default("context"),
15296 // Queries shape is shared, but keyed by query `stableKey` part. Original
15297 // reducer tracks only a single query object.
15298 on_sub_key_default("stableKey")
15299 ])((state = {}, action) => {
15300 const { type, page, perPage, key = DEFAULT_ENTITY_KEY } = action;
15301 if (type !== "RECEIVE_ITEMS") {
15302 return state;
15303 }
15304 return {
15305 itemIds: getMergedItemIds(
15306 state?.itemIds || [],
15307 action.items.map((item) => item?.[key]).filter(Boolean),
15308 page,
15309 perPage
15310 ),
15311 meta: action.meta
15312 };
15313 });
15314 var queries = (state = {}, action) => {
15315 switch (action.type) {
15316 case "RECEIVE_ITEMS":
15317 return receiveQueries(state, action);
15318 case "REMOVE_ITEMS":
15319 const removedItems = action.itemIds.reduce((result, itemId) => {
15320 result[itemId] = true;
15321 return result;
15322 }, {});
15323 return Object.fromEntries(
15324 Object.entries(state).map(
15325 ([queryGroup, contextQueries]) => [
15326 queryGroup,
15327 Object.fromEntries(
15328 Object.entries(contextQueries).map(
15329 ([query, queryItems]) => [
15330 query,
15331 {
15332 ...queryItems,
15333 itemIds: queryItems.itemIds.filter(
15334 (queryId) => !removedItems[queryId]
15335 )
15336 }
15337 ]
15338 )
15339 )
15340 ]
15341 )
15342 );
15343 default:
15344 return state;
15345 }
15346 };
15347 var reducer_default = (0, import_data2.combineReducers)({
15348 items,
15349 itemIsComplete,
15350 queries
15351 });
15352
15353 // packages/core-data/build-module/reducer.js
15354 function users(state = { byId: {}, queries: {} }, action) {
15355 switch (action.type) {
15356 case "RECEIVE_USER_QUERY":
15357 return {
15358 byId: {
15359 ...state.byId,
15360 // Key users by their ID.
15361 ...action.users.reduce(
15362 (newUsers, user) => ({
15363 ...newUsers,
15364 [user.id]: user
15365 }),
15366 {}
15367 )
15368 },
15369 queries: {
15370 ...state.queries,
15371 [action.queryID]: action.users.map((user) => user.id)
15372 }
15373 };
15374 }
15375 return state;
15376 }
15377 function currentUser(state = {}, action) {
15378 switch (action.type) {
15379 case "RECEIVE_CURRENT_USER":
15380 return action.currentUser;
15381 }
15382 return state;
15383 }
15384 function currentTheme(state = void 0, action) {
15385 switch (action.type) {
15386 case "RECEIVE_CURRENT_THEME":
15387 return action.currentTheme.stylesheet;
15388 }
15389 return state;
15390 }
15391 function currentGlobalStylesId(state = void 0, action) {
15392 switch (action.type) {
15393 case "RECEIVE_CURRENT_GLOBAL_STYLES_ID":
15394 return action.id;
15395 }
15396 return state;
15397 }
15398 function themeBaseGlobalStyles(state = {}, action) {
15399 switch (action.type) {
15400 case "RECEIVE_THEME_GLOBAL_STYLES":
15401 return {
15402 ...state,
15403 [action.stylesheet]: action.globalStyles
15404 };
15405 }
15406 return state;
15407 }
15408 function themeGlobalStyleVariations(state = {}, action) {
15409 switch (action.type) {
15410 case "RECEIVE_THEME_GLOBAL_STYLE_VARIATIONS":
15411 return {
15412 ...state,
15413 [action.stylesheet]: action.variations
15414 };
15415 }
15416 return state;
15417 }
15418 var withMultiEntityRecordEdits = (reducer) => (state, action) => {
15419 if (action.type === "UNDO" || action.type === "REDO") {
15420 const { record } = action;
15421 let newState = state;
15422 record.forEach(({ id: { kind, name, recordId }, changes }) => {
15423 newState = reducer(newState, {
15424 type: "EDIT_ENTITY_RECORD",
15425 kind,
15426 name,
15427 recordId,
15428 edits: Object.entries(changes).reduce(
15429 (acc, [key, value]) => {
15430 acc[key] = action.type === "UNDO" ? value.from : value.to;
15431 return acc;
15432 },
15433 {}
15434 )
15435 });
15436 });
15437 return newState;
15438 }
15439 return reducer(state, action);
15440 };
15441 function entity(entityConfig) {
15442 return (0, import_compose2.compose)([
15443 withMultiEntityRecordEdits,
15444 // Limit to matching action type so we don't attempt to replace action on
15445 // an unhandled action.
15446 if_matching_action_default(
15447 (action) => action.name && action.kind && action.name === entityConfig.name && action.kind === entityConfig.kind
15448 ),
15449 // Inject the entity config into the action.
15450 replace_action_default((action) => {
15451 return {
15452 key: entityConfig.key || DEFAULT_ENTITY_KEY,
15453 ...action
15454 };
15455 })
15456 ])(
15457 (0, import_data3.combineReducers)({
15458 queriedData: reducer_default,
15459 edits: (state = {}, action) => {
15460 switch (action.type) {
15461 case "RECEIVE_ITEMS":
15462 const context = action?.query?.context ?? "default";
15463 if (context !== "default") {
15464 return state;
15465 }
15466 const nextState = { ...state };
15467 for (const record of action.items) {
15468 const recordId = record?.[action.key];
15469 const edits = nextState[recordId];
15470 if (!edits) {
15471 continue;
15472 }
15473 const nextEdits2 = Object.keys(edits).reduce(
15474 (acc, key) => {
15475 if (
15476 // Edits are the "raw" attribute values, but records may have
15477 // objects with more properties, so we use `get` here for the
15478 // comparison.
15479 !(0, import_es64.default)(
15480 edits[key],
15481 record[key]?.raw ?? record[key]
15482 ) && // Sometimes the server alters the sent value which means
15483 // we need to also remove the edits before the api request.
15484 (!action.persistedEdits || !(0, import_es64.default)(
15485 edits[key],
15486 action.persistedEdits[key]
15487 ))
15488 ) {
15489 acc[key] = edits[key];
15490 }
15491 return acc;
15492 },
15493 {}
15494 );
15495 if (Object.keys(nextEdits2).length) {
15496 nextState[recordId] = nextEdits2;
15497 } else {
15498 delete nextState[recordId];
15499 }
15500 }
15501 return nextState;
15502 case "EDIT_ENTITY_RECORD":
15503 const nextEdits = {
15504 ...state[action.recordId],
15505 ...action.edits
15506 };
15507 Object.keys(nextEdits).forEach((key) => {
15508 if (nextEdits[key] === void 0) {
15509 delete nextEdits[key];
15510 }
15511 });
15512 return {
15513 ...state,
15514 [action.recordId]: nextEdits
15515 };
15516 }
15517 return state;
15518 },
15519 saving: (state = {}, action) => {
15520 switch (action.type) {
15521 case "SAVE_ENTITY_RECORD_START":
15522 case "SAVE_ENTITY_RECORD_FINISH":
15523 return {
15524 ...state,
15525 [action.recordId]: {
15526 pending: action.type === "SAVE_ENTITY_RECORD_START",
15527 error: action.error,
15528 isAutosave: action.isAutosave
15529 }
15530 };
15531 }
15532 return state;
15533 },
15534 deleting: (state = {}, action) => {
15535 switch (action.type) {
15536 case "DELETE_ENTITY_RECORD_START":
15537 case "DELETE_ENTITY_RECORD_FINISH":
15538 return {
15539 ...state,
15540 [action.recordId]: {
15541 pending: action.type === "DELETE_ENTITY_RECORD_START",
15542 error: action.error
15543 }
15544 };
15545 }
15546 return state;
15547 },
15548 revisions: (state = {}, action) => {
15549 if (action.type === "RECEIVE_ITEM_REVISIONS") {
15550 const recordKey = action.recordKey;
15551 delete action.recordKey;
15552 const newState = reducer_default(state[recordKey], {
15553 ...action,
15554 type: "RECEIVE_ITEMS"
15555 });
15556 return {
15557 ...state,
15558 [recordKey]: newState
15559 };
15560 }
15561 if (action.type === "REMOVE_ITEMS") {
15562 return Object.fromEntries(
15563 Object.entries(state).filter(
15564 ([id2]) => !action.itemIds.some((itemId) => {
15565 if (Number.isInteger(itemId)) {
15566 return itemId === +id2;
15567 }
15568 return itemId === id2;
15569 })
15570 )
15571 );
15572 }
15573 return state;
15574 }
15575 })
15576 );
15577 }
15578 function entitiesConfig(state = rootEntitiesConfig, action) {
15579 switch (action.type) {
15580 case "ADD_ENTITIES":
15581 return [...state, ...action.entities];
15582 }
15583 return state;
15584 }
15585 var entities = (state = {}, action) => {
15586 const newConfig = entitiesConfig(state.config, action);
15587 let entitiesDataReducer = state.reducer;
15588 if (!entitiesDataReducer || newConfig !== state.config) {
15589 const entitiesByKind = newConfig.reduce((acc, record) => {
15590 const { kind } = record;
15591 if (!acc[kind]) {
15592 acc[kind] = [];
15593 }
15594 acc[kind].push(record);
15595 return acc;
15596 }, {});
15597 entitiesDataReducer = (0, import_data3.combineReducers)(
15598 Object.fromEntries(
15599 Object.entries(entitiesByKind).map(
15600 ([kind, subEntities]) => {
15601 const kindReducer = (0, import_data3.combineReducers)(
15602 Object.fromEntries(
15603 subEntities.map((entityConfig) => [
15604 entityConfig.name,
15605 entity(entityConfig)
15606 ])
15607 )
15608 );
15609 return [kind, kindReducer];
15610 }
15611 )
15612 )
15613 );
15614 }
15615 const newData = entitiesDataReducer(state.records, action);
15616 if (newData === state.records && newConfig === state.config && entitiesDataReducer === state.reducer) {
15617 return state;
15618 }
15619 return {
15620 reducer: entitiesDataReducer,
15621 records: newData,
15622 config: newConfig
15623 };
15624 };
15625 function undoManager(state = (0, import_undo_manager2.createUndoManager)()) {
15626 return state;
15627 }
15628 function editsReference(state = {}, action) {
15629 switch (action.type) {
15630 case "EDIT_ENTITY_RECORD":
15631 case "UNDO":
15632 case "REDO":
15633 return {};
15634 }
15635 return state;
15636 }
15637 function embedPreviews(state = {}, action) {
15638 switch (action.type) {
15639 case "RECEIVE_EMBED_PREVIEW":
15640 const { url, preview } = action;
15641 return {
15642 ...state,
15643 [url]: preview
15644 };
15645 }
15646 return state;
15647 }
15648 function userPermissions(state = {}, action) {
15649 switch (action.type) {
15650 case "RECEIVE_USER_PERMISSION":
15651 return {
15652 ...state,
15653 [action.key]: action.isAllowed
15654 };
15655 case "RECEIVE_USER_PERMISSIONS":
15656 return {
15657 ...state,
15658 ...action.permissions
15659 };
15660 }
15661 return state;
15662 }
15663 function autosaves(state = {}, action) {
15664 switch (action.type) {
15665 case "RECEIVE_AUTOSAVES":
15666 const { postId, autosaves: autosavesData } = action;
15667 return {
15668 ...state,
15669 [postId]: autosavesData
15670 };
15671 }
15672 return state;
15673 }
15674 function blockPatterns(state = [], action) {
15675 switch (action.type) {
15676 case "RECEIVE_BLOCK_PATTERNS":
15677 return action.patterns;
15678 }
15679 return state;
15680 }
15681 function blockPatternCategories(state = [], action) {
15682 switch (action.type) {
15683 case "RECEIVE_BLOCK_PATTERN_CATEGORIES":
15684 return action.categories;
15685 }
15686 return state;
15687 }
15688 function userPatternCategories(state = [], action) {
15689 switch (action.type) {
15690 case "RECEIVE_USER_PATTERN_CATEGORIES":
15691 return action.patternCategories;
15692 }
15693 return state;
15694 }
15695 function navigationFallbackId(state = null, action) {
15696 switch (action.type) {
15697 case "RECEIVE_NAVIGATION_FALLBACK_ID":
15698 return action.fallbackId;
15699 }
15700 return state;
15701 }
15702 function themeGlobalStyleRevisions(state = {}, action) {
15703 switch (action.type) {
15704 case "RECEIVE_THEME_GLOBAL_STYLE_REVISIONS":
15705 return {
15706 ...state,
15707 [action.currentId]: action.revisions
15708 };
15709 }
15710 return state;
15711 }
15712 function defaultTemplates(state = {}, action) {
15713 switch (action.type) {
15714 case "RECEIVE_DEFAULT_TEMPLATE":
15715 return {
15716 ...state,
15717 [JSON.stringify(action.query)]: action.templateId
15718 };
15719 }
15720 return state;
15721 }
15722 function registeredPostMeta(state = {}, action) {
15723 switch (action.type) {
15724 case "RECEIVE_REGISTERED_POST_META":
15725 return {
15726 ...state,
15727 [action.postType]: action.registeredPostMeta
15728 };
15729 }
15730 return state;
15731 }
15732 function editorSettings(state = null, action) {
15733 switch (action.type) {
15734 case "RECEIVE_EDITOR_SETTINGS":
15735 return action.settings;
15736 }
15737 return state;
15738 }
15739 function editorAssets(state = null, action) {
15740 switch (action.type) {
15741 case "RECEIVE_EDITOR_ASSETS":
15742 return action.assets;
15743 }
15744 return state;
15745 }
15746 var reducer_default2 = (0, import_data3.combineReducers)({
15747 users,
15748 currentTheme,
15749 currentGlobalStylesId,
15750 currentUser,
15751 themeGlobalStyleVariations,
15752 themeBaseGlobalStyles,
15753 themeGlobalStyleRevisions,
15754 entities,
15755 editsReference,
15756 undoManager,
15757 embedPreviews,
15758 userPermissions,
15759 autosaves,
15760 blockPatterns,
15761 blockPatternCategories,
15762 userPatternCategories,
15763 navigationFallbackId,
15764 defaultTemplates,
15765 registeredPostMeta,
15766 editorSettings,
15767 editorAssets
15768 });
15769
15770 // packages/core-data/build-module/selectors.js
15771 var selectors_exports = {};
15772 __export(selectors_exports, {
15773 __experimentalGetCurrentGlobalStylesId: () => __experimentalGetCurrentGlobalStylesId,
15774 __experimentalGetCurrentThemeBaseGlobalStyles: () => __experimentalGetCurrentThemeBaseGlobalStyles,
15775 __experimentalGetCurrentThemeGlobalStylesVariations: () => __experimentalGetCurrentThemeGlobalStylesVariations,
15776 __experimentalGetDirtyEntityRecords: () => __experimentalGetDirtyEntityRecords,
15777 __experimentalGetEntitiesBeingSaved: () => __experimentalGetEntitiesBeingSaved,
15778 __experimentalGetEntityRecordNoResolver: () => __experimentalGetEntityRecordNoResolver,
15779 canUser: () => canUser,
15780 canUserEditEntityRecord: () => canUserEditEntityRecord,
15781 getAuthors: () => getAuthors,
15782 getAutosave: () => getAutosave,
15783 getAutosaves: () => getAutosaves,
15784 getBlockPatternCategories: () => getBlockPatternCategories,
15785 getBlockPatterns: () => getBlockPatterns,
15786 getCurrentTheme: () => getCurrentTheme,
15787 getCurrentThemeGlobalStylesRevisions: () => getCurrentThemeGlobalStylesRevisions,
15788 getCurrentUser: () => getCurrentUser,
15789 getDefaultTemplateId: () => getDefaultTemplateId,
15790 getEditedEntityRecord: () => getEditedEntityRecord,
15791 getEmbedPreview: () => getEmbedPreview,
15792 getEntitiesByKind: () => getEntitiesByKind,
15793 getEntitiesConfig: () => getEntitiesConfig,
15794 getEntity: () => getEntity,
15795 getEntityConfig: () => getEntityConfig,
15796 getEntityRecord: () => getEntityRecord,
15797 getEntityRecordEdits: () => getEntityRecordEdits,
15798 getEntityRecordNonTransientEdits: () => getEntityRecordNonTransientEdits,
15799 getEntityRecords: () => getEntityRecords,
15800 getEntityRecordsTotalItems: () => getEntityRecordsTotalItems,
15801 getEntityRecordsTotalPages: () => getEntityRecordsTotalPages,
15802 getLastEntityDeleteError: () => getLastEntityDeleteError,
15803 getLastEntitySaveError: () => getLastEntitySaveError,
15804 getRawEntityRecord: () => getRawEntityRecord,
15805 getRedoEdit: () => getRedoEdit,
15806 getReferenceByDistinctEdits: () => getReferenceByDistinctEdits,
15807 getRevision: () => getRevision,
15808 getRevisions: () => getRevisions,
15809 getThemeSupports: () => getThemeSupports,
15810 getUndoEdit: () => getUndoEdit,
15811 getUserPatternCategories: () => getUserPatternCategories,
15812 getUserQueryResults: () => getUserQueryResults,
15813 hasEditsForEntityRecord: () => hasEditsForEntityRecord,
15814 hasEntityRecord: () => hasEntityRecord,
15815 hasEntityRecords: () => hasEntityRecords,
15816 hasFetchedAutosaves: () => hasFetchedAutosaves,
15817 hasRedo: () => hasRedo,
15818 hasUndo: () => hasUndo,
15819 isAutosavingEntityRecord: () => isAutosavingEntityRecord,
15820 isDeletingEntityRecord: () => isDeletingEntityRecord,
15821 isPreviewEmbedFallback: () => isPreviewEmbedFallback,
15822 isRequestingEmbedPreview: () => isRequestingEmbedPreview,
15823 isSavingEntityRecord: () => isSavingEntityRecord
15824 });
15825 var import_data5 = __toESM(require_data());
15826 var import_url3 = __toESM(require_url());
15827 var import_deprecated2 = __toESM(require_deprecated());
15828
15829 // packages/core-data/build-module/name.js
15830 var STORE_NAME = "core";
15831
15832 // packages/core-data/build-module/private-selectors.js
15833 var private_selectors_exports = {};
15834 __export(private_selectors_exports, {
15835 getBlockPatternsForPostType: () => getBlockPatternsForPostType,
15836 getEditorAssets: () => getEditorAssets,
15837 getEditorSettings: () => getEditorSettings,
15838 getEntityRecordPermissions: () => getEntityRecordPermissions,
15839 getEntityRecordsPermissions: () => getEntityRecordsPermissions,
15840 getHomePage: () => getHomePage,
15841 getNavigationFallbackId: () => getNavigationFallbackId,
15842 getPostsPageId: () => getPostsPageId,
15843 getRegisteredPostMeta: () => getRegisteredPostMeta,
15844 getTemplateId: () => getTemplateId,
15845 getUndoManager: () => getUndoManager
15846 });
15847 var import_data4 = __toESM(require_data());
15848
15849 // packages/core-data/build-module/lock-unlock.js
15850 var import_private_apis = __toESM(require_private_apis());
15851 var { lock, unlock } = (0, import_private_apis.__dangerousOptInToUnstableAPIsOnlyForCoreModules)(
15852 "I acknowledge private features are not for use in themes or plugins and doing so will break in the next version of WordPress.",
15853 "@wordpress/core-data"
15854 );
15855
15856 // packages/core-data/build-module/utils/log-entity-deprecation.js
15857 var import_deprecated = __toESM(require_deprecated());
15858 var loggedAlready = false;
15859 function logEntityDeprecation(kind, name, functionName, {
15860 alternativeFunctionName,
15861 isShorthandSelector = false
15862 } = {}) {
15863 const deprecation = deprecatedEntities[kind]?.[name];
15864 if (!deprecation) {
15865 return;
15866 }
15867 if (!loggedAlready) {
15868 const { alternative } = deprecation;
15869 const message = isShorthandSelector ? `'${functionName}'` : `The '${kind}', '${name}' entity (used via '${functionName}')`;
15870 let alternativeMessage = `the '${alternative.kind}', '${alternative.name}' entity`;
15871 if (alternativeFunctionName) {
15872 alternativeMessage += ` via the '${alternativeFunctionName}' function`;
15873 }
15874 (0, import_deprecated.default)(message, {
15875 ...deprecation,
15876 alternative: alternativeMessage
15877 });
15878 }
15879 loggedAlready = true;
15880 setTimeout(() => {
15881 loggedAlready = false;
15882 }, 0);
15883 }
15884
15885 // packages/core-data/build-module/private-selectors.js
15886 function getUndoManager(state) {
15887 if (window.__experimentalEnableSync) {
15888 if (true) {
15889 return getSyncManager()?.undoManager ?? state.undoManager;
15890 }
15891 }
15892 return state.undoManager;
15893 }
15894 function getNavigationFallbackId(state) {
15895 return state.navigationFallbackId;
15896 }
15897 var getBlockPatternsForPostType = (0, import_data4.createRegistrySelector)(
15898 (select) => (0, import_data4.createSelector)(
15899 (state, postType) => select(STORE_NAME).getBlockPatterns().filter(
15900 ({ postTypes }) => !postTypes || Array.isArray(postTypes) && postTypes.includes(postType)
15901 ),
15902 () => [select(STORE_NAME).getBlockPatterns()]
15903 )
15904 );
15905 var getEntityRecordsPermissions = (0, import_data4.createRegistrySelector)(
15906 (select) => (0, import_data4.createSelector)(
15907 (state, kind, name, ids) => {
15908 const normalizedIds = Array.isArray(ids) ? ids : [ids];
15909 return normalizedIds.map((id2) => ({
15910 delete: select(STORE_NAME).canUser("delete", {
15911 kind,
15912 name,
15913 id: id2
15914 }),
15915 update: select(STORE_NAME).canUser("update", {
15916 kind,
15917 name,
15918 id: id2
15919 })
15920 }));
15921 },
15922 (state) => [state.userPermissions]
15923 )
15924 );
15925 function getEntityRecordPermissions(state, kind, name, id2) {
15926 logEntityDeprecation(kind, name, "getEntityRecordPermissions");
15927 return getEntityRecordsPermissions(state, kind, name, id2)[0];
15928 }
15929 function getRegisteredPostMeta(state, postType) {
15930 return state.registeredPostMeta?.[postType] ?? {};
15931 }
15932 function normalizePageId(value) {
15933 if (!value || !["number", "string"].includes(typeof value)) {
15934 return null;
15935 }
15936 if (Number(value) === 0) {
15937 return null;
15938 }
15939 return value.toString();
15940 }
15941 var getHomePage = (0, import_data4.createRegistrySelector)(
15942 (select) => (0, import_data4.createSelector)(
15943 () => {
15944 const siteData = select(STORE_NAME).getEntityRecord(
15945 "root",
15946 "__unstableBase"
15947 );
15948 if (!siteData) {
15949 return null;
15950 }
15951 const homepageId = siteData?.show_on_front === "page" ? normalizePageId(siteData.page_on_front) : null;
15952 if (homepageId) {
15953 return { postType: "page", postId: homepageId };
15954 }
15955 const frontPageTemplateId = select(
15956 STORE_NAME
15957 ).getDefaultTemplateId({
15958 slug: "front-page"
15959 });
15960 if (!frontPageTemplateId) {
15961 return null;
15962 }
15963 return { postType: "wp_template", postId: frontPageTemplateId };
15964 },
15965 (state) => [
15966 // Even though getDefaultTemplateId.shouldInvalidate returns true when root/site changes,
15967 // it doesn't seem to invalidate this cache, I'm not sure why.
15968 getEntityRecord(state, "root", "site"),
15969 getEntityRecord(state, "root", "__unstableBase"),
15970 getDefaultTemplateId(state, {
15971 slug: "front-page"
15972 })
15973 ]
15974 )
15975 );
15976 var getPostsPageId = (0, import_data4.createRegistrySelector)((select) => () => {
15977 const siteData = select(STORE_NAME).getEntityRecord(
15978 "root",
15979 "__unstableBase"
15980 );
15981 return siteData?.show_on_front === "page" ? normalizePageId(siteData.page_for_posts) : null;
15982 });
15983 var getTemplateId = (0, import_data4.createRegistrySelector)(
15984 (select) => (state, postType, postId) => {
15985 const homepage = unlock(select(STORE_NAME)).getHomePage();
15986 if (!homepage) {
15987 return;
15988 }
15989 if (postType === "page" && postType === homepage?.postType && postId.toString() === homepage?.postId) {
15990 const templates = select(STORE_NAME).getEntityRecords(
15991 "postType",
15992 "wp_template",
15993 {
15994 per_page: -1
15995 }
15996 );
15997 if (!templates) {
15998 return;
15999 }
16000 const id2 = templates.find(({ slug }) => slug === "front-page")?.id;
16001 if (id2) {
16002 return id2;
16003 }
16004 }
16005 const editedEntity = select(STORE_NAME).getEditedEntityRecord(
16006 "postType",
16007 postType,
16008 postId
16009 );
16010 if (!editedEntity) {
16011 return;
16012 }
16013 const postsPageId = unlock(select(STORE_NAME)).getPostsPageId();
16014 if (postType === "page" && postsPageId === postId.toString()) {
16015 return select(STORE_NAME).getDefaultTemplateId({
16016 slug: "home"
16017 });
16018 }
16019 const currentTemplateSlug = editedEntity.template;
16020 if (currentTemplateSlug) {
16021 const currentTemplate = select(STORE_NAME).getEntityRecords("postType", "wp_template", {
16022 per_page: -1
16023 })?.find(({ slug }) => slug === currentTemplateSlug);
16024 if (currentTemplate) {
16025 return currentTemplate.id;
16026 }
16027 }
16028 let slugToCheck;
16029 if (editedEntity.slug) {
16030 slugToCheck = postType === "page" ? `${postType}-${editedEntity.slug}` : `single-${postType}-${editedEntity.slug}`;
16031 } else {
16032 slugToCheck = postType === "page" ? "page" : `single-${postType}`;
16033 }
16034 return select(STORE_NAME).getDefaultTemplateId({
16035 slug: slugToCheck
16036 });
16037 }
16038 );
16039 function getEditorSettings(state) {
16040 return state.editorSettings;
16041 }
16042 function getEditorAssets(state) {
16043 return state.editorAssets;
16044 }
16045
16046 // packages/core-data/build-module/selectors.js
16047 var EMPTY_OBJECT = {};
16048 var isRequestingEmbedPreview = (0, import_data5.createRegistrySelector)(
16049 (select) => (state, url) => {
16050 return select(STORE_NAME).isResolving("getEmbedPreview", [
16051 url
16052 ]);
16053 }
16054 );
16055 function getAuthors(state, query) {
16056 (0, import_deprecated2.default)("select( 'core' ).getAuthors()", {
16057 since: "5.9",
16058 alternative: "select( 'core' ).getUsers({ who: 'authors' })"
16059 });
16060 const path = (0, import_url3.addQueryArgs)(
16061 "/wp/v2/users/?who=authors&per_page=100",
16062 query
16063 );
16064 return getUserQueryResults(state, path);
16065 }
16066 function getCurrentUser(state) {
16067 return state.currentUser;
16068 }
16069 var getUserQueryResults = (0, import_data5.createSelector)(
16070 (state, queryID) => {
16071 const queryResults = state.users.queries[queryID] ?? [];
16072 return queryResults.map((id2) => state.users.byId[id2]);
16073 },
16074 (state, queryID) => [
16075 state.users.queries[queryID],
16076 state.users.byId
16077 ]
16078 );
16079 function getEntitiesByKind(state, kind) {
16080 (0, import_deprecated2.default)("wp.data.select( 'core' ).getEntitiesByKind()", {
16081 since: "6.0",
16082 alternative: "wp.data.select( 'core' ).getEntitiesConfig()"
16083 });
16084 return getEntitiesConfig(state, kind);
16085 }
16086 var getEntitiesConfig = (0, import_data5.createSelector)(
16087 (state, kind) => state.entities.config.filter((entity2) => entity2.kind === kind),
16088 /* eslint-disable @typescript-eslint/no-unused-vars */
16089 (state, kind) => state.entities.config
16090 /* eslint-enable @typescript-eslint/no-unused-vars */
16091 );
16092 function getEntity(state, kind, name) {
16093 (0, import_deprecated2.default)("wp.data.select( 'core' ).getEntity()", {
16094 since: "6.0",
16095 alternative: "wp.data.select( 'core' ).getEntityConfig()"
16096 });
16097 return getEntityConfig(state, kind, name);
16098 }
16099 function getEntityConfig(state, kind, name) {
16100 logEntityDeprecation(kind, name, "getEntityConfig");
16101 return state.entities.config?.find(
16102 (config) => config.kind === kind && config.name === name
16103 );
16104 }
16105 var getEntityRecord = (0, import_data5.createSelector)(
16106 ((state, kind, name, key, query) => {
16107 logEntityDeprecation(kind, name, "getEntityRecord");
16108 const queriedState = state.entities.records?.[kind]?.[name]?.queriedData;
16109 if (!queriedState) {
16110 return void 0;
16111 }
16112 const context = query?.context ?? "default";
16113 if (!query || !query._fields) {
16114 if (!queriedState.itemIsComplete[context]?.[key]) {
16115 return void 0;
16116 }
16117 return queriedState.items[context][key];
16118 }
16119 const item = queriedState.items[context]?.[key];
16120 if (!item) {
16121 return item;
16122 }
16123 const filteredItem = {};
16124 const fields = get_normalized_comma_separable_default(query._fields) ?? [];
16125 for (let f = 0; f < fields.length; f++) {
16126 const field = fields[f].split(".");
16127 let value = item;
16128 field.forEach((fieldName) => {
16129 value = value?.[fieldName];
16130 });
16131 setNestedValue(filteredItem, field, value);
16132 }
16133 return filteredItem;
16134 }),
16135 (state, kind, name, recordId, query) => {
16136 const context = query?.context ?? "default";
16137 const queriedState = state.entities.records?.[kind]?.[name]?.queriedData;
16138 return [
16139 queriedState?.items[context]?.[recordId],
16140 queriedState?.itemIsComplete[context]?.[recordId]
16141 ];
16142 }
16143 );
16144 getEntityRecord.__unstableNormalizeArgs = (args2) => {
16145 const newArgs = [...args2];
16146 const recordKey = newArgs?.[2];
16147 newArgs[2] = isNumericID(recordKey) ? Number(recordKey) : recordKey;
16148 return newArgs;
16149 };
16150 function hasEntityRecord(state, kind, name, key, query) {
16151 const queriedState = state.entities.records?.[kind]?.[name]?.queriedData;
16152 if (!queriedState) {
16153 return false;
16154 }
16155 const context = query?.context ?? "default";
16156 if (!query || !query._fields) {
16157 return !!queriedState.itemIsComplete[context]?.[key];
16158 }
16159 const item = queriedState.items[context]?.[key];
16160 if (!item) {
16161 return false;
16162 }
16163 const fields = get_normalized_comma_separable_default(query._fields) ?? [];
16164 for (let i = 0; i < fields.length; i++) {
16165 const path = fields[i].split(".");
16166 let value = item;
16167 for (let p = 0; p < path.length; p++) {
16168 const part = path[p];
16169 if (!value || !Object.hasOwn(value, part)) {
16170 return false;
16171 }
16172 value = value[part];
16173 }
16174 }
16175 return true;
16176 }
16177 function __experimentalGetEntityRecordNoResolver(state, kind, name, key) {
16178 return getEntityRecord(state, kind, name, key);
16179 }
16180 var getRawEntityRecord = (0, import_data5.createSelector)(
16181 (state, kind, name, key) => {
16182 logEntityDeprecation(kind, name, "getRawEntityRecord");
16183 const record = getEntityRecord(
16184 state,
16185 kind,
16186 name,
16187 key
16188 );
16189 return record && Object.keys(record).reduce((accumulator, _key) => {
16190 if (isRawAttribute(getEntityConfig(state, kind, name), _key)) {
16191 accumulator[_key] = record[_key]?.raw !== void 0 ? record[_key]?.raw : record[_key];
16192 } else {
16193 accumulator[_key] = record[_key];
16194 }
16195 return accumulator;
16196 }, {});
16197 },
16198 (state, kind, name, recordId, query) => {
16199 const context = query?.context ?? "default";
16200 return [
16201 state.entities.config,
16202 state.entities.records?.[kind]?.[name]?.queriedData?.items[context]?.[recordId],
16203 state.entities.records?.[kind]?.[name]?.queriedData?.itemIsComplete[context]?.[recordId]
16204 ];
16205 }
16206 );
16207 function hasEntityRecords(state, kind, name, query) {
16208 logEntityDeprecation(kind, name, "hasEntityRecords");
16209 return Array.isArray(getEntityRecords(state, kind, name, query));
16210 }
16211 var getEntityRecords = ((state, kind, name, query) => {
16212 logEntityDeprecation(kind, name, "getEntityRecords");
16213 const queriedState = state.entities.records?.[kind]?.[name]?.queriedData;
16214 if (!queriedState) {
16215 return null;
16216 }
16217 return getQueriedItems(queriedState, query);
16218 });
16219 var getEntityRecordsTotalItems = (state, kind, name, query) => {
16220 logEntityDeprecation(kind, name, "getEntityRecordsTotalItems");
16221 const queriedState = state.entities.records?.[kind]?.[name]?.queriedData;
16222 if (!queriedState) {
16223 return null;
16224 }
16225 return getQueriedTotalItems(queriedState, query);
16226 };
16227 var getEntityRecordsTotalPages = (state, kind, name, query) => {
16228 logEntityDeprecation(kind, name, "getEntityRecordsTotalPages");
16229 const queriedState = state.entities.records?.[kind]?.[name]?.queriedData;
16230 if (!queriedState) {
16231 return null;
16232 }
16233 if (query?.per_page === -1) {
16234 return 1;
16235 }
16236 const totalItems = getQueriedTotalItems(queriedState, query);
16237 if (!totalItems) {
16238 return totalItems;
16239 }
16240 if (!query?.per_page) {
16241 return getQueriedTotalPages(queriedState, query);
16242 }
16243 return Math.ceil(totalItems / query.per_page);
16244 };
16245 var __experimentalGetDirtyEntityRecords = (0, import_data5.createSelector)(
16246 (state) => {
16247 const {
16248 entities: { records }
16249 } = state;
16250 const dirtyRecords = [];
16251 Object.keys(records).forEach((kind) => {
16252 Object.keys(records[kind]).forEach((name) => {
16253 const primaryKeys = Object.keys(records[kind][name].edits).filter(
16254 (primaryKey) => (
16255 // The entity record must exist (not be deleted),
16256 // and it must have edits.
16257 getEntityRecord(state, kind, name, primaryKey) && hasEditsForEntityRecord(state, kind, name, primaryKey)
16258 )
16259 );
16260 if (primaryKeys.length) {
16261 const entityConfig = getEntityConfig(state, kind, name);
16262 primaryKeys.forEach((primaryKey) => {
16263 const entityRecord = getEditedEntityRecord(
16264 state,
16265 kind,
16266 name,
16267 primaryKey
16268 );
16269 dirtyRecords.push({
16270 // We avoid using primaryKey because it's transformed into a string
16271 // when it's used as an object key.
16272 key: entityRecord ? entityRecord[entityConfig.key || DEFAULT_ENTITY_KEY] : void 0,
16273 title: entityConfig?.getTitle?.(entityRecord) || "",
16274 name,
16275 kind
16276 });
16277 });
16278 }
16279 });
16280 });
16281 return dirtyRecords;
16282 },
16283 (state) => [state.entities.records]
16284 );
16285 var __experimentalGetEntitiesBeingSaved = (0, import_data5.createSelector)(
16286 (state) => {
16287 const {
16288 entities: { records }
16289 } = state;
16290 const recordsBeingSaved = [];
16291 Object.keys(records).forEach((kind) => {
16292 Object.keys(records[kind]).forEach((name) => {
16293 const primaryKeys = Object.keys(records[kind][name].saving).filter(
16294 (primaryKey) => isSavingEntityRecord(state, kind, name, primaryKey)
16295 );
16296 if (primaryKeys.length) {
16297 const entityConfig = getEntityConfig(state, kind, name);
16298 primaryKeys.forEach((primaryKey) => {
16299 const entityRecord = getEditedEntityRecord(
16300 state,
16301 kind,
16302 name,
16303 primaryKey
16304 );
16305 recordsBeingSaved.push({
16306 // We avoid using primaryKey because it's transformed into a string
16307 // when it's used as an object key.
16308 key: entityRecord ? entityRecord[entityConfig.key || DEFAULT_ENTITY_KEY] : void 0,
16309 title: entityConfig?.getTitle?.(entityRecord) || "",
16310 name,
16311 kind
16312 });
16313 });
16314 }
16315 });
16316 });
16317 return recordsBeingSaved;
16318 },
16319 (state) => [state.entities.records]
16320 );
16321 function getEntityRecordEdits(state, kind, name, recordId) {
16322 logEntityDeprecation(kind, name, "getEntityRecordEdits");
16323 return state.entities.records?.[kind]?.[name]?.edits?.[recordId];
16324 }
16325 var getEntityRecordNonTransientEdits = (0, import_data5.createSelector)(
16326 (state, kind, name, recordId) => {
16327 logEntityDeprecation(kind, name, "getEntityRecordNonTransientEdits");
16328 const { transientEdits } = getEntityConfig(state, kind, name) || {};
16329 const edits = getEntityRecordEdits(state, kind, name, recordId) || {};
16330 if (!transientEdits) {
16331 return edits;
16332 }
16333 return Object.keys(edits).reduce((acc, key) => {
16334 if (!transientEdits[key]) {
16335 acc[key] = edits[key];
16336 }
16337 return acc;
16338 }, {});
16339 },
16340 (state, kind, name, recordId) => [
16341 state.entities.config,
16342 state.entities.records?.[kind]?.[name]?.edits?.[recordId]
16343 ]
16344 );
16345 function hasEditsForEntityRecord(state, kind, name, recordId) {
16346 logEntityDeprecation(kind, name, "hasEditsForEntityRecord");
16347 return isSavingEntityRecord(state, kind, name, recordId) || Object.keys(
16348 getEntityRecordNonTransientEdits(state, kind, name, recordId)
16349 ).length > 0;
16350 }
16351 var getEditedEntityRecord = (0, import_data5.createSelector)(
16352 (state, kind, name, recordId) => {
16353 logEntityDeprecation(kind, name, "getEditedEntityRecord");
16354 const raw = getRawEntityRecord(state, kind, name, recordId);
16355 const edited = getEntityRecordEdits(state, kind, name, recordId);
16356 if (!raw && !edited) {
16357 return false;
16358 }
16359 return {
16360 ...raw,
16361 ...edited
16362 };
16363 },
16364 (state, kind, name, recordId, query) => {
16365 const context = query?.context ?? "default";
16366 return [
16367 state.entities.config,
16368 state.entities.records?.[kind]?.[name]?.queriedData.items[context]?.[recordId],
16369 state.entities.records?.[kind]?.[name]?.queriedData.itemIsComplete[context]?.[recordId],
16370 state.entities.records?.[kind]?.[name]?.edits?.[recordId]
16371 ];
16372 }
16373 );
16374 function isAutosavingEntityRecord(state, kind, name, recordId) {
16375 logEntityDeprecation(kind, name, "isAutosavingEntityRecord");
16376 const { pending, isAutosave } = state.entities.records?.[kind]?.[name]?.saving?.[recordId] ?? {};
16377 return Boolean(pending && isAutosave);
16378 }
16379 function isSavingEntityRecord(state, kind, name, recordId) {
16380 logEntityDeprecation(kind, name, "isSavingEntityRecord");
16381 return state.entities.records?.[kind]?.[name]?.saving?.[recordId]?.pending ?? false;
16382 }
16383 function isDeletingEntityRecord(state, kind, name, recordId) {
16384 logEntityDeprecation(kind, name, "isDeletingEntityRecord");
16385 return state.entities.records?.[kind]?.[name]?.deleting?.[recordId]?.pending ?? false;
16386 }
16387 function getLastEntitySaveError(state, kind, name, recordId) {
16388 logEntityDeprecation(kind, name, "getLastEntitySaveError");
16389 return state.entities.records?.[kind]?.[name]?.saving?.[recordId]?.error;
16390 }
16391 function getLastEntityDeleteError(state, kind, name, recordId) {
16392 logEntityDeprecation(kind, name, "getLastEntityDeleteError");
16393 return state.entities.records?.[kind]?.[name]?.deleting?.[recordId]?.error;
16394 }
16395 function getUndoEdit(state) {
16396 (0, import_deprecated2.default)("select( 'core' ).getUndoEdit()", {
16397 since: "6.3"
16398 });
16399 return void 0;
16400 }
16401 function getRedoEdit(state) {
16402 (0, import_deprecated2.default)("select( 'core' ).getRedoEdit()", {
16403 since: "6.3"
16404 });
16405 return void 0;
16406 }
16407 function hasUndo(state) {
16408 return getUndoManager(state).hasUndo();
16409 }
16410 function hasRedo(state) {
16411 return getUndoManager(state).hasRedo();
16412 }
16413 function getCurrentTheme(state) {
16414 if (!state.currentTheme) {
16415 return null;
16416 }
16417 return getEntityRecord(state, "root", "theme", state.currentTheme);
16418 }
16419 function __experimentalGetCurrentGlobalStylesId(state) {
16420 return state.currentGlobalStylesId;
16421 }
16422 function getThemeSupports(state) {
16423 return getCurrentTheme(state)?.theme_supports ?? EMPTY_OBJECT;
16424 }
16425 function getEmbedPreview(state, url) {
16426 return state.embedPreviews[url];
16427 }
16428 function isPreviewEmbedFallback(state, url) {
16429 const preview = state.embedPreviews[url];
16430 const oEmbedLinkCheck = '<a href="' + url + '">' + url + "</a>";
16431 if (!preview) {
16432 return false;
16433 }
16434 return preview.html === oEmbedLinkCheck;
16435 }
16436 function canUser(state, action, resource, id2) {
16437 const isEntity = typeof resource === "object";
16438 if (isEntity && (!resource.kind || !resource.name)) {
16439 return false;
16440 }
16441 if (isEntity) {
16442 logEntityDeprecation(resource.kind, resource.name, "canUser");
16443 }
16444 const key = getUserPermissionCacheKey(action, resource, id2);
16445 return state.userPermissions[key];
16446 }
16447 function canUserEditEntityRecord(state, kind, name, recordId) {
16448 (0, import_deprecated2.default)(`wp.data.select( 'core' ).canUserEditEntityRecord()`, {
16449 since: "6.7",
16450 alternative: `wp.data.select( 'core' ).canUser( 'update', { kind, name, id } )`
16451 });
16452 return canUser(state, "update", { kind, name, id: recordId });
16453 }
16454 function getAutosaves(state, postType, postId) {
16455 return state.autosaves[postId];
16456 }
16457 function getAutosave(state, postType, postId, authorId) {
16458 if (authorId === void 0) {
16459 return;
16460 }
16461 const autosaves2 = state.autosaves[postId];
16462 return autosaves2?.find(
16463 (autosave) => autosave.author === authorId
16464 );
16465 }
16466 var hasFetchedAutosaves = (0, import_data5.createRegistrySelector)(
16467 (select) => (state, postType, postId) => {
16468 return select(STORE_NAME).hasFinishedResolution("getAutosaves", [
16469 postType,
16470 postId
16471 ]);
16472 }
16473 );
16474 function getReferenceByDistinctEdits(state) {
16475 return state.editsReference;
16476 }
16477 function __experimentalGetCurrentThemeBaseGlobalStyles(state) {
16478 const currentTheme2 = getCurrentTheme(state);
16479 if (!currentTheme2) {
16480 return null;
16481 }
16482 return state.themeBaseGlobalStyles[currentTheme2.stylesheet];
16483 }
16484 function __experimentalGetCurrentThemeGlobalStylesVariations(state) {
16485 const currentTheme2 = getCurrentTheme(state);
16486 if (!currentTheme2) {
16487 return null;
16488 }
16489 return state.themeGlobalStyleVariations[currentTheme2.stylesheet];
16490 }
16491 function getBlockPatterns(state) {
16492 return state.blockPatterns;
16493 }
16494 function getBlockPatternCategories(state) {
16495 return state.blockPatternCategories;
16496 }
16497 function getUserPatternCategories(state) {
16498 return state.userPatternCategories;
16499 }
16500 function getCurrentThemeGlobalStylesRevisions(state) {
16501 (0, import_deprecated2.default)("select( 'core' ).getCurrentThemeGlobalStylesRevisions()", {
16502 since: "6.5.0",
16503 alternative: "select( 'core' ).getRevisions( 'root', 'globalStyles', ${ recordKey } )"
16504 });
16505 const currentGlobalStylesId2 = __experimentalGetCurrentGlobalStylesId(state);
16506 if (!currentGlobalStylesId2) {
16507 return null;
16508 }
16509 return state.themeGlobalStyleRevisions[currentGlobalStylesId2];
16510 }
16511 function getDefaultTemplateId(state, query) {
16512 return state.defaultTemplates[JSON.stringify(query)];
16513 }
16514 var getRevisions = (state, kind, name, recordKey, query) => {
16515 logEntityDeprecation(kind, name, "getRevisions");
16516 const queriedStateRevisions = state.entities.records?.[kind]?.[name]?.revisions?.[recordKey];
16517 if (!queriedStateRevisions) {
16518 return null;
16519 }
16520 return getQueriedItems(queriedStateRevisions, query);
16521 };
16522 var getRevision = (0, import_data5.createSelector)(
16523 (state, kind, name, recordKey, revisionKey, query) => {
16524 logEntityDeprecation(kind, name, "getRevision");
16525 const queriedState = state.entities.records?.[kind]?.[name]?.revisions?.[recordKey];
16526 if (!queriedState) {
16527 return void 0;
16528 }
16529 const context = query?.context ?? "default";
16530 if (!query || !query._fields) {
16531 if (!queriedState.itemIsComplete[context]?.[revisionKey]) {
16532 return void 0;
16533 }
16534 return queriedState.items[context][revisionKey];
16535 }
16536 const item = queriedState.items[context]?.[revisionKey];
16537 if (!item) {
16538 return item;
16539 }
16540 const filteredItem = {};
16541 const fields = get_normalized_comma_separable_default(query._fields) ?? [];
16542 for (let f = 0; f < fields.length; f++) {
16543 const field = fields[f].split(".");
16544 let value = item;
16545 field.forEach((fieldName) => {
16546 value = value?.[fieldName];
16547 });
16548 setNestedValue(filteredItem, field, value);
16549 }
16550 return filteredItem;
16551 },
16552 (state, kind, name, recordKey, revisionKey, query) => {
16553 const context = query?.context ?? "default";
16554 const queriedState = state.entities.records?.[kind]?.[name]?.revisions?.[recordKey];
16555 return [
16556 queriedState?.items?.[context]?.[revisionKey],
16557 queriedState?.itemIsComplete?.[context]?.[revisionKey]
16558 ];
16559 }
16560 );
16561
16562 // packages/core-data/build-module/actions.js
16563 var actions_exports = {};
16564 __export(actions_exports, {
16565 __experimentalBatch: () => __experimentalBatch,
16566 __experimentalReceiveCurrentGlobalStylesId: () => __experimentalReceiveCurrentGlobalStylesId,
16567 __experimentalReceiveThemeBaseGlobalStyles: () => __experimentalReceiveThemeBaseGlobalStyles,
16568 __experimentalReceiveThemeGlobalStyleVariations: () => __experimentalReceiveThemeGlobalStyleVariations,
16569 __experimentalSaveSpecifiedEntityEdits: () => __experimentalSaveSpecifiedEntityEdits,
16570 __unstableCreateUndoLevel: () => __unstableCreateUndoLevel,
16571 addEntities: () => addEntities,
16572 deleteEntityRecord: () => deleteEntityRecord,
16573 editEntityRecord: () => editEntityRecord,
16574 receiveAutosaves: () => receiveAutosaves,
16575 receiveCurrentTheme: () => receiveCurrentTheme,
16576 receiveCurrentUser: () => receiveCurrentUser,
16577 receiveDefaultTemplateId: () => receiveDefaultTemplateId,
16578 receiveEmbedPreview: () => receiveEmbedPreview,
16579 receiveEntityRecords: () => receiveEntityRecords,
16580 receiveNavigationFallbackId: () => receiveNavigationFallbackId,
16581 receiveRevisions: () => receiveRevisions,
16582 receiveThemeGlobalStyleRevisions: () => receiveThemeGlobalStyleRevisions,
16583 receiveThemeSupports: () => receiveThemeSupports,
16584 receiveUploadPermissions: () => receiveUploadPermissions,
16585 receiveUserPermission: () => receiveUserPermission,
16586 receiveUserPermissions: () => receiveUserPermissions,
16587 receiveUserQuery: () => receiveUserQuery,
16588 redo: () => redo,
16589 saveEditedEntityRecord: () => saveEditedEntityRecord,
16590 saveEntityRecord: () => saveEntityRecord,
16591 undo: () => undo
16592 });
16593 var import_es65 = __toESM(require_es6());
16594 var import_api_fetch3 = __toESM(require_api_fetch());
16595 var import_url4 = __toESM(require_url());
16596 var import_deprecated3 = __toESM(require_deprecated());
16597
16598 // packages/core-data/build-module/batch/default-processor.js
16599 var import_api_fetch2 = __toESM(require_api_fetch());
16600 var maxItems = null;
16601 function chunk(arr, chunkSize) {
16602 const tmp = [...arr];
16603 const cache3 = [];
16604 while (tmp.length) {
16605 cache3.push(tmp.splice(0, chunkSize));
16606 }
16607 return cache3;
16608 }
16609 async function defaultProcessor(requests) {
16610 if (maxItems === null) {
16611 const preflightResponse = await (0, import_api_fetch2.default)({
16612 path: "/batch/v1",
16613 method: "OPTIONS"
16614 });
16615 maxItems = preflightResponse.endpoints[0].args.requests.maxItems;
16616 }
16617 const results = [];
16618 for (const batchRequests of chunk(requests, maxItems)) {
16619 const batchResponse = await (0, import_api_fetch2.default)({
16620 path: "/batch/v1",
16621 method: "POST",
16622 data: {
16623 validation: "require-all-validate",
16624 requests: batchRequests.map((request) => ({
16625 path: request.path,
16626 body: request.data,
16627 // Rename 'data' to 'body'.
16628 method: request.method,
16629 headers: request.headers
16630 }))
16631 }
16632 });
16633 let batchResults;
16634 if (batchResponse.failed) {
16635 batchResults = batchResponse.responses.map((response) => ({
16636 error: response?.body
16637 }));
16638 } else {
16639 batchResults = batchResponse.responses.map((response) => {
16640 const result = {};
16641 if (response.status >= 200 && response.status < 300) {
16642 result.output = response.body;
16643 } else {
16644 result.error = response.body;
16645 }
16646 return result;
16647 });
16648 }
16649 results.push(...batchResults);
16650 }
16651 return results;
16652 }
16653
16654 // packages/core-data/build-module/batch/create-batch.js
16655 function createBatch(processor = defaultProcessor) {
16656 let lastId = 0;
16657 let queue = [];
16658 const pending = new ObservableSet();
16659 return {
16660 /**
16661 * Adds an input to the batch and returns a promise that is resolved or
16662 * rejected when the input is processed by `batch.run()`.
16663 *
16664 * You may also pass a thunk which allows inputs to be added
16665 * asynchronously.
16666 *
16667 * ```
16668 * // Both are allowed:
16669 * batch.add( { path: '/v1/books', ... } );
16670 * batch.add( ( add ) => add( { path: '/v1/books', ... } ) );
16671 * ```
16672 *
16673 * If a thunk is passed, `batch.run()` will pause until either:
16674 *
16675 * - The thunk calls its `add` argument, or;
16676 * - The thunk returns a promise and that promise resolves, or;
16677 * - The thunk returns a non-promise.
16678 *
16679 * @param {any|Function} inputOrThunk Input to add or thunk to execute.
16680 *
16681 * @return {Promise|any} If given an input, returns a promise that
16682 * is resolved or rejected when the batch is
16683 * processed. If given a thunk, returns the return
16684 * value of that thunk.
16685 */
16686 add(inputOrThunk) {
16687 const id2 = ++lastId;
16688 pending.add(id2);
16689 const add = (input) => new Promise((resolve2, reject2) => {
16690 queue.push({
16691 input,
16692 resolve: resolve2,
16693 reject: reject2
16694 });
16695 pending.delete(id2);
16696 });
16697 if (typeof inputOrThunk === "function") {
16698 return Promise.resolve(inputOrThunk(add)).finally(() => {
16699 pending.delete(id2);
16700 });
16701 }
16702 return add(inputOrThunk);
16703 },
16704 /**
16705 * Runs the batch. This calls `batchProcessor` and resolves or rejects
16706 * all promises returned by `add()`.
16707 *
16708 * @return {Promise<boolean>} A promise that resolves to a boolean that is true
16709 * if the processor returned no errors.
16710 */
16711 async run() {
16712 if (pending.size) {
16713 await new Promise((resolve2) => {
16714 const unsubscribe2 = pending.subscribe(() => {
16715 if (!pending.size) {
16716 unsubscribe2();
16717 resolve2(void 0);
16718 }
16719 });
16720 });
16721 }
16722 let results;
16723 try {
16724 results = await processor(
16725 queue.map(({ input }) => input)
16726 );
16727 if (results.length !== queue.length) {
16728 throw new Error(
16729 "run: Array returned by processor must be same size as input array."
16730 );
16731 }
16732 } catch (error) {
16733 for (const { reject: reject2 } of queue) {
16734 reject2(error);
16735 }
16736 throw error;
16737 }
16738 let isSuccess = true;
16739 results.forEach((result, key) => {
16740 const queueItem = queue[key];
16741 if (result?.error) {
16742 queueItem?.reject(result.error);
16743 isSuccess = false;
16744 } else {
16745 queueItem?.resolve(result?.output ?? result);
16746 }
16747 });
16748 queue = [];
16749 return isSuccess;
16750 }
16751 };
16752 }
16753 var ObservableSet = class {
16754 constructor(...args2) {
16755 this.set = new Set(...args2);
16756 this.subscribers = /* @__PURE__ */ new Set();
16757 }
16758 get size() {
16759 return this.set.size;
16760 }
16761 add(value) {
16762 this.set.add(value);
16763 this.subscribers.forEach((subscriber) => subscriber());
16764 return this;
16765 }
16766 delete(value) {
16767 const isSuccess = this.set.delete(value);
16768 this.subscribers.forEach((subscriber) => subscriber());
16769 return isSuccess;
16770 }
16771 subscribe(subscriber) {
16772 this.subscribers.add(subscriber);
16773 return () => {
16774 this.subscribers.delete(subscriber);
16775 };
16776 }
16777 };
16778
16779 // packages/core-data/build-module/actions.js
16780 function receiveUserQuery(queryID, users2) {
16781 return {
16782 type: "RECEIVE_USER_QUERY",
16783 users: Array.isArray(users2) ? users2 : [users2],
16784 queryID
16785 };
16786 }
16787 function receiveCurrentUser(currentUser2) {
16788 return {
16789 type: "RECEIVE_CURRENT_USER",
16790 currentUser: currentUser2
16791 };
16792 }
16793 function addEntities(entities2) {
16794 return {
16795 type: "ADD_ENTITIES",
16796 entities: entities2
16797 };
16798 }
16799 function receiveEntityRecords(kind, name, records, query = void 0, invalidateCache = false, edits = void 0, meta = void 0) {
16800 if (kind === "postType") {
16801 records = (Array.isArray(records) ? records : [records]).map(
16802 (record) => record.status === "auto-draft" ? { ...record, title: "" } : record
16803 );
16804 }
16805 let action;
16806 if (query) {
16807 action = receiveQueriedItems(records, query, edits, meta);
16808 } else {
16809 action = receiveItems(records, edits, meta);
16810 }
16811 return {
16812 ...action,
16813 kind,
16814 name,
16815 invalidateCache
16816 };
16817 }
16818 function receiveCurrentTheme(currentTheme2) {
16819 return {
16820 type: "RECEIVE_CURRENT_THEME",
16821 currentTheme: currentTheme2
16822 };
16823 }
16824 function __experimentalReceiveCurrentGlobalStylesId(currentGlobalStylesId2) {
16825 return {
16826 type: "RECEIVE_CURRENT_GLOBAL_STYLES_ID",
16827 id: currentGlobalStylesId2
16828 };
16829 }
16830 function __experimentalReceiveThemeBaseGlobalStyles(stylesheet, globalStyles) {
16831 return {
16832 type: "RECEIVE_THEME_GLOBAL_STYLES",
16833 stylesheet,
16834 globalStyles
16835 };
16836 }
16837 function __experimentalReceiveThemeGlobalStyleVariations(stylesheet, variations) {
16838 return {
16839 type: "RECEIVE_THEME_GLOBAL_STYLE_VARIATIONS",
16840 stylesheet,
16841 variations
16842 };
16843 }
16844 function receiveThemeSupports() {
16845 (0, import_deprecated3.default)("wp.data.dispatch( 'core' ).receiveThemeSupports", {
16846 since: "5.9"
16847 });
16848 return {
16849 type: "DO_NOTHING"
16850 };
16851 }
16852 function receiveThemeGlobalStyleRevisions(currentId, revisions) {
16853 (0, import_deprecated3.default)(
16854 "wp.data.dispatch( 'core' ).receiveThemeGlobalStyleRevisions()",
16855 {
16856 since: "6.5.0",
16857 alternative: "wp.data.dispatch( 'core' ).receiveRevisions"
16858 }
16859 );
16860 return {
16861 type: "RECEIVE_THEME_GLOBAL_STYLE_REVISIONS",
16862 currentId,
16863 revisions
16864 };
16865 }
16866 function receiveEmbedPreview(url, preview) {
16867 return {
16868 type: "RECEIVE_EMBED_PREVIEW",
16869 url,
16870 preview
16871 };
16872 }
16873 var deleteEntityRecord = (kind, name, recordId, query, { __unstableFetch = import_api_fetch3.default, throwOnError = false } = {}) => async ({ dispatch, resolveSelect }) => {
16874 logEntityDeprecation(kind, name, "deleteEntityRecord");
16875 const configs = await resolveSelect.getEntitiesConfig(kind);
16876 const entityConfig = configs.find(
16877 (config) => config.kind === kind && config.name === name
16878 );
16879 let error;
16880 let deletedRecord = false;
16881 if (!entityConfig) {
16882 return;
16883 }
16884 const lock2 = await dispatch.__unstableAcquireStoreLock(
16885 STORE_NAME,
16886 ["entities", "records", kind, name, recordId],
16887 { exclusive: true }
16888 );
16889 try {
16890 dispatch({
16891 type: "DELETE_ENTITY_RECORD_START",
16892 kind,
16893 name,
16894 recordId
16895 });
16896 let hasError = false;
16897 let { baseURL } = entityConfig;
16898 if (kind === "postType" && name === "wp_template" && (recordId && typeof recordId === "string" && !/^\d+$/.test(recordId) || !window?.__experimentalTemplateActivate)) {
16899 baseURL = baseURL.slice(0, baseURL.lastIndexOf("/")) + "/templates";
16900 }
16901 try {
16902 let path = `${baseURL}/${recordId}`;
16903 if (query) {
16904 path = (0, import_url4.addQueryArgs)(path, query);
16905 }
16906 deletedRecord = await __unstableFetch({
16907 path,
16908 method: "DELETE"
16909 });
16910 await dispatch(removeItems(kind, name, recordId, true));
16911 } catch (_error) {
16912 hasError = true;
16913 error = _error;
16914 }
16915 dispatch({
16916 type: "DELETE_ENTITY_RECORD_FINISH",
16917 kind,
16918 name,
16919 recordId,
16920 error
16921 });
16922 if (hasError && throwOnError) {
16923 throw error;
16924 }
16925 return deletedRecord;
16926 } finally {
16927 dispatch.__unstableReleaseStoreLock(lock2);
16928 }
16929 };
16930 var editEntityRecord = (kind, name, recordId, edits, options = {}) => ({ select, dispatch }) => {
16931 logEntityDeprecation(kind, name, "editEntityRecord");
16932 const entityConfig = select.getEntityConfig(kind, name);
16933 if (!entityConfig) {
16934 throw new Error(
16935 `The entity being edited (${kind}, ${name}) does not have a loaded config.`
16936 );
16937 }
16938 const { mergedEdits = {} } = entityConfig;
16939 const record = select.getRawEntityRecord(kind, name, recordId);
16940 const editedRecord = select.getEditedEntityRecord(
16941 kind,
16942 name,
16943 recordId
16944 );
16945 const edit = {
16946 kind,
16947 name,
16948 recordId,
16949 // Clear edits when they are equal to their persisted counterparts
16950 // so that the property is not considered dirty.
16951 edits: Object.keys(edits).reduce((acc, key) => {
16952 const recordValue = record[key];
16953 const editedRecordValue = editedRecord[key];
16954 const value = mergedEdits[key] ? { ...editedRecordValue, ...edits[key] } : edits[key];
16955 acc[key] = (0, import_es65.default)(recordValue, value) ? void 0 : value;
16956 return acc;
16957 }, {})
16958 };
16959 if (window.__experimentalEnableSync && entityConfig.syncConfig) {
16960 if (true) {
16961 const objectType = `${kind}/${name}`;
16962 const objectId = recordId;
16963 getSyncManager()?.update(
16964 objectType,
16965 objectId,
16966 edit.edits,
16967 LOCAL_EDITOR_ORIGIN
16968 );
16969 }
16970 }
16971 if (!options.undoIgnore) {
16972 select.getUndoManager().addRecord(
16973 [
16974 {
16975 id: { kind, name, recordId },
16976 changes: Object.keys(edits).reduce((acc, key) => {
16977 acc[key] = {
16978 from: editedRecord[key],
16979 to: edits[key]
16980 };
16981 return acc;
16982 }, {})
16983 }
16984 ],
16985 options.isCached
16986 );
16987 }
16988 dispatch({
16989 type: "EDIT_ENTITY_RECORD",
16990 ...edit
16991 });
16992 };
16993 var undo = () => ({ select, dispatch }) => {
16994 const undoRecord = select.getUndoManager().undo();
16995 if (!undoRecord) {
16996 return;
16997 }
16998 dispatch({
16999 type: "UNDO",
17000 record: undoRecord
17001 });
17002 };
17003 var redo = () => ({ select, dispatch }) => {
17004 const redoRecord = select.getUndoManager().redo();
17005 if (!redoRecord) {
17006 return;
17007 }
17008 dispatch({
17009 type: "REDO",
17010 record: redoRecord
17011 });
17012 };
17013 var __unstableCreateUndoLevel = () => ({ select }) => {
17014 select.getUndoManager().addRecord();
17015 };
17016 var saveEntityRecord = (kind, name, record, {
17017 isAutosave = false,
17018 __unstableFetch = import_api_fetch3.default,
17019 throwOnError = false
17020 } = {}) => async ({ select, resolveSelect, dispatch }) => {
17021 logEntityDeprecation(kind, name, "saveEntityRecord");
17022 const configs = await resolveSelect.getEntitiesConfig(kind);
17023 const entityConfig = configs.find(
17024 (config) => config.kind === kind && config.name === name
17025 );
17026 if (!entityConfig) {
17027 return;
17028 }
17029 const entityIdKey = entityConfig.key ?? DEFAULT_ENTITY_KEY;
17030 const recordId = record[entityIdKey];
17031 const isNewRecord = !!entityIdKey && !recordId;
17032 const lock2 = await dispatch.__unstableAcquireStoreLock(
17033 STORE_NAME,
17034 ["entities", "records", kind, name, recordId || v4_default()],
17035 { exclusive: true }
17036 );
17037 try {
17038 for (const [key, value] of Object.entries(record)) {
17039 if (typeof value === "function") {
17040 const evaluatedValue = value(
17041 select.getEditedEntityRecord(kind, name, recordId)
17042 );
17043 dispatch.editEntityRecord(
17044 kind,
17045 name,
17046 recordId,
17047 {
17048 [key]: evaluatedValue
17049 },
17050 { undoIgnore: true }
17051 );
17052 record[key] = evaluatedValue;
17053 }
17054 }
17055 dispatch({
17056 type: "SAVE_ENTITY_RECORD_START",
17057 kind,
17058 name,
17059 recordId,
17060 isAutosave
17061 });
17062 let updatedRecord;
17063 let error;
17064 let hasError = false;
17065 let { baseURL } = entityConfig;
17066 if (kind === "postType" && name === "wp_template" && (recordId && typeof recordId === "string" && !/^\d+$/.test(recordId) || !window?.__experimentalTemplateActivate)) {
17067 baseURL = baseURL.slice(0, baseURL.lastIndexOf("/")) + "/templates";
17068 }
17069 try {
17070 const path = `${baseURL}${recordId ? "/" + recordId : ""}`;
17071 const persistedRecord = !isNewRecord ? select.getRawEntityRecord(kind, name, recordId) : {};
17072 if (isAutosave) {
17073 const currentUser2 = select.getCurrentUser();
17074 const currentUserId = currentUser2 ? currentUser2.id : void 0;
17075 const autosavePost = await resolveSelect.getAutosave(
17076 persistedRecord.type,
17077 persistedRecord.id,
17078 currentUserId
17079 );
17080 let data = {
17081 ...persistedRecord,
17082 ...autosavePost,
17083 ...record
17084 };
17085 data = Object.keys(data).reduce(
17086 (acc, key) => {
17087 if ([
17088 "title",
17089 "excerpt",
17090 "content",
17091 "meta"
17092 ].includes(key)) {
17093 acc[key] = data[key];
17094 }
17095 return acc;
17096 },
17097 {
17098 // Do not update the `status` if we have edited it when auto saving.
17099 // It's very important to let the user explicitly save this change,
17100 // because it can lead to unexpected results. An example would be to
17101 // have a draft post and change the status to publish.
17102 status: data.status === "auto-draft" ? "draft" : void 0
17103 }
17104 );
17105 updatedRecord = await __unstableFetch({
17106 path: `${path}/autosaves`,
17107 method: "POST",
17108 data
17109 });
17110 if (persistedRecord.id === updatedRecord.id) {
17111 let newRecord = {
17112 ...persistedRecord,
17113 ...data,
17114 ...updatedRecord
17115 };
17116 newRecord = Object.keys(newRecord).reduce(
17117 (acc, key) => {
17118 if (["title", "excerpt", "content"].includes(
17119 key
17120 )) {
17121 acc[key] = newRecord[key];
17122 } else if (key === "status") {
17123 acc[key] = persistedRecord.status === "auto-draft" && newRecord.status === "draft" ? newRecord.status : persistedRecord.status;
17124 } else {
17125 acc[key] = persistedRecord[key];
17126 }
17127 return acc;
17128 },
17129 {}
17130 );
17131 dispatch.receiveEntityRecords(
17132 kind,
17133 name,
17134 newRecord,
17135 void 0,
17136 true
17137 );
17138 } else {
17139 dispatch.receiveAutosaves(
17140 persistedRecord.id,
17141 updatedRecord
17142 );
17143 }
17144 } else {
17145 let edits = record;
17146 if (entityConfig.__unstablePrePersist) {
17147 edits = {
17148 ...edits,
17149 ...entityConfig.__unstablePrePersist(
17150 persistedRecord,
17151 edits
17152 )
17153 };
17154 }
17155 updatedRecord = await __unstableFetch({
17156 path,
17157 method: recordId ? "PUT" : "POST",
17158 data: edits
17159 });
17160 dispatch.receiveEntityRecords(
17161 kind,
17162 name,
17163 updatedRecord,
17164 void 0,
17165 true,
17166 edits
17167 );
17168 }
17169 } catch (_error) {
17170 hasError = true;
17171 error = _error;
17172 }
17173 dispatch({
17174 type: "SAVE_ENTITY_RECORD_FINISH",
17175 kind,
17176 name,
17177 recordId,
17178 error,
17179 isAutosave
17180 });
17181 if (hasError && throwOnError) {
17182 throw error;
17183 }
17184 return updatedRecord;
17185 } finally {
17186 dispatch.__unstableReleaseStoreLock(lock2);
17187 }
17188 };
17189 var __experimentalBatch = (requests) => async ({ dispatch }) => {
17190 const batch = createBatch();
17191 const api = {
17192 saveEntityRecord(kind, name, record, options) {
17193 return batch.add(
17194 (add) => dispatch.saveEntityRecord(kind, name, record, {
17195 ...options,
17196 __unstableFetch: add
17197 })
17198 );
17199 },
17200 saveEditedEntityRecord(kind, name, recordId, options) {
17201 return batch.add(
17202 (add) => dispatch.saveEditedEntityRecord(kind, name, recordId, {
17203 ...options,
17204 __unstableFetch: add
17205 })
17206 );
17207 },
17208 deleteEntityRecord(kind, name, recordId, query, options) {
17209 return batch.add(
17210 (add) => dispatch.deleteEntityRecord(kind, name, recordId, query, {
17211 ...options,
17212 __unstableFetch: add
17213 })
17214 );
17215 }
17216 };
17217 const resultPromises = requests.map((request) => request(api));
17218 const [, ...results] = await Promise.all([
17219 batch.run(),
17220 ...resultPromises
17221 ]);
17222 return results;
17223 };
17224 var saveEditedEntityRecord = (kind, name, recordId, options) => async ({ select, dispatch, resolveSelect }) => {
17225 logEntityDeprecation(kind, name, "saveEditedEntityRecord");
17226 if (!select.hasEditsForEntityRecord(kind, name, recordId)) {
17227 return;
17228 }
17229 const configs = await resolveSelect.getEntitiesConfig(kind);
17230 const entityConfig = configs.find(
17231 (config) => config.kind === kind && config.name === name
17232 );
17233 if (!entityConfig) {
17234 return;
17235 }
17236 const entityIdKey = entityConfig.key || DEFAULT_ENTITY_KEY;
17237 const edits = select.getEntityRecordNonTransientEdits(
17238 kind,
17239 name,
17240 recordId
17241 );
17242 const record = { [entityIdKey]: recordId, ...edits };
17243 return await dispatch.saveEntityRecord(kind, name, record, options);
17244 };
17245 var __experimentalSaveSpecifiedEntityEdits = (kind, name, recordId, itemsToSave, options) => async ({ select, dispatch, resolveSelect }) => {
17246 logEntityDeprecation(
17247 kind,
17248 name,
17249 "__experimentalSaveSpecifiedEntityEdits"
17250 );
17251 if (!select.hasEditsForEntityRecord(kind, name, recordId)) {
17252 return;
17253 }
17254 const edits = select.getEntityRecordNonTransientEdits(
17255 kind,
17256 name,
17257 recordId
17258 );
17259 const editsToSave = {};
17260 for (const item of itemsToSave) {
17261 setNestedValue(editsToSave, item, getNestedValue(edits, item));
17262 }
17263 const configs = await resolveSelect.getEntitiesConfig(kind);
17264 const entityConfig = configs.find(
17265 (config) => config.kind === kind && config.name === name
17266 );
17267 const entityIdKey = entityConfig?.key || DEFAULT_ENTITY_KEY;
17268 if (recordId) {
17269 editsToSave[entityIdKey] = recordId;
17270 }
17271 return await dispatch.saveEntityRecord(
17272 kind,
17273 name,
17274 editsToSave,
17275 options
17276 );
17277 };
17278 function receiveUploadPermissions(hasUploadPermissions) {
17279 (0, import_deprecated3.default)("wp.data.dispatch( 'core' ).receiveUploadPermissions", {
17280 since: "5.9",
17281 alternative: "receiveUserPermission"
17282 });
17283 return receiveUserPermission("create/media", hasUploadPermissions);
17284 }
17285 function receiveUserPermission(key, isAllowed) {
17286 return {
17287 type: "RECEIVE_USER_PERMISSION",
17288 key,
17289 isAllowed
17290 };
17291 }
17292 function receiveUserPermissions(permissions) {
17293 return {
17294 type: "RECEIVE_USER_PERMISSIONS",
17295 permissions
17296 };
17297 }
17298 function receiveAutosaves(postId, autosaves2) {
17299 return {
17300 type: "RECEIVE_AUTOSAVES",
17301 postId,
17302 autosaves: Array.isArray(autosaves2) ? autosaves2 : [autosaves2]
17303 };
17304 }
17305 function receiveNavigationFallbackId(fallbackId) {
17306 return {
17307 type: "RECEIVE_NAVIGATION_FALLBACK_ID",
17308 fallbackId
17309 };
17310 }
17311 function receiveDefaultTemplateId(query, templateId) {
17312 return {
17313 type: "RECEIVE_DEFAULT_TEMPLATE",
17314 query,
17315 templateId
17316 };
17317 }
17318 var receiveRevisions = (kind, name, recordKey, records, query, invalidateCache = false, meta) => async ({ dispatch, resolveSelect }) => {
17319 logEntityDeprecation(kind, name, "receiveRevisions");
17320 const configs = await resolveSelect.getEntitiesConfig(kind);
17321 const entityConfig = configs.find(
17322 (config) => config.kind === kind && config.name === name
17323 );
17324 const key = entityConfig && entityConfig?.revisionKey ? entityConfig.revisionKey : DEFAULT_ENTITY_KEY;
17325 dispatch({
17326 type: "RECEIVE_ITEM_REVISIONS",
17327 key,
17328 items: Array.isArray(records) ? records : [records],
17329 recordKey,
17330 meta,
17331 query,
17332 kind,
17333 name,
17334 invalidateCache
17335 });
17336 };
17337
17338 // packages/core-data/build-module/private-actions.js
17339 var private_actions_exports = {};
17340 __export(private_actions_exports, {
17341 editMediaEntity: () => editMediaEntity,
17342 receiveEditorAssets: () => receiveEditorAssets,
17343 receiveEditorSettings: () => receiveEditorSettings,
17344 receiveRegisteredPostMeta: () => receiveRegisteredPostMeta
17345 });
17346 var import_api_fetch4 = __toESM(require_api_fetch());
17347 function receiveRegisteredPostMeta(postType, registeredPostMeta2) {
17348 return {
17349 type: "RECEIVE_REGISTERED_POST_META",
17350 postType,
17351 registeredPostMeta: registeredPostMeta2
17352 };
17353 }
17354 var editMediaEntity = (recordId, edits = {}, { __unstableFetch = import_api_fetch4.default, throwOnError = false } = {}) => async ({ dispatch, resolveSelect }) => {
17355 if (!recordId) {
17356 return;
17357 }
17358 const kind = "postType";
17359 const name = "attachment";
17360 const configs = await resolveSelect.getEntitiesConfig(kind);
17361 const entityConfig = configs.find(
17362 (config) => config.kind === kind && config.name === name
17363 );
17364 if (!entityConfig) {
17365 return;
17366 }
17367 const lock2 = await dispatch.__unstableAcquireStoreLock(
17368 STORE_NAME,
17369 ["entities", "records", kind, name, recordId],
17370 { exclusive: true }
17371 );
17372 let updatedRecord;
17373 let error;
17374 let hasError = false;
17375 try {
17376 dispatch({
17377 type: "SAVE_ENTITY_RECORD_START",
17378 kind,
17379 name,
17380 recordId
17381 });
17382 try {
17383 const path = `${entityConfig.baseURL}/${recordId}/edit`;
17384 const newRecord = await __unstableFetch({
17385 path,
17386 method: "POST",
17387 data: {
17388 ...edits
17389 }
17390 });
17391 if (newRecord) {
17392 dispatch.receiveEntityRecords(
17393 kind,
17394 name,
17395 [newRecord],
17396 void 0,
17397 true,
17398 void 0,
17399 void 0
17400 );
17401 updatedRecord = newRecord;
17402 }
17403 } catch (e) {
17404 error = e;
17405 hasError = true;
17406 }
17407 dispatch({
17408 type: "SAVE_ENTITY_RECORD_FINISH",
17409 kind,
17410 name,
17411 recordId,
17412 error
17413 });
17414 if (hasError && throwOnError) {
17415 throw error;
17416 }
17417 return updatedRecord;
17418 } finally {
17419 dispatch.__unstableReleaseStoreLock(lock2);
17420 }
17421 };
17422 function receiveEditorSettings(settings) {
17423 return {
17424 type: "RECEIVE_EDITOR_SETTINGS",
17425 settings
17426 };
17427 }
17428 function receiveEditorAssets(assets) {
17429 return {
17430 type: "RECEIVE_EDITOR_ASSETS",
17431 assets
17432 };
17433 }
17434
17435 // packages/core-data/build-module/resolvers.js
17436 var resolvers_exports = {};
17437 __export(resolvers_exports, {
17438 __experimentalGetCurrentGlobalStylesId: () => __experimentalGetCurrentGlobalStylesId2,
17439 __experimentalGetCurrentThemeBaseGlobalStyles: () => __experimentalGetCurrentThemeBaseGlobalStyles2,
17440 __experimentalGetCurrentThemeGlobalStylesVariations: () => __experimentalGetCurrentThemeGlobalStylesVariations2,
17441 canUser: () => canUser2,
17442 canUserEditEntityRecord: () => canUserEditEntityRecord2,
17443 getAuthors: () => getAuthors2,
17444 getAutosave: () => getAutosave2,
17445 getAutosaves: () => getAutosaves2,
17446 getBlockPatternCategories: () => getBlockPatternCategories2,
17447 getBlockPatterns: () => getBlockPatterns2,
17448 getCurrentTheme: () => getCurrentTheme2,
17449 getCurrentThemeGlobalStylesRevisions: () => getCurrentThemeGlobalStylesRevisions2,
17450 getCurrentUser: () => getCurrentUser2,
17451 getDefaultTemplateId: () => getDefaultTemplateId2,
17452 getEditedEntityRecord: () => getEditedEntityRecord2,
17453 getEditorAssets: () => getEditorAssets2,
17454 getEditorSettings: () => getEditorSettings2,
17455 getEmbedPreview: () => getEmbedPreview2,
17456 getEntitiesConfig: () => getEntitiesConfig2,
17457 getEntityRecord: () => getEntityRecord2,
17458 getEntityRecords: () => getEntityRecords2,
17459 getEntityRecordsTotalItems: () => getEntityRecordsTotalItems2,
17460 getEntityRecordsTotalPages: () => getEntityRecordsTotalPages2,
17461 getNavigationFallbackId: () => getNavigationFallbackId2,
17462 getRawEntityRecord: () => getRawEntityRecord2,
17463 getRegisteredPostMeta: () => getRegisteredPostMeta2,
17464 getRevision: () => getRevision2,
17465 getRevisions: () => getRevisions2,
17466 getThemeSupports: () => getThemeSupports2,
17467 getUserPatternCategories: () => getUserPatternCategories2
17468 });
17469 var import_url7 = __toESM(require_url());
17470 var import_html_entities2 = __toESM(require_html_entities());
17471 var import_api_fetch8 = __toESM(require_api_fetch());
17472
17473 // packages/core-data/build-module/fetch/index.js
17474 var import_api_fetch7 = __toESM(require_api_fetch());
17475
17476 // packages/core-data/build-module/fetch/__experimental-fetch-link-suggestions.js
17477 var import_api_fetch5 = __toESM(require_api_fetch());
17478 var import_url5 = __toESM(require_url());
17479 var import_html_entities = __toESM(require_html_entities());
17480 var import_i18n2 = __toESM(require_i18n());
17481 async function fetchLinkSuggestions(search, searchOptions = {}, editorSettings2 = {}) {
17482 const searchOptionsToUse = searchOptions.isInitialSuggestions && searchOptions.initialSuggestionsSearchOptions ? {
17483 ...searchOptions,
17484 ...searchOptions.initialSuggestionsSearchOptions
17485 } : searchOptions;
17486 const {
17487 type,
17488 subtype,
17489 page,
17490 perPage = searchOptions.isInitialSuggestions ? 3 : 20
17491 } = searchOptionsToUse;
17492 const { disablePostFormats = false } = editorSettings2;
17493 const queries2 = [];
17494 if (!type || type === "post") {
17495 queries2.push(
17496 (0, import_api_fetch5.default)({
17497 path: (0, import_url5.addQueryArgs)("/wp/v2/search", {
17498 search,
17499 page,
17500 per_page: perPage,
17501 type: "post",
17502 subtype
17503 })
17504 }).then((results2) => {
17505 return results2.map((result) => {
17506 return {
17507 id: result.id,
17508 url: result.url,
17509 title: (0, import_html_entities.decodeEntities)(result.title || "") || (0, import_i18n2.__)("(no title)"),
17510 type: result.subtype || result.type,
17511 kind: "post-type"
17512 };
17513 });
17514 }).catch(() => [])
17515 // Fail by returning no results.
17516 );
17517 }
17518 if (!type || type === "term") {
17519 queries2.push(
17520 (0, import_api_fetch5.default)({
17521 path: (0, import_url5.addQueryArgs)("/wp/v2/search", {
17522 search,
17523 page,
17524 per_page: perPage,
17525 type: "term",
17526 subtype
17527 })
17528 }).then((results2) => {
17529 return results2.map((result) => {
17530 return {
17531 id: result.id,
17532 url: result.url,
17533 title: (0, import_html_entities.decodeEntities)(result.title || "") || (0, import_i18n2.__)("(no title)"),
17534 type: result.subtype || result.type,
17535 kind: "taxonomy"
17536 };
17537 });
17538 }).catch(() => [])
17539 // Fail by returning no results.
17540 );
17541 }
17542 if (!disablePostFormats && (!type || type === "post-format")) {
17543 queries2.push(
17544 (0, import_api_fetch5.default)({
17545 path: (0, import_url5.addQueryArgs)("/wp/v2/search", {
17546 search,
17547 page,
17548 per_page: perPage,
17549 type: "post-format",
17550 subtype
17551 })
17552 }).then((results2) => {
17553 return results2.map((result) => {
17554 return {
17555 id: result.id,
17556 url: result.url,
17557 title: (0, import_html_entities.decodeEntities)(result.title || "") || (0, import_i18n2.__)("(no title)"),
17558 type: result.subtype || result.type,
17559 kind: "taxonomy"
17560 };
17561 });
17562 }).catch(() => [])
17563 // Fail by returning no results.
17564 );
17565 }
17566 if (!type || type === "attachment") {
17567 queries2.push(
17568 (0, import_api_fetch5.default)({
17569 path: (0, import_url5.addQueryArgs)("/wp/v2/media", {
17570 search,
17571 page,
17572 per_page: perPage
17573 })
17574 }).then((results2) => {
17575 return results2.map((result) => {
17576 return {
17577 id: result.id,
17578 url: result.source_url,
17579 title: (0, import_html_entities.decodeEntities)(result.title.rendered || "") || (0, import_i18n2.__)("(no title)"),
17580 type: result.type,
17581 kind: "media"
17582 };
17583 });
17584 }).catch(() => [])
17585 // Fail by returning no results.
17586 );
17587 }
17588 const responses = await Promise.all(queries2);
17589 let results = responses.flat();
17590 results = results.filter((result) => !!result.id);
17591 results = sortResults(results, search);
17592 results = results.slice(0, perPage);
17593 return results;
17594 }
17595 function sortResults(results, search) {
17596 const searchTokens = tokenize(search);
17597 const scores = {};
17598 for (const result of results) {
17599 if (result.title) {
17600 const titleTokens = tokenize(result.title);
17601 const exactMatchingTokens = titleTokens.filter(
17602 (titleToken) => searchTokens.some(
17603 (searchToken) => titleToken === searchToken
17604 )
17605 );
17606 const subMatchingTokens = titleTokens.filter(
17607 (titleToken) => searchTokens.some(
17608 (searchToken) => titleToken !== searchToken && titleToken.includes(searchToken)
17609 )
17610 );
17611 const exactMatchScore = exactMatchingTokens.length / titleTokens.length * 10;
17612 const subMatchScore = subMatchingTokens.length / titleTokens.length;
17613 scores[result.id] = exactMatchScore + subMatchScore;
17614 } else {
17615 scores[result.id] = 0;
17616 }
17617 }
17618 return results.sort((a, b) => scores[b.id] - scores[a.id]);
17619 }
17620 function tokenize(text2) {
17621 return text2.toLowerCase().match(/[\p{L}\p{N}]+/gu) || [];
17622 }
17623
17624 // packages/core-data/build-module/fetch/__experimental-fetch-url-data.js
17625 var import_api_fetch6 = __toESM(require_api_fetch());
17626 var import_url6 = __toESM(require_url());
17627 var CACHE = /* @__PURE__ */ new Map();
17628 var fetchUrlData = async (url, options = {}) => {
17629 const endpoint = "/wp-block-editor/v1/url-details";
17630 const args2 = {
17631 url: (0, import_url6.prependHTTP)(url)
17632 };
17633 if (!(0, import_url6.isURL)(url)) {
17634 return Promise.reject(`${url} is not a valid URL.`);
17635 }
17636 const protocol = (0, import_url6.getProtocol)(url);
17637 if (!protocol || !(0, import_url6.isValidProtocol)(protocol) || !protocol.startsWith("http") || !/^https?:\/\/[^\/\s]/i.test(url)) {
17638 return Promise.reject(
17639 `${url} does not have a valid protocol. URLs must be "http" based`
17640 );
17641 }
17642 if (CACHE.has(url)) {
17643 return CACHE.get(url);
17644 }
17645 return (0, import_api_fetch6.default)({
17646 path: (0, import_url6.addQueryArgs)(endpoint, args2),
17647 ...options
17648 }).then((res) => {
17649 CACHE.set(url, res);
17650 return res;
17651 });
17652 };
17653 var experimental_fetch_url_data_default = fetchUrlData;
17654
17655 // packages/core-data/build-module/fetch/index.js
17656 async function fetchBlockPatterns() {
17657 const restPatterns = await (0, import_api_fetch7.default)({
17658 path: "/wp/v2/block-patterns/patterns"
17659 });
17660 if (!restPatterns) {
17661 return [];
17662 }
17663 return restPatterns.map(
17664 (pattern) => Object.fromEntries(
17665 Object.entries(pattern).map(([key, value]) => [
17666 camelCase(key),
17667 value
17668 ])
17669 )
17670 );
17671 }
17672
17673 // packages/core-data/build-module/resolvers.js
17674 var getAuthors2 = (query) => async ({ dispatch }) => {
17675 const path = (0, import_url7.addQueryArgs)(
17676 "/wp/v2/users/?who=authors&per_page=100",
17677 query
17678 );
17679 const users2 = await (0, import_api_fetch8.default)({ path });
17680 dispatch.receiveUserQuery(path, users2);
17681 };
17682 var getCurrentUser2 = () => async ({ dispatch }) => {
17683 const currentUser2 = await (0, import_api_fetch8.default)({ path: "/wp/v2/users/me" });
17684 dispatch.receiveCurrentUser(currentUser2);
17685 };
17686 var getEntityRecord2 = (kind, name, key = "", query) => async ({ select, dispatch, registry, resolveSelect }) => {
17687 const configs = await resolveSelect.getEntitiesConfig(kind);
17688 const entityConfig = configs.find(
17689 (config) => config.name === name && config.kind === kind
17690 );
17691 if (!entityConfig) {
17692 return;
17693 }
17694 const lock2 = await dispatch.__unstableAcquireStoreLock(
17695 STORE_NAME,
17696 ["entities", "records", kind, name, key],
17697 { exclusive: false }
17698 );
17699 try {
17700 if (query !== void 0 && query._fields) {
17701 query = {
17702 ...query,
17703 _fields: [
17704 .../* @__PURE__ */ new Set([
17705 ...get_normalized_comma_separable_default(query._fields) || [],
17706 entityConfig.key || DEFAULT_ENTITY_KEY
17707 ])
17708 ].join()
17709 };
17710 }
17711 if (query !== void 0 && query._fields) {
17712 const hasRecord = select.hasEntityRecord(
17713 kind,
17714 name,
17715 key,
17716 query
17717 );
17718 if (hasRecord) {
17719 return;
17720 }
17721 }
17722 let { baseURL } = entityConfig;
17723 if (kind === "postType" && name === "wp_template" && (key && typeof key === "string" && !/^\d+$/.test(key) || !window?.__experimentalTemplateActivate)) {
17724 baseURL = baseURL.slice(0, baseURL.lastIndexOf("/")) + "/templates";
17725 }
17726 const path = (0, import_url7.addQueryArgs)(baseURL + (key ? "/" + key : ""), {
17727 ...entityConfig.baseURLParams,
17728 ...query
17729 });
17730 const response = await (0, import_api_fetch8.default)({ path, parse: false });
17731 const record = await response.json();
17732 const permissions = getUserPermissionsFromAllowHeader(
17733 response.headers?.get("allow")
17734 );
17735 const canUserResolutionsArgs = [];
17736 const receiveUserPermissionArgs = {};
17737 for (const action of ALLOWED_RESOURCE_ACTIONS) {
17738 receiveUserPermissionArgs[getUserPermissionCacheKey(action, {
17739 kind,
17740 name,
17741 id: key
17742 })] = permissions[action];
17743 canUserResolutionsArgs.push([
17744 action,
17745 { kind, name, id: key }
17746 ]);
17747 }
17748 if (window.__experimentalEnableSync && entityConfig.syncConfig && isNumericID(key) && !query) {
17749 if (true) {
17750 const objectType = `${kind}/${name}`;
17751 const objectId = key;
17752 const recordWithTransients = { ...record };
17753 Object.entries(entityConfig.transientEdits ?? {}).filter(
17754 ([propName, transientConfig]) => void 0 === recordWithTransients[propName] && transientConfig && "object" === typeof transientConfig && "read" in transientConfig && "function" === typeof transientConfig.read
17755 ).forEach(([propName, transientConfig]) => {
17756 recordWithTransients[propName] = transientConfig.read(recordWithTransients);
17757 });
17758 await getSyncManager()?.load(
17759 entityConfig.syncConfig,
17760 objectType,
17761 objectId,
17762 recordWithTransients,
17763 {
17764 // Handle edits sourced from the sync manager.
17765 editRecord: (edits) => {
17766 if (!Object.keys(edits).length) {
17767 return;
17768 }
17769 dispatch({
17770 type: "EDIT_ENTITY_RECORD",
17771 kind,
17772 name,
17773 recordId: key,
17774 edits,
17775 meta: {
17776 undo: void 0
17777 }
17778 });
17779 },
17780 // Get the current entity record (with edits)
17781 getEditedRecord: async () => await resolveSelect.getEditedEntityRecord(
17782 kind,
17783 name,
17784 key
17785 ),
17786 // Save the current entity record's unsaved edits.
17787 saveRecord: () => {
17788 dispatch.saveEditedEntityRecord(
17789 kind,
17790 name,
17791 key
17792 );
17793 }
17794 }
17795 );
17796 }
17797 }
17798 registry.batch(() => {
17799 dispatch.receiveEntityRecords(kind, name, record, query);
17800 dispatch.receiveUserPermissions(receiveUserPermissionArgs);
17801 dispatch.finishResolutions("canUser", canUserResolutionsArgs);
17802 });
17803 } finally {
17804 dispatch.__unstableReleaseStoreLock(lock2);
17805 }
17806 };
17807 getEntityRecord2.shouldInvalidate = (action, kind, name) => {
17808 return kind === "root" && name === "site" && (action.type === "RECEIVE_ITEMS" && // Making sure persistedEdits is set seems to be the only way of
17809 // knowing whether it's an update or fetch. Only an update would
17810 // have persistedEdits.
17811 action.persistedEdits && action.persistedEdits.status !== "auto-draft" || action.type === "REMOVE_ITEMS") && action.kind === "postType" && action.name === "wp_template";
17812 };
17813 var getRawEntityRecord2 = forward_resolver_default("getEntityRecord");
17814 var getEditedEntityRecord2 = forward_resolver_default("getEntityRecord");
17815 var getEntityRecords2 = (kind, name, query = {}) => async ({ dispatch, registry, resolveSelect }) => {
17816 const configs = await resolveSelect.getEntitiesConfig(kind);
17817 const entityConfig = configs.find(
17818 (config) => config.name === name && config.kind === kind
17819 );
17820 if (!entityConfig) {
17821 return;
17822 }
17823 const lock2 = await dispatch.__unstableAcquireStoreLock(
17824 STORE_NAME,
17825 ["entities", "records", kind, name],
17826 { exclusive: false }
17827 );
17828 const rawQuery = { ...query };
17829 const key = entityConfig.key || DEFAULT_ENTITY_KEY;
17830 function getResolutionsArgs(records, recordsQuery) {
17831 const queryArgs = Object.fromEntries(
17832 Object.entries(recordsQuery).filter(([k, v]) => {
17833 return ["context", "_fields"].includes(k) && !!v;
17834 })
17835 );
17836 return records.filter((record) => record?.[key]).map((record) => [
17837 kind,
17838 name,
17839 record[key],
17840 Object.keys(queryArgs).length > 0 ? queryArgs : void 0
17841 ]);
17842 }
17843 try {
17844 if (query._fields) {
17845 query = {
17846 ...query,
17847 _fields: [
17848 .../* @__PURE__ */ new Set([
17849 ...get_normalized_comma_separable_default(query._fields) || [],
17850 key
17851 ])
17852 ].join()
17853 };
17854 }
17855 let { baseURL } = entityConfig;
17856 const { combinedTemplates = true } = query;
17857 if (kind === "postType" && name === "wp_template" && combinedTemplates) {
17858 baseURL = baseURL.slice(0, baseURL.lastIndexOf("/")) + "/templates";
17859 }
17860 const path = (0, import_url7.addQueryArgs)(baseURL, {
17861 ...entityConfig.baseURLParams,
17862 ...query
17863 });
17864 let records = [], meta;
17865 if (entityConfig.supportsPagination && query.per_page !== -1) {
17866 const response = await (0, import_api_fetch8.default)({ path, parse: false });
17867 records = Object.values(await response.json());
17868 meta = {
17869 totalItems: parseInt(
17870 response.headers.get("X-WP-Total")
17871 ),
17872 totalPages: parseInt(
17873 response.headers.get("X-WP-TotalPages")
17874 )
17875 };
17876 } else if (query.per_page === -1 && query[RECEIVE_INTERMEDIATE_RESULTS] === true) {
17877 let page = 1;
17878 let totalPages;
17879 do {
17880 const response = await (0, import_api_fetch8.default)({
17881 path: (0, import_url7.addQueryArgs)(path, { page, per_page: 100 }),
17882 parse: false
17883 });
17884 const pageRecords = Object.values(await response.json());
17885 totalPages = parseInt(
17886 response.headers.get("X-WP-TotalPages")
17887 );
17888 if (!meta) {
17889 meta = {
17890 totalItems: parseInt(
17891 response.headers.get("X-WP-Total")
17892 ),
17893 totalPages: 1
17894 };
17895 }
17896 records.push(...pageRecords);
17897 registry.batch(() => {
17898 dispatch.receiveEntityRecords(
17899 kind,
17900 name,
17901 records,
17902 query,
17903 false,
17904 void 0,
17905 meta
17906 );
17907 dispatch.finishResolutions(
17908 "getEntityRecord",
17909 getResolutionsArgs(pageRecords, rawQuery)
17910 );
17911 });
17912 page++;
17913 } while (page <= totalPages);
17914 } else {
17915 records = Object.values(await (0, import_api_fetch8.default)({ path }));
17916 meta = {
17917 totalItems: records.length,
17918 totalPages: 1
17919 };
17920 }
17921 if (query._fields) {
17922 records = records.map((record) => {
17923 query._fields.split(",").forEach((field) => {
17924 if (!record.hasOwnProperty(field)) {
17925 record[field] = void 0;
17926 }
17927 });
17928 return record;
17929 });
17930 }
17931 registry.batch(() => {
17932 dispatch.receiveEntityRecords(
17933 kind,
17934 name,
17935 records,
17936 query,
17937 false,
17938 void 0,
17939 meta
17940 );
17941 const targetHints = records.filter(
17942 (record) => !!record?.[key] && !!record?._links?.self?.[0]?.targetHints?.allow
17943 ).map((record) => ({
17944 id: record[key],
17945 permissions: getUserPermissionsFromAllowHeader(
17946 record._links.self[0].targetHints.allow
17947 )
17948 }));
17949 const canUserResolutionsArgs = [];
17950 const receiveUserPermissionArgs = {};
17951 for (const targetHint of targetHints) {
17952 for (const action of ALLOWED_RESOURCE_ACTIONS) {
17953 canUserResolutionsArgs.push([
17954 action,
17955 { kind, name, id: targetHint.id }
17956 ]);
17957 receiveUserPermissionArgs[getUserPermissionCacheKey(action, {
17958 kind,
17959 name,
17960 id: targetHint.id
17961 })] = targetHint.permissions[action];
17962 }
17963 }
17964 if (targetHints.length > 0) {
17965 dispatch.receiveUserPermissions(
17966 receiveUserPermissionArgs
17967 );
17968 dispatch.finishResolutions(
17969 "canUser",
17970 canUserResolutionsArgs
17971 );
17972 }
17973 dispatch.finishResolutions(
17974 "getEntityRecord",
17975 getResolutionsArgs(records, rawQuery)
17976 );
17977 dispatch.__unstableReleaseStoreLock(lock2);
17978 });
17979 } catch (e) {
17980 dispatch.__unstableReleaseStoreLock(lock2);
17981 }
17982 };
17983 getEntityRecords2.shouldInvalidate = (action, kind, name) => {
17984 return (action.type === "RECEIVE_ITEMS" || action.type === "REMOVE_ITEMS") && action.invalidateCache && kind === action.kind && name === action.name;
17985 };
17986 var getEntityRecordsTotalItems2 = forward_resolver_default("getEntityRecords");
17987 var getEntityRecordsTotalPages2 = forward_resolver_default("getEntityRecords");
17988 var getCurrentTheme2 = () => async ({ dispatch, resolveSelect }) => {
17989 const activeThemes = await resolveSelect.getEntityRecords(
17990 "root",
17991 "theme",
17992 { status: "active" }
17993 );
17994 dispatch.receiveCurrentTheme(activeThemes[0]);
17995 };
17996 var getThemeSupports2 = forward_resolver_default("getCurrentTheme");
17997 var getEmbedPreview2 = (url) => async ({ dispatch }) => {
17998 try {
17999 const embedProxyResponse = await (0, import_api_fetch8.default)({
18000 path: (0, import_url7.addQueryArgs)("/oembed/1.0/proxy", { url })
18001 });
18002 dispatch.receiveEmbedPreview(url, embedProxyResponse);
18003 } catch (error) {
18004 dispatch.receiveEmbedPreview(url, false);
18005 }
18006 };
18007 var canUser2 = (requestedAction, resource, id2) => async ({ dispatch, registry, resolveSelect }) => {
18008 if (!ALLOWED_RESOURCE_ACTIONS.includes(requestedAction)) {
18009 throw new Error(`'${requestedAction}' is not a valid action.`);
18010 }
18011 const { hasStartedResolution } = registry.select(STORE_NAME);
18012 for (const relatedAction of ALLOWED_RESOURCE_ACTIONS) {
18013 if (relatedAction === requestedAction) {
18014 continue;
18015 }
18016 const isAlreadyResolving = hasStartedResolution("canUser", [
18017 relatedAction,
18018 resource,
18019 id2
18020 ]);
18021 if (isAlreadyResolving) {
18022 return;
18023 }
18024 }
18025 let resourcePath = null;
18026 if (typeof resource === "object") {
18027 if (!resource.kind || !resource.name) {
18028 throw new Error("The entity resource object is not valid.");
18029 }
18030 const configs = await resolveSelect.getEntitiesConfig(
18031 resource.kind
18032 );
18033 const entityConfig = configs.find(
18034 (config) => config.name === resource.name && config.kind === resource.kind
18035 );
18036 if (!entityConfig) {
18037 return;
18038 }
18039 resourcePath = entityConfig.baseURL + (resource.id ? "/" + resource.id : "");
18040 } else {
18041 resourcePath = `/wp/v2/${resource}` + (id2 ? "/" + id2 : "");
18042 }
18043 let response;
18044 try {
18045 response = await (0, import_api_fetch8.default)({
18046 path: resourcePath,
18047 method: "OPTIONS",
18048 parse: false
18049 });
18050 } catch (error) {
18051 return;
18052 }
18053 const permissions = getUserPermissionsFromAllowHeader(
18054 response.headers?.get("allow")
18055 );
18056 registry.batch(() => {
18057 for (const action of ALLOWED_RESOURCE_ACTIONS) {
18058 const key = getUserPermissionCacheKey(action, resource, id2);
18059 dispatch.receiveUserPermission(key, permissions[action]);
18060 if (action !== requestedAction) {
18061 dispatch.finishResolution("canUser", [
18062 action,
18063 resource,
18064 id2
18065 ]);
18066 }
18067 }
18068 });
18069 };
18070 var canUserEditEntityRecord2 = (kind, name, recordId) => async ({ dispatch }) => {
18071 await dispatch(canUser2("update", { kind, name, id: recordId }));
18072 };
18073 var getAutosaves2 = (postType, postId) => async ({ dispatch, resolveSelect }) => {
18074 const {
18075 rest_base: restBase,
18076 rest_namespace: restNamespace = "wp/v2",
18077 supports
18078 } = await resolveSelect.getPostType(postType);
18079 if (!supports?.autosave) {
18080 return;
18081 }
18082 const autosaves2 = await (0, import_api_fetch8.default)({
18083 path: `/${restNamespace}/${restBase}/${postId}/autosaves?context=edit`
18084 });
18085 if (autosaves2 && autosaves2.length) {
18086 dispatch.receiveAutosaves(postId, autosaves2);
18087 }
18088 };
18089 var getAutosave2 = (postType, postId) => async ({ resolveSelect }) => {
18090 await resolveSelect.getAutosaves(postType, postId);
18091 };
18092 var __experimentalGetCurrentGlobalStylesId2 = () => async ({ dispatch, resolveSelect }) => {
18093 const activeThemes = await resolveSelect.getEntityRecords(
18094 "root",
18095 "theme",
18096 { status: "active" }
18097 );
18098 const globalStylesURL = activeThemes?.[0]?._links?.["wp:user-global-styles"]?.[0]?.href;
18099 if (!globalStylesURL) {
18100 return;
18101 }
18102 const matches = globalStylesURL.match(/\/(\d+)(?:\?|$)/);
18103 const id2 = matches ? Number(matches[1]) : null;
18104 if (id2) {
18105 dispatch.__experimentalReceiveCurrentGlobalStylesId(id2);
18106 }
18107 };
18108 var __experimentalGetCurrentThemeBaseGlobalStyles2 = () => async ({ resolveSelect, dispatch }) => {
18109 const currentTheme2 = await resolveSelect.getCurrentTheme();
18110 const themeGlobalStyles = await (0, import_api_fetch8.default)({
18111 path: `/wp/v2/global-styles/themes/${currentTheme2.stylesheet}?context=view`
18112 });
18113 dispatch.__experimentalReceiveThemeBaseGlobalStyles(
18114 currentTheme2.stylesheet,
18115 themeGlobalStyles
18116 );
18117 };
18118 var __experimentalGetCurrentThemeGlobalStylesVariations2 = () => async ({ resolveSelect, dispatch }) => {
18119 const currentTheme2 = await resolveSelect.getCurrentTheme();
18120 const variations = await (0, import_api_fetch8.default)({
18121 path: `/wp/v2/global-styles/themes/${currentTheme2.stylesheet}/variations?context=view`
18122 });
18123 dispatch.__experimentalReceiveThemeGlobalStyleVariations(
18124 currentTheme2.stylesheet,
18125 variations
18126 );
18127 };
18128 var getCurrentThemeGlobalStylesRevisions2 = () => async ({ resolveSelect, dispatch }) => {
18129 const globalStylesId = await resolveSelect.__experimentalGetCurrentGlobalStylesId();
18130 const record = globalStylesId ? await resolveSelect.getEntityRecord(
18131 "root",
18132 "globalStyles",
18133 globalStylesId
18134 ) : void 0;
18135 const revisionsURL = record?._links?.["version-history"]?.[0]?.href;
18136 if (revisionsURL) {
18137 const resetRevisions = await (0, import_api_fetch8.default)({
18138 url: revisionsURL
18139 });
18140 const revisions = resetRevisions?.map(
18141 (revision) => Object.fromEntries(
18142 Object.entries(revision).map(([key, value]) => [
18143 camelCase(key),
18144 value
18145 ])
18146 )
18147 );
18148 dispatch.receiveThemeGlobalStyleRevisions(
18149 globalStylesId,
18150 revisions
18151 );
18152 }
18153 };
18154 getCurrentThemeGlobalStylesRevisions2.shouldInvalidate = (action) => {
18155 return action.type === "SAVE_ENTITY_RECORD_FINISH" && action.kind === "root" && !action.error && action.name === "globalStyles";
18156 };
18157 var getBlockPatterns2 = () => async ({ dispatch }) => {
18158 const patterns = await fetchBlockPatterns();
18159 dispatch({ type: "RECEIVE_BLOCK_PATTERNS", patterns });
18160 };
18161 var getBlockPatternCategories2 = () => async ({ dispatch }) => {
18162 const categories = await (0, import_api_fetch8.default)({
18163 path: "/wp/v2/block-patterns/categories"
18164 });
18165 dispatch({ type: "RECEIVE_BLOCK_PATTERN_CATEGORIES", categories });
18166 };
18167 var getUserPatternCategories2 = () => async ({ dispatch, resolveSelect }) => {
18168 const patternCategories = await resolveSelect.getEntityRecords(
18169 "taxonomy",
18170 "wp_pattern_category",
18171 {
18172 per_page: -1,
18173 _fields: "id,name,description,slug",
18174 context: "view"
18175 }
18176 );
18177 const mappedPatternCategories = patternCategories?.map((userCategory) => ({
18178 ...userCategory,
18179 label: (0, import_html_entities2.decodeEntities)(userCategory.name),
18180 name: userCategory.slug
18181 })) || [];
18182 dispatch({
18183 type: "RECEIVE_USER_PATTERN_CATEGORIES",
18184 patternCategories: mappedPatternCategories
18185 });
18186 };
18187 var getNavigationFallbackId2 = () => async ({ dispatch, select, registry }) => {
18188 const fallback = await (0, import_api_fetch8.default)({
18189 path: (0, import_url7.addQueryArgs)("/wp-block-editor/v1/navigation-fallback", {
18190 _embed: true
18191 })
18192 });
18193 const record = fallback?._embedded?.self;
18194 registry.batch(() => {
18195 dispatch.receiveNavigationFallbackId(fallback?.id);
18196 if (!record) {
18197 return;
18198 }
18199 const existingFallbackEntityRecord = select.getEntityRecord(
18200 "postType",
18201 "wp_navigation",
18202 fallback.id
18203 );
18204 const invalidateNavigationQueries = !existingFallbackEntityRecord;
18205 dispatch.receiveEntityRecords(
18206 "postType",
18207 "wp_navigation",
18208 record,
18209 void 0,
18210 invalidateNavigationQueries
18211 );
18212 dispatch.finishResolution("getEntityRecord", [
18213 "postType",
18214 "wp_navigation",
18215 fallback.id
18216 ]);
18217 });
18218 };
18219 var getDefaultTemplateId2 = (query) => async ({ dispatch, registry, resolveSelect }) => {
18220 const template = await (0, import_api_fetch8.default)({
18221 path: (0, import_url7.addQueryArgs)("/wp/v2/templates/lookup", query)
18222 });
18223 await resolveSelect.getEntitiesConfig("postType");
18224 const id2 = window?.__experimentalTemplateActivate ? template?.wp_id || template?.id : template?.id;
18225 if (id2) {
18226 template.id = id2;
18227 registry.batch(() => {
18228 dispatch.receiveDefaultTemplateId(query, id2);
18229 dispatch.receiveEntityRecords("postType", template.type, [
18230 template
18231 ]);
18232 dispatch.finishResolution("getEntityRecord", [
18233 "postType",
18234 template.type,
18235 id2
18236 ]);
18237 });
18238 }
18239 };
18240 getDefaultTemplateId2.shouldInvalidate = (action) => {
18241 return action.type === "RECEIVE_ITEMS" && action.kind === "root" && action.name === "site";
18242 };
18243 var getRevisions2 = (kind, name, recordKey, query = {}) => async ({ dispatch, registry, resolveSelect }) => {
18244 const configs = await resolveSelect.getEntitiesConfig(kind);
18245 const entityConfig = configs.find(
18246 (config) => config.name === name && config.kind === kind
18247 );
18248 if (!entityConfig) {
18249 return;
18250 }
18251 if (query._fields) {
18252 query = {
18253 ...query,
18254 _fields: [
18255 .../* @__PURE__ */ new Set([
18256 ...get_normalized_comma_separable_default(query._fields) || [],
18257 entityConfig.revisionKey || DEFAULT_ENTITY_KEY
18258 ])
18259 ].join()
18260 };
18261 }
18262 const path = (0, import_url7.addQueryArgs)(
18263 entityConfig.getRevisionsUrl(recordKey),
18264 query
18265 );
18266 let records, response;
18267 const meta = {};
18268 const isPaginated = entityConfig.supportsPagination && query.per_page !== -1;
18269 try {
18270 response = await (0, import_api_fetch8.default)({ path, parse: !isPaginated });
18271 } catch (error) {
18272 return;
18273 }
18274 if (response) {
18275 if (isPaginated) {
18276 records = Object.values(await response.json());
18277 meta.totalItems = parseInt(
18278 response.headers.get("X-WP-Total")
18279 );
18280 } else {
18281 records = Object.values(response);
18282 }
18283 if (query._fields) {
18284 records = records.map((record) => {
18285 query._fields.split(",").forEach((field) => {
18286 if (!record.hasOwnProperty(field)) {
18287 record[field] = void 0;
18288 }
18289 });
18290 return record;
18291 });
18292 }
18293 registry.batch(() => {
18294 dispatch.receiveRevisions(
18295 kind,
18296 name,
18297 recordKey,
18298 records,
18299 query,
18300 false,
18301 meta
18302 );
18303 if (!query?._fields && !query.context) {
18304 const key = entityConfig.key || DEFAULT_ENTITY_KEY;
18305 const resolutionsArgs = records.filter((record) => record[key]).map((record) => [
18306 kind,
18307 name,
18308 recordKey,
18309 record[key]
18310 ]);
18311 dispatch.finishResolutions(
18312 "getRevision",
18313 resolutionsArgs
18314 );
18315 }
18316 });
18317 }
18318 };
18319 getRevisions2.shouldInvalidate = (action, kind, name, recordKey) => action.type === "SAVE_ENTITY_RECORD_FINISH" && name === action.name && kind === action.kind && !action.error && recordKey === action.recordId;
18320 var getRevision2 = (kind, name, recordKey, revisionKey, query) => async ({ dispatch, resolveSelect }) => {
18321 const configs = await resolveSelect.getEntitiesConfig(kind);
18322 const entityConfig = configs.find(
18323 (config) => config.name === name && config.kind === kind
18324 );
18325 if (!entityConfig) {
18326 return;
18327 }
18328 if (query !== void 0 && query._fields) {
18329 query = {
18330 ...query,
18331 _fields: [
18332 .../* @__PURE__ */ new Set([
18333 ...get_normalized_comma_separable_default(query._fields) || [],
18334 entityConfig.revisionKey || DEFAULT_ENTITY_KEY
18335 ])
18336 ].join()
18337 };
18338 }
18339 const path = (0, import_url7.addQueryArgs)(
18340 entityConfig.getRevisionsUrl(recordKey, revisionKey),
18341 query
18342 );
18343 let record;
18344 try {
18345 record = await (0, import_api_fetch8.default)({ path });
18346 } catch (error) {
18347 return;
18348 }
18349 if (record) {
18350 dispatch.receiveRevisions(kind, name, recordKey, record, query);
18351 }
18352 };
18353 var getRegisteredPostMeta2 = (postType) => async ({ dispatch, resolveSelect }) => {
18354 let options;
18355 try {
18356 const {
18357 rest_namespace: restNamespace = "wp/v2",
18358 rest_base: restBase
18359 } = await resolveSelect.getPostType(postType) || {};
18360 options = await (0, import_api_fetch8.default)({
18361 path: `${restNamespace}/${restBase}/?context=edit`,
18362 method: "OPTIONS"
18363 });
18364 } catch (error) {
18365 return;
18366 }
18367 if (options) {
18368 dispatch.receiveRegisteredPostMeta(
18369 postType,
18370 options?.schema?.properties?.meta?.properties
18371 );
18372 }
18373 };
18374 var getEntitiesConfig2 = (kind) => async ({ dispatch }) => {
18375 const loader = additionalEntityConfigLoaders.find(
18376 (l) => l.kind === kind
18377 );
18378 if (!loader) {
18379 return;
18380 }
18381 try {
18382 const configs = await loader.loadEntities();
18383 if (!configs.length) {
18384 return;
18385 }
18386 dispatch.addEntities(configs);
18387 } catch {
18388 }
18389 };
18390 var getEditorSettings2 = () => async ({ dispatch }) => {
18391 const settings = await (0, import_api_fetch8.default)({
18392 path: "/wp-block-editor/v1/settings"
18393 });
18394 dispatch.receiveEditorSettings(settings);
18395 };
18396 var getEditorAssets2 = () => async ({ dispatch }) => {
18397 const assets = await (0, import_api_fetch8.default)({
18398 path: "/wp-block-editor/v1/assets"
18399 });
18400 dispatch.receiveEditorAssets(assets);
18401 };
18402
18403 // packages/core-data/build-module/locks/utils.js
18404 function deepCopyLocksTreePath(tree, path) {
18405 const newTree = { ...tree };
18406 let currentNode = newTree;
18407 for (const branchName of path) {
18408 currentNode.children = {
18409 ...currentNode.children,
18410 [branchName]: {
18411 locks: [],
18412 children: {},
18413 ...currentNode.children[branchName]
18414 }
18415 };
18416 currentNode = currentNode.children[branchName];
18417 }
18418 return newTree;
18419 }
18420 function getNode(tree, path) {
18421 let currentNode = tree;
18422 for (const branchName of path) {
18423 const nextNode = currentNode.children[branchName];
18424 if (!nextNode) {
18425 return null;
18426 }
18427 currentNode = nextNode;
18428 }
18429 return currentNode;
18430 }
18431 function* iteratePath(tree, path) {
18432 let currentNode = tree;
18433 yield currentNode;
18434 for (const branchName of path) {
18435 const nextNode = currentNode.children[branchName];
18436 if (!nextNode) {
18437 break;
18438 }
18439 yield nextNode;
18440 currentNode = nextNode;
18441 }
18442 }
18443 function* iterateDescendants(node) {
18444 const stack = Object.values(node.children);
18445 while (stack.length) {
18446 const childNode = stack.pop();
18447 yield childNode;
18448 stack.push(...Object.values(childNode.children));
18449 }
18450 }
18451 function hasConflictingLock({ exclusive }, locks2) {
18452 if (exclusive && locks2.length) {
18453 return true;
18454 }
18455 if (!exclusive && locks2.filter((lock2) => lock2.exclusive).length) {
18456 return true;
18457 }
18458 return false;
18459 }
18460
18461 // packages/core-data/build-module/locks/reducer.js
18462 var DEFAULT_STATE = {
18463 requests: [],
18464 tree: {
18465 locks: [],
18466 children: {}
18467 }
18468 };
18469 function locks(state = DEFAULT_STATE, action) {
18470 switch (action.type) {
18471 case "ENQUEUE_LOCK_REQUEST": {
18472 const { request } = action;
18473 return {
18474 ...state,
18475 requests: [request, ...state.requests]
18476 };
18477 }
18478 case "GRANT_LOCK_REQUEST": {
18479 const { lock: lock2, request } = action;
18480 const { store: store2, path } = request;
18481 const storePath = [store2, ...path];
18482 const newTree = deepCopyLocksTreePath(state.tree, storePath);
18483 const node = getNode(newTree, storePath);
18484 node.locks = [...node.locks, lock2];
18485 return {
18486 ...state,
18487 requests: state.requests.filter((r) => r !== request),
18488 tree: newTree
18489 };
18490 }
18491 case "RELEASE_LOCK": {
18492 const { lock: lock2 } = action;
18493 const storePath = [lock2.store, ...lock2.path];
18494 const newTree = deepCopyLocksTreePath(state.tree, storePath);
18495 const node = getNode(newTree, storePath);
18496 node.locks = node.locks.filter((l) => l !== lock2);
18497 return {
18498 ...state,
18499 tree: newTree
18500 };
18501 }
18502 }
18503 return state;
18504 }
18505
18506 // packages/core-data/build-module/locks/selectors.js
18507 function getPendingLockRequests(state) {
18508 return state.requests;
18509 }
18510 function isLockAvailable(state, store2, path, { exclusive }) {
18511 const storePath = [store2, ...path];
18512 const locks2 = state.tree;
18513 for (const node2 of iteratePath(locks2, storePath)) {
18514 if (hasConflictingLock({ exclusive }, node2.locks)) {
18515 return false;
18516 }
18517 }
18518 const node = getNode(locks2, storePath);
18519 if (!node) {
18520 return true;
18521 }
18522 for (const descendant of iterateDescendants(node)) {
18523 if (hasConflictingLock({ exclusive }, descendant.locks)) {
18524 return false;
18525 }
18526 }
18527 return true;
18528 }
18529
18530 // packages/core-data/build-module/locks/engine.js
18531 function createLocks() {
18532 let state = locks(void 0, { type: "@@INIT" });
18533 function processPendingLockRequests() {
18534 for (const request of getPendingLockRequests(state)) {
18535 const { store: store2, path, exclusive, notifyAcquired } = request;
18536 if (isLockAvailable(state, store2, path, { exclusive })) {
18537 const lock2 = { store: store2, path, exclusive };
18538 state = locks(state, {
18539 type: "GRANT_LOCK_REQUEST",
18540 lock: lock2,
18541 request
18542 });
18543 notifyAcquired(lock2);
18544 }
18545 }
18546 }
18547 function acquire(store2, path, exclusive) {
18548 return new Promise((resolve2) => {
18549 state = locks(state, {
18550 type: "ENQUEUE_LOCK_REQUEST",
18551 request: { store: store2, path, exclusive, notifyAcquired: resolve2 }
18552 });
18553 processPendingLockRequests();
18554 });
18555 }
18556 function release(lock2) {
18557 state = locks(state, {
18558 type: "RELEASE_LOCK",
18559 lock: lock2
18560 });
18561 processPendingLockRequests();
18562 }
18563 return { acquire, release };
18564 }
18565
18566 // packages/core-data/build-module/locks/actions.js
18567 function createLocksActions() {
18568 const locks2 = createLocks();
18569 function __unstableAcquireStoreLock(store2, path, { exclusive }) {
18570 return () => locks2.acquire(store2, path, exclusive);
18571 }
18572 function __unstableReleaseStoreLock(lock2) {
18573 return () => locks2.release(lock2);
18574 }
18575 return { __unstableAcquireStoreLock, __unstableReleaseStoreLock };
18576 }
18577
18578 // packages/core-data/build-module/dynamic-entities.js
18579 var dynamicActions;
18580 var dynamicSelectors;
18581
18582 // packages/core-data/build-module/entity-provider.js
18583 var import_element2 = __toESM(require_element());
18584
18585 // packages/core-data/build-module/entity-context.js
18586 var import_element = __toESM(require_element());
18587 var EntityContext = (0, import_element.createContext)({});
18588 EntityContext.displayName = "EntityContext";
18589
18590 // packages/core-data/build-module/entity-provider.js
18591 var import_jsx_runtime = __toESM(require_jsx_runtime());
18592 function EntityProvider({ kind, type: name, id: id2, children }) {
18593 const parent = (0, import_element2.useContext)(EntityContext);
18594 const childContext = (0, import_element2.useMemo)(
18595 () => ({
18596 ...parent,
18597 [kind]: {
18598 ...parent?.[kind],
18599 [name]: id2
18600 }
18601 }),
18602 [parent, kind, name, id2]
18603 );
18604 return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(EntityContext.Provider, { value: childContext, children });
18605 }
18606
18607 // packages/core-data/build-module/hooks/use-entity-record.js
18608 var import_data7 = __toESM(require_data());
18609 var import_deprecated4 = __toESM(require_deprecated());
18610 var import_element3 = __toESM(require_element());
18611
18612 // packages/core-data/build-module/hooks/use-query-select.js
18613 var import_data6 = __toESM(require_data());
18614
18615 // node_modules/memize/dist/index.js
18616 function memize(fn, options) {
18617 var size = 0;
18618 var head;
18619 var tail;
18620 options = options || {};
18621 function memoized() {
18622 var node = head, len = arguments.length, args2, i;
18623 searchCache: while (node) {
18624 if (node.args.length !== arguments.length) {
18625 node = node.next;
18626 continue;
18627 }
18628 for (i = 0; i < len; i++) {
18629 if (node.args[i] !== arguments[i]) {
18630 node = node.next;
18631 continue searchCache;
18632 }
18633 }
18634 if (node !== head) {
18635 if (node === tail) {
18636 tail = node.prev;
18637 }
18638 node.prev.next = node.next;
18639 if (node.next) {
18640 node.next.prev = node.prev;
18641 }
18642 node.next = head;
18643 node.prev = null;
18644 head.prev = node;
18645 head = node;
18646 }
18647 return node.val;
18648 }
18649 args2 = new Array(len);
18650 for (i = 0; i < len; i++) {
18651 args2[i] = arguments[i];
18652 }
18653 node = {
18654 args: args2,
18655 // Generate the result from original function
18656 val: fn.apply(null, args2)
18657 };
18658 if (head) {
18659 head.prev = node;
18660 node.next = head;
18661 } else {
18662 tail = node;
18663 }
18664 if (size === /** @type {MemizeOptions} */
18665 options.maxSize) {
18666 tail = /** @type {MemizeCacheNode} */
18667 tail.prev;
18668 tail.next = null;
18669 } else {
18670 size++;
18671 }
18672 head = node;
18673 return node.val;
18674 }
18675 memoized.clear = function() {
18676 head = null;
18677 tail = null;
18678 size = 0;
18679 };
18680 return memoized;
18681 }
18682
18683 // packages/core-data/build-module/hooks/memoize.js
18684 var memoize_default = memize;
18685
18686 // packages/core-data/build-module/hooks/constants.js
18687 var Status = /* @__PURE__ */ ((Status2) => {
18688 Status2["Idle"] = "IDLE";
18689 Status2["Resolving"] = "RESOLVING";
18690 Status2["Error"] = "ERROR";
18691 Status2["Success"] = "SUCCESS";
18692 return Status2;
18693 })(Status || {});
18694
18695 // packages/core-data/build-module/hooks/use-query-select.js
18696 var META_SELECTORS = [
18697 "getIsResolving",
18698 "hasStartedResolution",
18699 "hasFinishedResolution",
18700 "isResolving",
18701 "getCachedResolvers"
18702 ];
18703 function useQuerySelect(mapQuerySelect, deps) {
18704 return (0, import_data6.useSelect)((select, registry) => {
18705 const resolve2 = (store2) => enrichSelectors(select(store2));
18706 return mapQuerySelect(resolve2, registry);
18707 }, deps);
18708 }
18709 var enrichSelectors = memoize_default(((selectors) => {
18710 const resolvers = {};
18711 for (const selectorName in selectors) {
18712 if (META_SELECTORS.includes(selectorName)) {
18713 continue;
18714 }
18715 Object.defineProperty(resolvers, selectorName, {
18716 get: () => (...args2) => {
18717 const data = selectors[selectorName](...args2);
18718 const resolutionStatus = selectors.getResolutionState(
18719 selectorName,
18720 args2
18721 )?.status;
18722 let status;
18723 switch (resolutionStatus) {
18724 case "resolving":
18725 status = Status.Resolving;
18726 break;
18727 case "finished":
18728 status = Status.Success;
18729 break;
18730 case "error":
18731 status = Status.Error;
18732 break;
18733 case void 0:
18734 status = Status.Idle;
18735 break;
18736 }
18737 return {
18738 data,
18739 status,
18740 isResolving: status === Status.Resolving,
18741 hasStarted: status !== Status.Idle,
18742 hasResolved: status === Status.Success || status === Status.Error
18743 };
18744 }
18745 });
18746 }
18747 return resolvers;
18748 }));
18749
18750 // packages/core-data/build-module/hooks/use-entity-record.js
18751 var EMPTY_OBJECT2 = {};
18752 function useEntityRecord(kind, name, recordId, options = { enabled: true }) {
18753 const { editEntityRecord: editEntityRecord2, saveEditedEntityRecord: saveEditedEntityRecord2 } = (0, import_data7.useDispatch)(store);
18754 const mutations = (0, import_element3.useMemo)(
18755 () => ({
18756 edit: (record2, editOptions = {}) => editEntityRecord2(kind, name, recordId, record2, editOptions),
18757 save: (saveOptions = {}) => saveEditedEntityRecord2(kind, name, recordId, {
18758 throwOnError: true,
18759 ...saveOptions
18760 })
18761 }),
18762 [editEntityRecord2, kind, name, recordId, saveEditedEntityRecord2]
18763 );
18764 const { editedRecord, hasEdits, edits } = (0, import_data7.useSelect)(
18765 (select) => {
18766 if (!options.enabled) {
18767 return {
18768 editedRecord: EMPTY_OBJECT2,
18769 hasEdits: false,
18770 edits: EMPTY_OBJECT2
18771 };
18772 }
18773 return {
18774 editedRecord: select(store).getEditedEntityRecord(
18775 kind,
18776 name,
18777 recordId
18778 ),
18779 hasEdits: select(store).hasEditsForEntityRecord(
18780 kind,
18781 name,
18782 recordId
18783 ),
18784 edits: select(store).getEntityRecordNonTransientEdits(
18785 kind,
18786 name,
18787 recordId
18788 )
18789 };
18790 },
18791 [kind, name, recordId, options.enabled]
18792 );
18793 const { data: record, ...querySelectRest } = useQuerySelect(
18794 (query) => {
18795 if (!options.enabled) {
18796 return {
18797 data: null
18798 };
18799 }
18800 return query(store).getEntityRecord(kind, name, recordId);
18801 },
18802 [kind, name, recordId, options.enabled]
18803 );
18804 return {
18805 record,
18806 editedRecord,
18807 hasEdits,
18808 edits,
18809 ...querySelectRest,
18810 ...mutations
18811 };
18812 }
18813 function __experimentalUseEntityRecord(kind, name, recordId, options) {
18814 (0, import_deprecated4.default)(`wp.data.__experimentalUseEntityRecord`, {
18815 alternative: "wp.data.useEntityRecord",
18816 since: "6.1"
18817 });
18818 return useEntityRecord(kind, name, recordId, options);
18819 }
18820
18821 // packages/core-data/build-module/hooks/use-entity-records.js
18822 var import_url8 = __toESM(require_url());
18823 var import_deprecated5 = __toESM(require_deprecated());
18824 var import_data8 = __toESM(require_data());
18825 var import_element4 = __toESM(require_element());
18826 var EMPTY_ARRAY = [];
18827 function useEntityRecords(kind, name, queryArgs = {}, options = { enabled: true }) {
18828 const queryAsString = (0, import_url8.addQueryArgs)("", queryArgs);
18829 const { data: records, ...rest } = useQuerySelect(
18830 (query) => {
18831 if (!options.enabled) {
18832 return {
18833 // Avoiding returning a new reference on every execution.
18834 data: EMPTY_ARRAY
18835 };
18836 }
18837 return query(store).getEntityRecords(kind, name, queryArgs);
18838 },
18839 [kind, name, queryAsString, options.enabled]
18840 );
18841 const { totalItems, totalPages } = (0, import_data8.useSelect)(
18842 (select) => {
18843 if (!options.enabled) {
18844 return {
18845 totalItems: null,
18846 totalPages: null
18847 };
18848 }
18849 return {
18850 totalItems: select(store).getEntityRecordsTotalItems(
18851 kind,
18852 name,
18853 queryArgs
18854 ),
18855 totalPages: select(store).getEntityRecordsTotalPages(
18856 kind,
18857 name,
18858 queryArgs
18859 )
18860 };
18861 },
18862 [kind, name, queryAsString, options.enabled]
18863 );
18864 return {
18865 records,
18866 totalItems,
18867 totalPages,
18868 ...rest
18869 };
18870 }
18871 function __experimentalUseEntityRecords(kind, name, queryArgs, options) {
18872 (0, import_deprecated5.default)(`wp.data.__experimentalUseEntityRecords`, {
18873 alternative: "wp.data.useEntityRecords",
18874 since: "6.1"
18875 });
18876 return useEntityRecords(kind, name, queryArgs, options);
18877 }
18878 function useEntityRecordsWithPermissions(kind, name, queryArgs = {}, options = { enabled: true }) {
18879 const entityConfig = (0, import_data8.useSelect)(
18880 (select) => select(store).getEntityConfig(kind, name),
18881 [kind, name]
18882 );
18883 const { records: data, ...ret } = useEntityRecords(
18884 kind,
18885 name,
18886 {
18887 ...queryArgs,
18888 // If _fields is provided, we need to include _links in the request for permission caching to work.
18889 ...queryArgs._fields ? {
18890 _fields: [
18891 .../* @__PURE__ */ new Set([
18892 ...get_normalized_comma_separable_default(
18893 queryArgs._fields
18894 ) || [],
18895 "_links"
18896 ])
18897 ].join()
18898 } : {}
18899 },
18900 options
18901 );
18902 const ids = (0, import_element4.useMemo)(
18903 () => data?.map(
18904 // @ts-ignore
18905 (record) => record[entityConfig?.key ?? "id"]
18906 ) ?? [],
18907 [data, entityConfig?.key]
18908 );
18909 const permissions = (0, import_data8.useSelect)(
18910 (select) => {
18911 const { getEntityRecordsPermissions: getEntityRecordsPermissions2 } = unlock(
18912 select(store)
18913 );
18914 return getEntityRecordsPermissions2(kind, name, ids);
18915 },
18916 [ids, kind, name]
18917 );
18918 const dataWithPermissions = (0, import_element4.useMemo)(
18919 () => data?.map((record, index) => ({
18920 // @ts-ignore
18921 ...record,
18922 permissions: permissions[index]
18923 })) ?? [],
18924 [data, permissions]
18925 );
18926 return { records: dataWithPermissions, ...ret };
18927 }
18928
18929 // packages/core-data/build-module/hooks/use-resource-permissions.js
18930 var import_deprecated6 = __toESM(require_deprecated());
18931 var import_warning = __toESM(require_warning());
18932 function useResourcePermissions(resource, id2) {
18933 const isEntity = typeof resource === "object";
18934 const resourceAsString = isEntity ? JSON.stringify(resource) : resource;
18935 if (isEntity && typeof id2 !== "undefined") {
18936 (0, import_warning.default)(
18937 `When 'resource' is an entity object, passing 'id' as a separate argument isn't supported.`
18938 );
18939 }
18940 return useQuerySelect(
18941 (resolve2) => {
18942 const hasId = isEntity ? !!resource.id : !!id2;
18943 const { canUser: canUser3 } = resolve2(store);
18944 const create8 = canUser3(
18945 "create",
18946 isEntity ? { kind: resource.kind, name: resource.name } : resource
18947 );
18948 if (!hasId) {
18949 const read2 = canUser3("read", resource);
18950 const isResolving2 = create8.isResolving || read2.isResolving;
18951 const hasResolved2 = create8.hasResolved && read2.hasResolved;
18952 let status2 = Status.Idle;
18953 if (isResolving2) {
18954 status2 = Status.Resolving;
18955 } else if (hasResolved2) {
18956 status2 = Status.Success;
18957 }
18958 return {
18959 status: status2,
18960 isResolving: isResolving2,
18961 hasResolved: hasResolved2,
18962 canCreate: create8.hasResolved && create8.data,
18963 canRead: read2.hasResolved && read2.data
18964 };
18965 }
18966 const read = canUser3("read", resource, id2);
18967 const update = canUser3("update", resource, id2);
18968 const _delete = canUser3("delete", resource, id2);
18969 const isResolving = read.isResolving || create8.isResolving || update.isResolving || _delete.isResolving;
18970 const hasResolved = read.hasResolved && create8.hasResolved && update.hasResolved && _delete.hasResolved;
18971 let status = Status.Idle;
18972 if (isResolving) {
18973 status = Status.Resolving;
18974 } else if (hasResolved) {
18975 status = Status.Success;
18976 }
18977 return {
18978 status,
18979 isResolving,
18980 hasResolved,
18981 canRead: hasResolved && read.data,
18982 canCreate: hasResolved && create8.data,
18983 canUpdate: hasResolved && update.data,
18984 canDelete: hasResolved && _delete.data
18985 };
18986 },
18987 [resourceAsString, id2]
18988 );
18989 }
18990 var use_resource_permissions_default = useResourcePermissions;
18991 function __experimentalUseResourcePermissions(resource, id2) {
18992 (0, import_deprecated6.default)(`wp.data.__experimentalUseResourcePermissions`, {
18993 alternative: "wp.data.useResourcePermissions",
18994 since: "6.1"
18995 });
18996 return useResourcePermissions(resource, id2);
18997 }
18998
18999 // packages/core-data/build-module/hooks/use-entity-block-editor.js
19000 var import_element6 = __toESM(require_element());
19001 var import_data9 = __toESM(require_data());
19002 var import_blocks4 = __toESM(require_blocks());
19003
19004 // packages/core-data/build-module/hooks/use-entity-id.js
19005 var import_element5 = __toESM(require_element());
19006 function useEntityId(kind, name) {
19007 const context = (0, import_element5.useContext)(EntityContext);
19008 return context?.[kind]?.[name];
19009 }
19010
19011 // packages/core-data/build-module/footnotes/index.js
19012 var import_rich_text2 = __toESM(require_rich_text());
19013
19014 // packages/core-data/build-module/footnotes/get-rich-text-values-cached.js
19015 var import_block_editor = __toESM(require_block_editor());
19016 var unlockedApis;
19017 var cache = /* @__PURE__ */ new WeakMap();
19018 function getRichTextValuesCached(block) {
19019 if (!unlockedApis) {
19020 unlockedApis = unlock(import_block_editor.privateApis);
19021 }
19022 if (!cache.has(block)) {
19023 const values = unlockedApis.getRichTextValues([block]);
19024 cache.set(block, values);
19025 }
19026 return cache.get(block);
19027 }
19028
19029 // packages/core-data/build-module/footnotes/get-footnotes-order.js
19030 var cache2 = /* @__PURE__ */ new WeakMap();
19031 function getBlockFootnotesOrder(block) {
19032 if (!cache2.has(block)) {
19033 const order = [];
19034 for (const value of getRichTextValuesCached(block)) {
19035 if (!value) {
19036 continue;
19037 }
19038 value.replacements.forEach(({ type, attributes }) => {
19039 if (type === "core/footnote") {
19040 order.push(attributes["data-fn"]);
19041 }
19042 });
19043 }
19044 cache2.set(block, order);
19045 }
19046 return cache2.get(block);
19047 }
19048 function getFootnotesOrder(blocks) {
19049 return blocks.flatMap(getBlockFootnotesOrder);
19050 }
19051
19052 // packages/core-data/build-module/footnotes/index.js
19053 var oldFootnotes = {};
19054 function updateFootnotesFromMeta(blocks, meta) {
19055 const output = { blocks };
19056 if (!meta) {
19057 return output;
19058 }
19059 if (meta.footnotes === void 0) {
19060 return output;
19061 }
19062 const newOrder = getFootnotesOrder(blocks);
19063 const footnotes = meta.footnotes ? JSON.parse(meta.footnotes) : [];
19064 const currentOrder = footnotes.map((fn) => fn.id);
19065 if (currentOrder.join("") === newOrder.join("")) {
19066 return output;
19067 }
19068 const newFootnotes = newOrder.map(
19069 (fnId) => footnotes.find((fn) => fn.id === fnId) || oldFootnotes[fnId] || {
19070 id: fnId,
19071 content: ""
19072 }
19073 );
19074 function updateAttributes(attributes) {
19075 if (!attributes || Array.isArray(attributes) || typeof attributes !== "object") {
19076 return attributes;
19077 }
19078 attributes = { ...attributes };
19079 for (const key in attributes) {
19080 const value = attributes[key];
19081 if (Array.isArray(value)) {
19082 attributes[key] = value.map(updateAttributes);
19083 continue;
19084 }
19085 if (typeof value !== "string" && !(value instanceof import_rich_text2.RichTextData)) {
19086 continue;
19087 }
19088 const richTextValue = typeof value === "string" ? import_rich_text2.RichTextData.fromHTMLString(value) : new import_rich_text2.RichTextData(value);
19089 let hasFootnotes = false;
19090 richTextValue.replacements.forEach((replacement) => {
19091 if (replacement.type === "core/footnote") {
19092 const id2 = replacement.attributes["data-fn"];
19093 const index = newOrder.indexOf(id2);
19094 const countValue = (0, import_rich_text2.create)({
19095 html: replacement.innerHTML
19096 });
19097 countValue.text = String(index + 1);
19098 countValue.formats = Array.from(
19099 { length: countValue.text.length },
19100 () => countValue.formats[0]
19101 );
19102 countValue.replacements = Array.from(
19103 { length: countValue.text.length },
19104 () => countValue.replacements[0]
19105 );
19106 replacement.innerHTML = (0, import_rich_text2.toHTMLString)({
19107 value: countValue
19108 });
19109 hasFootnotes = true;
19110 }
19111 });
19112 if (hasFootnotes) {
19113 attributes[key] = typeof value === "string" ? richTextValue.toHTMLString() : richTextValue;
19114 }
19115 }
19116 return attributes;
19117 }
19118 function updateBlocksAttributes(__blocks) {
19119 return __blocks.map((block) => {
19120 return {
19121 ...block,
19122 attributes: updateAttributes(block.attributes),
19123 innerBlocks: updateBlocksAttributes(block.innerBlocks)
19124 };
19125 });
19126 }
19127 const newBlocks = updateBlocksAttributes(blocks);
19128 oldFootnotes = {
19129 ...oldFootnotes,
19130 ...footnotes.reduce((acc, fn) => {
19131 if (!newOrder.includes(fn.id)) {
19132 acc[fn.id] = fn;
19133 }
19134 return acc;
19135 }, {})
19136 };
19137 return {
19138 meta: {
19139 ...meta,
19140 footnotes: JSON.stringify(newFootnotes)
19141 },
19142 blocks: newBlocks
19143 };
19144 }
19145
19146 // packages/core-data/build-module/hooks/use-entity-block-editor.js
19147 var EMPTY_ARRAY2 = [];
19148 var parsedBlocksCache = /* @__PURE__ */ new WeakMap();
19149 function useEntityBlockEditor(kind, name, { id: _id } = {}) {
19150 const providerId = useEntityId(kind, name);
19151 const id2 = _id ?? providerId;
19152 const { getEntityRecord: getEntityRecord3, getEntityRecordEdits: getEntityRecordEdits2 } = (0, import_data9.useSelect)(STORE_NAME);
19153 const { content, editedBlocks, meta } = (0, import_data9.useSelect)(
19154 (select) => {
19155 if (!id2) {
19156 return {};
19157 }
19158 const { getEditedEntityRecord: getEditedEntityRecord3 } = select(STORE_NAME);
19159 const editedRecord = getEditedEntityRecord3(kind, name, id2);
19160 return {
19161 editedBlocks: editedRecord.blocks,
19162 content: editedRecord.content,
19163 meta: editedRecord.meta
19164 };
19165 },
19166 [kind, name, id2]
19167 );
19168 const { __unstableCreateUndoLevel: __unstableCreateUndoLevel2, editEntityRecord: editEntityRecord2 } = (0, import_data9.useDispatch)(STORE_NAME);
19169 const blocks = (0, import_element6.useMemo)(() => {
19170 if (!id2) {
19171 return void 0;
19172 }
19173 if (editedBlocks) {
19174 return editedBlocks;
19175 }
19176 if (!content || typeof content !== "string") {
19177 return EMPTY_ARRAY2;
19178 }
19179 const edits = getEntityRecordEdits2(kind, name, id2);
19180 const isUnedited = !edits || !Object.keys(edits).length;
19181 const cackeKey = isUnedited ? getEntityRecord3(kind, name, id2) : edits;
19182 let _blocks = parsedBlocksCache.get(cackeKey);
19183 if (!_blocks) {
19184 _blocks = (0, import_blocks4.parse)(content);
19185 parsedBlocksCache.set(cackeKey, _blocks);
19186 }
19187 return _blocks;
19188 }, [
19189 kind,
19190 name,
19191 id2,
19192 editedBlocks,
19193 content,
19194 getEntityRecord3,
19195 getEntityRecordEdits2
19196 ]);
19197 const onChange2 = (0, import_element6.useCallback)(
19198 (newBlocks, options) => {
19199 const noChange = blocks === newBlocks;
19200 if (noChange) {
19201 return __unstableCreateUndoLevel2(kind, name, id2);
19202 }
19203 const { selection, ...rest } = options;
19204 const edits = {
19205 selection,
19206 content: ({ blocks: blocksForSerialization = [] }) => (0, import_blocks4.__unstableSerializeAndClean)(blocksForSerialization),
19207 ...updateFootnotesFromMeta(newBlocks, meta)
19208 };
19209 editEntityRecord2(kind, name, id2, edits, {
19210 isCached: false,
19211 ...rest
19212 });
19213 },
19214 [
19215 kind,
19216 name,
19217 id2,
19218 blocks,
19219 meta,
19220 __unstableCreateUndoLevel2,
19221 editEntityRecord2
19222 ]
19223 );
19224 const onInput = (0, import_element6.useCallback)(
19225 (newBlocks, options) => {
19226 const { selection, ...rest } = options;
19227 const footnotesChanges = updateFootnotesFromMeta(newBlocks, meta);
19228 const edits = { selection, ...footnotesChanges };
19229 editEntityRecord2(kind, name, id2, edits, {
19230 isCached: true,
19231 ...rest
19232 });
19233 },
19234 [kind, name, id2, meta, editEntityRecord2]
19235 );
19236 return [blocks, onInput, onChange2];
19237 }
19238
19239 // packages/core-data/build-module/hooks/use-entity-prop.js
19240 var import_element7 = __toESM(require_element());
19241 var import_data10 = __toESM(require_data());
19242 function useEntityProp(kind, name, prop, _id) {
19243 const providerId = useEntityId(kind, name);
19244 const id2 = _id ?? providerId;
19245 const { value, fullValue } = (0, import_data10.useSelect)(
19246 (select) => {
19247 const { getEntityRecord: getEntityRecord3, getEditedEntityRecord: getEditedEntityRecord3 } = select(STORE_NAME);
19248 const record = getEntityRecord3(kind, name, id2);
19249 const editedRecord = getEditedEntityRecord3(kind, name, id2);
19250 return record && editedRecord ? {
19251 value: editedRecord[prop],
19252 fullValue: record[prop]
19253 } : {};
19254 },
19255 [kind, name, id2, prop]
19256 );
19257 const { editEntityRecord: editEntityRecord2 } = (0, import_data10.useDispatch)(STORE_NAME);
19258 const setValue = (0, import_element7.useCallback)(
19259 (newValue) => {
19260 editEntityRecord2(kind, name, id2, {
19261 [prop]: newValue
19262 });
19263 },
19264 [editEntityRecord2, kind, name, id2, prop]
19265 );
19266 return [value, setValue, fullValue];
19267 }
19268
19269 // packages/core-data/build-module/private-apis.js
19270 var privateApis = {};
19271 lock(privateApis, {
19272 useEntityRecordsWithPermissions,
19273 RECEIVE_INTERMEDIATE_RESULTS
19274 });
19275
19276 // packages/core-data/build-module/index.js
19277 var entitiesConfig2 = [
19278 ...rootEntitiesConfig,
19279 ...additionalEntityConfigLoaders.filter((config) => !!config.name)
19280 ];
19281 var entitySelectors = entitiesConfig2.reduce((result, entity2) => {
19282 const { kind, name, plural } = entity2;
19283 const getEntityRecordMethodName = getMethodName(kind, name);
19284 result[getEntityRecordMethodName] = (state, key, query) => {
19285 logEntityDeprecation(kind, name, getEntityRecordMethodName, {
19286 isShorthandSelector: true,
19287 alternativeFunctionName: "getEntityRecord"
19288 });
19289 return getEntityRecord(state, kind, name, key, query);
19290 };
19291 if (plural) {
19292 const getEntityRecordsMethodName = getMethodName(kind, plural, "get");
19293 result[getEntityRecordsMethodName] = (state, query) => {
19294 logEntityDeprecation(kind, name, getEntityRecordsMethodName, {
19295 isShorthandSelector: true,
19296 alternativeFunctionName: "getEntityRecords"
19297 });
19298 return getEntityRecords(state, kind, name, query);
19299 };
19300 }
19301 return result;
19302 }, {});
19303 var entityResolvers = entitiesConfig2.reduce((result, entity2) => {
19304 const { kind, name, plural } = entity2;
19305 const getEntityRecordMethodName = getMethodName(kind, name);
19306 result[getEntityRecordMethodName] = (key, query) => {
19307 logEntityDeprecation(kind, name, getEntityRecordMethodName, {
19308 isShorthandSelector: true,
19309 alternativeFunctionName: "getEntityRecord"
19310 });
19311 return getEntityRecord2(kind, name, key, query);
19312 };
19313 if (plural) {
19314 const getEntityRecordsMethodName = getMethodName(kind, plural, "get");
19315 result[getEntityRecordsMethodName] = (...args2) => {
19316 logEntityDeprecation(kind, plural, getEntityRecordsMethodName, {
19317 isShorthandSelector: true,
19318 alternativeFunctionName: "getEntityRecords"
19319 });
19320 return getEntityRecords2(kind, name, ...args2);
19321 };
19322 result[getEntityRecordsMethodName].shouldInvalidate = (action) => getEntityRecords2.shouldInvalidate(action, kind, name);
19323 }
19324 return result;
19325 }, {});
19326 var entityActions = entitiesConfig2.reduce((result, entity2) => {
19327 const { kind, name } = entity2;
19328 const saveEntityRecordMethodName = getMethodName(kind, name, "save");
19329 result[saveEntityRecordMethodName] = (record, options) => {
19330 logEntityDeprecation(kind, name, saveEntityRecordMethodName, {
19331 isShorthandSelector: true,
19332 alternativeFunctionName: "saveEntityRecord"
19333 });
19334 return saveEntityRecord(kind, name, record, options);
19335 };
19336 const deleteEntityRecordMethodName = getMethodName(kind, name, "delete");
19337 result[deleteEntityRecordMethodName] = (key, query, options) => {
19338 logEntityDeprecation(kind, name, deleteEntityRecordMethodName, {
19339 isShorthandSelector: true,
19340 alternativeFunctionName: "deleteEntityRecord"
19341 });
19342 return deleteEntityRecord(kind, name, key, query, options);
19343 };
19344 return result;
19345 }, {});
19346 var storeConfig = () => ({
19347 reducer: reducer_default2,
19348 actions: {
19349 ...dynamicActions,
19350 ...actions_exports,
19351 ...entityActions,
19352 ...createLocksActions()
19353 },
19354 selectors: {
19355 ...dynamicSelectors,
19356 ...selectors_exports,
19357 ...entitySelectors
19358 },
19359 resolvers: { ...resolvers_exports, ...entityResolvers }
19360 });
19361 var store = (0, import_data11.createReduxStore)(STORE_NAME, storeConfig());
19362 unlock(store).registerPrivateSelectors(private_selectors_exports);
19363 unlock(store).registerPrivateActions(private_actions_exports);
19364 (0, import_data11.register)(store);
19365 return __toCommonJS(index_exports);
19366 })();
19367 /*! Bundled license information:
19368
19369 simple-peer/simplepeer.min.js:
19370 (*!
19371 * The buffer module from node.js, for the browser.
19372 *
19373 * @author Feross Aboukhadijeh <https://feross.org>
19374 * @license MIT
19375 *)
19376 (*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> *)
19377 (*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> *)
19378 (*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> *)
19379 (*! simple-peer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> *)
19380 */
19381 //# sourceMappingURL=index.js.map
19382