anonyma 1.1.1 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +109 -1
- package/README.md +125 -7
- package/dist/ai/index.cjs +31 -20
- package/dist/ai/index.cjs.map +1 -1
- package/dist/ai/index.d.cts +5 -5
- package/dist/ai/index.d.ts +5 -5
- package/dist/ai/index.js +24 -13
- package/dist/ai/index.js.map +1 -1
- package/dist/audit/index.cjs +14 -14
- package/dist/audit/index.d.cts +2 -2
- package/dist/audit/index.d.ts +2 -2
- package/dist/audit/index.js +9 -9
- package/dist/{chunk-YMLR375Z.js → chunk-264R3VFP.js} +4 -3
- package/dist/chunk-264R3VFP.js.map +1 -0
- package/dist/{chunk-ISL5B4LU.cjs → chunk-32U3DM7M.cjs} +11 -11
- package/dist/{chunk-ISL5B4LU.cjs.map → chunk-32U3DM7M.cjs.map} +1 -1
- package/dist/{chunk-ZXPZ7W37.cjs → chunk-42ZZZUMO.cjs} +231 -60
- package/dist/chunk-42ZZZUMO.cjs.map +1 -0
- package/dist/chunk-4BYN6GVK.js +213 -0
- package/dist/chunk-4BYN6GVK.js.map +1 -0
- package/dist/{chunk-JKW36IPT.js → chunk-A2OMTO3L.js} +4 -4
- package/dist/{chunk-JKW36IPT.js.map → chunk-A2OMTO3L.js.map} +1 -1
- package/dist/{chunk-TW7PM3UJ.cjs → chunk-AITKBKQX.cjs} +2 -2
- package/dist/{chunk-TW7PM3UJ.cjs.map → chunk-AITKBKQX.cjs.map} +1 -1
- package/dist/{chunk-G4AN7FND.js → chunk-BWE4O2ES.js} +23 -9
- package/dist/chunk-BWE4O2ES.js.map +1 -0
- package/dist/{chunk-GS3FRH4K.js → chunk-CMJXIEBA.js} +2 -2
- package/dist/chunk-CMJXIEBA.js.map +1 -0
- package/dist/{chunk-GYMG5OI3.cjs → chunk-ESVFPMG4.cjs} +2 -2
- package/dist/{chunk-GYMG5OI3.cjs.map → chunk-ESVFPMG4.cjs.map} +1 -1
- package/dist/{chunk-2YG7R4KJ.cjs → chunk-EUNLKSYP.cjs} +5 -5
- package/dist/{chunk-2YG7R4KJ.cjs.map → chunk-EUNLKSYP.cjs.map} +1 -1
- package/dist/{chunk-S7NH6CHY.cjs → chunk-F3BYJFUM.cjs} +5 -3
- package/dist/chunk-F3BYJFUM.cjs.map +1 -0
- package/dist/{chunk-IJAMLYOT.cjs → chunk-HDHQXVUM.cjs} +50 -36
- package/dist/chunk-HDHQXVUM.cjs.map +1 -0
- package/dist/{chunk-OGNLB2KA.js → chunk-HFAIBE3T.js} +3 -3
- package/dist/{chunk-OGNLB2KA.js.map → chunk-HFAIBE3T.js.map} +1 -1
- package/dist/{chunk-PKHZ7CVI.js → chunk-IBDFBUFZ.js} +2 -2
- package/dist/chunk-IBDFBUFZ.js.map +1 -0
- package/dist/{chunk-3CY6ATKS.cjs → chunk-JBH2EFFF.cjs} +36 -36
- package/dist/{chunk-3CY6ATKS.cjs.map → chunk-JBH2EFFF.cjs.map} +1 -1
- package/dist/chunk-JPU7KQZX.cjs +82 -0
- package/dist/{chunk-CRXRJZEV.cjs.map → chunk-JPU7KQZX.cjs.map} +1 -1
- package/dist/{chunk-E3PICZYI.js → chunk-KHT23UVV.js} +3 -3
- package/dist/{chunk-E3PICZYI.js.map → chunk-KHT23UVV.js.map} +1 -1
- package/dist/{chunk-2ZZHLCEJ.js → chunk-LAZIR73I.js} +18 -87
- package/dist/chunk-LAZIR73I.js.map +1 -0
- package/dist/{chunk-FB56NAAH.cjs → chunk-NO4ZCIM6.cjs} +19 -92
- package/dist/chunk-NO4ZCIM6.cjs.map +1 -0
- package/dist/{chunk-S4BJ2ADB.cjs → chunk-PCU6AG7H.cjs} +4 -4
- package/dist/{chunk-S4BJ2ADB.cjs.map → chunk-PCU6AG7H.cjs.map} +1 -1
- package/dist/{chunk-GBYHQQUY.js → chunk-PSZHBY5V.js} +221 -50
- package/dist/chunk-PSZHBY5V.js.map +1 -0
- package/dist/{chunk-6LDAIJBL.js → chunk-QBBJR7DZ.js} +2 -2
- package/dist/{chunk-6LDAIJBL.js.map → chunk-QBBJR7DZ.js.map} +1 -1
- package/dist/{chunk-3D5ZCJ7R.js → chunk-QHQ2AU45.js} +3 -3
- package/dist/{chunk-3D5ZCJ7R.js.map → chunk-QHQ2AU45.js.map} +1 -1
- package/dist/{chunk-IHEIYZPL.cjs → chunk-RJX27YEX.cjs} +2 -2
- package/dist/chunk-RJX27YEX.cjs.map +1 -0
- package/dist/{chunk-QYD4F6T7.cjs → chunk-ROXNQKOA.cjs} +2 -2
- package/dist/{chunk-QYD4F6T7.cjs.map → chunk-ROXNQKOA.cjs.map} +1 -1
- package/dist/chunk-SHEXFU6T.js +107 -0
- package/dist/chunk-SHEXFU6T.js.map +1 -0
- package/dist/chunk-T2KIN6VL.cjs +218 -0
- package/dist/chunk-T2KIN6VL.cjs.map +1 -0
- package/dist/{chunk-RCW5IPPR.js → chunk-UCT6HDUD.js} +3 -3
- package/dist/{chunk-RCW5IPPR.js.map → chunk-UCT6HDUD.js.map} +1 -1
- package/dist/chunk-UN74SYHV.cjs +115 -0
- package/dist/chunk-UN74SYHV.cjs.map +1 -0
- package/dist/{chunk-F7O2FA3F.cjs → chunk-VAO3Y3HZ.cjs} +7 -6
- package/dist/chunk-VAO3Y3HZ.cjs.map +1 -0
- package/dist/{chunk-BBJPQPGP.js → chunk-VE3OSDM7.js} +5 -3
- package/dist/chunk-VE3OSDM7.js.map +1 -0
- package/dist/{chunk-7HK2V5Q4.js → chunk-X7IVXKDE.js} +3 -3
- package/dist/{chunk-7HK2V5Q4.js.map → chunk-X7IVXKDE.js.map} +1 -1
- package/dist/{chunk-UA3EOFBS.cjs → chunk-XVCVIUZS.cjs} +8 -8
- package/dist/{chunk-UA3EOFBS.cjs.map → chunk-XVCVIUZS.cjs.map} +1 -1
- package/dist/{chunk-SIHPDZXA.js → chunk-YSTC7WRF.js} +2 -2
- package/dist/{chunk-SIHPDZXA.js.map → chunk-YSTC7WRF.js.map} +1 -1
- package/dist/compliance/index.cjs +15 -15
- package/dist/compliance/index.d.cts +4 -4
- package/dist/compliance/index.d.ts +4 -4
- package/dist/compliance/index.js +5 -5
- package/dist/crypto.cjs +4 -4
- package/dist/crypto.d.cts +1 -1
- package/dist/crypto.d.ts +1 -1
- package/dist/crypto.js +2 -2
- package/dist/detectors/index.cjs +38 -38
- package/dist/detectors/index.d.cts +1 -1
- package/dist/detectors/index.d.ts +1 -1
- package/dist/detectors/index.js +3 -3
- package/dist/engine/index.cjs +70 -70
- package/dist/engine/index.d.cts +3 -3
- package/dist/engine/index.d.ts +3 -3
- package/dist/engine/index.js +8 -8
- package/dist/hash-P2VGKVFP.cjs +14 -0
- package/dist/{hash-2PSYNDMM.cjs.map → hash-P2VGKVFP.cjs.map} +1 -1
- package/dist/hash-T6YJG3DU.js +5 -0
- package/dist/{hash-CELLDNKN.js.map → hash-T6YJG3DU.js.map} +1 -1
- package/dist/index.cjs +44 -34
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +23 -5
- package/dist/index.d.ts +23 -5
- package/dist/index.js +11 -9
- package/dist/index.js.map +1 -1
- package/dist/{json-CvKtPL8l.d.cts → json-BXN577tt.d.cts} +3 -2
- package/dist/{json-BruY_-tV.d.ts → json-BudrzkOQ.d.ts} +3 -2
- package/dist/mcp/index.cjs +29 -28
- package/dist/mcp/index.cjs.map +1 -1
- package/dist/mcp/index.js +14 -13
- package/dist/mcp/index.js.map +1 -1
- package/dist/middleware/express.cjs +11 -11
- package/dist/middleware/express.d.cts +3 -3
- package/dist/middleware/express.d.ts +3 -3
- package/dist/middleware/express.js +10 -10
- package/dist/middleware/hono.cjs +11 -11
- package/dist/middleware/hono.d.cts +3 -3
- package/dist/middleware/hono.d.ts +3 -3
- package/dist/middleware/hono.js +10 -10
- package/dist/middleware/index.cjs +11 -11
- package/dist/middleware/index.d.cts +3 -3
- package/dist/middleware/index.d.ts +3 -3
- package/dist/middleware/index.js +10 -10
- package/dist/schemas.cjs +47 -47
- package/dist/schemas.cjs.map +1 -1
- package/dist/schemas.d.cts +2 -2
- package/dist/schemas.d.ts +2 -2
- package/dist/schemas.js +2 -2
- package/dist/schemas.js.map +1 -1
- package/dist/{session-CEFGgjFV.d.ts → session-CPXEQ2uC.d.cts} +18 -5
- package/dist/{session-DEQrPea7.d.cts → session-D3WMN6fE.d.ts} +18 -5
- package/dist/stream.cjs +10 -8
- package/dist/stream.cjs.map +1 -1
- package/dist/stream.d.cts +1 -1
- package/dist/stream.d.ts +1 -1
- package/dist/stream.js +7 -5
- package/dist/stream.js.map +1 -1
- package/dist/{types-oxllMFYF.d.ts → types-B3VjDuP8.d.cts} +2 -282
- package/dist/{types-D5BeXwnX.d.ts → types-DHAVKfzT.d.ts} +2 -2
- package/dist/types-LZHFEgx5.d.cts +1083 -0
- package/dist/types-LZHFEgx5.d.ts +1083 -0
- package/dist/{types-BtvX8QTd.d.cts → types-vmONSbz4.d.cts} +2 -2
- package/dist/{types-BL5UWH0y.d.cts → types-yZHnS7yv.d.ts} +2 -282
- package/dist/validators.cjs +10 -10
- package/dist/validators.js +1 -1
- package/dist/vault/index.cjs +65 -46
- package/dist/vault/index.cjs.map +1 -1
- package/dist/vault/index.d.cts +98 -5
- package/dist/vault/index.d.ts +98 -5
- package/dist/vault/index.js +11 -5
- package/dist/vault/index.js.map +1 -1
- package/package.json +16 -7
- package/dist/chunk-2ZZHLCEJ.js.map +0 -1
- package/dist/chunk-BBJPQPGP.js.map +0 -1
- package/dist/chunk-CRXRJZEV.cjs +0 -82
- package/dist/chunk-F7O2FA3F.cjs.map +0 -1
- package/dist/chunk-FB56NAAH.cjs.map +0 -1
- package/dist/chunk-G4AN7FND.js.map +0 -1
- package/dist/chunk-GBYHQQUY.js.map +0 -1
- package/dist/chunk-GS3FRH4K.js.map +0 -1
- package/dist/chunk-IHEIYZPL.cjs.map +0 -1
- package/dist/chunk-IJAMLYOT.cjs.map +0 -1
- package/dist/chunk-PKHZ7CVI.js.map +0 -1
- package/dist/chunk-S7NH6CHY.cjs.map +0 -1
- package/dist/chunk-YMLR375Z.js.map +0 -1
- package/dist/chunk-ZXPZ7W37.cjs.map +0 -1
- package/dist/hash-2PSYNDMM.cjs +0 -14
- package/dist/hash-CELLDNKN.js +0 -5
- package/dist/types-cbGVW8cD.d.cts +0 -592
- package/dist/types-cbGVW8cD.d.ts +0 -592
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/engine/resolve.ts","../src/engine/pipeline.ts","../src/engine/replacers.ts","../src/engine/precise.ts","../src/engine/compile.ts"],"names":[],"mappings":";;;;;;;;;AAwCA,IAAM,UAAA,GAAa,IAAA;AAMnB,SAAS,cAAc,UAAA,EAA8C;AACnE,EAAA,MAAM,SAAS,CAAC,GAAG,UAAU,CAAA,CAAE,KAAK,CAAC,CAAA,EAAG,CAAA,KAAM,CAAA,CAAE,QAAQ,CAAA,CAAE,KAAA,IAAS,CAAA,CAAE,UAAA,GAAa,EAAE,UAAU,CAAA;AAC9F,EAAA,MAAM,MAAkB,EAAC;AACzB,EAAA,IAAI,MAAA,GAAS,CAAA;AACb,EAAA,KAAA,MAAW,aAAa,MAAA,EAAQ;AAC9B,IAAA,IAAI,SAAA,CAAU,QAAQ,MAAA,EAAQ;AAC9B,IAAA,MAAA,GAAS,SAAA,CAAU,GAAA;AACnB,IAAA,IAAI,UAAU,OAAA,EAAS;AACvB,IAAA,GAAA,CAAI,IAAA,CAAK;AAAA,MACP,OAAO,SAAA,CAAU,KAAA;AAAA,MACjB,KAAK,SAAA,CAAU,GAAA;AAAA,MACf,YAAY,SAAA,CAAU,UAAA;AAAA,MACtB,UAAU,SAAA,CAAU,QAAA;AAAA,MACpB,QAAA,EAAU;AAAA,KACX,CAAA;AAAA,EACH;AACA,EAAA,OAAO,GAAA;AACT;AAGA,SAAS,UAAA,CAAW,GAAc,CAAA,EAAsB;AACtD,EAAA,OACE,EAAE,UAAA,GAAa,CAAA,CAAE,cACjB,CAAA,CAAE,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,GAC5B,EAAE,kBAAA,EAAoB,IAAA,CAAK,kBAAA,EAAmB,GAC9C,EAAC;AAAA,IACL,GAAI,KAAK,OAAA,KAAY,MAAA,GAAY,EAAE,OAAA,EAAS,IAAA,CAAK,OAAA,EAAQ,GAAI;AAAC,GAC/D,CAAA;AACH","file":"chunk-G4AN7FND.js","sourcesContent":["/**\n * @module engine/resolve\n * @description Overlap resolution on spans. Turns the raw, possibly\n * overlapping hits of several detectors into a list of disjoint spans.\n */\n\nimport type { OverlapPolicy } from \"./types.js\";\n\n/**\n * A raw detector hit.\n */\nexport interface Candidate {\n /** Start offset in the scanned text. */\n readonly start: number;\n /** Exclusive end offset in the scanned text. */\n readonly end: number;\n /** Confidence score in [0, 1]. */\n readonly confidence: number;\n /** Index of the reporting detector in the pipeline's detector list. */\n readonly detector: number;\n /** `true` when the hit matches an allow rule and must be left untouched. */\n readonly allowed: boolean;\n}\n\n/**\n * A span that survived overlap resolution.\n */\nexport interface Resolved {\n /** Start offset in the scanned text. */\n readonly start: number;\n /** Exclusive end offset in the scanned text. */\n readonly end: number;\n /** Confidence score in [0, 1]. */\n readonly confidence: number;\n /** Index of the reporting detector in the pipeline's detector list. */\n readonly detector: number;\n /** `true` for the uncovered remainder of a hit that lost to another one. */\n readonly residual: boolean;\n}\n\nconst WHITESPACE = /\\s/;\n\n/**\n * The 1.x rule: earliest start wins, ties go to the higher confidence, and\n * every hit that overlaps an accepted one is dropped entirely.\n */\nfunction resolveLegacy(candidates: readonly Candidate[]): Resolved[] {\n const sorted = [...candidates].sort((a, b) => a.start - b.start || b.confidence - a.confidence);\n const out: Resolved[] = [];\n let cursor = 0;\n for (const candidate of sorted) {\n if (candidate.start < cursor) continue;\n cursor = candidate.end;\n if (candidate.allowed) continue;\n out.push({\n start: candidate.start,\n end: candidate.end,\n confidence: candidate.confidence,\n detector: candidate.detector,\n residual: false,\n });\n }\n return out;\n}\n\n/** Order in which overlapping hits are accepted. */\nfunction byPriority(a: Candidate, b: Candidate): number {\n return (\n b.confidence - a.confidence ||\n b.end - b.start - (a.end - a.start) ||\n a.start - b.start ||\n a.detector - b.detector\n );\n}\n\n/**\n * Resolve one group of transitively overlapping hits, which lie in\n * `text[base, end)`. One flag per character records what has been claimed, so\n * the cost is the total length of the hits rather than their number squared.\n */\nfunction resolveCluster(\n text: string,\n cluster: Candidate[],\n base: number,\n end: number,\n out: Resolved[],\n): void {\n const [only] = cluster;\n if (cluster.length === 1 && only !== undefined) {\n if (!only.allowed) out.push({ ...stripAllowed(only), residual: false });\n return;\n }\n\n cluster.sort(byPriority);\n const claimed = new Uint8Array(end - base);\n\n for (const candidate of cluster) {\n // Collect what the candidate adds to the characters claimed so far.\n const gaps: { start: number; end: number }[] = [];\n let open = -1;\n for (let at = candidate.start; at < candidate.end; at++) {\n if (claimed[at - base] === 0) {\n if (open < 0) open = at;\n } else if (open >= 0) {\n gaps.push({ start: open, end: at });\n open = -1;\n }\n }\n if (open >= 0) gaps.push({ start: open, end: candidate.end });\n\n const [first] = gaps;\n const untouched =\n gaps.length === 1 && first?.start === candidate.start && first.end === candidate.end;\n\n if (untouched) {\n claimed.fill(1, candidate.start - base, candidate.end - base);\n if (!candidate.allowed) out.push({ ...stripAllowed(candidate), residual: false });\n continue;\n }\n\n // A hit the caller allow-listed never produces partial replacements.\n if (candidate.allowed) continue;\n\n for (const gap of gaps) {\n // Keep the whitespace around a remainder, so words do not run together.\n let { start, end: stop } = gap;\n while (start < stop && WHITESPACE.test(text.charAt(start))) start++;\n while (stop > start && WHITESPACE.test(text.charAt(stop - 1))) stop--;\n if (start === stop) continue;\n claimed.fill(1, start - base, stop - base);\n out.push({\n start,\n end: stop,\n confidence: candidate.confidence,\n detector: candidate.detector,\n residual: true,\n });\n }\n }\n}\n\nfunction stripAllowed(candidate: Candidate): Omit<Resolved, \"residual\"> {\n return {\n start: candidate.start,\n end: candidate.end,\n confidence: candidate.confidence,\n detector: candidate.detector,\n };\n}\n\n/**\n * The default rule: within each group of overlapping hits, hits are accepted\n * by priority, and whatever a losing hit covers beyond the accepted ones is\n * kept as a residual span. No detected character is left uncovered.\n */\nfunction resolveCover(text: string, candidates: readonly Candidate[]): Resolved[] {\n const sorted = [...candidates].sort((a, b) => a.start - b.start || a.end - b.end);\n const out: Resolved[] = [];\n\n let cluster: Candidate[] = [];\n let clusterStart = 0;\n let clusterEnd = -1;\n for (const candidate of sorted) {\n if (cluster.length > 0 && candidate.start >= clusterEnd) {\n resolveCluster(text, cluster, clusterStart, clusterEnd, out);\n cluster = [];\n }\n if (cluster.length === 0) clusterStart = candidate.start;\n cluster.push(candidate);\n clusterEnd = Math.max(clusterEnd, candidate.end);\n }\n if (cluster.length > 0) resolveCluster(text, cluster, clusterStart, clusterEnd, out);\n\n return out.sort((a, b) => a.start - b.start);\n}\n\n/**\n * Resolve overlapping hits into disjoint spans in document order.\n *\n * @param text - The scanned text (used to trim whitespace from remainders).\n * @param candidates - Raw hits, in any order.\n * @param policy - The overlap policy.\n * @returns Disjoint spans sorted by start offset. Allow-listed hits are not returned.\n *\n * @example\n * ```ts\n * resolveSpans(\"a@b.co\", [{ start: 0, end: 6, confidence: 0.99, detector: 0, allowed: false }], \"cover\");\n * // [{ start: 0, end: 6, confidence: 0.99, detector: 0, residual: false }]\n * ```\n */\nexport function resolveSpans(\n text: string,\n candidates: readonly Candidate[],\n policy: OverlapPolicy,\n): Resolved[] {\n if (candidates.length === 0) return [];\n return policy === \"legacy\" ? resolveLegacy(candidates) : resolveCover(text, candidates);\n}\n","/**\n * @module engine/pipeline\n * @description The pipeline orchestrator: runs detectors, filters and\n * resolves their hits on offsets, and assembles the output in one\n * left-to-right pass.\n */\n\nimport { AsyncStrategyError, ValidationError } from \"../errors.js\";\nimport { resolveSpans } from \"./resolve.js\";\nimport type { Candidate, Resolved } from \"./resolve.js\";\nimport type {\n AllowRule,\n AppliedSpan,\n DetectedSpan,\n Pipeline,\n PipelineOptions,\n ReplaceContext,\n Replacer,\n SpanDetector,\n TransformResult,\n} from \"./types.js\";\n\nconst NO_SPANS: readonly AppliedSpan[] = Object.freeze([]);\n\nconst OVERLAP_POLICIES: ReadonlySet<string> = new Set([\"cover\", \"legacy\"]);\n\n/** Signals `collect()` to stop after the first qualifying hit. */\nconst STOP = Symbol(\"stop\");\n\ntype AllowTest = (\n value: string,\n start: number,\n end: number,\n owner: SpanDetector,\n confidence: number,\n) => boolean;\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\n/**\n * Compile allow rules into a single predicate. Returns `undefined` when there\n * are no rules, so callers can skip the check entirely.\n */\nfunction compileAllow(rules: readonly AllowRule[], caseSensitive: boolean): AllowTest | undefined {\n if (rules.length === 0) return undefined;\n\n const exact = new Set<string>();\n const patterns: RegExp[] = [];\n const predicates: ((value: string, span: DetectedSpan) => boolean)[] = [];\n\n for (const rule of rules) {\n if (typeof rule === \"string\") {\n exact.add(caseSensitive ? rule : rule.toLowerCase());\n } else if (rule instanceof RegExp) {\n // Drop `g` and `y`: a stateful `lastIndex` would make `test()` alternate.\n patterns.push(new RegExp(rule.source, rule.flags.replace(/[gy]/g, \"\")));\n } else if (typeof rule === \"function\") {\n predicates.push(rule);\n } else {\n throw new ValidationError(\"allow\", \"entries must be strings, RegExp instances or functions\");\n }\n }\n\n return (value, start, end, owner, confidence) => {\n if (exact.has(caseSensitive ? value : value.toLowerCase())) return true;\n for (const pattern of patterns) if (pattern.test(value)) return true;\n if (predicates.length === 0) return false;\n const span: DetectedSpan = {\n start,\n end,\n category: owner.category,\n confidence,\n detector: owner.id,\n residual: false,\n };\n return predicates.some((predicate) => predicate(value, span));\n };\n}\n\n/**\n * Create a reusable detection-and-replacement pipeline.\n *\n * @param options - Detectors, replacement plan and filters.\n * @returns An immutable {@link Pipeline}.\n * @throws {@link ValidationError} When the configuration is invalid.\n *\n * @example\n * ```ts\n * import { createPipeline, emailDetector, creditCardDetector, redactWith, maskWith } from \"anonyma/engine\";\n *\n * const pipeline = createPipeline({\n * detectors: [emailDetector, creditCardDetector],\n * replace: {\n * fallback: redactWith(),\n * byCategory: { \"credit-card\": maskWith({ keepTrailing: 4 }) },\n * },\n * });\n *\n * pipeline.transform(\"Mail alice@example.com, card 4111 1111 1111 1111\").text;\n * // \"Mail [REDACTED], card ***************1111\"\n * ```\n */\nexport function createPipeline(options: PipelineOptions): Pipeline {\n const detectors = Object.freeze([...options.detectors]);\n const { minConfidence = 0, overlap = \"cover\", allowCaseSensitive = false } = options;\n\n const seen = new Set<string>();\n for (const detector of detectors) {\n if (seen.has(detector.id)) {\n throw new ValidationError(\"detectors\", `contains the id \"${detector.id}\" more than once`);\n }\n seen.add(detector.id);\n }\n if (typeof minConfidence !== \"number\" || !(minConfidence >= 0 && minConfidence <= 1)) {\n throw new ValidationError(\"minConfidence\", \"must be a number between 0 and 1\");\n }\n if (!OVERLAP_POLICIES.has(overlap)) {\n throw new ValidationError(\"overlap\", 'must be \"cover\" or \"legacy\"');\n }\n if (typeof options.replace.fallback !== \"function\") {\n throw new ValidationError(\"replace.fallback\", \"must be a function\");\n }\n\n const fallback = options.replace.fallback;\n const byCategory = new Map<string, Replacer>();\n for (const [category, replacer] of Object.entries(options.replace.byCategory ?? {})) {\n if (typeof replacer !== \"function\") {\n throw new ValidationError(`replace.byCategory.${category}`, \"must be a function\");\n }\n byCategory.set(category, replacer);\n }\n\n const allow = compileAllow(options.allow ?? [], allowCaseSensitive);\n\n function owner(index: number): SpanDetector {\n const detector = detectors[index];\n /* v8 ignore next 3 -- indices only ever come from this pipeline's own detector list */\n if (detector === undefined) {\n throw new ValidationError(\"detector\", \"index out of range\");\n }\n return detector;\n }\n\n /**\n * Run every detector and collect the hits that pass the confidence filter.\n * With `first` set, returns `STOP` as soon as one hit that is not\n * allow-listed has been seen.\n */\n function collect(text: string, first: boolean): Candidate[] | typeof STOP {\n if (typeof text !== \"string\") {\n throw new ValidationError(\"text\", \"must be a string\");\n }\n const candidates: Candidate[] = [];\n const state = { index: 0, found: false };\n\n const emit = (start: number, end: number, confidence: number): void => {\n if (\n !Number.isInteger(start) ||\n !Number.isInteger(end) ||\n start < 0 ||\n end <= start ||\n end > text.length ||\n !(confidence >= 0 && confidence <= 1)\n ) {\n throw new ValidationError(\n \"detector\",\n `\"${owner(state.index).id}\" reported an invalid span`,\n );\n }\n if (confidence < minConfidence) return;\n const allowed =\n allow?.(text.slice(start, end), start, end, owner(state.index), confidence) === true;\n if (!allowed) state.found = true;\n candidates.push({ start, end, confidence, detector: state.index, allowed });\n };\n\n for (const [index, detector] of detectors.entries()) {\n if (detector.prefilter?.(text) === false) continue;\n state.index = index;\n detector.scan(text, emit);\n if (first && state.found) return STOP;\n }\n return candidates;\n }\n\n function describe(resolved: Resolved): DetectedSpan {\n const detector = owner(resolved.detector);\n return {\n start: resolved.start,\n end: resolved.end,\n category: detector.category,\n confidence: resolved.confidence,\n detector: detector.id,\n residual: resolved.residual,\n };\n }\n\n function scan(text: string): DetectedSpan[] {\n const candidates = collect(text, false);\n /* v8 ignore next -- collect() only stops early when asked to */\n if (candidates === STOP) return [];\n return resolveSpans(text, candidates, overlap).map(describe);\n }\n\n function test(text: string): boolean {\n // Without allow rules any hit survives resolution in some form. With allow\n // rules an allow-listed hit can shadow others, so resolve to be exact.\n if (allow === undefined) return collect(text, true) === STOP;\n return scan(text).length > 0;\n }\n\n function context(span: DetectedSpan, ordinal: number): ReplaceContext {\n return {\n category: span.category,\n detector: span.detector,\n confidence: span.confidence,\n start: span.start,\n end: span.end,\n ordinal,\n residual: span.residual,\n };\n }\n\n function replace(value: string, replaceContext: ReplaceContext): string | Promise<string> {\n return (byCategory.get(replaceContext.category) ?? fallback)(value, replaceContext);\n }\n\n function checked(replacement: unknown, category: string): string {\n if (typeof replacement !== \"string\") {\n throw new ValidationError(\n \"replace\",\n `the replacer for category \"${category}\" must return a string`,\n );\n }\n return replacement;\n }\n\n function transform(text: string): TransformResult {\n const spans = scan(text);\n if (spans.length === 0) return { text, spans: NO_SPANS };\n\n const parts: string[] = [];\n const applied: AppliedSpan[] = [];\n let cursor = 0;\n let outLength = 0;\n\n for (const [i, span] of spans.entries()) {\n const replacement = replace(text.slice(span.start, span.end), context(span, i));\n if (isThenable(replacement)) {\n // Do not leave a rejection unhandled when the caller picked the wrong entry point.\n void Promise.resolve(replacement).catch(() => undefined);\n throw new AsyncStrategyError(span.category);\n }\n const value = checked(replacement, span.category);\n parts.push(text.slice(cursor, span.start), value);\n outLength += span.start - cursor;\n applied.push({ ...span, outStart: outLength, outEnd: outLength + value.length });\n outLength += value.length;\n cursor = span.end;\n }\n parts.push(text.slice(cursor));\n return { text: parts.join(\"\"), spans: applied };\n }\n\n async function transformAsync(text: string): Promise<TransformResult> {\n const spans = scan(text);\n if (spans.length === 0) return { text, spans: NO_SPANS };\n\n const parts: string[] = [];\n const applied: AppliedSpan[] = [];\n let cursor = 0;\n let outLength = 0;\n\n for (const [i, span] of spans.entries()) {\n const value = checked(\n await replace(text.slice(span.start, span.end), context(span, i)),\n span.category,\n );\n parts.push(text.slice(cursor, span.start), value);\n outLength += span.start - cursor;\n applied.push({ ...span, outStart: outLength, outEnd: outLength + value.length });\n outLength += value.length;\n cursor = span.end;\n }\n parts.push(text.slice(cursor));\n return { text: parts.join(\"\"), spans: applied };\n }\n\n return Object.freeze({ detectors, scan, test, replace, transform, transformAsync });\n}\n\n/**\n * Return the text a span refers to.\n *\n * @param text - The text the span was detected in.\n * @param span - The span.\n * @returns The matched text.\n *\n * @example\n * ```ts\n * const [span] = pipeline.scan(\"Mail alice@example.com\");\n * spanText(\"Mail alice@example.com\", span); // \"alice@example.com\"\n * ```\n */\nexport function spanText(text: string, span: Pick<DetectedSpan, \"start\" | \"end\">): string {\n return text.slice(span.start, span.end);\n}\n","/**\n * @module engine/replacers\n * @description Replacer factories for the span engine. Each factory can be\n * imported on its own, so a pipeline only pulls in the strategies it uses.\n *\n * Every built-in replacer fails closed: if a strategy would hand back the\n * original value unchanged, the value is redacted instead.\n */\n\nimport { ValidationError } from \"../errors.js\";\nimport { encrypt } from \"../strategies/encrypt.js\";\nimport { generalize } from \"../strategies/generalize.js\";\nimport { hash } from \"../strategies/hash.js\";\nimport { mask } from \"../strategies/mask.js\";\nimport { pseudonymize } from \"../strategies/pseudonymize.js\";\nimport { redact } from \"../strategies/redact.js\";\nimport { synthesize } from \"../strategies/synthesize.js\";\nimport type {\n EncryptOptions,\n GeneralizeOptions,\n HashOptions,\n MaskOptions,\n PseudonymizeOptions,\n RedactOptions,\n SynthesizeOptions,\n} from \"../types.js\";\nimport type { CompileDependencies, Replacer, StrategySpec } from \"./types.js\";\n\n/**\n * Replacement used when a strategy would otherwise return the original value.\n * @internal\n */\nexport const FAIL_CLOSED_LABEL = \"[REDACTED]\";\n\n/** A range may show this many leading digits of a number; beyond that it is an identifier. */\nconst MAX_REVEALED_DIGITS = 3;\n\nfunction failClosed(value: string, replacement: string): string {\n return replacement === value && value.length > 0 ? FAIL_CLOSED_LABEL : replacement;\n}\n\n/**\n * Replace every value with the same fixed string.\n *\n * @param replacement - The replacement text. Must not be empty.\n * @returns A synchronous {@link Replacer}.\n * @throws {@link ValidationError} When `replacement` is empty or whitespace only.\n *\n * @example\n * ```ts\n * constant(\"***\")(\"alice@example.com\", context); // \"***\"\n * ```\n */\nexport function constant(replacement: string): Replacer {\n if (typeof replacement !== \"string\" || replacement.trim().length === 0) {\n throw new ValidationError(\"replacement\", \"must be a non-empty string\");\n }\n return () => replacement;\n}\n\n/**\n * Replace every value with a label (the `redact` strategy).\n *\n * @param options - Redaction options. The label defaults to `\"[REDACTED]\"`.\n * @returns A synchronous {@link Replacer}.\n * @throws {@link ValidationError} When the label is empty.\n *\n * @example\n * ```ts\n * redactWith({ label: \"[EMAIL]\" })(\"alice@example.com\", context); // \"[EMAIL]\"\n * ```\n */\nexport function redactWith(options: RedactOptions = {}): Replacer {\n const label = redact(\"\", options);\n return () => label;\n}\n\n/**\n * Mask every value (the `mask` strategy). A configuration that would leave a\n * value fully visible redacts it instead.\n *\n * @param options - Masking options.\n * @returns A synchronous {@link Replacer}.\n * @throws {@link ValidationError} When the options are invalid.\n *\n * @example\n * ```ts\n * maskWith({ keepTrailing: 4 })(\"4111 1111 1111 1111\", context); // \"***************1111\"\n * ```\n */\nexport function maskWith(options: MaskOptions = {}): Replacer {\n mask(\"\", options);\n return (value) => failClosed(value, mask(value, options));\n}\n\n/**\n * Replace every value with a pseudonym (the `pseudonymize` strategy).\n *\n * @param options - Pseudonymization options.\n * @returns A synchronous {@link Replacer}.\n * @throws {@link ValidationError} When the prefix is invalid.\n *\n * @remarks\n * The seeded form of this strategy is not cryptographic. For keyed,\n * deterministic pseudonyms use a keyed tokenizer from `\"anonyma/vault\"`.\n *\n * @example\n * ```ts\n * pseudonymizeWith({ prefix: \"user_\" })(\"alice@example.com\", context); // \"user_9d1ba6c1f89a49d9\"\n * ```\n */\nexport function pseudonymizeWith(options: PseudonymizeOptions = {}): Replacer {\n pseudonymize(\"\", options);\n return (value) => failClosed(value, pseudonymize(value, options));\n}\n\n/**\n * Replace numeric values with a range (the `generalize` strategy). Values that\n * are not numeric are redacted rather than passed through, and so is a number\n * whose range would still show more than three of its leading digits: a range\n * hides a quantity such as an age or a year, not an identifier such as an\n * account or a card number.\n *\n * @param options - Generalization options.\n * @returns A synchronous {@link Replacer}.\n * @throws {@link ValidationError} When `bucketSize` is invalid or `1`.\n *\n * @example\n * ```ts\n * generalizeWith({ bucketSize: 10 })(\"27\", context); // \"20-29\"\n * generalizeWith()(\"alice@example.com\", context); // \"[REDACTED]\"\n * generalizeWith()(\"123456789\", context); // \"[REDACTED]\"\n * ```\n */\nexport function generalizeWith(options: GeneralizeOptions = {}): Replacer {\n generalize(\"0\", options);\n const bucketSize = options.bucketSize ?? 10;\n if (bucketSize < 2) {\n throw new ValidationError(\n \"bucketSize\",\n \"must be at least 2: a range of one value hides nothing\",\n );\n }\n const hiddenDigits = Math.floor(Math.log10(bucketSize));\n return (value) => {\n const parsed = Number(value);\n if (value.trim().length === 0 || !Number.isFinite(parsed)) return FAIL_CLOSED_LABEL;\n const digits = String(Math.abs(Math.trunc(parsed))).length;\n if (digits - hiddenDigits > MAX_REVEALED_DIGITS) return FAIL_CLOSED_LABEL;\n return failClosed(value, generalize(value, options));\n };\n}\n\n/**\n * Replace every value with format-preserving synthetic data (the `synthesize`\n * strategy), using the category of the span to pick the generator.\n *\n * @param options - Synthesis options.\n * @returns A synchronous {@link Replacer}.\n *\n * @example\n * ```ts\n * synthesizeWith({ seed: \"s3cret\" })(\"alice@example.com\", context); // \"grace.taylor95@demo.io\"\n * ```\n */\nexport function synthesizeWith(options: SynthesizeOptions = {}): Replacer {\n return (value, context) => failClosed(value, synthesize(value, context.category, options));\n}\n\n/**\n * Replace every value with a SHA-256 digest (the `hash` strategy).\n *\n * @param options - Hashing options.\n * @returns An asynchronous {@link Replacer}.\n * @throws {@link ValidationError} When `truncate` is not an integer between 1 and 64.\n *\n * @remarks\n * A hash of a low-entropy identifier can be reversed by enumeration. Supply a\n * `pepper`, or prefer a keyed tokenizer from `\"anonyma/vault\"`.\n *\n * @example\n * ```ts\n * await hashWith({ pepper: \"p\", truncate: 32 })(\"alice@example.com\", context);\n * ```\n */\nexport function hashWith(options: HashOptions = {}): Replacer {\n const { truncate = 16 } = options;\n if (!Number.isInteger(truncate) || truncate < 1 || truncate > 64) {\n throw new ValidationError(\"truncate\", \"must be an integer between 1 and 64 (inclusive)\");\n }\n return (value) => hash(value, options);\n}\n\n/**\n * Replace every value with AES-GCM ciphertext in the 1.x `encrypt()` format.\n *\n * @param options - Key material and encoding.\n * @returns An asynchronous {@link Replacer}.\n * @throws {@link ValidationError} When neither `passphrase` nor `keyBytes` is given,\n * `keyBytes` is not 16 or 32 bytes long, or `encoding` is unknown.\n *\n * @remarks\n * With a `passphrase` the key is derived again for every value, which costs\n * tens of milliseconds each. Pass `keyBytes`, or use a sealed tokenizer from\n * `\"anonyma/vault\"`, for anything but small inputs.\n *\n * @example\n * ```ts\n * await encryptWith({ keyBytes })(\"alice@example.com\", context); // \"base64:…:…\"\n * ```\n */\nexport function encryptWith(options: EncryptOptions): Replacer {\n if (options.keyBytes === undefined && (options.passphrase ?? \"\") === \"\") {\n throw new ValidationError(\"encryption\", \"requires `passphrase` or `keyBytes`\");\n }\n if (\n options.keyBytes !== undefined &&\n options.keyBytes.length !== 16 &&\n options.keyBytes.length !== 32\n ) {\n throw new ValidationError(\"encryption.keyBytes\", \"must be 16 or 32 bytes long\");\n }\n const encoding: unknown = options.encoding;\n if (encoding !== undefined && encoding !== \"base64\" && encoding !== \"hex\") {\n throw new ValidationError(\"encryption.encoding\", 'must be \"base64\" or \"hex\"');\n }\n return (value) => encrypt(value, options);\n}\n\n/**\n * Build the replacer for a strategy given as data.\n *\n * @param spec - The strategy.\n * @param dependencies - Provider and secrets for strategies that need them.\n * @returns The {@link Replacer} implementing the strategy.\n * @throws {@link ValidationError} When the strategy needs a dependency that was not supplied,\n * or its options are invalid.\n *\n * @example\n * ```ts\n * const replacer = strategyReplacer({ strategy: \"mask\", keepTrailing: 4 });\n * ```\n */\nexport function strategyReplacer(\n spec: StrategySpec,\n dependencies: CompileDependencies = {},\n): Replacer {\n const secrets = dependencies.secrets ?? {};\n switch (spec.strategy) {\n case \"redact\":\n return redactWith(spec);\n case \"mask\":\n return maskWith(spec);\n case \"generalize\":\n return generalizeWith(spec);\n case \"pseudonymize\":\n return pseudonymizeWith(\n spec.seed === undefined && secrets.pseudonymizeSeed !== undefined\n ? { ...spec, seed: secrets.pseudonymizeSeed }\n : spec,\n );\n case \"synthesize\":\n return synthesizeWith(\n spec.seed === undefined && secrets.synthesizeSeed !== undefined\n ? { ...spec, seed: secrets.synthesizeSeed }\n : spec,\n );\n case \"hash\":\n return hashWith(\n spec.pepper === undefined && secrets.hashPepper !== undefined\n ? { ...spec, pepper: secrets.hashPepper }\n : spec,\n );\n case \"encrypt\": {\n if (dependencies.encryption === undefined) {\n throw new ValidationError(\"encryption\", \"is required by the `encrypt` strategy\");\n }\n return encryptWith(dependencies.encryption);\n }\n case \"tokenize\": {\n const provider = dependencies.tokenization;\n if (provider === undefined) {\n throw new ValidationError(\"tokenization\", \"is required by the `tokenize` strategy\");\n }\n return (value, context) => provider.tokenize(value, { category: context.category });\n }\n default: {\n const unknown: never = spec;\n throw new ValidationError(\n \"strategy\",\n `\"${String((unknown as { strategy?: unknown }).strategy)}\" is not a known strategy`,\n );\n }\n }\n}\n","/**\n * @module engine/precise\n * @description Native span detectors for the five identifier families whose\n * formats are defined by a standard: email addresses, US Social Security\n * Numbers, IBANs, IP addresses and payment card numbers.\n *\n * Unlike the 1.x detectors they validate what they match (issuer ranges and\n * Luhn for cards, the ISO 13616 country length table and mod-97 for IBANs,\n * SSA allocation rules for SSNs, the RFC 4291 text grammar for IPv6) and they\n * look at the surrounding text to reject look-alikes such as version strings,\n * ZIP+4 codes, file names and MAC addresses. Their patterns are compiled once.\n */\n\nimport { ibanMod97, luhn } from \"../validators.js\";\nimport { defineDetector } from \"./detector.js\";\nimport type { EmitSpan, SpanDetector } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Email\n// ---------------------------------------------------------------------------\n\n// The local part is bounded (RFC 5321 allows 64 octets), so that a long run of\n// local-part characters costs a fixed amount per start position.\nconst EMAIL_PATTERN =\n /(?<![\\p{L}\\p{N}_%+-])[\\p{L}\\p{N}_%+-](?:[\\p{L}\\p{N}._%+'-]{0,62}[\\p{L}\\p{N}_%+-])?@((?:[\\p{L}\\p{N}](?:[\\p{L}\\p{N}-]{0,61}[\\p{L}\\p{N}])?\\.)+)(xn--[a-z0-9-]{1,59}|\\p{L}{2,24})(?!\\p{L})/giu;\n\n/** \"Top-level domains\" that are really asset or unit-file suffixes. */\nconst NOT_A_TLD: ReadonlySet<string> = new Set([\n \"png\",\n \"jpg\",\n \"jpeg\",\n \"gif\",\n \"svg\",\n \"webp\",\n \"ico\",\n \"bmp\",\n \"css\",\n \"js\",\n \"json\",\n \"map\",\n \"service\",\n \"socket\",\n \"timer\",\n \"mount\",\n \"target\",\n \"slice\",\n \"scope\",\n]);\n\n/** Top-level domains common enough that `x@y.com(` is an address and not a method call. */\nconst COMMON_TLD: ReadonlySet<string> = new Set([\n \"com\",\n \"org\",\n \"net\",\n \"edu\",\n \"gov\",\n \"mil\",\n \"int\",\n \"info\",\n \"biz\",\n \"name\",\n \"pro\",\n \"io\",\n \"co\",\n \"me\",\n \"dev\",\n \"app\",\n \"ai\",\n]);\n\n/**\n * `scheme://user[:password]` immediately before the match: URL userinfo, not\n * an address. Only characters that occur in a user name or a password may sit\n * between the scheme and the match, so `\"https://acme.com\",\"email\":\"a@b.co\"`\n * and `https://acme.com,a@b.co` are still addresses.\n */\nconst URL_USERINFO_BEFORE = /[a-z][a-z0-9+.-]*:\\/\\/[a-z0-9._~%!$*+:-]*$/i;\n/** A mail header whose value is a list of `<message identifiers>`, not of addresses. */\nconst MESSAGE_ID_BEFORE =\n /\\b(?:message-id|in-reply-to|references)\\s*:\\s*(?:<[^\\s<>]*>\\s*)*<[^\\s<>@]*$/i;\n\nfunction scanEmail(text: string, emit: EmitSpan): void {\n EMAIL_PATTERN.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = EMAIL_PATTERN.exec(text)) !== null) {\n const start = match.index;\n const end = start + match[0].length;\n const domain = match[1] ?? \"\";\n const tld = (match[2] ?? \"\").toLowerCase();\n\n if (NOT_A_TLD.has(tld)) continue;\n // \"name@1.0.0-beta\": a package version, not a domain.\n if (/^\\d+\\.\\d+\\./.test(domain)) continue;\n // \"W@x.flatten()\": a call on a short identifier, not an address.\n if (\n text.charCodeAt(end) === 40 &&\n match[0].indexOf(\"@\") <= 2 &&\n tld.length > 2 &&\n !COMMON_TLD.has(tld)\n ) {\n continue;\n }\n // The account every Git remote uses (\"git@github.com:org/repo.git\") is nobody's address.\n if (match[0].startsWith(\"git@\")) continue;\n\n const before = text.slice(Math.max(0, start - 96), start);\n if (URL_USERINFO_BEFORE.test(before) || MESSAGE_ID_BEFORE.test(before)) continue;\n\n emit(start, end, 0.99);\n }\n}\n\n/**\n * Email addresses, including internationalised ones (RFC 6531).\n *\n * @example\n * ```ts\n * import { createPipeline, emailDetector, redactWith } from \"anonyma/engine\";\n *\n * createPipeline({ detectors: [emailDetector], replace: { fallback: redactWith() } })\n * .transform(\"Write to josé.garcia@example.com\").text;\n * // \"Write to [REDACTED]\"\n * ```\n */\nexport const emailDetector: SpanDetector = defineDetector({\n id: \"email\",\n category: \"email\",\n prefilter: (text) => text.includes(\"@\"),\n scan: scanEmail,\n maxMatchLength: 320,\n});\n\nconst OBFUSCATED_EMAIL_PATTERN =\n /(?<![\\p{L}\\p{N}._%+-])[\\p{L}\\p{N}_%+-][\\p{L}\\p{N}._%+-]{0,63}(?:\\s*(?:\\[at\\]|\\(at\\)|\\{at\\}|\\[@\\])\\s*|[ \\t]+@[ \\t]*|@[ \\t]+)[\\p{L}\\p{N}](?:[\\p{L}\\p{N}-]*[\\p{L}\\p{N}])?(?:\\s*(?:\\[dot\\]|\\(dot\\)|\\{dot\\}|\\[\\.\\]|\\.)\\s*[\\p{L}\\p{N}](?:[\\p{L}\\p{N}-]*[\\p{L}\\p{N}])?)*\\s*(?:\\[dot\\]|\\(dot\\)|\\{dot\\}|\\[\\.\\]|\\.)\\s*\\p{L}{2,24}(?![\\p{L}\\p{N}])/giu;\n\n/**\n * Obfuscated email addresses such as `user [at] example [dot] com`,\n * `user[@]example[.]com` and `user @ example.com`. Used by aggressive\n * pipelines in addition to {@link emailDetector}.\n *\n * @example\n * ```ts\n * createPipeline({ detectors: [emailDetector, obfuscatedEmailDetector], replace: { fallback: redactWith() } });\n * ```\n */\nexport const obfuscatedEmailDetector: SpanDetector = defineDetector({\n id: \"email/obfuscated\",\n category: \"email\",\n prefilter: (text) => /\\[at\\]|\\(at\\)|\\{at\\}|@/i.test(text),\n scan(text, emit) {\n OBFUSCATED_EMAIL_PATTERN.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = OBFUSCATED_EMAIL_PATTERN.exec(text)) !== null) {\n emit(match.index, match.index + match[0].length, 0.75);\n }\n },\n maxMatchLength: 320,\n});\n\n// ---------------------------------------------------------------------------\n// US Social Security Number\n// ---------------------------------------------------------------------------\n\nconst SSN_SEPARATOR = String.raw`(?:\\s?[-\\u2010-\\u2015\\u2212.]\\s?|\\s{1,2})`;\nconst SSN_SEPARATED_PATTERN = new RegExp(\n String.raw`(?<!\\d)(?<!\\d[-\\u2010-\\u2015\\u2212./])(\\d{3})${SSN_SEPARATOR}(\\d{2})${SSN_SEPARATOR}(\\d{4})(?![-\\u2010-\\u2015\\u2212.]?\\d)`,\n \"g\",\n);\n// After the label, up to 24 characters that are neither digits nor the end of\n// a sentence may precede the number: \"SSN is\", \"SSN of the applicant:\".\nconst SSN_LABELLED_PATTERN =\n /(?:\\bssn|\\bss#|\\bsocial\\s+security)(?:\\s*(?:number|num\\.?|no\\.?|#))?[^\\d\\n.;!?]{0,24}(\\d{9})(?!\\d)/dgi;\n\n/** SSA allocation rules: no area 000, 666 or 900-999, no group 00, no serial 0000. */\nfunction isAssignableSsn(area: string, group: string, serial: string): boolean {\n return (\n area !== \"000\" && area !== \"666\" && !area.startsWith(\"9\") && group !== \"00\" && serial !== \"0000\"\n );\n}\n\nfunction scanSsn(text: string, emit: EmitSpan): void {\n SSN_SEPARATED_PATTERN.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = SSN_SEPARATED_PATTERN.exec(text)) !== null) {\n if (isAssignableSsn(match[1] ?? \"\", match[2] ?? \"\", match[3] ?? \"\")) {\n emit(match.index, match.index + match[0].length, 0.95);\n }\n }\n SSN_LABELLED_PATTERN.lastIndex = 0;\n while ((match = SSN_LABELLED_PATTERN.exec(text)) !== null) {\n const digits = match[1] ?? \"\";\n const bounds = match.indices?.[1];\n if (\n bounds !== undefined &&\n isAssignableSsn(digits.slice(0, 3), digits.slice(3, 5), digits.slice(5))\n ) {\n emit(bounds[0], bounds[1], 0.9);\n }\n }\n}\n\n/**\n * US Social Security Numbers written with separators (`123-45-6789`), and\n * unseparated nine-digit numbers only when a label such as `SSN` or\n * `social security number` precedes them in the same sentence. A bare\n * nine-digit number is not reported.\n *\n * @example\n * ```ts\n * createPipeline({ detectors: [ssnDetector], replace: { fallback: redactWith() } })\n * .transform(\"SSN 123-45-6789, ZIP 10001-1234\").text;\n * // \"SSN [REDACTED], ZIP 10001-1234\"\n * ```\n */\nexport const ssnDetector: SpanDetector = defineDetector({\n id: \"ssn\",\n category: \"ssn\",\n prefilter: (text) => /\\d{4}/.test(text),\n scan: scanSsn,\n maxMatchLength: 48,\n});\n\nconst SSN_BARE_PATTERN = /(?<![\\d.,])(\\d{3})(\\d{2})(\\d{4})(?![\\d.,]?\\d)/g;\n\n/**\n * Unseparated nine-digit numbers that satisfy the SSA allocation rules. Most\n * such numbers are not SSNs, so the confidence is low. Used by aggressive\n * pipelines in addition to {@link ssnDetector}.\n *\n * @example\n * ```ts\n * createPipeline({ detectors: [ssnDetector, bareSsnDetector], replace: { fallback: redactWith() } });\n * ```\n */\nexport const bareSsnDetector: SpanDetector = defineDetector({\n id: \"ssn/bare\",\n category: \"ssn\",\n prefilter: (text) => /\\d{9}/.test(text),\n scan(text, emit) {\n SSN_BARE_PATTERN.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = SSN_BARE_PATTERN.exec(text)) !== null) {\n if (isAssignableSsn(match[1] ?? \"\", match[2] ?? \"\", match[3] ?? \"\")) {\n emit(match.index, match.index + 9, 0.5);\n }\n }\n },\n maxMatchLength: 12,\n});\n\n// ---------------------------------------------------------------------------\n// IBAN\n// ---------------------------------------------------------------------------\n\n/**\n * IBAN length per country: the ISO 13616 registry, followed by the countries\n * that issue IBAN-format account numbers without being in the registry.\n */\nconst IBAN_LENGTHS: Readonly<Record<string, number>> = {\n AD: 24,\n AE: 23,\n AL: 28,\n AT: 20,\n AZ: 28,\n BA: 20,\n BE: 16,\n BG: 22,\n BH: 22,\n BI: 27,\n BR: 29,\n BY: 28,\n CH: 21,\n CR: 22,\n CY: 28,\n CZ: 24,\n DE: 22,\n DJ: 27,\n DK: 18,\n DO: 28,\n EE: 20,\n EG: 29,\n ES: 24,\n FI: 18,\n FK: 18,\n FO: 18,\n FR: 27,\n GB: 22,\n GE: 22,\n GI: 23,\n GL: 18,\n GR: 27,\n GT: 28,\n HN: 28,\n HR: 21,\n HU: 28,\n IE: 22,\n IL: 23,\n IQ: 23,\n IS: 26,\n IT: 27,\n JO: 30,\n KW: 30,\n KZ: 20,\n LB: 28,\n LC: 32,\n LI: 21,\n LT: 20,\n LU: 20,\n LV: 21,\n LY: 25,\n MC: 27,\n MD: 24,\n ME: 22,\n MK: 19,\n MN: 20,\n MR: 27,\n MT: 31,\n MU: 30,\n NI: 28,\n NL: 18,\n NO: 15,\n OM: 23,\n PK: 24,\n PL: 28,\n PS: 29,\n PT: 25,\n QA: 29,\n RO: 24,\n RS: 22,\n RU: 33,\n SA: 24,\n SC: 31,\n SD: 18,\n SE: 24,\n SI: 19,\n SK: 24,\n SM: 27,\n SO: 23,\n ST: 25,\n SV: 28,\n TL: 23,\n TN: 24,\n TR: 26,\n UA: 29,\n VA: 22,\n VG: 24,\n XK: 20,\n YE: 30,\n // Not in the registry.\n AO: 25,\n BF: 28,\n BJ: 28,\n CF: 27,\n CG: 27,\n CI: 28,\n CM: 27,\n CV: 25,\n DZ: 26,\n GA: 27,\n GQ: 27,\n GW: 25,\n IR: 26,\n KM: 27,\n MA: 28,\n MG: 27,\n ML: 28,\n MZ: 25,\n NE: 28,\n SN: 28,\n TD: 27,\n TG: 28,\n};\n\nconst IBAN_START_PATTERN = /(?<![A-Za-z0-9])[A-Za-z]{2}\\d{2}/g;\n\nfunction isAlphanumeric(code: number): boolean {\n return (code >= 48 && code <= 57) || (code >= 65 && code <= 90) || (code >= 97 && code <= 122);\n}\n\n/** Space, no-break space, hyphen, tab, line feed or carriage return. */\nfunction isIbanSeparator(code: number): boolean {\n return code === 32 || code === 160 || code === 45 || code === 9 || code === 10 || code === 13;\n}\n\nfunction isValidIban(collected: string): boolean {\n const normalised = collected.toUpperCase();\n const checkDigits = Number(normalised.slice(2, 4));\n return checkDigits >= 2 && checkDigits <= 98 && ibanMod97(normalised);\n}\n\n/**\n * End offset of the IBAN that starts at `start`, or -1. Exactly `length`\n * alphanumerics are collected, with at most two separators in a row.\n */\nfunction endOfIban(text: string, start: number, length: number): number {\n let collected = \"\";\n let at = start;\n let end = start;\n let separators = 2;\n while (collected.length < length && at < text.length) {\n const code = text.charCodeAt(at);\n if (isAlphanumeric(code)) {\n collected += text.charAt(at);\n separators = 0;\n end = at + 1;\n } else if (separators < 2 && isIbanSeparator(code)) {\n separators++;\n } else {\n break;\n }\n at++;\n }\n if (collected.length !== length || isAlphanumeric(text.charCodeAt(end))) return -1;\n return isValidIban(collected) ? end : -1;\n}\n\nfunction scanIban(text: string, emit: EmitSpan): void {\n IBAN_START_PATTERN.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = IBAN_START_PATTERN.exec(text)) !== null) {\n const start = match.index;\n const country = match[0].slice(0, 2).toUpperCase();\n if (!Object.hasOwn(IBAN_LENGTHS, country)) continue;\n const end = endOfIban(text, start, IBAN_LENGTHS[country] ?? 0);\n if (end < 0) continue;\n\n emit(start, end, 0.99);\n IBAN_START_PATTERN.lastIndex = end;\n }\n}\n\n/**\n * International Bank Account Numbers, validated against the country's length\n * and the mod-97 check. Spaces or hyphens between groups and lower-case\n * letters are accepted. The length table holds the ISO 13616 registry and the\n * countries that issue IBAN-format numbers outside it.\n *\n * @example\n * ```ts\n * createPipeline({ detectors: [ibanDetector], replace: { fallback: redactWith() } })\n * .transform(\"IBAN: BE68 5390 0754 7034 BIC: GKCCBEBB\").text;\n * // \"IBAN: [REDACTED] BIC: GKCCBEBB\"\n * ```\n */\nexport const ibanDetector: SpanDetector = defineDetector({\n id: \"iban\",\n category: \"iban\",\n prefilter: (text) => /[A-Za-z]{2}\\d{2}/.test(text),\n scan: scanIban,\n maxMatchLength: 72,\n});\n\n// ---------------------------------------------------------------------------\n// IPv4\n// ---------------------------------------------------------------------------\n\nconst IPV4_PATTERN =\n /(?<![\\d.])((?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.)((?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d)\\.(?:25[0-5]|2[0-4]\\d|[01]?\\d?\\d))(\\/(?:3[0-2]|[12]?\\d)(?![\\w/.]))?(?!\\.?\\d)/g;\n\n/** Words that always introduce a version number. */\nconst VERSION_BEFORE = /(?:\\bv|version|\\bver\\.?|\\bfirmware|\\brev\\.?)\\s*[:=#(\"']{0,3}\\s*$/i;\n/**\n * A product token such as `Chrome/` directly before the value. A path segment\n * (`/geoip/203.0.113.57`) and a protocol name (`tcp/203.0.113.9`) are not\n * product tokens.\n */\nconst PRODUCT_BEFORE =\n /(?<![/\\w.+-])(?!(?:tcp|udp|sctp|icmp|ip|ipv4|inet|ssh|dns|peer|host|addr|src|dst)\\/)[a-z][\\w.+-]*\\/\\s*$/i;\n/** Words that introduce a section or clause number, or an object identifier. */\nconst NUMBERING_BEFORE =\n /(?:\\bsection|\\bsec\\.|\\bchapter|\\bclause|\\bappendix|\\bannex|\\boid|\\u00a7)\\s*[:=#(\"']{0,3}\\s*$/i;\n/** Words that introduce a version or a number, and just as often an address. */\nconst WEAK_VERSION_BEFORE = /(?:\\brelease|\\bbuild)\\s*[:=#(\"']{0,3}\\s*$/i;\n/** Capitalised references (\"Table 3.2.1.1\", \"ISO-27001 5.1.2.3\"). */\nconst REFERENCE_BEFORE = /(?:\\bTable|\\bFigure|\\bFig\\.|\\b[A-Z]{2,6}-\\d+)\\s*[:=#(\"']{0,3}\\s*$/;\n/** A suffix that makes the value a version or a file name (\"1.2.3.4-beta\", \"1.2.3.4.tar\"). */\nconst VERSION_SUFFIX_AFTER = /^(?:[-.][A-Za-z]|-\\d+[A-Za-z])/;\n\n/**\n * `true` for addresses in the private, loopback, link-local, shared and\n * documentation ranges. A value in one of them is an address even where the\n * surrounding words suggest a version or a reference number.\n */\nfunction isReservedIpv4(octets: readonly string[]): boolean {\n const first = Number(octets[0]);\n const second = Number(octets[1]);\n const third = Number(octets[2]);\n return (\n first === 10 ||\n first === 127 ||\n (first === 172 && second >= 16 && second <= 31) ||\n (first === 192 && second === 168) ||\n (first === 169 && second === 254) ||\n (first === 100 && second >= 64 && second <= 127) ||\n (first === 192 && second === 0 && third === 2) ||\n (first === 198 && second === 51 && third === 100) ||\n (first === 203 && second === 0 && third === 113)\n );\n}\n\nfunction scanIpv4(text: string, emit: EmitSpan): void {\n IPV4_PATTERN.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = IPV4_PATTERN.exec(text)) !== null) {\n const start = match.index;\n let value = match[0];\n // Netmasks, broadcast and the unspecified address identify nobody.\n if (match[1] === \"255.\" || value.startsWith(\"0.0.0.0\")) continue;\n // Zero-padded octets are only credible when padded to three digits throughout\n // (\"192.168.001.010\"); \"1.200.000.000\" and \"02.123.45.67\" are numbers and phones.\n const octets = value.split(\"/\", 1).join(\"\").split(\".\");\n if (octets.some((octet) => octet.length === 2 && octet.startsWith(\"0\"))) continue;\n if (octets.includes(\"000\") && octets.some((octet) => octet.length !== 3)) continue;\n\n const before = text.slice(Math.max(0, start - 48), start);\n if (VERSION_BEFORE.test(before) || PRODUCT_BEFORE.test(before)) continue;\n // Section and clause numbers are small; an address after such a word usually is not.\n const small = octets.every((octet) => octet.length <= 2);\n if (small && NUMBERING_BEFORE.test(before)) continue;\n if (!isReservedIpv4(octets)) {\n if (WEAK_VERSION_BEFORE.test(before) || (small && REFERENCE_BEFORE.test(before))) continue;\n const end = start + value.length;\n if (VERSION_SUFFIX_AFTER.test(text.slice(end, end + 8))) continue;\n }\n // After \"//\" a slash starts a URL path, not a prefix length.\n if (match[3] !== undefined && before.endsWith(\"//\")) {\n value = value.slice(0, -match[3].length);\n }\n emit(start, start + value.length, 0.95);\n }\n}\n\n/**\n * IPv4 addresses in dotted-decimal notation, with an optional CIDR prefix\n * length. Version strings, section numbers, OIDs, netmasks and numbers with\n * more than four parts are not reported.\n *\n * @example\n * ```ts\n * createPipeline({ detectors: [ipv4Detector], replace: { fallback: redactWith() } })\n * .transform(\"client 203.0.113.57, Chrome/124.0.0.0\").text;\n * // \"client [REDACTED], Chrome/124.0.0.0\"\n * ```\n */\nexport const ipv4Detector: SpanDetector = defineDetector({\n id: \"ipv4\",\n category: \"ipv4\",\n prefilter: (text) => /\\d\\.\\d/.test(text),\n scan: scanIpv4,\n maxMatchLength: 40,\n});\n\n// ---------------------------------------------------------------------------\n// IPv6\n// ---------------------------------------------------------------------------\n\nconst IPV6_RUN_PATTERN = /[0-9A-Fa-f:.]{2,}/g;\nconst HEX_GROUP = /^[0-9A-Fa-f]{1,4}$/;\nconst DOTTED_QUAD =\n /^(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)\\.){3}(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)$/;\n\n/** Number of 16-bit groups in one side of an address, or -1 when it is malformed. */\nfunction countGroups(side: string, allowIpv4Tail: boolean): number {\n if (side === \"\") return 0;\n const groups = side.split(\":\");\n let count = 0;\n for (const [index, group] of groups.entries()) {\n if (HEX_GROUP.test(group)) count += 1;\n else if (allowIpv4Tail && index === groups.length - 1 && DOTTED_QUAD.test(group)) count += 2;\n else return -1;\n }\n return count;\n}\n\n/** RFC 4291 §2.2 text representation. */\nfunction isIpv6(candidate: string): boolean {\n const compression = candidate.indexOf(\"::\");\n if (compression < 0) {\n const groups = candidate.split(\":\");\n // Eight groups of two hex digits is an EUI-64 / MAC-style identifier.\n if (groups.length === 8 && groups.every((group) => group.length === 2)) return false;\n return countGroups(candidate, true) === 8;\n }\n if (candidate.includes(\"::\", compression + 1)) return false;\n const head = countGroups(candidate.slice(0, compression), false);\n const tail = countGroups(candidate.slice(compression + 2), true);\n return head >= 0 && tail >= 0 && head + tail <= 7 && head + tail > 0;\n}\n\nconst WORD_CHARACTER = /[\\p{L}\\p{N}_]/u;\n\nfunction scanIpv6(text: string, emit: EmitSpan): void {\n IPV6_RUN_PATTERN.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = IPV6_RUN_PATTERN.exec(text)) !== null) {\n let start = match.index;\n let value = match[0];\n // A run that starts inside a label (\"IPv6:2001:db8::1\", \"eth0:fe80::1\") or\n // right after one (\"addr:fe80::1\"): the address begins after the first colon.\n // \"x2001:db8::1\" is a malformed token, not a label.\n const glued = start > 0 && WORD_CHARACTER.test(text.charAt(start - 1));\n const colon = value.indexOf(\":\");\n if (!value.startsWith(\"::\") && (colon === 0 || (glued && colon > 0 && colon <= 2))) {\n start += colon + 1;\n value = value.slice(colon + 1);\n } else if (glued) {\n continue;\n }\n // Trailing sentence punctuation and a single trailing colon are not part of an address.\n while (value.endsWith(\".\")) value = value.slice(0, -1);\n if (value.endsWith(\":\") && !value.endsWith(\"::\")) value = value.slice(0, -1);\n // No address is longer than 45 characters.\n if (value.length < 3 || value.length > 45) continue;\n if (value.indexOf(\":\") === value.lastIndexOf(\":\")) continue;\n\n const end = start + value.length;\n if (WORD_CHARACTER.test(text.charAt(end))) continue;\n // \"Add::add\" and \"dead::beef\" are identifiers and words, not addresses.\n if (!/\\d/.test(value) && value.split(\":\").filter((group) => group !== \"\").length < 3) continue;\n if (!isIpv6(value)) continue;\n\n emit(start, end, 0.95);\n }\n}\n\n/**\n * IPv6 addresses in every RFC 4291 text form: full, `::`-compressed and with\n * an embedded IPv4 tail. MAC-style identifiers, times and `::` scope\n * operators are not reported.\n *\n * @example\n * ```ts\n * createPipeline({ detectors: [ipv6Detector], replace: { fallback: redactWith() } })\n * .transform(\"from 2001:db8::1 at 12:30:45\").text;\n * // \"from [REDACTED] at 12:30:45\"\n * ```\n */\nexport const ipv6Detector: SpanDetector = defineDetector({\n id: \"ipv6\",\n category: \"ipv6\",\n prefilter: (text) => text.includes(\":\"),\n scan: scanIpv6,\n maxMatchLength: 64,\n});\n\n// ---------------------------------------------------------------------------\n// Payment cards\n// ---------------------------------------------------------------------------\n\nfunction isDigit(code: number): boolean {\n return code >= 48 && code <= 57;\n}\n\n/** Digit-group layouts in which card numbers are written, longest first. */\nconst CARD_GROUPINGS: readonly (readonly number[])[] = [\n [4, 4, 4, 4, 3],\n [4, 4, 4, 4],\n [4, 4, 4, 3],\n [4, 4, 4, 2],\n [4, 4, 4, 1],\n [4, 6, 5],\n [4, 6, 4],\n [8, 8],\n [6, 13],\n];\n\nconst SEPARATOR_NONE = 0;\nconst SEPARATOR_SPACE = 1;\nconst SEPARATOR_HYPHEN = 2;\nconst SEPARATOR_DOT = 3;\nconst SEPARATOR_NEWLINE = 4;\n\n/** Kind of group separator in `text[from, to)`, or `SEPARATOR_NONE` when it is not one. */\nfunction separatorKind(text: string, from: number, to: number): number {\n const first = text.charCodeAt(from);\n if (to - from === 1) {\n if (first === 32 || first === 160) return SEPARATOR_SPACE;\n if (first === 45) return SEPARATOR_HYPHEN;\n if (first === 46) return SEPARATOR_DOT;\n if (first === 10) return SEPARATOR_NEWLINE;\n return SEPARATOR_NONE;\n }\n if (to - from !== 2) return SEPARATOR_NONE;\n const second = text.charCodeAt(from + 1);\n if ((first === 32 || first === 160) && (second === 32 || second === 160)) return SEPARATOR_SPACE;\n if (first === 13 && second === 10) return SEPARATOR_NEWLINE;\n return SEPARATOR_NONE;\n}\n\nfunction inRange(digits: string, length: number, low: number, high: number): boolean {\n const prefix = Number(digits.slice(0, length));\n return prefix >= low && prefix <= high;\n}\n\n/**\n * `true` when the prefix and length belong to a card network (ISO/IEC 7812\n * issuer ranges). `grouped` tells whether the number was written in groups.\n */\nfunction isIssuedRange(digits: string, grouped: boolean): boolean {\n const length = digits.length;\n if (digits.startsWith(\"4\")) return length === 13 || length === 16 || length === 19;\n if (inRange(digits, 2, 51, 55) || inRange(digits, 4, 2221, 2720)) return length === 16;\n if (digits.startsWith(\"34\") || digits.startsWith(\"37\")) return length === 15;\n // UATP; an unseparated 15-digit number that starts with 1 is too often something else.\n if (digits.startsWith(\"1\")) return grouped && length === 15;\n if (length === 14) return inRange(digits, 3, 300, 305) || /^3(?:095|6|8|9)/.test(digits);\n if (length < 16) return false;\n return (\n digits.startsWith(\"6011\") ||\n inRange(digits, 3, 644, 649) ||\n digits.startsWith(\"65\") ||\n digits.startsWith(\"62\") ||\n inRange(digits, 4, 3528, 3589) ||\n inRange(digits, 3, 300, 305) ||\n /^3(?:095|6|8|9)/.test(digits) ||\n inRange(digits, 4, 2200, 2205) ||\n digits.startsWith(\"50\") ||\n inRange(digits, 2, 56, 69) ||\n // RuPay, UzCard, Humo, Troy, NAPAS, T-Union.\n inRange(digits, 2, 81, 82) ||\n digits.startsWith(\"8600\") ||\n digits.startsWith(\"9860\") ||\n digits.startsWith(\"9792\") ||\n digits.startsWith(\"9704\") ||\n digits.startsWith(\"31\")\n );\n}\n\ninterface CardCandidate {\n /** Index of the first digit run of the candidate. */\n readonly run: number;\n readonly start: number;\n readonly end: number;\n readonly confidence: number;\n}\n\n/**\n * Every position at which a digit run begins is tried on its own, in every\n * layout, so a number that fails the checks never hides the one that starts\n * inside it (\"2024\\n4111 1111 1111 1111\", a column of card numbers).\n */\nfunction scanCard(text: string, emit: EmitSpan): void {\n // The digit runs of the text, found without a regular expression: a dense\n // text has one every few characters, and a match object for each adds up.\n const starts: number[] = [];\n const ends: number[] = [];\n for (let at = 0; at < text.length; at++) {\n if (!isDigit(text.charCodeAt(at))) continue;\n starts.push(at);\n while (at < text.length && isDigit(text.charCodeAt(at))) at++;\n ends.push(at);\n }\n\n const candidates: CardCandidate[] = [];\n /** Per first run: the furthest end of a candidate that starts there. */\n const reach = new Map<number, number>();\n const add = (run: number, end: number, confidence: number): void => {\n candidates.push({ run, start: starts[run] ?? 0, end, confidence });\n reach.set(run, Math.max(reach.get(run) ?? 0, end));\n };\n\n for (const [run, start] of starts.entries()) {\n const length = (ends[run] ?? start) - start;\n\n if (length >= 13 && length <= 19) {\n const digits = text.slice(start, start + length);\n if (isIssuedRange(digits, false) && luhn(digits)) add(run, start + length, 0.92);\n continue;\n }\n\n for (const grouping of CARD_GROUPINGS) {\n if (grouping[0] !== length) continue;\n let digits = \"\";\n let uniform = true;\n let kind = SEPARATOR_NONE;\n let fits = true;\n for (const [offset, size] of grouping.entries()) {\n const from = starts[run + offset];\n const to = ends[run + offset];\n if (from === undefined || to === undefined || to - from !== size) {\n fits = false;\n break;\n }\n if (offset > 0) {\n const between = separatorKind(text, ends[run + offset - 1] ?? from, from);\n if (between === SEPARATOR_NONE) {\n fits = false;\n break;\n }\n if (kind !== SEPARATOR_NONE && between !== kind) uniform = false;\n kind = between;\n }\n digits += text.slice(from, to);\n }\n if (!fits || !luhn(digits)) continue;\n\n const end = ends[run + grouping.length - 1] ?? start;\n if (isIssuedRange(digits, true)) {\n add(run, end, uniform ? 0.97 : 0.85);\n } else if (\n uniform &&\n digits.length === 16 &&\n grouping.length === 4 &&\n !/^(\\d)\\1+$/.test(digits)\n ) {\n // Four groups of four with a valid check digit: a card of a network outside the table.\n add(run, end, 0.6);\n }\n }\n }\n\n // Report the candidates that add something. One that only covers the end of\n // an accepted number and the beginning of the next candidate is the same\n // digits read out of phase.\n let covered = -1;\n for (const candidate of candidates) {\n if (candidate.end <= covered) continue;\n if (candidate.start < covered) {\n let next = candidate.run;\n while ((starts[next] ?? Infinity) < covered) next++;\n if ((reach.get(next) ?? 0) >= candidate.end) continue;\n }\n emit(candidate.start, candidate.end, candidate.confidence);\n covered = Math.max(covered, candidate.end);\n }\n}\n\n/**\n * Payment card numbers (PANs): 13 to 19 digits, unseparated or in the usual\n * groupings, that fall in an issuer range and pass the Luhn check. Four groups\n * of four digits that pass the Luhn check are reported with a low confidence\n * when no issuer range matches.\n *\n * @example\n * ```ts\n * createPipeline({ detectors: [creditCardDetector], replace: { fallback: redactWith() } })\n * .transform(\"4111 1111 1111 1111 12/25, IMEI 490154203237518\").text;\n * // \"[REDACTED] 12/25, IMEI 490154203237518\"\n * ```\n */\nexport const creditCardDetector: SpanDetector = defineDetector({\n id: \"credit-card\",\n category: \"credit-card\",\n prefilter: (text) => /\\d{4}/.test(text),\n scan: scanCard,\n maxMatchLength: 48,\n});\n\nconst MASKED_CARD_PATTERN =\n /(?<![\\w*])(?:[*Xx\\u2022]{4}[ -]?){2,3}(?:[*Xx\\u2022]{2}\\d{2}|\\d{4})(?!\\d)/g;\n\n/**\n * Partially masked card numbers such as `****-****-****-1234` and\n * `XXXX XXXX XXXX 1234`. Used by aggressive pipelines in addition to\n * {@link creditCardDetector}.\n *\n * @example\n * ```ts\n * createPipeline({ detectors: [creditCardDetector, maskedCardDetector], replace: { fallback: redactWith() } });\n * ```\n */\nexport const maskedCardDetector: SpanDetector = defineDetector({\n id: \"credit-card/masked\",\n category: \"credit-card\",\n prefilter: (text) => /[*Xx\\u2022]{4}/.test(text),\n scan(text, emit) {\n MASKED_CARD_PATTERN.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = MASKED_CARD_PATTERN.exec(text)) !== null) {\n emit(match.index, match.index + match[0].length, 0.8);\n }\n },\n maxMatchLength: 24,\n});\n","/**\n * @module engine/compile\n * @description Compiles a declarative {@link PipelineSpec} into a pipeline.\n */\n\nimport { UnknownCategoryError, ValidationError } from \"../errors.js\";\nimport { getPreset } from \"../presets.js\";\nimport type { PiiCategory } from \"../types.js\";\nimport { BUILTIN_CATEGORIES, LEGACY_AGGRESSIVE_DETECTORS, LEGACY_DETECTORS } from \"./builtin.js\";\nimport { defineRegexDetector } from \"./detector.js\";\nimport { createPipeline } from \"./pipeline.js\";\nimport {\n bareSsnDetector,\n creditCardDetector,\n emailDetector,\n ibanDetector,\n ipv4Detector,\n ipv6Detector,\n maskedCardDetector,\n obfuscatedEmailDetector,\n ssnDetector,\n} from \"./precise.js\";\nimport { FAIL_CLOSED_LABEL, strategyReplacer } from \"./replacers.js\";\nimport type {\n CompileDependencies,\n Pipeline,\n PipelineSpec,\n Replacer,\n SpanDetector,\n StrategySpec,\n} from \"./types.js\";\n\n/** The validating detectors, and the extra detectors each gains in aggressive mode. */\nconst PRECISE: Readonly<Partial<Record<PiiCategory, readonly [SpanDetector, ...SpanDetector[]]>>> =\n {\n email: [emailDetector, obfuscatedEmailDetector],\n ssn: [ssnDetector, bareSsnDetector],\n iban: [ibanDetector],\n ipv4: [ipv4Detector],\n ipv6: [ipv6Detector],\n \"credit-card\": [creditCardDetector, maskedCardDetector],\n };\n\nconst DEFAULT_STRATEGY: StrategySpec = { strategy: \"redact\" };\n\nfunction isBuiltinCategory(category: string): category is PiiCategory {\n return (BUILTIN_CATEGORIES as readonly string[]).includes(category);\n}\n\n/**\n * Return the built-in span detectors for a set of categories.\n *\n * @param categories - The categories to detect. Defaults to every built-in category.\n * @param options - `detection` selects the validating or the 1.x detectors,\n * `aggressive` adds the permissive variants.\n * @returns The detectors, in scan order.\n * @throws {@link UnknownCategoryError} When a category is not built in.\n *\n * @example\n * ```ts\n * import { builtinDetectors, createPipeline, redactWith } from \"anonyma/engine\";\n *\n * const pipeline = createPipeline({\n * detectors: builtinDetectors([\"email\", \"phone\"]),\n * replace: { fallback: redactWith() },\n * });\n * ```\n */\nexport function builtinDetectors(\n categories: readonly PiiCategory[] = BUILTIN_CATEGORIES,\n options: { readonly detection?: \"precise\" | \"legacy\"; readonly aggressive?: boolean } = {},\n): SpanDetector[] {\n const { detection = \"precise\", aggressive = false } = options;\n const out: SpanDetector[] = [];\n const seen = new Set<string>();\n\n for (const category of categories) {\n if (!isBuiltinCategory(category)) throw new UnknownCategoryError(category);\n if (seen.has(category)) continue;\n seen.add(category);\n\n const precise = detection === \"precise\" ? PRECISE[category] : undefined;\n if (precise !== undefined) {\n out.push(...(aggressive ? precise : [precise[0]]));\n } else {\n out.push((aggressive ? LEGACY_AGGRESSIVE_DETECTORS : LEGACY_DETECTORS)[category]);\n }\n }\n return out;\n}\n\n/**\n * Compile a declarative pipeline specification.\n *\n * Every strategy is instantiated while compiling, so an invalid option or a\n * missing dependency is reported here rather than on the first match.\n *\n * @param spec - The specification. An empty object detects every built-in\n * category and redacts it.\n * @param dependencies - Tokenization provider, encryption key and secrets for\n * the strategies that need them.\n * @returns The compiled {@link Pipeline}.\n * @throws {@link UnknownCategoryError} When a listed category is not built in.\n * @throws {@link ValidationError} When a strategy, pattern or option is invalid.\n *\n * @example\n * ```ts\n * import { compilePipeline } from \"anonyma/engine\";\n *\n * const pipeline = compilePipeline({\n * preset: \"pci-dss\",\n * rules: { email: { strategy: \"mask\", keepLeading: 1 } },\n * minConfidence: 0.8,\n * });\n * pipeline.transform(\"Card 4111 1111 1111 1111\").text; // \"Card ***************1111\"\n * ```\n */\nexport function compilePipeline(\n spec: PipelineSpec = {},\n dependencies: CompileDependencies = {},\n): Pipeline {\n const input: unknown = spec;\n if (typeof input !== \"object\" || input === null) {\n throw new ValidationError(\"spec\", \"must be an object\");\n }\n const preset = spec.preset === undefined ? undefined : getPreset(spec.preset);\n const detection: unknown = spec.detection;\n if (detection !== undefined && detection !== \"precise\" && detection !== \"legacy\") {\n throw new ValidationError(\"detection\", 'must be \"precise\" or \"legacy\"');\n }\n\n const detectors = builtinDetectors(spec.categories ?? preset?.categories ?? BUILTIN_CATEGORIES, {\n ...(spec.detection !== undefined ? { detection: spec.detection } : {}),\n ...(spec.aggressive !== undefined ? { aggressive: spec.aggressive } : {}),\n });\n\n for (const [index, pattern] of (spec.patterns ?? []).entries()) {\n if (typeof pattern.category !== \"string\" || pattern.category.length === 0) {\n throw new ValidationError(\n `patterns[${String(index)}].category`,\n \"must be a non-empty string\",\n );\n }\n const { confidence } = pattern;\n if (\n confidence !== undefined &&\n !(typeof confidence === \"number\" && confidence >= 0 && confidence <= 1)\n ) {\n throw new ValidationError(\n `patterns[${String(index)}].confidence`,\n \"must be a number between 0 and 1\",\n );\n }\n let compiled: RegExp;\n try {\n compiled = new RegExp(pattern.source, pattern.flags ?? \"\");\n } catch {\n throw new ValidationError(`patterns[${String(index)}]`, \"is not a valid regular expression\");\n }\n detectors.push(\n defineRegexDetector({\n id: `pattern/${String(index)}`,\n category: pattern.category,\n pattern: compiled,\n ...(pattern.confidence !== undefined ? { confidence: pattern.confidence } : {}),\n }),\n );\n }\n\n const strategies = new Map<string, StrategySpec>();\n for (const rule of preset?.rules ?? []) {\n // Preset rules never use the strategies that need a dependency.\n strategies.set(rule.category, rule.strategy as StrategySpec);\n }\n for (const [category, strategy] of Object.entries(spec.rules ?? {})) {\n const rule: unknown = strategy;\n if (typeof rule !== \"object\" || rule === null) {\n throw new ValidationError(`rules.${category}`, \"must be a strategy object\");\n }\n strategies.set(category, strategy);\n }\n\n const byCategory: Record<string, Replacer> = {};\n for (const [category, strategy] of strategies) {\n Object.defineProperty(byCategory, category, {\n value: strategyReplacer(strategy, dependencies),\n enumerable: true,\n });\n }\n\n const defaultStrategy =\n spec.defaultStrategy ??\n (preset?.defaultStrategy as StrategySpec | undefined) ??\n DEFAULT_STRATEGY;\n\n // A redaction label must survive a second pass unchanged. The 1.x bank-account\n // detector reads any eight-letter upper-case word, \"REDACTED\" included, as a\n // BIC, so the labels in use are exempt from detection. That includes the label\n // the other strategies fall back to when they cannot change a value.\n const labels = new Set<string>();\n for (const strategy of [defaultStrategy, ...strategies.values()]) {\n if (strategy.strategy === \"tokenize\" || strategy.strategy === \"hash\") continue;\n if (strategy.strategy === \"encrypt\") continue;\n const label =\n strategy.strategy === \"redact\" ? (strategy.label ?? \"[REDACTED]\") : FAIL_CLOSED_LABEL;\n labels.add(label);\n labels.add(label.replace(/^[^\\p{L}\\p{N}]+|[^\\p{L}\\p{N}]+$/gu, \"\"));\n }\n labels.delete(\"\");\n\n return createPipeline({\n detectors,\n replace: { fallback: strategyReplacer(defaultStrategy, dependencies), byCategory },\n ...(spec.minConfidence !== undefined ? { minConfidence: spec.minConfidence } : {}),\n allow: [...(spec.allow ?? []), ...labels],\n ...(spec.allowCaseSensitive !== undefined\n ? { allowCaseSensitive: spec.allowCaseSensitive }\n : {}),\n ...(spec.overlap !== undefined ? { overlap: spec.overlap } : {}),\n });\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
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,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,GAAY,CAAA,CAAA,EAAI,MAAM,CAAA,CAAA,EAAI,EAAE,CAAA,CAAA,CAAA,GAAM,CAAA,CAAA,EAAI,MAAM,CAAA,CAAA,EAAI,EAAE,CAAA,CAAA,CAAA;AAE3E,EAAA,KAAA,CAAM,KAAA,CAAM,GAAA,CAAI,QAAA,EAAU,KAAK,CAAA;AAC/B,E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,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"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/strategies/mask.ts","../src/strategies/redact.ts","../src/strategies/pseudonymize.ts","../src/strategies/generalize.ts","../src/presets.ts"],"names":["totalVisible"],"mappings":";;;AAoCO,SAAS,IAAA,CAAK,KAAA,EAAe,OAAA,GAAuB,EAAC,EAAW;AACrE,EAAA,MAAM,EAAE,WAAW,GAAA,EAAK,WAAA,GAAc,GAAG,YAAA,GAAe,CAAA,EAAG,cAAA,GAAiB,KAAA,EAAM,GAAI,OAAA;AAEtF,EAAA,IAAI,QAAA,CAAS,WAAW,CAAA,EAAG;AACzB,IAAA,MAAM,IAAI,eAAA,CAAgB,UAAA,EAAY,+BAA+B,CAAA;AAAA,EACvE;AACA,EAAA,IAAI,CAAC,MAAA,CAAO,SAAA,CAAU,WAAW,CAAA,IAAK,cAAc,CAAA,EAAG;AACrD,IAAA,MAAM,IAAI,eAAA,CAAgB,aAAA,EAAe,gCAAgC,CAAA;AAAA,EAC3E;AACA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IAAA,MAAM,IAAI,oBAAoB,IAAI,CAAA;AAAA,EACpC;AACA,EAAA,OAAO,MAAA;AACT","file":"chunk-GS3FRH4K.js","sourcesContent":["/**\n * @module strategies/mask\n * @description The `mask` anonymization strategy.\n */\n\nimport { ValidationError } from \"../errors.js\";\nimport type { MaskOptions } from \"../types.js\";\n\n/**\n * Replace interior characters of `value` with a mask character, optionally\n * keeping a number of leading and/or trailing characters visible.\n *\n * The function is deterministic and pure — given the same inputs it always\n * produces the same output.\n *\n * @param value - The string to mask.\n * @param options - Masking configuration.\n * @returns The masked string.\n *\n * @throws {@link ValidationError} When `keepLeading` or `keepTrailing` is negative.\n * @throws {@link ValidationError} When `maskChar` is not exactly one character.\n *\n * @example\n * ```ts\n * import { mask } from \"anonyma\";\n *\n * mask(\"john.doe@example.com\");\n * // \"********************\"\n *\n * mask(\"john.doe@example.com\", { keepLeading: 1, keepTrailing: 4 });\n * // \"j***************m\" (keeps \"j\" and \".com\")\n *\n * mask(\"+1 (555) 867-5309\", { keepLeading: 0, keepTrailing: 4 });\n * // \"*************5309\"\n * ```\n */\nexport function mask(value: string, options: MaskOptions = {}): string {\n const { maskChar = \"*\", keepLeading = 0, keepTrailing = 0, preserveFormat = false } = options;\n\n if (maskChar.length !== 1) {\n throw new ValidationError(\"maskChar\", \"must be exactly one character\");\n }\n if (!Number.isInteger(keepLeading) || keepLeading < 0) {\n throw new ValidationError(\"keepLeading\", \"must be a non-negative integer\");\n }\n if (!Number.isInteger(keepTrailing) || keepTrailing < 0) {\n throw new ValidationError(\"keepTrailing\", \"must be a non-negative integer\");\n }\n\n if (value.length === 0) return value;\n\n // --- Format-preserving mode ---\n // Letter → 'X' / 'x', digit → '0', separators/punctuation preserved. Letters\n // and digits of every script are masked, not only ASCII ones.\n // `keepLeading` / `keepTrailing` still apply (character counts, ignoring separators).\n if (preserveFormat) {\n const chars = Array.from(value);\n const totalVisible = keepLeading + keepTrailing;\n if (totalVisible >= chars.length) {\n return value; // everything is visible, nothing to mask\n }\n\n // Determine the interior slice to mask (skip leading / trailing).\n const interior = chars.slice(keepLeading, chars.length - (keepTrailing > 0 ? keepTrailing : 0));\n const maskedInterior = interior.map((ch) => {\n if (/\\p{L}/u.test(ch)) return ch !== ch.toLowerCase() ? \"X\" : \"x\";\n if (/\\p{N}/u.test(ch)) return \"0\";\n return ch; // separator / punctuation — preserved\n });\n\n return (\n chars.slice(0, keepLeading).join(\"\") +\n maskedInterior.join(\"\") +\n (keepTrailing > 0 ? chars.slice(-keepTrailing).join(\"\") : \"\")\n );\n }\n\n // --- Standard mode ---\n // When the visible region covers or exceeds the whole string, just mask everything.\n const totalVisible = keepLeading + keepTrailing;\n if (totalVisible >= value.length) {\n return maskChar.repeat(value.length);\n }\n\n const leading = value.slice(0, keepLeading);\n const trailing = keepTrailing > 0 ? value.slice(-keepTrailing) : \"\";\n const maskedLength = value.length - keepLeading - keepTrailing;\n\n return leading + maskChar.repeat(maskedLength) + trailing;\n}\n","/**\n * @module strategies/redact\n * @description The `redact` anonymization strategy.\n */\n\nimport { ValidationError } from \"../errors.js\";\nimport type { RedactOptions } from \"../types.js\";\n\n/**\n * Replace `value` entirely with a redaction label.\n *\n * @param value - The string to redact (validated but not inspected).\n * @param options - Redaction configuration.\n * @returns The redaction label.\n *\n * @throws {@link ValidationError} When `label` is an empty string.\n *\n * @example\n * ```ts\n * import { redact } from \"anonyma\";\n *\n * redact(\"john.doe@example.com\");\n * // \"[REDACTED]\"\n *\n * redact(\"123-45-6789\", { label: \"[SSN REMOVED]\" });\n * // \"[SSN REMOVED]\"\n * ```\n */\nexport function redact(value: string, options: RedactOptions = {}): string {\n const { label = \"[REDACTED]\" } = options;\n\n if (label.trim().length === 0) {\n throw new ValidationError(\"label\", \"must not be an empty string\");\n }\n\n // `value` is validated to be a string by TypeScript; no runtime check needed\n // other than ensuring it is not undefined at the call-site.\n void value; // explicitly acknowledge the parameter (pure function, input unused)\n\n return label;\n}\n","/**\n * @module strategies/pseudonymize\n * @description The `pseudonymize` anonymization strategy.\n *\n * Generates a deterministic pseudonym from the input value + an optional seed.\n * The same `(value, seed)` pair always produces the same pseudonym, enabling\n * consistent replacement throughout a dataset without storing a lookup table.\n *\n * When no `seed` is provided, the pseudonym is randomly generated and is NOT\n * deterministic across calls.\n *\n * ⚠️ This strategy is NOT cryptographically secure. For strong irreversibility\n * use the `hash` strategy instead.\n */\n\nimport { ValidationError } from \"../errors.js\";\nimport type { PseudonymizeOptions } from \"../types.js\";\n\n/**\n * A lightweight, non-cryptographic integer hash (djb2 variant).\n * Used only for deterministic pseudonym generation.\n *\n * @internal\n */\nfunction djb2(str: string): number {\n let hash = 5381;\n for (let i = 0; i < str.length; i++) {\n // Safe: str.charCodeAt never throws for valid indices.\n hash = ((hash << 5) + hash) ^ str.charCodeAt(i);\n hash = hash >>> 0; // Convert to unsigned 32-bit integer\n }\n return hash;\n}\n\n/**\n * Generate a fixed-length hex string from a 32-bit integer.\n *\n * @internal\n */\nfunction toHex8(n: number): string {\n return (n >>> 0).toString(16).padStart(8, \"0\");\n}\n\n/**\n * Replace `value` with a deterministic (or random) pseudonym.\n *\n * @param value - The original PII value.\n * @param options - Pseudonymization configuration.\n * @returns A pseudonym string.\n *\n * @throws {@link ValidationError} When `prefix` contains whitespace or control characters.\n *\n * @example\n * ```ts\n * import { pseudonymize } from \"anonyma\";\n *\n * // Deterministic when a seed is provided:\n * pseudonymize(\"alice@example.com\", { seed: \"my-secret\" });\n * // \"id_3a7f1c2b\" (same output every time for this input+seed)\n *\n * // Random when no seed is provided:\n * pseudonymize(\"alice@example.com\");\n * // \"id_e9a3f7d1\" (different on every call)\n * ```\n */\nexport function pseudonymize(value: string, options: PseudonymizeOptions = {}): string {\n const { seed, prefix = \"id_\" } = options;\n\n if (/\\s/.test(prefix)) {\n throw new ValidationError(\"prefix\", \"must not contain whitespace characters\");\n }\n\n if (seed !== undefined) {\n // Deterministic path: mix value + seed through djb2.\n const combined = `${seed}:${value}`;\n const h1 = djb2(combined);\n const h2 = djb2(`${combined}:v2`);\n return `${prefix}${toHex8(h1)}${toHex8(h2)}`;\n }\n\n // Non-deterministic path: use crypto-quality random bytes if available.\n if (\n typeof globalThis.crypto !== \"undefined\" &&\n typeof globalThis.crypto.getRandomValues === \"function\"\n ) {\n const bytes = new Uint8Array(8);\n globalThis.crypto.getRandomValues(bytes);\n const hex = Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n return `${prefix}${hex}`;\n }\n\n // Fallback for constrained environments (should not occur in Node ≥ 18).\n const fallback = Math.floor(Math.random() * 0xffffffff);\n return `${prefix}${toHex8(fallback)}`;\n}\n","/**\n * @module strategies/generalize\n * @description The `generalize` anonymization strategy.\n *\n * Replaces a precise value with a coarser, less-identifying representation.\n * Currently supports:\n * - **Numeric generalization**: bucketing a number into a range (e.g. `27` → `\"20-29\"`)\n * - **String passthrough**: non-numeric strings are returned unchanged.\n */\n\nimport { ValidationError } from \"../errors.js\";\nimport type { GeneralizeOptions } from \"../types.js\";\n\n/**\n * Generalize `value` by replacing exact numeric values with a range bucket.\n * Non-numeric strings are returned without modification.\n *\n * @param value - The value to generalize.\n * @param options - Generalization configuration.\n * @returns A generalized string representation.\n *\n * @throws {@link ValidationError} When `bucketSize` is not a positive integer.\n *\n * @example\n * ```ts\n * import { generalize } from \"anonyma\";\n *\n * generalize(\"27\"); // \"20-29\"\n * generalize(\"30\"); // \"30-39\"\n * generalize(\"72\"); // \"70-79\"\n * generalize(\"27\", { bucketSize: 5 }); // \"25-29\"\n * generalize(\"not-a-number\"); // \"not-a-number\" (passthrough)\n * ```\n */\nexport function generalize(value: string, options: GeneralizeOptions = {}): string {\n const { bucketSize = 10 } = options;\n\n if (!Number.isInteger(bucketSize) || bucketSize < 1) {\n throw new ValidationError(\"bucketSize\", \"must be a positive integer\");\n }\n\n const parsed = Number(value);\n\n if (!Number.isFinite(parsed)) {\n // Non-numeric value: return as-is (best-effort generalization).\n return value;\n }\n\n const n = Math.floor(parsed);\n const low = Math.floor(n / bucketSize) * bucketSize;\n const high = low + bucketSize - 1;\n\n return `${String(low)}-${String(high)}`;\n}\n","/**\n * @module presets\n * @description Built-in compliance preset configurations for GDPR, LGPD,\n * PIPEDA, CCPA/CPRA, HIPAA, PCI-DSS, SOX, and FERPA. Import from `\"anonyma\"`\n * or extend using the `preset` option in {@link AnonymizeOptions}.\n *\n * A preset selects the categories that the library can detect for an\n * instrument and the strategy applied to them. The legal provisions behind\n * each category, and the data elements each instrument names that no detector\n * covers, are documented in `\"anonyma/compliance\"`.\n *\n * @example\n * ```ts\n * import { anonymize } from \"anonyma\";\n *\n * // Apply HIPAA preset — redacts the Safe Harbor identifiers that have a detector\n * anonymize(text, { preset: \"hipaa\" });\n *\n * // Extend GDPR preset with API key detection (anonymize() uses the preset's categories)\n * import { compilePipeline } from \"anonyma/engine\";\n * compilePipeline({ preset: \"gdpr\", categories: [...getPreset(\"gdpr\").categories, \"api-key\"] });\n * ```\n */\n\nimport { PresetNotFoundError } from \"./errors.js\";\nimport type { CompliancePreset, PiiCategory, StrategyOptions, AnonymizationRule } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Preset definition type\n// ---------------------------------------------------------------------------\n\n/**\n * A compliance preset configuration.\n */\nexport interface PresetConfig {\n /** Display name of the preset. */\n readonly name: CompliancePreset;\n /** Description of what the preset covers. */\n readonly description: string;\n /**\n * PII categories this preset activates.\n * The anonymizer will detect and redact these categories.\n */\n readonly categories: readonly PiiCategory[];\n /**\n * Default strategy applied to all categories in this preset.\n */\n readonly defaultStrategy: StrategyOptions;\n /**\n * Per-category strategy overrides (optional).\n */\n readonly rules?: readonly AnonymizationRule[];\n}\n\n// ---------------------------------------------------------------------------\n// Individual preset definitions\n// ---------------------------------------------------------------------------\n\n/**\n * GDPR — EU General Data Protection Regulation.\n * Covers all personal data that can identify an EU natural person.\n * Default strategy: pseudonymize (allows data utility while protecting identity).\n */\nconst GDPR_PRESET: PresetConfig = {\n name: \"gdpr\",\n description:\n \"EU General Data Protection Regulation — Covers all categories of personal data \" +\n \"that can identify a natural person.\",\n categories: [\n \"name\",\n \"email\",\n \"phone\",\n \"address\",\n \"date-of-birth\",\n \"ssn\",\n \"national-id\",\n \"passport\",\n \"drivers-license\",\n \"iban\",\n \"bank-account\",\n \"credit-card\",\n \"ipv4\",\n \"ipv6\",\n \"url\",\n \"medical-record\",\n \"health-insurance\",\n \"prescription\",\n \"social-media\",\n \"cryptocurrency\",\n \"tax-id\",\n ],\n defaultStrategy: { strategy: \"pseudonymize\" },\n};\n\n/**\n * HIPAA — US Health Insurance Portability and Accountability Act.\n * Covers the HIPAA Safe Harbor identifiers that can be detected in text.\n * Default strategy: redact (no reconstructability).\n *\n * The 18 Safe Harbor identifiers are listed below. City, county, ZIP code,\n * dates other than birth dates, ages over 89, device identifiers, biometrics\n * and photographs have no detector and need field-level rules:\n * 1. Names, 2. Geographic data, 3. Dates (except year), 4. Phone numbers,\n * 5. Fax numbers, 6. Email addresses, 7. SSNs, 8. MRN, 9. Health plan beneficiary numbers,\n * 10. Account numbers, 11. Certificate/license numbers, 12. VINs, 13. Device identifiers,\n * 14. URLs, 15. IP addresses, 16. Biometric identifiers, 17. Full-face photos,\n * 18. Unique identifying numbers/codes (NPI, DEA, etc.)\n */\nconst HIPAA_PRESET: PresetConfig = {\n name: \"hipaa\",\n description:\n \"US HIPAA Safe Harbor — Redacts the identifiers of 45 CFR 164.514(b)(2)(i) that can be \" +\n \"detected in text. City, county, ZIP code, dates other than birth dates, ages over 89, \" +\n \"device identifiers, biometrics and photographs need field-level rules.\",\n categories: [\n \"name\",\n \"address\",\n \"date-of-birth\",\n \"phone\",\n \"email\",\n \"ssn\",\n \"medical-record\",\n \"health-insurance\",\n \"prescription\",\n \"bank-account\",\n \"credit-card\",\n \"iban\",\n \"drivers-license\",\n \"passport\",\n \"vin\",\n \"license-plate\",\n \"url\",\n \"ipv4\",\n \"ipv6\",\n \"national-id\",\n \"tax-id\",\n \"social-media\",\n \"company-registration\",\n ],\n defaultStrategy: { strategy: \"redact\" },\n};\n\n/**\n * CCPA — California Consumer Privacy Act.\n * Covers consumer data categories defined by CCPA.\n * Default strategy: redact.\n */\nconst CCPA_PRESET: PresetConfig = {\n name: \"ccpa\",\n description:\n \"California Consumer Privacy Act — Covers personal information categories defined \" +\n \"by CCPA, including identifiers, financial data, and online activity.\",\n categories: [\n \"name\",\n \"email\",\n \"phone\",\n \"address\",\n \"ssn\",\n \"national-id\",\n \"passport\",\n \"drivers-license\",\n \"bank-account\",\n \"credit-card\",\n \"tax-id\",\n \"ipv4\",\n \"ipv6\",\n \"url\",\n \"social-media\",\n \"date-of-birth\",\n \"medical-record\",\n \"health-insurance\",\n \"api-key\",\n ],\n defaultStrategy: { strategy: \"redact\" },\n};\n\n/**\n * LGPD — Lei Geral de Proteção de Dados Pessoais (Brazil, Lei nº 13.709/2018).\n * Covers dados pessoais and the identifiers that lead to dados pessoais sensíveis.\n * Default strategy: redact (anonymisation in the sense of Art. 5, XI).\n */\nconst LGPD_PRESET: PresetConfig = {\n name: \"lgpd\",\n description:\n \"Brazilian Lei Geral de Proteção de Dados — Covers personal data that identifies a \" +\n \"natural person. CPF is detected in its punctuated form; CNPJ, RG, CNH and CEP need \" +\n \"custom patterns.\",\n categories: [\n \"name\",\n \"email\",\n \"phone\",\n \"address\",\n \"date-of-birth\",\n \"national-id\",\n \"tax-id\",\n \"passport\",\n \"drivers-license\",\n \"bank-account\",\n \"iban\",\n \"credit-card\",\n \"cryptocurrency\",\n \"ipv4\",\n \"ipv6\",\n \"url\",\n \"social-media\",\n \"license-plate\",\n \"medical-record\",\n \"health-insurance\",\n \"prescription\",\n ],\n defaultStrategy: { strategy: \"redact\" },\n};\n\n/**\n * PIPEDA — Personal Information Protection and Electronic Documents Act (Canada).\n * Covers information about an identifiable individual.\n * Default strategy: redact.\n */\nconst PIPEDA_PRESET: PresetConfig = {\n name: \"pipeda\",\n description:\n \"Canadian PIPEDA — Covers information about an identifiable individual, including the \" +\n \"Social Insurance Number. Provincial health card numbers and postal codes need custom \" +\n \"patterns.\",\n categories: [\n \"name\",\n \"email\",\n \"phone\",\n \"address\",\n \"date-of-birth\",\n \"national-id\",\n \"ssn\",\n \"passport\",\n \"drivers-license\",\n \"tax-id\",\n \"bank-account\",\n \"iban\",\n \"credit-card\",\n \"ipv4\",\n \"ipv6\",\n \"social-media\",\n \"medical-record\",\n \"health-insurance\",\n \"prescription\",\n ],\n defaultStrategy: { strategy: \"redact\" },\n};\n\n/**\n * PCI-DSS — Payment Card Industry Data Security Standard.\n * Covers the card number and the cardholder data around it. Sensitive\n * authentication data (card verification codes, track data, PINs) has no\n * detector.\n * Default strategy: redact. Card and bank account numbers are masked with\n * the last 4 digits visible (industry standard).\n */\nconst PCI_DSS_PRESET: PresetConfig = {\n name: \"pci-dss\",\n description:\n \"PCI-DSS Cardholder Data — Covers credit/debit card numbers, bank accounts, \" +\n \"and associated cardholder identifiers.\",\n categories: [\"credit-card\", \"bank-account\", \"name\", \"address\", \"email\", \"phone\"],\n defaultStrategy: { strategy: \"redact\" },\n rules: [\n {\n category: \"credit-card\",\n strategy: { strategy: \"mask\", keepTrailing: 4 },\n },\n {\n category: \"bank-account\",\n strategy: { strategy: \"mask\", keepTrailing: 4 },\n },\n ],\n};\n\n/**\n * SOX — Sarbanes-Oxley Act.\n * Covers financial audit trail and corporate officer identifiers.\n * Default strategy: redact.\n */\nconst SOX_PRESET: PresetConfig = {\n name: \"sox\",\n description:\n \"Sarbanes-Oxley Act — Covers financial records, corporate officer identifiers, \" +\n \"and audit trail data.\",\n categories: [\n \"name\",\n \"email\",\n \"tax-id\",\n \"bank-account\",\n \"company-registration\",\n \"ssn\",\n \"address\",\n \"phone\",\n ],\n defaultStrategy: { strategy: \"redact\" },\n};\n\n/**\n * FERPA — Family Educational Rights and Privacy Act.\n * Covers student education records.\n * Default strategy: redact.\n */\nconst FERPA_PRESET: PresetConfig = {\n name: \"ferpa\",\n description:\n \"FERPA — Covers education records and student personally identifiable information (PII).\",\n categories: [\"name\", \"email\", \"phone\", \"address\", \"date-of-birth\", \"ssn\", \"national-id\"],\n defaultStrategy: { strategy: \"redact\" },\n};\n\n// ---------------------------------------------------------------------------\n// Registry & lookup\n// ---------------------------------------------------------------------------\n\n/** All built-in presets keyed by name. */\nexport const PRESET_REGISTRY: Readonly<Record<CompliancePreset, PresetConfig>> = {\n gdpr: GDPR_PRESET,\n lgpd: LGPD_PRESET,\n pipeda: PIPEDA_PRESET,\n hipaa: HIPAA_PRESET,\n ccpa: CCPA_PRESET,\n \"pci-dss\": PCI_DSS_PRESET,\n sox: SOX_PRESET,\n ferpa: FERPA_PRESET,\n} as const;\n\n/**\n * Get a compliance preset configuration by name.\n *\n * @param name - The preset name.\n * @returns The {@link PresetConfig} for the named preset.\n * @throws {@link PresetNotFoundError} if the preset name is not recognised.\n *\n * @example\n * ```ts\n * import { getPreset } from \"anonyma\";\n *\n * const preset = getPreset(\"hipaa\");\n * console.log(preset.categories); // [\"name\", \"address\", ...]\n * ```\n */\nexport function getPreset(name: CompliancePreset): PresetConfig {\n const preset = (PRESET_REGISTRY as Partial<Record<CompliancePreset, PresetConfig>>)[name];\n if (preset === undefined) {\n throw new PresetNotFoundError(name);\n }\n return preset;\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/strategies/mask.ts","../src/strategies/redact.ts","../src/strategies/pseudonymize.ts","../src/strategies/generalize.ts","../src/presets.ts"],"names":["ValidationError","totalVisible","PresetNotFoundError"],"mappings":";;;;;AAoCO,SAAS,IAAA,CAAK,KAAA,EAAe,OAAA,GAAuB,EAAC,EAAW;AACrE,EAAA,MAAM,EAAE,WAAW,GAAA,EAAK,WAAA,GAAc,GAAG,YAAA,GAAe,CAAA,EAAG,cAAA,GAAiB,KAAA,EAAM,GAAI,OAAA;AAEtF,EAAA,IAAI,QAAA,CAAS,WAAW,CAAA,EAAG;AACzB,IAAA,MAAM,IAAIA,iCAAA,CAAgB,UAAA,EAAY,+BAA+B,C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W,cAAA;AAAA,EACX,GAAA,EAAK,UAAA;AAAA,EACL,KAAA,EAAO;AACT;AAiBO,SAAS,UAAU,IAAA,EAAsC;AAC9D,EAAA,MAAM,MAAA,GAAU,gBAAoE,IAAI,CAAA;AACxF,EAAA,IAAI,WAAW,MAAA,EAAW;AACxB,IAAA,MAAM,IAAIE,sCAAoB,IAAI,CAAA;AAAA,EACpC;AACA,EAAA,OAAO,MAAA;AACT","file":"chunk-IHEIYZPL.cjs","sourcesContent":["/**\n * @module strategies/mask\n * @description The `mask` anonymization strategy.\n */\n\nimport { ValidationError } from \"../errors.js\";\nimport type { MaskOptions } from \"../types.js\";\n\n/**\n * Replace interior characters of `value` with a mask character, optionally\n * keeping a number of leading and/or trailing characters visible.\n *\n * The function is deterministic and pure — given the same inputs it always\n * produces the same output.\n *\n * @param value - The string to mask.\n * @param options - Masking configuration.\n * @returns The masked string.\n *\n * @throws {@link ValidationError} When `keepLeading` or `keepTrailing` is negative.\n * @throws {@link ValidationError} When `maskChar` is not exactly one character.\n *\n * @example\n * ```ts\n * import { mask } from \"anonyma\";\n *\n * mask(\"john.doe@example.com\");\n * // \"********************\"\n *\n * mask(\"john.doe@example.com\", { keepLeading: 1, keepTrailing: 4 });\n * // \"j***************m\" (keeps \"j\" and \".com\")\n *\n * mask(\"+1 (555) 867-5309\", { keepLeading: 0, keepTrailing: 4 });\n * // \"*************5309\"\n * ```\n */\nexport function mask(value: string, options: MaskOptions = {}): string {\n const { maskChar = \"*\", keepLeading = 0, keepTrailing = 0, preserveFormat = false } = options;\n\n if (maskChar.length !== 1) {\n throw new ValidationError(\"maskChar\", \"must be exactly one character\");\n }\n if (!Number.isInteger(keepLeading) || keepLeading < 0) {\n throw new ValidationError(\"keepLeading\", \"must be a non-negative integer\");\n }\n if (!Number.isInteger(keepTrailing) || keepTrailing < 0) {\n throw new ValidationError(\"keepTrailing\", \"must be a non-negative integer\");\n }\n\n if (value.length === 0) return value;\n\n // --- Format-preserving mode ---\n // Letter → 'X' / 'x', digit → '0', separators/punctuation preserved. Letters\n // and digits of every script are masked, not only ASCII ones.\n // `keepLeading` / `keepTrailing` still apply (character counts, ignoring separators).\n if (preserveFormat) {\n const chars = Array.from(value);\n const totalVisible = keepLeading + keepTrailing;\n if (totalVisible >= chars.length) {\n return value; // everything is visible, nothing to mask\n }\n\n // Determine the interior slice to mask (skip leading / trailing).\n const interior = chars.slice(keepLeading, chars.length - (keepTrailing > 0 ? keepTrailing : 0));\n const maskedInterior = interior.map((ch) => {\n if (/\\p{L}/u.test(ch)) return ch !== ch.toLowerCase() ? \"X\" : \"x\";\n if (/\\p{N}/u.test(ch)) return \"0\";\n return ch; // separator / punctuation — preserved\n });\n\n return (\n chars.slice(0, keepLeading).join(\"\") +\n maskedInterior.join(\"\") +\n (keepTrailing > 0 ? chars.slice(-keepTrailing).join(\"\") : \"\")\n );\n }\n\n // --- Standard mode ---\n // When the visible region covers or exceeds the whole string, just mask everything.\n const totalVisible = keepLeading + keepTrailing;\n if (totalVisible >= value.length) {\n return maskChar.repeat(value.length);\n }\n\n const leading = value.slice(0, keepLeading);\n const trailing = keepTrailing > 0 ? value.slice(-keepTrailing) : \"\";\n const maskedLength = value.length - keepLeading - keepTrailing;\n\n return leading + maskChar.repeat(maskedLength) + trailing;\n}\n","/**\n * @module strategies/redact\n * @description The `redact` anonymization strategy.\n */\n\nimport { ValidationError } from \"../errors.js\";\nimport type { RedactOptions } from \"../types.js\";\n\n/**\n * Replace `value` entirely with a redaction label.\n *\n * @param value - The string to redact (validated but not inspected).\n * @param options - Redaction configuration.\n * @returns The redaction label.\n *\n * @throws {@link ValidationError} When `label` is an empty string.\n *\n * @example\n * ```ts\n * import { redact } from \"anonyma\";\n *\n * redact(\"john.doe@example.com\");\n * // \"[REDACTED]\"\n *\n * redact(\"123-45-6789\", { label: \"[SSN REMOVED]\" });\n * // \"[SSN REMOVED]\"\n * ```\n */\nexport function redact(value: string, options: RedactOptions = {}): string {\n const { label = \"[REDACTED]\" } = options;\n\n if (label.trim().length === 0) {\n throw new ValidationError(\"label\", \"must not be an empty string\");\n }\n\n // `value` is validated to be a string by TypeScript; no runtime check needed\n // other than ensuring it is not undefined at the call-site.\n void value; // explicitly acknowledge the parameter (pure function, input unused)\n\n return label;\n}\n","/**\n * @module strategies/pseudonymize\n * @description The `pseudonymize` anonymization strategy.\n *\n * Generates a deterministic pseudonym from the input value + an optional seed.\n * The same `(value, seed)` pair always produces the same pseudonym, enabling\n * consistent replacement throughout a dataset without storing a lookup table.\n *\n * When no `seed` is provided, the pseudonym is randomly generated and is NOT\n * deterministic across calls.\n *\n * ⚠️ This strategy is NOT cryptographically secure. For strong irreversibility\n * use the `hash` strategy instead.\n */\n\nimport { ValidationError } from \"../errors.js\";\nimport type { PseudonymizeOptions } from \"../types.js\";\n\n/**\n * A lightweight, non-cryptographic integer hash (djb2 variant).\n * Used only for deterministic pseudonym generation.\n *\n * @internal\n */\nfunction djb2(str: string): number {\n let hash = 5381;\n for (let i = 0; i < str.length; i++) {\n // Safe: str.charCodeAt never throws for valid indices.\n hash = ((hash << 5) + hash) ^ str.charCodeAt(i);\n hash = hash >>> 0; // Convert to unsigned 32-bit integer\n }\n return hash;\n}\n\n/**\n * Generate a fixed-length hex string from a 32-bit integer.\n *\n * @internal\n */\nfunction toHex8(n: number): string {\n return (n >>> 0).toString(16).padStart(8, \"0\");\n}\n\n/**\n * Replace `value` with a deterministic (or random) pseudonym.\n *\n * @param value - The original PII value.\n * @param options - Pseudonymization configuration.\n * @returns A pseudonym string.\n *\n * @throws {@link ValidationError} When `prefix` contains whitespace or control characters.\n *\n * @example\n * ```ts\n * import { pseudonymize } from \"anonyma\";\n *\n * // Deterministic when a seed is provided:\n * pseudonymize(\"alice@example.com\", { seed: \"my-secret\" });\n * // \"id_3a7f1c2b\" (same output every time for this input+seed)\n *\n * // Random when no seed is provided:\n * pseudonymize(\"alice@example.com\");\n * // \"id_e9a3f7d1\" (different on every call)\n * ```\n */\nexport function pseudonymize(value: string, options: PseudonymizeOptions = {}): string {\n const { seed, prefix = \"id_\" } = options;\n\n if (/\\s/.test(prefix)) {\n throw new ValidationError(\"prefix\", \"must not contain whitespace characters\");\n }\n\n if (seed !== undefined) {\n // Deterministic path: mix value + seed through djb2.\n const combined = `${seed}:${value}`;\n const h1 = djb2(combined);\n const h2 = djb2(`${combined}:v2`);\n return `${prefix}${toHex8(h1)}${toHex8(h2)}`;\n }\n\n // Non-deterministic path: use crypto-quality random bytes if available.\n if (\n typeof globalThis.crypto !== \"undefined\" &&\n typeof globalThis.crypto.getRandomValues === \"function\"\n ) {\n const bytes = new Uint8Array(8);\n globalThis.crypto.getRandomValues(bytes);\n const hex = Array.from(bytes)\n .map((b) => b.toString(16).padStart(2, \"0\"))\n .join(\"\");\n return `${prefix}${hex}`;\n }\n\n // Fallback for constrained environments (should not occur in Node ≥ 18).\n const fallback = Math.floor(Math.random() * 0xffffffff);\n return `${prefix}${toHex8(fallback)}`;\n}\n","/**\n * @module strategies/generalize\n * @description The `generalize` anonymization strategy.\n *\n * Replaces a precise value with a coarser, less-identifying representation.\n * Currently supports:\n * - **Numeric generalization**: bucketing a number into a range (e.g. `27` → `\"20-29\"`)\n * - **String passthrough**: non-numeric strings are returned unchanged.\n */\n\nimport { ValidationError } from \"../errors.js\";\nimport type { GeneralizeOptions } from \"../types.js\";\n\n/**\n * Generalize `value` by replacing exact numeric values with a range bucket.\n * Non-numeric strings are returned without modification.\n *\n * @param value - The value to generalize.\n * @param options - Generalization configuration.\n * @returns A generalized string representation.\n *\n * @throws {@link ValidationError} When `bucketSize` is not a positive integer.\n *\n * @example\n * ```ts\n * import { generalize } from \"anonyma\";\n *\n * generalize(\"27\"); // \"20-29\"\n * generalize(\"30\"); // \"30-39\"\n * generalize(\"72\"); // \"70-79\"\n * generalize(\"27\", { bucketSize: 5 }); // \"25-29\"\n * generalize(\"not-a-number\"); // \"not-a-number\" (passthrough)\n * ```\n */\nexport function generalize(value: string, options: GeneralizeOptions = {}): string {\n const { bucketSize = 10 } = options;\n\n if (!Number.isInteger(bucketSize) || bucketSize < 1) {\n throw new ValidationError(\"bucketSize\", \"must be a positive integer\");\n }\n\n const parsed = Number(value);\n\n if (!Number.isFinite(parsed)) {\n // Non-numeric value: return as-is (best-effort generalization).\n return value;\n }\n\n const n = Math.floor(parsed);\n const low = Math.floor(n / bucketSize) * bucketSize;\n const high = low + bucketSize - 1;\n\n return `${String(low)}-${String(high)}`;\n}\n","/**\n * @module presets\n * @description Built-in compliance preset configurations for GDPR, LGPD,\n * PIPEDA, CCPA/CPRA, HIPAA, PCI-DSS, SOX, and FERPA. Import from `\"anonyma\"`\n * or extend using the `preset` option in {@link AnonymizeOptions}.\n *\n * A preset selects the categories that the library can detect for an\n * instrument and the strategy applied to them. The legal provisions behind\n * each category, and the data elements each instrument names that no detector\n * covers, are documented in `\"anonyma/compliance\"`.\n *\n * @example\n * ```ts\n * import { anonymize } from \"anonyma\";\n *\n * // Apply HIPAA preset — redacts the Safe Harbor identifiers that have a detector\n * anonymize(text, { preset: \"hipaa\" });\n *\n * // Extend GDPR preset with API key detection (anonymize() uses the preset's categories)\n * import { compilePipeline } from \"anonyma/engine\";\n * compilePipeline({ preset: \"gdpr\", categories: [...getPreset(\"gdpr\").categories, \"api-key\"] });\n * ```\n */\n\nimport { PresetNotFoundError } from \"./errors.js\";\nimport type { CompliancePreset, PiiCategory, StrategyOptions, AnonymizationRule } from \"./types.js\";\n\n// ---------------------------------------------------------------------------\n// Preset definition type\n// ---------------------------------------------------------------------------\n\n/**\n * A compliance preset configuration.\n */\nexport interface PresetConfig {\n /** Display name of the preset. */\n readonly name: CompliancePreset;\n /** Description of what the preset covers. */\n readonly description: string;\n /**\n * PII categories this preset activates.\n * The anonymizer will detect and redact these categories.\n */\n readonly categories: readonly PiiCategory[];\n /**\n * Default strategy applied to all categories in this preset.\n */\n readonly defaultStrategy: StrategyOptions;\n /**\n * Per-category strategy overrides (optional).\n */\n readonly rules?: readonly AnonymizationRule[];\n}\n\n// ---------------------------------------------------------------------------\n// Individual preset definitions\n// ---------------------------------------------------------------------------\n\n/**\n * GDPR — EU General Data Protection Regulation.\n * Covers all personal data that can identify an EU natural person.\n * Default strategy: pseudonymize (allows data utility while protecting identity).\n */\nconst GDPR_PRESET: PresetConfig = {\n name: \"gdpr\",\n description:\n \"EU General Data Protection Regulation — Covers all categories of personal data \" +\n \"that can identify a natural person.\",\n categories: [\n \"name\",\n \"email\",\n \"phone\",\n \"address\",\n \"date-of-birth\",\n \"ssn\",\n \"national-id\",\n \"passport\",\n \"drivers-license\",\n \"iban\",\n \"bank-account\",\n \"credit-card\",\n \"ipv4\",\n \"ipv6\",\n \"url\",\n \"medical-record\",\n \"health-insurance\",\n \"prescription\",\n \"social-media\",\n \"cryptocurrency\",\n \"tax-id\",\n ],\n defaultStrategy: { strategy: \"pseudonymize\" },\n};\n\n/**\n * HIPAA — US Health Insurance Portability and Accountability Act.\n * Covers the HIPAA Safe Harbor identifiers that can be detected in text.\n * Default strategy: redact (no reconstructability).\n *\n * The 18 Safe Harbor identifiers are listed below. City, county, ZIP code,\n * dates other than birth dates, ages over 89, device identifiers, biometrics\n * and photographs have no detector and need field-level rules:\n * 1. Names, 2. Geographic data, 3. Dates (except year), 4. Phone numbers,\n * 5. Fax numbers, 6. Email addresses, 7. SSNs, 8. MRN, 9. Health plan beneficiary numbers,\n * 10. Account numbers, 11. Certificate/license numbers, 12. VINs, 13. Device identifiers,\n * 14. URLs, 15. IP addresses, 16. Biometric identifiers, 17. Full-face photos,\n * 18. Unique identifying numbers/codes (NPI, DEA, etc.)\n */\nconst HIPAA_PRESET: PresetConfig = {\n name: \"hipaa\",\n description:\n \"US HIPAA Safe Harbor — Redacts the identifiers of 45 CFR 164.514(b)(2)(i) that can be \" +\n \"detected in text. City, county, ZIP code, dates other than birth dates, ages over 89, \" +\n \"device identifiers, biometrics and photographs need field-level rules.\",\n categories: [\n \"name\",\n \"address\",\n \"date-of-birth\",\n \"phone\",\n \"email\",\n \"ssn\",\n \"medical-record\",\n \"health-insurance\",\n \"prescription\",\n \"bank-account\",\n \"credit-card\",\n \"iban\",\n \"drivers-license\",\n \"passport\",\n \"vin\",\n \"license-plate\",\n \"url\",\n \"ipv4\",\n \"ipv6\",\n \"national-id\",\n \"tax-id\",\n \"social-media\",\n \"company-registration\",\n ],\n defaultStrategy: { strategy: \"redact\" },\n};\n\n/**\n * CCPA — California Consumer Privacy Act.\n * Covers consumer data categories defined by CCPA.\n * Default strategy: redact.\n */\nconst CCPA_PRESET: PresetConfig = {\n name: \"ccpa\",\n description:\n \"California Consumer Privacy Act — Covers personal information categories defined \" +\n \"by CCPA, including identifiers, financial data, and online activity.\",\n categories: [\n \"name\",\n \"email\",\n \"phone\",\n \"address\",\n \"ssn\",\n \"national-id\",\n \"passport\",\n \"drivers-license\",\n \"bank-account\",\n \"credit-card\",\n \"tax-id\",\n \"ipv4\",\n \"ipv6\",\n \"url\",\n \"social-media\",\n \"date-of-birth\",\n \"medical-record\",\n \"health-insurance\",\n \"api-key\",\n ],\n defaultStrategy: { strategy: \"redact\" },\n};\n\n/**\n * LGPD — Lei Geral de Proteção de Dados Pessoais (Brazil, Lei nº 13.709/2018).\n * Covers dados pessoais and the identifiers that lead to dados pessoais sensíveis.\n * Default strategy: redact (anonymisation in the sense of Art. 5, XI).\n */\nconst LGPD_PRESET: PresetConfig = {\n name: \"lgpd\",\n description:\n \"Brazilian Lei Geral de Proteção de Dados — Covers personal data that identifies a \" +\n \"natural person. CPF is detected in its punctuated form; CNPJ, RG, CNH and CEP need \" +\n \"custom patterns.\",\n categories: [\n \"name\",\n \"email\",\n \"phone\",\n \"address\",\n \"date-of-birth\",\n \"national-id\",\n \"tax-id\",\n \"passport\",\n \"drivers-license\",\n \"bank-account\",\n \"iban\",\n \"credit-card\",\n \"cryptocurrency\",\n \"ipv4\",\n \"ipv6\",\n \"url\",\n \"social-media\",\n \"license-plate\",\n \"medical-record\",\n \"health-insurance\",\n \"prescription\",\n ],\n defaultStrategy: { strategy: \"redact\" },\n};\n\n/**\n * PIPEDA — Personal Information Protection and Electronic Documents Act (Canada).\n * Covers information about an identifiable individual.\n * Default strategy: redact.\n */\nconst PIPEDA_PRESET: PresetConfig = {\n name: \"pipeda\",\n description:\n \"Canadian PIPEDA — Covers information about an identifiable individual, including the \" +\n \"Social Insurance Number. Provincial health card numbers and postal codes need custom \" +\n \"patterns.\",\n categories: [\n \"name\",\n \"email\",\n \"phone\",\n \"address\",\n \"date-of-birth\",\n \"national-id\",\n \"ssn\",\n \"passport\",\n \"drivers-license\",\n \"tax-id\",\n \"bank-account\",\n \"iban\",\n \"credit-card\",\n \"ipv4\",\n \"ipv6\",\n \"social-media\",\n \"medical-record\",\n \"health-insurance\",\n \"prescription\",\n ],\n defaultStrategy: { strategy: \"redact\" },\n};\n\n/**\n * PCI-DSS — Payment Card Industry Data Security Standard.\n * Covers the card number and the cardholder data around it. Sensitive\n * authentication data (card verification codes, track data, PINs) has no\n * detector.\n * Default strategy: redact. Card and bank account numbers are masked with\n * the last 4 digits visible (industry standard).\n */\nconst PCI_DSS_PRESET: PresetConfig = {\n name: \"pci-dss\",\n description:\n \"PCI-DSS Cardholder Data — Covers credit/debit card numbers, bank accounts, \" +\n \"and associated cardholder identifiers.\",\n categories: [\"credit-card\", \"bank-account\", \"name\", \"address\", \"email\", \"phone\"],\n defaultStrategy: { strategy: \"redact\" },\n rules: [\n {\n category: \"credit-card\",\n strategy: { strategy: \"mask\", keepTrailing: 4 },\n },\n {\n category: \"bank-account\",\n strategy: { strategy: \"mask\", keepTrailing: 4 },\n },\n ],\n};\n\n/**\n * SOX — Sarbanes-Oxley Act.\n * Covers financial audit trail and corporate officer identifiers.\n * Default strategy: redact.\n */\nconst SOX_PRESET: PresetConfig = {\n name: \"sox\",\n description:\n \"Sarbanes-Oxley Act — Covers financial records, corporate officer identifiers, \" +\n \"and audit trail data.\",\n categories: [\n \"name\",\n \"email\",\n \"tax-id\",\n \"bank-account\",\n \"company-registration\",\n \"ssn\",\n \"address\",\n \"phone\",\n ],\n defaultStrategy: { strategy: \"redact\" },\n};\n\n/**\n * FERPA — Family Educational Rights and Privacy Act.\n * Covers student education records.\n * Default strategy: redact.\n */\nconst FERPA_PRESET: PresetConfig = {\n name: \"ferpa\",\n description:\n \"FERPA — Covers education records and student personally identifiable information (PII).\",\n categories: [\"name\", \"email\", \"phone\", \"address\", \"date-of-birth\", \"ssn\", \"national-id\"],\n defaultStrategy: { strategy: \"redact\" },\n};\n\n// ---------------------------------------------------------------------------\n// Registry & lookup\n// ---------------------------------------------------------------------------\n\n/** All built-in presets keyed by name. */\nexport const PRESET_REGISTRY: Readonly<Record<CompliancePreset, PresetConfig>> = {\n gdpr: GDPR_PRESET,\n lgpd: LGPD_PRESET,\n pipeda: PIPEDA_PRESET,\n hipaa: HIPAA_PRESET,\n ccpa: CCPA_PRESET,\n \"pci-dss\": PCI_DSS_PRESET,\n sox: SOX_PRESET,\n ferpa: FERPA_PRESET,\n} as const;\n\n/**\n * Get a compliance preset configuration by name.\n *\n * @param name - The preset name.\n * @returns The {@link PresetConfig} for the named preset.\n * @throws {@link PresetNotFoundError} if the preset name is not recognised.\n *\n * @example\n * ```ts\n * import { getPreset } from \"anonyma\";\n *\n * const preset = getPreset(\"hipaa\");\n * console.log(preset.categories); // [\"name\", \"address\", ...]\n * ```\n */\nexport function getPreset(name: CompliancePreset): PresetConfig {\n const preset = (PRESET_REGISTRY as Partial<Record<CompliancePreset, PresetConfig>>)[name];\n if (preset === undefined) {\n throw new PresetNotFoundError(name);\n }\n return preset;\n}\n"]}
|