JavaScript SDK
JavaScript SDK
JavaScript SDK
The official PrivaiShield SDK for JavaScript and TypeScript. Works in Node.js and browser environments with full TypeScript support.
Installation
Install the SDK using your preferred package manager.
npmbash
npm install @privaishield/sdk
yarnbash
yarn add @privaishield/sdk
pnpmbash
pnpm add @privaishield/sdk
Requirements
- Node.js 18+ or modern browser
- TypeScript 4.7+ (optional)
Quick Start
Initialize the client with your API key and make your first request.
Basic Usagetypescript
import { PrivaiShield } from '@privaishield/sdk';
// Initialize the client
const client = new PrivaiShield({
apiKey: process.env.PRIVAISHIELD_API_KEY,
});
// Redact PII from text
const result = await client.redact({
text: 'Contact John Smith at john@acme.com or 555-123-4567',
mode: 'enhanced',
});
console.log(result.redacted);
// "Contact [PERSON_1] at [EMAIL_1] or [PHONE_1]"
console.log(result.entities);
// [{ type: 'PERSON', token: '[PERSON_1]', confidence: 0.97 }, ...]Environment Variablebash
# .env or .env.local PRIVAISHIELD_API_KEY=sk_live_your_key_here
API Reference
Complete reference for all SDK methods and options.
new PrivaiShield(options)Create a new PrivaiShield client instance.
apiKeystringYour API key (required)baseUrlstringCustom API base URLtimeoutnumberRequest timeout in ms (default: 30000)retriesnumberMax retry attempts (default: 3)client.redact(options)asyncRedact PII from a text string.
interface RedactOptions {
text: string;
mode?: 'standard' | 'enhanced';
entities?: string[];
confidence?: number;
returnOriginal?: boolean;
}
interface RedactResult {
redacted: string;
entities: Entity[];
mode: string;
processingTime: string;
}client.redactDocument(options)asyncProcess and redact a document file.
interface DocumentOptions {
file: File | Buffer | ReadableStream;
mode?: 'standard' | 'enhanced';
outputFormat?: 'pdf' | 'text' | 'json';
}
interface DocumentResult {
documentId: string;
pages: number;
totalEntities: number;
downloadUrl: string;
expiresAt: string;
}client.redactBatch(options)asyncProcess multiple texts in a single request.
interface BatchOptions {
items: Array<{ id: string; text: string }>;
mode?: 'standard' | 'enhanced';
}
interface BatchResult {
results: Array<{ id: string; redacted: string; entities: Entity[] }>;
totalItems: number;
totalEntities: number;
processingTime: string;
}TypeScript
The SDK is written in TypeScript and includes comprehensive type definitions. No additional @types package needed.
Type Importstypescript
import {
PrivaiShield,
RedactOptions,
RedactResult,
Entity,
EntityType,
DocumentOptions,
DocumentResult,
BatchOptions,
BatchResult,
} from '@privaishield/sdk';
// Full type safety
const result: RedactResult = await client.redact({
text: 'Contact john@example.com',
mode: 'enhanced',
});
// Entity types are strongly typed
result.entities.forEach((entity: Entity) => {
console.log(entity.type); // EntityType
console.log(entity.token); // string
console.log(entity.confidence); // number
});Custom Entity Typestypescript
// You can extend entity types for custom patterns
type CustomEntityType = EntityType | 'CUSTOM_ID' | 'INTERNAL_CODE';
const result = await client.redact({
text: 'ID: CUST-12345',
entities: ['CUSTOM_ID'] as CustomEntityType[],
});Streaming
Stream redaction results in real-time for large documents or progressive UI updates.
Streaming Exampletypescript
import { PrivaiShield } from '@privaishield/sdk';
const client = new PrivaiShield({
apiKey: process.env.PRIVAISHIELD_API_KEY,
});
// Stream redaction events
const stream = await client.redactStream({
text: longDocument,
mode: 'enhanced',
});
for await (const event of stream) {
switch (event.type) {
case 'entity':
console.log('Found:', event.data.type, event.data.token);
break;
case 'progress':
console.log(`Progress: ${event.data.processed}/${event.data.total}`);
break;
case 'complete':
console.log('Done:', event.data.redacted);
break;
}
}With AbortControllertypescript
const controller = new AbortController();
// Cancel after 5 seconds
setTimeout(() => controller.abort(), 5000);
try {
const stream = await client.redactStream({
text: longDocument,
signal: controller.signal,
});
for await (const event of stream) {
// Process events...
}
} catch (err) {
if (err.name === 'AbortError') {
console.log('Stream cancelled');
}
}Batch Processing
Process multiple texts efficiently in a single API call.
Basic Batchtypescript
const items = [
{ id: '1', text: 'Email: john@example.com' },
{ id: '2', text: 'Phone: 555-123-4567' },
{ id: '3', text: 'SSN: 123-45-6789' },
];
const result = await client.redactBatch({
items,
mode: 'enhanced',
});
result.results.forEach((item) => {
console.log(`${item.id}: ${item.redacted}`);
});
// 1: Email: [EMAIL_1]
// 2: Phone: [PHONE_1]
// 3: SSN: [SSN_1]Batch with Concurrency Controltypescript
// For very large batches, use chunking
import { chunk } from 'lodash';
const allItems = [...]; // thousands of items
const chunks = chunk(allItems, 100); // 100 items per batch
const results = await Promise.all(
chunks.map((items) =>
client.redactBatch({ items, mode: 'enhanced' })
)
);
const allResults = results.flatMap((r) => r.results);Error Handling
import { PrivaiShield, PrivaiShieldError } from '@privaishield/sdk';
try {
const result = await client.redact({ text: '...' });
} catch (err) {
if (err instanceof PrivaiShieldError) {
console.log(err.code); // 'invalid_request'
console.log(err.message); // 'The text field is required'
console.log(err.status); // 400
if (err.code === 'rate_limited') {
const retryAfter = err.headers['retry-after'];
// Wait and retry...
}
}
}