npm package: @neureus/js
Description: Neureus Platform JavaScript/TypeScript SDK - Unified SDK for external clients
Author: Neureus
Latest version: 1.0.1

# @neureus/js

> Unified JavaScript/TypeScript SDK for the Neureus AI Platform

Single consolidated SDK for all Neureus Platform services. Use this for external client applications (web, mobile, Node.js).

**For worker-to-worker communication, use [service bindings](../../docs/SERVICE_BINDINGS_GUIDE.md) instead.**

## Installation

```bash
npm install @neureus/js
# or
pnpm add @neureus/js
# or
yarn add @neureus/js
```

## Quick Start

```typescript
import { NeureusClient } from '@neureus/js';

const neureus = new NeureusClient({
  apiKey: process.env.NEUREUS_API_KEY,
  baseUrl: 'https://api.neureus.ai', // optional
});

// AI Gateway - Chat completions
const chat = await neureus.ai.chat({
  messages: [
    { role: 'user', content: 'Hello!' }
  ],
  model: 'gpt-4',
});

// Vector Database - Similarity search
const results = await neureus.vector.search({
  query: [0.1, 0.2, 0.3, ...],
  topK: 5,
});

// RAG - Document Q&A
const answer = await neureus.rag.query({
  collection: 'docs',
  query: 'How do I get started?',
});

// Fraud Detection - Transaction risk assessment
const fraud = await neureus.fraud.assess({
  transactionId: 'tx_123',
  customerId: 'cust_456',
  amount: 1000,
  currency: 'USD',
});

// PII Protection - Mask sensitive data
const masked = await neureus.pii.mask({
  value: 'john@example.com',
  strategy: 'partial',
});
```

## Features

- **AI Gateway**: Multi-provider LLM routing with automatic failover
- **Vector Database**: Fast vector similarity search
- **RAG Pipeline**: Complete retrieval-augmented generation
- **Fraud Detection**: Transaction risk assessment with ML
- **PII Protection**: Data privacy compliance tools
- **TypeScript**: Full type safety and IntelliSense
- **Edge-Ready**: Works in browsers, Node.js, and edge runtimes

## API Reference

### NeureusClient

Main unified client providing access to all services.

```typescript
const neureus = new NeureusClient({
  apiKey: string;       // Required: Your Neureus API key
  baseUrl?: string;     // Optional: API base URL (default: 'https://api.neureus.ai')
  timeout?: number;     // Optional: Request timeout in ms (default: 60000)
  retries?: number;     // Optional: Retry attempts (default: 3)
  userId?: string;      // Optional: User ID for tracking
  teamId?: string;      // Optional: Team ID for tracking
});
```

### AI Gateway

```typescript
// Chat completion
const response = await neureus.ai.chat({
  messages: [
    { role: 'system', content: 'You are a helpful assistant.' },
    { role: 'user', content: 'Hello!' }
  ],
  model: 'gpt-4',
  temperature: 0.7,
  maxTokens: 1000,
});

// Generate embeddings
const embeddings = await neureus.ai.embed('Hello world');
// Or batch
const embeddings = await neureus.ai.embed(['Text 1', 'Text 2']);
```

### Vector Database

```typescript
// Upsert vectors
await neureus.vector.upsert([
  {
    id: '1',
    vector: [0.1, 0.2, 0.3, ...],
    metadata: { text: 'Hello world' }
  }
]);

// Search for similar vectors
const results = await neureus.vector.search({
  query: [0.1, 0.2, 0.3, ...],
  topK: 5,
  filter: { category: 'docs' },
  includeMetadata: true,
});

// Get vector by ID
const vector = await neureus.vector.get('1');

// Delete vectors
await neureus.vector.delete(['1', '2', '3']);
```

### RAG Pipeline

```typescript
// Index documents
await neureus.rag.index('knowledge-base', [
  {
    id: 'doc-1',
    content: 'Neureus is an AI platform...',
    metadata: { category: 'intro' }
  }
]);

// Query with RAG
const answer = await neureus.rag.query({
  collection: 'knowledge-base',
  query: 'What is Neureus?',
  topK: 3,
  includeContext: true,
});

// Create collection
await neureus.rag.createCollection('my-docs', {
  embeddingModel: 'text-embedding-ada-002',
});

// Delete documents
await neureus.rag.delete('knowledge-base', ['doc-1', 'doc-2']);
```

### Fraud Detection

```typescript
// Assess transaction risk
const result = await neureus.fraud.assess({
  transactionId: 'tx_123',
  customerId: 'cust_456',
  amount: 1000,
  currency: 'USD',
  merchantId: 'merch_789',
  location: {
    country: 'US',
    city: 'New York',
  },
  deviceFingerprint: 'fp_abc123',
  ipAddress: '192.168.1.1',
});

console.log(result.decision);    // 'approve' | 'review' | 'decline'
console.log(result.riskScore);   // 0-100
console.log(result.riskLevel);   // 'low' | 'medium' | 'high'
console.log(result.reasons);     // Array of risk factors

// Analyze user network
const network = await neureus.fraud.analyzeNetwork('user_123', 30);

// Get fraud statistics
const stats = await neureus.fraud.getStats('24h');
```

