anonyma 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,457 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ---
9
+
10
+ ## [1.0.0] — 2026-03-06
11
+
12
+ ### Added
13
+
14
+ ---
15
+
16
+ #### Core API (`"anonyma"`)
17
+
18
+ - **`detect(text, categories?, customDetectors?, aggressive?)`** — Scan a string for PII
19
+ and return a sorted, non-overlapping array of `PiiMatch` objects. An optional `categories`
20
+ array restricts scanning to a subset; `customDetectors` override built-in detectors per
21
+ category; `aggressive: true` switches to the expanded `AGGRESSIVE_DETECTOR_REGISTRY`.
22
+
23
+ - **`anonymize(text, options?)`** — Synchronous detect-and-replace pipeline. Applies the
24
+ configured strategy to every match and returns `{ text, matches }`. Async strategies
25
+ (`hash`, `encrypt`, `tokenize`, `synthesize`) fall back to a safe synchronous substitute
26
+ and emit a `console.warn`; use `anonymizeAsync()` for those strategies.
27
+
28
+ - **`anonymizeAsync(text, options?)`** — Fully async variant of `anonymize()`. Supports all
29
+ eight strategies natively, including `hash` (SHA-256), `encrypt` (AES-GCM), `tokenize`,
30
+ and `synthesize`.
31
+
32
+ - **`anonymizeRecord(record, rules)`** — Field-level anonymization of plain objects. `rules`
33
+ is a `FieldRuleMap` keyed by dot-notation paths (e.g. `"user.email"`); only the specified
34
+ fields are processed and the rest of the object is cloned unchanged.
35
+
36
+ - **`anonymizeObject<T>(obj, options?)`** — Deep recursive anonymization of any
37
+ JSON-serializable object tree. Walks arrays, nested objects, and mixed structures;
38
+ all string leaves are passed through the full `anonymize()` pipeline. Returns a deep
39
+ clone — the original is never mutated. Detects circular references and throws
40
+ `ValidationError` with a clear message.
41
+
42
+ - **`hasPII(text, categories?, customDetectors?)`** — Boolean check for PII presence.
43
+ Uses an early-exit optimisation: scanning stops immediately after the first detector
44
+ returns a match, making this significantly faster than a full `detect()` call when
45
+ the answer is `true`.
46
+
47
+ - **`createAnonymizer(config?)`** — Factory that produces a reusable `Anonymizer` instance
48
+ with built-in configuration. Returned instances expose `anonymize()`, `anonymizeAsync()`,
49
+ `detect()`, `anonymizeRecord()`, `anonymizeObject()`, `tokenize()`, and `hasPII()` — all
50
+ pre-bound to the factory config and accepting per-call overrides.
51
+
52
+ ---
53
+
54
+ #### Reversible Tokenization (`"anonyma"`)
55
+
56
+ - **`tokenize(text, options?)`** — Replace all detected PII with opaque, reversible tokens
57
+ (`[EMAIL_0001]`, `[PHONE_0001]`, etc.). Returns `{ text, mapping, tokens }` where
58
+ `mapping` is a `Map<token, originalValue>`. Supports `angle`, `bracket`, and `custom`
59
+ token formats; a `tokenTemplate` function can fully control the token shape.
60
+
61
+ - **`tokenizeAsync(text, options?)`** — Async variant of `tokenize()`.
62
+
63
+ - **`detokenize(text, mapping)`** — Restore a tokenized string. Returns
64
+ `{ text, replacedCount, unresolved }` — tokens absent from the mapping are left
65
+ unchanged and listed in `unresolved` so callers can detect data loss.
66
+
67
+ ---
68
+
69
+ #### LLM Pipeline Helpers (`"anonyma"`)
70
+
71
+ - **`sanitizeForLLM(text, options?)`** — Convenience wrapper around `tokenize()` with
72
+ defaults tuned for large-language-model use (`format: "bracket"`, aggressive mode off
73
+ to minimise false-positive noise in prompts). Returns a `TokenizeResult`; pass the
74
+ `mapping` to `restoreFromLLM()`.
75
+
76
+ - **`restoreFromLLM(response, mapping)`** — Swap tokens back into the LLM's response text.
77
+ Tokens use a safe character set (`[CATEGORY_NNNN]`) that language models rarely
78
+ re-format, maximising round-trip fidelity.
79
+
80
+ ---
81
+
82
+ #### Batch Processing (`"anonyma"`)
83
+
84
+ - **`anonymizeBatch(texts, options?)`** — Synchronously anonymize an array of strings.
85
+ Each item is processed independently; a failure in one item does not abort the rest.
86
+ Returns `BatchResult<AnonymizeResult>[]` with per-item `ok` / `error` discriminant.
87
+
88
+ - **`anonymizeBatchAsync(texts, options?, concurrency?)`** — Async batch anonymization.
89
+ Items run in parallel via `Promise.allSettled`. An optional `concurrency` cap limits
90
+ simultaneous in-flight items, controlling memory pressure for large datasets.
91
+
92
+ - **`tokenizeBatch(texts, options?)`** — Batch tokenization. Each item receives its own
93
+ independent token counter sequence (tokens do not cross item boundaries).
94
+
95
+ - **`detectBatch(texts, categories?)`** — Batch PII detection. Returns
96
+ `BatchResult<PiiMatch[]>[]`.
97
+
98
+ ---
99
+
100
+ #### Compliance Presets (`"anonyma"`)
101
+
102
+ - **`getPreset(name)`** — Retrieve a `PresetConfig` by name. Throws `PresetNotFoundError`
103
+ for unknown names.
104
+
105
+ - **`PRESET_REGISTRY`** — Read-only map of all six built-in presets keyed by name.
106
+
107
+ Six presets are available out of the box, each pre-configuring `enabledCategories` and
108
+ `defaultStrategy`:
109
+
110
+ | Preset | Default Strategy | Coverage |
111
+ |---|---|---|
112
+ | `"gdpr"` | `pseudonymize` | All personal data categories defined by the EU GDPR. |
113
+ | `"hipaa"` | `redact` | All 18 HIPAA Safe Harbor identifiers for PHI de-identification. |
114
+ | `"ccpa"` | `redact` | Consumer data categories defined by the California Consumer Privacy Act. |
115
+ | `"pci-dss"` | `redact` (card numbers: `mask` keepTrailing 4) | Cardholder and sensitive authentication data per PCI-DSS. |
116
+ | `"sox"` | `redact` | Financial records and corporate officer identifiers for SOX audit trails. |
117
+ | `"ferpa"` | `redact` | Student education records as defined by FERPA. |
118
+
119
+ ---
120
+
121
+ #### Anonymization Strategies (`"anonyma"`)
122
+
123
+ Eight strategies are available. The first five are synchronous; the final three require
124
+ `anonymizeAsync()` (or the dedicated `encrypt`/`hash`/`synthesize` functions):
125
+
126
+ - **`mask(value, options?)`** — Replace inner characters with a mask character (default
127
+ `"*"`). Options: `keepLeading`, `keepTrailing` (characters to leave visible),
128
+ `maskChar` (single character), and `preserveFormat` (format-preserving masking: letters
129
+ become `X`, digits become `0`, separators are preserved — e.g. `123-45-6789` →
130
+ `000-00-0000`).
131
+
132
+ - **`redact(value, options?)`** — Replace the entire value with a configurable label.
133
+ Default label: `[REDACTED]`.
134
+
135
+ - **`pseudonymize(value, options?)`** — Replace with a deterministic pseudo-identifier.
136
+ When a `seed` is supplied, the same `(value, seed)` pair always produces the same
137
+ pseudonym, enabling consistent replacement across a dataset. Without a seed, a random
138
+ pseudonym is generated. A custom `prefix` (default `"id_"`) is prepended.
139
+
140
+ - **`generalize(value, options?)`** — Replace a numeric value with a bucket range.
141
+ Default `bucketSize` of `10` turns `27` into `"20-29"`. Useful for age or year fields
142
+ where relative ranges retain analytical utility.
143
+
144
+ - **`hash(value, options?)`** — Async SHA-256 hash (requires Web Crypto / Node ≥ 18).
145
+ Options: `truncate` (number of hex characters to keep, default `16`) and `pepper`
146
+ (a per-deployment secret mixed into the hash to prevent rainbow-table reversal).
147
+
148
+ - **`encrypt(value, options)` / `decrypt(ciphertext, options)`** — Async AES-256-GCM
149
+ encryption (requires Web Crypto / Node ≥ 18). Provide either a `passphrase` (key
150
+ derived via PBKDF2 + SHA-256, 100,000 iterations) or raw `keyBytes` (16 or 32 bytes
151
+ for AES-128/256). Output format: `"<encoding>:<iv>:<ciphertext>"` where both IV and
152
+ payload are encoded as `base64` (default) or `hex`. Also exported from the dedicated
153
+ `"anonyma/crypto"` subpath.
154
+
155
+ - **`synthesize(value, options?)`** — Replace PII with structurally valid, format-
156
+ preserving synthetic data. The generator is deterministic: the same `(value, seed)`
157
+ pair always yields the same synthetic stand-in, preserving referential integrity across
158
+ a dataset without retaining real PII. Synthetic generators are built in for `email`,
159
+ `phone`, `ssn`, `credit-card`, `ipv4`, `ipv6`, `url`, `iban`, `date-of-birth`, `name`,
160
+ `address`, `passport`, `drivers-license`, `national-id`, `bank-account`,
161
+ `cryptocurrency`, `tax-id`, `medical-record`, `health-insurance`, `prescription`,
162
+ `api-key`, `social-media`, `vin`, `license-plate`, `tracking-number` and `case-number`.
163
+
164
+ - **`tokenize` (as a strategy)** — When `strategy: "tokenize"` is supplied in a rule set,
165
+ the value is replaced with a reversible opaque token. This is the same mechanism that
166
+ powers the top-level `tokenize()` function.
167
+
168
+ ---
169
+
170
+ #### PII Detectors (`"anonyma/detectors"`)
171
+
172
+ All detectors are pure functions `(text: string) => PiiMatch[]` and can be imported
173
+ individually for maximum tree-shaking. Twenty-seven categories are supported.
174
+
175
+ **Email, Network & Identity**
176
+
177
+ | Function | Confidence | Notes |
178
+ |---|---|---|
179
+ | `detectEmail` | 0.99 | RFC 5321 email addresses. |
180
+ | `detectEmailAggressive` | 0.75 | Obfuscated formats, e.g. `user [at] example [dot] com`. |
181
+ | `detectIpv4` | 0.98 | Dotted-decimal IPv4 with optional CIDR notation. |
182
+ | `detectIpv6` | 0.98 | Full and compressed IPv6 addresses. |
183
+ | `detectUrl` | 0.95 | http and https URLs with paths, query strings, and fragments. |
184
+ | `detectApiKey` | — | Common API key patterns (hex strings, Bearer tokens, `sk-`/`pk-`/`ghp_`-prefixed keys, etc.). |
185
+ | `detectSocialMedia` | — | Social media handles (`@username`) and profile URL patterns. |
186
+
187
+ **Phone & Identity Numbers**
188
+
189
+ | Function | Confidence | Notes |
190
+ |---|---|---|
191
+ | `detectPhone` | 0.90 | North American + E.164 international formats. |
192
+ | `detectPhoneAggressive` | 0.70 | 7-digit local formats (e.g. `555-1234`). |
193
+ | `detectSsn` | 0.95 | US Social Security Numbers with format and known-invalid range exclusions. |
194
+ | `detectSsnAggressive` | 0.80 | Expanded SSN pattern set. |
195
+
196
+ **Financial**
197
+
198
+ | Function | Confidence | Notes |
199
+ |---|---|---|
200
+ | `detectCreditCard` | 0.97 | 13–19 digit card numbers validated with the Luhn algorithm. |
201
+ | `detectCreditCardAggressive` | 0.80 | Also catches masked formats `****-****-****-1234`. |
202
+ | `detectIban` | 0.99 | IBAN strings validated with the ISO 13616 MOD-97 algorithm. |
203
+ | `detectBankAccount` | — | Common bank account number formats. |
204
+ | `detectCryptocurrency` | — | Bitcoin, Ethereum, and other common cryptocurrency wallet addresses. |
205
+ | `detectTaxId` | — | US EIN and common international tax identification number formats. |
206
+
207
+ **Personal Information**
208
+
209
+ | Function | Confidence | Notes |
210
+ |---|---|---|
211
+ | `detectName` | 0.75 | Heuristic: catches names preceded by greeting/salutation keywords (`Dear`, `Hi`, `Hello`, `To`, `From`, `Patient`, `Client`, `Defendant`, etc.). Not an NLP-based named-entity recogniser. |
212
+ | `detectNameAggressive` | 0.65 | Extends `detectName` with title-prefix patterns (`Mr.`, `Mrs.`, `Ms.`, `Dr.`, `Prof.`). |
213
+ | `detectDateOfBirth` | 0.78–0.88 | ISO 8601, US (`MM/DD/YYYY`), European (`DD/MM/YYYY`), and long-form date patterns. |
214
+ | `detectAddress` | — | Multi-line postal address patterns (street number, city, state/zip). |
215
+ | `detectPassport` | — | Passport number formats for major issuing countries. |
216
+ | `detectDriversLicense` | — | US and international driver's licence number patterns. |
217
+ | `detectNationalId` | — | National identity document numbers (SSN-adjacent, Aadhaar, NINO, etc.). |
218
+
219
+ **Healthcare**
220
+
221
+ | Function | Notes |
222
+ |---|---|
223
+ | `detectMedicalRecord` | Medical record number (MRN) patterns. |
224
+ | `detectHealthInsurance` | Health insurance member ID and policy number patterns. |
225
+ | `detectPrescription` | Prescription and DEA registration number patterns. |
226
+
227
+ **Vehicles & Transportation**
228
+
229
+ | Function | Notes |
230
+ |---|---|
231
+ | `detectVin` | 17-character Vehicle Identification Numbers validated with the ISO 3779 mod-11 checksum. |
232
+ | `detectVinAggressive` | Expanded VIN pattern set for partial or obfuscated VINs. |
233
+ | `detectLicensePlate` | Common licence plate formats across multiple countries. |
234
+ | `detectTrackingNumber` | Shipping tracking numbers (UPS, FedEx, USPS, DHL formats). |
235
+
236
+ **Government & Legal**
237
+
238
+ | Function | Notes |
239
+ |---|---|
240
+ | `detectCaseNumber` | Court case number formats (`YYYY-CV-NNNNN` and variants). |
241
+ | `detectCompanyRegistration` | Company registration and incorporation number formats. |
242
+
243
+ **Registries**
244
+
245
+ - **`DETECTOR_REGISTRY`** — Pre-assembled `Record<PiiCategory, Detector>` using all
246
+ standard-confidence detectors. Keyed by `PiiCategory`.
247
+
248
+ - **`AGGRESSIVE_DETECTOR_REGISTRY`** — Pre-assembled registry using every available
249
+ aggressive variant in place of its standard counterpart. Enables detection of
250
+ obfuscated or partial PII at the cost of a higher false-positive rate.
251
+
252
+ ---
253
+
254
+ #### `AnonymizeOptions` Reference
255
+
256
+ | Option | Type | Default | Description |
257
+ |---|---|---|---|
258
+ | `rules` | `AnonymizationRule[]` | `[]` | Per-category strategy overrides. When non-empty, only listed categories are scanned. |
259
+ | `defaultStrategy` | `StrategyOptions` | `{ strategy: "redact" }` | Strategy applied to any category not covered by `rules`. |
260
+ | `includeMatches` | `boolean` | `false` | Include the `PiiMatch` array in the result. |
261
+ | `customDetectors` | `Partial<Record<PiiCategory, Detector>>` | — | Replace built-in detectors on a per-category basis. |
262
+ | `customPatterns` | `CustomPattern[]` | — | Ad-hoc `RegExp` patterns merged into the detection pipeline. Matches participate in standard overlap deduplication. |
263
+ | `globalReplacement` | `string` | — | Replace every detected entity with this exact string, overriding all strategy settings. |
264
+ | `consistentTokens` | `boolean` | `false` | Map repeated identical PII values to the same token within a single call (e.g. `EMAIL_1`, `EMAIL_1` for the same address appearing twice). Different values get different counters. |
265
+ | `aggressive` | `boolean` | `false` | Switch to `AGGRESSIVE_DETECTOR_REGISTRY` for all built-in categories. |
266
+ | `enabledCategories` | `Partial<Record<PiiCategory, boolean>>` | — | Convenience boolean map. Only categories set to `true` are active; `rules` takes precedence for categories it covers. |
267
+ | `allowlist` | `string[]` | `[]` | Exact values to never anonymize (case-insensitive by default). |
268
+ | `allowlistPatterns` | `RegExp[]` | `[]` | Regular expressions matched against detected values; matches are skipped. |
269
+ | `allowlistCaseSensitive` | `boolean` | `false` | Make `allowlist` string matching case-sensitive. |
270
+ | `confidenceThreshold` | `number` | `0` | Minimum confidence score `[0, 1]` for a match to be anonymized. |
271
+ | `preset` | `CompliancePreset` | — | Apply a compliance preset as the base configuration. Explicit `rules` and `defaultStrategy` take precedence. |
272
+ | `locales` | `Locale[]` | `["global"]` | Activate locale-specific detector patterns. Values: `"global"`, `"us"`, `"uk"`, `"eu"`, `"ca"`, `"au"`, `"br"`, `"in"`, `"cn"`, `"jp"`, `"kr"`, `"za"`. |
273
+
274
+ ---
275
+
276
+ #### Error Classes (`"anonyma"`)
277
+
278
+ All errors extend `AnonymaError` and carry a machine-readable `code` string, enabling
279
+ precise `switch`/`instanceof` error handling.
280
+
281
+ | Class | Code | Extra Properties | When Thrown |
282
+ |---|---|---|---|
283
+ | `AnonymaError` | — | `code: string` | Base class; never thrown directly. |
284
+ | `ValidationError` | `VALIDATION_ERROR` | `field: string` | A function argument fails validation (wrong type, out-of-range value, etc.). |
285
+ | `UnsupportedStrategyError` | `UNSUPPORTED_STRATEGY` | `strategy: string` | An unrecognised strategy name is passed. |
286
+ | `UnknownCategoryError` | `UNKNOWN_CATEGORY` | `category: string` | A rule or config references an unknown PII category. |
287
+ | `CryptoNotAvailableError` | `CRYPTO_NOT_AVAILABLE` | — | `globalThis.crypto.subtle` is absent (Node < 18 or no polyfill). |
288
+ | `EncryptionError` | `ENCRYPTION_ERROR` | `operation: "encrypt" \| "decrypt"` | The underlying AES-GCM operation fails (wrong key, corrupt ciphertext, etc.). |
289
+ | `PresetNotFoundError` | `PRESET_NOT_FOUND` | `preset: string` | `getPreset()` is called with an unknown preset name. |
290
+ | `AllowlistMatchError` | `ALLOWLIST_MATCH_ERROR` | `field: string` | An allowlist configuration entry is malformed. |
291
+ | `BatchProcessingError` | `BATCH_PROCESSING_ERROR` | `succeeded`, `failed`, `total: number` | One or more items in a batch fail; carries partial result counts. |
292
+
293
+ ---
294
+
295
+ #### Streaming API (`"anonyma/stream"`)
296
+
297
+ Requires the WHATWG Streams API: Node.js ≥ 18 (native global `TransformStream`) or a
298
+ browser with Streams API support. Throws `ValidationError` if `TransformStream` is
299
+ unavailable.
300
+
301
+ - **`createAnonymizeStream(options?)`** — Returns a `TransformStream<string, AnonymizeResult>`
302
+ that anonymizes each string chunk synchronously. Input chunks must be complete strings
303
+ (e.g. individual lines); partial-chunk reassembly is the caller's responsibility.
304
+
305
+ - **`createAnonymizeStreamAsync(options?)`** — Async variant that uses `anonymizeAsync()`
306
+ internally. Supports `hash`, `encrypt`, and all other async strategies within a stream
307
+ pipeline.
308
+
309
+ - **`createTokenizeStream(options?)`** — Returns a `TransformStream<string, TokenizeResult>`
310
+ that tokenizes each chunk independently. Each chunk receives its own token counter
311
+ sequence; for a shared token map across chunks, manage tokenization externally.
312
+
313
+ ---
314
+
315
+ #### Checksum Validators (`"anonyma/validators"`)
316
+
317
+ Pure validation functions for PII checksum and format algorithms. All accept a string and
318
+ return `boolean`.
319
+
320
+ | Function | Algorithm / Standard | Notes |
321
+ |---|---|---|
322
+ | `luhn(digits)` | Luhn (ISO/IEC 7812) | Credit/debit card numbers and some national IDs. |
323
+ | `verhoeff(digits)` | Verhoeff | Indian Aadhaar numbers and some other national IDs. |
324
+ | `nhsMod11(value)` | NHS mod-11 | UK NHS 10-digit numbers (with or without spaces/hyphens). |
325
+ | `cpfChecksum(value)` | Brazilian CPF | 11-digit CPF with two check digits; rejects all-same-digit sequences. |
326
+ | `vinChecksum(vin)` | ISO 3779 mod-11 | 17-character Vehicle Identification Numbers. |
327
+ | `deaChecksum(value)` | DEA mod-10 | US Drug Enforcement Administration registration numbers. |
328
+ | `ibanMod97(value)` | ISO 13616 mod-97 | IBAN strings (15–34 characters, with or without spaces). |
329
+ | `ninoValid(value)` | UK NINO format | UK National Insurance Numbers; rejects invalid letter prefixes. |
330
+ | `aadhaarFormat(value)` | Aadhaar format | 12-digit Indian Aadhaar; does not start with `0` or `1`. |
331
+
332
+ ---
333
+
334
+ #### Encryption Utilities (`"anonyma/crypto"`)
335
+
336
+ Standalone re-export of the AES-GCM primitives for callers that need raw
337
+ encrypt/decrypt access without the full anonymization pipeline.
338
+
339
+ - **`encrypt(value, options)`** — AES-256-GCM encryption. Accepts `passphrase` (PBKDF2-
340
+ derived, `anonyma_kdf_v1` salt, 100,000 iterations) or raw `keyBytes` (16 or 32
341
+ bytes). Output: `"<encoding>:<iv>:<ciphertext>"` (`base64` or `hex`).
342
+ - **`decrypt(ciphertext, options)`** — Decrypts a value produced by `encrypt()`. Must use
343
+ the same `passphrase` or `keyBytes`.
344
+ - **`EncryptOptions`** type is also exported from this subpath.
345
+
346
+ ---
347
+
348
+ #### Zod Schemas & AI / MCP Definitions (`"anonyma/schemas"`)
349
+
350
+ Requires `zod` as a peer dependency. Import from `"anonyma/schemas"`.
351
+
352
+ **Zod Schemas**
353
+
354
+ | Export | Validates |
355
+ |---|---|
356
+ | `PiiCategorySchema` | All 27 `PiiCategory` string literals. |
357
+ | `MaskOptionsSchema` | `MaskOptions` including `maskChar`, `keepLeading`, `keepTrailing`. |
358
+ | `RedactOptionsSchema` | `RedactOptions` with `label`. |
359
+ | `PseudonymizeOptionsSchema` | `PseudonymizeOptions` with `seed` and `prefix`. |
360
+ | `HashOptionsSchema` | `HashOptions` with `truncate` and `pepper`. |
361
+ | `GeneralizeOptionsSchema` | `GeneralizeOptions` with `bucketSize`. |
362
+ | `StrategyOptionsSchema` | Discriminated union of all strategy option shapes. |
363
+ | `PiiMatchSchema` | `PiiMatch` output object. |
364
+ | `AnonymizeResultSchema` | `AnonymizeResult` with `text` and `matches`. |
365
+ | `AnonymizationRuleSchema` | Single `{ category, strategy }` rule. |
366
+ | `CustomPatternSchema` | `CustomPattern` with `pattern` (RegExp instance), `category`, `confidence`, `label`. |
367
+ | `AnonymizeOptionsSchema` | Full `AnonymizeOptions` input object. |
368
+ | `FieldRuleSchema` | Single field-level `{ strategy }` rule. |
369
+ | `FieldRuleMapSchema` | `Record<string, FieldRule>` for `anonymizeRecord()`. |
370
+
371
+ **OpenAI / MCP Tool Definitions**
372
+
373
+ Pre-built `OpenAiFunctionDefinition` objects ready to pass to the OpenAI client's
374
+ `tools` array or an MCP server's tool registry:
375
+
376
+ - **`ANONYMIZE_TOOL_DEFINITION`** — Function definition for `anonymize()`.
377
+ - **`DETECT_TOOL_DEFINITION`** — Function definition for `detect()`.
378
+ - **`HAS_PII_TOOL_DEFINITION`** — Function definition for `hasPII()`.
379
+ - **`ANONYMIZE_OBJECT_TOOL_DEFINITION`** — Function definition for `anonymizeObject()`.
380
+
381
+ **Capability Manifest**
382
+
383
+ - **`ANONYMA_MANIFEST`** — Machine-readable `as const` object describing all capabilities,
384
+ supported categories, strategy descriptions, and option keys. Intended for inclusion in
385
+ AI agent system prompts so models can self-discover available tools.
386
+
387
+ **Inferred TypeScript Types**
388
+
389
+ All Zod schema input/output types are re-exported as TypeScript types:
390
+ `PiiCategoryInput`, `StrategyOptionsInput`, `AnonymizeOptionsInput`,
391
+ `AnonymizationRuleInput`, `CustomPatternInput`, `PiiMatchOutput`,
392
+ `AnonymizeResultOutput`, `FieldRuleInput`, `FieldRuleMapInput`.
393
+
394
+ ---
395
+
396
+ #### TypeScript Types (`"anonyma"`)
397
+
398
+ All types are zero-cost, type-only exports (stripped by `tsc`; no runtime overhead).
399
+
400
+ | Type | Description |
401
+ |---|---|
402
+ | `PiiCategory` | Union of all 27 supported category string literals. |
403
+ | `PiiMatch` | `{ category, value, start, end, confidence }` — a single detected PII entity. |
404
+ | `CustomPattern` | `{ pattern: RegExp; category?; confidence?; label? }` — ad-hoc detection pattern. |
405
+ | `Locale` | `"global" \| "us" \| "uk" \| "eu" \| "ca" \| "au" \| "br" \| "in" \| "cn" \| "jp" \| "kr" \| "za"` |
406
+ | `CompliancePreset` | `"gdpr" \| "hipaa" \| "ccpa" \| "pci-dss" \| "sox" \| "ferpa"` |
407
+ | `StrategyName` | `"mask" \| "redact" \| "pseudonymize" \| "hash" \| "generalize" \| "tokenize" \| "encrypt" \| "synthesize"` |
408
+ | `StrategyOptions` | Discriminated union of all per-strategy option shapes. |
409
+ | `MaskOptions` | `{ maskChar?, keepLeading?, keepTrailing?, preserveFormat? }` |
410
+ | `RedactOptions` | `{ label? }` |
411
+ | `PseudonymizeOptions` | `{ seed?, prefix? }` |
412
+ | `HashOptions` | `{ truncate?, pepper? }` |
413
+ | `GeneralizeOptions` | `{ bucketSize? }` |
414
+ | `EncryptOptions` | `{ passphrase?, keyBytes?, encoding? }` |
415
+ | `SynthesizeOptions` | `{ seed?, locale? }` |
416
+ | `AnonymizationRule` | `{ category: PiiCategory, strategy: StrategyOptions }` |
417
+ | `AnonymizeOptions` | Full options accepted by `anonymize()` and `anonymizeAsync()`. |
418
+ | `AnonymizeResult` | `{ text: string, matches: ReadonlyArray<PiiMatch> }` |
419
+ | `TokenFormat` | `"angle" \| "bracket" \| "custom"` |
420
+ | `TokenizeOptions` | Options for `tokenize()` including `categories`, `format`, `tokenTemplate`, `deterministic`, `aggressive`, `locales`, `confidenceThreshold`, `allowlist`. |
421
+ | `TokenizeResult` | `{ text, mapping: ReadonlyMap<string, string>, tokens: TokenMatch[] }` |
422
+ | `DetokenizeResult` | `{ text, replacedCount, unresolved: string[] }` |
423
+ | `TokenMatch` | `{ token, original, category, start, end }` |
424
+ | `BatchResult<T>` | Discriminated union: `{ index, ok: true, value: T } \| { index, ok: false, error: Error }` |
425
+ | `FieldRule` | `{ strategy: StrategyOptions }` |
426
+ | `FieldRuleMap` | `Record<string, FieldRule>` — dot-notation paths for `anonymizeRecord()`. |
427
+ | `Detector` | `(text: string) => PiiMatch[]` — detector function signature. |
428
+ | `DetectorRegistry` | `Record<PiiCategory, Detector>` |
429
+ | `Anonymizer` | Interface returned by `createAnonymizer()`. |
430
+ | `AnonymizerConfig` | Config accepted by `createAnonymizer()`. |
431
+ | `AnonymaPlugin` | `{ name, detectors?, strategies?, validators? }` — plugin extension point. |
432
+ | `ValidatorFunction` | `(value: string) => boolean` |
433
+ | `StrategyFunction` | `(value: string, options?) => string` |
434
+ | `PresetConfig` | Full configuration shape for a compliance preset. |
435
+
436
+ ---
437
+
438
+ #### Package & Infrastructure
439
+
440
+ - **Dual ESM + CJS output** via `tsup` with `sideEffects: false` for full tree-shaking
441
+ support in all bundlers.
442
+ - **Full TypeScript declarations** — `.d.ts` + `.d.cts` files generated for every subpath.
443
+ - **Six subpath exports**: `"anonyma"`, `"anonyma/detectors"`, `"anonyma/schemas"`,
444
+ `"anonyma/validators"`, `"anonyma/crypto"`, `"anonyma/stream"`.
445
+ - **Zero runtime dependencies** — the main package and all subpaths except
446
+ `"anonyma/schemas"` have no external dependencies. `"anonyma/schemas"` requires `zod`
447
+ as a peer dependency.
448
+ - **GitHub Actions CI** — lint (`eslint`), typecheck (`tsc --noEmit`), test, and build
449
+ on Node.js 18, 20, and 22.
450
+ - **GitHub Actions Release** — automated npm publish with provenance on version tag push.
451
+ - **Vitest** test suite with ≥ 90% coverage target across statements, branches, and
452
+ functions.
453
+ - **ESLint flat config (v9)** with strict TypeScript rules.
454
+ - **Prettier** code formatting.
455
+ - **MIT License**.
456
+
457
+ [1.0.0]: https://github.com/izaccavalheiro/anonyma/releases/tag/v1.0.0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Anonyma Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.