File size: 26,453 Bytes
d0a4896
 
 
 
 
 
 
 
 
3bbcdfe
d0a4896
 
3bbcdfe
c5ecdb0
 
 
 
 
 
 
 
d0a4896
 
 
 
 
 
c5ecdb0
d0a4896
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c5ecdb0
 
 
 
d0a4896
c5ecdb0
 
 
 
d0a4896
 
 
c5ecdb0
 
d0a4896
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c5ecdb0
d0a4896
 
 
 
 
c5ecdb0
 
 
 
 
 
 
 
 
 
d0a4896
 
 
 
c5ecdb0
d0a4896
 
 
 
 
 
 
 
 
 
3bbcdfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0a4896
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c5ecdb0
3bbcdfe
d0a4896
 
 
3bbcdfe
 
 
 
d0a4896
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
// decima-pii in the browser: a port of decima_pii.py (https://huggingface.co/amyrmahdy/decima-pii) — the token
// offsets, the window loop, decode (bridging of whitespace-only tokens) and postfilter, kept line for line with the
// Python file. All positions are in code points, like Python string indices; `cps` is [...text].
// No DOM and no model here, so the same file runs in the page's worker and in node for the checks.

export const TRAIL = new Set([...".,;:!?\u060c\u061b\u061f\u00bb)\"'\u06d4"]);
export const LEAD = new Set([..."\u00ab\"'"]);
export const MARKS = new Set(["\u200e", "\u200f", "\u200c"]);
const DIGIT = /[0-9\u0660-\u0669\u06f0-\u06f9]/u;
export const DEFAULT_DECODER = "v2.1";
export const MIN_DIGITS = { PHONE: 6, CARD: 12, IBAN: 10, NATIONAL_ID: 5, PASSPORT: 5, DATE_OF_BIRTH: 2, IP_ADDRESS: 4 };
const CLITICS = new Set([..."\u0648\u0628\u0644\u0641\u0643\u0633"]);   // و ب ل ف ك س
// decoder v2 (from decima-pii v0.2; v2.1 = v2 + phone backstop is the default from v0.2.1): number words count toward a PHONE / NATIONAL_ID digit minimum.
export const NUM_WORDS = new Set(`zero oh one two three four five six seven eight nine ten eleven twelve thirteen fourteen fifteen sixteen seventeen
eighteen nineteen twenty thirty forty fifty sixty seventy eighty ninety hundred double triple
sıfır bir iki üç dört beş altı yedi sekiz dokuz on yirmi otuz kırk elli altmış yetmiş seksen doksan yüz
صفر واحد اثنين اثنان اتنين ثلاثة تلاتة أربعة اربعة خمسة ستة سبعة ثمانية تمانية تسعة عشرة
یک دو سه چهار پنج شش هفت هشت نه ده یازده دوازده سیزده چهارده پانزده شانزده هفده هجده نوزده بیست سی چهل پنجاه شصت هفتاد هشتاد نود
صد دویست سیصد چهارصد پانصد ششصد هفتصد هشتصد نهصد
ایک تین چار پانچ چھ سات آٹھ نو`.split(/\s+/));
const WORD = /[\p{L}\p{Nl}\p{No}]+/gu;      // Python's [^\W\d_]+ : letters and non-decimal numerals

// Python's str.isspace() and str.isalnum() for one code point.
const PY_SPACE = /^[\t\n\x0b\x0c\r\x1c-\x1f \x85\xa0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]$/u;
const PY_ALNUM = /^[\p{L}\p{N}]$/u;
export const isspace = (c) => c !== undefined && PY_SPACE.test(c);
export const isalnum = (c) => c !== undefined && PY_ALNUM.test(c);
const isalpha = (c) => c !== undefined && /^\p{L}$/u.test(c);

// ───────────────────────── tokens with offsets ─────────────────────────

