@insightpro-ai/sdk
v1.0.0
Published
Official JavaScript/TypeScript SDK for InsightPro AI Analytics Platform
Maintainers
Readme
@insightpro-ai/sdk
Official JavaScript/TypeScript SDK for the InsightPro AI Analytics Platform.
Features
- 🚀 Easy to use - Simple and intuitive API
- 📦 Lightweight - Minimal dependencies
- 🔒 Type-safe - Full TypeScript support
- 🌐 Universal - Works in Node.js and browsers
- 📊 Comprehensive - Covers all InsightPro API endpoints
- ⚡ Promise-based - Async/await ready
Installation
npm install @insightpro-ai/sdkor with yarn:
yarn add @insightpro-ai/sdkor with pnpm:
pnpm add @insightpro-ai/sdkQuick Start
import { InsightProClient } from '@insightpro-ai/sdk';
// Initialize the client
const client = new InsightProClient({
apiKey: 'your-api-key',
baseUrl: 'https://your-instance.insightpro-ai.com', // Optional
tenantId: 'your-tenant-id', // Optional for multi-tenant setups
});
// Track an analytics event
await client.trackEvent({
event: 'page_view',
userId: 'user-123',
properties: {
page: '/dashboard',
referrer: 'https://google.com',
},
});
// Get analytics overview
const overview = await client.getAnalyticsOverview(30); // Last 30 days
console.log(`Total Events: ${overview.totalEvents}`);
console.log(`Total Users: ${overview.totalUsers}`);Configuration
Basic Configuration
const client = new InsightProClient({
apiKey: 'your-api-key',
});Advanced Configuration
const client = new InsightProClient({
apiKey: 'your-api-key',
baseUrl: 'https://api.insightpro-ai.com',
tenantId: 'your-tenant-id',
timeout: 30000, // Request timeout in milliseconds
headers: {
// Custom headers to include in all requests
'X-Custom-Header': 'value',
},
});API Reference
Health & Status
Check the health of the InsightPro API:
const health = await client.health();
console.log(health.status); // 'healthy'Authentication
// Login
const session = await client.login({
email: '[email protected]',
password: 'password',
});
// Get current user
const user = await client.me();
// Get available auth providers
const providers = await client.getAuthProviders();
// Logout
await client.logout();Analytics
Track events and retrieve analytics data:
// Track a custom event
await client.trackEvent({
event: 'button_click',
userId: 'user-123',
sessionId: 'session-456',
properties: {
button_id: 'signup-cta',
page: '/landing',
},
context: {
device: {
type: 'desktop',
os: 'macOS',
browser: 'Chrome',
},
location: {
country: 'US',
region: 'CA',
city: 'San Francisco',
},
},
});
// Get analytics overview
const overview = await client.getAnalyticsOverview(7); // Last 7 days
console.log(`Revenue: $${overview.revenue}`);
console.log(`Total Users: ${overview.totalUsers}`);Tenants
Manage tenants (admin operations):
// Get all tenants
const tenants = await client.getTenants({ page: 1, limit: 50 });
// Get specific tenant
const tenant = await client.getTenant('tenant-id');
// Create a tenant
const newTenant = await client.createTenant({
company_name: 'Acme Corp',
admin_email: '[email protected]',
subscription_tier: 'PROFESSIONAL',
metadata: {
industry: 'Technology',
},
});
// Update tenant
const updated = await client.updateTenant('tenant-id', {
subscription_tier: 'ENTERPRISE',
});
// Delete tenant
await client.deleteTenant('tenant-id');Users
Manage users:
// Get all users
const users = await client.getUsers({ page: 1, limit: 50 });
// Get specific user
const user = await client.getUser('user-id');
// Update user
const updated = await client.updateUser('user-id', {
name: 'New Name',
role: 'admin',
});
// Delete user
await client.deleteUser('user-id');Alerts
Configure and manage alerts:
// Get alert history
const alerts = await client.getAlerts({ page: 1, limit: 20 });
// Get alert rules
const rules = await client.getAlertRules();
// Create alert rule
const rule = await client.createAlertRule({
name: 'High Error Rate',
description: 'Alert when error rate exceeds threshold',
condition: 'error_rate > threshold',
threshold: 0.05,
severity: 'CRITICAL',
enabled: true,
});
// Update alert rule
await client.updateAlertRule('rule-id', {
threshold: 0.1,
});
// Acknowledge alert
await client.acknowledgeAlert('alert-id');
// Delete alert rule
await client.deleteAlertRule('rule-id');Deals
Manage sales deals:
// Get all deals
const deals = await client.getDeals({ page: 1, limit: 50 });
// Get specific deal
const deal = await client.getDeal('deal-id');
// Create deal
const newDeal = await client.createDeal({
name: 'Enterprise Deal - Acme Corp',
value: 50000,
stage: 'negotiation',
probability: 75,
expected_close_date: '2024-12-31',
metadata: {
source: 'referral',
},
});
// Update deal
await client.updateDeal('deal-id', {
stage: 'closed-won',
probability: 100,
});
// Delete deal
await client.deleteDeal('deal-id');Leads
Manage sales leads:
// Get all leads
const leads = await client.getLeads({ page: 1, limit: 50 });
// Get specific lead
const lead = await client.getLead('lead-id');
// Create lead
const newLead = await client.createLead({
email: '[email protected]',
name: 'John Doe',
company: 'Acme Corp',
phone: '+1-555-0123',
source: 'website',
status: 'new',
score: 75,
});
// Update lead
await client.updateLead('lead-id', {
status: 'qualified',
score: 90,
});
// Delete lead
await client.deleteLead('lead-id');A/B Testing & Experiments
Manage experiments:
// Get all experiments
const experiments = await client.getExperiments();
// Get specific experiment
const experiment = await client.getExperiment('experiment-id');
// Create experiment
const newExperiment = await client.createExperiment({
name: 'Homepage CTA Test',
description: 'Testing different call-to-action buttons',
variants: [
{ name: 'Control', traffic_percentage: 50 },
{ name: 'Variant A', traffic_percentage: 50 },
],
});
// Get experiment results
const results = await client.getExperimentResults('experiment-id');
console.log(`Winner: ${results.winner}`);
results.variants.forEach((variant) => {
console.log(
`${variant.name}: ${variant.conversion_rate}% conversion rate`
);
});
// Update experiment
await client.updateExperiment('experiment-id', {
status: 'PAUSED',
});
// Delete experiment
await client.deleteExperiment('experiment-id');Reports
Generate and manage reports:
// Get all reports
const reports = await client.getReports();
// Get specific report
const report = await client.getReport('report-id');
// Create scheduled report
const newReport = await client.createReport({
name: 'Weekly Analytics Report',
description: 'Automated weekly analytics summary',
type: 'ANALYTICS',
format: 'PDF',
schedule: {
frequency: 'WEEKLY',
day_of_week: 1, // Monday
time: '09:00',
recipients: ['[email protected]'],
},
});
// Generate report
const reportBlob = await client.generateReport('report-id');
// Save or process the blob
// Update report
await client.updateReport('report-id', {
schedule: {
frequency: 'MONTHLY',
day_of_month: 1,
},
});
// Delete report
await client.deleteReport('report-id');Audit Logs
Query audit logs:
// Get audit logs
const logs = await client.getAuditLogs({
startDate: '2024-01-01',
endDate: '2024-01-31',
userId: 'user-123',
action: 'UPDATE',
resourceType: 'tenant',
limit: 100,
});
logs.items.forEach((log) => {
console.log(`${log.timestamp}: ${log.action} on ${log.resource_type}`);
});Feedback
Submit and manage feedback:
// Get all feedback
const feedback = await client.getFeedback({ page: 1, limit: 20 });
// Submit feedback
const newFeedback = await client.submitFeedback({
type: 'FEATURE_REQUEST',
subject: 'Add dark mode',
message: 'Would love to have a dark mode option',
rating: 5,
});
// Update feedback status
await client.updateFeedback('feedback-id', {
status: 'IN_PROGRESS',
});Error Handling
The SDK throws InsightProError for API errors:
try {
await client.createDeal({
name: 'New Deal',
value: 10000,
stage: 'discovery',
});
} catch (error) {
if (error instanceof Error) {
console.error('Error:', error.message);
if ('statusCode' in error) {
console.error('Status:', error.statusCode);
}
if ('code' in error) {
console.error('Code:', error.code);
}
}
}TypeScript Support
The SDK is written in TypeScript and includes full type definitions:
import {
InsightProClient,
AnalyticsEvent,
Deal,
Tenant,
InsightProError,
} from '@insightpro-ai/sdk';
// All types are exported and available
const event: AnalyticsEvent = {
event: 'purchase',
userId: 'user-123',
properties: {
amount: 99.99,
currency: 'USD',
},
};Environment Variables
You can configure the SDK using environment variables:
INSIGHTPRO_API_KEY=your-api-key
INSIGHTPRO_BASE_URL=https://api.insightpro-ai.com
INSIGHTPRO_TENANT_ID=your-tenant-idThen initialize without passing config:
const client = new InsightProClient({
apiKey: process.env.INSIGHTPRO_API_KEY!,
baseUrl: process.env.INSIGHTPRO_BASE_URL,
tenantId: process.env.INSIGHTPRO_TENANT_ID,
});Examples
Track User Journey
// Track complete user journey
async function trackUserJourney(userId: string) {
// Page view
await client.trackEvent({
event: 'page_view',
userId,
properties: { page: '/landing' },
});
// Button click
await client.trackEvent({
event: 'button_click',
userId,
properties: { button: 'signup' },
});
// Form submission
await client.trackEvent({
event: 'form_submit',
userId,
properties: { form: 'signup_form' },
});
// Conversion
await client.trackEvent({
event: 'conversion',
userId,
properties: { type: 'signup', value: 99.99 },
});
}Create and Monitor Experiment
// Create A/B test
const experiment = await client.createExperiment({
name: 'Pricing Page Test',
variants: [
{ name: 'Original', traffic_percentage: 50 },
{ name: 'New Design', traffic_percentage: 50 },
],
});
// Monitor results
setInterval(async () => {
const results = await client.getExperimentResults(experiment.experiment_id);
console.log('Current Results:', results);
// Check if we have a winner
if (results.statistical_significance && results.statistical_significance > 0.95) {
console.log(`Winner: ${results.winner}`);
}
}, 60000); // Check every minuteAutomated Lead Scoring
async function scoreAndQualifyLeads() {
const leads = await client.getLeads({ limit: 100 });
for (const lead of leads.items) {
let score = 0;
// Score based on properties
if (lead.company) score += 20;
if (lead.phone) score += 15;
if (lead.source === 'referral') score += 30;
// Update lead with new score
await client.updateLead(lead.lead_id, {
score,
status: score > 70 ? 'qualified' : 'new',
});
// Create deal for high-scoring leads
if (score > 80) {
await client.createDeal({
name: `Deal - ${lead.name || lead.email}`,
value: 10000,
stage: 'discovery',
metadata: { lead_id: lead.lead_id },
});
}
}
}Browser Usage
The SDK works in browsers with bundlers like Webpack, Rollup, or Vite:
<script type="module">
import { InsightProClient } from '@insightpro-ai/sdk';
const client = new InsightProClient({
apiKey: 'your-api-key',
});
// Track page view on load
client.trackEvent({
event: 'page_view',
properties: {
page: window.location.pathname,
referrer: document.referrer,
},
});
</script>Support
License
MIT © InsightPro Team
Contributing
Contributions are welcome! Please read our Contributing Guide for details.
