Skip to main content

API reference

Zero-dependency TypeScript data anonymization and PII detection library.

This page covers the core functions of "anonyma". The other entry points — anonyma/engine, anonyma/vault, anonyma/ai, anonyma/audit, anonyma/compliance, anonyma/middleware and anonyma/mcp — are described in the library guide and in the TSDoc of their declarations, which editors show on hover.


Contents​

  1. Core Functions
  2. Strategies
  3. Detectors
  4. Error Classes
  5. AI / MCP Integration
  6. Types Reference

Core Functions​

detect​

detect(
text: string,
categories?: PiiCategory[],
customDetectors?: Partial<Record<PiiCategory, Detector>>,
aggressive?: boolean
): PiiMatch[]

Scan text for PII and return a sorted, de-duplicated array of matches — without modifying the input.

ParameterTypeDefaultDescription
textstringrequiredThe input string to scan.
categoriesPiiCategory[]allRestrict scanning to these categories.
customDetectorsPartial<Record<...>>—Override or extend built-in detectors.
aggressivebooleanfalseUse expanded, more permissive patterns for each detector.

Returns: PiiMatch[] — each entry includes category, value, start, end, confidence.

Example:

import { detect } from "anonyma";

detect("alice@example.com and 192.168.1.1");
// [
// { category: "email", value: "alice@example.com", start: 0, end: 17, confidence: 0.99 },
// { category: "ipv4", value: "192.168.1.1", start: 22, end: 33, confidence: 0.98 },
// ]

hasPII​

hasPII(
text: string,
categories?: PiiCategory[],
customDetectors?: Partial<Record<PiiCategory, Detector>>
): boolean

Return true if text contains any detectable PII, false otherwise. Stops scanning after the first match for performance (early-exit optimisation).

ParameterTypeDefaultDescription
textstringrequiredThe input string to check.
categoriesPiiCategory[]allRestrict check to these categories.
customDetectorsPartial<Record<...>>—Override built-in detectors.

Example:

import { hasPII } from "anonyma";

if (hasPII(commentText)) {
return { error: "Comment contains personal information." };
}

hasPII("Call 555-867-5309"); // true
hasPII("No sensitive data here"); // false
hasPII("alice@example.com", ["phone"]); // false — email present but only checking phone

anonymize​

anonymize(text: string, options?: AnonymizeOptions): AnonymizeResult

Detect all PII in text and replace each match according to the configured strategy. Operates in a single pass, applying replacements right-to-left to preserve offsets.

Options (AnonymizeOptions):

FieldTypeDefaultDescription
defaultStrategyStrategyOptions{ strategy: "redact" }Strategy for all unmatched categories.
rulesAnonymizationRule[][]Per-category strategies. A non-empty list is also the list of categories replaced, and takes the place of a preset's rules.
includeMatchesbooleanfalsePopulate result.matches.
customDetectorsPartial<Record<PiiCategory, Detector>>—Override specific built-in detectors.
customPatternsCustomPattern[]—Ad-hoc regex patterns matched alongside built-in detectors.
globalReplacementstring—Replace ALL detected PII with this string, overriding strategies.
consistentTokensbooleanfalseSame value → same token (EMAIL_1, PHONE_2, etc.) within a call.
aggressivebooleanfalseUse expanded patterns to catch obfuscated PII (higher false-positive risk).
enabledCategoriesPartial<Record<PiiCategory, boolean>>—Convenience map — only categories set to true are processed.

Returns: AnonymizeResult — { text: string; matches: PiiMatch[] }

Example:

import { anonymize } from "anonyma";

// Default redact:
anonymize("Contact alice@example.com for help.").text;
// "Contact [REDACTED] for help."

// Global replacement — override all strategies:
anonymize("alice@example.com and 555-867-5309", { globalReplacement: "***" }).text;
// "*** and ***"

// Consistent token mapping:
anonymize("alice@example.com and alice@example.com", { consistentTokens: true }).text;
// "EMAIL_1 and EMAIL_1"

// Aggressive mode — catch obfuscated PII:
anonymize("user [at] example [dot] com", { aggressive: true }).text;
// "[REDACTED]"

