doxum 0.1.35 → 0.1.37
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 +7 -0
- package/dist/advanced.cjs +0 -2
- package/dist/advanced.d.cts +1 -2
- package/dist/advanced.d.ts +1 -2
- package/dist/advanced.js +0 -2
- package/dist/contract-CNR6BS75.d.cts +1 -2
- package/dist/contract-COgxO5sv.d.ts +1 -2
- package/dist/dependency-Cbf3C8eJ.d.cts +1 -2
- package/dist/dependency-DzxXGYe1.d.ts +1 -2
- package/dist/driver-B7RR-VfX.js +0 -2
- package/dist/driver-CN3dGxQI.cjs +0 -2
- package/dist/index.cjs +0 -2
- package/dist/index.d.cts +2 -3
- package/dist/index.d.ts +2 -3
- package/dist/index.js +0 -2
- package/dist/local-sync.cjs +0 -2
- package/dist/local-sync.d.cts +1 -2
- package/dist/local-sync.d.ts +1 -2
- package/dist/local-sync.js +0 -2
- package/dist/react.cjs +0 -2
- package/dist/react.d.cts +1 -2
- package/dist/react.d.ts +1 -2
- package/dist/react.js +0 -2
- package/dist/record-B2yRhYsc.js +0 -2
- package/dist/record-ChYUi8PP.cjs +0 -2
- package/dist/transform-3mj0eStL.js +0 -2
- package/dist/transform-D45KWMzj.cjs +0 -2
- package/package.json +8 -3
- package/skills/doxum-runtime/references/projections.md +2 -0
- package/skills/doxum-runtime/references/public-api.md +1 -0
- package/dist/advanced.cjs.map +0 -1
- package/dist/advanced.js.map +0 -1
- package/dist/driver-B7RR-VfX.js.map +0 -1
- package/dist/driver-CN3dGxQI.cjs.map +0 -1
- package/dist/index.cjs.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/local-sync.cjs.map +0 -1
- package/dist/local-sync.js.map +0 -1
- package/dist/react.cjs.map +0 -1
- package/dist/react.js.map +0 -1
- package/dist/record-B2yRhYsc.js.map +0 -1
- package/dist/record-ChYUi8PP.cjs.map +0 -1
- package/dist/transform-3mj0eStL.js.map +0 -1
- package/dist/transform-D45KWMzj.cjs.map +0 -1
package/dist/local-sync.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"local-sync.cjs","names":["isPlainObject","positiveInteger","isRecord","installRuntimeWriteDriver"],"sources":["../core/src/local-sync/error.ts","../core/src/local-sync/json.ts","../core/src/local-sync/timeline.ts","../core/src/local-sync/session.ts"],"sourcesContent":["export type LocalSyncErrorCode =\n | 'unavailable'\n | 'schema-mismatch'\n | 'consistency'\n | 'read-only'\n | 'unsupported-operation'\n | 'disposed'\n | 'invalid-data';\n\nexport class LocalSyncError extends Error {\n readonly code: LocalSyncErrorCode;\n\n constructor(code: LocalSyncErrorCode, message: string, options?: { readonly cause?: unknown }) {\n super(message, options);\n this.name = 'LocalSyncError';\n this.code = code;\n }\n}\n\nexport const normalizeLocalSyncError = (\n error: unknown,\n code: LocalSyncErrorCode,\n message: string\n): LocalSyncError =>\n error instanceof LocalSyncError ? error : new LocalSyncError(code, message, { cause: error });\n","import { isPlainObject } from '@/value/record';\nimport * as changeSet from '@/mutation/changes';\nimport type { ChangeSet } from '@/changes';\nimport { LocalSyncError } from './error';\n\nexport type JsonPrimitive = null | boolean | number | string;\nexport type JsonValue =\n JsonPrimitive | readonly JsonValue[] | { readonly [key: string]: JsonValue };\n\nexport type JsonChangeLimits = {\n readonly maxChanges?: number;\n readonly maxBytes?: number;\n readonly maxDepth?: number;\n readonly maxStringLength?: number;\n};\n\ntype ResolvedJsonLimits = {\n readonly maxChanges: number;\n readonly maxBytes: number;\n readonly maxDepth: number;\n readonly maxStringLength: number;\n};\n\nexport const defaultJsonChangeLimits: Readonly<ResolvedJsonLimits> = Object.freeze({\n maxChanges: 1_000,\n maxBytes: 1_000_000,\n maxDepth: 64,\n maxStringLength: 256_000,\n});\n\nconst describePath = (path: readonly string[]): string =>\n path.length === 0 ? 'value' : path.join('.');\n\nconst limit = (value: number | undefined, fallback: number, label: string): number => {\n if (value === undefined) return fallback;\n if (Number.isSafeInteger(value) && value > 0) return value;\n throw new TypeError(`${label} must be a positive safe integer.`);\n};\n\nconst resolveLimits = (input: JsonChangeLimits | undefined): ResolvedJsonLimits => ({\n maxChanges: limit(input?.maxChanges, defaultJsonChangeLimits.maxChanges, 'maxChanges'),\n maxBytes: limit(input?.maxBytes, defaultJsonChangeLimits.maxBytes, 'maxBytes'),\n maxDepth: limit(input?.maxDepth, defaultJsonChangeLimits.maxDepth, 'maxDepth'),\n maxStringLength: limit(\n input?.maxStringLength,\n defaultJsonChangeLimits.maxStringLength,\n 'maxStringLength'\n ),\n});\n\nconst validate = (\n value: unknown,\n path: string[],\n limits: ResolvedJsonLimits | undefined,\n depth: number,\n ancestors: WeakSet<object>\n): JsonValue => {\n if (limits && depth > limits.maxDepth)\n throw new LocalSyncError(\n 'invalid-data',\n `${describePath(path)} exceeds the maximum JSON depth.`\n );\n if (value === null || typeof value === 'boolean') return value;\n if (typeof value === 'string') {\n if (!limits || value.length <= limits.maxStringLength) return value;\n throw new LocalSyncError(\n 'invalid-data',\n `${describePath(path)} exceeds the maximum string length.`\n );\n }\n if (typeof value === 'number') {\n if (Number.isFinite(value)) return value;\n throw new LocalSyncError('invalid-data', `${describePath(path)} contains a non-finite number.`);\n }\n if (Array.isArray(value)) {\n if (ancestors.has(value))\n throw new LocalSyncError('invalid-data', `${describePath(path)} contains a cycle.`);\n ancestors.add(value);\n try {\n for (let index = 0; index < value.length; index += 1) {\n path.push(String(index));\n validate(value[index], path, limits, depth + 1, ancestors);\n path.pop();\n }\n } finally {\n ancestors.delete(value);\n }\n return value as readonly JsonValue[];\n }\n if (isPlainObject(value)) {\n if (ancestors.has(value))\n throw new LocalSyncError('invalid-data', `${describePath(path)} contains a cycle.`);\n ancestors.add(value);\n try {\n for (const key of Object.keys(value)) {\n path.push(key);\n validate(value[key], path, limits, depth + 1, ancestors);\n path.pop();\n }\n } finally {\n ancestors.delete(value);\n }\n return value as { readonly [key: string]: JsonValue };\n }\n throw new LocalSyncError('invalid-data', `${describePath(path)} must be JSON data.`);\n};\n\nexport const json = (value: unknown, label: string): JsonValue =>\n validate(value, [label], undefined, 0, new WeakSet());\n\nexport const jsonChanges = (value: unknown, label: string, input?: JsonChangeLimits): ChangeSet => {\n const limits = input === undefined ? undefined : resolveLimits(input);\n let changes: ChangeSet;\n try {\n changes = changeSet.decodeChanges(value);\n } catch {\n throw new LocalSyncError('invalid-data', `${label} contains an invalid ChangeSet.`);\n }\n if (limits && changeSet.changeCount(changes) > limits.maxChanges)\n throw new LocalSyncError('invalid-data', `${label} exceeds the maximum change count.`);\n validate(changes.changes, [label], limits, 0, new WeakSet());\n if (limits) {\n const serialized = JSON.stringify(changes.changes);\n if (new TextEncoder().encode(serialized).byteLength > limits.maxBytes)\n throw new LocalSyncError('invalid-data', `${label} exceeds the maximum ChangeSet size.`);\n }\n return changes;\n};\n","import { LocalSyncError, normalizeLocalSyncError } from './error';\nimport { json, jsonChanges, type JsonValue } from './json';\nimport type { ChangeSet } from '@/changes';\nimport { isRecord } from '@/value/record';\n\nconst DATABASE_VERSION = 5;\nconst FORMAT_VERSION = 3;\nconst DOCUMENTS = 'documents';\nconst COMMITS = 'commits';\n\nexport type StoredDocument = {\n readonly formatVersion: number;\n readonly documentId: string;\n readonly schemaVersion: number;\n readonly checkpointSeq: number;\n readonly headSeq: number;\n readonly checkpoint: JsonValue;\n};\n\nexport type StoredCommit = {\n readonly formatVersion: number;\n readonly documentId: string;\n readonly seq: number;\n readonly changes: ChangeSet;\n readonly createdAt: number;\n};\n\nconst request = <T>(value: IDBRequest<T>): Promise<T> =>\n new Promise((resolve, reject) => {\n value.onsuccess = () => resolve(value.result);\n value.onerror = () =>\n reject(normalizeLocalSyncError(value.error, 'unavailable', 'IndexedDB request failed.'));\n });\n\nconst complete = (transaction: IDBTransaction): Promise<void> =>\n new Promise((resolve, reject) => {\n transaction.oncomplete = () => resolve();\n transaction.onabort = () =>\n reject(\n normalizeLocalSyncError(\n transaction.error,\n 'unavailable',\n 'IndexedDB transaction was aborted.'\n )\n );\n transaction.onerror = () =>\n reject(\n normalizeLocalSyncError(transaction.error, 'unavailable', 'IndexedDB transaction failed.')\n );\n });\n\nconst factory = (): IDBFactory => {\n if (!globalThis.indexedDB)\n throw new LocalSyncError(\n 'unavailable',\n 'IndexedDB is required by doxum/local-sync in this environment.'\n );\n return globalThis.indexedDB;\n};\n\nconst keyRange = (): typeof IDBKeyRange => {\n if (!globalThis.IDBKeyRange)\n throw new LocalSyncError(\n 'unavailable',\n 'IndexedDB is required by doxum/local-sync in this environment.'\n );\n return globalThis.IDBKeyRange;\n};\n\nconst string = (value: unknown, label: string): string => {\n if (typeof value === 'string') return value;\n throw new LocalSyncError('consistency', `${label} is malformed in IndexedDB.`);\n};\n\nconst nonNegativeInteger = (value: unknown, label: string): number => {\n if (typeof value === 'number' && Number.isSafeInteger(value) && value >= 0) return value;\n throw new LocalSyncError('consistency', `${label} is malformed in IndexedDB.`);\n};\n\nconst positiveInteger = (value: unknown, label: string): number => {\n const parsed = nonNegativeInteger(value, label);\n if (parsed > 0) return parsed;\n throw new LocalSyncError('consistency', `${label} is malformed in IndexedDB.`);\n};\n\nconst documentRecord = (value: unknown): StoredDocument => {\n if (!isRecord(value) || value.formatVersion !== FORMAT_VERSION)\n throw new LocalSyncError('consistency', 'Document record is malformed in IndexedDB.');\n const checkpointSeq = nonNegativeInteger(value.checkpointSeq, 'document.checkpointSeq');\n const headSeq = nonNegativeInteger(value.headSeq, 'document.headSeq');\n if (checkpointSeq > headSeq)\n throw new LocalSyncError('consistency', 'Document checkpoint exceeds its head sequence.');\n return Object.freeze({\n formatVersion: FORMAT_VERSION,\n documentId: string(value.documentId, 'document.documentId'),\n schemaVersion: positiveInteger(value.schemaVersion, 'document.schemaVersion'),\n checkpointSeq,\n headSeq,\n checkpoint: json(value.checkpoint, 'document.checkpoint'),\n });\n};\n\nconst commitRecord = (value: unknown): StoredCommit => {\n if (!isRecord(value) || value.formatVersion !== FORMAT_VERSION)\n throw new LocalSyncError('consistency', 'Commit record is malformed in IndexedDB.');\n return Object.freeze({\n formatVersion: FORMAT_VERSION,\n documentId: string(value.documentId, 'commit.documentId'),\n seq: positiveInteger(value.seq, 'commit.seq'),\n changes: jsonChanges({ changes: value.changes }, 'commit.changes'),\n createdAt: nonNegativeInteger(value.createdAt, 'commit.createdAt'),\n });\n};\n\nexport type IndexedDbTimeline = {\n readonly initialize: (\n documentId: string,\n schemaVersion: number,\n checkpoint: JsonValue\n ) => Promise<StoredDocument>;\n readonly read: (documentId: string) => Promise<StoredDocument>;\n readonly tail: (documentId: string, afterSeq: number) => Promise<readonly StoredCommit[]>;\n readonly append: (input: {\n readonly documentId: string;\n readonly expectedHeadSeq: number;\n readonly changes: ChangeSet;\n }) => Promise<StoredCommit>;\n readonly close: () => void;\n};\n\nexport const openIndexedDbTimeline = async (databaseName: string): Promise<IndexedDbTimeline> => {\n const database = await new Promise<IDBDatabase>((resolve, reject) => {\n let incompatible = false;\n const open = factory().open(databaseName, DATABASE_VERSION);\n open.onerror = () =>\n reject(\n incompatible\n ? new LocalSyncError(\n 'consistency',\n 'Unsupported Doxum storage format. Existing data was left unchanged.'\n )\n : (open.error ?? new Error('Unable to open IndexedDB.'))\n );\n open.onblocked = () => reject(new Error(`IndexedDB database '${databaseName}' is blocked.`));\n open.onupgradeneeded = event => {\n if (event.oldVersion !== 0) {\n incompatible = true;\n open.transaction?.abort();\n return;\n }\n const db = open.result;\n if (!db.objectStoreNames.contains(DOCUMENTS))\n db.createObjectStore(DOCUMENTS, { keyPath: 'documentId' });\n if (!db.objectStoreNames.contains(COMMITS))\n db.createObjectStore(COMMITS, { keyPath: ['documentId', 'seq'] });\n };\n open.onsuccess = () => resolve(open.result);\n });\n\n const readDocument = async (\n transaction: IDBTransaction,\n documentId: string\n ): Promise<StoredDocument> => {\n const value = await request(transaction.objectStore(DOCUMENTS).get(documentId));\n if (value === undefined)\n throw new LocalSyncError('consistency', `Local document '${documentId}' does not exist.`);\n return documentRecord(value);\n };\n\n return {\n initialize: async (documentId, schemaVersion, checkpoint) => {\n const transaction = database.transaction(DOCUMENTS, 'readwrite');\n const store = transaction.objectStore(DOCUMENTS);\n const existing = await request(store.get(documentId));\n if (existing !== undefined) {\n const record = documentRecord(existing);\n if (record.schemaVersion !== schemaVersion)\n throw new LocalSyncError(\n 'schema-mismatch',\n `Local document '${documentId}' uses schema version ${record.schemaVersion}, but version ${schemaVersion} was requested.`\n );\n await complete(transaction);\n return record;\n }\n const record: StoredDocument = {\n formatVersion: FORMAT_VERSION,\n documentId,\n schemaVersion,\n checkpointSeq: 0,\n headSeq: 0,\n checkpoint,\n };\n store.put(record);\n await complete(transaction);\n return Object.freeze(record);\n },\n read: async documentId => {\n const transaction = database.transaction(DOCUMENTS, 'readonly');\n const record = await readDocument(transaction, documentId);\n await complete(transaction);\n return record;\n },\n tail: async (documentId, afterSeq) => {\n const transaction = database.transaction(COMMITS, 'readonly');\n const range = keyRange().bound(\n [documentId, afterSeq + 1],\n [documentId, Number.MAX_SAFE_INTEGER]\n );\n const values = await request(transaction.objectStore(COMMITS).getAll(range));\n await complete(transaction);\n return Object.freeze(values.map(commitRecord).sort((left, right) => left.seq - right.seq));\n },\n append: async input => {\n const transaction = database.transaction([DOCUMENTS, COMMITS], 'readwrite');\n const documents = transaction.objectStore(DOCUMENTS);\n const current = await readDocument(transaction, input.documentId);\n if (current.headSeq !== input.expectedHeadSeq)\n throw new LocalSyncError(\n 'consistency',\n 'Local document advanced before the leader could append its commit.'\n );\n const commit: StoredCommit = {\n formatVersion: FORMAT_VERSION,\n documentId: input.documentId,\n seq: current.headSeq + 1,\n changes: input.changes,\n createdAt: Date.now(),\n };\n documents.put({ ...current, headSeq: commit.seq });\n transaction.objectStore(COMMITS).put({ ...commit, changes: commit.changes.changes });\n await complete(transaction);\n return Object.freeze(commit);\n },\n close: () => database.close(),\n };\n};\n","import {\n installRuntimeWriteDriver,\n type RuntimeWriteDriverLease,\n type RuntimeWriteIntent,\n} from '@/runtime/driver';\nimport type { DocumentCommit } from '@/runtime/contract';\nimport type { Infer, ObjectSchema } from '@/schema/model';\nimport { type AttachLocalSyncOptions, type LocalSync, type LocalSyncState } from './contract';\nimport { LocalSyncError, normalizeLocalSyncError } from './error';\nimport { json, jsonChanges } from './json';\nimport type { ChangeSet } from '@/changes';\nimport { openIndexedDbTimeline, type StoredCommit } from './timeline';\n\ntype LockOptions = {\n readonly mode: 'exclusive';\n readonly ifAvailable?: boolean;\n};\n\ntype LockManager = {\n readonly request: <TResult>(\n name: string,\n options: LockOptions,\n callback: (lock: unknown | null) => TResult | PromiseLike<TResult>\n ) => Promise<TResult>;\n};\n\ntype Channel = {\n onmessage: ((event: MessageEvent<unknown>) => void) | null;\n postMessage(message: unknown): void;\n close(): void;\n};\n\ntype ChannelConstructor = new (name: string) => Channel;\n\ntype CommitNotification = {\n readonly kind: 'commit';\n readonly documentId: string;\n readonly headSeq: number;\n};\n\nconst locks = (): LockManager => {\n const value: unknown = globalThis.navigator?.locks;\n if (\n typeof value !== 'object' ||\n value === null ||\n !('request' in value) ||\n typeof value.request !== 'function'\n )\n throw new LocalSyncError(\n 'unavailable',\n 'Web Locks is required by doxum/local-sync in this environment.'\n );\n return value as LockManager;\n};\n\nconst channelConstructor = (): ChannelConstructor => {\n const value: unknown = globalThis.BroadcastChannel;\n if (typeof value !== 'function')\n throw new LocalSyncError(\n 'unavailable',\n 'BroadcastChannel is required by doxum/local-sync in this environment.'\n );\n return value as ChannelConstructor;\n};\n\nconst requiredString = (value: string, label: string): string => {\n if (value.length > 0) return value;\n throw new TypeError(`${label} must not be empty.`);\n};\n\nconst positiveInteger = (value: number, label: string): number => {\n if (Number.isSafeInteger(value) && value > 0) return value;\n throw new TypeError(`${label} must be a positive safe integer.`);\n};\n\nconst notification = (value: unknown): CommitNotification | undefined => {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined;\n const record = value as Record<string, unknown>;\n if (\n record.kind !== 'commit' ||\n typeof record.documentId !== 'string' ||\n typeof record.headSeq !== 'number' ||\n !Number.isSafeInteger(record.headSeq) ||\n record.headSeq < 0\n )\n return undefined;\n return record as CommitNotification;\n};\n\nexport const attachLocalSync = async <TSchema extends ObjectSchema<object>>(\n input: AttachLocalSyncOptions<TSchema>\n): Promise<LocalSync> => {\n const runtime = input.runtime;\n const databaseName = requiredString(input.database, 'database');\n const documentId = requiredString(input.documentId, 'documentId');\n const schemaVersion = positiveInteger(input.schemaVersion ?? 1, 'schemaVersion');\n const lockManager = locks();\n const BroadcastChannel = channelConstructor();\n const timeline = await openIndexedDbTimeline(databaseName).catch(error => {\n throw normalizeLocalSyncError(error, 'unavailable', 'Unable to open local sync storage.');\n });\n\n let channel: Channel | undefined;\n let unsubscribe: (() => void) | undefined;\n let driver: RuntimeWriteDriverLease | undefined;\n try {\n const stored = await timeline.initialize(\n documentId,\n schemaVersion,\n json(runtime.snapshot(), 'runtime snapshot')\n );\n let headSeq = stored.checkpointSeq;\n let checkpointSeq = stored.checkpointSeq;\n let role: 'leader' | 'follower' = 'follower';\n let fault: LocalSyncError | undefined;\n let closing = false;\n let disposed = false;\n let releaseLeadership: (() => void) | undefined;\n let leadershipLease: Promise<void> | undefined;\n let queued: Promise<void> = Promise.resolve();\n let snapshot: LocalSyncState = Object.freeze({ status: role, headSeq, checkpointSeq });\n let stateRevision = 0;\n const stateListeners = new Set<() => void>();\n const publishState = (): void => {\n const next: LocalSyncState = disposed\n ? { status: 'disposed' }\n : fault\n ? { status: 'error', headSeq, checkpointSeq, error: fault }\n : { status: role, headSeq, checkpointSeq };\n if (\n snapshot.status === next.status &&\n (snapshot.status === 'disposed' ||\n (next.status !== 'disposed' &&\n snapshot.headSeq === next.headSeq &&\n snapshot.checkpointSeq === next.checkpointSeq &&\n (snapshot.status !== 'error' ||\n (next.status === 'error' && snapshot.error === next.error))))\n )\n return;\n snapshot = Object.freeze(next);\n stateRevision++;\n for (const listener of [...stateListeners]) {\n if (!stateListeners.has(listener)) continue;\n try {\n listener();\n } catch {\n // Consumer state listeners are isolated from synchronization state.\n }\n }\n };\n\n const fail = (error: unknown): LocalSyncError => {\n const failure = normalizeLocalSyncError(\n error,\n 'unavailable',\n 'Local synchronization failed.'\n );\n if (fault || disposed) return fault ?? failure;\n fault = failure;\n publishState();\n try {\n input.onError?.(failure);\n } catch {\n // Error reporting cannot repair or replace the original synchronization failure.\n }\n return failure;\n };\n\n const assertOpen = (): void => {\n if (closing || disposed)\n throw new LocalSyncError('disposed', 'Local sync has been disposed.');\n if (fault) throw fault;\n };\n\n const assertLeader = (intent: RuntimeWriteIntent): void => {\n assertOpen();\n if (role !== 'leader')\n throw new LocalSyncError(\n 'read-only',\n 'This tab is following the local document and cannot write until it becomes the leader.'\n );\n if (intent.kind === 'replace' || (intent.kind === 'apply' && intent.source === 'remote'))\n throw new LocalSyncError(\n 'unsupported-operation',\n 'Local sync appends committed changes. runtime.replace() and externally supplied remote changes are unavailable while it is attached.'\n );\n };\n\n const runRuntime = <TResult>(run: () => TResult): TResult => driver?.run(run) ?? run();\n const replayRuntime = <TResult>(run: () => TResult, message: string): TResult => {\n try {\n return runRuntime(run);\n } catch (error) {\n throw normalizeLocalSyncError(error, 'consistency', message);\n }\n };\n\n const applyStored = (commit: StoredCommit): void => {\n if (commit.seq !== headSeq + 1)\n throw new LocalSyncError('consistency', 'Local commit log contains a sequence gap.');\n const result = replayRuntime(\n () =>\n runtime.apply(commit.changes, {\n expectedRevision: runtime.revision(),\n source: 'remote',\n }),\n 'A stored local ChangeSet could not be replayed.'\n );\n if (result.status !== 'committed')\n throw new LocalSyncError('consistency', 'A stored local ChangeSet could not be applied.');\n headSeq = commit.seq;\n };\n\n const restore = async (reset = false): Promise<void> => {\n const current = await timeline.read(documentId);\n if (current.schemaVersion !== schemaVersion)\n throw new LocalSyncError(\n 'consistency',\n 'Local document schema changed while this attachment was open.'\n );\n if (headSeq > current.headSeq)\n throw new LocalSyncError('consistency', 'The local timeline moved behind this attachment.');\n if (reset || headSeq < current.checkpointSeq) {\n const result = replayRuntime(\n () => runtime.replace(current.checkpoint as Infer<TSchema>, { source: 'remote' }),\n 'The local checkpoint could not be restored.'\n );\n if (result.status === 'rejected')\n throw new LocalSyncError('consistency', 'The local checkpoint could not be restored.');\n headSeq = current.checkpointSeq;\n }\n const tail = await timeline.tail(documentId, headSeq);\n for (const commit of tail) applyStored(commit);\n if (headSeq !== current.headSeq)\n throw new LocalSyncError(\n 'consistency',\n 'Local commit log does not reach its recorded head sequence.'\n );\n checkpointSeq = current.checkpointSeq;\n publishState();\n };\n\n const enqueue = (run: () => Promise<void>): Promise<void> => {\n const next = queued.then(run, run);\n queued = next.then(\n () => undefined,\n error => {\n fail(error);\n }\n );\n return next;\n };\n\n const persist = async (changes: ChangeSet): Promise<void> => {\n const storedCommit = await timeline.append({\n documentId,\n expectedHeadSeq: headSeq,\n changes,\n });\n if (storedCommit.seq !== headSeq + 1)\n throw new LocalSyncError(\n 'consistency',\n 'A local commit was assigned an unexpected sequence.'\n );\n headSeq = storedCommit.seq;\n publishState();\n channel?.postMessage({\n kind: 'commit',\n documentId,\n headSeq,\n } satisfies CommitNotification);\n };\n\n const record = (commit: DocumentCommit<TSchema>): void => {\n try {\n const changes = jsonChanges(\n commit.changes,\n 'local commit changes',\n input.changeLimits ?? {}\n );\n void enqueue(() => persist(changes)).catch(() => undefined);\n } catch (error) {\n fail(error);\n }\n };\n\n const holdLeadership = (): Promise<void> =>\n new Promise(resolve => {\n releaseLeadership = resolve;\n });\n\n const lead = async (activated?: () => void): Promise<void> => {\n if (closing || disposed || fault) return;\n await restore();\n if (closing || disposed || fault) return;\n role = 'leader';\n publishState();\n activated?.();\n try {\n await holdLeadership();\n } finally {\n releaseLeadership = undefined;\n if (!closing && !disposed && !fault) {\n role = 'follower';\n publishState();\n }\n }\n };\n\n const watchLeadership = (): void => {\n leadershipLease = lockManager\n .request(`doxum:${documentId}`, { mode: 'exclusive' }, async () => {\n try {\n await lead();\n } catch (error) {\n fail(error);\n }\n })\n .catch(error => {\n if (!closing && !disposed) fail(error);\n });\n };\n\n const claimInitialLeadership = async (): Promise<void> => {\n let resolve!: (value: boolean) => void;\n const claimed = new Promise<boolean>(done => {\n resolve = done;\n });\n leadershipLease = lockManager\n .request(`doxum:${documentId}`, { mode: 'exclusive', ifAvailable: true }, async lock => {\n if (lock === null) {\n resolve(false);\n return;\n }\n try {\n await lead(() => resolve(true));\n } catch (error) {\n fail(error);\n resolve(false);\n }\n })\n .catch(error => {\n if (!closing && !disposed) fail(error);\n resolve(false);\n });\n if (!(await claimed) && !fault && !closing && !disposed) watchLeadership();\n };\n\n await restore(true);\n // The timeline, not a runtime constructed before attachment, is the baseline\n // for local undo. Even an identical restored snapshot must discard prior history.\n runtime.history.clear();\n driver = installRuntimeWriteDriver(runtime, { assertWritable: assertLeader });\n channel = new BroadcastChannel(`doxum:${databaseName}:${documentId}`);\n unsubscribe = runtime.subscribe(commit => {\n if (\n (commit.source === 'local' || commit.source === 'system' || commit.source === 'history') &&\n !closing &&\n !disposed\n )\n record(commit);\n });\n channel.onmessage = event => {\n const message = notification(event.data);\n if (\n !message ||\n message.documentId !== documentId ||\n message.headSeq <= headSeq ||\n closing ||\n disposed ||\n fault\n )\n return;\n void enqueue(restore).catch(() => undefined);\n };\n await claimInitialLeadership();\n if (fault) throw fault;\n\n const localSync: LocalSync = {\n state: Object.freeze({\n current: () => snapshot,\n revision: () => stateRevision,\n subscribe: (listener: () => void) => {\n if (disposed) throw new LocalSyncError('disposed', 'Local sync has been disposed.');\n stateListeners.add(listener);\n return () => {\n stateListeners.delete(listener);\n };\n },\n }),\n flush: async (): Promise<void> => {\n assertOpen();\n try {\n await enqueue(restore);\n } catch (error) {\n throw fail(error);\n }\n assertOpen();\n },\n dispose: async (): Promise<void> => {\n if (disposed) return;\n if (closing) {\n await queued;\n return;\n }\n closing = true;\n unsubscribe?.();\n await queued;\n releaseLeadership?.();\n if (role === 'leader') await leadershipLease;\n disposed = true;\n driver?.dispose();\n channel?.close();\n timeline.close();\n publishState();\n stateListeners.clear();\n },\n };\n return Object.freeze(localSync);\n } catch (error) {\n unsubscribe?.();\n driver?.dispose();\n channel?.close();\n timeline.close();\n throw normalizeLocalSyncError(error, 'unavailable', 'Unable to attach local sync.');\n }\n};\n"],"mappings":";;;;AASA,IAAa,iBAAb,cAAoC,MAAM;CACxC;CAEA,YAAY,MAA0B,SAAiB,SAAwC;AAC7F,QAAM,SAAS,QAAQ;AACvB,OAAK,OAAO;AACZ,OAAK,OAAO;;;AAIhB,MAAa,2BACX,OACA,MACA,YAEA,iBAAiB,iBAAiB,QAAQ,IAAI,eAAe,MAAM,SAAS,EAAE,OAAO,OAAO,CAAC;;;ACD/F,MAAa,0BAAwD,OAAO,OAAO;CACjF,YAAY;CACZ,UAAU;CACV,UAAU;CACV,iBAAiB;CAClB,CAAC;AAEF,MAAM,gBAAgB,SACpB,KAAK,WAAW,IAAI,UAAU,KAAK,KAAK,IAAI;AAE9C,MAAM,SAAS,OAA2B,UAAkB,UAA0B;AACpF,KAAI,UAAU,KAAA,EAAW,QAAO;AAChC,KAAI,OAAO,cAAc,MAAM,IAAI,QAAQ,EAAG,QAAO;AACrD,OAAM,IAAI,UAAU,GAAG,MAAM,mCAAmC;;AAGlE,MAAM,iBAAiB,WAA6D;CAClF,YAAY,MAAM,OAAO,YAAY,wBAAwB,YAAY,aAAa;CACtF,UAAU,MAAM,OAAO,UAAU,wBAAwB,UAAU,WAAW;CAC9E,UAAU,MAAM,OAAO,UAAU,wBAAwB,UAAU,WAAW;CAC9E,iBAAiB,MACf,OAAO,iBACP,wBAAwB,iBACxB,kBACD;CACF;AAED,MAAM,YACJ,OACA,MACA,QACA,OACA,cACc;AACd,KAAI,UAAU,QAAQ,OAAO,SAC3B,OAAM,IAAI,eACR,gBACA,GAAG,aAAa,KAAK,CAAC,kCACvB;AACH,KAAI,UAAU,QAAQ,OAAO,UAAU,UAAW,QAAO;AACzD,KAAI,OAAO,UAAU,UAAU;AAC7B,MAAI,CAAC,UAAU,MAAM,UAAU,OAAO,gBAAiB,QAAO;AA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AACd,WAAM,KAAK,MAAM;;AAEnB,gBAAY;;GAEd,SAAS,YAA2B;AAClC,QAAI,SAAU;AACd,QAAI,SAAS;AACX,WAAM;AACN;;AAEF,cAAU;AACV,mBAAe;AACf,UAAM;AACN,yBAAqB;AACrB,QAAI,SAAS,SAAU,OAAM;AAC7B,eAAW;AACX,YAAQ,SAAS;AACjB,aAAS,OAAO;AAChB,aAAS,OAAO;AAChB,kBAAc;AACd,mBAAe,OAAO;;GAEzB;AACD,SAAO,OAAO,OAAO,UAAU;UACxB,OAAO;AACd,iBAAe;AACf,UAAQ,SAAS;AACjB,WAAS,OAAO;AAChB,WAAS,OAAO;AAChB,QAAM,wBAAwB,OAAO,eAAe,+BAA+B"}
|
package/dist/local-sync.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"local-sync.js","names":["changeSet.decodeChanges","changeSet.changeCount","positiveInteger"],"sources":["../core/src/local-sync/error.ts","../core/src/local-sync/json.ts","../core/src/local-sync/timeline.ts","../core/src/local-sync/session.ts"],"sourcesContent":["export type LocalSyncErrorCode =\n | 'unavailable'\n | 'schema-mismatch'\n | 'consistency'\n | 'read-only'\n | 'unsupported-operation'\n | 'disposed'\n | 'invalid-data';\n\nexport class LocalSyncError extends Error {\n readonly code: LocalSyncErrorCode;\n\n constructor(code: LocalSyncErrorCode, message: string, options?: { readonly cause?: unknown }) {\n super(message, options);\n this.name = 'LocalSyncError';\n this.code = code;\n }\n}\n\nexport const normalizeLocalSyncError = (\n error: unknown,\n code: LocalSyncErrorCode,\n message: string\n): LocalSyncError =>\n error instanceof LocalSyncError ? error : new LocalSyncError(code, message, { cause: error });\n","import { isPlainObject } from '@/value/record';\nimport * as changeSet from '@/mutation/changes';\nimport type { ChangeSet } from '@/changes';\nimport { LocalSyncError } from './error';\n\nexport type JsonPrimitive = null | boolean | number | string;\nexport type JsonValue =\n JsonPrimitive | readonly JsonValue[] | { readonly [key: string]: JsonValue };\n\nexport type JsonChangeLimits = {\n readonly maxChanges?: number;\n readonly maxBytes?: number;\n readonly maxDepth?: number;\n readonly maxStringLength?: number;\n};\n\ntype ResolvedJsonLimits = {\n readonly maxChanges: number;\n readonly maxBytes: number;\n readonly maxDepth: number;\n readonly maxStringLength: number;\n};\n\nexport const defaultJsonChangeLimits: Readonly<ResolvedJsonLimits> = Object.freeze({\n maxChanges: 1_000,\n maxBytes: 1_000_000,\n maxDepth: 64,\n maxStringLength: 256_000,\n});\n\nconst describePath = (path: readonly string[]): string =>\n path.length === 0 ? 'value' : path.join('.');\n\nconst limit = (value: number | undefined, fallback: number, label: string): number => {\n if (value === undefined) return fallback;\n if (Number.isSafeInteger(value) && value > 0) return value;\n throw new TypeError(`${label} must be a positive safe integer.`);\n};\n\nconst resolveLimits = (input: JsonChangeLimits | undefined): ResolvedJsonLimits => ({\n maxChanges: limit(input?.maxChanges, defaultJsonChangeLimits.maxChanges, 'maxChanges'),\n maxBytes: limit(input?.maxBytes, defaultJsonChangeLimits.maxBytes, 'maxBytes'),\n maxDepth: limit(input?.maxDepth, defaultJsonChangeLimits.maxDepth, 'maxDepth'),\n maxStringLength: limit(\n input?.maxStringLength,\n defaultJsonChangeLimits.maxStringLength,\n 'maxStringLength'\n ),\n});\n\nconst validate = (\n value: unknown,\n path: string[],\n limits: ResolvedJsonLimits | undefined,\n depth: number,\n ancestors: WeakSet<object>\n): JsonValue => {\n if (limits && depth > limits.maxDepth)\n throw new LocalSyncError(\n 'invalid-data',\n `${describePath(path)} exceeds the maximum JSON depth.`\n );\n if (value === null || typeof value === 'boolean') return value;\n if (typeof value === 'string') {\n if (!limits || value.length <= limits.maxStringLength) return value;\n throw new LocalSyncError(\n 'invalid-data',\n `${describePath(path)} exceeds the maximum string length.`\n );\n }\n if (typeof value === 'number') {\n if (Number.isFinite(value)) return value;\n throw new LocalSyncError('invalid-data', `${describePath(path)} contains a non-finite number.`);\n }\n if (Array.isArray(value)) {\n if (ancestors.has(value))\n throw new LocalSyncError('invalid-data', `${describePath(path)} contains a cycle.`);\n ancestors.add(value);\n try {\n for (let index = 0; index < value.length; index += 1) {\n path.push(String(index));\n validate(value[index], path, limits, depth + 1, ancestors);\n path.pop();\n }\n } finally {\n ancestors.delete(value);\n }\n return value as readonly JsonValue[];\n }\n if (isPlainObject(value)) {\n if (ancestors.has(value))\n throw new LocalSyncError('invalid-data', `${describePath(path)} contains a cycle.`);\n ancestors.add(value);\n try {\n for (const key of Object.keys(value)) {\n path.push(key);\n validate(value[key], path, limits, depth + 1, ancestors);\n path.pop();\n }\n } finally {\n ancestors.delete(value);\n }\n return value as { readonly [key: string]: JsonValue };\n }\n throw new LocalSyncError('invalid-data', `${describePath(path)} must be JSON data.`);\n};\n\nexport const json = (value: unknown, label: string): JsonValue =>\n validate(value, [label], undefined, 0, new WeakSet());\n\nexport const jsonChanges = (value: unknown, label: string, input?: JsonChangeLimits): ChangeSet => {\n const limits = input === undefined ? undefined : resolveLimits(input);\n let changes: ChangeSet;\n try {\n changes = changeSet.decodeChanges(value);\n } catch {\n throw new LocalSyncError('invalid-data', `${label} contains an invalid ChangeSet.`);\n }\n if (limits && changeSet.changeCount(changes) > limits.maxChanges)\n throw new LocalSyncError('invalid-data', `${label} exceeds the maximum change count.`);\n validate(changes.changes, [label], limits, 0, new WeakSet());\n if (limits) {\n const serialized = JSON.stringify(changes.changes);\n if (new TextEncoder().encode(serialized).byteLength > limits.maxBytes)\n throw new LocalSyncError('invalid-data', `${label} exceeds the maximum ChangeSet size.`);\n }\n return changes;\n};\n","import { LocalSyncError, normalizeLocalSyncError } from './error';\nimport { json, jsonChanges, type JsonValue } from './json';\nimport type { ChangeSet } from '@/changes';\nimport { isRecord } from '@/value/record';\n\nconst DATABASE_VERSION = 5;\nconst FORMAT_VERSION = 3;\nconst DOCUMENTS = 'documents';\nconst COMMITS = 'commits';\n\nexport type StoredDocument = {\n readonly formatVersion: number;\n readonly documentId: string;\n readonly schemaVersion: number;\n readonly checkpointSeq: number;\n readonly headSeq: number;\n readonly checkpoint: JsonValue;\n};\n\nexport type StoredCommit = {\n readonly formatVersion: number;\n readonly documentId: string;\n readonly seq: number;\n readonly changes: ChangeSet;\n readonly createdAt: number;\n};\n\nconst request = <T>(value: IDBRequest<T>): Promise<T> =>\n new Promise((resolve, reject) => {\n value.onsuccess = () => resolve(value.result);\n value.onerror = () =>\n reject(normalizeLocalSyncError(value.error, 'unavailable', 'IndexedDB request failed.'));\n });\n\nconst complete = (transaction: IDBTransaction): Promise<void> =>\n new Promise((resolve, reject) => {\n transaction.oncomplete = () => resolve();\n transaction.onabort = () =>\n reject(\n normalizeLocalSyncError(\n transaction.error,\n 'unavailable',\n 'IndexedDB transaction was aborted.'\n )\n );\n transaction.onerror = () =>\n reject(\n normalizeLocalSyncError(transaction.error, 'unavailable', 'IndexedDB transaction failed.')\n );\n });\n\nconst factory = (): IDBFactory => {\n if (!globalThis.indexedDB)\n throw new LocalSyncError(\n 'unavailable',\n 'IndexedDB is required by doxum/local-sync in this environment.'\n );\n return globalThis.indexedDB;\n};\n\nconst keyRange = (): typeof IDBKeyRange => {\n if (!globalThis.IDBKeyRange)\n throw new LocalSyncError(\n 'unavailable',\n 'IndexedDB is required by doxum/local-sync in this environment.'\n );\n return globalThis.IDBKeyRange;\n};\n\nconst string = (value: unknown, label: string): string => {\n if (typeof value === 'string') return value;\n throw new LocalSyncError('consistency', `${label} is malformed in IndexedDB.`);\n};\n\nconst nonNegativeInteger = (value: unknown, label: string): number => {\n if (typeof value === 'number' && Number.isSafeInteger(value) && value >= 0) return value;\n throw new LocalSyncError('consistency', `${label} is malformed in IndexedDB.`);\n};\n\nconst positiveInteger = (value: unknown, label: string): number => {\n const parsed = nonNegativeInteger(value, label);\n if (parsed > 0) return parsed;\n throw new LocalSyncError('consistency', `${label} is malformed in IndexedDB.`);\n};\n\nconst documentRecord = (value: unknown): StoredDocument => {\n if (!isRecord(value) || value.formatVersion !== FORMAT_VERSION)\n throw new LocalSyncError('consistency', 'Document record is malformed in IndexedDB.');\n const checkpointSeq = nonNegativeInteger(value.checkpointSeq, 'document.checkpointSeq');\n const headSeq = nonNegativeInteger(value.headSeq, 'document.headSeq');\n if (checkpointSeq > headSeq)\n throw new LocalSyncError('consistency', 'Document checkpoint exceeds its head sequence.');\n return Object.freeze({\n formatVersion: FORMAT_VERSION,\n documentId: string(value.documentId, 'document.documentId'),\n schemaVersion: positiveInteger(value.schemaVersion, 'document.schemaVersion'),\n checkpointSeq,\n headSeq,\n checkpoint: json(value.checkpoint, 'document.checkpoint'),\n });\n};\n\nconst commitRecord = (value: unknown): StoredCommit => {\n if (!isRecord(value) || value.formatVersion !== FORMAT_VERSION)\n throw new LocalSyncError('consistency', 'Commit record is malformed in IndexedDB.');\n return Object.freeze({\n formatVersion: FORMAT_VERSION,\n documentId: string(value.documentId, 'commit.documentId'),\n seq: positiveInteger(value.seq, 'commit.seq'),\n changes: jsonChanges({ changes: value.changes }, 'commit.changes'),\n createdAt: nonNegativeInteger(value.createdAt, 'commit.createdAt'),\n });\n};\n\nexport type IndexedDbTimeline = {\n readonly initialize: (\n documentId: string,\n schemaVersion: number,\n checkpoint: JsonValue\n ) => Promise<StoredDocument>;\n readonly read: (documentId: string) => Promise<StoredDocument>;\n readonly tail: (documentId: string, afterSeq: number) => Promise<readonly StoredCommit[]>;\n readonly append: (input: {\n readonly documentId: string;\n readonly expectedHeadSeq: number;\n readonly changes: ChangeSet;\n }) => Promise<StoredCommit>;\n readonly close: () => void;\n};\n\nexport const openIndexedDbTimeline = async (databaseName: string): Promise<IndexedDbTimeline> => {\n const database = await new Promise<IDBDatabase>((resolve, reject) => {\n let incompatible = false;\n const open = factory().open(databaseName, DATABASE_VERSION);\n open.onerror = () =>\n reject(\n incompatible\n ? new LocalSyncError(\n 'consistency',\n 'Unsupported Doxum storage format. Existing data was left unchanged.'\n )\n : (open.error ?? new Error('Unable to open IndexedDB.'))\n );\n open.onblocked = () => reject(new Error(`IndexedDB database '${databaseName}' is blocked.`));\n open.onupgradeneeded = event => {\n if (event.oldVersion !== 0) {\n incompatible = true;\n open.transaction?.abort();\n return;\n }\n const db = open.result;\n if (!db.objectStoreNames.contains(DOCUMENTS))\n db.createObjectStore(DOCUMENTS, { keyPath: 'documentId' });\n if (!db.objectStoreNames.contains(COMMITS))\n db.createObjectStore(COMMITS, { keyPath: ['documentId', 'seq'] });\n };\n open.onsuccess = () => resolve(open.result);\n });\n\n const readDocument = async (\n transaction: IDBTransaction,\n documentId: string\n ): Promise<StoredDocument> => {\n const value = await request(transaction.objectStore(DOCUMENTS).get(documentId));\n if (value === undefined)\n throw new LocalSyncError('consistency', `Local document '${documentId}' does not exist.`);\n return documentRecord(value);\n };\n\n return {\n initialize: async (documentId, schemaVersion, checkpoint) => {\n const transaction = database.transaction(DOCUMENTS, 'readwrite');\n const store = transaction.objectStore(DOCUMENTS);\n const existing = await request(store.get(documentId));\n if (existing !== undefined) {\n const record = documentRecord(existing);\n if (record.schemaVersion !== schemaVersion)\n throw new LocalSyncError(\n 'schema-mismatch',\n `Local document '${documentId}' uses schema version ${record.schemaVersion}, but version ${schemaVersion} was requested.`\n );\n await complete(transaction);\n return record;\n }\n const record: StoredDocument = {\n formatVersion: FORMAT_VERSION,\n documentId,\n schemaVersion,\n checkpointSeq: 0,\n headSeq: 0,\n checkpoint,\n };\n store.put(record);\n await complete(transaction);\n return Object.freeze(record);\n },\n read: async documentId => {\n const transaction = database.transaction(DOCUMENTS, 'readonly');\n const record = await readDocument(transaction, documentId);\n await complete(transaction);\n return record;\n },\n tail: async (documentId, afterSeq) => {\n const transaction = database.transaction(COMMITS, 'readonly');\n const range = keyRange().bound(\n [documentId, afterSeq + 1],\n [documentId, Number.MAX_SAFE_INTEGER]\n );\n const values = await request(transaction.objectStore(COMMITS).getAll(range));\n await complete(transaction);\n return Object.freeze(values.map(commitRecord).sort((left, right) => left.seq - right.seq));\n },\n append: async input => {\n const transaction = database.transaction([DOCUMENTS, COMMITS], 'readwrite');\n const documents = transaction.objectStore(DOCUMENTS);\n const current = await readDocument(transaction, input.documentId);\n if (current.headSeq !== input.expectedHeadSeq)\n throw new LocalSyncError(\n 'consistency',\n 'Local document advanced before the leader could append its commit.'\n );\n const commit: StoredCommit = {\n formatVersion: FORMAT_VERSION,\n documentId: input.documentId,\n seq: current.headSeq + 1,\n changes: input.changes,\n createdAt: Date.now(),\n };\n documents.put({ ...current, headSeq: commit.seq });\n transaction.objectStore(COMMITS).put({ ...commit, changes: commit.changes.changes });\n await complete(transaction);\n return Object.freeze(commit);\n },\n close: () => database.close(),\n };\n};\n","import {\n installRuntimeWriteDriver,\n type RuntimeWriteDriverLease,\n type RuntimeWriteIntent,\n} from '@/runtime/driver';\nimport type { DocumentCommit } from '@/runtime/contract';\nimport type { Infer, ObjectSchema } from '@/schema/model';\nimport { type AttachLocalSyncOptions, type LocalSync, type LocalSyncState } from './contract';\nimport { LocalSyncError, normalizeLocalSyncError } from './error';\nimport { json, jsonChanges } from './json';\nimport type { ChangeSet } from '@/changes';\nimport { openIndexedDbTimeline, type StoredCommit } from './timeline';\n\ntype LockOptions = {\n readonly mode: 'exclusive';\n readonly ifAvailable?: boolean;\n};\n\ntype LockManager = {\n readonly request: <TResult>(\n name: string,\n options: LockOptions,\n callback: (lock: unknown | null) => TResult | PromiseLike<TResult>\n ) => Promise<TResult>;\n};\n\ntype Channel = {\n onmessage: ((event: MessageEvent<unknown>) => void) | null;\n postMessage(message: unknown): void;\n close(): void;\n};\n\ntype ChannelConstructor = new (name: string) => Channel;\n\ntype CommitNotification = {\n readonly kind: 'commit';\n readonly documentId: string;\n readonly headSeq: number;\n};\n\nconst locks = (): LockManager => {\n const value: unknown = globalThis.navigator?.locks;\n if (\n typeof value !== 'object' ||\n value === null ||\n !('request' in value) ||\n typeof value.request !== 'function'\n )\n throw new LocalSyncError(\n 'unavailable',\n 'Web Locks is required by doxum/local-sync in this environment.'\n );\n return value as LockManager;\n};\n\nconst channelConstructor = (): ChannelConstructor => {\n const value: unknown = globalThis.BroadcastChannel;\n if (typeof value !== 'function')\n throw new LocalSyncError(\n 'unavailable',\n 'BroadcastChannel is required by doxum/local-sync in this environment.'\n );\n return value as ChannelConstructor;\n};\n\nconst requiredString = (value: string, label: string): string => {\n if (value.length > 0) return value;\n throw new TypeError(`${label} must not be empty.`);\n};\n\nconst positiveInteger = (value: number, label: string): number => {\n if (Number.isSafeInteger(value) && value > 0) return value;\n throw new TypeError(`${label} must be a positive safe integer.`);\n};\n\nconst notification = (value: unknown): CommitNotification | undefined => {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return undefined;\n const record = value as Record<string, unknown>;\n if (\n record.kind !== 'commit' ||\n typeof record.documentId !== 'string' ||\n typeof record.headSeq !== 'number' ||\n !Number.isSafeInteger(record.headSeq) ||\n record.headSeq < 0\n )\n return undefined;\n return record as CommitNotification;\n};\n\nexport const attachLocalSync = async <TSchema extends ObjectSchema<object>>(\n input: AttachLocalSyncOptions<TSchema>\n): Promise<LocalSync> => {\n const runtime = input.runtime;\n const databaseName = requiredString(input.database, 'database');\n const documentId = requiredString(input.documentId, 'documentId');\n const schemaVersion = positiveInteger(input.schemaVersion ?? 1, 'schemaVersion');\n const lockManager = locks();\n const BroadcastChannel = channelConstructor();\n const timeline = await openIndexedDbTimeline(databaseName).catch(error => {\n throw normalizeLocalSyncError(error, 'unavailable', 'Unable to open local sync storage.');\n });\n\n let channel: Channel | undefined;\n let unsubscribe: (() => void) | undefined;\n let driver: RuntimeWriteDriverLease | undefined;\n try {\n const stored = await timeline.initialize(\n documentId,\n schemaVersion,\n json(runtime.snapshot(), 'runtime snapshot')\n );\n let headSeq = stored.checkpointSeq;\n let checkpointSeq = stored.checkpointSeq;\n let role: 'leader' | 'follower' = 'follower';\n let fault: LocalSyncError | undefined;\n let closing = false;\n let disposed = false;\n let releaseLeadership: (() => void) | undefined;\n let leadershipLease: Promise<void> | undefined;\n let queued: Promise<void> = Promise.resolve();\n let snapshot: LocalSyncState = Object.freeze({ status: role, headSeq, checkpointSeq });\n let stateRevision = 0;\n const stateListeners = new Set<() => void>();\n const publishState = (): void => {\n const next: LocalSyncState = disposed\n ? { status: 'disposed' }\n : fault\n ? { status: 'error', headSeq, checkpointSeq, error: fault }\n : { status: role, headSeq, checkpointSeq };\n if (\n snapshot.status === next.status &&\n (snapshot.status === 'disposed' ||\n (next.status !== 'disposed' &&\n snapshot.headSeq === next.headSeq &&\n snapshot.checkpointSeq === next.checkpointSeq &&\n (snapshot.status !== 'error' ||\n (next.status === 'error' && snapshot.error === next.error))))\n )\n return;\n snapshot = Object.freeze(next);\n stateRevision++;\n for (const listener of [...stateListeners]) {\n if (!stateListeners.has(listener)) continue;\n try {\n listener();\n } catch {\n // Consumer state listeners are isolated from synchronization state.\n }\n }\n };\n\n const fail = (error: unknown): LocalSyncError => {\n const failure = normalizeLocalSyncError(\n error,\n 'unavailable',\n 'Local synchronization failed.'\n );\n if (fault || disposed) return fault ?? failure;\n fault = failure;\n publishState();\n try {\n input.onError?.(failure);\n } catch {\n // Error reporting cannot repair or replace the original synchronization failure.\n }\n return failure;\n };\n\n const assertOpen = (): void => {\n if (closing || disposed)\n throw new LocalSyncError('disposed', 'Local sync has been disposed.');\n if (fault) throw fault;\n };\n\n const assertLeader = (intent: RuntimeWriteIntent): void => {\n assertOpen();\n if (role !== 'leader')\n throw new LocalSyncError(\n 'read-only',\n 'This tab is following the local document and cannot write until it becomes the leader.'\n );\n if (intent.kind === 'replace' || (intent.kind === 'apply' && intent.source === 'remote'))\n throw new LocalSyncError(\n 'unsupported-operation',\n 'Local sync appends committed changes. runtime.replace() and externally supplied remote changes are unavailable while it is attached.'\n );\n };\n\n const runRuntime = <TResult>(run: () => TResult): TResult => driver?.run(run) ?? run();\n const replayRuntime = <TResult>(run: () => TResult, message: string): TResult => {\n try {\n return runRuntime(run);\n } catch (error) {\n throw normalizeLocalSyncError(error, 'consistency', message);\n }\n };\n\n const applyStored = (commit: StoredCommit): void => {\n if (commit.seq !== headSeq + 1)\n throw new LocalSyncError('consistency', 'Local commit log contains a sequence gap.');\n const result = replayRuntime(\n () =>\n runtime.apply(commit.changes, {\n expectedRevision: runtime.revision(),\n source: 'remote',\n }),\n 'A stored local ChangeSet could not be replayed.'\n );\n if (result.status !== 'committed')\n throw new LocalSyncError('consistency', 'A stored local ChangeSet could not be applied.');\n headSeq = commit.seq;\n };\n\n const restore = async (reset = false): Promise<void> => {\n const current = await timeline.read(documentId);\n if (current.schemaVersion !== schemaVersion)\n throw new LocalSyncError(\n 'consistency',\n 'Local document schema changed while this attachment was open.'\n );\n if (headSeq > current.headSeq)\n throw new LocalSyncError('consistency', 'The local timeline moved behind this attachment.');\n if (reset || headSeq < current.checkpointSeq) {\n const result = replayRuntime(\n () => runtime.replace(current.checkpoint as Infer<TSchema>, { source: 'remote' }),\n 'The local checkpoint could not be restored.'\n );\n if (result.status === 'rejected')\n throw new LocalSyncError('consistency', 'The local checkpoint could not be restored.');\n headSeq = current.checkpointSeq;\n }\n const tail = await timeline.tail(documentId, headSeq);\n for (const commit of tail) applyStored(commit);\n if (headSeq !== current.headSeq)\n throw new LocalSyncError(\n 'consistency',\n 'Local commit log does not reach its recorded head sequence.'\n );\n checkpointSeq = current.checkpointSeq;\n publishState();\n };\n\n const enqueue = (run: () => Promise<void>): Promise<void> => {\n const next = queued.then(run, run);\n queued = next.then(\n () => undefined,\n error => {\n fail(error);\n }\n );\n return next;\n };\n\n const persist = async (changes: ChangeSet): Promise<void> => {\n const storedCommit = await timeline.append({\n documentId,\n expectedHeadSeq: headSeq,\n changes,\n });\n if (storedCommit.seq !== headSeq + 1)\n throw new LocalSyncError(\n 'consistency',\n 'A local commit was assigned an unexpected sequence.'\n );\n headSeq = storedCommit.seq;\n publishState();\n channel?.postMessage({\n kind: 'commit',\n documentId,\n headSeq,\n } satisfies CommitNotification);\n };\n\n const record = (commit: DocumentCommit<TSchema>): void => {\n try {\n const changes = jsonChanges(\n commit.changes,\n 'local commit changes',\n input.changeLimits ?? {}\n );\n void enqueue(() => persist(changes)).catch(() => undefined);\n } catch (error) {\n fail(error);\n }\n };\n\n const holdLeadership = (): Promise<void> =>\n new Promise(resolve => {\n releaseLeadership = resolve;\n });\n\n const lead = async (activated?: () => void): Promise<void> => {\n if (closing || disposed || fault) return;\n await restore();\n if (closing || disposed || fault) return;\n role = 'leader';\n publishState();\n activated?.();\n try {\n await holdLeadership();\n } finally {\n releaseLeadership = undefined;\n if (!closing && !disposed && !fault) {\n role = 'follower';\n publishState();\n }\n }\n };\n\n const watchLeadership = (): void => {\n leadershipLease = lockManager\n .request(`doxum:${documentId}`, { mode: 'exclusive' }, async () => {\n try {\n await lead();\n } catch (error) {\n fail(error);\n }\n })\n .catch(error => {\n if (!closing && !disposed) fail(error);\n });\n };\n\n const claimInitialLeadership = async (): Promise<void> => {\n let resolve!: (value: boolean) => void;\n const claimed = new Promise<boolean>(done => {\n resolve = done;\n });\n leadershipLease = lockManager\n .request(`doxum:${documentId}`, { mode: 'exclusive', ifAvailable: true }, async lock => {\n if (lock === null) {\n resolve(false);\n return;\n }\n try {\n await lead(() => resolve(true));\n } catch (error) {\n fail(error);\n resolve(false);\n }\n })\n .catch(error => {\n if (!closing && !disposed) fail(error);\n resolve(false);\n });\n if (!(await claimed) && !fault && !closing && !disposed) watchLeadership();\n };\n\n await restore(true);\n // The timeline, not a runtime constructed before attachment, is the baseline\n // for local undo. Even an identical restored snapshot must discard prior history.\n runtime.history.clear();\n driver = installRuntimeWriteDriver(runtime, { assertWritable: assertLeader });\n channel = new BroadcastChannel(`doxum:${databaseName}:${documentId}`);\n unsubscribe = runtime.subscribe(commit => {\n if (\n (commit.source === 'local' || commit.source === 'system' || commit.source === 'history') &&\n !closing &&\n !disposed\n )\n record(commit);\n });\n channel.onmessage = event => {\n const message = notification(event.data);\n if (\n !message ||\n message.documentId !== documentId ||\n message.headSeq <= headSeq ||\n closing ||\n disposed ||\n fault\n )\n return;\n void enqueue(restore).catch(() => undefined);\n };\n await claimInitialLeadership();\n if (fault) throw fault;\n\n const localSync: LocalSync = {\n state: Object.freeze({\n current: () => snapshot,\n revision: () => stateRevision,\n subscribe: (listener: () => void) => {\n if (disposed) throw new LocalSyncError('disposed', 'Local sync has been disposed.');\n stateListeners.add(listener);\n return () => {\n stateListeners.delete(listener);\n };\n },\n }),\n flush: async (): Promise<void> => {\n assertOpen();\n try {\n await enqueue(restore);\n } catch (error) {\n throw fail(error);\n }\n assertOpen();\n },\n dispose: async (): Promise<void> => {\n if (disposed) return;\n if (closing) {\n await queued;\n return;\n }\n closing = true;\n unsubscribe?.();\n await queued;\n releaseLeadership?.();\n if (role === 'leader') await leadershipLease;\n disposed = true;\n driver?.dispose();\n channel?.close();\n timeline.close();\n publishState();\n stateListeners.clear();\n },\n };\n return Object.freeze(localSync);\n } catch (error) {\n unsubscribe?.();\n driver?.dispose();\n channel?.close();\n timeline.close();\n throw normalizeLocalSyncError(error, 'unavailable', 'Unable to attach local sync.');\n }\n};\n"],"mappings":";;;AASA,IAAa,iBAAb,cAAoC,MAAM;CACxC;CAEA,YAAY,MAA0B,SAAiB,SAAwC;AAC7F,QAAM,SAAS,QAAQ;AACvB,OAAK,OAAO;AACZ,OAAK,OAAO;;;AAIhB,MAAa,2BACX,OACA,MACA,YAEA,iBAAiB,iBAAiB,QAAQ,IAAI,eAAe,MAAM,SAAS,EAAE,OAAO,OAAO,CAAC;;;ACD/F,MAAa,0BAAwD,OAAO,OAAO;CACjF,YAAY;CACZ,UAAU;CACV,UAAU;CACV,iBAAiB;CAClB,CAAC;AAEF,MAAM,gBAAgB,SACpB,KAAK,WAAW,IAAI,UAAU,KAAK,KAAK,IAAI;AAE9C,MAAM,SAAS,OAA2B,UAAkB,UAA0B;AACpF,KAAI,UAAU,KAAA,EAAW,QAAO;AAChC,KAAI,OAAO,cAAc,MAAM,IAAI,QAAQ,EAAG,QAAO;AACrD,OAAM,IAAI,UAAU,GAAG,MAAM,mCAAmC;;AAGlE,MAAM,iBAAiB,WAA6D;CAClF,YAAY,MAAM,OAAO,YAAY,wBAAwB,YAAY,aAAa;CACtF,UAAU,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,QAAQ,CAAC,YAAY,KAAA,EAAU;;AAE9C,QAAM,wBAAwB;AAC9B,MAAI,MAAO,OAAM;EAEjB,MAAM,YAAuB;GAC3B,OAAO,OAAO,OAAO;IACnB,eAAe;IACf,gBAAgB;IAChB,YAAY,aAAyB;AACnC,SAAI,SAAU,OAAM,IAAI,eAAe,YAAY,gCAAgC;AACnF,oBAAe,IAAI,SAAS;AAC5B,kBAAa;AACX,qBAAe,OAAO,SAAS;;;IAGpC,CAAC;GACF,OAAO,YAA2B;AAChC,gBAAY;AACZ,QAAI;AACF,WAAM,QAAQ,QAAQ;aACf,OAAO;AACd,WAAM,KAAK,MAAM;;AAEnB,gBAAY;;GAEd,SAAS,YAA2B;AAClC,QAAI,SAAU;AACd,QAAI,SAAS;AACX,WAAM;AACN;;AAEF,cAAU;AACV,mBAAe;AACf,UAAM;AACN,yBAAqB;AACrB,QAAI,SAAS,SAAU,OAAM;AAC7B,eAAW;AACX,YAAQ,SAAS;AACjB,aAAS,OAAO;AAChB,aAAS,OAAO;AAChB,kBAAc;AACd,mBAAe,OAAO;;GAEzB;AACD,SAAO,OAAO,OAAO,UAAU;UACxB,OAAO;AACd,iBAAe;AACf,UAAQ,SAAS;AACjB,WAAS,OAAO;AAChB,WAAS,OAAO;AAChB,QAAM,wBAAwB,OAAO,eAAe,+BAA+B"}
|
package/dist/react.cjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"react.cjs","names":[],"sources":["../react/src/hooks.ts"],"sourcesContent":["import type {\n ReadonlyDocument,\n ObjectSchema,\n DocumentSelector,\n HistoryState,\n LocalHistory,\n OperationResult,\n Readable,\n ProjectionRuntime,\n ProjectionScope,\n Projection,\n Input,\n CollectionInput,\n CollectionInputDraft,\n} from 'doxum';\nimport { select } from 'doxum';\nimport { createContext, useCallback, useContext, useMemo, useSyncExternalStore } from 'react';\n\nconst ProjectionContext = createContext<ProjectionRuntime | ProjectionScope | undefined>(undefined);\nexport const ProjectionProvider = ProjectionContext.Provider;\n\nexport function useProjection<T>(projection: Projection<T>): T;\nexport function useProjection<T, R>(\n projection: Projection<T>,\n selector: (value: T) => R,\n equality?: (previous: R, next: R) => boolean\n): R;\nexport function useProjection<T, R>(\n projection: Projection<T>,\n selector?: (value: T) => R,\n equality: (previous: R, next: R) => boolean = Object.is\n): T | R {\n const context = useContext(ProjectionContext);\n const owner = context;\n if (!owner) throw new Error('ProjectionRuntime is required.');\n const readable = useMemo(\n () => (selector ? owner.select(projection, selector, equality) : owner.select(projection)),\n [equality, owner, projection, selector]\n );\n return useReadable(readable as Readable<T | R>);\n}\n\nexport function useInput<T>(input: Input<T>): readonly [T, (value: T) => void];\nexport function useInput<K extends string, V>(\n input: CollectionInput<K, V>\n): readonly [\n ReadonlyMap<K, V>,\n <R>(\n run: (draft: CollectionInputDraft<K, V>) => R extends PromiseLike<unknown> ? never : R\n ) => void,\n];\nexport function useInput(input: Projection<unknown>): readonly [unknown, (next: never) => void] {\n const context = useContext(ProjectionContext);\n const owner = context;\n if (!owner) throw new Error('ProjectionRuntime is required.');\n const value = useProjection(input);\n const update = useCallback(\n (next: never) =>\n (owner.update as (target: Projection<unknown>, next: unknown) => void)(input, next),\n [input, owner]\n );\n return useMemo(() => [value, update] as const, [update, value]);\n}\n\nconst objectIs = <T>(previous: T, next: T): boolean => Object.is(previous, next);\n\nexport function useDocumentSelector<TSchema extends ObjectSchema<object>, TResult>(\n runtime: ReadonlyDocument<TSchema>,\n selector: DocumentSelector<TSchema, TResult>,\n equality: (previous: TResult, next: TResult) => boolean = objectIs\n): TResult {\n const readable = useMemo(\n () => select(runtime, selector, equality),\n [equality, runtime, selector]\n );\n return useReadable(readable);\n}\n\nexport function useReadable<T>(readable: Readable<T>): T {\n const subscribe = useCallback((listener: () => void) => readable.subscribe(listener), [readable]);\n const read = useCallback(() => readable.current(), [readable]);\n return useSyncExternalStore(subscribe, read, read);\n}\n\nexport function useHistory<TCommit>(history: LocalHistory<TCommit>): HistoryState & {\n undo(): OperationResult<TCommit>;\n redo(): OperationResult<TCommit>;\n} {\n const subscribe = useCallback((listener: () => void) => history.subscribe(listener), [history]);\n const read = useCallback(() => history.current(), [history]);\n const state = useSyncExternalStore(subscribe, read, read);\n const undo = useCallback(() => history.undo(), [history]);\n const redo = useCallback(() => history.redo(), [history]);\n\n return useMemo(() => ({ ...state, undo, redo }), [redo, state, undo]);\n}\n"],"mappings":";;;;AAkBA,MAAM,qBAAA,GAAA,MAAA,eAAmF,KAAA,EAAU;AACnG,MAAa,qBAAqB,kBAAkB;AAQpD,SAAgB,cACd,YACA,UACA,WAA8C,OAAO,IAC9C;CAEP,MAAM,SAAA,GAAA,MAAA,YADqB,kBACN;AACrB,KAAI,CAAC,MAAO,OAAM,IAAI,MAAM,iCAAiC;AAK7D,QAAO,aAAA,GAAA,MAAA,eAHE,WAAW,MAAM,OAAO,YAAY,UAAU,SAAS,GAAG,MAAM,OAAO,WAAW,EACzF;EAAC;EAAU;EAAO;EAAY;EAAS,CAEd,CAAoB;;AAYjD,SAAgB,SAAS,OAAuE;CAE9F,MAAM,SAAA,GAAA,MAAA,YADqB,kBACN;AACrB,KAAI,CAAC,MAAO,OAAM,IAAI,MAAM,iCAAiC;CAC7D,MAAM,QAAQ,cAAc,MAAM;CAClC,MAAM,UAAA,GAAA,MAAA,cACH,SACE,MAAM,OAAgE,OAAO,KAAK,EACrF,CAAC,OAAO,MAAM,CACf;AACD,SAAA,GAAA,MAAA,eAAqB,CAAC,OAAO,OAAO,EAAW,CAAC,QAAQ,MAAM,CAAC;;AAGjE,MAAM,YAAe,UAAa,SAAqB,OAAO,GAAG,UAAU,KAAK;AAEhF,SAAgB,oBACd,SACA,UACA,WAA0D,UACjD;AAKT,QAAO,aAAA,GAAA,MAAA,gBAAA,GAAA,MAAA,QAHQ,SAAS,UAAU,SAAS,EACzC;EAAC;EAAU;EAAS;EAAS,CAEJ,CAAC;;AAG9B,SAAgB,YAAe,UAA0B;CACvD,MAAM,aAAA,GAAA,MAAA,cAAyB,aAAyB,SAAS,UAAU,SAAS,EAAE,CAAC,SAAS,CAAC;CACjG,MAAM,QAAA,GAAA,MAAA,mBAAyB,SAAS,SAAS,EAAE,CAAC,SAAS,CAAC;AAC9D,SAAA,GAAA,MAAA,sBAA4B,WAAW,MAAM,KAAK;;AAGpD,SAAgB,WAAoB,SAGlC;CACA,MAAM,aAAA,GAAA,MAAA,cAAyB,aAAyB,QAAQ,UAAU,SAAS,EAAE,CAAC,QAAQ,CAAC;CAC/F,MAAM,QAAA,GAAA,MAAA,mBAAyB,QAAQ,SAAS,EAAE,CAAC,QAAQ,CAAC;CAC5D,MAAM,SAAA,GAAA,MAAA,sBAA6B,WAAW,MAAM,KAAK;CACzD,MAAM,QAAA,GAAA,MAAA,mBAAyB,QAAQ,MAAM,EAAE,CAAC,QAAQ,CAAC;CACzD,MAAM,QAAA,GAAA,MAAA,mBAAyB,QAAQ,MAAM,EAAE,CAAC,QAAQ,CAAC;AAEzD,SAAA,GAAA,MAAA,gBAAsB;EAAE,GAAG;EAAO;EAAM;EAAM,GAAG;EAAC;EAAM;EAAO;EAAK,CAAC"}
|
package/dist/react.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"react.js","names":[],"sources":["../react/src/hooks.ts"],"sourcesContent":["import type {\n ReadonlyDocument,\n ObjectSchema,\n DocumentSelector,\n HistoryState,\n LocalHistory,\n OperationResult,\n Readable,\n ProjectionRuntime,\n ProjectionScope,\n Projection,\n Input,\n CollectionInput,\n CollectionInputDraft,\n} from 'doxum';\nimport { select } from 'doxum';\nimport { createContext, useCallback, useContext, useMemo, useSyncExternalStore } from 'react';\n\nconst ProjectionContext = createContext<ProjectionRuntime | ProjectionScope | undefined>(undefined);\nexport const ProjectionProvider = ProjectionContext.Provider;\n\nexport function useProjection<T>(projection: Projection<T>): T;\nexport function useProjection<T, R>(\n projection: Projection<T>,\n selector: (value: T) => R,\n equality?: (previous: R, next: R) => boolean\n): R;\nexport function useProjection<T, R>(\n projection: Projection<T>,\n selector?: (value: T) => R,\n equality: (previous: R, next: R) => boolean = Object.is\n): T | R {\n const context = useContext(ProjectionContext);\n const owner = context;\n if (!owner) throw new Error('ProjectionRuntime is required.');\n const readable = useMemo(\n () => (selector ? owner.select(projection, selector, equality) : owner.select(projection)),\n [equality, owner, projection, selector]\n );\n return useReadable(readable as Readable<T | R>);\n}\n\nexport function useInput<T>(input: Input<T>): readonly [T, (value: T) => void];\nexport function useInput<K extends string, V>(\n input: CollectionInput<K, V>\n): readonly [\n ReadonlyMap<K, V>,\n <R>(\n run: (draft: CollectionInputDraft<K, V>) => R extends PromiseLike<unknown> ? never : R\n ) => void,\n];\nexport function useInput(input: Projection<unknown>): readonly [unknown, (next: never) => void] {\n const context = useContext(ProjectionContext);\n const owner = context;\n if (!owner) throw new Error('ProjectionRuntime is required.');\n const value = useProjection(input);\n const update = useCallback(\n (next: never) =>\n (owner.update as (target: Projection<unknown>, next: unknown) => void)(input, next),\n [input, owner]\n );\n return useMemo(() => [value, update] as const, [update, value]);\n}\n\nconst objectIs = <T>(previous: T, next: T): boolean => Object.is(previous, next);\n\nexport function useDocumentSelector<TSchema extends ObjectSchema<object>, TResult>(\n runtime: ReadonlyDocument<TSchema>,\n selector: DocumentSelector<TSchema, TResult>,\n equality: (previous: TResult, next: TResult) => boolean = objectIs\n): TResult {\n const readable = useMemo(\n () => select(runtime, selector, equality),\n [equality, runtime, selector]\n );\n return useReadable(readable);\n}\n\nexport function useReadable<T>(readable: Readable<T>): T {\n const subscribe = useCallback((listener: () => void) => readable.subscribe(listener), [readable]);\n const read = useCallback(() => readable.current(), [readable]);\n return useSyncExternalStore(subscribe, read, read);\n}\n\nexport function useHistory<TCommit>(history: LocalHistory<TCommit>): HistoryState & {\n undo(): OperationResult<TCommit>;\n redo(): OperationResult<TCommit>;\n} {\n const subscribe = useCallback((listener: () => void) => history.subscribe(listener), [history]);\n const read = useCallback(() => history.current(), [history]);\n const state = useSyncExternalStore(subscribe, read, read);\n const undo = useCallback(() => history.undo(), [history]);\n const redo = useCallback(() => history.redo(), [history]);\n\n return useMemo(() => ({ ...state, undo, redo }), [redo, state, undo]);\n}\n"],"mappings":";;;AAkBA,MAAM,oBAAoB,cAA+D,KAAA,EAAU;AACnG,MAAa,qBAAqB,kBAAkB;AAQpD,SAAgB,cACd,YACA,UACA,WAA8C,OAAO,IAC9C;CAEP,MAAM,QADU,WAAW,kBACN;AACrB,KAAI,CAAC,MAAO,OAAM,IAAI,MAAM,iCAAiC;AAK7D,QAAO,YAJU,cACR,WAAW,MAAM,OAAO,YAAY,UAAU,SAAS,GAAG,MAAM,OAAO,WAAW,EACzF;EAAC;EAAU;EAAO;EAAY;EAAS,CAEd,CAAoB;;AAYjD,SAAgB,SAAS,OAAuE;CAE9F,MAAM,QADU,WAAW,kBACN;AACrB,KAAI,CAAC,MAAO,OAAM,IAAI,MAAM,iCAAiC;CAC7D,MAAM,QAAQ,cAAc,MAAM;CAClC,MAAM,SAAS,aACZ,SACE,MAAM,OAAgE,OAAO,KAAK,EACrF,CAAC,OAAO,MAAM,CACf;AACD,QAAO,cAAc,CAAC,OAAO,OAAO,EAAW,CAAC,QAAQ,MAAM,CAAC;;AAGjE,MAAM,YAAe,UAAa,SAAqB,OAAO,GAAG,UAAU,KAAK;AAEhF,SAAgB,oBACd,SACA,UACA,WAA0D,UACjD;AAKT,QAAO,YAJU,cACT,OAAO,SAAS,UAAU,SAAS,EACzC;EAAC;EAAU;EAAS;EAAS,CAEJ,CAAC;;AAG9B,SAAgB,YAAe,UAA0B;CACvD,MAAM,YAAY,aAAa,aAAyB,SAAS,UAAU,SAAS,EAAE,CAAC,SAAS,CAAC;CACjG,MAAM,OAAO,kBAAkB,SAAS,SAAS,EAAE,CAAC,SAAS,CAAC;AAC9D,QAAO,qBAAqB,WAAW,MAAM,KAAK;;AAGpD,SAAgB,WAAoB,SAGlC;CACA,MAAM,YAAY,aAAa,aAAyB,QAAQ,UAAU,SAAS,EAAE,CAAC,QAAQ,CAAC;CAC/F,MAAM,OAAO,kBAAkB,QAAQ,SAAS,EAAE,CAAC,QAAQ,CAAC;CAC5D,MAAM,QAAQ,qBAAqB,WAAW,MAAM,KAAK;CACzD,MAAM,OAAO,kBAAkB,QAAQ,MAAM,EAAE,CAAC,QAAQ,CAAC;CACzD,MAAM,OAAO,kBAAkB,QAAQ,MAAM,EAAE,CAAC,QAAQ,CAAC;AAEzD,QAAO,eAAe;EAAE,GAAG;EAAO;EAAM;EAAM,GAAG;EAAC;EAAM;EAAO;EAAK,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"record-B2yRhYsc.js","names":[],"sources":["../core/src/value/record.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"],"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,UAAQ,eAAe,QAAQ,IAAI;AACnC;;AAEF,KAAI,OAAO,OAAO,QAAQ,IAAI,EAAE;AAC9B,UAAQ,IAAI,QAAQ,KAAK,MAAM;AAC/B;;AAEF,QAAO,eAAe,QAAQ,KAAK;EACjC;EACA,UAAU;EACV,cAAc;EACd,YAAY;EACb,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"record-ChYUi8PP.cjs","names":[],"sources":["../core/src/value/record.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"],"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,UAAQ,eAAe,QAAQ,IAAI;AACnC;;AAEF,KAAI,OAAO,OAAO,QAAQ,IAAI,EAAE;AAC9B,UAAQ,IAAI,QAAQ,KAAK,MAAM;AAC/B;;AAEF,QAAO,eAAe,QAAQ,KAAK;EACjC;EACA,UAAU;EACV,cAAc;EACd,YAAY;EACb,CAAC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"transform-3mj0eStL.js","names":[],"sources":["../core/src/profile.ts","../core/src/projection/definition.ts","../core/src/projection/collection/view.ts","../core/src/projection/dependency.ts","../core/src/projection/keyed/invalidation.ts","../core/src/projection/contract.ts","../core/src/projection/graph/scheduler.ts","../core/src/value/array.ts","../core/src/projection/keyed/relation.ts","../core/src/projection/keyed/dependency.ts","../core/src/projection/collection/change.ts","../core/src/projection/keyed/transform.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 dependency: { comparisons: 0, segmentsCompared: 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 dependency: {\n comparison: () => {\n if (active) active.dependency.comparisons++;\n },\n segmentCompared: () => {\n if (active) active.dependency.segmentsCompared++;\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 type { ReadonlyDocument } from '@/runtime/contract';\nimport type { ObjectSchema } from '@/schema/model';\nimport type { CollectionSelector, ValueSelector } from '@/schema/path';\nimport type {\n CollectionChange,\n CollectionDraft,\n CollectionRead,\n ExternalCollectionSource,\n ExternalValueSource,\n SourceContext,\n} from './contract';\nimport type { Readable } from '@/readable';\n\ndeclare const projectionDefinition: unique symbol;\ndeclare const keyedProjection: unique symbol;\ndeclare const writableInput: unique symbol;\ndeclare const writableCollectionInput: unique symbol;\n\n/** A lazy output reference with no materialized Runtime state. */\nexport type Projection<T> = {\n readonly [projectionDefinition]: T;\n};\n\n/** A projection whose output is a keyed collection with per-key change semantics. */\nexport type KeyedProjection<K extends string, V> = Projection<ReadonlyMap<K, V>> & {\n readonly [keyedProjection]: { readonly key: K; readonly value: V };\n};\n\n/** A writable source projection. */\nexport type Input<T> = Projection<T> & { readonly [writableInput]: true };\n\n/** A writable keyed collection source projection. */\nexport type CollectionInput<K extends string, V> = KeyedProjection<K, V> & {\n readonly [writableCollectionInput]: { readonly key: K; readonly value: V };\n};\n\nexport type CollectionInputDraft<K extends string, V> = {\n get(key: K): V | undefined;\n has(key: K): boolean;\n set(key: K, value: V): void;\n remove(key: K): void;\n};\n\nexport type ProjectionChange<P> =\n P extends KeyedProjection<infer K, infer V> ? CollectionChange<K, V> : undefined;\n\nexport type Equality = (a: unknown, b: unknown) => boolean;\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 ProcessorInstance = {\n evaluate(input: ProcessorEvaluation): void;\n release?(): void;\n};\n\nexport type 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 readonly equality: Equality;\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: ReadonlyDocument<ObjectSchema<object>>;\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 materialized?: true;\n};\n\nexport type ProcessorDefinition = {\n readonly kind: 'processor';\n readonly dependencies: readonly Projection<unknown>[];\n readonly outputs: readonly OutputDefinition[];\n readonly create: () => ProcessorInstance;\n readonly name?: string;\n owner?: object;\n materialized?: true;\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>(producer: ProducerDefinition, output: number): Projection<T> => {\n const handle = Object.freeze({}) as Projection<T>;\n projections.set(handle, Object.freeze({ producer, output }));\n return handle;\n};\n\nexport const projectionRef = (projection: Projection<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>): ProducerDefinition =>\n projectionRef(projection).producer;\n\n/** Resolves the immutable output description owned by a projection definition. */\nexport const outputDefinitionOf = (projection: Projection<unknown>): OutputDefinition => {\n const ref = projectionRef(projection);\n const producer = ref.producer;\n const output = producer.kind === 'source' ? producer.output : producer.outputs[ref.output];\n if (!output) throw new TypeError('Projection output does not exist.');\n return output;\n};\n\nexport const isProjection = (value: unknown): value is Projection<unknown> =>\n value !== null && typeof value === 'object' && projections.has(value);\n\nexport const ownProjections = (\n projections: readonly Projection<unknown>[],\n owner: object\n): void => {\n const producers = new Set(projections.map(producerOf));\n for (const producer of producers) {\n if (producer.owner !== undefined && producer.owner !== owner)\n throw new TypeError('Projection producer already belongs to another scope.');\n if (producer.owner === undefined && producer.materialized)\n throw new TypeError('A materialized root projection cannot become scope-owned.');\n if (producer.kind !== 'processor') continue;\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 for (const producer of producers) producer.owner = owner;\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>[];\n readonly outputs: readonly OutputDefinition[];\n readonly create: () => ProcessorInstance;\n readonly name?: string;\n}): readonly Projection<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(producer.outputs.map((_, output) => defineRef<unknown>(producer, output)));\n};\n\nexport const defineSource = <T>(source: SourceAdapter, output: OutputDefinition): Projection<T> => {\n const producer: SourceDefinition = {\n kind: 'source',\n source,\n output: freezeOutput(output),\n };\n return defineRef<T>(producer, 0);\n};\n","import type { CollectionRead } from '@/projection/contract';\n\nexport const mapRead = <K extends string, V>(value: ReadonlyMap<K, V>): CollectionRead<K, V> => {\n let ids: readonly K[] | undefined;\n return {\n get: key => value.get(key),\n has: key => value.has(key),\n ids: () => (ids ??= Object.freeze([...value.keys()])),\n };\n};\n\n/** Immutable map-like view over a CollectionRead. */\nexport const collectionView = <K extends string, V>(\n read: CollectionRead<K, V>,\n knownIds?: readonly K[]\n): ReadonlyMap<K, V> => {\n const ids = knownIds ?? read.ids();\n const iterate = <T>(select: (key: K) => T): IterableIterator<T> => {\n read.ids();\n let index = 0;\n return {\n next() {\n read.ids();\n if (index === ids.length) return { done: true, value: undefined };\n return { done: false, value: select(ids[index++]) };\n },\n [Symbol.iterator]() {\n return this;\n },\n };\n };\n const entries = (): IterableIterator<[K, V]> => iterate(key => [key, read.get(key) as V]);\n const values = (): IterableIterator<V> => iterate(key => read.get(key) as V);\n const view: ReadonlyMap<K, V> = {\n get: key => read.get(key),\n has: key => read.has(key),\n get size() {\n read.ids();\n return ids.length;\n },\n keys: () => iterate(key => key),\n values,\n entries,\n forEach: (callback, thisArg) => {\n read.ids();\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), ids);\n};\n","import { isPlainObject } from '@/value/record';\nimport { snapshotCollectionView } from '@/projection/collection/view';\nimport type { SourceContext } from './contract';\nimport { isProjection, projectionRef, type Projection } from './definition';\n\nexport type ProjectionDependencies = Readonly<Record<string, Projection<unknown>>> &\n Partial<Record<keyof Projection<unknown>, never>>;\nexport type ProjectionValues<D extends ProjectionDependencies> = {\n readonly [K in keyof D]: D[K] extends Projection<infer T> ? T : never;\n};\n\nexport type CompiledProjectionDependencies = {\n readonly names: readonly string[];\n readonly projections: readonly Projection<unknown>[];\n};\n\nexport type NamedDependencyEntry = {\n readonly name: string;\n readonly value: unknown;\n};\n\n/** Owns validation of the shared named dependency object shape. */\nexport const readNamedDependencyEntries = (\n dependencies: unknown,\n label: string\n): readonly NamedDependencyEntry[] => {\n if (!isPlainObject(dependencies) || isProjection(dependencies))\n throw new TypeError(`${label} dependencies must be a plain object.`);\n const entries: NamedDependencyEntry[] = [];\n for (const name of Reflect.ownKeys(dependencies)) {\n if (typeof name !== 'string') throw new TypeError(`${label} dependency names must be strings.`);\n const descriptor = Object.getOwnPropertyDescriptor(dependencies, name);\n if (!descriptor?.enumerable || !('value' in descriptor))\n throw new TypeError(`${label} dependencies must be enumerable data properties.`);\n entries.push(Object.freeze({ name, value: descriptor.value }));\n }\n return Object.freeze(entries);\n};\n\n/** Creates the durable dependency value exposed to pure derive callbacks. */\nexport const snapshotDependencyValue = (source: SourceContext): unknown =>\n source.kind === 'value' ? source.value : snapshotCollectionView(source.read);\n\n/** Builds the same readonly named value boundary for scalar and keyed pure computations. */\nexport const snapshotProjectionValues = <D extends ProjectionDependencies>(\n names: readonly string[],\n sources: readonly SourceContext[]\n): ProjectionValues<D> => {\n const values: Record<string, unknown> = Object.create(null) as Record<string, unknown>;\n for (let index = 0; index < names.length; index++)\n values[names[index]] = snapshotDependencyValue(sources[index]);\n return Object.freeze(values) as ProjectionValues<D>;\n};\n\n/** Compiles the shared named Projection dependency declaration contract. */\nexport const compileProjectionDependencies = (\n dependencies: unknown,\n label: string\n): CompiledProjectionDependencies => {\n const names: string[] = [];\n const projections: Projection<unknown>[] = [];\n for (const { name, value } of readNamedDependencyEntries(dependencies, label)) {\n const projection = value as Projection<unknown>;\n projectionRef(projection);\n names.push(name);\n projections.push(projection);\n }\n return Object.freeze({\n names: Object.freeze(names),\n projections: Object.freeze(projections),\n });\n};\n","import type { CollectionContext, SourceContext } from '@/projection/contract';\nimport type { KeyedDependencyRuntime } from './dependency';\n\ntype KeyedInvalidation = {\n readonly rebuild: boolean;\n readonly keys: Iterable<string>;\n readonly removed: readonly { readonly key: string }[];\n readonly structural: boolean;\n};\n\n/** Shared driver/dependency invalidation policy; owns no revisions or member cache. */\nexport const collectKeyedInvalidation = (\n driver: CollectionContext<string, unknown>,\n sources: readonly SourceContext[],\n dependencies: KeyedDependencyRuntime,\n reset: boolean\n): KeyedInvalidation => {\n const changed = dependencies.driverChanged(driver);\n const change = changed ? driver.change : undefined;\n if (reset || (changed && (!change || change.kind === 'reset')))\n return { rebuild: true, keys: driver.read.ids(), removed: [], structural: true };\n\n const dirty = new Set<string>();\n let removed: readonly { readonly key: string }[] = [];\n let structural = false;\n if (change?.kind === 'incremental') {\n removed = change.removed;\n for (const entry of change.added) dirty.add(entry.key);\n for (const entry of change.updated) dirty.add(entry.key);\n structural = Boolean(change.added.length || change.removed.length || change.order);\n }\n const all = dependencies.collectInvalidated(sources, dirty);\n if (!all) for (const key of dirty) if (!driver.read.has(key)) dirty.delete(key);\n return { rebuild: false, keys: all ? driver.read.ids() : dirty, removed, structural };\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 readonly cause: unknown;\n\n constructor(\n readonly phase: 'processor' | 'listener' | 'source' | 'blocked',\n cause: unknown\n ) {\n super(`Projection ${phase} failed.`, { cause });\n this.name = 'ProjectionError';\n this.cause = cause;\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 '@/projection/contract';\nimport { ProjectionDisposedError, ProjectionError } from '@/projection/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 OutputListener = (change?: CollectionChange<string, unknown>) => void;\n\nexport type OutputRecord = {\n readonly kind: 'value' | 'collection';\n readonly owner: ProducerRecord;\n context(active: () => boolean, consumer?: ProcessorRecord): SourceContext;\n acknowledge(consumer: ProcessorRecord): void;\n pending(consumer: ProcessorRecord): boolean;\n current(): unknown;\n revision(): number;\n reset(consumer?: ProcessorRecord): boolean;\n subscribe(listener: OutputListener): Unsubscribe;\n observe(listener: OutputListener): Unsubscribe;\n emit(\n call: (listener: OutputListener, change?: CollectionChange<string, unknown>) => void,\n force?: boolean\n ): void;\n finish(): void;\n hasConsumers(): boolean;\n forEachConsumer(run: (consumer: ProcessorRecord) => void): void;\n attachConsumer(consumer: ProcessorRecord): void;\n detachConsumer(consumer: ProcessorRecord): 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 evaluate(reset: boolean, cause: unknown, recreate?: boolean): 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' | 'input' | '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 dirty = new Set<ProducerRecord>();\n const queued = new Set<ProcessorRecord>();\n const completed = new Set<ProcessorRecord>();\n const emissions = new Set<OutputRecord>();\n const forced = new Set<OutputRecord>();\n const errors: ProjectionError[] = [];\n let reportingFailures: unknown[] = [];\n const guards = new Set<(locked: boolean) => 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(\n 'Projection cannot be re-entered during input callbacks, processing or notification.'\n );\n };\n const lock = (value: boolean) => guards.forEach(guard => guard(value));\n\n const markDirty = (producer: ProducerRecord): void => {\n const pending = [producer];\n for (let index = 0; index < pending.length; index++) {\n const current = pending[index];\n if (current.disposed || dirty.has(current)) continue;\n dirty.add(current);\n for (const output of current.outputs)\n output.forEachConsumer(consumer => pending.push(consumer));\n }\n };\n const enqueue = (processor: ProcessorRecord): void => {\n if (processor.disposed || queued.has(processor)) return;\n queued.add(processor);\n profile.projection('scheduledNodes');\n };\n\n const errorFor = (\n producer: ProducerRecord,\n cause: unknown,\n kind: ProjectionError['phase'] = producer.kind === 'source' ? 'source' : 'processor'\n ) => new ProjectionError(kind, 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 markDirty(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 propagate = (output: OutputRecord, force = false): void => {\n emissions.add(output);\n if (force) forced.add(output);\n output.forEachConsumer(enqueue);\n };\n\n const advanceSource = (source: SourceBoundaryRecord, cause: unknown): void => {\n pendingSources.delete(source);\n const wasFaulted = source.fault !== undefined;\n let changed = false;\n let force = false;\n if (!source.fault || source.recovering()) {\n try {\n // A fresh attempt may read the last valid source snapshot internally.\n // Public re-entry remains forbidden until this compute phase completes.\n source.fault = undefined;\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 if (changed || force) source.publish();\n if (source.fault || changed || force || wasFaulted) propagate(source.outputs[0], force);\n source.clear();\n };\n\n const advanceProcessor = (processor: ProcessorRecord, cause: unknown): void => {\n queued.delete(processor);\n const wasFaulted = processor.fault !== undefined;\n profile.projection('processedNodes');\n let changedOutputs: readonly OutputRecord[] = [];\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(processor));\n try {\n changedOutputs = processor.evaluate(reset, cause, wasFaulted);\n const failure = processor.dependencies.find(output => output.owner.fault)?.owner.fault;\n if (failure) throw failure;\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, true);\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 if (processor.fault) {\n processor.outputs.forEach(output => propagate(output));\n } else {\n if (changedOutputs.length) processor.publish();\n const recovered = wasFaulted && !processor.fault;\n (recovered ? processor.outputs : changedOutputs).forEach(output => propagate(output));\n }\n if (processor.fault || changedOutputs.length) profile.projection('publishedNodes');\n };\n\n // Iterative dependency-first traversal also supports deep projection chains.\n const advance = (target: ProducerRecord, cause: unknown): void => {\n const stack = [{ producer: target, dependency: 0 }];\n while (stack.length) {\n const frame = stack[stack.length - 1];\n const { producer } = frame;\n if (producer.disposed || !dirty.has(producer)) {\n dirty.delete(producer);\n stack.pop();\n continue;\n }\n if (producer.kind === 'processor') {\n let dependency: ProducerRecord | undefined;\n while (frame.dependency < producer.dependencies.length) {\n const candidate = producer.dependencies[frame.dependency++].owner;\n if (dirty.has(candidate)) {\n dependency = candidate;\n break;\n }\n }\n if (dependency) {\n stack.push({ producer: dependency, dependency: 0 });\n continue;\n }\n }\n stack.pop();\n dirty.delete(producer);\n if (producer.kind === 'source') advanceSource(producer, cause);\n else if (queued.has(producer)) {\n if (\n producer.fault ||\n producer.dependencies.some(output => output.owner.fault || output.pending(producer))\n )\n advanceProcessor(producer, cause);\n else {\n queued.delete(producer);\n producer.dependencies.forEach(output => output.acknowledge(producer));\n }\n }\n }\n };\n\n const compute = <T>(run: () => T): T => {\n phase = 'compute';\n lock(true);\n try {\n return run();\n } finally {\n lock(false);\n phase = 'idle';\n }\n };\n const settle = () => {\n if (disposed || depth || phase !== 'idle') return;\n const cause = settleCause();\n compute(() => {\n for (const producer of dirty) advance(producer, cause);\n });\n };\n const ensureCurrent = (output: OutputRecord): void => {\n assertActive();\n // Listener reads are safe after settlement; compute/input callbacks may not\n // use public reads to bypass dependency declarations or acceptance isolation.\n if (phase === 'notify') return;\n assertIdle();\n if (dirty.has(output.owner)) {\n const cause = settleCause();\n compute(() => advance(output.owner, cause));\n }\n };\n\n const flush = (): readonly ObserverError[] => {\n if (disposed || depth) return [];\n if (emissions.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(\n (listener, change) => {\n try {\n listener(change);\n } catch (cause) {\n errors.push(errorFor(output.owner, cause, 'listener'));\n }\n },\n forced.has(output) || Boolean(output.owner.fault)\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 emissions.forEach(output => output.finish());\n completed.forEach(processor => processor.clear());\n pendingSources.clear();\n queued.clear();\n completed.clear();\n emissions.clear();\n forced.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>(callback: () => T, options?: BatchOptions): T => {\n assertIdle();\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.hasConsumers()))\n throw new Error('Projection producer is still used by another processor.');\n producer.disposed = true;\n dirty.delete(producer);\n if (producer.kind === 'processor') {\n producer.dependencies.forEach(output => output.detachConsumer(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 const failures: unknown[] = [];\n try {\n producer.release();\n } catch (error) {\n failures.push(error);\n }\n try {\n producer.clear();\n } catch (error) {\n failures.push(error);\n }\n producer.outputs.forEach(output => emissions.delete(output));\n if (failures.length) throw failures[0];\n };\n\n return {\n assertActive,\n assertIdle,\n capture,\n settle,\n ensureCurrent,\n flush,\n run,\n registerGuard(guard: (locked: boolean) => void): Unsubscribe {\n assertActive();\n guards.add(guard);\n let registered = true;\n return () => {\n if (!registered) return;\n registered = false;\n guards.delete(guard);\n };\n },\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.attachConsumer(processor));\n },\n releaseProducer,\n nextId: () => sequence++,\n acceptInput<T>(callback: () => T): T {\n assertIdle();\n phase = 'input';\n lock(true);\n try {\n return callback();\n } finally {\n lock(false);\n phase = 'idle';\n }\n },\n initialize<T>(callback: () => T): T {\n assertIdle();\n return compute(callback);\n },\n batch,\n batchContext: () => activeBatch,\n dispose() {\n if (disposed) return;\n assertIdle();\n disposed = true;\n const failures: unknown[] = [];\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 dirty.clear();\n queued.clear();\n completed.clear();\n emissions.clear();\n forced.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","/** Allocation-free strict equality for ordered readonly arrays. */\nexport const sameArray = <T>(left: readonly T[], right: readonly T[]): boolean => {\n if (left === right) return true;\n if (left.length !== right.length) return false;\n for (let index = 0; index < left.length; index++) if (left[index] !== right[index]) return false;\n return true;\n};\n\n/** Owns an immutable shallow snapshot while reusing arrays that are already frozen. */\nexport const snapshotArray = <T>(values: readonly T[]): readonly T[] =>\n Object.isFrozen(values) ? values : Object.freeze([...values]);\n\n/** Compares an iterable with an ordered array without materializing the iterable. */\nexport const iterableMatchesArray = <T>(values: Iterable<T>, expected: readonly T[]): boolean => {\n let index = 0;\n for (const value of values) {\n if (index >= expected.length || value !== expected[index]) return false;\n index++;\n }\n return index === expected.length;\n};\n","import { sameArray, snapshotArray } from '@/value/array';\n\nexport type KeyRelation = {\n replaceOne(left: string, right: string | undefined): boolean;\n replace(left: string, right: readonly string[]): boolean;\n delete(left: string): boolean;\n forward(left: string): readonly string[] | undefined;\n reverse(right: string): ReadonlySet<string> | undefined;\n lefts(): IterableIterator<string>;\n rights(): IterableIterator<string>;\n clear(): void;\n};\n\n/** Runtime-local domain-neutral many-to-many keyed relation. */\nexport const createKeyRelation = (): KeyRelation => {\n const forward = new Map<string, readonly string[]>();\n const reverse = new Map<string, Set<string>>();\n\n const detach = (left: string, right: readonly string[]): void => {\n for (const key of right) {\n const dependents = reverse.get(key);\n dependents?.delete(left);\n if (dependents?.size === 0) reverse.delete(key);\n }\n };\n\n const attach = (left: string, right: readonly string[]): void => {\n for (const key of right) {\n const dependents = reverse.get(key);\n if (dependents) dependents.add(left);\n else reverse.set(key, new Set([left]));\n }\n };\n\n return {\n replaceOne(left, right) {\n const previous = forward.get(left);\n if (right === undefined) {\n if (!previous) return false;\n detach(left, previous);\n forward.delete(left);\n return true;\n }\n if (previous?.length === 1 && previous[0] === right) return false;\n if (previous) detach(left, previous);\n const next = Object.freeze([right]);\n forward.set(left, next);\n attach(left, next);\n return true;\n },\n replace(left, right) {\n const previous = forward.get(left);\n if (previous ? sameArray(previous, right) : right.length === 0) return false;\n if (previous) detach(left, previous);\n if (!right.length) {\n forward.delete(left);\n return true;\n }\n const next = snapshotArray(right);\n forward.set(left, next);\n attach(left, next);\n return true;\n },\n delete(left) {\n const previous = forward.get(left);\n if (!previous) return false;\n detach(left, previous);\n forward.delete(left);\n return true;\n },\n forward: left => forward.get(left),\n reverse: right => reverse.get(right),\n lefts: () => forward.keys(),\n rights: () => reverse.keys(),\n clear() {\n forward.clear();\n reverse.clear();\n },\n };\n};\n","import type { Synchronous } from '@/runtime/contract';\nimport { isPlainObject } from '@/value/record';\nimport { collectionView, mapRead } from '@/projection/collection/view';\nimport type { SourceContext } from '@/projection/contract';\nimport { readNamedDependencyEntries, snapshotDependencyValue } from '@/projection/dependency';\nimport {\n isProjection,\n outputDefinitionOf,\n type KeyedProjection,\n type Projection,\n} from '@/projection/definition';\nimport { assertSynchronous } from '@/projection/graph/scheduler';\nimport { createKeyRelation, type KeyRelation } from './relation';\n\nexport type SingularKeyedDependency<\n DriverKey extends string,\n DriverValue,\n SourceKey extends string,\n SourceValue,\n> = {\n readonly source: KeyedProjection<SourceKey, SourceValue>;\n readonly key: (value: DriverValue, key: DriverKey) => Synchronous<SourceKey | undefined>;\n readonly keys?: never;\n};\n\nexport type SameKeyedDependency<SourceKey extends string, SourceValue> = {\n readonly source: KeyedProjection<SourceKey, SourceValue>;\n readonly key?: never;\n readonly keys?: never;\n};\n\nexport type PluralKeyedDependency<\n DriverKey extends string,\n DriverValue,\n SourceKey extends string,\n SourceValue,\n> = {\n readonly source: KeyedProjection<SourceKey, SourceValue>;\n readonly keys: (value: DriverValue, key: DriverKey) => Synchronous<readonly SourceKey[]>;\n readonly key?: never;\n};\n\nexport type KeyedDependency<DriverKey extends string, DriverValue> =\n | (Projection<unknown> & {\n readonly source?: never;\n readonly key?: never;\n readonly keys?: never;\n })\n | SameKeyedDependency<string, unknown>\n | SingularKeyedDependency<DriverKey, DriverValue, string, unknown>\n | PluralKeyedDependency<DriverKey, DriverValue, string, unknown>;\n\nexport type KeyedDependencyRecord<DriverKey extends string, DriverValue> = Readonly<\n Record<string, KeyedDependency<DriverKey, DriverValue>>\n>;\n\ntype SameKeyConstraint<DriverKey extends string, Dependency> = Dependency extends {\n readonly source: KeyedProjection<infer SourceKey extends string, unknown>;\n}\n ? Dependency extends { readonly key: unknown } | { readonly keys: unknown }\n ? unknown\n : [DriverKey] extends [SourceKey]\n ? unknown\n : never\n : unknown;\n\nexport type KeyedDependencies<DriverKey extends string, DriverValue, D extends object> = {\n readonly [P in keyof D]: P extends string\n ? KeyedDependency<DriverKey, DriverValue> & SameKeyConstraint<DriverKey, D[P]>\n : never;\n};\n\nexport type KeyedDependencyValues<D extends object> = {\n readonly [P in keyof D]: D[P] extends {\n readonly source: KeyedProjection<infer K extends string, infer V>;\n readonly keys: (...args: never[]) => unknown;\n }\n ? ReadonlyMap<K, V>\n : D[P] extends {\n readonly source: KeyedProjection<infer _K extends string, infer V>;\n }\n ? V | undefined\n : D[P] extends Projection<infer T>\n ? T\n : never;\n};\n\ntype CompiledDynamicKeyedDependency =\n | {\n readonly kind: 'same';\n readonly projection: Projection<unknown>;\n }\n | {\n readonly kind: 'one';\n readonly projection: Projection<unknown>;\n readonly select: (value: unknown, key: string) => unknown;\n }\n | {\n readonly kind: 'many';\n readonly projection: Projection<unknown>;\n readonly select: (value: unknown, key: string) => unknown;\n };\n\ntype CompiledKeyedDependency =\n | {\n readonly name: string;\n readonly kind: 'global';\n readonly projection: Projection<unknown>;\n }\n | ({ readonly name: string } & CompiledDynamicKeyedDependency);\n\nexport type CompiledKeyedDependencies = {\n readonly entries: readonly CompiledKeyedDependency[];\n readonly projections: readonly Projection<unknown>[];\n};\n\nexport const outputKind = (projection: Projection<unknown>): 'value' | 'collection' =>\n outputDefinitionOf(projection).kind;\n\nexport const assertKeyedProjection = (projection: Projection<unknown>, role: string): void => {\n if (outputKind(projection) !== 'collection')\n throw new TypeError(`${role} must be a keyed collection projection.`);\n};\n\nconst compileDynamicDependency = (\n value: unknown,\n label: string\n): CompiledDynamicKeyedDependency => {\n if (!isPlainObject(value) || isProjection(value))\n throw new TypeError(`${label} dependencies must be projections or keyed lookups.`);\n const candidate: { source?: unknown; key?: unknown; keys?: unknown } = {};\n const allowed = new Set(['source', 'key', 'keys']);\n let hasKey = false;\n let hasKeys = false;\n for (const name of Reflect.ownKeys(value)) {\n if (typeof name !== 'string' || !allowed.has(name))\n throw new TypeError(`${label} dynamic keyed dependency contains an unknown property.`);\n const descriptor = Object.getOwnPropertyDescriptor(value, name);\n if (!descriptor?.enumerable || !('value' in descriptor))\n throw new TypeError(`${label} dynamic keyed dependency must use enumerable data properties.`);\n candidate[name as 'source' | 'key' | 'keys'] = descriptor.value;\n if (name === 'key') hasKey = true;\n if (name === 'keys') hasKeys = true;\n }\n if (!isProjection(candidate.source))\n throw new TypeError(`${label} dynamic keyed dependency source must be a projection.`);\n if (hasKey && hasKeys)\n throw new TypeError(`${label} dynamic keyed dependency must not declare both key and keys.`);\n assertKeyedProjection(candidate.source, `${label} dynamic keyed dependency source`);\n if (!hasKey && !hasKeys)\n return {\n kind: 'same',\n projection: candidate.source,\n };\n const singular = hasKey;\n const selector = singular ? candidate.key : candidate.keys;\n if (typeof selector !== 'function')\n throw new TypeError(`${label} dynamic keyed dependency selector must be a function.`);\n return singular\n ? {\n kind: 'one',\n projection: candidate.source,\n select: selector as (value: unknown, key: string) => unknown,\n }\n : {\n kind: 'many',\n projection: candidate.source,\n select: selector as (value: unknown, key: string) => unknown,\n };\n};\n\nexport const compileKeyedDependencies = (\n driver: Projection<unknown>,\n dependencySpecs: KeyedDependencyRecord<string, unknown> | undefined,\n label: string\n): CompiledKeyedDependencies => {\n const entries: CompiledKeyedDependency[] = [];\n const projections: Projection<unknown>[] = [driver];\n if (dependencySpecs === undefined)\n return Object.freeze({\n entries: Object.freeze(entries),\n projections: Object.freeze(projections),\n });\n for (const { name, value: dependency } of readNamedDependencyEntries(dependencySpecs, label)) {\n if (isProjection(dependency)) {\n entries.push(Object.freeze({ name, kind: 'global' as const, projection: dependency }));\n projections.push(dependency);\n continue;\n }\n const dynamic = compileDynamicDependency(dependency, label);\n entries.push(Object.freeze({ name, ...dynamic }));\n projections.push(dynamic.projection);\n }\n return Object.freeze({\n entries: Object.freeze(entries),\n projections: Object.freeze(projections),\n });\n};\n\nconst selectedKey = (\n dependency: Extract<CompiledDynamicKeyedDependency, { readonly kind: 'one' }>,\n value: unknown,\n key: string\n): string | undefined => {\n const result = dependency.select(value, key);\n assertSynchronous(result);\n if (result === undefined) return undefined;\n if (typeof result !== 'string')\n throw new TypeError('Dynamic keyed dependency key must be a string or undefined.');\n return result;\n};\n\nconst selectedKeys = (\n dependency: Extract<CompiledDynamicKeyedDependency, { readonly kind: 'many' }>,\n value: unknown,\n key: string\n): readonly string[] => {\n const result = dependency.select(value, key);\n assertSynchronous(result);\n if (!Array.isArray(result))\n throw new TypeError('Dynamic keyed dependency keys must be an array of strings.');\n const seen = new Set<string>();\n for (const selected of result) {\n if (typeof selected !== 'string')\n throw new TypeError('Dynamic keyed dependency keys must contain only strings.');\n if (seen.has(selected))\n throw new TypeError('Dynamic keyed dependency keys must not contain duplicates.');\n seen.add(selected);\n }\n return result as readonly string[];\n};\n\nexport type KeyedDependencyRuntime = {\n prepare(sources: readonly SourceContext[], reset: boolean): void;\n resolve(\n driverValue: unknown,\n driverKey: string,\n sources: readonly SourceContext[]\n ): Readonly<Record<string, unknown>>;\n driverChanged(source: SourceContext): boolean;\n collectInvalidated(sources: readonly SourceContext[], dirty: Set<string>): boolean;\n remove(driverKey: string): void;\n clearBindings(): void;\n remember(sources: readonly SourceContext[]): void;\n release(): void;\n};\n\nconst emptyValues: Readonly<Record<string, unknown>> = Object.freeze(\n Object.create(null) as Record<string, unknown>\n);\n\nexport const createKeyedDependencyRuntime = (\n compiled: CompiledKeyedDependencies\n): KeyedDependencyRuntime => {\n type GlobalDependencyState = {\n readonly kind: 'global';\n readonly entry: Extract<CompiledKeyedDependency, { readonly kind: 'global' }>;\n readonly sourceIndex: number;\n revision: number;\n globalValue: unknown;\n };\n type SameDependencyState = {\n readonly kind: 'same';\n readonly entry: Extract<CompiledKeyedDependency, { readonly kind: 'same' }>;\n readonly sourceIndex: number;\n revision: number;\n };\n type DynamicDependencyState = {\n readonly kind: 'dynamic';\n readonly entry: Extract<CompiledKeyedDependency, { readonly kind: 'one' | 'many' }>;\n readonly sourceIndex: number;\n readonly relation: KeyRelation;\n revision: number;\n };\n type DependencyState = GlobalDependencyState | SameDependencyState | DynamicDependencyState;\n const states: DependencyState[] = compiled.entries.map((entry, index) => {\n const sourceIndex = index + 1;\n if (entry.kind === 'global')\n return { kind: 'global', entry, sourceIndex, revision: -1, globalValue: undefined };\n if (entry.kind === 'same') return { kind: 'same', entry, sourceIndex, revision: -1 };\n return {\n kind: 'dynamic',\n entry,\n sourceIndex,\n relation: createKeyRelation(),\n revision: -1,\n };\n });\n let driverRevision = -1;\n\n return {\n prepare(sources, reset) {\n for (const state of states) {\n if (state.kind !== 'global') continue;\n const source = sources[state.sourceIndex];\n if (reset || state.revision !== source.revision)\n state.globalValue = snapshotDependencyValue(source);\n }\n },\n resolve(driverValue, driverKey, sources) {\n if (!states.length) return emptyValues;\n const values = Object.create(null) as Record<string, unknown>;\n for (const state of states) {\n if (state.kind === 'global') {\n values[state.entry.name] = state.globalValue;\n continue;\n }\n const source = sources[state.sourceIndex];\n if (source.kind !== 'collection')\n throw new TypeError('Dynamic keyed dependency resolved to a non-collection source.');\n if (state.kind === 'same') {\n values[state.entry.name] = source.read.get(driverKey);\n continue;\n }\n const dependency = state.entry;\n if (dependency.kind === 'one') {\n const selected = selectedKey(dependency, driverValue, driverKey);\n state.relation.replaceOne(driverKey, selected);\n values[dependency.name] = selected === undefined ? undefined : source.read.get(selected);\n continue;\n }\n const keys = selectedKeys(dependency, driverValue, driverKey);\n state.relation.replace(driverKey, keys);\n const selected = new Map<string, unknown>();\n for (const key of keys) if (source.read.has(key)) selected.set(key, source.read.get(key));\n values[dependency.name] = collectionView(mapRead(selected));\n }\n return Object.freeze(values);\n },\n driverChanged(source) {\n return driverRevision !== source.revision;\n },\n collectInvalidated(sources, dirty) {\n let all = false;\n for (const state of states) {\n const source = sources[state.sourceIndex];\n if (state.revision === source.revision) continue;\n if (state.kind === 'global') {\n all = true;\n continue;\n }\n if (source.kind !== 'collection' || !source.change || source.change.kind === 'reset') {\n all = true;\n continue;\n }\n if (state.kind === 'same') {\n for (const entry of source.change.added) dirty.add(entry.key);\n for (const entry of source.change.updated) dirty.add(entry.key);\n for (const entry of source.change.removed) dirty.add(entry.key);\n continue;\n }\n for (const entry of source.change.added)\n for (const dependent of state.relation.reverse(entry.key) ?? []) dirty.add(dependent);\n for (const entry of source.change.updated)\n for (const dependent of state.relation.reverse(entry.key) ?? []) dirty.add(dependent);\n for (const entry of source.change.removed)\n for (const dependent of state.relation.reverse(entry.key) ?? []) dirty.add(dependent);\n }\n return all;\n },\n remove(driverKey) {\n for (const state of states) if (state.kind === 'dynamic') state.relation.delete(driverKey);\n },\n clearBindings() {\n for (const state of states) if (state.kind === 'dynamic') state.relation.clear();\n },\n remember(sources) {\n driverRevision = sources[0]?.revision ?? -1;\n for (const state of states) state.revision = sources[state.sourceIndex].revision;\n },\n release() {\n for (const state of states) {\n state.revision = -1;\n if (state.kind === 'global') state.globalValue = undefined;\n else if (state.kind === 'dynamic') state.relation.clear();\n }\n driverRevision = -1;\n },\n };\n};\n","import type { CollectionChange } from '@/projection/contract';\nimport { sameArray, snapshotArray } from '@/value/array';\n\ntype Added<K extends string, V> = { readonly key: K; readonly after: V };\ntype Updated<K extends string, V> = {\n readonly key: K;\n readonly before: V;\n readonly after: V;\n};\ntype Removed<K extends string, V> = { readonly key: K; readonly before: V };\n\nconst transitionContains = <K extends string>(\n entries: readonly { readonly key: K }[],\n key: K\n): boolean => {\n for (const entry of entries) if (entry.key === key) return true;\n return false;\n};\n\nconst transitionSet = <K extends string>(\n entries: readonly { readonly key: K }[]\n): ReadonlySet<K> | undefined => {\n // Small net membership changes are overwhelmingly common. Linear lookup avoids\n // allocating a Set while keeping large batches O(n).\n if (entries.length <= 4) return undefined;\n const keys = new Set<K>();\n for (const entry of entries) keys.add(entry.key);\n return keys;\n};\n\nconst nextExcluding = <K extends string>(\n iterator: Iterator<K>,\n excluded: readonly { readonly key: K }[],\n index: ReadonlySet<K> | undefined\n): IteratorResult<K> => {\n while (true) {\n const next = iterator.next();\n if (next.done || !(index ? index.has(next.value) : transitionContains(excluded, next.value)))\n return next;\n }\n};\n\n/** Compares common-member order from known transitions without materializing common arrays. */\nconst transitionOrderChanged = <K extends string>(\n before: Iterable<K>,\n after: Iterable<K>,\n removed: readonly { readonly key: K }[],\n added: readonly { readonly key: K }[]\n): boolean => {\n const removedKeys = transitionSet(removed);\n const addedKeys = transitionSet(added);\n const beforeIterator = before[Symbol.iterator]();\n const afterIterator = after[Symbol.iterator]();\n while (true) {\n const left = nextExcluding(beforeIterator, removed, removedKeys);\n const right = nextExcluding(afterIterator, added, addedKeys);\n if (left.done || right.done) return left.done !== right.done;\n if (left.value !== right.value) return true;\n }\n};\n\nconst nextPresentIn = <K, V>(\n iterator: Iterator<K>,\n membership: ReadonlyMap<K, V>\n): IteratorResult<K> => {\n while (true) {\n const next = iterator.next();\n if (next.done || membership.has(next.value)) return next;\n }\n};\n\n/** Compares common-member order between two map snapshots without key snapshots or closures. */\nconst mapOrderChanged = <K, V>(before: ReadonlyMap<K, V>, after: ReadonlyMap<K, V>): boolean => {\n const beforeIterator = before.keys();\n const afterIterator = after.keys();\n while (true) {\n const left = nextPresentIn(beforeIterator, after);\n const right = nextPresentIn(afterIterator, before);\n if (left.done || right.done) return left.done !== right.done;\n if (left.value !== right.value) return true;\n }\n};\n\nconst sealIncrementalChange = <K extends string, V>(\n added: Added<K, V>[],\n updated: Updated<K, V>[],\n removed: Removed<K, V>[],\n order?: { readonly before: readonly K[]; readonly after: readonly K[] }\n): CollectionChange<K, V> | undefined => {\n if (!added.length && !updated.length && !removed.length && !order) return undefined;\n return Object.freeze({\n kind: 'incremental' as const,\n added: Object.freeze(added),\n updated: Object.freeze(updated),\n removed: Object.freeze(removed),\n ...(order\n ? {\n order: Object.freeze({\n before: snapshotArray(order.before),\n after: snapshotArray(order.after),\n }),\n }\n : {}),\n });\n};\n\n/** Builds the canonical incremental CollectionChange from already-known net transitions. */\nexport const createCollectionChange = <K extends string, V>(input: {\n readonly added: Added<K, V>[];\n readonly updated: Updated<K, V>[];\n readonly removed: Removed<K, V>[];\n readonly beforeOrder: readonly K[];\n readonly afterOrder: readonly K[];\n}): CollectionChange<K, V> | undefined => {\n let orderChanged = false;\n if (input.beforeOrder !== input.afterOrder) {\n if (!input.added.length && !input.removed.length)\n orderChanged = !sameArray(input.beforeOrder, input.afterOrder);\n else\n orderChanged = transitionOrderChanged(\n input.beforeOrder,\n input.afterOrder,\n input.removed,\n input.added\n );\n }\n return sealIncrementalChange(\n input.added,\n input.updated,\n input.removed,\n orderChanged ? { before: input.beforeOrder, after: input.afterOrder } : undefined\n );\n};\n\n/** Exact fallback diff between two published map-like snapshots. */\nexport const diffCollection = <K extends string, V>(\n previous: ReadonlyMap<K, V>,\n current: ReadonlyMap<K, V>,\n isEqual: (previous: V, next: V) => boolean = Object.is\n): CollectionChange<K, V> | undefined => {\n const added: Added<K, V>[] = [];\n const updated: Updated<K, V>[] = [];\n const removed: Removed<K, V>[] = [];\n for (const [key, before] of previous) {\n if (!current.has(key)) removed.push({ key, before });\n else {\n const after = current.get(key) as V;\n if (!isEqual(before, after)) updated.push({ key, before, after });\n }\n }\n for (const [key, after] of current) if (!previous.has(key)) added.push({ key, after });\n const orderChanged = mapOrderChanged(previous, current);\n return sealIncrementalChange(\n added,\n updated,\n removed,\n orderChanged\n ? {\n before: Object.freeze([...previous.keys()]),\n after: Object.freeze([...current.keys()]),\n }\n : undefined\n );\n};\n\nconst changedKeys = function* <K extends string, V>(\n change: Extract<CollectionChange<K, V>, { readonly kind: 'incremental' }>\n): IterableIterator<K> {\n if ((change as CollectionChange<K, V>).kind !== 'incremental')\n throw new TypeError('collectionChange.keys requires an incremental CollectionChange.');\n for (const entry of change.added) yield entry.key;\n for (const entry of change.updated) yield entry.key;\n for (const entry of change.removed) yield entry.key;\n};\n\nexport const collectionChange: {\n readonly keys: <K extends string, V>(\n change: Extract<CollectionChange<K, V>, { readonly kind: 'incremental' }>\n ) => Iterable<K>;\n} = Object.freeze({ keys: changedKeys });\n\nexport const collectionHasStructuralChange = <K extends string, V>(\n change: CollectionChange<K, V>\n): boolean =>\n change.kind === 'reset' || Boolean(change.added.length || change.removed.length || change.order);\n\nexport const collectionChangeTouchesKey = <K extends string, V>(\n change: Extract<CollectionChange<K, V>, { readonly kind: 'incremental' }>,\n key: K\n): boolean => {\n for (const entry of change.added) if (entry.key === key) return true;\n for (const entry of change.updated) if (entry.key === key) return true;\n for (const entry of change.removed) if (entry.key === key) return true;\n return false;\n};\n\nexport const collectionChangeIntersects = <K extends string, V>(\n change: Extract<CollectionChange<K, V>, { readonly kind: 'incremental' }>,\n keys: ReadonlySet<K>\n): boolean => {\n for (const entry of change.added) if (keys.has(entry.key)) return true;\n for (const entry of change.updated) if (keys.has(entry.key)) return true;\n for (const entry of change.removed) if (keys.has(entry.key)) return true;\n return false;\n};\n","import { collectKeyedInvalidation } from './invalidation';\nimport { defineProcessor, type KeyedProjection } from '@/projection/definition';\nimport { assertSynchronous } from '@/projection/graph/scheduler';\nimport {\n assertKeyedProjection,\n compileKeyedDependencies,\n createKeyedDependencyRuntime,\n type KeyedDependencyRecord,\n} from './dependency';\n\nexport const keyedAbsent = Symbol('keyed-transform-absent');\nexport type KeyedTransformResult<T> = T | typeof keyedAbsent;\n\nexport type KeyedTransformContext<K extends string, V, State> = {\n readonly key: K;\n readonly value: V;\n readonly dependencies: Readonly<Record<string, unknown>>;\n readonly state: State;\n readonly reset: boolean;\n readonly cause: unknown;\n};\n\nexport type KeyedTransformDefinition<K extends string, V, T, State> = {\n readonly source: KeyedProjection<K, V>;\n readonly dependencies?: KeyedDependencyRecord<K, V>;\n readonly equality?: (previous: T, next: T) => boolean;\n readonly name: string;\n readonly state?: (value: V, key: K) => State;\n readonly evaluate: (context: KeyedTransformContext<K, V, State>) => KeyedTransformResult<T>;\n};\n\n/** Shared driver-keyed lifecycle for pure and retained keyed transforms. */\nexport const createKeyedTransform = <K extends string, V, T, State = undefined>(\n definition: KeyedTransformDefinition<K, V, T, State>\n): KeyedProjection<K, T> => {\n assertKeyedProjection(definition.source, `${definition.name} source`);\n const compiled = compileKeyedDependencies(\n definition.source,\n definition.dependencies as KeyedDependencyRecord<string, unknown> | undefined,\n definition.name\n );\n const [projection] = defineProcessor({\n dependencies: compiled.projections,\n outputs: [\n {\n kind: 'collection',\n equality: (definition.equality ?? Object.is) as (\n previous: unknown,\n next: unknown\n ) => boolean,\n },\n ],\n create: () => {\n const dependencies = createKeyedDependencyRuntime(compiled);\n const states = new Map<string, State>();\n\n const dropState = (key: string): void => {\n states.delete(key);\n dependencies.remove(key);\n };\n\n return {\n evaluate: evaluation => {\n const driver = evaluation.sources[0];\n const output = evaluation.outputs[0];\n if (driver.kind !== 'collection' || output.kind !== 'collection')\n throw new Error(`${definition.name} requires collection input and output.`);\n const invalidation = collectKeyedInvalidation(\n driver,\n evaluation.sources,\n dependencies,\n evaluation.reset\n );\n dependencies.prepare(evaluation.sources, invalidation.rebuild);\n\n const stateFor = (key: string, value: V): State => {\n if (states.has(key)) return states.get(key) as State;\n const state = definition.state\n ? definition.state(value, key as K)\n : (undefined as State);\n assertSynchronous(state);\n if (definition.state) states.set(key, state);\n return state;\n };\n\n const project = (key: string): boolean => {\n if (!driver.read.has(key)) return false;\n const value = driver.read.get(key) as V;\n const beforePresent = output.previous.has(key);\n const next = definition.evaluate({\n key: key as K,\n value,\n dependencies: dependencies.resolve(value, key, evaluation.sources),\n state: stateFor(key, value),\n reset: evaluation.reset,\n cause: evaluation.cause,\n });\n assertSynchronous(next);\n if (next === keyedAbsent) output.output.remove(key);\n else output.output.set(key, next);\n return beforePresent !== output.next.has(key);\n };\n\n if (invalidation.rebuild) {\n dependencies.clearBindings();\n const ids = driver.read.ids();\n for (const key of states.keys()) if (!driver.read.has(key)) states.delete(key);\n if (!evaluation.reset)\n for (const key of output.previous.ids())\n if (!driver.read.has(key)) output.output.remove(key);\n for (const key of ids) project(key);\n output.output.order(ids.filter(key => output.next.has(key)));\n dependencies.remember(evaluation.sources);\n return;\n }\n\n let membershipChanged = false;\n for (const entry of invalidation.removed) {\n membershipChanged ||= output.previous.has(entry.key);\n output.output.remove(entry.key);\n dropState(entry.key);\n }\n for (const key of invalidation.keys) {\n const changedMembership = project(key);\n membershipChanged ||= changedMembership;\n }\n if (invalidation.structural || membershipChanged)\n output.output.order(driver.read.ids().filter(key => output.next.has(key)));\n dependencies.remember(evaluation.sources);\n },\n release: () => {\n states.clear();\n dependencies.release();\n },\n };\n },\n name: definition.name,\n });\n return projection as KeyedProjection<K, T>;\n};\n"],"mappings":";AAkDA,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,YAAY;EACV,kBAAkB;EAGlB,uBAAuB;EAGxB;CACD,iBAAiB;EACf,YAAY;EAGZ,QAAQ,UAAkB;EA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