euredact 0.0.1 → 0.2.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.
package/LICENSE ADDED
@@ -0,0 +1,189 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work.
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship. For the purposes
43
+ of this License, Derivative Works shall not include works that remain
44
+ separable from, or merely link (or bind by name) to the interfaces of,
45
+ the Work and Derivative Works thereof.
46
+
47
+ "Contribution" shall mean any work of authorship, including
48
+ the original version of the Work and any modifications or additions
49
+ to that Work or Derivative Works thereof, that is intentionally
50
+ submitted to the Licensor for inclusion in the Work by the copyright owner
51
+ or by an individual or Legal Entity authorized to submit on behalf of
52
+ the copyright owner. For the purposes of this definition, "submitted"
53
+ means any form of electronic, verbal, or written communication sent
54
+ to the Licensor or its representatives, including but not limited to
55
+ communication on electronic mailing lists, source code control systems,
56
+ and issue tracking systems that are managed by, or on behalf of, the
57
+ Licensor for the purpose of discussing and improving the Work, but
58
+ excluding communication that is conspicuously marked or otherwise
59
+ designated in writing by the copyright owner as "Not a Contribution."
60
+
61
+ "Contributor" shall mean Licensor and any individual or Legal Entity
62
+ on behalf of whom a Contribution has been received by the Licensor and
63
+ subsequently incorporated within the Work.
64
+
65
+ 2. Grant of Copyright License. Subject to the terms and conditions of
66
+ this License, each Contributor hereby grants to You a perpetual,
67
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
68
+ copyright license to reproduce, prepare Derivative Works of,
69
+ publicly display, publicly perform, sublicense, and distribute the
70
+ Work and such Derivative Works in Source or Object form.
71
+
72
+ 3. Grant of Patent License. Subject to the terms and conditions of
73
+ this License, each Contributor hereby grants to You a perpetual,
74
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
75
+ (except as stated in this section) patent license to make, have made,
76
+ use, offer to sell, sell, import, and otherwise transfer the Work,
77
+ where such license applies only to those patent claims licensable
78
+ by such Contributor that are necessarily infringed by their
79
+ Contribution(s) alone or by combination of their Contribution(s)
80
+ with the Work to which such Contribution(s) was submitted. If You
81
+ institute patent litigation against any entity (including a
82
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
83
+ or a Contribution incorporated within the Work constitutes direct
84
+ or contributory patent infringement, then any patent licenses
85
+ granted to You under this License for that Work shall terminate
86
+ as of the date such litigation is filed.
87
+
88
+ 4. Redistribution. You may reproduce and distribute copies of the
89
+ Work or Derivative Works thereof in any medium, with or without
90
+ modifications, and in Source or Object form, provided that You
91
+ meet the following conditions:
92
+
93
+ (a) You must give any other recipients of the Work or
94
+ Derivative Works a copy of this License; and
95
+
96
+ (b) You must cause any modified files to carry prominent notices
97
+ stating that You changed the files; and
98
+
99
+ (c) You must retain, in the Source form of any Derivative Works
100
+ that You distribute, all copyright, patent, trademark, and
101
+ attribution notices from the Source form of the Work,
102
+ excluding those notices that do not pertain to any part of
103
+ the Derivative Works; and
104
+
105
+ (d) If the Work includes a "NOTICE" text file as part of its
106
+ distribution, then any Derivative Works that You distribute must
107
+ include a readable copy of the attribution notices contained
108
+ within such NOTICE file, excluding any notices that do not
109
+ pertain to any part of the Derivative Works, in at least one
110
+ of the following places: within a NOTICE text file distributed
111
+ as part of the Derivative Works; within the Source form or
112
+ documentation, if provided along with the Derivative Works; or,
113
+ within a display generated by the Derivative Works, if and
114
+ wherever such third-party notices normally appear. The contents
115
+ of the NOTICE file are for informational purposes only and
116
+ do not modify the License. You may add Your own attribution
117
+ notices within Derivative Works that You distribute, alongside
118
+ or as an addendum to the NOTICE text from the Work, provided
119
+ that such additional attribution notices cannot be construed
120
+ as modifying the License.
121
+
122
+ You may add Your own copyright statement to Your modifications and
123
+ may provide additional or different license terms and conditions
124
+ for use, reproduction, or distribution of Your modifications, or
125
+ for any such Derivative Works as a whole, provided Your use,
126
+ reproduction, and distribution of the Work otherwise complies with
127
+ the conditions stated in this License.
128
+
129
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
130
+ any Contribution intentionally submitted for inclusion in the Work
131
+ by You to the Licensor shall be under the terms and conditions of
132
+ this License, without any additional terms or conditions.
133
+ Notwithstanding the above, nothing herein shall supersede or modify
134
+ the terms of any separate license agreement you may have executed
135
+ with Licensor regarding such Contributions.
136
+
137
+ 6. Trademarks. This License does not grant permission to use the trade
138
+ names, trademarks, service marks, or product names of the Licensor,
139
+ except as required for reasonable and customary use in describing the
140
+ origin of the Work and reproducing the content of the NOTICE file.
141
+
142
+ 7. Disclaimer of Warranty. Unless required by applicable law or
143
+ agreed to in writing, Licensor provides the Work (and each
144
+ Contributor provides its Contributions) on an "AS IS" BASIS,
145
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
146
+ implied, including, without limitation, any warranties or conditions
147
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
148
+ PARTICULAR PURPOSE. You are solely responsible for determining the
149
+ appropriateness of using or redistributing the Work and assume any
150
+ risks associated with Your exercise of permissions under this License.
151
+
152
+ 8. Limitation of Liability. In no event and under no legal theory,
153
+ whether in tort (including negligence), contract, or otherwise,
154
+ unless required by applicable law (such as deliberate and grossly
155
+ negligent acts) or agreed to in writing, shall any Contributor be
156
+ liable to You for damages, including any direct, indirect, special,
157
+ incidental, or consequential damages of any character arising as a
158
+ result of this License or out of the use or inability to use the
159
+ Work (including but not limited to damages for loss of goodwill,
160
+ work stoppage, computer failure or malfunction, or any and all
161
+ other commercial damages or losses), even if such Contributor
162
+ has been advised of the possibility of such damages.
163
+
164
+ 9. Accepting Warranty or Additional Liability. While redistributing
165
+ the Work or Derivative Works thereof, You may choose to offer,
166
+ and charge a fee for, acceptance of support, warranty, indemnity,
167
+ or other liability obligations and/or rights consistent with this
168
+ License. However, in accepting such obligations, You may act only
169
+ on Your own behalf and on Your sole responsibility, not on behalf
170
+ of any other Contributor, and only if You agree to indemnify,
171
+ defend, and hold each Contributor harmless for any liability
172
+ incurred by, or claims asserted against, such Contributor by reason
173
+ of your accepting any such warranty or additional liability.
174
+
175
+ END OF TERMS AND CONDITIONS
176
+
177
+ Copyright 2024 JNJS
178
+
179
+ Licensed under the Apache License, Version 2.0 (the "License");
180
+ you may not use this file except in compliance with the License.
181
+ You may obtain a copy of the License at
182
+
183
+ http://www.apache.org/licenses/LICENSE-2.0
184
+
185
+ Unless required by applicable law or agreed to in writing, software
186
+ distributed under the License is distributed on an "AS IS" BASIS,
187
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
188
+ See the License for the specific language governing permissions and
189
+ limitations under the License.
package/README.md CHANGED
@@ -1,20 +1,349 @@
1
- # EUREdact
1
+ # euredact
2
2
 
3
- **European PII redaction SDK — rule engine + cloud tier.**
3
+ **European PII detection and redaction for Node.js / TypeScript**
4
4
 
5
- > ⚠️ The Node.js/TypeScript SDK is in development. The Python SDK is available now.
5
+ ---
6
+
7
+ Fast, zero-dependency European PII detection and redaction SDK. Detects and
8
+ redacts personal data across **31 European countries** using rule-based pattern
9
+ matching with checksum validation, context-aware false-positive suppression,
10
+ and priority-based deduplication.
11
+
12
+ ## Install
6
13
 
7
14
  ```bash
8
- pip install euredact
15
+ npm install euredact
16
+ ```
17
+
18
+ ## Quick Start
19
+
20
+ ```ts
21
+ import { redact } from "euredact";
22
+
23
+ const result = redact("Mijn BSN is 123456782 en email jan@example.com", {
24
+ countries: ["NL"],
25
+ });
26
+
27
+ console.log(result.redactedText);
28
+ // "Mijn BSN is [NATIONAL_ID] en email [EMAIL]"
29
+
30
+ console.log(result.detections);
31
+ // [{ entityType: "NATIONAL_ID", text: "123456782", start: 12, end: 21, ... }, ...]
32
+ ```
33
+
34
+ ## Features
35
+
36
+ - **31 European countries** with country-specific patterns
37
+ - **25+ PII entity types:** national IDs, IBANs, phone numbers, email, VAT
38
+ numbers, license plates, credit cards, BIC/SWIFT, VIN, IMEI, GPS coordinates,
39
+ UUIDs, social handles, IP/IPv6, MAC addresses, secrets/API keys, and more
40
+ - **Secret/API key detection:** known-prefix patterns for AWS, GitHub, Stripe,
41
+ OpenAI, Slack, JWT, SendGrid, plus Shannon entropy-based detection for generic
42
+ high-entropy tokens near context keywords
43
+ - **Custom patterns:** register your own regex patterns for domain-specific PII
44
+ - **Checksum validation:** IBAN mod-97, Luhn (credit cards/IMEI), and 30+
45
+ country-specific validators
46
+ - **Priority-aware deduplication:** validated (checksum) > custom > regex-only
47
+ - **Context-aware:** keyword proximity checks and structural detection (JSON field
48
+ names, CSV headers) for ambiguous patterns
49
+ - **Zero runtime dependencies**
50
+ - **ESM and CommonJS** dual-published
51
+
52
+ ### Supported Countries
53
+
54
+ | Region | Countries |
55
+ |---|---|
56
+ | Western Europe | AT, BE, CH, DE, FR, LU, NL |
57
+ | Southern Europe | CY, EL, ES, IT, MT, PT |
58
+ | Northern Europe | DK, EE, FI, IS, LT, LV, NO, SE |
59
+ | Eastern Europe | BG, CZ, HR, HU, PL, RO, SI, SK |
60
+ | British Isles | IE, UK |
61
+
62
+ ## API Reference
63
+
64
+ ### Module-Level Functions
65
+
66
+ #### `redact(text, options?)`
67
+
68
+ ```ts
69
+ function redact(text: string, options?: RedactOptions): RedactResult;
70
+ ```
71
+
72
+ Main entry point. Detects and redacts PII in the given text.
73
+
74
+ ```ts
75
+ interface RedactOptions {
76
+ countries?: string[] | null; // Country codes (e.g. ["NL", "BE"]) — null loads all
77
+ referentialIntegrity?: boolean; // Replace with consistent labels (default: false)
78
+ detectDates?: boolean; // Include DOB/date-of-death detections (default: false)
79
+ cache?: boolean; // Enable result caching (default: true)
80
+ }
81
+ ```
82
+
83
+ | Parameter | Default | Description |
84
+ |---|---|---|
85
+ | `countries` | `null` | ISO 3166-1 alpha-2 codes to restrict detection. `null` loads all 31 countries. |
86
+ | `referentialIntegrity` | `false` | Replace PII with consistent labels instead of entity-type labels. |
87
+ | `detectDates` | `false` | Include date-of-birth and date-of-death detections. Off by default. |
88
+ | `cache` | `true` | Cache results for identical inputs. |
89
+
90
+ #### `redactBatch(texts, options?)`
91
+
92
+ ```ts
93
+ function redactBatch(texts: string[], options?: RedactOptions): RedactResult[];
94
+ ```
95
+
96
+ Process multiple texts efficiently. Loads country configs once. Returns results
97
+ in the same order as the input.
98
+
99
+ #### `addCustomPattern(name, pattern)`
100
+
101
+ ```ts
102
+ function addCustomPattern(name: string, pattern: string): void;
103
+ ```
104
+
105
+ Register a custom regex pattern. Matches are reported with `name` as the entity
106
+ type. See [Custom Patterns](#custom-patterns) below.
107
+
108
+ #### `availableCountries()`
109
+
110
+ ```ts
111
+ function availableCountries(): string[];
112
+ ```
113
+
114
+ Returns a sorted list of supported ISO country codes.
115
+
116
+ ### Instance-Based API (`EuRedact` Class)
117
+
118
+ For applications that need isolated instances with separate caches and custom
119
+ pattern registrations:
120
+
121
+ ```ts
122
+ import { EuRedact } from "euredact";
123
+
124
+ const instance = new EuRedact();
125
+ instance.addCustomPattern("CASE_REF", "CASE-\\d{8}");
126
+
127
+ const result = instance.redact("See CASE-20260401 for details", {
128
+ countries: ["NL", "BE"],
129
+ });
130
+ console.log(result.redactedText);
131
+ // "See [CASE_REF] for details"
132
+ ```
133
+
134
+ The `EuRedact` class exposes: `redact()`, `redactBatch()`, and
135
+ `addCustomPattern()`.
136
+
137
+ ### Return Types
138
+
139
+ #### `RedactResult`
140
+
141
+ ```ts
142
+ interface RedactResult {
143
+ redactedText: string; // The input text with PII replaced
144
+ detections: Detection[]; // All PII spans found
145
+ source: string; // Detection backend ("rules")
146
+ degraded: boolean; // True if the engine fell back to a simpler mode
147
+ }
148
+ ```
149
+
150
+ #### `Detection`
151
+
152
+ ```ts
153
+ interface Detection {
154
+ entityType: EntityType | string; // PII category (enum or custom name)
155
+ start: number; // Start offset in the original text
156
+ end: number; // End offset (exclusive)
157
+ text: string; // The matched substring
158
+ source: DetectionSource; // "rules" or "cloud"
159
+ country: string | null; // ISO code or null for shared/custom patterns
160
+ confidence: string; // Confidence level
161
+ }
162
+ ```
163
+
164
+ #### `EntityType`
165
+
166
+ String enum with all supported PII categories:
167
+
168
+ ```
169
+ NAME ADDRESS IBAN BIC
170
+ CREDIT_CARD PHONE EMAIL DOB
171
+ DATE_OF_DEATH NATIONAL_ID SSN TAX_ID
172
+ PASSPORT DRIVERS_LICENSE RESIDENCE_PERMIT LICENSE_PLATE
173
+ VIN VAT POSTAL_CODE IP_ADDRESS
174
+ IPV6_ADDRESS MAC_ADDRESS HEALTH_INSURANCE HEALTHCARE_PROVIDER
175
+ CHAMBER_OF_COMMERCE IMEI GPS_COORDINATES UUID
176
+ SOCIAL_HANDLE SECRET OTHER
177
+ ```
178
+
179
+ For custom patterns, `entityType` is a plain string (e.g. `"EMPLOYEE_ID"`).
180
+
181
+ ## Custom Patterns
182
+
183
+ Register domain-specific PII patterns at runtime:
184
+
185
+ ```ts
186
+ import { addCustomPattern, redact } from "euredact";
187
+
188
+ // Register patterns
189
+ addCustomPattern("EMPLOYEE_ID", "EMP-\\d{6}");
190
+ addCustomPattern("CASE_REF", "CASE-\\d{8}");
191
+
192
+ // They are detected alongside built-in PII
193
+ const result = redact(
194
+ "Employee EMP-123456, email jan@example.com, ref CASE-20260401"
195
+ );
196
+ console.log(result.redactedText);
197
+ // "Employee [EMPLOYEE_ID], email [EMAIL], ref [CASE_REF]"
198
+ ```
199
+
200
+ ### How Custom Patterns Work
201
+
202
+ - `name` becomes the entity type in detections and replacement tags
203
+ - `pattern` is a JavaScript regular expression (same syntax as `RegExp`)
204
+ - Custom patterns are always active regardless of the `countries` option
205
+ - In overlap resolution, custom patterns have higher priority than built-in
206
+ regex-only patterns but lower priority than built-in patterns with a passing
207
+ checksum validator
208
+
209
+ ### Instance Isolation
210
+
211
+ Custom patterns registered on the module-level function apply to the shared
212
+ singleton. For isolated registrations, use separate `EuRedact` instances:
213
+
214
+ ```ts
215
+ import { EuRedact } from "euredact";
216
+
217
+ const a = new EuRedact();
218
+ a.addCustomPattern("EMPLOYEE_ID", "EMP-\\d{6}");
219
+
220
+ const b = new EuRedact();
221
+ b.addCustomPattern("CASE_REF", "CASE-\\d{8}");
222
+ ```
223
+
224
+ ## Secret and API Key Detection
225
+
226
+ Built-in detection for API keys, tokens, and passwords. Always active -- no
227
+ configuration required.
228
+
229
+ ### Known-Prefix Patterns
230
+
231
+ | Pattern | Description |
232
+ |---|---|
233
+ | `AKIA...` | AWS Access Key ID |
234
+ | `ghp_`, `gho_`, `ghs_`, `github_pat_` | GitHub tokens (PAT, OAuth, app, server) |
235
+ | `sk_live_`, `pk_live_`, `sk_test_`, `pk_test_` | Stripe secret and publishable keys |
236
+ | `sk-`, `sk-ant-` | OpenAI and Anthropic API keys |
237
+ | `xoxb-`, `xoxp-`, `xoxa-`, `xoxs-` | Slack tokens |
238
+ | `eyJ...` (3-part base64url) | JWT tokens |
239
+ | `SG.` | SendGrid API keys |
240
+
241
+ ```ts
242
+ const result = redact("My API key is sk-proj-abc123def456ghi789jkl0");
243
+ console.log(result.redactedText);
244
+ // "My API key is [SECRET]"
245
+ ```
246
+
247
+ ### Entropy-Based Detection
248
+
249
+ High-entropy strings (32+ alphanumeric characters) near context keywords like
250
+ `key`, `token`, `secret`, `password`, `credential`, `auth`, or `bearer`
251
+ (including 12 European language translations) are flagged via Shannon entropy
252
+ analysis:
253
+
254
+ ```ts
255
+ redact("The api_key is xK9mPqR7vLnW2bFjY8cGhT4sDfAeU6iO").redactedText;
256
+ // "The api_key is [SECRET]"
257
+
258
+ // Without a context keyword -- not flagged:
259
+ redact("identifier: xK9mPqR7vLnW2bFjY8cGhT4sDfAeU6iO").redactedText;
260
+ // "identifier: xK9mPqR7vLnW2bFjY8cGhT4sDfAeU6iO"
261
+ ```
262
+
263
+ ## Country Hints
264
+
265
+ When you know which countries appear in your data, pass them explicitly:
266
+
267
+ ```ts
268
+ const result = redact(text, { countries: ["NL", "BE"] });
269
+ ```
270
+
271
+ This restricts pattern matching to Dutch and Belgian rules (plus shared patterns
272
+ and custom patterns). Benefits:
273
+
274
+ - **Fewer false positives.** A 9-digit number that passes the Dutch BSN checksum
275
+ won't also be tested against unrelated country patterns.
276
+ - **Faster.** Fewer patterns to compile and scan.
277
+
278
+ ## Referential Integrity
279
+
280
+ When `referentialIntegrity: true`, each unique PII value is mapped to a consistent
281
+ label:
282
+
283
+ ```ts
284
+ const result = redact(
285
+ "BSN 123456782 en later weer 123456782",
286
+ { countries: ["NL"], referentialIntegrity: true }
287
+ );
288
+ console.log(result.redactedText);
289
+ // "BSN NATIONAL_ID_1 en later weer NATIONAL_ID_1"
290
+ ```
291
+
292
+ ## Architecture
293
+
294
+ ```
295
+ Input text
296
+ |
297
+ v
298
+ [Normalizer] -- Unicode normalization, whitespace cleanup
299
+ |
300
+ v
301
+ [Pass 1: Pattern Matching] -- All country + shared + custom regexes
302
+ |
303
+ v
304
+ [Pass 2a: Validation] -- Checksum validators (mod-97, Luhn, entropy, ...)
305
+ | Failed-validation spans become suppression zones
306
+ v
307
+ [Pass 2b: Suppression] -- Remove false positives (currency amounts, units,
308
+ | references, overlapping matches in suppression zones)
309
+ v
310
+ [Deduplication] -- Priority-aware: validated > custom > regex-only
311
+ | Within same tier, longer span wins
312
+ v
313
+ [Replacement] -- Right-to-left substitution with [ENTITY_TYPE] labels
314
+ | or labels
315
+ v
316
+ RedactResult
317
+ ```
318
+
319
+ ### Suppression Zones
320
+
321
+ When a regex matches a pattern that has a checksum validator but the checksum
322
+ fails, the matched span becomes a "suppression zone." Any purely regex-based
323
+ detection fully contained within that zone is suppressed as a false positive.
324
+
325
+ ### Deduplication Priority
326
+
327
+ 1. **Validated patterns** (checksum passes) -- highest priority
328
+ 2. **Custom patterns** (registered via `addCustomPattern()`)
329
+ 3. **Regex-only patterns** (no validator) -- lowest priority
330
+
331
+ Within the same tier, the longer span wins.
332
+
333
+ ## CommonJS
334
+
335
+ ```js
336
+ const { redact } = require("euredact");
9
337
  ```
10
338
 
11
- ## Links
339
+ ## Performance
12
340
 
13
- - **Website:** [euredact.eu](https://euredact.eu)
14
- - **Docs:** [docs.euredact.dev](https://docs.euredact.dev)
15
- - **GitHub:** [github.com/euredact/euredact](https://github.com/euredact/euredact)
16
- - **PyPI:** [pypi.org/project/euredact](https://pypi.org/project/euredact)
341
+ | Metric | Value |
342
+ |---|---|
343
+ | Latency per redaction | ~0.02 ms |
344
+ | Package size | ~86 KB |
345
+ | Runtime dependencies | 0 |
17
346
 
18
347
  ## License
19
348
 
20
- Apache 2.0
349
+ Apache-2.0
@@ -0,0 +1,56 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ResultCache = void 0;
4
+ // Simple hash function (FNV-1a) - no crypto dependency needed for cache keys
5
+ function fnv1aHash(str) {
6
+ let hash = 0x811c9dc5;
7
+ for (let i = 0; i < str.length; i++) {
8
+ hash ^= str.charCodeAt(i);
9
+ hash = (hash * 0x01000193) >>> 0;
10
+ }
11
+ return hash.toString(16).padStart(8, "0");
12
+ }
13
+ class ResultCache {
14
+ maxsize;
15
+ enabled;
16
+ store = new Map();
17
+ constructor(maxsize = 1024, enabled = true) {
18
+ this.maxsize = maxsize;
19
+ this.enabled = enabled;
20
+ }
21
+ key(text, countries, mode) {
22
+ const sorted = [...countries].sort();
23
+ const raw = `${text}|${sorted.join("|")}|${mode}`;
24
+ // Use multiple FNV-1a hashes on different slices for reduced collisions
25
+ const h1 = fnv1aHash(raw);
26
+ const h2 = fnv1aHash(raw.slice(Math.floor(raw.length / 2)) + raw.slice(0, Math.floor(raw.length / 2)));
27
+ return h1 + h2;
28
+ }
29
+ get(key) {
30
+ if (!this.enabled)
31
+ return null;
32
+ const result = this.store.get(key);
33
+ if (result !== undefined) {
34
+ // Move to end (LRU)
35
+ this.store.delete(key);
36
+ this.store.set(key, result);
37
+ return result;
38
+ }
39
+ return null;
40
+ }
41
+ put(key, result) {
42
+ if (!this.enabled)
43
+ return;
44
+ this.store.delete(key);
45
+ this.store.set(key, result);
46
+ while (this.store.size > this.maxsize) {
47
+ const first = this.store.keys().next().value;
48
+ if (first !== undefined)
49
+ this.store.delete(first);
50
+ }
51
+ }
52
+ clear() {
53
+ this.store.clear();
54
+ }
55
+ }
56
+ exports.ResultCache = ResultCache;
@@ -0,0 +1,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.COUNTRY_CONFIGS = exports.EuRedact = exports.DetectionSource = exports.EntityType = void 0;
4
+ exports.availableCountries = availableCountries;
5
+ exports.redact = redact;
6
+ exports.addCustomPattern = addCustomPattern;
7
+ exports.redactBatch = redactBatch;
8
+ var types_js_1 = require("./types.js");
9
+ Object.defineProperty(exports, "EntityType", { enumerable: true, get: function () { return types_js_1.EntityType; } });
10
+ Object.defineProperty(exports, "DetectionSource", { enumerable: true, get: function () { return types_js_1.DetectionSource; } });
11
+ var sdk_js_1 = require("./sdk.js");
12
+ Object.defineProperty(exports, "EuRedact", { enumerable: true, get: function () { return sdk_js_1.EuRedact; } });
13
+ var index_js_1 = require("./rules/countries/index.js");
14
+ Object.defineProperty(exports, "COUNTRY_CONFIGS", { enumerable: true, get: function () { return index_js_1.COUNTRY_CONFIGS; } });
15
+ const sdk_js_2 = require("./sdk.js");
16
+ const index_js_2 = require("./rules/countries/index.js");
17
+ let _instance = null;
18
+ function getInstance() {
19
+ if (_instance === null)
20
+ _instance = new sdk_js_2.EuRedact();
21
+ return _instance;
22
+ }
23
+ function availableCountries() {
24
+ return Object.keys(index_js_2.COUNTRY_CONFIGS).filter(c => c !== "SHARED").sort();
25
+ }
26
+ function redact(text, options) {
27
+ return getInstance().redact(text, options);
28
+ }
29
+ function addCustomPattern(name, pattern) {
30
+ getInstance().addCustomPattern(name, pattern);
31
+ }
32
+ function redactBatch(texts, options) {
33
+ return getInstance().redactBatch(texts, options);
34
+ }
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normalize = normalize;
4
+ exports.mapOffsetToOriginal = mapOffsetToOriginal;
5
+ function normalize(text) {
6
+ const normalized = text.normalize("NFC");
7
+ if (normalized.length === text.length)
8
+ return [normalized, null];
9
+ return [normalized, buildOffsetMapping(text, normalized)];
10
+ }
11
+ function buildOffsetMapping(original, normalized) {
12
+ const nfdOriginal = original.normalize("NFD");
13
+ const nfdNormalized = normalized.normalize("NFD");
14
+ // Build: normalized index -> original index via NFD as intermediate
15
+ const normToOrig = [];
16
+ for (let normIdx = 0; normIdx < normalized.length; normIdx++) {
17
+ const nfdOfNormChar = normalized[normIdx].normalize("NFD");
18
+ let nfdStart = 0;
19
+ for (let i = 0; i < normIdx; i++) {
20
+ nfdStart += normalized[i].normalize("NFD").length;
21
+ }
22
+ let targetOrig = 0;
23
+ let running = 0;
24
+ for (let oi = 0; oi < original.length; oi++) {
25
+ const nfdOc = original[oi].normalize("NFD");
26
+ if (running + nfdOc.length > nfdStart) {
27
+ targetOrig = oi;
28
+ break;
29
+ }
30
+ running += nfdOc.length;
31
+ }
32
+ normToOrig.push(targetOrig);
33
+ }
34
+ return normToOrig;
35
+ }
36
+ function mapOffsetToOriginal(offset, mapping) {
37
+ if (mapping === null)
38
+ return offset;
39
+ if (offset >= mapping.length) {
40
+ if (mapping.length > 0)
41
+ return mapping[mapping.length - 1] + (offset - mapping.length + 1);
42
+ return offset;
43
+ }
44
+ return mapping[offset];
45
+ }
@@ -0,0 +1 @@
1
+ {"type":"commonjs"}