/** Token ids and (start, end) code-point offsets, as `Tokenizer.encode(text, add_special_tokens=False)` of the Rust
 *  tokenizers library gives them for mmBERT's tokenizer.json (Replace " "→"▁", Metaspace prepend "always",
 *  BPE with byte fallback), with no truncation. tokenizers.js returns tokens but no offsets, and keeps a run of
 *  spaces together where Rust splits it, so the text is encoded in pieces that each start at a space (each Rust
 *  Metaspace piece starts at a "▁"), and the offsets are recovered by walking the token strings over the text. */
export function encodeWithOffsets(tok, text) {
  const tokens = [];
  for (const seg of text.split(/(?= )/)) if (seg) tokens.push(...tok.encode(seg, { add_special_tokens: false }).tokens);
  const cps = [...text];
  const ids = [], offsets = [];
  let p = 0;
  let pend = 0;                      // UTF-8 bytes still expected for the char being spelled out by byte tokens
  for (const t of tokens) {
    const id = tok.token_to_id(t);
    if (id === undefined || id === null) throw new Error(`unknown token ${JSON.stringify(t)}`);
    ids.push(id);
    const byte = /^<0x([0-9A-F]{2})>$/.exec(t);
    if (byte) {                     // Rust gives every byte token the offsets of its whole character
      const b = parseInt(byte[1], 16);
      if (pend === 0) pend = b >= 0xf0 ? 4 : b >= 0xe0 ? 3 : b >= 0xc0 ? 2 : 1;
      offsets.push([p, p + 1]);
      if (--pend === 0) p += 1;
      continue;
    }
    if (pend) throw new Error("token offsets: broken byte sequence");
    let s = p, consumed = false, first = true;
    for (const c of t) {
      if (c === "▁" && (cps[p] === " " || cps[p] === "▁")) { p += 1; consumed = true; }
      else if (c === "▁" && first) { /* the "▁" Metaspace prepends: no character of its own */ }
      else {
        // an added token with lstrip (<mask>) takes the whitespace before it
        if (first && cps[p] !== c) while (p < cps.length && isspace(cps[p]) && cps[p] !== c) p += 1;
        if (first) s = p;
        if (cps[p] !== c) throw new Error(`token offsets: ${JSON.stringify(t)} does not match the text at ${p}`);
        p += 1; consumed = true;
      }
      first = false;
    }
    offsets.push([s, consumed ? p : p + 1]);   // a lone prepended "▁" carries the next character's offsets
  }
  if (p !== cps.length && !cps.slice(p).every(isspace)) throw new Error("token offsets: text not fully covered");
  return { ids, offsets, cps };
}

// ───────────────────────── decima_pii.py ─────────────────────────

const isInitialPeriod = (cps, s, i) =>
  cps[i] === "." && i - 1 >= s && isalpha(cps[i - 1]) && (i - 1 === s || [" ", ".", "\u00a0"].includes(cps[i - 2]));

function trim(cps, s, e, label = null, initials = true) {
  while (s < e && (isspace(cps[s]) || LEAD.has(cps[s]) || MARKS.has(cps[s]))) s += 1;
  while (e > s && (isspace(cps[e - 1]) || TRAIL.has(cps[e - 1]) || MARKS.has(cps[e - 1]))) {
    if (initials && label === "PERSON_NAME" && isInitialPeriod(cps, s, e - 1)) break;   // "Anna S." keeps the period
    e -= 1;
  }
  return [s, e];
}

/** Token BIO tags -> character spans, bridging bare space tokens inside an entity. initials=false is decoder v1. */
export function decode(cps, offsets, tags, initials = true) {
  const spans = [];
  let cur = null;
  for (let i = 0; i < offsets.length && i < tags.length; i++) {
    const [a, b] = offsets[i], lab = tags[i];
    if (a === b) continue;
    if (lab === "O") {
      if (cur && cps.slice(a, b).every(isspace)) continue;
      if (cur) { spans.push(cur); cur = null; }
      continue;
    }
    const k = lab.indexOf("-");
    const tag = lab.slice(0, k), typ = lab.slice(k + 1);
    if (cur && tag === "I" && cur.label === typ) cur.end = b;
    else {
      if (cur) spans.push(cur);
      cur = { start: a, end: b, label: typ };
    }
  }
  if (cur) spans.push(cur);
  const out = [];
  for (const s of spans) {
    const [a, b] = trim(cps, s.start, s.end, s.label, initials);
    if (a < b) out.push({ start: a, end: b, label: s.label });
  }
  return out;
}

