@12-apps/chat 0.0.0-stage → 1.1.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 (44) hide show
  1. package/README.md +194 -2
  2. package/package.json +95 -4
  3. package/prisma/chat.prisma +61 -0
  4. package/prisma/migrations/20261002120000_add_chat/migration.sql +41 -0
  5. package/prisma/migrations/20261003120000_add_chat_thread_activity_index/migration.sql +2 -0
  6. package/scripts/sync-chat-schema.mjs +64 -0
  7. package/src/client/api.ts +146 -0
  8. package/src/client/assert.ts +7 -0
  9. package/src/client/copy.ts +43 -0
  10. package/src/client/en-US.ts +17 -0
  11. package/src/client/index.ts +18 -0
  12. package/src/client/locales.ts +12 -0
  13. package/src/client/pt-BR.ts +17 -0
  14. package/src/client/use-chat-thread.ts +302 -0
  15. package/src/core/contact-views.ts +231 -0
  16. package/src/core/contact.ts +333 -0
  17. package/src/core/errors.ts +9 -0
  18. package/src/core/types.ts +82 -0
  19. package/src/index.ts +26 -0
  20. package/src/manifest/index.ts +20 -0
  21. package/src/manifest/native.ts +13 -0
  22. package/src/manifest/server.ts +14 -0
  23. package/src/manifest/web.ts +14 -0
  24. package/src/native/composer.tsx +52 -0
  25. package/src/native/index.ts +21 -0
  26. package/src/native/layout.tsx +96 -0
  27. package/src/react/composer.tsx +58 -0
  28. package/src/react/index.ts +20 -0
  29. package/src/react/layout.tsx +103 -0
  30. package/src/server/context.ts +228 -0
  31. package/src/server/copy.ts +73 -0
  32. package/src/server/db.ts +87 -0
  33. package/src/server/en-US.ts +14 -0
  34. package/src/server/handler.ts +110 -0
  35. package/src/server/index.ts +34 -0
  36. package/src/server/locales.ts +12 -0
  37. package/src/server/pt-BR.ts +14 -0
  38. package/src/server/rate.ts +34 -0
  39. package/src/server/reads.ts +52 -0
  40. package/src/server/routes.ts +119 -0
  41. package/src/server/send.ts +203 -0
  42. package/src/ui/bubble-tint.ts +19 -0
  43. package/src/ui/surface.tsx +87 -0
  44. package/src/ui/thread-view.tsx +225 -0
