@athenaintel/react 0.53.0 → 0.54.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/README.md +24 -1
  2. package/dist/agent-runtime/src/call-recap.cjs +2 -3
  3. package/dist/agent-runtime/src/call-recap.cjs.map +1 -1
  4. package/dist/agent-runtime/src/call-recap.d.ts +1 -2
  5. package/dist/agent-runtime/src/call-recap.js +1 -2
  6. package/dist/agent-runtime/src/call-recap.js.map +1 -1
  7. package/dist/agent-runtime/src/deep-agent-transport-recipe.cjs +7 -3
  8. package/dist/agent-runtime/src/deep-agent-transport-recipe.cjs.map +1 -1
  9. package/dist/agent-runtime/src/deep-agent-transport-recipe.d.ts +10 -2
  10. package/dist/agent-runtime/src/deep-agent-transport-recipe.js +8 -4
  11. package/dist/agent-runtime/src/deep-agent-transport-recipe.js.map +1 -1
  12. package/dist/agent-runtime/src/desktop-handoff.d.ts +7 -0
  13. package/dist/agent-runtime/src/dictation-session.d.ts +158 -0
  14. package/dist/agent-runtime/src/edit-command.cjs +6 -0
  15. package/dist/agent-runtime/src/edit-command.cjs.map +1 -1
  16. package/dist/agent-runtime/src/edit-command.d.ts +8 -0
  17. package/dist/agent-runtime/src/edit-command.js +6 -0
  18. package/dist/agent-runtime/src/edit-command.js.map +1 -1
  19. package/dist/agent-runtime/src/generated/runconfig-contract.cjs +6 -0
  20. package/dist/agent-runtime/src/generated/runconfig-contract.cjs.map +1 -1
  21. package/dist/agent-runtime/src/generated/runconfig-contract.d.ts +13 -0
  22. package/dist/agent-runtime/src/generated/runconfig-contract.js +6 -0
  23. package/dist/agent-runtime/src/generated/runconfig-contract.js.map +1 -1
  24. package/dist/agent-runtime/src/index.d.ts +6 -6
  25. package/dist/agent-runtime/src/message-window.cjs +111 -7
  26. package/dist/agent-runtime/src/message-window.cjs.map +1 -1
  27. package/dist/agent-runtime/src/message-window.d.ts +66 -6
  28. package/dist/agent-runtime/src/message-window.js +112 -8
  29. package/dist/agent-runtime/src/message-window.js.map +1 -1
  30. package/dist/agent-runtime/src/offline-status.cjs.map +1 -1
  31. package/dist/agent-runtime/src/offline-status.d.ts +33 -0
  32. package/dist/agent-runtime/src/offline-status.js.map +1 -1
  33. package/dist/agent-runtime/src/runtime.d.ts +4 -3
  34. package/dist/agent-runtime/src/subagent-transcripts.cjs +23 -1
  35. package/dist/agent-runtime/src/subagent-transcripts.cjs.map +1 -1
  36. package/dist/agent-runtime/src/subagent-transcripts.js +25 -3
  37. package/dist/agent-runtime/src/subagent-transcripts.js.map +1 -1
  38. package/dist/agent-runtime/src/subagents.cjs +112 -0
  39. package/dist/agent-runtime/src/subagents.cjs.map +1 -1
  40. package/dist/agent-runtime/src/subagents.d.ts +103 -0
  41. package/dist/agent-runtime/src/subagents.js +113 -1
  42. package/dist/agent-runtime/src/subagents.js.map +1 -1
  43. package/dist/agent-runtime/src/thread-handoff-protocol.d.ts +37 -9
  44. package/dist/agent-runtime/src/thread-handoff.d.ts +1 -1
  45. package/dist/agent-runtime/src/tool-metadata.cjs +8 -0
  46. package/dist/agent-runtime/src/tool-metadata.cjs.map +1 -1
  47. package/dist/agent-runtime/src/tool-metadata.js +8 -0
  48. package/dist/agent-runtime/src/tool-metadata.js.map +1 -1
  49. package/dist/agent-runtime/src/use-deep-agent-thread.cjs +6 -0
  50. package/dist/agent-runtime/src/use-deep-agent-thread.cjs.map +1 -1
  51. package/dist/agent-runtime/src/use-deep-agent-thread.js +7 -1
  52. package/dist/agent-runtime/src/use-deep-agent-thread.js.map +1 -1
  53. package/dist/agent-runtime/src/use-deep-agent-window-sync.cjs +39 -10
  54. package/dist/agent-runtime/src/use-deep-agent-window-sync.cjs.map +1 -1
  55. package/dist/agent-runtime/src/use-deep-agent-window-sync.d.ts +14 -4
  56. package/dist/agent-runtime/src/use-deep-agent-window-sync.js +41 -12
  57. package/dist/agent-runtime/src/use-deep-agent-window-sync.js.map +1 -1
  58. package/dist/agent-runtime/src/use-thread-handoff-flow.d.ts +5 -9
  59. package/dist/agent-runtime/src/voice-presentation.cjs +34 -0
  60. package/dist/agent-runtime/src/voice-presentation.cjs.map +1 -1
  61. package/dist/agent-runtime/src/voice-presentation.d.ts +35 -0
  62. package/dist/agent-runtime/src/voice-presentation.js +34 -0
  63. package/dist/agent-runtime/src/voice-presentation.js.map +1 -1
  64. package/dist/assets/AthenaAssetEmbed.cjs +4 -2
  65. package/dist/assets/AthenaAssetEmbed.cjs.map +1 -1
  66. package/dist/assets/AthenaAssetEmbed.d.ts +17 -8
  67. package/dist/assets/AthenaAssetEmbed.js +4 -2
  68. package/dist/assets/AthenaAssetEmbed.js.map +1 -1
  69. package/dist/assets/use-asset-embed.cjs.map +1 -1
  70. package/dist/assets/use-asset-embed.d.ts +7 -5
  71. package/dist/assets/use-asset-embed.js.map +1 -1
  72. package/dist/auth/account-identity.cjs +69 -0
  73. package/dist/auth/account-identity.cjs.map +1 -0
  74. package/dist/auth/account-identity.d.ts +57 -0
  75. package/dist/auth/account-identity.js +69 -0
  76. package/dist/auth/account-identity.js.map +1 -0
  77. package/dist/chat/AthenaChat.cjs +1 -1
  78. package/dist/chat/AthenaChat.cjs.map +1 -1
  79. package/dist/chat/AthenaChat.js +1 -1
  80. package/dist/chat/AthenaChat.js.map +1 -1
  81. package/dist/chat/super-grouping/toolkit-map.cjs +1 -0
  82. package/dist/chat/super-grouping/toolkit-map.cjs.map +1 -1
  83. package/dist/chat/super-grouping/toolkit-map.js +1 -0
  84. package/dist/chat/super-grouping/toolkit-map.js.map +1 -1
  85. package/dist/chat/use-statewire-approval-request.cjs +5 -5
  86. package/dist/chat/use-statewire-approval-request.cjs.map +1 -1
  87. package/dist/chat/use-statewire-approval-request.d.ts +7 -0
  88. package/dist/chat/use-statewire-approval-request.js +5 -5
  89. package/dist/chat/use-statewire-approval-request.js.map +1 -1
  90. package/dist/chat-ui/mentions/use-account-workspace-id.cjs +18 -58
  91. package/dist/chat-ui/mentions/use-account-workspace-id.cjs.map +1 -1
  92. package/dist/chat-ui/mentions/use-account-workspace-id.js +18 -58
  93. package/dist/chat-ui/mentions/use-account-workspace-id.js.map +1 -1
  94. package/dist/chat-ui/messages/voice-delegation-card.cjs +93 -25
  95. package/dist/chat-ui/messages/voice-delegation-card.cjs.map +1 -1
  96. package/dist/chat-ui/messages/voice-delegation-card.d.ts +16 -7
  97. package/dist/chat-ui/messages/voice-delegation-card.js +95 -27
  98. package/dist/chat-ui/messages/voice-delegation-card.js.map +1 -1
  99. package/dist/chat-ui/thread/handoff-cursor.cjs +30 -5
  100. package/dist/chat-ui/thread/handoff-cursor.cjs.map +1 -1
  101. package/dist/chat-ui/thread/handoff-cursor.d.ts +13 -5
  102. package/dist/chat-ui/thread/handoff-cursor.js +32 -7
  103. package/dist/chat-ui/thread/handoff-cursor.js.map +1 -1
  104. package/dist/collab/client.cjs +94 -6
  105. package/dist/collab/client.cjs.map +1 -1
  106. package/dist/collab/client.d.ts +27 -0
  107. package/dist/collab/client.js +94 -6
  108. package/dist/collab/client.js.map +1 -1
  109. package/dist/collab/index.d.ts +1 -1
  110. package/dist/keryx-http/src/initial-sync.cjs +121 -0
  111. package/dist/keryx-http/src/initial-sync.cjs.map +1 -0
  112. package/dist/keryx-http/src/initial-sync.d.ts +77 -0
  113. package/dist/keryx-http/src/initial-sync.js +104 -0
  114. package/dist/keryx-http/src/initial-sync.js.map +1 -0
  115. package/dist/keryx-http/src/unconfirmed-update-attributions.cjs +8 -0
  116. package/dist/keryx-http/src/unconfirmed-update-attributions.cjs.map +1 -1
  117. package/dist/keryx-http/src/unconfirmed-update-attributions.d.ts +6 -0
  118. package/dist/keryx-http/src/unconfirmed-update-attributions.js +8 -0
  119. package/dist/keryx-http/src/unconfirmed-update-attributions.js.map +1 -1
  120. package/dist/react/package.json.cjs +1 -1
  121. package/dist/react/package.json.js +1 -1
  122. package/dist/styles.css +1 -1
  123. package/dist/threads/api.cjs +1 -2
  124. package/dist/threads/api.cjs.map +1 -1
  125. package/dist/threads/api.d.ts +3 -2
  126. package/dist/threads/api.js +1 -2
  127. package/dist/threads/api.js.map +1 -1
  128. package/dist/threads/statewire-thread-list.cjs +5 -7
  129. package/dist/threads/statewire-thread-list.cjs.map +1 -1
  130. package/dist/threads/statewire-thread-list.js +7 -9
  131. package/dist/threads/statewire-thread-list.js.map +1 -1
  132. package/dist/tools/subagent-task-tool-ui.cjs +15 -5
  133. package/dist/tools/subagent-task-tool-ui.cjs.map +1 -1
  134. package/dist/tools/subagent-task-tool-ui.d.ts +5 -4
  135. package/dist/tools/subagent-task-tool-ui.js +16 -6
  136. package/dist/tools/subagent-task-tool-ui.js.map +1 -1
  137. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sources":["../../src/collab/client.ts"],"sourcesContent":["/**\n * Vanilla (framework-agnostic) live client for Generic Doc assets.\n *\n * `connectGenericDoc` owns the full connection lifecycle: mint a room-bound\n * token via the public API, open the Keryx WebSocket with the v14 provider\n * (`@y/websocket` + `@y/y`), re-mint before expiry, apply the close-code\n * policy (4401 → one fresh mint, other 44xx → permanent stop, everything\n * else → provider backoff), and expose presence from awareness. React apps\n * use `useGenericDoc` from `@athenaintel/react/collab` instead of calling\n * this directly.\n *\n * A host that keeps a local copy of the document (`localCopy`) gets it applied\n * before the first connection, keeps its unacknowledged edits waiting across\n * sessions, and can hold a connection that would send edits made without one\n * until it has checked them against the server (`beforeConnect`). Offline, a\n * mint that fails for want of the network is retried (`retryMintError`)\n * instead of ending the handle, and past `offlineGateAfterMs` without a socket\n * the handle reconnects itself, re-minting each time, so every reconnect after\n * a real outage re-checks access and passes the host's gate.\n *\n * A write the host makes on its own (an editor's housekeeping, a restored value)\n * goes out as housekeeping when it is made inside `runWithDocUpdateAttributions`\n * for `handle.doc` with `BACKGROUND_UPDATE_ATTRIBUTIONS`: the socket appends the\n * scope's attributions to the update, which Keryx counts as system work instead\n * of the person's edit (`socketFor`). One made while no socket is open is kept\n * until Keryx acknowledges it and sent the same way, ahead of the next\n * connection's sync (`UnconfirmedUpdateAttributions`). On a read-only grant\n * nothing that carries document content leaves the socket.\n *\n * A host that can read Keryx's document status with the room's grant\n * (`readDocumentStatus`) learns whether Keryx takes the room's writes for now\n * (`handle.writesRefused`): a quarantined room takes none, and its socket drops\n * every edit unconfirmed without a word (`document-status.ts`).\n */\n\nimport { receiveOnlyWebSocket } from '@athenaintel/keryx-http/receive-only-socket';\nimport { UnconfirmedUpdateAttributions } from '@athenaintel/keryx-http/unconfirmed-update-attributions';\nimport {\n attributingWebSocket,\n docUpdateAttributions,\n} from '@athenaintel/keryx-http/update-attributions';\nimport { WebsocketProvider } from '@y/websocket';\nimport * as Y from '@y/y';\nimport { classifyClose } from './close-policy';\nimport { type ReadDocumentStatus, watchDocumentStatus } from './document-status';\nimport {\n type CollabAuth,\n type CollabTokenResponse,\n CollabTokenError,\n mintCollabToken,\n} from './mint';\nimport { MAX_CONSECUTIVE_REMINTS, MIN_REFRESH_DELAY_MS, refreshDelayMs } from './token-refresh';\n\nexport type GenericDocStatus =\n | 'connecting'\n | 'connected'\n | 'disconnected'\n | 'closed'\n | 'error';\n\nexport interface PresenceEntry {\n clientId: number;\n state: Record<string, unknown>;\n}\n\nexport interface GenericDocHandle {\n /** The live shared document. Owned by the handle; destroyed with it. */\n readonly doc: Y.Doc;\n readonly status: GenericDocStatus;\n /**\n * Whether the initial server sync has completed for the current connection.\n * `status === 'connected'` fires before the server state arrives, so a doc\n * read immediately after connect can still be empty — gate first reads on\n * this (or `waitForSync`).\n */\n readonly synced: boolean;\n /**\n * Whether every change made to this document has reached the server: `false` from a local edit\n * until the server sends it back (`@y/websocket`'s `syncStatus.localUpdatesSynced`; yhub echoes\n * every update to its sender). Kept across reconnects and re-mints: a replaced provider hands its\n * unconfirmed edits to the next, and an edit made between providers waits for one. A host that\n * closes the document while this is `false` loses those edits, unless a local copy keeps them.\n */\n readonly localChangesSynced: boolean;\n /** Granted access from the last successful mint. */\n readonly accessType: 'r' | 'rw' | null;\n /** Terminal error, when status is 'error' or 'closed'. */\n readonly error: Error | null;\n /**\n * Whether the document holds what the host's local copy stored (always `true` without one).\n * Mount readers after it: until then the document is still empty.\n */\n readonly prepared: boolean;\n /** Whether this host allows a live connection. Disabled documents remain editable locally. */\n readonly connectionEnabled: boolean;\n /**\n * A connection the host's `beforeConnect` held: the handle waits, sending nothing, until the\n * host calls `resume()` (or destroys the handle).\n */\n readonly held: boolean;\n /** Monotonic change counter — bumps on every status/presence notification. */\n readonly version: number;\n /**\n * Resolve once the initial server sync completes; reject on timeout, on a\n * terminal connection state, or if the handle is destroyed first.\n */\n waitForSync: (timeoutMs?: number) => Promise<void>;\n /**\n * Resolve once connected, initially synced, and every local change has been acknowledged,\n * including any edits the local-copy hook restores after sync. The host must prevent further\n * editing while saving a checkpoint. Reject on timeout, a disabled connection, or a terminal state.\n */\n waitForAcknowledged: (timeoutMs?: number) => Promise<void>;\n getPresence: () => PresenceEntry[];\n /** Broadcast this client's presence state (requires a live connection). */\n setPresence: (state: Record<string, unknown> | null) => void;\n /**\n * Force an early token refresh. Session-preserving: the live connection\n * stays up until the fresh token is minted; a failed mint retries on a\n * short timer instead of dropping the session. Without a connection it\n * reconnects now.\n */\n refreshNow: () => Promise<void>;\n /**\n * Disable all connections without losing the document or its pending edits. Enabling mints a\n * fresh grant and runs the host's beforeConnect gate; it never bypasses a permission or review.\n */\n setConnectionEnabled: (enabled: boolean) => void;\n /** Connect past a hold, without asking `beforeConnect` again. */\n resume: () => void;\n /** Local edits the server has not echoed yet (handed between providers too), or `null`. */\n unconfirmedEdits: () => Y.ContentIds | null;\n /**\n * Keryx's document status, as last read with the room's grant, says the room takes no writes for\n * now: it is quarantined while it is repaired, and its socket drops every edit unconfirmed until\n * it is released. Always `false` without `readDocumentStatus`, on a read-only grant, and whenever\n * the last read could not answer.\n */\n readonly writesRefused: boolean;\n onChange: (listener: () => void) => () => void;\n destroy: () => void;\n}\n\n/**\n * Issues a room-bound Keryx token for one asset. The default calls the public\n * `/collab-token` route with the handle's `auth`; a host with its own trusted\n * mint (a desktop app's main process holding the user's key) passes one\n * instead, and the handle uses it for the first mint and every re-mint.\n */\nexport type CollabMint = (params: {\n assetId: string;\n access: 'view' | 'edit';\n}) => Promise<CollabTokenResponse>;\n\n/** What a host's local copy reads of the handle's transport. */\nexport interface GenericDocTransportView {\n /** True for a transaction the transport applied (the server's state, a peer's edit). */\n isRemoteOrigin: (origin: unknown) => boolean;\n /** Local edits the server has not echoed yet, or `null`. */\n getUnconfirmed: () => Y.ContentIds | null;\n /** Connected, past the initial sync, and nothing unconfirmed. */\n isFullySynced: () => boolean;\n}\n\n/** What `beforeConnect` is asked about. */\nexport interface GenericDocConnectGate {\n /** The grant the connection would use (its access is the server's current verdict). */\n grant: CollabTokenResponse;\n /** The handle has not connected yet. */\n firstConnection: boolean;\n /** How long the handle had been without a connection, when it had one before. */\n offlineForMs: number | null;\n /** Local edits made without a connection (or inherited from an earlier session) wait to be sent. */\n hasUnsyncedEdits: boolean;\n}\n\n/** A host's local copy of the document (`@athenaintel/local-copy` behind a host's glue). */\nexport interface GenericDocLocalCopy {\n /**\n * Called once, before the first mint: apply the stored copy to `doc` and return the local edits\n * it holds that the server never acknowledged. The handle sends them and waits for their echo\n * like its own. A failure here must resolve `{ unsyncedEdits: null }`: the handle then runs\n * without a copy.\n */\n prepare: (params: {\n doc: Y.Doc;\n transport: GenericDocTransportView;\n }) => Promise<{ unsyncedEdits: Y.ContentIds | null }>;\n /** The handle's unconfirmed edits or sync state changed. */\n transportChanged: () => void;\n /**\n * An explicit host pause/resume policy changed. Invalidate decisions that must be checked afresh\n * before a later manual save. A pause runs after its provider is destroyed and its status is\n * disconnected, so edits restored by the hook stay local. A resume runs before minting.\n * Network retries and an immediate conflict `resume()` do not call it.\n */\n connectionPolicyChanged?: (enabled: boolean) => void;\n /**\n * Asked after each mint and before the connection it would open: the first connection, a\n * reconnect after an outage longer than `offlineGateAfterMs`, and a re-mint after a revocation\n * (never a scheduled token refresh of a live connection, never past `resume()`). The host\n * checks what it must before anything is sent (the document still opens here; access; edits\n * made without a connection against the server's). `'hold'` keeps the handle from connecting\n * until `resume()`; a throw counts as \"not yet\" and is asked again on the next attempt.\n */\n beforeConnect?: (gate: GenericDocConnectGate) => Promise<'connect' | 'hold'>;\n}\n\n/** After this long without a socket, the handle reconnects itself (re-mint, gate) instead of the provider. */\nexport const DEFAULT_OFFLINE_GATE_AFTER_MS = 15_000;\n\n/** Retry delays for a mint that failed for want of the network. */\nconst MINT_RETRY_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 15_000, 30_000, 60_000];\n\n/**\n * The default `retryMintError`: a network failure, a timeout, a rate limit or a server error is\n * worth retrying; a refusal (401/403/404) is the server's verdict and ends the handle.\n */\nexport function isRetryableMintError(error: unknown): boolean {\n if (error instanceof CollabTokenError) {\n return error.status >= 500 || error.status === 408 || error.status === 429;\n }\n return error instanceof TypeError || (error instanceof DOMException && error.name === 'TimeoutError');\n}\n\nfunction resolveMint({ auth, mint }: { auth?: CollabAuth; mint?: CollabMint }): CollabMint {\n if (mint) return mint;\n if (!auth) throw new Error('connectGenericDoc needs `auth` or `mint`');\n return ({ assetId, access }) => mintCollabToken({ auth, assetId, access });\n}\n\n/**\n * The socket a provider for `grant` opens (`@athenaintel/keryx-http`'s wrappers, the ones\n * Olympus's rooms use). On a read-write grant, each sync update a write made inside a\n * `runWithDocUpdateAttributions` scope for `doc` sends carries the scope's attributions, which\n * Keryx reads after the update (`origin: background` counts as system work; a Keryx that predates\n * the trailer ignores it), and its sync step 2 goes out behind such writes made while no socket\n * was open, each as its own marked update (`unconfirmed`). On a read-only grant no frame that\n * carries document content leaves: a sync step 2 or an update is dropped (Keryx ignores them on\n * such a grant anyway), awareness passes. Read when each provider is built, as `@y/websocket` reads\n * `WebSocket`; `undefined` where there is none, and the provider fails at connect as it always did.\n */\nfunction socketFor({\n grant,\n doc,\n unconfirmed,\n}: {\n grant: CollabTokenResponse;\n doc: Y.Doc;\n unconfirmed: UnconfirmedUpdateAttributions;\n}): typeof WebSocket | undefined {\n const Base: typeof WebSocket | undefined = globalThis.WebSocket;\n if (typeof Base !== 'function') return undefined;\n if (grant.access_type === 'r') return receiveOnlyWebSocket({ Base });\n return attributingWebSocket({\n Base,\n attributionsFor: () => docUpdateAttributions(doc),\n unconfirmed,\n });\n}\n\nexport function connectGenericDoc(args: {\n assetId: string;\n /** Credentials for the default mint; not used when `mint` is given. */\n auth?: CollabAuth;\n access?: 'view' | 'edit';\n mint?: CollabMint;\n /** A local copy of the document the host keeps (see {@link GenericDocLocalCopy}). */\n localCopy?: GenericDocLocalCopy;\n /** Whether a failed mint is worth retrying; defaults to {@link isRetryableMintError}. */\n retryMintError?: (error: unknown) => boolean;\n /** See {@link DEFAULT_OFFLINE_GATE_AFTER_MS}. */\n offlineGateAfterMs?: number;\n /** Start without connecting or minting (for a host's manual-save mode). Defaults to true. */\n connectionEnabled?: boolean;\n /**\n * Reads Keryx's document status with the room's grant (see `ReadDocumentStatus`), for\n * `handle.writesRefused`. A host that cannot read it leaves it out.\n */\n readDocumentStatus?: ReadDocumentStatus;\n}): GenericDocHandle {\n const access = args.access ?? 'view';\n const mint = resolveMint({ auth: args.auth, mint: args.mint });\n const localCopy = args.localCopy;\n const retryMintError = args.retryMintError ?? isRetryableMintError;\n const offlineGateAfterMs = args.offlineGateAfterMs ?? DEFAULT_OFFLINE_GATE_AFTER_MS;\n const doc = new Y.Doc();\n // Writes made in a `runWithDocUpdateAttributions` scope, until Keryx acknowledges them: the\n // sockets every provider opens send those made while no socket was open ahead of their sync.\n const unconfirmedAttributions = new UnconfirmedUpdateAttributions({\n doc,\n attributionsFor: () => docUpdateAttributions(doc),\n isRemoteOrigin: (origin) => origin instanceof WebsocketProvider,\n });\n const listeners = new Set<() => void>();\n\n let provider: WebsocketProvider | null = null;\n let refreshTimer: ReturnType<typeof setTimeout> | null = null;\n let retryTimer: ReturnType<typeof setTimeout> | null = null;\n let offlineTimer: ReturnType<typeof setTimeout> | null = null;\n /** The provider whose socket was still opening, with nothing to send, at the threshold. */\n let openingPastThreshold: WebsocketProvider | null = null;\n let mintRetries = 0;\n let destroyed = false;\n let connectionEnabled = args.connectionEnabled ?? true;\n let status: GenericDocStatus = connectionEnabled ? 'connecting' : 'disconnected';\n let synced = false;\n let accessType: 'r' | 'rw' | null = null;\n let error: Error | null = null;\n let lastPresence: Record<string, unknown> | null = null;\n let version = 0;\n let consecutiveRemints = 0;\n let prepared = localCopy === undefined;\n let held = false;\n let heldGrant: CollabTokenResponse | null = null;\n let everConnected = false;\n let disconnectedSince: number | null = null;\n /** Bumped by every connect attempt: an attempt that finds it changed after an await stops. */\n let connectSeq = 0;\n /** Local edits no provider holds: handed on by a replaced provider, or made with none. */\n let carriedUpdates: WebsocketProvider['unconfirmedUpdates'] = [];\n let localChangesSynced = true;\n /** The grant the current provider connects with. */\n let liveGrant: CollabTokenResponse | null = null;\n /** Keryx's auth re-check closed the socket (4401): the next connection reads the document status. */\n let readStatusOnConnect = false;\n\n const notify = () => {\n version += 1;\n for (const listener of listeners) listener();\n };\n\n const documentStatus = args.readDocumentStatus\n ? watchDocumentStatus({\n read: args.readDocumentStatus,\n currentGrant: () => liveGrant,\n onChange: () => {\n if (!destroyed) notify();\n },\n })\n : null;\n\n const unconfirmedEdits = (): Y.ContentIds | null => {\n const all = [...carriedUpdates, ...(provider?.unconfirmedUpdates ?? [])].map(\n (entry) => entry.ids as Y.ContentIds\n );\n if (all.length === 0) return null;\n return all.length === 1 ? (all[0] as Y.ContentIds) : Y.mergeContentIds(all);\n };\n\n const transport: GenericDocTransportView = {\n isRemoteOrigin: (origin) => origin instanceof WebsocketProvider,\n getUnconfirmed: unconfirmedEdits,\n isFullySynced: () => status === 'connected' && synced && localChangesSynced,\n };\n\n const transportChanged = () => {\n localCopy?.transportChanged();\n };\n\n const refreshLocalChangesSynced = () => {\n const next = carriedUpdates.length === 0 && (provider?.unconfirmedUpdates.length ?? 0) === 0;\n const changed = next !== localChangesSynced;\n localChangesSynced = next;\n documentStatus?.unconfirmedChanged(!next);\n // After the flag: the copy reads `isFullySynced()` in its callback.\n // Before notifying: the callback can restore values and create more unconfirmed edits.\n transportChanged();\n if (changed) notify();\n };\n\n // An edit made while no provider exists (a re-mint in flight, offline) is sent by the next one,\n // which takes it as unconfirmed. The local copy's own load is not an edit.\n doc.on('update', (update: Uint8Array, origin: unknown) => {\n if (!prepared || provider !== null || destroyed || origin instanceof WebsocketProvider) return;\n carriedUpdates = [\n ...carriedUpdates,\n { created: Date.now(), ids: Y.createContentIdsFromUpdate(update) },\n ];\n refreshLocalChangesSynced();\n });\n\n const setStatus = (next: GenericDocStatus, err: Error | null = null) => {\n if (destroyed && next !== 'closed') return;\n const wasConnected = status === 'connected';\n status = next;\n error = err;\n if (next === 'connected') {\n everConnected = true;\n disconnectedSince = null;\n clearOfflineTimer();\n } else {\n if (wasConnected || (everConnected && disconnectedSince === null)) {\n disconnectedSince = Date.now();\n }\n documentStatus?.disconnected();\n }\n transportChanged();\n notify();\n };\n\n const clearRefreshTimer = () => {\n if (refreshTimer !== null) {\n clearTimeout(refreshTimer);\n refreshTimer = null;\n }\n };\n\n const clearRetryTimer = () => {\n if (retryTimer !== null) {\n clearTimeout(retryTimer);\n retryTimer = null;\n }\n };\n\n function clearOfflineTimer() {\n if (offlineTimer !== null) {\n clearTimeout(offlineTimer);\n offlineTimer = null;\n }\n }\n\n const teardownProvider = () => {\n clearRefreshTimer();\n // A future provider must complete its own initial sync; the doc keeps its\n // content either way. Subscribers must observe the flip immediately —\n // waiting for the next provider event would let them act on synced=true\n // across the replacement gap.\n if (synced) {\n synced = false;\n notify();\n }\n if (provider) {\n // Its unconfirmed edits outlive it: the next provider sends them and waits for their echo.\n const previous = provider;\n provider = null;\n carriedUpdates = [...carriedUpdates, ...previous.unconfirmedUpdates];\n previous.destroy();\n }\n };\n\n const scheduleRefresh = (grant: CollabTokenResponse) => {\n clearRefreshTimer();\n const delay = refreshDelayMs({ expiresAtMs: grant.expires_at_ms, now: Date.now() });\n refreshTimer = setTimeout(() => {\n void connect({ scheduledRefresh: true });\n }, delay);\n };\n\n /** A failed attempt that is worth retrying: try again later, or as soon as the network returns. */\n const scheduleRetry = () => {\n clearRetryTimer();\n const delay = MINT_RETRY_DELAYS_MS[Math.min(mintRetries, MINT_RETRY_DELAYS_MS.length - 1)];\n mintRetries += 1;\n retryTimer = setTimeout(() => {\n retryTimer = null;\n void connect();\n }, delay);\n };\n\n const onBrowserOnline = () => {\n // Only a handle waiting to retry: a refused or permanently closed one stays stopped.\n if (\n destroyed || !connectionEnabled || status === 'closed' || status === 'error' ||\n provider !== null || held\n ) return;\n mintRetries = 0;\n clearRetryTimer();\n void connect();\n };\n if (typeof window !== 'undefined') window.addEventListener('online', onBrowserOnline);\n\n /**\n * Past the gate's threshold without a socket, the handle reconnects itself (re-mint, gate). A\n * socket still being opened with nothing waiting to be sent is left to finish (a slow network\n * is not restarted every threshold), and the handle looks again a threshold later; if it opens\n * holding edits made since, they go through the gate first (`status`).\n */\n const armOfflineTakeover = () => {\n if (!connectionEnabled || offlineTimer !== null || !localCopy?.beforeConnect) return;\n offlineTimer = setTimeout(() => {\n offlineTimer = null;\n if (destroyed || !connectionEnabled || status === 'connected' || provider === null) return;\n if (provider.wsconnecting && !hasUnsyncedLocalEdits()) {\n openingPastThreshold = provider;\n armOfflineTakeover();\n return;\n }\n teardownProvider();\n void connect();\n }, offlineGateAfterMs);\n };\n\n const hasUnsyncedLocalEdits = () =>\n carriedUpdates.length > 0 || (provider?.unconfirmedUpdates.length ?? 0) > 0;\n\n\n const connect = async (opts?: {\n scheduledRefresh?: boolean;\n skipGate?: boolean;\n grant?: CollabTokenResponse;\n }): Promise<void> => {\n if (destroyed || !connectionEnabled) return;\n const seq = ++connectSeq;\n await preparing;\n if (destroyed || !connectionEnabled || seq !== connectSeq) return;\n // Only a live connection is refreshed in place (and skips the host's gate); a refresh while the\n // socket is down is a reconnect like any other.\n const scheduledRefresh = opts?.scheduledRefresh === true && status === 'connected';\n // A scheduled refresh mints FIRST and keeps the live session up: the old\n // token has ~5 minutes of headroom, so a transient mint failure retries\n // on a short timer instead of dropping a healthy connection.\n if (!scheduledRefresh) {\n teardownProvider();\n } else {\n clearRefreshTimer();\n }\n clearRetryTimer();\n if (destroyed || !connectionEnabled || seq !== connectSeq) return;\n let grant: CollabTokenResponse;\n if (opts?.grant && opts.grant.expires_at_ms - Date.now() > MIN_REFRESH_DELAY_MS) {\n grant = opts.grant;\n } else {\n try {\n grant = await mint({ assetId: args.assetId, access });\n } catch (err) {\n if (destroyed || !connectionEnabled || seq !== connectSeq) return;\n if (scheduledRefresh) {\n refreshTimer = setTimeout(() => {\n void connect({ scheduledRefresh: true });\n }, MIN_REFRESH_DELAY_MS);\n return;\n }\n if (retryMintError(err)) {\n // Offline (or the mint's server is): keep the document and try again.\n if (status !== 'disconnected') setStatus('disconnected');\n scheduleRetry();\n return;\n }\n // A denied mint is authoritative (revoked / not shared / not eligible).\n setStatus('error', err instanceof Error ? err : new Error(String(err)));\n return;\n }\n }\n if (destroyed || !connectionEnabled || seq !== connectSeq) return;\n mintRetries = 0;\n accessType = grant.access_type;\n const beforeConnect = localCopy?.beforeConnect;\n if (beforeConnect && !scheduledRefresh && !opts?.skipGate) {\n const firstConnection = !everConnected;\n const offlineForMs = disconnectedSince === null ? null : Date.now() - disconnectedSince;\n let decision: 'connect' | 'hold';\n try {\n decision = await beforeConnect({\n grant,\n firstConnection,\n offlineForMs,\n hasUnsyncedEdits: hasUnsyncedLocalEdits(),\n });\n } catch {\n if (destroyed || !connectionEnabled || seq !== connectSeq) return;\n if (status !== 'disconnected') setStatus('disconnected');\n scheduleRetry();\n return;\n }\n if (destroyed || !connectionEnabled || seq !== connectSeq) return;\n if (decision === 'hold') {\n held = true;\n heldGrant = grant;\n if (status !== 'disconnected') setStatus('disconnected');\n else notify();\n return;\n }\n }\n if (scheduledRefresh) {\n teardownProvider();\n }\n if (destroyed || !connectionEnabled || seq !== connectSeq) return;\n\n const socket = socketFor({ grant, doc, unconfirmed: unconfirmedAttributions });\n const nextProvider = new WebsocketProvider(grant.ws_url, `${grant.org}/${grant.doc_id}`, doc, {\n params: {\n yauth: grant.token,\n branch: grant.branch,\n gc: 'true',\n },\n // BroadcastChannel would sync same-origin clients locally, bypassing the\n // server's permission enforcement (a read-only tab could write into an\n // editor tab's doc). Permissioned docs must round-trip the server.\n disableBc: true,\n ...(socket && { WebSocketPolyfill: socket }),\n });\n provider = nextProvider;\n liveGrant = grant;\n nextProvider.unconfirmedUpdates = [...carriedUpdates, ...nextProvider.unconfirmedUpdates];\n carriedUpdates = [];\n refreshLocalChangesSynced();\n\n nextProvider.on('sync-status', () => {\n if (provider !== nextProvider) return;\n refreshLocalChangesSynced();\n });\n\n nextProvider.on('status', (event: { status: 'connecting' | 'connected' | 'disconnected' }) => {\n if (provider !== nextProvider) return;\n if (\n event.status === 'connected' &&\n openingPastThreshold === nextProvider &&\n hasUnsyncedLocalEdits()\n ) {\n // Opened after the threshold holding edits made meanwhile: before its handshake sends\n // them (`@y/websocket` reports `connected` first), they go through the gate.\n teardownProvider();\n void connect();\n return;\n }\n // The connections that read Keryx's document status at once: the first, the one after an auth\n // re-check close, and one after an outage the handle treats as real. Never an ordinary\n // reconnect (a Keryx deploy reconnects every room at once).\n const readStatusNow =\n event.status === 'connected' &&\n (!everConnected ||\n readStatusOnConnect ||\n (disconnectedSince !== null && Date.now() - disconnectedSince >= offlineGateAfterMs));\n if (event.status === 'connected') {\n consecutiveRemints = 0;\n readStatusOnConnect = false;\n }\n setStatus(event.status);\n if (event.status === 'connected') documentStatus?.connected({ readNow: readStatusNow });\n if (event.status === 'connected' && lastPresence !== null) {\n nextProvider.awareness.setLocalState(lastPresence);\n }\n // `@y/websocket` reports `disconnected` only for a socket that had opened: one that never\n // opens (the server unreachable while the mint goes through) only ever reports `connecting`,\n // and is just as offline.\n if (event.status !== 'connected') armOfflineTakeover();\n });\n // Its first `connecting` came from its constructor, before this listener existed.\n if (!nextProvider.wsconnected) armOfflineTakeover();\n\n nextProvider.on('sync', (state: boolean) => {\n if (provider !== nextProvider) return;\n if (synced !== state) {\n synced = state;\n transportChanged();\n notify();\n }\n });\n\n nextProvider.on('connection-close', (event: CloseEvent | null) => {\n if (provider !== nextProvider) return;\n const action = classifyClose(event?.code);\n if (action === 'remint') {\n // Revoked mid-session: a fresh mint re-runs the server-side permission\n // check. If access is truly gone the mint 403s and we land in 'error'.\n // Bounded: repeated 4401s without an intervening successful connect\n // mean the server keeps rejecting freshly minted tokens — stop rather\n // than loop mint→connect→kick.\n consecutiveRemints += 1;\n // A quarantine and a release both close the room's sockets this way, once Keryx has written\n // or cleared the marker: the reconnected socket learns which. Until then nothing is read\n // (the handle stays `connected` through the re-mint, on a grant Keryx just bounced).\n readStatusOnConnect = true;\n documentStatus?.disconnected();\n teardownProvider();\n if (consecutiveRemints > MAX_CONSECUTIVE_REMINTS) {\n setStatus(\n 'closed',\n new Error('Access repeatedly revoked mid-session (4401); giving up.')\n );\n return;\n }\n void connect();\n } else if (action === 'stop') {\n teardownProvider();\n setStatus(\n 'closed',\n new Error(`Connection closed permanently (code ${event?.code ?? 'unknown'})`)\n );\n }\n // 'retry': the provider's exponential backoff handles it, until the offline takeover.\n });\n\n nextProvider.awareness.on('change', () => {\n if (provider !== nextProvider) return;\n notify();\n });\n\n scheduleRefresh(grant);\n };\n\n const preparing: Promise<void> = localCopy\n ? localCopy\n .prepare({ doc, transport })\n .catch(() => ({ unsyncedEdits: null }))\n .then(({ unsyncedEdits }) => {\n if (destroyed) return;\n if (unsyncedEdits && !(unsyncedEdits.inserts.isEmpty() && unsyncedEdits.deletes.isEmpty())) {\n carriedUpdates = [...carriedUpdates, { created: Date.now(), ids: unsyncedEdits }];\n }\n prepared = true;\n refreshLocalChangesSynced();\n notify();\n })\n : Promise.resolve();\n\n void connect();\n\n const waitForSync = (timeoutMs = 15_000): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n const terminal = (): Error | null => {\n if (destroyed) return new Error('Handle destroyed before initial sync');\n if (status === 'closed' || status === 'error') {\n return error ?? new Error(`Connection ${status} before initial sync`);\n }\n return null;\n };\n if (synced) {\n resolve();\n return;\n }\n const immediate = terminal();\n if (immediate) {\n reject(immediate);\n return;\n }\n const cleanup = () => {\n clearTimeout(timer);\n listeners.delete(listener);\n };\n const timer = setTimeout(() => {\n cleanup();\n reject(new Error(`Timed out after ${timeoutMs}ms waiting for initial sync`));\n }, timeoutMs);\n const listener = () => {\n if (synced) {\n cleanup();\n resolve();\n return;\n }\n const err = terminal();\n if (err) {\n cleanup();\n reject(err);\n }\n };\n listeners.add(listener);\n });\n\n const waitForAcknowledged = (timeoutMs = 15_000): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n let finished = false;\n let checkQueued = false;\n let timer: ReturnType<typeof setTimeout> | null = null;\n const finish = (failure?: Error) => {\n if (finished) return;\n finished = true;\n if (timer !== null) clearTimeout(timer);\n listeners.delete(check);\n if (failure) reject(failure);\n else resolve();\n };\n const check = () => {\n if (finished || checkQueued) return;\n checkQueued = true;\n // All synchronous transport hooks and change listeners finish before a save settles.\n queueMicrotask(() => {\n checkQueued = false;\n if (finished) return;\n if (destroyed) {\n finish(new Error('Handle destroyed before local changes were acknowledged'));\n } else if (!connectionEnabled) {\n finish(new Error('Connection disabled before local changes were acknowledged'));\n } else if (status === 'closed' || status === 'error') {\n finish(error ?? new Error(`Connection ${status} before local changes were acknowledged`));\n } else if (prepared && status === 'connected' && synced && localChangesSynced) {\n finish();\n }\n });\n };\n timer = setTimeout(() => {\n finish(new Error(`Timed out after ${timeoutMs}ms waiting for local changes to be acknowledged`));\n }, timeoutMs);\n listeners.add(check);\n check();\n });\n\n return {\n doc,\n get status() {\n return status;\n },\n get synced() {\n return synced;\n },\n get localChangesSynced() {\n return localChangesSynced;\n },\n get accessType() {\n return accessType;\n },\n get error() {\n return error;\n },\n get prepared() {\n return prepared;\n },\n get connectionEnabled() {\n return connectionEnabled;\n },\n get held() {\n return held;\n },\n get version() {\n return version;\n },\n get writesRefused() {\n return documentStatus?.writesRefused ?? false;\n },\n waitForSync,\n waitForAcknowledged,\n getPresence: () => {\n if (!provider) return [];\n const entries: PresenceEntry[] = [];\n provider.awareness.getStates().forEach((state, clientId) => {\n entries.push({ clientId, state: state as Record<string, unknown> });\n });\n return entries;\n },\n setPresence: (state) => {\n lastPresence = state;\n provider?.awareness.setLocalState(state);\n },\n refreshNow: () => {\n if (!connectionEnabled || held) return Promise.resolve();\n return provider ? connect({ scheduledRefresh: true }) : connect();\n },\n setConnectionEnabled: (enabled) => {\n if (destroyed || enabled === connectionEnabled) return;\n connectionEnabled = enabled;\n if (!enabled) {\n // Invalidate every mint/gate already in flight before tearing down the live provider.\n connectSeq += 1;\n clearRetryTimer();\n clearOfflineTimer();\n teardownProvider();\n setStatus('disconnected');\n localCopy?.connectionPolicyChanged?.(false);\n return;\n }\n localCopy?.connectionPolicyChanged?.(true);\n held = false;\n heldGrant = null;\n setStatus('connecting');\n void connect();\n },\n resume: () => {\n if (!held || destroyed || !connectionEnabled) return;\n held = false;\n const grant = heldGrant;\n heldGrant = null;\n notify();\n void connect({ skipGate: true, grant: grant ?? undefined });\n },\n unconfirmedEdits,\n onChange: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n destroy: () => {\n if (destroyed) return;\n destroyed = true;\n documentStatus?.destroy();\n teardownProvider();\n clearRetryTimer();\n clearOfflineTimer();\n if (typeof window !== 'undefined') window.removeEventListener('online', onBrowserOnline);\n status = 'closed';\n // Final notification so pending waitForSync callers reject instead of\n // hanging on listeners that are about to be dropped.\n for (const listener of [...listeners]) listener();\n listeners.clear();\n unconfirmedAttributions.destroy();\n doc.destroy();\n },\n };\n}\n\nexport { CollabTokenError };\nexport type { CollabAuth, CollabTokenResponse };\n"],"names":[],"mappings":";;;;;;;;;AAiNO,MAAM,gCAAgC;AAG7C,MAAM,uBAAuB,CAAC,KAAO,KAAO,KAAO,KAAO,MAAQ,KAAQ,GAAM;AAMzE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AA,IACN;AAAA,EAAA;AAEJ;"}
1
+ {"version":3,"file":"client.js","sources":["../../src/collab/client.ts"],"sourcesContent":["/**\n * Vanilla (framework-agnostic) live client for Generic Doc assets.\n *\n * `connectGenericDoc` owns the full connection lifecycle: mint a room-bound\n * token via the public API, open the Keryx WebSocket with the v14 provider\n * (`@y/websocket` + `@y/y`), re-mint before expiry, apply the close-code\n * policy (4401 → one fresh mint, other 44xx → permanent stop, everything\n * else → provider backoff), and expose presence from awareness. React apps\n * use `useGenericDoc` from `@athenaintel/react/collab` instead of calling\n * this directly.\n *\n * A host that keeps a local copy of the document (`localCopy`) gets it applied\n * before the first connection, keeps its unacknowledged edits waiting across\n * sessions, and can hold a connection that would send edits made without one\n * until it has checked them against the server (`beforeConnect`). Offline, a\n * mint that fails for want of the network is retried (`retryMintError`)\n * instead of ending the handle, and past `offlineGateAfterMs` without a socket\n * the handle reconnects itself, re-minting each time, so every reconnect after\n * a real outage re-checks access and passes the host's gate.\n *\n * A write the host makes on its own (an editor's housekeeping, a restored value)\n * goes out as housekeeping when it is made inside `runWithDocUpdateAttributions`\n * for `handle.doc` with `BACKGROUND_UPDATE_ATTRIBUTIONS`: the socket appends the\n * scope's attributions to the update, which Keryx counts as system work instead\n * of the person's edit (`socketFor`). One made while no socket is open is kept\n * until Keryx acknowledges it and sent the same way, ahead of the next\n * connection's sync (`UnconfirmedUpdateAttributions`). On a read-only grant\n * nothing that carries document content leaves the socket.\n *\n * A host that can read Keryx's document status with the room's grant\n * (`readDocumentStatus`) learns whether Keryx takes the room's writes for now\n * (`handle.writesRefused`): a quarantined room takes none, and its socket drops\n * every edit unconfirmed without a word (`document-status.ts`).\n */\n\nimport {\n INITIAL_SYNC_DIFF,\n INITIAL_SYNC_PARAM,\n type InitialSyncSupportStorage,\n keryxOriginOf,\n keryxRoomReadUrl,\n knownInitialSyncSupport,\n readRoomOverHttp,\n rememberInitialSyncSupport,\n} from '@athenaintel/keryx-http/initial-sync';\nimport { receiveOnlyWebSocket } from '@athenaintel/keryx-http/receive-only-socket';\nimport { UnconfirmedUpdateAttributions } from '@athenaintel/keryx-http/unconfirmed-update-attributions';\nimport {\n attributingWebSocket,\n docUpdateAttributions,\n} from '@athenaintel/keryx-http/update-attributions';\nimport { WebsocketProvider } from '@y/websocket';\nimport * as Y from '@y/y';\nimport { classifyClose } from './close-policy';\nimport { type ReadDocumentStatus, watchDocumentStatus } from './document-status';\nimport {\n type CollabAuth,\n type CollabTokenResponse,\n CollabTokenError,\n mintCollabToken,\n} from './mint';\nimport { MAX_CONSECUTIVE_REMINTS, MIN_REFRESH_DELAY_MS, refreshDelayMs } from './token-refresh';\n\nexport type GenericDocStatus =\n | 'connecting'\n | 'connected'\n | 'disconnected'\n | 'closed'\n | 'error';\n\nexport interface PresenceEntry {\n clientId: number;\n state: Record<string, unknown>;\n}\n\nexport interface GenericDocHandle {\n /** The live shared document. Owned by the handle; destroyed with it. */\n readonly doc: Y.Doc;\n readonly status: GenericDocStatus;\n /**\n * Whether the initial server sync has completed for the current connection.\n * `status === 'connected'` fires before the server state arrives, so a doc\n * read immediately after connect can still be empty — gate first reads on\n * this (or `waitForSync`).\n */\n readonly synced: boolean;\n /**\n * Whether every change made to this document has reached the server: `false` from a local edit\n * until the server sends it back (`@y/websocket`'s `syncStatus.localUpdatesSynced`; yhub echoes\n * every update to its sender). Kept across reconnects and re-mints: a replaced provider hands its\n * unconfirmed edits to the next, and an edit made between providers waits for one. A host that\n * closes the document while this is `false` loses those edits, unless a local copy keeps them.\n */\n readonly localChangesSynced: boolean;\n /** Granted access from the last successful mint. */\n readonly accessType: 'r' | 'rw' | null;\n /** Terminal error, when status is 'error' or 'closed'. */\n readonly error: Error | null;\n /**\n * Whether the document holds what the host's local copy stored (always `true` without one).\n * Mount readers after it: until then the document is still empty.\n */\n readonly prepared: boolean;\n /** Whether this host allows a live connection. Disabled documents remain editable locally. */\n readonly connectionEnabled: boolean;\n /**\n * A connection the host's `beforeConnect` held: the handle waits, sending nothing, until the\n * host calls `resume()` (or destroys the handle).\n */\n readonly held: boolean;\n /** Monotonic change counter — bumps on every status/presence notification. */\n readonly version: number;\n /**\n * Resolve once the initial server sync completes; reject on timeout, on a\n * terminal connection state, or if the handle is destroyed first.\n */\n waitForSync: (timeoutMs?: number) => Promise<void>;\n /**\n * Resolve once connected, initially synced, and every local change has been acknowledged,\n * including any edits the local-copy hook restores after sync. The host must prevent further\n * editing while saving a checkpoint. Reject on timeout, a disabled connection, or a terminal state.\n */\n waitForAcknowledged: (timeoutMs?: number) => Promise<void>;\n getPresence: () => PresenceEntry[];\n /** Broadcast this client's presence state (requires a live connection). */\n setPresence: (state: Record<string, unknown> | null) => void;\n /**\n * Force an early token refresh. Session-preserving: the live connection\n * stays up until the fresh token is minted; a failed mint retries on a\n * short timer instead of dropping the session. Without a connection it\n * reconnects now.\n */\n refreshNow: () => Promise<void>;\n /**\n * Disable all connections without losing the document or its pending edits. Enabling mints a\n * fresh grant and runs the host's beforeConnect gate; it never bypasses a permission or review.\n */\n setConnectionEnabled: (enabled: boolean) => void;\n /** Connect past a hold, without asking `beforeConnect` again. */\n resume: () => void;\n /** Local edits the server has not echoed yet (handed between providers too), or `null`. */\n unconfirmedEdits: () => Y.ContentIds | null;\n /**\n * Keryx's document status, as last read with the room's grant, says the room takes no writes for\n * now: it is quarantined while it is repaired, and its socket drops every edit unconfirmed until\n * it is released. Always `false` without `readDocumentStatus`, on a read-only grant, and whenever\n * the last read could not answer.\n */\n readonly writesRefused: boolean;\n onChange: (listener: () => void) => () => void;\n destroy: () => void;\n}\n\n/**\n * Issues a room-bound Keryx token for one asset. The default calls the public\n * `/collab-token` route with the handle's `auth`; a host with its own trusted\n * mint (a desktop app's main process holding the user's key) passes one\n * instead, and the handle uses it for the first mint and every re-mint.\n */\nexport type CollabMint = (params: {\n assetId: string;\n access: 'view' | 'edit';\n}) => Promise<CollabTokenResponse>;\n\n/** What a host's local copy reads of the handle's transport. */\nexport interface GenericDocTransportView {\n /** True for a transaction the transport applied (the server's state, a peer's edit). */\n isRemoteOrigin: (origin: unknown) => boolean;\n /** Local edits the server has not echoed yet, or `null`. */\n getUnconfirmed: () => Y.ContentIds | null;\n /** Connected, past the initial sync, and nothing unconfirmed. */\n isFullySynced: () => boolean;\n}\n\n/** What `beforeConnect` is asked about. */\nexport interface GenericDocConnectGate {\n /** The grant the connection would use (its access is the server's current verdict). */\n grant: CollabTokenResponse;\n /** The handle has not connected yet. */\n firstConnection: boolean;\n /** How long the handle had been without a connection, when it had one before. */\n offlineForMs: number | null;\n /** Local edits made without a connection (or inherited from an earlier session) wait to be sent. */\n hasUnsyncedEdits: boolean;\n}\n\n/** A host's local copy of the document (`@athenaintel/local-copy` behind a host's glue). */\nexport interface GenericDocLocalCopy {\n /**\n * Called once, before the first mint: apply the stored copy to `doc` and return the local edits\n * it holds that the server never acknowledged. The handle sends them and waits for their echo\n * like its own. A failure here must resolve `{ unsyncedEdits: null }`: the handle then runs\n * without a copy.\n */\n prepare: (params: {\n doc: Y.Doc;\n transport: GenericDocTransportView;\n }) => Promise<{ unsyncedEdits: Y.ContentIds | null }>;\n /** The handle's unconfirmed edits or sync state changed. */\n transportChanged: () => void;\n /**\n * An explicit host pause/resume policy changed. Invalidate decisions that must be checked afresh\n * before a later manual save. A pause runs after its provider is destroyed and its status is\n * disconnected, so edits restored by the hook stay local. A resume runs before minting.\n * Network retries and an immediate conflict `resume()` do not call it.\n */\n connectionPolicyChanged?: (enabled: boolean) => void;\n /**\n * Asked after each mint and before the connection it would open: the first connection, a\n * reconnect after an outage longer than `offlineGateAfterMs`, and a re-mint after a revocation\n * (never a scheduled token refresh of a live connection, never past `resume()`). The host\n * checks what it must before anything is sent (the document still opens here; access; edits\n * made without a connection against the server's). `'hold'` keeps the handle from connecting\n * until `resume()`; a throw counts as \"not yet\" and is asked again on the next attempt.\n */\n beforeConnect?: (gate: GenericDocConnectGate) => Promise<'connect' | 'hold'>;\n}\n\n/** After this long without a socket, the handle reconnects itself (re-mint, gate) instead of the provider. */\nexport const DEFAULT_OFFLINE_GATE_AFTER_MS = 15_000;\n\n/** Retry delays for a mint that failed for want of the network. */\nconst MINT_RETRY_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 15_000, 30_000, 60_000];\n\n/**\n * The default `retryMintError`: a network failure, a timeout, a rate limit or a server error is\n * worth retrying; a refusal (401/403/404) is the server's verdict and ends the handle.\n */\nexport function isRetryableMintError(error: unknown): boolean {\n if (error instanceof CollabTokenError) {\n return error.status >= 500 || error.status === 408 || error.status === 429;\n }\n return error instanceof TypeError || (error instanceof DOMException && error.name === 'TimeoutError');\n}\n\nfunction resolveMint({ auth, mint }: { auth?: CollabAuth; mint?: CollabMint }): CollabMint {\n if (mint) return mint;\n if (!auth) throw new Error('connectGenericDoc needs `auth` or `mint`');\n return ({ assetId, access }) => mintCollabToken({ auth, assetId, access });\n}\n\n/**\n * The socket a provider for `grant` opens (`@athenaintel/keryx-http`'s wrappers, the ones\n * Olympus's rooms use). On a read-write grant, each sync update a write made inside a\n * `runWithDocUpdateAttributions` scope for `doc` sends carries the scope's attributions, which\n * Keryx reads after the update (`origin: background` counts as system work; a Keryx that predates\n * the trailer ignores it), and its sync step 2 goes out behind such writes made while no socket\n * was open, each as its own marked update (`unconfirmed`). On a read-only grant no frame that\n * carries document content leaves: a sync step 2 or an update is dropped (Keryx ignores them on\n * such a grant anyway), awareness passes. Read when each provider is built, as `@y/websocket` reads\n * `WebSocket`; `undefined` where there is none, and the provider fails at connect as it always did.\n */\nfunction socketFor({\n grant,\n doc,\n unconfirmed,\n}: {\n grant: CollabTokenResponse;\n doc: Y.Doc;\n unconfirmed: UnconfirmedUpdateAttributions;\n}): typeof WebSocket | undefined {\n const Base: typeof WebSocket | undefined = globalThis.WebSocket;\n if (typeof Base !== 'function') return undefined;\n if (grant.access_type === 'r') return receiveOnlyWebSocket({ Base });\n return attributingWebSocket({\n Base,\n attributionsFor: () => docUpdateAttributions(doc),\n unconfirmed,\n });\n}\n\n/** How an HTTP-first read went (`connectGenericDoc`'s `httpFirstOpen`). */\nexport interface GenericDocHttpFirstOpenEvent {\n /**\n * `read`: read over HTTP and applied; the socket asks for the diff. `unsupported`: Keryx answered\n * without saying it answers a socket's sync step 1; its document was not used. `failed`: the read\n * failed (`error` says why). `skipped`: Keryx is known not to answer, so nothing was read.\n * `aborted`: the room replaced or closed the provider during the read, which it stopped.\n */\n outcome: 'read' | 'unsupported' | 'failed' | 'skipped' | 'aborted';\n /** The decoded body's size (`read`, `unsupported`). */\n bytes?: number;\n /** From the request to the socket's connect. */\n durationMs: number;\n /** Why the read failed (`failed`): the error's name and message. */\n error?: string;\n}\n\n/** How long an HTTP-first read may take before the room falls back to the socket's whole-document sync. */\nconst HTTP_FIRST_READ_TIMEOUT_MS = 60_000;\n\n/** `localStorage`, when the host has one (a browser, Electron's renderer, the phone's editor page). */\nfunction browserStorage(): InitialSyncSupportStorage | null {\n try {\n return typeof window !== 'undefined' && window.localStorage ? window.localStorage : null;\n } catch {\n return null;\n }\n}\n\nexport function connectGenericDoc(args: {\n assetId: string;\n /** Credentials for the default mint; not used when `mint` is given. */\n auth?: CollabAuth;\n access?: 'view' | 'edit';\n mint?: CollabMint;\n /** A local copy of the document the host keeps (see {@link GenericDocLocalCopy}). */\n localCopy?: GenericDocLocalCopy;\n /** Whether a failed mint is worth retrying; defaults to {@link isRetryableMintError}. */\n retryMintError?: (error: unknown) => boolean;\n /** See {@link DEFAULT_OFFLINE_GATE_AFTER_MS}. */\n offlineGateAfterMs?: number;\n /** Start without connecting or minting (for a host's manual-save mode). Defaults to true. */\n connectionEnabled?: boolean;\n /**\n * Reads Keryx's document status with the room's grant (see `ReadDocumentStatus`), for\n * `handle.writesRefused`. A host that cannot read it leaves it out.\n */\n readDocumentStatus?: ReadDocumentStatus;\n /**\n * Open the room HTTP-first (Word at scale), as Olympus opens a Word room: a document that holds\n * nothing yet is read over `GET /ydoc` (compressed, decoded as it downloads), applied as Keryx's\n * own state, and the socket asks Keryx for only what it still lacks (`?initialSync=diff`) - when\n * Keryx says it answers that way (`@athenaintel/keryx-http/initial-sync`). Every later socket of\n * the room asks for the diff too while Keryx is known to answer and the room holds no write Keryx\n * has not echoed. For rooms whose documents can be large (Word documents).\n */\n httpFirstOpen?: boolean;\n /** Hears how each HTTP-first read went (`httpFirstOpen`), for the host's telemetry. */\n onHttpFirstOpen?: (event: GenericDocHttpFirstOpenEvent) => void;\n}): GenericDocHandle {\n const access = args.access ?? 'view';\n const mint = resolveMint({ auth: args.auth, mint: args.mint });\n const localCopy = args.localCopy;\n const retryMintError = args.retryMintError ?? isRetryableMintError;\n const offlineGateAfterMs = args.offlineGateAfterMs ?? DEFAULT_OFFLINE_GATE_AFTER_MS;\n const doc = new Y.Doc();\n // Writes made in a `runWithDocUpdateAttributions` scope, until Keryx acknowledges them: the\n // sockets every provider opens send those made while no socket was open ahead of their sync.\n const unconfirmedAttributions = new UnconfirmedUpdateAttributions({\n doc,\n attributionsFor: () => docUpdateAttributions(doc),\n isRemoteOrigin: (origin) => origin instanceof WebsocketProvider,\n });\n const listeners = new Set<() => void>();\n\n let provider: WebsocketProvider | null = null;\n let refreshTimer: ReturnType<typeof setTimeout> | null = null;\n let retryTimer: ReturnType<typeof setTimeout> | null = null;\n let offlineTimer: ReturnType<typeof setTimeout> | null = null;\n /** The provider whose socket was still opening, with nothing to send, at the threshold. */\n let openingPastThreshold: WebsocketProvider | null = null;\n let mintRetries = 0;\n let destroyed = false;\n let connectionEnabled = args.connectionEnabled ?? true;\n let status: GenericDocStatus = connectionEnabled ? 'connecting' : 'disconnected';\n let synced = false;\n let accessType: 'r' | 'rw' | null = null;\n let error: Error | null = null;\n let lastPresence: Record<string, unknown> | null = null;\n let version = 0;\n let consecutiveRemints = 0;\n let prepared = localCopy === undefined;\n let held = false;\n let heldGrant: CollabTokenResponse | null = null;\n let everConnected = false;\n let disconnectedSince: number | null = null;\n /** Bumped by every connect attempt: an attempt that finds it changed after an await stops. */\n let connectSeq = 0;\n /** Local edits no provider holds: handed on by a replaced provider, or made with none. */\n let carriedUpdates: WebsocketProvider['unconfirmedUpdates'] = [];\n let localChangesSynced = true;\n /** The grant the current provider connects with. */\n let liveGrant: CollabTokenResponse | null = null;\n /** Keryx's auth re-check closed the socket (4401): the next connection reads the document status. */\n let readStatusOnConnect = false;\n /** This room saw its Keryx say it answers a socket's sync step 1 (its HTTP-first read). */\n let keryxAnswersSyncStep1 = false;\n /**\n * The HTTP-first read of a provider's document, while it runs: that provider is opening, and\n * replacing it (a re-mint, the offline takeover, `setConnectionEnabled(false)`, `destroy()`) stops\n * the download.\n */\n let httpFirstRead: { target: WebsocketProvider; controller: AbortController } | null = null;\n\n const notify = () => {\n version += 1;\n for (const listener of listeners) listener();\n };\n\n const documentStatus = args.readDocumentStatus\n ? watchDocumentStatus({\n read: args.readDocumentStatus,\n currentGrant: () => liveGrant,\n onChange: () => {\n if (!destroyed) notify();\n },\n })\n : null;\n\n const unconfirmedEdits = (): Y.ContentIds | null => {\n const all = [...carriedUpdates, ...(provider?.unconfirmedUpdates ?? [])].map(\n (entry) => entry.ids as Y.ContentIds\n );\n if (all.length === 0) return null;\n return all.length === 1 ? (all[0] as Y.ContentIds) : Y.mergeContentIds(all);\n };\n\n const transport: GenericDocTransportView = {\n isRemoteOrigin: (origin) => origin instanceof WebsocketProvider,\n getUnconfirmed: unconfirmedEdits,\n isFullySynced: () => status === 'connected' && synced && localChangesSynced,\n };\n\n const transportChanged = () => {\n localCopy?.transportChanged();\n };\n\n const refreshLocalChangesSynced = () => {\n const next = carriedUpdates.length === 0 && (provider?.unconfirmedUpdates.length ?? 0) === 0;\n const changed = next !== localChangesSynced;\n localChangesSynced = next;\n documentStatus?.unconfirmedChanged(!next);\n // After the flag: the copy reads `isFullySynced()` in its callback.\n // Before notifying: the callback can restore values and create more unconfirmed edits.\n transportChanged();\n if (changed) notify();\n };\n\n // An edit made while no provider exists (a re-mint in flight, offline) is sent by the next one,\n // which takes it as unconfirmed. The local copy's own load is not an edit.\n doc.on('update', (update: Uint8Array, origin: unknown) => {\n if (!prepared || provider !== null || destroyed || origin instanceof WebsocketProvider) return;\n carriedUpdates = [\n ...carriedUpdates,\n { created: Date.now(), ids: Y.createContentIdsFromUpdate(update) },\n ];\n refreshLocalChangesSynced();\n });\n\n const setStatus = (next: GenericDocStatus, err: Error | null = null) => {\n if (destroyed && next !== 'closed') return;\n const wasConnected = status === 'connected';\n status = next;\n error = err;\n if (next === 'connected') {\n everConnected = true;\n disconnectedSince = null;\n clearOfflineTimer();\n } else {\n if (wasConnected || (everConnected && disconnectedSince === null)) {\n disconnectedSince = Date.now();\n }\n documentStatus?.disconnected();\n }\n transportChanged();\n notify();\n };\n\n const clearRefreshTimer = () => {\n if (refreshTimer !== null) {\n clearTimeout(refreshTimer);\n refreshTimer = null;\n }\n };\n\n const clearRetryTimer = () => {\n if (retryTimer !== null) {\n clearTimeout(retryTimer);\n retryTimer = null;\n }\n };\n\n function clearOfflineTimer() {\n if (offlineTimer !== null) {\n clearTimeout(offlineTimer);\n offlineTimer = null;\n }\n }\n\n const teardownProvider = () => {\n clearRefreshTimer();\n // A future provider must complete its own initial sync; the doc keeps its\n // content either way. Subscribers must observe the flip immediately —\n // waiting for the next provider event would let them act on synced=true\n // across the replacement gap.\n if (synced) {\n synced = false;\n notify();\n }\n if (provider) {\n // Its unconfirmed edits outlive it: the next provider sends them and waits for their echo.\n const previous = provider;\n provider = null;\n if (httpFirstRead?.target === previous) {\n httpFirstRead.controller.abort(new DOMException('The room closed', 'AbortError'));\n httpFirstRead = null;\n }\n carriedUpdates = [...carriedUpdates, ...previous.unconfirmedUpdates];\n previous.destroy();\n }\n };\n\n const scheduleRefresh = (grant: CollabTokenResponse) => {\n clearRefreshTimer();\n const delay = refreshDelayMs({ expiresAtMs: grant.expires_at_ms, now: Date.now() });\n refreshTimer = setTimeout(() => {\n void connect({ scheduledRefresh: true });\n }, delay);\n };\n\n /** A failed attempt that is worth retrying: try again later, or as soon as the network returns. */\n const scheduleRetry = () => {\n clearRetryTimer();\n const delay = MINT_RETRY_DELAYS_MS[Math.min(mintRetries, MINT_RETRY_DELAYS_MS.length - 1)];\n mintRetries += 1;\n retryTimer = setTimeout(() => {\n retryTimer = null;\n void connect();\n }, delay);\n };\n\n const onBrowserOnline = () => {\n // Only a handle waiting to retry: a refused or permanently closed one stays stopped.\n if (\n destroyed || !connectionEnabled || status === 'closed' || status === 'error' ||\n provider !== null || held\n ) return;\n mintRetries = 0;\n clearRetryTimer();\n void connect();\n };\n if (typeof window !== 'undefined') window.addEventListener('online', onBrowserOnline);\n\n /**\n * Past the gate's threshold without a socket, the handle reconnects itself (re-mint, gate). A\n * socket still being opened with nothing waiting to be sent is left to finish (a slow network\n * is not restarted every threshold), and the handle looks again a threshold later; if it opens\n * holding edits made since, they go through the gate first (`status`).\n */\n const armOfflineTakeover = () => {\n if (!connectionEnabled || offlineTimer !== null || !localCopy?.beforeConnect) return;\n offlineTimer = setTimeout(() => {\n offlineTimer = null;\n if (destroyed || !connectionEnabled || status === 'connected' || provider === null) return;\n // A provider reading its document over HTTP first is opening too (a long report, a slow link)\n if ((provider.wsconnecting || httpFirstRead?.target === provider) && !hasUnsyncedLocalEdits()) {\n openingPastThreshold = provider;\n armOfflineTakeover();\n return;\n }\n teardownProvider();\n void connect();\n }, offlineGateAfterMs);\n };\n\n const hasUnsyncedLocalEdits = () =>\n carriedUpdates.length > 0 || (provider?.unconfirmedUpdates.length ?? 0) > 0;\n\n\n const connect = async (opts?: {\n scheduledRefresh?: boolean;\n skipGate?: boolean;\n grant?: CollabTokenResponse;\n }): Promise<void> => {\n if (destroyed || !connectionEnabled) return;\n const seq = ++connectSeq;\n await preparing;\n if (destroyed || !connectionEnabled || seq !== connectSeq) return;\n // Only a live connection is refreshed in place (and skips the host's gate); a refresh while the\n // socket is down is a reconnect like any other.\n const scheduledRefresh = opts?.scheduledRefresh === true && status === 'connected';\n // A scheduled refresh mints FIRST and keeps the live session up: the old\n // token has ~5 minutes of headroom, so a transient mint failure retries\n // on a short timer instead of dropping a healthy connection.\n if (!scheduledRefresh) {\n teardownProvider();\n } else {\n clearRefreshTimer();\n }\n clearRetryTimer();\n if (destroyed || !connectionEnabled || seq !== connectSeq) return;\n let grant: CollabTokenResponse;\n if (opts?.grant && opts.grant.expires_at_ms - Date.now() > MIN_REFRESH_DELAY_MS) {\n grant = opts.grant;\n } else {\n try {\n grant = await mint({ assetId: args.assetId, access });\n } catch (err) {\n if (destroyed || !connectionEnabled || seq !== connectSeq) return;\n if (scheduledRefresh) {\n refreshTimer = setTimeout(() => {\n void connect({ scheduledRefresh: true });\n }, MIN_REFRESH_DELAY_MS);\n return;\n }\n if (retryMintError(err)) {\n // Offline (or the mint's server is): keep the document and try again.\n if (status !== 'disconnected') setStatus('disconnected');\n scheduleRetry();\n return;\n }\n // A denied mint is authoritative (revoked / not shared / not eligible).\n setStatus('error', err instanceof Error ? err : new Error(String(err)));\n return;\n }\n }\n if (destroyed || !connectionEnabled || seq !== connectSeq) return;\n mintRetries = 0;\n accessType = grant.access_type;\n const beforeConnect = localCopy?.beforeConnect;\n if (beforeConnect && !scheduledRefresh && !opts?.skipGate) {\n const firstConnection = !everConnected;\n const offlineForMs = disconnectedSince === null ? null : Date.now() - disconnectedSince;\n let decision: 'connect' | 'hold';\n try {\n decision = await beforeConnect({\n grant,\n firstConnection,\n offlineForMs,\n hasUnsyncedEdits: hasUnsyncedLocalEdits(),\n });\n } catch {\n if (destroyed || !connectionEnabled || seq !== connectSeq) return;\n if (status !== 'disconnected') setStatus('disconnected');\n scheduleRetry();\n return;\n }\n if (destroyed || !connectionEnabled || seq !== connectSeq) return;\n if (decision === 'hold') {\n held = true;\n heldGrant = grant;\n if (status !== 'disconnected') setStatus('disconnected');\n else notify();\n return;\n }\n }\n if (scheduledRefresh) {\n teardownProvider();\n }\n if (destroyed || !connectionEnabled || seq !== connectSeq) return;\n\n const socket = socketFor({ grant, doc, unconfirmed: unconfirmedAttributions });\n const roomUrl = `${grant.ws_url}/${grant.org}/${grant.doc_id}`;\n // Word at scale: a document that holds nothing yet is read over HTTP first, then the socket connects\n const httpFirstUrl =\n args.httpFirstOpen === true && doc.store.clients.size === 0 && carriedUpdates.length === 0\n ? keryxRoomReadUrl({ wsUrl: roomUrl, token: grant.token, branch: grant.branch })\n : null;\n const params: Record<string, string> = {\n yauth: grant.token,\n branch: grant.branch,\n gc: 'true',\n };\n if (httpFirstUrl === null && asksForDiffedSync({ roomUrl, unconfirmed: carriedUpdates.length })) {\n params[INITIAL_SYNC_PARAM] = INITIAL_SYNC_DIFF;\n }\n const nextProvider = new WebsocketProvider(grant.ws_url, `${grant.org}/${grant.doc_id}`, doc, {\n params,\n // BroadcastChannel would sync same-origin clients locally, bypassing the\n // server's permission enforcement (a read-only tab could write into an\n // editor tab's doc). Permissioned docs must round-trip the server.\n disableBc: true,\n connect: httpFirstUrl === null,\n ...(socket && { WebSocketPolyfill: socket }),\n });\n provider = nextProvider;\n liveGrant = grant;\n nextProvider.unconfirmedUpdates = [...carriedUpdates, ...nextProvider.unconfirmedUpdates];\n carriedUpdates = [];\n refreshLocalChangesSynced();\n\n nextProvider.on('sync-status', () => {\n if (provider !== nextProvider) return;\n refreshLocalChangesSynced();\n });\n\n nextProvider.on('status', (event: { status: 'connecting' | 'connected' | 'disconnected' }) => {\n if (provider !== nextProvider) return;\n if (\n event.status === 'connected' &&\n openingPastThreshold === nextProvider &&\n hasUnsyncedLocalEdits()\n ) {\n // Opened after the threshold holding edits made meanwhile: before its handshake sends\n // them (`@y/websocket` reports `connected` first), they go through the gate.\n teardownProvider();\n void connect();\n return;\n }\n // The connections that read Keryx's document status at once: the first, the one after an auth\n // re-check close, and one after an outage the handle treats as real. Never an ordinary\n // reconnect (a Keryx deploy reconnects every room at once).\n const readStatusNow =\n event.status === 'connected' &&\n (!everConnected ||\n readStatusOnConnect ||\n (disconnectedSince !== null && Date.now() - disconnectedSince >= offlineGateAfterMs));\n if (event.status === 'connected') {\n consecutiveRemints = 0;\n readStatusOnConnect = false;\n }\n setStatus(event.status);\n if (event.status === 'connected') documentStatus?.connected({ readNow: readStatusNow });\n if (event.status === 'connected' && lastPresence !== null) {\n nextProvider.awareness.setLocalState(lastPresence);\n }\n // `@y/websocket` reports `disconnected` only for a socket that had opened: one that never\n // opens (the server unreachable while the mint goes through) only ever reports `connecting`,\n // and is just as offline.\n if (event.status !== 'connected') armOfflineTakeover();\n });\n // Its first `connecting` came from its constructor, before this listener existed.\n if (!nextProvider.wsconnected) armOfflineTakeover();\n\n nextProvider.on('sync', (state: boolean) => {\n if (provider !== nextProvider) return;\n if (synced !== state) {\n synced = state;\n transportChanged();\n notify();\n }\n });\n\n nextProvider.on('connection-close', (event: CloseEvent | null) => {\n if (provider !== nextProvider) return;\n // The next socket asks for a diffed initial sync only while nothing it holds needs Keryx's whole document\n if (asksForDiffedSync({ roomUrl, unconfirmed: nextProvider.unconfirmedUpdates.length })) {\n nextProvider.params[INITIAL_SYNC_PARAM] = INITIAL_SYNC_DIFF;\n } else {\n delete nextProvider.params[INITIAL_SYNC_PARAM];\n }\n const action = classifyClose(event?.code);\n if (action === 'remint') {\n // Revoked mid-session: a fresh mint re-runs the server-side permission\n // check. If access is truly gone the mint 403s and we land in 'error'.\n // Bounded: repeated 4401s without an intervening successful connect\n // mean the server keeps rejecting freshly minted tokens — stop rather\n // than loop mint→connect→kick.\n consecutiveRemints += 1;\n // A quarantine and a release both close the room's sockets this way, once Keryx has written\n // or cleared the marker: the reconnected socket learns which. Until then nothing is read\n // (the handle stays `connected` through the re-mint, on a grant Keryx just bounced).\n readStatusOnConnect = true;\n documentStatus?.disconnected();\n teardownProvider();\n if (consecutiveRemints > MAX_CONSECUTIVE_REMINTS) {\n setStatus(\n 'closed',\n new Error('Access repeatedly revoked mid-session (4401); giving up.')\n );\n return;\n }\n void connect();\n } else if (action === 'stop') {\n teardownProvider();\n setStatus(\n 'closed',\n new Error(`Connection closed permanently (code ${event?.code ?? 'unknown'})`)\n );\n }\n // 'retry': the provider's exponential backoff handles it, until the offline takeover.\n });\n\n nextProvider.awareness.on('change', () => {\n if (provider !== nextProvider) return;\n notify();\n });\n\n scheduleRefresh(grant);\n if (httpFirstUrl !== null) void openOverHttp({ target: nextProvider, url: httpFirstUrl, roomUrl });\n };\n\n /**\n * Word at scale: whether a socket of this room asks for a diffed initial sync - a room that opens\n * HTTP-first, whose Keryx is known to answer it, whose document holds something, and that holds no\n * write Keryx may hold without having echoed it (an unconfirmed update, a kept attributed write):\n * those are confirmed by the whole document Keryx sends when a socket opens.\n */\n function asksForDiffedSync({ roomUrl, unconfirmed }: { roomUrl: string; unconfirmed: number }): boolean {\n if (args.httpFirstOpen !== true) return false;\n const origin = keryxOriginOf(roomUrl);\n const known =\n keryxAnswersSyncStep1 ||\n (origin !== null && knownInitialSyncSupport({ storage: browserStorage(), origin }) === true);\n return known && doc.store.clients.size > 0 && unconfirmed === 0 && !unconfirmedAttributions.keepsWrites;\n }\n\n /**\n * Word at scale: read the room over HTTP, apply it as Keryx's own state (the provider's origin, so\n * nothing treats it as a local edit), then connect the provider's socket, asking for the diff when\n * Keryx said it answers that way. A Keryx that did not, a failed read, or a provider replaced\n * meanwhile: the document is left as it was and the socket connects as every room's does.\n */\n async function openOverHttp({\n target,\n url,\n roomUrl,\n }: {\n target: WebsocketProvider;\n url: string;\n roomUrl: string;\n }): Promise<void> {\n const started = performance.now();\n const origin = keryxOriginOf(roomUrl);\n const storage = browserStorage();\n let event: GenericDocHttpFirstOpenEvent;\n if (origin !== null && knownInitialSyncSupport({ storage, origin }) === false) {\n event = { outcome: 'skipped', durationMs: 0 };\n } else {\n const controller = new AbortController();\n httpFirstRead = { target, controller };\n const timeout = setTimeout(\n () => controller.abort(new DOMException('The HTTP-first read timed out', 'TimeoutError')),\n HTTP_FIRST_READ_TIMEOUT_MS\n );\n try {\n const read = await readRoomOverHttp({ url, signal: controller.signal });\n if (origin !== null) rememberInitialSyncSupport({ storage, origin, supported: read.answersSyncStep1 });\n if (read.answersSyncStep1 && provider === target && !destroyed) {\n if (read.update.byteLength > 2) Y.applyUpdate(doc, read.update, target);\n keryxAnswersSyncStep1 = true;\n }\n event = {\n outcome: read.answersSyncStep1 ? 'read' : 'unsupported',\n bytes: read.bytes,\n durationMs: performance.now() - started,\n };\n } catch (err) {\n // the socket's whole-document sync, as before; a read the room stopped is no failure\n event =\n controller.signal.aborted && (destroyed || provider !== target)\n ? { outcome: 'aborted', durationMs: performance.now() - started }\n : {\n outcome: 'failed',\n durationMs: performance.now() - started,\n error: err instanceof Error ? `${err.name}: ${err.message}` : String(err),\n };\n } finally {\n clearTimeout(timeout);\n if (httpFirstRead?.controller === controller) httpFirstRead = null;\n }\n }\n try {\n args.onHttpFirstOpen?.(event);\n } catch {\n // a host's telemetry never keeps the room from opening its socket\n }\n if (destroyed || provider !== target) return;\n if (asksForDiffedSync({ roomUrl, unconfirmed: target.unconfirmedUpdates.length })) {\n target.params[INITIAL_SYNC_PARAM] = INITIAL_SYNC_DIFF;\n } else {\n delete target.params[INITIAL_SYNC_PARAM];\n }\n target.connect();\n }\n\n const preparing: Promise<void> = localCopy\n ? localCopy\n .prepare({ doc, transport })\n .catch(() => ({ unsyncedEdits: null }))\n .then(({ unsyncedEdits }) => {\n if (destroyed) return;\n if (unsyncedEdits && !(unsyncedEdits.inserts.isEmpty() && unsyncedEdits.deletes.isEmpty())) {\n carriedUpdates = [...carriedUpdates, { created: Date.now(), ids: unsyncedEdits }];\n }\n prepared = true;\n refreshLocalChangesSynced();\n notify();\n })\n : Promise.resolve();\n\n void connect();\n\n const waitForSync = (timeoutMs = 15_000): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n const terminal = (): Error | null => {\n if (destroyed) return new Error('Handle destroyed before initial sync');\n if (status === 'closed' || status === 'error') {\n return error ?? new Error(`Connection ${status} before initial sync`);\n }\n return null;\n };\n if (synced) {\n resolve();\n return;\n }\n const immediate = terminal();\n if (immediate) {\n reject(immediate);\n return;\n }\n const cleanup = () => {\n clearTimeout(timer);\n listeners.delete(listener);\n };\n const timer = setTimeout(() => {\n cleanup();\n reject(new Error(`Timed out after ${timeoutMs}ms waiting for initial sync`));\n }, timeoutMs);\n const listener = () => {\n if (synced) {\n cleanup();\n resolve();\n return;\n }\n const err = terminal();\n if (err) {\n cleanup();\n reject(err);\n }\n };\n listeners.add(listener);\n });\n\n const waitForAcknowledged = (timeoutMs = 15_000): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n let finished = false;\n let checkQueued = false;\n let timer: ReturnType<typeof setTimeout> | null = null;\n const finish = (failure?: Error) => {\n if (finished) return;\n finished = true;\n if (timer !== null) clearTimeout(timer);\n listeners.delete(check);\n if (failure) reject(failure);\n else resolve();\n };\n const check = () => {\n if (finished || checkQueued) return;\n checkQueued = true;\n // All synchronous transport hooks and change listeners finish before a save settles.\n queueMicrotask(() => {\n checkQueued = false;\n if (finished) return;\n if (destroyed) {\n finish(new Error('Handle destroyed before local changes were acknowledged'));\n } else if (!connectionEnabled) {\n finish(new Error('Connection disabled before local changes were acknowledged'));\n } else if (status === 'closed' || status === 'error') {\n finish(error ?? new Error(`Connection ${status} before local changes were acknowledged`));\n } else if (prepared && status === 'connected' && synced && localChangesSynced) {\n finish();\n }\n });\n };\n timer = setTimeout(() => {\n finish(new Error(`Timed out after ${timeoutMs}ms waiting for local changes to be acknowledged`));\n }, timeoutMs);\n listeners.add(check);\n check();\n });\n\n return {\n doc,\n get status() {\n return status;\n },\n get synced() {\n return synced;\n },\n get localChangesSynced() {\n return localChangesSynced;\n },\n get accessType() {\n return accessType;\n },\n get error() {\n return error;\n },\n get prepared() {\n return prepared;\n },\n get connectionEnabled() {\n return connectionEnabled;\n },\n get held() {\n return held;\n },\n get version() {\n return version;\n },\n get writesRefused() {\n return documentStatus?.writesRefused ?? false;\n },\n waitForSync,\n waitForAcknowledged,\n getPresence: () => {\n if (!provider) return [];\n const entries: PresenceEntry[] = [];\n provider.awareness.getStates().forEach((state, clientId) => {\n entries.push({ clientId, state: state as Record<string, unknown> });\n });\n return entries;\n },\n setPresence: (state) => {\n lastPresence = state;\n provider?.awareness.setLocalState(state);\n },\n refreshNow: () => {\n if (!connectionEnabled || held) return Promise.resolve();\n return provider ? connect({ scheduledRefresh: true }) : connect();\n },\n setConnectionEnabled: (enabled) => {\n if (destroyed || enabled === connectionEnabled) return;\n connectionEnabled = enabled;\n if (!enabled) {\n // Invalidate every mint/gate already in flight before tearing down the live provider.\n connectSeq += 1;\n clearRetryTimer();\n clearOfflineTimer();\n teardownProvider();\n setStatus('disconnected');\n localCopy?.connectionPolicyChanged?.(false);\n return;\n }\n localCopy?.connectionPolicyChanged?.(true);\n held = false;\n heldGrant = null;\n setStatus('connecting');\n void connect();\n },\n resume: () => {\n if (!held || destroyed || !connectionEnabled) return;\n held = false;\n const grant = heldGrant;\n heldGrant = null;\n notify();\n void connect({ skipGate: true, grant: grant ?? undefined });\n },\n unconfirmedEdits,\n onChange: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n destroy: () => {\n if (destroyed) return;\n destroyed = true;\n documentStatus?.destroy();\n teardownProvider();\n clearRetryTimer();\n clearOfflineTimer();\n if (typeof window !== 'undefined') window.removeEventListener('online', onBrowserOnline);\n status = 'closed';\n // Final notification so pending waitForSync callers reject instead of\n // hanging on listeners that are about to be dropped.\n for (const listener of [...listeners]) listener();\n listeners.clear();\n unconfirmedAttributions.destroy();\n doc.destroy();\n },\n };\n}\n\nexport { CollabTokenError };\nexport type { CollabAuth, CollabTokenResponse };\n"],"names":[],"mappings":";;;;;;;;;;AA2NO,MAAM,gCAAgC;AAG7C,MAAM,uBAAuB,CAAC,KAAO,KAAO,KAAO,KAAO,MAAQ,KAAQ,GAAM;AAMzE,SAAS,qBAAqB,OAAyB;AAC5D,MAAI,iBAAiB,kBAAkB;AACrC,WAAO,MAAM,UAAU,OAAO,MAAM,WAAW,OAAO,MAAM,WAAW;AAAA,EACzE;AACA,SAAO,iBAAiB,aAAc,iBAAiB,gBAAgB,MAAM,SAAS;AACxF;AAEA,SAAS,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AAO,WAAW,YAAa,QAAO,oBAAoB,UAAU,eAAe;AACvF,eAAS;AAGT,iBAAW,YAAY,CAAC,GAAG,SAAS,EAAG,UAAA;AACvC,gBAAU,MAAA;AACV,8BAAwB,QAAA;AACxB,UAAI,QAAA;AAAA,IACN;AAAA,EAAA;AAEJ;"}
@@ -21,7 +21,7 @@
21
21
  */
22
22
  export { classifyClose, WS_CLOSE_AUTH_REVOKED, WS_CLOSE_DOC_DELETED } from './close-policy';
23
23
  export { DOCUMENT_STATUS_READ_TIMEOUT_MS, DOCUMENT_STATUS_REFRESH_MS, DOCUMENT_STATUS_REFUSED_REFRESH_MS, type DocumentStatusReading, type ReadDocumentStatus, } from './document-status';
24
- export { CollabTokenError, connectGenericDoc, DEFAULT_OFFLINE_GATE_AFTER_MS, isRetryableMintError, type CollabAuth, type CollabMint, type CollabTokenResponse, type GenericDocConnectGate, type GenericDocHandle, type GenericDocLocalCopy, type GenericDocStatus, type GenericDocTransportView, type PresenceEntry, } from './client';
24
+ export { CollabTokenError, connectGenericDoc, DEFAULT_OFFLINE_GATE_AFTER_MS, isRetryableMintError, type CollabAuth, type CollabMint, type CollabTokenResponse, type GenericDocConnectGate, type GenericDocHandle, type GenericDocHttpFirstOpenEvent, type GenericDocLocalCopy, type GenericDocStatus, type GenericDocTransportView, type PresenceEntry, } from './client';
25
25
  export { BACKGROUND_UPDATE_ATTRIBUTIONS, runWithDocUpdateAttributions, type UpdateAttribution, } from '../keryx-http/src/update-attributions';
26
26
  export { getAthenaApiBaseUrl, mintCollabToken } from './mint';
27
27
  export { PRESENCE_SWEEP_INTERVAL_MS, connectWorkspacePresence, type WorkspacePresenceHandle, type WorkspacePresenceStatus, } from './presence-client';
@@ -0,0 +1,121 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ const decoding = require("lib0/decoding");
4
+ function _interopNamespaceDefault(e) {
5
+ const n = Object.create(null, { [Symbol.toStringTag]: { value: "Module" } });
6
+ if (e) {
7
+ for (const k in e) {
8
+ if (k !== "default") {
9
+ const d = Object.getOwnPropertyDescriptor(e, k);
10
+ Object.defineProperty(n, k, d.get ? d : {
11
+ enumerable: true,
12
+ get: () => e[k]
13
+ });
14
+ }
15
+ }
16
+ }
17
+ n.default = e;
18
+ return Object.freeze(n);
19
+ }
20
+ const decoding__namespace = /* @__PURE__ */ _interopNamespaceDefault(decoding);
21
+ const INITIAL_SYNC_PARAM = "initialSync";
22
+ const INITIAL_SYNC_DIFF = "diff";
23
+ const INITIAL_SYNC_CAPABILITY_HEADER = "x-keryx-initial-sync";
24
+ function keryxRoomReadUrl({
25
+ wsUrl,
26
+ token,
27
+ branch
28
+ }) {
29
+ let parsed;
30
+ try {
31
+ parsed = new URL(wsUrl);
32
+ } catch {
33
+ return null;
34
+ }
35
+ const scheme = parsed.protocol === "wss:" ? "https:" : parsed.protocol === "ws:" ? "http:" : null;
36
+ if (scheme === null) return null;
37
+ const match = /^(.*?)\/(?:api\/ws\/v1|ws)\/([^/]+)\/([^/]+)\/?$/.exec(parsed.pathname);
38
+ if (match === null) return null;
39
+ const [, prefix = "", org = "", docId = ""] = match;
40
+ const read = new URL(`${scheme}//${parsed.host}${prefix}/api/ydoc/v1/${org}/${docId}`);
41
+ read.searchParams.set("yauth", token);
42
+ read.searchParams.set("branch", branch);
43
+ return read.toString();
44
+ }
45
+ async function readRoomOverHttp({
46
+ url,
47
+ signal,
48
+ fetchImpl = fetch
49
+ }) {
50
+ var _a;
51
+ const response = await fetchImpl(url, { headers: { Accept: "application/octet-stream" }, signal });
52
+ if (!response.ok) {
53
+ await ((_a = response.body) == null ? void 0 : _a.cancel().catch(() => void 0));
54
+ throw new Error(`GET /ydoc answered ${response.status}`);
55
+ }
56
+ const body = new Uint8Array(await response.arrayBuffer());
57
+ const decoded = decoding__namespace.readAny(decoding__namespace.createDecoder(body));
58
+ if (decoded === null || typeof decoded !== "object" || !(decoded.doc instanceof Uint8Array)) {
59
+ throw new Error("GET /ydoc answered a body without a document");
60
+ }
61
+ return {
62
+ // a copy: lib0 hands out a view into the body
63
+ update: new Uint8Array(decoded.doc),
64
+ answersSyncStep1: response.headers.get(INITIAL_SYNC_CAPABILITY_HEADER) === INITIAL_SYNC_DIFF,
65
+ bytes: body.byteLength
66
+ };
67
+ }
68
+ const MEMO_PREFIX = "keryx-initial-sync:";
69
+ const INITIAL_SYNC_UNSUPPORTED_TTL_MS = 60 * 60 * 1e3;
70
+ const INITIAL_SYNC_SUPPORTED_TTL_MS = 7 * 24 * 60 * 60 * 1e3;
71
+ function keryxOriginOf(wsUrl) {
72
+ try {
73
+ const parsed = new URL(wsUrl);
74
+ return `${parsed.protocol}//${parsed.host}`;
75
+ } catch {
76
+ return null;
77
+ }
78
+ }
79
+ function rememberInitialSyncSupport({
80
+ storage,
81
+ origin,
82
+ supported,
83
+ now = Date.now()
84
+ }) {
85
+ try {
86
+ storage == null ? void 0 : storage.setItem(`${MEMO_PREFIX}${origin}`, JSON.stringify({ supported, at: now }));
87
+ } catch {
88
+ }
89
+ }
90
+ function knownInitialSyncSupport({
91
+ storage,
92
+ origin,
93
+ now = Date.now()
94
+ }) {
95
+ let raw = null;
96
+ try {
97
+ raw = (storage == null ? void 0 : storage.getItem(`${MEMO_PREFIX}${origin}`)) ?? null;
98
+ } catch {
99
+ return null;
100
+ }
101
+ if (raw === null) return null;
102
+ try {
103
+ const memo = JSON.parse(raw);
104
+ if (typeof memo.supported !== "boolean" || typeof memo.at !== "number") return null;
105
+ const ttl = memo.supported ? INITIAL_SYNC_SUPPORTED_TTL_MS : INITIAL_SYNC_UNSUPPORTED_TTL_MS;
106
+ return now - memo.at <= ttl ? memo.supported : null;
107
+ } catch {
108
+ return null;
109
+ }
110
+ }
111
+ exports.INITIAL_SYNC_CAPABILITY_HEADER = INITIAL_SYNC_CAPABILITY_HEADER;
112
+ exports.INITIAL_SYNC_DIFF = INITIAL_SYNC_DIFF;
113
+ exports.INITIAL_SYNC_PARAM = INITIAL_SYNC_PARAM;
114
+ exports.INITIAL_SYNC_SUPPORTED_TTL_MS = INITIAL_SYNC_SUPPORTED_TTL_MS;
115
+ exports.INITIAL_SYNC_UNSUPPORTED_TTL_MS = INITIAL_SYNC_UNSUPPORTED_TTL_MS;
116
+ exports.keryxOriginOf = keryxOriginOf;
117
+ exports.keryxRoomReadUrl = keryxRoomReadUrl;
118
+ exports.knownInitialSyncSupport = knownInitialSyncSupport;
119
+ exports.readRoomOverHttp = readRoomOverHttp;
120
+ exports.rememberInitialSyncSupport = rememberInitialSyncSupport;
121
+ //# sourceMappingURL=initial-sync.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"initial-sync.cjs","sources":["../../../../keryx-http/src/initial-sync.ts"],"sourcesContent":["/**\n * Opening a big room HTTP-first (Word at scale, 2026-11-02).\n *\n * A Keryx socket's initial sync step 2 is the whole document, sent as one frame that uWS deflates on\n * Keryx's event loop: 1.4-1.8 s for a 132 MiB Word room, during which no other room on that server\n * is served, then 17 MiB on the wire. A Keryx that carries the `@y/hub` patch's diffed initial sync\n * answers a socket that connects with `?initialSync=diff` with only what the client lacks past its\n * own sync step 1, and serves `GET /ydoc` compressed (zstd, brotli or gzip, as the browser names\n * them) from a kept copy. So a client opening a big room reads it over HTTP first - decoded by the\n * browser as it downloads - applies it as the server's state, and opens its socket asking for the\n * rest: usually just the delete set.\n *\n * A Keryx says it answers that way in its `GET /ydoc` answer to a browser\n * (`X-Keryx-Initial-Sync: diff`, exposed to cross-origin readers). A Keryx without the patch says\n * nothing: its document is then not used, the socket opens as before, and the origin is remembered\n * as one that does not answer, so the next open skips the read.\n */\n\nimport * as decoding from 'lib0/decoding';\n\n/** The socket query parameter, and its one value, that ask for a diffed initial sync. */\nexport const INITIAL_SYNC_PARAM = 'initialSync';\nexport const INITIAL_SYNC_DIFF = 'diff';\n\n/** The `GET /ydoc` response header with which a Keryx says it answers `?initialSync=diff`. */\nexport const INITIAL_SYNC_CAPABILITY_HEADER = 'x-keryx-initial-sync';\n\n/**\n * The `GET /ydoc` URL of the room a socket URL names: `wss://host/ws/<org>/<docId>` (or the\n * `/api/ws/v1/` spelling) becomes `https://host/api/ydoc/v1/<org>/<docId>?yauth=…&branch=…`. `null`\n * for a URL of any other shape.\n */\nexport function keryxRoomReadUrl({\n wsUrl,\n token,\n branch,\n}: {\n wsUrl: string;\n token: string;\n branch: string;\n}): string | null {\n let parsed: URL;\n try {\n parsed = new URL(wsUrl);\n } catch {\n return null;\n }\n const scheme = parsed.protocol === 'wss:' ? 'https:' : parsed.protocol === 'ws:' ? 'http:' : null;\n if (scheme === null) return null;\n const match = /^(.*?)\\/(?:api\\/ws\\/v1|ws)\\/([^/]+)\\/([^/]+)\\/?$/.exec(parsed.pathname);\n if (match === null) return null;\n const [, prefix = '', org = '', docId = ''] = match;\n const read = new URL(`${scheme}//${parsed.host}${prefix}/api/ydoc/v1/${org}/${docId}`);\n read.searchParams.set('yauth', token);\n read.searchParams.set('branch', branch);\n return read.toString();\n}\n\n/** A room read over HTTP. */\nexport interface RoomReadOverHttp {\n /** The room's state as one update (empty for a room never written). */\n update: Uint8Array;\n /** Keryx said it answers a socket's sync step 1 (`INITIAL_SYNC_CAPABILITY_HEADER`). */\n answersSyncStep1: boolean;\n /** The decoded body's size. */\n bytes: number;\n}\n\n/**\n * Read a room over `GET /ydoc` (`url` from {@link keryxRoomReadUrl}). The runtime's `fetch` names\n * and decodes the content codings. Throws on a non-2xx answer or a body that is not a lib0 `{ doc }`.\n */\nexport async function readRoomOverHttp({\n url,\n signal,\n fetchImpl = fetch,\n}: {\n url: string;\n signal?: AbortSignal;\n fetchImpl?: typeof fetch;\n}): Promise<RoomReadOverHttp> {\n const response = await fetchImpl(url, { headers: { Accept: 'application/octet-stream' }, signal });\n if (!response.ok) {\n await response.body?.cancel().catch(() => undefined);\n throw new Error(`GET /ydoc answered ${response.status}`);\n }\n const body = new Uint8Array(await response.arrayBuffer());\n const decoded = decoding.readAny(decoding.createDecoder(body)) as { doc?: unknown } | null;\n if (decoded === null || typeof decoded !== 'object' || !(decoded.doc instanceof Uint8Array)) {\n throw new Error('GET /ydoc answered a body without a document');\n }\n return {\n // a copy: lib0 hands out a view into the body\n update: new Uint8Array(decoded.doc),\n answersSyncStep1: response.headers.get(INITIAL_SYNC_CAPABILITY_HEADER) === INITIAL_SYNC_DIFF,\n bytes: body.byteLength,\n };\n}\n\n/** Where {@link rememberInitialSyncSupport} keeps what it learned: `localStorage`'s surface. */\nexport interface InitialSyncSupportStorage {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n}\n\nconst MEMO_PREFIX = 'keryx-initial-sync:';\n/** A Keryx that answered without the header is asked again an hour later: it may have been upgraded. */\nexport const INITIAL_SYNC_UNSUPPORTED_TTL_MS = 60 * 60 * 1000;\n/** A Keryx that answers is believed for a week; one rolled back meanwhile just sends whole documents. */\nexport const INITIAL_SYNC_SUPPORTED_TTL_MS = 7 * 24 * 60 * 60 * 1000;\n\n/** The origin a socket URL connects to, as the memo keys it (`wss://host`). */\nexport function keryxOriginOf(wsUrl: string): string | null {\n try {\n const parsed = new URL(wsUrl);\n return `${parsed.protocol}//${parsed.host}`;\n } catch {\n return null;\n }\n}\n\n/** Remember whether the Keryx at `origin` answered with the capability header. */\nexport function rememberInitialSyncSupport({\n storage,\n origin,\n supported,\n now = Date.now(),\n}: {\n storage: InitialSyncSupportStorage | null;\n origin: string;\n supported: boolean;\n now?: number;\n}): void {\n try {\n storage?.setItem(`${MEMO_PREFIX}${origin}`, JSON.stringify({ supported, at: now }));\n } catch {\n // a full or refused storage only costs the next open a read\n }\n}\n\n/**\n * What is known of the Keryx at `origin`: `true` (it answers a socket's sync step 1), `false` (it\n * did not, within the last hour) or `null` (not known: read it and see).\n */\nexport function knownInitialSyncSupport({\n storage,\n origin,\n now = Date.now(),\n}: {\n storage: InitialSyncSupportStorage | null;\n origin: string;\n now?: number;\n}): boolean | null {\n let raw: string | null = null;\n try {\n raw = storage?.getItem(`${MEMO_PREFIX}${origin}`) ?? null;\n } catch {\n return null;\n }\n if (raw === null) return null;\n try {\n const memo = JSON.parse(raw) as { supported?: unknown; at?: unknown };\n if (typeof memo.supported !== 'boolean' || typeof memo.at !== 'number') return null;\n const ttl = memo.supported ? INITIAL_SYNC_SUPPORTED_TTL_MS : INITIAL_SYNC_UNSUPPORTED_TTL_MS;\n return now - memo.at <= ttl ? memo.supported : null;\n } catch {\n return null;\n }\n}\n"],"names":["decoding"],"mappings":";;;;;;;;;;;;;;;;;;;;AAqBO,MAAM,qBAAqB;AAC3B,MAAM,oBAAoB;AAG1B,MAAM,iCAAiC;AAOvC,SAAS,iBAAiB;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AACF,GAIkB;AAChB,MAAI;AACJ,MAAI;AACF,aAAS,IAAI,IAAI,KAAK;AAAA,EACxB,QAAQ;AACN,WAAO;AAAA,EACT;AACA,QAAM,SAAS,OAAO,aAAa,SAAS,WAAW,OAAO,aAAa,QAAQ,UAAU;AAC7F,MAAI,WAAW,KAAM,QAAO;AAC5B,QAAM,QAAQ,mDAAmD,KAAK,OAAO,QAAQ;AACrF,MAAI,UAAU,KAAM,QAAO;AAC3B,QAAM,CAAA,EAAG,SAAS,IAAI,MAAM,IAAI,QAAQ,EAAE,IAAI;AAC9C,QAAM,OAAO,IAAI,IAAI,GAAG,MAAM,KAAK,OAAO,IAAI,GAAG,MAAM,gBAAgB,GAAG,IAAI,KAAK,EAAE;AACrF,OAAK,aAAa,IAAI,SAAS,KAAK;AACpC,OAAK,aAAa,IAAI,UAAU,MAAM;AACtC,SAAO,KAAK,SAAA;AACd;AAgBA,eAAsB,iBAAiB;AAAA,EACrC;AAAA,EACA;AAAA,EACA,YAAY;AACd,GAI8B;;AAC5B,QAAM,WAAW,MAAM,UAAU,KAAK,EAAE,SAAS,EAAE,QAAQ,8BAA8B,QAAQ;AACjG,MAAI,CAAC,SAAS,IAAI;AAChB,YAAM,cAAS,SAAT,mBAAe,SAAS,MAAM,MAAM;AAC1C,UAAM,IAAI,MAAM,sBAAs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AAa,OAAO,KAAK,OAAO,SAAU,QAAO;AAC/E,UAAM,MAAM,KAAK,YAAY,gCAAgC;AAC7D,WAAO,MAAM,KAAK,MAAM,MAAM,KAAK,YAAY;AAAA,EACjD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;;;;;;;;;;;"}
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Opening a big room HTTP-first (Word at scale, 2026-11-02).
3
+ *
4
+ * A Keryx socket's initial sync step 2 is the whole document, sent as one frame that uWS deflates on
5
+ * Keryx's event loop: 1.4-1.8 s for a 132 MiB Word room, during which no other room on that server
6
+ * is served, then 17 MiB on the wire. A Keryx that carries the `@y/hub` patch's diffed initial sync
7
+ * answers a socket that connects with `?initialSync=diff` with only what the client lacks past its
8
+ * own sync step 1, and serves `GET /ydoc` compressed (zstd, brotli or gzip, as the browser names
9
+ * them) from a kept copy. So a client opening a big room reads it over HTTP first - decoded by the
10
+ * browser as it downloads - applies it as the server's state, and opens its socket asking for the
11
+ * rest: usually just the delete set.
12
+ *
13
+ * A Keryx says it answers that way in its `GET /ydoc` answer to a browser
14
+ * (`X-Keryx-Initial-Sync: diff`, exposed to cross-origin readers). A Keryx without the patch says
15
+ * nothing: its document is then not used, the socket opens as before, and the origin is remembered
16
+ * as one that does not answer, so the next open skips the read.
17
+ */
18
+ /** The socket query parameter, and its one value, that ask for a diffed initial sync. */
19
+ export declare const INITIAL_SYNC_PARAM = "initialSync";
20
+ export declare const INITIAL_SYNC_DIFF = "diff";
21
+ /** The `GET /ydoc` response header with which a Keryx says it answers `?initialSync=diff`. */
22
+ export declare const INITIAL_SYNC_CAPABILITY_HEADER = "x-keryx-initial-sync";
23
+ /**
24
+ * The `GET /ydoc` URL of the room a socket URL names: `wss://host/ws/<org>/<docId>` (or the
25
+ * `/api/ws/v1/` spelling) becomes `https://host/api/ydoc/v1/<org>/<docId>?yauth=…&branch=…`. `null`
26
+ * for a URL of any other shape.
27
+ */
28
+ export declare function keryxRoomReadUrl({ wsUrl, token, branch, }: {
29
+ wsUrl: string;
30
+ token: string;
31
+ branch: string;
32
+ }): string | null;
33
+ /** A room read over HTTP. */
34
+ export interface RoomReadOverHttp {
35
+ /** The room's state as one update (empty for a room never written). */
36
+ update: Uint8Array;
37
+ /** Keryx said it answers a socket's sync step 1 (`INITIAL_SYNC_CAPABILITY_HEADER`). */
38
+ answersSyncStep1: boolean;
39
+ /** The decoded body's size. */
40
+ bytes: number;
41
+ }
42
+ /**
43
+ * Read a room over `GET /ydoc` (`url` from {@link keryxRoomReadUrl}). The runtime's `fetch` names
44
+ * and decodes the content codings. Throws on a non-2xx answer or a body that is not a lib0 `{ doc }`.
45
+ */
46
+ export declare function readRoomOverHttp({ url, signal, fetchImpl, }: {
47
+ url: string;
48
+ signal?: AbortSignal;
49
+ fetchImpl?: typeof fetch;
50
+ }): Promise<RoomReadOverHttp>;
51
+ /** Where {@link rememberInitialSyncSupport} keeps what it learned: `localStorage`'s surface. */
52
+ export interface InitialSyncSupportStorage {
53
+ getItem(key: string): string | null;
54
+ setItem(key: string, value: string): void;
55
+ }
56
+ /** A Keryx that answered without the header is asked again an hour later: it may have been upgraded. */
57
+ export declare const INITIAL_SYNC_UNSUPPORTED_TTL_MS: number;
58
+ /** A Keryx that answers is believed for a week; one rolled back meanwhile just sends whole documents. */
59
+ export declare const INITIAL_SYNC_SUPPORTED_TTL_MS: number;
60
+ /** The origin a socket URL connects to, as the memo keys it (`wss://host`). */
61
+ export declare function keryxOriginOf(wsUrl: string): string | null;
62
+ /** Remember whether the Keryx at `origin` answered with the capability header. */
63
+ export declare function rememberInitialSyncSupport({ storage, origin, supported, now, }: {
64
+ storage: InitialSyncSupportStorage | null;
65
+ origin: string;
66
+ supported: boolean;
67
+ now?: number;
68
+ }): void;
69
+ /**
70
+ * What is known of the Keryx at `origin`: `true` (it answers a socket's sync step 1), `false` (it
71
+ * did not, within the last hour) or `null` (not known: read it and see).
72
+ */
73
+ export declare function knownInitialSyncSupport({ storage, origin, now, }: {
74
+ storage: InitialSyncSupportStorage | null;
75
+ origin: string;
76
+ now?: number;
77
+ }): boolean | null;
@@ -0,0 +1,104 @@
1
+ import * as decoding from "lib0/decoding";
2
+ const INITIAL_SYNC_PARAM = "initialSync";
3
+ const INITIAL_SYNC_DIFF = "diff";
4
+ const INITIAL_SYNC_CAPABILITY_HEADER = "x-keryx-initial-sync";
5
+ function keryxRoomReadUrl({
6
+ wsUrl,
7
+ token,
8
+ branch
9
+ }) {
10
+ let parsed;
11
+ try {
12
+ parsed = new URL(wsUrl);
13
+ } catch {
14
+ return null;
15
+ }
16
+ const scheme = parsed.protocol === "wss:" ? "https:" : parsed.protocol === "ws:" ? "http:" : null;
17
+ if (scheme === null) return null;
18
+ const match = /^(.*?)\/(?:api\/ws\/v1|ws)\/([^/]+)\/([^/]+)\/?$/.exec(parsed.pathname);
19
+ if (match === null) return null;
20
+ const [, prefix = "", org = "", docId = ""] = match;
21
+ const read = new URL(`${scheme}//${parsed.host}${prefix}/api/ydoc/v1/${org}/${docId}`);
22
+ read.searchParams.set("yauth", token);
23
+ read.searchParams.set("branch", branch);
24
+ return read.toString();
25
+ }
26
+ async function readRoomOverHttp({
27
+ url,
28
+ signal,
29
+ fetchImpl = fetch
30
+ }) {
31
+ var _a;
32
+ const response = await fetchImpl(url, { headers: { Accept: "application/octet-stream" }, signal });
33
+ if (!response.ok) {
34
+ await ((_a = response.body) == null ? void 0 : _a.cancel().catch(() => void 0));
35
+ throw new Error(`GET /ydoc answered ${response.status}`);
36
+ }
37
+ const body = new Uint8Array(await response.arrayBuffer());
38
+ const decoded = decoding.readAny(decoding.createDecoder(body));
39
+ if (decoded === null || typeof decoded !== "object" || !(decoded.doc instanceof Uint8Array)) {
40
+ throw new Error("GET /ydoc answered a body without a document");
41
+ }
42
+ return {
43
+ // a copy: lib0 hands out a view into the body
44
+ update: new Uint8Array(decoded.doc),
45
+ answersSyncStep1: response.headers.get(INITIAL_SYNC_CAPABILITY_HEADER) === INITIAL_SYNC_DIFF,
46
+ bytes: body.byteLength
47
+ };
48
+ }
49
+ const MEMO_PREFIX = "keryx-initial-sync:";
50
+ const INITIAL_SYNC_UNSUPPORTED_TTL_MS = 60 * 60 * 1e3;
51
+ const INITIAL_SYNC_SUPPORTED_TTL_MS = 7 * 24 * 60 * 60 * 1e3;
52
+ function keryxOriginOf(wsUrl) {
53
+ try {
54
+ const parsed = new URL(wsUrl);
55
+ return `${parsed.protocol}//${parsed.host}`;
56
+ } catch {
57
+ return null;
58
+ }
59
+ }
60
+ function rememberInitialSyncSupport({
61
+ storage,
62
+ origin,
63
+ supported,
64
+ now = Date.now()
65
+ }) {
66
+ try {
67
+ storage == null ? void 0 : storage.setItem(`${MEMO_PREFIX}${origin}`, JSON.stringify({ supported, at: now }));
68
+ } catch {
69
+ }
70
+ }
71
+ function knownInitialSyncSupport({
72
+ storage,
73
+ origin,
74
+ now = Date.now()
75
+ }) {
76
+ let raw = null;
77
+ try {
78
+ raw = (storage == null ? void 0 : storage.getItem(`${MEMO_PREFIX}${origin}`)) ?? null;
79
+ } catch {
80
+ return null;
81
+ }
82
+ if (raw === null) return null;
83
+ try {
84
+ const memo = JSON.parse(raw);
85
+ if (typeof memo.supported !== "boolean" || typeof memo.at !== "number") return null;
86
+ const ttl = memo.supported ? INITIAL_SYNC_SUPPORTED_TTL_MS : INITIAL_SYNC_UNSUPPORTED_TTL_MS;
87
+ return now - memo.at <= ttl ? memo.supported : null;
88
+ } catch {
89
+ return null;
90
+ }
91
+ }
92
+ export {
93
+ INITIAL_SYNC_CAPABILITY_HEADER,
94
+ INITIAL_SYNC_DIFF,
95
+ INITIAL_SYNC_PARAM,
96
+ INITIAL_SYNC_SUPPORTED_TTL_MS,
97
+ INITIAL_SYNC_UNSUPPORTED_TTL_MS,
98
+ keryxOriginOf,
99
+ keryxRoomReadUrl,
100
+ knownInitialSyncSupport,
101
+ readRoomOverHttp,
102
+ rememberInitialSyncSupport
103
+ };
104
+ //# sourceMappingURL=initial-sync.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"initial-sync.js","sources":["../../../../keryx-http/src/initial-sync.ts"],"sourcesContent":["/**\n * Opening a big room HTTP-first (Word at scale, 2026-11-02).\n *\n * A Keryx socket's initial sync step 2 is the whole document, sent as one frame that uWS deflates on\n * Keryx's event loop: 1.4-1.8 s for a 132 MiB Word room, during which no other room on that server\n * is served, then 17 MiB on the wire. A Keryx that carries the `@y/hub` patch's diffed initial sync\n * answers a socket that connects with `?initialSync=diff` with only what the client lacks past its\n * own sync step 1, and serves `GET /ydoc` compressed (zstd, brotli or gzip, as the browser names\n * them) from a kept copy. So a client opening a big room reads it over HTTP first - decoded by the\n * browser as it downloads - applies it as the server's state, and opens its socket asking for the\n * rest: usually just the delete set.\n *\n * A Keryx says it answers that way in its `GET /ydoc` answer to a browser\n * (`X-Keryx-Initial-Sync: diff`, exposed to cross-origin readers). A Keryx without the patch says\n * nothing: its document is then not used, the socket opens as before, and the origin is remembered\n * as one that does not answer, so the next open skips the read.\n */\n\nimport * as decoding from 'lib0/decoding';\n\n/** The socket query parameter, and its one value, that ask for a diffed initial sync. */\nexport const INITIAL_SYNC_PARAM = 'initialSync';\nexport const INITIAL_SYNC_DIFF = 'diff';\n\n/** The `GET /ydoc` response header with which a Keryx says it answers `?initialSync=diff`. */\nexport const INITIAL_SYNC_CAPABILITY_HEADER = 'x-keryx-initial-sync';\n\n/**\n * The `GET /ydoc` URL of the room a socket URL names: `wss://host/ws/<org>/<docId>` (or the\n * `/api/ws/v1/` spelling) becomes `https://host/api/ydoc/v1/<org>/<docId>?yauth=…&branch=…`. `null`\n * for a URL of any other shape.\n */\nexport function keryxRoomReadUrl({\n wsUrl,\n token,\n branch,\n}: {\n wsUrl: string;\n token: string;\n branch: string;\n}): string | null {\n let parsed: URL;\n try {\n parsed = new URL(wsUrl);\n } catch {\n return null;\n }\n const scheme = parsed.protocol === 'wss:' ? 'https:' : parsed.protocol === 'ws:' ? 'http:' : null;\n if (scheme === null) return null;\n const match = /^(.*?)\\/(?:api\\/ws\\/v1|ws)\\/([^/]+)\\/([^/]+)\\/?$/.exec(parsed.pathname);\n if (match === null) return null;\n const [, prefix = '', org = '', docId = ''] = match;\n const read = new URL(`${scheme}//${parsed.host}${prefix}/api/ydoc/v1/${org}/${docId}`);\n read.searchParams.set('yauth', token);\n read.searchParams.set('branch', branch);\n return read.toString();\n}\n\n/** A room read over HTTP. */\nexport interface RoomReadOverHttp {\n /** The room's state as one update (empty for a room never written). */\n update: Uint8Array;\n /** Keryx said it answers a socket's sync step 1 (`INITIAL_SYNC_CAPABILITY_HEADER`). */\n answersSyncStep1: boolean;\n /** The decoded body's size. */\n bytes: number;\n}\n\n/**\n * Read a room over `GET /ydoc` (`url` from {@link keryxRoomReadUrl}). The runtime's `fetch` names\n * and decodes the content codings. Throws on a non-2xx answer or a body that is not a lib0 `{ doc }`.\n */\nexport async function readRoomOverHttp({\n url,\n signal,\n fetchImpl = fetch,\n}: {\n url: string;\n signal?: AbortSignal;\n fetchImpl?: typeof fetch;\n}): Promise<RoomReadOverHttp> {\n const response = await fetchImpl(url, { headers: { Accept: 'application/octet-stream' }, signal });\n if (!response.ok) {\n await response.body?.cancel().catch(() => undefined);\n throw new Error(`GET /ydoc answered ${response.status}`);\n }\n const body = new Uint8Array(await response.arrayBuffer());\n const decoded = decoding.readAny(decoding.createDecoder(body)) as { doc?: unknown } | null;\n if (decoded === null || typeof decoded !== 'object' || !(decoded.doc instanceof Uint8Array)) {\n throw new Error('GET /ydoc answered a body without a document');\n }\n return {\n // a copy: lib0 hands out a view into the body\n update: new Uint8Array(decoded.doc),\n answersSyncStep1: response.headers.get(INITIAL_SYNC_CAPABILITY_HEADER) === INITIAL_SYNC_DIFF,\n bytes: body.byteLength,\n };\n}\n\n/** Where {@link rememberInitialSyncSupport} keeps what it learned: `localStorage`'s surface. */\nexport interface InitialSyncSupportStorage {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n}\n\nconst MEMO_PREFIX = 'keryx-initial-sync:';\n/** A Keryx that answered without the header is asked again an hour later: it may have been upgraded. */\nexport const INITIAL_SYNC_UNSUPPORTED_TTL_MS = 60 * 60 * 1000;\n/** A Keryx that answers is believed for a week; one rolled back meanwhile just sends whole documents. */\nexport const INITIAL_SYNC_SUPPORTED_TTL_MS = 7 * 24 * 60 * 60 * 1000;\n\n/** The origin a socket URL connects to, as the memo keys it (`wss://host`). */\nexport function keryxOriginOf(wsUrl: string): string | null {\n try {\n const parsed = new URL(wsUrl);\n return `${parsed.protocol}//${parsed.host}`;\n } catch {\n return null;\n }\n}\n\n/** Remember whether the Keryx at `origin` answered with the capability header. */\nexport function rememberInitialSyncSupport({\n storage,\n origin,\n supported,\n now = Date.now(),\n}: {\n storage: InitialSyncSupportStorage | null;\n origin: string;\n supported: boolean;\n now?: number;\n}): void {\n try {\n storage?.setItem(`${MEMO_PREFIX}${origin}`, JSON.stringify({ supported, at: now }));\n } catch {\n // a full or refused storage only costs the next open a read\n }\n}\n\n/**\n * What is known of the Keryx at `origin`: `true` (it answers a socket's sync step 1), `false` (it\n * did not, within the last hour) or `null` (not known: read it and see).\n */\nexport function knownInitialSyncSupport({\n storage,\n origin,\n now = Date.now(),\n}: {\n storage: InitialSyncSupportStorage | null;\n origin: string;\n now?: number;\n}): boolean | null {\n let raw: string | null = null;\n try {\n raw = storage?.getItem(`${MEMO_PREFIX}${origin}`) ?? null;\n } catch {\n return null;\n }\n if (raw === null) return null;\n try {\n const memo = JSON.parse(raw) as { supported?: unknown; at?: unknown };\n if (typeof memo.supported !== 'boolean' || typeof memo.at !== 'number') return null;\n const ttl = memo.supported ? INITIAL_SYNC_SUPPORTED_TTL_MS : INITIAL_SYNC_UNSUPPORTED_TTL_MS;\n return now - memo.at <= ttl ? memo.supported : null;\n } catch {\n return null;\n }\n}\n"],"names":[],"mappings":";AAqBO,MAAM,qBAAqB;AAC3B,MAAM,oBAAoB;AAG1B,MAAM,iCAAiC;AAOvC,SAAS,iBAAiB;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;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AAQA,MAAM,cAAc;AAEb,MAAM,kCAAkC,KAAK,KAAK;AAElD,MAAM,gCAAgC,IAAI,KAAK,KAAK,KAAK;AAGzD,SAAS,cAAc,OAA8B;AAC1D,MAAI;AACF,UAAM,SAAS,IAAI,IAAI,KAAK;AAC5B,WAAO,GAAG,OAAO,QAAQ,KAAK,OAAO,IAAI;AAAA,EAC3C,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGO,SAAS,2BAA2B;AAAA,EACzC;AAAA,EACA;AAAA,EACA;AAAA,EACA,MAAM,KAAK,IAAA;AACb,GAKS;AACP,MAAI;AACF,uCAAS,QAAQ,GAAG,WAAW,GAAG,MAAM,IAAI,KAAK,UAAU,EAAE,WAAW,IAAI,IAAA,CAAK;AAAA,EACnF,QAAQ;AAAA,EAER;AACF;AAMO,SAAS,wBAAwB;AAAA,EACtC;AAAA,EACA;AAAA,EACA,MAAM,KAAK,IAAA;AACb,GAImB;AACjB,MAAI,MAAqB;AACzB,MAAI;AACF,WAAM,mCAAS,QAAQ,GAAG,WAAW,GAAG,MAAM,QAAO;AAAA,EACvD,QAAQ;AACN,WAAO;AAAA,EACT;AACA,MAAI,QAAQ,KAAM,QAAO;AACzB,MAAI;AACF,UAAM,OAAO,KAAK,MAAM,GAAG;AAC3B,QAAI,OAAO,KAAK,cAAc,aAAa,OAAO,KAAK,OAAO,SAAU,QAAO;AAC/E,UAAM,MAAM,KAAK,YAAY,gCAAgC;AAC7D,WAAO,MAAM,KAAK,MAAM,MAAM,KAAK,YAAY;AAAA,EACjD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;"}
@@ -99,6 +99,14 @@ class UnconfirmedUpdateAttributions {
99
99
  get pending() {
100
100
  return this.runs.map(copyOf);
101
101
  }
102
+ /**
103
+ * Whether the room keeps a write Keryx has not acknowledged. Such a room's socket must not ask for
104
+ * a diffed initial sync (`./initial-sync.ts`): it tells which kept writes Keryx already holds from
105
+ * the whole document Keryx sends when the socket opens, and a diff leaves out what it holds.
106
+ */
107
+ get keepsWrites() {
108
+ return this.runs.length > 0;
109
+ }
102
110
  /** Writes an earlier session kept, older than any written here: they go out first. */
103
111
  restore(writes) {
104
112
  this.runs = bounded([...writes.map(copyOf), ...this.runs]);