@agentshouse/mdruntime 0.1.0-alpha.7 → 0.1.0-alpha.8
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/dist/adapter.d.ts +40 -4
- package/dist/adapter.d.ts.map +1 -1
- package/dist/adapter.js.map +1 -1
- package/dist/bootstrap.d.ts +3 -1
- package/dist/bootstrap.d.ts.map +1 -1
- package/dist/bootstrap.js +12 -6
- package/dist/bootstrap.js.map +1 -1
- package/dist/change.d.ts +1 -0
- package/dist/change.d.ts.map +1 -1
- package/dist/change.js.map +1 -1
- package/dist/collection.d.ts +8 -3
- package/dist/collection.d.ts.map +1 -1
- package/dist/collection.js +66 -28
- package/dist/collection.js.map +1 -1
- package/dist/connection.d.ts +10 -3
- package/dist/connection.d.ts.map +1 -1
- package/dist/connection.js +330 -21
- package/dist/connection.js.map +1 -1
- package/dist/identity.d.ts +2 -0
- package/dist/identity.d.ts.map +1 -0
- package/dist/identity.js +16 -0
- package/dist/identity.js.map +1 -0
- package/dist/index.d.ts +4 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/memory.d.ts +2 -0
- package/dist/memory.d.ts.map +1 -1
- package/dist/memory.js +27 -6
- package/dist/memory.js.map +1 -1
- package/dist/model.d.ts +70 -0
- package/dist/model.d.ts.map +1 -0
- package/dist/model.js +28 -0
- package/dist/model.js.map +1 -0
- package/dist/query.d.ts +12 -0
- package/dist/query.d.ts.map +1 -0
- package/dist/query.js +18 -0
- package/dist/query.js.map +1 -0
- package/dist/refresh.d.ts +2 -1
- package/dist/refresh.d.ts.map +1 -1
- package/dist/refresh.js +6 -4
- package/dist/refresh.js.map +1 -1
- package/dist/replica.d.ts +3 -1
- package/dist/replica.d.ts.map +1 -1
- package/dist/replica.js +10 -6
- package/dist/replica.js.map +1 -1
- package/dist/save.d.ts +6 -1
- package/dist/save.d.ts.map +1 -1
- package/dist/save.js +31 -9
- package/dist/save.js.map +1 -1
- package/dist/store.d.ts +7 -2
- package/dist/store.d.ts.map +1 -1
- package/dist/store.js +1 -1
- package/dist/store.js.map +1 -1
- package/package.json +1 -1
package/dist/connection.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/workspace/packages/mdruntime/src/connection.ts"],"sourcesContent":["import {\n query as evaluate,\n type QueryOptions,\n type QueryResult,\n type QueryRoom,\n} from '@agentshouse/query';\nimport {\n ROOM_CONTRACT_VERSION,\n VERSION_1_CAPABILITIES,\n type ActionResult,\n type Adapter,\n type AdapterFailure,\n type Authorization,\n type Capability,\n type DiscoveredRoom,\n type HistoryResult,\n type MutationResult,\n type ProviderLimit,\n} from './adapter.js';\nimport { bootstrapRoom } from './bootstrap.js';\nimport type { Change, ChangeBatch } from './change.js';\nimport { MD_MODEL, PRESENTED, type MdType } from './collection.js';\nimport { createLog } from './log.js';\nimport {\n queuedOutcome,\n refused,\n type QueueEntry,\n type QueueOutcome,\n type SubmissionOutcome,\n} from './outcome.js';\nimport { refreshRoom } from './refresh.js';\nimport { buildBatch, type SaveRefusal } from './save.js';\nimport {\n applyReturned,\n readConfirmed,\n replicaOf,\n type ConfirmedLayer,\n type Replica,\n} from './replica.js';\nimport {\n settled,\n same,\n saving,\n STARTING,\n transferring,\n type CycleProgress,\n type SyncStatus,\n} from './status.js';\nimport { detectStorageLoss, nextGeneration } from './durability.js';\nimport { openReplicaStore, type ReplicaStore } from './store.js';\nimport { unconfirmed, type Unconfirmed } from './transfer.js';\n\nconst DEFAULT_DISCOVERY_INTERVAL_MS = 60_000;\n\nconst knownCapabilities = new Set<string>(VERSION_1_CAPABILITIES);\n\nexport type AppRoom = {\n name: string;\n locator: string;\n writeGrants: readonly string[];\n providerOwnedPaths: readonly string[];\n roomVersion: string | null;\n synchronizationAvailable: boolean;\n};\n\nexport type ConnectionRefusalReason =\n | 'no-matching-version'\n | 'missing-required-guarantee'\n | 'md-model-version-mismatch'\n | 'revoked-authorization';\n\nexport type ConnectionRefusal = {\n reason: ConnectionRefusalReason;\n reauthorizationOffered: boolean;\n};\n\nexport type MdRuntimeOptions = {\n adapter: Adapter;\n requiredGuarantees: readonly string[];\n authorization?: Authorization;\n discoveryIntervalMs?: number;\n signal?: AbortSignal;\n};\n\nexport type SaveResult = { outcome: 'saved'; id: string } | ({ outcome: 'refused' } & SaveRefusal);\n\nexport type DraftEntry = {\n readonly locator: string;\n readonly path: string;\n readonly content: unknown;\n};\n\nexport type DraftSurface = {\n list(): Promise<readonly DraftEntry[]>;\n read(locator: string, path: string): unknown;\n replace(locator: string, path: string, content: unknown): Promise<void>;\n discard(locator: string, path: string): Promise<void>;\n};\n\nexport type QueueSurface = {\n discard(locator: string, identifier: string): Promise<void>;\n};\n\nexport type HistoryQuery = {\n revision?: string;\n pageToken?: string;\n};\n\nexport type CallResult = ActionResult | { kind: 'undeclared' };\n\nexport type MdRuntime = {\n rooms(): readonly AppRoom[];\n query(options?: QueryOptions): QueryResult;\n types(locator: string): readonly MdType[];\n syncStatus(): SyncStatus;\n draft: DraftSurface;\n save(locator: string, changes: readonly Change[], replacing?: string): Promise<SaveResult>;\n outcome(identifier: string): SubmissionOutcome | null;\n queue: QueueSurface;\n history(locator: string, path: string, query?: HistoryQuery): Promise<HistoryResult>;\n call(name: string, input: unknown): Promise<CallResult>;\n log(): string;\n storageLoss(): string | null;\n observe: {\n (topic: 'rooms', listener: (rooms: readonly AppRoom[]) => void): () => void;\n (\n topic: 'connection-refusal',\n listener: (refusal: ConnectionRefusal | null) => void,\n ): () => void;\n (topic: 'storage-loss', listener: (statement: string | null) => void): () => void;\n (topic: 'sync-status', listener: (status: SyncStatus) => void): () => void;\n (topic: 'query', query: QueryOptions, listener: (result: QueryResult) => void): () => void;\n (\n topic: 'queue',\n locator: string,\n listener: (entries: readonly QueueEntry[]) => void,\n ): () => void;\n (topic: 'drafts', listener: (drafts: readonly DraftEntry[]) => void): () => void;\n };\n reauthorize(): Promise<void>;\n};\n\ntype QuerySubscription = {\n query: QueryOptions;\n notify: (result: QueryResult) => void;\n};\n\ntype QueueSubscription = {\n locator: string;\n notify: (entries: readonly QueueEntry[]) => void;\n};\n\ntype DraftSubscription = {\n notify: (drafts: readonly DraftEntry[]) => void;\n ready: boolean;\n};\n\ntype Withheld = AdapterFailure | Unconfirmed;\n\nexport function createMdRuntime(options: MdRuntimeOptions): MdRuntime {\n const period = options.discoveryIntervalMs ?? DEFAULT_DISCOVERY_INTERVAL_MS;\n let authorization: Authorization | undefined = options.authorization;\n let opening: Promise<ReplicaStore> | undefined;\n let store: ReplicaStore | undefined;\n const replicas = new Map<string, Replica>();\n const drafts = new Map<string, Map<string, unknown>>();\n const outcomes = new Map<string, SubmissionOutcome>();\n let limits: readonly ProviderLimit[] = [];\n let capabilities: readonly Capability[] = [];\n const rooms = new Map<string, AppRoom>();\n const unreadable = new Set<string>();\n let refusal: ConnectionRefusal | null = null;\n let storageLoss: string | null = null;\n let status: SyncStatus = STARTING;\n let discoveryPaused = false;\n let timer: ReturnType<typeof setInterval> | undefined;\n let closed = false;\n let chain: Promise<void> = Promise.resolve();\n let mutations: Promise<unknown> = Promise.resolve();\n let inflight = false;\n let queued = false;\n const roomListeners = new Set<(rooms: readonly AppRoom[]) => void>();\n const refusalListeners = new Set<(refusal: ConnectionRefusal | null) => void>();\n const storageLossListeners = new Set<(statement: string | null) => void>();\n const statusListeners = new Set<(status: SyncStatus) => void>();\n const querySubscriptions = new Set<QuerySubscription>();\n const queueSubscriptions = new Set<QueueSubscription>();\n const draftListeners = new Set<DraftSubscription>();\n const journal = createLog();\n let notifyReady = () => {};\n const ready = new Promise<void>((resolve) => {\n notifyReady = resolve;\n });\n let leader = typeof window === 'undefined';\n let applyingRemote = false;\n let releaseLeadership = () => {};\n const channel = typeof window !== 'undefined' ? new BroadcastChannel('mdruntime') : undefined;\n\n function draftContent(locator: string, path: string) {\n return drafts.get(locator)?.get(path);\n }\n\n function rememberDraft(locator: string, path: string, content: unknown) {\n const room = drafts.get(locator) ?? new Map<string, unknown>();\n room.set(path, content);\n drafts.set(locator, room);\n }\n\n function forgetDraft(locator: string, path: string) {\n const room = drafts.get(locator);\n if (room === undefined) return;\n room.delete(path);\n if (room.size === 0) drafts.delete(locator);\n }\n\n function snapshotDrafts(): readonly DraftEntry[] {\n const entries: DraftEntry[] = [];\n for (const [locator, room] of drafts) {\n for (const [path, content] of room) {\n entries.push({ locator, path, content: structuredClone(content) });\n }\n }\n entries.sort((left, right) => {\n if (left.locator !== right.locator) return left.locator < right.locator ? -1 : 1;\n if (left.path !== right.path) return left.path < right.path ? -1 : 1;\n return 0;\n });\n return entries;\n }\n\n async function readDrafts(opened: ReplicaStore) {\n await acrossTabs('mdruntime-replica', async () => {\n await hydrate(opened);\n });\n return snapshotDrafts();\n }\n\n function publishDrafts(waitingOnly: boolean) {\n if (closed) return;\n const value = snapshotDrafts();\n for (const listener of draftListeners) {\n if (waitingOnly && listener.ready) continue;\n listener.ready = true;\n listener.notify(value);\n }\n }\n\n function emitDrafts() {\n publishDrafts(false);\n }\n\n function releaseWaitingDrafts() {\n publishDrafts(true);\n }\n\n function commitDraft(work: (local: ReplicaStore) => Promise<void>) {\n return exclusive(async () => {\n const local = await openLocal();\n await acrossTabs('mdruntime-replica', async () => {\n await hydrate(local);\n await work(local);\n });\n }).then(() => {\n emitDrafts();\n announce();\n });\n }\n\n function pending() {\n return [...replicas.values()].some((replica) => replica.queue.length > 0);\n }\n\n function attention() {\n return [...replicas.values()].some((replica) => {\n const head = replica.queue[0];\n return head !== undefined && refused(outcomes.get(head.id));\n });\n }\n\n function storedOutcomes(batches: readonly ChangeBatch[]) {\n const stored: Record<string, QueueOutcome> = {};\n for (const batch of batches) {\n const outcome = queuedOutcome(outcomes.get(batch.id));\n if (outcome.kind !== 'pending') stored[batch.id] = outcome;\n }\n return stored;\n }\n\n async function persistQueue(\n local: ReplicaStore,\n locator: string,\n batches: readonly ChangeBatch[],\n ) {\n await local.writeQueue({\n locator,\n batches,\n outcomes: storedOutcomes(batches),\n });\n announce();\n }\n\n function listed(): readonly AppRoom[] {\n return [...rooms.values()];\n }\n\n function queryRooms(): readonly QueryRoom[] {\n return [...replicas.values()].map((replica) => ({\n room: replica.confirmed.record.locator,\n roomVersion: replica.confirmed.record.roomVersion,\n documents: replica.visible.collection.documents,\n }));\n }\n\n function emitRooms() {\n const value = listed();\n for (const listener of roomListeners) listener(value);\n }\n\n function emitRefusal() {\n for (const listener of refusalListeners) listener(refusal);\n }\n\n function emitStorageLoss() {\n for (const listener of storageLossListeners) listener(storageLoss);\n }\n\n function announce(type: 'changed' | 'enqueue' | 'hello' = 'changed') {\n if (applyingRemote || channel === undefined) return;\n if (type === 'hello') {\n channel.postMessage({ type: 'hello' });\n return;\n }\n channel.postMessage({ type, status });\n }\n\n function adopt(next: SyncStatus) {\n if (closed || same(status, next)) return;\n status = next;\n for (const listener of statusListeners) listener(status);\n }\n\n function moveTo(next: SyncStatus) {\n if (closed || same(status, next)) return;\n adopt(next);\n announce();\n }\n\n function visible(request: QueryOptions): QueryResult {\n return evaluate(queryRooms(), {\n ...request,\n selector: { $and: [PRESENTED, request.selector ?? {}] },\n });\n }\n\n function emitVisible() {\n for (const subscription of querySubscriptions) {\n subscription.notify(visible(subscription.query));\n }\n }\n\n function entriesOf(locator: string): readonly QueueEntry[] {\n const replica = replicas.get(locator);\n if (replica === undefined) return [];\n return replica.queue.map((batch) =>\n Object.freeze({\n batch,\n outcome: queuedOutcome(outcomes.get(batch.id)),\n }),\n );\n }\n\n function emitQueue(locator: string) {\n const entries = entriesOf(locator);\n for (const subscription of queueSubscriptions) {\n if (subscription.locator === locator) subscription.notify(entries);\n }\n }\n\n function stopTimer() {\n if (timer === undefined) return;\n clearInterval(timer);\n timer = undefined;\n }\n\n function startTimer() {\n if (timer !== undefined) return;\n timer = setInterval(() => {\n void enqueue();\n }, period);\n }\n\n function refuse(reason: ConnectionRefusalReason) {\n stopTimer();\n discoveryPaused = true;\n refusal = {\n reason,\n reauthorizationOffered: reason === 'revoked-authorization',\n };\n journal.record(`connection refused ${reason}`);\n emitRefusal();\n }\n\n function list(room: DiscoveredRoom, synchronizationAvailable: boolean) {\n rooms.set(room.locator, {\n name: room.name,\n locator: room.locator,\n writeGrants: room.writeGrants,\n providerOwnedPaths: room.providerOwnedPaths,\n roomVersion: replicas.get(room.locator)?.confirmed.record.roomVersion ?? null,\n synchronizationAvailable,\n });\n }\n\n function applyDiscovery(discovered: readonly DiscoveredRoom[]): ReadonlySet<string> {\n const listedLocators = new Set(discovered.map((room) => room.locator));\n for (const room of discovered) {\n list(room, !unreadable.has(room.locator));\n }\n for (const [locator, room] of rooms) {\n if (listedLocators.has(locator)) continue;\n rooms.set(locator, { ...room, synchronizationAvailable: false });\n }\n emitRooms();\n return listedLocators;\n }\n\n async function hydrate(opened: ReplicaStore): Promise<{\n lastCompleted: string | null;\n locators: Set<string>;\n }> {\n const [records, queues, kept, lastCompleted, declared] = await Promise.all([\n opened.all(),\n opened.queues(),\n opened.drafts(),\n opened.lastCompleted(),\n opened.providerLimits(),\n ]);\n limits = declared;\n drafts.clear();\n for (const draft of kept) rememberDraft(draft.locator, draft.path, draft.content);\n const queuedBatches = new Map(queues.map((queue) => [queue.locator, queue.batches]));\n outcomes.clear();\n for (const queue of queues) {\n for (const [id, outcome] of Object.entries(queue.outcomes)) {\n outcomes.set(id, outcome);\n }\n }\n replicas.clear();\n for (const record of records) {\n const confirmed = readConfirmed(record);\n if (confirmed === null) continue;\n replicas.set(record.locator, replicaOf(confirmed, queuedBatches.get(record.locator) ?? []));\n const existing = rooms.get(record.locator);\n if (existing === undefined) list(record, false);\n else {\n rooms.set(record.locator, { ...existing, roomVersion: record.roomVersion });\n }\n }\n return {\n lastCompleted,\n locators: new Set([...queuedBatches.keys(), ...replicas.keys()]),\n };\n }\n\n async function readState(opened: ReplicaStore): Promise<string | null> {\n const { lastCompleted, locators } = await hydrate(opened);\n if (replicas.size > 0) {\n emitRooms();\n emitVisible();\n }\n for (const locator of locators) emitQueue(locator);\n emitDrafts();\n return lastCompleted;\n }\n\n async function applyRemote(message: { type?: unknown; status?: SyncStatus }) {\n if (closed) return;\n if (message.type === 'hello') {\n if (leader) announce();\n return;\n }\n applyingRemote = true;\n try {\n const local = await openLocal();\n const lastCompleted = await readState(local);\n if (message.status !== undefined) adopt(message.status);\n else {\n adopt({\n ...status,\n lastCompleted,\n attentionRequired: attention(),\n state: pending() ? 'pending' : status.state,\n });\n }\n } finally {\n applyingRemote = false;\n }\n if (message.type === 'enqueue' && leader) void enqueue();\n }\n\n async function open(): Promise<ReplicaStore> {\n const opened = await openReplicaStore();\n store = opened;\n await acrossTabs('mdruntime-generation', async () => {\n const storedGeneration = await opened.generation();\n const loss = detectStorageLoss(storedGeneration);\n const generation = nextGeneration(storedGeneration);\n if (generation !== storedGeneration) await opened.rememberGeneration(generation);\n if (loss !== null) {\n storageLoss = loss;\n emitStorageLoss();\n }\n });\n const lastCompleted = await readState(opened);\n adopt({ ...status, lastCompleted, attentionRequired: attention() });\n if (!leader) announce('hello');\n return opened;\n }\n\n function openLocal(): Promise<ReplicaStore> {\n opening ??= open().catch((error: unknown) => {\n opening = undefined;\n throw error;\n });\n return opening;\n }\n\n function exclusive<T>(work: () => Promise<T>): Promise<T> {\n const next = mutations.then(work, work);\n mutations = next.then(\n () => undefined,\n () => undefined,\n );\n return next;\n }\n\n function acrossTabs<T>(name: string, work: () => Promise<T>): Promise<T> {\n if (typeof window === 'undefined') return work();\n return window.navigator.locks.request(name, work);\n }\n\n function publish(local: ReplicaStore, room: DiscoveredRoom, confirmed: ConfirmedLayer) {\n return exclusive(async () => {\n await acrossTabs('mdruntime-replica', async () => {\n await hydrate(local);\n await local.publish(confirmed.record);\n unreadable.delete(room.locator);\n replicas.set(room.locator, replicaOf(confirmed, replicas.get(room.locator)?.queue ?? []));\n });\n list(room, true);\n emitRooms();\n emitVisible();\n announce();\n });\n }\n\n async function write(\n locator: string,\n changes: readonly Change[],\n replacing?: string,\n ): Promise<SaveResult> {\n const local = await openLocal();\n const result = await acrossTabs('mdruntime-replica', async () => {\n await hydrate(local);\n const replica = replicas.get(locator);\n const room = rooms.get(locator);\n if (replica === undefined || room === undefined) {\n throw new Error(`No Local Replica for ${locator}`);\n }\n const built = buildBatch({\n baseRoomVersion: replica.confirmed.record.roomVersion,\n writeGrants: room.writeGrants,\n providerOwnedPaths: room.providerOwnedPaths,\n providerLimits: limits,\n visible: replica.visible,\n changes,\n });\n if (built.kind === 'refused') return { outcome: 'refused' as const, ...built.refusal };\n const head = replica.queue[0];\n if (replacing !== undefined) {\n if (head === undefined || head.id !== replacing || !refused(outcomes.get(head.id))) {\n return { outcome: 'refused' as const, rule: 'no-refused-head' };\n }\n }\n const batches =\n replacing === undefined\n ? [...replica.queue, built.batch]\n : [built.batch, ...replica.queue.slice(1)];\n const consumed = [...new Set(changes.map((change) => change.path))];\n try {\n await local.append({ locator, batches, outcomes: storedOutcomes(batches) }, consumed);\n } catch {\n return { outcome: 'refused' as const, rule: 'durable-write' };\n }\n if (replacing !== undefined) outcomes.delete(replacing);\n for (const path of consumed) forgetDraft(locator, path);\n replicas.set(locator, replicaOf(replica.confirmed, batches));\n emitQueue(locator);\n emitVisible();\n emitDrafts();\n moveTo({ ...saving(status), attentionRequired: attention() });\n return { outcome: 'saved' as const, id: built.batch.id };\n });\n if (result.outcome === 'saved') void enqueue();\n return result;\n }\n\n async function discardHead(locator: string, identifier: string): Promise<void> {\n const local = await openLocal();\n const changed = await acrossTabs('mdruntime-replica', async () => {\n await hydrate(local);\n const replica = replicas.get(locator);\n const head = replica?.queue[0];\n if (\n replica === undefined ||\n head === undefined ||\n head.id !== identifier ||\n !refused(outcomes.get(head.id))\n ) {\n return false;\n }\n const batches = replica.queue.slice(1);\n outcomes.delete(identifier);\n await persistQueue(local, locator, batches);\n replicas.set(locator, replicaOf(replica.confirmed, batches));\n emitQueue(locator);\n emitVisible();\n moveTo({\n ...status,\n state: pending() ? 'pending' : status.state,\n attentionRequired: attention(),\n });\n return true;\n });\n if (changed) void enqueue();\n }\n\n async function readHistory(\n locator: string,\n path: string,\n query: HistoryQuery = {},\n ): Promise<HistoryResult> {\n if (closed || refusal !== null) return { kind: 'transport-uncertainty' };\n try {\n await ensureAuthorization();\n } catch {\n return { kind: 'transport-uncertainty' };\n }\n if (closed || authorization === undefined || refusal !== null) {\n return { kind: 'transport-uncertainty' };\n }\n const transfer = ['transfer', 'history', locator, path];\n if (query.revision !== undefined) transfer.push(query.revision);\n if (query.pageToken !== undefined) transfer.push(query.pageToken);\n journal.record(transfer.join(' '));\n try {\n const result = await options.adapter.history(authorization, {\n locator,\n path,\n ...(query.revision === undefined ? {} : { revision: query.revision }),\n ...(query.pageToken === undefined ? {} : { pageToken: query.pageToken }),\n });\n journal.record(`outcome history ${result.kind}`);\n if (result.kind === 'revoked-authorization') refuse('revoked-authorization');\n return result;\n } catch {\n journal.record('outcome history transport-uncertainty');\n return { kind: 'transport-uncertainty' };\n }\n }\n\n function declaredAction(name: string) {\n for (const capability of capabilities) {\n for (const action of capability.actions ?? []) {\n if (action.name === name) return action;\n }\n }\n return undefined;\n }\n\n async function invokeAction(name: string, input: unknown): Promise<CallResult> {\n await ready;\n if (closed || refusal !== null) return { kind: 'transport-uncertainty' };\n if (declaredAction(name) === undefined) return { kind: 'undeclared' };\n try {\n await ensureAuthorization();\n } catch {\n return { kind: 'transport-uncertainty' };\n }\n if (closed || authorization === undefined || refusal !== null) {\n return { kind: 'transport-uncertainty' };\n }\n journal.record(`transfer action ${name}`);\n try {\n const result = await options.adapter.action(authorization, { name, input });\n if (result.kind === 'revoked-authorization') refuse('revoked-authorization');\n journal.record(`outcome action ${result.kind}`);\n if (result.kind === 'rejected') journal.record(`refusal rejected ${result.text}`);\n return result;\n } catch {\n journal.record('outcome action transport-uncertainty');\n return { kind: 'transport-uncertainty' };\n }\n }\n\n async function pullRefresh(authorized: Authorization, confirmed: ConfirmedLayer) {\n try {\n const result = await refreshRoom(options.adapter, authorized, confirmed);\n const detail = result.kind === 'advanced' ? result.confirmed.record.roomVersion : result.kind;\n journal.record(`transfer refresh ${confirmed.record.locator} ${detail}`);\n return result;\n } catch (error) {\n journal.record(`transfer refresh ${confirmed.record.locator} transport-uncertainty`);\n throw error;\n }\n }\n\n async function pullBootstrap(authorized: Authorization, room: DiscoveredRoom) {\n try {\n const result = await bootstrapRoom(options.adapter, authorized, room);\n const detail = result.kind === 'staged' ? result.confirmed.record.roomVersion : result.kind;\n journal.record(`transfer bootstrap ${room.locator} ${detail}`);\n return result;\n } catch (error) {\n journal.record(`transfer bootstrap ${room.locator} transport-uncertainty`);\n throw error;\n }\n }\n\n async function advance(\n room: DiscoveredRoom,\n local: ReplicaStore,\n authorized: Authorization,\n ): Promise<Withheld | null> {\n const held = replicas.get(room.locator);\n if (held !== undefined) {\n const refreshed = await pullRefresh(authorized, held.confirmed);\n if (refreshed.kind === 'still-current') {\n if (unreadable.delete(room.locator)) {\n list(room, true);\n emitRooms();\n }\n return null;\n }\n if (refreshed.kind === 'advanced') {\n if (closed) return unconfirmed;\n await publish(local, room, refreshed.confirmed);\n return null;\n }\n if (refreshed.kind !== 'beyond-horizon') return refreshed;\n }\n const bootstrapped = await pullBootstrap(authorized, room);\n if (bootstrapped.kind !== 'staged') return bootstrapped;\n if (closed) return unconfirmed;\n await publish(local, room, bootstrapped.confirmed);\n return null;\n }\n\n function recordRefusal(\n result: Extract<MutationResult, { kind: 'conflicted' | 'rejected' | 'expired' }>,\n ): QueueOutcome {\n if (result.kind === 'expired') return { kind: 'expired' };\n if (result.kind === 'conflicted') {\n return {\n kind: 'conflicted',\n roomVersion: result.roomVersion,\n affected: result.affected,\n text: result.text,\n };\n }\n return { kind: 'rejected', affected: result.affected, text: result.text };\n }\n\n async function commitAccept(\n room: DiscoveredRoom,\n local: ReplicaStore,\n submitted: ChangeBatch,\n accepted: Extract<MutationResult, { kind: 'accepted' }>,\n base: ConfirmedLayer,\n overlay: boolean,\n ): Promise<boolean> {\n return acrossTabs('mdruntime-replica', async () => {\n await hydrate(local);\n const current = replicas.get(room.locator);\n if (current === undefined || !current.queue.some((batch) => batch.id === submitted.id)) {\n return true;\n }\n const remaining = current.queue.filter((batch) => batch.id !== submitted.id);\n const applied = overlay\n ? applyReturned(\n base,\n accepted.documents,\n accepted.revisions,\n accepted.removals,\n accepted.roomVersion,\n )\n : base;\n if (applied === null) return false;\n await local.publish(applied.record);\n await persistQueue(local, room.locator, remaining);\n outcomes.set(submitted.id, {\n kind: 'accepted',\n roomVersion: accepted.roomVersion,\n author: accepted.author,\n time: accepted.time,\n });\n unreadable.delete(room.locator);\n replicas.set(room.locator, replicaOf(applied, remaining));\n list(room, true);\n emitRooms();\n emitQueue(room.locator);\n emitVisible();\n journal.record(`outcome ${room.locator} ${submitted.id} accepted`);\n return true;\n });\n }\n\n async function submitRoom(\n room: DiscoveredRoom,\n local: ReplicaStore,\n authorized: Authorization,\n progress: CycleProgress,\n ): Promise<'stop' | null> {\n while (!closed && authorization !== undefined) {\n const replica = replicas.get(room.locator);\n const head = replica?.queue[0];\n if (replica === undefined || head === undefined || refused(outcomes.get(head.id))) {\n return null;\n }\n let result: MutationResult;\n journal.record(`submission ${room.locator} ${head.id}`);\n try {\n result = await options.adapter.mutate(authorized, {\n locator: room.locator,\n changeBatch: head,\n });\n } catch {\n progress.complete = false;\n progress.reachable = false;\n return null;\n }\n if (closed) return null;\n if (result.kind === 'transport-uncertainty') {\n progress.complete = false;\n progress.reachable = false;\n return null;\n }\n if (result.kind === 'room-not-readable') {\n progress.complete = false;\n unreadable.add(room.locator);\n list(room, false);\n emitRooms();\n return null;\n }\n if (result.kind === 'revoked-authorization') {\n refuse('revoked-authorization');\n return 'stop';\n }\n if (result.kind === 'conflicted' || result.kind === 'rejected' || result.kind === 'expired') {\n journal.record(`outcome ${room.locator} ${head.id} ${result.kind}`);\n if (result.kind !== 'expired') journal.record(`refusal ${result.kind} ${result.text}`);\n await exclusive(async () => {\n await acrossTabs('mdruntime-replica', async () => {\n await hydrate(local);\n const current = replicas.get(room.locator);\n if (current === undefined || !current.queue.some((batch) => batch.id === head.id)) {\n return;\n }\n outcomes.set(head.id, recordRefusal(result));\n await persistQueue(local, room.locator, current.queue);\n emitQueue(room.locator);\n moveTo({ ...status, attentionRequired: true });\n });\n });\n return null;\n }\n const from = replicas.get(room.locator)?.confirmed;\n if (from === undefined) return null;\n const pulled = await pullRefresh(authorized, from);\n if (pulled.kind === 'revoked-authorization') {\n refuse('revoked-authorization');\n return 'stop';\n }\n if (pulled.kind === 'still-current') {\n const committed = await exclusive(() =>\n commitAccept(room, local, head, result, from, true),\n );\n if (!committed) {\n progress.complete = false;\n return null;\n }\n continue;\n }\n if (pulled.kind === 'advanced') {\n const overlay = pulled.confirmed.record.roomVersion === result.roomVersion;\n const committed = await exclusive(() =>\n commitAccept(room, local, head, result, pulled.confirmed, overlay),\n );\n if (!committed) {\n progress.complete = false;\n return null;\n }\n continue;\n }\n if (pulled.kind === 'beyond-horizon') {\n const bootstrapped = await pullBootstrap(authorized, room);\n if (bootstrapped.kind === 'revoked-authorization') {\n refuse('revoked-authorization');\n return 'stop';\n }\n if (bootstrapped.kind === 'staged') {\n const overlay = bootstrapped.confirmed.record.roomVersion === result.roomVersion;\n const committed = await exclusive(() =>\n commitAccept(room, local, head, result, bootstrapped.confirmed, overlay),\n );\n if (!committed) {\n progress.complete = false;\n return null;\n }\n continue;\n }\n progress.complete = false;\n if (bootstrapped.kind === 'transport-uncertainty') {\n progress.reachable = false;\n } else if (bootstrapped.kind === 'room-not-readable') {\n unreadable.add(room.locator);\n list(room, false);\n emitRooms();\n }\n return null;\n }\n progress.complete = false;\n if (pulled.kind === 'transport-uncertainty') {\n progress.reachable = false;\n } else if (pulled.kind === 'room-not-readable') {\n unreadable.add(room.locator);\n list(room, false);\n emitRooms();\n }\n return null;\n }\n return null;\n }\n\n async function synchronize(\n discovered: readonly DiscoveredRoom[],\n local: ReplicaStore,\n progress: CycleProgress,\n ) {\n for (const room of discovered) {\n if (closed || authorization === undefined) {\n progress.complete = false;\n return;\n }\n const withheld = await advance(room, local, authorization);\n if (withheld !== null) {\n progress.complete = false;\n if (withheld.kind === 'transport-uncertainty') {\n progress.reachable = false;\n continue;\n }\n if (withheld.kind === 'room-not-readable') {\n unreadable.add(room.locator);\n list(room, false);\n emitRooms();\n continue;\n }\n if (withheld.kind === 'revoked-authorization') {\n refuse('revoked-authorization');\n return;\n }\n continue;\n }\n if ((await submitRoom(room, local, authorization, progress)) === 'stop') return;\n }\n }\n\n async function cycle(local: ReplicaStore, progress: CycleProgress) {\n if (closed || authorization === undefined) {\n notifyReady();\n return;\n }\n moveTo(transferring(status));\n let result;\n try {\n result = await options.adapter.discover(authorization);\n } catch (error) {\n journal.record('connection discover transport-uncertainty');\n notifyReady();\n throw error;\n }\n if (closed) {\n notifyReady();\n return;\n }\n journal.record(`connection discover ${result.kind}`);\n if (result.kind === 'transport-uncertainty') {\n progress.reachable = false;\n notifyReady();\n return;\n }\n if (result.kind === 'revoked-authorization') {\n refuse('revoked-authorization');\n notifyReady();\n return;\n }\n if (!result.supportedVersions.includes(ROOM_CONTRACT_VERSION)) {\n refuse('no-matching-version');\n notifyReady();\n return;\n }\n if (\n result.mdModel.identity !== MD_MODEL.identity ||\n result.mdModel.version !== MD_MODEL.version\n ) {\n refuse('md-model-version-mismatch');\n notifyReady();\n return;\n }\n const declared = new Set(result.capabilities.map((capability) => capability.name));\n for (const required of options.requiredGuarantees) {\n if (!knownCapabilities.has(required) || !declared.has(required)) {\n refuse('missing-required-guarantee');\n notifyReady();\n return;\n }\n }\n if (refusal !== null) {\n refusal = null;\n emitRefusal();\n }\n capabilities = result.capabilities;\n notifyReady();\n if (JSON.stringify(result.providerLimits) !== JSON.stringify(limits)) {\n limits = result.providerLimits;\n await local.declare(limits);\n }\n const listedLocators = applyDiscovery(result.rooms);\n progress.complete = [...replicas.keys()].every((locator) => listedLocators.has(locator));\n await synchronize(result.rooms, local, progress);\n }\n\n async function ensureAuthorization() {\n if (authorization !== undefined) return;\n try {\n authorization = await options.adapter.authorize();\n journal.record('connection authorize');\n } catch (error) {\n journal.record('connection authorize transport-uncertainty');\n throw error;\n }\n }\n\n async function connect() {\n if (closed || discoveryPaused) {\n notifyReady();\n return;\n }\n startTimer();\n const progress: CycleProgress = { complete: false, reachable: true };\n let completedAt = new Date().toISOString();\n try {\n const local = await openLocal();\n if (closed) return;\n await ensureAuthorization();\n if (closed) return;\n await cycle(local, progress);\n if (closed) return;\n if (progress.complete) {\n completedAt = new Date().toISOString();\n await local.complete(completedAt);\n }\n } catch {\n progress.complete = false;\n notifyReady();\n return;\n } finally {\n notifyReady();\n moveTo(settled(status, progress, completedAt, pending(), attention()));\n }\n }\n\n async function run() {\n try {\n await connect();\n } finally {\n inflight = false;\n if (queued && !closed) {\n queued = false;\n void enqueue();\n }\n }\n }\n\n function enqueue() {\n if (!leader) {\n announce('enqueue');\n return chain;\n }\n if (inflight) {\n queued = true;\n return chain;\n }\n inflight = true;\n chain = chain.then(run, run);\n return chain;\n }\n\n function startProcessing() {\n if (leader) {\n void enqueue();\n return;\n }\n void window.navigator.locks\n .request('mdruntime-sync', { signal: options.signal }, async () => {\n if (closed) return;\n leader = true;\n announce();\n void enqueue();\n await new Promise<void>((resolve) => {\n releaseLeadership = () => {\n leader = false;\n resolve();\n };\n });\n })\n .catch(() => {});\n }\n\n function close() {\n closed = true;\n stopTimer();\n releaseLeadership();\n channel?.close();\n store?.close();\n roomListeners.clear();\n refusalListeners.clear();\n storageLossListeners.clear();\n statusListeners.clear();\n querySubscriptions.clear();\n queueSubscriptions.clear();\n draftListeners.clear();\n }\n\n channel?.addEventListener('message', (event) => {\n const data = event.data;\n if (data === null || typeof data !== 'object') return;\n void exclusive(() => applyRemote(data as { type?: unknown; status?: SyncStatus }));\n });\n\n options.signal?.addEventListener('abort', close, { once: true });\n if (options.signal?.aborted) close();\n\n void openLocal().then(\n () => {\n if (!leader) notifyReady();\n },\n () => {\n notifyReady();\n },\n );\n startProcessing();\n\n return {\n rooms() {\n return listed();\n },\n query(request: QueryOptions = {}) {\n return visible(request);\n },\n types(locator: string) {\n return replicas.get(locator)?.visible.collection.types ?? [];\n },\n syncStatus() {\n return status;\n },\n draft: {\n list() {\n return exclusive(async () => {\n const local = await openLocal();\n return readDrafts(local);\n }).then((entries) => {\n releaseWaitingDrafts();\n return entries;\n });\n },\n read(locator: string, path: string) {\n const content = draftContent(locator, path);\n return content === undefined ? null : structuredClone(content);\n },\n replace(locator: string, path: string, content: unknown) {\n return commitDraft(async (local) => {\n const stored = structuredClone(content);\n await local.keep({ locator, path, content: stored });\n rememberDraft(locator, path, stored);\n });\n },\n discard(locator: string, path: string) {\n return commitDraft(async (local) => {\n await local.discard(locator, path);\n forgetDraft(locator, path);\n });\n },\n },\n save(locator: string, changes: readonly Change[], replacing?: string): Promise<SaveResult> {\n return exclusive(() => write(locator, changes, replacing));\n },\n outcome(identifier: string): SubmissionOutcome | null {\n const recorded = outcomes.get(identifier);\n if (recorded !== undefined) return recorded;\n for (const replica of replicas.values()) {\n if (replica.queue.some((batch) => batch.id === identifier)) return { kind: 'pending' };\n }\n return null;\n },\n queue: {\n discard(locator: string, identifier: string) {\n return exclusive(() => discardHead(locator, identifier));\n },\n },\n history(locator: string, path: string, query?: HistoryQuery) {\n return readHistory(locator, path, query);\n },\n call(name: string, input: unknown) {\n return invokeAction(name, input);\n },\n log() {\n return journal.export();\n },\n storageLoss() {\n return storageLoss;\n },\n observe(\n topic:\n | 'rooms'\n | 'connection-refusal'\n | 'storage-loss'\n | 'sync-status'\n | 'query'\n | 'queue'\n | 'drafts',\n second: QueryOptions | string | ((value: never) => void),\n third?: (value: never) => void,\n ) {\n if (topic === 'drafts') {\n const notify = second as (value: readonly DraftEntry[]) => void;\n const listener: DraftSubscription = { notify, ready: false };\n draftListeners.add(listener);\n void exclusive(async () => {\n const local = await openLocal();\n await readDrafts(local);\n if (closed || !draftListeners.has(listener)) return;\n listener.ready = true;\n }).then(\n () => {\n if (closed || !listener.ready || !draftListeners.has(listener)) return;\n listener.notify(snapshotDrafts());\n },\n () => {},\n );\n return () => {\n draftListeners.delete(listener);\n };\n }\n if (topic === 'rooms') {\n const notify = second as (value: readonly AppRoom[]) => void;\n roomListeners.add(notify);\n notify(listed());\n return () => {\n roomListeners.delete(notify);\n };\n }\n if (topic === 'connection-refusal') {\n const notify = second as (value: ConnectionRefusal | null) => void;\n refusalListeners.add(notify);\n notify(refusal);\n return () => {\n refusalListeners.delete(notify);\n };\n }\n if (topic === 'storage-loss') {\n const notify = second as (value: string | null) => void;\n storageLossListeners.add(notify);\n notify(storageLoss);\n return () => {\n storageLossListeners.delete(notify);\n };\n }\n if (topic === 'sync-status') {\n const notify = second as (value: SyncStatus) => void;\n statusListeners.add(notify);\n notify(status);\n return () => {\n statusListeners.delete(notify);\n };\n }\n if (topic === 'queue') {\n const queue: QueueSubscription = {\n locator: second as string,\n notify: third as (entries: readonly QueueEntry[]) => void,\n };\n queueSubscriptions.add(queue);\n queue.notify(entriesOf(queue.locator));\n return () => {\n queueSubscriptions.delete(queue);\n };\n }\n const subscription: QuerySubscription = {\n query: second as QueryOptions,\n notify: third as (result: QueryResult) => void,\n };\n const first = visible(subscription.query);\n querySubscriptions.add(subscription);\n subscription.notify(first);\n return () => {\n querySubscriptions.delete(subscription);\n };\n },\n async reauthorize() {\n if (refusal === null || !refusal.reauthorizationOffered) return;\n journal.record('connection reauthorize');\n authorization = undefined;\n discoveryPaused = false;\n await enqueue();\n },\n };\n}\n"],"names":["query","evaluate","ROOM_CONTRACT_VERSION","VERSION_1_CAPABILITIES","bootstrapRoom","MD_MODEL","PRESENTED","createLog","queuedOutcome","refused","refreshRoom","buildBatch","applyReturned","readConfirmed","replicaOf","settled","same","saving","STARTING","transferring","detectStorageLoss","nextGeneration","openReplicaStore","unconfirmed","DEFAULT_DISCOVERY_INTERVAL_MS","knownCapabilities","Set","createMdRuntime","options","period","discoveryIntervalMs","authorization","opening","store","replicas","Map","drafts","outcomes","limits","capabilities","rooms","unreadable","refusal","storageLoss","status","discoveryPaused","timer","closed","chain","Promise","resolve","mutations","inflight","queued","roomListeners","refusalListeners","storageLossListeners","statusListeners","querySubscriptions","queueSubscriptions","draftListeners","journal","notifyReady","ready","leader","window","applyingRemote","releaseLeadership","channel","BroadcastChannel","undefined","draftContent","locator","path","get","rememberDraft","content","room","set","forgetDraft","delete","size","snapshotDrafts","entries","push","structuredClone","sort","left","right","readDrafts","opened","acrossTabs","hydrate","publishDrafts","waitingOnly","value","listener","notify","emitDrafts","releaseWaitingDrafts","commitDraft","work","exclusive","local","openLocal","then","announce","pending","values","some","replica","queue","length","attention","head","id","storedOutcomes","batches","stored","batch","outcome","kind","persistQueue","writeQueue","listed","queryRooms","map","confirmed","record","roomVersion","documents","visible","collection","emitRooms","emitRefusal","emitStorageLoss","type","postMessage","adopt","next","moveTo","request","selector","$and","emitVisible","subscription","entriesOf","Object","freeze","emitQueue","stopTimer","clearInterval","startTimer","setInterval","enqueue","refuse","reason","reauthorizationOffered","list","synchronizationAvailable","name","writeGrants","providerOwnedPaths","applyDiscovery","discovered","listedLocators","has","records","queues","kept","lastCompleted","declared","all","providerLimits","clear","draft","queuedBatches","existing","locators","keys","readState","applyRemote","message","attentionRequired","state","open","storedGeneration","generation","loss","rememberGeneration","catch","error","navigator","locks","publish","write","changes","replacing","result","Error","built","baseRoomVersion","rule","slice","consumed","change","append","discardHead","identifier","changed","readHistory","ensureAuthorization","transfer","revision","pageToken","join","adapter","history","declaredAction","capability","action","actions","invokeAction","input","text","pullRefresh","authorized","detail","pullBootstrap","advance","held","refreshed","bootstrapped","recordRefusal","affected","commitAccept","submitted","accepted","base","overlay","current","remaining","filter","applied","revisions","removals","author","time","submitRoom","progress","mutate","changeBatch","complete","reachable","add","from","pulled","committed","synchronize","withheld","cycle","discover","supportedVersions","includes","mdModel","identity","version","required","requiredGuarantees","JSON","stringify","declare","every","authorize","connect","completedAt","Date","toISOString","run","startProcessing","signal","close","addEventListener","event","data","once","aborted","types","syncStatus","read","replace","keep","discard","save","recorded","call","log","export","observe","topic","second","third","first","reauthorize"],"mappings":"AAAA,SACEA,SAASC,QAAQ,QAIZ,qBAAqB;AAC5B,SACEC,qBAAqB,EACrBC,sBAAsB,QAUjB,eAAe;AACtB,SAASC,aAAa,QAAQ,iBAAiB;AAE/C,SAASC,QAAQ,EAAEC,SAAS,QAAqB,kBAAkB;AACnE,SAASC,SAAS,QAAQ,WAAW;AACrC,SACEC,aAAa,EACbC,OAAO,QAIF,eAAe;AACtB,SAASC,WAAW,QAAQ,eAAe;AAC3C,SAASC,UAAU,QAA0B,YAAY;AACzD,SACEC,aAAa,EACbC,aAAa,EACbC,SAAS,QAGJ,eAAe;AACtB,SACEC,OAAO,EACPC,IAAI,EACJC,MAAM,EACNC,QAAQ,EACRC,YAAY,QAGP,cAAc;AACrB,SAASC,iBAAiB,EAAEC,cAAc,QAAQ,kBAAkB;AACpE,SAASC,gBAAgB,QAA2B,aAAa;AACjE,SAASC,WAAW,QAA0B,gBAAgB;AAE9D,MAAMC,gCAAgC;AAEtC,MAAMC,oBAAoB,IAAIC,IAAYvB;AAyG1C,OAAO,SAASwB,gBAAgBC,OAAyB;IACvD,MAAMC,SAASD,QAAQE,mBAAmB,IAAIN;IAC9C,IAAIO,gBAA2CH,QAAQG,aAAa;IACpE,IAAIC;IACJ,IAAIC;IACJ,MAAMC,WAAW,IAAIC;IACrB,MAAMC,SAAS,IAAID;IACnB,MAAME,WAAW,IAAIF;IACrB,IAAIG,SAAmC,EAAE;IACzC,IAAIC,eAAsC,EAAE;IAC5C,MAAMC,QAAQ,IAAIL;IAClB,MAAMM,aAAa,IAAIf;IACvB,IAAIgB,UAAoC;IACxC,IAAIC,cAA6B;IACjC,IAAIC,SAAqB1B;IACzB,IAAI2B,kBAAkB;IACtB,IAAIC;IACJ,IAAIC,SAAS;IACb,IAAIC,QAAuBC,QAAQC,OAAO;IAC1C,IAAIC,YAA8BF,QAAQC,OAAO;IACjD,IAAIE,WAAW;IACf,IAAIC,SAAS;IACb,MAAMC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IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["/workspace/packages/mdruntime/src/connection.ts"],"sourcesContent":["import { rawQuery, type QueryBinding, type QueryInput } from './query.js';\nimport {\n cached,\n modelTypes,\n NO_MODEL,\n sameModel,\n type AttachedModelBinding,\n type ModelState,\n type TypesResult,\n} from './model.js';\nimport {\n query as evaluate,\n type QueryOptions,\n type QueryResult,\n type QueryRoom,\n} from '@agentshouse/query';\nimport {\n ROOM_CONTRACT_VERSION,\n VERSION_1_CAPABILITIES,\n type ActionResult,\n type Adapter,\n type AdapterFailure,\n type Authorization,\n type Capability,\n type DiscoveredRoom,\n type HistoryResult,\n type MutationResult,\n type ProviderLimit,\n} from './adapter.js';\nimport { bootstrapRoom } from './bootstrap.js';\nimport type { Change, ChangeBatch } from './change.js';\nimport { MD_MODEL, PRESENTED, validRoot, type MdType } from './collection.js';\nimport { createLog } from './log.js';\nimport {\n queuedOutcome,\n refused,\n type QueueEntry,\n type QueueOutcome,\n type SubmissionOutcome,\n} from './outcome.js';\nimport { refreshRoom } from './refresh.js';\nimport { buildBatch, type SaveRefusal } from './save.js';\nimport {\n applyReturned,\n readConfirmed,\n replicaOf,\n type ConfirmedLayer,\n type Replica,\n} from './replica.js';\nimport {\n settled,\n same,\n saving,\n STARTING,\n transferring,\n type CycleProgress,\n type SyncStatus,\n} from './status.js';\nimport { detectStorageLoss, nextGeneration } from './durability.js';\nimport { openReplicaStore, type ReplicaStore } from './store.js';\nimport { unconfirmed, type Unconfirmed } from './transfer.js';\n\nconst DEFAULT_DISCOVERY_INTERVAL_MS = 60_000;\n\nconst knownCapabilities = new Set<string>(VERSION_1_CAPABILITIES);\n\nexport type AppRoom = {\n collectionRoot: string;\n name: string;\n locator: string;\n operations: import('./adapter.js').OperationScopes;\n replica: import('./adapter.js').ReplicaAdmission;\n attachedModel: import('./model.js').ModelIdentity | null;\n model: TypesResult;\n providerOwnedPaths: readonly string[];\n roomVersion: string | null;\n synchronizationAvailable: boolean;\n};\n\nexport type ConnectionRefusalReason =\n | 'no-matching-version'\n | 'missing-required-guarantee'\n | 'md-model-version-mismatch'\n | 'revoked-authorization';\n\nexport type ConnectionRefusal = {\n reason: ConnectionRefusalReason;\n reauthorizationOffered: boolean;\n};\n\nexport type MdRuntimeOptions = {\n adapter: Adapter;\n modelBinding: AttachedModelBinding | null;\n queryBinding: QueryBinding | null;\n requiredGuarantees: readonly string[];\n authorization?: Authorization;\n discoveryIntervalMs?: number;\n signal?: AbortSignal;\n};\n\nexport type SaveResult = { outcome: 'saved'; id: string } | ({ outcome: 'refused' } & SaveRefusal);\n\nexport type DraftEntry = {\n readonly locator: string;\n readonly path: string;\n readonly content: unknown;\n};\n\nexport type DraftSurface = {\n list(): Promise<readonly DraftEntry[]>;\n read(locator: string, path: string): unknown;\n replace(locator: string, path: string, content: unknown): Promise<void>;\n discard(locator: string, path: string): Promise<void>;\n};\n\nexport type QueueSurface = {\n discard(locator: string, identifier: string): Promise<void>;\n};\n\nexport type HistoryQuery = {\n revision?: string;\n pageToken?: string;\n};\n\nexport type CallResult = ActionResult | { kind: 'undeclared' };\n\nexport type MdRuntime = {\n rooms(): readonly AppRoom[];\n query(options?: QueryOptions): QueryResult;\n types(locator: string): TypesResult;\n syncStatus(): SyncStatus;\n draft: DraftSurface;\n save(locator: string, changes: readonly Change[], replacing?: string): Promise<SaveResult>;\n outcome(identifier: string): SubmissionOutcome | null;\n queue: QueueSurface;\n history(locator: string, path: string, query?: HistoryQuery): Promise<HistoryResult>;\n call(name: string, input: unknown): Promise<CallResult>;\n log(): string;\n storageLoss(): string | null;\n observe: {\n (topic: 'rooms', listener: (rooms: readonly AppRoom[]) => void): () => void;\n (\n topic: 'connection-refusal',\n listener: (refusal: ConnectionRefusal | null) => void,\n ): () => void;\n (topic: 'storage-loss', listener: (statement: string | null) => void): () => void;\n (topic: 'sync-status', listener: (status: SyncStatus) => void): () => void;\n (topic: 'query', query: QueryOptions, listener: (result: QueryResult) => void): () => void;\n (\n topic: 'queue',\n locator: string,\n listener: (entries: readonly QueueEntry[]) => void,\n ): () => void;\n (topic: 'drafts', listener: (drafts: readonly DraftEntry[]) => void): () => void;\n };\n reauthorize(): Promise<void>;\n};\n\ntype QuerySubscription = {\n query: QueryOptions;\n notify: (result: QueryResult) => void;\n};\n\ntype QueueSubscription = {\n locator: string;\n notify: (entries: readonly QueueEntry[]) => void;\n};\n\ntype DraftSubscription = {\n notify: (drafts: readonly DraftEntry[]) => void;\n ready: boolean;\n};\n\ntype Withheld = AdapterFailure | Unconfirmed;\n\nexport function createMdRuntime(options: MdRuntimeOptions): MdRuntime {\n const period = options.discoveryIntervalMs ?? DEFAULT_DISCOVERY_INTERVAL_MS;\n let authorization: Authorization | undefined = options.authorization;\n let opening: Promise<ReplicaStore> | undefined;\n let store: ReplicaStore | undefined;\n const replicas = new Map<string, Replica>();\n const drafts = new Map<string, Map<string, unknown>>();\n const outcomes = new Map<string, SubmissionOutcome>();\n let limits: readonly ProviderLimit[] = [];\n let capabilities: readonly Capability[] = [];\n const rooms = new Map<string, AppRoom>();\n const unreadable = new Set<string>();\n const models = new Map<string, ModelState>();\n const liveModels = new Map<string, string>();\n const invalidModels = new Set<string>();\n const modelEpoch = new Map<string, number>();\n function modelOf(locator: string): ModelState {\n return models.get(locator) ?? NO_MODEL;\n }\n\n const mismatchedRoots = new Set<string>();\n let refusal: ConnectionRefusal | null = null;\n let storageLoss: string | null = null;\n let status: SyncStatus = STARTING;\n let discoveryPaused = false;\n let timer: ReturnType<typeof setInterval> | undefined;\n let closed = false;\n let chain: Promise<void> = Promise.resolve();\n let mutations: Promise<unknown> = Promise.resolve();\n let inflight = false;\n let queued = false;\n const roomListeners = new Set<(rooms: readonly AppRoom[]) => void>();\n const refusalListeners = new Set<(refusal: ConnectionRefusal | null) => void>();\n const storageLossListeners = new Set<(statement: string | null) => void>();\n const statusListeners = new Set<(status: SyncStatus) => void>();\n const querySubscriptions = new Set<QuerySubscription>();\n const queueSubscriptions = new Set<QueueSubscription>();\n const draftListeners = new Set<DraftSubscription>();\n const journal = createLog();\n let notifyReady = () => {};\n const ready = new Promise<void>((resolve) => {\n notifyReady = resolve;\n });\n let leader = typeof window === 'undefined';\n let applyingRemote = false;\n let releaseLeadership = () => {};\n const channel = typeof window !== 'undefined' ? new BroadcastChannel('mdruntime') : undefined;\n\n function draftContent(locator: string, path: string) {\n return drafts.get(locator)?.get(path);\n }\n\n function rememberDraft(locator: string, path: string, content: unknown) {\n const room = drafts.get(locator) ?? new Map<string, unknown>();\n room.set(path, content);\n drafts.set(locator, room);\n }\n\n function forgetDraft(locator: string, path: string) {\n const room = drafts.get(locator);\n if (room === undefined) return;\n room.delete(path);\n if (room.size === 0) drafts.delete(locator);\n }\n\n function snapshotDrafts(): readonly DraftEntry[] {\n const entries: DraftEntry[] = [];\n for (const [locator, room] of drafts) {\n for (const [path, content] of room) {\n entries.push({ locator, path, content: structuredClone(content) });\n }\n }\n entries.sort((left, right) => {\n if (left.locator !== right.locator) return left.locator < right.locator ? -1 : 1;\n if (left.path !== right.path) return left.path < right.path ? -1 : 1;\n return 0;\n });\n return entries;\n }\n\n async function readDrafts(opened: ReplicaStore) {\n await acrossTabs('mdruntime-replica', async () => {\n await hydrate(opened);\n });\n return snapshotDrafts();\n }\n\n function publishDrafts(waitingOnly: boolean) {\n if (closed) return;\n const value = snapshotDrafts();\n for (const listener of draftListeners) {\n if (waitingOnly && listener.ready) continue;\n listener.ready = true;\n listener.notify(value);\n }\n }\n\n function emitDrafts() {\n publishDrafts(false);\n }\n\n function releaseWaitingDrafts() {\n publishDrafts(true);\n }\n\n function commitDraft(work: (local: ReplicaStore) => Promise<void>) {\n return exclusive(async () => {\n const local = await openLocal();\n await acrossTabs('mdruntime-replica', async () => {\n await hydrate(local);\n await work(local);\n });\n }).then(() => {\n emitDrafts();\n announce();\n });\n }\n\n function pending() {\n return [...replicas.values()].some((replica) => replica.queue.length > 0);\n }\n\n function attention() {\n return [...replicas.values()].some((replica) => {\n const head = replica.queue[0];\n return head !== undefined && refused(outcomes.get(head.id));\n });\n }\n\n function storedOutcomes(batches: readonly ChangeBatch[]) {\n const stored: Record<string, QueueOutcome> = {};\n for (const batch of batches) {\n const outcome = queuedOutcome(outcomes.get(batch.id));\n if (outcome.kind !== 'pending') stored[batch.id] = outcome;\n }\n return stored;\n }\n\n async function persistQueue(\n local: ReplicaStore,\n locator: string,\n batches: readonly ChangeBatch[],\n ) {\n await local.writeQueue({\n locator,\n batches,\n outcomes: storedOutcomes(batches),\n });\n announce();\n }\n\n function listed(): readonly AppRoom[] {\n return structuredClone([...rooms.values()]);\n }\n\n function queryRooms(): readonly QueryInput[] {\n return [...replicas.values()].map((replica) => ({\n room: replica.confirmed.record.locator,\n roomVersion: replica.confirmed.record.roomVersion,\n documents: replica.visible.collection.documents,\n model: modelTypes(modelOf(replica.confirmed.record.locator)),\n }));\n }\n\n function emitRooms() {\n const value = listed();\n for (const listener of roomListeners) listener(value);\n }\n\n function emitRefusal() {\n for (const listener of refusalListeners) listener(refusal);\n }\n\n function emitStorageLoss() {\n for (const listener of storageLossListeners) listener(storageLoss);\n }\n\n function announce(type: 'changed' | 'enqueue' | 'hello' = 'changed') {\n if (applyingRemote || channel === undefined) return;\n if (type === 'hello') {\n channel.postMessage({ type: 'hello' });\n return;\n }\n channel.postMessage({ type, status });\n }\n\n function adopt(next: SyncStatus) {\n if (closed || same(status, next)) return;\n status = next;\n for (const listener of statusListeners) listener(status);\n }\n\n function moveTo(next: SyncStatus) {\n if (closed || same(status, next)) return;\n adopt(next);\n announce();\n }\n\n function visible(request: QueryOptions): QueryResult {\n if (options.queryBinding === null) {\n if (Object.keys(request).length > 0) throw new Error('query-binding-unavailable');\n return rawQuery(queryRooms());\n }\n return options.queryBinding(queryRooms(), {\n ...request,\n selector: { $and: [PRESENTED, request.selector ?? {}] },\n });\n }\n\n function emitVisible() {\n for (const subscription of querySubscriptions) {\n subscription.notify(visible(subscription.query));\n }\n }\n\n function entriesOf(locator: string): readonly QueueEntry[] {\n const replica = replicas.get(locator);\n if (replica === undefined) return [];\n return replica.queue.map((batch) =>\n Object.freeze({\n batch,\n outcome: queuedOutcome(outcomes.get(batch.id)),\n }),\n );\n }\n\n function emitQueue(locator: string) {\n const entries = entriesOf(locator);\n for (const subscription of queueSubscriptions) {\n if (subscription.locator === locator) subscription.notify(entries);\n }\n }\n\n function stopTimer() {\n if (timer === undefined) return;\n clearInterval(timer);\n timer = undefined;\n }\n\n function startTimer() {\n if (timer !== undefined) return;\n timer = setInterval(() => {\n void enqueue();\n }, period);\n }\n\n function refuse(reason: ConnectionRefusalReason) {\n if (reason === 'revoked-authorization') {\n const revoked: ModelState = { status: 'unavailable', reason: 'revoked' };\n for (const locator of new Set([...models.keys(), ...rooms.keys()])) {\n invalidModels.add(locator);\n modelEpoch.set(locator, (modelEpoch.get(locator) ?? 0) + 1);\n models.set(locator, revoked);\n liveModels.delete(locator);\n }\n for (const [locator, room] of rooms)\n rooms.set(locator, { ...room, model: modelTypes(revoked) });\n emitRooms();\n void exclusive(async () => {\n const local = await openLocal();\n await acrossTabs('mdruntime-replica', async () => {\n for (const record of await local.all())\n await local.publish({ ...record, model: revoked });\n });\n announce();\n }).catch(() => {\n journal.record('model invalidation durable-write failure');\n });\n }\n stopTimer();\n discoveryPaused = true;\n refusal = {\n reason,\n reauthorizationOffered: reason === 'revoked-authorization',\n };\n journal.record(`connection refused ${reason}`);\n emitRefusal();\n }\n\n function list(room: Omit<DiscoveredRoom, 'roomVersion'>, synchronizationAvailable: boolean) {\n rooms.set(room.locator, {\n name: room.name,\n collectionRoot: room.collectionRoot,\n locator: room.locator,\n operations: room.operations,\n replica: room.replica,\n attachedModel: room.attachedModel,\n model: modelTypes(modelOf(room.locator)),\n providerOwnedPaths: room.providerOwnedPaths,\n roomVersion: replicas.get(room.locator)?.confirmed.record.roomVersion ?? null,\n synchronizationAvailable,\n });\n }\n\n function applyDiscovery(discovered: readonly DiscoveredRoom[]): ReadonlySet<string> {\n const listedLocators = new Set(discovered.map((room) => room.locator));\n for (const room of discovered) {\n const held = replicas.get(room.locator)?.confirmed.record;\n if (held !== undefined && held.replica.selection !== room.replica.selection) {\n list(held, false);\n continue;\n }\n list(room, room.replica.admission === 'admitted' && !unreadable.has(room.locator));\n }\n for (const [locator, room] of rooms) {\n if (listedLocators.has(locator)) continue;\n rooms.set(locator, { ...room, synchronizationAvailable: false });\n }\n emitRooms();\n return listedLocators;\n }\n\n async function hydrate(opened: ReplicaStore): Promise<{\n lastCompleted: string | null;\n locators: Set<string>;\n }> {\n const [records, queues, kept, lastCompleted, declared] = await Promise.all([\n opened.all(),\n opened.queues(),\n opened.drafts(),\n opened.lastCompleted(),\n opened.providerLimits(),\n ]);\n limits = declared;\n drafts.clear();\n for (const draft of kept) rememberDraft(draft.locator, draft.path, draft.content);\n const queuedBatches = new Map(queues.map((queue) => [queue.locator, queue.batches]));\n outcomes.clear();\n for (const queue of queues) {\n for (const [id, outcome] of Object.entries(queue.outcomes)) {\n outcomes.set(id, outcome);\n }\n }\n replicas.clear();\n for (const record of records) {\n const persisted = record.model;\n const priorModel = models.get(record.locator);\n if (\n priorModel !== undefined &&\n priorModel.status !== 'unavailable' &&\n (persisted.status === 'unavailable' || !sameModel(priorModel.snapshot, persisted.snapshot))\n ) {\n modelEpoch.set(record.locator, (modelEpoch.get(record.locator) ?? 0) + 1);\n invalidModels.add(record.locator);\n }\n const model =\n persisted.status === 'unavailable' ||\n liveModels.get(record.locator) === JSON.stringify(persisted.snapshot)\n ? persisted\n : cached(persisted);\n models.set(record.locator, model);\n if (model.status === 'unavailable') {\n liveModels.delete(record.locator);\n invalidModels.delete(record.locator);\n }\n const confirmed = readConfirmed({ ...record, model });\n if (confirmed === null) continue;\n replicas.set(record.locator, replicaOf(confirmed, queuedBatches.get(record.locator) ?? []));\n const existing = rooms.get(record.locator);\n if (existing === undefined) list(record, false);\n else {\n rooms.set(record.locator, {\n ...existing,\n roomVersion: record.roomVersion,\n operations: record.operations,\n replica: record.replica,\n attachedModel: record.attachedModel,\n model: modelTypes(model),\n });\n }\n }\n return {\n lastCompleted,\n locators: new Set([...queuedBatches.keys(), ...replicas.keys()]),\n };\n }\n\n async function readState(opened: ReplicaStore): Promise<string | null> {\n const { lastCompleted, locators } = await hydrate(opened);\n if (replicas.size > 0) {\n emitRooms();\n emitVisible();\n }\n for (const locator of locators) emitQueue(locator);\n emitDrafts();\n return lastCompleted;\n }\n\n async function applyRemote(message: { type?: unknown; status?: SyncStatus }) {\n if (closed) return;\n if (message.type === 'hello') {\n if (leader) announce();\n return;\n }\n applyingRemote = true;\n try {\n const local = await openLocal();\n const lastCompleted = await readState(local);\n if (message.status !== undefined) adopt(message.status);\n else {\n adopt({\n ...status,\n lastCompleted,\n attentionRequired: attention(),\n state: pending() ? 'pending' : status.state,\n });\n }\n } finally {\n applyingRemote = false;\n }\n if (message.type === 'enqueue' && leader) void enqueue();\n }\n\n async function open(): Promise<ReplicaStore> {\n const opened = await openReplicaStore();\n store = opened;\n await acrossTabs('mdruntime-generation', async () => {\n const storedGeneration = await opened.generation();\n const loss = detectStorageLoss(storedGeneration);\n const generation = nextGeneration(storedGeneration);\n if (generation !== storedGeneration) await opened.rememberGeneration(generation);\n if (loss !== null) {\n storageLoss = loss;\n emitStorageLoss();\n }\n });\n const lastCompleted = await readState(opened);\n adopt({ ...status, lastCompleted, attentionRequired: attention() });\n if (!leader) announce('hello');\n return opened;\n }\n\n function openLocal(): Promise<ReplicaStore> {\n opening ??= open().catch((error: unknown) => {\n opening = undefined;\n throw error;\n });\n return opening;\n }\n\n function exclusive<T>(work: () => Promise<T>): Promise<T> {\n const next = mutations.then(work, work);\n mutations = next.then(\n () => undefined,\n () => undefined,\n );\n return next;\n }\n\n function acrossTabs<T>(name: string, work: () => Promise<T>): Promise<T> {\n if (typeof window === 'undefined') return work();\n return window.navigator.locks.request(name, work);\n }\n\n function publish(local: ReplicaStore, room: DiscoveredRoom, confirmed: ConfirmedLayer) {\n return exclusive(async () => {\n await acrossTabs('mdruntime-replica', async () => {\n await hydrate(local);\n const retained = readConfirmed({ ...confirmed.record, model: modelOf(room.locator) });\n if (retained === null) return;\n await local.publish(retained.record);\n unreadable.delete(room.locator);\n replicas.set(room.locator, replicaOf(retained, replicas.get(room.locator)?.queue ?? []));\n });\n list(room, true);\n emitRooms();\n emitVisible();\n announce();\n });\n }\n\n async function write(\n locator: string,\n changes: readonly Change[],\n replacing?: string,\n ): Promise<SaveResult> {\n const local = await openLocal();\n const result = await acrossTabs('mdruntime-replica', async () => {\n await hydrate(local);\n const replica = replicas.get(locator);\n const room = rooms.get(locator);\n if (replica === undefined || room === undefined) {\n throw new Error(`No Local Replica for ${locator}`);\n }\n if (mismatchedRoots.has(locator))\n return { outcome: 'refused' as const, rule: 'collection-root-mismatch' };\n const built = buildBatch({\n baseRoomVersion: replica.confirmed.record.roomVersion,\n collectionRoot: replica.confirmed.record.collectionRoot,\n operations: room.operations,\n model: invalidModels.has(locator)\n ? { status: 'unavailable', reason: 'revoked' }\n : modelOf(locator),\n binding: options.modelBinding,\n providerOwnedPaths: room.providerOwnedPaths,\n providerLimits: limits,\n visible: replica.visible,\n changes,\n });\n if (built.kind === 'refused') return { outcome: 'refused' as const, ...built.refusal };\n const head = replica.queue[0];\n if (replacing !== undefined) {\n if (head === undefined || head.id !== replacing || !refused(outcomes.get(head.id))) {\n return { outcome: 'refused' as const, rule: 'no-refused-head' };\n }\n }\n const batches =\n replacing === undefined\n ? [...replica.queue, built.batch]\n : [built.batch, ...replica.queue.slice(1)];\n const consumed = [...new Set(changes.map((change) => change.path))];\n try {\n await local.append({ locator, batches, outcomes: storedOutcomes(batches) }, consumed);\n } catch {\n return { outcome: 'refused' as const, rule: 'durable-write' };\n }\n if (replacing !== undefined) outcomes.delete(replacing);\n for (const path of consumed) forgetDraft(locator, path);\n replicas.set(locator, replicaOf(replica.confirmed, batches));\n emitQueue(locator);\n emitVisible();\n emitDrafts();\n moveTo({ ...saving(status), attentionRequired: attention() });\n return { outcome: 'saved' as const, id: built.batch.id };\n });\n if (result.outcome === 'saved') void enqueue();\n return result;\n }\n\n async function discardHead(locator: string, identifier: string): Promise<void> {\n const local = await openLocal();\n const changed = await acrossTabs('mdruntime-replica', async () => {\n await hydrate(local);\n const replica = replicas.get(locator);\n const head = replica?.queue[0];\n if (\n replica === undefined ||\n head === undefined ||\n head.id !== identifier ||\n !refused(outcomes.get(head.id))\n ) {\n return false;\n }\n const batches = replica.queue.slice(1);\n outcomes.delete(identifier);\n await persistQueue(local, locator, batches);\n replicas.set(locator, replicaOf(replica.confirmed, batches));\n emitQueue(locator);\n emitVisible();\n moveTo({\n ...status,\n state: pending() ? 'pending' : status.state,\n attentionRequired: attention(),\n });\n return true;\n });\n if (changed) void enqueue();\n }\n\n async function readHistory(\n locator: string,\n path: string,\n query: HistoryQuery = {},\n ): Promise<HistoryResult> {\n if (closed || refusal !== null) return { kind: 'transport-uncertainty' };\n try {\n await ensureAuthorization();\n } catch {\n return { kind: 'transport-uncertainty' };\n }\n if (closed || authorization === undefined || refusal !== null) {\n return { kind: 'transport-uncertainty' };\n }\n const transfer = ['transfer', 'history', locator, path];\n if (query.revision !== undefined) transfer.push(query.revision);\n if (query.pageToken !== undefined) transfer.push(query.pageToken);\n journal.record(transfer.join(' '));\n try {\n const result = await options.adapter.history(authorization, {\n locator,\n path,\n ...(query.revision === undefined ? {} : { revision: query.revision }),\n ...(query.pageToken === undefined ? {} : { pageToken: query.pageToken }),\n });\n journal.record(`outcome history ${result.kind}`);\n if (result.kind === 'scoped-refusal') {\n const room = replicas.get(result.locator)?.confirmed.record;\n if (room !== undefined) await scoped(result, room, await openLocal());\n }\n if (result.kind === 'revoked-authorization') refuse('revoked-authorization');\n return result;\n } catch {\n journal.record('outcome history transport-uncertainty');\n return { kind: 'transport-uncertainty' };\n }\n }\n\n function declaredAction(name: string) {\n for (const capability of capabilities) {\n for (const action of capability.actions ?? []) {\n if (action.name === name) return action;\n }\n }\n return undefined;\n }\n\n async function invokeAction(name: string, input: unknown): Promise<CallResult> {\n await ready;\n if (closed || refusal !== null) return { kind: 'transport-uncertainty' };\n if (declaredAction(name) === undefined) return { kind: 'undeclared' };\n try {\n await ensureAuthorization();\n } catch {\n return { kind: 'transport-uncertainty' };\n }\n if (closed || authorization === undefined || refusal !== null) {\n return { kind: 'transport-uncertainty' };\n }\n journal.record(`transfer action ${name}`);\n try {\n const result = await options.adapter.action(authorization, { name, input });\n if (result.kind === 'scoped-refusal') {\n const room = replicas.get(result.locator)?.confirmed.record;\n if (room !== undefined) await scoped(result, room, await openLocal());\n }\n if (result.kind === 'revoked-authorization') refuse('revoked-authorization');\n journal.record(`outcome action ${result.kind}`);\n if (result.kind === 'rejected') journal.record(`refusal rejected ${result.text}`);\n return result;\n } catch {\n journal.record('outcome action transport-uncertainty');\n return { kind: 'transport-uncertainty' };\n }\n }\n\n async function pullRefresh(authorized: Authorization, confirmed: ConfirmedLayer) {\n try {\n const result = await refreshRoom(\n options.adapter,\n authorized,\n confirmed,\n options.modelBinding,\n );\n const detail = result.kind === 'advanced' ? result.confirmed.record.roomVersion : result.kind;\n journal.record(`transfer refresh ${confirmed.record.locator} ${detail}`);\n return result;\n } catch (error) {\n journal.record(`transfer refresh ${confirmed.record.locator} transport-uncertainty`);\n throw error;\n }\n }\n\n async function pullBootstrap(authorized: Authorization, room: DiscoveredRoom) {\n try {\n const result = await bootstrapRoom(\n options.adapter,\n authorized,\n room,\n modelOf(room.locator),\n options.modelBinding,\n );\n const detail = result.kind === 'staged' ? result.confirmed.record.roomVersion : result.kind;\n journal.record(`transfer bootstrap ${room.locator} ${detail}`);\n return result;\n } catch (error) {\n journal.record(`transfer bootstrap ${room.locator} transport-uncertainty`);\n throw error;\n }\n }\n\n async function advance(\n room: DiscoveredRoom,\n local: ReplicaStore,\n authorized: Authorization,\n ): Promise<Withheld | null> {\n const held = replicas.get(room.locator);\n if (held !== undefined) {\n const refreshed = await pullRefresh(authorized, held.confirmed);\n if (refreshed.kind === 'still-current') {\n if (unreadable.delete(room.locator)) {\n list(room, true);\n emitRooms();\n }\n return null;\n }\n if (refreshed.kind === 'advanced') {\n if (closed) return unconfirmed;\n await publish(local, room, refreshed.confirmed);\n return null;\n }\n if (refreshed.kind !== 'beyond-horizon') return refreshed;\n }\n const bootstrapped = await pullBootstrap(authorized, room);\n if (bootstrapped.kind !== 'staged') return bootstrapped;\n if (closed) return unconfirmed;\n await publish(local, room, bootstrapped.confirmed);\n return null;\n }\n\n function recordRefusal(\n result: Extract<MutationResult, { kind: 'conflicted' | 'rejected' | 'expired' }>,\n ): QueueOutcome {\n if (result.kind === 'expired') return { kind: 'expired' };\n if (result.kind === 'conflicted') {\n return {\n kind: 'conflicted',\n roomVersion: result.roomVersion,\n affected: result.affected,\n text: result.text,\n };\n }\n return { kind: 'rejected', affected: result.affected, text: result.text };\n }\n\n async function commitAccept(\n room: DiscoveredRoom,\n local: ReplicaStore,\n submitted: ChangeBatch,\n accepted: Extract<MutationResult, { kind: 'accepted' }>,\n base: ConfirmedLayer,\n overlay: boolean,\n ): Promise<boolean> {\n return acrossTabs('mdruntime-replica', async () => {\n await hydrate(local);\n const current = replicas.get(room.locator);\n if (current === undefined || !current.queue.some((batch) => batch.id === submitted.id)) {\n return true;\n }\n const remaining = current.queue.filter((batch) => batch.id !== submitted.id);\n const retainedBase = readConfirmed({ ...base.record, model: modelOf(room.locator) });\n if (retainedBase === null) return false;\n const applied = overlay\n ? applyReturned(\n retainedBase,\n accepted.documents,\n accepted.revisions,\n accepted.removals,\n accepted.roomVersion,\n options.modelBinding,\n )\n : retainedBase;\n if (applied === null) return false;\n await local.publish(applied.record);\n await persistQueue(local, room.locator, remaining);\n outcomes.set(submitted.id, {\n kind: 'accepted',\n roomVersion: accepted.roomVersion,\n author: accepted.author,\n time: accepted.time,\n });\n unreadable.delete(room.locator);\n replicas.set(room.locator, replicaOf(applied, remaining));\n list(room, true);\n emitRooms();\n emitQueue(room.locator);\n emitVisible();\n journal.record(`outcome ${room.locator} ${submitted.id} accepted`);\n return true;\n });\n }\n\n async function submitRoom(\n room: DiscoveredRoom,\n local: ReplicaStore,\n authorized: Authorization,\n progress: CycleProgress,\n ): Promise<'stop' | null> {\n while (!closed && authorization !== undefined) {\n const replica = replicas.get(room.locator);\n const head = replica?.queue[0];\n if (replica === undefined || head === undefined || refused(outcomes.get(head.id))) {\n return null;\n }\n let result: MutationResult;\n journal.record(`submission ${room.locator} ${head.id}`);\n try {\n result = await options.adapter.mutate(authorized, {\n locator: room.locator,\n changeBatch: head,\n });\n } catch {\n progress.complete = false;\n progress.reachable = false;\n return null;\n }\n if (closed) return null;\n if (result.kind === 'transport-uncertainty') {\n progress.complete = false;\n progress.reachable = false;\n return null;\n }\n if (result.kind === 'room-not-readable') {\n progress.complete = false;\n unreadable.add(room.locator);\n list(room, false);\n emitRooms();\n return null;\n }\n if (result.kind === 'revoked-authorization') {\n refuse('revoked-authorization');\n return 'stop';\n }\n if (result.kind === 'scoped-refusal') {\n await scoped(result, room, local);\n progress.complete = false;\n return null;\n }\n if (result.kind === 'conflicted' || result.kind === 'rejected' || result.kind === 'expired') {\n journal.record(`outcome ${room.locator} ${head.id} ${result.kind}`);\n if (result.kind !== 'expired') journal.record(`refusal ${result.kind} ${result.text}`);\n await exclusive(async () => {\n await acrossTabs('mdruntime-replica', async () => {\n await hydrate(local);\n const current = replicas.get(room.locator);\n if (current === undefined || !current.queue.some((batch) => batch.id === head.id)) {\n return;\n }\n outcomes.set(head.id, recordRefusal(result));\n await persistQueue(local, room.locator, current.queue);\n emitQueue(room.locator);\n moveTo({ ...status, attentionRequired: true });\n });\n });\n return null;\n }\n const from = replicas.get(room.locator)?.confirmed;\n if (from === undefined) return null;\n const pulled = await pullRefresh(authorized, from);\n if (pulled.kind === 'revoked-authorization') {\n refuse('revoked-authorization');\n return 'stop';\n }\n if (pulled.kind === 'scoped-refusal') {\n await scoped(pulled, room, local);\n progress.complete = false;\n return null;\n }\n if (pulled.kind === 'still-current') {\n const committed = await exclusive(() =>\n commitAccept(room, local, head, result, from, true),\n );\n if (!committed) {\n progress.complete = false;\n return null;\n }\n continue;\n }\n if (pulled.kind === 'advanced') {\n const overlay = pulled.confirmed.record.roomVersion === result.roomVersion;\n const committed = await exclusive(() =>\n commitAccept(room, local, head, result, pulled.confirmed, overlay),\n );\n if (!committed) {\n progress.complete = false;\n return null;\n }\n continue;\n }\n if (pulled.kind === 'beyond-horizon') {\n const bootstrapped = await pullBootstrap(authorized, room);\n if (bootstrapped.kind === 'revoked-authorization') {\n refuse('revoked-authorization');\n return 'stop';\n }\n if (bootstrapped.kind === 'scoped-refusal') {\n await scoped(bootstrapped, room, local);\n progress.complete = false;\n return null;\n }\n if (bootstrapped.kind === 'staged') {\n const overlay = bootstrapped.confirmed.record.roomVersion === result.roomVersion;\n const committed = await exclusive(() =>\n commitAccept(room, local, head, result, bootstrapped.confirmed, overlay),\n );\n if (!committed) {\n progress.complete = false;\n return null;\n }\n continue;\n }\n progress.complete = false;\n if (bootstrapped.kind === 'transport-uncertainty') {\n progress.reachable = false;\n } else if (bootstrapped.kind === 'room-not-readable') {\n unreadable.add(room.locator);\n list(room, false);\n emitRooms();\n }\n return null;\n }\n progress.complete = false;\n if (pulled.kind === 'transport-uncertainty') {\n progress.reachable = false;\n } else if (pulled.kind === 'room-not-readable') {\n unreadable.add(room.locator);\n list(room, false);\n emitRooms();\n }\n return null;\n }\n return null;\n }\n\n async function retainModel(\n local: ReplicaStore,\n room: Omit<DiscoveredRoom, 'roomVersion'>,\n next: ModelState,\n ) {\n if (next.status === 'unavailable')\n modelEpoch.set(room.locator, (modelEpoch.get(room.locator) ?? 0) + 1);\n const epoch = modelEpoch.get(room.locator) ?? 0;\n const previous = modelOf(room.locator);\n const heldBefore = replicas.get(room.locator)?.confirmed.record;\n if (\n JSON.stringify(previous) === JSON.stringify(next) &&\n (heldBefore === undefined ||\n (JSON.stringify(heldBefore.operations) === JSON.stringify(room.operations) &&\n JSON.stringify(heldBefore.replica) === JSON.stringify(room.replica) &&\n JSON.stringify(heldBefore.attachedModel) === JSON.stringify(room.attachedModel)))\n )\n return;\n const queryChanged =\n previous.status === 'unavailable' || next.status === 'unavailable'\n ? previous.status !== next.status\n : JSON.stringify(previous.types) !== JSON.stringify(next.types);\n if (next.status === 'unavailable') {\n invalidModels.add(room.locator);\n liveModels.delete(room.locator);\n }\n await exclusive(async () =>\n acrossTabs('mdruntime-replica', async () => {\n await hydrate(local);\n if (next.status !== 'unavailable' && epoch !== (modelEpoch.get(room.locator) ?? 0)) return;\n const held = replicas.get(room.locator);\n if (held !== undefined) {\n const record = {\n ...held.confirmed.record,\n operations: room.operations,\n replica: room.replica,\n attachedModel: room.attachedModel,\n model: next,\n };\n await local.publish(record);\n const confirmed = readConfirmed(record);\n if (confirmed !== null) replicas.set(room.locator, replicaOf(confirmed, held.queue));\n }\n models.set(room.locator, next);\n if (next.status === 'current') {\n liveModels.set(room.locator, JSON.stringify(next.snapshot));\n invalidModels.delete(room.locator);\n }\n list(room, room.replica.admission === 'admitted' && !unreadable.has(room.locator));\n emitRooms();\n if (queryChanged && held !== undefined) emitVisible();\n announce();\n }),\n );\n }\n\n async function acquireModel(\n local: ReplicaStore,\n room: DiscoveredRoom,\n authorized: Authorization,\n ) {\n let previous = modelOf(room.locator);\n if (\n previous.status !== 'unavailable' &&\n (room.attachedModel === null || !sameModel(previous.snapshot, room.attachedModel))\n ) {\n previous = { status: 'unavailable', reason: 'version-changed' };\n await retainModel(local, room, previous);\n }\n const epoch = modelEpoch.get(room.locator) ?? 0;\n let answer;\n try {\n answer = await options.adapter.model(authorized, {\n locator: room.locator,\n collectionRoot: room.collectionRoot,\n model: room.attachedModel,\n });\n } catch {\n answer = { kind: 'transport-uncertainty' as const };\n }\n if (epoch !== (modelEpoch.get(room.locator) ?? 0)) return;\n if (answer.kind === 'revoked-authorization') {\n await retainModel(local, room, { status: 'unavailable', reason: 'revoked' });\n refuse('revoked-authorization');\n return;\n }\n if (answer.kind === 'transport-uncertainty') {\n await retainModel(local, room, cached(previous));\n return;\n }\n if (answer.kind === 'model-unavailable') {\n await retainModel(local, room, { status: 'unavailable', reason: answer.reason });\n return;\n }\n if (room.attachedModel === null || !sameModel(answer.snapshot, room.attachedModel)) {\n await retainModel(local, room, { status: 'unavailable', reason: 'version-changed' });\n return;\n }\n if (\n previous.status !== 'unavailable' &&\n sameModel(previous.snapshot, answer.snapshot) &&\n JSON.stringify(Object.entries(previous.snapshot.definitions).sort()) !==\n JSON.stringify(Object.entries(answer.snapshot.definitions).sort())\n ) {\n await retainModel(local, room, { status: 'unavailable', reason: 'invalid' });\n return;\n }\n const verified = options.modelBinding?.verify(answer.snapshot);\n await retainModel(\n local,\n room,\n verified?.kind === 'verified'\n ? {\n status: 'current',\n snapshot: structuredClone(answer.snapshot),\n verifiedWith: MD_MODEL,\n types: verified.types,\n }\n : {\n status: 'unavailable',\n reason: verified === undefined ? 'binding-unavailable' : 'invalid',\n },\n );\n }\n\n async function scoped(\n result: import('./adapter.js').ScopedRefusal,\n room: DiscoveredRoom,\n local: ReplicaStore,\n ) {\n if (result.scope === 'model')\n await retainModel(local, room, { status: 'unavailable', reason: 'not-readable' });\n else if (result.scope !== 'operation') {\n unreadable.add(room.locator);\n const unavailable: DiscoveredRoom = {\n ...room,\n replica: { ...room.replica, admission: 'unavailable' },\n operations: {\n ...room.operations,\n ...(result.scope === 'content' ? { read: [] } : {}),\n ...(result.scope === 'sync' ? { sync: [] } : {}),\n },\n };\n await retainModel(local, unavailable, modelOf(room.locator));\n list(unavailable, false);\n emitRooms();\n }\n journal.record(`scoped refusal ${room.locator} ${result.scope} ${result.text}`);\n }\n\n async function synchronize(\n discovered: readonly DiscoveredRoom[],\n local: ReplicaStore,\n progress: CycleProgress,\n ) {\n for (const room of discovered) {\n if (closed || authorization === undefined) {\n progress.complete = false;\n return;\n }\n const prior = replicas.get(room.locator)?.confirmed.record;\n if (prior !== undefined && prior.replica.selection !== room.replica.selection) {\n list(prior, false);\n emitRooms();\n journal.record(`selection changed ${room.locator}`);\n progress.complete = false;\n continue;\n }\n await acquireModel(local, room, authorization);\n if (discoveryPaused) return;\n if (room.replica.admission !== 'admitted') {\n progress.complete = false;\n continue;\n }\n const held = replicas.get(room.locator);\n if (\n held !== undefined &&\n held.confirmed.record.replica.selection !== room.replica.selection\n ) {\n progress.complete = false;\n continue;\n }\n const withheld = await advance(room, local, authorization);\n if (withheld !== null) {\n progress.complete = false;\n if (withheld.kind === 'scoped-refusal') {\n await scoped(withheld, room, local);\n continue;\n }\n if (withheld.kind === 'transport-uncertainty') {\n progress.reachable = false;\n continue;\n }\n if (withheld.kind === 'room-not-readable') {\n unreadable.add(room.locator);\n list(room, false);\n emitRooms();\n continue;\n }\n if (withheld.kind === 'revoked-authorization') {\n refuse('revoked-authorization');\n return;\n }\n continue;\n }\n if ((await submitRoom(room, local, authorization, progress)) === 'stop') return;\n }\n }\n\n async function cycle(local: ReplicaStore, progress: CycleProgress) {\n if (closed || authorization === undefined) {\n notifyReady();\n return;\n }\n moveTo(transferring(status));\n let result;\n try {\n result = await options.adapter.discover(authorization);\n } catch {\n result = { kind: 'transport-uncertainty' as const };\n }\n if (closed) {\n notifyReady();\n return;\n }\n journal.record(`connection discover ${result.kind}`);\n if (result.kind === 'transport-uncertainty') {\n for (const room of rooms.values())\n await retainModel(local, room, cached(modelOf(room.locator)));\n progress.reachable = false;\n notifyReady();\n return;\n }\n if (result.kind === 'contract-unavailable') {\n journal.record(`connection contract unavailable ${result.text}`);\n refuse('missing-required-guarantee');\n notifyReady();\n return;\n }\n if (result.kind === 'revoked-authorization') {\n refuse('revoked-authorization');\n notifyReady();\n return;\n }\n if (!result.supportedVersions.includes(ROOM_CONTRACT_VERSION)) {\n refuse('no-matching-version');\n notifyReady();\n return;\n }\n if (\n result.mdModel.identity !== MD_MODEL.identity ||\n result.mdModel.version !== MD_MODEL.version\n ) {\n refuse('md-model-version-mismatch');\n notifyReady();\n return;\n }\n mismatchedRoots.clear();\n for (const room of result.rooms) {\n const held = replicas.get(room.locator)?.confirmed.record;\n const malformed = !validRoot(room.collectionRoot);\n if (\n room.operations === undefined ||\n !['read', 'sync', 'write', 'delete'].every(\n (operation) =>\n Array.isArray(room.operations[operation as keyof typeof room.operations]) &&\n room.operations[operation as keyof typeof room.operations].every(\n (scope) => typeof scope === 'string',\n ),\n ) ||\n room.replica === undefined ||\n typeof room.replica.selection !== 'string' ||\n room.replica.selection.length === 0 ||\n !['admitted', 'unavailable'].includes(room.replica.admission) ||\n room.attachedModel === undefined ||\n (room.attachedModel !== null &&\n (typeof room.attachedModel.identity !== 'string' ||\n !room.attachedModel.identity ||\n typeof room.attachedModel.version !== 'string' ||\n !room.attachedModel.version))\n ) {\n journal.record(`invalid model or replica declaration ${room.locator}`);\n refuse('missing-required-guarantee');\n notifyReady();\n return;\n }\n if (malformed || (held !== undefined && held.collectionRoot !== room.collectionRoot)) {\n mismatchedRoots.add(room.locator);\n journal.record(`collection root ${malformed ? 'invalid' : 'changed'} ${room.locator}`);\n }\n }\n if (mismatchedRoots.size > 0) {\n refuse('missing-required-guarantee');\n notifyReady();\n return;\n }\n const declared = new Set(result.capabilities.map((capability) => capability.name));\n for (const required of options.requiredGuarantees) {\n if (!knownCapabilities.has(required) || !declared.has(required)) {\n refuse('missing-required-guarantee');\n notifyReady();\n return;\n }\n }\n if (refusal !== null) {\n refusal = null;\n emitRefusal();\n }\n capabilities = result.capabilities;\n notifyReady();\n if (JSON.stringify(result.providerLimits) !== JSON.stringify(limits)) {\n limits = result.providerLimits;\n await local.declare(limits);\n }\n const listedLocators = applyDiscovery(result.rooms);\n progress.complete = [...replicas.keys()].every((locator) => listedLocators.has(locator));\n await synchronize(result.rooms, local, progress);\n }\n\n async function ensureAuthorization() {\n if (authorization !== undefined) return;\n try {\n authorization = await options.adapter.authorize();\n journal.record('connection authorize');\n } catch (error) {\n journal.record('connection authorize transport-uncertainty');\n throw error;\n }\n }\n\n async function connect() {\n if (closed || discoveryPaused) {\n notifyReady();\n return;\n }\n startTimer();\n const progress: CycleProgress = { complete: false, reachable: true };\n let completedAt = new Date().toISOString();\n try {\n const local = await openLocal();\n if (closed) return;\n await ensureAuthorization();\n if (closed) return;\n await cycle(local, progress);\n if (closed) return;\n if (progress.complete) {\n completedAt = new Date().toISOString();\n await local.complete(completedAt);\n }\n } catch {\n progress.complete = false;\n notifyReady();\n return;\n } finally {\n notifyReady();\n moveTo(settled(status, progress, completedAt, pending(), attention()));\n }\n }\n\n async function run() {\n try {\n await connect();\n } finally {\n inflight = false;\n if (queued && !closed) {\n queued = false;\n void enqueue();\n }\n }\n }\n\n function enqueue() {\n if (!leader) {\n announce('enqueue');\n return chain;\n }\n if (inflight) {\n queued = true;\n return chain;\n }\n inflight = true;\n chain = chain.then(run, run);\n return chain;\n }\n\n function startProcessing() {\n if (leader) {\n void enqueue();\n return;\n }\n void window.navigator.locks\n .request('mdruntime-sync', { signal: options.signal }, async () => {\n if (closed) return;\n leader = true;\n announce();\n void enqueue();\n await new Promise<void>((resolve) => {\n releaseLeadership = () => {\n leader = false;\n resolve();\n };\n });\n })\n .catch(() => {});\n }\n\n function close() {\n closed = true;\n stopTimer();\n releaseLeadership();\n channel?.close();\n store?.close();\n roomListeners.clear();\n refusalListeners.clear();\n storageLossListeners.clear();\n statusListeners.clear();\n querySubscriptions.clear();\n queueSubscriptions.clear();\n draftListeners.clear();\n }\n\n channel?.addEventListener('message', (event) => {\n const data = event.data;\n if (data === null || typeof data !== 'object') return;\n void exclusive(() => applyRemote(data as { type?: unknown; status?: SyncStatus }));\n });\n\n options.signal?.addEventListener('abort', close, { once: true });\n if (options.signal?.aborted) close();\n\n void openLocal().then(\n () => {\n if (!leader) notifyReady();\n },\n () => {\n notifyReady();\n },\n );\n startProcessing();\n\n return {\n rooms() {\n return listed();\n },\n query(request: QueryOptions = {}) {\n return visible(request);\n },\n types(locator: string) {\n return modelTypes(modelOf(locator));\n },\n syncStatus() {\n return status;\n },\n draft: {\n list() {\n return exclusive(async () => {\n const local = await openLocal();\n return readDrafts(local);\n }).then((entries) => {\n releaseWaitingDrafts();\n return entries;\n });\n },\n read(locator: string, path: string) {\n const content = draftContent(locator, path);\n return content === undefined ? null : structuredClone(content);\n },\n replace(locator: string, path: string, content: unknown) {\n return commitDraft(async (local) => {\n const stored = structuredClone(content);\n await local.keep({ locator, path, content: stored });\n rememberDraft(locator, path, stored);\n });\n },\n discard(locator: string, path: string) {\n return commitDraft(async (local) => {\n await local.discard(locator, path);\n forgetDraft(locator, path);\n });\n },\n },\n save(locator: string, changes: readonly Change[], replacing?: string): Promise<SaveResult> {\n return exclusive(() => write(locator, changes, replacing));\n },\n outcome(identifier: string): SubmissionOutcome | null {\n const recorded = outcomes.get(identifier);\n if (recorded !== undefined) return recorded;\n for (const replica of replicas.values()) {\n if (replica.queue.some((batch) => batch.id === identifier)) return { kind: 'pending' };\n }\n return null;\n },\n queue: {\n discard(locator: string, identifier: string) {\n return exclusive(() => discardHead(locator, identifier));\n },\n },\n history(locator: string, path: string, query?: HistoryQuery) {\n return readHistory(locator, path, query);\n },\n call(name: string, input: unknown) {\n return invokeAction(name, input);\n },\n log() {\n return journal.export();\n },\n storageLoss() {\n return storageLoss;\n },\n observe(\n topic:\n | 'rooms'\n | 'connection-refusal'\n | 'storage-loss'\n | 'sync-status'\n | 'query'\n | 'queue'\n | 'drafts',\n second: QueryOptions | string | ((value: never) => void),\n third?: (value: never) => void,\n ) {\n if (topic === 'drafts') {\n const notify = second as (value: readonly DraftEntry[]) => void;\n const listener: DraftSubscription = { notify, ready: false };\n draftListeners.add(listener);\n void exclusive(async () => {\n const local = await openLocal();\n await readDrafts(local);\n if (closed || !draftListeners.has(listener)) return;\n listener.ready = true;\n }).then(\n () => {\n if (closed || !listener.ready || !draftListeners.has(listener)) return;\n listener.notify(snapshotDrafts());\n },\n () => {},\n );\n return () => {\n draftListeners.delete(listener);\n };\n }\n if (topic === 'rooms') {\n const notify = second as (value: readonly AppRoom[]) => void;\n roomListeners.add(notify);\n notify(listed());\n return () => {\n roomListeners.delete(notify);\n };\n }\n if (topic === 'connection-refusal') {\n const notify = second as (value: ConnectionRefusal | null) => void;\n refusalListeners.add(notify);\n notify(refusal);\n return () => {\n refusalListeners.delete(notify);\n };\n }\n if (topic === 'storage-loss') {\n const notify = second as (value: string | null) => void;\n storageLossListeners.add(notify);\n notify(storageLoss);\n return () => {\n storageLossListeners.delete(notify);\n };\n }\n if (topic === 'sync-status') {\n const notify = second as (value: SyncStatus) => void;\n statusListeners.add(notify);\n notify(status);\n return () => {\n statusListeners.delete(notify);\n };\n }\n if (topic === 'queue') {\n const queue: QueueSubscription = {\n locator: second as string,\n notify: third as (entries: readonly QueueEntry[]) => void,\n };\n queueSubscriptions.add(queue);\n queue.notify(entriesOf(queue.locator));\n return () => {\n queueSubscriptions.delete(queue);\n };\n }\n const subscription: QuerySubscription = {\n query: second as QueryOptions,\n notify: third as (result: QueryResult) => void,\n };\n const first = visible(subscription.query);\n querySubscriptions.add(subscription);\n subscription.notify(first);\n return () => {\n querySubscriptions.delete(subscription);\n };\n },\n async reauthorize() {\n if (refusal === null || !refusal.reauthorizationOffered) return;\n journal.record('connection reauthorize');\n authorization = undefined;\n discoveryPaused = false;\n await enqueue();\n },\n };\n}\n"],"names":["rawQuery","cached","modelTypes","NO_MODEL","sameModel","ROOM_CONTRACT_VERSION","VERSION_1_CAPABILITIES","bootstrapRoom","MD_MODEL","PRESENTED","validRoot","createLog","queuedOutcome","refused","refreshRoom","buildBatch","applyReturned","readConfirmed","replicaOf","settled","same","saving","STARTING","transferring","detectStorageLoss","nextGeneration","openReplicaStore","unconfirmed","DEFAULT_DISCOVERY_INTERVAL_MS","knownCapabilities","Set","createMdRuntime","options","period","discoveryIntervalMs","authorization","opening","store","replicas","Map","drafts","outcomes","limits","capabilities","rooms","unreadable","models","liveModels","invalidModels","modelEpoch","modelOf","locator","get","mismatchedRoots","refusal","storageLoss","status","discoveryPaused","timer","closed","chain","Promise","resolve","mutations","inflight","queued","roomListeners","refusalListeners","storageLossListeners","statusListeners","querySubscriptions","queueSubscriptions","draftListeners","journal","notifyReady","ready","leader","window","applyingRemote","releaseLeadership","channel","BroadcastChannel","undefined","draftContent","path","rememberDraft","content","room","set","forgetDraft","delete","size","snapshotDrafts","entries","push","structuredClone","sort","left","right","readDrafts","opened","acrossTabs","hydrate","publishDrafts","waitingOnly","value","listener","notify","emitDrafts","releaseWaitingDrafts","commitDraft","work","exclusive","local","openLocal","then","announce","pending","values","some","replica","queue","length","attention","head","id","storedOutcomes","batches","stored","batch","outcome","kind","persistQueue","writeQueue","listed","queryRooms","map","confirmed","record","roomVersion","documents","visible","collection","model","emitRooms","emitRefusal","emitStorageLoss","type","postMessage","adopt","next","moveTo","request","queryBinding","Object","keys","Error","selector","$and","emitVisible","subscription","query","entriesOf","freeze","emitQueue","stopTimer","clearInterval","startTimer","setInterval","enqueue","refuse","reason","revoked","add","all","publish","catch","reauthorizationOffered","list","synchronizationAvailable","name","collectionRoot","operations","attachedModel","providerOwnedPaths","applyDiscovery","discovered","listedLocators","held","selection","admission","has","records","queues","kept","lastCompleted","declared","providerLimits","clear","draft","queuedBatches","persisted","priorModel","snapshot","JSON","stringify","existing","locators","readState","applyRemote","message","attentionRequired","state","open","storedGeneration","generation","loss","rememberGeneration","error","navigator","locks","retained","write","changes","replacing","result","rule","built","baseRoomVersion","binding","modelBinding","slice","consumed","change","append","discardHead","identifier","changed","readHistory","ensureAuthorization","transfer","revision","pageToken","join","adapter","history","scoped","declaredAction","capability","action","actions","invokeAction","input","text","pullRefresh","authorized","detail","pullBootstrap","advance","refreshed","bootstrapped","recordRefusal","affected","commitAccept","submitted","accepted","base","overlay","current","remaining","filter","retainedBase","applied","revisions","removals","author","time","submitRoom","progress","mutate","changeBatch","complete","reachable","from","pulled","committed","retainModel","epoch","previous","heldBefore","queryChanged","types","acquireModel","answer","definitions","verified","verify","verifiedWith","scope","unavailable","read","sync","synchronize","prior","withheld","cycle","discover","supportedVersions","includes","mdModel","identity","version","malformed","every","operation","Array","isArray","required","requiredGuarantees","declare","authorize","connect","completedAt","Date","toISOString","run","startProcessing","signal","close","addEventListener","event","data","once","aborted","syncStatus","replace","keep","discard","save","recorded","call","log","export","observe","topic","second","third","first","reauthorize"],"mappings":"AAAA,SAASA,QAAQ,QAA4C,aAAa;AAC1E,SACEC,MAAM,EACNC,UAAU,EACVC,QAAQ,EACRC,SAAS,QAIJ,aAAa;AAOpB,SACEC,qBAAqB,EACrBC,sBAAsB,QAUjB,eAAe;AACtB,SAASC,aAAa,QAAQ,iBAAiB;AAE/C,SAASC,QAAQ,EAAEC,SAAS,EAAEC,SAAS,QAAqB,kBAAkB;AAC9E,SAASC,SAAS,QAAQ,WAAW;AACrC,SACEC,aAAa,EACbC,OAAO,QAIF,eAAe;AACtB,SAASC,WAAW,QAAQ,eAAe;AAC3C,SAASC,UAAU,QAA0B,YAAY;AACzD,SACEC,aAAa,EACbC,aAAa,EACbC,SAAS,QAGJ,eAAe;AACtB,SACEC,OAAO,EACPC,IAAI,EACJC,MAAM,EACNC,QAAQ,EACRC,YAAY,QAGP,cAAc;AACrB,SAASC,iBAAiB,EAAEC,cAAc,QAAQ,kBAAkB;AACpE,SAASC,gBAAgB,QAA2B,aAAa;AACjE,SAASC,WAAW,QAA0B,gBAAgB;AAE9D,MAAMC,gCAAgC;AAEtC,MAAMC,oBAAoB,IAAIC,IAAYxB;AA+G1C,OAAO,SAASyB,gBAAgBC,OAAyB;IACvD,MAAMC,SAASD,QAAQE,mBAAmB,IAAIN;IAC9C,IAAIO,gBAA2CH,QAAQG,aAAa;IACpE,IAAIC;IACJ,IAAIC;IACJ,MAAMC,WAAW,IAAIC;IACrB,MAAMC,SAAS,IAAID;IACnB,MAAME,WAAW,IAAIF;IACrB,IAAIG,SAAmC,EAAE;IACzC,IAAIC,eAAsC,EAAE;IAC5C,MAAMC,QAAQ,IAAIL;IAClB,MAAMM,aAAa,IAAIf;IACvB,MAAMgB,SAAS,IAAIP;IACnB,MAAMQ,aAAa,IAAIR;IACvB,MAAMS,gBAAgB,IAAIlB;IAC1B,M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GAAG,CAACpD;gBACvBA,MAAMd,MAAM,CAACuD,UAAUzC,MAAMtE,OAAO;gBACpC,OAAO;oBACLoB,mBAAmBmB,MAAM,CAAC+B;gBAC5B;YACF;YACA,MAAMuC,eAAkC;gBACtCC,OAAOwL;gBACP9O,QAAQ+O;YACV;YACA,MAAMC,QAAQ9M,QAAQmB,aAAaC,KAAK;YACxC3F,mBAAmBuG,GAAG,CAACb;YACvBA,aAAarD,MAAM,CAACgP;YACpB,OAAO;gBACLrR,mBAAmBoB,MAAM,CAACsE;YAC5B;QACF;QACA,MAAM4L;YACJ,IAAItS,YAAY,QAAQ,CAACA,QAAQ2H,sBAAsB,EAAE;YACzDxG,QAAQiE,MAAM,CAAC;YACfvG,gBAAgB+C;YAChBzB,kBAAkB;YAClB,MAAMgH;QACR;IACF;AACF"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"identity.d.ts","sourceRoot":"","sources":["../src/identity.ts"],"names":[],"mappings":"AAAA,wBAAgB,mBAAmB,CAAC,EAAE,GAAE,MAAmB,GAAG,MAAM,CAWnE"}
|
package/dist/identity.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export function changeBatchIdentity(at = Date.now()) {
|
|
2
|
+
const bytes = new Uint8Array(16);
|
|
3
|
+
crypto.getRandomValues(bytes);
|
|
4
|
+
const time = BigInt(at);
|
|
5
|
+
for(let index = 0; index < 6; index += 1){
|
|
6
|
+
bytes[index] = Number(time >> BigInt(8 * (5 - index)) & 0xffn);
|
|
7
|
+
}
|
|
8
|
+
bytes[6] = bytes[6] & 0x0f | 0x70;
|
|
9
|
+
bytes[8] = bytes[8] & 0x3f | 0x80;
|
|
10
|
+
const hex = [
|
|
11
|
+
...bytes
|
|
12
|
+
].map((byte)=>byte.toString(16).padStart(2, '0')).join('');
|
|
13
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
//# sourceMappingURL=identity.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/workspace/packages/mdruntime/src/identity.ts"],"sourcesContent":["export function changeBatchIdentity(at: number = Date.now()): string {\n const bytes = new Uint8Array(16);\n crypto.getRandomValues(bytes);\n const time = BigInt(at);\n for (let index = 0; index < 6; index += 1) {\n bytes[index] = Number((time >> BigInt(8 * (5 - index))) & 0xffn);\n }\n bytes[6] = (bytes[6] & 0x0f) | 0x70;\n bytes[8] = (bytes[8] & 0x3f) | 0x80;\n const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, '0')).join('');\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n"],"names":["changeBatchIdentity","at","Date","now","bytes","Uint8Array","crypto","getRandomValues","time","BigInt","index","Number","hex","map","byte","toString","padStart","join","slice"],"mappings":"AAAA,OAAO,SAASA,oBAAoBC,KAAaC,KAAKC,GAAG,EAAE;IACzD,MAAMC,QAAQ,IAAIC,WAAW;IAC7BC,OAAOC,eAAe,CAACH;IACvB,MAAMI,OAAOC,OAAOR;IACpB,IAAK,IAAIS,QAAQ,GAAGA,QAAQ,GAAGA,SAAS,EAAG;QACzCN,KAAK,CAACM,MAAM,GAAGC,OAAO,AAACH,QAAQC,OAAO,IAAK,CAAA,IAAIC,KAAI,KAAO,KAAK;IACjE;IACAN,KAAK,CAAC,EAAE,GAAG,AAACA,KAAK,CAAC,EAAE,GAAG,OAAQ;IAC/BA,KAAK,CAAC,EAAE,GAAG,AAACA,KAAK,CAAC,EAAE,GAAG,OAAQ;IAC/B,MAAMQ,MAAM;WAAIR;KAAM,CAACS,GAAG,CAAC,CAACC,OAASA,KAAKC,QAAQ,CAAC,IAAIC,QAAQ,CAAC,GAAG,MAAMC,IAAI,CAAC;IAC9E,OAAO,GAAGL,IAAIM,KAAK,CAAC,GAAG,GAAG,CAAC,EAAEN,IAAIM,KAAK,CAAC,GAAG,IAAI,CAAC,EAAEN,IAAIM,KAAK,CAAC,IAAI,IAAI,CAAC,EAAEN,IAAIM,KAAK,CAAC,IAAI,IAAI,CAAC,EAAEN,IAAIM,KAAK,CAAC,KAAK;AAC5G"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type { ActionDeclaration, ActionRequest, ActionResult, Adapter, AdapterFailure, Authorization, BootstrapPage, BootstrapRequest, BootstrapResult, Capability, DiscoverResult, DiscoveredRoom, Discovery, HistoryRequest, HistoryResult, HistoryRevision, MdModelIdentity, MutationRequest, MutationResult, PageToken, ProviderLimit, RefreshPage, RefreshRequest, RefreshResult, Retention, RevokedAuthorization, RoomNotReadable, TransportUncertainty, } from './adapter.js';
|
|
1
|
+
export type { ActionDeclaration, ActionRequest, ActionResult, Adapter, AdapterFailure, Authorization, BootstrapPage, BootstrapRequest, BootstrapResult, Capability, DiscoverResult, DiscoveredRoom, Discovery, HistoryRequest, HistoryResult, HistoryRetention, HistoryRevision, MdModelIdentity, MutationRequest, MutationResult, PageToken, ProviderLimit, RefreshPage, RefreshRequest, RefreshResult, Retention, RevokedAuthorization, RoomNotReadable, TransportUncertainty, } from './adapter.js';
|
|
2
2
|
export type { Change, ChangeBatch, Precondition } from './change.js';
|
|
3
3
|
export type { MdType } from './collection.js';
|
|
4
4
|
export type { AppRoom, CallResult, ConnectionRefusal, ConnectionRefusalReason, DraftEntry, DraftSurface, HistoryQuery, MdRuntime, MdRuntimeOptions, QueueSurface, SaveResult, } from './connection.js';
|
|
@@ -7,4 +7,7 @@ export type { SaveRefusal } from './save.js';
|
|
|
7
7
|
export { createMdRuntime } from './connection.js';
|
|
8
8
|
export type { SyncStatus } from './status.js';
|
|
9
9
|
export type { Backlink, QueryDocument, QueryGroup, QueryOptions, QueryResult, Selector, } from '@agentshouse/query';
|
|
10
|
+
export type { AttachedModelBinding, ModelIdentity, ModelSnapshot, ModelState, ModelResult, ModelValidation, TypesResult, ValidationReceipt, } from './model.js';
|
|
11
|
+
export type { OperationScopes, ReplicaAdmission, ScopedRefusal } from './adapter.js';
|
|
12
|
+
export type { QueryBinding, QueryInput } from './query.js';
|
|
10
13
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,iBAAiB,EACjB,aAAa,EACb,YAAY,EACZ,OAAO,EACP,cAAc,EACd,aAAa,EACb,aAAa,EACb,gBAAgB,EAChB,eAAe,EACf,UAAU,EACV,cAAc,EACd,cAAc,EACd,SAAS,EACT,cAAc,EACd,aAAa,EACb,eAAe,EACf,eAAe,EACf,eAAe,EACf,cAAc,EACd,SAAS,EACT,aAAa,EACb,WAAW,EACX,cAAc,EACd,aAAa,EACb,SAAS,EACT,oBAAoB,EACpB,eAAe,EACf,oBAAoB,GACrB,MAAM,cAAc,CAAC;AACtB,YAAY,EAAE,MAAM,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AACrE,YAAY,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAC9C,YAAY,EACV,OAAO,EACP,UAAU,EACV,iBAAiB,EACjB,uBAAuB,EACvB,UAAU,EACV,YAAY,EACZ,YAAY,EACZ,SAAS,EACT,gBAAgB,EAChB,YAAY,EACZ,UAAU,GACX,MAAM,iBAAiB,CAAC;AACzB,YAAY,EACV,eAAe,EACf,aAAa,EACb,UAAU,EACV,YAAY,EACZ,iBAAiB,GAClB,MAAM,cAAc,CAAC;AACtB,YAAY,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAC7C,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,YAAY,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAC9C,YAAY,EACV,QAAQ,EACR,aAAa,EACb,UAAU,EACV,YAAY,EACZ,WAAW,EACX,QAAQ,GACT,MAAM,oBAAoB,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,iBAAiB,EACjB,aAAa,EACb,YAAY,EACZ,OAAO,EACP,cAAc,EACd,aAAa,EACb,aAAa,EACb,gBAAgB,EAChB,eAAe,EACf,UAAU,EACV,cAAc,EACd,cAAc,EACd,SAAS,EACT,cAAc,EACd,aAAa,EACb,gBAAgB,EAChB,eAAe,EACf,eAAe,EACf,eAAe,EACf,cAAc,EACd,SAAS,EACT,aAAa,EACb,WAAW,EACX,cAAc,EACd,aAAa,EACb,SAAS,EACT,oBAAoB,EACpB,eAAe,EACf,oBAAoB,GACrB,MAAM,cAAc,CAAC;AACtB,YAAY,EAAE,MAAM,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AACrE,YAAY,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAC9C,YAAY,EACV,OAAO,EACP,UAAU,EACV,iBAAiB,EACjB,uBAAuB,EACvB,UAAU,EACV,YAAY,EACZ,YAAY,EACZ,SAAS,EACT,gBAAgB,EAChB,YAAY,EACZ,UAAU,GACX,MAAM,iBAAiB,CAAC;AACzB,YAAY,EACV,eAAe,EACf,aAAa,EACb,UAAU,EACV,YAAY,EACZ,iBAAiB,GAClB,MAAM,cAAc,CAAC;AACtB,YAAY,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAC7C,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAClD,YAAY,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAC9C,YAAY,EACV,QAAQ,EACR,aAAa,EACb,UAAU,EACV,YAAY,EACZ,WAAW,EACX,QAAQ,GACT,MAAM,oBAAoB,CAAC;AAE5B,YAAY,EACV,oBAAoB,EACpB,aAAa,EACb,aAAa,EACb,UAAU,EACV,WAAW,EACX,eAAe,EACf,WAAW,EACX,iBAAiB,GAClB,MAAM,YAAY,CAAC;AACpB,YAAY,EAAE,eAAe,EAAE,gBAAgB,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AACrF,YAAY,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC"}
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["/workspace/packages/mdruntime/src/index.ts"],"sourcesContent":["export type {\n ActionDeclaration,\n ActionRequest,\n ActionResult,\n Adapter,\n AdapterFailure,\n Authorization,\n BootstrapPage,\n BootstrapRequest,\n BootstrapResult,\n Capability,\n DiscoverResult,\n DiscoveredRoom,\n Discovery,\n HistoryRequest,\n HistoryResult,\n HistoryRevision,\n MdModelIdentity,\n MutationRequest,\n MutationResult,\n PageToken,\n ProviderLimit,\n RefreshPage,\n RefreshRequest,\n RefreshResult,\n Retention,\n RevokedAuthorization,\n RoomNotReadable,\n TransportUncertainty,\n} from './adapter.js';\nexport type { Change, ChangeBatch, Precondition } from './change.js';\nexport type { MdType } from './collection.js';\nexport type {\n AppRoom,\n CallResult,\n ConnectionRefusal,\n ConnectionRefusalReason,\n DraftEntry,\n DraftSurface,\n HistoryQuery,\n MdRuntime,\n MdRuntimeOptions,\n QueueSurface,\n SaveResult,\n} from './connection.js';\nexport type {\n AcceptedOutcome,\n AffectedState,\n QueueEntry,\n QueueOutcome,\n SubmissionOutcome,\n} from './outcome.js';\nexport type { SaveRefusal } from './save.js';\nexport { createMdRuntime } from './connection.js';\nexport type { SyncStatus } from './status.js';\nexport type {\n Backlink,\n QueryDocument,\n QueryGroup,\n QueryOptions,\n QueryResult,\n Selector,\n} from '@agentshouse/query';\n"],"names":["createMdRuntime"],"mappings":"
|
|
1
|
+
{"version":3,"sources":["/workspace/packages/mdruntime/src/index.ts"],"sourcesContent":["export type {\n ActionDeclaration,\n ActionRequest,\n ActionResult,\n Adapter,\n AdapterFailure,\n Authorization,\n BootstrapPage,\n BootstrapRequest,\n BootstrapResult,\n Capability,\n DiscoverResult,\n DiscoveredRoom,\n Discovery,\n HistoryRequest,\n HistoryResult,\n HistoryRetention,\n HistoryRevision,\n MdModelIdentity,\n MutationRequest,\n MutationResult,\n PageToken,\n ProviderLimit,\n RefreshPage,\n RefreshRequest,\n RefreshResult,\n Retention,\n RevokedAuthorization,\n RoomNotReadable,\n TransportUncertainty,\n} from './adapter.js';\nexport type { Change, ChangeBatch, Precondition } from './change.js';\nexport type { MdType } from './collection.js';\nexport type {\n AppRoom,\n CallResult,\n ConnectionRefusal,\n ConnectionRefusalReason,\n DraftEntry,\n DraftSurface,\n HistoryQuery,\n MdRuntime,\n MdRuntimeOptions,\n QueueSurface,\n SaveResult,\n} from './connection.js';\nexport type {\n AcceptedOutcome,\n AffectedState,\n QueueEntry,\n QueueOutcome,\n SubmissionOutcome,\n} from './outcome.js';\nexport type { SaveRefusal } from './save.js';\nexport { createMdRuntime } from './connection.js';\nexport type { SyncStatus } from './status.js';\nexport type {\n Backlink,\n QueryDocument,\n QueryGroup,\n QueryOptions,\n QueryResult,\n Selector,\n} from '@agentshouse/query';\n\nexport type {\n AttachedModelBinding,\n ModelIdentity,\n ModelSnapshot,\n ModelState,\n ModelResult,\n ModelValidation,\n TypesResult,\n ValidationReceipt,\n} from './model.js';\nexport type { OperationScopes, ReplicaAdmission, ScopedRefusal } from './adapter.js';\nexport type { QueryBinding, QueryInput } from './query.js';\n"],"names":["createMdRuntime"],"mappings":"AAsDA,SAASA,eAAe,QAAQ,kBAAkB"}
|
package/dist/memory.d.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
+
import type { ModelResult } from './model.js';
|
|
1
2
|
import { type Adapter, type Capability, type DiscoveredRoom, type MdModelIdentity, type ProviderLimit, type Retention } from './adapter.js';
|
|
2
3
|
export type MemoryRoom = DiscoveredRoom & {
|
|
4
|
+
model?: ModelResult;
|
|
3
5
|
documents?: Readonly<Record<string, string>>;
|
|
4
6
|
revisions?: Readonly<Record<string, string>>;
|
|
5
7
|
binaryTargets?: readonly string[];
|
package/dist/memory.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"memory.d.ts","sourceRoot":"","sources":["../src/memory.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,KAAK,OAAO,EAIZ,KAAK,UAAU,EAEf,KAAK,cAAc,EAGnB,KAAK,eAAe,EAGpB,KAAK,aAAa,EAGlB,KAAK,SAAS,EACf,MAAM,cAAc,CAAC;
|
|
1
|
+
{"version":3,"file":"memory.d.ts","sourceRoot":"","sources":["../src/memory.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,EAIL,KAAK,OAAO,EAIZ,KAAK,UAAU,EAEf,KAAK,cAAc,EAGnB,KAAK,eAAe,EAGpB,KAAK,aAAa,EAGlB,KAAK,SAAS,EACf,MAAM,cAAc,CAAC;AAkBtB,MAAM,MAAM,UAAU,GAAG,cAAc,GAAG;IACxC,KAAK,CAAC,EAAE,WAAW,CAAC;IACpB,SAAS,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IAC7C,SAAS,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IAC7C,aAAa,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CACnC,CAAC;AAEF,MAAM,MAAM,oBAAoB,GAAG;IACjC,KAAK,CAAC,EAAE,SAAS,UAAU,EAAE,CAAC;IAC9B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,OAAO,CAAC,EAAE,eAAe,CAAC;IAC1B,iBAAiB,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IACtC,YAAY,CAAC,EAAE,SAAS,UAAU,EAAE,CAAC;IACrC,cAAc,CAAC,EAAE,SAAS,aAAa,EAAE,CAAC;IAC1C,SAAS,CAAC,EAAE,SAAS,CAAC;IACtB,OAAO,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAC7B,CAAC;AAEF,MAAM,MAAM,aAAa,GAAG,OAAO,GAAG;IACpC,QAAQ,CAAC,KAAK,EAAE,SAAS,UAAU,EAAE,GAAG,IAAI,CAAC;IAC7C,MAAM,CAAC,SAAS,EAAE,MAAM,OAAO,EAAE,MAAM,EAAE,OAAO,GAAG,IAAI,CAAC;CACzD,CAAC;AA+BF,wBAAgB,mBAAmB,CAAC,OAAO,GAAE,oBAAyB,GAAG,aAAa,CAwNrF"}
|
package/dist/memory.js
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
1
1
|
import { ROOM_CONTRACT_VERSION } from './adapter.js';
|
|
2
2
|
import { MD_MODEL } from './collection.js';
|
|
3
|
+
const FIXTURE_RETENTION = {
|
|
4
|
+
history: {
|
|
5
|
+
kind: 'duration',
|
|
6
|
+
seconds: 1
|
|
7
|
+
},
|
|
8
|
+
outcome: 1,
|
|
9
|
+
refreshHorizon: 1
|
|
10
|
+
};
|
|
11
|
+
function declaredRetention(value) {
|
|
12
|
+
const retention = value ?? FIXTURE_RETENTION;
|
|
13
|
+
if (retention.history.kind === 'no-declared-time-bound') return retention;
|
|
14
|
+
if (Number.isFinite(retention.history.seconds) && retention.history.seconds > 0) {
|
|
15
|
+
return retention;
|
|
16
|
+
}
|
|
17
|
+
throw new Error('history retention duration must be a finite positive number of seconds');
|
|
18
|
+
}
|
|
3
19
|
function named(source, paths) {
|
|
4
20
|
const taken = {};
|
|
5
21
|
for (const path of paths){
|
|
@@ -22,11 +38,7 @@ export function createMemoryAdapter(options = {}) {
|
|
|
22
38
|
];
|
|
23
39
|
const capabilities = options.capabilities ?? [];
|
|
24
40
|
const providerLimits = options.providerLimits ?? [];
|
|
25
|
-
const retention = options.retention
|
|
26
|
-
history: 1,
|
|
27
|
-
outcome: 1,
|
|
28
|
-
refreshHorizon: 1
|
|
29
|
-
};
|
|
41
|
+
const retention = declaredRetention(options.retention);
|
|
30
42
|
const origins = options.origins ?? [
|
|
31
43
|
'https://origin.example'
|
|
32
44
|
];
|
|
@@ -46,8 +58,11 @@ export function createMemoryAdapter(options = {}) {
|
|
|
46
58
|
return {
|
|
47
59
|
name: room.name,
|
|
48
60
|
locator: room.locator,
|
|
61
|
+
collectionRoot: room.collectionRoot,
|
|
49
62
|
roomVersion: room.roomVersion,
|
|
50
|
-
|
|
63
|
+
operations: room.operations,
|
|
64
|
+
replica: room.replica,
|
|
65
|
+
attachedModel: room.attachedModel,
|
|
51
66
|
providerOwnedPaths: room.providerOwnedPaths
|
|
52
67
|
};
|
|
53
68
|
}
|
|
@@ -125,6 +140,12 @@ export function createMemoryAdapter(options = {}) {
|
|
|
125
140
|
if (answer === undefined) delete scripts[operation];
|
|
126
141
|
else scripts[operation] = answer;
|
|
127
142
|
},
|
|
143
|
+
async model (_authorization, request) {
|
|
144
|
+
return resolveScript(scripts.model, ()=>rooms.find((room)=>room.locator === request.locator)?.model ?? {
|
|
145
|
+
kind: 'model-unavailable',
|
|
146
|
+
reason: 'not-readable'
|
|
147
|
+
}, request);
|
|
148
|
+
},
|
|
128
149
|
async authorize () {
|
|
129
150
|
return resolveScript(scripts.authorize, ()=>({}), undefined);
|
|
130
151
|
},
|