function numCount(v, spelled) {
  let n = v.filter((c) => DIGIT.test(c)).length;
  if (spelled) for (const w of v.join("").match(WORD) || []) if (NUM_WORDS.has(w.toLowerCase())) n += 2;   // 1-3 digits each
  return n;
}

/** Drop spans with too few digits for their type (number words count for PHONE / NATIONAL_ID unless spelled=false,
 *  which is decoder v1), emails without '@', one-character names, and spans that cut through a word (a one-letter
 *  Arabic-script clitic such as و before a name is allowed). */
export function postfilter(cps, spans, spelled = true) {
  const out = [];
  for (const p of spans) {
    const a = p.start, b = p.end, lab = p.label;
    const v = cps.slice(a, b);
    if (lab in MIN_DIGITS && numCount(v, spelled && (lab === "PHONE" || lab === "NATIONAL_ID")) < MIN_DIGITS[lab]) continue;
    if ((lab === "EMAIL" && !v.includes("@")) || ((lab === "PERSON_NAME" || lab === "ADDRESS") && v.length < 2)) continue;
    const left = a > 0 && isalnum(cps[a - 1]) && isalnum(cps[a])
      && !(CLITICS.has(cps[a - 1]) && (a < 2 || !isalnum(cps[a - 2])));
    const right = b < cps.length && isalnum(cps[b]) && isalnum(cps[b - 1]);
    if (left || right) continue;
    out.push(p);
  }
  return out;
}

// ───────────────────────── decoder v2.1: cue-gated phone backstop (port of phone_backstop in decima_pii.py) ─────────
// Runs after the model + post-filter and can only ADD PHONE spans. A digit run becomes PHONE only when (a) a phone cue
// word sits right before it (at most 3 filler words / 25 characters between, no blocker word such as order / invoice /
// ID / price near the cue) or right after it, or it follows another phone after "/", "or", ","; (b) with Arabic-Indic
// and Persian digits read as 0-9 and separators removed, it fits a national or international phone pattern (toll-free
// and hotline prefixes excluded); (c) it overlaps no span already found and is not a date or card by format, nor glued
// to letters (IBANs), and no currency or unit follows it. Kept identical with decima_pii.py and decima/pii.py.

