anonyma 1.1.0 → 1.1.1

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 (56) hide show
  1. package/CHANGELOG.md +23 -2
  2. package/dist/ai/index.d.cts +5 -5
  3. package/dist/ai/index.d.ts +5 -5
  4. package/dist/audit/index.d.cts +2 -2
  5. package/dist/audit/index.d.ts +2 -2
  6. package/dist/{chunk-W6RBCHYF.js → chunk-GBYHQQUY.js} +16 -27
  7. package/dist/chunk-GBYHQQUY.js.map +1 -0
  8. package/dist/{chunk-26IHMQHL.cjs → chunk-ZXPZ7W37.cjs} +16 -27
  9. package/dist/chunk-ZXPZ7W37.cjs.map +1 -0
  10. package/dist/compliance/index.d.cts +4 -4
  11. package/dist/compliance/index.d.ts +4 -4
  12. package/dist/crypto.d.cts +1 -1
  13. package/dist/crypto.d.ts +1 -1
  14. package/dist/detectors/index.d.cts +1 -1
  15. package/dist/detectors/index.d.ts +1 -1
  16. package/dist/engine/index.d.cts +3 -3
  17. package/dist/engine/index.d.ts +3 -3
  18. package/dist/index.cjs +18 -18
  19. package/dist/index.d.cts +4 -4
  20. package/dist/index.d.ts +4 -4
  21. package/dist/index.js +2 -2
  22. package/dist/{json-CKDvlRtl.d.ts → json-BruY_-tV.d.ts} +1 -1
  23. package/dist/{json-s8ny-RCo.d.cts → json-CvKtPL8l.d.cts} +1 -1
  24. package/dist/mcp/index.cjs +1 -1
  25. package/dist/mcp/index.cjs.map +1 -1
  26. package/dist/mcp/index.js +1 -1
  27. package/dist/mcp/index.js.map +1 -1
  28. package/dist/middleware/express.d.cts +3 -3
  29. package/dist/middleware/express.d.ts +3 -3
  30. package/dist/middleware/hono.d.cts +3 -3
  31. package/dist/middleware/hono.d.ts +3 -3
  32. package/dist/middleware/index.d.cts +3 -3
  33. package/dist/middleware/index.d.ts +3 -3
  34. package/dist/schemas.cjs +1 -1
  35. package/dist/schemas.cjs.map +1 -1
  36. package/dist/schemas.d.cts +1 -1
  37. package/dist/schemas.d.ts +1 -1
  38. package/dist/schemas.js +1 -1
  39. package/dist/schemas.js.map +1 -1
  40. package/dist/{session-Cs2zlNQp.d.ts → session-CEFGgjFV.d.ts} +1 -1
  41. package/dist/{session-BdRftyZ5.d.cts → session-DEQrPea7.d.cts} +1 -1
  42. package/dist/stream.cjs +4 -4
  43. package/dist/stream.d.cts +1 -1
  44. package/dist/stream.d.ts +1 -1
  45. package/dist/stream.js +1 -1
  46. package/dist/{types-CPUhjvl8.d.cts → types-BL5UWH0y.d.cts} +1 -1
  47. package/dist/{types-0BJH_wqc.d.cts → types-BtvX8QTd.d.cts} +2 -2
  48. package/dist/{types--tPm_AjY.d.ts → types-D5BeXwnX.d.ts} +2 -2
  49. package/dist/{types-EJTj_BKY.d.ts → types-cbGVW8cD.d.cts} +11 -3
  50. package/dist/{types-EJTj_BKY.d.cts → types-cbGVW8cD.d.ts} +11 -3
  51. package/dist/{types-Dtht33aq.d.ts → types-oxllMFYF.d.ts} +1 -1
  52. package/dist/vault/index.d.cts +4 -4
  53. package/dist/vault/index.d.ts +4 -4
  54. package/package.json +1 -1
  55. package/dist/chunk-26IHMQHL.cjs.map +0 -1
  56. package/dist/chunk-W6RBCHYF.js.map +0 -1
package/CHANGELOG.md CHANGED
@@ -7,7 +7,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ---
9
9
 
10
- ## [Unreleased]
10
+ ## [1.1.1] — 2026-10-05
11
+
12
+ Patch release. The 1.x functions now exempt a detected value only when it equals an `allowlist`
13
+ entry, as documented; since 1.0.0 they also exempted every value that contained one. Code that
14
+ relied on such partial matches will see those values anonymized, and can use `allowlistPatterns`
15
+ to match a part of a value instead. The span engine (`"anonyma/engine"`) is unchanged.
16
+
17
+ ### Fixed
18
+
19
+ - **`allowlist`** skips a detected value only when the value equals an entry, as documented.
20
+ Entries were matched as substrings, so `allowlist: ["bob@example.com"]` also left
21
+ `jimbob@example.com` in the output of `anonymize()`, `anonymizeAsync()`, `tokenize()`,
22
+ `sanitizeForLLM()` and the methods of `createAnonymizer()`; an entry naming a domain left
23
+ every address of that domain, and an empty entry left every value. A value that merely
24
+ contains an entry is now anonymized. `allowlistPatterns` still match a part of a value.
25
+ - **`createAnonymizer().tokenize()`** matched `allowlist` entries as regular expressions: an
26
+ entry containing `(` threw a `SyntaxError`, and `"x.y@example.com"` also exempted
27
+ `"xzy@example.com"`.
28
+ - **`allowlistPatterns`** with the `g` or `y` flag skipped only every other matching value,
29
+ because `RegExp.test()` kept its `lastIndex` between values, and left the caller's pattern
30
+ with a changed `lastIndex`. These flags are now ignored.
11
31
 
12
32
  ---
13
33
 
