vector-index 0.0.1 → 0.1.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.
Files changed (46) hide show
  1. package/LICENSE +201 -21
  2. package/README.md +1447 -12
  3. package/build-browser.js +67 -0
  4. package/index.js +38 -6
  5. package/package.json +70 -6
  6. package/src/async.js +458 -0
  7. package/src/clustering.js +226 -0
  8. package/src/embeddings/als.js +211 -0
  9. package/src/embeddings/bpr.js +149 -0
  10. package/src/embeddings/embeddings.js +222 -0
  11. package/src/embeddings/evaluate.js +193 -0
  12. package/src/embeddings/graph.js +376 -0
  13. package/src/embeddings/idmap.js +120 -0
  14. package/src/embeddings/interactions.js +123 -0
  15. package/src/embeddings/memory.js +52 -0
  16. package/src/embeddings/node2vec.js +142 -0
  17. package/src/embeddings/sgns.js +191 -0
  18. package/src/embeddings/skipgram.js +128 -0
  19. package/src/embeddings/trainer.js +147 -0
  20. package/src/embeddings/walker.js +208 -0
  21. package/src/errors.js +41 -0
  22. package/src/heap.js +82 -0
  23. package/src/index/block-codec.js +191 -0
  24. package/src/index/diskann-block-engine.js +891 -0
  25. package/src/index/diskann.js +331 -0
  26. package/src/index/engine-common.js +159 -0
  27. package/src/index/flat.js +49 -0
  28. package/src/index/hnsw.js +282 -0
  29. package/src/index/ivf.js +232 -0
  30. package/src/index/prune.js +70 -0
  31. package/src/index/vector-index.js +391 -0
  32. package/src/lru.js +32 -0
  33. package/src/math.js +666 -0
  34. package/src/metric.js +62 -0
  35. package/src/quant/bq.js +172 -0
  36. package/src/quant/pq.js +418 -0
  37. package/src/quant/scan.js +52 -0
  38. package/src/quant/sq.js +274 -0
  39. package/src/quant/turboquant.js +527 -0
  40. package/src/reduce/pca.js +253 -0
  41. package/src/results.js +86 -0
  42. package/src/search.js +52 -0
  43. package/src/sparse/sparse-index.js +349 -0
  44. package/src/store.js +476 -0
  45. package/src/typed.js +23 -0
  46. package/src/validate.js +130 -0
