UNPKG

alinea

Version:
1,778 lines (1,758 loc) 229 kB
import { BIT1, BIT2, BIT3, BIT4, BIT6, BIT7, BIT8, BITS5, IntDiffOptRleDecoder, IntDiffOptRleEncoder, RleDecoder, RleEncoder, StringDecoder, StringEncoder, UintOptRleDecoder, UintOptRleEncoder, abs, appendTo, create, create2, createDecoder, createEncoder, floor, from, fromCamelCase, hasContent, isArray, last, max, methodUnimplemented, min, readAny, readUint8, readVarInt, readVarString, readVarUint, readVarUint8Array, repeat, some, toUint8Array, unexpectedCase, writeAny, writeBinaryEncoder, writeUint8, writeUint8Array, writeVarInt, writeVarString, writeVarUint, writeVarUint8Array } from "./chunk-AJJSW27C.js"; // 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/observable.js var Observable = class { constructor() { this._observers = create3(); } /** * @param {N} name * @param {function} f */ on(name, f) { setIfUndefined(this._observers, name, create).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(); } }; // <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 = "10000000-1000-4000-8000" + -1e11; var uuidv4 = () => uuidv4Template.replace( /[018]/g, /** @param {number} c */ (c) => (c ^ uint32() & 15 >> c / 4).toString(16) ); // node_modules/lib0/time.js var getUnixTime = Date.now; // node_modules/lib0/promise.js var create4 = (f) => ( /** @type {Promise<T>} */ new Promise(f) ); var all = Promise.all.bind(Promise); // 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 = 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) && Object.prototype.toString.call(typeof process !== "undefined" ? process : 0) === "[object process]"; 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/buffer.js var createUint8ArrayFromLen = (len) => new Uint8Array(len); var copyUint8Array = (uint8Array) => { const newBuf = createUint8ArrayFromLen(uint8Array.byteLength); newBuf.set(uint8Array); return newBuf; }; // 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 warn = (...args2) => { console.warn(...computeLoggingArgs(args2)); args2.unshift(ORANGE); vconsoles.forEach((vc) => vc.print(args2)); }; var vconsoles = create(); // 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-src/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, length2) => { setIfUndefined(ds.clients, client, () => ( /** @type {Array<DeleteItem>} */ [] )).push(new DeleteItem(clock, length2)); }; 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 = create4((resolve) => { this.on("load", () => { this.isLoaded = true; resolve(this); }); }); const provideSyncedPromise = () => create4((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.isSynced && !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 {string} */ readString() { return this.stringDecoder.read(); } /** * @return {boolean} */ readParentInfo() { return this.parentInfoDecoder.read() === 1; } /** * @return {number} An unsigned 8-bit integer */ readTypeRef() { return this.typeRefDecoder.read(); } /** * Write len of a struct - well suited for Opt RLE encoder. * * @return {number} */ readLen() { return this.lenDecoder.read(); } /** * @return {any} */ readAny() { return readAny(this.restDecoder); } /** * @return {Uint8Array} */ readBuf() { return readVarUint8Array(this.restDecoder); } /** * This is mainly here for legacy purposes. * * 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. * * @return {any} */ readJSON() { return readAny(this.restDecoder); } /** * @return {string} */ readKey() { const keyClock = this.keyClockDecoder.read(); if (keyClock < this.keys.length) { return this.keys[keyClock]; } else { const key = this.stringDecoder.read(); this.keys.push(key); return key; } } }; var DSEncoderV1 = class { constructor() { this.restEncoder = createEncoder(); } toUint8Array() { return toUint8Array(this.restEncoder); } resetDsCurVal() { } /** * @param {number} clock */ writeDsClock(clock) { writeVarUint(this.restEncoder, clock); } /** * @param {number} len */ writeDsLen(len) { writeVarUint(this.restEncoder, len); } }; var UpdateEncoderV1 = class extends DSEncoderV1 { /** * @param {ID} id */ writeLeftID(id2) { writeVarUint(this.restEncoder, id2.client); writeVarUint(this.restEncoder, id2.clock); } /** * @param {ID} id */ writeRightID(id2) { writeVarUint(this.restEncoder, id2.client); writeVarUint(this.restEncoder, id2.clock); } /** * Use writeClient and writeClock instead of writeID if possible. * @param {number} client */ writeClient(client) { writeVarUint(this.restEncoder, client); } /** * @param {number} info An unsigned 8-bit integer */ writeInfo(info) { writeUint8(this.restEncoder, info); } /** * @param {string} s */ writeString(s) { writeVarString(this.restEncoder, s); } /** * @param {boolean} isYKey */ writeParentInfo(isYKey) { writeVarUint(this.restEncoder, isYKey ? 1 : 0); } /** * @param {number} info An unsigned 8-bit integer */ writeTypeRef(info) { writeVarUint(this.restEncoder, info); } /** * Write len of a struct - well suited for Opt RLE encoder. * * @param {number} len */ writeLen(len) { writeVarUint(this.restEncoder, len); } /** * @param {any} any */ writeAny(any2) { writeAny(this.restEncoder, any2); } /** * @param {Uint8Array} buf */ writeBuf(buf) { writeVarUint8Array(this.restEncoder, buf); } /** * @param {any} embed */ writeJSON(embed) { writeVarString(this.restEncoder, JSON.stringify(embed)); } /** * @param {string} key */ writeKey(key) { writeVarString(this.restEncoder, key); } }; var DSEncoderV2 = class { constructor() { this.restEncoder = createEncoder(); this.dsCurrVal = 0; } toUint8Array() { return toUint8Array(this.restEncoder); } resetDsCurVal() { this.dsCurrVal = 0; } /** * @param {number} clock */ writeDsClock(clock) { const diff = clock - this.dsCurrVal; this.dsCurrVal = clock; writeVarUint(this.restEncoder, diff); } /** * @param {number} len */ writeDsLen(len) { if (len === 0) { unexpectedCase(); } writeVarUint(this.restEncoder, len - 1); this.dsCurrVal += len; } }; var UpdateEncoderV2 = class extends DSEncoderV2 { constructor() { super(); this.keyMap = /* @__PURE__ */ new Map(); this.keyClock = 0; this.keyClockEncoder = new IntDiffOptRleEncoder(); this.clientEncoder = new UintOptRleEncoder(); this.leftClockEncoder = new IntDiffOptRleEncoder(); this.rightClockEncoder = new IntDiffOptRleEncoder(); this.infoEncoder = new RleEncoder(writeUint8); this.stringEncoder = new StringEncoder(); this.parentInfoEncoder = new RleEncoder(writeUint8); this.typeRefEncoder = new UintOptRleEncoder(); this.lenEncoder = new UintOptRleEncoder(); } toUint8Array() { const encoder = createEncoder(); writeVarUint(encoder, 0); writeVarUint8Array(encoder, this.keyClockEncoder.toUint8Array()); writeVarUint8Array(encoder, this.clientEncoder.toUint8Array()); writeVarUint8Array(encoder, this.leftClockEncoder.toUint8Array()); writeVarUint8Array(encoder, this.rightClockEncoder.toUint8Array()); writeVarUint8Array(encoder, toUint8Array(this.infoEncoder)); writeVarUint8Array(encoder, this.stringEncoder.toUint8Array()); writeVarUint8Array(encoder, toUint8Array(this.parentInfoEncoder)); writeVarUint8Array(encoder, this.typeRefEncoder.toUint8Array()); writeVarUint8Array(encoder, this.lenEncoder.toUint8Array()); writeUint8Array(encoder, toUint8Array(this.restEncoder)); return toUint8Array(encoder); } /** * @param {ID} id */ writeLeftID(id2) { this.clientEncoder.write(id2.client); this.leftClockEncoder.write(id2.clock); } /** * @param {ID} id */ writeRightID(id2) { this.clientEncoder.write(id2.client); this.rightClockEncoder.write(id2.clock); } /** * @param {number} client */ writeClient(client) { this.clientEncoder.write(client); } /** * @param {number} info An unsigned 8-bit integer */ writeInfo(info) { this.infoEncoder.write(info); } /** * @param {string} s */ writeString(s) { this.stringEncoder.write(s); } /** * @param {boolean} isYKey */ writeParentInfo(isYKey) { this.parentInfoEncoder.write(isYKey ? 1 : 0); } /** * @param {number} info An unsigned 8-bit integer */ writeTypeRef(info) { this.typeRefEncoder.write(info); } /** * Write len of a struct - well suited for Opt RLE encoder. * * @param {number} len */ writeLen(len) { this.lenEncoder.write(len); } /** * @param {any} any */ writeAny(any2) { writeAny(this.restEncoder, any2); } /** * @param {Uint8Array} buf */ writeBuf(buf) { writeVarUint8Array(this.restEncoder, buf); } /** * This is mainly here for legacy purposes. * * 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. * * @param {any} embed */ writeJSON(embed) { writeAny(this.restEncoder, embed); } /** * Property keys are often reused. For example, in y-prosemirror the key `bold` might * occur very often. For a 3d application, the key `position` might occur very often. * * We cache these keys in a Map and refer to them via a unique number. * * @param {string} key */ writeKey(key) { const clock = this.keyMap.get(key); if (clock === void 0) { this.keyClockEncoder.write(this.keyClock++); this.stringEncoder.write(key); } else { this.keyClockEncoder.write(clock); } } }; var writeStructs = (encoder, structs, client, clock) => { clock = max(clock, structs[0].id.clock); const startNewStructs = findIndexSS(structs, clock); writeVarUint(encoder.restEncoder, structs.length - startNewStructs); encoder.writeClient(client); writeVarUint(encoder.restEncoder, clock); const firstStruct = structs[startNewStructs]; firstStruct.write(encoder, clock - firstStruct.id.clock); for (let i = startNewStructs + 1; i < structs.length; i++) { structs[i].write(encoder, 0); } }; var writeClientsStructs = (encoder, store, _sm) => { const sm = /* @__PURE__ */ new Map(); _sm.forEach((clock, client) => { if (getState(store, client) > clock) { sm.set(client, clock); } }); getStateVector(store).forEach((_clock, client) => { if (!_sm.has(client)) { sm.set(client, 0); } }); writeVarUint(encoder.restEncoder, sm.size); from(sm.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, clock]) => { writeStructs( encoder, /** @type {Array<GC|Item>} */ store.clients.get(client), client, clock ); }); }; var readClientsStructRefs = (decoder, doc2) => { const clientRefs = create3(); const numOfStateUpdates = readVarUint(decoder.restDecoder); for (let i = 0; i < numOfStateUpdates; i++) { const numberOfStructs = readVarUint(decoder.restDecoder); const refs = new Array(numberOfStructs); const client = decoder.readClient(); let clock = readVarUint(decoder.restDecoder); clientRefs.set(client, { i: 0, refs }); for (let i2 = 0; i2 < numberOfStructs; i2++) { const info = decoder.readInfo(); switch (BITS5 & info) { case 0: { const len = decoder.readLen(); refs[i2] = new GC(createID(client, clock), len); clock += len; break; } case 10: { const len = readVarUint(decoder.restDecoder); refs[i2] = new Skip(createID(client, clock), len); clock += len; break; } default: { const cantCopyParentInfo = (info & (BIT7 | BIT8)) === 0; const struct = new Item( createID(client, clock), null, // leftd (info & BIT8) === BIT8 ? decoder.readLeftID() : null, // origin null, // right (info & BIT7) === BIT7 ? decoder.readRightID() : null, // right origin cantCopyParentInfo ? decoder.readParentInfo() ? doc2.get(decoder.readString()) : decoder.readLeftID() : null, // parent cantCopyParentInfo && (info & BIT6) === BIT6 ? decoder.readString() : null, // parentSub readItemContent(decoder, info) // item content ); refs[i2] = struct; clock += struct.length; } } } } return clientRefs; }; var integrateStructs = (transaction, store, clientsStructRefs) => { const stack = []; let clientsStructRefsIds = from(clientsStructRefs.keys()).sort((a, b) => a - b); if (clientsStructRefsIds.length === 0) { return null; } const getNextStructTarget = () => { if (clientsStructRefsIds.length === 0) { return null; } let nextStructsTarget = ( /** @type {{i:number,refs:Array<GC|Item>}} */ clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1]) ); while (nextStructsTarget.refs.length === nextStructsTarget.i) { clientsStructRefsIds.pop(); if (clientsStructRefsIds.length > 0) { nextStructsTarget = /** @type {{i:number,refs:Array<GC|Item>}} */ clientsStructRefs.get(clientsStructRefsIds[clientsStructRefsIds.length - 1]); } else { return null; } } return nextStructsTarget; }; let curStructsTarget = getNextStructTarget(); if (curStructsTarget === null) { return null; } const restStructs = new StructStore(); const missingSV = /* @__PURE__ */ new Map(); const updateMissingSv = (client, clock) => { const mclock = missingSV.get(client); if (mclock == null || mclock > clock) { missingSV.set(client, clock); } }; let stackHead = ( /** @type {any} */ curStructsTarget.refs[ /** @type {any} */ curStructsTarget.i++ ] ); const state = /* @__PURE__ */ new Map(); const addStackToRestSS = () => { for (const item of stack) { const client = item.id.client; const unapplicableItems = clientsStructRefs.get(client); if (unapplicableItems) { unapplicableItems.i--; restStructs.clients.set(client, unapplicableItems.refs.slice(unapplicableItems.i)); clientsStructRefs.delete(client); unapplicableItems.i = 0; unapplicableItems.refs = []; } else { restStructs.clients.set(client, [item]); } clientsStructRefsIds = clientsStructRefsIds.filter((c) => c !== client); } stack.length = 0; }; while (true) { if (stackHead.constructor !== Skip) { const localClock = setIfUndefined(state, stackHead.id.client, () => getState(store, stackHead.id.client)); const offset = localClock - stackHead.id.clock; if (offset < 0) { stack.push(stackHead); updateMissingSv(stackHead.id.client, stackHead.id.clock - 1); addStackToRestSS(); } else { const missing = stackHead.getMissing(transaction, store); if (missing !== null) { stack.push(stackHead); const structRefs = clientsStructRefs.get( /** @type {number} */ missing ) || { refs: [], i: 0 }; if (structRefs.refs.length === structRefs.i) { updateMissingSv( /** @type {number} */ missing, getState(store, missing) ); addStackToRestSS(); } else { stackHead = structRefs.refs[structRefs.i++]; continue; } } else if (offset === 0 || offset < stackHead.length) { stackHead.integrate(transaction, offset); state.set(stackHead.id.client, stackHead.id.clock + stackHead.length); } } } if (stack.length > 0) { stackHead = /** @type {GC|Item} */ stack.pop(); } else if (curStructsTarget !== null && curStructsTarget.i < curStructsTarget.refs.length) { stackHead = /** @type {GC|Item} */ curStructsTarget.refs[curStructsTarget.i++]; } else { curStructsTarget = getNextStructTarget(); if (curStructsTarget === null) { break; } else { stackHead = /** @type {GC|Item} */ curStructsTarget.refs[curStructsTarget.i++]; } } } if (restStructs.clients.size > 0) { const encoder = new UpdateEncoderV2(); writeClientsStructs(encoder, restStructs, /* @__PURE__ */ new Map()); writeVarUint(encoder.restEncoder, 0); return { missing: missingSV, update: encoder.toUint8Array() }; } return null; }; var writeStructsFromTransaction = (encoder, transaction) => writeClientsStructs(encoder, transaction.doc.store, transaction.beforeState); var readUpdateV2 = (decoder, ydoc, transactionOrigin, structDecoder = new UpdateDecoderV2(decoder)) => transact(ydoc, (transaction) => { transaction.local = false; let retry = false; const doc2 = transaction.doc; const store = doc2.store; const ss = readClientsStructRefs(structDecoder, doc2); const restStructs = integrateStructs(transaction, store, ss); const pending = store.pendingStructs; if (pending) { for (const [client, clock] of pending.missing) { if (clock < getState(store, client)) { retry = true; break; } } if (restStructs) { for (const [client, clock] of restStructs.missing) { const mclock = pending.missing.get(client); if (mclock == null || mclock > clock) { pending.missing.set(client, clock); } } pending.update = mergeUpdatesV2([pending.update, restStructs.update]); } } else { store.pendingStructs = restStructs; } const dsRest = readAndApplyDeleteSet(structDecoder, transaction, store); if (store.pendingDs) { const pendingDSUpdate = new UpdateDecoderV2(createDecoder(store.pendingDs)); readVarUint(pendingDSUpdate.restDecoder); const dsRest2 = readAndApplyDeleteSet(pendingDSUpdate, transaction, store); if (dsRest && dsRest2) { store.pendingDs = mergeUpdatesV2([dsRest, dsRest2]); } else { store.pendingDs = dsRest || dsRest2; } } else { store.pendingDs = dsRest; } if (retry) { const update = ( /** @type {{update: Uint8Array}} */ store.pendingStructs.update ); store.pendingStructs = null; applyUpdateV2(transaction.doc, update); } }, transactionOrigin, false); var readUpdate = (decoder, ydoc, transactionOrigin) => readUpdateV2(decoder, ydoc, transactionOrigin, new UpdateDecoderV1(decoder)); var applyUpdateV2 = (ydoc, update, transactionOrigin, YDecoder = UpdateDecoderV2) => { const decoder = createDecoder(update); readUpdateV2(decoder, ydoc, transactionOrigin, new YDecoder(decoder)); }; var applyUpdate = (ydoc, update, transactionOrigin) => applyUpdateV2(ydoc, update, transactionOrigin, UpdateDecoderV1); var writeStateAsUpdate = (encoder, doc2, targetStateVector = /* @__PURE__ */ new Map()) => { writeClientsStructs(encoder, doc2.store, targetStateVector); writeDeleteSet(encoder, createDeleteSetFromStructStore(doc2.store)); }; var encodeStateAsUpdateV2 = (doc2, encodedTargetStateVector = new Uint8Array([0]), encoder = new UpdateEncoderV2()) => { const targetStateVector = decodeStateVector(encodedTargetStateVector); writeStateAsUpdate(encoder, doc2, targetStateVector); const updates = [encoder.toUint8Array()]; if (doc2.store.pendingDs) { updates.push(doc2.store.pendingDs); } if (doc2.store.pendingStructs) { updates.push(diffUpdateV2(doc2.store.pendingStructs.update, encodedTargetStateVector)); } if (updates.length > 1) { if (encoder.constructor === UpdateEncoderV1) { return mergeUpdates(updates.map((update, i) => i === 0 ? update : convertUpdateFormatV2ToV1(update))); } else if (encoder.constructor === UpdateEncoderV2) { return mergeUpdatesV2(updates); } } return updates[0]; }; var encodeStateAsUpdate = (doc2, encodedTargetStateVector) => encodeStateAsUpdateV2(doc2, encodedTargetStateVector, new UpdateEncoderV1()); var readStateVector = (decoder) => { const ss = /* @__PURE__ */ new Map(); const ssLength = readVarUint(decoder.restDecoder); for (let i = 0; i < ssLength; i++) { const client = readVarUint(decoder.restDecoder); const clock = readVarUint(decoder.restDecoder); ss.set(client, clock); } return ss; }; var decodeStateVector = (decodedState) => readStateVector(new DSDecoderV1(createDecoder(decodedState))); var writeStateVector = (encoder, sv) => { writeVarUint(encoder.restEncoder, sv.size); from(sv.entries()).sort((a, b) => b[0] - a[0]).forEach(([client, clock]) => { writeVarUint(encoder.restEncoder, client); writeVarUint(encoder.restEncoder, clock); }); return encoder; }; var writeDocumentStateVector = (encoder, doc2) => writeStateVector(encoder, getStateVector(doc2.store)); var encodeStateVectorV2 = (doc2, encoder = new DSEncoderV2()) => { if (doc2 instanceof Map) { writeStateVector(encoder, doc2); } else { writeDocumentStateVector(encoder, doc2); } return encoder.toUint8Array(); }; var encodeStateVector = (doc2) => encodeStateVectorV2(doc2, new DSEncoderV1()); var EventHandler = class { constructor() { this.l = []; } }; var createEventHandler = () => new EventHandler(); var addEventHandlerListener = (eventHandler, f) => eventHandler.l.push(f); var removeEventHandlerListener = (eventHandler, f) => { const l = eventHandler.l; const len = l.length; eventHandler.l = l.filter((g) => f !== g); if (len === eventHandler.l.length) { console.error("[yjs] Tried to remove event handler that doesn't exist."); } }; var callEventHandlerListeners = (eventHandler, arg0, arg1) => callAll(eventHandler.l, [arg0, arg1]); var ID = class { /** * @param {number} client client id * @param {number} clock unique per client id, continuous number */ constructor(client, clock) { this.client = client; this.clock = clock; } }; var compareIDs = (a, b) => a === b || a !== null && b !== null && a.client === b.client && a.clock === b.clock; var createID = (client, clock) => new ID(client, clock); var writeID = (encoder, id2) => { writeVarUint(encoder, id2.client); writeVarUint(encoder, id2.clock); }; var readID = (decoder) => createID(readVarUint(decoder), readVarUint(decoder)); var findRootTypeKey = (type) => { for (const [key, value] of type.doc.share.entries()) { if (value === type) { return key; } }