@parcha/agentrun-serve 0.1.0-beta.55 → 0.1.0-beta.56

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +44 -10
  3. package/dist/adapters.d.ts +3 -2
  4. package/dist/adapters.js +6 -3
  5. package/dist/answer-json.d.ts +6 -2
  6. package/dist/answer-json.js +22 -4
  7. package/dist/api-only.js +2 -0
  8. package/dist/calendar/tools.js +3 -2
  9. package/dist/chatgpt-plan.d.ts +16 -1
  10. package/dist/chatgpt-plan.js +116 -12
  11. package/dist/claude-login.d.ts +34 -5
  12. package/dist/claude-login.js +31 -7
  13. package/dist/claude-sign-in.d.ts +35 -0
  14. package/dist/claude-sign-in.js +90 -0
  15. package/dist/console/assets/{backend-D5EmB4N3.js → backend-Boh7tC4i.js} +1 -1
  16. package/dist/console/assets/{index-DUYLaqiR.js → index-CQ3cJRzI.js} +130 -130
  17. package/dist/console/assets/index-DKkaS3a0.css +1 -0
  18. package/dist/console/index.html +2 -2
  19. package/dist/host-check.d.ts +4 -0
  20. package/dist/host-check.js +4 -0
  21. package/dist/key-refusal.d.ts +21 -5
  22. package/dist/key-refusal.js +231 -37
  23. package/dist/learn/secrets.d.ts +20 -10
  24. package/dist/learn/secrets.js +44 -184
  25. package/dist/llms.txt +1 -1
  26. package/dist/openapi.d.ts +3 -3
  27. package/dist/openapi.js +70 -18
  28. package/dist/place-offers.d.ts +14 -6
  29. package/dist/place-offers.js +26 -13
  30. package/dist/redact/match.d.ts +74 -0
  31. package/dist/redact/match.js +771 -0
  32. package/dist/run-timeline-served.d.ts +1 -1
  33. package/dist/run-timeline-served.js +4 -4
  34. package/dist/runner/adapter-loop.d.ts +3 -0
  35. package/dist/runner/adapter-loop.js +1 -1
  36. package/dist/runner/adapter-run-spec.js +4 -1
  37. package/dist/runner/beside.js +7 -3
  38. package/dist/runner/cli-run-spec.js +3 -1
  39. package/dist/runner/loop-contract.d.ts +4 -0
  40. package/dist/runner/main.js +8 -4
  41. package/dist/runner/presence.d.ts +4 -3
  42. package/dist/runner/presence.js +4 -2
  43. package/dist/runner/run-child-host.d.ts +2 -0
  44. package/dist/runner/run-child-host.js +2 -2
  45. package/dist/runner/runner.d.ts +4 -0
  46. package/dist/runner/runner.js +33 -3
  47. package/dist/server.d.ts +5 -2
  48. package/dist/server.js +41 -10
  49. package/dist/store/dialect.d.ts +3 -0
  50. package/dist/store/dialect.js +1 -0
  51. package/dist/store/index.d.ts +1 -1
  52. package/dist/store/index.js +1 -1
  53. package/dist/store/postgres/dialect.js +3 -0
  54. package/dist/store/sqlite/store.js +43 -13
  55. package/dist/store/store.d.ts +10 -1
  56. package/dist/store/store.js +7 -0
  57. package/dist/store-view.js +1 -1
  58. package/dist/template-eval.d.ts +2 -2
  59. package/dist/template-eval.js +9 -8
  60. package/dist/timeline/index.d.ts +1 -1
  61. package/dist/timeline/index.js +1 -1
  62. package/dist/timeline/timeline.d.ts +12 -7
  63. package/dist/timeline/timeline.js +14 -6
  64. package/dist/tool-gate.js +3 -1
  65. package/dist/validate.js +1 -1
  66. package/dist/workspace/computer-deps.d.ts +2 -1
  67. package/dist/workspace/computer-deps.js +5 -4
  68. package/dist/workspace/computer-for-claim.d.ts +8 -2
  69. package/dist/workspace/computer-for-claim.js +28 -9
  70. package/dist/workspace/computer-janitor.d.ts +15 -7
  71. package/dist/workspace/computer-janitor.js +33 -8
  72. package/dist/workspace/computer-kept.d.ts +52 -4
  73. package/dist/workspace/computer-kept.js +118 -6
  74. package/dist/workspace/run-end-computers.d.ts +5 -1
  75. package/dist/workspace/run-end-computers.js +27 -1
  76. package/dist/wrapped.d.ts +57 -0
  77. package/dist/wrapped.js +51 -0
  78. package/package.json +11 -11
  79. package/templates/README.md +8 -7
  80. package/dist/console/assets/index-DYhU4adm.css +0 -1
