@kennra/app-sdk 0.0.0 → 0.2.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.
@@ -0,0 +1,198 @@
1
+ export const DEFAULT_HISTORY_YEARS = 3;
2
+ export const MAX_HISTORY_YEARS = 10;
3
+ /** How many years back the installation looks for a new contact (the `historyYears` setting, clamped). */
4
+ export function historyYearsOf(ctx) {
5
+ const raw = Number(ctx.config['historyYears'] ?? DEFAULT_HISTORY_YEARS);
6
+ if (!Number.isFinite(raw))
7
+ return DEFAULT_HISTORY_YEARS;
8
+ return Math.min(MAX_HISTORY_YEARS, Math.max(1, Math.round(raw)));
9
+ }
10
+ /** Messages read per tick across every request. */
11
+ export const BACKFILL_MESSAGES_PER_RUN = 300;
12
+ /** Calendar pages per tick across every request. */
13
+ export const BACKFILL_EVENT_PAGES_PER_RUN = 20;
14
+ export const emptyBackfillReport = () => ({
15
+ requests: 0,
16
+ finished: 0,
17
+ meetings: 0,
18
+ emails: 0,
19
+ seen: 0,
20
+ waiting: 0,
21
+ errors: [],
22
+ });
23
+ const connOf = (t) => `${t.userId}|${t.connectionKey}`;
24
+ const kindOf = (t) => (t.kind === 'calendar' ? 'meetings' : 'emails');
25
+ const stateKey = (partyId) => `backfill:${partyId}`;
26
+ /** Whether an ingest result means the item is in Kennra now (captured now or before). */
27
+ const kept = (r) => r.ok && r.outcome !== 'skipped' && r.outcome !== 'cancelled';
28
+ /** An address or domain an item is with (an attendee or the organizer). */
29
+ export function hasTerm(emails, term) {
30
+ return emails.some((a) => {
31
+ const x = a.toLowerCase();
32
+ return term.includes('@') ? x === term : x.endsWith(`@${term}`);
33
+ });
34
+ }
35
+ /** One tick: the requests Kennra has for this installation, oldest first, within the run's budget. */
36
+ export async function runCaptureBackfills(ctx, deps) {
37
+ const report = emptyBackfillReport();
38
+ let requests;
39
+ try {
40
+ requests = await ctx.kennra.captureBackfills();
41
+ }
42
+ catch (e) {
43
+ // An installation on a grant without backfill (or Kennra without it): nothing to do.
44
+ report.errors.push(`backfill: ${e.message}`.slice(0, 300));
45
+ return report;
46
+ }
47
+ if (!requests.length)
48
+ return report;
49
+ const conns = (await ctx.kennra.userConnections()).filter((c) => c.status === 'connected' && (c.kind === 'calendar' || c.kind === 'mailbox'));
50
+ const internal = new Set(deps.internalDomains.map((d) => d.toLowerCase()));
51
+ const budget = {
52
+ messages: deps.limits?.messages ?? BACKFILL_MESSAGES_PER_RUN,
53
+ pages: deps.limits?.pages ?? BACKFILL_EVENT_PAGES_PER_RUN,
54
+ };
55
+ // Connections the provider asked to slow down for, for the rest of this run (across requests).
56
+ const limited = new Set();
57
+ for (const req of requests) {
58
+ // Stopped (the run's deadline, a shutdown): each request's cursor is saved; the next run goes on.
59
+ if ((budget.messages <= 0 && budget.pages <= 0) || ctx.signal.aborted)
60
+ break;
61
+ report.requests++;
62
+ await runRequest(ctx, deps, req, conns, internal, budget, limited, report);
63
+ }
64
+ return report;
65
+ }
66
+ /** Works on one request until it is done, the budget is spent or what is left waits for the provider. */
67
+ async function runRequest(ctx, deps, req, conns, internal, budget, limited, report) {
68
+ const now = deps.now();
69
+ const terms = [
70
+ ...new Set((req.partyType === 'person' ? req.emails : req.domains)
71
+ .map((t) => t.trim().toLowerCase())
72
+ // Never the workspace's own domain or its people: those are internal.
73
+ .filter((t) => t && !internal.has(t.includes('@') ? (t.split('@')[1] ?? '') : t))),
74
+ ];
75
+ const saved = await ctx.state.get(stateKey(req.partyId));
76
+ let cursor;
77
+ if (saved?.backfillId === req.backfillId)
78
+ cursor = saved;
79
+ else {
80
+ const since = new Date(now.getTime() - historyYearsOf(ctx) * 365.25 * 86_400_000);
81
+ cursor = {
82
+ backfillId: req.backfillId,
83
+ since: since.toISOString(),
84
+ // Each member's own connections only: their own token, captured as theirs.
85
+ tasks: conns.flatMap((c) => {
86
+ const kind = c.kind;
87
+ const base = { kind, userId: c.userId, connectionKey: c.connectionKey };
88
+ if (deps.searches[kind].perTerm === false)
89
+ return terms.length ? [{ ...base, term: terms.join(','), terms }] : [];
90
+ return terms.map((term) => ({ ...base, term }));
91
+ }),
92
+ meetings: 0,
93
+ emails: 0,
94
+ seen: 0,
95
+ skipped: 0,
96
+ };
97
+ }
98
+ const since = new Date(cursor.since);
99
+ const progress = async (status, error, waiting = []) => {
100
+ await ctx.kennra
101
+ .reportCaptureBackfill({
102
+ backfillId: req.backfillId,
103
+ status,
104
+ counters: {
105
+ meetings: cursor.meetings,
106
+ emails: cursor.emails,
107
+ seen: cursor.seen,
108
+ skipped: cursor.skipped,
109
+ },
110
+ since: cursor.since,
111
+ ...(waiting.length ? { waiting } : {}),
112
+ ...(error ? { error: error.slice(0, 500) } : {}),
113
+ })
114
+ .catch((e) => report.errors.push(`backfill report: ${e.message}`.slice(0, 300)));
115
+ };
116
+ const counted = { meetings: cursor.meetings, emails: cursor.emails, seen: cursor.seen };
117
+ const tally = () => {
118
+ report.meetings += cursor.meetings - counted.meetings;
119
+ report.emails += cursor.emails - counted.emails;
120
+ report.seen += cursor.seen - counted.seen;
121
+ Object.assign(counted, { meetings: cursor.meetings, emails: cursor.emails, seen: cursor.seen });
122
+ };
123
+ if (!req.progress)
124
+ await progress('running');
125
+ // Calendars first: meetings show up even when a mailbox waits for the provider's quota.
126
+ const order = [
127
+ ...cursor.tasks.filter((t) => t.kind === 'calendar'),
128
+ ...cursor.tasks.filter((t) => t.kind !== 'calendar'),
129
+ ];
130
+ for (const task of order) {
131
+ if (ctx.signal.aborted)
132
+ break;
133
+ const search = deps.searches[task.kind];
134
+ if (task.done || limited.has(connOf(task)))
135
+ continue;
136
+ if (budget[search.budget] <= 0)
137
+ continue;
138
+ try {
139
+ const token = await deps.accessToken(task.userId, task.connectionKey);
140
+ if (!token)
141
+ throw new Error('no refresh token stored (reconnect)');
142
+ while (budget[search.budget] > 0 && !ctx.signal.aborted) {
143
+ const page = await search.page({ task, token, since, now, budget, signal: ctx.signal });
144
+ cursor.seen += page.seen;
145
+ cursor.skipped += page.skipped ?? 0;
146
+ if (page.items.length)
147
+ for (const r of await ctx.kennra.ingest('live', page.items)) {
148
+ if (kept(r))
149
+ cursor[kindOf(task)]++;
150
+ else
151
+ cursor.skipped++;
152
+ }
153
+ if (page.nextPageToken)
154
+ task.pageToken = page.nextPageToken;
155
+ else {
156
+ delete task.pageToken;
157
+ task.done = true;
158
+ break;
159
+ }
160
+ }
161
+ }
162
+ catch (e) {
163
+ if (deps.rateLimited(e)) {
164
+ // Only this connection waits; the cursor keeps its place for the next run.
165
+ limited.add(connOf(task));
166
+ report.errors.push(`backfill ${task.kind}: ${deps.provider} asks to slow down; going on next run`);
167
+ await ctx.state.put(stateKey(req.partyId), cursor);
168
+ tally();
169
+ continue;
170
+ }
171
+ // This connection can't be read (revoked, refused): the others go on.
172
+ task.done = true;
173
+ task.error = String(e.message ?? e).slice(0, 200);
174
+ report.errors.push(`backfill ${task.kind} ${task.userId}: ${task.error}`);
175
+ }
176
+ await ctx.state.put(stateKey(req.partyId), cursor);
177
+ tally();
178
+ await progress('running');
179
+ }
180
+ tally();
181
+ const left = cursor.tasks.filter((t) => !t.done);
182
+ if (!left.length) {
183
+ const failed = cursor.tasks.length > 0 && cursor.tasks.every((t) => t.error);
184
+ await progress(failed ? 'failed' : 'done', failed ? cursor.tasks[0].error : undefined);
185
+ await ctx.state.put(stateKey(req.partyId), null);
186
+ report.finished++;
187
+ return;
188
+ }
189
+ await ctx.state.put(stateKey(req.partyId), cursor);
190
+ const waiting = [...new Set(left.filter((t) => limited.has(connOf(t))).map(kindOf))].sort();
191
+ if (left.every((t) => limited.has(connOf(t)))) {
192
+ // All that is left waits for the provider: say what was found and what waits (no endless spinner).
193
+ report.waiting++;
194
+ await progress('partial', undefined, waiting);
195
+ }
196
+ else if (waiting.length)
197
+ await progress('running', undefined, waiting);
198
+ }
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Building blocks for capture apps that read each member's own calendar and mailbox (docs/15
3
+ * §9.3): a per-member throttle that waits out a provider's rate limit within a run's budget, a
4
+ * bounded pool, and the rules for reading an email that do not depend on the provider (addresses
5
+ * and display names in a header, the new part of a reply, HTML to text, automated mail and
6
+ * internal-only messages). Pure and provider-neutral: each app keeps its provider's API, error
7
+ * classes and wording, and decides which errors are a rate limit.
8
+ */
9
+ export interface ThrottleOptions {
10
+ /** Quota units per second per member. */
11
+ unitsPerSecond: number;
12
+ /** Units that may be spent at once after a quiet spell. */
13
+ burst: number;
14
+ /** Calls in flight per member. */
15
+ concurrency: number;
16
+ /** The longest a run waits in total for rate limits per member before it stops. */
17
+ maxBackoffMs: number;
18
+ now: () => number;
19
+ sleep: (ms: number) => Promise<void>;
20
+ random: () => number;
21
+ }
22
+ export declare const DEFAULT_THROTTLE: ThrottleOptions;
23
+ /** One member's token bucket and in-flight limit. */
24
+ export declare class UserThrottle {
25
+ private readonly o;
26
+ private tokens;
27
+ private last;
28
+ private active;
29
+ private readonly waiting;
30
+ private pausedUntil;
31
+ constructor(o: ThrottleOptions);
32
+ private refill;
33
+ /** Waits for a free slot and `cost` units. Call `release` when the call is done. */
34
+ acquire(cost: number): Promise<void>;
35
+ release(): void;
36
+ /** The provider said to slow down: no call for this member for `ms`. */
37
+ pause(ms: number): void;
38
+ }
39
+ /** The wait budget for rate limits in one run for one member. */
40
+ export interface BackoffBudget {
41
+ spentMs: number;
42
+ }
43
+ /**
44
+ * Whether an error is the provider's rate limit, and how long it asked to wait (null: no
45
+ * Retry-After). Null for any other error, which is never retried.
46
+ */
47
+ export type RateLimitOf = (err: unknown) => {
48
+ retryAfterMs: number | null;
49
+ } | null;
50
+ /**
51
+ * Runs one provider call through the member's throttle, and tries again after a rate limit
52
+ * (Retry-After, else exponential backoff with jitter) while the run's budget lasts. When the
53
+ * budget is spent the error goes up, so the run stops with its progress saved.
54
+ */
55
+ export declare function throttledCall<T>(t: UserThrottle, o: ThrottleOptions, budget: BackoffBudget, cost: number, call: () => Promise<T>, rateLimitOf: RateLimitOf): Promise<T>;
56
+ /** Runs `fn` over `items` with at most `n` at a time; the results keep the items' order. */
57
+ export declare function pool<A, B>(items: readonly A[], n: number, fn: (a: A) => Promise<B>): Promise<B[]>;
58
+ /** A Retry-After header in seconds or as an HTTP date, in milliseconds (null when absent). */
59
+ export declare function retryAfterHeader(header: string | null | undefined, now?: number): number | null;
60
+ /** The addresses in an address header (`"Kari, N." <kari@x.no>, per@x.no`), lower case. */
61
+ export declare function addresses(value: string | undefined): string[];
62
+ /**
63
+ * Display names in an address header, by address (`"Nordmann, Kari" <kari@x.no>` → kari@x.no:
64
+ * Nordmann, Kari). Only names given with an address in angle brackets; bare addresses have none.
65
+ */
66
+ export declare function displayNames(value: string | undefined): Map<string, string>;
67
+ /** HTML as plain text: no styles or scripts, line breaks kept, entities decoded. */
68
+ export declare const htmlToText: (html: string) => string;
69
+ /**
70
+ * Whether the quoted part starts at `lines[i]`: a `>` line, an attribution line (also when the
71
+ * client wrapped it over two lines), a forwarded or original-message marker, the underline before
72
+ * a quoted header block, or the header block itself (`From:` followed within three lines by `Sent:`,
73
+ * `Date:` or `To:`, or all on one line).
74
+ */
75
+ export declare function isQuoteStart(lines: readonly string[], i: number): boolean;
76
+ /** The index of the first quoted line, or `lines.length` when nothing is quoted. */
77
+ export declare function quoteStart(lines: readonly string[]): number;
78
+ /**
79
+ * The new part of a reply: the body up to the quoted earlier messages (`isQuoteStart`). Only this
80
+ * is sent to the core for the summary.
81
+ */
82
+ export declare function newText(body: string): string;
83
+ /**
84
+ * The new part of an HTML reply as text: the HTML is cut before its first quote container, then
85
+ * converted, then cut by the text rules (`newText`) too.
86
+ */
87
+ export declare function htmlNewText(html: string): string;
88
+ /**
89
+ * The new part of a message that has a text and an HTML body: each is cut by its own rules, and
90
+ * the shorter wins (the cut that found the quote earliest). Either may be empty.
91
+ */
92
+ export declare function newPart(text: string | null | undefined, html: string | null | undefined): string;
93
+ /**
94
+ * Mailing lists and automated mail, by their headers (`List-Id`, `List-Unsubscribe`,
95
+ * `Precedence: bulk|list|junk`, `Auto-Submitted` other than `no`). `header` reads one header by
96
+ * name, case-insensitively.
97
+ */
98
+ export declare function isAutomatedMail(header: (name: string) => string | undefined): boolean;
99
+ /** Every participant other than the mailbox's owner is on the workspace's own domains. */
100
+ export declare function isInternalOnly(participants: readonly string[], mailbox: string, internalDomains: readonly string[]): boolean;
101
+ /**
102
+ * Subjects that calendars put on invitations, updates, replies and cancellations, in English and
103
+ * Norwegian (the common calendars' wording and variants). Matched at the start of the subject only:
104
+ * "Re: Invitation: …" is a person replying, and is kept.
105
+ */
106
+ export declare const CALENDAR_NOTICE_SUBJECTS: readonly RegExp[];
107
+ /** Whether a subject starts like a calendar's notification (`extra`: an app's own wording on top). */
108
+ export declare function isCalendarNoticeSubject(subject: string | undefined, extra?: readonly RegExp[]): boolean;
109
+ /** The workspace's own email domains from a comma-separated setting (`internalDomains`). */
110
+ export declare const domainsOf: (setting: unknown) => string[];
@@ -0,0 +1,321 @@
1
+ /**
2
+ * Building blocks for capture apps that read each member's own calendar and mailbox (docs/15
3
+ * §9.3): a per-member throttle that waits out a provider's rate limit within a run's budget, a
4
+ * bounded pool, and the rules for reading an email that do not depend on the provider (addresses
5
+ * and display names in a header, the new part of a reply, HTML to text, automated mail and
6
+ * internal-only messages). Pure and provider-neutral: each app keeps its provider's API, error
7
+ * classes and wording, and decides which errors are a rate limit.
8
+ */
9
+ export const DEFAULT_THROTTLE = {
10
+ unitsPerSecond: 50,
11
+ burst: 250,
12
+ concurrency: 4,
13
+ maxBackoffMs: 45_000,
14
+ now: () => Date.now(),
15
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
16
+ random: Math.random,
17
+ };
18
+ /** One member's token bucket and in-flight limit. */
19
+ export class UserThrottle {
20
+ o;
21
+ tokens;
22
+ last;
23
+ active = 0;
24
+ waiting = [];
25
+ pausedUntil = 0;
26
+ constructor(o) {
27
+ this.o = o;
28
+ this.tokens = o.burst;
29
+ this.last = o.now();
30
+ }
31
+ refill() {
32
+ const now = this.o.now();
33
+ this.tokens = Math.min(this.o.burst, this.tokens + ((now - this.last) / 1000) * this.o.unitsPerSecond);
34
+ this.last = now;
35
+ }
36
+ /** Waits for a free slot and `cost` units. Call `release` when the call is done. */
37
+ async acquire(cost) {
38
+ if (this.active >= this.o.concurrency)
39
+ await new Promise((r) => this.waiting.push(r));
40
+ this.active++;
41
+ const need = Math.min(cost, this.o.burst);
42
+ for (;;) {
43
+ this.refill();
44
+ const paused = this.pausedUntil - this.o.now();
45
+ if (paused > 0) {
46
+ await this.o.sleep(paused);
47
+ continue;
48
+ }
49
+ if (this.tokens >= need) {
50
+ this.tokens -= need;
51
+ return;
52
+ }
53
+ await this.o.sleep(Math.ceil(((need - this.tokens) / this.o.unitsPerSecond) * 1000));
54
+ }
55
+ }
56
+ release() {
57
+ this.active--;
58
+ this.waiting.shift()?.();
59
+ }
60
+ /** The provider said to slow down: no call for this member for `ms`. */
61
+ pause(ms) {
62
+ this.pausedUntil = Math.max(this.pausedUntil, this.o.now() + ms);
63
+ this.tokens = 0;
64
+ }
65
+ }
66
+ /**
67
+ * Runs one provider call through the member's throttle, and tries again after a rate limit
68
+ * (Retry-After, else exponential backoff with jitter) while the run's budget lasts. When the
69
+ * budget is spent the error goes up, so the run stops with its progress saved.
70
+ */
71
+ export async function throttledCall(t, o, budget, cost, call, rateLimitOf) {
72
+ for (let attempt = 0;; attempt++) {
73
+ await t.acquire(cost);
74
+ try {
75
+ return await call();
76
+ }
77
+ catch (err) {
78
+ const limit = rateLimitOf(err);
79
+ if (!limit)
80
+ throw err;
81
+ const backoff = Math.min(32_000, 1000 * 2 ** attempt) * (0.5 + o.random() / 2);
82
+ const wait = Math.max(limit.retryAfterMs ?? 0, backoff);
83
+ if (budget.spentMs + wait > o.maxBackoffMs)
84
+ throw err;
85
+ budget.spentMs += wait;
86
+ t.pause(wait);
87
+ }
88
+ finally {
89
+ t.release();
90
+ }
91
+ }
92
+ }
93
+ /** Runs `fn` over `items` with at most `n` at a time; the results keep the items' order. */
94
+ export async function pool(items, n, fn) {
95
+ const out = new Array(items.length);
96
+ let next = 0;
97
+ let failed = null;
98
+ const worker = async () => {
99
+ while (next < items.length && failed === null) {
100
+ const i = next++;
101
+ try {
102
+ out[i] = await fn(items[i]);
103
+ }
104
+ catch (e) {
105
+ failed ??= e;
106
+ }
107
+ }
108
+ };
109
+ await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker));
110
+ if (failed !== null)
111
+ throw failed;
112
+ return out;
113
+ }
114
+ /** A Retry-After header in seconds or as an HTTP date, in milliseconds (null when absent). */
115
+ export function retryAfterHeader(header, now = Date.now()) {
116
+ const h = header?.trim();
117
+ if (h && /^\d+$/.test(h))
118
+ return Number(h) * 1000;
119
+ const at = h ? Date.parse(h) : Number.NaN;
120
+ return Number.isNaN(at) ? null : Math.max(0, at - now);
121
+ }
122
+ // ---------------------------------------------------------------------------
123
+ // Reading an email
124
+ /** The addresses in an address header (`"Kari, N." <kari@x.no>, per@x.no`), lower case. */
125
+ export function addresses(value) {
126
+ if (!value)
127
+ return [];
128
+ const out = new Set();
129
+ for (const m of value.matchAll(/[^\s<>",;:()]+@[^\s<>",;:()]+\.[^\s<>",;:()]+/g))
130
+ out.add(m[0].toLowerCase());
131
+ return [...out];
132
+ }
133
+ /**
134
+ * Display names in an address header, by address (`"Nordmann, Kari" <kari@x.no>` → kari@x.no:
135
+ * Nordmann, Kari). Only names given with an address in angle brackets; bare addresses have none.
136
+ */
137
+ export function displayNames(value) {
138
+ const out = new Map();
139
+ if (!value)
140
+ return out;
141
+ for (const m of value.matchAll(/(?:"((?:[^"\\]|\\.)*)"|([^<>",;]*?))\s*<([^\s<>",;:()]+@[^\s<>",;:()]+)>/g)) {
142
+ const name = (m[1] ?? m[2] ?? '').replace(/\\(.)/g, '$1').trim();
143
+ const email = (m[3] ?? '').toLowerCase();
144
+ if (name && email && !name.includes('@'))
145
+ out.set(email, name.slice(0, 200));
146
+ }
147
+ return out;
148
+ }
149
+ /** HTML as plain text: no styles or scripts, line breaks kept, entities decoded. */
150
+ export const htmlToText = (html) => html
151
+ .replace(/<(style|script)[\s\S]*?<\/\1>/gi, ' ')
152
+ .replace(/<br\s*\/?>|<\/p>|<\/div>|<\/tr>|<\/li>|<hr\b[^>]*>/gi, '\n')
153
+ .replace(/<[^>]+>/g, ' ')
154
+ .replace(/&nbsp;/g, ' ')
155
+ .replace(/&amp;/g, '&')
156
+ .replace(/&lt;/g, '<')
157
+ .replace(/&gt;/g, '>')
158
+ .replace(/&quot;/g, '"')
159
+ .replace(/&#39;/g, "'")
160
+ .replace(/[ \t]+/g, ' ')
161
+ .replace(/\n\s*\n+/g, '\n\n')
162
+ .trim();
163
+ /*
164
+ * Where the quoted part of an email starts (decision 27 November 2026), in the languages Kennra's
165
+ * customers write: nb, nn, sv, da, en, de, nl, fi (and fr, es, it for the attribution line).
166
+ */
167
+ /** "On … wrote:", "Den … skrev …:", "11 maj 2024 kl. 10:00 skrev …:", "… kirjoitti:". */
168
+ const ATTRIBUTION_VERB = /\b(wrote|writes|skrev|skreiv|schrieb|schreef|kirjoitti|a écrit|escribió|ha scritto|escreveu)\b.{0,200}:\s*$/i;
169
+ /** An attribution line names a date, a time or an address; prose that ends in "skrev:" does not. */
170
+ const ATTRIBUTION_EVIDENCE = /@|\b\d{1,2}[:.]\d{2}\b|\b(19|20)\d{2}\b|^(On|Den|Am|Op|Le|El|Il|På|Em)\s/i;
171
+ /** Forwarded and original-message markers, with or without dashes around them. */
172
+ const MARKER = /^[-_=*\s]*(original message|opprinnelig melding|opprinneleg melding|opphavleg melding|ursprungligt meddelande|originalmeddelande|oprindelig meddelelse|originalmeddelelse|ursprüngliche nachricht|originalnachricht|oorspronkelijk bericht|origineel bericht|alkuperäinen viesti|forwarded message|videresendt melding|vidaresendt melding|vidarebefordrat meddelande|vidarebefordrat brev|videresendt meddelelse|videresendt besked|weitergeleitete nachricht|doorgestuurd bericht|välitetty viesti|edelleenlähetetty viesti|begin forwarded message|start på videresendt melding|start på videresendt besked|anfang der weitergeleiteten (nachricht|e-mail)|begin doorgestuurd bericht|välitetty viesti alkaa|message transféré)\b[-_=*\s:]*$/i;
173
+ /** A quoted header block's first line: `From:` (and its translations), with a value. */
174
+ const HEADER_FROM = /^[*\s]*(From|Fra|Frå|Från|Afsender|Avsender|Avsändare|Von|Van|Lähettäjä|De|Da)\s*:[*\s]*\S/i;
175
+ /** The lines that follow `From:` in a quoted header block. */
176
+ const HEADER_NEXT = /^[*\s]*(Sent|Date|To|Cc|Subject|Sendt|Dato|Til|Kopi|Emne|Skickat|Datum|Till|Kopia|Ämne|Gesendet|An|Betreff|Kopie|Verzonden|Verstuurd|Aan|Onderwerp|Lähetetty|Päivämäärä|Päiväys|Vastaanottaja|Kopio|Aihe|Envoyé|À|Objet)\s*:/i;
177
+ /** A header block flattened onto one line: `From: … Sent: … To: …`. */
178
+ const HEADER_INLINE = /^[*\s]*(From|Fra|Frå|Från|Von|Van|Lähettäjä|De)\s*:.{1,300}?\s(Sent|Date|Sendt|Dato|Skickat|Datum|Gesendet|Verzonden|Verstuurd|Lähetetty|Päivämäärä|Envoyé)\s*:/i;
179
+ /**
180
+ * Whether the quoted part starts at `lines[i]`: a `>` line, an attribution line (also when the
181
+ * client wrapped it over two lines), a forwarded or original-message marker, the underline before
182
+ * a quoted header block, or the header block itself (`From:` followed within three lines by `Sent:`,
183
+ * `Date:` or `To:`, or all on one line).
184
+ */
185
+ export function isQuoteStart(lines, i) {
186
+ const t = (lines[i] ?? '').trim();
187
+ if (!t)
188
+ return false;
189
+ if (t.startsWith('>') || /^_{10,}$/.test(t) || MARKER.test(t) || HEADER_INLINE.test(t))
190
+ return true;
191
+ if (t.length <= 400 && ATTRIBUTION_VERB.test(t) && ATTRIBUTION_EVIDENCE.test(t))
192
+ return true;
193
+ const next = (lines[i + 1] ?? '').trim();
194
+ if (next && !next.startsWith('>')) {
195
+ const joined = `${t} ${next}`;
196
+ if (joined.length <= 400 && ATTRIBUTION_VERB.test(next) && ATTRIBUTION_EVIDENCE.test(t)) {
197
+ // Only when the verb is in the joined line's tail: "…Kari <" + "kari@x.no> wrote:".
198
+ if (ATTRIBUTION_VERB.test(joined) && /[<(@\d]/.test(t))
199
+ return true;
200
+ }
201
+ }
202
+ if (HEADER_FROM.test(t))
203
+ return lines.slice(i + 1, i + 5).some((l) => HEADER_NEXT.test(l.trim()) && !HEADER_FROM.test(l.trim()));
204
+ return false;
205
+ }
206
+ /** The index of the first quoted line, or `lines.length` when nothing is quoted. */
207
+ export function quoteStart(lines) {
208
+ for (let i = 0; i < lines.length; i++)
209
+ if (isQuoteStart(lines, i))
210
+ return i;
211
+ return lines.length;
212
+ }
213
+ /**
214
+ * The new part of a reply: the body up to the quoted earlier messages (`isQuoteStart`). Only this
215
+ * is sent to the core for the summary.
216
+ */
217
+ export function newText(body) {
218
+ const lines = body.split(/\r?\n/);
219
+ return lines.slice(0, quoteStart(lines)).join('\n').trim();
220
+ }
221
+ /**
222
+ * The containers mail clients put a quoted message in: `<blockquote>`, a quote class (`…_quote`,
223
+ * `…_quoted`, `moz-cite-prefix`), the reply header's container (`divRplyFwdMsg`, `appendonsend`,
224
+ * the reference message container), a citation (`type="cite"`), and the top-bordered div a desktop
225
+ * client opens the reply header with.
226
+ */
227
+ const QUOTE_CONTAINERS = [
228
+ /<blockquote\b/i,
229
+ /<[a-z]+\b[^>]*\bclass\s*=\s*["'][^"']*\b[a-z]+_quoted?(_container)?\b/i,
230
+ /<[a-z]+\b[^>]*\bclass\s*=\s*["'][^"']*\bmoz-cite-prefix\b/i,
231
+ /<[a-z]+\b[^>]*\bid\s*=\s*["']?(divRplyFwdMsg|appendonsend|mail-editor-reference-message-container)\b/i,
232
+ /<[a-z]+\b[^>]*\btype\s*=\s*["']?cite\b/i,
233
+ /<div\b[^>]*\bstyle\s*=\s*["'][^"']*border\s*:\s*none\s*;\s*border-top\s*:\s*solid/i,
234
+ ];
235
+ /**
236
+ * The new part of an HTML reply as text: the HTML is cut before its first quote container, then
237
+ * converted, then cut by the text rules (`newText`) too.
238
+ */
239
+ export function htmlNewText(html) {
240
+ let cut = html.length;
241
+ for (const re of QUOTE_CONTAINERS) {
242
+ const m = re.exec(html);
243
+ if (m && m.index < cut)
244
+ cut = m.index;
245
+ }
246
+ return newText(htmlToText(html.slice(0, cut)));
247
+ }
248
+ /**
249
+ * The new part of a message that has a text and an HTML body: each is cut by its own rules, and
250
+ * the shorter wins (the cut that found the quote earliest). Either may be empty.
251
+ */
252
+ export function newPart(text, html) {
253
+ const a = text ? newText(text) : '';
254
+ const b = html ? htmlNewText(html) : '';
255
+ if (a && b)
256
+ return b.length < a.length ? b : a;
257
+ return a || b;
258
+ }
259
+ /**
260
+ * Mailing lists and automated mail, by their headers (`List-Id`, `List-Unsubscribe`,
261
+ * `Precedence: bulk|list|junk`, `Auto-Submitted` other than `no`). `header` reads one header by
262
+ * name, case-insensitively.
263
+ */
264
+ export function isAutomatedMail(header) {
265
+ const precedence = header('Precedence')?.toLowerCase() ?? '';
266
+ const auto = header('Auto-Submitted')?.toLowerCase().trim() ?? '';
267
+ return !!(header('List-Id') ||
268
+ header('List-Unsubscribe') ||
269
+ ['bulk', 'list', 'junk'].includes(precedence) ||
270
+ (auto && auto !== 'no'));
271
+ }
272
+ /** Every participant other than the mailbox's owner is on the workspace's own domains. */
273
+ export function isInternalOnly(participants, mailbox, internalDomains) {
274
+ const internal = new Set(internalDomains.map((d) => d.toLowerCase()));
275
+ const others = participants.map((a) => a.toLowerCase()).filter((a) => a !== mailbox.toLowerCase());
276
+ return !others.some((a) => !internal.has(a.split('@')[1] ?? ''));
277
+ }
278
+ /**
279
+ * Subjects that calendars put on invitations, updates, replies and cancellations, in English and
280
+ * Norwegian (the common calendars' wording and variants). Matched at the start of the subject only:
281
+ * "Re: Invitation: …" is a person replying, and is kept.
282
+ */
283
+ export const CALENDAR_NOTICE_SUBJECTS = [
284
+ // English
285
+ /^invitation:/i,
286
+ /^updated invitation\b/i,
287
+ /^invitation updated\b/i,
288
+ /^new event:/i,
289
+ /^updated event:/i,
290
+ /^accepted:/i,
291
+ /^declined:/i,
292
+ /^tentatively accepted:/i,
293
+ /^canceled event\b/i,
294
+ /^cancelled event\b/i,
295
+ /^event canceled:/i,
296
+ /^event cancelled:/i,
297
+ // Norwegian (bokmål)
298
+ /^invitasjon:/i,
299
+ /^oppdatert invitasjon\b/i,
300
+ /^invitasjonen er oppdatert\b/i,
301
+ /^ny hendelse:/i,
302
+ /^oppdatert hendelse:/i,
303
+ /^godtatt:/i,
304
+ /^akseptert:/i,
305
+ /^avslått:/i,
306
+ /^foreløpig godtatt:/i,
307
+ /^kanskje:/i,
308
+ /^avlyst hendelse\b/i,
309
+ /^avlyst arrangement\b/i,
310
+ /^hendelsen er avlyst\b/i,
311
+ ];
312
+ /** Whether a subject starts like a calendar's notification (`extra`: an app's own wording on top). */
313
+ export function isCalendarNoticeSubject(subject, extra = []) {
314
+ const s = (subject ?? '').trim();
315
+ return CALENDAR_NOTICE_SUBJECTS.some((r) => r.test(s)) || extra.some((r) => r.test(s));
316
+ }
317
+ /** The workspace's own email domains from a comma-separated setting (`internalDomains`). */
318
+ export const domainsOf = (setting) => String(setting ?? '')
319
+ .split(',')
320
+ .map((d) => d.trim().toLowerCase())
321
+ .filter(Boolean);