euredact 0.2.0 → 0.3.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.
@@ -1,15 +1,66 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.RuleEngine = void 0;
3
+ exports.RuleEngine = exports.COUNTRY_CODE_ALIASES = void 0;
4
+ exports.resolveCountryCode = resolveCountryCode;
4
5
  const types_js_1 = require("../types.js");
5
6
  const matchers_js_1 = require("./matchers.js");
6
7
  const suppressors_js_1 = require("./suppressors.js");
7
8
  const structural_js_1 = require("./structural.js");
8
9
  const index_js_1 = require("./countries/index.js");
10
+ /**
11
+ * Heuristic to detect nested quantifiers that cause catastrophic backtracking.
12
+ * After stripping escaped chars and character classes, look for an unbounded
13
+ * quantifier (+/*) closing a group that is itself quantified (+/*).
14
+ */
15
+ const NESTED_QUANTIFIER_RE = /[+*]\)[+*]/;
16
+ function validateCustomPattern(pattern) {
17
+ try {
18
+ new RegExp(pattern, "gu");
19
+ }
20
+ catch (e) {
21
+ throw new Error(`Invalid regex pattern: ${e instanceof Error ? e.message : e}`);
22
+ }
23
+ const stripped = pattern
24
+ .replace(/\\./g, "X")
25
+ .replace(/\[(?:[^\]\\]|\\.)*\]/g, "X");
26
+ if (NESTED_QUANTIFIER_RE.test(stripped)) {
27
+ throw new Error("Pattern contains nested quantifiers (e.g. (a+)+) which can cause " +
28
+ "catastrophic backtracking (ReDoS). Restructure the pattern to " +
29
+ "avoid quantifiers inside quantified groups.");
30
+ }
31
+ }
32
+ /**
33
+ * The country modules use the EU/VAT convention (UK, EL) while the public
34
+ * contract is ISO 3166-1 alpha-2 (GB, GR). Accept both spellings so a caller
35
+ * passing correct ISO codes is not punished for it.
36
+ */
37
+ exports.COUNTRY_CODE_ALIASES = {
38
+ GB: "UK",
39
+ GR: "EL",
40
+ UK: "UK",
41
+ EL: "EL",
42
+ };
43
+ /** Map a caller-supplied code to a registered one, or null if unknown. */
44
+ function resolveCountryCode(countryCode) {
45
+ let code = countryCode.trim().toUpperCase();
46
+ code = exports.COUNTRY_CODE_ALIASES[code] ?? code;
47
+ return code in index_js_1.COUNTRY_CONFIGS && code !== "SHARED" ? code : null;
48
+ }
49
+ const warnedCountries = new Set();
50
+ function warnUnknownCountry(code) {
51
+ if (warnedCountries.has(code))
52
+ return;
53
+ warnedCountries.add(code);
54
+ const available = Object.keys(index_js_1.COUNTRY_CONFIGS).filter(c => c !== "SHARED").sort();
55
+ console.warn(`[euredact] Unknown country code: ${JSON.stringify(code)}. Continuing with ` +
56
+ `shared country-independent patterns only (email, IBAN, international ` +
57
+ `phone, credit card, ...). Available: ${available.join(", ")}`);
58
+ }
9
59
  class RuleEngine {
10
60
  matcher = new matchers_js_1.MultiPatternMatcher();
11
61
  loadedCountries = new Set();
12
62
  addCustomPattern(name, pattern) {
63
+ validateCustomPattern(pattern);
13
64
  const pdef = {
14
65
  entityType: name, pattern, validator: null,
15
66
  description: "", contextKeywords: [], requiresContext: false,
@@ -25,7 +76,15 @@ class RuleEngine {
25
76
  else {
26
77
  configs = [];
27
78
  for (const c of countryCodes) {
28
- const code = c.toUpperCase();
79
+ const code = resolveCountryCode(c);
80
+ if (code === null) {
81
+ // Detection continues with the shared, country-independent
82
+ // patterns. Throwing on an unknown locale invites callers to wrap
83
+ // the call in try/catch and skip redaction — failing open, with
84
+ // unredacted PII in the output.
85
+ warnUnknownCountry(c);
86
+ continue;
87
+ }
29
88
  const config = index_js_1.COUNTRY_CONFIGS[code];
30
89
  if (config)
31
90
  configs.push(config);
@@ -47,38 +106,87 @@ class RuleEngine {
47
106
  }
48
107
  detect(text, countryCodes) {
49
108
  this.loadCountries(countryCodes);
50
- let rawMatches = this.matcher.scan(text);
109
+ // Scope the scan to requested countries for efficiency
110
+ // Resolve through the alias table so `countries: ["GB"]` actually scans
111
+ // the patterns registered under "UK".
112
+ let scanCodes = null;
51
113
  if (countryCodes !== null) {
52
- const codesUpper = new Set(countryCodes.map(c => c.toUpperCase()));
53
- rawMatches = rawMatches.filter(m => codesUpper.has(m.countryCode) || m.countryCode === "SHARED" || m.countryCode === "CUSTOM");
114
+ scanCodes = new Set();
115
+ for (const c of countryCodes) {
116
+ const code = resolveCountryCode(c);
117
+ if (code !== null)
118
+ scanCodes.add(code);
119
+ }
120
+ scanCodes.add("SHARED");
121
+ scanCodes.add("CUSTOM");
54
122
  }
123
+ let rawMatches = this.matcher.scan(text, scanCodes);
55
124
  // Matches that have a validator but fail it create suppression zones:
56
125
  // the span is recognisably a specific entity (e.g. IBAN-shaped) so
57
126
  // overlapping regex-only matches (license plate, phone) are false
58
127
  // positives and must be suppressed.
59
128
  const validated = [];
60
- const suppressionZones = [];
129
+ const rawZones = [];
61
130
  for (const m of rawMatches) {
62
- if (this.matcher.validate(m)) {
63
- validated.push(m);
131
+ const isValid = this.matcher.validate(m);
132
+ if (isValid) {
133
+ validated.push({ match: m, hasValidValidator: m.patternDef.validator !== null });
64
134
  }
65
135
  else if (m.patternDef.validator !== null && !m.patternDef.requiresContext) {
66
- suppressionZones.push([m.start, m.end]);
136
+ rawZones.push([m.start, m.end]);
137
+ }
138
+ }
139
+ // Merge overlapping suppression zones for O(log n) containment checks
140
+ let zoneStarts = [];
141
+ let zoneEnds = [];
142
+ if (rawZones.length > 0) {
143
+ rawZones.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
144
+ let [ms, me] = rawZones[0];
145
+ for (let i = 1; i < rawZones.length; i++) {
146
+ const [zs, ze] = rawZones[i];
147
+ if (zs <= me) {
148
+ me = Math.max(me, ze);
149
+ }
150
+ else {
151
+ zoneStarts.push(ms);
152
+ zoneEnds.push(me);
153
+ ms = zs;
154
+ me = ze;
155
+ }
67
156
  }
157
+ zoneStarts.push(ms);
158
+ zoneEnds.push(me);
68
159
  }
69
160
  // Build candidates with priority: validated (3) > custom (2) > regex-only (1)
70
161
  const candidates = [];
71
- for (const match of validated) {
162
+ for (const { match, hasValidValidator } of validated) {
72
163
  if ((0, suppressors_js_1.shouldSuppress)(text, match))
73
164
  continue;
74
- if (match.patternDef.validator === null && suppressionZones.length > 0) {
75
- if (suppressionZones.some(([zStart, zEnd]) => match.start >= zStart && match.end <= zEnd)) {
76
- continue;
165
+ // O(log n) binary-search containment check on merged zones
166
+ if (match.patternDef.validator === null && zoneStarts.length > 0) {
167
+ let lo = 0, hi = zoneStarts.length;
168
+ while (lo < hi) {
169
+ const mid = (lo + hi) >>> 1;
170
+ if (zoneStarts[mid] <= match.start)
171
+ lo = mid + 1;
172
+ else
173
+ hi = mid;
77
174
  }
175
+ const idx = lo - 1;
176
+ if (idx >= 0 && zoneEnds[idx] >= match.end)
177
+ continue;
78
178
  }
79
- const hasValidator = match.patternDef.validator !== null;
80
- const isValid = this.matcher.validate(match);
81
- const priority = (hasValidator && isValid) ? 3 : match.countryCode === "CUSTOM" ? 2 : 1;
179
+ // A bare digit run is the weakest evidence in the engine and must never
180
+ // re-cut a span a structured detector claims (PHONE, SSN, NATIONAL_ID,
181
+ // BANK_ACCOUNT, VAT...). Postal codes take unclaimed spans only,
182
+ // whatever the span lengths.
183
+ const priority = hasValidValidator
184
+ ? 3
185
+ : match.countryCode === "CUSTOM"
186
+ ? 2
187
+ : match.patternDef.entityType === types_js_1.EntityType.POSTAL_CODE
188
+ ? 0
189
+ : 1;
82
190
  const spanLength = match.end - match.start;
83
191
  const score = priority * 1_000_000 + spanLength;
84
192
  candidates.push({
@@ -109,16 +217,20 @@ class RuleEngine {
109
217
  return [];
110
218
  const sorted = [...candidates].sort((a, b) => b.score - a.score);
111
219
  const result = [];
220
+ const occupied = new Set();
112
221
  for (const { det } of sorted) {
113
222
  let overlaps = false;
114
- for (const kept of result) {
115
- if (det.start < kept.end && det.end > kept.start) {
223
+ for (let p = det.start; p < det.end; p++) {
224
+ if (occupied.has(p)) {
116
225
  overlaps = true;
117
226
  break;
118
227
  }
119
228
  }
120
- if (!overlaps)
229
+ if (!overlaps) {
230
+ for (let p = det.start; p < det.end; p++)
231
+ occupied.add(p);
121
232
  result.push(det);
233
+ }
122
234
  }
123
235
  return result;
124
236
  }
@@ -22,11 +22,13 @@ class MultiPatternMatcher {
22
22
  compile() {
23
23
  this.compiled = true;
24
24
  }
25
- scan(text) {
25
+ scan(text, countryCodes = null) {
26
26
  if (!this.compiled)
27
27
  this.compile();
28
28
  const matches = [];
29
29
  for (const { regex, patternDef, countryCode } of this.patterns) {
30
+ if (countryCodes !== null && !countryCodes.has(countryCode))
31
+ continue;
30
32
  regex.lastIndex = 0;
31
33
  let m;
32
34
  while ((m = regex.exec(text)) !== null) {
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.shouldSuppress = shouldSuppress;
4
4
  const types_js_1 = require("../types.js");
5
+ const bicRegistry_js_1 = require("./bicRegistry.js");
5
6
  const CONTEXT_CHARS = 150;
6
7
  function getContext(text, start, end) {
7
8
  const ctxStart = Math.max(0, start - CONTEXT_CHARS);
@@ -21,12 +22,14 @@ const REFERENCE_BEFORE = /(?:dossier|ref\.?|referentie|reference|référence|fac
21
22
  const LEGAL_BEFORE = /(?:Art(?:ikel|icle|\.)|§|Artikel|Section|Sectie|Afdeling|paragraaf|Absatz|alinéa|punt|point|Punkt|lid)\s*$/i;
22
23
  const MATH_BEFORE = /[=+\-×÷*/]\s*$/;
23
24
  const MATH_AFTER = /^\s*[=+\-×÷*/]/;
25
+ // "A-1010", "B-2000", "L-1234", "CH-8000", "D-10115": a country prefix on a
26
+ // postal code, not a minus sign.
27
+ const COUNTRY_PREFIX_HYPHEN = /(?:^|[^A-Za-z0-9])[A-Z]{1,2}-\s*$/;
24
28
  const SEQUENTIAL_PATTERNS = /^(?:0{6,}|1234567890?|0123456789|9876543210?|1111111111?|000000000|123456789)$/;
25
- const YEAR_PATTERN = /^(?:19[4-9]\d|20[0-3]\d)$/;
26
- const DATE_KEYWORD_NEAR = /(?:jaar|year|année|Jahr|datum|date|Datum|in\s+\d{4}|since|sinds|depuis|seit|født|fødselsdato|fødsel|Fødselsdato|född|födelsedatum|födelsedag|syntynyt|syntymäaika|fæddur|fæðingardagur|\d{2}\.\d{2}\.|(?:januar|februar|marts|april|maj|juni|juli|august|september|oktober|november|december|januari|februari|mars|april|mei|juin|juillet|août|Tiltr[æa]delsesdato|Tiltredelsesdato))/i;
29
+ // YEAR_PATTERN kept for reference but replaced by RECENT_YEAR in suppressYearAsPostal
27
30
  const ID_LABEL_BEFORE = /(?:BSN|RR|NN|NIR|INSZ|NISS|NIS|Steuer-?ID|TIN|NIF|NIE|SSN|rijksregisternummer|numéro\s*national|national\s*number|matricule|Ausweisnummer|Personalausweis|Versichertennummer|KVNR|KV-Nr|Steuernummer|St\.\-Nr|StNr|Finanzamt\s+ist|Ondernemingen\s+onder\s+nummer|ondernemingsnummer|numéro\s*d'entreprise|enterprise\s*number|Kruispuntbank)\s*[:.]?\s*$/i;
28
31
  const SERVICE_NUMBER = /^0800[\-\s]/;
29
- const DATE_PATTERN_FULL = /^\d{2}[-/.]\d{2}[-/.]\d{4}$/;
32
+ const DATE_PATTERN_FULL = /^\d{2}[-/.]\d{2}[-/.]\d{4}$|^\d{4}[-/.]\d{2}[-/.]\d{2}$/;
30
33
  const PASSPORT_CONTEXT_BEFORE = /(?:Reisepass|passport|passeport|paspoort|Bisheriger\s+Reisepass)\s*(?:Nr\.?|Nummer|nummer|number|n[°o])?\s*[:.]?\s*$/i;
31
34
  const SE_ORG_CONTEXT_BEFORE = /(?:org\.?\s*nr\.?|organisationsnummer|organisationsnr|Bolagsverket|företag)\s*[:.]?\s*$/i;
32
35
  const NUMERIC_TYPES = new Set([types_js_1.EntityType.PHONE, types_js_1.EntityType.NATIONAL_ID, types_js_1.EntityType.SSN, types_js_1.EntityType.TAX_ID, types_js_1.EntityType.POSTAL_CODE]);
@@ -66,23 +69,40 @@ function suppressMath(text, match) {
66
69
  if (!NUMERIC_TYPES.has(match.patternDef.entityType))
67
70
  return false;
68
71
  const [before, after] = getContext(text, match.start, match.end);
72
+ // A country-prefixed postal code is an address, not a subtraction:
73
+ // "A-1010 Wien", "B-2000 Antwerpen", "D-10115 Berlin".
74
+ if (match.patternDef.entityType === types_js_1.EntityType.POSTAL_CODE && COUNTRY_PREFIX_HYPHEN.test(before)) {
75
+ return false;
76
+ }
69
77
  return MATH_BEFORE.test(before) || MATH_AFTER.test(after);
70
78
  }
71
79
  function suppressSequential(_text, match) {
72
80
  const clean = match.text.replace(/[\s.\-]/g, "");
73
81
  return SEQUENTIAL_PATTERNS.test(clean);
74
82
  }
83
+ const RECENT_YEAR = /^(?:19[5-9]\d|20[0-3]\d)$/;
84
+ const POSTAL_CONTEXT_NEAR = /(?:postcode|postal|code\s*postal|PLZ|Postleitzahl|postnummer|postinumero|póstnúmer|zip|straat|straße|strasse|rue\s|via\s|calle\s|rua\s|ulica|utca|street|avenue|laan\s|weg\s|plein|adres|adresse|address|woonplaats|wonende|woonachtig|gevestigd|domicili|demeurant|résidant|residant|bosatt|bopæl|wohnhaft|ansässig|stad\b|ville\b|city\b|Stadt|città|ciudad|cidade|miasto|město|város)/i;
85
+ const DATE_KEYWORD_NEAR = /(?:født|fødselsdato|fødsel|Fødselsdato|född|födelsedatum|födelsedag|syntynyt|syntymäaika|fæddur|fæðingardagur|geboren|geboortedatum|Geburtsdatum|nascido|nacido|data di nascita|nato il|nata il|Tiltr[æa]delsesdato|Tiltredelsesdato|datum|date\b|Datum|jaar|year|année|Jahr|since|sinds|depuis|seit|\d{2}\.\d{2}\.|(?:januar|februar|marts|april|maj|juni|juli|august|september|oktober|november|december|januari|februari|mars|mei|juin|juillet|août))/i;
75
86
  function suppressYearAsPostal(text, match) {
76
87
  if (match.patternDef.entityType !== types_js_1.EntityType.POSTAL_CODE)
77
88
  return false;
78
89
  const clean = match.text.trim();
79
- if (!YEAR_PATTERN.test(clean))
90
+ if (!RECENT_YEAR.test(clean))
91
+ return false;
92
+ const [before, after] = getContext(text, match.start, match.end);
93
+ const context = before + after;
94
+ // Keep as postal code if postal/address context nearby
95
+ if (POSTAL_CONTEXT_NEAR.test(context))
80
96
  return false;
97
+ // Keep if preceded by comma+space (address pattern: "Amsterdam, 2026")
81
98
  const immediateBefore = text.slice(Math.max(0, match.start - 3), match.start);
82
- if (immediateBefore.endsWith(", ") || immediateBefore.endsWith(",\n"))
99
+ if (/,\s*$/.test(immediateBefore))
83
100
  return false;
84
- const [before, after] = getContext(text, match.start, match.end);
85
- return DATE_KEYWORD_NEAR.test(before + after);
101
+ // Suppress if date keyword nearby (birth date, employment date, etc.)
102
+ if (DATE_KEYWORD_NEAR.test(context))
103
+ return true;
104
+ // Suppress: recent years without postal context are almost never postal codes
105
+ return true;
86
106
  }
87
107
  function suppressPhoneAfterIdLabel(text, match) {
88
108
  if (match.patternDef.entityType !== types_js_1.EntityType.PHONE)
@@ -104,9 +124,13 @@ const NOT_CITY_CODES = new Set([
104
124
  "ID", "NR", "NO", "ST", "DR", "MR", "MS", "HR", "FR", "IM", "IN", "OR", "IF", "IS", "IT", "AT", "AD", "AG", "AV",
105
125
  "BE", "DE", "EU", "NL", "LU", "WS", "SS", "IP",
106
126
  ]);
127
+ const CURRENCY_PLATE = /^(?:EUR|USD|GBP|CHF|SEK|NOK|DKK|ISK|CZK|PLN|HUF|RON|BGN|HRK)\s/i;
107
128
  function suppressPlateInCompound(text, match) {
108
129
  if (match.patternDef.entityType !== types_js_1.EntityType.LICENSE_PLATE)
109
130
  return false;
131
+ // Suppress currency + number misread as plate (e.g. "EUR 2")
132
+ if (CURRENCY_PLATE.test(match.text))
133
+ return true;
110
134
  if (match.start >= 3) {
111
135
  const before = text.slice(Math.max(0, match.start - 10), match.start);
112
136
  if (/[A-Za-zÄÖÜäöüß]{2,}-$/.test(before))
@@ -178,6 +202,218 @@ function suppressPostalAsHouseNumber(text, match) {
178
202
  }
179
203
  return false;
180
204
  }
205
+ // ── BIC: banking-context cues and heading shapes ────────────────────────
206
+ // \bSWIFT\b also covers SWIFT-Code / SWIFT-BIC / Code SWIFT, and \bBIC\b
207
+ // covers BIC-code / BIC/SWIFT.
208
+ const BIC_KEYWORD = /\b(?:BIC|SWIFT)\b/i;
209
+ const BANK_BLOCK = /\b(?:IBAN|Bankverbindung|Bankgegevens|Bankrekening|Rekening(?:nummer)?|Kontonummer|Konto|Kontoinhaber|Compte|Coordonn[ée]es\s+bancaires|Banque|Account\s+(?:number|holder)|Bankleitzahl|BLZ|Betaalgegevens|Zahlungsdaten)\b/i;
210
+ // A line that is nothing but a BIC/SWIFT label, as used in table and column
211
+ // layouts where the code sits on the following line.
212
+ const BIC_LABEL_LINE = /^\s*(?:BIC|SWIFT|SWIFT[-\s]?BIC|BIC\s?\/\s?SWIFT|SWIFT[-\s]?Code|BIC[-\s]?code|Code\s+SWIFT)\s*:?\s*$/i;
213
+ // An IBAN in the same structural unit: CC + 2 check digits + 2 or more groups.
214
+ const IBAN_SHAPE = /\b[A-Z]{2}\d{2}(?:\s?[A-Z0-9]{4}){2,}/;
215
+ // Largest paragraph still treated as one structural unit. Beyond this the unit
216
+ // falls back to the enclosing line, so a run-on document body cannot lend
217
+ // banking context to a token 2,000 characters away.
218
+ const MAX_UNIT_CHARS = 600;
219
+ function enclosingLine(text, start, end) {
220
+ const lineStart = text.lastIndexOf("\n", start - 1) + 1;
221
+ let lineEnd = text.indexOf("\n", end);
222
+ if (lineEnd === -1)
223
+ lineEnd = text.length;
224
+ return [lineStart, lineEnd];
225
+ }
226
+ /**
227
+ * Return the enclosing line / record / paragraph around a match.
228
+ *
229
+ * The context window for BIC is scoped structurally, not by character count.
230
+ * A tight character window measured on the corpus rejects 97.3% of dictionary
231
+ * false positives but wrongly discards ~316 real-looking codes, because the
232
+ * banking cue often sits further away in the same record — e.g. a CSV row
233
+ * carrying the IBAN in one field and the BIC several fields later.
234
+ */
235
+ function structuralUnit(text, start, end) {
236
+ const [lineStart, lineEnd] = enclosingLine(text, start, end);
237
+ let paraStart = lineStart;
238
+ while (paraStart > 0) {
239
+ const prevEnd = paraStart - 1;
240
+ const prevStart = text.lastIndexOf("\n", prevEnd - 1) + 1;
241
+ if (text.slice(prevStart, prevEnd).trim() === "")
242
+ break;
243
+ paraStart = prevStart;
244
+ }
245
+ let paraEnd = lineEnd;
246
+ while (paraEnd < text.length) {
247
+ const nextStart = paraEnd + 1;
248
+ let nextEnd = text.indexOf("\n", nextStart);
249
+ if (nextEnd === -1)
250
+ nextEnd = text.length;
251
+ if (text.slice(nextStart, nextEnd).trim() === "")
252
+ break;
253
+ paraEnd = nextEnd;
254
+ }
255
+ if (paraEnd - paraStart <= MAX_UNIT_CHARS)
256
+ return text.slice(paraStart, paraEnd);
257
+ return text.slice(lineStart, lineEnd);
258
+ }
259
+ function previousNonblankLine(text, lineStart) {
260
+ let pos = lineStart;
261
+ while (pos > 0) {
262
+ const prevEnd = pos - 1;
263
+ const prevStart = text.lastIndexOf("\n", prevEnd - 1) + 1;
264
+ const line = text.slice(prevStart, prevEnd);
265
+ if (line.trim() !== "")
266
+ return line;
267
+ pos = prevStart;
268
+ }
269
+ return "";
270
+ }
271
+ function escapeRe(s) {
272
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
273
+ }
274
+ /**
275
+ * Does `token` also occur as an ordinary lowercase word in this document?
276
+ *
277
+ * `hospital`/`HOSPITAL`, `gegevens`/`GEGEVENS` — a token that appears in
278
+ * ordinary case elsewhere in the same document is a word, not a bank code.
279
+ * Email and domain contexts are excluded, so `ing.nl` does not vouch for a
280
+ * heading. Measured on the corpus this alone identifies ~78% of the BIC false
281
+ * positives with no dictionaries and no labelled data.
282
+ */
283
+ function occursAsLowercaseWord(text, token) {
284
+ if (!/^[A-Za-z]+$/.test(token))
285
+ return false;
286
+ const lower = token.toLowerCase();
287
+ const capitalised = lower[0].toUpperCase() + lower.slice(1);
288
+ for (const form of [lower, capitalised]) {
289
+ // Cheap pre-check: a plain substring test almost always answers "no".
290
+ if (!text.includes(form))
291
+ continue;
292
+ const re = new RegExp(`\\b${escapeRe(form)}\\b`, "g");
293
+ let m;
294
+ while ((m = re.exec(text)) !== null) {
295
+ const before = m.index > 0 ? text[m.index - 1] : "";
296
+ const after = text.slice(m.index + form.length, m.index + form.length + 8);
297
+ if (before === "@" || (before === "." && m.index >= 2 && /[A-Za-z0-9]/.test(text[m.index - 2])))
298
+ continue;
299
+ if (after.startsWith("@") || /^\.[a-zA-Z]{2,6}\b/.test(after))
300
+ continue;
301
+ return true;
302
+ }
303
+ }
304
+ return false;
305
+ }
306
+ /**
307
+ * Is the candidate positioned as a section heading rather than a value?
308
+ * Headings and shouted words are never bank codes. Lines carrying an explicit
309
+ * BIC/SWIFT keyword are exempt from the all-caps rule, so a genuine
310
+ * `BIC: GEBABEBB` line is not mistaken for a heading.
311
+ */
312
+ function isHeadingShape(text, start, end, token) {
313
+ const [lineStart, lineEnd] = enclosingLine(text, start, end);
314
+ const line = text.slice(lineStart, lineEnd);
315
+ // The token is the entire line — unless the line above is a bare BIC/SWIFT
316
+ // label, which makes this a labelled value in a table layout, not a heading.
317
+ if (line.trim() === token) {
318
+ return !BIC_LABEL_LINE.test(previousNonblankLine(text, lineStart));
319
+ }
320
+ // The token starts its line and is immediately followed by a colon
321
+ if (text.slice(lineStart, start).trim() === "" && text.slice(end, lineEnd).trimStart().startsWith(":")) {
322
+ return true;
323
+ }
324
+ // A shouted line: no lowercase, no digits, and no banking keyword
325
+ if (!/[a-z]/.test(line) && !/\d/.test(line) && !BIC_KEYWORD.test(line))
326
+ return true;
327
+ return false;
328
+ }
329
+ /**
330
+ * Emit a BIC only on registry membership or banking context.
331
+ *
332
+ * 0. the token also occurs as an ordinary lowercase word here -> reject;
333
+ * 1. registry hit (deployment-supplied, then bundled seed prefixes) -> emit;
334
+ * 2. heading / shouted-word shape -> reject;
335
+ * 3. BIC/SWIFT keyword, IBAN or bank block in the structural unit -> emit;
336
+ *
337
+ * and a bare shape match reaching the end with none of the above is never
338
+ * emitted. Gate 0 outranks every tier below it — no genuine BIC is also an
339
+ * ordinary lowercase word — so it is applied on both emitting paths. It scans
340
+ * the whole document, so it runs only on the paths that would otherwise emit.
341
+ */
342
+ function suppressBicWithoutEvidence(text, match) {
343
+ if (match.patternDef.entityType !== types_js_1.EntityType.BIC)
344
+ return false;
345
+ const token = match.text.trim();
346
+ if ((0, bicRegistry_js_1.isRegisteredBic)(token))
347
+ return occursAsLowercaseWord(text, token);
348
+ if (isHeadingShape(text, match.start, match.end, token))
349
+ return true;
350
+ // The token itself is blanked out so it cannot vouch for itself.
351
+ const unit = structuralUnit(text, match.start, match.end).split(token).join(" ".repeat(token.length));
352
+ if (BIC_KEYWORD.test(unit) || IBAN_SHAPE.test(unit) || BANK_BLOCK.test(unit)) {
353
+ return occursAsLowercaseWord(text, token);
354
+ }
355
+ return true;
356
+ }
357
+ // ── Postal code: digits belonging to a longer identifier ────────────────
358
+ // An identifier label immediately before the digits. A postal code is never
359
+ // introduced this way; an SVNr, policy number or service number always is.
360
+ const ID_CUE_BEFORE = /(?:[\w\-]*Nr|[\w\-]*N[°ºo]|[\w\-]*Nummer|[\w\-]*Numero|[\w\-]*Numéro|No|number|num|Kennzahl|Aktenzeichen|Az|e-?card|Polizze|Police|Policen)\.?\s*:?\s*$/i;
361
+ // An international dialling prefix earlier on the same line, with nothing but
362
+ // number punctuation in between: these digits belong to the phone detector.
363
+ const DIALLING_PREFIX_BEFORE = /\+\d{1,3}[\d\s\-().]*$/;
364
+ // A country prefix on a postal code — "A-1010 Wien", "B-2000", "L-1234".
365
+ const COUNTRY_PREFIXED = /(?:^|[^A-Za-z0-9])[A-Z]{1,2}$/;
366
+ /**
367
+ * Suppress bare digit runs that belong to a longer number, not an address.
368
+ *
369
+ * A bare 4- or 5-digit run is the weakest shape in the engine, and when it
370
+ * cuts into a longer identifier the damage is worse than a plain false
371
+ * positive: `SV-Nummer: [POSTAL_CODE] 040390` leaves half an Austrian social
372
+ * security number exposed with no way to label the remainder.
373
+ *
374
+ * Applies only to digits-only matches, so structured forms keep their own
375
+ * behaviour — NL `1234 AB`, PT `1234-567`, LU `L-1234`.
376
+ */
377
+ function suppressPostalInLongerIdentifier(text, match) {
378
+ if (match.patternDef.entityType !== types_js_1.EntityType.POSTAL_CODE)
379
+ return false;
380
+ const clean = match.text.trim();
381
+ if (!/^\d+$/.test(clean))
382
+ return false;
383
+ const beforeChar = match.start > 0 ? text[match.start - 1] : "";
384
+ const afterChar = match.end < text.length ? text[match.end] : "";
385
+ const prevPrev = match.start >= 2 ? text[match.start - 2] : "";
386
+ const nextNext = match.end + 1 < text.length ? text[match.end + 1] : "";
387
+ // Directly glued to more digits
388
+ if (/\d/.test(beforeChar) || /\d/.test(afterChar))
389
+ return true;
390
+ // Joined by identifier punctuation: "0456.2398.71-02", "4471/2025".
391
+ // The punctuation only counts when it actually *joins two digit groups* — a
392
+ // trailing period is ordinary sentence punctuation, and treating it as a
393
+ // separator discards every postal code that ends a sentence
394
+ // ("Domicilio: Palma, 13867. Pagos a ...").
395
+ if ("._/".includes(beforeChar) && /\d/.test(prevPrev))
396
+ return true;
397
+ if ("._/".includes(afterChar) && /\d/.test(nextNext))
398
+ return true;
399
+ if (afterChar === "-" && /\d/.test(nextNext))
400
+ return true;
401
+ if (beforeChar === "-" && !COUNTRY_PREFIXED.test(text.slice(0, match.start - 1)))
402
+ return true;
403
+ // A further digit group on the same line: "1268 040390", "1234 5678 925",
404
+ // "+43 664 8213 907". Horizontal whitespace only — a digit on the *next*
405
+ // line is a separate field, not a continuation.
406
+ if (/^[ \t]+\d/.test(text.slice(match.end, match.end + 4)))
407
+ return true;
408
+ // An identifier label introduces the digits: "DiNr. 4471", "Policen-Nr."
409
+ if (ID_CUE_BEFORE.test(text.slice(Math.max(0, match.start - 40), match.start)))
410
+ return true;
411
+ // Digits after an international dialling prefix belong to PHONE
412
+ const [lineStart] = enclosingLine(text, match.start, match.end);
413
+ if (DIALLING_PREFIX_BEFORE.test(text.slice(lineStart, match.start)))
414
+ return true;
415
+ return false;
416
+ }
181
417
  function suppressRequiresContext(text, match) {
182
418
  if (!match.patternDef.requiresContext || match.patternDef.contextKeywords.length === 0)
183
419
  return false;
@@ -190,8 +426,9 @@ const TYPE_SUPPRESSORS = {
190
426
  [types_js_1.EntityType.NATIONAL_ID]: [suppressCurrency, suppressUnits, suppressReference, suppressLegal, suppressMath, suppressNatidAsPassport, suppressSeNatidAsOrg],
191
427
  [types_js_1.EntityType.SSN]: [suppressCurrency, suppressUnits, suppressReference, suppressMath],
192
428
  [types_js_1.EntityType.TAX_ID]: [suppressCurrency, suppressUnits, suppressReference, suppressMath],
193
- [types_js_1.EntityType.POSTAL_CODE]: [suppressCurrency, suppressUnits, suppressMath, suppressLegal, suppressYearAsPostal, suppressPostalInsideIban, suppressPostalAsHouseNumber],
194
- [types_js_1.EntityType.IBAN]: [suppressReference],
429
+ [types_js_1.EntityType.POSTAL_CODE]: [suppressCurrency, suppressUnits, suppressMath, suppressLegal, suppressYearAsPostal, suppressPostalInsideIban, suppressPostalAsHouseNumber, suppressPostalInLongerIdentifier],
430
+ [types_js_1.EntityType.BIC]: [suppressBicWithoutEvidence],
431
+ [types_js_1.EntityType.BANK_ACCOUNT]: [suppressReference],
195
432
  [types_js_1.EntityType.LICENSE_PLATE]: [suppressPlateInCompound],
196
433
  [types_js_1.EntityType.CHAMBER_OF_COMMERCE]: [suppressReference],
197
434
  };