@wiscale/velesdb-sdk 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,160 @@
1
+ # @velesdb/sdk
2
+
3
+ Official TypeScript SDK for VelesDB - Vector Search in Microseconds.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @velesdb/sdk
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ### WASM Backend (Browser/Node.js)
14
+
15
+ ```typescript
16
+ import { VelesDB } from '@velesdb/sdk';
17
+
18
+ // Initialize with WASM backend
19
+ const db = new VelesDB({ backend: 'wasm' });
20
+ await db.init();
21
+
22
+ // Create a collection
23
+ await db.createCollection('documents', {
24
+ dimension: 768, // BERT embedding dimension
25
+ metric: 'cosine'
26
+ });
27
+
28
+ // Insert vectors
29
+ await db.insert('documents', {
30
+ id: 'doc-1',
31
+ vector: new Float32Array(768).fill(0.1),
32
+ payload: { title: 'Hello World', category: 'greeting' }
33
+ });
34
+
35
+ // Batch insert
36
+ await db.insertBatch('documents', [
37
+ { id: 'doc-2', vector: [...], payload: { title: 'Second doc' } },
38
+ { id: 'doc-3', vector: [...], payload: { title: 'Third doc' } },
39
+ ]);
40
+
41
+ // Search
42
+ const results = await db.search('documents', queryVector, { k: 5 });
43
+ console.log(results);
44
+ // [{ id: 'doc-1', score: 0.95, payload: { title: '...' } }, ...]
45
+
46
+ // Cleanup
47
+ await db.close();
48
+ ```
49
+
50
+ ### REST Backend (Server)
51
+
52
+ ```typescript
53
+ import { VelesDB } from '@velesdb/sdk';
54
+
55
+ const db = new VelesDB({
56
+ backend: 'rest',
57
+ url: 'http://localhost:8080',
58
+ apiKey: 'your-api-key' // optional
59
+ });
60
+
61
+ await db.init();
62
+
63
+ // Same API as WASM backend
64
+ await db.createCollection('products', { dimension: 1536 });
65
+ await db.insert('products', { id: 'p1', vector: [...] });
66
+ const results = await db.search('products', query, { k: 10 });
67
+ ```
68
+
69
+ ## API Reference
70
+
71
+ ### `new VelesDB(config)`
72
+
73
+ Create a new VelesDB client.
74
+
75
+ | Option | Type | Required | Description |
76
+ |--------|------|----------|-------------|
77
+ | `backend` | `'wasm' \| 'rest'` | Yes | Backend type |
78
+ | `url` | `string` | REST only | Server URL |
79
+ | `apiKey` | `string` | No | API key for authentication |
80
+ | `timeout` | `number` | No | Request timeout (ms, default: 30000) |
81
+
82
+ ### `db.init()`
83
+
84
+ Initialize the client. Must be called before any operations.
85
+
86
+ ### `db.createCollection(name, config)`
87
+
88
+ Create a new collection.
89
+
90
+ | Option | Type | Default | Description |
91
+ |--------|------|---------|-------------|
92
+ | `dimension` | `number` | Required | Vector dimension |
93
+ | `metric` | `'cosine' \| 'euclidean' \| 'dot'` | `'cosine'` | Distance metric |
94
+
95
+ ### `db.insert(collection, document)`
96
+
97
+ Insert a single vector.
98
+
99
+ ```typescript
100
+ await db.insert('docs', {
101
+ id: 'unique-id',
102
+ vector: [0.1, 0.2, ...], // or Float32Array
103
+ payload: { key: 'value' } // optional metadata
104
+ });
105
+ ```
106
+
107
+ ### `db.insertBatch(collection, documents)`
108
+
109
+ Insert multiple vectors efficiently.
110
+
111
+ ### `db.search(collection, query, options)`
112
+
113
+ Search for similar vectors.
114
+
115
+ | Option | Type | Default | Description |
116
+ |--------|------|---------|-------------|
117
+ | `k` | `number` | `10` | Number of results |
118
+ | `filter` | `object` | - | Filter expression |
119
+ | `includeVectors` | `boolean` | `false` | Include vectors in results |
120
+
121
+ ### `db.delete(collection, id)`
122
+
123
+ Delete a vector by ID. Returns `true` if deleted.
124
+
125
+ ### `db.get(collection, id)`
126
+
127
+ Get a vector by ID. Returns `null` if not found.
128
+
129
+ ### `db.close()`
130
+
131
+ Close the client and release resources.
132
+
133
+ ## Error Handling
134
+
135
+ ```typescript
136
+ import { VelesDBError, ValidationError, ConnectionError, NotFoundError } from '@velesdb/sdk';
137
+
138
+ try {
139
+ await db.search('nonexistent', query);
140
+ } catch (error) {
141
+ if (error instanceof NotFoundError) {
142
+ console.log('Collection not found');
143
+ } else if (error instanceof ValidationError) {
144
+ console.log('Invalid input:', error.message);
145
+ } else if (error instanceof ConnectionError) {
146
+ console.log('Connection failed:', error.message);
147
+ }
148
+ }
149
+ ```
150
+
151
+ ## Performance Tips
152
+
153
+ 1. **Use batch operations** for multiple inserts
154
+ 2. **Reuse Float32Array** for queries when possible
155
+ 3. **Use WASM backend** for browser apps (no network latency)
156
+ 4. **Pre-initialize** the client at app startup
157
+
158
+ ## License
159
+
160
+ Elastic License 2.0 (ELv2) - See [LICENSE](../../LICENSE) for details.
@@ -0,0 +1,299 @@
1
+ /**
2
+ * VelesDB TypeScript SDK - Type Definitions
3
+ * @packageDocumentation
4
+ */
5
+ /** Supported distance metrics for vector similarity */
6
+ type DistanceMetric = 'cosine' | 'euclidean' | 'dot';
7
+ /** Backend type for VelesDB connection */
8
+ type BackendType = 'wasm' | 'rest';
9
+ /** Configuration options for VelesDB client */
10
+ interface VelesDBConfig {
11
+ /** Backend type: 'wasm' for browser/Node.js, 'rest' for server */
12
+ backend: BackendType;
13
+ /** REST API URL (required for 'rest' backend) */
14
+ url?: string;
15
+ /** API key for authentication (optional) */
16
+ apiKey?: string;
17
+ /** Request timeout in milliseconds (default: 30000) */
18
+ timeout?: number;
19
+ }
20
+ /** Collection configuration */
21
+ interface CollectionConfig {
22
+ /** Vector dimension (e.g., 768 for BERT, 1536 for GPT) */
23
+ dimension: number;
24
+ /** Distance metric (default: 'cosine') */
25
+ metric?: DistanceMetric;
26
+ /** Optional collection description */
27
+ description?: string;
28
+ }
29
+ /** Collection metadata */
30
+ interface Collection {
31
+ /** Collection name */
32
+ name: string;
33
+ /** Vector dimension */
34
+ dimension: number;
35
+ /** Distance metric */
36
+ metric: DistanceMetric;
37
+ /** Number of vectors */
38
+ count: number;
39
+ /** Creation timestamp */
40
+ createdAt?: Date;
41
+ }
42
+ /** Vector document to insert */
43
+ interface VectorDocument {
44
+ /** Unique identifier */
45
+ id: string | number;
46
+ /** Vector data */
47
+ vector: number[] | Float32Array;
48
+ /** Optional payload/metadata */
49
+ payload?: Record<string, unknown>;
50
+ }
51
+ /** Search options */
52
+ interface SearchOptions {
53
+ /** Number of results to return (default: 10) */
54
+ k?: number;
55
+ /** Filter expression (optional) */
56
+ filter?: Record<string, unknown>;
57
+ /** Include vectors in results (default: false) */
58
+ includeVectors?: boolean;
59
+ }
60
+ /** Search result */
61
+ interface SearchResult {
62
+ /** Document ID */
63
+ id: string | number;
64
+ /** Similarity score */
65
+ score: number;
66
+ /** Document payload (if requested) */
67
+ payload?: Record<string, unknown>;
68
+ /** Vector data (if includeVectors is true) */
69
+ vector?: number[];
70
+ }
71
+ /** Backend interface that all backends must implement */
72
+ interface IVelesDBBackend {
73
+ /** Initialize the backend */
74
+ init(): Promise<void>;
75
+ /** Check if backend is initialized */
76
+ isInitialized(): boolean;
77
+ /** Create a new collection */
78
+ createCollection(name: string, config: CollectionConfig): Promise<void>;
79
+ /** Delete a collection */
80
+ deleteCollection(name: string): Promise<void>;
81
+ /** Get collection info */
82
+ getCollection(name: string): Promise<Collection | null>;
83
+ /** List all collections */
84
+ listCollections(): Promise<Collection[]>;
85
+ /** Insert a single vector */
86
+ insert(collection: string, doc: VectorDocument): Promise<void>;
87
+ /** Insert multiple vectors */
88
+ insertBatch(collection: string, docs: VectorDocument[]): Promise<void>;
89
+ /** Search for similar vectors */
90
+ search(collection: string, query: number[] | Float32Array, options?: SearchOptions): Promise<SearchResult[]>;
91
+ /** Delete a vector by ID */
92
+ delete(collection: string, id: string | number): Promise<boolean>;
93
+ /** Get a vector by ID */
94
+ get(collection: string, id: string | number): Promise<VectorDocument | null>;
95
+ /** Close/cleanup the backend */
96
+ close(): Promise<void>;
97
+ }
98
+ /** Error types */
99
+ declare class VelesDBError extends Error {
100
+ readonly code: string;
101
+ readonly cause?: Error | undefined;
102
+ constructor(message: string, code: string, cause?: Error | undefined);
103
+ }
104
+ declare class ConnectionError extends VelesDBError {
105
+ constructor(message: string, cause?: Error);
106
+ }
107
+ declare class ValidationError extends VelesDBError {
108
+ constructor(message: string);
109
+ }
110
+ declare class NotFoundError extends VelesDBError {
111
+ constructor(resource: string);
112
+ }
113
+
114
+ /**
115
+ * VelesDB Client - Unified interface for all backends
116
+ */
117
+
118
+ /**
119
+ * VelesDB Client
120
+ *
121
+ * Provides a unified interface for interacting with VelesDB
122
+ * using either WASM (browser/Node.js) or REST API backends.
123
+ *
124
+ * @example
125
+ * ```typescript
126
+ * const db = new VelesDB({ backend: 'wasm' });
127
+ * await db.init();
128
+ *
129
+ * await db.createCollection('embeddings', { dimension: 768, metric: 'cosine' });
130
+ * await db.insert('embeddings', { id: 'doc1', vector: [...], payload: { title: 'Hello' } });
131
+ *
132
+ * const results = await db.search('embeddings', queryVector, { k: 5 });
133
+ * ```
134
+ */
135
+ declare class VelesDB {
136
+ private readonly config;
137
+ private backend;
138
+ private initialized;
139
+ /**
140
+ * Create a new VelesDB client
141
+ *
142
+ * @param config - Client configuration
143
+ * @throws {ValidationError} If configuration is invalid
144
+ */
145
+ constructor(config: VelesDBConfig);
146
+ private validateConfig;
147
+ private createBackend;
148
+ /**
149
+ * Initialize the client
150
+ * Must be called before any other operations
151
+ */
152
+ init(): Promise<void>;
153
+ /**
154
+ * Check if client is initialized
155
+ */
156
+ isInitialized(): boolean;
157
+ private ensureInitialized;
158
+ /**
159
+ * Create a new collection
160
+ *
161
+ * @param name - Collection name
162
+ * @param config - Collection configuration
163
+ */
164
+ createCollection(name: string, config: CollectionConfig): Promise<void>;
165
+ /**
166
+ * Delete a collection
167
+ *
168
+ * @param name - Collection name
169
+ */
170
+ deleteCollection(name: string): Promise<void>;
171
+ /**
172
+ * Get collection information
173
+ *
174
+ * @param name - Collection name
175
+ * @returns Collection info or null if not found
176
+ */
177
+ getCollection(name: string): Promise<Collection | null>;
178
+ /**
179
+ * List all collections
180
+ *
181
+ * @returns Array of collections
182
+ */
183
+ listCollections(): Promise<Collection[]>;
184
+ /**
185
+ * Insert a vector document
186
+ *
187
+ * @param collection - Collection name
188
+ * @param doc - Document to insert
189
+ */
190
+ insert(collection: string, doc: VectorDocument): Promise<void>;
191
+ /**
192
+ * Insert multiple vector documents
193
+ *
194
+ * @param collection - Collection name
195
+ * @param docs - Documents to insert
196
+ */
197
+ insertBatch(collection: string, docs: VectorDocument[]): Promise<void>;
198
+ private validateDocument;
199
+ /**
200
+ * Search for similar vectors
201
+ *
202
+ * @param collection - Collection name
203
+ * @param query - Query vector
204
+ * @param options - Search options
205
+ * @returns Search results sorted by relevance
206
+ */
207
+ search(collection: string, query: number[] | Float32Array, options?: SearchOptions): Promise<SearchResult[]>;
208
+ /**
209
+ * Delete a vector by ID
210
+ *
211
+ * @param collection - Collection name
212
+ * @param id - Document ID
213
+ * @returns true if deleted, false if not found
214
+ */
215
+ delete(collection: string, id: string | number): Promise<boolean>;
216
+ /**
217
+ * Get a vector by ID
218
+ *
219
+ * @param collection - Collection name
220
+ * @param id - Document ID
221
+ * @returns Document or null if not found
222
+ */
223
+ get(collection: string, id: string | number): Promise<VectorDocument | null>;
224
+ /**
225
+ * Close the client and release resources
226
+ */
227
+ close(): Promise<void>;
228
+ /**
229
+ * Get the current backend type
230
+ */
231
+ get backendType(): string;
232
+ }
233
+
234
+ /**
235
+ * WASM Backend for VelesDB
236
+ *
237
+ * Uses velesdb-wasm for in-browser/Node.js vector operations
238
+ */
239
+
240
+ /**
241
+ * WASM Backend
242
+ *
243
+ * Provides vector storage using WebAssembly for optimal performance
244
+ * in browser and Node.js environments.
245
+ */
246
+ declare class WasmBackend implements IVelesDBBackend {
247
+ private wasmModule;
248
+ private collections;
249
+ private _initialized;
250
+ init(): Promise<void>;
251
+ isInitialized(): boolean;
252
+ private ensureInitialized;
253
+ createCollection(name: string, config: CollectionConfig): Promise<void>;
254
+ deleteCollection(name: string): Promise<void>;
255
+ getCollection(name: string): Promise<Collection | null>;
256
+ listCollections(): Promise<Collection[]>;
257
+ insert(collectionName: string, doc: VectorDocument): Promise<void>;
258
+ insertBatch(collectionName: string, docs: VectorDocument[]): Promise<void>;
259
+ search(collectionName: string, query: number[] | Float32Array, options?: SearchOptions): Promise<SearchResult[]>;
260
+ delete(collectionName: string, id: string | number): Promise<boolean>;
261
+ get(collectionName: string, id: string | number): Promise<VectorDocument | null>;
262
+ close(): Promise<void>;
263
+ private toNumericId;
264
+ }
265
+
266
+ /**
267
+ * REST Backend for VelesDB
268
+ *
269
+ * Connects to VelesDB server via REST API
270
+ */
271
+
272
+ /**
273
+ * REST Backend
274
+ *
275
+ * Provides vector storage via VelesDB REST API server.
276
+ */
277
+ declare class RestBackend implements IVelesDBBackend {
278
+ private readonly baseUrl;
279
+ private readonly apiKey?;
280
+ private readonly timeout;
281
+ private _initialized;
282
+ constructor(url: string, apiKey?: string, timeout?: number);
283
+ init(): Promise<void>;
284
+ isInitialized(): boolean;
285
+ private ensureInitialized;
286
+ private request;
287
+ createCollection(name: string, config: CollectionConfig): Promise<void>;
288
+ deleteCollection(name: string): Promise<void>;
289
+ getCollection(name: string): Promise<Collection | null>;
290
+ listCollections(): Promise<Collection[]>;
291
+ insert(collection: string, doc: VectorDocument): Promise<void>;
292
+ insertBatch(collection: string, docs: VectorDocument[]): Promise<void>;
293
+ search(collection: string, query: number[] | Float32Array, options?: SearchOptions): Promise<SearchResult[]>;
294
+ delete(collection: string, id: string | number): Promise<boolean>;
295
+ get(collection: string, id: string | number): Promise<VectorDocument | null>;
296
+ close(): Promise<void>;
297
+ }
298
+
299
+ export { type BackendType, type Collection, type CollectionConfig, ConnectionError, type DistanceMetric, type IVelesDBBackend, NotFoundError, RestBackend, type SearchOptions, type SearchResult, ValidationError, type VectorDocument, VelesDB, type VelesDBConfig, VelesDBError, WasmBackend };