@@ -580,7 +600,8 @@ All types are zero-cost, type-only exports (stripped by `tsc`; no runtime overhe
580
600
  - **Prettier** code formatting.
581
601
  - **MIT License**.
582
602
 
583
- [Unreleased]: https://github.com/izaccavalheiro/anonyma/compare/v1.1.0...HEAD
603
+ [Unreleased]: https://github.com/izaccavalheiro/anonyma/compare/v1.1.1...HEAD
604
+ [1.1.1]: https://github.com/izaccavalheiro/anonyma/releases/tag/v1.1.1
584
605
  [1.1.0]: https://github.com/izaccavalheiro/anonyma/releases/tag/v1.1.0
585
606
  [1.1.0-beta.0]: https://github.com/izaccavalheiro/anonyma/releases/tag/v1.1.0-beta.0
586
607
  [1.0.0]: https://github.com/izaccavalheiro/anonyma/releases/tag/v1.0.0
@@ -1,9 +1,9 @@
1
- import { K as KeyRule } from '../json-s8ny-RCo.cjs';
2
- export { J as JsonSanitizeOptions, a as JsonSanitizeResult, s as sanitizeJson, b as sanitizeJsonAsync } from '../json-s8ny-RCo.cjs';
3
- import { T as TokenizationProvider, A as AsyncChunkTransformer, R as RestoreResult, c as PipelineSpec } from '../types-CPUhjvl8.cjs';
1
+ import { K as KeyRule } from '../json-CvKtPL8l.cjs';
2
+ export { J as JsonSanitizeOptions, a as JsonSanitizeResult, s as sanitizeJson, b as sanitizeJsonAsync } from '../json-CvKtPL8l.cjs';
3
+ import { T as TokenizationProvider, A as AsyncChunkTransformer, R as RestoreResult, c as PipelineSpec } from '../types-BL5UWH0y.cjs';
4
4
  import { A as AuditFieldEntry } from '../types-Zt_bZvwS.cjs';
5
- import { S as SessionTokenizer, a as SessionSnapshot, b as SessionTokenizerOptions } from '../session-BdRftyZ5.cjs';
6
- import '../types-EJTj_BKY.cjs';
5
+ import { S as SessionTokenizer, a as SessionSnapshot, b as SessionTokenizerOptions } from '../session-DEQrPea7.cjs';
6
+ import '../types-cbGVW8cD.cjs';
7
7
 
8
8
  /**
9
9
  * @module ai/restore
@@ -1,9 +1,9 @@
1
- import { K as KeyRule } from '../json-CKDvlRtl.js';
2
- export { J as JsonSanitizeOptions, a as JsonSanitizeResult, s as sanitizeJson, b as sanitizeJsonAsync } from '../json-CKDvlRtl.js';
3
- import { T as TokenizationProvider, A as AsyncChunkTransformer, R as RestoreResult, c as PipelineSpec } from '../types-Dtht33aq.js';
1
+ import { K as KeyRule } from '../json-BruY_-tV.js';
2
+ export { J as JsonSanitizeOptions, a as JsonSanitizeResult, s as sanitizeJson, b as sanitizeJsonAsync } from '../json-BruY_-tV.js';
3
+ import { T as TokenizationProvider, A as AsyncChunkTransformer, R as RestoreResult, c as PipelineSpec } from '../types-oxllMFYF.js';
4
4
  import { A as AuditFieldEntry } from '../types-Zt_bZvwS.js';
5
- import { S as SessionTokenizer, a as SessionSnapshot, b as SessionTokenizerOptions } from '../session-Cs2zlNQp.js';
6
- import '../types-EJTj_BKY.js';
5
+ import { S as SessionTokenizer, a as SessionSnapshot, b as SessionTokenizerOptions } from '../session-CEFGgjFV.js';
6
+ import '../types-cbGVW8cD.js';
7
7
 
8
8
  /**
9
9
  * @module ai/restore
@@ -1,7 +1,7 @@
1
- import { D as DetectedSpan, d as AppliedSpan } from '../types-CPUhjvl8.cjs';
1
+ import { D as DetectedSpan, d as AppliedSpan } from '../types-BL5UWH0y.cjs';
2
2
  import { A as AuditFieldEntry, b as AuditSink, c as AuditHead, a as AuditLogger, d as AuditRecord, e as AuditVerification } from '../types-Zt_bZvwS.cjs';
3
3
  export { f as AuditChecksums, g as AuditEvent, h as AuditFailure, i as AuditOperation, j as AuditPolicyRef } from '../types-Zt_bZvwS.cjs';
4
- import '../types-EJTj_BKY.cjs';
4
+ import '../types-cbGVW8cD.cjs';
5
5
 
6
6
  /**
7
7
  * @module audit/canonical
@@ -1,7 +1,7 @@
1
- import { D as DetectedSpan, d as AppliedSpan } from '../types-Dtht33aq.js';
1
+ import { D as DetectedSpan, d as AppliedSpan } from '../types-oxllMFYF.js';
2
2
  import { A as AuditFieldEntry, b as AuditSink, c as AuditHead, a as AuditLogger, d as AuditRecord, e as AuditVerification } from '../types-Zt_bZvwS.js';
3
3
  export { f as AuditChecksums, g as AuditEvent, h as AuditFailure, i as AuditOperation, j as AuditPolicyRef } from '../types-Zt_bZvwS.js';
4
- import '../types-EJTj_BKY.js';
4
+ import '../types-cbGVW8cD.js';
5
5
 
6
6
  /**
7
7
  * @module audit/canonical
@@ -34,6 +34,16 @@ function detokenizeText(text, store) {
34
34
  return { text: result, unresolved };
35
35
  }
36
36
 
37
+ // src/internal/allowlist.ts
38
+ function compileAllowlist(entries, patterns, caseSensitive) {
39
+ if (entries.length === 0 && patterns.length === 0) return () => false;
40
+ const exact = new Set(entries.map((entry) => caseSensitive ? entry : entry.toLowerCase()));
41
+ const compiled = patterns.map(
42
+ (pattern) => new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, ""))
43
+ );
44
+ return (value) => exact.has(caseSensitive ? value : value.toLowerCase()) || compiled.some((pattern) => pattern.test(value));
45
+ }
46
+
37
47
  // src/anonymize.ts
38
48
  var ALL_CATEGORIES = [
39
49
  "email",
@@ -243,16 +253,7 @@ function anonymize(text, options = {}) {
243
253
  rules,
244
254
  ...enabledCategories !== void 0 ? { enabledCategories } : {}
245
255
  });
246
- const compiledAllowlistPatterns = [
247
- ...allowlistPatterns,
248
- ...allowlist.map(
249
- (entry) => new RegExp(entry.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), allowlistCaseSensitive ? "" : "i")
250
- )
251
- ];
252
- function isAllowlisted(value) {
253
- if (compiledAllowlistPatterns.length === 0) return false;
254
- return compiledAllowlistPatterns.some((re) => re.test(value));
255
- }
256
+ const isAllowlisted = compileAllowlist(allowlist, allowlistPatterns, allowlistCaseSensitive);
256
257
  const builtInMatches = detect(text, categories, customDetectors, aggressive);
257
258
  const customMatches = customPatterns.length > 0 ? detectCustomPatterns(text, customPatterns) : [];
258
259
  const filteredBuiltInMatches = builtInMatches.filter(
@@ -342,13 +343,7 @@ async function anonymizeAsync(text, options = {}) {
342
343
  });
343
344
  const builtInMatches = detect(text, categories, customDetectors, aggressive);
344
345
  const customMatches = customPatterns.length > 0 ? detectCustomPatterns(text, customPatterns) : [];
345
- const compiledAllowlistPatterns = [
346
- ...allowlistPatterns,
347
- ...allowlist.map(
348
- (entry) => new RegExp(entry.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), allowlistCaseSensitive ? "" : "i")
349
- )
350
- ];
351
- const isAllowlisted = (value) => compiledAllowlistPatterns.some((re) => re.test(value));
346
+ const isAllowlisted = compileAllowlist(allowlist, allowlistPatterns, allowlistCaseSensitive);
352
347
  const filteredBuiltInMatches = builtInMatches.filter(
353
348
  (m) => m.confidence >= confidenceThreshold && !isAllowlisted(m.value)
354
349
  );
@@ -530,10 +525,7 @@ function createAnonymizer(config = {}) {
530
525
  allowlist: tAllowlist = [],
531
526
  allowlistCaseSensitive: tCaseSensitive = false
532
527
  } = options ?? {};
533
- const tCompiledAllowlist = tAllowlist.map(
534
- (entry) => new RegExp(entry.replace(/[.*+?^${}()|[\\]\\]/g, "\\$&"), tCaseSensitive ? "" : "i")
535
- );
536
- const isAllowlisted = (v) => tCompiledAllowlist.some((re) => re.test(v));
528
+ const isAllowlisted = compileAllowlist(tAllowlist, [], tCaseSensitive);
537
529
  const tMatches = detect(text, tCats ?? categories, tCustDet ?? customDetectors, tAgg).filter(
538
530
  (m) => m.confidence >= tConfidence && !isAllowlisted(m.value)
539
531
  );
@@ -601,10 +593,7 @@ function tokenize(text, options = {}) {
601
593
  allowlist = [],
602
594
  allowlistCaseSensitive = false
603
595
  } = options;
604
- const compiledAllowlist = allowlist.map(
605
- (entry) => new RegExp(entry.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), allowlistCaseSensitive ? "" : "i")
606
- );
607
- const isAllowlisted = (v) => compiledAllowlist.some((re) => re.test(v));
596
+ const isAllowlisted = compileAllowlist(allowlist, [], allowlistCaseSensitive);
608
597
  const allMatches = detect(text, categories, customDetectors, aggressive).filter(
609
598
  (m) => m.confidence >= confidenceThreshold && !isAllowlisted(m.value)
610
599
  );
@@ -647,5 +636,5 @@ function detokenize(text, mapping) {
647
636
  }
648
637
 
649
638
  export { anonymize, anonymizeAsync, anonymizeObject, anonymizeRecord, createAnonymizer, detect, detokenize, hasPII, tokenize, tokenizeAsync };
650
- //# sourceMappingURL=chunk-W6RBCHYF.js.map
651
- //# sourceMappingURL=chunk-W6RBCHYF.js.map
639
+ //# sourceMappingURL=chunk-GBYHQQUY.js.map
640
+ //# sourceMappingURL=chunk-GBYHQQUY.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/strategies/tokenize.ts","../src/internal/allowlist.ts","../src/anonymize.ts","../src/tokenize.ts"],"names":["assignToken","result","TOKEN_PREFIX_MAP"],"mappings":";;;;;AA+BO,SAAS,gBAAA,GAA+B;AAC7C,EAAA,OAAO;AAAA,IACL,MAAA,sBAAY,GAAA,EAAI;AAAA,IAChB,KAAA,sBAAW,GAAA,EAAI;AAAA,IACf,QAAA,sBAAc,GAAA;AAAI,GACpB;AACF;AAeO,SAAS,YACd,KAAA,EACA,QAAA,EACA,KAAA,EACA,MAAA,EACA,SAAsB,SAAA,EACd;AACR,EAAA,MAAM,WAAW,CAAA,EAAG,MAAM,CAAA,CAAA,EAAI,KAAA,CAAM,aAAa,CAAA,CAAA;AACjD,EAAA,MAAM,QAAA,GAAW,KAAA,CAAM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AAA,EAAM,OAAO,CAAC,CAAA;AAChD;AAuBO,SAAS,UAAA,CAAW,MAAc,OAAA,EAAwD;AAC/F,EAAA,IAAI,OAAO,IAAA,KAAS,QAAA,QAAgB,IAAI,eAAA,CAAgB,QAAQ,kBAAkB,CAAA;AAGlF,EAAA,MAAM,QAAQ,gBAAA,EAAiB;AAC/B,EAAA,KAAA,MAAW,CAAC,KAAA,EAAO,KAAK,CAAA,IAAK,OAAA,EAAS;AACpC,IAAA,KAAA,CAAM,MAAA,CAAO,GAAA,CAAI,KAAA,EAAO,KAAK,CAAA;AAAA,EAC/B;AAEA,EAAA,MAAM,MAAA,GAAS,cAAA,CAAe,IAAA,EAAM,KAAK,CAAA;AAGzC,EAAA,MAAM,QAAA,GAAW,kCAAA;AACjB,EAAA,MAAM,eAAe,IAAA,CAAK,KAAA,CAAM,QAAQ,CAAA,IAAK,EAAC,EAAG,MAAA;AACjD,EAAA,MAAM,aAAA,GAAgB,WAAA,GAAc,MAAA,CAAO,UAAA,CAAW,MAAA;AACtD,EAAA,OAAO;AAAA,IACL,MAAM,MAAA,CAAO,IAAA;AAAA,IACb,aAAA;AAAA,IACA,YAAY,MAAA,CAAO;AAAA,GACrB;AACF","file":"chunk-GBYHQQUY.js","sourcesContent":["/**\n * @module strategies/tokenize\n * @description The `tokenize` anonymization strategy — replaces PII with\n * deterministic, reversible tokens that can later be detokenized.\n *\n * Tokens are opaque identifiers (`[CATEGORY_xxxx]` or `<CATEGORY_N>`) that\n * carry no information about the original value but allow lossless recovery\n * when the token map is retained.\n *\n * This module provides low-level building blocks used by the public\n * `tokenize()` / `detokenize()` API in `src/tokenize.ts`.\n */\n\nimport type { TokenFormat } from \"../types.js\";\n\n/**\n * A mutable in-memory token store mapping token→value and value→token.\n * Scoped to a single tokenisation session.\n *\n * @public\n */\nexport interface TokenStore {\n /** Map: token string → original PII value */\n readonly tokens: Map<string, string>;\n /** Map: `\"CATEGORY:normalizedValue\"` → existing token (for dedup) */\n readonly index: Map<string, string>;\n /** Per-category counters for generating sequential token IDs */\n readonly counters: Map<string, number>;\n}\n\n/** Create an empty token store. */\nexport function createTokenStore(): TokenStore {\n return {\n tokens: new Map(),\n index: new Map(),\n counters: new Map(),\n };\n}\n\n/**\n * Produce a new or existing token for `(category, value)`.\n *\n * Tokens are *deduplicated* — the same value in the same category always\n * receives the same token within a session.\n *\n * @param store - The active token store.\n * @param category - The PII category (e.g. `\"email\"`).\n * @param value - The original PII string.\n * @param prefix - Category prefix used in the token label (e.g. `\"EMAIL\"`).\n * @param format - Token format: `\"bracket\"` (`[EMAIL_0001]`) or `\"angle\"` (`<EMAIL_1>`).\n * @returns The deterministic token string.\n */\nexport function assignToken(\n store: TokenStore,\n category: string,\n value: string,\n prefix: string,\n format: TokenFormat = \"bracket\",\n): string {\n const indexKey = `${prefix}:${value.toLowerCase()}`;\n const existing = store.index.get(indexKey);\n if (existing !== undefined) return existing;\n\n const count = (store.counters.get(prefix) ?? 0) + 1;\n store.counters.set(prefix, count);\n\n const id = format === \"bracket\" ? String(count).padStart(4, \"0\") : String(count);\n const token = format === \"bracket\" ? `[${prefix}_${id}]` : `<${prefix}_${id}>`;\n\n store.index.set(indexKey, token);\n store.tokens.set(token, value);\n return token;\n}\n\n/**\n * Replace a token with its original value. Returns `undefined` when the token\n * is not found in `store`.\n *\n * @param store - The active token store.\n * @param token - The token to resolve.\n */\nexport function resolveToken(store: TokenStore, token: string): string | undefined {\n return store.tokens.get(token);\n}\n\n/**\n * Restore all tokens in `text` using `store`.\n * Tokens that are not found in `store` are left unchanged.\n *\n * @param text - The tokenized text.\n * @param store - The token store from the original tokenization call.\n * @returns The restored text and a list of any unresolved tokens.\n */\nexport function detokenizeText(\n text: string,\n store: TokenStore,\n): { text: string; unresolved: string[] } {\n const unresolved: string[] = [];\n\n // Match both bracket `[PREFIX_NNNN]` and angle `<PREFIX_N>` format tokens.\n const re = /(\\[[A-Z_]+_\\d+\\]|<[A-Z_]+_\\d+>)/g;\n\n const result = text.replace(re, (token) => {\n const original = store.tokens.get(token);\n if (original !== undefined) return original;\n unresolved.push(token);\n return token;\n });\n\n return { text: result, unresolved };\n}\n","/**\n * @module internal/allowlist\n * @description Allowlist matching of the 1.x functions: the detected values\n * that the caller lists are left untouched.\n * @internal\n */\n\n/**\n * Compile an allowlist into a predicate that tells whether a detected value\n * is allowlisted.\n *\n * A string entry matches a value equal to it, ignoring case unless\n * `caseSensitive` is set; a value that merely contains an entry does not\n * match. A pattern matches a value it finds a match in. Its `g` and `y` flags\n * are dropped, so that no value depends on the values tested before it and\n * the caller's `RegExp` keeps its `lastIndex`.\n *\n * @param entries - Exact values to leave untouched.\n * @param patterns - Patterns of values to leave untouched.\n * @param caseSensitive - Whether entries are compared case-sensitively.\n * @returns A predicate that returns `true` for an allowlisted value.\n * @internal\n */\nexport function compileAllowlist(\n entries: readonly string[],\n patterns: readonly RegExp[],\n caseSensitive: boolean,\n): (value: string) => boolean {\n if (entries.length === 0 && patterns.length === 0) return () => false;\n\n const exact = new Set(entries.map((entry) => (caseSensitive ? entry : entry.toLowerCase())));\n const compiled = patterns.map(\n (pattern) => new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, \"\")),\n );\n\n return (value) =>\n exact.has(caseSensitive ? value : value.toLowerCase()) ||\n compiled.some((pattern) => pattern.test(value));\n}\n","/**\n * @module anonymize\n * @description Core anonymization engine — detects PII and applies strategies.\n */\n\nimport { DETECTOR_REGISTRY, AGGRESSIVE_DETECTOR_REGISTRY } from \"./detectors/index.js\";\nimport { createTokenStore, assignToken as assignTokenFn } from \"./strategies/tokenize.js\";\nimport { mask } from \"./strategies/mask.js\";\nimport { redact } from \"./strategies/redact.js\";\nimport { pseudonymize } from \"./strategies/pseudonymize.js\";\nimport { generalize } from \"./strategies/generalize.js\";\nimport {\n UnsupportedStrategyError,\n UnknownCategoryError,\n ValidationError,\n PresetNotFoundError,\n} from \"./errors.js\";\nimport { getPreset } from \"./presets.js\";\nimport { compileAllowlist } from \"./internal/allowlist.js\";\nimport type {\n AnonymizeOptions,\n AnonymizeResult,\n AnonymizerConfig,\n Anonymizer,\n FieldRuleMap,\n PiiCategory,\n PiiMatch,\n StrategyOptions,\n Detector,\n CustomPattern,\n TokenizeOptions,\n TokenMatch,\n} from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\n/** All recognised PII category names. */\nconst ALL_CATEGORIES: readonly PiiCategory[] = [\n \"email\",\n \"phone\",\n \"ssn\",\n \"credit-card\",\n \"ipv4\",\n \"ipv6\",\n \"url\",\n \"iban\",\n \"date-of-birth\",\n \"name\",\n \"address\",\n \"passport\",\n \"drivers-license\",\n \"national-id\",\n \"bank-account\",\n \"cryptocurrency\",\n \"tax-id\",\n \"medical-record\",\n \"health-insurance\",\n \"prescription\",\n \"api-key\",\n \"social-media\",\n \"vin\",\n \"license-plate\",\n \"tracking-number\",\n \"case-number\",\n \"company-registration\",\n] as const;\n\n/**\n * Category → token prefix mapping for `consistentTokens` mode.\n * @internal\n */\nconst TOKEN_PREFIX_MAP: Readonly<Record<PiiCategory, string>> = {\n email: \"EMAIL\",\n phone: \"PHONE\",\n ssn: \"SSN\",\n \"credit-card\": \"CREDIT_CARD\",\n ipv4: \"IPV4\",\n ipv6: \"IPV6\",\n url: \"URL\",\n iban: \"IBAN\",\n \"date-of-birth\": \"DATE\",\n name: \"PERSON\",\n address: \"ADDRESS\",\n passport: \"PASSPORT\",\n \"drivers-license\": \"DRIVERS_LICENSE\",\n \"national-id\": \"NATIONAL_ID\",\n \"bank-account\": \"BANK_ACCOUNT\",\n cryptocurrency: \"CRYPTO\",\n \"tax-id\": \"TAX_ID\",\n \"medical-record\": \"MEDICAL_RECORD\",\n \"health-insurance\": \"HEALTH_INSURANCE\",\n prescription: \"PRESCRIPTION\",\n \"api-key\": \"API_KEY\",\n \"social-media\": \"SOCIAL_MEDIA\",\n vin: \"VIN\",\n \"license-plate\": \"LICENSE_PLATE\",\n \"tracking-number\": \"TRACKING_NUMBER\",\n \"case-number\": \"CASE_NUMBER\",\n \"company-registration\": \"COMPANY_REG\",\n} as const;\n\n/**\n * Apply a single strategy synchronously. The `hash` strategy is async but\n * for text-level anonymization we need synchronous replacement. We use\n * pseudonymize as a deterministic fallback for hash in sync contexts.\n *\n * @remarks\n * ⚠️ **`hash` fallback**: When `hash` is used in a synchronous `anonymize()`\n * call, it falls back to a deterministic pseudonym. If true SHA-256 hashing is\n * required, call `hash()` directly (it returns a `Promise<string>`).\n *\n * @internal\n */\nfunction applyStrategySync(value: string, opts: StrategyOptions): string {\n switch (opts.strategy) {\n case \"mask\":\n return mask(value, opts);\n case \"redact\":\n return redact(value, opts);\n case \"pseudonymize\":\n return pseudonymize(value, opts);\n case \"hash\":\n // Hash is async; callers that need true hashing should use hashValue() directly.\n // For the synchronous pipeline we fall back to a deterministic pseudonym.\n // eslint-disable-next-line no-console\n console.warn(\n \"[anonyma] The `hash` strategy is async and cannot be used in the synchronous \" +\n \"`anonymize()` pipeline. Falling back to a deterministic pseudonym. \" +\n \"Use `anonymizeAsync()` or `hash()` for SHA-256 output.\",\n );\n return pseudonymize(value, { seed: opts.pepper ?? \"__hash_fallback__\", prefix: \"hsh_\" });\n case \"generalize\":\n return generalize(value, opts);\n case \"tokenize\":\n case \"encrypt\":\n case \"synthesize\":\n // Neither anonymize() nor anonymizeAsync() applies these strategies: the\n // value is redacted. The span engine applies all of them.\n // eslint-disable-next-line no-console\n console.warn(\n `[anonyma] anonymize() and anonymizeAsync() do not apply the \\`${opts.strategy}\\` ` +\n `strategy; the value is redacted instead. Use a pipeline of \"anonyma/engine\" ` +\n `to apply it.`,\n );\n return redact(value);\n default: {\n // Exhaustiveness check — TypeScript should never reach here.\n const _exhaustive: never = opts;\n throw new UnsupportedStrategyError((_exhaustive as StrategyOptions).strategy);\n }\n }\n}\n\n/**\n * Sort and de-duplicate an array of PII matches by position.\n * When matches overlap, the one with the higher confidence wins.\n *\n * Works on any match-like object that has `start`, `end`, and `confidence`.\n *\n * @internal\n */\nfunction deduplicateMatches<T extends { start: number; end: number; confidence: number }>(\n matches: T[],\n): T[] {\n // Sort by start position; on ties prefer higher confidence.\n const sorted = [...matches].sort((a, b) => a.start - b.start || b.confidence - a.confidence);\n\n const result: T[] = [];\n let cursor = 0;\n\n for (const m of sorted) {\n if (m.start >= cursor) {\n result.push(m);\n cursor = m.end;\n }\n }\n\n return result;\n}\n\n/**\n * Get the active detector for a category, merging custom overrides.\n *\n * @internal\n */\nfunction resolveDetector(\n category: PiiCategory,\n customDetectors?: Partial<Record<PiiCategory, Detector>>,\n aggressive?: boolean,\n): Detector {\n if (customDetectors?.[category]) return customDetectors[category];\n return aggressive ? AGGRESSIVE_DETECTOR_REGISTRY[category] : DETECTOR_REGISTRY[category];\n}\n\n/**\n * Internal representation of a custom pattern match used within the\n * anonymization pipeline. Not exposed publicly.\n *\n * @internal\n */\ninterface CustomMatch {\n readonly category: string;\n readonly value: string;\n readonly start: number;\n readonly end: number;\n readonly confidence: number;\n readonly replacement: string;\n}\n\n/**\n * Run custom patterns against `text` and produce CustomMatch objects.\n *\n * @internal\n */\nfunction detectCustomPatterns(\n text: string,\n customPatterns: readonly CustomPattern[],\n): CustomMatch[] {\n const results: CustomMatch[] = [];\n\n for (const cp of customPatterns) {\n if (!(cp.pattern instanceof RegExp)) {\n throw new ValidationError(\"customPatterns[].pattern\", \"must be a RegExp instance\");\n }\n\n // Ensure global flag is set; create a fresh copy to avoid lastIndex mutation.\n const flags = cp.pattern.flags.includes(\"g\") ? cp.pattern.flags : cp.pattern.flags + \"g\";\n const re = new RegExp(cp.pattern.source, flags);\n const category = cp.category ?? \"custom\";\n const confidence = cp.confidence ?? 0.85;\n const label = cp.label ?? \"[REDACTED]\";\n\n let m: RegExpExecArray | null;\n while ((m = re.exec(text)) !== null) {\n results.push({\n category,\n value: m[0],\n start: m.index,\n end: m.index + m[0].length,\n confidence,\n replacement: label,\n });\n }\n }\n\n return results;\n}\n\n/**\n * Resolve the list of categories to detect from `AnonymizeOptions`.\n * Handles `rules`, `enabledCategories`, and defaults.\n *\n * @internal\n */\nfunction resolveCategories(options: AnonymizeOptions): PiiCategory[] {\n const { rules = [], enabledCategories } = options;\n\n if (rules.length > 0) {\n // rules takes priority — only scan the explicitly listed categories.\n return rules.map((r) => r.category);\n }\n\n if (enabledCategories) {\n return ALL_CATEGORIES.filter((cat) => enabledCategories[cat] === true);\n }\n\n return [...ALL_CATEGORIES];\n}\n\n// ---------------------------------------------------------------------------\n// Public: detect()\n// ---------------------------------------------------------------------------\n\n/**\n * Detect all PII in `text` using the built-in detectors.\n *\n * @param text - The input string to scan.\n * @param categories - Optional subset of categories to check. Defaults to all.\n * @param customDetectors - Optional overrides for built-in detectors.\n * @param aggressive - When `true`, use expanded pattern sets for each detector.\n * @returns A sorted array of non-overlapping {@link PiiMatch} objects.\n *\n * @example\n * ```ts\n * import { detect } from \"anonyma\";\n *\n * detect(\"Email: alice@example.com, IP: 192.168.1.1\");\n * // [\n * // { category: \"email\", value: \"alice@example.com\", start: 7, end: 24, confidence: 0.99 },\n * // { category: \"ipv4\", value: \"192.168.1.1\", start: 30, end: 41, confidence: 0.98 },\n * // ]\n * ```\n */\nexport function detect(\n text: string,\n categories: readonly PiiCategory[] = ALL_CATEGORIES,\n customDetectors?: Partial<Record<PiiCategory, Detector>>,\n aggressive?: boolean,\n): PiiMatch[] {\n if (typeof text !== \"string\") {\n throw new ValidationError(\"text\", \"must be a string\");\n }\n\n const raw: PiiMatch[] = [];\n\n for (const category of categories) {\n if (!ALL_CATEGORIES.includes(category)) {\n throw new UnknownCategoryError(category);\n }\n const detector = resolveDetector(category, customDetectors, aggressive);\n raw.push(...detector(text));\n }\n\n return deduplicateMatches(raw);\n}\n\n// ---------------------------------------------------------------------------\n// Public: hasPII()\n// ---------------------------------------------------------------------------\n\n/**\n * Return `true` if `text` contains any detectable PII, `false` otherwise.\n *\n * Uses an early-exit optimisation — scanning stops after the first match is\n * found. Useful for validation gates and conditional processing pipelines.\n *\n * @param text - The input string to scan.\n * @param categories - Optional subset of categories to check. Defaults to all.\n * @param customDetectors - Optional overrides for built-in detectors.\n * @returns `true` if any PII is detected; `false` otherwise.\n *\n * @example\n * ```ts\n * import { hasPII } from \"anonyma\";\n *\n * if (hasPII(commentText)) {\n * return { error: \"Comment contains personal information.\" };\n * }\n * ```\n */\nexport function hasPII(\n text: string,\n categories: readonly PiiCategory[] = ALL_CATEGORIES,\n customDetectors?: Partial<Record<PiiCategory, Detector>>,\n): boolean {\n if (typeof text !== \"string\") {\n throw new ValidationError(\"text\", \"must be a string\");\n }\n\n for (const category of categories) {\n if (!ALL_CATEGORIES.includes(category)) {\n throw new UnknownCategoryError(category);\n }\n const detector = resolveDetector(category, customDetectors);\n if (detector(text).length > 0) return true;\n }\n\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// Public: anonymize()\n// ---------------------------------------------------------------------------\n\n/**\n * Detect and anonymize all PII in `text`.\n *\n * Operates in a single left-to-right pass: detected matches are replaced in\n * reverse order (right-to-left) to preserve correct string offsets.\n *\n * @param text - The input string to anonymize.\n * @param options - Anonymization configuration.\n * @returns An {@link AnonymizeResult} containing the anonymized text and\n * optionally the detected matches.\n *\n * @example\n * ```ts\n * import { anonymize } from \"anonyma\";\n *\n * anonymize(\"Contact alice@example.com or call 555-867-5309.\");\n * // { text: \"Contact [REDACTED] or call [REDACTED].\", matches: [] }\n *\n * // Consistent tokens — same value gets same label\n * anonymize(\"alice@example.com and alice@example.com again\", { consistentTokens: true });\n * // { text: \"EMAIL_1 and EMAIL_1 again\", matches: [] }\n *\n * // Aggressive mode — catches obfuscated PII\n * anonymize(\"Email user [at] example [dot] com\", { aggressive: true });\n * // { text: \"Email [REDACTED]\", matches: [] }\n * ```\n */\nexport function anonymize(text: string, options: AnonymizeOptions = {}): AnonymizeResult {\n if (typeof text !== \"string\") {\n throw new ValidationError(\"text\", \"must be a string\");\n }\n\n if (options.globalReplacement?.trim().length === 0) {\n throw new ValidationError(\"globalReplacement\", \"must not be an empty string\");\n }\n\n // Resolve preset if provided.\n let resolvedPreset: ReturnType<typeof getPreset> | undefined;\n if (options.preset) {\n try {\n resolvedPreset = getPreset(options.preset);\n } catch {\n throw new PresetNotFoundError(options.preset);\n }\n }\n\n const {\n rules = resolvedPreset\n ? resolvedPreset.categories.map((category) => ({\n category,\n strategy:\n resolvedPreset.rules?.find((r) => r.category === category)?.strategy ??\n resolvedPreset.defaultStrategy,\n }))\n : [],\n defaultStrategy = resolvedPreset?.defaultStrategy ?? { strategy: \"redact\" as const },\n includeMatches = false,\n customDetectors,\n customPatterns = [],\n globalReplacement,\n consistentTokens = false,\n aggressive = false,\n enabledCategories,\n allowlist = [],\n allowlistPatterns = [],\n allowlistCaseSensitive = false,\n confidenceThreshold = 0,\n } = options;\n\n // Build a category → strategy map from the rules array.\n const ruleMap = new Map<PiiCategory, StrategyOptions>();\n for (const rule of rules) {\n if (!ALL_CATEGORIES.includes(rule.category)) {\n throw new UnknownCategoryError(rule.category);\n }\n ruleMap.set(rule.category, rule.strategy);\n }\n\n // Resolve which categories to scan.\n const categories = resolveCategories({\n rules,\n ...(enabledCategories !== undefined ? { enabledCategories } : {}),\n });\n\n // True for a value that must NOT be anonymized even if detected as PII.\n const isAllowlisted = compileAllowlist(allowlist, allowlistPatterns, allowlistCaseSensitive);\n\n // Run built-in detectors.\n const builtInMatches = detect(text, categories, customDetectors, aggressive);\n\n // Run custom patterns.\n const customMatches = customPatterns.length > 0 ? detectCustomPatterns(text, customPatterns) : [];\n\n // Apply allowlist + confidenceThreshold filtering to built-in matches.\n const filteredBuiltInMatches = builtInMatches.filter(\n (m) => m.confidence >= confidenceThreshold && !isAllowlisted(m.value),\n );\n\n // Combine and deduplicate all matches by position.\n type UnifiedMatch = (PiiMatch & { replacement?: string }) | CustomMatch;\n const allRaw: UnifiedMatch[] = [...filteredBuiltInMatches, ...customMatches];\n const allDeduped = deduplicateMatches(allRaw);\n\n // --- Consistent token state (scoped to this call only) ---\n const tokenMap = new Map<string, string>(); // key: \"category:normalizedValue\" → token\n const tokenCounters = new Map<string, number>(); // key: prefix → counter\n\n function assignToken(category: string, value: string): string {\n const prefix =\n (TOKEN_PREFIX_MAP as Readonly<Record<string, string | undefined>>)[category] ??\n category.toUpperCase();\n const key = `${prefix}:${value.toLowerCase()}`;\n const existing = tokenMap.get(key);\n if (existing) return existing;\n const count = (tokenCounters.get(prefix) ?? 0) + 1;\n tokenCounters.set(prefix, count);\n const token = `${prefix}_${String(count)}`;\n tokenMap.set(key, token);\n return token;\n }\n\n // Apply strategies in reverse order to preserve indices.\n let result = text;\n const reversed = [...allDeduped].reverse();\n\n for (const match of reversed) {\n let replacement: string;\n\n if (globalReplacement !== undefined) {\n replacement = globalReplacement;\n } else if (consistentTokens) {\n replacement = assignToken(match.category, match.value);\n } else if (\"replacement\" in match) {\n // Pre-computed replacement from custom pattern.\n replacement = match.replacement;\n } else {\n // Built-in PII match: look up per-category rule or fall back to default.\n const strategy = ruleMap.get(match.category) ?? defaultStrategy;\n replacement = applyStrategySync(match.value, strategy);\n }\n\n result = result.slice(0, match.start) + replacement + result.slice(match.end);\n }\n\n // Only include built-in PiiMatch objects in the public result (custom matches\n // have a non-PiiCategory category and are not part of the public API surface).\n const reportedMatches = includeMatches ? filteredBuiltInMatches : [];\n\n return {\n text: result,\n matches: reportedMatches,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Public: anonymizeAsync()\n// ---------------------------------------------------------------------------\n\n/**\n * Asynchronous version of {@link anonymize}. Supports the `hash` strategy\n * (uses true SHA-256 via the Web Crypto API) and future async strategies\n * (`tokenize`, `encrypt`, `synthesize`).\n *\n * Falls back to the synchronous implementation for all other strategies.\n *\n * @param text - The input string to anonymize.\n * @param options - Anonymization configuration. Supports the same options as\n * {@link anonymize} plus `hash` strategy with actual SHA-256 output.\n * @returns A promise that resolves to an {@link AnonymizeResult}.\n *\n * @example\n * ```ts\n * import { anonymizeAsync } from \"anonyma\";\n *\n * const result = await anonymizeAsync(\"Contact alice@example.com\", {\n * defaultStrategy: { strategy: \"hash\" },\n * });\n * // { text: \"Contact <sha256-hex>\", matches: [] }\n * ```\n */\nexport async function anonymizeAsync(\n text: string,\n options: AnonymizeOptions = {},\n): Promise<AnonymizeResult> {\n if (typeof text !== \"string\") {\n throw new ValidationError(\"text\", \"must be a string\");\n }\n\n // For strategies that don't involve async primitives, delegate to sync.\n const hasAsyncStrategy = (opts: StrategyOptions): boolean =>\n opts.strategy === \"hash\" ||\n opts.strategy === \"encrypt\" ||\n opts.strategy === \"tokenize\" ||\n opts.strategy === \"synthesize\";\n\n const needsAsync =\n (options.defaultStrategy != null && hasAsyncStrategy(options.defaultStrategy)) ||\n (options.rules ?? []).some((r) => hasAsyncStrategy(r.strategy));\n\n if (!needsAsync) {\n return anonymize(text, options);\n }\n\n // Lazy-import to avoid circular dependency on strategies not yet in the\n // synchronous bundle (hash is async-native, others upcoming).\n const { hash: hashFn } = await import(\"./strategies/hash.js\");\n\n // Resolve identical logic as sync path.\n let resolvedPreset: ReturnType<typeof getPreset> | undefined;\n if (options.preset) {\n try {\n resolvedPreset = getPreset(options.preset);\n } catch {\n throw new PresetNotFoundError(options.preset);\n }\n }\n\n const {\n rules = resolvedPreset\n ? resolvedPreset.categories.map((category) => ({\n category,\n strategy:\n resolvedPreset.rules?.find((r) => r.category === category)?.strategy ??\n resolvedPreset.defaultStrategy,\n }))\n : [],\n defaultStrategy = resolvedPreset?.defaultStrategy ?? { strategy: \"redact\" as const },\n includeMatches = false,\n customDetectors,\n customPatterns = [],\n globalReplacement,\n consistentTokens = false,\n aggressive = false,\n enabledCategories,\n allowlist = [],\n allowlistPatterns = [],\n allowlistCaseSensitive = false,\n confidenceThreshold = 0,\n } = options;\n\n const ruleMap = new Map<PiiCategory, StrategyOptions>();\n for (const rule of rules) {\n if (!ALL_CATEGORIES.includes(rule.category)) throw new UnknownCategoryError(rule.category);\n ruleMap.set(rule.category, rule.strategy);\n }\n\n const categories = resolveCategories({\n rules,\n ...(enabledCategories !== undefined ? { enabledCategories } : {}),\n });\n\n const builtInMatches = detect(text, categories, customDetectors, aggressive);\n const customMatches = customPatterns.length > 0 ? detectCustomPatterns(text, customPatterns) : [];\n\n const isAllowlisted = compileAllowlist(allowlist, allowlistPatterns, allowlistCaseSensitive);\n\n const filteredBuiltInMatches = builtInMatches.filter(\n (m) => m.confidence >= confidenceThreshold && !isAllowlisted(m.value),\n );\n\n type UnifiedMatch = (PiiMatch & { replacement?: string }) | CustomMatch;\n const allRaw: UnifiedMatch[] = [...filteredBuiltInMatches, ...customMatches];\n const allDeduped = deduplicateMatches(allRaw);\n\n const tokenMap = new Map<string, string>();\n const tokenCounters = new Map<string, number>();\n function assignToken(category: string, value: string): string {\n const prefix =\n (TOKEN_PREFIX_MAP as Readonly<Record<string, string | undefined>>)[category] ??\n category.toUpperCase();\n const key = `${prefix}:${value.toLowerCase()}`;\n const existing = tokenMap.get(key);\n if (existing) return existing;\n const count = (tokenCounters.get(prefix) ?? 0) + 1;\n tokenCounters.set(prefix, count);\n const token = `${prefix}_${String(count)}`;\n tokenMap.set(key, token);\n return token;\n }\n\n let result = text;\n const reversed = [...allDeduped].reverse();\n\n for (const match of reversed) {\n let replacement: string;\n\n if (globalReplacement !== undefined) {\n replacement = globalReplacement;\n } else if (consistentTokens) {\n replacement = assignToken(match.category, match.value);\n } else if (\"replacement\" in match) {\n replacement = match.replacement;\n } else {\n const strategy = ruleMap.get(match.category) ?? defaultStrategy;\n if (strategy.strategy === \"hash\") {\n replacement = await hashFn(match.value, strategy);\n } else {\n replacement = applyStrategySync(match.value, strategy);\n }\n }\n\n result = result.slice(0, match.start) + replacement + result.slice(match.end);\n }\n\n return {\n text: result,\n matches: includeMatches ? filteredBuiltInMatches : [],\n };\n}\n\n// ---------------------------------------------------------------------------\n// Public: anonymizeObject()\n// ---------------------------------------------------------------------------\n\n/**\n * Recursively anonymize every string value found in a JSON-serializable object\n * tree. Returns a deep clone — the input is never mutated.\n *\n * Handles:\n * - Plain objects (nested to any depth)\n * - Arrays (including mixed-type arrays)\n * - Primitive values (`null`, `undefined`, numbers, booleans) — passed through unchanged\n * - Circular references — throws {@link ValidationError}\n *\n * @param obj - The root object to anonymize. Must be free of circular references.\n * @param options - Optional anonymization configuration forwarded to `anonymize()`.\n * @returns A new object of the same shape with all string values anonymized.\n *\n * @throws {@link ValidationError} When `obj` contains a circular reference or is not an object.\n *\n * @example\n * ```ts\n * import { anonymizeObject } from \"anonyma\";\n *\n * const result = anonymizeObject({\n * user: { name: \"Alice\", email: \"alice@example.com\" },\n * notes: [\"Call 555-867-5309\", \"No PII here\"],\n * });\n * // {\n * // user: { name: \"Alice\", email: \"[REDACTED]\" },\n * // notes: [\"[REDACTED]\", \"No PII here\"],\n * // }\n * ```\n */\nexport function anonymizeObject<T extends object>(obj: T, options?: AnonymizeOptions): T {\n if (typeof obj !== \"object\") {\n throw new ValidationError(\"obj\", \"must be an object\");\n }\n return deepAnonymizeValue(obj, options, new WeakSet()) as T;\n}\n\n/**\n * Recursive implementation for `anonymizeObject`.\n * `seen` tracks visited objects to detect circular references.\n *\n * @internal\n */\nfunction deepAnonymizeValue(\n value: unknown,\n options: AnonymizeOptions | undefined,\n seen: WeakSet<object>,\n): unknown {\n if (value === null || value === undefined) return value;\n\n if (typeof value === \"string\") {\n return anonymize(value, options).text;\n }\n\n if (typeof value !== \"object\") {\n // numbers, booleans, Symbols, BigInts — pass through unchanged.\n return value;\n }\n\n if (seen.has(value)) {\n throw new ValidationError(\"obj\", \"contains a circular reference\");\n }\n seen.add(value);\n\n if (Array.isArray(value)) {\n const result = value.map((item) => deepAnonymizeValue(item, options, seen));\n seen.delete(value as object);\n return result;\n }\n\n // Plain object.\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(value as Record<string, unknown>)) {\n result[key] = deepAnonymizeValue((value as Record<string, unknown>)[key], options, seen);\n }\n seen.delete(value);\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Public: anonymizeRecord()\n// ---------------------------------------------------------------------------\n\n/**\n * Safely get a nested value from a plain record using dot-notation path.\n *\n * @internal\n */\nfunction getByPath(obj: Record<string, unknown>, path: string): unknown {\n const parts = path.split(\".\");\n let current: unknown = obj;\n\n for (const part of parts) {\n if (current === null || typeof current !== \"object\" || Array.isArray(current)) {\n return undefined;\n }\n // Safe: we check isObject above.\n current = (current as Record<string, unknown>)[part];\n }\n\n return current;\n}\n\n/**\n * Safely set a nested value on a plain record using dot-notation path.\n * Returns a new object (shallow clone at each level touched).\n *\n * @internal\n */\nfunction setByPath(\n obj: Record<string, unknown>,\n path: string,\n value: unknown,\n): Record<string, unknown> {\n const parts = path.split(\".\");\n\n if (parts.length === 1) {\n return { ...obj, [path]: value };\n }\n\n const [head, ...tail] = parts as [string, ...string[]];\n // setByPath is only called after getByPath confirmed the path exists, so obj[head] is\n // always defined in practice. The `?? {}` fallback is a defensive guard.\n /* v8 ignore next */\n const nested = (obj[head] ?? {}) as Record<string, unknown>;\n return {\n ...obj,\n [head]: setByPath(nested, tail.join(\".\"), value),\n };\n}\n\n/**\n * Anonymize specific fields in a plain record using field-level rules.\n * Supports dot-notation paths for nested fields.\n *\n * This function returns a new record — it never mutates the input.\n *\n * @param record - The input record.\n * @param rules - A map of field path → {@link FieldRule}.\n * @returns A new record with the specified fields anonymized.\n *\n * @example\n * ```ts\n * import { anonymizeRecord } from \"anonyma\";\n *\n * anonymizeRecord(\n * { name: \"Alice\", email: \"alice@example.com\", age: \"27\" },\n * {\n * email: { strategy: { strategy: \"mask\", keepLeading: 1, keepTrailing: 3 } },\n * age: { strategy: { strategy: \"generalize\" } },\n * }\n * );\n * // { name: \"Alice\", email: \"a***************com\", age: \"20-29\" }\n * ```\n */\nexport function anonymizeRecord<T extends Record<string, unknown>>(\n record: T,\n rules: FieldRuleMap,\n): T {\n if (typeof record !== \"object\" || Array.isArray(record)) {\n throw new ValidationError(\"record\", \"must be a plain object\");\n }\n\n let result: Record<string, unknown> = { ...record };\n\n for (const [path, rule] of Object.entries(rules)) {\n if (Object.prototype.hasOwnProperty.call(rules, path)) {\n const raw = getByPath(result, path);\n if (raw === undefined || raw === null) continue;\n if (typeof raw !== \"string\" && typeof raw !== \"number\" && typeof raw !== \"boolean\") continue;\n\n const strValue = String(raw);\n const anonymized = applyStrategySync(strValue, rule.strategy);\n result = setByPath(result, path, anonymized);\n }\n }\n\n return result as T;\n}\n\n// ---------------------------------------------------------------------------\n// Public: createAnonymizer()\n// ---------------------------------------------------------------------------\n\n/**\n * Create a reusable, pre-configured {@link Anonymizer} instance.\n *\n * @param config - Anonymizer configuration.\n * @returns A configured {@link Anonymizer}.\n *\n * @example\n * ```ts\n * import { createAnonymizer } from \"anonyma\";\n *\n * const anonymizer = createAnonymizer({\n * categories: [\"email\", \"phone\"],\n * defaultStrategy: { strategy: \"mask\", keepLeading: 0, keepTrailing: 4 },\n * });\n *\n * anonymizer.anonymize(\"Call 555-867-5309 or email alice@example.com\");\n * // { text: \"Call ****5309 or email **.com\", matches: [] }\n *\n * anonymizer.hasPII(\"No PII here\");\n * // false\n *\n * anonymizer.anonymizeObject({ email: \"alice@example.com\", score: 42 });\n * // { email: \"[REDACTED]\", score: 42 }\n * ```\n */\nexport function createAnonymizer(config: AnonymizerConfig = {}): Anonymizer {\n // Resolve preset first so its defaults can be overridden by explicit config.\n let presetConfig: ReturnType<typeof getPreset> | undefined;\n if (config.preset) {\n try {\n presetConfig = getPreset(config.preset);\n } catch {\n throw new PresetNotFoundError(config.preset);\n }\n }\n\n const {\n categories = presetConfig ? presetConfig.categories : [...ALL_CATEGORIES],\n defaultStrategy = presetConfig?.defaultStrategy ?? { strategy: \"redact\" as const },\n customDetectors,\n customPatterns,\n globalReplacement,\n consistentTokens,\n aggressive,\n } = config;\n\n // Validate categories up-front.\n for (const cat of categories) {\n if (!ALL_CATEGORIES.includes(cat)) {\n throw new UnknownCategoryError(cat);\n }\n }\n\n /** Shared base options derived from config. */\n function baseOptions(overrides?: Partial<AnonymizeOptions>): AnonymizeOptions {\n const base: AnonymizeOptions = {\n defaultStrategy,\n ...(customDetectors !== undefined ? { customDetectors } : {}),\n ...(customPatterns !== undefined ? { customPatterns } : {}),\n ...(globalReplacement !== undefined ? { globalReplacement } : {}),\n ...(consistentTokens !== undefined ? { consistentTokens } : {}),\n ...(aggressive !== undefined ? { aggressive } : {}),\n ...overrides,\n rules:\n overrides?.rules ??\n (presetConfig\n ? presetConfig.categories.map((category) => ({\n category,\n strategy:\n presetConfig.rules?.find((r) => r.category === category)?.strategy ??\n defaultStrategy,\n }))\n : categories.map((category) => ({\n category,\n strategy: defaultStrategy,\n }))),\n };\n return base;\n }\n\n return {\n anonymize(text: string, options?: Partial<AnonymizeOptions>): AnonymizeResult {\n return anonymize(text, baseOptions(options));\n },\n\n detect(text: string): PiiMatch[] {\n return detect(text, categories, customDetectors, aggressive);\n },\n\n anonymizeRecord<T extends Record<string, unknown>>(record: T, rules: FieldRuleMap): T {\n return anonymizeRecord(record, rules);\n },\n\n anonymizeObject<T extends object>(obj: T, options?: AnonymizeOptions): T {\n return anonymizeObject(obj, baseOptions(options));\n },\n\n async anonymizeAsync(\n text: string,\n options?: Partial<AnonymizeOptions>,\n ): Promise<AnonymizeResult> {\n return anonymizeAsync(text, baseOptions(options));\n },\n\n tokenize(text: string, options?: TokenizeOptions): ReturnType<Anonymizer[\"tokenize\"]> {\n // Inline implementation to avoid circular dependency (tokenize.ts imports detectFn)\n const {\n categories: tCats,\n format = \"bracket\",\n customDetectors: tCustDet,\n aggressive: tAgg = aggressive,\n confidenceThreshold: tConfidence = 0,\n allowlist: tAllowlist = [],\n allowlistCaseSensitive: tCaseSensitive = false,\n } = options ?? {};\n\n const isAllowlisted = compileAllowlist(tAllowlist, [], tCaseSensitive);\n\n const tMatches = detect(text, tCats ?? categories, tCustDet ?? customDetectors, tAgg).filter(\n (m) => m.confidence >= tConfidence && !isAllowlisted(m.value),\n );\n\n const store = createTokenStore();\n let tResult = text;\n const tTokens: TokenMatch[] = [];\n for (const match of [...tMatches].reverse()) {\n // detect() exclusively returns PiiCategory matches, so the toUpperCase() fallback\n // is unreachable through the public API.\n /* v8 ignore next */\n const prefix = TOKEN_PREFIX_MAP[match.category];\n const token = assignTokenFn(store, match.category, match.value, prefix, format);\n tTokens.push({\n token,\n original: match.value,\n category: match.category,\n start: match.start,\n end: match.end,\n });\n tResult = tResult.slice(0, match.start) + token + tResult.slice(match.end);\n }\n return { text: tResult, mapping: store.tokens, tokens: tTokens };\n },\n\n hasPII(text: string): boolean {\n return hasPII(text, categories, customDetectors);\n },\n };\n}\n","/**\n * @module tokenize\n * @description High-level reversible tokenization API for anonyma.\n *\n * Unlike `anonymize()` — which is one-way — `tokenize()` replaces PII with\n * opaque tokens that can be restored later via `detokenize()`. This is\n * particularly useful for LLM pipelines where the model receives sanitized\n * text and the output must be un-redacted before delivery.\n *\n * @example\n * ```ts\n * import { tokenize, detokenize } from \"anonyma\";\n *\n * const { text, mapping } = tokenize(\"Contact alice@example.com\");\n * // text: \"Contact [EMAIL_0001]\"\n * // mapping: Map { \"[EMAIL_0001]\" => \"alice@example.com\" }\n *\n * const original = detokenize(text, mapping);\n * // \"Contact alice@example.com\"\n * ```\n */\n\nimport { detect } from \"./anonymize.js\";\nimport { createTokenStore, assignToken, detokenizeText } from \"./strategies/tokenize.js\";\nimport { ValidationError } from \"./errors.js\";\nimport { compileAllowlist } from \"./internal/allowlist.js\";\nimport type { TokenizeResult, DetokenizeResult, TokenizeOptions, TokenMatch } from \"./types.js\";\n\n// Category → token prefix mapping (mirrors TOKEN_PREFIX_MAP in anonymize.ts).\nconst TOKEN_PREFIX_MAP: Record<string, string> = {\n email: \"EMAIL\",\n phone: \"PHONE\",\n ssn: \"SSN\",\n \"credit-card\": \"CREDIT_CARD\",\n ipv4: \"IPV4\",\n ipv6: \"IPV6\",\n url: \"URL\",\n iban: \"IBAN\",\n \"date-of-birth\": \"DATE\",\n name: \"PERSON\",\n address: \"ADDRESS\",\n passport: \"PASSPORT\",\n \"drivers-license\": \"DRIVERS_LICENSE\",\n \"national-id\": \"NATIONAL_ID\",\n \"bank-account\": \"BANK_ACCOUNT\",\n cryptocurrency: \"CRYPTO\",\n \"tax-id\": \"TAX_ID\",\n \"medical-record\": \"MEDICAL_RECORD\",\n \"health-insurance\": \"HEALTH_INSURANCE\",\n prescription: \"PRESCRIPTION\",\n \"api-key\": \"API_KEY\",\n \"social-media\": \"SOCIAL_MEDIA\",\n vin: \"VIN\",\n \"license-plate\": \"LICENSE_PLATE\",\n \"tracking-number\": \"TRACKING_NUMBER\",\n \"case-number\": \"CASE_NUMBER\",\n \"company-registration\": \"COMPANY_REG\",\n};\n\n// ---------------------------------------------------------------------------\n// Public: tokenize()\n// ---------------------------------------------------------------------------\n\n/**\n * Replace all detected PII in `text` with reversible opaque tokens.\n *\n * The returned `mapping` maps each token back to its original value. Pass it\n * to {@link detokenize} to restore the original text.\n *\n * @param text - The input string.\n * @param options - Tokenization options (categories, format, custom detectors…).\n * @returns A {@link TokenizeResult} containing `text` and `mapping`.\n *\n * @example\n * ```ts\n * const { text, mapping } = tokenize(\n * \"Email alice@example.com, phone 555-867-5309\",\n * { categories: [\"email\", \"phone\"], format: \"bracket\" }\n * );\n * // text: \"Email [EMAIL_0001], phone [PHONE_0001]\"\n * // mapping: Map { \"[EMAIL_0001]\" => \"alice@example.com\", \"[PHONE_0001]\" => \"555-867-5309\" }\n * ```\n */\nexport function tokenize(text: string, options: TokenizeOptions = {}): TokenizeResult {\n if (typeof text !== \"string\") throw new ValidationError(\"text\", \"must be a string\");\n\n const {\n categories,\n format = \"bracket\",\n customDetectors,\n aggressive = false,\n confidenceThreshold = 0,\n allowlist = [],\n allowlistCaseSensitive = false,\n } = options;\n\n const isAllowlisted = compileAllowlist(allowlist, [], allowlistCaseSensitive);\n\n // Detect PII.\n const allMatches = detect(text, categories, customDetectors, aggressive).filter(\n (m) => m.confidence >= confidenceThreshold && !isAllowlisted(m.value),\n );\n\n const store = createTokenStore();\n let result = text;\n const reversed = [...allMatches].reverse();\n const tokenMatches: TokenMatch[] = [];\n\n for (const match of reversed) {\n const prefix = TOKEN_PREFIX_MAP[match.category] ?? match.category.toUpperCase();\n const token = assignToken(store, match.category, match.value, prefix, format);\n tokenMatches.push({\n token,\n original: match.value,\n category: match.category,\n start: match.start,\n end: match.end,\n });\n result = result.slice(0, match.start) + token + result.slice(match.end);\n }\n\n return { text: result, mapping: store.tokens, tokens: tokenMatches };\n}\n\n// ---------------------------------------------------------------------------\n// Public: tokenizeAsync()\n// ---------------------------------------------------------------------------\n\n/**\n * Async variant of {@link tokenize} — identical behaviour but returns a Promise.\n * Useful for consistency in async pipelines.\n */\nexport function tokenizeAsync(\n text: string,\n options: TokenizeOptions = {},\n): Promise<TokenizeResult> {\n return Promise.resolve(tokenize(text, options));\n}\n\n// ---------------------------------------------------------------------------\n// Public: detokenize()\n// ---------------------------------------------------------------------------\n\n/**\n * Restore all tokens in `text` using the `mapping` returned by {@link tokenize}.\n *\n * Tokens not present in `mapping` are left unchanged and reported in\n * `unresolved`.\n *\n * @param text - A tokenized string produced by {@link tokenize}.\n * @param mapping - The `mapping` from the matching {@link TokenizeResult}.\n * @returns A {@link DetokenizeResult} with the restored `text` and\n * any `unresolved` tokens.\n *\n * @example\n * ```ts\n * const original = detokenize(\"[EMAIL_0001]\", new Map([[\"[EMAIL_0001]\", \"alice@example.com\"]]));\n * // { text: \"alice@example.com\", unresolved: [] }\n * ```\n */\nexport function detokenize(text: string, mapping: ReadonlyMap<string, string>): DetokenizeResult {\n if (typeof text !== \"string\") throw new ValidationError(\"text\", \"must be a string\");\n\n // Build a temporary store from the mapping.\n const store = createTokenStore();\n for (const [token, value] of mapping) {\n store.tokens.set(token, value);\n }\n\n const result = detokenizeText(text, store);\n // Count how many token occurrences appeared in the text and were resolved.\n // We scan the text for all token-like patterns and subtract the unresolved ones.\n const TOKEN_RE = /(\\[[A-Z_]+_\\d+\\]|<[A-Z_]+_\\d+>)/g;\n const totalInText = (text.match(TOKEN_RE) ?? []).length;\n const replacedCount = totalInText - result.unresolved.length;\n return {\n text: result.text,\n replacedCount,\n unresolved: result.unresolved,\n };\n}\n"]}
@@ -36,6 +36,16 @@ function detokenizeText(text, store) {
36
36
  return { text: result, unresolved };
37
37
  }