// Enable only specific categories:
anonymize("alice@example.com — call 555-867-5309", {
enabledCategories: { email: true },
}).text;
// "[REDACTED] — call 555-867-5309"

// Custom pattern:
anonymize("Order ACME-001234 confirmed.", {
customPatterns: [{ pattern: /\bACME-\d{6}\b/g, label: "[ORDER_ID]" }],
rules: [],
}).text;
// "Order [ORDER_ID] confirmed."

anonymizeObject​

anonymizeObject<T extends object>(obj: T, options?: AnonymizeOptions): T

Recursively walk every string value in a JSON-serializable object tree, applying anonymize() to each one. Returns a deep clone — the input is never mutated.

Handles:

  • Plain objects (nested to any depth)
  • Arrays (including mixed-type arrays)
  • null, undefined, numbers, booleans — passed through unchanged
  • Circular references — throws ValidationError
ParameterTypeDefaultDescription
objobjectrequiredThe root object to anonymize.
optionsAnonymizeOptions—Forwarded to anonymize() for each string.

Example:

import { anonymizeObject } from "anonyma";

anonymizeObject({
user: { name: "Alice", email: "alice@example.com" },
notes: ["Call 555-867-5309", "No PII here"],
score: 42,
});
// {
// user: { name: "Alice", email: "[REDACTED]" },
// notes: ["[REDACTED]", "No PII here"],
// score: 42,
// }

// Consistent tokens across all fields:
anonymizeObject({ a: "alice@example.com", b: "alice@example.com" }, { consistentTokens: true });
// { a: "EMAIL_1", b: "EMAIL_1" }

anonymizeRecord​

anonymizeRecord<T extends Record<string, unknown>>(
record: T,
rules: FieldRuleMap
): T

Anonymize specific fields in a plain record/object. Supports dot-notation paths for nested fields. Returns a new object — never mutates the input.

Example:

import { anonymizeRecord } from "anonyma";

anonymizeRecord(
{ name: "Alice", email: "alice@example.com", age: "27" },
{
email: { strategy: { strategy: "redact" } },
age: { strategy: { strategy: "generalize" } },
},
);
// { name: "Alice", email: "[REDACTED]", age: "20-29" }

// Nested fields (dot notation):
anonymizeRecord(
{ user: { email: "alice@example.com", role: "admin" } },
{ "user.email": { strategy: { strategy: "mask" } } },
);
// { user: { email: "******************", role: "admin" } }

createAnonymizer​

createAnonymizer(config?: AnonymizerConfig): Anonymizer

Create a pre-configured, reusable anonymizer instance. Ideal for applications that run many anonymization operations with the same settings.

Config (AnonymizerConfig):

FieldTypeDefaultDescription
categoriesPiiCategory[]allCategories to detect.
defaultStrategyStrategyOptionsredactStrategy applied to all matches.
customDetectorsPartial<Record<PiiCategory, Detector>>—Override built-in detectors.
customPatternsCustomPattern[]—Ad-hoc regex patterns.
globalReplacementstring—Replace all PII with this string.
consistentTokensbooleanfalseEnable consistent token mapping.
aggressivebooleanfalseUse expanded detection patterns.

Anonymizer interface:

MethodSignatureDescription
anonymize(text, options?) → AnonymizeResultAnonymize a string.
detect(text) → PiiMatch[]Detect PII without modifying.
hasPII(text) → booleanCheck for PII presence.
anonymizeObject<T extends object>(obj: T, options?) → TRecursively anonymize an object tree.
anonymizeRecord<T extends Record<string, unknown>>(record: T, rules: FieldRuleMap) → TField-level anonymization.

Example:

import { createAnonymizer } from "anonyma";

const anonymizer = createAnonymizer({
categories: ["email", "phone"],
defaultStrategy: { strategy: "mask", keepLeading: 0, keepTrailing: 4 },
consistentTokens: true,
});

anonymizer.anonymize("Call 555-867-5309 or email alice@example.com").text;
// "Call ****5309 or email ************.com"

anonymizer.hasPII("No PII here"); // false

anonymizer.anonymizeObject({ contact: "alice@example.com", score: 99 });
// { contact: "EMAIL_1", score: 99 }

