@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.
- package/README.md +24 -1
- package/dist/agent-runtime/src/call-recap.cjs +2 -3
- package/dist/agent-runtime/src/call-recap.cjs.map +1 -1
- package/dist/agent-runtime/src/call-recap.d.ts +1 -2
- package/dist/agent-runtime/src/call-recap.js +1 -2
- package/dist/agent-runtime/src/call-recap.js.map +1 -1
- package/dist/agent-runtime/src/deep-agent-transport-recipe.cjs +7 -3
- package/dist/agent-runtime/src/deep-agent-transport-recipe.cjs.map +1 -1
- package/dist/agent-runtime/src/deep-agent-transport-recipe.d.ts +10 -2
- package/dist/agent-runtime/src/deep-agent-transport-recipe.js +8 -4
- package/dist/agent-runtime/src/deep-agent-transport-recipe.js.map +1 -1
- package/dist/agent-runtime/src/desktop-handoff.d.ts +7 -0
- package/dist/agent-runtime/src/dictation-session.d.ts +158 -0
- package/dist/agent-runtime/src/edit-command.cjs +6 -0
- package/dist/agent-runtime/src/edit-command.cjs.map +1 -1
- package/dist/agent-runtime/src/edit-command.d.ts +8 -0
- package/dist/agent-runtime/src/edit-command.js +6 -0
- package/dist/agent-runtime/src/edit-command.js.map +1 -1
- package/dist/agent-runtime/src/generated/runconfig-contract.cjs +6 -0
- package/dist/agent-runtime/src/generated/runconfig-contract.cjs.map +1 -1
- package/dist/agent-runtime/src/generated/runconfig-contract.d.ts +13 -0
- package/dist/agent-runtime/src/generated/runconfig-contract.js +6 -0
- package/dist/agent-runtime/src/generated/runconfig-contract.js.map +1 -1
- package/dist/agent-runtime/src/index.d.ts +6 -6
- package/dist/agent-runtime/src/message-window.cjs +111 -7
- package/dist/agent-runtime/src/message-window.cjs.map +1 -1
- package/dist/agent-runtime/src/message-window.d.ts +66 -6
- package/dist/agent-runtime/src/message-window.js +112 -8
- package/dist/agent-runtime/src/message-window.js.map +1 -1
- package/dist/agent-runtime/src/offline-status.cjs.map +1 -1
- package/dist/agent-runtime/src/offline-status.d.ts +33 -0
- package/dist/agent-runtime/src/offline-status.js.map +1 -1
- package/dist/agent-runtime/src/runtime.d.ts +4 -3
- package/dist/agent-runtime/src/subagent-transcripts.cjs +23 -1
- package/dist/agent-runtime/src/subagent-transcripts.cjs.map +1 -1
- package/dist/agent-runtime/src/subagent-transcripts.js +25 -3
- package/dist/agent-runtime/src/subagent-transcripts.js.map +1 -1
- package/dist/agent-runtime/src/subagents.cjs +112 -0
- package/dist/agent-runtime/src/subagents.cjs.map +1 -1
- package/dist/agent-runtime/src/subagents.d.ts +103 -0
- package/dist/agent-runtime/src/subagents.js +113 -1
- package/dist/agent-runtime/src/subagents.js.map +1 -1
- package/dist/agent-runtime/src/thread-handoff-protocol.d.ts +37 -9
- package/dist/agent-runtime/src/thread-handoff.d.ts +1 -1
- package/dist/agent-runtime/src/tool-metadata.cjs +8 -0
- package/dist/agent-runtime/src/tool-metadata.cjs.map +1 -1
- package/dist/agent-runtime/src/tool-metadata.js +8 -0
- package/dist/agent-runtime/src/tool-metadata.js.map +1 -1
- package/dist/agent-runtime/src/use-deep-agent-thread.cjs +6 -0
- package/dist/agent-runtime/src/use-deep-agent-thread.cjs.map +1 -1
- package/dist/agent-runtime/src/use-deep-agent-thread.js +7 -1
- package/dist/agent-runtime/src/use-deep-agent-thread.js.map +1 -1
- package/dist/agent-runtime/src/use-deep-agent-window-sync.cjs +39 -10
- package/dist/agent-runtime/src/use-deep-agent-window-sync.cjs.map +1 -1
- package/dist/agent-runtime/src/use-deep-agent-window-sync.d.ts +14 -4
- package/dist/agent-runtime/src/use-deep-agent-window-sync.js +41 -12
- package/dist/agent-runtime/src/use-deep-agent-window-sync.js.map +1 -1
- package/dist/agent-runtime/src/use-thread-handoff-flow.d.ts +5 -9
- package/dist/agent-runtime/src/voice-presentation.cjs +34 -0
- package/dist/agent-runtime/src/voice-presentation.cjs.map +1 -1
- package/dist/agent-runtime/src/voice-presentation.d.ts +35 -0
- package/dist/agent-runtime/src/voice-presentation.js +34 -0
- package/dist/agent-runtime/src/voice-presentation.js.map +1 -1
- package/dist/assets/AthenaAssetEmbed.cjs +4 -2
- package/dist/assets/AthenaAssetEmbed.cjs.map +1 -1
- package/dist/assets/AthenaAssetEmbed.d.ts +17 -8
- package/dist/assets/AthenaAssetEmbed.js +4 -2
- package/dist/assets/AthenaAssetEmbed.js.map +1 -1
- package/dist/assets/use-asset-embed.cjs.map +1 -1
- package/dist/assets/use-asset-embed.d.ts +7 -5
- package/dist/assets/use-asset-embed.js.map +1 -1
- package/dist/auth/account-identity.cjs +69 -0
- package/dist/auth/account-identity.cjs.map +1 -0
- package/dist/auth/account-identity.d.ts +57 -0
- package/dist/auth/account-identity.js +69 -0
- package/dist/auth/account-identity.js.map +1 -0
- package/dist/chat/AthenaChat.cjs +1 -1
- package/dist/chat/AthenaChat.cjs.map +1 -1
- package/dist/chat/AthenaChat.js +1 -1
- package/dist/chat/AthenaChat.js.map +1 -1
- package/dist/chat/super-grouping/toolkit-map.cjs +1 -0
- package/dist/chat/super-grouping/toolkit-map.cjs.map +1 -1
- package/dist/chat/super-grouping/toolkit-map.js +1 -0
- package/dist/chat/super-grouping/toolkit-map.js.map +1 -1
- package/dist/chat/use-statewire-approval-request.cjs +5 -5
- package/dist/chat/use-statewire-approval-request.cjs.map +1 -1
- package/dist/chat/use-statewire-approval-request.d.ts +7 -0
- package/dist/chat/use-statewire-approval-request.js +5 -5
- package/dist/chat/use-statewire-approval-request.js.map +1 -1
- package/dist/chat-ui/mentions/use-account-workspace-id.cjs +18 -58
- package/dist/chat-ui/mentions/use-account-workspace-id.cjs.map +1 -1
- package/dist/chat-ui/mentions/use-account-workspace-id.js +18 -58
- package/dist/chat-ui/mentions/use-account-workspace-id.js.map +1 -1
- package/dist/chat-ui/messages/voice-delegation-card.cjs +93 -25
- package/dist/chat-ui/messages/voice-delegation-card.cjs.map +1 -1
- package/dist/chat-ui/messages/voice-delegation-card.d.ts +16 -7
- package/dist/chat-ui/messages/voice-delegation-card.js +95 -27
- package/dist/chat-ui/messages/voice-delegation-card.js.map +1 -1
- package/dist/chat-ui/thread/handoff-cursor.cjs +30 -5
- package/dist/chat-ui/thread/handoff-cursor.cjs.map +1 -1
- package/dist/chat-ui/thread/handoff-cursor.d.ts +13 -5
- package/dist/chat-ui/thread/handoff-cursor.js +32 -7
- package/dist/chat-ui/thread/handoff-cursor.js.map +1 -1
- package/dist/collab/client.cjs +94 -6
- package/dist/collab/client.cjs.map +1 -1
- package/dist/collab/client.d.ts +27 -0
- package/dist/collab/client.js +94 -6
- package/dist/collab/client.js.map +1 -1
- package/dist/collab/index.d.ts +1 -1
- package/dist/keryx-http/src/initial-sync.cjs +121 -0
- package/dist/keryx-http/src/initial-sync.cjs.map +1 -0
- package/dist/keryx-http/src/initial-sync.d.ts +77 -0
- package/dist/keryx-http/src/initial-sync.js +104 -0
- package/dist/keryx-http/src/initial-sync.js.map +1 -0
- package/dist/keryx-http/src/unconfirmed-update-attributions.cjs +8 -0
- package/dist/keryx-http/src/unconfirmed-update-attributions.cjs.map +1 -1
- package/dist/keryx-http/src/unconfirmed-update-attributions.d.ts +6 -0
- package/dist/keryx-http/src/unconfirmed-update-attributions.js +8 -0
- package/dist/keryx-http/src/unconfirmed-update-attributions.js.map +1 -1
- package/dist/react/package.json.cjs +1 -1
- package/dist/react/package.json.js +1 -1
- package/dist/styles.css +1 -1
- package/dist/threads/api.cjs +1 -2
- package/dist/threads/api.cjs.map +1 -1
- package/dist/threads/api.d.ts +3 -2
- package/dist/threads/api.js +1 -2
- package/dist/threads/api.js.map +1 -1
- package/dist/threads/statewire-thread-list.cjs +5 -7
- package/dist/threads/statewire-thread-list.cjs.map +1 -1
- package/dist/threads/statewire-thread-list.js +7 -9
- package/dist/threads/statewire-thread-list.js.map +1 -1
- package/dist/tools/subagent-task-tool-ui.cjs +15 -5
- package/dist/tools/subagent-task-tool-ui.cjs.map +1 -1
- package/dist/tools/subagent-task-tool-ui.d.ts +5 -4
- package/dist/tools/subagent-task-tool-ui.js +16 -6
- package/dist/tools/subagent-task-tool-ui.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.cjs","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":["CollabTokenError","mint","mintCollabToken","receiveOnlyWebSocket","attributingWebSocket","docUpdateAttributions","Y","UnconfirmedUpdateAttributions","WebsocketProvider","documentStatus","watchDocumentStatus","refreshDelayMs","MIN_REFRESH_DELAY_MS","classifyClose","MAX_CONSECUTIVE_REMINTS"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiNO,MAAM,gCAAgC;AAG7C,MAAM,uBAAuB,CAAC,KAAO,KAAO,KAAO,KAAO,MAAQ,KAAQ,GAAM;AAMzE,SAAS,qBAAqB,OAAyB;AAC5D,MAAI,iBAAiBA,KAAAA,kBAAkB;AACrC,WAAO,MAAM,UAAU,OAAO,MAAM,WAAW,OAAO,MAAM,WAAW;AAAA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A;AAAA,IACN;AAAA,EAAA;AAEJ;;;;;"}
|
|
1
|
+
{"version":3,"file":"client.cjs","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":["CollabTokenError","mint","mintCollabToken","receiveOnlyWebSocket","attributingWebSocket","docUpdateAttributions","Y","UnconfirmedUpdateAttributions","WebsocketProvider","documentStatus","watchDocumentStatus","refreshDelayMs","MIN_REFRESH_DELAY_MS","keryxRoomReadUrl","INITIAL_SYNC_PARAM","INITIAL_SYNC_DIFF","classifyClose","MAX_CONSECUTIVE_REMINTS","keryxOriginOf","knownInitialSyncSupport","readRoomOverHttp","rememberInitialSyncSupport"],"mappings":";;;;;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C;AACrC;AAAA,MACF;AACA,mDAAW,4BAAX,mCAAqC;AACrC,aAAO;AACP,kBAAY;AACZ,gBAAU,YAAY;AACtB,WAAK,QAAA;AAAA,IACP;AAAA,IACA,QAAQ,MAAM;AACZ,UAAI,CAAC,QAAQ,aAAa,CAAC,kBAAmB;AAC9C,aAAO;AACP,YAAM,QAAQ;AACd,kBAAY;AACZ,aAAA;AACA,WAAK,QAAQ,EAAE,UAAU,MAAM,OAAO,SAAS,QAAW;AAAA,IAC5D;AAAA,IACA;AAAA,IACA,UAAU,CAAC,aAAa;AACtB,gBAAU,IAAI,QAAQ;AACtB,aAAO,MAAM;AACX,kBAAU,OAAO,QAAQ;AAAA,MAC3B;AAAA,IACF;AAAA,IACA,SAAS,MAAM;AACb,UAAI,UAAW;AACf,kBAAY;AACZA,2DAAgB;AAChB,uBAAA;AACA,sBAAA;AACA,wBAAA;AACA,UAAI,OAAO,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;;;;;"}
|
package/dist/collab/client.d.ts
CHANGED
|
@@ -187,6 +187,22 @@ export declare const DEFAULT_OFFLINE_GATE_AFTER_MS = 15000;
|
|
|
187
187
|
* worth retrying; a refusal (401/403/404) is the server's verdict and ends the handle.
|
|
188
188
|
*/
|
|
189
189
|
export declare function isRetryableMintError(error: unknown): boolean;
|
|
190
|
+
/** How an HTTP-first read went (`connectGenericDoc`'s `httpFirstOpen`). */
|
|
191
|
+
export interface GenericDocHttpFirstOpenEvent {
|
|
192
|
+
/**
|
|
193
|
+
* `read`: read over HTTP and applied; the socket asks for the diff. `unsupported`: Keryx answered
|
|
194
|
+
* without saying it answers a socket's sync step 1; its document was not used. `failed`: the read
|
|
195
|
+
* failed (`error` says why). `skipped`: Keryx is known not to answer, so nothing was read.
|
|
196
|
+
* `aborted`: the room replaced or closed the provider during the read, which it stopped.
|
|
197
|
+
*/
|
|
198
|
+
outcome: 'read' | 'unsupported' | 'failed' | 'skipped' | 'aborted';
|
|
199
|
+
/** The decoded body's size (`read`, `unsupported`). */
|
|
200
|
+
bytes?: number;
|
|
201
|
+
/** From the request to the socket's connect. */
|
|
202
|
+
durationMs: number;
|
|
203
|
+
/** Why the read failed (`failed`): the error's name and message. */
|
|
204
|
+
error?: string;
|
|
205
|
+
}
|
|
190
206
|
export declare function connectGenericDoc(args: {
|
|
191
207
|
assetId: string;
|
|
192
208
|
/** Credentials for the default mint; not used when `mint` is given. */
|
|
@@ -206,6 +222,17 @@ export declare function connectGenericDoc(args: {
|
|
|
206
222
|
* `handle.writesRefused`. A host that cannot read it leaves it out.
|
|
207
223
|
*/
|
|
208
224
|
readDocumentStatus?: ReadDocumentStatus;
|
|
225
|
+
/**
|
|
226
|
+
* Open the room HTTP-first (Word at scale), as Olympus opens a Word room: a document that holds
|
|
227
|
+
* nothing yet is read over `GET /ydoc` (compressed, decoded as it downloads), applied as Keryx's
|
|
228
|
+
* own state, and the socket asks Keryx for only what it still lacks (`?initialSync=diff`) - when
|
|
229
|
+
* Keryx says it answers that way (`@athenaintel/keryx-http/initial-sync`). Every later socket of
|
|
230
|
+
* the room asks for the diff too while Keryx is known to answer and the room holds no write Keryx
|
|
231
|
+
* has not echoed. For rooms whose documents can be large (Word documents).
|
|
232
|
+
*/
|
|
233
|
+
httpFirstOpen?: boolean;
|
|
234
|
+
/** Hears how each HTTP-first read went (`httpFirstOpen`), for the host's telemetry. */
|
|
235
|
+
onHttpFirstOpen?: (event: GenericDocHttpFirstOpenEvent) => void;
|
|
209
236
|
}): GenericDocHandle;
|
|
210
237
|
export { CollabTokenError };
|
|
211
238
|
export type { CollabAuth, CollabTokenResponse };
|
package/dist/collab/client.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { keryxRoomReadUrl, INITIAL_SYNC_DIFF, INITIAL_SYNC_PARAM, keryxOriginOf, knownInitialSyncSupport, readRoomOverHttp, rememberInitialSyncSupport } from "../keryx-http/src/initial-sync.js";
|
|
1
2
|
import { receiveOnlyWebSocket } from "../keryx-http/src/receive-only-socket.js";
|
|
2
3
|
import { UnconfirmedUpdateAttributions } from "../keryx-http/src/unconfirmed-update-attributions.js";
|
|
3
4
|
import { docUpdateAttributions, attributingWebSocket } from "../keryx-http/src/update-attributions.js";
|
|
@@ -34,6 +35,14 @@ function socketFor({
|
|
|
34
35
|
unconfirmed
|
|
35
36
|
});
|
|
36
37
|
}
|
|
38
|
+
const HTTP_FIRST_READ_TIMEOUT_MS = 6e4;
|
|
39
|
+
function browserStorage() {
|
|
40
|
+
try {
|
|
41
|
+
return typeof window !== "undefined" && window.localStorage ? window.localStorage : null;
|
|
42
|
+
} catch {
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
37
46
|
function connectGenericDoc(args) {
|
|
38
47
|
const access = args.access ?? "view";
|
|
39
48
|
const mint = resolveMint({ auth: args.auth, mint: args.mint });
|
|
@@ -72,6 +81,8 @@ function connectGenericDoc(args) {
|
|
|
72
81
|
let localChangesSynced = true;
|
|
73
82
|
let liveGrant = null;
|
|
74
83
|
let readStatusOnConnect = false;
|
|
84
|
+
let keryxAnswersSyncStep1 = false;
|
|
85
|
+
let httpFirstRead = null;
|
|
75
86
|
const notify = () => {
|
|
76
87
|
version += 1;
|
|
77
88
|
for (const listener of listeners) listener();
|
|
@@ -159,6 +170,10 @@ function connectGenericDoc(args) {
|
|
|
159
170
|
if (provider) {
|
|
160
171
|
const previous = provider;
|
|
161
172
|
provider = null;
|
|
173
|
+
if ((httpFirstRead == null ? void 0 : httpFirstRead.target) === previous) {
|
|
174
|
+
httpFirstRead.controller.abort(new DOMException("The room closed", "AbortError"));
|
|
175
|
+
httpFirstRead = null;
|
|
176
|
+
}
|
|
162
177
|
carriedUpdates = [...carriedUpdates, ...previous.unconfirmedUpdates];
|
|
163
178
|
previous.destroy();
|
|
164
179
|
}
|
|
@@ -191,7 +206,7 @@ function connectGenericDoc(args) {
|
|
|
191
206
|
offlineTimer = setTimeout(() => {
|
|
192
207
|
offlineTimer = null;
|
|
193
208
|
if (destroyed || !connectionEnabled || status === "connected" || provider === null) return;
|
|
194
|
-
if (provider.wsconnecting && !hasUnsyncedLocalEdits()) {
|
|
209
|
+
if ((provider.wsconnecting || (httpFirstRead == null ? void 0 : httpFirstRead.target) === provider) && !hasUnsyncedLocalEdits()) {
|
|
195
210
|
openingPastThreshold = provider;
|
|
196
211
|
armOfflineTakeover();
|
|
197
212
|
return;
|
|
@@ -272,16 +287,23 @@ function connectGenericDoc(args) {
|
|
|
272
287
|
}
|
|
273
288
|
if (destroyed || !connectionEnabled || seq !== connectSeq) return;
|
|
274
289
|
const socket = socketFor({ grant, doc, unconfirmed: unconfirmedAttributions });
|
|
290
|
+
const roomUrl = `${grant.ws_url}/${grant.org}/${grant.doc_id}`;
|
|
291
|
+
const httpFirstUrl = args.httpFirstOpen === true && doc.store.clients.size === 0 && carriedUpdates.length === 0 ? keryxRoomReadUrl({ wsUrl: roomUrl, token: grant.token, branch: grant.branch }) : null;
|
|
292
|
+
const params = {
|
|
293
|
+
yauth: grant.token,
|
|
294
|
+
branch: grant.branch,
|
|
295
|
+
gc: "true"
|
|
296
|
+
};
|
|
297
|
+
if (httpFirstUrl === null && asksForDiffedSync({ roomUrl, unconfirmed: carriedUpdates.length })) {
|
|
298
|
+
params[INITIAL_SYNC_PARAM] = INITIAL_SYNC_DIFF;
|
|
299
|
+
}
|
|
275
300
|
const nextProvider = new WebsocketProvider(grant.ws_url, `${grant.org}/${grant.doc_id}`, doc, {
|
|
276
|
-
params
|
|
277
|
-
yauth: grant.token,
|
|
278
|
-
branch: grant.branch,
|
|
279
|
-
gc: "true"
|
|
280
|
-
},
|
|
301
|
+
params,
|
|
281
302
|
// BroadcastChannel would sync same-origin clients locally, bypassing the
|
|
282
303
|
// server's permission enforcement (a read-only tab could write into an
|
|
283
304
|
// editor tab's doc). Permissioned docs must round-trip the server.
|
|
284
305
|
disableBc: true,
|
|
306
|
+
connect: httpFirstUrl === null,
|
|
285
307
|
...socket && { WebSocketPolyfill: socket }
|
|
286
308
|
});
|
|
287
309
|
provider = nextProvider;
|
|
@@ -323,6 +345,11 @@ function connectGenericDoc(args) {
|
|
|
323
345
|
});
|
|
324
346
|
nextProvider.on("connection-close", (event) => {
|
|
325
347
|
if (provider !== nextProvider) return;
|
|
348
|
+
if (asksForDiffedSync({ roomUrl, unconfirmed: nextProvider.unconfirmedUpdates.length })) {
|
|
349
|
+
nextProvider.params[INITIAL_SYNC_PARAM] = INITIAL_SYNC_DIFF;
|
|
350
|
+
} else {
|
|
351
|
+
delete nextProvider.params[INITIAL_SYNC_PARAM];
|
|
352
|
+
}
|
|
326
353
|
const action = classifyClose(event == null ? void 0 : event.code);
|
|
327
354
|
if (action === "remint") {
|
|
328
355
|
consecutiveRemints += 1;
|
|
@@ -350,7 +377,68 @@ function connectGenericDoc(args) {
|
|
|
350
377
|
notify();
|
|
351
378
|
});
|
|
352
379
|
scheduleRefresh(grant);
|
|
380
|
+
if (httpFirstUrl !== null) void openOverHttp({ target: nextProvider, url: httpFirstUrl, roomUrl });
|
|
353
381
|
};
|
|
382
|
+
function asksForDiffedSync({ roomUrl, unconfirmed }) {
|
|
383
|
+
if (args.httpFirstOpen !== true) return false;
|
|
384
|
+
const origin = keryxOriginOf(roomUrl);
|
|
385
|
+
const known = keryxAnswersSyncStep1 || origin !== null && knownInitialSyncSupport({ storage: browserStorage(), origin }) === true;
|
|
386
|
+
return known && doc.store.clients.size > 0 && unconfirmed === 0 && !unconfirmedAttributions.keepsWrites;
|
|
387
|
+
}
|
|
388
|
+
async function openOverHttp({
|
|
389
|
+
target,
|
|
390
|
+
url,
|
|
391
|
+
roomUrl
|
|
392
|
+
}) {
|
|
393
|
+
var _a;
|
|
394
|
+
const started = performance.now();
|
|
395
|
+
const origin = keryxOriginOf(roomUrl);
|
|
396
|
+
const storage = browserStorage();
|
|
397
|
+
let event;
|
|
398
|
+
if (origin !== null && knownInitialSyncSupport({ storage, origin }) === false) {
|
|
399
|
+
event = { outcome: "skipped", durationMs: 0 };
|
|
400
|
+
} else {
|
|
401
|
+
const controller = new AbortController();
|
|
402
|
+
httpFirstRead = { target, controller };
|
|
403
|
+
const timeout = setTimeout(
|
|
404
|
+
() => controller.abort(new DOMException("The HTTP-first read timed out", "TimeoutError")),
|
|
405
|
+
HTTP_FIRST_READ_TIMEOUT_MS
|
|
406
|
+
);
|
|
407
|
+
try {
|
|
408
|
+
const read = await readRoomOverHttp({ url, signal: controller.signal });
|
|
409
|
+
if (origin !== null) rememberInitialSyncSupport({ storage, origin, supported: read.answersSyncStep1 });
|
|
410
|
+
if (read.answersSyncStep1 && provider === target && !destroyed) {
|
|
411
|
+
if (read.update.byteLength > 2) Y.applyUpdate(doc, read.update, target);
|
|
412
|
+
keryxAnswersSyncStep1 = true;
|
|
413
|
+
}
|
|
414
|
+
event = {
|
|
415
|
+
outcome: read.answersSyncStep1 ? "read" : "unsupported",
|
|
416
|
+
bytes: read.bytes,
|
|
417
|
+
durationMs: performance.now() - started
|
|
418
|
+
};
|
|
419
|
+
} catch (err) {
|
|
420
|
+
event = controller.signal.aborted && (destroyed || provider !== target) ? { outcome: "aborted", durationMs: performance.now() - started } : {
|
|
421
|
+
outcome: "failed",
|
|
422
|
+
durationMs: performance.now() - started,
|
|
423
|
+
error: err instanceof Error ? `${err.name}: ${err.message}` : String(err)
|
|
424
|
+
};
|
|
425
|
+
} finally {
|
|
426
|
+
clearTimeout(timeout);
|
|
427
|
+
if ((httpFirstRead == null ? void 0 : httpFirstRead.controller) === controller) httpFirstRead = null;
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
try {
|
|
431
|
+
(_a = args.onHttpFirstOpen) == null ? void 0 : _a.call(args, event);
|
|
432
|
+
} catch {
|
|
433
|
+
}
|
|
434
|
+
if (destroyed || provider !== target) return;
|
|
435
|
+
if (asksForDiffedSync({ roomUrl, unconfirmed: target.unconfirmedUpdates.length })) {
|
|
436
|
+
target.params[INITIAL_SYNC_PARAM] = INITIAL_SYNC_DIFF;
|
|
437
|
+
} else {
|
|
438
|
+
delete target.params[INITIAL_SYNC_PARAM];
|
|
439
|
+
}
|
|
440
|
+
target.connect();
|
|
441
|
+
}
|
|
354
442
|
const preparing = localCopy ? localCopy.prepare({ doc, transport }).catch(() => ({ unsyncedEdits: null })).then(({ unsyncedEdits }) => {
|
|
355
443
|
if (destroyed) return;
|
|
356
444
|
if (unsyncedEdits && !(unsyncedEdits.inserts.isEmpty() && unsyncedEdits.deletes.isEmpty())) {
|