@loro-extended/change 1.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/derive-placeholder.ts","../src/functional-helpers.ts","../src/utils/type-guards.ts","../src/overlay.ts","../src/placeholder-proxy.ts","../src/shape.ts","../src/typed-doc.ts","../src/json-patch.ts","../src/typed-refs/base.ts","../src/typed-refs/utils.ts","../src/typed-refs/counter.ts","../src/conversion.ts","../src/typed-refs/list-base.ts","../src/typed-refs/list.ts","../src/typed-refs/movable-list.ts","../src/typed-refs/proxy-handlers.ts","../src/typed-refs/record.ts","../src/typed-refs/struct.ts","../src/typed-refs/text.ts","../src/typed-refs/tree.ts","../src/typed-refs/doc.ts","../src/validation.ts","../src/typed-presence.ts"],"sourcesContent":["import type { ContainerOrValueShape, DocShape, ValueShape } from \"./shape.js\"\nimport type { InferPlaceholderType } from \"./types.js\"\n\n/**\n * Derives the placeholder state from a schema by composing placeholder values.\n *\n * For leaf nodes (text, counter, values): uses _placeholder directly\n * For containers (map, list, record): recurses into nested shapes\n */\nexport function derivePlaceholder<T extends DocShape>(\n schema: T,\n): InferPlaceholderType<T> {\n const result: Record<string, unknown> = {}\n\n for (const [key, shape] of Object.entries(schema.shapes)) {\n result[key] = deriveShapePlaceholder(shape)\n }\n\n return result as InferPlaceholderType<T>\n}\n\n/**\n * Derives placeholder for a single shape.\n *\n * Leaf nodes: return _placeholder directly\n * Containers: recurse into nested shapes (ignore _placeholder on containers)\n */\nexport function deriveShapePlaceholder(shape: ContainerOrValueShape): unknown {\n switch (shape._type) {\n // Leaf containers - use _placeholder directly\n case \"text\":\n return shape._placeholder\n case \"counter\":\n return shape._placeholder\n\n // Dynamic containers - always empty (no per-entry merging)\n case \"list\":\n case \"movableList\":\n case \"tree\":\n return []\n case \"record\":\n return {}\n\n // Structured container - recurse into nested shapes\n case \"struct\": {\n const result: Record<string, unknown> = {}\n for (const [key, nestedShape] of Object.entries(shape.shapes)) {\n result[key] = deriveShapePlaceholder(nestedShape)\n }\n return result\n }\n\n case \"value\":\n return deriveValueShapePlaceholder(shape)\n\n default:\n return undefined\n }\n}\n\nfunction deriveValueShapePlaceholder(shape: ValueShape): unknown {\n switch (shape.valueType) {\n // Leaf values - use _placeholder directly\n case \"string\":\n return shape._placeholder\n case \"number\":\n return shape._placeholder\n case \"boolean\":\n return shape._placeholder\n case \"null\":\n return null\n case \"undefined\":\n return undefined\n case \"uint8array\":\n return shape._placeholder\n\n // Structured value - recurse into nested shapes (like struct)\n case \"struct\": {\n const result: Record<string, unknown> = {}\n for (const [key, nestedShape] of Object.entries(shape.shape)) {\n result[key] = deriveValueShapePlaceholder(nestedShape)\n }\n return result\n }\n\n // Dynamic values - always empty\n case \"array\":\n return []\n case \"record\":\n return {}\n\n // Unions - use _placeholder if explicitly set, otherwise derive from first variant\n case \"union\": {\n // Check if _placeholder was explicitly set (not the default empty object)\n // We need to check if it's a primitive value OR a non-empty object\n const placeholder = shape._placeholder\n if (placeholder !== undefined) {\n // If it's a primitive (null, string, number, boolean), use it\n if (placeholder === null || typeof placeholder !== \"object\") {\n return placeholder\n }\n // If it's an object with keys, use it\n if (Object.keys(placeholder as object).length > 0) {\n return placeholder\n }\n }\n // Otherwise derive from first variant\n return deriveValueShapePlaceholder(shape.shapes[0])\n }\n\n case \"discriminatedUnion\": {\n // Check if _placeholder was explicitly set (not the default empty object)\n const placeholder = shape._placeholder\n if (placeholder !== undefined) {\n // If it's a primitive (null, string, number, boolean), use it\n if (placeholder === null || typeof placeholder !== \"object\") {\n return placeholder\n }\n // If it's an object with keys, use it\n if (Object.keys(placeholder as object).length > 0) {\n return placeholder\n }\n }\n // Otherwise derive from first variant\n const firstKey = Object.keys(shape.variants)[0]\n return deriveValueShapePlaceholder(shape.variants[firstKey])\n }\n\n default:\n return undefined\n }\n}\n","import type { LoroDoc } from \"loro-crdt\"\nimport type { DocShape } from \"./shape.js\"\nimport type { TypedDoc } from \"./typed-doc.js\"\nimport type { Mutable } from \"./types.js\"\n\n/**\n * The primary method of mutating typed documents.\n * Batches multiple mutations into a single transaction.\n * All changes commit together at the end.\n *\n * Use this for:\n * - Find-and-mutate operations (required due to JS limitations)\n * - Performance (fewer commits)\n * - Atomic undo (all changes = one undo step)\n *\n * Returns the doc for chaining.\n *\n * @param doc - The TypedDoc to mutate\n * @param fn - Function that performs mutations on the draft\n * @returns The same TypedDoc for chaining\n *\n * @example\n * ```typescript\n * import { change } from \"@loro-extended/change\"\n *\n * // Chainable API\n * change(doc, draft => {\n * draft.count.increment(10)\n * draft.title.update(\"Hello\")\n * })\n * .count.increment(5) // Optional: continue mutating\n * .toJSON() // Optional: get last item snapshot when needed\n * ```\n */\nexport function change<Shape extends DocShape>(\n doc: TypedDoc<Shape>,\n fn: (draft: Mutable<Shape>) => void,\n): TypedDoc<Shape> {\n return doc.$.change(fn)\n}\n\n/**\n * Access the underlying LoroDoc for advanced operations.\n *\n * @param doc - The TypedDoc to unwrap\n * @returns The underlying LoroDoc instance\n *\n * @example\n * ```typescript\n * import { getLoroDoc } from \"@loro-extended/change\"\n *\n * const loroDoc = getLoroDoc(doc)\n * const version = loroDoc.version()\n * loroDoc.subscribe(() => console.log(\"changed\"))\n * ```\n */\nexport function getLoroDoc<Shape extends DocShape>(\n doc: TypedDoc<Shape>,\n): LoroDoc {\n return doc.$.loroDoc\n}\n","import type {\n Container,\n LoroCounter,\n LoroList,\n LoroMap,\n LoroMovableList,\n LoroText,\n LoroTree,\n LoroTreeNode,\n Value,\n} from \"loro-crdt\"\nimport type {\n ContainerOrValueShape,\n ContainerShape,\n CounterContainerShape,\n ListContainerShape,\n MovableListContainerShape,\n RecordContainerShape,\n StructContainerShape,\n TextContainerShape,\n TreeContainerShape,\n ValueShape,\n} from \"../shape.js\"\n\nexport { isContainer, isContainerId } from \"loro-crdt\"\n\n/**\n * Type guard to check if a container is a LoroCounter\n */\nexport function isLoroCounter(container: Container): container is LoroCounter {\n return container.kind() === \"Counter\"\n}\n\n/**\n * Type guard to check if a container is a LoroList\n */\nexport function isLoroList(container: Container): container is LoroList {\n return container.kind() === \"List\"\n}\n\n/**\n * Type guard to check if a container is a LoroMap\n */\nexport function isLoroMap(container: Container): container is LoroMap {\n return container.kind() === \"Map\"\n}\n\n/**\n * Type guard to check if a container is a LoroMovableList\n */\nexport function isLoroMovableList(\n container: Container,\n): container is LoroMovableList {\n return container.kind() === \"MovableList\"\n}\n\n/**\n * Type guard to check if a container is a LoroText\n */\nexport function isLoroText(container: Container): container is LoroText {\n return container.kind() === \"Text\"\n}\n\n/**\n * Type guard to check if a container is a LoroTree\n */\nexport function isLoroTree(container: Container): container is LoroTree {\n return container.kind() === \"Tree\"\n}\n\n/**\n * Type guard to check if an object is a LoroTreeNode\n * Note: LoroTreeNode is not a Container, so we check for its specific properties\n */\nexport function isLoroTreeNode(obj: any): obj is LoroTreeNode {\n return (\n obj &&\n typeof obj === \"object\" &&\n typeof obj.id === \"string\" &&\n typeof obj.data === \"object\" &&\n typeof obj.parent === \"function\" &&\n typeof obj.children === \"function\" &&\n typeof obj.createNode === \"function\"\n )\n}\n\n/**\n * Type guard to ensure cached container matches expected type using kind() method\n */\nexport function assertContainerType<T extends Container>(\n cached: Container,\n expected: T,\n context: string = \"container operation\",\n): asserts cached is T {\n if (cached.kind() !== expected.kind()) {\n throw new Error(\n `Type safety violation in ${context}: ` +\n `cached container kind '${cached.kind()}' does not match ` +\n `expected kind '${expected.kind()}'`,\n )\n }\n\n // Additional safety check: ensure IDs match\n if (cached.id !== expected.id) {\n throw new Error(\n `Container ID mismatch in ${context}: ` +\n `cached ID '${cached.id}' does not match expected ID '${expected.id}'`,\n )\n }\n}\n\n/**\n * Type guard to check if a schema is for TextDraftNode\n */\nexport function isTextShape(\n schema: ContainerOrValueShape,\n): schema is TextContainerShape {\n return schema && typeof schema === \"object\" && schema._type === \"text\"\n}\n\n/**\n * Type guard to check if a schema is for CounterDraftNode\n */\nexport function isCounterShape(\n schema: ContainerOrValueShape,\n): schema is CounterContainerShape {\n return schema && typeof schema === \"object\" && schema._type === \"counter\"\n}\n\n/**\n * Type guard to check if a schema is for ListDraftNode\n */\nexport function isListShape(\n schema: ContainerOrValueShape,\n): schema is ListContainerShape {\n return schema && typeof schema === \"object\" && schema._type === \"list\"\n}\n\n/**\n * Type guard to check if a schema is for MovableListDraftNode\n */\nexport function isMovableListShape(\n schema: ContainerOrValueShape,\n): schema is MovableListContainerShape {\n return schema && typeof schema === \"object\" && schema._type === \"movableList\"\n}\n\n/**\n * Type guard to check if a schema is for StructDraftNode\n */\nexport function isStructShape(\n schema: ContainerOrValueShape,\n): schema is StructContainerShape {\n return schema && typeof schema === \"object\" && schema._type === \"struct\"\n}\n\n/**\n * @deprecated Use isStructShape instead. isMapShape is an alias for backward compatibility.\n */\nexport const isMapShape = isStructShape\n\n/**\n * Type guard to check if a schema is for RecordDraftNode\n */\nexport function isRecordShape(\n schema: ContainerOrValueShape,\n): schema is RecordContainerShape {\n return schema && typeof schema === \"object\" && schema._type === \"record\"\n}\n\n/**\n * Type guard to check if a schema is for TreeDraftNode\n */\nexport function isTreeShape(\n schema: ContainerOrValueShape,\n): schema is TreeContainerShape {\n return schema && typeof schema === \"object\" && schema._type === \"tree\"\n}\n\nexport function isContainerShape(\n schema: ContainerOrValueShape,\n): schema is ContainerShape {\n return schema._type && schema._type !== \"value\"\n}\n\n/**\n * Type guard to check if a schema is any of the Value shapes\n */\nexport function isValueShape(\n schema: ContainerOrValueShape,\n): schema is ValueShape {\n return (\n schema._type === \"value\" &&\n [\n \"string\",\n \"number\",\n \"boolean\",\n \"null\",\n \"undefined\",\n \"uint8array\",\n \"struct\",\n \"record\",\n \"array\",\n \"union\",\n \"discriminatedUnion\",\n ].includes(schema.valueType)\n )\n}\n\nexport function isObjectValue(value: Value): value is { [key: string]: Value } {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n !(value instanceof Uint8Array)\n )\n}\n","import type { Value } from \"loro-crdt\"\nimport { deriveShapePlaceholder } from \"./derive-placeholder.js\"\nimport type {\n ContainerShape,\n DiscriminatedUnionValueShape,\n DocShape,\n ValueShape,\n} from \"./shape.js\"\nimport { isObjectValue } from \"./utils/type-guards.js\"\n\n/**\n * Overlays CRDT state with placeholder defaults\n */\nexport function overlayPlaceholder<Shape extends DocShape>(\n shape: Shape,\n crdtValue: { [key: string]: Value },\n placeholderValue: { [key: string]: Value },\n): { [key: string]: Value } {\n if (typeof crdtValue !== \"object\") {\n throw new Error(\"crdt object is required\")\n }\n\n if (typeof placeholderValue !== \"object\") {\n throw new Error(\"placeholder object is required\")\n }\n\n const result = { ...placeholderValue }\n\n for (const [key, propShape] of Object.entries(shape.shapes)) {\n const propCrdtValue = crdtValue[key]\n\n const propPlaceholderValue =\n placeholderValue[key as keyof typeof placeholderValue]\n\n result[key as keyof typeof result] = mergeValue(\n propShape,\n propCrdtValue,\n propPlaceholderValue,\n )\n }\n\n return result\n}\n\n/**\n * Merges individual CRDT values with placeholder defaults\n */\nexport function mergeValue<Shape extends ContainerShape | ValueShape>(\n shape: Shape,\n crdtValue: Value,\n placeholderValue: Value,\n): Value {\n if (crdtValue === undefined && placeholderValue === undefined) {\n throw new Error(\"either crdt or placeholder value must be defined\")\n }\n\n switch (shape._type) {\n case \"text\":\n return crdtValue !== undefined ? crdtValue : (placeholderValue ?? \"\")\n case \"counter\":\n return crdtValue !== undefined ? crdtValue : (placeholderValue ?? 0)\n case \"list\":\n case \"movableList\": {\n if (crdtValue === undefined) {\n return placeholderValue ?? []\n }\n\n const crdtArray = crdtValue as Value[]\n const itemShape = shape.shape\n const itemPlaceholder = deriveShapePlaceholder(itemShape)\n\n return crdtArray.map(item =>\n mergeValue(itemShape, item, itemPlaceholder as Value),\n )\n }\n case \"struct\": {\n if (!isObjectValue(crdtValue) && crdtValue !== undefined) {\n throw new Error(\"struct crdt must be object\")\n }\n\n const crdtStructValue = crdtValue ?? {}\n\n if (!isObjectValue(placeholderValue) && placeholderValue !== undefined) {\n throw new Error(\"struct placeholder must be object\")\n }\n\n const placeholderStructValue = placeholderValue ?? {}\n\n const result = { ...placeholderStructValue }\n for (const [key, nestedShape] of Object.entries(shape.shapes)) {\n const nestedCrdtValue = crdtStructValue[key]\n const nestedPlaceholderValue = placeholderStructValue[key]\n\n result[key as keyof typeof result] = mergeValue(\n nestedShape,\n nestedCrdtValue,\n nestedPlaceholderValue,\n )\n }\n\n return result\n }\n case \"tree\":\n return crdtValue !== undefined ? crdtValue : (placeholderValue ?? [])\n case \"record\": {\n if (!isObjectValue(crdtValue) && crdtValue !== undefined) {\n throw new Error(\"record crdt must be object\")\n }\n\n const crdtRecordValue = (crdtValue as Record<string, Value>) ?? {}\n const result: Record<string, Value> = {}\n\n // For records, we iterate over the keys present in the CRDT value\n // and apply the nested shape's placeholder logic to each value\n for (const key of Object.keys(crdtRecordValue)) {\n const nestedCrdtValue = crdtRecordValue[key]\n // For records, the placeholder is always {}, so we need to derive\n // the placeholder for the nested shape on the fly\n const nestedPlaceholderValue = deriveShapePlaceholder(shape.shape)\n\n result[key] = mergeValue(\n shape.shape,\n nestedCrdtValue,\n nestedPlaceholderValue as Value,\n )\n }\n\n return result\n }\n default:\n if (shape._type === \"value\" && shape.valueType === \"struct\") {\n const crdtObj = (crdtValue as any) ?? {}\n const placeholderObj = (placeholderValue as any) ?? {}\n const result = { ...placeholderObj }\n\n if (typeof crdtObj !== \"object\" || crdtObj === null) {\n return crdtValue !== undefined ? crdtValue : placeholderValue\n }\n\n for (const [key, propShape] of Object.entries(shape.shape)) {\n const propCrdt = crdtObj[key]\n const propPlaceholder = placeholderObj[key]\n result[key] = mergeValue(propShape, propCrdt, propPlaceholder)\n }\n return result\n }\n\n // Handle discriminated unions\n if (shape._type === \"value\" && shape.valueType === \"discriminatedUnion\") {\n return mergeDiscriminatedUnion(\n shape as DiscriminatedUnionValueShape,\n crdtValue,\n placeholderValue,\n )\n }\n\n return crdtValue !== undefined ? crdtValue : placeholderValue\n }\n}\n\n/**\n * Merges a discriminated union value by determining the variant from the discriminant key.\n * Uses the placeholderValue's discriminant to determine the default variant when the discriminant is missing.\n */\nfunction mergeDiscriminatedUnion(\n shape: DiscriminatedUnionValueShape,\n crdtValue: Value,\n placeholderValue: Value,\n): Value {\n const crdtObj = (crdtValue as Record<string, Value>) ?? {}\n const placeholderObj = (placeholderValue as Record<string, Value>) ?? {}\n\n // Get the discriminant value from CRDT, falling back to placeholder\n const discriminantValue =\n crdtObj[shape.discriminantKey] ?? placeholderObj[shape.discriminantKey]\n\n if (typeof discriminantValue !== \"string\") {\n // If no valid discriminant, return the placeholder\n return placeholderValue\n }\n\n // Find the variant shape for this discriminant value\n const variantShape = shape.variants[discriminantValue]\n\n if (!variantShape) {\n // Unknown variant - return CRDT value or placeholder\n return crdtValue !== undefined ? crdtValue : placeholderValue\n }\n\n // Merge using the variant's object shape\n // If the placeholder's discriminant doesn't match the current discriminant,\n // we shouldn't use the placeholder for merging as it belongs to a different variant.\n const placeholderDiscriminant = placeholderObj[shape.discriminantKey]\n const effectivePlaceholderValue =\n placeholderDiscriminant === discriminantValue ? placeholderValue : undefined\n\n return mergeValue(variantShape, crdtValue, effectivePlaceholderValue as Value)\n}\n","/**\n * Creates a proxy around a placeholder value (plain object/array) that mimics\n * the behavior of TypedRef, specifically adding a .toJSON() method.\n *\n * This ensures consistent UX where users can call .toJSON() on document state\n * regardless of whether it's loading (placeholder) or loaded (live ref).\n */\nexport function createPlaceholderProxy<T extends object>(target: T): T {\n // Cache for wrapped properties to ensure referential stability\n const cache = new Map<string | symbol, any>()\n\n return new Proxy(target, {\n get(target, prop, receiver) {\n // Intercept .toJSON()\n if (prop === \"toJSON\") {\n return () => target\n }\n\n // Check cache first\n if (cache.has(prop)) {\n return cache.get(prop)\n }\n\n // Get value from target\n const value = Reflect.get(target, prop, receiver)\n\n // Recursively wrap objects/arrays\n if (value && typeof value === \"object\") {\n const wrapped = createPlaceholderProxy(value)\n cache.set(prop, wrapped)\n return wrapped\n }\n\n return value\n },\n })\n}\n","// biome-ignore-all lint/suspicious/noExplicitAny: required\n\nimport type {\n LoroCounter,\n LoroList,\n LoroMap,\n LoroMovableList,\n LoroText,\n LoroTree,\n} from \"loro-crdt\"\n\nimport type { CounterRef } from \"./typed-refs/counter.js\"\nimport type { ListRef } from \"./typed-refs/list.js\"\nimport type { MovableListRef } from \"./typed-refs/movable-list.js\"\nimport type { RecordRef } from \"./typed-refs/record.js\"\nimport type { StructRef } from \"./typed-refs/struct.js\"\nimport type { TextRef } from \"./typed-refs/text.js\"\n\nexport interface Shape<Plain, Mutable, Placeholder = Plain> {\n readonly _type: string\n readonly _plain: Plain\n readonly _mutable: Mutable\n readonly _placeholder: Placeholder\n}\n\n// Type for shapes that support placeholder customization\nexport type WithPlaceholder<S extends Shape<any, any, any>> = S & {\n placeholder(value: S[\"_placeholder\"]): S\n}\n\nexport interface DocShape<\n NestedShapes extends Record<string, ContainerShape> = Record<\n string,\n ContainerShape\n >,\n> extends Shape<\n { [K in keyof NestedShapes]: NestedShapes[K][\"_plain\"] },\n { [K in keyof NestedShapes]: NestedShapes[K][\"_mutable\"] },\n { [K in keyof NestedShapes]: NestedShapes[K][\"_placeholder\"] }\n > {\n readonly _type: \"doc\"\n // A doc's root containers each separately has its own shape, hence 'shapes'\n readonly shapes: NestedShapes\n}\n\nexport interface TextContainerShape extends Shape<string, TextRef, string> {\n readonly _type: \"text\"\n}\nexport interface CounterContainerShape\n extends Shape<number, CounterRef, number> {\n readonly _type: \"counter\"\n}\nexport interface TreeContainerShape<NestedShape = ContainerOrValueShape>\n extends Shape<any, any, never[]> {\n readonly _type: \"tree\"\n // TODO(duane): What does a tree contain? One type, or many?\n readonly shape: NestedShape\n}\n\n// Container schemas using interfaces for recursive references\n// NOTE: List and Record use never[] and Record<string, never> for Placeholder\n// to enforce that only empty values ([] and {}) are valid in placeholder state.\n// This prevents users from expecting per-entry merging behavior.\nexport interface ListContainerShape<\n NestedShape extends ContainerOrValueShape = ContainerOrValueShape,\n> extends Shape<NestedShape[\"_plain\"][], ListRef<NestedShape>, never[]> {\n readonly _type: \"list\"\n // A list contains many elements, all of the same 'shape'\n readonly shape: NestedShape\n}\n\nexport interface MovableListContainerShape<\n NestedShape extends ContainerOrValueShape = ContainerOrValueShape,\n> extends Shape<NestedShape[\"_plain\"][], MovableListRef<NestedShape>, never[]> {\n readonly _type: \"movableList\"\n // A list contains many elements, all of the same 'shape'\n readonly shape: NestedShape\n}\n\n/**\n * @deprecated Use StructContainerShape instead. MapContainerShape is an alias for backward compatibility.\n */\nexport type MapContainerShape<\n NestedShapes extends Record<string, ContainerOrValueShape> = Record<\n string,\n ContainerOrValueShape\n >,\n> = StructContainerShape<NestedShapes>\n\n/**\n * Container shape for objects with fixed keys (structs).\n * This is the preferred way to define fixed-key objects.\n * Uses LoroMap as the underlying container.\n */\nexport interface StructContainerShape<\n NestedShapes extends Record<string, ContainerOrValueShape> = Record<\n string,\n ContainerOrValueShape\n >,\n> extends Shape<\n { [K in keyof NestedShapes]: NestedShapes[K][\"_plain\"] },\n StructRef<NestedShapes> & {\n [K in keyof NestedShapes]: NestedShapes[K][\"_mutable\"]\n },\n { [K in keyof NestedShapes]: NestedShapes[K][\"_placeholder\"] }\n > {\n readonly _type: \"struct\"\n // Each struct property has its own shape, hence 'shapes'\n readonly shapes: NestedShapes\n}\n\nexport interface RecordContainerShape<\n NestedShape extends ContainerOrValueShape = ContainerOrValueShape,\n> extends Shape<\n Record<string, NestedShape[\"_plain\"]>,\n RecordRef<NestedShape>,\n Record<string, never>\n > {\n readonly _type: \"record\"\n readonly shape: NestedShape\n}\n\nexport type ContainerShape =\n | CounterContainerShape\n | ListContainerShape\n | MovableListContainerShape\n | RecordContainerShape\n | StructContainerShape\n | TextContainerShape\n | TreeContainerShape\n\nexport type ContainerType = ContainerShape[\"_type\"]\n\n// LoroValue shape types - a shape for each of Loro's Value types\nexport interface StringValueShape<T extends string = string>\n extends Shape<T, T, T> {\n readonly _type: \"value\"\n readonly valueType: \"string\"\n readonly options?: T[]\n}\nexport interface NumberValueShape extends Shape<number, number, number> {\n readonly _type: \"value\"\n readonly valueType: \"number\"\n}\nexport interface BooleanValueShape extends Shape<boolean, boolean, boolean> {\n readonly _type: \"value\"\n readonly valueType: \"boolean\"\n}\nexport interface NullValueShape extends Shape<null, null, null> {\n readonly _type: \"value\"\n readonly valueType: \"null\"\n}\nexport interface UndefinedValueShape\n extends Shape<undefined, undefined, undefined> {\n readonly _type: \"value\"\n readonly valueType: \"undefined\"\n}\nexport interface Uint8ArrayValueShape\n extends Shape<Uint8Array, Uint8Array, Uint8Array> {\n readonly _type: \"value\"\n readonly valueType: \"uint8array\"\n}\n\n/**\n * @deprecated Use StructValueShape instead. ObjectValueShape is an alias for backward compatibility.\n */\nexport type ObjectValueShape<\n T extends Record<string, ValueShape> = Record<string, ValueShape>,\n> = StructValueShape<T>\n\n/**\n * Value shape for objects with fixed keys (structs).\n * This is the preferred way to define fixed-key plain value objects.\n * Identical structure to ObjectValueShape but with valueType: \"struct\".\n */\nexport interface StructValueShape<\n T extends Record<string, ValueShape> = Record<string, ValueShape>,\n> extends Shape<\n { [K in keyof T]: T[K][\"_plain\"] },\n { [K in keyof T]: T[K][\"_mutable\"] },\n { [K in keyof T]: T[K][\"_placeholder\"] }\n > {\n readonly _type: \"value\"\n readonly valueType: \"struct\"\n readonly shape: T\n}\n\n// NOTE: RecordValueShape and ArrayValueShape use Record<string, never> and never[]\n// for Placeholder to enforce that only empty values ({} and []) are valid.\nexport interface RecordValueShape<T extends ValueShape = ValueShape>\n extends Shape<\n Record<string, T[\"_plain\"]>,\n Record<string, T[\"_mutable\"]>,\n Record<string, never>\n > {\n readonly _type: \"value\"\n readonly valueType: \"record\"\n readonly shape: T\n}\n\nexport interface ArrayValueShape<T extends ValueShape = ValueShape>\n extends Shape<T[\"_plain\"][], T[\"_mutable\"][], never[]> {\n readonly _type: \"value\"\n readonly valueType: \"array\"\n readonly shape: T\n}\n\nexport interface UnionValueShape<T extends ValueShape[] = ValueShape[]>\n extends Shape<\n T[number][\"_plain\"],\n T[number][\"_mutable\"],\n T[number][\"_placeholder\"]\n > {\n readonly _type: \"value\"\n readonly valueType: \"union\"\n readonly shapes: T\n}\n\n/**\n * A discriminated union shape that uses a discriminant key to determine which variant to use.\n * This enables type-safe handling of tagged unions like:\n *\n * ```typescript\n * type GamePresence =\n * | { type: \"client\"; name: string; input: { force: number; angle: number } }\n * | { type: \"server\"; cars: Record<string, CarState>; tick: number }\n * ```\n *\n * @typeParam K - The discriminant key (e.g., \"type\")\n * @typeParam T - A record mapping discriminant values to their object shapes\n */\nexport interface DiscriminatedUnionValueShape<\n K extends string = string,\n T extends Record<string, StructValueShape> = Record<string, StructValueShape>,\n Plain = T[keyof T][\"_plain\"],\n Mutable = T[keyof T][\"_mutable\"],\n Placeholder = T[keyof T][\"_placeholder\"],\n> extends Shape<Plain, Mutable, Placeholder> {\n readonly _type: \"value\"\n readonly valueType: \"discriminatedUnion\"\n readonly discriminantKey: K\n readonly variants: T\n}\n\n// Union of all ValueShapes - these can only contain other ValueShapes, not ContainerShapes\nexport type ValueShape =\n | StringValueShape\n | NumberValueShape\n | BooleanValueShape\n | NullValueShape\n | UndefinedValueShape\n | Uint8ArrayValueShape\n | StructValueShape\n | RecordValueShape\n | ArrayValueShape\n | UnionValueShape\n | DiscriminatedUnionValueShape\n\nexport type ContainerOrValueShape = ContainerShape | ValueShape\n\n/**\n * The LoroShape factory object\n *\n * If a container has a `shape` type variable, it refers to the shape it contains--\n * so for example, a `LoroShape.list(LoroShape.text())` would return a value of type\n * `ListContainerShape<TextContainerShape>`.\n */\nexport const Shape = {\n doc: <T extends Record<string, ContainerShape>>(shape: T): DocShape<T> => ({\n _type: \"doc\" as const,\n shapes: shape,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as any,\n }),\n\n // CRDTs are represented by Loro Containers--they converge on state using Loro's\n // various CRDT algorithms\n counter: (): WithPlaceholder<CounterContainerShape> => {\n const base: CounterContainerShape = {\n _type: \"counter\" as const,\n _plain: 0,\n _mutable: {} as CounterRef,\n _placeholder: 0,\n }\n return Object.assign(base, {\n placeholder(value: number): CounterContainerShape {\n return { ...base, _placeholder: value }\n },\n })\n },\n\n list: <T extends ContainerOrValueShape>(shape: T): ListContainerShape<T> => ({\n _type: \"list\" as const,\n shape,\n _plain: [] as any,\n _mutable: {} as any,\n _placeholder: [] as never[],\n }),\n\n /**\n * Creates a struct container shape for objects with fixed keys.\n * This is the preferred way to define fixed-key objects.\n *\n * @example\n * ```typescript\n * const UserSchema = Shape.doc({\n * user: Shape.struct({\n * name: Shape.text(),\n * age: Shape.counter(),\n * }),\n * })\n * ```\n */\n struct: <T extends Record<string, ContainerOrValueShape>>(\n shape: T,\n ): StructContainerShape<T> => ({\n _type: \"struct\" as const,\n shapes: shape,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as any,\n }),\n\n /**\n * @deprecated Use `Shape.struct` instead. `Shape.struct` will be removed in a future version.\n */\n map: <T extends Record<string, ContainerOrValueShape>>(\n shape: T,\n ): StructContainerShape<T> => ({\n _type: \"struct\" as const,\n shapes: shape,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as any,\n }),\n\n record: <T extends ContainerOrValueShape>(\n shape: T,\n ): RecordContainerShape<T> => ({\n _type: \"record\" as const,\n shape,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as Record<string, never>,\n }),\n\n movableList: <T extends ContainerOrValueShape>(\n shape: T,\n ): MovableListContainerShape<T> => ({\n _type: \"movableList\" as const,\n shape,\n _plain: [] as any,\n _mutable: {} as any,\n _placeholder: [] as never[],\n }),\n\n text: (): WithPlaceholder<TextContainerShape> => {\n const base: TextContainerShape = {\n _type: \"text\" as const,\n _plain: \"\",\n _mutable: {} as TextRef,\n _placeholder: \"\",\n }\n return Object.assign(base, {\n placeholder(value: string): TextContainerShape {\n return { ...base, _placeholder: value }\n },\n })\n },\n\n tree: <T extends MapContainerShape | StructContainerShape>(\n shape: T,\n ): TreeContainerShape => ({\n _type: \"tree\" as const,\n shape,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: [] as never[],\n }),\n\n // Values are represented as plain JS objects, with the limitation that they MUST be\n // representable as a Loro \"Value\"--basically JSON. The behavior of a Value is basically\n // \"Last Write Wins\", meaning there is no subtle convergent behavior here, just taking\n // the most recent value based on the current available information.\n plain: {\n string: <T extends string = string>(\n ...options: T[]\n ): WithPlaceholder<StringValueShape<T>> => {\n const base: StringValueShape<T> = {\n _type: \"value\" as const,\n valueType: \"string\" as const,\n _plain: (options[0] ?? \"\") as T,\n _mutable: (options[0] ?? \"\") as T,\n _placeholder: (options[0] ?? \"\") as T,\n options: options.length > 0 ? options : undefined,\n }\n return Object.assign(base, {\n placeholder(value: T): StringValueShape<T> {\n return { ...base, _placeholder: value }\n },\n })\n },\n\n number: (): WithPlaceholder<NumberValueShape> => {\n const base: NumberValueShape = {\n _type: \"value\" as const,\n valueType: \"number\" as const,\n _plain: 0,\n _mutable: 0,\n _placeholder: 0,\n }\n return Object.assign(base, {\n placeholder(value: number): NumberValueShape {\n return { ...base, _placeholder: value }\n },\n })\n },\n\n boolean: (): WithPlaceholder<BooleanValueShape> => {\n const base: BooleanValueShape = {\n _type: \"value\" as const,\n valueType: \"boolean\" as const,\n _plain: false,\n _mutable: false,\n _placeholder: false,\n }\n return Object.assign(base, {\n placeholder(value: boolean): BooleanValueShape {\n return { ...base, _placeholder: value }\n },\n })\n },\n\n null: (): NullValueShape => ({\n _type: \"value\" as const,\n valueType: \"null\" as const,\n _plain: null,\n _mutable: null,\n _placeholder: null,\n }),\n\n undefined: (): UndefinedValueShape => ({\n _type: \"value\" as const,\n valueType: \"undefined\" as const,\n _plain: undefined,\n _mutable: undefined,\n _placeholder: undefined,\n }),\n\n uint8Array: (): Uint8ArrayValueShape => ({\n _type: \"value\" as const,\n valueType: \"uint8array\" as const,\n _plain: new Uint8Array(),\n _mutable: new Uint8Array(),\n _placeholder: new Uint8Array(),\n }),\n\n /**\n * Creates a struct value shape for plain objects with fixed keys.\n * This is the preferred way to define fixed-key plain value objects.\n *\n * @example\n * ```typescript\n * const PointSchema = Shape.plain.struct({\n * x: Shape.plain.number(),\n * y: Shape.plain.number(),\n * })\n * ```\n */\n struct: <T extends Record<string, ValueShape>>(\n shape: T,\n ): StructValueShape<T> => ({\n _type: \"value\" as const,\n valueType: \"struct\" as const,\n shape,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as any,\n }),\n\n /**\n * @deprecated Use `Shape.plain.struct` instead. `Shape.plain.struct` will be removed in a future version.\n */\n object: <T extends Record<string, ValueShape>>(\n shape: T,\n ): StructValueShape<T> => ({\n _type: \"value\" as const,\n valueType: \"struct\" as const,\n shape,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as any,\n }),\n\n record: <T extends ValueShape>(shape: T): RecordValueShape<T> => ({\n _type: \"value\" as const,\n valueType: \"record\" as const,\n shape,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as Record<string, never>,\n }),\n\n array: <T extends ValueShape>(shape: T): ArrayValueShape<T> => ({\n _type: \"value\" as const,\n valueType: \"array\" as const,\n shape,\n _plain: [] as any,\n _mutable: [] as any,\n _placeholder: [] as never[],\n }),\n\n // Special value type that helps make things like `string | null` representable\n // TODO(duane): should this be a more general type for containers too?\n union: <T extends ValueShape[]>(\n shapes: T,\n ): WithPlaceholder<UnionValueShape<T>> => {\n const base: UnionValueShape<T> = {\n _type: \"value\" as const,\n valueType: \"union\" as const,\n shapes,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as any,\n }\n return Object.assign(base, {\n placeholder(value: T[number][\"_placeholder\"]): UnionValueShape<T> {\n return { ...base, _placeholder: value }\n },\n })\n },\n\n /**\n * Creates a discriminated union shape for type-safe tagged unions.\n *\n * @example\n * ```typescript\n * const ClientPresenceShape = Shape.plain.struct({\n * type: Shape.plain.string(\"client\"),\n * name: Shape.plain.string(),\n * input: Shape.plain.struct({ force: Shape.plain.number(), angle: Shape.plain.number() }),\n * })\n *\n * const ServerPresenceShape = Shape.plain.struct({\n * type: Shape.plain.string(\"server\"),\n * cars: Shape.plain.record(Shape.plain.struct({ x: Shape.plain.number(), y: Shape.plain.number() })),\n * tick: Shape.plain.number(),\n * })\n *\n * const GamePresenceSchema = Shape.plain.discriminatedUnion(\"type\", {\n * client: ClientPresenceShape,\n * server: ServerPresenceShape,\n * })\n * ```\n *\n * @param discriminantKey - The key used to discriminate between variants (e.g., \"type\")\n * @param variants - A record mapping discriminant values to their object shapes\n */\n discriminatedUnion: <\n K extends string,\n T extends Record<string, StructValueShape>,\n >(\n discriminantKey: K,\n variants: T,\n ): WithPlaceholder<DiscriminatedUnionValueShape<K, T>> => {\n const base: DiscriminatedUnionValueShape<K, T> = {\n _type: \"value\" as const,\n valueType: \"discriminatedUnion\" as const,\n discriminantKey,\n variants,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as any,\n }\n return Object.assign(base, {\n placeholder(\n value: T[keyof T][\"_placeholder\"],\n ): DiscriminatedUnionValueShape<K, T> {\n return { ...base, _placeholder: value }\n },\n })\n },\n },\n}\n\n// Add this type mapping near the top of your file, after the imports\nexport type ShapeToContainer<T extends DocShape | ContainerShape> =\n T extends TextContainerShape\n ? LoroText\n : T extends CounterContainerShape\n ? LoroCounter\n : T extends ListContainerShape\n ? LoroList\n : T extends MovableListContainerShape\n ? LoroMovableList\n : T extends StructContainerShape | RecordContainerShape\n ? LoroMap\n : T extends TreeContainerShape\n ? LoroTree\n : never // not a container\n","/** biome-ignore-all lint/suspicious/noExplicitAny: fix later */\n\nimport { LoroDoc } from \"loro-crdt\"\nimport { derivePlaceholder } from \"./derive-placeholder.js\"\nimport {\n type JsonPatch,\n JsonPatchApplicator,\n type JsonPatchOperation,\n normalizePath,\n} from \"./json-patch.js\"\nimport { overlayPlaceholder } from \"./overlay.js\"\nimport type { DocShape } from \"./shape.js\"\nimport { DocRef } from \"./typed-refs/doc.js\"\nimport type { Infer, InferPlaceholderType, Mutable } from \"./types.js\"\nimport { validatePlaceholder } from \"./validation.js\"\n\n/**\n * Meta-operations namespace for TypedDoc.\n * Access via doc.$ to perform batch operations, serialization, etc.\n */\nexport class TypedDocMeta<Shape extends DocShape> {\n constructor(private internal: TypedDocInternal<Shape>) {}\n\n /**\n * The primary method of mutating typed documents.\n * Batches multiple mutations into a single transaction.\n * All changes commit together at the end.\n *\n * Use this for:\n * - Find-and-mutate operations (required due to JS limitations)\n * - Performance (fewer commits)\n * - Atomic undo (all changes = one undo step)\n *\n * Returns the doc for chaining.\n */\n change(fn: (draft: Mutable<Shape>) => void): TypedDoc<Shape> {\n this.internal.change(fn)\n return this.internal.proxy as TypedDoc<Shape>\n }\n\n /**\n * Returns the full plain JavaScript object representation of the document.\n * This is an expensive O(N) operation that serializes the entire document.\n */\n toJSON(): Infer<Shape> {\n return this.internal.toJSON()\n }\n\n /**\n * Apply JSON Patch operations to the document\n *\n * @param patch - Array of JSON Patch operations (RFC 6902)\n * @param pathPrefix - Optional path prefix for scoped operations\n * @returns Updated document value\n */\n applyPatch(\n patch: JsonPatch,\n pathPrefix?: (string | number)[],\n ): TypedDoc<Shape> {\n this.internal.applyPatch(patch, pathPrefix)\n return this.internal.proxy as TypedDoc<Shape>\n }\n\n /**\n * Access the underlying LoroDoc for advanced operations.\n */\n get loroDoc(): LoroDoc {\n return this.internal.loroDoc\n }\n\n /**\n * Access the document schema shape.\n */\n get docShape(): Shape {\n return this.internal.docShape\n }\n\n /**\n * Get raw CRDT value without placeholder overlay.\n */\n get rawValue(): any {\n return this.internal.rawValue\n }\n}\n\n/**\n * Internal TypedDoc implementation (not directly exposed to users).\n * Users interact with the proxied version that provides direct schema access.\n */\nclass TypedDocInternal<Shape extends DocShape> {\n private shape: Shape\n private placeholder: InferPlaceholderType<Shape>\n private doc: LoroDoc\n private _valueRef: DocRef<Shape> | null = null\n // Reference to the proxy for returning from change()\n proxy: TypedDoc<Shape> | null = null\n\n constructor(shape: Shape, doc: LoroDoc = new LoroDoc()) {\n this.shape = shape\n this.placeholder = derivePlaceholder(shape)\n this.doc = doc\n\n validatePlaceholder(this.placeholder, this.shape)\n }\n\n get value(): Mutable<Shape> {\n if (!this._valueRef) {\n this._valueRef = new DocRef({\n shape: this.shape,\n placeholder: this.placeholder as any,\n doc: this.doc,\n autoCommit: true,\n })\n }\n return this._valueRef as unknown as Mutable<Shape>\n }\n\n toJSON(): Infer<Shape> {\n const crdtValue = this.doc.toJSON()\n return overlayPlaceholder(\n this.shape,\n crdtValue,\n this.placeholder as any,\n ) as Infer<Shape>\n }\n\n change(fn: (draft: Mutable<Shape>) => void): void {\n const draft = new DocRef({\n shape: this.shape,\n placeholder: this.placeholder as any,\n doc: this.doc,\n autoCommit: false,\n })\n fn(draft as unknown as Mutable<Shape>)\n draft.absorbPlainValues()\n this.doc.commit()\n\n // Invalidate cached value ref since doc changed\n this._valueRef = null\n }\n\n applyPatch(patch: JsonPatch, pathPrefix?: (string | number)[]): void {\n this.change(draft => {\n const applicator = new JsonPatchApplicator(draft)\n\n const prefixedPatch = pathPrefix\n ? patch.map((op: JsonPatchOperation) => ({\n ...op,\n path: [...pathPrefix, ...normalizePath(op.path)],\n }))\n : patch\n\n applicator.applyPatch(prefixedPatch)\n })\n }\n\n get loroDoc(): LoroDoc {\n return this.doc\n }\n\n get docShape(): Shape {\n return this.shape\n }\n\n get rawValue(): any {\n return this.doc.toJSON()\n }\n}\n\n/**\n * The proxied TypedDoc type that provides direct schema access.\n * Schema properties are accessed directly on the doc object.\n * Meta-operations are available via the $ namespace.\n *\n * @example\n * ```typescript\n * const doc = createTypedDoc(schema);\n *\n * // Direct schema access\n * doc.count.increment(5);\n * doc.title.insert(0, \"Hello\");\n *\n * // Serialize to JSON (works on doc and all refs)\n * const snapshot = doc.toJSON();\n * const users = doc.users.toJSON();\n *\n * // Meta-operations via $ (escape hatch)\n * doc.$.change(draft => { ... });\n * doc.$.loroDoc;\n * ```\n */\nexport type TypedDoc<Shape extends DocShape> = Mutable<Shape> & {\n /**\n * Meta-operations namespace.\n * Use for change(), loroDoc, etc.\n */\n $: TypedDocMeta<Shape>\n\n /**\n * Returns the full plain JavaScript object representation of the document.\n * This is an O(N) operation that serializes the entire document.\n *\n * @example\n * ```typescript\n * const snapshot = doc.toJSON();\n * console.log(snapshot.count); // number\n * ```\n */\n toJSON(): Infer<Shape>\n}\n\n/**\n * Creates a new TypedDoc with the given schema.\n * Returns a proxied document where schema properties are accessed directly.\n *\n * @param shape - The document schema (with optional .placeholder() values)\n * @param existingDoc - Optional existing LoroDoc to wrap\n * @returns A proxied TypedDoc with direct schema access and $ namespace\n *\n * @example\n * ```typescript\n * const schema = Shape.doc({\n * title: Shape.text(),\n * count: Shape.counter(),\n * });\n *\n * const doc = createTypedDoc(schema);\n *\n * // Direct mutations (auto-commit)\n * doc.count.increment(5);\n * doc.title.insert(0, \"Hello\");\n *\n * // Batched mutations are committed together via `change`\n * doc.$.change(draft => {\n * draft.count.increment(10);\n * draft.title.update(\"World\");\n * });\n *\n * // Get plain JSON\n * const snapshot = doc.toJSON();\n * ```\n */\nexport function createTypedDoc<Shape extends DocShape>(\n shape: Shape,\n existingDoc?: LoroDoc,\n): TypedDoc<Shape> {\n const internal = new TypedDocInternal(shape, existingDoc || new LoroDoc())\n const meta = new TypedDocMeta(internal)\n\n // Create a proxy that delegates schema properties to the DocRef\n // and provides $ namespace for meta-operations\n const proxy = new Proxy(internal.value as object, {\n get(target, prop, receiver) {\n // $ namespace for meta-operations\n if (prop === \"$\") {\n return meta\n }\n\n // toJSON() should always read fresh from the CRDT\n if (prop === \"toJSON\") {\n return () => internal.toJSON()\n }\n\n // Delegate to the DocRef (which is the target)\n return Reflect.get(target, prop, receiver)\n },\n\n set(target, prop, value, receiver) {\n // Don't allow setting $ namespace\n if (prop === \"$\") {\n return false\n }\n\n // Delegate to the DocRef\n return Reflect.set(target, prop, value, receiver)\n },\n\n // Support 'in' operator\n has(target, prop) {\n if (prop === \"$\") return true\n return Reflect.has(target, prop)\n },\n\n // Support Object.keys() - don't include $ in enumeration\n ownKeys(target) {\n return Reflect.ownKeys(target)\n },\n\n getOwnPropertyDescriptor(target, prop) {\n if (prop === \"$\") {\n return {\n configurable: true,\n enumerable: false,\n value: meta,\n }\n }\n return Reflect.getOwnPropertyDescriptor(target, prop)\n },\n }) as TypedDoc<Shape>\n\n // Store reference to proxy for returning from change()\n internal.proxy = proxy\n\n return proxy\n}\n","/** biome-ignore-all lint/suspicious/noExplicitAny: JSON Patch values can be any type */\n\nimport type { DocShape } from \"./shape.js\"\nimport type { Draft } from \"./types.js\"\n\n// =============================================================================\n// JSON PATCH TYPES - Discriminated Union for Type Safety\n// =============================================================================\n\nexport type JsonPatchAddOperation = {\n op: \"add\"\n path: string | (string | number)[]\n value: any\n}\n\nexport type JsonPatchRemoveOperation = {\n op: \"remove\"\n path: string | (string | number)[]\n}\n\nexport type JsonPatchReplaceOperation = {\n op: \"replace\"\n path: string | (string | number)[]\n value: any\n}\n\nexport type JsonPatchMoveOperation = {\n op: \"move\"\n path: string | (string | number)[]\n from: string | (string | number)[]\n}\n\nexport type JsonPatchCopyOperation = {\n op: \"copy\"\n path: string | (string | number)[]\n from: string | (string | number)[]\n}\n\nexport type JsonPatchTestOperation = {\n op: \"test\"\n path: string | (string | number)[]\n value: any\n}\n\nexport type JsonPatchOperation =\n | JsonPatchAddOperation\n | JsonPatchRemoveOperation\n | JsonPatchReplaceOperation\n | JsonPatchMoveOperation\n | JsonPatchCopyOperation\n | JsonPatchTestOperation\n\nexport type JsonPatch = JsonPatchOperation[]\n\n// =============================================================================\n// PATH NAVIGATION UTILITIES\n// =============================================================================\n\n/**\n * Normalize JSON Pointer string to path array\n * Handles RFC 6901 escaping: ~1 -> /, ~0 -> ~\n */\nexport function normalizePath(\n path: string | (string | number)[],\n): (string | number)[] {\n if (Array.isArray(path)) {\n return path\n }\n\n // Handle JSON Pointer format (RFC 6901)\n if (path.startsWith(\"/\")) {\n return path\n .slice(1) // Remove leading slash\n .split(\"/\")\n .map(segment => {\n // Handle JSON Pointer escaping\n const unescaped = segment.replace(/~1/g, \"/\").replace(/~0/g, \"~\")\n // Try to parse as number for array indices\n const asNumber = Number(unescaped)\n return Number.isInteger(asNumber) && asNumber >= 0\n ? asNumber\n : unescaped\n })\n }\n\n // Handle simple dot notation or single segment\n return path.split(\".\").map(segment => {\n const asNumber = Number(segment)\n return Number.isInteger(asNumber) && asNumber >= 0 ? asNumber : segment\n })\n}\n\n/**\n * Navigate to a target path using natural DraftNode property access\n * This follows the existing patterns from the test suite\n */\nfunction navigateToPath<T extends DocShape>(\n draft: Draft<T>,\n path: (string | number)[],\n): { parent: any; key: string | number } {\n if (path.length === 0) {\n throw new Error(\"Cannot navigate to empty path\")\n }\n\n let current = draft as any\n\n // Navigate to parent of target\n for (let i = 0; i < path.length - 1; i++) {\n const segment = path[i]\n\n if (typeof segment === \"string\") {\n // Use natural property access - this leverages existing DraftNode lazy creation\n current = current[segment]\n if (current === undefined) {\n throw new Error(`Cannot navigate to path segment: ${segment}`)\n }\n } else if (typeof segment === \"number\") {\n // List/array access using get() method (following existing patterns)\n if (current.get && typeof current.get === \"function\") {\n current = current.get(segment)\n if (current === undefined) {\n throw new Error(`List index ${segment} does not exist`)\n }\n } else {\n throw new Error(`Cannot use numeric index ${segment} on non-list`)\n }\n } else {\n throw new Error(`Invalid path segment type: ${typeof segment}`)\n }\n }\n\n const targetKey = path[path.length - 1]\n return { parent: current, key: targetKey }\n}\n\n/**\n * Get value at path using natural DraftNode access patterns\n */\nfunction getValueAtPath<T extends DocShape>(\n draft: Draft<T>,\n path: (string | number)[],\n): any {\n if (path.length === 0) {\n return draft\n }\n\n const { parent, key } = navigateToPath(draft, path)\n\n if (typeof key === \"string\") {\n // Use natural property access or get() method\n if (parent.get && typeof parent.get === \"function\") {\n return parent.get(key)\n }\n return parent[key]\n } else if (typeof key === \"number\") {\n // List access using get() method\n if (parent.get && typeof parent.get === \"function\") {\n return parent.get(key)\n }\n throw new Error(`Cannot use numeric index ${key} on non-list`)\n }\n\n throw new Error(`Invalid key type: ${typeof key}`)\n}\n\n// =============================================================================\n// OPERATION HANDLERS - Following existing DraftNode patterns\n// =============================================================================\n\n/**\n * Handle 'add' operation using existing DraftNode methods\n */\nfunction handleAdd<T extends DocShape>(\n draft: Draft<T>,\n operation: JsonPatchAddOperation,\n): void {\n const path = normalizePath(operation.path)\n const { parent, key } = navigateToPath(draft, path)\n\n if (typeof key === \"string\") {\n // Map-like operations - use natural assignment or set() method\n if (parent.set && typeof parent.set === \"function\") {\n parent.set(key, operation.value)\n } else {\n // Natural property assignment (follows existing test patterns)\n parent[key] = operation.value\n }\n } else if (typeof key === \"number\") {\n // List operations - use insert() method (follows existing patterns)\n if (parent.insert && typeof parent.insert === \"function\") {\n parent.insert(key, operation.value)\n } else {\n throw new Error(`Cannot insert at numeric index ${key} on non-list`)\n }\n } else {\n throw new Error(`Invalid key type: ${typeof key}`)\n }\n}\n\n/**\n * Handle 'remove' operation using existing DraftNode methods\n */\nfunction handleRemove<T extends DocShape>(\n draft: Draft<T>,\n operation: JsonPatchRemoveOperation,\n): void {\n const path = normalizePath(operation.path)\n const { parent, key } = navigateToPath(draft, path)\n\n if (typeof key === \"string\") {\n // Map-like operations - use delete() method (follows existing patterns)\n if (parent.delete && typeof parent.delete === \"function\") {\n parent.delete(key)\n } else {\n delete parent[key]\n }\n } else if (typeof key === \"number\") {\n // List operations - use delete() method with count (follows existing patterns)\n if (parent.delete && typeof parent.delete === \"function\") {\n parent.delete(key, 1)\n } else {\n throw new Error(`Cannot remove at numeric index ${key} on non-list`)\n }\n } else {\n throw new Error(`Invalid key type: ${typeof key}`)\n }\n}\n\n/**\n * Handle 'replace' operation using existing DraftNode methods\n */\nfunction handleReplace<T extends DocShape>(\n draft: Draft<T>,\n operation: JsonPatchReplaceOperation,\n): void {\n const path = normalizePath(operation.path)\n const { parent, key } = navigateToPath(draft, path)\n\n if (typeof key === \"string\") {\n // Map-like operations - use set() method or natural assignment\n if (parent.set && typeof parent.set === \"function\") {\n parent.set(key, operation.value)\n } else {\n parent[key] = operation.value\n }\n } else if (typeof key === \"number\") {\n // List operations - delete then insert (follows existing patterns)\n if (\n parent.delete &&\n parent.insert &&\n typeof parent.delete === \"function\" &&\n typeof parent.insert === \"function\"\n ) {\n parent.delete(key, 1)\n parent.insert(key, operation.value)\n } else {\n throw new Error(`Cannot replace at numeric index ${key} on non-list`)\n }\n } else {\n throw new Error(`Invalid key type: ${typeof key}`)\n }\n}\n\n/**\n * Handle 'move' operation using existing DraftNode methods\n */\nfunction handleMove<T extends DocShape>(\n draft: Draft<T>,\n operation: JsonPatchMoveOperation,\n): void {\n const fromPath = normalizePath(operation.from)\n const toPath = normalizePath(operation.path)\n\n // For list moves within the same parent, we need special handling\n if (\n fromPath.length === toPath.length &&\n fromPath.slice(0, -1).every((segment, i) => segment === toPath[i])\n ) {\n // Same parent container - use list move operation if available\n const fromIndex = fromPath[fromPath.length - 1]\n const toIndex = toPath[toPath.length - 1]\n\n if (typeof fromIndex === \"number\" && typeof toIndex === \"number\") {\n const { parent } = navigateToPath(draft, fromPath.slice(0, -1))\n\n // Check if the parent has a move method (like LoroMovableList)\n if (parent.move && typeof parent.move === \"function\") {\n parent.move(fromIndex, toIndex)\n return\n }\n\n // Otherwise, get value, remove, then add at target index\n const value = getValueAtPath(draft, fromPath)\n handleRemove(draft, { op: \"remove\", path: operation.from })\n\n // For JSON Patch move semantics, the target index refers to the position\n // in the final array, not the intermediate array after removal.\n // No index adjustment needed - use the original target index.\n handleAdd(draft, { op: \"add\", path: operation.path, value })\n return\n }\n }\n\n // Different parents or non-numeric indices - standard move\n const value = getValueAtPath(draft, fromPath)\n handleRemove(draft, { op: \"remove\", path: operation.from })\n handleAdd(draft, { op: \"add\", path: operation.path, value })\n}\n\n/**\n * Handle 'copy' operation using existing DraftNode methods\n */\nfunction handleCopy<T extends DocShape>(\n draft: Draft<T>,\n operation: JsonPatchCopyOperation,\n): void {\n const fromPath = normalizePath(operation.from)\n\n // Get the value to copy\n const value = getValueAtPath(draft, fromPath)\n\n // Add to destination (no removal)\n handleAdd(draft, { op: \"add\", path: operation.path, value })\n}\n\n/**\n * Handle 'test' operation using existing DraftNode value access\n */\nfunction handleTest<T extends DocShape>(\n draft: Draft<T>,\n operation: JsonPatchTestOperation,\n): boolean {\n const path = normalizePath(operation.path)\n const actualValue = getValueAtPath(draft, path)\n\n // Deep equality check for test operation\n return JSON.stringify(actualValue) === JSON.stringify(operation.value)\n}\n\n// =============================================================================\n// MAIN APPLICATOR - Simple orchestration following existing patterns\n// =============================================================================\n\n/**\n * Main JSON Patch applicator - follows existing change() patterns\n */\nexport class JsonPatchApplicator<T extends DocShape> {\n constructor(private rootDraft: Draft<T>) {}\n\n /**\n * Apply a single JSON Patch operation\n */\n applyOperation(operation: JsonPatchOperation): void {\n switch (operation.op) {\n case \"add\":\n handleAdd(this.rootDraft, operation)\n break\n case \"remove\":\n handleRemove(this.rootDraft, operation)\n break\n case \"replace\":\n handleReplace(this.rootDraft, operation)\n break\n case \"move\":\n handleMove(this.rootDraft, operation)\n break\n case \"copy\":\n handleCopy(this.rootDraft, operation)\n break\n case \"test\":\n if (!handleTest(this.rootDraft, operation)) {\n throw new Error(`JSON Patch test failed at path: ${operation.path}`)\n }\n break\n default:\n // TypeScript will catch this at compile time with proper discriminated union\n throw new Error(\n `Unsupported JSON Patch operation: ${(operation as any).op}`,\n )\n }\n }\n\n /**\n * Apply multiple JSON Patch operations in sequence\n */\n applyPatch(patch: JsonPatch): void {\n for (const operation of patch) {\n this.applyOperation(operation)\n }\n }\n}\n","import type { LoroDoc } from \"loro-crdt\"\nimport type { ContainerShape, DocShape, ShapeToContainer } from \"../shape.js\"\nimport type { Infer } from \"../types.js\"\n\nexport type TypedRefParams<Shape extends DocShape | ContainerShape> = {\n shape: Shape\n placeholder?: Infer<Shape>\n getContainer: () => ShapeToContainer<Shape>\n readonly?: boolean // DEPRECATED - remove in future\n autoCommit?: boolean // NEW: auto-commit after mutations\n getDoc?: () => LoroDoc // NEW: needed for auto-commit\n}\n\n// Base class for all typed refs\nexport abstract class TypedRef<Shape extends DocShape | ContainerShape> {\n protected _cachedContainer?: ShapeToContainer<Shape>\n\n constructor(protected _params: TypedRefParams<Shape>) {}\n\n abstract absorbPlainValues(): void\n\n protected get shape(): Shape {\n return this._params.shape\n }\n\n protected get placeholder(): Infer<Shape> | undefined {\n return this._params.placeholder\n }\n\n protected get readonly(): boolean {\n return !!this._params.readonly\n }\n\n protected get autoCommit(): boolean {\n return !!this._params.autoCommit\n }\n\n protected get doc(): LoroDoc | undefined {\n return this._params.getDoc?.()\n }\n\n /**\n * Commits changes if autoCommit is enabled.\n * Call this after any mutation operation.\n */\n protected commitIfAuto(): void {\n if (this.autoCommit && this.doc) {\n this.doc.commit()\n }\n }\n\n /**\n * Throws an error if this ref is in readonly mode.\n * Call this at the start of any mutating method.\n * @deprecated Mutations are always allowed now; this will be removed.\n */\n protected assertMutable(): void {\n if (this.readonly) {\n throw new Error(\"Cannot modify readonly ref\")\n }\n }\n\n protected get container(): ShapeToContainer<Shape> {\n if (!this._cachedContainer) {\n const container = this._params.getContainer()\n this._cachedContainer = container\n return container\n }\n return this._cachedContainer\n }\n}\n","import {\n LoroCounter,\n LoroList,\n LoroMap,\n LoroMovableList,\n LoroText,\n LoroTree,\n type Value,\n} from \"loro-crdt\"\nimport type {\n ContainerShape,\n CounterContainerShape,\n ListContainerShape,\n MovableListContainerShape,\n RecordContainerShape,\n StructContainerShape,\n TextContainerShape,\n TreeContainerShape,\n} from \"../shape.js\"\nimport { TypedRef, type TypedRefParams } from \"./base.js\"\nimport { CounterRef } from \"./counter.js\"\nimport { ListRef } from \"./list.js\"\nimport { MovableListRef } from \"./movable-list.js\"\nimport {\n listProxyHandler,\n movableListProxyHandler,\n recordProxyHandler,\n} from \"./proxy-handlers.js\"\nimport { RecordRef } from \"./record.js\"\nimport { StructRef } from \"./struct.js\"\nimport { TextRef } from \"./text.js\"\nimport { TreeRef } from \"./tree.js\"\n\n/**\n * Mapping from container shape types to their Loro constructor classes.\n * Used when creating new containers via getOrCreateContainer().\n */\nexport const containerConstructor = {\n counter: LoroCounter,\n list: LoroList,\n movableList: LoroMovableList,\n record: LoroMap, // Records use LoroMap as their underlying container\n struct: LoroMap, // Structs use LoroMap as their underlying container\n text: LoroText,\n tree: LoroTree,\n} as const\n\n/**\n * Unwraps a TypedRef to its primitive value for readonly access.\n * Counter refs return their numeric value, Text refs return their string.\n * Other container types are returned as-is.\n */\nexport function unwrapReadonlyPrimitive(\n ref: TypedRef<any>,\n shape: ContainerShape,\n): any {\n if (shape._type === \"counter\") {\n return (ref as any).value\n }\n if (shape._type === \"text\") {\n return (ref as any).toString()\n }\n return ref\n}\n\n/**\n * Absorbs cached plain values back into a LoroMap container.\n * For TypedRef entries, recursively calls absorbPlainValues().\n * For plain Value entries, sets them directly on the container.\n */\nexport function absorbCachedPlainValues(\n cache: Map<string, TypedRef<ContainerShape> | Value>,\n getContainer: () => LoroMap,\n): void {\n let container: LoroMap | undefined\n\n for (const [key, ref] of cache.entries()) {\n if (ref instanceof TypedRef) {\n // Contains a TypedRef, not a plain Value: keep recursing\n ref.absorbPlainValues()\n } else {\n // Plain value!\n if (!container) container = getContainer()\n container.set(key, ref)\n }\n }\n}\n\n/**\n * Serializes a TypedRef to JSON by iterating over its keys.\n * For nested TypedRefs with toJSON(), calls their toJSON method.\n * For plain values, includes them directly.\n */\nexport function serializeRefToJSON(\n ref: Record<string, any>,\n keys: Iterable<string>,\n): Record<string, any> {\n const result: Record<string, any> = {}\n for (const key of keys) {\n const value = ref[key]\n if (value && typeof value === \"object\" && \"toJSON\" in value) {\n result[key] = value.toJSON()\n } else {\n result[key] = value\n }\n }\n return result\n}\n\n// Generic catch-all overload\nexport function createContainerTypedRef<T extends ContainerShape>(\n params: TypedRefParams<T>,\n): TypedRef<T>\n\n// Implementation\nexport function createContainerTypedRef(\n params: TypedRefParams<ContainerShape>,\n): TypedRef<ContainerShape> {\n switch (params.shape._type) {\n case \"counter\":\n return new CounterRef(params as TypedRefParams<CounterContainerShape>)\n case \"list\":\n return new Proxy(\n new ListRef(params as TypedRefParams<ListContainerShape>),\n listProxyHandler,\n )\n case \"struct\":\n return new StructRef(params as TypedRefParams<StructContainerShape>)\n case \"movableList\":\n return new Proxy(\n new MovableListRef(params as TypedRefParams<MovableListContainerShape>),\n movableListProxyHandler,\n )\n case \"record\":\n return new Proxy(\n new RecordRef(params as TypedRefParams<RecordContainerShape>),\n recordProxyHandler,\n )\n case \"text\":\n return new TextRef(params as TypedRefParams<TextContainerShape>)\n case \"tree\":\n return new TreeRef(params as TypedRefParams<TreeContainerShape>)\n default:\n throw new Error(\n `Unknown container type: ${(params.shape as ContainerShape)._type}`,\n )\n }\n}\n\nexport function assignPlainValueToTypedRef(\n ref: TypedRef<any>,\n value: any,\n): boolean {\n const shapeType = (ref as any).shape._type\n\n if (shapeType === \"struct\" || shapeType === \"record\") {\n for (const k in value) {\n ;(ref as any)[k] = value[k]\n }\n return true\n }\n\n if (shapeType === \"list\" || shapeType === \"movableList\") {\n if (Array.isArray(value)) {\n const listRef = ref as any\n if (listRef.length > 0) {\n listRef.delete(0, listRef.length)\n }\n for (const item of value) {\n listRef.push(item)\n }\n return true\n }\n }\n\n if (shapeType === \"text\") {\n if (typeof value === \"string\") {\n ;(ref as any).update(value)\n return true\n }\n return false\n }\n\n if (shapeType === \"counter\") {\n if (typeof value === \"number\") {\n const currentValue = (ref as any).value\n const diff = value - currentValue\n if (diff > 0) {\n ;(ref as any).increment(diff)\n } else if (diff < 0) {\n ;(ref as any).decrement(-diff)\n }\n return true\n }\n return false\n }\n\n return false\n}\n","import type { LoroCounter } from \"loro-crdt\"\nimport type { CounterContainerShape } from \"../shape.js\"\nimport { TypedRef } from \"./base.js\"\n\n// Counter typed ref\nexport class CounterRef extends TypedRef<CounterContainerShape> {\n // Track if we've materialized the container (made any changes)\n private _materialized = false\n\n protected get container(): LoroCounter {\n return super.container as LoroCounter\n }\n\n absorbPlainValues() {\n // no plain values contained within\n }\n\n increment(value: number = 1): void {\n this.assertMutable()\n this._materialized = true\n this.container.increment(value)\n this.commitIfAuto()\n }\n\n decrement(value: number = 1): void {\n this.assertMutable()\n this._materialized = true\n this.container.decrement(value)\n this.commitIfAuto()\n }\n\n /**\n * Returns the counter value.\n * If the counter hasn't been materialized (no operations performed),\n * returns the placeholder value if available.\n */\n get value(): number {\n // Check if the container has any value (non-zero means it was modified)\n const containerValue = this.container.value\n if (containerValue !== 0 || this._materialized) {\n return containerValue\n }\n // Return placeholder if available and container is at default state\n if (this.placeholder !== undefined) {\n return this.placeholder as number\n }\n return containerValue\n }\n\n valueOf(): number {\n return this.value\n }\n\n toJSON(): number {\n return this.value\n }\n\n [Symbol.toPrimitive](hint: string): number | string {\n if (hint === \"string\") {\n return String(this.value)\n }\n return this.value\n }\n}\n","import {\n type Container,\n LoroCounter,\n LoroList,\n LoroMap,\n LoroMovableList,\n LoroText,\n type Value,\n} from \"loro-crdt\"\nimport type {\n ArrayValueShape,\n ContainerOrValueShape,\n ListContainerShape,\n MovableListContainerShape,\n RecordContainerShape,\n RecordValueShape,\n StructContainerShape,\n StructValueShape,\n} from \"./shape.js\"\nimport {\n isContainer,\n isContainerShape,\n isObjectValue,\n isValueShape,\n} from \"./utils/type-guards.js\"\n\n/**\n * Converts string input to LoroText container\n */\nfunction convertTextInput(value: string): LoroText {\n const text = new LoroText()\n\n text.insert(0, value)\n\n return text\n}\n\n/**\n * Converts number input to LoroCounter container\n */\nfunction convertCounterInput(value: number): LoroCounter {\n const counter = new LoroCounter()\n counter.increment(value)\n return counter\n}\n\n/**\n * Converts array input to LoroList container\n */\nfunction convertListInput(\n value: Value[],\n shape: ListContainerShape | ArrayValueShape,\n // parentPath: string[],\n): LoroList | Value[] {\n if (!isContainerShape(shape)) {\n return value\n }\n\n const list = new LoroList()\n\n for (const item of value) {\n const convertedItem = convertInputToRef(item, shape.shape)\n if (isContainer(convertedItem)) {\n list.pushContainer(convertedItem)\n } else {\n list.push(convertedItem)\n }\n }\n\n return list\n}\n\n/**\n * Converts array input to LoroMovableList container\n */\nfunction convertMovableListInput(\n value: Value[],\n shape: MovableListContainerShape | ArrayValueShape,\n // parentPath: string[],\n): LoroMovableList | Value[] {\n if (!isContainerShape(shape)) {\n return value\n }\n\n const list = new LoroMovableList()\n\n for (const item of value) {\n const convertedItem = convertInputToRef(item, shape.shape)\n if (isContainer(convertedItem)) {\n list.pushContainer(convertedItem)\n } else {\n list.push(convertedItem)\n }\n }\n\n return list\n}\n\n/**\n * Converts object input to LoroMap container (Struct)\n */\nfunction convertStructInput(\n value: { [key: string]: Value },\n shape: StructContainerShape | StructValueShape,\n): LoroMap | { [key: string]: Value } {\n if (!isContainerShape(shape)) {\n return value\n }\n\n const map = new LoroMap()\n for (const [k, v] of Object.entries(value)) {\n const nestedSchema = shape.shapes[k]\n if (nestedSchema) {\n const convertedValue = convertInputToRef(v, nestedSchema)\n if (isContainer(convertedValue)) {\n map.setContainer(k, convertedValue)\n } else {\n map.set(k, convertedValue)\n }\n } else {\n map.set(k, value)\n }\n }\n\n return map\n}\n\n/**\n * Converts object input to LoroMap container (Record)\n */\nfunction convertRecordInput(\n value: { [key: string]: Value },\n shape: RecordContainerShape | RecordValueShape,\n): LoroMap | { [key: string]: Value } {\n if (!isContainerShape(shape)) {\n return value\n }\n\n const map = new LoroMap()\n for (const [k, v] of Object.entries(value)) {\n const convertedValue = convertInputToRef(v, shape.shape)\n if (isContainer(convertedValue)) {\n map.setContainer(k, convertedValue)\n } else {\n map.set(k, convertedValue)\n }\n }\n\n return map\n}\n\n/**\n * Main conversion function that transforms input values to appropriate CRDT containers\n * based on schema definitions\n */\nexport function convertInputToRef<Shape extends ContainerOrValueShape>(\n value: Value,\n shape: Shape,\n): Container | Value {\n switch (shape._type) {\n case \"text\": {\n if (typeof value !== \"string\") {\n throw new Error(\"string expected\")\n }\n\n return convertTextInput(value)\n }\n case \"counter\": {\n if (typeof value !== \"number\") {\n throw new Error(\"number expected\")\n }\n\n return convertCounterInput(value)\n }\n case \"list\": {\n if (!Array.isArray(value)) {\n throw new Error(\"array expected\")\n }\n\n return convertListInput(value, shape)\n }\n case \"movableList\": {\n if (!Array.isArray(value)) {\n throw new Error(\"array expected\")\n }\n\n return convertMovableListInput(value, shape)\n }\n case \"struct\": {\n if (!isObjectValue(value)) {\n throw new Error(\"object expected\")\n }\n\n return convertStructInput(value, shape)\n }\n case \"record\": {\n if (!isObjectValue(value)) {\n throw new Error(\"object expected\")\n }\n\n return convertRecordInput(value, shape)\n }\n case \"value\": {\n if (!isValueShape(shape)) {\n throw new Error(\"value expected\")\n }\n\n return value\n }\n\n case \"tree\":\n throw new Error(\"tree type unimplemented\")\n\n default:\n throw new Error(`unexpected type: ${(shape as Shape)._type}`)\n }\n}\n","import type { Container, LoroList, LoroMovableList } from \"loro-crdt\"\nimport { convertInputToRef } from \"../conversion.js\"\nimport { deriveShapePlaceholder } from \"../derive-placeholder.js\"\nimport { mergeValue } from \"../overlay.js\"\nimport type {\n ContainerOrValueShape,\n ContainerShape,\n ListContainerShape,\n MovableListContainerShape,\n} from \"../shape.js\"\nimport {\n isContainer,\n isContainerShape,\n isValueShape,\n} from \"../utils/type-guards.js\"\nimport { TypedRef, type TypedRefParams } from \"./base.js\"\nimport { createContainerTypedRef, unwrapReadonlyPrimitive } from \"./utils.js\"\n\n// Shared logic for list operations\nexport abstract class ListRefBase<\n NestedShape extends ContainerOrValueShape,\n Item = NestedShape[\"_plain\"],\n MutableItem = NestedShape[\"_mutable\"],\n> extends TypedRef<any> {\n // Cache for items returned by array methods to track mutations\n private itemCache = new Map<number, any>()\n\n protected get container(): LoroList | LoroMovableList {\n return super.container as LoroList | LoroMovableList\n }\n\n protected get shape():\n | ListContainerShape<NestedShape>\n | MovableListContainerShape<NestedShape> {\n return super.shape as\n | ListContainerShape<NestedShape>\n | MovableListContainerShape<NestedShape>\n }\n\n absorbPlainValues() {\n // Critical function: absorb mutated plain values back into Loro containers\n // This is called at the end of change() to persist mutations made to plain objects\n for (const [index, cachedItem] of this.itemCache.entries()) {\n if (cachedItem) {\n if (isValueShape(this.shape.shape)) {\n // For value shapes, delegate to subclass-specific absorption logic\n this.absorbValueAtIndex(index, cachedItem)\n } else {\n // For container shapes, the item should be a typed ref that handles its own absorption\n if (\n cachedItem &&\n typeof cachedItem === \"object\" &&\n \"absorbPlainValues\" in cachedItem\n ) {\n ;(cachedItem as any).absorbPlainValues()\n }\n }\n }\n }\n\n // Clear the cache after absorbing values\n this.itemCache.clear()\n }\n\n // Abstract method to be implemented by subclasses\n // Each subclass knows how to handle its specific container type\n protected abstract absorbValueAtIndex(index: number, value: any): void\n\n protected insertWithConversion(index: number, item: Item): void {\n const convertedItem = convertInputToRef(item as any, this.shape.shape)\n if (isContainer(convertedItem)) {\n this.container.insertContainer(index, convertedItem)\n } else {\n this.container.insert(index, convertedItem)\n }\n }\n\n protected pushWithConversion(item: Item): void {\n const convertedItem = convertInputToRef(item as any, this.shape.shape)\n if (isContainer(convertedItem)) {\n this.container.pushContainer(convertedItem)\n } else {\n this.container.push(convertedItem)\n }\n }\n\n getTypedRefParams(\n index: number,\n shape: ContainerShape,\n ): TypedRefParams<ContainerShape> {\n return {\n shape,\n placeholder: undefined, // List items don't have placeholder\n getContainer: () => {\n const containerItem = this.container.get(index)\n if (!containerItem || !isContainer(containerItem)) {\n throw new Error(`No container found at index ${index}`)\n }\n return containerItem\n },\n readonly: this.readonly,\n autoCommit: this._params.autoCommit,\n getDoc: this._params.getDoc,\n }\n }\n\n // Get item for predicate functions - always returns plain Item for filtering logic\n protected getPredicateItem(index: number): Item {\n // CRITICAL FIX: For predicates to work correctly with mutations,\n // we need to check if there's a cached (mutated) version first\n const cachedItem = this.itemCache.get(index)\n if (cachedItem && isValueShape(this.shape.shape)) {\n // For value shapes, if we have a cached item, use it so predicates see mutations\n return cachedItem as Item\n }\n\n const containerItem = this.container.get(index)\n if (containerItem === undefined) {\n return undefined as Item\n }\n\n if (isValueShape(this.shape.shape)) {\n // For value shapes, return the plain value directly\n return containerItem as Item\n } else {\n // For container shapes, we need to return the plain object representation\n // This allows predicates to access nested properties like article.metadata.author\n if (isContainer(containerItem)) {\n // Convert container to plain object for predicate logic\n // Handle different container types that may not have toJSON method\n if (\n typeof containerItem === \"object\" &&\n containerItem !== null &&\n \"toJSON\" in containerItem\n ) {\n return (containerItem as any).toJSON() as Item\n } else if (\n typeof containerItem === \"object\" &&\n containerItem !== null &&\n \"getShallowValue\" in containerItem\n ) {\n // For containers like LoroCounter that don't have toJSON but have getShallowValue\n return (containerItem as any).getShallowValue() as Item\n } else {\n // Fallback for other container types\n return containerItem as Item\n }\n }\n return containerItem as Item\n }\n }\n\n // Get item for return values - returns MutableItem that can be mutated\n protected getMutableItem(index: number): any {\n // Check if we already have a cached item for this index\n let cachedItem = this.itemCache.get(index)\n if (cachedItem) {\n return cachedItem\n }\n\n // Get the raw container item\n const containerItem = this.container.get(index)\n if (containerItem === undefined) {\n return undefined as MutableItem\n }\n\n if (isValueShape(this.shape.shape)) {\n // For value shapes, we need to ensure mutations persist\n // The key insight: we must return the SAME object for the same index\n // so that mutations to filtered/found items persist back to the cache\n if (typeof containerItem === \"object\" && containerItem !== null) {\n // Create a deep copy for objects so mutations can be tracked\n // IMPORTANT: Only create the copy once, then always return the same cached object\n cachedItem = JSON.parse(JSON.stringify(containerItem))\n } else {\n // For primitives, just use the value directly\n cachedItem = containerItem\n }\n // Only cache primitive values if NOT readonly\n if (!this.readonly) {\n this.itemCache.set(index, cachedItem)\n }\n return cachedItem as MutableItem\n } else {\n // For container shapes, create a proper typed ref using the new pattern\n cachedItem = createContainerTypedRef(\n this.getTypedRefParams(index, this.shape.shape as ContainerShape),\n )\n // Cache container refs\n this.itemCache.set(index, cachedItem)\n\n if (this.readonly) {\n return unwrapReadonlyPrimitive(\n cachedItem,\n this.shape.shape as ContainerShape,\n )\n }\n\n return cachedItem as MutableItem\n }\n }\n\n // Array-like methods for better developer experience\n // DUAL INTERFACE: Predicates get Item (plain data), return values are MutableItem (mutable)\n\n find(\n predicate: (item: Item, index: number) => boolean,\n ): MutableItem | undefined {\n for (let i = 0; i < this.length; i++) {\n const predicateItem = this.getPredicateItem(i)\n if (predicate(predicateItem, i)) {\n return this.getMutableItem(i) // Return mutable item\n }\n }\n return undefined\n }\n\n findIndex(predicate: (item: Item, index: number) => boolean): number {\n for (let i = 0; i < this.length; i++) {\n const predicateItem = this.getPredicateItem(i)\n if (predicate(predicateItem, i)) {\n return i\n }\n }\n return -1\n }\n\n map<ReturnType>(\n callback: (item: Item, index: number) => ReturnType,\n ): ReturnType[] {\n const result: ReturnType[] = []\n for (let i = 0; i < this.length; i++) {\n const predicateItem = this.getPredicateItem(i)\n result.push(callback(predicateItem, i))\n }\n return result\n }\n\n filter(predicate: (item: Item, index: number) => boolean): MutableItem[] {\n const result: MutableItem[] = []\n for (let i = 0; i < this.length; i++) {\n const predicateItem = this.getPredicateItem(i)\n if (predicate(predicateItem, i)) {\n result.push(this.getMutableItem(i)) // Return mutable items\n }\n }\n return result\n }\n\n forEach(callback: (item: Item, index: number) => void): void {\n for (let i = 0; i < this.length; i++) {\n const predicateItem = this.getPredicateItem(i)\n callback(predicateItem, i)\n }\n }\n\n some(predicate: (item: Item, index: number) => boolean): boolean {\n for (let i = 0; i < this.length; i++) {\n const predicateItem = this.getPredicateItem(i)\n if (predicate(predicateItem, i)) {\n return true\n }\n }\n return false\n }\n\n every(predicate: (item: Item, index: number) => boolean): boolean {\n for (let i = 0; i < this.length; i++) {\n const predicateItem = this.getPredicateItem(i)\n if (!predicate(predicateItem, i)) {\n return false\n }\n }\n return true\n }\n\n slice(start?: number, end?: number): MutableItem[] {\n const len = this.length\n\n // Normalize start index (following JavaScript Array.prototype.slice semantics)\n const startIndex =\n start === undefined\n ? 0\n : start < 0\n ? Math.max(len + start, 0)\n : Math.min(start, len)\n\n // Normalize end index\n const endIndex =\n end === undefined\n ? len\n : end < 0\n ? Math.max(len + end, 0)\n : Math.min(end, len)\n\n const result: MutableItem[] = []\n for (let i = startIndex; i < endIndex; i++) {\n result.push(this.getMutableItem(i))\n }\n return result\n }\n\n insert(index: number, item: Item): void {\n this.assertMutable()\n // Update cache indices before performing the insert operation\n this.updateCacheForInsert(index)\n this.insertWithConversion(index, item)\n this.commitIfAuto()\n }\n\n delete(index: number, len: number): void {\n this.assertMutable()\n // Update cache indices before performing the delete operation\n this.updateCacheForDelete(index, len)\n this.container.delete(index, len)\n this.commitIfAuto()\n }\n\n push(item: Item): void {\n this.assertMutable()\n this.pushWithConversion(item)\n this.commitIfAuto()\n }\n\n pushContainer(container: Container): Container {\n this.assertMutable()\n const result = this.container.pushContainer(container)\n this.commitIfAuto()\n return result\n }\n\n insertContainer(index: number, container: Container): Container {\n this.assertMutable()\n const result = this.container.insertContainer(index, container)\n this.commitIfAuto()\n return result\n }\n\n get(index: number): MutableItem {\n return this.getMutableItem(index)\n }\n\n toArray(): Item[] {\n const result: Item[] = []\n for (let i = 0; i < this.length; i++) {\n result.push(this.getPredicateItem(i))\n }\n return result\n }\n\n toJSON(): Item[] {\n const nativeJson = this.container.toJSON() as any[]\n\n // If the nested shape is a container shape (map, record, etc.) or an object value shape,\n // we need to overlay placeholders for each item\n if (\n isContainerShape(this.shape.shape) ||\n (isValueShape(this.shape.shape) &&\n this.shape.shape.valueType === \"struct\")\n ) {\n const itemPlaceholder = deriveShapePlaceholder(this.shape.shape)\n return nativeJson.map(item =>\n mergeValue(this.shape.shape, item, itemPlaceholder as any),\n ) as Item[]\n }\n\n // For primitive value shapes, no overlay needed\n return nativeJson ?? []\n }\n\n [Symbol.iterator](): IterableIterator<MutableItem> {\n let index = 0\n return {\n next: (): IteratorResult<MutableItem> => {\n if (index < this.length) {\n return { value: this.getMutableItem(index++), done: false }\n }\n return { value: undefined, done: true }\n },\n [Symbol.iterator]() {\n return this\n },\n }\n }\n\n get length(): number {\n return this.container.length\n }\n\n // Update cache indices when items are deleted\n private updateCacheForDelete(deleteIndex: number, deleteLen: number): void {\n const newCache = new Map<number, any>()\n\n for (const [cachedIndex, cachedItem] of this.itemCache.entries()) {\n if (cachedIndex < deleteIndex) {\n // Items before the deletion point keep their indices\n newCache.set(cachedIndex, cachedItem)\n } else if (cachedIndex >= deleteIndex + deleteLen) {\n // Items after the deletion range shift down by deleteLen\n newCache.set(cachedIndex - deleteLen, cachedItem)\n }\n // Items within the deletion range are removed from cache\n }\n\n this.itemCache = newCache\n }\n\n // Update cache indices when items are inserted\n private updateCacheForInsert(insertIndex: number): void {\n const newCache = new Map<number, any>()\n\n for (const [cachedIndex, cachedItem] of this.itemCache.entries()) {\n if (cachedIndex < insertIndex) {\n // Items before the insertion point keep their indices\n newCache.set(cachedIndex, cachedItem)\n } else {\n // Items at or after the insertion point shift up by 1\n newCache.set(cachedIndex + 1, cachedItem)\n }\n }\n\n this.itemCache = newCache\n }\n}\n","import type { LoroList } from \"loro-crdt\"\nimport type { ContainerOrValueShape } from \"../shape.js\"\nimport type { Infer } from \"../types.js\"\nimport { ListRefBase } from \"./list-base.js\"\n\n// List typed ref\nexport class ListRef<\n NestedShape extends ContainerOrValueShape,\n> extends ListRefBase<NestedShape> {\n [index: number]: Infer<NestedShape>\n\n protected get container(): LoroList {\n return super.container as LoroList\n }\n\n protected absorbValueAtIndex(index: number, value: any): void {\n // LoroList doesn't have set method, need to delete and insert\n this.container.delete(index, 1)\n this.container.insert(index, value)\n }\n}\n","import type { Container, LoroMovableList } from \"loro-crdt\"\nimport type { ContainerOrValueShape } from \"../shape.js\"\nimport type { Infer } from \"../types.js\"\nimport { ListRefBase } from \"./list-base.js\"\n\n// Movable list typed ref\nexport class MovableListRef<\n NestedShape extends ContainerOrValueShape,\n Item = NestedShape[\"_plain\"],\n> extends ListRefBase<NestedShape> {\n [index: number]: Infer<NestedShape>\n\n protected get container(): LoroMovableList {\n return super.container as LoroMovableList\n }\n\n protected absorbValueAtIndex(index: number, value: any): void {\n // LoroMovableList has set method\n this.container.set(index, value)\n }\n\n move(from: number, to: number): void {\n this.assertMutable()\n this.container.move(from, to)\n this.commitIfAuto()\n }\n\n set(index: number, item: Exclude<Item, Container>) {\n this.assertMutable()\n const result = this.container.set(index, item)\n this.commitIfAuto()\n return result\n }\n}\n","import type { ListRef } from \"./list.js\"\nimport type { MovableListRef } from \"./movable-list.js\"\nimport type { RecordRef } from \"./record.js\"\n\nexport const recordProxyHandler: ProxyHandler<RecordRef<any>> = {\n get: (target, prop) => {\n if (typeof prop === \"string\" && !(prop in target)) {\n // Use getRef for reading - returns undefined for non-existent keys\n return target.getRef(prop)\n }\n return Reflect.get(target, prop)\n },\n set: (target, prop, value) => {\n if (typeof prop === \"string\" && !(prop in target)) {\n target.set(prop, value)\n return true\n }\n return Reflect.set(target, prop, value)\n },\n deleteProperty: (target, prop) => {\n if (typeof prop === \"string\" && !(prop in target)) {\n target.delete(prop)\n return true\n }\n return Reflect.deleteProperty(target, prop)\n },\n // Support `in` operator for checking key existence\n has: (target, prop) => {\n if (typeof prop === \"string\") {\n // Check if it's a method/property on the class first\n if (prop in target) {\n return true\n }\n // Otherwise check the underlying container\n return target.has(prop)\n }\n return Reflect.has(target, prop)\n },\n ownKeys: target => {\n return target.keys()\n },\n getOwnPropertyDescriptor: (target, prop) => {\n if (typeof prop === \"string\" && target.has(prop)) {\n return {\n configurable: true,\n enumerable: true,\n value: target.get(prop),\n }\n }\n return Reflect.getOwnPropertyDescriptor(target, prop)\n },\n}\n\nexport const listProxyHandler: ProxyHandler<ListRef<any>> = {\n get: (target, prop) => {\n if (typeof prop === \"string\") {\n const index = Number(prop)\n if (!Number.isNaN(index)) {\n return target.get(index)\n }\n }\n return Reflect.get(target, prop)\n },\n set: (target, prop, value) => {\n if (typeof prop === \"string\") {\n const index = Number(prop)\n if (!Number.isNaN(index)) {\n // For lists, assignment to index implies replacement\n target.delete(index, 1)\n target.insert(index, value)\n return true\n }\n }\n return Reflect.set(target, prop, value)\n },\n}\n\nexport const movableListProxyHandler: ProxyHandler<MovableListRef<any>> = {\n get: (target, prop) => {\n if (typeof prop === \"string\") {\n const index = Number(prop)\n if (!Number.isNaN(index)) {\n return target.get(index)\n }\n }\n return Reflect.get(target, prop)\n },\n set: (target, prop, value) => {\n if (typeof prop === \"string\") {\n const index = Number(prop)\n if (!Number.isNaN(index)) {\n // MovableList supports set directly\n target.set(index, value)\n return true\n }\n }\n return Reflect.set(target, prop, value)\n },\n}\n","import type { Container, LoroMap, Value } from \"loro-crdt\"\nimport { deriveShapePlaceholder } from \"../derive-placeholder.js\"\nimport { mergeValue } from \"../overlay.js\"\nimport type {\n ContainerOrValueShape,\n ContainerShape,\n RecordContainerShape,\n} from \"../shape.js\"\nimport type { Infer, InferMutableType } from \"../types.js\"\nimport { isContainerShape, isValueShape } from \"../utils/type-guards.js\"\nimport { TypedRef, type TypedRefParams } from \"./base.js\"\nimport {\n absorbCachedPlainValues,\n assignPlainValueToTypedRef,\n containerConstructor,\n createContainerTypedRef,\n serializeRefToJSON,\n unwrapReadonlyPrimitive,\n} from \"./utils.js\"\n\n// Record typed ref\nexport class RecordRef<\n NestedShape extends ContainerOrValueShape,\n> extends TypedRef<any> {\n [key: string]: Infer<NestedShape> | any\n private refCache = new Map<string, TypedRef<ContainerShape> | Value>()\n\n protected get shape(): RecordContainerShape<NestedShape> {\n return super.shape as RecordContainerShape<NestedShape>\n }\n\n protected get container(): LoroMap {\n return super.container as LoroMap\n }\n\n absorbPlainValues() {\n absorbCachedPlainValues(this.refCache, () => this.container)\n }\n\n getTypedRefParams<S extends ContainerShape>(\n key: string,\n shape: S,\n ): TypedRefParams<ContainerShape> {\n // First try to get placeholder from the Record's placeholder (if it has an entry for this key)\n let placeholder = (this.placeholder as any)?.[key]\n\n // If no placeholder exists for this key, derive one from the schema's shape\n // This is critical for Records where the placeholder is always {} but nested\n // containers need valid placeholders to fall back to for missing values\n if (placeholder === undefined) {\n placeholder = deriveShapePlaceholder(shape)\n }\n\n const LoroContainer = containerConstructor[shape._type]\n\n return {\n shape,\n placeholder,\n getContainer: () =>\n this.container.getOrCreateContainer(key, new (LoroContainer as any)()),\n readonly: this.readonly,\n autoCommit: this._params.autoCommit,\n getDoc: this._params.getDoc,\n }\n }\n\n /**\n * Gets an existing ref for a key, or returns undefined if the key doesn't exist.\n * Used for reading operations where we want optional chaining to work.\n */\n getRef(key: string): any {\n // For container shapes, check if the key exists first\n // This allows optional chaining (?.) to work correctly for non-existent keys\n if (isContainerShape(this.shape.shape)) {\n const existing = this.container.get(key)\n if (existing === undefined) {\n return undefined\n }\n }\n\n return this.getOrCreateRef(key)\n }\n\n /**\n * Gets or creates a ref for a key.\n * Always creates the container if it doesn't exist.\n * This is the method used for write operations.\n */\n getOrCreateRef(key: string): any {\n let ref = this.refCache.get(key)\n if (!ref) {\n const shape = this.shape.shape\n if (isContainerShape(shape)) {\n ref = createContainerTypedRef(\n this.getTypedRefParams(key, shape as ContainerShape),\n )\n // Cache container refs\n this.refCache.set(key, ref)\n } else {\n // For value shapes, first try to get the value from the container\n const containerValue = this.container.get(key)\n if (containerValue !== undefined) {\n ref = containerValue as Value\n } else {\n // Only fall back to placeholder if the container doesn't have the value\n const placeholder = (this.placeholder as any)?.[key]\n if (placeholder === undefined) {\n // If it's a value type and not in container or placeholder,\n // fallback to the default value from the shape\n ref = (shape as any)._plain\n } else {\n ref = placeholder as Value\n }\n }\n // Only cache primitive values if NOT readonly\n if (ref !== undefined && !this.readonly) {\n this.refCache.set(key, ref)\n }\n }\n }\n\n if (this.readonly && isContainerShape(this.shape.shape)) {\n return unwrapReadonlyPrimitive(\n ref as TypedRef<any>,\n this.shape.shape as ContainerShape,\n )\n }\n\n return ref as any\n }\n\n get(key: string): InferMutableType<NestedShape> {\n return this.getRef(key)\n }\n\n set(key: string, value: any): void {\n this.assertMutable()\n if (isValueShape(this.shape.shape)) {\n this.container.set(key, value)\n this.refCache.set(key, value)\n this.commitIfAuto()\n } else {\n // For container shapes, try to assign the plain value\n // Use getOrCreateRef to ensure the container is created\n const ref = this.getOrCreateRef(key)\n if (assignPlainValueToTypedRef(ref, value)) {\n this.commitIfAuto()\n return\n }\n throw new Error(\n \"Cannot set container directly, modify the typed ref instead\",\n )\n }\n }\n\n setContainer<C extends Container>(key: string, container: C): C {\n this.assertMutable()\n const result = this.container.setContainer(key, container)\n this.commitIfAuto()\n return result\n }\n\n delete(key: string): void {\n this.assertMutable()\n this.container.delete(key)\n this.refCache.delete(key)\n this.commitIfAuto()\n }\n\n has(key: string): boolean {\n return this.container.get(key) !== undefined\n }\n\n keys(): string[] {\n return this.container.keys()\n }\n\n values(): any[] {\n return this.container.values()\n }\n\n get size(): number {\n return this.container.size\n }\n\n toJSON(): Record<string, Infer<NestedShape>> {\n // Fast path: readonly mode\n if (this.readonly) {\n const nativeJson = this.container.toJSON() as Record<string, any>\n // For records, we need to overlay placeholders for each entry's nested shape\n const result: Record<string, Infer<NestedShape>> = {}\n for (const key of Object.keys(nativeJson)) {\n // For records, the placeholder is always {}, so we need to derive\n // the placeholder for the nested shape on the fly\n const nestedPlaceholderValue = deriveShapePlaceholder(this.shape.shape)\n\n result[key] = mergeValue(\n this.shape.shape,\n nativeJson[key],\n nestedPlaceholderValue as Value,\n ) as Infer<NestedShape>\n }\n return result\n }\n\n return serializeRefToJSON(this, this.keys()) as Record<\n string,\n Infer<NestedShape>\n >\n }\n}\n","import type { Container, LoroMap, Value } from \"loro-crdt\"\nimport { mergeValue } from \"../overlay.js\"\nimport type {\n ContainerOrValueShape,\n ContainerShape,\n StructContainerShape,\n ValueShape,\n} from \"../shape.js\"\nimport type { Infer } from \"../types.js\"\nimport { isContainerShape, isValueShape } from \"../utils/type-guards.js\"\nimport { TypedRef, type TypedRefParams } from \"./base.js\"\nimport {\n absorbCachedPlainValues,\n assignPlainValueToTypedRef,\n containerConstructor,\n createContainerTypedRef,\n serializeRefToJSON,\n unwrapReadonlyPrimitive,\n} from \"./utils.js\"\n\n/**\n * Typed ref for struct containers (objects with fixed keys).\n * Uses LoroMap as the underlying container.\n */\nexport class StructRef<\n NestedShapes extends Record<string, ContainerOrValueShape>,\n> extends TypedRef<any> {\n private propertyCache = new Map<string, TypedRef<ContainerShape> | Value>()\n\n constructor(params: TypedRefParams<StructContainerShape<NestedShapes>>) {\n super(params)\n this.createLazyProperties()\n }\n\n protected get shape(): StructContainerShape<NestedShapes> {\n return super.shape as StructContainerShape<NestedShapes>\n }\n\n protected get container(): LoroMap {\n return super.container as LoroMap\n }\n\n absorbPlainValues() {\n absorbCachedPlainValues(this.propertyCache, () => this.container)\n }\n\n getTypedRefParams<S extends ContainerShape>(\n key: string,\n shape: S,\n ): TypedRefParams<ContainerShape> {\n const placeholder = (this.placeholder as any)?.[key]\n\n const LoroContainer = containerConstructor[shape._type]\n\n return {\n shape,\n placeholder,\n getContainer: () =>\n this.container.getOrCreateContainer(key, new (LoroContainer as any)()),\n readonly: this.readonly,\n autoCommit: this._params.autoCommit,\n getDoc: this._params.getDoc,\n }\n }\n\n getOrCreateRef<Shape extends ContainerShape | ValueShape>(\n key: string,\n shape: Shape,\n ): any {\n let ref = this.propertyCache.get(key)\n if (!ref) {\n if (isContainerShape(shape)) {\n ref = createContainerTypedRef(this.getTypedRefParams(key, shape))\n // We cache container refs even in readonly mode because they are just handles\n this.propertyCache.set(key, ref)\n } else {\n // For value shapes, first try to get the value from the container\n const containerValue = this.container.get(key)\n if (containerValue !== undefined) {\n ref = containerValue as Value\n } else {\n // Only fall back to placeholder if the container doesn't have the value\n const placeholder = (this.placeholder as any)?.[key]\n if (placeholder === undefined) {\n throw new Error(\"placeholder required\")\n }\n ref = placeholder as Value\n }\n\n // In readonly mode, we DO NOT cache primitive values.\n // This ensures we always get the latest value from the CRDT on next access.\n if (!this.readonly) {\n this.propertyCache.set(key, ref)\n }\n }\n if (ref === undefined) throw new Error(\"no container made\")\n }\n\n if (this.readonly && isContainerShape(shape)) {\n // In readonly mode, if the container doesn't exist, return the placeholder\n // This ensures we respect default values (e.g. counter: 1)\n const existing = this.container.get(key)\n if (existing === undefined) {\n return (this.placeholder as any)?.[key]\n }\n\n return unwrapReadonlyPrimitive(ref as TypedRef<any>, shape)\n }\n\n return ref as Shape extends ContainerShape ? TypedRef<Shape> : Value\n }\n\n private createLazyProperties(): void {\n for (const key in this.shape.shapes) {\n const shape = this.shape.shapes[key]\n Object.defineProperty(this, key, {\n get: () => this.getOrCreateRef(key, shape),\n set: value => {\n this.assertMutable()\n if (isValueShape(shape)) {\n this.container.set(key, value)\n this.propertyCache.set(key, value)\n } else {\n // For container shapes, try to assign the plain value\n const ref = this.getOrCreateRef(key, shape)\n if (assignPlainValueToTypedRef(ref as TypedRef<any>, value)) {\n return\n }\n throw new Error(\n \"Cannot set container directly, modify the typed ref instead\",\n )\n }\n },\n enumerable: true,\n })\n }\n }\n\n toJSON(): Infer<StructContainerShape<NestedShapes>> {\n // Fast path: readonly mode\n if (this.readonly) {\n const nativeJson = this.container.toJSON() as Value\n // Overlay placeholders for missing properties\n return mergeValue(\n this.shape,\n nativeJson,\n this.placeholder as Value,\n ) as Infer<StructContainerShape<NestedShapes>>\n }\n\n return serializeRefToJSON(\n this as any,\n Object.keys(this.shape.shapes),\n ) as Infer<StructContainerShape<NestedShapes>>\n }\n\n // TODO(duane): return correct type here\n get(key: string): any {\n return this.container.get(key)\n }\n\n set(key: string, value: Value): void {\n this.assertMutable()\n this.container.set(key, value)\n this.commitIfAuto()\n }\n\n setContainer<C extends Container>(key: string, container: C): C {\n this.assertMutable()\n const result = this.container.setContainer(key, container)\n this.commitIfAuto()\n return result\n }\n\n delete(key: string): void {\n this.assertMutable()\n this.container.delete(key)\n this.commitIfAuto()\n }\n\n has(key: string): boolean {\n // LoroMap doesn't have a has method, so we check if get returns undefined\n return this.container.get(key) !== undefined\n }\n\n keys(): string[] {\n return this.container.keys()\n }\n\n values(): any[] {\n return this.container.values()\n }\n\n get size(): number {\n return this.container.size\n }\n}\n","import type { LoroText } from \"loro-crdt\"\nimport type { TextContainerShape } from \"../shape.js\"\nimport { TypedRef } from \"./base.js\"\n\n// Text typed ref\nexport class TextRef extends TypedRef<TextContainerShape> {\n // Track if we've materialized the container (made any changes)\n private _materialized = false\n\n protected get container(): LoroText {\n return super.container as LoroText\n }\n\n absorbPlainValues() {\n // no plain values contained within\n }\n\n // Text methods\n insert(index: number, content: string): void {\n this.assertMutable()\n this._materialized = true\n this.container.insert(index, content)\n this.commitIfAuto()\n }\n\n delete(index: number, len: number): void {\n this.assertMutable()\n this._materialized = true\n this.container.delete(index, len)\n this.commitIfAuto()\n }\n\n /**\n * Returns the text content.\n * If the text hasn't been materialized (no operations performed),\n * returns the placeholder value if available.\n */\n toString(): string {\n const containerValue = this.container.toString()\n if (containerValue !== \"\" || this._materialized) {\n return containerValue\n }\n // Return placeholder if available and container is at default state\n if (this.placeholder !== undefined) {\n return this.placeholder as string\n }\n return containerValue\n }\n\n valueOf(): string {\n return this.toString()\n }\n\n toJSON(): string {\n return this.toString()\n }\n\n [Symbol.toPrimitive](_hint: string): string {\n return this.toString()\n }\n\n update(text: string): void {\n this.assertMutable()\n this._materialized = true\n this.container.update(text)\n this.commitIfAuto()\n }\n\n mark(range: { start: number; end: number }, key: string, value: any): void {\n this.assertMutable()\n this._materialized = true\n this.container.mark(range, key, value)\n this.commitIfAuto()\n }\n\n unmark(range: { start: number; end: number }, key: string): void {\n this.assertMutable()\n this._materialized = true\n this.container.unmark(range, key)\n this.commitIfAuto()\n }\n\n toDelta(): any[] {\n return this.container.toDelta()\n }\n\n applyDelta(delta: any[]): void {\n this.assertMutable()\n this._materialized = true\n this.container.applyDelta(delta)\n this.commitIfAuto()\n }\n\n get length(): number {\n return this.container.length\n }\n}\n","import type { TreeContainerShape } from \"../shape.js\"\nimport { TypedRef } from \"./base.js\"\n\n// Tree typed ref\nexport class TreeRef<T extends TreeContainerShape> extends TypedRef<T> {\n absorbPlainValues() {\n // TODO(duane): implement for trees\n }\n\n createNode(parent?: any, index?: number): any {\n this.assertMutable()\n return this.container.createNode(parent, index)\n }\n\n move(target: any, parent?: any, index?: number): void {\n this.assertMutable()\n this.container.move(target, parent, index)\n }\n\n delete(target: any): void {\n this.assertMutable()\n this.container.delete(target)\n }\n\n has(target: any): boolean {\n return this.container.has(target)\n }\n\n getNodeByID(id: any): any {\n return this.container.getNodeByID\n ? this.container.getNodeByID(id)\n : undefined\n }\n}\n","import type { LoroDoc } from \"loro-crdt\"\nimport type { Infer } from \"../index.js\"\nimport type { ContainerShape, DocShape } from \"../shape.js\"\nimport { TypedRef, type TypedRefParams } from \"./base.js\"\nimport {\n createContainerTypedRef,\n serializeRefToJSON,\n unwrapReadonlyPrimitive,\n} from \"./utils.js\"\n\nconst containerGetter = {\n counter: \"getCounter\",\n list: \"getList\",\n movableList: \"getMovableList\",\n record: \"getMap\",\n struct: \"getMap\", // Structs use LoroMap as their underlying container\n text: \"getText\",\n tree: \"getTree\",\n} as const\n\n// Doc Ref class -- the actual object passed to the change `mutation` function\nexport class DocRef<Shape extends DocShape> extends TypedRef<Shape> {\n private _doc: LoroDoc\n private propertyCache = new Map<string, TypedRef<ContainerShape>>()\n private requiredPlaceholder!: Infer<Shape>\n\n constructor(\n _params: Omit<TypedRefParams<Shape>, \"getContainer\" | \"getDoc\"> & {\n doc: LoroDoc\n autoCommit?: boolean\n },\n ) {\n super({\n ..._params,\n getContainer: () => {\n throw new Error(\"can't get container on DocRef\")\n },\n getDoc: () => this._doc,\n })\n if (!_params.placeholder) throw new Error(\"placeholder required\")\n this._doc = _params.doc\n this.requiredPlaceholder = _params.placeholder\n this.createLazyProperties()\n }\n\n getTypedRefParams<S extends ContainerShape>(\n key: string,\n shape: S,\n ): TypedRefParams<ContainerShape> {\n const getter = this._doc[containerGetter[shape._type]].bind(this._doc)\n\n return {\n shape,\n placeholder: this.requiredPlaceholder[key],\n getContainer: () => getter(key),\n readonly: this.readonly,\n autoCommit: this._params.autoCommit,\n getDoc: () => this._doc,\n }\n }\n\n getOrCreateTypedRef(\n key: string,\n shape: ContainerShape,\n ): TypedRef<ContainerShape> | number | string {\n if (\n this.readonly &&\n (shape._type === \"counter\" || shape._type === \"text\")\n ) {\n // Check if the container exists in the doc without creating it\n const shallow = this._doc.getShallowValue()\n if (!shallow[key]) {\n return this.requiredPlaceholder[key] as any\n }\n }\n\n let ref = this.propertyCache.get(key)\n\n if (!ref) {\n ref = createContainerTypedRef(this.getTypedRefParams(key, shape))\n this.propertyCache.set(key, ref)\n }\n\n if (this.readonly) {\n return unwrapReadonlyPrimitive(ref, shape)\n }\n\n return ref\n }\n\n private createLazyProperties(): void {\n for (const key in this.shape.shapes) {\n const shape = this.shape.shapes[key]\n Object.defineProperty(this, key, {\n get: () => this.getOrCreateTypedRef(key, shape),\n enumerable: true,\n })\n }\n }\n\n toJSON(): Infer<Shape> {\n return serializeRefToJSON(\n this as any,\n Object.keys(this.shape.shapes),\n ) as Infer<Shape>\n }\n\n absorbPlainValues(): void {\n // By iterating over the propertyCache, we achieve a small optimization\n // by only absorbing values that have been 'touched' in some way\n for (const [, ref] of this.propertyCache.entries()) {\n ref.absorbPlainValues()\n }\n }\n}\n","import type {\n ArrayValueShape,\n ContainerOrValueShape,\n DiscriminatedUnionValueShape,\n DocShape,\n ListContainerShape,\n MovableListContainerShape,\n RecordContainerShape,\n RecordValueShape,\n StringValueShape,\n StructContainerShape,\n StructValueShape,\n UnionValueShape,\n ValueShape,\n} from \"./shape.js\"\nimport type { Infer } from \"./types.js\"\n\n/**\n * Validates a value against a ContainerShape or ValueShape schema\n */\nexport function validateValue(\n value: unknown,\n schema: ContainerOrValueShape,\n path: string = \"\",\n): unknown {\n if (!schema || typeof schema !== \"object\" || !(\"_type\" in schema)) {\n throw new Error(`Invalid schema at path ${path}: missing _type`)\n }\n\n const currentPath = path || \"root\"\n\n // Handle ContainerShape types\n if (schema._type === \"text\") {\n if (typeof value !== \"string\") {\n throw new Error(\n `Expected string at path ${currentPath}, got ${typeof value}`,\n )\n }\n return value\n }\n\n if (schema._type === \"counter\") {\n if (typeof value !== \"number\") {\n throw new Error(\n `Expected number at path ${currentPath}, got ${typeof value}`,\n )\n }\n return value\n }\n\n if (schema._type === \"list\" || schema._type === \"movableList\") {\n if (!Array.isArray(value)) {\n throw new Error(\n `Expected array at path ${currentPath}, got ${typeof value}`,\n )\n }\n const listSchema = schema as ListContainerShape | MovableListContainerShape\n return value.map((item, index) =>\n validateValue(item, listSchema.shape, `${currentPath}[${index}]`),\n )\n }\n\n if (schema._type === \"struct\") {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(\n `Expected object at path ${currentPath}, got ${typeof value}`,\n )\n }\n const structSchema = schema as StructContainerShape\n const result: Record<string, unknown> = {}\n\n // Validate each property in the struct shape\n for (const [key, nestedSchema] of Object.entries(structSchema.shapes)) {\n const nestedPath = `${currentPath}.${key}`\n const nestedValue = (value as Record<string, unknown>)[key]\n result[key] = validateValue(nestedValue, nestedSchema, nestedPath)\n }\n return result\n }\n\n if (schema._type === \"record\") {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(\n `Expected object at path ${currentPath}, got ${typeof value}`,\n )\n }\n const recordSchema = schema as RecordContainerShape\n const result: Record<string, unknown> = {}\n\n // Validate each property in the record\n for (const [key, nestedValue] of Object.entries(value)) {\n const nestedPath = `${currentPath}.${key}`\n result[key] = validateValue(nestedValue, recordSchema.shape, nestedPath)\n }\n return result\n }\n\n if (schema._type === \"tree\") {\n if (!Array.isArray(value)) {\n throw new Error(\n `Expected array for tree at path ${currentPath}, got ${typeof value}`,\n )\n }\n // Trees can contain any structure, so we just validate it's an array\n return value\n }\n\n // Handle ValueShape types\n if (schema._type === \"value\") {\n const valueSchema = schema as ValueShape\n\n switch (valueSchema.valueType) {\n case \"string\": {\n if (typeof value !== \"string\") {\n throw new Error(\n `Expected string at path ${currentPath}, got ${typeof value}`,\n )\n }\n const stringSchema = valueSchema as StringValueShape\n if (stringSchema.options && !stringSchema.options.includes(value)) {\n throw new Error(\n `Expected one of [${stringSchema.options.join(\", \")}] at path ${currentPath}, got \"${value}\"`,\n )\n }\n return value\n }\n\n case \"number\":\n if (typeof value !== \"number\") {\n throw new Error(\n `Expected number at path ${currentPath}, got ${typeof value}`,\n )\n }\n return value\n\n case \"boolean\":\n if (typeof value !== \"boolean\") {\n throw new Error(\n `Expected boolean at path ${currentPath}, got ${typeof value}`,\n )\n }\n return value\n\n case \"null\":\n if (value !== null) {\n throw new Error(\n `Expected null at path ${currentPath}, got ${typeof value}`,\n )\n }\n return value\n\n case \"undefined\":\n if (value !== undefined) {\n throw new Error(\n `Expected undefined at path ${currentPath}, got ${typeof value}`,\n )\n }\n return value\n\n case \"uint8array\":\n if (!(value instanceof Uint8Array)) {\n throw new Error(\n `Expected Uint8Array at path ${currentPath}, got ${typeof value}`,\n )\n }\n return value\n\n case \"struct\": {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(\n `Expected object at path ${currentPath}, got ${typeof value}`,\n )\n }\n const structSchema = valueSchema as StructValueShape\n const result: Record<string, unknown> = {}\n\n // Validate each property in the struct shape\n for (const [key, nestedSchema] of Object.entries(structSchema.shape)) {\n const nestedPath = `${currentPath}.${key}`\n const nestedValue = (value as Record<string, unknown>)[key]\n result[key] = validateValue(nestedValue, nestedSchema, nestedPath)\n }\n return result\n }\n\n case \"record\": {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(\n `Expected object at path ${currentPath}, got ${typeof value}`,\n )\n }\n const recordSchema = valueSchema as RecordValueShape\n const result: Record<string, unknown> = {}\n\n // Validate each property in the record\n for (const [key, nestedValue] of Object.entries(value)) {\n const nestedPath = `${currentPath}.${key}`\n result[key] = validateValue(\n nestedValue,\n recordSchema.shape,\n nestedPath,\n )\n }\n return result\n }\n\n case \"array\": {\n if (!Array.isArray(value)) {\n throw new Error(\n `Expected array at path ${currentPath}, got ${typeof value}`,\n )\n }\n const arraySchema = valueSchema as ArrayValueShape\n return value.map((item, index) =>\n validateValue(item, arraySchema.shape, `${currentPath}[${index}]`),\n )\n }\n\n case \"union\": {\n const unionSchema = valueSchema as UnionValueShape\n let lastError: Error | null = null\n\n // Try to validate against each shape in the union\n for (const shape of unionSchema.shapes) {\n try {\n return validateValue(value, shape, currentPath)\n } catch (error) {\n lastError = error as Error\n }\n }\n\n throw new Error(\n `Value at path ${currentPath} does not match any union type: ${lastError?.message}`,\n )\n }\n\n case \"discriminatedUnion\": {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(\n `Expected object at path ${currentPath}, got ${typeof value}`,\n )\n }\n\n const unionSchema = valueSchema as DiscriminatedUnionValueShape\n const discriminantKey = unionSchema.discriminantKey\n const discriminantValue = (value as Record<string, unknown>)[\n discriminantKey\n ]\n\n if (typeof discriminantValue !== \"string\") {\n throw new Error(\n `Expected string for discriminant key \"${discriminantKey}\" at path ${currentPath}, got ${typeof discriminantValue}`,\n )\n }\n\n const variantSchema = unionSchema.variants[discriminantValue]\n\n if (!variantSchema) {\n throw new Error(\n `Invalid discriminant value \"${discriminantValue}\" at path ${currentPath}. Expected one of: ${Object.keys(\n unionSchema.variants,\n ).join(\", \")}`,\n )\n }\n\n return validateValue(value, variantSchema, currentPath)\n }\n\n default:\n throw new Error(`Unknown value type: ${(valueSchema as any).valueType}`)\n }\n }\n\n throw new Error(`Unknown schema type: ${(schema as any)._type}`)\n}\n\n/**\n * Validates placeholder against schema structure without using Zod\n * Combines the functionality of createPlaceholderValidator and createValueValidator\n */\nexport function validatePlaceholder<T extends DocShape>(\n placeholder: unknown,\n schema: T,\n): Infer<T> {\n if (\n !placeholder ||\n typeof placeholder !== \"object\" ||\n Array.isArray(placeholder)\n ) {\n throw new Error(\"Placeholder must be an object\")\n }\n\n const result: Record<string, unknown> = {}\n\n // Validate each property in the document schema\n for (const [key, schemaValue] of Object.entries(schema.shapes)) {\n const value = (placeholder as Record<string, unknown>)[key]\n result[key] = validateValue(value, schemaValue, key)\n }\n\n return result as Infer<T>\n}\n","import { deriveShapePlaceholder } from \"./derive-placeholder.js\"\nimport { mergeValue } from \"./overlay.js\"\nimport type { ObjectValue, PresenceInterface } from \"./presence-interface.js\"\nimport type { ContainerShape, ValueShape } from \"./shape.js\"\nimport type { Infer } from \"./types.js\"\n\n/**\n * A strongly-typed wrapper around a PresenceInterface.\n * Provides type-safe access to presence data with automatic placeholder merging.\n *\n * @typeParam S - The shape of the presence data\n */\nexport class TypedPresence<S extends ContainerShape | ValueShape> {\n private placeholder: Infer<S>\n\n constructor(\n public shape: S,\n private presence: PresenceInterface,\n ) {\n this.placeholder = deriveShapePlaceholder(shape) as Infer<S>\n }\n\n /**\n * Get the current peer's presence state with placeholder values merged in.\n */\n get self(): Infer<S> {\n return mergeValue(\n this.shape,\n this.presence.self,\n this.placeholder,\n ) as Infer<S>\n }\n\n /**\n * Get other peers' presence states with placeholder values merged in.\n * Does NOT include self. Use this for iterating over remote peers.\n */\n get peers(): Map<string, Infer<S>> {\n const result = new Map<string, Infer<S>>()\n for (const [peerId, value] of this.presence.peers) {\n result.set(\n peerId,\n mergeValue(this.shape, value, this.placeholder) as Infer<S>,\n )\n }\n return result\n }\n\n /**\n * Get all peers' presence states with placeholder values merged in.\n * @deprecated Use `peers` and `self` separately. This property is synthesized\n * from `peers` and `self` for backward compatibility.\n */\n get all(): Record<string, Infer<S>> {\n const result: Record<string, Infer<S>> = {}\n const all = this.presence.all\n for (const peerId of Object.keys(all)) {\n result[peerId] = mergeValue(\n this.shape,\n all[peerId],\n this.placeholder,\n ) as Infer<S>\n }\n return result\n }\n\n /**\n * Set presence values for the current peer.\n */\n set(value: Partial<Infer<S>>) {\n this.presence.set(value as ObjectValue)\n }\n\n /**\n * Subscribe to presence changes.\n * The callback is called immediately with the current state, then on each change.\n *\n * @param cb Callback that receives the typed presence state\n * @returns Unsubscribe function\n */\n subscribe(\n cb: (state: {\n self: Infer<S>\n peers: Map<string, Infer<S>>\n /** @deprecated Use `peers` and `self` separately */\n all: Record<string, Infer<S>>\n }) => void,\n ): () => void {\n // Initial call\n cb({ self: this.self, peers: this.peers, all: this.all })\n\n return this.presence.subscribe(() => {\n cb({ self: this.self, peers: this.peers, all: this.all })\n })\n }\n}\n"],"mappings":";AASO,SAAS,kBACd,QACyB;AACzB,QAAM,SAAkC,CAAC;AAEzC,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,OAAO,MAAM,GAAG;AACxD,WAAO,GAAG,IAAI,uBAAuB,KAAK;AAAA,EAC5C;AAEA,SAAO;AACT;AAQO,SAAS,uBAAuB,OAAuC;AAC5E,UAAQ,MAAM,OAAO;AAAA;AAAA,IAEnB,KAAK;AACH,aAAO,MAAM;AAAA,IACf,KAAK;AACH,aAAO,MAAM;AAAA;AAAA,IAGf,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACH,aAAO,CAAC;AAAA,IACV,KAAK;AACH,aAAO,CAAC;AAAA;AAAA,IAGV,KAAK,UAAU;AACb,YAAM,SAAkC,CAAC;AACzC,iBAAW,CAAC,KAAK,WAAW,KAAK,OAAO,QAAQ,MAAM,MAAM,GAAG;AAC7D,eAAO,GAAG,IAAI,uBAAuB,WAAW;AAAA,MAClD;AACA,aAAO;AAAA,IACT;AAAA,IAEA,KAAK;AACH,aAAO,4BAA4B,KAAK;AAAA,IAE1C;AACE,aAAO;AAAA,EACX;AACF;AAEA,SAAS,4BAA4B,OAA4B;AAC/D,UAAQ,MAAM,WAAW;AAAA;AAAA,IAEvB,KAAK;AACH,aAAO,MAAM;AAAA,IACf,KAAK;AACH,aAAO,MAAM;AAAA,IACf,KAAK;AACH,aAAO,MAAM;AAAA,IACf,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO,MAAM;AAAA;AAAA,IAGf,KAAK,UAAU;AACb,YAAM,SAAkC,CAAC;AACzC,iBAAW,CAAC,KAAK,WAAW,KAAK,OAAO,QAAQ,MAAM,KAAK,GAAG;AAC5D,eAAO,GAAG,IAAI,4BAA4B,WAAW;AAAA,MACvD;AACA,aAAO;AA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;AAAA,QACf,KAAK;AAAA,QACL,IAAI,MAAM;AAAA,QACV,KAAK;AAAA,MACP;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAKA,IAAI,OAA0B;AAC5B,SAAK,SAAS,IAAI,KAAoB;AAAA,EACxC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,UACE,IAMY;AAEZ,OAAG,EAAE,MAAM,KAAK,MAAM,OAAO,KAAK,OAAO,KAAK,KAAK,IAAI,CAAC;AAExD,WAAO,KAAK,SAAS,UAAU,MAAM;AACnC,SAAG,EAAE,MAAM,KAAK,MAAM,OAAO,KAAK,OAAO,KAAK,KAAK,IAAI,CAAC;AAAA,IAC1D,CAAC;AAAA,EACH;AACF;","names":["target","value","LoroCounter","LoroList","LoroMap","LoroMovableList","LoroText","LoroCounter","LoroList","LoroMovableList","LoroMap","LoroText"]}
1
+ {"version":3,"sources":["../src/derive-placeholder.ts","../src/functional-helpers.ts","../src/utils/type-guards.ts","../src/overlay.ts","../src/placeholder-proxy.ts","../src/shape.ts","../src/typed-doc.ts","../src/json-patch.ts","../src/typed-refs/base.ts","../src/typed-refs/utils.ts","../src/typed-refs/counter.ts","../src/conversion.ts","../src/typed-refs/list-base.ts","../src/typed-refs/list.ts","../src/typed-refs/movable-list.ts","../src/typed-refs/proxy-handlers.ts","../src/typed-refs/record.ts","../src/typed-refs/struct.ts","../src/typed-refs/text.ts","../src/typed-refs/tree.ts","../src/typed-refs/doc.ts","../src/validation.ts","../src/typed-presence.ts"],"sourcesContent":["import type { ContainerOrValueShape, DocShape, ValueShape } from \"./shape.js\"\nimport type { InferPlaceholderType } from \"./types.js\"\n\n/**\n * Derives the placeholder state from a schema by composing placeholder values.\n *\n * For leaf nodes (text, counter, values): uses _placeholder directly\n * For containers (map, list, record): recurses into nested shapes\n */\nexport function derivePlaceholder<T extends DocShape>(\n schema: T,\n): InferPlaceholderType<T> {\n const result: Record<string, unknown> = {}\n\n for (const [key, shape] of Object.entries(schema.shapes)) {\n result[key] = deriveShapePlaceholder(shape)\n }\n\n return result as InferPlaceholderType<T>\n}\n\n/**\n * Derives placeholder for a single shape.\n *\n * Leaf nodes: return _placeholder directly\n * Containers: recurse into nested shapes (ignore _placeholder on containers)\n */\nexport function deriveShapePlaceholder(shape: ContainerOrValueShape): unknown {\n switch (shape._type) {\n // Leaf containers - use _placeholder directly\n case \"text\":\n return shape._placeholder\n case \"counter\":\n return shape._placeholder\n\n // Dynamic containers - always empty (no per-entry merging)\n case \"list\":\n case \"movableList\":\n case \"tree\":\n return []\n case \"record\":\n return {}\n\n // Structured container - recurse into nested shapes\n case \"struct\": {\n const result: Record<string, unknown> = {}\n for (const [key, nestedShape] of Object.entries(shape.shapes)) {\n result[key] = deriveShapePlaceholder(nestedShape)\n }\n return result\n }\n\n case \"value\":\n return deriveValueShapePlaceholder(shape)\n\n default:\n return undefined\n }\n}\n\nfunction deriveValueShapePlaceholder(shape: ValueShape): unknown {\n switch (shape.valueType) {\n // Leaf values - use _placeholder directly\n case \"string\":\n return shape._placeholder\n case \"number\":\n return shape._placeholder\n case \"boolean\":\n return shape._placeholder\n case \"null\":\n return null\n case \"undefined\":\n return undefined\n case \"uint8array\":\n return shape._placeholder\n\n // Structured value - recurse into nested shapes (like struct)\n case \"struct\": {\n const result: Record<string, unknown> = {}\n for (const [key, nestedShape] of Object.entries(shape.shape)) {\n result[key] = deriveValueShapePlaceholder(nestedShape)\n }\n return result\n }\n\n // Dynamic values - always empty\n case \"array\":\n return []\n case \"record\":\n return {}\n\n // Unions - use _placeholder if explicitly set, otherwise derive from first variant\n case \"union\": {\n // Check if _placeholder was explicitly set (not the default empty object)\n // We need to check if it's a primitive value OR a non-empty object\n const placeholder = shape._placeholder\n if (placeholder !== undefined) {\n // If it's a primitive (null, string, number, boolean), use it\n if (placeholder === null || typeof placeholder !== \"object\") {\n return placeholder\n }\n // If it's an object with keys, use it\n if (Object.keys(placeholder as object).length > 0) {\n return placeholder\n }\n }\n // Otherwise derive from first variant\n return deriveValueShapePlaceholder(shape.shapes[0])\n }\n\n case \"discriminatedUnion\": {\n // Check if _placeholder was explicitly set (not the default empty object)\n const placeholder = shape._placeholder\n if (placeholder !== undefined) {\n // If it's a primitive (null, string, number, boolean), use it\n if (placeholder === null || typeof placeholder !== \"object\") {\n return placeholder\n }\n // If it's an object with keys, use it\n if (Object.keys(placeholder as object).length > 0) {\n return placeholder\n }\n }\n // Otherwise derive from first variant\n const firstKey = Object.keys(shape.variants)[0]\n return deriveValueShapePlaceholder(shape.variants[firstKey])\n }\n\n default:\n return undefined\n }\n}\n","import type { LoroDoc } from \"loro-crdt\"\nimport type { DocShape } from \"./shape.js\"\nimport type { TypedDoc } from \"./typed-doc.js\"\nimport type { Mutable } from \"./types.js\"\n\n/**\n * The primary method of mutating typed documents.\n * Batches multiple mutations into a single transaction.\n * All changes commit together at the end.\n *\n * Use this for:\n * - Find-and-mutate operations (required due to JS limitations)\n * - Performance (fewer commits)\n * - Atomic undo (all changes = one undo step)\n *\n * Returns the doc for chaining.\n *\n * @param doc - The TypedDoc to mutate\n * @param fn - Function that performs mutations on the draft\n * @returns The same TypedDoc for chaining\n *\n * @example\n * ```typescript\n * import { change } from \"@loro-extended/change\"\n *\n * // Chainable API\n * change(doc, draft => {\n * draft.count.increment(10)\n * draft.title.update(\"Hello\")\n * })\n * .count.increment(5) // Optional: continue mutating\n * .toJSON() // Optional: get last item snapshot when needed\n * ```\n */\nexport function change<Shape extends DocShape>(\n doc: TypedDoc<Shape>,\n fn: (draft: Mutable<Shape>) => void,\n): TypedDoc<Shape> {\n return doc.$.change(fn)\n}\n\n/**\n * Access the underlying LoroDoc for advanced operations.\n *\n * @param doc - The TypedDoc to unwrap\n * @returns The underlying LoroDoc instance\n *\n * @example\n * ```typescript\n * import { getLoroDoc } from \"@loro-extended/change\"\n *\n * const loroDoc = getLoroDoc(doc)\n * const version = loroDoc.version()\n * loroDoc.subscribe(() => console.log(\"changed\"))\n * ```\n */\nexport function getLoroDoc<Shape extends DocShape>(\n doc: TypedDoc<Shape>,\n): LoroDoc {\n return doc.$.loroDoc\n}\n","import type {\n Container,\n LoroCounter,\n LoroList,\n LoroMap,\n LoroMovableList,\n LoroText,\n LoroTree,\n LoroTreeNode,\n Value,\n} from \"loro-crdt\"\nimport type {\n ContainerOrValueShape,\n ContainerShape,\n CounterContainerShape,\n ListContainerShape,\n MovableListContainerShape,\n RecordContainerShape,\n StructContainerShape,\n TextContainerShape,\n TreeContainerShape,\n ValueShape,\n} from \"../shape.js\"\n\nexport { isContainer, isContainerId } from \"loro-crdt\"\n\n/**\n * Type guard to check if a container is a LoroCounter\n */\nexport function isLoroCounter(container: Container): container is LoroCounter {\n return container.kind() === \"Counter\"\n}\n\n/**\n * Type guard to check if a container is a LoroList\n */\nexport function isLoroList(container: Container): container is LoroList {\n return container.kind() === \"List\"\n}\n\n/**\n * Type guard to check if a container is a LoroMap\n */\nexport function isLoroMap(container: Container): container is LoroMap {\n return container.kind() === \"Map\"\n}\n\n/**\n * Type guard to check if a container is a LoroMovableList\n */\nexport function isLoroMovableList(\n container: Container,\n): container is LoroMovableList {\n return container.kind() === \"MovableList\"\n}\n\n/**\n * Type guard to check if a container is a LoroText\n */\nexport function isLoroText(container: Container): container is LoroText {\n return container.kind() === \"Text\"\n}\n\n/**\n * Type guard to check if a container is a LoroTree\n */\nexport function isLoroTree(container: Container): container is LoroTree {\n return container.kind() === \"Tree\"\n}\n\n/**\n * Type guard to check if an object is a LoroTreeNode\n * Note: LoroTreeNode is not a Container, so we check for its specific properties\n */\nexport function isLoroTreeNode(obj: any): obj is LoroTreeNode {\n return (\n obj &&\n typeof obj === \"object\" &&\n typeof obj.id === \"string\" &&\n typeof obj.data === \"object\" &&\n typeof obj.parent === \"function\" &&\n typeof obj.children === \"function\" &&\n typeof obj.createNode === \"function\"\n )\n}\n\n/**\n * Type guard to ensure cached container matches expected type using kind() method\n */\nexport function assertContainerType<T extends Container>(\n cached: Container,\n expected: T,\n context: string = \"container operation\",\n): asserts cached is T {\n if (cached.kind() !== expected.kind()) {\n throw new Error(\n `Type safety violation in ${context}: ` +\n `cached container kind '${cached.kind()}' does not match ` +\n `expected kind '${expected.kind()}'`,\n )\n }\n\n // Additional safety check: ensure IDs match\n if (cached.id !== expected.id) {\n throw new Error(\n `Container ID mismatch in ${context}: ` +\n `cached ID '${cached.id}' does not match expected ID '${expected.id}'`,\n )\n }\n}\n\n/**\n * Type guard to check if a schema is for TextDraftNode\n */\nexport function isTextShape(\n schema: ContainerOrValueShape,\n): schema is TextContainerShape {\n return schema && typeof schema === \"object\" && schema._type === \"text\"\n}\n\n/**\n * Type guard to check if a schema is for CounterDraftNode\n */\nexport function isCounterShape(\n schema: ContainerOrValueShape,\n): schema is CounterContainerShape {\n return schema && typeof schema === \"object\" && schema._type === \"counter\"\n}\n\n/**\n * Type guard to check if a schema is for ListDraftNode\n */\nexport function isListShape(\n schema: ContainerOrValueShape,\n): schema is ListContainerShape {\n return schema && typeof schema === \"object\" && schema._type === \"list\"\n}\n\n/**\n * Type guard to check if a schema is for MovableListDraftNode\n */\nexport function isMovableListShape(\n schema: ContainerOrValueShape,\n): schema is MovableListContainerShape {\n return schema && typeof schema === \"object\" && schema._type === \"movableList\"\n}\n\n/**\n * Type guard to check if a schema is for StructDraftNode\n */\nexport function isStructShape(\n schema: ContainerOrValueShape,\n): schema is StructContainerShape {\n return schema && typeof schema === \"object\" && schema._type === \"struct\"\n}\n\n/**\n * @deprecated Use isStructShape instead. isMapShape is an alias for backward compatibility.\n */\nexport const isMapShape = isStructShape\n\n/**\n * Type guard to check if a schema is for RecordDraftNode\n */\nexport function isRecordShape(\n schema: ContainerOrValueShape,\n): schema is RecordContainerShape {\n return schema && typeof schema === \"object\" && schema._type === \"record\"\n}\n\n/**\n * Type guard to check if a schema is for TreeDraftNode\n */\nexport function isTreeShape(\n schema: ContainerOrValueShape,\n): schema is TreeContainerShape {\n return schema && typeof schema === \"object\" && schema._type === \"tree\"\n}\n\nexport function isContainerShape(\n schema: ContainerOrValueShape,\n): schema is ContainerShape {\n return schema._type && schema._type !== \"value\"\n}\n\n/**\n * Type guard to check if a schema is any of the Value shapes\n */\nexport function isValueShape(\n schema: ContainerOrValueShape,\n): schema is ValueShape {\n return (\n schema._type === \"value\" &&\n [\n \"string\",\n \"number\",\n \"boolean\",\n \"null\",\n \"undefined\",\n \"uint8array\",\n \"struct\",\n \"record\",\n \"array\",\n \"union\",\n \"discriminatedUnion\",\n ].includes(schema.valueType)\n )\n}\n\nexport function isObjectValue(value: Value): value is { [key: string]: Value } {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n !(value instanceof Uint8Array)\n )\n}\n","import type { Value } from \"loro-crdt\"\nimport { deriveShapePlaceholder } from \"./derive-placeholder.js\"\nimport type {\n ContainerShape,\n DiscriminatedUnionValueShape,\n DocShape,\n ValueShape,\n} from \"./shape.js\"\nimport { isObjectValue } from \"./utils/type-guards.js\"\n\n/**\n * Overlays CRDT state with placeholder defaults\n */\nexport function overlayPlaceholder<Shape extends DocShape>(\n shape: Shape,\n crdtValue: { [key: string]: Value },\n placeholderValue: { [key: string]: Value },\n): { [key: string]: Value } {\n if (typeof crdtValue !== \"object\") {\n throw new Error(\"crdt object is required\")\n }\n\n if (typeof placeholderValue !== \"object\") {\n throw new Error(\"placeholder object is required\")\n }\n\n const result = { ...placeholderValue }\n\n for (const [key, propShape] of Object.entries(shape.shapes)) {\n const propCrdtValue = crdtValue[key]\n\n const propPlaceholderValue =\n placeholderValue[key as keyof typeof placeholderValue]\n\n result[key as keyof typeof result] = mergeValue(\n propShape,\n propCrdtValue,\n propPlaceholderValue,\n )\n }\n\n return result\n}\n\n/**\n * Merges individual CRDT values with placeholder defaults\n */\nexport function mergeValue<Shape extends ContainerShape | ValueShape>(\n shape: Shape,\n crdtValue: Value,\n placeholderValue: Value,\n): Value {\n if (crdtValue === undefined && placeholderValue === undefined) {\n throw new Error(\"either crdt or placeholder value must be defined\")\n }\n\n switch (shape._type) {\n case \"text\":\n return crdtValue !== undefined ? crdtValue : (placeholderValue ?? \"\")\n case \"counter\":\n return crdtValue !== undefined ? crdtValue : (placeholderValue ?? 0)\n case \"list\":\n case \"movableList\": {\n if (crdtValue === undefined) {\n return placeholderValue ?? []\n }\n\n const crdtArray = crdtValue as Value[]\n const itemShape = shape.shape\n const itemPlaceholder = deriveShapePlaceholder(itemShape)\n\n return crdtArray.map(item =>\n mergeValue(itemShape, item, itemPlaceholder as Value),\n )\n }\n case \"struct\": {\n if (!isObjectValue(crdtValue) && crdtValue !== undefined) {\n throw new Error(\"struct crdt must be object\")\n }\n\n const crdtStructValue = crdtValue ?? {}\n\n if (!isObjectValue(placeholderValue) && placeholderValue !== undefined) {\n throw new Error(\"struct placeholder must be object\")\n }\n\n const placeholderStructValue = placeholderValue ?? {}\n\n const result = { ...placeholderStructValue }\n for (const [key, nestedShape] of Object.entries(shape.shapes)) {\n const nestedCrdtValue = crdtStructValue[key]\n const nestedPlaceholderValue = placeholderStructValue[key]\n\n result[key as keyof typeof result] = mergeValue(\n nestedShape,\n nestedCrdtValue,\n nestedPlaceholderValue,\n )\n }\n\n return result\n }\n case \"tree\":\n return crdtValue !== undefined ? crdtValue : (placeholderValue ?? [])\n case \"record\": {\n if (!isObjectValue(crdtValue) && crdtValue !== undefined) {\n throw new Error(\"record crdt must be object\")\n }\n\n const crdtRecordValue = (crdtValue as Record<string, Value>) ?? {}\n const result: Record<string, Value> = {}\n\n // For records, we iterate over the keys present in the CRDT value\n // and apply the nested shape's placeholder logic to each value\n for (const key of Object.keys(crdtRecordValue)) {\n const nestedCrdtValue = crdtRecordValue[key]\n // For records, the placeholder is always {}, so we need to derive\n // the placeholder for the nested shape on the fly\n const nestedPlaceholderValue = deriveShapePlaceholder(shape.shape)\n\n result[key] = mergeValue(\n shape.shape,\n nestedCrdtValue,\n nestedPlaceholderValue as Value,\n )\n }\n\n return result\n }\n default:\n if (shape._type === \"value\" && shape.valueType === \"struct\") {\n const crdtObj = (crdtValue as any) ?? {}\n const placeholderObj = (placeholderValue as any) ?? {}\n const result = { ...placeholderObj }\n\n if (typeof crdtObj !== \"object\" || crdtObj === null) {\n return crdtValue !== undefined ? crdtValue : placeholderValue\n }\n\n for (const [key, propShape] of Object.entries(shape.shape)) {\n const propCrdt = crdtObj[key]\n const propPlaceholder = placeholderObj[key]\n result[key] = mergeValue(propShape, propCrdt, propPlaceholder)\n }\n return result\n }\n\n // Handle discriminated unions\n if (shape._type === \"value\" && shape.valueType === \"discriminatedUnion\") {\n return mergeDiscriminatedUnion(\n shape as DiscriminatedUnionValueShape,\n crdtValue,\n placeholderValue,\n )\n }\n\n return crdtValue !== undefined ? crdtValue : placeholderValue\n }\n}\n\n/**\n * Merges a discriminated union value by determining the variant from the discriminant key.\n * Uses the placeholderValue's discriminant to determine the default variant when the discriminant is missing.\n */\nfunction mergeDiscriminatedUnion(\n shape: DiscriminatedUnionValueShape,\n crdtValue: Value,\n placeholderValue: Value,\n): Value {\n const crdtObj = (crdtValue as Record<string, Value>) ?? {}\n const placeholderObj = (placeholderValue as Record<string, Value>) ?? {}\n\n // Get the discriminant value from CRDT, falling back to placeholder\n const discriminantValue =\n crdtObj[shape.discriminantKey] ?? placeholderObj[shape.discriminantKey]\n\n if (typeof discriminantValue !== \"string\") {\n // If no valid discriminant, return the placeholder\n return placeholderValue\n }\n\n // Find the variant shape for this discriminant value\n const variantShape = shape.variants[discriminantValue]\n\n if (!variantShape) {\n // Unknown variant - return CRDT value or placeholder\n return crdtValue !== undefined ? crdtValue : placeholderValue\n }\n\n // Merge using the variant's object shape\n // If the placeholder's discriminant doesn't match the current discriminant,\n // we shouldn't use the placeholder for merging as it belongs to a different variant.\n const placeholderDiscriminant = placeholderObj[shape.discriminantKey]\n const effectivePlaceholderValue =\n placeholderDiscriminant === discriminantValue ? placeholderValue : undefined\n\n return mergeValue(variantShape, crdtValue, effectivePlaceholderValue as Value)\n}\n","/**\n * Creates a proxy around a placeholder value (plain object/array) that mimics\n * the behavior of TypedRef, specifically adding a .toJSON() method.\n *\n * This ensures consistent UX where users can call .toJSON() on document state\n * regardless of whether it's loading (placeholder) or loaded (live ref).\n */\nexport function createPlaceholderProxy<T extends object>(target: T): T {\n // Cache for wrapped properties to ensure referential stability\n const cache = new Map<string | symbol, any>()\n\n return new Proxy(target, {\n get(target, prop, receiver) {\n // Intercept .toJSON()\n if (prop === \"toJSON\") {\n return () => target\n }\n\n // Check cache first\n if (cache.has(prop)) {\n return cache.get(prop)\n }\n\n // Get value from target\n const value = Reflect.get(target, prop, receiver)\n\n // Recursively wrap objects/arrays\n if (value && typeof value === \"object\") {\n const wrapped = createPlaceholderProxy(value)\n cache.set(prop, wrapped)\n return wrapped\n }\n\n return value\n },\n })\n}\n","// biome-ignore-all lint/suspicious/noExplicitAny: required\n\nimport type {\n LoroCounter,\n LoroList,\n LoroMap,\n LoroMovableList,\n LoroText,\n LoroTree,\n} from \"loro-crdt\"\n\nimport type { CounterRef } from \"./typed-refs/counter.js\"\nimport type { ListRef } from \"./typed-refs/list.js\"\nimport type { MovableListRef } from \"./typed-refs/movable-list.js\"\nimport type { RecordRef } from \"./typed-refs/record.js\"\nimport type { StructRef } from \"./typed-refs/struct.js\"\nimport type { TextRef } from \"./typed-refs/text.js\"\n\nexport interface Shape<Plain, Mutable, Placeholder = Plain> {\n readonly _type: string\n readonly _plain: Plain\n readonly _mutable: Mutable\n readonly _placeholder: Placeholder\n}\n\n// Type for shapes that support placeholder customization\nexport type WithPlaceholder<S extends Shape<any, any, any>> = S & {\n placeholder(value: S[\"_placeholder\"]): S\n}\n\n/**\n * Type for value shapes that support the .nullable() method.\n * Returns a union of null and the original shape with null as the default placeholder.\n */\nexport type WithNullable<S extends ValueShape> = {\n nullable(): WithPlaceholder<UnionValueShape<[NullValueShape, S]>>\n}\n\nexport interface DocShape<\n NestedShapes extends Record<string, ContainerShape> = Record<\n string,\n ContainerShape\n >,\n> extends Shape<\n { [K in keyof NestedShapes]: NestedShapes[K][\"_plain\"] },\n { [K in keyof NestedShapes]: NestedShapes[K][\"_mutable\"] },\n { [K in keyof NestedShapes]: NestedShapes[K][\"_placeholder\"] }\n > {\n readonly _type: \"doc\"\n // A doc's root containers each separately has its own shape, hence 'shapes'\n readonly shapes: NestedShapes\n}\n\nexport interface TextContainerShape extends Shape<string, TextRef, string> {\n readonly _type: \"text\"\n}\nexport interface CounterContainerShape\n extends Shape<number, CounterRef, number> {\n readonly _type: \"counter\"\n}\nexport interface TreeContainerShape<NestedShape = ContainerOrValueShape>\n extends Shape<any, any, never[]> {\n readonly _type: \"tree\"\n // TODO(duane): What does a tree contain? One type, or many?\n readonly shape: NestedShape\n}\n\n// Container schemas using interfaces for recursive references\n// NOTE: List and Record use never[] and Record<string, never> for Placeholder\n// to enforce that only empty values ([] and {}) are valid in placeholder state.\n// This prevents users from expecting per-entry merging behavior.\nexport interface ListContainerShape<\n NestedShape extends ContainerOrValueShape = ContainerOrValueShape,\n> extends Shape<NestedShape[\"_plain\"][], ListRef<NestedShape>, never[]> {\n readonly _type: \"list\"\n // A list contains many elements, all of the same 'shape'\n readonly shape: NestedShape\n}\n\nexport interface MovableListContainerShape<\n NestedShape extends ContainerOrValueShape = ContainerOrValueShape,\n> extends Shape<NestedShape[\"_plain\"][], MovableListRef<NestedShape>, never[]> {\n readonly _type: \"movableList\"\n // A list contains many elements, all of the same 'shape'\n readonly shape: NestedShape\n}\n\n/**\n * @deprecated Use StructContainerShape instead. MapContainerShape is an alias for backward compatibility.\n */\nexport type MapContainerShape<\n NestedShapes extends Record<string, ContainerOrValueShape> = Record<\n string,\n ContainerOrValueShape\n >,\n> = StructContainerShape<NestedShapes>\n\n/**\n * Container shape for objects with fixed keys (structs).\n * This is the preferred way to define fixed-key objects.\n * Uses LoroMap as the underlying container.\n */\nexport interface StructContainerShape<\n NestedShapes extends Record<string, ContainerOrValueShape> = Record<\n string,\n ContainerOrValueShape\n >,\n> extends Shape<\n { [K in keyof NestedShapes]: NestedShapes[K][\"_plain\"] },\n StructRef<NestedShapes> & {\n [K in keyof NestedShapes]: NestedShapes[K][\"_mutable\"]\n },\n { [K in keyof NestedShapes]: NestedShapes[K][\"_placeholder\"] }\n > {\n readonly _type: \"struct\"\n // Each struct property has its own shape, hence 'shapes'\n readonly shapes: NestedShapes\n}\n\nexport interface RecordContainerShape<\n NestedShape extends ContainerOrValueShape = ContainerOrValueShape,\n> extends Shape<\n Record<string, NestedShape[\"_plain\"]>,\n RecordRef<NestedShape>,\n Record<string, never>\n > {\n readonly _type: \"record\"\n readonly shape: NestedShape\n}\n\nexport type ContainerShape =\n | CounterContainerShape\n | ListContainerShape\n | MovableListContainerShape\n | RecordContainerShape\n | StructContainerShape\n | TextContainerShape\n | TreeContainerShape\n\nexport type ContainerType = ContainerShape[\"_type\"]\n\n// LoroValue shape types - a shape for each of Loro's Value types\nexport interface StringValueShape<T extends string = string>\n extends Shape<T, T, T> {\n readonly _type: \"value\"\n readonly valueType: \"string\"\n readonly options?: T[]\n}\nexport interface NumberValueShape extends Shape<number, number, number> {\n readonly _type: \"value\"\n readonly valueType: \"number\"\n}\nexport interface BooleanValueShape extends Shape<boolean, boolean, boolean> {\n readonly _type: \"value\"\n readonly valueType: \"boolean\"\n}\nexport interface NullValueShape extends Shape<null, null, null> {\n readonly _type: \"value\"\n readonly valueType: \"null\"\n}\nexport interface UndefinedValueShape\n extends Shape<undefined, undefined, undefined> {\n readonly _type: \"value\"\n readonly valueType: \"undefined\"\n}\nexport interface Uint8ArrayValueShape\n extends Shape<Uint8Array, Uint8Array, Uint8Array> {\n readonly _type: \"value\"\n readonly valueType: \"uint8array\"\n}\n\n/**\n * @deprecated Use StructValueShape instead. ObjectValueShape is an alias for backward compatibility.\n */\nexport type ObjectValueShape<\n T extends Record<string, ValueShape> = Record<string, ValueShape>,\n> = StructValueShape<T>\n\n/**\n * Value shape for objects with fixed keys (structs).\n * This is the preferred way to define fixed-key plain value objects.\n * Identical structure to ObjectValueShape but with valueType: \"struct\".\n */\nexport interface StructValueShape<\n T extends Record<string, ValueShape> = Record<string, ValueShape>,\n> extends Shape<\n { [K in keyof T]: T[K][\"_plain\"] },\n { [K in keyof T]: T[K][\"_mutable\"] },\n { [K in keyof T]: T[K][\"_placeholder\"] }\n > {\n readonly _type: \"value\"\n readonly valueType: \"struct\"\n readonly shape: T\n}\n\n// NOTE: RecordValueShape and ArrayValueShape use Record<string, never> and never[]\n// for Placeholder to enforce that only empty values ({} and []) are valid.\nexport interface RecordValueShape<T extends ValueShape = ValueShape>\n extends Shape<\n Record<string, T[\"_plain\"]>,\n Record<string, T[\"_mutable\"]>,\n Record<string, never>\n > {\n readonly _type: \"value\"\n readonly valueType: \"record\"\n readonly shape: T\n}\n\nexport interface ArrayValueShape<T extends ValueShape = ValueShape>\n extends Shape<T[\"_plain\"][], T[\"_mutable\"][], never[]> {\n readonly _type: \"value\"\n readonly valueType: \"array\"\n readonly shape: T\n}\n\nexport interface UnionValueShape<T extends ValueShape[] = ValueShape[]>\n extends Shape<\n T[number][\"_plain\"],\n T[number][\"_mutable\"],\n T[number][\"_placeholder\"]\n > {\n readonly _type: \"value\"\n readonly valueType: \"union\"\n readonly shapes: T\n}\n\n/**\n * A discriminated union shape that uses a discriminant key to determine which variant to use.\n * This enables type-safe handling of tagged unions like:\n *\n * ```typescript\n * type GamePresence =\n * | { type: \"client\"; name: string; input: { force: number; angle: number } }\n * | { type: \"server\"; cars: Record<string, CarState>; tick: number }\n * ```\n *\n * @typeParam K - The discriminant key (e.g., \"type\")\n * @typeParam T - A record mapping discriminant values to their object shapes\n */\nexport interface DiscriminatedUnionValueShape<\n K extends string = string,\n T extends Record<string, StructValueShape> = Record<string, StructValueShape>,\n Plain = T[keyof T][\"_plain\"],\n Mutable = T[keyof T][\"_mutable\"],\n Placeholder = T[keyof T][\"_placeholder\"],\n> extends Shape<Plain, Mutable, Placeholder> {\n readonly _type: \"value\"\n readonly valueType: \"discriminatedUnion\"\n readonly discriminantKey: K\n readonly variants: T\n}\n\n// Union of all ValueShapes - these can only contain other ValueShapes, not ContainerShapes\nexport type ValueShape =\n | StringValueShape\n | NumberValueShape\n | BooleanValueShape\n | NullValueShape\n | UndefinedValueShape\n | Uint8ArrayValueShape\n | StructValueShape\n | RecordValueShape\n | ArrayValueShape\n | UnionValueShape\n | DiscriminatedUnionValueShape\n\nexport type ContainerOrValueShape = ContainerShape | ValueShape\n\n/**\n * Creates a nullable version of a value shape.\n * @internal\n */\nfunction makeNullable<S extends ValueShape>(\n shape: S,\n): WithPlaceholder<UnionValueShape<[NullValueShape, S]>> {\n const nullShape: NullValueShape = {\n _type: \"value\" as const,\n valueType: \"null\" as const,\n _plain: null,\n _mutable: null,\n _placeholder: null,\n }\n\n const base: UnionValueShape<[NullValueShape, S]> = {\n _type: \"value\" as const,\n valueType: \"union\" as const,\n shapes: [nullShape, shape] as [NullValueShape, S],\n _plain: null as any,\n _mutable: null as any,\n _placeholder: null as any, // Default placeholder is null\n }\n\n return Object.assign(base, {\n placeholder(\n value: S[\"_placeholder\"] | null,\n ): UnionValueShape<[NullValueShape, S]> {\n return { ...base, _placeholder: value } as UnionValueShape<\n [NullValueShape, S]\n >\n },\n })\n}\n\n/**\n * The LoroShape factory object\n *\n * If a container has a `shape` type variable, it refers to the shape it contains--\n * so for example, a `LoroShape.list(LoroShape.text())` would return a value of type\n * `ListContainerShape<TextContainerShape>`.\n */\nexport const Shape = {\n doc: <T extends Record<string, ContainerShape>>(shape: T): DocShape<T> => ({\n _type: \"doc\" as const,\n shapes: shape,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as any,\n }),\n\n // CRDTs are represented by Loro Containers--they converge on state using Loro's\n // various CRDT algorithms\n counter: (): WithPlaceholder<CounterContainerShape> => {\n const base: CounterContainerShape = {\n _type: \"counter\" as const,\n _plain: 0,\n _mutable: {} as CounterRef,\n _placeholder: 0,\n }\n return Object.assign(base, {\n placeholder(value: number): CounterContainerShape {\n return { ...base, _placeholder: value }\n },\n })\n },\n\n list: <T extends ContainerOrValueShape>(shape: T): ListContainerShape<T> => ({\n _type: \"list\" as const,\n shape,\n _plain: [] as any,\n _mutable: {} as any,\n _placeholder: [] as never[],\n }),\n\n /**\n * Creates a struct container shape for objects with fixed keys.\n * This is the preferred way to define fixed-key objects.\n *\n * @example\n * ```typescript\n * const UserSchema = Shape.doc({\n * user: Shape.struct({\n * name: Shape.text(),\n * age: Shape.counter(),\n * }),\n * })\n * ```\n */\n struct: <T extends Record<string, ContainerOrValueShape>>(\n shape: T,\n ): StructContainerShape<T> => ({\n _type: \"struct\" as const,\n shapes: shape,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as any,\n }),\n\n /**\n * @deprecated Use `Shape.struct` instead. `Shape.struct` will be removed in a future version.\n */\n map: <T extends Record<string, ContainerOrValueShape>>(\n shape: T,\n ): StructContainerShape<T> => ({\n _type: \"struct\" as const,\n shapes: shape,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as any,\n }),\n\n record: <T extends ContainerOrValueShape>(\n shape: T,\n ): RecordContainerShape<T> => ({\n _type: \"record\" as const,\n shape,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as Record<string, never>,\n }),\n\n movableList: <T extends ContainerOrValueShape>(\n shape: T,\n ): MovableListContainerShape<T> => ({\n _type: \"movableList\" as const,\n shape,\n _plain: [] as any,\n _mutable: {} as any,\n _placeholder: [] as never[],\n }),\n\n text: (): WithPlaceholder<TextContainerShape> => {\n const base: TextContainerShape = {\n _type: \"text\" as const,\n _plain: \"\",\n _mutable: {} as TextRef,\n _placeholder: \"\",\n }\n return Object.assign(base, {\n placeholder(value: string): TextContainerShape {\n return { ...base, _placeholder: value }\n },\n })\n },\n\n tree: <T extends MapContainerShape | StructContainerShape>(\n shape: T,\n ): TreeContainerShape => ({\n _type: \"tree\" as const,\n shape,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: [] as never[],\n }),\n\n // Values are represented as plain JS objects, with the limitation that they MUST be\n // representable as a Loro \"Value\"--basically JSON. The behavior of a Value is basically\n // \"Last Write Wins\", meaning there is no subtle convergent behavior here, just taking\n // the most recent value based on the current available information.\n plain: {\n string: <T extends string = string>(\n ...options: T[]\n ): WithPlaceholder<StringValueShape<T>> &\n WithNullable<StringValueShape<T>> => {\n const base: StringValueShape<T> = {\n _type: \"value\" as const,\n valueType: \"string\" as const,\n _plain: (options[0] ?? \"\") as T,\n _mutable: (options[0] ?? \"\") as T,\n _placeholder: (options[0] ?? \"\") as T,\n options: options.length > 0 ? options : undefined,\n }\n return Object.assign(base, {\n placeholder(value: T): StringValueShape<T> {\n return { ...base, _placeholder: value }\n },\n nullable(): WithPlaceholder<\n UnionValueShape<[NullValueShape, StringValueShape<T>]>\n > {\n return makeNullable(base)\n },\n })\n },\n\n number: (): WithPlaceholder<NumberValueShape> &\n WithNullable<NumberValueShape> => {\n const base: NumberValueShape = {\n _type: \"value\" as const,\n valueType: \"number\" as const,\n _plain: 0,\n _mutable: 0,\n _placeholder: 0,\n }\n return Object.assign(base, {\n placeholder(value: number): NumberValueShape {\n return { ...base, _placeholder: value }\n },\n nullable(): WithPlaceholder<\n UnionValueShape<[NullValueShape, NumberValueShape]>\n > {\n return makeNullable(base)\n },\n })\n },\n\n boolean: (): WithPlaceholder<BooleanValueShape> &\n WithNullable<BooleanValueShape> => {\n const base: BooleanValueShape = {\n _type: \"value\" as const,\n valueType: \"boolean\" as const,\n _plain: false,\n _mutable: false,\n _placeholder: false,\n }\n return Object.assign(base, {\n placeholder(value: boolean): BooleanValueShape {\n return { ...base, _placeholder: value }\n },\n nullable(): WithPlaceholder<\n UnionValueShape<[NullValueShape, BooleanValueShape]>\n > {\n return makeNullable(base)\n },\n })\n },\n\n null: (): NullValueShape => ({\n _type: \"value\" as const,\n valueType: \"null\" as const,\n _plain: null,\n _mutable: null,\n _placeholder: null,\n }),\n\n undefined: (): UndefinedValueShape => ({\n _type: \"value\" as const,\n valueType: \"undefined\" as const,\n _plain: undefined,\n _mutable: undefined,\n _placeholder: undefined,\n }),\n\n uint8Array: (): Uint8ArrayValueShape => ({\n _type: \"value\" as const,\n valueType: \"uint8array\" as const,\n _plain: new Uint8Array(),\n _mutable: new Uint8Array(),\n _placeholder: new Uint8Array(),\n }),\n\n /**\n * Creates a struct value shape for plain objects with fixed keys.\n * This is the preferred way to define fixed-key plain value objects.\n *\n * @example\n * ```typescript\n * const PointSchema = Shape.plain.struct({\n * x: Shape.plain.number(),\n * y: Shape.plain.number(),\n * })\n * ```\n */\n struct: <T extends Record<string, ValueShape>>(\n shape: T,\n ): StructValueShape<T> & WithNullable<StructValueShape<T>> => {\n const base: StructValueShape<T> = {\n _type: \"value\" as const,\n valueType: \"struct\" as const,\n shape,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as any,\n }\n return Object.assign(base, {\n nullable(): WithPlaceholder<\n UnionValueShape<[NullValueShape, StructValueShape<T>]>\n > {\n return makeNullable(base)\n },\n })\n },\n\n /**\n * @deprecated Use `Shape.plain.struct` instead. `Shape.plain.struct` will be removed in a future version.\n */\n object: <T extends Record<string, ValueShape>>(\n shape: T,\n ): StructValueShape<T> & WithNullable<StructValueShape<T>> => {\n const base: StructValueShape<T> = {\n _type: \"value\" as const,\n valueType: \"struct\" as const,\n shape,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as any,\n }\n return Object.assign(base, {\n nullable(): WithPlaceholder<\n UnionValueShape<[NullValueShape, StructValueShape<T>]>\n > {\n return makeNullable(base)\n },\n })\n },\n\n record: <T extends ValueShape>(\n shape: T,\n ): RecordValueShape<T> & WithNullable<RecordValueShape<T>> => {\n const base: RecordValueShape<T> = {\n _type: \"value\" as const,\n valueType: \"record\" as const,\n shape,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as Record<string, never>,\n }\n return Object.assign(base, {\n nullable(): WithPlaceholder<\n UnionValueShape<[NullValueShape, RecordValueShape<T>]>\n > {\n return makeNullable(base)\n },\n })\n },\n\n array: <T extends ValueShape>(\n shape: T,\n ): ArrayValueShape<T> & WithNullable<ArrayValueShape<T>> => {\n const base: ArrayValueShape<T> = {\n _type: \"value\" as const,\n valueType: \"array\" as const,\n shape,\n _plain: [] as any,\n _mutable: [] as any,\n _placeholder: [] as never[],\n }\n return Object.assign(base, {\n nullable(): WithPlaceholder<\n UnionValueShape<[NullValueShape, ArrayValueShape<T>]>\n > {\n return makeNullable(base)\n },\n })\n },\n\n // Special value type that helps make things like `string | null` representable\n // TODO(duane): should this be a more general type for containers too?\n union: <T extends ValueShape[]>(\n shapes: T,\n ): WithPlaceholder<UnionValueShape<T>> => {\n const base: UnionValueShape<T> = {\n _type: \"value\" as const,\n valueType: \"union\" as const,\n shapes,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as any,\n }\n return Object.assign(base, {\n placeholder(value: T[number][\"_placeholder\"]): UnionValueShape<T> {\n return { ...base, _placeholder: value }\n },\n })\n },\n\n /**\n * Creates a discriminated union shape for type-safe tagged unions.\n *\n * @example\n * ```typescript\n * const ClientPresenceShape = Shape.plain.struct({\n * type: Shape.plain.string(\"client\"),\n * name: Shape.plain.string(),\n * input: Shape.plain.struct({ force: Shape.plain.number(), angle: Shape.plain.number() }),\n * })\n *\n * const ServerPresenceShape = Shape.plain.struct({\n * type: Shape.plain.string(\"server\"),\n * cars: Shape.plain.record(Shape.plain.struct({ x: Shape.plain.number(), y: Shape.plain.number() })),\n * tick: Shape.plain.number(),\n * })\n *\n * const GamePresenceSchema = Shape.plain.discriminatedUnion(\"type\", {\n * client: ClientPresenceShape,\n * server: ServerPresenceShape,\n * })\n * ```\n *\n * @param discriminantKey - The key used to discriminate between variants (e.g., \"type\")\n * @param variants - A record mapping discriminant values to their object shapes\n */\n discriminatedUnion: <\n K extends string,\n T extends Record<string, StructValueShape>,\n >(\n discriminantKey: K,\n variants: T,\n ): WithPlaceholder<DiscriminatedUnionValueShape<K, T>> => {\n const base: DiscriminatedUnionValueShape<K, T> = {\n _type: \"value\" as const,\n valueType: \"discriminatedUnion\" as const,\n discriminantKey,\n variants,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as any,\n }\n return Object.assign(base, {\n placeholder(\n value: T[keyof T][\"_placeholder\"],\n ): DiscriminatedUnionValueShape<K, T> {\n return { ...base, _placeholder: value }\n },\n })\n },\n },\n}\n\n// Add this type mapping near the top of your file, after the imports\nexport type ShapeToContainer<T extends DocShape | ContainerShape> =\n T extends TextContainerShape\n ? LoroText\n : T extends CounterContainerShape\n ? LoroCounter\n : T extends ListContainerShape\n ? LoroList\n : T extends MovableListContainerShape\n ? LoroMovableList\n : T extends StructContainerShape | RecordContainerShape\n ? LoroMap\n : T extends TreeContainerShape\n ? LoroTree\n : never // not a container\n","/** biome-ignore-all lint/suspicious/noExplicitAny: fix later */\n\nimport { LoroDoc } from \"loro-crdt\"\nimport { derivePlaceholder } from \"./derive-placeholder.js\"\nimport {\n type JsonPatch,\n JsonPatchApplicator,\n type JsonPatchOperation,\n normalizePath,\n} from \"./json-patch.js\"\nimport { overlayPlaceholder } from \"./overlay.js\"\nimport type { DocShape } from \"./shape.js\"\nimport { DocRef } from \"./typed-refs/doc.js\"\nimport type { Infer, InferPlaceholderType, Mutable } from \"./types.js\"\nimport { validatePlaceholder } from \"./validation.js\"\n\n/**\n * Meta-operations namespace for TypedDoc.\n * Access via doc.$ to perform batch operations, serialization, etc.\n */\nexport class TypedDocMeta<Shape extends DocShape> {\n constructor(private internal: TypedDocInternal<Shape>) {}\n\n /**\n * The primary method of mutating typed documents.\n * Batches multiple mutations into a single transaction.\n * All changes commit together at the end.\n *\n * Use this for:\n * - Find-and-mutate operations (required due to JS limitations)\n * - Performance (fewer commits)\n * - Atomic undo (all changes = one undo step)\n *\n * Returns the doc for chaining.\n */\n change(fn: (draft: Mutable<Shape>) => void): TypedDoc<Shape> {\n this.internal.change(fn)\n return this.internal.proxy as TypedDoc<Shape>\n }\n\n /**\n * Returns the full plain JavaScript object representation of the document.\n * This is an expensive O(N) operation that serializes the entire document.\n */\n toJSON(): Infer<Shape> {\n return this.internal.toJSON()\n }\n\n /**\n * Apply JSON Patch operations to the document\n *\n * @param patch - Array of JSON Patch operations (RFC 6902)\n * @param pathPrefix - Optional path prefix for scoped operations\n * @returns Updated document value\n */\n applyPatch(\n patch: JsonPatch,\n pathPrefix?: (string | number)[],\n ): TypedDoc<Shape> {\n this.internal.applyPatch(patch, pathPrefix)\n return this.internal.proxy as TypedDoc<Shape>\n }\n\n /**\n * Access the underlying LoroDoc for advanced operations.\n */\n get loroDoc(): LoroDoc {\n return this.internal.loroDoc\n }\n\n /**\n * Access the document schema shape.\n */\n get docShape(): Shape {\n return this.internal.docShape\n }\n\n /**\n * Get raw CRDT value without placeholder overlay.\n */\n get rawValue(): any {\n return this.internal.rawValue\n }\n}\n\n/**\n * Internal TypedDoc implementation (not directly exposed to users).\n * Users interact with the proxied version that provides direct schema access.\n */\nclass TypedDocInternal<Shape extends DocShape> {\n private shape: Shape\n private placeholder: InferPlaceholderType<Shape>\n private doc: LoroDoc\n private _valueRef: DocRef<Shape> | null = null\n // Reference to the proxy for returning from change()\n proxy: TypedDoc<Shape> | null = null\n\n constructor(shape: Shape, doc: LoroDoc = new LoroDoc()) {\n this.shape = shape\n this.placeholder = derivePlaceholder(shape)\n this.doc = doc\n\n validatePlaceholder(this.placeholder, this.shape)\n }\n\n get value(): Mutable<Shape> {\n if (!this._valueRef) {\n this._valueRef = new DocRef({\n shape: this.shape,\n placeholder: this.placeholder as any,\n doc: this.doc,\n autoCommit: true,\n })\n }\n return this._valueRef as unknown as Mutable<Shape>\n }\n\n toJSON(): Infer<Shape> {\n const crdtValue = this.doc.toJSON()\n return overlayPlaceholder(\n this.shape,\n crdtValue,\n this.placeholder as any,\n ) as Infer<Shape>\n }\n\n change(fn: (draft: Mutable<Shape>) => void): void {\n const draft = new DocRef({\n shape: this.shape,\n placeholder: this.placeholder as any,\n doc: this.doc,\n autoCommit: false,\n })\n fn(draft as unknown as Mutable<Shape>)\n draft.absorbPlainValues()\n this.doc.commit()\n\n // Invalidate cached value ref since doc changed\n this._valueRef = null\n }\n\n applyPatch(patch: JsonPatch, pathPrefix?: (string | number)[]): void {\n this.change(draft => {\n const applicator = new JsonPatchApplicator(draft)\n\n const prefixedPatch = pathPrefix\n ? patch.map((op: JsonPatchOperation) => ({\n ...op,\n path: [...pathPrefix, ...normalizePath(op.path)],\n }))\n : patch\n\n applicator.applyPatch(prefixedPatch)\n })\n }\n\n get loroDoc(): LoroDoc {\n return this.doc\n }\n\n get docShape(): Shape {\n return this.shape\n }\n\n get rawValue(): any {\n return this.doc.toJSON()\n }\n}\n\n/**\n * The proxied TypedDoc type that provides direct schema access.\n * Schema properties are accessed directly on the doc object.\n * Meta-operations are available via the $ namespace.\n *\n * @example\n * ```typescript\n * const doc = createTypedDoc(schema);\n *\n * // Direct schema access\n * doc.count.increment(5);\n * doc.title.insert(0, \"Hello\");\n *\n * // Serialize to JSON (works on doc and all refs)\n * const snapshot = doc.toJSON();\n * const users = doc.users.toJSON();\n *\n * // Meta-operations via $ (escape hatch)\n * doc.$.change(draft => { ... });\n * doc.$.loroDoc;\n * ```\n */\nexport type TypedDoc<Shape extends DocShape> = Mutable<Shape> & {\n /**\n * Meta-operations namespace.\n * Use for change(), loroDoc, etc.\n */\n $: TypedDocMeta<Shape>\n\n /**\n * Returns the full plain JavaScript object representation of the document.\n * This is an O(N) operation that serializes the entire document.\n *\n * @example\n * ```typescript\n * const snapshot = doc.toJSON();\n * console.log(snapshot.count); // number\n * ```\n */\n toJSON(): Infer<Shape>\n}\n\n/**\n * Creates a new TypedDoc with the given schema.\n * Returns a proxied document where schema properties are accessed directly.\n *\n * @param shape - The document schema (with optional .placeholder() values)\n * @param existingDoc - Optional existing LoroDoc to wrap\n * @returns A proxied TypedDoc with direct schema access and $ namespace\n *\n * @example\n * ```typescript\n * const schema = Shape.doc({\n * title: Shape.text(),\n * count: Shape.counter(),\n * });\n *\n * const doc = createTypedDoc(schema);\n *\n * // Direct mutations (auto-commit)\n * doc.count.increment(5);\n * doc.title.insert(0, \"Hello\");\n *\n * // Batched mutations are committed together via `change`\n * doc.$.change(draft => {\n * draft.count.increment(10);\n * draft.title.update(\"World\");\n * });\n *\n * // Get plain JSON\n * const snapshot = doc.toJSON();\n * ```\n */\nexport function createTypedDoc<Shape extends DocShape>(\n shape: Shape,\n existingDoc?: LoroDoc,\n): TypedDoc<Shape> {\n const internal = new TypedDocInternal(shape, existingDoc || new LoroDoc())\n const meta = new TypedDocMeta(internal)\n\n // Create a proxy that delegates schema properties to the DocRef\n // and provides $ namespace for meta-operations\n const proxy = new Proxy(internal.value as object, {\n get(target, prop, receiver) {\n // $ namespace for meta-operations\n if (prop === \"$\") {\n return meta\n }\n\n // toJSON() should always read fresh from the CRDT\n if (prop === \"toJSON\") {\n return () => internal.toJSON()\n }\n\n // Delegate to the DocRef (which is the target)\n return Reflect.get(target, prop, receiver)\n },\n\n set(target, prop, value, receiver) {\n // Don't allow setting $ namespace\n if (prop === \"$\") {\n return false\n }\n\n // Delegate to the DocRef\n return Reflect.set(target, prop, value, receiver)\n },\n\n // Support 'in' operator\n has(target, prop) {\n if (prop === \"$\") return true\n return Reflect.has(target, prop)\n },\n\n // Support Object.keys() - don't include $ in enumeration\n ownKeys(target) {\n return Reflect.ownKeys(target)\n },\n\n getOwnPropertyDescriptor(target, prop) {\n if (prop === \"$\") {\n return {\n configurable: true,\n enumerable: false,\n value: meta,\n }\n }\n return Reflect.getOwnPropertyDescriptor(target, prop)\n },\n }) as TypedDoc<Shape>\n\n // Store reference to proxy for returning from change()\n internal.proxy = proxy\n\n return proxy\n}\n","/** biome-ignore-all lint/suspicious/noExplicitAny: JSON Patch values can be any type */\n\nimport type { DocShape } from \"./shape.js\"\nimport type { Draft } from \"./types.js\"\n\n// =============================================================================\n// JSON PATCH TYPES - Discriminated Union for Type Safety\n// =============================================================================\n\nexport type JsonPatchAddOperation = {\n op: \"add\"\n path: string | (string | number)[]\n value: any\n}\n\nexport type JsonPatchRemoveOperation = {\n op: \"remove\"\n path: string | (string | number)[]\n}\n\nexport type JsonPatchReplaceOperation = {\n op: \"replace\"\n path: string | (string | number)[]\n value: any\n}\n\nexport type JsonPatchMoveOperation = {\n op: \"move\"\n path: string | (string | number)[]\n from: string | (string | number)[]\n}\n\nexport type JsonPatchCopyOperation = {\n op: \"copy\"\n path: string | (string | number)[]\n from: string | (string | number)[]\n}\n\nexport type JsonPatchTestOperation = {\n op: \"test\"\n path: string | (string | number)[]\n value: any\n}\n\nexport type JsonPatchOperation =\n | JsonPatchAddOperation\n | JsonPatchRemoveOperation\n | JsonPatchReplaceOperation\n | JsonPatchMoveOperation\n | JsonPatchCopyOperation\n | JsonPatchTestOperation\n\nexport type JsonPatch = JsonPatchOperation[]\n\n// =============================================================================\n// PATH NAVIGATION UTILITIES\n// =============================================================================\n\n/**\n * Normalize JSON Pointer string to path array\n * Handles RFC 6901 escaping: ~1 -> /, ~0 -> ~\n */\nexport function normalizePath(\n path: string | (string | number)[],\n): (string | number)[] {\n if (Array.isArray(path)) {\n return path\n }\n\n // Handle JSON Pointer format (RFC 6901)\n if (path.startsWith(\"/\")) {\n return path\n .slice(1) // Remove leading slash\n .split(\"/\")\n .map(segment => {\n // Handle JSON Pointer escaping\n const unescaped = segment.replace(/~1/g, \"/\").replace(/~0/g, \"~\")\n // Try to parse as number for array indices\n const asNumber = Number(unescaped)\n return Number.isInteger(asNumber) && asNumber >= 0\n ? asNumber\n : unescaped\n })\n }\n\n // Handle simple dot notation or single segment\n return path.split(\".\").map(segment => {\n const asNumber = Number(segment)\n return Number.isInteger(asNumber) && asNumber >= 0 ? asNumber : segment\n })\n}\n\n/**\n * Navigate to a target path using natural DraftNode property access\n * This follows the existing patterns from the test suite\n */\nfunction navigateToPath<T extends DocShape>(\n draft: Draft<T>,\n path: (string | number)[],\n): { parent: any; key: string | number } {\n if (path.length === 0) {\n throw new Error(\"Cannot navigate to empty path\")\n }\n\n let current = draft as any\n\n // Navigate to parent of target\n for (let i = 0; i < path.length - 1; i++) {\n const segment = path[i]\n\n if (typeof segment === \"string\") {\n // Use natural property access - this leverages existing DraftNode lazy creation\n current = current[segment]\n if (current === undefined) {\n throw new Error(`Cannot navigate to path segment: ${segment}`)\n }\n } else if (typeof segment === \"number\") {\n // List/array access using get() method (following existing patterns)\n if (current.get && typeof current.get === \"function\") {\n current = current.get(segment)\n if (current === undefined) {\n throw new Error(`List index ${segment} does not exist`)\n }\n } else {\n throw new Error(`Cannot use numeric index ${segment} on non-list`)\n }\n } else {\n throw new Error(`Invalid path segment type: ${typeof segment}`)\n }\n }\n\n const targetKey = path[path.length - 1]\n return { parent: current, key: targetKey }\n}\n\n/**\n * Get value at path using natural DraftNode access patterns\n */\nfunction getValueAtPath<T extends DocShape>(\n draft: Draft<T>,\n path: (string | number)[],\n): any {\n if (path.length === 0) {\n return draft\n }\n\n const { parent, key } = navigateToPath(draft, path)\n\n if (typeof key === \"string\") {\n // Use natural property access or get() method\n if (parent.get && typeof parent.get === \"function\") {\n return parent.get(key)\n }\n return parent[key]\n } else if (typeof key === \"number\") {\n // List access using get() method\n if (parent.get && typeof parent.get === \"function\") {\n return parent.get(key)\n }\n throw new Error(`Cannot use numeric index ${key} on non-list`)\n }\n\n throw new Error(`Invalid key type: ${typeof key}`)\n}\n\n// =============================================================================\n// OPERATION HANDLERS - Following existing DraftNode patterns\n// =============================================================================\n\n/**\n * Handle 'add' operation using existing DraftNode methods\n */\nfunction handleAdd<T extends DocShape>(\n draft: Draft<T>,\n operation: JsonPatchAddOperation,\n): void {\n const path = normalizePath(operation.path)\n const { parent, key } = navigateToPath(draft, path)\n\n if (typeof key === \"string\") {\n // Map-like operations - use natural assignment or set() method\n if (parent.set && typeof parent.set === \"function\") {\n parent.set(key, operation.value)\n } else {\n // Natural property assignment (follows existing test patterns)\n parent[key] = operation.value\n }\n } else if (typeof key === \"number\") {\n // List operations - use insert() method (follows existing patterns)\n if (parent.insert && typeof parent.insert === \"function\") {\n parent.insert(key, operation.value)\n } else {\n throw new Error(`Cannot insert at numeric index ${key} on non-list`)\n }\n } else {\n throw new Error(`Invalid key type: ${typeof key}`)\n }\n}\n\n/**\n * Handle 'remove' operation using existing DraftNode methods\n */\nfunction handleRemove<T extends DocShape>(\n draft: Draft<T>,\n operation: JsonPatchRemoveOperation,\n): void {\n const path = normalizePath(operation.path)\n const { parent, key } = navigateToPath(draft, path)\n\n if (typeof key === \"string\") {\n // Map-like operations - use delete() method (follows existing patterns)\n if (parent.delete && typeof parent.delete === \"function\") {\n parent.delete(key)\n } else {\n delete parent[key]\n }\n } else if (typeof key === \"number\") {\n // List operations - use delete() method with count (follows existing patterns)\n if (parent.delete && typeof parent.delete === \"function\") {\n parent.delete(key, 1)\n } else {\n throw new Error(`Cannot remove at numeric index ${key} on non-list`)\n }\n } else {\n throw new Error(`Invalid key type: ${typeof key}`)\n }\n}\n\n/**\n * Handle 'replace' operation using existing DraftNode methods\n */\nfunction handleReplace<T extends DocShape>(\n draft: Draft<T>,\n operation: JsonPatchReplaceOperation,\n): void {\n const path = normalizePath(operation.path)\n const { parent, key } = navigateToPath(draft, path)\n\n if (typeof key === \"string\") {\n // Map-like operations - use set() method or natural assignment\n if (parent.set && typeof parent.set === \"function\") {\n parent.set(key, operation.value)\n } else {\n parent[key] = operation.value\n }\n } else if (typeof key === \"number\") {\n // List operations - delete then insert (follows existing patterns)\n if (\n parent.delete &&\n parent.insert &&\n typeof parent.delete === \"function\" &&\n typeof parent.insert === \"function\"\n ) {\n parent.delete(key, 1)\n parent.insert(key, operation.value)\n } else {\n throw new Error(`Cannot replace at numeric index ${key} on non-list`)\n }\n } else {\n throw new Error(`Invalid key type: ${typeof key}`)\n }\n}\n\n/**\n * Handle 'move' operation using existing DraftNode methods\n */\nfunction handleMove<T extends DocShape>(\n draft: Draft<T>,\n operation: JsonPatchMoveOperation,\n): void {\n const fromPath = normalizePath(operation.from)\n const toPath = normalizePath(operation.path)\n\n // For list moves within the same parent, we need special handling\n if (\n fromPath.length === toPath.length &&\n fromPath.slice(0, -1).every((segment, i) => segment === toPath[i])\n ) {\n // Same parent container - use list move operation if available\n const fromIndex = fromPath[fromPath.length - 1]\n const toIndex = toPath[toPath.length - 1]\n\n if (typeof fromIndex === \"number\" && typeof toIndex === \"number\") {\n const { parent } = navigateToPath(draft, fromPath.slice(0, -1))\n\n // Check if the parent has a move method (like LoroMovableList)\n if (parent.move && typeof parent.move === \"function\") {\n parent.move(fromIndex, toIndex)\n return\n }\n\n // Otherwise, get value, remove, then add at target index\n const value = getValueAtPath(draft, fromPath)\n handleRemove(draft, { op: \"remove\", path: operation.from })\n\n // For JSON Patch move semantics, the target index refers to the position\n // in the final array, not the intermediate array after removal.\n // No index adjustment needed - use the original target index.\n handleAdd(draft, { op: \"add\", path: operation.path, value })\n return\n }\n }\n\n // Different parents or non-numeric indices - standard move\n const value = getValueAtPath(draft, fromPath)\n handleRemove(draft, { op: \"remove\", path: operation.from })\n handleAdd(draft, { op: \"add\", path: operation.path, value })\n}\n\n/**\n * Handle 'copy' operation using existing DraftNode methods\n */\nfunction handleCopy<T extends DocShape>(\n draft: Draft<T>,\n operation: JsonPatchCopyOperation,\n): void {\n const fromPath = normalizePath(operation.from)\n\n // Get the value to copy\n const value = getValueAtPath(draft, fromPath)\n\n // Add to destination (no removal)\n handleAdd(draft, { op: \"add\", path: operation.path, value })\n}\n\n/**\n * Handle 'test' operation using existing DraftNode value access\n */\nfunction handleTest<T extends DocShape>(\n draft: Draft<T>,\n operation: JsonPatchTestOperation,\n): boolean {\n const path = normalizePath(operation.path)\n const actualValue = getValueAtPath(draft, path)\n\n // Deep equality check for test operation\n return JSON.stringify(actualValue) === JSON.stringify(operation.value)\n}\n\n// =============================================================================\n// MAIN APPLICATOR - Simple orchestration following existing patterns\n// =============================================================================\n\n/**\n * Main JSON Patch applicator - follows existing change() patterns\n */\nexport class JsonPatchApplicator<T extends DocShape> {\n constructor(private rootDraft: Draft<T>) {}\n\n /**\n * Apply a single JSON Patch operation\n */\n applyOperation(operation: JsonPatchOperation): void {\n switch (operation.op) {\n case \"add\":\n handleAdd(this.rootDraft, operation)\n break\n case \"remove\":\n handleRemove(this.rootDraft, operation)\n break\n case \"replace\":\n handleReplace(this.rootDraft, operation)\n break\n case \"move\":\n handleMove(this.rootDraft, operation)\n break\n case \"copy\":\n handleCopy(this.rootDraft, operation)\n break\n case \"test\":\n if (!handleTest(this.rootDraft, operation)) {\n throw new Error(`JSON Patch test failed at path: ${operation.path}`)\n }\n break\n default:\n // TypeScript will catch this at compile time with proper discriminated union\n throw new Error(\n `Unsupported JSON Patch operation: ${(operation as any).op}`,\n )\n }\n }\n\n /**\n * Apply multiple JSON Patch operations in sequence\n */\n applyPatch(patch: JsonPatch): void {\n for (const operation of patch) {\n this.applyOperation(operation)\n }\n }\n}\n","import type { LoroDoc } from \"loro-crdt\"\nimport type { ContainerShape, DocShape, ShapeToContainer } from \"../shape.js\"\nimport type { Infer } from \"../types.js\"\n\nexport type TypedRefParams<Shape extends DocShape | ContainerShape> = {\n shape: Shape\n placeholder?: Infer<Shape>\n getContainer: () => ShapeToContainer<Shape>\n readonly?: boolean // DEPRECATED - remove in future\n autoCommit?: boolean // NEW: auto-commit after mutations\n getDoc?: () => LoroDoc // NEW: needed for auto-commit\n}\n\n// Base class for all typed refs\nexport abstract class TypedRef<Shape extends DocShape | ContainerShape> {\n protected _cachedContainer?: ShapeToContainer<Shape>\n\n constructor(protected _params: TypedRefParams<Shape>) {}\n\n abstract absorbPlainValues(): void\n\n protected get shape(): Shape {\n return this._params.shape\n }\n\n protected get placeholder(): Infer<Shape> | undefined {\n return this._params.placeholder\n }\n\n protected get readonly(): boolean {\n return !!this._params.readonly\n }\n\n protected get autoCommit(): boolean {\n return !!this._params.autoCommit\n }\n\n protected get doc(): LoroDoc | undefined {\n return this._params.getDoc?.()\n }\n\n /**\n * Commits changes if autoCommit is enabled.\n * Call this after any mutation operation.\n */\n protected commitIfAuto(): void {\n if (this.autoCommit && this.doc) {\n this.doc.commit()\n }\n }\n\n /**\n * Throws an error if this ref is in readonly mode.\n * Call this at the start of any mutating method.\n * @deprecated Mutations are always allowed now; this will be removed.\n */\n protected assertMutable(): void {\n if (this.readonly) {\n throw new Error(\"Cannot modify readonly ref\")\n }\n }\n\n protected get container(): ShapeToContainer<Shape> {\n if (!this._cachedContainer) {\n const container = this._params.getContainer()\n this._cachedContainer = container\n return container\n }\n return this._cachedContainer\n }\n}\n","import {\n LoroCounter,\n LoroList,\n LoroMap,\n LoroMovableList,\n LoroText,\n LoroTree,\n type Value,\n} from \"loro-crdt\"\nimport type {\n ContainerShape,\n CounterContainerShape,\n ListContainerShape,\n MovableListContainerShape,\n RecordContainerShape,\n StructContainerShape,\n TextContainerShape,\n TreeContainerShape,\n} from \"../shape.js\"\nimport { TypedRef, type TypedRefParams } from \"./base.js\"\nimport { CounterRef } from \"./counter.js\"\nimport { ListRef } from \"./list.js\"\nimport { MovableListRef } from \"./movable-list.js\"\nimport {\n listProxyHandler,\n movableListProxyHandler,\n recordProxyHandler,\n} from \"./proxy-handlers.js\"\nimport { RecordRef } from \"./record.js\"\nimport { StructRef } from \"./struct.js\"\nimport { TextRef } from \"./text.js\"\nimport { TreeRef } from \"./tree.js\"\n\n/**\n * Mapping from container shape types to their Loro constructor classes.\n * Used when creating new containers via getOrCreateContainer().\n */\nexport const containerConstructor = {\n counter: LoroCounter,\n list: LoroList,\n movableList: LoroMovableList,\n record: LoroMap, // Records use LoroMap as their underlying container\n struct: LoroMap, // Structs use LoroMap as their underlying container\n text: LoroText,\n tree: LoroTree,\n} as const\n\n/**\n * Unwraps a TypedRef to its primitive value for readonly access.\n * Counter refs return their numeric value, Text refs return their string.\n * Other container types are returned as-is.\n */\nexport function unwrapReadonlyPrimitive(\n ref: TypedRef<any>,\n shape: ContainerShape,\n): any {\n if (shape._type === \"counter\") {\n return (ref as any).value\n }\n if (shape._type === \"text\") {\n return (ref as any).toString()\n }\n return ref\n}\n\n/**\n * Absorbs cached plain values back into a LoroMap container.\n * For TypedRef entries, recursively calls absorbPlainValues().\n * For plain Value entries, sets them directly on the container.\n */\nexport function absorbCachedPlainValues(\n cache: Map<string, TypedRef<ContainerShape> | Value>,\n getContainer: () => LoroMap,\n): void {\n let container: LoroMap | undefined\n\n for (const [key, ref] of cache.entries()) {\n if (ref instanceof TypedRef) {\n // Contains a TypedRef, not a plain Value: keep recursing\n ref.absorbPlainValues()\n } else {\n // Plain value!\n if (!container) container = getContainer()\n container.set(key, ref)\n }\n }\n}\n\n/**\n * Serializes a TypedRef to JSON by iterating over its keys.\n * For nested TypedRefs with toJSON(), calls their toJSON method.\n * For plain values, includes them directly.\n */\nexport function serializeRefToJSON(\n ref: Record<string, any>,\n keys: Iterable<string>,\n): Record<string, any> {\n const result: Record<string, any> = {}\n for (const key of keys) {\n const value = ref[key]\n if (value && typeof value === \"object\" && \"toJSON\" in value) {\n result[key] = value.toJSON()\n } else {\n result[key] = value\n }\n }\n return result\n}\n\n// Generic catch-all overload\nexport function createContainerTypedRef<T extends ContainerShape>(\n params: TypedRefParams<T>,\n): TypedRef<T>\n\n// Implementation\nexport function createContainerTypedRef(\n params: TypedRefParams<ContainerShape>,\n): TypedRef<ContainerShape> {\n switch (params.shape._type) {\n case \"counter\":\n return new CounterRef(params as TypedRefParams<CounterContainerShape>)\n case \"list\":\n return new Proxy(\n new ListRef(params as TypedRefParams<ListContainerShape>),\n listProxyHandler,\n )\n case \"struct\":\n return new StructRef(params as TypedRefParams<StructContainerShape>)\n case \"movableList\":\n return new Proxy(\n new MovableListRef(params as TypedRefParams<MovableListContainerShape>),\n movableListProxyHandler,\n )\n case \"record\":\n return new Proxy(\n new RecordRef(params as TypedRefParams<RecordContainerShape>),\n recordProxyHandler,\n )\n case \"text\":\n return new TextRef(params as TypedRefParams<TextContainerShape>)\n case \"tree\":\n return new TreeRef(params as TypedRefParams<TreeContainerShape>)\n default:\n throw new Error(\n `Unknown container type: ${(params.shape as ContainerShape)._type}`,\n )\n }\n}\n\nexport function assignPlainValueToTypedRef(\n ref: TypedRef<any>,\n value: any,\n): boolean {\n const shapeType = (ref as any).shape._type\n\n if (shapeType === \"struct\" || shapeType === \"record\") {\n for (const k in value) {\n ;(ref as any)[k] = value[k]\n }\n return true\n }\n\n if (shapeType === \"list\" || shapeType === \"movableList\") {\n if (Array.isArray(value)) {\n const listRef = ref as any\n if (listRef.length > 0) {\n listRef.delete(0, listRef.length)\n }\n for (const item of value) {\n listRef.push(item)\n }\n return true\n }\n }\n\n if (shapeType === \"text\") {\n if (typeof value === \"string\") {\n ;(ref as any).update(value)\n return true\n }\n return false\n }\n\n if (shapeType === \"counter\") {\n if (typeof value === \"number\") {\n const currentValue = (ref as any).value\n const diff = value - currentValue\n if (diff > 0) {\n ;(ref as any).increment(diff)\n } else if (diff < 0) {\n ;(ref as any).decrement(-diff)\n }\n return true\n }\n return false\n }\n\n return false\n}\n","import type { LoroCounter } from \"loro-crdt\"\nimport type { CounterContainerShape } from \"../shape.js\"\nimport { TypedRef } from \"./base.js\"\n\n// Counter typed ref\nexport class CounterRef extends TypedRef<CounterContainerShape> {\n // Track if we've materialized the container (made any changes)\n private _materialized = false\n\n protected get container(): LoroCounter {\n return super.container as LoroCounter\n }\n\n absorbPlainValues() {\n // no plain values contained within\n }\n\n increment(value: number = 1): void {\n this.assertMutable()\n this._materialized = true\n this.container.increment(value)\n this.commitIfAuto()\n }\n\n decrement(value: number = 1): void {\n this.assertMutable()\n this._materialized = true\n this.container.decrement(value)\n this.commitIfAuto()\n }\n\n /**\n * Returns the counter value.\n * If the counter hasn't been materialized (no operations performed),\n * returns the placeholder value if available.\n */\n get value(): number {\n // Check if the container has any value (non-zero means it was modified)\n const containerValue = this.container.value\n if (containerValue !== 0 || this._materialized) {\n return containerValue\n }\n // Return placeholder if available and container is at default state\n if (this.placeholder !== undefined) {\n return this.placeholder as number\n }\n return containerValue\n }\n\n valueOf(): number {\n return this.value\n }\n\n toJSON(): number {\n return this.value\n }\n\n [Symbol.toPrimitive](hint: string): number | string {\n if (hint === \"string\") {\n return String(this.value)\n }\n return this.value\n }\n}\n","import {\n type Container,\n LoroCounter,\n LoroList,\n LoroMap,\n LoroMovableList,\n LoroText,\n type Value,\n} from \"loro-crdt\"\nimport type {\n ArrayValueShape,\n ContainerOrValueShape,\n ListContainerShape,\n MovableListContainerShape,\n RecordContainerShape,\n RecordValueShape,\n StructContainerShape,\n StructValueShape,\n} from \"./shape.js\"\nimport {\n isContainer,\n isContainerShape,\n isObjectValue,\n isValueShape,\n} from \"./utils/type-guards.js\"\n\n/**\n * Converts string input to LoroText container\n */\nfunction convertTextInput(value: string): LoroText {\n const text = new LoroText()\n\n text.insert(0, value)\n\n return text\n}\n\n/**\n * Converts number input to LoroCounter container\n */\nfunction convertCounterInput(value: number): LoroCounter {\n const counter = new LoroCounter()\n counter.increment(value)\n return counter\n}\n\n/**\n * Converts array input to LoroList container\n */\nfunction convertListInput(\n value: Value[],\n shape: ListContainerShape | ArrayValueShape,\n // parentPath: string[],\n): LoroList | Value[] {\n if (!isContainerShape(shape)) {\n return value\n }\n\n const list = new LoroList()\n\n for (const item of value) {\n const convertedItem = convertInputToRef(item, shape.shape)\n if (isContainer(convertedItem)) {\n list.pushContainer(convertedItem)\n } else {\n list.push(convertedItem)\n }\n }\n\n return list\n}\n\n/**\n * Converts array input to LoroMovableList container\n */\nfunction convertMovableListInput(\n value: Value[],\n shape: MovableListContainerShape | ArrayValueShape,\n // parentPath: string[],\n): LoroMovableList | Value[] {\n if (!isContainerShape(shape)) {\n return value\n }\n\n const list = new LoroMovableList()\n\n for (const item of value) {\n const convertedItem = convertInputToRef(item, shape.shape)\n if (isContainer(convertedItem)) {\n list.pushContainer(convertedItem)\n } else {\n list.push(convertedItem)\n }\n }\n\n return list\n}\n\n/**\n * Converts object input to LoroMap container (Struct)\n */\nfunction convertStructInput(\n value: { [key: string]: Value },\n shape: StructContainerShape | StructValueShape,\n): LoroMap | { [key: string]: Value } {\n if (!isContainerShape(shape)) {\n return value\n }\n\n const map = new LoroMap()\n for (const [k, v] of Object.entries(value)) {\n const nestedSchema = shape.shapes[k]\n if (nestedSchema) {\n const convertedValue = convertInputToRef(v, nestedSchema)\n if (isContainer(convertedValue)) {\n map.setContainer(k, convertedValue)\n } else {\n map.set(k, convertedValue)\n }\n } else {\n map.set(k, value)\n }\n }\n\n return map\n}\n\n/**\n * Converts object input to LoroMap container (Record)\n */\nfunction convertRecordInput(\n value: { [key: string]: Value },\n shape: RecordContainerShape | RecordValueShape,\n): LoroMap | { [key: string]: Value } {\n if (!isContainerShape(shape)) {\n return value\n }\n\n const map = new LoroMap()\n for (const [k, v] of Object.entries(value)) {\n const convertedValue = convertInputToRef(v, shape.shape)\n if (isContainer(convertedValue)) {\n map.setContainer(k, convertedValue)\n } else {\n map.set(k, convertedValue)\n }\n }\n\n return map\n}\n\n/**\n * Main conversion function that transforms input values to appropriate CRDT containers\n * based on schema definitions\n */\nexport function convertInputToRef<Shape extends ContainerOrValueShape>(\n value: Value,\n shape: Shape,\n): Container | Value {\n switch (shape._type) {\n case \"text\": {\n if (typeof value !== \"string\") {\n throw new Error(\"string expected\")\n }\n\n return convertTextInput(value)\n }\n case \"counter\": {\n if (typeof value !== \"number\") {\n throw new Error(\"number expected\")\n }\n\n return convertCounterInput(value)\n }\n case \"list\": {\n if (!Array.isArray(value)) {\n throw new Error(\"array expected\")\n }\n\n return convertListInput(value, shape)\n }\n case \"movableList\": {\n if (!Array.isArray(value)) {\n throw new Error(\"array expected\")\n }\n\n return convertMovableListInput(value, shape)\n }\n case \"struct\": {\n if (!isObjectValue(value)) {\n throw new Error(\"object expected\")\n }\n\n return convertStructInput(value, shape)\n }\n case \"record\": {\n if (!isObjectValue(value)) {\n throw new Error(\"object expected\")\n }\n\n return convertRecordInput(value, shape)\n }\n case \"value\": {\n if (!isValueShape(shape)) {\n throw new Error(\"value expected\")\n }\n\n return value\n }\n\n case \"tree\":\n throw new Error(\"tree type unimplemented\")\n\n default:\n throw new Error(`unexpected type: ${(shape as Shape)._type}`)\n }\n}\n","import type { Container, LoroList, LoroMovableList } from \"loro-crdt\"\nimport { convertInputToRef } from \"../conversion.js\"\nimport { deriveShapePlaceholder } from \"../derive-placeholder.js\"\nimport { mergeValue } from \"../overlay.js\"\nimport type {\n ContainerOrValueShape,\n ContainerShape,\n ListContainerShape,\n MovableListContainerShape,\n} from \"../shape.js\"\nimport {\n isContainer,\n isContainerShape,\n isValueShape,\n} from \"../utils/type-guards.js\"\nimport { TypedRef, type TypedRefParams } from \"./base.js\"\nimport { createContainerTypedRef, unwrapReadonlyPrimitive } from \"./utils.js\"\n\n// Shared logic for list operations\nexport abstract class ListRefBase<\n NestedShape extends ContainerOrValueShape,\n Item = NestedShape[\"_plain\"],\n MutableItem = NestedShape[\"_mutable\"],\n> extends TypedRef<any> {\n // Cache for items returned by array methods to track mutations\n private itemCache = new Map<number, any>()\n\n protected get container(): LoroList | LoroMovableList {\n return super.container as LoroList | LoroMovableList\n }\n\n protected get shape():\n | ListContainerShape<NestedShape>\n | MovableListContainerShape<NestedShape> {\n return super.shape as\n | ListContainerShape<NestedShape>\n | MovableListContainerShape<NestedShape>\n }\n\n absorbPlainValues() {\n // Critical function: absorb mutated plain values back into Loro containers\n // This is called at the end of change() to persist mutations made to plain objects\n for (const [index, cachedItem] of this.itemCache.entries()) {\n if (cachedItem) {\n if (isValueShape(this.shape.shape)) {\n // For value shapes, delegate to subclass-specific absorption logic\n this.absorbValueAtIndex(index, cachedItem)\n } else {\n // For container shapes, the item should be a typed ref that handles its own absorption\n if (\n cachedItem &&\n typeof cachedItem === \"object\" &&\n \"absorbPlainValues\" in cachedItem\n ) {\n ;(cachedItem as any).absorbPlainValues()\n }\n }\n }\n }\n\n // Clear the cache after absorbing values\n this.itemCache.clear()\n }\n\n // Abstract method to be implemented by subclasses\n // Each subclass knows how to handle its specific container type\n protected abstract absorbValueAtIndex(index: number, value: any): void\n\n protected insertWithConversion(index: number, item: Item): void {\n const convertedItem = convertInputToRef(item as any, this.shape.shape)\n if (isContainer(convertedItem)) {\n this.container.insertContainer(index, convertedItem)\n } else {\n this.container.insert(index, convertedItem)\n }\n }\n\n protected pushWithConversion(item: Item): void {\n const convertedItem = convertInputToRef(item as any, this.shape.shape)\n if (isContainer(convertedItem)) {\n this.container.pushContainer(convertedItem)\n } else {\n this.container.push(convertedItem)\n }\n }\n\n getTypedRefParams(\n index: number,\n shape: ContainerShape,\n ): TypedRefParams<ContainerShape> {\n return {\n shape,\n placeholder: undefined, // List items don't have placeholder\n getContainer: () => {\n const containerItem = this.container.get(index)\n if (!containerItem || !isContainer(containerItem)) {\n throw new Error(`No container found at index ${index}`)\n }\n return containerItem\n },\n readonly: this.readonly,\n autoCommit: this._params.autoCommit,\n getDoc: this._params.getDoc,\n }\n }\n\n // Get item for predicate functions - always returns plain Item for filtering logic\n protected getPredicateItem(index: number): Item {\n // CRITICAL FIX: For predicates to work correctly with mutations,\n // we need to check if there's a cached (mutated) version first\n const cachedItem = this.itemCache.get(index)\n if (cachedItem && isValueShape(this.shape.shape)) {\n // For value shapes, if we have a cached item, use it so predicates see mutations\n return cachedItem as Item\n }\n\n const containerItem = this.container.get(index)\n if (containerItem === undefined) {\n return undefined as Item\n }\n\n if (isValueShape(this.shape.shape)) {\n // For value shapes, return the plain value directly\n return containerItem as Item\n } else {\n // For container shapes, we need to return the plain object representation\n // This allows predicates to access nested properties like article.metadata.author\n if (isContainer(containerItem)) {\n // Convert container to plain object for predicate logic\n // Handle different container types that may not have toJSON method\n if (\n typeof containerItem === \"object\" &&\n containerItem !== null &&\n \"toJSON\" in containerItem\n ) {\n return (containerItem as any).toJSON() as Item\n } else if (\n typeof containerItem === \"object\" &&\n containerItem !== null &&\n \"getShallowValue\" in containerItem\n ) {\n // For containers like LoroCounter that don't have toJSON but have getShallowValue\n return (containerItem as any).getShallowValue() as Item\n } else {\n // Fallback for other container types\n return containerItem as Item\n }\n }\n return containerItem as Item\n }\n }\n\n // Get item for return values - returns MutableItem that can be mutated\n protected getMutableItem(index: number): any {\n // Check if we already have a cached item for this index\n let cachedItem = this.itemCache.get(index)\n if (cachedItem) {\n return cachedItem\n }\n\n // Get the raw container item\n const containerItem = this.container.get(index)\n if (containerItem === undefined) {\n return undefined as MutableItem\n }\n\n if (isValueShape(this.shape.shape)) {\n // For value shapes, we need to ensure mutations persist\n // The key insight: we must return the SAME object for the same index\n // so that mutations to filtered/found items persist back to the cache\n if (typeof containerItem === \"object\" && containerItem !== null) {\n // Create a deep copy for objects so mutations can be tracked\n // IMPORTANT: Only create the copy once, then always return the same cached object\n cachedItem = JSON.parse(JSON.stringify(containerItem))\n } else {\n // For primitives, just use the value directly\n cachedItem = containerItem\n }\n // Only cache primitive values if NOT readonly\n if (!this.readonly) {\n this.itemCache.set(index, cachedItem)\n }\n return cachedItem as MutableItem\n } else {\n // For container shapes, create a proper typed ref using the new pattern\n cachedItem = createContainerTypedRef(\n this.getTypedRefParams(index, this.shape.shape as ContainerShape),\n )\n // Cache container refs\n this.itemCache.set(index, cachedItem)\n\n if (this.readonly) {\n return unwrapReadonlyPrimitive(\n cachedItem,\n this.shape.shape as ContainerShape,\n )\n }\n\n return cachedItem as MutableItem\n }\n }\n\n // Array-like methods for better developer experience\n // DUAL INTERFACE: Predicates get Item (plain data), return values are MutableItem (mutable)\n\n find(\n predicate: (item: Item, index: number) => boolean,\n ): MutableItem | undefined {\n for (let i = 0; i < this.length; i++) {\n const predicateItem = this.getPredicateItem(i)\n if (predicate(predicateItem, i)) {\n return this.getMutableItem(i) // Return mutable item\n }\n }\n return undefined\n }\n\n findIndex(predicate: (item: Item, index: number) => boolean): number {\n for (let i = 0; i < this.length; i++) {\n const predicateItem = this.getPredicateItem(i)\n if (predicate(predicateItem, i)) {\n return i\n }\n }\n return -1\n }\n\n map<ReturnType>(\n callback: (item: Item, index: number) => ReturnType,\n ): ReturnType[] {\n const result: ReturnType[] = []\n for (let i = 0; i < this.length; i++) {\n const predicateItem = this.getPredicateItem(i)\n result.push(callback(predicateItem, i))\n }\n return result\n }\n\n filter(predicate: (item: Item, index: number) => boolean): MutableItem[] {\n const result: MutableItem[] = []\n for (let i = 0; i < this.length; i++) {\n const predicateItem = this.getPredicateItem(i)\n if (predicate(predicateItem, i)) {\n result.push(this.getMutableItem(i)) // Return mutable items\n }\n }\n return result\n }\n\n forEach(callback: (item: Item, index: number) => void): void {\n for (let i = 0; i < this.length; i++) {\n const predicateItem = this.getPredicateItem(i)\n callback(predicateItem, i)\n }\n }\n\n some(predicate: (item: Item, index: number) => boolean): boolean {\n for (let i = 0; i < this.length; i++) {\n const predicateItem = this.getPredicateItem(i)\n if (predicate(predicateItem, i)) {\n return true\n }\n }\n return false\n }\n\n every(predicate: (item: Item, index: number) => boolean): boolean {\n for (let i = 0; i < this.length; i++) {\n const predicateItem = this.getPredicateItem(i)\n if (!predicate(predicateItem, i)) {\n return false\n }\n }\n return true\n }\n\n slice(start?: number, end?: number): MutableItem[] {\n const len = this.length\n\n // Normalize start index (following JavaScript Array.prototype.slice semantics)\n const startIndex =\n start === undefined\n ? 0\n : start < 0\n ? Math.max(len + start, 0)\n : Math.min(start, len)\n\n // Normalize end index\n const endIndex =\n end === undefined\n ? len\n : end < 0\n ? Math.max(len + end, 0)\n : Math.min(end, len)\n\n const result: MutableItem[] = []\n for (let i = startIndex; i < endIndex; i++) {\n result.push(this.getMutableItem(i))\n }\n return result\n }\n\n insert(index: number, item: Item): void {\n this.assertMutable()\n // Update cache indices before performing the insert operation\n this.updateCacheForInsert(index)\n this.insertWithConversion(index, item)\n this.commitIfAuto()\n }\n\n delete(index: number, len: number): void {\n this.assertMutable()\n // Update cache indices before performing the delete operation\n this.updateCacheForDelete(index, len)\n this.container.delete(index, len)\n this.commitIfAuto()\n }\n\n push(item: Item): void {\n this.assertMutable()\n this.pushWithConversion(item)\n this.commitIfAuto()\n }\n\n pushContainer(container: Container): Container {\n this.assertMutable()\n const result = this.container.pushContainer(container)\n this.commitIfAuto()\n return result\n }\n\n insertContainer(index: number, container: Container): Container {\n this.assertMutable()\n const result = this.container.insertContainer(index, container)\n this.commitIfAuto()\n return result\n }\n\n get(index: number): MutableItem {\n return this.getMutableItem(index)\n }\n\n toArray(): Item[] {\n const result: Item[] = []\n for (let i = 0; i < this.length; i++) {\n result.push(this.getPredicateItem(i))\n }\n return result\n }\n\n toJSON(): Item[] {\n const nativeJson = this.container.toJSON() as any[]\n\n // If the nested shape is a container shape (map, record, etc.) or an object value shape,\n // we need to overlay placeholders for each item\n if (\n isContainerShape(this.shape.shape) ||\n (isValueShape(this.shape.shape) &&\n this.shape.shape.valueType === \"struct\")\n ) {\n const itemPlaceholder = deriveShapePlaceholder(this.shape.shape)\n return nativeJson.map(item =>\n mergeValue(this.shape.shape, item, itemPlaceholder as any),\n ) as Item[]\n }\n\n // For primitive value shapes, no overlay needed\n return nativeJson ?? []\n }\n\n [Symbol.iterator](): IterableIterator<MutableItem> {\n let index = 0\n return {\n next: (): IteratorResult<MutableItem> => {\n if (index < this.length) {\n return { value: this.getMutableItem(index++), done: false }\n }\n return { value: undefined, done: true }\n },\n [Symbol.iterator]() {\n return this\n },\n }\n }\n\n get length(): number {\n return this.container.length\n }\n\n // Update cache indices when items are deleted\n private updateCacheForDelete(deleteIndex: number, deleteLen: number): void {\n const newCache = new Map<number, any>()\n\n for (const [cachedIndex, cachedItem] of this.itemCache.entries()) {\n if (cachedIndex < deleteIndex) {\n // Items before the deletion point keep their indices\n newCache.set(cachedIndex, cachedItem)\n } else if (cachedIndex >= deleteIndex + deleteLen) {\n // Items after the deletion range shift down by deleteLen\n newCache.set(cachedIndex - deleteLen, cachedItem)\n }\n // Items within the deletion range are removed from cache\n }\n\n this.itemCache = newCache\n }\n\n // Update cache indices when items are inserted\n private updateCacheForInsert(insertIndex: number): void {\n const newCache = new Map<number, any>()\n\n for (const [cachedIndex, cachedItem] of this.itemCache.entries()) {\n if (cachedIndex < insertIndex) {\n // Items before the insertion point keep their indices\n newCache.set(cachedIndex, cachedItem)\n } else {\n // Items at or after the insertion point shift up by 1\n newCache.set(cachedIndex + 1, cachedItem)\n }\n }\n\n this.itemCache = newCache\n }\n}\n","import type { LoroList } from \"loro-crdt\"\nimport type { ContainerOrValueShape } from \"../shape.js\"\nimport type { Infer } from \"../types.js\"\nimport { ListRefBase } from \"./list-base.js\"\n\n// List typed ref\nexport class ListRef<\n NestedShape extends ContainerOrValueShape,\n> extends ListRefBase<NestedShape> {\n [index: number]: Infer<NestedShape>\n\n protected get container(): LoroList {\n return super.container as LoroList\n }\n\n protected absorbValueAtIndex(index: number, value: any): void {\n // LoroList doesn't have set method, need to delete and insert\n this.container.delete(index, 1)\n this.container.insert(index, value)\n }\n}\n","import type { Container, LoroMovableList } from \"loro-crdt\"\nimport type { ContainerOrValueShape } from \"../shape.js\"\nimport type { Infer } from \"../types.js\"\nimport { ListRefBase } from \"./list-base.js\"\n\n// Movable list typed ref\nexport class MovableListRef<\n NestedShape extends ContainerOrValueShape,\n Item = NestedShape[\"_plain\"],\n> extends ListRefBase<NestedShape> {\n [index: number]: Infer<NestedShape>\n\n protected get container(): LoroMovableList {\n return super.container as LoroMovableList\n }\n\n protected absorbValueAtIndex(index: number, value: any): void {\n // LoroMovableList has set method\n this.container.set(index, value)\n }\n\n move(from: number, to: number): void {\n this.assertMutable()\n this.container.move(from, to)\n this.commitIfAuto()\n }\n\n set(index: number, item: Exclude<Item, Container>) {\n this.assertMutable()\n const result = this.container.set(index, item)\n this.commitIfAuto()\n return result\n }\n}\n","import type { ListRef } from \"./list.js\"\nimport type { MovableListRef } from \"./movable-list.js\"\nimport type { RecordRef } from \"./record.js\"\n\nexport const recordProxyHandler: ProxyHandler<RecordRef<any>> = {\n get: (target, prop) => {\n if (typeof prop === \"string\" && !(prop in target)) {\n // Use getRef for reading - returns undefined for non-existent keys\n return target.getRef(prop)\n }\n return Reflect.get(target, prop)\n },\n set: (target, prop, value) => {\n if (typeof prop === \"string\" && !(prop in target)) {\n target.set(prop, value)\n return true\n }\n return Reflect.set(target, prop, value)\n },\n deleteProperty: (target, prop) => {\n if (typeof prop === \"string\" && !(prop in target)) {\n target.delete(prop)\n return true\n }\n return Reflect.deleteProperty(target, prop)\n },\n // Support `in` operator for checking key existence\n has: (target, prop) => {\n if (typeof prop === \"string\") {\n // Check if it's a method/property on the class first\n if (prop in target) {\n return true\n }\n // Otherwise check the underlying container\n return target.has(prop)\n }\n return Reflect.has(target, prop)\n },\n ownKeys: target => {\n return target.keys()\n },\n getOwnPropertyDescriptor: (target, prop) => {\n if (typeof prop === \"string\" && target.has(prop)) {\n return {\n configurable: true,\n enumerable: true,\n value: target.get(prop),\n }\n }\n return Reflect.getOwnPropertyDescriptor(target, prop)\n },\n}\n\nexport const listProxyHandler: ProxyHandler<ListRef<any>> = {\n get: (target, prop) => {\n if (typeof prop === \"string\") {\n const index = Number(prop)\n if (!Number.isNaN(index)) {\n return target.get(index)\n }\n }\n return Reflect.get(target, prop)\n },\n set: (target, prop, value) => {\n if (typeof prop === \"string\") {\n const index = Number(prop)\n if (!Number.isNaN(index)) {\n // For lists, assignment to index implies replacement\n target.delete(index, 1)\n target.insert(index, value)\n return true\n }\n }\n return Reflect.set(target, prop, value)\n },\n}\n\nexport const movableListProxyHandler: ProxyHandler<MovableListRef<any>> = {\n get: (target, prop) => {\n if (typeof prop === \"string\") {\n const index = Number(prop)\n if (!Number.isNaN(index)) {\n return target.get(index)\n }\n }\n return Reflect.get(target, prop)\n },\n set: (target, prop, value) => {\n if (typeof prop === \"string\") {\n const index = Number(prop)\n if (!Number.isNaN(index)) {\n // MovableList supports set directly\n target.set(index, value)\n return true\n }\n }\n return Reflect.set(target, prop, value)\n },\n}\n","import type { Container, LoroMap, Value } from \"loro-crdt\"\nimport { deriveShapePlaceholder } from \"../derive-placeholder.js\"\nimport { mergeValue } from \"../overlay.js\"\nimport type {\n ContainerOrValueShape,\n ContainerShape,\n RecordContainerShape,\n} from \"../shape.js\"\nimport type { Infer, InferMutableType } from \"../types.js\"\nimport { isContainerShape, isValueShape } from \"../utils/type-guards.js\"\nimport { TypedRef, type TypedRefParams } from \"./base.js\"\nimport {\n absorbCachedPlainValues,\n assignPlainValueToTypedRef,\n containerConstructor,\n createContainerTypedRef,\n serializeRefToJSON,\n unwrapReadonlyPrimitive,\n} from \"./utils.js\"\n\n// Record typed ref\nexport class RecordRef<\n NestedShape extends ContainerOrValueShape,\n> extends TypedRef<any> {\n [key: string]: Infer<NestedShape> | any\n private refCache = new Map<string, TypedRef<ContainerShape> | Value>()\n\n protected get shape(): RecordContainerShape<NestedShape> {\n return super.shape as RecordContainerShape<NestedShape>\n }\n\n protected get container(): LoroMap {\n return super.container as LoroMap\n }\n\n absorbPlainValues() {\n absorbCachedPlainValues(this.refCache, () => this.container)\n }\n\n getTypedRefParams<S extends ContainerShape>(\n key: string,\n shape: S,\n ): TypedRefParams<ContainerShape> {\n // First try to get placeholder from the Record's placeholder (if it has an entry for this key)\n let placeholder = (this.placeholder as any)?.[key]\n\n // If no placeholder exists for this key, derive one from the schema's shape\n // This is critical for Records where the placeholder is always {} but nested\n // containers need valid placeholders to fall back to for missing values\n if (placeholder === undefined) {\n placeholder = deriveShapePlaceholder(shape)\n }\n\n const LoroContainer = containerConstructor[shape._type]\n\n return {\n shape,\n placeholder,\n getContainer: () =>\n this.container.getOrCreateContainer(key, new (LoroContainer as any)()),\n readonly: this.readonly,\n autoCommit: this._params.autoCommit,\n getDoc: this._params.getDoc,\n }\n }\n\n /**\n * Gets an existing ref for a key, or returns undefined if the key doesn't exist.\n * Used for reading operations where we want optional chaining to work.\n */\n getRef(key: string): any {\n // For container shapes, check if the key exists first\n // This allows optional chaining (?.) to work correctly for non-existent keys\n if (isContainerShape(this.shape.shape)) {\n const existing = this.container.get(key)\n if (existing === undefined) {\n return undefined\n }\n }\n\n return this.getOrCreateRef(key)\n }\n\n /**\n * Gets or creates a ref for a key.\n * Always creates the container if it doesn't exist.\n * This is the method used for write operations.\n */\n getOrCreateRef(key: string): any {\n let ref = this.refCache.get(key)\n if (!ref) {\n const shape = this.shape.shape\n if (isContainerShape(shape)) {\n ref = createContainerTypedRef(\n this.getTypedRefParams(key, shape as ContainerShape),\n )\n // Cache container refs\n this.refCache.set(key, ref)\n } else {\n // For value shapes, first try to get the value from the container\n const containerValue = this.container.get(key)\n if (containerValue !== undefined) {\n ref = containerValue as Value\n } else {\n // Only fall back to placeholder if the container doesn't have the value\n const placeholder = (this.placeholder as any)?.[key]\n if (placeholder === undefined) {\n // If it's a value type and not in container or placeholder,\n // fallback to the default value from the shape\n ref = (shape as any)._plain\n } else {\n ref = placeholder as Value\n }\n }\n // Only cache primitive values if NOT readonly\n if (ref !== undefined && !this.readonly) {\n this.refCache.set(key, ref)\n }\n }\n }\n\n if (this.readonly && isContainerShape(this.shape.shape)) {\n return unwrapReadonlyPrimitive(\n ref as TypedRef<any>,\n this.shape.shape as ContainerShape,\n )\n }\n\n return ref as any\n }\n\n get(key: string): InferMutableType<NestedShape> {\n return this.getRef(key)\n }\n\n set(key: string, value: any): void {\n this.assertMutable()\n if (isValueShape(this.shape.shape)) {\n this.container.set(key, value)\n this.refCache.set(key, value)\n this.commitIfAuto()\n } else {\n // For container shapes, try to assign the plain value\n // Use getOrCreateRef to ensure the container is created\n const ref = this.getOrCreateRef(key)\n if (assignPlainValueToTypedRef(ref, value)) {\n this.commitIfAuto()\n return\n }\n throw new Error(\n \"Cannot set container directly, modify the typed ref instead\",\n )\n }\n }\n\n setContainer<C extends Container>(key: string, container: C): C {\n this.assertMutable()\n const result = this.container.setContainer(key, container)\n this.commitIfAuto()\n return result\n }\n\n delete(key: string): void {\n this.assertMutable()\n this.container.delete(key)\n this.refCache.delete(key)\n this.commitIfAuto()\n }\n\n has(key: string): boolean {\n return this.container.get(key) !== undefined\n }\n\n keys(): string[] {\n return this.container.keys()\n }\n\n values(): any[] {\n return this.container.values()\n }\n\n get size(): number {\n return this.container.size\n }\n\n toJSON(): Record<string, Infer<NestedShape>> {\n // Fast path: readonly mode\n if (this.readonly) {\n const nativeJson = this.container.toJSON() as Record<string, any>\n // For records, we need to overlay placeholders for each entry's nested shape\n const result: Record<string, Infer<NestedShape>> = {}\n for (const key of Object.keys(nativeJson)) {\n // For records, the placeholder is always {}, so we need to derive\n // the placeholder for the nested shape on the fly\n const nestedPlaceholderValue = deriveShapePlaceholder(this.shape.shape)\n\n result[key] = mergeValue(\n this.shape.shape,\n nativeJson[key],\n nestedPlaceholderValue as Value,\n ) as Infer<NestedShape>\n }\n return result\n }\n\n return serializeRefToJSON(this, this.keys()) as Record<\n string,\n Infer<NestedShape>\n >\n }\n}\n","import type { Container, LoroMap, Value } from \"loro-crdt\"\nimport { mergeValue } from \"../overlay.js\"\nimport type {\n ContainerOrValueShape,\n ContainerShape,\n StructContainerShape,\n ValueShape,\n} from \"../shape.js\"\nimport type { Infer } from \"../types.js\"\nimport { isContainerShape, isValueShape } from \"../utils/type-guards.js\"\nimport { TypedRef, type TypedRefParams } from \"./base.js\"\nimport {\n absorbCachedPlainValues,\n assignPlainValueToTypedRef,\n containerConstructor,\n createContainerTypedRef,\n serializeRefToJSON,\n unwrapReadonlyPrimitive,\n} from \"./utils.js\"\n\n/**\n * Typed ref for struct containers (objects with fixed keys).\n * Uses LoroMap as the underlying container.\n */\nexport class StructRef<\n NestedShapes extends Record<string, ContainerOrValueShape>,\n> extends TypedRef<any> {\n private propertyCache = new Map<string, TypedRef<ContainerShape> | Value>()\n\n constructor(params: TypedRefParams<StructContainerShape<NestedShapes>>) {\n super(params)\n this.createLazyProperties()\n }\n\n protected get shape(): StructContainerShape<NestedShapes> {\n return super.shape as StructContainerShape<NestedShapes>\n }\n\n protected get container(): LoroMap {\n return super.container as LoroMap\n }\n\n absorbPlainValues() {\n absorbCachedPlainValues(this.propertyCache, () => this.container)\n }\n\n getTypedRefParams<S extends ContainerShape>(\n key: string,\n shape: S,\n ): TypedRefParams<ContainerShape> {\n const placeholder = (this.placeholder as any)?.[key]\n\n const LoroContainer = containerConstructor[shape._type]\n\n return {\n shape,\n placeholder,\n getContainer: () =>\n this.container.getOrCreateContainer(key, new (LoroContainer as any)()),\n readonly: this.readonly,\n autoCommit: this._params.autoCommit,\n getDoc: this._params.getDoc,\n }\n }\n\n getOrCreateRef<Shape extends ContainerShape | ValueShape>(\n key: string,\n shape: Shape,\n ): any {\n let ref = this.propertyCache.get(key)\n if (!ref) {\n if (isContainerShape(shape)) {\n ref = createContainerTypedRef(this.getTypedRefParams(key, shape))\n // We cache container refs even in readonly mode because they are just handles\n this.propertyCache.set(key, ref)\n } else {\n // For value shapes, first try to get the value from the container\n const containerValue = this.container.get(key)\n if (containerValue !== undefined) {\n ref = containerValue as Value\n } else {\n // Only fall back to placeholder if the container doesn't have the value\n const placeholder = (this.placeholder as any)?.[key]\n if (placeholder === undefined) {\n throw new Error(\"placeholder required\")\n }\n ref = placeholder as Value\n }\n\n // In readonly mode, we DO NOT cache primitive values.\n // This ensures we always get the latest value from the CRDT on next access.\n if (!this.readonly) {\n this.propertyCache.set(key, ref)\n }\n }\n if (ref === undefined) throw new Error(\"no container made\")\n }\n\n if (this.readonly && isContainerShape(shape)) {\n // In readonly mode, if the container doesn't exist, return the placeholder\n // This ensures we respect default values (e.g. counter: 1)\n const existing = this.container.get(key)\n if (existing === undefined) {\n return (this.placeholder as any)?.[key]\n }\n\n return unwrapReadonlyPrimitive(ref as TypedRef<any>, shape)\n }\n\n return ref as Shape extends ContainerShape ? TypedRef<Shape> : Value\n }\n\n private createLazyProperties(): void {\n for (const key in this.shape.shapes) {\n const shape = this.shape.shapes[key]\n Object.defineProperty(this, key, {\n get: () => this.getOrCreateRef(key, shape),\n set: value => {\n this.assertMutable()\n if (isValueShape(shape)) {\n this.container.set(key, value)\n this.propertyCache.set(key, value)\n } else {\n // For container shapes, try to assign the plain value\n const ref = this.getOrCreateRef(key, shape)\n if (assignPlainValueToTypedRef(ref as TypedRef<any>, value)) {\n return\n }\n throw new Error(\n \"Cannot set container directly, modify the typed ref instead\",\n )\n }\n },\n enumerable: true,\n })\n }\n }\n\n toJSON(): Infer<StructContainerShape<NestedShapes>> {\n // Fast path: readonly mode\n if (this.readonly) {\n const nativeJson = this.container.toJSON() as Value\n // Overlay placeholders for missing properties\n return mergeValue(\n this.shape,\n nativeJson,\n this.placeholder as Value,\n ) as Infer<StructContainerShape<NestedShapes>>\n }\n\n return serializeRefToJSON(\n this as any,\n Object.keys(this.shape.shapes),\n ) as Infer<StructContainerShape<NestedShapes>>\n }\n\n // TODO(duane): return correct type here\n get(key: string): any {\n return this.container.get(key)\n }\n\n set(key: string, value: Value): void {\n this.assertMutable()\n this.container.set(key, value)\n this.commitIfAuto()\n }\n\n setContainer<C extends Container>(key: string, container: C): C {\n this.assertMutable()\n const result = this.container.setContainer(key, container)\n this.commitIfAuto()\n return result\n }\n\n delete(key: string): void {\n this.assertMutable()\n this.container.delete(key)\n this.commitIfAuto()\n }\n\n has(key: string): boolean {\n // LoroMap doesn't have a has method, so we check if get returns undefined\n return this.container.get(key) !== undefined\n }\n\n keys(): string[] {\n return this.container.keys()\n }\n\n values(): any[] {\n return this.container.values()\n }\n\n get size(): number {\n return this.container.size\n }\n}\n","import type { LoroText } from \"loro-crdt\"\nimport type { TextContainerShape } from \"../shape.js\"\nimport { TypedRef } from \"./base.js\"\n\n// Text typed ref\nexport class TextRef extends TypedRef<TextContainerShape> {\n // Track if we've materialized the container (made any changes)\n private _materialized = false\n\n protected get container(): LoroText {\n return super.container as LoroText\n }\n\n absorbPlainValues() {\n // no plain values contained within\n }\n\n // Text methods\n insert(index: number, content: string): void {\n this.assertMutable()\n this._materialized = true\n this.container.insert(index, content)\n this.commitIfAuto()\n }\n\n delete(index: number, len: number): void {\n this.assertMutable()\n this._materialized = true\n this.container.delete(index, len)\n this.commitIfAuto()\n }\n\n /**\n * Returns the text content.\n * If the text hasn't been materialized (no operations performed),\n * returns the placeholder value if available.\n */\n toString(): string {\n const containerValue = this.container.toString()\n if (containerValue !== \"\" || this._materialized) {\n return containerValue\n }\n // Return placeholder if available and container is at default state\n if (this.placeholder !== undefined) {\n return this.placeholder as string\n }\n return containerValue\n }\n\n valueOf(): string {\n return this.toString()\n }\n\n toJSON(): string {\n return this.toString()\n }\n\n [Symbol.toPrimitive](_hint: string): string {\n return this.toString()\n }\n\n update(text: string): void {\n this.assertMutable()\n this._materialized = true\n this.container.update(text)\n this.commitIfAuto()\n }\n\n mark(range: { start: number; end: number }, key: string, value: any): void {\n this.assertMutable()\n this._materialized = true\n this.container.mark(range, key, value)\n this.commitIfAuto()\n }\n\n unmark(range: { start: number; end: number }, key: string): void {\n this.assertMutable()\n this._materialized = true\n this.container.unmark(range, key)\n this.commitIfAuto()\n }\n\n toDelta(): any[] {\n return this.container.toDelta()\n }\n\n applyDelta(delta: any[]): void {\n this.assertMutable()\n this._materialized = true\n this.container.applyDelta(delta)\n this.commitIfAuto()\n }\n\n get length(): number {\n return this.container.length\n }\n}\n","import type { TreeContainerShape } from \"../shape.js\"\nimport { TypedRef } from \"./base.js\"\n\n// Tree typed ref\nexport class TreeRef<T extends TreeContainerShape> extends TypedRef<T> {\n absorbPlainValues() {\n // TODO(duane): implement for trees\n }\n\n createNode(parent?: any, index?: number): any {\n this.assertMutable()\n return this.container.createNode(parent, index)\n }\n\n move(target: any, parent?: any, index?: number): void {\n this.assertMutable()\n this.container.move(target, parent, index)\n }\n\n delete(target: any): void {\n this.assertMutable()\n this.container.delete(target)\n }\n\n has(target: any): boolean {\n return this.container.has(target)\n }\n\n getNodeByID(id: any): any {\n return this.container.getNodeByID\n ? this.container.getNodeByID(id)\n : undefined\n }\n}\n","import type { LoroDoc } from \"loro-crdt\"\nimport type { Infer } from \"../index.js\"\nimport type { ContainerShape, DocShape } from \"../shape.js\"\nimport { TypedRef, type TypedRefParams } from \"./base.js\"\nimport {\n createContainerTypedRef,\n serializeRefToJSON,\n unwrapReadonlyPrimitive,\n} from \"./utils.js\"\n\nconst containerGetter = {\n counter: \"getCounter\",\n list: \"getList\",\n movableList: \"getMovableList\",\n record: \"getMap\",\n struct: \"getMap\", // Structs use LoroMap as their underlying container\n text: \"getText\",\n tree: \"getTree\",\n} as const\n\n// Doc Ref class -- the actual object passed to the change `mutation` function\nexport class DocRef<Shape extends DocShape> extends TypedRef<Shape> {\n private _doc: LoroDoc\n private propertyCache = new Map<string, TypedRef<ContainerShape>>()\n private requiredPlaceholder!: Infer<Shape>\n\n constructor(\n _params: Omit<TypedRefParams<Shape>, \"getContainer\" | \"getDoc\"> & {\n doc: LoroDoc\n autoCommit?: boolean\n },\n ) {\n super({\n ..._params,\n getContainer: () => {\n throw new Error(\"can't get container on DocRef\")\n },\n getDoc: () => this._doc,\n })\n if (!_params.placeholder) throw new Error(\"placeholder required\")\n this._doc = _params.doc\n this.requiredPlaceholder = _params.placeholder\n this.createLazyProperties()\n }\n\n getTypedRefParams<S extends ContainerShape>(\n key: string,\n shape: S,\n ): TypedRefParams<ContainerShape> {\n const getter = this._doc[containerGetter[shape._type]].bind(this._doc)\n\n return {\n shape,\n placeholder: this.requiredPlaceholder[key],\n getContainer: () => getter(key),\n readonly: this.readonly,\n autoCommit: this._params.autoCommit,\n getDoc: () => this._doc,\n }\n }\n\n getOrCreateTypedRef(\n key: string,\n shape: ContainerShape,\n ): TypedRef<ContainerShape> | number | string {\n if (\n this.readonly &&\n (shape._type === \"counter\" || shape._type === \"text\")\n ) {\n // Check if the container exists in the doc without creating it\n const shallow = this._doc.getShallowValue()\n if (!shallow[key]) {\n return this.requiredPlaceholder[key] as any\n }\n }\n\n let ref = this.propertyCache.get(key)\n\n if (!ref) {\n ref = createContainerTypedRef(this.getTypedRefParams(key, shape))\n this.propertyCache.set(key, ref)\n }\n\n if (this.readonly) {\n return unwrapReadonlyPrimitive(ref, shape)\n }\n\n return ref\n }\n\n private createLazyProperties(): void {\n for (const key in this.shape.shapes) {\n const shape = this.shape.shapes[key]\n Object.defineProperty(this, key, {\n get: () => this.getOrCreateTypedRef(key, shape),\n enumerable: true,\n })\n }\n }\n\n toJSON(): Infer<Shape> {\n return serializeRefToJSON(\n this as any,\n Object.keys(this.shape.shapes),\n ) as Infer<Shape>\n }\n\n absorbPlainValues(): void {\n // By iterating over the propertyCache, we achieve a small optimization\n // by only absorbing values that have been 'touched' in some way\n for (const [, ref] of this.propertyCache.entries()) {\n ref.absorbPlainValues()\n }\n }\n}\n","import type {\n ArrayValueShape,\n ContainerOrValueShape,\n DiscriminatedUnionValueShape,\n DocShape,\n ListContainerShape,\n MovableListContainerShape,\n RecordContainerShape,\n RecordValueShape,\n StringValueShape,\n StructContainerShape,\n StructValueShape,\n UnionValueShape,\n ValueShape,\n} from \"./shape.js\"\nimport type { Infer } from \"./types.js\"\n\n/**\n * Validates a value against a ContainerShape or ValueShape schema\n */\nexport function validateValue(\n value: unknown,\n schema: ContainerOrValueShape,\n path: string = \"\",\n): unknown {\n if (!schema || typeof schema !== \"object\" || !(\"_type\" in schema)) {\n throw new Error(`Invalid schema at path ${path}: missing _type`)\n }\n\n const currentPath = path || \"root\"\n\n // Handle ContainerShape types\n if (schema._type === \"text\") {\n if (typeof value !== \"string\") {\n throw new Error(\n `Expected string at path ${currentPath}, got ${typeof value}`,\n )\n }\n return value\n }\n\n if (schema._type === \"counter\") {\n if (typeof value !== \"number\") {\n throw new Error(\n `Expected number at path ${currentPath}, got ${typeof value}`,\n )\n }\n return value\n }\n\n if (schema._type === \"list\" || schema._type === \"movableList\") {\n if (!Array.isArray(value)) {\n throw new Error(\n `Expected array at path ${currentPath}, got ${typeof value}`,\n )\n }\n const listSchema = schema as ListContainerShape | MovableListContainerShape\n return value.map((item, index) =>\n validateValue(item, listSchema.shape, `${currentPath}[${index}]`),\n )\n }\n\n if (schema._type === \"struct\") {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(\n `Expected object at path ${currentPath}, got ${typeof value}`,\n )\n }\n const structSchema = schema as StructContainerShape\n const result: Record<string, unknown> = {}\n\n // Validate each property in the struct shape\n for (const [key, nestedSchema] of Object.entries(structSchema.shapes)) {\n const nestedPath = `${currentPath}.${key}`\n const nestedValue = (value as Record<string, unknown>)[key]\n result[key] = validateValue(nestedValue, nestedSchema, nestedPath)\n }\n return result\n }\n\n if (schema._type === \"record\") {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(\n `Expected object at path ${currentPath}, got ${typeof value}`,\n )\n }\n const recordSchema = schema as RecordContainerShape\n const result: Record<string, unknown> = {}\n\n // Validate each property in the record\n for (const [key, nestedValue] of Object.entries(value)) {\n const nestedPath = `${currentPath}.${key}`\n result[key] = validateValue(nestedValue, recordSchema.shape, nestedPath)\n }\n return result\n }\n\n if (schema._type === \"tree\") {\n if (!Array.isArray(value)) {\n throw new Error(\n `Expected array for tree at path ${currentPath}, got ${typeof value}`,\n )\n }\n // Trees can contain any structure, so we just validate it's an array\n return value\n }\n\n // Handle ValueShape types\n if (schema._type === \"value\") {\n const valueSchema = schema as ValueShape\n\n switch (valueSchema.valueType) {\n case \"string\": {\n if (typeof value !== \"string\") {\n throw new Error(\n `Expected string at path ${currentPath}, got ${typeof value}`,\n )\n }\n const stringSchema = valueSchema as StringValueShape\n if (stringSchema.options && !stringSchema.options.includes(value)) {\n throw new Error(\n `Expected one of [${stringSchema.options.join(\", \")}] at path ${currentPath}, got \"${value}\"`,\n )\n }\n return value\n }\n\n case \"number\":\n if (typeof value !== \"number\") {\n throw new Error(\n `Expected number at path ${currentPath}, got ${typeof value}`,\n )\n }\n return value\n\n case \"boolean\":\n if (typeof value !== \"boolean\") {\n throw new Error(\n `Expected boolean at path ${currentPath}, got ${typeof value}`,\n )\n }\n return value\n\n case \"null\":\n if (value !== null) {\n throw new Error(\n `Expected null at path ${currentPath}, got ${typeof value}`,\n )\n }\n return value\n\n case \"undefined\":\n if (value !== undefined) {\n throw new Error(\n `Expected undefined at path ${currentPath}, got ${typeof value}`,\n )\n }\n return value\n\n case \"uint8array\":\n if (!(value instanceof Uint8Array)) {\n throw new Error(\n `Expected Uint8Array at path ${currentPath}, got ${typeof value}`,\n )\n }\n return value\n\n case \"struct\": {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(\n `Expected object at path ${currentPath}, got ${typeof value}`,\n )\n }\n const structSchema = valueSchema as StructValueShape\n const result: Record<string, unknown> = {}\n\n // Validate each property in the struct shape\n for (const [key, nestedSchema] of Object.entries(structSchema.shape)) {\n const nestedPath = `${currentPath}.${key}`\n const nestedValue = (value as Record<string, unknown>)[key]\n result[key] = validateValue(nestedValue, nestedSchema, nestedPath)\n }\n return result\n }\n\n case \"record\": {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(\n `Expected object at path ${currentPath}, got ${typeof value}`,\n )\n }\n const recordSchema = valueSchema as RecordValueShape\n const result: Record<string, unknown> = {}\n\n // Validate each property in the record\n for (const [key, nestedValue] of Object.entries(value)) {\n const nestedPath = `${currentPath}.${key}`\n result[key] = validateValue(\n nestedValue,\n recordSchema.shape,\n nestedPath,\n )\n }\n return result\n }\n\n case \"array\": {\n if (!Array.isArray(value)) {\n throw new Error(\n `Expected array at path ${currentPath}, got ${typeof value}`,\n )\n }\n const arraySchema = valueSchema as ArrayValueShape\n return value.map((item, index) =>\n validateValue(item, arraySchema.shape, `${currentPath}[${index}]`),\n )\n }\n\n case \"union\": {\n const unionSchema = valueSchema as UnionValueShape\n let lastError: Error | null = null\n\n // Try to validate against each shape in the union\n for (const shape of unionSchema.shapes) {\n try {\n return validateValue(value, shape, currentPath)\n } catch (error) {\n lastError = error as Error\n }\n }\n\n throw new Error(\n `Value at path ${currentPath} does not match any union type: ${lastError?.message}`,\n )\n }\n\n case \"discriminatedUnion\": {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(\n `Expected object at path ${currentPath}, got ${typeof value}`,\n )\n }\n\n const unionSchema = valueSchema as DiscriminatedUnionValueShape\n const discriminantKey = unionSchema.discriminantKey\n const discriminantValue = (value as Record<string, unknown>)[\n discriminantKey\n ]\n\n if (typeof discriminantValue !== \"string\") {\n throw new Error(\n `Expected string for discriminant key \"${discriminantKey}\" at path ${currentPath}, got ${typeof discriminantValue}`,\n )\n }\n\n const variantSchema = unionSchema.variants[discriminantValue]\n\n if (!variantSchema) {\n throw new Error(\n `Invalid discriminant value \"${discriminantValue}\" at path ${currentPath}. Expected one of: ${Object.keys(\n unionSchema.variants,\n ).join(\", \")}`,\n )\n }\n\n return validateValue(value, variantSchema, currentPath)\n }\n\n default:\n throw new Error(`Unknown value type: ${(valueSchema as any).valueType}`)\n }\n }\n\n throw new Error(`Unknown schema type: ${(schema as any)._type}`)\n}\n\n/**\n * Validates placeholder against schema structure without using Zod\n * Combines the functionality of createPlaceholderValidator and createValueValidator\n */\nexport function validatePlaceholder<T extends DocShape>(\n placeholder: unknown,\n schema: T,\n): Infer<T> {\n if (\n !placeholder ||\n typeof placeholder !== \"object\" ||\n Array.isArray(placeholder)\n ) {\n throw new Error(\"Placeholder must be an object\")\n }\n\n const result: Record<string, unknown> = {}\n\n // Validate each property in the document schema\n for (const [key, schemaValue] of Object.entries(schema.shapes)) {\n const value = (placeholder as Record<string, unknown>)[key]\n result[key] = validateValue(value, schemaValue, key)\n }\n\n return result as Infer<T>\n}\n","import { deriveShapePlaceholder } from \"./derive-placeholder.js\"\nimport { mergeValue } from \"./overlay.js\"\nimport type { ObjectValue, PresenceInterface } from \"./presence-interface.js\"\nimport type { ContainerShape, ValueShape } from \"./shape.js\"\nimport type { Infer } from \"./types.js\"\n\n/**\n * A strongly-typed wrapper around a PresenceInterface.\n * Provides type-safe access to presence data with automatic placeholder merging.\n *\n * @typeParam S - The shape of the presence data\n */\nexport class TypedPresence<S extends ContainerShape | ValueShape> {\n private placeholder: Infer<S>\n\n constructor(\n public shape: S,\n private presence: PresenceInterface,\n ) {\n this.placeholder = deriveShapePlaceholder(shape) as Infer<S>\n }\n\n /**\n * Get the current peer's presence state with placeholder values merged in.\n */\n get self(): Infer<S> {\n return mergeValue(\n this.shape,\n this.presence.self,\n this.placeholder,\n ) as Infer<S>\n }\n\n /**\n * Get other peers' presence states with placeholder values merged in.\n * Does NOT include self. Use this for iterating over remote peers.\n */\n get peers(): Map<string, Infer<S>> {\n const result = new Map<string, Infer<S>>()\n for (const [peerId, value] of this.presence.peers) {\n result.set(\n peerId,\n mergeValue(this.shape, value, this.placeholder) as Infer<S>,\n )\n }\n return result\n }\n\n /**\n * Get all peers' presence states with placeholder values merged in.\n * @deprecated Use `peers` and `self` separately. This property is synthesized\n * from `peers` and `self` for backward compatibility.\n */\n get all(): Record<string, Infer<S>> {\n const result: Record<string, Infer<S>> = {}\n const all = this.presence.all\n for (const peerId of Object.keys(all)) {\n result[peerId] = mergeValue(\n this.shape,\n all[peerId],\n this.placeholder,\n ) as Infer<S>\n }\n return result\n }\n\n /**\n * Set presence values for the current peer.\n */\n set(value: Partial<Infer<S>>) {\n this.presence.set(value as ObjectValue)\n }\n\n /**\n * Subscribe to presence changes.\n * The callback is called immediately with the current state, then on each change.\n *\n * @param cb Callback that receives the typed presence state\n * @returns Unsubscribe function\n */\n subscribe(\n cb: (state: {\n self: Infer<S>\n peers: Map<string, Infer<S>>\n /** @deprecated Use `peers` and `self` separately */\n all: Record<string, Infer<S>>\n }) => void,\n ): () => void {\n // Initial call\n cb({ self: this.self, peers: this.peers, all: this.all })\n\n return this.presence.subscribe(() => {\n cb({ self: this.self, peers: this.peers, all: this.all })\n })\n }\n}\n"],"mappings":";AASO,SAAS,kBACd,QACyB;AACzB,QAAM,SAAkC,CAAC;AAEzC,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,OAAO,MAAM,GAAG;AACxD,WAAO,GAAG,IAAI,uBAAuB,KAAK;AAAA,EAC5C;AAEA,SAAO;AACT;AAQO,SAAS,uBAAuB,OAAuC;AAC5E,UAAQ,MAAM,OAAO;AAAA;AAAA,IAEnB,KAAK;AACH,aAAO,MAAM;AAAA,IACf,KAAK;AACH,aAAO,MAAM;AAAA;AAAA,IAGf,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACH,aAAO,CAAC;AAAA,IACV,KAAK;AACH,aAAO,CAAC;AAAA;AAAA,IAGV,KAAK,UAAU;AACb,YAAM,SAAkC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AA;AAAA;AAAA;AAAA,EAYR,IAAI,OAAiB;AACnB,WAAO;AAAA,MACL,KAAK;AAAA,MACL,KAAK,SAAS;AAAA,MACd,KAAK;AAAA,IACP;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,IAAI,QAA+B;AACjC,UAAM,SAAS,oBAAI,IAAsB;AACzC,eAAW,CAAC,QAAQ,KAAK,KAAK,KAAK,SAAS,OAAO;AACjD,aAAO;AAAA,QACL;AAAA,QACA,WAAW,KAAK,OAAO,OAAO,KAAK,WAAW;AAAA,MAChD;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,IAAI,MAAgC;AAClC,UAAM,SAAmC,CAAC;AAC1C,UAAM,MAAM,KAAK,SAAS;AAC1B,eAAW,UAAU,OAAO,KAAK,GAAG,GAAG;AACrC,aAAO,MAAM,IAAI;AAAA,QACf,KAAK;AAAA,QACL,IAAI,MAAM;AAAA,QACV,KAAK;AAAA,MACP;AAAA,IACF;AACA,WAAO;AAAA,EACT;AAAA;AAAA;AAAA;AAAA,EAKA,IAAI,OAA0B;AAC5B,SAAK,SAAS,IAAI,KAAoB;AAAA,EACxC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,UACE,IAMY;AAEZ,OAAG,EAAE,MAAM,KAAK,MAAM,OAAO,KAAK,OAAO,KAAK,KAAK,IAAI,CAAC;AAExD,WAAO,KAAK,SAAS,UAAU,MAAM;AACnC,SAAG,EAAE,MAAM,KAAK,MAAM,OAAO,KAAK,OAAO,KAAK,KAAK,IAAI,CAAC;AAAA,IAC1D,CAAC;AAAA,EACH;AACF;","names":["target","value","LoroCounter","LoroList","LoroMap","LoroMovableList","LoroText","LoroCounter","LoroList","LoroMovableList","LoroMap","LoroText"]}