const TO_ASCII = new Map([..."٠١٢٣٤٥٦٧٨٩۰۱۲۳۴۵۶۷۸۹"].map((c, i) => [c, String(i % 10)]));
const LETTER = new Map(Object.entries({ "أ": "ا", "إ": "ا", "آ": "ا", "ٱ": "ا", "ى": "ي", "ی": "ي", "ک": "ك", "ة": "ه", "ۀ": "ه", "ہ": "ه", "ھ": "ه" }));
const AR_PRE = ["", "و", "ب", "ل", "ف", "ك", "ال", "وال", "بال", "لل", "فال", "كال", "ولل", "وب", "ول", "فب"];
// "*": the word may carry up to 3 more letters (جوال* → جوالي, جوالك; phone* → phones); "~": no Arabic prefix (و ب ل ال …)
export const PHONE_CUES_STRONG = `جوال* موبايل* موبيل* مبايل* محمول* تلفون* تليفون* تلفن* هاتف* نقال* خلوي* بورطابل* تيليفون* واتساب* واتس* وتساب* وتس*
واتساپ* موبائل* فون* واٹس* واٹساپ* telefon* tel cep cebim* gsm whatsapp* whats* wp phone* mobile* mob cell cellphone* telephone* ph
jawal* jawwal* mobil mobilim mobilam mobaily mobayl* tlfn tlf tlfoni tlfon* tilifon* talafon* watsap* wats* whatsap*`;
export const PHONE_CUES_WEAK = `~رقمي ~رقمك ~رقمه ~رقمها ~رقمنا ~نمرتي ~نمرتك اتصل* تواصل* كلمني كلموني كلمي رن رنلي دق دقلي عيط* نومرو* احكيني
شمارم* شماره_ام شماره_من شماره_جديدم شماره_جديد شماره_همراه تماس* زنگ* ميرا_نمبر رابطه* كال* numaram* ara arayın arayin arayınız
arayabilirsiniz ulaşın ulasin ulaşabilirsiniz ulasabilirsiniz iletişim* iletisim* my_number new_number contact_number call contact text reach
dial بيت منزل* خانه home ev اتصال* rakmi ra2mi raqmi ra8mi kalimni kallemni kalemni shomaram* shomare_man shomare_jadidam tamas zang`;
export const PHONE_BLOCKERS = `طلب* اوردر* فاتور* هوي* اقام* مدني قومي* حساب* ايبان* بطاق* جواز* شحن* تتبع مرجع* تسلسل* سيريال* موديل* طراز اصدار
شكوي بلاغ* عقد حجز* تذكر* لوحه عضوي* سعر* ثمن* قيم* مبلغ* كود* رمز* التحقق تفعيل* سري* قسط* باقه جيجا كوموند* خدمه عملاء طوارئ مركز
ساخن سفارش* فاكتور* كارت* ملي كد پيگيري* شبا پاسپورت گذرنامه پرسنلي دانشجويي پرونده پلاك قيمت* سريال مدل* بليت بليط رزرو قرارداد
عضويت شارژ بسته گيگ تاييد پشتيباني اورژانس ارڈر شناختي اكاؤنٹ كارڈ پاسپورٹ ماڈل بل رسيد پيكج ٹريكنگ sipariş* siparis* fatura* kimlik
tc tckn hesap hesab* iban kart* pasaport* kargo* takip abone* sicil* seri model* fiyat* tutar* ücret* ucret* bilet* rezervasyon* poliçe*
police dosya* plaka* şifre* sifre* kod* doğrulama dogrulama vergi hizmetleri* order* invoice* account* acct card* id passport* tracking ref
reference serial imei price* cost* total amount ticket* booking* reservation policy sku otp pin password code verification bill* plan*
receipt* transaction* ssn service center centre hotline support emergency talab gheymat sefaresh نسخه version* sürüm* surum*
شناسه* بيمه* گواهينامه مالياتي وظيف* ضريب* رخصه tax license* licence* ehliyet* insurance sigorta*`;
// person-role words: block only the generic cues ("öğrenci numaram …", "customer number …" is not a phone)
export const PHONE_ROLE_WORDS = `müşteri* musteri* öğrenci* ogrenci* çalışan* calisan* personel* üye* uye* hasta* customer* student* employee* member*
patient* staff عميل* طالب* موظف* عضو* مريض* مشترك* مشتري* دانشجو* پرسنل* كارمند* بيمار* ملازم* گاهك*`;
export const PHONE_UNITS = `ريال* درهم* دينار* جنيه* ليره تومان روپے روپي tl lira sar aed qar kwd bhd omr egp usd dollar* riyal* toman rial rs pkr gb mb
جيجا ميجا گيگ جي kg mah adet`;
export const PHONE_CUES_AFTER = "تماس* زنگ* numaralı_telefon* numarali_telefon* nolu_telefon* numaralı_cep*";   // may also follow the number
const OR_WORDS = new Set(["او", "or", "veya", "ya", "يا", "يان"]);
const INTL_SRC = { "966": "5\\d{8}|1[1-7]\\d{7}", "971": "5\\d{8}|[2-9]\\d{7}", "974": "[3-7]\\d{7}", "965": "[2569]\\d{7}", "973": "[136]\\d{7}",
  "968": "[279]\\d{7}", "20": "1[0125]\\d{8}|[2-9]\\d{7,8}", "962": "7[789]\\d{7}|[2-6]\\d{7}", "212": "[5-7]\\d{8}",
  "98": "9\\d{9}|[1-8]\\d{9}", "92": "3\\d{9}|[2-9]\\d{8,9}", "90": "5\\d{9}|[2-4]\\d{9}", "44": "7\\d{9}|[1-3]\\d{8,9}",
  "1": "[2-9]\\d{2}[2-9]\\d{6}", "961": "[3-9]\\d{6,7}", "963": "9\\d{8}|[1-5]\\d{7,8}", "964": "7\\d{9}|[1-6]\\d{7,8}",
  "967": "7\\d{8}|[1-6]\\d{6,7}", "213": "[5-7]\\d{8}|[2-4]\\d{7}", "216": "[2-9]\\d{7}", "218": "9\\d{8}|[2-8]\\d{7,8}",
  "249": "[19]\\d{8}", "970": "5\\d{8}", "91": "[6-9]\\d{9}", "93": "7\\d{8}" };
