doxum 0.1.25 → 0.1.26

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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["node","length","insert","remove","record","isRecord","isPlainObject","sequence.keys","sequence.equal","isRecord","sequence.indexedKeys","anchor.valid","index","anchor.index","remove","replace","insert","keys","sequence.keys","anchor.valid","anchor.index","replace","sequence.indexedKeys","remove","node","replace","move","anchor.moveSelection","sequence.equal","sequence.listSequence","sequence.matches","tree","AddressIndex","target.tree","schemaValue.copyValue","address.resolveChild","address.resolveLocated","address.nodeAt","sequence.indexedKeys","children","AddressIndex","target.belongs","target.affected","target.indexedAddress","relation.contains","sequence.toArray","sequence.indexedKeys","schemaValue.equalValue","schemaValue.copyValue","sequence.equal","address.resolveLocated","address.resolveValue","schemaValue.copyTreeNode","address.memberKey","sequence.indexedKeys","state.orderOf","schemaValue.equalTreeNode","AddressIndex","relation.contains","address.createAddressResolver","schemaValue.checkValue","address.resolveContainer","address.resolveTreeContainer","address.resolveValue","schemaValue.copyValue","address.memberKey","schemaValue.checkKey","state.orderOf","sequence.matches","schemaValue.checkTreePayload","schemaValue.copyTreeNode","contextOf","target.SubscriptionIndex","schemaValue.checkValue","schemaValue.ParseError","schemaValue.copyValue","target.dependencyBucket","target.same","contextOf","target.same","contextOf","defineSource","defineSource","contextOf","snapshotCollectionView","projectionRef","isProjection","isPlainObject","defineProcessor","ProjectionDisposedError","schemaValue.equalValue","schemaValue.copyValue","isRecord","sequence.equal","sequence.listSequence","sequence.indexedKeys","schemaValue.equalTreeNode","schemaValue.copyTreeNode","relation.contains","ProjectionError","ProjectionDisposedError","contextOf","impactTarget.SubscriptionIndex","address.resolveValue","isRecord","schemaValue.equalTreeNode","schemaValue.copyTreeNode","schemaValue.copyValue","sequence.toArray","sequence.indexedKeys","contextOf","mapRead","createScheduler","ProjectionDisposedError","producerOf","projectionRef","collectionView","snapshotCollectionView","mapRead","isProjection","isPlainObject"],"sources":["../core/src/schema/model.ts","../core/src/order/sequence.ts","../core/src/schema/layout.ts","../core/src/schema/value.ts","../core/src/address/resolve.ts","../core/src/order/anchor.ts","../core/src/mutation/operations/table.ts","../core/src/mutation/operations/list.ts","../core/src/mutation/operations/tree.ts","../core/src/mutation/operations/order.ts","../core/src/impact/target.ts","../core/src/access/scope.ts","../core/src/schema/path.ts","../core/src/address/relation.ts","../core/src/impact.ts","../core/src/runtime/contract.ts","../core/src/history.ts","../core/src/mutation/state.ts","../core/src/mutation/recorder.ts","../core/src/mutation/session.ts","../core/src/mutation/operations/replay.ts","../core/src/runtime/readable.ts","../core/src/runtime/notification.ts","../core/src/runtime.ts","../core/src/access/dependency.ts","../core/src/runtime/access.ts","../core/src/runtime/select.ts","../core/src/projection/input.ts","../core/src/projection/observe.ts","../core/src/projection/derive.ts","../core/src/projection/collection/change.ts","../core/src/projection/collection/index.ts","../core/src/projection/output/collection.ts","../core/src/projection/output/value.ts","../core/src/projection/graph/processor.ts","../core/src/projection/readable/selection.ts","../core/src/projection/source/materialization.ts","../core/src/projection/source/dirty.ts","../core/src/projection/source/boundary.ts","../core/src/projection/source/document.ts","../core/src/projection/source/external.ts","../core/src/projection/source/input.ts","../core/src/projection/source/registry.ts","../core/src/projection/runtime.ts"],"sourcesContent":["export type DocumentAddress = readonly string[];\n\n/** Pure synchronous validation. Successful output is ignored; input is never transformed. */\nexport type Validator<T> =\n | ((value: unknown) => value is T)\n | ((value: unknown) => asserts value is T)\n | {\n readonly '~standard': {\n readonly version: 1;\n readonly vendor: string;\n readonly types?: { readonly input: unknown; readonly output: T };\n validate(value: unknown):\n | { readonly value: T; readonly issues?: undefined }\n | {\n readonly issues: readonly {\n readonly message: string;\n readonly path?: readonly (PropertyKey | { readonly key: PropertyKey })[];\n }[];\n }\n | PromiseLike<unknown>;\n };\n };\n\n/** Shared payloads are immutable through every alias, including builtin methods. */\nexport type ReadonlyValue<T> = T extends (...args: never[]) => unknown\n ? T\n : T extends ReadonlyMap<infer K, infer V>\n ? ReadonlyMap<ReadonlyValue<K>, ReadonlyValue<V>>\n : T extends ReadonlySet<infer V>\n ? ReadonlySet<ReadonlyValue<V>>\n : T extends Date\n ? Omit<Date, `set${string}`>\n : T extends object\n ? { readonly [K in keyof T]: ReadonlyValue<T[K]> }\n : T;\n\nexport type DocumentListConfig<TItem> = {\n readonly keyOf: (item: ReadonlyValue<TItem>) => string;\n};\nexport type DocumentTreeNode<TValue, ValueOptional extends boolean = false> = {\n readonly parentId?: string;\n readonly children: readonly string[];\n} & (ValueOptional extends true\n ? { readonly value?: ReadonlyValue<TValue> }\n : { readonly value: ReadonlyValue<TValue> });\nexport type DocumentTreeValue<TValue, ValueOptional extends boolean = false> = {\n readonly rootId?: string;\n readonly nodes: Readonly<Record<string, DocumentTreeNode<TValue, ValueOptional>>>;\n};\n\ntype BaseNode<K extends string> = {\n readonly kind: K;\n readonly optional?: boolean;\n};\nexport type FieldNode<T, Optional extends boolean = false> = BaseNode<'field'> & {\n readonly __value?: T;\n readonly validator?: Validator<T>;\n} & (Optional extends true ? { readonly optional: true } : { readonly optional?: false });\n/** A node with optional presence. The marker replaces, rather than intersects, a field marker. */\nexport type OptionalNode<TNode extends DocumentNode> =\n TNode extends FieldNode<infer TValue, boolean>\n ? FieldNode<TValue, true>\n : TNode & { readonly optional: true };\nexport interface ObjectShape {\n readonly [key: string]: DocumentNode;\n}\nexport type ObjectNode<TShape extends ObjectShape = ObjectShape> = BaseNode<'object'> & {\n readonly shape: TShape;\n};\nexport interface VariantShape {\n readonly [key: string]: ObjectNode<ObjectShape>;\n}\nexport type VariantNode<\n TTag extends string,\n TVariants extends VariantShape,\n> = BaseNode<'variant'> & {\n readonly tag: TTag;\n readonly variants: TVariants;\n};\nexport type TableNode<\n TValue extends ObjectNode<ObjectShape> | VariantNode<string, VariantShape>,\n TKey extends string = string,\n> = BaseNode<'table'> & {\n readonly value: TValue;\n readonly key?: Validator<TKey>;\n};\nexport type MapNode<\n TValue extends ValueSchemaNode,\n TKey extends string = string,\n> = BaseNode<'map'> & {\n readonly value: TValue;\n readonly key?: Validator<TKey>;\n};\nexport type ListNode<TItem> = BaseNode<'list'> & {\n readonly value: FieldNode<TItem, false>;\n keyOf(item: ReadonlyValue<TItem>): string;\n};\nexport type TreeNode<TValue, ValueOptional extends boolean = false> = BaseNode<'tree'> & {\n readonly value: FieldNode<TValue, ValueOptional>;\n};\n\nexport type DocumentNode =\n | FieldNode<unknown, false>\n | FieldNode<unknown, true>\n | ObjectNode<ObjectShape>\n | VariantNode<string, VariantShape>\n | TableNode<ObjectNode<ObjectShape> | VariantNode<string, VariantShape>>\n | MapNode<ValueSchemaNode>\n | ListNode<unknown>\n | TreeNode<unknown, false>\n | TreeNode<unknown, true>;\n\ndeclare const schemaType: unique symbol;\ndeclare const schemaNode: unique symbol;\ndeclare const objectSchema: unique symbol;\n\nexport type Schema<T = unknown> = {\n readonly [schemaType]: T;\n};\n\nexport type ObjectSchema<T extends object = object> = Schema<T> & {\n readonly [objectSchema]: true;\n};\n\nexport type SchemaNodeOf<S extends Schema<unknown>> = S extends {\n readonly [schemaNode]: infer N extends DocumentNode;\n}\n ? N\n : S extends ObjectSchema<object>\n ? ObjectNode\n : DocumentNode;\n\nexport const schemaNodeOf = <S extends Schema<unknown>>(schema: S): SchemaNodeOf<S> =>\n schema as unknown as SchemaNodeOf<S>;\n\n// Flatten only schema-generated objects; user-supplied field values stay opaque.\ntype SchemaObject<T> = { [K in keyof T]: T[K] } & {};\n\n/** Infer a document or node value, including optional node presence. */\ntype InferNode<T extends DocumentNode> = T extends { readonly optional: true }\n ? NodeValue<T> | undefined\n : NodeValue<T>;\n\nexport type Infer<T extends Schema<unknown> | DocumentNode> =\n T extends Schema<infer TValue> ? TValue : T extends DocumentNode ? InferNode<T> : never;\n\ntype NodeValue<N> =\n N extends FieldNode<infer T, infer O>\n ? O extends true\n ? ReadonlyValue<T> | undefined\n : ReadonlyValue<T>\n : N extends ObjectNode<infer S>\n ? ShapeValue<S>\n : N extends VariantNode<infer T, infer V>\n ? {\n [K in keyof V & string]: SchemaObject<{ readonly [P in T]: K } & NodeValue<V[K]>>;\n }[keyof V & string]\n : N extends TableNode<infer V, infer K>\n ? {\n readonly ids: readonly K[];\n readonly byId: Readonly<Record<K, NodeValue<V>>>;\n }\n : N extends MapNode<infer V, infer K>\n ? Readonly<Record<K, NodeValue<V>>>\n : N extends ListNode<infer I>\n ? readonly ReadonlyValue<I>[]\n : N extends TreeNode<infer T, infer O>\n ? DocumentTreeValue<T, O>\n : never;\n\ntype OptionalKeys<S extends ObjectShape> = {\n [K in keyof S]: S[K] extends { readonly optional: true } ? K : never;\n}[keyof S];\ntype RequiredKeys<S extends ObjectShape> = Exclude<keyof S, OptionalKeys<S>>;\ntype ShapeValue<S extends ObjectShape> = SchemaObject<\n { readonly [K in RequiredKeys<S>]: NodeValue<S[K]> } & {\n readonly [K in OptionalKeys<S>]?: NodeValue<S[K]>;\n }\n>;\n\nexport type RootNodeOf<S extends ObjectSchema<object>> = Extract<SchemaNodeOf<S>, ObjectNode>;\nexport type EntitySchemaNode = ObjectNode<ObjectShape> | VariantNode<string, VariantShape>;\nexport type ValueSchemaNode = EntitySchemaNode | FieldNode<unknown, boolean>;\nexport type DocumentAnchor<K extends string = string> =\n { readonly at: 'start' | 'end' } | { readonly before: K } | { readonly after: K };\n\ntype SchemaHandle<N extends DocumentNode> = Schema<InferNode<N>> & {\n readonly [schemaNode]: N;\n};\ntype PublicSchemaShape = { readonly [key: string]: Schema<unknown> };\ntype NodeShapeOf<S extends PublicSchemaShape> = {\n readonly [K in keyof S]: SchemaNodeOf<S[K]>;\n};\ntype PublicOptionalKeys<S extends PublicSchemaShape> = {\n [K in keyof S]: SchemaNodeOf<S[K]> extends { readonly optional: true } ? K : never;\n}[keyof S];\ntype PublicRequiredKeys<S extends PublicSchemaShape> = Exclude<keyof S, PublicOptionalKeys<S>>;\ntype PublicShapeValue<S extends PublicSchemaShape> = SchemaObject<\n { readonly [K in PublicRequiredKeys<S>]: Infer<S[K]> } & {\n readonly [K in PublicOptionalKeys<S>]?: Infer<S[K]>;\n }\n>;\ntype ObjectSchemaHandle<S extends PublicSchemaShape> = ObjectSchema<PublicShapeValue<S>> & {\n readonly [schemaNode]: ObjectNode<NodeShapeOf<S>>;\n};\ntype FieldSchemaHandle<T> = SchemaHandle<FieldNode<T, false>>;\ntype OptionalFieldSchemaHandle<T> = SchemaHandle<FieldNode<T, true>>;\ntype OptionalSchemaHandle = Schema<unknown> & { readonly [schemaNode]: OptionalLeaf };\ntype EntitySchemaHandle = Schema<unknown> & { readonly [schemaNode]: EntitySchemaNode };\ntype ValueSchemaHandle = Schema<unknown> & { readonly [schemaNode]: ValueSchemaNode };\ntype PublicVariantShape = { readonly [key: string]: ObjectSchema<object> };\ntype VariantNodeShapeOf<V extends PublicVariantShape> = {\n readonly [K in keyof V]: Extract<SchemaNodeOf<V[K]>, ObjectNode>;\n};\ntype VariantSchemaHandle<T extends string, V extends PublicVariantShape> = Schema<\n {\n [K in keyof V & string]: SchemaObject<{ readonly [P in T]: K } & Infer<V[K]>>;\n }[keyof V & string]\n> & {\n readonly [schemaNode]: VariantNode<T, VariantNodeShapeOf<V>>;\n};\nexport const collectionEntryNode = (node: DocumentNode): ValueSchemaNode | undefined =>\n node.kind === 'map' || node.kind === 'table' || node.kind === 'list' ? node.value : undefined;\n\nconst node = <T extends DocumentNode>(value: T): T => Object.freeze(value);\ntype OptionalLeaf =\n | FieldNode<unknown, boolean>\n | VariantNode<string, VariantShape>\n | MapNode<ValueSchemaNode>\n | ListNode<unknown>\n | TreeNode<unknown, false>\n | TreeNode<unknown, true>;\ntype OptionalResult<T extends OptionalSchemaHandle> = SchemaHandle<\n OptionalNode<Extract<SchemaNodeOf<T>, OptionalLeaf>>\n>;\ntype EntityNodeOf<V extends EntitySchemaHandle> = Extract<SchemaNodeOf<V>, EntitySchemaNode>;\ntype ValueNodeOf<V extends ValueSchemaHandle> = Extract<SchemaNodeOf<V>, ValueSchemaNode>;\n\nexport const field = <T>(validator?: Validator<T>): FieldSchemaHandle<T> =>\n node({ kind: 'field', ...(validator ? { validator } : {}) }) as unknown as FieldSchemaHandle<T>;\nexport const optional = <T extends OptionalSchemaHandle>(value: T): OptionalResult<T> => {\n const concrete = schemaNodeOf(value) as Extract<SchemaNodeOf<T>, OptionalLeaf>;\n if (!['field', 'variant', 'map', 'list', 'tree'].includes(concrete.kind))\n throw new TypeError('Only field, variant, map, list and tree nodes support optional presence.');\n return node({ ...concrete, optional: true } as OptionalNode<\n typeof concrete\n >) as unknown as OptionalResult<T>;\n};\nexport const object = <S extends PublicSchemaShape>(shape: S): ObjectSchemaHandle<S> =>\n node({\n kind: 'object',\n shape: Object.freeze(\n Object.fromEntries(Object.entries(shape).map(([key, value]) => [key, schemaNodeOf(value)]))\n ) as NodeShapeOf<S>,\n }) as unknown as ObjectSchemaHandle<S>;\nexport const variant = <T extends string, V extends PublicVariantShape>(\n tag: T,\n variants: V\n): VariantSchemaHandle<T, V> =>\n node({\n kind: 'variant',\n tag,\n variants: Object.freeze(\n Object.fromEntries(Object.entries(variants).map(([key, value]) => [key, schemaNodeOf(value)]))\n ) as VariantNodeShapeOf<V>,\n }) as unknown as VariantSchemaHandle<T, V>;\nexport const table = <V extends EntitySchemaHandle, K extends string = string>(\n value: V,\n options?: { readonly key: Validator<K> }\n): SchemaHandle<TableNode<EntityNodeOf<V>, K>> =>\n node({\n kind: 'table',\n value: schemaNodeOf(value) as EntityNodeOf<V>,\n ...options,\n }) as unknown as SchemaHandle<TableNode<EntityNodeOf<V>, K>>;\nexport const map = <V extends ValueSchemaHandle, K extends string = string>(\n value: V,\n options?: { readonly key: Validator<K> }\n): SchemaHandle<MapNode<ValueNodeOf<V>, K>> =>\n node({\n kind: 'map',\n value: schemaNodeOf(value) as ValueNodeOf<V>,\n ...options,\n }) as unknown as SchemaHandle<MapNode<ValueNodeOf<V>, K>>;\nexport const list = <TItem>(\n value: FieldSchemaHandle<TItem>,\n config: DocumentListConfig<TItem>\n): SchemaHandle<ListNode<TItem>> =>\n node({\n kind: 'list',\n keyOf: config.keyOf,\n value: schemaNodeOf(value),\n }) as unknown as SchemaHandle<ListNode<TItem>>;\nexport function tree<TValue>(\n value: FieldSchemaHandle<TValue>\n): SchemaHandle<TreeNode<TValue, false>>;\nexport function tree<TValue>(\n value: OptionalFieldSchemaHandle<TValue>\n): SchemaHandle<TreeNode<TValue, true>>;\nexport function tree(\n value: FieldSchemaHandle<unknown> | OptionalFieldSchemaHandle<unknown>\n): SchemaHandle<TreeNode<unknown, false> | TreeNode<unknown, true>> {\n return Object.freeze({\n kind: 'tree' as const,\n value: schemaNodeOf(value),\n }) as unknown as SchemaHandle<TreeNode<unknown, false> | TreeNode<unknown, true>>;\n}\n","import { profile } from '../profile';\n\nexport type KeyOrder = {\n readonly length: number;\n readonly at: (index: number) => string | undefined;\n readonly index: (key: string) => number;\n};\n\nexport type OrderedKeys = readonly string[] | KeyOrder;\n\ntype ListSequence = {\n readonly order: readonly string[];\n readonly values: ReadonlyMap<string, unknown>;\n};\n\nconst length = (keys: OrderedKeys): number => keys.length;\nconst keyAt = (keys: OrderedKeys, index: number): string | undefined =>\n Array.isArray(keys) ? keys[index] : keys.at(index);\n\nexport const equal = (left: readonly string[], right: OrderedKeys): boolean => {\n profile.equality.call();\n if (left === right) return true;\n profile.equality.container();\n if (left.length !== right.length) return false;\n for (let index = 0; index < left.length; index++)\n if (left[index] !== keyAt(right, index)) return false;\n return true;\n};\n\nexport const keys = (values: readonly unknown[], keyOf: (value: unknown) => string): KeyOrder => ({\n length: values.length,\n at: index => (index >= 0 && index < values.length ? keyOf(values[index]) : undefined),\n index: key => {\n for (let index = 0; index < values.length; index += 1)\n if (keyOf(values[index]) === key) return index;\n return -1;\n },\n});\n\nconst listIndexes = new WeakMap<\n readonly unknown[],\n { keyOf: (value: unknown) => string; order: KeyOrder }\n>();\n\nconst knownKeys = (values: readonly string[]): KeyOrder => {\n let positions: Map<string, number> | undefined;\n return {\n length: values.length,\n at: index => values[index],\n index: key => {\n if (!positions) {\n positions = new Map();\n for (let index = 0; index < values.length; index++) positions.set(values[index], index);\n profile.address.listIndex(values.length);\n }\n return positions.get(key) ?? -1;\n },\n };\n};\n\nconst cacheKnownKeys = (\n values: readonly unknown[],\n keyOf: (value: unknown) => string,\n order: readonly string[]\n): void => {\n listIndexes.set(values, { keyOf, order: knownKeys(order) });\n};\n\n/** Canonical lists keep their key positions until a structural write invalidates them. */\nexport const indexedKeys = (\n values: readonly unknown[],\n keyOf: (value: unknown) => string\n): KeyOrder => {\n const cached = listIndexes.get(values);\n if (cached?.keyOf === keyOf) return cached.order;\n let positions: Map<string, number> | undefined;\n const order: KeyOrder = {\n length: values.length,\n at: index => (index >= 0 && index < values.length ? keyOf(values[index]) : undefined),\n index: key => {\n if (!positions) {\n positions = new Map();\n for (let index = 0; index < values.length; index++)\n positions.set(keyOf(values[index]), index);\n profile.address.listIndex(values.length);\n }\n return positions.get(key) ?? -1;\n },\n };\n listIndexes.set(values, { keyOf, order });\n return order;\n};\n\nexport const toArray = (keys: OrderedKeys): string[] => {\n const result = new Array<string>(length(keys));\n for (let index = 0; index < result.length; index++) result[index] = keyAt(keys, index) as string;\n return result;\n};\n\n/** One operation-local list scan provides both stable keys and item association. */\nexport const listSequence = (\n values: readonly unknown[],\n keyOf: (value: unknown) => string\n): ListSequence => {\n const current = indexedKeys(values, keyOf);\n const order = new Array<string>(values.length);\n const byKey = new Map<string, unknown>();\n for (let index = 0; index < values.length; index++) {\n const key = current.at(index) as string;\n order[index] = key;\n byKey.set(key, values[index]);\n }\n cacheKnownKeys(values, keyOf, order);\n return { order, values: byKey };\n};\n\n/** Structural sequence writes own invalidation, including rollback writes. */\nexport const insert = (values: unknown[], index: number, value: unknown): void => {\n values.splice(index, 0, value);\n listIndexes.delete(values);\n};\n\nexport const remove = (values: unknown[], index: number): void => {\n values.splice(index, 1);\n listIndexes.delete(values);\n};\n\n/** Installs an exact string-key sequence such as table ids in one structural write. */\nexport const installKeys = (values: string[], order: readonly string[]): void => {\n values.length = order.length;\n for (let index = 0; index < order.length; index++) values[index] = order[index];\n};\n\n/** Installs a pre-resolved list sequence without running keyOf again. */\nexport const installList = (\n values: unknown[],\n keyOf: (value: unknown) => string,\n sequence: ListSequence,\n order: readonly string[]\n): void => {\n values.length = order.length;\n for (let index = 0; index < order.length; index++)\n values[index] = sequence.values.get(order[index]);\n cacheKnownKeys(values, keyOf, order);\n};\n\nexport const install = (\n values: unknown[],\n keyOf: (value: unknown) => string,\n order: readonly string[]\n): void => {\n installList(values, keyOf, listSequence(values, keyOf), order);\n};\n\nexport const matches = (order: readonly string[], members: readonly string[]): boolean => {\n if (order.length !== members.length) return false;\n const ids = new Set(order);\n return ids.size === order.length && members.every(id => ids.has(id));\n};\n","import { profile } from '../profile';\nimport type { DocumentNode, ObjectNode, ObjectShape, VariantNode, VariantShape } from './model';\n\ntype MemberDefinition = {\n readonly node: DocumentNode;\n readonly field: boolean;\n};\n\nexport type FixedMember = MemberDefinition & {\n readonly kind: 'fixed';\n readonly key: string;\n readonly slot: number;\n};\n\ntype CollectionMember = MemberDefinition & { readonly kind: 'entry' };\n\nexport type CompiledMember = FixedMember | CollectionMember;\n\nexport type FixedLayout = {\n readonly kind: 'fixed';\n readonly members: ReadonlyMap<string, FixedMember>;\n};\n\ntype DynamicLayout = {\n readonly kind: 'dynamic';\n readonly entry: CollectionMember;\n};\n\nexport type MemberLayout = FixedLayout | DynamicLayout;\n\nconst compiledObjects = new WeakMap<object, FixedLayout>();\nconst compiledEntries = new WeakMap<DocumentNode, DynamicLayout>();\n\nexport const variantBranch = (\n node: VariantNode<string, VariantShape>,\n discriminator: string | undefined\n): ObjectNode<ObjectShape> | undefined =>\n node.variants[discriminator ?? Object.keys(node.variants)[0] ?? ''];\n\nconst objectBranch = (node: DocumentNode, value: unknown): ObjectNode<ObjectShape> | undefined => {\n if (node.kind === 'object') return node;\n if (\n node.kind !== 'variant' ||\n typeof value !== 'object' ||\n value === null ||\n Array.isArray(value)\n )\n return undefined;\n const record = value as Record<string, unknown>;\n const rawTag = record[node.tag];\n const tag = typeof rawTag === 'string' ? rawTag : undefined;\n return variantBranch(node, tag);\n};\n\nexport const compiledShape = (node: DocumentNode, value: unknown): FixedLayout | undefined => {\n const branch = objectBranch(node, value);\n if (!branch) return undefined;\n const shape: ObjectShape = branch.shape;\n let layout = compiledObjects.get(shape);\n if (!layout) {\n const members = new Map<string, FixedMember>();\n for (const key of Object.keys(shape).sort()) {\n profile.address.schemaStep();\n members.set(key, {\n kind: 'fixed',\n key,\n node: shape[key],\n field: shape[key].kind === 'field',\n slot: members.size,\n });\n }\n layout = { kind: 'fixed', members };\n compiledObjects.set(shape, layout);\n }\n return layout;\n};\n\nexport const compiledLayout = (node: DocumentNode, value: unknown): MemberLayout | undefined => {\n if (node.kind !== 'map' && node.kind !== 'table' && node.kind !== 'list')\n return compiledShape(node, value);\n let layout = compiledEntries.get(node);\n if (!layout) {\n layout = {\n kind: 'dynamic',\n entry: { kind: 'entry', node: node.value, field: node.value.kind === 'field' },\n };\n compiledEntries.set(node, layout);\n }\n return layout;\n};\n","import { profile } from '../profile';\nimport * as sequence from '../order/sequence';\nimport * as tree from '../tree/topology';\nimport { isPlainObject, isRecord } from '../value/record';\nimport type {\n DocumentAddress,\n DocumentNode,\n DocumentTreeNode,\n FieldNode,\n Infer,\n Schema,\n Validator,\n} from './model';\nimport { schemaNodeOf } from './model';\nimport { compiledShape } from './layout';\n\nexport type ParseIssue = {\n readonly address: DocumentAddress;\n readonly code: 'invalid-value' | 'invalid-key' | 'missing-validator' | 'invalid-tree';\n readonly message: string;\n};\nexport class ParseError extends TypeError {\n readonly issues: readonly ParseIssue[];\n constructor(issue: ParseIssue) {\n super(`${issue.message} at ${JSON.stringify(issue.address)}`);\n this.name = 'ParseError';\n this.issues = Object.freeze([\n Object.freeze({ ...issue, address: Object.freeze([...issue.address]) }),\n ]);\n }\n}\n\nconst issue = (\n address: DocumentAddress,\n message: string,\n code: ParseIssue['code'] = 'invalid-value'\n): ParseIssue => ({ address, message, code });\n\nconst checkScalar = (\n validator: Validator<unknown> | undefined,\n value: unknown,\n address: DocumentAddress,\n strict: boolean\n): ParseIssue | undefined => {\n if (!validator)\n return strict\n ? issue(address, 'A validator is required to parse an opaque value.', 'missing-validator')\n : undefined;\n try {\n const result =\n typeof validator === 'function' ? validator(value) : validator['~standard'].validate(value);\n if (\n result &&\n (typeof result === 'object' || typeof result === 'function') &&\n 'then' in result &&\n typeof result.then === 'function'\n )\n return issue(address, 'Validators must be synchronous.');\n if (typeof validator === 'function') {\n if (result === false) return issue(address, 'Value validation failed.');\n if (result !== undefined && result !== true)\n return issue(address, 'Function validators must return boolean or undefined.');\n } else {\n if (!isRecord(result)) return issue(address, 'Malformed validator result.');\n if (Array.isArray(result.issues)) {\n const first = result.issues[0];\n return issue(\n [\n ...address,\n ...(first?.path ?? []).map((part: PropertyKey | { key: PropertyKey }) =>\n String(typeof part === 'object' ? part.key : part)\n ),\n ],\n first?.message ?? 'Value validation failed.'\n );\n }\n if (!Object.hasOwn(result, 'value')) return issue(address, 'Malformed validator result.');\n if (!Object.is((result as { readonly value: unknown }).value, value))\n return issue(address, 'Validators must not transform values.');\n }\n return undefined;\n } catch (error) {\n return issue(address, error instanceof Error ? error.message : 'Value validation failed.');\n }\n};\n\nexport const checkKey = (\n validator: Validator<string> | undefined,\n value: unknown,\n address: DocumentAddress\n): ParseIssue | undefined => {\n if (typeof value !== 'string')\n return issue(address, 'Collection keys must be strings.', 'invalid-key');\n const failure = checkScalar(validator, value, address, false);\n return failure ? { ...failure, code: 'invalid-key' } : undefined;\n};\n\nexport const checkValue = (\n node: DocumentNode,\n value: unknown,\n address: DocumentAddress = [],\n strict = false\n): ParseIssue | undefined => {\n if (node.optional && value === undefined) return undefined;\n if (node.kind === 'field') return checkScalar(node.validator, value, address, strict);\n if (node.kind === 'object' || node.kind === 'variant') {\n if (!isPlainObject(value)) return issue(address, 'Expected an object.');\n if (node.kind === 'variant') {\n const tag = value[node.tag];\n if (\n !Object.hasOwn(value, node.tag) ||\n typeof tag !== 'string' ||\n !Object.hasOwn(node.variants, tag)\n )\n return issue([...address, node.tag], 'Unknown variant tag.');\n }\n const { members } = compiledShape(node, value)!;\n for (const key of Reflect.ownKeys(value)) {\n if (node.kind === 'variant' && key === node.tag) continue;\n if (typeof key !== 'string' || !members.has(key))\n return issue([...address, String(key)], 'Property is not declared in the object schema.');\n }\n for (const [key, member] of members) {\n const child = member.node;\n if (!Object.prototype.hasOwnProperty.call(value, key) && !child.optional)\n return issue([...address, key], 'Required property is missing.');\n const failure = checkValue(child, value[key], [...address, key], strict);\n if (failure) return failure;\n }\n return undefined;\n }\n if (node.kind === 'table' || node.kind === 'map') {\n if (!isPlainObject(value)) return issue(address, 'Expected a collection object.');\n const entries = node.kind === 'table' ? value.byId : value;\n if (!isPlainObject(entries)) return issue(address, 'Expected a byId object.');\n if (node.kind === 'table') {\n if (!Array.isArray(value.ids) || value.ids.length !== Object.keys(entries).length)\n return issue(address, 'Table ids and entries must agree.');\n const seen = new Set<string>();\n for (const id of value.ids) {\n const failure = checkKey(node.key, id, address);\n if (failure) return failure;\n if (seen.has(id) || !Object.prototype.hasOwnProperty.call(entries, id))\n return issue(address, 'Table ids must be unique and reference existing entries.');\n seen.add(id);\n }\n }\n for (const id of Object.keys(entries)) {\n const failure =\n checkKey(node.key, id, [...address, id]) ??\n checkValue(node.value, entries[id], [...address, id], strict);\n if (failure) return failure;\n }\n return undefined;\n }\n if (node.kind === 'list') {\n if (!Array.isArray(value)) return issue(address, 'Expected a list.');\n const seen = new Set<string>();\n const order = sequence.keys(value, node.keyOf);\n for (let i = 0; i < value.length; i++) {\n const failure = checkValue(node.value, value[i], [...address, String(i)], strict);\n if (failure) return failure;\n let key: unknown;\n try {\n key = order.at(i);\n } catch {\n return issue(address, 'List keyOf failed.');\n }\n if (typeof key !== 'string' || seen.has(key))\n return issue(address, 'List keys must be unique strings.', 'invalid-key');\n seen.add(key);\n }\n return undefined;\n }\n if (!tree.validate(value)) return issue(address, 'Invalid tree structure.', 'invalid-tree');\n for (const id of Object.keys(value.nodes)) {\n const failure = checkTreePayload(node.value, value.nodes[id], [...address, id], strict);\n if (failure) return failure;\n }\n return undefined;\n};\n\nexport const checkTreePayload = (\n node: FieldNode<unknown, boolean>,\n value: unknown,\n address: DocumentAddress,\n strict = false\n): ParseIssue | undefined => {\n if (!isRecord(value)) return issue(address, 'Invalid tree node.', 'invalid-tree');\n const present = Object.prototype.hasOwnProperty.call(value, 'value');\n if (!present && !node.optional) return issue(address, 'Tree node value is required.');\n return present ? checkValue(node, value.value, address, strict) : undefined;\n};\n\nexport const copyTreeNode = <T extends { readonly children: readonly string[] }>(\n value: T\n): Omit<T, 'children'> & { children: string[] } => {\n profile.copy.treeNode();\n return { ...value, children: [...value.children] };\n};\n\nexport const equalTreeNode = (\n left: DocumentTreeNode<unknown, false> | DocumentTreeNode<unknown, true> | undefined,\n right: DocumentTreeNode<unknown, false> | DocumentTreeNode<unknown, true> | undefined\n): boolean => {\n if (left === right) return true;\n if (!left || !right) return false;\n return (\n left.parentId === right.parentId &&\n sequence.equal(left.children, right.children) &&\n Object.hasOwn(left, 'value') === Object.hasOwn(right, 'value') &&\n Object.is(left.value, right.value)\n );\n};\n\n/** Copy editable structure; atomic payloads retain their immutable ownership contract. */\nexport const copyValue = (node: DocumentNode, value: unknown): unknown => {\n if (value === undefined || node.kind === 'field') return value;\n profile.copy.structure();\n if ((node.kind === 'object' || node.kind === 'variant') && isRecord(value)) {\n const result = Object.create(Object.getPrototypeOf(value));\n const { members } = compiledShape(node, value)!;\n for (const key of Object.getOwnPropertyNames(value)) {\n Object.defineProperty(result, key, {\n value:\n node.kind === 'variant' && key === node.tag\n ? value[key]\n : copyValue(members.get(key)!.node, value[key]),\n writable: true,\n enumerable: Object.getOwnPropertyDescriptor(value, key)?.enumerable,\n configurable: true,\n });\n }\n return result;\n }\n if ((node.kind === 'table' || node.kind === 'map') && isRecord(value)) {\n const entries = (node.kind === 'table' ? value.byId : value) as Record<string, unknown>;\n const result = Object.fromEntries(\n Object.keys(entries).map(id => [id, copyValue(node.value, entries[id])])\n );\n return node.kind === 'table' ? { ids: [...(value.ids as string[])], byId: result } : result;\n }\n if (node.kind === 'list') return [...(value as unknown[])];\n if (node.kind === 'tree' && isRecord(value)) {\n const entries = value.nodes as Record<\n string,\n DocumentTreeNode<unknown, false> | DocumentTreeNode<unknown, true>\n >;\n return {\n ...value,\n nodes: Object.fromEntries(Object.entries(entries).map(([id, n]) => [id, copyTreeNode(n)])),\n };\n }\n return value;\n};\n\nexport const equalValue = (node: DocumentNode, left: unknown, right: unknown): boolean => {\n if (Object.is(left, right)) return true;\n if (node.kind === 'field' || left === undefined || right === undefined) return false;\n if ((node.kind === 'object' || node.kind === 'variant') && isRecord(left) && isRecord(right)) {\n if (node.kind === 'variant' && left[node.tag] !== right[node.tag]) return false;\n for (const [key, member] of compiledShape(node, left)!.members) {\n if (Object.hasOwn(left, key) !== Object.hasOwn(right, key)) return false;\n if (!equalValue(member.node, left[key], right[key])) return false;\n }\n return true;\n }\n if (node.kind === 'list' && Array.isArray(left) && Array.isArray(right))\n return (\n left.length === right.length && left.every((v, i) => equalValue(node.value, v, right[i]))\n );\n if (node.kind === 'table' && isRecord(left) && isRecord(right))\n return (\n sequence.equal(left.ids as string[], right.ids as string[]) &&\n equalValue({ kind: 'map', value: node.value }, left.byId, right.byId)\n );\n if (node.kind === 'tree' && isRecord(left) && isRecord(right)) {\n if (left.rootId !== right.rootId) return false;\n const a = left.nodes as Record<\n string,\n DocumentTreeNode<unknown, false> | DocumentTreeNode<unknown, true>\n >,\n b = right.nodes as typeof a;\n return (\n Object.keys(a).length === Object.keys(b).length &&\n Object.keys(a).every(id => Object.hasOwn(b, id) && equalTreeNode(a[id], b[id]))\n );\n }\n if (node.kind === 'map' && isRecord(left) && isRecord(right)) {\n const keys = Object.keys(left);\n return (\n keys.length === Object.keys(right).length &&\n keys.every(key => Object.hasOwn(right, key) && equalValue(node.value, left[key], right[key]))\n );\n }\n return false;\n};\n\nexport const parse = <S extends Schema<unknown>>(schema: S, input: unknown): Infer<S> => {\n const valueNode = schemaNodeOf(schema);\n const failure = checkValue(valueNode, input, [], true);\n if (failure) throw new ParseError(failure);\n return copyValue(valueNode, input) as Infer<S>;\n};\n","import * as sequence from '../order/sequence';\nimport { profile } from '../profile';\nimport type { DocumentAddress, DocumentNode } from '../schema/model';\nimport { compiledLayout, variantBranch, type MemberLayout } from '../schema/layout';\nimport * as tree from '../tree/topology';\nimport { isRecord } from '../value/record';\n\nconst step = (\n nodeInput: DocumentNode | undefined,\n value: unknown,\n segment: string\n): DocumentNode | undefined => {\n let node = nodeInput;\n if (!node) return undefined;\n if (node.kind === 'variant') {\n const rawTag = isRecord(value) ? value[node.tag] : undefined;\n const tag = typeof rawTag === 'string' ? rawTag : undefined;\n node = variantBranch(node, tag);\n }\n if (!node) return undefined;\n if (node.kind === 'object')\n return Object.hasOwn(node.shape, segment) ? node.shape[segment] : undefined;\n if (node.kind === 'table' || node.kind === 'map') return node.value;\n // List items use stable keys; tree topology remains a structural unit.\n if (node.kind === 'list') return node.value;\n return undefined;\n};\n\nexport const nodeAt = (\n schema: DocumentNode,\n address: DocumentAddress,\n document?: unknown\n): DocumentNode | undefined => {\n let node: DocumentNode | undefined = schema;\n let value = document;\n for (const segment of address) {\n const resolved = step(node, value, segment);\n value = readSegment(value, segment, node);\n node = resolved;\n if (!node) return undefined;\n }\n return node;\n};\n\nconst readSegment = (value: unknown, segment: string, node?: DocumentNode): unknown => {\n if (!isRecord(value) && !Array.isArray(value)) return undefined;\n if (node?.kind === 'list' && Array.isArray(value))\n return value[sequence.indexedKeys(value, node.keyOf).index(segment)];\n if (node?.kind === 'table' && isRecord(value) && isRecord(value.byId)) {\n return Object.hasOwn(value.byId, segment) ? value.byId[segment] : undefined;\n }\n return Object.prototype.hasOwnProperty.call(value, segment)\n ? (value as Record<string, unknown>)[segment]\n : undefined;\n};\n\ntype ResolvedAddress = {\n readonly parent: Record<string, unknown> | unknown[];\n readonly key: string | number;\n readonly node: DocumentNode;\n};\n\n/** Immutable location facts, valid only for the resolving session generation. */\nexport type ResolvedContainer = {\n readonly owner: object;\n readonly generation: number;\n readonly at: DocumentAddress;\n readonly node: Exclude<DocumentNode, { kind: 'tree' }>;\n readonly parent: Record<string, unknown> | unknown[];\n readonly value: unknown;\n readonly layout: MemberLayout;\n};\nexport type ResolvedTreeContainer = {\n readonly owner: object;\n readonly generation: number;\n readonly at: DocumentAddress;\n readonly node: Extract<DocumentNode, { kind: 'tree' }>;\n readonly value: tree.MutableTree;\n};\nexport const resolveContainer = (\n owner: object,\n generation: number,\n at: DocumentAddress,\n node: DocumentNode | undefined,\n value: unknown\n): ResolvedContainer | undefined => {\n if (!node || (!isRecord(value) && !Array.isArray(value))) return undefined;\n const parent = node.kind === 'table' && isRecord(value) ? value.byId : value;\n if (!isRecord(parent) && !Array.isArray(parent)) return undefined;\n if (node.kind === 'tree') return undefined;\n const layout = compiledLayout(node, value);\n if (!layout) return undefined;\n return { owner, generation, at, node, parent, value, layout };\n};\nexport const resolveTreeContainer = (\n owner: object,\n generation: number,\n at: DocumentAddress,\n node: DocumentNode | undefined,\n value: unknown\n): ResolvedTreeContainer | undefined =>\n node?.kind === 'tree' && tree.is(value) ? { owner, generation, at, node, value } : undefined;\nexport const memberKey = (\n container: { readonly node: DocumentNode; readonly parent: Record<string, unknown> | unknown[] },\n key: string\n): string | number =>\n container.node.kind === 'list'\n ? sequence.indexedKeys(container.parent as unknown[], container.node.keyOf).index(key)\n : key;\n\ntype ResolutionPrefix = {\n segment: string;\n node: DocumentNode;\n value: unknown;\n};\n\n/** One recent path per transaction; structural writes invalidate all retained locations. */\nexport const createAddressResolver = (schema: DocumentNode, root: unknown) => {\n const prefix: ResolutionPrefix[] = [];\n return {\n container: (owner: object, generation: number, at: DocumentAddress) => {\n if (!at.length) return resolveContainer(owner, generation, at, schema, root);\n const location = resolveWithPrefix(schema, root, at, prefix);\n if (!location || !Object.hasOwn(location.parent, location.key)) return undefined;\n return resolveContainer(\n owner,\n generation,\n at,\n location.node,\n (location.parent as Record<string | number, unknown>)[location.key]\n );\n },\n invalidate: () => {\n prefix.length = 0;\n },\n };\n};\n\n/** A subtree root is a value, not a fabricated member of an ObjectNode. */\nexport const resolveValue = (\n schema: DocumentNode,\n root: unknown,\n address: DocumentAddress,\n prefix?: ResolutionPrefix[]\n): { node: DocumentNode; value: unknown } | undefined => {\n if (!address.length) return { node: schema, value: root };\n const location = resolveWithPrefix(schema, root, address, prefix);\n return (\n location && {\n node: location.node,\n value: Object.hasOwn(location.parent, location.key)\n ? (location.parent as Record<string | number, unknown>)[location.key]\n : undefined,\n }\n );\n};\n\n/** Resolves schema and document location in one address traversal. */\nexport const resolveLocated = (\n schema: DocumentNode,\n root: unknown,\n address: DocumentAddress\n): ResolvedAddress | undefined => resolveWithPrefix(schema, root, address);\n\nconst resolveWithPrefix = (\n schema: DocumentNode,\n root: unknown,\n address: DocumentAddress,\n prefix?: ResolutionPrefix[]\n): ResolvedAddress | undefined => {\n if (address.length === 0) return undefined;\n let node: DocumentNode | undefined = schema;\n let current: unknown = root;\n let start = 0;\n if (prefix) {\n while (\n start < prefix.length &&\n start < address.length - 1 &&\n prefix[start].segment === address[start]\n )\n start++;\n prefix.length = start;\n if (start) {\n const retained = prefix[start - 1];\n node = retained.node;\n current = retained.value;\n }\n }\n let cacheable = true;\n for (let index = start; index < address.length - 1; index += 1) {\n profile.address.schemaStep();\n profile.address.documentStep();\n const resolved = step(node, current, address[index]);\n if (!resolved) return undefined;\n if (node?.kind !== 'object' && node?.kind !== 'table' && node?.kind !== 'map')\n cacheable = false;\n current = readSegment(current, address[index], node);\n node = resolved;\n if (prefix && cacheable)\n prefix.push({\n segment: address[index],\n node: resolved,\n value: current,\n });\n if (!node) return undefined;\n }\n const last = address[address.length - 1];\n return resolveChild(node, current, last);\n};\n\n/** Resolves one member from an already current schema/container pair. */\nexport const resolveChild = (\n node: DocumentNode | undefined,\n current: unknown,\n last: string\n): ResolvedAddress | undefined => {\n profile.address.schemaStep();\n profile.address.documentStep();\n const resolved = step(node, current, last);\n if (!resolved || (!isRecord(current) && !Array.isArray(current))) return undefined;\n if (node?.kind === 'table' && isRecord(current) && isRecord(current.byId))\n return {\n node: resolved,\n parent: current.byId,\n key: last,\n };\n return {\n node: resolved,\n parent: current,\n key:\n node?.kind === 'list' && Array.isArray(current)\n ? sequence.indexedKeys(current, node.keyOf).index(last)\n : last,\n };\n};\n","import type { DocumentAnchor } from '../schema/model';\nimport type { KeyOrder, OrderedKeys } from './sequence';\n\ntype MoveSelection =\n | { readonly kind: 'ok'; readonly order: readonly string[] }\n | { readonly kind: 'duplicate' }\n | { readonly kind: 'missing' }\n | { readonly kind: 'invalid-anchor' };\n\nconst length = (keys: OrderedKeys): number => keys.length;\nconst keyIndex = (keys: OrderedKeys, key: string): number =>\n Array.isArray(keys) ? keys.indexOf(key) : (keys as KeyOrder).index(key);\n\n/** Plan one relative move against the order that remains after removing the selection. */\nexport const moveSelection = (\n current: readonly string[],\n selection: readonly string[],\n position?: DocumentAnchor\n): MoveSelection => {\n if (!selection.length) return { kind: 'ok', order: current };\n const selected = new Set<string>();\n for (const key of selection) {\n if (selected.has(key)) return { kind: 'duplicate' };\n selected.add(key);\n }\n const moved: string[] = [];\n const remaining: string[] = [];\n for (const key of current) (selected.has(key) ? moved : remaining).push(key);\n if (moved.length !== selected.size) return { kind: 'missing' };\n if (!valid(remaining, position)) return { kind: 'invalid-anchor' };\n const insertion = index(remaining, position);\n return {\n kind: 'ok',\n order: [...remaining.slice(0, insertion), ...moved, ...remaining.slice(insertion)],\n };\n};\n\nexport const index = (keys: OrderedKeys, anchor?: DocumentAnchor): number => {\n if (!anchor) return length(keys);\n if ('at' in anchor) return anchor.at === 'start' ? 0 : length(keys);\n if ('before' in anchor) return keyIndex(keys, anchor.before);\n return keyIndex(keys, anchor.after) + 1;\n};\n\nexport const valid = (keys: OrderedKeys, anchor?: DocumentAnchor): boolean => {\n if (!anchor) return true;\n if (typeof anchor !== 'object' || anchor === null) return false;\n if (Number('at' in anchor) + Number('before' in anchor) + Number('after' in anchor) !== 1)\n return false;\n if ('at' in anchor) return anchor.at === 'start' || anchor.at === 'end';\n return keyIndex(keys, 'before' in anchor ? anchor.before : anchor.after) >= 0;\n};\n","import type { DocumentAnchor } from '../../schema/model';\nimport type { MutationSession } from '../session';\nimport type { ResolvedContainer } from '../../address/resolve';\nimport * as anchor from '../../order/anchor';\nimport * as issue from '../issue';\nexport function create(\n session: MutationSession,\n container: ResolvedContainer,\n entries: readonly { id: string; value: unknown }[],\n position?: DocumentAnchor\n): void {\n const { at, node, value } = container;\n if (node.kind !== 'table') return issue.fail(at, 'invalid-collection', 'Expected a table.');\n const table = value as { ids: string[]; byId: Record<string, unknown> };\n if (!anchor.valid(table.ids, position))\n return issue.fail(at, 'invalid-anchor', 'Unknown table anchor.');\n const ids = new Set<string>();\n for (const entry of entries) {\n if (Object.hasOwn(table.byId, entry.id) || ids.has(entry.id))\n return issue.fail(at, 'duplicate-entity', 'Table key already exists.');\n ids.add(entry.id);\n }\n if (!entries.length) return;\n const index = anchor.index(table.ids, position);\n for (const entry of entries) session.writeMember(container, entry.id, entry.value, 'set');\n const length = table.ids.length;\n table.ids.length += entries.length;\n table.ids.copyWithin(index + entries.length, index, length);\n for (let i = 0; i < entries.length; i++) table.ids[index + i] = entries[i].id;\n}\nexport function remove(\n session: MutationSession,\n container: ResolvedContainer,\n ids: readonly string[]\n): void {\n const { at, node, value } = container;\n if (node.kind !== 'table') return issue.fail(at, 'invalid-collection', 'Expected a table.');\n const table = value as { ids: string[]; byId: Record<string, unknown> };\n for (const id of ids)\n if (!Object.hasOwn(table.byId, id))\n return issue.fail(at, 'missing-entity', 'Table key does not exist.');\n if (!ids.length) return;\n const removed = new Set(ids);\n for (const id of removed) session.writeMember(container, id, undefined, 'remove');\n table.ids = table.ids.filter(id => !removed.has(id));\n}\n\nexport function replace(\n session: MutationSession,\n container: ResolvedContainer,\n id: string,\n value: unknown\n): void {\n const { at, node, value: tableValue } = container;\n if (node.kind !== 'table') return issue.fail(at, 'invalid-collection', 'Expected a table.');\n const table = tableValue as { byId: Record<string, unknown> };\n if (!Object.hasOwn(table.byId, id))\n return issue.fail(at.concat(id), 'missing-entity', 'Table key does not exist.');\n session.writeMember(container, id, value, 'set');\n}\n","import type { DocumentAnchor } from '../../schema/model';\nimport type { MutationSession } from '../session';\nimport type { ResolvedContainer } from '../../address/resolve';\nimport * as anchor from '../../order/anchor';\nimport * as sequence from '../../order/sequence';\nimport * as issue from '../issue';\nexport function insert(\n session: MutationSession,\n container: ResolvedContainer,\n value: unknown,\n position?: DocumentAnchor\n): void {\n const { at, node, value: current } = container;\n if (node.kind !== 'list') return issue.fail(at, 'invalid-list-key', 'Expected a list.');\n session.validate(node.value, value, at);\n const id = node.keyOf(value);\n if (typeof id !== 'string')\n return issue.fail(at, 'invalid-list-key', 'List key must be a string.');\n const items = current as unknown[],\n keys = sequence.keys(items, node.keyOf);\n if (keys.index(id) >= 0) return issue.fail(at, 'duplicate-list-item', 'List key already exists.');\n if (!anchor.valid(keys, position))\n return issue.fail(at, 'invalid-anchor', 'Unknown list anchor.');\n session.recorder.order(container);\n session.recorder.member(container, id, session.definition(container, id), -1);\n sequence.insert(items, anchor.index(keys, position), value);\n session.invalidate();\n}\nexport function replace(\n session: MutationSession,\n container: ResolvedContainer,\n id: string,\n value: unknown\n): void {\n const { at, node, value: items } = container;\n if (node.kind !== 'list') return issue.fail(at, 'invalid-list-key', 'Expected a list.');\n const index = sequence.indexedKeys(items as unknown[], node.keyOf).index(id);\n if (index < 0) return issue.fail(at, 'missing-list-item', 'List key does not exist.');\n session.writeMember(container, id, value, 'set', index);\n}\nexport function remove(session: MutationSession, container: ResolvedContainer, id: string): void {\n const { at, node, value } = container;\n if (node.kind !== 'list') return issue.fail(at, 'missing-list-item', 'List key does not exist.');\n const index = sequence.keys(value as unknown[], node.keyOf).index(id);\n if (index < 0) return issue.fail(at, 'missing-list-item', 'List key does not exist.');\n session.writeMember(container, id, undefined, 'remove', index);\n}\n","import type { DocumentAddress } from '../../schema/model';\nimport type { ResolvedTreeContainer } from '../../address/resolve';\nimport type { MutationSession } from '../session';\nimport * as treeTopology from '../../tree/topology';\nimport type { MutableTree, TreePosition } from '../../tree/topology';\nimport * as issue from '../issue';\nconst node = (tree: MutableTree, id: string) =>\n Object.hasOwn(tree.nodes, id) ? tree.nodes[id] : undefined;\nconst positionIndex = (index: number | undefined, length: number, at: DocumentAddress): number => {\n if (index !== undefined && (!Number.isInteger(index) || index < 0))\n return issue.fail(at, 'invalid-tree-index', 'Tree index must be nonnegative.');\n return Math.min(index ?? length, length);\n};\nexport const insert = (\n session: MutationSession,\n container: ResolvedTreeContainer,\n id: string,\n value: unknown,\n position: TreePosition | undefined\n): void => {\n const { at, node: schema, value: tree } = container;\n if (typeof id !== 'string') return issue.fail(at, 'invalid-key', 'Tree keys must be strings.');\n if (treeTopology.contains(tree, id))\n return issue.fail(at, 'duplicate-tree-node', 'Tree node already exists.');\n const parentId = position?.parentId;\n const parent = parentId === undefined ? undefined : node(tree, parentId);\n if (\n (tree.rootId !== undefined && !parent) ||\n (tree.rootId === undefined && parentId !== undefined)\n )\n return issue.fail(at, 'missing-tree-parent', 'A nonempty tree requires an existing parent.');\n const index = positionIndex(position?.index, parent?.children.length ?? 0, at);\n session.validate(schema.value, value, at.concat(id));\n session.recorder.tree(container, id);\n if (parentId !== undefined) session.recorder.tree(container, parentId);\n Object.defineProperty(tree.nodes, id, {\n value: { ...(parentId === undefined ? {} : { parentId }), children: [], value },\n writable: true,\n configurable: true,\n enumerable: true,\n });\n if (parent) parent.children.splice(index, 0, id);\n else tree.rootId = id;\n session.invalidate();\n};\nexport const replace = (\n session: MutationSession,\n container: ResolvedTreeContainer,\n id: string,\n value: unknown\n): void => {\n const { at, node: schema, value: tree } = container;\n const entry = node(tree, id);\n if (!entry) return issue.fail(at, 'missing-tree-node', 'Tree node does not exist.');\n if (Object.is(entry.value, value) && Object.hasOwn(entry, 'value')) return;\n session.validate(schema.value, value, at.concat(id));\n session.recorder.tree(container, id);\n entry.value = value;\n};\nexport const remove = (\n session: MutationSession,\n container: ResolvedTreeContainer,\n id: string\n): void => {\n const { at, value: tree } = container;\n const entry = node(tree, id);\n if (!entry) return issue.fail(at, 'missing-tree-node', 'Tree node does not exist.');\n const ids: string[] = [],\n stack = [id];\n while (stack.length) {\n const current = stack.pop()!;\n ids.push(current);\n for (const child of tree.nodes[current].children) stack.push(child);\n }\n for (const key of ids) session.recorder.tree(container, key);\n if (entry.parentId !== undefined) session.recorder.tree(container, entry.parentId);\n if (entry.parentId === undefined) delete tree.rootId;\n else {\n const children = tree.nodes[entry.parentId].children;\n children.splice(children.indexOf(id), 1);\n }\n for (const key of ids) delete tree.nodes[key];\n session.invalidate();\n};\nexport const move = (\n session: MutationSession,\n container: ResolvedTreeContainer,\n id: string,\n position: TreePosition | undefined\n): void => {\n const { at, value: tree } = container;\n const entry = node(tree, id),\n parentId = position?.parentId;\n if (!entry) return issue.fail(at, 'missing-tree-node', 'Tree node does not exist.');\n if (\n entry.parentId === undefined ||\n parentId === undefined ||\n !treeTopology.contains(tree, parentId)\n )\n return issue.fail(\n at,\n 'missing-tree-parent',\n 'Moving requires a non-root node and an existing parent.'\n );\n for (\n let ancestor: string | undefined = parentId;\n ancestor !== undefined;\n ancestor = tree.nodes[ancestor].parentId\n )\n if (ancestor === id)\n return issue.fail(at, 'tree-cycle', 'Cannot move a node under its descendant.');\n const old = tree.nodes[entry.parentId],\n next = tree.nodes[parentId];\n const index = positionIndex(position?.index, next.children.length - (old === next ? 1 : 0), at);\n const previous = old.children.indexOf(id);\n if (old === next && previous === index) return;\n session.recorder.tree(container, id);\n session.recorder.tree(container, entry.parentId);\n session.recorder.tree(container, parentId);\n old.children.splice(previous, 1);\n next.children.splice(index, 0, id);\n entry.parentId = parentId;\n session.invalidate();\n};\n","import type { DocumentAnchor } from '../../schema/model';\nimport type { MutationSession } from '../session';\nimport type { ResolvedContainer } from '../../address/resolve';\nimport * as sequence from '../../order/sequence';\nimport * as anchor from '../../order/anchor';\nimport * as issue from '../issue';\n\nconst assertOrdered = (\n container: ResolvedContainer\n): Extract<ResolvedContainer['node'], { kind: 'table' | 'list' }> => {\n const { at, node } = container;\n if (node.kind !== 'table' && node.kind !== 'list')\n return issue.fail(at, 'invalid-collection', 'Expected an ordered container.');\n return node;\n};\n\nconst plannedOrder = (\n at: ResolvedContainer['at'],\n current: readonly string[],\n selection: readonly string[],\n position?: DocumentAnchor\n): readonly string[] => {\n const plan = anchor.moveSelection(current, selection, position);\n switch (plan.kind) {\n case 'ok':\n return plan.order;\n case 'duplicate':\n return issue.fail(at, 'invalid-key', 'Moved keys must be unique.');\n case 'missing':\n return issue.fail(at, 'missing-entity', 'Ordered key does not exist.');\n case 'invalid-anchor':\n return issue.fail(at, 'invalid-anchor', 'Unknown order anchor.');\n }\n};\n\nexport function move(\n session: MutationSession,\n container: ResolvedContainer,\n ids: string | readonly string[],\n position?: DocumentAnchor\n): void {\n const node = assertOrdered(container);\n const selection = typeof ids === 'string' ? [ids] : ids;\n if (!selection.length) return;\n\n if (node.kind === 'table') {\n const order = (container.value as { ids: string[] }).ids;\n const next = plannedOrder(container.at, order, selection, position);\n if (sequence.equal(order, next)) return;\n session.recorder.order(container);\n sequence.installKeys(order, next);\n } else {\n const items = container.value as unknown[];\n const current = sequence.listSequence(items, node.keyOf);\n const next = plannedOrder(container.at, current.order, selection, position);\n if (sequence.equal(current.order, next)) return;\n session.recorder.order(container);\n sequence.installList(items, node.keyOf, current, next);\n }\n session.invalidate();\n}\n\nexport function reorder(\n session: MutationSession,\n container: ResolvedContainer,\n next: readonly string[]\n): void {\n const node = assertOrdered(container);\n if (node.kind === 'table') {\n const current = (container.value as { ids: string[] }).ids;\n if (!sequence.matches(next, current))\n return issue.fail(\n container.at,\n 'invalid-collection',\n 'Order must contain every key exactly once.'\n );\n if (sequence.equal(current, next)) return;\n session.recorder.order(container);\n sequence.installKeys(current, next);\n } else {\n const items = container.value as unknown[];\n const current = sequence.listSequence(items, node.keyOf);\n if (!sequence.matches(next, current.order))\n return issue.fail(\n container.at,\n 'invalid-collection',\n 'Order must contain every key exactly once.'\n );\n if (sequence.equal(current.order, next)) return;\n session.recorder.order(container);\n sequence.installList(items, node.keyOf, current, next);\n }\n session.invalidate();\n}\n","import type { ChangeSet } from '../changes';\nimport type { DocumentAddress, ObjectNode } from '../schema/model';\nimport type { ImpactTarget, TreeTarget } from '../schema/path';\nimport { AddressIndex } from '../address/index';\nimport { profile } from '../profile';\n\nconst treeRootSegment = 'rootId';\nconst treeNodesSegment = 'nodes';\nconst ordinaryNamespace = '\\0value';\nconst treeNamespace = '\\0tree';\n\nexport const tree = (\n at: DocumentAddress,\n selection: Exclude<TreeTarget, { readonly kind: 'nodes' }>\n): ImpactTarget => ({ kind: 'value', at, tree: selection });\n\nexport const address = (target: ImpactTarget<unknown>): DocumentAddress =>\n 'at' in target ? target.at : target.address;\n\nexport const id = (target: ImpactTarget<unknown>): string | undefined =>\n target.kind === 'collection' && 'id' in target ? target.id : undefined;\n\nexport const belongs = (target: ImpactTarget<unknown>, schema: ObjectNode): boolean =>\n !('schema' in target) || target.schema === schema;\n\nconst treeTarget = (target: ImpactTarget<unknown>): TreeTarget | undefined =>\n 'tree' in target ? target.tree : undefined;\n\nconst sameTreeTarget = (left: TreeTarget | undefined, right: TreeTarget | undefined): boolean => {\n if (!left || !right) return left === right;\n if (left.kind !== right.kind) return false;\n return left.kind !== 'node' || (right.kind === 'node' && left.id === right.id);\n};\n\nexport const same = (left: ImpactTarget<unknown>, right: ImpactTarget<unknown>): boolean => {\n profile.dependency.comparison();\n if ('schema' in left && 'schema' in right && left.schema !== right.schema) return false;\n if (!sameTreeTarget(treeTarget(left), treeTarget(right))) return false;\n if (left.kind !== right.kind) return false;\n const leftAddress = address(left);\n const rightAddress = address(right);\n if (leftAddress.length !== rightAddress.length) return false;\n for (let index = 0; index < leftAddress.length; index += 1) {\n profile.dependency.segmentCompared();\n if (leftAddress[index] !== rightAddress[index]) return false;\n }\n return left.kind !== 'collection' || id(left) === id(right);\n};\n\nexport const indexedAddress = (target: ImpactTarget<unknown>): DocumentAddress => {\n const tree = treeTarget(target);\n if (tree?.kind === 'root') return [treeNamespace, ...address(target), treeRootSegment];\n if (tree?.kind === 'nodes') return [treeNamespace, ...address(target), treeNodesSegment];\n if (tree?.kind === 'node') return [treeNamespace, ...address(target), treeNodesSegment, tree.id];\n const key = id(target);\n return key === undefined\n ? [ordinaryNamespace, ...address(target)]\n : [ordinaryNamespace, ...address(target), key];\n};\n\n/**\n * Coarse identity for dependency de-duplication. Schema is intentionally excluded because\n * schema-bound and schema-free targets may compare equal; callers must still use same()\n * inside a bucket for the final equality decision.\n */\nexport const dependencyBucket = (target: ImpactTarget<unknown>): string =>\n JSON.stringify([target.kind, indexedAddress(target)]);\n\nexport const visitChangedLocations = (\n changes: ChangeSet,\n value: (at: DocumentAddress) => void,\n order: (at: DocumentAddress) => void\n): void => {\n for (const change of changes.changes) {\n if (change.kind === 'reset') continue;\n if (change.kind === 'members') {\n for (const member of change.members) {\n value([ordinaryNamespace, ...change.at, member.key]);\n value([treeNamespace, ...change.at, member.key]);\n }\n if (change.order) order([ordinaryNamespace, ...change.at]);\n continue;\n }\n value([ordinaryNamespace, ...change.at]);\n if (change.before !== change.after) value([treeNamespace, ...change.at, treeRootSegment]);\n for (const node of change.nodes)\n value([treeNamespace, ...change.at, treeNodesSegment, node.id]);\n }\n};\n\nexport const affected = (\n target: ImpactTarget,\n values: AddressIndex<true>,\n orders: AddressIndex<true>\n): boolean => {\n const at = indexedAddress(target);\n return id(target) !== undefined\n ? values.hasAncestor(at)\n : values.overlaps(at) || orders.hasDescendant(at);\n};\n\n/** Targets are classified once; commit matching never builds a reverse impact index. */\nexport class SubscriptionIndex<T> {\n private readonly ordinary = new AddressIndex<T>();\n private readonly membership = new AddressIndex<T>();\n constructor(private readonly schema: ObjectNode) {}\n add(target: ImpactTarget, value: T): void {\n if (!belongs(target, this.schema)) return;\n (id(target) === undefined ? this.ordinary : this.membership).add(indexedAddress(target), value);\n }\n delete(target: ImpactTarget, value: T): void {\n if (!belongs(target, this.schema)) return;\n (id(target) === undefined ? this.ordinary : this.membership).delete(\n indexedAddress(target),\n value\n );\n }\n collect(changes: ChangeSet, visit: (value: T) => void): void {\n const values = this.ordinary.query(visit);\n const members = this.membership.query(visit, 'descendants');\n const orders = this.ordinary.query(visit, 'ancestors');\n if (changes.changes.some(change => change.kind === 'reset')) {\n values([]);\n members([]);\n return;\n }\n visitChangedLocations(\n changes,\n at => {\n values(at);\n members(at);\n },\n orders\n );\n }\n clear(): void {\n this.ordinary.clear();\n this.membership.clear();\n }\n}\n","import type {\n DocumentAddress,\n DocumentAnchor,\n DocumentNode,\n DocumentTreeValue,\n FieldNode,\n Infer,\n ListNode,\n MapNode,\n ObjectNode,\n ObjectShape,\n ReadonlyValue,\n Schema,\n SchemaNodeOf,\n TableNode,\n TreeNode,\n ValueSchemaNode,\n VariantNode,\n} from '../schema/model';\nimport * as address from '../address/resolve';\nimport { compiledShape, type FixedMember } from '../schema/layout';\nimport * as schemaValue from '../schema/value';\nimport type { DependencyTracker } from './dependency';\nimport type { CanonicalState } from '../mutation/state';\nimport type { MutationSession } from '../mutation/session';\nimport * as tableOperations from '../mutation/operations/table';\nimport * as listOperations from '../mutation/operations/list';\nimport * as treeOperations from '../mutation/operations/tree';\nimport * as orderOperations from '../mutation/operations/order';\nimport * as sequence from '../order/sequence';\nimport * as tree from '../tree/topology';\nimport { profile } from '../profile';\nimport * as target from '../impact/target';\n\ndeclare const scopeValue: unique symbol;\ntype Scoped<N extends DocumentNode, W extends boolean, V = Infer<N>> = {\n readonly [scopeValue]?: readonly [node: N, writable: W, value: V];\n};\ntype ShapeAccess<S extends ObjectShape, W extends boolean> = W extends true\n ? { -readonly [K in keyof S]: Access<S[K], W> }\n : { readonly [K in keyof S]: Access<S[K], W> };\ntype MapAccess<K extends string, N extends ValueSchemaNode, W extends boolean> = {\n get(id: K): Access<N, W> | undefined;\n has(id: K): boolean;\n ids(): readonly K[];\n} & (W extends true\n ? {\n put(id: K, value: Infer<N>): void;\n remove(id: K): void;\n replace(value: Readonly<Record<K, Infer<N>>>): void;\n }\n : {});\ntype TableAccess<K extends string, N extends ValueSchemaNode, W extends boolean> = {\n get(id: K): Access<N, W> | undefined;\n has(id: K): boolean;\n ids(): readonly K[];\n} & (W extends true\n ? {\n create(id: K, value: Infer<N>, anchor?: DocumentAnchor<K>): void;\n create(\n entries: readonly { readonly id: K; readonly value: Infer<N> }[],\n anchor?: DocumentAnchor<K>\n ): void;\n remove(ids: K | readonly K[]): void;\n move(ids: K | readonly K[], anchor?: DocumentAnchor<K>): void;\n reorder(ids: readonly K[]): void;\n replace(value: {\n readonly ids: readonly K[];\n readonly byId: Readonly<Record<K, Infer<N>>>;\n }): void;\n replace(id: K, value: Infer<N>): void;\n }\n : {});\ntype ListAccess<T, W extends boolean> = {\n get(key: string): ReadonlyValue<T> | undefined;\n has(key: string): boolean;\n ids(): readonly string[];\n} & (W extends true\n ? {\n insert(value: ReadonlyValue<T>, anchor?: DocumentAnchor): void;\n remove(key: string): void;\n move(keys: string | readonly string[], anchor?: DocumentAnchor): void;\n reorder(keys: readonly string[]): void;\n replace(value: readonly ReadonlyValue<T>[]): void;\n replace(key: string, value: ReadonlyValue<T>): void;\n }\n : {});\ntype TreeAccess<T, O extends boolean, W extends boolean> = {\n rootId(): string | undefined;\n get(id: string): ReadonlyValue<T> | undefined;\n has(id: string): boolean;\n parent(id: string): string | undefined;\n children(id: string): readonly string[] | undefined;\n} & (W extends true\n ? {\n insert(\n id: string,\n value: O extends true ? ReadonlyValue<T> | undefined : ReadonlyValue<T>,\n position?: tree.TreePosition\n ): void;\n move(id: string, position?: tree.TreePosition): void;\n remove(id: string): void;\n replace(value: DocumentTreeValue<T, O>): void;\n replace(\n id: string,\n value: O extends true ? ReadonlyValue<T> | undefined : ReadonlyValue<T>\n ): void;\n }\n : {});\ntype NodeAccess<N extends DocumentNode, W extends boolean> =\n N extends FieldNode<infer T, boolean>\n ? ReadonlyValue<T>\n : N extends ObjectNode<infer S>\n ? ShapeAccess<S, W> & Scoped<N, W>\n : N extends VariantNode<infer Tag, infer V>\n ? {\n [K in keyof V & string]: ShapeAccess<V[K]['shape'], W> & {\n readonly [P in Tag]: K;\n } & Scoped<N, W, Extract<Infer<N>, Record<Tag, K>>>;\n }[keyof V & string]\n : N extends MapNode<infer V, infer K>\n ? MapAccess<K, V, W> & Scoped<N, W>\n : N extends TableNode<infer V, infer K>\n ? TableAccess<K, V, W> & Scoped<N, W>\n : N extends ListNode<infer T>\n ? ListAccess<T, W> & Scoped<N, W>\n : N extends TreeNode<infer T, infer O>\n ? TreeAccess<T, O, W> & Scoped<N, W>\n : never;\ntype Access<N extends DocumentNode, W extends boolean> = N extends { readonly optional: true }\n ? NodeAccess<N, W> | undefined\n : NodeAccess<N, W>;\ntype AccessNode<S extends Schema<unknown> | DocumentNode> =\n S extends Schema<unknown> ? SchemaNodeOf<S> : Extract<S, DocumentNode>;\nexport type Read<S extends Schema<unknown> | DocumentNode> = Access<AccessNode<S>, false>;\nexport type Draft<S extends Schema<unknown> | DocumentNode> = Access<AccessNode<S>, true>;\ntype Snapshot<T> = T extends {\n readonly [scopeValue]?: readonly [DocumentNode, boolean, infer V];\n}\n ? V\n : ReadonlyValue<T>;\ntype Target = {\n at?: DocumentAddress;\n parent?: Target;\n key: string;\n node: DocumentNode | undefined;\n value: unknown;\n generation: number;\n children:\n | { kind: 'fixed'; schema: DocumentNode; slots: (Target | undefined)[] }\n | { kind: 'dynamic'; keys: Map<string, Target> }\n | undefined;\n proxy: object | undefined;\n container?: address.ResolvedContainer | address.ResolvedTreeContainer;\n};\ntype Location = { readonly context: AccessContext; readonly target: Target };\nconst locations = new WeakMap<object, Location>();\nconst locationOf = (value: object): Location | undefined => locations.get(value);\nconst addressOf = (target: Target): DocumentAddress => {\n if (target.at) return target.at;\n profile.access('addresses');\n return (target.at = addressOf(target.parent!).concat(target.key));\n};\nexport type AccessContext = {\n readonly state: CanonicalState;\n /** Omitted for borrowed synchronous Draft and readers that must not escape. */\n readonly active?: () => boolean;\n readonly dependencies?: DependencyTracker;\n readonly session?: MutationSession;\n};\nconst assertActive = (context: AccessContext) => {\n if (context.active && !context.active()) throw new Error('Document access scope has expired.');\n};\nconst collect = (\n context: AccessContext,\n at: DocumentAddress,\n kind: 'value' | 'collection' = 'value',\n id?: string\n) => {\n context.dependencies?.record(\n kind === 'value' ? { kind, at } : { kind, at, ...(id === undefined ? {} : { id }) }\n );\n};\nconst collectTree = (\n context: AccessContext,\n at: DocumentAddress,\n selection: { readonly kind: 'root' } | { readonly kind: 'node'; readonly id: string }\n) => context.dependencies?.record(target.tree(at, selection));\nexport const snapshot = <T>(value: T): Snapshot<T> => {\n const location = value && typeof value === 'object' ? locationOf(value) : undefined;\n if (!location) return value as Snapshot<T>;\n const { context } = location;\n const at = addressOf(location.target);\n profile.access('snapshots');\n collect(context, at);\n const resolved = resolve(context, location.target);\n if (!resolved.node) throw new Error('The selected schema address no longer exists.');\n return schemaValue.copyValue(resolved.node, resolved.value) as Snapshot<T>;\n};\n/** Replace a member with its plain Infer value through the owning draft session. */\ntype ReplaceParentAccess = {\n readonly [scopeValue]?: readonly [\n Extract<DocumentNode, { readonly kind: 'object' | 'variant' }>,\n true,\n unknown,\n ];\n};\nexport const replace = <T extends object & ReplaceParentAccess, K extends keyof Snapshot<T>>(\n container: T,\n key: K,\n value: NoInfer<Snapshot<T>[K]>\n): void => {\n const location = locationOf(container);\n if (!location) throw new TypeError('replace requires scoped document access.');\n if (typeof key !== 'string') throw new TypeError('Document keys must be strings.');\n Reflect.set(container, key, value);\n};\nconst resolve = (context: AccessContext, target: Target): Target => {\n assertActive(context);\n const generation = context.session?.generation ?? 0;\n if (target.generation !== generation) {\n profile.access('resolutions');\n if (!target.parent && !target.at!.length) {\n target.node = context.state.schema;\n target.value = context.state.document;\n } else {\n const parent = target.parent && resolve(context, target.parent);\n const location = parent\n ? address.resolveChild(parent.node, parent.value, target.key)\n : address.resolveLocated(context.state.schema, context.state.document, target.at!);\n target.node =\n location?.node ??\n address.nodeAt(context.state.schema, addressOf(target), context.state.document);\n target.value =\n location && Object.hasOwn(location.parent, location.key)\n ? (location.parent as Record<string | number, unknown>)[location.key]\n : undefined;\n }\n target.generation = generation;\n }\n return target;\n};\n\nexport const createAccess = (context: AccessContext, initial: DocumentAddress = []): unknown => {\n profile.access('scopes');\n const mutable = (): MutationSession => {\n assertActive(context);\n if (!context.session) throw new TypeError('Cannot modify read-only document access.');\n return context.session;\n };\n const writableContainer = (\n target: Target,\n session: MutationSession\n ): address.ResolvedContainer => {\n if (target.container?.generation === session.generation && 'layout' in target.container)\n return target.container;\n return (target.container = session.bind(addressOf(target), target.node, target.value));\n };\n const childAt = (target: Target, key: string): DocumentAddress => {\n profile.access('addresses');\n return addressOf(target).concat(key);\n };\n const access = (target: Target): unknown => {\n if (target.proxy) return target.proxy;\n const proxy = new Proxy(target, handler);\n profile.access('proxies');\n locations.set(proxy, { context, target });\n target.proxy = proxy;\n return proxy;\n };\n const createTarget = (\n at: DocumentAddress | undefined,\n parent: Target | undefined,\n key: string\n ): Target => ({\n at,\n parent,\n key,\n node: undefined,\n value: undefined,\n generation: -1,\n children: undefined,\n proxy: undefined,\n });\n const childAccess = (\n target: Target,\n member: string | FixedMember,\n node: DocumentNode,\n value: unknown\n ) => {\n const key = typeof member === 'string' ? member : member.key;\n if (node.kind === 'field' || value === undefined) {\n if (context.dependencies) collect(context, childAt(target, key));\n return value;\n }\n let children = target.children;\n let child: Target;\n if (typeof member !== 'string') {\n if (children?.kind !== 'fixed' || children.schema !== target.node)\n children = {\n kind: 'fixed',\n schema: target.node!,\n slots: new Array(compiledShape(target.node!, target.value)!.members.size),\n };\n child = children.slots[member.slot] ??= createTarget(undefined, target, key);\n } else {\n if (children?.kind !== 'dynamic') children = { kind: 'dynamic', keys: new Map() };\n const retained = children.keys.get(key);\n child = retained ?? createTarget(undefined, target, key);\n if (!retained) children.keys.set(key, child);\n }\n target.children = children;\n if (child.generation === target.generation) return child.proxy;\n child.node = node;\n child.value = value;\n child.generation = target.generation;\n return access(child);\n };\n const collectionValue = (target: Target, node: DocumentNode) => {\n const current = resolve(context, target);\n if (current.node !== node || current.value === undefined)\n throw new TypeError('The collection method belongs to a replaced schema branch.');\n return current.value;\n };\n const writableCollection = (target: Target, node: DocumentNode): address.ResolvedContainer => {\n const session = mutable();\n collectionValue(target, node);\n return writableContainer(target, session);\n };\n const writableTree = (target: Target, node: DocumentNode): address.ResolvedTreeContainer => {\n const session = mutable();\n collectionValue(target, node);\n if (target.container?.generation === session.generation && !('layout' in target.container))\n return target.container;\n return (target.container = session.bindTree(addressOf(target), target.node, target.value));\n };\n const replaceCollection = (target: Target, node: DocumentNode, value: unknown) => {\n const session = mutable();\n collectionValue(target, node);\n session.replace(addressOf(target), value);\n };\n const mapMethod = (\n target: Target,\n property: string,\n node: Extract<DocumentNode, { kind: 'map' }>\n ): unknown => {\n if (property === 'ids')\n return () => {\n const current = collectionValue(target, node) as Record<string, unknown>;\n if (context.dependencies) collect(context, addressOf(target), 'collection');\n return Object.keys(current);\n };\n if (property === 'has')\n return (id: string) => {\n const current = collectionValue(target, node) as Record<string, unknown>;\n if (context.dependencies) collect(context, addressOf(target), 'collection', id);\n return Object.hasOwn(current, id);\n };\n if (property === 'get')\n return (id: string) => {\n const current = collectionValue(target, node) as Record<string, unknown>;\n if (context.dependencies) collect(context, addressOf(target), 'collection', id);\n if (!Object.hasOwn(current, id)) return undefined;\n if (node.value.kind === 'field') {\n if (context.dependencies) collect(context, childAt(target, id));\n return current[id];\n }\n return childAccess(target, id, node.value, current[id]);\n };\n if (property === 'put')\n return (id: string, value: unknown) => {\n const session = mutable();\n const writable = writableCollection(target, node);\n session.writeMember(writable, id, value, 'set');\n };\n if (property === 'remove')\n return (id: string) => {\n const session = mutable();\n const writable = writableCollection(target, node);\n session.writeMember(writable, id, undefined, 'remove');\n };\n if (property === 'replace') return (value: unknown) => replaceCollection(target, node, value);\n return undefined;\n };\n const orderedMethod = (\n target: Target,\n property: string,\n node: Extract<DocumentNode, { kind: 'table' | 'list' }>\n ): unknown => {\n const at = addressOf(target);\n if (property === 'ids')\n return () => {\n const current = collectionValue(target, node);\n collect(context, at, 'collection');\n return node.kind === 'table'\n ? [...(current as { ids: string[] }).ids]\n : (current as unknown[]).map(node.keyOf);\n };\n if (property === 'has')\n return (id: string) => {\n const current = collectionValue(target, node);\n collect(context, at, 'collection', id);\n return node.kind === 'table'\n ? Object.hasOwn((current as { byId: object }).byId, id)\n : sequence.indexedKeys(current as unknown[], node.keyOf).index(id) >= 0;\n };\n if (property === 'get')\n return (id: string) => {\n const current = collectionValue(target, node);\n collect(context, at, 'collection', id);\n const location = address.resolveChild(node, current, id);\n if (!location || !Object.hasOwn(location.parent, location.key)) return undefined;\n return childAccess(\n target,\n id,\n location.node,\n (location.parent as Record<string | number, unknown>)[location.key]\n );\n };\n if (property === 'move')\n return (ids: string | readonly string[], position?: DocumentAnchor) => {\n const writable = writableCollection(target, node);\n orderOperations.move(context.session!, writable, ids, position);\n };\n if (property === 'reorder')\n return (ids: readonly string[]) => {\n const writable = writableCollection(target, node);\n orderOperations.reorder(context.session!, writable, ids);\n };\n return undefined;\n };\n const tableMethod = (\n target: Target,\n property: string,\n node: Extract<DocumentNode, { kind: 'table' }>\n ): unknown => {\n if (property === 'create')\n return (\n input: string | readonly { id: string; value: unknown }[],\n valueOrPosition?: unknown,\n position?: DocumentAnchor\n ) => {\n const writable = writableCollection(target, node);\n tableOperations.create(\n context.session!,\n writable,\n Array.isArray(input) ? input : [{ id: input as string, value: valueOrPosition }],\n Array.isArray(input) ? (valueOrPosition as DocumentAnchor | undefined) : position\n );\n };\n if (property === 'remove')\n return (ids: string | readonly string[]) => {\n const writable = writableCollection(target, node);\n tableOperations.remove(context.session!, writable, typeof ids === 'string' ? [ids] : ids);\n };\n if (property === 'replace')\n return (...args: [unknown, unknown?]) => {\n const [valueOrId, value] = args;\n if (args.length === 1) return replaceCollection(target, node, valueOrId);\n const writable = writableCollection(target, node);\n tableOperations.replace(context.session!, writable, valueOrId as string, value);\n };\n return orderedMethod(target, property, node);\n };\n const listMethod = (\n target: Target,\n property: string,\n node: Extract<DocumentNode, { kind: 'list' }>\n ): unknown => {\n if (property === 'insert')\n return (value: unknown, position?: DocumentAnchor) => {\n const writable = writableCollection(target, node);\n listOperations.insert(context.session!, writable, value, position);\n };\n if (property === 'remove')\n return (id: string) => {\n const writable = writableCollection(target, node);\n listOperations.remove(context.session!, writable, id);\n };\n if (property === 'replace')\n return (...args: [unknown, unknown?]) => {\n const [valueOrId, value] = args;\n if (args.length === 1) return replaceCollection(target, node, valueOrId);\n const writable = writableCollection(target, node);\n listOperations.replace(context.session!, writable, valueOrId as string, value);\n };\n return orderedMethod(target, property, node);\n };\n const treeMethod = (\n target: Target,\n property: string,\n node: Extract<DocumentNode, { kind: 'tree' }>\n ): unknown => {\n const at = addressOf(target);\n if (property === 'insert')\n return (id: string, value: unknown, position?: tree.TreePosition) => {\n const writable = writableTree(target, node);\n treeOperations.insert(context.session!, writable, id, value, position);\n };\n if (property === 'remove')\n return (id: string) => {\n const writable = writableTree(target, node);\n treeOperations.remove(context.session!, writable, id);\n };\n if (property === 'move')\n return (id: string, position?: tree.TreePosition) => {\n const writable = writableTree(target, node);\n treeOperations.move(context.session!, writable, id, position);\n };\n if (property === 'replace')\n return (...args: [unknown, unknown?]) => {\n const [valueOrId, value] = args;\n if (args.length === 1) return replaceCollection(target, node, valueOrId);\n const writable = writableTree(target, node);\n treeOperations.replace(context.session!, writable, valueOrId as string, value);\n };\n const current = () => collectionValue(target, node) as tree.MutableTree;\n if (property === 'rootId')\n return () => {\n collectTree(context, at, { kind: 'root' });\n return current().rootId;\n };\n if (property === 'get')\n return (id: string) => {\n collectTree(context, at, { kind: 'node', id });\n const value = current();\n return tree.contains(value, id) ? value.nodes[id].value : undefined;\n };\n if (property === 'has')\n return (id: string) => {\n collectTree(context, at, { kind: 'node', id });\n return tree.contains(current(), id);\n };\n if (property === 'parent')\n return (id: string) => {\n collectTree(context, at, { kind: 'node', id });\n return tree.parent(current(), id);\n };\n if (property === 'children')\n return (id: string) => {\n collectTree(context, at, { kind: 'node', id });\n const children = tree.children(current(), id);\n return children ? [...children] : undefined;\n };\n return undefined;\n };\n const handler: ProxyHandler<Target> = {\n get: (target, property) => {\n const { node, value } = resolve(context, target);\n if (!node || value === undefined) return undefined;\n if (typeof property !== 'string') return undefined;\n if (node.kind === 'map') return mapMethod(target, property, node);\n if (node.kind === 'table') return tableMethod(target, property, node);\n if (node.kind === 'list') return listMethod(target, property, node);\n if (node.kind === 'tree') return treeMethod(target, property, node);\n if (node.kind === 'variant' && property === node.tag) {\n collect(context, childAt(target, property));\n return (value as Record<string, unknown>)[property];\n }\n const member = compiledShape(node, value)?.members.get(property);\n if (!member) return undefined;\n if (member.field) {\n if (context.dependencies) collect(context, childAt(target, property));\n return (value as Record<string, unknown>)[property];\n }\n return childAccess(\n target,\n node.kind === 'object' ? member : property,\n member.node,\n (value as Record<string, unknown>)[property]\n );\n },\n set: (target, property, value) => {\n const session = mutable(),\n { node } = resolve(context, target);\n if (\n typeof property !== 'string' ||\n !node ||\n (node.kind !== 'object' && node.kind !== 'variant')\n )\n throw new TypeError('Invalid structural assignment.');\n if (node.kind === 'variant' && node.tag === property)\n throw new TypeError('Variant discriminants are read-only.');\n session.assignMember(writableContainer(target, session), property, value);\n return true;\n },\n deleteProperty: (target, property) => {\n const session = mutable(),\n { node } = resolve(context, target);\n if (\n typeof property !== 'string' ||\n node?.kind === 'map' ||\n (node?.kind === 'variant' && node.tag === property)\n )\n throw new TypeError('Invalid structural deletion.');\n session.removeMember(writableContainer(target, session), property);\n return true;\n },\n has: (target, property) => {\n const { node, value } = resolve(context, target);\n if (typeof property !== 'string') return false;\n if (node?.kind === 'map') return false;\n collect(context, addressOf(target));\n return value !== undefined && Object.hasOwn(value as object, property);\n },\n ownKeys: target => {\n const { node, value } = resolve(context, target);\n if (node?.kind === 'map') return [];\n if (context.dependencies) collect(context, addressOf(target));\n return value && typeof value === 'object' ? Object.keys(value) : [];\n },\n getOwnPropertyDescriptor: (target, property) => {\n const { node, value } = resolve(context, target);\n if (node?.kind === 'map') return undefined;\n return value && Object.hasOwn(value as object, property)\n ? { enumerable: true, configurable: true }\n : undefined;\n },\n defineProperty: () => {\n assertActive(context);\n throw new TypeError('Use schema assignments.');\n },\n setPrototypeOf: () => {\n assertActive(context);\n throw new TypeError('Document prototypes are immutable.');\n },\n preventExtensions: () => {\n assertActive(context);\n throw new TypeError('Document access cannot be frozen.');\n },\n };\n const root = resolve(context, createTarget(initial, undefined, ''));\n if (!root.node || root.node.kind === 'field' || root.value === undefined) {\n if (context.dependencies) collect(context, initial);\n return root.value;\n }\n return access(root);\n};\n","import { checkKey } from './value';\nimport {\n collectionEntryNode,\n type DocumentAddress,\n type DocumentNode,\n type DocumentTreeNode,\n type FieldNode,\n type Infer,\n type ListNode,\n type MapNode,\n type ObjectNode,\n type ObjectSchema,\n type ObjectShape,\n type ReadonlyValue,\n type RootNodeOf,\n type SchemaNodeOf,\n type TableNode,\n type TreeNode,\n type VariantNode,\n type VariantShape,\n} from './model';\n\nexport type TreeTarget =\n | { readonly kind: 'root' }\n | { readonly kind: 'nodes' }\n | { readonly kind: 'node'; readonly id: string };\ntype TreeValueTarget = Exclude<TreeTarget, { readonly kind: 'nodes' }>;\ntype TreeCollectionTarget = Extract<TreeTarget, { readonly kind: 'nodes' }>;\n\nexport type CollectionSelector<TId extends string = string> = {\n readonly kind: 'collection';\n readonly schema: ObjectNode;\n readonly address: DocumentAddress;\n readonly tree?: TreeCollectionTarget;\n readonly __id?: TId;\n};\nexport type ValueSelector<TResult = unknown> = {\n readonly kind: 'value';\n readonly schema: ObjectNode;\n readonly address: DocumentAddress;\n readonly tree?: TreeValueTarget;\n readonly __value?: TResult;\n};\nexport type ImpactTarget<T = unknown> =\n | { readonly kind: 'value'; readonly at: DocumentAddress; readonly tree?: TreeValueTarget }\n | ValueSelector<T>\n | {\n readonly kind: 'collection';\n readonly at: DocumentAddress;\n readonly id?: string;\n }\n | CollectionSelector<string>;\ndeclare const pathValue: unique symbol;\ndeclare const collectionEntry: unique symbol;\ndeclare const collectionKey: unique symbol;\ntype PathMarker<TValue> = { readonly [pathValue]: TValue };\nexport type PathValueOf<T> = T extends { readonly [pathValue]: infer TValue } ? TValue : never;\n\ntype Or<A extends boolean, B extends boolean> = A extends true ? true : B;\ntype NodeAbsent<N extends DocumentNode, ParentAbsent extends boolean> = Or<\n ParentAbsent,\n N extends { readonly optional: true } ? true : false\n>;\ntype PathResult<N extends DocumentNode, ParentAbsent extends boolean> =\n Infer<N> | (ParentAbsent extends true ? undefined : never);\n\ntype SchemaPathFor<\n S extends ObjectShape = ObjectShape,\n TValue = unknown,\n Absent extends boolean = false,\n> = {\n readonly [K in keyof S]: PathValue<S[K], Absent>;\n} & PathMarker<TValue | (Absent extends true ? undefined : never)>;\n\nexport type SchemaPath<S extends ObjectSchema<object> = ObjectSchema<object>> =\n RootNodeOf<S> extends ObjectNode<infer Shape> ? SchemaPathFor<Shape, Infer<S>> : never;\nexport type PathPick<S extends ObjectSchema<object> = ObjectSchema<object>> = (\n path: SchemaPath<S>\n) => PathMarker<unknown>;\n\ntype VariantKeys<V extends VariantShape> = {\n [K in keyof V & string]: keyof (V[K] extends ObjectNode<infer S> ? S : {});\n}[keyof V & string] &\n string;\ntype VariantFieldMissing<V extends VariantShape, K extends string> = {\n [P in keyof V & string]: V[P] extends ObjectNode<infer S> ? (K extends keyof S ? never : P) : P;\n}[keyof V & string] extends never\n ? false\n : true;\ntype VariantFieldPath<V extends VariantShape, K extends string, Absent extends boolean> = {\n [P in keyof V & string]: V[P] extends ObjectNode<infer S>\n ? K extends keyof S\n ? PathValue<S[K], Or<Absent, VariantFieldMissing<V, K>>>\n : never\n : never;\n}[keyof V & string];\ntype VariantPath<T extends string, V extends VariantShape, TValue, Absent extends boolean> = {\n readonly [K in VariantKeys<V>]: VariantFieldPath<V, K, Absent>;\n} & {\n readonly [K in T]: PathMarker<(keyof V & string) | (Absent extends true ? undefined : never)>;\n} & PathMarker<TValue>;\nexport type CollectionPath<\n K extends string = string,\n TValue = unknown,\n TEntry = unknown,\n TItem = PathMarker<TEntry | undefined>,\n> = PathMarker<TValue> & {\n item(id: K): TItem;\n readonly [collectionEntry]: TEntry;\n readonly [collectionKey]: K;\n};\ntype TreeNodesPath<TValue, ValueOptional extends boolean> = CollectionPath<\n string,\n Readonly<Record<string, DocumentTreeNode<TValue, ValueOptional>>>,\n DocumentTreeNode<TValue, ValueOptional>,\n PathMarker<DocumentTreeNode<TValue, ValueOptional> | undefined>\n>;\ntype TreePath<TValue, ValueOptional extends boolean, TValueResult> = PathMarker<TValueResult> & {\n readonly rootId: PathMarker<string | undefined>;\n readonly nodes: TreeNodesPath<TValue, ValueOptional>;\n};\n\ntype PathValue<N extends DocumentNode, ParentAbsent extends boolean = false> =\n N extends ObjectNode<infer S>\n ? SchemaPathFor<S, PathResult<N, ParentAbsent>, NodeAbsent<N, ParentAbsent>>\n : N extends VariantNode<infer TTag, infer V>\n ? VariantPath<TTag, V, PathResult<N, ParentAbsent>, NodeAbsent<N, ParentAbsent>>\n : N extends TableNode<infer V, infer K>\n ? CollectionPath<K, PathResult<N, ParentAbsent>, Infer<V>, PathValue<V, true>>\n : N extends MapNode<infer V, infer K>\n ? CollectionPath<K, PathResult<N, ParentAbsent>, Infer<V>, PathValue<V, true>>\n : N extends ListNode<infer I>\n ? CollectionPath<\n string,\n PathResult<N, ParentAbsent>,\n ReadonlyValue<I>,\n PathMarker<ReadonlyValue<I> | undefined>\n >\n : N extends TreeNode<infer T, infer O>\n ? TreePath<T, O, PathResult<N, ParentAbsent>>\n : PathMarker<PathResult<N, ParentAbsent>>;\ntype CollectionInfo<T> = T extends {\n readonly [collectionEntry]: infer TEntry;\n readonly [collectionKey]: infer K extends string;\n}\n ? { readonly id: K; readonly entry: TEntry }\n : never;\nexport type CollectionId<T> =\n CollectionInfo<T> extends { readonly id: infer TId extends string } ? TId : string;\nexport type CollectionEntry<T> =\n CollectionInfo<T> extends { readonly entry: infer TEntry } ? TEntry : unknown;\n\nconst paths = new WeakMap<\n object,\n {\n readonly address: DocumentAddress;\n readonly nodes: readonly DocumentNode[];\n readonly owner: object;\n readonly tree?: TreeTarget;\n }\n>();\n\nconst pathProxy = (\n nodes: readonly DocumentNode[],\n address: DocumentAddress,\n owner: object,\n treeSelection?: TreeTarget\n): object => {\n const proxy = new Proxy(\n {},\n {\n get: (_target, property: string | symbol) => {\n if (typeof property !== 'string') return undefined;\n const trees = nodes.every(node => node.kind === 'tree');\n if (!treeSelection && trees && property === 'rootId')\n return pathProxy(nodes, address, owner, { kind: 'root' });\n if (!treeSelection && trees && property === 'nodes')\n return pathProxy(nodes, address, owner, { kind: 'nodes' });\n if (treeSelection?.kind === 'nodes' && property === 'item')\n return (id: string) => {\n if (typeof id !== 'string') throw new TypeError('Tree node keys must be strings.');\n return pathProxy(nodes, address, owner, { kind: 'node', id });\n };\n if (treeSelection) throw new TypeError(`Invalid tree path segment: ${property}`);\n const collection = nodes.every(node => collectionEntryNode(node) !== undefined);\n if (collection && property === 'item')\n return (id: string) => {\n if (typeof id !== 'string') throw new TypeError('Collection keys must be strings.');\n for (const node of nodes)\n if (node.kind === 'table' || node.kind === 'map') {\n const invalid = checkKey(node.key, id, [...address, id]);\n if (invalid) throw new TypeError(invalid.message);\n }\n return pathProxy(\n nodes.map(node => collectionEntryNode(node)!),\n [...address, id],\n owner\n );\n };\n const children = nodes.flatMap(node => {\n if (node.kind === 'object')\n return Object.hasOwn(node.shape, property) ? [node.shape[property]] : [];\n if (node.kind !== 'variant') return [];\n if (property === node.tag)\n return [Object.freeze({ kind: 'field' as const }) as FieldNode<string>];\n return Object.values(node.variants).flatMap(branch =>\n Object.hasOwn(branch.shape, property) ? [branch.shape[property]] : []\n );\n });\n if (!children.length) throw new TypeError(`Invalid schema path segment: ${property}`);\n return pathProxy(children, [...address, property], owner);\n },\n }\n );\n paths.set(proxy, { nodes, address, owner, ...(treeSelection ? { tree: treeSelection } : {}) });\n return proxy;\n};\n\nexport const compilePath = <S extends ObjectSchema<object>>(\n owner: RootNodeOf<S>,\n kind: 'collection' | 'value' | 'auto',\n pick: (path: SchemaPath<S>) => unknown\n): CollectionSelector | ValueSelector => {\n const scope = {};\n const value = pick(pathProxy([owner], [], scope) as SchemaPath<S>);\n const selected = typeof value === 'object' && value !== null ? paths.get(value) : undefined;\n if (!selected || selected.owner !== scope)\n throw new TypeError('Selector must return a path from its callback.');\n const collection =\n selected.tree?.kind === 'nodes' ||\n selected.nodes.every(node => collectionEntryNode(node) !== undefined);\n if (kind === 'collection' && !collection)\n throw new TypeError('Collection selectors require a map, table, list or tree nodes path.');\n const resolvedKind = kind === 'auto' ? (collection ? 'collection' : 'value') : kind;\n const result = Object.freeze({\n kind: resolvedKind,\n schema: owner,\n address: Object.freeze([...selected.address]),\n ...(selected.tree ? { tree: Object.freeze({ ...selected.tree }) } : {}),\n }) as CollectionSelector | ValueSelector;\n return result;\n};\n","import { profile } from '../profile';\nimport type { DocumentAddress } from '../schema/model';\n\nexport const contains = (parent: DocumentAddress, child: DocumentAddress): boolean => {\n profile.address.prefixComparison();\n if (parent.length > child.length) return false;\n for (let index = 0; index < parent.length; index += 1) {\n profile.address.segmentCompared();\n if (parent[index] !== child[index]) return false;\n }\n return true;\n};\n","import type { ObjectSchema, RootNodeOf } from './schema/model';\nimport type {\n CollectionId,\n CollectionPath,\n CollectionSelector,\n ImpactTarget,\n PathPick,\n SchemaPath,\n} from './schema/path';\nimport { compilePath } from './schema/path';\nimport type { ChangeSet } from './changes';\nimport { AddressIndex } from './address/index';\nimport * as relation from './address/relation';\nimport * as target from './impact/target';\nimport { profile } from './profile';\n\nexport type CollectionImpact<K> =\n | { readonly kind: 'reset' }\n | {\n readonly kind: 'incremental';\n readonly added: ReadonlySet<K>;\n readonly removed: ReadonlySet<K>;\n readonly updated: ReadonlySet<K>;\n readonly orderChanged: boolean;\n };\nexport type DocumentImpact<S extends ObjectSchema<object>> = {\n readonly kind: 'incremental' | 'reset';\n affects(pick: PathPick<S>): boolean;\n collection<P extends CollectionPath>(\n pick: (path: SchemaPath<S>) => P\n ): CollectionImpact<CollectionId<P>>;\n};\nexport const createImpact = <S extends ObjectSchema<object>>(\n schema: RootNodeOf<S>,\n changes: ChangeSet\n): DocumentImpact<S> => {\n const reset = changes.changes.some(change => change.kind === 'reset');\n let values: AddressIndex<true> | undefined;\n let orders: AddressIndex<true> | undefined;\n const index = () => {\n if (!values) {\n profile.impact.index();\n values = new AddressIndex();\n orders = new AddressIndex();\n target.visitChangedLocations(\n changes,\n at => values!.add(at, true),\n at => orders!.add(at, true)\n );\n }\n return values;\n };\n const cache = new Map<string, CollectionImpact<string>>();\n const affects = (value: ImpactTarget): boolean => {\n profile.impact.affects();\n if (!target.belongs(value, schema)) return false;\n if (reset) return true;\n return target.affected(value, index(), orders!);\n };\n const collection = (selector: CollectionSelector): CollectionImpact<string> => {\n if (selector.schema !== schema)\n throw new TypeError('Collection belongs to another root model.');\n const key = JSON.stringify(target.indexedAddress(selector)),\n cached = cache.get(key);\n if (cached) return cached;\n if (reset) {\n const result = { kind: 'reset' } as const;\n cache.set(key, result);\n return result;\n }\n const at = selector.address;\n const tree = selector.tree;\n const added = new Set<string>(),\n removed = new Set<string>(),\n updated = new Set<string>();\n let orderChanged = false;\n for (const change of changes.changes) {\n if (change.kind === 'reset') continue;\n if (change.kind === 'members') {\n if (change.at.length < at.length && relation.contains(change.at, at)) {\n if (change.members.some(member => member.key === at[change.at.length])) {\n const result = { kind: 'reset' } as const;\n cache.set(key, result);\n return result;\n }\n } else if (relation.contains(at, change.at)) {\n if (change.at.length === at.length) {\n if (change.order) {\n const positions = new Map(change.order.after.map((id, i) => [id, i]));\n let previous = -1;\n for (const id of change.order.before) {\n const position = positions.get(id);\n if (position === undefined) continue;\n if (position < previous) orderChanged = true;\n previous = position;\n }\n }\n for (const member of change.members) {\n if (member.kind === 'added') added.add(member.key);\n else if (member.kind === 'removed') removed.add(member.key);\n else updated.add(member.key);\n }\n } else updated.add(change.at[at.length]);\n }\n continue;\n }\n if (change.kind === 'tree' && relation.contains(change.at, at)) {\n if (\n tree?.kind === 'nodes' &&\n change.at.length === at.length &&\n relation.contains(at, change.at)\n ) {\n for (const node of change.nodes) {\n if (node.kind === 'added') added.add(node.id);\n else if (node.kind === 'removed') removed.add(node.id);\n else updated.add(node.id);\n }\n continue;\n }\n const result = { kind: 'reset' } as const;\n cache.set(key, result);\n return result;\n }\n if (!relation.contains(at, change.at)) continue;\n if (change.at.length === at.length) continue;\n const id = change.at[at.length];\n updated.add(id);\n }\n added.forEach(id => updated.delete(id));\n removed.forEach(id => updated.delete(id));\n const result = { kind: 'incremental', added, removed, updated, orderChanged } as const;\n cache.set(key, result);\n return result;\n };\n const impact: DocumentImpact<S> = Object.freeze({\n kind: reset ? 'reset' : 'incremental',\n affects: (pick: PathPick<S>) => affects(compilePath<S>(schema, 'value', pick)),\n collection: <P extends CollectionPath>(pick: (path: SchemaPath<S>) => P) =>\n collection(\n compilePath<S>(schema, 'collection', pick) as CollectionSelector\n ) as CollectionImpact<CollectionId<P>>,\n });\n return impact;\n};\n","import type { DocumentAddress, Infer, ObjectSchema } from '../schema/model';\nimport type { PathPick } from '../schema/path';\nimport type { ChangeSet } from '../changes';\nimport type { DocumentImpact } from '../impact';\nimport type { Draft } from '../access/scope';\nimport type { MutationIssue } from '../mutation/issue';\nimport type { Readable, Unsubscribe } from '../readable';\nexport type { Unsubscribe } from '../readable';\nexport type Synchronous<T> = T extends PromiseLike<unknown> ? never : T;\nexport type CommitSource = 'local' | 'system' | 'history' | 'remote';\nexport class DocumentReentrancyError extends Error {\n constructor() {\n super('Document writes cannot be re-entered during an update or notification.');\n this.name = 'DocumentReentrancyError';\n }\n}\nexport class DocumentDisposedError extends Error {\n constructor() {\n super('Doxum runtime has been disposed.');\n this.name = 'DocumentDisposedError';\n }\n}\nexport type DiagnosticInput = {\n readonly code: string;\n readonly message: string;\n readonly address?: DocumentAddress;\n};\nexport type DocumentDiagnostic = DiagnosticInput & { readonly source: 'application' };\nexport type DocumentProblem = DocumentDiagnostic | MutationIssue;\nexport class TransactionRejected extends Error {\n readonly issues: readonly DocumentDiagnostic[];\n constructor(input: DiagnosticInput | readonly DiagnosticInput[]) {\n super('Document update rejected.');\n this.name = 'TransactionRejected';\n const issues: readonly DiagnosticInput[] = Array.isArray(input)\n ? input\n : [input as DiagnosticInput];\n this.issues = Object.freeze(\n issues.map(issue =>\n Object.freeze({\n code: issue.code,\n message: issue.message,\n source: 'application' as const,\n ...(issue.address === undefined ? {} : { address: Object.freeze([...issue.address]) }),\n })\n )\n );\n }\n}\nexport type DocumentCommit<S extends ObjectSchema<object>> = {\n readonly revision: number;\n readonly source: CommitSource;\n readonly changes: ChangeSet;\n readonly impact: DocumentImpact<S>;\n};\nexport type ObserverError = {\n readonly phase: 'processor' | 'flush' | 'listener';\n readonly error: unknown;\n};\nexport type TransactionResult<V, C> =\n | {\n readonly status: 'committed';\n readonly value: V;\n readonly commit: C;\n readonly observerErrors: readonly ObserverError[];\n }\n | { readonly status: 'unchanged'; readonly value: V; readonly revision: number }\n | {\n readonly status: 'rejected';\n readonly issues: readonly DocumentProblem[];\n readonly revision: number;\n };\nexport type OperationResult<C> =\n | {\n readonly status: 'committed';\n readonly commit: C;\n readonly observerErrors: readonly ObserverError[];\n }\n | { readonly status: 'unchanged'; readonly revision: number }\n | {\n readonly status: 'rejected';\n readonly issues: readonly MutationIssue[];\n readonly revision: number;\n };\nexport type HistoryState = { readonly undoDepth: number; readonly redoDepth: number };\nexport type LocalHistory<C> = Readable<HistoryState> & {\n undo(): OperationResult<C>;\n redo(): OperationResult<C>;\n clear(): void;\n group(): { end(): void; cancel(): OperationResult<C> };\n};\nexport type CommitListener<S extends ObjectSchema<object>> = (commit: DocumentCommit<S>) => void;\nexport type ReadonlyDocument<S extends ObjectSchema<object>> = {\n revision(): number;\n subscribe(listener: CommitListener<S>): Unsubscribe;\n subscribe(\n pick: PathPick<S> | readonly [PathPick<S>, ...PathPick<S>[]],\n listener: CommitListener<S>\n ): Unsubscribe;\n};\nexport type DocumentRuntime<S extends ObjectSchema<object>> = ReadonlyDocument<S> & {\n readonly schema: S;\n readonly(): ReadonlyDocument<S>;\n update<V>(\n run: (draft: Draft<S>) => Synchronous<V>,\n options?: {\n readonly source?: Extract<CommitSource, 'local' | 'system'>;\n readonly history?: boolean;\n }\n ): TransactionResult<V, DocumentCommit<S>>;\n apply(\n changes: unknown,\n options:\n | {\n readonly expectedRevision: number;\n readonly source?: Extract<CommitSource, 'local' | 'system'>;\n readonly history?: boolean;\n }\n | {\n readonly expectedRevision: number;\n readonly source: 'remote';\n readonly history?: never;\n }\n ): OperationResult<DocumentCommit<S>>;\n replace(\n value: Infer<S>,\n options?: { readonly source?: Extract<CommitSource, 'system' | 'remote'> }\n ): OperationResult<DocumentCommit<S>>;\n snapshot(): Infer<S>;\n readonly history: LocalHistory<DocumentCommit<S>>;\n dispose(): void;\n};\n","import type { ChangeSet, ChangeDirection } from './changes';\nimport type {\n HistoryState,\n LocalHistory,\n ObserverError,\n OperationResult,\n} from './runtime/contract';\nimport { DocumentDisposedError } from './runtime/contract';\n\ntype Entry = { readonly batches: ChangeSet[] };\ntype Group = { entry?: Entry; readonly undos: Entry[]; readonly redos: Entry[] };\n\nexport const createHistory = <TCommit>(input: {\n readonly capacity: number;\n readonly apply: (\n changes: readonly ChangeSet[],\n direction: ChangeDirection\n ) => OperationResult<TCommit>;\n readonly revision: () => number;\n readonly assertIdle: () => void;\n readonly notify: (run: () => readonly ObserverError[]) => readonly ObserverError[];\n}) => {\n let undos: Entry[] = [];\n let redos: Entry[] = [];\n const listeners = new Set<() => void>();\n let state: HistoryState = Object.freeze({ undoDepth: 0, redoDepth: 0 });\n let revision = 0;\n let pending = false;\n let disposed = false;\n let group: Group | undefined;\n const unchanged = (): OperationResult<TCommit> => ({\n status: 'unchanged',\n revision: input.revision(),\n });\n const publish = () => {\n if (state.undoDepth === undos.length && state.redoDepth === redos.length) return;\n state = Object.freeze({ undoDepth: undos.length, redoDepth: redos.length });\n revision++;\n pending = true;\n };\n const flush = (): readonly ObserverError[] => {\n if (!pending) return [];\n pending = false;\n const errors: ObserverError[] = [];\n for (const listener of [...listeners]) {\n if (!listeners.has(listener)) continue;\n try {\n listener();\n } catch (error) {\n errors.push({ phase: 'listener', error });\n }\n }\n return errors;\n };\n const clear = () => {\n group = undefined;\n undos.length = redos.length = 0;\n publish();\n };\n const travel = (direction: 'undo' | 'redo' | 'cancel'): OperationResult<TCommit> => {\n input.assertIdle();\n const from = direction === 'redo' ? redos : undos;\n const to = direction === 'redo' ? undos : redos;\n const previousUndos = undos;\n const previousRedos = redos;\n const entry = direction === 'cancel' ? from.at(-1) : from.pop();\n if (!entry) return unchanged();\n if (direction === 'cancel') {\n if (!group || group.entry !== entry)\n throw new Error('History group no longer owns its entry.');\n undos = group.undos;\n redos = group.redos;\n } else to.push(entry);\n let committed = false;\n try {\n const changes = direction === 'redo' ? entry.batches : entry.batches.slice().reverse();\n const result = input.apply(changes, direction === 'redo' ? 'forward' : 'backward');\n committed = result.status !== 'rejected';\n if (committed && direction === 'cancel') group = undefined;\n if (result.status === 'unchanged') {\n publish();\n const errors = input.notify(flush);\n if (errors.length)\n throw new AggregateError(\n errors.map(entry => entry.error),\n 'History listeners failed.'\n );\n }\n return result;\n } finally {\n if (!committed) {\n if (direction === 'cancel') {\n undos = previousUndos;\n redos = previousRedos;\n } else {\n to.pop();\n from.push(entry);\n }\n }\n }\n };\n const api: LocalHistory<TCommit> = {\n current: () => state,\n revision: () => revision,\n subscribe: listener => {\n if (disposed) throw new DocumentDisposedError();\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n undo: () => {\n input.assertIdle();\n group = undefined;\n return travel('undo');\n },\n redo: () => {\n input.assertIdle();\n group = undefined;\n return travel('redo');\n },\n clear: () => {\n input.assertIdle();\n clear();\n const errors = input.notify(flush);\n if (errors.length)\n throw new AggregateError(\n errors.map(entry => entry.error),\n 'History listeners failed.'\n );\n },\n group: () => {\n input.assertIdle();\n if (group) throw new Error('A history group is already active.');\n if (input.capacity <= 0) throw new Error('History is disabled.');\n const scope: Group = { undos: undos.slice(), redos: redos.slice() };\n group = scope;\n return Object.freeze({\n end: () => {\n input.assertIdle();\n if (group === scope) group = undefined;\n },\n cancel: () => {\n input.assertIdle();\n if (group !== scope) return unchanged();\n if (!scope.entry) {\n group = undefined;\n return unchanged();\n }\n const result = travel('cancel');\n if (result.status !== 'rejected') group = undefined;\n return result;\n },\n });\n },\n };\n return {\n api,\n record: (batch: ChangeSet) => {\n if (input.capacity <= 0) return;\n if (group?.entry) group.entry.batches.push(batch);\n else {\n const entry: Entry = { batches: [batch] };\n undos.push(entry);\n if (group) group.entry = entry;\n if (undos.length > input.capacity) undos.shift();\n }\n redos.length = 0;\n publish();\n },\n publish,\n flush,\n endGroup: () => {\n group = undefined;\n },\n invalidate: clear,\n dispose: () => {\n disposed = true;\n listeners.clear();\n clear();\n pending = false;\n },\n };\n};\n","import type { DocumentNode, ObjectNode } from '../schema/model';\nimport * as sequence from '../order/sequence';\nimport { installOwn } from '../value/record';\n\nexport type CanonicalState = { schema: ObjectNode; document: unknown };\n\n/** Install validated values, or captured before values during rollback. */\nexport const installMember = (\n parent: Record<string, unknown> | unknown[],\n key: string | number,\n present: boolean,\n value: unknown\n): void => {\n if (Array.isArray(parent)) {\n const index = Number(key);\n if (present) {\n if (index < 0) sequence.insert(parent, parent.length, value);\n else parent[index] = value;\n } else if (index >= 0) sequence.remove(parent, index);\n } else installOwn(parent, key, present, value);\n};\n\nexport const orderOf = (node: DocumentNode, value: unknown): string[] => {\n if (node.kind === 'list')\n return sequence.toArray(sequence.indexedKeys(value as unknown[], node.keyOf));\n if (node.kind === 'table') return [...(value as { ids: string[] }).ids];\n throw new Error('Order requires a table or list.');\n};\n\nexport const installOrder = (\n node: DocumentNode,\n value: unknown,\n order: readonly string[]\n): void => {\n if (node.kind === 'list') sequence.install(value as unknown[], node.keyOf, order);\n else if (node.kind === 'table') (value as { ids: string[] }).ids = [...order];\n else throw new Error('Order requires a table or list.');\n};\n","import type { Change, ChangeSet, MemberChange } from '../changes';\nimport type { DocumentAddress, DocumentNode } from '../schema/model';\nimport { AddressIndex } from '../address/index';\nimport * as address from '../address/resolve';\nimport * as relation from '../address/relation';\nimport * as sequence from '../order/sequence';\nimport { profile } from '../profile';\nimport { compiledShape, type CompiledMember, type FixedLayout } from '../schema/layout';\nimport * as schemaValue from '../schema/value';\nimport type { MutableTree, MutableTreeNode } from '../tree/topology';\nimport * as changeSet from './changes';\nimport * as state from './state';\ntype MemberFact = { key: string; node: DocumentNode; present: boolean; value: unknown };\ntype MemberGroup = {\n kind: 'members';\n at: DocumentAddress;\n node: DocumentNode;\n parent: Record<string, unknown> | unknown[];\n value: unknown;\n order?: readonly string[];\n} & (\n | { layout: 'fixed'; definitions: FixedLayout['members']; members: (MemberFact | undefined)[] }\n | { layout: 'dynamic'; members: Map<string, MemberFact> | undefined }\n);\ntype TreeFact = {\n kind: 'tree';\n at: DocumentAddress;\n before: string | null;\n nodes: Map<string, MutableTreeNode | undefined>;\n};\ntype Fact = MemberGroup | TreeFact;\ntype RestoreFact =\n | { kind: 'order'; at: DocumentAddress; group: MemberGroup }\n | TreeFact\n | { kind: 'member'; at: DocumentAddress; group: MemberGroup; member: MemberFact };\nconst firstMember = (group: MemberGroup, key: string): MemberFact | undefined => {\n if (group.layout === 'dynamic') return group.members?.get(key);\n const member = group.definitions.get(key);\n return member && group.members[member.slot];\n};\n\nconst forgetMember = (group: MemberGroup, key: string): void => {\n if (group.layout === 'dynamic') group.members?.delete(key);\n else {\n const definition = group.definitions.get(key);\n if (definition) group.members[definition.slot] = undefined;\n }\n};\nconst emptyGroup = (group: MemberGroup): boolean =>\n !group.order && (group.layout === 'fixed' ? !group.members.some(Boolean) : !group.members?.size);\n\nconst transition = (\n node: DocumentNode,\n key: string,\n beforePresent: boolean,\n before: unknown,\n afterPresent: boolean,\n after: unknown\n): MemberChange | undefined => {\n if (beforePresent === afterPresent && (!beforePresent || Object.is(before, after))) return;\n if (\n node.kind !== 'field' &&\n beforePresent === afterPresent &&\n schemaValue.equalValue(node, before, after)\n )\n return;\n const value = afterPresent\n ? node.kind === 'field'\n ? after\n : schemaValue.copyValue(node, after)\n : undefined;\n profile.recorder('transitions');\n return !beforePresent\n ? { key, kind: 'added', after: value }\n : !afterPresent\n ? { key, kind: 'removed', before }\n : { key, kind: 'updated', before, after: value };\n};\n\nconst publishMembers = (\n changes: Change[],\n at: DocumentAddress,\n members: MemberChange[],\n order?: { before: readonly string[]; after: readonly string[] }\n): void => {\n if (!members.length && !order) return;\n for (let i = 1; i < members.length; i++)\n if (members[i - 1].key > members[i].key) {\n members.sort((a, b) => lexical(a.key, b.key));\n break;\n }\n changes.push(order ? { kind: 'members', at, members, order } : { kind: 'members', at, members });\n};\n\n/** Diff only the captured subtree; this algorithm has no recorder or session state. */\nconst diffMember = (\n changes: Change[],\n members: MemberChange[],\n node: DocumentNode,\n at: DocumentAddress,\n key: string,\n beforePresent: boolean,\n before: unknown,\n afterPresent: boolean,\n after: unknown\n): void => {\n if (beforePresent === afterPresent && (!beforePresent || Object.is(before, after))) return;\n if (beforePresent && afterPresent && before !== undefined && after !== undefined) {\n const sameShape =\n node.kind === 'object' ||\n (node.kind === 'variant' &&\n (before as Record<string, unknown>)[node.tag] ===\n (after as Record<string, unknown>)[node.tag]);\n if (sameShape) {\n const left = before as Record<string, unknown>,\n right = after as typeof left;\n const childAt = at.concat(key);\n const children: MemberChange[] = [];\n for (const [child, definition] of compiledShape(node, before)!.members)\n diffMember(\n changes,\n children,\n definition.node,\n childAt,\n child,\n Object.hasOwn(left, child),\n left[child],\n Object.hasOwn(right, child),\n right[child]\n );\n publishMembers(changes, childAt, children);\n return;\n }\n if (node.kind === 'map' || node.kind === 'table') {\n const a = before as Record<string, unknown>,\n b = after as typeof a;\n const left = (node.kind === 'table' ? a.byId : a) as Record<string, unknown>;\n const right = (node.kind === 'table' ? b.byId : b) as typeof left;\n const childAt = at.concat(key);\n const children: MemberChange[] = [];\n for (const id of Object.keys(left))\n diffMember(\n changes,\n children,\n node.value,\n childAt,\n id,\n true,\n left[id],\n Object.hasOwn(right, id),\n right[id]\n );\n for (const id of Object.keys(right))\n if (!Object.hasOwn(left, id))\n diffMember(changes, children, node.value, childAt, id, false, undefined, true, right[id]);\n let order: { before: readonly string[]; after: readonly string[] } | undefined;\n if (node.kind === 'table' && !sequence.equal(a.ids as string[], b.ids as string[])) {\n profile.recorder('publishedOrderItems', (b.ids as string[]).length);\n order = { before: a.ids as string[], after: [...(b.ids as string[])] };\n }\n publishMembers(changes, childAt, children, order);\n return;\n }\n }\n const member = transition(node, key, beforePresent, before, afterPresent, after);\n if (member) members.push(member);\n};\nconst restore = (fact: RestoreFact, schema: DocumentNode, root: unknown, skip = 0): unknown => {\n const at = skip ? fact.at.slice(skip) : fact.at;\n if (fact.kind === 'member') {\n const member = fact.member;\n const value = member.present ? schemaValue.copyValue(member.node, member.value) : undefined;\n if (!at.length) return value;\n const location = address.resolveLocated(schema, root, at);\n if (!location) throw new Error('Cannot restore an unresolved member.');\n state.installMember(location.parent, location.key, member.present, value);\n return root;\n }\n const location = address.resolveValue(schema, root, at);\n if (!location) throw new Error('Cannot restore an unresolved subtree.');\n if (fact.kind === 'order') state.installOrder(location.node, location.value, fact.group.order!);\n else {\n const tree = location.value as MutableTree;\n if (fact.before === null) delete tree.rootId;\n else tree.rootId = fact.before;\n for (const [id, node] of fact.nodes)\n state.installMember(\n tree.nodes,\n id,\n node !== undefined,\n node && schemaValue.copyTreeNode(node)\n );\n }\n return root;\n};\n\nconst reconstructBefore = (\n node: DocumentNode,\n current: unknown,\n records: readonly RestoreFact[],\n offset: number\n): unknown => {\n let before = schemaValue.copyValue(node, current);\n for (let i = records.length - 1; i >= 0; i--)\n if (records[i].kind !== 'order') before = restore(records[i], node, before, offset);\n for (const record of records)\n if (record.kind === 'order') before = restore(record, node, before, offset);\n return before;\n};\n\nconst sealMembers = (fact: MemberGroup, changes: Change[]): void => {\n const members: MemberChange[] = [];\n for (const member of fact.members?.values() ?? []) {\n if (!member) continue;\n const key = address.memberKey(fact, member.key);\n const present = Object.hasOwn(fact.parent, key);\n const value = (fact.parent as Record<string | number, unknown>)[key];\n if (member.node.kind === 'field') {\n const change = transition(\n member.node,\n member.key,\n member.present,\n member.value,\n present,\n value\n );\n if (change) members.push(change);\n } else\n diffMember(\n changes,\n members,\n member.node,\n fact.at,\n member.key,\n member.present,\n member.value,\n present,\n value\n );\n }\n let order: { before: readonly string[]; after: readonly string[] } | undefined;\n if (fact.order) {\n const current =\n fact.node.kind === 'list'\n ? sequence.indexedKeys(fact.value as unknown[], fact.node.keyOf)\n : (fact.value as { ids: string[] }).ids;\n if (!sequence.equal(fact.order, current)) {\n const after = state.orderOf(fact.node, fact.value);\n profile.recorder('publishedOrderItems', after.length);\n order = { before: fact.order, after };\n }\n }\n publishMembers(changes, fact.at, members, order);\n};\n\nconst sealTree = (fact: TreeFact, canonical: state.CanonicalState, changes: Change[]): void => {\n const location = address.resolveValue(canonical.schema, canonical.document, fact.at);\n const tree = location?.value as MutableTree;\n const node = location?.node;\n if (node?.kind !== 'tree') throw new Error('Tree schema disappeared before sealing.');\n const nodes: Extract<Change, { kind: 'tree' }>['nodes'][number][] = [];\n for (const [id, before] of fact.nodes) {\n const after = Object.hasOwn(tree.nodes, id) ? tree.nodes[id] : undefined;\n if (!before && !after) continue;\n if (before && after && schemaValue.equalTreeNode(before, after)) continue;\n nodes.push(\n !before\n ? { id, kind: 'added', after: schemaValue.copyTreeNode(after!) }\n : !after\n ? { id, kind: 'removed', before }\n : { id, kind: 'updated', before, after: schemaValue.copyTreeNode(after) }\n );\n }\n const after = tree.rootId ?? null;\n if (nodes.length || fact.before !== after)\n changes.push({\n kind: 'tree',\n at: fact.at,\n before: fact.before,\n after,\n nodes: nodes.sort((a, b) => lexical(a.id, b.id)),\n });\n};\n\n/** One first-touch record per owning container, never a per-write operation log. */\nexport class ChangeRecorder {\n private readonly facts = new Set<Fact>();\n private groups = new WeakMap<object, MemberGroup>();\n private index?: AddressIndex<Fact>;\n private indexedGroups = false;\n private resetBefore?: { value: unknown };\n constructor(private readonly state: state.CanonicalState) {}\n private indexGroups(): AddressIndex<Fact> {\n const index = (this.index ??= new AddressIndex());\n if (!this.indexedGroups) {\n this.indexedGroups = true;\n for (const fact of this.facts) {\n if (fact.kind === 'members') {\n index.add(fact.at, fact);\n profile.recorder('indexedGroups');\n }\n }\n }\n return index;\n }\n private covered(at: DocumentAddress): boolean {\n return (\n this.resetBefore !== undefined ||\n (this.indexedGroups &&\n this.index!.someAncestor(\n at,\n fact =>\n fact.kind === 'members' &&\n fact.at.length < at.length &&\n firstMember(fact, at[fact.at.length]) !== undefined\n ))\n );\n }\n private absorb(\n at: DocumentAddress,\n node: DocumentNode,\n value: unknown,\n present: boolean\n ): unknown {\n const index = this.indexGroups();\n const children: RestoreFact[] = [];\n index.query(fact => {\n if (fact.kind === 'members') {\n // An ancestor group can contribute only its one directly addressed member.\n if (fact.at.length < at.length) {\n if (fact.at.length + 1 === at.length) {\n const member = firstMember(fact, at[fact.at.length]);\n if (member) children.push({ kind: 'member', at, group: fact, member });\n }\n return;\n }\n if (fact.order && relation.contains(at, fact.at))\n children.push({ kind: 'order', at: fact.at, group: fact });\n for (const member of fact.members?.values() ?? []) {\n if (!member) continue;\n const memberAt = fact.at.concat(member.key);\n if (relation.contains(at, memberAt))\n children.push({ kind: 'member', at: memberAt, group: fact, member });\n }\n } else if (relation.contains(at, fact.at)) children.push(fact);\n })(at);\n if (present) value = reconstructBefore(node, value, children, at.length);\n this.releaseCovered(children);\n return value;\n }\n private releaseCovered(children: readonly RestoreFact[]): void {\n let changedGroups: Set<MemberGroup> | undefined;\n for (const child of children) {\n profile.recorder('absorbed');\n if (child.kind === 'member') {\n const { group, member } = child;\n forgetMember(group, member.key);\n (changedGroups ??= new Set()).add(group);\n } else if (child.kind === 'order') {\n child.group.order = undefined;\n (changedGroups ??= new Set()).add(child.group);\n } else {\n this.unregister(child);\n }\n }\n for (const group of changedGroups ?? []) {\n if (emptyGroup(group)) {\n this.unregister(group);\n }\n }\n }\n private register(fact: Fact): void {\n this.facts.add(fact);\n if (fact.kind === 'members') {\n this.groups.set(fact.parent, fact);\n profile.recorder('groups');\n if (!this.indexedGroups) return;\n profile.recorder('indexedGroups');\n }\n (this.index ??= new AddressIndex()).add(fact.at, fact);\n }\n private unregister(fact: Fact): void {\n this.facts.delete(fact);\n this.index?.delete(fact.at, fact);\n if (fact.kind === 'members') this.groups.delete(fact.parent);\n }\n member(\n container: address.ResolvedContainer,\n key: string,\n definition: CompiledMember,\n physicalKey: string | number\n ): void {\n if (this.resetBefore) return;\n const { node } = definition;\n let group = this.groups.get(container.parent);\n if (group?.layout === 'dynamic' && group.members?.has(key)) return;\n if (group?.layout === 'fixed' && definition.kind === 'fixed' && group.members[definition.slot])\n return;\n const at = this.indexedGroups || node.kind !== 'field' ? container.at.concat(key) : undefined;\n if (at && this.covered(at)) return;\n const present = Object.hasOwn(container.parent, physicalKey);\n let value = (container.parent as Record<string | number, unknown>)[physicalKey];\n if (node.kind !== 'field') value = this.absorb(at!, node, value, present);\n if (!group || !this.facts.has(group)) {\n group = this.createGroup(container);\n }\n const member: MemberFact = { key, node, present, value };\n if (group.layout === 'dynamic') (group.members ??= new Map()).set(key, member);\n else if (definition.kind === 'fixed') group.members[definition.slot] = member;\n else throw new Error('A fixed member group requires a fixed schema member.');\n profile.recorder('facts');\n }\n reset(): void {\n if (this.resetBefore) return;\n const value = this.absorb([], this.state.schema, this.state.document, true);\n this.resetBefore = { value };\n this.groups = new WeakMap();\n profile.recorder('facts');\n }\n private createGroup(container: address.ResolvedContainer): MemberGroup {\n const group: MemberGroup =\n container.layout.kind === 'fixed'\n ? {\n kind: 'members',\n at: container.at,\n node: container.node,\n parent: container.parent,\n value: container.value,\n layout: 'fixed',\n definitions: container.layout.members,\n members: new Array<MemberFact | undefined>(container.layout.members.size),\n }\n : {\n kind: 'members',\n at: container.at,\n node: container.node,\n parent: container.parent,\n value: container.value,\n layout: 'dynamic',\n members: undefined,\n };\n this.register(group);\n return group;\n }\n order(container: address.ResolvedContainer): void {\n profile.recorder('orderCaptures');\n let group = this.groups.get(container.parent);\n if (group?.order || this.covered(container.at)) return;\n group ??= this.createGroup(container);\n group.order = state.orderOf(container.node, container.value);\n profile.recorder('orderSnapshots');\n profile.recorder('orderItems', group.order.length);\n }\n tree(container: address.ResolvedTreeContainer, id?: string): void {\n const { at, value: tree } = container;\n if (this.covered(at)) return;\n const index = (this.index ??= new AddressIndex());\n let fact: TreeFact | undefined;\n for (const item of index.exact(at) ?? []) if (item.kind === 'tree') fact = item;\n if (!fact) {\n fact = { kind: 'tree', at, before: tree.rootId ?? null, nodes: new Map() };\n this.register(fact);\n }\n if (id !== undefined && !fact.nodes.has(id)) {\n profile.recorder('treeNodes');\n fact.nodes.set(\n id,\n Object.hasOwn(tree.nodes, id) ? schemaValue.copyTreeNode(tree.nodes[id]) : undefined\n );\n }\n }\n rollback(): void {\n if (this.resetBefore) {\n this.state.document = this.resetBefore.value;\n return;\n }\n const facts = [...this.facts];\n for (let i = facts.length - 1; i >= 0; i--) {\n const fact = facts[i];\n if (fact.kind === 'members') {\n for (const member of fact.members?.values() ?? []) {\n if (!member) continue;\n state.installMember(\n fact.parent,\n address.memberKey(fact, member.key),\n member.present,\n member.present ? schemaValue.copyValue(member.node, member.value) : undefined\n );\n }\n } else if (fact.kind === 'tree') restore(fact, this.state.schema, this.state.document);\n }\n for (const fact of facts)\n if (fact.kind === 'members' && fact.order)\n state.installOrder(fact.node, fact.value, fact.order);\n }\n seal(): ChangeSet {\n if (this.resetBefore) {\n if (schemaValue.equalValue(this.state.schema, this.resetBefore.value, this.state.document))\n return changeSet.sealChanges([]);\n profile.recorder('sealed');\n return changeSet.sealChanges([\n {\n kind: 'reset',\n before: this.resetBefore.value,\n after: schemaValue.copyValue(this.state.schema, this.state.document),\n },\n ]);\n }\n const changes: Change[] = [];\n for (const fact of this.facts) {\n if (fact.kind === 'members') sealMembers(fact, changes);\n else sealTree(fact, this.state, changes);\n }\n const result = changeSet.sealChanges(changes);\n profile.recorder('sealed', result.changes.length);\n return result;\n }\n}\nconst lexical = (a: string, b: string): number => (a < b ? -1 : a === b ? 0 : 1);\n","import type { ChangeSet } from '../changes';\nimport type { DocumentAddress, DocumentNode } from '../schema/model';\nimport * as address from '../address/resolve';\nimport type { CompiledMember } from '../schema/layout';\nimport * as schemaValue from '../schema/value';\nimport { ChangeRecorder } from './recorder';\nimport * as state from './state';\nimport * as issue from './issue';\n\nexport class MutationSession {\n readonly identity = {};\n generation = 0;\n readonly recorder: ChangeRecorder;\n private resolver;\n private resolvedRoot: unknown;\n constructor(readonly state: state.CanonicalState) {\n this.recorder = new ChangeRecorder(state);\n this.resolver = address.createAddressResolver(state.schema, state.document);\n this.resolvedRoot = state.document;\n }\n validate(node: DocumentNode, value: unknown, at: DocumentAddress): void {\n const failure = schemaValue.checkValue(node, value, at);\n if (failure) issue.invalidValue(failure);\n }\n resolveContainer(at: DocumentAddress): address.ResolvedContainer {\n return (\n this.resolver.container(this.identity, this.generation, at) ??\n issue.fail(at, 'invalid-address', 'Container does not exist.')\n );\n }\n /** Bind access-resolved canonical facts without walking the address again. */\n bind(\n at: DocumentAddress,\n node: DocumentNode | undefined,\n value: unknown\n ): address.ResolvedContainer {\n return (\n address.resolveContainer(this.identity, this.generation, at, node, value) ??\n issue.fail(at, 'invalid-address', 'Container does not exist.')\n );\n }\n bindTree(\n at: DocumentAddress,\n node: DocumentNode | undefined,\n value: unknown\n ): address.ResolvedTreeContainer {\n return (\n address.resolveTreeContainer(this.identity, this.generation, at, node, value) ??\n issue.fail(at, 'invalid-tree', 'Expected a tree.')\n );\n }\n resolveTree(at: DocumentAddress): address.ResolvedTreeContainer {\n const location = address.resolveValue(this.state.schema, this.state.document, at);\n return this.bindTree(at, location?.node, location?.value);\n }\n replace(at: DocumentAddress, value: unknown): void {\n if (!at.length) {\n this.validate(this.state.schema, value, at);\n if (Object.is(this.state.document, value)) return;\n this.recorder.reset();\n this.state.document = schemaValue.copyValue(this.state.schema, value);\n this.invalidate();\n return;\n }\n this.writeMember(this.resolveContainer(at.slice(0, -1)), at[at.length - 1], value, 'set');\n }\n assignMember(container: address.ResolvedContainer, key: string, value: unknown): void {\n container = this.refresh(container);\n const member = this.definition(container, key);\n if (\n container.layout.kind === 'fixed' &&\n member.node.kind !== 'field' &&\n member.node.kind !== 'variant' &&\n !member.node.optional\n )\n return issue.fail(\n container.at.concat(key),\n 'invalid-value',\n 'Replace fields, variants, or collection entries; edit object members individually.'\n );\n this.writeLocatedMember(\n container,\n key,\n member,\n address.memberKey(container, key),\n value,\n 'set'\n );\n }\n removeMember(container: address.ResolvedContainer, key: string): void {\n this.writeMember(this.refresh(container), key, undefined, 'remove');\n }\n private refresh(container: address.ResolvedContainer): address.ResolvedContainer {\n if (container.owner !== this.identity)\n return issue.fail(\n container.at,\n 'invalid-address',\n 'Container belongs to another mutation session.'\n );\n return container.generation === this.generation\n ? container\n : this.resolveContainer(container.at);\n }\n definition(container: address.ResolvedContainer, key: string): CompiledMember {\n const layout = container.layout;\n const member = layout.kind === 'dynamic' ? layout.entry : layout.members.get(key);\n if (!member)\n return issue.fail(container.at.concat(key), 'invalid-address', 'Address does not exist.');\n return member;\n }\n /** Consume a current command-local container; bulk writes retain its storage. */\n writeMember(\n container: address.ResolvedContainer,\n key: string,\n value: unknown,\n operation: 'set' | 'remove',\n physicalKey = address.memberKey(container, key)\n ): boolean {\n const member = this.definition(container, key);\n return this.writeLocatedMember(container, key, member, physicalKey, value, operation);\n }\n /** Location and definition are resolved once by the calling operation. */\n private writeLocatedMember(\n container: address.ResolvedContainer,\n key: string,\n member: CompiledMember,\n physicalKey: string | number,\n value: unknown,\n operation: 'set' | 'remove'\n ): boolean {\n const parentNode = container.node;\n const node = member.node;\n const present = operation === 'set';\n if (parentNode.kind === 'variant' && parentNode.tag === key)\n return issue.fail(\n container.at.concat(key),\n 'invalid-value',\n 'Variant discriminants are read-only.'\n );\n const entry = container.layout.kind === 'dynamic';\n if (!present && !node.optional && !entry)\n return issue.fail(\n container.at.concat(key),\n 'required-field',\n 'A required value cannot be removed.'\n );\n const existed = Object.hasOwn(container.parent, physicalKey);\n const previous = (container.parent as Record<string | number, unknown>)[physicalKey];\n if (existed === present && (!present || Object.is(previous, value))) return false;\n if (parentNode.kind === 'map' || parentNode.kind === 'table') {\n const failure = schemaValue.checkKey(parentNode.key, key, []);\n if (failure)\n return issue.fail(\n container.at.concat(key, ...failure.address),\n 'invalid-key',\n failure.message\n );\n }\n if (present) {\n if (node.kind === 'field') {\n const failure = schemaValue.checkValue(node, value, []);\n if (failure)\n return issue.invalidValue(failure, container.at.concat(key, ...failure.address));\n } else this.validate(node, value, container.at.concat(key));\n if (parentNode.kind === 'list' && parentNode.keyOf(value) !== key)\n return issue.fail(\n container.at.concat(key),\n 'invalid-list-key',\n 'Replacing an item must retain its addressed key.'\n );\n }\n const membershipChanged = entry && existed !== present;\n if (membershipChanged && (parentNode.kind === 'list' || parentNode.kind === 'table'))\n this.recorder.order(container);\n this.recorder.member(container, key, member, physicalKey);\n const next = present\n ? node.kind === 'field'\n ? value\n : schemaValue.copyValue(node, value)\n : undefined;\n state.installMember(container.parent, physicalKey, present, next);\n if (node.kind !== 'field' || membershipChanged) this.invalidate();\n return membershipChanged;\n }\n invalidate(): void {\n this.generation++;\n if (this.resolvedRoot !== this.state.document) {\n this.resolvedRoot = this.state.document;\n this.resolver = address.createAddressResolver(this.state.schema, this.state.document);\n } else this.resolver.invalidate();\n }\n finish(): ChangeSet {\n return this.recorder.seal();\n }\n rollback(): void {\n this.recorder.rollback();\n this.invalidate();\n }\n}\n","import type { ChangeDirection, ChangeSet } from '../../changes';\nimport type { MutationSession } from '../session';\nimport * as state from '../state';\nimport * as sequence from '../../order/sequence';\nimport * as issue from '../issue';\nimport * as schemaValue from '../../schema/value';\nimport * as tree from '../../tree/topology';\nexport function apply(\n session: MutationSession,\n changes: ChangeSet,\n direction: ChangeDirection\n): void {\n const side = direction === 'forward' ? 'after' : 'before';\n for (const change of changes.changes) {\n if (change.kind === 'reset') {\n session.replace([], change[side]);\n } else if (change.kind === 'members') {\n const container = session.resolveContainer(change.at);\n const { node, value: current } = container;\n if (change.order) {\n if (node.kind !== 'table' && node.kind !== 'list')\n return issue.fail(change.at, 'invalid-changes', 'Order requires an ordered container.');\n session.recorder.order(container);\n }\n let membershipChanged = false;\n for (const member of change.members) {\n const present = side === 'after' ? member.kind !== 'removed' : member.kind !== 'added';\n const value =\n side === 'after'\n ? member.kind !== 'removed'\n ? member.after\n : undefined\n : member.kind !== 'added'\n ? member.before\n : undefined;\n membershipChanged =\n session.writeMember(container, member.key, value, present ? 'set' : 'remove') ||\n membershipChanged;\n }\n if (change.order) {\n const keys =\n node.kind === 'table' ? Object.keys(container.parent) : state.orderOf(node, current);\n if (!sequence.matches(change.order[side], keys))\n return issue.fail(\n change.at,\n 'invalid-changes',\n 'Order must contain exactly the resulting keys.'\n );\n state.installOrder(node, current, change.order[side]);\n session.invalidate();\n } else if (membershipChanged && node.kind === 'table') {\n const ids = (current as { ids: string[] }).ids;\n if (!sequence.matches(ids, Object.keys(container.parent)))\n return issue.fail(\n change.at,\n 'invalid-changes',\n 'Table membership changes require a matching order.'\n );\n }\n } else {\n const container = session.resolveTree(change.at);\n const { value: current, node } = container;\n session.recorder.tree(container);\n for (const item of change.nodes) session.recorder.tree(container, item.id);\n const root = change[side];\n if (root === null) delete current.rootId;\n else current.rootId = root;\n for (const item of change.nodes) {\n const next =\n side === 'after'\n ? item.kind !== 'removed'\n ? item.after\n : undefined\n : item.kind !== 'added'\n ? item.before\n : undefined;\n if (next !== undefined) {\n const diagnostic = schemaValue.checkTreePayload(\n node.value,\n next,\n change.at.concat(item.id)\n );\n if (diagnostic) issue.invalidValue(diagnostic);\n }\n state.installMember(\n current.nodes,\n item.id,\n next !== undefined,\n next && schemaValue.copyTreeNode(next)\n );\n }\n if (!tree.validate(current))\n return issue.fail(change.at, 'invalid-tree', 'Invalid tree structure.');\n session.invalidate();\n }\n }\n}\n","import type { ObjectSchema } from '../schema/model';\nimport type { ReadonlyDocument, DocumentRuntime } from './contract';\nimport { bindContext, contextOf } from './context';\n\n// A readable capability keeps the canonical runtime behind an explicit\n// mutation funnel while remaining fully compatible with selectors, views, and\n// framework subscriptions.\nexport const readonlyDocument = <TSchema extends ObjectSchema<object>>(\n runtime: DocumentRuntime<TSchema>\n): ReadonlyDocument<TSchema> => {\n const readable: ReadonlyDocument<TSchema> = {\n revision: runtime.revision,\n subscribe: runtime.subscribe,\n };\n bindContext(readable, contextOf(runtime));\n return Object.freeze(readable);\n};\n","import type { ObjectSchema, RootNodeOf } from '../schema/model';\nimport type { ImpactTarget } from '../schema/path';\nimport type { CommitListener, DocumentCommit, Unsubscribe, ObserverError } from './contract';\nimport * as target from '../impact/target';\n\ntype ProjectionAttachment<TSchema extends ObjectSchema<object>> = {\n capture(commit: DocumentCommit<TSchema>): void;\n settle(): void;\n flush(): readonly ObserverError[];\n dispose(): void;\n};\ntype ProcessorEntry<TSchema extends ObjectSchema<object>> = {\n readonly processor: ProjectionAttachment<TSchema>;\n active: boolean;\n};\ntype RootEntry<TSchema extends ObjectSchema<object>> = {\n readonly listener: CommitListener<TSchema>;\n active: boolean;\n};\ntype FilteredEntry<TSchema extends ObjectSchema<object>> = {\n readonly targets: readonly ImpactTarget<unknown>[];\n readonly listener: CommitListener<TSchema>;\n active: boolean;\n};\ntype NotificationState<TSchema extends ObjectSchema<object>> = {\n readonly root: Set<RootEntry<TSchema>>;\n readonly filtered: Set<FilteredEntry<TSchema>>;\n readonly index: target.SubscriptionIndex<FilteredEntry<TSchema>>;\n readonly cleanups: Set<() => void>;\n readonly processors: ProcessorEntry<TSchema>[];\n readonly candidates: Set<FilteredEntry<TSchema>>;\n readonly rootSnapshot: RootEntry<TSchema>[];\n notifying: boolean;\n};\nexport type NotificationCenter<TSchema extends ObjectSchema<object>> = {\n subscribe(listener: CommitListener<TSchema>): Unsubscribe;\n subscribeTargets(\n targets: readonly ImpactTarget<unknown>[],\n listener: CommitListener<TSchema>\n ): Unsubscribe;\n attachProjection(processor: ProjectionAttachment<TSchema>): Unsubscribe;\n publish(\n commit: DocumentCommit<TSchema>,\n afterSettle?: () => readonly ObserverError[]\n ): readonly ObserverError[];\n dispose(): void;\n};\n\nconst attachProjection = <TSchema extends ObjectSchema<object>>(\n notification: NotificationState<TSchema>,\n processor: ProjectionAttachment<TSchema>\n): Unsubscribe => {\n const entry: ProcessorEntry<TSchema> = { processor, active: true };\n notification.processors.push(entry);\n return () => {\n if (!entry.active) return;\n entry.active = false;\n if (!notification.notifying) {\n const index = notification.processors.indexOf(entry);\n if (index >= 0) notification.processors.splice(index, 1);\n }\n };\n};\n\nconst addRoot = <TSchema extends ObjectSchema<object>>(\n notification: NotificationState<TSchema>,\n listener: CommitListener<TSchema>\n): Unsubscribe => {\n const entry: RootEntry<TSchema> = { listener, active: true };\n notification.root.add(entry);\n return () => {\n entry.active = false;\n if (!notification.notifying) notification.root.delete(entry);\n else\n notification.cleanups.add(() => {\n notification.root.delete(entry);\n });\n };\n};\n\nconst addFiltered = <TSchema extends ObjectSchema<object>>(\n notification: NotificationState<TSchema>,\n targets: readonly ImpactTarget<unknown>[],\n listener: CommitListener<TSchema>\n): Unsubscribe => {\n const entry: FilteredEntry<TSchema> = {\n targets: Object.freeze(targets.slice()),\n listener,\n active: true,\n };\n notification.filtered.add(entry);\n entry.targets.forEach(value => notification.index.add(value, entry));\n const remove = () => {\n notification.filtered.delete(entry);\n entry.targets.forEach(value => notification.index.delete(value, entry));\n };\n return () => {\n if (!entry.active) return;\n entry.active = false;\n if (notification.notifying) notification.cleanups.add(remove);\n else remove();\n };\n};\n\nconst publishState = <TSchema extends ObjectSchema<object>>(\n notification: NotificationState<TSchema>,\n commit: DocumentCommit<TSchema>,\n afterSettle?: () => readonly ObserverError[]\n): readonly ObserverError[] => {\n notification.notifying = true;\n const errors: ObserverError[] = [];\n const call = (listener: CommitListener<TSchema>): void => {\n try {\n listener(commit);\n } catch (error) {\n errors.push(Object.freeze({ phase: 'listener', error }));\n }\n };\n try {\n const processorCount = notification.processors.length;\n for (let index = 0; index < processorCount; index += 1) {\n const entry = notification.processors[index];\n if (!entry?.active) continue;\n try {\n entry.processor.capture(commit);\n } catch (error) {\n errors.push(Object.freeze({ phase: 'processor', error }));\n }\n }\n for (let index = 0; index < processorCount; index += 1) {\n const entry = notification.processors[index];\n if (!entry?.active) continue;\n try {\n entry.processor.settle();\n } catch (error) {\n errors.push(Object.freeze({ phase: 'processor', error }));\n }\n }\n for (let index = 0; index < processorCount; index += 1) {\n const entry = notification.processors[index];\n if (!entry?.active) continue;\n try {\n errors.push(...entry.processor.flush());\n } catch (error) {\n errors.push(Object.freeze({ phase: 'flush', error }));\n }\n }\n\n if (afterSettle) errors.push(...afterSettle());\n const candidates = notification.candidates;\n candidates.clear();\n if (notification.filtered.size)\n notification.index.collect(commit.changes, entry => candidates.add(entry));\n candidates.forEach(entry => {\n if (entry.active) call(entry.listener);\n });\n const rootSnapshot = notification.rootSnapshot;\n rootSnapshot.length = 0;\n notification.root.forEach(entry => rootSnapshot.push(entry));\n for (const entry of rootSnapshot) if (entry.active) call(entry.listener);\n } finally {\n notification.notifying = false;\n let writeIndex = 0;\n for (const entry of notification.processors)\n if (entry.active) notification.processors[writeIndex++] = entry;\n notification.processors.length = writeIndex;\n notification.cleanups.forEach(cleanup => cleanup());\n notification.cleanups.clear();\n }\n return Object.freeze(errors);\n};\n\nconst disposeState = <TSchema extends ObjectSchema<object>>(\n notification: NotificationState<TSchema>\n): void => {\n const attachments = notification.processors.slice();\n notification.root.clear();\n notification.filtered.clear();\n notification.index.clear();\n notification.cleanups.clear();\n notification.processors.length = 0;\n notification.candidates.clear();\n notification.rootSnapshot.length = 0;\n const errors: unknown[] = [];\n attachments.forEach(entry => {\n if (!entry.active) return;\n try {\n entry.processor.dispose();\n } catch (error) {\n errors.push(error);\n }\n });\n if (errors.length) throw new AggregateError(errors, 'Projection disposal notification failed.');\n};\n\nexport const createNotificationCenter = <TSchema extends ObjectSchema<object>>(\n schema: RootNodeOf<TSchema>\n): NotificationCenter<TSchema> => {\n const state: NotificationState<TSchema> = {\n root: new Set(),\n filtered: new Set(),\n index: new target.SubscriptionIndex(schema),\n cleanups: new Set(),\n processors: [],\n candidates: new Set(),\n rootSnapshot: [],\n notifying: false,\n };\n return Object.freeze({\n subscribe: (listener: CommitListener<TSchema>) => addRoot(state, listener),\n subscribeTargets: (\n targets: readonly ImpactTarget<unknown>[],\n listener: CommitListener<TSchema>\n ) => addFiltered(state, targets, listener),\n attachProjection: (processor: ProjectionAttachment<TSchema>) =>\n attachProjection(state, processor),\n publish: (commit: DocumentCommit<TSchema>, afterSettle?: () => readonly ObserverError[]) =>\n publishState(state, commit, afterSettle),\n dispose: () => disposeState(state),\n });\n};\n","import type { Infer, ObjectSchema, RootNodeOf } from './schema/model';\nimport { schemaNodeOf } from './schema/model';\nimport type { PathPick } from './schema/path';\nimport { compilePath } from './schema/path';\nimport { createImpact } from './impact';\nimport { createHistory } from './history';\nimport { createAccess, type Draft } from './access/scope';\nimport { MutationSession } from './mutation/session';\nimport * as replay from './mutation/operations/replay';\nimport type { RuntimeWriteIntent } from './runtime/driver';\nimport * as changeSet from './mutation/changes';\nimport * as issue from './mutation/issue';\nimport type { ChangeSet } from './changes';\nimport * as schemaValue from './schema/value';\nimport {\n DocumentDisposedError,\n DocumentReentrancyError,\n TransactionRejected,\n} from './runtime/contract';\nimport type {\n CommitListener,\n CommitSource,\n DocumentCommit,\n DocumentRuntime,\n ReadonlyDocument,\n OperationResult,\n TransactionResult,\n} from './runtime/contract';\nimport { readonlyDocument } from './runtime/readable';\nimport { assertRuntimeWritable } from './runtime/driver';\nimport { bindContext, type RuntimeContext, type RuntimeState } from './runtime/context';\nimport { createNotificationCenter } from './runtime/notification';\n\nexport const createDocument = <S extends ObjectSchema<object>>(input: {\n readonly schema: S;\n readonly initial: Infer<S>;\n readonly history?: { readonly capacity?: number } | false;\n}): DocumentRuntime<S> => {\n const schema = schemaNodeOf(input.schema) as RootNodeOf<S>;\n const invalid = schemaValue.checkValue(schema, input.initial);\n if (invalid) throw new schemaValue.ParseError(invalid);\n const state: RuntimeState<S> = {\n schema,\n document: schemaValue.copyValue(schema, input.initial) as Infer<S>,\n disposed: false,\n projectionLocks: 0,\n };\n let revision = 0,\n busy = false;\n const notifications = createNotificationCenter<S>(schema);\n let runtime!: DocumentRuntime<S>, context!: RuntimeContext<S>;\n let readonlyAlias: ReadonlyDocument<S> | undefined;\n const idle = () => {\n if (state.disposed) throw new DocumentDisposedError();\n if (busy || state.projectionLocks) throw new DocumentReentrancyError();\n };\n const writable = (intent: Parameters<typeof assertRuntimeWritable>[1]) => {\n idle();\n assertRuntimeWritable(runtime, intent);\n };\n const history = createHistory<DocumentCommit<S>>({\n capacity: input.history === false ? 0 : Math.max(0, input.history?.capacity ?? 100),\n revision: () => revision,\n apply: (changes, direction) =>\n mutate({ kind: 'apply', source: 'history' }, false, session => {\n for (const change of changes) replay.apply(session, change, direction);\n }),\n assertIdle: idle,\n notify: run => {\n busy = true;\n try {\n return run();\n } finally {\n busy = false;\n }\n },\n });\n const publish = (\n changes: ChangeSet,\n source: CommitSource,\n recordHistory: boolean\n ): Extract<OperationResult<DocumentCommit<S>>, { status: 'committed' }> => {\n const commit: DocumentCommit<S> = {\n revision: ++revision,\n source,\n changes,\n impact: createImpact<S>(schema, changes),\n };\n if (source === 'remote') history.invalidate();\n else if (recordHistory && (source === 'local' || source === 'system')) history.record(changes);\n else if (source === 'history') history.publish();\n else history.endGroup();\n return {\n status: 'committed',\n commit,\n observerErrors: notifications.publish(commit, history.flush),\n };\n };\n function mutate(\n intent: Extract<RuntimeWriteIntent, { kind: 'update' }>,\n recordHistory: boolean,\n execute: (session: MutationSession) => void\n ):\n | OperationResult<DocumentCommit<S>>\n | Extract<TransactionResult<never, never>, { status: 'rejected' }>;\n function mutate(\n intent: Exclude<RuntimeWriteIntent, { kind: 'update' }>,\n recordHistory: boolean,\n execute: (session: MutationSession) => void\n ): OperationResult<DocumentCommit<S>>;\n function mutate(\n intent: RuntimeWriteIntent,\n recordHistory: boolean,\n execute: (session: MutationSession) => void\n ):\n | OperationResult<DocumentCommit<S>>\n | Extract<TransactionResult<never, never>, { status: 'rejected' }> {\n writable(intent);\n busy = true;\n try {\n const session = new MutationSession(state);\n let changes: ChangeSet;\n try {\n execute(session);\n changes = session.finish();\n } catch (error) {\n session.rollback();\n if (error instanceof issue.MutationRejected)\n return { status: 'rejected', issues: [error.issue], revision };\n if (intent.kind === 'update' && error instanceof TransactionRejected)\n return { status: 'rejected', issues: error.issues, revision };\n throw error;\n }\n if (!changes.changes.length) return { status: 'unchanged', revision };\n // Publication is outside the rollback boundary: observers see accepted state.\n return publish(changes, intent.source, recordHistory);\n } finally {\n busy = false;\n }\n }\n runtime = {\n schema: input.schema,\n revision: () => revision,\n readonly: () => (readonlyAlias ??= readonlyDocument(runtime)),\n update: <V>(\n run: (draft: Draft<S>) => V,\n options?: { source?: Extract<CommitSource, 'local' | 'system'>; history?: boolean }\n ): TransactionResult<V, DocumentCommit<S>> => {\n const source = options?.source ?? 'local';\n let value!: V;\n const result = mutate({ kind: 'update', source }, options?.history ?? true, session => {\n // Draft is a trusted borrowed view. It must not escape this synchronous callback.\n const draft = createAccess({\n state,\n session,\n }) as Draft<S>;\n value = run(draft);\n if (\n value !== null &&\n (typeof value === 'object' || typeof value === 'function') &&\n typeof (value as { then?: unknown }).then === 'function'\n )\n throw new TypeError('Document updates must be synchronous.');\n });\n return result.status === 'rejected' ? result : { ...result, value };\n },\n apply: (inputChanges, options) => {\n const source = options?.source ?? 'local';\n return mutate(\n { kind: 'apply', source },\n source === 'remote' ? false : (options?.history ?? true),\n session => {\n if (!options || options.expectedRevision !== revision)\n issue.fail([], 'baseline-mismatch', 'apply requires the current expectedRevision.');\n replay.apply(session, changeSet.decodeChanges(inputChanges), 'forward');\n }\n );\n },\n replace: (value, options) => {\n const source = options?.source ?? 'system';\n return mutate({ kind: 'replace', source }, source !== 'remote', session =>\n session.replace([], value)\n );\n },\n snapshot: () => {\n if (state.disposed) throw new DocumentDisposedError();\n return schemaValue.copyValue(schema, state.document) as Infer<S>;\n },\n subscribe: ((\n pick: PathPick<S> | readonly PathPick<S>[] | CommitListener<S>,\n listener?: CommitListener<S>\n ) => {\n if (state.disposed) throw new DocumentDisposedError();\n if (!listener) return notifications.subscribe(pick as CommitListener<S>);\n const picks: readonly PathPick<S>[] = Array.isArray(pick) ? pick : [pick as PathPick<S>];\n if (!picks.length) throw new TypeError('Expected at least one subscription path.');\n return notifications.subscribeTargets(\n picks.map(p => compilePath<S>(schema, 'value', p)),\n listener\n );\n }) as DocumentRuntime<S>['subscribe'],\n history: history.api,\n dispose: () => {\n if (state.disposed) return;\n idle();\n state.disposed = true;\n try {\n notifications.dispose();\n } finally {\n history.dispose();\n context.driver = undefined;\n }\n },\n };\n context = {\n state,\n owner: runtime,\n notifications,\n driver: undefined,\n bypassDepth: 0,\n };\n bindContext(runtime, context);\n bindContext(history.api, context);\n return runtime;\n};\n","import type { ImpactTarget } from '../schema/path';\nimport * as target from '../impact/target';\n\nexport type DependencyTracker = {\n readonly record: (target: ImpactTarget<unknown>) => void;\n readonly snapshot: () => readonly ImpactTarget<unknown>[];\n};\n\nexport const createDependencyTracker = (): DependencyTracker => {\n const targets: ImpactTarget<unknown>[] = [];\n const buckets = new Map<string, ImpactTarget<unknown>[]>();\n return {\n record: value => {\n const key = target.dependencyBucket(value);\n let entries = buckets.get(key);\n if (!entries) {\n entries = [];\n buckets.set(key, entries);\n } else if (entries.some(entry => target.same(entry, value))) return;\n entries.push(value);\n targets.push(value);\n },\n snapshot: () => Object.freeze(targets.slice()),\n };\n};\n","import type { ObjectSchema } from '../schema/model';\nimport { createAccess, type Read } from '../access/scope';\nimport type { DependencyTracker } from '../access/dependency';\nimport { DocumentDisposedError } from './contract';\nimport type { ReadonlyDocument } from './contract';\nimport { contextOf } from './context';\n\nexport const readWith = <TSchema extends ObjectSchema<object>, TResult>(\n runtime: ReadonlyDocument<TSchema>,\n run: (read: Read<TSchema>) => TResult,\n dependencies?: DependencyTracker\n): TResult => {\n const state = contextOf<TSchema>(runtime).state;\n if (state.disposed) throw new DocumentDisposedError();\n state.projectionLocks += 1;\n try {\n const reader = createAccess({\n state,\n dependencies,\n }) as Read<TSchema>;\n return run(reader);\n } finally {\n // readWith is an internal borrowed-reader boundary. Retaining its reader or\n // collection methods after this callback is undefined behavior.\n state.projectionLocks--;\n }\n};\n","import { createDependencyTracker } from '../access/dependency';\nimport type { Read } from '../access/scope';\nimport * as target from '../impact/target';\nimport type { Readable, Unsubscribe } from '../readable';\nimport type { ObjectSchema } from '../schema/model';\nimport type { ImpactTarget } from '../schema/path';\nimport { readWith } from './access';\nimport { DocumentDisposedError, type ReadonlyDocument } from './contract';\nimport { contextOf } from './context';\n\nexport type DocumentSelector<TSchema extends ObjectSchema<object>, TResult> = (\n read: Read<TSchema>\n) => TResult;\n\nexport const read = <TSchema extends ObjectSchema<object>, TResult>(\n document: ReadonlyDocument<TSchema>,\n selector: DocumentSelector<TSchema, TResult>\n): TResult => readWith(document, selector);\n\nconst sameDependencySet = (\n left: readonly ImpactTarget<unknown>[],\n right: readonly ImpactTarget<unknown>[]\n): boolean => {\n if (left.length !== right.length) return false;\n for (let index = 0; index < left.length; index += 1)\n if (!target.same(left[index], right[index])) return false;\n return true;\n};\n\nexport const select = <TSchema extends ObjectSchema<object>, TResult>(\n document: ReadonlyDocument<TSchema>,\n selector: DocumentSelector<TSchema, TResult>,\n equality: (previous: TResult, next: TResult) => boolean = Object.is\n): Readable<TResult> => {\n const context = contextOf<TSchema>(document);\n let initialized = false;\n let value!: TResult;\n let selectedRevision = 0;\n let documentRevision = -1;\n let dependencies: readonly ImpactTarget<unknown>[] = Object.freeze([]);\n let unsubscribeDocument: Unsubscribe | undefined;\n const listeners = new Set<() => void>();\n\n const evaluate = (): { readonly changed: boolean; readonly rebound: boolean } => {\n const tracker = createDependencyTracker();\n const next = readWith(document, selector, tracker);\n const nextDependencies = tracker.snapshot();\n const changed = !initialized || !equality(value, next);\n const rebound = !sameDependencySet(dependencies, nextDependencies);\n if (changed) {\n if (initialized) selectedRevision += 1;\n value = next;\n }\n dependencies = nextDependencies;\n initialized = true;\n documentRevision = document.revision();\n return { changed, rebound };\n };\n\n const installSubscription = (): void => {\n unsubscribeDocument?.();\n unsubscribeDocument =\n dependencies.length > 0\n ? context.notifications.subscribeTargets(dependencies, () => {\n const result = evaluate();\n if (result.rebound) installSubscription();\n if (result.changed) for (const listener of [...listeners]) listener();\n })\n : undefined;\n };\n\n const ensureCurrent = (): TResult => {\n if (context.state.disposed) throw new DocumentDisposedError();\n if (!initialized || (!unsubscribeDocument && documentRevision !== document.revision()))\n evaluate();\n return value;\n };\n\n return Object.freeze({\n current: ensureCurrent,\n revision: () => {\n ensureCurrent();\n return selectedRevision;\n },\n subscribe: (listener: () => void) => {\n ensureCurrent();\n listeners.add(listener);\n if (listeners.size === 1) installSubscription();\n return () => {\n listeners.delete(listener);\n if (!listeners.size) {\n unsubscribeDocument?.();\n unsubscribeDocument = undefined;\n }\n };\n },\n });\n};\n","import type { CollectionChange } from './contract';\nimport { defineSource, type CollectionInput, type Equality, type Input } from './definition';\n\nconst valueInput = <T>(\n initial: T,\n equality: (previous: T, next: T) => boolean = Object.is\n): Input<T> =>\n defineSource<T>(\n { kind: 'value-input', initial, equality: equality as Equality },\n { kind: 'value', equality: equality as Equality }\n ) as unknown as Input<T>;\n\nconst collectionInput = <K extends string, V>(\n initial: ReadonlyMap<K, V> = new Map<K, V>(),\n equality: (previous: V, next: V) => boolean = Object.is\n): CollectionInput<K, V> => {\n const entries = new Map<string, unknown>();\n for (const [key, value] of initial) {\n if (typeof key !== 'string') throw new TypeError('Projection keys must be strings.');\n entries.set(key, value);\n }\n return defineSource<ReadonlyMap<K, V>, CollectionChange<K, V>>(\n { kind: 'collection-input', initial: entries, equality: equality as Equality },\n { kind: 'collection', equality: equality as Equality }\n ) as CollectionInput<K, V>;\n};\n\nexport const input = Object.assign(valueInput, { collection: collectionInput });\n","import type { Readable } from '../readable';\nimport { contextOf } from '../runtime/context';\nimport type { ReadonlyDocument } from '../runtime/contract';\nimport type { Infer, ObjectSchema, ReadonlyValue } from '../schema/model';\nimport {\n compilePath,\n type CollectionEntry,\n type CollectionId,\n type CollectionPath,\n type PathValueOf,\n type SchemaPath,\n type ValueSelector,\n} from '../schema/path';\nimport type { CollectionChange, ExternalCollectionSource, ExternalValueSource } from './contract';\nimport { defineSource, type Projection, type ProjectionWithChange } from './definition';\n\ntype PathSelector<S extends ObjectSchema<object>> = (path: SchemaPath<S>) => unknown;\n\n/** Establish a lazy reactive boundary from a document, readable, or external source. */\nexport function observe<S extends ObjectSchema<object>>(\n document: ReadonlyDocument<S>\n): Projection<Infer<S>>;\nexport function observe<T>(source: ExternalValueSource<T>): Projection<T>;\nexport function observe<K extends string, V>(\n source: ExternalCollectionSource<K, V>\n): ProjectionWithChange<ReadonlyMap<K, V>, CollectionChange<K, V>>;\nexport function observe<T>(readable: Readable<T>): Projection<T>;\nexport function observe<S extends ObjectSchema<object>, P extends CollectionPath>(\n document: ReadonlyDocument<S>,\n selector: (path: SchemaPath<S>) => P\n): ProjectionWithChange<\n ReadonlyMap<CollectionId<P>, ReadonlyValue<CollectionEntry<P>>>,\n CollectionChange<CollectionId<P>, ReadonlyValue<CollectionEntry<P>>>\n>;\nexport function observe<S extends ObjectSchema<object>, P>(\n document: ReadonlyDocument<S>,\n selector: (path: SchemaPath<S>) => P\n): Projection<PathValueOf<P>>;\nexport function observe<S extends ObjectSchema<object>>(\n source:\n | ReadonlyDocument<S>\n | Readable<unknown>\n | ExternalValueSource<unknown>\n | ExternalCollectionSource<string, unknown>,\n selector?: PathSelector<S>\n): Projection<unknown> {\n if (isExternalSource(source))\n return source.kind === 'collection'\n ? defineSource(\n { kind: 'external-collection', source },\n { kind: 'collection', equality: Object.is }\n )\n : defineSource(\n { kind: 'external-value', source, equality: Object.is },\n { kind: 'value', equality: Object.is }\n );\n if ('current' in source && typeof source.current === 'function')\n return defineSource(\n { kind: 'readable', readable: source as Readable<unknown>, equality: Object.is },\n { kind: 'value', equality: Object.is }\n );\n\n const document = source as ReadonlyDocument<S>;\n const state = contextOf<S>(document).state;\n const selected = selector\n ? compilePath<S>(state.schema, 'auto', selector)\n : (Object.freeze({\n kind: 'value' as const,\n schema: state.schema,\n address: Object.freeze([]),\n }) as ValueSelector);\n return defineSource(\n {\n kind: 'document',\n document: document as unknown as ReadonlyDocument<ObjectSchema<object>>,\n selector: selected,\n },\n { kind: selected.kind, equality: Object.is }\n );\n}\n\nconst isExternalSource = (\n source: unknown\n): source is ExternalValueSource<unknown> | ExternalCollectionSource<string, unknown> => {\n if (!source || typeof source !== 'object') return false;\n const candidate = source as {\n readonly kind?: unknown;\n readonly current?: unknown;\n readonly revision?: unknown;\n readonly subscribe?: unknown;\n };\n return (\n (candidate.kind === 'value' || candidate.kind === 'collection') &&\n typeof candidate.current === 'function' &&\n typeof candidate.revision === 'function' &&\n typeof candidate.subscribe === 'function'\n );\n};\n","import type { Synchronous } from '../runtime/contract';\nimport { snapshotCollectionView } from './collection/view';\nimport type { CollectionChange, SourceContext } from './contract';\nimport {\n defineProcessor,\n isProjection,\n projectionRef,\n type Projection,\n type ProjectionWithChange,\n type ProducerDefinition,\n} from './definition';\nimport { assertSynchronous } from './graph/scheduler';\nimport { isPlainObject } from '../value/record';\n\ntype ProjectionDependencies = Readonly<Record<string, Projection<unknown>>>;\ntype ProjectionValues<D extends ProjectionDependencies> = {\n readonly [K in keyof D]: D[K] extends Projection<infer T> ? T : never;\n};\n\ntype Equality<T> = (previous: T, next: T) => boolean;\ntype KeyedProjection<K extends string, V> = ProjectionWithChange<\n ReadonlyMap<K, V>,\n CollectionChange<K, V>\n>;\n\n/** A declared dynamic lookup from one driver entry to one key in another keyed projection. */\ntype KeyedDependency<\n DriverKey extends string,\n DriverValue,\n SourceKey extends string = string,\n SourceValue = unknown,\n> = {\n readonly source: KeyedProjection<SourceKey, SourceValue>;\n readonly key: (value: DriverValue, key: DriverKey) => Synchronous<SourceKey | undefined>;\n};\n\ntype KeyedDeriveDependency<K extends string, V> =\n | (Projection<unknown> & { readonly source?: never; readonly key?: never })\n | KeyedDependency<K, V, string, unknown>;\n\ntype KeyedDeriveDependencyRecord<K extends string, V> = Readonly<\n Record<string, KeyedDeriveDependency<K, V>>\n>;\n\ntype KeyedDeriveDependencies<K extends string, V, D extends object> = {\n readonly [P in keyof D]: P extends string ? KeyedDeriveDependency<K, V> : never;\n};\n\ntype KeyedDependencyValues<D extends Readonly<Record<string, unknown>>> = {\n readonly [P in keyof D]: D[P] extends {\n readonly source: KeyedProjection<infer _K extends string, infer V>;\n }\n ? V | undefined\n : D[P] extends Projection<infer T>\n ? T\n : never;\n};\n\ntype RuntimeKeyedDependency = {\n readonly source: Projection<unknown>;\n readonly key: (value: unknown, key: string) => unknown;\n};\n\ntype BindingIndex = {\n readonly forward: Map<string, string>;\n readonly reverse: Map<string, Set<string>>;\n};\n\nconst sourceValue = (source: SourceContext): unknown =>\n source.kind === 'value' ? source.value : snapshotCollectionView(source.read);\n\nconst outputKind = (projection: Projection<unknown>): 'value' | 'collection' => {\n const ref = projectionRef(projection);\n const definition: ProducerDefinition = ref.producer;\n const output = definition.kind === 'source' ? definition.output : definition.outputs[ref.output];\n if (!output) throw new TypeError('Projection output does not exist.');\n return output.kind;\n};\n\nconst assertKeyedProjection = (projection: Projection<unknown>, role: string): void => {\n if (outputKind(projection) !== 'collection')\n throw new TypeError(`${role} must be a keyed collection projection.`);\n};\n\nconst isKeyedDependency = (value: unknown): value is RuntimeKeyedDependency => {\n if (!value || typeof value !== 'object' || isProjection(value)) return false;\n const candidate = value as { readonly source?: unknown; readonly key?: unknown };\n return isProjection(candidate.source) && typeof candidate.key === 'function';\n};\n\nconst bindKey = (index: BindingIndex, outputKey: string, sourceKey: string | undefined): void => {\n const previous = index.forward.get(outputKey);\n if (previous === sourceKey) return;\n if (previous !== undefined) {\n const dependents = index.reverse.get(previous);\n dependents?.delete(outputKey);\n if (dependents?.size === 0) index.reverse.delete(previous);\n index.forward.delete(outputKey);\n }\n if (sourceKey === undefined) return;\n index.forward.set(outputKey, sourceKey);\n const dependents = index.reverse.get(sourceKey);\n if (dependents) dependents.add(outputKey);\n else index.reverse.set(sourceKey, new Set([outputKey]));\n};\n\nconst unbindKey = (indexes: readonly BindingIndex[], outputKey: string): void => {\n for (const index of indexes) bindKey(index, outputKey, undefined);\n};\n\nconst createBindingIndex = (): BindingIndex => ({ forward: new Map(), reverse: new Map() });\n\nfunction createValueDerive<const D extends ProjectionDependencies, T>(\n dependencies: D,\n compute: (values: ProjectionValues<D>) => Synchronous<T>,\n equality: Equality<T> = Object.is\n): Projection<T> {\n if (!isPlainObject(dependencies) || isProjection(dependencies))\n throw new TypeError('Derive dependencies must be a plain object.');\n const names = Object.keys(dependencies);\n const ordered = names.map(name => dependencies[name]);\n ordered.forEach(projectionRef);\n const [projection] = defineProcessor({\n dependencies: ordered,\n outputs: [{ kind: 'value', equality: equality as Equality<unknown> }],\n create: () => ({\n evaluate: evaluation => {\n const output = evaluation.outputs[0];\n if (output.kind !== 'value') throw new Error('derive requires a value output.');\n const values: Record<string, unknown> = Object.create(null) as Record<string, unknown>;\n for (let index = 0; index < names.length; index++)\n values[names[index]] = sourceValue(evaluation.sources[index]);\n const next = compute(Object.freeze(values) as ProjectionValues<D>);\n assertSynchronous(next);\n output.output.set(next);\n },\n }),\n });\n return projection as Projection<T>;\n}\n\nexport function createKeyedDerive<K extends string, V, T>(\n source: KeyedProjection<K, V>,\n select: (value: V, key: K) => Synchronous<T>,\n equality?: Equality<T>\n): KeyedProjection<K, T>;\nexport function createKeyedDerive<\n K extends string,\n V,\n const D extends object & KeyedDeriveDependencies<K, V, D>,\n T,\n>(\n source: KeyedProjection<K, V>,\n dependencies: D,\n select: (value: V, key: K, dependencies: KeyedDependencyValues<D>) => Synchronous<T>,\n equality?: Equality<T>\n): KeyedProjection<K, T>;\nexport function createKeyedDerive<K extends string, V, T>(\n source: KeyedProjection<K, V>,\n dependenciesOrSelect: KeyedDeriveDependencyRecord<K, V> | ((value: V, key: K) => Synchronous<T>),\n selectOrEquality?:\n | ((value: V, key: K, dependencies: Readonly<Record<string, unknown>>) => Synchronous<T>)\n | Equality<T>,\n maybeEquality?: Equality<T>\n): KeyedProjection<K, T> {\n assertKeyedProjection(source, 'Keyed derive source');\n const dependencySpecs =\n typeof dependenciesOrSelect === 'function' ? undefined : dependenciesOrSelect;\n const select = (dependencySpecs === undefined\n ? dependenciesOrSelect\n : selectOrEquality) as unknown as (\n value: V,\n key: K,\n dependencies?: Readonly<Record<string, unknown>>\n ) => Synchronous<T>;\n const equality = (dependencySpecs === undefined ? selectOrEquality : maybeEquality) as\n Equality<T> | undefined;\n if (typeof select !== 'function') throw new TypeError('Keyed derive requires a selector.');\n\n const dependencies: Projection<unknown>[] = [source];\n const dependencyNames: string[] = [];\n const keyed: Array<RuntimeKeyedDependency | undefined> = [];\n if (dependencySpecs !== undefined) {\n if (!isPlainObject(dependencySpecs) || isProjection(dependencySpecs))\n throw new TypeError('Keyed derive dependencies must be a plain object.');\n for (const name of Reflect.ownKeys(dependencySpecs)) {\n if (typeof name !== 'string')\n throw new TypeError('Keyed derive dependency names must be strings.');\n const descriptor = Object.getOwnPropertyDescriptor(dependencySpecs, name);\n if (!descriptor?.enumerable || !('value' in descriptor))\n throw new TypeError('Keyed derive dependencies must be enumerable data properties.');\n const dependency = descriptor.value as KeyedDeriveDependency<K, V>;\n dependencyNames.push(name);\n if (isProjection(dependency)) {\n dependencies.push(dependency);\n keyed.push(undefined);\n continue;\n }\n if (!isKeyedDependency(dependency))\n throw new TypeError('Keyed derive dependencies must be projections or keyed lookups.');\n assertKeyedProjection(dependency.source, 'Dynamic keyed dependency source');\n dependencies.push(dependency.source);\n keyed.push(dependency);\n }\n }\n\n const [projection] = defineProcessor({\n dependencies,\n outputs: [{ kind: 'collection', equality: (equality ?? Object.is) as Equality<unknown> }],\n create: () => {\n const bindings = keyed.map(dependency => (dependency ? createBindingIndex() : undefined));\n const bindingIndexes = bindings.filter((index): index is BindingIndex => index !== undefined);\n const globalValues: unknown[] = keyed.map(() => undefined);\n let revisions: readonly number[] = Object.freeze([]);\n\n const clearBindings = (): void => {\n for (const index of bindings) {\n index?.forward.clear();\n index?.reverse.clear();\n }\n };\n\n return {\n evaluate: evaluation => {\n const driver = evaluation.sources[0];\n const output = evaluation.outputs[0];\n if (driver.kind !== 'collection' || output.kind !== 'collection')\n throw new Error('Keyed derive requires collection input and output.');\n const currentRevisions = evaluation.sources.map(current => current.revision);\n for (let index = 0; index < keyed.length; index++) {\n if (keyed[index]) continue;\n if (evaluation.reset || revisions[index + 1] !== currentRevisions[index + 1])\n globalValues[index] = sourceValue(evaluation.sources[index + 1]);\n }\n\n const project = (key: string): void => {\n if (!driver.read.has(key)) return;\n const value = driver.read.get(key) as V;\n const dependencyValues: Record<string, unknown> = Object.create(null) as Record<\n string,\n unknown\n >;\n for (let index = 0; index < keyed.length; index++) {\n const dependency = keyed[index];\n if (!dependency) {\n dependencyValues[dependencyNames[index]] = globalValues[index];\n continue;\n }\n const sourceContext = evaluation.sources[index + 1];\n if (sourceContext.kind !== 'collection')\n throw new TypeError(\n 'Dynamic keyed dependency resolved to a non-collection source.'\n );\n const selectedKey = dependency.key(value, key);\n assertSynchronous(selectedKey);\n if (selectedKey !== undefined && typeof selectedKey !== 'string')\n throw new TypeError('Dynamic keyed dependency keys must be strings or undefined.');\n bindKey(bindings[index]!, key, selectedKey);\n dependencyValues[dependencyNames[index]] =\n selectedKey === undefined ? undefined : sourceContext.read.get(selectedKey);\n }\n const next =\n dependencySpecs === undefined\n ? select(value, key as K)\n : select(value, key as K, Object.freeze(dependencyValues));\n assertSynchronous(next);\n output.output.set(key, next);\n };\n\n if (evaluation.reset) {\n clearBindings();\n const ids = driver.read.ids();\n for (const key of ids) project(key);\n output.output.order(ids);\n revisions = Object.freeze(currentRevisions);\n return;\n }\n\n const dirty = new Set<string>();\n let all = false;\n let updateOrder = false;\n const driverChanged = revisions[0] !== currentRevisions[0];\n if (driverChanged) {\n const change = driver.change;\n if (!change || change.kind === 'reset') {\n all = true;\n updateOrder = true;\n } else {\n for (const entry of change.removed) {\n output.output.remove(entry.key);\n unbindKey(bindingIndexes, entry.key);\n dirty.delete(entry.key);\n }\n for (const entry of change.added) dirty.add(entry.key);\n for (const entry of change.updated) dirty.add(entry.key);\n updateOrder = Boolean(change.added.length || change.removed.length || change.order);\n }\n }\n\n for (let index = 0; index < keyed.length; index++) {\n if (revisions[index + 1] === currentRevisions[index + 1]) continue;\n const dependency = keyed[index];\n if (!dependency) {\n all = true;\n continue;\n }\n const sourceContext = evaluation.sources[index + 1];\n if (sourceContext.kind !== 'collection' || !sourceContext.change) {\n all = true;\n continue;\n }\n if (sourceContext.change.kind === 'reset') {\n all = true;\n continue;\n }\n const reverse = bindings[index]!.reverse;\n for (const transition of sourceContext.change.added) {\n for (const outputKey of reverse.get(transition.key) ?? []) dirty.add(outputKey);\n }\n for (const transition of sourceContext.change.updated) {\n for (const outputKey of reverse.get(transition.key) ?? []) dirty.add(outputKey);\n }\n for (const transition of sourceContext.change.removed) {\n for (const outputKey of reverse.get(transition.key) ?? []) dirty.add(outputKey);\n }\n }\n\n if (all) for (const key of driver.read.ids()) dirty.add(key);\n for (const key of dirty) if (driver.read.has(key)) project(key);\n if (updateOrder) output.output.order(driver.read.ids());\n revisions = Object.freeze(currentRevisions);\n },\n release: () => {\n clearBindings();\n revisions = Object.freeze([]);\n },\n };\n },\n name: 'derive.keyed',\n });\n return projection as KeyedProjection<K, T>;\n}\n\nexport const derive = Object.assign(createValueDerive, { keyed: createKeyedDerive });\n","import type { CollectionChange } from '../contract';\n\ntype Added<K extends string, V> = { readonly key: K; readonly after: V };\ntype Updated<K extends string, V> = {\n readonly key: K;\n readonly before: V;\n readonly after: V;\n};\ntype Removed<K extends string, V> = { readonly key: K; readonly before: V };\n\nconst commonOrderChanged = <K extends string>(\n before: readonly K[],\n after: readonly K[],\n added: ReadonlySet<K>,\n removed: ReadonlySet<K>\n): boolean => {\n const beforeCommon = before.filter(key => !removed.has(key));\n const afterCommon = after.filter(key => !added.has(key));\n return beforeCommon.some((key, index) => afterCommon[index] !== key);\n};\n\n/** Builds the canonical incremental CollectionChange from already-known net transitions. */\nexport const createCollectionChange = <K extends string, V>(input: {\n readonly added: readonly Added<K, V>[];\n readonly updated: readonly Updated<K, V>[];\n readonly removed: readonly Removed<K, V>[];\n readonly beforeOrder: readonly K[];\n readonly afterOrder: readonly K[];\n}): CollectionChange<K, V> | undefined => {\n const addedKeys = new Set(input.added.map(entry => entry.key));\n const removedKeys = new Set(input.removed.map(entry => entry.key));\n const orderChanged =\n input.beforeOrder !== input.afterOrder &&\n commonOrderChanged(input.beforeOrder, input.afterOrder, addedKeys, removedKeys);\n if (!input.added.length && !input.updated.length && !input.removed.length && !orderChanged)\n return undefined;\n return Object.freeze({\n kind: 'incremental' as const,\n added: Object.freeze([...input.added]),\n updated: Object.freeze([...input.updated]),\n removed: Object.freeze([...input.removed]),\n ...(orderChanged\n ? {\n order: Object.freeze({\n before: Object.freeze([...input.beforeOrder]),\n after: Object.freeze([...input.afterOrder]),\n }),\n }\n : {}),\n });\n};\n\n/** Exact fallback diff between two published map-like snapshots. */\nexport const diffCollection = <K extends string, V>(\n previous: ReadonlyMap<K, V>,\n current: ReadonlyMap<K, V>,\n isEqual: (previous: V, next: V) => boolean = Object.is\n): CollectionChange<K, V> | undefined => {\n const added: Added<K, V>[] = [];\n const updated: Updated<K, V>[] = [];\n const removed: Removed<K, V>[] = [];\n for (const [key, before] of previous) {\n if (!current.has(key)) removed.push({ key, before });\n else {\n const after = current.get(key) as V;\n if (!isEqual(before, after)) updated.push({ key, before, after });\n }\n }\n for (const [key, after] of current) if (!previous.has(key)) added.push({ key, after });\n return createCollectionChange({\n added,\n updated,\n removed,\n beforeOrder: [...previous.keys()],\n afterOrder: [...current.keys()],\n });\n};\n\nexport const collectionChangedKeys = <K extends string, V>(\n change: CollectionChange<K, V>\n): ReadonlySet<K> =>\n change.kind === 'reset'\n ? new Set<K>()\n : new Set([\n ...change.added.map(entry => entry.key),\n ...change.updated.map(entry => entry.key),\n ...change.removed.map(entry => entry.key),\n ]);\n\nexport const collectionHasStructuralChange = <K extends string, V>(\n change: CollectionChange<K, V>\n): boolean =>\n change.kind === 'reset' || Boolean(change.added.length || change.removed.length || change.order);\n\nexport const collectionHasAnyChange = <K extends string, V>(\n change: CollectionChange<K, V>\n): boolean =>\n change.kind === 'reset' ||\n Boolean(change.added.length || change.updated.length || change.removed.length || change.order);\n","import { profile } from '../../profile';\n\ntype IndexNode<K extends string, V> = {\n readonly key: K;\n readonly value: V;\n readonly height: number;\n readonly left?: IndexNode<K, V>;\n readonly right?: IndexNode<K, V>;\n};\n\nconst height = <K extends string, V>(node: IndexNode<K, V> | undefined): number =>\n node?.height ?? 0;\n\nconst node = <K extends string, V>(\n key: K,\n value: V,\n left?: IndexNode<K, V>,\n right?: IndexNode<K, V>\n): IndexNode<K, V> => {\n profile.collectionIndex.node();\n return Object.freeze({\n key,\n value,\n left,\n right,\n height: Math.max(height(left), height(right)) + 1,\n });\n};\n\nconst rotateLeft = <K extends string, V>(current: IndexNode<K, V>): IndexNode<K, V> => {\n const right = current.right!;\n return node(\n right.key,\n right.value,\n node(current.key, current.value, current.left, right.left),\n right.right\n );\n};\n\nconst rotateRight = <K extends string, V>(current: IndexNode<K, V>): IndexNode<K, V> => {\n const left = current.left!;\n return node(\n left.key,\n left.value,\n left.left,\n node(current.key, current.value, left.right, current.right)\n );\n};\n\nconst rebalance = <K extends string, V>(current: IndexNode<K, V>): IndexNode<K, V> => {\n const balance = height(current.left) - height(current.right);\n if (balance > 1) {\n if (height(current.left!.left) < height(current.left!.right))\n return rotateRight(\n node(current.key, current.value, rotateLeft(current.left!), current.right)\n );\n return rotateRight(current);\n }\n if (balance < -1) {\n if (height(current.right!.right) < height(current.right!.left))\n return rotateLeft(\n node(current.key, current.value, current.left, rotateRight(current.right!))\n );\n return rotateLeft(current);\n }\n return current;\n};\n\nconst setNode = <K extends string, V>(\n current: IndexNode<K, V> | undefined,\n key: K,\n value: V\n): IndexNode<K, V> => {\n if (!current) return node(key, value);\n if (key === current.key) return node(key, value, current.left, current.right);\n if (key < current.key)\n return rebalance(\n node(current.key, current.value, setNode(current.left, key, value), current.right)\n );\n return rebalance(\n node(current.key, current.value, current.left, setNode(current.right, key, value))\n );\n};\n\nconst minNode = <K extends string, V>(current: IndexNode<K, V>): IndexNode<K, V> =>\n current.left ? minNode(current.left) : current;\n\nconst removeNode = <K extends string, V>(\n current: IndexNode<K, V> | undefined,\n key: K\n): IndexNode<K, V> | undefined => {\n if (!current) return undefined;\n if (key < current.key)\n return rebalance(\n node(current.key, current.value, removeNode(current.left, key), current.right)\n );\n if (key > current.key)\n return rebalance(\n node(current.key, current.value, current.left, removeNode(current.right, key))\n );\n if (!current.left) return current.right;\n if (!current.right) return current.left;\n const next = minNode(current.right);\n return rebalance(node(next.key, next.value, current.left, removeNode(current.right, next.key)));\n};\n\nconst fromSorted = <K extends string, V>(\n entries: readonly (readonly [K, V])[],\n start = 0,\n end = entries.length\n): IndexNode<K, V> | undefined => {\n if (start >= end) return undefined;\n const middle = (start + end) >> 1;\n const [key, value] = entries[middle];\n return node(key, value, fromSorted(entries, start, middle), fromSorted(entries, middle + 1, end));\n};\n\n/** Immutable keyed lookup used to keep published collection snapshots durable across revisions. */\nexport class PersistentKeyedIndex<K extends string, V> {\n private constructor(private readonly root?: IndexNode<K, V>) {}\n\n static empty<K extends string, V>(): PersistentKeyedIndex<K, V> {\n return new PersistentKeyedIndex<K, V>();\n }\n\n static from<K extends string, V>(entries: Iterable<readonly [K, V]>): PersistentKeyedIndex<K, V> {\n const sorted = [...entries].sort(([left], [right]) =>\n left < right ? -1 : left > right ? 1 : 0\n );\n profile.collectionIndex.build(sorted.length);\n return new PersistentKeyedIndex(fromSorted(sorted));\n }\n\n get(key: K): V | undefined {\n let current = this.root;\n while (current) {\n if (key === current.key) return current.value;\n current = key < current.key ? current.left : current.right;\n }\n return undefined;\n }\n\n has(key: K): boolean {\n let current = this.root;\n while (current) {\n if (key === current.key) return true;\n current = key < current.key ? current.left : current.right;\n }\n return false;\n }\n\n set(key: K, value: V): PersistentKeyedIndex<K, V> {\n return new PersistentKeyedIndex(setNode(this.root, key, value));\n }\n\n remove(key: K): PersistentKeyedIndex<K, V> {\n return new PersistentKeyedIndex(removeNode(this.root, key));\n }\n}\n","import { profile } from '../../profile';\nimport { createCollectionChange } from '../collection/change';\nimport { PersistentKeyedIndex } from '../collection/index';\nimport type {\n CollectionChange,\n CollectionContext,\n CollectionDraft,\n CollectionRead,\n} from '../contract';\nimport {\n assertScope,\n type OutputRecord,\n type ProcessorRecord,\n type ProducerRecord,\n} from '../graph/scheduler';\n\ntype Entry<V> = { readonly present: true; readonly value: V } | { readonly present: false };\n\ntype PublishedCollection<K extends string, V> = {\n get(key: K): V | undefined;\n has(key: K): boolean;\n keys(): IterableIterator<K>;\n size(): number;\n ids(): readonly K[];\n read(check: () => void): CollectionRead<K, V>;\n publish(staged: ReadonlyMap<K, Entry<V>>, ids: readonly K[], reset: boolean): void;\n release(): void;\n};\n\nconst createPublishedCollection = <K extends string, V>(): PublishedCollection<K, V> => {\n const values = new Map<K, V>();\n let ids: readonly K[] = Object.freeze([]);\n let index = PersistentKeyedIndex.empty<K, V>();\n\n return {\n get: key => values.get(key),\n has: key => values.has(key),\n keys: () => values.keys(),\n size: () => values.size,\n ids: () => ids,\n read: check => {\n const snapshotIndex = index;\n const snapshotIds = ids;\n return Object.freeze({\n get: key => {\n check();\n return snapshotIndex.get(key);\n },\n has: key => {\n check();\n return snapshotIndex.has(key);\n },\n ids: () => {\n check();\n return snapshotIds;\n },\n });\n },\n publish: (staged, nextIds, reset) => {\n if (reset) {\n const entries: [K, V][] = [];\n for (const [key, entry] of staged) if (entry.present) entries.push([key, entry.value]);\n index = PersistentKeyedIndex.from(entries);\n values.clear();\n } else {\n for (const [key, entry] of staged)\n index = entry.present ? index.set(key, entry.value) : index.remove(key);\n }\n for (const [key, entry] of staged) {\n if (entry.present) values.set(key, entry.value);\n else values.delete(key);\n }\n ids = nextIds;\n },\n release: () => {\n values.clear();\n ids = Object.freeze([]);\n index = PersistentKeyedIndex.empty<K, V>();\n },\n };\n};\n\nexport type CollectionOutputEvaluation<K extends string, V> = {\n readonly previous: CollectionRead<K, V>;\n readonly next: CollectionRead<K, V>;\n readonly output: CollectionDraft<K, V>;\n};\n\nexport type CollectionOutputState<K extends string, V> = Omit<\n OutputRecord,\n 'context' | 'current'\n> & {\n begin(active: () => boolean, initialize: boolean): CollectionOutputEvaluation<K, V>;\n seal(reset: boolean, isEqual: (previous: V, next: V) => boolean): boolean;\n context(active: () => boolean): CollectionContext<K, V>;\n current(): CollectionRead<K, V>;\n publish(): void;\n};\n\ntype CollectionOutputBinding = {\n owner(): ProducerRecord;\n check(): void;\n cause(): unknown;\n};\n\n/** Owns staged keyed intent, exact transitions and published collection state. */\nexport const createCollectionOutput = <K extends string, V>(\n binding: CollectionOutputBinding\n): CollectionOutputState<K, V> => {\n const published = createPublishedCollection<K, V>();\n let staged = new Map<K, Entry<V>>();\n let nextIds = published.ids();\n let change: CollectionChange<K, V> | undefined;\n let initialized = false;\n let reset = false;\n let revision = 0;\n let explicitOrder: readonly K[] | undefined;\n let cleared = false;\n const listeners = new Set<() => void>();\n const consumers = new Set<ProcessorRecord>();\n\n const hasNext = (key: K): boolean =>\n staged.has(key) ? staged.get(key)!.present : !cleared && published.has(key);\n\n const getNext = (key: K): V | undefined => {\n const entry = staged.get(key);\n return entry\n ? entry.present\n ? entry.value\n : undefined\n : cleared\n ? undefined\n : published.get(key);\n };\n\n const deriveIds = (): readonly K[] => {\n const result = cleared ? [] : published.ids().filter(hasNext);\n for (const [key, entry] of staged)\n if (entry.present && (cleared || !published.has(key))) result.push(key);\n return result;\n };\n\n const begin = (active: () => boolean, initialize: boolean): CollectionOutputEvaluation<K, V> => {\n staged = new Map();\n nextIds = published.ids();\n change = undefined;\n explicitOrder = undefined;\n cleared = initialize;\n reset = initialize;\n const read = (next: boolean): CollectionRead<K, V> => ({\n get: key => {\n assertScope(active);\n return next ? getNext(key) : published.get(key);\n },\n has: key => {\n assertScope(active);\n return next ? hasNext(key) : published.has(key);\n },\n ids: () => {\n assertScope(active);\n return next\n ? Object.freeze(explicitOrder ? [...explicitOrder] : [...deriveIds()])\n : published.ids();\n },\n });\n const output: CollectionDraft<K, V> = {\n set: (key, value) => {\n assertScope(active);\n if (typeof key !== 'string') throw new TypeError('Projection keys must be strings.');\n staged.set(key, { present: true, value });\n },\n remove: key => {\n assertScope(active);\n staged.set(key, { present: false });\n },\n order: order => {\n assertScope(active);\n explicitOrder = Object.freeze([...order]);\n },\n };\n return { previous: read(false), next: read(true), output };\n };\n\n const seal = (nextReset: boolean, isEqual: (previous: V, next: V) => boolean): boolean => {\n if (cleared)\n for (const key of published.keys()) if (!staged.has(key)) staged.set(key, { present: false });\n\n profile.projection('touchedKeys', staged.size);\n const added = new Set<K>();\n const removed = new Set<K>();\n const updated = new Set<K>();\n for (const [key, entry] of staged) {\n const existed = published.has(key);\n if (entry.present) {\n if (!existed) added.add(key);\n else if (!isEqual(published.get(key) as V, entry.value)) updated.add(key);\n else if (!nextReset) staged.delete(key);\n } else if (existed) removed.add(key);\n else staged.delete(key);\n }\n\n const ids = published.ids();\n if (explicitOrder || added.size || removed.size) {\n const order = explicitOrder ?? [...ids.filter(key => !removed.has(key)), ...added];\n const seen = new Set(order);\n if (\n seen.size !== order.length ||\n order.length !== published.size() + added.size - removed.size ||\n order.some(key => !hasNext(key))\n )\n throw new TypeError('Projection order must contain every key exactly once.');\n nextIds =\n ids.length === order.length && ids.every((key, index) => key === order[index])\n ? ids\n : Object.freeze([...order]);\n } else nextIds = ids;\n\n const changedKeys = new Set<K>();\n added.forEach(key => changedKeys.add(key));\n removed.forEach(key => changedKeys.add(key));\n updated.forEach(key => changedKeys.add(key));\n profile.projection('changedKeys', changedKeys.size);\n const addedEntries: { readonly key: K; readonly after: V }[] = [];\n const updatedEntries: { readonly key: K; readonly before: V; readonly after: V }[] = [];\n const removedEntries: { readonly key: K; readonly before: V }[] = [];\n for (const key of changedKeys) {\n const beforePresent = published.has(key);\n const afterPresent = hasNext(key);\n if (beforePresent === afterPresent) {\n if (!beforePresent) continue;\n if (isEqual !== Object.is && isEqual(published.get(key) as V, getNext(key) as V)) continue;\n }\n if (!beforePresent) addedEntries.push({ key, after: getNext(key) as V });\n else if (!afterPresent) removedEntries.push({ key, before: published.get(key) as V });\n else\n updatedEntries.push({\n key,\n before: published.get(key) as V,\n after: getNext(key) as V,\n });\n }\n\n change = nextReset\n ? Object.freeze({ kind: 'reset' as const })\n : createCollectionChange({\n added: addedEntries,\n updated: updatedEntries,\n removed: removedEntries,\n beforeOrder: ids,\n afterOrder: nextIds,\n });\n reset = nextReset;\n return change !== undefined;\n };\n\n const context = (active: () => boolean, cause: unknown): CollectionContext<K, V> =>\n Object.freeze({\n kind: 'collection' as const,\n read: {\n get: key => {\n assertScope(active);\n return getNext(key);\n },\n has: key => {\n assertScope(active);\n return hasNext(key);\n },\n ids: () => {\n assertScope(active);\n return nextIds;\n },\n },\n change,\n revision,\n reset,\n cause,\n });\n\n return {\n kind: 'collection',\n get owner() {\n return binding.owner();\n },\n begin,\n seal,\n context: active => context(active, binding.cause()),\n current: () => published.read(binding.check),\n revision: () => revision,\n reset: () => reset,\n publish: () => {\n if (change) published.publish(staged, nextIds, change.kind === 'reset');\n if (change && initialized) revision++;\n initialized = true;\n },\n emit: call => {\n Array.from(listeners).forEach(listener => call(listener));\n },\n hasConsumers: () => consumers.size > 0,\n forEachConsumer: run => consumers.forEach(run),\n attachConsumer: consumer => consumers.add(consumer),\n detachConsumer: consumer => consumers.delete(consumer),\n clear: () => {\n staged.clear();\n nextIds = published.ids();\n change = undefined;\n reset = false;\n explicitOrder = undefined;\n cleared = false;\n },\n release: () => {\n published.release();\n staged.clear();\n listeners.clear();\n consumers.clear();\n nextIds = Object.freeze([]);\n change = undefined;\n initialized = false;\n revision = 0;\n reset = false;\n explicitOrder = undefined;\n cleared = false;\n },\n subscribe: listener => {\n binding.check();\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n };\n};\n","import { profile } from '../../profile';\nimport type { ValueContext } from '../contract';\nimport {\n assertScope,\n type OutputRecord,\n type ProcessorRecord,\n type ProducerRecord,\n} from '../graph/scheduler';\n\nconst unset = Symbol('projection-value-unset');\n\nexport type ValueOutputEvaluation<T> = {\n readonly previous: T | undefined;\n readonly next: () => T | undefined;\n readonly output: { set(value: T): void };\n};\n\nexport type ValueOutputState<T> = OutputRecord & {\n begin(active: () => boolean, initialize: boolean): ValueOutputEvaluation<T>;\n seal(reset: boolean, isEqual: (previous: T, next: T) => boolean): boolean;\n publish(): void;\n};\n\ntype ValueOutputBinding = {\n owner(): ProducerRecord;\n check(): void;\n cause(): unknown;\n};\n\n/** Owns staged and published state for one scalar Projection output. */\nexport const createValueOutput = <T>(binding: ValueOutputBinding): ValueOutputState<T> => {\n let value!: T;\n let staged: T | typeof unset = unset;\n let next!: T;\n let initialized = false;\n let revision = 0;\n let changed = false;\n let reset = false;\n const listeners = new Set<() => void>();\n const consumers = new Set<ProcessorRecord>();\n\n const begin = (active: () => boolean, initialize: boolean): ValueOutputEvaluation<T> => {\n staged = unset;\n next = value;\n changed = false;\n reset = initialize;\n return {\n previous: initialized ? value : undefined,\n next: () => {\n assertScope(active);\n if (staged !== unset) return staged;\n return initialize ? undefined : initialized ? value : undefined;\n },\n output: Object.freeze({\n set: (candidate: T) => {\n assertScope(active);\n staged = candidate;\n },\n }),\n };\n };\n\n const seal = (nextReset: boolean, isEqual: (previous: T, next: T) => boolean): boolean => {\n if (reset && staged === unset)\n throw new TypeError('Value output must be initialized on reset.');\n if (staged === unset) {\n reset = nextReset;\n changed = false;\n next = value;\n return false;\n }\n const candidate = staged;\n changed = !initialized || !isEqual(value, candidate);\n next = changed ? candidate : value;\n reset = nextReset;\n return changed;\n };\n\n return {\n kind: 'value',\n get owner() {\n return binding.owner();\n },\n begin,\n seal,\n context: active => {\n assertScope(active);\n return Object.freeze({\n kind: 'value' as const,\n value: next,\n revision,\n reset,\n cause: binding.cause(),\n });\n },\n current: () => {\n binding.check();\n return value;\n },\n revision: () => revision,\n reset: () => reset,\n publish: () => {\n if (changed && initialized) revision++;\n if (changed) value = next;\n initialized = true;\n },\n emit: call => {\n profile.materialized.notification();\n Array.from(listeners).forEach(listener => call(listener));\n },\n hasConsumers: () => consumers.size > 0,\n forEachConsumer: run => consumers.forEach(run),\n attachConsumer: consumer => consumers.add(consumer),\n detachConsumer: consumer => consumers.delete(consumer),\n clear: () => {\n staged = unset;\n next = value;\n changed = false;\n reset = false;\n },\n release: () => {\n listeners.clear();\n consumers.clear();\n staged = unset;\n value = next = undefined as T;\n initialized = false;\n revision = 0;\n changed = false;\n reset = false;\n },\n subscribe: listener => {\n binding.check();\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n };\n};\n","import { profile } from '../../profile';\nimport { createCollectionOutput, type CollectionOutputState } from '../output/collection';\nimport { ProjectionDisposedError } from '../contract';\nimport type {\n CollectionOutputEvaluation,\n OutputDefinition,\n OutputEvaluation,\n ProcessorDefinition,\n ProcessorInstance,\n ValueOutputEvaluation,\n} from '../definition';\nimport {\n assertSynchronous,\n type OutputRecord,\n type ProcessorRecord,\n type Scheduler,\n} from './scheduler';\nimport { createValueOutput, type ValueOutputState } from '../output/value';\n\ntype BoundOutput =\n | {\n readonly kind: 'value';\n readonly definition: Extract<OutputDefinition, { readonly kind: 'value' }>;\n readonly state: ValueOutputState<unknown>;\n }\n | {\n readonly kind: 'collection';\n readonly definition: Extract<OutputDefinition, { readonly kind: 'collection' }>;\n readonly state: CollectionOutputState<string, unknown>;\n };\n\n/** Materializes every derive/incremental/group definition through one processor lifecycle. */\nexport const createProcessor = (\n scheduler: Scheduler,\n definition: ProcessorDefinition,\n dependencies: readonly OutputRecord[]\n): ProcessorRecord => {\n scheduler.assertIdle();\n let processor!: ProcessorRecord;\n let instance: ProcessorInstance | undefined;\n let cause: unknown;\n\n const check = () => {\n if (!scheduler.active || processor.disposed) throw new ProjectionDisposedError();\n if (processor.fault) throw processor.fault;\n };\n\n const bound: readonly BoundOutput[] = definition.outputs.map(outputDefinition => {\n if (outputDefinition.kind === 'value') {\n const state = createValueOutput<unknown>({\n owner: () => processor,\n check,\n cause: () => cause,\n });\n return { kind: 'value', definition: outputDefinition, state };\n }\n const state = createCollectionOutput<string, unknown>({\n owner: () => processor,\n check,\n cause: () => cause,\n });\n return { kind: 'collection', definition: outputDefinition, state };\n });\n\n const begin = (active: () => boolean, initialize: boolean): readonly OutputEvaluation[] =>\n Object.freeze(\n bound.map(entry => {\n if (entry.kind === 'value') {\n const evaluation = entry.state.begin(active, initialize);\n return Object.freeze({ kind: 'value' as const, ...evaluation }) as ValueOutputEvaluation;\n }\n const evaluation = entry.state.begin(active, initialize);\n return Object.freeze({\n kind: 'collection' as const,\n ...evaluation,\n }) as CollectionOutputEvaluation;\n })\n );\n\n const seal = (reset: boolean): readonly OutputRecord[] => {\n const changed: OutputRecord[] = [];\n for (const entry of bound) {\n const didChange = entry.state.seal(reset, entry.definition.equality);\n if (didChange) changed.push(entry.state);\n }\n return Object.freeze(changed);\n };\n\n const run = (reset: boolean, runCause: unknown, recreate = false): readonly OutputRecord[] => {\n cause = runCause;\n let active = true;\n try {\n const scopeActive = () => active;\n const sources = Object.freeze(dependencies.map(output => output.context(scopeActive)));\n const outputs = begin(scopeActive, reset);\n if (recreate && instance) {\n instance.release?.();\n instance = undefined;\n }\n if (!instance) instance = definition.create();\n profile.materialized[reset ? 'rebuilt' : 'updated']();\n const result = instance.evaluate({ reset, cause: runCause, sources, outputs });\n assertSynchronous(result);\n return seal(reset);\n } finally {\n active = false;\n }\n };\n\n const order = scheduler.order();\n processor = {\n kind: 'processor',\n order,\n name: definition.name ? `${definition.name} (${order})` : `projection-${order}`,\n dependencies: Object.freeze([...dependencies]),\n outputs: Object.freeze(bound.map(entry => entry.state)),\n fault: undefined,\n disposed: false,\n evaluate: run,\n publish: () => bound.forEach(entry => entry.state.publish()),\n clear: () => {\n bound.forEach(entry => entry.state.clear());\n cause = undefined;\n },\n release: () => {\n const current = instance;\n instance = undefined;\n const failures: unknown[] = [];\n try {\n current?.release?.();\n } catch (error) {\n failures.push(error);\n }\n for (const entry of bound) {\n try {\n entry.state.release();\n } catch (error) {\n failures.push(error);\n }\n }\n cause = undefined;\n if (failures.length) throw failures[0];\n },\n };\n\n try {\n scheduler.initialize(() => {\n const invalid = dependencies.find(output => output.owner.fault || output.owner.disposed);\n if (invalid) throw invalid.owner.fault ?? new ProjectionDisposedError();\n const changed = processor.evaluate(true, undefined);\n if (changed.length) processor.publish();\n processor.clear();\n });\n scheduler.addProcessor(processor);\n } catch (error) {\n processor.disposed = true;\n try {\n processor.release();\n } catch {\n /* Initialization failure retains priority. */\n }\n throw error;\n }\n return processor;\n};\n","import type { Unsubscribe } from '../../runtime/contract';\nimport {\n collectionChangedKeys,\n collectionHasAnyChange,\n collectionHasStructuralChange,\n diffCollection,\n} from '../collection/change';\nimport type { CollectionChange } from '../contract';\nimport type { Readable } from '../../readable';\n\nexport type ProjectionReadableSource<T> = {\n readonly kind: 'value' | 'collection';\n current(): T;\n revision(): number;\n subscribe(listener: (change?: CollectionChange<string, unknown>) => void): Unsubscribe;\n};\n\ntype SelectionTracker = {\n readonly keys: Set<string>;\n all: boolean;\n structure: boolean;\n};\n\ntype Selection = {\n readonly keys: ReadonlySet<string>;\n readonly all: boolean;\n readonly structure: boolean;\n};\n\nlet activeTracker: SelectionTracker | undefined;\n\nconst trackKey = (key: string): void => {\n activeTracker?.keys.add(key);\n};\n\nconst trackStructure = (): void => {\n if (activeTracker) activeTracker.structure = true;\n};\n\nconst trackAll = (): void => {\n if (activeTracker) activeTracker.all = true;\n};\n\nexport const isMapLike = (value: unknown): value is ReadonlyMap<string, unknown> =>\n value instanceof Map ||\n (value !== null &&\n typeof value === 'object' &&\n typeof (value as { get?: unknown }).get === 'function' &&\n typeof (value as { keys?: unknown }).keys === 'function' &&\n typeof (value as { entries?: unknown }).entries === 'function');\n\nconst trackedMap = <K extends string, V>(source: ReadonlyMap<K, V>): ReadonlyMap<K, V> => {\n const view: ReadonlyMap<K, V> = {\n get: key => {\n trackKey(key);\n return source.get(key);\n },\n has: key => {\n trackKey(key);\n return source.has(key);\n },\n get size() {\n trackStructure();\n return source.size;\n },\n keys: () => {\n trackStructure();\n return source.keys();\n },\n values: () => {\n trackAll();\n return source.values();\n },\n entries: () => {\n trackAll();\n return source.entries();\n },\n forEach: (callback, thisArg) => {\n trackAll();\n source.forEach((value, key) => callback.call(thisArg, value, key, view));\n },\n [Symbol.iterator]: () => {\n trackAll();\n return source[Symbol.iterator]();\n },\n };\n return Object.freeze(view);\n};\n\nconst selectionAffects = (\n selection: Selection,\n change: CollectionChange<string, unknown> | undefined\n): boolean => {\n if (!change || change.kind === 'reset') return true;\n if (selection.all && collectionHasAnyChange(change)) return true;\n if (selection.structure && collectionHasStructuralChange(change)) return true;\n const changedKeys = collectionChangedKeys(change);\n for (const key of selection.keys) if (changedKeys.has(key)) return true;\n return false;\n};\n\nexport const createDirectReadable = <T>(source: ProjectionReadableSource<T>): Readable<T> =>\n Object.freeze({\n current: source.current,\n revision: source.revision,\n subscribe: (listener: () => void) => source.subscribe(() => listener()),\n });\n\n/** Consumer-side selector tracking; it never mutates processor dependencies. */\nexport const createSelectorReadable = <T, R>(\n source: ProjectionReadableSource<T>,\n selector: (value: T) => R,\n equality: (previous: R, next: R) => boolean = Object.is\n): Readable<R> => {\n let initialized = false;\n let value!: R;\n let selectedRevision = 0;\n let sourceRevision = -1;\n let selection: Selection = Object.freeze({\n keys: new Set<string>(),\n all: true,\n structure: false,\n });\n let previousCollection: ReadonlyMap<string, unknown> | undefined;\n let unsubscribeSource: Unsubscribe | undefined;\n const listeners = new Set<() => void>();\n\n const updateCollectionSnapshot = (current?: T) => {\n const candidate = current ?? source.current();\n previousCollection = isMapLike(candidate) ? candidate : undefined;\n };\n\n const evaluate = (): boolean => {\n const tracker: SelectionTracker = { keys: new Set(), all: false, structure: false };\n const previousTracker = activeTracker;\n activeTracker = tracker;\n let current!: T;\n let next!: R;\n try {\n current = source.current();\n const selectedSource = isMapLike(current) ? (trackedMap(current) as unknown as T) : current;\n next = selector(selectedSource);\n } finally {\n activeTracker = previousTracker;\n }\n const nextSelection: Selection = Object.freeze({\n keys: new Set(tracker.keys),\n all: tracker.all || (isMapLike(current) && tracker.keys.size === 0 && !tracker.structure),\n structure: tracker.structure,\n });\n const changed = !initialized || !equality(value, next);\n if (changed) {\n if (initialized) selectedRevision++;\n value = next;\n }\n selection = nextSelection;\n initialized = true;\n sourceRevision = source.revision();\n updateCollectionSnapshot(current);\n return changed;\n };\n\n const ensureCurrent = (): R => {\n const revision = source.revision();\n if (!initialized || (!unsubscribeSource && sourceRevision !== revision)) evaluate();\n return value;\n };\n\n const onProjectionChange = (incoming?: CollectionChange<string, unknown>) => {\n let change = incoming;\n if (!change && previousCollection) {\n const current = source.current();\n if (isMapLike(current)) {\n change = diffCollection(previousCollection, current);\n previousCollection = current;\n if (!change) {\n sourceRevision = source.revision();\n return;\n }\n } else previousCollection = undefined;\n }\n if (!selectionAffects(selection, change)) {\n sourceRevision = source.revision();\n updateCollectionSnapshot();\n return;\n }\n if (evaluate()) Array.from(listeners).forEach(listener => listener());\n };\n\n const installSource = () => {\n if (!unsubscribeSource) unsubscribeSource = source.subscribe(onProjectionChange);\n };\n\n return Object.freeze({\n current: ensureCurrent,\n revision: () => {\n ensureCurrent();\n return selectedRevision;\n },\n subscribe: (listener: () => void) => {\n ensureCurrent();\n listeners.add(listener);\n installSource();\n return () => {\n listeners.delete(listener);\n if (!listeners.size && unsubscribeSource) {\n unsubscribeSource();\n unsubscribeSource = undefined;\n }\n };\n },\n });\n};\n","import * as sequence from '../../order/sequence';\nimport { profile } from '../../profile';\nimport type { DocumentNode, DocumentTreeNode } from '../../schema/model';\nimport { compiledShape } from '../../schema/layout';\nimport * as schemaValue from '../../schema/value';\nimport { installOwn, isRecord } from '../../value/record';\nimport type { DocumentDirty } from './dirty';\n\nconst hasDocumentDirty = (dirty: DocumentDirty): boolean =>\n dirty.replace ||\n dirty.order ||\n dirty.treeRoot ||\n dirty.treeNodes.size > 0 ||\n dirty.children.size > 0;\n\nconst equivalent = (node: DocumentNode, left: unknown, right: unknown): boolean =>\n node.kind === 'field' ? Object.is(left, right) : schemaValue.equalValue(node, left, right);\n\nconst replaceValue = (node: DocumentNode, previous: unknown, current: unknown): unknown =>\n equivalent(node, previous, current) ? previous : schemaValue.copyValue(node, current);\n\nconst cloneRecord = (value: Record<string, unknown>): Record<string, unknown> => {\n profile.copy.shallowRecord(Object.getOwnPropertyNames(value).length);\n return Object.create(\n Object.getPrototypeOf(value),\n Object.getOwnPropertyDescriptors(value)\n ) as Record<string, unknown>;\n};\n\nconst materializeRecordChild = (\n node: DocumentNode,\n previous: Record<string, unknown>,\n current: Record<string, unknown>,\n key: string,\n dirty: DocumentDirty\n):\n | { readonly changed: false }\n | { readonly changed: true; readonly present: boolean; readonly value: unknown } => {\n const before = Object.hasOwn(previous, key);\n const after = Object.hasOwn(current, key);\n if (!before && !after) return { changed: false };\n if (!after) return { changed: true, present: false, value: undefined };\n const next = before\n ? materializeDocumentValue(node, previous[key], current[key], dirty)\n : schemaValue.copyValue(node, current[key]);\n if (before && next === previous[key]) return { changed: false };\n return { changed: true, present: true, value: next };\n};\n\nconst materializeObject = (\n node: Extract<DocumentNode, { kind: 'object' | 'variant' }>,\n previous: Record<string, unknown>,\n current: Record<string, unknown>,\n dirty: DocumentDirty\n): unknown => {\n if (node.kind === 'variant' && previous[node.tag] !== current[node.tag])\n return replaceValue(node, previous, current);\n const layout = compiledShape(node, current);\n if (!layout) return replaceValue(node, previous, current);\n let result: Record<string, unknown> | undefined;\n for (const [key, childDirty] of dirty.children) {\n const member = layout.members.get(key);\n if (!member) return replaceValue(node, previous, current);\n const child = materializeRecordChild(member.node, previous, current, key, childDirty);\n if (!child.changed) continue;\n result ??= cloneRecord(previous);\n installOwn(result, key, child.present, child.value);\n }\n return result ?? previous;\n};\n\nconst materializeMap = (\n node: Extract<DocumentNode, { kind: 'map' }>,\n previous: Record<string, unknown>,\n current: Record<string, unknown>,\n dirty: DocumentDirty\n): unknown => {\n let result: Record<string, unknown> | undefined;\n for (const [key, childDirty] of dirty.children) {\n const child = materializeRecordChild(node.value, previous, current, key, childDirty);\n if (!child.changed) continue;\n result ??= cloneRecord(previous);\n installOwn(result, key, child.present, child.value);\n }\n return result ?? previous;\n};\n\nconst materializeTable = (\n node: Extract<DocumentNode, { kind: 'table' }>,\n previous: Record<string, unknown>,\n current: Record<string, unknown>,\n dirty: DocumentDirty\n): unknown => {\n if (!isRecord(previous.byId) || !isRecord(current.byId))\n return replaceValue(node, previous, current);\n const beforeById = previous.byId;\n const afterById = current.byId;\n let result: Record<string, unknown> | undefined;\n let nextById: Record<string, unknown> | undefined;\n for (const [key, childDirty] of dirty.children) {\n const child = materializeRecordChild(node.value, beforeById, afterById, key, childDirty);\n if (!child.changed) continue;\n nextById ??= cloneRecord(beforeById);\n installOwn(nextById, key, child.present, child.value);\n }\n if (nextById) {\n result = cloneRecord(previous);\n installOwn(result, 'byId', true, nextById);\n }\n if (dirty.order) {\n const beforeIds = previous.ids;\n const afterIds = current.ids;\n if (!Array.isArray(beforeIds) || !Array.isArray(afterIds))\n return replaceValue(node, previous, current);\n if (!sequence.equal(beforeIds as string[], afterIds as string[])) {\n result ??= cloneRecord(previous);\n installOwn(result, 'ids', true, [...(afterIds as string[])]);\n }\n }\n return result ?? previous;\n};\n\nconst materializeList = (\n node: Extract<DocumentNode, { kind: 'list' }>,\n previous: readonly unknown[],\n current: readonly unknown[],\n dirty: DocumentDirty\n): unknown => {\n if (dirty.order) {\n const before = sequence.listSequence(previous, node.keyOf);\n const after = sequence.listSequence(current, node.keyOf);\n const sameOrder = sequence.equal(before.order, after.order);\n let changed = !sameOrder;\n const result = new Array<unknown>(after.order.length);\n for (let index = 0; index < after.order.length; index++) {\n const key = after.order[index];\n const currentValue = after.values.get(key);\n if (!before.values.has(key)) {\n changed = true;\n result[index] = currentValue;\n continue;\n }\n const previousValue = before.values.get(key);\n const childDirty = dirty.children.get(key);\n const next = childDirty\n ? materializeDocumentValue(node.value, previousValue, currentValue, childDirty)\n : previousValue;\n changed ||= next !== previousValue;\n result[index] = next;\n }\n return changed ? result : previous;\n }\n\n let result: unknown[] | undefined;\n const before = sequence.indexedKeys(previous, node.keyOf);\n const after = sequence.indexedKeys(current, node.keyOf);\n for (const [key, childDirty] of dirty.children) {\n const previousIndex = before.index(key);\n const currentIndex = after.index(key);\n if (previousIndex < 0 || currentIndex < 0) return replaceValue(node, previous, current);\n const next = materializeDocumentValue(\n node.value,\n previous[previousIndex],\n current[currentIndex],\n childDirty\n );\n if (next === previous[previousIndex] && previousIndex === currentIndex) continue;\n result ??= [...previous];\n result[currentIndex] = next;\n }\n return result ?? previous;\n};\n\nconst materializeTree = (\n node: Extract<DocumentNode, { kind: 'tree' }>,\n previous: Record<string, unknown>,\n current: Record<string, unknown>,\n dirty: DocumentDirty\n): unknown => {\n if (!isRecord(previous.nodes) || !isRecord(current.nodes))\n return replaceValue(node, previous, current);\n let result: Record<string, unknown> | undefined;\n\n if (dirty.treeRoot) {\n const beforePresent = Object.hasOwn(previous, 'rootId');\n const afterPresent = Object.hasOwn(current, 'rootId');\n if (beforePresent !== afterPresent || !Object.is(previous.rootId, current.rootId)) {\n result = cloneRecord(previous);\n installOwn(result, 'rootId', afterPresent, current.rootId);\n }\n }\n\n let nodes: Record<string, unknown> | undefined;\n for (const id of dirty.treeNodes) {\n const beforePresent = Object.hasOwn(previous.nodes, id);\n const afterPresent = Object.hasOwn(current.nodes, id);\n const before = beforePresent\n ? (previous.nodes[id] as DocumentTreeNode<unknown, false> | DocumentTreeNode<unknown, true>)\n : undefined;\n const after = afterPresent\n ? (current.nodes[id] as DocumentTreeNode<unknown, false> | DocumentTreeNode<unknown, true>)\n : undefined;\n if (beforePresent === afterPresent && schemaValue.equalTreeNode(before, after)) continue;\n nodes ??= cloneRecord(previous.nodes);\n installOwn(nodes, id, afterPresent, after && schemaValue.copyTreeNode(after));\n }\n if (nodes) {\n result ??= cloneRecord(previous);\n installOwn(result, 'nodes', true, nodes);\n }\n return result ?? previous;\n};\n\nexport const materializeDocumentValue = (\n node: DocumentNode,\n previous: unknown,\n current: unknown,\n dirty: DocumentDirty\n): unknown => {\n if (!hasDocumentDirty(dirty)) return previous;\n if (dirty.replace || previous === undefined || current === undefined || node.kind === 'field')\n return replaceValue(node, previous, current);\n if (node.kind === 'object' || node.kind === 'variant') {\n if (!isRecord(previous) || !isRecord(current)) return replaceValue(node, previous, current);\n return materializeObject(node, previous, current, dirty);\n }\n if (node.kind === 'map') {\n if (!isRecord(previous) || !isRecord(current)) return replaceValue(node, previous, current);\n return materializeMap(node, previous, current, dirty);\n }\n if (node.kind === 'table') {\n if (!isRecord(previous) || !isRecord(current)) return replaceValue(node, previous, current);\n return materializeTable(node, previous, current, dirty);\n }\n if (node.kind === 'list') {\n if (!Array.isArray(previous) || !Array.isArray(current))\n return replaceValue(node, previous, current);\n return materializeList(node, previous, current, dirty);\n }\n if (!isRecord(previous) || !isRecord(current)) return replaceValue(node, previous, current);\n return materializeTree(node, previous, current, dirty);\n};\n","import * as relation from '../../address/relation';\nimport type { ChangeSet } from '../../changes';\nimport type { CollectionSelector, ValueSelector } from '../../schema/path';\n\nexport type DocumentDirty = {\n replace: boolean;\n order: boolean;\n treeRoot: boolean;\n readonly treeNodes: Set<string>;\n readonly children: Map<string, DocumentDirty>;\n};\n\nexport const createDocumentDirty = (): DocumentDirty => ({\n replace: false,\n order: false,\n treeRoot: false,\n treeNodes: new Set(),\n children: new Map(),\n});\n\nexport const clearDocumentDirty = (dirty: DocumentDirty): void => {\n dirty.replace = false;\n dirty.order = false;\n dirty.treeRoot = false;\n dirty.treeNodes.clear();\n dirty.children.clear();\n};\n\nconst locate = (dirty: DocumentDirty, path: readonly string[]): DocumentDirty | undefined => {\n let current = dirty;\n for (const key of path) {\n if (current.replace) return undefined;\n let child = current.children.get(key);\n if (!child) {\n child = createDocumentDirty();\n current.children.set(key, child);\n }\n current = child;\n }\n return current;\n};\n\nexport const markDocumentReplace = (dirty: DocumentDirty, path: readonly string[]): void => {\n const current = locate(dirty, path);\n if (!current) return;\n current.replace = true;\n current.order = false;\n current.treeRoot = false;\n current.treeNodes.clear();\n current.children.clear();\n};\n\nconst markDocumentOrder = (dirty: DocumentDirty, path: readonly string[]): void => {\n const current = locate(dirty, path);\n if (current && !current.replace) current.order = true;\n};\n\nconst markDocumentTree = (\n dirty: DocumentDirty,\n path: readonly string[],\n root: boolean,\n nodes: Iterable<string>\n): void => {\n const current = locate(dirty, path);\n if (!current || current.replace) return;\n current.treeRoot ||= root;\n for (const id of nodes) current.treeNodes.add(id);\n};\n\ntype DocumentCollectionPending = {\n reset: boolean;\n order: boolean;\n readonly entries: Map<string, DocumentDirty>;\n};\n\nexport const createCollectionPending = (): DocumentCollectionPending => ({\n reset: false,\n order: false,\n entries: new Map(),\n});\n\nexport const resetCollectionPending = (pending: DocumentCollectionPending): void => {\n pending.reset = true;\n pending.order = false;\n pending.entries.clear();\n};\n\nexport const clearCollectionPending = (pending: DocumentCollectionPending): void => {\n pending.reset = false;\n pending.order = false;\n pending.entries.clear();\n};\n\nconst dirtyEntry = (pending: DocumentCollectionPending, key: string): DocumentDirty => {\n let dirty = pending.entries.get(key);\n if (!dirty) {\n dirty = createDocumentDirty();\n pending.entries.set(key, dirty);\n }\n return dirty;\n};\n\nexport const mergeValueChanges = (\n selector: ValueSelector,\n dirty: DocumentDirty,\n changes: ChangeSet\n): void => {\n if (selector.tree) return;\n const at = selector.address;\n for (const change of changes.changes) {\n if (change.kind === 'reset') {\n markDocumentReplace(dirty, []);\n return;\n }\n if (change.kind === 'members') {\n for (const member of change.members) {\n const changed = [...change.at, member.key];\n if (relation.contains(changed, at)) markDocumentReplace(dirty, []);\n else if (relation.contains(at, changed))\n markDocumentReplace(dirty, changed.slice(at.length));\n }\n if (change.order && relation.contains(at, change.at))\n markDocumentOrder(dirty, change.at.slice(at.length));\n continue;\n }\n if (relation.contains(at, change.at))\n markDocumentTree(\n dirty,\n change.at.slice(at.length),\n change.before !== change.after,\n change.nodes.map(node => node.id)\n );\n }\n};\n\nexport const mergeCollectionChanges = (\n selector: CollectionSelector,\n pending: DocumentCollectionPending,\n changes: ChangeSet\n): void => {\n if (pending.reset) return;\n const at = selector.address;\n for (const change of changes.changes) {\n if (change.kind === 'reset') {\n resetCollectionPending(pending);\n return;\n }\n\n if (selector.tree?.kind === 'nodes') {\n if (change.kind === 'members') {\n for (const member of change.members) {\n const changed = [...change.at, member.key];\n if (relation.contains(changed, at)) {\n resetCollectionPending(pending);\n return;\n }\n }\n } else if (change.at.length === at.length && relation.contains(change.at, at)) {\n for (const node of change.nodes) {\n markDocumentReplace(dirtyEntry(pending, node.id), []);\n pending.order ||= node.kind !== 'updated';\n }\n } else if (relation.contains(change.at, at)) {\n resetCollectionPending(pending);\n return;\n }\n continue;\n }\n\n if (change.kind === 'members') {\n for (const member of change.members) {\n const changed = [...change.at, member.key];\n if (relation.contains(changed, at)) {\n resetCollectionPending(pending);\n return;\n }\n if (!relation.contains(at, changed)) continue;\n const relative = changed.slice(at.length);\n if (!relative.length) {\n resetCollectionPending(pending);\n return;\n }\n const entry = dirtyEntry(pending, relative[0]);\n markDocumentReplace(entry, relative.slice(1));\n if (relative.length === 1 && member.kind !== 'updated') pending.order = true;\n }\n if (change.order && relation.contains(at, change.at)) {\n const relative = change.at.slice(at.length);\n if (!relative.length) pending.order = true;\n else markDocumentOrder(dirtyEntry(pending, relative[0]), relative.slice(1));\n }\n continue;\n }\n\n if (!relation.contains(at, change.at)) continue;\n const relative = change.at.slice(at.length);\n if (!relative.length) {\n resetCollectionPending(pending);\n return;\n }\n markDocumentTree(\n dirtyEntry(pending, relative[0]),\n relative.slice(1),\n change.before !== change.after,\n change.nodes.map(node => node.id)\n );\n }\n};\n","import { profile } from '../../profile';\nimport type { Unsubscribe } from '../../runtime/contract';\nimport { createCollectionOutput, type CollectionOutputState } from '../output/collection';\nimport type { CollectionRead } from '../contract';\nimport { ProjectionDisposedError, ProjectionError } from '../contract';\nimport type { OutputRecord, Scheduler, SourceBoundaryRecord } from '../graph/scheduler';\nimport { createValueOutput, type ValueOutputState } from '../output/value';\nimport type { CollectionInputDraft } from '../definition';\n\nexport type SourceWrite =\n | { readonly kind: 'value'; set(value: unknown): void }\n | {\n readonly kind: 'collection';\n update(run: (draft: CollectionInputDraft<string, unknown>) => void): void;\n };\n\nexport type SourceMaterialization = {\n readonly producer: SourceBoundaryRecord;\n readonly output: OutputRecord;\n readonly write?: SourceWrite;\n};\n\nexport type SourceMark = { readonly reset?: boolean; readonly cause?: unknown };\ntype CollectionMark = SourceMark & {\n readonly candidates?: Iterable<string>;\n readonly fullScan?: boolean;\n readonly orderMayChange?: boolean;\n};\n\nexport type ValueBoundary = SourceMaterialization & {\n readonly mark: (metadata?: SourceMark) => void;\n readonly fail: (cause: unknown) => void;\n readonly detach: (cleanup: Unsubscribe) => void;\n};\n\nexport type CollectionBoundary = SourceMaterialization & {\n readonly mark: (metadata?: CollectionMark) => void;\n readonly fail: (cause: unknown) => void;\n readonly detach: (cleanup: Unsubscribe) => void;\n};\n\nconst sourceError = (cause: unknown): ProjectionError => new ProjectionError('source', cause);\n\nexport const createValueBoundary = (\n scheduler: Scheduler,\n name: string,\n initial: unknown,\n equality: (previous: unknown, next: unknown) => boolean,\n prepare: (previous: unknown) => unknown,\n clearSource: (failed: boolean) => void\n): ValueBoundary => {\n let boundary!: SourceBoundaryRecord;\n let pendingReset = false;\n let pendingCause: unknown;\n let contextCause: unknown;\n let recovering = false;\n let cleanup: Unsubscribe | undefined;\n\n const check = () => {\n if (!scheduler.active || boundary.disposed) throw new ProjectionDisposedError();\n if (boundary.fault) throw boundary.fault;\n };\n const state: ValueOutputState<unknown> = createValueOutput({\n owner: () => boundary,\n check,\n cause: () => contextCause,\n });\n const output: OutputRecord = state;\n\n boundary = {\n kind: 'source',\n name,\n outputs: Object.freeze([output]) as readonly [OutputRecord],\n fault: undefined,\n disposed: false,\n pendingCause: () => pendingCause,\n recovering: () => recovering,\n prepare: cause => {\n contextCause = cause;\n let active = true;\n try {\n const evaluation = state.begin(() => active, pendingReset);\n evaluation.output.set(prepare(evaluation.previous));\n const changed = state.seal(pendingReset, equality);\n recovering = false;\n return { changed, force: pendingReset };\n } finally {\n active = false;\n }\n },\n publish: state.publish,\n clear: () => {\n const failed = boundary.fault !== undefined;\n state.clear();\n pendingReset = false;\n pendingCause = undefined;\n contextCause = undefined;\n recovering = false;\n clearSource(failed);\n },\n release: () => {\n const detach = cleanup;\n cleanup = undefined;\n const failures: unknown[] = [];\n try {\n detach?.();\n } catch (error) {\n failures.push(error);\n }\n try {\n state.release();\n } catch (error) {\n failures.push(error);\n }\n if (failures.length) throw failures[0];\n },\n };\n\n try {\n scheduler.initialize(() => {\n let active = true;\n try {\n const evaluation = state.begin(() => active, true);\n evaluation.output.set(initial);\n state.seal(true, equality);\n state.publish();\n state.clear();\n } finally {\n active = false;\n }\n });\n scheduler.addSource(boundary);\n } catch (error) {\n boundary.disposed = true;\n try {\n boundary.release();\n } catch {\n /* Initialization failure retains priority. */\n }\n throw error;\n }\n\n const mark = (metadata: SourceMark = {}) => {\n scheduler.assertIdle();\n pendingReset ||= metadata.reset ?? false;\n if (metadata.cause !== undefined) pendingCause ??= metadata.cause;\n if (boundary.fault) recovering = true;\n scheduler.capture(boundary);\n };\n const fail = (cause: unknown) => {\n boundary.fault = sourceError(cause);\n recovering = false;\n scheduler.capture(boundary);\n };\n return {\n producer: boundary,\n output,\n mark,\n fail,\n detach: next => {\n cleanup = next;\n },\n };\n};\n\ntype CollectionStageOptions<K extends string, V> = {\n readonly reset: boolean;\n readonly candidates?: Iterable<K>;\n readonly orderMayChange?: boolean;\n readonly isEqual?: (previous: V, next: V) => boolean;\n};\n\n/** Applies source hints to an output draft; exact net change semantics remain in the output. */\nconst stageCollectionRead = <K extends string, V>(\n state: CollectionOutputState<K, V>,\n read: CollectionRead<K, V>,\n active: () => boolean,\n options: CollectionStageOptions<K, V>\n): boolean => {\n const evaluation = state.begin(active, options.reset);\n if (options.reset) {\n const ids = read.ids();\n profile.collectionView.idsScanned(ids.length);\n for (const key of ids) {\n profile.collectionView.mapped();\n evaluation.output.set(key, read.get(key) as V);\n }\n evaluation.output.order(ids);\n } else {\n const previous = state.current();\n const keys = options.candidates\n ? [...new Set(options.candidates)]\n : [...new Set([...previous.ids(), ...read.ids()])];\n if (!options.candidates) profile.collectionView.idsScanned(keys.length);\n for (const key of keys) {\n if (read.has(key)) {\n profile.collectionView.mapped();\n evaluation.output.set(key, read.get(key) as V);\n } else evaluation.output.remove(key);\n }\n if (options.orderMayChange || !options.candidates) {\n const ids = read.ids();\n if (options.candidates) profile.collectionView.idsScanned(ids.length);\n evaluation.output.order(ids);\n }\n }\n return state.seal(options.reset, options.isEqual ?? Object.is);\n};\n\nexport const createCollectionBoundary = (\n scheduler: Scheduler,\n name: string,\n readLatest: (\n active: () => boolean,\n previous: CollectionRead<string, unknown>\n ) => CollectionRead<string, unknown>,\n equality: (previous: unknown, next: unknown) => boolean,\n clearSource: (failed: boolean) => void\n): CollectionBoundary => {\n let boundary!: SourceBoundaryRecord;\n let pendingReset = false;\n let pendingCause: unknown;\n let contextCause: unknown;\n let recovering = false;\n let fullScan = false;\n let orderMayChange = false;\n const candidates = new Set<string>();\n let cleanup: Unsubscribe | undefined;\n\n const check = () => {\n if (!scheduler.active || boundary.disposed) throw new ProjectionDisposedError();\n if (boundary.fault) throw boundary.fault;\n };\n const state: CollectionOutputState<string, unknown> = createCollectionOutput({\n owner: () => boundary,\n check,\n cause: () => contextCause,\n });\n const output: OutputRecord = state;\n\n boundary = {\n kind: 'source',\n name,\n outputs: Object.freeze([output]) as readonly [OutputRecord],\n fault: undefined,\n disposed: false,\n pendingCause: () => pendingCause,\n recovering: () => recovering,\n prepare: cause => {\n contextCause = cause;\n let active = true;\n try {\n const changed = stageCollectionRead(\n state,\n readLatest(() => active, state.current()),\n () => active,\n {\n reset: pendingReset,\n ...(fullScan ? {} : { candidates }),\n orderMayChange,\n isEqual: equality,\n }\n );\n recovering = false;\n return { changed, force: pendingReset };\n } finally {\n active = false;\n }\n },\n publish: state.publish,\n clear: () => {\n const failed = boundary.fault !== undefined;\n state.clear();\n pendingReset = false;\n pendingCause = undefined;\n contextCause = undefined;\n recovering = false;\n fullScan = false;\n orderMayChange = false;\n candidates.clear();\n clearSource(failed);\n },\n release: () => {\n const detach = cleanup;\n cleanup = undefined;\n const failures: unknown[] = [];\n try {\n detach?.();\n } catch (error) {\n failures.push(error);\n }\n try {\n state.release();\n } catch (error) {\n failures.push(error);\n }\n if (failures.length) throw failures[0];\n },\n };\n\n try {\n scheduler.initialize(() => {\n let active = true;\n try {\n stageCollectionRead(\n state,\n readLatest(() => active, state.current()),\n () => active,\n { reset: true, isEqual: equality }\n );\n state.publish();\n state.clear();\n } finally {\n active = false;\n }\n });\n scheduler.addSource(boundary);\n } catch (error) {\n boundary.disposed = true;\n try {\n boundary.release();\n } catch {\n /* Initialization failure retains priority. */\n }\n throw error;\n }\n\n const mark = (metadata: CollectionMark = {}) => {\n scheduler.assertIdle();\n pendingReset ||= metadata.reset ?? false;\n if (metadata.cause !== undefined) pendingCause ??= metadata.cause;\n fullScan ||= metadata.fullScan ?? false;\n orderMayChange ||= metadata.orderMayChange ?? false;\n if (metadata.candidates) for (const key of metadata.candidates) candidates.add(key);\n if (boundary.fault) recovering = true;\n scheduler.capture(boundary);\n };\n const fail = (cause: unknown) => {\n boundary.fault = sourceError(cause);\n recovering = false;\n scheduler.capture(boundary);\n };\n return {\n producer: boundary,\n output,\n mark,\n fail,\n detach: next => {\n cleanup = next;\n },\n };\n};\n","import * as address from '../../address/resolve';\nimport * as impactTarget from '../../impact/target';\nimport * as sequence from '../../order/sequence';\nimport { contextOf } from '../../runtime/context';\nimport type { ReadonlyDocument, Unsubscribe } from '../../runtime/contract';\nimport { collectionEntryNode } from '../../schema/model';\nimport type { DocumentTreeNode, ObjectSchema } from '../../schema/model';\nimport type { ImpactTarget } from '../../schema/path';\nimport type { ChangeSet } from '../../changes';\nimport * as schemaValue from '../../schema/value';\nimport { isRecord } from '../../value/record';\nimport type { CollectionRead } from '../contract';\nimport type { SourceDefinition } from '../definition';\nimport { materializeDocumentValue } from './materialization';\nimport {\n clearCollectionPending,\n clearDocumentDirty,\n createCollectionPending,\n createDocumentDirty,\n markDocumentReplace,\n mergeCollectionChanges,\n mergeValueChanges,\n resetCollectionPending,\n} from './dirty';\nimport { assertScope, type Scheduler } from '../graph/scheduler';\nimport {\n createCollectionBoundary,\n createValueBoundary,\n type CollectionBoundary,\n type SourceMaterialization,\n type ValueBoundary,\n} from './boundary';\n\ntype DocumentBinding = {\n readonly target: ImpactTarget;\n capture(commit: { readonly changes: ChangeSet }): void;\n dispose(): void;\n};\n\ntype DocumentConnection = {\n add(binding: DocumentBinding): Unsubscribe;\n close(): void;\n};\n\nconst documentRootTarget: ImpactTarget = Object.freeze({\n kind: 'value' as const,\n at: Object.freeze([]),\n});\n\nexport const createDocumentSourceRegistry = (scheduler: Scheduler) => {\n const documents = new Map<object, DocumentConnection>();\n\n const connection = <S extends ObjectSchema<object>>(\n runtime: ReadonlyDocument<S>\n ): DocumentConnection => {\n const context = contextOf<S>(runtime);\n const state = context.state;\n const cached = documents.get(state);\n if (cached) return cached;\n if (state.disposed) throw new Error('Document has been disposed.');\n const bindings = new Set<DocumentBinding>();\n const index = new impactTarget.SubscriptionIndex<DocumentBinding>(state.schema);\n const candidates = new Set<DocumentBinding>();\n const guard = (locked: boolean) => {\n state.projectionLocks += locked ? 1 : -1;\n };\n let unregisterGuard = scheduler.registerGuard(guard);\n let closed = false;\n let detach: Unsubscribe | undefined;\n const documentConnection: DocumentConnection = {\n add(binding) {\n if (closed) throw new Error('Document projection connection is closed.');\n bindings.add(binding);\n try {\n index.add(binding.target, binding);\n } catch (error) {\n bindings.delete(binding);\n throw error;\n }\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n bindings.delete(binding);\n index.delete(binding.target, binding);\n if (!bindings.size) documentConnection.close();\n };\n },\n close() {\n if (closed) return;\n closed = true;\n const stopNotifications = detach;\n detach = undefined;\n const stopGuard = unregisterGuard;\n unregisterGuard = () => undefined;\n bindings.clear();\n candidates.clear();\n index.clear();\n documents.delete(state);\n const failures: unknown[] = [];\n try {\n stopNotifications?.();\n } catch (error) {\n failures.push(error);\n }\n try {\n stopGuard();\n } catch (error) {\n failures.push(error);\n }\n if (failures.length) throw failures[0];\n },\n };\n try {\n detach = context.notifications.attachProjection({\n capture: commit => {\n candidates.clear();\n index.collect(commit.changes, binding => candidates.add(binding));\n candidates.forEach(binding => binding.capture(commit));\n },\n settle: scheduler.settle,\n flush: scheduler.flush,\n dispose: () => {\n const failures: unknown[] = [];\n for (const binding of [...bindings]) {\n try {\n binding.dispose();\n } catch (error) {\n failures.push(error);\n }\n }\n try {\n scheduler.run();\n } catch (error) {\n failures.push(error);\n }\n if (failures.length) throw failures[0];\n },\n });\n } catch (error) {\n try {\n documentConnection.close();\n } catch {\n /* Connection initialization failure retains priority. */\n }\n throw error;\n }\n documents.set(state, documentConnection);\n return documentConnection;\n };\n\n const materialize = (definition: SourceDefinition): SourceMaterialization => {\n if (definition.source.kind !== 'document') throw new Error('Invalid document source.');\n const { document, selector } = definition.source;\n const state = contextOf(document).state;\n const current = () => address.resolveValue(state.schema, state.document, selector.address);\n const disposed = () => {\n if (state.disposed) throw new Error('Document has been disposed.');\n };\n\n if (selector.kind === 'value') {\n const dirty = createDocumentDirty();\n const read = (previous?: unknown): unknown => {\n disposed();\n const resolved = current();\n const node = resolved?.node;\n const value = resolved?.value;\n if (selector.tree?.kind === 'root')\n return node?.kind === 'tree' && isRecord(value) && typeof value.rootId === 'string'\n ? value.rootId\n : undefined;\n if (selector.tree?.kind === 'node') {\n if (node?.kind !== 'tree' || !isRecord(value) || !isRecord(value.nodes)) return undefined;\n const entry = Object.hasOwn(value.nodes, selector.tree.id)\n ? (value.nodes[selector.tree.id] as\n DocumentTreeNode<unknown, false> | DocumentTreeNode<unknown, true>)\n : undefined;\n if (\n schemaValue.equalTreeNode(\n previous as\n DocumentTreeNode<unknown, false> | DocumentTreeNode<unknown, true> | undefined,\n entry\n )\n )\n return previous;\n return entry ? schemaValue.copyTreeNode(entry) : undefined;\n }\n if (!node) return undefined;\n return previous === undefined\n ? schemaValue.copyValue(node, value)\n : materializeDocumentValue(node, previous, value, dirty);\n };\n\n const initial = read();\n let boundary!: ValueBoundary;\n boundary = createValueBoundary(\n scheduler,\n 'document source',\n initial,\n Object.is,\n previous => read(previous),\n failed => {\n if (failed) markDocumentReplace(dirty, []);\n else clearDocumentDirty(dirty);\n }\n );\n let remove: Unsubscribe;\n try {\n remove = connection(document).add({\n target: selector,\n capture: commit => {\n try {\n mergeValueChanges(selector, dirty, commit.changes);\n boundary.mark({\n reset: commit.changes.changes.some(change => change.kind === 'reset'),\n });\n } catch (cause) {\n boundary.fail(cause);\n }\n },\n dispose: () => boundary.fail(new Error('Document has been disposed.')),\n });\n } catch (error) {\n try {\n scheduler.releaseProducer(boundary.producer);\n } catch {\n /* Connection initialization failure retains priority. */\n }\n throw error;\n }\n boundary.detach(remove);\n return boundary;\n }\n\n const pending = createCollectionPending();\n const read = (\n active: () => boolean,\n previous: CollectionRead<string, unknown>\n ): CollectionRead<string, unknown> => {\n disposed();\n const resolved = current();\n const node = resolved?.node;\n const value = resolved?.value;\n const treeNodes = selector.tree?.kind === 'nodes';\n const entryNode = !treeNodes && node ? collectionEntryNode(node) : undefined;\n const snapshots = new Map<string, unknown>();\n const replacement = createDocumentDirty();\n if (pending.reset) markDocumentReplace(replacement, []);\n\n const ids = (): readonly string[] => {\n assertScope(active);\n if (treeNodes)\n return node?.kind === 'tree' && isRecord(value) && isRecord(value.nodes)\n ? Object.freeze(Object.keys(value.nodes))\n : Object.freeze([]);\n if (node?.kind === 'map' && isRecord(value)) return Object.freeze(Object.keys(value));\n if (node?.kind === 'table' && isRecord(value) && Array.isArray(value.ids))\n return Object.freeze([...(value.ids as string[])]);\n if (node?.kind === 'list' && Array.isArray(value))\n return Object.freeze(sequence.toArray(sequence.indexedKeys(value, node.keyOf)));\n return Object.freeze([]);\n };\n\n const has = (key: string): boolean => {\n assertScope(active);\n if (treeNodes)\n return Boolean(\n node?.kind === 'tree' &&\n isRecord(value) &&\n isRecord(value.nodes) &&\n Object.hasOwn(value.nodes, key)\n );\n if (node?.kind === 'map' && isRecord(value)) return Object.hasOwn(value, key);\n if (node?.kind === 'table' && isRecord(value) && isRecord(value.byId))\n return Object.hasOwn(value.byId, key);\n if (node?.kind === 'list' && Array.isArray(value))\n return sequence.indexedKeys(value, node.keyOf).index(key) >= 0;\n return false;\n };\n\n const raw = (key: string): unknown => {\n if (treeNodes) {\n if (node?.kind !== 'tree' || !isRecord(value) || !isRecord(value.nodes)) return undefined;\n return Object.hasOwn(value.nodes, key) ? value.nodes[key] : undefined;\n }\n if (node?.kind === 'map' && isRecord(value))\n return Object.hasOwn(value, key) ? value[key] : undefined;\n if (node?.kind === 'table' && isRecord(value) && isRecord(value.byId))\n return Object.hasOwn(value.byId, key) ? value.byId[key] : undefined;\n if (node?.kind === 'list' && Array.isArray(value)) {\n const index = sequence.indexedKeys(value, node.keyOf).index(key);\n return index < 0 ? undefined : value[index];\n }\n return undefined;\n };\n\n return Object.freeze({\n get: (key: string) => {\n assertScope(active);\n if (!snapshots.has(key)) {\n if (!has(key)) snapshots.set(key, undefined);\n else {\n const current = raw(key);\n if (treeNodes) {\n const entry = current as\n DocumentTreeNode<unknown, false> | DocumentTreeNode<unknown, true>;\n const before = previous.has(key)\n ? (previous.get(key) as\n DocumentTreeNode<unknown, false> | DocumentTreeNode<unknown, true>)\n : undefined;\n snapshots.set(\n key,\n schemaValue.equalTreeNode(before, entry)\n ? before\n : schemaValue.copyTreeNode(entry)\n );\n } else if (!entryNode) snapshots.set(key, current);\n else if (!previous.has(key))\n snapshots.set(key, schemaValue.copyValue(entryNode, current));\n else {\n const dirty = pending.entries.get(key) ?? (pending.reset ? replacement : undefined);\n snapshots.set(\n key,\n dirty\n ? materializeDocumentValue(entryNode, previous.get(key), current, dirty)\n : previous.get(key)\n );\n }\n }\n }\n return snapshots.get(key);\n },\n has,\n ids,\n });\n };\n\n let boundary!: CollectionBoundary;\n boundary = createCollectionBoundary(\n scheduler,\n 'document collection source',\n read,\n Object.is,\n failed => {\n if (failed) resetCollectionPending(pending);\n else clearCollectionPending(pending);\n }\n );\n let remove: Unsubscribe;\n try {\n remove = connection(document).add({\n target: selector,\n capture: commit => {\n try {\n mergeCollectionChanges(selector, pending, commit.changes);\n boundary.mark({\n reset: pending.reset,\n ...(pending.reset ? {} : { candidates: pending.entries.keys() }),\n orderMayChange: pending.order,\n });\n } catch (cause) {\n boundary.fail(cause);\n }\n },\n dispose: () => boundary.fail(new Error('Document has been disposed.')),\n });\n } catch (error) {\n try {\n scheduler.releaseProducer(boundary.producer);\n } catch {\n /* Connection initialization failure retains priority. */\n }\n throw error;\n }\n boundary.detach(remove);\n return boundary;\n };\n\n return {\n materialize,\n attachRoot<S extends ObjectSchema<object>>(\n runtime: ReadonlyDocument<S>,\n handlers: { readonly capture: () => void; readonly dispose: () => void }\n ): Unsubscribe {\n return connection(runtime).add({\n target: documentRootTarget,\n capture: handlers.capture,\n dispose: handlers.dispose,\n });\n },\n dispose() {\n const failures: unknown[] = [];\n for (const document of [...documents.values()]) {\n try {\n document.close();\n } catch (error) {\n failures.push(error);\n }\n }\n documents.clear();\n if (failures.length) throw failures[0];\n },\n };\n};\n","import type { Readable } from '../../readable';\nimport { contextOf } from '../../runtime/context';\nimport type { Unsubscribe } from '../../runtime/contract';\nimport type { ExternalCollectionSource } from '../contract';\nimport type { SourceDefinition } from '../definition';\nimport type { Scheduler } from '../graph/scheduler';\nimport {\n createCollectionBoundary,\n createValueBoundary,\n type CollectionBoundary,\n type SourceMark,\n type SourceMaterialization,\n type ValueBoundary,\n} from './boundary';\nimport type { createDocumentSourceRegistry } from './document';\n\ntype ValueMember = {\n readonly boundary: ValueBoundary;\n receive(value: unknown, metadata?: SourceMark): void;\n};\n\ntype DocumentSources = ReturnType<typeof createDocumentSourceRegistry>;\n\nexport const createExternalSourceRegistry = (scheduler: Scheduler, documents: DocumentSources) => {\n const readables = new Map<Readable<unknown>, { members: Set<ValueMember>; close(): void }>();\n const externalValues = new Map<object, { members: Set<ValueMember>; close(): void }>();\n const externalCollections = new Map<\n object,\n { members: Set<CollectionBoundary>; close(): void }\n >();\n\n const readable = (definition: SourceDefinition): SourceMaterialization => {\n if (definition.source.kind !== 'readable') throw new Error('Invalid Readable source.');\n const { readable, equality } = definition.source;\n let latest = readable.current();\n const boundary = createValueBoundary(\n scheduler,\n 'external readable',\n latest,\n equality,\n () => latest,\n () => undefined\n );\n const member: ValueMember = {\n boundary,\n receive(value, metadata) {\n latest = value;\n boundary.mark(metadata);\n },\n };\n let connection = readables.get(readable);\n if (!connection) {\n const members = new Set<ValueMember>();\n let closed = false;\n let unsubscribe: Unsubscribe | undefined;\n let detachDocument: Unsubscribe | undefined;\n const receive = (settle: boolean) => {\n if (closed || !scheduler.active) return;\n try {\n const value = readable.current();\n members.forEach(next => next.receive(value));\n } catch (cause) {\n members.forEach(next => next.boundary.fail(cause));\n }\n if (settle) scheduler.run();\n };\n const created = {\n members,\n close() {\n if (closed) return;\n closed = true;\n const stopReadable = unsubscribe;\n unsubscribe = undefined;\n const stopDocument = detachDocument;\n detachDocument = undefined;\n readables.delete(readable);\n members.clear();\n const failures: unknown[] = [];\n try {\n stopReadable?.();\n } catch (error) {\n failures.push(error);\n }\n try {\n stopDocument?.();\n } catch (error) {\n failures.push(error);\n }\n if (failures.length) throw failures[0];\n },\n };\n try {\n const owner = contextOf(readable, false)?.owner;\n if (owner) {\n detachDocument = documents.attachRoot(owner, {\n capture: () => receive(false),\n dispose: () => {\n members.forEach(next => next.boundary.fail(new Error('Document has been disposed.')));\n },\n });\n }\n unsubscribe = readable.subscribe(() => receive(true));\n } catch (error) {\n try {\n created.close();\n } catch {\n /* Connection initialization failure retains priority. */\n }\n try {\n scheduler.releaseProducer(boundary.producer);\n } catch {\n /* Connection initialization failure retains priority. */\n }\n throw error;\n }\n connection = created;\n readables.set(readable, connection);\n }\n connection.members.add(member);\n boundary.detach(() => {\n connection!.members.delete(member);\n if (!connection!.members.size) connection!.close();\n });\n return boundary;\n };\n\n const externalValue = (definition: SourceDefinition): SourceMaterialization => {\n if (definition.source.kind !== 'external-value')\n throw new Error('Invalid external value source.');\n const { source, equality } = definition.source;\n let latest = source.current();\n const boundary = createValueBoundary(\n scheduler,\n 'external source',\n latest,\n equality,\n () => latest,\n () => undefined\n );\n const member: ValueMember = {\n boundary,\n receive(value, metadata) {\n latest = value;\n boundary.mark(metadata);\n },\n };\n let connection = externalValues.get(source);\n if (!connection) {\n const members = new Set<ValueMember>();\n let closed = false;\n let unsubscribe: Unsubscribe | undefined;\n const created = {\n members,\n close() {\n if (closed) return;\n closed = true;\n const stop = unsubscribe;\n unsubscribe = undefined;\n externalValues.delete(source);\n members.clear();\n stop?.();\n },\n };\n try {\n unsubscribe = source.subscribe(event => {\n try {\n members.forEach(next =>\n next.receive(event.value, { reset: event.reset, cause: event.cause })\n );\n } catch (cause) {\n members.forEach(next => next.boundary.fail(cause));\n }\n scheduler.run();\n });\n } catch (error) {\n try {\n created.close();\n } catch {\n /* Connection initialization failure retains priority. */\n }\n try {\n scheduler.releaseProducer(boundary.producer);\n } catch {\n /* Connection initialization failure retains priority. */\n }\n throw error;\n }\n connection = created;\n externalValues.set(source, connection);\n }\n connection.members.add(member);\n boundary.detach(() => {\n connection!.members.delete(member);\n if (!connection!.members.size) connection!.close();\n });\n return boundary;\n };\n\n const externalCollection = (definition: SourceDefinition): SourceMaterialization => {\n if (definition.source.kind !== 'external-collection')\n throw new Error('Invalid external collection source.');\n const source = definition.source.source as ExternalCollectionSource<string, unknown>;\n const boundary = createCollectionBoundary(\n scheduler,\n 'external collection source',\n () => {\n const current = source.current();\n return Object.freeze({\n get: key => current.get(key),\n has: key => current.has(key),\n ids: () => current.ids(),\n });\n },\n definition.output.equality,\n () => undefined\n );\n let connection = externalCollections.get(source);\n if (!connection) {\n const members = new Set<CollectionBoundary>();\n let closed = false;\n let unsubscribe: Unsubscribe | undefined;\n const created = {\n members,\n close() {\n if (closed) return;\n closed = true;\n const stop = unsubscribe;\n unsubscribe = undefined;\n externalCollections.delete(source);\n members.clear();\n stop?.();\n },\n };\n try {\n unsubscribe = source.subscribe(event => {\n try {\n const impact = event.impact;\n if (impact?.kind === 'reset') {\n members.forEach(next => next.mark({ reset: true, cause: event.cause }));\n } else if (impact?.kind === 'incremental') {\n const candidates = new Set<string>([\n ...impact.added,\n ...impact.updated,\n ...impact.removed,\n ]);\n members.forEach(next =>\n next.mark({\n candidates,\n orderMayChange: Boolean(\n impact.added.size || impact.removed.size || impact.orderChanged\n ),\n cause: event.cause,\n })\n );\n } else {\n members.forEach(next =>\n next.mark({ fullScan: true, orderMayChange: true, cause: event.cause })\n );\n }\n } catch (cause) {\n members.forEach(next => next.fail(cause));\n }\n scheduler.run();\n });\n } catch (error) {\n try {\n created.close();\n } catch {\n /* Connection initialization failure retains priority. */\n }\n try {\n scheduler.releaseProducer(boundary.producer);\n } catch {\n /* Connection initialization failure retains priority. */\n }\n throw error;\n }\n connection = created;\n externalCollections.set(source, connection);\n }\n connection.members.add(boundary);\n boundary.detach(() => {\n connection!.members.delete(boundary);\n if (!connection!.members.size) connection!.close();\n });\n return boundary;\n };\n\n return {\n materialize(definition: SourceDefinition): SourceMaterialization {\n switch (definition.source.kind) {\n case 'readable':\n return readable(definition);\n case 'external-value':\n return externalValue(definition);\n case 'external-collection':\n return externalCollection(definition);\n default:\n throw new Error('Invalid external projection source.');\n }\n },\n dispose() {\n const failures: unknown[] = [];\n const connections = new Set([\n ...readables.values(),\n ...externalValues.values(),\n ...externalCollections.values(),\n ]);\n for (const connection of connections) {\n try {\n connection.close();\n } catch (error) {\n failures.push(error);\n }\n }\n readables.clear();\n externalValues.clear();\n externalCollections.clear();\n if (failures.length) throw failures[0];\n },\n };\n};\n","import { mapRead } from '../collection/view';\nimport type { CollectionInputDraft, SourceDefinition } from '../definition';\nimport { assertScope, assertSynchronous, type Scheduler } from '../graph/scheduler';\nimport {\n createCollectionBoundary,\n createValueBoundary,\n type SourceMaterialization,\n} from './boundary';\n\nexport const materializeInputSource = (\n scheduler: Scheduler,\n definition: SourceDefinition\n): SourceMaterialization => {\n const source = definition.source;\n if (source.kind === 'value-input') {\n let latest = source.initial;\n const boundary = createValueBoundary(\n scheduler,\n 'projection input',\n source.initial,\n source.equality,\n () => latest,\n () => undefined\n );\n return {\n ...boundary,\n write: {\n kind: 'value',\n set(value) {\n scheduler.assertIdle();\n latest = value;\n boundary.mark();\n scheduler.run();\n },\n },\n };\n }\n if (source.kind !== 'collection-input') throw new Error('Invalid projection input source.');\n\n const values = new Map(source.initial);\n const boundary = createCollectionBoundary(\n scheduler,\n 'projection collection input',\n () => mapRead(values),\n definition.output.equality,\n () => undefined\n );\n return {\n ...boundary,\n write: {\n kind: 'collection',\n update(run) {\n scheduler.assertIdle();\n const staged = new Map<\n string,\n { readonly present: true; readonly value: unknown } | { readonly present: false }\n >();\n const operations: (\n | { readonly kind: 'set'; readonly key: string; readonly value: unknown }\n | { readonly kind: 'remove'; readonly key: string }\n )[] = [];\n let active = true;\n const draft: CollectionInputDraft<string, unknown> = Object.freeze({\n get: key => {\n assertScope(() => active);\n const entry = staged.get(key);\n return entry ? (entry.present ? entry.value : undefined) : values.get(key);\n },\n has: key => {\n assertScope(() => active);\n const entry = staged.get(key);\n return entry ? entry.present : values.has(key);\n },\n set: (key, value) => {\n assertScope(() => active);\n if (typeof key !== 'string') throw new TypeError('Projection keys must be strings.');\n staged.set(key, { present: true, value });\n operations.push({ kind: 'set', key, value });\n },\n remove: key => {\n assertScope(() => active);\n if (typeof key !== 'string') throw new TypeError('Projection keys must be strings.');\n staged.set(key, { present: false });\n operations.push({ kind: 'remove', key });\n },\n });\n try {\n assertSynchronous(run(draft));\n } finally {\n active = false;\n }\n\n const candidates = new Set<string>();\n let structural = false;\n const accepted: typeof operations = [];\n const overlay = new Map<\n string,\n { readonly present: true; readonly value: unknown } | { readonly present: false }\n >();\n for (const operation of operations) {\n const overlayValue = overlay.get(operation.key);\n const present = overlayValue ? overlayValue.present : values.has(operation.key);\n if (operation.kind === 'set') {\n const previous = overlayValue\n ? overlayValue.present\n ? overlayValue.value\n : undefined\n : values.get(operation.key);\n if (present && source.equality(previous, operation.value)) continue;\n structural ||= !present;\n overlay.set(operation.key, { present: true, value: operation.value });\n } else {\n if (!present) continue;\n structural = true;\n overlay.set(operation.key, { present: false });\n }\n accepted.push(operation);\n candidates.add(operation.key);\n }\n if (!accepted.length) return;\n for (const operation of accepted) {\n if (operation.kind === 'set') values.set(operation.key, operation.value);\n else values.delete(operation.key);\n }\n boundary.mark({ candidates, orderMayChange: structural });\n scheduler.run();\n },\n },\n };\n};\n","import type { SourceDefinition } from '../definition';\nimport type { Scheduler } from '../graph/scheduler';\nimport type { SourceMaterialization } from './boundary';\nimport { createDocumentSourceRegistry } from './document';\nimport { createExternalSourceRegistry } from './external';\nimport { materializeInputSource } from './input';\n\nexport const createSourceRegistry = (scheduler: Scheduler) => {\n const documents = createDocumentSourceRegistry(scheduler);\n const external = createExternalSourceRegistry(scheduler, documents);\n\n return {\n materialize(definition: SourceDefinition): SourceMaterialization {\n switch (definition.source.kind) {\n case 'value-input':\n case 'collection-input':\n return materializeInputSource(scheduler, definition);\n case 'document':\n return documents.materialize(definition);\n case 'readable':\n case 'external-value':\n case 'external-collection':\n return external.materialize(definition);\n }\n },\n dispose() {\n const failures: unknown[] = [];\n try {\n external.dispose();\n } catch (error) {\n failures.push(error);\n }\n try {\n documents.dispose();\n } catch (error) {\n failures.push(error);\n }\n if (failures.length) throw failures[0];\n },\n };\n};\n","import type { Unsubscribe } from '../runtime/contract';\nimport { collectionView, mapRead, snapshotCollectionView } from './collection/view';\nimport type { CollectionRead } from './contract';\nimport { ProjectionDisposedError } from './contract';\nimport {\n isProjection,\n ownProjections,\n producerOf,\n projectionRef,\n type CollectionInput,\n type CollectionInputDraft,\n type Input,\n type ProducerDefinition,\n type Projection,\n} from './definition';\nimport { isPlainObject } from '../value/record';\nimport { createProcessor } from './graph/processor';\nimport {\n createDirectReadable,\n createSelectorReadable,\n isMapLike,\n type ProjectionReadableSource,\n} from './readable/selection';\nimport type { Readable } from '../readable';\nimport { createScheduler, type OutputRecord, type ProducerRecord } from './graph/scheduler';\nimport { createSourceRegistry } from './source/registry';\nimport type { SourceWrite } from './source/boundary';\n\nexport type ProjectionRuntime = {\n read<T>(projection: Projection<T>): T;\n select<T>(projection: Projection<T>): Readable<T>;\n select<T, R>(\n projection: Projection<T>,\n selector: (value: T) => R,\n equality?: (previous: R, next: R) => boolean\n ): Readable<R>;\n update<T>(input: Input<T>, value: T): void;\n update<K extends string, V>(\n input: CollectionInput<K, V>,\n run: (draft: CollectionInputDraft<K, V>) => void\n ): void;\n batch<T>(run: () => T, options?: { readonly cause?: unknown }): T;\n scope(): ProjectionScope;\n dispose(): void;\n};\n\ntype ProjectionOwnershipTree = {\n readonly [name: string]: Projection<unknown> | ProjectionOwnershipTree;\n};\n\nexport type ProjectionScope = {\n own<P extends Projection<unknown>>(projection: P): P;\n own<T extends ProjectionOwnershipTree>(tree: T): T;\n read<T>(projection: Projection<T>): T;\n select<T>(projection: Projection<T>): Readable<T>;\n select<T, R>(\n projection: Projection<T>,\n selector: (value: T) => R,\n equality?: (previous: R, next: R) => boolean\n ): Readable<R>;\n update<T>(input: Input<T>, value: T): void;\n update<K extends string, V>(\n input: CollectionInput<K, V>,\n run: (draft: CollectionInputDraft<K, V>) => void\n ): void;\n batch<T>(run: () => T, options?: { readonly cause?: unknown }): T;\n dispose(): void;\n};\n\ntype MaterializedProducer = {\n readonly record: ProducerRecord;\n readonly outputs: readonly OutputRecord[];\n readonly write?: SourceWrite;\n};\n\ntype ScopeState = {\n active: boolean;\n readonly materialized: ProducerDefinition[];\n readonly subscriptions: Set<Unsubscribe>;\n};\n\nexport const createProjectionRuntime = (options?: {\n readonly onError?: (error: import('./contract').ProjectionError) => void;\n}): ProjectionRuntime => {\n const scheduler = createScheduler(options?.onError ?? (() => undefined));\n const sources = createSourceRegistry(scheduler);\n const materialized = new WeakMap<ProducerDefinition, MaterializedProducer>();\n const publicViews = new WeakMap<\n OutputRecord,\n { readonly revision: number; readonly value: ReadonlyMap<string, unknown> }\n >();\n const scopes = new Set<ScopeState>();\n\n const assertAccess = (definition: ProducerDefinition, requester?: ScopeState): void => {\n scheduler.assertActive();\n const owner = definition.owner;\n if (owner === undefined) return;\n if (owner !== requester) throw new TypeError('Projection belongs to another scope.');\n if (!requester?.active) throw new ProjectionDisposedError();\n };\n\n const rememberScoped = (\n definition: ProducerDefinition,\n requester: ScopeState | undefined\n ): void => {\n if (requester && definition.owner === requester) requester.materialized.push(definition);\n };\n\n const materializeProducer = (\n definition: ProducerDefinition,\n requester?: ScopeState\n ): MaterializedProducer => {\n assertAccess(definition, requester);\n const existing = materialized.get(definition);\n if (existing) return existing;\n\n let result: MaterializedProducer;\n if (definition.kind === 'source') {\n const source = sources.materialize(definition);\n result = Object.freeze({\n record: source.producer,\n outputs: Object.freeze([source.output]),\n ...(source.write ? { write: source.write } : {}),\n });\n } else {\n if (\n definition.owner === undefined &&\n definition.dependencies.some(dependency => producerOf(dependency).owner !== undefined)\n )\n throw new TypeError('A root projection cannot depend on a scoped projection.');\n const dependencies = definition.dependencies.map(dependency =>\n resolveOutput(dependency, requester)\n );\n const processor = createProcessor(scheduler, definition, Object.freeze(dependencies));\n result = Object.freeze({\n record: processor,\n outputs: processor.outputs,\n });\n }\n\n definition.materialized = true;\n materialized.set(definition, result);\n rememberScoped(definition, requester);\n return result;\n };\n\n const resolveOutput = (projection: Projection<unknown>, requester?: ScopeState): OutputRecord => {\n const ref = projectionRef(projection);\n const producer = materializeProducer(ref.producer, requester);\n const output = producer.outputs[ref.output];\n if (!output) throw new TypeError('Projection output does not exist.');\n return output;\n };\n\n const assertOutput = (output: OutputRecord): void => {\n scheduler.assertActive();\n if (output.owner.disposed) throw new ProjectionDisposedError();\n if (output.owner.fault) throw output.owner.fault;\n };\n\n const publicCurrent = (output: OutputRecord): unknown => {\n assertOutput(output);\n const current = output.current();\n const revision = output.revision();\n const cached = publicViews.get(output);\n if (cached?.revision === revision) return cached.value;\n\n if (output.kind === 'collection') {\n const value = collectionView(current as CollectionRead<string, unknown>);\n publicViews.set(output, { revision, value });\n return value;\n }\n if (isMapLike(current)) {\n const value = snapshotCollectionView(mapRead(current));\n publicViews.set(output, { revision, value });\n return value;\n }\n publicViews.delete(output);\n return current;\n };\n\n const readProjection = <T>(projection: Projection<T>, requester?: ScopeState): T =>\n publicCurrent(resolveOutput(projection as Projection<unknown>, requester)) as T;\n\n const readableSource = <T>(\n projection: Projection<T>,\n requester?: ScopeState\n ): ProjectionReadableSource<T> => {\n const output = resolveOutput(projection as Projection<unknown>, requester);\n return Object.freeze({\n kind: output.kind,\n current: () => readProjection(projection, requester),\n revision: () => {\n assertOutput(output);\n return output.revision();\n },\n subscribe: output.subscribe,\n });\n };\n\n const makeReadable = <T, R>(\n projection: Projection<T>,\n selector?: (value: T) => R,\n equality?: (previous: R, next: R) => boolean,\n requester?: ScopeState\n ): Readable<T | R> => {\n const source = readableSource(projection, requester);\n return selector\n ? createSelectorReadable(source, selector, equality)\n : createDirectReadable(source);\n };\n\n function selectProjection<T>(projection: Projection<T>): Readable<T>;\n function selectProjection<T, R>(\n projection: Projection<T>,\n selector: (value: T) => R,\n equality?: (previous: R, next: R) => boolean\n ): Readable<R>;\n function selectProjection<T, R>(\n projection: Projection<T>,\n selector?: (value: T) => R,\n equality?: (previous: R, next: R) => boolean\n ): Readable<T | R> {\n return makeReadable(projection, selector, equality);\n }\n\n const inputWrite = (target: Projection<unknown>, requester?: ScopeState): SourceWrite => {\n const ref = projectionRef(target);\n if (ref.output !== 0 || ref.producer.kind !== 'source')\n throw new TypeError('Projection is not an input.');\n if (\n ref.producer.source.kind !== 'value-input' &&\n ref.producer.source.kind !== 'collection-input'\n )\n throw new TypeError('Projection is not an input.');\n const write = materializeProducer(ref.producer, requester).write;\n if (!write) throw new TypeError('Projection input is not writable.');\n return write;\n };\n\n const updateInput = (\n target: Projection<unknown>,\n valueOrRun: unknown,\n requester?: ScopeState\n ): void => {\n const write = inputWrite(target, requester);\n if (write.kind === 'value') {\n write.set(valueOrRun);\n return;\n }\n if (typeof valueOrRun !== 'function')\n throw new TypeError('Collection input update requires a draft callback.');\n write.update(valueOrRun as (draft: CollectionInputDraft<string, unknown>) => void);\n };\n\n function update<T>(target: Input<T>, value: T): void;\n function update<K extends string, V>(\n target: CollectionInput<K, V>,\n run: (draft: CollectionInputDraft<K, V>) => void\n ): void;\n function update(target: Projection<unknown>, valueOrRun: unknown): void {\n updateInput(target, valueOrRun);\n }\n\n const batch = <T>(run: () => T, options?: { readonly cause?: unknown }): T =>\n scheduler.batch(run, options);\n\n const disposeScope = (state: ScopeState): void => {\n if (!state.active) return;\n scheduler.assertIdle();\n state.active = false;\n const failures: unknown[] = [];\n const subscriptions = [...state.subscriptions];\n state.subscriptions.clear();\n for (const unsubscribe of subscriptions) {\n try {\n unsubscribe();\n } catch (error) {\n failures.push(error);\n }\n }\n for (let index = state.materialized.length - 1; index >= 0; index--) {\n const definition = state.materialized[index];\n const current = materialized.get(definition);\n if (!current) continue;\n try {\n scheduler.releaseProducer(current.record);\n } catch (error) {\n failures.push(error);\n } finally {\n materialized.delete(definition);\n }\n }\n state.materialized.length = 0;\n scopes.delete(state);\n if (failures.length) throw failures[0];\n };\n\n const createScope = (): ProjectionScope => {\n scheduler.assertIdle();\n const state: ScopeState = {\n active: true,\n materialized: [],\n subscriptions: new Set(),\n };\n scopes.add(state);\n\n const assertActive = () => {\n if (!state.active) throw new ProjectionDisposedError();\n scheduler.assertActive();\n };\n function own<P extends Projection<unknown>>(projection: P): P;\n function own<T extends ProjectionOwnershipTree>(tree: T): T;\n function own<T extends Projection<unknown> | ProjectionOwnershipTree>(target: T): T {\n assertActive();\n const projections: Projection<unknown>[] = [];\n const collect = (value: Projection<unknown> | ProjectionOwnershipTree): void => {\n if (isProjection(value)) {\n projections.push(value);\n return;\n }\n if (!isPlainObject(value))\n throw new TypeError('Projection ownership tree must be a plain object.');\n for (const key of Reflect.ownKeys(value)) {\n if (typeof key !== 'string')\n throw new TypeError('Projection ownership tree keys must be strings.');\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (!descriptor?.enumerable || !('value' in descriptor))\n throw new TypeError('Projection ownership tree must use enumerable data properties.');\n const child = descriptor.value;\n if (!isProjection(child) && !isPlainObject(child))\n throw new TypeError('Projection ownership tree leaves must be projections.');\n collect(child as Projection<unknown> | ProjectionOwnershipTree);\n }\n };\n collect(target);\n if (!projections.length)\n throw new TypeError('Projection ownership tree must contain a projection.');\n ownProjections(projections, state);\n return target;\n }\n\n function scopeSelect<T>(projection: Projection<T>): Readable<T>;\n function scopeSelect<T, R>(\n projection: Projection<T>,\n selector: (value: T) => R,\n equality?: (previous: R, next: R) => boolean\n ): Readable<R>;\n function scopeSelect<T, R>(\n projection: Projection<T>,\n selector?: (value: T) => R,\n equality?: (previous: R, next: R) => boolean\n ): Readable<T | R> {\n assertActive();\n const source = makeReadable(projection, selector, equality, state);\n return Object.freeze({\n current: () => {\n assertActive();\n return source.current();\n },\n revision: () => {\n assertActive();\n return source.revision();\n },\n subscribe: listener => {\n assertActive();\n const stop = source.subscribe(listener);\n let subscribed = true;\n const unsubscribe = () => {\n if (!subscribed) return;\n subscribed = false;\n state.subscriptions.delete(unsubscribe);\n stop();\n };\n state.subscriptions.add(unsubscribe);\n return unsubscribe;\n },\n });\n }\n\n function scopeUpdate<T>(target: Input<T>, value: T): void;\n function scopeUpdate<K extends string, V>(\n target: CollectionInput<K, V>,\n run: (draft: CollectionInputDraft<K, V>) => void\n ): void;\n function scopeUpdate(target: Projection<unknown>, valueOrRun: unknown): void {\n assertActive();\n updateInput(target, valueOrRun, state);\n }\n\n function scopeBatch<T>(run: () => T, options?: { readonly cause?: unknown }): T {\n assertActive();\n return batch(run, options);\n }\n\n return Object.freeze({\n own,\n read: <T>(projection: Projection<T>) => {\n assertActive();\n return readProjection(projection, state);\n },\n select: scopeSelect,\n update: scopeUpdate,\n batch: scopeBatch,\n dispose: () => disposeScope(state),\n });\n };\n\n return Object.freeze({\n read: readProjection,\n select: selectProjection,\n update,\n batch,\n scope: createScope,\n dispose: () => {\n if (!scheduler.active) return;\n scheduler.assertIdle();\n const failures: unknown[] = [];\n for (const scope of scopes) {\n scope.active = false;\n const subscriptions = [...scope.subscriptions];\n scope.subscriptions.clear();\n for (const unsubscribe of subscriptions) {\n try {\n unsubscribe();\n } catch (error) {\n failures.push(error);\n }\n }\n scope.materialized.length = 0;\n }\n scopes.clear();\n try {\n sources.dispose();\n } catch (error) {\n failures.push(error);\n }\n try {\n scheduler.dispose();\n } catch (error) {\n failures.push(error);\n }\n if (failures.length === 1) throw failures[0];\n if (failures.length) throw new AggregateError(failures, 'Projection cleanup failed.');\n },\n });\n};\n"],"mappings":";;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ACN,QAAQ;EACR;EACA;EACA,OAAO;EACP,eAAe;AACb,OAAI,CAAC,UAAU,OAAQ;AACvB,aAAU,YAAY;GACtB,MAAM,WAAsB,EAAE;AAC9B,QAAK,MAAM,SAAS,QAAQ;AAC1B,UAAM,SAAS;IACf,MAAM,gBAAgB,CAAC,GAAG,MAAM,cAAc;AAC9C,UAAM,cAAc,OAAO;AAC3B,SAAK,MAAM,eAAe,cACxB,KAAI;AACF,kBAAa;aACN,OAAO;AACd,cAAS,KAAK,MAAM;;AAGxB,UAAM,aAAa,SAAS;;AAE9B,UAAO,OAAO;AACd,OAAI;AACF,YAAQ,SAAS;YACV,OAAO;AACd,aAAS,KAAK,MAAM;;AAEtB,OAAI;AACF,cAAU,SAAS;YACZ,OAAO;AACd,aAAS,KAAK,MAAM;;AAEtB,OAAI,SAAS,WAAW,EAAG,OAAM,SAAS;AAC1C,OAAI,SAAS,OAAQ,OAAM,IAAI,eAAe,UAAU,6BAA6B;;EAExF,CAAC"}
1
+ {"version":3,"file":"index.cjs","names":["node","length","insert","remove","record","isRecord","isPlainObject","sequence.keys","sequence.equal","isRecord","sequence.indexedKeys","anchor.valid","index","anchor.index","remove","replace","insert","keys","sequence.keys","anchor.valid","anchor.index","replace","sequence.indexedKeys","remove","node","replace","move","anchor.moveSelection","sequence.equal","sequence.listSequence","sequence.matches","tree","AddressIndex","target.tree","schemaValue.copyValue","address.resolveChild","address.resolveLocated","address.nodeAt","sequence.indexedKeys","children","AddressIndex","target.belongs","target.affected","target.indexedAddress","relation.contains","sequence.toArray","sequence.indexedKeys","schemaValue.equalValue","schemaValue.copyValue","sequence.equal","address.resolveLocated","address.resolveValue","schemaValue.copyTreeNode","address.memberKey","sequence.indexedKeys","state.orderOf","schemaValue.equalTreeNode","AddressIndex","relation.contains","address.createAddressResolver","schemaValue.checkValue","address.resolveContainer","address.resolveTreeContainer","address.resolveValue","schemaValue.copyValue","address.memberKey","schemaValue.checkKey","state.orderOf","sequence.matches","schemaValue.checkTreePayload","schemaValue.copyTreeNode","contextOf","target.SubscriptionIndex","schemaValue.checkValue","schemaValue.ParseError","schemaValue.copyValue","target.dependencyBucket","target.same","contextOf","target.same","contextOf","defineSource","defineSource","contextOf","snapshotCollectionView","projectionRef","isProjection","isPlainObject","defineProcessor","ProjectionDisposedError","schemaValue.equalValue","schemaValue.copyValue","isRecord","sequence.equal","sequence.listSequence","sequence.indexedKeys","schemaValue.equalTreeNode","schemaValue.copyTreeNode","relation.contains","ProjectionError","ProjectionDisposedError","contextOf","impactTarget.SubscriptionIndex","address.resolveValue","isRecord","schemaValue.equalTreeNode","schemaValue.copyTreeNode","schemaValue.copyValue","sequence.toArray","sequence.indexedKeys","contextOf","mapRead","createScheduler","ProjectionDisposedError","producerOf","projectionRef","collectionView","snapshotCollectionView","mapRead","isProjection","isPlainObject"],"sources":["../core/src/schema/model.ts","../core/src/order/sequence.ts","../core/src/schema/layout.ts","../core/src/schema/value.ts","../core/src/address/resolve.ts","../core/src/order/anchor.ts","../core/src/mutation/operations/table.ts","../core/src/mutation/operations/list.ts","../core/src/mutation/operations/tree.ts","../core/src/mutation/operations/order.ts","../core/src/impact/target.ts","../core/src/access/scope.ts","../core/src/schema/path.ts","../core/src/address/relation.ts","../core/src/impact.ts","../core/src/runtime/contract.ts","../core/src/history.ts","../core/src/mutation/state.ts","../core/src/mutation/recorder.ts","../core/src/mutation/session.ts","../core/src/mutation/operations/replay.ts","../core/src/runtime/readable.ts","../core/src/runtime/notification.ts","../core/src/runtime.ts","../core/src/access/dependency.ts","../core/src/runtime/access.ts","../core/src/runtime/select.ts","../core/src/projection/input.ts","../core/src/projection/observe.ts","../core/src/projection/derive.ts","../core/src/projection/collection/change.ts","../core/src/projection/collection/index.ts","../core/src/projection/output/collection.ts","../core/src/projection/output/value.ts","../core/src/projection/graph/processor.ts","../core/src/projection/readable/selection.ts","../core/src/projection/source/materialization.ts","../core/src/projection/source/dirty.ts","../core/src/projection/source/boundary.ts","../core/src/projection/source/document.ts","../core/src/projection/source/external.ts","../core/src/projection/source/input.ts","../core/src/projection/source/registry.ts","../core/src/projection/runtime.ts"],"sourcesContent":["export type DocumentAddress = readonly string[];\n\n/** Pure synchronous validation. Successful output is ignored; input is never transformed. */\nexport type Validator<T> =\n | ((value: unknown) => value is T)\n | ((value: unknown) => asserts value is T)\n | {\n readonly '~standard': {\n readonly version: 1;\n readonly vendor: string;\n readonly types?: { readonly input: unknown; readonly output: T };\n validate(value: unknown):\n | { readonly value: T; readonly issues?: undefined }\n | {\n readonly issues: readonly {\n readonly message: string;\n readonly path?: readonly (PropertyKey | { readonly key: PropertyKey })[];\n }[];\n }\n | PromiseLike<unknown>;\n };\n };\n\n/** Shared payloads are immutable through every alias, including builtin methods. */\nexport type ReadonlyValue<T> = T extends (...args: never[]) => unknown\n ? T\n : T extends ReadonlyMap<infer K, infer V>\n ? ReadonlyMap<ReadonlyValue<K>, ReadonlyValue<V>>\n : T extends ReadonlySet<infer V>\n ? ReadonlySet<ReadonlyValue<V>>\n : T extends Date\n ? Omit<Date, `set${string}`>\n : T extends object\n ? { readonly [K in keyof T]: ReadonlyValue<T[K]> }\n : T;\n\nexport type DocumentListConfig<TItem> = {\n readonly keyOf: (item: ReadonlyValue<TItem>) => string;\n};\nexport type DocumentTreeNode<TValue, ValueOptional extends boolean = false> = {\n readonly parentId?: string;\n readonly children: readonly string[];\n} & (ValueOptional extends true\n ? { readonly value?: ReadonlyValue<TValue> }\n : { readonly value: ReadonlyValue<TValue> });\nexport type DocumentTreeValue<TValue, ValueOptional extends boolean = false> = {\n readonly rootId?: string;\n readonly nodes: Readonly<Record<string, DocumentTreeNode<TValue, ValueOptional>>>;\n};\n\ntype BaseNode<K extends string> = {\n readonly kind: K;\n readonly optional?: boolean;\n};\nexport type FieldNode<T, Optional extends boolean = false> = BaseNode<'field'> & {\n readonly __value?: T;\n readonly validator?: Validator<T>;\n} & (Optional extends true ? { readonly optional: true } : { readonly optional?: false });\n/** A node with optional presence. The marker replaces, rather than intersects, a field marker. */\nexport type OptionalNode<TNode extends DocumentNode> =\n TNode extends FieldNode<infer TValue, boolean>\n ? FieldNode<TValue, true>\n : TNode & { readonly optional: true };\nexport interface ObjectShape {\n readonly [key: string]: DocumentNode;\n}\nexport type ObjectNode<TShape extends ObjectShape = ObjectShape> = BaseNode<'object'> & {\n readonly shape: TShape;\n};\nexport interface VariantShape {\n readonly [key: string]: ObjectNode<ObjectShape>;\n}\nexport type VariantNode<\n TTag extends string,\n TVariants extends VariantShape,\n> = BaseNode<'variant'> & {\n readonly tag: TTag;\n readonly variants: TVariants;\n};\nexport type TableNode<\n TValue extends ObjectNode<ObjectShape> | VariantNode<string, VariantShape>,\n TKey extends string = string,\n> = BaseNode<'table'> & {\n readonly value: TValue;\n readonly key?: Validator<TKey>;\n};\nexport type MapNode<\n TValue extends ValueSchemaNode,\n TKey extends string = string,\n> = BaseNode<'map'> & {\n readonly value: TValue;\n readonly key?: Validator<TKey>;\n};\nexport type ListNode<TItem> = BaseNode<'list'> & {\n readonly value: FieldNode<TItem, false>;\n keyOf(item: ReadonlyValue<TItem>): string;\n};\nexport type TreeNode<TValue, ValueOptional extends boolean = false> = BaseNode<'tree'> & {\n readonly value: FieldNode<TValue, ValueOptional>;\n};\n\nexport type DocumentNode =\n | FieldNode<unknown, false>\n | FieldNode<unknown, true>\n | ObjectNode<ObjectShape>\n | VariantNode<string, VariantShape>\n | TableNode<ObjectNode<ObjectShape> | VariantNode<string, VariantShape>>\n | MapNode<ValueSchemaNode>\n | ListNode<unknown>\n | TreeNode<unknown, false>\n | TreeNode<unknown, true>;\n\ndeclare const schemaType: unique symbol;\ndeclare const objectSchema: unique symbol;\n\n/** Portable public schema handle. The definition parameter carries compile-time shape only. */\nexport type Schema<T = unknown, Definition = unknown> = {\n readonly [schemaType]: {\n readonly value: T;\n readonly definition: Definition;\n };\n};\n\ntype PublicSchemaShape = { readonly [key: string]: Schema<unknown, unknown> };\n\nexport type ObjectSchema<\n T extends object = object,\n Shape extends PublicSchemaShape = PublicSchemaShape,\n> = Schema<T, { readonly kind: 'object'; readonly shape: Shape }> & {\n readonly [objectSchema]: true;\n};\n\ntype SchemaDefinitionOf<S extends Schema<unknown, unknown>> =\n S extends Schema<unknown, infer Definition> ? Definition : unknown;\n\ntype Optionalized<N extends DocumentNode, Optional extends boolean> = Optional extends true\n ? OptionalNode<N>\n : N;\ntype FieldNodeFor<TValue, Optional extends boolean> = Optional extends true\n ? FieldNode<TValue, true>\n : FieldNode<TValue, false>;\ntype TreeNodeFor<TValue, ValueOptional extends boolean> = ValueOptional extends true\n ? TreeNode<TValue, true>\n : TreeNode<TValue, false>;\n\ntype SchemaNodeFromDefinition<Definition> = Definition extends {\n readonly kind: 'field';\n readonly value: infer TValue;\n readonly optional: infer Optional extends boolean;\n}\n ? FieldNodeFor<TValue, Optional>\n : Definition extends {\n readonly kind: 'object';\n readonly shape: infer Shape extends PublicSchemaShape;\n }\n ? ObjectNode<NodeShapeOf<Shape>>\n : Definition extends {\n readonly kind: 'variant';\n readonly tag: infer Tag extends string;\n readonly variants: infer Variants extends PublicVariantShape;\n readonly optional: infer Optional extends boolean;\n }\n ? Optionalized<VariantNode<Tag, VariantNodeShapeOf<Variants>>, Optional>\n : Definition extends {\n readonly kind: 'table';\n readonly value: infer Value extends Schema<unknown, unknown>;\n readonly key: infer Key extends string;\n }\n ? TableNode<Extract<SchemaNodeOf<Value>, EntitySchemaNode>, Key>\n : Definition extends {\n readonly kind: 'map';\n readonly value: infer Value extends Schema<unknown, unknown>;\n readonly key: infer Key extends string;\n readonly optional: infer Optional extends boolean;\n }\n ? Optionalized<MapNode<Extract<SchemaNodeOf<Value>, ValueSchemaNode>, Key>, Optional>\n : Definition extends {\n readonly kind: 'list';\n readonly value: infer TValue;\n readonly optional: infer Optional extends boolean;\n }\n ? Optionalized<ListNode<TValue>, Optional>\n : Definition extends {\n readonly kind: 'tree';\n readonly value: infer TValue;\n readonly valueOptional: infer ValueOptional extends boolean;\n readonly optional: infer Optional extends boolean;\n }\n ? Optionalized<TreeNodeFor<TValue, ValueOptional>, Optional>\n : DocumentNode;\n\nexport type SchemaNodeOf<S extends Schema<unknown, unknown>> = SchemaNodeFromDefinition<\n SchemaDefinitionOf<S>\n>;\n\nexport const schemaNodeOf = <S extends Schema<unknown, unknown>>(schema: S): SchemaNodeOf<S> =>\n schema as unknown as SchemaNodeOf<S>;\n\n// Flatten only schema-generated objects; user-supplied field values stay opaque.\ntype SchemaObject<T> = { [K in keyof T]: T[K] } & {};\n\n/** Infer a document or node value, including optional node presence. */\ntype InferNode<T extends DocumentNode> = T extends { readonly optional: true }\n ? NodeValue<T> | undefined\n : NodeValue<T>;\n\nexport type Infer<T extends Schema<unknown, unknown> | DocumentNode> =\n T extends Schema<infer TValue, unknown> ? TValue : T extends DocumentNode ? InferNode<T> : never;\n\ntype NodeValue<N> =\n N extends FieldNode<infer T, infer O>\n ? O extends true\n ? ReadonlyValue<T> | undefined\n : ReadonlyValue<T>\n : N extends ObjectNode<infer S>\n ? ShapeValue<S>\n : N extends VariantNode<infer T, infer V>\n ? {\n [K in keyof V & string]: SchemaObject<{ readonly [P in T]: K } & NodeValue<V[K]>>;\n }[keyof V & string]\n : N extends TableNode<infer V, infer K>\n ? {\n readonly ids: readonly K[];\n readonly byId: Readonly<Record<K, NodeValue<V>>>;\n }\n : N extends MapNode<infer V, infer K>\n ? Readonly<Record<K, NodeValue<V>>>\n : N extends ListNode<infer I>\n ? readonly ReadonlyValue<I>[]\n : N extends TreeNode<infer T, infer O>\n ? DocumentTreeValue<T, O>\n : never;\n\ntype OptionalKeys<S extends ObjectShape> = {\n [K in keyof S]: S[K] extends { readonly optional: true } ? K : never;\n}[keyof S];\ntype RequiredKeys<S extends ObjectShape> = Exclude<keyof S, OptionalKeys<S>>;\ntype ShapeValue<S extends ObjectShape> = SchemaObject<\n { readonly [K in RequiredKeys<S>]: NodeValue<S[K]> } & {\n readonly [K in OptionalKeys<S>]?: NodeValue<S[K]>;\n }\n>;\n\nexport type RootNodeOf<S extends ObjectSchema<object>> = Extract<SchemaNodeOf<S>, ObjectNode>;\nexport type EntitySchemaNode = ObjectNode<ObjectShape> | VariantNode<string, VariantShape>;\nexport type ValueSchemaNode = EntitySchemaNode | FieldNode<unknown, boolean>;\nexport type DocumentAnchor<K extends string = string> =\n { readonly at: 'start' | 'end' } | { readonly before: K } | { readonly after: K };\n\ntype NodeShapeOf<S extends PublicSchemaShape> = {\n readonly [K in keyof S]: SchemaNodeOf<S[K]>;\n};\ntype PublicOptionalKeys<S extends PublicSchemaShape> = {\n [K in keyof S]: SchemaNodeOf<S[K]> extends { readonly optional: true } ? K : never;\n}[keyof S];\ntype PublicRequiredKeys<S extends PublicSchemaShape> = Exclude<keyof S, PublicOptionalKeys<S>>;\ntype PublicShapeValue<S extends PublicSchemaShape> = SchemaObject<\n { readonly [K in PublicRequiredKeys<S>]: Infer<S[K]> } & {\n readonly [K in PublicOptionalKeys<S>]?: Infer<S[K]>;\n }\n>;\ntype PublicVariantShape = { readonly [key: string]: ObjectSchema<object> };\ntype VariantNodeShapeOf<V extends PublicVariantShape> = {\n readonly [K in keyof V]: Extract<SchemaNodeOf<V[K]>, ObjectNode>;\n};\nexport const collectionEntryNode = (node: DocumentNode): ValueSchemaNode | undefined =>\n node.kind === 'map' || node.kind === 'table' || node.kind === 'list' ? node.value : undefined;\n\nconst node = <T extends DocumentNode>(value: T): T => Object.freeze(value);\ntype OptionalLeaf =\n | FieldNode<unknown, boolean>\n | VariantNode<string, VariantShape>\n | MapNode<ValueSchemaNode>\n | ListNode<unknown>\n | TreeNode<unknown, false>\n | TreeNode<unknown, true>;\ntype FieldSchema<T, Optional extends boolean = boolean> = Schema<\n ReadonlyValue<T> | (Optional extends true ? undefined : never),\n { readonly kind: 'field'; readonly value: T; readonly optional: Optional }\n>;\ntype VariantSchema = Schema<\n unknown,\n {\n readonly kind: 'variant';\n readonly tag: string;\n readonly variants: PublicVariantShape;\n readonly optional: boolean;\n }\n>;\ntype MapSchema = Schema<\n unknown,\n {\n readonly kind: 'map';\n readonly value: Schema<unknown, unknown>;\n readonly key: string;\n readonly optional: boolean;\n }\n>;\ntype ListSchema = Schema<\n unknown,\n { readonly kind: 'list'; readonly value: unknown; readonly optional: boolean }\n>;\ntype TreeSchema = Schema<\n unknown,\n {\n readonly kind: 'tree';\n readonly value: unknown;\n readonly valueOptional: boolean;\n readonly optional: boolean;\n }\n>;\ntype OptionalSchema = FieldSchema<unknown> | VariantSchema | MapSchema | ListSchema | TreeSchema;\ntype EntitySchema = ObjectSchema<object> | VariantSchema;\ntype ValueSchema = EntitySchema | FieldSchema<unknown>;\ntype EntityNodeOf<V extends EntitySchema> = Extract<SchemaNodeOf<V>, EntitySchemaNode>;\ntype ValueNodeOf<V extends ValueSchema> = Extract<SchemaNodeOf<V>, ValueSchemaNode>;\n\nexport const field = <T>(\n validator?: Validator<T>\n): Schema<\n ReadonlyValue<T>,\n { readonly kind: 'field'; readonly value: T; readonly optional: false }\n> =>\n node({ kind: 'field', ...(validator ? { validator } : {}) }) as unknown as Schema<\n ReadonlyValue<T>,\n { readonly kind: 'field'; readonly value: T; readonly optional: false }\n >;\n\nexport function optional<T, Optional extends boolean>(\n value: Schema<\n ReadonlyValue<T> | (Optional extends true ? undefined : never),\n { readonly kind: 'field'; readonly value: T; readonly optional: Optional }\n >\n): Schema<\n ReadonlyValue<T> | undefined,\n { readonly kind: 'field'; readonly value: T; readonly optional: true }\n>;\nexport function optional<\n TValue,\n Tag extends string,\n Variants extends PublicVariantShape,\n Optional extends boolean,\n>(\n value: Schema<\n TValue,\n {\n readonly kind: 'variant';\n readonly tag: Tag;\n readonly variants: Variants;\n readonly optional: Optional;\n }\n >\n): Schema<\n TValue | undefined,\n {\n readonly kind: 'variant';\n readonly tag: Tag;\n readonly variants: Variants;\n readonly optional: true;\n }\n>;\nexport function optional<\n TValue,\n Value extends Schema<unknown, unknown>,\n Key extends string,\n Optional extends boolean,\n>(\n value: Schema<\n TValue,\n {\n readonly kind: 'map';\n readonly value: Value;\n readonly key: Key;\n readonly optional: Optional;\n }\n >\n): Schema<\n TValue | undefined,\n { readonly kind: 'map'; readonly value: Value; readonly key: Key; readonly optional: true }\n>;\nexport function optional<TValue, TItem, Optional extends boolean>(\n value: Schema<\n TValue,\n { readonly kind: 'list'; readonly value: TItem; readonly optional: Optional }\n >\n): Schema<\n TValue | undefined,\n { readonly kind: 'list'; readonly value: TItem; readonly optional: true }\n>;\nexport function optional<\n TValue,\n TNodeValue,\n ValueOptional extends boolean,\n Optional extends boolean,\n>(\n value: Schema<\n TValue,\n {\n readonly kind: 'tree';\n readonly value: TNodeValue;\n readonly valueOptional: ValueOptional;\n readonly optional: Optional;\n }\n >\n): Schema<\n TValue | undefined,\n {\n readonly kind: 'tree';\n readonly value: TNodeValue;\n readonly valueOptional: ValueOptional;\n readonly optional: true;\n }\n>;\nexport function optional(value: OptionalSchema): Schema<unknown, unknown> {\n const concrete = schemaNodeOf(value) as OptionalLeaf;\n if (!['field', 'variant', 'map', 'list', 'tree'].includes(concrete.kind))\n throw new TypeError('Only field, variant, map, list and tree nodes support optional presence.');\n return node({ ...concrete, optional: true } as OptionalNode<\n typeof concrete\n >) as unknown as Schema<unknown, unknown>;\n}\n\nexport const object = <S extends PublicSchemaShape>(\n shape: S\n): ObjectSchema<PublicShapeValue<S>, S> =>\n node({\n kind: 'object',\n shape: Object.freeze(\n Object.fromEntries(Object.entries(shape).map(([key, value]) => [key, schemaNodeOf(value)]))\n ) as NodeShapeOf<S>,\n }) as unknown as ObjectSchema<PublicShapeValue<S>, S>;\nexport const variant = <T extends string, V extends PublicVariantShape>(\n tag: T,\n variants: V\n): Schema<\n {\n [K in keyof V & string]: SchemaObject<{ readonly [P in T]: K } & Infer<V[K]>>;\n }[keyof V & string],\n {\n readonly kind: 'variant';\n readonly tag: T;\n readonly variants: V;\n readonly optional: false;\n }\n> =>\n node({\n kind: 'variant',\n tag,\n variants: Object.freeze(\n Object.fromEntries(Object.entries(variants).map(([key, value]) => [key, schemaNodeOf(value)]))\n ) as VariantNodeShapeOf<V>,\n }) as unknown as Schema<\n {\n [K in keyof V & string]: SchemaObject<{ readonly [P in T]: K } & Infer<V[K]>>;\n }[keyof V & string],\n {\n readonly kind: 'variant';\n readonly tag: T;\n readonly variants: V;\n readonly optional: false;\n }\n >;\nexport const table = <V extends EntitySchema, K extends string = string>(\n value: V,\n options?: { readonly key: Validator<K> }\n): Schema<\n {\n readonly ids: readonly K[];\n readonly byId: Readonly<Record<K, Exclude<Infer<V>, undefined>>>;\n },\n { readonly kind: 'table'; readonly value: V; readonly key: K }\n> =>\n node({\n kind: 'table',\n value: schemaNodeOf(value) as EntityNodeOf<V>,\n ...options,\n }) as unknown as Schema<\n {\n readonly ids: readonly K[];\n readonly byId: Readonly<Record<K, Exclude<Infer<V>, undefined>>>;\n },\n { readonly kind: 'table'; readonly value: V; readonly key: K }\n >;\nexport const map = <V extends ValueSchema, K extends string = string>(\n value: V,\n options?: { readonly key: Validator<K> }\n): Schema<\n Readonly<\n Record<\n K,\n V extends Schema<infer TValue, infer Definition>\n ? Definition extends { readonly kind: 'field' }\n ? TValue\n : Exclude<TValue, undefined>\n : never\n >\n >,\n {\n readonly kind: 'map';\n readonly value: V;\n readonly key: K;\n readonly optional: false;\n }\n> =>\n node({\n kind: 'map',\n value: schemaNodeOf(value) as ValueNodeOf<V>,\n ...options,\n }) as unknown as Schema<\n Readonly<\n Record<\n K,\n V extends Schema<infer TValue, infer Definition>\n ? Definition extends { readonly kind: 'field' }\n ? TValue\n : Exclude<TValue, undefined>\n : never\n >\n >,\n {\n readonly kind: 'map';\n readonly value: V;\n readonly key: K;\n readonly optional: false;\n }\n >;\nexport const list = <TItem>(\n value: Schema<\n ReadonlyValue<TItem>,\n { readonly kind: 'field'; readonly value: TItem; readonly optional: false }\n >,\n config: DocumentListConfig<TItem>\n): Schema<\n readonly ReadonlyValue<TItem>[],\n { readonly kind: 'list'; readonly value: TItem; readonly optional: false }\n> =>\n node({\n kind: 'list',\n keyOf: config.keyOf,\n value: schemaNodeOf(value),\n }) as unknown as Schema<\n readonly ReadonlyValue<TItem>[],\n { readonly kind: 'list'; readonly value: TItem; readonly optional: false }\n >;\nexport function tree<TValue>(\n value: Schema<\n ReadonlyValue<TValue>,\n { readonly kind: 'field'; readonly value: TValue; readonly optional: false }\n >\n): Schema<\n DocumentTreeValue<TValue, false>,\n {\n readonly kind: 'tree';\n readonly value: TValue;\n readonly valueOptional: false;\n readonly optional: false;\n }\n>;\nexport function tree<TValue>(\n value: Schema<\n ReadonlyValue<TValue> | undefined,\n { readonly kind: 'field'; readonly value: TValue; readonly optional: true }\n >\n): Schema<\n DocumentTreeValue<TValue, true>,\n {\n readonly kind: 'tree';\n readonly value: TValue;\n readonly valueOptional: true;\n readonly optional: false;\n }\n>;\nexport function tree(\n value: FieldSchema<unknown>\n): Schema<DocumentTreeValue<unknown, boolean>, unknown> {\n return Object.freeze({\n kind: 'tree' as const,\n value: schemaNodeOf(value),\n }) as unknown as Schema<DocumentTreeValue<unknown, boolean>, unknown>;\n}\n","import { profile } from '../profile';\n\nexport type KeyOrder = {\n readonly length: number;\n readonly at: (index: number) => string | undefined;\n readonly index: (key: string) => number;\n};\n\nexport type OrderedKeys = readonly string[] | KeyOrder;\n\ntype ListSequence = {\n readonly order: readonly string[];\n readonly values: ReadonlyMap<string, unknown>;\n};\n\nconst length = (keys: OrderedKeys): number => keys.length;\nconst keyAt = (keys: OrderedKeys, index: number): string | undefined =>\n Array.isArray(keys) ? keys[index] : keys.at(index);\n\nexport const equal = (left: readonly string[], right: OrderedKeys): boolean => {\n profile.equality.call();\n if (left === right) return true;\n profile.equality.container();\n if (left.length !== right.length) return false;\n for (let index = 0; index < left.length; index++)\n if (left[index] !== keyAt(right, index)) return false;\n return true;\n};\n\nexport const keys = (values: readonly unknown[], keyOf: (value: unknown) => string): KeyOrder => ({\n length: values.length,\n at: index => (index >= 0 && index < values.length ? keyOf(values[index]) : undefined),\n index: key => {\n for (let index = 0; index < values.length; index += 1)\n if (keyOf(values[index]) === key) return index;\n return -1;\n },\n});\n\nconst listIndexes = new WeakMap<\n readonly unknown[],\n { keyOf: (value: unknown) => string; order: KeyOrder }\n>();\n\nconst knownKeys = (values: readonly string[]): KeyOrder => {\n let positions: Map<string, number> | undefined;\n return {\n length: values.length,\n at: index => values[index],\n index: key => {\n if (!positions) {\n positions = new Map();\n for (let index = 0; index < values.length; index++) positions.set(values[index], index);\n profile.address.listIndex(values.length);\n }\n return positions.get(key) ?? -1;\n },\n };\n};\n\nconst cacheKnownKeys = (\n values: readonly unknown[],\n keyOf: (value: unknown) => string,\n order: readonly string[]\n): void => {\n listIndexes.set(values, { keyOf, order: knownKeys(order) });\n};\n\n/** Canonical lists keep their key positions until a structural write invalidates them. */\nexport const indexedKeys = (\n values: readonly unknown[],\n keyOf: (value: unknown) => string\n): KeyOrder => {\n const cached = listIndexes.get(values);\n if (cached?.keyOf === keyOf) return cached.order;\n let positions: Map<string, number> | undefined;\n const order: KeyOrder = {\n length: values.length,\n at: index => (index >= 0 && index < values.length ? keyOf(values[index]) : undefined),\n index: key => {\n if (!positions) {\n positions = new Map();\n for (let index = 0; index < values.length; index++)\n positions.set(keyOf(values[index]), index);\n profile.address.listIndex(values.length);\n }\n return positions.get(key) ?? -1;\n },\n };\n listIndexes.set(values, { keyOf, order });\n return order;\n};\n\nexport const toArray = (keys: OrderedKeys): string[] => {\n const result = new Array<string>(length(keys));\n for (let index = 0; index < result.length; index++) result[index] = keyAt(keys, index) as string;\n return result;\n};\n\n/** One operation-local list scan provides both stable keys and item association. */\nexport const listSequence = (\n values: readonly unknown[],\n keyOf: (value: unknown) => string\n): ListSequence => {\n const current = indexedKeys(values, keyOf);\n const order = new Array<string>(values.length);\n const byKey = new Map<string, unknown>();\n for (let index = 0; index < values.length; index++) {\n const key = current.at(index) as string;\n order[index] = key;\n byKey.set(key, values[index]);\n }\n cacheKnownKeys(values, keyOf, order);\n return { order, values: byKey };\n};\n\n/** Structural sequence writes own invalidation, including rollback writes. */\nexport const insert = (values: unknown[], index: number, value: unknown): void => {\n values.splice(index, 0, value);\n listIndexes.delete(values);\n};\n\nexport const remove = (values: unknown[], index: number): void => {\n values.splice(index, 1);\n listIndexes.delete(values);\n};\n\n/** Installs an exact string-key sequence such as table ids in one structural write. */\nexport const installKeys = (values: string[], order: readonly string[]): void => {\n values.length = order.length;\n for (let index = 0; index < order.length; index++) values[index] = order[index];\n};\n\n/** Installs a pre-resolved list sequence without running keyOf again. */\nexport const installList = (\n values: unknown[],\n keyOf: (value: unknown) => string,\n sequence: ListSequence,\n order: readonly string[]\n): void => {\n values.length = order.length;\n for (let index = 0; index < order.length; index++)\n values[index] = sequence.values.get(order[index]);\n cacheKnownKeys(values, keyOf, order);\n};\n\nexport const install = (\n values: unknown[],\n keyOf: (value: unknown) => string,\n order: readonly string[]\n): void => {\n installList(values, keyOf, listSequence(values, keyOf), order);\n};\n\nexport const matches = (order: readonly string[], members: readonly string[]): boolean => {\n if (order.length !== members.length) return false;\n const ids = new Set(order);\n return ids.size === order.length && members.every(id => ids.has(id));\n};\n","import { profile } from '../profile';\nimport type { DocumentNode, ObjectNode, ObjectShape, VariantNode, VariantShape } from './model';\n\ntype MemberDefinition = {\n readonly node: DocumentNode;\n readonly field: boolean;\n};\n\nexport type FixedMember = MemberDefinition & {\n readonly kind: 'fixed';\n readonly key: string;\n readonly slot: number;\n};\n\ntype CollectionMember = MemberDefinition & { readonly kind: 'entry' };\n\nexport type CompiledMember = FixedMember | CollectionMember;\n\nexport type FixedLayout = {\n readonly kind: 'fixed';\n readonly members: ReadonlyMap<string, FixedMember>;\n};\n\ntype DynamicLayout = {\n readonly kind: 'dynamic';\n readonly entry: CollectionMember;\n};\n\nexport type MemberLayout = FixedLayout | DynamicLayout;\n\nconst compiledObjects = new WeakMap<object, FixedLayout>();\nconst compiledEntries = new WeakMap<DocumentNode, DynamicLayout>();\n\nexport const variantBranch = (\n node: VariantNode<string, VariantShape>,\n discriminator: string | undefined\n): ObjectNode<ObjectShape> | undefined =>\n node.variants[discriminator ?? Object.keys(node.variants)[0] ?? ''];\n\nconst objectBranch = (node: DocumentNode, value: unknown): ObjectNode<ObjectShape> | undefined => {\n if (node.kind === 'object') return node;\n if (\n node.kind !== 'variant' ||\n typeof value !== 'object' ||\n value === null ||\n Array.isArray(value)\n )\n return undefined;\n const record = value as Record<string, unknown>;\n const rawTag = record[node.tag];\n const tag = typeof rawTag === 'string' ? rawTag : undefined;\n return variantBranch(node, tag);\n};\n\nexport const compiledShape = (node: DocumentNode, value: unknown): FixedLayout | undefined => {\n const branch = objectBranch(node, value);\n if (!branch) return undefined;\n const shape: ObjectShape = branch.shape;\n let layout = compiledObjects.get(shape);\n if (!layout) {\n const members = new Map<string, FixedMember>();\n for (const key of Object.keys(shape).sort()) {\n profile.address.schemaStep();\n members.set(key, {\n kind: 'fixed',\n key,\n node: shape[key],\n field: shape[key].kind === 'field',\n slot: members.size,\n });\n }\n layout = { kind: 'fixed', members };\n compiledObjects.set(shape, layout);\n }\n return layout;\n};\n\nexport const compiledLayout = (node: DocumentNode, value: unknown): MemberLayout | undefined => {\n if (node.kind !== 'map' && node.kind !== 'table' && node.kind !== 'list')\n return compiledShape(node, value);\n let layout = compiledEntries.get(node);\n if (!layout) {\n layout = {\n kind: 'dynamic',\n entry: { kind: 'entry', node: node.value, field: node.value.kind === 'field' },\n };\n compiledEntries.set(node, layout);\n }\n return layout;\n};\n","import { profile } from '../profile';\nimport * as sequence from '../order/sequence';\nimport * as tree from '../tree/topology';\nimport { isPlainObject, isRecord } from '../value/record';\nimport type {\n DocumentAddress,\n DocumentNode,\n DocumentTreeNode,\n FieldNode,\n Infer,\n Schema,\n Validator,\n} from './model';\nimport { schemaNodeOf } from './model';\nimport { compiledShape } from './layout';\n\nexport type ParseIssue = {\n readonly address: DocumentAddress;\n readonly code: 'invalid-value' | 'invalid-key' | 'missing-validator' | 'invalid-tree';\n readonly message: string;\n};\nexport class ParseError extends TypeError {\n readonly issues: readonly ParseIssue[];\n constructor(issue: ParseIssue) {\n super(`${issue.message} at ${JSON.stringify(issue.address)}`);\n this.name = 'ParseError';\n this.issues = Object.freeze([\n Object.freeze({ ...issue, address: Object.freeze([...issue.address]) }),\n ]);\n }\n}\n\nconst issue = (\n address: DocumentAddress,\n message: string,\n code: ParseIssue['code'] = 'invalid-value'\n): ParseIssue => ({ address, message, code });\n\nconst checkScalar = (\n validator: Validator<unknown> | undefined,\n value: unknown,\n address: DocumentAddress,\n strict: boolean\n): ParseIssue | undefined => {\n if (!validator)\n return strict\n ? issue(address, 'A validator is required to parse an opaque value.', 'missing-validator')\n : undefined;\n try {\n const result =\n typeof validator === 'function' ? validator(value) : validator['~standard'].validate(value);\n if (\n result &&\n (typeof result === 'object' || typeof result === 'function') &&\n 'then' in result &&\n typeof result.then === 'function'\n )\n return issue(address, 'Validators must be synchronous.');\n if (typeof validator === 'function') {\n if (result === false) return issue(address, 'Value validation failed.');\n if (result !== undefined && result !== true)\n return issue(address, 'Function validators must return boolean or undefined.');\n } else {\n if (!isRecord(result)) return issue(address, 'Malformed validator result.');\n if (Array.isArray(result.issues)) {\n const first = result.issues[0];\n return issue(\n [\n ...address,\n ...(first?.path ?? []).map((part: PropertyKey | { key: PropertyKey }) =>\n String(typeof part === 'object' ? part.key : part)\n ),\n ],\n first?.message ?? 'Value validation failed.'\n );\n }\n if (!Object.hasOwn(result, 'value')) return issue(address, 'Malformed validator result.');\n if (!Object.is((result as { readonly value: unknown }).value, value))\n return issue(address, 'Validators must not transform values.');\n }\n return undefined;\n } catch (error) {\n return issue(address, error instanceof Error ? error.message : 'Value validation failed.');\n }\n};\n\nexport const checkKey = (\n validator: Validator<string> | undefined,\n value: unknown,\n address: DocumentAddress\n): ParseIssue | undefined => {\n if (typeof value !== 'string')\n return issue(address, 'Collection keys must be strings.', 'invalid-key');\n const failure = checkScalar(validator, value, address, false);\n return failure ? { ...failure, code: 'invalid-key' } : undefined;\n};\n\nexport const checkValue = (\n node: DocumentNode,\n value: unknown,\n address: DocumentAddress = [],\n strict = false\n): ParseIssue | undefined => {\n if (node.optional && value === undefined) return undefined;\n if (node.kind === 'field') return checkScalar(node.validator, value, address, strict);\n if (node.kind === 'object' || node.kind === 'variant') {\n if (!isPlainObject(value)) return issue(address, 'Expected an object.');\n if (node.kind === 'variant') {\n const tag = value[node.tag];\n if (\n !Object.hasOwn(value, node.tag) ||\n typeof tag !== 'string' ||\n !Object.hasOwn(node.variants, tag)\n )\n return issue([...address, node.tag], 'Unknown variant tag.');\n }\n const { members } = compiledShape(node, value)!;\n for (const key of Reflect.ownKeys(value)) {\n if (node.kind === 'variant' && key === node.tag) continue;\n if (typeof key !== 'string' || !members.has(key))\n return issue([...address, String(key)], 'Property is not declared in the object schema.');\n }\n for (const [key, member] of members) {\n const child = member.node;\n if (!Object.prototype.hasOwnProperty.call(value, key) && !child.optional)\n return issue([...address, key], 'Required property is missing.');\n const failure = checkValue(child, value[key], [...address, key], strict);\n if (failure) return failure;\n }\n return undefined;\n }\n if (node.kind === 'table' || node.kind === 'map') {\n if (!isPlainObject(value)) return issue(address, 'Expected a collection object.');\n const entries = node.kind === 'table' ? value.byId : value;\n if (!isPlainObject(entries)) return issue(address, 'Expected a byId object.');\n if (node.kind === 'table') {\n if (!Array.isArray(value.ids) || value.ids.length !== Object.keys(entries).length)\n return issue(address, 'Table ids and entries must agree.');\n const seen = new Set<string>();\n for (const id of value.ids) {\n const failure = checkKey(node.key, id, address);\n if (failure) return failure;\n if (seen.has(id) || !Object.prototype.hasOwnProperty.call(entries, id))\n return issue(address, 'Table ids must be unique and reference existing entries.');\n seen.add(id);\n }\n }\n for (const id of Object.keys(entries)) {\n const failure =\n checkKey(node.key, id, [...address, id]) ??\n checkValue(node.value, entries[id], [...address, id], strict);\n if (failure) return failure;\n }\n return undefined;\n }\n if (node.kind === 'list') {\n if (!Array.isArray(value)) return issue(address, 'Expected a list.');\n const seen = new Set<string>();\n const order = sequence.keys(value, node.keyOf);\n for (let i = 0; i < value.length; i++) {\n const failure = checkValue(node.value, value[i], [...address, String(i)], strict);\n if (failure) return failure;\n let key: unknown;\n try {\n key = order.at(i);\n } catch {\n return issue(address, 'List keyOf failed.');\n }\n if (typeof key !== 'string' || seen.has(key))\n return issue(address, 'List keys must be unique strings.', 'invalid-key');\n seen.add(key);\n }\n return undefined;\n }\n if (!tree.validate(value)) return issue(address, 'Invalid tree structure.', 'invalid-tree');\n for (const id of Object.keys(value.nodes)) {\n const failure = checkTreePayload(node.value, value.nodes[id], [...address, id], strict);\n if (failure) return failure;\n }\n return undefined;\n};\n\nexport const checkTreePayload = (\n node: FieldNode<unknown, boolean>,\n value: unknown,\n address: DocumentAddress,\n strict = false\n): ParseIssue | undefined => {\n if (!isRecord(value)) return issue(address, 'Invalid tree node.', 'invalid-tree');\n const present = Object.prototype.hasOwnProperty.call(value, 'value');\n if (!present && !node.optional) return issue(address, 'Tree node value is required.');\n return present ? checkValue(node, value.value, address, strict) : undefined;\n};\n\nexport const copyTreeNode = <T extends { readonly children: readonly string[] }>(\n value: T\n): Omit<T, 'children'> & { children: string[] } => {\n profile.copy.treeNode();\n return { ...value, children: [...value.children] };\n};\n\nexport const equalTreeNode = (\n left: DocumentTreeNode<unknown, false> | DocumentTreeNode<unknown, true> | undefined,\n right: DocumentTreeNode<unknown, false> | DocumentTreeNode<unknown, true> | undefined\n): boolean => {\n if (left === right) return true;\n if (!left || !right) return false;\n return (\n left.parentId === right.parentId &&\n sequence.equal(left.children, right.children) &&\n Object.hasOwn(left, 'value') === Object.hasOwn(right, 'value') &&\n Object.is(left.value, right.value)\n );\n};\n\n/** Copy editable structure; atomic payloads retain their immutable ownership contract. */\nexport const copyValue = (node: DocumentNode, value: unknown): unknown => {\n if (value === undefined || node.kind === 'field') return value;\n profile.copy.structure();\n if ((node.kind === 'object' || node.kind === 'variant') && isRecord(value)) {\n const result = Object.create(Object.getPrototypeOf(value));\n const { members } = compiledShape(node, value)!;\n for (const key of Object.getOwnPropertyNames(value)) {\n Object.defineProperty(result, key, {\n value:\n node.kind === 'variant' && key === node.tag\n ? value[key]\n : copyValue(members.get(key)!.node, value[key]),\n writable: true,\n enumerable: Object.getOwnPropertyDescriptor(value, key)?.enumerable,\n configurable: true,\n });\n }\n return result;\n }\n if ((node.kind === 'table' || node.kind === 'map') && isRecord(value)) {\n const entries = (node.kind === 'table' ? value.byId : value) as Record<string, unknown>;\n const result = Object.fromEntries(\n Object.keys(entries).map(id => [id, copyValue(node.value, entries[id])])\n );\n return node.kind === 'table' ? { ids: [...(value.ids as string[])], byId: result } : result;\n }\n if (node.kind === 'list') return [...(value as unknown[])];\n if (node.kind === 'tree' && isRecord(value)) {\n const entries = value.nodes as Record<\n string,\n DocumentTreeNode<unknown, false> | DocumentTreeNode<unknown, true>\n >;\n return {\n ...value,\n nodes: Object.fromEntries(Object.entries(entries).map(([id, n]) => [id, copyTreeNode(n)])),\n };\n }\n return value;\n};\n\nexport const equalValue = (node: DocumentNode, left: unknown, right: unknown): boolean => {\n if (Object.is(left, right)) return true;\n if (node.kind === 'field' || left === undefined || right === undefined) return false;\n if ((node.kind === 'object' || node.kind === 'variant') && isRecord(left) && isRecord(right)) {\n if (node.kind === 'variant' && left[node.tag] !== right[node.tag]) return false;\n for (const [key, member] of compiledShape(node, left)!.members) {\n if (Object.hasOwn(left, key) !== Object.hasOwn(right, key)) return false;\n if (!equalValue(member.node, left[key], right[key])) return false;\n }\n return true;\n }\n if (node.kind === 'list' && Array.isArray(left) && Array.isArray(right))\n return (\n left.length === right.length && left.every((v, i) => equalValue(node.value, v, right[i]))\n );\n if (node.kind === 'table' && isRecord(left) && isRecord(right))\n return (\n sequence.equal(left.ids as string[], right.ids as string[]) &&\n equalValue({ kind: 'map', value: node.value }, left.byId, right.byId)\n );\n if (node.kind === 'tree' && isRecord(left) && isRecord(right)) {\n if (left.rootId !== right.rootId) return false;\n const a = left.nodes as Record<\n string,\n DocumentTreeNode<unknown, false> | DocumentTreeNode<unknown, true>\n >,\n b = right.nodes as typeof a;\n return (\n Object.keys(a).length === Object.keys(b).length &&\n Object.keys(a).every(id => Object.hasOwn(b, id) && equalTreeNode(a[id], b[id]))\n );\n }\n if (node.kind === 'map' && isRecord(left) && isRecord(right)) {\n const keys = Object.keys(left);\n return (\n keys.length === Object.keys(right).length &&\n keys.every(key => Object.hasOwn(right, key) && equalValue(node.value, left[key], right[key]))\n );\n }\n return false;\n};\n\nexport const parse = <S extends Schema<unknown>>(schema: S, input: unknown): Infer<S> => {\n const valueNode = schemaNodeOf(schema);\n const failure = checkValue(valueNode, input, [], true);\n if (failure) throw new ParseError(failure);\n return copyValue(valueNode, input) as Infer<S>;\n};\n","import * as sequence from '../order/sequence';\nimport { profile } from '../profile';\nimport type { DocumentAddress, DocumentNode } from '../schema/model';\nimport { compiledLayout, variantBranch, type MemberLayout } from '../schema/layout';\nimport * as tree from '../tree/topology';\nimport { isRecord } from '../value/record';\n\nconst step = (\n nodeInput: DocumentNode | undefined,\n value: unknown,\n segment: string\n): DocumentNode | undefined => {\n let node = nodeInput;\n if (!node) return undefined;\n if (node.kind === 'variant') {\n const rawTag = isRecord(value) ? value[node.tag] : undefined;\n const tag = typeof rawTag === 'string' ? rawTag : undefined;\n node = variantBranch(node, tag);\n }\n if (!node) return undefined;\n if (node.kind === 'object')\n return Object.hasOwn(node.shape, segment) ? node.shape[segment] : undefined;\n if (node.kind === 'table' || node.kind === 'map') return node.value;\n // List items use stable keys; tree topology remains a structural unit.\n if (node.kind === 'list') return node.value;\n return undefined;\n};\n\nexport const nodeAt = (\n schema: DocumentNode,\n address: DocumentAddress,\n document?: unknown\n): DocumentNode | undefined => {\n let node: DocumentNode | undefined = schema;\n let value = document;\n for (const segment of address) {\n const resolved = step(node, value, segment);\n value = readSegment(value, segment, node);\n node = resolved;\n if (!node) return undefined;\n }\n return node;\n};\n\nconst readSegment = (value: unknown, segment: string, node?: DocumentNode): unknown => {\n if (!isRecord(value) && !Array.isArray(value)) return undefined;\n if (node?.kind === 'list' && Array.isArray(value))\n return value[sequence.indexedKeys(value, node.keyOf).index(segment)];\n if (node?.kind === 'table' && isRecord(value) && isRecord(value.byId)) {\n return Object.hasOwn(value.byId, segment) ? value.byId[segment] : undefined;\n }\n return Object.prototype.hasOwnProperty.call(value, segment)\n ? (value as Record<string, unknown>)[segment]\n : undefined;\n};\n\ntype ResolvedAddress = {\n readonly parent: Record<string, unknown> | unknown[];\n readonly key: string | number;\n readonly node: DocumentNode;\n};\n\n/** Immutable location facts, valid only for the resolving session generation. */\nexport type ResolvedContainer = {\n readonly owner: object;\n readonly generation: number;\n readonly at: DocumentAddress;\n readonly node: Exclude<DocumentNode, { kind: 'tree' }>;\n readonly parent: Record<string, unknown> | unknown[];\n readonly value: unknown;\n readonly layout: MemberLayout;\n};\nexport type ResolvedTreeContainer = {\n readonly owner: object;\n readonly generation: number;\n readonly at: DocumentAddress;\n readonly node: Extract<DocumentNode, { kind: 'tree' }>;\n readonly value: tree.MutableTree;\n};\nexport const resolveContainer = (\n owner: object,\n generation: number,\n at: DocumentAddress,\n node: DocumentNode | undefined,\n value: unknown\n): ResolvedContainer | undefined => {\n if (!node || (!isRecord(value) && !Array.isArray(value))) return undefined;\n const parent = node.kind === 'table' && isRecord(value) ? value.byId : value;\n if (!isRecord(parent) && !Array.isArray(parent)) return undefined;\n if (node.kind === 'tree') return undefined;\n const layout = compiledLayout(node, value);\n if (!layout) return undefined;\n return { owner, generation, at, node, parent, value, layout };\n};\nexport const resolveTreeContainer = (\n owner: object,\n generation: number,\n at: DocumentAddress,\n node: DocumentNode | undefined,\n value: unknown\n): ResolvedTreeContainer | undefined =>\n node?.kind === 'tree' && tree.is(value) ? { owner, generation, at, node, value } : undefined;\nexport const memberKey = (\n container: { readonly node: DocumentNode; readonly parent: Record<string, unknown> | unknown[] },\n key: string\n): string | number =>\n container.node.kind === 'list'\n ? sequence.indexedKeys(container.parent as unknown[], container.node.keyOf).index(key)\n : key;\n\ntype ResolutionPrefix = {\n segment: string;\n node: DocumentNode;\n value: unknown;\n};\n\n/** One recent path per transaction; structural writes invalidate all retained locations. */\nexport const createAddressResolver = (schema: DocumentNode, root: unknown) => {\n const prefix: ResolutionPrefix[] = [];\n return {\n container: (owner: object, generation: number, at: DocumentAddress) => {\n if (!at.length) return resolveContainer(owner, generation, at, schema, root);\n const location = resolveWithPrefix(schema, root, at, prefix);\n if (!location || !Object.hasOwn(location.parent, location.key)) return undefined;\n return resolveContainer(\n owner,\n generation,\n at,\n location.node,\n (location.parent as Record<string | number, unknown>)[location.key]\n );\n },\n invalidate: () => {\n prefix.length = 0;\n },\n };\n};\n\n/** A subtree root is a value, not a fabricated member of an ObjectNode. */\nexport const resolveValue = (\n schema: DocumentNode,\n root: unknown,\n address: DocumentAddress,\n prefix?: ResolutionPrefix[]\n): { node: DocumentNode; value: unknown } | undefined => {\n if (!address.length) return { node: schema, value: root };\n const location = resolveWithPrefix(schema, root, address, prefix);\n return (\n location && {\n node: location.node,\n value: Object.hasOwn(location.parent, location.key)\n ? (location.parent as Record<string | number, unknown>)[location.key]\n : undefined,\n }\n );\n};\n\n/** Resolves schema and document location in one address traversal. */\nexport const resolveLocated = (\n schema: DocumentNode,\n root: unknown,\n address: DocumentAddress\n): ResolvedAddress | undefined => resolveWithPrefix(schema, root, address);\n\nconst resolveWithPrefix = (\n schema: DocumentNode,\n root: unknown,\n address: DocumentAddress,\n prefix?: ResolutionPrefix[]\n): ResolvedAddress | undefined => {\n if (address.length === 0) return undefined;\n let node: DocumentNode | undefined = schema;\n let current: unknown = root;\n let start = 0;\n if (prefix) {\n while (\n start < prefix.length &&\n start < address.length - 1 &&\n prefix[start].segment === address[start]\n )\n start++;\n prefix.length = start;\n if (start) {\n const retained = prefix[start - 1];\n node = retained.node;\n current = retained.value;\n }\n }\n let cacheable = true;\n for (let index = start; index < address.length - 1; index += 1) {\n profile.address.schemaStep();\n profile.address.documentStep();\n const resolved = step(node, current, address[index]);\n if (!resolved) return undefined;\n if (node?.kind !== 'object' && node?.kind !== 'table' && node?.kind !== 'map')\n cacheable = false;\n current = readSegment(current, address[index], node);\n node = resolved;\n if (prefix && cacheable)\n prefix.push({\n segment: address[index],\n node: resolved,\n value: current,\n });\n if (!node) return undefined;\n }\n const last = address[address.length - 1];\n return resolveChild(node, current, last);\n};\n\n/** Resolves one member from an already current schema/container pair. */\nexport const resolveChild = (\n node: DocumentNode | undefined,\n current: unknown,\n last: string\n): ResolvedAddress | undefined => {\n profile.address.schemaStep();\n profile.address.documentStep();\n const resolved = step(node, current, last);\n if (!resolved || (!isRecord(current) && !Array.isArray(current))) return undefined;\n if (node?.kind === 'table' && isRecord(current) && isRecord(current.byId))\n return {\n node: resolved,\n parent: current.byId,\n key: last,\n };\n return {\n node: resolved,\n parent: current,\n key:\n node?.kind === 'list' && Array.isArray(current)\n ? sequence.indexedKeys(current, node.keyOf).index(last)\n : last,\n };\n};\n","import type { DocumentAnchor } from '../schema/model';\nimport type { KeyOrder, OrderedKeys } from './sequence';\n\ntype MoveSelection =\n | { readonly kind: 'ok'; readonly order: readonly string[] }\n | { readonly kind: 'duplicate' }\n | { readonly kind: 'missing' }\n | { readonly kind: 'invalid-anchor' };\n\nconst length = (keys: OrderedKeys): number => keys.length;\nconst keyIndex = (keys: OrderedKeys, key: string): number =>\n Array.isArray(keys) ? keys.indexOf(key) : (keys as KeyOrder).index(key);\n\n/** Plan one relative move against the order that remains after removing the selection. */\nexport const moveSelection = (\n current: readonly string[],\n selection: readonly string[],\n position?: DocumentAnchor\n): MoveSelection => {\n if (!selection.length) return { kind: 'ok', order: current };\n const selected = new Set<string>();\n for (const key of selection) {\n if (selected.has(key)) return { kind: 'duplicate' };\n selected.add(key);\n }\n const moved: string[] = [];\n const remaining: string[] = [];\n for (const key of current) (selected.has(key) ? moved : remaining).push(key);\n if (moved.length !== selected.size) return { kind: 'missing' };\n if (!valid(remaining, position)) return { kind: 'invalid-anchor' };\n const insertion = index(remaining, position);\n return {\n kind: 'ok',\n order: [...remaining.slice(0, insertion), ...moved, ...remaining.slice(insertion)],\n };\n};\n\nexport const index = (keys: OrderedKeys, anchor?: DocumentAnchor): number => {\n if (!anchor) return length(keys);\n if ('at' in anchor) return anchor.at === 'start' ? 0 : length(keys);\n if ('before' in anchor) return keyIndex(keys, anchor.before);\n return keyIndex(keys, anchor.after) + 1;\n};\n\nexport const valid = (keys: OrderedKeys, anchor?: DocumentAnchor): boolean => {\n if (!anchor) return true;\n if (typeof anchor !== 'object' || anchor === null) return false;\n if (Number('at' in anchor) + Number('before' in anchor) + Number('after' in anchor) !== 1)\n return false;\n if ('at' in anchor) return anchor.at === 'start' || anchor.at === 'end';\n return keyIndex(keys, 'before' in anchor ? anchor.before : anchor.after) >= 0;\n};\n","import type { DocumentAnchor } from '../../schema/model';\nimport type { MutationSession } from '../session';\nimport type { ResolvedContainer } from '../../address/resolve';\nimport * as anchor from '../../order/anchor';\nimport * as issue from '../issue';\nexport function create(\n session: MutationSession,\n container: ResolvedContainer,\n entries: readonly { id: string; value: unknown }[],\n position?: DocumentAnchor\n): void {\n const { at, node, value } = container;\n if (node.kind !== 'table') return issue.fail(at, 'invalid-collection', 'Expected a table.');\n const table = value as { ids: string[]; byId: Record<string, unknown> };\n if (!anchor.valid(table.ids, position))\n return issue.fail(at, 'invalid-anchor', 'Unknown table anchor.');\n const ids = new Set<string>();\n for (const entry of entries) {\n if (Object.hasOwn(table.byId, entry.id) || ids.has(entry.id))\n return issue.fail(at, 'duplicate-entity', 'Table key already exists.');\n ids.add(entry.id);\n }\n if (!entries.length) return;\n const index = anchor.index(table.ids, position);\n for (const entry of entries) session.writeMember(container, entry.id, entry.value, 'set');\n const length = table.ids.length;\n table.ids.length += entries.length;\n table.ids.copyWithin(index + entries.length, index, length);\n for (let i = 0; i < entries.length; i++) table.ids[index + i] = entries[i].id;\n}\nexport function remove(\n session: MutationSession,\n container: ResolvedContainer,\n ids: readonly string[]\n): void {\n const { at, node, value } = container;\n if (node.kind !== 'table') return issue.fail(at, 'invalid-collection', 'Expected a table.');\n const table = value as { ids: string[]; byId: Record<string, unknown> };\n for (const id of ids)\n if (!Object.hasOwn(table.byId, id))\n return issue.fail(at, 'missing-entity', 'Table key does not exist.');\n if (!ids.length) return;\n const removed = new Set(ids);\n for (const id of removed) session.writeMember(container, id, undefined, 'remove');\n table.ids = table.ids.filter(id => !removed.has(id));\n}\n\nexport function replace(\n session: MutationSession,\n container: ResolvedContainer,\n id: string,\n value: unknown\n): void {\n const { at, node, value: tableValue } = container;\n if (node.kind !== 'table') return issue.fail(at, 'invalid-collection', 'Expected a table.');\n const table = tableValue as { byId: Record<string, unknown> };\n if (!Object.hasOwn(table.byId, id))\n return issue.fail(at.concat(id), 'missing-entity', 'Table key does not exist.');\n session.writeMember(container, id, value, 'set');\n}\n","import type { DocumentAnchor } from '../../schema/model';\nimport type { MutationSession } from '../session';\nimport type { ResolvedContainer } from '../../address/resolve';\nimport * as anchor from '../../order/anchor';\nimport * as sequence from '../../order/sequence';\nimport * as issue from '../issue';\nexport function insert(\n session: MutationSession,\n container: ResolvedContainer,\n value: unknown,\n position?: DocumentAnchor\n): void {\n const { at, node, value: current } = container;\n if (node.kind !== 'list') return issue.fail(at, 'invalid-list-key', 'Expected a list.');\n session.validate(node.value, value, at);\n const id = node.keyOf(value);\n if (typeof id !== 'string')\n return issue.fail(at, 'invalid-list-key', 'List key must be a string.');\n const items = current as unknown[],\n keys = sequence.keys(items, node.keyOf);\n if (keys.index(id) >= 0) return issue.fail(at, 'duplicate-list-item', 'List key already exists.');\n if (!anchor.valid(keys, position))\n return issue.fail(at, 'invalid-anchor', 'Unknown list anchor.');\n session.recorder.order(container);\n session.recorder.member(container, id, session.definition(container, id), -1);\n sequence.insert(items, anchor.index(keys, position), value);\n session.invalidate();\n}\nexport function replace(\n session: MutationSession,\n container: ResolvedContainer,\n id: string,\n value: unknown\n): void {\n const { at, node, value: items } = container;\n if (node.kind !== 'list') return issue.fail(at, 'invalid-list-key', 'Expected a list.');\n const index = sequence.indexedKeys(items as unknown[], node.keyOf).index(id);\n if (index < 0) return issue.fail(at, 'missing-list-item', 'List key does not exist.');\n session.writeMember(container, id, value, 'set', index);\n}\nexport function remove(session: MutationSession, container: ResolvedContainer, id: string): void {\n const { at, node, value } = container;\n if (node.kind !== 'list') return issue.fail(at, 'missing-list-item', 'List key does not exist.');\n const index = sequence.keys(value as unknown[], node.keyOf).index(id);\n if (index < 0) return issue.fail(at, 'missing-list-item', 'List key does not exist.');\n session.writeMember(container, id, undefined, 'remove', index);\n}\n","import type { DocumentAddress } from '../../schema/model';\nimport type { ResolvedTreeContainer } from '../../address/resolve';\nimport type { MutationSession } from '../session';\nimport * as treeTopology from '../../tree/topology';\nimport type { MutableTree, TreePosition } from '../../tree/topology';\nimport * as issue from '../issue';\nconst node = (tree: MutableTree, id: string) =>\n Object.hasOwn(tree.nodes, id) ? tree.nodes[id] : undefined;\nconst positionIndex = (index: number | undefined, length: number, at: DocumentAddress): number => {\n if (index !== undefined && (!Number.isInteger(index) || index < 0))\n return issue.fail(at, 'invalid-tree-index', 'Tree index must be nonnegative.');\n return Math.min(index ?? length, length);\n};\nexport const insert = (\n session: MutationSession,\n container: ResolvedTreeContainer,\n id: string,\n value: unknown,\n position: TreePosition | undefined\n): void => {\n const { at, node: schema, value: tree } = container;\n if (typeof id !== 'string') return issue.fail(at, 'invalid-key', 'Tree keys must be strings.');\n if (treeTopology.contains(tree, id))\n return issue.fail(at, 'duplicate-tree-node', 'Tree node already exists.');\n const parentId = position?.parentId;\n const parent = parentId === undefined ? undefined : node(tree, parentId);\n if (\n (tree.rootId !== undefined && !parent) ||\n (tree.rootId === undefined && parentId !== undefined)\n )\n return issue.fail(at, 'missing-tree-parent', 'A nonempty tree requires an existing parent.');\n const index = positionIndex(position?.index, parent?.children.length ?? 0, at);\n session.validate(schema.value, value, at.concat(id));\n session.recorder.tree(container, id);\n if (parentId !== undefined) session.recorder.tree(container, parentId);\n Object.defineProperty(tree.nodes, id, {\n value: { ...(parentId === undefined ? {} : { parentId }), children: [], value },\n writable: true,\n configurable: true,\n enumerable: true,\n });\n if (parent) parent.children.splice(index, 0, id);\n else tree.rootId = id;\n session.invalidate();\n};\nexport const replace = (\n session: MutationSession,\n container: ResolvedTreeContainer,\n id: string,\n value: unknown\n): void => {\n const { at, node: schema, value: tree } = container;\n const entry = node(tree, id);\n if (!entry) return issue.fail(at, 'missing-tree-node', 'Tree node does not exist.');\n if (Object.is(entry.value, value) && Object.hasOwn(entry, 'value')) return;\n session.validate(schema.value, value, at.concat(id));\n session.recorder.tree(container, id);\n entry.value = value;\n};\nexport const remove = (\n session: MutationSession,\n container: ResolvedTreeContainer,\n id: string\n): void => {\n const { at, value: tree } = container;\n const entry = node(tree, id);\n if (!entry) return issue.fail(at, 'missing-tree-node', 'Tree node does not exist.');\n const ids: string[] = [],\n stack = [id];\n while (stack.length) {\n const current = stack.pop()!;\n ids.push(current);\n for (const child of tree.nodes[current].children) stack.push(child);\n }\n for (const key of ids) session.recorder.tree(container, key);\n if (entry.parentId !== undefined) session.recorder.tree(container, entry.parentId);\n if (entry.parentId === undefined) delete tree.rootId;\n else {\n const children = tree.nodes[entry.parentId].children;\n children.splice(children.indexOf(id), 1);\n }\n for (const key of ids) delete tree.nodes[key];\n session.invalidate();\n};\nexport const move = (\n session: MutationSession,\n container: ResolvedTreeContainer,\n id: string,\n position: TreePosition | undefined\n): void => {\n const { at, value: tree } = container;\n const entry = node(tree, id),\n parentId = position?.parentId;\n if (!entry) return issue.fail(at, 'missing-tree-node', 'Tree node does not exist.');\n if (\n entry.parentId === undefined ||\n parentId === undefined ||\n !treeTopology.contains(tree, parentId)\n )\n return issue.fail(\n at,\n 'missing-tree-parent',\n 'Moving requires a non-root node and an existing parent.'\n );\n for (\n let ancestor: string | undefined = parentId;\n ancestor !== undefined;\n ancestor = tree.nodes[ancestor].parentId\n )\n if (ancestor === id)\n return issue.fail(at, 'tree-cycle', 'Cannot move a node under its descendant.');\n const old = tree.nodes[entry.parentId],\n next = tree.nodes[parentId];\n const index = positionIndex(position?.index, next.children.length - (old === next ? 1 : 0), at);\n const previous = old.children.indexOf(id);\n if (old === next && previous === index) return;\n session.recorder.tree(container, id);\n session.recorder.tree(container, entry.parentId);\n session.recorder.tree(container, parentId);\n old.children.splice(previous, 1);\n next.children.splice(index, 0, id);\n entry.parentId = parentId;\n session.invalidate();\n};\n","import type { DocumentAnchor } from '../../schema/model';\nimport type { MutationSession } from '../session';\nimport type { ResolvedContainer } from '../../address/resolve';\nimport * as sequence from '../../order/sequence';\nimport * as anchor from '../../order/anchor';\nimport * as issue from '../issue';\n\nconst assertOrdered = (\n container: ResolvedContainer\n): Extract<ResolvedContainer['node'], { kind: 'table' | 'list' }> => {\n const { at, node } = container;\n if (node.kind !== 'table' && node.kind !== 'list')\n return issue.fail(at, 'invalid-collection', 'Expected an ordered container.');\n return node;\n};\n\nconst plannedOrder = (\n at: ResolvedContainer['at'],\n current: readonly string[],\n selection: readonly string[],\n position?: DocumentAnchor\n): readonly string[] => {\n const plan = anchor.moveSelection(current, selection, position);\n switch (plan.kind) {\n case 'ok':\n return plan.order;\n case 'duplicate':\n return issue.fail(at, 'invalid-key', 'Moved keys must be unique.');\n case 'missing':\n return issue.fail(at, 'missing-entity', 'Ordered key does not exist.');\n case 'invalid-anchor':\n return issue.fail(at, 'invalid-anchor', 'Unknown order anchor.');\n }\n};\n\nexport function move(\n session: MutationSession,\n container: ResolvedContainer,\n ids: string | readonly string[],\n position?: DocumentAnchor\n): void {\n const node = assertOrdered(container);\n const selection = typeof ids === 'string' ? [ids] : ids;\n if (!selection.length) return;\n\n if (node.kind === 'table') {\n const order = (container.value as { ids: string[] }).ids;\n const next = plannedOrder(container.at, order, selection, position);\n if (sequence.equal(order, next)) return;\n session.recorder.order(container);\n sequence.installKeys(order, next);\n } else {\n const items = container.value as unknown[];\n const current = sequence.listSequence(items, node.keyOf);\n const next = plannedOrder(container.at, current.order, selection, position);\n if (sequence.equal(current.order, next)) return;\n session.recorder.order(container);\n sequence.installList(items, node.keyOf, current, next);\n }\n session.invalidate();\n}\n\nexport function reorder(\n session: MutationSession,\n container: ResolvedContainer,\n next: readonly string[]\n): void {\n const node = assertOrdered(container);\n if (node.kind === 'table') {\n const current = (container.value as { ids: string[] }).ids;\n if (!sequence.matches(next, current))\n return issue.fail(\n container.at,\n 'invalid-collection',\n 'Order must contain every key exactly once.'\n );\n if (sequence.equal(current, next)) return;\n session.recorder.order(container);\n sequence.installKeys(current, next);\n } else {\n const items = container.value as unknown[];\n const current = sequence.listSequence(items, node.keyOf);\n if (!sequence.matches(next, current.order))\n return issue.fail(\n container.at,\n 'invalid-collection',\n 'Order must contain every key exactly once.'\n );\n if (sequence.equal(current.order, next)) return;\n session.recorder.order(container);\n sequence.installList(items, node.keyOf, current, next);\n }\n session.invalidate();\n}\n","import type { ChangeSet } from '../changes';\nimport type { DocumentAddress, ObjectNode } from '../schema/model';\nimport type { ImpactTarget, TreeTarget } from '../schema/path';\nimport { AddressIndex } from '../address/index';\nimport { profile } from '../profile';\n\nconst treeRootSegment = 'rootId';\nconst treeNodesSegment = 'nodes';\nconst ordinaryNamespace = '\\0value';\nconst treeNamespace = '\\0tree';\n\nexport const tree = (\n at: DocumentAddress,\n selection: Exclude<TreeTarget, { readonly kind: 'nodes' }>\n): ImpactTarget => ({ kind: 'value', at, tree: selection });\n\nexport const address = (target: ImpactTarget<unknown>): DocumentAddress =>\n 'at' in target ? target.at : target.address;\n\nexport const id = (target: ImpactTarget<unknown>): string | undefined =>\n target.kind === 'collection' && 'id' in target ? target.id : undefined;\n\nexport const belongs = (target: ImpactTarget<unknown>, schema: ObjectNode): boolean =>\n !('schema' in target) || target.schema === schema;\n\nconst treeTarget = (target: ImpactTarget<unknown>): TreeTarget | undefined =>\n 'tree' in target ? target.tree : undefined;\n\nconst sameTreeTarget = (left: TreeTarget | undefined, right: TreeTarget | undefined): boolean => {\n if (!left || !right) return left === right;\n if (left.kind !== right.kind) return false;\n return left.kind !== 'node' || (right.kind === 'node' && left.id === right.id);\n};\n\nexport const same = (left: ImpactTarget<unknown>, right: ImpactTarget<unknown>): boolean => {\n profile.dependency.comparison();\n if ('schema' in left && 'schema' in right && left.schema !== right.schema) return false;\n if (!sameTreeTarget(treeTarget(left), treeTarget(right))) return false;\n if (left.kind !== right.kind) return false;\n const leftAddress = address(left);\n const rightAddress = address(right);\n if (leftAddress.length !== rightAddress.length) return false;\n for (let index = 0; index < leftAddress.length; index += 1) {\n profile.dependency.segmentCompared();\n if (leftAddress[index] !== rightAddress[index]) return false;\n }\n return left.kind !== 'collection' || id(left) === id(right);\n};\n\nexport const indexedAddress = (target: ImpactTarget<unknown>): DocumentAddress => {\n const tree = treeTarget(target);\n if (tree?.kind === 'root') return [treeNamespace, ...address(target), treeRootSegment];\n if (tree?.kind === 'nodes') return [treeNamespace, ...address(target), treeNodesSegment];\n if (tree?.kind === 'node') return [treeNamespace, ...address(target), treeNodesSegment, tree.id];\n const key = id(target);\n return key === undefined\n ? [ordinaryNamespace, ...address(target)]\n : [ordinaryNamespace, ...address(target), key];\n};\n\n/**\n * Coarse identity for dependency de-duplication. Schema is intentionally excluded because\n * schema-bound and schema-free targets may compare equal; callers must still use same()\n * inside a bucket for the final equality decision.\n */\nexport const dependencyBucket = (target: ImpactTarget<unknown>): string =>\n JSON.stringify([target.kind, indexedAddress(target)]);\n\nexport const visitChangedLocations = (\n changes: ChangeSet,\n value: (at: DocumentAddress) => void,\n order: (at: DocumentAddress) => void\n): void => {\n for (const change of changes.changes) {\n if (change.kind === 'reset') continue;\n if (change.kind === 'members') {\n for (const member of change.members) {\n value([ordinaryNamespace, ...change.at, member.key]);\n value([treeNamespace, ...change.at, member.key]);\n }\n if (change.order) order([ordinaryNamespace, ...change.at]);\n continue;\n }\n value([ordinaryNamespace, ...change.at]);\n if (change.before !== change.after) value([treeNamespace, ...change.at, treeRootSegment]);\n for (const node of change.nodes)\n value([treeNamespace, ...change.at, treeNodesSegment, node.id]);\n }\n};\n\nexport const affected = (\n target: ImpactTarget,\n values: AddressIndex<true>,\n orders: AddressIndex<true>\n): boolean => {\n const at = indexedAddress(target);\n return id(target) !== undefined\n ? values.hasAncestor(at)\n : values.overlaps(at) || orders.hasDescendant(at);\n};\n\n/** Targets are classified once; commit matching never builds a reverse impact index. */\nexport class SubscriptionIndex<T> {\n private readonly ordinary = new AddressIndex<T>();\n private readonly membership = new AddressIndex<T>();\n constructor(private readonly schema: ObjectNode) {}\n add(target: ImpactTarget, value: T): void {\n if (!belongs(target, this.schema)) return;\n (id(target) === undefined ? this.ordinary : this.membership).add(indexedAddress(target), value);\n }\n delete(target: ImpactTarget, value: T): void {\n if (!belongs(target, this.schema)) return;\n (id(target) === undefined ? this.ordinary : this.membership).delete(\n indexedAddress(target),\n value\n );\n }\n collect(changes: ChangeSet, visit: (value: T) => void): void {\n const values = this.ordinary.query(visit);\n const members = this.membership.query(visit, 'descendants');\n const orders = this.ordinary.query(visit, 'ancestors');\n if (changes.changes.some(change => change.kind === 'reset')) {\n values([]);\n members([]);\n return;\n }\n visitChangedLocations(\n changes,\n at => {\n values(at);\n members(at);\n },\n orders\n );\n }\n clear(): void {\n this.ordinary.clear();\n this.membership.clear();\n }\n}\n","import type {\n DocumentAddress,\n DocumentAnchor,\n DocumentNode,\n DocumentTreeValue,\n FieldNode,\n Infer,\n ListNode,\n MapNode,\n ObjectNode,\n ObjectShape,\n ReadonlyValue,\n Schema,\n SchemaNodeOf,\n TableNode,\n TreeNode,\n ValueSchemaNode,\n VariantNode,\n} from '../schema/model';\nimport * as address from '../address/resolve';\nimport { compiledShape, type FixedMember } from '../schema/layout';\nimport * as schemaValue from '../schema/value';\nimport type { DependencyTracker } from './dependency';\nimport type { CanonicalState } from '../mutation/state';\nimport type { MutationSession } from '../mutation/session';\nimport * as tableOperations from '../mutation/operations/table';\nimport * as listOperations from '../mutation/operations/list';\nimport * as treeOperations from '../mutation/operations/tree';\nimport * as orderOperations from '../mutation/operations/order';\nimport * as sequence from '../order/sequence';\nimport * as tree from '../tree/topology';\nimport { profile } from '../profile';\nimport * as target from '../impact/target';\n\ndeclare const scopeValue: unique symbol;\ntype Scoped<N extends DocumentNode, W extends boolean, V = Infer<N>> = {\n readonly [scopeValue]?: readonly [node: N, writable: W, value: V];\n};\ntype ShapeAccess<S extends ObjectShape, W extends boolean> = W extends true\n ? { -readonly [K in keyof S]: Access<S[K], W> }\n : { readonly [K in keyof S]: Access<S[K], W> };\ntype MapAccess<K extends string, N extends ValueSchemaNode, W extends boolean> = {\n get(id: K): Access<N, W> | undefined;\n has(id: K): boolean;\n ids(): readonly K[];\n} & (W extends true\n ? {\n put(id: K, value: Infer<N>): void;\n remove(id: K): void;\n replace(value: Readonly<Record<K, Infer<N>>>): void;\n }\n : {});\ntype TableAccess<K extends string, N extends ValueSchemaNode, W extends boolean> = {\n get(id: K): Access<N, W> | undefined;\n has(id: K): boolean;\n ids(): readonly K[];\n} & (W extends true\n ? {\n create(id: K, value: Infer<N>, anchor?: DocumentAnchor<K>): void;\n create(\n entries: readonly { readonly id: K; readonly value: Infer<N> }[],\n anchor?: DocumentAnchor<K>\n ): void;\n remove(ids: K | readonly K[]): void;\n move(ids: K | readonly K[], anchor?: DocumentAnchor<K>): void;\n reorder(ids: readonly K[]): void;\n replace(value: {\n readonly ids: readonly K[];\n readonly byId: Readonly<Record<K, Infer<N>>>;\n }): void;\n replace(id: K, value: Infer<N>): void;\n }\n : {});\ntype ListAccess<T, W extends boolean> = {\n get(key: string): ReadonlyValue<T> | undefined;\n has(key: string): boolean;\n ids(): readonly string[];\n} & (W extends true\n ? {\n insert(value: ReadonlyValue<T>, anchor?: DocumentAnchor): void;\n remove(key: string): void;\n move(keys: string | readonly string[], anchor?: DocumentAnchor): void;\n reorder(keys: readonly string[]): void;\n replace(value: readonly ReadonlyValue<T>[]): void;\n replace(key: string, value: ReadonlyValue<T>): void;\n }\n : {});\ntype TreeAccess<T, O extends boolean, W extends boolean> = {\n rootId(): string | undefined;\n get(id: string): ReadonlyValue<T> | undefined;\n has(id: string): boolean;\n parent(id: string): string | undefined;\n children(id: string): readonly string[] | undefined;\n} & (W extends true\n ? {\n insert(\n id: string,\n value: O extends true ? ReadonlyValue<T> | undefined : ReadonlyValue<T>,\n position?: tree.TreePosition\n ): void;\n move(id: string, position?: tree.TreePosition): void;\n remove(id: string): void;\n replace(value: DocumentTreeValue<T, O>): void;\n replace(\n id: string,\n value: O extends true ? ReadonlyValue<T> | undefined : ReadonlyValue<T>\n ): void;\n }\n : {});\ntype NodeAccess<N extends DocumentNode, W extends boolean> =\n N extends FieldNode<infer T, boolean>\n ? ReadonlyValue<T>\n : N extends ObjectNode<infer S>\n ? ShapeAccess<S, W> & Scoped<N, W>\n : N extends VariantNode<infer Tag, infer V>\n ? {\n [K in keyof V & string]: ShapeAccess<V[K]['shape'], W> & {\n readonly [P in Tag]: K;\n } & Scoped<N, W, Extract<Infer<N>, Record<Tag, K>>>;\n }[keyof V & string]\n : N extends MapNode<infer V, infer K>\n ? MapAccess<K, V, W> & Scoped<N, W>\n : N extends TableNode<infer V, infer K>\n ? TableAccess<K, V, W> & Scoped<N, W>\n : N extends ListNode<infer T>\n ? ListAccess<T, W> & Scoped<N, W>\n : N extends TreeNode<infer T, infer O>\n ? TreeAccess<T, O, W> & Scoped<N, W>\n : never;\ntype Access<N extends DocumentNode, W extends boolean> = N extends { readonly optional: true }\n ? NodeAccess<N, W> | undefined\n : NodeAccess<N, W>;\ntype AccessNode<S extends Schema<unknown> | DocumentNode> =\n S extends Schema<unknown> ? SchemaNodeOf<S> : Extract<S, DocumentNode>;\nexport type Read<S extends Schema<unknown> | DocumentNode> = Access<AccessNode<S>, false>;\nexport type Draft<S extends Schema<unknown> | DocumentNode> = Access<AccessNode<S>, true>;\ntype Snapshot<T> = T extends {\n readonly [scopeValue]?: readonly [DocumentNode, boolean, infer V];\n}\n ? V\n : ReadonlyValue<T>;\ntype Target = {\n at?: DocumentAddress;\n parent?: Target;\n key: string;\n node: DocumentNode | undefined;\n value: unknown;\n generation: number;\n children:\n | { kind: 'fixed'; schema: DocumentNode; slots: (Target | undefined)[] }\n | { kind: 'dynamic'; keys: Map<string, Target> }\n | undefined;\n proxy: object | undefined;\n container?: address.ResolvedContainer | address.ResolvedTreeContainer;\n};\ntype Location = { readonly context: AccessContext; readonly target: Target };\nconst locations = new WeakMap<object, Location>();\nconst locationOf = (value: object): Location | undefined => locations.get(value);\nconst addressOf = (target: Target): DocumentAddress => {\n if (target.at) return target.at;\n profile.access('addresses');\n return (target.at = addressOf(target.parent!).concat(target.key));\n};\nexport type AccessContext = {\n readonly state: CanonicalState;\n /** Omitted for borrowed synchronous Draft and readers that must not escape. */\n readonly active?: () => boolean;\n readonly dependencies?: DependencyTracker;\n readonly session?: MutationSession;\n};\nconst assertActive = (context: AccessContext) => {\n if (context.active && !context.active()) throw new Error('Document access scope has expired.');\n};\nconst collect = (\n context: AccessContext,\n at: DocumentAddress,\n kind: 'value' | 'collection' = 'value',\n id?: string\n) => {\n context.dependencies?.record(\n kind === 'value' ? { kind, at } : { kind, at, ...(id === undefined ? {} : { id }) }\n );\n};\nconst collectTree = (\n context: AccessContext,\n at: DocumentAddress,\n selection: { readonly kind: 'root' } | { readonly kind: 'node'; readonly id: string }\n) => context.dependencies?.record(target.tree(at, selection));\nexport const snapshot = <T>(value: T): Snapshot<T> => {\n const location = value && typeof value === 'object' ? locationOf(value) : undefined;\n if (!location) return value as Snapshot<T>;\n const { context } = location;\n const at = addressOf(location.target);\n profile.access('snapshots');\n collect(context, at);\n const resolved = resolve(context, location.target);\n if (!resolved.node) throw new Error('The selected schema address no longer exists.');\n return schemaValue.copyValue(resolved.node, resolved.value) as Snapshot<T>;\n};\n/** Replace a member with its plain Infer value through the owning draft session. */\ntype ReplaceParentAccess = {\n readonly [scopeValue]?: readonly [\n Extract<DocumentNode, { readonly kind: 'object' | 'variant' }>,\n true,\n unknown,\n ];\n};\nexport const replace = <T extends object & ReplaceParentAccess, K extends keyof Snapshot<T>>(\n container: T,\n key: K,\n value: NoInfer<Snapshot<T>[K]>\n): void => {\n const location = locationOf(container);\n if (!location) throw new TypeError('replace requires scoped document access.');\n if (typeof key !== 'string') throw new TypeError('Document keys must be strings.');\n Reflect.set(container, key, value);\n};\nconst resolve = (context: AccessContext, target: Target): Target => {\n assertActive(context);\n const generation = context.session?.generation ?? 0;\n if (target.generation !== generation) {\n profile.access('resolutions');\n if (!target.parent && !target.at!.length) {\n target.node = context.state.schema;\n target.value = context.state.document;\n } else {\n const parent = target.parent && resolve(context, target.parent);\n const location = parent\n ? address.resolveChild(parent.node, parent.value, target.key)\n : address.resolveLocated(context.state.schema, context.state.document, target.at!);\n target.node =\n location?.node ??\n address.nodeAt(context.state.schema, addressOf(target), context.state.document);\n target.value =\n location && Object.hasOwn(location.parent, location.key)\n ? (location.parent as Record<string | number, unknown>)[location.key]\n : undefined;\n }\n target.generation = generation;\n }\n return target;\n};\n\nexport const createAccess = (context: AccessContext, initial: DocumentAddress = []): unknown => {\n profile.access('scopes');\n const mutable = (): MutationSession => {\n assertActive(context);\n if (!context.session) throw new TypeError('Cannot modify read-only document access.');\n return context.session;\n };\n const writableContainer = (\n target: Target,\n session: MutationSession\n ): address.ResolvedContainer => {\n if (target.container?.generation === session.generation && 'layout' in target.container)\n return target.container;\n return (target.container = session.bind(addressOf(target), target.node, target.value));\n };\n const childAt = (target: Target, key: string): DocumentAddress => {\n profile.access('addresses');\n return addressOf(target).concat(key);\n };\n const access = (target: Target): unknown => {\n if (target.proxy) return target.proxy;\n const proxy = new Proxy(target, handler);\n profile.access('proxies');\n locations.set(proxy, { context, target });\n target.proxy = proxy;\n return proxy;\n };\n const createTarget = (\n at: DocumentAddress | undefined,\n parent: Target | undefined,\n key: string\n ): Target => ({\n at,\n parent,\n key,\n node: undefined,\n value: undefined,\n generation: -1,\n children: undefined,\n proxy: undefined,\n });\n const childAccess = (\n target: Target,\n member: string | FixedMember,\n node: DocumentNode,\n value: unknown\n ) => {\n const key = typeof member === 'string' ? member : member.key;\n if (node.kind === 'field' || value === undefined) {\n if (context.dependencies) collect(context, childAt(target, key));\n return value;\n }\n let children = target.children;\n let child: Target;\n if (typeof member !== 'string') {\n if (children?.kind !== 'fixed' || children.schema !== target.node)\n children = {\n kind: 'fixed',\n schema: target.node!,\n slots: new Array(compiledShape(target.node!, target.value)!.members.size),\n };\n child = children.slots[member.slot] ??= createTarget(undefined, target, key);\n } else {\n if (children?.kind !== 'dynamic') children = { kind: 'dynamic', keys: new Map() };\n const retained = children.keys.get(key);\n child = retained ?? createTarget(undefined, target, key);\n if (!retained) children.keys.set(key, child);\n }\n target.children = children;\n if (child.generation === target.generation) return child.proxy;\n child.node = node;\n child.value = value;\n child.generation = target.generation;\n return access(child);\n };\n const collectionValue = (target: Target, node: DocumentNode) => {\n const current = resolve(context, target);\n if (current.node !== node || current.value === undefined)\n throw new TypeError('The collection method belongs to a replaced schema branch.');\n return current.value;\n };\n const writableCollection = (target: Target, node: DocumentNode): address.ResolvedContainer => {\n const session = mutable();\n collectionValue(target, node);\n return writableContainer(target, session);\n };\n const writableTree = (target: Target, node: DocumentNode): address.ResolvedTreeContainer => {\n const session = mutable();\n collectionValue(target, node);\n if (target.container?.generation === session.generation && !('layout' in target.container))\n return target.container;\n return (target.container = session.bindTree(addressOf(target), target.node, target.value));\n };\n const replaceCollection = (target: Target, node: DocumentNode, value: unknown) => {\n const session = mutable();\n collectionValue(target, node);\n session.replace(addressOf(target), value);\n };\n const mapMethod = (\n target: Target,\n property: string,\n node: Extract<DocumentNode, { kind: 'map' }>\n ): unknown => {\n if (property === 'ids')\n return () => {\n const current = collectionValue(target, node) as Record<string, unknown>;\n if (context.dependencies) collect(context, addressOf(target), 'collection');\n return Object.keys(current);\n };\n if (property === 'has')\n return (id: string) => {\n const current = collectionValue(target, node) as Record<string, unknown>;\n if (context.dependencies) collect(context, addressOf(target), 'collection', id);\n return Object.hasOwn(current, id);\n };\n if (property === 'get')\n return (id: string) => {\n const current = collectionValue(target, node) as Record<string, unknown>;\n if (context.dependencies) collect(context, addressOf(target), 'collection', id);\n if (!Object.hasOwn(current, id)) return undefined;\n if (node.value.kind === 'field') {\n if (context.dependencies) collect(context, childAt(target, id));\n return current[id];\n }\n return childAccess(target, id, node.value, current[id]);\n };\n if (property === 'put')\n return (id: string, value: unknown) => {\n const session = mutable();\n const writable = writableCollection(target, node);\n session.writeMember(writable, id, value, 'set');\n };\n if (property === 'remove')\n return (id: string) => {\n const session = mutable();\n const writable = writableCollection(target, node);\n session.writeMember(writable, id, undefined, 'remove');\n };\n if (property === 'replace') return (value: unknown) => replaceCollection(target, node, value);\n return undefined;\n };\n const orderedMethod = (\n target: Target,\n property: string,\n node: Extract<DocumentNode, { kind: 'table' | 'list' }>\n ): unknown => {\n const at = addressOf(target);\n if (property === 'ids')\n return () => {\n const current = collectionValue(target, node);\n collect(context, at, 'collection');\n return node.kind === 'table'\n ? [...(current as { ids: string[] }).ids]\n : (current as unknown[]).map(node.keyOf);\n };\n if (property === 'has')\n return (id: string) => {\n const current = collectionValue(target, node);\n collect(context, at, 'collection', id);\n return node.kind === 'table'\n ? Object.hasOwn((current as { byId: object }).byId, id)\n : sequence.indexedKeys(current as unknown[], node.keyOf).index(id) >= 0;\n };\n if (property === 'get')\n return (id: string) => {\n const current = collectionValue(target, node);\n collect(context, at, 'collection', id);\n const location = address.resolveChild(node, current, id);\n if (!location || !Object.hasOwn(location.parent, location.key)) return undefined;\n return childAccess(\n target,\n id,\n location.node,\n (location.parent as Record<string | number, unknown>)[location.key]\n );\n };\n if (property === 'move')\n return (ids: string | readonly string[], position?: DocumentAnchor) => {\n const writable = writableCollection(target, node);\n orderOperations.move(context.session!, writable, ids, position);\n };\n if (property === 'reorder')\n return (ids: readonly string[]) => {\n const writable = writableCollection(target, node);\n orderOperations.reorder(context.session!, writable, ids);\n };\n return undefined;\n };\n const tableMethod = (\n target: Target,\n property: string,\n node: Extract<DocumentNode, { kind: 'table' }>\n ): unknown => {\n if (property === 'create')\n return (\n input: string | readonly { id: string; value: unknown }[],\n valueOrPosition?: unknown,\n position?: DocumentAnchor\n ) => {\n const writable = writableCollection(target, node);\n tableOperations.create(\n context.session!,\n writable,\n Array.isArray(input) ? input : [{ id: input as string, value: valueOrPosition }],\n Array.isArray(input) ? (valueOrPosition as DocumentAnchor | undefined) : position\n );\n };\n if (property === 'remove')\n return (ids: string | readonly string[]) => {\n const writable = writableCollection(target, node);\n tableOperations.remove(context.session!, writable, typeof ids === 'string' ? [ids] : ids);\n };\n if (property === 'replace')\n return (...args: [unknown, unknown?]) => {\n const [valueOrId, value] = args;\n if (args.length === 1) return replaceCollection(target, node, valueOrId);\n const writable = writableCollection(target, node);\n tableOperations.replace(context.session!, writable, valueOrId as string, value);\n };\n return orderedMethod(target, property, node);\n };\n const listMethod = (\n target: Target,\n property: string,\n node: Extract<DocumentNode, { kind: 'list' }>\n ): unknown => {\n if (property === 'insert')\n return (value: unknown, position?: DocumentAnchor) => {\n const writable = writableCollection(target, node);\n listOperations.insert(context.session!, writable, value, position);\n };\n if (property === 'remove')\n return (id: string) => {\n const writable = writableCollection(target, node);\n listOperations.remove(context.session!, writable, id);\n };\n if (property === 'replace')\n return (...args: [unknown, unknown?]) => {\n const [valueOrId, value] = args;\n if (args.length === 1) return replaceCollection(target, node, valueOrId);\n const writable = writableCollection(target, node);\n listOperations.replace(context.session!, writable, valueOrId as string, value);\n };\n return orderedMethod(target, property, node);\n };\n const treeMethod = (\n target: Target,\n property: string,\n node: Extract<DocumentNode, { kind: 'tree' }>\n ): unknown => {\n const at = addressOf(target);\n if (property === 'insert')\n return (id: string, value: unknown, position?: tree.TreePosition) => {\n const writable = writableTree(target, node);\n treeOperations.insert(context.session!, writable, id, value, position);\n };\n if (property === 'remove')\n return (id: string) => {\n const writable = writableTree(target, node);\n treeOperations.remove(context.session!, writable, id);\n };\n if (property === 'move')\n return (id: string, position?: tree.TreePosition) => {\n const writable = writableTree(target, node);\n treeOperations.move(context.session!, writable, id, position);\n };\n if (property === 'replace')\n return (...args: [unknown, unknown?]) => {\n const [valueOrId, value] = args;\n if (args.length === 1) return replaceCollection(target, node, valueOrId);\n const writable = writableTree(target, node);\n treeOperations.replace(context.session!, writable, valueOrId as string, value);\n };\n const current = () => collectionValue(target, node) as tree.MutableTree;\n if (property === 'rootId')\n return () => {\n collectTree(context, at, { kind: 'root' });\n return current().rootId;\n };\n if (property === 'get')\n return (id: string) => {\n collectTree(context, at, { kind: 'node', id });\n const value = current();\n return tree.contains(value, id) ? value.nodes[id].value : undefined;\n };\n if (property === 'has')\n return (id: string) => {\n collectTree(context, at, { kind: 'node', id });\n return tree.contains(current(), id);\n };\n if (property === 'parent')\n return (id: string) => {\n collectTree(context, at, { kind: 'node', id });\n return tree.parent(current(), id);\n };\n if (property === 'children')\n return (id: string) => {\n collectTree(context, at, { kind: 'node', id });\n const children = tree.children(current(), id);\n return children ? [...children] : undefined;\n };\n return undefined;\n };\n const handler: ProxyHandler<Target> = {\n get: (target, property) => {\n const { node, value } = resolve(context, target);\n if (!node || value === undefined) return undefined;\n if (typeof property !== 'string') return undefined;\n if (node.kind === 'map') return mapMethod(target, property, node);\n if (node.kind === 'table') return tableMethod(target, property, node);\n if (node.kind === 'list') return listMethod(target, property, node);\n if (node.kind === 'tree') return treeMethod(target, property, node);\n if (node.kind === 'variant' && property === node.tag) {\n collect(context, childAt(target, property));\n return (value as Record<string, unknown>)[property];\n }\n const member = compiledShape(node, value)?.members.get(property);\n if (!member) return undefined;\n if (member.field) {\n if (context.dependencies) collect(context, childAt(target, property));\n return (value as Record<string, unknown>)[property];\n }\n return childAccess(\n target,\n node.kind === 'object' ? member : property,\n member.node,\n (value as Record<string, unknown>)[property]\n );\n },\n set: (target, property, value) => {\n const session = mutable(),\n { node } = resolve(context, target);\n if (\n typeof property !== 'string' ||\n !node ||\n (node.kind !== 'object' && node.kind !== 'variant')\n )\n throw new TypeError('Invalid structural assignment.');\n if (node.kind === 'variant' && node.tag === property)\n throw new TypeError('Variant discriminants are read-only.');\n session.assignMember(writableContainer(target, session), property, value);\n return true;\n },\n deleteProperty: (target, property) => {\n const session = mutable(),\n { node } = resolve(context, target);\n if (\n typeof property !== 'string' ||\n node?.kind === 'map' ||\n (node?.kind === 'variant' && node.tag === property)\n )\n throw new TypeError('Invalid structural deletion.');\n session.removeMember(writableContainer(target, session), property);\n return true;\n },\n has: (target, property) => {\n const { node, value } = resolve(context, target);\n if (typeof property !== 'string') return false;\n if (node?.kind === 'map') return false;\n collect(context, addressOf(target));\n return value !== undefined && Object.hasOwn(value as object, property);\n },\n ownKeys: target => {\n const { node, value } = resolve(context, target);\n if (node?.kind === 'map') return [];\n if (context.dependencies) collect(context, addressOf(target));\n return value && typeof value === 'object' ? Object.keys(value) : [];\n },\n getOwnPropertyDescriptor: (target, property) => {\n const { node, value } = resolve(context, target);\n if (node?.kind === 'map') return undefined;\n return value && Object.hasOwn(value as object, property)\n ? { enumerable: true, configurable: true }\n : undefined;\n },\n defineProperty: () => {\n assertActive(context);\n throw new TypeError('Use schema assignments.');\n },\n setPrototypeOf: () => {\n assertActive(context);\n throw new TypeError('Document prototypes are immutable.');\n },\n preventExtensions: () => {\n assertActive(context);\n throw new TypeError('Document access cannot be frozen.');\n },\n };\n const root = resolve(context, createTarget(initial, undefined, ''));\n if (!root.node || root.node.kind === 'field' || root.value === undefined) {\n if (context.dependencies) collect(context, initial);\n return root.value;\n }\n return access(root);\n};\n","import { checkKey } from './value';\nimport {\n collectionEntryNode,\n type DocumentAddress,\n type DocumentNode,\n type DocumentTreeNode,\n type FieldNode,\n type Infer,\n type ListNode,\n type MapNode,\n type ObjectNode,\n type ObjectSchema,\n type ObjectShape,\n type ReadonlyValue,\n type RootNodeOf,\n type SchemaNodeOf,\n type TableNode,\n type TreeNode,\n type VariantNode,\n type VariantShape,\n} from './model';\n\nexport type TreeTarget =\n | { readonly kind: 'root' }\n | { readonly kind: 'nodes' }\n | { readonly kind: 'node'; readonly id: string };\ntype TreeValueTarget = Exclude<TreeTarget, { readonly kind: 'nodes' }>;\ntype TreeCollectionTarget = Extract<TreeTarget, { readonly kind: 'nodes' }>;\n\nexport type CollectionSelector<TId extends string = string> = {\n readonly kind: 'collection';\n readonly schema: ObjectNode;\n readonly address: DocumentAddress;\n readonly tree?: TreeCollectionTarget;\n readonly __id?: TId;\n};\nexport type ValueSelector<TResult = unknown> = {\n readonly kind: 'value';\n readonly schema: ObjectNode;\n readonly address: DocumentAddress;\n readonly tree?: TreeValueTarget;\n readonly __value?: TResult;\n};\nexport type ImpactTarget<T = unknown> =\n | { readonly kind: 'value'; readonly at: DocumentAddress; readonly tree?: TreeValueTarget }\n | ValueSelector<T>\n | {\n readonly kind: 'collection';\n readonly at: DocumentAddress;\n readonly id?: string;\n }\n | CollectionSelector<string>;\ndeclare const pathValue: unique symbol;\ndeclare const collectionEntry: unique symbol;\ndeclare const collectionKey: unique symbol;\ntype PathMarker<TValue> = { readonly [pathValue]: TValue };\nexport type PathValueOf<T> = T extends { readonly [pathValue]: infer TValue } ? TValue : never;\n\ntype Or<A extends boolean, B extends boolean> = A extends true ? true : B;\ntype NodeAbsent<N extends DocumentNode, ParentAbsent extends boolean> = Or<\n ParentAbsent,\n N extends { readonly optional: true } ? true : false\n>;\ntype PathResult<N extends DocumentNode, ParentAbsent extends boolean> =\n Infer<N> | (ParentAbsent extends true ? undefined : never);\n\ntype SchemaPathFor<\n S extends ObjectShape = ObjectShape,\n TValue = unknown,\n Absent extends boolean = false,\n> = {\n readonly [K in keyof S]: PathValue<S[K], Absent>;\n} & PathMarker<TValue | (Absent extends true ? undefined : never)>;\n\nexport type SchemaPath<S extends ObjectSchema<object> = ObjectSchema<object>> =\n RootNodeOf<S> extends ObjectNode<infer Shape> ? SchemaPathFor<Shape, Infer<S>> : never;\nexport type PathPick<S extends ObjectSchema<object> = ObjectSchema<object>> = (\n path: SchemaPath<S>\n) => PathMarker<unknown>;\n\ntype VariantKeys<V extends VariantShape> = {\n [K in keyof V & string]: keyof (V[K] extends ObjectNode<infer S> ? S : {});\n}[keyof V & string] &\n string;\ntype VariantFieldMissing<V extends VariantShape, K extends string> = {\n [P in keyof V & string]: V[P] extends ObjectNode<infer S> ? (K extends keyof S ? never : P) : P;\n}[keyof V & string] extends never\n ? false\n : true;\ntype VariantFieldPath<V extends VariantShape, K extends string, Absent extends boolean> = {\n [P in keyof V & string]: V[P] extends ObjectNode<infer S>\n ? K extends keyof S\n ? PathValue<S[K], Or<Absent, VariantFieldMissing<V, K>>>\n : never\n : never;\n}[keyof V & string];\ntype VariantPath<T extends string, V extends VariantShape, TValue, Absent extends boolean> = {\n readonly [K in VariantKeys<V>]: VariantFieldPath<V, K, Absent>;\n} & {\n readonly [K in T]: PathMarker<(keyof V & string) | (Absent extends true ? undefined : never)>;\n} & PathMarker<TValue>;\nexport type CollectionPath<\n K extends string = string,\n TValue = unknown,\n TEntry = unknown,\n TItem = PathMarker<TEntry | undefined>,\n> = PathMarker<TValue> & {\n item(id: K): TItem;\n readonly [collectionEntry]: TEntry;\n readonly [collectionKey]: K;\n};\ntype TreeNodesPath<TValue, ValueOptional extends boolean> = CollectionPath<\n string,\n Readonly<Record<string, DocumentTreeNode<TValue, ValueOptional>>>,\n DocumentTreeNode<TValue, ValueOptional>,\n PathMarker<DocumentTreeNode<TValue, ValueOptional> | undefined>\n>;\ntype TreePath<TValue, ValueOptional extends boolean, TValueResult> = PathMarker<TValueResult> & {\n readonly rootId: PathMarker<string | undefined>;\n readonly nodes: TreeNodesPath<TValue, ValueOptional>;\n};\n\ntype PathValue<N extends DocumentNode, ParentAbsent extends boolean = false> =\n N extends ObjectNode<infer S>\n ? SchemaPathFor<S, PathResult<N, ParentAbsent>, NodeAbsent<N, ParentAbsent>>\n : N extends VariantNode<infer TTag, infer V>\n ? VariantPath<TTag, V, PathResult<N, ParentAbsent>, NodeAbsent<N, ParentAbsent>>\n : N extends TableNode<infer V, infer K>\n ? CollectionPath<K, PathResult<N, ParentAbsent>, Infer<V>, PathValue<V, true>>\n : N extends MapNode<infer V, infer K>\n ? CollectionPath<K, PathResult<N, ParentAbsent>, Infer<V>, PathValue<V, true>>\n : N extends ListNode<infer I>\n ? CollectionPath<\n string,\n PathResult<N, ParentAbsent>,\n ReadonlyValue<I>,\n PathMarker<ReadonlyValue<I> | undefined>\n >\n : N extends TreeNode<infer T, infer O>\n ? TreePath<T, O, PathResult<N, ParentAbsent>>\n : PathMarker<PathResult<N, ParentAbsent>>;\ntype CollectionInfo<T> = T extends {\n readonly [collectionEntry]: infer TEntry;\n readonly [collectionKey]: infer K extends string;\n}\n ? { readonly id: K; readonly entry: TEntry }\n : never;\nexport type CollectionId<T> =\n CollectionInfo<T> extends { readonly id: infer TId extends string } ? TId : string;\nexport type CollectionEntry<T> =\n CollectionInfo<T> extends { readonly entry: infer TEntry } ? TEntry : unknown;\n\nconst paths = new WeakMap<\n object,\n {\n readonly address: DocumentAddress;\n readonly nodes: readonly DocumentNode[];\n readonly owner: object;\n readonly tree?: TreeTarget;\n }\n>();\n\nconst pathProxy = (\n nodes: readonly DocumentNode[],\n address: DocumentAddress,\n owner: object,\n treeSelection?: TreeTarget\n): object => {\n const proxy = new Proxy(\n {},\n {\n get: (_target, property: string | symbol) => {\n if (typeof property !== 'string') return undefined;\n const trees = nodes.every(node => node.kind === 'tree');\n if (!treeSelection && trees && property === 'rootId')\n return pathProxy(nodes, address, owner, { kind: 'root' });\n if (!treeSelection && trees && property === 'nodes')\n return pathProxy(nodes, address, owner, { kind: 'nodes' });\n if (treeSelection?.kind === 'nodes' && property === 'item')\n return (id: string) => {\n if (typeof id !== 'string') throw new TypeError('Tree node keys must be strings.');\n return pathProxy(nodes, address, owner, { kind: 'node', id });\n };\n if (treeSelection) throw new TypeError(`Invalid tree path segment: ${property}`);\n const collection = nodes.every(node => collectionEntryNode(node) !== undefined);\n if (collection && property === 'item')\n return (id: string) => {\n if (typeof id !== 'string') throw new TypeError('Collection keys must be strings.');\n for (const node of nodes)\n if (node.kind === 'table' || node.kind === 'map') {\n const invalid = checkKey(node.key, id, [...address, id]);\n if (invalid) throw new TypeError(invalid.message);\n }\n return pathProxy(\n nodes.map(node => collectionEntryNode(node)!),\n [...address, id],\n owner\n );\n };\n const children = nodes.flatMap(node => {\n if (node.kind === 'object')\n return Object.hasOwn(node.shape, property) ? [node.shape[property]] : [];\n if (node.kind !== 'variant') return [];\n if (property === node.tag)\n return [Object.freeze({ kind: 'field' as const }) as FieldNode<string>];\n return Object.values(node.variants).flatMap(branch =>\n Object.hasOwn(branch.shape, property) ? [branch.shape[property]] : []\n );\n });\n if (!children.length) throw new TypeError(`Invalid schema path segment: ${property}`);\n return pathProxy(children, [...address, property], owner);\n },\n }\n );\n paths.set(proxy, { nodes, address, owner, ...(treeSelection ? { tree: treeSelection } : {}) });\n return proxy;\n};\n\nexport const compilePath = <S extends ObjectSchema<object>>(\n owner: RootNodeOf<S>,\n kind: 'collection' | 'value' | 'auto',\n pick: (path: SchemaPath<S>) => unknown\n): CollectionSelector | ValueSelector => {\n const scope = {};\n const value = pick(pathProxy([owner], [], scope) as SchemaPath<S>);\n const selected = typeof value === 'object' && value !== null ? paths.get(value) : undefined;\n if (!selected || selected.owner !== scope)\n throw new TypeError('Selector must return a path from its callback.');\n const collection =\n selected.tree?.kind === 'nodes' ||\n selected.nodes.every(node => collectionEntryNode(node) !== undefined);\n if (kind === 'collection' && !collection)\n throw new TypeError('Collection selectors require a map, table, list or tree nodes path.');\n const resolvedKind = kind === 'auto' ? (collection ? 'collection' : 'value') : kind;\n const result = Object.freeze({\n kind: resolvedKind,\n schema: owner,\n address: Object.freeze([...selected.address]),\n ...(selected.tree ? { tree: Object.freeze({ ...selected.tree }) } : {}),\n }) as CollectionSelector | ValueSelector;\n return result;\n};\n","import { profile } from '../profile';\nimport type { DocumentAddress } from '../schema/model';\n\nexport const contains = (parent: DocumentAddress, child: DocumentAddress): boolean => {\n profile.address.prefixComparison();\n if (parent.length > child.length) return false;\n for (let index = 0; index < parent.length; index += 1) {\n profile.address.segmentCompared();\n if (parent[index] !== child[index]) return false;\n }\n return true;\n};\n","import type { ObjectSchema, RootNodeOf } from './schema/model';\nimport type {\n CollectionId,\n CollectionPath,\n CollectionSelector,\n ImpactTarget,\n PathPick,\n SchemaPath,\n} from './schema/path';\nimport { compilePath } from './schema/path';\nimport type { ChangeSet } from './changes';\nimport { AddressIndex } from './address/index';\nimport * as relation from './address/relation';\nimport * as target from './impact/target';\nimport { profile } from './profile';\n\nexport type CollectionImpact<K> =\n | { readonly kind: 'reset' }\n | {\n readonly kind: 'incremental';\n readonly added: ReadonlySet<K>;\n readonly removed: ReadonlySet<K>;\n readonly updated: ReadonlySet<K>;\n readonly orderChanged: boolean;\n };\nexport type DocumentImpact<S extends ObjectSchema<object>> = {\n readonly kind: 'incremental' | 'reset';\n affects(pick: PathPick<S>): boolean;\n collection<P extends CollectionPath>(\n pick: (path: SchemaPath<S>) => P\n ): CollectionImpact<CollectionId<P>>;\n};\nexport const createImpact = <S extends ObjectSchema<object>>(\n schema: RootNodeOf<S>,\n changes: ChangeSet\n): DocumentImpact<S> => {\n const reset = changes.changes.some(change => change.kind === 'reset');\n let values: AddressIndex<true> | undefined;\n let orders: AddressIndex<true> | undefined;\n const index = () => {\n if (!values) {\n profile.impact.index();\n values = new AddressIndex();\n orders = new AddressIndex();\n target.visitChangedLocations(\n changes,\n at => values!.add(at, true),\n at => orders!.add(at, true)\n );\n }\n return values;\n };\n const cache = new Map<string, CollectionImpact<string>>();\n const affects = (value: ImpactTarget): boolean => {\n profile.impact.affects();\n if (!target.belongs(value, schema)) return false;\n if (reset) return true;\n return target.affected(value, index(), orders!);\n };\n const collection = (selector: CollectionSelector): CollectionImpact<string> => {\n if (selector.schema !== schema)\n throw new TypeError('Collection belongs to another root model.');\n const key = JSON.stringify(target.indexedAddress(selector)),\n cached = cache.get(key);\n if (cached) return cached;\n if (reset) {\n const result = { kind: 'reset' } as const;\n cache.set(key, result);\n return result;\n }\n const at = selector.address;\n const tree = selector.tree;\n const added = new Set<string>(),\n removed = new Set<string>(),\n updated = new Set<string>();\n let orderChanged = false;\n for (const change of changes.changes) {\n if (change.kind === 'reset') continue;\n if (change.kind === 'members') {\n if (change.at.length < at.length && relation.contains(change.at, at)) {\n if (change.members.some(member => member.key === at[change.at.length])) {\n const result = { kind: 'reset' } as const;\n cache.set(key, result);\n return result;\n }\n } else if (relation.contains(at, change.at)) {\n if (change.at.length === at.length) {\n if (change.order) {\n const positions = new Map(change.order.after.map((id, i) => [id, i]));\n let previous = -1;\n for (const id of change.order.before) {\n const position = positions.get(id);\n if (position === undefined) continue;\n if (position < previous) orderChanged = true;\n previous = position;\n }\n }\n for (const member of change.members) {\n if (member.kind === 'added') added.add(member.key);\n else if (member.kind === 'removed') removed.add(member.key);\n else updated.add(member.key);\n }\n } else updated.add(change.at[at.length]);\n }\n continue;\n }\n if (change.kind === 'tree' && relation.contains(change.at, at)) {\n if (\n tree?.kind === 'nodes' &&\n change.at.length === at.length &&\n relation.contains(at, change.at)\n ) {\n for (const node of change.nodes) {\n if (node.kind === 'added') added.add(node.id);\n else if (node.kind === 'removed') removed.add(node.id);\n else updated.add(node.id);\n }\n continue;\n }\n const result = { kind: 'reset' } as const;\n cache.set(key, result);\n return result;\n }\n if (!relation.contains(at, change.at)) continue;\n if (change.at.length === at.length) continue;\n const id = change.at[at.length];\n updated.add(id);\n }\n added.forEach(id => updated.delete(id));\n removed.forEach(id => updated.delete(id));\n const result = { kind: 'incremental', added, removed, updated, orderChanged } as const;\n cache.set(key, result);\n return result;\n };\n const impact: DocumentImpact<S> = Object.freeze({\n kind: reset ? 'reset' : 'incremental',\n affects: (pick: PathPick<S>) => affects(compilePath<S>(schema, 'value', pick)),\n collection: <P extends CollectionPath>(pick: (path: SchemaPath<S>) => P) =>\n collection(\n compilePath<S>(schema, 'collection', pick) as CollectionSelector\n ) as CollectionImpact<CollectionId<P>>,\n });\n return impact;\n};\n","import type { DocumentAddress, Infer, ObjectSchema } from '../schema/model';\nimport type { PathPick } from '../schema/path';\nimport type { ChangeSet } from '../changes';\nimport type { DocumentImpact } from '../impact';\nimport type { Draft } from '../access/scope';\nimport type { MutationIssue } from '../mutation/issue';\nimport type { Readable, Unsubscribe } from '../readable';\nexport type { Unsubscribe } from '../readable';\nexport type Synchronous<T> = T extends PromiseLike<unknown> ? never : T;\nexport type CommitSource = 'local' | 'system' | 'history' | 'remote';\nexport class DocumentReentrancyError extends Error {\n constructor() {\n super('Document writes cannot be re-entered during an update or notification.');\n this.name = 'DocumentReentrancyError';\n }\n}\nexport class DocumentDisposedError extends Error {\n constructor() {\n super('Doxum runtime has been disposed.');\n this.name = 'DocumentDisposedError';\n }\n}\nexport type DiagnosticInput = {\n readonly code: string;\n readonly message: string;\n readonly address?: DocumentAddress;\n};\nexport type DocumentDiagnostic = DiagnosticInput & { readonly source: 'application' };\nexport type DocumentProblem = DocumentDiagnostic | MutationIssue;\nexport class TransactionRejected extends Error {\n readonly issues: readonly DocumentDiagnostic[];\n constructor(input: DiagnosticInput | readonly DiagnosticInput[]) {\n super('Document update rejected.');\n this.name = 'TransactionRejected';\n const issues: readonly DiagnosticInput[] = Array.isArray(input)\n ? input\n : [input as DiagnosticInput];\n this.issues = Object.freeze(\n issues.map(issue =>\n Object.freeze({\n code: issue.code,\n message: issue.message,\n source: 'application' as const,\n ...(issue.address === undefined ? {} : { address: Object.freeze([...issue.address]) }),\n })\n )\n );\n }\n}\nexport type DocumentCommit<S extends ObjectSchema<object>> = {\n readonly revision: number;\n readonly source: CommitSource;\n readonly changes: ChangeSet;\n readonly impact: DocumentImpact<S>;\n};\nexport type ObserverError = {\n readonly phase: 'processor' | 'flush' | 'listener';\n readonly error: unknown;\n};\nexport type TransactionResult<V, C> =\n | {\n readonly status: 'committed';\n readonly value: V;\n readonly commit: C;\n readonly observerErrors: readonly ObserverError[];\n }\n | { readonly status: 'unchanged'; readonly value: V; readonly revision: number }\n | {\n readonly status: 'rejected';\n readonly issues: readonly DocumentProblem[];\n readonly revision: number;\n };\nexport type OperationResult<C> =\n | {\n readonly status: 'committed';\n readonly commit: C;\n readonly observerErrors: readonly ObserverError[];\n }\n | { readonly status: 'unchanged'; readonly revision: number }\n | {\n readonly status: 'rejected';\n readonly issues: readonly MutationIssue[];\n readonly revision: number;\n };\nexport type HistoryState = { readonly undoDepth: number; readonly redoDepth: number };\nexport type LocalHistory<C> = Readable<HistoryState> & {\n undo(): OperationResult<C>;\n redo(): OperationResult<C>;\n clear(): void;\n group(): { end(): void; cancel(): OperationResult<C> };\n};\nexport type CommitListener<S extends ObjectSchema<object>> = (commit: DocumentCommit<S>) => void;\nexport type ReadonlyDocument<S extends ObjectSchema<object>> = {\n revision(): number;\n subscribe(listener: CommitListener<S>): Unsubscribe;\n subscribe(\n pick: PathPick<S> | readonly [PathPick<S>, ...PathPick<S>[]],\n listener: CommitListener<S>\n ): Unsubscribe;\n};\nexport type DocumentRuntime<S extends ObjectSchema<object>> = ReadonlyDocument<S> & {\n readonly schema: S;\n readonly(): ReadonlyDocument<S>;\n update<V>(\n run: (draft: Draft<S>) => Synchronous<V>,\n options?: {\n readonly source?: Extract<CommitSource, 'local' | 'system'>;\n readonly history?: boolean;\n }\n ): TransactionResult<V, DocumentCommit<S>>;\n apply(\n changes: unknown,\n options:\n | {\n readonly expectedRevision: number;\n readonly source?: Extract<CommitSource, 'local' | 'system'>;\n readonly history?: boolean;\n }\n | {\n readonly expectedRevision: number;\n readonly source: 'remote';\n readonly history?: never;\n }\n ): OperationResult<DocumentCommit<S>>;\n replace(\n value: Infer<S>,\n options?: { readonly source?: Extract<CommitSource, 'system' | 'remote'> }\n ): OperationResult<DocumentCommit<S>>;\n snapshot(): Infer<S>;\n readonly history: LocalHistory<DocumentCommit<S>>;\n dispose(): void;\n};\n","import type { ChangeSet, ChangeDirection } from './changes';\nimport type {\n HistoryState,\n LocalHistory,\n ObserverError,\n OperationResult,\n} from './runtime/contract';\nimport { DocumentDisposedError } from './runtime/contract';\n\ntype Entry = { readonly batches: ChangeSet[] };\ntype Group = { entry?: Entry; readonly undos: Entry[]; readonly redos: Entry[] };\n\nexport const createHistory = <TCommit>(input: {\n readonly capacity: number;\n readonly apply: (\n changes: readonly ChangeSet[],\n direction: ChangeDirection\n ) => OperationResult<TCommit>;\n readonly revision: () => number;\n readonly assertIdle: () => void;\n readonly notify: (run: () => readonly ObserverError[]) => readonly ObserverError[];\n}) => {\n let undos: Entry[] = [];\n let redos: Entry[] = [];\n const listeners = new Set<() => void>();\n let state: HistoryState = Object.freeze({ undoDepth: 0, redoDepth: 0 });\n let revision = 0;\n let pending = false;\n let disposed = false;\n let group: Group | undefined;\n const unchanged = (): OperationResult<TCommit> => ({\n status: 'unchanged',\n revision: input.revision(),\n });\n const publish = () => {\n if (state.undoDepth === undos.length && state.redoDepth === redos.length) return;\n state = Object.freeze({ undoDepth: undos.length, redoDepth: redos.length });\n revision++;\n pending = true;\n };\n const flush = (): readonly ObserverError[] => {\n if (!pending) return [];\n pending = false;\n const errors: ObserverError[] = [];\n for (const listener of [...listeners]) {\n if (!listeners.has(listener)) continue;\n try {\n listener();\n } catch (error) {\n errors.push({ phase: 'listener', error });\n }\n }\n return errors;\n };\n const clear = () => {\n group = undefined;\n undos.length = redos.length = 0;\n publish();\n };\n const travel = (direction: 'undo' | 'redo' | 'cancel'): OperationResult<TCommit> => {\n input.assertIdle();\n const from = direction === 'redo' ? redos : undos;\n const to = direction === 'redo' ? undos : redos;\n const previousUndos = undos;\n const previousRedos = redos;\n const entry = direction === 'cancel' ? from.at(-1) : from.pop();\n if (!entry) return unchanged();\n if (direction === 'cancel') {\n if (!group || group.entry !== entry)\n throw new Error('History group no longer owns its entry.');\n undos = group.undos;\n redos = group.redos;\n } else to.push(entry);\n let committed = false;\n try {\n const changes = direction === 'redo' ? entry.batches : entry.batches.slice().reverse();\n const result = input.apply(changes, direction === 'redo' ? 'forward' : 'backward');\n committed = result.status !== 'rejected';\n if (committed && direction === 'cancel') group = undefined;\n if (result.status === 'unchanged') {\n publish();\n const errors = input.notify(flush);\n if (errors.length)\n throw new AggregateError(\n errors.map(entry => entry.error),\n 'History listeners failed.'\n );\n }\n return result;\n } finally {\n if (!committed) {\n if (direction === 'cancel') {\n undos = previousUndos;\n redos = previousRedos;\n } else {\n to.pop();\n from.push(entry);\n }\n }\n }\n };\n const api: LocalHistory<TCommit> = {\n current: () => state,\n revision: () => revision,\n subscribe: listener => {\n if (disposed) throw new DocumentDisposedError();\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n undo: () => {\n input.assertIdle();\n group = undefined;\n return travel('undo');\n },\n redo: () => {\n input.assertIdle();\n group = undefined;\n return travel('redo');\n },\n clear: () => {\n input.assertIdle();\n clear();\n const errors = input.notify(flush);\n if (errors.length)\n throw new AggregateError(\n errors.map(entry => entry.error),\n 'History listeners failed.'\n );\n },\n group: () => {\n input.assertIdle();\n if (group) throw new Error('A history group is already active.');\n if (input.capacity <= 0) throw new Error('History is disabled.');\n const scope: Group = { undos: undos.slice(), redos: redos.slice() };\n group = scope;\n return Object.freeze({\n end: () => {\n input.assertIdle();\n if (group === scope) group = undefined;\n },\n cancel: () => {\n input.assertIdle();\n if (group !== scope) return unchanged();\n if (!scope.entry) {\n group = undefined;\n return unchanged();\n }\n const result = travel('cancel');\n if (result.status !== 'rejected') group = undefined;\n return result;\n },\n });\n },\n };\n return {\n api,\n record: (batch: ChangeSet) => {\n if (input.capacity <= 0) return;\n if (group?.entry) group.entry.batches.push(batch);\n else {\n const entry: Entry = { batches: [batch] };\n undos.push(entry);\n if (group) group.entry = entry;\n if (undos.length > input.capacity) undos.shift();\n }\n redos.length = 0;\n publish();\n },\n publish,\n flush,\n endGroup: () => {\n group = undefined;\n },\n invalidate: clear,\n dispose: () => {\n disposed = true;\n listeners.clear();\n clear();\n pending = false;\n },\n };\n};\n","import type { DocumentNode, ObjectNode } from '../schema/model';\nimport * as sequence from '../order/sequence';\nimport { installOwn } from '../value/record';\n\nexport type CanonicalState = { schema: ObjectNode; document: unknown };\n\n/** Install validated values, or captured before values during rollback. */\nexport const installMember = (\n parent: Record<string, unknown> | unknown[],\n key: string | number,\n present: boolean,\n value: unknown\n): void => {\n if (Array.isArray(parent)) {\n const index = Number(key);\n if (present) {\n if (index < 0) sequence.insert(parent, parent.length, value);\n else parent[index] = value;\n } else if (index >= 0) sequence.remove(parent, index);\n } else installOwn(parent, key, present, value);\n};\n\nexport const orderOf = (node: DocumentNode, value: unknown): string[] => {\n if (node.kind === 'list')\n return sequence.toArray(sequence.indexedKeys(value as unknown[], node.keyOf));\n if (node.kind === 'table') return [...(value as { ids: string[] }).ids];\n throw new Error('Order requires a table or list.');\n};\n\nexport const installOrder = (\n node: DocumentNode,\n value: unknown,\n order: readonly string[]\n): void => {\n if (node.kind === 'list') sequence.install(value as unknown[], node.keyOf, order);\n else if (node.kind === 'table') (value as { ids: string[] }).ids = [...order];\n else throw new Error('Order requires a table or list.');\n};\n","import type { Change, ChangeSet, MemberChange } from '../changes';\nimport type { DocumentAddress, DocumentNode } from '../schema/model';\nimport { AddressIndex } from '../address/index';\nimport * as address from '../address/resolve';\nimport * as relation from '../address/relation';\nimport * as sequence from '../order/sequence';\nimport { profile } from '../profile';\nimport { compiledShape, type CompiledMember, type FixedLayout } from '../schema/layout';\nimport * as schemaValue from '../schema/value';\nimport type { MutableTree, MutableTreeNode } from '../tree/topology';\nimport * as changeSet from './changes';\nimport * as state from './state';\ntype MemberFact = { key: string; node: DocumentNode; present: boolean; value: unknown };\ntype MemberGroup = {\n kind: 'members';\n at: DocumentAddress;\n node: DocumentNode;\n parent: Record<string, unknown> | unknown[];\n value: unknown;\n order?: readonly string[];\n} & (\n | { layout: 'fixed'; definitions: FixedLayout['members']; members: (MemberFact | undefined)[] }\n | { layout: 'dynamic'; members: Map<string, MemberFact> | undefined }\n);\ntype TreeFact = {\n kind: 'tree';\n at: DocumentAddress;\n before: string | null;\n nodes: Map<string, MutableTreeNode | undefined>;\n};\ntype Fact = MemberGroup | TreeFact;\ntype RestoreFact =\n | { kind: 'order'; at: DocumentAddress; group: MemberGroup }\n | TreeFact\n | { kind: 'member'; at: DocumentAddress; group: MemberGroup; member: MemberFact };\nconst firstMember = (group: MemberGroup, key: string): MemberFact | undefined => {\n if (group.layout === 'dynamic') return group.members?.get(key);\n const member = group.definitions.get(key);\n return member && group.members[member.slot];\n};\n\nconst forgetMember = (group: MemberGroup, key: string): void => {\n if (group.layout === 'dynamic') group.members?.delete(key);\n else {\n const definition = group.definitions.get(key);\n if (definition) group.members[definition.slot] = undefined;\n }\n};\nconst emptyGroup = (group: MemberGroup): boolean =>\n !group.order && (group.layout === 'fixed' ? !group.members.some(Boolean) : !group.members?.size);\n\nconst transition = (\n node: DocumentNode,\n key: string,\n beforePresent: boolean,\n before: unknown,\n afterPresent: boolean,\n after: unknown\n): MemberChange | undefined => {\n if (beforePresent === afterPresent && (!beforePresent || Object.is(before, after))) return;\n if (\n node.kind !== 'field' &&\n beforePresent === afterPresent &&\n schemaValue.equalValue(node, before, after)\n )\n return;\n const value = afterPresent\n ? node.kind === 'field'\n ? after\n : schemaValue.copyValue(node, after)\n : undefined;\n profile.recorder('transitions');\n return !beforePresent\n ? { key, kind: 'added', after: value }\n : !afterPresent\n ? { key, kind: 'removed', before }\n : { key, kind: 'updated', before, after: value };\n};\n\nconst publishMembers = (\n changes: Change[],\n at: DocumentAddress,\n members: MemberChange[],\n order?: { before: readonly string[]; after: readonly string[] }\n): void => {\n if (!members.length && !order) return;\n for (let i = 1; i < members.length; i++)\n if (members[i - 1].key > members[i].key) {\n members.sort((a, b) => lexical(a.key, b.key));\n break;\n }\n changes.push(order ? { kind: 'members', at, members, order } : { kind: 'members', at, members });\n};\n\n/** Diff only the captured subtree; this algorithm has no recorder or session state. */\nconst diffMember = (\n changes: Change[],\n members: MemberChange[],\n node: DocumentNode,\n at: DocumentAddress,\n key: string,\n beforePresent: boolean,\n before: unknown,\n afterPresent: boolean,\n after: unknown\n): void => {\n if (beforePresent === afterPresent && (!beforePresent || Object.is(before, after))) return;\n if (beforePresent && afterPresent && before !== undefined && after !== undefined) {\n const sameShape =\n node.kind === 'object' ||\n (node.kind === 'variant' &&\n (before as Record<string, unknown>)[node.tag] ===\n (after as Record<string, unknown>)[node.tag]);\n if (sameShape) {\n const left = before as Record<string, unknown>,\n right = after as typeof left;\n const childAt = at.concat(key);\n const children: MemberChange[] = [];\n for (const [child, definition] of compiledShape(node, before)!.members)\n diffMember(\n changes,\n children,\n definition.node,\n childAt,\n child,\n Object.hasOwn(left, child),\n left[child],\n Object.hasOwn(right, child),\n right[child]\n );\n publishMembers(changes, childAt, children);\n return;\n }\n if (node.kind === 'map' || node.kind === 'table') {\n const a = before as Record<string, unknown>,\n b = after as typeof a;\n const left = (node.kind === 'table' ? a.byId : a) as Record<string, unknown>;\n const right = (node.kind === 'table' ? b.byId : b) as typeof left;\n const childAt = at.concat(key);\n const children: MemberChange[] = [];\n for (const id of Object.keys(left))\n diffMember(\n changes,\n children,\n node.value,\n childAt,\n id,\n true,\n left[id],\n Object.hasOwn(right, id),\n right[id]\n );\n for (const id of Object.keys(right))\n if (!Object.hasOwn(left, id))\n diffMember(changes, children, node.value, childAt, id, false, undefined, true, right[id]);\n let order: { before: readonly string[]; after: readonly string[] } | undefined;\n if (node.kind === 'table' && !sequence.equal(a.ids as string[], b.ids as string[])) {\n profile.recorder('publishedOrderItems', (b.ids as string[]).length);\n order = { before: a.ids as string[], after: [...(b.ids as string[])] };\n }\n publishMembers(changes, childAt, children, order);\n return;\n }\n }\n const member = transition(node, key, beforePresent, before, afterPresent, after);\n if (member) members.push(member);\n};\nconst restore = (fact: RestoreFact, schema: DocumentNode, root: unknown, skip = 0): unknown => {\n const at = skip ? fact.at.slice(skip) : fact.at;\n if (fact.kind === 'member') {\n const member = fact.member;\n const value = member.present ? schemaValue.copyValue(member.node, member.value) : undefined;\n if (!at.length) return value;\n const location = address.resolveLocated(schema, root, at);\n if (!location) throw new Error('Cannot restore an unresolved member.');\n state.installMember(location.parent, location.key, member.present, value);\n return root;\n }\n const location = address.resolveValue(schema, root, at);\n if (!location) throw new Error('Cannot restore an unresolved subtree.');\n if (fact.kind === 'order') state.installOrder(location.node, location.value, fact.group.order!);\n else {\n const tree = location.value as MutableTree;\n if (fact.before === null) delete tree.rootId;\n else tree.rootId = fact.before;\n for (const [id, node] of fact.nodes)\n state.installMember(\n tree.nodes,\n id,\n node !== undefined,\n node && schemaValue.copyTreeNode(node)\n );\n }\n return root;\n};\n\nconst reconstructBefore = (\n node: DocumentNode,\n current: unknown,\n records: readonly RestoreFact[],\n offset: number\n): unknown => {\n let before = schemaValue.copyValue(node, current);\n for (let i = records.length - 1; i >= 0; i--)\n if (records[i].kind !== 'order') before = restore(records[i], node, before, offset);\n for (const record of records)\n if (record.kind === 'order') before = restore(record, node, before, offset);\n return before;\n};\n\nconst sealMembers = (fact: MemberGroup, changes: Change[]): void => {\n const members: MemberChange[] = [];\n for (const member of fact.members?.values() ?? []) {\n if (!member) continue;\n const key = address.memberKey(fact, member.key);\n const present = Object.hasOwn(fact.parent, key);\n const value = (fact.parent as Record<string | number, unknown>)[key];\n if (member.node.kind === 'field') {\n const change = transition(\n member.node,\n member.key,\n member.present,\n member.value,\n present,\n value\n );\n if (change) members.push(change);\n } else\n diffMember(\n changes,\n members,\n member.node,\n fact.at,\n member.key,\n member.present,\n member.value,\n present,\n value\n );\n }\n let order: { before: readonly string[]; after: readonly string[] } | undefined;\n if (fact.order) {\n const current =\n fact.node.kind === 'list'\n ? sequence.indexedKeys(fact.value as unknown[], fact.node.keyOf)\n : (fact.value as { ids: string[] }).ids;\n if (!sequence.equal(fact.order, current)) {\n const after = state.orderOf(fact.node, fact.value);\n profile.recorder('publishedOrderItems', after.length);\n order = { before: fact.order, after };\n }\n }\n publishMembers(changes, fact.at, members, order);\n};\n\nconst sealTree = (fact: TreeFact, canonical: state.CanonicalState, changes: Change[]): void => {\n const location = address.resolveValue(canonical.schema, canonical.document, fact.at);\n const tree = location?.value as MutableTree;\n const node = location?.node;\n if (node?.kind !== 'tree') throw new Error('Tree schema disappeared before sealing.');\n const nodes: Extract<Change, { kind: 'tree' }>['nodes'][number][] = [];\n for (const [id, before] of fact.nodes) {\n const after = Object.hasOwn(tree.nodes, id) ? tree.nodes[id] : undefined;\n if (!before && !after) continue;\n if (before && after && schemaValue.equalTreeNode(before, after)) continue;\n nodes.push(\n !before\n ? { id, kind: 'added', after: schemaValue.copyTreeNode(after!) }\n : !after\n ? { id, kind: 'removed', before }\n : { id, kind: 'updated', before, after: schemaValue.copyTreeNode(after) }\n );\n }\n const after = tree.rootId ?? null;\n if (nodes.length || fact.before !== after)\n changes.push({\n kind: 'tree',\n at: fact.at,\n before: fact.before,\n after,\n nodes: nodes.sort((a, b) => lexical(a.id, b.id)),\n });\n};\n\n/** One first-touch record per owning container, never a per-write operation log. */\nexport class ChangeRecorder {\n private readonly facts = new Set<Fact>();\n private groups = new WeakMap<object, MemberGroup>();\n private index?: AddressIndex<Fact>;\n private indexedGroups = false;\n private resetBefore?: { value: unknown };\n constructor(private readonly state: state.CanonicalState) {}\n private indexGroups(): AddressIndex<Fact> {\n const index = (this.index ??= new AddressIndex());\n if (!this.indexedGroups) {\n this.indexedGroups = true;\n for (const fact of this.facts) {\n if (fact.kind === 'members') {\n index.add(fact.at, fact);\n profile.recorder('indexedGroups');\n }\n }\n }\n return index;\n }\n private covered(at: DocumentAddress): boolean {\n return (\n this.resetBefore !== undefined ||\n (this.indexedGroups &&\n this.index!.someAncestor(\n at,\n fact =>\n fact.kind === 'members' &&\n fact.at.length < at.length &&\n firstMember(fact, at[fact.at.length]) !== undefined\n ))\n );\n }\n private absorb(\n at: DocumentAddress,\n node: DocumentNode,\n value: unknown,\n present: boolean\n ): unknown {\n const index = this.indexGroups();\n const children: RestoreFact[] = [];\n index.query(fact => {\n if (fact.kind === 'members') {\n // An ancestor group can contribute only its one directly addressed member.\n if (fact.at.length < at.length) {\n if (fact.at.length + 1 === at.length) {\n const member = firstMember(fact, at[fact.at.length]);\n if (member) children.push({ kind: 'member', at, group: fact, member });\n }\n return;\n }\n if (fact.order && relation.contains(at, fact.at))\n children.push({ kind: 'order', at: fact.at, group: fact });\n for (const member of fact.members?.values() ?? []) {\n if (!member) continue;\n const memberAt = fact.at.concat(member.key);\n if (relation.contains(at, memberAt))\n children.push({ kind: 'member', at: memberAt, group: fact, member });\n }\n } else if (relation.contains(at, fact.at)) children.push(fact);\n })(at);\n if (present) value = reconstructBefore(node, value, children, at.length);\n this.releaseCovered(children);\n return value;\n }\n private releaseCovered(children: readonly RestoreFact[]): void {\n let changedGroups: Set<MemberGroup> | undefined;\n for (const child of children) {\n profile.recorder('absorbed');\n if (child.kind === 'member') {\n const { group, member } = child;\n forgetMember(group, member.key);\n (changedGroups ??= new Set()).add(group);\n } else if (child.kind === 'order') {\n child.group.order = undefined;\n (changedGroups ??= new Set()).add(child.group);\n } else {\n this.unregister(child);\n }\n }\n for (const group of changedGroups ?? []) {\n if (emptyGroup(group)) {\n this.unregister(group);\n }\n }\n }\n private register(fact: Fact): void {\n this.facts.add(fact);\n if (fact.kind === 'members') {\n this.groups.set(fact.parent, fact);\n profile.recorder('groups');\n if (!this.indexedGroups) return;\n profile.recorder('indexedGroups');\n }\n (this.index ??= new AddressIndex()).add(fact.at, fact);\n }\n private unregister(fact: Fact): void {\n this.facts.delete(fact);\n this.index?.delete(fact.at, fact);\n if (fact.kind === 'members') this.groups.delete(fact.parent);\n }\n member(\n container: address.ResolvedContainer,\n key: string,\n definition: CompiledMember,\n physicalKey: string | number\n ): void {\n if (this.resetBefore) return;\n const { node } = definition;\n let group = this.groups.get(container.parent);\n if (group?.layout === 'dynamic' && group.members?.has(key)) return;\n if (group?.layout === 'fixed' && definition.kind === 'fixed' && group.members[definition.slot])\n return;\n const at = this.indexedGroups || node.kind !== 'field' ? container.at.concat(key) : undefined;\n if (at && this.covered(at)) return;\n const present = Object.hasOwn(container.parent, physicalKey);\n let value = (container.parent as Record<string | number, unknown>)[physicalKey];\n if (node.kind !== 'field') value = this.absorb(at!, node, value, present);\n if (!group || !this.facts.has(group)) {\n group = this.createGroup(container);\n }\n const member: MemberFact = { key, node, present, value };\n if (group.layout === 'dynamic') (group.members ??= new Map()).set(key, member);\n else if (definition.kind === 'fixed') group.members[definition.slot] = member;\n else throw new Error('A fixed member group requires a fixed schema member.');\n profile.recorder('facts');\n }\n reset(): void {\n if (this.resetBefore) return;\n const value = this.absorb([], this.state.schema, this.state.document, true);\n this.resetBefore = { value };\n this.groups = new WeakMap();\n profile.recorder('facts');\n }\n private createGroup(container: address.ResolvedContainer): MemberGroup {\n const group: MemberGroup =\n container.layout.kind === 'fixed'\n ? {\n kind: 'members',\n at: container.at,\n node: container.node,\n parent: container.parent,\n value: container.value,\n layout: 'fixed',\n definitions: container.layout.members,\n members: new Array<MemberFact | undefined>(container.layout.members.size),\n }\n : {\n kind: 'members',\n at: container.at,\n node: container.node,\n parent: container.parent,\n value: container.value,\n layout: 'dynamic',\n members: undefined,\n };\n this.register(group);\n return group;\n }\n order(container: address.ResolvedContainer): void {\n profile.recorder('orderCaptures');\n let group = this.groups.get(container.parent);\n if (group?.order || this.covered(container.at)) return;\n group ??= this.createGroup(container);\n group.order = state.orderOf(container.node, container.value);\n profile.recorder('orderSnapshots');\n profile.recorder('orderItems', group.order.length);\n }\n tree(container: address.ResolvedTreeContainer, id?: string): void {\n const { at, value: tree } = container;\n if (this.covered(at)) return;\n const index = (this.index ??= new AddressIndex());\n let fact: TreeFact | undefined;\n for (const item of index.exact(at) ?? []) if (item.kind === 'tree') fact = item;\n if (!fact) {\n fact = { kind: 'tree', at, before: tree.rootId ?? null, nodes: new Map() };\n this.register(fact);\n }\n if (id !== undefined && !fact.nodes.has(id)) {\n profile.recorder('treeNodes');\n fact.nodes.set(\n id,\n Object.hasOwn(tree.nodes, id) ? schemaValue.copyTreeNode(tree.nodes[id]) : undefined\n );\n }\n }\n rollback(): void {\n if (this.resetBefore) {\n this.state.document = this.resetBefore.value;\n return;\n }\n const facts = [...this.facts];\n for (let i = facts.length - 1; i >= 0; i--) {\n const fact = facts[i];\n if (fact.kind === 'members') {\n for (const member of fact.members?.values() ?? []) {\n if (!member) continue;\n state.installMember(\n fact.parent,\n address.memberKey(fact, member.key),\n member.present,\n member.present ? schemaValue.copyValue(member.node, member.value) : undefined\n );\n }\n } else if (fact.kind === 'tree') restore(fact, this.state.schema, this.state.document);\n }\n for (const fact of facts)\n if (fact.kind === 'members' && fact.order)\n state.installOrder(fact.node, fact.value, fact.order);\n }\n seal(): ChangeSet {\n if (this.resetBefore) {\n if (schemaValue.equalValue(this.state.schema, this.resetBefore.value, this.state.document))\n return changeSet.sealChanges([]);\n profile.recorder('sealed');\n return changeSet.sealChanges([\n {\n kind: 'reset',\n before: this.resetBefore.value,\n after: schemaValue.copyValue(this.state.schema, this.state.document),\n },\n ]);\n }\n const changes: Change[] = [];\n for (const fact of this.facts) {\n if (fact.kind === 'members') sealMembers(fact, changes);\n else sealTree(fact, this.state, changes);\n }\n const result = changeSet.sealChanges(changes);\n profile.recorder('sealed', result.changes.length);\n return result;\n }\n}\nconst lexical = (a: string, b: string): number => (a < b ? -1 : a === b ? 0 : 1);\n","import type { ChangeSet } from '../changes';\nimport type { DocumentAddress, DocumentNode } from '../schema/model';\nimport * as address from '../address/resolve';\nimport type { CompiledMember } from '../schema/layout';\nimport * as schemaValue from '../schema/value';\nimport { ChangeRecorder } from './recorder';\nimport * as state from './state';\nimport * as issue from './issue';\n\nexport class MutationSession {\n readonly identity = {};\n generation = 0;\n readonly recorder: ChangeRecorder;\n private resolver;\n private resolvedRoot: unknown;\n constructor(readonly state: state.CanonicalState) {\n this.recorder = new ChangeRecorder(state);\n this.resolver = address.createAddressResolver(state.schema, state.document);\n this.resolvedRoot = state.document;\n }\n validate(node: DocumentNode, value: unknown, at: DocumentAddress): void {\n const failure = schemaValue.checkValue(node, value, at);\n if (failure) issue.invalidValue(failure);\n }\n resolveContainer(at: DocumentAddress): address.ResolvedContainer {\n return (\n this.resolver.container(this.identity, this.generation, at) ??\n issue.fail(at, 'invalid-address', 'Container does not exist.')\n );\n }\n /** Bind access-resolved canonical facts without walking the address again. */\n bind(\n at: DocumentAddress,\n node: DocumentNode | undefined,\n value: unknown\n ): address.ResolvedContainer {\n return (\n address.resolveContainer(this.identity, this.generation, at, node, value) ??\n issue.fail(at, 'invalid-address', 'Container does not exist.')\n );\n }\n bindTree(\n at: DocumentAddress,\n node: DocumentNode | undefined,\n value: unknown\n ): address.ResolvedTreeContainer {\n return (\n address.resolveTreeContainer(this.identity, this.generation, at, node, value) ??\n issue.fail(at, 'invalid-tree', 'Expected a tree.')\n );\n }\n resolveTree(at: DocumentAddress): address.ResolvedTreeContainer {\n const location = address.resolveValue(this.state.schema, this.state.document, at);\n return this.bindTree(at, location?.node, location?.value);\n }\n replace(at: DocumentAddress, value: unknown): void {\n if (!at.length) {\n this.validate(this.state.schema, value, at);\n if (Object.is(this.state.document, value)) return;\n this.recorder.reset();\n this.state.document = schemaValue.copyValue(this.state.schema, value);\n this.invalidate();\n return;\n }\n this.writeMember(this.resolveContainer(at.slice(0, -1)), at[at.length - 1], value, 'set');\n }\n assignMember(container: address.ResolvedContainer, key: string, value: unknown): void {\n container = this.refresh(container);\n const member = this.definition(container, key);\n if (\n container.layout.kind === 'fixed' &&\n member.node.kind !== 'field' &&\n member.node.kind !== 'variant' &&\n !member.node.optional\n )\n return issue.fail(\n container.at.concat(key),\n 'invalid-value',\n 'Replace fields, variants, or collection entries; edit object members individually.'\n );\n this.writeLocatedMember(\n container,\n key,\n member,\n address.memberKey(container, key),\n value,\n 'set'\n );\n }\n removeMember(container: address.ResolvedContainer, key: string): void {\n this.writeMember(this.refresh(container), key, undefined, 'remove');\n }\n private refresh(container: address.ResolvedContainer): address.ResolvedContainer {\n if (container.owner !== this.identity)\n return issue.fail(\n container.at,\n 'invalid-address',\n 'Container belongs to another mutation session.'\n );\n return container.generation === this.generation\n ? container\n : this.resolveContainer(container.at);\n }\n definition(container: address.ResolvedContainer, key: string): CompiledMember {\n const layout = container.layout;\n const member = layout.kind === 'dynamic' ? layout.entry : layout.members.get(key);\n if (!member)\n return issue.fail(container.at.concat(key), 'invalid-address', 'Address does not exist.');\n return member;\n }\n /** Consume a current command-local container; bulk writes retain its storage. */\n writeMember(\n container: address.ResolvedContainer,\n key: string,\n value: unknown,\n operation: 'set' | 'remove',\n physicalKey = address.memberKey(container, key)\n ): boolean {\n const member = this.definition(container, key);\n return this.writeLocatedMember(container, key, member, physicalKey, value, operation);\n }\n /** Location and definition are resolved once by the calling operation. */\n private writeLocatedMember(\n container: address.ResolvedContainer,\n key: string,\n member: CompiledMember,\n physicalKey: string | number,\n value: unknown,\n operation: 'set' | 'remove'\n ): boolean {\n const parentNode = container.node;\n const node = member.node;\n const present = operation === 'set';\n if (parentNode.kind === 'variant' && parentNode.tag === key)\n return issue.fail(\n container.at.concat(key),\n 'invalid-value',\n 'Variant discriminants are read-only.'\n );\n const entry = container.layout.kind === 'dynamic';\n if (!present && !node.optional && !entry)\n return issue.fail(\n container.at.concat(key),\n 'required-field',\n 'A required value cannot be removed.'\n );\n const existed = Object.hasOwn(container.parent, physicalKey);\n const previous = (container.parent as Record<string | number, unknown>)[physicalKey];\n if (existed === present && (!present || Object.is(previous, value))) return false;\n if (parentNode.kind === 'map' || parentNode.kind === 'table') {\n const failure = schemaValue.checkKey(parentNode.key, key, []);\n if (failure)\n return issue.fail(\n container.at.concat(key, ...failure.address),\n 'invalid-key',\n failure.message\n );\n }\n if (present) {\n if (node.kind === 'field') {\n const failure = schemaValue.checkValue(node, value, []);\n if (failure)\n return issue.invalidValue(failure, container.at.concat(key, ...failure.address));\n } else this.validate(node, value, container.at.concat(key));\n if (parentNode.kind === 'list' && parentNode.keyOf(value) !== key)\n return issue.fail(\n container.at.concat(key),\n 'invalid-list-key',\n 'Replacing an item must retain its addressed key.'\n );\n }\n const membershipChanged = entry && existed !== present;\n if (membershipChanged && (parentNode.kind === 'list' || parentNode.kind === 'table'))\n this.recorder.order(container);\n this.recorder.member(container, key, member, physicalKey);\n const next = present\n ? node.kind === 'field'\n ? value\n : schemaValue.copyValue(node, value)\n : undefined;\n state.installMember(container.parent, physicalKey, present, next);\n if (node.kind !== 'field' || membershipChanged) this.invalidate();\n return membershipChanged;\n }\n invalidate(): void {\n this.generation++;\n if (this.resolvedRoot !== this.state.document) {\n this.resolvedRoot = this.state.document;\n this.resolver = address.createAddressResolver(this.state.schema, this.state.document);\n } else this.resolver.invalidate();\n }\n finish(): ChangeSet {\n return this.recorder.seal();\n }\n rollback(): void {\n this.recorder.rollback();\n this.invalidate();\n }\n}\n","import type { ChangeDirection, ChangeSet } from '../../changes';\nimport type { MutationSession } from '../session';\nimport * as state from '../state';\nimport * as sequence from '../../order/sequence';\nimport * as issue from '../issue';\nimport * as schemaValue from '../../schema/value';\nimport * as tree from '../../tree/topology';\nexport function apply(\n session: MutationSession,\n changes: ChangeSet,\n direction: ChangeDirection\n): void {\n const side = direction === 'forward' ? 'after' : 'before';\n for (const change of changes.changes) {\n if (change.kind === 'reset') {\n session.replace([], change[side]);\n } else if (change.kind === 'members') {\n const container = session.resolveContainer(change.at);\n const { node, value: current } = container;\n if (change.order) {\n if (node.kind !== 'table' && node.kind !== 'list')\n return issue.fail(change.at, 'invalid-changes', 'Order requires an ordered container.');\n session.recorder.order(container);\n }\n let membershipChanged = false;\n for (const member of change.members) {\n const present = side === 'after' ? member.kind !== 'removed' : member.kind !== 'added';\n const value =\n side === 'after'\n ? member.kind !== 'removed'\n ? member.after\n : undefined\n : member.kind !== 'added'\n ? member.before\n : undefined;\n membershipChanged =\n session.writeMember(container, member.key, value, present ? 'set' : 'remove') ||\n membershipChanged;\n }\n if (change.order) {\n const keys =\n node.kind === 'table' ? Object.keys(container.parent) : state.orderOf(node, current);\n if (!sequence.matches(change.order[side], keys))\n return issue.fail(\n change.at,\n 'invalid-changes',\n 'Order must contain exactly the resulting keys.'\n );\n state.installOrder(node, current, change.order[side]);\n session.invalidate();\n } else if (membershipChanged && node.kind === 'table') {\n const ids = (current as { ids: string[] }).ids;\n if (!sequence.matches(ids, Object.keys(container.parent)))\n return issue.fail(\n change.at,\n 'invalid-changes',\n 'Table membership changes require a matching order.'\n );\n }\n } else {\n const container = session.resolveTree(change.at);\n const { value: current, node } = container;\n session.recorder.tree(container);\n for (const item of change.nodes) session.recorder.tree(container, item.id);\n const root = change[side];\n if (root === null) delete current.rootId;\n else current.rootId = root;\n for (const item of change.nodes) {\n const next =\n side === 'after'\n ? item.kind !== 'removed'\n ? item.after\n : undefined\n : item.kind !== 'added'\n ? item.before\n : undefined;\n if (next !== undefined) {\n const diagnostic = schemaValue.checkTreePayload(\n node.value,\n next,\n change.at.concat(item.id)\n );\n if (diagnostic) issue.invalidValue(diagnostic);\n }\n state.installMember(\n current.nodes,\n item.id,\n next !== undefined,\n next && schemaValue.copyTreeNode(next)\n );\n }\n if (!tree.validate(current))\n return issue.fail(change.at, 'invalid-tree', 'Invalid tree structure.');\n session.invalidate();\n }\n }\n}\n","import type { ObjectSchema } from '../schema/model';\nimport type { ReadonlyDocument, DocumentRuntime } from './contract';\nimport { bindContext, contextOf } from './context';\n\n// A readable capability keeps the canonical runtime behind an explicit\n// mutation funnel while remaining fully compatible with selectors, views, and\n// framework subscriptions.\nexport const readonlyDocument = <TSchema extends ObjectSchema<object>>(\n runtime: DocumentRuntime<TSchema>\n): ReadonlyDocument<TSchema> => {\n const readable: ReadonlyDocument<TSchema> = {\n revision: runtime.revision,\n subscribe: runtime.subscribe,\n };\n bindContext(readable, contextOf(runtime));\n return Object.freeze(readable);\n};\n","import type { ObjectSchema, RootNodeOf } from '../schema/model';\nimport type { ImpactTarget } from '../schema/path';\nimport type { CommitListener, DocumentCommit, Unsubscribe, ObserverError } from './contract';\nimport * as target from '../impact/target';\n\ntype ProjectionAttachment<TSchema extends ObjectSchema<object>> = {\n capture(commit: DocumentCommit<TSchema>): void;\n settle(): void;\n flush(): readonly ObserverError[];\n dispose(): void;\n};\ntype ProcessorEntry<TSchema extends ObjectSchema<object>> = {\n readonly processor: ProjectionAttachment<TSchema>;\n active: boolean;\n};\ntype RootEntry<TSchema extends ObjectSchema<object>> = {\n readonly listener: CommitListener<TSchema>;\n active: boolean;\n};\ntype FilteredEntry<TSchema extends ObjectSchema<object>> = {\n readonly targets: readonly ImpactTarget<unknown>[];\n readonly listener: CommitListener<TSchema>;\n active: boolean;\n};\ntype NotificationState<TSchema extends ObjectSchema<object>> = {\n readonly root: Set<RootEntry<TSchema>>;\n readonly filtered: Set<FilteredEntry<TSchema>>;\n readonly index: target.SubscriptionIndex<FilteredEntry<TSchema>>;\n readonly cleanups: Set<() => void>;\n readonly processors: ProcessorEntry<TSchema>[];\n readonly candidates: Set<FilteredEntry<TSchema>>;\n readonly rootSnapshot: RootEntry<TSchema>[];\n notifying: boolean;\n};\nexport type NotificationCenter<TSchema extends ObjectSchema<object>> = {\n subscribe(listener: CommitListener<TSchema>): Unsubscribe;\n subscribeTargets(\n targets: readonly ImpactTarget<unknown>[],\n listener: CommitListener<TSchema>\n ): Unsubscribe;\n attachProjection(processor: ProjectionAttachment<TSchema>): Unsubscribe;\n publish(\n commit: DocumentCommit<TSchema>,\n afterSettle?: () => readonly ObserverError[]\n ): readonly ObserverError[];\n dispose(): void;\n};\n\nconst attachProjection = <TSchema extends ObjectSchema<object>>(\n notification: NotificationState<TSchema>,\n processor: ProjectionAttachment<TSchema>\n): Unsubscribe => {\n const entry: ProcessorEntry<TSchema> = { processor, active: true };\n notification.processors.push(entry);\n return () => {\n if (!entry.active) return;\n entry.active = false;\n if (!notification.notifying) {\n const index = notification.processors.indexOf(entry);\n if (index >= 0) notification.processors.splice(index, 1);\n }\n };\n};\n\nconst addRoot = <TSchema extends ObjectSchema<object>>(\n notification: NotificationState<TSchema>,\n listener: CommitListener<TSchema>\n): Unsubscribe => {\n const entry: RootEntry<TSchema> = { listener, active: true };\n notification.root.add(entry);\n return () => {\n entry.active = false;\n if (!notification.notifying) notification.root.delete(entry);\n else\n notification.cleanups.add(() => {\n notification.root.delete(entry);\n });\n };\n};\n\nconst addFiltered = <TSchema extends ObjectSchema<object>>(\n notification: NotificationState<TSchema>,\n targets: readonly ImpactTarget<unknown>[],\n listener: CommitListener<TSchema>\n): Unsubscribe => {\n const entry: FilteredEntry<TSchema> = {\n targets: Object.freeze(targets.slice()),\n listener,\n active: true,\n };\n notification.filtered.add(entry);\n entry.targets.forEach(value => notification.index.add(value, entry));\n const remove = () => {\n notification.filtered.delete(entry);\n entry.targets.forEach(value => notification.index.delete(value, entry));\n };\n return () => {\n if (!entry.active) return;\n entry.active = false;\n if (notification.notifying) notification.cleanups.add(remove);\n else remove();\n };\n};\n\nconst publishState = <TSchema extends ObjectSchema<object>>(\n notification: NotificationState<TSchema>,\n commit: DocumentCommit<TSchema>,\n afterSettle?: () => readonly ObserverError[]\n): readonly ObserverError[] => {\n notification.notifying = true;\n const errors: ObserverError[] = [];\n const call = (listener: CommitListener<TSchema>): void => {\n try {\n listener(commit);\n } catch (error) {\n errors.push(Object.freeze({ phase: 'listener', error }));\n }\n };\n try {\n const processorCount = notification.processors.length;\n for (let index = 0; index < processorCount; index += 1) {\n const entry = notification.processors[index];\n if (!entry?.active) continue;\n try {\n entry.processor.capture(commit);\n } catch (error) {\n errors.push(Object.freeze({ phase: 'processor', error }));\n }\n }\n for (let index = 0; index < processorCount; index += 1) {\n const entry = notification.processors[index];\n if (!entry?.active) continue;\n try {\n entry.processor.settle();\n } catch (error) {\n errors.push(Object.freeze({ phase: 'processor', error }));\n }\n }\n for (let index = 0; index < processorCount; index += 1) {\n const entry = notification.processors[index];\n if (!entry?.active) continue;\n try {\n errors.push(...entry.processor.flush());\n } catch (error) {\n errors.push(Object.freeze({ phase: 'flush', error }));\n }\n }\n\n if (afterSettle) errors.push(...afterSettle());\n const candidates = notification.candidates;\n candidates.clear();\n if (notification.filtered.size)\n notification.index.collect(commit.changes, entry => candidates.add(entry));\n candidates.forEach(entry => {\n if (entry.active) call(entry.listener);\n });\n const rootSnapshot = notification.rootSnapshot;\n rootSnapshot.length = 0;\n notification.root.forEach(entry => rootSnapshot.push(entry));\n for (const entry of rootSnapshot) if (entry.active) call(entry.listener);\n } finally {\n notification.notifying = false;\n let writeIndex = 0;\n for (const entry of notification.processors)\n if (entry.active) notification.processors[writeIndex++] = entry;\n notification.processors.length = writeIndex;\n notification.cleanups.forEach(cleanup => cleanup());\n notification.cleanups.clear();\n }\n return Object.freeze(errors);\n};\n\nconst disposeState = <TSchema extends ObjectSchema<object>>(\n notification: NotificationState<TSchema>\n): void => {\n const attachments = notification.processors.slice();\n notification.root.clear();\n notification.filtered.clear();\n notification.index.clear();\n notification.cleanups.clear();\n notification.processors.length = 0;\n notification.candidates.clear();\n notification.rootSnapshot.length = 0;\n const errors: unknown[] = [];\n attachments.forEach(entry => {\n if (!entry.active) return;\n try {\n entry.processor.dispose();\n } catch (error) {\n errors.push(error);\n }\n });\n if (errors.length) throw new AggregateError(errors, 'Projection disposal notification failed.');\n};\n\nexport const createNotificationCenter = <TSchema extends ObjectSchema<object>>(\n schema: RootNodeOf<TSchema>\n): NotificationCenter<TSchema> => {\n const state: NotificationState<TSchema> = {\n root: new Set(),\n filtered: new Set(),\n index: new target.SubscriptionIndex(schema),\n cleanups: new Set(),\n processors: [],\n candidates: new Set(),\n rootSnapshot: [],\n notifying: false,\n };\n return Object.freeze({\n subscribe: (listener: CommitListener<TSchema>) => addRoot(state, listener),\n subscribeTargets: (\n targets: readonly ImpactTarget<unknown>[],\n listener: CommitListener<TSchema>\n ) => addFiltered(state, targets, listener),\n attachProjection: (processor: ProjectionAttachment<TSchema>) =>\n attachProjection(state, processor),\n publish: (commit: DocumentCommit<TSchema>, afterSettle?: () => readonly ObserverError[]) =>\n publishState(state, commit, afterSettle),\n dispose: () => disposeState(state),\n });\n};\n","import type { Infer, ObjectSchema, RootNodeOf } from './schema/model';\nimport { schemaNodeOf } from './schema/model';\nimport type { PathPick } from './schema/path';\nimport { compilePath } from './schema/path';\nimport { createImpact } from './impact';\nimport { createHistory } from './history';\nimport { createAccess, type Draft } from './access/scope';\nimport { MutationSession } from './mutation/session';\nimport * as replay from './mutation/operations/replay';\nimport type { RuntimeWriteIntent } from './runtime/driver';\nimport * as changeSet from './mutation/changes';\nimport * as issue from './mutation/issue';\nimport type { ChangeSet } from './changes';\nimport * as schemaValue from './schema/value';\nimport {\n DocumentDisposedError,\n DocumentReentrancyError,\n TransactionRejected,\n} from './runtime/contract';\nimport type {\n CommitListener,\n CommitSource,\n DocumentCommit,\n DocumentRuntime,\n ReadonlyDocument,\n OperationResult,\n TransactionResult,\n} from './runtime/contract';\nimport { readonlyDocument } from './runtime/readable';\nimport { assertRuntimeWritable } from './runtime/driver';\nimport { bindContext, type RuntimeContext, type RuntimeState } from './runtime/context';\nimport { createNotificationCenter } from './runtime/notification';\n\nexport const createDocument = <S extends ObjectSchema<object>>(input: {\n readonly schema: S;\n readonly initial: Infer<S>;\n readonly history?: { readonly capacity?: number } | false;\n}): DocumentRuntime<S> => {\n const schema = schemaNodeOf(input.schema) as RootNodeOf<S>;\n const invalid = schemaValue.checkValue(schema, input.initial);\n if (invalid) throw new schemaValue.ParseError(invalid);\n const state: RuntimeState<S> = {\n schema,\n document: schemaValue.copyValue(schema, input.initial) as Infer<S>,\n disposed: false,\n projectionLocks: 0,\n };\n let revision = 0,\n busy = false;\n const notifications = createNotificationCenter<S>(schema);\n let runtime!: DocumentRuntime<S>, context!: RuntimeContext<S>;\n let readonlyAlias: ReadonlyDocument<S> | undefined;\n const idle = () => {\n if (state.disposed) throw new DocumentDisposedError();\n if (busy || state.projectionLocks) throw new DocumentReentrancyError();\n };\n const writable = (intent: Parameters<typeof assertRuntimeWritable>[1]) => {\n idle();\n assertRuntimeWritable(runtime, intent);\n };\n const history = createHistory<DocumentCommit<S>>({\n capacity: input.history === false ? 0 : Math.max(0, input.history?.capacity ?? 100),\n revision: () => revision,\n apply: (changes, direction) =>\n mutate({ kind: 'apply', source: 'history' }, false, session => {\n for (const change of changes) replay.apply(session, change, direction);\n }),\n assertIdle: idle,\n notify: run => {\n busy = true;\n try {\n return run();\n } finally {\n busy = false;\n }\n },\n });\n const publish = (\n changes: ChangeSet,\n source: CommitSource,\n recordHistory: boolean\n ): Extract<OperationResult<DocumentCommit<S>>, { status: 'committed' }> => {\n const commit: DocumentCommit<S> = {\n revision: ++revision,\n source,\n changes,\n impact: createImpact<S>(schema, changes),\n };\n if (source === 'remote') history.invalidate();\n else if (recordHistory && (source === 'local' || source === 'system')) history.record(changes);\n else if (source === 'history') history.publish();\n else history.endGroup();\n return {\n status: 'committed',\n commit,\n observerErrors: notifications.publish(commit, history.flush),\n };\n };\n function mutate(\n intent: Extract<RuntimeWriteIntent, { kind: 'update' }>,\n recordHistory: boolean,\n execute: (session: MutationSession) => void\n ):\n | OperationResult<DocumentCommit<S>>\n | Extract<TransactionResult<never, never>, { status: 'rejected' }>;\n function mutate(\n intent: Exclude<RuntimeWriteIntent, { kind: 'update' }>,\n recordHistory: boolean,\n execute: (session: MutationSession) => void\n ): OperationResult<DocumentCommit<S>>;\n function mutate(\n intent: RuntimeWriteIntent,\n recordHistory: boolean,\n execute: (session: MutationSession) => void\n ):\n | OperationResult<DocumentCommit<S>>\n | Extract<TransactionResult<never, never>, { status: 'rejected' }> {\n writable(intent);\n busy = true;\n try {\n const session = new MutationSession(state);\n let changes: ChangeSet;\n try {\n execute(session);\n changes = session.finish();\n } catch (error) {\n session.rollback();\n if (error instanceof issue.MutationRejected)\n return { status: 'rejected', issues: [error.issue], revision };\n if (intent.kind === 'update' && error instanceof TransactionRejected)\n return { status: 'rejected', issues: error.issues, revision };\n throw error;\n }\n if (!changes.changes.length) return { status: 'unchanged', revision };\n // Publication is outside the rollback boundary: observers see accepted state.\n return publish(changes, intent.source, recordHistory);\n } finally {\n busy = false;\n }\n }\n runtime = {\n schema: input.schema,\n revision: () => revision,\n readonly: () => (readonlyAlias ??= readonlyDocument(runtime)),\n update: <V>(\n run: (draft: Draft<S>) => V,\n options?: { source?: Extract<CommitSource, 'local' | 'system'>; history?: boolean }\n ): TransactionResult<V, DocumentCommit<S>> => {\n const source = options?.source ?? 'local';\n let value!: V;\n const result = mutate({ kind: 'update', source }, options?.history ?? true, session => {\n // Draft is a trusted borrowed view. It must not escape this synchronous callback.\n const draft = createAccess({\n state,\n session,\n }) as Draft<S>;\n value = run(draft);\n if (\n value !== null &&\n (typeof value === 'object' || typeof value === 'function') &&\n typeof (value as { then?: unknown }).then === 'function'\n )\n throw new TypeError('Document updates must be synchronous.');\n });\n return result.status === 'rejected' ? result : { ...result, value };\n },\n apply: (inputChanges, options) => {\n const source = options?.source ?? 'local';\n return mutate(\n { kind: 'apply', source },\n source === 'remote' ? false : (options?.history ?? true),\n session => {\n if (!options || options.expectedRevision !== revision)\n issue.fail([], 'baseline-mismatch', 'apply requires the current expectedRevision.');\n replay.apply(session, changeSet.decodeChanges(inputChanges), 'forward');\n }\n );\n },\n replace: (value, options) => {\n const source = options?.source ?? 'system';\n return mutate({ kind: 'replace', source }, source !== 'remote', session =>\n session.replace([], value)\n );\n },\n snapshot: () => {\n if (state.disposed) throw new DocumentDisposedError();\n return schemaValue.copyValue(schema, state.document) as Infer<S>;\n },\n subscribe: ((\n pick: PathPick<S> | readonly PathPick<S>[] | CommitListener<S>,\n listener?: CommitListener<S>\n ) => {\n if (state.disposed) throw new DocumentDisposedError();\n if (!listener) return notifications.subscribe(pick as CommitListener<S>);\n const picks: readonly PathPick<S>[] = Array.isArray(pick) ? pick : [pick as PathPick<S>];\n if (!picks.length) throw new TypeError('Expected at least one subscription path.');\n return notifications.subscribeTargets(\n picks.map(p => compilePath<S>(schema, 'value', p)),\n listener\n );\n }) as DocumentRuntime<S>['subscribe'],\n history: history.api,\n dispose: () => {\n if (state.disposed) return;\n idle();\n state.disposed = true;\n try {\n notifications.dispose();\n } finally {\n history.dispose();\n context.driver = undefined;\n }\n },\n };\n context = {\n state,\n owner: runtime,\n notifications,\n driver: undefined,\n bypassDepth: 0,\n };\n bindContext(runtime, context);\n bindContext(history.api, context);\n return runtime;\n};\n","import type { ImpactTarget } from '../schema/path';\nimport * as target from '../impact/target';\n\nexport type DependencyTracker = {\n readonly record: (target: ImpactTarget<unknown>) => void;\n readonly snapshot: () => readonly ImpactTarget<unknown>[];\n};\n\nexport const createDependencyTracker = (): DependencyTracker => {\n const targets: ImpactTarget<unknown>[] = [];\n const buckets = new Map<string, ImpactTarget<unknown>[]>();\n return {\n record: value => {\n const key = target.dependencyBucket(value);\n let entries = buckets.get(key);\n if (!entries) {\n entries = [];\n buckets.set(key, entries);\n } else if (entries.some(entry => target.same(entry, value))) return;\n entries.push(value);\n targets.push(value);\n },\n snapshot: () => Object.freeze(targets.slice()),\n };\n};\n","import type { ObjectSchema } from '../schema/model';\nimport { createAccess, type Read } from '../access/scope';\nimport type { DependencyTracker } from '../access/dependency';\nimport { DocumentDisposedError } from './contract';\nimport type { ReadonlyDocument } from './contract';\nimport { contextOf } from './context';\n\nexport const readWith = <TSchema extends ObjectSchema<object>, TResult>(\n runtime: ReadonlyDocument<TSchema>,\n run: (read: Read<TSchema>) => TResult,\n dependencies?: DependencyTracker\n): TResult => {\n const state = contextOf<TSchema>(runtime).state;\n if (state.disposed) throw new DocumentDisposedError();\n state.projectionLocks += 1;\n try {\n const reader = createAccess({\n state,\n dependencies,\n }) as Read<TSchema>;\n return run(reader);\n } finally {\n // readWith is an internal borrowed-reader boundary. Retaining its reader or\n // collection methods after this callback is undefined behavior.\n state.projectionLocks--;\n }\n};\n","import { createDependencyTracker } from '../access/dependency';\nimport type { Read } from '../access/scope';\nimport * as target from '../impact/target';\nimport type { Readable, Unsubscribe } from '../readable';\nimport type { ObjectSchema } from '../schema/model';\nimport type { ImpactTarget } from '../schema/path';\nimport { readWith } from './access';\nimport { DocumentDisposedError, type ReadonlyDocument } from './contract';\nimport { contextOf } from './context';\n\nexport type DocumentSelector<TSchema extends ObjectSchema<object>, TResult> = (\n read: Read<TSchema>\n) => TResult;\n\nexport const read = <TSchema extends ObjectSchema<object>, TResult>(\n document: ReadonlyDocument<TSchema>,\n selector: DocumentSelector<TSchema, TResult>\n): TResult => readWith(document, selector);\n\nconst sameDependencySet = (\n left: readonly ImpactTarget<unknown>[],\n right: readonly ImpactTarget<unknown>[]\n): boolean => {\n if (left.length !== right.length) return false;\n for (let index = 0; index < left.length; index += 1)\n if (!target.same(left[index], right[index])) return false;\n return true;\n};\n\nexport const select = <TSchema extends ObjectSchema<object>, TResult>(\n document: ReadonlyDocument<TSchema>,\n selector: DocumentSelector<TSchema, TResult>,\n equality: (previous: TResult, next: TResult) => boolean = Object.is\n): Readable<TResult> => {\n const context = contextOf<TSchema>(document);\n let initialized = false;\n let value!: TResult;\n let selectedRevision = 0;\n let documentRevision = -1;\n let dependencies: readonly ImpactTarget<unknown>[] = Object.freeze([]);\n let unsubscribeDocument: Unsubscribe | undefined;\n const listeners = new Set<() => void>();\n\n const evaluate = (): { readonly changed: boolean; readonly rebound: boolean } => {\n const tracker = createDependencyTracker();\n const next = readWith(document, selector, tracker);\n const nextDependencies = tracker.snapshot();\n const changed = !initialized || !equality(value, next);\n const rebound = !sameDependencySet(dependencies, nextDependencies);\n if (changed) {\n if (initialized) selectedRevision += 1;\n value = next;\n }\n dependencies = nextDependencies;\n initialized = true;\n documentRevision = document.revision();\n return { changed, rebound };\n };\n\n const installSubscription = (): void => {\n unsubscribeDocument?.();\n unsubscribeDocument =\n dependencies.length > 0\n ? context.notifications.subscribeTargets(dependencies, () => {\n const result = evaluate();\n if (result.rebound) installSubscription();\n if (result.changed) for (const listener of [...listeners]) listener();\n })\n : undefined;\n };\n\n const ensureCurrent = (): TResult => {\n if (context.state.disposed) throw new DocumentDisposedError();\n if (!initialized || (!unsubscribeDocument && documentRevision !== document.revision()))\n evaluate();\n return value;\n };\n\n return Object.freeze({\n current: ensureCurrent,\n revision: () => {\n ensureCurrent();\n return selectedRevision;\n },\n subscribe: (listener: () => void) => {\n ensureCurrent();\n listeners.add(listener);\n if (listeners.size === 1) installSubscription();\n return () => {\n listeners.delete(listener);\n if (!listeners.size) {\n unsubscribeDocument?.();\n unsubscribeDocument = undefined;\n }\n };\n },\n });\n};\n","import { defineSource, type CollectionInput, type Equality, type Input } from './definition';\n\nconst valueInput = <T>(\n initial: T,\n equality: (previous: T, next: T) => boolean = Object.is\n): Input<T> =>\n defineSource<T>(\n { kind: 'value-input', initial, equality: equality as Equality },\n { kind: 'value', equality: equality as Equality }\n ) as unknown as Input<T>;\n\nconst collectionInput = <K extends string, V>(\n initial: ReadonlyMap<K, V> = new Map<K, V>(),\n equality: (previous: V, next: V) => boolean = Object.is\n): CollectionInput<K, V> => {\n const entries = new Map<string, unknown>();\n for (const [key, value] of initial) {\n if (typeof key !== 'string') throw new TypeError('Projection keys must be strings.');\n entries.set(key, value);\n }\n return defineSource<ReadonlyMap<K, V>>(\n { kind: 'collection-input', initial: entries, equality: equality as Equality },\n { kind: 'collection', equality: equality as Equality }\n ) as CollectionInput<K, V>;\n};\n\nexport const input = Object.assign(valueInput, { collection: collectionInput });\n","import type { Readable } from '../readable';\nimport { contextOf } from '../runtime/context';\nimport type { ReadonlyDocument } from '../runtime/contract';\nimport type { Infer, ObjectSchema, ReadonlyValue } from '../schema/model';\nimport {\n compilePath,\n type CollectionEntry,\n type CollectionId,\n type CollectionPath,\n type PathValueOf,\n type SchemaPath,\n type ValueSelector,\n} from '../schema/path';\nimport type { ExternalCollectionSource, ExternalValueSource } from './contract';\nimport { defineSource, type KeyedProjection, type Projection } from './definition';\n\ntype PathSelector<S extends ObjectSchema<object>> = (path: SchemaPath<S>) => unknown;\n\n/** Establish a lazy reactive boundary from a document, readable, or external source. */\nexport function observe<S extends ObjectSchema<object>>(\n document: ReadonlyDocument<S>\n): Projection<Infer<S>>;\nexport function observe<T>(source: ExternalValueSource<T>): Projection<T>;\nexport function observe<K extends string, V>(\n source: ExternalCollectionSource<K, V>\n): KeyedProjection<K, V>;\nexport function observe<T>(readable: Readable<T>): Projection<T>;\nexport function observe<S extends ObjectSchema<object>, P extends CollectionPath>(\n document: ReadonlyDocument<S>,\n selector: (path: SchemaPath<S>) => P\n): KeyedProjection<CollectionId<P>, ReadonlyValue<CollectionEntry<P>>>;\nexport function observe<S extends ObjectSchema<object>, P>(\n document: ReadonlyDocument<S>,\n selector: (path: SchemaPath<S>) => P\n): Projection<PathValueOf<P>>;\nexport function observe<S extends ObjectSchema<object>>(\n source:\n | ReadonlyDocument<S>\n | Readable<unknown>\n | ExternalValueSource<unknown>\n | ExternalCollectionSource<string, unknown>,\n selector?: PathSelector<S>\n): Projection<unknown> {\n if (isExternalSource(source))\n return source.kind === 'collection'\n ? defineSource(\n { kind: 'external-collection', source },\n { kind: 'collection', equality: Object.is }\n )\n : defineSource(\n { kind: 'external-value', source, equality: Object.is },\n { kind: 'value', equality: Object.is }\n );\n if ('current' in source && typeof source.current === 'function')\n return defineSource(\n { kind: 'readable', readable: source as Readable<unknown>, equality: Object.is },\n { kind: 'value', equality: Object.is }\n );\n\n const document = source as ReadonlyDocument<S>;\n const state = contextOf<S>(document).state;\n const selected = selector\n ? compilePath<S>(state.schema, 'auto', selector)\n : (Object.freeze({\n kind: 'value' as const,\n schema: state.schema,\n address: Object.freeze([]),\n }) as ValueSelector);\n return defineSource(\n {\n kind: 'document',\n document: document as unknown as ReadonlyDocument<ObjectSchema<object>>,\n selector: selected,\n },\n { kind: selected.kind, equality: Object.is }\n );\n}\n\nconst isExternalSource = (\n source: unknown\n): source is ExternalValueSource<unknown> | ExternalCollectionSource<string, unknown> => {\n if (!source || typeof source !== 'object') return false;\n const candidate = source as {\n readonly kind?: unknown;\n readonly current?: unknown;\n readonly revision?: unknown;\n readonly subscribe?: unknown;\n };\n return (\n (candidate.kind === 'value' || candidate.kind === 'collection') &&\n typeof candidate.current === 'function' &&\n typeof candidate.revision === 'function' &&\n typeof candidate.subscribe === 'function'\n );\n};\n","import type { Synchronous } from '../runtime/contract';\nimport { snapshotCollectionView } from './collection/view';\nimport type { SourceContext } from './contract';\nimport {\n defineProcessor,\n isProjection,\n projectionRef,\n type KeyedProjection,\n type Projection,\n type ProducerDefinition,\n} from './definition';\nimport { assertSynchronous } from './graph/scheduler';\nimport { isPlainObject } from '../value/record';\n\ntype ProjectionDependencies = Readonly<Record<string, Projection<unknown>>>;\ntype ProjectionValues<D extends ProjectionDependencies> = {\n readonly [K in keyof D]: D[K] extends Projection<infer T> ? T : never;\n};\n\ntype Equality<T> = (previous: T, next: T) => boolean;\n\n/** A declared dynamic lookup from one driver entry to one key in another keyed projection. */\ntype KeyedDependency<\n DriverKey extends string,\n DriverValue,\n SourceKey extends string = string,\n SourceValue = unknown,\n> = {\n readonly source: KeyedProjection<SourceKey, SourceValue>;\n readonly key: (value: DriverValue, key: DriverKey) => Synchronous<SourceKey | undefined>;\n};\n\ntype KeyedDeriveDependency<K extends string, V> =\n | (Projection<unknown> & { readonly source?: never; readonly key?: never })\n | KeyedDependency<K, V, string, unknown>;\n\ntype KeyedDeriveDependencyRecord<K extends string, V> = Readonly<\n Record<string, KeyedDeriveDependency<K, V>>\n>;\n\ntype KeyedDeriveDependencies<K extends string, V, D extends object> = {\n readonly [P in keyof D]: P extends string ? KeyedDeriveDependency<K, V> : never;\n};\n\ntype KeyedDependencyValues<D extends Readonly<Record<string, unknown>>> = {\n readonly [P in keyof D]: D[P] extends {\n readonly source: KeyedProjection<infer _K extends string, infer V>;\n }\n ? V | undefined\n : D[P] extends Projection<infer T>\n ? T\n : never;\n};\n\ntype RuntimeKeyedDependency = {\n readonly source: Projection<unknown>;\n readonly key: (value: unknown, key: string) => unknown;\n};\n\ntype BindingIndex = {\n readonly forward: Map<string, string>;\n readonly reverse: Map<string, Set<string>>;\n};\n\nconst sourceValue = (source: SourceContext): unknown =>\n source.kind === 'value' ? source.value : snapshotCollectionView(source.read);\n\nconst outputKind = (projection: Projection<unknown>): 'value' | 'collection' => {\n const ref = projectionRef(projection);\n const definition: ProducerDefinition = ref.producer;\n const output = definition.kind === 'source' ? definition.output : definition.outputs[ref.output];\n if (!output) throw new TypeError('Projection output does not exist.');\n return output.kind;\n};\n\nconst assertKeyedProjection = (projection: Projection<unknown>, role: string): void => {\n if (outputKind(projection) !== 'collection')\n throw new TypeError(`${role} must be a keyed collection projection.`);\n};\n\nconst isKeyedDependency = (value: unknown): value is RuntimeKeyedDependency => {\n if (!value || typeof value !== 'object' || isProjection(value)) return false;\n const candidate = value as { readonly source?: unknown; readonly key?: unknown };\n return isProjection(candidate.source) && typeof candidate.key === 'function';\n};\n\nconst bindKey = (index: BindingIndex, outputKey: string, sourceKey: string | undefined): void => {\n const previous = index.forward.get(outputKey);\n if (previous === sourceKey) return;\n if (previous !== undefined) {\n const dependents = index.reverse.get(previous);\n dependents?.delete(outputKey);\n if (dependents?.size === 0) index.reverse.delete(previous);\n index.forward.delete(outputKey);\n }\n if (sourceKey === undefined) return;\n index.forward.set(outputKey, sourceKey);\n const dependents = index.reverse.get(sourceKey);\n if (dependents) dependents.add(outputKey);\n else index.reverse.set(sourceKey, new Set([outputKey]));\n};\n\nconst unbindKey = (indexes: readonly BindingIndex[], outputKey: string): void => {\n for (const index of indexes) bindKey(index, outputKey, undefined);\n};\n\nconst createBindingIndex = (): BindingIndex => ({ forward: new Map(), reverse: new Map() });\n\nfunction createValueDerive<const D extends ProjectionDependencies, T>(\n dependencies: D,\n compute: (values: ProjectionValues<D>) => Synchronous<T>,\n equality: Equality<T> = Object.is\n): Projection<T> {\n if (!isPlainObject(dependencies) || isProjection(dependencies))\n throw new TypeError('Derive dependencies must be a plain object.');\n const names = Object.keys(dependencies);\n const ordered = names.map(name => dependencies[name]);\n ordered.forEach(projectionRef);\n const [projection] = defineProcessor({\n dependencies: ordered,\n outputs: [{ kind: 'value', equality: equality as Equality<unknown> }],\n create: () => ({\n evaluate: evaluation => {\n const output = evaluation.outputs[0];\n if (output.kind !== 'value') throw new Error('derive requires a value output.');\n const values: Record<string, unknown> = Object.create(null) as Record<string, unknown>;\n for (let index = 0; index < names.length; index++)\n values[names[index]] = sourceValue(evaluation.sources[index]);\n const next = compute(Object.freeze(values) as ProjectionValues<D>);\n assertSynchronous(next);\n output.output.set(next);\n },\n }),\n });\n return projection as Projection<T>;\n}\n\nexport function createKeyedDerive<K extends string, V, T>(\n source: KeyedProjection<K, V>,\n select: (value: V, key: K) => Synchronous<T>,\n equality?: Equality<T>\n): KeyedProjection<K, T>;\nexport function createKeyedDerive<\n K extends string,\n V,\n const D extends object & KeyedDeriveDependencies<K, V, D>,\n T,\n>(\n source: KeyedProjection<K, V>,\n dependencies: D,\n select: (value: V, key: K, dependencies: KeyedDependencyValues<D>) => Synchronous<T>,\n equality?: Equality<T>\n): KeyedProjection<K, T>;\nexport function createKeyedDerive<K extends string, V, T>(\n source: KeyedProjection<K, V>,\n dependenciesOrSelect: KeyedDeriveDependencyRecord<K, V> | ((value: V, key: K) => Synchronous<T>),\n selectOrEquality?:\n | ((value: V, key: K, dependencies: Readonly<Record<string, unknown>>) => Synchronous<T>)\n | Equality<T>,\n maybeEquality?: Equality<T>\n): KeyedProjection<K, T> {\n assertKeyedProjection(source, 'Keyed derive source');\n const dependencySpecs =\n typeof dependenciesOrSelect === 'function' ? undefined : dependenciesOrSelect;\n const select = (dependencySpecs === undefined\n ? dependenciesOrSelect\n : selectOrEquality) as unknown as (\n value: V,\n key: K,\n dependencies?: Readonly<Record<string, unknown>>\n ) => Synchronous<T>;\n const equality = (dependencySpecs === undefined ? selectOrEquality : maybeEquality) as\n Equality<T> | undefined;\n if (typeof select !== 'function') throw new TypeError('Keyed derive requires a selector.');\n\n const dependencies: Projection<unknown>[] = [source];\n const dependencyNames: string[] = [];\n const keyed: Array<RuntimeKeyedDependency | undefined> = [];\n if (dependencySpecs !== undefined) {\n if (!isPlainObject(dependencySpecs) || isProjection(dependencySpecs))\n throw new TypeError('Keyed derive dependencies must be a plain object.');\n for (const name of Reflect.ownKeys(dependencySpecs)) {\n if (typeof name !== 'string')\n throw new TypeError('Keyed derive dependency names must be strings.');\n const descriptor = Object.getOwnPropertyDescriptor(dependencySpecs, name);\n if (!descriptor?.enumerable || !('value' in descriptor))\n throw new TypeError('Keyed derive dependencies must be enumerable data properties.');\n const dependency = descriptor.value as KeyedDeriveDependency<K, V>;\n dependencyNames.push(name);\n if (isProjection(dependency)) {\n dependencies.push(dependency);\n keyed.push(undefined);\n continue;\n }\n if (!isKeyedDependency(dependency))\n throw new TypeError('Keyed derive dependencies must be projections or keyed lookups.');\n assertKeyedProjection(dependency.source, 'Dynamic keyed dependency source');\n dependencies.push(dependency.source);\n keyed.push(dependency);\n }\n }\n\n const [projection] = defineProcessor({\n dependencies,\n outputs: [{ kind: 'collection', equality: (equality ?? Object.is) as Equality<unknown> }],\n create: () => {\n const bindings = keyed.map(dependency => (dependency ? createBindingIndex() : undefined));\n const bindingIndexes = bindings.filter((index): index is BindingIndex => index !== undefined);\n const globalValues: unknown[] = keyed.map(() => undefined);\n let revisions: readonly number[] = Object.freeze([]);\n\n const clearBindings = (): void => {\n for (const index of bindings) {\n index?.forward.clear();\n index?.reverse.clear();\n }\n };\n\n return {\n evaluate: evaluation => {\n const driver = evaluation.sources[0];\n const output = evaluation.outputs[0];\n if (driver.kind !== 'collection' || output.kind !== 'collection')\n throw new Error('Keyed derive requires collection input and output.');\n const currentRevisions = evaluation.sources.map(current => current.revision);\n for (let index = 0; index < keyed.length; index++) {\n if (keyed[index]) continue;\n if (evaluation.reset || revisions[index + 1] !== currentRevisions[index + 1])\n globalValues[index] = sourceValue(evaluation.sources[index + 1]);\n }\n\n const project = (key: string): void => {\n if (!driver.read.has(key)) return;\n const value = driver.read.get(key) as V;\n const dependencyValues: Record<string, unknown> = Object.create(null) as Record<\n string,\n unknown\n >;\n for (let index = 0; index < keyed.length; index++) {\n const dependency = keyed[index];\n if (!dependency) {\n dependencyValues[dependencyNames[index]] = globalValues[index];\n continue;\n }\n const sourceContext = evaluation.sources[index + 1];\n if (sourceContext.kind !== 'collection')\n throw new TypeError(\n 'Dynamic keyed dependency resolved to a non-collection source.'\n );\n const selectedKey = dependency.key(value, key);\n assertSynchronous(selectedKey);\n if (selectedKey !== undefined && typeof selectedKey !== 'string')\n throw new TypeError('Dynamic keyed dependency keys must be strings or undefined.');\n bindKey(bindings[index]!, key, selectedKey);\n dependencyValues[dependencyNames[index]] =\n selectedKey === undefined ? undefined : sourceContext.read.get(selectedKey);\n }\n const next =\n dependencySpecs === undefined\n ? select(value, key as K)\n : select(value, key as K, Object.freeze(dependencyValues));\n assertSynchronous(next);\n output.output.set(key, next);\n };\n\n if (evaluation.reset) {\n clearBindings();\n const ids = driver.read.ids();\n for (const key of ids) project(key);\n output.output.order(ids);\n revisions = Object.freeze(currentRevisions);\n return;\n }\n\n const dirty = new Set<string>();\n let all = false;\n let updateOrder = false;\n const driverChanged = revisions[0] !== currentRevisions[0];\n if (driverChanged) {\n const change = driver.change;\n if (!change || change.kind === 'reset') {\n all = true;\n updateOrder = true;\n } else {\n for (const entry of change.removed) {\n output.output.remove(entry.key);\n unbindKey(bindingIndexes, entry.key);\n dirty.delete(entry.key);\n }\n for (const entry of change.added) dirty.add(entry.key);\n for (const entry of change.updated) dirty.add(entry.key);\n updateOrder = Boolean(change.added.length || change.removed.length || change.order);\n }\n }\n\n for (let index = 0; index < keyed.length; index++) {\n if (revisions[index + 1] === currentRevisions[index + 1]) continue;\n const dependency = keyed[index];\n if (!dependency) {\n all = true;\n continue;\n }\n const sourceContext = evaluation.sources[index + 1];\n if (sourceContext.kind !== 'collection' || !sourceContext.change) {\n all = true;\n continue;\n }\n if (sourceContext.change.kind === 'reset') {\n all = true;\n continue;\n }\n const reverse = bindings[index]!.reverse;\n for (const transition of sourceContext.change.added) {\n for (const outputKey of reverse.get(transition.key) ?? []) dirty.add(outputKey);\n }\n for (const transition of sourceContext.change.updated) {\n for (const outputKey of reverse.get(transition.key) ?? []) dirty.add(outputKey);\n }\n for (const transition of sourceContext.change.removed) {\n for (const outputKey of reverse.get(transition.key) ?? []) dirty.add(outputKey);\n }\n }\n\n if (all) for (const key of driver.read.ids()) dirty.add(key);\n for (const key of dirty) if (driver.read.has(key)) project(key);\n if (updateOrder) output.output.order(driver.read.ids());\n revisions = Object.freeze(currentRevisions);\n },\n release: () => {\n clearBindings();\n revisions = Object.freeze([]);\n },\n };\n },\n name: 'derive.keyed',\n });\n return projection as KeyedProjection<K, T>;\n}\n\nexport const derive = Object.assign(createValueDerive, { keyed: createKeyedDerive });\n","import type { CollectionChange } from '../contract';\n\ntype Added<K extends string, V> = { readonly key: K; readonly after: V };\ntype Updated<K extends string, V> = {\n readonly key: K;\n readonly before: V;\n readonly after: V;\n};\ntype Removed<K extends string, V> = { readonly key: K; readonly before: V };\n\nconst commonOrderChanged = <K extends string>(\n before: readonly K[],\n after: readonly K[],\n added: ReadonlySet<K>,\n removed: ReadonlySet<K>\n): boolean => {\n const beforeCommon = before.filter(key => !removed.has(key));\n const afterCommon = after.filter(key => !added.has(key));\n return beforeCommon.some((key, index) => afterCommon[index] !== key);\n};\n\n/** Builds the canonical incremental CollectionChange from already-known net transitions. */\nexport const createCollectionChange = <K extends string, V>(input: {\n readonly added: readonly Added<K, V>[];\n readonly updated: readonly Updated<K, V>[];\n readonly removed: readonly Removed<K, V>[];\n readonly beforeOrder: readonly K[];\n readonly afterOrder: readonly K[];\n}): CollectionChange<K, V> | undefined => {\n const addedKeys = new Set(input.added.map(entry => entry.key));\n const removedKeys = new Set(input.removed.map(entry => entry.key));\n const orderChanged =\n input.beforeOrder !== input.afterOrder &&\n commonOrderChanged(input.beforeOrder, input.afterOrder, addedKeys, removedKeys);\n if (!input.added.length && !input.updated.length && !input.removed.length && !orderChanged)\n return undefined;\n return Object.freeze({\n kind: 'incremental' as const,\n added: Object.freeze([...input.added]),\n updated: Object.freeze([...input.updated]),\n removed: Object.freeze([...input.removed]),\n ...(orderChanged\n ? {\n order: Object.freeze({\n before: Object.freeze([...input.beforeOrder]),\n after: Object.freeze([...input.afterOrder]),\n }),\n }\n : {}),\n });\n};\n\n/** Exact fallback diff between two published map-like snapshots. */\nexport const diffCollection = <K extends string, V>(\n previous: ReadonlyMap<K, V>,\n current: ReadonlyMap<K, V>,\n isEqual: (previous: V, next: V) => boolean = Object.is\n): CollectionChange<K, V> | undefined => {\n const added: Added<K, V>[] = [];\n const updated: Updated<K, V>[] = [];\n const removed: Removed<K, V>[] = [];\n for (const [key, before] of previous) {\n if (!current.has(key)) removed.push({ key, before });\n else {\n const after = current.get(key) as V;\n if (!isEqual(before, after)) updated.push({ key, before, after });\n }\n }\n for (const [key, after] of current) if (!previous.has(key)) added.push({ key, after });\n return createCollectionChange({\n added,\n updated,\n removed,\n beforeOrder: [...previous.keys()],\n afterOrder: [...current.keys()],\n });\n};\n\nexport const collectionChangedKeys = <K extends string, V>(\n change: CollectionChange<K, V>\n): ReadonlySet<K> =>\n change.kind === 'reset'\n ? new Set<K>()\n : new Set([\n ...change.added.map(entry => entry.key),\n ...change.updated.map(entry => entry.key),\n ...change.removed.map(entry => entry.key),\n ]);\n\nexport const collectionHasStructuralChange = <K extends string, V>(\n change: CollectionChange<K, V>\n): boolean =>\n change.kind === 'reset' || Boolean(change.added.length || change.removed.length || change.order);\n\nexport const collectionHasAnyChange = <K extends string, V>(\n change: CollectionChange<K, V>\n): boolean =>\n change.kind === 'reset' ||\n Boolean(change.added.length || change.updated.length || change.removed.length || change.order);\n","import { profile } from '../../profile';\n\ntype IndexNode<K extends string, V> = {\n readonly key: K;\n readonly value: V;\n readonly height: number;\n readonly left?: IndexNode<K, V>;\n readonly right?: IndexNode<K, V>;\n};\n\nconst height = <K extends string, V>(node: IndexNode<K, V> | undefined): number =>\n node?.height ?? 0;\n\nconst node = <K extends string, V>(\n key: K,\n value: V,\n left?: IndexNode<K, V>,\n right?: IndexNode<K, V>\n): IndexNode<K, V> => {\n profile.collectionIndex.node();\n return Object.freeze({\n key,\n value,\n left,\n right,\n height: Math.max(height(left), height(right)) + 1,\n });\n};\n\nconst rotateLeft = <K extends string, V>(current: IndexNode<K, V>): IndexNode<K, V> => {\n const right = current.right!;\n return node(\n right.key,\n right.value,\n node(current.key, current.value, current.left, right.left),\n right.right\n );\n};\n\nconst rotateRight = <K extends string, V>(current: IndexNode<K, V>): IndexNode<K, V> => {\n const left = current.left!;\n return node(\n left.key,\n left.value,\n left.left,\n node(current.key, current.value, left.right, current.right)\n );\n};\n\nconst rebalance = <K extends string, V>(current: IndexNode<K, V>): IndexNode<K, V> => {\n const balance = height(current.left) - height(current.right);\n if (balance > 1) {\n if (height(current.left!.left) < height(current.left!.right))\n return rotateRight(\n node(current.key, current.value, rotateLeft(current.left!), current.right)\n );\n return rotateRight(current);\n }\n if (balance < -1) {\n if (height(current.right!.right) < height(current.right!.left))\n return rotateLeft(\n node(current.key, current.value, current.left, rotateRight(current.right!))\n );\n return rotateLeft(current);\n }\n return current;\n};\n\nconst setNode = <K extends string, V>(\n current: IndexNode<K, V> | undefined,\n key: K,\n value: V\n): IndexNode<K, V> => {\n if (!current) return node(key, value);\n if (key === current.key) return node(key, value, current.left, current.right);\n if (key < current.key)\n return rebalance(\n node(current.key, current.value, setNode(current.left, key, value), current.right)\n );\n return rebalance(\n node(current.key, current.value, current.left, setNode(current.right, key, value))\n );\n};\n\nconst minNode = <K extends string, V>(current: IndexNode<K, V>): IndexNode<K, V> =>\n current.left ? minNode(current.left) : current;\n\nconst removeNode = <K extends string, V>(\n current: IndexNode<K, V> | undefined,\n key: K\n): IndexNode<K, V> | undefined => {\n if (!current) return undefined;\n if (key < current.key)\n return rebalance(\n node(current.key, current.value, removeNode(current.left, key), current.right)\n );\n if (key > current.key)\n return rebalance(\n node(current.key, current.value, current.left, removeNode(current.right, key))\n );\n if (!current.left) return current.right;\n if (!current.right) return current.left;\n const next = minNode(current.right);\n return rebalance(node(next.key, next.value, current.left, removeNode(current.right, next.key)));\n};\n\nconst fromSorted = <K extends string, V>(\n entries: readonly (readonly [K, V])[],\n start = 0,\n end = entries.length\n): IndexNode<K, V> | undefined => {\n if (start >= end) return undefined;\n const middle = (start + end) >> 1;\n const [key, value] = entries[middle];\n return node(key, value, fromSorted(entries, start, middle), fromSorted(entries, middle + 1, end));\n};\n\n/** Immutable keyed lookup used to keep published collection snapshots durable across revisions. */\nexport class PersistentKeyedIndex<K extends string, V> {\n private constructor(private readonly root?: IndexNode<K, V>) {}\n\n static empty<K extends string, V>(): PersistentKeyedIndex<K, V> {\n return new PersistentKeyedIndex<K, V>();\n }\n\n static from<K extends string, V>(entries: Iterable<readonly [K, V]>): PersistentKeyedIndex<K, V> {\n const sorted = [...entries].sort(([left], [right]) =>\n left < right ? -1 : left > right ? 1 : 0\n );\n profile.collectionIndex.build(sorted.length);\n return new PersistentKeyedIndex(fromSorted(sorted));\n }\n\n get(key: K): V | undefined {\n let current = this.root;\n while (current) {\n if (key === current.key) return current.value;\n current = key < current.key ? current.left : current.right;\n }\n return undefined;\n }\n\n has(key: K): boolean {\n let current = this.root;\n while (current) {\n if (key === current.key) return true;\n current = key < current.key ? current.left : current.right;\n }\n return false;\n }\n\n set(key: K, value: V): PersistentKeyedIndex<K, V> {\n return new PersistentKeyedIndex(setNode(this.root, key, value));\n }\n\n remove(key: K): PersistentKeyedIndex<K, V> {\n return new PersistentKeyedIndex(removeNode(this.root, key));\n }\n}\n","import { profile } from '../../profile';\nimport { createCollectionChange } from '../collection/change';\nimport { PersistentKeyedIndex } from '../collection/index';\nimport type {\n CollectionChange,\n CollectionContext,\n CollectionDraft,\n CollectionRead,\n} from '../contract';\nimport {\n assertScope,\n type OutputRecord,\n type ProcessorRecord,\n type ProducerRecord,\n} from '../graph/scheduler';\n\ntype Entry<V> = { readonly present: true; readonly value: V } | { readonly present: false };\n\ntype PublishedCollection<K extends string, V> = {\n get(key: K): V | undefined;\n has(key: K): boolean;\n keys(): IterableIterator<K>;\n size(): number;\n ids(): readonly K[];\n read(check: () => void): CollectionRead<K, V>;\n publish(staged: ReadonlyMap<K, Entry<V>>, ids: readonly K[], reset: boolean): void;\n release(): void;\n};\n\nconst createPublishedCollection = <K extends string, V>(): PublishedCollection<K, V> => {\n const values = new Map<K, V>();\n let ids: readonly K[] = Object.freeze([]);\n let index = PersistentKeyedIndex.empty<K, V>();\n\n return {\n get: key => values.get(key),\n has: key => values.has(key),\n keys: () => values.keys(),\n size: () => values.size,\n ids: () => ids,\n read: check => {\n const snapshotIndex = index;\n const snapshotIds = ids;\n return Object.freeze({\n get: key => {\n check();\n return snapshotIndex.get(key);\n },\n has: key => {\n check();\n return snapshotIndex.has(key);\n },\n ids: () => {\n check();\n return snapshotIds;\n },\n });\n },\n publish: (staged, nextIds, reset) => {\n if (reset) {\n const entries: [K, V][] = [];\n for (const [key, entry] of staged) if (entry.present) entries.push([key, entry.value]);\n index = PersistentKeyedIndex.from(entries);\n values.clear();\n } else {\n for (const [key, entry] of staged)\n index = entry.present ? index.set(key, entry.value) : index.remove(key);\n }\n for (const [key, entry] of staged) {\n if (entry.present) values.set(key, entry.value);\n else values.delete(key);\n }\n ids = nextIds;\n },\n release: () => {\n values.clear();\n ids = Object.freeze([]);\n index = PersistentKeyedIndex.empty<K, V>();\n },\n };\n};\n\nexport type CollectionOutputEvaluation<K extends string, V> = {\n readonly previous: CollectionRead<K, V>;\n readonly next: CollectionRead<K, V>;\n readonly output: CollectionDraft<K, V>;\n};\n\nexport type CollectionOutputState<K extends string, V> = Omit<\n OutputRecord,\n 'context' | 'current'\n> & {\n begin(active: () => boolean, initialize: boolean): CollectionOutputEvaluation<K, V>;\n seal(reset: boolean, isEqual: (previous: V, next: V) => boolean): boolean;\n context(active: () => boolean): CollectionContext<K, V>;\n current(): CollectionRead<K, V>;\n publish(): void;\n};\n\ntype CollectionOutputBinding = {\n owner(): ProducerRecord;\n check(): void;\n cause(): unknown;\n};\n\n/** Owns staged keyed intent, exact transitions and published collection state. */\nexport const createCollectionOutput = <K extends string, V>(\n binding: CollectionOutputBinding\n): CollectionOutputState<K, V> => {\n const published = createPublishedCollection<K, V>();\n let staged = new Map<K, Entry<V>>();\n let nextIds = published.ids();\n let change: CollectionChange<K, V> | undefined;\n let initialized = false;\n let reset = false;\n let revision = 0;\n let explicitOrder: readonly K[] | undefined;\n let cleared = false;\n const listeners = new Set<() => void>();\n const consumers = new Set<ProcessorRecord>();\n\n const hasNext = (key: K): boolean =>\n staged.has(key) ? staged.get(key)!.present : !cleared && published.has(key);\n\n const getNext = (key: K): V | undefined => {\n const entry = staged.get(key);\n return entry\n ? entry.present\n ? entry.value\n : undefined\n : cleared\n ? undefined\n : published.get(key);\n };\n\n const deriveIds = (): readonly K[] => {\n const result = cleared ? [] : published.ids().filter(hasNext);\n for (const [key, entry] of staged)\n if (entry.present && (cleared || !published.has(key))) result.push(key);\n return result;\n };\n\n const begin = (active: () => boolean, initialize: boolean): CollectionOutputEvaluation<K, V> => {\n staged = new Map();\n nextIds = published.ids();\n change = undefined;\n explicitOrder = undefined;\n cleared = initialize;\n reset = initialize;\n const read = (next: boolean): CollectionRead<K, V> => ({\n get: key => {\n assertScope(active);\n return next ? getNext(key) : published.get(key);\n },\n has: key => {\n assertScope(active);\n return next ? hasNext(key) : published.has(key);\n },\n ids: () => {\n assertScope(active);\n return next\n ? Object.freeze(explicitOrder ? [...explicitOrder] : [...deriveIds()])\n : published.ids();\n },\n });\n const output: CollectionDraft<K, V> = {\n set: (key, value) => {\n assertScope(active);\n if (typeof key !== 'string') throw new TypeError('Projection keys must be strings.');\n staged.set(key, { present: true, value });\n },\n remove: key => {\n assertScope(active);\n staged.set(key, { present: false });\n },\n order: order => {\n assertScope(active);\n explicitOrder = Object.freeze([...order]);\n },\n };\n return { previous: read(false), next: read(true), output };\n };\n\n const seal = (nextReset: boolean, isEqual: (previous: V, next: V) => boolean): boolean => {\n if (cleared)\n for (const key of published.keys()) if (!staged.has(key)) staged.set(key, { present: false });\n\n profile.projection('touchedKeys', staged.size);\n const added = new Set<K>();\n const removed = new Set<K>();\n const updated = new Set<K>();\n for (const [key, entry] of staged) {\n const existed = published.has(key);\n if (entry.present) {\n if (!existed) added.add(key);\n else if (!isEqual(published.get(key) as V, entry.value)) updated.add(key);\n else if (!nextReset) staged.delete(key);\n } else if (existed) removed.add(key);\n else staged.delete(key);\n }\n\n const ids = published.ids();\n if (explicitOrder || added.size || removed.size) {\n const order = explicitOrder ?? [...ids.filter(key => !removed.has(key)), ...added];\n const seen = new Set(order);\n if (\n seen.size !== order.length ||\n order.length !== published.size() + added.size - removed.size ||\n order.some(key => !hasNext(key))\n )\n throw new TypeError('Projection order must contain every key exactly once.');\n nextIds =\n ids.length === order.length && ids.every((key, index) => key === order[index])\n ? ids\n : Object.freeze([...order]);\n } else nextIds = ids;\n\n const changedKeys = new Set<K>();\n added.forEach(key => changedKeys.add(key));\n removed.forEach(key => changedKeys.add(key));\n updated.forEach(key => changedKeys.add(key));\n profile.projection('changedKeys', changedKeys.size);\n const addedEntries: { readonly key: K; readonly after: V }[] = [];\n const updatedEntries: { readonly key: K; readonly before: V; readonly after: V }[] = [];\n const removedEntries: { readonly key: K; readonly before: V }[] = [];\n for (const key of changedKeys) {\n const beforePresent = published.has(key);\n const afterPresent = hasNext(key);\n if (beforePresent === afterPresent) {\n if (!beforePresent) continue;\n if (isEqual !== Object.is && isEqual(published.get(key) as V, getNext(key) as V)) continue;\n }\n if (!beforePresent) addedEntries.push({ key, after: getNext(key) as V });\n else if (!afterPresent) removedEntries.push({ key, before: published.get(key) as V });\n else\n updatedEntries.push({\n key,\n before: published.get(key) as V,\n after: getNext(key) as V,\n });\n }\n\n change = nextReset\n ? Object.freeze({ kind: 'reset' as const })\n : createCollectionChange({\n added: addedEntries,\n updated: updatedEntries,\n removed: removedEntries,\n beforeOrder: ids,\n afterOrder: nextIds,\n });\n reset = nextReset;\n return change !== undefined;\n };\n\n const context = (active: () => boolean, cause: unknown): CollectionContext<K, V> =>\n Object.freeze({\n kind: 'collection' as const,\n read: {\n get: key => {\n assertScope(active);\n return getNext(key);\n },\n has: key => {\n assertScope(active);\n return hasNext(key);\n },\n ids: () => {\n assertScope(active);\n return nextIds;\n },\n },\n change,\n revision,\n reset,\n cause,\n });\n\n return {\n kind: 'collection',\n get owner() {\n return binding.owner();\n },\n begin,\n seal,\n context: active => context(active, binding.cause()),\n current: () => published.read(binding.check),\n revision: () => revision,\n reset: () => reset,\n publish: () => {\n if (change) published.publish(staged, nextIds, change.kind === 'reset');\n if (change && initialized) revision++;\n initialized = true;\n },\n emit: call => {\n Array.from(listeners).forEach(listener => call(listener));\n },\n hasConsumers: () => consumers.size > 0,\n forEachConsumer: run => consumers.forEach(run),\n attachConsumer: consumer => consumers.add(consumer),\n detachConsumer: consumer => consumers.delete(consumer),\n clear: () => {\n staged.clear();\n nextIds = published.ids();\n change = undefined;\n reset = false;\n explicitOrder = undefined;\n cleared = false;\n },\n release: () => {\n published.release();\n staged.clear();\n listeners.clear();\n consumers.clear();\n nextIds = Object.freeze([]);\n change = undefined;\n initialized = false;\n revision = 0;\n reset = false;\n explicitOrder = undefined;\n cleared = false;\n },\n subscribe: listener => {\n binding.check();\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n };\n};\n","import { profile } from '../../profile';\nimport type { ValueContext } from '../contract';\nimport {\n assertScope,\n type OutputRecord,\n type ProcessorRecord,\n type ProducerRecord,\n} from '../graph/scheduler';\n\nconst unset = Symbol('projection-value-unset');\n\nexport type ValueOutputEvaluation<T> = {\n readonly previous: T | undefined;\n readonly next: () => T | undefined;\n readonly output: { set(value: T): void };\n};\n\nexport type ValueOutputState<T> = OutputRecord & {\n begin(active: () => boolean, initialize: boolean): ValueOutputEvaluation<T>;\n seal(reset: boolean, isEqual: (previous: T, next: T) => boolean): boolean;\n publish(): void;\n};\n\ntype ValueOutputBinding = {\n owner(): ProducerRecord;\n check(): void;\n cause(): unknown;\n};\n\n/** Owns staged and published state for one scalar Projection output. */\nexport const createValueOutput = <T>(binding: ValueOutputBinding): ValueOutputState<T> => {\n let value!: T;\n let staged: T | typeof unset = unset;\n let next!: T;\n let initialized = false;\n let revision = 0;\n let changed = false;\n let reset = false;\n const listeners = new Set<() => void>();\n const consumers = new Set<ProcessorRecord>();\n\n const begin = (active: () => boolean, initialize: boolean): ValueOutputEvaluation<T> => {\n staged = unset;\n next = value;\n changed = false;\n reset = initialize;\n return {\n previous: initialized ? value : undefined,\n next: () => {\n assertScope(active);\n if (staged !== unset) return staged;\n return initialize ? undefined : initialized ? value : undefined;\n },\n output: Object.freeze({\n set: (candidate: T) => {\n assertScope(active);\n staged = candidate;\n },\n }),\n };\n };\n\n const seal = (nextReset: boolean, isEqual: (previous: T, next: T) => boolean): boolean => {\n if (reset && staged === unset)\n throw new TypeError('Value output must be initialized on reset.');\n if (staged === unset) {\n reset = nextReset;\n changed = false;\n next = value;\n return false;\n }\n const candidate = staged;\n changed = !initialized || !isEqual(value, candidate);\n next = changed ? candidate : value;\n reset = nextReset;\n return changed;\n };\n\n return {\n kind: 'value',\n get owner() {\n return binding.owner();\n },\n begin,\n seal,\n context: active => {\n assertScope(active);\n return Object.freeze({\n kind: 'value' as const,\n value: next,\n revision,\n reset,\n cause: binding.cause(),\n });\n },\n current: () => {\n binding.check();\n return value;\n },\n revision: () => revision,\n reset: () => reset,\n publish: () => {\n if (changed && initialized) revision++;\n if (changed) value = next;\n initialized = true;\n },\n emit: call => {\n profile.materialized.notification();\n Array.from(listeners).forEach(listener => call(listener));\n },\n hasConsumers: () => consumers.size > 0,\n forEachConsumer: run => consumers.forEach(run),\n attachConsumer: consumer => consumers.add(consumer),\n detachConsumer: consumer => consumers.delete(consumer),\n clear: () => {\n staged = unset;\n next = value;\n changed = false;\n reset = false;\n },\n release: () => {\n listeners.clear();\n consumers.clear();\n staged = unset;\n value = next = undefined as T;\n initialized = false;\n revision = 0;\n changed = false;\n reset = false;\n },\n subscribe: listener => {\n binding.check();\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n };\n};\n","import { profile } from '../../profile';\nimport { createCollectionOutput, type CollectionOutputState } from '../output/collection';\nimport { ProjectionDisposedError } from '../contract';\nimport type {\n CollectionOutputEvaluation,\n OutputDefinition,\n OutputEvaluation,\n ProcessorDefinition,\n ProcessorInstance,\n ValueOutputEvaluation,\n} from '../definition';\nimport {\n assertSynchronous,\n type OutputRecord,\n type ProcessorRecord,\n type Scheduler,\n} from './scheduler';\nimport { createValueOutput, type ValueOutputState } from '../output/value';\n\ntype BoundOutput =\n | {\n readonly kind: 'value';\n readonly definition: Extract<OutputDefinition, { readonly kind: 'value' }>;\n readonly state: ValueOutputState<unknown>;\n }\n | {\n readonly kind: 'collection';\n readonly definition: Extract<OutputDefinition, { readonly kind: 'collection' }>;\n readonly state: CollectionOutputState<string, unknown>;\n };\n\n/** Materializes every derive/incremental/group definition through one processor lifecycle. */\nexport const createProcessor = (\n scheduler: Scheduler,\n definition: ProcessorDefinition,\n dependencies: readonly OutputRecord[]\n): ProcessorRecord => {\n scheduler.assertIdle();\n let processor!: ProcessorRecord;\n let instance: ProcessorInstance | undefined;\n let cause: unknown;\n\n const check = () => {\n if (!scheduler.active || processor.disposed) throw new ProjectionDisposedError();\n if (processor.fault) throw processor.fault;\n };\n\n const bound: readonly BoundOutput[] = definition.outputs.map(outputDefinition => {\n if (outputDefinition.kind === 'value') {\n const state = createValueOutput<unknown>({\n owner: () => processor,\n check,\n cause: () => cause,\n });\n return { kind: 'value', definition: outputDefinition, state };\n }\n const state = createCollectionOutput<string, unknown>({\n owner: () => processor,\n check,\n cause: () => cause,\n });\n return { kind: 'collection', definition: outputDefinition, state };\n });\n\n const begin = (active: () => boolean, initialize: boolean): readonly OutputEvaluation[] =>\n Object.freeze(\n bound.map(entry => {\n if (entry.kind === 'value') {\n const evaluation = entry.state.begin(active, initialize);\n return Object.freeze({ kind: 'value' as const, ...evaluation }) as ValueOutputEvaluation;\n }\n const evaluation = entry.state.begin(active, initialize);\n return Object.freeze({\n kind: 'collection' as const,\n ...evaluation,\n }) as CollectionOutputEvaluation;\n })\n );\n\n const seal = (reset: boolean): readonly OutputRecord[] => {\n const changed: OutputRecord[] = [];\n for (const entry of bound) {\n const didChange = entry.state.seal(reset, entry.definition.equality);\n if (didChange) changed.push(entry.state);\n }\n return Object.freeze(changed);\n };\n\n const run = (reset: boolean, runCause: unknown, recreate = false): readonly OutputRecord[] => {\n cause = runCause;\n let active = true;\n try {\n const scopeActive = () => active;\n const sources = Object.freeze(dependencies.map(output => output.context(scopeActive)));\n const outputs = begin(scopeActive, reset);\n if (recreate && instance) {\n instance.release?.();\n instance = undefined;\n }\n if (!instance) instance = definition.create();\n profile.materialized[reset ? 'rebuilt' : 'updated']();\n const result = instance.evaluate({ reset, cause: runCause, sources, outputs });\n assertSynchronous(result);\n return seal(reset);\n } finally {\n active = false;\n }\n };\n\n const order = scheduler.order();\n processor = {\n kind: 'processor',\n order,\n name: definition.name ? `${definition.name} (${order})` : `projection-${order}`,\n dependencies: Object.freeze([...dependencies]),\n outputs: Object.freeze(bound.map(entry => entry.state)),\n fault: undefined,\n disposed: false,\n evaluate: run,\n publish: () => bound.forEach(entry => entry.state.publish()),\n clear: () => {\n bound.forEach(entry => entry.state.clear());\n cause = undefined;\n },\n release: () => {\n const current = instance;\n instance = undefined;\n const failures: unknown[] = [];\n try {\n current?.release?.();\n } catch (error) {\n failures.push(error);\n }\n for (const entry of bound) {\n try {\n entry.state.release();\n } catch (error) {\n failures.push(error);\n }\n }\n cause = undefined;\n if (failures.length) throw failures[0];\n },\n };\n\n try {\n scheduler.initialize(() => {\n const invalid = dependencies.find(output => output.owner.fault || output.owner.disposed);\n if (invalid) throw invalid.owner.fault ?? new ProjectionDisposedError();\n const changed = processor.evaluate(true, undefined);\n if (changed.length) processor.publish();\n processor.clear();\n });\n scheduler.addProcessor(processor);\n } catch (error) {\n processor.disposed = true;\n try {\n processor.release();\n } catch {\n /* Initialization failure retains priority. */\n }\n throw error;\n }\n return processor;\n};\n","import type { Unsubscribe } from '../../runtime/contract';\nimport {\n collectionChangedKeys,\n collectionHasAnyChange,\n collectionHasStructuralChange,\n diffCollection,\n} from '../collection/change';\nimport type { CollectionChange } from '../contract';\nimport type { Readable } from '../../readable';\n\nexport type ProjectionReadableSource<T> = {\n readonly kind: 'value' | 'collection';\n current(): T;\n revision(): number;\n subscribe(listener: (change?: CollectionChange<string, unknown>) => void): Unsubscribe;\n};\n\ntype SelectionTracker = {\n readonly keys: Set<string>;\n all: boolean;\n structure: boolean;\n};\n\ntype Selection = {\n readonly keys: ReadonlySet<string>;\n readonly all: boolean;\n readonly structure: boolean;\n};\n\nlet activeTracker: SelectionTracker | undefined;\n\nconst trackKey = (key: string): void => {\n activeTracker?.keys.add(key);\n};\n\nconst trackStructure = (): void => {\n if (activeTracker) activeTracker.structure = true;\n};\n\nconst trackAll = (): void => {\n if (activeTracker) activeTracker.all = true;\n};\n\nexport const isMapLike = (value: unknown): value is ReadonlyMap<string, unknown> =>\n value instanceof Map ||\n (value !== null &&\n typeof value === 'object' &&\n typeof (value as { get?: unknown }).get === 'function' &&\n typeof (value as { keys?: unknown }).keys === 'function' &&\n typeof (value as { entries?: unknown }).entries === 'function');\n\nconst trackedMap = <K extends string, V>(source: ReadonlyMap<K, V>): ReadonlyMap<K, V> => {\n const view: ReadonlyMap<K, V> = {\n get: key => {\n trackKey(key);\n return source.get(key);\n },\n has: key => {\n trackKey(key);\n return source.has(key);\n },\n get size() {\n trackStructure();\n return source.size;\n },\n keys: () => {\n trackStructure();\n return source.keys();\n },\n values: () => {\n trackAll();\n return source.values();\n },\n entries: () => {\n trackAll();\n return source.entries();\n },\n forEach: (callback, thisArg) => {\n trackAll();\n source.forEach((value, key) => callback.call(thisArg, value, key, view));\n },\n [Symbol.iterator]: () => {\n trackAll();\n return source[Symbol.iterator]();\n },\n };\n return Object.freeze(view);\n};\n\nconst selectionAffects = (\n selection: Selection,\n change: CollectionChange<string, unknown> | undefined\n): boolean => {\n if (!change || change.kind === 'reset') return true;\n if (selection.all && collectionHasAnyChange(change)) return true;\n if (selection.structure && collectionHasStructuralChange(change)) return true;\n const changedKeys = collectionChangedKeys(change);\n for (const key of selection.keys) if (changedKeys.has(key)) return true;\n return false;\n};\n\nexport const createDirectReadable = <T>(source: ProjectionReadableSource<T>): Readable<T> =>\n Object.freeze({\n current: source.current,\n revision: source.revision,\n subscribe: (listener: () => void) => source.subscribe(() => listener()),\n });\n\n/** Consumer-side selector tracking; it never mutates processor dependencies. */\nexport const createSelectorReadable = <T, R>(\n source: ProjectionReadableSource<T>,\n selector: (value: T) => R,\n equality: (previous: R, next: R) => boolean = Object.is\n): Readable<R> => {\n let initialized = false;\n let value!: R;\n let selectedRevision = 0;\n let sourceRevision = -1;\n let selection: Selection = Object.freeze({\n keys: new Set<string>(),\n all: true,\n structure: false,\n });\n let previousCollection: ReadonlyMap<string, unknown> | undefined;\n let unsubscribeSource: Unsubscribe | undefined;\n const listeners = new Set<() => void>();\n\n const updateCollectionSnapshot = (current?: T) => {\n const candidate = current ?? source.current();\n previousCollection = isMapLike(candidate) ? candidate : undefined;\n };\n\n const evaluate = (): boolean => {\n const tracker: SelectionTracker = { keys: new Set(), all: false, structure: false };\n const previousTracker = activeTracker;\n activeTracker = tracker;\n let current!: T;\n let next!: R;\n try {\n current = source.current();\n const selectedSource = isMapLike(current) ? (trackedMap(current) as unknown as T) : current;\n next = selector(selectedSource);\n } finally {\n activeTracker = previousTracker;\n }\n const nextSelection: Selection = Object.freeze({\n keys: new Set(tracker.keys),\n all: tracker.all || (isMapLike(current) && tracker.keys.size === 0 && !tracker.structure),\n structure: tracker.structure,\n });\n const changed = !initialized || !equality(value, next);\n if (changed) {\n if (initialized) selectedRevision++;\n value = next;\n }\n selection = nextSelection;\n initialized = true;\n sourceRevision = source.revision();\n updateCollectionSnapshot(current);\n return changed;\n };\n\n const ensureCurrent = (): R => {\n const revision = source.revision();\n if (!initialized || (!unsubscribeSource && sourceRevision !== revision)) evaluate();\n return value;\n };\n\n const onProjectionChange = (incoming?: CollectionChange<string, unknown>) => {\n let change = incoming;\n if (!change && previousCollection) {\n const current = source.current();\n if (isMapLike(current)) {\n change = diffCollection(previousCollection, current);\n previousCollection = current;\n if (!change) {\n sourceRevision = source.revision();\n return;\n }\n } else previousCollection = undefined;\n }\n if (!selectionAffects(selection, change)) {\n sourceRevision = source.revision();\n updateCollectionSnapshot();\n return;\n }\n if (evaluate()) Array.from(listeners).forEach(listener => listener());\n };\n\n const installSource = () => {\n if (!unsubscribeSource) unsubscribeSource = source.subscribe(onProjectionChange);\n };\n\n return Object.freeze({\n current: ensureCurrent,\n revision: () => {\n ensureCurrent();\n return selectedRevision;\n },\n subscribe: (listener: () => void) => {\n ensureCurrent();\n listeners.add(listener);\n installSource();\n return () => {\n listeners.delete(listener);\n if (!listeners.size && unsubscribeSource) {\n unsubscribeSource();\n unsubscribeSource = undefined;\n }\n };\n },\n });\n};\n","import * as sequence from '../../order/sequence';\nimport { profile } from '../../profile';\nimport type { DocumentNode, DocumentTreeNode } from '../../schema/model';\nimport { compiledShape } from '../../schema/layout';\nimport * as schemaValue from '../../schema/value';\nimport { installOwn, isRecord } from '../../value/record';\nimport type { DocumentDirty } from './dirty';\n\nconst hasDocumentDirty = (dirty: DocumentDirty): boolean =>\n dirty.replace ||\n dirty.order ||\n dirty.treeRoot ||\n dirty.treeNodes.size > 0 ||\n dirty.children.size > 0;\n\nconst equivalent = (node: DocumentNode, left: unknown, right: unknown): boolean =>\n node.kind === 'field' ? Object.is(left, right) : schemaValue.equalValue(node, left, right);\n\nconst replaceValue = (node: DocumentNode, previous: unknown, current: unknown): unknown =>\n equivalent(node, previous, current) ? previous : schemaValue.copyValue(node, current);\n\nconst cloneRecord = (value: Record<string, unknown>): Record<string, unknown> => {\n profile.copy.shallowRecord(Object.getOwnPropertyNames(value).length);\n return Object.create(\n Object.getPrototypeOf(value),\n Object.getOwnPropertyDescriptors(value)\n ) as Record<string, unknown>;\n};\n\nconst materializeRecordChild = (\n node: DocumentNode,\n previous: Record<string, unknown>,\n current: Record<string, unknown>,\n key: string,\n dirty: DocumentDirty\n):\n | { readonly changed: false }\n | { readonly changed: true; readonly present: boolean; readonly value: unknown } => {\n const before = Object.hasOwn(previous, key);\n const after = Object.hasOwn(current, key);\n if (!before && !after) return { changed: false };\n if (!after) return { changed: true, present: false, value: undefined };\n const next = before\n ? materializeDocumentValue(node, previous[key], current[key], dirty)\n : schemaValue.copyValue(node, current[key]);\n if (before && next === previous[key]) return { changed: false };\n return { changed: true, present: true, value: next };\n};\n\nconst materializeObject = (\n node: Extract<DocumentNode, { kind: 'object' | 'variant' }>,\n previous: Record<string, unknown>,\n current: Record<string, unknown>,\n dirty: DocumentDirty\n): unknown => {\n if (node.kind === 'variant' && previous[node.tag] !== current[node.tag])\n return replaceValue(node, previous, current);\n const layout = compiledShape(node, current);\n if (!layout) return replaceValue(node, previous, current);\n let result: Record<string, unknown> | undefined;\n for (const [key, childDirty] of dirty.children) {\n const member = layout.members.get(key);\n if (!member) return replaceValue(node, previous, current);\n const child = materializeRecordChild(member.node, previous, current, key, childDirty);\n if (!child.changed) continue;\n result ??= cloneRecord(previous);\n installOwn(result, key, child.present, child.value);\n }\n return result ?? previous;\n};\n\nconst materializeMap = (\n node: Extract<DocumentNode, { kind: 'map' }>,\n previous: Record<string, unknown>,\n current: Record<string, unknown>,\n dirty: DocumentDirty\n): unknown => {\n let result: Record<string, unknown> | undefined;\n for (const [key, childDirty] of dirty.children) {\n const child = materializeRecordChild(node.value, previous, current, key, childDirty);\n if (!child.changed) continue;\n result ??= cloneRecord(previous);\n installOwn(result, key, child.present, child.value);\n }\n return result ?? previous;\n};\n\nconst materializeTable = (\n node: Extract<DocumentNode, { kind: 'table' }>,\n previous: Record<string, unknown>,\n current: Record<string, unknown>,\n dirty: DocumentDirty\n): unknown => {\n if (!isRecord(previous.byId) || !isRecord(current.byId))\n return replaceValue(node, previous, current);\n const beforeById = previous.byId;\n const afterById = current.byId;\n let result: Record<string, unknown> | undefined;\n let nextById: Record<string, unknown> | undefined;\n for (const [key, childDirty] of dirty.children) {\n const child = materializeRecordChild(node.value, beforeById, afterById, key, childDirty);\n if (!child.changed) continue;\n nextById ??= cloneRecord(beforeById);\n installOwn(nextById, key, child.present, child.value);\n }\n if (nextById) {\n result = cloneRecord(previous);\n installOwn(result, 'byId', true, nextById);\n }\n if (dirty.order) {\n const beforeIds = previous.ids;\n const afterIds = current.ids;\n if (!Array.isArray(beforeIds) || !Array.isArray(afterIds))\n return replaceValue(node, previous, current);\n if (!sequence.equal(beforeIds as string[], afterIds as string[])) {\n result ??= cloneRecord(previous);\n installOwn(result, 'ids', true, [...(afterIds as string[])]);\n }\n }\n return result ?? previous;\n};\n\nconst materializeList = (\n node: Extract<DocumentNode, { kind: 'list' }>,\n previous: readonly unknown[],\n current: readonly unknown[],\n dirty: DocumentDirty\n): unknown => {\n if (dirty.order) {\n const before = sequence.listSequence(previous, node.keyOf);\n const after = sequence.listSequence(current, node.keyOf);\n const sameOrder = sequence.equal(before.order, after.order);\n let changed = !sameOrder;\n const result = new Array<unknown>(after.order.length);\n for (let index = 0; index < after.order.length; index++) {\n const key = after.order[index];\n const currentValue = after.values.get(key);\n if (!before.values.has(key)) {\n changed = true;\n result[index] = currentValue;\n continue;\n }\n const previousValue = before.values.get(key);\n const childDirty = dirty.children.get(key);\n const next = childDirty\n ? materializeDocumentValue(node.value, previousValue, currentValue, childDirty)\n : previousValue;\n changed ||= next !== previousValue;\n result[index] = next;\n }\n return changed ? result : previous;\n }\n\n let result: unknown[] | undefined;\n const before = sequence.indexedKeys(previous, node.keyOf);\n const after = sequence.indexedKeys(current, node.keyOf);\n for (const [key, childDirty] of dirty.children) {\n const previousIndex = before.index(key);\n const currentIndex = after.index(key);\n if (previousIndex < 0 || currentIndex < 0) return replaceValue(node, previous, current);\n const next = materializeDocumentValue(\n node.value,\n previous[previousIndex],\n current[currentIndex],\n childDirty\n );\n if (next === previous[previousIndex] && previousIndex === currentIndex) continue;\n result ??= [...previous];\n result[currentIndex] = next;\n }\n return result ?? previous;\n};\n\nconst materializeTree = (\n node: Extract<DocumentNode, { kind: 'tree' }>,\n previous: Record<string, unknown>,\n current: Record<string, unknown>,\n dirty: DocumentDirty\n): unknown => {\n if (!isRecord(previous.nodes) || !isRecord(current.nodes))\n return replaceValue(node, previous, current);\n let result: Record<string, unknown> | undefined;\n\n if (dirty.treeRoot) {\n const beforePresent = Object.hasOwn(previous, 'rootId');\n const afterPresent = Object.hasOwn(current, 'rootId');\n if (beforePresent !== afterPresent || !Object.is(previous.rootId, current.rootId)) {\n result = cloneRecord(previous);\n installOwn(result, 'rootId', afterPresent, current.rootId);\n }\n }\n\n let nodes: Record<string, unknown> | undefined;\n for (const id of dirty.treeNodes) {\n const beforePresent = Object.hasOwn(previous.nodes, id);\n const afterPresent = Object.hasOwn(current.nodes, id);\n const before = beforePresent\n ? (previous.nodes[id] as DocumentTreeNode<unknown, false> | DocumentTreeNode<unknown, true>)\n : undefined;\n const after = afterPresent\n ? (current.nodes[id] as DocumentTreeNode<unknown, false> | DocumentTreeNode<unknown, true>)\n : undefined;\n if (beforePresent === afterPresent && schemaValue.equalTreeNode(before, after)) continue;\n nodes ??= cloneRecord(previous.nodes);\n installOwn(nodes, id, afterPresent, after && schemaValue.copyTreeNode(after));\n }\n if (nodes) {\n result ??= cloneRecord(previous);\n installOwn(result, 'nodes', true, nodes);\n }\n return result ?? previous;\n};\n\nexport const materializeDocumentValue = (\n node: DocumentNode,\n previous: unknown,\n current: unknown,\n dirty: DocumentDirty\n): unknown => {\n if (!hasDocumentDirty(dirty)) return previous;\n if (dirty.replace || previous === undefined || current === undefined || node.kind === 'field')\n return replaceValue(node, previous, current);\n if (node.kind === 'object' || node.kind === 'variant') {\n if (!isRecord(previous) || !isRecord(current)) return replaceValue(node, previous, current);\n return materializeObject(node, previous, current, dirty);\n }\n if (node.kind === 'map') {\n if (!isRecord(previous) || !isRecord(current)) return replaceValue(node, previous, current);\n return materializeMap(node, previous, current, dirty);\n }\n if (node.kind === 'table') {\n if (!isRecord(previous) || !isRecord(current)) return replaceValue(node, previous, current);\n return materializeTable(node, previous, current, dirty);\n }\n if (node.kind === 'list') {\n if (!Array.isArray(previous) || !Array.isArray(current))\n return replaceValue(node, previous, current);\n return materializeList(node, previous, current, dirty);\n }\n if (!isRecord(previous) || !isRecord(current)) return replaceValue(node, previous, current);\n return materializeTree(node, previous, current, dirty);\n};\n","import * as relation from '../../address/relation';\nimport type { ChangeSet } from '../../changes';\nimport type { CollectionSelector, ValueSelector } from '../../schema/path';\n\nexport type DocumentDirty = {\n replace: boolean;\n order: boolean;\n treeRoot: boolean;\n readonly treeNodes: Set<string>;\n readonly children: Map<string, DocumentDirty>;\n};\n\nexport const createDocumentDirty = (): DocumentDirty => ({\n replace: false,\n order: false,\n treeRoot: false,\n treeNodes: new Set(),\n children: new Map(),\n});\n\nexport const clearDocumentDirty = (dirty: DocumentDirty): void => {\n dirty.replace = false;\n dirty.order = false;\n dirty.treeRoot = false;\n dirty.treeNodes.clear();\n dirty.children.clear();\n};\n\nconst locate = (dirty: DocumentDirty, path: readonly string[]): DocumentDirty | undefined => {\n let current = dirty;\n for (const key of path) {\n if (current.replace) return undefined;\n let child = current.children.get(key);\n if (!child) {\n child = createDocumentDirty();\n current.children.set(key, child);\n }\n current = child;\n }\n return current;\n};\n\nexport const markDocumentReplace = (dirty: DocumentDirty, path: readonly string[]): void => {\n const current = locate(dirty, path);\n if (!current) return;\n current.replace = true;\n current.order = false;\n current.treeRoot = false;\n current.treeNodes.clear();\n current.children.clear();\n};\n\nconst markDocumentOrder = (dirty: DocumentDirty, path: readonly string[]): void => {\n const current = locate(dirty, path);\n if (current && !current.replace) current.order = true;\n};\n\nconst markDocumentTree = (\n dirty: DocumentDirty,\n path: readonly string[],\n root: boolean,\n nodes: Iterable<string>\n): void => {\n const current = locate(dirty, path);\n if (!current || current.replace) return;\n current.treeRoot ||= root;\n for (const id of nodes) current.treeNodes.add(id);\n};\n\ntype DocumentCollectionPending = {\n reset: boolean;\n order: boolean;\n readonly entries: Map<string, DocumentDirty>;\n};\n\nexport const createCollectionPending = (): DocumentCollectionPending => ({\n reset: false,\n order: false,\n entries: new Map(),\n});\n\nexport const resetCollectionPending = (pending: DocumentCollectionPending): void => {\n pending.reset = true;\n pending.order = false;\n pending.entries.clear();\n};\n\nexport const clearCollectionPending = (pending: DocumentCollectionPending): void => {\n pending.reset = false;\n pending.order = false;\n pending.entries.clear();\n};\n\nconst dirtyEntry = (pending: DocumentCollectionPending, key: string): DocumentDirty => {\n let dirty = pending.entries.get(key);\n if (!dirty) {\n dirty = createDocumentDirty();\n pending.entries.set(key, dirty);\n }\n return dirty;\n};\n\nexport const mergeValueChanges = (\n selector: ValueSelector,\n dirty: DocumentDirty,\n changes: ChangeSet\n): void => {\n if (selector.tree) return;\n const at = selector.address;\n for (const change of changes.changes) {\n if (change.kind === 'reset') {\n markDocumentReplace(dirty, []);\n return;\n }\n if (change.kind === 'members') {\n for (const member of change.members) {\n const changed = [...change.at, member.key];\n if (relation.contains(changed, at)) markDocumentReplace(dirty, []);\n else if (relation.contains(at, changed))\n markDocumentReplace(dirty, changed.slice(at.length));\n }\n if (change.order && relation.contains(at, change.at))\n markDocumentOrder(dirty, change.at.slice(at.length));\n continue;\n }\n if (relation.contains(at, change.at))\n markDocumentTree(\n dirty,\n change.at.slice(at.length),\n change.before !== change.after,\n change.nodes.map(node => node.id)\n );\n }\n};\n\nexport const mergeCollectionChanges = (\n selector: CollectionSelector,\n pending: DocumentCollectionPending,\n changes: ChangeSet\n): void => {\n if (pending.reset) return;\n const at = selector.address;\n for (const change of changes.changes) {\n if (change.kind === 'reset') {\n resetCollectionPending(pending);\n return;\n }\n\n if (selector.tree?.kind === 'nodes') {\n if (change.kind === 'members') {\n for (const member of change.members) {\n const changed = [...change.at, member.key];\n if (relation.contains(changed, at)) {\n resetCollectionPending(pending);\n return;\n }\n }\n } else if (change.at.length === at.length && relation.contains(change.at, at)) {\n for (const node of change.nodes) {\n markDocumentReplace(dirtyEntry(pending, node.id), []);\n pending.order ||= node.kind !== 'updated';\n }\n } else if (relation.contains(change.at, at)) {\n resetCollectionPending(pending);\n return;\n }\n continue;\n }\n\n if (change.kind === 'members') {\n for (const member of change.members) {\n const changed = [...change.at, member.key];\n if (relation.contains(changed, at)) {\n resetCollectionPending(pending);\n return;\n }\n if (!relation.contains(at, changed)) continue;\n const relative = changed.slice(at.length);\n if (!relative.length) {\n resetCollectionPending(pending);\n return;\n }\n const entry = dirtyEntry(pending, relative[0]);\n markDocumentReplace(entry, relative.slice(1));\n if (relative.length === 1 && member.kind !== 'updated') pending.order = true;\n }\n if (change.order && relation.contains(at, change.at)) {\n const relative = change.at.slice(at.length);\n if (!relative.length) pending.order = true;\n else markDocumentOrder(dirtyEntry(pending, relative[0]), relative.slice(1));\n }\n continue;\n }\n\n if (!relation.contains(at, change.at)) continue;\n const relative = change.at.slice(at.length);\n if (!relative.length) {\n resetCollectionPending(pending);\n return;\n }\n markDocumentTree(\n dirtyEntry(pending, relative[0]),\n relative.slice(1),\n change.before !== change.after,\n change.nodes.map(node => node.id)\n );\n }\n};\n","import { profile } from '../../profile';\nimport type { Unsubscribe } from '../../runtime/contract';\nimport { createCollectionOutput, type CollectionOutputState } from '../output/collection';\nimport type { CollectionRead } from '../contract';\nimport { ProjectionDisposedError, ProjectionError } from '../contract';\nimport type { OutputRecord, Scheduler, SourceBoundaryRecord } from '../graph/scheduler';\nimport { createValueOutput, type ValueOutputState } from '../output/value';\nimport type { CollectionInputDraft } from '../definition';\n\nexport type SourceWrite =\n | { readonly kind: 'value'; set(value: unknown): void }\n | {\n readonly kind: 'collection';\n update(run: (draft: CollectionInputDraft<string, unknown>) => void): void;\n };\n\nexport type SourceMaterialization = {\n readonly producer: SourceBoundaryRecord;\n readonly output: OutputRecord;\n readonly write?: SourceWrite;\n};\n\nexport type SourceMark = { readonly reset?: boolean; readonly cause?: unknown };\ntype CollectionMark = SourceMark & {\n readonly candidates?: Iterable<string>;\n readonly fullScan?: boolean;\n readonly orderMayChange?: boolean;\n};\n\nexport type ValueBoundary = SourceMaterialization & {\n readonly mark: (metadata?: SourceMark) => void;\n readonly fail: (cause: unknown) => void;\n readonly detach: (cleanup: Unsubscribe) => void;\n};\n\nexport type CollectionBoundary = SourceMaterialization & {\n readonly mark: (metadata?: CollectionMark) => void;\n readonly fail: (cause: unknown) => void;\n readonly detach: (cleanup: Unsubscribe) => void;\n};\n\nconst sourceError = (cause: unknown): ProjectionError => new ProjectionError('source', cause);\n\nexport const createValueBoundary = (\n scheduler: Scheduler,\n name: string,\n initial: unknown,\n equality: (previous: unknown, next: unknown) => boolean,\n prepare: (previous: unknown) => unknown,\n clearSource: (failed: boolean) => void\n): ValueBoundary => {\n let boundary!: SourceBoundaryRecord;\n let pendingReset = false;\n let pendingCause: unknown;\n let contextCause: unknown;\n let recovering = false;\n let cleanup: Unsubscribe | undefined;\n\n const check = () => {\n if (!scheduler.active || boundary.disposed) throw new ProjectionDisposedError();\n if (boundary.fault) throw boundary.fault;\n };\n const state: ValueOutputState<unknown> = createValueOutput({\n owner: () => boundary,\n check,\n cause: () => contextCause,\n });\n const output: OutputRecord = state;\n\n boundary = {\n kind: 'source',\n name,\n outputs: Object.freeze([output]) as readonly [OutputRecord],\n fault: undefined,\n disposed: false,\n pendingCause: () => pendingCause,\n recovering: () => recovering,\n prepare: cause => {\n contextCause = cause;\n let active = true;\n try {\n const evaluation = state.begin(() => active, pendingReset);\n evaluation.output.set(prepare(evaluation.previous));\n const changed = state.seal(pendingReset, equality);\n recovering = false;\n return { changed, force: pendingReset };\n } finally {\n active = false;\n }\n },\n publish: state.publish,\n clear: () => {\n const failed = boundary.fault !== undefined;\n state.clear();\n pendingReset = false;\n pendingCause = undefined;\n contextCause = undefined;\n recovering = false;\n clearSource(failed);\n },\n release: () => {\n const detach = cleanup;\n cleanup = undefined;\n const failures: unknown[] = [];\n try {\n detach?.();\n } catch (error) {\n failures.push(error);\n }\n try {\n state.release();\n } catch (error) {\n failures.push(error);\n }\n if (failures.length) throw failures[0];\n },\n };\n\n try {\n scheduler.initialize(() => {\n let active = true;\n try {\n const evaluation = state.begin(() => active, true);\n evaluation.output.set(initial);\n state.seal(true, equality);\n state.publish();\n state.clear();\n } finally {\n active = false;\n }\n });\n scheduler.addSource(boundary);\n } catch (error) {\n boundary.disposed = true;\n try {\n boundary.release();\n } catch {\n /* Initialization failure retains priority. */\n }\n throw error;\n }\n\n const mark = (metadata: SourceMark = {}) => {\n scheduler.assertIdle();\n pendingReset ||= metadata.reset ?? false;\n if (metadata.cause !== undefined) pendingCause ??= metadata.cause;\n if (boundary.fault) recovering = true;\n scheduler.capture(boundary);\n };\n const fail = (cause: unknown) => {\n boundary.fault = sourceError(cause);\n recovering = false;\n scheduler.capture(boundary);\n };\n return {\n producer: boundary,\n output,\n mark,\n fail,\n detach: next => {\n cleanup = next;\n },\n };\n};\n\ntype CollectionStageOptions<K extends string, V> = {\n readonly reset: boolean;\n readonly candidates?: Iterable<K>;\n readonly orderMayChange?: boolean;\n readonly isEqual?: (previous: V, next: V) => boolean;\n};\n\n/** Applies source hints to an output draft; exact net change semantics remain in the output. */\nconst stageCollectionRead = <K extends string, V>(\n state: CollectionOutputState<K, V>,\n read: CollectionRead<K, V>,\n active: () => boolean,\n options: CollectionStageOptions<K, V>\n): boolean => {\n const evaluation = state.begin(active, options.reset);\n if (options.reset) {\n const ids = read.ids();\n profile.collectionView.idsScanned(ids.length);\n for (const key of ids) {\n profile.collectionView.mapped();\n evaluation.output.set(key, read.get(key) as V);\n }\n evaluation.output.order(ids);\n } else {\n const previous = state.current();\n const keys = options.candidates\n ? [...new Set(options.candidates)]\n : [...new Set([...previous.ids(), ...read.ids()])];\n if (!options.candidates) profile.collectionView.idsScanned(keys.length);\n for (const key of keys) {\n if (read.has(key)) {\n profile.collectionView.mapped();\n evaluation.output.set(key, read.get(key) as V);\n } else evaluation.output.remove(key);\n }\n if (options.orderMayChange || !options.candidates) {\n const ids = read.ids();\n if (options.candidates) profile.collectionView.idsScanned(ids.length);\n evaluation.output.order(ids);\n }\n }\n return state.seal(options.reset, options.isEqual ?? Object.is);\n};\n\nexport const createCollectionBoundary = (\n scheduler: Scheduler,\n name: string,\n readLatest: (\n active: () => boolean,\n previous: CollectionRead<string, unknown>\n ) => CollectionRead<string, unknown>,\n equality: (previous: unknown, next: unknown) => boolean,\n clearSource: (failed: boolean) => void\n): CollectionBoundary => {\n let boundary!: SourceBoundaryRecord;\n let pendingReset = false;\n let pendingCause: unknown;\n let contextCause: unknown;\n let recovering = false;\n let fullScan = false;\n let orderMayChange = false;\n const candidates = new Set<string>();\n let cleanup: Unsubscribe | undefined;\n\n const check = () => {\n if (!scheduler.active || boundary.disposed) throw new ProjectionDisposedError();\n if (boundary.fault) throw boundary.fault;\n };\n const state: CollectionOutputState<string, unknown> = createCollectionOutput({\n owner: () => boundary,\n check,\n cause: () => contextCause,\n });\n const output: OutputRecord = state;\n\n boundary = {\n kind: 'source',\n name,\n outputs: Object.freeze([output]) as readonly [OutputRecord],\n fault: undefined,\n disposed: false,\n pendingCause: () => pendingCause,\n recovering: () => recovering,\n prepare: cause => {\n contextCause = cause;\n let active = true;\n try {\n const changed = stageCollectionRead(\n state,\n readLatest(() => active, state.current()),\n () => active,\n {\n reset: pendingReset,\n ...(fullScan ? {} : { candidates }),\n orderMayChange,\n isEqual: equality,\n }\n );\n recovering = false;\n return { changed, force: pendingReset };\n } finally {\n active = false;\n }\n },\n publish: state.publish,\n clear: () => {\n const failed = boundary.fault !== undefined;\n state.clear();\n pendingReset = false;\n pendingCause = undefined;\n contextCause = undefined;\n recovering = false;\n fullScan = false;\n orderMayChange = false;\n candidates.clear();\n clearSource(failed);\n },\n release: () => {\n const detach = cleanup;\n cleanup = undefined;\n const failures: unknown[] = [];\n try {\n detach?.();\n } catch (error) {\n failures.push(error);\n }\n try {\n state.release();\n } catch (error) {\n failures.push(error);\n }\n if (failures.length) throw failures[0];\n },\n };\n\n try {\n scheduler.initialize(() => {\n let active = true;\n try {\n stageCollectionRead(\n state,\n readLatest(() => active, state.current()),\n () => active,\n { reset: true, isEqual: equality }\n );\n state.publish();\n state.clear();\n } finally {\n active = false;\n }\n });\n scheduler.addSource(boundary);\n } catch (error) {\n boundary.disposed = true;\n try {\n boundary.release();\n } catch {\n /* Initialization failure retains priority. */\n }\n throw error;\n }\n\n const mark = (metadata: CollectionMark = {}) => {\n scheduler.assertIdle();\n pendingReset ||= metadata.reset ?? false;\n if (metadata.cause !== undefined) pendingCause ??= metadata.cause;\n fullScan ||= metadata.fullScan ?? false;\n orderMayChange ||= metadata.orderMayChange ?? false;\n if (metadata.candidates) for (const key of metadata.candidates) candidates.add(key);\n if (boundary.fault) recovering = true;\n scheduler.capture(boundary);\n };\n const fail = (cause: unknown) => {\n boundary.fault = sourceError(cause);\n recovering = false;\n scheduler.capture(boundary);\n };\n return {\n producer: boundary,\n output,\n mark,\n fail,\n detach: next => {\n cleanup = next;\n },\n };\n};\n","import * as address from '../../address/resolve';\nimport * as impactTarget from '../../impact/target';\nimport * as sequence from '../../order/sequence';\nimport { contextOf } from '../../runtime/context';\nimport type { ReadonlyDocument, Unsubscribe } from '../../runtime/contract';\nimport { collectionEntryNode } from '../../schema/model';\nimport type { DocumentTreeNode, ObjectSchema } from '../../schema/model';\nimport type { ImpactTarget } from '../../schema/path';\nimport type { ChangeSet } from '../../changes';\nimport * as schemaValue from '../../schema/value';\nimport { isRecord } from '../../value/record';\nimport type { CollectionRead } from '../contract';\nimport type { SourceDefinition } from '../definition';\nimport { materializeDocumentValue } from './materialization';\nimport {\n clearCollectionPending,\n clearDocumentDirty,\n createCollectionPending,\n createDocumentDirty,\n markDocumentReplace,\n mergeCollectionChanges,\n mergeValueChanges,\n resetCollectionPending,\n} from './dirty';\nimport { assertScope, type Scheduler } from '../graph/scheduler';\nimport {\n createCollectionBoundary,\n createValueBoundary,\n type CollectionBoundary,\n type SourceMaterialization,\n type ValueBoundary,\n} from './boundary';\n\ntype DocumentBinding = {\n readonly target: ImpactTarget;\n capture(commit: { readonly changes: ChangeSet }): void;\n dispose(): void;\n};\n\ntype DocumentConnection = {\n add(binding: DocumentBinding): Unsubscribe;\n close(): void;\n};\n\nconst documentRootTarget: ImpactTarget = Object.freeze({\n kind: 'value' as const,\n at: Object.freeze([]),\n});\n\nexport const createDocumentSourceRegistry = (scheduler: Scheduler) => {\n const documents = new Map<object, DocumentConnection>();\n\n const connection = <S extends ObjectSchema<object>>(\n runtime: ReadonlyDocument<S>\n ): DocumentConnection => {\n const context = contextOf<S>(runtime);\n const state = context.state;\n const cached = documents.get(state);\n if (cached) return cached;\n if (state.disposed) throw new Error('Document has been disposed.');\n const bindings = new Set<DocumentBinding>();\n const index = new impactTarget.SubscriptionIndex<DocumentBinding>(state.schema);\n const candidates = new Set<DocumentBinding>();\n const guard = (locked: boolean) => {\n state.projectionLocks += locked ? 1 : -1;\n };\n let unregisterGuard = scheduler.registerGuard(guard);\n let closed = false;\n let detach: Unsubscribe | undefined;\n const documentConnection: DocumentConnection = {\n add(binding) {\n if (closed) throw new Error('Document projection connection is closed.');\n bindings.add(binding);\n try {\n index.add(binding.target, binding);\n } catch (error) {\n bindings.delete(binding);\n throw error;\n }\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n bindings.delete(binding);\n index.delete(binding.target, binding);\n if (!bindings.size) documentConnection.close();\n };\n },\n close() {\n if (closed) return;\n closed = true;\n const stopNotifications = detach;\n detach = undefined;\n const stopGuard = unregisterGuard;\n unregisterGuard = () => undefined;\n bindings.clear();\n candidates.clear();\n index.clear();\n documents.delete(state);\n const failures: unknown[] = [];\n try {\n stopNotifications?.();\n } catch (error) {\n failures.push(error);\n }\n try {\n stopGuard();\n } catch (error) {\n failures.push(error);\n }\n if (failures.length) throw failures[0];\n },\n };\n try {\n detach = context.notifications.attachProjection({\n capture: commit => {\n candidates.clear();\n index.collect(commit.changes, binding => candidates.add(binding));\n candidates.forEach(binding => binding.capture(commit));\n },\n settle: scheduler.settle,\n flush: scheduler.flush,\n dispose: () => {\n const failures: unknown[] = [];\n for (const binding of [...bindings]) {\n try {\n binding.dispose();\n } catch (error) {\n failures.push(error);\n }\n }\n try {\n scheduler.run();\n } catch (error) {\n failures.push(error);\n }\n if (failures.length) throw failures[0];\n },\n });\n } catch (error) {\n try {\n documentConnection.close();\n } catch {\n /* Connection initialization failure retains priority. */\n }\n throw error;\n }\n documents.set(state, documentConnection);\n return documentConnection;\n };\n\n const materialize = (definition: SourceDefinition): SourceMaterialization => {\n if (definition.source.kind !== 'document') throw new Error('Invalid document source.');\n const { document, selector } = definition.source;\n const state = contextOf(document).state;\n const current = () => address.resolveValue(state.schema, state.document, selector.address);\n const disposed = () => {\n if (state.disposed) throw new Error('Document has been disposed.');\n };\n\n if (selector.kind === 'value') {\n const dirty = createDocumentDirty();\n const read = (previous?: unknown): unknown => {\n disposed();\n const resolved = current();\n const node = resolved?.node;\n const value = resolved?.value;\n if (selector.tree?.kind === 'root')\n return node?.kind === 'tree' && isRecord(value) && typeof value.rootId === 'string'\n ? value.rootId\n : undefined;\n if (selector.tree?.kind === 'node') {\n if (node?.kind !== 'tree' || !isRecord(value) || !isRecord(value.nodes)) return undefined;\n const entry = Object.hasOwn(value.nodes, selector.tree.id)\n ? (value.nodes[selector.tree.id] as\n DocumentTreeNode<unknown, false> | DocumentTreeNode<unknown, true>)\n : undefined;\n if (\n schemaValue.equalTreeNode(\n previous as\n DocumentTreeNode<unknown, false> | DocumentTreeNode<unknown, true> | undefined,\n entry\n )\n )\n return previous;\n return entry ? schemaValue.copyTreeNode(entry) : undefined;\n }\n if (!node) return undefined;\n return previous === undefined\n ? schemaValue.copyValue(node, value)\n : materializeDocumentValue(node, previous, value, dirty);\n };\n\n const initial = read();\n let boundary!: ValueBoundary;\n boundary = createValueBoundary(\n scheduler,\n 'document source',\n initial,\n Object.is,\n previous => read(previous),\n failed => {\n if (failed) markDocumentReplace(dirty, []);\n else clearDocumentDirty(dirty);\n }\n );\n let remove: Unsubscribe;\n try {\n remove = connection(document).add({\n target: selector,\n capture: commit => {\n try {\n mergeValueChanges(selector, dirty, commit.changes);\n boundary.mark({\n reset: commit.changes.changes.some(change => change.kind === 'reset'),\n });\n } catch (cause) {\n boundary.fail(cause);\n }\n },\n dispose: () => boundary.fail(new Error('Document has been disposed.')),\n });\n } catch (error) {\n try {\n scheduler.releaseProducer(boundary.producer);\n } catch {\n /* Connection initialization failure retains priority. */\n }\n throw error;\n }\n boundary.detach(remove);\n return boundary;\n }\n\n const pending = createCollectionPending();\n const read = (\n active: () => boolean,\n previous: CollectionRead<string, unknown>\n ): CollectionRead<string, unknown> => {\n disposed();\n const resolved = current();\n const node = resolved?.node;\n const value = resolved?.value;\n const treeNodes = selector.tree?.kind === 'nodes';\n const entryNode = !treeNodes && node ? collectionEntryNode(node) : undefined;\n const snapshots = new Map<string, unknown>();\n const replacement = createDocumentDirty();\n if (pending.reset) markDocumentReplace(replacement, []);\n\n const ids = (): readonly string[] => {\n assertScope(active);\n if (treeNodes)\n return node?.kind === 'tree' && isRecord(value) && isRecord(value.nodes)\n ? Object.freeze(Object.keys(value.nodes))\n : Object.freeze([]);\n if (node?.kind === 'map' && isRecord(value)) return Object.freeze(Object.keys(value));\n if (node?.kind === 'table' && isRecord(value) && Array.isArray(value.ids))\n return Object.freeze([...(value.ids as string[])]);\n if (node?.kind === 'list' && Array.isArray(value))\n return Object.freeze(sequence.toArray(sequence.indexedKeys(value, node.keyOf)));\n return Object.freeze([]);\n };\n\n const has = (key: string): boolean => {\n assertScope(active);\n if (treeNodes)\n return Boolean(\n node?.kind === 'tree' &&\n isRecord(value) &&\n isRecord(value.nodes) &&\n Object.hasOwn(value.nodes, key)\n );\n if (node?.kind === 'map' && isRecord(value)) return Object.hasOwn(value, key);\n if (node?.kind === 'table' && isRecord(value) && isRecord(value.byId))\n return Object.hasOwn(value.byId, key);\n if (node?.kind === 'list' && Array.isArray(value))\n return sequence.indexedKeys(value, node.keyOf).index(key) >= 0;\n return false;\n };\n\n const raw = (key: string): unknown => {\n if (treeNodes) {\n if (node?.kind !== 'tree' || !isRecord(value) || !isRecord(value.nodes)) return undefined;\n return Object.hasOwn(value.nodes, key) ? value.nodes[key] : undefined;\n }\n if (node?.kind === 'map' && isRecord(value))\n return Object.hasOwn(value, key) ? value[key] : undefined;\n if (node?.kind === 'table' && isRecord(value) && isRecord(value.byId))\n return Object.hasOwn(value.byId, key) ? value.byId[key] : undefined;\n if (node?.kind === 'list' && Array.isArray(value)) {\n const index = sequence.indexedKeys(value, node.keyOf).index(key);\n return index < 0 ? undefined : value[index];\n }\n return undefined;\n };\n\n return Object.freeze({\n get: (key: string) => {\n assertScope(active);\n if (!snapshots.has(key)) {\n if (!has(key)) snapshots.set(key, undefined);\n else {\n const current = raw(key);\n if (treeNodes) {\n const entry = current as\n DocumentTreeNode<unknown, false> | DocumentTreeNode<unknown, true>;\n const before = previous.has(key)\n ? (previous.get(key) as\n DocumentTreeNode<unknown, false> | DocumentTreeNode<unknown, true>)\n : undefined;\n snapshots.set(\n key,\n schemaValue.equalTreeNode(before, entry)\n ? before\n : schemaValue.copyTreeNode(entry)\n );\n } else if (!entryNode) snapshots.set(key, current);\n else if (!previous.has(key))\n snapshots.set(key, schemaValue.copyValue(entryNode, current));\n else {\n const dirty = pending.entries.get(key) ?? (pending.reset ? replacement : undefined);\n snapshots.set(\n key,\n dirty\n ? materializeDocumentValue(entryNode, previous.get(key), current, dirty)\n : previous.get(key)\n );\n }\n }\n }\n return snapshots.get(key);\n },\n has,\n ids,\n });\n };\n\n let boundary!: CollectionBoundary;\n boundary = createCollectionBoundary(\n scheduler,\n 'document collection source',\n read,\n Object.is,\n failed => {\n if (failed) resetCollectionPending(pending);\n else clearCollectionPending(pending);\n }\n );\n let remove: Unsubscribe;\n try {\n remove = connection(document).add({\n target: selector,\n capture: commit => {\n try {\n mergeCollectionChanges(selector, pending, commit.changes);\n boundary.mark({\n reset: pending.reset,\n ...(pending.reset ? {} : { candidates: pending.entries.keys() }),\n orderMayChange: pending.order,\n });\n } catch (cause) {\n boundary.fail(cause);\n }\n },\n dispose: () => boundary.fail(new Error('Document has been disposed.')),\n });\n } catch (error) {\n try {\n scheduler.releaseProducer(boundary.producer);\n } catch {\n /* Connection initialization failure retains priority. */\n }\n throw error;\n }\n boundary.detach(remove);\n return boundary;\n };\n\n return {\n materialize,\n attachRoot<S extends ObjectSchema<object>>(\n runtime: ReadonlyDocument<S>,\n handlers: { readonly capture: () => void; readonly dispose: () => void }\n ): Unsubscribe {\n return connection(runtime).add({\n target: documentRootTarget,\n capture: handlers.capture,\n dispose: handlers.dispose,\n });\n },\n dispose() {\n const failures: unknown[] = [];\n for (const document of [...documents.values()]) {\n try {\n document.close();\n } catch (error) {\n failures.push(error);\n }\n }\n documents.clear();\n if (failures.length) throw failures[0];\n },\n };\n};\n","import type { Readable } from '../../readable';\nimport { contextOf } from '../../runtime/context';\nimport type { Unsubscribe } from '../../runtime/contract';\nimport type { ExternalCollectionSource } from '../contract';\nimport type { SourceDefinition } from '../definition';\nimport type { Scheduler } from '../graph/scheduler';\nimport {\n createCollectionBoundary,\n createValueBoundary,\n type CollectionBoundary,\n type SourceMark,\n type SourceMaterialization,\n type ValueBoundary,\n} from './boundary';\nimport type { createDocumentSourceRegistry } from './document';\n\ntype ValueMember = {\n readonly boundary: ValueBoundary;\n receive(value: unknown, metadata?: SourceMark): void;\n};\n\ntype DocumentSources = ReturnType<typeof createDocumentSourceRegistry>;\n\nexport const createExternalSourceRegistry = (scheduler: Scheduler, documents: DocumentSources) => {\n const readables = new Map<Readable<unknown>, { members: Set<ValueMember>; close(): void }>();\n const externalValues = new Map<object, { members: Set<ValueMember>; close(): void }>();\n const externalCollections = new Map<\n object,\n { members: Set<CollectionBoundary>; close(): void }\n >();\n\n const readable = (definition: SourceDefinition): SourceMaterialization => {\n if (definition.source.kind !== 'readable') throw new Error('Invalid Readable source.');\n const { readable, equality } = definition.source;\n let latest = readable.current();\n const boundary = createValueBoundary(\n scheduler,\n 'external readable',\n latest,\n equality,\n () => latest,\n () => undefined\n );\n const member: ValueMember = {\n boundary,\n receive(value, metadata) {\n latest = value;\n boundary.mark(metadata);\n },\n };\n let connection = readables.get(readable);\n if (!connection) {\n const members = new Set<ValueMember>();\n let closed = false;\n let unsubscribe: Unsubscribe | undefined;\n let detachDocument: Unsubscribe | undefined;\n const receive = (settle: boolean) => {\n if (closed || !scheduler.active) return;\n try {\n const value = readable.current();\n members.forEach(next => next.receive(value));\n } catch (cause) {\n members.forEach(next => next.boundary.fail(cause));\n }\n if (settle) scheduler.run();\n };\n const created = {\n members,\n close() {\n if (closed) return;\n closed = true;\n const stopReadable = unsubscribe;\n unsubscribe = undefined;\n const stopDocument = detachDocument;\n detachDocument = undefined;\n readables.delete(readable);\n members.clear();\n const failures: unknown[] = [];\n try {\n stopReadable?.();\n } catch (error) {\n failures.push(error);\n }\n try {\n stopDocument?.();\n } catch (error) {\n failures.push(error);\n }\n if (failures.length) throw failures[0];\n },\n };\n try {\n const owner = contextOf(readable, false)?.owner;\n if (owner) {\n detachDocument = documents.attachRoot(owner, {\n capture: () => receive(false),\n dispose: () => {\n members.forEach(next => next.boundary.fail(new Error('Document has been disposed.')));\n },\n });\n }\n unsubscribe = readable.subscribe(() => receive(true));\n } catch (error) {\n try {\n created.close();\n } catch {\n /* Connection initialization failure retains priority. */\n }\n try {\n scheduler.releaseProducer(boundary.producer);\n } catch {\n /* Connection initialization failure retains priority. */\n }\n throw error;\n }\n connection = created;\n readables.set(readable, connection);\n }\n connection.members.add(member);\n boundary.detach(() => {\n connection!.members.delete(member);\n if (!connection!.members.size) connection!.close();\n });\n return boundary;\n };\n\n const externalValue = (definition: SourceDefinition): SourceMaterialization => {\n if (definition.source.kind !== 'external-value')\n throw new Error('Invalid external value source.');\n const { source, equality } = definition.source;\n let latest = source.current();\n const boundary = createValueBoundary(\n scheduler,\n 'external source',\n latest,\n equality,\n () => latest,\n () => undefined\n );\n const member: ValueMember = {\n boundary,\n receive(value, metadata) {\n latest = value;\n boundary.mark(metadata);\n },\n };\n let connection = externalValues.get(source);\n if (!connection) {\n const members = new Set<ValueMember>();\n let closed = false;\n let unsubscribe: Unsubscribe | undefined;\n const created = {\n members,\n close() {\n if (closed) return;\n closed = true;\n const stop = unsubscribe;\n unsubscribe = undefined;\n externalValues.delete(source);\n members.clear();\n stop?.();\n },\n };\n try {\n unsubscribe = source.subscribe(event => {\n try {\n members.forEach(next =>\n next.receive(event.value, { reset: event.reset, cause: event.cause })\n );\n } catch (cause) {\n members.forEach(next => next.boundary.fail(cause));\n }\n scheduler.run();\n });\n } catch (error) {\n try {\n created.close();\n } catch {\n /* Connection initialization failure retains priority. */\n }\n try {\n scheduler.releaseProducer(boundary.producer);\n } catch {\n /* Connection initialization failure retains priority. */\n }\n throw error;\n }\n connection = created;\n externalValues.set(source, connection);\n }\n connection.members.add(member);\n boundary.detach(() => {\n connection!.members.delete(member);\n if (!connection!.members.size) connection!.close();\n });\n return boundary;\n };\n\n const externalCollection = (definition: SourceDefinition): SourceMaterialization => {\n if (definition.source.kind !== 'external-collection')\n throw new Error('Invalid external collection source.');\n const source = definition.source.source as ExternalCollectionSource<string, unknown>;\n const boundary = createCollectionBoundary(\n scheduler,\n 'external collection source',\n () => {\n const current = source.current();\n return Object.freeze({\n get: key => current.get(key),\n has: key => current.has(key),\n ids: () => current.ids(),\n });\n },\n definition.output.equality,\n () => undefined\n );\n let connection = externalCollections.get(source);\n if (!connection) {\n const members = new Set<CollectionBoundary>();\n let closed = false;\n let unsubscribe: Unsubscribe | undefined;\n const created = {\n members,\n close() {\n if (closed) return;\n closed = true;\n const stop = unsubscribe;\n unsubscribe = undefined;\n externalCollections.delete(source);\n members.clear();\n stop?.();\n },\n };\n try {\n unsubscribe = source.subscribe(event => {\n try {\n const impact = event.impact;\n if (impact?.kind === 'reset') {\n members.forEach(next => next.mark({ reset: true, cause: event.cause }));\n } else if (impact?.kind === 'incremental') {\n const candidates = new Set<string>([\n ...impact.added,\n ...impact.updated,\n ...impact.removed,\n ]);\n members.forEach(next =>\n next.mark({\n candidates,\n orderMayChange: Boolean(\n impact.added.size || impact.removed.size || impact.orderChanged\n ),\n cause: event.cause,\n })\n );\n } else {\n members.forEach(next =>\n next.mark({ fullScan: true, orderMayChange: true, cause: event.cause })\n );\n }\n } catch (cause) {\n members.forEach(next => next.fail(cause));\n }\n scheduler.run();\n });\n } catch (error) {\n try {\n created.close();\n } catch {\n /* Connection initialization failure retains priority. */\n }\n try {\n scheduler.releaseProducer(boundary.producer);\n } catch {\n /* Connection initialization failure retains priority. */\n }\n throw error;\n }\n connection = created;\n externalCollections.set(source, connection);\n }\n connection.members.add(boundary);\n boundary.detach(() => {\n connection!.members.delete(boundary);\n if (!connection!.members.size) connection!.close();\n });\n return boundary;\n };\n\n return {\n materialize(definition: SourceDefinition): SourceMaterialization {\n switch (definition.source.kind) {\n case 'readable':\n return readable(definition);\n case 'external-value':\n return externalValue(definition);\n case 'external-collection':\n return externalCollection(definition);\n default:\n throw new Error('Invalid external projection source.');\n }\n },\n dispose() {\n const failures: unknown[] = [];\n const connections = new Set([\n ...readables.values(),\n ...externalValues.values(),\n ...externalCollections.values(),\n ]);\n for (const connection of connections) {\n try {\n connection.close();\n } catch (error) {\n failures.push(error);\n }\n }\n readables.clear();\n externalValues.clear();\n externalCollections.clear();\n if (failures.length) throw failures[0];\n },\n };\n};\n","import { mapRead } from '../collection/view';\nimport type { CollectionInputDraft, SourceDefinition } from '../definition';\nimport { assertScope, assertSynchronous, type Scheduler } from '../graph/scheduler';\nimport {\n createCollectionBoundary,\n createValueBoundary,\n type SourceMaterialization,\n} from './boundary';\n\nexport const materializeInputSource = (\n scheduler: Scheduler,\n definition: SourceDefinition\n): SourceMaterialization => {\n const source = definition.source;\n if (source.kind === 'value-input') {\n let latest = source.initial;\n const boundary = createValueBoundary(\n scheduler,\n 'projection input',\n source.initial,\n source.equality,\n () => latest,\n () => undefined\n );\n return {\n ...boundary,\n write: {\n kind: 'value',\n set(value) {\n scheduler.assertIdle();\n latest = value;\n boundary.mark();\n scheduler.run();\n },\n },\n };\n }\n if (source.kind !== 'collection-input') throw new Error('Invalid projection input source.');\n\n const values = new Map(source.initial);\n const boundary = createCollectionBoundary(\n scheduler,\n 'projection collection input',\n () => mapRead(values),\n definition.output.equality,\n () => undefined\n );\n return {\n ...boundary,\n write: {\n kind: 'collection',\n update(run) {\n scheduler.assertIdle();\n const staged = new Map<\n string,\n { readonly present: true; readonly value: unknown } | { readonly present: false }\n >();\n const operations: (\n | { readonly kind: 'set'; readonly key: string; readonly value: unknown }\n | { readonly kind: 'remove'; readonly key: string }\n )[] = [];\n let active = true;\n const draft: CollectionInputDraft<string, unknown> = Object.freeze({\n get: key => {\n assertScope(() => active);\n const entry = staged.get(key);\n return entry ? (entry.present ? entry.value : undefined) : values.get(key);\n },\n has: key => {\n assertScope(() => active);\n const entry = staged.get(key);\n return entry ? entry.present : values.has(key);\n },\n set: (key, value) => {\n assertScope(() => active);\n if (typeof key !== 'string') throw new TypeError('Projection keys must be strings.');\n staged.set(key, { present: true, value });\n operations.push({ kind: 'set', key, value });\n },\n remove: key => {\n assertScope(() => active);\n if (typeof key !== 'string') throw new TypeError('Projection keys must be strings.');\n staged.set(key, { present: false });\n operations.push({ kind: 'remove', key });\n },\n });\n try {\n assertSynchronous(run(draft));\n } finally {\n active = false;\n }\n\n const candidates = new Set<string>();\n let structural = false;\n const accepted: typeof operations = [];\n const overlay = new Map<\n string,\n { readonly present: true; readonly value: unknown } | { readonly present: false }\n >();\n for (const operation of operations) {\n const overlayValue = overlay.get(operation.key);\n const present = overlayValue ? overlayValue.present : values.has(operation.key);\n if (operation.kind === 'set') {\n const previous = overlayValue\n ? overlayValue.present\n ? overlayValue.value\n : undefined\n : values.get(operation.key);\n if (present && source.equality(previous, operation.value)) continue;\n structural ||= !present;\n overlay.set(operation.key, { present: true, value: operation.value });\n } else {\n if (!present) continue;\n structural = true;\n overlay.set(operation.key, { present: false });\n }\n accepted.push(operation);\n candidates.add(operation.key);\n }\n if (!accepted.length) return;\n for (const operation of accepted) {\n if (operation.kind === 'set') values.set(operation.key, operation.value);\n else values.delete(operation.key);\n }\n boundary.mark({ candidates, orderMayChange: structural });\n scheduler.run();\n },\n },\n };\n};\n","import type { SourceDefinition } from '../definition';\nimport type { Scheduler } from '../graph/scheduler';\nimport type { SourceMaterialization } from './boundary';\nimport { createDocumentSourceRegistry } from './document';\nimport { createExternalSourceRegistry } from './external';\nimport { materializeInputSource } from './input';\n\nexport const createSourceRegistry = (scheduler: Scheduler) => {\n const documents = createDocumentSourceRegistry(scheduler);\n const external = createExternalSourceRegistry(scheduler, documents);\n\n return {\n materialize(definition: SourceDefinition): SourceMaterialization {\n switch (definition.source.kind) {\n case 'value-input':\n case 'collection-input':\n return materializeInputSource(scheduler, definition);\n case 'document':\n return documents.materialize(definition);\n case 'readable':\n case 'external-value':\n case 'external-collection':\n return external.materialize(definition);\n }\n },\n dispose() {\n const failures: unknown[] = [];\n try {\n external.dispose();\n } catch (error) {\n failures.push(error);\n }\n try {\n documents.dispose();\n } catch (error) {\n failures.push(error);\n }\n if (failures.length) throw failures[0];\n },\n };\n};\n","import type { Unsubscribe } from '../runtime/contract';\nimport { collectionView, mapRead, snapshotCollectionView } from './collection/view';\nimport type { CollectionRead } from './contract';\nimport { ProjectionDisposedError } from './contract';\nimport {\n isProjection,\n ownProjections,\n producerOf,\n projectionRef,\n type CollectionInput,\n type CollectionInputDraft,\n type Input,\n type ProducerDefinition,\n type Projection,\n} from './definition';\nimport { isPlainObject } from '../value/record';\nimport { createProcessor } from './graph/processor';\nimport {\n createDirectReadable,\n createSelectorReadable,\n isMapLike,\n type ProjectionReadableSource,\n} from './readable/selection';\nimport type { Readable } from '../readable';\nimport { createScheduler, type OutputRecord, type ProducerRecord } from './graph/scheduler';\nimport { createSourceRegistry } from './source/registry';\nimport type { SourceWrite } from './source/boundary';\n\nexport type ProjectionRuntime = {\n read<T>(projection: Projection<T>): T;\n select<T>(projection: Projection<T>): Readable<T>;\n select<T, R>(\n projection: Projection<T>,\n selector: (value: T) => R,\n equality?: (previous: R, next: R) => boolean\n ): Readable<R>;\n update<T>(input: Input<T>, value: T): void;\n update<K extends string, V>(\n input: CollectionInput<K, V>,\n run: (draft: CollectionInputDraft<K, V>) => void\n ): void;\n batch<T>(run: () => T, options?: { readonly cause?: unknown }): T;\n scope(): ProjectionScope;\n dispose(): void;\n};\n\ntype ProjectionOwnershipTree = {\n readonly [name: string]: Projection<unknown> | ProjectionOwnershipTree;\n};\n\nexport type ProjectionScope = {\n own<P extends Projection<unknown>>(projection: P): P;\n own<T extends ProjectionOwnershipTree>(tree: T): T;\n read<T>(projection: Projection<T>): T;\n select<T>(projection: Projection<T>): Readable<T>;\n select<T, R>(\n projection: Projection<T>,\n selector: (value: T) => R,\n equality?: (previous: R, next: R) => boolean\n ): Readable<R>;\n update<T>(input: Input<T>, value: T): void;\n update<K extends string, V>(\n input: CollectionInput<K, V>,\n run: (draft: CollectionInputDraft<K, V>) => void\n ): void;\n batch<T>(run: () => T, options?: { readonly cause?: unknown }): T;\n dispose(): void;\n};\n\ntype MaterializedProducer = {\n readonly record: ProducerRecord;\n readonly outputs: readonly OutputRecord[];\n readonly write?: SourceWrite;\n};\n\ntype ScopeState = {\n active: boolean;\n readonly materialized: ProducerDefinition[];\n readonly subscriptions: Set<Unsubscribe>;\n};\n\nexport const createProjectionRuntime = (options?: {\n readonly onError?: (error: import('./contract').ProjectionError) => void;\n}): ProjectionRuntime => {\n const scheduler = createScheduler(options?.onError ?? (() => undefined));\n const sources = createSourceRegistry(scheduler);\n const materialized = new WeakMap<ProducerDefinition, MaterializedProducer>();\n const publicViews = new WeakMap<\n OutputRecord,\n { readonly revision: number; readonly value: ReadonlyMap<string, unknown> }\n >();\n const scopes = new Set<ScopeState>();\n\n const assertAccess = (definition: ProducerDefinition, requester?: ScopeState): void => {\n scheduler.assertActive();\n const owner = definition.owner;\n if (owner === undefined) return;\n if (owner !== requester) throw new TypeError('Projection belongs to another scope.');\n if (!requester?.active) throw new ProjectionDisposedError();\n };\n\n const rememberScoped = (\n definition: ProducerDefinition,\n requester: ScopeState | undefined\n ): void => {\n if (requester && definition.owner === requester) requester.materialized.push(definition);\n };\n\n const materializeProducer = (\n definition: ProducerDefinition,\n requester?: ScopeState\n ): MaterializedProducer => {\n assertAccess(definition, requester);\n const existing = materialized.get(definition);\n if (existing) return existing;\n\n let result: MaterializedProducer;\n if (definition.kind === 'source') {\n const source = sources.materialize(definition);\n result = Object.freeze({\n record: source.producer,\n outputs: Object.freeze([source.output]),\n ...(source.write ? { write: source.write } : {}),\n });\n } else {\n if (\n definition.owner === undefined &&\n definition.dependencies.some(dependency => producerOf(dependency).owner !== undefined)\n )\n throw new TypeError('A root projection cannot depend on a scoped projection.');\n const dependencies = definition.dependencies.map(dependency =>\n resolveOutput(dependency, requester)\n );\n const processor = createProcessor(scheduler, definition, Object.freeze(dependencies));\n result = Object.freeze({\n record: processor,\n outputs: processor.outputs,\n });\n }\n\n definition.materialized = true;\n materialized.set(definition, result);\n rememberScoped(definition, requester);\n return result;\n };\n\n const resolveOutput = (projection: Projection<unknown>, requester?: ScopeState): OutputRecord => {\n const ref = projectionRef(projection);\n const producer = materializeProducer(ref.producer, requester);\n const output = producer.outputs[ref.output];\n if (!output) throw new TypeError('Projection output does not exist.');\n return output;\n };\n\n const assertOutput = (output: OutputRecord): void => {\n scheduler.assertActive();\n if (output.owner.disposed) throw new ProjectionDisposedError();\n if (output.owner.fault) throw output.owner.fault;\n };\n\n const publicCurrent = (output: OutputRecord): unknown => {\n assertOutput(output);\n const current = output.current();\n const revision = output.revision();\n const cached = publicViews.get(output);\n if (cached?.revision === revision) return cached.value;\n\n if (output.kind === 'collection') {\n const value = collectionView(current as CollectionRead<string, unknown>);\n publicViews.set(output, { revision, value });\n return value;\n }\n if (isMapLike(current)) {\n const value = snapshotCollectionView(mapRead(current));\n publicViews.set(output, { revision, value });\n return value;\n }\n publicViews.delete(output);\n return current;\n };\n\n const readProjection = <T>(projection: Projection<T>, requester?: ScopeState): T =>\n publicCurrent(resolveOutput(projection as Projection<unknown>, requester)) as T;\n\n const readableSource = <T>(\n projection: Projection<T>,\n requester?: ScopeState\n ): ProjectionReadableSource<T> => {\n const output = resolveOutput(projection as Projection<unknown>, requester);\n return Object.freeze({\n kind: output.kind,\n current: () => readProjection(projection, requester),\n revision: () => {\n assertOutput(output);\n return output.revision();\n },\n subscribe: output.subscribe,\n });\n };\n\n const makeReadable = <T, R>(\n projection: Projection<T>,\n selector?: (value: T) => R,\n equality?: (previous: R, next: R) => boolean,\n requester?: ScopeState\n ): Readable<T | R> => {\n const source = readableSource(projection, requester);\n return selector\n ? createSelectorReadable(source, selector, equality)\n : createDirectReadable(source);\n };\n\n function selectProjection<T>(projection: Projection<T>): Readable<T>;\n function selectProjection<T, R>(\n projection: Projection<T>,\n selector: (value: T) => R,\n equality?: (previous: R, next: R) => boolean\n ): Readable<R>;\n function selectProjection<T, R>(\n projection: Projection<T>,\n selector?: (value: T) => R,\n equality?: (previous: R, next: R) => boolean\n ): Readable<T | R> {\n return makeReadable(projection, selector, equality);\n }\n\n const inputWrite = (target: Projection<unknown>, requester?: ScopeState): SourceWrite => {\n const ref = projectionRef(target);\n if (ref.output !== 0 || ref.producer.kind !== 'source')\n throw new TypeError('Projection is not an input.');\n if (\n ref.producer.source.kind !== 'value-input' &&\n ref.producer.source.kind !== 'collection-input'\n )\n throw new TypeError('Projection is not an input.');\n const write = materializeProducer(ref.producer, requester).write;\n if (!write) throw new TypeError('Projection input is not writable.');\n return write;\n };\n\n const updateInput = (\n target: Projection<unknown>,\n valueOrRun: unknown,\n requester?: ScopeState\n ): void => {\n const write = inputWrite(target, requester);\n if (write.kind === 'value') {\n write.set(valueOrRun);\n return;\n }\n if (typeof valueOrRun !== 'function')\n throw new TypeError('Collection input update requires a draft callback.');\n write.update(valueOrRun as (draft: CollectionInputDraft<string, unknown>) => void);\n };\n\n function update<T>(target: Input<T>, value: T): void;\n function update<K extends string, V>(\n target: CollectionInput<K, V>,\n run: (draft: CollectionInputDraft<K, V>) => void\n ): void;\n function update(target: Projection<unknown>, valueOrRun: unknown): void {\n updateInput(target, valueOrRun);\n }\n\n const batch = <T>(run: () => T, options?: { readonly cause?: unknown }): T =>\n scheduler.batch(run, options);\n\n const disposeScope = (state: ScopeState): void => {\n if (!state.active) return;\n scheduler.assertIdle();\n state.active = false;\n const failures: unknown[] = [];\n const subscriptions = [...state.subscriptions];\n state.subscriptions.clear();\n for (const unsubscribe of subscriptions) {\n try {\n unsubscribe();\n } catch (error) {\n failures.push(error);\n }\n }\n for (let index = state.materialized.length - 1; index >= 0; index--) {\n const definition = state.materialized[index];\n const current = materialized.get(definition);\n if (!current) continue;\n try {\n scheduler.releaseProducer(current.record);\n } catch (error) {\n failures.push(error);\n } finally {\n materialized.delete(definition);\n }\n }\n state.materialized.length = 0;\n scopes.delete(state);\n if (failures.length) throw failures[0];\n };\n\n const createScope = (): ProjectionScope => {\n scheduler.assertIdle();\n const state: ScopeState = {\n active: true,\n materialized: [],\n subscriptions: new Set(),\n };\n scopes.add(state);\n\n const assertActive = () => {\n if (!state.active) throw new ProjectionDisposedError();\n scheduler.assertActive();\n };\n function own<P extends Projection<unknown>>(projection: P): P;\n function own<T extends ProjectionOwnershipTree>(tree: T): T;\n function own<T extends Projection<unknown> | ProjectionOwnershipTree>(target: T): T {\n assertActive();\n const projections: Projection<unknown>[] = [];\n const collect = (value: Projection<unknown> | ProjectionOwnershipTree): void => {\n if (isProjection(value)) {\n projections.push(value);\n return;\n }\n if (!isPlainObject(value))\n throw new TypeError('Projection ownership tree must be a plain object.');\n for (const key of Reflect.ownKeys(value)) {\n if (typeof key !== 'string')\n throw new TypeError('Projection ownership tree keys must be strings.');\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (!descriptor?.enumerable || !('value' in descriptor))\n throw new TypeError('Projection ownership tree must use enumerable data properties.');\n const child = descriptor.value;\n if (!isProjection(child) && !isPlainObject(child))\n throw new TypeError('Projection ownership tree leaves must be projections.');\n collect(child as Projection<unknown> | ProjectionOwnershipTree);\n }\n };\n collect(target);\n if (!projections.length)\n throw new TypeError('Projection ownership tree must contain a projection.');\n ownProjections(projections, state);\n return target;\n }\n\n function scopeSelect<T>(projection: Projection<T>): Readable<T>;\n function scopeSelect<T, R>(\n projection: Projection<T>,\n selector: (value: T) => R,\n equality?: (previous: R, next: R) => boolean\n ): Readable<R>;\n function scopeSelect<T, R>(\n projection: Projection<T>,\n selector?: (value: T) => R,\n equality?: (previous: R, next: R) => boolean\n ): Readable<T | R> {\n assertActive();\n const source = makeReadable(projection, selector, equality, state);\n return Object.freeze({\n current: () => {\n assertActive();\n return source.current();\n },\n revision: () => {\n assertActive();\n return source.revision();\n },\n subscribe: listener => {\n assertActive();\n const stop = source.subscribe(listener);\n let subscribed = true;\n const unsubscribe = () => {\n if (!subscribed) return;\n subscribed = false;\n state.subscriptions.delete(unsubscribe);\n stop();\n };\n state.subscriptions.add(unsubscribe);\n return unsubscribe;\n },\n });\n }\n\n function scopeUpdate<T>(target: Input<T>, value: T): void;\n function scopeUpdate<K extends string, V>(\n target: CollectionInput<K, V>,\n run: (draft: CollectionInputDraft<K, V>) => void\n ): void;\n function scopeUpdate(target: Projection<unknown>, valueOrRun: unknown): void {\n assertActive();\n updateInput(target, valueOrRun, state);\n }\n\n function scopeBatch<T>(run: () => T, options?: { readonly cause?: unknown }): T {\n assertActive();\n return batch(run, options);\n }\n\n return Object.freeze({\n own,\n read: <T>(projection: Projection<T>) => {\n assertActive();\n return readProjection(projection, state);\n },\n select: scopeSelect,\n update: scopeUpdate,\n batch: scopeBatch,\n dispose: () => disposeScope(state),\n });\n };\n\n return Object.freeze({\n read: readProjection,\n select: selectProjection,\n update,\n batch,\n scope: createScope,\n dispose: () => {\n if (!scheduler.active) return;\n scheduler.assertIdle();\n const failures: unknown[] = [];\n for (const scope of scopes) {\n scope.active = false;\n const subscriptions = [...scope.subscriptions];\n scope.subscriptions.clear();\n for (const unsubscribe of subscriptions) {\n try {\n unsubscribe();\n } catch (error) {\n failures.push(error);\n }\n }\n scope.materialized.length = 0;\n }\n scopes.clear();\n try {\n sources.dispose();\n } catch (error) {\n failures.push(error);\n }\n try {\n scheduler.dispose();\n } catch (error) {\n failures.push(error);\n }\n if (failures.length === 1) throw failures[0];\n if (failures.length) throw new AggregateError(failures, 'Projection cleanup failed.');\n },\n });\n};\n"],"mappings":";;;;;AAmMA,MAAa,gBAAoD,WAC/D;AAqEF,MAAa,uBAAuB,SAClC,KAAK,SAAS,SA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