38
38
 
39
+ // src/internal/allowlist.ts
40
+ function compileAllowlist(entries, patterns, caseSensitive) {
41
+ if (entries.length === 0 && patterns.length === 0) return () => false;
42
+ const exact = new Set(entries.map((entry) => caseSensitive ? entry : entry.toLowerCase()));
43
+ const compiled = patterns.map(
44
+ (pattern) => new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, ""))
45
+ );
46
+ return (value) => exact.has(caseSensitive ? value : value.toLowerCase()) || compiled.some((pattern) => pattern.test(value));
47
+ }
48
+
39
49
  // src/anonymize.ts
40
50
  var ALL_CATEGORIES = [
41
51
  "email",
@@ -245,16 +255,7 @@ function anonymize(text, options = {}) {
245
255
  rules,
246
256
  ...enabledCategories !== void 0 ? { enabledCategories } : {}
247
257
  });
248
- const compiledAllowlistPatterns = [
249
- ...allowlistPatterns,
250
- ...allowlist.map(
251
- (entry) => new RegExp(entry.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), allowlistCaseSensitive ? "" : "i")
252
- )
253
- ];
254
- function isAllowlisted(value) {
255
- if (compiledAllowlistPatterns.length === 0) return false;
256
- return compiledAllowlistPatterns.some((re) => re.test(value));
257
- }
258
+ const isAllowlisted = compileAllowlist(allowlist, allowlistPatterns, allowlistCaseSensitive);
258
259
  const builtInMatches = detect(text, categories, customDetectors, aggressive);