const INTL_RE = Object.fromEntries(Object.entries(INTL_SRC).map(([k, v]) => [k, new RegExp(`^(?:${v})$`)]));
const CC = Object.keys(INTL_SRC).sort((a, b) => b.length - a.length);   // stable: same order as Python's sorted(…, key=len, reverse=True)
const CC_NOPLUS = ["966", "971", "974", "965", "973", "968", "20", "962"];      // written without "+" (WhatsApp exports, forms)
const NATIONAL_RE = new RegExp("^(?:05\\d{8}|01[1-7]\\d{7}|5\\d{8}|0[2-9]\\d{7}|[1-79]\\d{7}|01[0125]\\d{8}|0[2-9]\\d{8}|07[789]\\d{7}|0[5-7]\\d{8}"
  + "|09\\d{9}|0[1-8]\\d{9}|03\\d{9}|0[2-9]\\d{9}|05\\d{9}|0[2-4]\\d{9}|5\\d{9}|07\\d{9}|0[1-3]\\d{8,9}"
  + "|1?[2-9]\\d{2}[2-9]\\d{6}|07\\d{9}|[6-9]\\d{9})$");
const TOLL_FREE = ["800", "0800", "080", "0850", "0845", "0870", "0871", "0900", "9200", "1800", "1888", "1877", "1866", "1855", "1844",
  "888", "877", "866", "855", "844", "4444"];
const SEPS = new Set([..."  -./()"]), PRE_BAD = new Set([..."/=#@_&?$€£₺%"]), CUR = new Set([..."$€£₺%@"]);
const STOPS = new Set([...".,،؛;!?\n|"]), CHAIN_OK = new Set([..."  ,،/-|;؛\n"]);
const isMark = (c) => /^\p{M}$/u.test(c);
const tokchar = (c) => /^[\p{L}\p{Nd}\p{M}]$/u.test(c);
const isDigit = (c) => c >= "0" && c <= "9";

/** Word key for matching: lower case, marks dropped, Arabic/Persian/Urdu letter variants unified. */
export function wkey(w) {
  return [...w.toLowerCase()].filter((c) => !isMark(c)).map((c) => LETTER.get(c) ?? c).join("");
}

function cueList(s) {
  return s.split(/\s+/).filter(Boolean).map((e) => {
    const bare = e.startsWith("~");
    return [e.replace(/^~+/, "").split("_").map((w) => [wkey(w.replace(/\*+$/, "")), w.endsWith("*")]), !bare];
  });
}
const STRONG = cueList(PHONE_CUES_STRONG), WEAK = cueList(PHONE_CUES_WEAK), BLOCK = cueList(PHONE_BLOCKERS), UNITS = cueList(PHONE_UNITS);
const AFTER = [...STRONG, ...cueList(PHONE_CUES_AFTER)], ROLE = cueList(PHONE_ROLE_WORDS);

function wmatch(key, pat, star, pre) {
  for (const p of pre ? AR_PRE : [""]) {
    if (key.startsWith(p)) {
      const rest = key.slice(p.length);
      if (rest === pat || (star && rest.startsWith(pat) && [...rest].length - [...pat].length <= 3)) return true;
    }
  }
  return false;
}