Strategies​

mask​

mask(value: string, options?: MaskOptions): string

Replace interior characters with a mask character, optionally keeping visible leading and/or trailing characters.

OptionTypeDefaultDescription
maskCharstring"*"Single-character mask. Must be length 1.
keepLeadingnumber0Characters to keep at the start.
keepTrailingnumber0Characters to keep at the end.
import { mask } from "anonyma";

mask("alice@example.com"); // "******************"
mask("alice@example.com", { keepLeading: 1, keepTrailing: 3 }); // "a**************com"
mask("4111-1111-1111-1111", { maskChar: "X", keepTrailing: 4 }); // "XXXXXXXXXXXXXXX1111"

redact​

redact(value: string, options?: RedactOptions): string

Replace the entire value with a label.

OptionTypeDefaultDescription
labelstring"[REDACTED]"The replacement text. Non-empty.
import { redact } from "anonyma";

redact("alice@example.com"); // "[REDACTED]"
redact("123-45-6789", { label: "[SSN REMOVED]" }); // "[SSN REMOVED]"

pseudonymize​

pseudonymize(value: string, options?: PseudonymizeOptions): string

Replace with a deterministic (seeded) or random pseudonym. Providing the same value + seed always returns the same pseudonym.

⚠️ Not cryptographically secure. Use hash for irreversibility.

OptionTypeDefaultDescription
seedstring—When set, output is deterministic.
prefixstring"id_"Prepended to the pseudonym hex string.
import { pseudonymize } from "anonyma";

pseudonymize("alice@example.com", { seed: "my-secret" });
// "id_3a7f1c2b9e4d0f1a" (same on every run)

pseudonymize("alice@example.com");
// "id_e9a3f7d1..." (random on every run)

hash​

hash(value: string, options?: HashOptions): Promise<string>

One-way SHA-256 hash. Requires Node.js ≥ 18 or a Web Crypto polyfill. Adding a pepper prevents rainbow-table attacks.

⚠️ Sync pipeline fallback: When used in the synchronous anonymize() pipeline, the hash strategy falls back to a deterministic pseudonym and emits a console.warn. Call hash() directly if you need true SHA-256 output.

OptionTypeDefaultDescription
truncatenumber16Number of hex chars to keep (1–64).
pepperstring—Per-deployment secret mixed into hash.
import { hash } from "anonyma";

await hash("alice@example.com");
// "5f3e4b3a9c1d8f2a"

generalize​

generalize(value: string, options?: GeneralizeOptions): string

Replace a numeric value with a range bucket. Non-numeric values are passed through unchanged.

OptionTypeDefaultDescription
bucketSizenumber10Width of each bucket.
import { generalize } from "anonyma";

generalize("27"); // "20-29"
generalize("5", { bucketSize: 5 }); // "5-9"

Detectors​

Each detector is exported individually from "anonyma/detectors" for maximum tree-shaking. Each category also has an *Aggressive variant with expanded patterns (lower confidence).

Built-in Detectors​

ExportCategoryConfidenceMethod
detectEmailemail0.99Regex (RFC 5321)
detectPhonephone0.90Regex (multi-format)
detectSsnssn0.95Regex + exclusions
detectCreditCardcredit-card0.97Regex + Luhn
detectIpv4ipv40.98Regex
detectIpv6ipv60.98Regex
detectUrlurl0.95Regex (http/https only)
detectIbaniban0.99Regex + MOD-97
detectDateOfBirthdate-of-birth0.78–0.88Multi-pattern
detectNamename0.75Heuristic (greeting context)

Note on detectName: Name detection is greeting-context only — it catches names preceded by keywords like "Dear", "Hi", "Hello", etc. It is not an NLP-based named-entity recogniser. Single-word names and names without greeting context will not be detected in normal mode.

Aggressive Variants​

ExportAdds over normal modeConfidence
detectEmailAggressiveObfuscated formats: user [at] domain [dot] com0.75
detectPhoneAggressive7-digit local format: 555-12340.70
detectSsnAggressiveNo-separator 9-digit: 1234567890.80
detectCreditCardAggressiveMasked format: ****-****-****-12340.80
detectNameAggressiveTitle prefixes: Mr., Mrs., Dr., Prof.0.65

