@12-apps/chat 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/README.md +153 -2
  2. package/package.json +95 -4
  3. package/prisma/chat.prisma +59 -0
  4. package/prisma/migrations/20261002120000_add_chat/migration.sql +41 -0
  5. package/scripts/sync-chat-schema.mjs +64 -0
  6. package/src/client/api.ts +146 -0
  7. package/src/client/assert.ts +7 -0
  8. package/src/client/copy.ts +43 -0
  9. package/src/client/en-US.ts +17 -0
  10. package/src/client/index.ts +17 -0
  11. package/src/client/locales.ts +12 -0
  12. package/src/client/pt-BR.ts +17 -0
  13. package/src/client/use-chat-thread.ts +232 -0
  14. package/src/core/contact-views.ts +231 -0
  15. package/src/core/contact.ts +333 -0
  16. package/src/core/errors.ts +9 -0
  17. package/src/core/types.ts +82 -0
  18. package/src/index.ts +26 -0
  19. package/src/manifest/index.ts +20 -0
  20. package/src/manifest/native.ts +13 -0
  21. package/src/manifest/server.ts +14 -0
  22. package/src/manifest/web.ts +14 -0
  23. package/src/native/composer.tsx +52 -0
  24. package/src/native/index.ts +16 -0
  25. package/src/native/layout.tsx +60 -0
  26. package/src/react/composer.tsx +48 -0
  27. package/src/react/index.ts +15 -0
  28. package/src/react/layout.tsx +36 -0
  29. package/src/server/context.ts +228 -0
  30. package/src/server/copy.ts +73 -0
  31. package/src/server/db.ts +87 -0
  32. package/src/server/en-US.ts +14 -0
  33. package/src/server/handler.ts +110 -0
  34. package/src/server/index.ts +34 -0
  35. package/src/server/locales.ts +12 -0
  36. package/src/server/pt-BR.ts +14 -0
  37. package/src/server/rate.ts +34 -0
  38. package/src/server/reads.ts +52 -0
  39. package/src/server/routes.ts +119 -0
  40. package/src/server/send.ts +203 -0
  41. package/src/ui/surface.tsx +83 -0
  42. package/src/ui/thread-view.tsx +198 -0
