flare-redact 1.6.1 → 1.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/README.md +99 -6
  3. package/SECURITY.md +5 -0
  4. package/bench/entities-cases.json +154 -0
  5. package/bench/entities.mjs +151 -0
  6. package/dist/checksums.d.ts +13 -0
  7. package/dist/checksums.d.ts.map +1 -1
  8. package/dist/checksums.js +38 -1
  9. package/dist/checksums.js.map +1 -1
  10. package/dist/cli.d.ts.map +1 -1
  11. package/dist/cli.js +8 -0
  12. package/dist/cli.js.map +1 -1
  13. package/dist/detectors.d.ts.map +1 -1
  14. package/dist/detectors.js +7 -2
  15. package/dist/detectors.js.map +1 -1
  16. package/dist/engine.d.ts +30 -0
  17. package/dist/engine.d.ts.map +1 -1
  18. package/dist/engine.js +56 -1
  19. package/dist/engine.js.map +1 -1
  20. package/dist/entities.d.ts +36 -0
  21. package/dist/entities.d.ts.map +1 -0
  22. package/dist/entities.js +897 -0
  23. package/dist/entities.js.map +1 -0
  24. package/dist/entity-lexicon.d.ts +11 -0
  25. package/dist/entity-lexicon.d.ts.map +1 -0
  26. package/dist/entity-lexicon.js +202 -0
  27. package/dist/entity-lexicon.js.map +1 -0
  28. package/dist/gateway/cli.d.ts +1 -1
  29. package/dist/gateway/cli.d.ts.map +1 -1
  30. package/dist/gateway/cli.js +4 -0
  31. package/dist/gateway/cli.js.map +1 -1
  32. package/dist/gateway/config.d.ts.map +1 -1
  33. package/dist/gateway/config.js +11 -0
  34. package/dist/gateway/config.js.map +1 -1
  35. package/dist/gateway/server.d.ts.map +1 -1
  36. package/dist/gateway/server.js +7 -0
  37. package/dist/gateway/server.js.map +1 -1
  38. package/dist/help.d.ts +1 -1
  39. package/dist/help.d.ts.map +1 -1
  40. package/dist/help.js +12 -2
  41. package/dist/help.js.map +1 -1
  42. package/dist/index.d.ts +3 -2
  43. package/dist/index.d.ts.map +1 -1
  44. package/dist/index.js +2 -1
  45. package/dist/index.js.map +1 -1
  46. package/dist/init.d.ts +35 -0
  47. package/dist/init.d.ts.map +1 -0
  48. package/dist/init.js +183 -0
  49. package/dist/init.js.map +1 -0
  50. package/dist/locales.d.ts.map +1 -1
  51. package/dist/locales.js +10 -5
  52. package/dist/locales.js.map +1 -1
  53. package/dist/stream.d.ts.map +1 -1
  54. package/dist/stream.js +6 -3
  55. package/dist/stream.js.map +1 -1
  56. package/dist/transforms.d.ts.map +1 -1
  57. package/dist/transforms.js +5 -2
  58. package/dist/transforms.js.map +1 -1
  59. package/package.json +8 -1
  60. package/spec/SPEC.md +10 -4
  61. package/spec/conformance/cases.json +12 -0
  62. package/spec/conformance/expected.json +176 -0
  63. package/spec/detectors.json +7 -7
package/CHANGELOG.md CHANGED
@@ -1,5 +1,69 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.8.0 (2026-11-14)
4
+
5
+ ### Simpler setup
6
+
7
+ - Add presets, so a caller names a goal instead of a list of tags:
8
+ `logs` (defaults plus phone numbers), `llm` (every personal identifier plus
9
+ the `entities` recogniser), `gdpr` (`llm` plus network, device and wallet
10
+ identifiers) and `strict` (every detector). `redact(text, { preset: 'llm' })`,
11
+ `--preset` on the CLI and the gateway, and `FLARE_REDACT_PRESET`. `enable`
12
+ and `disable` apply on top and `only` ignores a preset. An unknown name throws
13
+ `ERR_UNKNOWN_PRESET`; the gateway refuses one at startup and answers a client
14
+ that sends one with HTTP 400.
15
+ - Add `flare-redact init`. It reads `package.json`, prints a ready-to-paste
16
+ step for each library it recognises (openai, `@anthropic-ai/sdk`, pino,
17
+ winston, express, with console as the fallback) and never edits source
18
+ files. `--ci` writes a GitHub workflow that runs `flare-redact --scan` on
19
+ every pull request, and keeps an existing one unless `--force` is given.
20
+ - Export `PRESETS` and the `Preset` type.
21
+
22
+ No existing option changed meaning; code without `preset` behaves as before.
23
+
24
+ ## 1.7.0 (2026-11-06)
25
+
26
+ ### Security: printed values and broken PEM blocks (GHSA-2jx3-6xv8-798v)
27
+
28
+ - IBANs printed in groups of four (`GB82 WEST 1234 5698 7654 32`) are masked by
29
+ the default policy. Groups may be separated by spaces, no-break spaces, thin
30
+ spaces or narrow no-break spaces. The match stops at each country's registry
31
+ length, so a currency code or BIC after the number is left alone, and the
32
+ check digits are still validated.
33
+ - US SSNs, Brazilian CPFs and German tax IDs written with spaces are masked like
34
+ their compact forms.
35
+ - A private key whose END footer is missing or carries another label is masked
36
+ through that footer, or to the end of the input when no footer follows. Before,
37
+ such a block passed through unmasked. `redactStream()` buffers it the same way.
38
+ - The fixes ship in all four engines (Node, Python, Go and Rust) and in the FRS-1
39
+ pack, which moves to version 1.7.0, with new conformance cases. Thanks to
40
+ roshcompanylabs for the report.
41
+
42
+ ### Free-text PII without a model
43
+
44
+ - Add `enable: ['entities']` (or `entities: true`): a model-free recogniser for
45
+ `private_person`, `private_address`, `private_phone`, `private_date`,
46
+ `account_number`, `private_handle`, `private_url` and `secret`, the label set
47
+ of OpenAI's privacy-filter. It combines cue phrases in the 24 library
48
+ languages, name lists, address, phone and date shapes, context scoring and
49
+ propagation to later mentions of a name.
50
+ - Add `recognizeEntities()`, `createEntityRecognizer()`, `ENTITY_LABELS` and the
51
+ `flare-redact/entities` subpath. The labels are ordinary detectors, so
52
+ `disable`, `only`, vaults, every replacement mode, streams, the CLI and the
53
+ gateway take them.
54
+ - Add `npm run benchmark:entities` and a hand-labelled corpus. On a holdout
55
+ written after tuning stopped, the first run reached 84.1% F1 with 12.0% of PII
56
+ characters left visible, against 35.1% F1 and 67.4% for the regex detectors
57
+ alone.
58
+ - Every pattern is bounded; 200,000-character hostile inputs finish in
59
+ milliseconds and the suite checks it.
60
+
61
+ ### Fixes
62
+
63
+ - The label-only `person_name` detector no longer runs across a line break:
64
+ `Name: Fatima Haddad` followed by `Address: ...` used to take
65
+ `Fatima Haddad\nAddress`. Fixed in all four engines.
66
+
3
67
  ## 1.6.1 — 2026-08-09