Registries​

import { DETECTOR_REGISTRY, AGGRESSIVE_DETECTOR_REGISTRY } from "anonyma/detectors";

// Normal mode:
DETECTOR_REGISTRY.email("alice@example.com");

// Aggressive mode:
AGGRESSIVE_DETECTOR_REGISTRY.email("user [at] example [dot] com");

Custom Patterns​

Add arbitrary regex patterns to the detection pipeline alongside built-in detectors.

import { anonymize } from "anonyma";

anonymize("Order ACME-001234 confirmed.", {
customPatterns: [
{
pattern: /\bACME-\d{6}\b/g,
category: "order-id", // optional label (defaults to "custom")
confidence: 0.9, // optional (defaults to 0.85)
label: "[ORDER_ID]", // replacement label (defaults to "[REDACTED]")
},
],
rules: [],
}).text;
// "Order [ORDER_ID] confirmed."

Custom pattern matches participate in the same overlap deduplication as built-in detector matches. If the global flag is absent from the supplied RegExp, it is added automatically.


Error Classes​

All errors extend AnonymaError and carry a code string for programmatic handling.

ClassCodeWhen thrown
AnonymaError(base class)Never thrown directly.
ValidationErrorVALIDATION_ERRORInvalid function argument (also exposes .field).
UnsupportedStrategyErrorUNSUPPORTED_STRATEGYUnknown strategy name (also exposes .strategy).
UnknownCategoryErrorUNKNOWN_CATEGORYUnknown PII category (also exposes .category).
CryptoNotAvailableErrorCRYPTO_NOT_AVAILABLEglobalThis.crypto.subtle not available.
import { AnonymaError, ValidationError } from "anonyma";

try {
mask("x", { keepLeading: -1 });
} catch (err) {
if (err instanceof ValidationError) {
console.error(`Bad field "${err.field}":`, err.message);
}
}

AI / MCP Integration​

OpenAI Function Calling​

import {
ANONYMIZE_TOOL_DEFINITION,
DETECT_TOOL_DEFINITION,
HAS_PII_TOOL_DEFINITION,
ANONYMIZE_OBJECT_TOOL_DEFINITION,
} from "anonyma/schemas";
import OpenAI from "openai";

const client = new OpenAI();

const response = await client.chat.completions.create({
model: "gpt-4o",
tools: [
{ type: "function", function: ANONYMIZE_TOOL_DEFINITION },
{ type: "function", function: DETECT_TOOL_DEFINITION },
{ type: "function", function: HAS_PII_TOOL_DEFINITION },
{ type: "function", function: ANONYMIZE_OBJECT_TOOL_DEFINITION },
],
messages: [{ role: "user", content: "Anonymize: 'Call me at 555-867-5309'" }],
});

Runtime Validation with Zod​

import { AnonymizeOptionsSchema } from "anonyma/schemas";
import { anonymize } from "anonyma";

// Validate untrusted input:
const parsed = AnonymizeOptionsSchema.parse(req.body);
const result = anonymize(req.body.text as string, parsed);

Capability Manifest​

import { ANONYMA_MANIFEST } from "anonyma/schemas";

// Provide to an AI system prompt for autonomous tool discovery:
const systemContext = JSON.stringify(ANONYMA_MANIFEST, null, 2);

Types Reference​

All types are exported from "anonyma" as type-only imports (zero runtime cost).

import type {
PiiCategory, // "email" | "phone" | "ssn" | ... | "name"
PiiMatch, // { category, value, start, end, confidence }
StrategyOptions, // Discriminated union of all strategy option shapes
AnonymizeOptions, // Options for anonymize()
AnonymizeResult, // { text: string; matches: PiiMatch[] }
CustomPattern, // { pattern: RegExp; category?; confidence?; label? }
FieldRuleMap, // Record<string, FieldRule>
Anonymizer, // Instance returned by createAnonymizer()
AnonymizerConfig, // Config for createAnonymizer()
Detector, // (text: string) => PiiMatch[]
} from "anonyma";