anonyma 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (183) hide show
  1. package/CHANGELOG.md +273 -144
  2. package/README.md +427 -143
  3. package/dist/ai/index.cjs +522 -0
  4. package/dist/ai/index.cjs.map +1 -0
  5. package/dist/ai/index.d.cts +322 -0
  6. package/dist/ai/index.d.ts +322 -0
  7. package/dist/ai/index.js +505 -0
  8. package/dist/ai/index.js.map +1 -0
  9. package/dist/audit/index.cjs +359 -0
  10. package/dist/audit/index.cjs.map +1 -0
  11. package/dist/audit/index.d.cts +287 -0
  12. package/dist/audit/index.d.ts +287 -0
  13. package/dist/audit/index.js +340 -0
  14. package/dist/audit/index.js.map +1 -0
  15. package/dist/chunk-26IHMQHL.cjs +662 -0
  16. package/dist/chunk-26IHMQHL.cjs.map +1 -0
  17. package/dist/chunk-2F2GWGTB.js +174 -0
  18. package/dist/chunk-2F2GWGTB.js.map +1 -0
  19. package/dist/chunk-2NNMJ55L.cjs +45 -0
  20. package/dist/chunk-2NNMJ55L.cjs.map +1 -0
  21. package/dist/chunk-2YG7R4KJ.cjs +114 -0
  22. package/dist/chunk-2YG7R4KJ.cjs.map +1 -0
  23. package/dist/chunk-2ZZHLCEJ.js +237 -0
  24. package/dist/chunk-2ZZHLCEJ.js.map +1 -0
  25. package/dist/chunk-3CY6ATKS.cjs +308 -0
  26. package/dist/chunk-3CY6ATKS.cjs.map +1 -0
  27. package/dist/chunk-3D5ZCJ7R.js +268 -0
  28. package/dist/chunk-3D5ZCJ7R.js.map +1 -0
  29. package/dist/chunk-6LDAIJBL.js +103 -0
  30. package/dist/chunk-6LDAIJBL.js.map +1 -0
  31. package/dist/chunk-7HK2V5Q4.js +111 -0
  32. package/dist/chunk-7HK2V5Q4.js.map +1 -0
  33. package/dist/chunk-AAP472NG.js +177 -0
  34. package/dist/chunk-AAP472NG.js.map +1 -0
  35. package/dist/chunk-AP4JIUNW.js +42 -0
  36. package/dist/chunk-AP4JIUNW.js.map +1 -0
  37. package/dist/chunk-BBJPQPGP.js +457 -0
  38. package/dist/chunk-BBJPQPGP.js.map +1 -0
  39. package/dist/chunk-CRXRJZEV.cjs +82 -0
  40. package/dist/chunk-CRXRJZEV.cjs.map +1 -0
  41. package/dist/chunk-E3PICZYI.js +20 -0
  42. package/dist/chunk-E3PICZYI.js.map +1 -0
  43. package/dist/chunk-F7O2FA3F.cjs +1255 -0
  44. package/dist/chunk-F7O2FA3F.cjs.map +1 -0
  45. package/dist/chunk-FB56NAAH.cjs +243 -0
  46. package/dist/chunk-FB56NAAH.cjs.map +1 -0
  47. package/dist/chunk-G4AN7FND.js +1063 -0
  48. package/dist/chunk-G4AN7FND.js.map +1 -0
  49. package/dist/chunk-GS3FRH4K.js +294 -0
  50. package/dist/chunk-GS3FRH4K.js.map +1 -0
  51. package/dist/chunk-GYMG5OI3.cjs +186 -0
  52. package/dist/chunk-GYMG5OI3.cjs.map +1 -0
  53. package/dist/chunk-IHEIYZPL.cjs +301 -0
  54. package/dist/chunk-IHEIYZPL.cjs.map +1 -0
  55. package/dist/chunk-IJAMLYOT.cjs +1087 -0
  56. package/dist/chunk-IJAMLYOT.cjs.map +1 -0
  57. package/dist/chunk-ISL5B4LU.cjs +181 -0
  58. package/dist/chunk-ISL5B4LU.cjs.map +1 -0
  59. package/dist/chunk-JKW36IPT.js +179 -0
  60. package/dist/chunk-JKW36IPT.js.map +1 -0
  61. package/dist/chunk-KOCQBDI4.cjs +179 -0
  62. package/dist/chunk-KOCQBDI4.cjs.map +1 -0
  63. package/dist/chunk-OGNLB2KA.js +79 -0
  64. package/dist/chunk-OGNLB2KA.js.map +1 -0
  65. package/dist/chunk-PKHZ7CVI.js +28 -0
  66. package/dist/chunk-PKHZ7CVI.js.map +1 -0
  67. package/dist/chunk-QYD4F6T7.cjs +114 -0
  68. package/dist/chunk-QYD4F6T7.cjs.map +1 -0
  69. package/dist/chunk-RCW5IPPR.js +1288 -0
  70. package/dist/chunk-RCW5IPPR.js.map +1 -0
  71. package/dist/chunk-RMMKYHUN.cjs +35 -0
  72. package/dist/chunk-RMMKYHUN.cjs.map +1 -0
  73. package/dist/chunk-S4BJ2ADB.cjs +22 -0
  74. package/dist/chunk-S4BJ2ADB.cjs.map +1 -0
  75. package/dist/chunk-S7NH6CHY.cjs +462 -0
  76. package/dist/chunk-S7NH6CHY.cjs.map +1 -0
  77. package/dist/chunk-SIHPDZXA.js +176 -0
  78. package/dist/chunk-SIHPDZXA.js.map +1 -0
  79. package/dist/chunk-TW7PM3UJ.cjs +30 -0
  80. package/dist/chunk-TW7PM3UJ.cjs.map +1 -0
  81. package/dist/chunk-UA3EOFBS.cjs +1322 -0
  82. package/dist/chunk-UA3EOFBS.cjs.map +1 -0
  83. package/dist/chunk-VE4CCW7W.js +32 -0
  84. package/dist/chunk-VE4CCW7W.js.map +1 -0
  85. package/dist/chunk-W6RBCHYF.js +651 -0
  86. package/dist/chunk-W6RBCHYF.js.map +1 -0
  87. package/dist/chunk-WLJN7GIS.cjs +189 -0
  88. package/dist/chunk-WLJN7GIS.cjs.map +1 -0
  89. package/dist/chunk-YMLR375Z.js +1244 -0
  90. package/dist/chunk-YMLR375Z.js.map +1 -0
  91. package/dist/compliance/index.cjs +88 -0
  92. package/dist/compliance/index.cjs.map +1 -0
  93. package/dist/compliance/index.d.cts +277 -0
  94. package/dist/compliance/index.d.ts +277 -0
  95. package/dist/compliance/index.js +47 -0
  96. package/dist/compliance/index.js.map +1 -0
  97. package/dist/crypto.cjs +12 -136
  98. package/dist/crypto.cjs.map +1 -1
  99. package/dist/crypto.d.cts +4 -3
  100. package/dist/crypto.d.ts +4 -3
  101. package/dist/crypto.js +3 -137
  102. package/dist/crypto.js.map +1 -1
  103. package/dist/detectors/index.cjs +146 -1483
  104. package/dist/detectors/index.cjs.map +1 -1
  105. package/dist/detectors/index.d.cts +1 -1
  106. package/dist/detectors/index.d.ts +1 -1
  107. package/dist/detectors/index.js +3 -1449
  108. package/dist/detectors/index.js.map +1 -1
  109. package/dist/engine/index.cjs +441 -0
  110. package/dist/engine/index.cjs.map +1 -0
  111. package/dist/engine/index.d.cts +728 -0
  112. package/dist/engine/index.d.ts +728 -0
  113. package/dist/engine/index.js +189 -0
  114. package/dist/engine/index.js.map +1 -0
  115. package/dist/hash-2PSYNDMM.cjs +14 -0
  116. package/dist/hash-2PSYNDMM.cjs.map +1 -0
  117. package/dist/hash-CELLDNKN.js +5 -0
  118. package/dist/hash-CELLDNKN.js.map +1 -0
  119. package/dist/index.cjs +153 -2816
  120. package/dist/index.cjs.map +1 -1
  121. package/dist/index.d.cts +93 -11
  122. package/dist/index.d.ts +93 -11
  123. package/dist/index.js +13 -2791
  124. package/dist/index.js.map +1 -1
  125. package/dist/json-CKDvlRtl.d.ts +147 -0
  126. package/dist/json-s8ny-RCo.d.cts +147 -0
  127. package/dist/mcp/index.cjs +751 -0
  128. package/dist/mcp/index.cjs.map +1 -0
  129. package/dist/mcp/index.d.cts +226 -0
  130. package/dist/mcp/index.d.ts +226 -0
  131. package/dist/mcp/index.js +744 -0
  132. package/dist/mcp/index.js.map +1 -0
  133. package/dist/middleware/express.cjs +93 -0
  134. package/dist/middleware/express.cjs.map +1 -0
  135. package/dist/middleware/express.d.cts +90 -0
  136. package/dist/middleware/express.d.ts +90 -0
  137. package/dist/middleware/express.js +91 -0
  138. package/dist/middleware/express.js.map +1 -0
  139. package/dist/middleware/hono.cjs +58 -0
  140. package/dist/middleware/hono.cjs.map +1 -0
  141. package/dist/middleware/hono.d.cts +75 -0
  142. package/dist/middleware/hono.d.ts +75 -0
  143. package/dist/middleware/hono.js +56 -0
  144. package/dist/middleware/hono.js.map +1 -0
  145. package/dist/middleware/index.cjs +24 -0
  146. package/dist/middleware/index.cjs.map +1 -0
  147. package/dist/middleware/index.d.cts +106 -0
  148. package/dist/middleware/index.d.ts +106 -0
  149. package/dist/middleware/index.js +15 -0
  150. package/dist/middleware/index.js.map +1 -0
  151. package/dist/schemas.cjs +5 -5
  152. package/dist/schemas.cjs.map +1 -1
  153. package/dist/schemas.d.cts +20 -10
  154. package/dist/schemas.d.ts +20 -10
  155. package/dist/schemas.js +5 -5
  156. package/dist/schemas.js.map +1 -1
  157. package/dist/session-BdRftyZ5.d.cts +102 -0
  158. package/dist/session-Cs2zlNQp.d.ts +102 -0
  159. package/dist/stream.cjs +13 -2262
  160. package/dist/stream.cjs.map +1 -1
  161. package/dist/stream.d.cts +1 -1
  162. package/dist/stream.d.ts +1 -1
  163. package/dist/stream.js +6 -2255
  164. package/dist/stream.js.map +1 -1
  165. package/dist/types--tPm_AjY.d.ts +199 -0
  166. package/dist/types-0BJH_wqc.d.cts +199 -0
  167. package/dist/types-CPUhjvl8.d.cts +629 -0
  168. package/dist/types-Dtht33aq.d.ts +629 -0
  169. package/dist/{types-D-9HzVuy.d.cts → types-EJTj_BKY.d.cts} +38 -7
  170. package/dist/{types-D-9HzVuy.d.ts → types-EJTj_BKY.d.ts} +38 -7
  171. package/dist/types-Zt_bZvwS.d.cts +182 -0
  172. package/dist/types-Zt_bZvwS.d.ts +182 -0
  173. package/dist/validators.cjs +39 -181
  174. package/dist/validators.cjs.map +1 -1
  175. package/dist/validators.js +1 -174
  176. package/dist/validators.js.map +1 -1
  177. package/dist/vault/index.cjs +688 -0
  178. package/dist/vault/index.cjs.map +1 -0
  179. package/dist/vault/index.d.cts +385 -0
  180. package/dist/vault/index.d.ts +385 -0
  181. package/dist/vault/index.js +669 -0
  182. package/dist/vault/index.js.map +1 -0
  183. package/package.json +128 -11