4
68
 
5
69
  ### NeMo Guardrails interoperability
package/README.md CHANGED
@@ -15,7 +15,7 @@
15
15
  <img src="https://img.shields.io/npm/types/flare-redact.svg" alt="TypeScript">
16
16
  <img src="https://img.shields.io/badge/dependencies-0-brightgreen" alt="Zero dependencies">
17
17
  <img src="https://img.shields.io/badge/languages-24-4f46e5" alt="24 languages">
18
- <img src="https://img.shields.io/badge/detectors-82-4f46e5" alt="82 detectors">
18
+ <img src="https://img.shields.io/badge/detectors-90-4f46e5" alt="90 detectors">
19
19
  <img src="https://img.shields.io/badge/runtime-node%20%7C%20browser%20%7C%20edge-blue" alt="Runtimes">
20
20
  </p>
21
21
 
@@ -78,6 +78,7 @@ Nothing to configure. No list of field paths to maintain. No native build step.
78
78
  - [Redact prompts before they reach an LLM](#redact-prompts-before-they-reach-an-llm)
79
79
  - [Ways to hide a value](#ways-to-hide-a-value)
80
80
  - [Reversible redaction](#reversible-redaction)
81
+ - [Free-text PII without a model](#free-text-pii-without-a-model)
81
82
  - [Contextual and model-assisted PII](#contextual-and-model-assisted-pii)
82
83
  - [Learned confidence, fewer false positives](#learned-confidence-fewer-false-positives)
83
84
  - [Build a private chat app](#build-a-private-chat-app)
@@ -110,6 +111,40 @@ Upgrading from `0.9.x`? Read the [`1.0 migration guide`](MIGRATION.md). Existing
110
111
  projects are not forced across the major version; upgrade explicitly with
111
112
  `npm install flare-redact@^1.0.0`.
112
113
 
114
+ ### Set up in one command
115
+
116
+ ```bash
117
+ npx flare-redact init # the lines to paste for openai, @anthropic-ai/sdk, pino, winston, express
118
+ npx flare-redact init --ci # also writes .github/workflows/flare-redact.yml
119
+ ```
120
+
121
+ `init` reads `package.json`, prints one ready-to-paste step per library it
122
+ recognises (console when there is no logger), and never edits source files.
123
+ `--ci` adds a workflow that runs `flare-redact --scan` on every pull request.
124
+
125
+ ### Presets
126
+
127
+ Pick a goal instead of a list of detector tags:
128
+
129
+ | Preset | Adds to the defaults |
130
+ |---|---|
131
+ | `logs` | phone numbers |
132
+ | `llm` | every personal identifier (`pii`) plus names, addresses and other PII in prose (`entities`) |
133
+ | `gdpr` | `llm` plus IP and MAC addresses, coordinates, VINs and wallet addresses |
134
+ | `strict` | every detector, `high_entropy` included |
135
+
136
+ ```js
137
+ redact(text, { preset: 'llm' });
138
+ const openai = wrapOpenAI(new OpenAI(), { preset: 'llm' });
139
+ const log = pino(pinoRedact({ preset: 'logs' }));
140
+ ```
141
+
142
+ The CLI takes `--preset gdpr`, the gateway `--preset` or `FLARE_REDACT_PRESET`.
143
+ `enable` and `disable` apply on top of a preset and `only` ignores it. An unknown
144
+ name throws `ERR_UNKNOWN_PRESET` instead of quietly redacting less. Presets belong
145
+ to the Node package, the CLI and the gateway; the Python, Go and Rust clients
146
+ reach them through the gateway.
147
+
113
148
  ### React and the browser
114
149
 
115
150
  The core is plain ESM with no Node built-ins, is tree-shakeable
@@ -176,8 +211,8 @@ dependencies of any kind.
176
211
  | | Install | Docs |
177
212
  |---|---|---|
178
213
  | **Go** | `go get github.com/flare-collection/flare-redact/sdk/go` | [`sdk/go`](sdk/go) |
179
- | **Python** | `pip install "flare-redact @ git+https://github.com/flare-collection/flare-redact@v1.6.1#subdirectory=sdk/python"` | [`sdk/python`](sdk/python) |
180
- | **Rust** | `flare-redact = { git = "https://github.com/flare-collection/flare-redact", tag = "v1.6.1" }` | [`sdk/rust`](sdk/rust) |
214
+ | **Python** | `pip install "flare-redact @ git+https://github.com/flare-collection/flare-redact@v1.8.0#subdirectory=sdk/python"` | [`sdk/python`](sdk/python) |
215
+ | **Rust** | `flare-redact = { git = "https://github.com/flare-collection/flare-redact", tag = "v1.8.0" }` | [`sdk/rust`](sdk/rust) |
181
216
 
182
217
  The Python and Rust engines are not published to PyPI and crates.io yet, so they
183
218
  install from this repository. The commands above are the ones that work today.
@@ -455,6 +490,61 @@ flare-redact --vault session.vault.json < input.txt > safe.txt
455
490
  flare-redact --restore session.vault.json < safe.txt > restored.txt
456
491
  ```
457
492
 
493
+ ## Free-text PII without a model
494
+
495
+ Masking models published on Hugging Face, such as OpenAI's privacy-filter, find
496
+ people, addresses and dates in prose. They also mean a model download, a runtime
497
+ and a slow CPU path. `entities` gets close to what they do with no model at all:
498
+ cue phrases in the 24 library languages ("my name is", "ich heiße", "меня зовут",
499
+ "我叫"), name lists, address, phone and date shapes, context scoring, and later
500
+ mentions of a name already found ("Alice Johnson ... Alice said").
501
+
502
+ ```js
503
+ import { redact, recognizeEntities } from 'flare-redact';
504
+
505
+ redact(
506
+ 'Hi, my name is Alice Johnson and I live at 221B Baker Street, London NW1 6XE. Call me at 415-555-0132.',
507
+ { enable: ['entities'] },
508
+ );
509
+ // 'Hi, my name is [REDACTED PERSON] and I live at [REDACTED ADDRESS]. Call me at [REDACTED PHONE].'
510
+
511
+ redact('我的名字是李华,住在北京市朝阳区建国路88号。', { enable: ['entities'] });
512
+ // '我的名字是[REDACTED PERSON],住在[REDACTED ADDRESS]。'
513
+
514
+ recognizeEntities('Patient: Maria García, DOB: 03/04/1985, MRN 00482913.');
515
+ // private_person 'Maria García' (0.99), private_date '03/04/1985' (0.95),
516
+ // account_number '00482913' (0.86)
517
+ ```
518
+
519
+ | Label | Finds |
520
+ |---|---|
521
+ | `private_person` | names after introductions, form labels, titles, greetings, sign-offs and email headers, plus known names in running text |
522
+ | `private_address` | street addresses in Latin, Cyrillic, Chinese, Japanese and Korean formats, PO boxes, postcode lines |
523
+ | `private_phone` | numbers after a phone cue, international numbers, North American numbers |
524
+ | `private_date` | birth dates and dates tied to a person (admission, discharge, appointment) |
525
+ | `account_number` | customer, policy, passport, patient, employee and other IDs that only their label identifies |
526
+ | `private_handle` | `@handles` and usernames |
527
+ | `private_url` | profile links, and URLs whose query carries an email, name or token |
528
+ | `secret` | passwords, PINs and one-time codes written in a sentence |
529
+
530
+ The labels are the privacy-filter ones, so the outputs can be compared or swapped.
531
+ They are ordinary detectors: `disable: ['private_url']` drops one,
532
+ `entities: { labels: ['private_person'], minConfidence: 0.7, propagate: false }`
533
+ tunes the recogniser, and vaults, `surrogate` mode, streams, the CLI
534
+ (`--enable entities`) and the gateway all take them. `createEntityRecognizer()`
535
+ from `flare-redact/entities` returns the same recogniser as a `semanticProvider`.
536
+
537
+ On the hand-labelled corpus in [`bench/entities-cases.json`](bench/entities-cases.json)
538
+ (`npm run benchmark:entities`), the holdout of 57 lines was written after tuning
539
+ stopped. On its first run the regex detectors alone, with every PII detector
540
+ switched on, reached 35.1% F1 and left 67.4% of the PII characters visible. With
541
+ `entities` it reached 84.1% F1 with 12.0% left visible and 1.4% of the clean text
542
+ masked. The corpus is small and synthetic, so read it as a regression signal and
543
+ not as a comparison with published model scores. A trained model still does
544
+ better on names with no cue and no match in the name lists, on unusual address
545
+ formats and on languages outside the 24. When you need that, plug one in through
546
+ `semanticProvider`.
547
+
458
548
  ## Contextual and model-assisted PII
459
549
 
460
550
  Structured identifiers and credentials are best handled by deterministic rules
@@ -867,7 +957,7 @@ machine-readable JSON and SARIF reports never echo the matched secret value:
867
957
  with:
868
958
  node-version: 24
869
959
  - name: Scan project text files
870
- run: npx --yes --package flare-redact@1.6.1 flare-redact --scan . --exclude package-lock.json
960
+ run: npx --yes --package flare-redact@1.8.0 flare-redact --scan . --exclude package-lock.json
871
961
  ```
872
962
 
873
963
  The scan runs on the GitHub runner, reports safe file and source locations, and
@@ -971,6 +1061,7 @@ Opt in with `enable`:
971
1061
  | `finance` | SWIFT/BIC, US ABA routing numbers |
972
1062
  | `vehicle` | VINs (checksum-validated) |
973
1063
  | `network` | IPs, MAC addresses, coordinates, internal URLs |
1064
+ | `entities` | people, addresses, phones, personal dates, account numbers, handles, personal URLs and secrets in prose, without a model ([details](#free-text-pii-without-a-model)) |
974
1065
  | `phone` | E.164 and formatted national numbers (`+90 532 123 45 67`, `(555) 123-4567`, `0532 123 45 67`) — digit-count validated, date-safe |
975
1066
 
976
1067
  Plus object values whose **key name** is sensitive (`password`, `token`,
@@ -1146,8 +1237,10 @@ npm run benchmark:adversarial
1146
1237
  - The legacy `createToolBoundary()` restores every placeholder in its shared
1147
1238
  vault. Use `createScopedToolBoundary()` whenever more than one tool or trust
1148
1239
  domain can receive model-produced arguments.
1149
- - The 24-language badge describes secret-key vocabulary, not general multilingual
1150
- named-entity recognition. Use a local `semanticProvider` for that task.
1240
+ - The 24-language badge describes secret-key vocabulary and the cue words of the
1241
+ `entities` recogniser. That recogniser uses rules and name lists, not a trained
1242
+ model: a name with no cue and no list match is missed. Use a local
1243
+ `semanticProvider` when you need model-level recall.
1151
1244
 
1152
1245
  Encrypted vaults do not protect a compromised host or secrets already resident
1153
1246
  in process memory. Deterministic transforms reveal when two inputs are equal.
package/SECURITY.md CHANGED
@@ -25,6 +25,11 @@ untrusted code running in the same process, or keys already present in process
25
25
  memory. Restoring a placeholder intentionally reveals its original value, and
26
26
  deterministic transforms intentionally reveal equality between matching inputs.
27
27
 
28
+ The `entities` recogniser finds names, addresses and other free-text PII with
29
+ rules and name lists, not a trained model. A miss on a name with no cue is a known
30
+ limit, not a vulnerability. A recogniser pattern that backtracks, or a cue that
31
+ leaves part of a value visible after the label it promises to mask, is in scope.
32
+
28
33
  `scan()` omits matched values by default. Enabling `includeValues` is an explicit
29
34
  confidentiality tradeoff: those findings must not be logged or exported. HTTP
30
35
  redaction covers only the returned snapshot, never the live request. Tool and LLM
@@ -0,0 +1,154 @@
1
+ {
2
+ "description": "Hand-labelled synthetic text for the entity recogniser. Every name, number and address is invented. [[label|text]] marks a gold span; everything else must stay unmasked. The dev split was used while tuning (it includes the first holdout, folded in after its errors were studied). The holdout split was written on 2026-11-06 after tuning stopped, and its first score is the one reported.",
3
+ "dev": [
4
+ "Hi, my name is [[private_person|Alice Johnson]] and I live at [[private_address|221B Baker Street, London NW1 6XE]].",
5
+ "Call me at [[private_phone|415-555-0132]] after 6pm.",
6
+ "Patient: [[private_person|Maria García]], DOB: [[private_date|03/04/1985]], MRN [[account_number|00482913]].",
7
+ "Admitted on [[private_date|12 March 2024]] and seen by Dr. [[private_person|Rajesh Patel]].",
8
+ "Please ship to [[private_address|1600 Amphitheatre Parkway, Mountain View, CA 94043]].",
9
+ "My customer number is [[account_number|CX-55821-7]] and my policy number is [[account_number|PLC-2024-88812]].",
10
+ "[[private_person|Tom Becker]] said the invoice was paid. Later [[private_person|Tom]] called back from [[private_phone|+44 20 7946 0958]].",
11
+ "Hallo, ich heiße [[private_person|Jürgen Müller]] und wohne in der [[private_address|Hauptstraße 5, 10115 Berlin]].",
12
+ "Geburtsdatum: [[private_date|3. März 1979]].",
13
+ "Salam, mənim adım [[private_person|Nigar Əliyeva]]. Ünvan: [[private_address|Nizami küçəsi 25, Bakı]].",
14
+ "Telefon: [[private_phone|+994 50 123 45 67]].",
15
+ "my password is [[secret|hunter2]] and the wifi password is \"[[secret|Sunsh1ne!]]\".",
16
+ "Follow me on Instagram: [[private_handle|@alice_codes]] or [[private_url|https://www.linkedin.com/in/alice-johnson-1234]]",
17
+ "Passport no. [[account_number|X1234567]], card ending in [[account_number|4242]].",
18
+ "Regards,\n[[private_person|Grace Hopper]]",
19
+ "Dear [[private_person|Ahmed]],\nyour appointment on [[private_date|5 June 2025]] is confirmed.",
20
+ "Je m'appelle [[private_person|Camille Lefèvre]], j'habite au [[private_address|12 rue de la Paix, 75002 Paris]].",
21
+ "Me llamo [[private_person|Lucía Fernández]] y mi teléfono es [[private_phone|612 345 678]].",
22
+ "From: [[private_person|Daniel Kowalski]] <dk@example.org>",
23
+ "The verification code is [[secret|482913]].",
24
+ "Username: [[private_handle|dark_knight77]]",
25
+ "Spoke with [[private_person|Emily Clarke]] about the refund.",
26
+ "Mi chiamo [[private_person|Giulia Rossi]] e abito in [[private_address|Via Roma 10, 00184 Roma]].",
27
+ "Меня зовут [[private_person|Ольга Петрова]], дата рождения [[private_date|12.05.1990]].",
28
+ "我叫[[private_person|王小明]],电话:[[private_phone|13812345678]]。",
29
+ "Mijn naam is [[private_person|Sanne de Vries]] en ik woon op [[private_address|Kalverstraat 12, 1012 AB Amsterdam]].",
30
+ "Benim adım [[private_person|Ayşe Yılmaz]], doğum tarihi [[private_date|14.02.1992]].",
31
+ "Contact person: [[private_person|Kenji Watanabe]], mobile [[private_phone|090-1234-5678]].",
32
+ "Employee ID [[account_number|E-449120]] belongs to [[private_person|Priya Sharma]].",
33
+ "Send the documents to [[private_address|P.O. Box 4471, Austin, TX 78765]].",
34
+ "We deployed version 2.3.1 to Production Cluster on Monday.",
35
+ "Order #48213 shipped via UPS 3 days later.",
36
+ "The Machine Learning team met in New York last week.",
37
+ "Google released Gemini and Microsoft updated Copilot.",
38
+ "IP address 10.0.0.1 resolved to the staging host.",
39
+ "Spring 2024 roadmap: faster builds, fewer flaky tests.",
40
+ "The password is incorrect, please try again.",
41
+ "Invoice INV-2024-0042 is due on 2024-12-31.",
42
+ "Route 66 is a famous highway.",
43
+ "@Override\npublic String toString() { return name; }",
44
+ "name: api-gateway\nreplicas: 3",
45
+ "See page 12, line 4 of the report.",
46
+ "Meeting at 10:30 in Room 4B with the Data Platform group.",
47
+ "Ticket 55821 was closed by the on-call bot.",
48
+ "The Bank of England raised rates on 2 November 2023.",
49
+ "Hey team, quick note: [[private_person|Marcus Webb]] will cover support this weekend.",
50
+ "Name: [[private_person|Fatima Haddad]]\nAddress: [[private_address|48 Elm Grove, Leeds LS6 2AB]]\nPhone: [[private_phone|07700 900461]]",
51
+ "I was born on [[private_date|July 4, 1988]] in Ohio.",
52
+ "Her date of birth is [[private_date|1979-11-23]].",
53
+ "Can you text me on [[private_phone|(212) 555-0187]]?",
54
+ "My account number is [[account_number|00417 22839]] at the credit union.",
55
+ "Driver's license: [[account_number|D1234-56789-01234]]",
56
+ "Thanks,\n[[private_person|Oliver Bennett]]",
57
+ "Please contact Mrs. [[private_person|Helen Carter]] regarding the lease.",
58
+ "The tenant [[private_person|Jacob Miller]] moved to [[private_address|742 Evergreen Terrace, Springfield, IL 62704]].",
59
+ "Ich heiße [[private_person|Lena Schmidt]], meine Telefonnummer ist [[private_phone|0151 23456789]].",
60
+ "Mon nom est [[private_person|Hugo Martin]] et ma date de naissance est le [[private_date|2 avril 1995]].",
61
+ "Meu nome é [[private_person|João Silva]] e moro na [[private_address|Rua Augusta, 120, São Paulo]].",
62
+ "Nazywam się [[private_person|Piotr Nowak]], mieszkam przy [[private_address|ul. Marszałkowska 10, 00-001 Warszawa]].",
63
+ "Mənim adım [[private_person|Rəşad Quliyev]], telefon nömrəsi [[private_phone|+994 55 987 65 43]].",
64
+ "Мене звати [[private_person|Андрій Шевченко]].",
65
+ "私の名前は[[private_person|田中太郎]]です。",
66
+ "The OTP is [[secret|739104]], do not share it.",
67
+ "Wi-Fi password: [[secret|Blue-Harbor-2291]]",
68
+ "Find me on twitter [[private_handle|@jsmith_dev]].",
69
+ "Profile: [[private_url|https://instagram.com/lucia.travels]]",
70
+ "Reset link: [[private_url|https://example.com/reset?email=anna%40example.com&token=9f8e7d]]",
71
+ "Medical record number: [[account_number|MRN-7731-0042]]",
72
+ "Discharged on [[private_date|18/09/2024]] after observation.",
73
+ "[[private_person|Sarah Thompson]] emailed the landlord yesterday; [[private_person|Sarah]] has not heard back.",
74
+ "Kind regards,\n[[private_person|Wei Zhang]]",
75
+ "Hola [[private_person|Diego]], tu número de cliente es [[account_number|884213]].",
76
+ "Ship to: [[private_address|15 Rue Victor Hugo, 69002 Lyon]]",
77
+ "Il paziente [[private_person|Marco Bianchi]], nato il [[private_date|8 maggio 1962]], è stato ricoverato.",
78
+ "Mein Name ist [[private_person|Felix Wagner]], ich wohne in der [[private_address|Lindenallee 7, 50968 Köln]].",
79
+ "The quarterly report covers Europe, Asia and Latin America.",
80
+ "Download Python 3.12 from the official site.",
81
+ "Our office is closed on Christmas Day.",
82
+ "Build 4471 failed on the Windows runner.",
83
+ "The meeting with Acme Corp is on Thursday.",
84
+ "Version 1.6.1 fixed the stream redactor.",
85
+ "Use the @param tag to document arguments.",
86
+ "Order number 99812 will arrive in 3 to 5 business days.",
87
+ "The server listens on port 8080 at address 0.0.0.0.",
88
+ "Machine Learning Engineer, Remote, Full Time.",
89
+ "Please reset your password if it has expired.",
90
+ "Population of Berlin: 3,850,809 (2023).",
91
+ "Call the front desk to book Room 12.",
92
+ "Paris and London are both expensive in summer.",
93
+ "The New York Times published the story on March 3, 2024."
94
+ ],
95
+ "holdout": [
96
+ "Good morning, this is [[private_person|Rachel Adams]] from accounting.",
97
+ "Please forward the contract to [[private_person|Michael O'Brien]] before Friday.",
98
+ "Applicant: [[private_person|Samuel Okafor]]\nDate of birth: [[private_date|22/01/1991]]\nPhone: [[private_phone|+234 803 123 4567]]",
99
+ "She lives at [[private_address|19 Maple Avenue, Toronto, ON M4B 1B3]].",
100
+ "You can reach Dr. [[private_person|Anika Rao]] on [[private_phone|020 7123 4567]].",
101
+ "My IBAN is [[account_number|DE89 3704 0044 0532 0130 00]].",
102
+ "Social security number: [[account_number|123-45-6789]]",
103
+ "Best,\n[[private_person|Laura Kim]]",
104
+ "Cheers,\n[[private_person|Ben]]",
105
+ "Hi [[private_person|Olivia]], your order has shipped.",
106
+ "Ich bin [[private_person|Katrin Hoffmann]] und meine Adresse ist [[private_address|Gartenweg 3, 80331 München]].",
107
+ "Soy [[private_person|Carlos Ruiz]], vivo en [[private_address|Calle Mayor 15, 28013 Madrid]].",
108
+ "Je suis né le [[private_date|14 juillet 1983]] à Lyon.",
109
+ "Il mio numero di telefono è [[private_phone|333 123 4567]].",
110
+ "Meu telefone é [[private_phone|(11) 91234-5678]].",
111
+ "Mój numer telefonu to [[private_phone|601 234 567]].",
112
+ "Benim telefon numaram [[private_phone|0532 123 45 67]].",
113
+ "Мой телефон: [[private_phone|+7 916 123-45-67]].",
114
+ "我的名字是[[private_person|李华]],住在[[private_address|北京市朝阳区建国路88号]]。",
115
+ "저는 [[private_person|김민준]]입니다.",
116
+ "مرحبا، اسمي [[private_person|أحمد علي]].",
117
+ "मेरा नाम [[private_person|राहुल शर्मा]] है।",
118
+ "Tax ID: [[account_number|98-7654321]]",
119
+ "Your one-time password is [[secret|551907]].",
120
+ "db_password = \"[[secret|Tr0ub4dor&3]]\"",
121
+ "GitHub: [[private_url|https://github.com/marta-dev]]",
122
+ "DM me on telegram [[private_handle|@nikos_k]].",
123
+ "Membership number: [[account_number|M-20931-44]]",
124
+ "Appointment confirmed for [[private_person|Thomas Lee]] on [[private_date|3 October 2025]].",
125
+ "The customer, [[private_person|Hannah Fischer]], asked for a refund.",
126
+ "Signed: [[private_person|Robert Chen]]",
127
+ "Emergency contact: [[private_person|Maya Singh]], [[private_phone|+1 (646) 555-0199]]",
128
+ "Card number [[account_number|4111 1111 1111 1111]] was declined.",
129
+ "Mi dirección es [[private_address|Avenida de la Constitución 22, 41001 Sevilla]].",
130
+ "Adres: [[private_address|ul. Długa 5, 80-831 Gdańsk]]",
131
+ "I'm [[private_person|Jake]] by the way.",
132
+ "[[private_person|Isabel Moreno]] opened the ticket. Support replied to [[private_person|Isabel]] within an hour.",
133
+ "To: [[private_person|Grace Liu]] <grace.liu@example.com>",
134
+ "Amazon Web Services announced new regions in Paris and Tokyo.",
135
+ "Run npm install and then npm test.",
136
+ "The function returns null when the key is missing.",
137
+ "Mercedes and BMW reported strong sales in March 2024.",
138
+ "Room 101 is reserved for the Finance Committee.",
139
+ "Error 404: page not found.",
140
+ "The Eiffel Tower is 330 metres tall.",
141
+ "Set MAX_RETRIES to 5 in the config file.",
142
+ "Chapter 7 explains gradient descent.",
143
+ "The Lincoln Memorial attracts millions of visitors.",
144
+ "Download the report from https://example.com/reports/2024.pdf.",
145
+ "Total: 1,249.99 EUR including VAT.",
146
+ "Team Alpha beat Team Bravo 3-1 on Sunday.",
147
+ "SELECT name, email FROM users WHERE id = 42;",
148
+ "Jordan is a country in the Middle East.",
149
+ "Phone support is available from 9 to 5.",
150
+ "The password field must contain at least 12 characters.",
151
+ "The meeting notes are in the Product Strategy folder.",
152
+ "version: 3.8\nservices:\n web:\n image: nginx:1.25"
153
+ ]
154
+ }
@@ -0,0 +1,151 @@
1
+ // Entity recognition quality on hand-labelled text.
2
+ //
3
+ // npm run benchmark:entities # table
4
+ // npm run benchmark:entities -- --json # machine-readable
5
+ //
6
+ // Compares the regex detectors alone (every PII detector switched on, the best
7
+ // the library could do before the recogniser) against the same detectors plus
8
+ // `entities`. Reports typed exact-span and overlap F1 per label, the share of
9
+ // gold PII characters left unmasked (leak), and the share of clean characters
10
+ // masked (over-redaction). The corpus is small and synthetic; read the numbers
11
+ // as a regression signal, not as a comparison with published model scores.
12
+
13
+ import { readFileSync } from 'node:fs';
14
+ import { performance } from 'node:perf_hooks';
15
+ import { scan } from '../dist/index.js';
16
+
17
+ const corpus = JSON.parse(readFileSync(new URL('./entities-cases.json', import.meta.url), 'utf8'));
18
+ const asJson = process.argv.includes('--json');
19
+
20
+ /** Map the regex detectors onto the recogniser's label set. */
21
+ const LABEL_OF = {
22
+ person_name: 'private_person',
23
+ street_address: 'private_address',
24
+ date_of_birth: 'private_date',
25
+ phone: 'private_phone',
26
+ generic_assignment: 'secret',
27
+ credit_card: 'account_number',
28
+ iban: 'account_number',
29
+ us_ssn: 'account_number',
30
+ };
31
+
32
+ const LABELS = [
33
+ 'private_person', 'private_address', 'private_phone', 'private_date',
34
+ 'account_number', 'private_handle', 'private_url', 'secret',
35
+ ];
36
+
37
+ /** generic_assignment reports `password: x` but masks only `x`; score the part it masks. */
38
+ function valueSpan(text, f) {
39
+ if (f.detector !== 'generic_assignment') return { start: f.start, end: f.end };
40
+ const m = /[:=]\s*["']?/.exec(text.slice(f.start, f.end));
41
+ return m ? { start: f.start + m.index + m[0].length, end: f.end - (/["']$/.test(text.slice(f.start, f.end)) ? 1 : 0) } : { start: f.start, end: f.end };
42
+ }
43
+
44
+ function parse(line) {
45
+ let text = '';
46
+ const gold = [];
47
+ const re = /\[\[([a-z_]+)\|([\s\S]*?)\]\]/g;
48
+ let last = 0;
49
+ let m;
50
+ while ((m = re.exec(line)) !== null) {
51
+ text += line.slice(last, m.index);
52
+ gold.push({ label: m[1], start: text.length, end: text.length + m[2].length });
53
+ text += m[2];
54
+ last = m.index + m[0].length;
55
+ }
56
+ return { text: text + line.slice(last), gold };
57
+ }
58
+
59
+ const SYSTEMS = {
60
+ 'regex detectors': { enable: ['pii', 'contextual', 'phone'] },
61
+ 'regex + entities': { enable: ['pii', 'contextual', 'phone', 'entities'] },
62
+ };
63
+
64
+ function evaluate(lines, options) {
65
+ const perLabel = Object.fromEntries(LABELS.map((l) => [l, { tp: 0, fp: 0, fn: 0, overlapTp: 0, overlapFn: 0 }]));
66
+ let goldChars = 0;
67
+ let leakedChars = 0;
68
+ let cleanChars = 0;
69
+ let overMasked = 0;
70
+ let ms = 0;
71
+ for (const line of lines) {
72
+ const { text, gold } = parse(line);
73
+ const started = performance.now();
74
+ const found = scan(text, options)
75
+ .filter((f) => f.detector !== 'email')
76
+ .map((f) => ({ label: LABEL_OF[f.detector] ?? f.detector, ...valueSpan(text, f) }));
77
+ ms += performance.now() - started;
78
+
79
+ const masked = new Uint8Array(text.length);
80
+ for (const f of found) masked.fill(1, f.start, f.end);
81
+ const inGold = new Uint8Array(text.length);
82
+ for (const g of gold) {
83
+ inGold.fill(1, g.start, g.end);
84
+ goldChars += g.end - g.start;
85
+ for (let i = g.start; i < g.end; i++) if (!masked[i] && /\S/.test(text[i])) leakedChars++;
86
+ }
87
+ for (let i = 0; i < text.length; i++) {
88
+ if (inGold[i] || !/\S/.test(text[i])) continue;
89
+ cleanChars++;
90
+ if (masked[i]) overMasked++;
91
+ }
92
+
93
+ for (const g of gold) {
94
+ const stats = perLabel[g.label];
95
+ if (found.some((f) => f.label === g.label && f.start === g.start && f.end === g.end)) stats.tp++;
96
+ else stats.fn++;
97
+ if (found.some((f) => f.label === g.label && f.start < g.end && g.start < f.end)) stats.overlapTp++;
98
+ else stats.overlapFn++;
99
+ }
100
+ for (const f of found) {
101
+ const stats = perLabel[f.label];
102
+ if (!stats) continue;
103
+ if (!gold.some((g) => g.label === f.label && g.start === f.start && g.end === f.end)) stats.fp++;
104
+ }
105
+ }
106
+ const f1 = (tp, fp, fn) => (tp ? (2 * tp) / (2 * tp + fp + fn) : 0);
107
+ const labels = {};
108
+ let tp = 0, fp = 0, fn = 0;
109
+ for (const [label, s] of Object.entries(perLabel)) {
110
+ tp += s.tp; fp += s.fp; fn += s.fn;
111
+ const support = s.tp + s.fn;
112
+ if (!support && !s.fp) continue;
113
+ labels[label] = {
114
+ support,
115
+ precision: s.tp + s.fp ? s.tp / (s.tp + s.fp) : 0,
116
+ recall: support ? s.tp / support : 0,
117
+ f1: f1(s.tp, s.fp, s.fn),
118
+ overlapRecall: support ? s.overlapTp / support : 0,
119
+ };
120
+ }
121
+ return {
122
+ labels,
123
+ micro: { precision: tp + fp ? tp / (tp + fp) : 0, recall: tp + fn ? tp / (tp + fn) : 0, f1: f1(tp, fp, fn) },
124
+ leak: goldChars ? leakedChars / goldChars : 0,
125
+ overRedaction: cleanChars ? overMasked / cleanChars : 0,
126
+ msPerLine: ms / lines.length,
127
+ };
128
+ }
129
+
130
+ const results = {};
131
+ for (const split of ['dev', 'holdout']) {
132
+ results[split] = {};
133
+ for (const [name, options] of Object.entries(SYSTEMS)) results[split][name] = evaluate(corpus[split], options);
134
+ }
135
+
136
+ if (asJson) {
137
+ process.stdout.write(JSON.stringify({ schemaVersion: 1, results }, null, 2) + '\n');
138
+ } else {
139
+ const pct = (n) => `${(n * 100).toFixed(1)}%`.padStart(7);
140
+ for (const split of ['dev', 'holdout']) {
141
+ process.stdout.write(`\n${split} (${corpus[split].length} lines)\n`);
142
+ process.stdout.write(`${'system'.padEnd(18)} ${'P'.padStart(7)} ${'R'.padStart(7)} ${'F1'.padStart(7)} ${'leak'.padStart(7)} ${'over'.padStart(7)}\n`);
143
+ for (const [name, r] of Object.entries(results[split])) {
144
+ process.stdout.write(`${name.padEnd(18)} ${pct(r.micro.precision)} ${pct(r.micro.recall)} ${pct(r.micro.f1)} ${pct(r.leak)} ${pct(r.overRedaction)}\n`);
145
+ }
146
+ const best = results[split]['regex + entities'];
147
+ for (const [label, s] of Object.entries(best.labels)) {
148
+ process.stdout.write(` ${label.padEnd(16)} n=${String(s.support).padStart(2)} P ${pct(s.precision)} R ${pct(s.recall)} F1 ${pct(s.f1)} overlap R ${pct(s.overlapRecall)}\n`);
149
+ }
150
+ }
151
+ }
@@ -2,6 +2,19 @@
2
2
  export declare function luhnCheck(value: string): boolean;
3
3
  /** ISO 13616 IBAN check: rearrange, letters→numbers, mod 97 === 1. */
4
4
  export declare function ibanValid(value: string): boolean;
5
+ /**
6
+ * Total IBAN length per country: the SWIFT IBAN registry, then the countries
7
+ * that use the format without being in it. The compact form needs no table, but
8
+ * the printed form does: "BE68 5390 0754 7034 EUR" only stops before "EUR" if
9
+ * the pattern knows a Belgian IBAN ends after three groups.
10
+ */
11
+ export declare const IBAN_LENGTHS: Readonly<Record<string, number>>;
12
+ /**
13
+ * Pattern source for an IBAN in ISO 13616 print format: groups of four after
14
+ * the country and check digits, the last group shorter. `separator` is a
15
+ * character class; `digit` lets the FRS-1 pack spell `\d` as `[0-9]`.
16
+ */
17
+ export declare function ibanPrintedPattern(separator: string, digit?: string): string;
5
18
  /** Turkey T.C. Kimlik No — 11 digits, two check digits. */
6
19
  export declare function tcknValid(value: string): boolean;
7
20
  /** Brazil CPF — 11 digits, two mod-11 check digits. */
@@ -1 +1 @@
1
- {"version":3,"file":"checksums.d.ts","sourceRoot":"","sources":["../src/checksums.ts"],"names":[],"mappings":"AAEA,iFAAiF;AACjF,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAehD;AAED,sEAAsE;AACtE,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAYhD;AAED,2DAA2D;AAC3D,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAShD;AAED,uDAAuD;AACvD,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAU/C;AAGD,gEAAgE;AAChE,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAM/C;AAED,+DAA+D;AAC/D,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAO/C;AAED,uDAAuD;AACvD,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAOjD;AAED,uEAAuE;AACvE,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAWnD;AAED,+DAA+D;AAC/D,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAQ/C;AAED,8DAA8D;AAC9D,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAS/C;AAOD,kFAAkF;AAClF,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAY/C;AAED,sEAAsE;AACtE,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAQ/C;AAED,gFAAgF;AAChF,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CASjD;AAeD,qEAAqE;AACrE,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAQnD;AAGD,8DAA8D;AAC9D,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAM/C;AAID,uEAAuE;AACvE,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAMxD;AAED,gEAAgE;AAChE,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAWtD;AAOD,gEAAgE;AAChE,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAczD"}
1
+ {"version":3,"file":"checksums.d.ts","sourceRoot":"","sources":["../src/checksums.ts"],"names":[],"mappings":"AAEA,iFAAiF;AACjF,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAehD;AAED,sEAAsE;AACtE,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAYhD;AAED;;;;;GAKG;AACH,eAAO,MAAM,YAAY,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAazD,CAAC;AAEF;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,SAAS,EAAE,MAAM,EAAE,KAAK,SAAU,GAAG,MAAM,CAW7E;AAED,2DAA2D;AAC3D,wBAAgB,SAAS,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAShD;AAED,uDAAuD;AACvD,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAU/C;AAGD,gEAAgE;AAChE,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAM/C;AAED,+DAA+D;AAC/D,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAO/C;AAED,uDAAuD;AACvD,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAOjD;AAED,uEAAuE;AACvE,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAWnD;AAED,+DAA+D;AAC/D,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAQ/C;AAED,8DAA8D;AAC9D,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAS/C;AAOD,kFAAkF;AAClF,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAY/C;AAED,sEAAsE;AACtE,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAQ/C;AAED,gFAAgF;AAChF,wBAAgB,UAAU,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CASjD;AAeD,qEAAqE;AACrE,wBAAgB,YAAY,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAQnD;AAGD,8DAA8D;AAC9D,wBAAgB,QAAQ,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAM/C;AAID,uEAAuE;AACvE,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAMxD;AAED,gEAAgE;AAChE,wBAAgB,eAAe,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAWtD;AAOD,gEAAgE;AAChE,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAczD"}
package/dist/checksums.js CHANGED
@@ -33,6 +33,43 @@ export function ibanValid(value) {
33
33
  }
34
34
  return remainder === 1;
35
35
  }
36
+ /**
37
+ * Total IBAN length per country: the SWIFT IBAN registry, then the countries
38
+ * that use the format without being in it. The compact form needs no table, but
39
+ * the printed form does: "BE68 5390 0754 7034 EUR" only stops before "EUR" if
40
+ * the pattern knows a Belgian IBAN ends after three groups.
41
+ */
42
+ export const IBAN_LENGTHS = {
43
+ AD: 24, AE: 23, AL: 28, AT: 20, AZ: 28, BA: 20, BE: 16, BG: 22, BH: 22, BI: 27,
44
+ BR: 29, BY: 28, CH: 21, CR: 22, CY: 28, CZ: 24, DE: 22, DJ: 27, DK: 18, DO: 28,
45
+ EE: 20, EG: 29, ES: 24, FI: 18, FK: 18, FO: 18, FR: 27, GB: 22, GE: 22, GI: 23,
46
+ GL: 18, GR: 27, GT: 28, HN: 28, HR: 21, HU: 28, IE: 22, IL: 23, IQ: 23, IS: 26,
47
+ IT: 27, JO: 30, KW: 30, KZ: 20, LB: 28, LC: 32, LI: 21, LT: 20, LU: 20, LV: 21,
48
+ LY: 25, MC: 27, MD: 24, ME: 22, MK: 19, MN: 20, MR: 27, MT: 31, MU: 30, NI: 28,
49
+ NL: 18, NO: 15, OM: 23, PK: 24, PL: 28, PS: 29, PT: 25, QA: 29, RO: 24, RS: 22,
50
+ RU: 33, SA: 24, SC: 31, SD: 18, SE: 24, SI: 19, SK: 24, SM: 27, SO: 23, ST: 25,
51
+ SV: 28, TL: 23, TN: 24, TR: 26, UA: 29, VA: 22, VG: 24, XK: 20, YE: 30,
52
+ AO: 25, BF: 28, BJ: 28, CF: 27, CG: 27, CI: 28, CM: 27, CV: 25, DZ: 26, GA: 27,
53
+ GQ: 27, GW: 25, IR: 26, KM: 27, MA: 28, MG: 27, ML: 28, MZ: 25, NE: 28, SN: 28,
54
+ TD: 27, TG: 28,
55
+ };
56
+ /**
57
+ * Pattern source for an IBAN in ISO 13616 print format: groups of four after
58
+ * the country and check digits, the last group shorter. `separator` is a
59
+ * character class; `digit` lets the FRS-1 pack spell `\d` as `[0-9]`.
60
+ */
61
+ export function ibanPrintedPattern(separator, digit = '[0-9]') {
62
+ const byShape = new Map();
63
+ for (const [country, length] of Object.entries(IBAN_LENGTHS)) {
64
+ const groups = Math.floor((length - 4) / 4);
65
+ const tail = (length - 4) % 4;
66
+ const shape = `(?:${separator}[A-Z0-9]{4}){${groups}}` + (tail ? `${separator}[A-Z0-9]{${tail}}` : '');
67
+ const list = byShape.get(shape) ?? [];
68
+ list.push(country);
69
+ byShape.set(shape, list);
70
+ }
71
+ return [...byShape].map(([shape, countries]) => `(?:${countries.join('|')})${digit}{2}${shape}`).join('|');
72
+ }
36
73
  /** Turkey T.C. Kimlik No — 11 digits, two check digits. */
37
74
  export function tcknValid(value) {
38
75
  const d = onlyDigits(value);
@@ -156,7 +193,7 @@ export function vinValid(value) {
156
193
  }
157
194
  /** US SSN — no checksum exists, but whole ranges are never issued. */
158
195
  export function ssnValid(value) {
159
- const m = value.match(/^(\d{3})-?(\d{2})-?(\d{4})$/);
196
+ const m = value.match(/^(\d{3})[- ]?(\d{2})[- ]?(\d{4})$/);
160
197
  if (!m)
161
198
  return false;
162
199
  const area = Number(m[1]);