doxum 0.1.21 → 0.1.22

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 (65) hide show
  1. package/README.md +21 -2
  2. package/dist/{access-BeSV5ve-.js → access-CZXv_DIF.js} +179 -37
  3. package/dist/access-CZXv_DIF.js.map +1 -0
  4. package/dist/{access-Bienf28h.cjs → access-D64MFRSm.cjs} +228 -38
  5. package/dist/access-D64MFRSm.cjs.map +1 -0
  6. package/dist/{advanced-COFJtWMT.js → advanced-BTStm2cW.js} +29 -25
  7. package/dist/advanced-BTStm2cW.js.map +1 -0
  8. package/dist/{advanced-FgdTwu5b.d.ts → advanced-CqrR_4dh.d.ts} +3 -3
  9. package/dist/{advanced-DfKc7TZR.d.cts → advanced-CyR5o3Xr.d.cts} +3 -3
  10. package/dist/{advanced-BRL5pN0y.cjs → advanced-GKZ-CZ6a.cjs} +29 -25
  11. package/dist/advanced-GKZ-CZ6a.cjs.map +1 -0
  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-KG5XnQZt.d.ts → contract-CRrZ-3sF.d.cts} +64 -34
  17. package/dist/{contract-CdmDHRUq.d.cts → contract-CxiNcqMn.d.ts} +64 -34
  18. package/dist/{driver-Djr3BVvo.cjs → driver-BC06FEMF.cjs} +2 -2
  19. package/dist/{driver-Djr3BVvo.cjs.map → driver-BC06FEMF.cjs.map} +1 -1
  20. package/dist/{driver-CLYJOGDQ.js → driver-BqRjwFmU.js} +2 -2
  21. package/dist/{driver-CLYJOGDQ.js.map → driver-BqRjwFmU.js.map} +1 -1
  22. package/dist/index.cjs +480 -117
  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 +478 -115
  27. package/dist/index.js.map +1 -1
  28. package/dist/{integration-Z6MsfFI7.cjs → integration-BqDw7e2w.cjs} +3 -4
  29. package/dist/{integration-Z6MsfFI7.cjs.map → integration-BqDw7e2w.cjs.map} +1 -1
  30. package/dist/{integration-C4Isp8lJ.js → integration-CSXaF8HP.js} +2 -3
  31. package/dist/{integration-C4Isp8lJ.js.map → integration-CSXaF8HP.js.map} +1 -1
  32. package/dist/integration.cjs +5 -4
  33. package/dist/integration.d.cts +1 -1
  34. package/dist/integration.d.ts +1 -1
  35. package/dist/integration.js +4 -3
  36. package/dist/{issue-W0hT8u8D.js → issue-9U6YLYz3.js} +11 -6
  37. package/dist/issue-9U6YLYz3.js.map +1 -0
  38. package/dist/{issue-DjK1xp5K.cjs → issue-Bo0FIO3b.cjs} +11 -6
  39. package/dist/issue-Bo0FIO3b.cjs.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-Bkjau6B6.js → notification-CrZHVx3a.js} +3 -59
  45. package/dist/notification-CrZHVx3a.js.map +1 -0
  46. package/dist/{notification-DJfouMEb.cjs → notification-DFoA9bQY.cjs} +3 -77
  47. package/dist/notification-DFoA9bQY.cjs.map +1 -0
  48. package/dist/react.cjs +4 -3
  49. package/dist/react.cjs.map +1 -1
  50. package/dist/react.js +3 -2
  51. package/dist/react.js.map +1 -1
  52. package/package.json +1 -1
  53. package/skills/doxum-runtime/SKILL.md +5 -0
  54. package/skills/doxum-runtime/references/guide.en.md +9 -0
  55. package/skills/doxum-runtime/references/guide.zh-CN.md +8 -0
  56. package/skills/doxum-runtime/references/projections.en.md +5 -0
  57. package/skills/doxum-runtime/references/projections.zh-CN.md +5 -0
  58. package/dist/access-BeSV5ve-.js.map +0 -1
  59. package/dist/access-Bienf28h.cjs.map +0 -1
  60. package/dist/advanced-BRL5pN0y.cjs.map +0 -1
  61. package/dist/advanced-COFJtWMT.js.map +0 -1
  62. package/dist/issue-DjK1xp5K.cjs.map +0 -1
  63. package/dist/issue-W0hT8u8D.js.map +0 -1
  64. package/dist/notification-Bkjau6B6.js.map +0 -1
  65. package/dist/notification-DJfouMEb.cjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"access-Bienf28h.cjs","names":["isRecord","isPlainObject","compiledShape","validTree","fail","remove","fail","index","remove","replace","insert","fail","keys","replace","remove","fail","contains","replace","move","fail","resolveChild","resolveLocated","nodeAt","compiledShape","children"],"sources":["../core/src/schema-value.ts","../core/src/mutation/operations/map.ts","../core/src/mutation/operations/table.ts","../core/src/mutation/operations/list.ts","../core/src/mutation/operations/tree.ts","../core/src/mutation/operations/order.ts","../core/src/access/scope.ts","../core/src/runtime/contract.ts","../core/src/runtime/access.ts"],"sourcesContent":["import type { DocumentAddress, DocumentNode, Infer } from './schema';\nimport { compiledShape } from './address';\nimport { isPlainObject, isRecord } from './value/ownership';\nimport { validate as validTree } from './mutation/tree';\nimport * as anchor from './mutation/anchor';\nimport { profile } from './profile';\n\n/** Pure synchronous validation. Successful output is ignored; input is never transformed. */\nexport type Validator<T> =\n | ((value: unknown) => T)\n | {\n readonly '~standard': {\n readonly version: 1;\n readonly vendor: string;\n readonly types?: { readonly input: unknown; readonly output: T };\n validate(value: unknown):\n | { readonly value: T; readonly issues?: undefined }\n | {\n readonly issues: readonly {\n readonly message: string;\n readonly path?: readonly (PropertyKey | { readonly key: PropertyKey })[];\n }[];\n }\n | PromiseLike<unknown>;\n };\n };\n\nexport type ParseIssue = {\n readonly address: DocumentAddress;\n readonly code: 'invalid-value' | 'invalid-key' | 'missing-validator' | 'invalid-tree';\n readonly message: string;\n};\nexport class ParseError extends TypeError {\n readonly issues: readonly ParseIssue[];\n constructor(issue: ParseIssue) {\n super(`${issue.message} at ${JSON.stringify(issue.address)}`);\n this.name = 'ParseError';\n this.issues = Object.freeze([\n Object.freeze({ ...issue, address: Object.freeze([...issue.address]) }),\n ]);\n }\n}\n\nconst issue = (\n address: DocumentAddress,\n message: string,\n code: ParseIssue['code'] = 'invalid-value'\n): ParseIssue => ({ address, message, code });\n\nexport const checkScalar = (\n validator: Validator<unknown> | undefined,\n value: unknown,\n address: DocumentAddress,\n strict: boolean\n): ParseIssue | undefined => {\n if (!validator)\n return strict\n ? issue(address, 'A validator is required to parse an opaque value.', 'missing-validator')\n : undefined;\n try {\n const result =\n typeof validator === 'function' ? validator(value) : validator['~standard'].validate(value);\n if (\n result &&\n (typeof result === 'object' || typeof result === 'function') &&\n 'then' in result &&\n typeof result.then === 'function'\n )\n return issue(address, 'Validators must be synchronous.');\n if (typeof validator !== 'function') {\n if (!isRecord(result)) return issue(address, 'Malformed validator result.');\n if (Array.isArray(result.issues)) {\n const first = result.issues[0];\n return issue(\n [\n ...address,\n ...(first?.path ?? []).map((part: PropertyKey | { key: PropertyKey }) =>\n String(typeof part === 'object' ? part.key : part)\n ),\n ],\n first?.message ?? 'Value validation failed.'\n );\n }\n if (!Object.hasOwn(result, 'value')) return issue(address, 'Malformed validator result.');\n }\n return undefined;\n } catch (error) {\n return issue(address, error instanceof Error ? error.message : 'Value validation failed.');\n }\n};\n\nexport const checkKey = (\n validator: Validator<string> | undefined,\n value: unknown,\n address: DocumentAddress\n): ParseIssue | undefined => {\n if (typeof value !== 'string')\n return issue(address, 'Collection keys must be strings.', 'invalid-key');\n const failure = checkScalar(validator, value, address, false);\n return failure ? { ...failure, code: 'invalid-key' } : undefined;\n};\n\nexport const checkValue = (\n node: DocumentNode,\n value: unknown,\n address: DocumentAddress = [],\n strict = false\n): ParseIssue | undefined => {\n if (node.optional && value === undefined) return undefined;\n if (node.kind === 'field') return checkScalar(node.validator, value, address, strict);\n if (node.kind === 'object' || node.kind === 'variant') {\n if (!isPlainObject(value)) return issue(address, 'Expected an object.');\n if (node.kind === 'variant') {\n const tag = value[node.tag];\n if (\n !Object.hasOwn(value, node.tag) ||\n typeof tag !== 'string' ||\n !Object.hasOwn(node.variants, tag)\n )\n return issue([...address, node.tag], 'Unknown variant tag.');\n }\n const { members } = compiledShape(node, value)!;\n for (const key of Reflect.ownKeys(value)) {\n if (node.kind === 'variant' && key === node.tag) continue;\n if (typeof key !== 'string' || !members.has(key))\n return issue([...address, String(key)], 'Property is not declared in the object schema.');\n }\n for (const [key, member] of members) {\n const child = member.node;\n if (!Object.prototype.hasOwnProperty.call(value, key) && !child.optional)\n return issue([...address, key], 'Required property is missing.');\n const failure = checkValue(child, value[key], [...address, key], strict);\n if (failure) return failure;\n }\n return undefined;\n }\n if (node.kind === 'table' || node.kind === 'map') {\n if (!isPlainObject(value)) return issue(address, 'Expected a collection object.');\n const entries = node.kind === 'table' ? value.byId : value;\n if (!isPlainObject(entries)) return issue(address, 'Expected a byId object.');\n if (node.kind === 'table') {\n if (!Array.isArray(value.ids) || value.ids.length !== Object.keys(entries).length)\n return issue(address, 'Table ids and entries must agree.');\n const seen = new Set<string>();\n for (const id of value.ids) {\n const failure = checkKey(node.key, id, address);\n if (failure) return failure;\n if (seen.has(id) || !Object.prototype.hasOwnProperty.call(entries, id))\n return issue(address, 'Table ids must be unique and reference existing entries.');\n seen.add(id);\n }\n }\n for (const id of Object.keys(entries)) {\n const failure =\n checkKey(node.key, id, [...address, id]) ??\n checkValue(node.value, entries[id], [...address, id], strict);\n if (failure) return failure;\n }\n return undefined;\n }\n if (node.kind === 'list') {\n if (!Array.isArray(value)) return issue(address, 'Expected a list.');\n const seen = new Set<string>();\n const order = anchor.keys(value, node.keyOf);\n for (let i = 0; i < value.length; i++) {\n const failure = checkValue(node.value, value[i], [...address, String(i)], strict);\n if (failure) return failure;\n let key: unknown;\n try {\n key = order.at(i);\n } catch {\n return issue(address, 'List keyOf failed.');\n }\n if (typeof key !== 'string' || seen.has(key))\n return issue(address, 'List keys must be unique strings.', 'invalid-key');\n seen.add(key);\n }\n return undefined;\n }\n if (!validTree(value)) return issue(address, 'Invalid tree structure.', 'invalid-tree');\n if (isRecord(value) && isRecord(value.nodes)) {\n for (const id of Object.keys(value.nodes)) {\n const entry = value.nodes[id];\n if (isRecord(entry) && Object.prototype.hasOwnProperty.call(entry, 'value')) {\n const failure = checkValue(node.value, entry.value, [...address, id], strict);\n if (failure) return failure;\n }\n }\n }\n return undefined;\n};\n\n/** Copy editable structure; atomic payloads retain their immutable ownership contract. */\nexport const copyValue = (node: DocumentNode, value: unknown): unknown => {\n if (value === undefined || node.kind === 'field') return value;\n profile.copy.structure();\n if ((node.kind === 'object' || node.kind === 'variant') && isRecord(value)) {\n const result = Object.create(Object.getPrototypeOf(value));\n const { members } = compiledShape(node, value)!;\n for (const key of Object.getOwnPropertyNames(value)) {\n Object.defineProperty(result, key, {\n value:\n node.kind === 'variant' && key === node.tag\n ? value[key]\n : copyValue(members.get(key)!.node, value[key]),\n writable: true,\n enumerable: Object.getOwnPropertyDescriptor(value, key)?.enumerable,\n configurable: true,\n });\n }\n return result;\n }\n if ((node.kind === 'table' || node.kind === 'map') && isRecord(value)) {\n const entries = (node.kind === 'table' ? value.byId : value) as Record<string, unknown>;\n const result = Object.fromEntries(\n Object.keys(entries).map(id => [id, copyValue(node.value, entries[id])])\n );\n return node.kind === 'table' ? { ids: [...(value.ids as string[])], byId: result } : result;\n }\n if (node.kind === 'list') return [...(value as unknown[])];\n if (node.kind === 'tree' && isRecord(value)) {\n const entries = value.nodes as Record<string, { children: readonly string[] }>;\n return {\n ...value,\n nodes: Object.fromEntries(\n Object.entries(entries).map(([id, n]) => [id, { ...n, children: [...n.children] }])\n ),\n };\n }\n return value;\n};\n\nexport const equalValue = (node: DocumentNode, left: unknown, right: unknown): boolean => {\n if (Object.is(left, right)) return true;\n if (node.kind === 'field' || left === undefined || right === undefined) return false;\n if ((node.kind === 'object' || node.kind === 'variant') && isRecord(left) && isRecord(right)) {\n if (node.kind === 'variant' && left[node.tag] !== right[node.tag]) return false;\n for (const [key, member] of compiledShape(node, left)!.members) {\n if (Object.hasOwn(left, key) !== Object.hasOwn(right, key)) return false;\n if (!equalValue(member.node, left[key], right[key])) return false;\n }\n return true;\n }\n if (node.kind === 'list' && Array.isArray(left) && Array.isArray(right))\n return (\n left.length === right.length && left.every((v, i) => equalValue(node.value, v, right[i]))\n );\n if (node.kind === 'table' && isRecord(left) && isRecord(right))\n return (\n anchor.equal(left.ids as string[], right.ids as string[]) &&\n equalValue({ kind: 'map', value: node.value }, left.byId, right.byId)\n );\n if (node.kind === 'tree' && isRecord(left) && isRecord(right)) {\n if (left.rootId !== right.rootId) return false;\n const a = left.nodes as Record<\n string,\n { parentId?: string; children: string[]; value?: unknown }\n >,\n b = right.nodes as typeof a;\n return (\n Object.keys(a).length === Object.keys(b).length &&\n Object.keys(a).every(\n id =>\n Object.hasOwn(b, id) &&\n a[id].parentId === b[id].parentId &&\n anchor.equal(a[id].children, b[id].children) &&\n Object.hasOwn(a[id], 'value') === Object.hasOwn(b[id], 'value') &&\n equalValue(node.value, a[id].value, b[id].value)\n )\n );\n }\n if (node.kind === 'map' && isRecord(left) && isRecord(right)) {\n const keys = Object.keys(left);\n return (\n keys.length === Object.keys(right).length &&\n keys.every(key => Object.hasOwn(right, key) && equalValue(node.value, left[key], right[key]))\n );\n }\n return false;\n};\n\nexport const parse = <N extends DocumentNode>(node: N, input: unknown): Infer<N> => {\n const valueNode: DocumentNode = node;\n const failure = checkValue(valueNode, input, [], true);\n if (failure) throw new ParseError(failure);\n return copyValue(valueNode, input) as Infer<N>;\n};\n","import type { MutationSession } from '../session';\nimport type { ResolvedContainer } from '../../address';\nimport { fail } from '../issue';\n\nexport function put(\n session: MutationSession,\n container: ResolvedContainer,\n id: string,\n value: unknown\n): void {\n if (container.node.kind !== 'map')\n return fail(container.at, 'invalid-collection', 'Expected a map.');\n session.writeMember(container, id, value, 'set');\n}\n\nexport function remove(session: MutationSession, container: ResolvedContainer, id: string): void {\n if (container.node.kind !== 'map')\n return fail(container.at, 'invalid-collection', 'Expected a map.');\n session.writeMember(container, id, undefined, 'remove');\n}\n","import type { DocumentAnchor } from '../../schema';\nimport type { MutationSession } from '../session';\nimport type { ResolvedContainer } from '../../address';\nimport * as anchor from '../anchor';\nimport { fail } from '../issue';\nexport function create(\n session: MutationSession,\n container: ResolvedContainer,\n entries: readonly { id: string; value: unknown }[],\n position?: DocumentAnchor\n): void {\n const { at, node, value } = container;\n if (node.kind !== 'table') return fail(at, 'invalid-collection', 'Expected a table.');\n const table = value as { ids: string[]; byId: Record<string, unknown> };\n if (!anchor.valid(table.ids, position))\n return fail(at, 'invalid-anchor', 'Unknown table anchor.');\n const ids = new Set<string>();\n for (const entry of entries) {\n if (Object.hasOwn(table.byId, entry.id) || ids.has(entry.id))\n return fail(at, 'duplicate-entity', 'Table key already exists.');\n ids.add(entry.id);\n }\n if (!entries.length) return;\n const index = anchor.index(table.ids, position);\n for (const entry of entries) session.writeMember(container, entry.id, entry.value, 'set');\n const length = table.ids.length;\n table.ids.length += entries.length;\n table.ids.copyWithin(index + entries.length, index, length);\n for (let i = 0; i < entries.length; i++) table.ids[index + i] = entries[i].id;\n}\nexport function remove(\n session: MutationSession,\n container: ResolvedContainer,\n ids: readonly string[]\n): void {\n const { at, node, value } = container;\n if (node.kind !== 'table') return fail(at, 'invalid-collection', 'Expected a table.');\n const table = value as { ids: string[]; byId: Record<string, unknown> };\n for (const id of ids)\n if (!Object.hasOwn(table.byId, id))\n return fail(at, 'missing-entity', 'Table key does not exist.');\n if (!ids.length) return;\n const removed = new Set(ids);\n for (const id of removed) session.writeMember(container, id, undefined, 'remove');\n table.ids = table.ids.filter(id => !removed.has(id));\n}\n\nexport function replace(\n session: MutationSession,\n container: ResolvedContainer,\n id: string,\n value: unknown\n): void {\n const { at, node, value: tableValue } = container;\n if (node.kind !== 'table') return fail(at, 'invalid-collection', 'Expected a table.');\n const table = tableValue as { byId: Record<string, unknown> };\n if (!Object.hasOwn(table.byId, id))\n return fail(at.concat(id), 'missing-entity', 'Table key does not exist.');\n session.writeMember(container, id, value, 'set');\n}\n","import type { DocumentAnchor } from '../../schema';\nimport type { MutationSession } from '../session';\nimport type { ResolvedContainer } from '../../address';\nimport * as anchor from '../anchor';\nimport { fail } from '../issue';\nexport function insert(\n session: MutationSession,\n container: ResolvedContainer,\n value: unknown,\n position?: DocumentAnchor\n): void {\n const { at, node, value: current } = container;\n if (node.kind !== 'list') return fail(at, 'invalid-list-key', 'Expected a list.');\n session.validate(node.value, value, at);\n const id = node.keyOf(value);\n if (typeof id !== 'string') return fail(at, 'invalid-list-key', 'List key must be a string.');\n const items = current as unknown[],\n keys = anchor.keys(items, node.keyOf);\n if (keys.index(id) >= 0) return fail(at, 'duplicate-list-item', 'List key already exists.');\n if (!anchor.valid(keys, position)) return fail(at, 'invalid-anchor', 'Unknown list anchor.');\n session.recorder.order(container);\n session.recorder.member(container, id, session.definition(container, id), -1);\n anchor.insert(items, anchor.index(keys, position), value);\n session.invalidate();\n}\nexport function replace(\n session: MutationSession,\n container: ResolvedContainer,\n id: string,\n value: unknown\n): void {\n const { at, node, value: items } = container;\n if (node.kind !== 'list') return fail(at, 'invalid-list-key', 'Expected a list.');\n const index = anchor.indexedKeys(items as unknown[], node.keyOf).index(id);\n if (index < 0) return fail(at, 'missing-list-item', 'List key does not exist.');\n session.writeMember(container, id, value, 'set', index);\n}\nexport function remove(session: MutationSession, container: ResolvedContainer, id: string): void {\n const { at, node, value } = container;\n if (node.kind !== 'list') return fail(at, 'missing-list-item', 'List key does not exist.');\n const index = anchor.keys(value as unknown[], node.keyOf).index(id);\n if (index < 0) return fail(at, 'missing-list-item', 'List key does not exist.');\n session.writeMember(container, id, undefined, 'remove', index);\n}\n","import type { DocumentAddress } from '../../schema';\nimport type { ResolvedTreeContainer } from '../../address';\nimport type { MutationSession } from '../session';\nimport { contains, type MutableTree, type TreePosition } from '../tree';\nimport { fail } from '../issue';\nconst node = (tree: MutableTree, id: string) =>\n Object.hasOwn(tree.nodes, id) ? tree.nodes[id] : undefined;\nconst positionIndex = (index: number | undefined, length: number, at: DocumentAddress): number => {\n if (index !== undefined && (!Number.isInteger(index) || index < 0))\n return fail(at, 'invalid-tree-index', 'Tree index must be nonnegative.');\n return Math.min(index ?? length, length);\n};\nexport const insert = (\n session: MutationSession,\n container: ResolvedTreeContainer,\n id: string,\n value: unknown,\n position: TreePosition | undefined\n): void => {\n const { at, node: schema, value: tree } = container;\n if (typeof id !== 'string') return fail(at, 'invalid-key', 'Tree keys must be strings.');\n if (contains(tree, id)) return fail(at, 'duplicate-tree-node', 'Tree node already exists.');\n const parentId = position?.parentId;\n const parent = parentId === undefined ? undefined : node(tree, parentId);\n if (\n (tree.rootId !== undefined && !parent) ||\n (tree.rootId === undefined && parentId !== undefined)\n )\n return fail(at, 'missing-tree-parent', 'A nonempty tree requires an existing parent.');\n const index = positionIndex(position?.index, parent?.children.length ?? 0, at);\n session.validate(schema.value, value, at.concat(id));\n session.recorder.tree(container, id);\n if (parentId !== undefined) session.recorder.tree(container, parentId);\n Object.defineProperty(tree.nodes, id, {\n value: { ...(parentId === undefined ? {} : { parentId }), children: [], value },\n writable: true,\n configurable: true,\n enumerable: true,\n });\n if (parent) parent.children.splice(index, 0, id);\n else tree.rootId = id;\n session.invalidate();\n};\nexport const replace = (\n session: MutationSession,\n container: ResolvedTreeContainer,\n id: string,\n value: unknown\n): void => {\n const { at, node: schema, value: tree } = container;\n const entry = node(tree, id);\n if (!entry) return fail(at, 'missing-tree-node', 'Tree node does not exist.');\n if (Object.is(entry.value, value) && Object.hasOwn(entry, 'value')) return;\n session.validate(schema.value, value, at.concat(id));\n session.recorder.tree(container, id);\n entry.value = value;\n};\nexport const remove = (\n session: MutationSession,\n container: ResolvedTreeContainer,\n id: string\n): void => {\n const { at, value: tree } = container;\n const entry = node(tree, id);\n if (!entry) return fail(at, 'missing-tree-node', 'Tree node does not exist.');\n const ids: string[] = [],\n stack = [id];\n while (stack.length) {\n const current = stack.pop()!;\n ids.push(current);\n for (const child of tree.nodes[current].children) stack.push(child);\n }\n for (const key of ids) session.recorder.tree(container, key);\n if (entry.parentId !== undefined) session.recorder.tree(container, entry.parentId);\n if (entry.parentId === undefined) delete tree.rootId;\n else {\n const children = tree.nodes[entry.parentId].children;\n children.splice(children.indexOf(id), 1);\n }\n for (const key of ids) delete tree.nodes[key];\n session.invalidate();\n};\nexport const move = (\n session: MutationSession,\n container: ResolvedTreeContainer,\n id: string,\n position: TreePosition | undefined\n): void => {\n const { at, value: tree } = container;\n const entry = node(tree, id),\n parentId = position?.parentId;\n if (!entry) return fail(at, 'missing-tree-node', 'Tree node does not exist.');\n if (entry.parentId === undefined || parentId === undefined || !contains(tree, parentId))\n return fail(\n at,\n 'missing-tree-parent',\n 'Moving requires a non-root node and an existing parent.'\n );\n for (\n let ancestor: string | undefined = parentId;\n ancestor !== undefined;\n ancestor = tree.nodes[ancestor].parentId\n )\n if (ancestor === id) return fail(at, 'tree-cycle', 'Cannot move a node under its descendant.');\n const old = tree.nodes[entry.parentId],\n next = tree.nodes[parentId];\n const index = positionIndex(position?.index, next.children.length - (old === next ? 1 : 0), at);\n const previous = old.children.indexOf(id);\n if (old === next && previous === index) return;\n session.recorder.tree(container, id);\n session.recorder.tree(container, entry.parentId);\n session.recorder.tree(container, parentId);\n old.children.splice(previous, 1);\n next.children.splice(index, 0, id);\n entry.parentId = parentId;\n session.invalidate();\n};\n","import type { DocumentAnchor } from '../../schema';\nimport type { MutationSession } from '../session';\nimport type { ResolvedContainer } from '../../address';\nimport * as anchor from '../anchor';\nimport { fail } from '../issue';\n\nconst assertOrdered = (\n container: ResolvedContainer\n): Extract<ResolvedContainer['node'], { kind: 'table' | 'list' }> => {\n const { at, node } = container;\n if (node.kind !== 'table' && node.kind !== 'list')\n return fail(at, 'invalid-collection', 'Expected an ordered container.');\n return node;\n};\n\nconst plannedOrder = (\n at: ResolvedContainer['at'],\n current: readonly string[],\n selection: readonly string[],\n position?: DocumentAnchor\n): readonly string[] => {\n const plan = anchor.moveSelection(current, selection, position);\n switch (plan.kind) {\n case 'ok':\n return plan.order;\n case 'duplicate':\n return fail(at, 'invalid-key', 'Moved keys must be unique.');\n case 'missing':\n return fail(at, 'missing-entity', 'Ordered key does not exist.');\n case 'invalid-anchor':\n return fail(at, 'invalid-anchor', 'Unknown order anchor.');\n }\n};\n\nexport function move(\n session: MutationSession,\n container: ResolvedContainer,\n ids: string | readonly string[],\n position?: DocumentAnchor\n): void {\n const node = assertOrdered(container);\n const selection = typeof ids === 'string' ? [ids] : ids;\n if (!selection.length) return;\n\n if (node.kind === 'table') {\n const order = (container.value as { ids: string[] }).ids;\n const next = plannedOrder(container.at, order, selection, position);\n if (anchor.equal(order, next)) return;\n session.recorder.order(container);\n anchor.installKeys(order, next);\n } else {\n const items = container.value as unknown[];\n const sequence = anchor.listSequence(items, node.keyOf);\n const next = plannedOrder(container.at, sequence.order, selection, position);\n if (anchor.equal(sequence.order, next)) return;\n session.recorder.order(container);\n anchor.installList(items, node.keyOf, sequence, next);\n }\n session.invalidate();\n}\n\nexport function reorder(\n session: MutationSession,\n container: ResolvedContainer,\n next: readonly string[]\n): void {\n const node = assertOrdered(container);\n if (node.kind === 'table') {\n const current = (container.value as { ids: string[] }).ids;\n if (!anchor.matches(next, current))\n return fail(container.at, 'invalid-collection', 'Order must contain every key exactly once.');\n if (anchor.equal(current, next)) return;\n session.recorder.order(container);\n anchor.installKeys(current, next);\n } else {\n const items = container.value as unknown[];\n const sequence = anchor.listSequence(items, node.keyOf);\n if (!anchor.matches(next, sequence.order))\n return fail(container.at, 'invalid-collection', 'Order must contain every key exactly once.');\n if (anchor.equal(sequence.order, next)) return;\n session.recorder.order(container);\n anchor.installList(items, node.keyOf, sequence, next);\n }\n session.invalidate();\n}\n","import type {\n DocumentAddress,\n DocumentAnchor,\n DocumentNode,\n DocumentTreeValue,\n FieldNode,\n Infer,\n ListNode,\n MapNode,\n ObjectNode,\n ObjectShape,\n ReadonlyValue,\n TableNode,\n TreeNode,\n ValueSchemaNode,\n VariantNode,\n} from '../schema';\nimport {\n nodeAt,\n resolveChild,\n resolveLocated,\n compiledShape,\n type FixedMember,\n type ResolvedContainer,\n type ResolvedTreeContainer,\n} from '../address';\nimport { copyValue } from '../schema-value';\nimport type { DependencyTracker } from './dependency';\nimport type { CanonicalState } from '../mutation/state';\nimport type { MutationSession } from '../mutation/session';\nimport * as mapOperations from '../mutation/operations/map';\nimport * as tableOperations from '../mutation/operations/table';\nimport * as listOperations from '../mutation/operations/list';\nimport * as treeOperations from '../mutation/operations/tree';\nimport * as orderOperations from '../mutation/operations/order';\nimport * as tree from '../mutation/tree';\nimport * as anchor from '../mutation/anchor';\nimport { profile } from '../profile';\n\ndeclare const scopeValue: unique symbol;\ntype Scoped<N extends DocumentNode, W extends boolean, V = Infer<N>> = {\n readonly [scopeValue]?: readonly [node: N, writable: W, value: V];\n};\ntype ShapeAccess<S extends ObjectShape, W extends boolean> = W extends true\n ? { -readonly [K in keyof S]: Access<S[K], W> }\n : { readonly [K in keyof S]: Access<S[K], W> };\ntype MapAccess<K extends string, N extends ValueSchemaNode, W extends boolean> = {\n get(id: K): Access<N, W> | undefined;\n has(id: K): boolean;\n ids(): readonly K[];\n} & (W extends true\n ? {\n put(id: K, value: Infer<N>): void;\n remove(id: K): void;\n replace(value: Readonly<Record<K, Infer<N>>>): void;\n }\n : {});\ntype TableAccess<K extends string, N extends ValueSchemaNode, W extends boolean> = {\n get(id: K): Access<N, W> | undefined;\n has(id: K): boolean;\n ids(): readonly K[];\n} & (W extends true\n ? {\n create(id: K, value: Infer<N>, anchor?: DocumentAnchor<K>): void;\n create(\n entries: readonly { readonly id: K; readonly value: Infer<N> }[],\n anchor?: DocumentAnchor<K>\n ): void;\n remove(ids: K | readonly K[]): void;\n move(ids: K | readonly K[], anchor?: DocumentAnchor<K>): void;\n reorder(ids: readonly K[]): void;\n replace(value: {\n readonly ids: readonly K[];\n readonly byId: Readonly<Record<K, Infer<N>>>;\n }): void;\n replace(id: K, value: Infer<N>): void;\n }\n : {});\ntype ListAccess<T, W extends boolean> = {\n get(key: string): ReadonlyValue<T> | undefined;\n has(key: string): boolean;\n ids(): readonly string[];\n} & (W extends true\n ? {\n insert(value: ReadonlyValue<T>, anchor?: DocumentAnchor): void;\n remove(key: string): void;\n move(keys: string | readonly string[], anchor?: DocumentAnchor): void;\n reorder(keys: readonly string[]): void;\n replace(value: readonly ReadonlyValue<T>[]): void;\n replace(key: string, value: ReadonlyValue<T>): void;\n }\n : {});\ntype TreeAccess<T, W extends boolean> = {\n rootId(): string | undefined;\n get(id: string): ReadonlyValue<T> | undefined;\n has(id: string): boolean;\n parent(id: string): string | undefined;\n children(id: string): readonly string[] | undefined;\n} & (W extends true\n ? {\n insert(id: string, value: ReadonlyValue<T>, position?: tree.TreePosition): void;\n move(id: string, position?: tree.TreePosition): void;\n remove(id: string): void;\n replace(value: DocumentTreeValue<T>): void;\n replace(id: string, value: ReadonlyValue<T>): void;\n }\n : {});\ntype NodeAccess<N extends DocumentNode, W extends boolean> =\n N extends FieldNode<infer T, boolean>\n ? ReadonlyValue<T>\n : N extends ObjectNode<infer S>\n ? ShapeAccess<S, W> & Scoped<N, W>\n : N extends VariantNode<infer Tag, infer V>\n ? {\n [K in keyof V & string]: ShapeAccess<V[K]['shape'], W> & {\n readonly [P in Tag]: K;\n } & Scoped<N, W, Extract<Infer<N>, Record<Tag, K>>>;\n }[keyof V & string]\n : N extends MapNode<infer V, infer K>\n ? MapAccess<K, V, W> & Scoped<N, W>\n : N extends TableNode<infer V, infer K>\n ? TableAccess<K, V, W> & Scoped<N, W>\n : N extends ListNode<infer T>\n ? ListAccess<T, W> & Scoped<N, W>\n : N extends TreeNode<infer T>\n ? TreeAccess<T, W> & Scoped<N, W>\n : never;\ntype Access<N extends DocumentNode, W extends boolean> = N extends { readonly optional: true }\n ? NodeAccess<N, W> | undefined\n : NodeAccess<N, W>;\nexport type Read<N extends DocumentNode> = Access<N, false>;\nexport type Draft<N extends DocumentNode> = Access<N, true>;\ntype Snapshot<T> = T extends {\n readonly [scopeValue]?: readonly [DocumentNode, boolean, infer V];\n}\n ? V\n : ReadonlyValue<T>;\ntype Target = {\n at?: DocumentAddress;\n parent?: Target;\n key: string;\n node: DocumentNode | undefined;\n value: unknown;\n generation: number;\n children:\n | { kind: 'fixed'; schema: DocumentNode; slots: (Target | undefined)[] }\n | { kind: 'dynamic'; keys: Map<string, Target> }\n | undefined;\n proxy: object | undefined;\n container?: ResolvedContainer | ResolvedTreeContainer;\n};\ntype Location = { readonly context: AccessContext; readonly target: Target };\nconst locations = new WeakMap<object, Location>();\nconst locationOf = (value: object): Location | undefined => locations.get(value);\nconst addressOf = (target: Target): DocumentAddress => {\n if (target.at) return target.at;\n profile.access('addresses');\n return (target.at = addressOf(target.parent!).concat(target.key));\n};\nexport type AccessContext = {\n readonly state: CanonicalState;\n /** Omitted for borrowed synchronous Draft and readers that must not escape. */\n readonly active?: () => boolean;\n readonly dependencies?: DependencyTracker;\n readonly session?: MutationSession;\n};\nconst assertActive = (context: AccessContext) => {\n if (context.active && !context.active()) throw new Error('Document access scope has expired.');\n};\nconst collect = (\n context: AccessContext,\n at: DocumentAddress,\n kind: 'value' | 'collection' = 'value',\n id?: string\n) => {\n context.dependencies?.record(\n kind === 'value' ? { kind, at } : { kind, at, ...(id === undefined ? {} : { id }) }\n );\n};\nexport const snapshot = <T>(value: T): Snapshot<T> => {\n const location = value && typeof value === 'object' ? locationOf(value) : undefined;\n if (!location) return value as Snapshot<T>;\n const { context } = location;\n const at = addressOf(location.target);\n profile.access('snapshots');\n collect(context, at);\n const resolved = resolve(context, location.target);\n if (!resolved.node) throw new Error('The selected schema address no longer exists.');\n return copyValue(resolved.node, resolved.value) as Snapshot<T>;\n};\n/** Replace a member with its plain Infer value through the owning draft session. */\ntype ReplaceParentAccess = {\n readonly [scopeValue]?: readonly [\n Extract<DocumentNode, { readonly kind: 'object' | 'variant' }>,\n true,\n unknown,\n ];\n};\nexport const replace = <T extends object & ReplaceParentAccess, K extends keyof Snapshot<T>>(\n container: T,\n key: K,\n value: NoInfer<Snapshot<T>[K]>\n): void => {\n const location = locationOf(container);\n if (!location) throw new TypeError('replace requires scoped document access.');\n if (typeof key !== 'string') throw new TypeError('Document keys must be strings.');\n Reflect.set(container, key, value);\n};\n/** Projection collection contexts use the same scoped access, with explicit collection tools. */\nexport type CollectionAccess<K extends string, N extends ValueSchemaNode> = TableAccess<\n K,\n N,\n false\n>;\nconst resolve = (context: AccessContext, target: Target): Target => {\n assertActive(context);\n const generation = context.session?.generation ?? 0;\n if (target.generation !== generation) {\n profile.access('resolutions');\n if (!target.parent && !target.at!.length) {\n target.node = context.state.schema;\n target.value = context.state.document;\n } else {\n const parent = target.parent && resolve(context, target.parent);\n const location = parent\n ? resolveChild(parent.node, parent.value, target.key)\n : resolveLocated(context.state.schema, context.state.document, target.at!);\n target.node =\n location?.node ?? nodeAt(context.state.schema, addressOf(target), context.state.document);\n target.value =\n location && Object.hasOwn(location.parent, location.key)\n ? (location.parent as Record<string | number, unknown>)[location.key]\n : undefined;\n }\n target.generation = generation;\n }\n return target;\n};\n\nexport const createAccess = (context: AccessContext, initial: DocumentAddress = []): unknown => {\n profile.access('scopes');\n const mutable = (): MutationSession => {\n assertActive(context);\n if (!context.session) throw new TypeError('Cannot modify read-only document access.');\n return context.session;\n };\n const writableContainer = (target: Target, session: MutationSession): ResolvedContainer => {\n if (target.container?.generation === session.generation && 'layout' in target.container)\n return target.container;\n return (target.container = session.bind(addressOf(target), target.node, target.value));\n };\n const childAt = (target: Target, key: string): DocumentAddress => {\n profile.access('addresses');\n return addressOf(target).concat(key);\n };\n const access = (target: Target): unknown => {\n if (target.proxy) return target.proxy;\n const proxy = new Proxy(target, handler);\n profile.access('proxies');\n locations.set(proxy, { context, target });\n target.proxy = proxy;\n return proxy;\n };\n const createTarget = (\n at: DocumentAddress | undefined,\n parent: Target | undefined,\n key: string\n ): Target => ({\n at,\n parent,\n key,\n node: undefined,\n value: undefined,\n generation: -1,\n children: undefined,\n proxy: undefined,\n });\n const childAccess = (\n target: Target,\n member: string | FixedMember,\n node: DocumentNode,\n value: unknown\n ) => {\n const key = typeof member === 'string' ? member : member.key;\n if (node.kind === 'field' || value === undefined) {\n if (context.dependencies) collect(context, childAt(target, key));\n return value;\n }\n let children = target.children;\n let child: Target;\n if (typeof member !== 'string') {\n if (children?.kind !== 'fixed' || children.schema !== target.node)\n children = {\n kind: 'fixed',\n schema: target.node!,\n slots: new Array(compiledShape(target.node!, target.value)!.members.size),\n };\n child = children.slots[member.slot] ??= createTarget(undefined, target, key);\n } else {\n if (children?.kind !== 'dynamic') children = { kind: 'dynamic', keys: new Map() };\n const retained = children.keys.get(key);\n child = retained ?? createTarget(undefined, target, key);\n if (!retained) children.keys.set(key, child);\n }\n target.children = children;\n if (child.generation === target.generation) return child.proxy;\n child.node = node;\n child.value = value;\n child.generation = target.generation;\n return access(child);\n };\n const collectionValue = (target: Target, node: DocumentNode) => {\n const current = resolve(context, target);\n if (current.node !== node || current.value === undefined)\n throw new TypeError('The collection method belongs to a replaced schema branch.');\n return current.value;\n };\n const writableCollection = (target: Target, node: DocumentNode): ResolvedContainer => {\n const session = mutable();\n collectionValue(target, node);\n return writableContainer(target, session);\n };\n const writableTree = (target: Target, node: DocumentNode): ResolvedTreeContainer => {\n const session = mutable();\n collectionValue(target, node);\n if (target.container?.generation === session.generation && !('layout' in target.container))\n return target.container;\n return (target.container = session.bindTree(addressOf(target), target.node, target.value));\n };\n const replaceCollection = (target: Target, node: DocumentNode, value: unknown) => {\n const session = mutable();\n collectionValue(target, node);\n session.replace(addressOf(target), value);\n };\n const mapMethod = (\n target: Target,\n property: string,\n node: Extract<DocumentNode, { kind: 'map' }>\n ): unknown => {\n if (property === 'ids')\n return () => {\n const current = collectionValue(target, node) as Record<string, unknown>;\n if (context.dependencies) collect(context, addressOf(target), 'collection');\n return Object.keys(current);\n };\n if (property === 'has')\n return (id: string) => {\n const current = collectionValue(target, node) as Record<string, unknown>;\n if (context.dependencies) collect(context, addressOf(target), 'collection', id);\n return Object.hasOwn(current, id);\n };\n if (property === 'get')\n return (id: string) => {\n const current = collectionValue(target, node) as Record<string, unknown>;\n if (context.dependencies) collect(context, addressOf(target), 'collection', id);\n if (!Object.hasOwn(current, id)) return undefined;\n if (node.value.kind === 'field') {\n if (context.dependencies) collect(context, childAt(target, id));\n return current[id];\n }\n return childAccess(target, id, node.value, current[id]);\n };\n if (property === 'put')\n return (id: string, value: unknown) => {\n const writable = writableCollection(target, node);\n mapOperations.put(context.session!, writable, id, value);\n };\n if (property === 'remove')\n return (id: string) => {\n const writable = writableCollection(target, node);\n mapOperations.remove(context.session!, writable, id);\n };\n if (property === 'replace') return (value: unknown) => replaceCollection(target, node, value);\n return undefined;\n };\n const orderedMethod = (\n target: Target,\n property: string,\n node: Extract<DocumentNode, { kind: 'table' | 'list' }>\n ): unknown => {\n const at = addressOf(target);\n if (property === 'ids')\n return () => {\n const current = collectionValue(target, node);\n collect(context, at, 'collection');\n return node.kind === 'table'\n ? [...(current as { ids: string[] }).ids]\n : (current as unknown[]).map(node.keyOf);\n };\n if (property === 'has')\n return (id: string) => {\n const current = collectionValue(target, node);\n collect(context, at, 'collection', id);\n return node.kind === 'table'\n ? Object.hasOwn((current as { byId: object }).byId, id)\n : anchor.indexedKeys(current as unknown[], node.keyOf).index(id) >= 0;\n };\n if (property === 'get')\n return (id: string) => {\n const current = collectionValue(target, node);\n collect(context, at, 'collection', id);\n const location = resolveChild(node, current, id);\n if (!location || !Object.hasOwn(location.parent, location.key)) return undefined;\n return childAccess(\n target,\n id,\n location.node,\n (location.parent as Record<string | number, unknown>)[location.key]\n );\n };\n if (property === 'move')\n return (ids: string | readonly string[], position?: DocumentAnchor) => {\n const writable = writableCollection(target, node);\n orderOperations.move(context.session!, writable, ids, position);\n };\n if (property === 'reorder')\n return (ids: readonly string[]) => {\n const writable = writableCollection(target, node);\n orderOperations.reorder(context.session!, writable, ids);\n };\n return undefined;\n };\n const tableMethod = (\n target: Target,\n property: string,\n node: Extract<DocumentNode, { kind: 'table' }>\n ): unknown => {\n if (property === 'create')\n return (\n input: string | readonly { id: string; value: unknown }[],\n valueOrPosition?: unknown,\n position?: DocumentAnchor\n ) => {\n const writable = writableCollection(target, node);\n tableOperations.create(\n context.session!,\n writable,\n Array.isArray(input) ? input : [{ id: input as string, value: valueOrPosition }],\n Array.isArray(input) ? (valueOrPosition as DocumentAnchor | undefined) : position\n );\n };\n if (property === 'remove')\n return (ids: string | readonly string[]) => {\n const writable = writableCollection(target, node);\n tableOperations.remove(context.session!, writable, typeof ids === 'string' ? [ids] : ids);\n };\n if (property === 'replace')\n return (...args: [unknown, unknown?]) => {\n const [valueOrId, value] = args;\n if (args.length === 1) return replaceCollection(target, node, valueOrId);\n const writable = writableCollection(target, node);\n tableOperations.replace(context.session!, writable, valueOrId as string, value);\n };\n return orderedMethod(target, property, node);\n };\n const listMethod = (\n target: Target,\n property: string,\n node: Extract<DocumentNode, { kind: 'list' }>\n ): unknown => {\n if (property === 'insert')\n return (value: unknown, position?: DocumentAnchor) => {\n const writable = writableCollection(target, node);\n listOperations.insert(context.session!, writable, value, position);\n };\n if (property === 'remove')\n return (id: string) => {\n const writable = writableCollection(target, node);\n listOperations.remove(context.session!, writable, id);\n };\n if (property === 'replace')\n return (...args: [unknown, unknown?]) => {\n const [valueOrId, value] = args;\n if (args.length === 1) return replaceCollection(target, node, valueOrId);\n const writable = writableCollection(target, node);\n listOperations.replace(context.session!, writable, valueOrId as string, value);\n };\n return orderedMethod(target, property, node);\n };\n const treeMethod = (\n target: Target,\n property: string,\n node: Extract<DocumentNode, { kind: 'tree' }>\n ): unknown => {\n const at = addressOf(target);\n if (property === 'insert')\n return (id: string, value: unknown, position?: tree.TreePosition) => {\n const writable = writableTree(target, node);\n treeOperations.insert(context.session!, writable, id, value, position);\n };\n if (property === 'remove')\n return (id: string) => {\n const writable = writableTree(target, node);\n treeOperations.remove(context.session!, writable, id);\n };\n if (property === 'move')\n return (id: string, position?: tree.TreePosition) => {\n const writable = writableTree(target, node);\n treeOperations.move(context.session!, writable, id, position);\n };\n if (property === 'replace')\n return (...args: [unknown, unknown?]) => {\n const [valueOrId, value] = args;\n if (args.length === 1) return replaceCollection(target, node, valueOrId);\n const writable = writableTree(target, node);\n treeOperations.replace(context.session!, writable, valueOrId as string, value);\n };\n const current = () => {\n collect(context, at);\n return collectionValue(target, node) as tree.MutableTree;\n };\n if (property === 'rootId') return () => current().rootId;\n if (property === 'get')\n return (id: string) => {\n const value = current();\n return tree.contains(value, id) ? value.nodes[id].value : undefined;\n };\n if (property === 'has') return (id: string) => tree.contains(current(), id);\n if (property === 'parent') return (id: string) => tree.parent(current(), id);\n if (property === 'children')\n return (id: string) => {\n const children = tree.children(current(), id);\n return children ? [...children] : undefined;\n };\n return undefined;\n };\n const handler: ProxyHandler<Target> = {\n get: (target, property) => {\n const { node, value } = resolve(context, target);\n if (!node || value === undefined) return undefined;\n if (typeof property !== 'string') return undefined;\n if (node.kind === 'map') return mapMethod(target, property, node);\n if (node.kind === 'table') return tableMethod(target, property, node);\n if (node.kind === 'list') return listMethod(target, property, node);\n if (node.kind === 'tree') return treeMethod(target, property, node);\n if (node.kind === 'variant' && property === node.tag) {\n collect(context, childAt(target, property));\n return (value as Record<string, unknown>)[property];\n }\n const member = compiledShape(node, value)?.members.get(property);\n if (!member) return undefined;\n if (member.field) {\n if (context.dependencies) collect(context, childAt(target, property));\n return (value as Record<string, unknown>)[property];\n }\n return childAccess(\n target,\n node.kind === 'object' ? member : property,\n member.node,\n (value as Record<string, unknown>)[property]\n );\n },\n set: (target, property, value) => {\n const session = mutable(),\n { node } = resolve(context, target);\n if (\n typeof property !== 'string' ||\n !node ||\n (node.kind !== 'object' && node.kind !== 'variant')\n )\n throw new TypeError('Invalid structural assignment.');\n if (node.kind === 'variant' && node.tag === property)\n throw new TypeError('Variant discriminants are read-only.');\n session.assignMember(writableContainer(target, session), property, value);\n return true;\n },\n deleteProperty: (target, property) => {\n const session = mutable(),\n { node } = resolve(context, target);\n if (\n typeof property !== 'string' ||\n node?.kind === 'map' ||\n (node?.kind === 'variant' && node.tag === property)\n )\n throw new TypeError('Invalid structural deletion.');\n session.removeMember(writableContainer(target, session), property);\n return true;\n },\n has: (target, property) => {\n const { node, value } = resolve(context, target);\n if (typeof property !== 'string') return false;\n if (node?.kind === 'map') return false;\n collect(context, addressOf(target));\n return value !== undefined && Object.hasOwn(value as object, property);\n },\n ownKeys: target => {\n const { node, value } = resolve(context, target);\n if (node?.kind === 'map') return [];\n if (context.dependencies) collect(context, addressOf(target));\n return value && typeof value === 'object' ? Object.keys(value) : [];\n },\n getOwnPropertyDescriptor: (target, property) => {\n const { node, value } = resolve(context, target);\n if (node?.kind === 'map') return undefined;\n return value && Object.hasOwn(value as object, property)\n ? { enumerable: true, configurable: true }\n : undefined;\n },\n defineProperty: () => {\n assertActive(context);\n throw new TypeError('Use schema assignments.');\n },\n setPrototypeOf: () => {\n assertActive(context);\n throw new TypeError('Document prototypes are immutable.');\n },\n preventExtensions: () => {\n assertActive(context);\n throw new TypeError('Document access cannot be frozen.');\n },\n };\n const root = resolve(context, createTarget(initial, undefined, ''));\n if (!root.node || root.node.kind === 'field' || root.value === undefined) {\n if (context.dependencies) collect(context, initial);\n return root.value;\n }\n return access(root);\n};\nexport const collectionAccess = (\n context: AccessContext,\n at: DocumentAddress\n): CollectionAccess<string, ValueSchemaNode> => {\n const value = createAccess(context, at);\n if (value === undefined)\n return {\n get: () => {\n assertActive(context);\n return undefined;\n },\n has: () => {\n assertActive(context);\n return false;\n },\n ids: () => {\n assertActive(context);\n return [];\n },\n };\n return value as CollectionAccess<string, ValueSchemaNode>;\n};\n","import type { DocumentAddress, ObjectNode, PathPick, Infer } from '../schema';\nimport type { AddressRef } from '../address';\nimport type { ChangeSet } from '../changes';\nimport type { DocumentImpact } from '../impact';\nimport type { Draft } from '../access/scope';\nimport type { MutationIssue } from '../mutation/issue';\nimport type { Readable } from '../projection/readable';\nexport type Unsubscribe = () => void;\nexport type Synchronous<T> = T extends PromiseLike<unknown> ? never : T;\nexport type CommitSource = 'local' | 'system' | 'history' | 'remote';\nexport class DocumentReentrancyError extends Error {\n constructor() {\n super('Document writes cannot be re-entered during an update or notification.');\n this.name = 'DocumentReentrancyError';\n }\n}\nexport class DocumentDisposedError extends Error {\n constructor() {\n super('Doxum runtime has been disposed.');\n this.name = 'DocumentDisposedError';\n }\n}\nexport type DiagnosticInput = {\n readonly code: string;\n readonly message: string;\n readonly address?: DocumentAddress;\n};\nexport type DocumentDiagnostic = DiagnosticInput & { readonly source: 'application' };\nexport type DocumentProblem = DocumentDiagnostic | MutationIssue;\nexport class TransactionRejected extends Error {\n readonly issues: readonly DocumentDiagnostic[];\n constructor(input: DiagnosticInput | readonly DiagnosticInput[]) {\n super('Document update rejected.');\n this.name = 'TransactionRejected';\n const issues: readonly DiagnosticInput[] = Array.isArray(input)\n ? input\n : [input as DiagnosticInput];\n this.issues = Object.freeze(\n issues.map(issue =>\n Object.freeze({\n code: issue.code,\n message: issue.message,\n source: 'application' as const,\n ...(issue.address === undefined ? {} : { address: Object.freeze([...issue.address]) }),\n })\n )\n );\n }\n}\nexport type DocumentCommit<S extends ObjectNode> = {\n readonly revision: number;\n readonly source: CommitSource;\n readonly changes: ChangeSet;\n readonly impact: DocumentImpact<S>;\n};\nexport type ObserverError = {\n readonly phase: 'processor' | 'flush' | 'listener';\n readonly error: unknown;\n};\nexport type TransactionResult<V, C> =\n | {\n readonly status: 'committed';\n readonly value: V;\n readonly commit: C;\n readonly observerErrors: readonly ObserverError[];\n }\n | { readonly status: 'unchanged'; readonly value: V; readonly revision: number }\n | {\n readonly status: 'rejected';\n readonly issues: readonly DocumentProblem[];\n readonly revision: number;\n };\nexport type OperationResult<C> =\n | {\n readonly status: 'committed';\n readonly commit: C;\n readonly observerErrors: readonly ObserverError[];\n }\n | { readonly status: 'unchanged'; readonly revision: number }\n | {\n readonly status: 'rejected';\n readonly issues: readonly MutationIssue[];\n readonly revision: number;\n };\nexport type HistoryState = { readonly undoDepth: number; readonly redoDepth: number };\nexport type LocalHistory<C> = Readable<HistoryState> & {\n undo(): OperationResult<C>;\n redo(): OperationResult<C>;\n clear(): void;\n group(): { end(): void; cancel(): OperationResult<C> };\n};\nexport type CommitListener<S extends ObjectNode> = (commit: DocumentCommit<S>) => void;\nexport type DocumentReadable<S extends ObjectNode> = {\n readonly address: {\n resolve(address: DocumentAddress): AddressRef | undefined;\n read(address: DocumentAddress): unknown;\n contains(parent: DocumentAddress, child: DocumentAddress): boolean;\n overlaps(left: DocumentAddress, right: DocumentAddress): boolean;\n debugKey(address: DocumentAddress): string;\n };\n revision(): number;\n subscribe(listener: CommitListener<S>): Unsubscribe;\n subscribe(\n pick: PathPick<S> | readonly [PathPick<S>, ...PathPick<S>[]],\n listener: CommitListener<S>\n ): Unsubscribe;\n};\nexport type DocumentRuntime<S extends ObjectNode> = DocumentReadable<S> & {\n readonly schema: S;\n update<V>(\n run: (draft: Draft<S>) => Synchronous<V>,\n options?: {\n readonly source?: Extract<CommitSource, 'local' | 'system'>;\n readonly history?: boolean;\n }\n ): TransactionResult<V, DocumentCommit<S>>;\n apply(\n changes: unknown,\n options: {\n readonly expectedRevision: number;\n readonly source?: Exclude<CommitSource, 'history'>;\n readonly history?: boolean;\n }\n ): OperationResult<DocumentCommit<S>>;\n replace(\n value: Infer<S>,\n options?: { readonly source?: Extract<CommitSource, 'system' | 'remote'> }\n ): OperationResult<DocumentCommit<S>>;\n snapshot(): Infer<S>;\n readonly history: LocalHistory<DocumentCommit<S>>;\n dispose(): void;\n};\n","import type { ObjectNode, Infer } from '../schema';\nimport { createAccess, type Read } from '../access/scope';\nimport type { DependencyTracker } from '../access/dependency';\nimport { DocumentDisposedError } from './contract';\nimport type { DocumentReadable } from './contract';\n\nexport type RuntimeAccessState<TSchema extends ObjectNode> = {\n readonly schema: TSchema;\n document: Infer<TSchema>;\n disposed: boolean;\n projectionLocks?: number;\n};\n\nconst states = new WeakMap<object, RuntimeAccessState<ObjectNode>>();\n\nexport const bindRuntimeAccess = <TSchema extends ObjectNode>(\n runtime: DocumentReadable<TSchema>,\n state: RuntimeAccessState<TSchema>\n): void => {\n states.set(runtime as object, state as RuntimeAccessState<ObjectNode>);\n};\n\nexport const accessOf = <TSchema extends ObjectNode>(\n runtime: DocumentReadable<TSchema>\n): RuntimeAccessState<TSchema> => {\n const state = states.get(runtime as object);\n if (!state) throw new Error('Unknown Doxum runtime.');\n return state as RuntimeAccessState<TSchema>;\n};\n\nexport const readWith = <TSchema extends ObjectNode, TResult>(\n runtime: DocumentReadable<TSchema>,\n run: (read: Read<TSchema>) => TResult,\n dependencies?: DependencyTracker\n): TResult => {\n const state = accessOf(runtime);\n if (state.disposed) throw new DocumentDisposedError();\n state.projectionLocks = (state.projectionLocks ?? 0) + 1;\n try {\n const reader = createAccess({\n state,\n dependencies,\n }) as Read<TSchema>;\n return run(reader);\n } finally {\n // readWith is an internal borrowed-reader boundary. Retaining its reader or\n // collection methods after this callback is undefined behavior.\n state.projectionLocks!--;\n }\n};\n"],"mappings":";;AAgCA,IAAa,aAAb,cAAgC,UAAU;CACxC;CACA,YAAY,OAAmB;AAC7B,QAAM,GAAG,MAAM,QAAQ,MAAM,KAAK,UAAU,MAAM,QAAQ,GAAG;AAC7D,OAAK,OAAO;AACZ,OAAK,SAAS,OAAO,OAAO,CAC1B,OAAO,OAAO;GAAE,GAAG;GAAO,SAAS,OAAO,OAAO,CAAC,GAAG,MAAM,QAAQ,CAAC;GAAE,CAAC,CACxE,CAAC;;;AAIN,MAAM,SACJ,SACA,SACA,OAA2B,qBACX;CAAE;CAAS;CAAS;CAAM;AAE5C,MAAa,eACX,WACA,OACA,SACA,WAC2B;AAC3B,KAAI,CAAC,UACH,QAAO,SACH,MAAM,SAAS,qDAAqD,oBAAoB,GACxF,KAAA;AACN,KAAI;EACF,MAAM,SACJ,OAAO,cAAc,aAAa,UAAU,MAAM,GAAG,UAAU,aAAa,SAAS,MAAM;AAC7F,MACE,WACC,OAAO,WAAW,YAAY,OAAO,WAAW,eACjD,UAAU,UACV,OAAO,OAAO,SAAS,WAEvB,QAAO,MAAM,SAAS,kCAAkC;AAC1D,MAAI,OAAO,cAAc,YAAY;AACnC,O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IAJQ,aAAa;GAC1B;GACA;GACD,CACgB,CAAC;WACV;AAGR,QAAM"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"advanced-BRL5pN0y.cjs","names":["checkKey","accessOf"],"sources":["../core/src/schema.ts","../core/src/projection/contract.ts","../core/src/projection/scheduler.ts","../core/src/projection/collection-output.ts","../core/src/projection/definition.ts","../core/src/projection/advanced.ts"],"sourcesContent":["import type { Validator } from './schema-value';\nimport { checkKey } from './schema-value';\nexport type DocumentAddress = readonly string[];\n\n/** Shared payloads are immutable through every alias, including builtin methods. */\nexport type ReadonlyValue<T> = T extends (...args: never[]) => unknown\n ? T\n : T extends ReadonlyMap<infer K, infer V>\n ? ReadonlyMap<ReadonlyValue<K>, ReadonlyValue<V>>\n : T extends ReadonlySet<infer V>\n ? ReadonlySet<ReadonlyValue<V>>\n : T extends Date\n ? Omit<Date, `set${string}`>\n : T extends object\n ? { readonly [K in keyof T]: ReadonlyValue<T[K]> }\n : T;\n\nexport type DocumentListConfig<TItem> = {\n readonly keyOf: (item: ReadonlyValue<TItem>) => string;\n};\nexport type DocumentTreeNode<TValue> = {\n readonly parentId?: string;\n readonly children: readonly string[];\n readonly value?: ReadonlyValue<TValue>;\n};\nexport type DocumentTreeValue<TValue> = {\n readonly rootId?: string;\n readonly nodes: Readonly<Record<string, DocumentTreeNode<TValue>>>;\n};\n\ntype BaseNode<K extends string> = {\n readonly kind: K;\n readonly optional?: boolean;\n};\nexport type FieldNode<T, Optional extends boolean = false> = BaseNode<'field'> & {\n readonly __value?: T;\n readonly validator?: Validator<T>;\n} & (Optional extends true ? { readonly optional: true } : { readonly optional?: false });\n/** A node with optional presence. The marker replaces, rather than intersects, a field marker. */\nexport type OptionalNode<TNode extends DocumentNode> =\n TNode extends FieldNode<infer TValue, boolean>\n ? FieldNode<TValue, true>\n : TNode & { readonly optional: true };\nexport interface ObjectShape {\n readonly [key: string]: DocumentNode;\n}\nexport type ObjectNode<TShape extends ObjectShape = ObjectShape> = BaseNode<'object'> & {\n readonly shape: TShape;\n};\nexport interface VariantShape {\n readonly [key: string]: ObjectNode<ObjectShape>;\n}\nexport type VariantNode<\n TTag extends string,\n TVariants extends VariantShape,\n> = BaseNode<'variant'> & {\n readonly tag: TTag;\n readonly variants: TVariants;\n};\nexport type TableNode<\n TValue extends ObjectNode<ObjectShape> | VariantNode<string, VariantShape>,\n TKey extends string = string,\n> = BaseNode<'table'> & {\n readonly value: TValue;\n readonly key?: Validator<TKey>;\n};\nexport type MapNode<\n TValue extends ValueSchemaNode,\n TKey extends string = string,\n> = BaseNode<'map'> & {\n readonly value: TValue;\n readonly key?: Validator<TKey>;\n};\nexport type ListNode<TItem> = BaseNode<'list'> & {\n readonly value: FieldNode<TItem, false>;\n keyOf(item: ReadonlyValue<TItem>): string;\n};\nexport type TreeNode<TValue> = BaseNode<'tree'> & {\n readonly value: FieldNode<TValue, boolean>;\n};\n\nexport type DocumentNode =\n | FieldNode<unknown, false>\n | FieldNode<unknown, true>\n | ObjectNode<ObjectShape>\n | VariantNode<string, VariantShape>\n | TableNode<ObjectNode<ObjectShape> | VariantNode<string, VariantShape>>\n | MapNode<ValueSchemaNode>\n | ListNode<unknown>\n | TreeNode<unknown>;\n\n// Flatten only schema-generated objects; user-supplied field values stay opaque.\ntype SchemaObject<T> = { [K in keyof T]: T[K] } & {};\n\n/** Infer a document or node value, including optional node presence. */\nexport type Infer<T extends DocumentNode> = T extends { readonly optional: true }\n ? NodeValue<T> | undefined\n : NodeValue<T>;\n\ntype NodeValue<N> =\n N extends FieldNode<infer T, infer O>\n ? O extends true\n ? ReadonlyValue<T> | undefined\n : ReadonlyValue<T>\n : N extends ObjectNode<infer S>\n ? ShapeValue<S>\n : N extends VariantNode<infer T, infer V>\n ? {\n [K in keyof V & string]: SchemaObject<{ readonly [P in T]: K } & NodeValue<V[K]>>;\n }[keyof V & string]\n : N extends TableNode<infer V, infer K>\n ? {\n readonly ids: readonly K[];\n readonly byId: Readonly<Record<K, NodeValue<V>>>;\n }\n : N extends MapNode<infer V, infer K>\n ? Readonly<Record<K, NodeValue<V>>>\n : N extends ListNode<infer I>\n ? readonly ReadonlyValue<I>[]\n : N extends TreeNode<infer T>\n ? DocumentTreeValue<T>\n : never;\n\ntype OptionalKeys<S extends ObjectShape> = {\n [K in keyof S]: S[K] extends { readonly optional: true } ? K : never;\n}[keyof S];\ntype RequiredKeys<S extends ObjectShape> = Exclude<keyof S, OptionalKeys<S>>;\ntype ShapeValue<S extends ObjectShape> = SchemaObject<\n { readonly [K in RequiredKeys<S>]: NodeValue<S[K]> } & {\n readonly [K in OptionalKeys<S>]?: NodeValue<S[K]>;\n }\n>;\n\nexport type EntitySchemaNode = ObjectNode<ObjectShape> | VariantNode<string, VariantShape>;\nexport type ValueSchemaNode = EntitySchemaNode | FieldNode<unknown, boolean>;\nexport type DocumentAnchor<K extends string = string> =\n { readonly at: 'start' | 'end' } | { readonly before: K } | { readonly after: K };\n\nexport type CollectionSelector<\n TId extends string = string,\n TNode extends ValueSchemaNode = ValueSchemaNode,\n> = {\n readonly kind: 'collection';\n readonly schema: ObjectNode;\n readonly address: DocumentAddress;\n readonly __id?: TId;\n /** Compile-time entry schema carried by schema selectors. */\n readonly __node?: TNode;\n};\nexport type ValueSelector<TResult = unknown> = {\n readonly kind: 'value';\n readonly schema: ObjectNode;\n readonly address: DocumentAddress;\n readonly __value?: TResult;\n};\nexport type ImpactTarget<T = unknown> =\n | { readonly kind: 'value'; readonly at: DocumentAddress }\n | ValueSelector<T>\n | {\n readonly kind: 'collection';\n readonly at: DocumentAddress;\n readonly id?: string;\n }\n | CollectionSelector<string>;\ndeclare const pathValue: unique symbol;\ndeclare const collectionNode: unique symbol;\ndeclare const collectionKey: unique symbol;\ntype PathMarker<TValue> = { readonly [pathValue]: TValue };\nexport type PathValueOf<T> = T extends { readonly [pathValue]: infer TValue } ? TValue : never;\n\ntype SchemaPathFor<S extends ObjectShape = ObjectShape, TValue = unknown> = {\n readonly [K in keyof S]: PathValue<S[K]>;\n} & PathMarker<TValue>;\n\nexport type SchemaPath<S extends ObjectShape = ObjectShape> = SchemaPathFor<S, ShapeValue<S>>;\nexport type PathPick<S extends ObjectNode = ObjectNode> = (\n path: SchemaPath<S['shape']>\n) => PathMarker<unknown>;\n\ntype VariantKeys<V extends VariantShape> = {\n [K in keyof V & string]: keyof (V[K] extends ObjectNode<infer S> ? S : {});\n}[keyof V & string] &\n string;\ntype VariantFieldPath<V extends VariantShape, K extends string> = {\n [P in keyof V & string]: V[P] extends ObjectNode<infer S>\n ? K extends keyof S\n ? PathValue<S[K]>\n : never\n : never;\n}[keyof V & string];\ntype VariantPath<T extends string, V extends VariantShape, TValue> = {\n readonly [K in VariantKeys<V>]: VariantFieldPath<V, K>;\n} & { readonly [K in T]: PathMarker<keyof V & string> } & PathMarker<TValue>;\nexport type CollectionPath<\n N extends ValueSchemaNode = ValueSchemaNode,\n TValue = unknown,\n K extends string = string,\n> = PathMarker<TValue> & {\n item(id: K): PathValue<N>;\n readonly [collectionNode]: N;\n readonly [collectionKey]: K;\n};\n\ntype PathValue<N extends DocumentNode> =\n N extends ObjectNode<infer S>\n ? SchemaPathFor<S, Infer<N>>\n : N extends VariantNode<infer TTag, infer V>\n ? VariantPath<TTag, V, Infer<N>>\n : N extends TableNode<infer V, infer K>\n ? CollectionPath<V, Infer<N>, K>\n : N extends MapNode<infer V, infer K>\n ? CollectionPath<V, Infer<N>, K>\n : N extends ListNode<infer I>\n ? CollectionPath<FieldNode<I, false>, Infer<N>, string>\n : PathMarker<Infer<N>>;\ntype CollectionInfo<T> = T extends {\n readonly [collectionNode]: infer TNode extends ValueSchemaNode;\n readonly [collectionKey]: infer K extends string;\n}\n ? { readonly id: K; readonly node: TNode }\n : never;\nexport type CollectionId<T> =\n CollectionInfo<T> extends { readonly id: infer TId extends string } ? TId : string;\nexport type CollectionNode<T> =\n CollectionInfo<T> extends { readonly node: infer TNode extends ValueSchemaNode }\n ? TNode\n : ValueSchemaNode;\n\nexport const collectionEntryNode = (node: DocumentNode): ValueSchemaNode | undefined =>\n node.kind === 'map' || node.kind === 'table' || node.kind === 'list' ? node.value : undefined;\n\nconst node = <T extends DocumentNode>(value: T): T => Object.freeze(value);\nexport const field = <T>(validator?: Validator<T>): FieldNode<T> =>\n node({ kind: 'field', ...(validator ? { validator } : {}) });\ntype OptionalLeaf =\n | FieldNode<unknown, boolean>\n | VariantNode<string, VariantShape>\n | MapNode<ValueSchemaNode>\n | ListNode<unknown>\n | TreeNode<unknown>;\nexport const optional = <T extends OptionalLeaf>(value: T): OptionalNode<T> => {\n if (!['field', 'variant', 'map', 'list', 'tree'].includes(value.kind))\n throw new TypeError('Only field, variant, map, list and tree nodes support optional presence.');\n return node({ ...value, optional: true } as OptionalNode<T>);\n};\nexport const object = <S extends ObjectShape>(shape: S): ObjectNode<S> =>\n node({ kind: 'object', shape: Object.freeze({ ...shape }) });\nexport const variant = <T extends string, V extends VariantShape>(\n tag: T,\n variants: V\n): VariantNode<T, V> => node({ kind: 'variant', tag, variants: Object.freeze({ ...variants }) });\nexport const table = <V extends EntitySchemaNode, K extends string = string>(\n value: V,\n options?: { readonly key: Validator<K> }\n): TableNode<V, K> => node({ kind: 'table', value, ...options });\nexport const map = <V extends ValueSchemaNode, K extends string = string>(\n value: V,\n options?: { readonly key: Validator<K> }\n): MapNode<V, K> => node({ kind: 'map', value, ...options });\nexport const list = <TItem>(\n value: FieldNode<TItem, false>,\n config: DocumentListConfig<TItem>\n): ListNode<TItem> => node({ kind: 'list', keyOf: config.keyOf, value });\nexport const tree = <TValue>(value: FieldNode<TValue, boolean>): TreeNode<TValue> =>\n node({ kind: 'tree', value });\n\nconst paths = new WeakMap<\n object,\n {\n readonly address: DocumentAddress;\n readonly nodes: readonly DocumentNode[];\n readonly owner: object;\n }\n>();\n\nconst pathProxy = (\n nodes: readonly DocumentNode[],\n address: DocumentAddress,\n owner: object\n): object => {\n const proxy = new Proxy(\n {},\n {\n get: (_target, property: string | symbol) => {\n if (typeof property !== 'string') return undefined;\n const collection = nodes.every(node => collectionEntryNode(node) !== undefined);\n if (collection && property === 'item')\n return (id: string) => {\n if (typeof id !== 'string') throw new TypeError('Collection keys must be strings.');\n for (const node of nodes)\n if (node.kind === 'table' || node.kind === 'map') {\n const invalid = checkKey(node.key, id, [...address, id]);\n if (invalid) throw new TypeError(invalid.message);\n }\n return pathProxy(\n nodes.map(node => collectionEntryNode(node)!),\n [...address, id],\n owner\n );\n };\n const children = nodes.flatMap(node => {\n if (node.kind === 'object')\n return Object.hasOwn(node.shape, property) ? [node.shape[property]] : [];\n if (node.kind !== 'variant') return [];\n if (property === node.tag) return [field<string>()];\n return Object.values(node.variants).flatMap(branch =>\n Object.hasOwn(branch.shape, property) ? [branch.shape[property]] : []\n );\n });\n if (!children.length) throw new TypeError(`Invalid schema path segment: ${property}`);\n return pathProxy(children, [...address, property], owner);\n },\n }\n );\n paths.set(proxy, { nodes, address, owner });\n return proxy;\n};\n\nexport const compilePath = <S extends ObjectShape>(\n owner: ObjectNode<S>,\n kind: 'collection' | 'value' | 'auto',\n pick: (path: SchemaPath<S>) => unknown\n): CollectionSelector | ValueSelector => {\n const scope = {};\n const value = pick(pathProxy([owner], [], scope) as SchemaPath<S>);\n const selected = typeof value === 'object' && value !== null ? paths.get(value) : undefined;\n if (!selected || selected.owner !== scope)\n throw new TypeError('Selector must return a path from its callback.');\n const collection = selected.nodes.every(node => collectionEntryNode(node) !== undefined);\n if (kind === 'collection' && !collection)\n throw new TypeError('Collection selectors require a map, table or list path.');\n const resolvedKind = kind === 'auto' ? (collection ? 'collection' : 'value') : kind;\n const result = Object.freeze({\n kind: resolvedKind,\n schema: owner,\n address: Object.freeze([...selected.address]),\n }) as CollectionSelector | ValueSelector;\n return result;\n};\n","import type { CollectionImpact } from '../impact';\nimport type { Unsubscribe } from '../runtime/contract';\n\n/** Scheduler-owned metadata for one Runtime batch. */\nexport type BatchContext = {\n readonly id: number;\n readonly cause?: unknown;\n};\n\n/** The one processor-facing collection transition protocol. */\nexport type CollectionChange<K extends string, V> =\n | { readonly kind: 'reset' }\n | {\n readonly kind: 'incremental';\n readonly added: readonly { readonly key: K; readonly after: V }[];\n readonly updated: readonly {\n readonly key: K;\n readonly before: V;\n readonly after: V;\n }[];\n readonly removed: readonly { readonly key: K; readonly before: V }[];\n readonly order?: {\n readonly before: readonly K[];\n readonly after: readonly K[];\n };\n };\n\nexport type ValueContext<T> = {\n readonly kind: 'value';\n readonly value: T;\n readonly revision: number;\n readonly reset: boolean;\n readonly cause?: unknown;\n};\n\nexport type CollectionRead<K extends string, V> = {\n get(key: K): V | undefined;\n has(key: K): boolean;\n ids(): readonly K[];\n};\n\nexport type ExternalCollectionRead<K extends string, V> = {\n readonly get: (key: K) => V | undefined;\n readonly has: (key: K) => boolean;\n readonly ids: () => readonly K[];\n};\n\nexport type CollectionContext<K extends string, V> = {\n readonly kind: 'collection';\n readonly read: CollectionRead<K, V>;\n readonly change: CollectionChange<K, V> | undefined;\n readonly revision: number;\n readonly reset: boolean;\n readonly cause?: unknown;\n};\n\nexport type SourceContext = ValueContext<unknown> | CollectionContext<string, unknown>;\n\nexport type ExternalValueSource<T> = {\n readonly kind: 'value';\n current(): T;\n revision(): number;\n subscribe(listener: (event: ExternalValueEvent<T>) => void): Unsubscribe;\n};\n\nexport type ExternalCollectionSource<K extends string, V> = {\n readonly kind: 'collection';\n current(): ExternalCollectionRead<K, V>;\n revision(): number;\n subscribe(listener: (event: ExternalCollectionEvent<K, V>) => void): Unsubscribe;\n};\n\nexport type ExternalValueEvent<T> = {\n readonly value: T;\n readonly revision: number;\n readonly reset?: boolean;\n readonly cause?: unknown;\n};\n\nexport type ExternalCollectionEvent<K extends string, V> = {\n /** Stable read from the source before this event or external batch. */\n readonly previous: ExternalCollectionRead<K, V>;\n readonly revision: number;\n /** Optional document-style hint; the adapter resolves the canonical change. */\n readonly impact?: CollectionImpact<K>;\n readonly cause?: unknown;\n};\n\nexport type CollectionDraft<K extends string, V> = {\n set(key: K, value: V): void;\n remove(key: K): void;\n order(ids: readonly K[]): void;\n};\n\nexport class ProjectionError extends Error {\n constructor(\n readonly phase: 'processor' | 'listener' | 'source' | 'blocked',\n readonly identity: string,\n readonly revisions: readonly number[],\n cause: unknown\n ) {\n super(`Projection ${phase} failed: ${identity}`, { cause });\n this.name = 'ProjectionError';\n }\n}\n\nexport class ProjectionDisposedError extends Error {\n constructor() {\n super('Projection has been disposed.');\n this.name = 'ProjectionDisposedError';\n }\n}\n","import { profile } from '../profile';\nimport type { ObserverError, Unsubscribe } from '../runtime/contract';\nimport type { BatchContext, CollectionChange, SourceContext } from './contract';\nimport { ProjectionDisposedError, ProjectionError } from './contract';\n\ntype BatchOptions = { readonly cause?: unknown };\n\ntype ProducerBase = {\n readonly name: string;\n readonly outputs: readonly OutputRecord[];\n fault: ProjectionError | undefined;\n disposed: boolean;\n clear(): void;\n release(): void;\n};\n\nexport type OutputRecord = {\n readonly kind: 'value' | 'collection';\n readonly owner: ProducerRecord;\n readonly consumers: Set<ProcessorRecord>;\n context(active: () => boolean): SourceContext;\n current(): unknown;\n revision(): number;\n reset(): boolean;\n subscribe(listener: (change?: CollectionChange<string, unknown>) => void): Unsubscribe;\n emit(call: (listener: () => void) => void): void;\n clear(): void;\n release(): void;\n};\n\nexport type SourceBoundaryRecord = ProducerBase & {\n readonly kind: 'source';\n readonly outputs: readonly [OutputRecord];\n pendingCause(): unknown;\n recovering(): boolean;\n prepare(cause: unknown): { readonly changed: boolean; readonly force: boolean };\n publish(): void;\n};\n\nexport type ProcessorRecord = ProducerBase & {\n readonly kind: 'processor';\n readonly dependencies: readonly OutputRecord[];\n readonly order: number;\n evaluate(reset: boolean, cause: unknown): readonly OutputRecord[];\n publish(): void;\n};\n\nexport type ProducerRecord = SourceBoundaryRecord | ProcessorRecord;\n\nexport const createScheduler = (onError: (error: ProjectionError) => void) => {\n let disposed = false;\n let depth = 0;\n let batchSequence = 0;\n let activeBatch: BatchContext | undefined;\n let phase: 'idle' | 'compute' | 'notify' = 'idle';\n let sequence = 0;\n const sources = new Set<SourceBoundaryRecord>();\n const processors = new Set<ProcessorRecord>();\n const pendingSources = new Set<SourceBoundaryRecord>();\n const heap: ProcessorRecord[] = [];\n const queued = new Set<ProcessorRecord>();\n const completed = new Set<ProcessorRecord>();\n const emissions = new Set<OutputRecord>();\n const errors: ProjectionError[] = [];\n let reportingFailures: unknown[] = [];\n const guards = new Set<(locked: boolean) => void>();\n const cleanups = new Set<() => void>();\n\n const assertActive = () => {\n if (disposed) throw new ProjectionDisposedError();\n };\n const assertIdle = () => {\n assertActive();\n if (phase !== 'idle')\n throw new Error('Projection cannot be re-entered during processing or notification.');\n };\n const lock = (value: boolean) => guards.forEach(guard => guard(value));\n\n const enqueue = (processor: ProcessorRecord) => {\n if (processor.disposed || queued.has(processor)) return;\n queued.add(processor);\n profile.projection('scheduledNodes');\n let index = heap.length;\n heap.push(processor);\n while (index > 0) {\n const parent = (index - 1) >> 1;\n if (heap[parent].order < processor.order) break;\n heap[index] = heap[parent];\n index = parent;\n }\n heap[index] = processor;\n };\n\n const pop = (): ProcessorRecord => {\n const first = heap[0];\n const last = heap.pop()!;\n if (heap.length) {\n let index = 0;\n while (index * 2 + 1 < heap.length) {\n let child = index * 2 + 1;\n if (child + 1 < heap.length && heap[child + 1].order < heap[child].order) child++;\n if (last.order < heap[child].order) break;\n heap[index] = heap[child];\n index = child;\n }\n heap[index] = last;\n }\n return first;\n };\n\n const revisionsOf = (producer: ProducerRecord): readonly number[] =>\n producer.kind === 'processor'\n ? producer.dependencies.map(output => output.revision())\n : producer.outputs.map(output => output.revision());\n\n const errorFor = (\n producer: ProducerRecord,\n cause: unknown,\n kind: ProjectionError['phase'] = producer.kind === 'source' ? 'source' : 'processor'\n ) => new ProjectionError(kind, producer.name, revisionsOf(producer), cause);\n\n const capture = (source: SourceBoundaryRecord) => {\n if (disposed) return;\n if (phase !== 'idle') {\n source.fault = errorFor(\n source,\n new Error('Source changed while projection was running.'),\n 'source'\n );\n errors.push(source.fault);\n throw source.fault;\n }\n pendingSources.add(source);\n profile.projection('sourceEvents');\n if (source.fault) errors.push(source.fault);\n };\n\n const settleCause = (): unknown => {\n if (activeBatch?.cause !== undefined) return activeBatch.cause;\n for (const source of pendingSources) {\n const cause = source.pendingCause();\n if (cause !== undefined) return cause;\n }\n return undefined;\n };\n\n const settle = () => {\n if (disposed || depth || phase !== 'idle') return;\n phase = 'compute';\n lock(true);\n const cause = settleCause();\n try {\n for (const source of pendingSources) {\n if (source.disposed) continue;\n const wasFaulted = source.fault !== undefined;\n let changed = false;\n let force = false;\n if (!source.fault || source.recovering()) {\n try {\n const prepared = source.prepare(cause);\n changed = prepared.changed;\n force = prepared.force;\n source.fault = undefined;\n } catch (failure) {\n source.fault = errorFor(source, failure, 'source');\n errors.push(source.fault);\n }\n }\n const recovered = wasFaulted && !source.fault;\n if (changed) source.publish();\n if (source.fault || changed || force || recovered) {\n const output = source.outputs[0];\n emissions.add(output);\n output.consumers.forEach(enqueue);\n }\n }\n\n while (heap.length) {\n const processor = pop();\n if (processor.disposed) continue;\n const wasFaulted = processor.fault !== undefined;\n profile.projection('processedNodes');\n let changedOutputs: readonly OutputRecord[] = Object.freeze([]);\n const blocked = processor.dependencies.find(\n output => output.owner.fault || output.owner.disposed\n );\n if (blocked) {\n processor.fault = errorFor(\n processor,\n blocked.owner.fault ?? new ProjectionDisposedError(),\n 'blocked'\n );\n } else {\n const reset = wasFaulted || processor.dependencies.some(output => output.reset());\n try {\n changedOutputs = processor.evaluate(reset, cause);\n const dependencyFailure = processor.dependencies.find(output => output.owner.fault)\n ?.owner.fault;\n if (dependencyFailure) throw dependencyFailure;\n processor.fault = undefined;\n } catch (failure) {\n const error = errorFor(processor, failure);\n processor.fault = error;\n if (!reset) {\n try {\n changedOutputs = processor.evaluate(true, cause);\n const dependencyFailure = processor.dependencies.find(output => output.owner.fault)\n ?.owner.fault;\n if (dependencyFailure) throw dependencyFailure;\n processor.fault = undefined;\n errors.push(error);\n } catch (rebuildFailure) {\n processor.fault = errorFor(processor, rebuildFailure);\n errors.push(processor.fault);\n }\n } else errors.push(error);\n }\n }\n completed.add(processor);\n const recovered = wasFaulted && !processor.fault;\n if (processor.fault) {\n processor.outputs.forEach(output => {\n emissions.add(output);\n output.consumers.forEach(enqueue);\n });\n } else {\n if (changedOutputs.length) {\n processor.publish();\n changedOutputs.forEach(output => emissions.add(output));\n }\n const propagated = recovered ? processor.outputs : changedOutputs;\n propagated.forEach(output => output.consumers.forEach(enqueue));\n }\n if (processor.fault || changedOutputs.length) {\n profile.projection('publishedNodes');\n }\n }\n } finally {\n lock(false);\n phase = 'idle';\n }\n };\n\n const flush = (): readonly ObserverError[] => {\n if (disposed || depth) return [];\n if (pendingSources.size || completed.size) profile.projection('flushes');\n phase = 'notify';\n lock(true);\n const reportFailures: unknown[] = [];\n try {\n emissions.forEach(output =>\n output.emit(listener => {\n try {\n listener();\n } catch (cause) {\n errors.push(errorFor(output.owner, cause, 'listener'));\n }\n })\n );\n for (const error of errors.slice()) {\n try {\n onError(error);\n } catch (cause) {\n reportFailures.push(cause);\n }\n }\n return Object.freeze([\n ...errors.map(error =>\n Object.freeze({\n phase: error.phase === 'listener' ? ('listener' as const) : ('processor' as const),\n error,\n })\n ),\n ...reportFailures.map(error => Object.freeze({ phase: 'listener' as const, error })),\n ]);\n } finally {\n pendingSources.forEach(source => source.clear());\n completed.forEach(processor => processor.clear());\n pendingSources.clear();\n queued.clear();\n completed.clear();\n emissions.clear();\n errors.length = 0;\n reportingFailures = reportFailures;\n lock(false);\n phase = 'idle';\n }\n };\n\n const run = () => {\n settle();\n const result = flush();\n const failures = reportingFailures;\n reportingFailures = [];\n if (failures.length) throw new AggregateError(failures, 'Projection error reporter failed.');\n return result;\n };\n\n const batch = <T>(optionsOrCallback: BatchOptions | (() => T), maybeCallback?: () => T): T => {\n assertIdle();\n const options = typeof optionsOrCallback === 'function' ? undefined : optionsOrCallback;\n const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : maybeCallback;\n if (!callback) throw new TypeError('Projection batch requires a callback.');\n const outer = depth === 0;\n if (outer)\n activeBatch = Object.freeze({\n id: ++batchSequence,\n ...(options?.cause === undefined ? {} : { cause: options.cause }),\n });\n depth++;\n let failed = false;\n try {\n const value = callback();\n assertSynchronous(value);\n return value;\n } catch (error) {\n failed = true;\n throw error;\n } finally {\n depth--;\n if (!depth) {\n try {\n if (failed) {\n try {\n run();\n } catch {\n /* The original application error retains priority. */\n }\n } else run();\n } finally {\n activeBatch = undefined;\n }\n }\n }\n };\n\n const releaseProducer = (producer: ProducerRecord) => {\n assertIdle();\n if (producer.outputs.some(output => output.consumers.size))\n throw new Error('Projection producer is still used by another processor.');\n producer.disposed = true;\n if (producer.kind === 'processor') {\n producer.dependencies.forEach(output => output.consumers.delete(producer));\n processors.delete(producer);\n queued.delete(producer);\n completed.delete(producer);\n } else {\n sources.delete(producer);\n pendingSources.delete(producer);\n }\n producer.release();\n producer.clear();\n producer.outputs.forEach(output => emissions.delete(output));\n };\n\n return {\n assertActive,\n assertIdle,\n capture,\n settle,\n flush,\n run,\n guards,\n cleanups,\n get active() {\n return !disposed;\n },\n addSource(source: SourceBoundaryRecord) {\n assertIdle();\n sources.add(source);\n },\n addProcessor(processor: ProcessorRecord) {\n assertIdle();\n processors.add(processor);\n processor.dependencies.forEach(output => output.consumers.add(processor));\n },\n releaseProducer,\n order: () => sequence++,\n initialize<T>(callback: () => T): T {\n assertIdle();\n phase = 'compute';\n lock(true);\n try {\n return callback();\n } finally {\n lock(false);\n phase = 'idle';\n }\n },\n batch,\n batchContext: () => activeBatch,\n dispose() {\n if (disposed) return;\n assertIdle();\n disposed = true;\n const failures: unknown[] = [];\n cleanups.forEach(cleanup => {\n try {\n cleanup();\n } catch (error) {\n failures.push(error);\n }\n });\n cleanups.clear();\n processors.forEach(processor => {\n processor.disposed = true;\n try {\n processor.release();\n } catch (error) {\n failures.push(error);\n }\n });\n sources.forEach(source => {\n source.disposed = true;\n try {\n source.release();\n } catch (error) {\n failures.push(error);\n }\n });\n processors.clear();\n sources.clear();\n pendingSources.clear();\n heap.length = 0;\n queued.clear();\n completed.clear();\n emissions.clear();\n guards.clear();\n errors.length = 0;\n reportingFailures = [];\n if (failures.length) throw new AggregateError(failures, 'Projection cleanup failed.');\n },\n };\n};\n\nexport type Scheduler = ReturnType<typeof createScheduler>;\n\nexport const assertSynchronous = (value: unknown): void => {\n if (\n value != null &&\n (typeof value === 'object' || typeof value === 'function') &&\n 'then' in value &&\n typeof value.then === 'function'\n )\n throw new TypeError('Projection callbacks must be synchronous.');\n};\n\nexport const assertScope = (active: () => boolean) => {\n if (!active()) throw new Error('Projection reader or writer is no longer active.');\n};\n","import { profile } from '../profile';\nimport type {\n CollectionChange,\n CollectionContext,\n CollectionDraft,\n CollectionRead,\n} from './contract';\nimport { assertScope } from './scheduler';\n\ntype Entry<V> = { readonly present: true; readonly value: V } | { readonly present: false };\n\ntype TreeNode<K extends string, V> = {\n readonly key: K;\n readonly value: V;\n readonly height: number;\n readonly left?: TreeNode<K, V>;\n readonly right?: TreeNode<K, V>;\n};\n\nconst height = <K extends string, V>(node: TreeNode<K, V> | undefined): number => node?.height ?? 0;\n\nconst makeTreeNode = <K extends string, V>(\n key: K,\n value: V,\n left?: TreeNode<K, V>,\n right?: TreeNode<K, V>\n): TreeNode<K, V> =>\n Object.freeze({\n key,\n value,\n left,\n right,\n height: Math.max(height(left), height(right)) + 1,\n });\n\nconst rotateLeft = <K extends string, V>(node: TreeNode<K, V>): TreeNode<K, V> => {\n const right = node.right!;\n return makeTreeNode(\n right.key,\n right.value,\n makeTreeNode(node.key, node.value, node.left, right.left),\n right.right\n );\n};\n\nconst rotateRight = <K extends string, V>(node: TreeNode<K, V>): TreeNode<K, V> => {\n const left = node.left!;\n return makeTreeNode(\n left.key,\n left.value,\n left.left,\n makeTreeNode(node.key, node.value, left.right, node.right)\n );\n};\n\nconst rebalance = <K extends string, V>(node: TreeNode<K, V>): TreeNode<K, V> => {\n const balance = height(node.left) - height(node.right);\n if (balance > 1) {\n if (height(node.left!.left) < height(node.left!.right))\n return rotateRight(makeTreeNode(node.key, node.value, rotateLeft(node.left!), node.right));\n return rotateRight(node);\n }\n if (balance < -1) {\n if (height(node.right!.right) < height(node.right!.left))\n return rotateLeft(makeTreeNode(node.key, node.value, node.left, rotateRight(node.right!)));\n return rotateLeft(node);\n }\n return node;\n};\n\nconst treeSet = <K extends string, V>(\n node: TreeNode<K, V> | undefined,\n key: K,\n value: V\n): TreeNode<K, V> => {\n if (!node) return makeTreeNode(key, value);\n if (key === node.key) return makeTreeNode(key, value, node.left, node.right);\n if (key < node.key)\n return rebalance(\n makeTreeNode(node.key, node.value, treeSet(node.left, key, value), node.right)\n );\n return rebalance(makeTreeNode(node.key, node.value, node.left, treeSet(node.right, key, value)));\n};\n\nconst treeMin = <K extends string, V>(node: TreeNode<K, V>): TreeNode<K, V> =>\n node.left ? treeMin(node.left) : node;\n\nconst treeRemove = <K extends string, V>(\n node: TreeNode<K, V> | undefined,\n key: K\n): TreeNode<K, V> | undefined => {\n if (!node) return undefined;\n if (key < node.key)\n return rebalance(makeTreeNode(node.key, node.value, treeRemove(node.left, key), node.right));\n if (key > node.key)\n return rebalance(makeTreeNode(node.key, node.value, node.left, treeRemove(node.right, key)));\n if (!node.left) return node.right;\n if (!node.right) return node.left;\n const next = treeMin(node.right);\n return rebalance(makeTreeNode(next.key, next.value, node.left, treeRemove(node.right, next.key)));\n};\n\nconst treeGet = <K extends string, V>(node: TreeNode<K, V> | undefined, key: K): V | undefined => {\n let current = node;\n while (current) {\n if (key === current.key) return current.value;\n current = key < current.key ? current.left : current.right;\n }\n return undefined;\n};\n\nconst treeHas = <K extends string, V>(node: TreeNode<K, V> | undefined, key: K): boolean => {\n let current = node;\n while (current) {\n if (key === current.key) return true;\n current = key < current.key ? current.left : current.right;\n }\n return false;\n};\n\nconst treeFromSorted = <K extends string, V>(\n entries: readonly (readonly [K, V])[],\n start = 0,\n end = entries.length\n): TreeNode<K, V> | undefined => {\n if (start >= end) return undefined;\n const middle = (start + end) >> 1;\n const [key, value] = entries[middle];\n return makeTreeNode(\n key,\n value,\n treeFromSorted(entries, start, middle),\n treeFromSorted(entries, middle + 1, end)\n );\n};\n\nexport type CollectionOutputEvaluation<K extends string, V> = {\n readonly previous: CollectionRead<K, V>;\n readonly next: CollectionRead<K, V>;\n readonly output: CollectionDraft<K, V>;\n};\n\nexport type CollectionOutputState<K extends string, V> = {\n begin(active: () => boolean, initialize: boolean): CollectionOutputEvaluation<K, V>;\n seal(reset: boolean, isEqual: (previous: V, next: V) => boolean): boolean;\n context(active: () => boolean, cause: unknown): CollectionContext<K, V>;\n current(check: () => void): CollectionRead<K, V>;\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: (change: CollectionChange<K, V>) => void): void;\n unsubscribe(listener: (change: CollectionChange<K, V>) => void): void;\n};\n\n/** Owns staged keyed intent, exact transitions and the persistent published lookup. */\nexport const createCollectionOutput = <K extends string, V>(): CollectionOutputState<K, V> => {\n const values = new Map<K, V>();\n let ids: readonly K[] = Object.freeze([]);\n let staged = new Map<K, Entry<V>>();\n let nextIds = ids;\n let change: CollectionChange<K, V> | undefined;\n let initialized = false;\n let reset = false;\n let revision = 0;\n let publishedRoot: TreeNode<K, V> | undefined;\n let explicitOrder: readonly K[] | undefined;\n let cleared = false;\n const listeners = new Set<(change: CollectionChange<K, V>) => void>();\n\n const hasNext = (key: K): boolean =>\n staged.has(key) ? staged.get(key)!.present : !cleared && values.has(key);\n const getNext = (key: K): V | undefined => {\n const entry = staged.get(key);\n return entry\n ? entry.present\n ? entry.value\n : undefined\n : cleared\n ? undefined\n : values.get(key);\n };\n const deriveIds = (): readonly K[] => {\n const result = cleared ? [] : ids.filter(hasNext);\n for (const [key, entry] of staged)\n if (entry.present && (cleared || !values.has(key))) result.push(key);\n return result;\n };\n\n const begin = (active: () => boolean, initialize: boolean): CollectionOutputEvaluation<K, V> => {\n staged = new Map();\n nextIds = ids;\n change = undefined;\n explicitOrder = undefined;\n cleared = initialize;\n reset = initialize;\n const read = (next: boolean): CollectionRead<K, V> => ({\n get: key => {\n assertScope(active);\n return next ? getNext(key) : values.get(key);\n },\n has: key => {\n assertScope(active);\n return next ? hasNext(key) : values.has(key);\n },\n ids: () => {\n assertScope(active);\n return next ? Object.freeze(explicitOrder ? [...explicitOrder] : [...deriveIds()]) : ids;\n },\n });\n const output: CollectionDraft<K, V> = {\n set: (key, value) => {\n assertScope(active);\n if (typeof key !== 'string') throw new TypeError('Projection keys must be strings.');\n staged.set(key, { present: true, value });\n },\n remove: key => {\n assertScope(active);\n staged.set(key, { present: false });\n },\n order: order => {\n assertScope(active);\n explicitOrder = Object.freeze([...order]);\n },\n };\n return { previous: read(false), next: read(true), output };\n };\n\n const seal = (nextReset: boolean, isEqual: (previous: V, next: V) => boolean): boolean => {\n if (cleared)\n for (const key of values.keys()) if (!staged.has(key)) staged.set(key, { present: false });\n\n profile.projection('touchedKeys', staged.size);\n const added = new Set<K>();\n const removed = new Set<K>();\n const updated = new Set<K>();\n for (const [key, entry] of staged) {\n const existed = values.has(key);\n if (entry.present) {\n if (!existed) added.add(key);\n else if (!isEqual(values.get(key) as V, entry.value)) updated.add(key);\n else if (!nextReset) staged.delete(key);\n } else if (existed) removed.add(key);\n else staged.delete(key);\n }\n\n if (explicitOrder || added.size || removed.size) {\n const order = explicitOrder ?? [...ids.filter(key => !removed.has(key)), ...added];\n const seen = new Set(order);\n if (\n seen.size !== order.length ||\n order.length !== values.size + added.size - removed.size ||\n order.some(key => !hasNext(key))\n )\n throw new TypeError('Projection order must contain every key exactly once.');\n nextIds =\n ids.length === order.length && ids.every((key, index) => key === order[index])\n ? ids\n : Object.freeze([...order]);\n } else nextIds = ids;\n\n const changedKeys = new Set<K>([...added, ...removed, ...updated]);\n profile.projection('changedKeys', changedKeys.size);\n const addedEntries: { readonly key: K; readonly after: V }[] = [];\n const updatedEntries: {\n readonly key: K;\n readonly before: V;\n readonly after: V;\n }[] = [];\n const removedEntries: { readonly key: K; readonly before: V }[] = [];\n for (const key of changedKeys) {\n const beforePresent = values.has(key);\n const afterPresent = hasNext(key);\n if (beforePresent === afterPresent) {\n if (!beforePresent || isEqual(values.get(key) as V, getNext(key) as V)) continue;\n }\n if (!beforePresent) addedEntries.push({ key, after: getNext(key) as V });\n else if (!afterPresent) removedEntries.push({ key, before: values.get(key) as V });\n else\n updatedEntries.push({\n key,\n before: values.get(key) as V,\n after: getNext(key) as V,\n });\n }\n\n const orderChanged = nextIds !== ids;\n if (nextReset) change = Object.freeze({ kind: 'reset' as const });\n else if (\n addedEntries.length ||\n updatedEntries.length ||\n removedEntries.length ||\n orderChanged\n ) {\n let commonOrderChanged = false;\n if (orderChanged) {\n const before = ids.filter(key => !removed.has(key));\n const after = nextIds.filter(key => !added.has(key));\n commonOrderChanged = before.some((key, index) => after[index] !== key);\n }\n change = Object.freeze({\n kind: 'incremental' as const,\n added: Object.freeze(addedEntries),\n updated: Object.freeze(updatedEntries),\n removed: Object.freeze(removedEntries),\n ...(commonOrderChanged\n ? {\n order: Object.freeze({\n before: Object.freeze([...ids]),\n after: Object.freeze([...nextIds]),\n }),\n }\n : {}),\n });\n }\n reset = nextReset;\n return change !== undefined;\n };\n\n const context = (active: () => boolean, cause: unknown): CollectionContext<K, V> =>\n Object.freeze({\n kind: 'collection' as const,\n read: {\n get: key => {\n assertScope(active);\n return getNext(key);\n },\n has: key => {\n assertScope(active);\n return hasNext(key);\n },\n ids: () => {\n assertScope(active);\n return nextIds;\n },\n },\n change,\n revision,\n reset,\n cause,\n });\n\n const current = (check: () => void): CollectionRead<K, V> => {\n const root = publishedRoot;\n const publishedIds = ids;\n return Object.freeze({\n get: key => {\n check();\n return treeGet(root, key);\n },\n has: key => {\n check();\n return treeHas(root, key);\n },\n ids: () => {\n check();\n return publishedIds;\n },\n });\n };\n\n return {\n begin,\n seal,\n context,\n current,\n revision: () => revision,\n reset: () => reset,\n publish: () => {\n if (change) {\n if (change.kind === 'reset') {\n const entries: [K, V][] = [];\n for (const [key, entry] of staged) if (entry.present) entries.push([key, entry.value]);\n entries.sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0));\n publishedRoot = treeFromSorted(entries);\n } else {\n for (const [key, entry] of staged)\n publishedRoot = entry.present\n ? treeSet(publishedRoot, key, entry.value)\n : treeRemove(publishedRoot, key);\n }\n }\n for (const [key, entry] of staged) {\n if (entry.present) values.set(key, entry.value);\n else values.delete(key);\n }\n if (change && initialized) revision++;\n ids = nextIds;\n initialized = true;\n },\n emit: call => {\n const resetEvent = Object.freeze({ kind: 'reset' as const });\n Array.from(listeners).forEach(listener => call(() => listener(change ?? resetEvent)));\n },\n clear: () => {\n staged.clear();\n nextIds = ids;\n change = undefined;\n reset = false;\n explicitOrder = undefined;\n cleared = false;\n },\n release: () => {\n values.clear();\n staged.clear();\n publishedRoot = undefined;\n listeners.clear();\n ids = nextIds = Object.freeze([]);\n change = undefined;\n initialized = false;\n revision = 0;\n reset = false;\n explicitOrder = undefined;\n cleared = false;\n },\n subscribe: listener => listeners.add(listener),\n unsubscribe: listener => listeners.delete(listener),\n };\n};\n\nexport const mapRead = <K extends string, V>(value: ReadonlyMap<K, V>): CollectionRead<K, V> => ({\n get: key => value.get(key),\n has: key => value.has(key),\n ids: () => Object.freeze([...value.keys()]),\n});\n\n/** Immutable map-like view over a CollectionRead. */\nexport const collectionView = <K extends string, V>(\n read: CollectionRead<K, V>\n): ReadonlyMap<K, V> => {\n const ids = read.ids();\n const entries = function* (): IterableIterator<[K, V]> {\n for (const key of ids) yield [key, read.get(key) as V];\n };\n const values = function* (): IterableIterator<V> {\n for (const key of ids) yield read.get(key) as V;\n };\n const view: ReadonlyMap<K, V> = {\n get: key => read.get(key),\n has: key => read.has(key),\n get size() {\n return ids.length;\n },\n keys: () => ids[Symbol.iterator](),\n values,\n entries,\n forEach: (callback, thisArg) => {\n for (const key of ids) callback.call(thisArg, read.get(key) as V, key, view);\n },\n [Symbol.iterator]: entries,\n };\n return Object.freeze(view);\n};\n\n/** Eager durable view used when a processor result may retain its dependency value. */\nexport const snapshotCollectionView = <K extends string, V>(\n read: CollectionRead<K, V>\n): ReadonlyMap<K, V> => {\n const ids = read.ids();\n const values = new Map<K, V>();\n for (const key of ids) values.set(key, read.get(key) as V);\n return collectionView(mapRead(values));\n};\n\nexport type CollectionStageOptions<K extends string, V> = {\n readonly reset: boolean;\n readonly candidates?: Iterable<K>;\n readonly orderMayChange?: boolean;\n readonly isEqual?: (previous: V, next: V) => boolean;\n};\n\n/**\n * The one source-to-CollectionChange kernel. Candidate keys only narrow value work;\n * exact membership/value/order semantics remain owned here.\n */\nexport const stageCollectionRead = <K extends string, V>(\n state: CollectionOutputState<K, V>,\n read: CollectionRead<K, V>,\n active: () => boolean,\n options: CollectionStageOptions<K, V>\n): boolean => {\n const evaluation = state.begin(active, options.reset);\n if (options.reset) {\n const ids = read.ids();\n profile.collectionView.idsScanned(ids.length);\n for (const key of ids) {\n profile.collectionView.mapped();\n evaluation.output.set(key, read.get(key) as V);\n }\n evaluation.output.order(ids);\n } else {\n const previous = state.current(() => undefined);\n const keys = options.candidates\n ? [...new Set(options.candidates)]\n : [...new Set([...previous.ids(), ...read.ids()])];\n if (!options.candidates) profile.collectionView.idsScanned(keys.length);\n for (const key of keys) {\n if (read.has(key)) {\n profile.collectionView.mapped();\n evaluation.output.set(key, read.get(key) as V);\n } else evaluation.output.remove(key);\n }\n if (options.orderMayChange || !options.candidates) {\n const ids = read.ids();\n if (options.candidates) profile.collectionView.idsScanned(ids.length);\n evaluation.output.order(ids);\n }\n }\n return state.seal(options.reset, options.isEqual ?? Object.is);\n};\n\n/** Exact net transition between two published map-like snapshots. */\nexport const collectionChangeBetween = <K extends string, V>(\n previous: ReadonlyMap<K, V>,\n current: ReadonlyMap<K, V>,\n isEqual: (previous: V, next: V) => boolean = Object.is\n): CollectionChange<K, V> | undefined => {\n const added: { readonly key: K; readonly after: V }[] = [];\n const removed: { readonly key: K; readonly before: V }[] = [];\n const updated: { readonly key: K; readonly before: V; readonly after: V }[] = [];\n for (const [key, before] of previous) {\n if (!current.has(key)) removed.push({ key, before });\n else {\n const after = current.get(key) as V;\n if (!isEqual(before, after)) updated.push({ key, before, after });\n }\n }\n for (const [key, after] of current) if (!previous.has(key)) added.push({ key, after });\n const beforeKeys = new Set(previous.keys());\n const afterKeys = new Set(current.keys());\n const beforeCommon = [...previous.keys()].filter(key => afterKeys.has(key));\n const afterCommon = [...current.keys()].filter(key => beforeKeys.has(key));\n const orderChanged = beforeCommon.some((key, index) => afterCommon[index] !== key);\n if (!added.length && !removed.length && !updated.length && !orderChanged) return undefined;\n return Object.freeze({\n kind: 'incremental' as const,\n added: Object.freeze(added),\n updated: Object.freeze(updated),\n removed: Object.freeze(removed),\n ...(orderChanged\n ? {\n order: Object.freeze({\n before: Object.freeze([...previous.keys()]),\n after: Object.freeze([...current.keys()]),\n }),\n }\n : {}),\n });\n};\n","import { accessOf } from '../runtime/access';\nimport type { DocumentReadable, Synchronous } from '../runtime/contract';\nimport type {\n CollectionId,\n CollectionNode as SchemaCollectionNode,\n CollectionPath,\n CollectionSelector,\n Infer,\n ObjectNode,\n PathValueOf,\n ReadonlyValue,\n SchemaPath,\n ValueSelector,\n} from '../schema';\nimport { compilePath } from '../schema';\nimport { snapshotCollectionView } from './collection-output';\nimport type {\n CollectionChange,\n CollectionDraft,\n CollectionRead,\n ExternalCollectionSource,\n ExternalValueSource,\n SourceContext,\n} from './contract';\nimport type { Readable } from './readable';\nimport { assertSynchronous } from './scheduler';\n\ndeclare const projectionDefinition: unique symbol;\ndeclare const projectionChanges: unique symbol;\ndeclare const writableInput: unique symbol;\n\n/** A lazy output reference with no materialized Runtime state. */\nexport type Projection<T, C = undefined> = {\n readonly [projectionDefinition]: T;\n readonly [projectionChanges]: C;\n};\n\n/** A writable source projection. */\nexport type Input<T, C = undefined> = Projection<T, C> & { readonly [writableInput]: true };\n\ntype ProjectionValues<D extends readonly Projection<unknown, unknown>[]> = {\n readonly [K in keyof D]: D[K] extends Projection<infer T, unknown> ? T : never;\n};\n\nexport type Equality = (a: unknown, b: unknown) => boolean;\ntype PathSelector<S extends ObjectNode> = (path: SchemaPath<S['shape']>) => unknown;\n\nexport type OutputDefinition =\n | {\n readonly kind: 'value';\n readonly equality: Equality;\n readonly path?: readonly string[];\n }\n | {\n readonly kind: 'collection';\n readonly equality: Equality;\n readonly path?: readonly string[];\n };\n\nexport type ValueOutputEvaluation = {\n readonly kind: 'value';\n readonly previous: unknown;\n readonly next: () => unknown;\n readonly output: { set(value: unknown): void };\n};\n\nexport type CollectionOutputEvaluation = {\n readonly kind: 'collection';\n readonly previous: CollectionRead<string, unknown>;\n readonly next: CollectionRead<string, unknown>;\n readonly output: CollectionDraft<string, unknown>;\n};\n\nexport type OutputEvaluation = ValueOutputEvaluation | CollectionOutputEvaluation;\n\nexport type ProcessorEvaluation = {\n readonly reset: boolean;\n readonly cause: unknown;\n readonly sources: readonly SourceContext[];\n readonly outputs: readonly OutputEvaluation[];\n};\n\nexport type Rebuild = { readonly kind: 'rebuild' };\n\nexport type ProcessorInstance = {\n evaluate(input: ProcessorEvaluation): void | Rebuild;\n release?(): void;\n};\n\ntype SourceAdapter =\n | {\n readonly kind: 'value-input';\n readonly initial: unknown;\n readonly equality: Equality;\n }\n | {\n readonly kind: 'collection-input';\n readonly initial: ReadonlyMap<string, unknown>;\n }\n | {\n readonly kind: 'readable';\n readonly readable: Readable<unknown>;\n readonly equality: Equality;\n }\n | {\n readonly kind: 'external-value';\n readonly source: ExternalValueSource<unknown>;\n readonly equality: Equality;\n }\n | {\n readonly kind: 'external-collection';\n readonly source: ExternalCollectionSource<string, unknown>;\n }\n | {\n readonly kind: 'document-value';\n readonly document: DocumentReadable<ObjectNode>;\n readonly selector?: ValueSelector;\n }\n | {\n readonly kind: 'document-collection';\n readonly document: DocumentReadable<ObjectNode>;\n readonly selector: CollectionSelector;\n };\n\nexport type SourceDefinition = {\n readonly kind: 'source';\n readonly source: SourceAdapter;\n readonly output: OutputDefinition;\n owner?: object;\n};\n\nexport type ProcessorDefinition = {\n readonly kind: 'processor';\n readonly dependencies: readonly Projection<unknown, unknown>[];\n readonly outputs: readonly OutputDefinition[];\n readonly create: () => ProcessorInstance;\n readonly name?: string;\n owner?: object;\n};\n\nexport type ProducerDefinition = SourceDefinition | ProcessorDefinition;\n\nexport type ProjectionRef = {\n readonly producer: ProducerDefinition;\n readonly output: number;\n};\n\nconst projections = new WeakMap<object, ProjectionRef>();\n\nconst defineRef = <T, C = undefined>(\n producer: ProducerDefinition,\n output: number\n): Projection<T, C> => {\n const handle = Object.freeze({}) as Projection<T, C>;\n projections.set(handle, Object.freeze({ producer, output }));\n return handle;\n};\n\nexport const projectionRef = (projection: Projection<unknown, unknown>): ProjectionRef => {\n const ref = projections.get(projection);\n if (!ref) throw new TypeError('Unknown projection definition.');\n return ref;\n};\n\nexport const producerOf = (projection: Projection<unknown, unknown>): ProducerDefinition =>\n projectionRef(projection).producer;\n\nexport const isProjection = (value: unknown): value is Projection<unknown, unknown> =>\n value !== null && typeof value === 'object' && projections.has(value);\n\nexport const ownProjection = <P extends Projection<unknown, unknown>>(\n projection: P,\n owner: object\n): P => {\n const producer = producerOf(projection);\n if (producer.owner !== undefined && producer.owner !== owner)\n throw new TypeError('Projection producer already belongs to another scope.');\n if (producer.kind === 'processor') {\n for (const dependency of producer.dependencies) {\n const dependencyOwner = producerOf(dependency).owner;\n if (dependencyOwner !== undefined && dependencyOwner !== owner)\n throw new TypeError('A scope cannot depend on another scope.');\n }\n }\n producer.owner = owner;\n return projection;\n};\n\nconst freezeOutput = (output: OutputDefinition): OutputDefinition =>\n Object.freeze({\n kind: output.kind,\n equality: output.equality,\n ...(output.path ? { path: Object.freeze([...output.path]) } : {}),\n });\n\nexport const defineProcessor = (definition: {\n readonly dependencies: readonly Projection<unknown, unknown>[];\n readonly outputs: readonly OutputDefinition[];\n readonly create: () => ProcessorInstance;\n readonly name?: string;\n}): readonly Projection<unknown, unknown>[] => {\n if (!Array.isArray(definition.dependencies))\n throw new TypeError('Projection dependencies must be an array.');\n definition.dependencies.forEach(projectionRef);\n if (!definition.outputs.length) throw new TypeError('Projection processor requires an output.');\n const producer: ProcessorDefinition = {\n kind: 'processor',\n dependencies: Object.freeze([...definition.dependencies]),\n outputs: Object.freeze(definition.outputs.map(freezeOutput)),\n create: definition.create,\n ...(definition.name ? { name: definition.name } : {}),\n };\n return Object.freeze(\n producer.outputs.map((_, output) => defineRef<unknown, unknown>(producer, output))\n );\n};\n\nconst defineSource = <T, C = undefined>(\n source: SourceAdapter,\n output: OutputDefinition\n): Projection<T, C> => {\n const producer: SourceDefinition = {\n kind: 'source',\n source,\n output: freezeOutput(output),\n };\n return defineRef<T, C>(producer, 0);\n};\n\nconst sourceValue = (source: SourceContext): unknown =>\n source.kind === 'value' ? source.value : snapshotCollectionView(source.read);\n\nconst valueInput = <T>(\n initial: T,\n equality: (previous: T, next: T) => boolean = Object.is\n): Input<T> =>\n defineSource<T>(\n { kind: 'value-input', initial, equality: equality as Equality },\n { kind: 'value', equality: equality as Equality }\n ) as Input<T>;\n\nconst collectionInput = <K extends string, V>(\n initial: ReadonlyMap<K, V> = new Map<K, V>()\n): Input<ReadonlyMap<K, V>, CollectionChange<K, V>> => {\n const entries = new Map<string, unknown>();\n for (const [key, value] of initial) {\n if (typeof key !== 'string') throw new TypeError('Projection keys must be strings.');\n entries.set(key, value);\n }\n return defineSource<ReadonlyMap<K, V>, CollectionChange<K, V>>(\n { kind: 'collection-input', initial: entries },\n { kind: 'collection', equality: Object.is }\n ) as Input<ReadonlyMap<K, V>, CollectionChange<K, V>>;\n};\n\nexport const input = Object.assign(valueInput, { collection: collectionInput });\n\n/** Establish a lazy reactive boundary from a document, readable, or external source. */\nexport function observe<S extends ObjectNode>(document: DocumentReadable<S>): Projection<Infer<S>>;\nexport function observe<T>(source: ExternalValueSource<T>): Projection<T>;\nexport function observe<K extends string, V>(\n source: ExternalCollectionSource<K, V>\n): Projection<ReadonlyMap<K, V>, CollectionChange<K, V>>;\nexport function observe<T>(readable: Readable<T>): Projection<T>;\nexport function observe<S extends ObjectNode, P extends CollectionPath>(\n document: DocumentReadable<S>,\n selector: (path: SchemaPath<S['shape']>) => P\n): Projection<\n ReadonlyMap<CollectionId<P>, ReadonlyValue<Infer<SchemaCollectionNode<P>>>>,\n CollectionChange<CollectionId<P>, ReadonlyValue<Infer<SchemaCollectionNode<P>>>>\n>;\nexport function observe<S extends ObjectNode, P>(\n document: DocumentReadable<S>,\n selector: (path: SchemaPath<S['shape']>) => P\n): Projection<PathValueOf<P>>;\nexport function observe<S extends ObjectNode>(\n source:\n | DocumentReadable<S>\n | Readable<unknown>\n | ExternalValueSource<unknown>\n | ExternalCollectionSource<string, unknown>,\n selector?: PathSelector<S>\n): Projection<unknown, unknown> {\n if (isExternalSource(source))\n return source.kind === 'collection'\n ? defineSource(\n { kind: 'external-collection', source },\n { kind: 'collection', equality: Object.is }\n )\n : defineSource(\n { kind: 'external-value', source, equality: Object.is },\n { kind: 'value', equality: Object.is }\n );\n if ('current' in source && typeof source.current === 'function')\n return defineSource(\n { kind: 'readable', readable: source as Readable<unknown>, equality: Object.is },\n { kind: 'value', equality: Object.is }\n );\n\n const document = source as DocumentReadable<ObjectNode>;\n if (!selector)\n return defineSource(\n { kind: 'document-value', document },\n { kind: 'value', equality: Object.is }\n );\n const state = accessOf(document);\n const selected = compilePath(state.schema, 'auto', selector as never);\n return selected.kind === 'collection'\n ? defineSource(\n { kind: 'document-collection', document, selector: selected },\n { kind: 'collection', equality: Object.is }\n )\n : defineSource(\n { kind: 'document-value', document, selector: selected },\n { kind: 'value', equality: Object.is }\n );\n}\n\nconst isExternalSource = (\n source: unknown\n): source is ExternalValueSource<unknown> | ExternalCollectionSource<string, unknown> => {\n if (!source || typeof source !== 'object') return false;\n const candidate = source as {\n readonly kind?: unknown;\n readonly current?: unknown;\n readonly revision?: unknown;\n readonly subscribe?: unknown;\n };\n return (\n (candidate.kind === 'value' || candidate.kind === 'collection') &&\n typeof candidate.current === 'function' &&\n typeof candidate.revision === 'function' &&\n typeof candidate.subscribe === 'function'\n );\n};\n\nexport function derive<const D extends readonly Projection<unknown, unknown>[], T>(\n dependencies: D,\n compute: (...values: ProjectionValues<D>) => Synchronous<T>,\n equality: (previous: T, next: T) => boolean = Object.is\n): Projection<T> {\n const [projection] = defineProcessor({\n dependencies,\n outputs: [{ kind: 'value', equality: equality as Equality }],\n create: () => ({\n evaluate: evaluation => {\n const output = evaluation.outputs[0];\n if (output.kind !== 'value') throw new Error('derive requires a value output.');\n const next = compute(...(evaluation.sources.map(sourceValue) as ProjectionValues<D>));\n assertSynchronous(next);\n output.output.set(next);\n },\n }),\n });\n return projection as Projection<T>;\n}\n","import { collectionView } from './collection-output';\nimport type { CollectionChange, CollectionDraft, CollectionRead, SourceContext } from './contract';\nimport type {\n CollectionOutputEvaluation,\n OutputDefinition,\n OutputEvaluation,\n Projection,\n Rebuild,\n} from './definition';\nimport { defineProcessor, projectionRef } from './definition';\nimport { assertSynchronous } from './scheduler';\n\ntype ProjectionValues<D extends readonly Projection<unknown, unknown>[]> = {\n readonly [K in keyof D]: D[K] extends Projection<infer T, unknown> ? T : never;\n};\n\ntype ProjectionChanges<D extends readonly Projection<unknown, unknown>[]> = {\n readonly [K in keyof D]: D[K] extends Projection<unknown, infer C>\n ? [C] extends [undefined]\n ? undefined\n : C | undefined\n : undefined;\n};\n\nexport type IncrementalValueContext<D extends readonly Projection<unknown, unknown>[], T> = {\n readonly sources: ProjectionValues<D>;\n readonly changes: ProjectionChanges<D>;\n readonly previous: T | undefined;\n readonly reset: boolean;\n readonly cause: unknown;\n readonly state: Record<string, unknown>;\n};\n\nexport type IncrementalValueProcessor<D extends readonly Projection<unknown, unknown>[], T> = (\n context: IncrementalValueContext<D, T>\n) => T | Rebuild;\n\nexport type IncrementalCollectionContext<\n D extends readonly Projection<unknown, unknown>[],\n K extends string,\n V,\n> = {\n readonly sources: ProjectionValues<D>;\n readonly changes: ProjectionChanges<D>;\n readonly previous: CollectionRead<K, V>;\n readonly next: CollectionRead<K, V>;\n readonly reset: boolean;\n readonly cause: unknown;\n readonly state: Record<string, unknown>;\n readonly output: CollectionDraft<K, V>;\n};\n\nexport type IncrementalCollectionProcessor<\n D extends readonly Projection<unknown, unknown>[],\n K extends string,\n V,\n> = (context: IncrementalCollectionContext<D, K, V>) => void | Rebuild;\n\ndeclare const groupOutput: unique symbol;\n\ntype GroupCollectionOutput<K extends string, V> = {\n readonly [groupOutput]: { readonly kind: 'collection'; readonly key: K; readonly value: V };\n};\n\ntype GroupValueOutput<T> = {\n readonly [groupOutput]: { readonly kind: 'value'; readonly value: T };\n};\n\ntype GroupOutputShape = {\n readonly [name: string]:\n GroupCollectionOutput<string, unknown> | GroupValueOutput<unknown> | GroupOutputShape;\n};\n\nexport type IncrementalGroupOutputTree = GroupOutputShape;\n\ntype GroupOutputBuilder = {\n collection<K extends string, V>(\n equality?: (previous: V, next: V) => boolean\n ): GroupCollectionOutput<K, V>;\n value<T>(equality?: (previous: T, next: T) => boolean): GroupValueOutput<T>;\n};\n\nexport type IncrementalGroupDefine = GroupOutputBuilder;\n\nexport type GroupProjections<O> =\n O extends GroupCollectionOutput<infer K, infer V>\n ? Projection<ReadonlyMap<K, V>, CollectionChange<K, V>>\n : O extends GroupValueOutput<infer T>\n ? Projection<T>\n : { readonly [P in keyof O]: GroupProjections<O[P]> };\n\ntype GroupReads<O> =\n O extends GroupCollectionOutput<infer K, infer V>\n ? CollectionRead<K, V>\n : O extends GroupValueOutput<infer T>\n ? T | undefined\n : { readonly [P in keyof O]: GroupReads<O[P]> };\n\ntype GroupDrafts<O> =\n O extends GroupCollectionOutput<infer K, infer V>\n ? CollectionDraft<K, V>\n : O extends GroupValueOutput<infer T>\n ? { set(value: T): void }\n : { readonly [P in keyof O]: GroupDrafts<O[P]> };\n\nexport type IncrementalGroupContext<\n D extends readonly Projection<unknown, unknown>[],\n O extends GroupOutputShape,\n> = {\n readonly sources: ProjectionValues<D>;\n readonly changes: ProjectionChanges<D>;\n readonly previous: GroupReads<O>;\n readonly next: GroupReads<O>;\n readonly outputs: GroupDrafts<O>;\n readonly reset: boolean;\n readonly cause: unknown;\n readonly state: Record<string, unknown>;\n};\n\nexport type IncrementalGroupProcessor<\n D extends readonly Projection<unknown, unknown>[],\n O extends GroupOutputShape,\n> = (context: IncrementalGroupContext<D, O>) => void | Rebuild;\n\nconst resetCollectionChange = Object.freeze({ kind: 'reset' as const });\n\nconst isRebuild = (value: unknown): value is Rebuild =>\n value !== null &&\n typeof value === 'object' &&\n (value as { readonly kind?: unknown }).kind === 'rebuild';\n\nconst publicValue = (source: SourceContext): unknown =>\n source.kind === 'value' ? source.value : collectionView(source.read);\n\nconst publicInputs = (\n sources: readonly SourceContext[],\n reset: boolean\n): { readonly values: readonly unknown[]; readonly changes: readonly unknown[] } => ({\n values: Object.freeze(sources.map(publicValue)),\n changes: Object.freeze(\n sources.map(source =>\n source.kind === 'collection' ? (reset ? resetCollectionChange : source.change) : undefined\n )\n ),\n});\n\nconst validateDependencies = (dependencies: readonly Projection<unknown, unknown>[]) => {\n if (!Array.isArray(dependencies))\n throw new TypeError('Incremental dependencies must be projections.');\n dependencies.forEach(projectionRef);\n};\n\nfunction createIncrementalValue<const D extends readonly Projection<unknown, unknown>[], T>(\n dependencies: D,\n processor: IncrementalValueProcessor<D, T>\n): Projection<T> {\n validateDependencies(dependencies);\n const [projection] = defineProcessor({\n dependencies,\n outputs: [{ kind: 'value', equality: Object.is }],\n create: () => {\n const state: Record<string, unknown> = Object.create(null) as Record<string, unknown>;\n return {\n evaluate: evaluation => {\n const output = evaluation.outputs[0];\n if (output.kind !== 'value') throw new Error('Incremental value output is invalid.');\n const publicInput = publicInputs(evaluation.sources, evaluation.reset);\n const result = processor({\n sources: publicInput.values as ProjectionValues<D>,\n changes: publicInput.changes as ProjectionChanges<D>,\n previous: output.previous as T | undefined,\n reset: evaluation.reset,\n cause: evaluation.cause,\n state,\n });\n assertSynchronous(result);\n if (isRebuild(result)) return result;\n output.output.set(result as T);\n },\n };\n },\n });\n return projection as Projection<T>;\n}\n\nfunction createIncrementalCollection<\n const D extends readonly Projection<unknown, unknown>[],\n K extends string,\n V,\n>(\n dependencies: D,\n processor: IncrementalCollectionProcessor<D, K, V>\n): Projection<ReadonlyMap<K, V>, CollectionChange<K, V>> {\n validateDependencies(dependencies);\n const [projection] = defineProcessor({\n dependencies,\n outputs: [{ kind: 'collection', equality: Object.is }],\n create: () => {\n const state: Record<string, unknown> = Object.create(null) as Record<string, unknown>;\n return {\n evaluate: evaluation => {\n const output = evaluation.outputs[0];\n if (output.kind !== 'collection')\n throw new Error('Incremental collection output is invalid.');\n const publicInput = publicInputs(evaluation.sources, evaluation.reset);\n const result = processor({\n sources: publicInput.values as ProjectionValues<D>,\n changes: publicInput.changes as ProjectionChanges<D>,\n previous: output.previous as CollectionRead<K, V>,\n next: output.next as CollectionRead<K, V>,\n reset: evaluation.reset,\n cause: evaluation.cause,\n state,\n output: output.output as CollectionDraft<K, V>,\n });\n assertSynchronous(result);\n return isRebuild(result) ? result : undefined;\n },\n };\n },\n });\n return projection as Projection<ReadonlyMap<K, V>, CollectionChange<K, V>>;\n}\n\ntype GroupShape = number | { readonly [key: string]: GroupShape };\nconst groupOutputMetadata = new WeakMap<\n object,\n {\n readonly kind: OutputDefinition['kind'];\n readonly equality: (a: unknown, b: unknown) => boolean;\n }\n>();\n\nconst isPlainGroupNamespace = (value: unknown): value is Record<string, unknown> =>\n value !== null &&\n typeof value === 'object' &&\n !groupOutputMetadata.has(value) &&\n !Array.isArray(value) &&\n (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);\n\nconst compileGroupShape = (\n value: unknown,\n path: readonly string[],\n declaredOutputs: ReadonlySet<object>,\n used: Set<object>,\n outputs: OutputDefinition[]\n): GroupShape => {\n if (value !== null && typeof value === 'object') {\n const metadata = groupOutputMetadata.get(value);\n if (metadata) {\n if (!declaredOutputs.has(value))\n throw new TypeError('Incremental group outputs must be declared by this group.');\n if (used.has(value)) throw new TypeError('An incremental group output cannot be reused.');\n used.add(value);\n const index = outputs.length;\n outputs.push({\n kind: metadata.kind,\n equality: metadata.equality,\n path: Object.freeze([...path]),\n });\n return index;\n }\n }\n if (!isPlainGroupNamespace(value))\n throw new TypeError('Incremental group outputs must be a static object tree.');\n for (const key of Reflect.ownKeys(value)) {\n if (typeof key !== 'string')\n throw new TypeError('Incremental group output names must be strings.');\n if (!Object.prototype.propertyIsEnumerable.call(value, key))\n throw new TypeError('Incremental group namespaces must contain enumerable properties.');\n }\n const keys = Object.keys(value);\n if (!keys.length) throw new TypeError('Incremental group namespaces cannot be empty.');\n const result: Record<string, GroupShape> = Object.create(null) as Record<string, GroupShape>;\n for (const key of keys) {\n if (key === '__proto__' || key === 'prototype' || key === 'constructor')\n throw new TypeError(`Invalid incremental group output name: ${key}`);\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (!descriptor || !('value' in descriptor))\n throw new TypeError('Incremental group namespaces cannot contain accessors.');\n result[key] = compileGroupShape(\n descriptor.value,\n [...path, key],\n declaredOutputs,\n used,\n outputs\n );\n }\n return Object.freeze(result);\n};\n\nconst hydrateGroupShape = <T>(shape: GroupShape, values: readonly T[]): unknown => {\n if (typeof shape === 'number') return values[shape];\n const result: Record<string, unknown> = {};\n for (const [key, child] of Object.entries(shape)) result[key] = hydrateGroupShape(child, values);\n return Object.freeze(result);\n};\n\nconst previousOf = (output: OutputEvaluation): unknown => output.previous;\n\nconst hydrateGroupReads = (\n shape: GroupShape,\n outputs: readonly OutputEvaluation[],\n next: boolean\n): unknown => {\n if (typeof shape === 'number') {\n const output = outputs[shape];\n return next && output.kind === 'value' ? output.next() : next ? output.next : output.previous;\n }\n const result: Record<string, unknown> = {};\n for (const [key, child] of Object.entries(shape)) {\n if (typeof child === 'number' && next && outputs[child].kind === 'value') {\n Object.defineProperty(result, key, {\n enumerable: true,\n configurable: false,\n get: () => (outputs[child] as Extract<OutputEvaluation, { kind: 'value' }>).next(),\n });\n } else result[key] = hydrateGroupReads(child, outputs, next);\n }\n return Object.freeze(result);\n};\n\nfunction createIncrementalGroup<\n const D extends readonly Projection<unknown, unknown>[],\n const O extends GroupOutputShape,\n>(\n dependencies: D,\n defineOutputs: (define: GroupOutputBuilder) => O,\n processor: IncrementalGroupProcessor<D, O>\n): GroupProjections<O> {\n validateDependencies(dependencies);\n if (typeof defineOutputs !== 'function')\n throw new TypeError('Incremental group outputs must be declared by a callback.');\n if (typeof processor !== 'function')\n throw new TypeError('Incremental group processor must be a function.');\n\n let active = true;\n const declaredOutputs = new Set<object>();\n const defineOutput: GroupOutputBuilder = {\n collection: <K extends string, V>(equality: (previous: V, next: V) => boolean = Object.is) => {\n if (!active) throw new TypeError('Incremental group output declarations are synchronous.');\n const descriptor = Object.freeze({});\n groupOutputMetadata.set(descriptor, {\n kind: 'collection',\n equality: equality as (a: unknown, b: unknown) => boolean,\n });\n declaredOutputs.add(descriptor);\n return descriptor as GroupCollectionOutput<K, V>;\n },\n value: <T>(equality: (previous: T, next: T) => boolean = Object.is) => {\n if (!active) throw new TypeError('Incremental group output declarations are synchronous.');\n const descriptor = Object.freeze({});\n groupOutputMetadata.set(descriptor, {\n kind: 'value',\n equality: equality as (a: unknown, b: unknown) => boolean,\n });\n declaredOutputs.add(descriptor);\n return descriptor as GroupValueOutput<T>;\n },\n };\n const declared = defineOutputs(defineOutput);\n assertSynchronous(declared);\n active = false;\n const outputs: OutputDefinition[] = [];\n const used = new Set<object>();\n const shape = compileGroupShape(declared, [], declaredOutputs, used, outputs);\n if (typeof shape === 'number')\n throw new TypeError('Incremental group declarations must return an output namespace.');\n if (used.size === 0 || used.size !== declaredOutputs.size)\n throw new TypeError('Every incremental group output must be returned by the declaration.');\n\n const projections = defineProcessor({\n dependencies,\n outputs,\n create: () => {\n const state: Record<string, unknown> = Object.create(null) as Record<string, unknown>;\n return {\n evaluate: evaluation => {\n const publicInput = publicInputs(evaluation.sources, evaluation.reset);\n const result = processor({\n sources: publicInput.values as ProjectionValues<D>,\n changes: publicInput.changes as ProjectionChanges<D>,\n previous: hydrateGroupReads(shape, evaluation.outputs, false) as GroupReads<O>,\n next: hydrateGroupReads(shape, evaluation.outputs, true) as GroupReads<O>,\n outputs: hydrateGroupShape(\n shape,\n evaluation.outputs.map(output => output.output)\n ) as GroupDrafts<O>,\n reset: evaluation.reset,\n cause: evaluation.cause,\n state,\n });\n assertSynchronous(result);\n return isRebuild(result) ? result : undefined;\n },\n };\n },\n name: `processor-group:${outputs.map(output => output.path?.join('.') ?? '').join(',')}`,\n });\n void previousOf;\n return hydrateGroupShape(shape, projections) as GroupProjections<O>;\n}\n\nexport const incremental = Object.assign(createIncrementalValue, {\n collection: createIncrementalCollection,\n group: createIncrementalGroup,\n});\n\nexport type { CollectionChange } from './contract';\n"],"mappings":";;;AAoOA,MAAa,uBAAuB,SAClC,KAAK,SAAS,SAAS,KAAK,SAAS,WAAW,KAAK,SAAS,SAAS,KAAK,QAAQ,KAAA;AAEtF,MAAM,QAAgC,UAAgB,OAAO,OAAO,MAAM;AAC1E,MAAa,SAAY,cACvB,KAAK;CAAE,MAAM;CAAS,GAAI,YAAY,EAAE,WAAW,GAAG,EAAE;CAAG,CAAC;AAO9D,MAAa,YAAoC,UAA8B;AAC7E,KAAI,CAAC;EAAC;EAAS;EAAW;EAAO;EAAQ;EAAO,CAAC,SAAS,MAAM,KAAK,CACnE,OAAM,IAAI,UAAU,2EAA2E;AACjG,QAAO,KAAK;EAAE,GAAG;EAAO,UAAU;EAAM,CAAoB;;AAE9D,MAAa,UAAiC,UAC5C,KAAK;CAAE,MAAM;CAAU,OAAO,OAAO,OAAO,EAAE,GAAG,OAAO,CAAC;CAAE,CAAC;AAC9D,MAAa,WACX,KACA,aACsB,KAAK;CAAE,MAAM;CAAW;CAAK,UAAU,OAAO,OAAO,EAAE,GAAG,UAAU,CAAC;CAAE,CAAC;AAChG,MAAa,SACX,OACA,YAC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