### PII Protection

```typescript
// Detect PII in text
const detections = await neureus.pii.detect(
  'Contact me at john@example.com or 555-0123',
  ['email', 'phone']
);

// Mask PII
const masked = await neureus.pii.mask({
  value: 'john@example.com',
  strategy: 'partial',  // Results in: j***@example.com
});

// Tokenize sensitive data
const tokenized = await neureus.pii.tokenize({
  value: '123-45-6789',
  type: 'ssn',
  ttl: 3600,
});

// Detokenize
const original = await neureus.pii.detokenize(tokenized.token);

// Encrypt PII
const encrypted = await neureus.pii.encrypt('sensitive data');

// Decrypt PII
const decrypted = await neureus.pii.decrypt(encrypted);
```

## Individual Clients

You can also use individual clients if you only need specific services:

```typescript
import { createAIClient } from '@neureus/js/ai';
import { createVectorClient } from '@neureus/js/vector';
import { createRAGClient } from '@neureus/js/rag';
import { createFraudClient } from '@neureus/js/fraud';
import { createPIIClient } from '@neureus/js/pii';

const ai = createAIClient({ apiKey: 'your-api-key' });
const vector = createVectorClient({ apiKey: 'your-api-key' });
const rag = createRAGClient({ apiKey: 'your-api-key' });
const fraud = createFraudClient({ apiKey: 'your-api-key' });
const pii = createPIIClient({ apiKey: 'your-api-key' });
```

## Environment Variables

```bash
# Required
NEUREUS_API_KEY=nru_...

# Optional
NEUREUS_BASE_URL=https://api.neureus.ai
NEUREUS_TIMEOUT=60000
NEUREUS_RETRIES=3
```

## TypeScript Support

Full TypeScript support with comprehensive type definitions:

```typescript
import type {
  ChatMessage,
  ChatCompletionRequest,
  Vector,
  VectorSearchRequest,
  Transaction,
  FraudAssessmentResult,
  PIIDetection,
} from '@neureus/js';
```

## Error Handling

All methods throw errors on failure. Use try-catch for error handling:

```typescript
try {
  const result = await neureus.fraud.assess(transaction);
} catch (error) {
  if (error.response?.status === 401) {
    console.error('Invalid API key');
  } else if (error.response?.status === 429) {
    console.error('Rate limit exceeded');
  } else {
    console.error('Error:', error.message);
  }
}
```

## Worker-to-Worker Communication

**Important**: If you're building Cloudflare Workers that need to call other Neureus workers, use [service bindings](../../docs/SERVICE_BINDINGS_GUIDE.md) instead of this SDK.

Service bindings provide:
- Sub-millisecond latency (<1ms vs 50-100ms HTTP)
- No network overhead
- Type-safe direct method calls

See the [Service Bindings Migration Guide](../../docs/CARDQL_MIGRATION_EXAMPLE.md) for examples.

## Examples

### Next.js App

```typescript
// app/api/chat/route.ts
import { NeureusClient } from '@neureus/js';

const neureus = new NeureusClient({
  apiKey: process.env.NEUREUS_API_KEY!,
});

export async function POST(request: Request) {
  const { message } = await request.json();

  const response = await neureus.ai.chat({
    messages: [{ role: 'user', content: message }],
  });

  return Response.json(response);
}
```

### React Component

```typescript
import { NeureusClient } from '@neureus/js';
import { useState } from 'react';

const neureus = new NeureusClient({
  apiKey: process.env.NEXT_PUBLIC_NEUREUS_API_KEY!,
});

export function ChatComponent() {
  const [message, setMessage] = useState('');
  const [response, setResponse] = useState('');

  const handleSubmit = async () => {
    const result = await neureus.ai.chat({
      messages: [{ role: 'user', content: message }],
    });
    setResponse(result.choices[0].message.content);
  };

  return (
    <div>
      <input value={message} onChange={(e) => setMessage(e.target.value)} />
      <button onClick={handleSubmit}>Send</button>
      <p>{response}</p>
    </div>
  );
}
```

### Node.js CLI

```typescript
#!/usr/bin/env node
import { NeureusClient } from '@neureus/js';

const neureus = new NeureusClient({
  apiKey: process.env.NEUREUS_API_KEY!,
});

async function main() {
  const query = process.argv[2];
  if (!query) {
    console.error('Usage: node cli.js "your question"');
    process.exit(1);
  }

  const answer = await neureus.rag.query({
    collection: 'docs',
    query,
  });

  console.log(answer.answer);
}

main().catch(console.error);
```

## License

MIT

## Support

- [Documentation](https://docs.neureus.ai)
- [API Reference](https://api.neureus.ai/docs)
- [GitHub Issues](https://github.com/Neureus/Neureus/issues)
- [Discord Community](https://discord.gg/neureus)