/** [start, end, key, hasLetter] for every run of letters, marks and digits (code-point positions). */
function tokens(t) {
  const out = [];
  let i = 0;
  const n = t.length;
  while (i < n) {
    if (tokchar(t[i])) {
      let j = i;
      while (j < n && tokchar(t[j])) j += 1;
      const w = t.slice(i, j);
      out.push([i, j, wkey(w.join("")), w.some((c) => /^\p{L}$/u.test(c))]);
      i = j;
    } else i += 1;
  }
  return out;
}

/** Start index of an entry of lst whose last word is token k (forward: whose first word is token k), else -1. */
function phraseAt(toks, k, lst, forward = false) {
  for (const [words, pre] of lst) {
    const L = words.length;
    const a = forward ? k : k - L + 1;
    if (a < 0 || a + L > toks.length) continue;
    let ok = true;
    for (let m = 0; m < L; m++) {
      if (m && toks[a + m][0] - toks[a + m - 1][1] > 2) { ok = false; break; }
      if (!wmatch(toks[a + m][2], words[m][0], words[m][1], pre)) { ok = false; break; }
    }
    if (ok) return a;
  }
  return -1;
}

function isPhone(d, intl) {
  if (intl) {
    const s = d.startsWith("00") ? d.slice(2) : d;
    for (const cc of CC) {
      if (s.startsWith(cc)) {
        let nsn = s.slice(cc.length);
        if (nsn.startsWith("0")) nsn = nsn.slice(1);                       // "+44 (0) 7700 …"
        return INTL_RE[cc].test(nsn);
      }
    }
    return s.length >= 8 && s.length <= 15 && s[0] !== "0";
  }
  if (TOLL_FREE.some((p) => d.startsWith(p))) return false;
  if (NATIONAL_RE.test(d)) return true;
  return CC_NOPLUS.some((cc) => d.startsWith(cc) && INTL_RE[cc].test(d.slice(cc.length)));
}

function sepOk(s) {
  return s.length >= 1 && s.length <= 3 && s.every((c) => SEPS.has(c)) && s.filter((c) => "-./".includes(c)).length <= 1
    && s.filter((c) => c === "(").length <= 1 && s.filter((c) => c === ")").length <= 1 && s.filter((c) => c === " " || c === " ").length <= 2;
}

function dateLike(t, grp) {
  if (grp.length !== 3) return false;
  const seps = [0, 1].map((i) => t.slice(grp[i][1], grp[i + 1][0]));
  if (!seps.every((s) => s.length === 1 && "/.-".includes(s[0]))) return false;
  const L = grp.map(([a, b]) => b - a);
  return (L[0] <= 2 && L[1] <= 2 && (L[2] === 2 || L[2] === 4)) || (L[0] === 4 && L[1] <= 2 && L[2] <= 2);
}

/** A blocker word (for a generic cue also a person-role word) among the words right before position p (same clause:
 *  no . , ; ! ? or newline in between, at most 24 characters back)? */
function blocked(t, toks, p, weak = false) {
  let q = -1;
  toks.forEach((x, k) => { if (x[1] <= p) q = Math.max(q, k); });
  let nxt = p;
  while (q >= 0 && toks[q][0] >= p - 24 && toks[q][3] && !t.slice(toks[q][1], nxt).some((c) => STOPS.has(c))) {
    if (phraseAt(toks, q, BLOCK, true) === q || (weak && phraseAt(toks, q, ROLE, true) === q)) return true;
    nxt = toks[q][0];
    q -= 1;
  }
  return false;
}

const isalnumAt = (t, i) => isalnum(t[i]);

/** Decoder v2.1: spans + cue-gated PHONE spans the model missed (see the comment above). `cps` is the text as code
 *  points. Returns `spans` itself when nothing is added. */