259
260
  const customMatches = customPatterns.length > 0 ? detectCustomPatterns(text, customPatterns) : [];
260
261
  const filteredBuiltInMatches = builtInMatches.filter(
@@ -344,13 +345,7 @@ async function anonymizeAsync(text, options = {}) {
344
345
  });
345
346
  const builtInMatches = detect(text, categories, customDetectors, aggressive);
346
347
  const customMatches = customPatterns.length > 0 ? detectCustomPatterns(text, customPatterns) : [];
347
- const compiledAllowlistPatterns = [
348
- ...allowlistPatterns,
349
- ...allowlist.map(
350
- (entry) => new RegExp(entry.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), allowlistCaseSensitive ? "" : "i")
351
- )
352
- ];
353
- const isAllowlisted = (value) => compiledAllowlistPatterns.some((re) => re.test(value));
348
+ const isAllowlisted = compileAllowlist(allowlist, allowlistPatterns, allowlistCaseSensitive);
354
349
  const filteredBuiltInMatches = builtInMatches.filter(
355
350
  (m) => m.confidence >= confidenceThreshold && !isAllowlisted(m.value)
356
351
  );
@@ -532,10 +527,7 @@ function createAnonymizer(config = {}) {
532
527
  allowlist: tAllowlist = [],
533
528
  allowlistCaseSensitive: tCaseSensitive = false
534
529
  } = options ?? {};