package/src/store.js ADDED
@@ -0,0 +1,476 @@
1
+ /*
2
+ * vector-index — Apache-2.0 — https://github.com/colocohen/vector-index
3
+ */
4
+
5
+ // ===========================
6
+ // store.js — vector storage shared by the in-memory engines
7
+ //
8
+ // internal representation (none of it is visible through the public API):
9
+ //
10
+ // slot a dense integer 0, 1, 2, ... assigned on insert. every array
11
+ // below is indexed by slot. the caller's numeric id maps to a
12
+ // slot through one Map lookup at the API boundary only — graph
13
+ // traversal, heaps and visited marks work purely on slots.
14
+ // deleted Uint8Array of tombstone flags.
15
+ // visited Uint32Array of "epoch" marks: a node counts as visited in the
16
+ // current traversal when visited[slot] === epoch. starting a new
17
+ // traversal is one increment — nothing to allocate or clear.
18
+ //
19
+ // two stores, one interface — engines don't know which one they hold:
20
+ //
21
+ // createVectorStore full vectors in one Float32Array: L2-normalized for
22
+ // metric 'cosine' (similarity = dot product), as given
23
+ // for metric 'l2'.
24
+ // createCodeStore vectors in the caller's format (option `vectors`):
25
+ // whatever vectors.encode returned, back to back in one
26
+ // Uint8Array; compared through vectors.prepare /
27
+ // vectors.similarity, and vectors.decode for
28
+ // node-to-node comparisons during graph construction.
29
+ //
30
+ // interface used by the engines:
31
+ // add(id, vector) → slot remove(id) → slot liveSlot(id)
32
+ // query(vector) → handle sim(handle, slot) simSlots(a, b)
33
+ // vectorOf(slot) liveEntries() input(vector)
34
+ // newTraversal() mark(slot) idOf(slot) isDeleted(slot) onGrow(fn)
35
+ // count live capacity deletedFlags
36
+ //
37
+ // metric — the engines only ever see a similarity, higher = closer, and use
38
+ // 1 − sim as their distance:
39
+ // 'cosine' sim = ⟨q, v⟩ of unit vectors → distance 1 − cos
40
+ // 'l2' sim = 1 − ‖q − v‖² → distance ‖q − v‖²
41
+ // 'dot' inner product, reduced to l2 (Bachrach et al. 2014): every
42
+ // stored v gets one more coordinate e = √(M² − ‖v‖²), M the
43
+ // largest norm, a query gets 0 there. on these augmented
44
+ // vectors query → node is ‖q‖² + M² − 2⟨q, v⟩: the same order
45
+ // as the inner product, and node → node is a true metric, so
46
+ // graphs are built on solid ground. e is kept per slot and
47
+ // recomputed when a longer vector raises M — nothing to set.
48
+ // so every engine (greedy search, heaps, DiskANN's α-pruning, which the
49
+ // paper defines on squared L2) works unchanged for all three.
50
+ //
51
+ // nodeQuery(slot, vector): the handle of a STORED node (graph construction)
52
+ // — for 'dot' it carries the node's own e; otherwise the same as query.
53
+ // ip(handle, slot): ⟨q, v⟩ (the 'dot' score).
54
+ //
55
+ // arrays grow by doubling. engines that keep per-slot arrays of their own
56
+ // (neighbor lists) grow them alongside, via onGrow.
57
+ // ===========================
58
+
59
+ import { dotAt, l2sqAt, l2sqAtBounded } from './math.js';
60
+ import { vectorInput } from './metric.js';
61
+ import { ERR, createError, isLibraryError } from './errors.js';
62
+
63
+ // ===========================
64
+ // slot bookkeeping shared by both stores: ids, tombstones, visited epochs
65
+ // ===========================
66
+ function createSlots(initialCapacity, onGrowStore) {
67
+ let capacity = Math.max(16, initialCapacity || 1024);
68
+ let ids = new Float64Array(capacity);
69
+ let deleted = new Uint8Array(capacity);
70
+ let visited = new Uint32Array(capacity);
71
+ let epoch = 0;
72
+ let count = 0; // slots used (live + tombstones)
73
+ let live = 0;
74
+ const slotOf = new Map(); // user id → slot of its CURRENT (live or deleted) node
75
+ const growListeners = [];
76
+
77
+ function grow(min) {
78
+ let next = capacity * 2;
79
+ while (next < min) next *= 2;
80
+ const i = new Float64Array(next); i.set(ids); ids = i;
81
+ const del = new Uint8Array(next); del.set(deleted); deleted = del;
82
+ const vis = new Uint32Array(next); vis.set(visited); visited = vis;
83
+ const old = capacity;
84
+ capacity = next;
85
+ onGrowStore(capacity, old);
86
+ for (const fn of growListeners) fn(capacity, old);
87
+ }
88
+
89
+ // reserve the next slot for id. a soft-deleted id may be re-added: it gets
90
+ // a NEW slot and the old one stays behind as a tombstone (still a bridge
91
+ // in graphs, removed by compact)
92
+ function claim(id) {
93
+ const prev = slotOf.get(id);
94
+ if (prev !== undefined && !deleted[prev]) {
95
+ throw createError(ERR.DUPLICATE_ID, 'id already exists: ' + id);
96
+ }
97
+ if (count === capacity) grow(count + 1);
98
+ const slot = count;
99
+ ids[slot] = id;
100
+ deleted[slot] = 0;
101
+ return slot;
102
+ }
103
+
104
+ // make a claimed slot visible — only after the store wrote its data, so a
105
+ // failure in between (e.g. a bad encode result) leaves nothing behind
106
+ function commit(id, slot) {
107
+ count = slot + 1;
108
+ slotOf.set(id, slot);
109
+ live++;
110
+ }
111
+
112
+ function liveSlot(id) {
113
+ const slot = slotOf.get(id);
114
+ if (slot === undefined) throw createError(ERR.NOT_FOUND, 'id not found: ' + id);
115
+ if (deleted[slot]) throw createError(ERR.ALREADY_DELETED, 'id already deleted: ' + id);
116
+ return slot;
117
+ }
118
+
119
+ function remove(id) {
120
+ const slot = liveSlot(id);
121
+ deleted[slot] = 1;
122
+ live--;
123
+ return slot;
124
+ }
125
+
126
+ function newTraversal() {
127
+ epoch++;
128
+ if (epoch === 0xFFFFFFFF) { // wrapped: clear once every 4 billion traversals
129
+ visited.fill(0);
130
+ epoch = 1;
131
+ }
132
+ }
133
+
134
+ function mark(slot) {
135
+ if (visited[slot] === epoch) return false;
136
+ visited[slot] = epoch;
137
+ return true;
138
+ }
139
+
140
+ return {
141
+ claim,
142
+ commit,
143
+ liveSlot,
144
+ remove,
145
+ newTraversal,
146
+ mark,
147
+ onGrow: (fn) => growListeners.push(fn),
148
+ idOf: (slot) => ids[slot],
149
+ slotOf: (id) => {
150
+ const s = slotOf.get(id);
151
+ return s === undefined ? -1 : s;
152
+ },
153
+ isDeleted: (slot) => deleted[slot] === 1,
154
+ get count() { return count; },
155
+ get live() { return live; },
156
+ get capacity() { return capacity; },
157
+ get deletedFlags() { return deleted; }
158
+ };
159
+ }
160
+
161
+ // expose the shared bookkeeping members on a store object
162
+ function withSlots(store, slots) {
163
+ for (const key of ['liveSlot', 'remove', 'newTraversal', 'mark', 'onGrow', 'idOf', 'slotOf', 'isDeleted']) {
164
+ store[key] = slots[key];
165
+ }
166
+ for (const key of ['count', 'live', 'capacity', 'deletedFlags']) {
167
+ Object.defineProperty(store, key, { get: () => slots[key], enumerable: true });
168
+ }
169
+ return store;
170
+ }
171
+
172
+ // per-slot squared norms (l2, dot) and the extra coordinate e (dot)
173
+ function createNorms(metric, capacity) {
174
+ const dot = metric === 'dot';
175
+ let n2 = new Float64Array(capacity);
176
+ let e = dot ? new Float64Array(capacity) : null;
177
+ let M2 = 0;
178
+ let count = 0;
179
+ return {
180
+ grow(cap) {
181
+ const a = new Float64Array(cap); a.set(n2); n2 = a;
182
+ if (dot) { const b = new Float64Array(cap); b.set(e); e = b; }
183
+ },
184
+ set(slot, q) {
185
+ n2[slot] = q;
186
+ if (slot >= count) count = slot + 1;
187
+ if (!dot) return;
188
+ if (q > M2) {
189
+ // a longer vector raises M: every e changes (rare — O(log n) times
190
+ // for vectors in random order)
191
+ M2 = q;
192
+ for (let s = 0; s < count; s++) e[s] = Math.sqrt(Math.max(0, M2 - n2[s]));
193
+ } else {
194
+ e[slot] = Math.sqrt(M2 - q);
195
+ }
196
+ },
197
+ get n2() { return n2; },
198
+ get e() { return e; }
199
+ };
200
+ }
201
+
202
+ // ===========================
203
+ // createVectorStore — full vectors, contiguous
204
+ // ===========================
205
+ function createVectorStore(dimensions, initialCapacity, metric) {
206
+ const d = dimensions;
207
+ const l2 = metric === 'l2';
208
+ const dot = metric === 'dot';
209
+ let norms = null;
210
+ let vectors = null;
211
+ const slots = createSlots(initialCapacity, (cap) => {
212
+ const v = new Float32Array(cap * d);
213
+ v.set(vectors);
214
+ vectors = v;
215
+ if (norms) norms.grow(cap);
216
+ });
217
+ vectors = new Float32Array(slots.capacity * d);
218
+ const input = vectorInput(metric);
219
+ if (dot) norms = createNorms(metric, slots.capacity);
220
+
221
+ // copies `vector` into a new slot (normalized for cosine); returns the slot
222
+ function add(id, vector) {
223
+ const slot = slots.claim(id);
224
+ const off = slot * d;
225
+ if (l2 || dot) {
226
+ for (let i = 0; i < d; i++) vectors[off + i] = vector[i];
227
+ if (dot) norms.set(slot, dotAt(vectors, off, vectors, off, d));
228
+ } else {
229
+ let norm = 0;
230
+ for (let i = 0; i < d; i++) norm += vector[i] * vector[i];
231
+ const inv = norm > 0 ? 1 / Math.sqrt(norm) : 0; // a zero vector stays zero: similarity 0 to everything
232
+ for (let i = 0; i < d; i++) vectors[off + i] = vector[i] * inv;
233
+ }
234
+ slots.commit(id, slot);
235
+ return slot;
236
+ }
237
+
238
+ // a query handle: the query as the store keeps vectors (dot: plus ‖q‖²
239
+ // and its extra coordinate, 0 for a query)
240
+ function query(vector) {
241
+ if (!dot) return input(vector);
242
+ const v = input(vector);
243
+ return { v, qq: dotAt(v, 0, v, 0, d), e: 0 };
244
+ }
245
+
246
+ function nodeQuery(slot, vector) {
247
+ if (!dot) return query(vector);
248
+ const h = query(vector);
249
+ h.e = norms.e[slot];
250
+ return h;
251
+ }
252
+
253
+ // separate functions per metric: each call site stays monomorphic
254
+ // dot: 1 − ‖(q, e_q) − (v, e_v)‖² = 1 − (‖q‖² − 2⟨q, v⟩ + ‖v‖² + (e_q − e_v)²)
255
+ const sim = dot
256
+ ? (h, slot) => {
257
+ const de = h.e - norms.e[slot];
258
+ return 1 - (h.qq - 2 * dotAt(h.v, 0, vectors, slot * d, d) + norms.n2[slot] + de * de);
259
+ }
260
+ : l2
261
+ ? (h, slot) => 1 - l2sqAt(h, 0, vectors, slot * d, d)
262
+ : (h, slot) => dotAt(h, 0, vectors, slot * d, d);
263
+
264
+ const simSlots = dot
265
+ ? (a, b) => {
266
+ const de = norms.e[a] - norms.e[b];
267
+ return 1 - (l2sqAt(vectors, a * d, vectors, b * d, d) + de * de);
268
+ }
269
+ : l2
270
+ ? (a, b) => 1 - l2sqAt(vectors, a * d, vectors, b * d, d)
271
+ : (a, b) => dotAt(vectors, a * d, vectors, b * d, d);
272
+
273
+ const ip = (h, slot) => dotAt(h.v, 0, vectors, slot * d, d);
274
+
275
+ // l2 only: sim, but allowed to stop early once it's certain to be below
276
+ // minSim (early abandoning — see l2sqAtBounded). top-k scans use it.
277
+ // pays off only with enough dimensions to skip (measured: slower at 16,
278
+ // up to 5× faster at 768 on clustered data)
279
+ const simBounded = l2 && d >= 64
280
+ ? (h, slot, minSim, work) => 1 - l2sqAtBounded(h, 0, vectors, slot * d, d, 1 - minSim, work)
281
+ : null;
282
+
283
+ // the stored vector of a slot (a view — copy it before keeping it)
284
+ function vectorOf(slot) {
285
+ return vectors.subarray(slot * d, slot * d + d);
286
+ }
287
+
288
+ function liveEntries() {
289
+ const out = [];
290
+ for (let s = 0; s < slots.count; s++) {
291
+ if (!slots.isDeleted(s)) out.push({ id: slots.idOf(s), vector: vectors.slice(s * d, s * d + d) });
292
+ }
293
+ return out;
294
+ }
295
+
296
+ return withSlots({
297
+ dimensions: d,
298
+ metric: dot ? 'dot' : l2 ? 'l2' : 'cosine',
299
+ custom: false,
300
+ input,
301
+ add,
302
+ query,
303
+ nodeQuery,
304
+ ip,
305
+ sim,
306
+ simBounded,
307
+ simSlots,
308
+ vectorOf,
309
+ liveEntries
310
+ }, slots);
311
+ }
312
+
313
+ // ===========================
314
+ // createCodeStore — vectors in the caller's format (option `vectors`)
315
+ //
316
+ // format = { encode, decode, prepare, similarity } — plain synchronous
317
+ // functions supplied by the caller. the store never interprets the bytes:
318
+ //
319
+ // add encode(vector) → Uint8Array; stored back to back in one
320
+ // buffer; the size is fixed by the first one
321
+ // query → node prepare(query) once per operation, then
322
+ // similarity(prepared, data, offset) ≈ ⟨query, x⟩ per node
323
+ // node → node (graph construction) decode both and compare. decoded
324
+ // vectors are cached in a bounded map, since construction
325
+ // compares the same nodes repeatedly
326
+ //
327
+ // metric 'cosine': vectors and queries are normalized before encode /
328
+ // prepare, so ⟨query, x⟩ is the cosine.
329
+ // metric 'l2': they go in as given. the store keeps ‖x̂‖² of every stored
330
+ // code (x̂ = decode(code)) and turns the caller's inner product into a
331
+ // distance: ‖q − x̂‖² = ‖q‖² − 2⟨q, x̂⟩ + ‖x̂‖² — the same formats and the
332
+ // same quantizers work for both metrics.
333
+ //
334
+ // errors thrown by encode / decode / prepare that aren't library errors are
335
+ // wrapped as INVALID_ARGUMENT (the original on err.cause).
336
+ // ===========================
337
+ const DECODE_CACHE_LIMIT = 4096;
338
+
339
+ function createCodeStore(dimensions, format, initialCapacity, metric) {
340
+ const d = dimensions;
341
+ const l2 = metric === 'l2';
342
+ const dot = metric === 'dot';
343
+ const input = vectorInput(metric);
344
+ const similarity = format.similarity; // hot path: no property lookup per call
345
+ let bytes = 0; // per vector — learned from the first add
346
+ let data = null;
347
+ let norms = null; // l2, dot: ‖decode(code)‖² per slot (+ e for dot)
348
+ const cache = new Map(); // slot → decoded Float32Array
349
+
350
+ const slots = createSlots(initialCapacity, (cap) => {
351
+ if (norms) norms.grow(cap);
352
+ if (!data) return;
353
+ const next = new Uint8Array(cap * bytes);
354
+ next.set(data);
355
+ data = next;
356
+ });
357
+ if (l2 || dot) norms = createNorms(metric, slots.capacity);
358
+
359
+ function call(name, fn, arg) {
360
+ try {
361
+ return fn(arg);
362
+ } catch (err) {
363
+ if (isLibraryError(err)) throw err;
364
+ throw createError(ERR.INVALID_ARGUMENT, 'vectors.' + name + ' threw: ' + (err && err.message || err), err);
365
+ }
366
+ }
367
+
368
+ // `given`: bytes that are already encoded (compact moves codes as they are)
369
+ function add(id, vector, given) {
370
+ const code = given || call('encode', format.encode, input(vector));
371
+ if (!(code instanceof Uint8Array)) {
372
+ throw createError(ERR.INVALID_ARGUMENT, 'vectors.encode must return a Uint8Array, got ' + typeof code);
373
+ }
374
+ if (bytes === 0) {
375
+ if (code.length === 0) throw createError(ERR.INVALID_ARGUMENT, 'vectors.encode returned an empty Uint8Array');
376
+ bytes = code.length;
377
+ data = new Uint8Array(slots.capacity * bytes);
378
+ } else if (code.length !== bytes) {
379
+ throw createError(ERR.DIMENSION_MISMATCH,
380
+ 'vectors.encode returned ' + code.length + ' bytes, earlier vectors had ' + bytes);
381
+ }
382
+ const slot = slots.claim(id);
383
+ data.set(code, slot * bytes);
384
+ if (norms) {
385
+ cache.delete(slot);
386
+ const x = decodeSlot(slot);
387
+ norms.set(slot, dotAt(x, 0, x, 0, d));
388
+ }
389
+ slots.commit(id, slot);
390
+ return slot;
391
+ }
392
+
393
+ function decodeSlot(slot) {
394
+ let v = cache.get(slot);
395
+ if (v) return v;
396
+ const out = call('decode', format.decode, data.subarray(slot * bytes, slot * bytes + bytes));
397
+ if (!out || out.length !== d) {
398
+ throw createError(ERR.DIMENSION_MISMATCH,
399
+ 'vectors.decode returned ' + (out ? out.length : out) + ' values, expected ' + d);
400
+ }
401
+ v = out instanceof Float32Array ? out : Float32Array.from(out);
402
+ if (cache.size >= DECODE_CACHE_LIMIT) cache.clear();
403
+ cache.set(slot, v);
404
+ return v;
405
+ }
406
+
407
+ // query handle: whatever the caller's prepare returned (cosine), or that
408
+ // plus ‖q‖² (l2)
409
+ function query(vector) {
410
+ const v = input(vector);
411
+ const prepared = call('prepare', format.prepare, v);
412
+ return (l2 || dot) ? { prepared, qq: dotAt(v, 0, v, 0, d), e: 0 } : prepared;
413
+ }
414
+
415
+ function nodeQuery(slot, vector) {
416
+ const h = query(vector);
417
+ if (dot) h.e = norms.e[slot];
418
+ return h;
419
+ }
420
+
421
+ const sim = dot
422
+ ? (h, slot) => {
423
+ const de = h.e - norms.e[slot];
424
+ return 1 - (h.qq - 2 * similarity(h.prepared, data, slot * bytes) + norms.n2[slot] + de * de);
425
+ }
426
+ : l2
427
+ ? (h, slot) => 1 - Math.max(0, h.qq + norms.n2[slot] - 2 * similarity(h.prepared, data, slot * bytes))
428
+ : (prepared, slot) => similarity(prepared, data, slot * bytes);
429
+
430
+ const simSlots = dot
431
+ ? (a, b) => {
432
+ const de = norms.e[a] - norms.e[b];
433
+ return 1 - (l2sqAt(decodeSlot(a), 0, decodeSlot(b), 0, d) + de * de);
434
+ }
435
+ : l2
436
+ ? (a, b) => 1 - l2sqAt(decodeSlot(a), 0, decodeSlot(b), 0, d)
437
+ : (a, b) => dotAt(decodeSlot(a), 0, decodeSlot(b), 0, d);
438
+
439
+ const ip = (h, slot) => similarity(h.prepared, data, slot * bytes);
440
+
441
+ function vectorOf(slot) {
442
+ return decodeSlot(slot);
443
+ }
444
+
445
+ function liveEntries() {
446
+ const out = [];
447
+ for (let s = 0; s < slots.count; s++) {
448
+ if (!slots.isDeleted(s)) {
449
+ out.push({ id: slots.idOf(s), vector: decodeSlot(s), bytes: data.slice(s * bytes, s * bytes + bytes) });
450
+ }
451
+ }
452
+ return out;
453
+ }
454
+
455
+ return withSlots({
456
+ dimensions: d,
457
+ metric: dot ? 'dot' : l2 ? 'l2' : 'cosine',
458
+ custom: true,
459
+ input,
460
+ add,
461
+ query,
462
+ nodeQuery,
463
+ ip,
464
+ sim,
465
+ simSlots,
466
+ vectorOf,
467
+ liveEntries,
468
+ get bytesPerVector() { return bytes; }
469
+ }, slots);
470
+ }
471
+
472
+ export {
473
+ createSlots,
474
+ createVectorStore,
475
+ createCodeStore
476
+ };
package/src/typed.js ADDED
@@ -0,0 +1,23 @@
1
+ /*
2
+ * vector-index — Apache-2.0 — https://github.com/colocohen/vector-index
3
+ */
4
+
5
+ // ===========================
6
+ // typed-array helpers
7
+ // ===========================
8
+
9
+ // growable typed array helper
10
+ function grow(arr, minLength) {
11
+ let cap = arr.length || 16;
12
+ while (cap < minLength) cap *= 2;
13
+ const out = new arr.constructor(cap);
14
+ out.set(arr);
15
+ return out;
16
+ }
17
+
18
+ const LITTLE_ENDIAN = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
19
+
20
+ export {
21
+ grow,
22
+ LITTLE_ENDIAN
23
+ };
@@ -0,0 +1,130 @@
1
+ /*
2
+ * vector-index — Apache-2.0 — https://github.com/colocohen/vector-index
3
+ */
4
+
5
+ import { ERR, createError } from './errors.js';
6
+
7
+ // ===========================
8
+ // argument validation
9
+ // ===========================
10
+
11
+ // checks a vector-like input; returns it unchanged (no copy)
12
+ function checkVector(vec, dimensions, what) {
13
+ if (!vec || typeof vec.length !== 'number') {
14
+ throw createError(ERR.INVALID_ARGUMENT, (what || 'vector') + ' must be an array or typed array');
15
+ }
16
+ if (vec.length !== dimensions) {
17
+ throw createError(ERR.DIMENSION_MISMATCH,
18
+ (what || 'vector') + ' dimension mismatch: expected ' + dimensions + ', got ' + vec.length);
19
+ }
20
+ for (let i = 0; i < dimensions; i++) {
21
+ if (!Number.isFinite(vec[i])) {
22
+ throw createError(ERR.INVALID_ARGUMENT,
23
+ (what || 'vector') + ' contains a non-finite value at index ' + i);
24
+ }
25
+ }
26
+ return vec;
27
+ }
28
+
29
+
30
+ // checks an encoded code (Uint8Array of a fixed size)
31
+ function checkCode(code, codeSize) {
32
+ if (!(code instanceof Uint8Array)) {
33
+ throw createError(ERR.INVALID_ARGUMENT, 'code must be a Uint8Array');
34
+ }
35
+ if (code.length !== codeSize) {
36
+ throw createError(ERR.DIMENSION_MISMATCH,
37
+ 'code length mismatch: expected ' + codeSize + ', got ' + code.length);
38
+ }
39
+ return code;
40
+ }
41
+
42
+
43
+ // checks an array of vectors, as a generator step for long jobs:
44
+ // validating 200k vectors up front would itself block for tens of ms
45
+ function* checkVectorsJob(vectors, dimensions) {
46
+ if (!Array.isArray(vectors)) {
47
+ throw createError(ERR.INVALID_ARGUMENT, 'vectors must be an array of vectors');
48
+ }
49
+ for (let i = 0; i < vectors.length; i++) {
50
+ checkVector(vectors[i], dimensions, 'vector at index ' + i);
51
+ if ((i & 255) === 255) yield;
52
+ }
53
+ }
54
+
55
+ // ids are non-negative safe integers: 0 … Number.MAX_SAFE_INTEGER (2^53 − 1).
56
+ // every integer in that range is represented exactly by a JS number, so it
57
+ // round-trips through storage (8 bytes) without loss.
58
+ function checkId(id, name) {
59
+ if (typeof id !== 'number' || !Number.isSafeInteger(id) || id < 0) {
60
+ throw createError(ERR.INVALID_ARGUMENT,
61
+ (name || 'id') + ' must be an integer between 0 and Number.MAX_SAFE_INTEGER, got ' +
62
+ (typeof id === 'string' ? '"' + id + '"' : String(id)));
63
+ }
64
+ return id;
65
+ }
66
+
67
+ function checkPositiveInt(value, name) {
68
+ if (!Number.isInteger(value) || value <= 0) {
69
+ throw createError(ERR.INVALID_ARGUMENT, name + ' must be a positive integer, got ' + value);
70
+ }
71
+ return value;
72
+ }
73
+
74
+ function checkOptions(opts, allowed, fnName) {
75
+ if (opts == null) return {};
76
+ if (typeof opts !== 'object' || Array.isArray(opts)) {
77
+ throw createError(ERR.INVALID_ARGUMENT, fnName + ': options must be an object');
78
+ }
79
+ for (const key of Object.keys(opts)) {
80
+ if (!allowed.includes(key)) {
81
+ throw createError(ERR.INVALID_ARGUMENT,
82
+ fnName + ': unknown option "' + key + '" (allowed: ' + allowed.join(', ') + ')');
83
+ }
84
+ }
85
+ return opts;
86
+ }
87
+
88
+ function intOption(opts, name, def, min, max) {
89
+ const v = opts[name] === undefined ? def : opts[name];
90
+ if (!Number.isInteger(v) || v < min || v > max) {
91
+ throw createError(ERR.INVALID_ARGUMENT,
92
+ name + ' must be an integer in [' + min + ', ' + max + '], got ' + v);
93
+ }
94
+ return v;
95
+ }
96
+
97
+ function numOption(opts, name, def, min, max, exclusiveMin) {
98
+ const v = opts[name] === undefined ? def : opts[name];
99
+ if (typeof v !== 'number' || !Number.isFinite(v) || v > max || (exclusiveMin ? v <= min : v < min)) {
100
+ throw createError(ERR.INVALID_ARGUMENT,
101
+ name + ' must be a number in ' + (exclusiveMin ? '(' : '[') + min + ', ' + max + '], got ' + v);
102
+ }
103
+ return v;
104
+ }
105
+
106
+ function seedOption(opts) {
107
+ const s = opts.seed;
108
+ if (s === undefined || s === null) return (Math.random() * 0x100000000) >>> 0;
109
+ if (!Number.isInteger(s)) throw createError(ERR.INVALID_ARGUMENT, 'seed must be an integer, got ' + s);
110
+ return s >>> 0;
111
+ }
112
+
113
+ function boolOption(opts, name, def) {
114
+ const v = opts[name] === undefined ? def : opts[name];
115
+ if (typeof v !== 'boolean') throw createError(ERR.INVALID_ARGUMENT, name + ' must be a boolean, got ' + v);
116
+ return v;
117
+ }
118
+
119
+ export {
120
+ checkVector,
121
+ checkVectorsJob,
122
+ checkCode,
123
+ checkId,
124
+ checkPositiveInt,
125
+ checkOptions,
126
+ intOption,
127
+ numOption,
128
+ seedOption,
129
+ boolOption
130
+ };