@athenaintel/react 0.59.0 → 0.60.1
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 +124 -20
- package/dist/agent-runtime/src/client-tool-bridge.cjs +20 -2
- package/dist/agent-runtime/src/client-tool-bridge.cjs.map +1 -1
- package/dist/agent-runtime/src/client-tool-bridge.d.ts +9 -4
- package/dist/agent-runtime/src/client-tool-bridge.js +20 -2
- package/dist/agent-runtime/src/client-tool-bridge.js.map +1 -1
- package/dist/agent-runtime/src/client-tools.cjs.map +1 -1
- package/dist/agent-runtime/src/client-tools.d.ts +9 -0
- package/dist/agent-runtime/src/client-tools.js.map +1 -1
- package/dist/agent-runtime/src/composer-markdown.cjs +0 -16
- package/dist/agent-runtime/src/composer-markdown.cjs.map +1 -1
- package/dist/agent-runtime/src/composer-markdown.js +1 -17
- package/dist/agent-runtime/src/composer-markdown.js.map +1 -1
- package/dist/agent-runtime/src/named-agents.js +1 -1
- package/dist/agent-runtime/src/offline-status.cjs.map +1 -1
- package/dist/agent-runtime/src/offline-status.d.ts +27 -0
- package/dist/agent-runtime/src/offline-status.js.map +1 -1
- package/dist/agent-runtime/src/tool-metadata.cjs +7 -0
- package/dist/agent-runtime/src/tool-metadata.cjs.map +1 -1
- package/dist/agent-runtime/src/tool-metadata.js +7 -0
- package/dist/agent-runtime/src/tool-metadata.js.map +1 -1
- package/dist/chat/AthenaChat.cjs +17 -5
- package/dist/chat/AthenaChat.cjs.map +1 -1
- package/dist/chat/AthenaChat.js +18 -6
- package/dist/chat/AthenaChat.js.map +1 -1
- package/dist/chat/StatewireClientToolBridge.cjs +69 -1
- package/dist/chat/StatewireClientToolBridge.cjs.map +1 -1
- package/dist/chat/StatewireClientToolBridge.d.ts +14 -1
- package/dist/chat/StatewireClientToolBridge.js +70 -2
- package/dist/chat/StatewireClientToolBridge.js.map +1 -1
- package/dist/chat/StatewireClientToolConsentCard.cjs +65 -0
- package/dist/chat/StatewireClientToolConsentCard.cjs.map +1 -0
- package/dist/chat/StatewireClientToolConsentCard.d.ts +24 -0
- package/dist/chat/StatewireClientToolConsentCard.js +65 -0
- package/dist/chat/StatewireClientToolConsentCard.js.map +1 -0
- package/dist/chat/client-tool-write-consent.cjs +111 -0
- package/dist/chat/client-tool-write-consent.cjs.map +1 -0
- package/dist/chat/client-tool-write-consent.d.ts +71 -0
- package/dist/chat/client-tool-write-consent.js +111 -0
- package/dist/chat/client-tool-write-consent.js.map +1 -0
- package/dist/chat/statewire-client-tools.cjs +30 -5
- package/dist/chat/statewire-client-tools.cjs.map +1 -1
- package/dist/chat/statewire-client-tools.d.ts +34 -2
- package/dist/chat/statewire-client-tools.js +30 -5
- package/dist/chat/statewire-client-tools.js.map +1 -1
- package/dist/chat-ui/index.cjs +2 -0
- package/dist/chat-ui/index.cjs.map +1 -1
- package/dist/chat-ui/index.d.ts +1 -0
- package/dist/chat-ui/index.js +2 -0
- package/dist/chat-ui/index.js.map +1 -1
- package/dist/chat-ui/mentions/mention-chip.cjs +9 -3
- package/dist/chat-ui/mentions/mention-chip.cjs.map +1 -1
- package/dist/chat-ui/mentions/mention-chip.js +9 -3
- package/dist/chat-ui/mentions/mention-chip.js.map +1 -1
- package/dist/chat-ui/mentions/suggestions/components/mention-icon.cjs +18 -2
- package/dist/chat-ui/mentions/suggestions/components/mention-icon.cjs.map +1 -1
- package/dist/chat-ui/mentions/suggestions/components/mention-icon.d.ts +10 -1
- package/dist/chat-ui/mentions/suggestions/components/mention-icon.js +19 -3
- package/dist/chat-ui/mentions/suggestions/components/mention-icon.js.map +1 -1
- package/dist/chat-ui/mentions/suggestions/data/api-client.cjs +9 -0
- package/dist/chat-ui/mentions/suggestions/data/api-client.cjs.map +1 -1
- package/dist/chat-ui/mentions/suggestions/data/api-client.d.ts +6 -0
- package/dist/chat-ui/mentions/suggestions/data/api-client.js +9 -0
- package/dist/chat-ui/mentions/suggestions/data/api-client.js.map +1 -1
- package/dist/chat-ui/mentions/suggestions/data/sources/asset-type-icon-names.generated.cjs +89 -0
- package/dist/chat-ui/mentions/suggestions/data/sources/asset-type-icon-names.generated.cjs.map +1 -0
- package/dist/chat-ui/mentions/suggestions/data/sources/asset-type-icon-names.generated.d.ts +8 -0
- package/dist/chat-ui/mentions/suggestions/data/sources/asset-type-icon-names.generated.js +89 -0
- package/dist/chat-ui/mentions/suggestions/data/sources/asset-type-icon-names.generated.js.map +1 -0
- package/dist/chat-ui/mentions/suggestions/data/sources/asset-type-icons.cjs +153 -116
- package/dist/chat-ui/mentions/suggestions/data/sources/asset-type-icons.cjs.map +1 -1
- package/dist/chat-ui/mentions/suggestions/data/sources/asset-type-icons.d.ts +58 -12
- package/dist/chat-ui/mentions/suggestions/data/sources/asset-type-icons.js +154 -117
- package/dist/chat-ui/mentions/suggestions/data/sources/asset-type-icons.js.map +1 -1
- package/dist/chat-ui/mentions/suggestions/data/sources/index.cjs +38 -6
- package/dist/chat-ui/mentions/suggestions/data/sources/index.cjs.map +1 -1
- package/dist/chat-ui/mentions/suggestions/data/sources/index.js +40 -8
- package/dist/chat-ui/mentions/suggestions/data/sources/index.js.map +1 -1
- package/dist/chat-ui/mentions/use-asset-icon-app-url.cjs +13 -0
- package/dist/chat-ui/mentions/use-asset-icon-app-url.cjs.map +1 -0
- package/dist/chat-ui/mentions/use-asset-icon-app-url.d.ts +9 -0
- package/dist/chat-ui/mentions/use-asset-icon-app-url.js +13 -0
- package/dist/chat-ui/mentions/use-asset-icon-app-url.js.map +1 -0
- package/dist/chat-ui/statewire.cjs +4 -0
- package/dist/chat-ui/statewire.cjs.map +1 -1
- package/dist/chat-ui/statewire.d.ts +2 -0
- package/dist/chat-ui/statewire.js +4 -0
- package/dist/chat-ui/statewire.js.map +1 -1
- package/dist/collab/client.cjs +24 -1
- package/dist/collab/client.cjs.map +1 -1
- package/dist/collab/client.d.ts +16 -0
- package/dist/collab/client.js +24 -1
- package/dist/collab/client.js.map +1 -1
- package/dist/composer/attached-references.js +1 -1
- package/dist/composer/staged-message-metadata.cjs +12 -0
- package/dist/composer/staged-message-metadata.cjs.map +1 -0
- package/dist/composer/staged-message-metadata.d.ts +15 -0
- package/dist/composer/staged-message-metadata.js +12 -0
- package/dist/composer/staged-message-metadata.js.map +1 -0
- package/dist/data/athena-request.cjs +2 -0
- package/dist/data/athena-request.cjs.map +1 -1
- package/dist/data/athena-request.js +2 -0
- package/dist/data/athena-request.js.map +1 -1
- package/dist/index.cjs +5 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +6 -2
- package/dist/index.js +6 -1
- package/dist/index.js.map +1 -1
- package/dist/provider/AthenaProvider.cjs +26 -6
- package/dist/provider/AthenaProvider.cjs.map +1 -1
- package/dist/provider/AthenaProvider.d.ts +8 -1
- package/dist/provider/AthenaProvider.js +27 -7
- package/dist/provider/AthenaProvider.js.map +1 -1
- package/dist/react/package.json.cjs +1 -1
- package/dist/react/package.json.js +1 -1
- package/dist/references/src/anchors/parse.cjs +11 -1
- package/dist/references/src/anchors/parse.cjs.map +1 -1
- package/dist/references/src/anchors/parse.js +11 -1
- package/dist/references/src/anchors/parse.js.map +1 -1
- package/dist/references/src/anchors/schemas.d.ts +1 -0
- package/dist/references/src/anchors/serialize.cjs +1 -0
- package/dist/references/src/anchors/serialize.cjs.map +1 -1
- package/dist/references/src/anchors/serialize.js +1 -0
- package/dist/references/src/anchors/serialize.js.map +1 -1
- package/dist/references/src/anchors/types.cjs.map +1 -1
- package/dist/references/src/anchors/types.d.ts +9 -0
- package/dist/references/src/anchors/types.js.map +1 -1
- package/dist/references/src/schemas.d.ts +2 -0
- package/dist/runtime/useAthenaStatewireRuntime.cjs +6 -8
- package/dist/runtime/useAthenaStatewireRuntime.cjs.map +1 -1
- package/dist/runtime/useAthenaStatewireRuntime.js +6 -8
- package/dist/runtime/useAthenaStatewireRuntime.js.map +1 -1
- package/dist/threads/statewire-thread-list.cjs +14 -2
- package/dist/threads/statewire-thread-list.cjs.map +1 -1
- package/dist/threads/statewire-thread-list.d.ts +11 -2
- package/dist/threads/statewire-thread-list.js +14 -2
- package/dist/threads/statewire-thread-list.js.map +1 -1
- package/dist/tools/drive-tool-uis.cjs +8 -4
- package/dist/tools/drive-tool-uis.cjs.map +1 -1
- package/dist/tools/drive-tool-uis.d.ts +5 -4
- package/dist/tools/drive-tool-uis.js +9 -5
- package/dist/tools/drive-tool-uis.js.map +1 -1
- package/dist/version.cjs +4 -0
- package/dist/version.cjs.map +1 -1
- package/dist/version.d.ts +9 -0
- package/dist/version.js +4 -0
- package/dist/version.js.map +1 -1
- package/dist/workbench/live-desktop-api.cjs +2 -1
- package/dist/workbench/live-desktop-api.cjs.map +1 -1
- package/dist/workbench/live-desktop-api.js +2 -1
- package/dist/workbench/live-desktop-api.js.map +1 -1
- package/dist/workbench/session-workspace-api.cjs +7 -2
- package/dist/workbench/session-workspace-api.cjs.map +1 -1
- package/dist/workbench/session-workspace-api.d.ts +10 -0
- package/dist/workbench/session-workspace-api.js +7 -2
- package/dist/workbench/session-workspace-api.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sources":["../../src/collab/client.ts"],"sourcesContent":["/**\n * Vanilla (framework-agnostic) live client for Generic Doc assets.\n *\n * `connectGenericDoc` owns the full connection lifecycle: mint a room-bound\n * token via the public API, open the Keryx WebSocket with the v14 provider\n * (`@y/websocket` + `@y/y`), re-mint before expiry, apply the close-code\n * policy (4401 → one fresh mint, other 44xx → permanent stop, everything\n * else → provider backoff), and expose presence from awareness. React apps\n * use `useGenericDoc` from `@athenaintel/react/collab` instead of calling\n * this directly.\n *\n * A host that keeps a local copy of the document (`localCopy`) gets it applied\n * before the first connection, keeps its unacknowledged edits waiting across\n * sessions, and can hold a connection that would send edits made without one\n * until it has checked them against the server (`beforeConnect`). Offline, a\n * mint that fails for want of the network is retried (`retryMintError`)\n * instead of ending the handle, and past `offlineGateAfterMs` without a socket\n * the handle reconnects itself, re-minting each time, so every reconnect after\n * a real outage re-checks access and passes the host's gate.\n *\n * A write the host makes on its own (an editor's housekeeping, a restored value)\n * goes out as housekeeping when it is made inside `runWithDocUpdateAttributions`\n * for `handle.doc` with `BACKGROUND_UPDATE_ATTRIBUTIONS`: the socket appends the\n * scope's attributions to the update, which Keryx counts as system work instead\n * of the person's edit (`socketFor`). One made while no socket is open is kept\n * until Keryx acknowledges it and sent the same way, ahead of the next\n * connection's sync (`UnconfirmedUpdateAttributions`). On a read-only grant\n * nothing that carries document content leaves the socket.\n *\n * The socket sends the handle's own presence and never a collaborator's\n * (`publishOwnAwarenessOnly`): Keryx already holds and relays every other\n * client's entry, and drops a re-sent agent slot or departure.\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 type DiffedInitialSync,\n HTTP_FIRST_READ_IDLE_TIMEOUT_MS,\n HTTP_FIRST_READ_TIMEOUT_MS,\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 { publishOwnAwarenessOnly } from '@athenaintel/keryx-http/own-awareness';\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 * Asks for a grant now, reconnecting only when it edits: the host has reason to think the person\n * may edit again (their access rose while the document was open). A live socket hears of a\n * widening itself: Keryx closes a read-only socket of someone Agora lets edit again (4401) and the\n * handle re-mints. This is for what that signal misses: a room held with no socket, or an older\n * Keryx. A grant that edits reconnects the live room with it, or asks the host's\n * `beforeConnect` again for a room it held on a grant that only read; a grant that still only\n * reads changes nothing. One at a time. Resolves `true` when the room was handed a\n * grant that edits (a held room's `beforeConnect` still decides), `false` when the mint failed or\n * was refused, the grant still only reads, or the room is neither live nor held on a grant that\n * only read (a room on its way back mints its own).\n */\n refreshGrant: () => Promise<boolean>;\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 * The connection follows Keryx's re-check of the room's grant (it closed the live socket with\n * 4401: a share narrowed or removed, a quarantine or its release), not an outage: whatever the\n * grant says now changed while the document was connected and open. Absent otherwise.\n */\n accessRechecked?: 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/** `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`). Which later sockets ask\n * for the diff too is `diffedInitialSync`'s choice. A read whose bytes keep coming runs on; one\n * that receives nothing for a minute is given up for the socket's whole-document sync. For rooms\n * whose documents can be large (Word documents, decks).\n */\n httpFirstOpen?: boolean;\n /**\n * With `httpFirstOpen`: which sockets ask for the diff (`DiffedInitialSync`). `every-socket` (the\n * default, a Word document's room): every socket while Keryx is known to answer and the room holds\n * no write Keryx has not echoed. `after-read` (a deck's room): only the socket that follows the\n * room's own read.\n */\n diffedInitialSync?: DiffedInitialSync;\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 /**\n * Keryx's auth re-check closed the socket (4401): the gate asked before the next connection hears\n * that the grant changed while the document was connected (`accessRechecked`), until it answers.\n */\n let accessRecheckPending = 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 ...(accessRecheckPending ? { accessRechecked: true } : {}),\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 accessRecheckPending = false;\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 publishOwnAwarenessOnly({ transport: nextProvider });\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 accessRecheckPending = 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 // The host's gate hears that the grant changed while the document was open: a view-only\n // grant now holds the edits it never sent, in words that don't blame being offline.\n accessRecheckPending = 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. A deck's room\n * (`diffedInitialSync: 'after-read'`) asks only on the socket that follows its own read\n * (`afterRead`).\n */\n function asksForDiffedSync({\n roomUrl,\n unconfirmed,\n afterRead = false,\n }: {\n roomUrl: string;\n unconfirmed: number;\n afterRead?: boolean;\n }): boolean {\n if (args.httpFirstOpen !== true) return false;\n if (args.diffedInitialSync === 'after-read' && !afterRead) 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 // The read landed and the document holds Keryx's state from it: the socket after it may ask\n let applied = false;\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 // A read still downloading runs on (a large deck on a slow link); one that receives nothing\n // for the idle timeout is given up and the socket syncs instead.\n const read = await readRoomOverHttp({\n url,\n signal: controller.signal,\n idleTimeoutMs: HTTP_FIRST_READ_IDLE_TIMEOUT_MS,\n });\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 applied = 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, afterRead: applied })) {\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 /** A grant asked for by `refreshGrant`, while it runs. */\n let grantRefresh: Promise<boolean> | null = null;\n const askForGrant = async (): Promise<boolean> => {\n try {\n const grant = await mint({ assetId: args.assetId, access });\n if (destroyed || !connectionEnabled || grant.access_type !== 'rw') return false;\n if (held) {\n // Held meanwhile on a grant that edits (an overlap to review): the host's decision stands.\n if (heldGrant?.access_type !== 'r') return false;\n held = false;\n heldGrant = null;\n notify();\n void connect({ grant });\n return true;\n }\n if (status !== 'connected') return false;\n if (accessType === 'rw') return true;\n // Keryx reads a socket's grant when it opens: the live room reconnects on the new one.\n void connect({ scheduledRefresh: true, grant });\n return true;\n } catch {\n return false;\n }\n };\n const refreshGrant = (): Promise<boolean> => {\n if (destroyed || !connectionEnabled) return Promise.resolve(false);\n if (grantRefresh) return grantRefresh;\n const heldOnRead = held && heldGrant?.access_type === 'r';\n // A room on its way back mints its own grant; one live on a grant that edits needs none.\n if (!heldOnRead && status !== 'connected') return Promise.resolve(false);\n if (!heldOnRead && accessType === 'rw') return Promise.resolve(true);\n const asked = askForGrant().finally(() => {\n grantRefresh = null;\n });\n grantRefresh = asked;\n return asked;\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 refreshGrant,\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.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;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;AACZ,uDAAgB;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;"}
|
|
1
|
+
{"version":3,"file":"client.js","sources":["../../src/collab/client.ts"],"sourcesContent":["/**\n * Vanilla (framework-agnostic) live client for Generic Doc assets.\n *\n * `connectGenericDoc` owns the full connection lifecycle: mint a room-bound\n * token via the public API, open the Keryx WebSocket with the v14 provider\n * (`@y/websocket` + `@y/y`), re-mint before expiry, apply the close-code\n * policy (4401 → one fresh mint, other 44xx → permanent stop, everything\n * else → provider backoff), and expose presence from awareness. React apps\n * use `useGenericDoc` from `@athenaintel/react/collab` instead of calling\n * this directly.\n *\n * A host that keeps a local copy of the document (`localCopy`) gets it applied\n * before the first connection, keeps its unacknowledged edits waiting across\n * sessions, and can hold a connection that would send edits made without one\n * until it has checked them against the server (`beforeConnect`). Offline, a\n * mint that fails for want of the network is retried (`retryMintError`)\n * instead of ending the handle, and past `offlineGateAfterMs` without a socket\n * the handle reconnects itself, re-minting each time, so every reconnect after\n * a real outage re-checks access and passes the host's gate.\n *\n * A write the host makes on its own (an editor's housekeeping, a restored value)\n * goes out as housekeeping when it is made inside `runWithDocUpdateAttributions`\n * for `handle.doc` with `BACKGROUND_UPDATE_ATTRIBUTIONS`: the socket appends the\n * scope's attributions to the update, which Keryx counts as system work instead\n * of the person's edit (`socketFor`). One made while no socket is open is kept\n * until Keryx acknowledges it and sent the same way, ahead of the next\n * connection's sync (`UnconfirmedUpdateAttributions`). On a read-only grant\n * nothing that carries document content leaves the socket.\n *\n * The socket sends the handle's own presence and never a collaborator's\n * (`publishOwnAwarenessOnly`): Keryx already holds and relays every other\n * client's entry, and drops a re-sent agent slot or departure.\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 type DiffedInitialSync,\n HTTP_FIRST_READ_IDLE_TIMEOUT_MS,\n HTTP_FIRST_READ_TIMEOUT_MS,\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 { publishOwnAwarenessOnly } from '@athenaintel/keryx-http/own-awareness';\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 * Asks for a grant now, reconnecting only when it edits: the host has reason to think the person\n * may edit again (their access rose while the document was open). A live socket hears of a\n * widening itself: Keryx closes a read-only socket of someone Agora lets edit again (4401) and the\n * handle re-mints. This is for what that signal misses: a room held with no socket, or an older\n * Keryx. A grant that edits reconnects the live room with it, or asks the host's\n * `beforeConnect` again for a room it held on a grant that only read; a grant that still only\n * reads changes nothing. One at a time. Resolves `true` when the room was handed a\n * grant that edits (a held room's `beforeConnect` still decides), `false` when the mint failed or\n * was refused, the grant still only reads, or the room is neither live nor held on a grant that\n * only read (a room on its way back mints its own).\n */\n refreshGrant: () => Promise<boolean>;\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 /**\n * The update the room's HTTP-first read applied, handed over once (`keepHttpFirstRead`): the\n * document's whole state as Keryx served it, so an engine that hydrates from the document can take\n * these bytes instead of encoding the document again. `null` without `keepHttpFirstRead`, when the\n * room read nothing that way (a document its local copy filled, a Keryx that does not answer), once\n * taken, and once the document has changed since the read (a peer's edit, a local one, the socket's\n * sync), when the document itself is the only complete source. Optional: a host's own handle (a\n * relayed document, a test's) keeps none.\n */\n takeHttpFirstRead?: () => Uint8Array | null;\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 * The connection follows Keryx's re-check of the room's grant (it closed the live socket with\n * 4401: a share narrowed or removed, a quarantine or its release), not an outage: whatever the\n * grant says now changed while the document was connected and open. Absent otherwise.\n */\n accessRechecked?: 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/** `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`). Which later sockets ask\n * for the diff too is `diffedInitialSync`'s choice. A read whose bytes keep coming runs on; one\n * that receives nothing for a minute is given up for the socket's whole-document sync. For rooms\n * whose documents can be large (Word documents, decks).\n */\n httpFirstOpen?: boolean;\n /**\n * With `httpFirstOpen`: which sockets ask for the diff (`DiffedInitialSync`). `every-socket` (the\n * default, a Word document's room): every socket while Keryx is known to answer and the room holds\n * no write Keryx has not echoed. `after-read` (a deck's room): only the socket that follows the\n * room's own read.\n */\n diffedInitialSync?: DiffedInitialSync;\n /** Hears how each HTTP-first read went (`httpFirstOpen`), for the host's telemetry. */\n onHttpFirstOpen?: (event: GenericDocHttpFirstOpenEvent) => void;\n /**\n * With `httpFirstOpen`: keep the update the room's read applied to an empty document until\n * `takeHttpFirstRead()` takes it or the document changes (a workbook's room: the sheet engine\n * hydrates from those bytes instead of a full re-encode of the document).\n */\n keepHttpFirstRead?: boolean;\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 * Keryx's auth re-check closed the socket (4401): the gate asked before the next connection hears\n * that the grant changed while the document was connected (`accessRechecked`), until it answers.\n */\n let accessRecheckPending = 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 /** See `takeHttpFirstRead` (`keepHttpFirstRead`). */\n let keptHttpFirstRead: Uint8Array | null = null;\n /** The read's own update is being applied: the one document change that keeps `keptHttpFirstRead`. */\n let applyingHttpFirstRead = 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 // Any change but the read's own leaves the kept read short of the document's whole state.\n doc.on('update', () => {\n if (!applyingHttpFirstRead) keptHttpFirstRead = null;\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 ...(accessRecheckPending ? { accessRechecked: true } : {}),\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 accessRecheckPending = false;\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 publishOwnAwarenessOnly({ transport: nextProvider });\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 accessRecheckPending = 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 // The host's gate hears that the grant changed while the document was open: a view-only\n // grant now holds the edits it never sent, in words that don't blame being offline.\n accessRecheckPending = 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. A deck's room\n * (`diffedInitialSync: 'after-read'`) asks only on the socket that follows its own read\n * (`afterRead`).\n */\n function asksForDiffedSync({\n roomUrl,\n unconfirmed,\n afterRead = false,\n }: {\n roomUrl: string;\n unconfirmed: number;\n afterRead?: boolean;\n }): boolean {\n if (args.httpFirstOpen !== true) return false;\n if (args.diffedInitialSync === 'after-read' && !afterRead) 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 // The read landed and the document holds Keryx's state from it: the socket after it may ask\n let applied = false;\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 // A read still downloading runs on (a large deck on a slow link); one that receives nothing\n // for the idle timeout is given up and the socket syncs instead.\n const read = await readRoomOverHttp({\n url,\n signal: controller.signal,\n idleTimeoutMs: HTTP_FIRST_READ_IDLE_TIMEOUT_MS,\n });\n if (origin !== null) rememberInitialSyncSupport({ storage, origin, supported: read.answersSyncStep1 });\n if (read.answersSyncStep1 && provider === target && !destroyed) {\n if (read.update.byteLength > 2) applyHttpFirstRead({ update: read.update, target });\n keryxAnswersSyncStep1 = true;\n applied = 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, afterRead: applied })) {\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 /**\n * Applies the read's update as Keryx's own state (the provider's origin). With `keepHttpFirstRead`\n * the update is kept from before the apply, so a listener of the document's `update` event can\n * already take it, and only when the document held nothing: the kept update is then its whole state.\n */\n function applyHttpFirstRead({\n update,\n target,\n }: {\n update: Uint8Array;\n target: WebsocketProvider;\n }): void {\n if (args.keepHttpFirstRead === true && doc.store.clients.size === 0) keptHttpFirstRead = update;\n applyingHttpFirstRead = true;\n try {\n Y.applyUpdate(doc, update, target);\n } finally {\n applyingHttpFirstRead = false;\n }\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 /** A grant asked for by `refreshGrant`, while it runs. */\n let grantRefresh: Promise<boolean> | null = null;\n const askForGrant = async (): Promise<boolean> => {\n try {\n const grant = await mint({ assetId: args.assetId, access });\n if (destroyed || !connectionEnabled || grant.access_type !== 'rw') return false;\n if (held) {\n // Held meanwhile on a grant that edits (an overlap to review): the host's decision stands.\n if (heldGrant?.access_type !== 'r') return false;\n held = false;\n heldGrant = null;\n notify();\n void connect({ grant });\n return true;\n }\n if (status !== 'connected') return false;\n if (accessType === 'rw') return true;\n // Keryx reads a socket's grant when it opens: the live room reconnects on the new one.\n void connect({ scheduledRefresh: true, grant });\n return true;\n } catch {\n return false;\n }\n };\n const refreshGrant = (): Promise<boolean> => {\n if (destroyed || !connectionEnabled) return Promise.resolve(false);\n if (grantRefresh) return grantRefresh;\n const heldOnRead = held && heldGrant?.access_type === 'r';\n // A room on its way back mints its own grant; one live on a grant that edits needs none.\n if (!heldOnRead && status !== 'connected') return Promise.resolve(false);\n if (!heldOnRead && accessType === 'rw') return Promise.resolve(true);\n const asked = askForGrant().finally(() => {\n grantRefresh = null;\n });\n grantRefresh = asked;\n return asked;\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 takeHttpFirstRead: () => {\n const kept = keptHttpFirstRead;\n keptHttpFirstRead = null;\n return kept;\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 refreshGrant,\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 keptHttpFirstRead = null;\n documentStatus?.destroy();\n teardownProvider();\n clearRetryTimer();\n clearOfflineTimer();\n if (typeof window !== 'undefined') window.removeEventListener('online', onBrowserOnline);\n status = 'closed';\n // Final notification so pending waitForSync callers reject instead of\n // hanging on listeners that are about to be dropped.\n for (const listener of [...listeners]) listener();\n listeners.clear();\n unconfirmedAttributions.destroy();\n doc.destroy();\n },\n };\n}\n\nexport { CollabTokenError };\nexport type { CollabAuth, CollabTokenResponse };\n"],"names":[],"mappings":";;;;;;;;;;;AAgQO,MAAM,gCAAgC;AAG7C,MAAM,uBAAuB,CAAC,KAAO,KAAO,KAAO,KAAO,MAAQ,KAAQ,GAAM;AAMzE,SAAS,qBAAqB,OAAyB;AAC5D,MAAI,iBAAiB,kBAAkB;AACrC,WAAO,MAAM,UAAU,OAAO,MAAM,WAAW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AAX,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;AACZ,0BAAoB;AACpB,uDAAgB;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;"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { normalizeAttachableReference, attachableReferenceKey, MAX_ATTACHED_REFERENCES,
|
|
1
|
+
import { normalizeAttachableReference, attachableReferenceKey, MAX_ATTACHED_REFERENCES, withAttachedReferences, readAttachedReferences } from "../references/src/attachable.js";
|
|
2
2
|
import { useCallback, useSyncExternalStore } from "react";
|
|
3
3
|
const EMPTY = Object.freeze([]);
|
|
4
4
|
const pending = /* @__PURE__ */ new Map();
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
3
|
+
const namedAgents = require("../agent-runtime/src/named-agents.cjs");
|
|
4
|
+
const attachedReferences = require("./attached-references.cjs");
|
|
5
|
+
const composerMarkdown = require("../agent-runtime/src/composer-markdown.cjs");
|
|
6
|
+
function takeStagedMessageMetadata(threadId) {
|
|
7
|
+
const metadata = attachedReferences.withStagedAttachedReferences(threadId, namedAgents.stagedNamedAgentsMessageMetadata(threadId));
|
|
8
|
+
const markdown = composerMarkdown.takeStagedComposerMarkdownMetadata(threadId);
|
|
9
|
+
return markdown === void 0 ? metadata : { ...metadata, ...markdown };
|
|
10
|
+
}
|
|
11
|
+
exports.takeStagedMessageMetadata = takeStagedMessageMetadata;
|
|
12
|
+
//# sourceMappingURL=staged-message-metadata.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"staged-message-metadata.cjs","sources":["../../src/composer/staged-message-metadata.ts"],"sourcesContent":["import { takeStagedComposerMarkdownMetadata } from '@athenaintel/agent-runtime';\nimport { stagedNamedAgentsMessageMetadata } from '@athenaintel/agent-runtime/named-agents';\nimport { withStagedAttachedReferences } from './attached-references';\n\n/**\n * The metadata the message `threadId` sends now carries, taking every slot a composer staged for\n * it right before it sent: the agents it names (`addressedAgents`), what an app attached to it\n * (`attachedReferences`) and the draft its text came from (`composer_markdown`). `undefined` when\n * nothing was staged.\n *\n * Two readers, one taking each message's slots once:\n * - the runtime's `getMessageMetadata` (`useAthenaStatewireRuntime`), for a send the composer\n * runtime makes. That option exists only in the monorepo's patch of\n * `@assistant-ui/react-statewire`; the stock package an app installs with the SDK from npm\n * ignores it.\n * - a send that puts the metadata on its message itself (`AthenaChat`'s composed send of a message\n * with attachments), which the stock package forwards as the message's metadata.\n */\nexport function takeStagedMessageMetadata(threadId: string): Record<string, unknown> | undefined {\n const metadata = withStagedAttachedReferences(threadId, stagedNamedAgentsMessageMetadata(threadId));\n const markdown = takeStagedComposerMarkdownMetadata(threadId);\n return markdown === undefined ? metadata : { ...metadata, ...markdown };\n}\n"],"names":["withStagedAttachedReferences","stagedNamedAgentsMessageMetadata","takeStagedComposerMarkdownMetadata"],"mappings":";;;;;AAkBO,SAAS,0BAA0B,UAAuD;AAC/F,QAAM,WAAWA,mBAAAA,6BAA6B,UAAUC,YAAAA,iCAAiC,QAAQ,CAAC;AAClG,QAAM,WAAWC,iBAAAA,mCAAmC,QAAQ;AAC5D,SAAO,aAAa,SAAY,WAAW,EAAE,GAAG,UAAU,GAAG,SAAA;AAC/D;;"}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The metadata the message `threadId` sends now carries, taking every slot a composer staged for
|
|
3
|
+
* it right before it sent: the agents it names (`addressedAgents`), what an app attached to it
|
|
4
|
+
* (`attachedReferences`) and the draft its text came from (`composer_markdown`). `undefined` when
|
|
5
|
+
* nothing was staged.
|
|
6
|
+
*
|
|
7
|
+
* Two readers, one taking each message's slots once:
|
|
8
|
+
* - the runtime's `getMessageMetadata` (`useAthenaStatewireRuntime`), for a send the composer
|
|
9
|
+
* runtime makes. That option exists only in the monorepo's patch of
|
|
10
|
+
* `@assistant-ui/react-statewire`; the stock package an app installs with the SDK from npm
|
|
11
|
+
* ignores it.
|
|
12
|
+
* - a send that puts the metadata on its message itself (`AthenaChat`'s composed send of a message
|
|
13
|
+
* with attachments), which the stock package forwards as the message's metadata.
|
|
14
|
+
*/
|
|
15
|
+
export declare function takeStagedMessageMetadata(threadId: string): Record<string, unknown> | undefined;
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { stagedNamedAgentsMessageMetadata } from "../agent-runtime/src/named-agents.js";
|
|
2
|
+
import { withStagedAttachedReferences } from "./attached-references.js";
|
|
3
|
+
import { takeStagedComposerMarkdownMetadata } from "../agent-runtime/src/composer-markdown.js";
|
|
4
|
+
function takeStagedMessageMetadata(threadId) {
|
|
5
|
+
const metadata = withStagedAttachedReferences(threadId, stagedNamedAgentsMessageMetadata(threadId));
|
|
6
|
+
const markdown = takeStagedComposerMarkdownMetadata(threadId);
|
|
7
|
+
return markdown === void 0 ? metadata : { ...metadata, ...markdown };
|
|
8
|
+
}
|
|
9
|
+
export {
|
|
10
|
+
takeStagedMessageMetadata
|
|
11
|
+
};
|
|
12
|
+
//# sourceMappingURL=staged-message-metadata.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"staged-message-metadata.js","sources":["../../src/composer/staged-message-metadata.ts"],"sourcesContent":["import { takeStagedComposerMarkdownMetadata } from '@athenaintel/agent-runtime';\nimport { stagedNamedAgentsMessageMetadata } from '@athenaintel/agent-runtime/named-agents';\nimport { withStagedAttachedReferences } from './attached-references';\n\n/**\n * The metadata the message `threadId` sends now carries, taking every slot a composer staged for\n * it right before it sent: the agents it names (`addressedAgents`), what an app attached to it\n * (`attachedReferences`) and the draft its text came from (`composer_markdown`). `undefined` when\n * nothing was staged.\n *\n * Two readers, one taking each message's slots once:\n * - the runtime's `getMessageMetadata` (`useAthenaStatewireRuntime`), for a send the composer\n * runtime makes. That option exists only in the monorepo's patch of\n * `@assistant-ui/react-statewire`; the stock package an app installs with the SDK from npm\n * ignores it.\n * - a send that puts the metadata on its message itself (`AthenaChat`'s composed send of a message\n * with attachments), which the stock package forwards as the message's metadata.\n */\nexport function takeStagedMessageMetadata(threadId: string): Record<string, unknown> | undefined {\n const metadata = withStagedAttachedReferences(threadId, stagedNamedAgentsMessageMetadata(threadId));\n const markdown = takeStagedComposerMarkdownMetadata(threadId);\n return markdown === undefined ? metadata : { ...metadata, ...markdown };\n}\n"],"names":[],"mappings":";;;AAkBO,SAAS,0BAA0B,UAAuD;AAC/F,QAAM,WAAW,6BAA6B,UAAU,iCAAiC,QAAQ,CAAC;AAClG,QAAM,WAAW,mCAAmC,QAAQ;AAC5D,SAAO,aAAa,SAAY,WAAW,EAAE,GAAG,UAAU,GAAG,SAAA;AAC/D;"}
|
|
@@ -3,6 +3,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
|
3
3
|
const mint = require("../collab/mint.cjs");
|
|
4
4
|
const credentialRenewal = require("../runtime/credential-renewal.cjs");
|
|
5
5
|
const athenaApiError = require("./athena-api-error.cjs");
|
|
6
|
+
const version = require("../version.cjs");
|
|
6
7
|
const ATHENA_REQUEST_TIMEOUT_MS = 3e4;
|
|
7
8
|
const RATE_LIMIT_MAX_RETRIES = 2;
|
|
8
9
|
const RATE_LIMIT_MAX_WAIT_MS = 3e4;
|
|
@@ -67,6 +68,7 @@ function prepare(config, path, options) {
|
|
|
67
68
|
}
|
|
68
69
|
const headers = {
|
|
69
70
|
Accept: "application/json",
|
|
71
|
+
[version.ATHENA_CLIENT_HEADER]: version.ATHENA_REACT_CLIENT,
|
|
70
72
|
...options.json !== void 0 ? { "Content-Type": "application/json" } : {},
|
|
71
73
|
...options.headers
|
|
72
74
|
};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"athena-request.cjs","sources":["../../src/data/athena-request.ts"],"sourcesContent":["/**\n * The SDK's authenticated transport to agora, without React. Every request:\n *\n * - presents the provider's credential: the live token from `getToken`, renewed\n * once after a 401 (`sendWithCredentialRenewal`, the statewire transport's\n * `staleAuth` contract), else the API key;\n * - goes to the provider's `backendUrl`, and only there: a path must start\n * with `/`;\n * - waits out a 429 as agora's `Retry-After` asks, a bounded number of times;\n * - is abandoned after `timeoutMs`;\n * - fails as an `AthenaApiError`, except a request the caller cancelled, which\n * rejects with the abort's reason as `fetch` does.\n *\n * `useAthenaFetch` binds it to the provider, and the data hooks run on it.\n */\nimport { getAthenaApiBaseUrl } from '../collab/mint';\nimport { sendWithCredentialRenewal } from '../runtime/credential-renewal';\nimport type {\n AthenaStatewireTokenGetter,\n StatewireAuthSource,\n} from '../runtime/statewire-auth-headers';\nimport {\n AthenaApiError,\n AthenaApiErrorKind,\n graphQLErrorCode,\n graphQLErrorEntries,\n isAthenaApiError,\n restErrorDetail,\n} from './athena-api-error';\n\n/** Where a request goes and the credential it presents: the fields of `useAthenaConfig()` it reads. */\nexport interface AthenaRequestConfig {\n /** The Agora API base (`useAthenaConfig().backendUrl`). */\n backendUrl: string;\n apiKey?: string;\n token?: string | null;\n getToken?: AthenaStatewireTokenGetter;\n}\n\nexport type AthenaQueryParamValue = string | number | boolean | null | undefined;\n\n/** Query-string parameters: `null` and `undefined` are left out, an array repeats its key. */\nexport type AthenaQueryParams = Readonly<\n Record<string, AthenaQueryParamValue | readonly (string | number | boolean)[]>\n>;\n\n/** A body the SDK can send again (a 401's renewal and a 429's retry resend it): never a stream. */\nexport type AthenaRequestBody = Exclude<BodyInit, ReadableStream>;\n\n/** How a 429 is waited out. */\nexport interface AthenaRateLimitRetry {\n /** How many times the request is sent again (default 2). */\n maxRetries?: number;\n /**\n * The longest the SDK waits before sending again, in ms (default 30 000).\n * When agora asks for longer, the request fails at once with the 429, whose\n * `retryAfterMs` says when to come back.\n */\n maxWaitMs?: number;\n}\n\nexport interface AthenaRequestOptions {\n /** Default `GET`, or `POST` when the request has a body. */\n method?: string;\n params?: AthenaQueryParams;\n /** A body sent as JSON (`Content-Type: application/json`). Not with `body`. */\n json?: unknown;\n /** A body sent as is (`FormData`, `Blob`, text…). Not with `json`. */\n body?: AthenaRequestBody;\n /**\n * Extra headers. A request presents the provider's credential and no other:\n * `Authorization`, `X-API-KEY`, `Cookie`, `Proxy-Authorization` and\n * `X-Athena-View-As` are refused, in any letter case.\n */\n headers?: Readonly<Record<string, string>>;\n /** Cancels the request (and a wait between its attempts); it then rejects with the abort's reason. */\n signal?: AbortSignal;\n /** How long one attempt may take, in ms (default 30 000); `0` waits as long as it takes. */\n timeoutMs?: number;\n /** How a 429 is waited out; `false` fails at once. */\n rateLimitRetry?: AthenaRateLimitRetry | false;\n}\n\nexport const ATHENA_REQUEST_TIMEOUT_MS = 30_000;\nconst RATE_LIMIT_MAX_RETRIES = 2;\nconst RATE_LIMIT_MAX_WAIT_MS = 30_000;\n/** The first wait for a 429 that says nothing of when to come back; it doubles for each retry. */\nconst RATE_LIMIT_FIRST_BACKOFF_MS = 1_000;\n/** What agora's per-user limiter answers, before it runs anything (`user_request_rate_limit.py`). */\nconst RATE_LIMITED_CODE = 'RATE_LIMITED';\nconst SAFE_METHODS: ReadonlySet<string> = new Set(['GET', 'HEAD', 'OPTIONS']);\n/**\n * Headers that say who a request acts as, or through whose eyes\n * (`X-Athena-View-As`, agora's view-as lens): only the provider sets those.\n */\nconst IDENTITY_HEADERS: ReadonlySet<string> = new Set([\n 'authorization',\n 'proxy-authorization',\n 'cookie',\n 'x-api-key',\n 'x-athena-view-as',\n]);\n\n/** The request as sent: its method, its URL and its path for errors (no query string). */\ninterface PreparedRequest {\n method: string;\n url: string;\n path: string;\n headers: Record<string, string>;\n body: AthenaRequestBody | undefined;\n}\n\nfunction refuse(message: string, method: string, path: string): AthenaApiError {\n return new AthenaApiError({ kind: AthenaApiErrorKind.Request, message, method, path });\n}\n\nfunction prepare(\n config: AthenaRequestConfig,\n path: string,\n options: AthenaRequestOptions,\n): PreparedRequest {\n const hasBody = options.json !== undefined || options.body !== undefined;\n const method = (options.method ?? (hasBody ? 'POST' : 'GET')).toUpperCase();\n const errorPath = path.split('?')[0] ?? path;\n // A path, never a URL: a request carries the person's credential, so it goes\n // to the provider's backend and nowhere else.\n if (!path.startsWith('/') || path.startsWith('//')) {\n throw refuse(\n `A request path must start with a single \"/\" (it goes to the provider's backendUrl): ${JSON.stringify(path)}`,\n method,\n errorPath,\n );\n }\n if (options.json !== undefined && options.body !== undefined) {\n throw refuse('A request takes `json` or `body`, not both', method, errorPath);\n }\n // Header names are case-insensitive: a lowercase `authorization` would be\n // sent beside the provider's and could act as someone else, whose answer the\n // data hooks would then cache under the provider's identity.\n for (const name of Object.keys(options.headers ?? {})) {\n if (IDENTITY_HEADERS.has(name.toLowerCase())) {\n throw refuse(\n `A request may not set ${name}: it presents the provider's credential and no other`,\n method,\n errorPath,\n );\n }\n }\n const base = getAthenaApiBaseUrl(config.backendUrl);\n let url: URL;\n let backendOrigin: string;\n try {\n backendOrigin = new URL(base).origin;\n url = new URL(`${base}${path}`);\n } catch (error) {\n throw new AthenaApiError({\n kind: AthenaApiErrorKind.Request,\n message: `The provider's backendUrl is not a URL: ${JSON.stringify(config.backendUrl)}`,\n method,\n path: errorPath,\n cause: error,\n });\n }\n if (url.origin !== backendOrigin) {\n throw refuse(`A request path must stay on the provider's backendUrl: ${JSON.stringify(path)}`, method, errorPath);\n }\n for (const [name, value] of Object.entries(options.params ?? {})) {\n for (const item of Array.isArray(value) ? value : [value]) {\n if (item !== null && item !== undefined) url.searchParams.append(name, String(item));\n }\n }\n // TODO(#54756): name the app on every call (the provider's `appId`) once agora\n // records it and limits by it.\n const headers: Record<string, string> = {\n Accept: 'application/json',\n ...(options.json !== undefined ? { 'Content-Type': 'application/json' } : {}),\n ...options.headers,\n };\n return {\n method,\n url: url.toString(),\n path: errorPath,\n headers,\n body: options.json !== undefined ? JSON.stringify(options.json) : options.body,\n };\n}\n\n/** The provider's credential; a `getToken` that throws fails the request as `credential`. */\nfunction credentialSource(config: AthenaRequestConfig, request: PreparedRequest): StatewireAuthSource {\n const getToken = config.getToken;\n return {\n apiKey: config.apiKey,\n token: config.token,\n ...(getToken\n ? {\n getToken: async (options?: { force?: boolean }) => {\n try {\n return await getToken(options);\n } catch (error) {\n throw new AthenaApiError({\n kind: AthenaApiErrorKind.Credential,\n message: 'The provider could not resolve a credential for the request',\n method: request.method,\n path: request.path,\n cause: error,\n });\n }\n },\n }\n : {}),\n };\n}\n\n/** One attempt's signal: the caller's cancel, and its own timeout. */\ninterface Attempt {\n signal: AbortSignal;\n timedOut: () => boolean;\n /**\n * Stops the timeout. `keepCancel` leaves the caller's signal able to cancel\n * the body the caller still reads.\n */\n settle: (options?: { keepCancel?: boolean }) => void;\n}\n\nfunction startAttempt(parent: AbortSignal | undefined, timeoutMs: number): Attempt {\n const controller = new AbortController();\n let timedOut = false;\n const forward = () => controller.abort(parent?.reason);\n if (parent?.aborted) controller.abort(parent.reason);\n else parent?.addEventListener('abort', forward, { once: true });\n const timer =\n timeoutMs > 0 && Number.isFinite(timeoutMs)\n ? setTimeout(() => {\n timedOut = true;\n controller.abort(new DOMException(`No answer within ${timeoutMs} ms`, 'TimeoutError'));\n }, timeoutMs)\n : undefined;\n return {\n signal: controller.signal,\n timedOut: () => timedOut,\n settle: ({ keepCancel = false } = {}) => {\n if (timer !== undefined) clearTimeout(timer);\n if (!keepCancel) parent?.removeEventListener('abort', forward);\n },\n };\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason ?? new DOMException('The request was cancelled', 'AbortError');\n}\n\n/** A fetch or a body read that threw: the caller's cancel as is, else a typed failure. */\nfunction failureOf({\n error,\n attempt,\n signal,\n request,\n timeoutMs,\n reading,\n}: {\n error: unknown;\n attempt: Attempt;\n signal: AbortSignal | undefined;\n request: PreparedRequest;\n timeoutMs: number;\n reading: boolean;\n}): unknown {\n if (signal?.aborted) return abortReason(signal);\n if (isAthenaApiError(error)) return error;\n if (attempt.timedOut()) {\n return new AthenaApiError({\n kind: AthenaApiErrorKind.Timeout,\n message: `Athena did not answer within ${timeoutMs} ms`,\n method: request.method,\n path: request.path,\n cause: error,\n });\n }\n return new AthenaApiError({\n kind: reading ? AthenaApiErrorKind.Response : AthenaApiErrorKind.Network,\n message: reading ? 'The answer was cut off before it was read' : 'Athena could not be reached',\n method: request.method,\n path: request.path,\n cause: error,\n });\n}\n\n/**\n * How long agora asked the caller to wait, in ms: the `Retry-After` header\n * (seconds or a date), else the `retryAfterSeconds` of a rate-limit refusal's\n * body. `null` when it said nothing it is possible to read.\n */\nexport function retryAfterMsOf(response: Response, body: unknown, now: number = Date.now()): number | null {\n const header = response.headers.get('retry-after')?.trim();\n if (header) {\n if (/^\\d+$/.test(header)) return Number(header) * 1000;\n const date = Date.parse(header);\n if (Number.isFinite(date)) return Math.max(0, date - now);\n }\n for (const entry of graphQLErrorEntries(body)) {\n const seconds = entry.extensions?.retryAfterSeconds;\n if (typeof seconds === 'number' && Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;\n }\n const seconds = restErrorDetail(body).retryAfterSeconds;\n return seconds !== null && seconds >= 0 ? seconds * 1000 : null;\n}\n\n/** JSON when it reads as JSON, the text otherwise; `undefined` for nothing. */\nfunction lenientBody(text: string): unknown {\n if (text.length === 0) return undefined;\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\n/** How much of an error body that is not JSON (a proxy's error page) an error keeps. */\nconst TEXT_DETAIL_LIMIT = 1_000;\n\n/**\n * The `AthenaApiError` an error status answers, its body read for agora's code\n * and message. A body the attempt's timeout cut off is a timeout (a stalled\n * 5xx must not read as a 5xx, which a read retries), and the caller's cancel\n * stays a cancel; a body that fails otherwise is left out.\n */\nasync function httpError(\n response: Response,\n request: PreparedRequest,\n { signal, attempt, timeoutMs }: { signal: AbortSignal | undefined; attempt: Attempt; timeoutMs: number },\n): Promise<AthenaApiError> {\n let body: unknown;\n try {\n body = lenientBody(await response.text());\n } catch (error) {\n if (signal?.aborted || attempt.timedOut()) {\n throw failureOf({ error, attempt, signal, request, timeoutMs, reading: true });\n }\n body = undefined;\n }\n const statusLine = response.statusText\n ? `${response.status} ${response.statusText}`\n : `HTTP ${response.status}`;\n const common = {\n kind: AthenaApiErrorKind.Http,\n status: response.status,\n retryAfterMs: retryAfterMsOf(response, body),\n method: request.method,\n path: request.path,\n };\n // Not JSON: a gateway's or proxy's page, never agora's words.\n if (typeof body === 'string') {\n return new AthenaApiError({ ...common, message: statusLine, detail: body.slice(0, TEXT_DETAIL_LIMIT) });\n }\n const errors = graphQLErrorEntries(body);\n const rest = restErrorDetail(body);\n return new AthenaApiError({\n ...common,\n code: graphQLErrorCode(errors[0]) ?? rest.code,\n message: errors[0]?.message ?? rest.message ?? statusLine,\n errors,\n detail: errors.length > 0 ? undefined : rest.detail,\n });\n}\n\n/**\n * How long to wait before sending a refused request again, or `null` to fail\n * now. A write goes again only when agora's limiter refused it: that refusal\n * comes before anything runs, so the write cannot apply twice.\n */\nfunction rateLimitWaitMs({\n error,\n retry,\n method,\n policy,\n}: {\n error: AthenaApiError;\n retry: number;\n method: string;\n policy: AthenaRateLimitRetry | false | undefined;\n}): number | null {\n if (policy === false) return null;\n if (retry >= (policy?.maxRetries ?? RATE_LIMIT_MAX_RETRIES)) return null;\n if (!SAFE_METHODS.has(method) && error.code !== RATE_LIMITED_CODE) return null;\n const waitMs =\n error.retryAfterMs ?? RATE_LIMIT_FIRST_BACKOFF_MS * 2 ** retry * (0.8 + Math.random() * 0.4);\n return waitMs <= (policy?.maxWaitMs ?? RATE_LIMIT_MAX_WAIT_MS) ? waitMs : null;\n}\n\nfunction sleep(ms: number, signal: AbortSignal | undefined): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(abortReason(signal));\n return;\n }\n let timer: ReturnType<typeof setTimeout> | undefined;\n const onAbort = () => {\n clearTimeout(timer);\n if (signal) reject(abortReason(signal));\n };\n timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\n/**\n * Send until agora answers with something other than a 429 the SDK waits out.\n * Answers that response (any status) with the attempt that got it, whose\n * timeout still runs: the caller settles it once the body is read.\n */\nasync function exchange(\n config: AthenaRequestConfig,\n request: PreparedRequest,\n options: AthenaRequestOptions,\n): Promise<{ response: Response; attempt: Attempt; timeoutMs: number }> {\n const timeoutMs = options.timeoutMs ?? ATHENA_REQUEST_TIMEOUT_MS;\n const source = credentialSource(config, request);\n for (let retry = 0; ; retry += 1) {\n const attempt = startAttempt(options.signal, timeoutMs);\n let response: Response;\n try {\n response = await sendWithCredentialRenewal(source, (credentialHeaders) =>\n fetch(request.url, {\n method: request.method,\n headers: { ...request.headers, ...credentialHeaders },\n body: request.body ?? null,\n signal: attempt.signal,\n }),\n );\n } catch (error) {\n attempt.settle();\n throw failureOf({ error, attempt, signal: options.signal, request, timeoutMs, reading: false });\n }\n if (response.status !== 429) return { response, attempt, timeoutMs };\n let refusal: AthenaApiError;\n try {\n refusal = await httpError(response, request, { signal: options.signal, attempt, timeoutMs });\n } finally {\n attempt.settle();\n }\n const waitMs = rateLimitWaitMs({ error: refusal, retry, method: request.method, policy: options.rateLimitRetry });\n if (waitMs === null) throw refusal;\n await sleep(waitMs, options.signal);\n }\n}\n\n/**\n * Send a request and answer its response once agora answered 2xx, for a body\n * the caller reads itself (a file, a stream). An error status throws\n * `AthenaApiError`. The timeout covers the wait for the answer, not the body.\n */\nexport async function athenaFetchResponse(\n config: AthenaRequestConfig,\n path: string,\n options: AthenaRequestOptions = {},\n): Promise<Response> {\n const request = prepare(config, path, options);\n const { response, attempt, timeoutMs } = await exchange(config, request, options);\n if (response.ok) {\n attempt.settle({ keepCancel: true });\n return response;\n }\n try {\n throw await httpError(response, request, { signal: options.signal, attempt, timeoutMs });\n } finally {\n attempt.settle();\n }\n}\n\n/** A 2xx answer's body: JSON when agora says it is JSON, text otherwise, `undefined` for none. */\nasync function athenaFetchBody(\n config: AthenaRequestConfig,\n path: string,\n options: AthenaRequestOptions,\n): Promise<{ status: number; body: unknown; request: PreparedRequest }> {\n const request = prepare(config, path, options);\n const { response, attempt, timeoutMs } = await exchange(config, request, options);\n try {\n if (!response.ok) throw await httpError(response, request, { signal: options.signal, attempt, timeoutMs });\n let text: string;\n try {\n text = await response.text();\n } catch (error) {\n throw failureOf({ error, attempt, signal: options.signal, request, timeoutMs, reading: true });\n }\n if (text.length === 0) return { status: response.status, body: undefined, request };\n const contentType = response.headers.get('content-type') ?? '';\n if (!/[/+]json\\b/i.test(contentType)) {\n return { status: response.status, body: contentType ? text : lenientBody(text), request };\n }\n try {\n return { status: response.status, body: JSON.parse(text), request };\n } catch (error) {\n throw new AthenaApiError({\n kind: AthenaApiErrorKind.Response,\n status: response.status,\n message: 'Agora answered with JSON that could not be read',\n method: request.method,\n path: request.path,\n cause: error,\n });\n }\n } finally {\n attempt.settle();\n }\n}\n\n/**\n * Send a request and answer its body: JSON when agora says it is JSON, text\n * otherwise, `undefined` for an empty answer. `T` is the caller's word for\n * what the route answers; nothing checks it.\n */\nexport async function athenaFetchJson<T = unknown>(\n config: AthenaRequestConfig,\n path: string,\n options: AthenaRequestOptions = {},\n): Promise<T> {\n const { body } = await athenaFetchBody(config, path, options);\n return body as T;\n}\n\nexport type AthenaGraphQLVariables = Readonly<Record<string, unknown>>;\n\n/**\n * A GraphQL document whose result and variables types travel with it, as\n * graphql-codegen's `TypedDocumentString` (its client preset with\n * `documentMode: 'string'`) carries them.\n */\nexport interface AthenaTypedDocument<TData, TVariables> {\n toString(): string;\n __apiType?: (variables: TVariables) => TData;\n}\n\n/** A GraphQL document: its text, or a typed document that names its result and variables. */\nexport type AthenaGraphQLDocument<TData = unknown, TVariables = AthenaGraphQLVariables> =\n | string\n | AthenaTypedDocument<TData, TVariables>;\n\nexport interface AthenaGraphQLRequestOptions\n extends Pick<AthenaRequestOptions, 'headers' | 'signal' | 'timeoutMs' | 'rateLimitRetry'> {\n /** The operation to run when the document holds several. */\n operationName?: string;\n}\n\n/**\n * Run one GraphQL operation on agora's `/graphql` and answer its `data`. An\n * answer with errors throws `AthenaApiError` (`kind: 'graphql'`, `code` the\n * first error's `extensions.code`), as does one with no data.\n */\nexport async function athenaGraphQL<TData = unknown, TVariables extends object = AthenaGraphQLVariables>(\n config: AthenaRequestConfig,\n document: AthenaGraphQLDocument<TData, TVariables>,\n variables?: TVariables,\n options: AthenaGraphQLRequestOptions = {},\n): Promise<TData> {\n const { operationName, ...requestOptions } = options;\n // TODO(#54756): send a registered operation's id (`documentId`) instead of its\n // text once agora allowlists each app's operations.\n const { status, body, request } = await athenaFetchBody(config, '/graphql', {\n ...requestOptions,\n method: 'POST',\n json: {\n query: String(document),\n variables: variables ?? {},\n ...(operationName ? { operationName } : {}),\n },\n });\n const errors = graphQLErrorEntries(body);\n const first = errors[0];\n if (first) {\n throw new AthenaApiError({\n kind: AthenaApiErrorKind.GraphQL,\n status,\n code: graphQLErrorCode(first),\n message: first.message,\n errors,\n method: request.method,\n path: request.path,\n });\n }\n const data: unknown =\n typeof body === 'object' && body !== null ? Reflect.get(body, 'data') : undefined;\n if (data === undefined || data === null) {\n throw new AthenaApiError({\n kind: AthenaApiErrorKind.GraphQL,\n status,\n message: 'The GraphQL answer had no data',\n method: request.method,\n path: request.path,\n });\n }\n return data as TData;\n}\n\n/** One operation a GraphQL document defines. */\nexport interface AthenaGraphQLOperation {\n type: 'query' | 'mutation' | 'subscription';\n /** `null` for an anonymous operation. */\n name: string | null;\n}\n\nconst GRAPHQL_IGNORED = /(?:[\\s,]+|#[^\\n\\r]*)+/y;\nconst GRAPHQL_NAME = /[_A-Za-z][_0-9A-Za-z]*/y;\n\n/**\n * The operations a GraphQL document defines, in order, fragments left out. A\n * lexical read that skips strings, comments, variable definitions (default\n * values included), directives and selection sets; it never validates the\n * document, which agora does.\n */\nexport function graphQLOperationsOf(document: string): AthenaGraphQLOperation[] {\n const operations: AthenaGraphQLOperation[] = [];\n let at = 0;\n const skipIgnored = () => {\n GRAPHQL_IGNORED.lastIndex = at;\n if (GRAPHQL_IGNORED.exec(document)) at = GRAPHQL_IGNORED.lastIndex;\n };\n const readName = (): string | null => {\n GRAPHQL_NAME.lastIndex = at;\n const name = GRAPHQL_NAME.exec(document)?.[0] ?? null;\n if (name !== null) at = GRAPHQL_NAME.lastIndex;\n return name;\n };\n /** Past the balanced `(…)` or `{…}` that opens at `at`, strings and comments included. */\n const skipGroup = () => {\n const open = document[at];\n const close = open === '(' ? ')' : '}';\n let depth = 0;\n while (at < document.length) {\n if (document.startsWith('\"\"\"', at)) {\n const end = document.indexOf('\"\"\"', at + 3);\n at = end === -1 ? document.length : end + 3;\n continue;\n }\n const char = document[at];\n if (char === '\"') {\n at += 1;\n while (at < document.length && document[at] !== '\"' && document[at] !== '\\n') {\n at += document[at] === '\\\\' ? 2 : 1;\n }\n at += 1;\n continue;\n }\n if (char === '#') {\n while (at < document.length && document[at] !== '\\n') at += 1;\n continue;\n }\n at += 1;\n if (char === open) depth += 1;\n else if (char === close) {\n depth -= 1;\n if (depth === 0) return;\n }\n }\n };\n /** Past a definition's header (variables, type condition, directives) and its selection set. */\n const skipDefinition = () => {\n while (at < document.length) {\n skipIgnored();\n const char = document[at];\n if (char === '{') {\n skipGroup();\n return;\n }\n if (char === '(') skipGroup();\n else at += 1;\n }\n };\n for (;;) {\n skipIgnored();\n if (at >= document.length) return operations;\n if (document[at] === '{') {\n operations.push({ type: 'query', name: null });\n skipGroup();\n continue;\n }\n const word = readName();\n if (word === 'query' || word === 'mutation' || word === 'subscription') {\n skipIgnored();\n operations.push({ type: word, name: readName() });\n }\n skipDefinition();\n }\n}\n\n/**\n * The operation a request runs: the one `operationName` names, else the\n * document's only one. `null` when neither picks one (agora refuses those).\n */\nexport function selectedGraphQLOperation(\n document: string,\n operationName?: string | null,\n): AthenaGraphQLOperation | null {\n const operations = graphQLOperationsOf(document);\n if (operationName) return operations.find((operation) => operation.name === operationName) ?? null;\n return operations.length === 1 ? (operations[0] ?? null) : null;\n}\n\n/**\n * An authenticated fetch bound to one configuration (see `useAthenaFetch`).\n * Called, it answers the route's body; `raw` answers the response itself and\n * `graphql` runs one GraphQL operation.\n */\nexport interface AthenaFetch {\n <T = unknown>(path: string, options?: AthenaRequestOptions): Promise<T>;\n raw(path: string, options?: AthenaRequestOptions): Promise<Response>;\n graphql<TData = unknown, TVariables extends object = AthenaGraphQLVariables>(\n document: AthenaGraphQLDocument<TData, TVariables>,\n variables?: TVariables,\n options?: AthenaGraphQLRequestOptions,\n ): Promise<TData>;\n}\n\n/**\n * `useAthenaFetch` without React: the transport bound to `config`, read once.\n * Hosts outside a component can pass `useAthenaConfig()`'s value along.\n */\nexport function createAthenaFetch(config: AthenaRequestConfig): AthenaFetch {\n const bound: AthenaRequestConfig = {\n backendUrl: config.backendUrl,\n apiKey: config.apiKey,\n token: config.token,\n getToken: config.getToken,\n };\n return Object.assign(\n <T = unknown>(path: string, options?: AthenaRequestOptions) =>\n athenaFetchJson<T>(bound, path, options),\n {\n raw: (path: string, options?: AthenaRequestOptions) => athenaFetchResponse(bound, path, options),\n graphql: <TData = unknown, TVariables extends object = AthenaGraphQLVariables>(\n document: AthenaGraphQLDocument<TData, TVariables>,\n variables?: TVariables,\n options?: AthenaGraphQLRequestOptions,\n ) => athenaGraphQL<TData, TVariables>(bound, document, variables, options),\n },\n );\n}\n"],"names":["AthenaApiError","AthenaApiErrorKind","getAthenaApiBaseUrl","isAthenaApiError","graphQLErrorEntries","seconds","restErrorDetail","graphQLErrorCode","sendWithCredentialRenewal"],"mappings":";;;;;AAmFO,MAAM,4BAA4B;AACzC,MAAM,yBAAyB;AAC/B,MAAM,yBAAyB;AAE/B,MAAM,8BAA8B;AAEpC,MAAM,oBAAoB;AAC1B,MAAM,eAAoC,oBAAI,IAAI,CAAC,OAAO,QAAQ,SAAS,CAAC;AAK5E,MAAM,uCAA4C,IAAI;AAAA,EACpD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAWD,SAAS,OAAO,SAAiB,QAAgB,MAA8B;AAC7E,SAAO,IAAIA,eAAAA,eAAe,EAAE,MAAMC,eAAAA,mBAAmB,SAAS,SAAS,QAAQ,MAAM;AACvF;AAEA,SAAS,QACP,QACA,MACA,SACiB;AACjB,QAAM,UAAU,QAAQ,SAAS,UAAa,QAAQ,SAAS;AAC/D,QAAM,UAAU,QAAQ,WAAW,UAAU,SAAS,QAAQ,YAAA;AAC9D,QAAM,YAAY,KAAK,MAAM,GAAG,EAAE,CAAC,KAAK;AAGxC,MAAI,CAAC,KAAK,WAAW,GAAG,KAAK,KAAK,WAAW,IAAI,GAAG;AAClD,UAAM;AAAA,MACJ,uFAAuF,KAAK,UAAU,IAAI,CAAC;AAAA,MAC3G;AAAA,MACA;AAAA,IAAA;AAAA,EAEJ;AACA,MAAI,QAAQ,SAAS,UAAa,QAAQ,SAAS,QAAW;AAC5D,UAAM,OAAO,8CAA8C,QAAQ,SAAS;AAAA,EAC9E;AAIA,aAAW,QAAQ,OAAO,KAAK,QAAQ,WAAW,CAAA,CAAE,GAAG;AACrD,QAAI,iBAAiB,IAAI,KAAK,YAAA,CAAa,GAA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,QAA6B;AAAA,IACjC,YAAY,OAAO;AAAA,IACnB,QAAQ,OAAO;AAAA,IACf,OAAO,OAAO;AAAA,IACd,UAAU,OAAO;AAAA,EAAA;AAEnB,SAAO,OAAO;AAAA,IACZ,CAAc,MAAc,YAC1B,gBAAmB,OAAO,MAAM,OAAO;AAAA,IACzC;AAAA,MACE,KAAK,CAAC,MAAc,YAAmC,oBAAoB,OAAO,MAAM,OAAO;AAAA,MAC/F,SAAS,CACP,UACA,WACA,YACG,cAAiC,OAAO,UAAU,WAAW,OAAO;AAAA,IAAA;AAAA,EAC3E;AAEJ;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"athena-request.cjs","sources":["../../src/data/athena-request.ts"],"sourcesContent":["/**\n * The SDK's authenticated transport to agora, without React. Every request:\n *\n * - presents the provider's credential: the live token from `getToken`, renewed\n * once after a 401 (`sendWithCredentialRenewal`, the statewire transport's\n * `staleAuth` contract), else the API key;\n * - goes to the provider's `backendUrl`, and only there: a path must start\n * with `/`;\n * - waits out a 429 as agora's `Retry-After` asks, a bounded number of times;\n * - is abandoned after `timeoutMs`;\n * - fails as an `AthenaApiError`, except a request the caller cancelled, which\n * rejects with the abort's reason as `fetch` does.\n *\n * `useAthenaFetch` binds it to the provider, and the data hooks run on it.\n */\nimport { getAthenaApiBaseUrl } from '../collab/mint';\nimport { sendWithCredentialRenewal } from '../runtime/credential-renewal';\nimport type {\n AthenaStatewireTokenGetter,\n StatewireAuthSource,\n} from '../runtime/statewire-auth-headers';\nimport {\n AthenaApiError,\n AthenaApiErrorKind,\n graphQLErrorCode,\n graphQLErrorEntries,\n isAthenaApiError,\n restErrorDetail,\n} from './athena-api-error';\nimport { ATHENA_CLIENT_HEADER, ATHENA_REACT_CLIENT } from '../version';\n\n/** Where a request goes and the credential it presents: the fields of `useAthenaConfig()` it reads. */\nexport interface AthenaRequestConfig {\n /** The Agora API base (`useAthenaConfig().backendUrl`). */\n backendUrl: string;\n apiKey?: string;\n token?: string | null;\n getToken?: AthenaStatewireTokenGetter;\n}\n\nexport type AthenaQueryParamValue = string | number | boolean | null | undefined;\n\n/** Query-string parameters: `null` and `undefined` are left out, an array repeats its key. */\nexport type AthenaQueryParams = Readonly<\n Record<string, AthenaQueryParamValue | readonly (string | number | boolean)[]>\n>;\n\n/** A body the SDK can send again (a 401's renewal and a 429's retry resend it): never a stream. */\nexport type AthenaRequestBody = Exclude<BodyInit, ReadableStream>;\n\n/** How a 429 is waited out. */\nexport interface AthenaRateLimitRetry {\n /** How many times the request is sent again (default 2). */\n maxRetries?: number;\n /**\n * The longest the SDK waits before sending again, in ms (default 30 000).\n * When agora asks for longer, the request fails at once with the 429, whose\n * `retryAfterMs` says when to come back.\n */\n maxWaitMs?: number;\n}\n\nexport interface AthenaRequestOptions {\n /** Default `GET`, or `POST` when the request has a body. */\n method?: string;\n params?: AthenaQueryParams;\n /** A body sent as JSON (`Content-Type: application/json`). Not with `body`. */\n json?: unknown;\n /** A body sent as is (`FormData`, `Blob`, text…). Not with `json`. */\n body?: AthenaRequestBody;\n /**\n * Extra headers. A request presents the provider's credential and no other:\n * `Authorization`, `X-API-KEY`, `Cookie`, `Proxy-Authorization` and\n * `X-Athena-View-As` are refused, in any letter case.\n */\n headers?: Readonly<Record<string, string>>;\n /** Cancels the request (and a wait between its attempts); it then rejects with the abort's reason. */\n signal?: AbortSignal;\n /** How long one attempt may take, in ms (default 30 000); `0` waits as long as it takes. */\n timeoutMs?: number;\n /** How a 429 is waited out; `false` fails at once. */\n rateLimitRetry?: AthenaRateLimitRetry | false;\n}\n\nexport const ATHENA_REQUEST_TIMEOUT_MS = 30_000;\nconst RATE_LIMIT_MAX_RETRIES = 2;\nconst RATE_LIMIT_MAX_WAIT_MS = 30_000;\n/** The first wait for a 429 that says nothing of when to come back; it doubles for each retry. */\nconst RATE_LIMIT_FIRST_BACKOFF_MS = 1_000;\n/** What agora's per-user limiter answers, before it runs anything (`user_request_rate_limit.py`). */\nconst RATE_LIMITED_CODE = 'RATE_LIMITED';\nconst SAFE_METHODS: ReadonlySet<string> = new Set(['GET', 'HEAD', 'OPTIONS']);\n/**\n * Headers that say who a request acts as, or through whose eyes\n * (`X-Athena-View-As`, agora's view-as lens): only the provider sets those.\n */\nconst IDENTITY_HEADERS: ReadonlySet<string> = new Set([\n 'authorization',\n 'proxy-authorization',\n 'cookie',\n 'x-api-key',\n 'x-athena-view-as',\n]);\n\n/** The request as sent: its method, its URL and its path for errors (no query string). */\ninterface PreparedRequest {\n method: string;\n url: string;\n path: string;\n headers: Record<string, string>;\n body: AthenaRequestBody | undefined;\n}\n\nfunction refuse(message: string, method: string, path: string): AthenaApiError {\n return new AthenaApiError({ kind: AthenaApiErrorKind.Request, message, method, path });\n}\n\nfunction prepare(\n config: AthenaRequestConfig,\n path: string,\n options: AthenaRequestOptions,\n): PreparedRequest {\n const hasBody = options.json !== undefined || options.body !== undefined;\n const method = (options.method ?? (hasBody ? 'POST' : 'GET')).toUpperCase();\n const errorPath = path.split('?')[0] ?? path;\n // A path, never a URL: a request carries the person's credential, so it goes\n // to the provider's backend and nowhere else.\n if (!path.startsWith('/') || path.startsWith('//')) {\n throw refuse(\n `A request path must start with a single \"/\" (it goes to the provider's backendUrl): ${JSON.stringify(path)}`,\n method,\n errorPath,\n );\n }\n if (options.json !== undefined && options.body !== undefined) {\n throw refuse('A request takes `json` or `body`, not both', method, errorPath);\n }\n // Header names are case-insensitive: a lowercase `authorization` would be\n // sent beside the provider's and could act as someone else, whose answer the\n // data hooks would then cache under the provider's identity.\n for (const name of Object.keys(options.headers ?? {})) {\n if (IDENTITY_HEADERS.has(name.toLowerCase())) {\n throw refuse(\n `A request may not set ${name}: it presents the provider's credential and no other`,\n method,\n errorPath,\n );\n }\n }\n const base = getAthenaApiBaseUrl(config.backendUrl);\n let url: URL;\n let backendOrigin: string;\n try {\n backendOrigin = new URL(base).origin;\n url = new URL(`${base}${path}`);\n } catch (error) {\n throw new AthenaApiError({\n kind: AthenaApiErrorKind.Request,\n message: `The provider's backendUrl is not a URL: ${JSON.stringify(config.backendUrl)}`,\n method,\n path: errorPath,\n cause: error,\n });\n }\n if (url.origin !== backendOrigin) {\n throw refuse(`A request path must stay on the provider's backendUrl: ${JSON.stringify(path)}`, method, errorPath);\n }\n for (const [name, value] of Object.entries(options.params ?? {})) {\n for (const item of Array.isArray(value) ? value : [value]) {\n if (item !== null && item !== undefined) url.searchParams.append(name, String(item));\n }\n }\n // TODO(#54756): name the app on every call (the provider's `appId`) once agora\n // records it and limits by it.\n const headers: Record<string, string> = {\n Accept: 'application/json',\n [ATHENA_CLIENT_HEADER]: ATHENA_REACT_CLIENT,\n ...(options.json !== undefined ? { 'Content-Type': 'application/json' } : {}),\n ...options.headers,\n };\n return {\n method,\n url: url.toString(),\n path: errorPath,\n headers,\n body: options.json !== undefined ? JSON.stringify(options.json) : options.body,\n };\n}\n\n/** The provider's credential; a `getToken` that throws fails the request as `credential`. */\nfunction credentialSource(config: AthenaRequestConfig, request: PreparedRequest): StatewireAuthSource {\n const getToken = config.getToken;\n return {\n apiKey: config.apiKey,\n token: config.token,\n ...(getToken\n ? {\n getToken: async (options?: { force?: boolean }) => {\n try {\n return await getToken(options);\n } catch (error) {\n throw new AthenaApiError({\n kind: AthenaApiErrorKind.Credential,\n message: 'The provider could not resolve a credential for the request',\n method: request.method,\n path: request.path,\n cause: error,\n });\n }\n },\n }\n : {}),\n };\n}\n\n/** One attempt's signal: the caller's cancel, and its own timeout. */\ninterface Attempt {\n signal: AbortSignal;\n timedOut: () => boolean;\n /**\n * Stops the timeout. `keepCancel` leaves the caller's signal able to cancel\n * the body the caller still reads.\n */\n settle: (options?: { keepCancel?: boolean }) => void;\n}\n\nfunction startAttempt(parent: AbortSignal | undefined, timeoutMs: number): Attempt {\n const controller = new AbortController();\n let timedOut = false;\n const forward = () => controller.abort(parent?.reason);\n if (parent?.aborted) controller.abort(parent.reason);\n else parent?.addEventListener('abort', forward, { once: true });\n const timer =\n timeoutMs > 0 && Number.isFinite(timeoutMs)\n ? setTimeout(() => {\n timedOut = true;\n controller.abort(new DOMException(`No answer within ${timeoutMs} ms`, 'TimeoutError'));\n }, timeoutMs)\n : undefined;\n return {\n signal: controller.signal,\n timedOut: () => timedOut,\n settle: ({ keepCancel = false } = {}) => {\n if (timer !== undefined) clearTimeout(timer);\n if (!keepCancel) parent?.removeEventListener('abort', forward);\n },\n };\n}\n\nfunction abortReason(signal: AbortSignal): unknown {\n return signal.reason ?? new DOMException('The request was cancelled', 'AbortError');\n}\n\n/** A fetch or a body read that threw: the caller's cancel as is, else a typed failure. */\nfunction failureOf({\n error,\n attempt,\n signal,\n request,\n timeoutMs,\n reading,\n}: {\n error: unknown;\n attempt: Attempt;\n signal: AbortSignal | undefined;\n request: PreparedRequest;\n timeoutMs: number;\n reading: boolean;\n}): unknown {\n if (signal?.aborted) return abortReason(signal);\n if (isAthenaApiError(error)) return error;\n if (attempt.timedOut()) {\n return new AthenaApiError({\n kind: AthenaApiErrorKind.Timeout,\n message: `Athena did not answer within ${timeoutMs} ms`,\n method: request.method,\n path: request.path,\n cause: error,\n });\n }\n return new AthenaApiError({\n kind: reading ? AthenaApiErrorKind.Response : AthenaApiErrorKind.Network,\n message: reading ? 'The answer was cut off before it was read' : 'Athena could not be reached',\n method: request.method,\n path: request.path,\n cause: error,\n });\n}\n\n/**\n * How long agora asked the caller to wait, in ms: the `Retry-After` header\n * (seconds or a date), else the `retryAfterSeconds` of a rate-limit refusal's\n * body. `null` when it said nothing it is possible to read.\n */\nexport function retryAfterMsOf(response: Response, body: unknown, now: number = Date.now()): number | null {\n const header = response.headers.get('retry-after')?.trim();\n if (header) {\n if (/^\\d+$/.test(header)) return Number(header) * 1000;\n const date = Date.parse(header);\n if (Number.isFinite(date)) return Math.max(0, date - now);\n }\n for (const entry of graphQLErrorEntries(body)) {\n const seconds = entry.extensions?.retryAfterSeconds;\n if (typeof seconds === 'number' && Number.isFinite(seconds) && seconds >= 0) return seconds * 1000;\n }\n const seconds = restErrorDetail(body).retryAfterSeconds;\n return seconds !== null && seconds >= 0 ? seconds * 1000 : null;\n}\n\n/** JSON when it reads as JSON, the text otherwise; `undefined` for nothing. */\nfunction lenientBody(text: string): unknown {\n if (text.length === 0) return undefined;\n try {\n return JSON.parse(text);\n } catch {\n return text;\n }\n}\n\n/** How much of an error body that is not JSON (a proxy's error page) an error keeps. */\nconst TEXT_DETAIL_LIMIT = 1_000;\n\n/**\n * The `AthenaApiError` an error status answers, its body read for agora's code\n * and message. A body the attempt's timeout cut off is a timeout (a stalled\n * 5xx must not read as a 5xx, which a read retries), and the caller's cancel\n * stays a cancel; a body that fails otherwise is left out.\n */\nasync function httpError(\n response: Response,\n request: PreparedRequest,\n { signal, attempt, timeoutMs }: { signal: AbortSignal | undefined; attempt: Attempt; timeoutMs: number },\n): Promise<AthenaApiError> {\n let body: unknown;\n try {\n body = lenientBody(await response.text());\n } catch (error) {\n if (signal?.aborted || attempt.timedOut()) {\n throw failureOf({ error, attempt, signal, request, timeoutMs, reading: true });\n }\n body = undefined;\n }\n const statusLine = response.statusText\n ? `${response.status} ${response.statusText}`\n : `HTTP ${response.status}`;\n const common = {\n kind: AthenaApiErrorKind.Http,\n status: response.status,\n retryAfterMs: retryAfterMsOf(response, body),\n method: request.method,\n path: request.path,\n };\n // Not JSON: a gateway's or proxy's page, never agora's words.\n if (typeof body === 'string') {\n return new AthenaApiError({ ...common, message: statusLine, detail: body.slice(0, TEXT_DETAIL_LIMIT) });\n }\n const errors = graphQLErrorEntries(body);\n const rest = restErrorDetail(body);\n return new AthenaApiError({\n ...common,\n code: graphQLErrorCode(errors[0]) ?? rest.code,\n message: errors[0]?.message ?? rest.message ?? statusLine,\n errors,\n detail: errors.length > 0 ? undefined : rest.detail,\n });\n}\n\n/**\n * How long to wait before sending a refused request again, or `null` to fail\n * now. A write goes again only when agora's limiter refused it: that refusal\n * comes before anything runs, so the write cannot apply twice.\n */\nfunction rateLimitWaitMs({\n error,\n retry,\n method,\n policy,\n}: {\n error: AthenaApiError;\n retry: number;\n method: string;\n policy: AthenaRateLimitRetry | false | undefined;\n}): number | null {\n if (policy === false) return null;\n if (retry >= (policy?.maxRetries ?? RATE_LIMIT_MAX_RETRIES)) return null;\n if (!SAFE_METHODS.has(method) && error.code !== RATE_LIMITED_CODE) return null;\n const waitMs =\n error.retryAfterMs ?? RATE_LIMIT_FIRST_BACKOFF_MS * 2 ** retry * (0.8 + Math.random() * 0.4);\n return waitMs <= (policy?.maxWaitMs ?? RATE_LIMIT_MAX_WAIT_MS) ? waitMs : null;\n}\n\nfunction sleep(ms: number, signal: AbortSignal | undefined): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(abortReason(signal));\n return;\n }\n let timer: ReturnType<typeof setTimeout> | undefined;\n const onAbort = () => {\n clearTimeout(timer);\n if (signal) reject(abortReason(signal));\n };\n timer = setTimeout(() => {\n signal?.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n\n/**\n * Send until agora answers with something other than a 429 the SDK waits out.\n * Answers that response (any status) with the attempt that got it, whose\n * timeout still runs: the caller settles it once the body is read.\n */\nasync function exchange(\n config: AthenaRequestConfig,\n request: PreparedRequest,\n options: AthenaRequestOptions,\n): Promise<{ response: Response; attempt: Attempt; timeoutMs: number }> {\n const timeoutMs = options.timeoutMs ?? ATHENA_REQUEST_TIMEOUT_MS;\n const source = credentialSource(config, request);\n for (let retry = 0; ; retry += 1) {\n const attempt = startAttempt(options.signal, timeoutMs);\n let response: Response;\n try {\n response = await sendWithCredentialRenewal(source, (credentialHeaders) =>\n fetch(request.url, {\n method: request.method,\n headers: { ...request.headers, ...credentialHeaders },\n body: request.body ?? null,\n signal: attempt.signal,\n }),\n );\n } catch (error) {\n attempt.settle();\n throw failureOf({ error, attempt, signal: options.signal, request, timeoutMs, reading: false });\n }\n if (response.status !== 429) return { response, attempt, timeoutMs };\n let refusal: AthenaApiError;\n try {\n refusal = await httpError(response, request, { signal: options.signal, attempt, timeoutMs });\n } finally {\n attempt.settle();\n }\n const waitMs = rateLimitWaitMs({ error: refusal, retry, method: request.method, policy: options.rateLimitRetry });\n if (waitMs === null) throw refusal;\n await sleep(waitMs, options.signal);\n }\n}\n\n/**\n * Send a request and answer its response once agora answered 2xx, for a body\n * the caller reads itself (a file, a stream). An error status throws\n * `AthenaApiError`. The timeout covers the wait for the answer, not the body.\n */\nexport async function athenaFetchResponse(\n config: AthenaRequestConfig,\n path: string,\n options: AthenaRequestOptions = {},\n): Promise<Response> {\n const request = prepare(config, path, options);\n const { response, attempt, timeoutMs } = await exchange(config, request, options);\n if (response.ok) {\n attempt.settle({ keepCancel: true });\n return response;\n }\n try {\n throw await httpError(response, request, { signal: options.signal, attempt, timeoutMs });\n } finally {\n attempt.settle();\n }\n}\n\n/** A 2xx answer's body: JSON when agora says it is JSON, text otherwise, `undefined` for none. */\nasync function athenaFetchBody(\n config: AthenaRequestConfig,\n path: string,\n options: AthenaRequestOptions,\n): Promise<{ status: number; body: unknown; request: PreparedRequest }> {\n const request = prepare(config, path, options);\n const { response, attempt, timeoutMs } = await exchange(config, request, options);\n try {\n if (!response.ok) throw await httpError(response, request, { signal: options.signal, attempt, timeoutMs });\n let text: string;\n try {\n text = await response.text();\n } catch (error) {\n throw failureOf({ error, attempt, signal: options.signal, request, timeoutMs, reading: true });\n }\n if (text.length === 0) return { status: response.status, body: undefined, request };\n const contentType = response.headers.get('content-type') ?? '';\n if (!/[/+]json\\b/i.test(contentType)) {\n return { status: response.status, body: contentType ? text : lenientBody(text), request };\n }\n try {\n return { status: response.status, body: JSON.parse(text), request };\n } catch (error) {\n throw new AthenaApiError({\n kind: AthenaApiErrorKind.Response,\n status: response.status,\n message: 'Agora answered with JSON that could not be read',\n method: request.method,\n path: request.path,\n cause: error,\n });\n }\n } finally {\n attempt.settle();\n }\n}\n\n/**\n * Send a request and answer its body: JSON when agora says it is JSON, text\n * otherwise, `undefined` for an empty answer. `T` is the caller's word for\n * what the route answers; nothing checks it.\n */\nexport async function athenaFetchJson<T = unknown>(\n config: AthenaRequestConfig,\n path: string,\n options: AthenaRequestOptions = {},\n): Promise<T> {\n const { body } = await athenaFetchBody(config, path, options);\n return body as T;\n}\n\nexport type AthenaGraphQLVariables = Readonly<Record<string, unknown>>;\n\n/**\n * A GraphQL document whose result and variables types travel with it, as\n * graphql-codegen's `TypedDocumentString` (its client preset with\n * `documentMode: 'string'`) carries them.\n */\nexport interface AthenaTypedDocument<TData, TVariables> {\n toString(): string;\n __apiType?: (variables: TVariables) => TData;\n}\n\n/** A GraphQL document: its text, or a typed document that names its result and variables. */\nexport type AthenaGraphQLDocument<TData = unknown, TVariables = AthenaGraphQLVariables> =\n | string\n | AthenaTypedDocument<TData, TVariables>;\n\nexport interface AthenaGraphQLRequestOptions\n extends Pick<AthenaRequestOptions, 'headers' | 'signal' | 'timeoutMs' | 'rateLimitRetry'> {\n /** The operation to run when the document holds several. */\n operationName?: string;\n}\n\n/**\n * Run one GraphQL operation on agora's `/graphql` and answer its `data`. An\n * answer with errors throws `AthenaApiError` (`kind: 'graphql'`, `code` the\n * first error's `extensions.code`), as does one with no data.\n */\nexport async function athenaGraphQL<TData = unknown, TVariables extends object = AthenaGraphQLVariables>(\n config: AthenaRequestConfig,\n document: AthenaGraphQLDocument<TData, TVariables>,\n variables?: TVariables,\n options: AthenaGraphQLRequestOptions = {},\n): Promise<TData> {\n const { operationName, ...requestOptions } = options;\n // TODO(#54756): send a registered operation's id (`documentId`) instead of its\n // text once agora allowlists each app's operations.\n const { status, body, request } = await athenaFetchBody(config, '/graphql', {\n ...requestOptions,\n method: 'POST',\n json: {\n query: String(document),\n variables: variables ?? {},\n ...(operationName ? { operationName } : {}),\n },\n });\n const errors = graphQLErrorEntries(body);\n const first = errors[0];\n if (first) {\n throw new AthenaApiError({\n kind: AthenaApiErrorKind.GraphQL,\n status,\n code: graphQLErrorCode(first),\n message: first.message,\n errors,\n method: request.method,\n path: request.path,\n });\n }\n const data: unknown =\n typeof body === 'object' && body !== null ? Reflect.get(body, 'data') : undefined;\n if (data === undefined || data === null) {\n throw new AthenaApiError({\n kind: AthenaApiErrorKind.GraphQL,\n status,\n message: 'The GraphQL answer had no data',\n method: request.method,\n path: request.path,\n });\n }\n return data as TData;\n}\n\n/** One operation a GraphQL document defines. */\nexport interface AthenaGraphQLOperation {\n type: 'query' | 'mutation' | 'subscription';\n /** `null` for an anonymous operation. */\n name: string | null;\n}\n\nconst GRAPHQL_IGNORED = /(?:[\\s,]+|#[^\\n\\r]*)+/y;\nconst GRAPHQL_NAME = /[_A-Za-z][_0-9A-Za-z]*/y;\n\n/**\n * The operations a GraphQL document defines, in order, fragments left out. A\n * lexical read that skips strings, comments, variable definitions (default\n * values included), directives and selection sets; it never validates the\n * document, which agora does.\n */\nexport function graphQLOperationsOf(document: string): AthenaGraphQLOperation[] {\n const operations: AthenaGraphQLOperation[] = [];\n let at = 0;\n const skipIgnored = () => {\n GRAPHQL_IGNORED.lastIndex = at;\n if (GRAPHQL_IGNORED.exec(document)) at = GRAPHQL_IGNORED.lastIndex;\n };\n const readName = (): string | null => {\n GRAPHQL_NAME.lastIndex = at;\n const name = GRAPHQL_NAME.exec(document)?.[0] ?? null;\n if (name !== null) at = GRAPHQL_NAME.lastIndex;\n return name;\n };\n /** Past the balanced `(…)` or `{…}` that opens at `at`, strings and comments included. */\n const skipGroup = () => {\n const open = document[at];\n const close = open === '(' ? ')' : '}';\n let depth = 0;\n while (at < document.length) {\n if (document.startsWith('\"\"\"', at)) {\n const end = document.indexOf('\"\"\"', at + 3);\n at = end === -1 ? document.length : end + 3;\n continue;\n }\n const char = document[at];\n if (char === '\"') {\n at += 1;\n while (at < document.length && document[at] !== '\"' && document[at] !== '\\n') {\n at += document[at] === '\\\\' ? 2 : 1;\n }\n at += 1;\n continue;\n }\n if (char === '#') {\n while (at < document.length && document[at] !== '\\n') at += 1;\n continue;\n }\n at += 1;\n if (char === open) depth += 1;\n else if (char === close) {\n depth -= 1;\n if (depth === 0) return;\n }\n }\n };\n /** Past a definition's header (variables, type condition, directives) and its selection set. */\n const skipDefinition = () => {\n while (at < document.length) {\n skipIgnored();\n const char = document[at];\n if (char === '{') {\n skipGroup();\n return;\n }\n if (char === '(') skipGroup();\n else at += 1;\n }\n };\n for (;;) {\n skipIgnored();\n if (at >= document.length) return operations;\n if (document[at] === '{') {\n operations.push({ type: 'query', name: null });\n skipGroup();\n continue;\n }\n const word = readName();\n if (word === 'query' || word === 'mutation' || word === 'subscription') {\n skipIgnored();\n operations.push({ type: word, name: readName() });\n }\n skipDefinition();\n }\n}\n\n/**\n * The operation a request runs: the one `operationName` names, else the\n * document's only one. `null` when neither picks one (agora refuses those).\n */\nexport function selectedGraphQLOperation(\n document: string,\n operationName?: string | null,\n): AthenaGraphQLOperation | null {\n const operations = graphQLOperationsOf(document);\n if (operationName) return operations.find((operation) => operation.name === operationName) ?? null;\n return operations.length === 1 ? (operations[0] ?? null) : null;\n}\n\n/**\n * An authenticated fetch bound to one configuration (see `useAthenaFetch`).\n * Called, it answers the route's body; `raw` answers the response itself and\n * `graphql` runs one GraphQL operation.\n */\nexport interface AthenaFetch {\n <T = unknown>(path: string, options?: AthenaRequestOptions): Promise<T>;\n raw(path: string, options?: AthenaRequestOptions): Promise<Response>;\n graphql<TData = unknown, TVariables extends object = AthenaGraphQLVariables>(\n document: AthenaGraphQLDocument<TData, TVariables>,\n variables?: TVariables,\n options?: AthenaGraphQLRequestOptions,\n ): Promise<TData>;\n}\n\n/**\n * `useAthenaFetch` without React: the transport bound to `config`, read once.\n * Hosts outside a component can pass `useAthenaConfig()`'s value along.\n */\nexport function createAthenaFetch(config: AthenaRequestConfig): AthenaFetch {\n const bound: AthenaRequestConfig = {\n backendUrl: config.backendUrl,\n apiKey: config.apiKey,\n token: config.token,\n getToken: config.getToken,\n };\n return Object.assign(\n <T = unknown>(path: string, options?: AthenaRequestOptions) =>\n athenaFetchJson<T>(bound, path, options),\n {\n raw: (path: string, options?: AthenaRequestOptions) => athenaFetchResponse(bound, path, options),\n graphql: <TData = unknown, TVariables extends object = AthenaGraphQLVariables>(\n document: AthenaGraphQLDocument<TData, TVariables>,\n variables?: TVariables,\n options?: AthenaGraphQLRequestOptions,\n ) => athenaGraphQL<TData, TVariables>(bound, document, variables, options),\n },\n );\n}\n"],"names":["AthenaApiError","AthenaApiErrorKind","getAthenaApiBaseUrl","ATHENA_CLIENT_HEADER","ATHENA_REACT_CLIENT","isAthenaApiError","graphQLErrorEntries","seconds","restErrorDetail","graphQLErrorCode","sendWithCredentialRenewal"],"mappings":";;;;;;AAoFO,MAAM,4BAA4B;AACzC,MAAM,yBAAyB;AAC/B,MAAM,yBAAyB;AAE/B,MAAM,8BAA8B;AAEpC,MAAM,oBAAoB;AAC1B,MAAM,eAAoC,oBAAI,IAAI,CAAC,OAAO,QAAQ,SAAS,CAAC;AAK5E,MAAM,uCAA4C,IAAI;AAAA,EACpD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAWD,SAAS,OAAO,SAAiB,QAAgB,MAA8B;AAC7E,SAAO,IAAIA,eAAAA,eAAe,EAAE,MAAMC,eAAAA,mBAAmB,SAAS,SAAS,QAAQ,MAAM;AACvF;AAEA,SAAS,QACP,QACA,MACA,SACiB;AACjB,QAAM,UAAU,QAAQ,SAAS,UAAa,QAAQ,SAAS;AAC/D,QAAM,UAAU,QAAQ,WAAW,UAAU,SAAS,QAAQ,YAAA;AAC9D,QAAM,YAAY,KAAK,MAAM,GAAG,EAAE,CAAC,KAAK;AAGxC,MAAI,CAAC,KAAK,WAAW,GAAG,KAAK,KAAK,WAAW,IAAI,GAAG;AAClD,UAAM;AAAA,MACJ,uFAAuF,KAAK,UAAU,IAAI,CAAC;AAAA,MAC3G;AAAA,MACA;AAAA,IAAA;AAAA,EAEJ;AACA,MAAI,QAAQ,SAAS,UAAa,QAAQ,SAAS,QAAW;AAC5D,UAAM,OAAO,8CAA8C,QAAQ,SAAS;AAAA,EAC9E;AAIA,aAAW,QAAQ,O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