doxum 0.1.20 → 0.1.21

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.
Files changed (57) hide show
  1. package/README.md +10 -2
  2. package/dist/{access-B9XDWjHy.js → access-BeSV5ve-.js} +61 -19
  3. package/dist/access-BeSV5ve-.js.map +1 -0
  4. package/dist/{access-EQ-XiFyl.cjs → access-Bienf28h.cjs} +61 -19
  5. package/dist/access-Bienf28h.cjs.map +1 -0
  6. package/dist/{advanced-BIGP86NL.cjs → advanced-BRL5pN0y.cjs} +3 -3
  7. package/dist/{advanced-BIGP86NL.cjs.map → advanced-BRL5pN0y.cjs.map} +1 -1
  8. package/dist/{advanced-Bcle5C2M.js → advanced-COFJtWMT.js} +3 -3
  9. package/dist/{advanced-Bcle5C2M.js.map → advanced-COFJtWMT.js.map} +1 -1
  10. package/dist/{advanced-CSjF-u_k.d.cts → advanced-DfKc7TZR.d.cts} +2 -2
  11. package/dist/{advanced-Du3O8O1A.d.ts → advanced-FgdTwu5b.d.ts} +2 -2
  12. package/dist/advanced.cjs +1 -1
  13. package/dist/advanced.d.cts +1 -1
  14. package/dist/advanced.d.ts +1 -1
  15. package/dist/advanced.js +1 -1
  16. package/dist/{contract-BDQth1pe.d.cts → contract-CdmDHRUq.d.cts} +5 -3
  17. package/dist/{contract-BlEl8Ibo.d.ts → contract-KG5XnQZt.d.ts} +5 -3
  18. package/dist/{driver-DiN-0Mnc.js → driver-CLYJOGDQ.js} +2 -2
  19. package/dist/{driver-DiN-0Mnc.js.map → driver-CLYJOGDQ.js.map} +1 -1
  20. package/dist/{driver-DRoWiadc.cjs → driver-Djr3BVvo.cjs} +2 -2
  21. package/dist/{driver-DRoWiadc.cjs.map → driver-Djr3BVvo.cjs.map} +1 -1
  22. package/dist/index.cjs +7 -7
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.cts +2 -2
  25. package/dist/index.d.ts +2 -2
  26. package/dist/index.js +7 -7
  27. package/dist/index.js.map +1 -1
  28. package/dist/{integration-DHxVpbxc.js → integration-C4Isp8lJ.js} +3 -3
  29. package/dist/{integration-DHxVpbxc.js.map → integration-C4Isp8lJ.js.map} +1 -1
  30. package/dist/{integration-DL6dLuu1.cjs → integration-Z6MsfFI7.cjs} +3 -3
  31. package/dist/{integration-DL6dLuu1.cjs.map → integration-Z6MsfFI7.cjs.map} +1 -1
  32. package/dist/integration.cjs +3 -3
  33. package/dist/integration.d.cts +1 -1
  34. package/dist/integration.d.ts +1 -1
  35. package/dist/integration.js +3 -3
  36. package/dist/{issue-DhrNdQNg.cjs → issue-DjK1xp5K.cjs} +106 -22
  37. package/dist/issue-DjK1xp5K.cjs.map +1 -0
  38. package/dist/{issue-DVaGQGeP.js → issue-W0hT8u8D.js} +81 -15
  39. package/dist/issue-W0hT8u8D.js.map +1 -0
  40. package/dist/local-sync.cjs +2 -2
  41. package/dist/local-sync.d.cts +1 -1
  42. package/dist/local-sync.d.ts +1 -1
  43. package/dist/local-sync.js +2 -2
  44. package/dist/{notification-AXT94XYC.js → notification-Bkjau6B6.js} +2 -2
  45. package/dist/{notification-AXT94XYC.js.map → notification-Bkjau6B6.js.map} +1 -1
  46. package/dist/{notification-DGv-_G9t.cjs → notification-DJfouMEb.cjs} +2 -2
  47. package/dist/{notification-DGv-_G9t.cjs.map → notification-DJfouMEb.cjs.map} +1 -1
  48. package/dist/react.cjs +2 -2
  49. package/dist/react.js +2 -2
  50. package/package.json +1 -1
  51. package/skills/doxum-runtime/SKILL.md +2 -0
  52. package/skills/doxum-runtime/references/guide.en.md +5 -2
  53. package/skills/doxum-runtime/references/guide.zh-CN.md +5 -2
  54. package/dist/access-B9XDWjHy.js.map +0 -1
  55. package/dist/access-EQ-XiFyl.cjs.map +0 -1
  56. package/dist/issue-DVaGQGeP.js.map +0 -1
  57. package/dist/issue-DhrNdQNg.cjs.map +0 -1
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["target.belongs","target.affected","anchor.equal","anchor.keys","anchor.matches","read","readAddress"],"sources":["../core/src/impact.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.ts","../core/src/runtime/readable.ts","../core/src/projection/select.ts","../core/src/projection/value-output.ts","../core/src/projection/processor.ts","../core/src/projection/projection-readable.ts","../core/src/projection/source.ts","../core/src/projection/runtime.ts"],"sourcesContent":["import type {\n CollectionId,\n CollectionPath,\n CollectionSelector,\n ObjectNode,\n ImpactTarget,\n PathPick,\n SchemaPath,\n} from './schema';\nimport { compilePath } from './schema';\nimport type { ChangeSet } from './changes';\nimport { AddressIndex, contains } from './address';\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 ObjectNode> = {\n readonly kind: 'incremental' | 'reset';\n affects(pick: PathPick<S>): boolean;\n collection<P extends CollectionPath>(\n pick: (path: SchemaPath<S['shape']>) => P\n ): CollectionImpact<CollectionId<P>>;\n};\ntype ImpactQueries = {\n affects(value: ImpactTarget): boolean;\n collection(selector: CollectionSelector): CollectionImpact<string>;\n};\nconst queries = new WeakMap<object, ImpactQueries>();\nexport const affectsTarget = (impact: object, value: ImpactTarget): boolean =>\n queries.get(impact)!.affects(value);\nexport const collectionImpact = <K extends string>(\n impact: object,\n selector: CollectionSelector<K>\n): CollectionImpact<K> => queries.get(impact)!.collection(selector) as CollectionImpact<K>;\nexport const createImpact = <S extends ObjectNode>(\n schema: 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 for (const change of changes.changes) {\n if (change.kind === 'members') {\n for (const member of change.members) values.add(change.at, true, member.key);\n if (change.order) orders.add(change.at, true);\n } else if (change.kind === 'tree') values.add(change.at, true);\n }\n }\n return values;\n };\n const cache = new Map<string, CollectionImpact<string>>();\n const implementation: ImpactQueries = {\n affects(value) {\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 collection(selector) {\n if (selector.schema !== schema)\n throw new TypeError('Collection belongs to another root model.');\n const key = JSON.stringify(selector.address),\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 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 && 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 (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' && contains(change.at, at)) {\n const result = { kind: 'reset' } as const;\n cache.set(key, result);\n return result;\n }\n if (!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 };\n const impact: DocumentImpact<S> = Object.freeze({\n kind: reset ? 'reset' : 'incremental',\n affects: (pick: PathPick<S>) =>\n implementation.affects(compilePath<S['shape']>(schema, 'value', pick)),\n collection: <P extends CollectionPath>(pick: (path: SchemaPath<S['shape']>) => P) =>\n implementation.collection(\n compilePath<S['shape']>(schema, 'collection', pick) as CollectionSelector\n ) as CollectionImpact<CollectionId<P>>,\n });\n queries.set(impact, implementation);\n return impact;\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';\nimport * as anchor from './anchor';\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) anchor.insert(parent, parent.length, value);\n else parent[index] = value;\n } else if (index >= 0) anchor.remove(parent, index);\n } else if (!present) delete parent[key];\n else if (Object.hasOwn(parent, key)) parent[key] = value;\n else\n Object.defineProperty(parent, key, {\n value,\n writable: true,\n configurable: true,\n enumerable: true,\n });\n};\n\nexport const orderOf = (node: DocumentNode, value: unknown): string[] => {\n if (node.kind === 'list') return (value as unknown[]).map(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') anchor.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';\nimport {\n AddressIndex,\n contains,\n resolveValue,\n resolveLocated,\n memberKey,\n type ResolvedContainer,\n type ResolvedTreeContainer,\n type CompiledMember,\n compiledShape,\n type FixedLayout,\n} from '../address';\nimport * as anchor from './anchor';\nimport { copyValue, equalValue } from '../schema-value';\nimport type { MutableTree, MutableTreeNode } from './tree';\nimport { profile } from '../profile';\nimport { sealChanges } from './changes';\nimport { installMember, installOrder, orderOf, type CanonicalState } 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 copyNode = (node: MutableTreeNode): MutableTreeNode => ({\n ...node,\n children: [...node.children],\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 (node.kind !== 'field' && beforePresent === afterPresent && equalValue(node, before, after))\n return;\n const value = afterPresent ? (node.kind === 'field' ? after : copyValue(node, after)) : 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' && !anchor.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 ? copyValue(member.node, member.value) : undefined;\n if (!at.length) return value;\n const location = resolveLocated(schema, root, at);\n if (!location) throw new Error('Cannot restore an unresolved member.');\n installMember(location.parent, location.key, member.present, value);\n return root;\n }\n const location = resolveValue(schema, root, at);\n if (!location) throw new Error('Cannot restore an unresolved subtree.');\n if (fact.kind === 'order') 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 installMember(tree.nodes, id, node !== undefined, node && copyNode(node));\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 = 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 = 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 ? anchor.keys(fact.value as unknown[], fact.node.keyOf)\n : (fact.value as { ids: string[] }).ids;\n if (!anchor.equal(fact.order, current)) {\n const after = 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, state: CanonicalState, changes: Change[]): void => {\n const location = resolveValue(state.schema, state.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 (\n before &&\n after &&\n before.parentId === after.parentId &&\n anchor.equal(before.children, after.children) &&\n Object.hasOwn(before, 'value') === Object.hasOwn(after, 'value') &&\n equalValue(node.value, before.value, after.value)\n )\n continue;\n nodes.push(\n !before\n ? { id, kind: 'added', after: copyNode(after!) }\n : !after\n ? { id, kind: 'removed', before }\n : { id, kind: 'updated', before, after: copyNode(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: 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 && 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 (contains(at, memberAt))\n children.push({ kind: 'member', at: memberAt, group: fact, member });\n }\n } else if (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: 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: 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: 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 = orderOf(container.node, container.value);\n profile.recorder('orderSnapshots');\n profile.recorder('orderItems', group.order.length);\n }\n tree(container: 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(id, Object.hasOwn(tree.nodes, id) ? copyNode(tree.nodes[id]) : undefined);\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 installMember(\n fact.parent,\n memberKey(fact, member.key),\n member.present,\n member.present ? 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) installOrder(fact.node, fact.value, fact.order);\n }\n seal(): ChangeSet {\n if (this.resetBefore) {\n if (equalValue(this.state.schema, this.resetBefore.value, this.state.document))\n return sealChanges([]);\n profile.recorder('sealed');\n return sealChanges([\n {\n kind: 'reset',\n before: this.resetBefore.value,\n after: 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 = 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';\nimport {\n createAddressResolver,\n resolveContainer,\n resolveTreeContainer,\n resolveValue,\n memberKey,\n type CompiledMember,\n type ResolvedContainer,\n type ResolvedTreeContainer,\n} from '../address';\nimport { checkKey, checkValue, copyValue } from '../schema-value';\nimport { ChangeRecorder } from './recorder';\nimport { installMember, type CanonicalState } from './state';\nimport { fail, invalidValue } 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: CanonicalState) {\n this.recorder = new ChangeRecorder(state);\n this.resolver = createAddressResolver(state.schema, state.document);\n this.resolvedRoot = state.document;\n }\n validate(node: DocumentNode, value: unknown, at: DocumentAddress): void {\n const issue = checkValue(node, value, at);\n if (issue) invalidValue(issue);\n }\n resolveContainer(at: DocumentAddress): ResolvedContainer {\n return (\n this.resolver.container(this.identity, this.generation, at) ??\n fail(at, 'invalid-address', 'Container does not exist.')\n );\n }\n /** Bind access-resolved canonical facts without walking the address again. */\n bind(at: DocumentAddress, node: DocumentNode | undefined, value: unknown): ResolvedContainer {\n return (\n resolveContainer(this.identity, this.generation, at, node, value) ??\n fail(at, 'invalid-address', 'Container does not exist.')\n );\n }\n bindTree(\n at: DocumentAddress,\n node: DocumentNode | undefined,\n value: unknown\n ): ResolvedTreeContainer {\n return (\n resolveTreeContainer(this.identity, this.generation, at, node, value) ??\n fail(at, 'invalid-tree', 'Expected a tree.')\n );\n }\n resolveTree(at: DocumentAddress): ResolvedTreeContainer {\n const location = 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 = 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: 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 fail(\n container.at.concat(key),\n 'invalid-value',\n 'Replace fields, variants, or collection entries; edit object members individually.'\n );\n this.writeLocatedMember(container, key, member, memberKey(container, key), value, 'set');\n }\n removeMember(container: ResolvedContainer, key: string): void {\n this.writeMember(this.refresh(container), key, undefined, 'remove');\n }\n private refresh(container: ResolvedContainer): ResolvedContainer {\n if (container.owner !== this.identity)\n return 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: 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 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: ResolvedContainer,\n key: string,\n value: unknown,\n operation: 'set' | 'remove',\n physicalKey = 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: 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 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 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 issue = checkKey(parentNode.key, key, []);\n if (issue)\n return fail(container.at.concat(key, ...issue.address), 'invalid-key', issue.message);\n }\n if (present) {\n if (node.kind === 'field') {\n const issue = checkValue(node, value, []);\n if (issue) return invalidValue(issue, container.at.concat(key, ...issue.address));\n } else this.validate(node, value, container.at.concat(key));\n if (parentNode.kind === 'list' && parentNode.keyOf(value) !== key)\n return 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 ? (node.kind === 'field' ? value : copyValue(node, value)) : undefined;\n 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 = 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 { installOrder, installMember, orderOf } from '../state';\nimport * as anchor from '../anchor';\nimport { fail } from '../issue';\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 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 = node.kind === 'table' ? Object.keys(container.parent) : orderOf(node, current);\n if (!anchor.matches(change.order[side], keys))\n return fail(\n change.at,\n 'invalid-changes',\n 'Order must contain exactly the resulting keys.'\n );\n 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 (!anchor.matches(ids, Object.keys(container.parent)))\n return 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 installMember(\n current.nodes,\n item.id,\n next !== undefined,\n next && { ...next, children: [...next.children] }\n );\n }\n session.validate(node, current, change.at);\n session.invalidate();\n }\n }\n}\n","import type { ObjectNode, Infer, PathPick } from './schema';\nimport { compilePath } from './schema';\nimport { contains, debugKey, overlaps, read, resolveAddress } from './address';\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 { decodeChanges } from './mutation/changes';\nimport { MutationRejected, fail } from './mutation/issue';\nimport type { ChangeSet } from './changes';\nimport { checkValue, copyValue, ParseError } 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 OperationResult,\n TransactionResult,\n} from './runtime/contract';\nimport { bindRuntimeAccess, accessOf } from './runtime/access';\nimport { assertRuntimeWritable, bindRuntimeDriver, disposeRuntimeDriver } from './runtime/driver';\nimport {\n bindDocumentReadable,\n createNotification,\n disposeNotification,\n notify,\n subscribeRoot,\n subscribeTargets,\n type RuntimeNotification,\n} from './runtime/notification';\n\nexport const createDocument = <S extends ObjectNode>(input: {\n readonly schema: S;\n readonly initial: Infer<S>;\n readonly history?: { readonly capacity?: number } | false;\n}): DocumentRuntime<S> => {\n if (input.schema.kind !== 'object')\n throw new TypeError('Document schema must be a root object node.');\n const invalid = checkValue(input.schema, input.initial);\n if (invalid) throw new ParseError(invalid);\n const state = {\n schema: input.schema,\n document: copyValue(input.schema, input.initial) as Infer<S>,\n disposed: false,\n };\n let revision = 0,\n busy = false;\n let runtime!: DocumentRuntime<S>, notification!: RuntimeNotification<S>;\n const idle = () => {\n if (state.disposed) throw new DocumentDisposedError();\n if (busy || accessOf(runtime).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(input.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: notify(notification, 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 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 address: {\n resolve: at => resolveAddress(input.schema, at, state.document),\n read: at => read(state.document, at, input.schema),\n contains,\n overlaps,\n debugKey,\n },\n revision: () => revision,\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 mutate(\n { kind: 'apply', source: options?.source ?? 'local' },\n options?.history ?? true,\n session => {\n if (!options || options.expectedRevision !== revision)\n fail([], 'baseline-mismatch', 'apply requires the current expectedRevision.');\n replay.apply(session, decodeChanges(inputChanges), 'forward');\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 copyValue(input.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 subscribeRoot(notification, 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 subscribeTargets(\n notification,\n picks.map(p => compilePath<S['shape']>(input.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 disposeNotification(notification);\n } finally {\n history.dispose();\n disposeRuntimeDriver(runtime);\n }\n },\n };\n bindRuntimeAccess(runtime, state);\n bindRuntimeDriver(runtime);\n notification = createNotification(runtime);\n bindDocumentReadable(history.api, runtime);\n return runtime;\n};\n","import type { ObjectNode } from '../schema';\nimport type { DocumentReadable, DocumentRuntime } from './contract';\nimport { accessOf, bindRuntimeAccess } from './access';\nimport { shareNotification } from './notification';\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 asReadable = <TSchema extends ObjectNode>(\n runtime: DocumentRuntime<TSchema>\n): DocumentReadable<TSchema> => {\n const readable: DocumentReadable<TSchema> = {\n address: runtime.address,\n revision: runtime.revision,\n subscribe: runtime.subscribe,\n };\n bindRuntimeAccess(readable, accessOf(runtime));\n shareNotification(runtime, readable);\n return Object.freeze(readable);\n};\n","import type { ObjectNode } from '../schema';\nimport type { Read } from '../access/scope';\nimport type { DocumentReadable } from '../runtime/contract';\nimport { readWith } from '../runtime/access';\n\nexport type DocumentSelector<TSchema extends ObjectNode, TResult> = (\n read: Read<TSchema>\n) => TResult;\n\nexport const read = <TSchema extends ObjectNode, TResult>(\n runtime: DocumentReadable<TSchema>,\n selector: DocumentSelector<TSchema, TResult>\n): TResult => readWith(runtime, selector);\n","import { profile } from '../profile';\nimport type { ValueContext } from './contract';\nimport { assertScope } from './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> = {\n begin(active: () => boolean, initialize: boolean): ValueOutputEvaluation<T>;\n seal(reset: boolean, isEqual: (previous: T, next: T) => boolean): boolean;\n context(active: () => boolean, cause: unknown): ValueContext<T>;\n current(check: () => void): T;\n revision(): number;\n reset(): boolean;\n publish(): void;\n emit(call: (listener: () => void) => void): void;\n clear(): void;\n release(): void;\n subscribe(listener: () => void): void;\n unsubscribe(listener: () => void): void;\n};\n\n/** Owns staged and published state for one scalar Projection output. */\nexport const createValueOutput = <T>(): 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\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 begin,\n seal,\n context: (active, cause) => {\n assertScope(active);\n return Object.freeze({\n kind: 'value' as const,\n value: next,\n revision,\n reset,\n cause,\n });\n },\n current: check => {\n 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 clear: () => {\n staged = unset;\n next = value;\n changed = false;\n reset = false;\n },\n release: () => {\n listeners.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 => listeners.add(listener),\n unsubscribe: listener => listeners.delete(listener),\n };\n};\n","import { profile } from '../profile';\nimport { createCollectionOutput, type CollectionOutputState } from './collection-output';\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 './value-output';\n\ntype BoundOutput =\n | {\n readonly kind: 'value';\n readonly definition: Extract<OutputDefinition, { readonly kind: 'value' }>;\n readonly state: ValueOutputState<unknown>;\n readonly output: OutputRecord;\n }\n | {\n readonly kind: 'collection';\n readonly definition: Extract<OutputDefinition, { readonly kind: 'collection' }>;\n readonly state: CollectionOutputState<string, unknown>;\n readonly output: OutputRecord;\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 const output: OutputRecord = {\n kind: 'value',\n get owner() {\n return processor;\n },\n consumers: new Set(),\n context: active => state.context(active, cause),\n current: () => state.current(check),\n revision: state.revision,\n reset: state.reset,\n subscribe: listener => {\n check();\n const wrapped = () => listener();\n state.subscribe(wrapped);\n return () => state.unsubscribe(wrapped);\n },\n emit: state.emit,\n clear: state.clear,\n release: state.release,\n };\n return { kind: 'value', definition: outputDefinition, state, output };\n }\n const state = createCollectionOutput<string, unknown>();\n const output: OutputRecord = {\n kind: 'collection',\n get owner() {\n return processor;\n },\n consumers: new Set(),\n context: active => state.context(active, cause),\n current: () => state.current(check),\n revision: state.revision,\n reset: state.reset,\n subscribe: listener => {\n check();\n const wrapped = (change: import('./contract').CollectionChange<string, unknown>) =>\n listener(change);\n state.subscribe(wrapped);\n return () => state.unsubscribe(wrapped);\n },\n emit: state.emit,\n clear: state.clear,\n release: state.release,\n };\n return { kind: 'collection', definition: outputDefinition, state, output };\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.output);\n }\n return Object.freeze(changed);\n };\n\n const run = (reset: boolean, runCause: unknown): 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 let outputs = begin(scopeActive, reset);\n if (!instance) instance = definition.create();\n profile.materialized[reset ? 'rebuilt' : 'updated']();\n let result = instance.evaluate({ reset, cause: runCause, sources, outputs });\n assertSynchronous(result);\n if (result?.kind === 'rebuild') {\n if (reset) throw new TypeError('Initial or reset projection processor cannot rebuild.');\n instance.release?.();\n instance = definition.create();\n outputs = begin(scopeActive, true);\n result = instance.evaluate({ reset: true, cause: runCause, sources, outputs });\n assertSynchronous(result);\n if (result?.kind === 'rebuild')\n throw new TypeError('Reset projection processor cannot rebuild again.');\n return seal(true);\n }\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.output)),\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 instance?.release?.();\n instance = undefined;\n bound.forEach(entry => {\n entry.output.consumers.clear();\n entry.state.release();\n });\n cause = undefined;\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 } catch (error) {\n processor.release();\n throw error;\n }\n scheduler.addProcessor(processor);\n return processor;\n};\n","import type { Unsubscribe } from '../runtime/contract';\nimport { collectionChangeBetween } from './collection-output';\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 (\n selection.all &&\n (change.added.length || change.removed.length || change.updated.length || change.order)\n )\n return true;\n if (selection.structure && (change.added.length || change.removed.length || change.order))\n return true;\n for (const key of selection.keys) {\n if (\n change.added.some(entry => entry.key === key) ||\n change.removed.some(entry => entry.key === key) ||\n change.updated.some(entry => entry.key === key)\n )\n return true;\n }\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 = collectionChangeBetween(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 { read as readAddress, nodeAt } from '../address';\nimport { collectionAccess, snapshot } from '../access/scope';\nimport { affectsTarget, collectionImpact } from '../impact';\nimport { accessOf } from '../runtime/access';\nimport { attachProjection, documentReadableOwner } from '../runtime/notification';\nimport type { DocumentCommit, DocumentReadable, Unsubscribe } from '../runtime/contract';\nimport type { CollectionSelector, ObjectNode, ValueSelector } from '../schema';\nimport { collectionEntryNode } from '../schema';\nimport { copyValue, equalValue } from '../schema-value';\nimport {\n createCollectionOutput,\n mapRead,\n stageCollectionRead,\n type CollectionOutputState,\n} from './collection-output';\nimport type {\n CollectionChange,\n CollectionRead,\n ExternalCollectionSource,\n ExternalValueSource,\n} from './contract';\nimport { ProjectionDisposedError, ProjectionError } from './contract';\nimport type { SourceDefinition } from './definition';\nimport type { Readable } from './readable';\nimport {\n assertScope,\n assertSynchronous,\n type OutputRecord,\n type Scheduler,\n type SourceBoundaryRecord,\n} from './scheduler';\nimport { createValueOutput, type ValueOutputState } from './value-output';\n\nexport type KeyedInputDraft<K extends string, V> = {\n get(key: K): V | undefined;\n has(key: K): boolean;\n set(key: K, value: V): void;\n remove(key: K): void;\n};\n\nexport type SourceWrite =\n | { readonly kind: 'value'; set(value: unknown): void }\n | {\n readonly kind: 'collection';\n update(run: (draft: KeyedInputDraft<string, unknown>) => void): void;\n };\n\nexport type SourceMaterialization = {\n readonly producer: SourceBoundaryRecord;\n readonly output: OutputRecord;\n readonly write?: SourceWrite;\n};\n\ntype 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\ntype ValueBoundary = SourceMaterialization & {\n readonly setLatest: (value: unknown) => void;\n readonly mark: (metadata?: SourceMark) => void;\n readonly fail: (cause: unknown) => void;\n readonly detach: (cleanup: Unsubscribe) => void;\n};\n\ntype CollectionBoundary = SourceMaterialization & {\n readonly mark: (metadata?: CollectionMark) => void;\n readonly fail: (cause: unknown) => void;\n readonly detach: (cleanup: Unsubscribe) => void;\n};\n\nconst sourceError = (source: SourceBoundaryRecord, cause: unknown): ProjectionError =>\n new ProjectionError('source', source.name, [source.outputs[0].revision()], cause);\n\nconst createValueBoundary = (\n scheduler: Scheduler,\n name: string,\n initial: unknown,\n equality: (previous: unknown, next: unknown) => boolean\n): ValueBoundary => {\n const state: ValueOutputState<unknown> = createValueOutput();\n let boundary!: SourceBoundaryRecord;\n let latest = initial;\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\n const output: OutputRecord = {\n kind: 'value',\n get owner() {\n return boundary;\n },\n consumers: new Set(),\n context: active => state.context(active, contextCause),\n current: () => state.current(check),\n revision: state.revision,\n reset: state.reset,\n subscribe: listener => {\n check();\n const wrapped = () => listener();\n state.subscribe(wrapped);\n return () => state.unsubscribe(wrapped);\n },\n emit: state.emit,\n clear: state.clear,\n release: state.release,\n };\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(latest);\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 state.clear();\n pendingReset = false;\n pendingCause = undefined;\n contextCause = undefined;\n recovering = false;\n },\n release: () => {\n cleanup?.();\n cleanup = undefined;\n state.release();\n output.consumers.clear();\n },\n };\n\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\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(boundary, cause);\n recovering = false;\n scheduler.capture(boundary);\n };\n return {\n producer: boundary,\n output,\n setLatest: value => {\n latest = value;\n },\n mark,\n fail,\n detach: next => {\n cleanup = next;\n },\n };\n};\n\nconst createCollectionBoundary = (\n scheduler: Scheduler,\n name: string,\n readLatest: (active: () => boolean) => CollectionRead<string, unknown>,\n equality: (previous: unknown, next: unknown) => boolean\n): CollectionBoundary => {\n const state: CollectionOutputState<string, unknown> = createCollectionOutput();\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\n const output: OutputRecord = {\n kind: 'collection',\n get owner() {\n return boundary;\n },\n consumers: new Set(),\n context: active => state.context(active, contextCause),\n current: () => state.current(check),\n revision: state.revision,\n reset: state.reset,\n subscribe: listener => {\n check();\n const wrapped = (change: CollectionChange<string, unknown>) => listener(change);\n state.subscribe(wrapped);\n return () => state.unsubscribe(wrapped);\n },\n emit: state.emit,\n clear: state.clear,\n release: state.release,\n };\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),\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 state.clear();\n pendingReset = false;\n pendingCause = undefined;\n contextCause = undefined;\n recovering = false;\n fullScan = false;\n orderMayChange = false;\n candidates.clear();\n },\n release: () => {\n cleanup?.();\n cleanup = undefined;\n state.release();\n output.consumers.clear();\n },\n };\n\n scheduler.initialize(() => {\n let active = true;\n try {\n stageCollectionRead(\n state,\n readLatest(() => active),\n () => active,\n {\n reset: true,\n isEqual: equality,\n }\n );\n state.publish();\n state.clear();\n } finally {\n active = false;\n }\n });\n scheduler.addSource(boundary);\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(boundary, 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 DocumentBinding = {\n matches(commit: DocumentCommit<ObjectNode>): boolean;\n capture(commit: DocumentCommit<ObjectNode>): void;\n dispose(): void;\n};\n\ntype DocumentConnection = {\n add(binding: DocumentBinding): Unsubscribe;\n close(): void;\n};\n\ntype ValueMember = {\n readonly boundary: ValueBoundary;\n receive(value: unknown, metadata?: SourceMark): void;\n};\n\nexport const createSourceRegistry = (scheduler: Scheduler) => {\n const documents = new Map<object, DocumentConnection>();\n const readables = new Map<object, { members: Set<ValueMember>; close(): void }>();\n const externalValues = new WeakMap<object, { members: Set<ValueMember>; close(): void }>();\n const externalCollections = new WeakMap<\n object,\n { members: Set<CollectionBoundary>; close(): void }\n >();\n\n const documentConnection = <S extends ObjectNode>(\n runtime: DocumentReadable<S>\n ): DocumentConnection => {\n const state = accessOf(runtime);\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 guard = (locked: boolean) => {\n state.projectionLocks = (state.projectionLocks ?? 0) + (locked ? 1 : -1);\n };\n scheduler.guards.add(guard);\n let closed = false;\n let detach: Unsubscribe = () => undefined;\n const connection: DocumentConnection = {\n add(binding) {\n if (closed) throw new Error('Document projection connection is closed.');\n bindings.add(binding);\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n bindings.delete(binding);\n if (!bindings.size) connection.close();\n };\n },\n close() {\n if (closed) return;\n closed = true;\n detach();\n bindings.clear();\n scheduler.guards.delete(guard);\n documents.delete(state);\n },\n };\n detach = attachProjection(runtime, {\n capture: commit => {\n for (const binding of bindings)\n if (binding.matches(commit as DocumentCommit<ObjectNode>))\n binding.capture(commit as DocumentCommit<ObjectNode>);\n },\n settle: scheduler.settle,\n flush: scheduler.flush,\n dispose: () => {\n for (const binding of bindings) binding.dispose();\n scheduler.run();\n },\n });\n documents.set(state, connection);\n return connection;\n };\n\n const valueInput = (definition: SourceDefinition): SourceMaterialization => {\n if (definition.source.kind !== 'value-input') throw new Error('Invalid value input source.');\n const source = definition.source;\n const boundary = createValueBoundary(\n scheduler,\n 'projection input',\n source.initial,\n source.equality\n );\n return {\n ...boundary,\n write: {\n kind: 'value',\n set(value) {\n scheduler.assertIdle();\n boundary.setLatest(value);\n boundary.mark();\n scheduler.run();\n },\n },\n };\n };\n\n const collectionInput = (definition: SourceDefinition): SourceMaterialization => {\n if (definition.source.kind !== 'collection-input')\n throw new Error('Invalid collection input source.');\n const values = new Map(definition.source.initial);\n const boundary = createCollectionBoundary(\n scheduler,\n 'projection collection input',\n () => mapRead(values),\n definition.output.equality\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: KeyedInputDraft<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 let changed = false;\n for (const operation of operations) {\n const present = values.has(operation.key);\n if (operation.kind === 'set') {\n if (present && Object.is(values.get(operation.key), operation.value)) continue;\n structural ||= !present;\n values.set(operation.key, operation.value);\n } else {\n if (!present) continue;\n structural = true;\n values.delete(operation.key);\n }\n candidates.add(operation.key);\n changed = true;\n }\n if (!changed) return;\n boundary.mark({ candidates, orderMayChange: structural });\n scheduler.run();\n },\n },\n };\n };\n\n const documentValue = (definition: SourceDefinition): SourceMaterialization => {\n if (definition.source.kind !== 'document-value')\n throw new Error('Invalid document value source.');\n const { document, selector } = definition.source;\n const state = accessOf(document);\n const address = selector?.address ?? Object.freeze([]);\n const schemaNode = () => nodeAt(state.schema, address, state.document);\n const read = () => {\n if (state.disposed) throw new Error('Document has been disposed.');\n const node = schemaNode();\n if (!node) return undefined;\n const value = selector ? readAddress(state.document, address, state.schema) : state.document;\n return copyValue(node, value);\n };\n const initial = read();\n const boundary = createValueBoundary(scheduler, 'document source', initial, (left, right) => {\n const node = schemaNode();\n return node ? equalValue(node, left, right) : Object.is(left, right);\n });\n const remove = documentConnection(document).add({\n matches: commit => !selector || affectsTarget(commit.impact, selector),\n capture: commit => {\n try {\n boundary.setLatest(read());\n boundary.mark({ reset: commit.impact.kind === 'reset' });\n } catch (cause) {\n boundary.fail(cause);\n }\n },\n dispose: () => boundary.fail(new Error('Document has been disposed.')),\n });\n boundary.detach(remove);\n return boundary;\n };\n\n const documentCollection = (definition: SourceDefinition): SourceMaterialization => {\n if (definition.source.kind !== 'document-collection')\n throw new Error('Invalid document collection source.');\n const { document, selector } = definition.source;\n const state = accessOf(document);\n const read = (active: () => boolean): CollectionRead<string, unknown> => {\n if (state.disposed) throw new Error('Document has been disposed.');\n const raw = collectionAccess({ state, active }, selector.address) as CollectionRead<\n string,\n unknown\n >;\n const snapshots = new Map<string, unknown>();\n return Object.freeze({\n get: (key: string) => {\n assertScope(active);\n if (!snapshots.has(key)) snapshots.set(key, snapshot(raw.get(key)));\n return snapshots.get(key);\n },\n has: (key: string) => {\n assertScope(active);\n return raw.has(key);\n },\n ids: () => {\n assertScope(active);\n return raw.ids();\n },\n });\n };\n const collectionNode = () => nodeAt(state.schema, selector.address, state.document);\n const boundary = createCollectionBoundary(\n scheduler,\n 'document collection source',\n read,\n (left, right) => {\n const node = collectionNode();\n const entry = node && collectionEntryNode(node);\n return entry ? equalValue(entry, left, right) : Object.is(left, right);\n }\n );\n const remove = documentConnection(document).add({\n matches: commit => affectsTarget(commit.impact, selector),\n capture: commit => {\n const impact = collectionImpact(commit.impact, selector);\n if (impact.kind === 'reset') {\n boundary.mark({ reset: true });\n return;\n }\n const candidates = new Set<string>([...impact.added, ...impact.updated, ...impact.removed]);\n boundary.mark({\n candidates,\n orderMayChange: Boolean(impact.added.size || impact.removed.size || impact.orderChanged),\n });\n },\n dispose: () => boundary.fail(new Error('Document has been disposed.')),\n });\n boundary.detach(remove);\n return boundary;\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 initial = readable.current();\n const boundary = createValueBoundary(scheduler, 'external readable', initial, equality);\n const member: ValueMember = {\n boundary,\n receive(value, metadata) {\n initial = value;\n boundary.setLatest(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 unsubscribe?.();\n detachDocument?.();\n readables.delete(readable);\n },\n };\n const owner = documentReadableOwner(readable);\n if (owner) {\n detachDocument = documentConnection(owner).add({\n matches: () => true,\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 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 void initial;\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 const boundary = createValueBoundary(scheduler, 'external source', source.current(), equality);\n const member: ValueMember = {\n boundary,\n receive(value, metadata) {\n boundary.setLatest(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 unsubscribe?.();\n externalValues.delete(source);\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 (cause) {\n created.close();\n throw cause;\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 );\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 unsubscribe?.();\n externalCollections.delete(source);\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 (cause) {\n created.close();\n throw cause;\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 'value-input':\n return valueInput(definition);\n case 'collection-input':\n return collectionInput(definition);\n case 'document-value':\n return documentValue(definition);\n case 'document-collection':\n return documentCollection(definition);\n case 'readable':\n return readable(definition);\n case 'external-value':\n return externalValue(definition);\n case 'external-collection':\n return externalCollection(definition);\n }\n },\n dispose() {\n documents.forEach(connection => connection.close());\n readables.forEach(connection => connection.close());\n documents.clear();\n readables.clear();\n },\n };\n};\n","import type { Unsubscribe } from '../runtime/contract';\nimport {\n incremental,\n type IncrementalCollectionProcessor,\n type IncrementalGroupDefine,\n type IncrementalGroupOutputTree,\n type IncrementalGroupProcessor,\n type IncrementalValueProcessor,\n} from './advanced';\nimport { collectionView, mapRead, snapshotCollectionView } from './collection-output';\nimport type { CollectionChange, CollectionRead } from './contract';\nimport { ProjectionDisposedError } from './contract';\nimport {\n derive,\n input,\n isProjection,\n ownProjection,\n producerOf,\n projectionRef,\n type Input,\n type ProducerDefinition,\n type Projection,\n} from './definition';\nimport { createProcessor } from './processor';\nimport {\n createDirectReadable,\n createSelectorReadable,\n isMapLike,\n type ProjectionReadableSource,\n} from './projection-readable';\nimport type { Readable } from './readable';\nimport { createScheduler, type OutputRecord, type ProducerRecord } from './scheduler';\nimport { createSourceRegistry, type KeyedInputDraft, type SourceWrite } from './source';\n\ntype KeyedDraft<K extends string, V> = {\n get(key: K): V | undefined;\n has(key: K): boolean;\n set(key: K, value: V): void;\n remove(key: K): void;\n};\n\nexport type ProjectionRuntime = {\n get<T>(projection: Projection<T, unknown>): T;\n readable<T>(projection: Projection<T, unknown>): Readable<T>;\n readable<T, R>(\n projection: Projection<T, unknown>,\n selector: (value: T) => R,\n equality?: (previous: R, next: R) => boolean\n ): Readable<R>;\n set<T>(input: Input<T>, value: T): void;\n update<K extends string, V>(\n input: Input<ReadonlyMap<K, V>, CollectionChange<K, V>>,\n run: (draft: KeyedDraft<K, V>) => void\n ): void;\n batch<T>(run: () => T): T;\n batch<T>(options: { readonly cause?: unknown }, run: () => T): T;\n scope(): ProjectionScope;\n dispose(): void;\n};\n\nexport type ProjectionScope = {\n readonly input: typeof input;\n readonly derive: typeof derive;\n readonly incremental: typeof incremental;\n get<T>(projection: Projection<T, unknown>): T;\n readable<T>(projection: Projection<T, unknown>): Readable<T>;\n readable<T, R>(\n projection: Projection<T, unknown>,\n selector: (value: T) => R,\n equality?: (previous: R, next: R) => boolean\n ): Readable<R>;\n set<T>(input: Input<T>, value: T): void;\n update<K extends string, V>(\n input: Input<ReadonlyMap<K, V>, CollectionChange<K, V>>,\n run: (draft: KeyedDraft<K, V>) => void\n ): void;\n batch: ProjectionRuntime['batch'];\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 materialized.set(definition, result);\n rememberScoped(definition, requester);\n return result;\n };\n\n const resolveOutput = (\n projection: Projection<unknown, unknown>,\n requester?: ScopeState\n ): 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 get = <T>(projection: Projection<T, unknown>, requester?: ScopeState): T =>\n publicCurrent(resolveOutput(projection as Projection<unknown, unknown>, requester)) as T;\n\n const readableSource = <T>(\n projection: Projection<T, unknown>,\n requester?: ScopeState\n ): ProjectionReadableSource<T> => {\n const output = resolveOutput(projection as Projection<unknown, unknown>, requester);\n return Object.freeze({\n kind: output.kind,\n current: () => get(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, unknown>,\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 readable<T>(projection: Projection<T, unknown>): Readable<T>;\n function readable<T, R>(\n projection: Projection<T, unknown>,\n selector: (value: T) => R,\n equality?: (previous: R, next: R) => boolean\n ): Readable<R>;\n function readable<T, R>(\n projection: Projection<T, unknown>,\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 = (\n target: Projection<unknown, unknown>,\n requester?: ScopeState\n ): 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 setInput = <T>(target: Input<T>, value: T, requester?: ScopeState): void => {\n const write = inputWrite(target as Projection<unknown, unknown>, requester);\n if (write.kind !== 'value') throw new TypeError('Projection is not a value input.');\n write.set(value);\n };\n\n const updateInput = <K extends string, V>(\n target: Input<ReadonlyMap<K, V>, CollectionChange<K, V>>,\n run: (draft: KeyedDraft<K, V>) => void,\n requester?: ScopeState\n ): void => {\n const write = inputWrite(target as Projection<unknown, unknown>, requester);\n if (write.kind !== 'collection') throw new TypeError('Projection is not a collection input.');\n write.update(run as (draft: KeyedInputDraft<string, unknown>) => void);\n };\n\n function batch<T>(run: () => T): T;\n function batch<T>(options: { readonly cause?: unknown }, run: () => T): T;\n function batch<T>(\n optionsOrCallback: { readonly cause?: unknown } | (() => T),\n maybeCallback?: () => T\n ): T {\n return typeof optionsOrCallback === 'function'\n ? scheduler.batch(optionsOrCallback)\n : scheduler.batch(optionsOrCallback, maybeCallback);\n }\n\n const disposeScope = (state: ScopeState): void => {\n if (!state.active) return;\n scheduler.assertIdle();\n state.active = false;\n state.subscriptions.forEach(unsubscribe => unsubscribe());\n state.subscriptions.clear();\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 scheduler.releaseProducer(current.record);\n materialized.delete(definition);\n }\n state.materialized.length = 0;\n scopes.delete(state);\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 const own = <P extends Projection<unknown, unknown>>(projection: P): P => {\n assertActive();\n return ownProjection(projection, state);\n };\n const ownOutputTree = <T>(tree: T): T => {\n if (isProjection(tree)) return own(tree as Projection<unknown, unknown>) as T;\n if (!tree || typeof tree !== 'object')\n throw new TypeError('Incremental group output tree must be an object.');\n for (const value of Object.values(tree as Record<string, unknown>)) ownOutputTree(value);\n return tree;\n };\n\n const scopedInput: typeof input = Object.assign(\n <T>(initial: T, equality?: (previous: T, next: T) => boolean) =>\n own(input(initial, equality)),\n {\n collection: <K extends string, V>(initial?: ReadonlyMap<K, V>) =>\n own(input.collection(initial)),\n }\n );\n const scopedDerive: typeof derive = (dependencies, compute, equality) =>\n own(derive(dependencies, compute, equality));\n const scopedIncremental: typeof incremental = Object.assign(\n <const D extends readonly Projection<unknown, unknown>[], T>(\n dependencies: D,\n processor: IncrementalValueProcessor<D, T>\n ) => own(incremental(dependencies, processor)),\n {\n collection: <const D extends readonly Projection<unknown, unknown>[], K extends string, V>(\n dependencies: D,\n processor: IncrementalCollectionProcessor<D, K, V>\n ) => own(incremental.collection(dependencies, processor)),\n group: <\n const D extends readonly Projection<unknown, unknown>[],\n const O extends IncrementalGroupOutputTree,\n >(\n dependencies: D,\n defineOutputs: (define: IncrementalGroupDefine) => O,\n processor: IncrementalGroupProcessor<D, O>\n ) => ownOutputTree(incremental.group(dependencies, defineOutputs, processor)),\n }\n );\n\n function scopeReadable<T>(projection: Projection<T, unknown>): Readable<T>;\n function scopeReadable<T, R>(\n projection: Projection<T, unknown>,\n selector: (value: T) => R,\n equality?: (previous: R, next: R) => boolean\n ): Readable<R>;\n function scopeReadable<T, R>(\n projection: Projection<T, unknown>,\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 scopeBatch<T>(run: () => T): T;\n function scopeBatch<T>(options: { readonly cause?: unknown }, run: () => T): T;\n function scopeBatch<T>(\n optionsOrCallback: { readonly cause?: unknown } | (() => T),\n maybeCallback?: () => T\n ): T {\n assertActive();\n return typeof optionsOrCallback === 'function'\n ? batch(optionsOrCallback)\n : batch(optionsOrCallback, maybeCallback!);\n }\n\n return Object.freeze({\n input: scopedInput,\n derive: scopedDerive,\n incremental: scopedIncremental,\n get: <T>(projection: Projection<T, unknown>) => {\n assertActive();\n return get(projection, state);\n },\n readable: scopeReadable,\n set: <T>(target: Input<T>, value: T) => {\n assertActive();\n setInput(target, value, state);\n },\n update: <K extends string, V>(\n target: Input<ReadonlyMap<K, V>, CollectionChange<K, V>>,\n run: (draft: KeyedDraft<K, V>) => void\n ) => {\n assertActive();\n updateInput(target, run, state);\n },\n batch: scopeBatch,\n dispose: () => disposeScope(state),\n });\n };\n\n return Object.freeze({\n get,\n readable,\n set: setInput,\n update: updateInput,\n batch,\n scope: createScope,\n dispose: () => {\n if (!scheduler.active) return;\n scheduler.assertIdle();\n for (const scope of scopes) {\n scope.active = false;\n scope.subscriptions.forEach(unsubscribe => unsubscribe());\n scope.subscriptions.clear();\n scope.materialized.length = 0;\n }\n scopes.clear();\n sources.dispose();\n scheduler.dispose();\n },\n });\n};\n"],"mappings":";;;;;;AAmCA,MAAM,0BAAU,IAAI,SAAgC;AACpD,MAAa,iBAAiB,QAAgB,UAC5C,QAAQ,IAAI,OAAO,CAAE,QAAQ,MAAM;AACrC,MAAa,oBACX,QACA,aACwB,QAAQ,IAAI,OAAO,CAAE,WAAW,SAAS;AACnE,MAAa,gBACX,QACA,YACsB;CACtB,MAAM,QAAQ,QAAQ,QAAQ,MAAK,WAAU,OAAO,SAAS,QAAQ;CACrE,IAAI;CACJ,IAAI;CACJ,MAAM,cAAc;AAClB,MAAI,CAAC,QAAQ;AACX,WAAQ,OAAO,OAAO;AACtB,YAAS,IAAI,cAAc;AAC3B,YAAS,IAAI,cAAc;AAC3B,QAAK,MAAM,UAAU,QAAQ,QAC3B,KAAI,OAAO,SAAS,WAAW;AAC7B,SAAK,MAAM,UAAU,OAAO,QAAS,QAAO,IAAI,OAAO,IAAI,MAAM,OAAO,IAAI;AAC5E,QA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c;AACd,UAAO,OAAO,sBAAsB,aAChC,MAAM,kBAAkB,GACxB,MAAM,mBAAmB,cAAe;;AAG9C,SAAO,OAAO,OAAO;GACnB,OAAO;GACP,QAAQ;GACR,aAAa;GACb,MAAS,eAAuC;AAC9C,kBAAc;AACd,WAAO,IAAI,YAAY,MAAM;;GAE/B,UAAU;GACV,MAAS,QAAkB,UAAa;AACtC,kBAAc;AACd,aAAS,QAAQ,OAAO,MAAM;;GAEhC,SACE,QACA,QACG;AACH,kBAAc;AACd,gBAAY,QAAQ,KAAK,MAAM;;GAEjC,OAAO;GACP,eAAe,aAAa,MAAM;GACnC,CAAC;;AAGJ,QAAO,OAAO,OAAO;EACnB;EACA;EACA,KAAK;EACL,QAAQ;EACR;EACA,OAAO;EACP,eAAe;AACb,OAAI,CAAC,UAAU,OAAQ;AACvB,aAAU,YAAY;AACtB,QAAK,MAAM,SAAS,QAAQ;AAC1B,UAAM,SAAS;AACf,UAAM,cAAc,SAAQ,gBAAe,aAAa,CAAC;AACzD,UAAM,cAAc,OAAO;AAC3B,UAAM,aAAa,SAAS;;AAE9B,UAAO,OAAO;AACd,WAAQ,SAAS;AACjB,aAAU,SAAS;;EAEtB,CAAC"}
1
+ {"version":3,"file":"index.js","names":["target.belongs","target.affected","anchor.toArray","anchor.indexedKeys","anchor.equal","anchor.indexedKeys","anchor.matches","read","readAddress"],"sources":["../core/src/impact.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.ts","../core/src/runtime/readable.ts","../core/src/projection/select.ts","../core/src/projection/value-output.ts","../core/src/projection/processor.ts","../core/src/projection/projection-readable.ts","../core/src/projection/source.ts","../core/src/projection/runtime.ts"],"sourcesContent":["import type {\n CollectionId,\n CollectionPath,\n CollectionSelector,\n ObjectNode,\n ImpactTarget,\n PathPick,\n SchemaPath,\n} from './schema';\nimport { compilePath } from './schema';\nimport type { ChangeSet } from './changes';\nimport { AddressIndex, contains } from './address';\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 ObjectNode> = {\n readonly kind: 'incremental' | 'reset';\n affects(pick: PathPick<S>): boolean;\n collection<P extends CollectionPath>(\n pick: (path: SchemaPath<S['shape']>) => P\n ): CollectionImpact<CollectionId<P>>;\n};\ntype ImpactQueries = {\n affects(value: ImpactTarget): boolean;\n collection(selector: CollectionSelector): CollectionImpact<string>;\n};\nconst queries = new WeakMap<object, ImpactQueries>();\nexport const affectsTarget = (impact: object, value: ImpactTarget): boolean =>\n queries.get(impact)!.affects(value);\nexport const collectionImpact = <K extends string>(\n impact: object,\n selector: CollectionSelector<K>\n): CollectionImpact<K> => queries.get(impact)!.collection(selector) as CollectionImpact<K>;\nexport const createImpact = <S extends ObjectNode>(\n schema: 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 for (const change of changes.changes) {\n if (change.kind === 'members') {\n for (const member of change.members) values.add(change.at, true, member.key);\n if (change.order) orders.add(change.at, true);\n } else if (change.kind === 'tree') values.add(change.at, true);\n }\n }\n return values;\n };\n const cache = new Map<string, CollectionImpact<string>>();\n const implementation: ImpactQueries = {\n affects(value) {\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 collection(selector) {\n if (selector.schema !== schema)\n throw new TypeError('Collection belongs to another root model.');\n const key = JSON.stringify(selector.address),\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 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 && 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 (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' && contains(change.at, at)) {\n const result = { kind: 'reset' } as const;\n cache.set(key, result);\n return result;\n }\n if (!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 };\n const impact: DocumentImpact<S> = Object.freeze({\n kind: reset ? 'reset' : 'incremental',\n affects: (pick: PathPick<S>) =>\n implementation.affects(compilePath<S['shape']>(schema, 'value', pick)),\n collection: <P extends CollectionPath>(pick: (path: SchemaPath<S['shape']>) => P) =>\n implementation.collection(\n compilePath<S['shape']>(schema, 'collection', pick) as CollectionSelector\n ) as CollectionImpact<CollectionId<P>>,\n });\n queries.set(impact, implementation);\n return impact;\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';\nimport * as anchor from './anchor';\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) anchor.insert(parent, parent.length, value);\n else parent[index] = value;\n } else if (index >= 0) anchor.remove(parent, index);\n } else if (!present) delete parent[key];\n else if (Object.hasOwn(parent, key)) parent[key] = value;\n else\n Object.defineProperty(parent, key, {\n value,\n writable: true,\n configurable: true,\n enumerable: true,\n });\n};\n\nexport const orderOf = (node: DocumentNode, value: unknown): string[] => {\n if (node.kind === 'list')\n return anchor.toArray(anchor.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') anchor.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';\nimport {\n AddressIndex,\n contains,\n resolveValue,\n resolveLocated,\n memberKey,\n type ResolvedContainer,\n type ResolvedTreeContainer,\n type CompiledMember,\n compiledShape,\n type FixedLayout,\n} from '../address';\nimport * as anchor from './anchor';\nimport { copyValue, equalValue } from '../schema-value';\nimport type { MutableTree, MutableTreeNode } from './tree';\nimport { profile } from '../profile';\nimport { sealChanges } from './changes';\nimport { installMember, installOrder, orderOf, type CanonicalState } 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 copyNode = (node: MutableTreeNode): MutableTreeNode => ({\n ...node,\n children: [...node.children],\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 (node.kind !== 'field' && beforePresent === afterPresent && equalValue(node, before, after))\n return;\n const value = afterPresent ? (node.kind === 'field' ? after : copyValue(node, after)) : 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' && !anchor.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 ? copyValue(member.node, member.value) : undefined;\n if (!at.length) return value;\n const location = resolveLocated(schema, root, at);\n if (!location) throw new Error('Cannot restore an unresolved member.');\n installMember(location.parent, location.key, member.present, value);\n return root;\n }\n const location = resolveValue(schema, root, at);\n if (!location) throw new Error('Cannot restore an unresolved subtree.');\n if (fact.kind === 'order') 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 installMember(tree.nodes, id, node !== undefined, node && copyNode(node));\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 = 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 = 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 ? anchor.indexedKeys(fact.value as unknown[], fact.node.keyOf)\n : (fact.value as { ids: string[] }).ids;\n if (!anchor.equal(fact.order, current)) {\n const after = 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, state: CanonicalState, changes: Change[]): void => {\n const location = resolveValue(state.schema, state.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 (\n before &&\n after &&\n before.parentId === after.parentId &&\n anchor.equal(before.children, after.children) &&\n Object.hasOwn(before, 'value') === Object.hasOwn(after, 'value') &&\n equalValue(node.value, before.value, after.value)\n )\n continue;\n nodes.push(\n !before\n ? { id, kind: 'added', after: copyNode(after!) }\n : !after\n ? { id, kind: 'removed', before }\n : { id, kind: 'updated', before, after: copyNode(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: 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 && 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 (contains(at, memberAt))\n children.push({ kind: 'member', at: memberAt, group: fact, member });\n }\n } else if (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: 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: 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: 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 = orderOf(container.node, container.value);\n profile.recorder('orderSnapshots');\n profile.recorder('orderItems', group.order.length);\n }\n tree(container: 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(id, Object.hasOwn(tree.nodes, id) ? copyNode(tree.nodes[id]) : undefined);\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 installMember(\n fact.parent,\n memberKey(fact, member.key),\n member.present,\n member.present ? 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) installOrder(fact.node, fact.value, fact.order);\n }\n seal(): ChangeSet {\n if (this.resetBefore) {\n if (equalValue(this.state.schema, this.resetBefore.value, this.state.document))\n return sealChanges([]);\n profile.recorder('sealed');\n return sealChanges([\n {\n kind: 'reset',\n before: this.resetBefore.value,\n after: 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 = 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';\nimport {\n createAddressResolver,\n resolveContainer,\n resolveTreeContainer,\n resolveValue,\n memberKey,\n type CompiledMember,\n type ResolvedContainer,\n type ResolvedTreeContainer,\n} from '../address';\nimport { checkKey, checkValue, copyValue } from '../schema-value';\nimport { ChangeRecorder } from './recorder';\nimport { installMember, type CanonicalState } from './state';\nimport { fail, invalidValue } 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: CanonicalState) {\n this.recorder = new ChangeRecorder(state);\n this.resolver = createAddressResolver(state.schema, state.document);\n this.resolvedRoot = state.document;\n }\n validate(node: DocumentNode, value: unknown, at: DocumentAddress): void {\n const issue = checkValue(node, value, at);\n if (issue) invalidValue(issue);\n }\n resolveContainer(at: DocumentAddress): ResolvedContainer {\n return (\n this.resolver.container(this.identity, this.generation, at) ??\n fail(at, 'invalid-address', 'Container does not exist.')\n );\n }\n /** Bind access-resolved canonical facts without walking the address again. */\n bind(at: DocumentAddress, node: DocumentNode | undefined, value: unknown): ResolvedContainer {\n return (\n resolveContainer(this.identity, this.generation, at, node, value) ??\n fail(at, 'invalid-address', 'Container does not exist.')\n );\n }\n bindTree(\n at: DocumentAddress,\n node: DocumentNode | undefined,\n value: unknown\n ): ResolvedTreeContainer {\n return (\n resolveTreeContainer(this.identity, this.generation, at, node, value) ??\n fail(at, 'invalid-tree', 'Expected a tree.')\n );\n }\n resolveTree(at: DocumentAddress): ResolvedTreeContainer {\n const location = 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 = 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: 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 fail(\n container.at.concat(key),\n 'invalid-value',\n 'Replace fields, variants, or collection entries; edit object members individually.'\n );\n this.writeLocatedMember(container, key, member, memberKey(container, key), value, 'set');\n }\n removeMember(container: ResolvedContainer, key: string): void {\n this.writeMember(this.refresh(container), key, undefined, 'remove');\n }\n private refresh(container: ResolvedContainer): ResolvedContainer {\n if (container.owner !== this.identity)\n return 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: 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 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: ResolvedContainer,\n key: string,\n value: unknown,\n operation: 'set' | 'remove',\n physicalKey = 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: 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 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 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 issue = checkKey(parentNode.key, key, []);\n if (issue)\n return fail(container.at.concat(key, ...issue.address), 'invalid-key', issue.message);\n }\n if (present) {\n if (node.kind === 'field') {\n const issue = checkValue(node, value, []);\n if (issue) return invalidValue(issue, container.at.concat(key, ...issue.address));\n } else this.validate(node, value, container.at.concat(key));\n if (parentNode.kind === 'list' && parentNode.keyOf(value) !== key)\n return 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 ? (node.kind === 'field' ? value : copyValue(node, value)) : undefined;\n 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 = 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 { installOrder, installMember, orderOf } from '../state';\nimport * as anchor from '../anchor';\nimport { fail } from '../issue';\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 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 = node.kind === 'table' ? Object.keys(container.parent) : orderOf(node, current);\n if (!anchor.matches(change.order[side], keys))\n return fail(\n change.at,\n 'invalid-changes',\n 'Order must contain exactly the resulting keys.'\n );\n 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 (!anchor.matches(ids, Object.keys(container.parent)))\n return 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 installMember(\n current.nodes,\n item.id,\n next !== undefined,\n next && { ...next, children: [...next.children] }\n );\n }\n session.validate(node, current, change.at);\n session.invalidate();\n }\n }\n}\n","import type { ObjectNode, Infer, PathPick } from './schema';\nimport { compilePath } from './schema';\nimport { contains, debugKey, overlaps, read, resolveAddress } from './address';\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 { decodeChanges } from './mutation/changes';\nimport { MutationRejected, fail } from './mutation/issue';\nimport type { ChangeSet } from './changes';\nimport { checkValue, copyValue, ParseError } 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 OperationResult,\n TransactionResult,\n} from './runtime/contract';\nimport { bindRuntimeAccess, accessOf } from './runtime/access';\nimport { assertRuntimeWritable, bindRuntimeDriver, disposeRuntimeDriver } from './runtime/driver';\nimport {\n bindDocumentReadable,\n createNotification,\n disposeNotification,\n notify,\n subscribeRoot,\n subscribeTargets,\n type RuntimeNotification,\n} from './runtime/notification';\n\nexport const createDocument = <S extends ObjectNode>(input: {\n readonly schema: S;\n readonly initial: Infer<S>;\n readonly history?: { readonly capacity?: number } | false;\n}): DocumentRuntime<S> => {\n if (input.schema.kind !== 'object')\n throw new TypeError('Document schema must be a root object node.');\n const invalid = checkValue(input.schema, input.initial);\n if (invalid) throw new ParseError(invalid);\n const state = {\n schema: input.schema,\n document: copyValue(input.schema, input.initial) as Infer<S>,\n disposed: false,\n };\n let revision = 0,\n busy = false;\n let runtime!: DocumentRuntime<S>, notification!: RuntimeNotification<S>;\n const idle = () => {\n if (state.disposed) throw new DocumentDisposedError();\n if (busy || accessOf(runtime).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(input.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: notify(notification, 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 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 address: {\n resolve: at => resolveAddress(input.schema, at, state.document),\n read: at => read(state.document, at, input.schema),\n contains,\n overlaps,\n debugKey,\n },\n revision: () => revision,\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 mutate(\n { kind: 'apply', source: options?.source ?? 'local' },\n options?.history ?? true,\n session => {\n if (!options || options.expectedRevision !== revision)\n fail([], 'baseline-mismatch', 'apply requires the current expectedRevision.');\n replay.apply(session, decodeChanges(inputChanges), 'forward');\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 copyValue(input.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 subscribeRoot(notification, 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 subscribeTargets(\n notification,\n picks.map(p => compilePath<S['shape']>(input.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 disposeNotification(notification);\n } finally {\n history.dispose();\n disposeRuntimeDriver(runtime);\n }\n },\n };\n bindRuntimeAccess(runtime, state);\n bindRuntimeDriver(runtime);\n notification = createNotification(runtime);\n bindDocumentReadable(history.api, runtime);\n return runtime;\n};\n","import type { ObjectNode } from '../schema';\nimport type { DocumentReadable, DocumentRuntime } from './contract';\nimport { accessOf, bindRuntimeAccess } from './access';\nimport { shareNotification } from './notification';\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 asReadable = <TSchema extends ObjectNode>(\n runtime: DocumentRuntime<TSchema>\n): DocumentReadable<TSchema> => {\n const readable: DocumentReadable<TSchema> = {\n address: runtime.address,\n revision: runtime.revision,\n subscribe: runtime.subscribe,\n };\n bindRuntimeAccess(readable, accessOf(runtime));\n shareNotification(runtime, readable);\n return Object.freeze(readable);\n};\n","import type { ObjectNode } from '../schema';\nimport type { Read } from '../access/scope';\nimport type { DocumentReadable } from '../runtime/contract';\nimport { readWith } from '../runtime/access';\n\nexport type DocumentSelector<TSchema extends ObjectNode, TResult> = (\n read: Read<TSchema>\n) => TResult;\n\nexport const read = <TSchema extends ObjectNode, TResult>(\n runtime: DocumentReadable<TSchema>,\n selector: DocumentSelector<TSchema, TResult>\n): TResult => readWith(runtime, selector);\n","import { profile } from '../profile';\nimport type { ValueContext } from './contract';\nimport { assertScope } from './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> = {\n begin(active: () => boolean, initialize: boolean): ValueOutputEvaluation<T>;\n seal(reset: boolean, isEqual: (previous: T, next: T) => boolean): boolean;\n context(active: () => boolean, cause: unknown): ValueContext<T>;\n current(check: () => void): T;\n revision(): number;\n reset(): boolean;\n publish(): void;\n emit(call: (listener: () => void) => void): void;\n clear(): void;\n release(): void;\n subscribe(listener: () => void): void;\n unsubscribe(listener: () => void): void;\n};\n\n/** Owns staged and published state for one scalar Projection output. */\nexport const createValueOutput = <T>(): 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\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 begin,\n seal,\n context: (active, cause) => {\n assertScope(active);\n return Object.freeze({\n kind: 'value' as const,\n value: next,\n revision,\n reset,\n cause,\n });\n },\n current: check => {\n 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 clear: () => {\n staged = unset;\n next = value;\n changed = false;\n reset = false;\n },\n release: () => {\n listeners.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 => listeners.add(listener),\n unsubscribe: listener => listeners.delete(listener),\n };\n};\n","import { profile } from '../profile';\nimport { createCollectionOutput, type CollectionOutputState } from './collection-output';\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 './value-output';\n\ntype BoundOutput =\n | {\n readonly kind: 'value';\n readonly definition: Extract<OutputDefinition, { readonly kind: 'value' }>;\n readonly state: ValueOutputState<unknown>;\n readonly output: OutputRecord;\n }\n | {\n readonly kind: 'collection';\n readonly definition: Extract<OutputDefinition, { readonly kind: 'collection' }>;\n readonly state: CollectionOutputState<string, unknown>;\n readonly output: OutputRecord;\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 const output: OutputRecord = {\n kind: 'value',\n get owner() {\n return processor;\n },\n consumers: new Set(),\n context: active => state.context(active, cause),\n current: () => state.current(check),\n revision: state.revision,\n reset: state.reset,\n subscribe: listener => {\n check();\n const wrapped = () => listener();\n state.subscribe(wrapped);\n return () => state.unsubscribe(wrapped);\n },\n emit: state.emit,\n clear: state.clear,\n release: state.release,\n };\n return { kind: 'value', definition: outputDefinition, state, output };\n }\n const state = createCollectionOutput<string, unknown>();\n const output: OutputRecord = {\n kind: 'collection',\n get owner() {\n return processor;\n },\n consumers: new Set(),\n context: active => state.context(active, cause),\n current: () => state.current(check),\n revision: state.revision,\n reset: state.reset,\n subscribe: listener => {\n check();\n const wrapped = (change: import('./contract').CollectionChange<string, unknown>) =>\n listener(change);\n state.subscribe(wrapped);\n return () => state.unsubscribe(wrapped);\n },\n emit: state.emit,\n clear: state.clear,\n release: state.release,\n };\n return { kind: 'collection', definition: outputDefinition, state, output };\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.output);\n }\n return Object.freeze(changed);\n };\n\n const run = (reset: boolean, runCause: unknown): 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 let outputs = begin(scopeActive, reset);\n if (!instance) instance = definition.create();\n profile.materialized[reset ? 'rebuilt' : 'updated']();\n let result = instance.evaluate({ reset, cause: runCause, sources, outputs });\n assertSynchronous(result);\n if (result?.kind === 'rebuild') {\n if (reset) throw new TypeError('Initial or reset projection processor cannot rebuild.');\n instance.release?.();\n instance = definition.create();\n outputs = begin(scopeActive, true);\n result = instance.evaluate({ reset: true, cause: runCause, sources, outputs });\n assertSynchronous(result);\n if (result?.kind === 'rebuild')\n throw new TypeError('Reset projection processor cannot rebuild again.');\n return seal(true);\n }\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.output)),\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 instance?.release?.();\n instance = undefined;\n bound.forEach(entry => {\n entry.output.consumers.clear();\n entry.state.release();\n });\n cause = undefined;\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 } catch (error) {\n processor.release();\n throw error;\n }\n scheduler.addProcessor(processor);\n return processor;\n};\n","import type { Unsubscribe } from '../runtime/contract';\nimport { collectionChangeBetween } from './collection-output';\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 (\n selection.all &&\n (change.added.length || change.removed.length || change.updated.length || change.order)\n )\n return true;\n if (selection.structure && (change.added.length || change.removed.length || change.order))\n return true;\n for (const key of selection.keys) {\n if (\n change.added.some(entry => entry.key === key) ||\n change.removed.some(entry => entry.key === key) ||\n change.updated.some(entry => entry.key === key)\n )\n return true;\n }\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 = collectionChangeBetween(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 { read as readAddress, nodeAt } from '../address';\nimport { collectionAccess, snapshot } from '../access/scope';\nimport { affectsTarget, collectionImpact } from '../impact';\nimport { accessOf } from '../runtime/access';\nimport { attachProjection, documentReadableOwner } from '../runtime/notification';\nimport type { DocumentCommit, DocumentReadable, Unsubscribe } from '../runtime/contract';\nimport type { CollectionSelector, ObjectNode, ValueSelector } from '../schema';\nimport { collectionEntryNode } from '../schema';\nimport { copyValue, equalValue } from '../schema-value';\nimport {\n createCollectionOutput,\n mapRead,\n stageCollectionRead,\n type CollectionOutputState,\n} from './collection-output';\nimport type {\n CollectionChange,\n CollectionRead,\n ExternalCollectionSource,\n ExternalValueSource,\n} from './contract';\nimport { ProjectionDisposedError, ProjectionError } from './contract';\nimport type { SourceDefinition } from './definition';\nimport type { Readable } from './readable';\nimport {\n assertScope,\n assertSynchronous,\n type OutputRecord,\n type Scheduler,\n type SourceBoundaryRecord,\n} from './scheduler';\nimport { createValueOutput, type ValueOutputState } from './value-output';\n\nexport type KeyedInputDraft<K extends string, V> = {\n get(key: K): V | undefined;\n has(key: K): boolean;\n set(key: K, value: V): void;\n remove(key: K): void;\n};\n\nexport type SourceWrite =\n | { readonly kind: 'value'; set(value: unknown): void }\n | {\n readonly kind: 'collection';\n update(run: (draft: KeyedInputDraft<string, unknown>) => void): void;\n };\n\nexport type SourceMaterialization = {\n readonly producer: SourceBoundaryRecord;\n readonly output: OutputRecord;\n readonly write?: SourceWrite;\n};\n\ntype 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\ntype ValueBoundary = SourceMaterialization & {\n readonly setLatest: (value: unknown) => void;\n readonly mark: (metadata?: SourceMark) => void;\n readonly fail: (cause: unknown) => void;\n readonly detach: (cleanup: Unsubscribe) => void;\n};\n\ntype CollectionBoundary = SourceMaterialization & {\n readonly mark: (metadata?: CollectionMark) => void;\n readonly fail: (cause: unknown) => void;\n readonly detach: (cleanup: Unsubscribe) => void;\n};\n\nconst sourceError = (source: SourceBoundaryRecord, cause: unknown): ProjectionError =>\n new ProjectionError('source', source.name, [source.outputs[0].revision()], cause);\n\nconst createValueBoundary = (\n scheduler: Scheduler,\n name: string,\n initial: unknown,\n equality: (previous: unknown, next: unknown) => boolean\n): ValueBoundary => {\n const state: ValueOutputState<unknown> = createValueOutput();\n let boundary!: SourceBoundaryRecord;\n let latest = initial;\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\n const output: OutputRecord = {\n kind: 'value',\n get owner() {\n return boundary;\n },\n consumers: new Set(),\n context: active => state.context(active, contextCause),\n current: () => state.current(check),\n revision: state.revision,\n reset: state.reset,\n subscribe: listener => {\n check();\n const wrapped = () => listener();\n state.subscribe(wrapped);\n return () => state.unsubscribe(wrapped);\n },\n emit: state.emit,\n clear: state.clear,\n release: state.release,\n };\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(latest);\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 state.clear();\n pendingReset = false;\n pendingCause = undefined;\n contextCause = undefined;\n recovering = false;\n },\n release: () => {\n cleanup?.();\n cleanup = undefined;\n state.release();\n output.consumers.clear();\n },\n };\n\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\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(boundary, cause);\n recovering = false;\n scheduler.capture(boundary);\n };\n return {\n producer: boundary,\n output,\n setLatest: value => {\n latest = value;\n },\n mark,\n fail,\n detach: next => {\n cleanup = next;\n },\n };\n};\n\nconst createCollectionBoundary = (\n scheduler: Scheduler,\n name: string,\n readLatest: (active: () => boolean) => CollectionRead<string, unknown>,\n equality: (previous: unknown, next: unknown) => boolean\n): CollectionBoundary => {\n const state: CollectionOutputState<string, unknown> = createCollectionOutput();\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\n const output: OutputRecord = {\n kind: 'collection',\n get owner() {\n return boundary;\n },\n consumers: new Set(),\n context: active => state.context(active, contextCause),\n current: () => state.current(check),\n revision: state.revision,\n reset: state.reset,\n subscribe: listener => {\n check();\n const wrapped = (change: CollectionChange<string, unknown>) => listener(change);\n state.subscribe(wrapped);\n return () => state.unsubscribe(wrapped);\n },\n emit: state.emit,\n clear: state.clear,\n release: state.release,\n };\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),\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 state.clear();\n pendingReset = false;\n pendingCause = undefined;\n contextCause = undefined;\n recovering = false;\n fullScan = false;\n orderMayChange = false;\n candidates.clear();\n },\n release: () => {\n cleanup?.();\n cleanup = undefined;\n state.release();\n output.consumers.clear();\n },\n };\n\n scheduler.initialize(() => {\n let active = true;\n try {\n stageCollectionRead(\n state,\n readLatest(() => active),\n () => active,\n {\n reset: true,\n isEqual: equality,\n }\n );\n state.publish();\n state.clear();\n } finally {\n active = false;\n }\n });\n scheduler.addSource(boundary);\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(boundary, 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 DocumentBinding = {\n matches(commit: DocumentCommit<ObjectNode>): boolean;\n capture(commit: DocumentCommit<ObjectNode>): void;\n dispose(): void;\n};\n\ntype DocumentConnection = {\n add(binding: DocumentBinding): Unsubscribe;\n close(): void;\n};\n\ntype ValueMember = {\n readonly boundary: ValueBoundary;\n receive(value: unknown, metadata?: SourceMark): void;\n};\n\nexport const createSourceRegistry = (scheduler: Scheduler) => {\n const documents = new Map<object, DocumentConnection>();\n const readables = new Map<object, { members: Set<ValueMember>; close(): void }>();\n const externalValues = new WeakMap<object, { members: Set<ValueMember>; close(): void }>();\n const externalCollections = new WeakMap<\n object,\n { members: Set<CollectionBoundary>; close(): void }\n >();\n\n const documentConnection = <S extends ObjectNode>(\n runtime: DocumentReadable<S>\n ): DocumentConnection => {\n const state = accessOf(runtime);\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 guard = (locked: boolean) => {\n state.projectionLocks = (state.projectionLocks ?? 0) + (locked ? 1 : -1);\n };\n scheduler.guards.add(guard);\n let closed = false;\n let detach: Unsubscribe = () => undefined;\n const connection: DocumentConnection = {\n add(binding) {\n if (closed) throw new Error('Document projection connection is closed.');\n bindings.add(binding);\n let active = true;\n return () => {\n if (!active) return;\n active = false;\n bindings.delete(binding);\n if (!bindings.size) connection.close();\n };\n },\n close() {\n if (closed) return;\n closed = true;\n detach();\n bindings.clear();\n scheduler.guards.delete(guard);\n documents.delete(state);\n },\n };\n detach = attachProjection(runtime, {\n capture: commit => {\n for (const binding of bindings)\n if (binding.matches(commit as DocumentCommit<ObjectNode>))\n binding.capture(commit as DocumentCommit<ObjectNode>);\n },\n settle: scheduler.settle,\n flush: scheduler.flush,\n dispose: () => {\n for (const binding of bindings) binding.dispose();\n scheduler.run();\n },\n });\n documents.set(state, connection);\n return connection;\n };\n\n const valueInput = (definition: SourceDefinition): SourceMaterialization => {\n if (definition.source.kind !== 'value-input') throw new Error('Invalid value input source.');\n const source = definition.source;\n const boundary = createValueBoundary(\n scheduler,\n 'projection input',\n source.initial,\n source.equality\n );\n return {\n ...boundary,\n write: {\n kind: 'value',\n set(value) {\n scheduler.assertIdle();\n boundary.setLatest(value);\n boundary.mark();\n scheduler.run();\n },\n },\n };\n };\n\n const collectionInput = (definition: SourceDefinition): SourceMaterialization => {\n if (definition.source.kind !== 'collection-input')\n throw new Error('Invalid collection input source.');\n const values = new Map(definition.source.initial);\n const boundary = createCollectionBoundary(\n scheduler,\n 'projection collection input',\n () => mapRead(values),\n definition.output.equality\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: KeyedInputDraft<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 let changed = false;\n for (const operation of operations) {\n const present = values.has(operation.key);\n if (operation.kind === 'set') {\n if (present && Object.is(values.get(operation.key), operation.value)) continue;\n structural ||= !present;\n values.set(operation.key, operation.value);\n } else {\n if (!present) continue;\n structural = true;\n values.delete(operation.key);\n }\n candidates.add(operation.key);\n changed = true;\n }\n if (!changed) return;\n boundary.mark({ candidates, orderMayChange: structural });\n scheduler.run();\n },\n },\n };\n };\n\n const documentValue = (definition: SourceDefinition): SourceMaterialization => {\n if (definition.source.kind !== 'document-value')\n throw new Error('Invalid document value source.');\n const { document, selector } = definition.source;\n const state = accessOf(document);\n const address = selector?.address ?? Object.freeze([]);\n const schemaNode = () => nodeAt(state.schema, address, state.document);\n const read = () => {\n if (state.disposed) throw new Error('Document has been disposed.');\n const node = schemaNode();\n if (!node) return undefined;\n const value = selector ? readAddress(state.document, address, state.schema) : state.document;\n return copyValue(node, value);\n };\n const initial = read();\n const boundary = createValueBoundary(scheduler, 'document source', initial, (left, right) => {\n const node = schemaNode();\n return node ? equalValue(node, left, right) : Object.is(left, right);\n });\n const remove = documentConnection(document).add({\n matches: commit => !selector || affectsTarget(commit.impact, selector),\n capture: commit => {\n try {\n boundary.setLatest(read());\n boundary.mark({ reset: commit.impact.kind === 'reset' });\n } catch (cause) {\n boundary.fail(cause);\n }\n },\n dispose: () => boundary.fail(new Error('Document has been disposed.')),\n });\n boundary.detach(remove);\n return boundary;\n };\n\n const documentCollection = (definition: SourceDefinition): SourceMaterialization => {\n if (definition.source.kind !== 'document-collection')\n throw new Error('Invalid document collection source.');\n const { document, selector } = definition.source;\n const state = accessOf(document);\n const read = (active: () => boolean): CollectionRead<string, unknown> => {\n if (state.disposed) throw new Error('Document has been disposed.');\n const raw = collectionAccess({ state, active }, selector.address) as CollectionRead<\n string,\n unknown\n >;\n const snapshots = new Map<string, unknown>();\n return Object.freeze({\n get: (key: string) => {\n assertScope(active);\n if (!snapshots.has(key)) snapshots.set(key, snapshot(raw.get(key)));\n return snapshots.get(key);\n },\n has: (key: string) => {\n assertScope(active);\n return raw.has(key);\n },\n ids: () => {\n assertScope(active);\n return raw.ids();\n },\n });\n };\n const collectionNode = () => nodeAt(state.schema, selector.address, state.document);\n const boundary = createCollectionBoundary(\n scheduler,\n 'document collection source',\n read,\n (left, right) => {\n const node = collectionNode();\n const entry = node && collectionEntryNode(node);\n return entry ? equalValue(entry, left, right) : Object.is(left, right);\n }\n );\n const remove = documentConnection(document).add({\n matches: commit => affectsTarget(commit.impact, selector),\n capture: commit => {\n const impact = collectionImpact(commit.impact, selector);\n if (impact.kind === 'reset') {\n boundary.mark({ reset: true });\n return;\n }\n const candidates = new Set<string>([...impact.added, ...impact.updated, ...impact.removed]);\n boundary.mark({\n candidates,\n orderMayChange: Boolean(impact.added.size || impact.removed.size || impact.orderChanged),\n });\n },\n dispose: () => boundary.fail(new Error('Document has been disposed.')),\n });\n boundary.detach(remove);\n return boundary;\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 initial = readable.current();\n const boundary = createValueBoundary(scheduler, 'external readable', initial, equality);\n const member: ValueMember = {\n boundary,\n receive(value, metadata) {\n initial = value;\n boundary.setLatest(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 unsubscribe?.();\n detachDocument?.();\n readables.delete(readable);\n },\n };\n const owner = documentReadableOwner(readable);\n if (owner) {\n detachDocument = documentConnection(owner).add({\n matches: () => true,\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 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 void initial;\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 const boundary = createValueBoundary(scheduler, 'external source', source.current(), equality);\n const member: ValueMember = {\n boundary,\n receive(value, metadata) {\n boundary.setLatest(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 unsubscribe?.();\n externalValues.delete(source);\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 (cause) {\n created.close();\n throw cause;\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 );\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 unsubscribe?.();\n externalCollections.delete(source);\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 (cause) {\n created.close();\n throw cause;\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 'value-input':\n return valueInput(definition);\n case 'collection-input':\n return collectionInput(definition);\n case 'document-value':\n return documentValue(definition);\n case 'document-collection':\n return documentCollection(definition);\n case 'readable':\n return readable(definition);\n case 'external-value':\n return externalValue(definition);\n case 'external-collection':\n return externalCollection(definition);\n }\n },\n dispose() {\n documents.forEach(connection => connection.close());\n readables.forEach(connection => connection.close());\n documents.clear();\n readables.clear();\n },\n };\n};\n","import type { Unsubscribe } from '../runtime/contract';\nimport {\n incremental,\n type IncrementalCollectionProcessor,\n type IncrementalGroupDefine,\n type IncrementalGroupOutputTree,\n type IncrementalGroupProcessor,\n type IncrementalValueProcessor,\n} from './advanced';\nimport { collectionView, mapRead, snapshotCollectionView } from './collection-output';\nimport type { CollectionChange, CollectionRead } from './contract';\nimport { ProjectionDisposedError } from './contract';\nimport {\n derive,\n input,\n isProjection,\n ownProjection,\n producerOf,\n projectionRef,\n type Input,\n type ProducerDefinition,\n type Projection,\n} from './definition';\nimport { createProcessor } from './processor';\nimport {\n createDirectReadable,\n createSelectorReadable,\n isMapLike,\n type ProjectionReadableSource,\n} from './projection-readable';\nimport type { Readable } from './readable';\nimport { createScheduler, type OutputRecord, type ProducerRecord } from './scheduler';\nimport { createSourceRegistry, type KeyedInputDraft, type SourceWrite } from './source';\n\ntype KeyedDraft<K extends string, V> = {\n get(key: K): V | undefined;\n has(key: K): boolean;\n set(key: K, value: V): void;\n remove(key: K): void;\n};\n\nexport type ProjectionRuntime = {\n get<T>(projection: Projection<T, unknown>): T;\n readable<T>(projection: Projection<T, unknown>): Readable<T>;\n readable<T, R>(\n projection: Projection<T, unknown>,\n selector: (value: T) => R,\n equality?: (previous: R, next: R) => boolean\n ): Readable<R>;\n set<T>(input: Input<T>, value: T): void;\n update<K extends string, V>(\n input: Input<ReadonlyMap<K, V>, CollectionChange<K, V>>,\n run: (draft: KeyedDraft<K, V>) => void\n ): void;\n batch<T>(run: () => T): T;\n batch<T>(options: { readonly cause?: unknown }, run: () => T): T;\n scope(): ProjectionScope;\n dispose(): void;\n};\n\nexport type ProjectionScope = {\n readonly input: typeof input;\n readonly derive: typeof derive;\n readonly incremental: typeof incremental;\n get<T>(projection: Projection<T, unknown>): T;\n readable<T>(projection: Projection<T, unknown>): Readable<T>;\n readable<T, R>(\n projection: Projection<T, unknown>,\n selector: (value: T) => R,\n equality?: (previous: R, next: R) => boolean\n ): Readable<R>;\n set<T>(input: Input<T>, value: T): void;\n update<K extends string, V>(\n input: Input<ReadonlyMap<K, V>, CollectionChange<K, V>>,\n run: (draft: KeyedDraft<K, V>) => void\n ): void;\n batch: ProjectionRuntime['batch'];\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 materialized.set(definition, result);\n rememberScoped(definition, requester);\n return result;\n };\n\n const resolveOutput = (\n projection: Projection<unknown, unknown>,\n requester?: ScopeState\n ): 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 get = <T>(projection: Projection<T, unknown>, requester?: ScopeState): T =>\n publicCurrent(resolveOutput(projection as Projection<unknown, unknown>, requester)) as T;\n\n const readableSource = <T>(\n projection: Projection<T, unknown>,\n requester?: ScopeState\n ): ProjectionReadableSource<T> => {\n const output = resolveOutput(projection as Projection<unknown, unknown>, requester);\n return Object.freeze({\n kind: output.kind,\n current: () => get(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, unknown>,\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 readable<T>(projection: Projection<T, unknown>): Readable<T>;\n function readable<T, R>(\n projection: Projection<T, unknown>,\n selector: (value: T) => R,\n equality?: (previous: R, next: R) => boolean\n ): Readable<R>;\n function readable<T, R>(\n projection: Projection<T, unknown>,\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 = (\n target: Projection<unknown, unknown>,\n requester?: ScopeState\n ): 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 setInput = <T>(target: Input<T>, value: T, requester?: ScopeState): void => {\n const write = inputWrite(target as Projection<unknown, unknown>, requester);\n if (write.kind !== 'value') throw new TypeError('Projection is not a value input.');\n write.set(value);\n };\n\n const updateInput = <K extends string, V>(\n target: Input<ReadonlyMap<K, V>, CollectionChange<K, V>>,\n run: (draft: KeyedDraft<K, V>) => void,\n requester?: ScopeState\n ): void => {\n const write = inputWrite(target as Projection<unknown, unknown>, requester);\n if (write.kind !== 'collection') throw new TypeError('Projection is not a collection input.');\n write.update(run as (draft: KeyedInputDraft<string, unknown>) => void);\n };\n\n function batch<T>(run: () => T): T;\n function batch<T>(options: { readonly cause?: unknown }, run: () => T): T;\n function batch<T>(\n optionsOrCallback: { readonly cause?: unknown } | (() => T),\n maybeCallback?: () => T\n ): T {\n return typeof optionsOrCallback === 'function'\n ? scheduler.batch(optionsOrCallback)\n : scheduler.batch(optionsOrCallback, maybeCallback);\n }\n\n const disposeScope = (state: ScopeState): void => {\n if (!state.active) return;\n scheduler.assertIdle();\n state.active = false;\n state.subscriptions.forEach(unsubscribe => unsubscribe());\n state.subscriptions.clear();\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 scheduler.releaseProducer(current.record);\n materialized.delete(definition);\n }\n state.materialized.length = 0;\n scopes.delete(state);\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 const own = <P extends Projection<unknown, unknown>>(projection: P): P => {\n assertActive();\n return ownProjection(projection, state);\n };\n const ownOutputTree = <T>(tree: T): T => {\n if (isProjection(tree)) return own(tree as Projection<unknown, unknown>) as T;\n if (!tree || typeof tree !== 'object')\n throw new TypeError('Incremental group output tree must be an object.');\n for (const value of Object.values(tree as Record<string, unknown>)) ownOutputTree(value);\n return tree;\n };\n\n const scopedInput: typeof input = Object.assign(\n <T>(initial: T, equality?: (previous: T, next: T) => boolean) =>\n own(input(initial, equality)),\n {\n collection: <K extends string, V>(initial?: ReadonlyMap<K, V>) =>\n own(input.collection(initial)),\n }\n );\n const scopedDerive: typeof derive = (dependencies, compute, equality) =>\n own(derive(dependencies, compute, equality));\n const scopedIncremental: typeof incremental = Object.assign(\n <const D extends readonly Projection<unknown, unknown>[], T>(\n dependencies: D,\n processor: IncrementalValueProcessor<D, T>\n ) => own(incremental(dependencies, processor)),\n {\n collection: <const D extends readonly Projection<unknown, unknown>[], K extends string, V>(\n dependencies: D,\n processor: IncrementalCollectionProcessor<D, K, V>\n ) => own(incremental.collection(dependencies, processor)),\n group: <\n const D extends readonly Projection<unknown, unknown>[],\n const O extends IncrementalGroupOutputTree,\n >(\n dependencies: D,\n defineOutputs: (define: IncrementalGroupDefine) => O,\n processor: IncrementalGroupProcessor<D, O>\n ) => ownOutputTree(incremental.group(dependencies, defineOutputs, processor)),\n }\n );\n\n function scopeReadable<T>(projection: Projection<T, unknown>): Readable<T>;\n function scopeReadable<T, R>(\n projection: Projection<T, unknown>,\n selector: (value: T) => R,\n equality?: (previous: R, next: R) => boolean\n ): Readable<R>;\n function scopeReadable<T, R>(\n projection: Projection<T, unknown>,\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 scopeBatch<T>(run: () => T): T;\n function scopeBatch<T>(options: { readonly cause?: unknown }, run: () => T): T;\n function scopeBatch<T>(\n optionsOrCallback: { readonly cause?: unknown } | (() => T),\n maybeCallback?: () => T\n ): T {\n assertActive();\n return typeof optionsOrCallback === 'function'\n ? batch(optionsOrCallback)\n : batch(optionsOrCallback, maybeCallback!);\n }\n\n return Object.freeze({\n input: scopedInput,\n derive: scopedDerive,\n incremental: scopedIncremental,\n get: <T>(projection: Projection<T, unknown>) => {\n assertActive();\n return get(projection, state);\n },\n readable: scopeReadable,\n set: <T>(target: Input<T>, value: T) => {\n assertActive();\n setInput(target, value, state);\n },\n update: <K extends string, V>(\n target: Input<ReadonlyMap<K, V>, CollectionChange<K, V>>,\n run: (draft: KeyedDraft<K, V>) => void\n ) => {\n assertActive();\n updateInput(target, run, state);\n },\n batch: scopeBatch,\n dispose: () => disposeScope(state),\n });\n };\n\n return Object.freeze({\n get,\n readable,\n set: setInput,\n update: updateInput,\n batch,\n scope: createScope,\n dispose: () => {\n if (!scheduler.active) return;\n scheduler.assertIdle();\n for (const scope of scopes) {\n scope.active = false;\n scope.subscriptions.forEach(unsubscribe => unsubscribe());\n scope.subscriptions.clear();\n scope.materialized.length = 0;\n }\n scopes.clear();\n sources.dispose();\n scheduler.dispose();\n },\n });\n};\n"],"mappings":";;;;;;AAmCA,MAAM,0BAAU,IAAI,SAAgC;AACpD,MAAa,iBAAiB,QAAgB,UAC5C,QAAQ,IAAI,OAAO,CAAE,QAAQ,MAAM;AACrC,MAAa,oBACX,QACA,aACwB,QAAQ,IAAI,OAAO,CAAE,WAAW,SAAS;AACnE,MAAa,gBACX,QACA,YACsB;CACtB,MAAM,QAAQ,QAAQ,QAAQ,MAAK,WAAU,OAAO,SAAS,QAAQ;CACrE,IAAI;CACJ,IAAI;CACJ,MAAM,cAAc;AAClB,MAAI,CAAC,QAAQ;AACX,WAAQ,OAAO,OAAO;AACtB,YAAS,IAAI,cAAc;AAC3B,YAAS,IAAI,cAAc;AAC3B,QAAK,MAAM,UAAU,QAAQ,QAC3B,KAAI,OAAO,SAAS,WAAW;AAC7B,SAAK,MAAM,UAAU,OAAO,QAAS,QAAO,IAAI,OAAO,IAAI,MAAM,OAAO,IAAI;AAC5E,QAAI,OAAO,MAAO,QAAO,IAAI,OAAO,IAAI,KAAK;cACpC,OAAO,SAAS,OAAQ,QAAO,IAAI,OAAO,IAAI,KAAK;;AAGlE,SAAO;;CAET,MAAM,wBAAQ,IAAI,KAAuC;CACzD,MAAM,iBAAgC;EACpC,QAAQ,OAAO;AACb,WAAQ,OAAO,SAAS;AACxB,OAAI,CAACA,QAAe,OAAO,OAAO,CAAE,QAAO;AAC3C,OAAI,MAAO,QAAO;AAClB,UAAOC,SAAgB,OAAO,OAAO,EAAE,OAAQ;;EAEjD,WAAW,UAAU;AACnB,OAAI,SAAS,WAAW,OACtB,OAAM,IAAI,U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