535
- const tCompiledAllowlist = tAllowlist.map(
536
- (entry) => new RegExp(entry.replace(/[.*+?^${}()|[\\]\\]/g, "\\$&"), tCaseSensitive ? "" : "i")
537
- );
538
- const isAllowlisted = (v) => tCompiledAllowlist.some((re) => re.test(v));
530
+ const isAllowlisted = compileAllowlist(tAllowlist, [], tCaseSensitive);
539
531
  const tMatches = detect(text, tCats ?? categories, tCustDet ?? customDetectors, tAgg).filter(
540
532
  (m) => m.confidence >= tConfidence && !isAllowlisted(m.value)
541
533
  );
@@ -603,10 +595,7 @@ function tokenize(text, options = {}) {
603
595
  allowlist = [],
604
596
  allowlistCaseSensitive = false
605
597
  } = options;
606
- const compiledAllowlist = allowlist.map(
607
- (entry) => new RegExp(entry.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), allowlistCaseSensitive ? "" : "i")
608
- );
609
- const isAllowlisted = (v) => compiledAllowlist.some((re) => re.test(v));
598
+ const isAllowlisted = compileAllowlist(allowlist, [], allowlistCaseSensitive);
610
599
  const allMatches = detect(text, categories, customDetectors, aggressive).filter(
611
600
  (m) => m.confidence >= confidenceThreshold && !isAllowlisted(m.value)
612
601
  );
@@ -658,5 +647,5 @@ exports.detokenize = detokenize;
658
647
  exports.hasPII = hasPII;
659
648
  exports.tokenize = tokenize;
660
649
  exports.tokenizeAsync = tokenizeAsync;
