vector-index 0.0.0-stage → 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 -0
  2. package/README.md +1456 -2
  3. package/build-browser.js +67 -0
  4. package/index.js +39 -0
  5. package/package.json +72 -4
  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
@@ -0,0 +1,208 @@
1
+ /*
2
+ * vector-index — Apache-2.0 — https://github.com/colocohen/vector-index
3
+ */
4
+
5
+ // ===========================
6
+ // random walks over a compiled graph snapshot
7
+ //
8
+ // three modes, picked automatically:
9
+ //
10
+ // uniform unweighted, p = q = 1 (DeepWalk): next = random neighbor. O(1).
11
+ // weighted p = q = 1 with weights: neighbor chosen ∝ weight via binary
12
+ // search in per-row cumulative weights. O(log degree).
13
+ // node2vec p ≠ 1 or q ≠ 1: second-order walk by REJECTION SAMPLING —
14
+ // draw a candidate x from the first-order rule, accept it with
15
+ // probability bias(x) / maxBias where
16
+ // bias = 1/p if x is the previous node (go back)
17
+ // 1 if x is a neighbor of the previous node (stay close)
18
+ // 1/q otherwise (move outward)
19
+ // exact node2vec transition probabilities with NO per-edge
20
+ // tables: the classic alias-table approach needs O(Σ deg²)
21
+ // memory, which is what makes node2vec impossible on large graphs.
22
+ // the neighbor test is a binary search in the sorted CSR row.
23
+ //
24
+ // walks are generated on demand, one at a time, into a reusable buffer —
25
+ // the full walk corpus is never materialized.
26
+ // ===========================
27
+
28
+ import { binarySearch, randFloat, rngState } from '../math.js';
29
+ import { ERR, createError } from '../errors.js';
30
+ import { pairedApi, runJobSync } from '../async.js';
31
+ import { checkId, checkOptions, intOption, numOption, seedOption } from '../validate.js';
32
+ import { isGraph } from './graph.js';
33
+
34
+ // shared option parsing for anything that walks
35
+ function walkOptions(opts) {
36
+ return {
37
+ walkLength: intOption(opts, 'walkLength', 80, 1, 1 << 20),
38
+ p: numOption(opts, 'p', 1, 0, 1e6, true),
39
+ q: numOption(opts, 'q', 1, 0, 1e6, true)
40
+ };
41
+ }
42
+
43
+ // cumulative weights per row (float32; precision is relative to the row sum,
44
+ // which is all sampling needs). built once per snapshot when weighted.
45
+ function* buildCumulative(csr) {
46
+ const { n, offsets, weights } = csr;
47
+ const cum = new Float32Array(weights.length);
48
+ for (let v = 0; v < n; v++) {
49
+ if ((v & 0x3FFF) === 0x3FFF) yield;
50
+ let s = 0;
51
+ for (let i = offsets[v], end = offsets[v + 1]; i < end; i++) {
52
+ s += weights[i];
53
+ cum[i] = s;
54
+ }
55
+ }
56
+ return cum;
57
+ }
58
+
59
+ // → { walkInto(start, out) → length, mode }
60
+ // start/out are internal indices; out must have room for walkLength entries.
61
+ // rng: Uint32Array(1) state (math.rngState). the walk itself is module-level
62
+ // code over a fixed-shape state object (see math.randFloat).
63
+ function createWalkEngine(csr, wopts, rng, cumulative) {
64
+ const { walkLength, p, q } = wopts;
65
+ const cum = csr.weights ? (cumulative || runJobSync(buildCumulative(csr))) : null;
66
+ const secondOrder = p !== 1 || q !== 1;
67
+ const w = {
68
+ offsets: csr.offsets,
69
+ neighbors: csr.neighbors,
70
+ cum: cum || new Float32Array(0),
71
+ weighted: cum !== null,
72
+ walkLength,
73
+ invP: 1 / p,
74
+ invQ: 1 / q,
75
+ maxBias: Math.max(1 / p, 1, 1 / q),
76
+ rng
77
+ };
78
+ return {
79
+ walkInto: secondOrder
80
+ ? (start, out) => walkSecondOrder(w, start, out)
81
+ : (start, out) => walkFirstOrder(w, start, out),
82
+ mode: secondOrder ? 'node2vec' : (cum ? 'weighted' : 'uniform'),
83
+ cumulative: cum
84
+ };
85
+ }
86
+
87
+ // one first-order step from v (deg(v) > 0)
88
+ function step(w, v) {
89
+ const offsets = w.offsets;
90
+ let lo = offsets[v];
91
+ if (!w.weighted) {
92
+ return w.neighbors[lo + Math.floor(randFloat(w.rng) * (offsets[v + 1] - lo))];
93
+ }
94
+ const cum = w.cum;
95
+ let hi = offsets[v + 1] - 1;
96
+ const r = randFloat(w.rng) * cum[hi];
97
+ while (lo < hi) { // first i with cum[i] > r
98
+ const mid = (lo + hi) >>> 1;
99
+ if (cum[mid] > r) hi = mid;
100
+ else lo = mid + 1;
101
+ }
102
+ return w.neighbors[lo];
103
+ }
104
+
105
+ function walkFirstOrder(w, start, out) {
106
+ const offsets = w.offsets, walkLength = w.walkLength;
107
+ out[0] = start;
108
+ let v = start;
109
+ let len = 1;
110
+ while (len < walkLength) {
111
+ if (offsets[v + 1] === offsets[v]) break; // dead end (directed sink)
112
+ v = step(w, v);
113
+ out[len++] = v;
114
+ }
115
+ return len;
116
+ }
117
+
118
+ function walkSecondOrder(w, start, out) {
119
+ const { offsets, neighbors, walkLength, invP, invQ, maxBias, rng } = w;
120
+ out[0] = start;
121
+ if (walkLength === 1 || offsets[start + 1] === offsets[start]) return 1;
122
+ let prev = start;
123
+ let v = step(w, start);
124
+ out[1] = v;
125
+ let len = 2;
126
+ while (len < walkLength) {
127
+ if (offsets[v + 1] === offsets[v]) break;
128
+ let x;
129
+ while (true) {
130
+ x = step(w, v);
131
+ let bias;
132
+ if (x === prev) bias = invP;
133
+ // same convention as the reference implementation: x is "close" when
134
+ // the edge x → prev exists
135
+ else if (binarySearch(neighbors, offsets[x], offsets[x + 1], prev) >= 0) bias = 1;
136
+ else bias = invQ;
137
+ if (bias >= maxBias || randFloat(rng) * maxBias < bias) break;
138
+ }
139
+ prev = v;
140
+ v = x;
141
+ out[len++] = v;
142
+ }
143
+ return len;
144
+ }
145
+
146
+ // ===========================
147
+ // createWalker(graph, { walkLength, p, q, seed }) — public walker, mainly
148
+ // for inspection and custom pipelines (createSkipGram over your own walks).
149
+ // walk(startId, cb) / walkSync(startId) → Float64Array of node ids
150
+ // ===========================
151
+ function createWalker(graph, options) {
152
+ if (!isGraph(graph)) throw createError(ERR.INVALID_ARGUMENT, 'createWalker: first argument must be a graph');
153
+ const opts = checkOptions(options, ['walkLength', 'p', 'q', 'seed'], 'createWalker');
154
+ const wopts = walkOptions(opts);
155
+ const rng = rngState(seedOption(opts));
156
+ let cached = null; // { csr, engine, buf }
157
+
158
+ function engineFor(snap) {
159
+ if (!cached || cached.csr !== snap.csr) {
160
+ cached = {
161
+ csr: snap.csr,
162
+ engine: createWalkEngine(snap.csr, wopts, rng),
163
+ buf: new Uint32Array(wopts.walkLength)
164
+ };
165
+ }
166
+ return cached;
167
+ }
168
+
169
+ function walkFrom(snap, startId) {
170
+ checkId(startId, 'startId');
171
+ const s = snap.ids.get(startId);
172
+ if (s < 0 || s >= snap.n) throw createError(ERR.NOT_FOUND, 'node ' + startId + ' is not in the graph');
173
+ const { engine, buf } = engineFor(snap);
174
+ const len = engine.walkInto(s, buf);
175
+ const out = new Float64Array(len);
176
+ for (let i = 0; i < len; i++) out[i] = snap.ids.idOf(buf[i]);
177
+ return out;
178
+ }
179
+
180
+ const api = pairedApi({
181
+ walk(startId) {
182
+ return walkFrom(graph._prepareSync(), startId);
183
+ }
184
+ });
185
+
186
+ return {
187
+ walk(startId, cb) {
188
+ if (typeof cb !== 'function') return api.walk(startId, cb); // throws the standard TypeError
189
+ graph._prepare((err, snap) => {
190
+ if (err) return cb(err);
191
+ let result;
192
+ try { result = walkFrom(snap, startId); } catch (e) { return cb(e); }
193
+ cb(null, result);
194
+ });
195
+ },
196
+ walkSync: api.walkSync,
197
+ get mode() {
198
+ return (wopts.p !== 1 || wopts.q !== 1) ? 'node2vec' : (graph.weighted ? 'weighted' : 'uniform');
199
+ }
200
+ };
201
+ }
202
+
203
+ export {
204
+ createWalkEngine,
205
+ createWalker,
206
+ walkOptions,
207
+ buildCumulative
208
+ };
package/src/errors.js ADDED
@@ -0,0 +1,41 @@
1
+ /*
2
+ * vector-index — Apache-2.0 — https://github.com/colocohen/vector-index
3
+ */
4
+
5
+ // ===========================
6
+ // errors — every error the library creates has a stable err.code, one of ERR.
7
+ // compare against these constants instead of parsing messages.
8
+ // ===========================
9
+
10
+ const ERR = Object.freeze({
11
+ INVALID_ARGUMENT: 'INVALID_ARGUMENT', // wrong type/shape/value of an argument
12
+ DIMENSION_MISMATCH: 'DIMENSION_MISMATCH', // vector or code has the wrong length
13
+ DUPLICATE_ID: 'DUPLICATE_ID', // add() of an id that is already live
14
+ NOT_FOUND: 'NOT_FOUND', // id / block does not exist
15
+ ALREADY_DELETED: 'ALREADY_DELETED', // delete() of an id that is already deleted
16
+ NOT_TRAINED: 'NOT_TRAINED', // operation needs train() first
17
+ NOT_SUPPORTED: 'NOT_SUPPORTED', // method doesn't apply to this algorithm/quantizer
18
+ STORAGE: 'STORAGE', // storage handler missing or failed
19
+ CORRUPT_DATA: 'CORRUPT_DATA', // stored bytes can't be decoded
20
+ BUSY: 'BUSY', // a Sync call while an async job runs on the object
21
+ CANCELLED: 'CANCELLED', // the job was stopped with cancel()
22
+ TOO_LARGE: 'TOO_LARGE' // exceeds a hard limit (e.g. 2^32 - 1 adjacency entries)
23
+ });
24
+
25
+ function createError(code, message, cause) {
26
+ const err = new Error(message);
27
+ err.code = code;
28
+ if (cause !== undefined) err.cause = cause;
29
+ return err;
30
+ }
31
+
32
+ const ERR_CODES = new Set(Object.values(ERR));
33
+ function isLibraryError(err) {
34
+ return !!err && ERR_CODES.has(err.code);
35
+ }
36
+
37
+ export {
38
+ ERR,
39
+ createError,
40
+ isLibraryError
41
+ };
package/src/heap.js ADDED
@@ -0,0 +1,82 @@
1
+ /*
2
+ * vector-index — Apache-2.0 — https://github.com/colocohen/vector-index
3
+ */
4
+
5
+ // ===========================
6
+ // typed binary heaps over (distance, slot) pairs — no object per entry
7
+ //
8
+ // min heap: pop() returns the smallest distance (candidates to explore)
9
+ // max heap: pop() returns the largest (a bounded result set: evict the worst)
10
+ // ===========================
11
+ function createHeap(isMax, initialCapacity) {
12
+ let cap = Math.max(16, initialCapacity || 64);
13
+ let dist = new Float64Array(cap);
14
+ let slot = new Int32Array(cap);
15
+ let size = 0;
16
+
17
+ // a before b?
18
+ const before = isMax ? (a, b) => dist[a] > dist[b] : (a, b) => dist[a] < dist[b];
19
+
20
+ function swap(a, b) {
21
+ const td = dist[a]; dist[a] = dist[b]; dist[b] = td;
22
+ const ts = slot[a]; slot[a] = slot[b]; slot[b] = ts;
23
+ }
24
+
25
+ function push(d, s) {
26
+ if (size === cap) {
27
+ cap *= 2;
28
+ const nd = new Float64Array(cap); nd.set(dist); dist = nd;
29
+ const ns = new Int32Array(cap); ns.set(slot); slot = ns;
30
+ }
31
+ let i = size++;
32
+ dist[i] = d;
33
+ slot[i] = s;
34
+ while (i > 0) {
35
+ const p = (i - 1) >> 1;
36
+ if (!before(i, p)) break;
37
+ swap(i, p);
38
+ i = p;
39
+ }
40
+ }
41
+
42
+ // removes the top; read topDist()/topSlot() first if you need them
43
+ function pop() {
44
+ size--;
45
+ if (size === 0) return;
46
+ dist[0] = dist[size];
47
+ slot[0] = slot[size];
48
+ let i = 0;
49
+ while (true) {
50
+ const l = 2 * i + 1, r = l + 1;
51
+ let m = i;
52
+ if (l < size && before(l, m)) m = l;
53
+ if (r < size && before(r, m)) m = r;
54
+ if (m === i) break;
55
+ swap(i, m);
56
+ i = m;
57
+ }
58
+ }
59
+
60
+ return {
61
+ push,
62
+ pop,
63
+ topDist: () => dist[0],
64
+ topSlot: () => slot[0],
65
+ size: () => size,
66
+ clear: () => { size = 0; },
67
+ // drain into arrays sorted closest-first (destroys the heap)
68
+ drainSorted() {
69
+ const n = size;
70
+ const outD = new Float64Array(n);
71
+ const outS = new Int32Array(n);
72
+ if (isMax) {
73
+ for (let i = n - 1; i >= 0; i--) { outD[i] = dist[0]; outS[i] = slot[0]; pop(); }
74
+ } else {
75
+ for (let i = 0; i < n; i++) { outD[i] = dist[0]; outS[i] = slot[0]; pop(); }
76
+ }
77
+ return { dist: outD, slot: outS };
78
+ }
79
+ };
80
+ }
81
+
82
+ export { createHeap };
@@ -0,0 +1,191 @@
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
+ // block codec
9
+ //
10
+ // ids are non-negative safe integers stored as float64 (exact up to 2^53 − 1).
11
+ // the vector is stored normalized for metric 'cosine' (similarity = dot
12
+ // product) and as given for 'l2' and 'dot'.
13
+ //
14
+ // layout (v4):
15
+ // [4B] magic 'DAN4'
16
+ // [1B] flags (bit 0 = deleted)
17
+ // [1B] code bits of the neighbor codes
18
+ // [8B] id (float64)
19
+ // [4B] dimensions
20
+ // [4·D] vector (float32; normalized for cosine)
21
+ // [2B] neighbor count n
22
+ // [8B ×n] neighbor ids (float64)
23
+ // [C ×n] neighbor codes (C = codeSize of the TurboQuant code)
24
+ //
25
+ // older formats (v1–v3) are rejected: such an index has to be rebuilt.
26
+ // ===========================
27
+
28
+ const MAGIC = 0x44414E34; // 'DAN4'
29
+ const OLD_MAGICS = [0x44414E4E, 0x44414E32, 0x44414E33]; // 'DANN', 'DAN2', 'DAN3'
30
+ const META_MAGIC = 0x444D4554; // 'DMET'
31
+ const META_VERSION = 5; // v3: + code bits; v4: + metric; v5: + largest squared norm
32
+ const READABLE_VERSIONS = [3, 4, 5]; // v3 indexes are cosine; v4 have no norm (cosine or l2)
33
+ const METRIC_CODES = { cosine: 0, l2: 1, dot: 2 };
34
+ const FLAG_DELETED = 1;
35
+ const NO_ENTRY = -1; // entry point slot when the index is empty
36
+ const MAX_NEIGHBORS = 0xFFFF; // neighbor count is a uint16
37
+
38
+ function createBlockCodec(dimensions, codeBits, codeSize, metric) {
39
+ const HEADER = 4 + 1 + 1 + 8 + 4; // magic + flags + code bits + id + dimensions
40
+
41
+ function encode(node) {
42
+ const n = node.neighbors.length;
43
+ if (n > MAX_NEIGHBORS) {
44
+ throw createError(ERR.INVALID_ARGUMENT, 'too many neighbors: ' + n);
45
+ }
46
+ const totalSize = HEADER + 4 * dimensions + 2 + n * (8 + codeSize);
47
+ const buffer = new ArrayBuffer(totalSize);
48
+ const view = new DataView(buffer);
49
+ const u8 = new Uint8Array(buffer);
50
+
51
+ let o = 0;
52
+ view.setUint32(o, MAGIC, true); o += 4;
53
+ view.setUint8(o, node.deleted ? FLAG_DELETED : 0); o += 1;
54
+ view.setUint8(o, codeBits); o += 1;
55
+ view.setFloat64(o, node.id, true); o += 8;
56
+ view.setUint32(o, dimensions, true); o += 4;
57
+ for (let i = 0; i < dimensions; i++) { view.setFloat32(o, node.vector[i], true); o += 4; }
58
+ view.setUint16(o, n, true); o += 2;
59
+ for (let i = 0; i < n; i++) { view.setFloat64(o, node.neighbors[i], true); o += 8; }
60
+ u8.set(node.codes.subarray(0, n * codeSize), o);
61
+ return u8;
62
+ }
63
+
64
+ function readId(view, o, what) {
65
+ const id = view.getFloat64(o, true);
66
+ if (!Number.isSafeInteger(id) || id < 0) {
67
+ throw createError(ERR.CORRUPT_DATA, 'invalid ' + what + ' in block: ' + id);
68
+ }
69
+ return id;
70
+ }
71
+
72
+ function decode(bytes) {
73
+ if (!(bytes instanceof Uint8Array) || bytes.length < HEADER) {
74
+ throw createError(ERR.CORRUPT_DATA, 'block too small or not a Uint8Array');
75
+ }
76
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
77
+ let o = 0;
78
+
79
+ const magic = view.getUint32(o, true); o += 4;
80
+ if (magic !== MAGIC) {
81
+ if (OLD_MAGICS.indexOf(magic) !== -1) {
82
+ throw createError(ERR.CORRUPT_DATA, 'block was written by an older version — the index must be rebuilt');
83
+ }
84
+ throw createError(ERR.CORRUPT_DATA, 'bad magic: expected ' + MAGIC.toString(16) + ', got ' + magic.toString(16));
85
+ }
86
+ const flags = view.getUint8(o); o += 1;
87
+ const bits = view.getUint8(o); o += 1;
88
+ if (bits !== codeBits) {
89
+ throw createError(ERR.CORRUPT_DATA, 'block uses ' + bits + '-bit codes, engine is configured for ' + codeBits);
90
+ }
91
+ const id = readId(view, o, 'id'); o += 8;
92
+ const dim = view.getUint32(o, true); o += 4;
93
+ if (dim !== dimensions) {
94
+ throw createError(ERR.DIMENSION_MISMATCH, 'dimension mismatch: block has ' + dim + ', engine expects ' + dimensions);
95
+ }
96
+ if (bytes.length < HEADER + 4 * dimensions + 2) throw createError(ERR.CORRUPT_DATA, 'block truncated');
97
+
98
+ const vector = new Float32Array(dimensions);
99
+ for (let i = 0; i < dimensions; i++) { vector[i] = view.getFloat32(o, true); o += 4; }
100
+
101
+ const n = view.getUint16(o, true); o += 2;
102
+ if (bytes.length < o + n * (8 + codeSize)) throw createError(ERR.CORRUPT_DATA, 'block truncated');
103
+ const neighbors = new Array(n);
104
+ for (let i = 0; i < n; i++) { neighbors[i] = readId(view, o, 'neighbor id'); o += 8; }
105
+ const codes = bytes.slice(o, o + n * codeSize);
106
+
107
+ return { id, vector, neighbors, codes, deleted: (flags & FLAG_DELETED) !== 0 };
108
+ }
109
+
110
+ // ---------------------------
111
+ // metadata record
112
+ // [4B] magic 'DMET' [4B] version [4B] dimensions [4B] code bits
113
+ // [8B] total (f64) [8B] deleted (f64)
114
+ // [8B] entry point id (f64, -1 = none)
115
+ // [8·D] sum of live vectors, as stored (f64)
116
+ // [4B] metric (0 = cosine, 1 = l2, 2 = dot) — v4
117
+ // [8B] largest squared norm seen (f64; the M² of metric dot) — v5
118
+ // v3 records (no metric field) are read as cosine.
119
+ // ---------------------------
120
+ const META_SIZE_V3 = 4 + 4 + 4 + 4 + 8 + 8 + 8 + 8 * dimensions;
121
+ const META_SIZES = { 3: META_SIZE_V3, 4: META_SIZE_V3 + 4, 5: META_SIZE_V3 + 4 + 8 };
122
+ const META_SIZE = META_SIZES[META_VERSION];
123
+
124
+ function encodeMeta(meta) {
125
+ const buffer = new ArrayBuffer(META_SIZE);
126
+ const view = new DataView(buffer);
127
+ let o = 0;
128
+ view.setUint32(o, META_MAGIC, true); o += 4;
129
+ view.setUint32(o, META_VERSION, true); o += 4;
130
+ view.setUint32(o, dimensions, true); o += 4;
131
+ view.setUint32(o, codeBits, true); o += 4;
132
+ view.setFloat64(o, meta.total, true); o += 8;
133
+ view.setFloat64(o, meta.deleted, true); o += 8;
134
+ view.setFloat64(o, meta.entryPointId == null ? NO_ENTRY : meta.entryPointId, true); o += 8;
135
+ for (let i = 0; i < dimensions; i++) { view.setFloat64(o, meta.sum[i], true); o += 8; }
136
+ view.setUint32(o, METRIC_CODES[metric], true); o += 4;
137
+ view.setFloat64(o, meta.maxNorm2 || 0, true);
138
+ return new Uint8Array(buffer);
139
+ }
140
+
141
+ function decodeMeta(bytes) {
142
+ if (!(bytes instanceof Uint8Array) || bytes.length < 8) {
143
+ throw createError(ERR.CORRUPT_DATA, 'metadata record too small or not a Uint8Array');
144
+ }
145
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
146
+ let o = 0;
147
+ if (view.getUint32(o, true) !== META_MAGIC) throw createError(ERR.CORRUPT_DATA, 'bad metadata record');
148
+ o += 4;
149
+ const version = view.getUint32(o, true); o += 4;
150
+ if (READABLE_VERSIONS.indexOf(version) === -1) {
151
+ throw createError(ERR.CORRUPT_DATA, 'metadata version ' + version + ' is not supported — the index must be rebuilt');
152
+ }
153
+ if (bytes.length < META_SIZES[version]) {
154
+ throw createError(ERR.CORRUPT_DATA, 'metadata record too small');
155
+ }
156
+ const dim = view.getUint32(o, true); o += 4;
157
+ if (dim !== dimensions) {
158
+ throw createError(ERR.DIMENSION_MISMATCH, 'dimension mismatch: index has ' + dim + ', engine expects ' + dimensions);
159
+ }
160
+ const bits = view.getUint32(o, true); o += 4;
161
+ if (bits !== codeBits) {
162
+ throw createError(ERR.INVALID_ARGUMENT,
163
+ 'index was built with codeBits=' + bits + ', engine is configured with codeBits=' + codeBits);
164
+ }
165
+ const total = view.getFloat64(o, true); o += 8;
166
+ const deleted = view.getFloat64(o, true); o += 8;
167
+ const entry = view.getFloat64(o, true); o += 8;
168
+ const entryPointId = entry === NO_ENTRY ? null : entry;
169
+ if (entryPointId !== null && (!Number.isSafeInteger(entryPointId) || entryPointId < 0)) {
170
+ throw createError(ERR.CORRUPT_DATA, 'invalid entry point in metadata: ' + entry);
171
+ }
172
+ const sum = new Float64Array(dimensions);
173
+ for (let i = 0; i < dimensions; i++) { sum[i] = view.getFloat64(o, true); o += 8; }
174
+ let stored = 'cosine';
175
+ if (version >= 4) {
176
+ const code = view.getUint32(o, true); o += 4;
177
+ stored = Object.keys(METRIC_CODES).find(k => METRIC_CODES[k] === code);
178
+ if (!stored) throw createError(ERR.CORRUPT_DATA, 'unknown metric code in metadata');
179
+ }
180
+ const maxNorm2 = version >= 5 ? view.getFloat64(o, true) : 0;
181
+ if (stored !== metric) {
182
+ throw createError(ERR.INVALID_ARGUMENT,
183
+ 'index was built with metric "' + stored + '", engine is configured with metric "' + metric + '"');
184
+ }
185
+ return { total, deleted, entryPointId, sum, maxNorm2 };
186
+ }
187
+
188
+ return { encode, decode, encodeMeta, decodeMeta };
189
+ }
190
+
191
+ export { createBlockCodec, MAX_NEIGHBORS };