@ttt-productions/chat-react 0.13.15 → 0.13.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/context/ChatNameResolverContext.d.ts +3 -3
- package/dist/context/ChatNameResolverContext.d.ts.map +1 -1
- package/dist/context/ChatNameResolverContext.js +3 -3
- package/dist/context/ChatNameResolverContext.js.map +1 -1
- package/dist/firestore/queries.js +1 -1
- package/dist/firestore/queries.js.map +1 -1
- package/dist/hooks/useChatMessages.d.ts +3 -3
- package/dist/hooks/useChatMessages.d.ts.map +1 -1
- package/dist/hooks/useChatMessages.js +20 -12
- package/dist/hooks/useChatMessages.js.map +1 -1
- package/dist/index.d.ts +32 -18
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +18 -11
- package/dist/index.js.map +1 -1
- package/dist/realtime/channel-client.d.ts.map +1 -1
- package/dist/realtime/channel-client.js +97 -32
- package/dist/realtime/channel-client.js.map +1 -1
- package/dist/realtime/inbox-client.d.ts.map +1 -1
- package/dist/realtime/inbox-client.js +29 -11
- package/dist/realtime/inbox-client.js.map +1 -1
- package/dist/realtime/initial-load-budget.d.ts.map +1 -1
- package/dist/realtime/initial-load-budget.js.map +1 -1
- package/dist/realtime/map.d.ts +0 -2
- package/dist/realtime/map.d.ts.map +1 -1
- package/dist/realtime/map.js +3 -4
- package/dist/realtime/map.js.map +1 -1
- package/dist/realtime/shared.d.ts +0 -1
- package/dist/realtime/shared.d.ts.map +1 -1
- package/dist/realtime/shared.js +2 -6
- package/dist/realtime/shared.js.map +1 -1
- package/dist/realtime/socket.d.ts.map +1 -1
- package/dist/realtime/socket.js +1 -11
- package/dist/realtime/socket.js.map +1 -1
- package/dist/realtime/transport.d.ts +1 -2
- package/dist/realtime/transport.d.ts.map +1 -1
- package/dist/realtime/transport.js +1 -1
- package/dist/realtime/transport.js.map +1 -1
- package/dist/realtime/useRealtimeChatMessages.d.ts +4 -4
- package/dist/realtime/useRealtimeChatMessages.d.ts.map +1 -1
- package/dist/realtime/useRealtimeChatMessages.js +5 -5
- package/dist/realtime/useRealtimeChatMessages.js.map +1 -1
- package/dist/realtime/wire.d.ts +0 -2
- package/dist/realtime/wire.d.ts.map +1 -1
- package/dist/realtime/wire.js +0 -6
- package/dist/realtime/wire.js.map +1 -1
- package/dist/types.d.ts +3 -3
- package/dist/types.js.map +1 -1
- package/dist/ui/ChatShell.d.ts +5 -5
- package/dist/ui/ChatShell.d.ts.map +1 -1
- package/dist/ui/ChatShell.js +37 -34
- package/dist/ui/ChatShell.js.map +1 -1
- package/dist/ui/Composer.d.ts +1 -1
- package/dist/ui/Composer.js +12 -12
- package/dist/ui/Composer.js.map +1 -1
- package/dist/ui/MessageItemDefault.d.ts +2 -2
- package/dist/ui/MessageItemDefault.d.ts.map +1 -1
- package/dist/ui/MessageItemDefault.js +26 -24
- package/dist/ui/MessageItemDefault.js.map +1 -1
- package/dist/ui/MessageList.d.ts +3 -3
- package/dist/ui/MessageList.d.ts.map +1 -1
- package/dist/ui/MessageList.js +13 -16
- package/dist/ui/MessageList.js.map +1 -1
- package/dist/ui/SenderName.js +3 -3
- package/dist/ui/SenderName.js.map +1 -1
- package/dist/ui/menus.d.ts +1 -1
- package/dist/ui/menus.d.ts.map +1 -1
- package/dist/ui/menus.js +4 -4
- package/dist/ui/menus.js.map +1 -1
- package/package.json +10 -10
- package/dist/realtime/index.d.ts +0 -19
- package/dist/realtime/index.d.ts.map +0 -1
- package/dist/realtime/index.js +0 -15
- package/dist/realtime/index.js.map +0 -1
|
@@ -7,9 +7,9 @@
|
|
|
7
7
|
// mirrors the latest snapshot into an observable store + a per-channel unread set.
|
|
8
8
|
// Same connection lifecycle as the channel client (subprotocol auth, reconnect,
|
|
9
9
|
// 4401 re-grant once, 4403 stop, auth-switch teardown).
|
|
10
|
-
import { createReconnectController } from '@ttt-productions/realtime-core';
|
|
11
|
-
import { ChatMarkReadResultPayloadSchema, SERVER_KINDS, } from '@ttt-productions/chat-schemas';
|
|
12
|
-
import {
|
|
10
|
+
import { createReconnectController, } from '@ttt-productions/realtime-core';
|
|
11
|
+
import { ChatMarkReadResultPayloadSchema, SERVER_KINDS, CLIENT_KINDS, CHAT_CLOSE_CODES, } from '@ttt-productions/chat-schemas';
|
|
12
|
+
import { buildFrame, parseFrame, isInboxSnapshot, } from './wire.js';
|
|
13
13
|
import { defaultTimers, isChatAccessDeniedError, isTerminalErrorCode, newCorrelationId, TERMINAL_ERROR_CODE, } from './shared.js';
|
|
14
14
|
import { InitialLoadBudget } from './initial-load-budget.js';
|
|
15
15
|
import { createDiagnosticsEmitter, safeDiagnosticLabel, CHAT_CLIENT_DIAGNOSTIC_EVENTS as DIAG, } from './diagnostics.js';
|
|
@@ -201,10 +201,14 @@ export class InboxClient {
|
|
|
201
201
|
hasUnread: this.state.hasUnread,
|
|
202
202
|
});
|
|
203
203
|
// The DO sends a snapshot on accept; a `resume` re-requests it after a reconnect gap.
|
|
204
|
-
const sent = this.sendFrame(
|
|
204
|
+
const sent = this.sendFrame(CLIENT_KINDS.RESUME, {});
|
|
205
205
|
// The inbox resume is CURSORLESS by contract (the DO always answers with a full
|
|
206
206
|
// authoritative snapshot) — there is no `afterSeq` half to record here.
|
|
207
|
-
this.diag?.(DIAG.INBOX_RESUME_REQUEST, {
|
|
207
|
+
this.diag?.(DIAG.INBOX_RESUME_REQUEST, {
|
|
208
|
+
attempt: this.connectAttempt,
|
|
209
|
+
cursorless: true,
|
|
210
|
+
sent,
|
|
211
|
+
});
|
|
208
212
|
}
|
|
209
213
|
onClose(code, _reason) {
|
|
210
214
|
this.socket = null;
|
|
@@ -285,14 +289,18 @@ export class InboxClient {
|
|
|
285
289
|
// carries either a full snapshot or a `{ hasUnread }` dock-dot patch. Route both
|
|
286
290
|
// instead of silently dropping the `unread` type (C-M2).
|
|
287
291
|
if (frame.type !== 'snapshot' && frame.type !== 'unread') {
|
|
288
|
-
this.diag?.(DIAG.INBOX_FRAME_DROPPED, {
|
|
292
|
+
this.diag?.(DIAG.INBOX_FRAME_DROPPED, {
|
|
293
|
+
kind: safeDiagnosticLabel(frame.type),
|
|
294
|
+
reason: 'unknown-type',
|
|
295
|
+
});
|
|
289
296
|
return;
|
|
290
297
|
}
|
|
291
298
|
const payload = frame.payload;
|
|
292
299
|
if (isInboxSnapshot(payload)) {
|
|
293
300
|
this.applySnapshot(payload, frame.type);
|
|
294
301
|
}
|
|
295
|
-
else if (frame.type === 'unread' &&
|
|
302
|
+
else if (frame.type === 'unread' &&
|
|
303
|
+
typeof payload.hasUnread === 'boolean') {
|
|
296
304
|
const hasUnread = Boolean(payload.hasUnread);
|
|
297
305
|
const before = this.state.hasUnread;
|
|
298
306
|
this.setState({ hasUnread });
|
|
@@ -329,7 +337,13 @@ export class InboxClient {
|
|
|
329
337
|
const before = this.state;
|
|
330
338
|
if (!before.hasLoadedInitialData)
|
|
331
339
|
this.initialLoad.loaded();
|
|
332
|
-
this.setState({
|
|
340
|
+
this.setState({
|
|
341
|
+
registry,
|
|
342
|
+
hasUnread,
|
|
343
|
+
unreadChannelRefs,
|
|
344
|
+
hasLoadedInitialData: true,
|
|
345
|
+
initialLoadFailed: false,
|
|
346
|
+
});
|
|
333
347
|
if (!this.diag)
|
|
334
348
|
return;
|
|
335
349
|
// SIZES ONLY — a channelRef names one specific conversation and never enters a
|
|
@@ -344,7 +358,8 @@ export class InboxClient {
|
|
|
344
358
|
unreadCount: unreadChannelRefs.length,
|
|
345
359
|
registryDelta: registry.length - before.registry.length,
|
|
346
360
|
});
|
|
347
|
-
const unreadChanged = before.hasUnread !== hasUnread ||
|
|
361
|
+
const unreadChanged = before.hasUnread !== hasUnread ||
|
|
362
|
+
before.unreadChannelRefs.length !== unreadChannelRefs.length;
|
|
348
363
|
if (unreadChanged) {
|
|
349
364
|
this.diag(DIAG.INBOX_UNREAD_UPDATED, {
|
|
350
365
|
source: safeDiagnosticLabel(source),
|
|
@@ -377,7 +392,7 @@ export class InboxClient {
|
|
|
377
392
|
*/
|
|
378
393
|
markRead(channelRef) {
|
|
379
394
|
const requestId = newCorrelationId();
|
|
380
|
-
const sent = this.sendFrame(
|
|
395
|
+
const sent = this.sendFrame(CLIENT_KINDS.MARK_READ, { channelRef, requestId });
|
|
381
396
|
// The ref itself is never logged — only that a mark-read was written and what the
|
|
382
397
|
// unread projection looked like at that moment (the DO's snapshot is what clears it).
|
|
383
398
|
this.diag?.(DIAG.INBOX_MARK_READ, { sent, unreadCount: this.state.unreadChannelRefs.length });
|
|
@@ -389,7 +404,10 @@ export class InboxClient {
|
|
|
389
404
|
applyMarkReadResult(payload) {
|
|
390
405
|
const parsed = ChatMarkReadResultPayloadSchema.safeParse(payload);
|
|
391
406
|
if (!parsed.success) {
|
|
392
|
-
this.diag?.(DIAG.INBOX_FRAME_DROPPED, {
|
|
407
|
+
this.diag?.(DIAG.INBOX_FRAME_DROPPED, {
|
|
408
|
+
kind: SERVER_KINDS.MARK_READ_RESULT,
|
|
409
|
+
reason: 'malformed-payload',
|
|
410
|
+
});
|
|
393
411
|
return;
|
|
394
412
|
}
|
|
395
413
|
const resolve = this.pendingMarkReads.get(parsed.data.requestId);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"inbox-client.js","sourceRoot":"","sources":["../../src/realtime/inbox-client.ts"],"names":[],"mappings":"AAAA,gFAAgF;AAChF,8EAA8E;AAC9E,gFAAgF;AAChF,EAAE;AACF,iFAAiF;AACjF,2EAA2E;AAC3E,mFAAmF;AACnF,gFAAgF;AAChF,wDAAwD;AAExD,OAAO,EAAE,yBAAyB,EAA4B,MAAM,gCAAgC,CAAC;AACrG,OAAO,EACL,+BAA+B,EAC/B,YAAY,GAEb,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,YAAY,EACZ,gBAAgB,EAChB,UAAU,EACV,UAAU,EACV,eAAe,GAGhB,MAAM,WAAW,CAAC;AAGnB,OAAO,EACL,aAAa,EACb,uBAAuB,EACvB,mBAAmB,EACnB,gBAAgB,EAChB,mBAAmB,GACpB,MA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C,IAAI,EAAE,iBAAiB,CAAC,CAAC;QACxC,CAAC;QACD,IAAI,CAAC,sBAAsB,CAAC,EAAE,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,iBAAiB,EAAE,CAAC,CAAC;QACpE,IAAI,CAAC,QAAQ,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAC;IACtC,CAAC;CACF;AAED;;;;;;;;;GASG;AACH,SAAS,gBAAgB,CAAC,IAAuB;IAC/C,MAAM,IAAI,GAAa,EAAE,CAAC;IAC1B,KAAK,MAAM,CAAC,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;QAC9B,IAAI,CAAC,CAAC,KAAK,KAAK,QAAQ;YAAE,SAAS;QACnC,IAAI,CAAC,CAAC,QAAQ,KAAK,IAAI;YAAE,SAAS;QAClC,IAAI,CAAC,CAAC,MAAM,KAAK,IAAI;YAAE,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC;IACjD,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["// The Inbox realtime client: a SEPARATE WebSocket (scope `inbox`) to the user's\n// inbox DO. It maintains the channel/invite registry + unread projection that\n// drives the inbox view — DOTS ONLY, no counts (Contract C / \"Unread + inbox\").\n//\n// The inbox DO pushes a full `snapshot` ({ registry, hasUnread }) on connect, on\n// `resume`, and on every live delta (a projection apply). This client just\n// mirrors the latest snapshot into an observable store + a per-channel unread set.\n// Same connection lifecycle as the channel client (subprotocol auth, reconnect,\n// 4401 re-grant once, 4403 stop, auth-switch teardown).\n\nimport { createReconnectController, type ReconnectController } from '@ttt-productions/realtime-core';\nimport {\n ChatMarkReadResultPayloadSchema,\n SERVER_KINDS,\n type ChatMarkReadFailureCode,\n} from '@ttt-productions/chat-schemas';\nimport {\n CLIENT_FRAME,\n CHAT_CLOSE_CODES,\n buildFrame,\n parseFrame,\n isInboxSnapshot,\n type WireInboxSnapshot,\n type WireRegistryEntry,\n} from './wire.js';\nimport type { RealtimeSocket, SocketFactory } from './socket.js';\nimport type { GrantProvider, TransportTimers, RealtimeStatus } from './shared.js';\nimport {\n defaultTimers,\n isChatAccessDeniedError,\n isTerminalErrorCode,\n newCorrelationId,\n TERMINAL_ERROR_CODE,\n} from './shared.js';\nimport { InitialLoadBudget } from './initial-load-budget.js';\nimport {\n createDiagnosticsEmitter,\n safeDiagnosticLabel,\n CHAT_CLIENT_DIAGNOSTIC_EVENTS as DIAG,\n type ChatClientDiagnosticsEmitter,\n type ChatClientDiagnosticsOption,\n} from './diagnostics.js';\n\nexport interface InboxClientState {\n status: RealtimeStatus;\n /** Active (non-tombstoned) channel/invite registry entries — inbox-view visibility. */\n registry: WireRegistryEntry[];\n /** True if ANY active channel/invite has unread (drives the dock dot). */\n hasUnread: boolean;\n /** The set of channelRefs that currently carry an unread dot (per-row dots). */\n unreadChannelRefs: string[];\n /**\n * The last TERMINAL error code (mirrors `ChannelClientState.lastErrorCode`):\n * `'access-denied'` when the inbox grant provider throws `ChatAccessDeniedError`\n * (a genuine, terminal policy \"no\" — e.g. a banned/suspended account), and\n * `'revoked'` on a 4403 REVOKED close. Null while healthy and across transient\n * reconnects. The app subscribes to inbox state directly (there is no inbox React\n * hook in this package), so this stable code is the surface — it invents no new UI.\n */\n lastErrorCode: string | null;\n /**\n * True once the first authoritative snapshot has been applied — the registry and dots\n * are then the inbox runtime's answer, so an empty registry means \"nothing here\"\n * rather than \"not loaded yet\". Once true it stays true.\n */\n hasLoadedInitialData: boolean;\n /**\n * True once the first open has failed for long enough to say so — the same rule as\n * `ChannelClientState.initialLoadFailed`. Cleared by the first snapshot or `retryNow()`.\n */\n initialLoadFailed: boolean;\n}\n\n/**\n * How one `markRead` ended: `ok` — the inbox runtime advanced the read cursor (its\n * fresh snapshot clears the dot); otherwise `code` says why not — the runtime's own\n * reason, `not-sent` (no open socket, nothing was sent), or `connection-lost` (the\n * socket closed before the answer arrived, so the outcome is unknown and the dot stays).\n */\nexport type ChatMarkReadOutcome =\n | { ok: true }\n | { ok: false; code: ChatMarkReadFailureCode | 'not-sent' | 'connection-lost' };\n\nexport interface InboxClientConfig {\n endpoint: string;\n /** The authenticated uid (the inbox owner; the DO serves no one else's data). */\n currentUserId: string;\n /** Mints/refreshes an INBOX-scope grant (scope `{ kind:'inbox', uid }`). */\n grantProvider: GrantProvider;\n socketFactory: SocketFactory;\n timers?: TransportTimers;\n reconnect?: { baseDelayMs?: number; maxDelayMs?: number; maxAttempts?: number | null; random?: () => number };\n /**\n * OPT-IN structured client diagnostics — the SAME option type and emitter the\n * channel client uses (one owner, `./diagnostics.ts`). Default OFF: absent or\n * `false` changes nothing and costs one nullish check. `true` emits one\n * single-line `console.debug` entry per decision under the stable\n * `chat_client_inbox_*` names; a function routes them to the app's logger.\n * Inbox payloads are SIZES ONLY — registry/unread counts and deltas, never a\n * `channelRef` (which names one specific conversation).\n */\n diagnostics?: ChatClientDiagnosticsOption;\n}\n\nconst INITIAL: InboxClientState = {\n status: 'idle',\n registry: [],\n hasUnread: false,\n unreadChannelRefs: [],\n lastErrorCode: null,\n hasLoadedInitialData: false,\n initialLoadFailed: false,\n};\n\nexport class InboxClient {\n private readonly timers: TransportTimers;\n private readonly controller: ReconnectController;\n private socket: RealtimeSocket | null = null;\n private state: InboxClientState = INITIAL;\n private readonly listeners = new Set<(s: InboxClientState) => void>();\n private reauthAttempted = false;\n private reconnectTimer: ReturnType<TransportTimers['setTimeout']> | null = null;\n private closedByUs = false;\n /**\n * The current lifecycle's number, advanced by every `connect()` and `close()`; a grant,\n * timer, or socket callback of an older lifecycle is ignored (FRONTEND-108).\n */\n private lifecycle = 0;\n private readonly initialLoad: InitialLoadBudget;\n /** Mark-reads sent on the current socket, awaiting their correlated result, by requestId. */\n private readonly pendingMarkReads = new Map<string, (outcome: ChatMarkReadOutcome) => void>();\n /** Structured diagnostics emitter, or null when off (the default, zero-overhead). */\n private readonly diag: ChatClientDiagnosticsEmitter;\n /** Monotonic socket-open attempt counter (diagnostics correlation only). */\n private connectAttempt = 0;\n /** Why the CURRENT connect attempt is happening (diagnostics only). */\n private reconnectCause: 'initial' | 'auth-expired' | 'transient-close' | 'grant-error' | 'manual-retry' = 'initial';\n /** The last close code observed, carried into the next attempt's cause line. */\n private lastCloseCode: number | null = null;\n\n constructor(private readonly config: InboxClientConfig) {\n this.timers = config.timers ?? defaultTimers;\n this.controller = createReconnectController(config.reconnect ?? {});\n this.diag = createDiagnosticsEmitter(config.diagnostics);\n this.initialLoad = new InitialLoadBudget(this.timers, () => this.reportInitialLoadFailed());\n }\n\n getState(): InboxClientState {\n return this.state;\n }\n\n subscribe(fn: (s: InboxClientState) => void): () => void {\n this.listeners.add(fn);\n return () => this.listeners.delete(fn);\n }\n\n private setState(patch: Partial<InboxClientState>): void {\n this.state = { ...this.state, ...patch };\n for (const fn of this.listeners) fn(this.state);\n }\n\n async connect(): Promise<void> {\n return this.startLifecycle(true);\n }\n\n /**\n * Retry now (the first-open failure's Retry) — the same rule as `ChannelClient.retryNow`:\n * a reconnect waiting out its backoff opens at once; a stopped lifecycle starts again; an\n * attempt in flight is left to finish; the first-open failure clears either way.\n */\n retryNow(): void {\n if (!this.state.hasLoadedInitialData) this.initialLoad.manualRetry();\n if (this.state.status === 'closed') {\n void this.startLifecycle(false);\n return;\n }\n if (this.reconnectTimer == null) {\n if (this.state.initialLoadFailed) this.setState({ initialLoadFailed: false });\n return;\n }\n this.timers.clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n this.controller.reset();\n this.controller.start();\n this.reconnectCause = 'manual-retry';\n this.setState({ status: 'reconnecting', initialLoadFailed: false });\n void this.openSocket();\n }\n\n private async startLifecycle(freshBudget: boolean): Promise<void> {\n // Idempotency guard (mirrors ChannelClient): connect() only starts a lifecycle\n // from a fresh (idle) or fully torn-down (closed) state. A second connect()\n // while one is already connecting / open / reconnecting is a no-op, so a\n // double-mounted dock cannot open a SECOND inbox socket against the per-uid\n // cap. The reconnect path uses openSocket() / scheduleReconnect() directly\n // (never connect()), so this never blocks a legitimate reconnect.\n if (this.state.status !== 'idle' && this.state.status !== 'closed') return;\n // REVIVE the controller. `controller.close()` is PERMANENT: while it is in\n // state `closed`, `start()` and `onOpen()` no-op and every later `onClose()`\n // returns null — so without this reset a close() → connect() client opens a\n // socket and works normally until its FIRST transient close, then parks\n // terminally in `closed` with reconnect disabled and no surfaced error code.\n this.controller.reset();\n // A terminal verdict (4403 REVOKED / ChatAccessDeniedError) is terminal WITHIN\n // its lifecycle; an explicit connect() is a fresh attempt the authority may\n // legitimately re-deny, so the previous lifecycle's code must not persist.\n // The registry/unread projection is deliberately KEPT — the DO's next snapshot\n // is authoritative, and blanking the dock on every restart is pure UI churn.\n if (isTerminalErrorCode(this.state.lastErrorCode)) this.setState({ lastErrorCode: null });\n this.closedByUs = false;\n this.lifecycle += 1;\n this.reconnectCause = 'initial';\n if (!this.state.hasLoadedInitialData) this.initialLoad.begin(freshBudget);\n this.controller.start();\n this.setState({ status: 'connecting', initialLoadFailed: false });\n await this.openSocket();\n }\n\n private reportInitialLoadFailed(): void {\n if (this.state.hasLoadedInitialData || this.state.initialLoadFailed) return;\n this.setState({ initialLoadFailed: true });\n }\n\n private async openSocket(): Promise<void> {\n const lifecycle = this.lifecycle;\n this.connectAttempt += 1;\n this.diag?.(DIAG.INBOX_CONNECT_ATTEMPT, {\n attempt: this.connectAttempt,\n cause: this.reconnectCause,\n closeCode: this.lastCloseCode,\n registryCount: this.state.registry.length,\n });\n let grantToken: string;\n try {\n grantToken = await this.config.grantProvider();\n } catch (err) {\n if (lifecycle !== this.lifecycle) return;\n // A TERMINAL access denial (the app translated an authoritative policy \"no\"\n // — e.g. Firebase `permission-denied` for a banned/suspended account — into the\n // package-owned ChatAccessDeniedError) must NOT reconnect: the next mint would\n // just re-deny, reconnect-looping forever and warning every cycle. Every other\n // mint failure (network/transient) stays retryable and backs off as before.\n const terminal = isChatAccessDeniedError(err);\n this.diag?.(DIAG.INBOX_GRANT_FAILED, { attempt: this.connectAttempt, terminal });\n if (terminal) return this.denyAccessTerminally();\n this.reconnectCause = 'grant-error';\n if (!this.state.hasLoadedInitialData) this.initialLoad.noteFailedAttempt();\n return this.scheduleReconnect();\n }\n // A grant minted for an earlier lifecycle must never open a socket in this one.\n if (lifecycle !== this.lifecycle || this.closedByUs) return;\n const url = `${this.config.endpoint.replace(/\\/$/, '')}/inbox`;\n // Every callback is fenced to THIS socket: once it has been replaced or torn down, its\n // late open, frames, and close are ignored.\n let socket: RealtimeSocket | null = null;\n const isCurrent = () => socket !== null && this.socket === socket;\n socket = this.config.socketFactory({\n url,\n grantToken,\n handlers: {\n onOpen: () => {\n if (isCurrent()) this.onOpen();\n },\n onMessage: (data) => {\n if (isCurrent()) this.onMessage(data);\n },\n onClose: (code, reason) => {\n if (isCurrent()) this.onClose(code, reason);\n },\n onError: () => undefined,\n },\n });\n this.socket = socket;\n }\n\n private onOpen(): void {\n this.controller.onOpen();\n this.reauthAttempted = false;\n this.setState({ status: 'open' });\n this.diag?.(DIAG.INBOX_SOCKET_OPEN, {\n attempt: this.connectAttempt,\n cause: this.reconnectCause,\n registryCount: this.state.registry.length,\n hasUnread: this.state.hasUnread,\n });\n // The DO sends a snapshot on accept; a `resume` re-requests it after a reconnect gap.\n const sent = this.sendFrame(CLIENT_FRAME.RESUME, {});\n // The inbox resume is CURSORLESS by contract (the DO always answers with a full\n // authoritative snapshot) — there is no `afterSeq` half to record here.\n this.diag?.(DIAG.INBOX_RESUME_REQUEST, { attempt: this.connectAttempt, cursorless: true, sent });\n }\n\n private onClose(code: number, _reason: string): void {\n this.socket = null;\n this.lastCloseCode = code;\n // A mark-read sent on this socket can no longer be answered.\n this.settlePendingMarkReads({ ok: false, code: 'connection-lost' });\n if (this.closedByUs) {\n this.diag?.(DIAG.INBOX_SOCKET_CLOSE, { code, closedByUs: true, outcome: 'closed' });\n this.setState({ status: 'closed' });\n return;\n }\n if (code === CHAT_CLOSE_CODES.AUTH_EXPIRED && !this.reauthAttempted) {\n this.reauthAttempted = true;\n this.reconnectCause = 'auth-expired';\n this.diag?.(DIAG.INBOX_SOCKET_CLOSE, { code, closedByUs: false, outcome: 're-grant' });\n this.setState({ status: 'reconnecting' });\n void this.openSocket();\n return;\n }\n if (code === CHAT_CLOSE_CODES.REVOKED) {\n this.closedByUs = true;\n this.controller.close();\n this.diag?.(DIAG.INBOX_SOCKET_CLOSE, { code, closedByUs: false, outcome: 'revoked' });\n this.setState({ status: 'closed', lastErrorCode: TERMINAL_ERROR_CODE.REVOKED });\n this.reportInitialLoadFailed();\n return;\n }\n this.reconnectCause = 'transient-close';\n if (!this.state.hasLoadedInitialData) this.initialLoad.noteFailedAttempt();\n this.diag?.(DIAG.INBOX_SOCKET_CLOSE, { code, closedByUs: false, outcome: 'reconnect' });\n this.scheduleReconnect();\n }\n\n /**\n * Terminal access denial surfaced by the inbox grant provider\n * (`ChatAccessDeniedError`). Same terminal posture as the 4403 REVOKED close: mark\n * closed-by-us, close the reconnect controller, and surface the stable\n * `access-denied` code. The inbox client tracks NO optimistic/pending sends\n * (mark-read is fire-and-forget with no local pending state), so — unlike\n * ChannelClient — there is nothing to fail here; only the lifecycle stops.\n */\n private denyAccessTerminally(): void {\n this.closedByUs = true;\n this.controller.close();\n this.initialLoad.dispose();\n this.setState({ status: 'closed', lastErrorCode: TERMINAL_ERROR_CODE.ACCESS_DENIED });\n }\n\n private scheduleReconnect(): void {\n const delay = this.controller.onClose();\n this.diag?.(DIAG.INBOX_RECONNECT_SCHEDULED, {\n delayMs: delay,\n cause: this.reconnectCause,\n attempt: this.connectAttempt,\n });\n if (delay == null) {\n this.setState({ status: 'closed' });\n this.reportInitialLoadFailed();\n return;\n }\n this.setState({ status: 'reconnecting' });\n const lifecycle = this.lifecycle;\n this.reconnectTimer = this.timers.setTimeout(() => {\n this.reconnectTimer = null;\n if (this.closedByUs || lifecycle !== this.lifecycle) return;\n void this.openSocket();\n }, delay);\n }\n\n private onMessage(data: string): void {\n const frame = parseFrame(data);\n if (!frame || !frame.payload) {\n this.diag?.(DIAG.INBOX_FRAME_DROPPED, { kind: 'unparseable', reason: 'bad-envelope' });\n return;\n }\n if (frame.type === SERVER_KINDS.MARK_READ_RESULT) return this.applyMarkReadResult(frame.payload);\n // The inbox DO pushes a full `snapshot`; a future lightweight `unread` push\n // carries either a full snapshot or a `{ hasUnread }` dock-dot patch. Route both\n // instead of silently dropping the `unread` type (C-M2).\n if (frame.type !== 'snapshot' && frame.type !== 'unread') {\n this.diag?.(DIAG.INBOX_FRAME_DROPPED, { kind: safeDiagnosticLabel(frame.type), reason: 'unknown-type' });\n return;\n }\n const payload = frame.payload as unknown as WireInboxSnapshot | { hasUnread: boolean };\n if (isInboxSnapshot(payload as WireInboxSnapshot)) {\n this.applySnapshot(payload as WireInboxSnapshot, frame.type);\n } else if (frame.type === 'unread' && typeof (payload as { hasUnread?: unknown }).hasUnread === 'boolean') {\n const hasUnread = Boolean((payload as { hasUnread: boolean }).hasUnread);\n const before = this.state.hasUnread;\n this.setState({ hasUnread });\n if (before !== hasUnread) {\n this.diag?.(DIAG.INBOX_UNREAD_UPDATED, {\n source: 'unread-patch',\n hasUnreadBefore: before,\n hasUnreadAfter: hasUnread,\n unreadCountBefore: this.state.unreadChannelRefs.length,\n unreadCountAfter: this.state.unreadChannelRefs.length,\n unreadCountDelta: 0,\n });\n }\n } else {\n // A stray CHANNEL snapshot ({ lastMessageSeq, readSeq }) on the inbox socket —\n // deliberately inert, but never silently invisible under diagnostics.\n this.diag?.(DIAG.INBOX_FRAME_DROPPED, {\n kind: safeDiagnosticLabel(frame.type),\n reason: 'not-an-inbox-payload',\n });\n }\n }\n\n private applySnapshot(snap: WireInboxSnapshot, source: string): void {\n // Keep every non-tombstoned entry — including ARCHIVED rows — so the inbox view can\n // render both the active list and the Archived toggle. `archived` is a distinct\n // dimension from `tombstoned`; archived rows are still `state: 'active'`.\n const registry = snap.registry.filter((e) => e.state === 'active');\n // The DO's `hasUnread` is the authoritative dock dot. Per-row dots are derived from\n // the same projection but exclude ARCHIVED rows (archive = done — an archived row\n // never shows a dot). The DO clears unread on archive, so this is belt-and-braces.\n const unreadChannelRefs = deriveUnreadRefs(snap);\n const hasUnread = Boolean(snap.hasUnread);\n const before = this.state;\n if (!before.hasLoadedInitialData) this.initialLoad.loaded();\n this.setState({ registry, hasUnread, unreadChannelRefs, hasLoadedInitialData: true, initialLoadFailed: false });\n if (!this.diag) return;\n // SIZES ONLY — a channelRef names one specific conversation and never enters a\n // diagnostic line.\n this.diag(DIAG.INBOX_SNAPSHOT_APPLIED, {\n source: safeDiagnosticLabel(source),\n received: snap.registry.length,\n // `received - active` is the tombstoned count the client filtered out.\n active: registry.length,\n archived: registry.filter((e) => e.archived === true).length,\n hasUnread,\n unreadCount: unreadChannelRefs.length,\n registryDelta: registry.length - before.registry.length,\n });\n const unreadChanged =\n before.hasUnread !== hasUnread || before.unreadChannelRefs.length !== unreadChannelRefs.length;\n if (unreadChanged) {\n this.diag(DIAG.INBOX_UNREAD_UPDATED, {\n source: safeDiagnosticLabel(source),\n hasUnreadBefore: before.hasUnread,\n hasUnreadAfter: hasUnread,\n unreadCountBefore: before.unreadChannelRefs.length,\n unreadCountAfter: unreadChannelRefs.length,\n unreadCountDelta: unreadChannelRefs.length - before.unreadChannelRefs.length,\n });\n }\n }\n\n private sendFrame(type: string, payload: Record<string, unknown>): boolean {\n if (!this.socket || !this.socket.isOpen) return false;\n this.socket.send(buildFrame(type, payload));\n return true;\n }\n\n /** True if a specific channel/invite currently carries an unread dot. */\n channelHasUnread(channelRef: string): boolean {\n return this.state.unreadChannelRefs.includes(channelRef);\n }\n\n /**\n * Clear a channel/invite's unread WITHOUT opening it (the inbox-view mark-read\n * controls). Sends `mark-read` with a fresh `requestId`; the inbox runtime advances the\n * member's read cursor, pushes a fresh authoritative snapshot (which is what removes\n * the dot — there is NO optimistic local clear), and answers with a\n * `mark-read-result` naming the same request. The promise settles on that answer —\n * never on a timer — or with `not-sent` when no socket is open, or `connection-lost`\n * when the socket closes first.\n */\n markRead(channelRef: string): Promise<ChatMarkReadOutcome> {\n const requestId = newCorrelationId();\n const sent = this.sendFrame(CLIENT_FRAME.MARK_READ, { channelRef, requestId });\n // The ref itself is never logged — only that a mark-read was written and what the\n // unread projection looked like at that moment (the DO's snapshot is what clears it).\n this.diag?.(DIAG.INBOX_MARK_READ, { sent, unreadCount: this.state.unreadChannelRefs.length });\n if (!sent) return Promise.resolve({ ok: false, code: 'not-sent' });\n return new Promise((resolve) => this.pendingMarkReads.set(requestId, resolve));\n }\n\n /** Settle the mark-read the result names; a result naming no pending request is ignored. */\n private applyMarkReadResult(payload: Record<string, unknown> | undefined): void {\n const parsed = ChatMarkReadResultPayloadSchema.safeParse(payload);\n if (!parsed.success) {\n this.diag?.(DIAG.INBOX_FRAME_DROPPED, { kind: SERVER_KINDS.MARK_READ_RESULT, reason: 'malformed-payload' });\n return;\n }\n const resolve = this.pendingMarkReads.get(parsed.data.requestId);\n if (!resolve) return;\n this.pendingMarkReads.delete(parsed.data.requestId);\n resolve(parsed.data.ok ? { ok: true } : { ok: false, code: parsed.data.code });\n }\n\n private settlePendingMarkReads(outcome: ChatMarkReadOutcome): void {\n const pending = [...this.pendingMarkReads.values()];\n this.pendingMarkReads.clear();\n for (const resolve of pending) resolve(outcome);\n }\n\n /** Permanently close (auth-user switch / unmount). Idempotent. */\n close(): void {\n this.closedByUs = true;\n this.lifecycle += 1;\n this.controller.close();\n this.initialLoad.dispose();\n if (this.reconnectTimer != null) {\n this.timers.clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n if (this.socket) {\n // Detach first: the socket's own late close is not this lifecycle's event.\n const socket = this.socket;\n this.socket = null;\n socket.close(1000, 'client teardown');\n }\n this.settlePendingMarkReads({ ok: false, code: 'connection-lost' });\n this.setState({ status: 'closed' });\n }\n}\n\n/**\n * Derive the per-channel unread set from a snapshot. The inbox DO's snapshot\n * carries a per-entry `unread` boolean on every active registry entry alongside\n * the global `hasUnread` roll-up that drives the dock dot. An entry without the\n * field (a legacy/pre-per-entry row) simply carries no per-row dot — the dock dot\n * still lights off `hasUnread`.\n *\n * ARCHIVED rows are excluded from the unread roll-up (archive = done — the DO clears\n * unread on archive; the client also never counts them).\n */\nfunction deriveUnreadRefs(snap: WireInboxSnapshot): string[] {\n const refs: string[] = [];\n for (const e of snap.registry) {\n if (e.state !== 'active') continue;\n if (e.archived === true) continue;\n if (e.unread === true) refs.push(e.channelRef);\n }\n return refs;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"inbox-client.js","sourceRoot":"","sources":["../../src/realtime/inbox-client.ts"],"names":[],"mappings":"AAAA,gFAAgF;AAChF,8EAA8E;AAC9E,gFAAgF;AAChF,EAAE;AACF,iFAAiF;AACjF,2EAA2E;AAC3E,mFAAmF;AACnF,gFAAgF;AAChF,wDAAwD;AAExD,OAAO,EACL,yBAAyB,GAE1B,MAAM,gCAAgC,CAAC;AACxC,OAAO,EACL,+BAA+B,EAC/B,YAAY,EAEZ,YAAY,EACZ,gBAAgB,GACjB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EACL,UAAU,EACV,UAAU,EACV,eAAe,GAGhB,MAAM,WAAW,CAAC;AAGnB,OAAO,EACL,aAAa,EACb,uBAAuB,EACvB,mBAAmB,EACnB,gBAAgB,EAChB,mBAAmB,GACpB,MAAM,aAAa,CAAC;AACrB,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,EACL,wBAAwB,EACxB,mBAAmB,EACnB,6BAA6B,IAAI,IAAI,GAGtC,MAAM,kBAAkB,CAAC;AAmE1B,MAAM,OAAO,GAAqB;IAChC,MAAM,EAAE,MAAM;IACd,QAAQ,EAAE,EAAE;IACZ,SAAS,EAAE,KAAK;IAChB,iBAAiB,EAAE,EAAE;IACrB,aAAa,EAAE,IAAI;IACnB,oBAAoB,EAAE,KAAK;IAC3B,iBAAiB,EAAE,KAAK;CACzB,CAAC;AAEF,MAAM,OAAO,WAAW;IA2BO;IA1BZ,MAAM,CAAkB;IACxB,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,SAAS;QACnC,IAAI,CAAC,CAAC,QAAQ,KAAK,IAAI;YAAE,SAAS;QAClC,IAAI,CAAC,CAAC,MAAM,KAAK,IAAI;YAAE,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC;IACjD,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["// The Inbox realtime client: a SEPARATE WebSocket (scope `inbox`) to the user's\n// inbox DO. It maintains the channel/invite registry + unread projection that\n// drives the inbox view — DOTS ONLY, no counts (Contract C / \"Unread + inbox\").\n//\n// The inbox DO pushes a full `snapshot` ({ registry, hasUnread }) on connect, on\n// `resume`, and on every live delta (a projection apply). This client just\n// mirrors the latest snapshot into an observable store + a per-channel unread set.\n// Same connection lifecycle as the channel client (subprotocol auth, reconnect,\n// 4401 re-grant once, 4403 stop, auth-switch teardown).\n\nimport {\n createReconnectController,\n type ReconnectController,\n} from '@ttt-productions/realtime-core';\nimport {\n ChatMarkReadResultPayloadSchema,\n SERVER_KINDS,\n type ChatMarkReadFailureCode,\n CLIENT_KINDS,\n CHAT_CLOSE_CODES,\n} from '@ttt-productions/chat-schemas';\nimport {\n buildFrame,\n parseFrame,\n isInboxSnapshot,\n type WireInboxSnapshot,\n type WireRegistryEntry,\n} from './wire.js';\nimport type { RealtimeSocket, SocketFactory } from './socket.js';\nimport type { GrantProvider, TransportTimers, RealtimeStatus } from './shared.js';\nimport {\n defaultTimers,\n isChatAccessDeniedError,\n isTerminalErrorCode,\n newCorrelationId,\n TERMINAL_ERROR_CODE,\n} from './shared.js';\nimport { InitialLoadBudget } from './initial-load-budget.js';\nimport {\n createDiagnosticsEmitter,\n safeDiagnosticLabel,\n CHAT_CLIENT_DIAGNOSTIC_EVENTS as DIAG,\n type ChatClientDiagnosticsEmitter,\n type ChatClientDiagnosticsOption,\n} from './diagnostics.js';\n\nexport interface InboxClientState {\n status: RealtimeStatus;\n /** Active (non-tombstoned) channel/invite registry entries — inbox-view visibility. */\n registry: WireRegistryEntry[];\n /** True if ANY active channel/invite has unread (drives the dock dot). */\n hasUnread: boolean;\n /** The set of channelRefs that currently carry an unread dot (per-row dots). */\n unreadChannelRefs: string[];\n /**\n * The last TERMINAL error code (mirrors `ChannelClientState.lastErrorCode`):\n * `'access-denied'` when the inbox grant provider throws `ChatAccessDeniedError`\n * (a genuine, terminal policy \"no\" — e.g. a banned/suspended account), and\n * `'revoked'` on a 4403 REVOKED close. Null while healthy and across transient\n * reconnects. The app subscribes to inbox state directly (there is no inbox React\n * hook in this package), so this stable code is the surface — it invents no new UI.\n */\n lastErrorCode: string | null;\n /**\n * True once the first authoritative snapshot has been applied — the registry and dots\n * are then the inbox runtime's answer, so an empty registry means \"nothing here\"\n * rather than \"not loaded yet\". Once true it stays true.\n */\n hasLoadedInitialData: boolean;\n /**\n * True once the first open has failed for long enough to say so — the same rule as\n * `ChannelClientState.initialLoadFailed`. Cleared by the first snapshot or `retryNow()`.\n */\n initialLoadFailed: boolean;\n}\n\n/**\n * How one `markRead` ended: `ok` — the inbox runtime advanced the read cursor (its\n * fresh snapshot clears the dot); otherwise `code` says why not — the runtime's own\n * reason, `not-sent` (no open socket, nothing was sent), or `connection-lost` (the\n * socket closed before the answer arrived, so the outcome is unknown and the dot stays).\n */\nexport type ChatMarkReadOutcome =\n { ok: true } | { ok: false; code: ChatMarkReadFailureCode | 'not-sent' | 'connection-lost' };\n\nexport interface InboxClientConfig {\n endpoint: string;\n /** The authenticated uid (the inbox owner; the DO serves no one else's data). */\n currentUserId: string;\n /** Mints/refreshes an INBOX-scope grant (scope `{ kind:'inbox', uid }`). */\n grantProvider: GrantProvider;\n socketFactory: SocketFactory;\n timers?: TransportTimers;\n reconnect?: {\n baseDelayMs?: number;\n maxDelayMs?: number;\n maxAttempts?: number | null;\n random?: () => number;\n };\n /**\n * OPT-IN structured client diagnostics — the SAME option type and emitter the\n * channel client uses (one owner, `./diagnostics.ts`). Default OFF: absent or\n * `false` changes nothing and costs one nullish check. `true` emits one\n * single-line `console.debug` entry per decision under the stable\n * `chat_client_inbox_*` names; a function routes them to the app's logger.\n * Inbox payloads are SIZES ONLY — registry/unread counts and deltas, never a\n * `channelRef` (which names one specific conversation).\n */\n diagnostics?: ChatClientDiagnosticsOption;\n}\n\nconst INITIAL: InboxClientState = {\n status: 'idle',\n registry: [],\n hasUnread: false,\n unreadChannelRefs: [],\n lastErrorCode: null,\n hasLoadedInitialData: false,\n initialLoadFailed: false,\n};\n\nexport class InboxClient {\n private readonly timers: TransportTimers;\n private readonly controller: ReconnectController;\n private socket: RealtimeSocket | null = null;\n private state: InboxClientState = INITIAL;\n private readonly listeners = new Set<(s: InboxClientState) => void>();\n private reauthAttempted = false;\n private reconnectTimer: ReturnType<TransportTimers['setTimeout']> | null = null;\n private closedByUs = false;\n /**\n * The current lifecycle's number, advanced by every `connect()` and `close()`; a grant,\n * timer, or socket callback of an older lifecycle is ignored (FRONTEND-108).\n */\n private lifecycle = 0;\n private readonly initialLoad: InitialLoadBudget;\n /** Mark-reads sent on the current socket, awaiting their correlated result, by requestId. */\n private readonly pendingMarkReads = new Map<string, (outcome: ChatMarkReadOutcome) => void>();\n /** Structured diagnostics emitter, or null when off (the default, zero-overhead). */\n private readonly diag: ChatClientDiagnosticsEmitter;\n /** Monotonic socket-open attempt counter (diagnostics correlation only). */\n private connectAttempt = 0;\n /** Why the CURRENT connect attempt is happening (diagnostics only). */\n private reconnectCause:\n 'initial' | 'auth-expired' | 'transient-close' | 'grant-error' | 'manual-retry' = 'initial';\n /** The last close code observed, carried into the next attempt's cause line. */\n private lastCloseCode: number | null = null;\n\n constructor(private readonly config: InboxClientConfig) {\n this.timers = config.timers ?? defaultTimers;\n this.controller = createReconnectController(config.reconnect ?? {});\n this.diag = createDiagnosticsEmitter(config.diagnostics);\n this.initialLoad = new InitialLoadBudget(this.timers, () => this.reportInitialLoadFailed());\n }\n\n getState(): InboxClientState {\n return this.state;\n }\n\n subscribe(fn: (s: InboxClientState) => void): () => void {\n this.listeners.add(fn);\n return () => this.listeners.delete(fn);\n }\n\n private setState(patch: Partial<InboxClientState>): void {\n this.state = { ...this.state, ...patch };\n for (const fn of this.listeners) fn(this.state);\n }\n\n async connect(): Promise<void> {\n return this.startLifecycle(true);\n }\n\n /**\n * Retry now (the first-open failure's Retry) — the same rule as `ChannelClient.retryNow`:\n * a reconnect waiting out its backoff opens at once; a stopped lifecycle starts again; an\n * attempt in flight is left to finish; the first-open failure clears either way.\n */\n retryNow(): void {\n if (!this.state.hasLoadedInitialData) this.initialLoad.manualRetry();\n if (this.state.status === 'closed') {\n void this.startLifecycle(false);\n return;\n }\n if (this.reconnectTimer == null) {\n if (this.state.initialLoadFailed) this.setState({ initialLoadFailed: false });\n return;\n }\n this.timers.clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n this.controller.reset();\n this.controller.start();\n this.reconnectCause = 'manual-retry';\n this.setState({ status: 'reconnecting', initialLoadFailed: false });\n void this.openSocket();\n }\n\n private async startLifecycle(freshBudget: boolean): Promise<void> {\n // Idempotency guard (mirrors ChannelClient): connect() only starts a lifecycle\n // from a fresh (idle) or fully torn-down (closed) state. A second connect()\n // while one is already connecting / open / reconnecting is a no-op, so a\n // double-mounted dock cannot open a SECOND inbox socket against the per-uid\n // cap. The reconnect path uses openSocket() / scheduleReconnect() directly\n // (never connect()), so this never blocks a legitimate reconnect.\n if (this.state.status !== 'idle' && this.state.status !== 'closed') return;\n // REVIVE the controller. `controller.close()` is PERMANENT: while it is in\n // state `closed`, `start()` and `onOpen()` no-op and every later `onClose()`\n // returns null — so without this reset a close() → connect() client opens a\n // socket and works normally until its FIRST transient close, then parks\n // terminally in `closed` with reconnect disabled and no surfaced error code.\n this.controller.reset();\n // A terminal verdict (4403 REVOKED / ChatAccessDeniedError) is terminal WITHIN\n // its lifecycle; an explicit connect() is a fresh attempt the authority may\n // legitimately re-deny, so the previous lifecycle's code must not persist.\n // The registry/unread projection is deliberately KEPT — the DO's next snapshot\n // is authoritative, and blanking the dock on every restart is pure UI churn.\n if (isTerminalErrorCode(this.state.lastErrorCode)) this.setState({ lastErrorCode: null });\n this.closedByUs = false;\n this.lifecycle += 1;\n this.reconnectCause = 'initial';\n if (!this.state.hasLoadedInitialData) this.initialLoad.begin(freshBudget);\n this.controller.start();\n this.setState({ status: 'connecting', initialLoadFailed: false });\n await this.openSocket();\n }\n\n private reportInitialLoadFailed(): void {\n if (this.state.hasLoadedInitialData || this.state.initialLoadFailed) return;\n this.setState({ initialLoadFailed: true });\n }\n\n private async openSocket(): Promise<void> {\n const lifecycle = this.lifecycle;\n this.connectAttempt += 1;\n this.diag?.(DIAG.INBOX_CONNECT_ATTEMPT, {\n attempt: this.connectAttempt,\n cause: this.reconnectCause,\n closeCode: this.lastCloseCode,\n registryCount: this.state.registry.length,\n });\n let grantToken: string;\n try {\n grantToken = await this.config.grantProvider();\n } catch (err) {\n if (lifecycle !== this.lifecycle) return;\n // A TERMINAL access denial (the app translated an authoritative policy \"no\"\n // — e.g. Firebase `permission-denied` for a banned/suspended account — into the\n // package-owned ChatAccessDeniedError) must NOT reconnect: the next mint would\n // just re-deny, reconnect-looping forever and warning every cycle. Every other\n // mint failure (network/transient) stays retryable and backs off as before.\n const terminal = isChatAccessDeniedError(err);\n this.diag?.(DIAG.INBOX_GRANT_FAILED, { attempt: this.connectAttempt, terminal });\n if (terminal) return this.denyAccessTerminally();\n this.reconnectCause = 'grant-error';\n if (!this.state.hasLoadedInitialData) this.initialLoad.noteFailedAttempt();\n return this.scheduleReconnect();\n }\n // A grant minted for an earlier lifecycle must never open a socket in this one.\n if (lifecycle !== this.lifecycle || this.closedByUs) return;\n const url = `${this.config.endpoint.replace(/\\/$/, '')}/inbox`;\n // Every callback is fenced to THIS socket: once it has been replaced or torn down, its\n // late open, frames, and close are ignored.\n let socket: RealtimeSocket | null = null;\n const isCurrent = () => socket !== null && this.socket === socket;\n socket = this.config.socketFactory({\n url,\n grantToken,\n handlers: {\n onOpen: () => {\n if (isCurrent()) this.onOpen();\n },\n onMessage: (data) => {\n if (isCurrent()) this.onMessage(data);\n },\n onClose: (code, reason) => {\n if (isCurrent()) this.onClose(code, reason);\n },\n onError: () => undefined,\n },\n });\n this.socket = socket;\n }\n\n private onOpen(): void {\n this.controller.onOpen();\n this.reauthAttempted = false;\n this.setState({ status: 'open' });\n this.diag?.(DIAG.INBOX_SOCKET_OPEN, {\n attempt: this.connectAttempt,\n cause: this.reconnectCause,\n registryCount: this.state.registry.length,\n hasUnread: this.state.hasUnread,\n });\n // The DO sends a snapshot on accept; a `resume` re-requests it after a reconnect gap.\n const sent = this.sendFrame(CLIENT_KINDS.RESUME, {});\n // The inbox resume is CURSORLESS by contract (the DO always answers with a full\n // authoritative snapshot) — there is no `afterSeq` half to record here.\n this.diag?.(DIAG.INBOX_RESUME_REQUEST, {\n attempt: this.connectAttempt,\n cursorless: true,\n sent,\n });\n }\n\n private onClose(code: number, _reason: string): void {\n this.socket = null;\n this.lastCloseCode = code;\n // A mark-read sent on this socket can no longer be answered.\n this.settlePendingMarkReads({ ok: false, code: 'connection-lost' });\n if (this.closedByUs) {\n this.diag?.(DIAG.INBOX_SOCKET_CLOSE, { code, closedByUs: true, outcome: 'closed' });\n this.setState({ status: 'closed' });\n return;\n }\n if (code === CHAT_CLOSE_CODES.AUTH_EXPIRED && !this.reauthAttempted) {\n this.reauthAttempted = true;\n this.reconnectCause = 'auth-expired';\n this.diag?.(DIAG.INBOX_SOCKET_CLOSE, { code, closedByUs: false, outcome: 're-grant' });\n this.setState({ status: 'reconnecting' });\n void this.openSocket();\n return;\n }\n if (code === CHAT_CLOSE_CODES.REVOKED) {\n this.closedByUs = true;\n this.controller.close();\n this.diag?.(DIAG.INBOX_SOCKET_CLOSE, { code, closedByUs: false, outcome: 'revoked' });\n this.setState({ status: 'closed', lastErrorCode: TERMINAL_ERROR_CODE.REVOKED });\n this.reportInitialLoadFailed();\n return;\n }\n this.reconnectCause = 'transient-close';\n if (!this.state.hasLoadedInitialData) this.initialLoad.noteFailedAttempt();\n this.diag?.(DIAG.INBOX_SOCKET_CLOSE, { code, closedByUs: false, outcome: 'reconnect' });\n this.scheduleReconnect();\n }\n\n /**\n * Terminal access denial surfaced by the inbox grant provider\n * (`ChatAccessDeniedError`). Same terminal posture as the 4403 REVOKED close: mark\n * closed-by-us, close the reconnect controller, and surface the stable\n * `access-denied` code. The inbox client tracks NO optimistic/pending sends\n * (mark-read is fire-and-forget with no local pending state), so — unlike\n * ChannelClient — there is nothing to fail here; only the lifecycle stops.\n */\n private denyAccessTerminally(): void {\n this.closedByUs = true;\n this.controller.close();\n this.initialLoad.dispose();\n this.setState({ status: 'closed', lastErrorCode: TERMINAL_ERROR_CODE.ACCESS_DENIED });\n }\n\n private scheduleReconnect(): void {\n const delay = this.controller.onClose();\n this.diag?.(DIAG.INBOX_RECONNECT_SCHEDULED, {\n delayMs: delay,\n cause: this.reconnectCause,\n attempt: this.connectAttempt,\n });\n if (delay == null) {\n this.setState({ status: 'closed' });\n this.reportInitialLoadFailed();\n return;\n }\n this.setState({ status: 'reconnecting' });\n const lifecycle = this.lifecycle;\n this.reconnectTimer = this.timers.setTimeout(() => {\n this.reconnectTimer = null;\n if (this.closedByUs || lifecycle !== this.lifecycle) return;\n void this.openSocket();\n }, delay);\n }\n\n private onMessage(data: string): void {\n const frame = parseFrame(data);\n if (!frame || !frame.payload) {\n this.diag?.(DIAG.INBOX_FRAME_DROPPED, { kind: 'unparseable', reason: 'bad-envelope' });\n return;\n }\n if (frame.type === SERVER_KINDS.MARK_READ_RESULT)\n return this.applyMarkReadResult(frame.payload);\n // The inbox DO pushes a full `snapshot`; a future lightweight `unread` push\n // carries either a full snapshot or a `{ hasUnread }` dock-dot patch. Route both\n // instead of silently dropping the `unread` type (C-M2).\n if (frame.type !== 'snapshot' && frame.type !== 'unread') {\n this.diag?.(DIAG.INBOX_FRAME_DROPPED, {\n kind: safeDiagnosticLabel(frame.type),\n reason: 'unknown-type',\n });\n return;\n }\n const payload = frame.payload as unknown as WireInboxSnapshot | { hasUnread: boolean };\n if (isInboxSnapshot(payload as WireInboxSnapshot)) {\n this.applySnapshot(payload as WireInboxSnapshot, frame.type);\n } else if (\n frame.type === 'unread' &&\n typeof (payload as { hasUnread?: unknown }).hasUnread === 'boolean'\n ) {\n const hasUnread = Boolean((payload as { hasUnread: boolean }).hasUnread);\n const before = this.state.hasUnread;\n this.setState({ hasUnread });\n if (before !== hasUnread) {\n this.diag?.(DIAG.INBOX_UNREAD_UPDATED, {\n source: 'unread-patch',\n hasUnreadBefore: before,\n hasUnreadAfter: hasUnread,\n unreadCountBefore: this.state.unreadChannelRefs.length,\n unreadCountAfter: this.state.unreadChannelRefs.length,\n unreadCountDelta: 0,\n });\n }\n } else {\n // A stray CHANNEL snapshot ({ lastMessageSeq, readSeq }) on the inbox socket —\n // deliberately inert, but never silently invisible under diagnostics.\n this.diag?.(DIAG.INBOX_FRAME_DROPPED, {\n kind: safeDiagnosticLabel(frame.type),\n reason: 'not-an-inbox-payload',\n });\n }\n }\n\n private applySnapshot(snap: WireInboxSnapshot, source: string): void {\n // Keep every non-tombstoned entry — including ARCHIVED rows — so the inbox view can\n // render both the active list and the Archived toggle. `archived` is a distinct\n // dimension from `tombstoned`; archived rows are still `state: 'active'`.\n const registry = snap.registry.filter((e) => e.state === 'active');\n // The DO's `hasUnread` is the authoritative dock dot. Per-row dots are derived from\n // the same projection but exclude ARCHIVED rows (archive = done — an archived row\n // never shows a dot). The DO clears unread on archive, so this is belt-and-braces.\n const unreadChannelRefs = deriveUnreadRefs(snap);\n const hasUnread = Boolean(snap.hasUnread);\n const before = this.state;\n if (!before.hasLoadedInitialData) this.initialLoad.loaded();\n this.setState({\n registry,\n hasUnread,\n unreadChannelRefs,\n hasLoadedInitialData: true,\n initialLoadFailed: false,\n });\n if (!this.diag) return;\n // SIZES ONLY — a channelRef names one specific conversation and never enters a\n // diagnostic line.\n this.diag(DIAG.INBOX_SNAPSHOT_APPLIED, {\n source: safeDiagnosticLabel(source),\n received: snap.registry.length,\n // `received - active` is the tombstoned count the client filtered out.\n active: registry.length,\n archived: registry.filter((e) => e.archived === true).length,\n hasUnread,\n unreadCount: unreadChannelRefs.length,\n registryDelta: registry.length - before.registry.length,\n });\n const unreadChanged =\n before.hasUnread !== hasUnread ||\n before.unreadChannelRefs.length !== unreadChannelRefs.length;\n if (unreadChanged) {\n this.diag(DIAG.INBOX_UNREAD_UPDATED, {\n source: safeDiagnosticLabel(source),\n hasUnreadBefore: before.hasUnread,\n hasUnreadAfter: hasUnread,\n unreadCountBefore: before.unreadChannelRefs.length,\n unreadCountAfter: unreadChannelRefs.length,\n unreadCountDelta: unreadChannelRefs.length - before.unreadChannelRefs.length,\n });\n }\n }\n\n private sendFrame(type: string, payload: Record<string, unknown>): boolean {\n if (!this.socket || !this.socket.isOpen) return false;\n this.socket.send(buildFrame(type, payload));\n return true;\n }\n\n /** True if a specific channel/invite currently carries an unread dot. */\n channelHasUnread(channelRef: string): boolean {\n return this.state.unreadChannelRefs.includes(channelRef);\n }\n\n /**\n * Clear a channel/invite's unread WITHOUT opening it (the inbox-view mark-read\n * controls). Sends `mark-read` with a fresh `requestId`; the inbox runtime advances the\n * member's read cursor, pushes a fresh authoritative snapshot (which is what removes\n * the dot — there is NO optimistic local clear), and answers with a\n * `mark-read-result` naming the same request. The promise settles on that answer —\n * never on a timer — or with `not-sent` when no socket is open, or `connection-lost`\n * when the socket closes first.\n */\n markRead(channelRef: string): Promise<ChatMarkReadOutcome> {\n const requestId = newCorrelationId();\n const sent = this.sendFrame(CLIENT_KINDS.MARK_READ, { channelRef, requestId });\n // The ref itself is never logged — only that a mark-read was written and what the\n // unread projection looked like at that moment (the DO's snapshot is what clears it).\n this.diag?.(DIAG.INBOX_MARK_READ, { sent, unreadCount: this.state.unreadChannelRefs.length });\n if (!sent) return Promise.resolve({ ok: false, code: 'not-sent' });\n return new Promise((resolve) => this.pendingMarkReads.set(requestId, resolve));\n }\n\n /** Settle the mark-read the result names; a result naming no pending request is ignored. */\n private applyMarkReadResult(payload: Record<string, unknown> | undefined): void {\n const parsed = ChatMarkReadResultPayloadSchema.safeParse(payload);\n if (!parsed.success) {\n this.diag?.(DIAG.INBOX_FRAME_DROPPED, {\n kind: SERVER_KINDS.MARK_READ_RESULT,\n reason: 'malformed-payload',\n });\n return;\n }\n const resolve = this.pendingMarkReads.get(parsed.data.requestId);\n if (!resolve) return;\n this.pendingMarkReads.delete(parsed.data.requestId);\n resolve(parsed.data.ok ? { ok: true } : { ok: false, code: parsed.data.code });\n }\n\n private settlePendingMarkReads(outcome: ChatMarkReadOutcome): void {\n const pending = [...this.pendingMarkReads.values()];\n this.pendingMarkReads.clear();\n for (const resolve of pending) resolve(outcome);\n }\n\n /** Permanently close (auth-user switch / unmount). Idempotent. */\n close(): void {\n this.closedByUs = true;\n this.lifecycle += 1;\n this.controller.close();\n this.initialLoad.dispose();\n if (this.reconnectTimer != null) {\n this.timers.clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n if (this.socket) {\n // Detach first: the socket's own late close is not this lifecycle's event.\n const socket = this.socket;\n this.socket = null;\n socket.close(1000, 'client teardown');\n }\n this.settlePendingMarkReads({ ok: false, code: 'connection-lost' });\n this.setState({ status: 'closed' });\n }\n}\n\n/**\n * Derive the per-channel unread set from a snapshot. The inbox DO's snapshot\n * carries a per-entry `unread` boolean on every active registry entry alongside\n * the global `hasUnread` roll-up that drives the dock dot. An entry without the\n * field (a legacy/pre-per-entry row) simply carries no per-row dot — the dock dot\n * still lights off `hasUnread`.\n *\n * ARCHIVED rows are excluded from the unread roll-up (archive = done — the DO clears\n * unread on archive; the client also never counts them).\n */\nfunction deriveUnreadRefs(snap: WireInboxSnapshot): string[] {\n const refs: string[] = [];\n for (const e of snap.registry) {\n if (e.state !== 'active') continue;\n if (e.archived === true) continue;\n if (e.unread === true) refs.push(e.channelRef);\n }\n return refs;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"initial-load-budget.d.ts","sourceRoot":"","sources":["../../src/realtime/initial-load-budget.ts"],"names":[],"mappings":"AAMA,OAAO,EAAuC,KAAK,eAAe,EAAE,MAAM,aAAa,CAAC;AAExF,qBAAa,iBAAiB;IAM1B,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,0DAA0D;IAC1D,OAAO,CAAC,QAAQ,CAAC,WAAW;IAP9B,4FAA4F;IAC5F,OAAO,CAAC,SAAS,CAAuB;IACxC,OAAO,CAAC,KAAK,CAA0D;gBAGpD,MAAM,EAAE,eAAe;IACxC,0DAA0D;IACzC,WAAW,EAAE,MAAM,IAAI;IAG1C;;;OAGG;IACH,KAAK,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI;IAM3B,oGAAoG;IACpG,iBAAiB,IAAI,IAAI;
|
|
1
|
+
{"version":3,"file":"initial-load-budget.d.ts","sourceRoot":"","sources":["../../src/realtime/initial-load-budget.ts"],"names":[],"mappings":"AAMA,OAAO,EAAuC,KAAK,eAAe,EAAE,MAAM,aAAa,CAAC;AAExF,qBAAa,iBAAiB;IAM1B,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,0DAA0D;IAC1D,OAAO,CAAC,QAAQ,CAAC,WAAW;IAP9B,4FAA4F;IAC5F,OAAO,CAAC,SAAS,CAAuB;IACxC,OAAO,CAAC,KAAK,CAA0D;gBAGpD,MAAM,EAAE,eAAe;IACxC,0DAA0D;IACzC,WAAW,EAAE,MAAM,IAAI;IAG1C;;;OAGG;IACH,KAAK,CAAC,KAAK,EAAE,OAAO,GAAG,IAAI;IAM3B,oGAAoG;IACpG,iBAAiB,IAAI,IAAI;IAMzB;;;OAGG;IACH,WAAW,IAAI,IAAI;IAKnB,6EAA6E;IAC7E,MAAM,IAAI,IAAI;IAKd,oDAAoD;IACpD,OAAO,IAAI,IAAI;IAIf,OAAO,CAAC,GAAG;IAQX,OAAO,CAAC,UAAU;CAMnB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"initial-load-budget.js","sourceRoot":"","sources":["../../src/realtime/initial-load-budget.ts"],"names":[],"mappings":"AAAA,8FAA8F;AAC9F,mGAAmG;AACnG,iGAAiG;AACjG,gGAAgG;AAChG,oEAAoE;AAEpE,OAAO,EAAE,mCAAmC,EAAwB,MAAM,aAAa,CAAC;AAExF,MAAM,OAAO,iBAAiB;IAMT;IAEA;IAPnB,4FAA4F;IACpF,SAAS,GAAkB,IAAI,CAAC;IAChC,KAAK,GAAqD,IAAI,CAAC;IAEvE,YACmB,MAAuB;IACxC,0DAA0D;IACzC,WAAuB;QAFvB,WAAM,GAAN,MAAM,CAAiB;QAEvB,gBAAW,GAAX,WAAW,CAAY;IACvC,CAAC;IAEJ;;;OAGG;IACH,KAAK,CAAC,KAAc;QAClB,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,SAAS,IAAI,IAAI;YAAE,OAAO;QAC7C,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC;QACnC,IAAI,CAAC,GAAG,CAAC,mCAAmC,CAAC,CAAC;IAChD,CAAC;IAED,oGAAoG;IACpG,iBAAiB;QACf,IAAI,IAAI,CAAC,SAAS,IAAI,IAAI;YAAE,OAAO;QACnC,IAAI,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,SAAS,IAAI,mCAAmC;
|
|
1
|
+
{"version":3,"file":"initial-load-budget.js","sourceRoot":"","sources":["../../src/realtime/initial-load-budget.ts"],"names":[],"mappings":"AAAA,8FAA8F;AAC9F,mGAAmG;AACnG,iGAAiG;AACjG,gGAAgG;AAChG,oEAAoE;AAEpE,OAAO,EAAE,mCAAmC,EAAwB,MAAM,aAAa,CAAC;AAExF,MAAM,OAAO,iBAAiB;IAMT;IAEA;IAPnB,4FAA4F;IACpF,SAAS,GAAkB,IAAI,CAAC;IAChC,KAAK,GAAqD,IAAI,CAAC;IAEvE,YACmB,MAAuB;IACxC,0DAA0D;IACzC,WAAuB;QAFvB,WAAM,GAAN,MAAM,CAAiB;QAEvB,gBAAW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,IAAI,IAAI,EAAE,CAAC;YACvB,IAAI,CAAC,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YACrC,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QACpB,CAAC;IACH,CAAC;CACF","sourcesContent":["// The first-open failure budget both realtime clients share: a client that has not loaded its\n// first data CHAT_INITIAL_LOAD_FAILURE_BUDGET_MS after its first attempt started reports the first\n// open as failed — whether its attempts failed or one is still hanging (a grant mint stuck until\n// its timeout, a socket that opened but never sent a snapshot) — while it keeps retrying in the\n// background. One implementation for the channel and inbox sockets.\n\nimport { CHAT_INITIAL_LOAD_FAILURE_BUDGET_MS, type TransportTimers } from './shared.js';\n\nexport class InitialLoadBudget {\n /** When the first attempt of the current no-data run started; null once data has loaded. */\n private startedAt: number | null = null;\n private timer: ReturnType<TransportTimers['setTimeout']> | null = null;\n\n constructor(\n private readonly timers: TransportTimers,\n /** Called when the budget runs out with still no data. */\n private readonly onExhausted: () => void,\n ) {}\n\n /**\n * A lifecycle is starting without data. A fresh start opens a new budget; otherwise the budget\n * already running (or spent) is kept.\n */\n begin(fresh: boolean): void {\n if (!fresh && this.startedAt != null) return;\n this.startedAt = this.timers.now();\n this.arm(CHAT_INITIAL_LOAD_FAILURE_BUDGET_MS);\n }\n\n /** An attempt failed before any data loaded: once the budget is spent, that is reported at once. */\n noteFailedAttempt(): void {\n if (this.startedAt == null) return;\n if (this.timers.now() - this.startedAt >= CHAT_INITIAL_LOAD_FAILURE_BUDGET_MS)\n this.onExhausted();\n }\n\n /**\n * The user asked to retry. The spent budget stays spent — a retry that fails is reported at\n * once — and a retry that hangs is reported a full budget from now.\n */\n manualRetry(): void {\n if (this.startedAt == null) this.startedAt = this.timers.now();\n this.arm(CHAT_INITIAL_LOAD_FAILURE_BUDGET_MS);\n }\n\n /** The first data loaded — there is no first-open failure left to report. */\n loaded(): void {\n this.clearTimer();\n this.startedAt = null;\n }\n\n /** The lifecycle ended; nothing may fire for it. */\n dispose(): void {\n this.clearTimer();\n }\n\n private arm(ms: number): void {\n this.clearTimer();\n this.timer = this.timers.setTimeout(() => {\n this.timer = null;\n if (this.startedAt != null) this.onExhausted();\n }, ms);\n }\n\n private clearTimer(): void {\n if (this.timer != null) {\n this.timers.clearTimeout(this.timer);\n this.timer = null;\n }\n }\n}\n"]}
|
package/dist/realtime/map.d.ts
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
1
|
import type { ChatMessageV1 } from '@ttt-productions/chat-core';
|
|
2
|
-
import { MODERATION_REDACTED_TEXT } from '@ttt-productions/chat-schemas';
|
|
3
2
|
import type { RevisionKind, WireMessageRow } from './wire.js';
|
|
4
|
-
export { MODERATION_REDACTED_TEXT };
|
|
5
3
|
/** The effective moderation overlay for a message: the max-`messageRevision` kind. */
|
|
6
4
|
export interface ModerationOverlay {
|
|
7
5
|
kind: RevisionKind;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"map.d.ts","sourceRoot":"","sources":["../../src/realtime/map.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;
|
|
1
|
+
{"version":3,"file":"map.d.ts","sourceRoot":"","sources":["../../src/realtime/map.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAEhE,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAE9D,sFAAsF;AACtF,MAAM,WAAW,iBAAiB;IAChC,IAAI,EAAE,YAAY,CAAC;IACnB,eAAe,EAAE,MAAM,CAAC;CACzB;AAED;;;;;;;;;GASG;AACH,wBAAgB,sBAAsB,CACpC,OAAO,EAAE,aAAa,EACtB,OAAO,EAAE,iBAAiB,GAAG,IAAI,GAChC,aAAa,CAcf;AAED,4FAA4F;AAC5F,wBAAgB,cAAc,CAAC,GAAG,EAAE,cAAc,GAAG,iBAAiB,GAAG,IAAI,CAG5E;AAED,qFAAqF;AACrF,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAElD;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,GAAG,aAAa,CAgBrF;AAED,8FAA8F;AAC9F,wBAAgB,iBAAiB,CAAC,IAAI,EAAE;IACtC,eAAe,EAAE,MAAM,CAAC;IACxB,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,EAAE,MAAM,CAAC;CACnB,GAAG,aAAa,CAShB"}
|
package/dist/realtime/map.js
CHANGED
|
@@ -6,9 +6,6 @@
|
|
|
6
6
|
// display name — names resolve at render time through the ChatNameResolver
|
|
7
7
|
// context, identical to the Firestore path.
|
|
8
8
|
import { CHAT_SYSTEM_SENDER_ID, MODERATION_REDACTED_TEXT } from '@ttt-productions/chat-schemas';
|
|
9
|
-
// The redacted-text constant lives in the wire contract; re-export to keep this
|
|
10
|
-
// module's public surface stable.
|
|
11
|
-
export { MODERATION_REDACTED_TEXT };
|
|
12
9
|
/**
|
|
13
10
|
* Apply a moderation overlay to a mapped message so the ORIGINAL content never
|
|
14
11
|
* renders for a hidden/deleted message. Pure — returns a new message; the input
|
|
@@ -65,7 +62,9 @@ export function wireRowToMessage(row, threadId) {
|
|
|
65
62
|
senderId: row.senderUid,
|
|
66
63
|
text: row.text,
|
|
67
64
|
isSystemMessage: row.senderUid === CHAT_SYSTEM_SENDER_ID || undefined,
|
|
68
|
-
...(row.referencedUids && row.referencedUids.length > 0
|
|
65
|
+
...(row.referencedUids && row.referencedUids.length > 0
|
|
66
|
+
? { referencedUids: [...row.referencedUids] }
|
|
67
|
+
: {}),
|
|
69
68
|
meta: {
|
|
70
69
|
seq: row.seq,
|
|
71
70
|
epoch: row.epoch,
|
package/dist/realtime/map.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"map.js","sourceRoot":"","sources":["../../src/realtime/map.ts"],"names":[],"mappings":"AAAA,kFAAkF;AAClF,+EAA+E;AAC/E,kDAAkD;AAClD,EAAE;AACF,+EAA+E;AAC/E,2EAA2E;AAC3E,4CAA4C;AAG5C,OAAO,EAAE,qBAAqB,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;
|
|
1
|
+
{"version":3,"file":"map.js","sourceRoot":"","sources":["../../src/realtime/map.ts"],"names":[],"mappings":"AAAA,kFAAkF;AAClF,+EAA+E;AAC/E,kDAAkD;AAClD,EAAE;AACF,+EAA+E;AAC/E,2EAA2E;AAC3E,4CAA4C;AAG5C,OAAO,EAAE,qBAAqB,EAAE,wBAAwB,EAAE,MAAM,+BAA+B,CAAC;AAShG;;;;;;;;;GASG;AACH,MAAM,UAAU,sBAAsB,CACpC,OAAsB,EACtB,OAAiC;IAEjC,IAAI,CAAC,OAAO;QAAE,OAAO,OAAO,CAAC;IAC7B,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,KAAK,QAAQ,IAAI,OAAO,CAAC,IAAI,KAAK,UAAU,CAAC;IAC1E,OAAO;QACL,GAAG,OAAO;QACV,GAAG,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,wBAAwB,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;QACvD,IAAI,EAAE;YACJ,GAAG,OAAO,CAAC,IAAI;YACf,cAAc,EAAE,OAAO,CAAC,IAAI;YAC5B,eAAe,EAAE,OAAO,CAAC,eAAe;YACxC,8EAA8E;YAC9E,SAAS,EAAE,OAAO,CAAC,IAAI,KAAK,SAAS;SACtC;KACF,CAAC;AACJ,CAAC;AAED,4FAA4F;AAC5F,MAAM,UAAU,cAAc,CAAC,GAAmB;IAChD,IAAI,GAAG,CAAC,cAAc,IAAI,IAAI;QAAE,OAAO,IAAI,CAAC;IAC5C,OAAO,EAAE,IAAI,EAAE,GAAG,CAAC,cAAc,EAAE,eA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stays transport-agnostic — the MessageList renders the same shape whether\n// the bytes came from Firestore or the DO socket.\n//\n// Identity invariant: the DO stores uid references only (`senderUid`), never a\n// display name — names resolve at render time through the ChatNameResolver\n// context, identical to the Firestore path.\n\nimport type { ChatMessageV1 } from '@ttt-productions/chat-core';\nimport { CHAT_SYSTEM_SENDER_ID, MODERATION_REDACTED_TEXT } from '@ttt-productions/chat-schemas';\nimport type { RevisionKind, WireMessageRow } from './wire.js';\n\n/** The effective moderation overlay for a message: the max-`messageRevision` kind. */\nexport interface ModerationOverlay {\n kind: RevisionKind;\n messageRevision: number;\n}\n\n/**\n * Apply a moderation overlay to a mapped message so the ORIGINAL content never\n * renders for a hidden/deleted message. Pure — returns a new message; the input\n * is not mutated. The overlay state rides on `meta` (`meta` is opaque to\n * chat-core), so the renderer can branch on `meta.moderated` / `meta.moderationKind`.\n * - `delete` / `moderate` → blank/replace the text + mark moderated.\n * - `edit` → the row already carries the overlaid text (the DO rewrites `text`),\n * so only the marker is stamped.\n * - `restore` → original content (the DO row is the original); no redaction.\n */\nexport function applyModerationOverlay(\n message: ChatMessageV1,\n overlay: ModerationOverlay | null,\n): ChatMessageV1 {\n if (!overlay) return message;\n const redacted = overlay.kind === 'delete' || overlay.kind === 'moderate';\n return {\n ...message,\n ...(redacted ? { text: MODERATION_REDACTED_TEXT } : {}),\n meta: {\n ...message.meta,\n moderationKind: overlay.kind,\n messageRevision: overlay.messageRevision,\n // `restore` is the absence of active moderation — it reverts to the original.\n moderated: overlay.kind !== 'restore',\n },\n };\n}\n\n/** The overlay carried inline on a DO row (the getHistory/getDeltaSince merge), or null. */\nexport function overlayFromRow(row: WireMessageRow): ModerationOverlay | null {\n if (row.moderationKind == null) return null;\n return { kind: row.moderationKind, messageRevision: row.messageRevision ?? 0 };\n}\n\n/** The DO `seq` is the stable per-channel message id (monotonic, epoch-spanning). */\nexport function seqToMessageId(seq: number): string {\n return String(seq);\n}\n\n/**\n * Convert a DO message row to the UI message. `threadId` is the caller's logical\n * thread id (the UI's thread key); the DO row carries no threadId of its own.\n * - `messageId` = the server seq (string) — stable + dedup key.\n *\n * A DO row carries TEXT only. Files are not part of the message timeline — they\n * live in the conversation's Conversation Files list, published through the\n * canonical media pipeline and read from Firestore, never mapped from a chat row.\n * A legacy row's stored reply pointer is likewise NOT mapped: chat has no\n * reply-authoring affordance, so the UI has no reply renderer to feed\n * (DJ ruling 2026-07-29).\n */\nexport function wireRowToMessage(row: WireMessageRow, threadId: string): ChatMessageV1 {\n return {\n messageId: seqToMessageId(row.seq),\n threadId,\n createdAt: row.createdAt,\n senderId: row.senderUid,\n text: row.text,\n isSystemMessage: row.senderUid === CHAT_SYSTEM_SENDER_ID || undefined,\n ...(row.referencedUids && row.referencedUids.length > 0\n ? { referencedUids: [...row.referencedUids] }\n : {}),\n meta: {\n seq: row.seq,\n epoch: row.epoch,\n },\n };\n}\n\n/** The optimistic local echo a `send` produces before the server `ack` reconciles the seq. */\nexport function optimisticMessage(args: {\n clientMessageId: string;\n threadId: string;\n senderId: string;\n text: string;\n createdAt: number;\n}): ChatMessageV1 {\n return {\n messageId: `optimistic:${args.clientMessageId}`,\n threadId: args.threadId,\n createdAt: args.createdAt,\n senderId: args.senderId,\n text: args.text,\n meta: { clientMessageId: args.clientMessageId, optimistic: true },\n };\n}\n"]}
|
|
@@ -68,7 +68,6 @@ export declare function isTerminalErrorCode(code: string | null | undefined): co
|
|
|
68
68
|
* constant.
|
|
69
69
|
*/
|
|
70
70
|
export declare const CHAT_INITIAL_LOAD_FAILURE_BUDGET_MS = 15000;
|
|
71
|
-
export { HEARTBEAT_MS, TYPING_COALESCE_MS, HISTORY_PAGE_MAX } from '@ttt-productions/chat-schemas';
|
|
72
71
|
/**
|
|
73
72
|
* Max reconnect resends of one un-acked send before its optimistic row is flipped
|
|
74
73
|
* to a visible failed state (retry affordance) instead of a permanent ghost. Each
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shared.d.ts","sourceRoot":"","sources":["../../src/realtime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;;;GAIG;AACH,eAAO,MAAM,yBAAyB,IAAI,CAAC;AAE3C;;;GAGG;AACH,eAAO,MAAM,uBAAuB,QAAS,CAAC;AAE9C;;;;;;;;;GASG;AACH,eAAO,MAAM,2BAA2B,QAAS,CAAC;AAElD;;;;GAIG;AACH,eAAO,MAAM,uBAAuB,MAAM,CAAC;AAC3C,eAAO,MAAM,uBAAuB,QAAS,CAAC;AAE9C;;;GAGG;AACH,wBAAgB,gBAAgB,IAAI,MAAM,CAIzC"}
|
package/dist/realtime/shared.js
CHANGED
|
@@ -2,10 +2,9 @@
|
|
|
2
2
|
//
|
|
3
3
|
// The client-agreed limits (`HEARTBEAT_MS`, `TYPING_COALESCE_MS`,
|
|
4
4
|
// `HISTORY_PAGE_MAX`) come from the one wire contract in
|
|
5
|
-
// `@ttt-productions/chat-schemas
|
|
6
|
-
// existing import sites are unchanged. The worker runtime is the authority and
|
|
5
|
+
// `@ttt-productions/chat-schemas`. The worker runtime is the authority and
|
|
7
6
|
// rejects anything out of bounds, but the client uses these to coalesce and
|
|
8
|
-
// paginate politely. The
|
|
7
|
+
// paginate politely. The constants below are client-only retry policy.
|
|
9
8
|
/**
|
|
10
9
|
* Package-owned, Firebase-FREE terminal access-denial signal. A grant provider
|
|
11
10
|
* throws this (from `GrantProvider`) when the authoritative authorization answer
|
|
@@ -73,9 +72,6 @@ export function isTerminalErrorCode(code) {
|
|
|
73
72
|
* constant.
|
|
74
73
|
*/
|
|
75
74
|
export const CHAT_INITIAL_LOAD_FAILURE_BUDGET_MS = 15_000;
|
|
76
|
-
// The client-agreed limits live in the wire contract; re-export to keep this
|
|
77
|
-
// module's public surface stable.
|
|
78
|
-
export { HEARTBEAT_MS, TYPING_COALESCE_MS, HISTORY_PAGE_MAX } from '@ttt-productions/chat-schemas';
|
|
79
75
|
/**
|
|
80
76
|
* Max reconnect resends of one un-acked send before its optimistic row is flipped
|
|
81
77
|
* to a visible failed state (retry affordance) instead of a permanent ghost. Each
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shared.js","sourceRoot":"","sources":["../../src/realtime/shared.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,EAAE;AACF,kEAAkE;AAClE,yDAAyD;AACzD,
|
|
1
|
+
{"version":3,"file":"shared.js","sourceRoot":"","sources":["../../src/realtime/shared.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,EAAE;AACF,kEAAkE;AAClE,yDAAyD;AACzD,2EAA2E;AAC3E,4EAA4E;AAC5E,uEAAuE;AAWvE;;;;;;;;;;;;;;;;GAgBG;AACH,MAAM,OAAO,qBAAsB,SAAQ,KAAK;IAC9C,kFAAkF;IACzE,kBAAkB,GAAG,IAAI,CAAC;IACnC,YAAY,OAAO,GAAG,oBAAoB;QACxC,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,uBAAuB,CAAC;IACtC,CAAC;CACF;AAED,8FAA8F;AAC9F,MAAM,UAAU,uBAAuB,CAAC,GAAY;IAClD,OAAO,CACL,GAAG,YAAY,qBAAqB;QACpC,CAAC,OAAO,GAAG,KAAK,QAAQ;YACtB,GAAG,KAAK,IAAI;YACX,GAAwC,CAAC,kBAAkB,KAAK,IAAI,CAAC,CACzE,CAAC;AACJ,CAAC;AASD,MAAM,CAAC,MAAM,aAAa,GAAoB;IAC5C,UAAU,EAAE,CAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,UAAU,CAAC,EAAE,EAAE,EAAE,CAAC;IAC1C,YAAY,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,YAAY,CAAC,CAAC,CAAC;IACpC,GAAG,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE;CACtB,CAAC;AAKF;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG;IACjC,yEAAyE;IACzE,OAAO,EAAE,SAAS;IAClB,iFAAiF;IACjF,aAAa,EAAE,eAAe;CACtB,CAAC;AAIX,wEAAwE;AACxE,MAAM,UAAU,mBAAmB,CAAC,IAA+B;IACjE,OAAO,IAAI,KAAK,mBAAmB,CAAC,OAAO,IAAI,IAAI,KAAK,mBAAmB,CAAC,aAAa,CAAC;AAC5F,CAAC;AAED;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,mCAAmC,GAAG,MAAM,CAAC;AAE1D;;;;GAIG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAG,CAAC,CAAC;AAE3C;;;GAGG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,MAAM,CAAC;AAE9C;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,2BAA2B,GAAG,MAAM,CAAC;AAElD;;;;GAIG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,GAAG,CAAC;AAC3C,MAAM,CAAC,MAAM,uBAAuB,GAAG,MAAM,CAAC;AAE9C;;;GAGG;AACH,MAAM,UAAU,gBAAgB;IAC9B,MAAM,CAAC,GAAI,UAAyD,CAAC,MAAM,CAAC;IAC5E,IAAI,CAAC,EAAE,UAAU;QAAE,OAAO,CAAC,CAAC,UAAU,EAAE,CAAC;IACzC,OAAO,OAAO,IAAI,CAAC,GAAG,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;AACpE,CAAC","sourcesContent":["// Shared injected contracts + tunable constants for the realtime transport.\n//\n// The client-agreed limits (`HEARTBEAT_MS`, `TYPING_COALESCE_MS`,\n// `HISTORY_PAGE_MAX`) come from the one wire contract in\n// `@ttt-productions/chat-schemas`. The worker runtime is the authority and\n// rejects anything out of bounds, but the client uses these to coalesce and\n// paginate politely. The constants below are client-only retry policy.\n\n/**\n * Mints a short-lived chat grant token for the socket's scope. The app wires this\n * to its `mintChatGrant` callable (channel grant for a ChannelClient, inbox grant\n * for an InboxClient). Called on every connect AND once on a 4401 re-grant. The\n * app owns the Firestore permission check, the scope shape, caching to a React\n * Query staleTime < grant exp, and returning a FRESH token when re-invoked.\n */\nexport type GrantProvider = () => Promise<string>;\n\n/**\n * Package-owned, Firebase-FREE terminal access-denial signal. A grant provider\n * throws this (from `GrantProvider`) when the authoritative authorization answer\n * is a genuine, terminal \"no\" — as opposed to a transient/retryable mint failure.\n *\n * The transport treats it specially: instead of the normal reconnect backoff it\n * STOPS reconnecting, closes the lifecycle, fails any pending optimistic sends,\n * and surfaces the stable `access-denied` error code (which the React hook maps to\n * `allowed: false` so the shell renders its no-access surface instead of an eternal\n * loader). Every other thrown error stays transient and reconnects as before.\n *\n * This is deliberately generic: the consuming app translates its own backend\n * denial (e.g. a Firebase `functions/permission-denied`) into this class at the\n * grant-provider boundary. The package never imports or names Firebase. Consumers\n * that cannot subclass may instead throw any error carrying `isChatAccessDenied:\n * true` — `isChatAccessDeniedError` recognizes both (also cross-realm safe).\n */\nexport class ChatAccessDeniedError extends Error {\n /** Duck-typed marker so detection survives module-realm / re-throw boundaries. */\n readonly isChatAccessDenied = true;\n constructor(message = 'Chat access denied') {\n super(message);\n this.name = 'ChatAccessDeniedError';\n }\n}\n\n/** True when `err` is a terminal chat access denial (class instance or duck-typed marker). */\nexport function isChatAccessDeniedError(err: unknown): err is ChatAccessDeniedError {\n return (\n err instanceof ChatAccessDeniedError ||\n (typeof err === 'object' &&\n err !== null &&\n (err as { isChatAccessDenied?: unknown }).isChatAccessDenied === true)\n );\n}\n\n/** Injectable timers so the transport runs deterministically under fake timers in tests. */\nexport interface TransportTimers {\n setTimeout: (fn: () => void, ms: number) => ReturnType<typeof setTimeout>;\n clearTimeout: (h: ReturnType<typeof setTimeout>) => void;\n now: () => number;\n}\n\nexport const defaultTimers: TransportTimers = {\n setTimeout: (fn, ms) => setTimeout(fn, ms),\n clearTimeout: (h) => clearTimeout(h),\n now: () => Date.now(),\n};\n\n/** Connection status surfaced to the UI. */\nexport type RealtimeStatus = 'idle' | 'connecting' | 'open' | 'reconnecting' | 'closed';\n\n/**\n * The TERMINAL lifecycle verdicts both realtime clients surface on\n * `lastErrorCode` — the two codes that mean \"this lifecycle stopped on an\n * authoritative NO\", as opposed to a transient/protocol code (`send-failed`,\n * `blocked-word`, …) that leaves the socket running.\n *\n * ONE declaration for both clients: each sets and clears the same two strings,\n * and `useRealtimeChatMessages` maps `access-denied` to `allowed: false`.\n * A terminal verdict is terminal WITHIN its lifecycle; a later explicit\n * `connect()` is a fresh attempt the authority may legitimately re-deny, so the\n * stale code is cleared there (never carried into the new lifecycle's state).\n */\nexport const TERMINAL_ERROR_CODE = {\n /** A 4403 REVOKED close: access was pulled while the socket was open. */\n REVOKED: 'revoked',\n /** The grant provider threw `ChatAccessDeniedError` — a terminal policy \"no\". */\n ACCESS_DENIED: 'access-denied',\n} as const;\n\nexport type TerminalErrorCode = (typeof TERMINAL_ERROR_CODE)[keyof typeof TERMINAL_ERROR_CODE];\n\n/** True when `code` is one of the terminal lifecycle verdicts above. */\nexport function isTerminalErrorCode(code: string | null | undefined): code is TerminalErrorCode {\n return code === TERMINAL_ERROR_CODE.REVOKED || code === TERMINAL_ERROR_CODE.ACCESS_DENIED;\n}\n\n/**\n * How long a client keeps failing to open for the first time before it reports the\n * first open as failed (`initialLoadFailed`) — so a chat or inbox that cannot connect\n * shows a failure the user can retry instead of an opening state that never ends. The\n * client keeps retrying in the background after it reports. Client policy, not a wire\n * constant.\n */\nexport const CHAT_INITIAL_LOAD_FAILURE_BUDGET_MS = 15_000;\n\n/**\n * Max reconnect resends of one un-acked send before its optimistic row is flipped\n * to a visible failed state (retry affordance) instead of a permanent ghost. Each\n * reconnect that resumes with the pending send still un-acked counts one attempt.\n */\nexport const MAX_PENDING_SEND_ATTEMPTS = 5;\n\n/**\n * Max wall-clock age of an un-acked pending send before it is flipped to failed on\n * the next resume, even if the attempt cap hasn't been hit (a long offline window).\n */\nexport const PENDING_SEND_MAX_AGE_MS = 60_000;\n\n/**\n * Wall-clock budget (ms) for a SERVER-DECLARED retryable send. Once the Worker has\n * rejected a send as retryable — a correlated `send-rejected` frame OR the legacy\n * uncorrelated `error{code:'membership-pending'}` — that send keeps retrying on the\n * server's own hint until this budget elapses, and is NEVER failed by the generic\n * {@link MAX_PENDING_SEND_ATTEMPTS} cap (which governs only blind reconnect\n * resends). 90 s comfortably covers the backend projection/grant-bootstrap window\n * without stranding an optimistic bubble on \"Sending…\" the way the old ~10 s\n * five-attempt cap did.\n */\nexport const SERVER_RETRYABLE_MAX_AGE_MS = 90_000;\n\n/**\n * Lower/upper clamp (ms) applied to a server `retryAfterMs` hint before scheduling a\n * resend, so a pathological (but schema-valid) hint can neither hammer the socket\n * nor park a send for minutes.\n */\nexport const SEND_RETRY_MIN_DELAY_MS = 250;\nexport const SEND_RETRY_MAX_DELAY_MS = 30_000;\n\n/**\n * A fresh client-minted id for a command the client correlates with its answer (a send's\n * `clientMessageId`, a mark-read's `requestId`). Random, so two tabs never collide.\n */\nexport function newCorrelationId(): string {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) return c.randomUUID();\n return `cid-${Date.now()}-${Math.random().toString(36).slice(2)}`;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"socket.d.ts","sourceRoot":"","sources":["../../src/realtime/socket.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"socket.d.ts","sourceRoot":"","sources":["../../src/realtime/socket.ts"],"names":[],"mappings":"AAYA,+DAA+D;AAC/D,MAAM,WAAW,cAAc;IAC7B,MAAM,EAAE,MAAM,IAAI,CAAC;IACnB,SAAS,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;IAClC,2FAA2F;IAC3F,OAAO,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,KAAK,IAAI,CAAC;IAChD,OAAO,EAAE,MAAM,IAAI,CAAC;CACrB;AAED,+FAA+F;AAC/F,MAAM,WAAW,cAAc;IAC7B,kDAAkD;IAClD,IAAI,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,uEAAuE;IACvE,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5C,kEAAkE;IAClE,QAAQ,CAAC,MAAM,EAAE,OAAO,CAAC;CAC1B;AAED;;;;GAIG;AACH,MAAM,MAAM,aAAa,GAAG,CAAC,IAAI,EAAE;IACjC,GAAG,EAAE,MAAM,CAAC;IACZ,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,EAAE,cAAc,CAAC;CAC1B,KAAK,cAAc,CAAC;AAiBrB;;;GAGG;AACH,eAAO,MAAM,oBAAoB,EAAE,aAyBlC,CAAC"}
|
package/dist/realtime/socket.js
CHANGED
|
@@ -1,14 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
// browser-WebSocket factory. Injectable so unit tests pass a MOCK socket and no
|
|
3
|
-
// real network is touched.
|
|
4
|
-
//
|
|
5
|
-
// Contract A transport: the grant token is offered as the SECOND WebSocket
|
|
6
|
-
// subprotocol — `Sec-WebSocket-Protocol: <CHAT_SUBPROTOCOL>, <grant-token>` —
|
|
7
|
-
// never in the URL (tokens never appear in URLs; Contract A). The browser sets
|
|
8
|
-
// that header from `new WebSocket(url, [CHAT_SUBPROTOCOL, grantToken])`. The
|
|
9
|
-
// worker validates cookie + grant + Origin BEFORE accept and echoes back only
|
|
10
|
-
// CHAT_SUBPROTOCOL.
|
|
11
|
-
import { CHAT_SUBPROTOCOL } from './wire.js';
|
|
1
|
+
import { CHAT_SUBPROTOCOL } from '@ttt-productions/chat-schemas';
|
|
12
2
|
const WS_OPEN = 1;
|
|
13
3
|
/**
|
|
14
4
|
* The default browser socket factory. Offers `[CHAT_SUBPROTOCOL, grantToken]` as the
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"socket.js","sourceRoot":"","sources":["../../src/realtime/socket.ts"],"names":[],"mappings":"AAAA,
|
|
1
|
+
{"version":3,"file":"socket.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AAE,MAAM,CAAC,CAAC;YACzB,CAAC;YAAC,MAAM,CAAC;gBACP,4BAA4B;YAC9B,CAAC;QACH,CAAC;QACD,IAAI,MAAM;YACR,OAAO,EAAE,CAAC,UAAU,KAAK,OAAO,CAAC;QACnC,CAAC;KACF,CAAC;AACJ,CAAC,CAAC","sourcesContent":["import { CHAT_SUBPROTOCOL } from '@ttt-productions/chat-schemas';\n// The minimal socket abstraction the realtime clients drive, plus the default\n// browser-WebSocket factory. Injectable so unit tests pass a MOCK socket and no\n// real network is touched.\n//\n// Contract A transport: the grant token is offered as the SECOND WebSocket\n// subprotocol — `Sec-WebSocket-Protocol: <CHAT_SUBPROTOCOL>, <grant-token>` —\n// never in the URL (tokens never appear in URLs; Contract A). The browser sets\n// that header from `new WebSocket(url, [CHAT_SUBPROTOCOL, grantToken])`. The\n// worker validates cookie + grant + Origin BEFORE accept and echoes back only\n// CHAT_SUBPROTOCOL.\n\n/** Lifecycle events a socket surfaces to its owning client. */\nexport interface SocketHandlers {\n onOpen: () => void;\n onMessage: (data: string) => void;\n /** code/reason from the close frame (4401/4403/4408/4413/4429/1013 or transport codes). */\n onClose: (code: number, reason: string) => void;\n onError: () => void;\n}\n\n/** The transport-neutral socket the clients use. A mock implements the same shape in tests. */\nexport interface RealtimeSocket {\n /** Queue/send a text frame. No-op if not open. */\n send(data: string): void;\n /** Close the socket with an optional app code + reason. Idempotent. */\n close(code?: number, reason?: string): void;\n /** True once the underlying transport is OPEN (ready to send). */\n readonly isOpen: boolean;\n}\n\n/**\n * A factory that opens a socket to `url`, offering the chat subprotocol + the\n * grant token, and wires the handlers. Injected into the transport so tests\n * substitute a mock. The default factory uses the global `WebSocket`.\n */\nexport type SocketFactory = (args: {\n url: string;\n grantToken: string;\n handlers: SocketHandlers;\n}) => RealtimeSocket;\n\n/** A WebSocket-like minimal surface (so we don't hard-depend on lib.dom in node-safe builds). */\ninterface MinimalWebSocket {\n send(data: string): void;\n close(code?: number, reason?: string): void;\n readyState: number;\n onopen: ((ev: unknown) => void) | null;\n onmessage: ((ev: { data: unknown }) => void) | null;\n onclose: ((ev: { code: number; reason: string }) => void) | null;\n onerror: ((ev: unknown) => void) | null;\n}\n\ntype WebSocketCtor = new (url: string, protocols?: string | string[]) => MinimalWebSocket;\n\nconst WS_OPEN = 1;\n\n/**\n * The default browser socket factory. Offers `[CHAT_SUBPROTOCOL, grantToken]` as the\n * subprotocol list so the grant rides in `Sec-WebSocket-Protocol`, never the URL.\n */\nexport const browserSocketFactory: SocketFactory = ({ url, grantToken, handlers }) => {\n const Ctor = (globalThis as { WebSocket?: WebSocketCtor }).WebSocket;\n if (!Ctor)\n throw new Error('[chat-realtime] no global WebSocket available; inject a SocketFactory');\n const ws = new Ctor(url, [CHAT_SUBPROTOCOL, grantToken]);\n ws.onopen = () => handlers.onOpen();\n ws.onmessage = (ev) =>\n handlers.onMessage(typeof ev.data === 'string' ? ev.data : String(ev.data));\n ws.onclose = (ev) => handlers.onClose(ev.code, ev.reason);\n ws.onerror = () => handlers.onError();\n return {\n send(data: string) {\n if (ws.readyState === WS_OPEN) ws.send(data);\n },\n close(code?: number, reason?: string) {\n try {\n ws.close(code, reason);\n } catch {\n /* already closing/closed */\n }\n },\n get isOpen() {\n return ws.readyState === WS_OPEN;\n },\n };\n};\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ChannelClient, type ChannelClientConfig, type ChannelClientState } from './channel-client.js';
|
|
2
|
-
import { InboxClient, type InboxClientConfig
|
|
2
|
+
import { InboxClient, type InboxClientConfig } from './inbox-client.js';
|
|
3
3
|
import { type SocketFactory } from './socket.js';
|
|
4
4
|
import type { GrantProvider, TransportTimers } from './shared.js';
|
|
5
5
|
import type { ChatClientDiagnosticsOption } from './diagnostics.js';
|
|
@@ -58,5 +58,4 @@ export declare function createInboxClient(config: {
|
|
|
58
58
|
/** OPT-IN structured diagnostics, forwarded to the InboxClient (default OFF). */
|
|
59
59
|
diagnostics?: ChatClientDiagnosticsOption;
|
|
60
60
|
}): InboxClient;
|
|
61
|
-
export type { ChannelClientState, InboxClientState };
|
|
62
61
|
//# sourceMappingURL=transport.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../../src/realtime/transport.ts"],"names":[],"mappings":"AAYA,OAAO,
|
|
1
|
+
{"version":3,"file":"transport.d.ts","sourceRoot":"","sources":["../../src/realtime/transport.ts"],"names":[],"mappings":"AAYA,OAAO,EACL,aAAa,EACb,KAAK,mBAAmB,EACxB,KAAK,kBAAkB,EACxB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,WAAW,EAAE,KAAK,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACxE,OAAO,EAAwB,KAAK,aAAa,EAAE,MAAM,aAAa,CAAC;AACvE,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAE,MAAM,aAAa,CAAC;AAClE,OAAO,KAAK,EAAE,2BAA2B,EAAE,MAAM,kBAAkB,CAAC;AACpE,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AAEzE;;;;GAIG;AACH,MAAM,WAAW,uBAAuB;IACtC,QAAQ,EAAE,MAAM,CAAC;IACjB,yFAAyF;IACzF,UAAU,EAAE,mBAAmB,CAAC;IAChC,QAAQ,EAAE,MAAM,CAAC;IACjB,aAAa,EAAE,MAAM,CAAC;IACtB,aAAa,EAAE,aAAa,CAAC;IAC7B,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,MAAM,CAAC,EAAE,eAAe,CAAC;IACzB,SAAS,CAAC,EAAE,mBAAmB,CAAC,WAAW,CAAC,CAAC;IAC7C;;;;;;OAMG;IACH,WAAW,CAAC,EAAE,2BAA2B,CAAC;CAC3C;AAED;;;;GAIG;AACH,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,OAAO,EAAE,aAAa,CAAC;IAChC,QAAQ,CAAC,UAAU,EAAE,mBAAmB,CAAC;IACzC,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACzB,gGAAgG;IAChG,KAAK,IAAI,IAAI,CAAC;IACd,uEAAuE;IACvE,KAAK,IAAI,IAAI,CAAC;IACd,QAAQ,IAAI,kBAAkB,CAAC;IAC/B,SAAS,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,kBAAkB,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;CAC5D;AAED,4FAA4F;AAC5F,wBAAgB,wBAAwB,CAAC,MAAM,EAAE,uBAAuB,GAAG,kBAAkB,CAsB5F;AAED,iFAAiF;AACjF,wBAAgB,iBAAiB,CAAC,MAAM,EAAE;IACxC,QAAQ,EAAE,MAAM,CAAC;IACjB,aAAa,EAAE,MAAM,CAAC;IACtB,aAAa,EAAE,aAAa,CAAC;IAC7B,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,MAAM,CAAC,EAAE,eAAe,CAAC;IACzB,SAAS,CAAC,EAAE,iBAAiB,CAAC,WAAW,CAAC,CAAC;IAC3C,iFAAiF;IACjF,WAAW,CAAC,EAAE,2BAA2B,CAAC;CAC3C,GAAG,WAAW,CAUd"}
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
// lifetime (mount it once at the dock, not per ChatShell). This keeps the channel
|
|
10
10
|
// transport (per-thread) and the inbox transport (per-user) cleanly split, exactly
|
|
11
11
|
// as the worker splits Channel DOs from the Inbox DO.
|
|
12
|
-
import { ChannelClient } from './channel-client.js';
|
|
12
|
+
import { ChannelClient, } from './channel-client.js';
|
|
13
13
|
import { InboxClient } from './inbox-client.js';
|
|
14
14
|
import { browserSocketFactory } from './socket.js';
|
|
15
15
|
/** Create the per-thread realtime client (the value placed on `config.realtime.client`). */
|