@@ -0,0 +1,110 @@
1
+ /**
2
+ * What every route shares: the response shapes, resolving the caller's place
3
+ * in the thread, finding the thread row, and the wire form of a message.
4
+ *
5
+ * Every 2xx answers `{ data }` — the house envelope the other server packages
6
+ * answer with — and every refusal answers `{ error, message }`: the machine
7
+ * code is the package's, the sentence is the host's.
8
+ */
9
+
10
+ import type { ChatWireMessage } from "../core/types";
11
+ import type { ChatAccess, ChatRequest, ChatResponse, ChatRoleConfig, ChatServerConfig } from "./context";
12
+ import { resolveCompleteCopy, type ChatServerCopy } from "./copy";
13
+ import type { ChatDb, ChatMessageRow, ChatThreadRow } from "./db";
14
+
15
+ export function success(status: number, data: unknown): ChatResponse {
16
+ return { status, body: { data } };
17
+ }
18
+
19
+ export function failure(status: number, error: string, message: string): ChatResponse {
20
+ return { status, body: { error, message } };
21
+ }
22
+
23
+ export interface Resolved {
24
+ readonly access: ChatAccess;
25
+ readonly role: ChatRoleConfig;
26
+ readonly copy: ChatServerCopy;
27
+ }
28
+
29
+ /** The caller's place in the thread, or the refusal to answer with. */
30
+ export async function resolve<TActor>(
31
+ config: ChatServerConfig<TActor>,
32
+ request: ChatRequest<TActor>,
33
+ ): Promise<Resolved | ChatResponse> {
34
+ const copy = resolveCompleteCopy(config.copy, request.locale);
35
+ const access = await config.authorize(request);
36
+ if (!access) return failure(404, "not_found", copy.notFound);
37
+ const role = config.roles[access.role];
38
+ if (!role) throw new Error(`@12-apps/chat: authorize answered role "${access.role}", which roles does not declare.`);
39
+ return { access, role, copy };
40
+ }
41
+
42
+ export function isResponse(value: object): value is ChatResponse {
43
+ return "status" in value;
44
+ }
45
+
46
+ function threadKeyOf(access: ChatAccess): { tenantId_threadKey: { tenantId: string; threadKey: string } } {
47
+ return { tenantId_threadKey: { tenantId: access.tenantId, threadKey: access.threadKey } };
48
+ }
49
+
50
+ /** The thread, if anyone ever wrote in it. Reading never creates one. */
51
+ export function findThread(db: ChatDb, access: ChatAccess): Promise<ChatThreadRow | null> {
52
+ return db.chatThread.findUnique({ where: threadKeyOf(access) });
53
+ }
54
+
55
+ /**
56
+ * The thread, created on the first message. Two first messages at the same
57
+ * instant race on the unique key, and the loser's client throws — whatever
58
+ * its error code (the seam relies on none): the winner's row is then there,
59
+ * so read it back, and rethrow only when it is not.
60
+ */
61
+ export async function openThread(db: ChatDb, access: ChatAccess): Promise<ChatThreadRow> {
62
+ try {
63
+ return await db.chatThread.upsert({
64
+ where: threadKeyOf(access),
65
+ create: { tenantId: access.tenantId, threadKey: access.threadKey },
66
+ update: {},
67
+ });
68
+ } catch (error) {
69
+ const winner = await findThread(db, access);
70
+ if (winner) return winner;
71
+ throw error;
72
+ }
73
+ }
74
+
75
+ function isMine(row: ChatMessageRow, access: ChatAccess, role: ChatRoleConfig): boolean {
76
+ if (row.authorRole !== access.role) return false;
77
+ return role.shared || row.authorId === access.authorId;
78
+ }
79
+
80
+ export function wireMessage<TActor>(config: ChatServerConfig<TActor>, row: ChatMessageRow, resolved: Resolved): ChatWireMessage {
81
+ return {
82
+ id: row.id,
83
+ role: row.authorRole,
84
+ // A role the host has since removed still shows as its key, never a blank.
85
+ label: config.roles[row.authorRole]?.label ?? row.authorRole,
86
+ mine: isMine(row, resolved.access, resolved.role),
87
+ body: row.body,
88
+ createdAt: row.createdAt.toISOString(),
89
+ };
90
+ }
91
+
92
+ /**
93
+ * Run a host hook without making the caller wait for it or fail by it: the
94
+ * message is committed, and a push provider's latency or outage is the
95
+ * host's. A throw (or a rejected promise) goes to `onError`, when given.
96
+ */
97
+ export function inBackground<TActor>(config: ChatServerConfig<TActor>, hook: string, run: () => unknown): void {
98
+ const report = (error: unknown): void => {
99
+ try {
100
+ config.onError?.(error, { hook });
101
+ } catch {
102
+ // A failing error reporter has nowhere left to report to.
103
+ }
104
+ };
105
+ try {
106
+ void Promise.resolve(run()).catch(report);
107
+ } catch (error) {
108
+ report(error);
109
+ }
110
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * The one thing this package exposes to a BACKEND host: `createApiChat(config)
3
+ * → { routes }`, plus `createChatReads` for the host's own lists.
4
+ *
5
+ * Routes are framework-neutral descriptors (the wiring `WireRoute` twin). A
6
+ * host mounts one set per audience — each with its own `authorize`, which is
7
+ * where every rule about who is in which thread lives — under a path that
8
+ * names the subject. The package never learns what a thread is about.
9
+ */
10
+
11
+ import { assertChatServerConfig, type ChatRoute, type ChatServerConfig } from "./context";
12
+ import { chatRoutes } from "./routes";
13
+
14
+ export function createApiChat<TActor = unknown>(config: ChatServerConfig<TActor>): { routes: ChatRoute<TActor>[] } {
15
+ assertChatServerConfig(config as ChatServerConfig);
16
+ return { routes: chatRoutes(config) };
17
+ }
18
+
19
+ export { createChatReads, type ChatReads, type UnreadCountsQuery } from "./reads";
20
+ export type {
21
+ ChatAccess,
22
+ ChatMessageEvent,
23
+ ChatRefusalEvent,
24
+ ChatRequest,
25
+ ChatResponse,
26
+ ChatRoleConfig,
27
+ ChatRoute,
28
+ ChatServerConfig,
29
+ } from "./context";
30
+ export type { ChatDb, ChatMessageRow, ChatReadMarkerRow, ChatThreadRow } from "./db";
31
+ export type { ChatCopyResolver, ChatCopySource, ChatServerCopy } from "./copy";
32
+ export { PT_BR_CHAT_SERVER_COPY } from "./pt-BR";
33
+ export { EN_US_CHAT_SERVER_COPY } from "./en-US";
34
+ export { CHAT_SERVER_COPY } from "./locales";
@@ -0,0 +1,12 @@
1
+ import type { ChatServerCopy } from "./copy";
2
+ import { EN_US_CHAT_SERVER_COPY } from "./en-US";
3
+ import { PT_BR_CHAT_SERVER_COPY } from "./pt-BR";
4
+
5
+ /** Mirrored rather than imported, so the package stays liftable into any repo. */
6
+ type LocalePack<T> = { readonly "pt-BR": T; readonly "en-US": T };
7
+
8
+ /** Both languages, keyed by tag — what a host hands its i18n resolver. */
9
+ export const CHAT_SERVER_COPY = {
10
+ "pt-BR": PT_BR_CHAT_SERVER_COPY,
11
+ "en-US": EN_US_CHAT_SERVER_COPY,
12
+ } as const satisfies LocalePack<ChatServerCopy>;
@@ -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,19 @@
1
+ /**
2
+ * The surface of the reader's OWN bubbles: the theme's primary colour, washed
3
+ * out to a tint the body text still reads on. Derived from the theme on every
4
+ * render, so a host's brand colour (and its dark mode) reaches the thread with
5
+ * nothing to configure.
6
+ *
7
+ * The others' bubbles keep the paper surface. Both surfaces used to be a
8
+ * surface token, and the two tokens resolve to the same colour in most themes,
9
+ * so which side wrote a line was told only by the label's colour.
10
+ */
11
+
12
+ import { alpha, type UiTheme } from "@12-apps/ui/tokens";
13
+
14
+ /** How much of the primary colour shows through: light text on dark needs more to be seen. */
15
+ const OWN_TINT_STRENGTH = { light: 0.08, dark: 0.16 } as const;
16
+
17
+ export function ownBubbleTint(theme: UiTheme): string {
18
+ return alpha(theme.palette.primary.main, OWN_TINT_STRENGTH[theme.mode]);
19
+ }