@@ -0,0 +1,14 @@
1
+ import type { ChatServerCopy } from "./copy";
2
+
3
+ /** The routes' sentences in Brazilian Portuguese — pass by hand, never a default. */
4
+ export const PT_BR_CHAT_SERVER_COPY: ChatServerCopy = {
5
+ notFound: "Conversa não encontrada.",
6
+ closed: "Esta conversa foi encerrada. Você ainda pode ler as mensagens.",
7
+ invalidBody: "Não entendemos a mensagem enviada.",
8
+ empty: "Escreva uma mensagem antes de enviar.",
9
+ tooLong: "A mensagem pode ter até {max} caracteres.",
10
+ freeTextDisabled: "Use uma das respostas rápidas.",
11
+ unknownQuickReply: "Essa resposta rápida não está disponível.",
12
+ contactInfo: "Por segurança, não é permitido enviar telefone, e-mail, link ou perfil de rede social.",
13
+ rateLimited: "Muitas mensagens seguidas. Aguarde um pouco e tente de novo.",
14
+ };
@@ -0,0 +1,34 @@
1
+ /**
2
+ * A sliding-window limiter, in process. Enough for what it guards — a person
3
+ * flooding a thread — and deliberately not a distributed quota: several
4
+ * processes each allowing `max` is still a bounded nuisance, and the limit is a
5
+ * courtesy, not a security boundary (the host's guard and `canWrite` are).
6
+ */
7
+ export interface SlidingWindow {
8
+ /** Records a hit and answers whether it fits; a refused hit is not recorded. */
9
+ take(key: string, max: number, windowMs: number, now: number): boolean;
10
+ }
11
+
12
+ /** How many takes between sweeps of keys nobody has hit within their window. */
13
+ const SWEEP_EVERY = 500;
14
+
15
+ export function createSlidingWindow(): SlidingWindow {
16
+ const hits = new Map<string, { at: number[]; windowMs: number }>();
17
+ let takes = 0;
18
+ const sweep = (now: number): void => {
19
+ for (const [key, entry] of hits) {
20
+ if (entry.at.every((at) => now - at >= entry.windowMs)) hits.delete(key);
21
+ }
22
+ };
23
+ return {
24
+ take(key, max, windowMs, now) {
25
+ takes += 1;
26
+ if (takes % SWEEP_EVERY === 0) sweep(now);
27
+ const recent = (hits.get(key)?.at ?? []).filter((at) => now - at < windowMs);
28
+ const fits = recent.length < max;
29
+ if (fits) recent.push(now);
30
+ hits.set(key, { at: recent, windowMs });
31
+ return fits;
32
+ },
33
+ };
34
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Reads a host embeds in its OWN lists — the unread badge on every row of a
3
+ * board, say — without a request per row. Plain functions over the db seam,
4
+ * not routes: the list belongs to the host, the counts to this package.
5
+ */
6
+
7
+ import type { ChatDb } from "./db";
8
+
9
+ export interface UnreadCountsQuery {
10
+ readonly tenantId: string;
11
+ readonly threadKeys: readonly string[];
12
+ /** The reader's role: messages by THIS role never count as unread for it. */
13
+ readonly role: string;
14
+ readonly readerId: string;
15
+ }
16
+
17
+ export interface ChatReads {
18
+ /** Messages by other roles since the reader's marker, per thread key. Keys with no thread answer 0. */
19
+ unreadCounts(query: UnreadCountsQuery): Promise<Record<string, number>>;
20
+ }
21
+
22
+ export function createChatReads(config: { db: () => Promise<ChatDb> }): ChatReads {
23
+ return {
24
+ async unreadCounts(query) {
25
+ const counts: Record<string, number> = Object.fromEntries(query.threadKeys.map((key) => [key, 0]));
26
+ if (query.threadKeys.length === 0) return counts;
27
+ const db = await config.db();
28
+ const threads = await db.chatThread.findMany({
29
+ where: { tenantId: query.tenantId, threadKey: { in: [...query.threadKeys] } },
30
+ });
31
+ const live = threads.filter((thread) => thread.lastMessageAt !== null);
32
+ if (live.length === 0) return counts;
33
+ const markers = await db.chatReadMarker.findMany({
34
+ where: { threadId: { in: live.map((thread) => thread.id) }, role: query.role, readerId: query.readerId },
35
+ });
36
+ const readAt = new Map(markers.map((marker) => [marker.threadId, marker.lastReadAt]));
37
+ await Promise.all(
38
+ live.map(async (thread) => {
39
+ const since = readAt.get(thread.id);
40
+ counts[thread.threadKey] = await db.chatMessage.count({
41
+ where: {
42
+ threadId: thread.id,
43
+ authorRole: { not: query.role },
44
+ ...(since ? { createdAt: { gt: since } } : {}),
45
+ },
46
+ });
47
+ }),
48
+ );
49
+ return counts;
50
+ },
51
+ };
52
+ }
@@ -0,0 +1,119 @@
1
+ /**
2
+ * The three framework-neutral endpoints, mount-relative. The host mounts them
3
+ * once per audience (each with its own `authorize`) under whatever path names
4
+ * the subject — the package never sees what a thread is about.
5
+ *
6
+ * Every handler resolves `config.copy` against `request.locale` itself: the
7
+ * routes are built once per process, and a copy resolved at build time would
8
+ * answer every reader in one language for the life of the process.
9
+ *
10
+ * Reading never writes a thread row: a thread exists once somebody wrote in
11
+ * it, so a read-only viewer opening an empty one leaves nothing behind.
12
+ */
13
+
14
+ import type { ChatThreadPayload } from "../core/types";
15
+ import type { ChatAccess, ChatRoute, ChatServerConfig } from "./context";
16
+ import type { ChatDb, ChatThreadRow } from "./db";
17
+ import { findThread, isResponse, resolve, success, wireMessage, type Resolved } from "./handler";
18
+ import { createSlidingWindow } from "./rate";
19
+ import { sendRoute } from "./send";
20
+
21
+ const DEFAULT_HISTORY = 200;
22
+
23
+ function markerKeyOf(thread: ChatThreadRow, access: ChatAccess) {
24
+ return { threadId_role_readerId: { threadId: thread.id, role: access.role, readerId: access.readerId } };
25
+ }
26
+
27
+ async function unreadFor(db: ChatDb, thread: ChatThreadRow, access: ChatAccess): Promise<number> {
28
+ const marker = await db.chatReadMarker.findUnique({ where: markerKeyOf(thread, access) });
29
+ return db.chatMessage.count({
30
+ where: {
31
+ threadId: thread.id,
32
+ authorRole: { not: access.role },
33
+ ...(marker ? { createdAt: { gt: marker.lastReadAt } } : {}),
34
+ },
35
+ });
36
+ }
37
+
38
+ function threadOf(resolved: Resolved): ChatThreadPayload["thread"] {
39
+ return {
40
+ me: { role: resolved.access.role, label: resolved.role.label },
41
+ canWrite: resolved.access.canWrite,
42
+ freeText: resolved.role.freeText,
43
+ maxLength: resolved.role.maxLength,
44
+ quickReplies: resolved.role.quickReplies,
45
+ };
46
+ }
47
+
48
+ function threadRoute<TActor>(config: ChatServerConfig<TActor>): ChatRoute<TActor> {
49
+ return {
50
+ method: "GET",
51
+ path: "/",
52
+ async handle(request) {
53
+ const resolved = await resolve(config, request);
54
+ if (isResponse(resolved)) return resolved;
55
+ const db = await config.db();
56
+ const thread = await findThread(db, resolved.access);
57
+ if (!thread) return success(200, { thread: threadOf(resolved), messages: [], unread: 0 } satisfies ChatThreadPayload);
58
+ // `id` breaks ties: two messages in the same millisecond keep one order on every read.
59
+ const newestFirst = await db.chatMessage.findMany({
60
+ where: { threadId: thread.id },
61
+ orderBy: [{ createdAt: "desc" }, { id: "desc" }],
62
+ take: config.historyLimit ?? DEFAULT_HISTORY,
63
+ });
64
+ const payload: ChatThreadPayload = {
65
+ thread: threadOf(resolved),
66
+ messages: [...newestFirst].reverse().map((row) => wireMessage(config, row, resolved)),
67
+ unread: await unreadFor(db, thread, resolved.access),
68
+ };
69
+ return success(200, payload);
70
+ },
71
+ };
72
+ }
73
+
74
+ /**
75
+ * How far the reader has seen: the `upTo` the client sends (the newest
76
+ * message it SHOWED), never past now — so a message that arrived after the
77
+ * screen last loaded stays unread instead of being marked read unseen.
78
+ */
79
+ function seenUpTo(body: unknown, now: Date): Date {
80
+ const upTo = typeof body === "object" && body !== null ? (body as { upTo?: unknown }).upTo : undefined;
81
+ const at = typeof upTo === "string" ? new Date(upTo) : null;
82
+ if (!at || Number.isNaN(at.getTime())) return now;
83
+ return at.getTime() < now.getTime() ? at : now;
84
+ }
85
+
86
+ async function moveMarker(db: ChatDb, thread: ChatThreadRow, access: ChatAccess, at: Date): Promise<void> {
87
+ const where = markerKeyOf(thread, access);
88
+ const current = await db.chatReadMarker.findUnique({ where });
89
+ // Never backwards: a slow tab reporting an older screen does not un-read what another tab read.
90
+ if (current && current.lastReadAt.getTime() >= at.getTime()) return;
91
+ await db.chatReadMarker.upsert({
92
+ where,
93
+ create: { threadId: thread.id, role: access.role, readerId: access.readerId, lastReadAt: at },
94
+ update: { lastReadAt: at },
95
+ });
96
+ }
97
+
98
+ function readRoute<TActor>(config: ChatServerConfig<TActor>): ChatRoute<TActor> {
99
+ const clock = config.clock ?? (() => new Date());
100
+ return {
101
+ method: "POST",
102
+ path: "/read",
103
+ async handle(request) {
104
+ const resolved = await resolve(config, request);
105
+ if (isResponse(resolved)) return resolved;
106
+ const { access } = resolved;
107
+ const db = await config.db();
108
+ const thread = await findThread(db, access);
109
+ if (!thread) return success(200, { unread: 0 });
110
+ await moveMarker(db, thread, access, seenUpTo(request.body, clock()));
111
+ return success(200, { unread: await unreadFor(db, thread, access) });
112
+ },
113
+ };
114
+ }
115
+
116
+ export function chatRoutes<TActor>(config: ChatServerConfig<TActor>): ChatRoute<TActor>[] {
117
+ const limiter = createSlidingWindow();
118
+ return [threadRoute(config), sendRoute(config, limiter), readRoute(config)];
119
+ }
@@ -0,0 +1,203 @@
1
+ /**
2
+ * `POST /messages` — the one write, and the order its checks run in:
3
+ *
4
+ * 1. who may write here (`canWrite`);
5
+ * 2. what the body asks to send — a quick reply by key, or free text;
6
+ * 3. the rate limit, BEFORE the content rules, so a refused attempt still
7
+ * spends a slot: a role probing the contact filter with one encoding
8
+ * after another runs out of attempts instead of running the filter for
9
+ * free;
10
+ * 4. the content rules, on the draft alone and on the draft joined to the
11
+ * author's own recent free text, so a number split across messages is
12
+ * the same number. A refusal is reported to the host (`onRefused`): a
13
+ * person who keeps trying is the host's to see.
14
+ */
15
+
16
+ import { detectContactInfoAcross, type ContactKind } from "../core/contact";
17
+ import type { ChatAccess, ChatRoute, ChatServerConfig } from "./context";
18
+ import type { ChatDb, ChatMessageRow } from "./db";
19
+ import { failure, findThread, inBackground, isResponse, openThread, resolve, success, wireMessage, type Resolved } from "./handler";
20
+ import type { ChatResponse } from "./context";
21
+ import type { SlidingWindow } from "./rate";
22
+
23
+ /**
24
+ * The author's own recent free text the contact rules read with a draft —
25
+ * deep enough that a number trickled one digit per message still fits.
26
+ */
27
+ const DEFAULT_LOOKBACK = { messages: 12, windowMs: 10 * 60_000 } as const;
28
+
29
+ /**
30
+ * Characters that draw nothing: format characters (zero-width spaces,
31
+ * joiners, bidi marks), the fillers that are letters to Unicode but blank on
32
+ * screen (Hangul fillers, the braille blank, Khmer inherent vowels), the
33
+ * grapheme joiner and the variation selectors.
34
+ */
35
+ // The combining ones (grapheme joiner, Khmer inherent vowels, variation selectors) sit outside the class, where they cannot attach to a neighbour.
36
+ const INVISIBLE = /[\p{Cf}\u115F\u1160\u2800\u3164\uFFA0]|\u034F|\u17B4|\u17B5|\p{Variation_Selector}/gu;
37
+
38
+ /**
39
+ * Bidi controls, removed before a message is STORED: an override makes the
40
+ * screen show text in another order than the one the filter read
41
+ * (`\u202Emoc.liamg@ana` reads as nothing and shows an address).
42
+ */
43
+ const BIDI_CONTROLS = /[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/g;
44
+
45
+ type Draft = { body: string; quickKey: string | null };
46
+
47
+ function quickDraftOf(quickReply: unknown, { role, copy }: Resolved): Draft | ChatResponse {
48
+ const found = typeof quickReply === "string" ? role.quickReplies.find((entry) => entry.key === quickReply) : undefined;
49
+ return found ? { body: found.text, quickKey: found.key } : failure(422, "unknown_quick_reply", copy.unknownQuickReply);
50
+ }
51
+
52
+ function textDraftOf(text: unknown, { role, copy }: Resolved): Draft | ChatResponse {
53
+ if (typeof text !== "string") return failure(422, "invalid_body", copy.invalidBody);
54
+ if (!role.freeText) return failure(422, "free_text_disabled", copy.freeTextDisabled);
55
+ const trimmed = text.replace(BIDI_CONTROLS, "").trim();
56
+ // Stored otherwise as typed (an emoji's joiners are format characters too),
57
+ // but a message of nothing BUT invisible characters is an empty bubble.
58
+ if (trimmed.replace(INVISIBLE, "").trim() === "") return failure(422, "empty", copy.empty);
59
+ if (trimmed.length > role.maxLength) return failure(422, "too_long", copy.tooLong.replace("{max}", String(role.maxLength)));
60
+ return { body: trimmed, quickKey: null };
61
+ }
62
+
63
+ /** What the body asks to send — a quick reply by key, or free text — or the refusal. */
64
+ function draftOf(body: unknown, resolved: Resolved): Draft | ChatResponse {
65
+ if (typeof body !== "object" || body === null || Array.isArray(body)) {
66
+ return failure(422, "invalid_body", resolved.copy.invalidBody);
67
+ }
68
+ const { body: text, quickReply } = body as { body?: unknown; quickReply?: unknown };
69
+ // `null` reads as absent: a client that always sends both keys is not asking for a quick reply.
70
+ return quickReply !== undefined && quickReply !== null ? quickDraftOf(quickReply, resolved) : textDraftOf(text, resolved);
71
+ }
72
+
73
+ /** The author's own free text inside the lookback, oldest first. */
74
+ async function recentTextOf<TActor>(config: ChatServerConfig<TActor>, db: ChatDb, access: ChatAccess, now: Date): Promise<string[]> {
75
+ const lookback = config.contactLookback ?? DEFAULT_LOOKBACK;
76
+ const thread = await findThread(db, access);
77
+ if (!thread) return [];
78
+ const rows = await db.chatMessage.findMany({
79
+ where: {
80
+ threadId: thread.id,
81
+ authorRole: access.role,
82
+ authorId: access.authorId,
83
+ quickKey: null,
84
+ createdAt: { gt: new Date(now.getTime() - lookback.windowMs) },
85
+ },
86
+ orderBy: [{ createdAt: "desc" }, { id: "desc" }],
87
+ take: lookback.messages,
88
+ });
89
+ return rows.map((row) => row.body).reverse();
90
+ }
91
+
92
+ /** Contact kinds the draft carries, alone or with the author's recent text; `[]` when it may go. */
93
+ async function contactIn<TActor>(config: ChatServerConfig<TActor>, db: ChatDb, draft: Draft, resolved: Resolved, now: Date): Promise<ContactKind[]> {
94
+ const blocked = resolved.role.blockContact;
95
+ // Quick replies are the host's own words, and a role that blocks nothing is not scanned.
96
+ if (draft.quickKey !== null || blocked.length === 0) return [];
97
+ const recent = await recentTextOf(config, db, resolved.access, now);
98
+ return detectContactInfoAcross(recent, draft.body, blocked, config.contactVocabulary);
99
+ }
100
+
101
+ function refuseContact<TActor>(config: ChatServerConfig<TActor>, resolved: Resolved, kinds: ContactKind[]): ChatResponse {
102
+ const { access } = resolved;
103
+ if (config.onRefused) {
104
+ const onRefused = config.onRefused;
105
+ inBackground(config, "onRefused", () =>
106
+ onRefused({ tenantId: access.tenantId, threadKey: access.threadKey, role: access.role, authorId: access.authorId, code: "contact_info", kinds }),
107
+ );
108
+ }
109
+ return failure(422, "contact_info", resolved.copy.contactInfo);
110
+ }
111
+
112
+ function notify<TActor>(config: ChatServerConfig<TActor>, access: ChatAccess, row: ChatMessageRow, label: string): void {
113
+ const onMessage = config.onMessage;
114
+ if (!onMessage) return;
115
+ inBackground(config, "onMessage", () =>
116
+ onMessage({
117
+ tenantId: access.tenantId,
118
+ threadKey: access.threadKey,
119
+ message: {
120
+ id: row.id,
121
+ role: row.authorRole,
122
+ label,
123
+ authorId: row.authorId,
124
+ body: row.body,
125
+ quickKey: row.quickKey,
126
+ createdAt: row.createdAt.toISOString(),
127
+ },
128
+ }),
129
+ );
130
+ }
131
+
132
+ /** One key per author per thread; JSON so no id can contain the separator. */
133
+ function rateKeyOf(access: ChatAccess): string {
134
+ return JSON.stringify([access.tenantId, access.threadKey, access.role, access.authorId]);
135
+ }
136
+
137
+ async function commit<TActor>(config: ChatServerConfig<TActor>, db: ChatDb, draft: Draft, resolved: Resolved): Promise<ChatResponse> {
138
+ const { access, role } = resolved;
139
+ // Stamped at the insert, not at the request: a message must not carry an
140
+ // earlier time than one a reader has already seen (and marked read up to).
141
+ const now = (config.clock ?? (() => new Date()))();
142
+ const thread = await openThread(db, access);
143
+ const row = await db.chatMessage.create({
144
+ data: {
145
+ threadId: thread.id,
146
+ tenantId: access.tenantId,
147
+ authorRole: access.role,
148
+ authorId: access.authorId,
149
+ body: draft.body,
150
+ quickKey: draft.quickKey,
151
+ createdAt: now,
152
+ },
153
+ });
154
+ await db.chatThread.update({ where: { id: thread.id }, data: { lastMessageAt: row.createdAt } });
155
+ notify(config, access, row, role.label);
156
+ return success(201, { message: wireMessage(config, row, resolved) });
157
+ }
158
+
159
+ /**
160
+ * One author's sends to one thread run one at a time, in this process, so
161
+ * each is checked against the ones before it — parallel requests cannot all
162
+ * pass the cross-message rule against each other's absence. Several
163
+ * processes can still interleave; the rule is a deterrent, not a lock.
164
+ */
165
+ function serialised(): (key: string, run: () => Promise<ChatResponse>) => Promise<ChatResponse> {
166
+ const tails = new Map<string, Promise<unknown>>();
167
+ return (key, run) => {
168
+ const result = (tails.get(key) ?? Promise.resolve()).then(run, run);
169
+ const tail = result.catch(() => undefined);
170
+ tails.set(key, tail);
171
+ void tail.then(() => {
172
+ if (tails.get(key) === tail) tails.delete(key);
173
+ });
174
+ return result;
175
+ };
176
+ }
177
+
178
+ export function sendRoute<TActor>(config: ChatServerConfig<TActor>, limiter: SlidingWindow): ChatRoute<TActor> {
179
+ const clock = config.clock ?? (() => new Date());
180
+ const inTurn = serialised();
181
+ return {
182
+ method: "POST",
183
+ path: "/messages",
184
+ async handle(request) {
185
+ const resolved = await resolve(config, request);
186
+ if (isResponse(resolved)) return resolved;
187
+ const { access, role, copy } = resolved;
188
+ if (!access.canWrite) return failure(403, "closed", copy.closed);
189
+ const draft = draftOf(request.body, resolved);
190
+ if (isResponse(draft)) return draft;
191
+ const now = clock();
192
+ if (!limiter.take(rateKeyOf(access), role.rateLimit.max, role.rateLimit.windowMs, now.getTime())) {
193
+ return failure(429, "rate_limited", copy.rateLimited);
194
+ }
195
+ const db = await config.db();
196
+ return inTurn(rateKeyOf(access), async () => {
197
+ const kinds = await contactIn(config, db, draft, resolved, now);
198
+ if (kinds.length > 0) return refuseContact(config, resolved, kinds);
199
+ return commit(config, db, draft, resolved);
200
+ });
201
+ },
202
+ };
203
+ }
@@ -0,0 +1,83 @@
1
+ /**
2
+ * The surface factory both renderers share: config in, `{ ChatThread }` out.
3
+ * Each platform entry passes its own frame, message list and composer;
4
+ * everything else is common.
5
+ */
6
+
7
+ import { useMemo, type JSX } from "react";
8
+
9
+ import { createChatClient, type ChatFetch } from "../client/api";
10
+ import { missingUiCopy } from "../client/assert";
11
+ import type { ChatUiCopy } from "../client/copy";
12
+ import { useChatThread } from "../client/use-chat-thread";
13
+ import { ChatConfigError } from "../core/errors";
14
+ import { ChatThreadView, type ChatPlatform } from "./thread-view";
15
+
16
+ /** What a host supplies once. All REQUIRED. */
17
+ export interface ChatSurfaceConfig {
18
+ /** The host's credentialed fetch (cookie session, Bearer link, …). */
19
+ readonly fetch: ChatFetch;
20
+ /** Every rendered string. */
21
+ readonly copy: ChatUiCopy;
22
+ /** How a message's time reads — the host's locale and clock conventions. */
23
+ readonly formatTime: (iso: string) => string;
24
+ }
25
+
26
+ export interface ChatThreadProps {
27
+ /** Where this thread's three routes are mounted. */
28
+ readonly endpoint: string;
29
+ /** Change it to reload — the host's live channel says the thread moved. */
30
+ readonly refreshSignal?: unknown;
31
+ /** The unread count each load found, then what is left (0) once marked read. */
32
+ readonly onUnreadChange?: (unread: number) => void;
33
+ /**
34
+ * Mark the thread read once a load shows unread messages. Default true.
35
+ * A host that mounts the thread hidden only to drive a badge passes false,
36
+ * so nothing is marked read that nobody saw.
37
+ */
38
+ readonly autoMarkRead?: boolean;
39
+ /**
40
+ * Native only: the distance from the window top to the thread (a navigator
41
+ * header), in dp, so the composer clears the keyboard exactly. Default 0.
42
+ */
43
+ readonly keyboardOffset?: number;
44
+ readonly testID?: string;
45
+ }
46
+
47
+ export interface ChatSurface {
48
+ ChatThread: (props: ChatThreadProps) => JSX.Element;
49
+ }
50
+
51
+ export function buildChatSurface(config: ChatSurfaceConfig, platform: ChatPlatform): ChatSurface {
52
+ if (typeof config?.fetch !== "function") throw new ChatConfigError("fetch is required — the host's credentialed client.");
53
+ if (typeof config.formatTime !== "function") throw new ChatConfigError("formatTime is required — time formatting is the host's.");
54
+ const missing = missingUiCopy(config.copy);
55
+ if (missing.length > 0) {
56
+ throw new ChatConfigError(`copy is required, with every key non-blank — missing: ${missing.join(", ")}.`);
57
+ }
58
+ const { fetch, copy, formatTime } = config;
59
+
60
+ function ChatThread(props: ChatThreadProps): JSX.Element {
61
+ const client = useMemo(() => createChatClient({ fetch, endpoint: props.endpoint }), [props.endpoint]);
62
+ const controls = useChatThread({
63
+ client,
64
+ refreshSignal: props.refreshSignal,
65
+ onUnreadChange: props.onUnreadChange,
66
+ autoMarkRead: props.autoMarkRead,
67
+ });
68
+ // Keyed by endpoint: another thread starts with an empty draft, not this one's.
69
+ return (
70
+ <ChatThreadView
71
+ key={props.endpoint}
72
+ controls={controls}
73
+ copy={copy}
74
+ formatTime={formatTime}
75
+ platform={platform}
76
+ keyboardOffset={props.keyboardOffset}
77
+ testID={props.testID}
78
+ />
79
+ );
80
+ }
81
+
82
+ return { ChatThread };
83
+ }