@athenaintel/react 0.54.0 → 0.56.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +32 -0
- package/dist/agent-runtime/src/answer-label.cjs +8 -2
- package/dist/agent-runtime/src/answer-label.cjs.map +1 -1
- package/dist/agent-runtime/src/answer-label.d.ts +10 -4
- package/dist/agent-runtime/src/answer-label.js +8 -2
- package/dist/agent-runtime/src/answer-label.js.map +1 -1
- package/dist/agent-runtime/src/deep-agent-transport-recipe.cjs +6 -3
- package/dist/agent-runtime/src/deep-agent-transport-recipe.cjs.map +1 -1
- package/dist/agent-runtime/src/deep-agent-transport-recipe.js +6 -3
- package/dist/agent-runtime/src/deep-agent-transport-recipe.js.map +1 -1
- package/dist/agent-runtime/src/edit-command.cjs +42 -15
- package/dist/agent-runtime/src/edit-command.cjs.map +1 -1
- package/dist/agent-runtime/src/edit-command.d.ts +2 -0
- package/dist/agent-runtime/src/edit-command.js +43 -16
- package/dist/agent-runtime/src/edit-command.js.map +1 -1
- package/dist/agent-runtime/src/generated/runconfig-contract.cjs +12 -0
- package/dist/agent-runtime/src/generated/runconfig-contract.cjs.map +1 -1
- package/dist/agent-runtime/src/generated/runconfig-contract.d.ts +21 -1
- package/dist/agent-runtime/src/generated/runconfig-contract.js +12 -0
- package/dist/agent-runtime/src/generated/runconfig-contract.js.map +1 -1
- package/dist/agent-runtime/src/history-store.cjs +426 -0
- package/dist/agent-runtime/src/history-store.cjs.map +1 -0
- package/dist/agent-runtime/src/history-store.d.ts +282 -0
- package/dist/agent-runtime/src/history-store.js +426 -0
- package/dist/agent-runtime/src/history-store.js.map +1 -0
- package/dist/agent-runtime/src/index.d.ts +3 -2
- package/dist/agent-runtime/src/message-window.cjs +43 -5
- package/dist/agent-runtime/src/message-window.cjs.map +1 -1
- package/dist/agent-runtime/src/message-window.d.ts +26 -2
- package/dist/agent-runtime/src/message-window.js +44 -6
- package/dist/agent-runtime/src/message-window.js.map +1 -1
- package/dist/agent-runtime/src/offline-status.cjs.map +1 -1
- package/dist/agent-runtime/src/offline-status.d.ts +115 -5
- package/dist/agent-runtime/src/offline-status.js.map +1 -1
- package/dist/agent-runtime/src/runtime.d.ts +1 -0
- package/dist/agent-runtime/src/tool-metadata.cjs +8 -0
- package/dist/agent-runtime/src/tool-metadata.cjs.map +1 -1
- package/dist/agent-runtime/src/tool-metadata.js +8 -0
- package/dist/agent-runtime/src/tool-metadata.js.map +1 -1
- package/dist/agent-runtime/src/use-deep-agent-thread.cjs +7 -1
- package/dist/agent-runtime/src/use-deep-agent-thread.cjs.map +1 -1
- package/dist/agent-runtime/src/use-deep-agent-thread.js +8 -2
- package/dist/agent-runtime/src/use-deep-agent-thread.js.map +1 -1
- package/dist/agent-runtime/src/use-deep-agent-window-sync.cjs +73 -14
- package/dist/agent-runtime/src/use-deep-agent-window-sync.cjs.map +1 -1
- package/dist/agent-runtime/src/use-deep-agent-window-sync.d.ts +2 -2
- package/dist/agent-runtime/src/use-deep-agent-window-sync.js +75 -16
- package/dist/agent-runtime/src/use-deep-agent-window-sync.js.map +1 -1
- package/dist/chat/super-grouping/CollapsibleGroup.cjs +1 -1
- package/dist/chat/super-grouping/CollapsibleGroup.cjs.map +1 -1
- package/dist/chat/super-grouping/CollapsibleGroup.d.ts +6 -5
- package/dist/chat/super-grouping/CollapsibleGroup.js +1 -1
- package/dist/chat/super-grouping/CollapsibleGroup.js.map +1 -1
- package/dist/chat/super-grouping/SuperGroupingCard.cjs +51 -43
- package/dist/chat/super-grouping/SuperGroupingCard.cjs.map +1 -1
- package/dist/chat/super-grouping/SuperGroupingCard.js +51 -43
- package/dist/chat/super-grouping/SuperGroupingCard.js.map +1 -1
- package/dist/chat/super-grouping/SuperGroupingTranscript.cjs +9 -4
- package/dist/chat/super-grouping/SuperGroupingTranscript.cjs.map +1 -1
- package/dist/chat/super-grouping/SuperGroupingTranscript.js +9 -4
- package/dist/chat/super-grouping/SuperGroupingTranscript.js.map +1 -1
- package/dist/chat/super-grouping/activity-timeline.cjs +7 -4
- package/dist/chat/super-grouping/activity-timeline.cjs.map +1 -1
- package/dist/chat/super-grouping/activity-timeline.d.ts +10 -1
- package/dist/chat/super-grouping/activity-timeline.js +7 -4
- package/dist/chat/super-grouping/activity-timeline.js.map +1 -1
- package/dist/chat/super-grouping/earlier-steps-button.cjs +49 -0
- package/dist/chat/super-grouping/earlier-steps-button.cjs.map +1 -0
- package/dist/chat/super-grouping/earlier-steps-button.d.ts +11 -0
- package/dist/chat/super-grouping/earlier-steps-button.js +49 -0
- package/dist/chat/super-grouping/earlier-steps-button.js.map +1 -0
- package/dist/chat/super-grouping/toolkit-map.cjs +1 -0
- package/dist/chat/super-grouping/toolkit-map.cjs.map +1 -1
- package/dist/chat/super-grouping/toolkit-map.js +1 -0
- package/dist/chat/super-grouping/toolkit-map.js.map +1 -1
- package/dist/chat/super-grouping/use-turn-steps.cjs +28 -0
- package/dist/chat/super-grouping/use-turn-steps.cjs.map +1 -0
- package/dist/chat/super-grouping/use-turn-steps.d.ts +23 -0
- package/dist/chat/super-grouping/use-turn-steps.js +28 -0
- package/dist/chat/super-grouping/use-turn-steps.js.map +1 -0
- package/dist/chat-ui/statewire.cjs +6 -0
- package/dist/chat-ui/statewire.cjs.map +1 -1
- package/dist/chat-ui/statewire.d.ts +3 -1
- package/dist/chat-ui/statewire.js +7 -1
- package/dist/chat-ui/statewire.js.map +1 -1
- package/dist/chat-ui/thread/statewire-history-edge.cjs.map +1 -1
- package/dist/chat-ui/thread/statewire-history-edge.d.ts +8 -0
- package/dist/chat-ui/thread/statewire-history-edge.js.map +1 -1
- package/dist/collab/client.cjs +40 -1
- package/dist/collab/client.cjs.map +1 -1
- package/dist/collab/client.d.ts +17 -0
- package/dist/collab/client.js +40 -1
- package/dist/collab/client.js.map +1 -1
- package/dist/composer/QuoteContext.cjs +3 -3
- package/dist/composer/QuoteContext.cjs.map +1 -1
- package/dist/composer/QuoteContext.js +3 -3
- package/dist/composer/QuoteContext.js.map +1 -1
- package/dist/provider/AthenaProvider.cjs +13 -4
- package/dist/provider/AthenaProvider.cjs.map +1 -1
- package/dist/provider/AthenaProvider.js +11 -2
- package/dist/provider/AthenaProvider.js.map +1 -1
- package/dist/provider/statewire-window-context.cjs +6 -0
- package/dist/provider/statewire-window-context.cjs.map +1 -1
- package/dist/provider/statewire-window-context.d.ts +9 -0
- package/dist/provider/statewire-window-context.js +6 -0
- package/dist/provider/statewire-window-context.js.map +1 -1
- package/dist/react/package.json.cjs +1 -1
- package/dist/react/package.json.js +1 -1
- package/dist/runtime/useAthenaStatewireRuntime.cjs.map +1 -1
- package/dist/runtime/useAthenaStatewireRuntime.d.ts +6 -0
- package/dist/runtime/useAthenaStatewireRuntime.js.map +1 -1
- package/dist/styles.css +1 -1
- package/dist/threads/sessions-query.cjs +2 -0
- package/dist/threads/sessions-query.cjs.map +1 -1
- package/dist/threads/sessions-query.js +2 -0
- package/dist/threads/sessions-query.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 * A host that can read Keryx's document status with the room's grant\n * (`readDocumentStatus`) learns whether Keryx takes the room's writes for now\n * (`handle.writesRefused`): a quarantined room takes none, and its socket drops\n * every edit unconfirmed without a word (`document-status.ts`).\n */\n\nimport {\n INITIAL_SYNC_DIFF,\n INITIAL_SYNC_PARAM,\n type InitialSyncSupportStorage,\n keryxOriginOf,\n keryxRoomReadUrl,\n knownInitialSyncSupport,\n readRoomOverHttp,\n rememberInitialSyncSupport,\n} from '@athenaintel/keryx-http/initial-sync';\nimport { receiveOnlyWebSocket } from '@athenaintel/keryx-http/receive-only-socket';\nimport { UnconfirmedUpdateAttributions } from '@athenaintel/keryx-http/unconfirmed-update-attributions';\nimport {\n attributingWebSocket,\n docUpdateAttributions,\n} from '@athenaintel/keryx-http/update-attributions';\nimport { WebsocketProvider } from '@y/websocket';\nimport * as Y from '@y/y';\nimport { classifyClose } from './close-policy';\nimport { type ReadDocumentStatus, watchDocumentStatus } from './document-status';\nimport {\n type CollabAuth,\n type CollabTokenResponse,\n CollabTokenError,\n mintCollabToken,\n} from './mint';\nimport { MAX_CONSECUTIVE_REMINTS, MIN_REFRESH_DELAY_MS, refreshDelayMs } from './token-refresh';\n\nexport type GenericDocStatus =\n | 'connecting'\n | 'connected'\n | 'disconnected'\n | 'closed'\n | 'error';\n\nexport interface PresenceEntry {\n clientId: number;\n state: Record<string, unknown>;\n}\n\nexport interface GenericDocHandle {\n /** The live shared document. Owned by the handle; destroyed with it. */\n readonly doc: Y.Doc;\n readonly status: GenericDocStatus;\n /**\n * Whether the initial server sync has completed for the current connection.\n * `status === 'connected'` fires before the server state arrives, so a doc\n * read immediately after connect can still be empty — gate first reads on\n * this (or `waitForSync`).\n */\n readonly synced: boolean;\n /**\n * Whether every change made to this document has reached the server: `false` from a local edit\n * until the server sends it back (`@y/websocket`'s `syncStatus.localUpdatesSynced`; yhub echoes\n * every update to its sender). Kept across reconnects and re-mints: a replaced provider hands its\n * unconfirmed edits to the next, and an edit made between providers waits for one. A host that\n * closes the document while this is `false` loses those edits, unless a local copy keeps them.\n */\n readonly localChangesSynced: boolean;\n /** Granted access from the last successful mint. */\n readonly accessType: 'r' | 'rw' | null;\n /** Terminal error, when status is 'error' or 'closed'. */\n readonly error: Error | null;\n /**\n * Whether the document holds what the host's local copy stored (always `true` without one).\n * Mount readers after it: until then the document is still empty.\n */\n readonly prepared: boolean;\n /** Whether this host allows a live connection. Disabled documents remain editable locally. */\n readonly connectionEnabled: boolean;\n /**\n * A connection the host's `beforeConnect` held: the handle waits, sending nothing, until the\n * host calls `resume()` (or destroys the handle).\n */\n readonly held: boolean;\n /** Monotonic change counter — bumps on every status/presence notification. */\n readonly version: number;\n /**\n * Resolve once the initial server sync completes; reject on timeout, on a\n * terminal connection state, or if the handle is destroyed first.\n */\n waitForSync: (timeoutMs?: number) => Promise<void>;\n /**\n * Resolve once connected, initially synced, and every local change has been acknowledged,\n * including any edits the local-copy hook restores after sync. The host must prevent further\n * editing while saving a checkpoint. Reject on timeout, a disabled connection, or a terminal state.\n */\n waitForAcknowledged: (timeoutMs?: number) => Promise<void>;\n getPresence: () => PresenceEntry[];\n /** Broadcast this client's presence state (requires a live connection). */\n setPresence: (state: Record<string, unknown> | null) => void;\n /**\n * Force an early token refresh. Session-preserving: the live connection\n * stays up until the fresh token is minted; a failed mint retries on a\n * short timer instead of dropping the session. Without a connection it\n * reconnects now.\n */\n refreshNow: () => Promise<void>;\n /**\n * Disable all connections without losing the document or its pending edits. Enabling mints a\n * fresh grant and runs the host's beforeConnect gate; it never bypasses a permission or review.\n */\n setConnectionEnabled: (enabled: boolean) => void;\n /** Connect past a hold, without asking `beforeConnect` again. */\n resume: () => void;\n /** Local edits the server has not echoed yet (handed between providers too), or `null`. */\n unconfirmedEdits: () => Y.ContentIds | null;\n /**\n * Keryx's document status, as last read with the room's grant, says the room takes no writes for\n * now: it is quarantined while it is repaired, and its socket drops every edit unconfirmed until\n * it is released. Always `false` without `readDocumentStatus`, on a read-only grant, and whenever\n * the last read could not answer.\n */\n readonly writesRefused: boolean;\n onChange: (listener: () => void) => () => void;\n destroy: () => void;\n}\n\n/**\n * Issues a room-bound Keryx token for one asset. The default calls the public\n * `/collab-token` route with the handle's `auth`; a host with its own trusted\n * mint (a desktop app's main process holding the user's key) passes one\n * instead, and the handle uses it for the first mint and every re-mint.\n */\nexport type CollabMint = (params: {\n assetId: string;\n access: 'view' | 'edit';\n}) => Promise<CollabTokenResponse>;\n\n/** What a host's local copy reads of the handle's transport. */\nexport interface GenericDocTransportView {\n /** True for a transaction the transport applied (the server's state, a peer's edit). */\n isRemoteOrigin: (origin: unknown) => boolean;\n /** Local edits the server has not echoed yet, or `null`. */\n getUnconfirmed: () => Y.ContentIds | null;\n /** Connected, past the initial sync, and nothing unconfirmed. */\n isFullySynced: () => boolean;\n}\n\n/** What `beforeConnect` is asked about. */\nexport interface GenericDocConnectGate {\n /** The grant the connection would use (its access is the server's current verdict). */\n grant: CollabTokenResponse;\n /** The handle has not connected yet. */\n firstConnection: boolean;\n /** How long the handle had been without a connection, when it had one before. */\n offlineForMs: number | null;\n /** Local edits made without a connection (or inherited from an earlier session) wait to be sent. */\n hasUnsyncedEdits: boolean;\n}\n\n/** A host's local copy of the document (`@athenaintel/local-copy` behind a host's glue). */\nexport interface GenericDocLocalCopy {\n /**\n * Called once, before the first mint: apply the stored copy to `doc` and return the local edits\n * it holds that the server never acknowledged. The handle sends them and waits for their echo\n * like its own. A failure here must resolve `{ unsyncedEdits: null }`: the handle then runs\n * without a copy.\n */\n prepare: (params: {\n doc: Y.Doc;\n transport: GenericDocTransportView;\n }) => Promise<{ unsyncedEdits: Y.ContentIds | null }>;\n /** The handle's unconfirmed edits or sync state changed. */\n transportChanged: () => void;\n /**\n * An explicit host pause/resume policy changed. Invalidate decisions that must be checked afresh\n * before a later manual save. A pause runs after its provider is destroyed and its status is\n * disconnected, so edits restored by the hook stay local. A resume runs before minting.\n * Network retries and an immediate conflict `resume()` do not call it.\n */\n connectionPolicyChanged?: (enabled: boolean) => void;\n /**\n * Asked after each mint and before the connection it would open: the first connection, a\n * reconnect after an outage longer than `offlineGateAfterMs`, and a re-mint after a revocation\n * (never a scheduled token refresh of a live connection, never past `resume()`). The host\n * checks what it must before anything is sent (the document still opens here; access; edits\n * made without a connection against the server's). `'hold'` keeps the handle from connecting\n * until `resume()`; a throw counts as \"not yet\" and is asked again on the next attempt.\n */\n beforeConnect?: (gate: GenericDocConnectGate) => Promise<'connect' | 'hold'>;\n}\n\n/** After this long without a socket, the handle reconnects itself (re-mint, gate) instead of the provider. */\nexport const DEFAULT_OFFLINE_GATE_AFTER_MS = 15_000;\n\n/** Retry delays for a mint that failed for want of the network. */\nconst MINT_RETRY_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 15_000, 30_000, 60_000];\n\n/**\n * The default `retryMintError`: a network failure, a timeout, a rate limit or a server error is\n * worth retrying; a refusal (401/403/404) is the server's verdict and ends the handle.\n */\nexport function isRetryableMintError(error: unknown): boolean {\n if (error instanceof CollabTokenError) {\n return error.status >= 500 || error.status === 408 || error.status === 429;\n }\n return error instanceof TypeError || (error instanceof DOMException && error.name === 'TimeoutError');\n}\n\nfunction resolveMint({ auth, mint }: { auth?: CollabAuth; mint?: CollabMint }): CollabMint {\n if (mint) return mint;\n if (!auth) throw new Error('connectGenericDoc needs `auth` or `mint`');\n return ({ assetId, access }) => mintCollabToken({ auth, assetId, access });\n}\n\n/**\n * The socket a provider for `grant` opens (`@athenaintel/keryx-http`'s wrappers, the ones\n * Olympus's rooms use). On a read-write grant, each sync update a write made inside a\n * `runWithDocUpdateAttributions` scope for `doc` sends carries the scope's attributions, which\n * Keryx reads after the update (`origin: background` counts as system work; a Keryx that predates\n * the trailer ignores it), and its sync step 2 goes out behind such writes made while no socket\n * was open, each as its own marked update (`unconfirmed`). On a read-only grant no frame that\n * carries document content leaves: a sync step 2 or an update is dropped (Keryx ignores them on\n * such a grant anyway), awareness passes. Read when each provider is built, as `@y/websocket` reads\n * `WebSocket`; `undefined` where there is none, and the provider fails at connect as it always did.\n */\nfunction socketFor({\n grant,\n doc,\n unconfirmed,\n}: {\n grant: CollabTokenResponse;\n doc: Y.Doc;\n unconfirmed: UnconfirmedUpdateAttributions;\n}): typeof WebSocket | undefined {\n const Base: typeof WebSocket | undefined = globalThis.WebSocket;\n if (typeof Base !== 'function') return undefined;\n if (grant.access_type === 'r') return receiveOnlyWebSocket({ Base });\n return attributingWebSocket({\n Base,\n attributionsFor: () => docUpdateAttributions(doc),\n unconfirmed,\n });\n}\n\n/** How an HTTP-first read went (`connectGenericDoc`'s `httpFirstOpen`). */\nexport interface GenericDocHttpFirstOpenEvent {\n /**\n * `read`: read over HTTP and applied; the socket asks for the diff. `unsupported`: Keryx answered\n * without saying it answers a socket's sync step 1; its document was not used. `failed`: the read\n * failed (`error` says why). `skipped`: Keryx is known not to answer, so nothing was read.\n * `aborted`: the room replaced or closed the provider during the read, which it stopped.\n */\n outcome: 'read' | 'unsupported' | 'failed' | 'skipped' | 'aborted';\n /** The decoded body's size (`read`, `unsupported`). */\n bytes?: number;\n /** From the request to the socket's connect. */\n durationMs: number;\n /** Why the read failed (`failed`): the error's name and message. */\n error?: string;\n}\n\n/** How long an HTTP-first read may take before the room falls back to the socket's whole-document sync. */\nconst HTTP_FIRST_READ_TIMEOUT_MS = 60_000;\n\n/** `localStorage`, when the host has one (a browser, Electron's renderer, the phone's editor page). */\nfunction browserStorage(): InitialSyncSupportStorage | null {\n try {\n return typeof window !== 'undefined' && window.localStorage ? window.localStorage : null;\n } catch {\n return null;\n }\n}\n\nexport function connectGenericDoc(args: {\n assetId: string;\n /** Credentials for the default mint; not used when `mint` is given. */\n auth?: CollabAuth;\n access?: 'view' | 'edit';\n mint?: CollabMint;\n /** A local copy of the document the host keeps (see {@link GenericDocLocalCopy}). */\n localCopy?: GenericDocLocalCopy;\n /** Whether a failed mint is worth retrying; defaults to {@link isRetryableMintError}. */\n retryMintError?: (error: unknown) => boolean;\n /** See {@link DEFAULT_OFFLINE_GATE_AFTER_MS}. */\n offlineGateAfterMs?: number;\n /** Start without connecting or minting (for a host's manual-save mode). Defaults to true. */\n connectionEnabled?: boolean;\n /**\n * Reads Keryx's document status with the room's grant (see `ReadDocumentStatus`), for\n * `handle.writesRefused`. A host that cannot read it leaves it out.\n */\n readDocumentStatus?: ReadDocumentStatus;\n /**\n * Open the room HTTP-first (Word at scale), as Olympus opens a Word room: a document that holds\n * nothing yet is read over `GET /ydoc` (compressed, decoded as it downloads), applied as Keryx's\n * own state, and the socket asks Keryx for only what it still lacks (`?initialSync=diff`) - when\n * Keryx says it answers that way (`@athenaintel/keryx-http/initial-sync`). Every later socket of\n * the room asks for the diff too while Keryx is known to answer and the room holds no write Keryx\n * has not echoed. For rooms whose documents can be large (Word documents).\n */\n httpFirstOpen?: boolean;\n /** Hears how each HTTP-first read went (`httpFirstOpen`), for the host's telemetry. */\n onHttpFirstOpen?: (event: GenericDocHttpFirstOpenEvent) => void;\n}): GenericDocHandle {\n const access = args.access ?? 'view';\n const mint = resolveMint({ auth: args.auth, mint: args.mint });\n const localCopy = args.localCopy;\n const retryMintError = args.retryMintError ?? isRetryableMintError;\n const offlineGateAfterMs = args.offlineGateAfterMs ?? DEFAULT_OFFLINE_GATE_AFTER_MS;\n const doc = new Y.Doc();\n // Writes made in a `runWithDocUpdateAttributions` scope, until Keryx acknowledges them: the\n // sockets every provider opens send those made while no socket was open ahead of their sync.\n const unconfirmedAttributions = new UnconfirmedUpdateAttributions({\n doc,\n attributionsFor: () => docUpdateAttributions(doc),\n isRemoteOrigin: (origin) => origin instanceof WebsocketProvider,\n });\n const listeners = new Set<() => void>();\n\n let provider: WebsocketProvider | null = null;\n let refreshTimer: ReturnType<typeof setTimeout> | null = null;\n let retryTimer: ReturnType<typeof setTimeout> | null = null;\n let offlineTimer: ReturnType<typeof setTimeout> | null = null;\n /** The provider whose socket was still opening, with nothing to send, at the threshold. */\n let openingPastThreshold: WebsocketProvider | null = null;\n let mintRetries = 0;\n let destroyed = false;\n let connectionEnabled = args.connectionEnabled ?? true;\n let status: GenericDocStatus = connectionEnabled ? 'connecting' : 'disconnected';\n let synced = false;\n let accessType: 'r' | 'rw' | null = null;\n let error: Error | null = null;\n let lastPresence: Record<string, unknown> | null = null;\n let version = 0;\n let consecutiveRemints = 0;\n let prepared = localCopy === undefined;\n let held = false;\n let heldGrant: CollabTokenResponse | null = null;\n let everConnected = false;\n let disconnectedSince: number | null = null;\n /** Bumped by every connect attempt: an attempt that finds it changed after an await stops. */\n let connectSeq = 0;\n /** Local edits no provider holds: handed on by a replaced provider, or made with none. */\n let carriedUpdates: WebsocketProvider['unconfirmedUpdates'] = [];\n let localChangesSynced = true;\n /** The grant the current provider connects with. */\n let liveGrant: CollabTokenResponse | null = null;\n /** Keryx's auth re-check closed the socket (4401): the next connection reads the document status. */\n let readStatusOnConnect = false;\n /** This room saw its Keryx say it answers a socket's sync step 1 (its HTTP-first read). */\n let keryxAnswersSyncStep1 = false;\n /**\n * The HTTP-first read of a provider's document, while it runs: that provider is opening, and\n * replacing it (a re-mint, the offline takeover, `setConnectionEnabled(false)`, `destroy()`) stops\n * the download.\n */\n let httpFirstRead: { target: WebsocketProvider; controller: AbortController } | null = null;\n\n const notify = () => {\n version += 1;\n for (const listener of listeners) listener();\n };\n\n const documentStatus = args.readDocumentStatus\n ? watchDocumentStatus({\n read: args.readDocumentStatus,\n currentGrant: () => liveGrant,\n onChange: () => {\n if (!destroyed) notify();\n },\n })\n : null;\n\n const unconfirmedEdits = (): Y.ContentIds | null => {\n const all = [...carriedUpdates, ...(provider?.unconfirmedUpdates ?? [])].map(\n (entry) => entry.ids as Y.ContentIds\n );\n if (all.length === 0) return null;\n return all.length === 1 ? (all[0] as Y.ContentIds) : Y.mergeContentIds(all);\n };\n\n const transport: GenericDocTransportView = {\n isRemoteOrigin: (origin) => origin instanceof WebsocketProvider,\n getUnconfirmed: unconfirmedEdits,\n isFullySynced: () => status === 'connected' && synced && localChangesSynced,\n };\n\n const transportChanged = () => {\n localCopy?.transportChanged();\n };\n\n const refreshLocalChangesSynced = () => {\n const next = carriedUpdates.length === 0 && (provider?.unconfirmedUpdates.length ?? 0) === 0;\n const changed = next !== localChangesSynced;\n localChangesSynced = next;\n documentStatus?.unconfirmedChanged(!next);\n // After the flag: the copy reads `isFullySynced()` in its callback.\n // Before notifying: the callback can restore values and create more unconfirmed edits.\n transportChanged();\n if (changed) notify();\n };\n\n // An edit made while no provider exists (a re-mint in flight, offline) is sent by the next one,\n // which takes it as unconfirmed. The local copy's own load is not an edit.\n doc.on('update', (update: Uint8Array, origin: unknown) => {\n if (!prepared || provider !== null || destroyed || origin instanceof WebsocketProvider) return;\n carriedUpdates = [\n ...carriedUpdates,\n { created: Date.now(), ids: Y.createContentIdsFromUpdate(update) },\n ];\n refreshLocalChangesSynced();\n });\n\n const setStatus = (next: GenericDocStatus, err: Error | null = null) => {\n if (destroyed && next !== 'closed') return;\n const wasConnected = status === 'connected';\n status = next;\n error = err;\n if (next === 'connected') {\n everConnected = true;\n disconnectedSince = null;\n clearOfflineTimer();\n } else {\n if (wasConnected || (everConnected && disconnectedSince === null)) {\n disconnectedSince = Date.now();\n }\n documentStatus?.disconnected();\n }\n transportChanged();\n notify();\n };\n\n const clearRefreshTimer = () => {\n if (refreshTimer !== null) {\n clearTimeout(refreshTimer);\n refreshTimer = null;\n }\n };\n\n const clearRetryTimer = () => {\n if (retryTimer !== null) {\n clearTimeout(retryTimer);\n retryTimer = null;\n }\n };\n\n function clearOfflineTimer() {\n if (offlineTimer !== null) {\n clearTimeout(offlineTimer);\n offlineTimer = null;\n }\n }\n\n const teardownProvider = () => {\n clearRefreshTimer();\n // A future provider must complete its own initial sync; the doc keeps its\n // content either way. Subscribers must observe the flip immediately —\n // waiting for the next provider event would let them act on synced=true\n // across the replacement gap.\n if (synced) {\n synced = false;\n notify();\n }\n if (provider) {\n // Its unconfirmed edits outlive it: the next provider sends them and waits for their echo.\n const previous = provider;\n provider = null;\n if (httpFirstRead?.target === previous) {\n httpFirstRead.controller.abort(new DOMException('The room closed', 'AbortError'));\n httpFirstRead = null;\n }\n carriedUpdates = [...carriedUpdates, ...previous.unconfirmedUpdates];\n previous.destroy();\n }\n };\n\n const scheduleRefresh = (grant: CollabTokenResponse) => {\n clearRefreshTimer();\n const delay = refreshDelayMs({ expiresAtMs: grant.expires_at_ms, now: Date.now() });\n refreshTimer = setTimeout(() => {\n void connect({ scheduledRefresh: true });\n }, delay);\n };\n\n /** A failed attempt that is worth retrying: try again later, or as soon as the network returns. */\n const scheduleRetry = () => {\n clearRetryTimer();\n const delay = MINT_RETRY_DELAYS_MS[Math.min(mintRetries, MINT_RETRY_DELAYS_MS.length - 1)];\n mintRetries += 1;\n retryTimer = setTimeout(() => {\n retryTimer = null;\n void connect();\n }, delay);\n };\n\n const onBrowserOnline = () => {\n // Only a handle waiting to retry: a refused or permanently closed one stays stopped.\n if (\n destroyed || !connectionEnabled || status === 'closed' || status === 'error' ||\n provider !== null || held\n ) return;\n mintRetries = 0;\n clearRetryTimer();\n void connect();\n };\n if (typeof window !== 'undefined') window.addEventListener('online', onBrowserOnline);\n\n /**\n * Past the gate's threshold without a socket, the handle reconnects itself (re-mint, gate). A\n * socket still being opened with nothing waiting to be sent is left to finish (a slow network\n * is not restarted every threshold), and the handle looks again a threshold later; if it opens\n * holding edits made since, they go through the gate first (`status`).\n */\n const armOfflineTakeover = () => {\n if (!connectionEnabled || offlineTimer !== null || !localCopy?.beforeConnect) return;\n offlineTimer = setTimeout(() => {\n offlineTimer = null;\n if (destroyed || !connectionEnabled || status === 'connected' || provider === null) return;\n // A provider reading its document over HTTP first is opening too (a long report, a slow link)\n if ((provider.wsconnecting || httpFirstRead?.target === provider) && !hasUnsyncedLocalEdits()) {\n openingPastThreshold = provider;\n armOfflineTakeover();\n return;\n }\n teardownProvider();\n void connect();\n }, offlineGateAfterMs);\n };\n\n const hasUnsyncedLocalEdits = () =>\n carriedUpdates.length > 0 || (provider?.unconfirmedUpdates.length ?? 0) > 0;\n\n\n const connect = async (opts?: {\n scheduledRefresh?: boolean;\n skipGate?: boolean;\n grant?: CollabTokenResponse;\n }): Promise<void> => {\n if (destroyed || !connectionEnabled) return;\n const seq = ++connectSeq;\n await preparing;\n if (destroyed || !connectionEnabled || seq !== connectSeq) return;\n // Only a live connection is refreshed in place (and skips the host's gate); a refresh while the\n // socket is down is a reconnect like any other.\n const scheduledRefresh = opts?.scheduledRefresh === true && status === 'connected';\n // A scheduled refresh mints FIRST and keeps the live session up: the old\n // token has ~5 minutes of headroom, so a transient mint failure retries\n // on a short timer instead of dropping a healthy connection.\n if (!scheduledRefresh) {\n teardownProvider();\n } else {\n clearRefreshTimer();\n }\n clearRetryTimer();\n if (destroyed || !connectionEnabled || seq !== connectSeq) return;\n let grant: CollabTokenResponse;\n if (opts?.grant && opts.grant.expires_at_ms - Date.now() > MIN_REFRESH_DELAY_MS) {\n grant = opts.grant;\n } else {\n try {\n grant = await mint({ assetId: args.assetId, access });\n } catch (err) {\n if (destroyed || !connectionEnabled || seq !== connectSeq) return;\n if (scheduledRefresh) {\n refreshTimer = setTimeout(() => {\n void connect({ scheduledRefresh: true });\n }, MIN_REFRESH_DELAY_MS);\n return;\n }\n if (retryMintError(err)) {\n // Offline (or the mint's server is): keep the document and try again.\n if (status !== 'disconnected') setStatus('disconnected');\n scheduleRetry();\n return;\n }\n // A denied mint is authoritative (revoked / not shared / not eligible).\n setStatus('error', err instanceof Error ? err : new Error(String(err)));\n return;\n }\n }\n if (destroyed || !connectionEnabled || seq !== connectSeq) return;\n mintRetries = 0;\n accessType = grant.access_type;\n const beforeConnect = localCopy?.beforeConnect;\n if (beforeConnect && !scheduledRefresh && !opts?.skipGate) {\n const firstConnection = !everConnected;\n const offlineForMs = disconnectedSince === null ? null : Date.now() - disconnectedSince;\n let decision: 'connect' | 'hold';\n try {\n decision = await beforeConnect({\n grant,\n firstConnection,\n offlineForMs,\n hasUnsyncedEdits: hasUnsyncedLocalEdits(),\n });\n } catch {\n if (destroyed || !connectionEnabled || seq !== connectSeq) return;\n if (status !== 'disconnected') setStatus('disconnected');\n scheduleRetry();\n return;\n }\n if (destroyed || !connectionEnabled || seq !== connectSeq) return;\n if (decision === 'hold') {\n held = true;\n heldGrant = grant;\n if (status !== 'disconnected') setStatus('disconnected');\n else notify();\n return;\n }\n }\n if (scheduledRefresh) {\n teardownProvider();\n }\n if (destroyed || !connectionEnabled || seq !== connectSeq) return;\n\n const socket = socketFor({ grant, doc, unconfirmed: unconfirmedAttributions });\n const roomUrl = `${grant.ws_url}/${grant.org}/${grant.doc_id}`;\n // Word at scale: a document that holds nothing yet is read over HTTP first, then the socket connects\n const httpFirstUrl =\n args.httpFirstOpen === true && doc.store.clients.size === 0 && carriedUpdates.length === 0\n ? keryxRoomReadUrl({ wsUrl: roomUrl, token: grant.token, branch: grant.branch })\n : null;\n const params: Record<string, string> = {\n yauth: grant.token,\n branch: grant.branch,\n gc: 'true',\n };\n if (httpFirstUrl === null && asksForDiffedSync({ roomUrl, unconfirmed: carriedUpdates.length })) {\n params[INITIAL_SYNC_PARAM] = INITIAL_SYNC_DIFF;\n }\n const nextProvider = new WebsocketProvider(grant.ws_url, `${grant.org}/${grant.doc_id}`, doc, {\n params,\n // BroadcastChannel would sync same-origin clients locally, bypassing the\n // server's permission enforcement (a read-only tab could write into an\n // editor tab's doc). Permissioned docs must round-trip the server.\n disableBc: true,\n connect: httpFirstUrl === null,\n ...(socket && { WebSocketPolyfill: socket }),\n });\n provider = nextProvider;\n liveGrant = grant;\n nextProvider.unconfirmedUpdates = [...carriedUpdates, ...nextProvider.unconfirmedUpdates];\n carriedUpdates = [];\n refreshLocalChangesSynced();\n\n nextProvider.on('sync-status', () => {\n if (provider !== nextProvider) return;\n refreshLocalChangesSynced();\n });\n\n nextProvider.on('status', (event: { status: 'connecting' | 'connected' | 'disconnected' }) => {\n if (provider !== nextProvider) return;\n if (\n event.status === 'connected' &&\n openingPastThreshold === nextProvider &&\n hasUnsyncedLocalEdits()\n ) {\n // Opened after the threshold holding edits made meanwhile: before its handshake sends\n // them (`@y/websocket` reports `connected` first), they go through the gate.\n teardownProvider();\n void connect();\n return;\n }\n // The connections that read Keryx's document status at once: the first, the one after an auth\n // re-check close, and one after an outage the handle treats as real. Never an ordinary\n // reconnect (a Keryx deploy reconnects every room at once).\n const readStatusNow =\n event.status === 'connected' &&\n (!everConnected ||\n readStatusOnConnect ||\n (disconnectedSince !== null && Date.now() - disconnectedSince >= offlineGateAfterMs));\n if (event.status === 'connected') {\n consecutiveRemints = 0;\n readStatusOnConnect = false;\n }\n setStatus(event.status);\n if (event.status === 'connected') documentStatus?.connected({ readNow: readStatusNow });\n if (event.status === 'connected' && lastPresence !== null) {\n nextProvider.awareness.setLocalState(lastPresence);\n }\n // `@y/websocket` reports `disconnected` only for a socket that had opened: one that never\n // opens (the server unreachable while the mint goes through) only ever reports `connecting`,\n // and is just as offline.\n if (event.status !== 'connected') armOfflineTakeover();\n });\n // Its first `connecting` came from its constructor, before this listener existed.\n if (!nextProvider.wsconnected) armOfflineTakeover();\n\n nextProvider.on('sync', (state: boolean) => {\n if (provider !== nextProvider) return;\n if (synced !== state) {\n synced = state;\n transportChanged();\n notify();\n }\n });\n\n nextProvider.on('connection-close', (event: CloseEvent | null) => {\n if (provider !== nextProvider) return;\n // The next socket asks for a diffed initial sync only while nothing it holds needs Keryx's whole document\n if (asksForDiffedSync({ roomUrl, unconfirmed: nextProvider.unconfirmedUpdates.length })) {\n nextProvider.params[INITIAL_SYNC_PARAM] = INITIAL_SYNC_DIFF;\n } else {\n delete nextProvider.params[INITIAL_SYNC_PARAM];\n }\n const action = classifyClose(event?.code);\n if (action === 'remint') {\n // Revoked mid-session: a fresh mint re-runs the server-side permission\n // check. If access is truly gone the mint 403s and we land in 'error'.\n // Bounded: repeated 4401s without an intervening successful connect\n // mean the server keeps rejecting freshly minted tokens — stop rather\n // than loop mint→connect→kick.\n consecutiveRemints += 1;\n // A quarantine and a release both close the room's sockets this way, once Keryx has written\n // or cleared the marker: the reconnected socket learns which. Until then nothing is read\n // (the handle stays `connected` through the re-mint, on a grant Keryx just bounced).\n readStatusOnConnect = true;\n documentStatus?.disconnected();\n teardownProvider();\n if (consecutiveRemints > MAX_CONSECUTIVE_REMINTS) {\n setStatus(\n 'closed',\n new Error('Access repeatedly revoked mid-session (4401); giving up.')\n );\n return;\n }\n void connect();\n } else if (action === 'stop') {\n teardownProvider();\n setStatus(\n 'closed',\n new Error(`Connection closed permanently (code ${event?.code ?? 'unknown'})`)\n );\n }\n // 'retry': the provider's exponential backoff handles it, until the offline takeover.\n });\n\n nextProvider.awareness.on('change', () => {\n if (provider !== nextProvider) return;\n notify();\n });\n\n scheduleRefresh(grant);\n if (httpFirstUrl !== null) void openOverHttp({ target: nextProvider, url: httpFirstUrl, roomUrl });\n };\n\n /**\n * Word at scale: whether a socket of this room asks for a diffed initial sync - a room that opens\n * HTTP-first, whose Keryx is known to answer it, whose document holds something, and that holds no\n * write Keryx may hold without having echoed it (an unconfirmed update, a kept attributed write):\n * those are confirmed by the whole document Keryx sends when a socket opens.\n */\n function asksForDiffedSync({ roomUrl, unconfirmed }: { roomUrl: string; unconfirmed: number }): boolean {\n if (args.httpFirstOpen !== true) return false;\n const origin = keryxOriginOf(roomUrl);\n const known =\n keryxAnswersSyncStep1 ||\n (origin !== null && knownInitialSyncSupport({ storage: browserStorage(), origin }) === true);\n return known && doc.store.clients.size > 0 && unconfirmed === 0 && !unconfirmedAttributions.keepsWrites;\n }\n\n /**\n * Word at scale: read the room over HTTP, apply it as Keryx's own state (the provider's origin, so\n * nothing treats it as a local edit), then connect the provider's socket, asking for the diff when\n * Keryx said it answers that way. A Keryx that did not, a failed read, or a provider replaced\n * meanwhile: the document is left as it was and the socket connects as every room's does.\n */\n async function openOverHttp({\n target,\n url,\n roomUrl,\n }: {\n target: WebsocketProvider;\n url: string;\n roomUrl: string;\n }): Promise<void> {\n const started = performance.now();\n const origin = keryxOriginOf(roomUrl);\n const storage = browserStorage();\n let event: GenericDocHttpFirstOpenEvent;\n if (origin !== null && knownInitialSyncSupport({ storage, origin }) === false) {\n event = { outcome: 'skipped', durationMs: 0 };\n } else {\n const controller = new AbortController();\n httpFirstRead = { target, controller };\n const timeout = setTimeout(\n () => controller.abort(new DOMException('The HTTP-first read timed out', 'TimeoutError')),\n HTTP_FIRST_READ_TIMEOUT_MS\n );\n try {\n const read = await readRoomOverHttp({ url, signal: controller.signal });\n if (origin !== null) rememberInitialSyncSupport({ storage, origin, supported: read.answersSyncStep1 });\n if (read.answersSyncStep1 && provider === target && !destroyed) {\n if (read.update.byteLength > 2) Y.applyUpdate(doc, read.update, target);\n keryxAnswersSyncStep1 = true;\n }\n event = {\n outcome: read.answersSyncStep1 ? 'read' : 'unsupported',\n bytes: read.bytes,\n durationMs: performance.now() - started,\n };\n } catch (err) {\n // the socket's whole-document sync, as before; a read the room stopped is no failure\n event =\n controller.signal.aborted && (destroyed || provider !== target)\n ? { outcome: 'aborted', durationMs: performance.now() - started }\n : {\n outcome: 'failed',\n durationMs: performance.now() - started,\n error: err instanceof Error ? `${err.name}: ${err.message}` : String(err),\n };\n } finally {\n clearTimeout(timeout);\n if (httpFirstRead?.controller === controller) httpFirstRead = null;\n }\n }\n try {\n args.onHttpFirstOpen?.(event);\n } catch {\n // a host's telemetry never keeps the room from opening its socket\n }\n if (destroyed || provider !== target) return;\n if (asksForDiffedSync({ roomUrl, unconfirmed: target.unconfirmedUpdates.length })) {\n target.params[INITIAL_SYNC_PARAM] = INITIAL_SYNC_DIFF;\n } else {\n delete target.params[INITIAL_SYNC_PARAM];\n }\n target.connect();\n }\n\n const preparing: Promise<void> = localCopy\n ? localCopy\n .prepare({ doc, transport })\n .catch(() => ({ unsyncedEdits: null }))\n .then(({ unsyncedEdits }) => {\n if (destroyed) return;\n if (unsyncedEdits && !(unsyncedEdits.inserts.isEmpty() && unsyncedEdits.deletes.isEmpty())) {\n carriedUpdates = [...carriedUpdates, { created: Date.now(), ids: unsyncedEdits }];\n }\n prepared = true;\n refreshLocalChangesSynced();\n notify();\n })\n : Promise.resolve();\n\n void connect();\n\n const waitForSync = (timeoutMs = 15_000): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n const terminal = (): Error | null => {\n if (destroyed) return new Error('Handle destroyed before initial sync');\n if (status === 'closed' || status === 'error') {\n return error ?? new Error(`Connection ${status} before initial sync`);\n }\n return null;\n };\n if (synced) {\n resolve();\n return;\n }\n const immediate = terminal();\n if (immediate) {\n reject(immediate);\n return;\n }\n const cleanup = () => {\n clearTimeout(timer);\n listeners.delete(listener);\n };\n const timer = setTimeout(() => {\n cleanup();\n reject(new Error(`Timed out after ${timeoutMs}ms waiting for initial sync`));\n }, timeoutMs);\n const listener = () => {\n if (synced) {\n cleanup();\n resolve();\n return;\n }\n const err = terminal();\n if (err) {\n cleanup();\n reject(err);\n }\n };\n listeners.add(listener);\n });\n\n const waitForAcknowledged = (timeoutMs = 15_000): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n let finished = false;\n let checkQueued = false;\n let timer: ReturnType<typeof setTimeout> | null = null;\n const finish = (failure?: Error) => {\n if (finished) return;\n finished = true;\n if (timer !== null) clearTimeout(timer);\n listeners.delete(check);\n if (failure) reject(failure);\n else resolve();\n };\n const check = () => {\n if (finished || checkQueued) return;\n checkQueued = true;\n // All synchronous transport hooks and change listeners finish before a save settles.\n queueMicrotask(() => {\n checkQueued = false;\n if (finished) return;\n if (destroyed) {\n finish(new Error('Handle destroyed before local changes were acknowledged'));\n } else if (!connectionEnabled) {\n finish(new Error('Connection disabled before local changes were acknowledged'));\n } else if (status === 'closed' || status === 'error') {\n finish(error ?? new Error(`Connection ${status} before local changes were acknowledged`));\n } else if (prepared && status === 'connected' && synced && localChangesSynced) {\n finish();\n }\n });\n };\n timer = setTimeout(() => {\n finish(new Error(`Timed out after ${timeoutMs}ms waiting for local changes to be acknowledged`));\n }, timeoutMs);\n listeners.add(check);\n check();\n });\n\n return {\n doc,\n get status() {\n return status;\n },\n get synced() {\n return synced;\n },\n get localChangesSynced() {\n return localChangesSynced;\n },\n get accessType() {\n return accessType;\n },\n get error() {\n return error;\n },\n get prepared() {\n return prepared;\n },\n get connectionEnabled() {\n return connectionEnabled;\n },\n get held() {\n return held;\n },\n get version() {\n return version;\n },\n get writesRefused() {\n return documentStatus?.writesRefused ?? false;\n },\n waitForSync,\n waitForAcknowledged,\n getPresence: () => {\n if (!provider) return [];\n const entries: PresenceEntry[] = [];\n provider.awareness.getStates().forEach((state, clientId) => {\n entries.push({ clientId, state: state as Record<string, unknown> });\n });\n return entries;\n },\n setPresence: (state) => {\n lastPresence = state;\n provider?.awareness.setLocalState(state);\n },\n refreshNow: () => {\n if (!connectionEnabled || held) return Promise.resolve();\n return provider ? connect({ scheduledRefresh: true }) : connect();\n },\n setConnectionEnabled: (enabled) => {\n if (destroyed || enabled === connectionEnabled) return;\n connectionEnabled = enabled;\n if (!enabled) {\n // Invalidate every mint/gate already in flight before tearing down the live provider.\n connectSeq += 1;\n clearRetryTimer();\n clearOfflineTimer();\n teardownProvider();\n setStatus('disconnected');\n localCopy?.connectionPolicyChanged?.(false);\n return;\n }\n localCopy?.connectionPolicyChanged?.(true);\n held = false;\n heldGrant = null;\n setStatus('connecting');\n void connect();\n },\n resume: () => {\n if (!held || destroyed || !connectionEnabled) return;\n held = false;\n const grant = heldGrant;\n heldGrant = null;\n notify();\n void connect({ skipGate: true, grant: grant ?? undefined });\n },\n unconfirmedEdits,\n onChange: (listener) => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n destroy: () => {\n if (destroyed) return;\n destroyed = true;\n documentStatus?.destroy();\n teardownProvider();\n clearRetryTimer();\n clearOfflineTimer();\n if (typeof window !== 'undefined') window.removeEventListener('online', onBrowserOnline);\n status = 'closed';\n // Final notification so pending waitForSync callers reject instead of\n // hanging on listeners that are about to be dropped.\n for (const listener of [...listeners]) listener();\n listeners.clear();\n unconfirmedAttributions.destroy();\n doc.destroy();\n },\n };\n}\n\nexport { CollabTokenError };\nexport type { CollabAuth, CollabTokenResponse };\n"],"names":[],"mappings":";;;;;;;;;;AA2NO,MAAM,gCAAgC;AAG7C,MAAM,uBAAuB,CAAC,KAAO,KAAO,KAAO,KAAO,MAAQ,KAAQ,GAAM;AAMzE,SAAS,qBAAqB,OAAyB;AAC5D,MAAI,iBAAiB,kBAAkB;AACrC,WAAO,MAAM,UAAU,OAAO,MAAM,WAAW,OAAO,MAAM,WAAW;AAAA,EACzE;AACA,SAAO,iBAAiB,aAAc,iBAAiB,gBAAgB,MAAM,SAAS;AACxF;AAEA,SAAS,YAAY,EAAE,MAAM,QAA8D;AACzF,MAAI,KAAM,QAAO;AACjB,MAAI,CAAC,KAAM,OAAM,IAAI,MAAM,0CAA0C;AACrE,SAAO,CAAC,EAAE,SAAS,OAAA,MAAa,gBAAgB,EAAE,MAAM,SAAS,QAAQ;AAC3E;AAaA,SAAS,UAAU;AAAA,EACjB;AAAA,EACA;AAAA,EACA;AACF,GAIiC;AAC/B,QAAM,OAAqC,WAAW;AACtD,MAAI,OAAO,SAAS,WAAY,QAAO;AACvC,MAAI,MAAM,gBAAgB,YAAY,qBAAqB,EAAE,MAAM;AACnE,SAAO,qBAAqB;AAAA,IAC1B;AAAA,IACA,iBAAiB,MAAM,sBAAsB,GAAG;AAAA,IAChD;AAAA,EAAA,CACD;AACH;AAoBA,MAAM,6BAA6B;AAGnC,SAAS,iBAAmD;AAC1D,MAAI;AACF,WAAO,OAAO,WAAW,eAAe,OAAO,eAAe,OAAO,eAAe;AAAA,EACtF,QAAQ;AACN,WAAO;AAAA,EACT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,yBAAA;AACA,kBAAU,cAAc;AACxB,qDAAW,4BAAX,mCAAqC;AACrC;AAAA,MACF;AACA,mDAAW,4BAAX,mCAAqC;AACrC,aAAO;AACP,kBAAY;AACZ,gBAAU,YAAY;AACtB,WAAK,QAAA;AAAA,IACP;AAAA,IACA,QAAQ,MAAM;AACZ,UAAI,CAAC,QAAQ,aAAa,CAAC,kBAAmB;AAC9C,aAAO;AACP,YAAM,QAAQ;AACd,kBAAY;AACZ,aAAA;AACA,WAAK,QAAQ,EAAE,UAAU,MAAM,OAAO,SAAS,QAAW;AAAA,IAC5D;AAAA,IACA;AAAA,IACA,UAAU,CAAC,aAAa;AACtB,gBAAU,IAAI,QAAQ;AACtB,aAAO,MAAM;AACX,kBAAU,OAAO,QAAQ;AAAA,MAC3B;AAAA,IACF;AAAA,IACA,SAAS,MAAM;AACb,UAAI,UAAW;AACf,kBAAY;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 * A host that can read Keryx's document status with the room's grant\n * (`readDocumentStatus`) learns whether Keryx takes the room's writes for now\n * (`handle.writesRefused`): a quarantined room takes none, and its socket drops\n * every edit unconfirmed without a word (`document-status.ts`).\n */\n\nimport {\n INITIAL_SYNC_DIFF,\n INITIAL_SYNC_PARAM,\n type InitialSyncSupportStorage,\n keryxOriginOf,\n keryxRoomReadUrl,\n knownInitialSyncSupport,\n readRoomOverHttp,\n rememberInitialSyncSupport,\n} from '@athenaintel/keryx-http/initial-sync';\nimport { receiveOnlyWebSocket } from '@athenaintel/keryx-http/receive-only-socket';\nimport { UnconfirmedUpdateAttributions } from '@athenaintel/keryx-http/unconfirmed-update-attributions';\nimport {\n attributingWebSocket,\n docUpdateAttributions,\n} from '@athenaintel/keryx-http/update-attributions';\nimport { WebsocketProvider } from '@y/websocket';\nimport * as Y from '@y/y';\nimport { classifyClose } from './close-policy';\nimport { type ReadDocumentStatus, watchDocumentStatus } from './document-status';\nimport {\n type CollabAuth,\n type CollabTokenResponse,\n CollabTokenError,\n mintCollabToken,\n} from './mint';\nimport { MAX_CONSECUTIVE_REMINTS, MIN_REFRESH_DELAY_MS, refreshDelayMs } from './token-refresh';\n\nexport type GenericDocStatus =\n | 'connecting'\n | 'connected'\n | 'disconnected'\n | 'closed'\n | 'error';\n\nexport interface PresenceEntry {\n clientId: number;\n state: Record<string, unknown>;\n}\n\nexport interface GenericDocHandle {\n /** The live shared document. Owned by the handle; destroyed with it. */\n readonly doc: Y.Doc;\n readonly status: GenericDocStatus;\n /**\n * Whether the initial server sync has completed for the current connection.\n * `status === 'connected'` fires before the server state arrives, so a doc\n * read immediately after connect can still be empty — gate first reads on\n * this (or `waitForSync`).\n */\n readonly synced: boolean;\n /**\n * Whether every change made to this document has reached the server: `false` from a local edit\n * until the server sends it back (`@y/websocket`'s `syncStatus.localUpdatesSynced`; yhub echoes\n * every update to its sender). Kept across reconnects and re-mints: a replaced provider hands its\n * unconfirmed edits to the next, and an edit made between providers waits for one. A host that\n * closes the document while this is `false` loses those edits, unless a local copy keeps them.\n */\n readonly localChangesSynced: boolean;\n /** Granted access from the last successful mint. */\n readonly accessType: 'r' | 'rw' | null;\n /** Terminal error, when status is 'error' or 'closed'. */\n readonly error: Error | null;\n /**\n * Whether the document holds what the host's local copy stored (always `true` without one).\n * Mount readers after it: until then the document is still empty.\n */\n readonly prepared: boolean;\n /** Whether this host allows a live connection. Disabled documents remain editable locally. */\n readonly connectionEnabled: boolean;\n /**\n * A connection the host's `beforeConnect` held: the handle waits, sending nothing, until the\n * host calls `resume()` (or destroys the handle).\n */\n readonly held: boolean;\n /** Monotonic change counter — bumps on every status/presence notification. */\n readonly version: number;\n /**\n * Resolve once the initial server sync completes; reject on timeout, on a\n * terminal connection state, or if the handle is destroyed first.\n */\n waitForSync: (timeoutMs?: number) => Promise<void>;\n /**\n * Resolve once connected, initially synced, and every local change has been acknowledged,\n * including any edits the local-copy hook restores after sync. The host must prevent further\n * editing while saving a checkpoint. Reject on timeout, a disabled connection, or a terminal state.\n */\n waitForAcknowledged: (timeoutMs?: number) => Promise<void>;\n getPresence: () => PresenceEntry[];\n /** Broadcast this client's presence state (requires a live connection). */\n setPresence: (state: Record<string, unknown> | null) => void;\n /**\n * Force an early token refresh. Session-preserving: the live connection\n * stays up until the fresh token is minted; a failed mint retries on a\n * short timer instead of dropping the session. Without a connection it\n * reconnects now.\n */\n refreshNow: () => Promise<void>;\n /**\n * 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, which no socket close tells:\n * Keryx closes nothing on a widening). A grant that edits reconnects the live room with it, or\n * asks the host's `beforeConnect` again for a room it held on a grant that only read; a grant\n * that still only 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/** How long an HTTP-first read may take before the room falls back to the socket's whole-document sync. */\nconst HTTP_FIRST_READ_TIMEOUT_MS = 60_000;\n\n/** `localStorage`, when the host has one (a browser, Electron's renderer, the phone's editor page). */\nfunction browserStorage(): InitialSyncSupportStorage | null {\n try {\n return typeof window !== 'undefined' && window.localStorage ? window.localStorage : null;\n } catch {\n return null;\n }\n}\n\nexport function connectGenericDoc(args: {\n assetId: string;\n /** Credentials for the default mint; not used when `mint` is given. */\n auth?: CollabAuth;\n access?: 'view' | 'edit';\n mint?: CollabMint;\n /** A local copy of the document the host keeps (see {@link GenericDocLocalCopy}). */\n localCopy?: GenericDocLocalCopy;\n /** Whether a failed mint is worth retrying; defaults to {@link isRetryableMintError}. */\n retryMintError?: (error: unknown) => boolean;\n /** See {@link DEFAULT_OFFLINE_GATE_AFTER_MS}. */\n offlineGateAfterMs?: number;\n /** Start without connecting or minting (for a host's manual-save mode). Defaults to true. */\n connectionEnabled?: boolean;\n /**\n * Reads Keryx's document status with the room's grant (see `ReadDocumentStatus`), for\n * `handle.writesRefused`. A host that cannot read it leaves it out.\n */\n readDocumentStatus?: ReadDocumentStatus;\n /**\n * Open the room HTTP-first (Word at scale), as Olympus opens a Word room: a document that holds\n * nothing yet is read over `GET /ydoc` (compressed, decoded as it downloads), applied as Keryx's\n * own state, and the socket asks Keryx for only what it still lacks (`?initialSync=diff`) - when\n * Keryx says it answers that way (`@athenaintel/keryx-http/initial-sync`). Every later socket of\n * the room asks for the diff too while Keryx is known to answer and the room holds no write Keryx\n * has not echoed. For rooms whose documents can be large (Word documents).\n */\n httpFirstOpen?: boolean;\n /** Hears how each HTTP-first read went (`httpFirstOpen`), for the host's telemetry. */\n onHttpFirstOpen?: (event: GenericDocHttpFirstOpenEvent) => void;\n}): GenericDocHandle {\n const access = args.access ?? 'view';\n const mint = resolveMint({ auth: args.auth, mint: args.mint });\n const localCopy = args.localCopy;\n const retryMintError = args.retryMintError ?? isRetryableMintError;\n const offlineGateAfterMs = args.offlineGateAfterMs ?? DEFAULT_OFFLINE_GATE_AFTER_MS;\n const doc = new Y.Doc();\n // Writes made in a `runWithDocUpdateAttributions` scope, until Keryx acknowledges them: the\n // sockets every provider opens send those made while no socket was open ahead of their sync.\n const unconfirmedAttributions = new UnconfirmedUpdateAttributions({\n doc,\n attributionsFor: () => docUpdateAttributions(doc),\n isRemoteOrigin: (origin) => origin instanceof WebsocketProvider,\n });\n const listeners = new Set<() => void>();\n\n let provider: WebsocketProvider | null = null;\n let refreshTimer: ReturnType<typeof setTimeout> | null = null;\n let retryTimer: ReturnType<typeof setTimeout> | null = null;\n let offlineTimer: ReturnType<typeof setTimeout> | null = null;\n /** The provider whose socket was still opening, with nothing to send, at the threshold. */\n let openingPastThreshold: WebsocketProvider | null = null;\n let mintRetries = 0;\n let destroyed = false;\n let connectionEnabled = args.connectionEnabled ?? true;\n let status: GenericDocStatus = connectionEnabled ? 'connecting' : 'disconnected';\n let synced = false;\n let accessType: 'r' | 'rw' | null = null;\n let error: Error | null = null;\n let lastPresence: Record<string, unknown> | null = null;\n let version = 0;\n let consecutiveRemints = 0;\n let prepared = localCopy === undefined;\n let held = false;\n let heldGrant: CollabTokenResponse | null = null;\n let everConnected = false;\n let disconnectedSince: number | null = null;\n /** Bumped by every connect attempt: an attempt that finds it changed after an await stops. */\n let connectSeq = 0;\n /** Local edits no provider holds: handed on by a replaced provider, or made with none. */\n let carriedUpdates: WebsocketProvider['unconfirmedUpdates'] = [];\n let localChangesSynced = true;\n /** The grant the current provider connects with. */\n let liveGrant: CollabTokenResponse | null = null;\n /** Keryx's auth re-check closed the socket (4401): the next connection reads the document status. */\n let readStatusOnConnect = false;\n /**\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 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.\n */\n function asksForDiffedSync({ roomUrl, unconfirmed }: { roomUrl: string; unconfirmed: number }): boolean {\n if (args.httpFirstOpen !== true) return false;\n const origin = keryxOriginOf(roomUrl);\n const known =\n keryxAnswersSyncStep1 ||\n (origin !== null && knownInitialSyncSupport({ storage: browserStorage(), origin }) === true);\n return known && doc.store.clients.size > 0 && unconfirmed === 0 && !unconfirmedAttributions.keepsWrites;\n }\n\n /**\n * Word at scale: read the room over HTTP, apply it as Keryx's own state (the provider's origin, so\n * nothing treats it as a local edit), then connect the provider's socket, asking for the diff when\n * Keryx said it answers that way. A Keryx that did not, a failed read, or a provider replaced\n * meanwhile: the document is left as it was and the socket connects as every room's does.\n */\n async function openOverHttp({\n target,\n url,\n roomUrl,\n }: {\n target: WebsocketProvider;\n url: string;\n roomUrl: string;\n }): Promise<void> {\n const started = performance.now();\n const origin = keryxOriginOf(roomUrl);\n const storage = browserStorage();\n let event: GenericDocHttpFirstOpenEvent;\n if (origin !== null && knownInitialSyncSupport({ storage, origin }) === false) {\n event = { outcome: 'skipped', durationMs: 0 };\n } else {\n const controller = new AbortController();\n httpFirstRead = { target, controller };\n const timeout = setTimeout(\n () => controller.abort(new DOMException('The HTTP-first read timed out', 'TimeoutError')),\n HTTP_FIRST_READ_TIMEOUT_MS\n );\n try {\n const read = await readRoomOverHttp({ url, signal: controller.signal });\n if (origin !== null) rememberInitialSyncSupport({ storage, origin, supported: read.answersSyncStep1 });\n if (read.answersSyncStep1 && provider === target && !destroyed) {\n if (read.update.byteLength > 2) Y.applyUpdate(doc, read.update, target);\n keryxAnswersSyncStep1 = true;\n }\n event = {\n outcome: read.answersSyncStep1 ? 'read' : 'unsupported',\n bytes: read.bytes,\n durationMs: performance.now() - started,\n };\n } catch (err) {\n // the socket's whole-document sync, as before; a read the room stopped is no failure\n event =\n controller.signal.aborted && (destroyed || provider !== target)\n ? { outcome: 'aborted', durationMs: performance.now() - started }\n : {\n outcome: 'failed',\n durationMs: performance.now() - started,\n error: err instanceof Error ? `${err.name}: ${err.message}` : String(err),\n };\n } finally {\n clearTimeout(timeout);\n if (httpFirstRead?.controller === controller) httpFirstRead = null;\n }\n }\n try {\n args.onHttpFirstOpen?.(event);\n } catch {\n // a host's telemetry never keeps the room from opening its socket\n }\n if (destroyed || provider !== target) return;\n if (asksForDiffedSync({ roomUrl, unconfirmed: target.unconfirmedUpdates.length })) {\n target.params[INITIAL_SYNC_PARAM] = INITIAL_SYNC_DIFF;\n } else {\n delete target.params[INITIAL_SYNC_PARAM];\n }\n target.connect();\n }\n\n const preparing: Promise<void> = localCopy\n ? localCopy\n .prepare({ doc, transport })\n .catch(() => ({ unsyncedEdits: null }))\n .then(({ unsyncedEdits }) => {\n if (destroyed) return;\n if (unsyncedEdits && !(unsyncedEdits.inserts.isEmpty() && unsyncedEdits.deletes.isEmpty())) {\n carriedUpdates = [...carriedUpdates, { created: Date.now(), ids: unsyncedEdits }];\n }\n prepared = true;\n refreshLocalChangesSynced();\n notify();\n })\n : Promise.resolve();\n\n void connect();\n\n const waitForSync = (timeoutMs = 15_000): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n const terminal = (): Error | null => {\n if (destroyed) return new Error('Handle destroyed before initial sync');\n if (status === 'closed' || status === 'error') {\n return error ?? new Error(`Connection ${status} before initial sync`);\n }\n return null;\n };\n if (synced) {\n resolve();\n return;\n }\n const immediate = terminal();\n if (immediate) {\n reject(immediate);\n return;\n }\n const cleanup = () => {\n clearTimeout(timer);\n listeners.delete(listener);\n };\n const timer = setTimeout(() => {\n cleanup();\n reject(new Error(`Timed out after ${timeoutMs}ms waiting for initial sync`));\n }, timeoutMs);\n const listener = () => {\n if (synced) {\n cleanup();\n resolve();\n return;\n }\n const err = terminal();\n if (err) {\n cleanup();\n reject(err);\n }\n };\n listeners.add(listener);\n });\n\n const waitForAcknowledged = (timeoutMs = 15_000): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n let finished = false;\n let checkQueued = false;\n let timer: ReturnType<typeof setTimeout> | null = null;\n const finish = (failure?: Error) => {\n if (finished) return;\n finished = true;\n if (timer !== null) clearTimeout(timer);\n listeners.delete(check);\n if (failure) reject(failure);\n else resolve();\n };\n const check = () => {\n if (finished || checkQueued) return;\n checkQueued = true;\n // All synchronous transport hooks and change listeners finish before a save settles.\n queueMicrotask(() => {\n checkQueued = false;\n if (finished) return;\n if (destroyed) {\n finish(new Error('Handle destroyed before local changes were acknowledged'));\n } else if (!connectionEnabled) {\n finish(new Error('Connection disabled before local changes were acknowledged'));\n } else if (status === 'closed' || status === 'error') {\n finish(error ?? new Error(`Connection ${status} before local changes were acknowledged`));\n } else if (prepared && status === 'connected' && synced && localChangesSynced) {\n finish();\n }\n });\n };\n timer = setTimeout(() => {\n finish(new Error(`Timed out after ${timeoutMs}ms waiting for local changes to be acknowledged`));\n }, timeoutMs);\n listeners.add(check);\n check();\n });\n\n /** 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.destroy();\n },\n };\n}\n\nexport { CollabTokenError };\nexport type { CollabAuth, CollabTokenResponse };\n"],"names":[],"mappings":";;;;;;;;;;AA4OO,MAAM,gCAAgC;AAG7C,MAAM,uBAAuB,CAAC,KAAO,KAAO,KAAO,KAAO,MAAQ,KAAQ,GAAM;AAMzE,SAAS,qBAAqB,OAAyB;AAC5D,MAAI,iBAAiB,kBAAkB;AACrC,WAAO,MAAM,UAAU,OAAO,MAAM,WAAW,OAAO,MAAM,WAAW;AAAA,EACzE;AACA,SAAO,iBAAiB,aAAc,iBAAiB,gBAAgB,MAAM,SAAS;AACxF;AAEA,SAAS,YAAY,EAAE,MAAM,QAA8D;AACzF,MAAI,KAAM,QAAO;AACjB,MAAI,CAAC,KAAM,OAAM,IAAI,MAAM,0CAA0C;AACrE,SAAO,CAAC,EAAE,SAAS,OAAA,MAAa,gBAAgB,EAAE,MAAM,SAAS,QAAQ;AAC3E;AAaA,SAAS,UAAU;AAAA,EACjB;AAAA,EACA;AAAA,EACA;AACF,GAIiC;AAC/B,QAAM,O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sB,CAAC,YAAY;;AACjC,UAAI,aAAa,YAAY,kBAAmB;AAChD,0BAAoB;AACpB,UAAI,CAAC,SAAS;AAEZ,sBAAc;AACd,wBAAA;AACA,0BAAA;AACA,yBAAA;AACA,kBAAU,cAAc;AACxB,qDAAW,4BAAX,mCAAqC;AACrC;AAAA,MACF;AACA,mDAAW,4BAAX,mCAAqC;AACrC,aAAO;AACP,kBAAY;AACZ,gBAAU,YAAY;AACtB,WAAK,QAAA;AAAA,IACP;AAAA,IACA,QAAQ,MAAM;AACZ,UAAI,CAAC,QAAQ,aAAa,CAAC,kBAAmB;AAC9C,aAAO;AACP,YAAM,QAAQ;AACd,kBAAY;AACZ,aAAA;AACA,WAAK,QAAQ,EAAE,UAAU,MAAM,OAAO,SAAS,QAAW;AAAA,IAC5D;AAAA,IACA;AAAA,IACA,UAAU,CAAC,aAAa;AACtB,gBAAU,IAAI,QAAQ;AACtB,aAAO,MAAM;AACX,kBAAU,OAAO,QAAQ;AAAA,MAC3B;AAAA,IACF;AAAA,IACA,SAAS,MAAM;AACb,UAAI,UAAW;AACf,kBAAY;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;"}
|
|
@@ -82,10 +82,10 @@ function useQuoteFromPostMessage({ scope } = {}) {
|
|
|
82
82
|
}
|
|
83
83
|
};
|
|
84
84
|
const handleKeydown = (e) => {
|
|
85
|
-
var _a2;
|
|
86
|
-
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "l") {
|
|
85
|
+
var _a2, _b;
|
|
86
|
+
if ((e.metaKey || e.ctrlKey) && ((_a2 = e.key) == null ? void 0 : _a2.toLowerCase()) === "l") {
|
|
87
87
|
const sel = doc.getSelection();
|
|
88
|
-
const selection = (
|
|
88
|
+
const selection = (_b = sel == null ? void 0 : sel.toString()) == null ? void 0 : _b.trim();
|
|
89
89
|
if (selection && selection.length > 0 && takes((sel == null ? void 0 : sel.anchorNode) ?? null)) {
|
|
90
90
|
e.preventDefault();
|
|
91
91
|
let messageId;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"QuoteContext.cjs","sources":["../../src/composer/QuoteContext.tsx"],"sourcesContent":["import {\n createContext,\n type RefObject,\n useContext,\n useEffect,\n useMemo,\n useState,\n type ReactNode,\n} from 'react';\nimport { useStore } from 'zustand';\nimport { createStore, type StoreApi } from 'zustand/vanilla';\n\nexport interface QuoteData {\n /** The selected/quoted text. */\n text: string;\n /** Title of the source (e.g., asset title, document name). */\n sourceTitle?: string;\n /** Asset ID of the source (for attribution). */\n sourceAssetId?: string;\n /** Message ID of the source message (when quoting from chat). */\n sourceMessageId?: string;\n /** Role of the source message ('assistant' | 'user'). */\n sourceRole?: string;\n}\n\ninterface QuoteContextValue {\n quote: QuoteData | null;\n setQuote: (quote: QuoteData | null) => void;\n clearQuote: () => void;\n}\n\nconst QuoteCtx = createContext<QuoteContextValue | null>(null);\n\ninterface QuoteStoreState {\n quote: QuoteData | null;\n}\n\n/**\n * A composer's pending quote, kept outside React (`createQuoteStore`), like\n * `AttachmentStore`: one per chat when a host shows several.\n */\nexport type QuoteStore = StoreApi<QuoteStoreState>;\n\n/** An empty `QuoteStore`, for `<QuoteProvider store>`. */\nexport function createQuoteStore(): QuoteStore {\n return createStore<QuoteStoreState>(() => ({ quote: null }));\n}\n\n/**\n * The composer's pending quote. Like \\`AttachmentProvider\\`, a `store` makes\n * it that store's, and without one it reuses a provider already mounted\n * above, so a host can keep the quote across a remounting \\`AthenaChat\\`.\n */\nexport function QuoteProvider({ children, store }: { children: ReactNode; store?: QuoteStore }) {\n const outer = useContext(QuoteCtx);\n if (store) return <StoreQuoteProvider store={store}>{children}</StoreQuoteProvider>;\n if (outer) return <>{children}</>;\n return <OwnQuoteProvider>{children}</OwnQuoteProvider>;\n}\n\nfunction OwnQuoteProvider({ children }: { children: ReactNode }) {\n const [store] = useState(createQuoteStore);\n return <StoreQuoteProvider store={store}>{children}</StoreQuoteProvider>;\n}\n\nfunction StoreQuoteProvider({ children, store }: { children: ReactNode; store: QuoteStore }) {\n const quote = useStore(store, (state) => state.quote);\n const actions = useMemo(\n () => ({\n setQuote: (next: QuoteData | null) => store.setState({ quote: next }),\n clearQuote: () => store.setState({ quote: null }),\n }),\n [store],\n );\n const value = useMemo(() => ({ quote, ...actions }), [quote, actions]);\n\n return (\n <QuoteCtx.Provider value={value}>\n {children}\n </QuoteCtx.Provider>\n );\n}\n\nexport function useQuote(): QuoteContextValue {\n const ctx = useContext(QuoteCtx);\n if (!ctx) {\n throw new Error('[AthenaSDK] useQuote must be used within <QuoteProvider>');\n }\n return ctx;\n}\n\n/**\n * Whether a message came from a frame embedded directly in this window, for\n * any origin: the window of one of this document's iframes (an identity\n * comparison, safe cross-origin), or, for a frame inside a shadow root, a\n * window whose `parent` is this window (`parent` is readable on a\n * cross-origin window). A message port, a worker, this window itself, a\n * grandchild frame or an unrelated window is refused. `win` is the window the\n * message came to (default: this one), e.g. a popped-out chat's.\n */\nexport function isDirectChildFrame(\n source: MessageEventSource | null,\n win: Window = window,\n): boolean {\n if (!source || source === win) return false;\n for (const frame of win.document.querySelectorAll('iframe')) {\n if (frame.contentWindow === source) return true;\n }\n try {\n return Reflect.get(source, 'parent') === win;\n } catch {\n return false;\n }\n}\n\n/** `AthenaChat`'s thread root: the chats `useQuoteFromPostMessage` tells apart. */\nconst CHAT_ROOT_SELECTOR = '.aui-thread-root';\n\n/**\n * The chat the person last focused in each window, which takes a quote that\n * names no chat (a selection outside every chat, an embedded frame's text)\n * when that window shows several. A focus, not data: no state of the chats\n * themselves.\n */\nconst lastFocusedChatRoots = new WeakMap<Document, Element>();\n\n/** The element a node is, or sits in; duck-typed, since a pop-out window's nodes are another realm's. */\nfunction elementOf(node: Node | null | undefined): Element | null {\n if (!node) return null;\n return node.nodeType === 1 ? (node as Element) : node.parentElement;\n}\n\nexport interface QuoteFromPostMessageOptions {\n /**\n * An element inside the chat this composer belongs to. With several chats in\n * one window, a ⌘L selection goes to the chat it was made in, and one made\n * outside every chat (or an embedded frame's text) to the chat the person\n * last focused; the keys and an embedded frame's messages are heard in this\n * element's own window, a pop-out included. Without it, every quote is this\n * composer's, as before.\n */\n scope?: RefObject<Element | null>;\n}\n\n/**\n * Listens for:\n * 1. Cmd+L / Ctrl+L keydown — grabs the current text selection and sets it as a quote.\n * `preventDefault` stops the browser from focusing the URL bar.\n * 2. PostMessage events from child iframes (asset panels, embedded content)\n * with type `athena-add-to-composer`, only from a frame embedded directly\n * in this window ({@link isDirectChildFrame}).\n *\n * Mount this once per composer inside AthenaProvider (`AthenaChat` does).\n */\nexport function useQuoteFromPostMessage({ scope }: QuoteFromPostMessageOptions = {}) {\n const { setQuote } = useQuote();\n\n useEffect(() => {\n const doc = scope?.current?.ownerDocument ?? document;\n const win = doc.defaultView ?? window;\n const chatRoot = () => scope?.current?.closest(CHAT_ROOT_SELECTOR) ?? null;\n // Whether this composer takes a quote made at `anchor` (null: one that names no chat).\n const takes = (anchor: Node | null) => {\n const mine = chatRoot();\n if (!mine) return true;\n const owner = elementOf(anchor)?.closest(CHAT_ROOT_SELECTOR) ?? null;\n if (owner) return owner === mine;\n const remembered = lastFocusedChatRoots.get(doc);\n const focused = remembered?.isConnected ? remembered : doc.querySelector(CHAT_ROOT_SELECTOR);\n return focused === mine;\n };\n\n const handleFocusIn = (event: FocusEvent) => {\n const mine = chatRoot();\n const target = event.target as Node | null;\n if (mine && target && typeof target.nodeType === 'number' && mine.contains(target)) {\n lastFocusedChatRoots.set(doc, mine);\n }\n };\n\n // ── Cmd+L / Ctrl+L keyboard handler ──────────────────────────────\n const handleKeydown = (e: KeyboardEvent) => {\n if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'l') {\n const sel = doc.getSelection();\n const selection = sel?.toString()?.trim();\n\n if (selection && selection.length > 0 && takes(sel?.anchorNode ?? null)) {\n e.preventDefault();\n\n // Walk up from the selection anchor to find the message container.\n // assistant-ui message roots have data-role=\"assistant\" or data-role=\"user\".\n let messageId: string | undefined;\n let role: string | undefined;\n let node = elementOf(sel?.anchorNode);\n while (node && node !== doc.body) {\n const dataRole = node.getAttribute('data-role');\n if (dataRole === 'assistant' || dataRole === 'user') {\n role = dataRole;\n // assistant-ui sets data-message-id on message roots\n messageId = node.getAttribute('data-message-id') ?? undefined;\n break;\n }\n node = node.parentElement;\n }\n\n setQuote({ text: selection, sourceRole: role, sourceMessageId: messageId });\n }\n }\n };\n\n // ── PostMessage handler (from iframes) ───────────────────────────\n // Accepts messages from any origin, but only from a frame embedded\n // directly in this window: the SDK consumer controls which iframes are\n // embedded, and that is the trust boundary. A popup, an opener or another\n // tab holding a reference to this window cannot stage composer text.\n const handleMessage = (event: MessageEvent) => {\n const data = event.data;\n if (\n data &&\n typeof data === 'object' &&\n data.type === 'athena-add-to-composer' &&\n typeof data.text === 'string' &&\n data.text.trim().length > 0 &&\n isDirectChildFrame(event.source, win) &&\n takes(null)\n ) {\n setQuote({\n text: data.text,\n sourceTitle: data.sourceTitle,\n sourceAssetId: data.sourceAssetId,\n });\n }\n };\n\n doc.addEventListener('keydown', handleKeydown, true); // capture phase to beat the browser\n doc.addEventListener('focusin', handleFocusIn, true);\n win.addEventListener('message', handleMessage);\n\n return () => {\n doc.removeEventListener('keydown', handleKeydown, true);\n doc.removeEventListener('focusin', handleFocusIn, true);\n win.removeEventListener('message', handleMessage);\n };\n }, [scope, setQuote]);\n}\n"],"names":["createContext","createStore","useContext","jsx","Fragment","useState","useStore","useMemo","useEffect","_a"],"mappings":";;;;;;AA+BA,MAAM,WAAWA,WAAAA,cAAwC,IAAI;AAatD,SAAS,mBAA+B;AAC7C,SAAOC,QAAAA,YAA6B,OAAO,EAAE,OAAO,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,gBAAAA,IAAiB;AAEnC,YAAI,aAAa,UAAU,SAAS,KAAK,OAAM,2BAAK,eAAc,IAAI,GAAG;AACvE,YAAE,eAAA;AAIF,cAAI;AACJ,cAAI;AACJ,cAAI,OAAO,UAAU,2BAAK,UAAU;AACpC,iBAAO,QAAQ,SAAS,IAAI,MAAM;AAChC,kBAAM,WAAW,KAAK,aAAa,WAAW;AAC9C,gBAAI,aAAa,eAAe,aAAa,QAAQ;AACnD,qBAAO;AAEP,0BAAY,KAAK,aAAa,iBAAiB,KAAK;AACpD;AAAA,YACF;AACA,mBAAO,KAAK;AAAA,UACd;AAEA,mBAAS,EAAE,MAAM,WAAW,YAAY,MAAM,iBAAiB,WAAW;AAAA,QAC5E;AAAA,MACF;AAAA,IACF;AAOA,UAAM,gBAAgB,CAAC,UAAwB;AAC7C,YAAM,OAAO,MAAM;AACnB,UACE,QACA,OAAO,SAAS,YAChB,KAAK,SAAS,4BACd,OAAO,KAAK,SAAS,YACrB,KAAK,KAAK,KAAA,EAAO,SAAS,KAC1B,mBAAmB,MAAM,QAAQ,GAAG,KACpC,MAAM,IAAI,GACV;AACA,iBAAS;AAAA,UACP,MAAM,KAAK;AAAA,UACX,aAAa,KAAK;AAAA,UAClB,eAAe,KAAK;AAAA,QAAA,CACrB;AAAA,MACH;AAAA,IACF;AAEA,QAAI,iBAAiB,WAAW,eAAe,IAAI;AACnD,QAAI,iBAAiB,WAAW,eAAe,IAAI;AACnD,QAAI,iBAAiB,WAAW,aAAa;AAE7C,WAAO,MAAM;AACX,UAAI,oBAAoB,WAAW,eAAe,IAAI;AACtD,UAAI,oBAAoB,WAAW,eAAe,IAAI;AACtD,UAAI,oBAAoB,WAAW,aAAa;AAAA,IAClD;AAAA,EACF,GAAG,CAAC,OAAO,QAAQ,CAAC;AACtB;;;;;;"}
|
|
1
|
+
{"version":3,"file":"QuoteContext.cjs","sources":["../../src/composer/QuoteContext.tsx"],"sourcesContent":["import {\n createContext,\n type RefObject,\n useContext,\n useEffect,\n useMemo,\n useState,\n type ReactNode,\n} from 'react';\nimport { useStore } from 'zustand';\nimport { createStore, type StoreApi } from 'zustand/vanilla';\n\nexport interface QuoteData {\n /** The selected/quoted text. */\n text: string;\n /** Title of the source (e.g., asset title, document name). */\n sourceTitle?: string;\n /** Asset ID of the source (for attribution). */\n sourceAssetId?: string;\n /** Message ID of the source message (when quoting from chat). */\n sourceMessageId?: string;\n /** Role of the source message ('assistant' | 'user'). */\n sourceRole?: string;\n}\n\ninterface QuoteContextValue {\n quote: QuoteData | null;\n setQuote: (quote: QuoteData | null) => void;\n clearQuote: () => void;\n}\n\nconst QuoteCtx = createContext<QuoteContextValue | null>(null);\n\ninterface QuoteStoreState {\n quote: QuoteData | null;\n}\n\n/**\n * A composer's pending quote, kept outside React (`createQuoteStore`), like\n * `AttachmentStore`: one per chat when a host shows several.\n */\nexport type QuoteStore = StoreApi<QuoteStoreState>;\n\n/** An empty `QuoteStore`, for `<QuoteProvider store>`. */\nexport function createQuoteStore(): QuoteStore {\n return createStore<QuoteStoreState>(() => ({ quote: null }));\n}\n\n/**\n * The composer's pending quote. Like \\`AttachmentProvider\\`, a `store` makes\n * it that store's, and without one it reuses a provider already mounted\n * above, so a host can keep the quote across a remounting \\`AthenaChat\\`.\n */\nexport function QuoteProvider({ children, store }: { children: ReactNode; store?: QuoteStore }) {\n const outer = useContext(QuoteCtx);\n if (store) return <StoreQuoteProvider store={store}>{children}</StoreQuoteProvider>;\n if (outer) return <>{children}</>;\n return <OwnQuoteProvider>{children}</OwnQuoteProvider>;\n}\n\nfunction OwnQuoteProvider({ children }: { children: ReactNode }) {\n const [store] = useState(createQuoteStore);\n return <StoreQuoteProvider store={store}>{children}</StoreQuoteProvider>;\n}\n\nfunction StoreQuoteProvider({ children, store }: { children: ReactNode; store: QuoteStore }) {\n const quote = useStore(store, (state) => state.quote);\n const actions = useMemo(\n () => ({\n setQuote: (next: QuoteData | null) => store.setState({ quote: next }),\n clearQuote: () => store.setState({ quote: null }),\n }),\n [store],\n );\n const value = useMemo(() => ({ quote, ...actions }), [quote, actions]);\n\n return (\n <QuoteCtx.Provider value={value}>\n {children}\n </QuoteCtx.Provider>\n );\n}\n\nexport function useQuote(): QuoteContextValue {\n const ctx = useContext(QuoteCtx);\n if (!ctx) {\n throw new Error('[AthenaSDK] useQuote must be used within <QuoteProvider>');\n }\n return ctx;\n}\n\n/**\n * Whether a message came from a frame embedded directly in this window, for\n * any origin: the window of one of this document's iframes (an identity\n * comparison, safe cross-origin), or, for a frame inside a shadow root, a\n * window whose `parent` is this window (`parent` is readable on a\n * cross-origin window). A message port, a worker, this window itself, a\n * grandchild frame or an unrelated window is refused. `win` is the window the\n * message came to (default: this one), e.g. a popped-out chat's.\n */\nexport function isDirectChildFrame(\n source: MessageEventSource | null,\n win: Window = window,\n): boolean {\n if (!source || source === win) return false;\n for (const frame of win.document.querySelectorAll('iframe')) {\n if (frame.contentWindow === source) return true;\n }\n try {\n return Reflect.get(source, 'parent') === win;\n } catch {\n return false;\n }\n}\n\n/** `AthenaChat`'s thread root: the chats `useQuoteFromPostMessage` tells apart. */\nconst CHAT_ROOT_SELECTOR = '.aui-thread-root';\n\n/**\n * The chat the person last focused in each window, which takes a quote that\n * names no chat (a selection outside every chat, an embedded frame's text)\n * when that window shows several. A focus, not data: no state of the chats\n * themselves.\n */\nconst lastFocusedChatRoots = new WeakMap<Document, Element>();\n\n/** The element a node is, or sits in; duck-typed, since a pop-out window's nodes are another realm's. */\nfunction elementOf(node: Node | null | undefined): Element | null {\n if (!node) return null;\n return node.nodeType === 1 ? (node as Element) : node.parentElement;\n}\n\nexport interface QuoteFromPostMessageOptions {\n /**\n * An element inside the chat this composer belongs to. With several chats in\n * one window, a ⌘L selection goes to the chat it was made in, and one made\n * outside every chat (or an embedded frame's text) to the chat the person\n * last focused; the keys and an embedded frame's messages are heard in this\n * element's own window, a pop-out included. Without it, every quote is this\n * composer's, as before.\n */\n scope?: RefObject<Element | null>;\n}\n\n/**\n * Listens for:\n * 1. Cmd+L / Ctrl+L keydown — grabs the current text selection and sets it as a quote.\n * `preventDefault` stops the browser from focusing the URL bar.\n * 2. PostMessage events from child iframes (asset panels, embedded content)\n * with type `athena-add-to-composer`, only from a frame embedded directly\n * in this window ({@link isDirectChildFrame}).\n *\n * Mount this once per composer inside AthenaProvider (`AthenaChat` does).\n */\nexport function useQuoteFromPostMessage({ scope }: QuoteFromPostMessageOptions = {}) {\n const { setQuote } = useQuote();\n\n useEffect(() => {\n const doc = scope?.current?.ownerDocument ?? document;\n const win = doc.defaultView ?? window;\n const chatRoot = () => scope?.current?.closest(CHAT_ROOT_SELECTOR) ?? null;\n // Whether this composer takes a quote made at `anchor` (null: one that names no chat).\n const takes = (anchor: Node | null) => {\n const mine = chatRoot();\n if (!mine) return true;\n const owner = elementOf(anchor)?.closest(CHAT_ROOT_SELECTOR) ?? null;\n if (owner) return owner === mine;\n const remembered = lastFocusedChatRoots.get(doc);\n const focused = remembered?.isConnected ? remembered : doc.querySelector(CHAT_ROOT_SELECTOR);\n return focused === mine;\n };\n\n const handleFocusIn = (event: FocusEvent) => {\n const mine = chatRoot();\n const target = event.target as Node | null;\n if (mine && target && typeof target.nodeType === 'number' && mine.contains(target)) {\n lastFocusedChatRoots.set(doc, mine);\n }\n };\n\n // ── Cmd+L / Ctrl+L keyboard handler ──────────────────────────────\n const handleKeydown = (e: KeyboardEvent) => {\n if ((e.metaKey || e.ctrlKey) && e.key?.toLowerCase() === 'l') {\n const sel = doc.getSelection();\n const selection = sel?.toString()?.trim();\n\n if (selection && selection.length > 0 && takes(sel?.anchorNode ?? null)) {\n e.preventDefault();\n\n // Walk up from the selection anchor to find the message container.\n // assistant-ui message roots have data-role=\"assistant\" or data-role=\"user\".\n let messageId: string | undefined;\n let role: string | undefined;\n let node = elementOf(sel?.anchorNode);\n while (node && node !== doc.body) {\n const dataRole = node.getAttribute('data-role');\n if (dataRole === 'assistant' || dataRole === 'user') {\n role = dataRole;\n // assistant-ui sets data-message-id on message roots\n messageId = node.getAttribute('data-message-id') ?? undefined;\n break;\n }\n node = node.parentElement;\n }\n\n setQuote({ text: selection, sourceRole: role, sourceMessageId: messageId });\n }\n }\n };\n\n // ── PostMessage handler (from iframes) ───────────────────────────\n // Accepts messages from any origin, but only from a frame embedded\n // directly in this window: the SDK consumer controls which iframes are\n // embedded, and that is the trust boundary. A popup, an opener or another\n // tab holding a reference to this window cannot stage composer text.\n const handleMessage = (event: MessageEvent) => {\n const data = event.data;\n if (\n data &&\n typeof data === 'object' &&\n data.type === 'athena-add-to-composer' &&\n typeof data.text === 'string' &&\n data.text.trim().length > 0 &&\n isDirectChildFrame(event.source, win) &&\n takes(null)\n ) {\n setQuote({\n text: data.text,\n sourceTitle: data.sourceTitle,\n sourceAssetId: data.sourceAssetId,\n });\n }\n };\n\n doc.addEventListener('keydown', handleKeydown, true); // capture phase to beat the browser\n doc.addEventListener('focusin', handleFocusIn, true);\n win.addEventListener('message', handleMessage);\n\n return () => {\n doc.removeEventListener('keydown', handleKeydown, true);\n doc.removeEventListener('focusin', handleFocusIn, true);\n win.removeEventListener('message', handleMessage);\n };\n }, [scope, setQuote]);\n}\n"],"names":["createContext","createStore","useContext","jsx","Fragment","useState","useStore","useMemo","useEffect","_a"],"mappings":";;;;;;AA+BA,MAAM,WAAWA,WAAAA,cAAwC,IAAI;AAatD,SAAS,mBAA+B;AAC7C,SAAOC,QAAAA,YAA6B,OAAO,EAAE,OAAO,OAAO;AAC7D;AAOO,SAAS,cAAc,EAAE,UAAU,SAAsD;AAC9F,QAAM,QAAQC,WAAAA,WAAW,QAAQ;AACjC,MAAI,MAAO,QAAOC,2BAAAA,IAAC,oBAAA,EAAmB,OAAe,UAAS;AAC9D,MAAI,MAAO,QAAOA,2BAAAA,IAAAC,WAAAA,UAAA,EAAG,SAAA,CAAS;AAC9B,SAAOD,+BAAC,oBAAkB,UAAS;AACrC;AAEA,SAAS,iBAAiB,EAAE,YAAqC;AAC/D,QAAM,CAAC,KAAK,IAAIE,WAAAA,S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YACF;AACA,mBAAO,KAAK;AAAA,UACd;AAEA,mBAAS,EAAE,MAAM,WAAW,YAAY,MAAM,iBAAiB,WAAW;AAAA,QAC5E;AAAA,MACF;AAAA,IACF;AAOA,UAAM,gBAAgB,CAAC,UAAwB;AAC7C,YAAM,OAAO,MAAM;AACnB,UACE,QACA,OAAO,SAAS,YAChB,KAAK,SAAS,4BACd,OAAO,KAAK,SAAS,YACrB,KAAK,KAAK,KAAA,EAAO,SAAS,KAC1B,mBAAmB,MAAM,QAAQ,GAAG,KACpC,MAAM,IAAI,GACV;AACA,iBAAS;AAAA,UACP,MAAM,KAAK;AAAA,UACX,aAAa,KAAK;AAAA,UAClB,eAAe,KAAK;AAAA,QAAA,CACrB;AAAA,MACH;AAAA,IACF;AAEA,QAAI,iBAAiB,WAAW,eAAe,IAAI;AACnD,QAAI,iBAAiB,WAAW,eAAe,IAAI;AACnD,QAAI,iBAAiB,WAAW,aAAa;AAE7C,WAAO,MAAM;AACX,UAAI,oBAAoB,WAAW,eAAe,IAAI;AACtD,UAAI,oBAAoB,WAAW,eAAe,IAAI;AACtD,UAAI,oBAAoB,WAAW,aAAa;AAAA,IAClD;AAAA,EACF,GAAG,CAAC,OAAO,QAAQ,CAAC;AACtB;;;;;;"}
|
|
@@ -80,10 +80,10 @@ function useQuoteFromPostMessage({ scope } = {}) {
|
|
|
80
80
|
}
|
|
81
81
|
};
|
|
82
82
|
const handleKeydown = (e) => {
|
|
83
|
-
var _a2;
|
|
84
|
-
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "l") {
|
|
83
|
+
var _a2, _b;
|
|
84
|
+
if ((e.metaKey || e.ctrlKey) && ((_a2 = e.key) == null ? void 0 : _a2.toLowerCase()) === "l") {
|
|
85
85
|
const sel = doc.getSelection();
|
|
86
|
-
const selection = (
|
|
86
|
+
const selection = (_b = sel == null ? void 0 : sel.toString()) == null ? void 0 : _b.trim();
|
|
87
87
|
if (selection && selection.length > 0 && takes((sel == null ? void 0 : sel.anchorNode) ?? null)) {
|
|
88
88
|
e.preventDefault();
|
|
89
89
|
let messageId;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"QuoteContext.js","sources":["../../src/composer/QuoteContext.tsx"],"sourcesContent":["import {\n createContext,\n type RefObject,\n useContext,\n useEffect,\n useMemo,\n useState,\n type ReactNode,\n} from 'react';\nimport { useStore } from 'zustand';\nimport { createStore, type StoreApi } from 'zustand/vanilla';\n\nexport interface QuoteData {\n /** The selected/quoted text. */\n text: string;\n /** Title of the source (e.g., asset title, document name). */\n sourceTitle?: string;\n /** Asset ID of the source (for attribution). */\n sourceAssetId?: string;\n /** Message ID of the source message (when quoting from chat). */\n sourceMessageId?: string;\n /** Role of the source message ('assistant' | 'user'). */\n sourceRole?: string;\n}\n\ninterface QuoteContextValue {\n quote: QuoteData | null;\n setQuote: (quote: QuoteData | null) => void;\n clearQuote: () => void;\n}\n\nconst QuoteCtx = createContext<QuoteContextValue | null>(null);\n\ninterface QuoteStoreState {\n quote: QuoteData | null;\n}\n\n/**\n * A composer's pending quote, kept outside React (`createQuoteStore`), like\n * `AttachmentStore`: one per chat when a host shows several.\n */\nexport type QuoteStore = StoreApi<QuoteStoreState>;\n\n/** An empty `QuoteStore`, for `<QuoteProvider store>`. */\nexport function createQuoteStore(): QuoteStore {\n return createStore<QuoteStoreState>(() => ({ quote: null }));\n}\n\n/**\n * The composer's pending quote. Like \\`AttachmentProvider\\`, a `store` makes\n * it that store's, and without one it reuses a provider already mounted\n * above, so a host can keep the quote across a remounting \\`AthenaChat\\`.\n */\nexport function QuoteProvider({ children, store }: { children: ReactNode; store?: QuoteStore }) {\n const outer = useContext(QuoteCtx);\n if (store) return <StoreQuoteProvider store={store}>{children}</StoreQuoteProvider>;\n if (outer) return <>{children}</>;\n return <OwnQuoteProvider>{children}</OwnQuoteProvider>;\n}\n\nfunction OwnQuoteProvider({ children }: { children: ReactNode }) {\n const [store] = useState(createQuoteStore);\n return <StoreQuoteProvider store={store}>{children}</StoreQuoteProvider>;\n}\n\nfunction StoreQuoteProvider({ children, store }: { children: ReactNode; store: QuoteStore }) {\n const quote = useStore(store, (state) => state.quote);\n const actions = useMemo(\n () => ({\n setQuote: (next: QuoteData | null) => store.setState({ quote: next }),\n clearQuote: () => store.setState({ quote: null }),\n }),\n [store],\n );\n const value = useMemo(() => ({ quote, ...actions }), [quote, actions]);\n\n return (\n <QuoteCtx.Provider value={value}>\n {children}\n </QuoteCtx.Provider>\n );\n}\n\nexport function useQuote(): QuoteContextValue {\n const ctx = useContext(QuoteCtx);\n if (!ctx) {\n throw new Error('[AthenaSDK] useQuote must be used within <QuoteProvider>');\n }\n return ctx;\n}\n\n/**\n * Whether a message came from a frame embedded directly in this window, for\n * any origin: the window of one of this document's iframes (an identity\n * comparison, safe cross-origin), or, for a frame inside a shadow root, a\n * window whose `parent` is this window (`parent` is readable on a\n * cross-origin window). A message port, a worker, this window itself, a\n * grandchild frame or an unrelated window is refused. `win` is the window the\n * message came to (default: this one), e.g. a popped-out chat's.\n */\nexport function isDirectChildFrame(\n source: MessageEventSource | null,\n win: Window = window,\n): boolean {\n if (!source || source === win) return false;\n for (const frame of win.document.querySelectorAll('iframe')) {\n if (frame.contentWindow === source) return true;\n }\n try {\n return Reflect.get(source, 'parent') === win;\n } catch {\n return false;\n }\n}\n\n/** `AthenaChat`'s thread root: the chats `useQuoteFromPostMessage` tells apart. */\nconst CHAT_ROOT_SELECTOR = '.aui-thread-root';\n\n/**\n * The chat the person last focused in each window, which takes a quote that\n * names no chat (a selection outside every chat, an embedded frame's text)\n * when that window shows several. A focus, not data: no state of the chats\n * themselves.\n */\nconst lastFocusedChatRoots = new WeakMap<Document, Element>();\n\n/** The element a node is, or sits in; duck-typed, since a pop-out window's nodes are another realm's. */\nfunction elementOf(node: Node | null | undefined): Element | null {\n if (!node) return null;\n return node.nodeType === 1 ? (node as Element) : node.parentElement;\n}\n\nexport interface QuoteFromPostMessageOptions {\n /**\n * An element inside the chat this composer belongs to. With several chats in\n * one window, a ⌘L selection goes to the chat it was made in, and one made\n * outside every chat (or an embedded frame's text) to the chat the person\n * last focused; the keys and an embedded frame's messages are heard in this\n * element's own window, a pop-out included. Without it, every quote is this\n * composer's, as before.\n */\n scope?: RefObject<Element | null>;\n}\n\n/**\n * Listens for:\n * 1. Cmd+L / Ctrl+L keydown — grabs the current text selection and sets it as a quote.\n * `preventDefault` stops the browser from focusing the URL bar.\n * 2. PostMessage events from child iframes (asset panels, embedded content)\n * with type `athena-add-to-composer`, only from a frame embedded directly\n * in this window ({@link isDirectChildFrame}).\n *\n * Mount this once per composer inside AthenaProvider (`AthenaChat` does).\n */\nexport function useQuoteFromPostMessage({ scope }: QuoteFromPostMessageOptions = {}) {\n const { setQuote } = useQuote();\n\n useEffect(() => {\n const doc = scope?.current?.ownerDocument ?? document;\n const win = doc.defaultView ?? window;\n const chatRoot = () => scope?.current?.closest(CHAT_ROOT_SELECTOR) ?? null;\n // Whether this composer takes a quote made at `anchor` (null: one that names no chat).\n const takes = (anchor: Node | null) => {\n const mine = chatRoot();\n if (!mine) return true;\n const owner = elementOf(anchor)?.closest(CHAT_ROOT_SELECTOR) ?? null;\n if (owner) return owner === mine;\n const remembered = lastFocusedChatRoots.get(doc);\n const focused = remembered?.isConnected ? remembered : doc.querySelector(CHAT_ROOT_SELECTOR);\n return focused === mine;\n };\n\n const handleFocusIn = (event: FocusEvent) => {\n const mine = chatRoot();\n const target = event.target as Node | null;\n if (mine && target && typeof target.nodeType === 'number' && mine.contains(target)) {\n lastFocusedChatRoots.set(doc, mine);\n }\n };\n\n // ── Cmd+L / Ctrl+L keyboard handler ──────────────────────────────\n const handleKeydown = (e: KeyboardEvent) => {\n if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'l') {\n const sel = doc.getSelection();\n const selection = sel?.toString()?.trim();\n\n if (selection && selection.length > 0 && takes(sel?.anchorNode ?? null)) {\n e.preventDefault();\n\n // Walk up from the selection anchor to find the message container.\n // assistant-ui message roots have data-role=\"assistant\" or data-role=\"user\".\n let messageId: string | undefined;\n let role: string | undefined;\n let node = elementOf(sel?.anchorNode);\n while (node && node !== doc.body) {\n const dataRole = node.getAttribute('data-role');\n if (dataRole === 'assistant' || dataRole === 'user') {\n role = dataRole;\n // assistant-ui sets data-message-id on message roots\n messageId = node.getAttribute('data-message-id') ?? undefined;\n break;\n }\n node = node.parentElement;\n }\n\n setQuote({ text: selection, sourceRole: role, sourceMessageId: messageId });\n }\n }\n };\n\n // ── PostMessage handler (from iframes) ───────────────────────────\n // Accepts messages from any origin, but only from a frame embedded\n // directly in this window: the SDK consumer controls which iframes are\n // embedded, and that is the trust boundary. A popup, an opener or another\n // tab holding a reference to this window cannot stage composer text.\n const handleMessage = (event: MessageEvent) => {\n const data = event.data;\n if (\n data &&\n typeof data === 'object' &&\n data.type === 'athena-add-to-composer' &&\n typeof data.text === 'string' &&\n data.text.trim().length > 0 &&\n isDirectChildFrame(event.source, win) &&\n takes(null)\n ) {\n setQuote({\n text: data.text,\n sourceTitle: data.sourceTitle,\n sourceAssetId: data.sourceAssetId,\n });\n }\n };\n\n doc.addEventListener('keydown', handleKeydown, true); // capture phase to beat the browser\n doc.addEventListener('focusin', handleFocusIn, true);\n win.addEventListener('message', handleMessage);\n\n return () => {\n doc.removeEventListener('keydown', handleKeydown, true);\n doc.removeEventListener('focusin', handleFocusIn, true);\n win.removeEventListener('message', handleMessage);\n };\n }, [scope, setQuote]);\n}\n"],"names":["_a"],"mappings":";;;;AA+BA,MAAM,WAAW,cAAwC,IAAI;AAatD,SAAS,mBAA+B;AAC7C,SAAO,YAA6B,OAAO,EAAE,OAAO,OAAO;AAC7D;AAOO,SAAS,cAAc,EAAE,UAAU,SAAsD;AAC9F,QAAM,QAAQ,WAAW,QAAQ;AACjC,MAAI,MAAO,QAAO,oBAAC,oBAAA,EAAmB,OAAe,UAAS;AAC9D,MAAI,MAAO,QAAO,oBAAA,UAAA,EAAG,SAAA,CAAS;AAC9B,SAAO,oBAAC,oBAAkB,U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iB,KAAK;AACpD;AAAA,YACF;AACA,mBAAO,KAAK;AAAA,UACd;AAEA,mBAAS,EAAE,MAAM,WAAW,YAAY,MAAM,iBAAiB,WAAW;AAAA,QAC5E;AAAA,MACF;AAAA,IACF;AAOA,UAAM,gBAAgB,CAAC,UAAwB;AAC7C,YAAM,OAAO,MAAM;AACnB,UACE,QACA,OAAO,SAAS,YAChB,KAAK,SAAS,4BACd,OAAO,KAAK,SAAS,YACrB,KAAK,KAAK,KAAA,EAAO,SAAS,KAC1B,mBAAmB,MAAM,QAAQ,GAAG,KACpC,MAAM,IAAI,GACV;AACA,iBAAS;AAAA,UACP,MAAM,KAAK;AAAA,UACX,aAAa,KAAK;AAAA,UAClB,eAAe,KAAK;AAAA,QAAA,CACrB;AAAA,MACH;AAAA,IACF;AAEA,QAAI,iBAAiB,WAAW,eAAe,IAAI;AACnD,QAAI,iBAAiB,WAAW,eAAe,IAAI;AACnD,QAAI,iBAAiB,WAAW,aAAa;AAE7C,WAAO,MAAM;AACX,UAAI,oBAAoB,WAAW,eAAe,IAAI;AACtD,UAAI,oBAAoB,WAAW,eAAe,IAAI;AACtD,UAAI,oBAAoB,WAAW,aAAa;AAAA,IAClD;AAAA,EACF,GAAG,CAAC,OAAO,QAAQ,CAAC;AACtB;"}
|
|
1
|
+
{"version":3,"file":"QuoteContext.js","sources":["../../src/composer/QuoteContext.tsx"],"sourcesContent":["import {\n createContext,\n type RefObject,\n useContext,\n useEffect,\n useMemo,\n useState,\n type ReactNode,\n} from 'react';\nimport { useStore } from 'zustand';\nimport { createStore, type StoreApi } from 'zustand/vanilla';\n\nexport interface QuoteData {\n /** The selected/quoted text. */\n text: string;\n /** Title of the source (e.g., asset title, document name). */\n sourceTitle?: string;\n /** Asset ID of the source (for attribution). */\n sourceAssetId?: string;\n /** Message ID of the source message (when quoting from chat). */\n sourceMessageId?: string;\n /** Role of the source message ('assistant' | 'user'). */\n sourceRole?: string;\n}\n\ninterface QuoteContextValue {\n quote: QuoteData | null;\n setQuote: (quote: QuoteData | null) => void;\n clearQuote: () => void;\n}\n\nconst QuoteCtx = createContext<QuoteContextValue | null>(null);\n\ninterface QuoteStoreState {\n quote: QuoteData | null;\n}\n\n/**\n * A composer's pending quote, kept outside React (`createQuoteStore`), like\n * `AttachmentStore`: one per chat when a host shows several.\n */\nexport type QuoteStore = StoreApi<QuoteStoreState>;\n\n/** An empty `QuoteStore`, for `<QuoteProvider store>`. */\nexport function createQuoteStore(): QuoteStore {\n return createStore<QuoteStoreState>(() => ({ quote: null }));\n}\n\n/**\n * The composer's pending quote. Like \\`AttachmentProvider\\`, a `store` makes\n * it that store's, and without one it reuses a provider already mounted\n * above, so a host can keep the quote across a remounting \\`AthenaChat\\`.\n */\nexport function QuoteProvider({ children, store }: { children: ReactNode; store?: QuoteStore }) {\n const outer = useContext(QuoteCtx);\n if (store) return <StoreQuoteProvider store={store}>{children}</StoreQuoteProvider>;\n if (outer) return <>{children}</>;\n return <OwnQuoteProvider>{children}</OwnQuoteProvider>;\n}\n\nfunction OwnQuoteProvider({ children }: { children: ReactNode }) {\n const [store] = useState(createQuoteStore);\n return <StoreQuoteProvider store={store}>{children}</StoreQuoteProvider>;\n}\n\nfunction StoreQuoteProvider({ children, store }: { children: ReactNode; store: QuoteStore }) {\n const quote = useStore(store, (state) => state.quote);\n const actions = useMemo(\n () => ({\n setQuote: (next: QuoteData | null) => store.setState({ quote: next }),\n clearQuote: () => store.setState({ quote: null }),\n }),\n [store],\n );\n const value = useMemo(() => ({ quote, ...actions }), [quote, actions]);\n\n return (\n <QuoteCtx.Provider value={value}>\n {children}\n </QuoteCtx.Provider>\n );\n}\n\nexport function useQuote(): QuoteContextValue {\n const ctx = useContext(QuoteCtx);\n if (!ctx) {\n throw new Error('[AthenaSDK] useQuote must be used within <QuoteProvider>');\n }\n return ctx;\n}\n\n/**\n * Whether a message came from a frame embedded directly in this window, for\n * any origin: the window of one of this document's iframes (an identity\n * comparison, safe cross-origin), or, for a frame inside a shadow root, a\n * window whose `parent` is this window (`parent` is readable on a\n * cross-origin window). A message port, a worker, this window itself, a\n * grandchild frame or an unrelated window is refused. `win` is the window the\n * message came to (default: this one), e.g. a popped-out chat's.\n */\nexport function isDirectChildFrame(\n source: MessageEventSource | null,\n win: Window = window,\n): boolean {\n if (!source || source === win) return false;\n for (const frame of win.document.querySelectorAll('iframe')) {\n if (frame.contentWindow === source) return true;\n }\n try {\n return Reflect.get(source, 'parent') === win;\n } catch {\n return false;\n }\n}\n\n/** `AthenaChat`'s thread root: the chats `useQuoteFromPostMessage` tells apart. */\nconst CHAT_ROOT_SELECTOR = '.aui-thread-root';\n\n/**\n * The chat the person last focused in each window, which takes a quote that\n * names no chat (a selection outside every chat, an embedded frame's text)\n * when that window shows several. A focus, not data: no state of the chats\n * themselves.\n */\nconst lastFocusedChatRoots = new WeakMap<Document, Element>();\n\n/** The element a node is, or sits in; duck-typed, since a pop-out window's nodes are another realm's. */\nfunction elementOf(node: Node | null | undefined): Element | null {\n if (!node) return null;\n return node.nodeType === 1 ? (node as Element) : node.parentElement;\n}\n\nexport interface QuoteFromPostMessageOptions {\n /**\n * An element inside the chat this composer belongs to. With several chats in\n * one window, a ⌘L selection goes to the chat it was made in, and one made\n * outside every chat (or an embedded frame's text) to the chat the person\n * last focused; the keys and an embedded frame's messages are heard in this\n * element's own window, a pop-out included. Without it, every quote is this\n * composer's, as before.\n */\n scope?: RefObject<Element | null>;\n}\n\n/**\n * Listens for:\n * 1. Cmd+L / Ctrl+L keydown — grabs the current text selection and sets it as a quote.\n * `preventDefault` stops the browser from focusing the URL bar.\n * 2. PostMessage events from child iframes (asset panels, embedded content)\n * with type `athena-add-to-composer`, only from a frame embedded directly\n * in this window ({@link isDirectChildFrame}).\n *\n * Mount this once per composer inside AthenaProvider (`AthenaChat` does).\n */\nexport function useQuoteFromPostMessage({ scope }: QuoteFromPostMessageOptions = {}) {\n const { setQuote } = useQuote();\n\n useEffect(() => {\n const doc = scope?.current?.ownerDocument ?? document;\n const win = doc.defaultView ?? window;\n const chatRoot = () => scope?.current?.closest(CHAT_ROOT_SELECTOR) ?? null;\n // Whether this composer takes a quote made at `anchor` (null: one that names no chat).\n const takes = (anchor: Node | null) => {\n const mine = chatRoot();\n if (!mine) return true;\n const owner = elementOf(anchor)?.closest(CHAT_ROOT_SELECTOR) ?? null;\n if (owner) return owner === mine;\n const remembered = lastFocusedChatRoots.get(doc);\n const focused = remembered?.isConnected ? remembered : doc.querySelector(CHAT_ROOT_SELECTOR);\n return focused === mine;\n };\n\n const handleFocusIn = (event: FocusEvent) => {\n const mine = chatRoot();\n const target = event.target as Node | null;\n if (mine && target && typeof target.nodeType === 'number' && mine.contains(target)) {\n lastFocusedChatRoots.set(doc, mine);\n }\n };\n\n // ── Cmd+L / Ctrl+L keyboard handler ──────────────────────────────\n const handleKeydown = (e: KeyboardEvent) => {\n if ((e.metaKey || e.ctrlKey) && e.key?.toLowerCase() === 'l') {\n const sel = doc.getSelection();\n const selection = sel?.toString()?.trim();\n\n if (selection && selection.length > 0 && takes(sel?.anchorNode ?? null)) {\n e.preventDefault();\n\n // Walk up from the selection anchor to find the message container.\n // assistant-ui message roots have data-role=\"assistant\" or data-role=\"user\".\n let messageId: string | undefined;\n let role: string | undefined;\n let node = elementOf(sel?.anchorNode);\n while (node && node !== doc.body) {\n const dataRole = node.getAttribute('data-role');\n if (dataRole === 'assistant' || dataRole === 'user') {\n role = dataRole;\n // assistant-ui sets data-message-id on message roots\n messageId = node.getAttribute('data-message-id') ?? undefined;\n break;\n }\n node = node.parentElement;\n }\n\n setQuote({ text: selection, sourceRole: role, sourceMessageId: messageId });\n }\n }\n };\n\n // ── PostMessage handler (from iframes) ───────────────────────────\n // Accepts messages from any origin, but only from a frame embedded\n // directly in this window: the SDK consumer controls which iframes are\n // embedded, and that is the trust boundary. A popup, an opener or another\n // tab holding a reference to this window cannot stage composer text.\n const handleMessage = (event: MessageEvent) => {\n const data = event.data;\n if (\n data &&\n typeof data === 'object' &&\n data.type === 'athena-add-to-composer' &&\n typeof data.text === 'string' &&\n data.text.trim().length > 0 &&\n isDirectChildFrame(event.source, win) &&\n takes(null)\n ) {\n setQuote({\n text: data.text,\n sourceTitle: data.sourceTitle,\n sourceAssetId: data.sourceAssetId,\n });\n }\n };\n\n doc.addEventListener('keydown', handleKeydown, true); // capture phase to beat the browser\n doc.addEventListener('focusin', handleFocusIn, true);\n win.addEventListener('message', handleMessage);\n\n return () => {\n doc.removeEventListener('keydown', handleKeydown, true);\n doc.removeEventListener('focusin', handleFocusIn, true);\n win.removeEventListener('message', handleMessage);\n };\n }, [scope, setQuote]);\n}\n"],"names":["_a"],"mappings":";;;;AA+BA,MAAM,WAAW,cAAwC,IAAI;AAatD,SAAS,mBAA+B;AAC7C,SAAO,YAA6B,OAAO,EAAE,OAAO,OAAO;AAC7D;AAOO,SAAS,cAAc,EAAE,UAAU,SAAsD;AAC9F,QAAM,QAAQ,WAAW,QAAQ;AACjC,MAAI,MAAO,QAAO,oBAAC,oBAAA,EAAmB,OAAe,UAAS;AAC9D,MAAI,MAAO,QAAO,oBAAA,UAAA,EAAG,SAAA,CAAS;AAC9B,SAAO,oBAAC,oBAAkB,UAAS;AACrC;AAEA,SAAS,iBAAiB,EAAE,YAAqC;AAC/D,QAAM,CAAC,KAAK,IAAI,SAAS,gBAAgB;AACzC,SAAO,oBAAC,oBAAA,EAAmB,OAAe,SAAA,CAAS;AACrD;AAEA,SAAS,mBAAmB,EAAE,UAAU,SAAqD;AAC3F,QAAM,QAAQ,SAAS,OAAO,CAAC,UAAU,MAAM,KAAK;AACpD,QAAM,UAAU;AAAA,IACd,OAAO;AAAA,MACL,UAAU,CAAC,SAA2B,MAAM,SAAS,EAAE,OAAO,MAAM;AAAA,MACpE,YAAY,MAAM,MAAM,SAAS,EAAE,OAAO,MAAM;AAAA,IAAA;AAAA,IAElD,CAAC,KAAK;AAAA,EAAA;AAER,QAAM,QAAQ,QAAQ,OAAO,EAAE,OAAO,GAAG,QAAA,IAAY,CAAC,OAAO,O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AAW,eAAe,IAAI;AACnD,QAAI,iBAAiB,WAAW,eAAe,IAAI;AACnD,QAAI,iBAAiB,WAAW,aAAa;AAE7C,WAAO,MAAM;AACX,UAAI,oBAAoB,WAAW,eAAe,IAAI;AACtD,UAAI,oBAAoB,WAAW,eAAe,IAAI;AACtD,UAAI,oBAAoB,WAAW,aAAa;AAAA,IAClD;AAAA,EACF,GAAG,CAAC,OAAO,QAAQ,CAAC;AACtB;"}
|
|
@@ -23,6 +23,8 @@ const mintThreadId = require("../threads/mint-thread-id.cjs");
|
|
|
23
23
|
const statewireLifecycleContext = require("./statewire-lifecycle-context.cjs");
|
|
24
24
|
const composerHandoff = require("../composer/composer-handoff.cjs");
|
|
25
25
|
const statewireHistoryContext = require("./statewire-history-context.cjs");
|
|
26
|
+
const earlierStepsButton = require("../chat/super-grouping/earlier-steps-button.cjs");
|
|
27
|
+
const useTurnSteps = require("../chat/super-grouping/use-turn-steps.cjs");
|
|
26
28
|
const statewireWindowContext = require("./statewire-window-context.cjs");
|
|
27
29
|
const StatewireClientToolBridge = require("../chat/StatewireClientToolBridge.cjs");
|
|
28
30
|
const StatewireThreadConfigLaneSync = require("../runtime/StatewireThreadConfigLaneSync.cjs");
|
|
@@ -47,6 +49,7 @@ const durableThreadSnapshotCache = require("../agent-runtime/src/durable-thread-
|
|
|
47
49
|
const threadSnapshotCache = require("../agent-runtime/src/thread-snapshot-cache.cjs");
|
|
48
50
|
const chatOutboxAttachments = require("../agent-runtime/src/chat-outbox-attachments.cjs");
|
|
49
51
|
const toolOutputs = require("../agent-runtime/src/tool-outputs.cjs");
|
|
52
|
+
const historyStore = require("../agent-runtime/src/history-store.cjs");
|
|
50
53
|
const threadStatus = require("../agent-runtime/src/thread-status.cjs");
|
|
51
54
|
const useDeepAgentChatOutbox = require("../agent-runtime/src/use-deep-agent-chat-outbox.cjs");
|
|
52
55
|
const useDeepAgentConfig = require("../agent-runtime/src/use-deep-agent-config.cjs");
|
|
@@ -416,7 +419,7 @@ function AthenaStatewireStandalone({
|
|
|
416
419
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
417
420
|
[modeKey, modeScope, modePicks, sessionChannels, published, setModePick, setSessionChannel]
|
|
418
421
|
);
|
|
419
|
-
const scope = published && /* @__PURE__ */ jsxRuntime.jsx(react.AuiProvider, { value: published.client, children: /* @__PURE__ */ jsxRuntime.jsx(AthenaContext.AthenaContext.Provider, { value: athenaConfig, children: /* @__PURE__ */ jsxRuntime.jsx(threadIdContext.AthenaStatewireThreadIdContext.Provider, { value: published.threadId, children: /* @__PURE__ */ jsxRuntime.jsx(statewireLifecycleContext.AthenaStatewireLifecycleContext.Provider, { value: published.lifecycle, children: /* @__PURE__ */ jsxRuntime.jsx(threadStatus.DeepAgentConnectionContext.Provider, { value: published.lifecycle.connection, children: /* @__PURE__ */ jsxRuntime.jsx(statewireServerLaneContext.AthenaStatewireServerLaneContext.Provider, { value: published.serverLane, children: /* @__PURE__ */ jsxRuntime.jsx(statewireWindowContext.StatewireToolOutputsContext.Provider, { value: runtimeProps.toolOutputs, children: /* @__PURE__ */ jsxRuntime.jsx(statewireHistoryContext.StatewireHistoryContext.Provider, { value: runtimeProps.historyStore, children: /* @__PURE__ */ jsxRuntime.jsxs(tooltip.TooltipProvider, { children: [
|
|
422
|
+
const scope = published && /* @__PURE__ */ jsxRuntime.jsx(react.AuiProvider, { value: published.client, children: /* @__PURE__ */ jsxRuntime.jsx(AthenaContext.AthenaContext.Provider, { value: athenaConfig, children: /* @__PURE__ */ jsxRuntime.jsx(threadIdContext.AthenaStatewireThreadIdContext.Provider, { value: published.threadId, children: /* @__PURE__ */ jsxRuntime.jsx(statewireLifecycleContext.AthenaStatewireLifecycleContext.Provider, { value: published.lifecycle, children: /* @__PURE__ */ jsxRuntime.jsx(threadStatus.DeepAgentConnectionContext.Provider, { value: published.lifecycle.connection, children: /* @__PURE__ */ jsxRuntime.jsx(statewireServerLaneContext.AthenaStatewireServerLaneContext.Provider, { value: published.serverLane, children: /* @__PURE__ */ jsxRuntime.jsx(statewireWindowContext.StatewireToolOutputsContext.Provider, { value: runtimeProps.toolOutputs, children: /* @__PURE__ */ jsxRuntime.jsx(useTurnSteps.TurnStepsControlContext.Provider, { value: earlierStepsButton.EarlierStepsButton, children: /* @__PURE__ */ jsxRuntime.jsx(statewireHistoryContext.StatewireHistoryContext.Provider, { value: runtimeProps.historyStore, children: /* @__PURE__ */ jsxRuntime.jsxs(tooltip.TooltipProvider, { children: [
|
|
420
423
|
/* @__PURE__ */ jsxRuntime.jsx(StatewireClientToolBridge.StatewireClientToolBridge, { tools: clientTools, threadId: published.threadId }),
|
|
421
424
|
/* @__PURE__ */ jsxRuntime.jsx(
|
|
422
425
|
StatewireThreadConfigLaneSync.StatewireThreadConfigLaneSync,
|
|
@@ -436,7 +439,7 @@ function AthenaStatewireStandalone({
|
|
|
436
439
|
children
|
|
437
440
|
}
|
|
438
441
|
) }) })
|
|
439
|
-
] }) }) }) }) }) }) }) }) });
|
|
442
|
+
] }) }) }) }) }) }) }) }) }) });
|
|
440
443
|
return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
|
|
441
444
|
/* @__PURE__ */ jsxRuntime.jsx(
|
|
442
445
|
AthenaStatewireRuntimeMount,
|
|
@@ -742,11 +745,17 @@ function AthenaProvider({
|
|
|
742
745
|
);
|
|
743
746
|
const [composerHandoff$1] = require$$0.useState(composerHandoff.createComposerHandoffStore);
|
|
744
747
|
const [toolOutputs$1] = require$$0.useState(() => toolOutputs.createDeepAgentToolOutputStore());
|
|
745
|
-
const [historyStore] = require$$0.useState(statewireHistoryContext.createStatewireHistoryStore);
|
|
748
|
+
const [historyStore$1] = require$$0.useState(statewireHistoryContext.createStatewireHistoryStore);
|
|
746
749
|
const principal = ((_a = authContext == null ? void 0 : authContext.user) == null ? void 0 : _a.userId) ?? "";
|
|
750
|
+
const pagedIdentity = require$$0.useRef(null);
|
|
747
751
|
require$$0.useEffect(() => {
|
|
748
752
|
snapshotCache.clear();
|
|
749
753
|
toolOutputs$1.clear();
|
|
754
|
+
const previous = pagedIdentity.current;
|
|
755
|
+
if (previous !== null && (previous.principal !== principal || previous.apiKey !== configuredApiKey)) {
|
|
756
|
+
historyStore.clearDeepAgentHistoryStores();
|
|
757
|
+
}
|
|
758
|
+
pagedIdentity.current = { principal, apiKey: configuredApiKey };
|
|
750
759
|
}, [snapshotCache, toolOutputs$1, principal, configuredApiKey]);
|
|
751
760
|
const sessionPrincipal = statewireSessionKey.statewireSessionPrincipal(authContext);
|
|
752
761
|
const [sessionLane] = require$$0.useState(
|
|
@@ -830,7 +839,7 @@ function AthenaProvider({
|
|
|
830
839
|
extraRunConfig: configuredExtraRunConfig,
|
|
831
840
|
snapshotCache,
|
|
832
841
|
toolOutputs: toolOutputs$1,
|
|
833
|
-
historyStore,
|
|
842
|
+
historyStore: historyStore$1,
|
|
834
843
|
chatOutbox: chatOutboxHost,
|
|
835
844
|
sessionLane,
|
|
836
845
|
subagentLaneHistory,
|