primeguardia-sanctions-sdk
v1.0.0
Published
Official PrimeGuardia Sanctions Screening SDK for Node.js and browsers
Maintainers
Readme
PrimeGuardia JavaScript/TypeScript SDK
Official JavaScript/TypeScript SDK for PrimeGuardia's Sanctions Screening API. Screen individuals and entities against global sanctions lists, PEPs, and watchlists with a simple, intuitive interface.
Features
- ✅ Complete TypeScript support with full type definitions
- ⚡ Async/await ready
- 🔄 Automatic retry logic with exponential backoff
- 🛡️ Comprehensive error handling with typed exceptions
- 📊 Rate limit handling and quota tracking
- 🔍 Bulk screening support (up to 1,000 entities)
- 📡 Real-time monitoring capabilities
- 🎯 Zero dependencies (except axios)
- 🚀 Production-ready with connection pooling
- 📝 Excellent IDE support with autocomplete
Installation
npm install @primeguardia/sanctions-sdkOr with yarn:
yarn add @primeguardia/sanctions-sdkQuick Start (5 minutes)
1. Get your API key
Sign up at primeguardia.com and get your API key from the dashboard.
2. Initialize the client
import { PrimeGuardia } from '@primeguardia/sanctions-sdk';
const client = new PrimeGuardia({
apiKey: 'your-api-key-here'
});3. Screen an entity
// Screen a person
const result = await client.screen({
name: 'John Doe',
email: '[email protected]'
});
if (result.blocked) {
console.log('⚠️ Entity is sanctioned!');
console.log(`Risk level: ${result.risk_assessment}`);
console.log(`Matches:`, result.matches);
} else {
console.log('✅ Clear - no matches found');
}That's it! You're screening entities in 3 simple steps.
Usage Examples
Basic Screening
import { PrimeGuardia } from '@primeguardia/sanctions-sdk';
const client = new PrimeGuardia({
apiKey: process.env.PRIMEGUARDIA_API_KEY
});
// Screen by name
const result = await client.screen({
name: 'Vladimir Putin'
});
console.log(`Match: ${result.match}`);
console.log(`Confidence: ${result.confidence}`);
console.log(`Risk: ${result.risk_assessment}`);
// Screen by email
const emailResult = await client.screen({
email: '[email protected]'
});
// Screen with additional context
const detailedResult = await client.screen({
name: 'John Smith',
email: '[email protected]',
country: 'US',
date_of_birth: '1980-01-01',
metadata: {
customer_id: 'CUST-12345',
transaction_id: 'TXN-67890'
}
});Bulk Screening
Screen up to 1,000 entities in a single request:
const results = await client.bulkScreen({
names: [
'John Doe',
'Jane Smith',
'Vladimir Putin',
'Xi Jinping'
],
emails: [
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]'
]
});
console.log(`Processed ${results.processed} entities`);
console.log(`Time: ${results.processing_time_ms}ms`);
results.results.forEach(result => {
if (result.match) {
console.log(`⚠️ ${result.name}: ${result.risk_level} risk`);
}
});Search Sanctions Database
// Search for entities
const searchResults = await client.search({
query: 'putin',
limit: 20,
sources: ['ofac', 'eu_sanctions']
});
console.log(`Found ${searchResults.total} matches`);
searchResults.results.forEach(entity => {
console.log(`${entity.name}`);
console.log(` Sources: ${entity.source_dataset.join(', ')}`);
console.log(` Countries: ${entity.countries?.join(', ')}`);
});
// Get specific entity details
const entity = await client.getEntity(12345);
console.log(entity);Continuous Monitoring
Monitor entities for changes in sanctions lists:
// Add entity to monitoring
const monitored = await client.addMonitoring({
name: 'Suspicious Person',
email: '[email protected]',
frequency: 24, // Check every 24 hours
metadata: {
internal_id: 'CUST-12345',
risk_category: 'high'
}
});
console.log(`Now monitoring entity ${monitored.id}`);
// Get all monitored entities
const allMonitored = await client.getMonitoredEntities();
console.log(`Monitoring ${allMonitored.length} entities`);
// Check for alerts
const alerts = await client.getAlerts({ acknowledged: false });
console.log(`${alerts.length} unacknowledged alerts`);
for (const alert of alerts) {
if (alert.severity === 'high') {
console.log(`🚨 HIGH SEVERITY: ${alert.message}`);
// Handle the alert
await client.acknowledgeAlert(alert.id);
}
}
// Get monitoring statistics
const stats = await client.getMonitoringStats();
console.log(`Total alerts: ${stats.total_alerts}`);
console.log(`Unacknowledged: ${stats.unacknowledged_alerts}`);Account Management
// Get your account information
const profile = await client.getProfile();
console.log(`Client: ${profile.client_name}`);
console.log(`Tier: ${profile.tier}`);
console.log(`Status: ${profile.subscription_status}`);
// Get comprehensive account summary
const summary = await client.getAccountSummary();
console.log(`Usage: ${summary.usage_stats.percentage}%`);
console.log(`Remaining: ${summary.usage_stats.remaining} calls`);
console.log(`Available datasets: ${summary.available_sources.join(', ')}`);
// Check quota status
const quota = await client.getQuotaStatus();
if (quota.percentage > 80) {
console.warn(`⚠️ Warning: ${quota.percentage}% of quota used`);
}
// Update profile
await client.updateProfile({
client_name: 'My Company Ltd',
contact_email: '[email protected]'
});Notification Settings
// Get current settings
const settings = await client.getNotificationSettings();
// Update notification preferences
await client.updateNotificationSettings({
email_enabled: true,
webhook_url: 'https://myapp.com/webhooks/primeguardia',
alert_on_high_risk: true,
alert_on_medium_risk: false,
usage_alert_thresholds: [50, 80, 95]
});Available Datasets
const datasets = await client.getDatasets();
datasets.forEach(dataset => {
console.log(`${dataset.name}`);
console.log(` Records: ${dataset.record_count.toLocaleString()}`);
console.log(` Last updated: ${dataset.last_updated}`);
console.log(` Available: ${dataset.available ? '✅' : '❌ Upgrade required'}`);
});Error Handling
The SDK provides typed exceptions for better error handling:
import {
PrimeGuardia,
AuthenticationError,
QuotaExceededError,
RateLimitError,
ValidationError,
PrimeGuardiaError
} from '@primeguardia/sanctions-sdk';
const client = new PrimeGuardia({ apiKey: 'your-api-key' });
try {
const result = await client.screen({ name: 'John Doe' });
// Handle result
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('Invalid API key');
// Update API key
} else if (error instanceof QuotaExceededError) {
console.error('Monthly quota exceeded');
// Upgrade plan or wait for reset
} else if (error instanceof RateLimitError) {
console.error('Rate limit exceeded');
if (error.retryAfter) {
console.log(`Retry after ${error.retryAfter} seconds`);
}
} else if (error instanceof ValidationError) {
console.error('Validation error:', error.message);
console.log('Details:', error.details);
} else if (error instanceof PrimeGuardiaError) {
console.error(`API error (${error.statusCode}):`, error.message);
} else {
console.error('Unexpected error:', error);
}
}Configuration Options
const client = new PrimeGuardia({
// Required
apiKey: 'your-api-key-here',
// Optional
baseUrl: 'https://api.primeguardia.com', // Custom API endpoint
timeout: 30000, // Request timeout (ms)
enableRetry: true, // Enable automatic retries
maxRetries: 3, // Max retry attempts
debug: false // Enable debug logging
});TypeScript Support
The SDK is written in TypeScript and includes complete type definitions:
import {
PrimeGuardia,
ScreeningRequest,
ScreeningResponse,
ConfidenceLevel,
RiskLevel,
MonitoringEntity,
MonitoringAlert
} from '@primeguardia/sanctions-sdk';
// Full type safety and autocomplete
const request: ScreeningRequest = {
name: 'John Doe',
email: '[email protected]'
};
const result: ScreeningResponse = await client.screen(request);
// Type checking for confidence levels
const confidence: ConfidenceLevel = result.confidence; // 'high' | 'medium' | 'low' | 'none'
// Type checking for risk levels
const risk: RiskLevel = result.risk_assessment; // 'HIGH' | 'MEDIUM' | 'LOW' | 'CLEAR'Framework Integration
Express.js Middleware
import express from 'express';
import { PrimeGuardia } from '@primeguardia/sanctions-sdk';
const app = express();
const client = new PrimeGuardia({ apiKey: process.env.PRIMEGUARDIA_API_KEY });
// Middleware to screen user registrations
app.post('/api/register', async (req, res, next) => {
try {
const { name, email } = req.body;
// Screen the user
const result = await client.screen({ name, email });
if (result.blocked) {
return res.status(403).json({
error: 'Registration blocked',
reason: 'Sanctions screening failed',
risk_level: result.risk_assessment
});
}
// Continue with registration
next();
} catch (error) {
next(error);
}
});NestJS Service
import { Injectable } from '@nestjs/common';
import { PrimeGuardia } from '@primeguardia/sanctions-sdk';
@Injectable()
export class SanctionsService {
private client: PrimeGuardia;
constructor() {
this.client = new PrimeGuardia({
apiKey: process.env.PRIMEGUARDIA_API_KEY
});
}
async screenUser(name: string, email: string) {
return await this.client.screen({ name, email });
}
async bulkScreenUsers(users: Array<{ name: string; email: string }>) {
const names = users.map(u => u.name);
const emails = users.map(u => u.email);
return await this.client.bulkScreen({ names, emails });
}
}React Hook
import { useState, useEffect } from 'react';
import { PrimeGuardia } from '@primeguardia/sanctions-sdk';
// Note: In production, API calls should go through your backend
const client = new PrimeGuardia({ apiKey: process.env.REACT_APP_API_KEY });
function useSanctionsCheck(name: string, email: string) {
const [result, setResult] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
let cancelled = false;
async function check() {
try {
setLoading(true);
const screeningResult = await client.screen({ name, email });
if (!cancelled) {
setResult(screeningResult);
}
} catch (err) {
if (!cancelled) {
setError(err);
}
} finally {
if (!cancelled) {
setLoading(false);
}
}
}
check();
return () => {
cancelled = true;
};
}, [name, email]);
return { result, loading, error };
}Best Practices
1. Secure Your API Key
// ✅ Good: Use environment variables
const client = new PrimeGuardia({
apiKey: process.env.PRIMEGUARDIA_API_KEY
});
// ❌ Bad: Hardcode API key
const client = new PrimeGuardia({
apiKey: 'abc123...' // Never do this!
});2. Handle Errors Gracefully
try {
const result = await client.screen({ name, email });
// Process result
} catch (error) {
// Log error for monitoring
logger.error('Sanctions screening failed', { error, name, email });
// Fail safely - don't block legitimate users due to API errors
// unless your compliance requirements mandate it
return { cleared: true, note: 'Screening temporarily unavailable' };
}3. Cache Results When Appropriate
import NodeCache from 'node-cache';
const cache = new NodeCache({ stdTTL: 3600 }); // 1 hour cache
async function screenWithCache(name: string, email: string) {
const cacheKey = `screen:${name}:${email}`;
const cached = cache.get(cacheKey);
if (cached) {
return cached;
}
const result = await client.screen({ name, email });
cache.set(cacheKey, result);
return result;
}4. Use Bulk Operations When Possible
// ✅ Good: Bulk screening
const results = await client.bulkScreen({
names: ['User 1', 'User 2', 'User 3'],
emails: ['[email protected]', '[email protected]', '[email protected]']
});
// ❌ Less efficient: Individual calls
for (const user of users) {
await client.screen({ name: user.name, email: user.email });
}5. Monitor Your Quota
// Check quota before making many requests
const quota = await client.getQuotaStatus();
if (quota.remaining < 100) {
console.warn('Low quota warning! Consider rate limiting or upgrading.');
}
if (quota.is_exceeded) {
throw new Error('Quota exceeded. Upgrade your plan.');
}Performance Tips
- Enable connection pooling (built-in with axios)
- Use bulk operations for multiple entities
- Implement client-side caching for repeated checks
- Set appropriate timeouts based on your needs
- Handle rate limits gracefully with retry logic (built-in)
Troubleshooting
Connection Timeout
const client = new PrimeGuardia({
apiKey: 'your-key',
timeout: 60000 // Increase timeout to 60 seconds
});Debug Mode
const client = new PrimeGuardia({
apiKey: 'your-key',
debug: true // Enable request/response logging
});Test Connection
try {
await client.testConnection();
console.log('✅ Connection successful');
} catch (error) {
console.error('❌ Connection failed:', error.message);
}API Reference
For complete API documentation, see our API Reference.
Main Methods
screen(request)- Screen a single entitybulkScreen(request)- Screen multiple entitiessearch(params)- Search sanctions databasegetEntity(id)- Get entity detailsgetDatasets()- List available datasetsaddMonitoring(entity)- Add to monitoringgetMonitoredEntities()- List monitored entitiesgetAlerts()- Get monitoring alertsgetProfile()- Get account profilegetAccountSummary()- Get account summarygetQuotaStatus()- Check quota statustestConnection()- Test API connectivity
Support
- 📧 Email: [email protected]
- 📚 Documentation: https://docs.primeguardia.com
- 🐛 Issues: https://github.com/primeguardia/sanctions-sdk-js/issues
- 💬 Slack: Join our community
License
MIT © PrimeGuardia
Contributing
We welcome contributions! Please see our Contributing Guide for details.
