TypeScript SDK
TypeScript SDK reference for FastPII Connect with detection, protection, validation, batch operations, health, session management, and Gateway access.
TypeScript SDK
Complete API reference for the FastPIIClient TypeScript class, response types, and error handling.
Installation
npm install fastpii-connect
# or
pnpm add fastpii-connect
# or
yarn add fastpii-connectRequires Node.js 18+.
FastPIIClient
import { FastPIIClient } from "fastpii-connect";
const client = new FastPIIClient({
apiKey: "fpk_your_api_key",
baseUrl: "https://api.fastpii.com", // default
timeout: 30, // request timeout in seconds
maxRetries: 2, // retries for 408, 429, 502, 503, 504 errors
});Constructor parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
| apiKey | string | FASTPII_API_KEY env var | Your FastPII API key (starts with fpk_) |
| baseUrl | string | "https://api.fastpii.com" | API base URL (or FASTPII_BASE_URL env var) |
| timeout | number | 30 | Request timeout in seconds |
| maxRetries | number | 2 | Number of retries for transient errors |
The client sends the API key as an X-API-Key header on every request. It automatically retries on status codes 408, 429, 502, 503, and 504 with exponential backoff and jitter.
All methods are async and return Promises.
Methods
detect
Detect sensitive data entities in text. Calls POST /api/v1/detect.
const result = await client.detect("My rodné číslo is 900101/1234", {
country: "cz", // optional: ISO country code
language: "cs", // optional: language hint
privacy_preset: "balanced", // optional: "conservative", "balanced", "aggressive"
});
for (const entity of result.entities) {
console.log(`Found ${entity.type}: ${entity.original}`);
}| Parameter | Type | Required | Description |
|---|---|---|---|
| text | string | Yes | Text to scan (1–50,000 characters) |
| options.country | string | No | ISO 3166-1 alpha-2 country code. Auto-detected if omitted. |
| options.language | string | No | Language hint for detection |
| options.privacy_preset | string | No | "conservative", "balanced", or "aggressive" |
Returns a DetectResponse. See Detection API for the full response structure.
protect
Protect sensitive data in text using the specified mode. Calls POST /api/v1/protect.
const result = await client.protect("My rodné číslo is 900101/1234", {
mode: "replace", // "replace", "mask", "hash", "tokenize"
country: "cz", // optional
language: "cs", // optional
privacy_preset: "aggressive", // optional
});
console.log(result.protected_text);| Parameter | Type | Required | Default | Description |
|---|---|---|---|---|
| text | string | Yes | - | Text to protect (1–50,000 characters) |
| options.mode | string | No | "replace" | Protection mode: replace, mask, hash, tokenize |
| options.country | string | No | None | ISO country code |
| options.language | string | No | None | Language hint |
| options.privacy_preset | string | No | None | Privacy preset |
Returns a ProtectResponse. See Protection API for the full response structure.
validate
Validate a specific identifier. Calls POST /api/v1/validate.
const result = await client.validate("900101/1234", {
entity_type: "rodne_cislo",
country: "cz", // optional
});
console.log(`Valid: ${result.valid}, Confidence: ${result.confidence}`);| Parameter | Type | Required | Description |
|---|---|---|---|
| value | string | Yes | Value to validate |
| options.entity_type | string | Yes | Entity type (e.g., "rodne_cislo", "pesel", "steuer_id") |
| options.country | string | No | ISO country code |
Returns a ValidateResponse.
listDetectors
List available detectors. Calls GET /api/v1/detectors.
const detectors = await client.listDetectors({ country: "CZ" });
for (const d of detectors.detectors) {
console.log(`${d.name} (${d.region}): ${d.description}`);
}| Parameter | Type | Required | Description |
|---|---|---|---|
| options.country | string | No | Filter by ISO country code |
Returns a DetectorsResponse.
detectBatch
Detect sensitive data in multiple texts. Calls POST /api/v1/detect/batch.
const result = await client.detectBatch(
["Text one", "Text two", "Text three"],
{ country: "cz" }
);
console.log(`Total entities: ${result.total_entities}`);| Parameter | Type | Required | Description |
|---|---|---|---|
| texts | string[] | Yes | Texts to scan (1–50, each max 50,000 chars) |
| options.country | string | No | ISO country code |
| options.language | string | No | Language hint |
| options.privacy_preset | string | No | Privacy preset |
Returns a DetectBatchResponse. See batch detection for details.
protectBatch
Protect sensitive data in multiple texts. Calls POST /api/v1/protect/batch.
const result = await client.protectBatch(
["Text one", "Text two"],
{ mode: "mask", country: "cz" }
);
console.log(`Total entities: ${result.total_entities}`);| Parameter | Type | Required | Description |
|---|---|---|---|
| texts | string[] | Yes | Texts to protect (1–50, each max 50,000 chars) |
| options.mode | string | No | Protection mode (default "replace") |
| options.country | string | No | ISO country code |
| options.language | string | No | Language hint |
| options.privacy_preset | string | No | Privacy preset |
Returns a ProtectBatchResponse. See batch protection for details.
health
Check the API health status. Calls GET /api/v1/health.
const health = await client.health();
console.log(`Status: ${health.status}, Version: ${health.version}`);Returns a HealthResponse with status, version, and environment fields.
Session management
Create a session that tracks detected countries across calls.
const session = new Session(client);
const result1 = await session.detect("My rodné číslo is 900101/1234");
console.log(session.countries); // ["CZ"]
const result2 = await session.detect("My PESEL is 90010112345");
console.log(session.countries); // ["CZ", "PL"]
console.log(session.messageCount); // 2Gateway
Access the AI Gateway for OpenAI-compatible chat completions:
const client = new FastPIIClient({ apiKey: "fpk_your_api_key" });
// Non-streaming
const response = await client.gateway.chat.completions({
model: "gpt-4o",
messages: [{ role: "user", content: "Hello!" }],
});
console.log(response.choices[0].message.content);
// Streaming
for await (const event of client.gateway.chat.stream({
model: "gpt-4o",
messages: [{ role: "user", content: "Hello!" }],
})) {
if ("content" in event) {
process.stdout.write(event.content);
}
}See the Gateway reference for full Gateway documentation.
Response types
DetectResponse
| Field | Type | Description |
|---|---|---|
| text | string | Original input text |
| entities | DetectedEntity[] | Detected entities |
| countries_detected | CountryDetection[] | Countries detected by Intelligence Engine |
| privacy_preset | string | null | Privacy preset used |
| processing_time_ms | number | Processing time in milliseconds |
| api_version | string | API version (default "v1") |
ProtectResponse
| Field | Type | Description |
|---|---|---|
| original_text | string | Original text before protection |
| protected_text | string | Text after protection was applied |
| entities | ProtectedEntity[] | Protected entities |
| countries_detected | CountryDetection[] | Countries detected by Intelligence Engine |
| protection_mode | string | Protection mode used |
| processing_time_ms | number | Processing time in milliseconds |
| api_version | string | API version (default "v1") |
ValidateResponse
| Field | Type | Description |
|---|---|---|
| value | string | The value that was validated |
| entity_type | string | Entity type validated against |
| country | string | null | Country code used |
| valid | boolean | Whether the value is valid |
| confidence | number | Validation confidence (0–1) |
| metadata | Record<string, unknown> | null | Additional validation metadata |
DetectedEntity
| Field | Type | Description |
|---|---|---|
| type | string | Entity type (e.g., rodne_cislo, email) |
| original | string | The original text that was detected |
| country | string | null | Country code if entity is country-specific |
| confidence | number | Detection confidence (0–1) |
| validated | boolean | Whether the entity passed checksum validation |
| start | number | Start position in original text |
| end | number | End position in original text |
| metadata | Record<string, unknown> | null | Additional entity metadata |
ProtectedEntity
| Field | Type | Description |
|---|---|---|
| type | string | Entity type |
| original | string | The original text that was detected |
| protected | string | The protected or replaced text |
| country | string | null | Country code |
| confidence | number | Detection confidence (0–1) |
| validated | boolean | Whether the entity passed checksum validation |
| start | number | Start position in original text |
| end | number | End position in original text |
| metadata | Record<string, unknown> | null | Additional entity metadata |
DetectBatchResponse
| Field | Type | Description |
|---|---|---|
| results | DetectResponse[] | Detection results for each text |
| total_entities | number | Total entities found across all texts |
| total_processing_time_ms | number | Total processing time in milliseconds |
ProtectBatchResponse
| Field | Type | Description |
|---|---|---|
| results | ProtectResponse[] | Protection results for each text |
| total_entities | number | Total entities found across all texts |
| total_processing_time_ms | number | Total processing time in milliseconds |
DetectorInfo
| Field | Type | Description |
|---|---|---|
| name | string | Detector identifier (e.g., "rodne_cislo") |
| description | string | Human-readable description |
| region | string | Country code this detector belongs to |
| category | string | Category: personal, business, medical, or government |
CountryDetection
| Field | Type | Description |
|---|---|---|
| code | string | ISO 3166-1 alpha-2 country code |
| confidence | number | Detection confidence (0–1) |
HealthResponse
| Field | Type | Description |
|---|---|---|
| status | string | Service status (e.g., "healthy") |
| version | string | null | API version |
| environment | string | null | Deployment environment |
Error handling
All errors inherit from FastPIIError which has message, statusCode, and errorType properties.
import {
FastPIIError,
AuthenticationError,
RateLimitError,
QuotaExceededError,
ValidationError,
ServerError,
ConnectionError,
TimeoutError,
} from "fastpii-connect";
try {
const result = await client.detect("text");
} catch (error) {
if (error instanceof AuthenticationError) {
console.log("Invalid API key");
} else if (error instanceof RateLimitError) {
console.log(`Rate limited. Retry after ${error.retryAfter} seconds`);
} else if (error instanceof QuotaExceededError) {
console.log("Monthly quota exceeded");
} else if (error instanceof ValidationError) {
console.log(`Request error: ${error.message} (status ${error.statusCode})`);
} else if (error instanceof ServerError) {
console.log("Server error");
} else if (error instanceof ConnectionError) {
console.log(`Connection failed: ${error.message}`);
} else if (error instanceof FastPIIError) {
console.log(`FastPII error: ${error.message}`);
}
}| Error | Status | When | Key property |
|---|---|---|---|
AuthenticationError | 401 | Invalid or missing API key | — |
PermissionError | 403 | Permission denied | — |
QuotaExceededError | 403 | Monthly quota exceeded | — |
PolicyViolationError | 403 | Request violates policy | — |
ValidationError | 400/422 | Invalid request | message, statusCode |
NotFoundError | 404 | Resource not found | — |
RateLimitError | 429 | Rate limit exceeded | retryAfter (seconds) |
ServerError | 500+ | Internal server error | — |
ConnectionError | None | Network failure | message |
TimeoutError | None | Request timeout | message |
Connect automatically retries on status codes 408, 429, 502, 503, and 504 up to maxRetries times with exponential backoff and jitter. See the error handling reference for Gateway-specific errors.
Validation helpers
The TypeScript SDK includes client-side validation that throws before making a network request:
import {
validatePrivacyPreset,
validateProtectMode,
validateTextLength,
validateBatchTexts,
} from "fastpii-connect";
validatePrivacyPreset("balanced"); // OK
validatePrivacyPreset("extreme"); // throws Error
validateProtectMode("replace"); // OK
validateProtectMode("delete"); // throws Error
validateTextLength("hello"); // OK
validateTextLength(""); // throws Error
validateTextLength("x".repeat(50001)); // throws Error
validateBatchTexts(["a", "b"]); // OK
validateBatchTexts([]); // throws Error
validateBatchTexts(new Array(51).fill("x")); // throws Error