export function phoneBackstop(cps, spans) {
  const t = cps.map((c) => TO_ASCII.get(c) ?? c);
  const n = t.length;
  const groups = [];
  let i = 0;
  while (i < n) {
    if (isDigit(t[i])) {
      let j = i;
      while (j < n && isDigit(t[j])) j += 1;
      groups.push([i, j]); i = j;
    } else i += 1;
  }
  if (!groups.length) return spans;
  const runs = [];
  let cur = [groups[0]];
  for (const g of groups.slice(1)) {
    if (sepOk(t.slice(cur[cur.length - 1][1], g[0]))) cur.push(g);
    else { runs.push(cur); cur = [g]; }
  }
  runs.push(cur);
  let toks = null;
  const taken = spans.map((s) => [s.start, s.end]);
  const phoneEnds = spans.filter((s) => s.label === "PHONE").map((s) => s.end);
  const added = [];
  for (const run of runs) {
    if (run.length >= 4 && run.filter(([a, b]) => b - a === 4).length >= 3) continue;   // 4-4-4-4: a card or an account number
    if ((run.length >= 3 && dateLike(t, run.slice(0, 3)))
      || run.slice(1).filter((g, i) => t.slice(run[i][1], g[0]).includes(".")).length >= 3) continue;   // a date / timestamp; an IP or version
    let k = 0;
    while (k < run.length) {
      const a0 = run[k][0];
      let s = a0;
      const plus = k === 0 && s > 0 && t[s - 1] === "+";
      if (plus) s -= 1;
      if (k === 0 && s > 0 && t[s - 1] === "(" && t.slice(a0, run[run.length - 1][1]).includes(")")) s -= 1;
      let best = -1;
      for (let j = run.length - 1; j >= k; j--) {
        const d = run.slice(k, j + 1).map(([x, y]) => t.slice(x, y).join("")).join("");
        if (!dateLike(t, run.slice(k, j + 1)) && isPhone(d, plus || d.startsWith("00"))) { best = j; break; }
      }
      if (best < 0) break;
      const e = run[best][1];
      const first = k === 0;
      k = best + 1;
      if ((s > 0 && (isalnumAt(t, s - 1) || PRE_BAD.has(t[s - 1]))) || (e < n && (isalnumAt(t, e) || CUR.has(t[e])))) continue;
      if (first && s > 1 && "-./".includes(t[s - 1]) && isalnumAt(t, s - 2)) continue;     // "INV-2026-7741", "HSP-27321011"
      if (e + 1 < n && t[e] === ":" && isDigit(t[e + 1])) continue;                       // a time "… 09:14"
      if (taken.some(([x, y]) => x < e && s < y)) continue;
      if (toks === null) toks = tokens(t);
      const qa = toks.findIndex((x) => x[0] >= e);
      if (qa >= 0 && toks[qa][0] - e <= 2 && phraseAt(toks, qa, UNITS, true) >= 0) continue;
      let last = -1;
      toks.forEach((x, q) => { if (x[1] <= s) last = q; });
      let cued = false;
      const pe = Math.max(-1, ...phoneEnds.filter((p) => p <= s));
      if (pe >= 0 && s - pe <= 8) {                                              // "… 0551234567 / 0501234567", "… or …"
        const gap = toks.filter((x) => x[0] >= pe && x[1] <= s);
        cued = gap.every((x) => OR_WORDS.has(x[2])) && t.slice(pe, s).every((c) => tokchar(c) || CHAIN_OK.has(c));
      }
      if (!cued && last >= 0) {
        for (let g = 0; g < 4; g++) {                                            // g filler words between cue and number
          const c = last - g;
          if (c < 0 || s - toks[c][1] > 25) break;
          let bad = false;
          for (let q = c + 1; q <= last; q++) if (!toks[q][3] || phraseAt(toks, q, BLOCK, true) === q) { bad = true; break; }
          if (bad) break;
          let a = phraseAt(toks, c, STRONG), weak = false;
          if (a < 0) { a = phraseAt(toks, c, WEAK); weak = true; }
          if (a >= 0) {                                                          // no clause break between cue and number
            const gtxt = t.slice(toks[c][1], s);                                 // ("Tel. 0551…" keeps its period)
            cued = !gtxt.some((ch) => ";؛!?".includes(ch)) && !(weak ? gtxt : gtxt.slice(1)).includes(".")
              && !(weak && Array.from({ length: last - c }, (_, i) => c + 1 + i).some((q) => phraseAt(toks, q, ROLE, true) === q))
              && !blocked(t, toks, toks[a][0], weak);
            break;
          }
        }
      }
      if (!cued && qa >= 0 && toks[qa][0] - e <= 12 && !t.slice(e, toks[qa][0]).includes("\n")) {                        // "0551234567 (جوال)": cue right after,
        if (phraseAt(toks, qa, AFTER, true) === qa && toks.slice(qa + 1, qa + 4).every((x) => x[3]))   // unless a number follows it
          cued = !blocked(t, toks, s);
      }
      if (cued) {
        added.push({ start: s, end: e, label: "PHONE" });
        taken.push([s, e]); phoneEnds.push(e);
      }
    }
  }
  if (!added.length) return spans;
  return [...spans, ...added].sort((x, y) => x.start - y.start);
}

