UNPKG

alinea

Version:

[![npm](https://img.shields.io/npm/v/alinea.svg)](https://npmjs.org/package/alinea) [![install size](https://packagephobia.com/badge?p=alinea)](https://packagephobia.com/result?p=alinea)

1,812 lines (1,786 loc) 247 kB
import { abs, create, create2, floor, getUnixTime, isNegativeZero, max, methodUnimplemented, min, unexpectedCase } from "./chunk-O6EXLFU2.js"; import { __export } from "./chunk-U5RRZUYZ.js"; // node_modules/yjs/dist/yjs.mjs var yjs_exports = {}; __export(yjs_exports, { AbsolutePosition: () => AbsolutePosition, AbstractConnector: () => AbstractConnector, AbstractStruct: () => AbstractStruct, AbstractType: () => AbstractType, Array: () => YArray, ContentAny: () => ContentAny, ContentBinary: () => ContentBinary, ContentDeleted: () => ContentDeleted, ContentEmbed: () => ContentEmbed, ContentFormat: () => ContentFormat, ContentJSON: () => ContentJSON, ContentString: () => ContentString, ContentType: () => ContentType, Doc: () => Doc, GC: () => GC, ID: () => ID, Item: () => Item, Map: () => YMap, PermanentUserData: () => PermanentUserData, RelativePosition: () => RelativePosition, Snapshot: () => Snapshot, Text: () => YText, Transaction: () => Transaction, UndoManager: () => UndoManager, UpdateEncoderV1: () => UpdateEncoderV1, XmlElement: () => YXmlElement, XmlFragment: () => YXmlFragment, XmlHook: () => YXmlHook, XmlText: () => YXmlText, YArrayEvent: () => YArrayEvent, YEvent: () => YEvent, YMapEvent: () => YMapEvent, YTextEvent: () => YTextEvent, YXmlEvent: () => YXmlEvent, applyUpdate: () => applyUpdate, applyUpdateV2: () => applyUpdateV2, cleanupYTextFormatting: () => cleanupYTextFormatting, compareIDs: () => compareIDs, compareRelativePositions: () => compareRelativePositions, convertUpdateFormatV1ToV2: () => convertUpdateFormatV1ToV2, convertUpdateFormatV2ToV1: () => convertUpdateFormatV2ToV1, createAbsolutePositionFromRelativePosition: () => createAbsolutePositionFromRelativePosition, createDeleteSet: () => createDeleteSet, createDeleteSetFromStructStore: () => createDeleteSetFromStructStore, createDocFromSnapshot: () => createDocFromSnapshot, createID: () => createID, createRelativePositionFromJSON: () => createRelativePositionFromJSON, createRelativePositionFromTypeIndex: () => createRelativePositionFromTypeIndex, createSnapshot: () => createSnapshot, decodeRelativePosition: () => decodeRelativePosition, decodeSnapshot: () => decodeSnapshot, decodeSnapshotV2: () => decodeSnapshotV2, decodeStateVector: () => decodeStateVector, decodeUpdate: () => decodeUpdate, decodeUpdateV2: () => decodeUpdateV2, diffUpdate: () => diffUpdate, diffUpdateV2: () => diffUpdateV2, emptySnapshot: () => emptySnapshot, encodeRelativePosition: () => encodeRelativePosition, encodeSnapshot: () => encodeSnapshot, encodeSnapshotV2: () => encodeSnapshotV2, encodeStateAsUpdate: () => encodeStateAsUpdate, encodeStateAsUpdateV2: () => encodeStateAsUpdateV2, encodeStateVector: () => encodeStateVector, encodeStateVectorFromUpdate: () => encodeStateVectorFromUpdate, encodeStateVectorFromUpdateV2: () => encodeStateVectorFromUpdateV2, equalDeleteSets: () => equalDeleteSets, equalSnapshots: () => equalSnapshots, findIndexSS: () => findIndexSS, findRootTypeKey: () => findRootTypeKey, getItem: () => getItem, getState: () => getState, getTypeChildren: () => getTypeChildren, isDeleted: () => isDeleted, isParentOf: () => isParentOf, iterateDeletedStructs: () => iterateDeletedStructs, logType: () => logType, logUpdate: () => logUpdate, logUpdateV2: () => logUpdateV2, mergeUpdates: () => mergeUpdates, mergeUpdatesV2: () => mergeUpdatesV2, obfuscateUpdate: () => obfuscateUpdate, obfuscateUpdateV2: () => obfuscateUpdateV2, parseUpdateMeta: () => parseUpdateMeta, parseUpdateMetaV2: () => parseUpdateMetaV2, readUpdate: () => readUpdate, readUpdateV2: () => readUpdateV2, relativePositionToJSON: () => relativePositionToJSON, snapshot: () => snapshot, snapshotContainsUpdate: () => snapshotContainsUpdate, transact: () => transact, tryGc: () => tryGc, typeListToArraySnapshot: () => typeListToArraySnapshot, typeMapGetSnapshot: () => typeMapGetSnapshot }); // node_modules/lib0/map.js var create3 = () => /* @__PURE__ */ new Map(); var copy = (m) => { const r = create3(); m.forEach((v, k) => { r.set(k, v); }); return r; }; var setIfUndefined = (map2, key, createT) => { let set = map2.get(key); if (set === void 0) { map2.set(key, set = createT()); } return set; }; var map = (m, f) => { const res = []; for (const [key, value] of m) { res.push(f(value, key)); } return res; }; var any = (m, f) => { for (const [key, value] of m) { if (f(value, key)) { return true; } } return false; }; // node_modules/lib0/set.js var create4 = () => /* @__PURE__ */ new Set(); // node_modules/lib0/array.js var last = (arr) => arr[arr.length - 1]; var appendTo = (dest, src) => { for (let i = 0; i < src.length; i++) { dest.push(src[i]); } }; var from = Array.from; var some = (arr, f) => { for (let i = 0; i < arr.length; i++) { if (f(arr[i], i, arr)) { return true; } } return false; }; var unfold = (len, f) => { const array = new Array(len); for (let i = 0; i < len; i++) { array[i] = f(i, array); } return array; }; var isArray = Array.isArray; // node_modules/lib0/observable.js var Observable = class { constructor() { this._observers = create3(); } /** * @param {N} name * @param {function} f */ on(name, f) { setIfUndefined(this._observers, name, create4).add(f); } /** * @param {N} name * @param {function} f */ once(name, f) { const _f = (...args2) => { this.off(name, _f); f(...args2); }; this.on(name, _f); } /** * @param {N} name * @param {function} f */ off(name, f) { const observers = this._observers.get(name); if (observers !== void 0) { observers.delete(f); if (observers.size === 0) { this._observers.delete(name); } } } /** * Emit a named event. All registered event listeners that listen to the * specified name will receive the event. * * @todo This should catch exceptions * * @param {N} name The event name. * @param {Array<any>} args The arguments that are applied to the event listener. */ emit(name, args2) { return from((this._observers.get(name) || create3()).values()).forEach((f) => f(...args2)); } destroy() { this._observers = create3(); } }; // node_modules/lib0/string.js var fromCharCode = String.fromCharCode; var fromCodePoint = String.fromCodePoint; var toLowerCase = (s) => s.toLowerCase(); var trimLeftRegex = /^\s*/g; var trimLeft = (s) => s.replace(trimLeftRegex, ""); var fromCamelCaseRegex = /([A-Z])/g; var fromCamelCase = (s, separator) => trimLeft(s.replace(fromCamelCaseRegex, (match) => `${separator}${toLowerCase(match)}`)); var _encodeUtf8Polyfill = (str) => { const encodedString = unescape(encodeURIComponent(str)); const len = encodedString.length; const buf = new Uint8Array(len); for (let i = 0; i < len; i++) { buf[i] = /** @type {number} */ encodedString.codePointAt(i); } return buf; }; var utf8TextEncoder = ( /** @type {TextEncoder} */ typeof TextEncoder !== "undefined" ? new TextEncoder() : null ); var _encodeUtf8Native = (str) => utf8TextEncoder.encode(str); var encodeUtf8 = utf8TextEncoder ? _encodeUtf8Native : _encodeUtf8Polyfill; var utf8TextDecoder = typeof TextDecoder === "undefined" ? null : new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }); if (utf8TextDecoder && utf8TextDecoder.decode(new Uint8Array()).length === 1) { utf8TextDecoder = null; } var repeat = (source, n) => unfold(n, () => source).join(""); // node_modules/lib0/conditions.js var undefinedToNull = (v) => v === void 0 ? null : v; // node_modules/lib0/storage.js var VarStoragePolyfill = class { constructor() { this.map = /* @__PURE__ */ new Map(); } /** * @param {string} key * @param {any} newValue */ setItem(key, newValue) { this.map.set(key, newValue); } /** * @param {string} key */ getItem(key) { return this.map.get(key); } }; var _localStorage = new VarStoragePolyfill(); var usePolyfill = true; try { if (typeof localStorage !== "undefined") { _localStorage = localStorage; usePolyfill = false; } } catch (e) { } var varStorage = _localStorage; // node_modules/lib0/object.js var assign = Object.assign; var keys = Object.keys; var forEach = (obj, f) => { for (const key in obj) { f(obj[key], key); } }; var length = (obj) => keys(obj).length; var isEmpty = (obj) => { for (const _k in obj) { return false; } return true; }; var every = (obj, f) => { for (const key in obj) { if (!f(obj[key], key)) { return false; } } return true; }; var hasProperty = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key); var equalFlat = (a, b) => a === b || length(a) === length(b) && every(a, (val, key) => (val !== void 0 || hasProperty(b, key)) && b[key] === val); // node_modules/lib0/function.js var callAll = (fs, args2, i = 0) => { try { for (; i < fs.length; i++) { fs[i](...args2); } } finally { if (i < fs.length) { callAll(fs, args2, i + 1); } } }; var id = (a) => a; var isOneOf = (value, options) => options.includes(value); // node_modules/lib0/environment.js var isNode = typeof process !== "undefined" && process.release && /node|io\.js/.test(process.release.name); var isBrowser = typeof window !== "undefined" && typeof document !== "undefined" && !isNode; var isMac = typeof navigator !== "undefined" ? /Mac/.test(navigator.platform) : false; var params; var args = []; var computeParams = () => { if (params === void 0) { if (isNode) { params = create3(); const pargs = process.argv; let currParamName = null; for (let i = 0; i < pargs.length; i++) { const parg = pargs[i]; if (parg[0] === "-") { if (currParamName !== null) { params.set(currParamName, ""); } currParamName = parg; } else { if (currParamName !== null) { params.set(currParamName, parg); currParamName = null; } else { args.push(parg); } } } if (currParamName !== null) { params.set(currParamName, ""); } } else if (typeof location === "object") { params = create3(); (location.search || "?").slice(1).split("&").forEach((kv) => { if (kv.length !== 0) { const [key, value] = kv.split("="); params.set(`--${fromCamelCase(key, "-")}`, value); params.set(`-${fromCamelCase(key, "-")}`, value); } }); } else { params = create3(); } } return params; }; var hasParam = (name) => computeParams().has(name); var getVariable = (name) => isNode ? undefinedToNull(process.env[name.toUpperCase()]) : undefinedToNull(varStorage.getItem(name)); var hasConf = (name) => hasParam("--" + name) || getVariable(name) !== null; var production = hasConf("production"); var forceColor = isNode && isOneOf(process.env.FORCE_COLOR, ["true", "1", "2"]); var supportsColor = !hasParam("no-colors") && (!isNode || process.stdout.isTTY || forceColor) && (!isNode || hasParam("color") || forceColor || getVariable("COLORTERM") !== null || (getVariable("TERM") || "").includes("color")); // node_modules/lib0/binary.js var BIT1 = 1; var BIT2 = 2; var BIT3 = 4; var BIT4 = 8; var BIT6 = 32; var BIT7 = 64; var BIT8 = 128; var BIT18 = 1 << 17; var BIT19 = 1 << 18; var BIT20 = 1 << 19; var BIT21 = 1 << 20; var BIT22 = 1 << 21; var BIT23 = 1 << 22; var BIT24 = 1 << 23; var BIT25 = 1 << 24; var BIT26 = 1 << 25; var BIT27 = 1 << 26; var BIT28 = 1 << 27; var BIT29 = 1 << 28; var BIT30 = 1 << 29; var BIT31 = 1 << 30; var BIT32 = 1 << 31; var BITS5 = 31; var BITS6 = 63; var BITS7 = 127; var BITS17 = BIT18 - 1; var BITS18 = BIT19 - 1; var BITS19 = BIT20 - 1; var BITS20 = BIT21 - 1; var BITS21 = BIT22 - 1; var BITS22 = BIT23 - 1; var BITS23 = BIT24 - 1; var BITS24 = BIT25 - 1; var BITS25 = BIT26 - 1; var BITS26 = BIT27 - 1; var BITS27 = BIT28 - 1; var BITS28 = BIT29 - 1; var BITS29 = BIT30 - 1; var BITS30 = BIT31 - 1; var BITS31 = 2147483647; // node_modules/lib0/number.js var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER; var MIN_SAFE_INTEGER = Number.MIN_SAFE_INTEGER; var LOWEST_INT32 = 1 << 31; var isInteger = Number.isInteger || ((num) => typeof num === "number" && isFinite(num) && floor(num) === num); var isNaN = Number.isNaN; var parseInt = Number.parseInt; // node_modules/lib0/decoding.js var errorUnexpectedEndOfArray = create("Unexpected end of array"); var errorIntegerOutOfRange = create("Integer out of Range"); var Decoder = class { /** * @param {Uint8Array} uint8Array Binary data to decode */ constructor(uint8Array) { this.arr = uint8Array; this.pos = 0; } }; var createDecoder = (uint8Array) => new Decoder(uint8Array); var hasContent = (decoder) => decoder.pos !== decoder.arr.length; var readUint8Array = (decoder, len) => { const view = createUint8ArrayViewFromArrayBuffer(decoder.arr.buffer, decoder.pos + decoder.arr.byteOffset, len); decoder.pos += len; return view; }; var readVarUint8Array = (decoder) => readUint8Array(decoder, readVarUint(decoder)); var readUint8 = (decoder) => decoder.arr[decoder.pos++]; var readVarUint = (decoder) => { let num = 0; let mult = 1; const len = decoder.arr.length; while (decoder.pos < len) { const r = decoder.arr[decoder.pos++]; num = num + (r & BITS7) * mult; mult *= 128; if (r < BIT8) { return num; } if (num > MAX_SAFE_INTEGER) { throw errorIntegerOutOfRange; } } throw errorUnexpectedEndOfArray; }; var readVarInt = (decoder) => { let r = decoder.arr[decoder.pos++]; let num = r & BITS6; let mult = 64; const sign = (r & BIT7) > 0 ? -1 : 1; if ((r & BIT8) === 0) { return sign * num; } const len = decoder.arr.length; while (decoder.pos < len) { r = decoder.arr[decoder.pos++]; num = num + (r & BITS7) * mult; mult *= 128; if (r < BIT8) { return sign * num; } if (num > MAX_SAFE_INTEGER) { throw errorIntegerOutOfRange; } } throw errorUnexpectedEndOfArray; }; var _readVarStringPolyfill = (decoder) => { let remainingLen = readVarUint(decoder); if (remainingLen === 0) { return ""; } else { let encodedString = String.fromCodePoint(readUint8(decoder)); if (--remainingLen < 100) { while (remainingLen--) { encodedString += String.fromCodePoint(readUint8(decoder)); } } else { while (remainingLen > 0) { const nextLen = remainingLen < 1e4 ? remainingLen : 1e4; const bytes = decoder.arr.subarray(decoder.pos, decoder.pos + nextLen); decoder.pos += nextLen; encodedString += String.fromCodePoint.apply( null, /** @type {any} */ bytes ); remainingLen -= nextLen; } } return decodeURIComponent(escape(encodedString)); } }; var _readVarStringNative = (decoder) => ( /** @type any */ utf8TextDecoder.decode(readVarUint8Array(decoder)) ); var readVarString = utf8TextDecoder ? _readVarStringNative : _readVarStringPolyfill; var readFromDataView = (decoder, len) => { const dv = new DataView(decoder.arr.buffer, decoder.arr.byteOffset + decoder.pos, len); decoder.pos += len; return dv; }; var readFloat32 = (decoder) => readFromDataView(decoder, 4).getFloat32(0, false); var readFloat64 = (decoder) => readFromDataView(decoder, 8).getFloat64(0, false); var readBigInt64 = (decoder) => ( /** @type {any} */ readFromDataView(decoder, 8).getBigInt64(0, false) ); var readAnyLookupTable = [ (decoder) => void 0, // CASE 127: undefined (decoder) => null, // CASE 126: null readVarInt, // CASE 125: integer readFloat32, // CASE 124: float32 readFloat64, // CASE 123: float64 readBigInt64, // CASE 122: bigint (decoder) => false, // CASE 121: boolean (false) (decoder) => true, // CASE 120: boolean (true) readVarString, // CASE 119: string (decoder) => { const len = readVarUint(decoder); const obj = {}; for (let i = 0; i < len; i++) { const key = readVarString(decoder); obj[key] = readAny(decoder); } return obj; }, (decoder) => { const len = readVarUint(decoder); const arr = []; for (let i = 0; i < len; i++) { arr.push(readAny(decoder)); } return arr; }, readVarUint8Array // CASE 116: Uint8Array ]; var readAny = (decoder) => readAnyLookupTable[127 - readUint8(decoder)](decoder); var RleDecoder = class extends Decoder { /** * @param {Uint8Array} uint8Array * @param {function(Decoder):T} reader */ constructor(uint8Array, reader) { super(uint8Array); this.reader = reader; this.s = null; this.count = 0; } read() { if (this.count === 0) { this.s = this.reader(this); if (hasContent(this)) { this.count = readVarUint(this) + 1; } else { this.count = -1; } } this.count--; return ( /** @type {T} */ this.s ); } }; var UintOptRleDecoder = class extends Decoder { /** * @param {Uint8Array} uint8Array */ constructor(uint8Array) { super(uint8Array); this.s = 0; this.count = 0; } read() { if (this.count === 0) { this.s = readVarInt(this); const isNegative = isNegativeZero(this.s); this.count = 1; if (isNegative) { this.s = -this.s; this.count = readVarUint(this) + 2; } } this.count--; return ( /** @type {number} */ this.s ); } }; var IntDiffOptRleDecoder = class extends Decoder { /** * @param {Uint8Array} uint8Array */ constructor(uint8Array) { super(uint8Array); this.s = 0; this.count = 0; this.diff = 0; } /** * @return {number} */ read() { if (this.count === 0) { const diff = readVarInt(this); const hasCount = diff & 1; this.diff = floor(diff / 2); this.count = 1; if (hasCount) { this.count = readVarUint(this) + 2; } } this.s += this.diff; this.count--; return this.s; } }; var StringDecoder = class { /** * @param {Uint8Array} uint8Array */ constructor(uint8Array) { this.decoder = new UintOptRleDecoder(uint8Array); this.str = readVarString(this.decoder); this.spos = 0; } /** * @return {string} */ read() { const end = this.spos + this.decoder.read(); const res = this.str.slice(this.spos, end); this.spos = end; return res; } }; // node_modules/lib0/buffer.js var createUint8ArrayFromLen = (len) => new Uint8Array(len); var createUint8ArrayViewFromArrayBuffer = (buffer, byteOffset, length3) => new Uint8Array(buffer, byteOffset, length3); var copyUint8Array = (uint8Array) => { const newBuf = createUint8ArrayFromLen(uint8Array.byteLength); newBuf.set(uint8Array); return newBuf; }; // node_modules/lib0/encoding.js var Encoder = class { constructor() { this.cpos = 0; this.cbuf = new Uint8Array(100); this.bufs = []; } }; var createEncoder = () => new Encoder(); var length2 = (encoder) => { let len = encoder.cpos; for (let i = 0; i < encoder.bufs.length; i++) { len += encoder.bufs[i].length; } return len; }; var toUint8Array = (encoder) => { const uint8arr = new Uint8Array(length2(encoder)); let curPos = 0; for (let i = 0; i < encoder.bufs.length; i++) { const d = encoder.bufs[i]; uint8arr.set(d, curPos); curPos += d.length; } uint8arr.set(createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos), curPos); return uint8arr; }; var verifyLen = (encoder, len) => { const bufferLen = encoder.cbuf.length; if (bufferLen - encoder.cpos < len) { encoder.bufs.push(createUint8ArrayViewFromArrayBuffer(encoder.cbuf.buffer, 0, encoder.cpos)); encoder.cbuf = new Uint8Array(max(bufferLen, len) * 2); encoder.cpos = 0; } }; var write = (encoder, num) => { const bufferLen = encoder.cbuf.length; if (encoder.cpos === bufferLen) { encoder.bufs.push(encoder.cbuf); encoder.cbuf = new Uint8Array(bufferLen * 2); encoder.cpos = 0; } encoder.cbuf[encoder.cpos++] = num; }; var writeUint8 = write; var writeVarUint = (encoder, num) => { while (num > BITS7) { write(encoder, BIT8 | BITS7 & num); num = floor(num / 128); } write(encoder, BITS7 & num); }; var writeVarInt = (encoder, num) => { const isNegative = isNegativeZero(num); if (isNegative) { num = -num; } write(encoder, (num > BITS6 ? BIT8 : 0) | (isNegative ? BIT7 : 0) | BITS6 & num); num = floor(num / 64); while (num > 0) { write(encoder, (num > BITS7 ? BIT8 : 0) | BITS7 & num); num = floor(num / 128); } }; var _strBuffer = new Uint8Array(3e4); var _maxStrBSize = _strBuffer.length / 3; var _writeVarStringNative = (encoder, str) => { if (str.length < _maxStrBSize) { const written = utf8TextEncoder.encodeInto(str, _strBuffer).written || 0; writeVarUint(encoder, written); for (let i = 0; i < written; i++) { write(encoder, _strBuffer[i]); } } else { writeVarUint8Array(encoder, encodeUtf8(str)); } }; var _writeVarStringPolyfill = (encoder, str) => { const encodedString = unescape(encodeURIComponent(str)); const len = encodedString.length; writeVarUint(encoder, len); for (let i = 0; i < len; i++) { write( encoder, /** @type {number} */ encodedString.codePointAt(i) ); } }; var writeVarString = utf8TextEncoder && /** @type {any} */ utf8TextEncoder.encodeInto ? _writeVarStringNative : _writeVarStringPolyfill; var writeBinaryEncoder = (encoder, append2) => writeUint8Array(encoder, toUint8Array(append2)); var writeUint8Array = (encoder, uint8Array) => { const bufferLen = encoder.cbuf.length; const cpos = encoder.cpos; const leftCopyLen = min(bufferLen - cpos, uint8Array.length); const rightCopyLen = uint8Array.length - leftCopyLen; encoder.cbuf.set(uint8Array.subarray(0, leftCopyLen), cpos); encoder.cpos += leftCopyLen; if (rightCopyLen > 0) { encoder.bufs.push(encoder.cbuf); encoder.cbuf = new Uint8Array(max(bufferLen * 2, rightCopyLen)); encoder.cbuf.set(uint8Array.subarray(leftCopyLen)); encoder.cpos = rightCopyLen; } }; var writeVarUint8Array = (encoder, uint8Array) => { writeVarUint(encoder, uint8Array.byteLength); writeUint8Array(encoder, uint8Array); }; var writeOnDataView = (encoder, len) => { verifyLen(encoder, len); const dview = new DataView(encoder.cbuf.buffer, encoder.cpos, len); encoder.cpos += len; return dview; }; var writeFloat32 = (encoder, num) => writeOnDataView(encoder, 4).setFloat32(0, num, false); var writeFloat64 = (encoder, num) => writeOnDataView(encoder, 8).setFloat64(0, num, false); var writeBigInt64 = (encoder, num) => ( /** @type {any} */ writeOnDataView(encoder, 8).setBigInt64(0, num, false) ); var floatTestBed = new DataView(new ArrayBuffer(4)); var isFloat32 = (num) => { floatTestBed.setFloat32(0, num); return floatTestBed.getFloat32(0) === num; }; var writeAny = (encoder, data) => { switch (typeof data) { case "string": write(encoder, 119); writeVarString(encoder, data); break; case "number": if (isInteger(data) && abs(data) <= BITS31) { write(encoder, 125); writeVarInt(encoder, data); } else if (isFloat32(data)) { write(encoder, 124); writeFloat32(encoder, data); } else { write(encoder, 123); writeFloat64(encoder, data); } break; case "bigint": write(encoder, 122); writeBigInt64(encoder, data); break; case "object": if (data === null) { write(encoder, 126); } else if (isArray(data)) { write(encoder, 117); writeVarUint(encoder, data.length); for (let i = 0; i < data.length; i++) { writeAny(encoder, data[i]); } } else if (data instanceof Uint8Array) { write(encoder, 116); writeVarUint8Array(encoder, data); } else { write(encoder, 118); const keys2 = Object.keys(data); writeVarUint(encoder, keys2.length); for (let i = 0; i < keys2.length; i++) { const key = keys2[i]; writeVarString(encoder, key); writeAny(encoder, data[key]); } } break; case "boolean": write(encoder, data ? 120 : 121); break; default: write(encoder, 127); } }; var RleEncoder = class extends Encoder { /** * @param {function(Encoder, T):void} writer */ constructor(writer) { super(); this.w = writer; this.s = null; this.count = 0; } /** * @param {T} v */ write(v) { if (this.s === v) { this.count++; } else { if (this.count > 0) { writeVarUint(this, this.count - 1); } this.count = 1; this.w(this, v); this.s = v; } } }; var flushUintOptRleEncoder = (encoder) => { if (encoder.count > 0) { writeVarInt(encoder.encoder, encoder.count === 1 ? encoder.s : -encoder.s); if (encoder.count > 1) { writeVarUint(encoder.encoder, encoder.count - 2); } } }; var UintOptRleEncoder = class { constructor() { this.encoder = new Encoder(); this.s = 0; this.count = 0; } /** * @param {number} v */ write(v) { if (this.s === v) { this.count++; } else { flushUintOptRleEncoder(this); this.count = 1; this.s = v; } } toUint8Array() { flushUintOptRleEncoder(this); return toUint8Array(this.encoder); } }; var flushIntDiffOptRleEncoder = (encoder) => { if (encoder.count > 0) { const encodedDiff = encoder.diff * 2 + (encoder.count === 1 ? 0 : 1); writeVarInt(encoder.encoder, encodedDiff); if (encoder.count > 1) { writeVarUint(encoder.encoder, encoder.count - 2); } } }; var IntDiffOptRleEncoder = class { constructor() { this.encoder = new Encoder(); this.s = 0; this.count = 0; this.diff = 0; } /** * @param {number} v */ write(v) { if (this.diff === v - this.s) { this.s = v; this.count++; } else { flushIntDiffOptRleEncoder(this); this.count = 1; this.diff = v - this.s; this.s = v; } } toUint8Array() { flushIntDiffOptRleEncoder(this); return toUint8Array(this.encoder); } }; var StringEncoder = class { constructor() { this.sarr = []; this.s = ""; this.lensE = new UintOptRleEncoder(); } /** * @param {string} string */ write(string) { this.s += string; if (this.s.length > 19) { this.sarr.push(this.s); this.s = ""; } this.lensE.write(string.length); } toUint8Array() { const encoder = new Encoder(); this.sarr.push(this.s); this.s = ""; writeVarString(encoder, this.sarr.join("")); writeUint8Array(encoder, this.lensE.toUint8Array()); return toUint8Array(encoder); } }; // <data:text/javascript,\n import {crypto} from '@...> import { crypto } from "@alinea/iso"; var subtle = crypto.subtle; var getRandomValues = crypto.getRandomValues.bind(crypto); // node_modules/lib0/random.js var rand = Math.random; var uint32 = () => getRandomValues(new Uint32Array(1))[0]; var oneOf = (arr) => arr[floor(rand() * arr.length)]; var uuidv4Template = [1e7] + -1e3 + -4e3 + -8e3 + -1e11; var uuidv4 = () => uuidv4Template.replace( /[018]/g, /** @param {number} c */ (c) => (c ^ uint32() & 15 >> c / 4).toString(16) ); // node_modules/lib0/pair.js var Pair = class { /** * @param {L} left * @param {R} right */ constructor(left, right) { this.left = left; this.right = right; } }; var create5 = (left, right) => new Pair(left, right); // node_modules/lib0/dom.js var doc = ( /** @type {Document} */ typeof document !== "undefined" ? document : {} ); var domParser = ( /** @type {DOMParser} */ typeof DOMParser !== "undefined" ? new DOMParser() : null ); var mapToStyleString = (m) => map(m, (value, key) => `${key}:${value};`).join(""); var ELEMENT_NODE = doc.ELEMENT_NODE; var TEXT_NODE = doc.TEXT_NODE; var CDATA_SECTION_NODE = doc.CDATA_SECTION_NODE; var COMMENT_NODE = doc.COMMENT_NODE; var DOCUMENT_NODE = doc.DOCUMENT_NODE; var DOCUMENT_TYPE_NODE = doc.DOCUMENT_TYPE_NODE; var DOCUMENT_FRAGMENT_NODE = doc.DOCUMENT_FRAGMENT_NODE; // node_modules/lib0/eventloop.js var createTimeoutClass = (clearFunction) => class TT { /** * @param {number} timeoutId */ constructor(timeoutId) { this._ = timeoutId; } destroy() { clearFunction(this._); } }; var Timeout = createTimeoutClass(clearTimeout); var timeout = (timeout2, callback) => new Timeout(setTimeout(callback, timeout2)); var Interval = createTimeoutClass(clearInterval); var Animation = createTimeoutClass((arg) => typeof requestAnimationFrame !== "undefined" && cancelAnimationFrame(arg)); var Idle = createTimeoutClass((arg) => typeof cancelIdleCallback !== "undefined" && cancelIdleCallback(arg)); // node_modules/lib0/symbol.js var create6 = Symbol; // node_modules/lib0/logging.common.js var BOLD = create6(); var UNBOLD = create6(); var BLUE = create6(); var GREY = create6(); var GREEN = create6(); var RED = create6(); var PURPLE = create6(); var ORANGE = create6(); var UNCOLOR = create6(); var computeNoColorLoggingArgs = (args2) => { const strBuilder = []; const logArgs = []; let i = 0; for (; i < args2.length; i++) { const arg = args2[i]; if (arg.constructor === String || arg.constructor === Number) { strBuilder.push(arg); } else if (arg.constructor === Object) { logArgs.push(JSON.stringify(arg)); } } return logArgs; }; var lastLoggingTime = getUnixTime(); // node_modules/lib0/logging.js var _browserStyleMap = { [BOLD]: create5("font-weight", "bold"), [UNBOLD]: create5("font-weight", "normal"), [BLUE]: create5("color", "blue"), [GREEN]: create5("color", "green"), [GREY]: create5("color", "grey"), [RED]: create5("color", "red"), [PURPLE]: create5("color", "purple"), [ORANGE]: create5("color", "orange"), // not well supported in chrome when debugging node with inspector - TODO: deprecate [UNCOLOR]: create5("color", "black") }; var computeBrowserLoggingArgs = (args2) => { const strBuilder = []; const styles = []; const currentStyle = create3(); let logArgs = []; let i = 0; for (; i < args2.length; i++) { const arg = args2[i]; const style = _browserStyleMap[arg]; if (style !== void 0) { currentStyle.set(style.left, style.right); } else { if (arg.constructor === String || arg.constructor === Number) { const style2 = mapToStyleString(currentStyle); if (i > 0 || style2.length > 0) { strBuilder.push("%c" + arg); styles.push(style2); } else { strBuilder.push(arg); } } else { break; } } } if (i > 0) { logArgs = styles; logArgs.unshift(strBuilder.join("")); } for (; i < args2.length; i++) { const arg = args2[i]; if (!(arg instanceof Symbol)) { logArgs.push(arg); } } return logArgs; }; var computeLoggingArgs = supportsColor ? computeBrowserLoggingArgs : computeNoColorLoggingArgs; var print = (...args2) => { console.log(...computeLoggingArgs(args2)); vconsoles.forEach((vc) => vc.print(args2)); }; var vconsoles = create4(); // node_modules/lib0/iterator.js var createIterator = (next) => ({ /** * @return {IterableIterator<T>} */ [Symbol.iterator]() { return this; }, // @ts-ignore next }); var iteratorFilter = (iterator, filter) => createIterator(() => { let res; do { res = iterator.next(); } while (!res.done && !filter(res.value)); return res; }); var iteratorMap = (iterator, fmap) => createIterator(() => { const { done, value } = iterator.next(); return { done, value: done ? void 0 : fmap(value) }; }); // node_modules/yjs/dist/yjs.mjs var AbstractConnector = class extends Observable { /** * @param {Doc} ydoc * @param {any} awareness */ constructor(ydoc, awareness) { super(); this.doc = ydoc; this.awareness = awareness; } }; var DeleteItem = class { /** * @param {number} clock * @param {number} len */ constructor(clock, len) { this.clock = clock; this.len = len; } }; var DeleteSet = class { constructor() { this.clients = /* @__PURE__ */ new Map(); } }; var iterateDeletedStructs = (transaction, ds, f) => ds.clients.forEach((deletes, clientid) => { const structs = ( /** @type {Array<GC|Item>} */ transaction.doc.store.clients.get(clientid) ); for (let i = 0; i < deletes.length; i++) { const del = deletes[i]; iterateStructs(transaction, structs, del.clock, del.len, f); } }); var findIndexDS = (dis, clock) => { let left = 0; let right = dis.length - 1; while (left <= right) { const midindex = floor((left + right) / 2); const mid = dis[midindex]; const midclock = mid.clock; if (midclock <= clock) { if (clock < midclock + mid.len) { return midindex; } left = midindex + 1; } else { right = midindex - 1; } } return null; }; var isDeleted = (ds, id2) => { const dis = ds.clients.get(id2.client); return dis !== void 0 && findIndexDS(dis, id2.clock) !== null; }; var sortAndMergeDeleteSet = (ds) => { ds.clients.forEach((dels) => { dels.sort((a, b) => a.clock - b.clock); let i, j; for (i = 1, j = 1; i < dels.length; i++) { const left = dels[j - 1]; const right = dels[i]; if (left.clock + left.len >= right.clock) { left.len = max(left.len, right.clock + right.len - left.clock); } else { if (j < i) { dels[j] = right; } j++; } } dels.length = j; }); }; var mergeDeleteSets = (dss) => { const merged = new DeleteSet(); for (let dssI = 0; dssI < dss.length; dssI++) { dss[dssI].clients.forEach((delsLeft, client) => { if (!merged.clients.has(client)) { const dels = delsLeft.slice(); for (let i = dssI + 1; i < dss.length; i++) { appendTo(dels, dss[i].clients.get(client) || []); } merged.clients.set(client, dels); } }); } sortAndMergeDeleteSet(merged); return merged; }; var addToDeleteSet = (ds, client, clock, length3) => { setIfUndefined(ds.clients, client, () => ( /** @type {Array<DeleteItem>} */ [] )).push(new DeleteItem(clock, length3)); }; var createDeleteSet = () => new DeleteSet(); var createDeleteSetFromStructStore = (ss) => { const ds = createDeleteSet(); ss.clients.forEach((structs, client) => { const dsitems = []; for (let i = 0; i < structs.length; i++) { const struct = structs[i]; if (struct.deleted) { const clock = struct.id.clock; let len = struct.length; if (i + 1 < structs.length) { for (let next = structs[i + 1]; i + 1 < structs.length && next.deleted; next = structs[++i + 1]) { len += next.length; } } dsitems.push(new DeleteItem(clock, len)); } } if (dsitems.length > 0) { ds.clients.set(client, dsitems); } }); return ds; }; var writeDeleteSet = (encoder, ds) => { writeVarUint(encoder.restEncoder, ds.clients.size); from(ds.clients.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, dsitems]) => { encoder.resetDsCurVal(); writeVarUint(encoder.restEncoder, client); const len = dsitems.length; writeVarUint(encoder.restEncoder, len); for (let i = 0; i < len; i++) { const item = dsitems[i]; encoder.writeDsClock(item.clock); encoder.writeDsLen(item.len); } }); }; var readDeleteSet = (decoder) => { const ds = new DeleteSet(); const numClients = readVarUint(decoder.restDecoder); for (let i = 0; i < numClients; i++) { decoder.resetDsCurVal(); const client = readVarUint(decoder.restDecoder); const numberOfDeletes = readVarUint(decoder.restDecoder); if (numberOfDeletes > 0) { const dsField = setIfUndefined(ds.clients, client, () => ( /** @type {Array<DeleteItem>} */ [] )); for (let i2 = 0; i2 < numberOfDeletes; i2++) { dsField.push(new DeleteItem(decoder.readDsClock(), decoder.readDsLen())); } } } return ds; }; var readAndApplyDeleteSet = (decoder, transaction, store) => { const unappliedDS = new DeleteSet(); const numClients = readVarUint(decoder.restDecoder); for (let i = 0; i < numClients; i++) { decoder.resetDsCurVal(); const client = readVarUint(decoder.restDecoder); const numberOfDeletes = readVarUint(decoder.restDecoder); const structs = store.clients.get(client) || []; const state = getState(store, client); for (let i2 = 0; i2 < numberOfDeletes; i2++) { const clock = decoder.readDsClock(); const clockEnd = clock + decoder.readDsLen(); if (clock < state) { if (state < clockEnd) { addToDeleteSet(unappliedDS, client, state, clockEnd - state); } let index = findIndexSS(structs, clock); let struct = structs[index]; if (!struct.deleted && struct.id.clock < clock) { structs.splice(index + 1, 0, splitItem(transaction, struct, clock - struct.id.clock)); index++; } while (index < structs.length) { struct = structs[index++]; if (struct.id.clock < clockEnd) { if (!struct.deleted) { if (clockEnd < struct.id.clock + struct.length) { structs.splice(index, 0, splitItem(transaction, struct, clockEnd - struct.id.clock)); } struct.delete(transaction); } } else { break; } } } else { addToDeleteSet(unappliedDS, client, clock, clockEnd - clock); } } } if (unappliedDS.clients.size > 0) { const ds = new UpdateEncoderV2(); writeVarUint(ds.restEncoder, 0); writeDeleteSet(ds, unappliedDS); return ds.toUint8Array(); } return null; }; var equalDeleteSets = (ds1, ds2) => { if (ds1.clients.size !== ds2.clients.size) return false; for (const [client, deleteItems1] of ds1.clients.entries()) { const deleteItems2 = ( /** @type {Array<import('../internals.js').DeleteItem>} */ ds2.clients.get(client) ); if (deleteItems2 === void 0 || deleteItems1.length !== deleteItems2.length) return false; for (let i = 0; i < deleteItems1.length; i++) { const di1 = deleteItems1[i]; const di2 = deleteItems2[i]; if (di1.clock !== di2.clock || di1.len !== di2.len) { return false; } } } return true; }; var generateNewClientId = uint32; var Doc = class _Doc extends Observable { /** * @param {DocOpts} opts configuration */ constructor({ guid = uuidv4(), collectionid = null, gc = true, gcFilter = () => true, meta = null, autoLoad = false, shouldLoad = true } = {}) { super(); this.gc = gc; this.gcFilter = gcFilter; this.clientID = generateNewClientId(); this.guid = guid; this.collectionid = collectionid; this.share = /* @__PURE__ */ new Map(); this.store = new StructStore(); this._transaction = null; this._transactionCleanups = []; this.subdocs = /* @__PURE__ */ new Set(); this._item = null; this.shouldLoad = shouldLoad; this.autoLoad = autoLoad; this.meta = meta; this.isLoaded = false; this.isSynced = false; this.whenLoaded = create2((resolve) => { this.on("load", () => { this.isLoaded = true; resolve(this); }); }); const provideSyncedPromise = () => create2((resolve) => { const eventHandler = (isSynced) => { if (isSynced === void 0 || isSynced === true) { this.off("sync", eventHandler); resolve(); } }; this.on("sync", eventHandler); }); this.on("sync", (isSynced) => { if (isSynced === false && this.isSynced) { this.whenSynced = provideSyncedPromise(); } this.isSynced = isSynced === void 0 || isSynced === true; if (!this.isLoaded) { this.emit("load", []); } }); this.whenSynced = provideSyncedPromise(); } /** * Notify the parent document that you request to load data into this subdocument (if it is a subdocument). * * `load()` might be used in the future to request any provider to load the most current data. * * It is safe to call `load()` multiple times. */ load() { const item = this._item; if (item !== null && !this.shouldLoad) { transact( /** @type {any} */ item.parent.doc, (transaction) => { transaction.subdocsLoaded.add(this); }, null, true ); } this.shouldLoad = true; } getSubdocs() { return this.subdocs; } getSubdocGuids() { return new Set(from(this.subdocs).map((doc2) => doc2.guid)); } /** * Changes that happen inside of a transaction are bundled. This means that * the observer fires _after_ the transaction is finished and that all changes * that happened inside of the transaction are sent as one message to the * other peers. * * @template T * @param {function(Transaction):T} f The function that should be executed as a transaction * @param {any} [origin] Origin of who started the transaction. Will be stored on transaction.origin * @return T * * @public */ transact(f, origin = null) { return transact(this, f, origin); } /** * Define a shared data type. * * Multiple calls of `y.get(name, TypeConstructor)` yield the same result * and do not overwrite each other. I.e. * `y.define(name, Y.Array) === y.define(name, Y.Array)` * * After this method is called, the type is also available on `y.share.get(name)`. * * *Best Practices:* * Define all types right after the Yjs instance is created and store them in a separate object. * Also use the typed methods `getText(name)`, `getArray(name)`, .. * * @example * const y = new Y(..) * const appState = { * document: y.getText('document') * comments: y.getArray('comments') * } * * @param {string} name * @param {Function} TypeConstructor The constructor of the type definition. E.g. Y.Text, Y.Array, Y.Map, ... * @return {AbstractType<any>} The created type. Constructed with TypeConstructor * * @public */ get(name, TypeConstructor = AbstractType) { const type = setIfUndefined(this.share, name, () => { const t = new TypeConstructor(); t._integrate(this, null); return t; }); const Constr = type.constructor; if (TypeConstructor !== AbstractType && Constr !== TypeConstructor) { if (Constr === AbstractType) { const t = new TypeConstructor(); t._map = type._map; type._map.forEach( /** @param {Item?} n */ (n) => { for (; n !== null; n = n.left) { n.parent = t; } } ); t._start = type._start; for (let n = t._start; n !== null; n = n.right) { n.parent = t; } t._length = type._length; this.share.set(name, t); t._integrate(this, null); return t; } else { throw new Error(`Type with the name ${name} has already been defined with a different constructor`); } } return type; } /** * @template T * @param {string} [name] * @return {YArray<T>} * * @public */ getArray(name = "") { return this.get(name, YArray); } /** * @param {string} [name] * @return {YText} * * @public */ getText(name = "") { return this.get(name, YText); } /** * @template T * @param {string} [name] * @return {YMap<T>} * * @public */ getMap(name = "") { return this.get(name, YMap); } /** * @param {string} [name] * @return {YXmlFragment} * * @public */ getXmlFragment(name = "") { return this.get(name, YXmlFragment); } /** * Converts the entire document into a js object, recursively traversing each yjs type * Doesn't log types that have not been defined (using ydoc.getType(..)). * * @deprecated Do not use this method and rather call toJSON directly on the shared types. * * @return {Object<string, any>} */ toJSON() { const doc2 = {}; this.share.forEach((value, key) => { doc2[key] = value.toJSON(); }); return doc2; } /** * Emit `destroy` event and unregister all event handlers. */ destroy() { from(this.subdocs).forEach((subdoc) => subdoc.destroy()); const item = this._item; if (item !== null) { this._item = null; const content = ( /** @type {ContentDoc} */ item.content ); content.doc = new _Doc({ guid: this.guid, ...content.opts, shouldLoad: false }); content.doc._item = item; transact( /** @type {any} */ item.parent.doc, (transaction) => { const doc2 = content.doc; if (!item.deleted) { transaction.subdocsAdded.add(doc2); } transaction.subdocsRemoved.add(this); }, null, true ); } this.emit("destroyed", [true]); this.emit("destroy", [this]); super.destroy(); } /** * @param {string} eventName * @param {function(...any):any} f */ on(eventName, f) { super.on(eventName, f); } /** * @param {string} eventName * @param {function} f */ off(eventName, f) { super.off(eventName, f); } }; var DSDecoderV1 = class { /** * @param {decoding.Decoder} decoder */ constructor(decoder) { this.restDecoder = decoder; } resetDsCurVal() { } /** * @return {number} */ readDsClock() { return readVarUint(this.restDecoder); } /** * @return {number} */ readDsLen() { return readVarUint(this.restDecoder); } }; var UpdateDecoderV1 = class extends DSDecoderV1 { /** * @return {ID} */ readLeftID() { return createID(readVarUint(this.restDecoder), readVarUint(this.restDecoder)); } /** * @return {ID} */ readRightID() { return createID(readVarUint(this.restDecoder), readVarUint(this.restDecoder)); } /** * Read the next client id. * Use this in favor of readID whenever possible to reduce the number of objects created. */ readClient() { return readVarUint(this.restDecoder); } /** * @return {number} info An unsigned 8-bit integer */ readInfo() { return readUint8(this.restDecoder); } /** * @return {string} */ readString() { return readVarString(this.restDecoder); } /** * @return {boolean} isKey */ readParentInfo() { return readVarUint(this.restDecoder) === 1; } /** * @return {number} info An unsigned 8-bit integer */ readTypeRef() { return readVarUint(this.restDecoder); } /** * Write len of a struct - well suited for Opt RLE encoder. * * @return {number} len */ readLen() { return readVarUint(this.restDecoder); } /** * @return {any} */ readAny() { return readAny(this.restDecoder); } /** * @return {Uint8Array} */ readBuf() { return copyUint8Array(readVarUint8Array(this.restDecoder)); } /** * Legacy implementation uses JSON parse. We use any-decoding in v2. * * @return {any} */ readJSON() { return JSON.parse(readVarString(this.restDecoder)); } /** * @return {string} */ readKey() { return readVarString(this.restDecoder); } }; var DSDecoderV2 = class { /** * @param {decoding.Decoder} decoder */ constructor(decoder) { this.dsCurrVal = 0; this.restDecoder = decoder; } resetDsCurVal() { this.dsCurrVal = 0; } /** * @return {number} */ readDsClock() { this.dsCurrVal += readVarUint(this.restDecoder); return this.dsCurrVal; } /** * @return {number} */ readDsLen() { const diff = readVarUint(this.restDecoder) + 1; this.dsCurrVal += diff; return diff; } }; var UpdateDecoderV2 = class extends DSDecoderV2 { /** * @param {decoding.Decoder} decoder */ constructor(decoder) { super(decoder); this.keys = []; readVarUint(decoder); this.keyClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder)); this.clientDecoder = new UintOptRleDecoder(readVarUint8Array(decoder)); this.leftClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder)); this.rightClockDecoder = new IntDiffOptRleDecoder(readVarUint8Array(decoder)); this.infoDecoder = new RleDecoder(readVarUint8Array(decoder), readUint8); this.stringDecoder = new StringDecoder(readVarUint8Array(decoder)); this.parentInfoDecoder = new RleDecoder(readVarUint8Array(decoder), readUint8); this.typeRefDecoder = new UintOptRleDecoder(readVarUint8Array(decoder)); this.lenDecoder = new UintOptRleDecoder(readVarUint8Array(decoder)); } /** * @return {ID} */ readLeftID() { return new ID(this.clientDecoder.read(), this.leftClockDecoder.read()); } /** * @return {ID} */ readRightID() { return new ID(this.clientDecoder.read(), this.rightClockDecoder.read()); } /** * Read the next client id. * Use this in favor of readID whenever possible to reduce the number of objects created. */ readClient() { return this.clientDecoder.read(); } /** * @return {number} info An unsigned 8-bit integer */ readInfo() { return ( /** @type {number} */ this.infoDecoder.read() ); } /** * @return {s