@chatwarden/core 0.1.0 → 0.1.2
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 +202 -6
- package/dist/src/audit.d.ts +27 -5
- package/dist/src/audit.d.ts.map +1 -1
- package/dist/src/audit.js +59 -8
- package/dist/src/audit.js.map +1 -1
- package/dist/src/chat.d.ts +48 -0
- package/dist/src/chat.d.ts.map +1 -1
- package/dist/src/chat.js +94 -10
- package/dist/src/chat.js.map +1 -1
- package/dist/src/chatwarden.d.ts +209 -12
- package/dist/src/chatwarden.d.ts.map +1 -1
- package/dist/src/chatwarden.js +77 -11
- package/dist/src/chatwarden.js.map +1 -1
- package/dist/src/crypto.d.ts +22 -0
- package/dist/src/crypto.d.ts.map +1 -0
- package/dist/src/crypto.js +193 -0
- package/dist/src/crypto.js.map +1 -0
- package/dist/src/decide.d.ts.map +1 -1
- package/dist/src/decide.js +2 -4
- package/dist/src/decide.js.map +1 -1
- package/dist/src/documents.d.ts +12 -2
- package/dist/src/documents.d.ts.map +1 -1
- package/dist/src/documents.js +56 -34
- package/dist/src/documents.js.map +1 -1
- package/dist/src/events.d.ts +3 -0
- package/dist/src/events.d.ts.map +1 -1
- package/dist/src/events.js.map +1 -1
- package/dist/src/hasher.js +2 -2
- package/dist/src/hasher.js.map +1 -1
- package/dist/src/index.d.ts +21 -12
- package/dist/src/index.d.ts.map +1 -1
- package/dist/src/index.js +11 -6
- package/dist/src/index.js.map +1 -1
- package/dist/src/ladder.d.ts +2 -0
- package/dist/src/ladder.d.ts.map +1 -1
- package/dist/src/ladder.js +1 -1
- package/dist/src/ladder.js.map +1 -1
- package/dist/src/log.d.ts +16 -0
- package/dist/src/log.d.ts.map +1 -1
- package/dist/src/log.js +34 -0
- package/dist/src/log.js.map +1 -1
- package/dist/src/notices.js +2 -2
- package/dist/src/notices.js.map +1 -1
- package/dist/src/policy.d.ts +129 -0
- package/dist/src/policy.d.ts.map +1 -0
- package/dist/src/policy.js +242 -0
- package/dist/src/policy.js.map +1 -0
- package/dist/src/profile.d.ts +120 -7
- package/dist/src/profile.d.ts.map +1 -1
- package/dist/src/profile.js +295 -7
- package/dist/src/profile.js.map +1 -1
- package/dist/src/reporting.d.ts +127 -0
- package/dist/src/reporting.d.ts.map +1 -0
- package/dist/src/reporting.js +172 -0
- package/dist/src/reporting.js.map +1 -0
- package/dist/src/reports.d.ts +80 -4
- package/dist/src/reports.d.ts.map +1 -1
- package/dist/src/reports.js +122 -8
- package/dist/src/reports.js.map +1 -1
- package/dist/src/sanctions.js +3 -3
- package/dist/src/sanctions.js.map +1 -1
- package/dist/src/staffReports.d.ts +17 -5
- package/dist/src/staffReports.d.ts.map +1 -1
- package/dist/src/staffReports.js +22 -5
- package/dist/src/staffReports.js.map +1 -1
- package/dist/src/staffViews.d.ts +138 -0
- package/dist/src/staffViews.d.ts.map +1 -0
- package/dist/src/staffViews.js +205 -0
- package/dist/src/staffViews.js.map +1 -0
- package/dist/src/strikes.js +2 -2
- package/dist/src/strikes.js.map +1 -1
- package/dist/src/subjects.js +2 -2
- package/dist/src/subjects.js.map +1 -1
- package/dist/src/team.d.ts +149 -0
- package/dist/src/team.d.ts.map +1 -0
- package/dist/src/team.js +385 -0
- package/dist/src/team.js.map +1 -0
- package/dist/src/types.d.ts +245 -4
- package/dist/src/types.d.ts.map +1 -1
- package/dist/src/types.js +5 -0
- package/dist/src/types.js.map +1 -1
- package/package.json +4 -1
- package/src/audit.ts +73 -9
- package/src/chat.ts +109 -9
- package/src/chatwarden.ts +279 -22
- package/src/crypto.ts +206 -0
- package/src/decide.ts +2 -4
- package/src/documents.ts +70 -43
- package/src/events.ts +10 -1
- package/src/hasher.ts +2 -2
- package/src/index.ts +110 -5
- package/src/ladder.ts +1 -1
- package/src/log.ts +37 -0
- package/src/notices.ts +2 -2
- package/src/policy.ts +288 -0
- package/src/profile.ts +369 -14
- package/src/reporting.ts +251 -0
- package/src/reports.ts +165 -12
- package/src/sanctions.ts +3 -3
- package/src/staffReports.ts +33 -7
- package/src/staffViews.ts +325 -0
- package/src/strikes.ts +2 -2
- package/src/subjects.ts +2 -2
- package/src/team.ts +422 -0
- package/src/types.ts +257 -4
package/src/team.ts
ADDED
|
@@ -0,0 +1,422 @@
|
|
|
1
|
+
import { randomId } from './crypto.js';
|
|
2
|
+
import { isValidAuditActor } from './audit.js';
|
|
3
|
+
import { REPORT_CATEGORIES } from './reports.js';
|
|
4
|
+
import { canonicalReasonId, isReasonId } from './reporting.js';
|
|
5
|
+
import type { ReportReason } from './reporting.js';
|
|
6
|
+
import type { SubjectIndex } from './subjects.js';
|
|
7
|
+
import { CLAIM_TTL_MS } from './types.js';
|
|
8
|
+
import type { Clock, ReasonRow, ReportCategory, Store, SubjectId } from './types.js';
|
|
9
|
+
|
|
10
|
+
// The team workbench behind `cw.cases`, `cw.changes` and `cw.reasons`: soft claims on a person's case, take next, who
|
|
11
|
+
// has a case open, and the saved decision reasons. Staff only. Claims and reasons live in the store (so several
|
|
12
|
+
// processes on one database agree); viewing presence is a hint kept in this process's memory and never stored.
|
|
13
|
+
|
|
14
|
+
/** How long a viewing beat counts: 30 seconds. */
|
|
15
|
+
export const VIEWING_TTL_MS = 30_000;
|
|
16
|
+
|
|
17
|
+
/** The longest saved-reason label, in characters (code points), after trimming. */
|
|
18
|
+
export const REASON_LABEL_MAX = 40;
|
|
19
|
+
/** The longest saved-reason text, in characters (code points), after trimming. */
|
|
20
|
+
export const REASON_TEXT_MAX = 500;
|
|
21
|
+
/** The most saved reasons the kit keeps. */
|
|
22
|
+
export const REASONS_MAX = 200;
|
|
23
|
+
|
|
24
|
+
/** The most cases one actor keeps open at once for viewing; a newer beat drops their oldest. */
|
|
25
|
+
export const VIEWING_PER_ACTOR_MAX = 20;
|
|
26
|
+
|
|
27
|
+
/** How many times a claim is attempted when another process wins the database lock race in between (SQLITE_BUSY). */
|
|
28
|
+
export const CLAIM_BUSY_TRIES = 3;
|
|
29
|
+
|
|
30
|
+
/** The most distinct people viewing presence tracks at once; past it new people are not tracked (it is a hint). */
|
|
31
|
+
const VIEWING_PEOPLE_MAX = 10_000;
|
|
32
|
+
/** Above this many tracked people a beat first sweeps the expired ones. */
|
|
33
|
+
const VIEWING_SWEEP_AT = 1_000;
|
|
34
|
+
/** Reports read per page while take next scans for a free case. */
|
|
35
|
+
const NEXT_PAGE = 200;
|
|
36
|
+
|
|
37
|
+
/** A claim as staff see it. Staff only: `by` is a staff actor. */
|
|
38
|
+
export interface CaseClaim {
|
|
39
|
+
by: string;
|
|
40
|
+
/** Epoch ms the holder took the case (kept across heartbeats). */
|
|
41
|
+
since: number;
|
|
42
|
+
/** Epoch ms it lapses without another beat; the case is held strictly before it. */
|
|
43
|
+
until: number;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* What `cases.claim` answers: the claim now in force (`tookOverFrom` names the actor whose live claim a take over
|
|
48
|
+
* replaced, else null), or why not: the person has no open case, or somebody else holds it (their live claim comes back).
|
|
49
|
+
*/
|
|
50
|
+
export type ClaimOutcome =
|
|
51
|
+
| { ok: true; claim: CaseClaim; tookOverFrom: string | null }
|
|
52
|
+
| { ok: false; error: 'no_case' }
|
|
53
|
+
| { ok: false; error: 'claimed'; claim: CaseClaim };
|
|
54
|
+
|
|
55
|
+
/** The case take next claimed: the person, their newest open report, and the claim just taken. */
|
|
56
|
+
export interface NextCase {
|
|
57
|
+
person: SubjectId;
|
|
58
|
+
reportId: string;
|
|
59
|
+
claim: CaseClaim;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** A saved reason that cannot be stored: a label or text outside its limits, a bad id, or the list is full. Fixed message. */
|
|
63
|
+
export class ReasonError extends Error {
|
|
64
|
+
readonly field: 'label' | 'text' | 'id' | 'active' | 'input' | 'limit';
|
|
65
|
+
constructor(field: ReasonError['field']) {
|
|
66
|
+
super(`reasons: invalid ${field}`);
|
|
67
|
+
this.name = 'ReasonError';
|
|
68
|
+
this.field = field;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const claimOf = (c: { by: string; since: number; until: number }): CaseClaim => ({ by: c.by, since: c.since, until: c.until });
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Is this the store telling us another process got in between our read and our write (SQLite's "database is locked":
|
|
76
|
+
* BUSY, LOCKED or BUSY_SNAPSHOT)? Read from the error's `errcode` (low byte 5 or 6) or, failing that, its message.
|
|
77
|
+
*/
|
|
78
|
+
function isBusy(err: unknown): boolean {
|
|
79
|
+
if (typeof err !== 'object' || err === null) return false;
|
|
80
|
+
const code = (err as { errcode?: unknown }).errcode;
|
|
81
|
+
if (typeof code === 'number') return (code & 0xff) === 5 || (code & 0xff) === 6;
|
|
82
|
+
return /SQLITE_BUSY|SQLITE_LOCKED|database is locked/i.test(String((err as { message?: unknown }).message));
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Run a store transaction that reads then writes, again when it lost a lock race: the retry starts a fresh read, so the
|
|
87
|
+
* loser of a race for a case sees the winner's claim and answers the normal "claimed", not an error. Bounded by
|
|
88
|
+
* {@link CLAIM_BUSY_TRIES}; any other error, and the last busy one, is thrown.
|
|
89
|
+
*/
|
|
90
|
+
export function retryBusy<T>(run: () => T): T {
|
|
91
|
+
for (let attempt = 1; ; attempt++) {
|
|
92
|
+
try {
|
|
93
|
+
return run();
|
|
94
|
+
} catch (err) {
|
|
95
|
+
if (attempt >= CLAIM_BUSY_TRIES || !isBusy(err)) throw err;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
const needActor = (actor: unknown): string => {
|
|
101
|
+
if (!isValidAuditActor(actor)) throw new RangeError('cases: the actor is not a valid staff ref');
|
|
102
|
+
return actor;
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
const needPerson = (person: unknown): string => {
|
|
106
|
+
if (typeof person !== 'string' || person === '') throw new RangeError('cases: the person must be a staff ref');
|
|
107
|
+
return person;
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
/** Who has a case open, per person, each beat lasting {@link VIEWING_TTL_MS}. In memory, per process, never stored. */
|
|
111
|
+
export class ViewingPresence {
|
|
112
|
+
private readonly clock: Clock;
|
|
113
|
+
/** person -> actor -> the instant the beat stops counting. */
|
|
114
|
+
private readonly seen = new Map<SubjectId, Map<string, number>>();
|
|
115
|
+
/** actor -> the people they have open, oldest beat first (refreshing a beat moves it last). */
|
|
116
|
+
private readonly byActor = new Map<string, Set<SubjectId>>();
|
|
117
|
+
/** When the last sweep of expired beats ran; a sweep runs at most once per beat lifetime. */
|
|
118
|
+
private lastSweep = Number.NEGATIVE_INFINITY;
|
|
119
|
+
|
|
120
|
+
constructor(clock: Clock) {
|
|
121
|
+
this.clock = clock;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** Record that `actor` has `person`'s case open now. */
|
|
125
|
+
touch(person: SubjectId, actor: string): void {
|
|
126
|
+
const now = this.clock.now();
|
|
127
|
+
if (this.seen.size >= VIEWING_SWEEP_AT && now - this.lastSweep >= VIEWING_TTL_MS) this.sweep(now);
|
|
128
|
+
let who = this.seen.get(person);
|
|
129
|
+
if (who === undefined) {
|
|
130
|
+
if (this.seen.size >= VIEWING_PEOPLE_MAX) return;
|
|
131
|
+
who = new Map();
|
|
132
|
+
this.seen.set(person, who);
|
|
133
|
+
}
|
|
134
|
+
who.set(actor, now + VIEWING_TTL_MS);
|
|
135
|
+
// One actor holds at most VIEWING_PER_ACTOR_MAX cases open: the oldest beat makes room for the newest.
|
|
136
|
+
let mine = this.byActor.get(actor);
|
|
137
|
+
if (mine === undefined) {
|
|
138
|
+
mine = new Set();
|
|
139
|
+
this.byActor.set(actor, mine);
|
|
140
|
+
}
|
|
141
|
+
mine.delete(person);
|
|
142
|
+
mine.add(person);
|
|
143
|
+
if (mine.size > VIEWING_PER_ACTOR_MAX) {
|
|
144
|
+
const oldest = mine.values().next().value as SubjectId;
|
|
145
|
+
mine.delete(oldest);
|
|
146
|
+
this.forget(oldest, actor);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
private forget(person: SubjectId, actor: string): void {
|
|
151
|
+
const who = this.seen.get(person);
|
|
152
|
+
if (who === undefined) return;
|
|
153
|
+
who.delete(actor);
|
|
154
|
+
if (who.size === 0) this.seen.delete(person);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** The actors whose beat still counts for `person`, sorted, leaving `except` out. */
|
|
158
|
+
viewers(person: SubjectId, except?: string): string[] {
|
|
159
|
+
const who = this.seen.get(person);
|
|
160
|
+
if (who === undefined) return [];
|
|
161
|
+
const now = this.clock.now();
|
|
162
|
+
const out: string[] = [];
|
|
163
|
+
for (const [actor, until] of who) if (until > now && actor !== except) out.push(actor);
|
|
164
|
+
return out.sort();
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
private sweep(now: number): void {
|
|
168
|
+
this.lastSweep = now;
|
|
169
|
+
for (const [person, who] of this.seen) {
|
|
170
|
+
for (const [actor, until] of who) {
|
|
171
|
+
if (until > now) continue;
|
|
172
|
+
who.delete(actor);
|
|
173
|
+
const mine = this.byActor.get(actor);
|
|
174
|
+
mine?.delete(person);
|
|
175
|
+
if (mine?.size === 0) this.byActor.delete(actor);
|
|
176
|
+
}
|
|
177
|
+
if (who.size === 0) this.seen.delete(person);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export interface TeamDeps {
|
|
183
|
+
store: Store;
|
|
184
|
+
subjects: SubjectIndex;
|
|
185
|
+
clock: Clock;
|
|
186
|
+
/** The reporting reasons in force, so an old id (`disruption`) finds the reason that replaced it. Default: none. */
|
|
187
|
+
reasons?: () => readonly ReportReason[];
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Claims, take next and viewing. The facade exposes it as `cw.cases`. */
|
|
191
|
+
export class CaseDesk {
|
|
192
|
+
private readonly store: Store;
|
|
193
|
+
private readonly subjects: SubjectIndex;
|
|
194
|
+
private readonly clock: Clock;
|
|
195
|
+
private readonly reasons: () => readonly ReportReason[];
|
|
196
|
+
private readonly presence: ViewingPresence;
|
|
197
|
+
|
|
198
|
+
constructor(deps: TeamDeps) {
|
|
199
|
+
this.store = deps.store;
|
|
200
|
+
this.subjects = deps.subjects;
|
|
201
|
+
this.clock = deps.clock;
|
|
202
|
+
this.reasons = deps.reasons ?? (() => []);
|
|
203
|
+
this.presence = new ViewingPresence(deps.clock);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** The live claim on a person's case, or null. */
|
|
207
|
+
holder(person: SubjectId): CaseClaim | null {
|
|
208
|
+
const canonical = this.subjects.canonical(needPerson(person));
|
|
209
|
+
const [claim] = this.store.loadClaims([canonical], this.clock.now());
|
|
210
|
+
return claim === undefined ? null : claimOf(claim);
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** The live claims among these people (one store read), keyed by canonical person. People nobody holds are absent. */
|
|
214
|
+
holders(people: readonly SubjectId[]): Map<SubjectId, CaseClaim> {
|
|
215
|
+
const out = new Map<SubjectId, CaseClaim>();
|
|
216
|
+
if (people.length === 0) return out;
|
|
217
|
+
const canonical = [...new Set(people.map((p) => this.subjects.canonical(p)))];
|
|
218
|
+
for (const c of this.store.loadClaims(canonical, this.clock.now())) out.set(c.person, claimOf(c));
|
|
219
|
+
return out;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Claim a person's case for `actor`, or beat the claim they already hold. Needs at least one OPEN report against the
|
|
224
|
+
* person (else `no_case`). `takeOver` moves a live claim of someone else to `actor`; the caller decides who may use it.
|
|
225
|
+
* One atomic conditional write in the store: of two moderators racing, exactly one wins.
|
|
226
|
+
*/
|
|
227
|
+
claim(person: SubjectId, actor: string, opts: { takeOver?: boolean } = {}): ClaimOutcome {
|
|
228
|
+
needActor(actor);
|
|
229
|
+
const canonical = this.subjects.canonical(needPerson(person));
|
|
230
|
+
return retryBusy(() =>
|
|
231
|
+
this.store.transaction((): ClaimOutcome => {
|
|
232
|
+
if (this.store.listOpenReportsByPerson(this.subjects.aliasesOf(canonical), 1).length === 0) {
|
|
233
|
+
return { ok: false, error: 'no_case' };
|
|
234
|
+
}
|
|
235
|
+
const now = this.clock.now();
|
|
236
|
+
const res = this.store.claimCase(canonical, actor, now, now + CLAIM_TTL_MS, opts.takeOver === true ? 'takeover' : 'claim');
|
|
237
|
+
return res.won
|
|
238
|
+
? { ok: true, claim: claimOf(res.claim), tookOverFrom: res.from }
|
|
239
|
+
: { ok: false, error: 'claimed', claim: claimOf(res.claim) };
|
|
240
|
+
}),
|
|
241
|
+
);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** Release `actor`'s claim on the person. True only when it ended a live claim of theirs. */
|
|
245
|
+
release(person: SubjectId, actor: string): boolean {
|
|
246
|
+
needActor(actor);
|
|
247
|
+
const canonical = this.subjects.canonical(needPerson(person));
|
|
248
|
+
return this.store.transaction(() => this.store.releaseClaim(canonical, actor, this.clock.now()));
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* After a decision: end `actor`'s own claim on the person only when the person has no open report left (any alias counts).
|
|
253
|
+
* While another report about them is open the claim is kept untouched, so its heartbeat and its 10 minutes go on as normal and
|
|
254
|
+
* nobody else can take the case from under the moderator who is working through it. True only when it ended a live claim.
|
|
255
|
+
* The check and the release are one transaction.
|
|
256
|
+
*/
|
|
257
|
+
releaseWhenDone(person: SubjectId, actor: string): boolean {
|
|
258
|
+
needActor(actor);
|
|
259
|
+
const canonical = this.subjects.canonical(needPerson(person));
|
|
260
|
+
return this.store.transaction(() => {
|
|
261
|
+
if (this.store.listOpenReportsByPerson(this.subjects.aliasesOf(canonical), 1).length > 0) return false;
|
|
262
|
+
return this.store.releaseClaim(canonical, actor, this.clock.now());
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* Claim and return the oldest open case nobody holds (`category` limits it to cases with an open report of that
|
|
268
|
+
* category, `reason` to cases with an open report that gave that reason id, or none at all for `null`; both may be given), or null. A case is a person, ranked by their OLDEST open report; it opens on their NEWEST. A case
|
|
269
|
+
* `actor` already holds is skipped. Each candidate is one atomic conditional claim, so two moderators racing never
|
|
270
|
+
* get the same case.
|
|
271
|
+
*/
|
|
272
|
+
next(actor: string, filter: { category?: ReportCategory; reason?: string | null } = {}): NextCase | null {
|
|
273
|
+
needActor(actor);
|
|
274
|
+
const category = filter.category;
|
|
275
|
+
if (category !== undefined && !REPORT_CATEGORIES.includes(category)) throw new RangeError('cases: unknown category');
|
|
276
|
+
const asked = filter.reason;
|
|
277
|
+
if (asked !== undefined && asked !== null && !isReasonId(asked)) throw new RangeError('cases: unknown reason');
|
|
278
|
+
const reason = asked === undefined || asked === null ? asked : canonicalReasonId(this.reasons(), asked);
|
|
279
|
+
const seen = new Set<SubjectId>();
|
|
280
|
+
let after: { createdAt: number; id: string } | undefined;
|
|
281
|
+
for (;;) {
|
|
282
|
+
const page = this.store.listOpenReports({
|
|
283
|
+
...(category === undefined ? {} : { category }),
|
|
284
|
+
...(reason === undefined ? {} : { reason }),
|
|
285
|
+
...(after === undefined ? {} : { after: after.createdAt, afterId: after.id }),
|
|
286
|
+
limit: NEXT_PAGE,
|
|
287
|
+
});
|
|
288
|
+
// New people on this page, oldest report first. Who already holds one is read once for the whole page, so a held case
|
|
289
|
+
// costs no write; only the rest get the atomic 'free' claim (which stays the arbiter if a rival slips in).
|
|
290
|
+
const candidates: SubjectId[] = [];
|
|
291
|
+
for (const report of page) {
|
|
292
|
+
const person = this.subjects.canonical(report.targetSubject);
|
|
293
|
+
if (seen.has(person)) continue;
|
|
294
|
+
seen.add(person);
|
|
295
|
+
candidates.push(person);
|
|
296
|
+
}
|
|
297
|
+
const held = new Set(this.store.loadClaims(candidates, this.clock.now()).map((c) => c.person));
|
|
298
|
+
for (const person of candidates) {
|
|
299
|
+
if (held.has(person)) continue;
|
|
300
|
+
const won = retryBusy(() =>
|
|
301
|
+
this.store.transaction(() => {
|
|
302
|
+
const now = this.clock.now();
|
|
303
|
+
const res = this.store.claimCase(person, actor, now, now + CLAIM_TTL_MS, 'free');
|
|
304
|
+
if (!res.won) return null;
|
|
305
|
+
const newest = this.store.listOpenReportsByPerson(this.subjects.aliasesOf(person), 1)[0];
|
|
306
|
+
if (newest === undefined) {
|
|
307
|
+
// The case closed under us: do not leave a claim on nothing.
|
|
308
|
+
this.store.releaseClaim(person, actor, now);
|
|
309
|
+
return null;
|
|
310
|
+
}
|
|
311
|
+
return { person, reportId: newest.id, claim: claimOf(res.claim) };
|
|
312
|
+
}),
|
|
313
|
+
);
|
|
314
|
+
if (won !== null) return won;
|
|
315
|
+
}
|
|
316
|
+
const last = page[page.length - 1];
|
|
317
|
+
if (page.length < NEXT_PAGE || last === undefined) return null;
|
|
318
|
+
after = { createdAt: last.createdAt, id: last.id };
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
/**
|
|
323
|
+
* `actor` has the person's case open now (a beat; it counts for 30 seconds). Never stored, never blocks anyone. Only a
|
|
324
|
+
* person with an open report is tracked (false otherwise, nothing recorded), and one actor keeps at most
|
|
325
|
+
* {@link VIEWING_PER_ACTOR_MAX} cases open: a newer beat drops their oldest. True when the beat was recorded.
|
|
326
|
+
*/
|
|
327
|
+
view(person: SubjectId, actor: string): boolean {
|
|
328
|
+
needActor(actor);
|
|
329
|
+
const canonical = this.subjects.canonical(needPerson(person));
|
|
330
|
+
if (this.store.listOpenReportsByPerson(this.subjects.aliasesOf(canonical), 1).length === 0) return false;
|
|
331
|
+
this.presence.touch(canonical, actor);
|
|
332
|
+
return true;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** Who has the person's case open now, sorted, leaving `except` out. */
|
|
336
|
+
viewers(person: SubjectId, except?: string): string[] {
|
|
337
|
+
return this.presence.viewers(this.subjects.canonical(needPerson(person)), except);
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/** {@link viewers} for several people at once; people nobody is viewing are absent. */
|
|
341
|
+
viewersOf(people: readonly SubjectId[], except?: string): Map<SubjectId, string[]> {
|
|
342
|
+
const out = new Map<SubjectId, string[]>();
|
|
343
|
+
for (const p of people) {
|
|
344
|
+
const canonical = this.subjects.canonical(p);
|
|
345
|
+
if (out.has(canonical)) continue;
|
|
346
|
+
const v = this.presence.viewers(canonical, except);
|
|
347
|
+
if (v.length > 0) out.set(canonical, v);
|
|
348
|
+
}
|
|
349
|
+
return out;
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/** Saved decision reasons. The facade exposes it as `cw.reasons`. */
|
|
354
|
+
export class ReasonBook {
|
|
355
|
+
private readonly store: Store;
|
|
356
|
+
|
|
357
|
+
constructor(store: Store) {
|
|
358
|
+
this.store = store;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
list(): ReasonRow[] {
|
|
362
|
+
return this.store.listReasons();
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
add(input: { label: string; text: string }): ReasonRow {
|
|
366
|
+
if (typeof input !== 'object' || input === null) throw new ReasonError('input');
|
|
367
|
+
const label = cleanLabel(input.label);
|
|
368
|
+
const text = cleanText(input.text);
|
|
369
|
+
return this.store.transaction(() => {
|
|
370
|
+
if (this.store.listReasons().length >= REASONS_MAX) throw new ReasonError('limit');
|
|
371
|
+
const row: ReasonRow = { id: randomId(16), label, text, active: true };
|
|
372
|
+
this.store.insertReason(row);
|
|
373
|
+
return row;
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/** Change the label and/or text. Null for an unknown id. At least one of the two is required. */
|
|
378
|
+
update(id: string, patch: { label?: string; text?: string }): ReasonRow | null {
|
|
379
|
+
if (typeof id !== 'string' || id === '') throw new ReasonError('id');
|
|
380
|
+
if (typeof patch !== 'object' || patch === null) throw new ReasonError('input');
|
|
381
|
+
const change: { label?: string; text?: string } = {};
|
|
382
|
+
if (patch.label !== undefined) change.label = cleanLabel(patch.label);
|
|
383
|
+
if (patch.text !== undefined) change.text = cleanText(patch.text);
|
|
384
|
+
if (change.label === undefined && change.text === undefined) throw new ReasonError('input');
|
|
385
|
+
return this.store.transaction(() => (this.store.updateReason(id, change) ? this.find(id) : null));
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** Switch a reason on or off. Null for an unknown id. */
|
|
389
|
+
setActive(id: string, active: boolean): ReasonRow | null {
|
|
390
|
+
if (typeof id !== 'string' || id === '') return null;
|
|
391
|
+
if (typeof active !== 'boolean') throw new ReasonError('active');
|
|
392
|
+
return this.store.transaction(() => (this.store.setReasonActive(id, active) ? this.find(id) : null));
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
private find(id: string): ReasonRow | null {
|
|
396
|
+
return this.store.listReasons().find((r) => r.id === id) ?? null;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/** Any control character: a label is one line. */
|
|
401
|
+
// eslint-disable-next-line no-control-regex
|
|
402
|
+
const CONTROL = /[\u0000-\u001f\u007f]/;
|
|
403
|
+
/** Any control character but the newline: a text may run over several lines. */
|
|
404
|
+
// eslint-disable-next-line no-control-regex
|
|
405
|
+
const CONTROL_EXCEPT_NEWLINE = /[\u0000-\u0009\u000b-\u001f\u007f]/;
|
|
406
|
+
|
|
407
|
+
/** Length in characters (code points), so an emoji counts once. */
|
|
408
|
+
const length = (s: string): number => [...s].length;
|
|
409
|
+
|
|
410
|
+
function cleanLabel(v: unknown): string {
|
|
411
|
+
if (typeof v !== 'string') throw new ReasonError('label');
|
|
412
|
+
const label = v.trim();
|
|
413
|
+
if (label === '' || length(label) > REASON_LABEL_MAX || CONTROL.test(label)) throw new ReasonError('label');
|
|
414
|
+
return label;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
function cleanText(v: unknown): string {
|
|
418
|
+
if (typeof v !== 'string') throw new ReasonError('text');
|
|
419
|
+
const text = v.trim();
|
|
420
|
+
if (text === '' || length(text) > REASON_TEXT_MAX || CONTROL_EXCEPT_NEWLINE.test(text)) throw new ReasonError('text');
|
|
421
|
+
return text;
|
|
422
|
+
}
|