/** Tag ids in overlapping windows; each token takes the window where it is most central. `tagWindow(ids)` returns
 *  one label index per id (the model reads [bos] + ids + [eos]). */
export async function tagAll(ids, tagWindow, window = 256, stride = 192) {
  const n = ids.length, w = window - 2;
  if (!n) return [];
  if (n <= w) return tagWindow(ids);
  const pred = new Array(n).fill(0), best = new Array(n).fill(-1);
  const starts = [];
  for (let s = 0; s < n - w; s += stride) starts.push(s);
  starts.push(n - w);
  for (const s of starts) {
    const t = await tagWindow(ids.slice(s, s + w));
    t.forEach((lab, k) => {
      const centrality = Math.min(k, w - 1 - k);
      if (centrality > best[s + k]) { best[s + k] = centrality; pred[s + k] = lab; }
    });
  }
  return pred;
}

/** Spans {start, end, label, text} (code-point positions) for `text`. opts.decoder "v1" gives decima-pii v0.1's
 *  decoding; "v2" is v0.2's; "v2.1" (v0.2.1) adds the cue-gated phone backstop. */
export async function findPII(tok, labels, tagWindow, text, opts = {}) {
  const { ids, offsets, cps } = encodeWithOffsets(tok, text);
  const pred = await tagAll(ids, tagWindow, opts.window, opts.stride);
  const decoder = opts.decoder ?? DEFAULT_DECODER;
  const v2 = decoder !== "v1";
  let spans = postfilter(cps, decode(cps, offsets, pred.map((p) => labels[p]), v2), v2);
  if (decoder === "v2.1") spans = phoneBackstop(cps, spans);
  for (const s of spans) s.text = cps.slice(s.start, s.end).join("");
  return { spans, cps, tokens: ids.length };
}

/** The text with each span replaced by [LABEL]. */
export function redact(cps, spans, fmt = (l) => `[${l}]`) {
  let out = cps.slice();
  for (const s of [...spans].sort((x, y) => y.start - x.start)) out = [...out.slice(0, s.start), fmt(s.label), ...out.slice(s.end)];
  return out.join("");
}

/** ONNX Runtime (web or node) window tagger: argmax of the logits, special positions dropped. */
export function onnxTagger(ort, session, bos, eos) {
  return async (ids) => {
    const L = ids.length + 2;
    const x = BigInt64Array.from([bos, ...ids, eos], BigInt);
    const m = new BigInt64Array(L).fill(1n);
    const out = await session.run({ input_ids: new ort.Tensor("int64", x, [1, L]), attention_mask: new ort.Tensor("int64", m, [1, L]) });
    const lg = out.logits, C = lg.dims[2], d = lg.data;
    const tags = [];
    for (let i = 1; i < L - 1; i++) {
      let bi = 0, bv = d[i * C];
      for (let c = 1; c < C; c++) if (d[i * C + c] > bv) { bv = d[i * C + c]; bi = c; }
      tags.push(bi);
    }
    lg.dispose?.();
    return tags;
  };
}