@ttt-productions/chat-react 0.12.7 → 0.12.8
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/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/realtime/channel-client.d.ts +21 -0
- package/dist/realtime/channel-client.d.ts.map +1 -1
- package/dist/realtime/channel-client.js +35 -3
- package/dist/realtime/channel-client.js.map +1 -1
- package/dist/realtime/index.d.ts +1 -1
- package/dist/realtime/index.d.ts.map +1 -1
- package/dist/realtime/index.js +1 -1
- package/dist/realtime/index.js.map +1 -1
- package/dist/realtime/shared.d.ts +24 -0
- package/dist/realtime/shared.d.ts.map +1 -1
- package/dist/realtime/shared.js +32 -0
- package/dist/realtime/shared.js.map +1 -1
- package/dist/realtime/useRealtimeChatMessages.d.ts.map +1 -1
- package/dist/realtime/useRealtimeChatMessages.js +11 -5
- package/dist/realtime/useRealtimeChatMessages.js.map +1 -1
- package/dist/ui/ChatShell.d.ts.map +1 -1
- package/dist/ui/ChatShell.js +10 -8
- package/dist/ui/ChatShell.js.map +1 -1
- package/dist/ui/MessageItemDefault.d.ts.map +1 -1
- package/dist/ui/MessageItemDefault.js +11 -2
- package/dist/ui/MessageItemDefault.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -8,7 +8,7 @@ export { ChatNameResolverProvider, useChatNameResolver, useOptionalChatNameResol
|
|
|
8
8
|
export type { UseChatMessagesResult } from "./hooks/useChatMessages.js";
|
|
9
9
|
export { useChatMessages } from "./hooks/useChatMessages.js";
|
|
10
10
|
export { canAccessThread } from "./hooks/useChatThreadAccess.js";
|
|
11
|
-
export { createRealtimeChatClient, createInboxClient, ChannelClient, InboxClient, useRealtimeChatMessages, browserSocketFactory, CHAT_SUBPROTOCOL, CHAT_CLOSE_CODES, CLIENT_FRAME, SERVER_FRAME, buildFrame, parseFrame, } from "./realtime/index.js";
|
|
11
|
+
export { createRealtimeChatClient, createInboxClient, ChannelClient, InboxClient, useRealtimeChatMessages, browserSocketFactory, ChatAccessDeniedError, isChatAccessDeniedError, CHAT_SUBPROTOCOL, CHAT_CLOSE_CODES, CLIENT_FRAME, SERVER_FRAME, buildFrame, parseFrame, } from "./realtime/index.js";
|
|
12
12
|
export type { RealtimeChatClient, RealtimeTransportConfig, ChannelClientState, ChannelClientConfig, InboxClientState, InboxClientConfig, UseRealtimeChatMessagesResult, GrantProvider, TransportTimers, RealtimeStatus, RealtimeSocket, SocketFactory, SocketHandlers, ChannelRefTuple, WireMessageRow, WireInboxSnapshot, WireRegistryEntry, ServerFrame, } from "./realtime/index.js";
|
|
13
13
|
export type { ChatShellProps } from "./ui/ChatShell.js";
|
|
14
14
|
export { ChatShell } from "./ui/ChatShell.js";
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AASA,YAAY,EACV,cAAc,EACd,iBAAiB,EACjB,2BAA2B,EAC3B,oBAAoB,EACpB,iBAAiB,EACjB,iBAAiB,EACjB,eAAe,EACf,uBAAuB,EACvB,yBAAyB,EACzB,qBAAqB,GACtB,MAAM,YAAY,CAAC;AAGpB,YAAY,EACV,yBAAyB,EACzB,8BAA8B,GAC/B,MAAM,uCAAuC,CAAC;AAC/C,OAAO,EACL,yBAAyB,EACzB,4BAA4B,GAC7B,MAAM,uCAAuC,CAAC;AAM/C,YAAY,EACV,4BAA4B,EAC5B,gCAAgC,GACjC,MAAM,yCAAyC,CAAC;AACjD,OAAO,EACL,2BAA2B,EAC3B,+BAA+B,GAChC,MAAM,yCAAyC,CAAC;AAGjD,YAAY,EAAE,6BAA6B,EAAE,MAAM,sCAAsC,CAAC;AAC1F,OAAO,EACL,wBAAwB,EACxB,mBAAmB,EACnB,2BAA2B,EAC3B,qBAAqB,GACtB,MAAM,sCAAsC,CAA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ChB,iBAAiB,EACjB,6BAA6B,EAC7B,aAAa,EACb,eAAe,EACf,cAAc,EACd,cAAc,EACd,aAAa,EACb,cAAc,EACd,eAAe,EACf,cAAc,EACd,iBAAiB,EACjB,iBAAiB,EACjB,WAAW,GACZ,MAAM,qBAAqB,CAAC;AAU7B,YAAY,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACxD,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAClD,YAAY,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,YAAY,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AAC1E,OAAO,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAC9D,OAAO,EAAE,WAAW,EAAE,KAAK,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAC/E,OAAO,EACL,mBAAmB,EACnB,KAAK,wBAAwB,GAC9B,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,sBAAsB,EACtB,KAAK,0BAA0B,EAC/B,KAAK,4BAA4B,EACjC,KAAK,iBAAiB,EACtB,KAAK,uBAAuB,GAC7B,MAAM,wCAAwC,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -7,7 +7,7 @@ export { canAccessThread } from "./hooks/useChatThreadAccess.js";
|
|
|
7
7
|
// Realtime (Cloudflare Durable Object) transport — the client half of the chat
|
|
8
8
|
// worker wire protocol. Opt-in via `ChatCoreConfig.transport === 'realtime'`; the
|
|
9
9
|
// firestore transport stays the unchanged default. See docs/packages/chat-react.md.
|
|
10
|
-
export { createRealtimeChatClient, createInboxClient, ChannelClient, InboxClient, useRealtimeChatMessages, browserSocketFactory, CHAT_SUBPROTOCOL, CHAT_CLOSE_CODES, CLIENT_FRAME, SERVER_FRAME, buildFrame, parseFrame, } from "./realtime/index.js";
|
|
10
|
+
export { createRealtimeChatClient, createInboxClient, ChannelClient, InboxClient, useRealtimeChatMessages, browserSocketFactory, ChatAccessDeniedError, isChatAccessDeniedError, CHAT_SUBPROTOCOL, CHAT_CLOSE_CODES, CLIENT_FRAME, SERVER_FRAME, buildFrame, parseFrame, } from "./realtime/index.js";
|
|
11
11
|
export { ChatShell } from "./ui/ChatShell.js";
|
|
12
12
|
export { MessageList } from "./ui/MessageList.js";
|
|
13
13
|
export { Composer } from "./ui/Composer.js";
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AA2Bb,OAAO,EACL,yBAAyB,EACzB,4BAA4B,GAC7B,MAAM,uCAAuC,CAAC;AAU/C,OAAO,EACL,2BAA2B,EAC3B,+BAA+B,GAChC,MAAM,yCAAyC,CAAC;AAIjD,OAAO,EACL,wBAAwB,EACxB,mBAAmB,EACnB,2BAA2B,EAC3B,qBAAqB,GACtB,MAAM,sCAAsC,CAAC;AAG9C,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AAEjE,+EAA+E;AAC/E,kFAAkF;AAClF,oFAAoF;AACpF,OAAO,EACL,wBAAwB,EACxB,iBAAiB,EACjB,aAAa,EACb,WAAW,EACX,uBAAuB,EACvB,oBAAoB,EACpB,gBAAgB,EAChB,gBAAgB,EAChB,YAAY,EACZ,YAAY,EACZ,UAAU,EACV,UAAU,GACX,MAAM,qBAAqB,CAAC;AA+B7B,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAElD,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAE5C,OAAO,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAC9D,OAAO,EAAE,WAAW,EAAyB,MAAM,2BAA2B,CAAC;AAC/E,OAAO,EACL,mBAAmB,GAEpB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,sBAAsB,GAKvB,MAAM,wCAAwC,CAAC","sourcesContent":["\"use client\";\n\n// @ttt-productions/chat-react — chat React UI, hooks, the Firebase-client\n// adapter config types, and React render types. Depends on the pure\n// @ttt-productions/chat-core for contracts, parser, and grouping.\n//\n// Apps import chat CSS via \"@ttt-productions/chat-react/styles\".\n\n// React-coupled config + render types (previously on chat-core root).\nexport type {\n ChatCoreConfig,\n ChatTransportMode,\n ChatRealtimeTransportConfig,\n ChatAttachmentConfig,\n ChatUploadAdapter,\n ChatMentionConfig,\n MessageRenderer,\n MessageRendererRegistry,\n RenderableMentionProvider,\n MentionResultRenderer,\n} from \"./types.js\";\n\n// Attachment-URL resolver context (render-time URL building from mediaAssetId).\nexport type {\n ChatAttachmentUrlResolver,\n ChatAttachmentUrlProviderProps,\n} from \"./context/ChatAttachmentUrlContext.js\";\nexport {\n ChatAttachmentUrlProvider,\n useChatAttachmentUrlResolver,\n} from \"./context/ChatAttachmentUrlContext.js\";\n\n// Attachment media-component injection (optional) — the app hands chat its own\n// display-path wrapper (recovery adapter, diagnostics, telemetry) so chat\n// media rides the same pipeline as every other surface; default stays the\n// package MediaViewer.\nexport type {\n ChatAttachmentMediaComponent,\n ChatAttachmentMediaProviderProps,\n} from \"./context/ChatAttachmentMediaContext.js\";\nexport {\n ChatAttachmentMediaProvider,\n useChatAttachmentMediaComponent,\n} from \"./context/ChatAttachmentMediaContext.js\";\n\n// Name-resolver context.\nexport type { ChatNameResolverProviderProps } from \"./context/ChatNameResolverContext.js\";\nexport {\n ChatNameResolverProvider,\n useChatNameResolver,\n useOptionalChatNameResolver,\n useResolvedSenderName,\n} from \"./context/ChatNameResolverContext.js\";\n\nexport type { UseChatMessagesResult } from \"./hooks/useChatMessages.js\";\nexport { useChatMessages } from \"./hooks/useChatMessages.js\";\nexport { canAccessThread } from \"./hooks/useChatThreadAccess.js\";\n\n// Realtime (Cloudflare Durable Object) transport — the client half of the chat\n// worker wire protocol. Opt-in via `ChatCoreConfig.transport === 'realtime'`; the\n// firestore transport stays the unchanged default. See docs/packages/chat-react.md.\nexport {\n createRealtimeChatClient,\n createInboxClient,\n ChannelClient,\n InboxClient,\n useRealtimeChatMessages,\n browserSocketFactory,\n CHAT_SUBPROTOCOL,\n CHAT_CLOSE_CODES,\n CLIENT_FRAME,\n SERVER_FRAME,\n buildFrame,\n parseFrame,\n} from \"./realtime/index.js\";\nexport type {\n RealtimeChatClient,\n RealtimeTransportConfig,\n ChannelClientState,\n ChannelClientConfig,\n InboxClientState,\n InboxClientConfig,\n UseRealtimeChatMessagesResult,\n GrantProvider,\n TransportTimers,\n RealtimeStatus,\n RealtimeSocket,\n SocketFactory,\n SocketHandlers,\n ChannelRefTuple,\n WireMessageRow,\n WireInboxSnapshot,\n WireRegistryEntry,\n ServerFrame,\n} from \"./realtime/index.js\";\n\n// TODO (re-export when a consumer needs them): the moderation-overlay helpers\n// `RevisionKind`, `ModerationOverlay`, `applyModerationOverlay`, `overlayFromRow`,\n// and `MODERATION_REDACTED_TEXT` live in `./realtime` but are intentionally NOT\n// re-exported from this package root yet — the consuming app's renderer reads moderation\n// state off `message.meta` (the realtime client applies the overlay internally), so\n// nothing imports them from here today. Add them to the block above when a consumer\n// genuinely needs to apply the overlay directly. (Comment-only; rides the next publish.)\n\nexport type { ChatShellProps } from \"./ui/ChatShell.js\";\nexport { ChatShell } from \"./ui/ChatShell.js\";\nexport { MessageList } from \"./ui/MessageList.js\";\nexport type { ComposerProps } from \"./ui/Composer.js\";\nexport { Composer } from \"./ui/Composer.js\";\nexport type { MessageItemDefaultProps } from \"./ui/MessageItemDefault.js\";\nexport { MessageItemDefault } from \"./ui/MessageItemDefault.js\";\nexport { MessageActions, ThreadActions } from \"./ui/menus.js\";\nexport { MessageText, type MessageTextProps } from \"./mentions/MessageText.js\";\nexport {\n MentionAutocomplete,\n type MentionAutocompleteProps,\n} from \"./mentions/MentionAutocomplete.js\";\nexport {\n useMentionAutocomplete,\n type UseMentionAutocompleteArgs,\n type UseMentionAutocompleteResult,\n type AutocompleteState,\n type AutocompleteResultGroup,\n} from \"./mentions/use-mention-autocomplete.js\";\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AA2Bb,OAAO,EACL,yBAAyB,EACzB,4BAA4B,GAC7B,MAAM,uCAAuC,CAAC;AAU/C,OAAO,EACL,2BAA2B,EAC3B,+BAA+B,GAChC,MAAM,yCAAyC,CAAC;AAIjD,OAAO,EACL,wBAAwB,EACxB,mBAAmB,EACnB,2BAA2B,EAC3B,qBAAqB,GACtB,MAAM,sCAAsC,CAAC;AAG9C,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAC7D,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AAEjE,+EAA+E;AAC/E,kFAAkF;AAClF,oFAAoF;AACpF,OAAO,EACL,wBAAwB,EACxB,iBAAiB,EACjB,aAAa,EACb,WAAW,EACX,uBAAuB,EACvB,oBAAoB,EACpB,qBAAqB,EACrB,uBAAuB,EACvB,gBAAgB,EAChB,gBAAgB,EAChB,YAAY,EACZ,YAAY,EACZ,UAAU,EACV,UAAU,GACX,MAAM,qBAAqB,CAAC;AA+B7B,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAElD,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAE5C,OAAO,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAC9D,OAAO,EAAE,WAAW,EAAyB,MAAM,2BAA2B,CAAC;AAC/E,OAAO,EACL,mBAAmB,GAEpB,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EACL,sBAAsB,GAKvB,MAAM,wCAAwC,CAAC","sourcesContent":["\"use client\";\n\n// @ttt-productions/chat-react — chat React UI, hooks, the Firebase-client\n// adapter config types, and React render types. Depends on the pure\n// @ttt-productions/chat-core for contracts, parser, and grouping.\n//\n// Apps import chat CSS via \"@ttt-productions/chat-react/styles\".\n\n// React-coupled config + render types (previously on chat-core root).\nexport type {\n ChatCoreConfig,\n ChatTransportMode,\n ChatRealtimeTransportConfig,\n ChatAttachmentConfig,\n ChatUploadAdapter,\n ChatMentionConfig,\n MessageRenderer,\n MessageRendererRegistry,\n RenderableMentionProvider,\n MentionResultRenderer,\n} from \"./types.js\";\n\n// Attachment-URL resolver context (render-time URL building from mediaAssetId).\nexport type {\n ChatAttachmentUrlResolver,\n ChatAttachmentUrlProviderProps,\n} from \"./context/ChatAttachmentUrlContext.js\";\nexport {\n ChatAttachmentUrlProvider,\n useChatAttachmentUrlResolver,\n} from \"./context/ChatAttachmentUrlContext.js\";\n\n// Attachment media-component injection (optional) — the app hands chat its own\n// display-path wrapper (recovery adapter, diagnostics, telemetry) so chat\n// media rides the same pipeline as every other surface; default stays the\n// package MediaViewer.\nexport type {\n ChatAttachmentMediaComponent,\n ChatAttachmentMediaProviderProps,\n} from \"./context/ChatAttachmentMediaContext.js\";\nexport {\n ChatAttachmentMediaProvider,\n useChatAttachmentMediaComponent,\n} from \"./context/ChatAttachmentMediaContext.js\";\n\n// Name-resolver context.\nexport type { ChatNameResolverProviderProps } from \"./context/ChatNameResolverContext.js\";\nexport {\n ChatNameResolverProvider,\n useChatNameResolver,\n useOptionalChatNameResolver,\n useResolvedSenderName,\n} from \"./context/ChatNameResolverContext.js\";\n\nexport type { UseChatMessagesResult } from \"./hooks/useChatMessages.js\";\nexport { useChatMessages } from \"./hooks/useChatMessages.js\";\nexport { canAccessThread } from \"./hooks/useChatThreadAccess.js\";\n\n// Realtime (Cloudflare Durable Object) transport — the client half of the chat\n// worker wire protocol. Opt-in via `ChatCoreConfig.transport === 'realtime'`; the\n// firestore transport stays the unchanged default. See docs/packages/chat-react.md.\nexport {\n createRealtimeChatClient,\n createInboxClient,\n ChannelClient,\n InboxClient,\n useRealtimeChatMessages,\n browserSocketFactory,\n ChatAccessDeniedError,\n isChatAccessDeniedError,\n CHAT_SUBPROTOCOL,\n CHAT_CLOSE_CODES,\n CLIENT_FRAME,\n SERVER_FRAME,\n buildFrame,\n parseFrame,\n} from \"./realtime/index.js\";\nexport type {\n RealtimeChatClient,\n RealtimeTransportConfig,\n ChannelClientState,\n ChannelClientConfig,\n InboxClientState,\n InboxClientConfig,\n UseRealtimeChatMessagesResult,\n GrantProvider,\n TransportTimers,\n RealtimeStatus,\n RealtimeSocket,\n SocketFactory,\n SocketHandlers,\n ChannelRefTuple,\n WireMessageRow,\n WireInboxSnapshot,\n WireRegistryEntry,\n ServerFrame,\n} from \"./realtime/index.js\";\n\n// TODO (re-export when a consumer needs them): the moderation-overlay helpers\n// `RevisionKind`, `ModerationOverlay`, `applyModerationOverlay`, `overlayFromRow`,\n// and `MODERATION_REDACTED_TEXT` live in `./realtime` but are intentionally NOT\n// re-exported from this package root yet — the consuming app's renderer reads moderation\n// state off `message.meta` (the realtime client applies the overlay internally), so\n// nothing imports them from here today. Add them to the block above when a consumer\n// genuinely needs to apply the overlay directly. (Comment-only; rides the next publish.)\n\nexport type { ChatShellProps } from \"./ui/ChatShell.js\";\nexport { ChatShell } from \"./ui/ChatShell.js\";\nexport { MessageList } from \"./ui/MessageList.js\";\nexport type { ComposerProps } from \"./ui/Composer.js\";\nexport { Composer } from \"./ui/Composer.js\";\nexport type { MessageItemDefaultProps } from \"./ui/MessageItemDefault.js\";\nexport { MessageItemDefault } from \"./ui/MessageItemDefault.js\";\nexport { MessageActions, ThreadActions } from \"./ui/menus.js\";\nexport { MessageText, type MessageTextProps } from \"./mentions/MessageText.js\";\nexport {\n MentionAutocomplete,\n type MentionAutocompleteProps,\n} from \"./mentions/MentionAutocomplete.js\";\nexport {\n useMentionAutocomplete,\n type UseMentionAutocompleteArgs,\n type UseMentionAutocompleteResult,\n type AutocompleteState,\n type AutocompleteResultGroup,\n} from \"./mentions/use-mention-autocomplete.js\";\n"]}
|
|
@@ -15,6 +15,17 @@ export interface ChannelClientState {
|
|
|
15
15
|
hasOlder: boolean;
|
|
16
16
|
/** The last structured error code the DO sent (e.g. 'blocked-word', 'too-long', flood reason). */
|
|
17
17
|
lastErrorCode: string | null;
|
|
18
|
+
/**
|
|
19
|
+
* True once the FIRST authoritative chat data has been applied — a non-resync
|
|
20
|
+
* resume snapshot, OR the first history page (INCLUDING an empty one). Drives the
|
|
21
|
+
* hook's `isInitialLoading` so the shell shows an honest "Opening chat…" state
|
|
22
|
+
* while the first data is loading, and a real empty-chat surface only after an
|
|
23
|
+
* authoritative empty result. NEVER inferred from `messages.length === 0` (an
|
|
24
|
+
* empty first history page IS a successful load). Once true it stays true — a
|
|
25
|
+
* later disconnect/reconnect keeps loaded messages mounted, not a re-loader.
|
|
26
|
+
* A grant retry / socket open before any snapshot leaves it false.
|
|
27
|
+
*/
|
|
28
|
+
hasLoadedInitialData: boolean;
|
|
18
29
|
}
|
|
19
30
|
export interface ChannelClientConfig {
|
|
20
31
|
/** WebSocket endpoint base, e.g. `wss://chat.ttt.productions`. The client appends `/channel`. */
|
|
@@ -122,6 +133,16 @@ export declare class ChannelClient {
|
|
|
122
133
|
private onError;
|
|
123
134
|
private onClose;
|
|
124
135
|
private scheduleReconnect;
|
|
136
|
+
/**
|
|
137
|
+
* Terminal access denial surfaced by the grant provider (ChatAccessDeniedError).
|
|
138
|
+
* A reconnect would just re-deny at the next mint, so stop for good — the same
|
|
139
|
+
* terminal posture as a 4403 REVOKED close: mark closed-by-us, close the reconnect
|
|
140
|
+
* controller, and flip every un-acked pending send to the visible failed state.
|
|
141
|
+
* `access-denied` is set AFTER failAllPendingSends so its 'send-failed' code does
|
|
142
|
+
* not win as the surfaced error; the React hook maps 'access-denied' to
|
|
143
|
+
* `allowed: false` so the shell renders its existing no-access surface.
|
|
144
|
+
*/
|
|
145
|
+
private denyAccessTerminally;
|
|
125
146
|
private onMessage;
|
|
126
147
|
/**
|
|
127
148
|
* Apply a live moderation `revision` frame: record the overlay keyed by seq
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"channel-client.d.ts","sourceRoot":"","sources":["../../src/realtime/channel-client.ts"],"names":[],"mappings":"AAkBA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAWhE,OAAO,KAAK,EAAkB,aAAa,EAAE,MAAM,aAAa,CAAC;AASjE,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"channel-client.d.ts","sourceRoot":"","sources":["../../src/realtime/channel-client.ts"],"names":[],"mappings":"AAkBA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAWhE,OAAO,KAAK,EAAkB,aAAa,EAAE,MAAM,aAAa,CAAC;AASjE,OAAO,KAAK,EAAE,aAAa,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AA0BlF,MAAM,WAAW,kBAAkB;IACjC,MAAM,EAAE,cAAc,CAAC;IACvB,mFAAmF;IACnF,QAAQ,EAAE,aAAa,EAAE,CAAC;IAC1B,4EAA4E;IAC5E,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,6EAA6E;IAC7E,QAAQ,EAAE,MAAM,EAAE,CAAC;IACnB,6DAA6D;IAC7D,eAAe,EAAE,OAAO,CAAC;IACzB,2FAA2F;IAC3F,QAAQ,EAAE,OAAO,CAAC;IAClB,kGAAkG;IAClG,aAAa,EAAE,MAAM,GAAG,IAA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C;QAAC,OAAO,CAAC,EAAE;YAAE,UAAU,EAAE,MAAM,CAAC;YAAC,OAAO,EAAE,MAAM,CAAA;SAAE,GAAG,IAAI,CAAA;KAAE,GAAG,OAAO;IAsCxH;;;;;OAKG;IACH,OAAO,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,GAAG,OAAO;IAKnD,yEAAyE;IACzE,MAAM,IAAI,IAAI;IAOd,iBAAiB,IAAI,IAAI;IAKzB,mBAAmB,IAAI,IAAI;IAM3B,2FAA2F;IAC3F,UAAU,IAAI,IAAI;IAQlB,OAAO,CAAC,cAAc;IAMtB,OAAO,CAAC,cAAc;IAUtB,OAAO,CAAC,aAAa;IASrB,8EAA8E;IAC9E,KAAK,IAAI,IAAI;CAuBd"}
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
import { createReconnectController } from '@ttt-productions/realtime-core';
|
|
18
18
|
import { CLIENT_FRAME, CHAT_CLOSE_CODES, buildFrame, parseFrame, isInboxSnapshot, } from './wire.js';
|
|
19
19
|
import { wireRowToMessage, optimisticMessage, seqToMessageId, applyModerationOverlay, overlayFromRow, } from './map.js';
|
|
20
|
-
import { defaultTimers, HEARTBEAT_MS, TYPING_COALESCE_MS, HISTORY_PAGE_MAX, MAX_PENDING_SEND_ATTEMPTS, PENDING_SEND_MAX_AGE_MS, } from './shared.js';
|
|
20
|
+
import { defaultTimers, isChatAccessDeniedError, HEARTBEAT_MS, TYPING_COALESCE_MS, HISTORY_PAGE_MAX, MAX_PENDING_SEND_ATTEMPTS, PENDING_SEND_MAX_AGE_MS, } from './shared.js';
|
|
21
21
|
const INITIAL = {
|
|
22
22
|
status: 'idle',
|
|
23
23
|
messages: [],
|
|
@@ -26,6 +26,7 @@ const INITIAL = {
|
|
|
26
26
|
isFetchingOlder: false,
|
|
27
27
|
hasOlder: true,
|
|
28
28
|
lastErrorCode: null,
|
|
29
|
+
hasLoadedInitialData: false,
|
|
29
30
|
};
|
|
30
31
|
/**
|
|
31
32
|
* Retryable error-frame code the channel DO sends when a send arrives BEFORE the
|
|
@@ -119,8 +120,15 @@ export class ChannelClient {
|
|
|
119
120
|
try {
|
|
120
121
|
grantToken = await this.config.grantProvider();
|
|
121
122
|
}
|
|
122
|
-
catch {
|
|
123
|
-
//
|
|
123
|
+
catch (err) {
|
|
124
|
+
// A TERMINAL access denial (the app's grant provider translated an
|
|
125
|
+
// authoritative policy "no" into the package-owned ChatAccessDeniedError)
|
|
126
|
+
// must NOT reconnect — the next mint would just re-deny, stranding the shell
|
|
127
|
+
// on the opening loader forever. Every other mint failure (network, transient
|
|
128
|
+
// 'unavailable'/'internal', post-login 'unauthenticated') stays retryable and
|
|
129
|
+
// backs off exactly as before.
|
|
130
|
+
if (isChatAccessDeniedError(err))
|
|
131
|
+
return this.denyAccessTerminally();
|
|
124
132
|
return this.scheduleReconnect();
|
|
125
133
|
}
|
|
126
134
|
if (this.closedByUs)
|
|
@@ -301,6 +309,21 @@ export class ChannelClient {
|
|
|
301
309
|
void this.openSocket();
|
|
302
310
|
}, delay);
|
|
303
311
|
}
|
|
312
|
+
/**
|
|
313
|
+
* Terminal access denial surfaced by the grant provider (ChatAccessDeniedError).
|
|
314
|
+
* A reconnect would just re-deny at the next mint, so stop for good — the same
|
|
315
|
+
* terminal posture as a 4403 REVOKED close: mark closed-by-us, close the reconnect
|
|
316
|
+
* controller, and flip every un-acked pending send to the visible failed state.
|
|
317
|
+
* `access-denied` is set AFTER failAllPendingSends so its 'send-failed' code does
|
|
318
|
+
* not win as the surfaced error; the React hook maps 'access-denied' to
|
|
319
|
+
* `allowed: false` so the shell renders its existing no-access surface.
|
|
320
|
+
*/
|
|
321
|
+
denyAccessTerminally() {
|
|
322
|
+
this.closedByUs = true;
|
|
323
|
+
this.controller.close();
|
|
324
|
+
this.failAllPendingSends();
|
|
325
|
+
this.setState({ status: 'closed', lastErrorCode: 'access-denied' });
|
|
326
|
+
}
|
|
304
327
|
// ---- inbound frames ----
|
|
305
328
|
onMessage(data) {
|
|
306
329
|
const frame = parseFrame(data);
|
|
@@ -424,6 +447,11 @@ export class ChannelClient {
|
|
|
424
447
|
this.applyMessage(row);
|
|
425
448
|
if (snap.lastMessageSeq > this.resumeSeq)
|
|
426
449
|
this.resumeSeq = snap.lastMessageSeq;
|
|
450
|
+
// A non-resync snapshot IS the first authoritative data (even an empty delta =
|
|
451
|
+
// caught up) — end initial loading. A resync snapshot instead defers to the
|
|
452
|
+
// re-paged first history page below, so it must NOT end it here.
|
|
453
|
+
if (!this.state.hasLoadedInitialData)
|
|
454
|
+
this.setState({ hasLoadedInitialData: true });
|
|
427
455
|
return;
|
|
428
456
|
}
|
|
429
457
|
// Resync: drop the local tail and re-page from the top per the pinned contract.
|
|
@@ -519,6 +547,10 @@ export class ChannelClient {
|
|
|
519
547
|
messages: merged,
|
|
520
548
|
isFetchingOlder: false,
|
|
521
549
|
hasOlder: rows.length >= HISTORY_PAGE_MAX,
|
|
550
|
+
// The first history page — INCLUDING an empty one — is a successful authoritative
|
|
551
|
+
// load, so it ends initial loading. (Older-page fetches redundantly re-set true,
|
|
552
|
+
// which is a harmless no-op since the flag never flips back to false.)
|
|
553
|
+
hasLoadedInitialData: true,
|
|
522
554
|
});
|
|
523
555
|
}
|
|
524
556
|
applyTyping(uid) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"channel-client.js","sourceRoot":"","sources":["../../src/realtime/channel-client.ts"],"names":[],"mappings":"AAAA,iFAAiF;AACjF,kFAAkF;AAClF,8EAA8E;AAC9E,EAAE;AACF,iCAAiC;AACjC,iFAAiF;AACjF,4DAA4D;AAC5D,mFAAmF;AACnF,kEAAkE;AAClE,gDAAgD;AAChD,+DAA+D;AAC/D,wFAAwF;AACxF,2EAA2E;AAC3E,oFAAoF;AACpF,EAAE;AACF,oFAAoF;AAEpF,OAAO,EAAE,yBAAyB,EAA4B,MAAM,gCAAgC,CAAC;AAErG,OAAO,EACL,YAAY,EACZ,gBAAgB,EAChB,UAAU,EACV,U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C3C,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;QACrB,CAAC;QACD,IAAI,CAAC,QAAQ,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,QAAQ,EAAE,EAAE,EAAE,CAAC,CAAC;IAChE,CAAC;CACF;AAED,SAAS,SAAS,CAAC,CAAgB,EAAE,CAAgB;IACnD,MAAM,EAAE,GAAG,OAAO,CAAC,CAAC,IAAI,EAAE,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAE,CAAC,CAAC,IAAI,CAAC,GAAc,CAAC,CAAC,CAAC,MAAM,CAAC,iBAAiB,CAAC;IAC/F,MAAM,EAAE,GAAG,OAAO,CAAC,CAAC,IAAI,EAAE,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAE,CAAC,CAAC,IAAI,CAAC,GAAc,CAAC,CAAC,CAAC,MAAM,CAAC,iBAAiB,CAAC;IAC/F,IAAI,EAAE,KAAK,EAAE;QAAE,OAAO,EAAE,GAAG,EAAE,CAAC;IAC9B,OAAO,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC,SAAS,CAAC;AACnC,CAAC","sourcesContent":["// The Channel realtime client: ONE WebSocket to a single channel DO, driving the\n// Contract C wire protocol. Framework-neutral (a plain observable store the React\n// hook subscribes to) so it is unit-testable with a mock socket and no React.\n//\n// Responsibilities (Contract C):\n// - connect via subprotocol auth (grant offered by the injected grantProvider)\n// - receive versioned `message` frames; server owns `seq`\n// - optimistic send keyed by clientMessageId, reconciled on the server `ack` seq\n// - explicit read acks (delivery != read; focus signals \"read\")\n// - typing (>= 2s coalesced per the V1 limit)\n// - presence-subscribe/-unsubscribe + a 20s client heartbeat\n// - reconnect (realtime-core controller) with a resume cursor -> snapshot then deltas\n// - history pagination over the socket (page <= 50, epoch-aware via seq)\n// - error codes incl. 4401 AUTH_EXPIRED -> re-mint a grant ONCE via grantProvider\n//\n// Timers are injected (setTimeout/clearTimeout/now) so tests run deterministically.\n\nimport { createReconnectController, type ReconnectController } from '@ttt-productions/realtime-core';\nimport type { ChatMessageV1 } from '@ttt-productions/chat-core';\nimport {\n CLIENT_FRAME,\n CHAT_CLOSE_CODES,\n buildFrame,\n parseFrame,\n isInboxSnapshot,\n type WireMessageRow,\n type WireChannelSnapshot,\n type RevisionKind,\n} from './wire.js';\nimport type { RealtimeSocket, SocketFactory } from './socket.js';\nimport {\n wireRowToMessage,\n optimisticMessage,\n seqToMessageId,\n applyModerationOverlay,\n overlayFromRow,\n type ModerationOverlay,\n} from './map.js';\nimport type { GrantProvider, TransportTimers, RealtimeStatus } from './shared.js';\nimport {\n defaultTimers,\n HEARTBEAT_MS,\n TYPING_COALESCE_MS,\n HISTORY_PAGE_MAX,\n MAX_PENDING_SEND_ATTEMPTS,\n PENDING_SEND_MAX_AGE_MS,\n} from './shared.js';\n\n/** An un-acked send tracked for reconnect resend (clientMessageId idempotency). */\ninterface PendingSend {\n clientMessageId: string;\n text: string;\n replyTo: { messageSeq: number; preview: string } | null;\n /** When the send was first attempted (for the age cap). Reset by retrySend(). */\n sentAt: number;\n /** How many times it has been (re)sent over a socket. Reset by retrySend(). */\n attempts: number;\n /** True once the attempt/age cap flipped this send to the visible failed state.\n * A failed entry is RETAINED (not deleted) so retrySend() can re-queue it with\n * the SAME clientMessageId; it is skipped by the automatic reconnect resend. */\n failed: boolean;\n}\n\nexport interface ChannelClientState {\n status: RealtimeStatus;\n /** Ordered ascending by seq; optimistic messages (no seq yet) sort to the tail. */\n messages: ChatMessageV1[];\n /** uids currently typing (cleared after ~TYPING_COALESCE_MS of silence). */\n typing: string[];\n /** uids the DO reports online (presence). Empty until presence-subscribe. */\n presence: string[];\n /** True while an older-history page request is in flight. */\n isFetchingOlder: boolean;\n /** False once a history page returns fewer than the requested limit (reached the head). */\n hasOlder: boolean;\n /** The last structured error code the DO sent (e.g. 'blocked-word', 'too-long', flood reason). */\n lastErrorCode: string | null;\n}\n\nexport interface ChannelClientConfig {\n /** WebSocket endpoint base, e.g. `wss://chat.ttt.productions`. The client appends `/channel`. */\n endpoint: string;\n /** The logical thread id the UI keys on (used as ChatMessageV1.threadId). */\n threadId: string;\n /** The authenticated uid (sender identity for optimistic echoes + auth-switch guard). */\n currentUserId: string;\n /** Mints/refreshes a channel grant. Called on connect and once on a 4401 re-grant. */\n grantProvider: GrantProvider;\n socketFactory: SocketFactory;\n timers?: TransportTimers;\n /** Reconnect backoff tuning (forwarded to realtime-core). */\n reconnect?: { baseDelayMs?: number; maxDelayMs?: number; maxAttempts?: number | null; random?: () => number };\n}\n\nconst INITIAL: ChannelClientState = {\n status: 'idle',\n messages: [],\n typing: [],\n presence: [],\n isFetchingOlder: false,\n hasOlder: true,\n lastErrorCode: null,\n};\n\n/**\n * Retryable error-frame code the channel DO sends when a send arrives BEFORE the\n * member row has synced through the async backend→worker pipeline (a just-created\n * invite/channel). The socket stays open; the client re-sends after `retryAfterMs`\n * through the normal resendPendingSends machinery (same caps). The string is part\n * of the wire contract with the worker runtime's send handler.\n */\nconst MEMBERSHIP_PENDING_CODE = 'membership-pending';\n/** Fallback retry delay when the frame omits/breaks `retryAfterMs`. */\nconst MEMBERSHIP_PENDING_DEFAULT_RETRY_MS = 2000;\n\nexport class ChannelClient {\n private readonly timers: TransportTimers;\n private readonly controller: ReconnectController;\n private socket: RealtimeSocket | null = null;\n private state: ChannelClientState = INITIAL;\n private readonly listeners = new Set<(s: ChannelClientState) => void>();\n\n /** Resume cursor: highest seq we've durably applied. Sent on resume after reconnect. */\n private resumeSeq = 0;\n /** Last read-ack the UI requested; re-sent on reconnect so a drop during a closed\n * socket window is recovered (M2). */\n private lastReadAck: { readSeq: number; focused: boolean } | null = null;\n /** True after a `4401` re-grant has been attempted for the CURRENT connect cycle (once-only). */\n private reauthAttempted = false;\n private presenceSubscribed = false;\n private heartbeatTimer: ReturnType<TransportTimers['setTimeout']> | null = null;\n private typingTimers = new Map<string, ReturnType<TransportTimers['setTimeout']>>();\n private lastTypingSentAt = Number.NEGATIVE_INFINITY;\n private reconnectTimer: ReturnType<TransportTimers['setTimeout']> | null = null;\n /** Single scheduled re-send for the membership-pending window (never stacks). */\n private membershipRetryTimer: ReturnType<TransportTimers['setTimeout']> | null = null;\n private closedByUs = false;\n /**\n * Per-seq moderation overlay (the max-revision wins). A `revision` frame writes\n * here keyed by `messageSeq` so it applies whether it arrives BEFORE its base\n * row (re-applied when the row later renders) or AFTER (re-renders the present\n * row in place). Merged with the row's own inline `moderationKind` so a row that\n * arrives already-moderated from the DO AND one covered by a live frame both\n * render the moderated state. */\n private overlays = new Map<number, ModerationOverlay>();\n /**\n * The ORIGINAL (un-overlaid) mapped message per seq. A `restore` revision must\n * revert a previously-redacted message to its original text, so re-renders start\n * from this cache rather than the (possibly already-blanked) message in state. */\n private originalRows = new Map<number, ChatMessageV1>();\n /**\n * Un-acked sends keyed by clientMessageId. A send is added here when its frame is\n * written and removed when its `ack` (or the canonical `message` echo carrying the\n * same clientMessageId) arrives. On every reconnect resume they are RE-SENT with\n * the SAME clientMessageId — the DO dedups (re-acks without re-broadcast), so a\n * send that lost its socket before the ack is delivered exactly once. A pending\n * send that exceeds the attempt/age cap is flipped to a visible failed state\n * (retry affordance) instead of staying a ghost. */\n private pendingSends = new Map<string, PendingSend>();\n\n constructor(private readonly config: ChannelClientConfig) {\n this.timers = config.timers ?? defaultTimers;\n this.controller = createReconnectController(config.reconnect ?? {});\n }\n\n // ---- observable store ----\n\n getState(): ChannelClientState {\n return this.state;\n }\n\n subscribe(fn: (s: ChannelClientState) => void): () => void {\n this.listeners.add(fn);\n return () => this.listeners.delete(fn);\n }\n\n private setState(patch: Partial<ChannelClientState>): void {\n this.state = { ...this.state, ...patch };\n for (const fn of this.listeners) fn(this.state);\n }\n\n // ---- connection lifecycle ----\n\n async connect(): Promise<void> {\n // Idempotency guard (C-B7): connect() only starts a lifecycle from a fresh\n // (idle) or fully torn-down (closed) state. A second connect() while one is\n // already connecting / open / reconnecting is a no-op, so a stray double-owner\n // can't open a second WebSocket. The reconnect path uses openSocket() /\n // scheduleReconnect() directly (never connect()), so this never blocks a\n // legitimate reconnect.\n if (this.state.status !== 'idle' && this.state.status !== 'closed') return;\n this.closedByUs = false;\n this.controller.start();\n this.setState({ status: 'connecting' });\n await this.openSocket();\n }\n\n private async openSocket(): Promise<void> {\n let grantToken: string;\n try {\n grantToken = await this.config.grantProvider();\n } catch {\n // Grant mint failed — treat as a closed attempt and back off.\n return this.scheduleReconnect();\n }\n if (this.closedByUs) return;\n const url = `${this.config.endpoint.replace(/\\/$/, '')}/channel`;\n this.socket = this.config.socketFactory({\n url,\n grantToken,\n handlers: {\n onOpen: () => this.onOpen(),\n onMessage: (data) => this.onMessage(data),\n onClose: (code, reason) => this.onClose(code, reason),\n onError: () => this.onError(),\n },\n });\n }\n\n private onOpen(): void {\n this.controller.onOpen();\n this.reauthAttempted = false;\n this.setState({ status: 'open' });\n // Resume: ask the DO for the authoritative snapshot, then live deltas flow. The\n // field name MUST be `afterSeq` — the Channel DO reads `payload.afterSeq`; any other\n // name reads as cursorless and forces a full resync every reconnect.\n this.sendFrame(CLIENT_FRAME.RESUME, { afterSeq: this.resumeSeq });\n // If the UI had presence open, re-subscribe after a reconnect.\n if (this.presenceSubscribed) this.sendFrame(CLIENT_FRAME.PRESENCE_SUBSCRIBE, {});\n // Re-send the last read cursor so a read-ack dropped during the disconnect window\n // (sendFrame returns false on a closed socket) is not lost until the next message.\n if (this.lastReadAck) this.sendFrame(CLIENT_FRAME.READ_ACK, { ...this.lastReadAck });\n // Re-send every un-acked pending send with its ORIGINAL clientMessageId so a send\n // that lost its socket before the ack is not silently dropped. The DO dedups\n // (re-acks, no re-broadcast, no flood-token) — this is the client half of the\n // Contract C send-idempotency the server side was built for.\n this.resendPendingSends();\n this.startHeartbeat();\n }\n\n /**\n * On reconnect, re-send each un-acked pending send with the SAME clientMessageId\n * (the DO dedups). A send that has exceeded the attempt or age cap is flipped to a\n * visible failed state instead of being resent forever — the ghost becomes a\n * retryable failure the UI can surface.\n */\n private resendPendingSends(): void {\n if (this.pendingSends.size === 0) return;\n const now = this.timers.now();\n for (const pending of [...this.pendingSends.values()]) {\n // Already flipped to the visible failed state — only an explicit retrySend()\n // re-queues it; the automatic reconnect resend leaves it alone.\n if (pending.failed) continue;\n const tooOld = now - pending.sentAt >= PENDING_SEND_MAX_AGE_MS;\n const tooManyAttempts = pending.attempts >= MAX_PENDING_SEND_ATTEMPTS;\n if (tooOld || tooManyAttempts) {\n this.failPendingSend(pending.clientMessageId);\n continue;\n }\n const sent = this.sendFrame(CLIENT_FRAME.SEND, {\n clientMessageId: pending.clientMessageId,\n text: pending.text,\n replyTo: pending.replyTo,\n });\n if (sent) pending.attempts += 1;\n }\n }\n\n /**\n * Flip an un-acked optimistic row to a visible failed state. The pending entry is\n * RETAINED (marked `failed`) so retrySend() can re-queue it with the SAME\n * clientMessageId; the row is marked `meta.sendFailed` so the default renderer\n * shows a failure with a retry affordance rather than an indistinguishable\n * \"sent\" bubble. A late ack/echo still reconciles + clears it.\n */\n private failPendingSend(clientMessageId: string): void {\n const pending = this.pendingSends.get(clientMessageId);\n if (!pending || pending.failed) return;\n pending.failed = true;\n const next = this.state.messages.map((m) =>\n m.meta?.optimistic && m.meta?.clientMessageId === clientMessageId\n ? { ...m, meta: { ...m.meta, sendFailed: true } }\n : m,\n );\n this.setState({ messages: next, lastErrorCode: 'send-failed' });\n }\n\n /** One timer for the membership-pending re-send window; a newer frame resets it. */\n private scheduleMembershipPendingRetry(delayMs: number): void {\n if (this.membershipRetryTimer != null) this.timers.clearTimeout(this.membershipRetryTimer);\n this.membershipRetryTimer = this.timers.setTimeout(() => {\n this.membershipRetryTimer = null;\n if (this.closedByUs) return;\n this.resendPendingSends();\n }, delayMs);\n }\n\n /**\n * Flip EVERY un-acked pending send to the visible failed state. Called on the\n * terminal close paths (4403 REVOKED, reconnect give-up) — without this, a send\n * in flight when the socket dies for good shows \"Sending…\" until unmount.\n */\n private failAllPendingSends(): void {\n for (const clientMessageId of [...this.pendingSends.keys()]) {\n this.failPendingSend(clientMessageId);\n }\n }\n\n /**\n * Retry a FAILED (or still-pending) send, RE-USING its original clientMessageId\n * so the DO's send-idempotency dedups against any copy that actually landed.\n * Resets the attempt/age budget, clears the row's `sendFailed` marker (back to\n * the normal pending/optimistic look), and re-sends immediately when the socket\n * is open — otherwise the entry rides the next reconnect's automatic resend.\n * Returns false when the clientMessageId is not a tracked pending send (already\n * acked/reconciled, or never sent from this client).\n */\n retrySend(clientMessageId: string): boolean {\n const pending = this.pendingSends.get(clientMessageId);\n if (!pending) return false;\n pending.failed = false;\n pending.sentAt = this.timers.now();\n const sent = this.sendFrame(CLIENT_FRAME.SEND, {\n clientMessageId: pending.clientMessageId,\n text: pending.text,\n replyTo: pending.replyTo,\n });\n pending.attempts = sent ? 1 : 0;\n const next = this.state.messages.map((m) =>\n m.meta?.optimistic && m.meta?.clientMessageId === clientMessageId && m.meta?.sendFailed\n ? { ...m, meta: { ...m.meta, sendFailed: false } }\n : m,\n );\n this.setState({ messages: next, lastErrorCode: null });\n return true;\n }\n\n private onError(): void {\n // The close handler does the backoff; onerror is advisory in browsers.\n }\n\n private onClose(code: number, _reason: string): void {\n this.stopHeartbeat();\n this.socket = null;\n if (this.closedByUs) {\n this.setState({ status: 'closed' });\n return;\n }\n // 4401 AUTH_EXPIRED: re-mint a grant ONCE and reconnect immediately, no backoff.\n if (code === CHAT_CLOSE_CODES.AUTH_EXPIRED && !this.reauthAttempted) {\n this.reauthAttempted = true;\n this.setState({ status: 'reconnecting' });\n void this.openSocket();\n return;\n }\n // 4403 REVOKED: access pulled. Stop — a reconnect would just re-deny at mint.\n // Terminal: flip every un-acked pending send to the visible failed state first\n // (failPendingSend sets lastErrorCode 'send-failed'; the 'revoked' set below\n // wins as the final surfaced code).\n if (code === CHAT_CLOSE_CODES.REVOKED) {\n this.closedByUs = true;\n this.controller.close();\n this.failAllPendingSends();\n this.setState({ status: 'closed', lastErrorCode: 'revoked' });\n return;\n }\n this.scheduleReconnect();\n }\n\n private scheduleReconnect(): void {\n const delay = this.controller.onClose();\n if (delay == null) {\n // Reconnect give-up: terminal, same as REVOKED — pending sends must not stay\n // an eternal \"Sending…\"; flip them to the visible failed/retry state.\n this.failAllPendingSends();\n this.setState({ status: 'closed' });\n return;\n }\n this.setState({ status: 'reconnecting' });\n this.reconnectTimer = this.timers.setTimeout(() => {\n this.reconnectTimer = null;\n if (this.closedByUs) return;\n void this.openSocket();\n }, delay);\n }\n\n // ---- inbound frames ----\n\n private onMessage(data: string): void {\n const frame = parseFrame(data);\n if (!frame || !frame.type) return;\n const payload = frame.payload ?? {};\n switch (frame.type) {\n case 'message':\n return this.applyMessage((payload as { message: WireMessageRow }).message);\n case 'ack':\n return this.applyAck(payload as { clientMessageId?: string; seq?: number; readSeq?: number });\n case 'history-page':\n return this.applyHistoryPage((payload as { messages: WireMessageRow[] }).messages ?? []);\n case 'presence':\n return this.setState({ presence: (payload as { online: string[] }).online ?? [] });\n case 'typing':\n return this.applyTyping((payload as { uid: string }).uid);\n case 'snapshot':\n return this.applyChannelSnapshot(payload as unknown as WireChannelSnapshot);\n case 'error': {\n const code = String((payload as { code?: unknown }).code ?? 'error');\n // Retryable: membership row not yet synced to the DO. Keep the send pending\n // (no visible error — the optimistic bubble stays \"Sending…\") and re-send\n // after the server-suggested delay via the normal resend machinery, whose\n // attempt/age caps flip it to the visible failed state if the window never\n // closes. Everything else surfaces as before.\n if (code === MEMBERSHIP_PENDING_CODE) {\n const raw = (payload as { retryAfterMs?: unknown }).retryAfterMs;\n const delay = typeof raw === 'number' && raw > 0 ? raw : MEMBERSHIP_PENDING_DEFAULT_RETRY_MS;\n return this.scheduleMembershipPendingRetry(delay);\n }\n return this.setState({ lastErrorCode: code });\n }\n case 'revision':\n return this.applyRevisionFrame(payload as { messageSeq?: number; kind?: RevisionKind; messageRevision?: number });\n default:\n return; // unknown/optional types tolerated (forward compat)\n }\n }\n\n /**\n * Apply a live moderation `revision` frame: record the overlay keyed by seq\n * (max-`messageRevision` wins — a stale/older frame is ignored) and re-render the\n * matching message in place if it is already loaded. If the base row hasn't\n * arrived yet the overlay is retained and re-applied when the row renders, so a\n * frame that races ahead of its message never lets the original content show.\n */\n private applyRevisionFrame(payload: { messageSeq?: number; kind?: RevisionKind; messageRevision?: number }): void {\n const seq = payload.messageSeq;\n const kind = payload.kind;\n const messageRevision = payload.messageRevision;\n if (typeof seq !== 'number' || kind == null || typeof messageRevision !== 'number') return;\n const prev = this.overlays.get(seq);\n // Max-revision merge: a higher messageRevision supersedes; an older one is dropped.\n if (prev && prev.messageRevision >= messageRevision) return;\n this.overlays.set(seq, { kind, messageRevision });\n // Re-render the matching message in place if it is already present. Re-derive\n // from the ORIGINAL row so a `restore` reverts a previously-blanked text.\n const messageId = seqToMessageId(seq);\n const original = this.originalRows.get(seq);\n if (original && this.state.messages.some((m) => m.messageId === messageId)) {\n const overlaid = applyModerationOverlay(original, this.effectiveOverlay(seq, null));\n const next = this.state.messages.map((m) => (m.messageId === messageId ? overlaid : m));\n this.setState({ messages: next });\n }\n }\n\n /**\n * The effective overlay for a seq = the max-`messageRevision` between the row's\n * own inline overlay (from the DO history/delta merge) and any received `revision`\n * frame stored in `this.overlays`. Either source may be ahead of the other.\n */\n private effectiveOverlay(seq: number, rowOverlay: ModerationOverlay | null): ModerationOverlay | null {\n const fromFrame = this.overlays.get(seq) ?? null;\n if (!rowOverlay) return fromFrame;\n if (!fromFrame) return rowOverlay;\n return fromFrame.messageRevision >= rowOverlay.messageRevision ? fromFrame : rowOverlay;\n }\n\n /** Map a DO row to a UI message with its effective moderation overlay applied. */\n private renderRow(row: WireMessageRow): ChatMessageV1 {\n const mapped = wireRowToMessage(row, this.config.threadId);\n // Cache the ORIGINAL so a later `restore` frame can revert a blanked message.\n this.originalRows.set(row.seq, mapped);\n return applyModerationOverlay(mapped, this.effectiveOverlay(row.seq, overlayFromRow(row)));\n }\n\n /**\n * Apply the Contract C resume snapshot. The DO always returns the authoritative\n * tail + read cursor and, per the pinned contract, EITHER a contiguous delta\n * (`resync:false`) OR a resync directive (`resync:true`).\n *\n * - `resync === false`: apply the contiguous `delta` (the ≤500-message backlog\n * after our cursor, oldest-first) through the same render/merge path as a live\n * `message`, then advance `resumeSeq` to `lastMessageSeq`. This heals ANY gap\n * within the backlog — including moderation `revision`s the DO baked into the\n * delta rows — with no history fetch, so a >50-message reconnect gap is no\n * longer a permanent hole.\n * - `resync === true`: the gap is beyond the backlog (or we sent no cursor). Drop\n * the local tail (messages + overlays + original-row cache) and re-page history\n * from the top via a cursorless `requestHistory(null)`.\n *\n * A pre-contract DO (no `resync`/`delta`) is treated as `resync:true` ⇒ the safe\n * re-page path, so a stale worker never strands the client. An empty delta with\n * `resync:false` (already caught up) is a no-op beyond advancing the cursor.\n */\n private applyChannelSnapshot(snap: WireChannelSnapshot): void {\n // Guard: an inbox snapshot must never reach a channel client.\n if (isInboxSnapshot(snap as never)) return;\n if (typeof snap.lastMessageSeq !== 'number') return;\n\n // Absent `resync` (legacy/pre-contract DO) is treated as a resync directive.\n const resync = snap.resync !== false;\n\n if (!resync) {\n // Apply the contiguous delta oldest-first, exactly like live messages, then\n // advance the cursor to the authoritative tail so the NEXT resume tells the DO\n // we're caught up only after we actually applied the backlog.\n const delta = Array.isArray(snap.delta) ? snap.delta : [];\n for (const row of delta) this.applyMessage(row);\n if (snap.lastMessageSeq > this.resumeSeq) this.resumeSeq = snap.lastMessageSeq;\n return;\n }\n\n // Resync: drop the local tail and re-page from the top per the pinned contract.\n // Clear the derived caches too so a stale overlay/original-row can't resurrect a\n // message the re-page will reload fresh (with its baked-in moderation state).\n // KEEP un-acked optimistic rows — they aren't server history yet; their pending\n // sends were already re-sent in onOpen and reconcile when the DO echoes them.\n this.overlays.clear();\n this.originalRows.clear();\n this.resumeSeq = 0;\n const keptOptimistic = this.state.messages.filter((m) => m.meta?.optimistic);\n this.setState({ messages: keptOptimistic, hasOlder: true, isFetchingOlder: false });\n this.requestHistory(null);\n }\n\n private applyMessage(row: WireMessageRow): void {\n if (!row || typeof row.seq !== 'number') return;\n const mapped = this.renderRow(row);\n this.mergeMessage(mapped, row);\n if (row.seq > this.resumeSeq) this.resumeSeq = row.seq;\n }\n\n /**\n * Merge a server message: reconcile an optimistic echo by clientMessageId (swap\n * the `optimistic:` row for the canonical seq row), or insert/replace by seq.\n * Keeps the list sorted ascending by seq with optimistic rows at the tail.\n */\n private mergeMessage(mapped: ChatMessageV1, row: WireMessageRow): void {\n // If this canonical row carries a clientMessageId we still have pending (the\n // sender's own broadcast, or a resume delta that included our send), the send\n // landed — stop tracking it for reconnect resend.\n if (row.clientMessageId) this.pendingSends.delete(row.clientMessageId);\n const next = this.state.messages.filter(\n (m) =>\n m.messageId !== mapped.messageId &&\n // drop the optimistic placeholder this server row reconciles\n (m.meta?.clientMessageId !== row.clientMessageId || !m.meta?.optimistic),\n );\n next.push(mapped);\n next.sort(sortBySeq);\n this.setState({ messages: next });\n }\n\n private applyAck(payload: { clientMessageId?: string; seq?: number; readSeq?: number }): void {\n // A read-ack echo carries readSeq only — nothing to reconcile locally.\n if (payload.clientMessageId == null || typeof payload.seq !== 'number') return;\n // Reconcile the optimistic echo: stamp the server seq onto it. The canonical\n // `message` broadcast (which the sender also receives) replaces it fully; this\n // ack guarantees the seq even if the broadcast is dropped/reordered.\n const seq = payload.seq;\n const cmid = payload.clientMessageId;\n // The send is acked — stop tracking it for reconnect resend.\n this.pendingSends.delete(cmid);\n const next = this.state.messages.map((m) => {\n if (!m.meta?.optimistic || m.meta?.clientMessageId !== cmid) return m;\n // Strip any failed marker — a late ack (e.g. a retry raced the cap) means the\n // send actually landed, so the row must render as delivered, not failed.\n const { sendFailed: _sendFailed, ...restMeta } = m.meta;\n return { ...m, messageId: seqToMessageId(seq), meta: { ...restMeta, optimistic: false, seq } };\n });\n next.sort(sortBySeq);\n if (seq > this.resumeSeq) this.resumeSeq = seq;\n this.setState({ messages: next });\n }\n\n private applyHistoryPage(rows: WireMessageRow[]): void {\n const mapped = rows.map((r) => this.renderRow(r));\n // Mirror mergeMessage's optimistic reconciliation: a history row carrying a\n // clientMessageId we still hold as an optimistic placeholder IS that send (the\n // DO stored it; the ack was lost). Drop the placeholder — keyed `optimistic:{cmid}`,\n // it would otherwise survive alongside its seq-keyed server row as a duplicate\n // bubble after a resync + re-page — and stop tracking it for resend.\n const incomingCmids = new Set<string>();\n for (const r of rows) {\n if (r.clientMessageId) {\n incomingCmids.add(r.clientMessageId);\n this.pendingSends.delete(r.clientMessageId);\n }\n }\n const bySeq = new Map<string, ChatMessageV1>();\n for (const m of this.state.messages) {\n if (m.meta?.optimistic && typeof m.meta?.clientMessageId === 'string' && incomingCmids.has(m.meta.clientMessageId)) {\n continue; // reconciled by the incoming server row\n }\n bySeq.set(m.messageId, m);\n }\n for (const m of mapped) bySeq.set(m.messageId, m);\n const merged = [...bySeq.values()].sort(sortBySeq);\n for (const r of rows) if (r.seq > this.resumeSeq) this.resumeSeq = r.seq;\n this.setState({\n messages: merged,\n isFetchingOlder: false,\n hasOlder: rows.length >= HISTORY_PAGE_MAX,\n });\n }\n\n private applyTyping(uid: string): void {\n if (!uid || uid === this.config.currentUserId) return;\n if (!this.state.typing.includes(uid)) this.setState({ typing: [...this.state.typing, uid] });\n const prev = this.typingTimers.get(uid);\n if (prev) this.timers.clearTimeout(prev);\n this.typingTimers.set(\n uid,\n this.timers.setTimeout(() => {\n this.typingTimers.delete(uid);\n this.setState({ typing: this.state.typing.filter((u) => u !== uid) });\n }, TYPING_COALESCE_MS * 2),\n );\n }\n\n // ---- outbound actions ----\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 /**\n * Optimistic send: render the echo immediately keyed by clientMessageId, then\n * emit the `send` frame. The server `ack`/`message` reconciles on the seq.\n */\n send(args: { clientMessageId: string; text: string; replyTo?: { messageSeq: number; preview: string } | null }): boolean {\n // C-B8: write the frame FIRST and render the optimistic echo ONLY if it was\n // actually sent over an open socket. A closed socket returns false — no phantom\n // \"sent\" bubble, and the caller keeps the composer text — so a disconnect between\n // render and click can't silently swallow the message.\n const sent = this.sendFrame(CLIENT_FRAME.SEND, {\n clientMessageId: args.clientMessageId,\n text: args.text,\n replyTo: args.replyTo ?? null,\n });\n if (!sent) {\n this.setState({ lastErrorCode: 'send-failed' });\n return false;\n }\n const now = this.timers.now();\n // Track the un-acked send so a reconnect re-sends it with the same\n // clientMessageId (the DO dedups) — until the ack/echo clears it.\n this.pendingSends.set(args.clientMessageId, {\n clientMessageId: args.clientMessageId,\n text: args.text,\n replyTo: args.replyTo ?? null,\n sentAt: now,\n attempts: 1,\n failed: false,\n });\n const echo = optimisticMessage({\n clientMessageId: args.clientMessageId,\n threadId: this.config.threadId,\n senderId: this.config.currentUserId,\n text: args.text,\n createdAt: now,\n replyTo: args.replyTo ? { messageId: seqToMessageId(args.replyTo.messageSeq), messagePreview: args.replyTo.preview } : null,\n });\n const next = [...this.state.messages, echo].sort(sortBySeq);\n this.setState({ messages: next, lastErrorCode: null });\n return true;\n }\n\n /**\n * Explicit read ack (delivery != read). `focused` => the channel is open + at latest.\n * Remembers the cursor (re-sent on reconnect) and returns whether the frame was\n * actually sent over an open socket, so the caller only advances its local\n * already-acked marker on a real send (M2).\n */\n readAck(readSeq: number, focused: boolean): boolean {\n this.lastReadAck = { readSeq, focused };\n return this.sendFrame(CLIENT_FRAME.READ_ACK, { readSeq, focused });\n }\n\n /** Coalesced typing signal: at most one frame per TYPING_COALESCE_MS. */\n typing(): void {\n const now = this.timers.now();\n if (now - this.lastTypingSentAt < TYPING_COALESCE_MS) return;\n this.lastTypingSentAt = now;\n this.sendFrame(CLIENT_FRAME.TYPING, {});\n }\n\n presenceSubscribe(): void {\n this.presenceSubscribed = true;\n this.sendFrame(CLIENT_FRAME.PRESENCE_SUBSCRIBE, {});\n }\n\n presenceUnsubscribe(): void {\n this.presenceSubscribed = false;\n this.sendFrame(CLIENT_FRAME.PRESENCE_UNSUBSCRIBE, {});\n this.setState({ presence: [] });\n }\n\n /** Fetch the page of history older than the oldest loaded message (epoch-aware by seq). */\n fetchOlder(): void {\n if (this.state.isFetchingOlder || !this.state.hasOlder) return;\n const oldest = this.state.messages.find((m) => typeof m.meta?.seq === 'number');\n const beforeSeq = oldest && typeof oldest.meta?.seq === 'number' ? (oldest.meta.seq as number) : null;\n this.setState({ isFetchingOlder: true });\n this.requestHistory(beforeSeq);\n }\n\n private requestHistory(beforeSeq: number | null): void {\n this.sendFrame(CLIENT_FRAME.HISTORY, { beforeSeq, limit: HISTORY_PAGE_MAX });\n }\n\n // ---- heartbeat (20s) ----\n\n private startHeartbeat(): void {\n this.stopHeartbeat();\n const tick = () => {\n if (!this.socket || !this.socket.isOpen) return;\n this.sendFrame(CLIENT_FRAME.HEARTBEAT, {});\n this.heartbeatTimer = this.timers.setTimeout(tick, HEARTBEAT_MS);\n };\n this.heartbeatTimer = this.timers.setTimeout(tick, HEARTBEAT_MS);\n }\n\n private stopHeartbeat(): void {\n if (this.heartbeatTimer != null) {\n this.timers.clearTimeout(this.heartbeatTimer);\n this.heartbeatTimer = null;\n }\n }\n\n // ---- teardown ----\n\n /** Permanently close this client (auth-user switch / unmount). Idempotent. */\n close(): void {\n this.closedByUs = true;\n this.controller.close();\n this.stopHeartbeat();\n for (const t of this.typingTimers.values()) this.timers.clearTimeout(t);\n this.typingTimers.clear();\n this.overlays.clear();\n this.originalRows.clear();\n this.pendingSends.clear();\n if (this.reconnectTimer != null) {\n this.timers.clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n if (this.membershipRetryTimer != null) {\n this.timers.clearTimeout(this.membershipRetryTimer);\n this.membershipRetryTimer = null;\n }\n if (this.socket) {\n this.socket.close(1000, 'client teardown');\n this.socket = null;\n }\n this.setState({ status: 'closed', typing: [], presence: [] });\n }\n}\n\nfunction sortBySeq(a: ChatMessageV1, b: ChatMessageV1): number {\n const sa = typeof a.meta?.seq === 'number' ? (a.meta.seq as number) : Number.POSITIVE_INFINITY;\n const sb = typeof b.meta?.seq === 'number' ? (b.meta.seq as number) : Number.POSITIVE_INFINITY;\n if (sa !== sb) return sa - sb;\n return a.createdAt - b.createdAt;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"channel-client.js","sourceRoot":"","sources":["../../src/realtime/channel-client.ts"],"names":[],"mappings":"AAAA,iFAAiF;AACjF,kFAAkF;AAClF,8EAA8E;AAC9E,EAAE;AACF,iCAAiC;AACjC,iFAAiF;AACjF,4DAA4D;AAC5D,mFAAmF;AACnF,kEAAkE;AAClE,gDAAgD;AAChD,+DAA+D;AAC/D,wFAAwF;AACxF,2EAA2E;AAC3E,oFAAoF;AACpF,EAAE;AACF,oFAAoF;AAEpF,OAAO,EAAE,yBAAyB,EAA4B,MAAM,gCAAgC,CAAC;AAErG,OAAO,EACL,YAAY,EACZ,gBAAgB,EAChB,UAAU,EACV,UAAU,EACV,eAAe,GAIhB,MAAM,WAAW,CAAC;AAEnB,OAAO,EACL,gBAAgB,EAChB,iBAAiB,EACjB,cAAc,EACd,sBAAsB,EACtB,cAAc,GAEf,MAAM,UAAU,CAAC;AAElB,OAAO,EACL,aAAa,EACb,uBAAuB,EACvB,YAAY,EACZ,kBAAkB,EAClB,gBAAgB,EAChB,yBAAyB,EACzB,uBAAuB,GACxB,MAAM,aAAa,CAAC;AA2DrB,MAAM,OAAO,GAAuB;IAClC,MAAM,EAAE,MAAM;IACd,QAAQ,EAAE,EAAE;IACZ,MAAM,EAAE,EAAE;IACV,QAAQ,EAAE,EAAE;IACZ,eAAe,EAAE,KAAK;IACtB,QAAQ,EAAE,IAAI;IACd,aAAa,EAAE,IAAI;IACnB,oBAAoB,EAAE,KAAK;CAC5B,CAAC;AAEF;;;;;;GAMG;AACH,MAAM,uBAAuB,GAAG,oBAAoB,CAAC;AACrD,uEAAuE;AACvE,MAAM,mCAAmC,GAAG,IAAI,CAAC;AAEjD,MAAM,OAAO,aAAa;IA6CK;IA5CZ,MAAM,CAAkB;IACxB,UAA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C,KAAK,CAAC,IAAI,EAAE,iBAAiB,CAAC,CAAC;YAC3C,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;QACrB,CAAC;QACD,IAAI,CAAC,QAAQ,CAAC,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,EAAE,EAAE,QAAQ,EAAE,EAAE,EAAE,CAAC,CAAC;IAChE,CAAC;CACF;AAED,SAAS,SAAS,CAAC,CAAgB,EAAE,CAAgB;IACnD,MAAM,EAAE,GAAG,OAAO,CAAC,CAAC,IAAI,EAAE,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAE,CAAC,CAAC,IAAI,CAAC,GAAc,CAAC,CAAC,CAAC,MAAM,CAAC,iBAAiB,CAAC;IAC/F,MAAM,EAAE,GAAG,OAAO,CAAC,CAAC,IAAI,EAAE,GAAG,KAAK,QAAQ,CAAC,CAAC,CAAE,CAAC,CAAC,IAAI,CAAC,GAAc,CAAC,CAAC,CAAC,MAAM,CAAC,iBAAiB,CAAC;IAC/F,IAAI,EAAE,KAAK,EAAE;QAAE,OAAO,EAAE,GAAG,EAAE,CAAC;IAC9B,OAAO,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC,SAAS,CAAC;AACnC,CAAC","sourcesContent":["// The Channel realtime client: ONE WebSocket to a single channel DO, driving the\n// Contract C wire protocol. Framework-neutral (a plain observable store the React\n// hook subscribes to) so it is unit-testable with a mock socket and no React.\n//\n// Responsibilities (Contract C):\n// - connect via subprotocol auth (grant offered by the injected grantProvider)\n// - receive versioned `message` frames; server owns `seq`\n// - optimistic send keyed by clientMessageId, reconciled on the server `ack` seq\n// - explicit read acks (delivery != read; focus signals \"read\")\n// - typing (>= 2s coalesced per the V1 limit)\n// - presence-subscribe/-unsubscribe + a 20s client heartbeat\n// - reconnect (realtime-core controller) with a resume cursor -> snapshot then deltas\n// - history pagination over the socket (page <= 50, epoch-aware via seq)\n// - error codes incl. 4401 AUTH_EXPIRED -> re-mint a grant ONCE via grantProvider\n//\n// Timers are injected (setTimeout/clearTimeout/now) so tests run deterministically.\n\nimport { createReconnectController, type ReconnectController } from '@ttt-productions/realtime-core';\nimport type { ChatMessageV1 } from '@ttt-productions/chat-core';\nimport {\n CLIENT_FRAME,\n CHAT_CLOSE_CODES,\n buildFrame,\n parseFrame,\n isInboxSnapshot,\n type WireMessageRow,\n type WireChannelSnapshot,\n type RevisionKind,\n} from './wire.js';\nimport type { RealtimeSocket, SocketFactory } from './socket.js';\nimport {\n wireRowToMessage,\n optimisticMessage,\n seqToMessageId,\n applyModerationOverlay,\n overlayFromRow,\n type ModerationOverlay,\n} from './map.js';\nimport type { GrantProvider, TransportTimers, RealtimeStatus } from './shared.js';\nimport {\n defaultTimers,\n isChatAccessDeniedError,\n HEARTBEAT_MS,\n TYPING_COALESCE_MS,\n HISTORY_PAGE_MAX,\n MAX_PENDING_SEND_ATTEMPTS,\n PENDING_SEND_MAX_AGE_MS,\n} from './shared.js';\n\n/** An un-acked send tracked for reconnect resend (clientMessageId idempotency). */\ninterface PendingSend {\n clientMessageId: string;\n text: string;\n replyTo: { messageSeq: number; preview: string } | null;\n /** When the send was first attempted (for the age cap). Reset by retrySend(). */\n sentAt: number;\n /** How many times it has been (re)sent over a socket. Reset by retrySend(). */\n attempts: number;\n /** True once the attempt/age cap flipped this send to the visible failed state.\n * A failed entry is RETAINED (not deleted) so retrySend() can re-queue it with\n * the SAME clientMessageId; it is skipped by the automatic reconnect resend. */\n failed: boolean;\n}\n\nexport interface ChannelClientState {\n status: RealtimeStatus;\n /** Ordered ascending by seq; optimistic messages (no seq yet) sort to the tail. */\n messages: ChatMessageV1[];\n /** uids currently typing (cleared after ~TYPING_COALESCE_MS of silence). */\n typing: string[];\n /** uids the DO reports online (presence). Empty until presence-subscribe. */\n presence: string[];\n /** True while an older-history page request is in flight. */\n isFetchingOlder: boolean;\n /** False once a history page returns fewer than the requested limit (reached the head). */\n hasOlder: boolean;\n /** The last structured error code the DO sent (e.g. 'blocked-word', 'too-long', flood reason). */\n lastErrorCode: string | null;\n /**\n * True once the FIRST authoritative chat data has been applied — a non-resync\n * resume snapshot, OR the first history page (INCLUDING an empty one). Drives the\n * hook's `isInitialLoading` so the shell shows an honest \"Opening chat…\" state\n * while the first data is loading, and a real empty-chat surface only after an\n * authoritative empty result. NEVER inferred from `messages.length === 0` (an\n * empty first history page IS a successful load). Once true it stays true — a\n * later disconnect/reconnect keeps loaded messages mounted, not a re-loader.\n * A grant retry / socket open before any snapshot leaves it false.\n */\n hasLoadedInitialData: boolean;\n}\n\nexport interface ChannelClientConfig {\n /** WebSocket endpoint base, e.g. `wss://chat.ttt.productions`. The client appends `/channel`. */\n endpoint: string;\n /** The logical thread id the UI keys on (used as ChatMessageV1.threadId). */\n threadId: string;\n /** The authenticated uid (sender identity for optimistic echoes + auth-switch guard). */\n currentUserId: string;\n /** Mints/refreshes a channel grant. Called on connect and once on a 4401 re-grant. */\n grantProvider: GrantProvider;\n socketFactory: SocketFactory;\n timers?: TransportTimers;\n /** Reconnect backoff tuning (forwarded to realtime-core). */\n reconnect?: { baseDelayMs?: number; maxDelayMs?: number; maxAttempts?: number | null; random?: () => number };\n}\n\nconst INITIAL: ChannelClientState = {\n status: 'idle',\n messages: [],\n typing: [],\n presence: [],\n isFetchingOlder: false,\n hasOlder: true,\n lastErrorCode: null,\n hasLoadedInitialData: false,\n};\n\n/**\n * Retryable error-frame code the channel DO sends when a send arrives BEFORE the\n * member row has synced through the async backend→worker pipeline (a just-created\n * invite/channel). The socket stays open; the client re-sends after `retryAfterMs`\n * through the normal resendPendingSends machinery (same caps). The string is part\n * of the wire contract with the worker runtime's send handler.\n */\nconst MEMBERSHIP_PENDING_CODE = 'membership-pending';\n/** Fallback retry delay when the frame omits/breaks `retryAfterMs`. */\nconst MEMBERSHIP_PENDING_DEFAULT_RETRY_MS = 2000;\n\nexport class ChannelClient {\n private readonly timers: TransportTimers;\n private readonly controller: ReconnectController;\n private socket: RealtimeSocket | null = null;\n private state: ChannelClientState = INITIAL;\n private readonly listeners = new Set<(s: ChannelClientState) => void>();\n\n /** Resume cursor: highest seq we've durably applied. Sent on resume after reconnect. */\n private resumeSeq = 0;\n /** Last read-ack the UI requested; re-sent on reconnect so a drop during a closed\n * socket window is recovered (M2). */\n private lastReadAck: { readSeq: number; focused: boolean } | null = null;\n /** True after a `4401` re-grant has been attempted for the CURRENT connect cycle (once-only). */\n private reauthAttempted = false;\n private presenceSubscribed = false;\n private heartbeatTimer: ReturnType<TransportTimers['setTimeout']> | null = null;\n private typingTimers = new Map<string, ReturnType<TransportTimers['setTimeout']>>();\n private lastTypingSentAt = Number.NEGATIVE_INFINITY;\n private reconnectTimer: ReturnType<TransportTimers['setTimeout']> | null = null;\n /** Single scheduled re-send for the membership-pending window (never stacks). */\n private membershipRetryTimer: ReturnType<TransportTimers['setTimeout']> | null = null;\n private closedByUs = false;\n /**\n * Per-seq moderation overlay (the max-revision wins). A `revision` frame writes\n * here keyed by `messageSeq` so it applies whether it arrives BEFORE its base\n * row (re-applied when the row later renders) or AFTER (re-renders the present\n * row in place). Merged with the row's own inline `moderationKind` so a row that\n * arrives already-moderated from the DO AND one covered by a live frame both\n * render the moderated state. */\n private overlays = new Map<number, ModerationOverlay>();\n /**\n * The ORIGINAL (un-overlaid) mapped message per seq. A `restore` revision must\n * revert a previously-redacted message to its original text, so re-renders start\n * from this cache rather than the (possibly already-blanked) message in state. */\n private originalRows = new Map<number, ChatMessageV1>();\n /**\n * Un-acked sends keyed by clientMessageId. A send is added here when its frame is\n * written and removed when its `ack` (or the canonical `message` echo carrying the\n * same clientMessageId) arrives. On every reconnect resume they are RE-SENT with\n * the SAME clientMessageId — the DO dedups (re-acks without re-broadcast), so a\n * send that lost its socket before the ack is delivered exactly once. A pending\n * send that exceeds the attempt/age cap is flipped to a visible failed state\n * (retry affordance) instead of staying a ghost. */\n private pendingSends = new Map<string, PendingSend>();\n\n constructor(private readonly config: ChannelClientConfig) {\n this.timers = config.timers ?? defaultTimers;\n this.controller = createReconnectController(config.reconnect ?? {});\n }\n\n // ---- observable store ----\n\n getState(): ChannelClientState {\n return this.state;\n }\n\n subscribe(fn: (s: ChannelClientState) => void): () => void {\n this.listeners.add(fn);\n return () => this.listeners.delete(fn);\n }\n\n private setState(patch: Partial<ChannelClientState>): void {\n this.state = { ...this.state, ...patch };\n for (const fn of this.listeners) fn(this.state);\n }\n\n // ---- connection lifecycle ----\n\n async connect(): Promise<void> {\n // Idempotency guard (C-B7): connect() only starts a lifecycle from a fresh\n // (idle) or fully torn-down (closed) state. A second connect() while one is\n // already connecting / open / reconnecting is a no-op, so a stray double-owner\n // can't open a second WebSocket. The reconnect path uses openSocket() /\n // scheduleReconnect() directly (never connect()), so this never blocks a\n // legitimate reconnect.\n if (this.state.status !== 'idle' && this.state.status !== 'closed') return;\n this.closedByUs = false;\n this.controller.start();\n this.setState({ status: 'connecting' });\n await this.openSocket();\n }\n\n private async openSocket(): Promise<void> {\n let grantToken: string;\n try {\n grantToken = await this.config.grantProvider();\n } catch (err) {\n // A TERMINAL access denial (the app's grant provider translated an\n // authoritative policy \"no\" into the package-owned ChatAccessDeniedError)\n // must NOT reconnect — the next mint would just re-deny, stranding the shell\n // on the opening loader forever. Every other mint failure (network, transient\n // 'unavailable'/'internal', post-login 'unauthenticated') stays retryable and\n // backs off exactly as before.\n if (isChatAccessDeniedError(err)) return this.denyAccessTerminally();\n return this.scheduleReconnect();\n }\n if (this.closedByUs) return;\n const url = `${this.config.endpoint.replace(/\\/$/, '')}/channel`;\n this.socket = this.config.socketFactory({\n url,\n grantToken,\n handlers: {\n onOpen: () => this.onOpen(),\n onMessage: (data) => this.onMessage(data),\n onClose: (code, reason) => this.onClose(code, reason),\n onError: () => this.onError(),\n },\n });\n }\n\n private onOpen(): void {\n this.controller.onOpen();\n this.reauthAttempted = false;\n this.setState({ status: 'open' });\n // Resume: ask the DO for the authoritative snapshot, then live deltas flow. The\n // field name MUST be `afterSeq` — the Channel DO reads `payload.afterSeq`; any other\n // name reads as cursorless and forces a full resync every reconnect.\n this.sendFrame(CLIENT_FRAME.RESUME, { afterSeq: this.resumeSeq });\n // If the UI had presence open, re-subscribe after a reconnect.\n if (this.presenceSubscribed) this.sendFrame(CLIENT_FRAME.PRESENCE_SUBSCRIBE, {});\n // Re-send the last read cursor so a read-ack dropped during the disconnect window\n // (sendFrame returns false on a closed socket) is not lost until the next message.\n if (this.lastReadAck) this.sendFrame(CLIENT_FRAME.READ_ACK, { ...this.lastReadAck });\n // Re-send every un-acked pending send with its ORIGINAL clientMessageId so a send\n // that lost its socket before the ack is not silently dropped. The DO dedups\n // (re-acks, no re-broadcast, no flood-token) — this is the client half of the\n // Contract C send-idempotency the server side was built for.\n this.resendPendingSends();\n this.startHeartbeat();\n }\n\n /**\n * On reconnect, re-send each un-acked pending send with the SAME clientMessageId\n * (the DO dedups). A send that has exceeded the attempt or age cap is flipped to a\n * visible failed state instead of being resent forever — the ghost becomes a\n * retryable failure the UI can surface.\n */\n private resendPendingSends(): void {\n if (this.pendingSends.size === 0) return;\n const now = this.timers.now();\n for (const pending of [...this.pendingSends.values()]) {\n // Already flipped to the visible failed state — only an explicit retrySend()\n // re-queues it; the automatic reconnect resend leaves it alone.\n if (pending.failed) continue;\n const tooOld = now - pending.sentAt >= PENDING_SEND_MAX_AGE_MS;\n const tooManyAttempts = pending.attempts >= MAX_PENDING_SEND_ATTEMPTS;\n if (tooOld || tooManyAttempts) {\n this.failPendingSend(pending.clientMessageId);\n continue;\n }\n const sent = this.sendFrame(CLIENT_FRAME.SEND, {\n clientMessageId: pending.clientMessageId,\n text: pending.text,\n replyTo: pending.replyTo,\n });\n if (sent) pending.attempts += 1;\n }\n }\n\n /**\n * Flip an un-acked optimistic row to a visible failed state. The pending entry is\n * RETAINED (marked `failed`) so retrySend() can re-queue it with the SAME\n * clientMessageId; the row is marked `meta.sendFailed` so the default renderer\n * shows a failure with a retry affordance rather than an indistinguishable\n * \"sent\" bubble. A late ack/echo still reconciles + clears it.\n */\n private failPendingSend(clientMessageId: string): void {\n const pending = this.pendingSends.get(clientMessageId);\n if (!pending || pending.failed) return;\n pending.failed = true;\n const next = this.state.messages.map((m) =>\n m.meta?.optimistic && m.meta?.clientMessageId === clientMessageId\n ? { ...m, meta: { ...m.meta, sendFailed: true } }\n : m,\n );\n this.setState({ messages: next, lastErrorCode: 'send-failed' });\n }\n\n /** One timer for the membership-pending re-send window; a newer frame resets it. */\n private scheduleMembershipPendingRetry(delayMs: number): void {\n if (this.membershipRetryTimer != null) this.timers.clearTimeout(this.membershipRetryTimer);\n this.membershipRetryTimer = this.timers.setTimeout(() => {\n this.membershipRetryTimer = null;\n if (this.closedByUs) return;\n this.resendPendingSends();\n }, delayMs);\n }\n\n /**\n * Flip EVERY un-acked pending send to the visible failed state. Called on the\n * terminal close paths (4403 REVOKED, reconnect give-up) — without this, a send\n * in flight when the socket dies for good shows \"Sending…\" until unmount.\n */\n private failAllPendingSends(): void {\n for (const clientMessageId of [...this.pendingSends.keys()]) {\n this.failPendingSend(clientMessageId);\n }\n }\n\n /**\n * Retry a FAILED (or still-pending) send, RE-USING its original clientMessageId\n * so the DO's send-idempotency dedups against any copy that actually landed.\n * Resets the attempt/age budget, clears the row's `sendFailed` marker (back to\n * the normal pending/optimistic look), and re-sends immediately when the socket\n * is open — otherwise the entry rides the next reconnect's automatic resend.\n * Returns false when the clientMessageId is not a tracked pending send (already\n * acked/reconciled, or never sent from this client).\n */\n retrySend(clientMessageId: string): boolean {\n const pending = this.pendingSends.get(clientMessageId);\n if (!pending) return false;\n pending.failed = false;\n pending.sentAt = this.timers.now();\n const sent = this.sendFrame(CLIENT_FRAME.SEND, {\n clientMessageId: pending.clientMessageId,\n text: pending.text,\n replyTo: pending.replyTo,\n });\n pending.attempts = sent ? 1 : 0;\n const next = this.state.messages.map((m) =>\n m.meta?.optimistic && m.meta?.clientMessageId === clientMessageId && m.meta?.sendFailed\n ? { ...m, meta: { ...m.meta, sendFailed: false } }\n : m,\n );\n this.setState({ messages: next, lastErrorCode: null });\n return true;\n }\n\n private onError(): void {\n // The close handler does the backoff; onerror is advisory in browsers.\n }\n\n private onClose(code: number, _reason: string): void {\n this.stopHeartbeat();\n this.socket = null;\n if (this.closedByUs) {\n this.setState({ status: 'closed' });\n return;\n }\n // 4401 AUTH_EXPIRED: re-mint a grant ONCE and reconnect immediately, no backoff.\n if (code === CHAT_CLOSE_CODES.AUTH_EXPIRED && !this.reauthAttempted) {\n this.reauthAttempted = true;\n this.setState({ status: 'reconnecting' });\n void this.openSocket();\n return;\n }\n // 4403 REVOKED: access pulled. Stop — a reconnect would just re-deny at mint.\n // Terminal: flip every un-acked pending send to the visible failed state first\n // (failPendingSend sets lastErrorCode 'send-failed'; the 'revoked' set below\n // wins as the final surfaced code).\n if (code === CHAT_CLOSE_CODES.REVOKED) {\n this.closedByUs = true;\n this.controller.close();\n this.failAllPendingSends();\n this.setState({ status: 'closed', lastErrorCode: 'revoked' });\n return;\n }\n this.scheduleReconnect();\n }\n\n private scheduleReconnect(): void {\n const delay = this.controller.onClose();\n if (delay == null) {\n // Reconnect give-up: terminal, same as REVOKED — pending sends must not stay\n // an eternal \"Sending…\"; flip them to the visible failed/retry state.\n this.failAllPendingSends();\n this.setState({ status: 'closed' });\n return;\n }\n this.setState({ status: 'reconnecting' });\n this.reconnectTimer = this.timers.setTimeout(() => {\n this.reconnectTimer = null;\n if (this.closedByUs) return;\n void this.openSocket();\n }, delay);\n }\n\n /**\n * Terminal access denial surfaced by the grant provider (ChatAccessDeniedError).\n * A reconnect would just re-deny at the next mint, so stop for good — the same\n * terminal posture as a 4403 REVOKED close: mark closed-by-us, close the reconnect\n * controller, and flip every un-acked pending send to the visible failed state.\n * `access-denied` is set AFTER failAllPendingSends so its 'send-failed' code does\n * not win as the surfaced error; the React hook maps 'access-denied' to\n * `allowed: false` so the shell renders its existing no-access surface.\n */\n private denyAccessTerminally(): void {\n this.closedByUs = true;\n this.controller.close();\n this.failAllPendingSends();\n this.setState({ status: 'closed', lastErrorCode: 'access-denied' });\n }\n\n // ---- inbound frames ----\n\n private onMessage(data: string): void {\n const frame = parseFrame(data);\n if (!frame || !frame.type) return;\n const payload = frame.payload ?? {};\n switch (frame.type) {\n case 'message':\n return this.applyMessage((payload as { message: WireMessageRow }).message);\n case 'ack':\n return this.applyAck(payload as { clientMessageId?: string; seq?: number; readSeq?: number });\n case 'history-page':\n return this.applyHistoryPage((payload as { messages: WireMessageRow[] }).messages ?? []);\n case 'presence':\n return this.setState({ presence: (payload as { online: string[] }).online ?? [] });\n case 'typing':\n return this.applyTyping((payload as { uid: string }).uid);\n case 'snapshot':\n return this.applyChannelSnapshot(payload as unknown as WireChannelSnapshot);\n case 'error': {\n const code = String((payload as { code?: unknown }).code ?? 'error');\n // Retryable: membership row not yet synced to the DO. Keep the send pending\n // (no visible error — the optimistic bubble stays \"Sending…\") and re-send\n // after the server-suggested delay via the normal resend machinery, whose\n // attempt/age caps flip it to the visible failed state if the window never\n // closes. Everything else surfaces as before.\n if (code === MEMBERSHIP_PENDING_CODE) {\n const raw = (payload as { retryAfterMs?: unknown }).retryAfterMs;\n const delay = typeof raw === 'number' && raw > 0 ? raw : MEMBERSHIP_PENDING_DEFAULT_RETRY_MS;\n return this.scheduleMembershipPendingRetry(delay);\n }\n return this.setState({ lastErrorCode: code });\n }\n case 'revision':\n return this.applyRevisionFrame(payload as { messageSeq?: number; kind?: RevisionKind; messageRevision?: number });\n default:\n return; // unknown/optional types tolerated (forward compat)\n }\n }\n\n /**\n * Apply a live moderation `revision` frame: record the overlay keyed by seq\n * (max-`messageRevision` wins — a stale/older frame is ignored) and re-render the\n * matching message in place if it is already loaded. If the base row hasn't\n * arrived yet the overlay is retained and re-applied when the row renders, so a\n * frame that races ahead of its message never lets the original content show.\n */\n private applyRevisionFrame(payload: { messageSeq?: number; kind?: RevisionKind; messageRevision?: number }): void {\n const seq = payload.messageSeq;\n const kind = payload.kind;\n const messageRevision = payload.messageRevision;\n if (typeof seq !== 'number' || kind == null || typeof messageRevision !== 'number') return;\n const prev = this.overlays.get(seq);\n // Max-revision merge: a higher messageRevision supersedes; an older one is dropped.\n if (prev && prev.messageRevision >= messageRevision) return;\n this.overlays.set(seq, { kind, messageRevision });\n // Re-render the matching message in place if it is already present. Re-derive\n // from the ORIGINAL row so a `restore` reverts a previously-blanked text.\n const messageId = seqToMessageId(seq);\n const original = this.originalRows.get(seq);\n if (original && this.state.messages.some((m) => m.messageId === messageId)) {\n const overlaid = applyModerationOverlay(original, this.effectiveOverlay(seq, null));\n const next = this.state.messages.map((m) => (m.messageId === messageId ? overlaid : m));\n this.setState({ messages: next });\n }\n }\n\n /**\n * The effective overlay for a seq = the max-`messageRevision` between the row's\n * own inline overlay (from the DO history/delta merge) and any received `revision`\n * frame stored in `this.overlays`. Either source may be ahead of the other.\n */\n private effectiveOverlay(seq: number, rowOverlay: ModerationOverlay | null): ModerationOverlay | null {\n const fromFrame = this.overlays.get(seq) ?? null;\n if (!rowOverlay) return fromFrame;\n if (!fromFrame) return rowOverlay;\n return fromFrame.messageRevision >= rowOverlay.messageRevision ? fromFrame : rowOverlay;\n }\n\n /** Map a DO row to a UI message with its effective moderation overlay applied. */\n private renderRow(row: WireMessageRow): ChatMessageV1 {\n const mapped = wireRowToMessage(row, this.config.threadId);\n // Cache the ORIGINAL so a later `restore` frame can revert a blanked message.\n this.originalRows.set(row.seq, mapped);\n return applyModerationOverlay(mapped, this.effectiveOverlay(row.seq, overlayFromRow(row)));\n }\n\n /**\n * Apply the Contract C resume snapshot. The DO always returns the authoritative\n * tail + read cursor and, per the pinned contract, EITHER a contiguous delta\n * (`resync:false`) OR a resync directive (`resync:true`).\n *\n * - `resync === false`: apply the contiguous `delta` (the ≤500-message backlog\n * after our cursor, oldest-first) through the same render/merge path as a live\n * `message`, then advance `resumeSeq` to `lastMessageSeq`. This heals ANY gap\n * within the backlog — including moderation `revision`s the DO baked into the\n * delta rows — with no history fetch, so a >50-message reconnect gap is no\n * longer a permanent hole.\n * - `resync === true`: the gap is beyond the backlog (or we sent no cursor). Drop\n * the local tail (messages + overlays + original-row cache) and re-page history\n * from the top via a cursorless `requestHistory(null)`.\n *\n * A pre-contract DO (no `resync`/`delta`) is treated as `resync:true` ⇒ the safe\n * re-page path, so a stale worker never strands the client. An empty delta with\n * `resync:false` (already caught up) is a no-op beyond advancing the cursor.\n */\n private applyChannelSnapshot(snap: WireChannelSnapshot): void {\n // Guard: an inbox snapshot must never reach a channel client.\n if (isInboxSnapshot(snap as never)) return;\n if (typeof snap.lastMessageSeq !== 'number') return;\n\n // Absent `resync` (legacy/pre-contract DO) is treated as a resync directive.\n const resync = snap.resync !== false;\n\n if (!resync) {\n // Apply the contiguous delta oldest-first, exactly like live messages, then\n // advance the cursor to the authoritative tail so the NEXT resume tells the DO\n // we're caught up only after we actually applied the backlog.\n const delta = Array.isArray(snap.delta) ? snap.delta : [];\n for (const row of delta) this.applyMessage(row);\n if (snap.lastMessageSeq > this.resumeSeq) this.resumeSeq = snap.lastMessageSeq;\n // A non-resync snapshot IS the first authoritative data (even an empty delta =\n // caught up) — end initial loading. A resync snapshot instead defers to the\n // re-paged first history page below, so it must NOT end it here.\n if (!this.state.hasLoadedInitialData) this.setState({ hasLoadedInitialData: true });\n return;\n }\n\n // Resync: drop the local tail and re-page from the top per the pinned contract.\n // Clear the derived caches too so a stale overlay/original-row can't resurrect a\n // message the re-page will reload fresh (with its baked-in moderation state).\n // KEEP un-acked optimistic rows — they aren't server history yet; their pending\n // sends were already re-sent in onOpen and reconcile when the DO echoes them.\n this.overlays.clear();\n this.originalRows.clear();\n this.resumeSeq = 0;\n const keptOptimistic = this.state.messages.filter((m) => m.meta?.optimistic);\n this.setState({ messages: keptOptimistic, hasOlder: true, isFetchingOlder: false });\n this.requestHistory(null);\n }\n\n private applyMessage(row: WireMessageRow): void {\n if (!row || typeof row.seq !== 'number') return;\n const mapped = this.renderRow(row);\n this.mergeMessage(mapped, row);\n if (row.seq > this.resumeSeq) this.resumeSeq = row.seq;\n }\n\n /**\n * Merge a server message: reconcile an optimistic echo by clientMessageId (swap\n * the `optimistic:` row for the canonical seq row), or insert/replace by seq.\n * Keeps the list sorted ascending by seq with optimistic rows at the tail.\n */\n private mergeMessage(mapped: ChatMessageV1, row: WireMessageRow): void {\n // If this canonical row carries a clientMessageId we still have pending (the\n // sender's own broadcast, or a resume delta that included our send), the send\n // landed — stop tracking it for reconnect resend.\n if (row.clientMessageId) this.pendingSends.delete(row.clientMessageId);\n const next = this.state.messages.filter(\n (m) =>\n m.messageId !== mapped.messageId &&\n // drop the optimistic placeholder this server row reconciles\n (m.meta?.clientMessageId !== row.clientMessageId || !m.meta?.optimistic),\n );\n next.push(mapped);\n next.sort(sortBySeq);\n this.setState({ messages: next });\n }\n\n private applyAck(payload: { clientMessageId?: string; seq?: number; readSeq?: number }): void {\n // A read-ack echo carries readSeq only — nothing to reconcile locally.\n if (payload.clientMessageId == null || typeof payload.seq !== 'number') return;\n // Reconcile the optimistic echo: stamp the server seq onto it. The canonical\n // `message` broadcast (which the sender also receives) replaces it fully; this\n // ack guarantees the seq even if the broadcast is dropped/reordered.\n const seq = payload.seq;\n const cmid = payload.clientMessageId;\n // The send is acked — stop tracking it for reconnect resend.\n this.pendingSends.delete(cmid);\n const next = this.state.messages.map((m) => {\n if (!m.meta?.optimistic || m.meta?.clientMessageId !== cmid) return m;\n // Strip any failed marker — a late ack (e.g. a retry raced the cap) means the\n // send actually landed, so the row must render as delivered, not failed.\n const { sendFailed: _sendFailed, ...restMeta } = m.meta;\n return { ...m, messageId: seqToMessageId(seq), meta: { ...restMeta, optimistic: false, seq } };\n });\n next.sort(sortBySeq);\n if (seq > this.resumeSeq) this.resumeSeq = seq;\n this.setState({ messages: next });\n }\n\n private applyHistoryPage(rows: WireMessageRow[]): void {\n const mapped = rows.map((r) => this.renderRow(r));\n // Mirror mergeMessage's optimistic reconciliation: a history row carrying a\n // clientMessageId we still hold as an optimistic placeholder IS that send (the\n // DO stored it; the ack was lost). Drop the placeholder — keyed `optimistic:{cmid}`,\n // it would otherwise survive alongside its seq-keyed server row as a duplicate\n // bubble after a resync + re-page — and stop tracking it for resend.\n const incomingCmids = new Set<string>();\n for (const r of rows) {\n if (r.clientMessageId) {\n incomingCmids.add(r.clientMessageId);\n this.pendingSends.delete(r.clientMessageId);\n }\n }\n const bySeq = new Map<string, ChatMessageV1>();\n for (const m of this.state.messages) {\n if (m.meta?.optimistic && typeof m.meta?.clientMessageId === 'string' && incomingCmids.has(m.meta.clientMessageId)) {\n continue; // reconciled by the incoming server row\n }\n bySeq.set(m.messageId, m);\n }\n for (const m of mapped) bySeq.set(m.messageId, m);\n const merged = [...bySeq.values()].sort(sortBySeq);\n for (const r of rows) if (r.seq > this.resumeSeq) this.resumeSeq = r.seq;\n this.setState({\n messages: merged,\n isFetchingOlder: false,\n hasOlder: rows.length >= HISTORY_PAGE_MAX,\n // The first history page — INCLUDING an empty one — is a successful authoritative\n // load, so it ends initial loading. (Older-page fetches redundantly re-set true,\n // which is a harmless no-op since the flag never flips back to false.)\n hasLoadedInitialData: true,\n });\n }\n\n private applyTyping(uid: string): void {\n if (!uid || uid === this.config.currentUserId) return;\n if (!this.state.typing.includes(uid)) this.setState({ typing: [...this.state.typing, uid] });\n const prev = this.typingTimers.get(uid);\n if (prev) this.timers.clearTimeout(prev);\n this.typingTimers.set(\n uid,\n this.timers.setTimeout(() => {\n this.typingTimers.delete(uid);\n this.setState({ typing: this.state.typing.filter((u) => u !== uid) });\n }, TYPING_COALESCE_MS * 2),\n );\n }\n\n // ---- outbound actions ----\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 /**\n * Optimistic send: render the echo immediately keyed by clientMessageId, then\n * emit the `send` frame. The server `ack`/`message` reconciles on the seq.\n */\n send(args: { clientMessageId: string; text: string; replyTo?: { messageSeq: number; preview: string } | null }): boolean {\n // C-B8: write the frame FIRST and render the optimistic echo ONLY if it was\n // actually sent over an open socket. A closed socket returns false — no phantom\n // \"sent\" bubble, and the caller keeps the composer text — so a disconnect between\n // render and click can't silently swallow the message.\n const sent = this.sendFrame(CLIENT_FRAME.SEND, {\n clientMessageId: args.clientMessageId,\n text: args.text,\n replyTo: args.replyTo ?? null,\n });\n if (!sent) {\n this.setState({ lastErrorCode: 'send-failed' });\n return false;\n }\n const now = this.timers.now();\n // Track the un-acked send so a reconnect re-sends it with the same\n // clientMessageId (the DO dedups) — until the ack/echo clears it.\n this.pendingSends.set(args.clientMessageId, {\n clientMessageId: args.clientMessageId,\n text: args.text,\n replyTo: args.replyTo ?? null,\n sentAt: now,\n attempts: 1,\n failed: false,\n });\n const echo = optimisticMessage({\n clientMessageId: args.clientMessageId,\n threadId: this.config.threadId,\n senderId: this.config.currentUserId,\n text: args.text,\n createdAt: now,\n replyTo: args.replyTo ? { messageId: seqToMessageId(args.replyTo.messageSeq), messagePreview: args.replyTo.preview } : null,\n });\n const next = [...this.state.messages, echo].sort(sortBySeq);\n this.setState({ messages: next, lastErrorCode: null });\n return true;\n }\n\n /**\n * Explicit read ack (delivery != read). `focused` => the channel is open + at latest.\n * Remembers the cursor (re-sent on reconnect) and returns whether the frame was\n * actually sent over an open socket, so the caller only advances its local\n * already-acked marker on a real send (M2).\n */\n readAck(readSeq: number, focused: boolean): boolean {\n this.lastReadAck = { readSeq, focused };\n return this.sendFrame(CLIENT_FRAME.READ_ACK, { readSeq, focused });\n }\n\n /** Coalesced typing signal: at most one frame per TYPING_COALESCE_MS. */\n typing(): void {\n const now = this.timers.now();\n if (now - this.lastTypingSentAt < TYPING_COALESCE_MS) return;\n this.lastTypingSentAt = now;\n this.sendFrame(CLIENT_FRAME.TYPING, {});\n }\n\n presenceSubscribe(): void {\n this.presenceSubscribed = true;\n this.sendFrame(CLIENT_FRAME.PRESENCE_SUBSCRIBE, {});\n }\n\n presenceUnsubscribe(): void {\n this.presenceSubscribed = false;\n this.sendFrame(CLIENT_FRAME.PRESENCE_UNSUBSCRIBE, {});\n this.setState({ presence: [] });\n }\n\n /** Fetch the page of history older than the oldest loaded message (epoch-aware by seq). */\n fetchOlder(): void {\n if (this.state.isFetchingOlder || !this.state.hasOlder) return;\n const oldest = this.state.messages.find((m) => typeof m.meta?.seq === 'number');\n const beforeSeq = oldest && typeof oldest.meta?.seq === 'number' ? (oldest.meta.seq as number) : null;\n this.setState({ isFetchingOlder: true });\n this.requestHistory(beforeSeq);\n }\n\n private requestHistory(beforeSeq: number | null): void {\n this.sendFrame(CLIENT_FRAME.HISTORY, { beforeSeq, limit: HISTORY_PAGE_MAX });\n }\n\n // ---- heartbeat (20s) ----\n\n private startHeartbeat(): void {\n this.stopHeartbeat();\n const tick = () => {\n if (!this.socket || !this.socket.isOpen) return;\n this.sendFrame(CLIENT_FRAME.HEARTBEAT, {});\n this.heartbeatTimer = this.timers.setTimeout(tick, HEARTBEAT_MS);\n };\n this.heartbeatTimer = this.timers.setTimeout(tick, HEARTBEAT_MS);\n }\n\n private stopHeartbeat(): void {\n if (this.heartbeatTimer != null) {\n this.timers.clearTimeout(this.heartbeatTimer);\n this.heartbeatTimer = null;\n }\n }\n\n // ---- teardown ----\n\n /** Permanently close this client (auth-user switch / unmount). Idempotent. */\n close(): void {\n this.closedByUs = true;\n this.controller.close();\n this.stopHeartbeat();\n for (const t of this.typingTimers.values()) this.timers.clearTimeout(t);\n this.typingTimers.clear();\n this.overlays.clear();\n this.originalRows.clear();\n this.pendingSends.clear();\n if (this.reconnectTimer != null) {\n this.timers.clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n if (this.membershipRetryTimer != null) {\n this.timers.clearTimeout(this.membershipRetryTimer);\n this.membershipRetryTimer = null;\n }\n if (this.socket) {\n this.socket.close(1000, 'client teardown');\n this.socket = null;\n }\n this.setState({ status: 'closed', typing: [], presence: [] });\n }\n}\n\nfunction sortBySeq(a: ChatMessageV1, b: ChatMessageV1): number {\n const sa = typeof a.meta?.seq === 'number' ? (a.meta.seq as number) : Number.POSITIVE_INFINITY;\n const sb = typeof b.meta?.seq === 'number' ? (b.meta.seq as number) : Number.POSITIVE_INFINITY;\n if (sa !== sb) return sa - sb;\n return a.createdAt - b.createdAt;\n}\n"]}
|
package/dist/realtime/index.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ export type { ChannelRefTuple, ChatCloseCode, WireMessageRow, WireChannelSnapsho
|
|
|
3
3
|
export type { RealtimeSocket, SocketFactory, SocketHandlers } from './socket.js';
|
|
4
4
|
export { browserSocketFactory } from './socket.js';
|
|
5
5
|
export type { GrantProvider, TransportTimers, RealtimeStatus } from './shared.js';
|
|
6
|
-
export { defaultTimers, HEARTBEAT_MS, TYPING_COALESCE_MS, HISTORY_PAGE_MAX } from './shared.js';
|
|
6
|
+
export { defaultTimers, ChatAccessDeniedError, isChatAccessDeniedError, HEARTBEAT_MS, TYPING_COALESCE_MS, HISTORY_PAGE_MAX, } from './shared.js';
|
|
7
7
|
export { wireRowToMessage, optimisticMessage, seqToMessageId, applyModerationOverlay, overlayFromRow, MODERATION_REDACTED_TEXT, } from './map.js';
|
|
8
8
|
export type { ModerationOverlay } from './map.js';
|
|
9
9
|
export { ChannelClient } from './channel-client.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/realtime/index.ts"],"names":[],"mappings":"AAMA,OAAO,EACL,gBAAgB,EAChB,iBAAiB,EACjB,gBAAgB,EAChB,YAAY,EACZ,YAAY,EACZ,UAAU,EACV,UAAU,EACV,eAAe,GAChB,MAAM,WAAW,CAAC;AACnB,YAAY,EACV,eAAe,EACf,aAAa,EACb,cAAc,EACd,mBAAmB,EACnB,iBAAiB,EACjB,iBAAiB,EACjB,WAAW,EACX,YAAY,GACb,MAAM,WAAW,CAAC;AAEnB,YAAY,EAAE,cAAc,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AACjF,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAEnD,YAAY,EAAE,aAAa,EAAE,eAA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gBAAgB,CAAC;AAElF,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AACvE,YAAY,EAAE,6BAA6B,EAAE,MAAM,8BAA8B,CAAC"}
|
package/dist/realtime/index.js
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
// `createRealtimeChatClient(...)`.
|
|
6
6
|
export { CHAT_SUBPROTOCOL, CHAT_WIRE_VERSION, CHAT_CLOSE_CODES, CLIENT_FRAME, SERVER_FRAME, buildFrame, parseFrame, isInboxSnapshot, } from './wire.js';
|
|
7
7
|
export { browserSocketFactory } from './socket.js';
|
|
8
|
-
export { defaultTimers, HEARTBEAT_MS, TYPING_COALESCE_MS, HISTORY_PAGE_MAX } from './shared.js';
|
|
8
|
+
export { defaultTimers, ChatAccessDeniedError, isChatAccessDeniedError, HEARTBEAT_MS, TYPING_COALESCE_MS, HISTORY_PAGE_MAX, } from './shared.js';
|
|
9
9
|
export { wireRowToMessage, optimisticMessage, seqToMessageId, applyModerationOverlay, overlayFromRow, MODERATION_REDACTED_TEXT, } from './map.js';
|
|
10
10
|
export { ChannelClient } from './channel-client.js';
|
|
11
11
|
export { InboxClient } from './inbox-client.js';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/realtime/index.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,+EAA+E;AAC/E,sEAAsE;AACtE,uEAAuE;AACvE,mCAAmC;AAEnC,OAAO,EACL,gBAAgB,EAChB,iBAAiB,EACjB,gBAAgB,EAChB,YAAY,EACZ,YAAY,EACZ,UAAU,EACV,UAAU,EACV,eAAe,GAChB,MAAM,WAAW,CAAC;AAanB,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAGnD,OAAO,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/realtime/index.ts"],"names":[],"mappings":"AAAA,+EAA+E;AAC/E,+EAA+E;AAC/E,sEAAsE;AACtE,uEAAuE;AACvE,mCAAmC;AAEnC,OAAO,EACL,gBAAgB,EAChB,iBAAiB,EACjB,gBAAgB,EAChB,YAAY,EACZ,YAAY,EACZ,UAAU,EACV,UAAU,EACV,eAAe,GAChB,MAAM,WAAW,CAAC;AAanB,OAAO,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAGnD,OAAO,EACL,aAAa,EACb,qBAAqB,EACrB,uBAAuB,EACvB,YAAY,EACZ,kBAAkB,EAClB,gBAAgB,GACjB,MAAM,aAAa,CAAC;AAErB,OAAO,EACL,gBAAgB,EAChB,iBAAiB,EACjB,cAAc,EACd,sBAAsB,EACtB,cAAc,EACd,wBAAwB,GACzB,MAAM,UAAU,CAAC;AAGlB,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAGhD,OAAO,EACL,wBAAwB,EACxB,iBAAiB,GAClB,MAAM,gBAAgB,CAAC;AAGxB,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC","sourcesContent":["// The realtime (Cloudflare Durable Object) chat transport — the client half of\n// the chat Worker wire protocol (Contract A connection + Contract C wire). The\n// FIRESTORE transport stays the unchanged default; this is opt-in via\n// `ChatCoreConfig.transport === 'realtime'` + a `realtime.client` from\n// `createRealtimeChatClient(...)`.\n\nexport {\n CHAT_SUBPROTOCOL,\n CHAT_WIRE_VERSION,\n CHAT_CLOSE_CODES,\n CLIENT_FRAME,\n SERVER_FRAME,\n buildFrame,\n parseFrame,\n isInboxSnapshot,\n} from './wire.js';\nexport type {\n ChannelRefTuple,\n ChatCloseCode,\n WireMessageRow,\n WireChannelSnapshot,\n WireInboxSnapshot,\n WireRegistryEntry,\n ServerFrame,\n RevisionKind,\n} from './wire.js';\n\nexport type { RealtimeSocket, SocketFactory, SocketHandlers } from './socket.js';\nexport { browserSocketFactory } from './socket.js';\n\nexport type { GrantProvider, TransportTimers, RealtimeStatus } from './shared.js';\nexport {\n defaultTimers,\n ChatAccessDeniedError,\n isChatAccessDeniedError,\n HEARTBEAT_MS,\n TYPING_COALESCE_MS,\n HISTORY_PAGE_MAX,\n} from './shared.js';\n\nexport {\n wireRowToMessage,\n optimisticMessage,\n seqToMessageId,\n applyModerationOverlay,\n overlayFromRow,\n MODERATION_REDACTED_TEXT,\n} from './map.js';\nexport type { ModerationOverlay } from './map.js';\n\nexport { ChannelClient } from './channel-client.js';\nexport type { ChannelClientState, ChannelClientConfig } from './channel-client.js';\nexport { InboxClient } from './inbox-client.js';\nexport type { InboxClientState, InboxClientConfig } from './inbox-client.js';\n\nexport {\n createRealtimeChatClient,\n createInboxClient,\n} from './transport.js';\nexport type { RealtimeChatClient, RealtimeTransportConfig } from './transport.js';\n\nexport { useRealtimeChatMessages } from './useRealtimeChatMessages.js';\nexport type { UseRealtimeChatMessagesResult } from './useRealtimeChatMessages.js';\n"]}
|
|
@@ -6,6 +6,30 @@
|
|
|
6
6
|
* Query staleTime < grant exp, and returning a FRESH token when re-invoked.
|
|
7
7
|
*/
|
|
8
8
|
export type GrantProvider = () => Promise<string>;
|
|
9
|
+
/**
|
|
10
|
+
* Package-owned, Firebase-FREE terminal access-denial signal. A grant provider
|
|
11
|
+
* throws this (from `GrantProvider`) when the authoritative authorization answer
|
|
12
|
+
* is a genuine, terminal "no" — as opposed to a transient/retryable mint failure.
|
|
13
|
+
*
|
|
14
|
+
* The transport treats it specially: instead of the normal reconnect backoff it
|
|
15
|
+
* STOPS reconnecting, closes the lifecycle, fails any pending optimistic sends,
|
|
16
|
+
* and surfaces the stable `access-denied` error code (which the React hook maps to
|
|
17
|
+
* `allowed: false` so the shell renders its no-access surface instead of an eternal
|
|
18
|
+
* loader). Every other thrown error stays transient and reconnects as before.
|
|
19
|
+
*
|
|
20
|
+
* This is deliberately generic: the consuming app translates its own backend
|
|
21
|
+
* denial (e.g. a Firebase `functions/permission-denied`) into this class at the
|
|
22
|
+
* grant-provider boundary. The package never imports or names Firebase. Consumers
|
|
23
|
+
* that cannot subclass may instead throw any error carrying `isChatAccessDenied:
|
|
24
|
+
* true` — `isChatAccessDeniedError` recognizes both (also cross-realm safe).
|
|
25
|
+
*/
|
|
26
|
+
export declare class ChatAccessDeniedError extends Error {
|
|
27
|
+
/** Duck-typed marker so detection survives module-realm / re-throw boundaries. */
|
|
28
|
+
readonly isChatAccessDenied = true;
|
|
29
|
+
constructor(message?: string);
|
|
30
|
+
}
|
|
31
|
+
/** True when `err` is a terminal chat access denial (class instance or duck-typed marker). */
|
|
32
|
+
export declare function isChatAccessDeniedError(err: unknown): err is ChatAccessDeniedError;
|
|
9
33
|
/** Injectable timers so the transport runs deterministically under fake timers in tests. */
|
|
10
34
|
export interface TransportTimers {
|
|
11
35
|
setTimeout: (fn: () => void, ms: number) => ReturnType<typeof setTimeout>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shared.d.ts","sourceRoot":"","sources":["../../src/realtime/shared.ts"],"names":[],"mappings":"AASA;;;;;;GAMG;AACH,MAAM,MAAM,aAAa,GAAG,MAAM,OAAO,CAAC,MAAM,CAAC,CAAC;AAElD,4FAA4F;AAC5F,MAAM,WAAW,eAAe;IAC9B,UAAU,EAAE,CAAC,EAAE,EAAE,MAAM,IAAI,EAAE,EAAE,EAAE,MAAM,KAAK,UAAU,CAAC,OAAO,UAAU,CAAC,CAAC;IAC1E,YAAY,EAAE,CAAC,CAAC,EAAE,UAAU,CAAC,OAAO,UAAU,CAAC,KAAK,IAAI,CAAC;IACzD,GAAG,EAAE,MAAM,MAAM,CAAC;CACnB;AAED,eAAO,MAAM,aAAa,EAAE,eAI3B,CAAC;AAEF,4CAA4C;AAC5C,MAAM,MAAM,cAAc,GAAG,MAAM,GAAG,YAAY,GAAG,MAAM,GAAG,cAAc,GAAG,QAAQ,CAAC;AAIxF,OAAO,EAAE,YAAY,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AAEnG;;;;GAIG;AACH,eAAO,MAAM,yBAAyB,IAAI,CAAC;AAE3C;;;GAGG;AACH,eAAO,MAAM,uBAAuB,QAAS,CAAC"}
|
|
1
|
+
{"version":3,"file":"shared.d.ts","sourceRoot":"","sources":["../../src/realtime/shared.ts"],"names":[],"mappings":"AASA;;;;;;GAMG;AACH,MAAM,MAAM,aAAa,GAAG,MAAM,OAAO,CAAC,MAAM,CAAC,CAAC;AAElD;;;;;;;;;;;;;;;;GAgBG;AACH,qBAAa,qBAAsB,SAAQ,KAAK;IAC9C,kFAAkF;IAClF,QAAQ,CAAC,kBAAkB,QAAQ;gBACvB,OAAO,SAAuB;CAI3C;AAED,8FAA8F;AAC9F,wBAAgB,uBAAuB,CAAC,GAAG,EAAE,OAAO,GAAG,GAAG,IAAI,qBAAqB,CAOlF;AAED,4FAA4F;AAC5F,MAAM,WAAW,eAAe;IAC9B,UAAU,EAAE,CAAC,EAAE,EAAE,MAAM,IAAI,EAAE,EAAE,EAAE,MAAM,KAAK,UAAU,CAAC,OAAO,UAAU,CAAC,CAAC;IAC1E,YAAY,EAAE,CAAC,CAAC,EAAE,UAAU,CAAC,OAAO,UAAU,CAAC,KAAK,IAAI,CAAC;IACzD,GAAG,EAAE,MAAM,MAAM,CAAC;CACnB;AAED,eAAO,MAAM,aAAa,EAAE,eAI3B,CAAC;AAEF,4CAA4C;AAC5C,MAAM,MAAM,cAAc,GAAG,MAAM,GAAG,YAAY,GAAG,MAAM,GAAG,cAAc,GAAG,QAAQ,CAAC;AAIxF,OAAO,EAAE,YAAY,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AAEnG;;;;GAIG;AACH,eAAO,MAAM,yBAAyB,IAAI,CAAC;AAE3C;;;GAGG;AACH,eAAO,MAAM,uBAAuB,QAAS,CAAC"}
|
package/dist/realtime/shared.js
CHANGED
|
@@ -6,6 +6,38 @@
|
|
|
6
6
|
// existing import sites are unchanged. The worker runtime is the authority and
|
|
7
7
|
// rejects anything out of bounds, but the client uses these to coalesce and
|
|
8
8
|
// paginate politely. The remaining constants below are client-only retry policy.
|
|
9
|
+
/**
|
|
10
|
+
* Package-owned, Firebase-FREE terminal access-denial signal. A grant provider
|
|
11
|
+
* throws this (from `GrantProvider`) when the authoritative authorization answer
|
|
12
|
+
* is a genuine, terminal "no" — as opposed to a transient/retryable mint failure.
|
|
13
|
+
*
|
|
14
|
+
* The transport treats it specially: instead of the normal reconnect backoff it
|
|
15
|
+
* STOPS reconnecting, closes the lifecycle, fails any pending optimistic sends,
|
|
16
|
+
* and surfaces the stable `access-denied` error code (which the React hook maps to
|
|
17
|
+
* `allowed: false` so the shell renders its no-access surface instead of an eternal
|
|
18
|
+
* loader). Every other thrown error stays transient and reconnects as before.
|
|
19
|
+
*
|
|
20
|
+
* This is deliberately generic: the consuming app translates its own backend
|
|
21
|
+
* denial (e.g. a Firebase `functions/permission-denied`) into this class at the
|
|
22
|
+
* grant-provider boundary. The package never imports or names Firebase. Consumers
|
|
23
|
+
* that cannot subclass may instead throw any error carrying `isChatAccessDenied:
|
|
24
|
+
* true` — `isChatAccessDeniedError` recognizes both (also cross-realm safe).
|
|
25
|
+
*/
|
|
26
|
+
export class ChatAccessDeniedError extends Error {
|
|
27
|
+
/** Duck-typed marker so detection survives module-realm / re-throw boundaries. */
|
|
28
|
+
isChatAccessDenied = true;
|
|
29
|
+
constructor(message = 'Chat access denied') {
|
|
30
|
+
super(message);
|
|
31
|
+
this.name = 'ChatAccessDeniedError';
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/** True when `err` is a terminal chat access denial (class instance or duck-typed marker). */
|
|
35
|
+
export function isChatAccessDeniedError(err) {
|
|
36
|
+
return (err instanceof ChatAccessDeniedError ||
|
|
37
|
+
(typeof err === 'object' &&
|
|
38
|
+
err !== null &&
|
|
39
|
+
err.isChatAccessDenied === true));
|
|
40
|
+
}
|
|
9
41
|
export const defaultTimers = {
|
|
10
42
|
setTimeout: (fn, ms) => setTimeout(fn, ms),
|
|
11
43
|
clearTimeout: (h) => clearTimeout(h),
|
|
@@ -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,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,iFAAiF;
|
|
1
|
+
{"version":3,"file":"shared.js","sourceRoot":"","sources":["../../src/realtime/shared.ts"],"names":[],"mappings":"AAAA,4EAA4E;AAC5E,EAAE;AACF,kEAAkE;AAClE,yDAAyD;AACzD,gFAAgF;AAChF,+EAA+E;AAC/E,4EAA4E;AAC5E,iFAAiF;AAWjF;;;;;;;;;;;;;;;;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,6EAA6E;AAC7E,kCAAkC;AAClC,OAAO,EAAE,YAAY,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,+BAA+B,CAAC;AAEnG;;;;GAIG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAG,CAAC,CAAC;AAE3C;;;GAGG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,MAAM,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`; they are re-exported here so the transport's\n// existing import sites are unchanged. 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 remaining 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// The client-agreed limits live in the wire contract; re-export to keep this\n// module's public surface stable.\nexport { HEARTBEAT_MS, TYPING_COALESCE_MS, HISTORY_PAGE_MAX } from '@ttt-productions/chat-schemas';\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"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useRealtimeChatMessages.d.ts","sourceRoot":"","sources":["../../src/realtime/useRealtimeChatMessages.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACzD,OA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,KAAK,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AACzD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,qBAAqB,CAAC;AAG9D,MAAM,MAAM,6BAA6B,GAAG;IAC1C,OAAO,EAAE,OAAO,CAAC;IACjB,gBAAgB,EAAE,OAAO,CAAC;IAC1B,QAAQ,EAAE,aAAa,EAAE,CAAC;IAC1B,UAAU,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IAChC,QAAQ,EAAE,OAAO,CAAC;IAClB,eAAe,EAAE,OAAO,CAAC;IACzB,mFAAmF;IACnF,MAAM,EAAE,kBAAkB,CAAC,QAAQ,CAAC,CAAC;IACrC;4CACwC;IACxC,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;IAC7B,MAAM,EAAE,MAAM,EAAE,CAAC;IACjB,QAAQ,EAAE,MAAM,EAAE,CAAC;IACnB,iHAAiH;IACjH,IAAI,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE;QAAE,UAAU,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,GAAG,IAAI,KAAK,OAAO,CAAC;IAC1F;;;;;uCAKmC;IACnC,SAAS,EAAE,CAAC,eAAe,EAAE,MAAM,KAAK,OAAO,CAAC;IAChD,sIAAsI;IACtI,OAAO,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,KAAK,OAAO,CAAC;IACxD,YAAY,EAAE,MAAM,IAAI,CAAC;IACzB;;yEAEqE;IACrE,iBAAiB,EAAE,MAAM,IAAI,CAAC;IAC9B,mBAAmB,EAAE,MAAM,IAAI,CAAC;CACjC,CAAC;AAEF,wBAAgB,uBAAuB,CAAC,MAAM,EAAE,kBAAkB,GAAG,6BAA6B,CA6EjG"}
|
|
@@ -44,11 +44,17 @@ export function useRealtimeChatMessages(client) {
|
|
|
44
44
|
const presenceSubscribe = React.useCallback(() => client.channel.presenceSubscribe(), [client]);
|
|
45
45
|
const presenceUnsubscribe = React.useCallback(() => client.channel.presenceUnsubscribe(), [client]);
|
|
46
46
|
return {
|
|
47
|
-
// On the realtime transport DATA ACCESS is enforced by the DO grant, so the
|
|
48
|
-
//
|
|
49
|
-
//
|
|
50
|
-
allowed:
|
|
51
|
-
|
|
47
|
+
// On the realtime transport DATA ACCESS is enforced by the DO grant, so the hook
|
|
48
|
+
// is "allowed" client-side UNLESS the grant provider surfaced a TERMINAL access
|
|
49
|
+
// denial (ChatAccessDeniedError → stable 'access-denied' code). That single case
|
|
50
|
+
// maps to allowed:false so ChatShell renders its no-access surface instead of an
|
|
51
|
+
// eternal loader; a transient close / 4403-revoke keeps allowed:true and rides the
|
|
52
|
+
// reconnect/disconnected banner. Otherwise accessMode is presentation-only here.
|
|
53
|
+
allowed: state.lastErrorCode !== "access-denied",
|
|
54
|
+
// Derive initial loading from authoritative-data completion, NOT connection status:
|
|
55
|
+
// a socket can be 'open' with no snapshot yet, and a post-load reconnect must not
|
|
56
|
+
// fall back into the opening state. `hasLoadedInitialData` encodes the full table.
|
|
57
|
+
isInitialLoading: !state.hasLoadedInitialData,
|
|
52
58
|
messages: state.messages,
|
|
53
59
|
fetchOlder,
|
|
54
60
|
hasOlder: state.hasOlder,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useRealtimeChatMessages.js","sourceRoot":"","sources":["../../src/realtime/useRealtimeChatMessages.ts"],"names":[],"mappings":"AAAA,YAAY,CAAC;AAEb,qEAAqE;AACrE,+EAA+E;AAC/E,kFAAkF;AAClF,2EAA2E;AAC3E,oFAAoF;AACpF,iFAAiF;AACjF,mFAAmF;AACnF,oFAAoF;AACpF,gBAAgB;AAEhB,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAI/B,OAAO,EAAE,2BAA2B,EAAE,MAAM,uCAAuC,CAAC;AAmCpF,MAAM,UAAU,uBAAuB,CAAC,MAA0B;IAChE,MAAM,CAAC,KAAK,EAAE,QAAQ,CAA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C;IAChG,MAAM,mBAAmB,GAAG,KAAK,CAAC,WAAW,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,OAAO,CAAC,mBAAmB,EAAE,EAAE,CAAC,MAAM,CAAC,CAAC,CAAC;IAEpG,OAAO;QACL,iFAAiF;QACjF,gFAAgF;QAChF,iFAAiF;QACjF,iFAAiF;QACjF,mFAAmF;QACnF,iFAAiF;QACjF,OAAO,EAAE,KAAK,CAAC,aAAa,KAAK,eAAe;QAChD,oFAAoF;QACpF,kFAAkF;QAClF,mFAAmF;QACnF,gBAAgB,EAAE,CAAC,KAAK,CAAC,oBAAoB;QAC7C,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,UAAU;QACV,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,eAAe,EAAE,KAAK,CAAC,eAAe;QACtC,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,aAAa,EAAE,KAAK,CAAC,aAAa;QAClC,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,IAAI;QACJ,SAAS;QACT,OAAO;QACP,YAAY;QACZ,iBAAiB;QACjB,mBAAmB;KACpB,CAAC;AACJ,CAAC;AAED,wGAAwG;AACxG,SAAS,mBAAmB;IAC1B,MAAM,CAAC,GAAI,UAAyD,CAAC,MAAM,CAAC;IAC5E,IAAI,CAAC,EAAE,UAAU;QAAE,OAAO,CAAC,CAAC,UAAU,EAAE,CAAC;IACzC,OAAO,QAAQ,IAAI,CAAC,GAAG,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;AACrE,CAAC","sourcesContent":["\"use client\";\n\n// React hook for the REALTIME transport, returning the SAME shape as\n// `useChatMessages` (the firestore path) so `ChatShell` is transport-agnostic.\n// It SUBSCRIBES to a `RealtimeChatClient`'s observable state. It does NOT own the\n// socket lifecycle: the caller (the app hook that CREATES the client, e.g.\n// `useRealtimeChannelClient`) is the single connect/close owner (C-B7) — connecting\n// here too opened a second WebSocket. The client instance is owned by the caller\n// (passed via config) so its identity is the subscription key — a new client for a\n// new uid replaces the old one (Contract A auth-user-switch teardown happens in the\n// owning hook).\n\nimport * as React from \"react\";\nimport type { ChatMessageV1 } from \"@ttt-productions/chat-core\";\nimport type { RealtimeChatClient } from \"./transport.js\";\nimport type { ChannelClientState } from \"./channel-client.js\";\nimport { useOptionalChatNameResolver } from \"../context/ChatNameResolverContext.js\";\n\nexport type UseRealtimeChatMessagesResult = {\n allowed: boolean;\n isInitialLoading: boolean;\n messages: ChatMessageV1[];\n fetchOlder: () => Promise<void>;\n hasOlder: boolean;\n isFetchingOlder: boolean;\n /** Realtime extras (not present on the firestore result) — optional for the UI. */\n status: ChannelClientState[\"status\"];\n /** The last structured error code the DO sent (e.g. a close reason). Drives the\n * disconnected-banner detail (R13). */\n lastErrorCode: string | null;\n typing: string[];\n presence: string[];\n /** Returns false when the socket was closed and nothing was sent (C-B8) — the caller keeps the composer text. */\n send: (text: string, replyTo?: { messageSeq: number; preview: string } | null) => boolean;\n /** Retry a failed/un-acked send by its ORIGINAL clientMessageId (read from the\n * failed row's `meta.clientMessageId`) — the transport re-queues the tracked\n * pending send with the SAME id so the DO's send-idempotency dedups any copy\n * that already landed. Returns false for an unknown id (already acked/\n * reconciled). ChatShell wires this to MessageItemDefault's failed-bubble\n * retry affordance by default. */\n retrySend: (clientMessageId: string) => boolean;\n /** Returns whether the ack frame was sent (false on a closed socket) so the caller advances its local cursor only on success (M2). */\n readAck: (readSeq: number, focused: boolean) => boolean;\n signalTyping: () => void;\n /** Watched-only presence (R14): the UI subscribes ONLY while a member-list / online\n * indicator is open, and unsubscribes when it closes, so an unwatched channel runs\n * zero presence alarms. `presence` stays empty until subscribed. */\n presenceSubscribe: () => void;\n presenceUnsubscribe: () => void;\n};\n\nexport function useRealtimeChatMessages(client: RealtimeChatClient): UseRealtimeChatMessagesResult {\n const [state, setState] = React.useState<ChannelClientState>(() => client.getState());\n\n // Subscribe only; the owning hook drives connect/close (single lifecycle owner, C-B7).\n // Re-subscribes on client identity change (auth-user switch).\n React.useEffect(() => {\n const unsub = client.subscribe(setState);\n setState(client.getState());\n return unsub;\n }, [client]);\n\n // Pre-warm the name cache for visible senders (parity with the firestore hook).\n const resolverCtx = useOptionalChatNameResolver();\n const senderIds = React.useMemo(() => {\n const set = new Set<string>();\n for (const m of state.messages) {\n set.add(m.senderId);\n if (m.replyTo?.senderId) set.add(m.replyTo.senderId);\n }\n return Array.from(set);\n }, [state.messages]);\n\n React.useEffect(() => {\n if (resolverCtx?.prewarm && senderIds.length > 0) resolverCtx.prewarm(senderIds);\n }, [resolverCtx, senderIds]);\n\n const fetchOlder = React.useCallback(async () => {\n client.channel.fetchOlder();\n }, [client]);\n\n const send = React.useCallback(\n (text: string, replyTo?: { messageSeq: number; preview: string } | null): boolean =>\n client.channel.send({ clientMessageId: makeClientMessageId(), text, replyTo: replyTo ?? null }),\n [client],\n );\n\n const retrySend = React.useCallback(\n (clientMessageId: string): boolean => client.channel.retrySend(clientMessageId),\n [client],\n );\n\n const readAck = React.useCallback(\n (readSeq: number, focused: boolean) => client.channel.readAck(readSeq, focused),\n [client],\n );\n\n const signalTyping = React.useCallback(() => client.channel.typing(), [client]);\n const presenceSubscribe = React.useCallback(() => client.channel.presenceSubscribe(), [client]);\n const presenceUnsubscribe = React.useCallback(() => client.channel.presenceUnsubscribe(), [client]);\n\n return {\n // On the realtime transport DATA ACCESS is enforced by the DO grant, so the hook\n // is \"allowed\" client-side UNLESS the grant provider surfaced a TERMINAL access\n // denial (ChatAccessDeniedError → stable 'access-denied' code). That single case\n // maps to allowed:false so ChatShell renders its no-access surface instead of an\n // eternal loader; a transient close / 4403-revoke keeps allowed:true and rides the\n // reconnect/disconnected banner. Otherwise accessMode is presentation-only here.\n allowed: state.lastErrorCode !== \"access-denied\",\n // Derive initial loading from authoritative-data completion, NOT connection status:\n // a socket can be 'open' with no snapshot yet, and a post-load reconnect must not\n // fall back into the opening state. `hasLoadedInitialData` encodes the full table.\n isInitialLoading: !state.hasLoadedInitialData,\n messages: state.messages,\n fetchOlder,\n hasOlder: state.hasOlder,\n isFetchingOlder: state.isFetchingOlder,\n status: state.status,\n lastErrorCode: state.lastErrorCode,\n typing: state.typing,\n presence: state.presence,\n send,\n retrySend,\n readAck,\n signalTyping,\n presenceSubscribe,\n presenceUnsubscribe,\n };\n}\n\n/** A client message id for optimistic-send idempotency (SQLite unique (senderUid, clientMessageId)). */\nfunction makeClientMessageId(): string {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) return c.randomUUID();\n return `cmid-${Date.now()}-${Math.random().toString(36).slice(2)}`;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ChatShell.d.ts","sourceRoot":"","sources":["../../src/ui/ChatShell.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,OAAO,KAAK,EAAE,aAAa,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AACtG,OAAO,KAAK,EACV,cAAc,EACd,oBAAoB,EACpB,uBAAuB,EACxB,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"ChatShell.d.ts","sourceRoot":"","sources":["../../src/ui/ChatShell.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,OAAO,KAAK,EAAE,aAAa,EAAE,gBAAgB,EAAE,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AACtG,OAAO,KAAK,EACV,cAAc,EACd,oBAAoB,EACpB,uBAAuB,EACxB,MAAM,aAAa,CAAC;AAWrB,MAAM,MAAM,cAAc,GAAG;IAC3B,MAAM,EAAE,cAAc,CAAC;IAGvB,MAAM,CAAC,EAAE,KAAK,CAAC,SAAS,CAAC;IAKzB,MAAM,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,aAAa,CAAC,SAAS,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IAG7E,aAAa,CAAC,EAAE,CAAC,CAAC,EAAE,GAAG,KAAK,KAAK,CAAC,SAAS,CAAC;IAC5C,gBAAgB,CAAC,EAAE,uBAAuB,CAAC;IAC3C,QAAQ,CAAC,EAAE,kBAAkB,CAAC;IAG9B,gBAAgB,CAAC,EAAE,oBAAoB,CAAC;IACxC,cAAc,CAAC,EAAE,gBAAgB,CAAC;IAClC,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,SAAS,CAAC,EAAE,OAAO,CAAC;IAGpB,mBAAmB,CAAC,EAAE,MAAM,KAAK,CAAC,SAAS,CAAC;IAC5C,mBAAmB,CAAC,EAAE,MAAM,KAAK,CAAC,SAAS,CAAC;IAC5C,kDAAkD;IAClD,YAAY,CAAC,EAAE,MAAM,KAAK,CAAC,SAAS,CAAC;IAGrC,aAAa,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,KAAK,IAAI,CAAC;IAGhE,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAE3B;;;6FAGyF;IACzF,UAAU,CAAC,EAAE,OAAO,CAAC;IACrB;qDACiD;IACjD,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B,CAAC;AA0BF;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,cAAc,qBAK9C"}
|
package/dist/ui/ChatShell.js
CHANGED
|
@@ -3,6 +3,7 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
|
3
3
|
import * as React from "react";
|
|
4
4
|
import { Card, CardHeader, CardContent, CardFooter, Skeleton } from "@ttt-productions/ui-core/react";
|
|
5
5
|
import { KeyboardAvoidingView } from "@ttt-productions/mobile-core/react";
|
|
6
|
+
import { Loader2 } from "lucide-react";
|
|
6
7
|
import { useChatMessages } from "../hooks/useChatMessages.js";
|
|
7
8
|
import { useRealtimeChatMessages } from "../realtime/useRealtimeChatMessages.js";
|
|
8
9
|
import { MessageList } from "./MessageList.js";
|
|
@@ -126,14 +127,15 @@ function ChatShellView(props) {
|
|
|
126
127
|
return _jsx("div", { className: "p-4 text-sm opacity-70", children: "You don't have access to this thread." });
|
|
127
128
|
}
|
|
128
129
|
if (isInitialLoading) {
|
|
129
|
-
//
|
|
130
|
-
//
|
|
131
|
-
//
|
|
132
|
-
//
|
|
133
|
-
//
|
|
134
|
-
//
|
|
135
|
-
//
|
|
136
|
-
|
|
130
|
+
// Before the first authoritative snapshot/history result, show an HONEST working
|
|
131
|
+
// state — a visible "Opening chat…" spinner in a polite live region — NOT a blank
|
|
132
|
+
// parchment/skeleton box (which read as an empty chat) and NOT the reconnect banner
|
|
133
|
+
// (which must not compete with the initial-opening message). Only the MessageList
|
|
134
|
+
// region is replaced: the consumer's header + actions + the three render-slots +
|
|
135
|
+
// footer all still render, because a consumer that hangs critical controls off those
|
|
136
|
+
// slots (e.g. the guild-invite binding-agreement Agree/Decline/stake-share controls)
|
|
137
|
+
// must work whether or not realtime chat has connected yet (F4.1).
|
|
138
|
+
return (_jsxs(Card, { className: cardClassName, children: [(header || handlers) && (_jsxs(CardHeader, { className: "flex flex-row items-start justify-between gap-4 space-y-0", children: [_jsx("div", { children: header }), _jsx("div", { className: "flex flex-col items-end gap-2", children: _jsx(ThreadActions, { threadId: config.threadId, isAdmin: config.isAdmin, handlers: handlers }) })] })), renderAboveMessages && (_jsx("div", { className: "border-b", children: renderAboveMessages() })), _jsx(CardContent, { className: contentClassName, children: _jsxs("div", { className: "flex flex-col items-center justify-center gap-2 py-12 text-sm text-muted-foreground", role: "status", "aria-live": "polite", children: [_jsx(Loader2, { className: "h-5 w-5 animate-spin", "aria-hidden": "true" }), _jsx("span", { children: "Opening chat\u2026" })] }) }), renderBelowMessages && (_jsx("div", { className: "border-t", children: renderBelowMessages() })), renderFooter ? (_jsx(CardFooter, { className: "border-t", children: renderFooter() })) : (_jsx(CardFooter, { className: "border-t", children: _jsx(Skeleton, { className: "h-10 w-full" }) }))] }));
|
|
137
139
|
}
|
|
138
140
|
return (_jsxs(Card, { className: cardClassName, children: [(header || handlers) && (_jsxs(CardHeader, { className: "flex flex-row items-start justify-between gap-4 space-y-0", children: [_jsx("div", { children: header }), _jsx("div", { className: "flex flex-col items-end gap-2", children: _jsx(ThreadActions, { threadId: config.threadId, isAdmin: config.isAdmin, handlers: handlers }) })] })), _jsx(ChatConnectionBanner, { status: status }), renderAboveMessages && (_jsx("div", { className: "border-b", children: renderAboveMessages() })), _jsx(CardContent, { className: contentClassName, children: _jsx(MessageList, { messages: messages, currentUserId: config.currentUserId, isAdmin: config.isAdmin, isFetchingOlder: isFetchingOlder, hasOlder: hasOlder, onLoadOlder: () => fetchOlder(), renderMessage: renderMessage, messageRenderers: messageRenderers, showScrollToBottom: showScrollToBottom, onScrollToBottom: () => setShowScrollToBottom(false), onAtBottomChange: setAtBottom, fillHeight: fillHeight, scrollClassName: scrollClassName, handlers: handlers, onSenderClick: onSenderClick, onRetrySend: retrySend }) }), renderBelowMessages && (_jsx("div", { className: "border-t", children: renderBelowMessages() })), renderFooter ? (_jsx(CardFooter, { className: "border-t", children: renderFooter() })) : (_jsxs(CardFooter, { className: "border-t flex-col items-stretch gap-1", children: [_jsx(TypingIndicator, { typing: typing }), _jsx(KeyboardAvoidingView, { padding: true, offset: 8, className: "w-full", children: _jsx(Composer, { onSend: send, onTyping: signalTyping, attachmentConfig: attachmentConfig, sendAttachment: sendAttachment, disabled: composerDisabled, autoFocus: autoFocus, placeholder: composerPlaceholder, mentionConfig: config.mentionConfig }) })] }))] }));
|
|
139
141
|
}
|
package/dist/ui/ChatShell.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ChatShell.js","sourceRoot":"","sources":["../../src/ui/ChatShell.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAEb,OAAO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E,MAAM,CAAC,aAAa,GACnC,GACmB,IACZ,CACd,IACI,CACR,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAS,oBAAoB,CAAC,EAAE,MAAM,EAAuB;IAC3D,IAAI,MAAM,KAAK,cAAc,IAAI,MAAM,KAAK,QAAQ;QAAE,OAAO,IAAI,CAAC;IAClE,OAAO,CACL,cACE,SAAS,EAAC,yEAAyE,EACnF,IAAI,EAAC,QAAQ,eACH,QAAQ,YAEjB,MAAM,KAAK,cAAc;YACxB,CAAC,CAAC,wCAAwC;YAC1C,CAAC,CAAC,6CAA6C,GAC7C,CACP,CAAC;AACJ,CAAC;AAED;0EAC0E;AAC1E,SAAS,eAAe,CAAC,EAAE,MAAM,EAAyB;IACxD,IAAI,CAAC,MAAM,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IAChD,OAAO,CACL,cAAK,SAAS,EAAC,sCAAsC,eAAW,QAAQ,YACrE,MAAM,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC,CAAC,4BAA4B,GACtE,CACP,CAAC;AACJ,CAAC","sourcesContent":["\"use client\";\n\nimport * as React from \"react\";\nimport type { ChatMessageV1, SendAttachmentFn, ModerationHandlers } from \"@ttt-productions/chat-core\";\nimport type {\n ChatCoreConfig,\n ChatAttachmentConfig,\n MessageRendererRegistry,\n} from \"../types.js\";\nimport { Card, CardHeader, CardContent, CardFooter, Skeleton } from \"@ttt-productions/ui-core/react\";\nimport { KeyboardAvoidingView } from \"@ttt-productions/mobile-core/react\";\nimport { useChatMessages } from \"../hooks/useChatMessages.js\";\nimport { useRealtimeChatMessages } from \"../realtime/useRealtimeChatMessages.js\";\nimport type { RealtimeChatClient } from \"../realtime/transport.js\";\nimport { MessageList } from \"./MessageList.js\";\nimport { Composer } from \"./Composer.js\";\nimport { ThreadActions } from \"./menus.js\";\n\nexport type ChatShellProps = {\n config: ChatCoreConfig;\n\n // Header\n header?: React.ReactNode;\n\n // Send handler — text-only. On the realtime transport this is OPTIONAL: the\n // shell sends through the DO socket. If provided, it is still called (so a\n // consumer can mirror to analytics), but the socket send is authoritative.\n onSend?: (text: string, replyTo?: ChatMessageV1[\"replyTo\"]) => Promise<void>;\n\n // Message rendering\n renderMessage?: (m: any) => React.ReactNode;\n messageRenderers?: MessageRendererRegistry;\n handlers?: ModerationHandlers;\n\n // Composer attachment config\n attachmentConfig?: ChatAttachmentConfig;\n sendAttachment?: SendAttachmentFn;\n composerPlaceholder?: string;\n autoFocus?: boolean;\n\n // Three render slots\n renderAboveMessages?: () => React.ReactNode;\n renderBelowMessages?: () => React.ReactNode;\n /** If provided, replaces the Composer entirely */\n renderFooter?: () => React.ReactNode;\n\n // Sender interaction\n onSenderClick?: (senderId: string, displayName: string) => void;\n\n // Disable\n composerDisabled?: boolean;\n\n /** Fill the parent's height instead of the default fixed-height card. Lays the Card out\n * as `flex flex-col h-full` with the message list flexing to fill (scrolls inside), so a\n * full-height page panel doesn't grow unbounded or waste space on a fixed 400px box.\n * The consumer must give ChatShell a bounded-height parent (e.g. an `h-full` panel). */\n fillHeight?: boolean;\n /** Advanced override for the scrollable region's class (forwarded to MessageList).\n * Usually unnecessary — prefer `fillHeight`. */\n scrollClassName?: string;\n};\n\n/** The resolved data a transport hook hands the presentational view. */\ntype ResolvedChat = {\n allowed: boolean;\n isInitialLoading: boolean;\n messages: ChatMessageV1[];\n fetchOlder: () => Promise<void>;\n hasOlder: boolean;\n isFetchingOlder: boolean;\n /** The send handler the Composer calls (socket send on realtime, prop on firestore). */\n send: (text: string, replyTo?: ChatMessageV1[\"replyTo\"]) => Promise<void>;\n /** Retry a failed realtime send by its original clientMessageId (realtime only;\n * absent on firestore). Wired to MessageItemDefault's failed-bubble retry. */\n retrySend?: (clientMessageId: string) => void;\n /** Advance the authoritative read cursor (realtime only; absent on the firestore path).\n * Returns whether the ack was actually sent so the caller advances its local cursor only on success (M2). */\n readAck?: (latestSeq: number, focused: boolean) => boolean;\n /** Realtime connection status — drives the disconnected banner (R13). Absent on firestore. */\n status?: string;\n /** uids currently typing (realtime only) — drives the typing indicator (R14). */\n typing?: string[];\n /** Signal the local user is typing (coalesced by the transport). Wired to the Composer (R14). */\n signalTyping?: () => void;\n};\n\n/**\n * ChatShell dispatches on `config.transport`. Hooks must be unconditional, so the\n * two transports live in separate inner components (each calls exactly ONE data\n * hook) and both render the shared presentational `ChatShellView`. The default\n * (undefined / 'firestore') transport is byte-for-byte the previous behavior.\n */\nexport function ChatShell(props: ChatShellProps) {\n if (props.config.transport === \"realtime\") {\n return <RealtimeChatShell {...props} />;\n }\n return <FirestoreChatShell {...props} />;\n}\n\nfunction FirestoreChatShell(props: ChatShellProps) {\n const { config, onSend } = props;\n const r = useChatMessages(config);\n const send = React.useCallback(\n async (text: string, replyTo?: ChatMessageV1[\"replyTo\"]) => {\n if (onSend) await onSend(text, replyTo);\n },\n [onSend],\n );\n return <ChatShellView {...props} resolved={{ ...r, send }} />;\n}\n\nfunction RealtimeChatShell(props: ChatShellProps) {\n const { config, onSend } = props;\n const client = config.realtime?.client as RealtimeChatClient | undefined;\n if (!client) {\n throw new Error(\n \"[ChatShell] transport 'realtime' requires config.realtime.client (createRealtimeChatClient(...))\",\n );\n }\n const r = useRealtimeChatMessages(client);\n const send = React.useCallback(\n async (text: string, replyTo?: ChatMessageV1[\"replyTo\"]) => {\n // Map the UI replyTo (messageId-based) to the wire replyTo (seq + preview).\n const wireReply =\n replyTo && replyTo.messageId\n ? { messageSeq: Number(replyTo.messageId), preview: replyTo.messagePreview ?? \"\" }\n : null;\n const ok = r.send(text, Number.isFinite(wireReply?.messageSeq) ? wireReply : null);\n // C-B8: surface a closed-socket failure so the Composer keeps the user's text\n // instead of clearing it on a no-op send.\n if (!ok) throw new Error(\"chat-send-failed\");\n if (onSend) await onSend(text, replyTo); // optional mirror\n },\n [r, onSend],\n );\n return (\n <ChatShellView\n {...props}\n resolved={{\n allowed: r.allowed,\n isInitialLoading: r.isInitialLoading,\n messages: r.messages,\n fetchOlder: r.fetchOlder,\n hasOlder: r.hasOlder,\n isFetchingOlder: r.isFetchingOlder,\n send,\n retrySend: r.retrySend,\n readAck: r.readAck,\n status: r.status,\n typing: r.typing,\n signalTyping: r.signalTyping,\n }}\n />\n );\n}\n\nfunction ChatShellView(props: ChatShellProps & { resolved: ResolvedChat }) {\n const {\n config,\n header,\n renderMessage,\n messageRenderers,\n handlers,\n attachmentConfig,\n sendAttachment,\n composerPlaceholder,\n autoFocus = false,\n renderAboveMessages,\n renderBelowMessages,\n renderFooter,\n onSenderClick,\n composerDisabled,\n fillHeight = false,\n scrollClassName,\n resolved,\n } = props;\n\n const { allowed, isInitialLoading, messages, fetchOlder, hasOlder, isFetchingOlder, send, retrySend, readAck, status, typing, signalTyping } = resolved;\n\n const [showScrollToBottom, setShowScrollToBottom] = React.useState(false);\n const [atBottom, setAtBottom] = React.useState(true);\n const [focused, setFocused] = React.useState(true);\n const lastAckedRef = React.useRef(0);\n const leaseHeldRef = React.useRef(false);\n\n // The latest authoritative seq currently rendered (optimistic rows have no seq).\n const latestSeq = React.useMemo(() => {\n let max = 0;\n for (const m of messages) {\n const seq = typeof m.meta?.seq === \"number\" ? (m.meta?.seq as number) : 0;\n if (seq > max) max = seq;\n }\n return max;\n }, [messages]);\n\n // Track tab focus/visibility so the read-ack \"focused\" lease releases on blur/hide.\n React.useEffect(() => {\n const compute = () =>\n typeof document === \"undefined\" ||\n (document.visibilityState !== \"hidden\" && (typeof document.hasFocus !== \"function\" || document.hasFocus()));\n setFocused(compute());\n const onChange = () => setFocused(compute());\n window.addEventListener(\"focus\", onChange);\n window.addEventListener(\"blur\", onChange);\n document.addEventListener(\"visibilitychange\", onChange);\n return () => {\n window.removeEventListener(\"focus\", onChange);\n window.removeEventListener(\"blur\", onChange);\n document.removeEventListener(\"visibilitychange\", onChange);\n };\n }, []);\n\n // C-B6: advance the authoritative read cursor when the reader is actually at the\n // latest message (channel mounted + tab focused + scrolled to bottom); release the\n // focus lease exactly once when they stop. No-op on the firestore path (no readAck).\n React.useEffect(() => {\n if (!readAck || latestSeq <= 0) return;\n if (focused && atBottom) {\n leaseHeldRef.current = true;\n if (latestSeq > lastAckedRef.current) {\n // Advance the local marker ONLY if the frame was actually sent — a drop during a\n // disconnect window must stay un-acked so it retries (the client also re-sends the\n // cursor on reconnect). (M2)\n if (readAck(latestSeq, true)) lastAckedRef.current = latestSeq;\n }\n } else if (leaseHeldRef.current) {\n leaseHeldRef.current = false;\n readAck(latestSeq, false);\n }\n }, [readAck, latestSeq, atBottom, focused]);\n\n // In fill mode the Card flexes to its parent's height and the message list fills the\n // space between header and composer; otherwise it's the default natural-height card.\n const cardClassName = fillHeight ? \"w-full flex flex-col h-full min-h-0\" : \"w-full\";\n const contentClassName = fillHeight ? \"p-0 flex-1 min-h-0 flex flex-col\" : \"p-0\";\n\n if (!allowed) {\n return <div className=\"p-4 text-sm opacity-70\">You don't have access to this thread.</div>;\n }\n\n if (isInitialLoading) {\n // Render the consumer's header + render-slots even while the message list is still\n // loading — ONLY the MessageList region is skeletonized. Previously this early-return\n // was an all-skeleton Card that SWALLOWED renderAboveMessages/renderBelowMessages/\n // renderFooter, so a consumer that hangs critical controls off those slots (e.g. the\n // guild-invite binding-agreement Agree/Decline/stake-share controls) showed nothing for\n // the entire connect window while the realtime socket sat in 'connecting' (F4.1). The\n // agreement flow must work whether or not realtime chat is connected.\n return (\n <Card className={cardClassName}>\n {(header || handlers) && (\n <CardHeader className=\"flex flex-row items-start justify-between gap-4 space-y-0\">\n <div>{header}</div>\n <div className=\"flex flex-col items-end gap-2\">\n <ThreadActions threadId={config.threadId} isAdmin={config.isAdmin} handlers={handlers} />\n </div>\n </CardHeader>\n )}\n <ChatConnectionBanner status={status} />\n {renderAboveMessages && (\n <div className=\"border-b\">{renderAboveMessages()}</div>\n )}\n <CardContent className={contentClassName}>\n <Skeleton className=\"h-[240px] w-full\" />\n </CardContent>\n {renderBelowMessages && (\n <div className=\"border-t\">{renderBelowMessages()}</div>\n )}\n {renderFooter ? (\n <CardFooter className=\"border-t\">{renderFooter()}</CardFooter>\n ) : (\n <CardFooter className=\"border-t\">\n <Skeleton className=\"h-10 w-full\" />\n </CardFooter>\n )}\n </Card>\n );\n }\n\n return (\n <Card className={cardClassName}>\n {(header || handlers) && (\n <CardHeader className=\"flex flex-row items-start justify-between gap-4 space-y-0\">\n <div>{header}</div>\n <div className=\"flex flex-col items-end gap-2\">\n <ThreadActions threadId={config.threadId} isAdmin={config.isAdmin} handlers={handlers} />\n </div>\n </CardHeader>\n )}\n\n {/* R13: a disconnected/reconnecting banner so a configured-but-unreachable Worker\n never presents a healthy-looking empty thread. Only the realtime path sets `status`. */}\n <ChatConnectionBanner status={status} />\n\n {renderAboveMessages && (\n <div className=\"border-b\">{renderAboveMessages()}</div>\n )}\n\n <CardContent className={contentClassName}>\n <MessageList\n messages={messages}\n currentUserId={config.currentUserId}\n isAdmin={config.isAdmin}\n isFetchingOlder={isFetchingOlder}\n hasOlder={hasOlder}\n onLoadOlder={() => fetchOlder()}\n renderMessage={renderMessage}\n messageRenderers={messageRenderers}\n showScrollToBottom={showScrollToBottom}\n onScrollToBottom={() => setShowScrollToBottom(false)}\n onAtBottomChange={setAtBottom}\n fillHeight={fillHeight}\n scrollClassName={scrollClassName}\n handlers={handlers}\n onSenderClick={onSenderClick}\n onRetrySend={retrySend}\n />\n </CardContent>\n\n {renderBelowMessages && (\n <div className=\"border-t\">{renderBelowMessages()}</div>\n )}\n\n {renderFooter ? (\n <CardFooter className=\"border-t\">\n {renderFooter()}\n </CardFooter>\n ) : (\n <CardFooter className=\"border-t flex-col items-stretch gap-1\">\n {/* R14: typing dots above the composer (realtime only — `typing` is undefined on firestore). */}\n <TypingIndicator typing={typing} />\n <KeyboardAvoidingView padding offset={8} className=\"w-full\">\n <Composer\n onSend={send}\n onTyping={signalTyping}\n attachmentConfig={attachmentConfig}\n sendAttachment={sendAttachment}\n disabled={composerDisabled}\n autoFocus={autoFocus}\n placeholder={composerPlaceholder}\n mentionConfig={config.mentionConfig}\n />\n </KeyboardAvoidingView>\n </CardFooter>\n )}\n </Card>\n );\n}\n\n/**\n * R13 — connection-state banner. The realtime path sets `status`; once the first\n * snapshot has loaded (ChatShellView is past `isInitialLoading`), a dropped/unreachable\n * socket surfaces here instead of a silently-empty thread. Renders nothing on the\n * firestore path (`status` undefined) or while live (`open`).\n */\nfunction ChatConnectionBanner({ status }: { status?: string }) {\n if (status !== \"reconnecting\" && status !== \"closed\") return null;\n return (\n <div\n className=\"px-3 py-1.5 text-xs text-center bg-muted text-muted-foreground border-b\"\n role=\"status\"\n aria-live=\"polite\"\n >\n {status === \"reconnecting\"\n ? \"Reconnecting… messages may be delayed.\"\n : \"Disconnected — messages may be out of date.\"}\n </div>\n );\n}\n\n/** R14 — typing indicator. `typing` is the set of OTHER users typing (the transport\n * excludes the local user). Generic copy (no name resolution) for v1. */\nfunction TypingIndicator({ typing }: { typing?: string[] }) {\n if (!typing || typing.length === 0) return null;\n return (\n <div className=\"text-xs italic text-muted-foreground\" aria-live=\"polite\">\n {typing.length === 1 ? \"Someone is typing…\" : \"Several people are typing…\"}\n </div>\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"ChatShell.js","sourceRoot":"","sources":["../../src/ui/ChatShell.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAEb,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAO/B,OAAO,EAAE,IAAI,EAAE,UAAU,EAAE,WAAW,EAAE,UAAU,EAAE,QAAQ,EAAE,MAAM,gCAAgC,CAAC;AACrG,OAAO,EAAE,oBAAoB,EAAE,MAAM,oCAAoC,CAAC;AAC1E,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAE,eAAe,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,EAAE,uBAAuB,EAAE,MAAM,wCAAwC,CAAC;AAEjF,OAAO,EAAE,WAAW,EAAE,MAAM,kB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EAAC,QAAQ,eACH,QAAQ,YAEjB,MAAM,KAAK,cAAc;YACxB,CAAC,CAAC,wCAAwC;YAC1C,CAAC,CAAC,6CAA6C,GAC7C,CACP,CAAC;AACJ,CAAC;AAED;0EAC0E;AAC1E,SAAS,eAAe,CAAC,EAAE,MAAM,EAAyB;IACxD,IAAI,CAAC,MAAM,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IAChD,OAAO,CACL,cAAK,SAAS,EAAC,sCAAsC,eAAW,QAAQ,YACrE,MAAM,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,oBAAoB,CAAC,CAAC,CAAC,4BAA4B,GACtE,CACP,CAAC;AACJ,CAAC","sourcesContent":["\"use client\";\n\nimport * as React from \"react\";\nimport type { ChatMessageV1, SendAttachmentFn, ModerationHandlers } from \"@ttt-productions/chat-core\";\nimport type {\n ChatCoreConfig,\n ChatAttachmentConfig,\n MessageRendererRegistry,\n} from \"../types.js\";\nimport { Card, CardHeader, CardContent, CardFooter, Skeleton } from \"@ttt-productions/ui-core/react\";\nimport { KeyboardAvoidingView } from \"@ttt-productions/mobile-core/react\";\nimport { Loader2 } from \"lucide-react\";\nimport { useChatMessages } from \"../hooks/useChatMessages.js\";\nimport { useRealtimeChatMessages } from \"../realtime/useRealtimeChatMessages.js\";\nimport type { RealtimeChatClient } from \"../realtime/transport.js\";\nimport { MessageList } from \"./MessageList.js\";\nimport { Composer } from \"./Composer.js\";\nimport { ThreadActions } from \"./menus.js\";\n\nexport type ChatShellProps = {\n config: ChatCoreConfig;\n\n // Header\n header?: React.ReactNode;\n\n // Send handler — text-only. On the realtime transport this is OPTIONAL: the\n // shell sends through the DO socket. If provided, it is still called (so a\n // consumer can mirror to analytics), but the socket send is authoritative.\n onSend?: (text: string, replyTo?: ChatMessageV1[\"replyTo\"]) => Promise<void>;\n\n // Message rendering\n renderMessage?: (m: any) => React.ReactNode;\n messageRenderers?: MessageRendererRegistry;\n handlers?: ModerationHandlers;\n\n // Composer attachment config\n attachmentConfig?: ChatAttachmentConfig;\n sendAttachment?: SendAttachmentFn;\n composerPlaceholder?: string;\n autoFocus?: boolean;\n\n // Three render slots\n renderAboveMessages?: () => React.ReactNode;\n renderBelowMessages?: () => React.ReactNode;\n /** If provided, replaces the Composer entirely */\n renderFooter?: () => React.ReactNode;\n\n // Sender interaction\n onSenderClick?: (senderId: string, displayName: string) => void;\n\n // Disable\n composerDisabled?: boolean;\n\n /** Fill the parent's height instead of the default fixed-height card. Lays the Card out\n * as `flex flex-col h-full` with the message list flexing to fill (scrolls inside), so a\n * full-height page panel doesn't grow unbounded or waste space on a fixed 400px box.\n * The consumer must give ChatShell a bounded-height parent (e.g. an `h-full` panel). */\n fillHeight?: boolean;\n /** Advanced override for the scrollable region's class (forwarded to MessageList).\n * Usually unnecessary — prefer `fillHeight`. */\n scrollClassName?: string;\n};\n\n/** The resolved data a transport hook hands the presentational view. */\ntype ResolvedChat = {\n allowed: boolean;\n isInitialLoading: boolean;\n messages: ChatMessageV1[];\n fetchOlder: () => Promise<void>;\n hasOlder: boolean;\n isFetchingOlder: boolean;\n /** The send handler the Composer calls (socket send on realtime, prop on firestore). */\n send: (text: string, replyTo?: ChatMessageV1[\"replyTo\"]) => Promise<void>;\n /** Retry a failed realtime send by its original clientMessageId (realtime only;\n * absent on firestore). Wired to MessageItemDefault's failed-bubble retry. */\n retrySend?: (clientMessageId: string) => void;\n /** Advance the authoritative read cursor (realtime only; absent on the firestore path).\n * Returns whether the ack was actually sent so the caller advances its local cursor only on success (M2). */\n readAck?: (latestSeq: number, focused: boolean) => boolean;\n /** Realtime connection status — drives the disconnected banner (R13). Absent on firestore. */\n status?: string;\n /** uids currently typing (realtime only) — drives the typing indicator (R14). */\n typing?: string[];\n /** Signal the local user is typing (coalesced by the transport). Wired to the Composer (R14). */\n signalTyping?: () => void;\n};\n\n/**\n * ChatShell dispatches on `config.transport`. Hooks must be unconditional, so the\n * two transports live in separate inner components (each calls exactly ONE data\n * hook) and both render the shared presentational `ChatShellView`. The default\n * (undefined / 'firestore') transport is byte-for-byte the previous behavior.\n */\nexport function ChatShell(props: ChatShellProps) {\n if (props.config.transport === \"realtime\") {\n return <RealtimeChatShell {...props} />;\n }\n return <FirestoreChatShell {...props} />;\n}\n\nfunction FirestoreChatShell(props: ChatShellProps) {\n const { config, onSend } = props;\n const r = useChatMessages(config);\n const send = React.useCallback(\n async (text: string, replyTo?: ChatMessageV1[\"replyTo\"]) => {\n if (onSend) await onSend(text, replyTo);\n },\n [onSend],\n );\n return <ChatShellView {...props} resolved={{ ...r, send }} />;\n}\n\nfunction RealtimeChatShell(props: ChatShellProps) {\n const { config, onSend } = props;\n const client = config.realtime?.client as RealtimeChatClient | undefined;\n if (!client) {\n throw new Error(\n \"[ChatShell] transport 'realtime' requires config.realtime.client (createRealtimeChatClient(...))\",\n );\n }\n const r = useRealtimeChatMessages(client);\n const send = React.useCallback(\n async (text: string, replyTo?: ChatMessageV1[\"replyTo\"]) => {\n // Map the UI replyTo (messageId-based) to the wire replyTo (seq + preview).\n const wireReply =\n replyTo && replyTo.messageId\n ? { messageSeq: Number(replyTo.messageId), preview: replyTo.messagePreview ?? \"\" }\n : null;\n const ok = r.send(text, Number.isFinite(wireReply?.messageSeq) ? wireReply : null);\n // C-B8: surface a closed-socket failure so the Composer keeps the user's text\n // instead of clearing it on a no-op send.\n if (!ok) throw new Error(\"chat-send-failed\");\n if (onSend) await onSend(text, replyTo); // optional mirror\n },\n [r, onSend],\n );\n return (\n <ChatShellView\n {...props}\n resolved={{\n allowed: r.allowed,\n isInitialLoading: r.isInitialLoading,\n messages: r.messages,\n fetchOlder: r.fetchOlder,\n hasOlder: r.hasOlder,\n isFetchingOlder: r.isFetchingOlder,\n send,\n retrySend: r.retrySend,\n readAck: r.readAck,\n status: r.status,\n typing: r.typing,\n signalTyping: r.signalTyping,\n }}\n />\n );\n}\n\nfunction ChatShellView(props: ChatShellProps & { resolved: ResolvedChat }) {\n const {\n config,\n header,\n renderMessage,\n messageRenderers,\n handlers,\n attachmentConfig,\n sendAttachment,\n composerPlaceholder,\n autoFocus = false,\n renderAboveMessages,\n renderBelowMessages,\n renderFooter,\n onSenderClick,\n composerDisabled,\n fillHeight = false,\n scrollClassName,\n resolved,\n } = props;\n\n const { allowed, isInitialLoading, messages, fetchOlder, hasOlder, isFetchingOlder, send, retrySend, readAck, status, typing, signalTyping } = resolved;\n\n const [showScrollToBottom, setShowScrollToBottom] = React.useState(false);\n const [atBottom, setAtBottom] = React.useState(true);\n const [focused, setFocused] = React.useState(true);\n const lastAckedRef = React.useRef(0);\n const leaseHeldRef = React.useRef(false);\n\n // The latest authoritative seq currently rendered (optimistic rows have no seq).\n const latestSeq = React.useMemo(() => {\n let max = 0;\n for (const m of messages) {\n const seq = typeof m.meta?.seq === \"number\" ? (m.meta?.seq as number) : 0;\n if (seq > max) max = seq;\n }\n return max;\n }, [messages]);\n\n // Track tab focus/visibility so the read-ack \"focused\" lease releases on blur/hide.\n React.useEffect(() => {\n const compute = () =>\n typeof document === \"undefined\" ||\n (document.visibilityState !== \"hidden\" && (typeof document.hasFocus !== \"function\" || document.hasFocus()));\n setFocused(compute());\n const onChange = () => setFocused(compute());\n window.addEventListener(\"focus\", onChange);\n window.addEventListener(\"blur\", onChange);\n document.addEventListener(\"visibilitychange\", onChange);\n return () => {\n window.removeEventListener(\"focus\", onChange);\n window.removeEventListener(\"blur\", onChange);\n document.removeEventListener(\"visibilitychange\", onChange);\n };\n }, []);\n\n // C-B6: advance the authoritative read cursor when the reader is actually at the\n // latest message (channel mounted + tab focused + scrolled to bottom); release the\n // focus lease exactly once when they stop. No-op on the firestore path (no readAck).\n React.useEffect(() => {\n if (!readAck || latestSeq <= 0) return;\n if (focused && atBottom) {\n leaseHeldRef.current = true;\n if (latestSeq > lastAckedRef.current) {\n // Advance the local marker ONLY if the frame was actually sent — a drop during a\n // disconnect window must stay un-acked so it retries (the client also re-sends the\n // cursor on reconnect). (M2)\n if (readAck(latestSeq, true)) lastAckedRef.current = latestSeq;\n }\n } else if (leaseHeldRef.current) {\n leaseHeldRef.current = false;\n readAck(latestSeq, false);\n }\n }, [readAck, latestSeq, atBottom, focused]);\n\n // In fill mode the Card flexes to its parent's height and the message list fills the\n // space between header and composer; otherwise it's the default natural-height card.\n const cardClassName = fillHeight ? \"w-full flex flex-col h-full min-h-0\" : \"w-full\";\n const contentClassName = fillHeight ? \"p-0 flex-1 min-h-0 flex flex-col\" : \"p-0\";\n\n if (!allowed) {\n return <div className=\"p-4 text-sm opacity-70\">You don't have access to this thread.</div>;\n }\n\n if (isInitialLoading) {\n // Before the first authoritative snapshot/history result, show an HONEST working\n // state — a visible \"Opening chat…\" spinner in a polite live region — NOT a blank\n // parchment/skeleton box (which read as an empty chat) and NOT the reconnect banner\n // (which must not compete with the initial-opening message). Only the MessageList\n // region is replaced: the consumer's header + actions + the three render-slots +\n // footer all still render, because a consumer that hangs critical controls off those\n // slots (e.g. the guild-invite binding-agreement Agree/Decline/stake-share controls)\n // must work whether or not realtime chat has connected yet (F4.1).\n return (\n <Card className={cardClassName}>\n {(header || handlers) && (\n <CardHeader className=\"flex flex-row items-start justify-between gap-4 space-y-0\">\n <div>{header}</div>\n <div className=\"flex flex-col items-end gap-2\">\n <ThreadActions threadId={config.threadId} isAdmin={config.isAdmin} handlers={handlers} />\n </div>\n </CardHeader>\n )}\n {renderAboveMessages && (\n <div className=\"border-b\">{renderAboveMessages()}</div>\n )}\n <CardContent className={contentClassName}>\n <div\n className=\"flex flex-col items-center justify-center gap-2 py-12 text-sm text-muted-foreground\"\n role=\"status\"\n aria-live=\"polite\"\n >\n <Loader2 className=\"h-5 w-5 animate-spin\" aria-hidden=\"true\" />\n <span>Opening chat…</span>\n </div>\n </CardContent>\n {renderBelowMessages && (\n <div className=\"border-t\">{renderBelowMessages()}</div>\n )}\n {renderFooter ? (\n <CardFooter className=\"border-t\">{renderFooter()}</CardFooter>\n ) : (\n <CardFooter className=\"border-t\">\n <Skeleton className=\"h-10 w-full\" />\n </CardFooter>\n )}\n </Card>\n );\n }\n\n return (\n <Card className={cardClassName}>\n {(header || handlers) && (\n <CardHeader className=\"flex flex-row items-start justify-between gap-4 space-y-0\">\n <div>{header}</div>\n <div className=\"flex flex-col items-end gap-2\">\n <ThreadActions threadId={config.threadId} isAdmin={config.isAdmin} handlers={handlers} />\n </div>\n </CardHeader>\n )}\n\n {/* R13: a disconnected/reconnecting banner so a configured-but-unreachable Worker\n never presents a healthy-looking empty thread. Only the realtime path sets `status`. */}\n <ChatConnectionBanner status={status} />\n\n {renderAboveMessages && (\n <div className=\"border-b\">{renderAboveMessages()}</div>\n )}\n\n <CardContent className={contentClassName}>\n <MessageList\n messages={messages}\n currentUserId={config.currentUserId}\n isAdmin={config.isAdmin}\n isFetchingOlder={isFetchingOlder}\n hasOlder={hasOlder}\n onLoadOlder={() => fetchOlder()}\n renderMessage={renderMessage}\n messageRenderers={messageRenderers}\n showScrollToBottom={showScrollToBottom}\n onScrollToBottom={() => setShowScrollToBottom(false)}\n onAtBottomChange={setAtBottom}\n fillHeight={fillHeight}\n scrollClassName={scrollClassName}\n handlers={handlers}\n onSenderClick={onSenderClick}\n onRetrySend={retrySend}\n />\n </CardContent>\n\n {renderBelowMessages && (\n <div className=\"border-t\">{renderBelowMessages()}</div>\n )}\n\n {renderFooter ? (\n <CardFooter className=\"border-t\">\n {renderFooter()}\n </CardFooter>\n ) : (\n <CardFooter className=\"border-t flex-col items-stretch gap-1\">\n {/* R14: typing dots above the composer (realtime only — `typing` is undefined on firestore). */}\n <TypingIndicator typing={typing} />\n <KeyboardAvoidingView padding offset={8} className=\"w-full\">\n <Composer\n onSend={send}\n onTyping={signalTyping}\n attachmentConfig={attachmentConfig}\n sendAttachment={sendAttachment}\n disabled={composerDisabled}\n autoFocus={autoFocus}\n placeholder={composerPlaceholder}\n mentionConfig={config.mentionConfig}\n />\n </KeyboardAvoidingView>\n </CardFooter>\n )}\n </Card>\n );\n}\n\n/**\n * R13 — connection-state banner. The realtime path sets `status`; once the first\n * snapshot has loaded (ChatShellView is past `isInitialLoading`), a dropped/unreachable\n * socket surfaces here instead of a silently-empty thread. Renders nothing on the\n * firestore path (`status` undefined) or while live (`open`).\n */\nfunction ChatConnectionBanner({ status }: { status?: string }) {\n if (status !== \"reconnecting\" && status !== \"closed\") return null;\n return (\n <div\n className=\"px-3 py-1.5 text-xs text-center bg-muted text-muted-foreground border-b\"\n role=\"status\"\n aria-live=\"polite\"\n >\n {status === \"reconnecting\"\n ? \"Reconnecting… messages may be delayed.\"\n : \"Disconnected — messages may be out of date.\"}\n </div>\n );\n}\n\n/** R14 — typing indicator. `typing` is the set of OTHER users typing (the transport\n * excludes the local user). Generic copy (no name resolution) for v1. */\nfunction TypingIndicator({ typing }: { typing?: string[] }) {\n if (!typing || typing.length === 0) return null;\n return (\n <div className=\"text-xs italic text-muted-foreground\" aria-live=\"polite\">\n {typing.length === 1 ? \"Someone is typing…\" : \"Several people are typing…\"}\n </div>\n );\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MessageItemDefault.d.ts","sourceRoot":"","sources":["../../src/ui/MessageItemDefault.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAkB,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;
|
|
1
|
+
{"version":3,"file":"MessageItemDefault.d.ts","sourceRoot":"","sources":["../../src/ui/MessageItemDefault.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAkB,kBAAkB,EAAE,MAAM,4BAA4B,CAAC;AAiIpG,MAAM,MAAM,uBAAuB,GAAG;IACpC,CAAC,EAAE,aAAa,CAAC;IACjB,aAAa,EAAE,MAAM,CAAC;IACtB,OAAO,EAAE,OAAO,CAAC;IACjB,QAAQ,CAAC,EAAE,kBAAkB,CAAC;IAG9B,cAAc,CAAC,EAAE,OAAO,CAAC;IAGzB,aAAa,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,KAAK,IAAI,CAAC;IAEhE;;0DAEsD;IACtD,WAAW,CAAC,EAAE,CAAC,eAAe,EAAE,MAAM,KAAK,IAAI,CAAC;CAEjD,CAAC;AAEF,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,uBAAuB,+BAsGhE"}
|
|
@@ -40,8 +40,17 @@ function AttachmentView({ att }) {
|
|
|
40
40
|
}
|
|
41
41
|
// ready (or legacy/absent status) — resolve the display URL from the asset ref.
|
|
42
42
|
const url = resolveAttachmentUrl(att);
|
|
43
|
-
if (!url)
|
|
44
|
-
|
|
43
|
+
if (!url) {
|
|
44
|
+
// Terminal-ready row, but the authorized URL is still SETTLING (the grant/URL
|
|
45
|
+
// resolver has nothing yet). Returning null left only the surrounding message
|
|
46
|
+
// metadata → an observed empty bubble; a broken/grant-less <img> would flash a
|
|
47
|
+
// 403. Render a neutral loading placeholder in the existing loading visual
|
|
48
|
+
// language (spinner + kind-appropriate generic label + "Loading…", never
|
|
49
|
+
// "Sending…", NO filename) and do NOT mount the media/download renderer until a
|
|
50
|
+
// non-empty authorized URL exists. Sender-only pending/processing/failed states
|
|
51
|
+
// above are unchanged — this begins only after a terminal-ready row is received.
|
|
52
|
+
return (_jsxs("div", { className: "chat-attachment-pending", children: [_jsx(Loader2, { className: "h-4 w-4 shrink-0 animate-spin" }), _jsx("span", { className: "truncate", children: getAttachmentLabel(att.type) }), _jsx("span", { className: "chat-attachment-status-label", children: "Loading\u2026" })] }));
|
|
53
|
+
}
|
|
45
54
|
if (att.type === "image") {
|
|
46
55
|
return _jsx(Media, { type: "image", url: url, alt: "Image attachment", className: "chat-attachment-media" });
|
|
47
56
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MessageItemDefault.js","sourceRoot":"","sources":["../../src/ui/MessageItemDefault.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAGb,OAAO,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AACzD,O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V,IACG,CACP,EAEA,CAAC,cAAc,IAAI,CAClB,cAAK,SAAS,EAAC,MAAM,YACnB,KAAC,cAAc,IAAC,SAAS,EAAE,CAAC,CAAC,SAAS,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,QAAQ,GAAI,GAC5E,CACP,IACG,CACP,CAAC;AACJ,CAAC","sourcesContent":["\"use client\";\n\nimport type { ChatMessageV1, ChatAttachment, ModerationHandlers } from \"@ttt-productions/chat-core\";\nimport { MessageText } from \"../mentions/MessageText.js\";\nimport { cn } from \"@ttt-productions/ui-core\";\nimport { Button } from \"@ttt-productions/ui-core/react\";\nimport { MediaViewer } from \"@ttt-productions/media-viewer/react\";\nimport { FileText, Loader2, AlertTriangle } from \"lucide-react\";\nimport { MessageActions } from \"./menus.js\";\nimport { useResolvedSenderName } from \"../context/ChatNameResolverContext.js\";\nimport { useChatAttachmentUrlResolver } from \"../context/ChatAttachmentUrlContext.js\";\nimport { useChatAttachmentMediaComponent } from \"../context/ChatAttachmentMediaContext.js\";\n\n// ============================================\n// Attachment rendering\n// ============================================\n\nfunction getAttachmentLabel(type: ChatAttachment[\"type\"]): string {\n switch (type) {\n case \"image\": return \"Image attachment\";\n case \"video\": return \"Video attachment\";\n case \"audio\": return \"Audio attachment\";\n default: return \"File attachment\";\n }\n}\n\nfunction AttachmentView({ att }: { att: ChatAttachment }) {\n // Display URL is built at render time by the app-injected resolver from\n // att.mediaAssetId — attachments never store URLs (protected-gateway model).\n const resolveAttachmentUrl = useChatAttachmentUrlResolver();\n // App-injected media component (optional) — lets chat attachments ride the\n // app's ONE display path (recovery adapter, diagnostics, telemetry). Falls\n // back to the package's own MediaViewer when no provider is present.\n const Media = useChatAttachmentMediaComponent() ?? MediaViewer;\n // In-flight placeholder — bytes uploaded, processing/moderation pending. No\n // `mediaAssetId` yet. Rendered only to the sender (other participants can't\n // read a pending doc — Firestore rules scope it until `status === 'ready'`).\n if (att.status === \"pending\") {\n return (\n <div className=\"chat-attachment-pending\">\n <Loader2 className=\"h-4 w-4 shrink-0 animate-spin\" />\n <span className=\"truncate\">{getAttachmentLabel(att.type)}</span>\n <span className=\"chat-attachment-status-label\">Sending…</span>\n </div>\n );\n }\n // Processing/moderation rejected the attachment — sender-only.\n if (att.status === \"failed\") {\n return (\n <div className=\"chat-attachment-rejected\">\n <AlertTriangle className=\"h-4 w-4 shrink-0\" />\n <span className=\"truncate\">{getAttachmentLabel(att.type)}</span>\n <span className=\"chat-attachment-status-label\">\n {att.failureReason ?? \"Couldn't send this attachment\"}\n </span>\n </div>\n );\n }\n // ready (or legacy/absent status) — resolve the display URL from the asset ref.\n const url = resolveAttachmentUrl(att);\n if (!url) return null;\n if (att.type === \"image\") {\n return <Media type=\"image\" url={url} alt=\"Image attachment\" className=\"chat-attachment-media\" />;\n }\n if (att.type === \"video\") {\n return <Media type=\"video\" url={url} controls className=\"chat-attachment-media\" />;\n }\n if (att.type === \"audio\") {\n return <Media type=\"audio\" url={url} controls className=\"chat-attachment-media\" />;\n }\n // text/markdown — download link\n return (\n <a\n href={url}\n download={att.name}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className=\"chat-attachment-text-link\"\n >\n <FileText className=\"h-4 w-4 shrink-0\" />\n <span className=\"truncate\">Download attachment</span>\n </a>\n );\n}\n\n// ============================================\n// Reply-to quote\n// ============================================\n\nfunction ReplyQuote({ replyTo }: { replyTo: NonNullable<ChatMessageV1[\"replyTo\"]> }) {\n const replyName = useResolvedSenderName(replyTo.senderId);\n return (\n <div className=\"chat-reply-quote\">\n <span className=\"chat-reply-quote-sender\">{replyName}</span>\n <span className=\"chat-reply-quote-preview\"><MessageText text={replyTo.messagePreview} /></span>\n </div>\n );\n}\n\n// ============================================\n// System message\n// ============================================\n\nfunction SystemMessage({ m }: { m: ChatMessageV1 }) {\n return (\n <div className=\"chat-system-message\">\n {m.text && <span>{m.text}</span>}\n </div>\n );\n}\n\n// ============================================\n// Default message item\n// ============================================\n\nexport type MessageItemDefaultProps = {\n m: ChatMessageV1;\n currentUserId: string;\n isAdmin: boolean;\n handlers?: ModerationHandlers;\n\n // Grouping\n isContinuation?: boolean;\n\n // Sender interaction\n onSenderClick?: (senderId: string, displayName: string) => void;\n\n /** Retry a failed realtime send by its original clientMessageId (wired by\n * ChatShell on the realtime transport; absent on firestore). Enables the\n * retry affordance on a `meta.sendFailed` bubble. */\n onRetrySend?: (clientMessageId: string) => void;\n\n};\n\nexport function MessageItemDefault(props: MessageItemDefaultProps) {\n const { m, currentUserId, isAdmin, handlers, isContinuation, onSenderClick, onRetrySend } = props;\n const senderName = useResolvedSenderName(m.senderId);\n\n // System messages render differently\n if (m.isSystemMessage) {\n return <SystemMessage m={m} />;\n }\n\n const mine = m.senderId === currentUserId;\n\n // Realtime optimistic-send lifecycle (meta is stamped by the channel client):\n // an un-acked echo renders subtly pending; one past the retry/age cap renders a\n // visibly failed bubble with a retry affordance (same clientMessageId — the DO\n // dedups, so a retry can never double-send).\n const sendFailed = m.meta?.sendFailed === true;\n const sendPending = m.meta?.optimistic === true && !sendFailed;\n const clientMessageId =\n typeof m.meta?.clientMessageId === \"string\" ? m.meta.clientMessageId : null;\n\n return (\n <div\n className={cn(\n \"flex flex-col w-fit max-w-[85%]\",\n mine ? \"ml-auto items-end\" : \"mr-auto items-start\",\n isContinuation ? \"chat-continuation-gap\" : \"chat-group-gap\"\n )}\n >\n <div\n className={cn(\n \"chat-bubble\",\n mine ? \"chat-bubble--mine\" : \"chat-bubble--theirs\",\n sendPending && \"chat-bubble--pending\",\n sendFailed && \"chat-bubble--failed\"\n )}\n >\n {!isContinuation && (\n <div className=\"flex items-center gap-2 text-xs opacity-80 mb-1\">\n <span\n className={cn(\"font-medium\", onSenderClick && \"cursor-pointer hover:underline\")}\n onClick={onSenderClick ? () => onSenderClick(m.senderId, senderName) : undefined}\n role={onSenderClick ? \"button\" : undefined}\n tabIndex={onSenderClick ? 0 : undefined}\n onKeyDown={onSenderClick ? (e) => {\n if (e.key === \"Enter\" || e.key === \" \") onSenderClick(m.senderId, senderName);\n } : undefined}\n >\n {senderName}\n </span>\n <span>·</span>\n <span>{new Date(m.createdAt).toLocaleTimeString([], { hour: \"numeric\", minute: \"2-digit\" })}</span>\n </div>\n )}\n\n {m.replyTo && <ReplyQuote replyTo={m.replyTo} />}\n\n {m.text && (\n <p className=\"text-sm whitespace-pre-wrap\">\n <MessageText text={m.text} />\n </p>\n )}\n\n {m.attachment && (\n <div className=\"mt-2\">\n <AttachmentView att={m.attachment} />\n </div>\n )}\n </div>\n\n {/* Send-state status rows render regardless of grouping — a pending/failed\n send must never be indistinguishable from a delivered one. */}\n {sendPending && (\n <div className=\"chat-send-status mt-0.5\" role=\"status\" aria-live=\"polite\">\n <Loader2 className=\"h-3 w-3 shrink-0 animate-spin\" />\n <span>Sending…</span>\n </div>\n )}\n {sendFailed && (\n <div className=\"chat-send-status chat-send-status--failed mt-0.5\" role=\"alert\">\n <AlertTriangle className=\"h-3 w-3 shrink-0\" />\n <span>Couldn't send</span>\n {onRetrySend && clientMessageId && (\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n className=\"h-5 px-1.5 text-[0.6875rem]\"\n onClick={() => onRetrySend(clientMessageId)}\n >\n Retry\n </Button>\n )}\n </div>\n )}\n\n {!isContinuation && (\n <div className=\"mt-1\">\n <MessageActions messageId={m.messageId} isAdmin={isAdmin} handlers={handlers} />\n </div>\n )}\n </div>\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"MessageItemDefault.js","sourceRoot":"","sources":["../../src/ui/MessageItemDefault.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAGb,OAAO,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AACzD,OAAO,EAAE,EAAE,EAAE,MAAM,0BAA0B,CAAC;AAC9C,OAAO,EAAE,MAAM,EAAE,MAAM,gCAAgC,CAAC;AACxD,OAAO,EAAE,WAAW,EAAE,MAAM,qCAAqC,CAAC;AAClE,OAAO,EAAE,QAAQ,EAAE,OAAO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AAM,IACL,IAAI,EAAC,QAAQ,EACb,OAAO,EAAC,OAAO,EACf,IAAI,EAAC,IAAI,EACT,SAAS,EAAC,6BAA6B,EACvC,OAAO,EAAE,GAAG,EAAE,CAAC,WAAW,CAAC,eAAe,CAAC,sBAGpC,CACV,IACG,CACP,EAEA,CAAC,cAAc,IAAI,CAClB,cAAK,SAAS,EAAC,MAAM,YACnB,KAAC,cAAc,IAAC,SAAS,EAAE,CAAC,CAAC,SAAS,EAAE,OAAO,EAAE,OAAO,EAAE,QAAQ,EAAE,QAAQ,GAAI,GAC5E,CACP,IACG,CACP,CAAC;AACJ,CAAC","sourcesContent":["\"use client\";\n\nimport type { ChatMessageV1, ChatAttachment, ModerationHandlers } from \"@ttt-productions/chat-core\";\nimport { MessageText } from \"../mentions/MessageText.js\";\nimport { cn } from \"@ttt-productions/ui-core\";\nimport { Button } from \"@ttt-productions/ui-core/react\";\nimport { MediaViewer } from \"@ttt-productions/media-viewer/react\";\nimport { FileText, Loader2, AlertTriangle } from \"lucide-react\";\nimport { MessageActions } from \"./menus.js\";\nimport { useResolvedSenderName } from \"../context/ChatNameResolverContext.js\";\nimport { useChatAttachmentUrlResolver } from \"../context/ChatAttachmentUrlContext.js\";\nimport { useChatAttachmentMediaComponent } from \"../context/ChatAttachmentMediaContext.js\";\n\n// ============================================\n// Attachment rendering\n// ============================================\n\nfunction getAttachmentLabel(type: ChatAttachment[\"type\"]): string {\n switch (type) {\n case \"image\": return \"Image attachment\";\n case \"video\": return \"Video attachment\";\n case \"audio\": return \"Audio attachment\";\n default: return \"File attachment\";\n }\n}\n\nfunction AttachmentView({ att }: { att: ChatAttachment }) {\n // Display URL is built at render time by the app-injected resolver from\n // att.mediaAssetId — attachments never store URLs (protected-gateway model).\n const resolveAttachmentUrl = useChatAttachmentUrlResolver();\n // App-injected media component (optional) — lets chat attachments ride the\n // app's ONE display path (recovery adapter, diagnostics, telemetry). Falls\n // back to the package's own MediaViewer when no provider is present.\n const Media = useChatAttachmentMediaComponent() ?? MediaViewer;\n // In-flight placeholder — bytes uploaded, processing/moderation pending. No\n // `mediaAssetId` yet. Rendered only to the sender (other participants can't\n // read a pending doc — Firestore rules scope it until `status === 'ready'`).\n if (att.status === \"pending\") {\n return (\n <div className=\"chat-attachment-pending\">\n <Loader2 className=\"h-4 w-4 shrink-0 animate-spin\" />\n <span className=\"truncate\">{getAttachmentLabel(att.type)}</span>\n <span className=\"chat-attachment-status-label\">Sending…</span>\n </div>\n );\n }\n // Processing/moderation rejected the attachment — sender-only.\n if (att.status === \"failed\") {\n return (\n <div className=\"chat-attachment-rejected\">\n <AlertTriangle className=\"h-4 w-4 shrink-0\" />\n <span className=\"truncate\">{getAttachmentLabel(att.type)}</span>\n <span className=\"chat-attachment-status-label\">\n {att.failureReason ?? \"Couldn't send this attachment\"}\n </span>\n </div>\n );\n }\n // ready (or legacy/absent status) — resolve the display URL from the asset ref.\n const url = resolveAttachmentUrl(att);\n if (!url) {\n // Terminal-ready row, but the authorized URL is still SETTLING (the grant/URL\n // resolver has nothing yet). Returning null left only the surrounding message\n // metadata → an observed empty bubble; a broken/grant-less <img> would flash a\n // 403. Render a neutral loading placeholder in the existing loading visual\n // language (spinner + kind-appropriate generic label + \"Loading…\", never\n // \"Sending…\", NO filename) and do NOT mount the media/download renderer until a\n // non-empty authorized URL exists. Sender-only pending/processing/failed states\n // above are unchanged — this begins only after a terminal-ready row is received.\n return (\n <div className=\"chat-attachment-pending\">\n <Loader2 className=\"h-4 w-4 shrink-0 animate-spin\" />\n <span className=\"truncate\">{getAttachmentLabel(att.type)}</span>\n <span className=\"chat-attachment-status-label\">Loading…</span>\n </div>\n );\n }\n if (att.type === \"image\") {\n return <Media type=\"image\" url={url} alt=\"Image attachment\" className=\"chat-attachment-media\" />;\n }\n if (att.type === \"video\") {\n return <Media type=\"video\" url={url} controls className=\"chat-attachment-media\" />;\n }\n if (att.type === \"audio\") {\n return <Media type=\"audio\" url={url} controls className=\"chat-attachment-media\" />;\n }\n // text/markdown — download link\n return (\n <a\n href={url}\n download={att.name}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n className=\"chat-attachment-text-link\"\n >\n <FileText className=\"h-4 w-4 shrink-0\" />\n <span className=\"truncate\">Download attachment</span>\n </a>\n );\n}\n\n// ============================================\n// Reply-to quote\n// ============================================\n\nfunction ReplyQuote({ replyTo }: { replyTo: NonNullable<ChatMessageV1[\"replyTo\"]> }) {\n const replyName = useResolvedSenderName(replyTo.senderId);\n return (\n <div className=\"chat-reply-quote\">\n <span className=\"chat-reply-quote-sender\">{replyName}</span>\n <span className=\"chat-reply-quote-preview\"><MessageText text={replyTo.messagePreview} /></span>\n </div>\n );\n}\n\n// ============================================\n// System message\n// ============================================\n\nfunction SystemMessage({ m }: { m: ChatMessageV1 }) {\n return (\n <div className=\"chat-system-message\">\n {m.text && <span>{m.text}</span>}\n </div>\n );\n}\n\n// ============================================\n// Default message item\n// ============================================\n\nexport type MessageItemDefaultProps = {\n m: ChatMessageV1;\n currentUserId: string;\n isAdmin: boolean;\n handlers?: ModerationHandlers;\n\n // Grouping\n isContinuation?: boolean;\n\n // Sender interaction\n onSenderClick?: (senderId: string, displayName: string) => void;\n\n /** Retry a failed realtime send by its original clientMessageId (wired by\n * ChatShell on the realtime transport; absent on firestore). Enables the\n * retry affordance on a `meta.sendFailed` bubble. */\n onRetrySend?: (clientMessageId: string) => void;\n\n};\n\nexport function MessageItemDefault(props: MessageItemDefaultProps) {\n const { m, currentUserId, isAdmin, handlers, isContinuation, onSenderClick, onRetrySend } = props;\n const senderName = useResolvedSenderName(m.senderId);\n\n // System messages render differently\n if (m.isSystemMessage) {\n return <SystemMessage m={m} />;\n }\n\n const mine = m.senderId === currentUserId;\n\n // Realtime optimistic-send lifecycle (meta is stamped by the channel client):\n // an un-acked echo renders subtly pending; one past the retry/age cap renders a\n // visibly failed bubble with a retry affordance (same clientMessageId — the DO\n // dedups, so a retry can never double-send).\n const sendFailed = m.meta?.sendFailed === true;\n const sendPending = m.meta?.optimistic === true && !sendFailed;\n const clientMessageId =\n typeof m.meta?.clientMessageId === \"string\" ? m.meta.clientMessageId : null;\n\n return (\n <div\n className={cn(\n \"flex flex-col w-fit max-w-[85%]\",\n mine ? \"ml-auto items-end\" : \"mr-auto items-start\",\n isContinuation ? \"chat-continuation-gap\" : \"chat-group-gap\"\n )}\n >\n <div\n className={cn(\n \"chat-bubble\",\n mine ? \"chat-bubble--mine\" : \"chat-bubble--theirs\",\n sendPending && \"chat-bubble--pending\",\n sendFailed && \"chat-bubble--failed\"\n )}\n >\n {!isContinuation && (\n <div className=\"flex items-center gap-2 text-xs opacity-80 mb-1\">\n <span\n className={cn(\"font-medium\", onSenderClick && \"cursor-pointer hover:underline\")}\n onClick={onSenderClick ? () => onSenderClick(m.senderId, senderName) : undefined}\n role={onSenderClick ? \"button\" : undefined}\n tabIndex={onSenderClick ? 0 : undefined}\n onKeyDown={onSenderClick ? (e) => {\n if (e.key === \"Enter\" || e.key === \" \") onSenderClick(m.senderId, senderName);\n } : undefined}\n >\n {senderName}\n </span>\n <span>·</span>\n <span>{new Date(m.createdAt).toLocaleTimeString([], { hour: \"numeric\", minute: \"2-digit\" })}</span>\n </div>\n )}\n\n {m.replyTo && <ReplyQuote replyTo={m.replyTo} />}\n\n {m.text && (\n <p className=\"text-sm whitespace-pre-wrap\">\n <MessageText text={m.text} />\n </p>\n )}\n\n {m.attachment && (\n <div className=\"mt-2\">\n <AttachmentView att={m.attachment} />\n </div>\n )}\n </div>\n\n {/* Send-state status rows render regardless of grouping — a pending/failed\n send must never be indistinguishable from a delivered one. */}\n {sendPending && (\n <div className=\"chat-send-status mt-0.5\" role=\"status\" aria-live=\"polite\">\n <Loader2 className=\"h-3 w-3 shrink-0 animate-spin\" />\n <span>Sending…</span>\n </div>\n )}\n {sendFailed && (\n <div className=\"chat-send-status chat-send-status--failed mt-0.5\" role=\"alert\">\n <AlertTriangle className=\"h-3 w-3 shrink-0\" />\n <span>Couldn't send</span>\n {onRetrySend && clientMessageId && (\n <Button\n type=\"button\"\n variant=\"ghost\"\n size=\"sm\"\n className=\"h-5 px-1.5 text-[0.6875rem]\"\n onClick={() => onRetrySend(clientMessageId)}\n >\n Retry\n </Button>\n )}\n </div>\n )}\n\n {!isContinuation && (\n <div className=\"mt-1\">\n <MessageActions messageId={m.messageId} isAdmin={isAdmin} handlers={handlers} />\n </div>\n )}\n </div>\n );\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ttt-productions/chat-react",
|
|
3
|
-
"version": "0.12.
|
|
3
|
+
"version": "0.12.8",
|
|
4
4
|
"description": "Chat React UI, hooks, and Firebase-client adapter for TTT Productions apps (realtime newest window + infinite older pagination)",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|