@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,333 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Contact information in a message: the filter that keeps a role from passing
|
|
3
|
+
* a way to reach somebody outside the thread.
|
|
4
|
+
*
|
|
5
|
+
* Generic on purpose. Digits, `@`, a scheme and a domain look the same in
|
|
6
|
+
* every language; the WORDS people use to dodge a filter do not ("nine", a
|
|
7
|
+
* local word for "at", the name of a messaging app). Those arrive as host
|
|
8
|
+
* vocabulary in {@link ContactVocabulary}, never baked in here.
|
|
9
|
+
*
|
|
10
|
+
* Errs toward refusing: a false refusal costs the sender a rephrase, a missed
|
|
11
|
+
* phone number is the harm the filter exists to prevent.
|
|
12
|
+
*
|
|
13
|
+
* The scanners read normalised copies of the text built in `contact-views.ts`.
|
|
14
|
+
*/
|
|
15
|
+
import { AT_MARK, compile, DOT_MARK, view, views, type CompiledVocabulary, type View } from "./contact-views";
|
|
16
|
+
|
|
17
|
+
export type { ContactVocabulary } from "./contact-views";
|
|
18
|
+
import type { ContactVocabulary } from "./contact-views";
|
|
19
|
+
|
|
20
|
+
/** What the filter can look for. */
|
|
21
|
+
export type ContactKind = "phone" | "email" | "url" | "handle";
|
|
22
|
+
|
|
23
|
+
export const CONTACT_KINDS: readonly ContactKind[] = ["phone", "email", "url", "handle"];
|
|
24
|
+
|
|
25
|
+
/*
|
|
26
|
+
* PHONE: at least PHONE_MIN_DIGITS digits inside any PHONE_WINDOW characters,
|
|
27
|
+
* whatever sits between them, measured after every run of non-alphanumeric
|
|
28
|
+
* characters (spaces, punctuation, symbols, line breaks) has been collapsed to
|
|
29
|
+
* one space. So `9,8,7`, `9 , 8 , 7` and `9a8b7` all cost one character per
|
|
30
|
+
* gap, and `98765 e 4321` costs three.
|
|
31
|
+
*
|
|
32
|
+
* Eight digits because a landline without its area code is eight; a mobile
|
|
33
|
+
* with or without its area code (9 or 11) contains eight. Sixteen characters
|
|
34
|
+
* because that is the widest a digit-per-two-characters spelling of eight
|
|
35
|
+
* digits gets (`9 8 7 6 5 4 3 2` is 15), with room for one short word
|
|
36
|
+
* between two groups (`98765 e 4321`), while ordinary money lines stay over
|
|
37
|
+
* it (`100,00, total 37,90` spans 17).
|
|
38
|
+
*
|
|
39
|
+
* Before the window, spans that legitimately carry numbers collapse (see
|
|
40
|
+
* NEUTRAL_RULES): clock times, amounts after a currency symbol, and the
|
|
41
|
+
* host's `neutralPatterns` (address units). A collapsed span still counts —
|
|
42
|
+
* a unit or a time as one digit, an amount as one to three by its length —
|
|
43
|
+
* so it cannot launder a phone's tail (`11 98765 $4321`,
|
|
44
|
+
* `11 98765 apto 4321`). A host span collapses only when it holds at most
|
|
45
|
+
* four digits; an amount only when it is a canonical price of at most four
|
|
46
|
+
* integer digits (`25`, `1250`, `1.250`, `85,90`, `1.250,00`) — what a
|
|
47
|
+
* courier quotes — so `$8.765.432`, `$98765,43` and `$54321` stay digits.
|
|
48
|
+
* No span collapses when a digit follows straight away, or when a run of
|
|
49
|
+
* five or more digits precedes it — a mobile's first group (`98765 ap 4321`,
|
|
50
|
+
* `119876$54321`), while a street number (`Rua A, 1234 apto 5678`) is at most
|
|
51
|
+
* four.
|
|
52
|
+
*
|
|
53
|
+
* Known costs, accepted because a missed number is the harm: a CEP-shaped
|
|
54
|
+
* postcode (`01310-100`), a full date (`02/10/2026`), and money without a
|
|
55
|
+
* currency symbol (`total 100,00 + 37,90`) are eight digits and are refused.
|
|
56
|
+
* A five-digit street number followed by a unit is refused too.
|
|
57
|
+
* Known misses: digits spread wider than the window (`9 oi 8 oi 7 ...`); a
|
|
58
|
+
* number whose first group is shaped like a time, an amount or a host unit
|
|
59
|
+
* followed by a word (`apt 98765 and 4321`, `12:34 or 5678`) — exactly the
|
|
60
|
+
* shape of `apt 1204 and 1205`; a landline split by a unit
|
|
61
|
+
* (`1234 apto 5678`) — exactly `Rua A, 1234 apto 5678`; and double
|
|
62
|
+
* laundering, both groups dressed as spans (`apto 98765 apto 4321`,
|
|
63
|
+
* `R$ 98765 e R$ 4321`) — indistinguishable from two units or two prices;
|
|
64
|
+
* and a landline or ten-digit number split by one canonical price
|
|
65
|
+
* (`9876 $5.432`) — exactly a street number and a price.
|
|
66
|
+
*/
|
|
67
|
+
const PHONE_MIN_DIGITS = 8;
|
|
68
|
+
const PHONE_WINDOW = 16;
|
|
69
|
+
/** Host spans: an address unit is at most four digits. */
|
|
70
|
+
const HOST_NEUTRAL_MAX_DIGITS = 4;
|
|
71
|
+
/** A run this long right before a span is a phone's first group, never a street number. */
|
|
72
|
+
const PHONE_GROUP_DIGITS = 5;
|
|
73
|
+
interface NeutralRule {
|
|
74
|
+
readonly pattern: RegExp;
|
|
75
|
+
readonly maxDigits: number;
|
|
76
|
+
/** How many digits the collapsed span still counts as. */
|
|
77
|
+
readonly weight: (digits: number) => number;
|
|
78
|
+
/** A further test the span must pass to collapse. */
|
|
79
|
+
readonly accepts?: (span: string) => boolean;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const ONE_DIGIT = (): number => 1;
|
|
83
|
+
/** An amount counts by its length: a phone's tail dressed as a price stays heavy. */
|
|
84
|
+
const amountWeight = (digits: number): number => (digits >= 5 ? 3 : digits === 4 ? 2 : 1);
|
|
85
|
+
/** A price as a courier writes one: at most four integer digits, a thousands dot, cents. */
|
|
86
|
+
const CANONICAL_PRICE = /^(?:\d{1,4}|\d\.\d{3})(?:,\d{2})?$/;
|
|
87
|
+
const amountOf = (span: string): string => span.replace(/^[^\d]+/, "");
|
|
88
|
+
|
|
89
|
+
/** Domain-free spans that carry digits and are not a phone. */
|
|
90
|
+
const NEUTRAL_RULES: readonly NeutralRule[] = [
|
|
91
|
+
/** A valid clock time: `19:30`, `9h30`. */
|
|
92
|
+
{ pattern: /(?<!\d)(?:[01]?\d|2[0-3])[:h][0-5]\d(?!\d)/g, maxDigits: 4, weight: ONE_DIGIT },
|
|
93
|
+
/** A canonical price after a currency symbol (`R$` ends in `$`): `$ 1.250,00` is the largest, six digits. */
|
|
94
|
+
{
|
|
95
|
+
pattern: /[$\u20AC\u00A3\u00A5]\s*\d[\d.]*(?:,\d{2})?/g,
|
|
96
|
+
maxDigits: 6,
|
|
97
|
+
weight: amountWeight,
|
|
98
|
+
accepts: (span) => CANONICAL_PRICE.test(amountOf(span)),
|
|
99
|
+
},
|
|
100
|
+
];
|
|
101
|
+
|
|
102
|
+
/*
|
|
103
|
+
* Top-level domains. A curated list, because "any two letters" read `no.de`
|
|
104
|
+
* and `ok.me` as domains. STRONG ones count on their own; PATH ones are also
|
|
105
|
+
* ordinary words (`me`, `to`, `site`, `do`, `in`) and count only with a path
|
|
106
|
+
* after them (`t.me/x`, `wa.me/55...`, `goo.gl/x`, `youtu.be/x`). Any other
|
|
107
|
+
* alphabetic top-level domain counts with a path of three or more characters
|
|
108
|
+
* (`some.link/abc`); a shorter path is how `S.Paulo/SP` is written. Multi-part
|
|
109
|
+
* ones (`com.br`) need no entry: the `com` already matches.
|
|
110
|
+
*/
|
|
111
|
+
const STRONG_TLDS = ["com", "net", "org", "br", "io", "info", "biz", "xyz", "ly", "gg", "app", "dev"];
|
|
112
|
+
const PATH_TLDS = ["me", "co", "tv", "us", "uk", "pt", "to", "cc", "ai", "link", "site", "online", "ee", "gl", "be", "do", "in", "am"];
|
|
113
|
+
const STRONG = STRONG_TLDS.join("|");
|
|
114
|
+
const ANY_TLD = [...STRONG_TLDS, ...PATH_TLDS].join("|");
|
|
115
|
+
|
|
116
|
+
const LABEL = "[a-z0-9](?:[a-z0-9-]*[a-z0-9])?";
|
|
117
|
+
const AT = `(?:@|${AT_MARK})`;
|
|
118
|
+
const DOT = `(?:\\.|${DOT_MARK})`;
|
|
119
|
+
/*
|
|
120
|
+
* Every pattern below starts behind a lookbehind that admits only the FIRST
|
|
121
|
+
* position of a run, so an unanchored search never restarts inside the run it
|
|
122
|
+
* just failed on — a long `a.a.a.a…` or `aaaa…` stays linear, not quadratic.
|
|
123
|
+
*/
|
|
124
|
+
const LOCAL = "(?<![a-z0-9._%+-])[a-z0-9._%+-]+";
|
|
125
|
+
/** Not inside a label, and not right after `label.` (that start was already tried). */
|
|
126
|
+
const HOST_START = "(?<![a-z0-9-])(?<![a-z0-9-]\\.)";
|
|
127
|
+
|
|
128
|
+
/** `ana@gmail`, glued on both sides, no top-level domain needed (`ana@gmail com`, `ana(at)gmail`). The domain starts with a letter, so `25@10h` is not one. */
|
|
129
|
+
const EMAIL_GLUED = new RegExp(`${LOCAL}@[a-z][a-z0-9-]+`);
|
|
130
|
+
/** `ana@host.tld`, nothing between: any alphabetic top-level domain. */
|
|
131
|
+
const EMAIL_TIGHT = new RegExp(`${LOCAL}@${LABEL}(?:\\.${LABEL})*\\.[a-z]{2,}\\b`);
|
|
132
|
+
/** `ana @ host . com`, `ana <at-word> host <dot-word> com`: spacing allowed, so the domain must be a known one. */
|
|
133
|
+
const EMAIL_SPACED = new RegExp(`${LOCAL}\\s*${AT}\\s*${LABEL}(?:\\s*${DOT}\\s*${LABEL})*?\\s*${DOT}\\s*(?:${ANY_TLD})\\b`);
|
|
134
|
+
const URL_SCHEME = /\b(?:https?:\/\/|www\.)\S+/;
|
|
135
|
+
/** A literal dot with nothing around it — `Cheguei. Com` is a sentence, `site.com` is not. */
|
|
136
|
+
const DOMAIN = new RegExp(`${HOST_START}(?:${LABEL}\\.)+(?:${STRONG})\\b`);
|
|
137
|
+
const DOMAIN_WITH_PATH = new RegExp(`${HOST_START}(?:${LABEL}\\.)+(?:${ANY_TLD})\\/\\S`);
|
|
138
|
+
const DOMAIN_WITH_LONG_PATH = new RegExp(`${HOST_START}(?:${LABEL}\\.)+[a-z]{2,}\\/[a-z0-9_-]{3,}`);
|
|
139
|
+
/** `site <dot-word> com`: a label of three or more, so `no ponto com` (at the spot, with) is not one. */
|
|
140
|
+
const DOMAIN_SPELLED = new RegExp(`(?<![a-z0-9-])[a-z0-9-]{3,}\\s*${DOT_MARK}\\s*(?:${STRONG})\\b`);
|
|
141
|
+
/** A literal `@` not glued to a preceding word (that is an e-mail), then a name starting with a letter. */
|
|
142
|
+
const HANDLE = /(?<![a-z0-9_.])@\s*[a-z_][a-z0-9_.]+/;
|
|
143
|
+
|
|
144
|
+
const NON_ALPHANUMERIC_RUN = /[^\p{L}\p{N}]+/gu;
|
|
145
|
+
const ASCII_DIGIT = /[0-9]/g;
|
|
146
|
+
const FOLLOWED_BY_DIGIT = /[^\p{L}\p{N}]*[0-9]/uy;
|
|
147
|
+
const SEPARATOR_CHAR = /^[^\p{L}\p{N}]$/u;
|
|
148
|
+
const DIGIT_CHAR = /^[0-9]$/;
|
|
149
|
+
|
|
150
|
+
/** How many digits (up to PHONE_GROUP_DIGITS) sit right before `index`, punctuation and spaces skipped. */
|
|
151
|
+
function digitRunBefore(text: string, index: number): number {
|
|
152
|
+
let at = index - 1;
|
|
153
|
+
while (at >= 0 && SEPARATOR_CHAR.test(text.charAt(at))) at -= 1;
|
|
154
|
+
let run = 0;
|
|
155
|
+
while (run < PHONE_GROUP_DIGITS && at >= 0 && DIGIT_CHAR.test(text.charAt(at))) {
|
|
156
|
+
run += 1;
|
|
157
|
+
at -= 1;
|
|
158
|
+
}
|
|
159
|
+
return run;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function digitsIn(span: string): number {
|
|
163
|
+
return span.match(ASCII_DIGIT)?.length ?? 0;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
function isNeutral(text: string, match: RegExpExecArray, rule: NeutralRule): boolean {
|
|
167
|
+
const digits = digitsIn(match[0]);
|
|
168
|
+
if (digits === 0 || digits > rule.maxDigits || !(rule.accepts?.(match[0]) ?? true)) return false;
|
|
169
|
+
FOLLOWED_BY_DIGIT.lastIndex = match.index + match[0].length;
|
|
170
|
+
if (FOLLOWED_BY_DIGIT.test(text)) return false;
|
|
171
|
+
return digitRunBefore(text, match.index) < PHONE_GROUP_DIGITS;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/** Collapse every span of `rule` that may be collapsed to one digit. */
|
|
175
|
+
function neutralise(text: string, rule: NeutralRule): string {
|
|
176
|
+
let out = "";
|
|
177
|
+
let from = 0;
|
|
178
|
+
for (const match of text.matchAll(rule.pattern)) {
|
|
179
|
+
if (!isNeutral(text, match, rule)) continue;
|
|
180
|
+
out += `${text.slice(from, match.index)} ${"0".repeat(rule.weight(digitsIn(match[0])))} `;
|
|
181
|
+
from = match.index + match[0].length;
|
|
182
|
+
}
|
|
183
|
+
return out + text.slice(from);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** See PHONE_MIN_DIGITS / PHONE_WINDOW above. */
|
|
187
|
+
function hasPhone(scan: string, compiled: CompiledVocabulary): boolean {
|
|
188
|
+
const hostRules = compiled.neutral.map((pattern) => ({ pattern, maxDigits: HOST_NEUTRAL_MAX_DIGITS, weight: ONE_DIGIT }));
|
|
189
|
+
const blanked = [...NEUTRAL_RULES, ...hostRules].reduce(neutralise, scan);
|
|
190
|
+
const compact = blanked.replace(NON_ALPHANUMERIC_RUN, " ");
|
|
191
|
+
const positions = Array.from(compact.matchAll(ASCII_DIGIT), (match) => match.index);
|
|
192
|
+
for (let last = PHONE_MIN_DIGITS - 1; last < positions.length; last += 1) {
|
|
193
|
+
const first = positions[last - PHONE_MIN_DIGITS + 1] ?? 0;
|
|
194
|
+
if ((positions[last] ?? Infinity) - first < PHONE_WINDOW) return true;
|
|
195
|
+
}
|
|
196
|
+
return false;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function matchesHost(reading: View, extra: readonly RegExp[]): boolean {
|
|
200
|
+
const texts = [reading.raw, reading.folded, reading.scan, reading.collapsed];
|
|
201
|
+
return extra.some((pattern) => texts.some((text) => pattern.test(text)));
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
type Scanner = (reading: View, compiled: CompiledVocabulary) => boolean;
|
|
205
|
+
|
|
206
|
+
/** One scanner per kind. `extraPatterns` count as `handle` — they name a way to be reached. */
|
|
207
|
+
const SCANNERS: Readonly<Record<ContactKind, Scanner>> = {
|
|
208
|
+
phone: (reading, compiled) => hasPhone(reading.scan, compiled),
|
|
209
|
+
email: ({ scan }) => EMAIL_GLUED.test(scan) || EMAIL_TIGHT.test(scan) || EMAIL_SPACED.test(scan),
|
|
210
|
+
url: ({ scan }) => [URL_SCHEME, DOMAIN, DOMAIN_WITH_PATH, DOMAIN_WITH_LONG_PATH, DOMAIN_SPELLED].some((pattern) => pattern.test(scan)),
|
|
211
|
+
handle: (reading, compiled) => HANDLE.test(reading.scan) || matchesHost(reading, compiled.extra),
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
function detectCompiled(text: string, kinds: readonly ContactKind[], compiled: CompiledVocabulary): ContactKind[] {
|
|
215
|
+
if (kinds.length === 0) return [];
|
|
216
|
+
const readings = views(text, compiled);
|
|
217
|
+
return CONTACT_KINDS.filter((kind) => kinds.includes(kind) && readings.some((reading) => SCANNERS[kind](reading, compiled)));
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** Which of `kinds` the text contains, in {@link CONTACT_KINDS} order. Empty means the message may go. */
|
|
221
|
+
export function detectContactInfo(
|
|
222
|
+
text: string,
|
|
223
|
+
kinds: readonly ContactKind[],
|
|
224
|
+
vocabulary: ContactVocabulary = {},
|
|
225
|
+
): ContactKind[] {
|
|
226
|
+
return detectCompiled(text, kinds, compile(vocabulary));
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** A character a split number can be cut at: a digit or `.`. Counts only when BOTH sides of the cut have one. */
|
|
230
|
+
const CONTACT_EDGE = /^[0-9.]$/;
|
|
231
|
+
/** `@` or a host at/dot word: an address cut there needs only ONE side (`ana` | `@` | `gmail.com`). */
|
|
232
|
+
const ADDRESS_EDGE = new RegExp(`^[@${AT_MARK}${DOT_MARK}]$`);
|
|
233
|
+
const EDGE_SKIP = new RegExp(`[^\\p{L}\\p{N}@.${AT_MARK}${DOT_MARK}]`, "u");
|
|
234
|
+
/** A message that is nothing but a top-level domain, maybe with more after it: `com`, `com.br`, `me/ana`. */
|
|
235
|
+
const HOLDS_AT = new RegExp(`[@${AT_MARK}]`);
|
|
236
|
+
const LONE_TLD = new RegExp(`^\\s*(?:${ANY_TLD})(?:[./]\\S*)?\\s*$`);
|
|
237
|
+
|
|
238
|
+
/** One message as the chain reads it. */
|
|
239
|
+
interface Piece {
|
|
240
|
+
readonly raw: string;
|
|
241
|
+
readonly scan: string;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** The first (or last) character of a reading that is not a space or ordinary punctuation. */
|
|
245
|
+
function edge(scan: string, side: "start" | "end"): string {
|
|
246
|
+
const chars = [...scan];
|
|
247
|
+
if (side === "end") chars.reverse();
|
|
248
|
+
return chars.find((char) => !EDGE_SKIP.test(char)) ?? "";
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** `meusite.` then `com`: a domain cut at its dot, re-glued with nothing between. */
|
|
252
|
+
function cutAtDot(earlier: string, later: string): boolean {
|
|
253
|
+
return edge(earlier, "end") === "." && LONE_TLD.test(later);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Whether two consecutive messages may be one contact cut in two: digit (or
|
|
258
|
+
* dot) on both sides of the cut; an address symbol on either side; a later
|
|
259
|
+
* message opening with `.` (`.com`); or an earlier one ending in `.` when it
|
|
260
|
+
* holds an `@` (`ana@gmail.` | `com`) or the later one is a lone top-level
|
|
261
|
+
* domain (`meusite.` | `com`). A sentence ending in `.` is not enough on its
|
|
262
|
+
* own — it is how most sentences end.
|
|
263
|
+
*/
|
|
264
|
+
function touches(earlier: string, later: string): boolean {
|
|
265
|
+
const end = edge(earlier, "end");
|
|
266
|
+
const start = edge(later, "start");
|
|
267
|
+
if (ADDRESS_EDGE.test(end) || ADDRESS_EDGE.test(start) || start === ".") return true;
|
|
268
|
+
if (end === "." && (HOLDS_AT.test(earlier) || LONE_TLD.test(later))) return true;
|
|
269
|
+
return CONTACT_EDGE.test(end) && CONTACT_EDGE.test(start);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/** The recent messages that run contiguously into the draft, oldest first; stops at the first clean cut. */
|
|
273
|
+
function chainBefore(recent: readonly string[], draft: Piece, compiled: CompiledVocabulary): Piece[] {
|
|
274
|
+
const chain: Piece[] = [];
|
|
275
|
+
let later = draft.scan;
|
|
276
|
+
for (const raw of [...recent].reverse()) {
|
|
277
|
+
const earlier = view(raw, compiled).scan;
|
|
278
|
+
if (!touches(earlier, later)) break;
|
|
279
|
+
chain.unshift({ raw, scan: earlier });
|
|
280
|
+
later = earlier;
|
|
281
|
+
}
|
|
282
|
+
return chain;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** The pieces as one text: a line break between two, nothing between a domain cut at its dot. */
|
|
286
|
+
function joinPieces(pieces: readonly Piece[]): string {
|
|
287
|
+
let text = "";
|
|
288
|
+
let previous: Piece | null = null;
|
|
289
|
+
for (const piece of pieces) {
|
|
290
|
+
if (previous === null) text = piece.raw;
|
|
291
|
+
else text = cutAtDot(previous.scan, piece.scan) ? `${text.trimEnd()}${piece.raw.trimStart()}` : `${text}\n${piece.raw}`;
|
|
292
|
+
previous = piece;
|
|
293
|
+
}
|
|
294
|
+
return text;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* {@link detectContactInfo} for a draft that may finish something the author
|
|
299
|
+
* started in earlier messages (`98765`, then `4321`; `9`, `8`, `7`… one digit
|
|
300
|
+
* a message; `ana arroba gmail.`, then `com`).
|
|
301
|
+
*
|
|
302
|
+
* `recent` is the SAME author's earlier bodies in the thread, oldest first.
|
|
303
|
+
* Only the CHAIN that runs into the draft is read (see `touches`): walking
|
|
304
|
+
* back from the draft, the walk stops at the first clean cut. `Cheguei` then
|
|
305
|
+
* `1204` is a clean cut; `98765,` then `4321` is not. The chain and the draft
|
|
306
|
+
* are joined with line breaks, which the phone window counts as one
|
|
307
|
+
* character — except a domain cut at its dot, which is glued back.
|
|
308
|
+
*
|
|
309
|
+
* Known misses, the price of reading only a contiguous chain: a group opened
|
|
310
|
+
* by a word (`98765` then `e 4321`), and a digit trickle with chatter in the
|
|
311
|
+
* middle (`987654`, `Oi`, `3`, `2`).
|
|
312
|
+
*
|
|
313
|
+
* Refuses a kind found in the draft alone, or in chain + draft but NOT in the
|
|
314
|
+
* chain alone — a kind the earlier messages already carried (they were sent,
|
|
315
|
+
* so they passed) never refuses an innocent draft; only a draft that
|
|
316
|
+
* contributes to the match does. So `ana@gmail.` then `com` is refused at
|
|
317
|
+
* `ana@gmail.` (an e-mail on its own), not at `com`.
|
|
318
|
+
*/
|
|
319
|
+
export function detectContactInfoAcross(
|
|
320
|
+
recent: readonly string[],
|
|
321
|
+
draft: string,
|
|
322
|
+
kinds: readonly ContactKind[],
|
|
323
|
+
vocabulary: ContactVocabulary = {},
|
|
324
|
+
): ContactKind[] {
|
|
325
|
+
const compiled = compile(vocabulary);
|
|
326
|
+
const alone = detectCompiled(draft, kinds, compiled);
|
|
327
|
+
const last: Piece = { raw: draft, scan: view(draft, compiled).scan };
|
|
328
|
+
const chain = kinds.length === 0 ? [] : chainBefore(recent, last, compiled);
|
|
329
|
+
if (chain.length === 0) return alone;
|
|
330
|
+
const already = detectCompiled(joinPieces(chain), kinds, compiled);
|
|
331
|
+
const joined = detectCompiled(joinPieces([...chain, last]), kinds, compiled);
|
|
332
|
+
return CONTACT_KINDS.filter((kind) => alone.includes(kind) || (joined.includes(kind) && !already.includes(kind)));
|
|
333
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Thrown at ASSEMBLY for a miswired host — at the call site, never at a user's tap. */
|
|
2
|
+
export class ChatConfigError extends Error {
|
|
3
|
+
readonly code = "invalid_config";
|
|
4
|
+
|
|
5
|
+
constructor(message: string) {
|
|
6
|
+
super(`@12-apps/chat: ${message}`);
|
|
7
|
+
this.name = "ChatConfigError";
|
|
8
|
+
}
|
|
9
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The wire vocabulary both halves share — what the routes answer and what the
|
|
3
|
+
* thread screen reads. Framework-free, so every bundle may import it.
|
|
4
|
+
*
|
|
5
|
+
* A participant is known to the others ONLY by its role's label: no person
|
|
6
|
+
* id, no name, no contact detail ever crosses the wire. That is the point of
|
|
7
|
+
* the package, not a detail of it.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/** One message as a participant sees it. */
|
|
11
|
+
export interface ChatWireMessage {
|
|
12
|
+
readonly id: string;
|
|
13
|
+
/** The author's role key (host vocabulary). */
|
|
14
|
+
readonly role: string;
|
|
15
|
+
/** The author's role LABEL — the only name the thread ever shows. */
|
|
16
|
+
readonly label: string;
|
|
17
|
+
/** Whether the caller wrote it (or, for a shared role, the caller's role did). */
|
|
18
|
+
readonly mine: boolean;
|
|
19
|
+
readonly body: string;
|
|
20
|
+
/** ISO-8601. */
|
|
21
|
+
readonly createdAt: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** A canned line a role may send with one tap. */
|
|
25
|
+
export interface ChatQuickReply {
|
|
26
|
+
readonly key: string;
|
|
27
|
+
readonly text: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** What the caller may do in the thread, decided by the host per request. */
|
|
31
|
+
export interface ChatWireThread {
|
|
32
|
+
readonly me: { readonly role: string; readonly label: string };
|
|
33
|
+
readonly canWrite: boolean;
|
|
34
|
+
/** False ⇒ the caller may only send quick replies. */
|
|
35
|
+
readonly freeText: boolean;
|
|
36
|
+
readonly maxLength: number;
|
|
37
|
+
readonly quickReplies: readonly ChatQuickReply[];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** `GET` — the thread and its messages, oldest first. */
|
|
41
|
+
export interface ChatThreadPayload {
|
|
42
|
+
readonly thread: ChatWireThread;
|
|
43
|
+
readonly messages: readonly ChatWireMessage[];
|
|
44
|
+
/** Messages by others since the caller last read. */
|
|
45
|
+
readonly unread: number;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Machine codes a refused send answers with, beside the host's sentence. */
|
|
49
|
+
export type ChatErrorCode =
|
|
50
|
+
| "unauthenticated"
|
|
51
|
+
| "not_found"
|
|
52
|
+
| "closed"
|
|
53
|
+
| "invalid_body"
|
|
54
|
+
| "empty"
|
|
55
|
+
| "too_long"
|
|
56
|
+
| "free_text_disabled"
|
|
57
|
+
| "unknown_quick_reply"
|
|
58
|
+
| "contact_info"
|
|
59
|
+
| "rate_limited";
|
|
60
|
+
|
|
61
|
+
/** Keyed by every code, so a code added above fails to compile until it is listed here. */
|
|
62
|
+
const KNOWN_CODES = {
|
|
63
|
+
unauthenticated: true,
|
|
64
|
+
not_found: true,
|
|
65
|
+
closed: true,
|
|
66
|
+
invalid_body: true,
|
|
67
|
+
empty: true,
|
|
68
|
+
too_long: true,
|
|
69
|
+
free_text_disabled: true,
|
|
70
|
+
unknown_quick_reply: true,
|
|
71
|
+
contact_info: true,
|
|
72
|
+
rate_limited: true,
|
|
73
|
+
} as const satisfies Record<ChatErrorCode, true>;
|
|
74
|
+
|
|
75
|
+
/** Every code above, for a client deciding whether a refusal is the package's own. */
|
|
76
|
+
export const CHAT_ERROR_CODES = Object.keys(KNOWN_CODES) as readonly ChatErrorCode[];
|
|
77
|
+
|
|
78
|
+
/** The body of every refusal. */
|
|
79
|
+
export interface ChatWireError {
|
|
80
|
+
readonly error: ChatErrorCode;
|
|
81
|
+
readonly message: string;
|
|
82
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@12-apps/chat` — the shared vocabulary: wire types, the contact-info
|
|
3
|
+
* filter, and the config error. Framework-free; every bundle may import it.
|
|
4
|
+
*
|
|
5
|
+
* The halves live behind their own subpaths: `./server` (routes and reads),
|
|
6
|
+
* `./client` (the API client and the thread state hook), `./react` (a web
|
|
7
|
+
* host's surface), `./native` (a React Native host's surface), and the wiring
|
|
8
|
+
* manifests under `./manifest*`.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
export { ChatConfigError } from "./core/errors";
|
|
12
|
+
export {
|
|
13
|
+
CONTACT_KINDS,
|
|
14
|
+
detectContactInfo,
|
|
15
|
+
detectContactInfoAcross,
|
|
16
|
+
type ContactKind,
|
|
17
|
+
type ContactVocabulary,
|
|
18
|
+
} from "./core/contact";
|
|
19
|
+
export type {
|
|
20
|
+
ChatErrorCode,
|
|
21
|
+
ChatQuickReply,
|
|
22
|
+
ChatThreadPayload,
|
|
23
|
+
ChatWireError,
|
|
24
|
+
ChatWireMessage,
|
|
25
|
+
ChatWireThread,
|
|
26
|
+
} from "./core/types";
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@12-apps/chat/manifest` — the SHARED wiring manifest.
|
|
3
|
+
*
|
|
4
|
+
* Identity, the Prisma contribution and the runtime inventory: HTTP routes
|
|
5
|
+
* for a server host, the thread surface for a web host AND for a React Native
|
|
6
|
+
* host. `@12-apps/wiring` is a TYPE-ONLY devDependency; the producer
|
|
7
|
+
* assertions run in this package's own suite.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { PackageManifest } from "@12-apps/wiring";
|
|
11
|
+
|
|
12
|
+
export const chatManifest = {
|
|
13
|
+
name: "@12-apps/chat",
|
|
14
|
+
contract: 1,
|
|
15
|
+
db: { partial: "prisma/chat.prisma", migrations: "prisma/migrations" },
|
|
16
|
+
observability: { namespace: "chat" },
|
|
17
|
+
server: ["http"],
|
|
18
|
+
web: ["surface"],
|
|
19
|
+
native: ["surface"],
|
|
20
|
+
} as const satisfies PackageManifest;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@12-apps/chat/manifest/native` — `surface.create` IS `createNativeChat`,
|
|
3
|
+
* behind its own subpath so a native bundle never resolves the web surface.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { AnyNativeManifest } from "@12-apps/wiring";
|
|
7
|
+
|
|
8
|
+
import { createNativeChat } from "../native/index";
|
|
9
|
+
|
|
10
|
+
export const chatNativeManifest = {
|
|
11
|
+
name: "@12-apps/chat",
|
|
12
|
+
surface: { create: createNativeChat },
|
|
13
|
+
} as const satisfies AnyNativeManifest;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@12-apps/chat/manifest/server` — `http.create` IS `createApiChat`. A host
|
|
3
|
+
* that mounts one route set per audience calls the factory once per audience
|
|
4
|
+
* with its own `authorize`, binding the manifest for whichever it adopts.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { AnyServerManifest } from "@12-apps/wiring";
|
|
8
|
+
|
|
9
|
+
import { createApiChat } from "../server/index";
|
|
10
|
+
|
|
11
|
+
export const chatServerManifest = {
|
|
12
|
+
name: "@12-apps/chat",
|
|
13
|
+
http: { create: createApiChat },
|
|
14
|
+
} as const satisfies AnyServerManifest;
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@12-apps/chat/manifest/web` — `surface.create` IS `createWebChat`. No
|
|
3
|
+
* `areas`: a thread is not a page of its own, it sits inside whatever screen
|
|
4
|
+
* shows the thing it is about, which only the host knows.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import type { AnyWebManifest } from "@12-apps/wiring";
|
|
8
|
+
|
|
9
|
+
import { createWebChat } from "../react/index";
|
|
10
|
+
|
|
11
|
+
export const chatWebManifest = {
|
|
12
|
+
name: "@12-apps/chat",
|
|
13
|
+
surface: { create: createWebChat },
|
|
14
|
+
} as const satisfies AnyWebManifest;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The React Native composer: the design system's native field and button.
|
|
3
|
+
* The keyboard's send key submits and the keyboard STAYS UP
|
|
4
|
+
* (`submitBehavior="submit"`), so a conversation is typed without the
|
|
5
|
+
* keyboard bouncing after every message; the field's own change event is
|
|
6
|
+
* `onChangeText`, which is why this piece is per platform.
|
|
7
|
+
*
|
|
8
|
+
* The field stays editable while a message is in flight — making it inert
|
|
9
|
+
* would close the keyboard. Only the send action is gated (here, and again in
|
|
10
|
+
* the thread's submit).
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { Button } from "@12-apps/ui/form/Button";
|
|
14
|
+
import { Input } from "@12-apps/ui/form/Input";
|
|
15
|
+
import { Box } from "@12-apps/ui/layout/Box";
|
|
16
|
+
import type { JSX } from "react";
|
|
17
|
+
import type { TextInputProps } from "react-native";
|
|
18
|
+
|
|
19
|
+
import type { ChatComposerProps } from "../ui/thread-view";
|
|
20
|
+
|
|
21
|
+
/** The native field's own events, typed by react-native itself. */
|
|
22
|
+
type NativeFieldEvents = Required<
|
|
23
|
+
Pick<TextInputProps, "onChangeText" | "onSubmitEditing" | "returnKeyType" | "submitBehavior" | "accessibilityLabel">
|
|
24
|
+
>;
|
|
25
|
+
|
|
26
|
+
export function NativeComposer(props: ChatComposerProps): JSX.Element {
|
|
27
|
+
// A bag rather than attributes so the web type-check (`tsc -p tsconfig.json`,
|
|
28
|
+
// which sees the web `Input`) accepts the file too; `tsconfig.native.json`
|
|
29
|
+
// checks the same spread against the native `Input`.
|
|
30
|
+
const native: NativeFieldEvents = {
|
|
31
|
+
onChangeText: props.onChange,
|
|
32
|
+
onSubmitEditing: props.onSubmit,
|
|
33
|
+
returnKeyType: "send",
|
|
34
|
+
submitBehavior: "submit",
|
|
35
|
+
accessibilityLabel: props.copy.placeholder,
|
|
36
|
+
};
|
|
37
|
+
return (
|
|
38
|
+
<Box direction="row" gap={1} align="center">
|
|
39
|
+
<Box flex={1}>
|
|
40
|
+
<Input fullWidth value={props.value} placeholder={props.copy.placeholder} maxLength={props.maxLength} testID="chat-input" {...native} />
|
|
41
|
+
</Box>
|
|
42
|
+
<Button
|
|
43
|
+
variant="solid"
|
|
44
|
+
onClick={props.onSubmit}
|
|
45
|
+
disabled={props.sending || props.value.trim() === ""}
|
|
46
|
+
testID="chat-send"
|
|
47
|
+
>
|
|
48
|
+
{props.sending ? props.copy.sending : props.copy.send}
|
|
49
|
+
</Button>
|
|
50
|
+
</Box>
|
|
51
|
+
);
|
|
52
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@12-apps/chat/native` — the React Native host's surface:
|
|
3
|
+
* `createNativeChat(config) → { ChatThread }`. The same thread screen as the
|
|
4
|
+
* web surface, drawn with `@12-apps/ui`'s native primitives (its
|
|
5
|
+
* `react-native` export condition), with a native frame, list and composer.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { buildChatSurface, type ChatSurface, type ChatSurfaceConfig } from "../ui/surface";
|
|
9
|
+
import { NativeComposer } from "./composer";
|
|
10
|
+
import { NativeBubble, NativeFrame, NativeMessageList } from "./layout";
|
|
11
|
+
|
|
12
|
+
export function createNativeChat(config: ChatSurfaceConfig): ChatSurface {
|
|
13
|
+
return buildChatSurface(config, {
|
|
14
|
+
Frame: NativeFrame,
|
|
15
|
+
MessageList: NativeMessageList,
|
|
16
|
+
Bubble: NativeBubble,
|
|
17
|
+
Composer: NativeComposer,
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export type { ChatSurface, ChatSurfaceConfig, ChatThreadProps } from "../ui/surface";
|