npm package: @nosql-ai/sdk
Description: Official Node.js & TypeScript SDK for NoSQL - Global Edge-Native Database
Author: NoSQL Team
Latest version: 1.2.0

<!-- Project ID: 5f78b7bc-a066-48f5-861f-ddfc718c87de -->
# NoSQL SDK for Node.js & TypeScript

Official Node.js and TypeScript client library for [NoSQL](https://nosql-docs-prod.finhub.workers.dev) - Global Edge-Native Database.

Works in **Node.js** (18+), TypeScript, and modern JavaScript environments.

## Features

- 🚀 **Edge-Native**: Built for Cloudflare's global network
- 📄 **Document Database**: MongoDB-compatible operations
- 🤖 **Vector Database**: AI/ML similarity search
- ⏱️ **Time Series**: High-frequency data ingestion
- 🔍 **Hybrid Search**: Combined vector + document search
- 🔌 **Real-time**: WebSocket and SSE support
- 📦 **TypeScript**: Full type safety and IntelliSense
- ⚡ **Sub-10ms**: Global edge performance

## Installation

```bash
npm install @nosql/sdk
# or
yarn add @nosql/sdk
# or
pnpm add @nosql/sdk
```

## Quick Start

### Node.js (ESM)
```typescript
import { NoSQLClient } from '@nosql/sdk';

const client = new NoSQLClient({
  endpoint: 'https://nosql-db-prod.finhub.workers.dev',
  apiKey: 'your-api-key'
});
```

### Node.js (CommonJS)
```javascript
const { NoSQLClient } = require('@nosql/sdk');

const client = new NoSQLClient({
  endpoint: 'https://nosql-db-prod.finhub.workers.dev',
  apiKey: 'your-api-key'
});
```

### TypeScript
```typescript
import { NoSQLClient } from '@nosql/sdk';

// Initialize the client
const client = new NoSQLClient({
  endpoint: 'https://nosql-db-prod.finhub.workers.dev',
  apiKey: 'your-api-key'
});

// Document operations
await client.documents.insertOne('mydb', 'users', {
  name: 'John Doe',
  email: 'john@example.com'
});

const users = await client.documents.find('mydb', 'users', {
  filter: { name: 'John Doe' }
});

// Vector operations
await client.vectors.insert('mydb', 'embeddings', {
  id: 'doc1',
  vector: [0.1, 0.2, 0.3, /* ... */],
  metadata: { text: 'Hello world' }
});

const results = await client.vectors.search('mydb', 'embeddings', {
  vector: [0.1, 0.2, 0.3, /* ... */],
  topK: 10,
  metric: 'cosine'
});

// Time series operations
await client.timeseries.write('mydb', 'metrics', {
  timestamp: Date.now(),
  value: 42,
  tags: { host: 'server1', region: 'us-east' }
});

const data = await client.timeseries.query('mydb', {
  measurement: 'metrics',
  start: Date.now() - 3600000,
  end: Date.now(),
  aggregation: 'avg',
  interval: '5m'
});
```

## Authentication

### API Key

```typescript
const client = new NoSQLClient({
  endpoint: 'https://nosql-db-prod.finhub.workers.dev',
  apiKey: 'your-api-key'
});
```

### JWT Token

```typescript
const client = new NoSQLClient({
  endpoint: 'https://nosql-db-prod.finhub.workers.dev',
  token: 'your-jwt-token'
});

// Or authenticate with credentials
const { data } = await client.authenticate('email@example.com', 'password');
console.log('Authenticated:', data.token);
```

## Document Operations

```typescript
// Insert documents
await client.documents.insertOne('mydb', 'users', {
  name: 'Alice',
  age: 30,
  email: 'alice@example.com'
});

await client.documents.insertMany('mydb', 'users', [
  { name: 'Bob', age: 25 },
  { name: 'Charlie', age: 35 }
]);

// Query documents
const users = await client.documents.find('mydb', 'users', {
  filter: { age: { $gte: 25 } },
  sort: { age: 1 },
  limit: 10
});

// Update documents
await client.documents.updateById('mydb', 'users', 'user-id', {
  $set: { age: 31 }
});

await client.documents.updateMany('mydb', 'users',
  { age: { $lt: 30 } },
  { $inc: { age: 1 } }
);

// Delete documents
await client.documents.deleteById('mydb', 'users', 'user-id');

await client.documents.deleteMany('mydb', 'users', {
  age: { $lt: 18 }
});
```

## Vector Operations

```typescript
// Insert vectors
await client.vectors.insert('mydb', 'embeddings', {
  id: 'vec1',
  vector: [0.1, 0.2, 0.3],
  metadata: { type: 'document', title: 'My Document' }
});

// Similarity search
const results = await client.vectors.search('mydb', 'embeddings', {
  vector: [0.15, 0.25, 0.35],
  topK: 5,
  metric: 'cosine',
  filter: { type: 'document' }
});

// Generate embeddings
const { data } = await client.vectors.generateEmbedding(
  'Hello, world!',
  'openai'
);
console.log('Embedding:', data.embedding);

// Hybrid search (vector + text)
const hybridResults = await client.vectors.hybridSearch('mydb', 'embeddings', {
  text: 'machine learning',
  vector: [0.1, 0.2, 0.3],
  topK: 10,
  filter: { category: 'ai' }
});
```

## Time Series Operations

```typescript
// Write data points
await client.timeseries.write('mydb', 'cpu_usage', {
  timestamp: Date.now(),
  value: 75.5,
  tags: { host: 'server1', cpu: 'cpu0' },
  fields: { user: 45.2, system: 30.3 }
});

// Write multiple points
await client.timeseries.writeMany('mydb', 'cpu_usage', [
  { timestamp: Date.now(), value: 75.5, tags: { host: 'server1' } },
  { timestamp: Date.now(), value: 82.3, tags: { host: 'server2' } }
]);

// Query with aggregation
const metrics = await client.timeseries.aggregate(
  'mydb',
  'cpu_usage',
  Date.now() - 3600000, // 1 hour ago
  Date.now(),
  'avg',
  '5m' // 5-minute intervals
);

// Get latest value
const latest = await client.timeseries.latest('mydb', 'cpu_usage', {
  host: 'server1'
});
```

## Real-time Subscriptions

```typescript
// Connect WebSocket
client.connectWebSocket();

// Subscribe to changes
const unsubscribe = client.subscribe({
  channel: 'documents:mydb:users',
  filter: { age: { $gte: 18 } },
  onMessage: (data) => {
    console.log('New update:', data);
  },
  onError: (error) => {
    console.error('Subscription error:', error);
  },
  onClose: () => {
    console.log('Connection closed');
  }
});

// Later: unsubscribe
unsubscribe();

// Disconnect
client.disconnect();
```

## Bulk Operations

```typescript
const result = await client.bulk('mydb', 'users', [
  { type: 'insert', document: { name: 'Alice', age: 30 } },
  { type: 'update', filter: { name: 'Bob' }, update: { $set: { age: 26 } } },
  { type: 'delete', filter: { age: { $lt: 18 } } }
]);

console.log('Inserted:', result.data.insertedCount);
console.log('Modified:', result.data.modifiedCount);
console.log('Deleted:', result.data.deletedCount);
```

## Database Management

```typescript
// List databases
const databases = await client.listDatabases();

// Create database
await client.createDatabase('newdb');

// Delete database
await client.deleteDatabase('olddb');

// List collections
const collections = await client.listCollections('mydb');

// Create collection
await client.createCollection('mydb', 'users', { type: 'document' });

// Delete collection
await client.deleteCollection('mydb', 'users');
```

## Error Handling

```typescript
const result = await client.documents.insertOne('mydb', 'users', {
  name: 'John'
});

if (result.success) {
  console.log('Inserted ID:', result.data.insertedId);
} else {
  console.error('Error:', result.error.message);
  console.error('Code:', result.error.code);
}

// Or use try/catch with promises
try {
  const users = await client.documents.find('mydb', 'users', {});
  console.log('Found users:', users.data);
} catch (error) {
  console.error('Request failed:', error);
}
```

## Configuration Options

```typescript
const client = new NoSQLClient({
  endpoint: 'https://nosql-db-prod.finhub.workers.dev',
  apiKey: 'your-api-key',
  timeout: 30000, // Request timeout in ms (default: 30000)
  debug: true, // Enable debug logging
  headers: {
    'X-Custom-Header': 'value'
  }
});
```

## TypeScript

The SDK is written in TypeScript and provides full type safety:

```typescript
import type {
  Document,
  Vector,
  TimeSeriesPoint,
  VectorSearchResult
} from '@nosql/sdk';

const doc: Document = {
  _id: '123',
  name: 'John',
  age: 30
};

const vector: Vector = {
  id: 'vec1',
  vector: [0.1, 0.2, 0.3],
  metadata: { type: 'document' }
};
```

## Examples

See the [examples](./examples) directory for more comprehensive examples:

- [Document CRUD operations](./examples/documents.ts)
- [Vector similarity search](./examples/vectors.ts)
- [Time series data ingestion](./examples/timeseries.ts)
- [Real-time subscriptions](./examples/realtime.ts)
- [Bulk operations](./examples/bulk.ts)

## API Documentation

For complete API documentation, visit: https://nosql-docs-prod.finhub.workers.dev

## License

MIT © NoSQL Team

## Support

- **GitHub Issues**: https://github.com/FinHub-vc/NoSQL/issues
- **Documentation**: https://nosql-docs-prod.finhub.workers.dev
- **Email**: support@nosql.dev