@@ -0,0 +1,771 @@
1
+ // The one matcher served text is redacted with (learn/secrets.ts redactSecrets and redactLearned run on it): the secret
2
+ // and bank shapes as scanners, the held values' forms found as they stand, and the whole-text check over the views a
3
+ // value can hide in (whitespace gone, NFKC, percent-decoded, folded). Nothing here reads attacker text with a
4
+ // backtracking regex: each shape is a prefix found with indexOf, then runs of a character class read forward, and a
5
+ // start inside a run already read is not read again. So a text costs time in proportion to its length, whatever it
6
+ // repeats. The few bank shapes that stay regexes are tried only at their words, each reading a bounded head and one
7
+ // run of digits.
8
+ //
9
+ // The whole-text check reads the text as it came, never the text after its cut: a cut can hide part of a held value
10
+ // (a credential parameter's value cut in place, the rest of the held value past a line break), and the rest would then
11
+ // read as no value at all. A held value found in a view is cut only when every character the view read of it comes
12
+ // from text a cut covers; otherwise the text is withheld whole.
13
+ /** The characters the shape scanners have visited in this process: the text each prefix search passes over, each run
14
+ * read, each guard read back. A test sets it to 0, redacts, and reads it: a scanner that read a run once per start
15
+ * inside it would count the square of the run's length. */
16
+ export const scanned = { chars: 0 };
17
+ // ---- Character classes, as the regexes they replace wrote them.
18
+ /** JavaScript's \s. */
19
+ function isSpace(code) {
20
+ if (code < 128)
21
+ return code === 32 || (code >= 9 && code <= 13);
22
+ return code === 0xa0 || code === 0x1680 || (code >= 0x2000 && code <= 0x200a) || code === 0x2028 || code === 0x2029 || code === 0x202f || code === 0x205f || code === 0x3000 || code === 0xfeff;
23
+ }
24
+ const UPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
25
+ const LOWER = "abcdefghijklmnopqrstuvwxyz";
26
+ const DIGIT = "0123456789";
27
+ const ALNUM = UPPER + LOWER + DIGIT;
28
+ const tableOf = (chars) => {
29
+ const table = new Uint8Array(128);
30
+ for (const char of chars)
31
+ table[char.charCodeAt(0)] = 1;
32
+ return table;
33
+ };
34
+ /** The ASCII characters `chars`. */
35
+ const only = (chars) => {
36
+ const table = tableOf(chars);
37
+ return (code) => code < 128 && table[code] === 1;
38
+ };
39
+ /** Any character but whitespace and `chars`. */
40
+ const allBut = (chars) => {
41
+ const table = tableOf(chars);
42
+ return (code) => (code < 128 ? table[code] === 0 : true) && !isSpace(code);
43
+ };
44
+ const WORD = only(`${ALNUM}_`);
45
+ const ALNUM_CLASS = only(ALNUM);
46
+ const PART = only(`${ALNUM}_-`);
47
+ const isDigit = (code) => code >= 48 && code <= 57;
48
+ // ---- Reading.
49
+ /** Where the run of `cls` starting at `from` ends. */
50
+ function run(text, from, cls) {
51
+ let at = from;
52
+ while (at < text.length && cls(text.charCodeAt(at)))
53
+ at++;
54
+ scanned.chars += at - from + 1;
55
+ return at;
56
+ }
57
+ /** Whether `count` characters of `cls` start at `from`. */
58
+ function fixed(text, from, count, cls) {
59
+ let at = from;
60
+ while (at < text.length && at - from < count && cls(text.charCodeAt(at)))
61
+ at++;
62
+ scanned.chars += at - from + 1;
63
+ return at - from === count;
64
+ }
65
+ /** The next place `prefix` stands in `hay` at or after `from`. */
66
+ function seek(hay, prefix, from) {
67
+ const at = hay.indexOf(prefix, from);
68
+ scanned.chars += (at < 0 ? hay.length : at + prefix.length) - from;
69
+ return at < 0 ? Number.POSITIVE_INFINITY : at;
70
+ }
71
+ /** `text` with A-Z lowered and nothing else changed, so each offset is the same in both. */
72
+ export const asciiLower = (text) => text.replace(/[A-Z]+/g, (upper) => upper.toLowerCase());
73
+ const none = (next) => ({ start: -1, end: -1, next });
74
+ /** A prefix, then a run of `cls` of at least `min` characters to the end of that run. */
75
+ const prefixRun = (kind, prefixes, cls, min, guard) => ({
76
+ kind,
77
+ prefixes,
78
+ scan(text, at, prefix) {
79
+ if (guard && !guard(text, at))
80
+ return none(at + 1);
81
+ const from = at + prefix.length;
82
+ const end = run(text, from, cls);
83
+ const next = end - (prefix.length - 1);
84
+ return end - from >= min ? { start: at, end, next } : none(next);
85
+ },
86
+ });
87
+ /** A prefix, then exactly `count` characters of `cls`. */
88
+ const prefixFixed = (kind, prefixes, cls, count) => ({
89
+ kind,
90
+ prefixes,
91
+ scan: (text, at, prefix) => (fixed(text, at + prefix.length, count, cls) ? { start: at, end: at + prefix.length + count, next: at + 1 } : none(at + 1)),
92
+ });
93
+ const PRIVATE_KEY_HEADER = only(` ${UPPER}${DIGIT}`);
94
+ /** A private key block's header: "-----BEGIN", its key type (RSA, EC, OPENSSH, ENCRYPTED) at most 64 characters each
95
+ * side of "PRIVATE KEY", then "-----". Each start reads at most 140 characters. */
96
+ const PRIVATE_KEY = {
97
+ kind: "private key block",
98
+ prefixes: ["-----BEGIN"],
99
+ scan(text, at) {
100
+ const from = at + 10;
101
+ let end = from;
102
+ while (end < text.length && end - from < 140 && PRIVATE_KEY_HEADER(text.charCodeAt(end)))
103
+ end++;
104
+ scanned.chars += end - from + 1;
105
+ const length = end - from;
106
+ if (length >= 140 || !text.startsWith("-----", end))
107
+ return none(at + 1);
108
+ for (let i = Math.max(0, length - 75); i <= Math.min(64, length - 11); i++) {
109
+ scanned.chars += 11;
110
+ if (text.startsWith("PRIVATE KEY", from + i))
111
+ return { start: at, end: end + 5, next: at + 1 };
112
+ }
113
+ return none(at + 1);
114
+ },
115
+ };
116
+ /** A JWT: three base64url parts, the first two JSON objects ("eyJ"), each 8 characters or more after it. It starts at
117
+ * the first "eyJ" of a run of a part's characters, wherever that run starts ("token-eyJ…", "x9eyJ…"): a later "eyJ" in
118
+ * the same run reaches the same "." with fewer characters. Whether an "eyJ" is the first is read back to the "eyJ"
119
+ * before it or the run's start, so the reads back add up to one pass. A scan that fails reads on past the part it
120
+ * failed in: a start in an earlier part reads the same parts and fails there too. One that matched reads on from its
121
+ * second part, as a match starting there can run past this one into a fourth. */
122
+ const JWT = {
123
+ kind: "JWT",
124
+ prefixes: ["eyJ"],
125
+ scan(text, at) {
126
+ let back = at - 1;
127
+ while (back >= 0 && PART(text.charCodeAt(back))) {
128
+ if (back >= 2 && text.startsWith("eyJ", back - 2)) {
129
+ scanned.chars += at - back;
130
+ return none(at + 1);
131
+ }
132
+ back--;
133
+ }
134
+ scanned.chars += at - back;
135
+ const first = run(text, at + 3, PART);
136
+ if (first - (at + 3) < 8 || text[first] !== ".")
137
+ return none(first - 2);
138
+ if (!text.startsWith("eyJ", first + 1))
139
+ return none(first + 1);
140
+ const second = run(text, first + 4, PART);
141
+ if (second - (first + 4) < 8 || text[second] !== ".")
142
+ return none(second - 2);
143
+ const third = run(text, second + 1, PART);
144
+ if (third - (second + 1) < 8)
145
+ return none(third - 2);
146
+ return { start: at, end: third, next: first + 1 };
147
+ },
148
+ };
149
+ const WEBHOOK_BODY = only(`${ALNUM}+/`);
150
+ /** A Standard Webhooks signing secret: `whsec_` and base64, this server's or any other's. Its run's class has no "_",
151
+ * so the run can take the next secret's "whsec" and stop at its "_": that secret starts in this run's last characters. */
152
+ const WEBHOOK_SECRET = {
153
+ kind: "webhook signing secret",
154
+ prefixes: ["whsec_"],
155
+ scan(text, at) {
156
+ const from = at + 6;
157
+ const body = run(text, from, WEBHOOK_BODY);
158
+ if (body - from < 24)
159
+ return none(body - 5);
160
+ let end = body;
161
+ while (end < body + 2 && text[end] === "=")
162
+ end++;
163
+ return { start: at, end, next: body - 5 };
164
+ },
165
+ };
166
+ const URL_USER = allBut("/?#@:");
167
+ const URL_PASS = allBut("/?#@");
168
+ const SED_HOST = only(`${ALNUM}._~-`);
169
+ const SED_TARGET = only(`${ALNUM}.-`);
170
+ const isBlank = (char) => char === " " || char === "\t";
171
+ /** Whether the URL password at `at` ("://"), ending at `end`, is the capture pattern of a complete single-quoted sed
172
+ * search expression: `sed -n 's|https://<host or [^:]*>:\([^@]*\)@<host>|\1|p'`, opened at the text's start, after
173
+ * whitespace, ";" or "(". The "@" inside "[^@]" is regex syntax, not a password's end. A bracketed password or a bare
174
+ * URL is never one. Read back from the "://" over the expression's head and forward over its tail, each once. */
175
+ function inSedCapture(text, at, end) {
176
+ let head = text.startsWith("https", at - 5) ? at - 5 : text.startsWith("http", at - 4) ? at - 4 : -1;
177
+ if (head < 0 || !text.startsWith("'s|", head - 3))
178
+ return false;
179
+ head -= 3;
180
+ let blanks = head;
181
+ while (blanks > 0 && isBlank(text[blanks - 1]))
182
+ blanks--;
183
+ if (blanks === head || !text.startsWith("-n", blanks - 2))
184
+ return false;
185
+ const flag = blanks - 2;
186
+ blanks = flag;
187
+ while (blanks > 0 && isBlank(text[blanks - 1]))
188
+ blanks--;
189
+ scanned.chars += at - blanks;
190
+ if (blanks === flag || !text.startsWith("sed", blanks - 3))
191
+ return false;
192
+ const sed = blanks - 3;
193
+ if (sed > 0 && !(isSpace(text.charCodeAt(sed - 1)) || text[sed - 1] === ";" || text[sed - 1] === "("))
194
+ return false;
195
+ let tail = at + 3;
196
+ if (text.startsWith("[^:]*", tail))
197
+ tail += 5;
198
+ else {
199
+ const host = run(text, tail, SED_HOST);
200
+ if (host === tail)
201
+ return false;
202
+ tail = host;
203
+ }
204
+ if (!text.startsWith(":\\([^@]*\\)@", tail))
205
+ return false;
206
+ const target = run(text, tail + 11, SED_TARGET);
207
+ if (target === tail + 11 || !text.startsWith("|\\1|p'", target))
208
+ return false;
209
+ return end <= target + 6;
210
+ }
211
+ /** A URL with a user and password: "://", a user, ":", a password, then "@". An authority that stops at a "/" may stop
212
+ * at the next URL's "://", so a failed scan reads on from two characters before where it stopped. */
213
+ const URL_PASSWORD = {
214
+ kind: "URL with a password",
215
+ prefixes: ["://"],
216
+ scan(text, at) {
217
+ const user = run(text, at + 3, URL_USER);
218
+ if (user === at + 3 || text[user] !== ":")
219
+ return none(user - 2);
220
+ const password = run(text, user + 1, URL_PASS);
221
+ if (text[password] !== "@")
222
+ return none(password - 2);
223
+ return inSedCapture(text, at, password + 1) ? none(password - 2) : { start: at, end: password + 1, next: password - 2 };
224
+ },
225
+ };
226
+ const BEARER_TOKEN_CLASS = only(`${ALNUM}._~+/-`);
227
+ /** The token after a `Bearer` scheme (RFC 6750's characters), in any case: twenty characters or more with a digit among
228
+ * them, so a word after "bearer" ("bearer authentication/authorization"), a placeholder (`<token>`, `$TOKEN`,
229
+ * `YOUR_API_KEY`) and a challenge's parameter (`Bearer realm="x"`) are none. The token alone is the match: the scheme
230
+ * before it stays, so a reader still sees a header was there. The scheme is at most three blanks before the token. A
231
+ * token can hold the word "bearer" and then a blank and another token, so the next scheme is looked for from this
232
+ * token's start: each token is still read once. */
233
+ const BEARER_TOKEN = {
234
+ kind: "bearer token",
235
+ prefixes: ["bearer"],
236
+ ci: true,
237
+ scan(text, at) {
238
+ if (at > 0 && WORD(text.charCodeAt(at - 1)))
239
+ return none(at + 1);
240
+ let token = at + 6;
241
+ while (token < text.length && token - (at + 6) < 4 && isSpace(text.charCodeAt(token)))
242
+ token++;
243
+ scanned.chars += token - at - 5;
244
+ const blanks = token - (at + 6);
245
+ if (blanks < 1 || blanks > 3)
246
+ return none(at + 1);
247
+ let end = token;
248
+ let digit = false;
249
+ for (; end < text.length; end++) {
250
+ const code = text.charCodeAt(end);
251
+ if (!BEARER_TOKEN_CLASS(code))
252
+ break;
253
+ digit ||= isDigit(code);
254
+ }
255
+ scanned.chars += end - token + 1;
256
+ if (end - token < 20 || !digit)
257
+ return none(token);
258
+ const body = end;
259
+ while (end < body + 2 && text[end] === "=")
260
+ end++;
261
+ return { start: token, end, next: token };
262
+ },
263
+ };
264
+ /** Each name a credential parameter goes by, as written after "?" or "&" and lowered. */
265
+ const CREDENTIAL_NAMES = new Set([
266
+ ...["api", "access", "auth", "id", "refresh", "client"].flatMap((head) => {
267
+ const tail = head === "api" ? "key" : head === "client" ? "secret" : "token";
268
+ return [`${head}${tail}`, `${head}_${tail}`, `${head}-${tail}`];
269
+ }),
270
+ "x-amz-signature", "x-amz-security-token", "x-goog-signature", "token", "secret", "password", "passwd", "signature", "sig",
271
+ ]);
272
+ const NAME_CHAR = only(`${UPPER}${LOWER}_-`);
273
+ const URL_VALUE = allBut("&#\"'`<>\\[]");
274
+ /** The value of a URL parameter named like a credential, after `?` or `&`: sixteen characters or more, to the next
275
+ * separator. The name is the whole parameter's (`token`, never `page_token`), and the value alone is the match, so the
276
+ * name stays. A signed URL's signature is one: whoever holds the URL holds what it grants. No bracket is a value's
277
+ * character (a URL writes one percent-encoded), so a value already cut to "[redacted]" is never read as one. A value
278
+ * may hold "?" and "=", so a parameter of the same name inside it ends where it ends: the next start is looked for past
279
+ * it. */
280
+ const URL_CREDENTIAL = {
281
+ kind: "URL parameter named like a credential",
282
+ prefixes: ["?", "&"],
283
+ scan(text, at) {
284
+ let name = at + 1;
285
+ while (name < text.length && name - at <= 21 && NAME_CHAR(text.charCodeAt(name)))
286
+ name++;
287
+ scanned.chars += name - at;
288
+ if (text[name] !== "=" || !CREDENTIAL_NAMES.has(text.slice(at + 1, name).toLowerCase()))
289
+ return none(at + 1);
290
+ const end = run(text, name + 1, URL_VALUE);
291
+ return end - (name + 1) >= 16 ? { start: name + 1, end, next: end } : none(end);
292
+ },
293
+ };
294
+ /** Text shaped like a secret, by kind. The same shapes the Pi learning loop's guard refuses. */
295
+ export const SECRET_SHAPES = [
296
+ prefixFixed("AWS access key id", ["AKIA", "ASIA"], only(UPPER + DIGIT), 16),
297
+ prefixFixed("Google API key", ["AIza"], only(`${ALNUM}_-`), 35),
298
+ PRIVATE_KEY,
299
+ prefixRun("GitHub token", ["ghp_", "gho_", "ghu_", "ghs_", "ghr_"], ALNUM_CLASS, 30),
300
+ prefixRun("GitHub token", ["github_pat_"], WORD, 20),
301
+ prefixRun("sk- key", ["sk-"], PART, 20, (text, at) => at === 0 || !ALNUM_CLASS(text.charCodeAt(at - 1))),
302
+ prefixRun("Slack token", [..."abposre"].map((kind) => `xox${kind}-`).concat("xapp-"), only(`${ALNUM}-`), 10),
303
+ JWT,
304
+ WEBHOOK_SECRET,
305
+ URL_PASSWORD,
306
+ BEARER_TOKEN,
307
+ URL_CREDENTIAL,
308
+ ];
309
+ /** A bank's number beside its word, tried as `pattern` at each of its words only. Each try reads its word's bounded
310
+ * head (`head` characters), and ACCOUNT_NUMBER's digits, single dashes or spaces between them, to their end: what the
311
+ * regex can read from that start. */
312
+ const besideWord = (kind, words, pattern, head, digits = false) => {
313
+ const sticky = new RegExp(pattern.source, "iy");
314
+ return {
315
+ kind,
316
+ prefixes: words,
317
+ ci: true,
318
+ scan(text, at) {
319
+ let reach = Math.min(text.length, at + head);
320
+ if (digits)
321
+ while (reach < text.length && /[\d -]/.test(text[reach]))
322
+ reach++;
323
+ scanned.chars += reach - at + 1;
324
+ sticky.lastIndex = at;
325
+ const match = sticky.exec(text);
326
+ return match ? { start: at, end: at + match[0].length, next: at + 1 } : none(at + 1);
327
+ },
328
+ };
329
+ };
330
+ /** A bank account number beside its word: "account", "acct", "a/c" or "bank account", maybe "number", "no.", "#", ":"
331
+ * or "is" after it, then six digits or more, single dashes or spaces between them. A count before the word ("4
332
+ * accounts"), a date (YYYY-MM-DD), a year or a card's last four is none: the word must come first, the digits right
333
+ * after it, and there must be six. Every gap is at most three whitespace characters. */
334
+ const ACCOUNT_NUMBER = /\b(?:bank\s{1,3})?(?:account|acct|a\/c)(?:\s{1,3}(?:number|no\.?|num))?\s{0,3}(?:#|:|\bis\b)?\s{0,3}(?!\d{4}-\d{2}-\d{2}\b)\d(?:[ -]?\d){5,}/;
335
+ /** An IBAN beside its word: two letters, two check digits, then ten to thirty letters or digits, spaces between. */
336
+ const IBAN = /\bIBAN\s{0,3}(?:#|:|\bis\b)?\s{0,3}[A-Z]{2}\d{2}(?:\s?[A-Z0-9]){10,30}/;
337
+ /** A US routing (ABA) number beside its word: nine digits. */
338
+ const ROUTING_NUMBER = /\b(?:routing|ABA)(?:\s{1,3}(?:number|no\.?|num))?\s{0,3}(?:#|:|\bis\b)?\s{0,3}\d{9}\b/;
339
+ /** A UK sort code beside its word: three pairs of digits. */
340
+ const SORT_CODE = /\bsort\s{1,3}code\s{0,3}(?:#|:|\bis\b)?\s{0,3}\d{2}[- ]?\d{2}[- ]?\d{2}\b/;
341
+ /** A bank's numbers beside their words, which learning never keeps: an account, IBAN, routing or sort-code number. Not
342
+ * one of SECRET_SHAPES: a run may show its user an account number (a finance job's answer), and those shapes cut every
343
+ * run's view; only what learning keeps refuses them. */
344
+ export const MONEY_SHAPES = [
345
+ besideWord("bank account number", ["bank", "account", "acct", "a/c"], ACCOUNT_NUMBER, 40, true),
346
+ besideWord("IBAN", ["iban"], IBAN, 80),
347
+ besideWord("routing number", ["routing", "aba"], ROUTING_NUMBER, 40),
348
+ besideWord("sort code", ["sort"], SORT_CODE, 40),
349
+ ];
350
+ /** Every span `shape` matches in `text` (only the first with `first`). `lower`: the text lowered (asciiLower), for a
351
+ * shape found in any case. */
352
+ function spansOf(text, lower, shape, first = false) {
353
+ const hay = shape.ci ? lower() : text;
354
+ const { prefixes } = shape;
355
+ const next = prefixes.map(() => -1);
356
+ const out = [];
357
+ for (let from = 0;;) {
358
+ let at = Number.POSITIVE_INFINITY;
359
+ let prefix = "";
360
+ for (let i = 0; i < prefixes.length; i++) {
361
+ if (next[i] < from)
362
+ next[i] = seek(hay, prefixes[i], from);
363
+ if (next[i] < at) {
364
+ at = next[i];
365
+ prefix = prefixes[i];
366
+ }
367
+ }
368
+ if (at === Number.POSITIVE_INFINITY)
369
+ return out;
370
+ const found = shape.scan(text, at, prefix);
371
+ if (found.start >= 0) {
372
+ out.push([found.start, found.end]);
373
+ if (first)
374
+ return out;
375
+ }
376
+ from = Math.max(at + 1, found.next);
377
+ }
378
+ }
379
+ /** A text lowered once, on first use, counted as a read of the text. */
380
+ function lowered(text) {
381
+ let low;
382
+ return () => {
383
+ if (low === undefined) {
384
+ scanned.chars += text.length;
385
+ low = asciiLower(text);
386
+ }
387
+ return low;
388
+ };
389
+ }
390
+ /** The kinds of `shapes` in `text`, each once, in their order. */
391
+ export function shapeKinds(text, shapes) {
392
+ const lower = lowered(text);
393
+ const kinds = [];
394
+ for (const shape of shapes)
395
+ if (!kinds.includes(shape.kind) && spansOf(text, lower, shape, true).length > 0)
396
+ kinds.push(shape.kind);
397
+ return kinds;
398
+ }
399
+ /** Adds each place `needle` stands in `hay` to `out`, overlapping places too. */
400
+ function places(hay, needle, out) {
401
+ if (!needle)
402
+ return;
403
+ for (let at = hay.indexOf(needle); at >= 0; at = hay.indexOf(needle, at + 1))
404
+ out.push([at, at + needle.length]);
405
+ }
406
+ const isSeparator = (code) => code === 45 || code === 95 || code === 58 || code === 46;
407
+ /** Each place a folded needle stands in `text`: its digits in order, in any case, at most one separator between any
408
+ * two. Found in the text lowered with its separators gone, each character's offset in the text kept, and a place kept
409
+ * only where no two of its digits are more than one separator apart. */
410
+ function foldSpans(text, folds, out) {
411
+ const lower = asciiLower(text);
412
+ const at = new Int32Array(text.length);
413
+ const parts = [];
414
+ let count = 0;
415
+ let from = 0;
416
+ for (let i = 0; i <= text.length; i++) {
417
+ if (i < text.length && !isSeparator(text.charCodeAt(i))) {
418
+ at[count++] = i;
419
+ continue;
420
+ }
421
+ if (i > from)
422
+ parts.push(lower.slice(from, i));
423
+ from = i + 1;
424
+ }
425
+ const flat = parts.join("");
426
+ // The start of the stretch each character is in: a stretch ends where two kept characters are more than one apart.
427
+ const stretch = new Int32Array(count);
428
+ for (let k = 1; k < count; k++)
429
+ stretch[k] = at[k] - at[k - 1] > 2 ? k : stretch[k - 1];
430
+ for (const needle of folds) {
431
+ if (!needle)
432
+ continue;
433
+ for (let i = flat.indexOf(needle); i >= 0; i = flat.indexOf(needle, i + 1)) {
434
+ const last = i + needle.length - 1;
435
+ if (stretch[last] <= i)
436
+ out.push([at[i], at[last] + 1]);
437
+ }
438
+ }
439
+ }
440
+ /** `found` in order, each run of overlapping or touching spans as one. */
441
+ export function merged(found) {
442
+ const out = [];
443
+ for (const [start, end] of [...found].sort((a, b) => a[0] - b[0])) {
444
+ const last = out.at(-1);
445
+ if (last && start <= last[1])
446
+ last[1] = Math.max(last[1], end);
447
+ else
448
+ out.push([start, end]);
449
+ }
450
+ return out;
451
+ }
452
+ /** `text` with each of `spans` (merged, in order) replaced by "[redacted]". */
453
+ export function cutAt(text, spans) {
454
+ let out = "";
455
+ let from = 0;
456
+ for (const [start, end] of spans) {
457
+ out += `${text.slice(from, start)}[redacted]`;
458
+ from = end;
459
+ }
460
+ return out + text.slice(from);
461
+ }
462
+ const HEX = only("0123456789abcdefABCDEF");
463
+ const BLANKS = /[\t-\r ]+/y;
464
+ /** A run of percent-encoded bytes, decoded as UTF-8 (decoded). */
465
+ const PERCENT = {
466
+ trigger: "%",
467
+ decode(text, at, unit) {
468
+ let end = at;
469
+ while (text[end] === "%" && HEX(text.charCodeAt(end + 1)) && HEX(text.charCodeAt(end + 2)))
470
+ end += 3;
471
+ if (end === at)
472
+ return -1;
473
+ decoded(text, at, end, unit);
474
+ return end;
475
+ },
476
+ };
477
+ /** "+" as a space, as a form's encoding writes one. */
478
+ const PLUS = { trigger: "+", decode: (_text, at, unit) => (unit(" ", at, at + 1), at + 1) };
479
+ const viewSpec = (when, decoders) => ({
480
+ when,
481
+ decoders,
482
+ special: new RegExp(`[\\s${decoders.map((decoder) => `\\${decoder.trigger}`).join("")}\\u0080-\\uffff]`, "g"),
483
+ });
484
+ /** The views of a text read for each held value, in order: squeezed; percent-decoded; percent-decoded with "+" as a
485
+ * space. Each is lowered for hexes and flattened for folded identifiers in holds. */
486
+ const VIEWS = [
487
+ viewSpec(() => true, []),
488
+ viewSpec((text) => /%[0-9a-fA-F]{2}/.test(text), [PERCENT]),
489
+ viewSpec((text) => text.includes("+"), [PERCENT, PLUS]),
490
+ ];
491
+ /** `text` as the whole-text check reads it: decoded by `spec`'s decoders, NFKC, and its whitespace gone, as
492
+ * learn/secrets.ts has always squeezed it. NFKC is applied to each stretch of non-ASCII characters with the ASCII
493
+ * character before it, which gives what it gives over the whole text (an ASCII character is a starter nothing composes
494
+ * onto), and each character it makes comes from that whole stretch. With `cuts` (merged spans of `text`), the view's
495
+ * covered stretches: where every character comes from inside one cut. */
496
+ function viewOf(text, spec, cuts) {
497
+ const out = [];
498
+ const covered = [];
499
+ let length = 0;
500
+ let cut = 0;
501
+ const cover = (from, to) => {
502
+ const last = covered.at(-1);
503
+ if (last && last[1] === from)
504
+ last[1] = to;
505
+ else
506
+ covered.push([from, to]);
507
+ };
508
+ /** Text characters [from, to) as they are, all ASCII and none whitespace. */
509
+ const emitSlice = (from, to) => {
510
+ if (to <= from)
511
+ return;
512
+ out.push(text.slice(from, to));
513
+ if (cuts) {
514
+ while (cut < cuts.length && cuts[cut][1] <= from)
515
+ cut++;
516
+ for (let k = cut; k < cuts.length && cuts[k][0] < to; k++) {
517
+ const start = Math.max(from, cuts[k][0]);
518
+ const end = Math.min(to, cuts[k][1]);
519
+ if (start < end)
520
+ cover(length + start - from, length + end - from);
521
+ }
522
+ }
523
+ length += to - from;
524
+ };
525
+ /** View characters `chars`, each made of text [from, to). */
526
+ const emit = (chars, from, to) => {
527
+ if (!chars)
528
+ return;
529
+ out.push(chars);
530
+ if (cuts) {
531
+ while (cut < cuts.length && cuts[cut][1] <= from)
532
+ cut++;
533
+ if (cut < cuts.length && cuts[cut][0] <= from && to <= cuts[cut][1])
534
+ cover(length, length + chars.length);
535
+ }
536
+ length += chars.length;
537
+ };
538
+ let held;
539
+ let group;
540
+ const flushHeld = () => {
541
+ if (held && !isSpace(held.char.charCodeAt(0)))
542
+ emit(held.char, held.from, held.to);
543
+ held = undefined;
544
+ };
545
+ const nfkc = (chars) => chars.normalize("NFKC").replace(/\s+/gu, "");
546
+ const flushGroup = () => {
547
+ if (!group)
548
+ return;
549
+ const made = nfkc(group.chars);
550
+ const { lead } = group;
551
+ const rest = lead ? nfkc(group.chars.slice(lead.char.length)) : "";
552
+ // Where nothing composed onto the ASCII character, it comes from itself alone: a value cut in place right before
553
+ // a non-ASCII character is still covered to its last character.
554
+ if (lead && made === nfkc(lead.char) + rest) {
555
+ held = lead;
556
+ flushHeld();
557
+ emit(rest, lead.to, group.to);
558
+ }
559
+ else
560
+ emit(made, group.from, group.to);
561
+ group = undefined;
562
+ };
563
+ const unit = (char, from, to) => {
564
+ if (char.charCodeAt(0) >= 128) {
565
+ if (group) {
566
+ group.chars += char;
567
+ group.to = to;
568
+ }
569
+ else {
570
+ group = held ? { chars: held.char + char, from: held.from, to, lead: held } : { chars: char, from, to };
571
+ held = undefined;
572
+ }
573
+ return;
574
+ }
575
+ flushGroup();
576
+ flushHeld();
577
+ held = { char, from, to };
578
+ };
579
+ const special = new RegExp(spec.special.source, "g");
580
+ let at = 0;
581
+ while (at < text.length) {
582
+ special.lastIndex = at;
583
+ const hit = special.exec(text);
584
+ const stop = hit ? hit.index : text.length;
585
+ if (stop > at) {
586
+ flushGroup();
587
+ flushHeld();
588
+ emitSlice(at, stop - 1);
589
+ held = { char: text[stop - 1], from: stop - 1, to: stop };
590
+ }
591
+ if (!hit)
592
+ break;
593
+ const char = text[stop];
594
+ let end = -1;
595
+ for (const decoder of spec.decoders)
596
+ if (decoder.trigger === char)
597
+ end = decoder.decode(text, stop, unit);
598
+ if (end >= 0)
599
+ at = end;
600
+ else if (char.charCodeAt(0) < 128 && isSpace(char.charCodeAt(0))) {
601
+ // A run of ASCII whitespace is gone from the view: only its last character is held, as the one a non-ASCII
602
+ // character after it could compose onto.
603
+ BLANKS.lastIndex = stop;
604
+ BLANKS.test(text);
605
+ flushGroup();
606
+ flushHeld();
607
+ held = { char: text[BLANKS.lastIndex - 1], from: BLANKS.lastIndex - 1, to: BLANKS.lastIndex };
608
+ at = BLANKS.lastIndex;
609
+ }
610
+ else {
611
+ unit(char, stop, stop + 1);
612
+ at = stop + 1;
613
+ }
614
+ }
615
+ flushGroup();
616
+ flushHeld();
617
+ return { text: out.join(""), covered };
618
+ }
619
+ /** The characters a run of percent-encoded bytes text[from, to) decodes to (as UTF-8, invalid bytes as U+FFFD, as
620
+ * Buffer decodes the run whole), each with the bytes it came from; a run whose bytes decode otherwise one sequence at
621
+ * a time has each character come from the whole run. */
622
+ function decoded(text, from, to, unit) {
623
+ // An ASCII byte is its own character: a run of them (the common "%20", "%2F%3D") is read without a buffer.
624
+ let ascii = true;
625
+ for (let at = from + 1; at < to && ascii; at += 3)
626
+ ascii = text.charCodeAt(at) < 56;
627
+ if (ascii) {
628
+ for (let at = from; at < to; at += 3)
629
+ unit(String.fromCharCode(Number.parseInt(text.slice(at + 1, at + 3), 16)), at, at + 3);
630
+ return;
631
+ }
632
+ const bytes = Buffer.from(text.slice(from, to).replaceAll("%", ""), "hex");
633
+ const whole = bytes.toString("utf8");
634
+ const pieces = [];
635
+ for (let k = 0; k < bytes.length;) {
636
+ const lead = bytes[k];
637
+ const size = Math.min(bytes.length - k, lead < 0x80 ? 1 : lead >> 5 === 6 ? 2 : lead >> 4 === 14 ? 3 : lead >> 3 === 30 ? 4 : 1);
638
+ pieces.push([bytes.subarray(k, k + size).toString("utf8"), from + 3 * k, from + 3 * (k + size)]);
639
+ k += size;
640
+ }
641
+ if (pieces.map(([chars]) => chars).join("") === whole) {
642
+ for (const [chars, start, end] of pieces)
643
+ for (const char of chars)
644
+ for (let i = 0; i < char.length; i++)
645
+ unit(char[i], start, end);
646
+ }
647
+ else
648
+ for (let i = 0; i < whole.length; i++)
649
+ unit(whole[i], from, to);
650
+ }
651
+ /** A view with its separators ("-", "_", ":", ".") gone, its covered stretches moved to match. */
652
+ function flatOf(view) {
653
+ const parts = [];
654
+ const kept = new Int32Array(view.text.length + 1);
655
+ let from = 0;
656
+ let count = 0;
657
+ for (let i = 0; i < view.text.length; i++) {
658
+ kept[i] = count;
659
+ if (isSeparator(view.text.charCodeAt(i))) {
660
+ if (i > from)
661
+ parts.push(view.text.slice(from, i));
662
+ from = i + 1;
663
+ }
664
+ else
665
+ count++;
666
+ }
667
+ kept[view.text.length] = count;
668
+ if (view.text.length > from)
669
+ parts.push(view.text.slice(from));
670
+ const covered = [];
671
+ for (const [start, end] of view.covered) {
672
+ const [a, b] = [kept[start], kept[end]];
673
+ if (a >= b)
674
+ continue;
675
+ const last = covered.at(-1);
676
+ if (last && last[1] === a)
677
+ last[1] = b;
678
+ else
679
+ covered.push([a, b]);
680
+ }
681
+ return { text: parts.join(""), covered };
682
+ }
683
+ /** Whether [start, end) of a view lies in one of its covered stretches. */
684
+ function inside(covered, start, end) {
685
+ let lo = 0;
686
+ let hi = covered.length - 1;
687
+ while (lo <= hi) {
688
+ const mid = (lo + hi) >> 1;
689
+ if (covered[mid][0] <= start)
690
+ lo = mid + 1;
691
+ else
692
+ hi = mid - 1;
693
+ }
694
+ return hi >= 0 && covered[hi][1] >= end;
695
+ }
696
+ /** Whether `view` holds one of `needles` outside its covered stretches (with no `covered`, anywhere). */
697
+ function holdsIn(view, covered, needles) {
698
+ for (const needle of needles) {
699
+ if (!needle)
700
+ continue;
701
+ if (!covered) {
702
+ if (view.includes(needle))
703
+ return true;
704
+ continue;
705
+ }
706
+ for (let at = view.indexOf(needle); at >= 0; at = view.indexOf(needle, at + 1))
707
+ if (!inside(covered, at, at + needle.length))
708
+ return true;
709
+ }
710
+ return false;
711
+ }
712
+ /** Whether `text` holds a held value in a form the cut does not find as it stands: split by whitespace, percent or
713
+ * form encoded, an NFKC variant, its hex in any case, a hex identifier folded (`fold`). With `cuts`, a value whose
714
+ * every character the view read comes from inside the cuts is not held: it is cut in place. */
715
+ export function holds(text, needles, { fold = true, cuts } = {}) {
716
+ const folds = fold ? needles.folds : [];
717
+ if (!needles.plain.length && !needles.hexes.length && !folds.length)
718
+ return false;
719
+ for (const spec of VIEWS) {
720
+ if (!spec.when(text))
721
+ continue;
722
+ const view = viewOf(text, spec, cuts);
723
+ const covered = cuts ? view.covered : undefined;
724
+ if (holdsIn(view.text, covered, needles.plain))
725
+ return true;
726
+ if (!needles.hexes.length && !folds.length)
727
+ continue;
728
+ const lower = { text: asciiLower(view.text), covered: view.covered };
729
+ if (holdsIn(lower.text, covered, needles.hexes))
730
+ return true;
731
+ if (!folds.length)
732
+ continue;
733
+ const flat = flatOf(lower);
734
+ if (holdsIn(flat.text, cuts ? flat.covered : undefined, folds))
735
+ return true;
736
+ }
737
+ return false;
738
+ }
739
+ /** planCut's first step: every form, hex, folded identifier and shape of `text` as it came, and `held`, merged. */
740
+ export function cutSpans(text, needles, shapes, held = []) {
741
+ const lower = lowered(text);
742
+ const found = held.map(([start, end]) => [start, end]);
743
+ for (const form of needles.forms)
744
+ places(text, form, found);
745
+ for (const hex of needles.hexes)
746
+ places(lower(), hex, found);
747
+ // One by one: a text of very many finds would overflow the stack as one call's arguments.
748
+ for (const shape of shapes)
749
+ for (const span of spansOf(text, lower, shape))
750
+ found.push(span);
751
+ if (needles.folds.length)
752
+ foldSpans(text, needles.folds, found);
753
+ return merged(found);
754
+ }
755
+ /** Where `text` is cut of `needles` and of each of `shapes`, and the text so cut; or "whole" when it must be withheld
756
+ * whole. `held`: spans cut in place beside the finds. The order is fixed:
757
+ * 1. every form, hex, folded identifier and shape is found in the text as it came, and the spans merged;
758
+ * 2. the views of the text as it came are read for each held value: one any of whose characters comes from outside
759
+ * the spans withholds the text (a cut can hide part of a value, so the check never reads the cut text for it);
760
+ * 3. the spans are cut;
761
+ * 4. what is left is read again, for a value or a shape the cut made (a value whose rest the cut joined, a shape whose
762
+ * guard the cut removed), and withholds the text if it holds one. */
763
+ export function planCut(text, needles, shapes, held = []) {
764
+ const spans = cutSpans(text, needles, shapes, held);
765
+ if (holds(text, needles, { cuts: spans }))
766
+ return "whole";
767
+ const out = spans.length ? cutAt(text, spans) : text;
768
+ if (spans.length && (holds(out, needles) || shapeKinds(out, shapes).length > 0))
769
+ return "whole";
770
+ return { spans, out };
771
+ }