661
- //# sourceMappingURL=chunk-26IHMQHL.cjs.map
662
- //# sourceMappingURL=chunk-26IHMQHL.cjs.map
650
+ //# sourceMappingURL=chunk-ZXPZ7W37.cjs.map
651
+ //# sourceMappingURL=chunk-ZXPZ7W37.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/strategies/tokenize.ts","../src/internal/allowlist.ts","../src/anonymize.ts","../src/tokenize.ts"],"names":["mask","redact","pseudonymize","generalize","UnsupportedStrategyError","AGGRESSIVE_DETECTOR_REGISTRY","DETECTOR_REGISTRY","ValidationError","UnknownCategoryError","getPreset","PresetNotFoundError","assignToken","result","TOKEN_PREFIX_MAP"],"mappings":";;;;;;;AA+BO,SAAS,gBAAA,GAA+B;AAC7C,EAAA,OAAO;AAAA,IACL,MAAA,sBAAY,GAAA,EAAI;AAAA,IAChB,KAAA,sBAAW,GAAA,EAAI;AAAA,IACf,QAAA,sBAAc,GAAA;AAAI,GACpB;AACF;AAeO,SAAS,YACd,KAAA,EACA,QAAA,EACA,KAAA,EACA,MAAA,EACA,SAAsB,SAAA,EACd;AACR,EAAA,MAAM,WAAW,CAAA,EAAG,MAAM,CAAA,CAAA,EAAI,KAAA,CAAM,aAAa,CAAA,CAAA;AACjD,EAAA,MAAM,QAAA,GAAW,KAAA,CAAM,KAAA,CAAM,GAAA,CAAI,QAAQ,CAAA;AACzC,EAAA,IAAI,QAAA,KAAa,QAAW,OAAO,QAAA;AAEnC,EAAA,MAAM,SAAS,KAAA,CAAM,QAAA,CAAS,GAAA,CAAI,MAAM,KAAK,CAAA,IAAK,CAAA;AAClD,EAAA,KAAA,CAAM,QAAA,CAAS,GAAA,CAAI,MAAA,EAAQ,KAAK,CAAA;AAEhC,EAAA,MAAM,EAAA,GAAK,MAAA,KAAW,SAAA,GAAY,MAAA,CAAO,KAAK,CAAA,CAAE,QAAA,CAAS,CAAA,EAAG,GAAG,CAAA,GAAI,MAAA,CAAO,KAAK,CAAA;AAC/E,EAAA,MAAM,KAAA,GAAQ,MAAA,KAAW,SAAA,G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,GAAS,cAAA,CAAe,IAAA,EAAM,KAAK,CAAA;AAGzC,EAAA,MAAM,QAAA,GAAW,kCAAA;AACjB,EAAA,MAAM,eAAe,IAAA,CAAK,KAAA,CAAM,QAAQ,CAAA,IAAK,EAAC,EAAG,MAAA;AACjD,EAAA,MAAM,aAAA,GAAgB,WAAA,GAAc,MAAA,CAAO,UAAA,CAAW,MAAA;AACtD,EAAA,OAAO;AAAA,IACL,MAAM,MAAA,CAAO,IAAA;AAAA,IACb,aAAA;AAAA,IACA,YAAY,MAAA,CAAO;AAAA,GACrB;AACF","file":"chunk-ZXPZ7W37.cjs","sourcesContent":["/**\n * @module strategies/tokenize\n * @description The `tokenize` anonymization strategy — replaces PII with\n * deterministic, reversible tokens that can later be detokenized.\n *\n * Tokens are opaque identifiers (`[CATEGORY_xxxx]` or `<CATEGORY_N>`) that\n * carry no information about the original value but allow lossless recovery\n * when the token map is retained.\n *\n * This module provides low-level building blocks used by the public\n * `tokenize()` / `detokenize()` API in `src/tokenize.ts`.\n */\n\nimport type { TokenFormat } from \"../types.js\";\n\n/**\n * A mutable in-memory token store mapping token→value and value→token.\n * Scoped to a single tokenisation session.\n *\n * @public\n */\nexport interface TokenStore {\n /** Map: token string → original PII value */\n readonly tokens: Map<string, string>;\n /** Map: `\"CATEGORY:normalizedValue\"` → existing token (for dedup) */\n readonly index: Map<string, string>;\n /** Per-category counters for generating sequential token IDs */\n readonly counters: Map<string, number>;\n}\n\n/** Create an empty token store. */\nexport function createTokenStore(): TokenStore {\n return {\n tokens: new Map(),\n index: new Map(),\n counters: new Map(),\n };\n}\n\n/**\n * Produce a new or existing token for `(category, value)`.\n *\n * Tokens are *deduplicated* — the same value in the same category always\n * receives the same token within a session.\n *\n * @param store - The active token store.\n * @param category - The PII category (e.g. `\"email\"`).\n * @param value - The original PII string.\n * @param prefix - Category prefix used in the token label (e.g. `\"EMAIL\"`).\n * @param format - Token format: `\"bracket\"` (`[EMAIL_0001]`) or `\"angle\"` (`<EMAIL_1>`).\n * @returns The deterministic token string.\n */\nexport function assignToken(\n store: TokenStore,\n category: string,\n value: string,\n prefix: string,\n format: TokenFormat = \"bracket\",\n): string {\n const indexKey = `${prefix}:${value.toLowerCase()}`;\n const existing = store.index.get(indexKey);\n if (existing !== undefined) return existing;\n\n const count = (store.counters.get(prefix) ?? 0) + 1;\n store.counters.set(prefix, count);\n\n const id = format === \"bracket\" ? String(count).padStart(4, \"0\") : String(count);\n const token = format === \"bracket\" ? `[${prefix}_${id}]` : `<${prefix}_${id}>`;\n\n store.index.set(indexKey, token);\n store.tokens.set(token, value);\n return token;\n}\n\n/**\n * Replace a token with its original value. Returns `undefined` when the token\n * is not found in `store`.\n *\n * @param store - The active token store.\n * @param token - The token to resolve.\n */\nexport function resolveToken(store: TokenStore, token: string): string | undefined {\n return store.tokens.get(token);\n}\n\n/**\n * Restore all tokens in `text` using `store`.\n * Tokens that are not found in `store` are left unchanged.\n *\n * @param text - The tokenized text.\n * @param store - The token store from the original tokenization call.\n * @returns The restored text and a list of any unresolved tokens.\n */\nexport function detokenizeText(\n text: string,\n store: TokenStore,\n): { text: string; unresolved: string[] } {\n const unresolved: string[] = [];\n\n // Match both bracket `[PREFIX_NNNN]` and angle `<PREFIX_N>` format tokens.\n const re = /(\\[[A-Z_]+_\\d+\\]|<[A-Z_]+_\\d+>)/g;\n\n const result = text.replace(re, (token) => {\n const original = store.tokens.get(token);\n if (original !== undefined) return original;\n unresolved.push(token);\n return token;\n });\n\n return { text: result, unresolved };\n}\n","/**\n * @module internal/allowlist\n * @description Allowlist matching of the 1.x functions: the detected values\n * that the caller lists are left untouched.\n * @internal\n */\n\n/**\n * Compile an allowlist into a predicate that tells whether a detected value\n * is allowlisted.\n *\n * A string entry matches a value equal to it, ignoring case unless\n * `caseSensitive` is set; a value that merely contains an entry does not\n * match. A pattern matches a value it finds a match in. Its `g` and `y` flags\n * are dropped, so that no value depends on the values tested before it and\n * the caller's `RegExp` keeps its `lastIndex`.\n *\n * @param entries - Exact values to leave untouched.\n * @param patterns - Patterns of values to leave untouched.\n * @param caseSensitive - Whether entries are compared case-sensitively.\n * @returns A predicate that returns `true` for an allowlisted value.\n * @internal\n */\nexport function compileAllowlist(\n entries: readonly string[],\n patterns: readonly RegExp[],\n caseSensitive: boolean,\n): (value: string) => boolean {\n if (entries.length === 0 && patterns.length === 0) return () => false;\n\n const exact = new Set(entries.map((entry) => (caseSensitive ? entry : entry.toLowerCase())));\n const compiled = patterns.map(\n (pattern) => new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, \"\")),\n );\n\n return (value) =>\n exact.has(caseSensitive ? value : value.toLowerCase()) ||\n compiled.some((pattern) => pattern.test(value));\n}\n","/**\n * @module anonymize\n * @description Core anonymization engine — detects PII and applies strategies.\n */\n\nimport { DETECTOR_REGISTRY, AGGRESSIVE_DETECTOR_REGISTRY } from \"./detectors/index.js\";\nimport { createTokenStore, assignToken as assignTokenFn } from \"./strategies/tokenize.js\";\nimport { mask } from \"./strategies/mask.js\";\nimport { redact } from \"./strategies/redact.js\";\nimport { pseudonymize } from \"./strategies/pseudonymize.js\";\nimport { generalize } from \"./strategies/generalize.js\";\nimport {\n UnsupportedStrategyError,\n UnknownCategoryError,\n ValidationError,\n PresetNotFoundError,\n} from \"./errors.js\";\nimport { getPreset } from \"./presets.js\";\nimport { compileAllowlist } from \"./internal/allowlist.js\";\nimport type {\n AnonymizeOptions,\n AnonymizeResult,\n AnonymizerConfig,\n Anonymizer,\n FieldRuleMap,\n PiiCategory,\n PiiMatch,\n StrategyOptions,\n Detector,\n CustomPattern,\n TokenizeOptions,\n TokenMatch,\n} from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\n/** All recognised PII category names. */\nconst ALL_CATEGORIES: readonly PiiCategory[] = [\n \"email\",\n \"phone\",\n \"ssn\",\n \"credit-card\",\n \"ipv4\",\n \"ipv6\",\n \"url\",\n \"iban\",\n \"date-of-birth\",\n \"name\",\n \"address\",\n \"passport\",\n \"drivers-license\",\n \"national-id\",\n \"bank-account\",\n \"cryptocurrency\",\n \"tax-id\",\n \"medical-record\",\n \"health-insurance\",\n \"prescription\",\n \"api-key\",\n \"social-media\",\n \"vin\",\n \"license-plate\",\n \"tracking-number\",\n \"case-number\",\n \"company-registration\",\n] as const;\n\n/**\n * Category → token prefix mapping for `consistentTokens` mode.\n * @internal\n */\nconst TOKEN_PREFIX_MAP: Readonly<Record<PiiCategory, string>> = {\n email: \"EMAIL\",\n phone: \"PHONE\",\n ssn: \"SSN\",\n \"credit-card\": \"CREDIT_CARD\",\n ipv4: \"IPV4\",\n ipv6: \"IPV6\",\n url: \"URL\",\n iban: \"IBAN\",\n \"date-of-birth\": \"DATE\",\n name: \"PERSON\",\n address: \"ADDRESS\",\n passport: \"PASSPORT\",\n \"drivers-license\": \"DRIVERS_LICENSE\",\n \"national-id\": \"NATIONAL_ID\",\n \"bank-account\": \"BANK_ACCOUNT\",\n cryptocurrency: \"CRYPTO\",\n \"tax-id\": \"TAX_ID\",\n \"medical-record\": \"MEDICAL_RECORD\",\n \"health-insurance\": \"HEALTH_INSURANCE\",\n prescription: \"PRESCRIPTION\",\n \"api-key\": \"API_KEY\",\n \"social-media\": \"SOCIAL_MEDIA\",\n vin: \"VIN\",\n \"license-plate\": \"LICENSE_PLATE\",\n \"tracking-number\": \"TRACKING_NUMBER\",\n \"case-number\": \"CASE_NUMBER\",\n \"company-registration\": \"COMPANY_REG\",\n} as const;\n\n/**\n * Apply a single strategy synchronously. The `hash` strategy is async but\n * for text-level anonymization we need synchronous replacement. We use\n * pseudonymize as a deterministic fallback for hash in sync contexts.\n *\n * @remarks\n * ⚠️ **`hash` fallback**: When `hash` is used in a synchronous `anonymize()`\n * call, it falls back to a deterministic pseudonym. If true SHA-256 hashing is\n * required, call `hash()` directly (it returns a `Promise<string>`).\n *\n * @internal\n */\nfunction applyStrategySync(value: string, opts: StrategyOptions): string {\n switch (opts.strategy) {\n case \"mask\":\n return mask(value, opts);\n case \"redact\":\n return redact(value, opts);\n case \"pseudonymize\":\n return pseudonymize(value, opts);\n case \"hash\":\n // Hash is async; callers that need true hashing should use hashValue() directly.\n // For the synchronous pipeline we fall back to a deterministic pseudonym.\n // eslint-disable-next-line no-console\n console.warn(\n \"[anonyma] The `hash` strategy is async and cannot be used in the synchronous \" +\n \"`anonymize()` pipeline. Falling back to a deterministic pseudonym. \" +\n \"Use `anonymizeAsync()` or `hash()` for SHA-256 output.\",\n );\n return pseudonymize(value, { seed: opts.pepper ?? \"__hash_fallback__\", prefix: \"hsh_\" });\n case \"generalize\":\n return generalize(value, opts);\n case \"tokenize\":\n case \"encrypt\":\n case \"synthesize\":\n // Neither anonymize() nor anonymizeAsync() applies these strategies: the\n // value is redacted. The span engine applies all of them.\n // eslint-disable-next-line no-console\n console.warn(\n `[anonyma] anonymize() and anonymizeAsync() do not apply the \\`${opts.strategy}\\` ` +\n `strategy; the value is redacted instead. Use a pipeline of \"anonyma/engine\" ` +\n `to apply it.`,\n );\n return redact(value);\n default: {\n // Exhaustiveness check — TypeScript should never reach here.\n const _exhaustive: never = opts;\n throw new UnsupportedStrategyError((_exhaustive as StrategyOptions).strategy);\n }\n }\n}\n\n/**\n * Sort and de-duplicate an array of PII matches by position.\n * When matches overlap, the one with the higher confidence wins.\n *\n * Works on any match-like object that has `start`, `end`, and `confidence`.\n *\n * @internal\n */\nfunction deduplicateMatches<T extends { start: number; end: number; confidence: number }>(\n matches: T[],\n): T[] {\n // Sort by start position; on ties prefer higher confidence.\n const sorted = [...matches].sort((a, b) => a.start - b.start || b.confidence - a.confidence);\n\n const result: T[] = [];\n let cursor = 0;\n\n for (const m of sorted) {\n if (m.start >= cursor) {\n result.push(m);\n cursor = m.end;\n }\n }\n\n return result;\n}\n\n/**\n * Get the active detector for a category, merging custom overrides.\n *\n * @internal\n */\nfunction resolveDetector(\n category: PiiCategory,\n customDetectors?: Partial<Record<PiiCategory, Detector>>,\n aggressive?: boolean,\n): Detector {\n if (customDetectors?.[category]) return customDetectors[category];\n return aggressive ? AGGRESSIVE_DETECTOR_REGISTRY[category] : DETECTOR_REGISTRY[category];\n}\n\n/**\n * Internal representation of a custom pattern match used within the\n * anonymization pipeline. Not exposed publicly.\n *\n * @internal\n */\ninterface CustomMatch {\n readonly category: string;\n readonly value: string;\n readonly start: number;\n readonly end: number;\n readonly confidence: number;\n readonly replacement: string;\n}\n\n/**\n * Run custom patterns against `text` and produce CustomMatch objects.\n *\n * @internal\n */\nfunction detectCustomPatterns(\n text: string,\n customPatterns: readonly CustomPattern[],\n): CustomMatch[] {\n const results: CustomMatch[] = [];\n\n for (const cp of customPatterns) {\n if (!(cp.pattern instanceof RegExp)) {\n throw new ValidationError(\"customPatterns[].pattern\", \"must be a RegExp instance\");\n }\n\n // Ensure global flag is set; create a fresh copy to avoid lastIndex mutation.\n const flags = cp.pattern.flags.includes(\"g\") ? cp.pattern.flags : cp.pattern.flags + \"g\";\n const re = new RegExp(cp.pattern.source, flags);\n const category = cp.category ?? \"custom\";\n const confidence = cp.confidence ?? 0.85;\n const label = cp.label ?? \"[REDACTED]\";\n\n let m: RegExpExecArray | null;\n while ((m = re.exec(text)) !== null) {\n results.push({\n category,\n value: m[0],\n start: m.index,\n end: m.index + m[0].length,\n confidence,\n replacement: label,\n });\n }\n }\n\n return results;\n}\n\n/**\n * Resolve the list of categories to detect from `AnonymizeOptions`.\n * Handles `rules`, `enabledCategories`, and defaults.\n *\n * @internal\n */\nfunction resolveCategories(options: AnonymizeOptions): PiiCategory[] {\n const { rules = [], enabledCategories } = options;\n\n if (rules.length > 0) {\n // rules takes priority — only scan the explicitly listed categories.\n return rules.map((r) => r.category);\n }\n\n if (enabledCategories) {\n return ALL_CATEGORIES.filter((cat) => enabledCategories[cat] === true);\n }\n\n return [...ALL_CATEGORIES];\n}\n\n// ---------------------------------------------------------------------------\n// Public: detect()\n// ---------------------------------------------------------------------------\n\n/**\n * Detect all PII in `text` using the built-in detectors.\n *\n * @param text - The input string to scan.\n * @param categories - Optional subset of categories to check. Defaults to all.\n * @param customDetectors - Optional overrides for built-in detectors.\n * @param aggressive - When `true`, use expanded pattern sets for each detector.\n * @returns A sorted array of non-overlapping {@link PiiMatch} objects.\n *\n * @example\n * ```ts\n * import { detect } from \"anonyma\";\n *\n * detect(\"Email: alice@example.com, IP: 192.168.1.1\");\n * // [\n * // { category: \"email\", value: \"alice@example.com\", start: 7, end: 24, confidence: 0.99 },\n * // { category: \"ipv4\", value: \"192.168.1.1\", start: 30, end: 41, confidence: 0.98 },\n * // ]\n * ```\n */\nexport function detect(\n text: string,\n categories: readonly PiiCategory[] = ALL_CATEGORIES,\n customDetectors?: Partial<Record<PiiCategory, Detector>>,\n aggressive?: boolean,\n): PiiMatch[] {\n if (typeof text !== \"string\") {\n throw new ValidationError(\"text\", \"must be a string\");\n }\n\n const raw: PiiMatch[] = [];\n\n for (const category of categories) {\n if (!ALL_CATEGORIES.includes(category)) {\n throw new UnknownCategoryError(category);\n }\n const detector = resolveDetector(category, customDetectors, aggressive);\n raw.push(...detector(text));\n }\n\n return deduplicateMatches(raw);\n}\n\n// ---------------------------------------------------------------------------\n// Public: hasPII()\n// ---------------------------------------------------------------------------\n\n/**\n * Return `true` if `text` contains any detectable PII, `false` otherwise.\n *\n * Uses an early-exit optimisation — scanning stops after the first match is\n * found. Useful for validation gates and conditional processing pipelines.\n *\n * @param text - The input string to scan.\n * @param categories - Optional subset of categories to check. Defaults to all.\n * @param customDetectors - Optional overrides for built-in detectors.\n * @returns `true` if any PII is detected; `false` otherwise.\n *\n * @example\n * ```ts\n * import { hasPII } from \"anonyma\";\n *\n * if (hasPII(commentText)) {\n * return { error: \"Comment contains personal information.\" };\n * }\n * ```\n */\nexport function hasPII(\n text: string,\n categories: readonly PiiCategory[] = ALL_CATEGORIES,\n customDetectors?: Partial<Record<PiiCategory, Detector>>,\n): boolean {\n if (typeof text !== \"string\") {\n throw new ValidationError(\"text\", \"must be a string\");\n }\n\n for (const category of categories) {\n if (!ALL_CATEGORIES.includes(category)) {\n throw new UnknownCategoryError(category);\n }\n const detector = resolveDetector(category, customDetectors);\n if (detector(text).length > 0) return true;\n }\n\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// Public: anonymize()\n// ---------------------------------------------------------------------------\n\n/**\n * Detect and anonymize all PII in `text`.\n *\n * Operates in a single left-to-right pass: detected matches are replaced in\n * reverse order (right-to-left) to preserve correct string offsets.\n *\n * @param text - The input string to anonymize.\n * @param options - Anonymization configuration.\n * @returns An {@link AnonymizeResult} containing the anonymized text and\n * optionally the detected matches.\n *\n * @example\n * ```ts\n * import { anonymize } from \"anonyma\";\n *\n * anonymize(\"Contact alice@example.com or call 555-867-5309.\");\n * // { text: \"Contact [REDACTED] or call [REDACTED].\", matches: [] }\n *\n * // Consistent tokens — same value gets same label\n * anonymize(\"alice@example.com and alice@example.com again\", { consistentTokens: true });\n * // { text: \"EMAIL_1 and EMAIL_1 again\", matches: [] }\n *\n * // Aggressive mode — catches obfuscated PII\n * anonymize(\"Email user [at] example [dot] com\", { aggressive: true });\n * // { text: \"Email [REDACTED]\", matches: [] }\n * ```\n */\nexport function anonymize(text: string, options: AnonymizeOptions = {}): AnonymizeResult {\n if (typeof text !== \"string\") {\n throw new ValidationError(\"text\", \"must be a string\");\n }\n\n if (options.globalReplacement?.trim().length === 0) {\n throw new ValidationError(\"globalReplacement\", \"must not be an empty string\");\n }\n\n // Resolve preset if provided.\n let resolvedPreset: ReturnType<typeof getPreset> | undefined;\n if (options.preset) {\n try {\n resolvedPreset = getPreset(options.preset);\n } catch {\n throw new PresetNotFoundError(options.preset);\n }\n }\n\n const {\n rules = resolvedPreset\n ? resolvedPreset.categories.map((category) => ({\n category,\n strategy:\n resolvedPreset.rules?.find((r) => r.category === category)?.strategy ??\n resolvedPreset.defaultStrategy,\n }))\n : [],\n defaultStrategy = resolvedPreset?.defaultStrategy ?? { strategy: \"redact\" as const },\n includeMatches = false,\n customDetectors,\n customPatterns = [],\n globalReplacement,\n consistentTokens = false,\n aggressive = false,\n enabledCategories,\n allowlist = [],\n allowlistPatterns = [],\n allowlistCaseSensitive = false,\n confidenceThreshold = 0,\n } = options;\n\n // Build a category → strategy map from the rules array.\n const ruleMap = new Map<PiiCategory, StrategyOptions>();\n for (const rule of rules) {\n if (!ALL_CATEGORIES.includes(rule.category)) {\n throw new UnknownCategoryError(rule.category);\n }\n ruleMap.set(rule.category, rule.strategy);\n }\n\n // Resolve which categories to scan.\n const categories = resolveCategories({\n rules,\n ...(enabledCategories !== undefined ? { enabledCategories } : {}),\n });\n\n // True for a value that must NOT be anonymized even if detected as PII.\n const isAllowlisted = compileAllowlist(allowlist, allowlistPatterns, allowlistCaseSensitive);\n\n // Run built-in detectors.\n const builtInMatches = detect(text, categories, customDetectors, aggressive);\n\n // Run custom patterns.\n const customMatches = customPatterns.length > 0 ? detectCustomPatterns(text, customPatterns) : [];\n\n // Apply allowlist + confidenceThreshold filtering to built-in matches.\n const filteredBuiltInMatches = builtInMatches.filter(\n (m) => m.confidence >= confidenceThreshold && !isAllowlisted(m.value),\n );\n\n // Combine and deduplicate all matches by position.\n type UnifiedMatch = (PiiMatch & { replacement?: string }) | CustomMatch;\n const allRaw: UnifiedMatch[] = [...filteredBuiltInMatches, ...customMatches];\n const allDeduped = deduplicateMatches(allRaw);\n\n // --- Consistent token state (scoped to this call only) ---\n const tokenMap = new Map<string, string>(); // key: \"category:normalizedValue\" → token\n const tokenCounters = new Map<string, number>(); // key: prefix → counter\n\n function assignToken(category: string, value: string): string {\n const prefix =\n (TOKEN_PREFIX_MAP as Readonly<Record<string, string | undefined>>)[category] ??\n category.toUpperCase();\n const key = `${prefix}:${value.toLowerCase()}`;\n const existing = tokenMap.get(key);\n if (existing) return existing;\n const count = (tokenCounters.get(prefix) ?? 0) + 1;\n tokenCounters.set(prefix, count);\n const token = `${prefix}_${String(count)}`;\n tokenMap.set(key, token);\n return token;\n }\n\n // Apply strategies in reverse order to preserve indices.\n let result = text;\n const reversed = [...allDeduped].reverse();\n\n for (const match of reversed) {\n let replacement: string;\n\n if (globalReplacement !== undefined) {\n replacement = globalReplacement;\n } else if (consistentTokens) {\n replacement = assignToken(match.category, match.value);\n } else if (\"replacement\" in match) {\n // Pre-computed replacement from custom pattern.\n replacement = match.replacement;\n } else {\n // Built-in PII match: look up per-category rule or fall back to default.\n const strategy = ruleMap.get(match.category) ?? defaultStrategy;\n replacement = applyStrategySync(match.value, strategy);\n }\n\n result = result.slice(0, match.start) + replacement + result.slice(match.end);\n }\n\n // Only include built-in PiiMatch objects in the public result (custom matches\n // have a non-PiiCategory category and are not part of the public API surface).\n const reportedMatches = includeMatches ? filteredBuiltInMatches : [];\n\n return {\n text: result,\n matches: reportedMatches,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Public: anonymizeAsync()\n// ---------------------------------------------------------------------------\n\n/**\n * Asynchronous version of {@link anonymize}. Supports the `hash` strategy\n * (uses true SHA-256 via the Web Crypto API) and future async strategies\n * (`tokenize`, `encrypt`, `synthesize`).\n *\n * Falls back to the synchronous implementation for all other strategies.\n *\n * @param text - The input string to anonymize.\n * @param options - Anonymization configuration. Supports the same options as\n * {@link anonymize} plus `hash` strategy with actual SHA-256 output.\n * @returns A promise that resolves to an {@link AnonymizeResult}.\n *\n * @example\n * ```ts\n * import { anonymizeAsync } from \"anonyma\";\n *\n * const result = await anonymizeAsync(\"Contact alice@example.com\", {\n * defaultStrategy: { strategy: \"hash\" },\n * });\n * // { text: \"Contact <sha256-hex>\", matches: [] }\n * ```\n */\nexport async function anonymizeAsync(\n text: string,\n options: AnonymizeOptions = {},\n): Promise<AnonymizeResult> {\n if (typeof text !== \"string\") {\n throw new ValidationError(\"text\", \"must be a string\");\n }\n\n // For strategies that don't involve async primitives, delegate to sync.\n const hasAsyncStrategy = (opts: StrategyOptions): boolean =>\n opts.strategy === \"hash\" ||\n opts.strategy === \"encrypt\" ||\n opts.strategy === \"tokenize\" ||\n opts.strategy === \"synthesize\";\n\n const needsAsync =\n (options.defaultStrategy != null && hasAsyncStrategy(options.defaultStrategy)) ||\n (options.rules ?? []).some((r) => hasAsyncStrategy(r.strategy));\n\n if (!needsAsync) {\n return anonymize(text, options);\n }\n\n // Lazy-import to avoid circular dependency on strategies not yet in the\n // synchronous bundle (hash is async-native, others upcoming).\n const { hash: hashFn } = await import(\"./strategies/hash.js\");\n\n // Resolve identical logic as sync path.\n let resolvedPreset: ReturnType<typeof getPreset> | undefined;\n if (options.preset) {\n try {\n resolvedPreset = getPreset(options.preset);\n } catch {\n throw new PresetNotFoundError(options.preset);\n }\n }\n\n const {\n rules = resolvedPreset\n ? resolvedPreset.categories.map((category) => ({\n category,\n strategy:\n resolvedPreset.rules?.find((r) => r.category === category)?.strategy ??\n resolvedPreset.defaultStrategy,\n }))\n : [],\n defaultStrategy = resolvedPreset?.defaultStrategy ?? { strategy: \"redact\" as const },\n includeMatches = false,\n customDetectors,\n customPatterns = [],\n globalReplacement,\n consistentTokens = false,\n aggressive = false,\n enabledCategories,\n allowlist = [],\n allowlistPatterns = [],\n allowlistCaseSensitive = false,\n confidenceThreshold = 0,\n } = options;\n\n const ruleMap = new Map<PiiCategory, StrategyOptions>();\n for (const rule of rules) {\n if (!ALL_CATEGORIES.includes(rule.category)) throw new UnknownCategoryError(rule.category);\n ruleMap.set(rule.category, rule.strategy);\n }\n\n const categories = resolveCategories({\n rules,\n ...(enabledCategories !== undefined ? { enabledCategories } : {}),\n });\n\n const builtInMatches = detect(text, categories, customDetectors, aggressive);\n const customMatches = customPatterns.length > 0 ? detectCustomPatterns(text, customPatterns) : [];\n\n const isAllowlisted = compileAllowlist(allowlist, allowlistPatterns, allowlistCaseSensitive);\n\n const filteredBuiltInMatches = builtInMatches.filter(\n (m) => m.confidence >= confidenceThreshold && !isAllowlisted(m.value),\n );\n\n type UnifiedMatch = (PiiMatch & { replacement?: string }) | CustomMatch;\n const allRaw: UnifiedMatch[] = [...filteredBuiltInMatches, ...customMatches];\n const allDeduped = deduplicateMatches(allRaw);\n\n const tokenMap = new Map<string, string>();\n const tokenCounters = new Map<string, number>();\n function assignToken(category: string, value: string): string {\n const prefix =\n (TOKEN_PREFIX_MAP as Readonly<Record<string, string | undefined>>)[category] ??\n category.toUpperCase();\n const key = `${prefix}:${value.toLowerCase()}`;\n const existing = tokenMap.get(key);\n if (existing) return existing;\n const count = (tokenCounters.get(prefix) ?? 0) + 1;\n tokenCounters.set(prefix, count);\n const token = `${prefix}_${String(count)}`;\n tokenMap.set(key, token);\n return token;\n }\n\n let result = text;\n const reversed = [...allDeduped].reverse();\n\n for (const match of reversed) {\n let replacement: string;\n\n if (globalReplacement !== undefined) {\n replacement = globalReplacement;\n } else if (consistentTokens) {\n replacement = assignToken(match.category, match.value);\n } else if (\"replacement\" in match) {\n replacement = match.replacement;\n } else {\n const strategy = ruleMap.get(match.category) ?? defaultStrategy;\n if (strategy.strategy === \"hash\") {\n replacement = await hashFn(match.value, strategy);\n } else {\n replacement = applyStrategySync(match.value, strategy);\n }\n }\n\n result = result.slice(0, match.start) + replacement + result.slice(match.end);\n }\n\n return {\n text: result,\n matches: includeMatches ? filteredBuiltInMatches : [],\n };\n}\n\n// ---------------------------------------------------------------------------\n// Public: anonymizeObject()\n// ---------------------------------------------------------------------------\n\n/**\n * Recursively anonymize every string value found in a JSON-serializable object\n * tree. Returns a deep clone — the input is never mutated.\n *\n * Handles:\n * - Plain objects (nested to any depth)\n * - Arrays (including mixed-type arrays)\n * - Primitive values (`null`, `undefined`, numbers, booleans) — passed through unchanged\n * - Circular references — throws {@link ValidationError}\n *\n * @param obj - The root object to anonymize. Must be free of circular references.\n * @param options - Optional anonymization configuration forwarded to `anonymize()`.\n * @returns A new object of the same shape with all string values anonymized.\n *\n * @throws {@link ValidationError} When `obj` contains a circular reference or is not an object.\n *\n * @example\n * ```ts\n * import { anonymizeObject } from \"anonyma\";\n *\n * const result = anonymizeObject({\n * user: { name: \"Alice\", email: \"alice@example.com\" },\n * notes: [\"Call 555-867-5309\", \"No PII here\"],\n * });\n * // {\n * // user: { name: \"Alice\", email: \"[REDACTED]\" },\n * // notes: [\"[REDACTED]\", \"No PII here\"],\n * // }\n * ```\n */\nexport function anonymizeObject<T extends object>(obj: T, options?: AnonymizeOptions): T {\n if (typeof obj !== \"object\") {\n throw new ValidationError(\"obj\", \"must be an object\");\n }\n return deepAnonymizeValue(obj, options, new WeakSet()) as T;\n}\n\n/**\n * Recursive implementation for `anonymizeObject`.\n * `seen` tracks visited objects to detect circular references.\n *\n * @internal\n */\nfunction deepAnonymizeValue(\n value: unknown,\n options: AnonymizeOptions | undefined,\n seen: WeakSet<object>,\n): unknown {\n if (value === null || value === undefined) return value;\n\n if (typeof value === \"string\") {\n return anonymize(value, options).text;\n }\n\n if (typeof value !== \"object\") {\n // numbers, booleans, Symbols, BigInts — pass through unchanged.\n return value;\n }\n\n if (seen.has(value)) {\n throw new ValidationError(\"obj\", \"contains a circular reference\");\n }\n seen.add(value);\n\n if (Array.isArray(value)) {\n const result = value.map((item) => deepAnonymizeValue(item, options, seen));\n seen.delete(value as object);\n return result;\n }\n\n // Plain object.\n const result: Record<string, unknown> = {};\n for (const key of Object.keys(value as Record<string, unknown>)) {\n result[key] = deepAnonymizeValue((value as Record<string, unknown>)[key], options, seen);\n }\n seen.delete(value);\n return result;\n}\n\n// ---------------------------------------------------------------------------\n// Public: anonymizeRecord()\n// ---------------------------------------------------------------------------\n\n/**\n * Safely get a nested value from a plain record using dot-notation path.\n *\n * @internal\n */\nfunction getByPath(obj: Record<string, unknown>, path: string): unknown {\n const parts = path.split(\".\");\n let current: unknown = obj;\n\n for (const part of parts) {\n if (current === null || typeof current !== \"object\" || Array.isArray(current)) {\n return undefined;\n }\n // Safe: we check isObject above.\n current = (current as Record<string, unknown>)[part];\n }\n\n return current;\n}\n\n/**\n * Safely set a nested value on a plain record using dot-notation path.\n * Returns a new object (shallow clone at each level touched).\n *\n * @internal\n */\nfunction setByPath(\n obj: Record<string, unknown>,\n path: string,\n value: unknown,\n): Record<string, unknown> {\n const parts = path.split(\".\");\n\n if (parts.length === 1) {\n return { ...obj, [path]: value };\n }\n\n const [head, ...tail] = parts as [string, ...string[]];\n // setByPath is only called after getByPath confirmed the path exists, so obj[head] is\n // always defined in practice. The `?? {}` fallback is a defensive guard.\n /* v8 ignore next */\n const nested = (obj[head] ?? {}) as Record<string, unknown>;\n return {\n ...obj,\n [head]: setByPath(nested, tail.join(\".\"), value),\n };\n}\n\n/**\n * Anonymize specific fields in a plain record using field-level rules.\n * Supports dot-notation paths for nested fields.\n *\n * This function returns a new record — it never mutates the input.\n *\n * @param record - The input record.\n * @param rules - A map of field path → {@link FieldRule}.\n * @returns A new record with the specified fields anonymized.\n *\n * @example\n * ```ts\n * import { anonymizeRecord } from \"anonyma\";\n *\n * anonymizeRecord(\n * { name: \"Alice\", email: \"alice@example.com\", age: \"27\" },\n * {\n * email: { strategy: { strategy: \"mask\", keepLeading: 1, keepTrailing: 3 } },\n * age: { strategy: { strategy: \"generalize\" } },\n * }\n * );\n * // { name: \"Alice\", email: \"a***************com\", age: \"20-29\" }\n * ```\n */\nexport function anonymizeRecord<T extends Record<string, unknown>>(\n record: T,\n rules: FieldRuleMap,\n): T {\n if (typeof record !== \"object\" || Array.isArray(record)) {\n throw new ValidationError(\"record\", \"must be a plain object\");\n }\n\n let result: Record<string, unknown> = { ...record };\n\n for (const [path, rule] of Object.entries(rules)) {\n if (Object.prototype.hasOwnProperty.call(rules, path)) {\n const raw = getByPath(result, path);\n if (raw === undefined || raw === null) continue;\n if (typeof raw !== \"string\" && typeof raw !== \"number\" && typeof raw !== \"boolean\") continue;\n\n const strValue = String(raw);\n const anonymized = applyStrategySync(strValue, rule.strategy);\n result = setByPath(result, path, anonymized);\n }\n }\n\n return result as T;\n}\n\n// ---------------------------------------------------------------------------\n// Public: createAnonymizer()\n// ---------------------------------------------------------------------------\n\n/**\n * Create a reusable, pre-configured {@link Anonymizer} instance.\n *\n * @param config - Anonymizer configuration.\n * @returns A configured {@link Anonymizer}.\n *\n * @example\n * ```ts\n * import { createAnonymizer } from \"anonyma\";\n *\n * const anonymizer = createAnonymizer({\n * categories: [\"email\", \"phone\"],\n * defaultStrategy: { strategy: \"mask\", keepLeading: 0, keepTrailing: 4 },\n * });\n *\n * anonymizer.anonymize(\"Call 555-867-5309 or email alice@example.com\");\n * // { text: \"Call ****5309 or email **.com\", matches: [] }\n *\n * anonymizer.hasPII(\"No PII here\");\n * // false\n *\n * anonymizer.anonymizeObject({ email: \"alice@example.com\", score: 42 });\n * // { email: \"[REDACTED]\", score: 42 }\n * ```\n */\nexport function createAnonymizer(config: AnonymizerConfig = {}): Anonymizer {\n // Resolve preset first so its defaults can be overridden by explicit config.\n let presetConfig: ReturnType<typeof getPreset> | undefined;\n if (config.preset) {\n try {\n presetConfig = getPreset(config.preset);\n } catch {\n throw new PresetNotFoundError(config.preset);\n }\n }\n\n const {\n categories = presetConfig ? presetConfig.categories : [...ALL_CATEGORIES],\n defaultStrategy = presetConfig?.defaultStrategy ?? { strategy: \"redact\" as const },\n customDetectors,\n customPatterns,\n globalReplacement,\n consistentTokens,\n aggressive,\n } = config;\n\n // Validate categories up-front.\n for (const cat of categories) {\n if (!ALL_CATEGORIES.includes(cat)) {\n throw new UnknownCategoryError(cat);\n }\n }\n\n /** Shared base options derived from config. */\n function baseOptions(overrides?: Partial<AnonymizeOptions>): AnonymizeOptions {\n const base: AnonymizeOptions = {\n defaultStrategy,\n ...(customDetectors !== undefined ? { customDetectors } : {}),\n ...(customPatterns !== undefined ? { customPatterns } : {}),\n ...(globalReplacement !== undefined ? { globalReplacement } : {}),\n ...(consistentTokens !== undefined ? { consistentTokens } : {}),\n ...(aggressive !== undefined ? { aggressive } : {}),\n ...overrides,\n rules:\n overrides?.rules ??\n (presetConfig\n ? presetConfig.categories.map((category) => ({\n category,\n strategy:\n presetConfig.rules?.find((r) => r.category === category)?.strategy ??\n defaultStrategy,\n }))\n : categories.map((category) => ({\n category,\n strategy: defaultStrategy,\n }))),\n };\n return base;\n }\n\n return {\n anonymize(text: string, options?: Partial<AnonymizeOptions>): AnonymizeResult {\n return anonymize(text, baseOptions(options));\n },\n\n detect(text: string): PiiMatch[] {\n return detect(text, categories, customDetectors, aggressive);\n },\n\n anonymizeRecord<T extends Record<string, unknown>>(record: T, rules: FieldRuleMap): T {\n return anonymizeRecord(record, rules);\n },\n\n anonymizeObject<T extends object>(obj: T, options?: AnonymizeOptions): T {\n return anonymizeObject(obj, baseOptions(options));\n },\n\n async anonymizeAsync(\n text: string,\n options?: Partial<AnonymizeOptions>,\n ): Promise<AnonymizeResult> {\n return anonymizeAsync(text, baseOptions(options));\n },\n\n tokenize(text: string, options?: TokenizeOptions): ReturnType<Anonymizer[\"tokenize\"]> {\n // Inline implementation to avoid circular dependency (tokenize.ts imports detectFn)\n const {\n categories: tCats,\n format = \"bracket\",\n customDetectors: tCustDet,\n aggressive: tAgg = aggressive,\n confidenceThreshold: tConfidence = 0,\n allowlist: tAllowlist = [],\n allowlistCaseSensitive: tCaseSensitive = false,\n } = options ?? {};\n\n const isAllowlisted = compileAllowlist(tAllowlist, [], tCaseSensitive);\n\n const tMatches = detect(text, tCats ?? categories, tCustDet ?? customDetectors, tAgg).filter(\n (m) => m.confidence >= tConfidence && !isAllowlisted(m.value),\n );\n\n const store = createTokenStore();\n let tResult = text;\n const tTokens: TokenMatch[] = [];\n for (const match of [...tMatches].reverse()) {\n // detect() exclusively returns PiiCategory matches, so the toUpperCase() fallback\n // is unreachable through the public API.\n /* v8 ignore next */\n const prefix = TOKEN_PREFIX_MAP[match.category];\n const token = assignTokenFn(store, match.category, match.value, prefix, format);\n tTokens.push({\n token,\n original: match.value,\n category: match.category,\n start: match.start,\n end: match.end,\n });\n tResult = tResult.slice(0, match.start) + token + tResult.slice(match.end);\n }\n return { text: tResult, mapping: store.tokens, tokens: tTokens };\n },\n\n hasPII(text: string): boolean {\n return hasPII(text, categories, customDetectors);\n },\n };\n}\n","/**\n * @module tokenize\n * @description High-level reversible tokenization API for anonyma.\n *\n * Unlike `anonymize()` — which is one-way — `tokenize()` replaces PII with\n * opaque tokens that can be restored later via `detokenize()`. This is\n * particularly useful for LLM pipelines where the model receives sanitized\n * text and the output must be un-redacted before delivery.\n *\n * @example\n * ```ts\n * import { tokenize, detokenize } from \"anonyma\";\n *\n * const { text, mapping } = tokenize(\"Contact alice@example.com\");\n * // text: \"Contact [EMAIL_0001]\"\n * // mapping: Map { \"[EMAIL_0001]\" => \"alice@example.com\" }\n *\n * const original = detokenize(text, mapping);\n * // \"Contact alice@example.com\"\n * ```\n */\n\nimport { detect } from \"./anonymize.js\";\nimport { createTokenStore, assignToken, detokenizeText } from \"./strategies/tokenize.js\";\nimport { ValidationError } from \"./errors.js\";\nimport { compileAllowlist } from \"./internal/allowlist.js\";\nimport type { TokenizeResult, DetokenizeResult, TokenizeOptions, TokenMatch } from \"./types.js\";\n\n// Category → token prefix mapping (mirrors TOKEN_PREFIX_MAP in anonymize.ts).\nconst TOKEN_PREFIX_MAP: Record<string, string> = {\n email: \"EMAIL\",\n phone: \"PHONE\",\n ssn: \"SSN\",\n \"credit-card\": \"CREDIT_CARD\",\n ipv4: \"IPV4\",\n ipv6: \"IPV6\",\n url: \"URL\",\n iban: \"IBAN\",\n \"date-of-birth\": \"DATE\",\n name: \"PERSON\",\n address: \"ADDRESS\",\n passport: \"PASSPORT\",\n \"drivers-license\": \"DRIVERS_LICENSE\",\n \"national-id\": \"NATIONAL_ID\",\n \"bank-account\": \"BANK_ACCOUNT\",\n cryptocurrency: \"CRYPTO\",\n \"tax-id\": \"TAX_ID\",\n \"medical-record\": \"MEDICAL_RECORD\",\n \"health-insurance\": \"HEALTH_INSURANCE\",\n prescription: \"PRESCRIPTION\",\n \"api-key\": \"API_KEY\",\n \"social-media\": \"SOCIAL_MEDIA\",\n vin: \"VIN\",\n \"license-plate\": \"LICENSE_PLATE\",\n \"tracking-number\": \"TRACKING_NUMBER\",\n \"case-number\": \"CASE_NUMBER\",\n \"company-registration\": \"COMPANY_REG\",\n};\n\n// ---------------------------------------------------------------------------\n// Public: tokenize()\n// ---------------------------------------------------------------------------\n\n/**\n * Replace all detected PII in `text` with reversible opaque tokens.\n *\n * The returned `mapping` maps each token back to its original value. Pass it\n * to {@link detokenize} to restore the original text.\n *\n * @param text - The input string.\n * @param options - Tokenization options (categories, format, custom detectors…).\n * @returns A {@link TokenizeResult} containing `text` and `mapping`.\n *\n * @example\n * ```ts\n * const { text, mapping } = tokenize(\n * \"Email alice@example.com, phone 555-867-5309\",\n * { categories: [\"email\", \"phone\"], format: \"bracket\" }\n * );\n * // text: \"Email [EMAIL_0001], phone [PHONE_0001]\"\n * // mapping: Map { \"[EMAIL_0001]\" => \"alice@example.com\", \"[PHONE_0001]\" => \"555-867-5309\" }\n * ```\n */\nexport function tokenize(text: string, options: TokenizeOptions = {}): TokenizeResult {\n if (typeof text !== \"string\") throw new ValidationError(\"text\", \"must be a string\");\n\n const {\n categories,\n format = \"bracket\",\n customDetectors,\n aggressive = false,\n confidenceThreshold = 0,\n allowlist = [],\n allowlistCaseSensitive = false,\n } = options;\n\n const isAllowlisted = compileAllowlist(allowlist, [], allowlistCaseSensitive);\n\n // Detect PII.\n const allMatches = detect(text, categories, customDetectors, aggressive).filter(\n (m) => m.confidence >= confidenceThreshold && !isAllowlisted(m.value),\n );\n\n const store = createTokenStore();\n let result = text;\n const reversed = [...allMatches].reverse();\n const tokenMatches: TokenMatch[] = [];\n\n for (const match of reversed) {\n const prefix = TOKEN_PREFIX_MAP[match.category] ?? match.category.toUpperCase();\n const token = assignToken(store, match.category, match.value, prefix, format);\n tokenMatches.push({\n token,\n original: match.value,\n category: match.category,\n start: match.start,\n end: match.end,\n });\n result = result.slice(0, match.start) + token + result.slice(match.end);\n }\n\n return { text: result, mapping: store.tokens, tokens: tokenMatches };\n}\n\n// ---------------------------------------------------------------------------\n// Public: tokenizeAsync()\n// ---------------------------------------------------------------------------\n\n/**\n * Async variant of {@link tokenize} — identical behaviour but returns a Promise.\n * Useful for consistency in async pipelines.\n */\nexport function tokenizeAsync(\n text: string,\n options: TokenizeOptions = {},\n): Promise<TokenizeResult> {\n return Promise.resolve(tokenize(text, options));\n}\n\n// ---------------------------------------------------------------------------\n// Public: detokenize()\n// ---------------------------------------------------------------------------\n\n/**\n * Restore all tokens in `text` using the `mapping` returned by {@link tokenize}.\n *\n * Tokens not present in `mapping` are left unchanged and reported in\n * `unresolved`.\n *\n * @param text - A tokenized string produced by {@link tokenize}.\n * @param mapping - The `mapping` from the matching {@link TokenizeResult}.\n * @returns A {@link DetokenizeResult} with the restored `text` and\n * any `unresolved` tokens.\n *\n * @example\n * ```ts\n * const original = detokenize(\"[EMAIL_0001]\", new Map([[\"[EMAIL_0001]\", \"alice@example.com\"]]));\n * // { text: \"alice@example.com\", unresolved: [] }\n * ```\n */\nexport function detokenize(text: string, mapping: ReadonlyMap<string, string>): DetokenizeResult {\n if (typeof text !== \"string\") throw new ValidationError(\"text\", \"must be a string\");\n\n // Build a temporary store from the mapping.\n const store = createTokenStore();\n for (const [token, value] of mapping) {\n store.tokens.set(token, value);\n }\n\n const result = detokenizeText(text, store);\n // Count how many token occurrences appeared in the text and were resolved.\n // We scan the text for all token-like patterns and subtract the unresolved ones.\n const TOKEN_RE = /(\\[[A-Z_]+_\\d+\\]|<[A-Z_]+_\\d+>)/g;\n const totalInText = (text.match(TOKEN_RE) ?? []).length;\n const replacedCount = totalInText - result.unresolved.length;\n return {\n text: result.text,\n replacedCount,\n unresolved: result.unresolved,\n };\n}\n"]}
@@ -1,7 +1,7 @@
1
- import { P as PiiCategory } from '../types-EJTj_BKY.cjs';
2
- import { R as RegulationId, a as RegulationProfile, S as StrategyTraits, P as ProtectionRequirement, b as Policy, c as PolicyIssue, d as PolicyDocument } from '../types-0BJH_wqc.cjs';
3
- export { C as CategoryRule, e as CoverageGap, L as LegalReference } from '../types-0BJH_wqc.cjs';
4
- import { T as TokenizationProvider, S as StrategySpec, c as PipelineSpec } from '../types-CPUhjvl8.cjs';
1
+ import { P as PiiCategory } from '../types-cbGVW8cD.cjs';
2
+ import { R as RegulationId, a as RegulationProfile, S as StrategyTraits, P as ProtectionRequirement, b as Policy, c as PolicyIssue, d as PolicyDocument } from '../types-BtvX8QTd.cjs';
3
+ export { C as CategoryRule, e as CoverageGap, L as LegalReference } from '../types-BtvX8QTd.cjs';
4
+ import { T as TokenizationProvider, S as StrategySpec, c as PipelineSpec } from '../types-BL5UWH0y.cjs';
5
5
 
6
6
  /**
7
7
  * @module compliance/regulations