doxum 0.1.21 → 0.1.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -7
- package/dist/{advanced-FgdTwu5b.d.ts → advanced-CLJCWkHa.d.cts} +3 -3
- package/dist/{advanced-COFJtWMT.js → advanced-CRNHfJBu.js} +482 -446
- package/dist/advanced-CRNHfJBu.js.map +1 -0
- package/dist/{advanced-BRL5pN0y.cjs → advanced-Cle5g3B4.cjs} +615 -459
- package/dist/advanced-Cle5g3B4.cjs.map +1 -0
- package/dist/{advanced-DfKc7TZR.d.cts → advanced-d6J61er9.d.ts} +3 -3
- package/dist/advanced.cjs +1 -1
- package/dist/advanced.d.cts +1 -1
- package/dist/advanced.d.ts +1 -1
- package/dist/advanced.js +1 -1
- package/dist/context-BcLKGfq8.cjs +149 -0
- package/dist/context-BcLKGfq8.cjs.map +1 -0
- package/dist/context-DFEaDUv5.js +84 -0
- package/dist/context-DFEaDUv5.js.map +1 -0
- package/dist/{contract-CdmDHRUq.d.cts → contract-SYJFP0lM.d.cts} +62 -88
- package/dist/{contract-KG5XnQZt.d.ts → contract-ULPQmiEs.d.ts} +62 -88
- package/dist/driver-BD3DQOW6.cjs +382 -0
- package/dist/driver-BD3DQOW6.cjs.map +1 -0
- package/dist/{driver-CLYJOGDQ.js → driver-yFfvDMX5.js} +155 -26
- package/dist/driver-yFfvDMX5.js.map +1 -0
- package/dist/index.cjs +2370 -406
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +6 -5
- package/dist/index.d.ts +6 -5
- package/dist/index.js +2293 -330
- package/dist/index.js.map +1 -1
- package/dist/local-sync.cjs +5 -5
- package/dist/local-sync.cjs.map +1 -1
- package/dist/local-sync.d.cts +1 -1
- package/dist/local-sync.d.ts +1 -1
- package/dist/local-sync.js +2 -2
- package/dist/local-sync.js.map +1 -1
- package/dist/react.cjs +2 -69
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.cts +0 -1
- package/dist/react.d.ts +1 -2
- package/dist/react.js +3 -70
- package/dist/react.js.map +1 -1
- package/package.json +1 -6
- package/skills/doxum-runtime/SKILL.md +7 -1
- package/skills/doxum-runtime/references/guide.en.md +17 -6
- package/skills/doxum-runtime/references/guide.zh-CN.md +15 -5
- package/skills/doxum-runtime/references/invariants.en.md +5 -3
- package/skills/doxum-runtime/references/invariants.zh-CN.md +4 -3
- package/skills/doxum-runtime/references/projections.en.md +5 -0
- package/skills/doxum-runtime/references/projections.zh-CN.md +5 -0
- package/dist/access-BeSV5ve-.js +0 -816
- package/dist/access-BeSV5ve-.js.map +0 -1
- package/dist/access-Bienf28h.cjs +0 -911
- package/dist/access-Bienf28h.cjs.map +0 -1
- package/dist/advanced-BRL5pN0y.cjs.map +0 -1
- package/dist/advanced-COFJtWMT.js.map +0 -1
- package/dist/driver-CLYJOGDQ.js.map +0 -1
- package/dist/driver-Djr3BVvo.cjs +0 -241
- package/dist/driver-Djr3BVvo.cjs.map +0 -1
- package/dist/integration-C4Isp8lJ.js +0 -26
- package/dist/integration-C4Isp8lJ.js.map +0 -1
- package/dist/integration-Z6MsfFI7.cjs +0 -31
- package/dist/integration-Z6MsfFI7.cjs.map +0 -1
- package/dist/integration.cjs +0 -12
- package/dist/integration.d.cts +0 -17
- package/dist/integration.d.ts +0 -17
- package/dist/integration.js +0 -4
- package/dist/issue-DjK1xp5K.cjs +0 -881
- package/dist/issue-DjK1xp5K.cjs.map +0 -1
- package/dist/issue-W0hT8u8D.js +0 -642
- package/dist/issue-W0hT8u8D.js.map +0 -1
- package/dist/notification-Bkjau6B6.js +0 -232
- package/dist/notification-Bkjau6B6.js.map +0 -1
- package/dist/notification-DJfouMEb.cjs +0 -309
- package/dist/notification-DJfouMEb.cjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"advanced-Cle5g3B4.cjs","names":["isRecord","isPlainObject","sequence.keys","sequence.equal","schemaValue.checkKey","contextOf","isPlainObject"],"sources":["../core/src/profile.ts","../core/src/order/sequence.ts","../core/src/schema/layout.ts","../core/src/schema/value.ts","../core/src/schema.ts","../core/src/projection/collection/view.ts","../core/src/projection/contract.ts","../core/src/projection/graph/scheduler.ts","../core/src/projection/definition.ts","../core/src/projection/advanced.ts"],"sourcesContent":["const counters = () => ({\n projection: {\n sourceEvents: 0,\n scheduledNodes: 0,\n processedNodes: 0,\n touchedKeys: 0,\n changedKeys: 0,\n publishedNodes: 0,\n flushes: 0,\n },\n copy: { structures: 0, treeNodes: 0, shallowRecordItems: 0 },\n equality: { calls: 0, containers: 0 },\n recorder: {\n facts: 0,\n groups: 0,\n transitions: 0,\n absorbed: 0,\n orderSnapshots: 0,\n orderCaptures: 0,\n orderItems: 0,\n publishedOrderItems: 0,\n treeNodes: 0,\n sealed: 0,\n indexedGroups: 0,\n },\n access: { scopes: 0, proxies: 0, snapshots: 0, addresses: 0, resolutions: 0 },\n address: {\n schemaSteps: 0,\n documentSteps: 0,\n prefixComparisons: 0,\n segmentsCompared: 0,\n listIndexes: 0,\n listItems: 0,\n },\n impact: { affectsChecks: 0, indexes: 0 },\n collectionIndex: { nodes: 0, builds: 0, builtItems: 0 },\n collectionView: { mappedItems: 0, idsScanned: 0, arraysCopied: 0 },\n materialized: { updated: 0, rebuilt: 0, notifications: 0 },\n});\ntype Counters = ReturnType<typeof counters>;\ntype DeepReadonly<T> = { readonly [K in keyof T]: T[K] extends object ? DeepReadonly<T[K]> : T[K] };\nexport type ProfileSnapshot = DeepReadonly<Counters>;\nlet active: Counters | undefined;\nconst freeze = <T extends object>(value: T): DeepReadonly<T> => {\n Object.values(value).forEach(child => {\n if (child && typeof child === 'object') freeze(child);\n });\n return Object.freeze(value) as DeepReadonly<T>;\n};\nexport const profile = {\n projection: (key: keyof Counters['projection'], amount = 1) => {\n if (active) active.projection[key] += amount;\n },\n recorder: (key: keyof Counters['recorder'], amount = 1) => {\n if (active) active.recorder[key] += amount;\n },\n access: (key: keyof Counters['access']) => {\n if (active) active.access[key]++;\n },\n copy: {\n structure: () => {\n if (active) active.copy.structures++;\n },\n treeNode: () => {\n if (active) active.copy.treeNodes++;\n },\n shallowRecord: (items: number) => {\n if (active) active.copy.shallowRecordItems += items;\n },\n },\n equality: {\n call: () => {\n if (active) active.equality.calls++;\n },\n container: () => {\n if (active) active.equality.containers++;\n },\n },\n address: {\n listIndex: (items: number) => {\n if (active) {\n active.address.listIndexes++;\n active.address.listItems += items;\n }\n },\n schemaStep: () => {\n if (active) active.address.schemaSteps++;\n },\n documentStep: () => {\n if (active) active.address.documentSteps++;\n },\n prefixComparison: () => {\n if (active) active.address.prefixComparisons++;\n },\n segmentCompared: () => {\n if (active) active.address.segmentsCompared++;\n },\n },\n impact: {\n index: () => {\n if (active) active.impact.indexes++;\n },\n affects: () => {\n if (active) active.impact.affectsChecks++;\n },\n },\n collectionIndex: {\n node: () => {\n if (active) active.collectionIndex.nodes++;\n },\n build: (items: number) => {\n if (active) {\n active.collectionIndex.builds++;\n active.collectionIndex.builtItems += items;\n }\n },\n },\n collectionView: {\n mapped: () => {\n if (active) active.collectionView.mappedItems++;\n },\n idsScanned: (amount = 1) => {\n if (active) active.collectionView.idsScanned += amount;\n },\n arrayCopied: () => {\n if (active) active.collectionView.arraysCopied++;\n },\n },\n materialized: {\n updated: () => {\n if (active) active.materialized.updated++;\n },\n rebuilt: () => {\n if (active) active.materialized.rebuilt++;\n },\n notification: () => {\n if (active) active.materialized.notifications++;\n },\n },\n};\nexport type ProfileSession = { snapshot(): ProfileSnapshot; stop(): ProfileSnapshot };\nexport const startProfile = (): ProfileSession => {\n if (active) throw new Error('A document profile session is already active.');\n const value = counters();\n active = value;\n const snapshot = () => freeze(structuredClone(value));\n return {\n snapshot,\n stop: () => {\n if (active === value) active = undefined;\n return snapshot();\n },\n };\n};\nexport const measureProfile = <T>(run: () => T): { value: T; profile: ProfileSnapshot } => {\n const session = startProfile();\n try {\n return { value: run(), profile: session.stop() };\n } finally {\n session.stop();\n }\n};\n","import { profile } from '../profile';\n\nexport type KeyOrder = {\n readonly length: number;\n readonly at: (index: number) => string | undefined;\n readonly index: (key: string) => number;\n};\n\nexport type OrderedKeys = readonly string[] | KeyOrder;\n\ntype ListSequence = {\n readonly order: readonly string[];\n readonly values: ReadonlyMap<string, unknown>;\n};\n\nconst length = (keys: OrderedKeys): number => keys.length;\nconst keyAt = (keys: OrderedKeys, index: number): string | undefined =>\n Array.isArray(keys) ? keys[index] : keys.at(index);\n\nexport const equal = (left: readonly string[], right: OrderedKeys): boolean => {\n profile.equality.call();\n if (left === right) return true;\n profile.equality.container();\n if (left.length !== right.length) return false;\n for (let index = 0; index < left.length; index++)\n if (left[index] !== keyAt(right, index)) return false;\n return true;\n};\n\nexport const keys = (values: readonly unknown[], keyOf: (value: unknown) => string): KeyOrder => ({\n length: values.length,\n at: index => (index >= 0 && index < values.length ? keyOf(values[index]) : undefined),\n index: key => {\n for (let index = 0; index < values.length; index += 1)\n if (keyOf(values[index]) === key) return index;\n return -1;\n },\n});\n\nconst listIndexes = new WeakMap<\n readonly unknown[],\n { keyOf: (value: unknown) => string; order: KeyOrder }\n>();\n\nconst knownKeys = (values: readonly string[]): KeyOrder => {\n let positions: Map<string, number> | undefined;\n return {\n length: values.length,\n at: index => values[index],\n index: key => {\n if (!positions) {\n positions = new Map();\n for (let index = 0; index < values.length; index++) positions.set(values[index], index);\n profile.address.listIndex(values.length);\n }\n return positions.get(key) ?? -1;\n },\n };\n};\n\nconst cacheKnownKeys = (\n values: readonly unknown[],\n keyOf: (value: unknown) => string,\n order: readonly string[]\n): void => {\n listIndexes.set(values, { keyOf, order: knownKeys(order) });\n};\n\n/** Canonical lists keep their key positions until a structural write invalidates them. */\nexport const indexedKeys = (\n values: readonly unknown[],\n keyOf: (value: unknown) => string\n): KeyOrder => {\n const cached = listIndexes.get(values);\n if (cached?.keyOf === keyOf) return cached.order;\n let positions: Map<string, number> | undefined;\n const order: KeyOrder = {\n length: values.length,\n at: index => (index >= 0 && index < values.length ? keyOf(values[index]) : undefined),\n index: key => {\n if (!positions) {\n positions = new Map();\n for (let index = 0; index < values.length; index++)\n positions.set(keyOf(values[index]), index);\n profile.address.listIndex(values.length);\n }\n return positions.get(key) ?? -1;\n },\n };\n listIndexes.set(values, { keyOf, order });\n return order;\n};\n\nexport const toArray = (keys: OrderedKeys): string[] => {\n const result = new Array<string>(length(keys));\n for (let index = 0; index < result.length; index++) result[index] = keyAt(keys, index) as string;\n return result;\n};\n\n/** One operation-local list scan provides both stable keys and item association. */\nexport const listSequence = (\n values: readonly unknown[],\n keyOf: (value: unknown) => string\n): ListSequence => {\n const current = indexedKeys(values, keyOf);\n const order = new Array<string>(values.length);\n const byKey = new Map<string, unknown>();\n for (let index = 0; index < values.length; index++) {\n const key = current.at(index) as string;\n order[index] = key;\n byKey.set(key, values[index]);\n }\n cacheKnownKeys(values, keyOf, order);\n return { order, values: byKey };\n};\n\n/** Structural sequence writes own invalidation, including rollback writes. */\nexport const insert = (values: unknown[], index: number, value: unknown): void => {\n values.splice(index, 0, value);\n listIndexes.delete(values);\n};\n\nexport const remove = (values: unknown[], index: number): void => {\n values.splice(index, 1);\n listIndexes.delete(values);\n};\n\n/** Installs an exact string-key sequence such as table ids in one structural write. */\nexport const installKeys = (values: string[], order: readonly string[]): void => {\n values.length = order.length;\n for (let index = 0; index < order.length; index++) values[index] = order[index];\n};\n\n/** Installs a pre-resolved list sequence without running keyOf again. */\nexport const installList = (\n values: unknown[],\n keyOf: (value: unknown) => string,\n sequence: ListSequence,\n order: readonly string[]\n): void => {\n values.length = order.length;\n for (let index = 0; index < order.length; index++)\n values[index] = sequence.values.get(order[index]);\n cacheKnownKeys(values, keyOf, order);\n};\n\nexport const install = (\n values: unknown[],\n keyOf: (value: unknown) => string,\n order: readonly string[]\n): void => {\n installList(values, keyOf, listSequence(values, keyOf), order);\n};\n\nexport const matches = (order: readonly string[], members: readonly string[]): boolean => {\n if (order.length !== members.length) return false;\n const ids = new Set(order);\n return ids.size === order.length && members.every(id => ids.has(id));\n};\n","import { profile } from '../profile';\nimport type { DocumentNode, ObjectShape } from '../schema';\n\ntype MemberDefinition = {\n readonly node: DocumentNode;\n readonly field: boolean;\n};\n\nexport type FixedMember = MemberDefinition & {\n readonly kind: 'fixed';\n readonly key: string;\n readonly slot: number;\n};\n\ntype CollectionMember = MemberDefinition & { readonly kind: 'entry' };\n\nexport type CompiledMember = FixedMember | CollectionMember;\n\nexport type FixedLayout = {\n readonly kind: 'fixed';\n readonly members: ReadonlyMap<string, FixedMember>;\n};\n\ntype DynamicLayout = {\n readonly kind: 'dynamic';\n readonly entry: CollectionMember;\n};\n\nexport type MemberLayout = FixedLayout | DynamicLayout;\n\nconst compiledObjects = new WeakMap<object, FixedLayout>();\nconst compiledEntries = new WeakMap<DocumentNode, DynamicLayout>();\n\nconst objectBranch = (\n node: DocumentNode,\n value: unknown\n): Extract<DocumentNode, { readonly kind: 'object' }> | undefined => {\n if (node.kind === 'object') return node;\n if (\n node.kind !== 'variant' ||\n typeof value !== 'object' ||\n value === null ||\n Array.isArray(value)\n )\n return undefined;\n const record = value as Record<string, unknown>;\n const tag = typeof record[node.tag] === 'string' ? record[node.tag] : undefined;\n return node.variants[String(tag ?? Object.keys(node.variants)[0] ?? '')];\n};\n\nexport const compiledShape = (node: DocumentNode, value: unknown): FixedLayout | undefined => {\n const branch = objectBranch(node, value);\n if (!branch) return undefined;\n const shape: ObjectShape = branch.shape;\n let layout = compiledObjects.get(shape);\n if (!layout) {\n const members = new Map<string, FixedMember>();\n for (const key of Object.keys(shape).sort()) {\n profile.address.schemaStep();\n members.set(key, {\n kind: 'fixed',\n key,\n node: shape[key],\n field: shape[key].kind === 'field',\n slot: members.size,\n });\n }\n layout = { kind: 'fixed', members };\n compiledObjects.set(shape, layout);\n }\n return layout;\n};\n\nexport const compiledLayout = (node: DocumentNode, value: unknown): MemberLayout | undefined => {\n if (node.kind !== 'map' && node.kind !== 'table' && node.kind !== 'list')\n return compiledShape(node, value);\n let layout = compiledEntries.get(node);\n if (!layout) {\n layout = {\n kind: 'dynamic',\n entry: { kind: 'entry', node: node.value, field: node.value.kind === 'field' },\n };\n compiledEntries.set(node, layout);\n }\n return layout;\n};\n","import { profile } from '../profile';\nimport * as sequence from '../order/sequence';\nimport * as tree from '../tree/topology';\nimport { isPlainObject, isRecord } from '../value/record';\nimport type {\n DocumentAddress,\n DocumentNode,\n DocumentTreeNode,\n FieldNode,\n Infer,\n Validator,\n} from '../schema';\nimport { compiledShape } from './layout';\n\nexport type ParseIssue = {\n readonly address: DocumentAddress;\n readonly code: 'invalid-value' | 'invalid-key' | 'missing-validator' | 'invalid-tree';\n readonly message: string;\n};\nexport class ParseError extends TypeError {\n readonly issues: readonly ParseIssue[];\n constructor(issue: ParseIssue) {\n super(`${issue.message} at ${JSON.stringify(issue.address)}`);\n this.name = 'ParseError';\n this.issues = Object.freeze([\n Object.freeze({ ...issue, address: Object.freeze([...issue.address]) }),\n ]);\n }\n}\n\nconst issue = (\n address: DocumentAddress,\n message: string,\n code: ParseIssue['code'] = 'invalid-value'\n): ParseIssue => ({ address, message, code });\n\nconst checkScalar = (\n validator: Validator<unknown> | undefined,\n value: unknown,\n address: DocumentAddress,\n strict: boolean\n): ParseIssue | undefined => {\n if (!validator)\n return strict\n ? issue(address, 'A validator is required to parse an opaque value.', 'missing-validator')\n : undefined;\n try {\n const result =\n typeof validator === 'function' ? validator(value) : validator['~standard'].validate(value);\n if (\n result &&\n (typeof result === 'object' || typeof result === 'function') &&\n 'then' in result &&\n typeof result.then === 'function'\n )\n return issue(address, 'Validators must be synchronous.');\n if (typeof validator !== 'function') {\n if (!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 = sequence.keys(value, node.keyOf);\n for (let i = 0; i < value.length; i++) {\n const failure = checkValue(node.value, value[i], [...address, String(i)], strict);\n if (failure) return failure;\n let key: unknown;\n try {\n key = order.at(i);\n } catch {\n return issue(address, 'List keyOf failed.');\n }\n if (typeof key !== 'string' || seen.has(key))\n return issue(address, 'List keys must be unique strings.', 'invalid-key');\n seen.add(key);\n }\n return undefined;\n }\n if (!tree.validate(value)) return issue(address, 'Invalid tree structure.', 'invalid-tree');\n for (const id of Object.keys(value.nodes)) {\n const failure = checkTreePayload(node.value, value.nodes[id], [...address, id], strict);\n if (failure) return failure;\n }\n return undefined;\n};\n\nexport const checkTreePayload = (\n node: FieldNode<unknown, boolean>,\n value: unknown,\n address: DocumentAddress,\n strict = false\n): ParseIssue | undefined => {\n if (!isRecord(value)) return issue(address, 'Invalid tree node.', 'invalid-tree');\n const present = Object.prototype.hasOwnProperty.call(value, 'value');\n if (!present && !node.optional) return issue(address, 'Tree node value is required.');\n return present ? checkValue(node, value.value, address, strict) : undefined;\n};\n\nexport const copyTreeNode = <T extends { readonly children: readonly string[] }>(\n value: T\n): Omit<T, 'children'> & { children: string[] } => {\n profile.copy.treeNode();\n return { ...value, children: [...value.children] };\n};\n\nexport const equalTreeNode = (\n left: DocumentTreeNode<unknown, false> | DocumentTreeNode<unknown, true> | undefined,\n right: DocumentTreeNode<unknown, false> | DocumentTreeNode<unknown, true> | undefined\n): boolean => {\n if (left === right) return true;\n if (!left || !right) return false;\n return (\n left.parentId === right.parentId &&\n sequence.equal(left.children, right.children) &&\n Object.hasOwn(left, 'value') === Object.hasOwn(right, 'value') &&\n Object.is(left.value, right.value)\n );\n};\n\n/** Copy editable structure; atomic payloads retain their immutable ownership contract. */\nexport const copyValue = (node: DocumentNode, value: unknown): unknown => {\n if (value === undefined || node.kind === 'field') return value;\n profile.copy.structure();\n if ((node.kind === 'object' || node.kind === 'variant') && isRecord(value)) {\n const result = Object.create(Object.getPrototypeOf(value));\n const { members } = compiledShape(node, value)!;\n for (const key of Object.getOwnPropertyNames(value)) {\n Object.defineProperty(result, key, {\n value:\n node.kind === 'variant' && key === node.tag\n ? value[key]\n : copyValue(members.get(key)!.node, value[key]),\n writable: true,\n enumerable: Object.getOwnPropertyDescriptor(value, key)?.enumerable,\n configurable: true,\n });\n }\n return result;\n }\n if ((node.kind === 'table' || node.kind === 'map') && isRecord(value)) {\n const entries = (node.kind === 'table' ? value.byId : value) as Record<string, unknown>;\n const result = Object.fromEntries(\n Object.keys(entries).map(id => [id, copyValue(node.value, entries[id])])\n );\n return node.kind === 'table' ? { ids: [...(value.ids as string[])], byId: result } : result;\n }\n if (node.kind === 'list') return [...(value as unknown[])];\n if (node.kind === 'tree' && isRecord(value)) {\n const entries = value.nodes as Record<\n string,\n DocumentTreeNode<unknown, false> | DocumentTreeNode<unknown, true>\n >;\n return {\n ...value,\n nodes: Object.fromEntries(Object.entries(entries).map(([id, n]) => [id, copyTreeNode(n)])),\n };\n }\n return value;\n};\n\nexport const equalValue = (node: DocumentNode, left: unknown, right: unknown): boolean => {\n if (Object.is(left, right)) return true;\n if (node.kind === 'field' || left === undefined || right === undefined) return false;\n if ((node.kind === 'object' || node.kind === 'variant') && isRecord(left) && isRecord(right)) {\n if (node.kind === 'variant' && left[node.tag] !== right[node.tag]) return false;\n for (const [key, member] of compiledShape(node, left)!.members) {\n if (Object.hasOwn(left, key) !== Object.hasOwn(right, key)) return false;\n if (!equalValue(member.node, left[key], right[key])) return false;\n }\n return true;\n }\n if (node.kind === 'list' && Array.isArray(left) && Array.isArray(right))\n return (\n left.length === right.length && left.every((v, i) => equalValue(node.value, v, right[i]))\n );\n if (node.kind === 'table' && isRecord(left) && isRecord(right))\n return (\n sequence.equal(left.ids as string[], right.ids as string[]) &&\n equalValue({ kind: 'map', value: node.value }, left.byId, right.byId)\n );\n if (node.kind === 'tree' && isRecord(left) && isRecord(right)) {\n if (left.rootId !== right.rootId) return false;\n const a = left.nodes as Record<\n string,\n DocumentTreeNode<unknown, false> | DocumentTreeNode<unknown, true>\n >,\n b = right.nodes as typeof a;\n return (\n Object.keys(a).length === Object.keys(b).length &&\n Object.keys(a).every(id => Object.hasOwn(b, id) && equalTreeNode(a[id], b[id]))\n );\n }\n if (node.kind === 'map' && isRecord(left) && isRecord(right)) {\n const keys = Object.keys(left);\n return (\n keys.length === Object.keys(right).length &&\n keys.every(key => Object.hasOwn(right, key) && equalValue(node.value, left[key], right[key]))\n );\n }\n return false;\n};\n\nexport const parse = <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 * as schemaValue from './schema/value';\nexport type DocumentAddress = readonly string[];\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\n/** Shared payloads are immutable through every alias, including builtin methods. */\nexport type ReadonlyValue<T> = T extends (...args: never[]) => unknown\n ? T\n : T extends ReadonlyMap<infer K, infer V>\n ? ReadonlyMap<ReadonlyValue<K>, ReadonlyValue<V>>\n : T extends ReadonlySet<infer V>\n ? ReadonlySet<ReadonlyValue<V>>\n : T extends Date\n ? Omit<Date, `set${string}`>\n : T extends object\n ? { readonly [K in keyof T]: ReadonlyValue<T[K]> }\n : T;\n\nexport type DocumentListConfig<TItem> = {\n readonly keyOf: (item: ReadonlyValue<TItem>) => string;\n};\nexport type DocumentTreeNode<TValue, ValueOptional extends boolean = false> = {\n readonly parentId?: string;\n readonly children: readonly string[];\n} & (ValueOptional extends true\n ? { readonly value?: ReadonlyValue<TValue> }\n : { readonly value: ReadonlyValue<TValue> });\nexport type DocumentTreeValue<TValue, ValueOptional extends boolean = false> = {\n readonly rootId?: string;\n readonly nodes: Readonly<Record<string, DocumentTreeNode<TValue, ValueOptional>>>;\n};\n\ntype BaseNode<K extends string> = {\n readonly kind: K;\n readonly optional?: boolean;\n};\nexport type FieldNode<T, Optional extends boolean = false> = BaseNode<'field'> & {\n readonly __value?: T;\n readonly validator?: Validator<T>;\n} & (Optional extends true ? { readonly optional: true } : { readonly optional?: false });\n/** A node with optional presence. The marker replaces, rather than intersects, a field marker. */\nexport type OptionalNode<TNode extends DocumentNode> =\n TNode extends FieldNode<infer TValue, boolean>\n ? FieldNode<TValue, true>\n : TNode & { readonly optional: true };\nexport interface ObjectShape {\n readonly [key: string]: DocumentNode;\n}\nexport type ObjectNode<TShape extends ObjectShape = ObjectShape> = BaseNode<'object'> & {\n readonly shape: TShape;\n};\nexport interface VariantShape {\n readonly [key: string]: ObjectNode<ObjectShape>;\n}\nexport type VariantNode<\n TTag extends string,\n TVariants extends VariantShape,\n> = BaseNode<'variant'> & {\n readonly tag: TTag;\n readonly variants: TVariants;\n};\nexport type TableNode<\n TValue extends ObjectNode<ObjectShape> | VariantNode<string, VariantShape>,\n TKey extends string = string,\n> = BaseNode<'table'> & {\n readonly value: TValue;\n readonly key?: Validator<TKey>;\n};\nexport type MapNode<\n TValue extends ValueSchemaNode,\n TKey extends string = string,\n> = BaseNode<'map'> & {\n readonly value: TValue;\n readonly key?: Validator<TKey>;\n};\nexport type ListNode<TItem> = BaseNode<'list'> & {\n readonly value: FieldNode<TItem, false>;\n keyOf(item: ReadonlyValue<TItem>): string;\n};\nexport type TreeNode<TValue, ValueOptional extends boolean = false> = BaseNode<'tree'> & {\n readonly value: FieldNode<TValue, ValueOptional>;\n};\n\nexport type DocumentNode =\n | FieldNode<unknown, false>\n | FieldNode<unknown, true>\n | ObjectNode<ObjectShape>\n | VariantNode<string, VariantShape>\n | TableNode<ObjectNode<ObjectShape> | VariantNode<string, VariantShape>>\n | MapNode<ValueSchemaNode>\n | ListNode<unknown>\n | TreeNode<unknown, false>\n | TreeNode<unknown, true>;\n\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, infer O>\n ? DocumentTreeValue<T, O>\n : never;\n\ntype OptionalKeys<S extends ObjectShape> = {\n [K in keyof S]: S[K] extends { readonly optional: true } ? K : never;\n}[keyof S];\ntype RequiredKeys<S extends ObjectShape> = Exclude<keyof S, OptionalKeys<S>>;\ntype ShapeValue<S extends ObjectShape> = SchemaObject<\n { readonly [K in RequiredKeys<S>]: NodeValue<S[K]> } & {\n readonly [K in OptionalKeys<S>]?: NodeValue<S[K]>;\n }\n>;\n\nexport type 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 TreeTarget =\n | { readonly kind: 'root' }\n | { readonly kind: 'nodes' }\n | { readonly kind: 'node'; readonly id: string };\ntype TreeValueTarget = Exclude<TreeTarget, { readonly kind: 'nodes' }>;\ntype TreeCollectionTarget = Extract<TreeTarget, { readonly kind: 'nodes' }>;\n\nexport type CollectionSelector<TId extends string = string> = {\n readonly kind: 'collection';\n readonly schema: ObjectNode;\n readonly address: DocumentAddress;\n readonly tree?: TreeCollectionTarget;\n readonly __id?: TId;\n};\nexport type ValueSelector<TResult = unknown> = {\n readonly kind: 'value';\n readonly schema: ObjectNode;\n readonly address: DocumentAddress;\n readonly tree?: TreeValueTarget;\n readonly __value?: TResult;\n};\nexport type ImpactTarget<T = unknown> =\n | { readonly kind: 'value'; readonly at: DocumentAddress; readonly tree?: TreeValueTarget }\n | ValueSelector<T>\n | {\n readonly kind: 'collection';\n readonly at: DocumentAddress;\n readonly id?: string;\n }\n | CollectionSelector<string>;\ndeclare const pathValue: unique symbol;\ndeclare const collectionEntry: unique symbol;\ndeclare const collectionKey: unique symbol;\ntype PathMarker<TValue> = { readonly [pathValue]: TValue };\nexport type PathValueOf<T> = T extends { readonly [pathValue]: infer TValue } ? TValue : never;\n\ntype Or<A extends boolean, B extends boolean> = A extends true ? true : B;\ntype NodeAbsent<N extends DocumentNode, ParentAbsent extends boolean> = Or<\n ParentAbsent,\n N extends { readonly optional: true } ? true : false\n>;\ntype PathResult<N extends DocumentNode, ParentAbsent extends boolean> =\n Infer<N> | (ParentAbsent extends true ? undefined : never);\n\ntype SchemaPathFor<\n S extends ObjectShape = ObjectShape,\n TValue = unknown,\n Absent extends boolean = false,\n> = {\n readonly [K in keyof S]: PathValue<S[K], Absent>;\n} & PathMarker<TValue | (Absent extends true ? undefined : never)>;\n\nexport type SchemaPath<S extends 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 VariantFieldMissing<V extends VariantShape, K extends string> = {\n [P in keyof V & string]: V[P] extends ObjectNode<infer S> ? (K extends keyof S ? never : P) : P;\n}[keyof V & string] extends never\n ? false\n : true;\ntype VariantFieldPath<V extends VariantShape, K extends string, Absent extends boolean> = {\n [P in keyof V & string]: V[P] extends ObjectNode<infer S>\n ? K extends keyof S\n ? PathValue<S[K], Or<Absent, VariantFieldMissing<V, K>>>\n : never\n : never;\n}[keyof V & string];\ntype VariantPath<T extends string, V extends VariantShape, TValue, Absent extends boolean> = {\n readonly [K in VariantKeys<V>]: VariantFieldPath<V, K, Absent>;\n} & {\n readonly [K in T]: PathMarker<(keyof V & string) | (Absent extends true ? undefined : never)>;\n} & PathMarker<TValue>;\nexport type CollectionPath<\n K extends string = string,\n TValue = unknown,\n TEntry = unknown,\n TItem = PathMarker<TEntry | undefined>,\n> = PathMarker<TValue> & {\n item(id: K): TItem;\n readonly [collectionEntry]: TEntry;\n readonly [collectionKey]: K;\n};\ntype TreeNodesPath<TValue, ValueOptional extends boolean> = CollectionPath<\n string,\n Readonly<Record<string, DocumentTreeNode<TValue, ValueOptional>>>,\n DocumentTreeNode<TValue, ValueOptional>,\n PathMarker<DocumentTreeNode<TValue, ValueOptional> | undefined>\n>;\ntype TreePath<TValue, ValueOptional extends boolean, TValueResult> = PathMarker<TValueResult> & {\n readonly rootId: PathMarker<string | undefined>;\n readonly nodes: TreeNodesPath<TValue, ValueOptional>;\n};\n\ntype PathValue<N extends DocumentNode, ParentAbsent extends boolean = false> =\n N extends ObjectNode<infer S>\n ? SchemaPathFor<S, PathResult<N, ParentAbsent>, NodeAbsent<N, ParentAbsent>>\n : N extends VariantNode<infer TTag, infer V>\n ? VariantPath<TTag, V, PathResult<N, ParentAbsent>, NodeAbsent<N, ParentAbsent>>\n : N extends TableNode<infer V, infer K>\n ? CollectionPath<K, PathResult<N, ParentAbsent>, Infer<V>, PathValue<V, true>>\n : N extends MapNode<infer V, infer K>\n ? CollectionPath<K, PathResult<N, ParentAbsent>, Infer<V>, PathValue<V, true>>\n : N extends ListNode<infer I>\n ? CollectionPath<\n string,\n PathResult<N, ParentAbsent>,\n ReadonlyValue<I>,\n PathMarker<ReadonlyValue<I> | undefined>\n >\n : N extends TreeNode<infer T, infer O>\n ? TreePath<T, O, PathResult<N, ParentAbsent>>\n : PathMarker<PathResult<N, ParentAbsent>>;\ntype CollectionInfo<T> = T extends {\n readonly [collectionEntry]: infer TEntry;\n readonly [collectionKey]: infer K extends string;\n}\n ? { readonly id: K; readonly entry: TEntry }\n : never;\nexport type CollectionId<T> =\n CollectionInfo<T> extends { readonly id: infer TId extends string } ? TId : string;\nexport type CollectionEntry<T> =\n CollectionInfo<T> extends { readonly entry: infer TEntry } ? TEntry : unknown;\n\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, false>\n | TreeNode<unknown, true>;\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, ValueOptional extends boolean>(\n value: FieldNode<TValue, ValueOptional>\n): TreeNode<TValue, ValueOptional> => Object.freeze({ kind: 'tree' as const, value });\n\nconst paths = new WeakMap<\n object,\n {\n readonly address: DocumentAddress;\n readonly nodes: readonly DocumentNode[];\n readonly owner: object;\n readonly tree?: TreeTarget;\n }\n>();\n\nconst pathProxy = (\n nodes: readonly DocumentNode[],\n address: DocumentAddress,\n owner: object,\n treeSelection?: TreeTarget\n): object => {\n const proxy = new Proxy(\n {},\n {\n get: (_target, property: string | symbol) => {\n if (typeof property !== 'string') return undefined;\n const trees = nodes.every(node => node.kind === 'tree');\n if (!treeSelection && trees && property === 'rootId')\n return pathProxy(nodes, address, owner, { kind: 'root' });\n if (!treeSelection && trees && property === 'nodes')\n return pathProxy(nodes, address, owner, { kind: 'nodes' });\n if (treeSelection?.kind === 'nodes' && property === 'item')\n return (id: string) => {\n if (typeof id !== 'string') throw new TypeError('Tree node keys must be strings.');\n return pathProxy(nodes, address, owner, { kind: 'node', id });\n };\n if (treeSelection) throw new TypeError(`Invalid tree path segment: ${property}`);\n const collection = nodes.every(node => collectionEntryNode(node) !== undefined);\n if (collection && property === 'item')\n return (id: string) => {\n if (typeof id !== 'string') throw new TypeError('Collection keys must be strings.');\n for (const node of nodes)\n if (node.kind === 'table' || node.kind === 'map') {\n const invalid = schemaValue.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, ...(treeSelection ? { tree: treeSelection } : {}) });\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 =\n selected.tree?.kind === 'nodes' ||\n selected.nodes.every(node => collectionEntryNode(node) !== undefined);\n if (kind === 'collection' && !collection)\n throw new TypeError('Collection selectors require a map, table, list or tree nodes path.');\n const resolvedKind = kind === 'auto' ? (collection ? 'collection' : 'value') : kind;\n const result = Object.freeze({\n kind: resolvedKind,\n schema: owner,\n address: Object.freeze([...selected.address]),\n ...(selected.tree ? { tree: Object.freeze({ ...selected.tree }) } : {}),\n }) as CollectionSelector | ValueSelector;\n return result;\n};\n","import type { CollectionRead } from '../contract';\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","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 { contextOf } from '../runtime/context';\nimport type { DocumentReadable, Synchronous } from '../runtime/contract';\nimport type {\n CollectionEntry,\n CollectionId,\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/view';\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 './graph/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\ntype 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';\n readonly document: DocumentReadable<ObjectNode>;\n readonly selector: ValueSelector | 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<CollectionEntry<P>>>,\n CollectionChange<CollectionId<P>, ReadonlyValue<CollectionEntry<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 const state = contextOf(document).state;\n const selected = selector\n ? compilePath(state.schema, 'auto', selector as never)\n : (Object.freeze({\n kind: 'value' as const,\n schema: state.schema,\n address: Object.freeze([]),\n }) as ValueSelector);\n return defineSource(\n { kind: 'document', document, selector: selected },\n { kind: selected.kind, equality: Object.is }\n );\n}\n\nconst isExternalSource = (\n source: unknown\n): source is ExternalValueSource<unknown> | ExternalCollectionSource<string, unknown> => {\n if (!source || typeof source !== 'object') return false;\n const candidate = source as {\n readonly kind?: unknown;\n readonly current?: unknown;\n readonly revision?: unknown;\n readonly subscribe?: unknown;\n };\n return (\n (candidate.kind === 'value' || candidate.kind === 'collection') &&\n typeof candidate.current === 'function' &&\n typeof candidate.revision === 'function' &&\n typeof candidate.subscribe === 'function'\n );\n};\n\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/view';\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 './graph/scheduler';\nimport { isPlainObject } from '../value/record';\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 };\ntype GroupOutputMetadata = {\n readonly kind: OutputDefinition['kind'];\n readonly equality: (a: unknown, b: unknown) => boolean;\n};\n\nconst isPlainGroupNamespace = (\n value: unknown,\n metadata: ReadonlyMap<object, GroupOutputMetadata>\n): value is Record<string, unknown> => isPlainObject(value) && !metadata.has(value);\n\nconst compileGroupShape = (\n value: unknown,\n path: readonly string[],\n metadata: ReadonlyMap<object, GroupOutputMetadata>,\n used: Set<object>,\n outputs: OutputDefinition[]\n): GroupShape => {\n if (value !== null && typeof value === 'object') {\n const output = metadata.get(value);\n if (output) {\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: output.kind,\n equality: output.equality,\n path: Object.freeze([...path]),\n });\n return index;\n }\n }\n if (!isPlainGroupNamespace(value, metadata))\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(descriptor.value, [...path, key], metadata, used, outputs);\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 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 metadata = new Map<object, GroupOutputMetadata>();\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 metadata.set(descriptor, {\n kind: 'collection',\n equality: equality as (a: unknown, b: unknown) => boolean,\n });\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 metadata.set(descriptor, {\n kind: 'value',\n equality: equality as (a: unknown, b: unknown) => boolean,\n });\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, [], metadata, 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 !== metadata.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 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":";AAiDA,MAAa,UAAU;CACrB,aAAa,KAAmC,SAAS,MAAM;CAG/D,WAAW,KAAiC,SAAS,MAAM;CAG3D,SAAS,QAAkC;CAG3C,MAAM;EACJ,iBAAiB;EAGjB,gBAAgB;EAGhB,gBAAgB,UAAkB;EAGnC;CACD,UAAU;EACR,YAAY;EAGZ,iBAAiB;EAGlB;CACD,SAAS;EACP,YAAY,UAAkB;EAM9B,kBAAkB;EAGlB,oBAAoB;EAGpB,wBAAwB;EAGxB,uBAAuB;EAGxB;CACD,QAAQ;EACN,aAAa;EAGb,eAAe;EAGhB;CACD,iBAAiB;EACf,YAAY;EAGZ,QAAQ,UAAkB;EAM3B;CACD,gBAAgB;EACd,cAAc;EAGd,aAAa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AAO,WAAW;KAClB;KACD,CAAC;AACF,sBAAkB,OAAO;AACzB,WAAO,UAAU,OAAO,GAAG,SAAS,KAAA;MAEvC;;EAEH,MAAM,mBAAmB,QAAQ,KAAI,WAAU,OAAO,MAAM,KAAK,IAAI,IAAI,GAAG,CAAC,KAAK,IAAI;EACvF,CAC0C,CAAC;;AAG9C,MAAa,cAAc,OAAO,OAAO,wBAAwB;CAC/D,YAAY;CACZ,OAAO;CACR,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { F as CollectionPath, K as ObjectNode, N as CollectionEntry, P as CollectionId, U as Infer, X as ReadonlyValue, Y as PathValueOf, Z as SchemaPath, _ as Unsubscribe, b as CollectionImpact, g as Readable, o as DocumentReadable, p as Synchronous } from "./contract-ULPQmiEs.js";
|
|
2
2
|
|
|
3
3
|
//#region core/src/projection/contract.d.ts
|
|
4
4
|
/** The one processor-facing collection transition protocol. */
|
|
@@ -98,7 +98,7 @@ declare function observe<S extends ObjectNode>(document: DocumentReadable<S>): P
|
|
|
98
98
|
declare function observe<T>(source: ExternalValueSource<T>): Projection<T>;
|
|
99
99
|
declare function observe<K extends string, V>(source: ExternalCollectionSource<K, V>): Projection<ReadonlyMap<K, V>, CollectionChange<K, V>>;
|
|
100
100
|
declare function observe<T>(readable: Readable<T>): Projection<T>;
|
|
101
|
-
declare function observe<S extends ObjectNode, P extends CollectionPath>(document: DocumentReadable<S>, selector: (path: SchemaPath<S['shape']>) => P): Projection<ReadonlyMap<CollectionId<P>, ReadonlyValue<
|
|
101
|
+
declare function observe<S extends ObjectNode, P extends CollectionPath>(document: DocumentReadable<S>, selector: (path: SchemaPath<S['shape']>) => P): Projection<ReadonlyMap<CollectionId<P>, ReadonlyValue<CollectionEntry<P>>>, CollectionChange<CollectionId<P>, ReadonlyValue<CollectionEntry<P>>>>;
|
|
102
102
|
declare function observe<S extends ObjectNode, P>(document: DocumentReadable<S>, selector: (path: SchemaPath<S['shape']>) => P): Projection<PathValueOf<P>>;
|
|
103
103
|
declare function derive<const D extends readonly Projection<unknown, unknown>[], T>(dependencies: D, compute: (...values: ProjectionValues$1<D>) => Synchronous<T>, equality?: (previous: T, next: T) => boolean): Projection<T>;
|
|
104
104
|
//#endregion
|
|
@@ -173,4 +173,4 @@ declare const incremental: typeof createIncrementalValue & {
|
|
|
173
173
|
};
|
|
174
174
|
//#endregion
|
|
175
175
|
export { ProjectionError as C, ProjectionDisposedError as S, ExternalCollectionEvent as _, IncrementalGroupDefine as a, ExternalValueEvent as b, IncrementalValueContext as c, Input as d, Projection as f, CollectionChange as g, observe as h, IncrementalGroupContext as i, IncrementalValueProcessor as l, input as m, IncrementalCollectionContext as n, IncrementalGroupOutputTree as o, derive as p, IncrementalCollectionProcessor as r, IncrementalGroupProcessor as s, GroupProjections as t, incremental as u, ExternalCollectionRead as v, ExternalValueSource as x, ExternalCollectionSource as y };
|
|
176
|
-
//# sourceMappingURL=advanced-
|
|
176
|
+
//# sourceMappingURL=advanced-d6J61er9.d.ts.map
|
package/dist/advanced.cjs
CHANGED
package/dist/advanced.d.cts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as IncrementalGroupDefine, c as IncrementalValueContext, g as CollectionChange, i as IncrementalGroupContext, l as IncrementalValueProcessor, n as IncrementalCollectionContext, o as IncrementalGroupOutputTree, r as IncrementalCollectionProcessor, s as IncrementalGroupProcessor, t as GroupProjections, u as incremental } from "./advanced-
|
|
1
|
+
import { a as IncrementalGroupDefine, c as IncrementalValueContext, g as CollectionChange, i as IncrementalGroupContext, l as IncrementalValueProcessor, n as IncrementalCollectionContext, o as IncrementalGroupOutputTree, r as IncrementalCollectionProcessor, s as IncrementalGroupProcessor, t as GroupProjections, u as incremental } from "./advanced-CLJCWkHa.cjs";
|
|
2
2
|
export { CollectionChange, GroupProjections, IncrementalCollectionContext, IncrementalCollectionProcessor, IncrementalGroupContext, IncrementalGroupDefine, IncrementalGroupOutputTree, IncrementalGroupProcessor, IncrementalValueContext, IncrementalValueProcessor, incremental };
|
package/dist/advanced.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as IncrementalGroupDefine, c as IncrementalValueContext, g as CollectionChange, i as IncrementalGroupContext, l as IncrementalValueProcessor, n as IncrementalCollectionContext, o as IncrementalGroupOutputTree, r as IncrementalCollectionProcessor, s as IncrementalGroupProcessor, t as GroupProjections, u as incremental } from "./advanced-
|
|
1
|
+
import { a as IncrementalGroupDefine, c as IncrementalValueContext, g as CollectionChange, i as IncrementalGroupContext, l as IncrementalValueProcessor, n as IncrementalCollectionContext, o as IncrementalGroupOutputTree, r as IncrementalCollectionProcessor, s as IncrementalGroupProcessor, t as GroupProjections, u as incremental } from "./advanced-d6J61er9.js";
|
|
2
2
|
export { CollectionChange, GroupProjections, IncrementalCollectionContext, IncrementalCollectionProcessor, IncrementalGroupContext, IncrementalGroupDefine, IncrementalGroupOutputTree, IncrementalGroupProcessor, IncrementalValueContext, IncrementalValueProcessor, incremental };
|
package/dist/advanced.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { t as incremental } from "./advanced-
|
|
1
|
+
import { t as incremental } from "./advanced-CRNHfJBu.js";
|
|
2
2
|
export { incremental };
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
//#region core/src/value/record.ts
|
|
2
|
+
const isPlainObject = (value) => {
|
|
3
|
+
if (value === null || typeof value !== "object") return false;
|
|
4
|
+
const prototype = Object.getPrototypeOf(value);
|
|
5
|
+
return prototype === Object.prototype || prototype === null;
|
|
6
|
+
};
|
|
7
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
8
|
+
/** Installs an own data member without invoking inherited setters such as __proto__. */
|
|
9
|
+
const installOwn = (parent, key, present, value) => {
|
|
10
|
+
if (!present) {
|
|
11
|
+
Reflect.deleteProperty(parent, key);
|
|
12
|
+
return;
|
|
13
|
+
}
|
|
14
|
+
if (Object.hasOwn(parent, key)) {
|
|
15
|
+
Reflect.set(parent, key, value);
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
Object.defineProperty(parent, key, {
|
|
19
|
+
value,
|
|
20
|
+
writable: true,
|
|
21
|
+
configurable: true,
|
|
22
|
+
enumerable: true
|
|
23
|
+
});
|
|
24
|
+
};
|
|
25
|
+
//#endregion
|
|
26
|
+
//#region core/src/tree/topology.ts
|
|
27
|
+
const node = (tree, id) => Object.hasOwn(tree.nodes, id) ? tree.nodes[id] : void 0;
|
|
28
|
+
const is = (value) => isRecord(value) && isRecord(value.nodes);
|
|
29
|
+
const validNode = (value) => {
|
|
30
|
+
if (!isRecord(value) || !Array.isArray(value.children)) return false;
|
|
31
|
+
if (value.parentId !== void 0 && typeof value.parentId !== "string") return false;
|
|
32
|
+
const children = /* @__PURE__ */ new Set();
|
|
33
|
+
for (const id of value.children) {
|
|
34
|
+
if (typeof id !== "string" || children.has(id)) return false;
|
|
35
|
+
children.add(id);
|
|
36
|
+
}
|
|
37
|
+
return true;
|
|
38
|
+
};
|
|
39
|
+
const contains = (tree, id) => Object.hasOwn(tree.nodes, id);
|
|
40
|
+
const parent = (tree, id) => node(tree, id)?.parentId;
|
|
41
|
+
const children = (tree, id) => node(tree, id)?.children;
|
|
42
|
+
const validate = (value) => {
|
|
43
|
+
if (!is(value)) return false;
|
|
44
|
+
const ids = Object.keys(value.nodes);
|
|
45
|
+
if (ids.length === 0) return value.rootId === void 0;
|
|
46
|
+
if (typeof value.rootId !== "string" || !Object.hasOwn(value.nodes, value.rootId)) return false;
|
|
47
|
+
for (const id of ids) {
|
|
48
|
+
const entry = value.nodes[id];
|
|
49
|
+
if (!validNode(entry)) return false;
|
|
50
|
+
if (id === value.rootId) {
|
|
51
|
+
if (entry.parentId !== void 0) return false;
|
|
52
|
+
} else if (entry.parentId === void 0 || !Object.hasOwn(value.nodes, entry.parentId)) return false;
|
|
53
|
+
for (const child of entry.children) {
|
|
54
|
+
const childNode = value.nodes[child];
|
|
55
|
+
if (!childNode || childNode.parentId !== id) return false;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
const seen = /* @__PURE__ */ new Set();
|
|
59
|
+
const stack = [value.rootId];
|
|
60
|
+
while (stack.length) {
|
|
61
|
+
const id = stack.pop();
|
|
62
|
+
if (seen.has(id)) return false;
|
|
63
|
+
seen.add(id);
|
|
64
|
+
const entry = value.nodes[id];
|
|
65
|
+
if (!entry) return false;
|
|
66
|
+
for (const child of entry.children) stack.push(child);
|
|
67
|
+
}
|
|
68
|
+
return seen.size === ids.length;
|
|
69
|
+
};
|
|
70
|
+
//#endregion
|
|
71
|
+
//#region core/src/runtime/context.ts
|
|
72
|
+
const contexts = /* @__PURE__ */ new WeakMap();
|
|
73
|
+
const bindContext = (subject, context) => {
|
|
74
|
+
contexts.set(subject, context);
|
|
75
|
+
};
|
|
76
|
+
function contextOf(subject, required = true) {
|
|
77
|
+
const context = contexts.get(subject);
|
|
78
|
+
if (!context && required) throw new Error("Unknown Doxum runtime.");
|
|
79
|
+
return context;
|
|
80
|
+
}
|
|
81
|
+
//#endregion
|
|
82
|
+
Object.defineProperty(exports, "bindContext", {
|
|
83
|
+
enumerable: true,
|
|
84
|
+
get: function() {
|
|
85
|
+
return bindContext;
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
Object.defineProperty(exports, "children", {
|
|
89
|
+
enumerable: true,
|
|
90
|
+
get: function() {
|
|
91
|
+
return children;
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
Object.defineProperty(exports, "contains", {
|
|
95
|
+
enumerable: true,
|
|
96
|
+
get: function() {
|
|
97
|
+
return contains;
|
|
98
|
+
}
|
|
99
|
+
});
|
|
100
|
+
Object.defineProperty(exports, "contextOf", {
|
|
101
|
+
enumerable: true,
|
|
102
|
+
get: function() {
|
|
103
|
+
return contextOf;
|
|
104
|
+
}
|
|
105
|
+
});
|
|
106
|
+
Object.defineProperty(exports, "installOwn", {
|
|
107
|
+
enumerable: true,
|
|
108
|
+
get: function() {
|
|
109
|
+
return installOwn;
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
Object.defineProperty(exports, "is", {
|
|
113
|
+
enumerable: true,
|
|
114
|
+
get: function() {
|
|
115
|
+
return is;
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
Object.defineProperty(exports, "isPlainObject", {
|
|
119
|
+
enumerable: true,
|
|
120
|
+
get: function() {
|
|
121
|
+
return isPlainObject;
|
|
122
|
+
}
|
|
123
|
+
});
|
|
124
|
+
Object.defineProperty(exports, "isRecord", {
|
|
125
|
+
enumerable: true,
|
|
126
|
+
get: function() {
|
|
127
|
+
return isRecord;
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
Object.defineProperty(exports, "parent", {
|
|
131
|
+
enumerable: true,
|
|
132
|
+
get: function() {
|
|
133
|
+
return parent;
|
|
134
|
+
}
|
|
135
|
+
});
|
|
136
|
+
Object.defineProperty(exports, "validNode", {
|
|
137
|
+
enumerable: true,
|
|
138
|
+
get: function() {
|
|
139
|
+
return validNode;
|
|
140
|
+
}
|
|
141
|
+
});
|
|
142
|
+
Object.defineProperty(exports, "validate", {
|
|
143
|
+
enumerable: true,
|
|
144
|
+
get: function() {
|
|
145
|
+
return validate;
|
|
146
|
+
}
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
//# sourceMappingURL=context-BcLKGfq8.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context-BcLKGfq8.cjs","names":[],"sources":["../core/src/value/record.ts","../core/src/tree/topology.ts","../core/src/runtime/context.ts"],"sourcesContent":["export const isPlainObject = (value: unknown): value is Record<string, unknown> => {\n if (value === null || typeof value !== 'object') return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n};\n\nexport const isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\n/** Installs an own data member without invoking inherited setters such as __proto__. */\nexport const installOwn = (\n parent: object,\n key: PropertyKey,\n present: boolean,\n value: unknown\n): void => {\n if (!present) {\n Reflect.deleteProperty(parent, key);\n return;\n }\n if (Object.hasOwn(parent, key)) {\n Reflect.set(parent, key, value);\n return;\n }\n Object.defineProperty(parent, key, {\n value,\n writable: true,\n configurable: true,\n enumerable: true,\n });\n};\n","import { isRecord } from '../value/record';\nexport type MutableTreeNode = { parentId?: string; children: string[]; value?: unknown };\nexport type MutableTree = { rootId?: string; nodes: Record<string, MutableTreeNode> };\nconst node = (tree: MutableTree, id: string) =>\n Object.hasOwn(tree.nodes, id) ? tree.nodes[id] : undefined;\nexport const is = (value: unknown): value is MutableTree =>\n isRecord(value) && isRecord(value.nodes);\n\nexport const validNode = (value: unknown): value is MutableTreeNode => {\n if (!isRecord(value) || !Array.isArray(value.children)) return false;\n if (value.parentId !== undefined && typeof value.parentId !== 'string') return false;\n const children = new Set<string>();\n for (const id of value.children) {\n if (typeof id !== 'string' || children.has(id)) return false;\n children.add(id);\n }\n return true;\n};\n\nexport const contains = (tree: MutableTree, id: string): boolean => Object.hasOwn(tree.nodes, id);\n\nexport const parent = (tree: MutableTree, id: string): string | undefined =>\n node(tree, id)?.parentId;\n\nexport const children = (tree: MutableTree, id: string): readonly string[] | undefined =>\n node(tree, id)?.children;\n\nexport const validate = (value: unknown): value is MutableTree => {\n if (!is(value)) return false;\n const ids = Object.keys(value.nodes);\n if (ids.length === 0) return value.rootId === undefined;\n if (typeof value.rootId !== 'string' || !Object.hasOwn(value.nodes, value.rootId)) return false;\n\n for (const id of ids) {\n const entry = value.nodes[id];\n if (!validNode(entry)) return false;\n if (id === value.rootId) {\n if (entry.parentId !== undefined) return false;\n } else if (entry.parentId === undefined || !Object.hasOwn(value.nodes, entry.parentId))\n return false;\n for (const child of entry.children) {\n const childNode = value.nodes[child];\n if (!childNode || childNode.parentId !== id) return false;\n }\n }\n\n const seen = new Set<string>();\n const stack = [value.rootId];\n while (stack.length) {\n const id = stack.pop() as string;\n if (seen.has(id)) return false;\n seen.add(id);\n const entry = value.nodes[id];\n if (!entry) return false;\n for (const child of entry.children) stack.push(child);\n }\n return seen.size === ids.length;\n};\n\nexport type TreePosition = { readonly parentId?: string; readonly index?: number };\n","import type { Infer, ObjectNode } from '../schema';\nimport type { DocumentRuntime } from './contract';\nimport type { RuntimeWriteDriver } from './driver';\nimport type { NotificationCenter } from './notification';\n\nexport type RuntimeState<TSchema extends ObjectNode> = {\n readonly schema: TSchema;\n document: Infer<TSchema>;\n disposed: boolean;\n projectionLocks: number;\n};\n\nexport type RuntimeContext<TSchema extends ObjectNode> = {\n readonly state: RuntimeState<TSchema>;\n readonly owner: DocumentRuntime<TSchema>;\n readonly notifications: NotificationCenter<TSchema>;\n driver: RuntimeWriteDriver | undefined;\n bypassDepth: number;\n};\n\nconst contexts = new WeakMap<object, RuntimeContext<ObjectNode>>();\n\nexport const bindContext = <TSchema extends ObjectNode>(\n subject: object,\n context: RuntimeContext<TSchema>\n): void => {\n contexts.set(subject, context as RuntimeContext<ObjectNode>);\n};\n\nexport function contextOf<TSchema extends ObjectNode>(\n subject: object,\n required?: true\n): RuntimeContext<TSchema>;\nexport function contextOf<TSchema extends ObjectNode>(\n subject: object,\n required: false\n): RuntimeContext<TSchema> | undefined;\nexport function contextOf<TSchema extends ObjectNode>(\n subject: object,\n required = true\n): RuntimeContext<TSchema> | undefined {\n const context = contexts.get(subject);\n if (!context && required) throw new Error('Unknown Doxum runtime.');\n return context as RuntimeContext<TSchema> | undefined;\n}\n"],"mappings":";AAAA,MAAa,iBAAiB,UAAqD;AACjF,KAAI,UAAU,QAAQ,OAAO,UAAU,SAAU,QAAO;CACxD,MAAM,YAAY,OAAO,eAAe,MAAM;AAC9C,QAAO,cAAc,OAAO,aAAa,cAAc;;AAGzD,MAAa,YAAY,UACvB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,MAAM;;AAGtE,MAAa,cACX,QACA,KACA,SACA,UACS;AACT,KAAI,CAAC,SAAS;AACZ,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CAAE,QAAO;AAC9B,MAAI,OAAO,MAAM;OACX,MAAM,aAAa,KAAA,EAAW,QAAO;aAChC,MAAM,aAAa,KAAA,KAAa,CAAC,OAAO,OAAO,MAAM,OAAO,MAAM,SAAS,CACpF,QAAO;AACT,OAAK,MAAM,SAAS,MAAM,UAAU;GAClC,MAAM,YAAY,MAAM,MAAM;AAC9B,OAAI,CAAC,aAAa,UAAU,aAAa,GAAI,QAAO;;;CAIxD,MAAM,uBAAO,IAAI,KAAa;CAC9B,MAAM,QAAQ,CAAC,MAAM,OAAO;AAC5B,QAAO,MAAM,QAAQ;EACnB,MAAM,KAAK,MAAM,KAAK;AACtB,MAAI,KAAK,IAAI,GAAG,CAAE,QAAO;AACzB,OAAK,IAAI,GAAG;EACZ,MAAM,QAAQ,MAAM,MAAM;AAC1B,MAAI,CAAC,MAAO,QAAO;AACnB,OAAK,MAAM,SAAS,MAAM,SAAU,OAAM,KAAK,MAAM;;AAEvD,QAAO,KAAK,SAAS,IAAI;;;;ACpC3B,MAAM,2BAAW,IAAI,SAA6C;AAElE,MAAa,eACX,SACA,YACS;AACT,UAAS,IAAI,SAAS,QAAsC;;AAW9D,SAAgB,UACd,SACA,WAAW,MAC0B;CACrC,MAAM,UAAU,SAAS,IAAI,QAAQ;AACrC,KAAI,CAAC,WAAW,SAAU,OAAM,IAAI,MAAM,yBAAyB;AACnE,QAAO"}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
//#region core/src/value/record.ts
|
|
2
|
+
const isPlainObject = (value) => {
|
|
3
|
+
if (value === null || typeof value !== "object") return false;
|
|
4
|
+
const prototype = Object.getPrototypeOf(value);
|
|
5
|
+
return prototype === Object.prototype || prototype === null;
|
|
6
|
+
};
|
|
7
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
8
|
+
/** Installs an own data member without invoking inherited setters such as __proto__. */
|
|
9
|
+
const installOwn = (parent, key, present, value) => {
|
|
10
|
+
if (!present) {
|
|
11
|
+
Reflect.deleteProperty(parent, key);
|
|
12
|
+
return;
|
|
13
|
+
}
|
|
14
|
+
if (Object.hasOwn(parent, key)) {
|
|
15
|
+
Reflect.set(parent, key, value);
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
Object.defineProperty(parent, key, {
|
|
19
|
+
value,
|
|
20
|
+
writable: true,
|
|
21
|
+
configurable: true,
|
|
22
|
+
enumerable: true
|
|
23
|
+
});
|
|
24
|
+
};
|
|
25
|
+
//#endregion
|
|
26
|
+
//#region core/src/tree/topology.ts
|
|
27
|
+
const node = (tree, id) => Object.hasOwn(tree.nodes, id) ? tree.nodes[id] : void 0;
|
|
28
|
+
const is = (value) => isRecord(value) && isRecord(value.nodes);
|
|
29
|
+
const validNode = (value) => {
|
|
30
|
+
if (!isRecord(value) || !Array.isArray(value.children)) return false;
|
|
31
|
+
if (value.parentId !== void 0 && typeof value.parentId !== "string") return false;
|
|
32
|
+
const children = /* @__PURE__ */ new Set();
|
|
33
|
+
for (const id of value.children) {
|
|
34
|
+
if (typeof id !== "string" || children.has(id)) return false;
|
|
35
|
+
children.add(id);
|
|
36
|
+
}
|
|
37
|
+
return true;
|
|
38
|
+
};
|
|
39
|
+
const contains = (tree, id) => Object.hasOwn(tree.nodes, id);
|
|
40
|
+
const parent = (tree, id) => node(tree, id)?.parentId;
|
|
41
|
+
const children = (tree, id) => node(tree, id)?.children;
|
|
42
|
+
const validate = (value) => {
|
|
43
|
+
if (!is(value)) return false;
|
|
44
|
+
const ids = Object.keys(value.nodes);
|
|
45
|
+
if (ids.length === 0) return value.rootId === void 0;
|
|
46
|
+
if (typeof value.rootId !== "string" || !Object.hasOwn(value.nodes, value.rootId)) return false;
|
|
47
|
+
for (const id of ids) {
|
|
48
|
+
const entry = value.nodes[id];
|
|
49
|
+
if (!validNode(entry)) return false;
|
|
50
|
+
if (id === value.rootId) {
|
|
51
|
+
if (entry.parentId !== void 0) return false;
|
|
52
|
+
} else if (entry.parentId === void 0 || !Object.hasOwn(value.nodes, entry.parentId)) return false;
|
|
53
|
+
for (const child of entry.children) {
|
|
54
|
+
const childNode = value.nodes[child];
|
|
55
|
+
if (!childNode || childNode.parentId !== id) return false;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
const seen = /* @__PURE__ */ new Set();
|
|
59
|
+
const stack = [value.rootId];
|
|
60
|
+
while (stack.length) {
|
|
61
|
+
const id = stack.pop();
|
|
62
|
+
if (seen.has(id)) return false;
|
|
63
|
+
seen.add(id);
|
|
64
|
+
const entry = value.nodes[id];
|
|
65
|
+
if (!entry) return false;
|
|
66
|
+
for (const child of entry.children) stack.push(child);
|
|
67
|
+
}
|
|
68
|
+
return seen.size === ids.length;
|
|
69
|
+
};
|
|
70
|
+
//#endregion
|
|
71
|
+
//#region core/src/runtime/context.ts
|
|
72
|
+
const contexts = /* @__PURE__ */ new WeakMap();
|
|
73
|
+
const bindContext = (subject, context) => {
|
|
74
|
+
contexts.set(subject, context);
|
|
75
|
+
};
|
|
76
|
+
function contextOf(subject, required = true) {
|
|
77
|
+
const context = contexts.get(subject);
|
|
78
|
+
if (!context && required) throw new Error("Unknown Doxum runtime.");
|
|
79
|
+
return context;
|
|
80
|
+
}
|
|
81
|
+
//#endregion
|
|
82
|
+
export { is as a, validate as c, isRecord as d, contains as i, installOwn as l, contextOf as n, parent as o, children as r, validNode as s, bindContext as t, isPlainObject as u };
|
|
83
|
+
|
|
84
|
+
//# sourceMappingURL=context-DFEaDUv5.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context-DFEaDUv5.js","names":[],"sources":["../core/src/value/record.ts","../core/src/tree/topology.ts","../core/src/runtime/context.ts"],"sourcesContent":["export const isPlainObject = (value: unknown): value is Record<string, unknown> => {\n if (value === null || typeof value !== 'object') return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n};\n\nexport const isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\n/** Installs an own data member without invoking inherited setters such as __proto__. */\nexport const installOwn = (\n parent: object,\n key: PropertyKey,\n present: boolean,\n value: unknown\n): void => {\n if (!present) {\n Reflect.deleteProperty(parent, key);\n return;\n }\n if (Object.hasOwn(parent, key)) {\n Reflect.set(parent, key, value);\n return;\n }\n Object.defineProperty(parent, key, {\n value,\n writable: true,\n configurable: true,\n enumerable: true,\n });\n};\n","import { isRecord } from '../value/record';\nexport type MutableTreeNode = { parentId?: string; children: string[]; value?: unknown };\nexport type MutableTree = { rootId?: string; nodes: Record<string, MutableTreeNode> };\nconst node = (tree: MutableTree, id: string) =>\n Object.hasOwn(tree.nodes, id) ? tree.nodes[id] : undefined;\nexport const is = (value: unknown): value is MutableTree =>\n isRecord(value) && isRecord(value.nodes);\n\nexport const validNode = (value: unknown): value is MutableTreeNode => {\n if (!isRecord(value) || !Array.isArray(value.children)) return false;\n if (value.parentId !== undefined && typeof value.parentId !== 'string') return false;\n const children = new Set<string>();\n for (const id of value.children) {\n if (typeof id !== 'string' || children.has(id)) return false;\n children.add(id);\n }\n return true;\n};\n\nexport const contains = (tree: MutableTree, id: string): boolean => Object.hasOwn(tree.nodes, id);\n\nexport const parent = (tree: MutableTree, id: string): string | undefined =>\n node(tree, id)?.parentId;\n\nexport const children = (tree: MutableTree, id: string): readonly string[] | undefined =>\n node(tree, id)?.children;\n\nexport const validate = (value: unknown): value is MutableTree => {\n if (!is(value)) return false;\n const ids = Object.keys(value.nodes);\n if (ids.length === 0) return value.rootId === undefined;\n if (typeof value.rootId !== 'string' || !Object.hasOwn(value.nodes, value.rootId)) return false;\n\n for (const id of ids) {\n const entry = value.nodes[id];\n if (!validNode(entry)) return false;\n if (id === value.rootId) {\n if (entry.parentId !== undefined) return false;\n } else if (entry.parentId === undefined || !Object.hasOwn(value.nodes, entry.parentId))\n return false;\n for (const child of entry.children) {\n const childNode = value.nodes[child];\n if (!childNode || childNode.parentId !== id) return false;\n }\n }\n\n const seen = new Set<string>();\n const stack = [value.rootId];\n while (stack.length) {\n const id = stack.pop() as string;\n if (seen.has(id)) return false;\n seen.add(id);\n const entry = value.nodes[id];\n if (!entry) return false;\n for (const child of entry.children) stack.push(child);\n }\n return seen.size === ids.length;\n};\n\nexport type TreePosition = { readonly parentId?: string; readonly index?: number };\n","import type { Infer, ObjectNode } from '../schema';\nimport type { DocumentRuntime } from './contract';\nimport type { RuntimeWriteDriver } from './driver';\nimport type { NotificationCenter } from './notification';\n\nexport type RuntimeState<TSchema extends ObjectNode> = {\n readonly schema: TSchema;\n document: Infer<TSchema>;\n disposed: boolean;\n projectionLocks: number;\n};\n\nexport type RuntimeContext<TSchema extends ObjectNode> = {\n readonly state: RuntimeState<TSchema>;\n readonly owner: DocumentRuntime<TSchema>;\n readonly notifications: NotificationCenter<TSchema>;\n driver: RuntimeWriteDriver | undefined;\n bypassDepth: number;\n};\n\nconst contexts = new WeakMap<object, RuntimeContext<ObjectNode>>();\n\nexport const bindContext = <TSchema extends ObjectNode>(\n subject: object,\n context: RuntimeContext<TSchema>\n): void => {\n contexts.set(subject, context as RuntimeContext<ObjectNode>);\n};\n\nexport function contextOf<TSchema extends ObjectNode>(\n subject: object,\n required?: true\n): RuntimeContext<TSchema>;\nexport function contextOf<TSchema extends ObjectNode>(\n subject: object,\n required: false\n): RuntimeContext<TSchema> | undefined;\nexport function contextOf<TSchema extends ObjectNode>(\n subject: object,\n required = true\n): RuntimeContext<TSchema> | undefined {\n const context = contexts.get(subject);\n if (!context && required) throw new Error('Unknown Doxum runtime.');\n return context as RuntimeContext<TSchema> | undefined;\n}\n"],"mappings":";AAAA,MAAa,iBAAiB,UAAqD;AACjF,KAAI,UAAU,QAAQ,OAAO,UAAU,SAAU,QAAO;CACxD,MAAM,YAAY,OAAO,eAAe,MAAM;AAC9C,QAAO,cAAc,OAAO,aAAa,cAAc;;AAGzD,MAAa,YAAY,UACvB,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,MAAM;;AAGtE,MAAa,cACX,QACA,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