@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.
- package/README.md +194 -2
- package/package.json +95 -4
- package/prisma/chat.prisma +61 -0
- package/prisma/migrations/20261002120000_add_chat/migration.sql +41 -0
- package/prisma/migrations/20261003120000_add_chat_thread_activity_index/migration.sql +2 -0
- package/scripts/sync-chat-schema.mjs +64 -0
- package/src/client/api.ts +146 -0
- package/src/client/assert.ts +7 -0
- package/src/client/copy.ts +43 -0
- package/src/client/en-US.ts +17 -0
- package/src/client/index.ts +18 -0
- package/src/client/locales.ts +12 -0
- package/src/client/pt-BR.ts +17 -0
- package/src/client/use-chat-thread.ts +302 -0
- package/src/core/contact-views.ts +231 -0
- package/src/core/contact.ts +333 -0
- package/src/core/errors.ts +9 -0
- package/src/core/types.ts +82 -0
- package/src/index.ts +26 -0
- package/src/manifest/index.ts +20 -0
- package/src/manifest/native.ts +13 -0
- package/src/manifest/server.ts +14 -0
- package/src/manifest/web.ts +14 -0
- package/src/native/composer.tsx +52 -0
- package/src/native/index.ts +21 -0
- package/src/native/layout.tsx +96 -0
- package/src/react/composer.tsx +58 -0
- package/src/react/index.ts +20 -0
- package/src/react/layout.tsx +103 -0
- package/src/server/context.ts +228 -0
- package/src/server/copy.ts +73 -0
- package/src/server/db.ts +87 -0
- package/src/server/en-US.ts +14 -0
- package/src/server/handler.ts +110 -0
- package/src/server/index.ts +34 -0
- package/src/server/locales.ts +12 -0
- package/src/server/pt-BR.ts +14 -0
- package/src/server/rate.ts +34 -0
- package/src/server/reads.ts +52 -0
- package/src/server/routes.ts +119 -0
- package/src/server/send.ts +203 -0
- package/src/ui/bubble-tint.ts +19 -0
- package/src/ui/surface.tsx +87 -0
- package/src/ui/thread-view.tsx +225 -0
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The React Native thread's frame, message list and bubble.
|
|
3
|
+
*
|
|
4
|
+
* The frame is the design system's `Screen` with its own scrolling off and no
|
|
5
|
+
* safe-area edges (the host's screen owns those): it fills its parent and
|
|
6
|
+
* lifts above the soft keyboard, so the composer pinned under the list is
|
|
7
|
+
* never covered. The list is a `ScrollView` that follows the newest message
|
|
8
|
+
* whenever its content grows or its viewport shrinks (the keyboard opening),
|
|
9
|
+
* and lets a tap on the send button land while the keyboard is up. It is a
|
|
10
|
+
* polite live region, so TalkBack reads a message as it arrives; and it is on
|
|
11
|
+
* screen whenever it is mounted, so it reports itself visible on mount for a
|
|
12
|
+
* thread that marks read only once seen.
|
|
13
|
+
*
|
|
14
|
+
* Mount the thread in a bounded parent (a `Screen` with `scroll={false}`, a
|
|
15
|
+
* flex-1 view) — inside another ScrollView it has no height to fill. Pass
|
|
16
|
+
* `keyboardOffset` when a navigator header sits above it.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { Box } from "@12-apps/ui/layout/Box";
|
|
20
|
+
import { Screen } from "@12-apps/ui/layout/Screen";
|
|
21
|
+
import { Stack } from "@12-apps/ui/layout/Stack";
|
|
22
|
+
import { useUiTheme } from "@12-apps/ui/provider";
|
|
23
|
+
import { useEffect, useRef, type JSX } from "react";
|
|
24
|
+
import { ScrollView, StyleSheet } from "react-native";
|
|
25
|
+
|
|
26
|
+
import { ownBubbleTint } from "../ui/bubble-tint";
|
|
27
|
+
import type { ChatBubbleProps, ChatFrameProps, ChatMessageListProps } from "../ui/thread-view";
|
|
28
|
+
|
|
29
|
+
const NO_EDGES = [] as const;
|
|
30
|
+
const styles = StyleSheet.create({ fill: { flex: 1 } });
|
|
31
|
+
/** A bubble's widest, as a share of the thread. */
|
|
32
|
+
const BUBBLE_MAX_WIDTH = "80%" as const;
|
|
33
|
+
|
|
34
|
+
export function NativeFrame(props: ChatFrameProps): JSX.Element {
|
|
35
|
+
return (
|
|
36
|
+
<Screen
|
|
37
|
+
scroll={false}
|
|
38
|
+
safeAreaEdges={NO_EDGES}
|
|
39
|
+
keyboardAvoiding
|
|
40
|
+
keyboardVerticalOffset={props.keyboardOffset ?? 0}
|
|
41
|
+
bg="transparent"
|
|
42
|
+
gap={2}
|
|
43
|
+
testID={props.testID}
|
|
44
|
+
>
|
|
45
|
+
{props.children}
|
|
46
|
+
</Screen>
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** On screen while mounted: report it once, and `false` when the list goes away. */
|
|
51
|
+
function useMountedVisibility(onVisibleChange?: (visible: boolean) => void): void {
|
|
52
|
+
const latest = useRef(onVisibleChange);
|
|
53
|
+
useEffect(() => {
|
|
54
|
+
latest.current = onVisibleChange;
|
|
55
|
+
}, [onVisibleChange]);
|
|
56
|
+
const wanted = onVisibleChange !== undefined;
|
|
57
|
+
useEffect(() => {
|
|
58
|
+
if (!wanted) return undefined;
|
|
59
|
+
latest.current?.(true);
|
|
60
|
+
return () => latest.current?.(false);
|
|
61
|
+
}, [wanted]);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function NativeMessageList(props: ChatMessageListProps): JSX.Element {
|
|
65
|
+
const list = useRef<ScrollView>(null);
|
|
66
|
+
const toEnd = (): void => list.current?.scrollToEnd({ animated: true });
|
|
67
|
+
useMountedVisibility(props.onVisibleChange);
|
|
68
|
+
return (
|
|
69
|
+
<ScrollView
|
|
70
|
+
ref={list}
|
|
71
|
+
style={styles.fill}
|
|
72
|
+
keyboardShouldPersistTaps="handled"
|
|
73
|
+
keyboardDismissMode="interactive"
|
|
74
|
+
// A new message grows the content; the keyboard opening shrinks the viewport. Either way, show the newest.
|
|
75
|
+
onContentSizeChange={toEnd}
|
|
76
|
+
onLayout={toEnd}
|
|
77
|
+
accessibilityLabel={props.label}
|
|
78
|
+
accessibilityLiveRegion="polite"
|
|
79
|
+
testID={props.testID}
|
|
80
|
+
>
|
|
81
|
+
<Stack gap={1}>{props.children}</Stack>
|
|
82
|
+
</ScrollView>
|
|
83
|
+
);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function NativeBubble(props: ChatBubbleProps): JSX.Element {
|
|
87
|
+
const theme = useUiTheme();
|
|
88
|
+
// One plain object, not a style array: the web type-check (`tsc -p tsconfig.json`) reads this
|
|
89
|
+
// file against the web `Box`, whose `style` is CSS. An own bubble's tint replaces the paper surface.
|
|
90
|
+
const style = props.mine ? { maxWidth: BUBBLE_MAX_WIDTH, backgroundColor: ownBubbleTint(theme) } : { maxWidth: BUBBLE_MAX_WIDTH };
|
|
91
|
+
return (
|
|
92
|
+
<Box bg={props.mine ? undefined : "paper"} bordered radius="md" px={2} py={1} gap={0.5} style={style}>
|
|
93
|
+
{props.children}
|
|
94
|
+
</Box>
|
|
95
|
+
);
|
|
96
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The web composer: the design system's field and button, wired with the
|
|
3
|
+
* DOM's change event. Enter sends; Shift+Enter is left to the field, and so is
|
|
4
|
+
* the Enter that confirms an IME composition.
|
|
5
|
+
*
|
|
6
|
+
* The field stays enabled while a message is in flight: disabling it would
|
|
7
|
+
* drop focus after every Enter. Only the send action is gated (here, and again
|
|
8
|
+
* in the thread's submit). A click on the send button hands focus back to the
|
|
9
|
+
* field: the button disables itself while the message is in flight, and a
|
|
10
|
+
* focused control that turns disabled drops focus to the page.
|
|
11
|
+
*
|
|
12
|
+
* `maxLength` and the field's ref ride `inputProps`: given to `Input` itself
|
|
13
|
+
* they land on the text field's root `<div>`, where neither means anything.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { Button } from "@12-apps/ui/form/Button";
|
|
17
|
+
import { Input } from "@12-apps/ui/form/Input";
|
|
18
|
+
import { Box } from "@12-apps/ui/layout/Box";
|
|
19
|
+
import { useRef, type JSX, type KeyboardEvent } from "react";
|
|
20
|
+
|
|
21
|
+
import type { ChatComposerProps } from "../ui/thread-view";
|
|
22
|
+
|
|
23
|
+
export function WebComposer(props: ChatComposerProps): JSX.Element {
|
|
24
|
+
const field = useRef<HTMLInputElement | null>(null);
|
|
25
|
+
const onKeyDown = (event: KeyboardEvent<HTMLInputElement>): void => {
|
|
26
|
+
if (event.key !== "Enter" || event.shiftKey || event.nativeEvent.isComposing) return;
|
|
27
|
+
event.preventDefault();
|
|
28
|
+
props.onSubmit();
|
|
29
|
+
};
|
|
30
|
+
const onSend = (): void => {
|
|
31
|
+
props.onSubmit();
|
|
32
|
+
field.current?.focus();
|
|
33
|
+
};
|
|
34
|
+
return (
|
|
35
|
+
<Box direction="row" gap={1} align="center">
|
|
36
|
+
<Box flex={1}>
|
|
37
|
+
<Input
|
|
38
|
+
fullWidth
|
|
39
|
+
value={props.value}
|
|
40
|
+
placeholder={props.copy.placeholder}
|
|
41
|
+
aria-label={props.copy.placeholder}
|
|
42
|
+
inputProps={{ maxLength: props.maxLength, ref: field }}
|
|
43
|
+
onChange={(event) => props.onChange(event.target.value)}
|
|
44
|
+
onKeyDown={onKeyDown}
|
|
45
|
+
testID="chat-input"
|
|
46
|
+
/>
|
|
47
|
+
</Box>
|
|
48
|
+
<Button
|
|
49
|
+
variant="solid"
|
|
50
|
+
onClick={onSend}
|
|
51
|
+
disabled={props.sending || props.value.trim() === ""}
|
|
52
|
+
testID="chat-send"
|
|
53
|
+
>
|
|
54
|
+
{props.sending ? props.copy.sending : props.copy.send}
|
|
55
|
+
</Button>
|
|
56
|
+
</Box>
|
|
57
|
+
);
|
|
58
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@12-apps/chat/react` — the web host's surface: `createWebChat(config) →
|
|
3
|
+
* { ChatThread }`. One component per thread; the host decides where it sits.
|
|
4
|
+
* Members are component TYPES — build once per config (the wiring binder does).
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { buildChatSurface, type ChatSurface, type ChatSurfaceConfig } from "../ui/surface";
|
|
8
|
+
import { WebComposer } from "./composer";
|
|
9
|
+
import { WebBubble, WebFrame, WebMessageList } from "./layout";
|
|
10
|
+
|
|
11
|
+
export function createWebChat(config: ChatSurfaceConfig): ChatSurface {
|
|
12
|
+
return buildChatSurface(config, {
|
|
13
|
+
Frame: WebFrame,
|
|
14
|
+
MessageList: WebMessageList,
|
|
15
|
+
Bubble: WebBubble,
|
|
16
|
+
Composer: WebComposer,
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export type { ChatSurface, ChatSurfaceConfig, ChatThreadProps } from "../ui/surface";
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The web thread's frame, message list and bubble. The list is the design
|
|
3
|
+
* system's scroll region, bounded to a share of the viewport so a long thread
|
|
4
|
+
* scrolls inside it while the composer stays in view, and it follows the
|
|
5
|
+
* newest message whenever one is added (a send, a reload that brought one in).
|
|
6
|
+
* It is a polite live region, so a screen reader hears a message arrive
|
|
7
|
+
* without the reader's place being taken from them.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { Box } from "@12-apps/ui/layout/Box";
|
|
11
|
+
import { ScrollArea } from "@12-apps/ui/layout/ScrollArea";
|
|
12
|
+
import { Stack } from "@12-apps/ui/layout/Stack";
|
|
13
|
+
import { useUiTheme } from "@12-apps/ui/provider";
|
|
14
|
+
import { useEffect, useRef, type JSX } from "react";
|
|
15
|
+
|
|
16
|
+
import { ownBubbleTint } from "../ui/bubble-tint";
|
|
17
|
+
import type { ChatBubbleProps, ChatFrameProps, ChatMessageListProps } from "../ui/thread-view";
|
|
18
|
+
|
|
19
|
+
/** The list's ceiling: relative to the viewport, so it holds at every width and zoom. */
|
|
20
|
+
const LIST_MAX_HEIGHT = "60vh";
|
|
21
|
+
/** A bubble's widest: a share of the thread, and never a line too long to read. */
|
|
22
|
+
const BUBBLE_MAX_WIDTH = "min(80%, 60ch)";
|
|
23
|
+
/** On screen from the first sliver: 0 catches entering, the next step a pixel or so in. */
|
|
24
|
+
const VISIBLE_THRESHOLDS = [0, 0.01];
|
|
25
|
+
|
|
26
|
+
export function WebFrame(props: ChatFrameProps): JSX.Element {
|
|
27
|
+
return (
|
|
28
|
+
<Stack gap={2} testID={props.testID}>
|
|
29
|
+
{props.children}
|
|
30
|
+
</Stack>
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Tell `report` whether `element` is on screen, and `false` once it is gone.
|
|
36
|
+
* A browser without IntersectionObserver reports it on screen at once: the
|
|
37
|
+
* thread then marks read as it always did, rather than never.
|
|
38
|
+
*/
|
|
39
|
+
function observeVisibility(element: HTMLElement, report: (visible: boolean) => void): () => void {
|
|
40
|
+
if (typeof IntersectionObserver === "undefined") {
|
|
41
|
+
report(true);
|
|
42
|
+
return () => report(false);
|
|
43
|
+
}
|
|
44
|
+
const observer = new IntersectionObserver(
|
|
45
|
+
(entries) => {
|
|
46
|
+
const entry = entries.at(-1);
|
|
47
|
+
if (entry) report(entry.isIntersecting && entry.intersectionRatio > 0);
|
|
48
|
+
},
|
|
49
|
+
{ threshold: VISIBLE_THRESHOLDS },
|
|
50
|
+
);
|
|
51
|
+
observer.observe(element);
|
|
52
|
+
return () => {
|
|
53
|
+
observer.disconnect();
|
|
54
|
+
report(false);
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Report the viewport's visibility while the host asked for it; the latest callback, never a re-subscription. */
|
|
59
|
+
function useVisibility(viewport: { readonly current: HTMLDivElement | null }, onVisibleChange?: (visible: boolean) => void): void {
|
|
60
|
+
const latest = useRef(onVisibleChange);
|
|
61
|
+
useEffect(() => {
|
|
62
|
+
latest.current = onVisibleChange;
|
|
63
|
+
}, [onVisibleChange]);
|
|
64
|
+
const wanted = onVisibleChange !== undefined;
|
|
65
|
+
useEffect(() => {
|
|
66
|
+
const element = viewport.current;
|
|
67
|
+
if (!wanted || !element) return undefined;
|
|
68
|
+
return observeVisibility(element, (visible) => latest.current?.(visible));
|
|
69
|
+
}, [viewport, wanted]);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function WebMessageList(props: ChatMessageListProps): JSX.Element {
|
|
73
|
+
const viewport = useRef<HTMLDivElement | null>(null);
|
|
74
|
+
useEffect(() => {
|
|
75
|
+
const element = viewport.current;
|
|
76
|
+
if (element) element.scrollTop = element.scrollHeight;
|
|
77
|
+
}, [props.scrollKey]);
|
|
78
|
+
useVisibility(viewport, props.onVisibleChange);
|
|
79
|
+
return (
|
|
80
|
+
<ScrollArea regionLabel={props.label} scrollRef={viewport} height="auto" maxHeight={LIST_MAX_HEIGHT} testId={props.testID}>
|
|
81
|
+
<Stack gap={1} aria-live="polite" testID={`${props.testID}-live`}>
|
|
82
|
+
{props.children}
|
|
83
|
+
</Stack>
|
|
84
|
+
</ScrollArea>
|
|
85
|
+
);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function WebBubble(props: ChatBubbleProps): JSX.Element {
|
|
89
|
+
const theme = useUiTheme();
|
|
90
|
+
return (
|
|
91
|
+
<Box
|
|
92
|
+
bg={props.mine ? undefined : "paper"}
|
|
93
|
+
bordered
|
|
94
|
+
radius="md"
|
|
95
|
+
px={2}
|
|
96
|
+
py={1}
|
|
97
|
+
gap={0.5}
|
|
98
|
+
sx={{ maxWidth: BUBBLE_MAX_WIDTH, ...(props.mine ? { backgroundColor: ownBubbleTint(theme) } : {}) }}
|
|
99
|
+
>
|
|
100
|
+
{props.children}
|
|
101
|
+
</Box>
|
|
102
|
+
);
|
|
103
|
+
}
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The server surface's vocabulary: the host seams, the per-role rules, and the
|
|
3
|
+
* wire-route twins.
|
|
4
|
+
*
|
|
5
|
+
* The request/response/route shapes are RESTATED rather than imported from
|
|
6
|
+
* `@12-apps/wiring` (the structural-twin move), so the contract package stays
|
|
7
|
+
* a type-only devDependency. The manifest suite pins that they still fit.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { CONTACT_KINDS, type ContactKind, type ContactVocabulary } from "../core/contact";
|
|
11
|
+
import { ChatConfigError } from "../core/errors";
|
|
12
|
+
import type { ChatQuickReply } from "../core/types";
|
|
13
|
+
import { missingCopy, resolveCopy, SERVER_COPY_KEYS, type ChatCopySource, type ChatServerCopy } from "./copy";
|
|
14
|
+
import type { ChatDb } from "./db";
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Who the caller is IN THIS THREAD, decided by the host for every request.
|
|
18
|
+
* The host's whole policy lives behind it: whether this person is a party to
|
|
19
|
+
* the thread at all (no ⇒ `null` ⇒ 404), under which role, and whether that
|
|
20
|
+
* role may still write. The package never learns why.
|
|
21
|
+
*/
|
|
22
|
+
export interface ChatAccess {
|
|
23
|
+
/** Partition key — threads never cross it. */
|
|
24
|
+
readonly tenantId: string;
|
|
25
|
+
/** What the thread is about, in a string the host composes (`job:123`). */
|
|
26
|
+
readonly threadKey: string;
|
|
27
|
+
/** The caller's role key; must be a key of the config's `roles`. */
|
|
28
|
+
readonly role: string;
|
|
29
|
+
/** The person, kept on their messages for moderation; never sent to the others. */
|
|
30
|
+
readonly authorId: string;
|
|
31
|
+
/**
|
|
32
|
+
* Whose read marker this caller moves. A person's own id, or — for a role
|
|
33
|
+
* whose members read as one (a team) — one shared id for the whole role.
|
|
34
|
+
*/
|
|
35
|
+
readonly readerId: string;
|
|
36
|
+
/** False ⇒ read-only: the window closed, the role lost the thread, … */
|
|
37
|
+
readonly canWrite: boolean;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** How one role behaves in every thread. All REQUIRED: these are host decisions. */
|
|
41
|
+
export interface ChatRoleConfig {
|
|
42
|
+
/** The only name the thread shows for this role's messages. */
|
|
43
|
+
readonly label: string;
|
|
44
|
+
/**
|
|
45
|
+
* True when every member of the role speaks as one (a team): their messages
|
|
46
|
+
* all read as `mine` to each of them, and `readerId` is expected to be shared.
|
|
47
|
+
*/
|
|
48
|
+
readonly shared: boolean;
|
|
49
|
+
/** Longest message, in characters. */
|
|
50
|
+
readonly maxLength: number;
|
|
51
|
+
/** False ⇒ quick replies only. */
|
|
52
|
+
readonly freeText: boolean;
|
|
53
|
+
/** Contact information this role may not send; `[]` for none. */
|
|
54
|
+
readonly blockContact: readonly ContactKind[];
|
|
55
|
+
/** Canned lines this role may send with one tap; `[]` for none. */
|
|
56
|
+
readonly quickReplies: readonly ChatQuickReply[];
|
|
57
|
+
/** At most `max` messages per `windowMs`, per role and author, per thread. */
|
|
58
|
+
readonly rateLimit: { readonly max: number; readonly windowMs: number };
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** What a committed message tells the host — notifications and live hints are the host's. */
|
|
62
|
+
export interface ChatMessageEvent {
|
|
63
|
+
readonly tenantId: string;
|
|
64
|
+
readonly threadKey: string;
|
|
65
|
+
readonly message: {
|
|
66
|
+
readonly id: string;
|
|
67
|
+
readonly role: string;
|
|
68
|
+
readonly label: string;
|
|
69
|
+
readonly authorId: string;
|
|
70
|
+
readonly body: string;
|
|
71
|
+
/** The quick reply's key when one was sent, else `null` (free text). */
|
|
72
|
+
readonly quickKey: string | null;
|
|
73
|
+
readonly createdAt: string;
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** A send the content rules refused — so the host can see who keeps trying. */
|
|
78
|
+
export interface ChatRefusalEvent {
|
|
79
|
+
readonly tenantId: string;
|
|
80
|
+
readonly threadKey: string;
|
|
81
|
+
readonly role: string;
|
|
82
|
+
readonly authorId: string;
|
|
83
|
+
readonly code: "contact_info";
|
|
84
|
+
/** What the filter found. Never the text: the host decides what it keeps. */
|
|
85
|
+
readonly kinds: readonly ContactKind[];
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export interface ChatServerConfig<TActor = unknown> {
|
|
89
|
+
/** The host's Prisma client (or a structural twin), lazily. */
|
|
90
|
+
db: () => ChatDb | Promise<ChatDb>;
|
|
91
|
+
/** Resolve the caller's place in the thread the request names, or `null`. */
|
|
92
|
+
authorize: (request: ChatRequest<TActor>) => Promise<ChatAccess | null>;
|
|
93
|
+
/** Every role a thread may hold, keyed by the host's role key. */
|
|
94
|
+
roles: Readonly<Record<string, ChatRoleConfig>>;
|
|
95
|
+
/** Every sentence the routes answer with — host vocabulary, or a per-request resolver. */
|
|
96
|
+
copy: ChatCopySource<ChatServerCopy>;
|
|
97
|
+
/** Host words that widen the contact-info filter (spelled digits, app names, …). */
|
|
98
|
+
contactVocabulary?: ContactVocabulary;
|
|
99
|
+
/**
|
|
100
|
+
* After a message commits — the host's notifications and live hints. Run in
|
|
101
|
+
* the background: the send answers without waiting for it, and a throw or
|
|
102
|
+
* rejection goes to `onError`, never to the sender.
|
|
103
|
+
*/
|
|
104
|
+
onMessage?: (event: ChatMessageEvent) => void | Promise<void>;
|
|
105
|
+
/** After the content rules refuse a send. Background, like `onMessage`. */
|
|
106
|
+
onRefused?: (event: ChatRefusalEvent) => void | Promise<void>;
|
|
107
|
+
/** Where a failing background hook is reported (`hook` names which). Silent when absent. */
|
|
108
|
+
onError?: (error: unknown, context: { readonly hook: string }) => void;
|
|
109
|
+
/**
|
|
110
|
+
* How much of the author's own recent free text the contact rules read
|
|
111
|
+
* with a draft, so a number split over several messages is still caught.
|
|
112
|
+
* Defaults to the last 12 messages within 10 minutes.
|
|
113
|
+
*/
|
|
114
|
+
contactLookback?: { readonly messages: number; readonly windowMs: number };
|
|
115
|
+
/** How many messages a thread answers with, newest kept. Defaults to 200. */
|
|
116
|
+
historyLimit?: number;
|
|
117
|
+
/** Test seam. */
|
|
118
|
+
clock?: () => Date;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
// ─── WireRoute twins ─────────────────────────────────────────────────────────
|
|
122
|
+
|
|
123
|
+
export interface ChatRequest<TActor = unknown> {
|
|
124
|
+
actor: TActor;
|
|
125
|
+
params: Record<string, string | undefined>;
|
|
126
|
+
query: Record<string, string | undefined>;
|
|
127
|
+
body?: unknown;
|
|
128
|
+
/** BCP-47, set by the host's adapter; absent means "answer in the configured words". */
|
|
129
|
+
locale?: string;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export interface ChatResponse {
|
|
133
|
+
status: number;
|
|
134
|
+
body: unknown;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
export interface ChatRoute<TActor = unknown> {
|
|
138
|
+
method: "GET" | "POST";
|
|
139
|
+
/** Mount-relative. */
|
|
140
|
+
path: string;
|
|
141
|
+
handle(request: ChatRequest<TActor>): Promise<ChatResponse>;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// ─── Assembly checks ─────────────────────────────────────────────────────────
|
|
145
|
+
|
|
146
|
+
const isPositiveInt = (value: unknown): boolean => Number.isInteger(value) && (value as number) > 0;
|
|
147
|
+
|
|
148
|
+
/** Each rule a role must satisfy, with the message naming the field it broke. */
|
|
149
|
+
const ROLE_RULES: readonly [(role: ChatRoleConfig) => boolean, string][] = [
|
|
150
|
+
[(role) => typeof role?.label === "string" && role.label.trim() !== "", "label is required."],
|
|
151
|
+
[(role) => typeof role.shared === "boolean", "shared must be a boolean."],
|
|
152
|
+
[(role) => isPositiveInt(role.maxLength), "maxLength must be a positive integer."],
|
|
153
|
+
[(role) => typeof role.freeText === "boolean", "freeText must be a boolean."],
|
|
154
|
+
[
|
|
155
|
+
(role) => Array.isArray(role.blockContact) && role.blockContact.every((kind) => CONTACT_KINDS.includes(kind)),
|
|
156
|
+
`blockContact must list only ${CONTACT_KINDS.join(", ")}.`,
|
|
157
|
+
],
|
|
158
|
+
[(role) => isPositiveInt(role.rateLimit?.max) && isPositiveInt(role.rateLimit?.windowMs), "rateLimit needs a positive max and windowMs."],
|
|
159
|
+
];
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* The longest message a role that blocks contact info may send. The filter
|
|
163
|
+
* reads the draft with the author's recent text on every send, so its cost
|
|
164
|
+
* grows with the length; a few thousand characters is no chat message.
|
|
165
|
+
*/
|
|
166
|
+
const MAX_FILTERED_LENGTH = 2000;
|
|
167
|
+
|
|
168
|
+
function assertRole(key: string, role: ChatRoleConfig): void {
|
|
169
|
+
for (const [holds, message] of ROLE_RULES) {
|
|
170
|
+
if (!holds(role)) throw new ChatConfigError(`roles.${key}.${message}`);
|
|
171
|
+
}
|
|
172
|
+
if (role.blockContact.length > 0 && role.maxLength > MAX_FILTERED_LENGTH) {
|
|
173
|
+
throw new ChatConfigError(`roles.${key}.maxLength may be at most ${MAX_FILTERED_LENGTH} while blockContact is set.`);
|
|
174
|
+
}
|
|
175
|
+
assertQuickReplies(`roles.${key}`, role);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function assertQuickReply(at: string, reply: ChatQuickReply, seen: Set<string>): void {
|
|
179
|
+
if (typeof reply?.key !== "string" || reply.key.trim() === "") throw new ChatConfigError(`${at}.quickReplies needs a key on every entry.`);
|
|
180
|
+
if (typeof reply.text !== "string" || reply.text.trim() === "") throw new ChatConfigError(`${at}.quickReplies.${reply.key} needs text.`);
|
|
181
|
+
if (seen.has(reply.key)) throw new ChatConfigError(`${at}.quickReplies repeats "${reply.key}".`);
|
|
182
|
+
seen.add(reply.key);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function assertQuickReplies(at: string, role: ChatRoleConfig): void {
|
|
186
|
+
if (!Array.isArray(role.quickReplies)) throw new ChatConfigError(`${at}.quickReplies must be a list.`);
|
|
187
|
+
const seen = new Set<string>();
|
|
188
|
+
role.quickReplies.forEach((reply) => assertQuickReply(at, reply, seen));
|
|
189
|
+
if (!role.freeText && role.quickReplies.length === 0) {
|
|
190
|
+
throw new ChatConfigError(`${at} allows no free text and offers no quick replies — it could never write.`);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const HOOKS = ["onMessage", "onRefused", "onError"] as const;
|
|
195
|
+
|
|
196
|
+
function assertOptionalSettings(config: ChatServerConfig): void {
|
|
197
|
+
for (const hook of HOOKS) {
|
|
198
|
+
// A hook that is not a function would throw inside the background run, where nobody sees it.
|
|
199
|
+
if (config[hook] !== undefined && typeof config[hook] !== "function") throw new ChatConfigError(`${hook} must be a function.`);
|
|
200
|
+
}
|
|
201
|
+
if (config.historyLimit !== undefined && !isPositiveInt(config.historyLimit)) {
|
|
202
|
+
throw new ChatConfigError("historyLimit must be a positive integer.");
|
|
203
|
+
}
|
|
204
|
+
assertLookback(config.contactLookback);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function assertLookback(lookback: ChatServerConfig["contactLookback"]): void {
|
|
208
|
+
if (lookback === undefined) return;
|
|
209
|
+
if (!(isPositiveInt(lookback?.messages) && isPositiveInt(lookback?.windowMs))) {
|
|
210
|
+
throw new ChatConfigError("contactLookback needs a positive messages and windowMs.");
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Throws {@link ChatConfigError} at assembly, where the call site is. */
|
|
215
|
+
export function assertChatServerConfig(config: ChatServerConfig): void {
|
|
216
|
+
if (typeof config?.db !== "function") throw new ChatConfigError("db must be a function returning the client.");
|
|
217
|
+
if (typeof config.authorize !== "function") throw new ChatConfigError("authorize is required — who may see which thread is the host's.");
|
|
218
|
+
const keys = Object.keys(config.roles ?? {});
|
|
219
|
+
if (keys.length === 0) throw new ChatConfigError("roles must declare at least one role.");
|
|
220
|
+
keys.forEach((key) => assertRole(key, config.roles[key] as ChatRoleConfig));
|
|
221
|
+
assertOptionalSettings(config);
|
|
222
|
+
const missing = missingCopy(resolveCopy(config.copy, undefined), SERVER_COPY_KEYS);
|
|
223
|
+
if (missing.length > 0) {
|
|
224
|
+
throw new ChatConfigError(
|
|
225
|
+
`copy is required, with every key non-blank — missing: ${missing.join(", ")}. A host passes a named pack by hand.`,
|
|
226
|
+
);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Every sentence the routes answer a HUMAN with — required host config, no
|
|
3
|
+
* defaults (the copy-portability doctrine). The machine half of a refusal —
|
|
4
|
+
* status and `error` code — stays the package's; only the words are the host's.
|
|
5
|
+
*
|
|
6
|
+
* A host imports a named pack (`./pt-BR`, `./en-US`) and passes it by hand,
|
|
7
|
+
* or passes a RESOLVER to answer each request in its reader's language.
|
|
8
|
+
*/
|
|
9
|
+
export interface ChatServerCopy {
|
|
10
|
+
/** 404 — no thread the caller may see (not a participant, or no such subject). */
|
|
11
|
+
readonly notFound: string;
|
|
12
|
+
/** 403 — the caller may read but no longer write. */
|
|
13
|
+
readonly closed: string;
|
|
14
|
+
/** 422 — the body is not the JSON object the route reads. */
|
|
15
|
+
readonly invalidBody: string;
|
|
16
|
+
/** 422 — nothing to send. */
|
|
17
|
+
readonly empty: string;
|
|
18
|
+
/** 422 — longer than the role allows; `{max}` is replaced by the limit. */
|
|
19
|
+
readonly tooLong: string;
|
|
20
|
+
/** 422 — the role may only send quick replies. */
|
|
21
|
+
readonly freeTextDisabled: string;
|
|
22
|
+
/** 422 — the quick reply key is not one the role offers. */
|
|
23
|
+
readonly unknownQuickReply: string;
|
|
24
|
+
/** 422 — the text carries a phone number, address, link or handle. */
|
|
25
|
+
readonly contactInfo: string;
|
|
26
|
+
/** 429 — too many messages in a short time. */
|
|
27
|
+
readonly rateLimited: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export const SERVER_COPY_KEYS: readonly (keyof ChatServerCopy)[] = [
|
|
31
|
+
"notFound",
|
|
32
|
+
"closed",
|
|
33
|
+
"invalidBody",
|
|
34
|
+
"empty",
|
|
35
|
+
"tooLong",
|
|
36
|
+
"freeTextDisabled",
|
|
37
|
+
"unknownQuickReply",
|
|
38
|
+
"contactInfo",
|
|
39
|
+
"rateLimited",
|
|
40
|
+
];
|
|
41
|
+
|
|
42
|
+
/** Declared structurally (no `@12-apps/i18n` dependency): a raw tag in, words out. */
|
|
43
|
+
export type ChatCopyResolver<T> = (context: { readonly locale?: string | null }) => T;
|
|
44
|
+
|
|
45
|
+
/** The words, or a resolver choosing them per request. */
|
|
46
|
+
export type ChatCopySource<T> = T | ChatCopyResolver<T>;
|
|
47
|
+
|
|
48
|
+
export function resolveCopy<T>(source: ChatCopySource<T>, locale: string | undefined): T {
|
|
49
|
+
return typeof source === "function" ? (source as ChatCopyResolver<T>)({ locale }) : source;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The words for one request. A resolver that has no complete pack for the
|
|
54
|
+
* reader's locale (it answers `undefined`, or a pack with a blank key) falls
|
|
55
|
+
* back to the configured words — the ones assembly checked, with no locale —
|
|
56
|
+
* rather than failing the request it was only meant to phrase.
|
|
57
|
+
*/
|
|
58
|
+
export function resolveCompleteCopy(source: ChatCopySource<ChatServerCopy>, locale: string | undefined): ChatServerCopy {
|
|
59
|
+
const words = resolveCopy(source, locale);
|
|
60
|
+
if (locale === undefined || missingCopy(words, SERVER_COPY_KEYS).length === 0) return words;
|
|
61
|
+
return resolveCopy(source, undefined);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Keys absent or blank — checked at assembly. */
|
|
65
|
+
export function missingCopy<T extends object>(copy: T | undefined, keys: readonly (keyof T)[]): string[] {
|
|
66
|
+
if (copy === undefined || copy === null) return keys.map(String);
|
|
67
|
+
return keys
|
|
68
|
+
.filter((key) => {
|
|
69
|
+
const value = copy[key];
|
|
70
|
+
return typeof value !== "string" || value.trim() === "";
|
|
71
|
+
})
|
|
72
|
+
.map(String);
|
|
73
|
+
}
|
package/src/server/db.ts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The database seam: exactly the delegate calls this package makes, shaped so
|
|
3
|
+
* a generated Prisma client carrying the `prisma/chat.prisma` models satisfies
|
|
4
|
+
* it structurally — and so a test fake implementing the interface behaves the
|
|
5
|
+
* same. Nothing here may rely on a client-specific error code.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export interface ChatThreadRow {
|
|
9
|
+
readonly id: string;
|
|
10
|
+
readonly tenantId: string;
|
|
11
|
+
readonly threadKey: string;
|
|
12
|
+
readonly createdAt: Date;
|
|
13
|
+
readonly lastMessageAt: Date | null;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface ChatMessageRow {
|
|
17
|
+
readonly id: string;
|
|
18
|
+
readonly threadId: string;
|
|
19
|
+
readonly tenantId: string;
|
|
20
|
+
readonly authorRole: string;
|
|
21
|
+
readonly authorId: string;
|
|
22
|
+
readonly body: string;
|
|
23
|
+
readonly quickKey: string | null;
|
|
24
|
+
readonly createdAt: Date;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface ChatReadMarkerRow {
|
|
28
|
+
readonly id: string;
|
|
29
|
+
readonly threadId: string;
|
|
30
|
+
readonly role: string;
|
|
31
|
+
readonly readerId: string;
|
|
32
|
+
readonly lastReadAt: Date;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
type ThreadKeyWhere = { tenantId_threadKey: { tenantId: string; threadKey: string } };
|
|
36
|
+
type MarkerKeyWhere = { threadId_role_readerId: { threadId: string; role: string; readerId: string } };
|
|
37
|
+
|
|
38
|
+
export interface ChatDb {
|
|
39
|
+
chatThread: {
|
|
40
|
+
findUnique(args: { where: ThreadKeyWhere }): Promise<ChatThreadRow | null>;
|
|
41
|
+
upsert(args: {
|
|
42
|
+
where: ThreadKeyWhere;
|
|
43
|
+
create: { tenantId: string; threadKey: string };
|
|
44
|
+
update: Record<string, never>;
|
|
45
|
+
}): Promise<ChatThreadRow>;
|
|
46
|
+
findMany(args: { where: { tenantId: string; threadKey: { in: string[] } } }): Promise<ChatThreadRow[]>;
|
|
47
|
+
update(args: { where: { id: string }; data: { lastMessageAt: Date } }): Promise<unknown>;
|
|
48
|
+
};
|
|
49
|
+
chatMessage: {
|
|
50
|
+
findMany(args: {
|
|
51
|
+
where: {
|
|
52
|
+
threadId: string;
|
|
53
|
+
authorRole?: string;
|
|
54
|
+
authorId?: string;
|
|
55
|
+
quickKey?: null;
|
|
56
|
+
createdAt?: { gt: Date };
|
|
57
|
+
};
|
|
58
|
+
orderBy: [{ createdAt: "desc" }, { id: "desc" }];
|
|
59
|
+
take: number;
|
|
60
|
+
}): Promise<ChatMessageRow[]>;
|
|
61
|
+
create(args: {
|
|
62
|
+
data: {
|
|
63
|
+
threadId: string;
|
|
64
|
+
tenantId: string;
|
|
65
|
+
authorRole: string;
|
|
66
|
+
authorId: string;
|
|
67
|
+
body: string;
|
|
68
|
+
quickKey: string | null;
|
|
69
|
+
createdAt: Date;
|
|
70
|
+
};
|
|
71
|
+
}): Promise<ChatMessageRow>;
|
|
72
|
+
count(args: {
|
|
73
|
+
where: { threadId: string; authorRole: { not: string }; createdAt?: { gt: Date } };
|
|
74
|
+
}): Promise<number>;
|
|
75
|
+
};
|
|
76
|
+
chatReadMarker: {
|
|
77
|
+
findUnique(args: { where: MarkerKeyWhere }): Promise<ChatReadMarkerRow | null>;
|
|
78
|
+
findMany(args: {
|
|
79
|
+
where: { threadId: { in: string[] }; role: string; readerId: string };
|
|
80
|
+
}): Promise<ChatReadMarkerRow[]>;
|
|
81
|
+
upsert(args: {
|
|
82
|
+
where: MarkerKeyWhere;
|
|
83
|
+
create: { threadId: string; role: string; readerId: string; lastReadAt: Date };
|
|
84
|
+
update: { lastReadAt: Date };
|
|
85
|
+
}): Promise<ChatReadMarkerRow>;
|
|
86
|
+
};
|
|
87
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { ChatServerCopy } from "./copy";
|
|
2
|
+
|
|
3
|
+
/** The routes' sentences in US English — pass by hand, never a default. */
|
|
4
|
+
export const EN_US_CHAT_SERVER_COPY: ChatServerCopy = {
|
|
5
|
+
notFound: "Conversation not found.",
|
|
6
|
+
closed: "This conversation is closed. You can still read the messages.",
|
|
7
|
+
invalidBody: "We could not read that message.",
|
|
8
|
+
empty: "Write a message before sending.",
|
|
9
|
+
tooLong: "A message can be up to {max} characters.",
|
|
10
|
+
freeTextDisabled: "Use one of the quick replies.",
|
|
11
|
+
unknownQuickReply: "That quick reply is not available.",
|
|
12
|
+
contactInfo: "For safety, phone numbers, e-mail addresses, links and social profiles cannot be sent.",
|
|
13
|
+
rateLimited: "Too many messages in a row. Wait a moment and try again.",
|
|
14
|
+
};
|