package/dist/index.js CHANGED
@@ -1,2516 +1,14 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropNames = Object.getOwnPropertyNames;
3
- var __esm = (fn, res) => function __init() {
4
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
- };
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
-
11
- // src/errors.ts
12
- var AnonymaError, ValidationError, UnsupportedStrategyError, UnknownCategoryError, CryptoNotAvailableError, EncryptionError, PresetNotFoundError, AllowlistMatchError, BatchProcessingError;
13
- var init_errors = __esm({
14
- "src/errors.ts"() {
15
- AnonymaError = class extends Error {
16
- /** Machine-readable error code. */
17
- code;
18
- constructor(message, code) {
19
- super(message);
20
- this.name = "AnonymaError";
21
- this.code = code;
22
- Object.setPrototypeOf(this, new.target.prototype);
23
- }
24
- };
25
- ValidationError = class extends AnonymaError {
26
- /** The name of the invalid field or parameter. */
27
- field;
28
- constructor(field, reason) {
29
- super(`Validation failed for \`${field}\`: ${reason}`, "VALIDATION_ERROR");
30
- this.name = "ValidationError";
31
- this.field = field;
32
- Object.setPrototypeOf(this, new.target.prototype);
33
- }
34
- };
35
- UnsupportedStrategyError = class extends AnonymaError {
36
- /** The strategy name that was not recognised. */
37
- strategy;
38
- constructor(strategy) {
39
- super(
40
- `Unsupported anonymization strategy: "${strategy}". Supported strategies are: mask, redact, pseudonymize, hash, generalize.`,
41
- "UNSUPPORTED_STRATEGY"
42
- );
43
- this.name = "UnsupportedStrategyError";
44
- this.strategy = strategy;
45
- Object.setPrototypeOf(this, new.target.prototype);
46
- }
47
- };
48
- UnknownCategoryError = class extends AnonymaError {
49
- /** The category name that was not recognised. */
50
- category;
51
- constructor(category) {
52
- super(
53
- `Unknown PII category: "${category}". Supported categories are: email, phone, ssn, credit-card, ipv4, ipv6, url, iban, date-of-birth.`,
54
- "UNKNOWN_CATEGORY"
55
- );
56
- this.name = "UnknownCategoryError";
57
- this.category = category;
58
- Object.setPrototypeOf(this, new.target.prototype);
59
- }
60
- };
61
- CryptoNotAvailableError = class extends AnonymaError {
62
- constructor() {
63
- super(
64
- "The Web Crypto API (globalThis.crypto.subtle) is not available in this environment. Upgrade to Node.js \u2265 18 or use a polyfill.",
65
- "CRYPTO_NOT_AVAILABLE"
66
- );
67
- this.name = "CryptoNotAvailableError";
68
- Object.setPrototypeOf(this, new.target.prototype);
69
- }
70
- };
71
- EncryptionError = class extends AnonymaError {
72
- /** The operation that failed (`"encrypt"` or `"decrypt"`). */
73
- operation;
74
- constructor(operation, cause) {
75
- super(
76
- `Encryption operation "${operation}" failed.${cause instanceof Error ? ` Cause: ${cause.message}` : ""}`,
77
- "ENCRYPTION_ERROR"
78
- );
79
- this.name = "EncryptionError";
80
- this.operation = operation;
81
- if (cause !== void 0) {
82
- this.cause = cause;
83
- }
84
- Object.setPrototypeOf(this, new.target.prototype);
85
- }
86
- };
87
- PresetNotFoundError = class extends AnonymaError {
88
- /** The preset name that was not recognised. */
89
- preset;
90
- constructor(preset) {
91
- super(
92
- `Unknown compliance preset: "${preset}". Available presets are: gdpr, hipaa, ccpa, pci-dss, sox, ferpa.`,
93
- "PRESET_NOT_FOUND"
94
- );
95
- this.name = "PresetNotFoundError";
96
- this.preset = preset;
97
- Object.setPrototypeOf(this, new.target.prototype);
98
- }
99
- };
100
- AllowlistMatchError = class extends AnonymaError {
101
- /** The allowlist entry or field that was invalid. */
102
- field;
103
- constructor(field, reason) {
104
- super(`Invalid allowlist configuration for \`${field}\`: ${reason}`, "ALLOWLIST_MATCH_ERROR");
105
- this.name = "AllowlistMatchError";
106
- this.field = field;
107
- Object.setPrototypeOf(this, new.target.prototype);
108
- }
109
- };
110
- BatchProcessingError = class extends AnonymaError {
111
- /** Number of items that succeeded. */
112
- succeeded;
113
- /** Number of items that failed. */
114
- failed;
115
- /** Total items submitted. */
116
- total;
117
- constructor(succeeded, failed, total) {
118
- super(
119
- `Batch processing completed with errors: ${String(succeeded)}/${String(total)} succeeded, ${String(failed)} failed.`,
120
- "BATCH_PROCESSING_ERROR"
121
- );
122
- this.name = "BatchProcessingError";
123
- this.succeeded = succeeded;
124
- this.failed = failed;
125
- this.total = total;
126
- Object.setPrototypeOf(this, new.target.prototype);
127
- }
128
- };
129
- }
130
- });
131
-
132
- // src/strategies/hash.ts
133
- var hash_exports = {};
134
- __export(hash_exports, {
135
- hash: () => hash
136
- });
137
- function assertCrypto() {
138
- const subtle = globalThis.crypto?.subtle;
139
- if (typeof subtle === "undefined") {
140
- throw new CryptoNotAvailableError();
141
- }
142
- return subtle;
143
- }
144
- async function hash(value, options = {}) {
145
- const { truncate = 16, pepper } = options;
146
- if (!Number.isInteger(truncate) || truncate < 1 || truncate > 64) {
147
- throw new ValidationError("truncate", "must be an integer between 1 and 64 (inclusive)");
148
- }
149
- const subtle = assertCrypto();
150
- const input = pepper !== void 0 ? `${pepper}:${value}` : value;
151
- const encoded = new TextEncoder().encode(input);
152
- const buffer = await subtle.digest("SHA-256", encoded);
153
- const hex = Array.from(new Uint8Array(buffer)).map((b) => b.toString(16).padStart(2, "0")).join("");
154
- return hex.slice(0, truncate);
155
- }
156
- var init_hash = __esm({
157
- "src/strategies/hash.ts"() {
158
- init_errors();
159
- }
160
- });
161
-
162
- // src/detectors/email.ts
163
- var EMAIL_PATTERN = /\b[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*\.[a-zA-Z]{2,}\b/g;
164
- var EMAIL_AGGRESSIVE_PATTERN = /\b[a-z0-9][a-z0-9._-]*\s*(?:@|\[at\]|\(at\))\s*[a-z0-9][\w.-]*\s*(?:\.|\[dot\]|\(dot\))\s*[a-z]{2,}\b/gi;
165
- function detectEmail(text) {
166
- const matches = [];
167
- const pattern = new RegExp(EMAIL_PATTERN.source, "g");
168
- let match;
169
- while ((match = pattern.exec(text)) !== null) {
170
- matches.push({
171
- category: "email",
172
- value: match[0],
173
- start: match.index,
174
- end: match.index + match[0].length,
175
- confidence: 0.99
176
- });
177
- }
178
- return matches;
179
- }
180
- function detectEmailAggressive(text) {
181
- const standard = detectEmail(text);
182
- const standardRanges = standard.map((m) => [m.start, m.end]);
183
- const extra = [];
184
- const aggressivePattern = new RegExp(EMAIL_AGGRESSIVE_PATTERN.source, "gi");
185
- let match;
186
- while ((match = aggressivePattern.exec(text)) !== null) {
187
- const start = match.index;
188
- const end = start + match[0].length;
189
- const overlaps = standardRanges.some(([s, e]) => start < e && end > s);
190
- if (!overlaps) {
191
- extra.push({
192
- category: "email",
193
- value: match[0],
194
- start,
195
- end,
196
- confidence: 0.75
197
- });
198
- }
199
- }
200
- return [...standard, ...extra];
201
- }
202
-
203
- // src/detectors/phone.ts
204
- var PHONE_PATTERN = /(?<!\d)(?:\+?1[-.\s]?)?(?:\(\d{3}\)|\d{3})[-.\s]?\d{3}[-.\s]?\d{4}(?!\d)|(?:\+(?:[0-9] ?){6,14}[0-9])(?!\d)/g;
205
- var PHONE_SEVEN_DIGIT_PATTERN = /\b\d{3}[-.\s]\d{4}\b/g;
206
- function detectPhone(text) {
207
- const matches = [];
208
- const pattern = new RegExp(PHONE_PATTERN.source, "g");
209
- let match;
210
- while ((match = pattern.exec(text)) !== null) {
211
- const value = match[0].trim();
212
- if (value.replace(/\D/g, "").length < 7) continue;
213
- matches.push({
214
- category: "phone",
215
- value,
216
- start: match.index,
217
- end: match.index + match[0].length,
218
- confidence: 0.9
219
- });
220
- }
221
- return matches;
222
- }
223
- function detectPhoneAggressive(text) {
224
- const standard = detectPhone(text);
225
- const standardRanges = standard.map((m) => [m.start, m.end]);
226
- const extra = [];
227
- const sevenDigit = new RegExp(PHONE_SEVEN_DIGIT_PATTERN.source, "g");
228
- let match;
229
- while ((match = sevenDigit.exec(text)) !== null) {
230
- const start = match.index;
231
- const end = start + match[0].length;
232
- const overlaps = standardRanges.some(([s, e]) => start < e && end > s);
233
- if (!overlaps) {
234
- extra.push({
235
- category: "phone",
236
- value: match[0],
237
- start,
238
- end,
239
- confidence: 0.7
240
- });
241
- }
242
- }
243
- return [...standard, ...extra];
244
- }
245
-
246
- // src/detectors/ssn.ts
247
- var SSN_PATTERN = /\b(?!000|666|9\d{2})\d{3}[- ]?(?!00)\d{2}[- ]?(?!0{4})\d{4}\b/g;
248
- var SSN_AGGRESSIVE_PATTERN = /\b(?!000|666|9\d{2})\d{3}(?!00)\d{2}(?!0{4})\d{4}\b/g;
249
- function detectSsn(text) {
250
- const matches = [];
251
- const pattern = new RegExp(SSN_PATTERN.source, "g");
252
- let match;
253
- while ((match = pattern.exec(text)) !== null) {
254
- matches.push({
255
- category: "ssn",
256
- value: match[0],
257
- start: match.index,
258
- end: match.index + match[0].length,
259
- confidence: 0.95
260
- });
261
- }
262
- return matches;
263
- }
264
- function detectSsnAggressive(text) {
265
- const standard = detectSsn(text);
266
- const standardRanges = standard.map((m) => [m.start, m.end]);
267
- const extra = [];
268
- const aggressive = new RegExp(SSN_AGGRESSIVE_PATTERN.source, "g");
269
- let match;
270
- while ((match = aggressive.exec(text)) !== null) {
271
- const start = match.index;
272
- const end = start + match[0].length;
273
- const overlaps = standardRanges.some(([s, e]) => start < e && end > s);
274
- if (!overlaps) {
275
- extra.push({
276
- category: "ssn",
277
- value: match[0],
278
- start,
279
- end,
280
- confidence: 0.8
281
- });
282
- }
283
- }
284
- return [...standard, ...extra];
285
- }
286
-
287
- // src/detectors/credit-card.ts
288
- var CARD_PATTERN = /\b(?:\d[ -]?){13,19}\b/g;
289
- var CARD_MASKED_PATTERN = /\*{4}[ -]?\*{4}[ -]?\*{4}[ -]?\d{4}\b/g;
290
- function luhn(digits) {
291
- let sum = 0;
292
- let isEven = false;
293
- for (let i = digits.length - 1; i >= 0; i--) {
294
- let d = parseInt(digits[i] ?? "0", 10);
295
- if (isEven) {
296
- d *= 2;
297
- if (d > 9) d -= 9;
298
- }
299
- sum += d;
300
- isEven = !isEven;
301
- }
302
- return sum % 10 === 0;
303
- }
304
- function detectCreditCard(text) {
305
- const matches = [];
306
- const pattern = new RegExp(CARD_PATTERN.source, "g");
307
- let match;
308
- while ((match = pattern.exec(text)) !== null) {
309
- const raw = match[0];
310
- const digitsOnly = raw.replace(/[ -]/g, "");
311
- if (digitsOnly.length < 13 || digitsOnly.length > 19) continue;
312
- if (!luhn(digitsOnly)) continue;
313
- matches.push({
314
- category: "credit-card",
315
- value: raw,
316
- start: match.index,
317
- end: match.index + raw.length,
318
- confidence: 0.97
319
- });
320
- }
321
- return matches;
322
- }
323
- function detectCreditCardAggressive(text) {
324
- const standard = detectCreditCard(text);
325
- const standardRanges = standard.map((m) => [m.start, m.end]);
326
- const extra = [];
327
- const maskedPattern = new RegExp(CARD_MASKED_PATTERN.source, "g");
328
- let match;
329
- while ((match = maskedPattern.exec(text)) !== null) {
330
- const start = match.index;
331
- const end = start + match[0].length;
332
- const overlaps = standardRanges.some(([s, e]) => start < e && end > s);
333
- if (!overlaps) {
334
- extra.push({
335
- category: "credit-card",
336
- value: match[0],
337
- start,
338
- end,
339
- confidence: 0.8
340
- });
341
- }
342
- }
343
- return [...standard, ...extra];
344
- }
345
-
346
- // src/detectors/ip-address.ts
347
- var IPV4_PATTERN = /\b(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)(?:\/\d{1,2})?\b/g;
348
- var IPV6_PATTERN = /\b(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}\b|\b(?:[0-9a-fA-F]{1,4}:){1,7}:\b|\b(?:[0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}\b|\b(?:[0-9a-fA-F]{1,4}:){1,5}(?::[0-9a-fA-F]{1,4}){1,2}\b|\b(?:[0-9a-fA-F]{1,4}:){1,4}(?::[0-9a-fA-F]{1,4}){1,3}\b|\b(?:[0-9a-fA-F]{1,4}:){1,3}(?::[0-9a-fA-F]{1,4}){1,4}\b|\b(?:[0-9a-fA-F]{1,4}:){1,2}(?::[0-9a-fA-F]{1,4}){1,5}\b|\b[0-9a-fA-F]{1,4}:(?::[0-9a-fA-F]{1,4}){1,6}\b|\b:(?::[0-9a-fA-F]{1,4}){1,7}\b|\b::(?:[fF]{4}(?::0{1,4})?:)?(?:25[0-5]|2[0-4]\d|[01]?\d\d?)(?:\.(?:25[0-5]|2[0-4]\d|[01]?\d\d?)){3}\b/g;
349
- function detectIpv4(text) {
350
- const matches = [];
351
- const pattern = new RegExp(IPV4_PATTERN.source, "g");
352
- let match;
353
- while ((match = pattern.exec(text)) !== null) {
354
- matches.push({
355
- category: "ipv4",
356
- value: match[0],
357
- start: match.index,
358
- end: match.index + match[0].length,
359
- confidence: 0.98
360
- });
361
- }
362
- return matches;
363
- }
364
- function detectIpv6(text) {
365
- const matches = [];
366
- const pattern = new RegExp(IPV6_PATTERN.source, "g");
367
- let match;
368
- while ((match = pattern.exec(text)) !== null) {
369
- matches.push({
370
- category: "ipv6",
371
- value: match[0],
372
- start: match.index,
373
- end: match.index + match[0].length,
374
- confidence: 0.98
375
- });
376
- }
377
- return matches;
378
- }
379
-
380
- // src/detectors/url.ts
381
- var URL_PATTERN = /\bhttps?:\/\/(?:(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}|localhost|(?:\d{1,3}\.){3}\d{1,3})(?::\d{1,5})?(?:\/[^\s,;'"<>()[\]{}]*)?(?:\?[^\s,;'"<>()[\]{}]*)?(?:#[^\s,;'"<>()[\]{}]*)?\b/g;
382
- function detectUrl(text) {
383
- const matches = [];
384
- const pattern = new RegExp(URL_PATTERN.source, "g");
385
- let match;
386
- while ((match = pattern.exec(text)) !== null) {
387
- matches.push({
388
- category: "url",
389
- value: match[0],
390
- start: match.index,
391
- end: match.index + match[0].length,
392
- confidence: 0.95
393
- });
394
- }
395
- return matches;
396
- }
397
-
398
- // src/detectors/iban.ts
399
- var IBAN_PATTERN = /\b[A-Z]{2}\d{2}[ ]?(?:[A-Z0-9]{4}[ ]?){1,7}[A-Z0-9]{1,4}\b/g;
400
- function isValidIban(iban) {
401
- const cleaned = iban.replace(/\s/g, "").toUpperCase();
402
- if (cleaned.length < 5 || cleaned.length > 34) return false;
403
- const rearranged = cleaned.slice(4) + cleaned.slice(0, 4);
404
- const numeric = rearranged.split("").map((ch) => {
405
- const code = ch.charCodeAt(0);
406
- return code >= 65 && code <= 90 ? String(code - 55) : ch;
407
- }).join("");
408
- return BigInt(numeric) % 97n === 1n;
409
- }
410
- function detectIban(text) {
411
- const matches = [];
412
- const pattern = new RegExp(IBAN_PATTERN.source, "g");
413
- let match;
414
- while ((match = pattern.exec(text)) !== null) {
415
- const value = match[0];
416
- if (!isValidIban(value)) continue;
417
- matches.push({
418
- category: "iban",
419
- value,
420
- start: match.index,
421
- end: match.index + value.length,
422
- confidence: 0.99
423
- });
424
- }
425
- return matches;
426
- }
427
-
428
- // src/detectors/date-of-birth.ts
429
- var MONTH_NAMES = "(?:January|February|March|April|May|June|July|August|September|October|November|December|Jan|Feb|Mar|Apr|Jun|Jul|Aug|Sep|Oct|Nov|Dec)";
430
- var ISO_PATTERN = /\b(19|20)\d{2}[- /](0[1-9]|1[0-2])[- /](0[1-9]|[12]\d|3[01])\b/g;
431
- var US_PATTERN = /\b(0[1-9]|1[0-2])[-/](0[1-9]|[12]\d|3[01])[-/](19|20)\d{2}\b/g;
432
- var EU_PATTERN = /\b(0[1-9]|[12]\d|3[01])[/.](0[1-9]|1[0-2])[/.](19|20)\d{2}\b/g;
433
- var LONG_US_PATTERN = new RegExp(
434
- `\\b${MONTH_NAMES}\\s+(0?[1-9]|[12]\\d|3[01]),?\\s+(19|20)\\d{2}\\b`,
435
- "g"
436
- );
437
- var LONG_EU_PATTERN = new RegExp(
438
- `\\b(0?[1-9]|[12]\\d|3[01])\\s+${MONTH_NAMES}\\s+(19|20)\\d{2}\\b`,
439
- "g"
440
- );
441
- function collect(text, source, confidence) {
442
- const matches = [];
443
- const pattern = new RegExp(source, "g");
444
- let match;
445
- while ((match = pattern.exec(text)) !== null) {
446
- matches.push({
447
- category: "date-of-birth",
448
- value: match[0],
449
- start: match.index,
450
- end: match.index + match[0].length,
451
- confidence
452
- });
453
- }
454
- return matches;
455
- }
456
- function detectDateOfBirth(text) {
457
- const seen = /* @__PURE__ */ new Set();
458
- const all = [];
459
- const candidates = [
460
- ...collect(text, ISO_PATTERN.source, 0.85),
461
- ...collect(text, US_PATTERN.source, 0.8),
462
- ...collect(text, EU_PATTERN.source, 0.78),
463
- ...collect(text, LONG_US_PATTERN.source, 0.88),
464
- ...collect(text, LONG_EU_PATTERN.source, 0.88)
465
- ];
466
- const sorted = [...candidates].sort((a, b) => b.confidence - a.confidence);
467
- for (const match of sorted) {
468
- let overlaps = false;
469
- for (const pos of seen) {
470
- if (match.start < pos) {
471
- overlaps = true;
472
- break;
473
- }
474
- }
475
- if (!overlaps) {
476
- for (let i = match.start; i < match.end; i++) seen.add(i);
477
- all.push(match);
478
- }
479
- }
480
- return all.sort((a, b) => a.start - b.start);
481
- }
482
-
483
- // src/detectors/name.ts
484
- var NAME_GREETING_PATTERN = /(?:^|\.\s+)(?:dear|hi|hello|greetings|hey there|hey)\s+([A-Z][a-z]+(?:\s+[A-Z][a-z]+)+)/gi;
485
- var NAME_TITLE_PATTERN = /\b(?:Mr|Mrs|Ms|Miss|Mx|Dr|Prof(?:essor)?|Rev(?:erend)?|Hon(?:orable)?|Capt(?:ain)?|Cmdr|Commander|Lt|Lieu?t(?:enant)?|Sgt|Sergeant|Fr|Father|Sr|Sister|Br|Brother|Esq|Esquire)\.?\s+([A-Z][a-z]+(?:\s+[A-Z][a-z]+)*)/g;
486
- var NAME_CONTEXT_KEYWORDS = "patient|client|defendant|plaintiff|applicant|appellant|respondent|petitioner|claimant|employee|employer|teacher|student|author|by|from|to|signed by|authored by|submitted by|prepared by|filed by|reviewed by|approved by|written by|sent by|received by|referring to|regarding|re:|concerning|subject:|for|name:|full name:|contact:";
487
- var NAME_CONTEXT_PATTERN = new RegExp(
488
- `\\b(?:${NAME_CONTEXT_KEYWORDS})\\s+([A-Z][a-z]+(?:\\s+[A-Z][a-z]+)+)`,
489
- "g"
490
- );
491
- var NAME_AGGRESSIVE_PATTERN = new RegExp(
492
- // Greeting context
493
- `(?:(?:^|\\.[\\s]+)(?:dear|hi|hello|greetings|hey there|hey)\\s+([A-Z][a-z]+(?:\\s+[A-Z][a-z]+)*))|(?:\\b(?:Mr|Mrs|Ms|Miss|Mx|Dr|Prof(?:essor)?|Rev(?:erend)?|Hon(?:orable)?|Capt(?:ain)?|Cmdr|Commander|Lt|Lieu?t(?:enant)?|Sgt|Sergeant|Fr|Father|Sr|Sister|Br|Brother|Esq|Esquire)\\.?\\s+([A-Z][a-z]+(?:\\s+[A-Z][a-z]+)*))|(?:\\b(?:${NAME_CONTEXT_KEYWORDS.replace(/[-()\]{}*+?.,\\^$|#\s[]/g, "\\$&")})\\s+([A-Z][a-z]+(?:\\s+[A-Z][a-z]+)+))`,
494
- "gi"
495
- );
496
- function extractNameMatches(text, pattern, confidence) {
497
- const matches = [];
498
- const flags = pattern.flags.includes("g") ? pattern.flags : pattern.flags + "g";
499
- const re = new RegExp(pattern.source, flags);
500
- let m;
501
- while ((m = re.exec(text)) !== null) {
502
- const rawCapture = (m[1] ?? m[2] ?? m[3] ?? "").trim();
503
- if (!rawCapture) continue;
504
- const captureStart = text.indexOf(rawCapture, m.index);
505
- if (captureStart === -1) continue;
506
- const firstChar = text[captureStart];
507
- if (!firstChar || !/[A-Z]/.test(firstChar)) continue;
508
- const nameMatch = /^(?:[A-Z][a-z]+)(?:\s+[A-Z][a-z]+)*/.exec(text.slice(captureStart));
509
- if (!nameMatch) continue;
510
- const name = nameMatch[0];
511
- matches.push({
512
- category: "name",
513
- value: name,
514
- start: captureStart,
515
- end: captureStart + name.length,
516
- confidence
517
- });
518
- }
519
- return matches;
520
- }
521
- function deduplicateNameMatches(matches) {
522
- const sorted = [...matches].sort((a, b) => a.start - b.start || b.confidence - a.confidence);
523
- const result = [];
524
- let cursor = 0;
525
- for (const m of sorted) {
526
- if (m.start >= cursor) {
527
- result.push(m);
528
- cursor = m.end;
529
- }
530
- }
531
- return result;
532
- }
533
- function detectName(text) {
534
- const greetingMatches = extractNameMatches(text, NAME_GREETING_PATTERN, 0.75);
535
- const titleMatches = extractNameMatches(text, NAME_TITLE_PATTERN, 0.78);
536
- const contextMatches = extractNameMatches(text, NAME_CONTEXT_PATTERN, 0.7);
537
- return deduplicateNameMatches([...greetingMatches, ...titleMatches, ...contextMatches]);
538
- }
539
- function detectNameAggressive(text) {
540
- return deduplicateNameMatches(extractNameMatches(text, NAME_AGGRESSIVE_PATTERN, 0.65));
541
- }
542
-
543
- // src/detectors/address.ts
544
- var US_STREET_PATTERN = /\b\d{1,5}\s+(?:(?:N|S|E|W|NE|NW|SE|SW|North|South|East|West|Northeast|Northwest|Southeast|Southwest)\.?\s+)?(?:[A-Z][a-z]+\s+){1,4}(?:St(?:reet)?|Ave(?:nue)?|Blvd|Boulevard|Dr(?:ive)?|Rd|Road|Ln|Lane|Ct|Court|Pl|Place|Cir|Circle|Way|Pkwy|Parkway|Hwy|Highway|Trl|Trail|Terr(?:ace)?|Terr)\.?(?:\s+(?:Apt|Apartment|Suite|Ste|Unit|#)\s*\w+)?\b/gi;
545
- var UK_POSTCODE_PATTERN = /\b[A-Z]{1,2}\d[A-Z\d]?\s*\d[A-Z]{2}\b/gi;
546
- var PO_BOX_PATTERN = /\bP\.?O\.?\s+Box\s+\d+\b/gi;
547
- var ADDRESS_CONTEXT_PATTERN = /(?:address(?:ed to)?|lives at|located at|shipped? to|mailing address|billing address|residence|resides at|home address|headquartered at|office address)\s*:?\s*([^\n,]{10,80})/gi;
548
- function detectAddress(text) {
549
- const matches = [];
550
- const seen = /* @__PURE__ */ new Set();
551
- function push(value, start, end, confidence) {
552
- const key = `${String(start)}-${String(end)}`;
553
- if (seen.has(key)) return;
554
- seen.add(key);
555
- matches.push({ category: "address", value, start, end, confidence });
556
- }
557
- const usPattern = new RegExp(US_STREET_PATTERN.source, "gi");
558
- let m;
559
- while ((m = usPattern.exec(text)) !== null) {
560
- push(m[0], m.index, m.index + m[0].length, 0.8);
561
- }
562
- const ukPattern = new RegExp(UK_POSTCODE_PATTERN.source, "gi");
563
- while ((m = ukPattern.exec(text)) !== null) {
564
- push(m[0], m.index, m.index + m[0].length, 0.78);
565
- }
566
- const poPattern = new RegExp(PO_BOX_PATTERN.source, "gi");
567
- while ((m = poPattern.exec(text)) !== null) {
568
- push(m[0], m.index, m.index + m[0].length, 0.85);
569
- }
570
- const ctxPattern = new RegExp(ADDRESS_CONTEXT_PATTERN.source, "gi");
571
- while ((m = ctxPattern.exec(text)) !== null) {
572
- const captured = (m[1] ?? m[0]).trim();
573
- const start = text.indexOf(captured, m.index);
574
- if (start !== -1) {
575
- push(captured, start, start + captured.length, 0.82);
576
- }
577
- }
578
- return matches;
579
- }
580
-
581
- // src/detectors/passport.ts
582
- var PASSPORT_PATTERNS = [
583
- // US: 1 letter + 8 digits
584
- { pattern: /\b[A-Z]\d{8}\b/g, confidence: 0.75 },
585
- // Canada: 2 letters + 6 digits
586
- { pattern: /\b[A-Z]{2}\d{6}\b/g, confidence: 0.75 },
587
- // Australia: 1 letter + 7 digits
588
- { pattern: /\b[A-Z]\d{7}\b/g, confidence: 0.73 },
589
- // UK: 9 digits (no letters)
590
- { pattern: /\b\d{9}\b/g, confidence: 0.6 },
591
- // lower confidence — many false positives
592
- // EU generic: 1-2 letters + 5-8 digits
593
- { pattern: /\b[A-Z]{1,2}\d{5,8}\b/g, confidence: 0.7 }
594
- ];
595
- var PASSPORT_CONTEXT_RE = /\b(?:passport(?:\s+(?:number|no\.?|#))?)\s*:?\s*/gi;
596
- function detectPassport(text) {
597
- const matches = [];
598
- const contextPositions = [];
599
- const ctxRe = new RegExp(PASSPORT_CONTEXT_RE.source, "gi");
600
- let cm;
601
- while ((cm = ctxRe.exec(text)) !== null) {
602
- contextPositions.push(cm.index + cm[0].length);
603
- }
604
- const seen = /* @__PURE__ */ new Set();
605
- for (const { pattern, confidence } of PASSPORT_PATTERNS) {
606
- const re = new RegExp(pattern.source, "g");
607
- let m;
608
- while ((m = re.exec(text)) !== null) {
609
- const match = m;
610
- const key = `${String(match.index)}-${String(match.index + match[0].length)}`;
611
- if (seen.has(key)) continue;
612
- const hasContext = contextPositions.some(
613
- (pos) => pos <= match.index && match.index - pos <= 30
614
- );
615
- const adjustedConfidence = hasContext ? Math.min(confidence + 0.15, 0.95) : confidence;
616
- if (adjustedConfidence < 0.7 && !hasContext) continue;
617
- seen.add(key);
618
- matches.push({
619
- category: "passport",
620
- value: match[0],
621
- start: match.index,
622
- end: match.index + match[0].length,
623
- confidence: adjustedConfidence
624
- });
625
- }
626
- }
627
- return matches;
628
- }
629
-
630
- // src/detectors/drivers-license.ts
631
- var DL_CONTEXT_PATTERN = /\b(?:driver(?:'?s)?\s+licen[cs]e|driving\s+licen[cs]e|DL\s*#?|D\.?L\.?(?:\s*#)?|licen[cs]e\s+(?:no|number|#))\s*:?\s*/gi;
632
- var UK_DVLA_PATTERN = /\b[A-Z9]{5}\d{6}[02-9]\d[A-Z]{2}\w{2}\b/g;
633
- var GENERIC_DL_PATTERN = /\b[A-Z0-9]{5,15}\b/g;
634
- function detectDriversLicense(text) {
635
- const matches = [];
636
- const seen = /* @__PURE__ */ new Set();
637
- const contextPositions = [];
638
- const ctxRe = new RegExp(DL_CONTEXT_PATTERN.source, "gi");
639
- let cm;
640
- while ((cm = ctxRe.exec(text)) !== null) {
641
- contextPositions.push(cm.index + cm[0].length);
642
- }
643
- function push(value, start, end, confidence) {
644
- const key = `${String(start)}-${String(end)}`;
645
- if (seen.has(key)) return;
646
- seen.add(key);
647
- matches.push({ category: "drivers-license", value, start, end, confidence });
648
- }
649
- const ukRe = new RegExp(UK_DVLA_PATTERN.source, "g");
650
- let m;
651
- while ((m = ukRe.exec(text)) !== null) {
652
- push(m[0], m.index, m.index + m[0].length, 0.78);
653
- }
654
- const genericRe = new RegExp(GENERIC_DL_PATTERN.source, "g");
655
- while ((m = genericRe.exec(text)) !== null) {
656
- const match = m;
657
- const hasContext = contextPositions.some(
658
- (pos) => pos <= match.index && match.index - pos <= 20
659
- );
660
- if (hasContext) {
661
- push(match[0], match.index, match.index + match[0].length, 0.85);
662
- }
663
- }
664
- return matches;
665
- }
666
-
667
- // src/detectors/national-id.ts
668
- var CA_SIN_PATTERN = /\b\d{3}[\s-]\d{3}[\s-]\d{3}\b/g;
669
- var MX_CURP_PATTERN = /\b[A-Z]{4}\d{6}[HM][A-Z]{2}[A-Z]{3}[A-Z0-9]\d\b/g;
670
- var MX_RFC_PATTERN = /\b[A-ZÑ&]{3,4}\d{6}[A-Z0-9]{3}\b/g;
671
- var UK_NINO_PATTERN = /\b[A-CEGHJ-PR-TW-Z]{2}[\s-]?\d{2}[\s-]?\d{2}[\s-]?\d{2}[\s-]?[A-D]\b/gi;
672
- var IN_AADHAAR_PATTERN = /\b[2-9]\d{3}[\s-]?\d{4}[\s-]?\d{4}\b/g;
673
- var CN_RESIDENT_ID_PATTERN = /\b\d{17}[\dX]\b/gi;
674
- var KR_RRN_PATTERN = /\b\d{6}[\s-]\d{7}\b/g;
675
- var DE_PERSONALAUSWEIS_PATTERN = /\b[A-Z0-9]{9}\b/g;
676
- var FR_NIR_PATTERN = /\b[12]\s?\d{2}\s?\d{2}\s?\d{2}\s?\d{3}\s?\d{3}\s?\d{2}\b/g;
677
- var BR_CPF_PATTERN = /\b\d{3}\.\d{3}\.\d{3}[-\s]\d{2}\b/g;
678
- var AR_DNI_PATTERN = /\b\d{2,3}[.\s]?\d{3}[.\s]?\d{3}\b/g;
679
- var ZA_ID_PATTERN = /\b\d{13}\b/g;
680
- var NG_NIN_PATTERN = /\b\d{11}\b/g;
681
- var AU_TFN_PATTERN = /\b\d{3}[\s-]?\d{3}[\s-]?\d{3}\b/g;
682
- var SE_PERSONNUMMER_PATTERN = /\b\d{6}[-+]\d{4}\b/g;
683
- var ES_DNIE_PATTERN = /\b(?:\d{8}[A-Z]|[XYZ]\d{7}[A-Z])\b/gi;
684
- var IT_CF_PATTERN = /\b[A-Z]{6}\d{2}[A-EHLMPRST]\d{2}[A-Z]\d{3}[A-Z]\b/gi;
685
- var PT_NIF_PATTERN = /\b[1-9]\d{8}\b/g;
686
- var NL_BSN_PATTERN = /\b\d{9}\b/g;
687
- var NATIONAL_ID_CONTEXT_RE = /\b(?:national\s+(?:id|identification|identity)\s*(?:number|no\.?|card|#)?|id\s+(?:number|no\.?|#)|citizen(?:ship)?\s+(?:number|id)|personal\s+(?:id|identification)\s*(?:number|no\.?)?|identificat(?:ion|or))\s*:?\s*/gi;
688
- var NATIONAL_ID_ENTRIES = [
689
- { pattern: CA_SIN_PATTERN, confidence: 0.85, requiresContext: false },
690
- { pattern: MX_CURP_PATTERN, confidence: 0.9, requiresContext: false },
691
- { pattern: MX_RFC_PATTERN, confidence: 0.78, requiresContext: true },
692
- { pattern: UK_NINO_PATTERN, confidence: 0.9, requiresContext: false },
693
- { pattern: IN_AADHAAR_PATTERN, confidence: 0.82, requiresContext: false },
694
- { pattern: CN_RESIDENT_ID_PATTERN, confidence: 0.8, requiresContext: true },
695
- { pattern: KR_RRN_PATTERN, confidence: 0.87, requiresContext: false },
696
- { pattern: BR_CPF_PATTERN, confidence: 0.92, requiresContext: false },
697
- { pattern: SE_PERSONNUMMER_PATTERN, confidence: 0.87, requiresContext: false },
698
- { pattern: ES_DNIE_PATTERN, confidence: 0.82, requiresContext: false },
699
- { pattern: IT_CF_PATTERN, confidence: 0.88, requiresContext: false },
700
- { pattern: FR_NIR_PATTERN, confidence: 0.84, requiresContext: false },
701
- // More ambiguous — require context
702
- { pattern: AR_DNI_PATTERN, confidence: 0.75, requiresContext: true },
703
- { pattern: ZA_ID_PATTERN, confidence: 0.72, requiresContext: true },
704
- { pattern: NG_NIN_PATTERN, confidence: 0.7, requiresContext: true },
705
- { pattern: AU_TFN_PATTERN, confidence: 0.75, requiresContext: true },
706
- { pattern: DE_PERSONALAUSWEIS_PATTERN, confidence: 0.75, requiresContext: true },
707
- { pattern: PT_NIF_PATTERN, confidence: 0.7, requiresContext: true },
708
- { pattern: NL_BSN_PATTERN, confidence: 0.7, requiresContext: true }
709
- ];
710
- function detectNationalId(text) {
711
- const matches = [];
712
- const seen = /* @__PURE__ */ new Set();
713
- const contextPositions = [];
714
- const ctxRe = new RegExp(NATIONAL_ID_CONTEXT_RE.source, "gi");
715
- let cm;
716
- while ((cm = ctxRe.exec(text)) !== null) {
717
- contextPositions.push(cm.index + cm[0].length);
718
- }
719
- for (const entry of NATIONAL_ID_ENTRIES) {
720
- const re = new RegExp(entry.pattern.source, "g");
721
- let m;
722
- while ((m = re.exec(text)) !== null) {
723
- const match = m;
724
- const key = `${String(match.index)}-${String(match.index + match[0].length)}`;
725
- if (seen.has(key)) continue;
726
- const hasContext = contextPositions.some(
727
- (pos) => pos <= match.index && match.index - pos <= 40
728
- );
729
- if (entry.requiresContext && !hasContext) continue;
730
- const confidence = hasContext ? Math.min(entry.confidence + 0.05, 0.97) : entry.confidence;
731
- seen.add(key);
732
- matches.push({
733
- category: "national-id",
734
- value: match[0],
735
- start: match.index,
736
- end: match.index + match[0].length,
737
- confidence
738
- });
739
- }
740
- }
741
- return matches;
742
- }
743
-
744
- // src/detectors/bank-account.ts
745
- var BANK_CONTEXT_RE = /\b(?:routing\s+(?:number|no\.?|#)|sort\s+code|account\s+(?:number|no\.?|#)|bank\s+account|IBAN|BIC|SWIFT|ABA)\s*:?\s*/gi;
746
- var US_ABA_ROUTING_PATTERN = /\b(?:0[1-9]|1[0-2]|2[1-9]|3[0-2]|6[1-9]|7[0-2]|80)\d{7}\b/g;
747
- var UK_SORT_CODE_PATTERN = /\b\d{2}-\d{2}-\d{2}\b/g;
748
- var SWIFT_BIC_PATTERN = /\b[A-Z]{4}[A-Z]{2}[A-Z0-9]{2}(?:[A-Z0-9]{3})?\b/g;
749
- var GENERIC_ACCOUNT_PATTERN = /\b\d{7,18}\b/g;
750
- function detectBankAccount(text) {
751
- const matches = [];
752
- const seen = /* @__PURE__ */ new Set();
753
- const contextPositions = [];
754
- const ctxRe = new RegExp(BANK_CONTEXT_RE.source, "gi");
755
- let cm;
756
- while ((cm = ctxRe.exec(text)) !== null) {
757
- contextPositions.push(cm.index + cm[0].length);
758
- }
759
- function hasContext(index) {
760
- return contextPositions.some((pos) => pos <= index && index - pos <= 30);
761
- }
762
- function push(value, start, end, confidence) {
763
- const key = `${String(start)}-${String(end)}`;
764
- if (seen.has(key)) return;
765
- seen.add(key);
766
- matches.push({ category: "bank-account", value, start, end, confidence });
767
- }
768
- let m;
769
- const abaRe = new RegExp(US_ABA_ROUTING_PATTERN.source, "g");
770
- while ((m = abaRe.exec(text)) !== null) {
771
- if (hasContext(m.index)) push(m[0], m.index, m.index + m[0].length, 0.85);
772
- }
773
- const scRe = new RegExp(UK_SORT_CODE_PATTERN.source, "g");
774
- while ((m = scRe.exec(text)) !== null) {
775
- push(m[0], m.index, m.index + m[0].length, 0.8);
776
- }
777
- const swiftRe = new RegExp(SWIFT_BIC_PATTERN.source, "g");
778
- while ((m = swiftRe.exec(text)) !== null) {
779
- const countryCode = m[0].slice(4, 6);
780
- if (/^[A-Z]{2}$/.test(countryCode)) {
781
- push(m[0], m.index, m.index + m[0].length, 0.82);
782
- }
783
- }
784
- const genericRe = new RegExp(GENERIC_ACCOUNT_PATTERN.source, "g");
785
- while ((m = genericRe.exec(text)) !== null) {
786
- if (hasContext(m.index)) push(m[0], m.index, m.index + m[0].length, 0.8);
787
- }
788
- return matches;
789
- }
790
-
791
- // src/detectors/cryptocurrency.ts
792
- var BTC_LEGACY_PATTERN = /\b1[a-km-zA-HJ-NP-Z1-9]{25,34}\b/g;
793
- var BTC_P2SH_PATTERN = /\b3[a-km-zA-HJ-NP-Z1-9]{25,34}\b/g;
794
- var BTC_BECH32_PATTERN = /\bbc1[a-z0-9]{39,59}\b/g;
795
- var ETH_PATTERN = /\b0x[a-fA-F0-9]{40}\b/g;
796
- var LTC_LEGACY_PATTERN = /\bL[a-km-zA-HJ-NP-Z1-9]{26,33}\b/g;
797
- var LTC_M_PATTERN = /\bM[a-km-zA-HJ-NP-Z1-9]{26,33}\b/g;
798
- var XMR_PATTERN = /\b4[0-9AB][1-9A-HJ-NP-Za-km-z]{93}\b/g;
799
- var XRP_PATTERN = /\br[a-km-zA-HJ-NP-Z1-9]{24,33}\b/g;
800
- var SOL_PATTERN = /\b[1-9A-HJ-NP-Za-km-z]{43,44}\b/g;
801
- var ADA_PATTERN = /\baddr1[a-z0-9]{58,98}\b/g;
802
- var CRYPTO_ENTRIES = [
803
- { pattern: ETH_PATTERN, confidence: 0.97, requiresContext: false },
804
- { pattern: BTC_BECH32_PATTERN, confidence: 0.95, requiresContext: false },
805
- { pattern: ADA_PATTERN, confidence: 0.92, requiresContext: false },
806
- { pattern: BTC_LEGACY_PATTERN, confidence: 0.88, requiresContext: false },
807
- { pattern: BTC_P2SH_PATTERN, confidence: 0.85, requiresContext: false },
808
- { pattern: LTC_LEGACY_PATTERN, confidence: 0.83, requiresContext: false },
809
- { pattern: LTC_M_PATTERN, confidence: 0.8, requiresContext: false },
810
- { pattern: XMR_PATTERN, confidence: 0.9, requiresContext: false },
811
- { pattern: XRP_PATTERN, confidence: 0.78, requiresContext: true },
812
- { pattern: SOL_PATTERN, confidence: 0.72, requiresContext: true }
813
- ];
814
- var CRYPTO_CONTEXT_RE = /\b(?:wallet(?:\s+address)?|crypto(?:currency)?(?:\s+address)?|bitcoin|btc|ethereum|eth|litecoin|ltc|monero|xmr|ripple|xrp|solana|sol|cardano|ada|address)\s*:?\s*/gi;
815
- function detectCryptocurrency(text) {
816
- const matches = [];
817
- const seen = /* @__PURE__ */ new Set();
818
- const contextPositions = [];
819
- const ctxRe = new RegExp(CRYPTO_CONTEXT_RE.source, "gi");
820
- let cm;
821
- while ((cm = ctxRe.exec(text)) !== null) {
822
- contextPositions.push(cm.index + cm[0].length);
823
- }
824
- function hasContext(index) {
825
- return contextPositions.some((pos) => pos <= index && index - pos <= 40);
826
- }
827
- for (const entry of CRYPTO_ENTRIES) {
828
- const re = new RegExp(entry.pattern.source, entry.pattern.flags.includes("i") ? "gi" : "g");
829
- let m;
830
- while ((m = re.exec(text)) !== null) {
831
- if (entry.requiresContext && !hasContext(m.index)) continue;
832
- const key = `${String(m.index)}-${String(m.index + m[0].length)}`;
833
- if (seen.has(key)) continue;
834
- seen.add(key);
835
- const confidence = hasContext(m.index) ? Math.min(entry.confidence + 0.03, 0.99) : entry.confidence;
836
- matches.push({
837
- category: "cryptocurrency",
838
- value: m[0],
839
- start: m.index,
840
- end: m.index + m[0].length,
841
- confidence
842
- });
843
- }
844
- }
845
- return matches;
846
- }
847
-
848
- // src/detectors/tax-id.ts
849
- var US_EIN_PATTERN = /\b\d{2}-\d{7}\b/g;
850
- var US_ITIN_PATTERN = /\b9\d{2}[\s-](?:5[0-9]|6[0-5]|7[0-9]|8[0-8]|90|91|92|9[4-9])[\s-]\d{4}\b/g;
851
- var UK_UTR_PATTERN = /\b\d{10}\b/g;
852
- var EU_VAT_PATTERN = /\b(?:AT|BE|BG|CY|CZ|DE|DK|EE|EL|ES|FI|FR|GB|HR|HU|IE|IT|LT|LU|LV|MT|NL|PL|PT|RO|SE|SI|SK)[\s-]?[A-Z0-9]{8,12}\b/g;
853
- var AU_ABN_PATTERN = /\b\d{2}[\s]?\d{3}[\s]?\d{3}[\s]?\d{3}\b/g;
854
- var TAX_CONTEXT_RE = /\b(?:tax(?:\s+(?:id(?:entification)?|number|no\.?|#|reference))?|T\.?I\.?N\.?|EIN|ITIN|UTR|VAT(?:\s+(?:number|no\.?|reg(?:istration)?|#))?|ABN|TFN)\s*:?\s*/gi;
855
- function detectTaxId(text) {
856
- const matches = [];
857
- const seen = /* @__PURE__ */ new Set();
858
- const contextPositions = [];
859
- const ctxRe = new RegExp(TAX_CONTEXT_RE.source, "gi");
860
- let cm;
861
- while ((cm = ctxRe.exec(text)) !== null) {
862
- contextPositions.push(cm.index + cm[0].length);
863
- }
864
- function hasContext(index) {
865
- return contextPositions.some((pos) => pos <= index && index - pos <= 30);
866
- }
867
- function push(value, start, end, confidence) {
868
- const key = `${String(start)}-${String(end)}`;
869
- if (seen.has(key)) return;
870
- seen.add(key);
871
- matches.push({ category: "tax-id", value, start, end, confidence });
872
- }
873
- let m;
874
- const einRe = new RegExp(US_EIN_PATTERN.source, "g");
875
- while ((m = einRe.exec(text)) !== null) {
876
- push(m[0], m.index, m.index + m[0].length, hasContext(m.index) ? 0.92 : 0.8);
877
- }
878
- const itinRe = new RegExp(US_ITIN_PATTERN.source, "g");
879
- while ((m = itinRe.exec(text)) !== null) {
880
- push(m[0], m.index, m.index + m[0].length, 0.9);
881
- }
882
- const vatRe = new RegExp(EU_VAT_PATTERN.source, "g");
883
- while ((m = vatRe.exec(text)) !== null) {
884
- push(m[0], m.index, m.index + m[0].length, hasContext(m.index) ? 0.9 : 0.78);
885
- }
886
- const abnRe = new RegExp(AU_ABN_PATTERN.source, "g");
887
- while ((m = abnRe.exec(text)) !== null) {
888
- if (hasContext(m.index)) push(m[0], m.index, m.index + m[0].length, 0.82);
889
- }
890
- const utrRe = new RegExp(UK_UTR_PATTERN.source, "g");
891
- while ((m = utrRe.exec(text)) !== null) {
892
- if (hasContext(m.index)) push(m[0], m.index, m.index + m[0].length, 0.85);
893
- }
894
- return matches;
895
- }
896
-
897
- // src/validators.ts
898
- function luhn2(digits) {
899
- const stripped = digits.replace(/[\s-]/g, "");
900
- if (!/^\d+$/.test(stripped) || stripped.length < 2) return false;
901
- let sum = 0;
902
- let isEven = false;
903
- for (let i = stripped.length - 1; i >= 0; i--) {
904
- let d = parseInt(stripped[i] ?? "0", 10);
905
- if (isEven) {
906
- d *= 2;
907
- if (d > 9) d -= 9;
908
- }
909
- sum += d;
910
- isEven = !isEven;
911
- }
912
- return sum % 10 === 0;
913
- }
914
- function nhsMod11(value) {
915
- const stripped = value.replace(/[\s-]/g, "");
916
- if (!/^\d{10}$/.test(stripped)) return false;
917
- let sum = 0;
918
- for (let i = 0; i < 9; i++) {
919
- sum += parseInt(stripped[i] ?? "0", 10) * (10 - i);
920
- }
921
- const remainder = sum % 11;
922
- if (remainder === 1) return false;
923
- const checkDigit = remainder === 0 ? 0 : 11 - remainder;
924
- return parseInt(stripped[9] ?? "0", 10) === checkDigit;
925
- }
926
- var VIN_TRANSLITERATION = {
927
- A: 1,
928
- B: 2,
929
- C: 3,
930
- D: 4,
931
- E: 5,
932
- F: 6,
933
- G: 7,
934
- H: 8,
935
- J: 1,
936
- K: 2,
937
- L: 3,
938
- M: 4,
939
- N: 5,
940
- P: 7,
941
- R: 9,
942
- S: 2,
943
- T: 3,
944
- U: 4,
945
- V: 5,
946
- W: 6,
947
- X: 7,
948
- Y: 8,
949
- Z: 9,
950
- 0: 0,
951
- 1: 1,
952
- 2: 2,
953
- 3: 3,
954
- 4: 4,
955
- 5: 5,
956
- 6: 6,
957
- 7: 7,
958
- 8: 8,
959
- 9: 9
960
- };
961
- var VIN_WEIGHTS = [8, 7, 6, 5, 4, 3, 2, 10, 0, 9, 8, 7, 6, 5, 4, 3, 2];
962
- function vinChecksum(vin) {
963
- const upper = vin.toUpperCase();
964
- if (!/^[A-HJ-NPR-Z0-9]{17}$/.test(upper)) return false;
965
- let sum = 0;
966
- for (let i = 0; i < 17; i++) {
967
- const char = upper[i] ?? "";
968
- const val = VIN_TRANSLITERATION[char];
969
- const weight = VIN_WEIGHTS[i];
970
- if (val === void 0 || weight === void 0) return false;
971
- sum += val * weight;
972
- }
973
- const remainder = sum % 11;
974
- const checkChar = upper[8] ?? "";
975
- const expected = remainder === 10 ? "X" : String(remainder);
976
- return checkChar === expected;
977
- }
978
- function deaChecksum(value) {
979
- const stripped = value.replace(/[\s-]/g, "").toUpperCase();
980
- if (!/^[ABCDEFGHJKLMNPRSTUX][A-Z9]\d{7}$/.test(stripped)) return false;
981
- const digits = stripped.slice(2);
982
- const oddSum = parseInt(digits[0] ?? "0", 10) + parseInt(digits[2] ?? "0", 10) + parseInt(digits[4] ?? "0", 10);
983
- const evenSum = parseInt(digits[1] ?? "0", 10) + parseInt(digits[3] ?? "0", 10) + parseInt(digits[5] ?? "0", 10);
984
- const checksum = (oddSum + 2 * evenSum) % 10;
985
- return checksum === parseInt(digits[6] ?? "0", 10);
986
- }
987
-
988
- // src/detectors/medical-record.ts
989
- var MRN_CONTEXT_RE = /\b(?:MRN|medical\s+record\s+(?:number|no\.?|#)|patient\s+(?:id|number|no\.?|#)|chart\s+(?:number|no\.?|#))\s*:?\s*/gi;
990
- var US_NPI_PATTERN = /\b[12]\d{9}\b/g;
991
- var DEA_PATTERN = /\b[ABCDEFGHJKLMNPRSTUX][A-Z9]\d{7}\b/gi;
992
- var MRN_PATTERN = /\b[A-Z0-9]{6,12}\b/g;
993
- function detectMedicalRecord(text) {
994
- const matches = [];
995
- const seen = /* @__PURE__ */ new Set();
996
- const contextPositions = [];
997
- const ctxRe = new RegExp(MRN_CONTEXT_RE.source, "gi");
998
- let cm;
999
- while ((cm = ctxRe.exec(text)) !== null) {
1000
- contextPositions.push(cm.index + cm[0].length);
1001
- }
1002
- function hasContextAt(index) {
1003
- return contextPositions.some((pos) => pos <= index && index - pos <= 30);
1004
- }
1005
- function push(value, start, end, confidence) {
1006
- const key = `${String(start)}-${String(end)}`;
1007
- if (seen.has(key)) return;
1008
- seen.add(key);
1009
- matches.push({ category: "medical-record", value, start, end, confidence });
1010
- }
1011
- let m;
1012
- const deaRe = new RegExp(DEA_PATTERN.source, "gi");
1013
- while ((m = deaRe.exec(text)) !== null) {
1014
- if (deaChecksum(m[0])) {
1015
- push(m[0], m.index, m.index + m[0].length, 0.9);
1016
- }
1017
- }
1018
- const npiRe = new RegExp(US_NPI_PATTERN.source, "g");
1019
- while ((m = npiRe.exec(text)) !== null) {
1020
- const withPrefix = "80840" + m[0];
1021
- if (luhn2(withPrefix)) {
1022
- push(m[0], m.index, m.index + m[0].length, hasContextAt(m.index) ? 0.88 : 0.75);
1023
- }
1024
- }
1025
- const mrnRe = new RegExp(MRN_PATTERN.source, "g");
1026
- while ((m = mrnRe.exec(text)) !== null) {
1027
- if (hasContextAt(m.index)) {
1028
- push(m[0], m.index, m.index + m[0].length, 0.85);
1029
- }
1030
- }
1031
- return matches;
1032
- }
1033
-
1034
- // src/detectors/health-insurance.ts
1035
- var HI_CONTEXT_RE = /\b(?:health\s+insurance(?:\s+(?:number|id|no\.?|#|card))?|insurance\s+(?:number|id|no\.?|#|member\s+id)|member\s+(?:id|number|no\.?)|policy\s+(?:number|no\.?|#)|medicare|medicaid|NHS(?:\s+(?:number|no\.?|#))?|EHIC|beneficiary\s+(?:id|number))\s*:?\s*/gi;
1036
- var US_MBI_PATTERN = /\b[1-9][AC-HJ-NP-RT-Y][0-9][AC-HJ-NP-RT-Y][AC-HJ-NP-RT-Y0-9]\d[AC-HJ-NP-RT-Y][AC-HJ-NP-RT-Y0-9]{2}\d{2}\b/gi;
1037
- var UK_NHS_PATTERN = /\b\d{3}[\s-]\d{3}[\s-]\d{4}\b|\b\d{10}\b/g;
1038
- var EU_EHIC_PATTERN = /\b[A-Z]{2}\d{6,10}\b/g;
1039
- var GENERIC_MEMBER_ID = /\b[A-Z0-9]{8,14}\b/g;
1040
- function detectHealthInsurance(text) {
1041
- const matches = [];
1042
- const seen = /* @__PURE__ */ new Set();
1043
- const contextPositions = [];
1044
- const ctxRe = new RegExp(HI_CONTEXT_RE.source, "gi");
1045
- let cm;
1046
- while ((cm = ctxRe.exec(text)) !== null) {
1047
- contextPositions.push(cm.index + cm[0].length);
1048
- }
1049
- function hasContextAt(index) {
1050
- return contextPositions.some((pos) => pos <= index && index - pos <= 40);
1051
- }
1052
- function push(value, start, end, confidence) {
1053
- const key = `${String(start)}-${String(end)}`;
1054
- if (seen.has(key)) return;
1055
- seen.add(key);
1056
- matches.push({ category: "health-insurance", value, start, end, confidence });
1057
- }
1058
- let m;
1059
- const mbiRe = new RegExp(US_MBI_PATTERN.source, "gi");
1060
- while ((m = mbiRe.exec(text)) !== null) {
1061
- push(m[0], m.index, m.index + m[0].length, hasContextAt(m.index) ? 0.9 : 0.8);
1062
- }
1063
- const nhsRe = new RegExp(UK_NHS_PATTERN.source, "g");
1064
- while ((m = nhsRe.exec(text)) !== null) {
1065
- if (nhsMod11(m[0])) {
1066
- push(m[0], m.index, m.index + m[0].length, hasContextAt(m.index) ? 0.92 : 0.82);
1067
- }
1068
- }
1069
- const ehicRe = new RegExp(EU_EHIC_PATTERN.source, "g");
1070
- while ((m = ehicRe.exec(text)) !== null) {
1071
- if (hasContextAt(m.index)) {
1072
- push(m[0], m.index, m.index + m[0].length, 0.78);
1073
- }
1074
- }
1075
- const genericRe = new RegExp(GENERIC_MEMBER_ID.source, "g");
1076
- while ((m = genericRe.exec(text)) !== null) {
1077
- if (hasContextAt(m.index)) {
1078
- push(m[0], m.index, m.index + m[0].length, 0.75);
1079
- }
1080
- }
1081
- return matches;
1082
- }
1083
-
1084
- // src/detectors/prescription.ts
1085
- var RX_CONTEXT_RE = /\b(?:Rx\s*(?:number|no\.?|#)?|prescription\s*(?:number|no\.?|#)?|prescription\s+id|NDC|drug\s+code|DEA\s*(?:number|no\.?|#)?)\s*:?\s*/gi;
1086
- var DEA_PATTERN2 = /\b[ABCDEFGHJKLMNPRSTUX][A-Z9]\d{7}\b/gi;
1087
- var NDC_PATTERN = /\b\d{4}-\d{4}-\d{2}\b|\b\d{5}-\d{3}-\d{2}\b|\b\d{5}-\d{4}-\d{1}\b|\b\d{5}-\d{4}-\d{2}\b/g;
1088
- var RX_NUMBER_PATTERN = /\b\d{4,12}\b/g;
1089
- function detectPrescription(text) {
1090
- const matches = [];
1091
- const seen = /* @__PURE__ */ new Set();
1092
- const contextPositions = [];
1093
- const ctxRe = new RegExp(RX_CONTEXT_RE.source, "gi");
1094
- let cm;
1095
- while ((cm = ctxRe.exec(text)) !== null) {
1096
- contextPositions.push(cm.index + cm[0].length);
1097
- }
1098
- function hasContextAt(index) {
1099
- return contextPositions.some((pos) => pos <= index && index - pos <= 30);
1100
- }
1101
- function push(value, start, end, confidence) {
1102
- const key = `${String(start)}-${String(end)}`;
1103
- if (seen.has(key)) return;
1104
- seen.add(key);
1105
- matches.push({ category: "prescription", value, start, end, confidence });
1106
- }
1107
- let m;
1108
- const deaRe = new RegExp(DEA_PATTERN2.source, "gi");
1109
- while ((m = deaRe.exec(text)) !== null) {
1110
- if (deaChecksum(m[0])) {
1111
- push(m[0], m.index, m.index + m[0].length, 0.9);
1112
- }
1113
- }
1114
- const ndcRe = new RegExp(NDC_PATTERN.source, "g");
1115
- while ((m = ndcRe.exec(text)) !== null) {
1116
- push(m[0], m.index, m.index + m[0].length, hasContextAt(m.index) ? 0.9 : 0.78);
1117
- }
1118
- const rxRe = new RegExp(RX_NUMBER_PATTERN.source, "g");
1119
- while ((m = rxRe.exec(text)) !== null) {
1120
- if (hasContextAt(m.index)) {
1121
- push(m[0], m.index, m.index + m[0].length, 0.82);
1122
- }
1123
- }
1124
- return matches;
1125
- }
1126
-
1127
- // src/detectors/api-key.ts
1128
- var API_KEY_ENTRIES = [
1129
- // AWS Access Key ID
1130
- {
1131
- pattern: /\bAKIA[0-9A-Z]{16}\b/g,
1132
- confidence: 0.99,
1133
- requiresContext: false
1134
- },
1135
- // Stripe live secret key
1136
- {
1137
- pattern: /\bsk_live_[a-zA-Z0-9]{24,99}\b/g,
1138
- confidence: 0.99,
1139
- requiresContext: false
1140
- },
1141
- // Stripe live publishable key
1142
- {
1143
- pattern: /\bpk_live_[a-zA-Z0-9]{24,99}\b/g,
1144
- confidence: 0.99,
1145
- requiresContext: false
1146
- },
1147
- // Stripe test keys
1148
- {
1149
- pattern: /\b(?:sk|pk)_test_[a-zA-Z0-9]{24,99}\b/g,
1150
- confidence: 0.97,
1151
- requiresContext: false
1152
- },
1153
- // GitHub personal access tokens (classic)
1154
- {
1155
- pattern: /\bghp_[a-zA-Z0-9]{36}\b/g,
1156
- confidence: 0.99,
1157
- requiresContext: false
1158
- },
1159
- // GitHub OAuth tokens
1160
- {
1161
- pattern: /\bgho_[a-zA-Z0-9]{36}\b/g,
1162
- confidence: 0.99,
1163
- requiresContext: false
1164
- },
1165
- // GitHub server-to-server tokens
1166
- {
1167
- pattern: /\bghs_[a-zA-Z0-9]{36}\b/g,
1168
- confidence: 0.99,
1169
- requiresContext: false
1170
- },
1171
- // GitHub refresh tokens
1172
- {
1173
- pattern: /\bghr_[a-zA-Z0-9]{36,76}\b/g,
1174
- confidence: 0.99,
1175
- requiresContext: false
1176
- },
1177
- // GitHub fine-grained PAT
1178
- {
1179
- pattern: /\bgithub_pat_[a-zA-Z0-9_]{59,}\b/g,
1180
- confidence: 0.99,
1181
- requiresContext: false
1182
- },
1183
- // Slack bot tokens
1184
- {
1185
- pattern: /\bxoxb-[0-9A-Za-z-]{40,}\b/g,
1186
- confidence: 0.98,
1187
- requiresContext: false
1188
- },
1189
- // Slack user tokens
1190
- {
1191
- pattern: /\bxoxp-[0-9A-Za-z-]{40,}\b/g,
1192
- confidence: 0.98,
1193
- requiresContext: false
1194
- },
1195
- // Slack app tokens
1196
- {
1197
- pattern: /\bxoxa-[0-9A-Za-z-]{40,}\b/g,
1198
- confidence: 0.98,
1199
- requiresContext: false
1200
- },
1201
- // Slack workspace tokens
1202
- {
1203
- pattern: /\bxoxs-[0-9A-Za-z-]{40,}\b/g,
1204
- confidence: 0.96,
1205
- requiresContext: false
1206
- },
1207
- // OpenAI API keys
1208
- {
1209
- pattern: /\bsk-[a-zA-Z0-9]{32,}\b/g,
1210
- confidence: 0.9,
1211
- requiresContext: false
1212
- },
1213
- // Google API keys
1214
- {
1215
- pattern: /\bAIza[0-9A-Za-z_-]{35}\b/g,
1216
- confidence: 0.99,
1217
- requiresContext: false
1218
- },
1219
- // JWT tokens (only the full 3-part form)
1220
- {
1221
- pattern: /\beyJ[a-zA-Z0-9_-]{10,}\.eyJ[a-zA-Z0-9_-]{10,}\.[a-zA-Z0-9_-]{20,}\b/g,
1222
- confidence: 0.95,
1223
- requiresContext: false
1224
- }
1225
- ];
1226
- var API_KEY_CONTEXT_RE = /\b(?:api[_-\s]?key|api[_-\s]?token|access[_-\s]?token|secret[_-\s]?key|auth(?:orization)?[_-\s]?(?:key|token)|bearer(?:\s+token)?|x-api-key|credential[s]?)\s*[:=]\s*/gi;
1227
- var GENERIC_KEY_PATTERN = /\b[a-zA-Z0-9_.-]{20,80}\b/g;
1228
- function detectApiKey(text) {
1229
- const matches = [];
1230
- const seen = /* @__PURE__ */ new Set();
1231
- const contextPositions = [];
1232
- const ctxRe = new RegExp(API_KEY_CONTEXT_RE.source, "gi");
1233
- let cm;
1234
- while ((cm = ctxRe.exec(text)) !== null) {
1235
- contextPositions.push(cm.index + cm[0].length);
1236
- }
1237
- function hasContextAt(index) {
1238
- return contextPositions.some((pos) => pos <= index && index - pos <= 10);
1239
- }
1240
- function push(value, start, end, confidence) {
1241
- const key = `${String(start)}-${String(end)}`;
1242
- if (seen.has(key)) return;
1243
- seen.add(key);
1244
- matches.push({ category: "api-key", value, start, end, confidence });
1245
- }
1246
- for (const entry of API_KEY_ENTRIES) {
1247
- const re = new RegExp(entry.pattern.source, "g");
1248
- let m2;
1249
- while ((m2 = re.exec(text)) !== null) {
1250
- push(m2[0], m2.index, m2.index + m2[0].length, entry.confidence);
1251
- }
1252
- }
1253
- const genericRe = new RegExp(GENERIC_KEY_PATTERN.source, "g");
1254
- let m;
1255
- while ((m = genericRe.exec(text)) !== null) {
1256
- if (hasContextAt(m.index)) {
1257
- push(m[0], m.index, m.index + m[0].length, 0.82);
1258
- }
1259
- }
1260
- return matches;
1261
- }
1262
-
1263
- // src/detectors/social-media.ts
1264
- var TWITTER_HANDLE_PATTERN = /(?<![a-zA-Z0-9])@[a-zA-Z0-9_]{1,15}(?![a-zA-Z0-9_@])/g;
1265
- var DISCORD_ID_PATTERN = /\b\d{17,19}\b/g;
1266
- var YT_CHANNEL_PATTERN = /\bUC[a-zA-Z0-9_-]{22}\b/g;
1267
- var REDDIT_USER_PATTERN = /\b(?:u|\/u)\/[a-zA-Z0-9_-]{3,20}\b/g;
1268
- var LINKEDIN_PATTERN = /\blinkedin\.com\/in\/[a-zA-Z0-9-]{3,100}\b/gi;
1269
- var DISCORD_CONTEXT_RE = /\b(?:discord(?:\s+(?:id|user|server|guild))?|user\s+id|uid)\s*:?\s*/gi;
1270
- function detectSocialMedia(text) {
1271
- const matches = [];
1272
- const seen = /* @__PURE__ */ new Set();
1273
- const discordContextPositions = [];
1274
- const ctxRe = new RegExp(DISCORD_CONTEXT_RE.source, "gi");
1275
- let cm;
1276
- while ((cm = ctxRe.exec(text)) !== null) {
1277
- discordContextPositions.push(cm.index + cm[0].length);
1278
- }
1279
- function push(value, start, end, confidence) {
1280
- const key = `${String(start)}-${String(end)}`;
1281
- if (seen.has(key)) return;
1282
- seen.add(key);
1283
- matches.push({ category: "social-media", value, start, end, confidence });
1284
- }
1285
- let m;
1286
- const twitterRe = new RegExp(TWITTER_HANDLE_PATTERN.source, "g");
1287
- while ((m = twitterRe.exec(text)) !== null) {
1288
- push(m[0], m.index, m.index + m[0].length, 0.78);
1289
- }
1290
- const ytRe = new RegExp(YT_CHANNEL_PATTERN.source, "g");
1291
- while ((m = ytRe.exec(text)) !== null) {
1292
- push(m[0], m.index, m.index + m[0].length, 0.9);
1293
- }
1294
- const redditRe = new RegExp(REDDIT_USER_PATTERN.source, "g");
1295
- while ((m = redditRe.exec(text)) !== null) {
1296
- push(m[0], m.index, m.index + m[0].length, 0.85);
1297
- }
1298
- const linkedinRe = new RegExp(LINKEDIN_PATTERN.source, "gi");
1299
- while ((m = linkedinRe.exec(text)) !== null) {
1300
- push(m[0], m.index, m.index + m[0].length, 0.92);
1301
- }
1302
- const discordRe = new RegExp(DISCORD_ID_PATTERN.source, "g");
1303
- while ((m = discordRe.exec(text)) !== null) {
1304
- const match = m;
1305
- const hasContext = discordContextPositions.some(
1306
- (pos) => pos <= match.index && match.index - pos <= 30
1307
- );
1308
- if (hasContext) push(match[0], match.index, match.index + match[0].length, 0.85);
1309
- }
1310
- return matches;
1311
- }
1312
-
1313
- // src/detectors/vin.ts
1314
- var VIN_PATTERN = /\b[A-HJ-NPR-Z0-9]{17}\b/gi;
1315
- function detectVin(text) {
1316
- const matches = [];
1317
- const re = new RegExp(VIN_PATTERN.source, "gi");
1318
- let m;
1319
- while ((m = re.exec(text)) !== null) {
1320
- const upper = m[0].toUpperCase();
1321
- const valid = vinChecksum(upper);
1322
- if (valid) {
1323
- matches.push({
1324
- category: "vin",
1325
- value: m[0],
1326
- start: m.index,
1327
- end: m.index + m[0].length,
1328
- confidence: 0.95
1329
- });
1330
- }
1331
- }
1332
- return matches;
1333
- }
1334
- function detectVinAggressive(text) {
1335
- const strict = detectVin(text);
1336
- const strictRanges = new Set(strict.map((m2) => `${String(m2.start)}-${String(m2.end)}`));
1337
- const matches = [...strict];
1338
- const re = new RegExp(VIN_PATTERN.source, "gi");
1339
- let m;
1340
- while ((m = re.exec(text)) !== null) {
1341
- const key = `${String(m.index)}-${String(m.index + m[0].length)}`;
1342
- if (!strictRanges.has(key)) {
1343
- matches.push({
1344
- category: "vin",
1345
- value: m[0],
1346
- start: m.index,
1347
- end: m.index + m[0].length,
1348
- confidence: 0.7
1349
- });
1350
- }
1351
- }
1352
- return matches;
1353
- }
1354
-
1355
- // src/detectors/license-plate.ts
1356
- var LP_CONTEXT_RE = /\b(?:licen[sc]e\s+plate|number\s+plate|registration\s+(?:plate|number)|reg(?:istration)?\s*(?:no\.?|#|:)|plate(?:\s+(?:number|no\.?))?)\s*:?\s*/gi;
1357
- var UK_CURRENT_LP_PATTERN = /\b[A-Z]{2}\d{2}[\s]?[A-Z]{3}\b/gi;
1358
- var UK_OLD_LP_PATTERN = /\b[A-Z]\d{1,4}[\s]?[A-Z]{3}\b/gi;
1359
- var EU_LP_PATTERN = /\b[A-Z]{1,2}[\s-]?\d{1,4}[\s-]?[A-Z]{1,3}\b/gi;
1360
- var US_LP_PATTERN = /\b[A-Z0-9]{2,8}\b/g;
1361
- function detectLicensePlate(text) {
1362
- const matches = [];
1363
- const seen = /* @__PURE__ */ new Set();
1364
- const contextPositions = [];
1365
- const ctxRe = new RegExp(LP_CONTEXT_RE.source, "gi");
1366
- let cm;
1367
- while ((cm = ctxRe.exec(text)) !== null) {
1368
- contextPositions.push(cm.index + cm[0].length);
1369
- }
1370
- function hasContextAt(index) {
1371
- return contextPositions.some((pos) => pos <= index && index - pos <= 20);
1372
- }
1373
- function push(value, start, end, confidence) {
1374
- const key = `${String(start)}-${String(end)}`;
1375
- if (seen.has(key)) return;
1376
- seen.add(key);
1377
- matches.push({ category: "license-plate", value, start, end, confidence });
1378
- }
1379
- let m;
1380
- const ukCurrentRe = new RegExp(UK_CURRENT_LP_PATTERN.source, "gi");
1381
- while ((m = ukCurrentRe.exec(text)) !== null) {
1382
- push(m[0], m.index, m.index + m[0].length, hasContextAt(m.index) ? 0.9 : 0.78);
1383
- }
1384
- const ukOldRe = new RegExp(UK_OLD_LP_PATTERN.source, "gi");
1385
- while ((m = ukOldRe.exec(text)) !== null) {
1386
- push(m[0], m.index, m.index + m[0].length, hasContextAt(m.index) ? 0.85 : 0.7);
1387
- }
1388
- const euRe = new RegExp(EU_LP_PATTERN.source, "gi");
1389
- while ((m = euRe.exec(text)) !== null) {
1390
- const conf = hasContextAt(m.index) ? 0.82 : 0.65;
1391
- if (conf >= 0.7) push(m[0], m.index, m.index + m[0].length, conf);
1392
- }
1393
- const usRe = new RegExp(US_LP_PATTERN.source, "g");
1394
- while ((m = usRe.exec(text)) !== null) {
1395
- if (hasContextAt(m.index)) push(m[0], m.index, m.index + m[0].length, 0.8);
1396
- }
1397
- return matches;
1398
- }
1399
-
1400
- // src/detectors/tracking-number.ts
1401
- var UPS_PATTERN = /\b1Z[A-Z0-9]{16}\b/gi;
1402
- var USPS_LONG_PATTERN = /\b\d{20,22}\b/g;
1403
- var USPS_FORMAT_PATTERN = /\b(?:9[2-5]\d{18,20}|[A-Z]{2}\d{9}US)\b/gi;
1404
- var FEDEX_PATTERN = /\b(?:\d{12}|\d{15}|\d{20,22})\b/g;
1405
- var DHL_PATTERN = /\bJD\d{9}\b|\b\d{10,11}\b/gi;
1406
- var AMAZON_PATTERN = /\bTBA\d{12}\b/gi;
1407
- var TRACKING_CONTEXT_RE = /\b(?:tracking(?:\s+(?:number|no\.?|#|id))?|shipment(?:\s+(?:number|id|tracking))?|parcel(?:\s+(?:number|id))?|package(?:\s+(?:number|id|tracking))?|(?:fedex|ups|usps|dhl|amazon)\s+(?:tracking|shipment)?)\s*:?\s*/gi;
1408
- function detectTrackingNumber(text) {
1409
- const matches = [];
1410
- const seen = /* @__PURE__ */ new Set();
1411
- const contextPositions = [];
1412
- const ctxRe = new RegExp(TRACKING_CONTEXT_RE.source, "gi");
1413
- let cm;
1414
- while ((cm = ctxRe.exec(text)) !== null) {
1415
- contextPositions.push(cm.index + cm[0].length);
1416
- }
1417
- function hasContextAt(index) {
1418
- return contextPositions.some((pos) => pos <= index && index - pos <= 30);
1419
- }
1420
- function push(value, start, end, confidence) {
1421
- const key = `${String(start)}-${String(end)}`;
1422
- if (seen.has(key)) return;
1423
- seen.add(key);
1424
- matches.push({ category: "tracking-number", value, start, end, confidence });
1425
- }
1426
- let m;
1427
- const upsRe = new RegExp(UPS_PATTERN.source, "gi");
1428
- while ((m = upsRe.exec(text)) !== null) {
1429
- push(m[0], m.index, m.index + m[0].length, 0.96);
1430
- }
1431
- const amazonRe = new RegExp(AMAZON_PATTERN.source, "gi");
1432
- while ((m = amazonRe.exec(text)) !== null) {
1433
- push(m[0], m.index, m.index + m[0].length, 0.97);
1434
- }
1435
- const uspsFormatRe = new RegExp(USPS_FORMAT_PATTERN.source, "gi");
1436
- while ((m = uspsFormatRe.exec(text)) !== null) {
1437
- push(m[0], m.index, m.index + m[0].length, 0.9);
1438
- }
1439
- const dhlRe = new RegExp(DHL_PATTERN.source, "gi");
1440
- while ((m = dhlRe.exec(text)) !== null) {
1441
- if (m[0].startsWith("JD") || m[0].startsWith("jd")) {
1442
- push(m[0], m.index, m.index + m[0].length, 0.88);
1443
- } else if (hasContextAt(m.index)) {
1444
- push(m[0], m.index, m.index + m[0].length, 0.78);
1445
- }
1446
- }
1447
- const uspsLongRe = new RegExp(USPS_LONG_PATTERN.source, "g");
1448
- while ((m = uspsLongRe.exec(text)) !== null) {
1449
- if (hasContextAt(m.index)) push(m[0], m.index, m.index + m[0].length, 0.8);
1450
- }
1451
- const fedexRe = new RegExp(FEDEX_PATTERN.source, "g");
1452
- while ((m = fedexRe.exec(text)) !== null) {
1453
- if (hasContextAt(m.index)) push(m[0], m.index, m.index + m[0].length, 0.78);
1454
- }
1455
- return matches;
1456
- }
1457
-
1458
- // src/detectors/case-number.ts
1459
- var FEDERAL_CASE_PATTERN = /\b(?:\d:\s*)?\d{2}[\s-](?:cv|cr|civ|crim|mc|mj|po|br|ap|adv|bk)[\s-]\d{4,6}\b/gi;
1460
- var GENERAL_CASE_PATTERN = /\b(?:[A-Z]{1,4}[-\s])?\d{2,4}[-/]\d{2,6}(?:[-/][A-Z0-9]{1,5})?\b/gi;
1461
- var CASE_CONTEXT_RE = /\b(?:case(?:\s+(?:number|no\.?|#|id))?|docket(?:\s+(?:number|no\.?|#))?|civil\s+action|criminal\s+(?:case|no\.?|#)|court\s+(?:case|file(?:\s+no\.?)?)|matter\s+no\.?|file\s+(?:number|no\.?|#))\s*:?\s*/gi;
1462
- function detectCaseNumber(text) {
1463
- const matches = [];
1464
- const seen = /* @__PURE__ */ new Set();
1465
- const contextPositions = [];
1466
- const ctxRe = new RegExp(CASE_CONTEXT_RE.source, "gi");
1467
- let cm;
1468
- while ((cm = ctxRe.exec(text)) !== null) {
1469
- contextPositions.push(cm.index + cm[0].length);
1470
- }
1471
- function hasContextAt(index) {
1472
- return contextPositions.some((pos) => pos <= index && index - pos <= 30);
1473
- }
1474
- function push(value, start, end, confidence) {
1475
- const key = `${String(start)}-${String(end)}`;
1476
- if (seen.has(key)) return;
1477
- seen.add(key);
1478
- matches.push({ category: "case-number", value, start, end, confidence });
1479
- }
1480
- let m;
1481
- const fedRe = new RegExp(FEDERAL_CASE_PATTERN.source, "gi");
1482
- while ((m = fedRe.exec(text)) !== null) {
1483
- push(m[0], m.index, m.index + m[0].length, hasContextAt(m.index) ? 0.92 : 0.8);
1484
- }
1485
- const generalRe = new RegExp(GENERAL_CASE_PATTERN.source, "gi");
1486
- while ((m = generalRe.exec(text)) !== null) {
1487
- if (hasContextAt(m.index)) push(m[0], m.index, m.index + m[0].length, 0.78);
1488
- }
1489
- return matches;
1490
- }
1491
-
1492
- // src/detectors/company-registration.ts
1493
- var CR_CONTEXT_RE = /\b(?:company\s+(?:registration|reg(?:istration)?)\s*(?:number|no\.?|#)?|companies\s+house\s*(?:number|no\.?|#)?|registered\s+(?:number|company\s+number|no\.?)|incorporation\s*(?:number|no\.?|#)?|company\s+(?:number|no\.?|#)|corporate\s+(?:id|number|no\.?|registration)|business\s+(?:registration|number)|ABN|ACN|CIK)\s*:?\s*/gi;
1494
- var UK_CH_PATTERN = /\b(?:[A-Z]{2}\d{6}|\d{8})\b/gi;
1495
- var US_EIN_PATTERN2 = /\b\d{2}-\d{7}\b/g;
1496
- var AU_ACN_PATTERN = /\b\d{3}[\s]?\d{3}[\s]?\d{3}\b/g;
1497
- var EU_CO_REG_PATTERN = /\b[A-Z]{2}[\s-]?[A-Z0-9]{5,12}\b/g;
1498
- function detectCompanyRegistration(text) {
1499
- const matches = [];
1500
- const seen = /* @__PURE__ */ new Set();
1501
- const contextPositions = [];
1502
- const ctxRe = new RegExp(CR_CONTEXT_RE.source, "gi");
1503
- let cm;
1504
- while ((cm = ctxRe.exec(text)) !== null) {
1505
- contextPositions.push(cm.index + cm[0].length);
1506
- }
1507
- function hasContextAt(index) {
1508
- return contextPositions.some((pos) => pos <= index && index - pos <= 30);
1509
- }
1510
- function push(value, start, end, confidence) {
1511
- const key = `${String(start)}-${String(end)}`;
1512
- if (seen.has(key)) return;
1513
- seen.add(key);
1514
- matches.push({ category: "company-registration", value, start, end, confidence });
1515
- }
1516
- let m;
1517
- const einRe = new RegExp(US_EIN_PATTERN2.source, "g");
1518
- while ((m = einRe.exec(text)) !== null) {
1519
- push(m[0], m.index, m.index + m[0].length, hasContextAt(m.index) ? 0.88 : 0.72);
1520
- }
1521
- const ukRe = new RegExp(UK_CH_PATTERN.source, "gi");
1522
- while ((m = ukRe.exec(text)) !== null) {
1523
- if (hasContextAt(m.index)) push(m[0], m.index, m.index + m[0].length, 0.85);
1524
- }
1525
- const acnRe = new RegExp(AU_ACN_PATTERN.source, "g");
1526
- while ((m = acnRe.exec(text)) !== null) {
1527
- if (hasContextAt(m.index)) push(m[0], m.index, m.index + m[0].length, 0.82);
1528
- }
1529
- const euRe = new RegExp(EU_CO_REG_PATTERN.source, "g");
1530
- while ((m = euRe.exec(text)) !== null) {
1531
- if (hasContextAt(m.index)) push(m[0], m.index, m.index + m[0].length, 0.78);
1532
- }
1533
- return matches;
1534
- }
1535
-
1536
- // src/detectors/index.ts
1537
- var DETECTOR_REGISTRY = {
1538
- // Original
1539
- email: detectEmail,
1540
- phone: detectPhone,
1541
- ssn: detectSsn,
1542
- "credit-card": detectCreditCard,
1543
- ipv4: detectIpv4,
1544
- ipv6: detectIpv6,
1545
- url: detectUrl,
1546
- iban: detectIban,
1547
- "date-of-birth": detectDateOfBirth,
1548
- name: detectName,
1549
- // Personal Information
1550
- address: detectAddress,
1551
- passport: detectPassport,
1552
- "drivers-license": detectDriversLicense,
1553
- "national-id": detectNationalId,
1554
- // Financial
1555
- "bank-account": detectBankAccount,
1556
- cryptocurrency: detectCryptocurrency,
1557
- "tax-id": detectTaxId,
1558
- // Healthcare
1559
- "medical-record": detectMedicalRecord,
1560
- "health-insurance": detectHealthInsurance,
1561
- prescription: detectPrescription,
1562
- // Digital Identity
1563
- "api-key": detectApiKey,
1564
- "social-media": detectSocialMedia,
1565
- // Vehicles & Transportation
1566
- vin: detectVin,
1567
- "license-plate": detectLicensePlate,
1568
- "tracking-number": detectTrackingNumber,
1569
- // Government & Legal
1570
- "case-number": detectCaseNumber,
1571
- "company-registration": detectCompanyRegistration
1572
- };
1573
- var AGGRESSIVE_DETECTOR_REGISTRY = {
1574
- // Original (aggressive variants where available)
1575
- email: detectEmailAggressive,
1576
- phone: detectPhoneAggressive,
1577
- ssn: detectSsnAggressive,
1578
- "credit-card": detectCreditCardAggressive,
1579
- ipv4: detectIpv4,
1580
- ipv6: detectIpv6,
1581
- url: detectUrl,
1582
- iban: detectIban,
1583
- "date-of-birth": detectDateOfBirth,
1584
- name: detectNameAggressive,
1585
- // Personal Information
1586
- address: detectAddress,
1587
- passport: detectPassport,
1588
- "drivers-license": detectDriversLicense,
1589
- "national-id": detectNationalId,
1590
- // Financial
1591
- "bank-account": detectBankAccount,
1592
- cryptocurrency: detectCryptocurrency,
1593
- "tax-id": detectTaxId,
1594
- // Healthcare
1595
- "medical-record": detectMedicalRecord,
1596
- "health-insurance": detectHealthInsurance,
1597
- prescription: detectPrescription,
1598
- // Digital Identity
1599
- "api-key": detectApiKey,
1600
- "social-media": detectSocialMedia,
1601
- // Vehicles & Transportation
1602
- vin: detectVinAggressive,
1603
- "license-plate": detectLicensePlate,
1604
- "tracking-number": detectTrackingNumber,
1605
- // Government & Legal
1606
- "case-number": detectCaseNumber,
1607
- "company-registration": detectCompanyRegistration
1608
- };
1609
-
1610
- // src/strategies/tokenize.ts
1611
- function createTokenStore() {
1612
- return {
1613
- tokens: /* @__PURE__ */ new Map(),
1614
- index: /* @__PURE__ */ new Map(),
1615
- counters: /* @__PURE__ */ new Map()
1616
- };
1617
- }
1618
- function assignToken(store, category, value, prefix, format = "bracket") {
1619
- const indexKey = `${prefix}:${value.toLowerCase()}`;
1620
- const existing = store.index.get(indexKey);
1621
- if (existing !== void 0) return existing;
1622
- const count = (store.counters.get(prefix) ?? 0) + 1;
1623
- store.counters.set(prefix, count);
1624
- const id = format === "bracket" ? String(count).padStart(4, "0") : String(count);
1625
- const token = format === "bracket" ? `[${prefix}_${id}]` : `<${prefix}_${id}>`;
1626
- store.index.set(indexKey, token);
1627
- store.tokens.set(token, value);
1628
- return token;
1629
- }
1630
- function detokenizeText(text, store) {
1631
- const unresolved = [];
1632
- const re = /(\[[A-Z_]+_\d+\]|<[A-Z_]+_\d+>)/g;
1633
- const result = text.replace(re, (token) => {
1634
- const original = store.tokens.get(token);
1635
- if (original !== void 0) return original;
1636
- unresolved.push(token);
1637
- return token;
1638
- });
1639
- return { text: result, unresolved };
1640
- }
1641
-
1642
- // src/strategies/mask.ts
1643
- init_errors();
1644
- function mask(value, options = {}) {
1645
- const { maskChar = "*", keepLeading = 0, keepTrailing = 0, preserveFormat = false } = options;
1646
- if (maskChar.length !== 1) {
1647
- throw new ValidationError("maskChar", "must be exactly one character");
1648
- }
1649
- if (!Number.isInteger(keepLeading) || keepLeading < 0) {
1650
- throw new ValidationError("keepLeading", "must be a non-negative integer");
1651
- }
1652
- if (!Number.isInteger(keepTrailing) || keepTrailing < 0) {
1653
- throw new ValidationError("keepTrailing", "must be a non-negative integer");
1654
- }
1655
- if (value.length === 0) return value;
1656
- if (preserveFormat) {
1657
- const totalVisible2 = keepLeading + keepTrailing;
1658
- if (totalVisible2 >= value.length) {
1659
- return value;
1660
- }
1661
- const chars = value.split("");
1662
- const interior = chars.slice(keepLeading, value.length - (keepTrailing > 0 ? keepTrailing : 0));
1663
- const maskedInterior = interior.map((ch) => {
1664
- if (/[a-zA-Z]/.test(ch)) return ch === ch.toUpperCase() ? "X" : "x";
1665
- if (/\d/.test(ch)) return "0";
1666
- return ch;
1667
- });
1668
- return chars.slice(0, keepLeading).join("") + maskedInterior.join("") + (keepTrailing > 0 ? chars.slice(-keepTrailing).join("") : "");
1669
- }
1670
- const totalVisible = keepLeading + keepTrailing;
1671
- if (totalVisible >= value.length) {
1672
- return maskChar.repeat(value.length);
1673
- }
1674
- const leading = value.slice(0, keepLeading);
1675
- const trailing = keepTrailing > 0 ? value.slice(-keepTrailing) : "";
1676
- const maskedLength = value.length - keepLeading - keepTrailing;
1677
- return leading + maskChar.repeat(maskedLength) + trailing;
1678
- }
1679
-
1680
- // src/strategies/redact.ts
1681
- init_errors();
1682
- function redact(value, options = {}) {
1683
- const { label = "[REDACTED]" } = options;
1684
- if (label.trim().length === 0) {
1685
- throw new ValidationError("label", "must not be an empty string");
1686
- }
1687
- return label;
1688
- }
1689
-
1690
- // src/strategies/pseudonymize.ts
1691
- init_errors();
1692
- function djb2(str) {
1693
- let hash2 = 5381;
1694
- for (let i = 0; i < str.length; i++) {
1695
- hash2 = (hash2 << 5) + hash2 ^ str.charCodeAt(i);
1696
- hash2 = hash2 >>> 0;
1697
- }
1698
- return hash2;
1699
- }
1700
- function toHex8(n) {
1701
- return (n >>> 0).toString(16).padStart(8, "0");
1702
- }
1703
- function pseudonymize(value, options = {}) {
1704
- const { seed, prefix = "id_" } = options;
1705
- if (/\s/.test(prefix)) {
1706
- throw new ValidationError("prefix", "must not contain whitespace characters");
1707
- }
1708
- if (seed !== void 0) {
1709
- const combined = `${seed}:${value}`;
1710
- const h1 = djb2(combined);
1711
- const h2 = djb2(`${combined}:v2`);
1712
- return `${prefix}${toHex8(h1)}${toHex8(h2)}`;
1713
- }
1714
- if (typeof globalThis.crypto !== "undefined" && typeof globalThis.crypto.getRandomValues === "function") {
1715
- const bytes = new Uint8Array(8);
1716
- globalThis.crypto.getRandomValues(bytes);
1717
- const hex = Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
1718
- return `${prefix}${hex}`;
1719
- }
1720
- const fallback = Math.floor(Math.random() * 4294967295);
1721
- return `${prefix}${toHex8(fallback)}`;
1722
- }
1723
-
1724
- // src/strategies/generalize.ts
1725
- init_errors();
1726
- function generalize(value, options = {}) {
1727
- const { bucketSize = 10 } = options;
1728
- if (!Number.isInteger(bucketSize) || bucketSize < 1) {
1729
- throw new ValidationError("bucketSize", "must be a positive integer");
1730
- }
1731
- const parsed = Number(value);
1732
- if (!Number.isFinite(parsed)) {
1733
- return value;
1734
- }
1735
- const n = Math.floor(parsed);
1736
- const low = Math.floor(n / bucketSize) * bucketSize;
1737
- const high = low + bucketSize - 1;
1738
- return `${String(low)}-${String(high)}`;
1739
- }
1740
-
1741
- // src/anonymize.ts
1742
- init_errors();
1743
-
1744
- // src/presets.ts
1745
- init_errors();
1746
- var GDPR_PRESET = {
1747
- name: "gdpr",
1748
- description: "EU General Data Protection Regulation \u2014 Covers all categories of personal data that can identify a natural person.",
1749
- categories: [
1750
- "name",
1751
- "email",
1752
- "phone",
1753
- "address",
1754
- "date-of-birth",
1755
- "ssn",
1756
- "national-id",
1757
- "passport",
1758
- "drivers-license",
1759
- "iban",
1760
- "bank-account",
1761
- "credit-card",
1762
- "ipv4",
1763
- "ipv6",
1764
- "url",
1765
- "medical-record",
1766
- "health-insurance",
1767
- "prescription",
1768
- "social-media",
1769
- "cryptocurrency",
1770
- "tax-id"
1771
- ],
1772
- defaultStrategy: { strategy: "pseudonymize" }
1773
- };
1774
- var HIPAA_PRESET = {
1775
- name: "hipaa",
1776
- description: "US HIPAA Safe Harbor \u2014 Covers all 18 protected health information (PHI) identifiers to de-identify medical records.",
1777
- categories: [
1778
- "name",
1779
- "address",
1780
- "date-of-birth",
1781
- "phone",
1782
- "email",
1783
- "ssn",
1784
- "medical-record",
1785
- "health-insurance",
1786
- "prescription",
1787
- "bank-account",
1788
- "drivers-license",
1789
- "vin",
1790
- "url",
1791
- "ipv4",
1792
- "ipv6",
1793
- "national-id",
1794
- "tax-id",
1795
- "company-registration"
1796
- ],
1797
- defaultStrategy: { strategy: "redact" }
1798
- };
1799
- var CCPA_PRESET = {
1800
- name: "ccpa",
1801
- description: "California Consumer Privacy Act \u2014 Covers personal information categories defined by CCPA, including identifiers, financial data, and online activity.",
1802
- categories: [
1803
- "name",
1804
- "email",
1805
- "phone",
1806
- "address",
1807
- "ssn",
1808
- "national-id",
1809
- "passport",
1810
- "drivers-license",
1811
- "bank-account",
1812
- "credit-card",
1813
- "tax-id",
1814
- "ipv4",
1815
- "ipv6",
1816
- "url",
1817
- "social-media",
1818
- "date-of-birth"
1819
- ],
1820
- defaultStrategy: { strategy: "redact" }
1821
- };
1822
- var PCI_DSS_PRESET = {
1823
- name: "pci-dss",
1824
- description: "PCI-DSS Cardholder Data \u2014 Covers credit/debit card numbers, bank accounts, and associated cardholder identifiers.",
1825
- categories: [
1826
- "credit-card",
1827
- "bank-account",
1828
- "name",
1829
- "address",
1830
- "email",
1831
- "phone"
1832
- ],
1833
- defaultStrategy: { strategy: "redact" },
1834
- rules: [
1835
- {
1836
- category: "credit-card",
1837
- strategy: { strategy: "mask", keepTrailing: 4 }
1838
- },
1839
- {
1840
- category: "bank-account",
1841
- strategy: { strategy: "mask", keepTrailing: 4 }
1842
- }
1843
- ]
1844
- };
1845
- var SOX_PRESET = {
1846
- name: "sox",
1847
- description: "Sarbanes-Oxley Act \u2014 Covers financial records, corporate officer identifiers, and audit trail data.",
1848
- categories: [
1849
- "name",
1850
- "email",
1851
- "tax-id",
1852
- "bank-account",
1853
- "company-registration",
1854
- "ssn",
1855
- "address",
1856
- "phone"
1857
- ],
1858
- defaultStrategy: { strategy: "redact" }
1859
- };
1860
- var FERPA_PRESET = {
1861
- name: "ferpa",
1862
- description: "FERPA \u2014 Covers education records and student personally identifiable information (PII).",
1863
- categories: [
1864
- "name",
1865
- "email",
1866
- "phone",
1867
- "address",
1868
- "date-of-birth",
1869
- "ssn",
1870
- "national-id"
1871
- ],
1872
- defaultStrategy: { strategy: "redact" }
1873
- };
1874
- var PRESET_REGISTRY = {
1875
- gdpr: GDPR_PRESET,
1876
- hipaa: HIPAA_PRESET,
1877
- ccpa: CCPA_PRESET,
1878
- "pci-dss": PCI_DSS_PRESET,
1879
- sox: SOX_PRESET,
1880
- ferpa: FERPA_PRESET
1881
- };
1882
- function getPreset(name) {
1883
- const preset = PRESET_REGISTRY[name];
1884
- if (preset === void 0) {
1885
- throw new PresetNotFoundError(name);
1886
- }
1887
- return preset;
1888
- }
1889
-
1890
- // src/anonymize.ts
1891
- var ALL_CATEGORIES = [
1892
- "email",
1893
- "phone",
1894
- "ssn",
1895
- "credit-card",
1896
- "ipv4",
1897
- "ipv6",
1898
- "url",
1899
- "iban",
1900
- "date-of-birth",
1901
- "name",
1902
- "address",
1903
- "passport",
1904
- "drivers-license",
1905
- "national-id",
1906
- "bank-account",
1907
- "cryptocurrency",
1908
- "tax-id",
1909
- "medical-record",
1910
- "health-insurance",
1911
- "prescription",
1912
- "api-key",
1913
- "social-media",
1914
- "vin",
1915
- "license-plate",
1916
- "tracking-number",
1917
- "case-number",
1918
- "company-registration"
1919
- ];
1920
- var TOKEN_PREFIX_MAP = {
1921
- email: "EMAIL",
1922
- phone: "PHONE",
1923
- ssn: "SSN",
1924
- "credit-card": "CREDIT_CARD",
1925
- ipv4: "IPV4",
1926
- ipv6: "IPV6",
1927
- url: "URL",
1928
- iban: "IBAN",
1929
- "date-of-birth": "DATE",
1930
- name: "PERSON",
1931
- address: "ADDRESS",
1932
- passport: "PASSPORT",
1933
- "drivers-license": "DRIVERS_LICENSE",
1934
- "national-id": "NATIONAL_ID",
1935
- "bank-account": "BANK_ACCOUNT",
1936
- cryptocurrency: "CRYPTO",
1937
- "tax-id": "TAX_ID",
1938
- "medical-record": "MEDICAL_RECORD",
1939
- "health-insurance": "HEALTH_INSURANCE",
1940
- prescription: "PRESCRIPTION",
1941
- "api-key": "API_KEY",
1942
- "social-media": "SOCIAL_MEDIA",
1943
- vin: "VIN",
1944
- "license-plate": "LICENSE_PLATE",
1945
- "tracking-number": "TRACKING_NUMBER",
1946
- "case-number": "CASE_NUMBER",
1947
- "company-registration": "COMPANY_REG"
1948
- };
1949
- function applyStrategySync(value, opts) {
1950
- switch (opts.strategy) {
1951
- case "mask":
1952
- return mask(value, opts);
1953
- case "redact":
1954
- return redact(value, opts);
1955
- case "pseudonymize":
1956
- return pseudonymize(value, opts);
1957
- case "hash":
1958
- console.warn(
1959
- "[anonyma] The `hash` strategy is async and cannot be used in the synchronous `anonymize()` pipeline. Falling back to a deterministic pseudonym. Use `hash()` directly if you need true SHA-256 output."
1960
- );
1961
- return pseudonymize(value, { seed: opts.pepper ?? "__hash_fallback__", prefix: "hsh_" });
1962
- case "generalize":
1963
- return generalize(value, opts);
1964
- case "tokenize":
1965
- case "encrypt":
1966
- case "synthesize":
1967
- console.warn(
1968
- `[anonyma] The \`${opts.strategy}\` strategy requires async execution. Falling back to redact in the synchronous pipeline. Use anonymizeAsync() instead.`
1969
- );
1970
- return redact();
1971
- default: {
1972
- const _exhaustive = opts;
1973
- throw new UnsupportedStrategyError(_exhaustive.strategy);
1974
- }
1975
- }
1976
- }
1977
- function deduplicateMatches(matches) {
1978
- const sorted = [...matches].sort(
1979
- (a, b) => a.start - b.start || b.confidence - a.confidence
1980
- );
1981
- const result = [];
1982
- let cursor = 0;
1983
- for (const m of sorted) {
1984
- if (m.start >= cursor) {
1985
- result.push(m);
1986
- cursor = m.end;
1987
- }
1988
- }
1989
- return result;
1990
- }
1991
- function resolveDetector(category, customDetectors, aggressive) {
1992
- if (customDetectors?.[category]) return customDetectors[category];
1993
- return aggressive ? AGGRESSIVE_DETECTOR_REGISTRY[category] : DETECTOR_REGISTRY[category];
1994
- }
1995
- function detectCustomPatterns(text, customPatterns) {
1996
- const results = [];
1997
- for (const cp of customPatterns) {
1998
- if (!(cp.pattern instanceof RegExp)) {
1999
- throw new ValidationError("customPatterns[].pattern", "must be a RegExp instance");
2000
- }
2001
- const flags = cp.pattern.flags.includes("g") ? cp.pattern.flags : cp.pattern.flags + "g";
2002
- const re = new RegExp(cp.pattern.source, flags);
2003
- const category = cp.category ?? "custom";
2004
- const confidence = cp.confidence ?? 0.85;
2005
- const label = cp.label ?? "[REDACTED]";
2006
- let m;
2007
- while ((m = re.exec(text)) !== null) {
2008
- results.push({
2009
- category,
2010
- value: m[0],
2011
- start: m.index,
2012
- end: m.index + m[0].length,
2013
- confidence,
2014
- replacement: label
2015
- });
2016
- }
2017
- }
2018
- return results;
2019
- }
2020
- function resolveCategories(options) {
2021
- const { rules = [], enabledCategories } = options;
2022
- if (rules.length > 0) {
2023
- return rules.map((r) => r.category);
2024
- }
2025
- if (enabledCategories) {
2026
- return ALL_CATEGORIES.filter((cat) => enabledCategories[cat] === true);
2027
- }
2028
- return [...ALL_CATEGORIES];
2029
- }
2030
- function detect(text, categories = ALL_CATEGORIES, customDetectors, aggressive) {
2031
- if (typeof text !== "string") {
2032
- throw new ValidationError("text", "must be a string");
2033
- }
2034
- const raw = [];
2035
- for (const category of categories) {
2036
- if (!ALL_CATEGORIES.includes(category)) {
2037
- throw new UnknownCategoryError(category);
2038
- }
2039
- const detector = resolveDetector(category, customDetectors, aggressive);
2040
- raw.push(...detector(text));
2041
- }
2042
- return deduplicateMatches(raw);
2043
- }
2044
- function hasPII(text, categories = ALL_CATEGORIES, customDetectors) {
2045
- if (typeof text !== "string") {
2046
- throw new ValidationError("text", "must be a string");
2047
- }
2048
- for (const category of categories) {
2049
- if (!ALL_CATEGORIES.includes(category)) {
2050
- throw new UnknownCategoryError(category);
2051
- }
2052
- const detector = resolveDetector(category, customDetectors);
2053
- if (detector(text).length > 0) return true;
2054
- }
2055
- return false;
2056
- }
2057
- function anonymize(text, options = {}) {
2058
- if (typeof text !== "string") {
2059
- throw new ValidationError("text", "must be a string");
2060
- }
2061
- if (options.globalReplacement?.trim().length === 0) {
2062
- throw new ValidationError("globalReplacement", "must not be an empty string");
2063
- }
2064
- let resolvedPreset;
2065
- if (options.preset) {
2066
- try {
2067
- resolvedPreset = getPreset(options.preset);
2068
- } catch {
2069
- throw new PresetNotFoundError(options.preset);
2070
- }
2071
- }
2072
- const {
2073
- rules = resolvedPreset ? resolvedPreset.categories.map((category) => ({
2074
- category,
2075
- strategy: resolvedPreset.rules?.find((r) => r.category === category)?.strategy ?? resolvedPreset.defaultStrategy
2076
- })) : [],
2077
- defaultStrategy = resolvedPreset?.defaultStrategy ?? { strategy: "redact" },
2078
- includeMatches = false,
2079
- customDetectors,
2080
- customPatterns = [],
2081
- globalReplacement,
2082
- consistentTokens = false,
2083
- aggressive = false,
2084
- enabledCategories,
2085
- allowlist = [],
2086
- allowlistPatterns = [],
2087
- allowlistCaseSensitive = false,
2088
- confidenceThreshold = 0
2089
- } = options;
2090
- const ruleMap = /* @__PURE__ */ new Map();
2091
- for (const rule of rules) {
2092
- if (!ALL_CATEGORIES.includes(rule.category)) {
2093
- throw new UnknownCategoryError(rule.category);
2094
- }
2095
- ruleMap.set(rule.category, rule.strategy);
2096
- }
2097
- const categories = resolveCategories({
2098
- rules,
2099
- ...enabledCategories !== void 0 ? { enabledCategories } : {}
2100
- });
2101
- const compiledAllowlistPatterns = [
2102
- ...allowlistPatterns,
2103
- ...allowlist.map(
2104
- (entry) => new RegExp(
2105
- entry.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"),
2106
- allowlistCaseSensitive ? "" : "i"
2107
- )
2108
- )
2109
- ];
2110
- function isAllowlisted(value) {
2111
- if (compiledAllowlistPatterns.length === 0) return false;
2112
- return compiledAllowlistPatterns.some((re) => re.test(value));
2113
- }
2114
- const builtInMatches = detect(text, categories, customDetectors, aggressive);
2115
- const customMatches = customPatterns.length > 0 ? detectCustomPatterns(text, customPatterns) : [];
2116
- const filteredBuiltInMatches = builtInMatches.filter(
2117
- (m) => m.confidence >= confidenceThreshold && !isAllowlisted(m.value)
2118
- );
2119
- const allRaw = [...filteredBuiltInMatches, ...customMatches];
2120
- const allDeduped = deduplicateMatches(allRaw);
2121
- const tokenMap = /* @__PURE__ */ new Map();
2122
- const tokenCounters = /* @__PURE__ */ new Map();
2123
- function assignToken2(category, value) {
2124
- const prefix = TOKEN_PREFIX_MAP[category] ?? category.toUpperCase();
2125
- const key = `${prefix}:${value.toLowerCase()}`;
2126
- const existing = tokenMap.get(key);
2127
- if (existing) return existing;
2128
- const count = (tokenCounters.get(prefix) ?? 0) + 1;
2129
- tokenCounters.set(prefix, count);
2130
- const token = `${prefix}_${String(count)}`;
2131
- tokenMap.set(key, token);
2132
- return token;
2133
- }
2134
- let result = text;
2135
- const reversed = [...allDeduped].reverse();
2136
- for (const match of reversed) {
2137
- let replacement;
2138
- if (globalReplacement !== void 0) {
2139
- replacement = globalReplacement;
2140
- } else if (consistentTokens) {
2141
- replacement = assignToken2(match.category, match.value);
2142
- } else if ("replacement" in match) {
2143
- replacement = match.replacement;
2144
- } else {
2145
- const strategy = ruleMap.get(match.category) ?? defaultStrategy;
2146
- replacement = applyStrategySync(match.value, strategy);
2147
- }
2148
- result = result.slice(0, match.start) + replacement + result.slice(match.end);
2149
- }
2150
- const reportedMatches = includeMatches ? filteredBuiltInMatches : [];
2151
- return {
2152
- text: result,
2153
- matches: reportedMatches
2154
- };
2155
- }
2156
- async function anonymizeAsync(text, options = {}) {
2157
- if (typeof text !== "string") {
2158
- throw new ValidationError("text", "must be a string");
2159
- }
2160
- const hasAsyncStrategy = (opts) => opts.strategy === "hash" || opts.strategy === "encrypt" || opts.strategy === "tokenize" || opts.strategy === "synthesize";
2161
- const needsAsync = options.defaultStrategy != null && hasAsyncStrategy(options.defaultStrategy) || (options.rules ?? []).some((r) => hasAsyncStrategy(r.strategy));
2162
- if (!needsAsync) {
2163
- return anonymize(text, options);
2164
- }
2165
- const { hash: hashFn } = await Promise.resolve().then(() => (init_hash(), hash_exports));
2166
- let resolvedPreset;
2167
- if (options.preset) {
2168
- try {
2169
- resolvedPreset = getPreset(options.preset);
2170
- } catch {
2171
- throw new PresetNotFoundError(options.preset);
2172
- }
2173
- }
2174
- const {
2175
- rules = resolvedPreset ? resolvedPreset.categories.map((category) => ({
2176
- category,
2177
- strategy: resolvedPreset.rules?.find((r) => r.category === category)?.strategy ?? resolvedPreset.defaultStrategy
2178
- })) : [],
2179
- defaultStrategy = resolvedPreset?.defaultStrategy ?? { strategy: "redact" },
2180
- includeMatches = false,
2181
- customDetectors,
2182
- customPatterns = [],
2183
- globalReplacement,
2184
- consistentTokens = false,
2185
- aggressive = false,
2186
- enabledCategories,
2187
- allowlist = [],
2188
- allowlistPatterns = [],
2189
- allowlistCaseSensitive = false,
2190
- confidenceThreshold = 0
2191
- } = options;
2192
- const ruleMap = /* @__PURE__ */ new Map();
2193
- for (const rule of rules) {
2194
- if (!ALL_CATEGORIES.includes(rule.category)) throw new UnknownCategoryError(rule.category);
2195
- ruleMap.set(rule.category, rule.strategy);
2196
- }
2197
- const categories = resolveCategories({
2198
- rules,
2199
- ...enabledCategories !== void 0 ? { enabledCategories } : {}
2200
- });
2201
- const builtInMatches = detect(text, categories, customDetectors, aggressive);
2202
- const customMatches = customPatterns.length > 0 ? detectCustomPatterns(text, customPatterns) : [];
2203
- const compiledAllowlistPatterns = [
2204
- ...allowlistPatterns,
2205
- ...allowlist.map(
2206
- (entry) => new RegExp(
2207
- entry.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"),
2208
- allowlistCaseSensitive ? "" : "i"
2209
- )
2210
- )
2211
- ];
2212
- const isAllowlisted = (value) => compiledAllowlistPatterns.some((re) => re.test(value));
2213
- const filteredBuiltInMatches = builtInMatches.filter(
2214
- (m) => m.confidence >= confidenceThreshold && !isAllowlisted(m.value)
2215
- );
2216
- const allRaw = [...filteredBuiltInMatches, ...customMatches];
2217
- const allDeduped = deduplicateMatches(allRaw);
2218
- const tokenMap = /* @__PURE__ */ new Map();
2219
- const tokenCounters = /* @__PURE__ */ new Map();
2220
- function assignToken2(category, value) {
2221
- const prefix = TOKEN_PREFIX_MAP[category] ?? category.toUpperCase();
2222
- const key = `${prefix}:${value.toLowerCase()}`;
2223
- const existing = tokenMap.get(key);
2224
- if (existing) return existing;
2225
- const count = (tokenCounters.get(prefix) ?? 0) + 1;
2226
- tokenCounters.set(prefix, count);
2227
- const token = `${prefix}_${String(count)}`;
2228
- tokenMap.set(key, token);
2229
- return token;
2230
- }
2231
- let result = text;
2232
- const reversed = [...allDeduped].reverse();
2233
- for (const match of reversed) {
2234
- let replacement;
2235
- if (globalReplacement !== void 0) {
2236
- replacement = globalReplacement;
2237
- } else if (consistentTokens) {
2238
- replacement = assignToken2(match.category, match.value);
2239
- } else if ("replacement" in match) {
2240
- replacement = match.replacement;
2241
- } else {
2242
- const strategy = ruleMap.get(match.category) ?? defaultStrategy;
2243
- if (strategy.strategy === "hash") {
2244
- replacement = await hashFn(match.value, strategy);
2245
- } else {
2246
- replacement = applyStrategySync(match.value, strategy);
2247
- }
2248
- }
2249
- result = result.slice(0, match.start) + replacement + result.slice(match.end);
2250
- }
2251
- return {
2252
- text: result,
2253
- matches: includeMatches ? filteredBuiltInMatches : []
2254
- };
2255
- }
2256
- function anonymizeObject(obj, options) {
2257
- if (typeof obj !== "object") {
2258
- throw new ValidationError("obj", "must be an object");
2259
- }
2260
- return deepAnonymizeValue(obj, options, /* @__PURE__ */ new WeakSet());
2261
- }
2262
- function deepAnonymizeValue(value, options, seen) {
2263
- if (value === null || value === void 0) return value;
2264
- if (typeof value === "string") {
2265
- return anonymize(value, options).text;
2266
- }
2267
- if (typeof value !== "object") {
2268
- return value;
2269
- }
2270
- if (seen.has(value)) {
2271
- throw new ValidationError("obj", "contains a circular reference");
2272
- }
2273
- seen.add(value);
2274
- if (Array.isArray(value)) {
2275
- const result2 = value.map((item) => deepAnonymizeValue(item, options, seen));
2276
- seen.delete(value);
2277
- return result2;
2278
- }
2279
- const result = {};
2280
- for (const key of Object.keys(value)) {
2281
- result[key] = deepAnonymizeValue(
2282
- value[key],
2283
- options,
2284
- seen
2285
- );
2286
- }
2287
- seen.delete(value);
2288
- return result;
2289
- }
2290
- function getByPath(obj, path) {
2291
- const parts = path.split(".");
2292
- let current = obj;
2293
- for (const part of parts) {
2294
- if (current === null || typeof current !== "object" || Array.isArray(current)) {
2295
- return void 0;
2296
- }
2297
- current = current[part];
2298
- }
2299
- return current;
2300
- }
2301
- function setByPath(obj, path, value) {
2302
- const parts = path.split(".");
2303
- if (parts.length === 1) {
2304
- return { ...obj, [path]: value };
2305
- }
2306
- const [head, ...tail] = parts;
2307
- const nested = obj[head] ?? {};
2308
- return {
2309
- ...obj,
2310
- [head]: setByPath(nested, tail.join("."), value)
2311
- };
2312
- }
2313
- function anonymizeRecord(record, rules) {
2314
- if (typeof record !== "object" || Array.isArray(record)) {
2315
- throw new ValidationError("record", "must be a plain object");
2316
- }
2317
- let result = { ...record };
2318
- for (const [path, rule] of Object.entries(rules)) {
2319
- if (Object.prototype.hasOwnProperty.call(rules, path)) {
2320
- const raw = getByPath(result, path);
2321
- if (raw === void 0 || raw === null) continue;
2322
- if (typeof raw !== "string" && typeof raw !== "number" && typeof raw !== "boolean") continue;
2323
- const strValue = String(raw);
2324
- const anonymized = applyStrategySync(strValue, rule.strategy);
2325
- result = setByPath(result, path, anonymized);
2326
- }
2327
- }
2328
- return result;
2329
- }
2330
- function createAnonymizer(config = {}) {
2331
- let presetConfig;
2332
- if (config.preset) {
2333
- try {
2334
- presetConfig = getPreset(config.preset);
2335
- } catch {
2336
- throw new PresetNotFoundError(config.preset);
2337
- }
2338
- }
2339
- const {
2340
- categories = presetConfig ? presetConfig.categories : [...ALL_CATEGORIES],
2341
- defaultStrategy = presetConfig?.defaultStrategy ?? { strategy: "redact" },
2342
- customDetectors,
2343
- customPatterns,
2344
- globalReplacement,
2345
- consistentTokens,
2346
- aggressive
2347
- } = config;
2348
- for (const cat of categories) {
2349
- if (!ALL_CATEGORIES.includes(cat)) {
2350
- throw new UnknownCategoryError(cat);
2351
- }
2352
- }
2353
- function baseOptions(overrides) {
2354
- const base = {
2355
- defaultStrategy,
2356
- ...customDetectors !== void 0 ? { customDetectors } : {},
2357
- ...customPatterns !== void 0 ? { customPatterns } : {},
2358
- ...globalReplacement !== void 0 ? { globalReplacement } : {},
2359
- ...consistentTokens !== void 0 ? { consistentTokens } : {},
2360
- ...aggressive !== void 0 ? { aggressive } : {},
2361
- ...overrides,
2362
- rules: overrides?.rules ?? (presetConfig ? presetConfig.categories.map((category) => ({
2363
- category,
2364
- strategy: presetConfig.rules?.find((r) => r.category === category)?.strategy ?? defaultStrategy
2365
- })) : categories.map((category) => ({
2366
- category,
2367
- strategy: defaultStrategy
2368
- })))
2369
- };
2370
- return base;
2371
- }
2372
- return {
2373
- anonymize(text, options) {
2374
- return anonymize(text, baseOptions(options));
2375
- },
2376
- detect(text) {
2377
- return detect(text, categories, customDetectors, aggressive);
2378
- },
2379
- anonymizeRecord(record, rules) {
2380
- return anonymizeRecord(record, rules);
2381
- },
2382
- anonymizeObject(obj, options) {
2383
- return anonymizeObject(obj, baseOptions(options));
2384
- },
2385
- async anonymizeAsync(text, options) {
2386
- return anonymizeAsync(text, baseOptions(options));
2387
- },
2388
- tokenize(text, options) {
2389
- const {
2390
- categories: tCats,
2391
- format = "bracket",
2392
- customDetectors: tCustDet,
2393
- aggressive: tAgg = aggressive,
2394
- confidenceThreshold: tConfidence = 0,
2395
- allowlist: tAllowlist = [],
2396
- allowlistCaseSensitive: tCaseSensitive = false
2397
- } = options ?? {};
2398
- const tCompiledAllowlist = tAllowlist.map(
2399
- (entry) => new RegExp(entry.replace(/[.*+?^${}()|[\\]\\]/g, "\\$&"), tCaseSensitive ? "" : "i")
2400
- );
2401
- const isAllowlisted = (v) => tCompiledAllowlist.some((re) => re.test(v));
2402
- const tMatches = detect(text, tCats ?? categories, tCustDet ?? customDetectors, tAgg).filter(
2403
- (m) => m.confidence >= tConfidence && !isAllowlisted(m.value)
2404
- );
2405
- const store = createTokenStore();
2406
- let tResult = text;
2407
- const tTokens = [];
2408
- for (const match of [...tMatches].reverse()) {
2409
- const prefix = TOKEN_PREFIX_MAP[match.category];
2410
- const token = assignToken(store, match.category, match.value, prefix, format);
2411
- tTokens.push({
2412
- token,
2413
- original: match.value,
2414
- category: match.category,
2415
- start: match.start,
2416
- end: match.end
2417
- });
2418
- tResult = tResult.slice(0, match.start) + token + tResult.slice(match.end);
2419
- }
2420
- return { text: tResult, mapping: store.tokens, tokens: tTokens };
2421
- },
2422
- hasPII(text) {
2423
- return hasPII(text, categories, customDetectors);
2424
- }
2425
- };
2426
- }
2427
-
2428
- // src/tokenize.ts
2429
- init_errors();
2430
- var TOKEN_PREFIX_MAP2 = {
2431
- email: "EMAIL",
2432
- phone: "PHONE",
2433
- ssn: "SSN",
2434
- "credit-card": "CREDIT_CARD",
2435
- ipv4: "IPV4",
2436
- ipv6: "IPV6",
2437
- url: "URL",
2438
- iban: "IBAN",
2439
- "date-of-birth": "DATE",
2440
- name: "PERSON",
2441
- address: "ADDRESS",
2442
- passport: "PASSPORT",
2443
- "drivers-license": "DRIVERS_LICENSE",
2444
- "national-id": "NATIONAL_ID",
2445
- "bank-account": "BANK_ACCOUNT",
2446
- cryptocurrency: "CRYPTO",
2447
- "tax-id": "TAX_ID",
2448
- "medical-record": "MEDICAL_RECORD",
2449
- "health-insurance": "HEALTH_INSURANCE",
2450
- prescription: "PRESCRIPTION",
2451
- "api-key": "API_KEY",
2452
- "social-media": "SOCIAL_MEDIA",
2453
- vin: "VIN",
2454
- "license-plate": "LICENSE_PLATE",
2455
- "tracking-number": "TRACKING_NUMBER",
2456
- "case-number": "CASE_NUMBER",
2457
- "company-registration": "COMPANY_REG"
2458
- };
2459
- function tokenize(text, options = {}) {
2460
- if (typeof text !== "string") throw new ValidationError("text", "must be a string");
2461
- const {
2462
- categories,
2463
- format = "bracket",
2464
- customDetectors,
2465
- aggressive = false,
2466
- confidenceThreshold = 0,
2467
- allowlist = [],
2468
- allowlistCaseSensitive = false
2469
- } = options;
2470
- const compiledAllowlist = allowlist.map(
2471
- (entry) => new RegExp(entry.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), allowlistCaseSensitive ? "" : "i")
2472
- );
2473
- const isAllowlisted = (v) => compiledAllowlist.some((re) => re.test(v));
2474
- const allMatches = detect(text, categories, customDetectors, aggressive).filter(
2475
- (m) => m.confidence >= confidenceThreshold && !isAllowlisted(m.value)
2476
- );
2477
- const store = createTokenStore();
2478
- let result = text;
2479
- const reversed = [...allMatches].reverse();
2480
- const tokenMatches = [];
2481
- for (const match of reversed) {
2482
- const prefix = TOKEN_PREFIX_MAP2[match.category] ?? match.category.toUpperCase();
2483
- const token = assignToken(store, match.category, match.value, prefix, format);
2484
- tokenMatches.push({
2485
- token,
2486
- original: match.value,
2487
- category: match.category,
2488
- start: match.start,
2489
- end: match.end
2490
- });
2491
- result = result.slice(0, match.start) + token + result.slice(match.end);
2492
- }
2493
- return { text: result, mapping: store.tokens, tokens: tokenMatches };
2494
- }
2495
- function tokenizeAsync(text, options = {}) {
2496
- return Promise.resolve(tokenize(text, options));
2497
- }
2498
- function detokenize(text, mapping) {
2499
- if (typeof text !== "string") throw new ValidationError("text", "must be a string");
2500
- const store = createTokenStore();
2501
- for (const [token, value] of mapping) {
2502
- store.tokens.set(token, value);
2503
- }
2504
- const result = detokenizeText(text, store);
2505
- const TOKEN_RE = /(\[[A-Z_]+_\d+\]|<[A-Z_]+_\d+>)/g;
2506
- const totalInText = (text.match(TOKEN_RE) ?? []).length;
2507
- const replacedCount = totalInText - result.unresolved.length;
2508
- return {
2509
- text: result.text,
2510
- replacedCount,
2511
- unresolved: result.unresolved
2512
- };
2513
- }
1
+ import { tokenize, detokenize, anonymizeAsync, anonymize, detect } from './chunk-W6RBCHYF.js';
2
+ export { anonymize, anonymizeAsync, anonymizeObject, anonymizeRecord, createAnonymizer, detect, detokenize, hasPII, tokenize, tokenizeAsync } from './chunk-W6RBCHYF.js';
3
+ import './chunk-OGNLB2KA.js';
4
+ export { synthesize } from './chunk-AAP472NG.js';
5
+ export { hash } from './chunk-E3PICZYI.js';
6
+ export { decrypt, encrypt } from './chunk-7HK2V5Q4.js';
7
+ export { PRESET_REGISTRY, generalize, getPreset, mask, pseudonymize, redact } from './chunk-GS3FRH4K.js';
8
+ import './chunk-RCW5IPPR.js';
9
+ import './chunk-SIHPDZXA.js';
10
+ import './chunk-PKHZ7CVI.js';
11
+ export { AllowlistMatchError, AnonymaError, AsyncStrategyError, AuditIntegrityError, BatchProcessingError, CryptoNotAvailableError, EncryptionError, KeyManagementError, PolicyError, PresetNotFoundError, TokenVaultError, UnknownCategoryError, UnsupportedStrategyError, ValidationError } from './chunk-2F2GWGTB.js';
2514
12
 
2515
13
  // src/llm.ts
2516
14
  function sanitizeForLLM(text, options = {}) {
@@ -2566,285 +64,9 @@ function tokenizeBatch(texts, options = {}) {
2566
64
  return texts.map((text, index) => wrapSync(index, () => tokenize(text, options)));
2567
65
  }
2568
66
  function detectBatch(texts, categories) {
2569
- return texts.map(
2570
- (text, index) => wrapSync(index, () => detect(text, categories))
2571
- );
2572
- }
2573
-
2574
- // src/index.ts
2575
- init_hash();
2576
-
2577
- // src/strategies/encrypt.ts
2578
- init_errors();
2579
- function requireCrypto() {
2580
- if (typeof globalThis.crypto.subtle === "undefined") throw new CryptoNotAvailableError();
2581
- return globalThis.crypto.subtle;
2582
- }
2583
- function toBase64(buf) {
2584
- return btoa(String.fromCharCode(...new Uint8Array(buf)));
2585
- }
2586
- function fromBase64(s) {
2587
- return Uint8Array.from(atob(s), (c) => c.charCodeAt(0));
2588
- }
2589
- function toHex(buf) {
2590
- return [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, "0")).join("");
2591
- }
2592
- function fromHex(s) {
2593
- const bytes = [];
2594
- for (let i = 0; i < s.length; i += 2) bytes.push(parseInt(s.slice(i, i + 2), 16));
2595
- return new Uint8Array(bytes);
2596
- }
2597
- async function deriveKey(subtle, passphrase, salt) {
2598
- const enc = new TextEncoder();
2599
- const baseKey = await subtle.importKey(
2600
- "raw",
2601
- enc.encode(passphrase),
2602
- "PBKDF2",
2603
- false,
2604
- ["deriveKey"]
2605
- );
2606
- return subtle.deriveKey(
2607
- { name: "PBKDF2", salt, iterations: 1e5, hash: "SHA-256" },
2608
- baseKey,
2609
- { name: "AES-GCM", length: 256 },
2610
- false,
2611
- ["encrypt", "decrypt"]
2612
- );
2613
- }
2614
- async function importRawKey(subtle, keyBytes) {
2615
- if (keyBytes.length !== 16 && keyBytes.length !== 32) {
2616
- throw new EncryptionError("encrypt", new Error("keyBytes must be 16 or 32 bytes"));
2617
- }
2618
- return subtle.importKey("raw", keyBytes, { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
2619
- }
2620
- async function encrypt(value, options) {
2621
- const subtle = requireCrypto();
2622
- const encoding = options.encoding ?? "base64";
2623
- try {
2624
- const enc = new TextEncoder();
2625
- const iv = globalThis.crypto.getRandomValues(new Uint8Array(12));
2626
- let key;
2627
- if (options.keyBytes) {
2628
- key = await importRawKey(subtle, options.keyBytes);
2629
- } else if (options.passphrase) {
2630
- const salt = enc.encode("anonyma_kdf_v1");
2631
- key = await deriveKey(subtle, options.passphrase, salt);
2632
- } else {
2633
- throw new EncryptionError("encrypt", new Error("Provide `passphrase` or `keyBytes`"));
2634
- }
2635
- const cipherBuf = await subtle.encrypt(
2636
- { name: "AES-GCM", iv },
2637
- key,
2638
- enc.encode(value)
2639
- );
2640
- const encode = encoding === "hex" ? toHex : toBase64;
2641
- return `${encoding}:${encode(iv.buffer)}:${encode(cipherBuf)}`;
2642
- } catch (err) {
2643
- if (err instanceof EncryptionError) throw err;
2644
- throw new EncryptionError("encrypt", err);
2645
- }
2646
- }
2647
- async function decrypt(ciphertext, options) {
2648
- const subtle = requireCrypto();
2649
- const parts = ciphertext.split(":");
2650
- if (parts.length !== 3) {
2651
- throw new EncryptionError("decrypt", new Error("Malformed ciphertext \u2014 expected `encoding:iv:payload`"));
2652
- }
2653
- const [encoding, ivEncoded, payloadEncoded] = parts;
2654
- const decode = encoding === "hex" ? fromHex : fromBase64;
2655
- try {
2656
- const iv = decode(ivEncoded);
2657
- const payload = decode(payloadEncoded);
2658
- const enc = new TextEncoder();
2659
- let key;
2660
- if (options.keyBytes) {
2661
- key = await importRawKey(subtle, options.keyBytes);
2662
- } else if (options.passphrase) {
2663
- const salt = enc.encode("anonyma_kdf_v1");
2664
- key = await deriveKey(subtle, options.passphrase, salt);
2665
- } else {
2666
- throw new EncryptionError("decrypt", new Error("Provide `passphrase` or `keyBytes`"));
2667
- }
2668
- const plainBuf = await subtle.decrypt({ name: "AES-GCM", iv }, key, payload);
2669
- return new TextDecoder().decode(plainBuf);
2670
- } catch (err) {
2671
- if (err instanceof EncryptionError) throw err;
2672
- throw new EncryptionError("decrypt", err);
2673
- }
2674
- }
2675
-
2676
- // src/strategies/synthesize.ts
2677
- function strHash(s) {
2678
- let h = 2166136261;
2679
- for (let i = 0; i < s.length; i++) {
2680
- h = Math.imul(h ^ s.charCodeAt(i), 16777619) >>> 0;
2681
- }
2682
- return h === 0 ? 1 : h;
2683
- }
2684
- function makePrng(seed) {
2685
- let state = seed >>> 0;
2686
- return () => {
2687
- state ^= state << 13;
2688
- state ^= state >> 17;
2689
- state ^= state << 5;
2690
- state = state >>> 0;
2691
- return state / 4294967296;
2692
- };
2693
- }
2694
- function randInt(rng, min, max) {
2695
- return min + Math.floor(rng() * (max - min + 1));
2696
- }
2697
- function pick(rng, arr) {
2698
- return arr[Math.floor(rng() * arr.length)];
2699
- }
2700
- var DOMAINS = ["example.com", "test.org", "sample.net", "demo.io", "placeholder.dev"];
2701
- var NAMES_FIRST = [
2702
- "Alice",
2703
- "Bob",
2704
- "Carol",
2705
- "Dave",
2706
- "Eve",
2707
- "Frank",
2708
- "Grace",
2709
- "Hank",
2710
- "Irene",
2711
- "Jack",
2712
- "Karen",
2713
- "Leo",
2714
- "Mina",
2715
- "Neal",
2716
- "Olivia",
2717
- "Paul",
2718
- "Quinn",
2719
- "Rosa",
2720
- "Sam",
2721
- "Tina",
2722
- "Uma",
2723
- "Victor",
2724
- "Wendy",
2725
- "Xena",
2726
- "Yuri",
2727
- "Zoe"
2728
- ];
2729
- var NAMES_LAST = [
2730
- "Smith",
2731
- "Jones",
2732
- "Williams",
2733
- "Taylor",
2734
- "Brown",
2735
- "Davies",
2736
- "Evans",
2737
- "Wilson",
2738
- "Thomas",
2739
- "Roberts",
2740
- "Johnson",
2741
- "White",
2742
- "Martin",
2743
- "Anderson",
2744
- "Thompson",
2745
- "Garcia",
2746
- "Martinez",
2747
- "Robinson",
2748
- "Clark",
2749
- "Rodriguez"
2750
- ];
2751
- function synthEmail(rng) {
2752
- const user = `${pick(rng, NAMES_FIRST).toLowerCase()}.${pick(rng, NAMES_LAST).toLowerCase()}${String(randInt(rng, 1, 99))}`;
2753
- return `${user}@${pick(rng, DOMAINS)}`;
2754
- }
2755
- function synthPhone(rng) {
2756
- return `+1-${String(randInt(rng, 200, 999))}-${randInt(rng, 200, 999).toString().padStart(3, "0")}-${String(randInt(rng, 1e3, 9999))}`;
2757
- }
2758
- function synthSsn(rng) {
2759
- const area = randInt(rng, 100, 665);
2760
- const group = randInt(rng, 10, 99);
2761
- const serial = randInt(rng, 1e3, 9999);
2762
- return `${String(area)}-${String(group)}-${String(serial)}`;
67
+ return texts.map((text, index) => wrapSync(index, () => detect(text, categories)));
2763
68
  }
2764
- function synthCreditCard(rng) {
2765
- const d = () => randInt(rng, 0, 9);
2766
- const groups = [
2767
- `4${String(d())}${String(d())}${String(d())}`,
2768
- `${String(d())}${String(d())}${String(d())}${String(d())}`,
2769
- `${String(d())}${String(d())}${String(d())}${String(d())}`,
2770
- `${String(d())}${String(d())}${String(d())}${String(d())}`
2771
- ];
2772
- return groups.join(" ");
2773
- }
2774
- function synthIpv4(rng) {
2775
- return `192.0.2.${String(randInt(rng, 1, 254))}`;
2776
- }
2777
- function synthIpv6(rng) {
2778
- const h = () => randInt(rng, 0, 65535).toString(16).padStart(4, "0");
2779
- return `2001:0db8:${h()}:${h()}:${h()}:${h()}:${h()}:${h()}`;
2780
- }
2781
- function synthUrl(rng) {
2782
- const paths = ["user", "profile", "data", "record", "item"];
2783
- return `https://${pick(rng, DOMAINS)}/${pick(rng, paths)}/${String(randInt(rng, 1e3, 9999))}`;
2784
- }
2785
- function synthIban(rng) {
2786
- const bank = `SYNTH${String(randInt(rng, 10, 99))}`;
2787
- const sort = `${String(randInt(rng, 10, 99))}${String(randInt(rng, 10, 99))}${String(randInt(rng, 10, 99))}`;
2788
- const acct = String(randInt(rng, 1e7, 99999999));
2789
- return `GB00 ${bank.slice(0, 4)} ${sort.slice(0, 2)}${sort.slice(2, 4)} ${sort.slice(4, 6)}${acct.slice(0, 2)} ${acct.slice(2, 6)} ${acct.slice(6)}`;
2790
- }
2791
- function synthDob(rng) {
2792
- const year = 1940 + randInt(rng, 0, 64);
2793
- const month = randInt(rng, 1, 12).toString().padStart(2, "0");
2794
- const day = randInt(rng, 1, 28).toString().padStart(2, "0");
2795
- return `${String(year)}-${month}-${day}`;
2796
- }
2797
- function synthName(rng) {
2798
- return `${pick(rng, NAMES_FIRST)} ${pick(rng, NAMES_LAST)}`;
2799
- }
2800
- function synthAddress(rng) {
2801
- const streets = ["Main St", "Oak Ave", "Pine Rd", "Elm Blvd", "Maple Dr", "Cedar Ln"];
2802
- const cities = ["Springfield", "Shelbyville", "Riverdale", "Greenfield", "Maplewood"];
2803
- const states = ["CA", "TX", "FL", "NY", "WA", "IL", "OH", "PA", "GA", "NC"];
2804
- return `${String(randInt(rng, 1, 9999))} ${pick(rng, streets)}, ${pick(rng, cities)}, ${pick(rng, states)} ${String(randInt(rng, 1e4, 99999))}`;
2805
- }
2806
- function synthApiKey(rng) {
2807
- const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
2808
- let key = "sk_test_";
2809
- for (let i = 0; i < 32; i++) key += chars[Math.floor(rng() * chars.length)] ?? "";
2810
- return key;
2811
- }
2812
- function synthGeneric(rng, value) {
2813
- const lowers = "abcdefghijklmnopqrstuvwxyz";
2814
- const uppers = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
2815
- const digits = "0123456789";
2816
- return value.split("").map((ch) => {
2817
- if (/[a-z]/.test(ch)) return lowers[Math.floor(rng() * lowers.length)];
2818
- if (/[A-Z]/.test(ch)) return uppers[Math.floor(rng() * uppers.length)];
2819
- if (/\d/.test(ch)) return digits[Math.floor(rng() * digits.length)];
2820
- return ch;
2821
- }).join("");
2822
- }
2823
- var GENERATORS = {
2824
- email: (rng) => synthEmail(rng),
2825
- phone: (rng) => synthPhone(rng),
2826
- ssn: (rng) => synthSsn(rng),
2827
- "credit-card": (rng) => synthCreditCard(rng),
2828
- ipv4: (rng) => synthIpv4(rng),
2829
- ipv6: (rng) => synthIpv6(rng),
2830
- url: (rng) => synthUrl(rng),
2831
- iban: (rng) => synthIban(rng),
2832
- "date-of-birth": (rng) => synthDob(rng),
2833
- name: (rng) => synthName(rng),
2834
- address: (rng) => synthAddress(rng),
2835
- "api-key": (rng) => synthApiKey(rng)
2836
- };
2837
- function synthesize(value, category, options = {}) {
2838
- const seedStr = (options.seed ?? "") + category + ":" + value;
2839
- const rng = makePrng(strHash(seedStr));
2840
- const gen = GENERATORS[category];
2841
- if (gen) return gen(rng, value);
2842
- return synthGeneric(rng, value);
2843
- }
2844
-
2845
- // src/index.ts
2846
- init_errors();
2847
69
 
2848
- export { AllowlistMatchError, AnonymaError, BatchProcessingError, CryptoNotAvailableError, EncryptionError, PRESET_REGISTRY, PresetNotFoundError, UnknownCategoryError, UnsupportedStrategyError, ValidationError, anonymize, anonymizeAsync, anonymizeBatch, anonymizeBatchAsync, anonymizeObject, anonymizeRecord, createAnonymizer, decrypt, detect, detectBatch, detokenize, encrypt, generalize, getPreset, hasPII, hash, mask, pseudonymize, redact, restoreFromLLM, sanitizeForLLM, synthesize, tokenize, tokenizeAsync, tokenizeBatch };
70
+ export { anonymizeBatch, anonymizeBatchAsync, detectBatch, restoreFromLLM, sanitizeForLLM, tokenizeBatch };
2849
71
  //# sourceMappingURL=index.js.map
2850
72
  //# sourceMappingURL=index.js.map