eigen-db 4.0.0 → 4.0.1

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/CHANGELOG.md CHANGED
@@ -1,3 +1,7 @@
1
+ # v4.0.1
2
+
3
+ Fixed: the source code was stale
4
+
1
5
  # v4.0.0
2
6
 
3
7
  Changed: `query()` returns simple iterable
package/dist/eigen-db.js CHANGED
@@ -3,52 +3,7 @@ class b extends Error {
3
3
  super(`Capacity exceeded. Max vectors for this dimension size is ~${e}.`), this.name = "VectorCapacityExceededError";
4
4
  }
5
5
  }
6
- class d {
7
- /** Total number of results */
8
- length;
9
- /**
10
- * Sorted indices into the original database (by descending score).
11
- * sortedIndices[0] is the index of the best match.
12
- */
13
- sortedIndices;
14
- /** Raw scores array (not sorted, indexed by original DB position) */
15
- scores;
16
- /** Function to lazily resolve key from the slot index */
17
- resolveKey;
18
- constructor(e, t, r, s) {
19
- this.scores = e, this.sortedIndices = t, this.resolveKey = r, this.length = Math.min(s, t.length);
20
- }
21
- /**
22
- * Sort scores and return a ResultSet with lazy key resolution.
23
- *
24
- * @param scores - Float32Array of scores (one per DB vector)
25
- * @param resolveKey - Function to resolve key by original index
26
- * @param topK - Maximum number of results to include
27
- */
28
- static fromScores(e, t, r) {
29
- const s = e.length, o = new Uint32Array(s);
30
- for (let n = 0; n < s; n++) o[n] = n;
31
- return o.sort((n, a) => e[a] - e[n]), new d(e, o, t, r);
32
- }
33
- /** Fetch a single result by its rank (0 is best match) */
34
- get(e) {
35
- if (e < 0 || e >= this.length)
36
- throw new RangeError(`Rank ${e} out of bounds [0, ${this.length})`);
37
- const t = this.sortedIndices[e];
38
- return {
39
- key: this.resolveKey(t),
40
- score: this.scores[t]
41
- };
42
- }
43
- /** Helper for UI pagination. Instantiates strings only for the requested page. */
44
- getPage(e, t) {
45
- const r = e * t, s = Math.min(r + t, this.length), o = [];
46
- for (let n = r; n < s; n++)
47
- o.push(this.get(n));
48
- return o;
49
- }
50
- }
51
- class B {
6
+ class E {
52
7
  dirHandle = null;
53
8
  dirName;
54
9
  constructor(e) {
@@ -63,19 +18,19 @@ class B {
63
18
  }
64
19
  async readAll(e) {
65
20
  try {
66
- const o = await (await (await (await this.getDir()).getFileHandle(e)).getFile()).arrayBuffer();
67
- return new Uint8Array(o);
21
+ const n = await (await (await (await this.getDir()).getFileHandle(e)).getFile()).arrayBuffer();
22
+ return new Uint8Array(n);
68
23
  } catch {
69
24
  return new Uint8Array(0);
70
25
  }
71
26
  }
72
27
  async append(e, t) {
73
- const s = await (await this.getDir()).getFileHandle(e, { create: !0 }), o = await s.createWritable({ keepExistingData: !0 }), n = await s.getFile();
74
- await o.seek(n.size), await o.write(t), await o.close();
28
+ const r = await (await this.getDir()).getFileHandle(e, { create: !0 }), n = await r.createWritable({ keepExistingData: !0 }), i = await r.getFile();
29
+ await n.seek(i.size), await n.write(t), await n.close();
75
30
  }
76
31
  async write(e, t) {
77
- const o = await (await (await this.getDir()).getFileHandle(e, { create: !0 })).createWritable({ keepExistingData: !1 });
78
- await o.write(t), await o.close();
32
+ const n = await (await (await this.getDir()).getFileHandle(e, { create: !0 })).createWritable({ keepExistingData: !1 });
33
+ await n.write(t), await n.close();
79
34
  }
80
35
  async destroy() {
81
36
  await (await navigator.storage.getDirectory()).removeEntry(this.dirName, { recursive: !0 }), this.dirHandle = null;
@@ -86,11 +41,11 @@ class D {
86
41
  async readAll(e) {
87
42
  const t = this.files.get(e);
88
43
  if (!t || t.length === 0) return new Uint8Array(0);
89
- const r = t.reduce((n, a) => n + a.byteLength, 0), s = new Uint8Array(r);
90
- let o = 0;
91
- for (const n of t)
92
- s.set(n, o), o += n.byteLength;
93
- return s;
44
+ const s = t.reduce((i, o) => i + o.byteLength, 0), r = new Uint8Array(s);
45
+ let n = 0;
46
+ for (const i of t)
47
+ r.set(i, n), n += i.byteLength;
48
+ return r;
94
49
  }
95
50
  async append(e, t) {
96
51
  this.files.has(e) || this.files.set(e, []), this.files.get(e).push(new Uint8Array(t));
@@ -102,46 +57,46 @@ class D {
102
57
  this.files.clear();
103
58
  }
104
59
  }
105
- function M(i) {
60
+ function B(a) {
106
61
  let e = 0;
107
- for (let s = 0; s < i.length; s++)
108
- e += i[s] * i[s];
62
+ for (let r = 0; r < a.length; r++)
63
+ e += a[r] * a[r];
109
64
  const t = Math.sqrt(e);
110
65
  if (t === 0) return;
111
- const r = 1 / t;
112
- for (let s = 0; s < i.length; s++)
113
- i[s] *= r;
66
+ const s = 1 / t;
67
+ for (let r = 0; r < a.length; r++)
68
+ a[r] *= s;
114
69
  }
115
- function I(i, e, t, r, s) {
116
- for (let o = 0; o < r; o++) {
117
- let n = 0;
118
- const a = o * s;
119
- for (let c = 0; c < s; c++)
120
- n += i[c] * e[a + c];
121
- t[o] = n;
70
+ function M(a, e, t, s, r) {
71
+ for (let n = 0; n < s; n++) {
72
+ let i = 0;
73
+ const o = n * r;
74
+ for (let A = 0; A < r; A++)
75
+ i += a[A] * e[o + A];
76
+ t[n] = i;
122
77
  }
123
78
  }
124
- const Q = new TextEncoder(), S = new TextDecoder();
125
- function p(i) {
126
- const e = i.map((a) => Q.encode(a)), t = e.reduce((a, c) => a + 4 + c.byteLength, 0), r = new ArrayBuffer(t), s = new DataView(r), o = new Uint8Array(r);
127
- let n = 0;
128
- for (const a of e)
129
- s.setUint32(n, a.byteLength, !0), n += 4, o.set(a, n), n += a.byteLength;
130
- return o;
79
+ const I = new TextEncoder(), Q = new TextDecoder();
80
+ function S(a) {
81
+ const e = a.map((o) => I.encode(o)), t = e.reduce((o, A) => o + 4 + A.byteLength, 0), s = new ArrayBuffer(t), r = new DataView(s), n = new Uint8Array(s);
82
+ let i = 0;
83
+ for (const o of e)
84
+ r.setUint32(i, o.byteLength, !0), i += 4, n.set(o, i), i += o.byteLength;
85
+ return n;
131
86
  }
132
- function O(i) {
133
- const e = [], t = new DataView(i.buffer, i.byteOffset, i.byteLength);
134
- let r = 0;
135
- for (; r < i.byteLength; ) {
136
- const s = t.getUint32(r, !0);
137
- r += 4;
138
- const o = S.decode(i.subarray(r, r + s));
139
- e.push(o), r += s;
87
+ function O(a) {
88
+ const e = [], t = new DataView(a.buffer, a.byteOffset, a.byteLength);
89
+ let s = 0;
90
+ for (; s < a.byteLength; ) {
91
+ const r = t.getUint32(s, !0);
92
+ s += 4;
93
+ const n = Q.decode(a.subarray(s, s + r));
94
+ e.push(n), s += r;
140
95
  }
141
96
  return e;
142
97
  }
143
- const l = 65536, w = 65536;
144
- class x {
98
+ const y = 65536, d = 65536;
99
+ class p {
145
100
  memory;
146
101
  dimensions;
147
102
  queryOffset;
@@ -149,10 +104,10 @@ class x {
149
104
  _vectorCount;
150
105
  constructor(e, t = 0) {
151
106
  this.dimensions = e, this.queryOffset = 0;
152
- const r = e * 4;
153
- this.dbOffset = Math.ceil(r / l) * l;
154
- const s = t * e * 4, o = this.dbOffset + s, n = Math.max(1, Math.ceil(o / l));
155
- this.memory = new WebAssembly.Memory({ initial: n }), this._vectorCount = t;
107
+ const s = e * 4;
108
+ this.dbOffset = Math.ceil(s / y) * y;
109
+ const r = t * e * 4, n = this.dbOffset + r, i = Math.max(1, Math.ceil(n / y));
110
+ this.memory = new WebAssembly.Memory({ initial: i }), this._vectorCount = t;
156
111
  }
157
112
  /** Current number of vectors stored */
158
113
  get vectorCount() {
@@ -171,7 +126,7 @@ class x {
171
126
  * Accounts for query buffer, DB space, and scores buffer.
172
127
  */
173
128
  get maxVectors() {
174
- const e = w * l - this.dbOffset, t = this.dimensions * 4 + 4;
129
+ const e = d * y - this.dbOffset, t = this.dimensions * 4 + 4;
175
130
  return Math.floor(e / t);
176
131
  }
177
132
  /**
@@ -179,12 +134,12 @@ class x {
179
134
  * Calls memory.grow() if needed.
180
135
  */
181
136
  ensureCapacity(e) {
182
- const t = this._vectorCount + e, r = this.dbOffset + t * this.dimensions * 4 + t * 4, s = this.memory.buffer.byteLength;
183
- if (r > s) {
184
- const o = Math.ceil((r - s) / l);
185
- if (s / l + o > w)
137
+ const t = this._vectorCount + e, s = this.dbOffset + t * this.dimensions * 4 + t * 4, r = this.memory.buffer.byteLength;
138
+ if (s > r) {
139
+ const n = Math.ceil((s - r) / y);
140
+ if (r / y + n > d)
186
141
  throw new Error("WASM memory limit exceeded");
187
- this.memory.grow(o);
142
+ this.memory.grow(n);
188
143
  }
189
144
  }
190
145
  /**
@@ -199,9 +154,9 @@ class x {
199
154
  */
200
155
  appendVectors(e) {
201
156
  const t = this.dbOffset + this._vectorCount * this.dimensions * 4;
202
- let r = t;
203
- for (const s of e)
204
- new Float32Array(this.memory.buffer, r, this.dimensions).set(s), r += this.dimensions * 4;
157
+ let s = t;
158
+ for (const r of e)
159
+ new Float32Array(this.memory.buffer, s, this.dimensions).set(r), s += this.dimensions * 4;
205
160
  return this._vectorCount += e.length, t;
206
161
  }
207
162
  /**
@@ -228,8 +183,8 @@ class x {
228
183
  * Write a vector to a specific slot in the database region.
229
184
  */
230
185
  writeVector(e, t) {
231
- const r = this.dbOffset + e * this.dimensions * 4;
232
- new Float32Array(this.memory.buffer, r, this.dimensions).set(t);
186
+ const s = this.dbOffset + e * this.dimensions * 4;
187
+ new Float32Array(this.memory.buffer, s, this.dimensions).set(t);
233
188
  }
234
189
  /**
235
190
  * Reset the vector count to zero, logically clearing the database.
@@ -239,19 +194,55 @@ class x {
239
194
  this._vectorCount = 0;
240
195
  }
241
196
  }
242
- const v = "AGFzbQEAAAABDgJgAn9/AGAFf39/f38AAg8BA2VudgZtZW1vcnkCAAEDAwIAAQcaAglub3JtYWxpemUAAApzZWFyY2hfYWxsAAEKsgQCtQIFAX8BewN9AXsDf/0MAAAAAAAAAAAAAAAAAAAAACEDIAFBfHEhCEEAIQICQANAIAIgCE8NASAAIAJBAnRqIQogAyAK/QAEACAK/QAEAP3mAf3kASEDIAJBBGohAgwACwsgA/0fACAD/R8BkiAD/R8CIAP9HwOSkiEEIAghCQJAA0AgCSABTw0BIAAgCUECdGohCiAEIAoqAgAgCioCAJSSIQQgCUEBaiEJDAALCyAEkSEFIAVDAAAAAFsEQA8LQwAAgD8gBZUhBiAG/RMhB0EAIQICQANAIAIgCE8NASAAIAJBAnRqIQogCiAK/QAEACAH/eYB/QsEACACQQRqIQIMAAsLIAghCQJAA0AgCSABTw0BIAAgCUECdGohCiAKIAoqAgAgBpQ4AgAgCUEBaiEJDAALCwv4AQQCfwF7AX0GfyAEQXxxIQogBEECdCEOQQAhBQJAA0AgBSADTw0BIAEgBSAObGohCf0MAAAAAAAAAAAAAAAAAAAAACEHQQAhBgJAA0AgBiAKTw0BIAAgBkECdGohDCAJIAZBAnRqIQ0gByAM/QAEACAN/QAEAP3mAf3kASEHIAZBBGohBgwACwsgB/0fACAH/R8BkiAH/R8CIAf9HwOSkiEIIAohCwJAA0AgCyAETw0BIAAgC0ECdGohDCAJIAtBAnRqIQ0gCCAMKgIAIA0qAgCUkiEIIAtBAWohCwwACwsgAiAFQQJ0aiAIOAIAIAVBAWohBQwACwsL";
197
+ function x(a, e, t) {
198
+ const s = a.length;
199
+ if (s === 0) return [];
200
+ const r = new Uint32Array(s);
201
+ for (let o = 0; o < s; o++) r[o] = o;
202
+ r.sort((o, A) => a[A] - a[o]);
203
+ const n = Math.min(t, s), i = new Array(n);
204
+ for (let o = 0; o < n; o++) {
205
+ const A = r[o];
206
+ i[o] = { key: e(A), score: a[A] };
207
+ }
208
+ return i;
209
+ }
210
+ function v(a, e, t) {
211
+ const s = a.length;
212
+ if (s === 0) return [];
213
+ const r = new Uint32Array(s);
214
+ for (let i = 0; i < s; i++) r[i] = i;
215
+ r.sort((i, o) => a[o] - a[i]);
216
+ const n = Math.min(t, s);
217
+ return {
218
+ [Symbol.iterator]() {
219
+ let i = 0;
220
+ return {
221
+ next() {
222
+ if (i >= n) return { done: !0, value: void 0 };
223
+ const o = r[i++];
224
+ return {
225
+ done: !1,
226
+ value: { key: e(o), score: a[o] }
227
+ };
228
+ }
229
+ };
230
+ }
231
+ };
232
+ }
233
+ const k = "AGFzbQEAAAABDgJgAn9/AGAFf39/f38AAg8BA2VudgZtZW1vcnkCAAEDAwIAAQcaAglub3JtYWxpemUAAApzZWFyY2hfYWxsAAEKsgQCtQIFAX8BewN9AXsDf/0MAAAAAAAAAAAAAAAAAAAAACEDIAFBfHEhCEEAIQICQANAIAIgCE8NASAAIAJBAnRqIQogAyAK/QAEACAK/QAEAP3mAf3kASEDIAJBBGohAgwACwsgA/0fACAD/R8BkiAD/R8CIAP9HwOSkiEEIAghCQJAA0AgCSABTw0BIAAgCUECdGohCiAEIAoqAgAgCioCAJSSIQQgCUEBaiEJDAALCyAEkSEFIAVDAAAAAFsEQA8LQwAAgD8gBZUhBiAG/RMhB0EAIQICQANAIAIgCE8NASAAIAJBAnRqIQogCiAK/QAEACAH/eYB/QsEACACQQRqIQIMAAsLIAghCQJAA0AgCSABTw0BIAAgCUECdGohCiAKIAoqAgAgBpQ4AgAgCUEBaiEJDAALCwv4AQQCfwF7AX0GfyAEQXxxIQogBEECdCEOQQAhBQJAA0AgBSADTw0BIAEgBSAObGohCf0MAAAAAAAAAAAAAAAAAAAAACEHQQAhBgJAA0AgBiAKTw0BIAAgBkECdGohDCAJIAZBAnRqIQ0gByAM/QAEACAN/QAEAP3mAf3kASEHIAZBBGohBgwACwsgB/0fACAH/R8BkiAH/R8CIAf9HwOSkiEIIAohCwJAA0AgCyAETw0BIAAgC0ECdGohDCAJIAtBAnRqIQ0gCCAMKgIAIA0qAgCUkiEIIAtBAWohCwwACwsgAiAFQQJ0aiAIOAIAIAVBAWohBQwACwsL";
243
234
  function F() {
244
- const i = atob(v), e = new Uint8Array(i.length);
245
- for (let t = 0; t < i.length; t++)
246
- e[t] = i.charCodeAt(t);
235
+ const a = atob(k), e = new Uint8Array(a.length);
236
+ for (let t = 0; t < a.length; t++)
237
+ e[t] = a.charCodeAt(t);
247
238
  return e;
248
239
  }
249
- async function V(i, e) {
240
+ async function V(a, e) {
250
241
  const t = { env: { memory: e } };
251
- return (await WebAssembly.instantiate(i, t)).instance.exports;
242
+ return (await WebAssembly.instantiate(a, t)).instance.exports;
252
243
  }
253
- const u = "vectors.bin", C = "keys.bin";
254
- class E {
244
+ const u = "vectors.bin", w = "keys.bin";
245
+ class C {
255
246
  memoryManager;
256
247
  storage;
257
248
  dimensions;
@@ -263,23 +254,23 @@ class E {
263
254
  slotToKey;
264
255
  /** Whether this instance has been closed */
265
256
  closed = !1;
266
- constructor(e, t, r, s, o, n, a) {
267
- this.memoryManager = e, this.storage = t, this.dimensions = r, this.shouldNormalize = s, this.wasmExports = o, this.keyToSlot = n, this.slotToKey = a;
257
+ constructor(e, t, s, r, n, i, o) {
258
+ this.memoryManager = e, this.storage = t, this.dimensions = s, this.shouldNormalize = r, this.wasmExports = n, this.keyToSlot = i, this.slotToKey = o;
268
259
  }
269
260
  static async open(e) {
270
- const t = e.name ?? "default", r = e.storage ?? new B(t), s = e.normalize !== !1, [o, n] = await Promise.all([r.readAll(u), r.readAll(C)]), a = n.byteLength > 0 ? O(n) : [], c = o.byteLength / (e.dimensions * 4), m = /* @__PURE__ */ new Map(), y = [];
271
- for (let h = 0; h < a.length; h++)
272
- m.set(a[h], h), y[h] = a[h];
273
- const A = new x(e.dimensions, c);
274
- o.byteLength > 0 && A.loadVectorBytes(o, c);
275
- let f = null;
261
+ const t = e.name ?? "default", s = e.storage ?? new E(t), r = e.normalize !== !1, [n, i] = await Promise.all([s.readAll(u), s.readAll(w)]), o = i.byteLength > 0 ? O(i) : [], A = n.byteLength / (e.dimensions * 4), m = /* @__PURE__ */ new Map(), f = [];
262
+ for (let c = 0; c < o.length; c++)
263
+ m.set(o[c], c), f[c] = o[c];
264
+ const h = new p(e.dimensions, A);
265
+ n.byteLength > 0 && h.loadVectorBytes(n, A);
266
+ let l = null;
276
267
  const g = e.wasmBinary !== void 0 ? e.wasmBinary : F();
277
268
  if (g !== null)
278
269
  try {
279
- f = await V(g, A.memory);
270
+ l = await V(g, h.memory);
280
271
  } catch {
281
272
  }
282
- return new E(A, r, e.dimensions, s, f, m, y);
273
+ return new C(h, s, e.dimensions, r, l, m, f);
283
274
  }
284
275
  /** Total number of key-value pairs in the database */
285
276
  get size() {
@@ -289,20 +280,20 @@ class E {
289
280
  * Set a key-value pair. If the key already exists, its vector is overwritten (last-write-wins).
290
281
  * The value is a number[] or Float32Array of length equal to the configured dimensions.
291
282
  */
292
- set(e, t, r) {
283
+ set(e, t, s) {
293
284
  if (this.assertOpen(), t.length !== this.dimensions)
294
285
  throw new Error(`Vector dimension mismatch: expected ${this.dimensions}, got ${t.length}`);
295
- const s = new Float32Array(t);
296
- (r?.normalize ?? this.shouldNormalize) && this.normalizeVector(s);
297
- const n = this.keyToSlot.get(e);
298
- if (n !== void 0)
299
- this.memoryManager.writeVector(n, s);
286
+ const r = new Float32Array(t);
287
+ (s?.normalize ?? this.shouldNormalize) && this.normalizeVector(r);
288
+ const i = this.keyToSlot.get(e);
289
+ if (i !== void 0)
290
+ this.memoryManager.writeVector(i, r);
300
291
  else {
301
292
  if (this.memoryManager.vectorCount + 1 > this.memoryManager.maxVectors)
302
293
  throw new b(this.memoryManager.maxVectors);
303
294
  this.memoryManager.ensureCapacity(1);
304
- const c = this.memoryManager.vectorCount;
305
- this.memoryManager.appendVectors([s]), this.keyToSlot.set(e, c), this.slotToKey[c] = e;
295
+ const A = this.memoryManager.vectorCount;
296
+ this.memoryManager.appendVectors([r]), this.keyToSlot.set(e, A), this.slotToKey[A] = e;
306
297
  }
307
298
  }
308
299
  /**
@@ -319,8 +310,8 @@ class E {
319
310
  * Set multiple key-value pairs at once. Last-write-wins applies within the batch.
320
311
  */
321
312
  setMany(e) {
322
- for (const [t, r] of e)
323
- this.set(t, r);
313
+ for (const [t, s] of e)
314
+ this.set(t, s);
324
315
  }
325
316
  /**
326
317
  * Get vectors for multiple keys. Returns undefined for keys that don't exist.
@@ -328,42 +319,38 @@ class E {
328
319
  getMany(e) {
329
320
  return e.map((t) => this.get(t));
330
321
  }
331
- /**
332
- * Search for the most similar vectors to the given query vector.
333
- * Returns a ResultSet sorted by descending similarity score.
334
- */
335
322
  query(e, t) {
336
323
  this.assertOpen();
337
- const r = t?.topK ?? this.size;
324
+ const s = t?.topK ?? this.size, r = t && "iterable" in t && t.iterable;
338
325
  if (this.size === 0)
339
- return d.fromScores(new Float32Array(0), () => "", 0);
326
+ return [];
340
327
  if (e.length !== this.dimensions)
341
328
  throw new Error(`Query vector dimension mismatch: expected ${this.dimensions}, got ${e.length}`);
342
- const s = new Float32Array(e);
343
- (t?.normalize ?? this.shouldNormalize) && this.normalizeVector(s), this.memoryManager.writeQuery(s), this.memoryManager.ensureCapacity(0);
344
- const n = this.memoryManager.vectorCount, a = this.memoryManager.scoresOffset;
329
+ const n = new Float32Array(e);
330
+ (t?.normalize ?? this.shouldNormalize) && this.normalizeVector(n), this.memoryManager.writeQuery(n), this.memoryManager.ensureCapacity(0);
331
+ const o = this.memoryManager.vectorCount, A = this.memoryManager.scoresOffset;
345
332
  if (this.wasmExports)
346
333
  this.wasmExports.search_all(
347
334
  this.memoryManager.queryOffset,
348
335
  this.memoryManager.dbOffset,
349
- a,
350
- n,
336
+ A,
337
+ o,
351
338
  this.dimensions
352
339
  );
353
340
  else {
354
- const A = new Float32Array(
341
+ const l = new Float32Array(
355
342
  this.memoryManager.memory.buffer,
356
343
  this.memoryManager.queryOffset,
357
344
  this.dimensions
358
- ), f = new Float32Array(
345
+ ), g = new Float32Array(
359
346
  this.memoryManager.memory.buffer,
360
347
  this.memoryManager.dbOffset,
361
- n * this.dimensions
362
- ), g = new Float32Array(this.memoryManager.memory.buffer, a, n);
363
- I(A, f, g, n, this.dimensions);
348
+ o * this.dimensions
349
+ ), c = new Float32Array(this.memoryManager.memory.buffer, A, o);
350
+ M(l, g, c, o, this.dimensions);
364
351
  }
365
- const c = new Float32Array(this.memoryManager.readScores()), m = this.slotToKey, y = (A) => m[A];
366
- return d.fromScores(c, y, r);
352
+ const m = new Float32Array(this.memoryManager.readScores()), f = this.slotToKey, h = (l) => f[l];
353
+ return r ? v(m, h, s) : x(m, h, s);
367
354
  }
368
355
  /**
369
356
  * Persist the current in-memory state to storage.
@@ -372,15 +359,15 @@ class E {
372
359
  this.assertOpen();
373
360
  const e = this.memoryManager.vectorCount, t = new Uint8Array(e * this.dimensions * 4);
374
361
  if (e > 0) {
375
- const s = new Uint8Array(
362
+ const r = new Uint8Array(
376
363
  this.memoryManager.memory.buffer,
377
364
  this.memoryManager.dbOffset,
378
365
  e * this.dimensions * 4
379
366
  );
380
- t.set(s);
367
+ t.set(r);
381
368
  }
382
- const r = p(this.slotToKey);
383
- await Promise.all([this.storage.write(u, t), this.storage.write(C, r)]);
369
+ const s = S(this.slotToKey);
370
+ await Promise.all([this.storage.write(u, t), this.storage.write(w, s)]);
384
371
  }
385
372
  /**
386
373
  * Flush data to storage and release the instance.
@@ -402,10 +389,10 @@ class E {
402
389
  if (this.wasmExports) {
403
390
  const t = this.memoryManager.queryOffset;
404
391
  new Float32Array(this.memoryManager.memory.buffer, t, e.length).set(e), this.wasmExports.normalize(t, e.length);
405
- const r = new Float32Array(this.memoryManager.memory.buffer, t, e.length);
406
- e.set(r);
392
+ const s = new Float32Array(this.memoryManager.memory.buffer, t, e.length);
393
+ e.set(s);
407
394
  } else
408
- M(e);
395
+ B(e);
409
396
  }
410
397
  assertOpen() {
411
398
  if (this.closed)
@@ -413,10 +400,9 @@ class E {
413
400
  }
414
401
  }
415
402
  export {
416
- E as DB,
403
+ C as DB,
417
404
  D as InMemoryStorageProvider,
418
- B as OPFSStorageProvider,
419
- d as ResultSet,
405
+ E as OPFSStorageProvider,
420
406
  b as VectorCapacityExceededError
421
407
  };
422
408
  //# sourceMappingURL=eigen-db.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"eigen-db.js","sources":["../src/lib/errors.ts","../src/lib/result-set.ts","../src/lib/storage.ts","../src/lib/compute.ts","../src/lib/lexicon.ts","../src/lib/memory-manager.ts","../src/lib/simd-binary.ts","../src/lib/wasm-compute.ts","../src/lib/vector-db.ts"],"sourcesContent":["/**\n * Thrown when the database exceeds the 4GB WebAssembly 32-bit memory limit,\n * or the browser's available RAM.\n */\nexport class VectorCapacityExceededError extends Error {\n constructor(maxVectors: number) {\n super(`Capacity exceeded. Max vectors for this dimension size is ~${maxVectors}.`);\n this.name = \"VectorCapacityExceededError\";\n }\n}\n","/**\n * LAZY RESULT SET\n *\n * Holds pointers to sorted TypedArrays. Prevents JS heap overflow when K is massive.\n * Strings are only instantiated from the Lexicon when explicitly requested.\n */\n\nexport interface ResultItem {\n key: string;\n score: number;\n}\n\nexport type KeyResolver = (index: number) => string;\n\nexport class ResultSet {\n /** Total number of results */\n readonly length: number;\n\n /**\n * Sorted indices into the original database (by descending score).\n * sortedIndices[0] is the index of the best match.\n */\n private readonly sortedIndices: Uint32Array;\n\n /** Raw scores array (not sorted, indexed by original DB position) */\n private readonly scores: Float32Array;\n\n /** Function to lazily resolve key from the slot index */\n private readonly resolveKey: KeyResolver;\n\n constructor(\n scores: Float32Array,\n sortedIndices: Uint32Array,\n resolveKey: KeyResolver,\n topK: number,\n ) {\n this.scores = scores;\n this.sortedIndices = sortedIndices;\n this.resolveKey = resolveKey;\n this.length = Math.min(topK, sortedIndices.length);\n }\n\n /**\n * Sort scores and return a ResultSet with lazy key resolution.\n *\n * @param scores - Float32Array of scores (one per DB vector)\n * @param resolveKey - Function to resolve key by original index\n * @param topK - Maximum number of results to include\n */\n static fromScores(\n scores: Float32Array,\n resolveKey: KeyResolver,\n topK: number,\n ): ResultSet {\n const n = scores.length;\n\n // Create index array for sorting\n const indices = new Uint32Array(n);\n for (let i = 0; i < n; i++) indices[i] = i;\n\n // Sort indices by descending score\n indices.sort((a, b) => scores[b] - scores[a]);\n\n return new ResultSet(scores, indices, resolveKey, topK);\n }\n\n /** Fetch a single result by its rank (0 is best match) */\n get(rank: number): ResultItem {\n if (rank < 0 || rank >= this.length) {\n throw new RangeError(`Rank ${rank} out of bounds [0, ${this.length})`);\n }\n const dbIndex = this.sortedIndices[rank];\n return {\n key: this.resolveKey(dbIndex),\n score: this.scores[dbIndex],\n };\n }\n\n /** Helper for UI pagination. Instantiates strings only for the requested page. */\n getPage(page: number, pageSize: number): ResultItem[] {\n const start = page * pageSize;\n const end = Math.min(start + pageSize, this.length);\n const results: ResultItem[] = [];\n for (let i = start; i < end; i++) {\n results.push(this.get(i));\n }\n return results;\n }\n}\n","/**\n * Storage abstraction for append-only binary files.\n * Supports OPFS for browser and in-memory for testing.\n */\n\nexport interface StorageProvider {\n /** Read the entire contents of a file. Returns empty Uint8Array if file doesn't exist. */\n readAll(fileName: string): Promise<Uint8Array>;\n\n /** Append data to a file (creates if it doesn't exist). */\n append(fileName: string, data: Uint8Array): Promise<void>;\n\n /** Write data to a file, replacing all existing content. */\n write(fileName: string, data: Uint8Array): Promise<void>;\n\n /** Delete the storage directory and all files. */\n destroy(): Promise<void>;\n}\n\n/**\n * OPFS-backed storage provider for browser environments.\n * Uses Origin Private File System for high-performance persistent storage.\n */\nexport class OPFSStorageProvider implements StorageProvider {\n private dirHandle: FileSystemDirectoryHandle | null = null;\n private dirName: string;\n\n constructor(dirName: string) {\n this.dirName = dirName;\n }\n\n private async getDir(): Promise<FileSystemDirectoryHandle> {\n if (!this.dirHandle) {\n const root = await navigator.storage.getDirectory();\n this.dirHandle = await root.getDirectoryHandle(this.dirName, { create: true });\n }\n return this.dirHandle;\n }\n\n async readAll(fileName: string): Promise<Uint8Array> {\n try {\n const dir = await this.getDir();\n const fileHandle = await dir.getFileHandle(fileName);\n const file = await fileHandle.getFile();\n const buffer = await file.arrayBuffer();\n return new Uint8Array(buffer);\n } catch {\n return new Uint8Array(0);\n }\n }\n\n async append(fileName: string, data: Uint8Array): Promise<void> {\n const dir = await this.getDir();\n const fileHandle = await dir.getFileHandle(fileName, { create: true });\n const writable = await fileHandle.createWritable({ keepExistingData: true });\n const file = await fileHandle.getFile();\n await writable.seek(file.size);\n await writable.write(data as unknown as BufferSource);\n await writable.close();\n }\n\n async write(fileName: string, data: Uint8Array): Promise<void> {\n const dir = await this.getDir();\n const fileHandle = await dir.getFileHandle(fileName, { create: true });\n const writable = await fileHandle.createWritable({ keepExistingData: false });\n await writable.write(data as unknown as BufferSource);\n await writable.close();\n }\n\n async destroy(): Promise<void> {\n const root = await navigator.storage.getDirectory();\n await root.removeEntry(this.dirName, { recursive: true });\n this.dirHandle = null;\n }\n}\n\n/**\n * In-memory storage provider for testing.\n */\nexport class InMemoryStorageProvider implements StorageProvider {\n private files = new Map<string, Uint8Array[]>();\n\n async readAll(fileName: string): Promise<Uint8Array> {\n const chunks = this.files.get(fileName);\n if (!chunks || chunks.length === 0) return new Uint8Array(0);\n\n const totalSize = chunks.reduce((sum, c) => sum + c.byteLength, 0);\n const result = new Uint8Array(totalSize);\n let offset = 0;\n for (const chunk of chunks) {\n result.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return result;\n }\n\n async append(fileName: string, data: Uint8Array): Promise<void> {\n if (!this.files.has(fileName)) {\n this.files.set(fileName, []);\n }\n this.files.get(fileName)!.push(new Uint8Array(data));\n }\n\n async write(fileName: string, data: Uint8Array): Promise<void> {\n this.files.set(fileName, [new Uint8Array(data)]);\n }\n\n async destroy(): Promise<void> {\n this.files.clear();\n }\n}\n","/**\n * Pure JavaScript compute functions for vector operations.\n * These serve as the reference implementation and fallback when WASM SIMD is unavailable.\n */\n\n/**\n * Normalizes a vector in-place to unit length.\n * After normalization, cosine similarity reduces to a simple dot product.\n */\nexport function normalize(vec: Float32Array): void {\n let sumSq = 0;\n for (let i = 0; i < vec.length; i++) {\n sumSq += vec[i] * vec[i];\n }\n const mag = Math.sqrt(sumSq);\n if (mag === 0) return;\n const invMag = 1 / mag;\n for (let i = 0; i < vec.length; i++) {\n vec[i] *= invMag;\n }\n}\n\n/**\n * Computes dot products of query against all vectors in the database.\n * Writes scores to the output array.\n *\n * @param query - Normalized query vector (length = dimensions)\n * @param db - Contiguous flat array of normalized vectors (length = dbSize * dimensions)\n * @param scores - Output array for dot product scores (length = dbSize)\n * @param dbSize - Number of vectors in the database\n * @param dimensions - Dimensionality of each vector\n */\nexport function searchAll(\n query: Float32Array,\n db: Float32Array,\n scores: Float32Array,\n dbSize: number,\n dimensions: number,\n): void {\n for (let i = 0; i < dbSize; i++) {\n let dot = 0;\n const offset = i * dimensions;\n for (let j = 0; j < dimensions; j++) {\n dot += query[j] * db[offset + j];\n }\n scores[i] = dot;\n }\n}\n","/**\n * Lexicon: length-prefixed UTF-8 encoding for text strings.\n *\n * Format: Each entry is [4-byte uint32 length][UTF-8 bytes]\n * This allows efficient sequential reading and appending.\n */\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\n/**\n * Encodes an array of strings into a length-prefixed binary format.\n */\nexport function encodeLexicon(texts: string[]): Uint8Array {\n const encoded = texts.map((t) => encoder.encode(t));\n const totalSize = encoded.reduce((sum, e) => sum + 4 + e.byteLength, 0);\n\n const buffer = new ArrayBuffer(totalSize);\n const view = new DataView(buffer);\n const bytes = new Uint8Array(buffer);\n let offset = 0;\n\n for (const e of encoded) {\n view.setUint32(offset, e.byteLength, true); // little-endian\n offset += 4;\n bytes.set(e, offset);\n offset += e.byteLength;\n }\n\n return bytes;\n}\n\n/**\n * Decodes all strings from a length-prefixed binary buffer.\n */\nexport function decodeLexicon(data: Uint8Array): string[] {\n const result: string[] = [];\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n let offset = 0;\n\n while (offset < data.byteLength) {\n const len = view.getUint32(offset, true);\n offset += 4;\n const text = decoder.decode(data.subarray(offset, offset + len));\n result.push(text);\n offset += len;\n }\n\n return result;\n}\n\n/**\n * Decodes a single string at a given index from the lexicon.\n * Returns the string and the byte offset of the next entry.\n */\nexport function decodeLexiconAt(data: Uint8Array, index: number): string {\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n let offset = 0;\n\n for (let i = 0; i < index; i++) {\n const len = view.getUint32(offset, true);\n offset += 4 + len;\n }\n\n const len = view.getUint32(offset, true);\n offset += 4;\n return decoder.decode(data.subarray(offset, offset + len));\n}\n\n/**\n * Builds an index of byte offsets for each entry in the lexicon.\n * Enables O(1) access to any entry by index.\n */\nexport function buildLexiconIndex(data: Uint8Array): Uint32Array {\n const offsets: number[] = [];\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n let offset = 0;\n\n while (offset < data.byteLength) {\n offsets.push(offset);\n const len = view.getUint32(offset, true);\n offset += 4 + len;\n }\n\n return new Uint32Array(offsets);\n}\n\n/**\n * Decodes a string at a given byte offset in the lexicon.\n */\nexport function decodeLexiconAtOffset(data: Uint8Array, byteOffset: number): string {\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n const len = view.getUint32(byteOffset, true);\n return decoder.decode(data.subarray(byteOffset + 4, byteOffset + 4 + len));\n}\n","/**\n * Memory Manager for WASM shared memory.\n *\n * Memory Layout:\n * [ 0x00000 ] -> Query Vector Buffer (Fixed, dimensions * 4 bytes, aligned to 64KB page)\n * [ DB_OFFSET ] -> Vector Database (Grows dynamically)\n * [ Dynamic ] -> Scores Buffer (Mapped after DB during search)\n */\n\n/** WASM page size is 64KB */\nconst PAGE_SIZE = 65536;\n\n/** Maximum WASM memory: ~4GB (65536 pages of 64KB each) */\nconst MAX_PAGES = 65536;\n\nexport class MemoryManager {\n readonly memory: WebAssembly.Memory;\n readonly dimensions: number;\n readonly queryOffset: number;\n readonly dbOffset: number;\n private _vectorCount: number;\n\n constructor(dimensions: number, initialVectorCount: number = 0) {\n this.dimensions = dimensions;\n\n // Query buffer: dimensions * 4 bytes, aligned to page boundary\n this.queryOffset = 0;\n const queryBytes = dimensions * 4;\n this.dbOffset = Math.ceil(queryBytes / PAGE_SIZE) * PAGE_SIZE;\n\n // Calculate initial memory needed\n const dbBytes = initialVectorCount * dimensions * 4;\n const totalBytes = this.dbOffset + dbBytes;\n const initialPages = Math.max(1, Math.ceil(totalBytes / PAGE_SIZE));\n\n this.memory = new WebAssembly.Memory({ initial: initialPages });\n this._vectorCount = initialVectorCount;\n }\n\n /** Current number of vectors stored */\n get vectorCount(): number {\n return this._vectorCount;\n }\n\n /** Byte offset where the scores buffer starts (right after DB) */\n get scoresOffset(): number {\n return this.dbOffset + this._vectorCount * this.dimensions * 4;\n }\n\n /** Total bytes needed for scores buffer */\n get scoresBytes(): number {\n return this._vectorCount * 4;\n }\n\n /**\n * Maximum vectors that can be stored given the 4GB WASM memory limit.\n * Accounts for query buffer, DB space, and scores buffer.\n */\n get maxVectors(): number {\n const availableBytes = MAX_PAGES * PAGE_SIZE - this.dbOffset;\n // Each vector needs: dimensions * 4 bytes (DB) + 4 bytes (score)\n const bytesPerVector = this.dimensions * 4 + 4;\n return Math.floor(availableBytes / bytesPerVector);\n }\n\n /**\n * Ensures memory is large enough for the current DB + scores buffer.\n * Calls memory.grow() if needed.\n */\n ensureCapacity(additionalVectors: number): void {\n const newTotal = this._vectorCount + additionalVectors;\n const requiredBytes =\n this.dbOffset + newTotal * this.dimensions * 4 + newTotal * 4; // DB + scores\n const currentBytes = this.memory.buffer.byteLength;\n\n if (requiredBytes > currentBytes) {\n const pagesNeeded = Math.ceil((requiredBytes - currentBytes) / PAGE_SIZE);\n const currentPages = currentBytes / PAGE_SIZE;\n if (currentPages + pagesNeeded > MAX_PAGES) {\n throw new Error(\"WASM memory limit exceeded\");\n }\n this.memory.grow(pagesNeeded);\n }\n }\n\n /**\n * Write a query vector into the query buffer region.\n */\n writeQuery(vector: Float32Array): void {\n new Float32Array(this.memory.buffer, this.queryOffset, this.dimensions).set(vector);\n }\n\n /**\n * Append vectors to the database region.\n * Returns the byte offset where the new vectors were written.\n */\n appendVectors(vectors: Float32Array[]): number {\n const startOffset = this.dbOffset + this._vectorCount * this.dimensions * 4;\n let offset = startOffset;\n for (const vec of vectors) {\n new Float32Array(this.memory.buffer, offset, this.dimensions).set(vec);\n offset += this.dimensions * 4;\n }\n this._vectorCount += vectors.length;\n return startOffset;\n }\n\n /**\n * Load raw vector bytes directly into the database region.\n * Used for bulk loading from OPFS.\n */\n loadVectorBytes(data: Uint8Array, vectorCount: number): void {\n new Uint8Array(this.memory.buffer, this.dbOffset, data.byteLength).set(data);\n this._vectorCount = vectorCount;\n }\n\n /**\n * Read the scores buffer as a Float32Array view.\n */\n readScores(): Float32Array {\n return new Float32Array(this.memory.buffer, this.scoresOffset, this._vectorCount);\n }\n\n /**\n * Read the DB region for a specific vector index.\n */\n readVector(index: number): Float32Array {\n const offset = this.dbOffset + index * this.dimensions * 4;\n return new Float32Array(this.memory.buffer, offset, this.dimensions);\n }\n\n /**\n * Write a vector to a specific slot in the database region.\n */\n writeVector(index: number, vector: Float32Array): void {\n const offset = this.dbOffset + index * this.dimensions * 4;\n new Float32Array(this.memory.buffer, offset, this.dimensions).set(vector);\n }\n\n /**\n * Reset the vector count to zero, logically clearing the database.\n * WASM memory is not freed but will be overwritten on next writes.\n */\n reset(): void {\n this._vectorCount = 0;\n }\n}\n","// AUTO-GENERATED - Do not edit. Run: npx tsx scripts/compile-wat.ts\nconst SIMD_WASM_BASE64 = \"AGFzbQEAAAABDgJgAn9/AGAFf39/f38AAg8BA2VudgZtZW1vcnkCAAEDAwIAAQcaAglub3JtYWxpemUAAApzZWFyY2hfYWxsAAEKsgQCtQIFAX8BewN9AXsDf/0MAAAAAAAAAAAAAAAAAAAAACEDIAFBfHEhCEEAIQICQANAIAIgCE8NASAAIAJBAnRqIQogAyAK/QAEACAK/QAEAP3mAf3kASEDIAJBBGohAgwACwsgA/0fACAD/R8BkiAD/R8CIAP9HwOSkiEEIAghCQJAA0AgCSABTw0BIAAgCUECdGohCiAEIAoqAgAgCioCAJSSIQQgCUEBaiEJDAALCyAEkSEFIAVDAAAAAFsEQA8LQwAAgD8gBZUhBiAG/RMhB0EAIQICQANAIAIgCE8NASAAIAJBAnRqIQogCiAK/QAEACAH/eYB/QsEACACQQRqIQIMAAsLIAghCQJAA0AgCSABTw0BIAAgCUECdGohCiAKIAoqAgAgBpQ4AgAgCUEBaiEJDAALCwv4AQQCfwF7AX0GfyAEQXxxIQogBEECdCEOQQAhBQJAA0AgBSADTw0BIAEgBSAObGohCf0MAAAAAAAAAAAAAAAAAAAAACEHQQAhBgJAA0AgBiAKTw0BIAAgBkECdGohDCAJIAZBAnRqIQ0gByAM/QAEACAN/QAEAP3mAf3kASEHIAZBBGohBgwACwsgB/0fACAH/R8BkiAH/R8CIAf9HwOSkiEIIAohCwJAA0AgCyAETw0BIAAgC0ECdGohDCAJIAtBAnRqIQ0gCCAMKgIAIA0qAgCUkiEIIAtBAWohCwwACwsgAiAFQQJ0aiAIOAIAIAVBAWohBQwACwsL\";\n\nexport function getSimdWasmBinary(): Uint8Array {\n const binaryString = atob(SIMD_WASM_BASE64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\n","/**\n * WASM SIMD compute layer.\n * Compiles the hand-written WAT module and provides typed wrappers\n * that operate on shared WebAssembly.Memory.\n */\n\nexport interface WasmExports {\n normalize(ptr: number, dimensions: number): void;\n search_all(queryPtr: number, dbPtr: number, scoresPtr: number, dbSize: number, dimensions: number): void;\n}\n\n/**\n * Instantiates a WASM module with the given memory and returns typed exports.\n */\nexport async function instantiateWasm(wasmBinary: Uint8Array, memory: WebAssembly.Memory): Promise<WasmExports> {\n const importObject = { env: { memory } };\n const result = await WebAssembly.instantiate(wasmBinary, importObject);\n // WebAssembly.instantiate with a buffer returns { instance, module }\n const instance = (result as unknown as { instance: WebAssembly.Instance }).instance;\n return instance.exports as unknown as WasmExports;\n}\n","/**\n * VectorDB — Key-Value Vector Database\n *\n * Decoupled from embedding providers. Users pass pre-computed vectors\n * as number arrays (or Float32Array) with string keys.\n *\n * Supports:\n * - set/get/setMany/getMany for key-value CRUD\n * - query for similarity search (dot product on normalized vectors)\n * - flush to persist, close to flush+release, clear to wipe\n * - Last-write-wins semantics for duplicate keys (append-only storage)\n */\n\nimport { normalize, searchAll } from \"./compute\";\nimport { VectorCapacityExceededError } from \"./errors\";\nimport { decodeLexicon, encodeLexicon } from \"./lexicon\";\nimport { MemoryManager } from \"./memory-manager\";\nimport { ResultSet } from \"./result-set\";\nimport { getSimdWasmBinary } from \"./simd-binary\";\nimport type { StorageProvider } from \"./storage\";\nimport { OPFSStorageProvider } from \"./storage\";\nimport type { OpenOptions, OpenOptionsInternal, QueryOptions, SetOptions, VectorInput } from \"./types\";\nimport { instantiateWasm, type WasmExports } from \"./wasm-compute\";\n\nconst VECTORS_FILE = \"vectors.bin\";\nconst KEYS_FILE = \"keys.bin\";\n\nexport class VectorDB {\n private readonly memoryManager: MemoryManager;\n private readonly storage: StorageProvider;\n private readonly dimensions: number;\n private readonly shouldNormalize: boolean;\n private wasmExports: WasmExports | null;\n\n /** Maps key to its slot index in the vector array */\n private keyToSlot: Map<string, number>;\n\n /** Maps slot index back to its key */\n private slotToKey: string[];\n\n /** Whether this instance has been closed */\n private closed = false;\n\n private constructor(\n memoryManager: MemoryManager,\n storage: StorageProvider,\n dimensions: number,\n shouldNormalize: boolean,\n wasmExports: WasmExports | null,\n keyToSlot: Map<string, number>,\n slotToKey: string[],\n ) {\n this.memoryManager = memoryManager;\n this.storage = storage;\n this.dimensions = dimensions;\n this.shouldNormalize = shouldNormalize;\n this.wasmExports = wasmExports;\n this.keyToSlot = keyToSlot;\n this.slotToKey = slotToKey;\n }\n\n /**\n * Opens a VectorDB instance.\n * Loads existing data from storage into WASM memory.\n */\n static async open(options: OpenOptions): Promise<VectorDB>;\n static async open(options: OpenOptionsInternal): Promise<VectorDB>;\n static async open(options: OpenOptionsInternal): Promise<VectorDB> {\n const name = options.name ?? \"default\";\n const storage = options.storage ?? new OPFSStorageProvider(name);\n const shouldNormalize = options.normalize !== false;\n\n // Load existing data from storage\n const [vectorBytes, keysBytes] = await Promise.all([storage.readAll(VECTORS_FILE), storage.readAll(KEYS_FILE)]);\n\n // Decode stored keys\n const keys = keysBytes.byteLength > 0 ? decodeLexicon(keysBytes) : [];\n const vectorCount = vectorBytes.byteLength / (options.dimensions * 4);\n\n // Build key-to-slot mapping.\n // flush() always writes deduplicated state, so keys are unique on load.\n const keyToSlot = new Map<string, number>();\n const slotToKey: string[] = [];\n\n for (let i = 0; i < keys.length; i++) {\n keyToSlot.set(keys[i], i);\n slotToKey[i] = keys[i];\n }\n\n // Initialize memory manager\n const mm = new MemoryManager(options.dimensions, vectorCount);\n\n if (vectorBytes.byteLength > 0) {\n mm.loadVectorBytes(vectorBytes, vectorCount);\n }\n\n // Try to instantiate WASM SIMD module\n let wasmExports: WasmExports | null = null;\n const wasmBinary = options.wasmBinary !== undefined ? options.wasmBinary : getSimdWasmBinary();\n if (wasmBinary !== null) {\n try {\n wasmExports = await instantiateWasm(wasmBinary, mm.memory);\n } catch {\n // Fall back to JS compute\n }\n }\n\n return new VectorDB(mm, storage, options.dimensions, shouldNormalize, wasmExports, keyToSlot, slotToKey);\n }\n\n /** Total number of key-value pairs in the database */\n get size(): number {\n return this.keyToSlot.size;\n }\n\n /**\n * Set a key-value pair. If the key already exists, its vector is overwritten (last-write-wins).\n * The value is a number[] or Float32Array of length equal to the configured dimensions.\n */\n set(key: string, value: VectorInput, options?: SetOptions): void {\n this.assertOpen();\n\n if (value.length !== this.dimensions) {\n throw new Error(`Vector dimension mismatch: expected ${this.dimensions}, got ${value.length}`);\n }\n\n // Convert to Float32Array (also clones to avoid mutating caller's array)\n const vec = new Float32Array(value);\n\n // Normalize if needed\n const doNormalize = options?.normalize ?? this.shouldNormalize;\n if (doNormalize) {\n this.normalizeVector(vec);\n }\n\n const existingSlot = this.keyToSlot.get(key);\n if (existingSlot !== undefined) {\n // Overwrite existing slot\n this.memoryManager.writeVector(existingSlot, vec);\n } else {\n // Append new entry\n const newTotal = this.memoryManager.vectorCount + 1;\n if (newTotal > this.memoryManager.maxVectors) {\n throw new VectorCapacityExceededError(this.memoryManager.maxVectors);\n }\n this.memoryManager.ensureCapacity(1);\n const slotIndex = this.memoryManager.vectorCount;\n this.memoryManager.appendVectors([vec]);\n this.keyToSlot.set(key, slotIndex);\n this.slotToKey[slotIndex] = key;\n }\n }\n\n /**\n * Get the stored vector for a key. Returns undefined if the key does not exist.\n * Returns a copy of the stored vector as a plain number array.\n */\n get(key: string): number[] | undefined {\n this.assertOpen();\n\n const slot = this.keyToSlot.get(key);\n if (slot === undefined) return undefined;\n\n // Return a plain array copy so callers can't corrupt WASM memory\n return Array.from(this.memoryManager.readVector(slot));\n }\n\n /**\n * Set multiple key-value pairs at once. Last-write-wins applies within the batch.\n */\n setMany(entries: [string, VectorInput][]): void {\n for (const [key, value] of entries) {\n this.set(key, value);\n }\n }\n\n /**\n * Get vectors for multiple keys. Returns undefined for keys that don't exist.\n */\n getMany(keys: string[]): (number[] | undefined)[] {\n return keys.map((key) => this.get(key));\n }\n\n /**\n * Search for the most similar vectors to the given query vector.\n * Returns a ResultSet sorted by descending similarity score.\n */\n query(value: VectorInput, options?: QueryOptions): ResultSet {\n this.assertOpen();\n\n const k = options?.topK ?? this.size;\n\n if (this.size === 0) {\n return ResultSet.fromScores(new Float32Array(0), () => \"\", 0);\n }\n\n if (value.length !== this.dimensions) {\n throw new Error(`Query vector dimension mismatch: expected ${this.dimensions}, got ${value.length}`);\n }\n\n // Convert to Float32Array and optionally normalize the query vector\n const queryVec = new Float32Array(value);\n const doNormalize = options?.normalize ?? this.shouldNormalize;\n if (doNormalize) {\n this.normalizeVector(queryVec);\n }\n\n // Write query to WASM memory\n this.memoryManager.writeQuery(queryVec);\n\n // Ensure memory has space for scores buffer\n this.memoryManager.ensureCapacity(0);\n\n // Total vectors in memory\n const totalVectors = this.memoryManager.vectorCount;\n\n // Execute search\n const scoresOffset = this.memoryManager.scoresOffset;\n if (this.wasmExports) {\n this.wasmExports.search_all(\n this.memoryManager.queryOffset,\n this.memoryManager.dbOffset,\n scoresOffset,\n totalVectors,\n this.dimensions,\n );\n } else {\n const queryView = new Float32Array(\n this.memoryManager.memory.buffer,\n this.memoryManager.queryOffset,\n this.dimensions,\n );\n const dbView = new Float32Array(\n this.memoryManager.memory.buffer,\n this.memoryManager.dbOffset,\n totalVectors * this.dimensions,\n );\n const scoresView = new Float32Array(this.memoryManager.memory.buffer, scoresOffset, totalVectors);\n searchAll(queryView, dbView, scoresView, totalVectors, this.dimensions);\n }\n\n // Read scores (make a copy so the buffer can be reused)\n const scores = new Float32Array(this.memoryManager.readScores());\n\n // Resolve key from slot index\n const slotToKey = this.slotToKey;\n const resolveKey = (slotIndex: number): string => {\n return slotToKey[slotIndex];\n };\n\n return ResultSet.fromScores(scores, resolveKey, k);\n }\n\n /**\n * Persist the current in-memory state to storage.\n */\n async flush(): Promise<void> {\n this.assertOpen();\n\n const totalVectors = this.memoryManager.vectorCount;\n\n // Serialize vectors from WASM memory\n const vectorBytes = new Uint8Array(totalVectors * this.dimensions * 4);\n if (totalVectors > 0) {\n const src = new Uint8Array(\n this.memoryManager.memory.buffer,\n this.memoryManager.dbOffset,\n totalVectors * this.dimensions * 4,\n );\n vectorBytes.set(src);\n }\n\n // Serialize keys using lexicon format\n const keysBytes = encodeLexicon(this.slotToKey);\n\n await Promise.all([this.storage.write(VECTORS_FILE, vectorBytes), this.storage.write(KEYS_FILE, keysBytes)]);\n }\n\n /**\n * Flush data to storage and release the instance.\n * The instance cannot be used after close.\n */\n async close(): Promise<void> {\n if (this.closed) return;\n await this.flush();\n this.closed = true;\n }\n\n /**\n * Clear all data from the database and storage.\n */\n async clear(): Promise<void> {\n this.assertOpen();\n\n this.keyToSlot.clear();\n this.slotToKey.length = 0;\n this.memoryManager.reset();\n\n await this.storage.destroy();\n }\n\n /**\n * Normalize a vector using WASM (if available) or JS fallback.\n */\n private normalizeVector(vec: Float32Array): void {\n if (this.wasmExports) {\n const ptr = this.memoryManager.queryOffset;\n new Float32Array(this.memoryManager.memory.buffer, ptr, vec.length).set(vec);\n this.wasmExports.normalize(ptr, vec.length);\n const normalized = new Float32Array(this.memoryManager.memory.buffer, ptr, vec.length);\n vec.set(normalized);\n } else {\n normalize(vec);\n }\n }\n\n private assertOpen(): void {\n if (this.closed) {\n throw new Error(\"VectorDB instance has been closed\");\n }\n }\n}\n"],"names":["VectorCapacityExceededError","maxVectors","ResultSet","scores","sortedIndices","resolveKey","topK","n","indices","i","a","b","rank","dbIndex","page","pageSize","start","end","results","OPFSStorageProvider","dirName","root","fileName","buffer","data","fileHandle","writable","file","InMemoryStorageProvider","chunks","totalSize","sum","c","result","offset","chunk","normalize","vec","sumSq","mag","invMag","searchAll","query","db","dbSize","dimensions","dot","j","encoder","decoder","encodeLexicon","texts","encoded","t","e","view","bytes","decodeLexicon","len","text","PAGE_SIZE","MAX_PAGES","MemoryManager","initialVectorCount","queryBytes","dbBytes","totalBytes","initialPages","availableBytes","bytesPerVector","additionalVectors","newTotal","requiredBytes","currentBytes","pagesNeeded","vector","vectors","startOffset","vectorCount","index","SIMD_WASM_BASE64","getSimdWasmBinary","binaryString","instantiateWasm","wasmBinary","memory","importObject","VECTORS_FILE","KEYS_FILE","VectorDB","memoryManager","storage","shouldNormalize","wasmExports","keyToSlot","slotToKey","options","name","vectorBytes","keysBytes","keys","mm","key","value","existingSlot","slotIndex","slot","entries","k","queryVec","totalVectors","scoresOffset","queryView","dbView","scoresView","src","ptr","normalized"],"mappings":"AAIO,MAAMA,UAAoC,MAAM;AAAA,EACrD,YAAYC,GAAoB;AAC9B,UAAM,8DAA8DA,CAAU,GAAG,GACjF,KAAK,OAAO;AAAA,EACd;AACF;ACKO,MAAMC,EAAU;AAAA;AAAA,EAEZ;AAAA;AAAA;AAAA;AAAA;AAAA,EAMQ;AAAA;AAAA,EAGA;AAAA;AAAA,EAGA;AAAA,EAEjB,YACEC,GACAC,GACAC,GACAC,GACA;AACA,SAAK,SAASH,GACd,KAAK,gBAAgBC,GACrB,KAAK,aAAaC,GAClB,KAAK,SAAS,KAAK,IAAIC,GAAMF,EAAc,MAAM;AAAA,EACnD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASA,OAAO,WACLD,GACAE,GACAC,GACW;AACX,UAAMC,IAAIJ,EAAO,QA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;AAAA,IACpB;AACE,MAAAjF,EAAUC,CAAG;AAAA,EAEjB;AAAA,EAEQ,aAAmB;AACzB,QAAI,KAAK;AACP,YAAM,IAAI,MAAM,mCAAmC;AAAA,EAEvD;AACF;"}
1
+ {"version":3,"file":"eigen-db.js","sources":["../src/lib/errors.ts","../src/lib/storage.ts","../src/lib/compute.ts","../src/lib/lexicon.ts","../src/lib/memory-manager.ts","../src/lib/result-set.ts","../src/lib/simd-binary.ts","../src/lib/wasm-compute.ts","../src/lib/vector-db.ts"],"sourcesContent":["/**\n * Thrown when the database exceeds the 4GB WebAssembly 32-bit memory limit,\n * or the browser's available RAM.\n */\nexport class VectorCapacityExceededError extends Error {\n constructor(maxVectors: number) {\n super(`Capacity exceeded. Max vectors for this dimension size is ~${maxVectors}.`);\n this.name = \"VectorCapacityExceededError\";\n }\n}\n","/**\n * Storage abstraction for append-only binary files.\n * Supports OPFS for browser and in-memory for testing.\n */\n\nexport interface StorageProvider {\n /** Read the entire contents of a file. Returns empty Uint8Array if file doesn't exist. */\n readAll(fileName: string): Promise<Uint8Array>;\n\n /** Append data to a file (creates if it doesn't exist). */\n append(fileName: string, data: Uint8Array): Promise<void>;\n\n /** Write data to a file, replacing all existing content. */\n write(fileName: string, data: Uint8Array): Promise<void>;\n\n /** Delete the storage directory and all files. */\n destroy(): Promise<void>;\n}\n\n/**\n * OPFS-backed storage provider for browser environments.\n * Uses Origin Private File System for high-performance persistent storage.\n */\nexport class OPFSStorageProvider implements StorageProvider {\n private dirHandle: FileSystemDirectoryHandle | null = null;\n private dirName: string;\n\n constructor(dirName: string) {\n this.dirName = dirName;\n }\n\n private async getDir(): Promise<FileSystemDirectoryHandle> {\n if (!this.dirHandle) {\n const root = await navigator.storage.getDirectory();\n this.dirHandle = await root.getDirectoryHandle(this.dirName, { create: true });\n }\n return this.dirHandle;\n }\n\n async readAll(fileName: string): Promise<Uint8Array> {\n try {\n const dir = await this.getDir();\n const fileHandle = await dir.getFileHandle(fileName);\n const file = await fileHandle.getFile();\n const buffer = await file.arrayBuffer();\n return new Uint8Array(buffer);\n } catch {\n return new Uint8Array(0);\n }\n }\n\n async append(fileName: string, data: Uint8Array): Promise<void> {\n const dir = await this.getDir();\n const fileHandle = await dir.getFileHandle(fileName, { create: true });\n const writable = await fileHandle.createWritable({ keepExistingData: true });\n const file = await fileHandle.getFile();\n await writable.seek(file.size);\n await writable.write(data as unknown as BufferSource);\n await writable.close();\n }\n\n async write(fileName: string, data: Uint8Array): Promise<void> {\n const dir = await this.getDir();\n const fileHandle = await dir.getFileHandle(fileName, { create: true });\n const writable = await fileHandle.createWritable({ keepExistingData: false });\n await writable.write(data as unknown as BufferSource);\n await writable.close();\n }\n\n async destroy(): Promise<void> {\n const root = await navigator.storage.getDirectory();\n await root.removeEntry(this.dirName, { recursive: true });\n this.dirHandle = null;\n }\n}\n\n/**\n * In-memory storage provider for testing.\n */\nexport class InMemoryStorageProvider implements StorageProvider {\n private files = new Map<string, Uint8Array[]>();\n\n async readAll(fileName: string): Promise<Uint8Array> {\n const chunks = this.files.get(fileName);\n if (!chunks || chunks.length === 0) return new Uint8Array(0);\n\n const totalSize = chunks.reduce((sum, c) => sum + c.byteLength, 0);\n const result = new Uint8Array(totalSize);\n let offset = 0;\n for (const chunk of chunks) {\n result.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return result;\n }\n\n async append(fileName: string, data: Uint8Array): Promise<void> {\n if (!this.files.has(fileName)) {\n this.files.set(fileName, []);\n }\n this.files.get(fileName)!.push(new Uint8Array(data));\n }\n\n async write(fileName: string, data: Uint8Array): Promise<void> {\n this.files.set(fileName, [new Uint8Array(data)]);\n }\n\n async destroy(): Promise<void> {\n this.files.clear();\n }\n}\n","/**\n * Pure JavaScript compute functions for vector operations.\n * These serve as the reference implementation and fallback when WASM SIMD is unavailable.\n */\n\n/**\n * Normalizes a vector in-place to unit length.\n * After normalization, cosine similarity reduces to a simple dot product.\n */\nexport function normalize(vec: Float32Array): void {\n let sumSq = 0;\n for (let i = 0; i < vec.length; i++) {\n sumSq += vec[i] * vec[i];\n }\n const mag = Math.sqrt(sumSq);\n if (mag === 0) return;\n const invMag = 1 / mag;\n for (let i = 0; i < vec.length; i++) {\n vec[i] *= invMag;\n }\n}\n\n/**\n * Computes dot products of query against all vectors in the database.\n * Writes scores to the output array.\n *\n * @param query - Normalized query vector (length = dimensions)\n * @param db - Contiguous flat array of normalized vectors (length = dbSize * dimensions)\n * @param scores - Output array for dot product scores (length = dbSize)\n * @param dbSize - Number of vectors in the database\n * @param dimensions - Dimensionality of each vector\n */\nexport function searchAll(\n query: Float32Array,\n db: Float32Array,\n scores: Float32Array,\n dbSize: number,\n dimensions: number,\n): void {\n for (let i = 0; i < dbSize; i++) {\n let dot = 0;\n const offset = i * dimensions;\n for (let j = 0; j < dimensions; j++) {\n dot += query[j] * db[offset + j];\n }\n scores[i] = dot;\n }\n}\n","/**\n * Lexicon: length-prefixed UTF-8 encoding for text strings.\n *\n * Format: Each entry is [4-byte uint32 length][UTF-8 bytes]\n * This allows efficient sequential reading and appending.\n */\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\n/**\n * Encodes an array of strings into a length-prefixed binary format.\n */\nexport function encodeLexicon(texts: string[]): Uint8Array {\n const encoded = texts.map((t) => encoder.encode(t));\n const totalSize = encoded.reduce((sum, e) => sum + 4 + e.byteLength, 0);\n\n const buffer = new ArrayBuffer(totalSize);\n const view = new DataView(buffer);\n const bytes = new Uint8Array(buffer);\n let offset = 0;\n\n for (const e of encoded) {\n view.setUint32(offset, e.byteLength, true); // little-endian\n offset += 4;\n bytes.set(e, offset);\n offset += e.byteLength;\n }\n\n return bytes;\n}\n\n/**\n * Decodes all strings from a length-prefixed binary buffer.\n */\nexport function decodeLexicon(data: Uint8Array): string[] {\n const result: string[] = [];\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n let offset = 0;\n\n while (offset < data.byteLength) {\n const len = view.getUint32(offset, true);\n offset += 4;\n const text = decoder.decode(data.subarray(offset, offset + len));\n result.push(text);\n offset += len;\n }\n\n return result;\n}\n\n/**\n * Decodes a single string at a given index from the lexicon.\n * Returns the string and the byte offset of the next entry.\n */\nexport function decodeLexiconAt(data: Uint8Array, index: number): string {\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n let offset = 0;\n\n for (let i = 0; i < index; i++) {\n const len = view.getUint32(offset, true);\n offset += 4 + len;\n }\n\n const len = view.getUint32(offset, true);\n offset += 4;\n return decoder.decode(data.subarray(offset, offset + len));\n}\n\n/**\n * Builds an index of byte offsets for each entry in the lexicon.\n * Enables O(1) access to any entry by index.\n */\nexport function buildLexiconIndex(data: Uint8Array): Uint32Array {\n const offsets: number[] = [];\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n let offset = 0;\n\n while (offset < data.byteLength) {\n offsets.push(offset);\n const len = view.getUint32(offset, true);\n offset += 4 + len;\n }\n\n return new Uint32Array(offsets);\n}\n\n/**\n * Decodes a string at a given byte offset in the lexicon.\n */\nexport function decodeLexiconAtOffset(data: Uint8Array, byteOffset: number): string {\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n const len = view.getUint32(byteOffset, true);\n return decoder.decode(data.subarray(byteOffset + 4, byteOffset + 4 + len));\n}\n","/**\n * Memory Manager for WASM shared memory.\n *\n * Memory Layout:\n * [ 0x00000 ] -> Query Vector Buffer (Fixed, dimensions * 4 bytes, aligned to 64KB page)\n * [ DB_OFFSET ] -> Vector Database (Grows dynamically)\n * [ Dynamic ] -> Scores Buffer (Mapped after DB during search)\n */\n\n/** WASM page size is 64KB */\nconst PAGE_SIZE = 65536;\n\n/** Maximum WASM memory: ~4GB (65536 pages of 64KB each) */\nconst MAX_PAGES = 65536;\n\nexport class MemoryManager {\n readonly memory: WebAssembly.Memory;\n readonly dimensions: number;\n readonly queryOffset: number;\n readonly dbOffset: number;\n private _vectorCount: number;\n\n constructor(dimensions: number, initialVectorCount: number = 0) {\n this.dimensions = dimensions;\n\n // Query buffer: dimensions * 4 bytes, aligned to page boundary\n this.queryOffset = 0;\n const queryBytes = dimensions * 4;\n this.dbOffset = Math.ceil(queryBytes / PAGE_SIZE) * PAGE_SIZE;\n\n // Calculate initial memory needed\n const dbBytes = initialVectorCount * dimensions * 4;\n const totalBytes = this.dbOffset + dbBytes;\n const initialPages = Math.max(1, Math.ceil(totalBytes / PAGE_SIZE));\n\n this.memory = new WebAssembly.Memory({ initial: initialPages });\n this._vectorCount = initialVectorCount;\n }\n\n /** Current number of vectors stored */\n get vectorCount(): number {\n return this._vectorCount;\n }\n\n /** Byte offset where the scores buffer starts (right after DB) */\n get scoresOffset(): number {\n return this.dbOffset + this._vectorCount * this.dimensions * 4;\n }\n\n /** Total bytes needed for scores buffer */\n get scoresBytes(): number {\n return this._vectorCount * 4;\n }\n\n /**\n * Maximum vectors that can be stored given the 4GB WASM memory limit.\n * Accounts for query buffer, DB space, and scores buffer.\n */\n get maxVectors(): number {\n const availableBytes = MAX_PAGES * PAGE_SIZE - this.dbOffset;\n // Each vector needs: dimensions * 4 bytes (DB) + 4 bytes (score)\n const bytesPerVector = this.dimensions * 4 + 4;\n return Math.floor(availableBytes / bytesPerVector);\n }\n\n /**\n * Ensures memory is large enough for the current DB + scores buffer.\n * Calls memory.grow() if needed.\n */\n ensureCapacity(additionalVectors: number): void {\n const newTotal = this._vectorCount + additionalVectors;\n const requiredBytes =\n this.dbOffset + newTotal * this.dimensions * 4 + newTotal * 4; // DB + scores\n const currentBytes = this.memory.buffer.byteLength;\n\n if (requiredBytes > currentBytes) {\n const pagesNeeded = Math.ceil((requiredBytes - currentBytes) / PAGE_SIZE);\n const currentPages = currentBytes / PAGE_SIZE;\n if (currentPages + pagesNeeded > MAX_PAGES) {\n throw new Error(\"WASM memory limit exceeded\");\n }\n this.memory.grow(pagesNeeded);\n }\n }\n\n /**\n * Write a query vector into the query buffer region.\n */\n writeQuery(vector: Float32Array): void {\n new Float32Array(this.memory.buffer, this.queryOffset, this.dimensions).set(vector);\n }\n\n /**\n * Append vectors to the database region.\n * Returns the byte offset where the new vectors were written.\n */\n appendVectors(vectors: Float32Array[]): number {\n const startOffset = this.dbOffset + this._vectorCount * this.dimensions * 4;\n let offset = startOffset;\n for (const vec of vectors) {\n new Float32Array(this.memory.buffer, offset, this.dimensions).set(vec);\n offset += this.dimensions * 4;\n }\n this._vectorCount += vectors.length;\n return startOffset;\n }\n\n /**\n * Load raw vector bytes directly into the database region.\n * Used for bulk loading from OPFS.\n */\n loadVectorBytes(data: Uint8Array, vectorCount: number): void {\n new Uint8Array(this.memory.buffer, this.dbOffset, data.byteLength).set(data);\n this._vectorCount = vectorCount;\n }\n\n /**\n * Read the scores buffer as a Float32Array view.\n */\n readScores(): Float32Array {\n return new Float32Array(this.memory.buffer, this.scoresOffset, this._vectorCount);\n }\n\n /**\n * Read the DB region for a specific vector index.\n */\n readVector(index: number): Float32Array {\n const offset = this.dbOffset + index * this.dimensions * 4;\n return new Float32Array(this.memory.buffer, offset, this.dimensions);\n }\n\n /**\n * Write a vector to a specific slot in the database region.\n */\n writeVector(index: number, vector: Float32Array): void {\n const offset = this.dbOffset + index * this.dimensions * 4;\n new Float32Array(this.memory.buffer, offset, this.dimensions).set(vector);\n }\n\n /**\n * Reset the vector count to zero, logically clearing the database.\n * WASM memory is not freed but will be overwritten on next writes.\n */\n reset(): void {\n this._vectorCount = 0;\n }\n}\n","/**\n * RESULT HELPERS\n *\n * Utility functions for sorting scores and producing query results.\n * Two modes:\n * 1. topKResults — eagerly materializes a ResultItem[] (default query path)\n * 2. iterableResults — returns a lazy Iterable<ResultItem> where keys are\n * resolved only as each item is consumed (for pagination / streaming)\n */\n\nexport interface ResultItem {\n key: string;\n score: number;\n}\n\nexport type KeyResolver = (index: number) => string;\n\n/**\n * Sort scores descending and return the top K results as a plain array.\n * All keys are resolved eagerly.\n */\nexport function topKResults(scores: Float32Array, resolveKey: KeyResolver, topK: number): ResultItem[] {\n const n = scores.length;\n if (n === 0) return [];\n\n const indices = new Uint32Array(n);\n for (let i = 0; i < n; i++) indices[i] = i;\n indices.sort((a, b) => scores[b] - scores[a]);\n\n const k = Math.min(topK, n);\n const results: ResultItem[] = new Array(k);\n for (let i = 0; i < k; i++) {\n const idx = indices[i];\n results[i] = { key: resolveKey(idx), score: scores[idx] };\n }\n return results;\n}\n\n/**\n * Sort scores descending and return a lazy iterable over the top K results.\n * Keys are resolved only when each item is consumed, saving allocations\n * when the caller iterates partially (e.g., pagination).\n *\n * The returned iterable is re-iterable — each call to [Symbol.iterator]()\n * produces a fresh cursor over the same pre-sorted data.\n */\nexport function iterableResults(scores: Float32Array, resolveKey: KeyResolver, topK: number): Iterable<ResultItem> {\n const n = scores.length;\n if (n === 0) return [];\n\n const indices = new Uint32Array(n);\n for (let i = 0; i < n; i++) indices[i] = i;\n indices.sort((a, b) => scores[b] - scores[a]);\n\n const k = Math.min(topK, n);\n\n return {\n [Symbol.iterator](): Iterator<ResultItem> {\n let i = 0;\n return {\n next(): IteratorResult<ResultItem> {\n if (i >= k) return { done: true, value: undefined };\n const idx = indices[i++];\n return {\n done: false,\n value: { key: resolveKey(idx), score: scores[idx] },\n };\n },\n };\n },\n };\n}\n","// AUTO-GENERATED - Do not edit. Run: npx tsx scripts/compile-wat.ts\nconst SIMD_WASM_BASE64 = \"AGFzbQEAAAABDgJgAn9/AGAFf39/f38AAg8BA2VudgZtZW1vcnkCAAEDAwIAAQcaAglub3JtYWxpemUAAApzZWFyY2hfYWxsAAEKsgQCtQIFAX8BewN9AXsDf/0MAAAAAAAAAAAAAAAAAAAAACEDIAFBfHEhCEEAIQICQANAIAIgCE8NASAAIAJBAnRqIQogAyAK/QAEACAK/QAEAP3mAf3kASEDIAJBBGohAgwACwsgA/0fACAD/R8BkiAD/R8CIAP9HwOSkiEEIAghCQJAA0AgCSABTw0BIAAgCUECdGohCiAEIAoqAgAgCioCAJSSIQQgCUEBaiEJDAALCyAEkSEFIAVDAAAAAFsEQA8LQwAAgD8gBZUhBiAG/RMhB0EAIQICQANAIAIgCE8NASAAIAJBAnRqIQogCiAK/QAEACAH/eYB/QsEACACQQRqIQIMAAsLIAghCQJAA0AgCSABTw0BIAAgCUECdGohCiAKIAoqAgAgBpQ4AgAgCUEBaiEJDAALCwv4AQQCfwF7AX0GfyAEQXxxIQogBEECdCEOQQAhBQJAA0AgBSADTw0BIAEgBSAObGohCf0MAAAAAAAAAAAAAAAAAAAAACEHQQAhBgJAA0AgBiAKTw0BIAAgBkECdGohDCAJIAZBAnRqIQ0gByAM/QAEACAN/QAEAP3mAf3kASEHIAZBBGohBgwACwsgB/0fACAH/R8BkiAH/R8CIAf9HwOSkiEIIAohCwJAA0AgCyAETw0BIAAgC0ECdGohDCAJIAtBAnRqIQ0gCCAMKgIAIA0qAgCUkiEIIAtBAWohCwwACwsgAiAFQQJ0aiAIOAIAIAVBAWohBQwACwsL\";\n\nexport function getSimdWasmBinary(): Uint8Array {\n const binaryString = atob(SIMD_WASM_BASE64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\n","/**\n * WASM SIMD compute layer.\n * Compiles the hand-written WAT module and provides typed wrappers\n * that operate on shared WebAssembly.Memory.\n */\n\nexport interface WasmExports {\n normalize(ptr: number, dimensions: number): void;\n search_all(queryPtr: number, dbPtr: number, scoresPtr: number, dbSize: number, dimensions: number): void;\n}\n\n/**\n * Instantiates a WASM module with the given memory and returns typed exports.\n */\nexport async function instantiateWasm(wasmBinary: Uint8Array, memory: WebAssembly.Memory): Promise<WasmExports> {\n const importObject = { env: { memory } };\n const result = await WebAssembly.instantiate(wasmBinary, importObject);\n // WebAssembly.instantiate with a buffer returns { instance, module }\n const instance = (result as unknown as { instance: WebAssembly.Instance }).instance;\n return instance.exports as unknown as WasmExports;\n}\n","/**\n * VectorDB — Key-Value Vector Database\n *\n * Decoupled from embedding providers. Users pass pre-computed vectors\n * as number arrays (or Float32Array) with string keys.\n *\n * Supports:\n * - set/get/setMany/getMany for key-value CRUD\n * - query for similarity search (dot product on normalized vectors)\n * - flush to persist, close to flush+release, clear to wipe\n * - Last-write-wins semantics for duplicate keys (append-only storage)\n */\n\nimport { normalize, searchAll } from \"./compute\";\nimport { VectorCapacityExceededError } from \"./errors\";\nimport { decodeLexicon, encodeLexicon } from \"./lexicon\";\nimport { MemoryManager } from \"./memory-manager\";\nimport type { ResultItem } from \"./result-set\";\nimport { iterableResults, topKResults } from \"./result-set\";\nimport { getSimdWasmBinary } from \"./simd-binary\";\nimport type { StorageProvider } from \"./storage\";\nimport { OPFSStorageProvider } from \"./storage\";\nimport type {\n IterableQueryOptions,\n OpenOptions,\n OpenOptionsInternal,\n QueryOptions,\n SetOptions,\n VectorInput,\n} from \"./types\";\nimport { instantiateWasm, type WasmExports } from \"./wasm-compute\";\n\nconst VECTORS_FILE = \"vectors.bin\";\nconst KEYS_FILE = \"keys.bin\";\n\nexport class VectorDB {\n private readonly memoryManager: MemoryManager;\n private readonly storage: StorageProvider;\n private readonly dimensions: number;\n private readonly shouldNormalize: boolean;\n private wasmExports: WasmExports | null;\n\n /** Maps key to its slot index in the vector array */\n private keyToSlot: Map<string, number>;\n\n /** Maps slot index back to its key */\n private slotToKey: string[];\n\n /** Whether this instance has been closed */\n private closed = false;\n\n private constructor(\n memoryManager: MemoryManager,\n storage: StorageProvider,\n dimensions: number,\n shouldNormalize: boolean,\n wasmExports: WasmExports | null,\n keyToSlot: Map<string, number>,\n slotToKey: string[],\n ) {\n this.memoryManager = memoryManager;\n this.storage = storage;\n this.dimensions = dimensions;\n this.shouldNormalize = shouldNormalize;\n this.wasmExports = wasmExports;\n this.keyToSlot = keyToSlot;\n this.slotToKey = slotToKey;\n }\n\n /**\n * Opens a VectorDB instance.\n * Loads existing data from storage into WASM memory.\n */\n static async open(options: OpenOptions): Promise<VectorDB>;\n static async open(options: OpenOptionsInternal): Promise<VectorDB>;\n static async open(options: OpenOptionsInternal): Promise<VectorDB> {\n const name = options.name ?? \"default\";\n const storage = options.storage ?? new OPFSStorageProvider(name);\n const shouldNormalize = options.normalize !== false;\n\n // Load existing data from storage\n const [vectorBytes, keysBytes] = await Promise.all([storage.readAll(VECTORS_FILE), storage.readAll(KEYS_FILE)]);\n\n // Decode stored keys\n const keys = keysBytes.byteLength > 0 ? decodeLexicon(keysBytes) : [];\n const vectorCount = vectorBytes.byteLength / (options.dimensions * 4);\n\n // Build key-to-slot mapping.\n // flush() always writes deduplicated state, so keys are unique on load.\n const keyToSlot = new Map<string, number>();\n const slotToKey: string[] = [];\n\n for (let i = 0; i < keys.length; i++) {\n keyToSlot.set(keys[i], i);\n slotToKey[i] = keys[i];\n }\n\n // Initialize memory manager\n const mm = new MemoryManager(options.dimensions, vectorCount);\n\n if (vectorBytes.byteLength > 0) {\n mm.loadVectorBytes(vectorBytes, vectorCount);\n }\n\n // Try to instantiate WASM SIMD module\n let wasmExports: WasmExports | null = null;\n const wasmBinary = options.wasmBinary !== undefined ? options.wasmBinary : getSimdWasmBinary();\n if (wasmBinary !== null) {\n try {\n wasmExports = await instantiateWasm(wasmBinary, mm.memory);\n } catch {\n // Fall back to JS compute\n }\n }\n\n return new VectorDB(mm, storage, options.dimensions, shouldNormalize, wasmExports, keyToSlot, slotToKey);\n }\n\n /** Total number of key-value pairs in the database */\n get size(): number {\n return this.keyToSlot.size;\n }\n\n /**\n * Set a key-value pair. If the key already exists, its vector is overwritten (last-write-wins).\n * The value is a number[] or Float32Array of length equal to the configured dimensions.\n */\n set(key: string, value: VectorInput, options?: SetOptions): void {\n this.assertOpen();\n\n if (value.length !== this.dimensions) {\n throw new Error(`Vector dimension mismatch: expected ${this.dimensions}, got ${value.length}`);\n }\n\n // Convert to Float32Array (also clones to avoid mutating caller's array)\n const vec = new Float32Array(value);\n\n // Normalize if needed\n const doNormalize = options?.normalize ?? this.shouldNormalize;\n if (doNormalize) {\n this.normalizeVector(vec);\n }\n\n const existingSlot = this.keyToSlot.get(key);\n if (existingSlot !== undefined) {\n // Overwrite existing slot\n this.memoryManager.writeVector(existingSlot, vec);\n } else {\n // Append new entry\n const newTotal = this.memoryManager.vectorCount + 1;\n if (newTotal > this.memoryManager.maxVectors) {\n throw new VectorCapacityExceededError(this.memoryManager.maxVectors);\n }\n this.memoryManager.ensureCapacity(1);\n const slotIndex = this.memoryManager.vectorCount;\n this.memoryManager.appendVectors([vec]);\n this.keyToSlot.set(key, slotIndex);\n this.slotToKey[slotIndex] = key;\n }\n }\n\n /**\n * Get the stored vector for a key. Returns undefined if the key does not exist.\n * Returns a copy of the stored vector as a plain number array.\n */\n get(key: string): number[] | undefined {\n this.assertOpen();\n\n const slot = this.keyToSlot.get(key);\n if (slot === undefined) return undefined;\n\n // Return a plain array copy so callers can't corrupt WASM memory\n return Array.from(this.memoryManager.readVector(slot));\n }\n\n /**\n * Set multiple key-value pairs at once. Last-write-wins applies within the batch.\n */\n setMany(entries: [string, VectorInput][]): void {\n for (const [key, value] of entries) {\n this.set(key, value);\n }\n }\n\n /**\n * Get vectors for multiple keys. Returns undefined for keys that don't exist.\n */\n getMany(keys: string[]): (number[] | undefined)[] {\n return keys.map((key) => this.get(key));\n }\n\n /**\n * Search for the most similar vectors to the given query vector.\n *\n * Default: returns a plain ResultItem[] sorted by descending similarity.\n * With `{ iterable: true }`: returns a lazy Iterable<ResultItem> where keys\n * are resolved only as each item is consumed.\n */\n query(value: VectorInput, options: IterableQueryOptions): Iterable<ResultItem>;\n query(value: VectorInput, options?: QueryOptions): ResultItem[];\n query(value: VectorInput, options?: QueryOptions | IterableQueryOptions): ResultItem[] | Iterable<ResultItem> {\n this.assertOpen();\n\n const k = options?.topK ?? this.size;\n const iterable = options && \"iterable\" in options && options.iterable;\n\n if (this.size === 0) {\n return [];\n }\n\n if (value.length !== this.dimensions) {\n throw new Error(`Query vector dimension mismatch: expected ${this.dimensions}, got ${value.length}`);\n }\n\n // Convert to Float32Array and optionally normalize the query vector\n const queryVec = new Float32Array(value);\n const doNormalize = options?.normalize ?? this.shouldNormalize;\n if (doNormalize) {\n this.normalizeVector(queryVec);\n }\n\n // Write query to WASM memory\n this.memoryManager.writeQuery(queryVec);\n\n // Ensure memory has space for scores buffer\n this.memoryManager.ensureCapacity(0);\n\n // Total vectors in memory\n const totalVectors = this.memoryManager.vectorCount;\n\n // Execute search\n const scoresOffset = this.memoryManager.scoresOffset;\n if (this.wasmExports) {\n this.wasmExports.search_all(\n this.memoryManager.queryOffset,\n this.memoryManager.dbOffset,\n scoresOffset,\n totalVectors,\n this.dimensions,\n );\n } else {\n const queryView = new Float32Array(\n this.memoryManager.memory.buffer,\n this.memoryManager.queryOffset,\n this.dimensions,\n );\n const dbView = new Float32Array(\n this.memoryManager.memory.buffer,\n this.memoryManager.dbOffset,\n totalVectors * this.dimensions,\n );\n const scoresView = new Float32Array(this.memoryManager.memory.buffer, scoresOffset, totalVectors);\n searchAll(queryView, dbView, scoresView, totalVectors, this.dimensions);\n }\n\n // Read scores (make a copy so the buffer can be reused)\n const scores = new Float32Array(this.memoryManager.readScores());\n\n // Resolve key from slot index\n const slotToKey = this.slotToKey;\n const resolveKey = (slotIndex: number): string => {\n return slotToKey[slotIndex];\n };\n\n if (iterable) {\n return iterableResults(scores, resolveKey, k);\n }\n return topKResults(scores, resolveKey, k);\n }\n\n /**\n * Persist the current in-memory state to storage.\n */\n async flush(): Promise<void> {\n this.assertOpen();\n\n const totalVectors = this.memoryManager.vectorCount;\n\n // Serialize vectors from WASM memory\n const vectorBytes = new Uint8Array(totalVectors * this.dimensions * 4);\n if (totalVectors > 0) {\n const src = new Uint8Array(\n this.memoryManager.memory.buffer,\n this.memoryManager.dbOffset,\n totalVectors * this.dimensions * 4,\n );\n vectorBytes.set(src);\n }\n\n // Serialize keys using lexicon format\n const keysBytes = encodeLexicon(this.slotToKey);\n\n await Promise.all([this.storage.write(VECTORS_FILE, vectorBytes), this.storage.write(KEYS_FILE, keysBytes)]);\n }\n\n /**\n * Flush data to storage and release the instance.\n * The instance cannot be used after close.\n */\n async close(): Promise<void> {\n if (this.closed) return;\n await this.flush();\n this.closed = true;\n }\n\n /**\n * Clear all data from the database and storage.\n */\n async clear(): Promise<void> {\n this.assertOpen();\n\n this.keyToSlot.clear();\n this.slotToKey.length = 0;\n this.memoryManager.reset();\n\n await this.storage.destroy();\n }\n\n /**\n * Normalize a vector using WASM (if available) or JS fallback.\n */\n private normalizeVector(vec: Float32Array): void {\n if (this.wasmExports) {\n const ptr = this.memoryManager.queryOffset;\n new Float32Array(this.memoryManager.memory.buffer, ptr, vec.length).set(vec);\n this.wasmExports.normalize(ptr, vec.length);\n const normalized = new Float32Array(this.memoryManager.memory.buffer, ptr, vec.length);\n vec.set(normalized);\n } else {\n normalize(vec);\n }\n }\n\n private assertOpen(): void {\n if (this.closed) {\n throw new Error(\"VectorDB instance has been closed\");\n }\n }\n}\n"],"names":["VectorCapacityExceededError","maxVectors","OPFSStorageProvider","dirName","root","fileName","buffer","data","fileHandle","writable","file","InMemoryStorageProvider","chunks","totalSize","sum","c","result","offset","chunk","normalize","vec","sumSq","i","mag","invMag","searchAll","query","db","scores","dbSize","dimensions","dot","j","encoder","decoder","encodeLexicon","texts","encoded","t","e","view","bytes","decodeLexicon","len","text","PAGE_SIZE","MAX_PAGES","MemoryManager","initialVectorCount","queryBytes","dbBytes","totalBytes","initialPages","availableBytes","bytesPerVector","additionalVectors","newTotal","requiredBytes","currentBytes","pagesNeeded","vector","vectors","startOffset","vectorCount","index","topKResults","resolveKey","topK","n","indices","a","b","k","results","idx","iterableResults","SIMD_WASM_BASE64","getSimdWasmBinary","binaryString","instantiateWasm","wasmBinary","memory","importObject","VECTORS_FILE","KEYS_FILE","VectorDB","memoryManager","storage","shouldNormalize","wasmExports","keyToSlot","slotToKey","options","name","vectorBytes","keysBytes","keys","mm","key","value","existingSlot","slotIndex","slot","entries","iterable","queryVec","totalVectors","scoresOffset","queryView","dbView","scoresView","src","ptr","normalized"],"mappings":"AAIO,MAAMA,UAAoC,MAAM;AAAA,EACrD,YAAYC,GAAoB;AAC9B,UAAM,8DAA8DA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,KAAK,MAAA,GACX,KAAK,SAAS;AAAA,EAChB;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,QAAuB;AAC3B,SAAK,WAAA,GAEL,KAAK,UAAU,MAAA,GACf,KAAK,UAAU,SAAS,GACxB,KAAK,cAAc,MAAA,GAEnB,MAAM,KAAK,QAAQ,QAAA;AAAA,EACrB;AAAA;AAAA;AAAA;AAAA,EAKQ,gBAAgB3E,GAAyB;AAC/C,QAAI,KAAK,aAAa;AACpB,YAAM4F,IAAM,KAAK,cAAc;AAC/B,UAAI,aAAa,KAAK,cAAc,OAAO,QAAQA,GAAK5F,EAAI,MAAM,EAAE,IAAIA,CAAG,GAC3E,KAAK,YAAY,UAAU4F,GAAK5F,EAAI,MAAM;AAC1C,YAAM6F,IAAa,IAAI,aAAa,KAAK,cAAc,OAAO,QAAQD,GAAK5F,EAAI,MAAM;AACrF,MAAAA,EAAI,IAAI6F,CAAU;AAAA,IACpB;AACE,MAAA9F,EAAUC,CAAG;AAAA,EAEjB;AAAA,EAEQ,aAAmB;AACzB,QAAI,KAAK;AACP,YAAM,IAAI,MAAM,mCAAmC;AAAA,EAEvD;AACF;"}
@@ -1,2 +1,2 @@
1
- (function(A,l){typeof exports=="object"&&typeof module<"u"?l(exports):typeof define=="function"&&define.amd?define(["exports"],l):(A=typeof globalThis<"u"?globalThis:A||self,l(A.EigenDB={}))})(this,(function(A){"use strict";class l extends Error{constructor(e){super(`Capacity exceeded. Max vectors for this dimension size is ~${e}.`),this.name="VectorCapacityExceededError"}}class m{length;sortedIndices;scores;resolveKey;constructor(e,t,r,s){this.scores=e,this.sortedIndices=t,this.resolveKey=r,this.length=Math.min(s,t.length)}static fromScores(e,t,r){const s=e.length,o=new Uint32Array(s);for(let n=0;n<s;n++)o[n]=n;return o.sort((n,a)=>e[a]-e[n]),new m(e,o,t,r)}get(e){if(e<0||e>=this.length)throw new RangeError(`Rank ${e} out of bounds [0, ${this.length})`);const t=this.sortedIndices[e];return{key:this.resolveKey(t),score:this.scores[t]}}getPage(e,t){const r=e*t,s=Math.min(r+t,this.length),o=[];for(let n=r;n<s;n++)o.push(this.get(n));return o}}class E{dirHandle=null;dirName;constructor(e){this.dirName=e}async getDir(){if(!this.dirHandle){const e=await navigator.storage.getDirectory();this.dirHandle=await e.getDirectoryHandle(this.dirName,{create:!0})}return this.dirHandle}async readAll(e){try{const o=await(await(await(await this.getDir()).getFileHandle(e)).getFile()).arrayBuffer();return new Uint8Array(o)}catch{return new Uint8Array(0)}}async append(e,t){const s=await(await this.getDir()).getFileHandle(e,{create:!0}),o=await s.createWritable({keepExistingData:!0}),n=await s.getFile();await o.seek(n.size),await o.write(t),await o.close()}async write(e,t){const o=await(await(await this.getDir()).getFileHandle(e,{create:!0})).createWritable({keepExistingData:!1});await o.write(t),await o.close()}async destroy(){await(await navigator.storage.getDirectory()).removeEntry(this.dirName,{recursive:!0}),this.dirHandle=null}}class I{files=new Map;async readAll(e){const t=this.files.get(e);if(!t||t.length===0)return new Uint8Array(0);const r=t.reduce((n,a)=>n+a.byteLength,0),s=new Uint8Array(r);let o=0;for(const n of t)s.set(n,o),o+=n.byteLength;return s}async append(e,t){this.files.has(e)||this.files.set(e,[]),this.files.get(e).push(new Uint8Array(t))}async write(e,t){this.files.set(e,[new Uint8Array(t)])}async destroy(){this.files.clear()}}function S(i){let e=0;for(let s=0;s<i.length;s++)e+=i[s]*i[s];const t=Math.sqrt(e);if(t===0)return;const r=1/t;for(let s=0;s<i.length;s++)i[s]*=r}function p(i,e,t,r,s){for(let o=0;o<r;o++){let n=0;const a=o*s;for(let c=0;c<s;c++)n+=i[c]*e[a+c];t[o]=n}}const Q=new TextEncoder,O=new TextDecoder;function v(i){const e=i.map(a=>Q.encode(a)),t=e.reduce((a,c)=>a+4+c.byteLength,0),r=new ArrayBuffer(t),s=new DataView(r),o=new Uint8Array(r);let n=0;for(const a of e)s.setUint32(n,a.byteLength,!0),n+=4,o.set(a,n),n+=a.byteLength;return o}function x(i){const e=[],t=new DataView(i.buffer,i.byteOffset,i.byteLength);let r=0;for(;r<i.byteLength;){const s=t.getUint32(r,!0);r+=4;const o=O.decode(i.subarray(r,r+s));e.push(o),r+=s}return e}const y=65536,b=65536;class F{memory;dimensions;queryOffset;dbOffset;_vectorCount;constructor(e,t=0){this.dimensions=e,this.queryOffset=0;const r=e*4;this.dbOffset=Math.ceil(r/y)*y;const s=t*e*4,o=this.dbOffset+s,n=Math.max(1,Math.ceil(o/y));this.memory=new WebAssembly.Memory({initial:n}),this._vectorCount=t}get vectorCount(){return this._vectorCount}get scoresOffset(){return this.dbOffset+this._vectorCount*this.dimensions*4}get scoresBytes(){return this._vectorCount*4}get maxVectors(){const e=b*y-this.dbOffset,t=this.dimensions*4+4;return Math.floor(e/t)}ensureCapacity(e){const t=this._vectorCount+e,r=this.dbOffset+t*this.dimensions*4+t*4,s=this.memory.buffer.byteLength;if(r>s){const o=Math.ceil((r-s)/y);if(s/y+o>b)throw new Error("WASM memory limit exceeded");this.memory.grow(o)}}writeQuery(e){new Float32Array(this.memory.buffer,this.queryOffset,this.dimensions).set(e)}appendVectors(e){const t=this.dbOffset+this._vectorCount*this.dimensions*4;let r=t;for(const s of e)new Float32Array(this.memory.buffer,r,this.dimensions).set(s),r+=this.dimensions*4;return this._vectorCount+=e.length,t}loadVectorBytes(e,t){new Uint8Array(this.memory.buffer,this.dbOffset,e.byteLength).set(e),this._vectorCount=t}readScores(){return new Float32Array(this.memory.buffer,this.scoresOffset,this._vectorCount)}readVector(e){const t=this.dbOffset+e*this.dimensions*4;return new Float32Array(this.memory.buffer,t,this.dimensions)}writeVector(e,t){const r=this.dbOffset+e*this.dimensions*4;new Float32Array(this.memory.buffer,r,this.dimensions).set(t)}reset(){this._vectorCount=0}}const V="AGFzbQEAAAABDgJgAn9/AGAFf39/f38AAg8BA2VudgZtZW1vcnkCAAEDAwIAAQcaAglub3JtYWxpemUAAApzZWFyY2hfYWxsAAEKsgQCtQIFAX8BewN9AXsDf/0MAAAAAAAAAAAAAAAAAAAAACEDIAFBfHEhCEEAIQICQANAIAIgCE8NASAAIAJBAnRqIQogAyAK/QAEACAK/QAEAP3mAf3kASEDIAJBBGohAgwACwsgA/0fACAD/R8BkiAD/R8CIAP9HwOSkiEEIAghCQJAA0AgCSABTw0BIAAgCUECdGohCiAEIAoqAgAgCioCAJSSIQQgCUEBaiEJDAALCyAEkSEFIAVDAAAAAFsEQA8LQwAAgD8gBZUhBiAG/RMhB0EAIQICQANAIAIgCE8NASAAIAJBAnRqIQogCiAK/QAEACAH/eYB/QsEACACQQRqIQIMAAsLIAghCQJAA0AgCSABTw0BIAAgCUECdGohCiAKIAoqAgAgBpQ4AgAgCUEBaiEJDAALCwv4AQQCfwF7AX0GfyAEQXxxIQogBEECdCEOQQAhBQJAA0AgBSADTw0BIAEgBSAObGohCf0MAAAAAAAAAAAAAAAAAAAAACEHQQAhBgJAA0AgBiAKTw0BIAAgBkECdGohDCAJIAZBAnRqIQ0gByAM/QAEACAN/QAEAP3mAf3kASEHIAZBBGohBgwACwsgB/0fACAH/R8BkiAH/R8CIAf9HwOSkiEIIAohCwJAA0AgCyAETw0BIAAgC0ECdGohDCAJIAtBAnRqIQ0gCCAMKgIAIA0qAgCUkiEIIAtBAWohCwwACwsgAiAFQQJ0aiAIOAIAIAVBAWohBQwACwsL";function D(){const i=atob(V),e=new Uint8Array(i.length);for(let t=0;t<i.length;t++)e[t]=i.charCodeAt(t);return e}async function T(i,e){const t={env:{memory:e}};return(await WebAssembly.instantiate(i,t)).instance.exports}const B="vectors.bin",M="keys.bin";class C{memoryManager;storage;dimensions;shouldNormalize;wasmExports;keyToSlot;slotToKey;closed=!1;constructor(e,t,r,s,o,n,a){this.memoryManager=e,this.storage=t,this.dimensions=r,this.shouldNormalize=s,this.wasmExports=o,this.keyToSlot=n,this.slotToKey=a}static async open(e){const t=e.name??"default",r=e.storage??new E(t),s=e.normalize!==!1,[o,n]=await Promise.all([r.readAll(B),r.readAll(M)]),a=n.byteLength>0?x(n):[],c=o.byteLength/(e.dimensions*4),d=new Map,g=[];for(let f=0;f<a.length;f++)d.set(a[f],f),g[f]=a[f];const h=new F(e.dimensions,c);o.byteLength>0&&h.loadVectorBytes(o,c);let u=null;const w=e.wasmBinary!==void 0?e.wasmBinary:D();if(w!==null)try{u=await T(w,h.memory)}catch{}return new C(h,r,e.dimensions,s,u,d,g)}get size(){return this.keyToSlot.size}set(e,t,r){if(this.assertOpen(),t.length!==this.dimensions)throw new Error(`Vector dimension mismatch: expected ${this.dimensions}, got ${t.length}`);const s=new Float32Array(t);(r?.normalize??this.shouldNormalize)&&this.normalizeVector(s);const n=this.keyToSlot.get(e);if(n!==void 0)this.memoryManager.writeVector(n,s);else{if(this.memoryManager.vectorCount+1>this.memoryManager.maxVectors)throw new l(this.memoryManager.maxVectors);this.memoryManager.ensureCapacity(1);const c=this.memoryManager.vectorCount;this.memoryManager.appendVectors([s]),this.keyToSlot.set(e,c),this.slotToKey[c]=e}}get(e){this.assertOpen();const t=this.keyToSlot.get(e);if(t!==void 0)return Array.from(this.memoryManager.readVector(t))}setMany(e){for(const[t,r]of e)this.set(t,r)}getMany(e){return e.map(t=>this.get(t))}query(e,t){this.assertOpen();const r=t?.topK??this.size;if(this.size===0)return m.fromScores(new Float32Array(0),()=>"",0);if(e.length!==this.dimensions)throw new Error(`Query vector dimension mismatch: expected ${this.dimensions}, got ${e.length}`);const s=new Float32Array(e);(t?.normalize??this.shouldNormalize)&&this.normalizeVector(s),this.memoryManager.writeQuery(s),this.memoryManager.ensureCapacity(0);const n=this.memoryManager.vectorCount,a=this.memoryManager.scoresOffset;if(this.wasmExports)this.wasmExports.search_all(this.memoryManager.queryOffset,this.memoryManager.dbOffset,a,n,this.dimensions);else{const h=new Float32Array(this.memoryManager.memory.buffer,this.memoryManager.queryOffset,this.dimensions),u=new Float32Array(this.memoryManager.memory.buffer,this.memoryManager.dbOffset,n*this.dimensions),w=new Float32Array(this.memoryManager.memory.buffer,a,n);p(h,u,w,n,this.dimensions)}const c=new Float32Array(this.memoryManager.readScores()),d=this.slotToKey,g=h=>d[h];return m.fromScores(c,g,r)}async flush(){this.assertOpen();const e=this.memoryManager.vectorCount,t=new Uint8Array(e*this.dimensions*4);if(e>0){const s=new Uint8Array(this.memoryManager.memory.buffer,this.memoryManager.dbOffset,e*this.dimensions*4);t.set(s)}const r=v(this.slotToKey);await Promise.all([this.storage.write(B,t),this.storage.write(M,r)])}async close(){this.closed||(await this.flush(),this.closed=!0)}async clear(){this.assertOpen(),this.keyToSlot.clear(),this.slotToKey.length=0,this.memoryManager.reset(),await this.storage.destroy()}normalizeVector(e){if(this.wasmExports){const t=this.memoryManager.queryOffset;new Float32Array(this.memoryManager.memory.buffer,t,e.length).set(e),this.wasmExports.normalize(t,e.length);const r=new Float32Array(this.memoryManager.memory.buffer,t,e.length);e.set(r)}else S(e)}assertOpen(){if(this.closed)throw new Error("VectorDB instance has been closed")}}A.DB=C,A.InMemoryStorageProvider=I,A.OPFSStorageProvider=E,A.ResultSet=m,A.VectorCapacityExceededError=l,Object.defineProperty(A,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(A,l){typeof exports=="object"&&typeof module<"u"?l(exports):typeof define=="function"&&define.amd?define(["exports"],l):(A=typeof globalThis<"u"?globalThis:A||self,l(A.EigenDB={}))})(this,(function(A){"use strict";class l extends Error{constructor(e){super(`Capacity exceeded. Max vectors for this dimension size is ~${e}.`),this.name="VectorCapacityExceededError"}}class C{dirHandle=null;dirName;constructor(e){this.dirName=e}async getDir(){if(!this.dirHandle){const e=await navigator.storage.getDirectory();this.dirHandle=await e.getDirectoryHandle(this.dirName,{create:!0})}return this.dirHandle}async readAll(e){try{const n=await(await(await(await this.getDir()).getFileHandle(e)).getFile()).arrayBuffer();return new Uint8Array(n)}catch{return new Uint8Array(0)}}async append(e,t){const r=await(await this.getDir()).getFileHandle(e,{create:!0}),n=await r.createWritable({keepExistingData:!0}),i=await r.getFile();await n.seek(i.size),await n.write(t),await n.close()}async write(e,t){const n=await(await(await this.getDir()).getFileHandle(e,{create:!0})).createWritable({keepExistingData:!1});await n.write(t),await n.close()}async destroy(){await(await navigator.storage.getDirectory()).removeEntry(this.dirName,{recursive:!0}),this.dirHandle=null}}class M{files=new Map;async readAll(e){const t=this.files.get(e);if(!t||t.length===0)return new Uint8Array(0);const s=t.reduce((i,o)=>i+o.byteLength,0),r=new Uint8Array(s);let n=0;for(const i of t)r.set(i,n),n+=i.byteLength;return r}async append(e,t){this.files.has(e)||this.files.set(e,[]),this.files.get(e).push(new Uint8Array(t))}async write(e,t){this.files.set(e,[new Uint8Array(t)])}async destroy(){this.files.clear()}}function I(a){let e=0;for(let r=0;r<a.length;r++)e+=a[r]*a[r];const t=Math.sqrt(e);if(t===0)return;const s=1/t;for(let r=0;r<a.length;r++)a[r]*=s}function S(a,e,t,s,r){for(let n=0;n<s;n++){let i=0;const o=n*r;for(let c=0;c<r;c++)i+=a[c]*e[o+c];t[n]=i}}const Q=new TextEncoder,p=new TextDecoder;function O(a){const e=a.map(o=>Q.encode(o)),t=e.reduce((o,c)=>o+4+c.byteLength,0),s=new ArrayBuffer(t),r=new DataView(s),n=new Uint8Array(s);let i=0;for(const o of e)r.setUint32(i,o.byteLength,!0),i+=4,n.set(o,i),i+=o.byteLength;return n}function x(a){const e=[],t=new DataView(a.buffer,a.byteOffset,a.byteLength);let s=0;for(;s<a.byteLength;){const r=t.getUint32(s,!0);s+=4;const n=p.decode(a.subarray(s,s+r));e.push(n),s+=r}return e}const f=65536,b=65536;class v{memory;dimensions;queryOffset;dbOffset;_vectorCount;constructor(e,t=0){this.dimensions=e,this.queryOffset=0;const s=e*4;this.dbOffset=Math.ceil(s/f)*f;const r=t*e*4,n=this.dbOffset+r,i=Math.max(1,Math.ceil(n/f));this.memory=new WebAssembly.Memory({initial:i}),this._vectorCount=t}get vectorCount(){return this._vectorCount}get scoresOffset(){return this.dbOffset+this._vectorCount*this.dimensions*4}get scoresBytes(){return this._vectorCount*4}get maxVectors(){const e=b*f-this.dbOffset,t=this.dimensions*4+4;return Math.floor(e/t)}ensureCapacity(e){const t=this._vectorCount+e,s=this.dbOffset+t*this.dimensions*4+t*4,r=this.memory.buffer.byteLength;if(s>r){const n=Math.ceil((s-r)/f);if(r/f+n>b)throw new Error("WASM memory limit exceeded");this.memory.grow(n)}}writeQuery(e){new Float32Array(this.memory.buffer,this.queryOffset,this.dimensions).set(e)}appendVectors(e){const t=this.dbOffset+this._vectorCount*this.dimensions*4;let s=t;for(const r of e)new Float32Array(this.memory.buffer,s,this.dimensions).set(r),s+=this.dimensions*4;return this._vectorCount+=e.length,t}loadVectorBytes(e,t){new Uint8Array(this.memory.buffer,this.dbOffset,e.byteLength).set(e),this._vectorCount=t}readScores(){return new Float32Array(this.memory.buffer,this.scoresOffset,this._vectorCount)}readVector(e){const t=this.dbOffset+e*this.dimensions*4;return new Float32Array(this.memory.buffer,t,this.dimensions)}writeVector(e,t){const s=this.dbOffset+e*this.dimensions*4;new Float32Array(this.memory.buffer,s,this.dimensions).set(t)}reset(){this._vectorCount=0}}function k(a,e,t){const s=a.length;if(s===0)return[];const r=new Uint32Array(s);for(let o=0;o<s;o++)r[o]=o;r.sort((o,c)=>a[c]-a[o]);const n=Math.min(t,s),i=new Array(n);for(let o=0;o<n;o++){const c=r[o];i[o]={key:e(c),score:a[c]}}return i}function F(a,e,t){const s=a.length;if(s===0)return[];const r=new Uint32Array(s);for(let i=0;i<s;i++)r[i]=i;r.sort((i,o)=>a[o]-a[i]);const n=Math.min(t,s);return{[Symbol.iterator](){let i=0;return{next(){if(i>=n)return{done:!0,value:void 0};const o=r[i++];return{done:!1,value:{key:e(o),score:a[o]}}}}}}}const V="AGFzbQEAAAABDgJgAn9/AGAFf39/f38AAg8BA2VudgZtZW1vcnkCAAEDAwIAAQcaAglub3JtYWxpemUAAApzZWFyY2hfYWxsAAEKsgQCtQIFAX8BewN9AXsDf/0MAAAAAAAAAAAAAAAAAAAAACEDIAFBfHEhCEEAIQICQANAIAIgCE8NASAAIAJBAnRqIQogAyAK/QAEACAK/QAEAP3mAf3kASEDIAJBBGohAgwACwsgA/0fACAD/R8BkiAD/R8CIAP9HwOSkiEEIAghCQJAA0AgCSABTw0BIAAgCUECdGohCiAEIAoqAgAgCioCAJSSIQQgCUEBaiEJDAALCyAEkSEFIAVDAAAAAFsEQA8LQwAAgD8gBZUhBiAG/RMhB0EAIQICQANAIAIgCE8NASAAIAJBAnRqIQogCiAK/QAEACAH/eYB/QsEACACQQRqIQIMAAsLIAghCQJAA0AgCSABTw0BIAAgCUECdGohCiAKIAoqAgAgBpQ4AgAgCUEBaiEJDAALCwv4AQQCfwF7AX0GfyAEQXxxIQogBEECdCEOQQAhBQJAA0AgBSADTw0BIAEgBSAObGohCf0MAAAAAAAAAAAAAAAAAAAAACEHQQAhBgJAA0AgBiAKTw0BIAAgBkECdGohDCAJIAZBAnRqIQ0gByAM/QAEACAN/QAEAP3mAf3kASEHIAZBBGohBgwACwsgB/0fACAH/R8BkiAH/R8CIAf9HwOSkiEIIAohCwJAA0AgCyAETw0BIAAgC0ECdGohDCAJIAtBAnRqIQ0gCCAMKgIAIA0qAgCUkiEIIAtBAWohCwwACwsgAiAFQQJ0aiAIOAIAIAVBAWohBQwACwsL";function D(){const a=atob(V),e=new Uint8Array(a.length);for(let t=0;t<a.length;t++)e[t]=a.charCodeAt(t);return e}async function T(a,e){const t={env:{memory:e}};return(await WebAssembly.instantiate(a,t)).instance.exports}const E="vectors.bin",B="keys.bin";class w{memoryManager;storage;dimensions;shouldNormalize;wasmExports;keyToSlot;slotToKey;closed=!1;constructor(e,t,s,r,n,i,o){this.memoryManager=e,this.storage=t,this.dimensions=s,this.shouldNormalize=r,this.wasmExports=n,this.keyToSlot=i,this.slotToKey=o}static async open(e){const t=e.name??"default",s=e.storage??new C(t),r=e.normalize!==!1,[n,i]=await Promise.all([s.readAll(E),s.readAll(B)]),o=i.byteLength>0?x(i):[],c=n.byteLength/(e.dimensions*4),d=new Map,g=[];for(let h=0;h<o.length;h++)d.set(o[h],h),g[h]=o[h];const y=new v(e.dimensions,c);n.byteLength>0&&y.loadVectorBytes(n,c);let m=null;const u=e.wasmBinary!==void 0?e.wasmBinary:D();if(u!==null)try{m=await T(u,y.memory)}catch{}return new w(y,s,e.dimensions,r,m,d,g)}get size(){return this.keyToSlot.size}set(e,t,s){if(this.assertOpen(),t.length!==this.dimensions)throw new Error(`Vector dimension mismatch: expected ${this.dimensions}, got ${t.length}`);const r=new Float32Array(t);(s?.normalize??this.shouldNormalize)&&this.normalizeVector(r);const i=this.keyToSlot.get(e);if(i!==void 0)this.memoryManager.writeVector(i,r);else{if(this.memoryManager.vectorCount+1>this.memoryManager.maxVectors)throw new l(this.memoryManager.maxVectors);this.memoryManager.ensureCapacity(1);const c=this.memoryManager.vectorCount;this.memoryManager.appendVectors([r]),this.keyToSlot.set(e,c),this.slotToKey[c]=e}}get(e){this.assertOpen();const t=this.keyToSlot.get(e);if(t!==void 0)return Array.from(this.memoryManager.readVector(t))}setMany(e){for(const[t,s]of e)this.set(t,s)}getMany(e){return e.map(t=>this.get(t))}query(e,t){this.assertOpen();const s=t?.topK??this.size,r=t&&"iterable"in t&&t.iterable;if(this.size===0)return[];if(e.length!==this.dimensions)throw new Error(`Query vector dimension mismatch: expected ${this.dimensions}, got ${e.length}`);const n=new Float32Array(e);(t?.normalize??this.shouldNormalize)&&this.normalizeVector(n),this.memoryManager.writeQuery(n),this.memoryManager.ensureCapacity(0);const o=this.memoryManager.vectorCount,c=this.memoryManager.scoresOffset;if(this.wasmExports)this.wasmExports.search_all(this.memoryManager.queryOffset,this.memoryManager.dbOffset,c,o,this.dimensions);else{const m=new Float32Array(this.memoryManager.memory.buffer,this.memoryManager.queryOffset,this.dimensions),u=new Float32Array(this.memoryManager.memory.buffer,this.memoryManager.dbOffset,o*this.dimensions),h=new Float32Array(this.memoryManager.memory.buffer,c,o);S(m,u,h,o,this.dimensions)}const d=new Float32Array(this.memoryManager.readScores()),g=this.slotToKey,y=m=>g[m];return r?F(d,y,s):k(d,y,s)}async flush(){this.assertOpen();const e=this.memoryManager.vectorCount,t=new Uint8Array(e*this.dimensions*4);if(e>0){const r=new Uint8Array(this.memoryManager.memory.buffer,this.memoryManager.dbOffset,e*this.dimensions*4);t.set(r)}const s=O(this.slotToKey);await Promise.all([this.storage.write(E,t),this.storage.write(B,s)])}async close(){this.closed||(await this.flush(),this.closed=!0)}async clear(){this.assertOpen(),this.keyToSlot.clear(),this.slotToKey.length=0,this.memoryManager.reset(),await this.storage.destroy()}normalizeVector(e){if(this.wasmExports){const t=this.memoryManager.queryOffset;new Float32Array(this.memoryManager.memory.buffer,t,e.length).set(e),this.wasmExports.normalize(t,e.length);const s=new Float32Array(this.memoryManager.memory.buffer,t,e.length);e.set(s)}else I(e)}assertOpen(){if(this.closed)throw new Error("VectorDB instance has been closed")}}A.DB=w,A.InMemoryStorageProvider=M,A.OPFSStorageProvider=C,A.VectorCapacityExceededError=l,Object.defineProperty(A,Symbol.toStringTag,{value:"Module"})}));
2
2
  //# sourceMappingURL=eigen-db.umd.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"eigen-db.umd.cjs","sources":["../src/lib/errors.ts","../src/lib/result-set.ts","../src/lib/storage.ts","../src/lib/compute.ts","../src/lib/lexicon.ts","../src/lib/memory-manager.ts","../src/lib/simd-binary.ts","../src/lib/wasm-compute.ts","../src/lib/vector-db.ts"],"sourcesContent":["/**\n * Thrown when the database exceeds the 4GB WebAssembly 32-bit memory limit,\n * or the browser's available RAM.\n */\nexport class VectorCapacityExceededError extends Error {\n constructor(maxVectors: number) {\n super(`Capacity exceeded. Max vectors for this dimension size is ~${maxVectors}.`);\n this.name = \"VectorCapacityExceededError\";\n }\n}\n","/**\n * LAZY RESULT SET\n *\n * Holds pointers to sorted TypedArrays. Prevents JS heap overflow when K is massive.\n * Strings are only instantiated from the Lexicon when explicitly requested.\n */\n\nexport interface ResultItem {\n key: string;\n score: number;\n}\n\nexport type KeyResolver = (index: number) => string;\n\nexport class ResultSet {\n /** Total number of results */\n readonly length: number;\n\n /**\n * Sorted indices into the original database (by descending score).\n * sortedIndices[0] is the index of the best match.\n */\n private readonly sortedIndices: Uint32Array;\n\n /** Raw scores array (not sorted, indexed by original DB position) */\n private readonly scores: Float32Array;\n\n /** Function to lazily resolve key from the slot index */\n private readonly resolveKey: KeyResolver;\n\n constructor(\n scores: Float32Array,\n sortedIndices: Uint32Array,\n resolveKey: KeyResolver,\n topK: number,\n ) {\n this.scores = scores;\n this.sortedIndices = sortedIndices;\n this.resolveKey = resolveKey;\n this.length = Math.min(topK, sortedIndices.length);\n }\n\n /**\n * Sort scores and return a ResultSet with lazy key resolution.\n *\n * @param scores - Float32Array of scores (one per DB vector)\n * @param resolveKey - Function to resolve key by original index\n * @param topK - Maximum number of results to include\n */\n static fromScores(\n scores: Float32Array,\n resolveKey: KeyResolver,\n topK: number,\n ): ResultSet {\n const n = scores.length;\n\n // Create index array for sorting\n const indices = new Uint32Array(n);\n for (let i = 0; i < n; i++) indices[i] = i;\n\n // Sort indices by descending score\n indices.sort((a, b) => scores[b] - scores[a]);\n\n return new ResultSet(scores, indices, resolveKey, topK);\n }\n\n /** Fetch a single result by its rank (0 is best match) */\n get(rank: number): ResultItem {\n if (rank < 0 || rank >= this.length) {\n throw new RangeError(`Rank ${rank} out of bounds [0, ${this.length})`);\n }\n const dbIndex = this.sortedIndices[rank];\n return {\n key: this.resolveKey(dbIndex),\n score: this.scores[dbIndex],\n };\n }\n\n /** Helper for UI pagination. Instantiates strings only for the requested page. */\n getPage(page: number, pageSize: number): ResultItem[] {\n const start = page * pageSize;\n const end = Math.min(start + pageSize, this.length);\n const results: ResultItem[] = [];\n for (let i = start; i < end; i++) {\n results.push(this.get(i));\n }\n return results;\n }\n}\n","/**\n * Storage abstraction for append-only binary files.\n * Supports OPFS for browser and in-memory for testing.\n */\n\nexport interface StorageProvider {\n /** Read the entire contents of a file. Returns empty Uint8Array if file doesn't exist. */\n readAll(fileName: string): Promise<Uint8Array>;\n\n /** Append data to a file (creates if it doesn't exist). */\n append(fileName: string, data: Uint8Array): Promise<void>;\n\n /** Write data to a file, replacing all existing content. */\n write(fileName: string, data: Uint8Array): Promise<void>;\n\n /** Delete the storage directory and all files. */\n destroy(): Promise<void>;\n}\n\n/**\n * OPFS-backed storage provider for browser environments.\n * Uses Origin Private File System for high-performance persistent storage.\n */\nexport class OPFSStorageProvider implements StorageProvider {\n private dirHandle: FileSystemDirectoryHandle | null = null;\n private dirName: string;\n\n constructor(dirName: string) {\n this.dirName = dirName;\n }\n\n private async getDir(): Promise<FileSystemDirectoryHandle> {\n if (!this.dirHandle) {\n const root = await navigator.storage.getDirectory();\n this.dirHandle = await root.getDirectoryHandle(this.dirName, { create: true });\n }\n return this.dirHandle;\n }\n\n async readAll(fileName: string): Promise<Uint8Array> {\n try {\n const dir = await this.getDir();\n const fileHandle = await dir.getFileHandle(fileName);\n const file = await fileHandle.getFile();\n const buffer = await file.arrayBuffer();\n return new Uint8Array(buffer);\n } catch {\n return new Uint8Array(0);\n }\n }\n\n async append(fileName: string, data: Uint8Array): Promise<void> {\n const dir = await this.getDir();\n const fileHandle = await dir.getFileHandle(fileName, { create: true });\n const writable = await fileHandle.createWritable({ keepExistingData: true });\n const file = await fileHandle.getFile();\n await writable.seek(file.size);\n await writable.write(data as unknown as BufferSource);\n await writable.close();\n }\n\n async write(fileName: string, data: Uint8Array): Promise<void> {\n const dir = await this.getDir();\n const fileHandle = await dir.getFileHandle(fileName, { create: true });\n const writable = await fileHandle.createWritable({ keepExistingData: false });\n await writable.write(data as unknown as BufferSource);\n await writable.close();\n }\n\n async destroy(): Promise<void> {\n const root = await navigator.storage.getDirectory();\n await root.removeEntry(this.dirName, { recursive: true });\n this.dirHandle = null;\n }\n}\n\n/**\n * In-memory storage provider for testing.\n */\nexport class InMemoryStorageProvider implements StorageProvider {\n private files = new Map<string, Uint8Array[]>();\n\n async readAll(fileName: string): Promise<Uint8Array> {\n const chunks = this.files.get(fileName);\n if (!chunks || chunks.length === 0) return new Uint8Array(0);\n\n const totalSize = chunks.reduce((sum, c) => sum + c.byteLength, 0);\n const result = new Uint8Array(totalSize);\n let offset = 0;\n for (const chunk of chunks) {\n result.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return result;\n }\n\n async append(fileName: string, data: Uint8Array): Promise<void> {\n if (!this.files.has(fileName)) {\n this.files.set(fileName, []);\n }\n this.files.get(fileName)!.push(new Uint8Array(data));\n }\n\n async write(fileName: string, data: Uint8Array): Promise<void> {\n this.files.set(fileName, [new Uint8Array(data)]);\n }\n\n async destroy(): Promise<void> {\n this.files.clear();\n }\n}\n","/**\n * Pure JavaScript compute functions for vector operations.\n * These serve as the reference implementation and fallback when WASM SIMD is unavailable.\n */\n\n/**\n * Normalizes a vector in-place to unit length.\n * After normalization, cosine similarity reduces to a simple dot product.\n */\nexport function normalize(vec: Float32Array): void {\n let sumSq = 0;\n for (let i = 0; i < vec.length; i++) {\n sumSq += vec[i] * vec[i];\n }\n const mag = Math.sqrt(sumSq);\n if (mag === 0) return;\n const invMag = 1 / mag;\n for (let i = 0; i < vec.length; i++) {\n vec[i] *= invMag;\n }\n}\n\n/**\n * Computes dot products of query against all vectors in the database.\n * Writes scores to the output array.\n *\n * @param query - Normalized query vector (length = dimensions)\n * @param db - Contiguous flat array of normalized vectors (length = dbSize * dimensions)\n * @param scores - Output array for dot product scores (length = dbSize)\n * @param dbSize - Number of vectors in the database\n * @param dimensions - Dimensionality of each vector\n */\nexport function searchAll(\n query: Float32Array,\n db: Float32Array,\n scores: Float32Array,\n dbSize: number,\n dimensions: number,\n): void {\n for (let i = 0; i < dbSize; i++) {\n let dot = 0;\n const offset = i * dimensions;\n for (let j = 0; j < dimensions; j++) {\n dot += query[j] * db[offset + j];\n }\n scores[i] = dot;\n }\n}\n","/**\n * Lexicon: length-prefixed UTF-8 encoding for text strings.\n *\n * Format: Each entry is [4-byte uint32 length][UTF-8 bytes]\n * This allows efficient sequential reading and appending.\n */\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\n/**\n * Encodes an array of strings into a length-prefixed binary format.\n */\nexport function encodeLexicon(texts: string[]): Uint8Array {\n const encoded = texts.map((t) => encoder.encode(t));\n const totalSize = encoded.reduce((sum, e) => sum + 4 + e.byteLength, 0);\n\n const buffer = new ArrayBuffer(totalSize);\n const view = new DataView(buffer);\n const bytes = new Uint8Array(buffer);\n let offset = 0;\n\n for (const e of encoded) {\n view.setUint32(offset, e.byteLength, true); // little-endian\n offset += 4;\n bytes.set(e, offset);\n offset += e.byteLength;\n }\n\n return bytes;\n}\n\n/**\n * Decodes all strings from a length-prefixed binary buffer.\n */\nexport function decodeLexicon(data: Uint8Array): string[] {\n const result: string[] = [];\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n let offset = 0;\n\n while (offset < data.byteLength) {\n const len = view.getUint32(offset, true);\n offset += 4;\n const text = decoder.decode(data.subarray(offset, offset + len));\n result.push(text);\n offset += len;\n }\n\n return result;\n}\n\n/**\n * Decodes a single string at a given index from the lexicon.\n * Returns the string and the byte offset of the next entry.\n */\nexport function decodeLexiconAt(data: Uint8Array, index: number): string {\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n let offset = 0;\n\n for (let i = 0; i < index; i++) {\n const len = view.getUint32(offset, true);\n offset += 4 + len;\n }\n\n const len = view.getUint32(offset, true);\n offset += 4;\n return decoder.decode(data.subarray(offset, offset + len));\n}\n\n/**\n * Builds an index of byte offsets for each entry in the lexicon.\n * Enables O(1) access to any entry by index.\n */\nexport function buildLexiconIndex(data: Uint8Array): Uint32Array {\n const offsets: number[] = [];\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n let offset = 0;\n\n while (offset < data.byteLength) {\n offsets.push(offset);\n const len = view.getUint32(offset, true);\n offset += 4 + len;\n }\n\n return new Uint32Array(offsets);\n}\n\n/**\n * Decodes a string at a given byte offset in the lexicon.\n */\nexport function decodeLexiconAtOffset(data: Uint8Array, byteOffset: number): string {\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n const len = view.getUint32(byteOffset, true);\n return decoder.decode(data.subarray(byteOffset + 4, byteOffset + 4 + len));\n}\n","/**\n * Memory Manager for WASM shared memory.\n *\n * Memory Layout:\n * [ 0x00000 ] -> Query Vector Buffer (Fixed, dimensions * 4 bytes, aligned to 64KB page)\n * [ DB_OFFSET ] -> Vector Database (Grows dynamically)\n * [ Dynamic ] -> Scores Buffer (Mapped after DB during search)\n */\n\n/** WASM page size is 64KB */\nconst PAGE_SIZE = 65536;\n\n/** Maximum WASM memory: ~4GB (65536 pages of 64KB each) */\nconst MAX_PAGES = 65536;\n\nexport class MemoryManager {\n readonly memory: WebAssembly.Memory;\n readonly dimensions: number;\n readonly queryOffset: number;\n readonly dbOffset: number;\n private _vectorCount: number;\n\n constructor(dimensions: number, initialVectorCount: number = 0) {\n this.dimensions = dimensions;\n\n // Query buffer: dimensions * 4 bytes, aligned to page boundary\n this.queryOffset = 0;\n const queryBytes = dimensions * 4;\n this.dbOffset = Math.ceil(queryBytes / PAGE_SIZE) * PAGE_SIZE;\n\n // Calculate initial memory needed\n const dbBytes = initialVectorCount * dimensions * 4;\n const totalBytes = this.dbOffset + dbBytes;\n const initialPages = Math.max(1, Math.ceil(totalBytes / PAGE_SIZE));\n\n this.memory = new WebAssembly.Memory({ initial: initialPages });\n this._vectorCount = initialVectorCount;\n }\n\n /** Current number of vectors stored */\n get vectorCount(): number {\n return this._vectorCount;\n }\n\n /** Byte offset where the scores buffer starts (right after DB) */\n get scoresOffset(): number {\n return this.dbOffset + this._vectorCount * this.dimensions * 4;\n }\n\n /** Total bytes needed for scores buffer */\n get scoresBytes(): number {\n return this._vectorCount * 4;\n }\n\n /**\n * Maximum vectors that can be stored given the 4GB WASM memory limit.\n * Accounts for query buffer, DB space, and scores buffer.\n */\n get maxVectors(): number {\n const availableBytes = MAX_PAGES * PAGE_SIZE - this.dbOffset;\n // Each vector needs: dimensions * 4 bytes (DB) + 4 bytes (score)\n const bytesPerVector = this.dimensions * 4 + 4;\n return Math.floor(availableBytes / bytesPerVector);\n }\n\n /**\n * Ensures memory is large enough for the current DB + scores buffer.\n * Calls memory.grow() if needed.\n */\n ensureCapacity(additionalVectors: number): void {\n const newTotal = this._vectorCount + additionalVectors;\n const requiredBytes =\n this.dbOffset + newTotal * this.dimensions * 4 + newTotal * 4; // DB + scores\n const currentBytes = this.memory.buffer.byteLength;\n\n if (requiredBytes > currentBytes) {\n const pagesNeeded = Math.ceil((requiredBytes - currentBytes) / PAGE_SIZE);\n const currentPages = currentBytes / PAGE_SIZE;\n if (currentPages + pagesNeeded > MAX_PAGES) {\n throw new Error(\"WASM memory limit exceeded\");\n }\n this.memory.grow(pagesNeeded);\n }\n }\n\n /**\n * Write a query vector into the query buffer region.\n */\n writeQuery(vector: Float32Array): void {\n new Float32Array(this.memory.buffer, this.queryOffset, this.dimensions).set(vector);\n }\n\n /**\n * Append vectors to the database region.\n * Returns the byte offset where the new vectors were written.\n */\n appendVectors(vectors: Float32Array[]): number {\n const startOffset = this.dbOffset + this._vectorCount * this.dimensions * 4;\n let offset = startOffset;\n for (const vec of vectors) {\n new Float32Array(this.memory.buffer, offset, this.dimensions).set(vec);\n offset += this.dimensions * 4;\n }\n this._vectorCount += vectors.length;\n return startOffset;\n }\n\n /**\n * Load raw vector bytes directly into the database region.\n * Used for bulk loading from OPFS.\n */\n loadVectorBytes(data: Uint8Array, vectorCount: number): void {\n new Uint8Array(this.memory.buffer, this.dbOffset, data.byteLength).set(data);\n this._vectorCount = vectorCount;\n }\n\n /**\n * Read the scores buffer as a Float32Array view.\n */\n readScores(): Float32Array {\n return new Float32Array(this.memory.buffer, this.scoresOffset, this._vectorCount);\n }\n\n /**\n * Read the DB region for a specific vector index.\n */\n readVector(index: number): Float32Array {\n const offset = this.dbOffset + index * this.dimensions * 4;\n return new Float32Array(this.memory.buffer, offset, this.dimensions);\n }\n\n /**\n * Write a vector to a specific slot in the database region.\n */\n writeVector(index: number, vector: Float32Array): void {\n const offset = this.dbOffset + index * this.dimensions * 4;\n new Float32Array(this.memory.buffer, offset, this.dimensions).set(vector);\n }\n\n /**\n * Reset the vector count to zero, logically clearing the database.\n * WASM memory is not freed but will be overwritten on next writes.\n */\n reset(): void {\n this._vectorCount = 0;\n }\n}\n","// AUTO-GENERATED - Do not edit. Run: npx tsx scripts/compile-wat.ts\nconst SIMD_WASM_BASE64 = \"AGFzbQEAAAABDgJgAn9/AGAFf39/f38AAg8BA2VudgZtZW1vcnkCAAEDAwIAAQcaAglub3JtYWxpemUAAApzZWFyY2hfYWxsAAEKsgQCtQIFAX8BewN9AXsDf/0MAAAAAAAAAAAAAAAAAAAAACEDIAFBfHEhCEEAIQICQANAIAIgCE8NASAAIAJBAnRqIQogAyAK/QAEACAK/QAEAP3mAf3kASEDIAJBBGohAgwACwsgA/0fACAD/R8BkiAD/R8CIAP9HwOSkiEEIAghCQJAA0AgCSABTw0BIAAgCUECdGohCiAEIAoqAgAgCioCAJSSIQQgCUEBaiEJDAALCyAEkSEFIAVDAAAAAFsEQA8LQwAAgD8gBZUhBiAG/RMhB0EAIQICQANAIAIgCE8NASAAIAJBAnRqIQogCiAK/QAEACAH/eYB/QsEACACQQRqIQIMAAsLIAghCQJAA0AgCSABTw0BIAAgCUECdGohCiAKIAoqAgAgBpQ4AgAgCUEBaiEJDAALCwv4AQQCfwF7AX0GfyAEQXxxIQogBEECdCEOQQAhBQJAA0AgBSADTw0BIAEgBSAObGohCf0MAAAAAAAAAAAAAAAAAAAAACEHQQAhBgJAA0AgBiAKTw0BIAAgBkECdGohDCAJIAZBAnRqIQ0gByAM/QAEACAN/QAEAP3mAf3kASEHIAZBBGohBgwACwsgB/0fACAH/R8BkiAH/R8CIAf9HwOSkiEIIAohCwJAA0AgCyAETw0BIAAgC0ECdGohDCAJIAtBAnRqIQ0gCCAMKgIAIA0qAgCUkiEIIAtBAWohCwwACwsgAiAFQQJ0aiAIOAIAIAVBAWohBQwACwsL\";\n\nexport function getSimdWasmBinary(): Uint8Array {\n const binaryString = atob(SIMD_WASM_BASE64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\n","/**\n * WASM SIMD compute layer.\n * Compiles the hand-written WAT module and provides typed wrappers\n * that operate on shared WebAssembly.Memory.\n */\n\nexport interface WasmExports {\n normalize(ptr: number, dimensions: number): void;\n search_all(queryPtr: number, dbPtr: number, scoresPtr: number, dbSize: number, dimensions: number): void;\n}\n\n/**\n * Instantiates a WASM module with the given memory and returns typed exports.\n */\nexport async function instantiateWasm(wasmBinary: Uint8Array, memory: WebAssembly.Memory): Promise<WasmExports> {\n const importObject = { env: { memory } };\n const result = await WebAssembly.instantiate(wasmBinary, importObject);\n // WebAssembly.instantiate with a buffer returns { instance, module }\n const instance = (result as unknown as { instance: WebAssembly.Instance }).instance;\n return instance.exports as unknown as WasmExports;\n}\n","/**\n * VectorDB — Key-Value Vector Database\n *\n * Decoupled from embedding providers. Users pass pre-computed vectors\n * as number arrays (or Float32Array) with string keys.\n *\n * Supports:\n * - set/get/setMany/getMany for key-value CRUD\n * - query for similarity search (dot product on normalized vectors)\n * - flush to persist, close to flush+release, clear to wipe\n * - Last-write-wins semantics for duplicate keys (append-only storage)\n */\n\nimport { normalize, searchAll } from \"./compute\";\nimport { VectorCapacityExceededError } from \"./errors\";\nimport { decodeLexicon, encodeLexicon } from \"./lexicon\";\nimport { MemoryManager } from \"./memory-manager\";\nimport { ResultSet } from \"./result-set\";\nimport { getSimdWasmBinary } from \"./simd-binary\";\nimport type { StorageProvider } from \"./storage\";\nimport { OPFSStorageProvider } from \"./storage\";\nimport type { OpenOptions, OpenOptionsInternal, QueryOptions, SetOptions, VectorInput } from \"./types\";\nimport { instantiateWasm, type WasmExports } from \"./wasm-compute\";\n\nconst VECTORS_FILE = \"vectors.bin\";\nconst KEYS_FILE = \"keys.bin\";\n\nexport class VectorDB {\n private readonly memoryManager: MemoryManager;\n private readonly storage: StorageProvider;\n private readonly dimensions: number;\n private readonly shouldNormalize: boolean;\n private wasmExports: WasmExports | null;\n\n /** Maps key to its slot index in the vector array */\n private keyToSlot: Map<string, number>;\n\n /** Maps slot index back to its key */\n private slotToKey: string[];\n\n /** Whether this instance has been closed */\n private closed = false;\n\n private constructor(\n memoryManager: MemoryManager,\n storage: StorageProvider,\n dimensions: number,\n shouldNormalize: boolean,\n wasmExports: WasmExports | null,\n keyToSlot: Map<string, number>,\n slotToKey: string[],\n ) {\n this.memoryManager = memoryManager;\n this.storage = storage;\n this.dimensions = dimensions;\n this.shouldNormalize = shouldNormalize;\n this.wasmExports = wasmExports;\n this.keyToSlot = keyToSlot;\n this.slotToKey = slotToKey;\n }\n\n /**\n * Opens a VectorDB instance.\n * Loads existing data from storage into WASM memory.\n */\n static async open(options: OpenOptions): Promise<VectorDB>;\n static async open(options: OpenOptionsInternal): Promise<VectorDB>;\n static async open(options: OpenOptionsInternal): Promise<VectorDB> {\n const name = options.name ?? \"default\";\n const storage = options.storage ?? new OPFSStorageProvider(name);\n const shouldNormalize = options.normalize !== false;\n\n // Load existing data from storage\n const [vectorBytes, keysBytes] = await Promise.all([storage.readAll(VECTORS_FILE), storage.readAll(KEYS_FILE)]);\n\n // Decode stored keys\n const keys = keysBytes.byteLength > 0 ? decodeLexicon(keysBytes) : [];\n const vectorCount = vectorBytes.byteLength / (options.dimensions * 4);\n\n // Build key-to-slot mapping.\n // flush() always writes deduplicated state, so keys are unique on load.\n const keyToSlot = new Map<string, number>();\n const slotToKey: string[] = [];\n\n for (let i = 0; i < keys.length; i++) {\n keyToSlot.set(keys[i], i);\n slotToKey[i] = keys[i];\n }\n\n // Initialize memory manager\n const mm = new MemoryManager(options.dimensions, vectorCount);\n\n if (vectorBytes.byteLength > 0) {\n mm.loadVectorBytes(vectorBytes, vectorCount);\n }\n\n // Try to instantiate WASM SIMD module\n let wasmExports: WasmExports | null = null;\n const wasmBinary = options.wasmBinary !== undefined ? options.wasmBinary : getSimdWasmBinary();\n if (wasmBinary !== null) {\n try {\n wasmExports = await instantiateWasm(wasmBinary, mm.memory);\n } catch {\n // Fall back to JS compute\n }\n }\n\n return new VectorDB(mm, storage, options.dimensions, shouldNormalize, wasmExports, keyToSlot, slotToKey);\n }\n\n /** Total number of key-value pairs in the database */\n get size(): number {\n return this.keyToSlot.size;\n }\n\n /**\n * Set a key-value pair. If the key already exists, its vector is overwritten (last-write-wins).\n * The value is a number[] or Float32Array of length equal to the configured dimensions.\n */\n set(key: string, value: VectorInput, options?: SetOptions): void {\n this.assertOpen();\n\n if (value.length !== this.dimensions) {\n throw new Error(`Vector dimension mismatch: expected ${this.dimensions}, got ${value.length}`);\n }\n\n // Convert to Float32Array (also clones to avoid mutating caller's array)\n const vec = new Float32Array(value);\n\n // Normalize if needed\n const doNormalize = options?.normalize ?? this.shouldNormalize;\n if (doNormalize) {\n this.normalizeVector(vec);\n }\n\n const existingSlot = this.keyToSlot.get(key);\n if (existingSlot !== undefined) {\n // Overwrite existing slot\n this.memoryManager.writeVector(existingSlot, vec);\n } else {\n // Append new entry\n const newTotal = this.memoryManager.vectorCount + 1;\n if (newTotal > this.memoryManager.maxVectors) {\n throw new VectorCapacityExceededError(this.memoryManager.maxVectors);\n }\n this.memoryManager.ensureCapacity(1);\n const slotIndex = this.memoryManager.vectorCount;\n this.memoryManager.appendVectors([vec]);\n this.keyToSlot.set(key, slotIndex);\n this.slotToKey[slotIndex] = key;\n }\n }\n\n /**\n * Get the stored vector for a key. Returns undefined if the key does not exist.\n * Returns a copy of the stored vector as a plain number array.\n */\n get(key: string): number[] | undefined {\n this.assertOpen();\n\n const slot = this.keyToSlot.get(key);\n if (slot === undefined) return undefined;\n\n // Return a plain array copy so callers can't corrupt WASM memory\n return Array.from(this.memoryManager.readVector(slot));\n }\n\n /**\n * Set multiple key-value pairs at once. Last-write-wins applies within the batch.\n */\n setMany(entries: [string, VectorInput][]): void {\n for (const [key, value] of entries) {\n this.set(key, value);\n }\n }\n\n /**\n * Get vectors for multiple keys. Returns undefined for keys that don't exist.\n */\n getMany(keys: string[]): (number[] | undefined)[] {\n return keys.map((key) => this.get(key));\n }\n\n /**\n * Search for the most similar vectors to the given query vector.\n * Returns a ResultSet sorted by descending similarity score.\n */\n query(value: VectorInput, options?: QueryOptions): ResultSet {\n this.assertOpen();\n\n const k = options?.topK ?? this.size;\n\n if (this.size === 0) {\n return ResultSet.fromScores(new Float32Array(0), () => \"\", 0);\n }\n\n if (value.length !== this.dimensions) {\n throw new Error(`Query vector dimension mismatch: expected ${this.dimensions}, got ${value.length}`);\n }\n\n // Convert to Float32Array and optionally normalize the query vector\n const queryVec = new Float32Array(value);\n const doNormalize = options?.normalize ?? this.shouldNormalize;\n if (doNormalize) {\n this.normalizeVector(queryVec);\n }\n\n // Write query to WASM memory\n this.memoryManager.writeQuery(queryVec);\n\n // Ensure memory has space for scores buffer\n this.memoryManager.ensureCapacity(0);\n\n // Total vectors in memory\n const totalVectors = this.memoryManager.vectorCount;\n\n // Execute search\n const scoresOffset = this.memoryManager.scoresOffset;\n if (this.wasmExports) {\n this.wasmExports.search_all(\n this.memoryManager.queryOffset,\n this.memoryManager.dbOffset,\n scoresOffset,\n totalVectors,\n this.dimensions,\n );\n } else {\n const queryView = new Float32Array(\n this.memoryManager.memory.buffer,\n this.memoryManager.queryOffset,\n this.dimensions,\n );\n const dbView = new Float32Array(\n this.memoryManager.memory.buffer,\n this.memoryManager.dbOffset,\n totalVectors * this.dimensions,\n );\n const scoresView = new Float32Array(this.memoryManager.memory.buffer, scoresOffset, totalVectors);\n searchAll(queryView, dbView, scoresView, totalVectors, this.dimensions);\n }\n\n // Read scores (make a copy so the buffer can be reused)\n const scores = new Float32Array(this.memoryManager.readScores());\n\n // Resolve key from slot index\n const slotToKey = this.slotToKey;\n const resolveKey = (slotIndex: number): string => {\n return slotToKey[slotIndex];\n };\n\n return ResultSet.fromScores(scores, resolveKey, k);\n }\n\n /**\n * Persist the current in-memory state to storage.\n */\n async flush(): Promise<void> {\n this.assertOpen();\n\n const totalVectors = this.memoryManager.vectorCount;\n\n // Serialize vectors from WASM memory\n const vectorBytes = new Uint8Array(totalVectors * this.dimensions * 4);\n if (totalVectors > 0) {\n const src = new Uint8Array(\n this.memoryManager.memory.buffer,\n this.memoryManager.dbOffset,\n totalVectors * this.dimensions * 4,\n );\n vectorBytes.set(src);\n }\n\n // Serialize keys using lexicon format\n const keysBytes = encodeLexicon(this.slotToKey);\n\n await Promise.all([this.storage.write(VECTORS_FILE, vectorBytes), this.storage.write(KEYS_FILE, keysBytes)]);\n }\n\n /**\n * Flush data to storage and release the instance.\n * The instance cannot be used after close.\n */\n async close(): Promise<void> {\n if (this.closed) return;\n await this.flush();\n this.closed = true;\n }\n\n /**\n * Clear all data from the database and storage.\n */\n async clear(): Promise<void> {\n this.assertOpen();\n\n this.keyToSlot.clear();\n this.slotToKey.length = 0;\n this.memoryManager.reset();\n\n await this.storage.destroy();\n }\n\n /**\n * Normalize a vector using WASM (if available) or JS fallback.\n */\n private normalizeVector(vec: Float32Array): void {\n if (this.wasmExports) {\n const ptr = this.memoryManager.queryOffset;\n new Float32Array(this.memoryManager.memory.buffer, ptr, vec.length).set(vec);\n this.wasmExports.normalize(ptr, vec.length);\n const normalized = new Float32Array(this.memoryManager.memory.buffer, ptr, vec.length);\n vec.set(normalized);\n } else {\n normalize(vec);\n }\n }\n\n private assertOpen(): void {\n if (this.closed) {\n throw new Error(\"VectorDB instance has been closed\");\n }\n }\n}\n"],"names":["VectorCapacityExceededError","maxVectors","ResultSet","scores","sortedIndices","resolveKey","topK","n","indices","i","a","b","rank","dbIndex","page","pageSize","start","end","results","OPFSStorageProvider","dirName","root","fileName","buffer","data","fileHandle","writable","file","InMemoryStorageProvider","chunks","totalSize","sum","c","result","offset","chunk","normalize","vec","sumSq","mag","invMag","searchAll","query","db","dbSize","dimensions","dot","j","encoder","decoder","encodeLexicon","texts","encoded","t","e","view","bytes","decodeLexicon","len","text","PAGE_SIZE","MAX_PAGES","MemoryManager","initialVectorCount","queryBytes","dbBytes","totalBytes","initialPages","availableBytes","bytesPerVector","additionalVectors","newTotal","requiredBytes","currentBytes","pagesNeeded","vector","vectors","startOffset","vectorCount","index","SIMD_WASM_BASE64","getSimdWasmBinary","binaryString","instantiateWasm","wasmBinary","memory","importObject","VECTORS_FILE","KEYS_FILE","VectorDB","memoryManager","storage","shouldNormalize","wasmExports","keyToSlot","slotToKey","options","name","vectorBytes","keysBytes","keys","mm","key","value","existingSlot","slotIndex","slot","entries","k","queryVec","totalVectors","scoresOffset","queryView","dbView","scoresView","src","ptr","normalized"],"mappings":"gOAIO,MAAMA,UAAoC,KAAM,CACrD,YAAYC,EAAoB,CAC9B,MAAM,8DAA8DA,CAAU,GAAG,EACjF,KAAK,KAAO,6BACd,CACF,CCKO,MAAMC,CAAU,CAEZ,OAMQ,cAGA,OAGA,WAEjB,YACEC,EACAC,EACAC,EACAC,EACA,CACA,KAAK,OAASH,EACd,KAAK,cAAgBC,EACrB,KAAK,WAAaC,EAClB,KAAK,OAAS,KAAK,IAAIC,EAAMF,EAAc,MAAM,CACnD,CASA,OAAO,WACLD,EACAE,EACAC,EACW,CACX,MAAMC,EAAIJ,EAAO,OAGXK,EAAU,IAAI,YAAYD,CAAC,EACjC,QAASE,EAAI,EAAGA,EAAIF,EAAGE,IAAKD,EAAQC,CAAC,EAAIA,EAGzC,OAAAD,EAAQ,KAAK,CAACE,EAAGC,IAAMR,EAAOQ,CAAC,EAAIR,EAAOO,CAAC,CAAC,EAErC,IAAIR,EAAUC,EAAQK,EAASH,EAAYC,CAAI,CACxD,CAGA,IAAIM,EAA0B,CAC5B,GAAIA,EAAO,GAAKA,GAAQ,KAAK,OAC3B,MAAM,IAAI,WAAW,QAAQA,CAAI,sBAAsB,KAAK,MAAM,GAAG,EAEvE,MAAMC,EAAU,KAAK,cAAcD,CAAI,EACvC,MAAO,CACL,IAAK,KAAK,WAAWC,CAAO,EAC5B,MAAO,KAAK,OAAOA,CAAO,CAAA,CAE9B,CAGA,QAAQC,EAAc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G,KAAK,QAAQ,MAAMV,EAAWW,CAAS,CAAC,CAAC,CAC7G,CAMA,MAAM,OAAuB,CACvB,KAAK,SACT,MAAM,KAAK,MAAA,EACX,KAAK,OAAS,GAChB,CAKA,MAAM,OAAuB,CAC3B,KAAK,WAAA,EAEL,KAAK,UAAU,MAAA,EACf,KAAK,UAAU,OAAS,EACxB,KAAK,cAAc,MAAA,EAEnB,MAAM,KAAK,QAAQ,QAAA,CACrB,CAKQ,gBAAgB9D,EAAyB,CAC/C,GAAI,KAAK,YAAa,CACpB,MAAM+E,EAAM,KAAK,cAAc,YAC/B,IAAI,aAAa,KAAK,cAAc,OAAO,OAAQA,EAAK/E,EAAI,MAAM,EAAE,IAAIA,CAAG,EAC3E,KAAK,YAAY,UAAU+E,EAAK/E,EAAI,MAAM,EAC1C,MAAMgF,EAAa,IAAI,aAAa,KAAK,cAAc,OAAO,OAAQD,EAAK/E,EAAI,MAAM,EACrFA,EAAI,IAAIgF,CAAU,CACpB,MACEjF,EAAUC,CAAG,CAEjB,CAEQ,YAAmB,CACzB,GAAI,KAAK,OACP,MAAM,IAAI,MAAM,mCAAmC,CAEvD,CACF"}
1
+ {"version":3,"file":"eigen-db.umd.cjs","sources":["../src/lib/errors.ts","../src/lib/storage.ts","../src/lib/compute.ts","../src/lib/lexicon.ts","../src/lib/memory-manager.ts","../src/lib/result-set.ts","../src/lib/simd-binary.ts","../src/lib/wasm-compute.ts","../src/lib/vector-db.ts"],"sourcesContent":["/**\n * Thrown when the database exceeds the 4GB WebAssembly 32-bit memory limit,\n * or the browser's available RAM.\n */\nexport class VectorCapacityExceededError extends Error {\n constructor(maxVectors: number) {\n super(`Capacity exceeded. Max vectors for this dimension size is ~${maxVectors}.`);\n this.name = \"VectorCapacityExceededError\";\n }\n}\n","/**\n * Storage abstraction for append-only binary files.\n * Supports OPFS for browser and in-memory for testing.\n */\n\nexport interface StorageProvider {\n /** Read the entire contents of a file. Returns empty Uint8Array if file doesn't exist. */\n readAll(fileName: string): Promise<Uint8Array>;\n\n /** Append data to a file (creates if it doesn't exist). */\n append(fileName: string, data: Uint8Array): Promise<void>;\n\n /** Write data to a file, replacing all existing content. */\n write(fileName: string, data: Uint8Array): Promise<void>;\n\n /** Delete the storage directory and all files. */\n destroy(): Promise<void>;\n}\n\n/**\n * OPFS-backed storage provider for browser environments.\n * Uses Origin Private File System for high-performance persistent storage.\n */\nexport class OPFSStorageProvider implements StorageProvider {\n private dirHandle: FileSystemDirectoryHandle | null = null;\n private dirName: string;\n\n constructor(dirName: string) {\n this.dirName = dirName;\n }\n\n private async getDir(): Promise<FileSystemDirectoryHandle> {\n if (!this.dirHandle) {\n const root = await navigator.storage.getDirectory();\n this.dirHandle = await root.getDirectoryHandle(this.dirName, { create: true });\n }\n return this.dirHandle;\n }\n\n async readAll(fileName: string): Promise<Uint8Array> {\n try {\n const dir = await this.getDir();\n const fileHandle = await dir.getFileHandle(fileName);\n const file = await fileHandle.getFile();\n const buffer = await file.arrayBuffer();\n return new Uint8Array(buffer);\n } catch {\n return new Uint8Array(0);\n }\n }\n\n async append(fileName: string, data: Uint8Array): Promise<void> {\n const dir = await this.getDir();\n const fileHandle = await dir.getFileHandle(fileName, { create: true });\n const writable = await fileHandle.createWritable({ keepExistingData: true });\n const file = await fileHandle.getFile();\n await writable.seek(file.size);\n await writable.write(data as unknown as BufferSource);\n await writable.close();\n }\n\n async write(fileName: string, data: Uint8Array): Promise<void> {\n const dir = await this.getDir();\n const fileHandle = await dir.getFileHandle(fileName, { create: true });\n const writable = await fileHandle.createWritable({ keepExistingData: false });\n await writable.write(data as unknown as BufferSource);\n await writable.close();\n }\n\n async destroy(): Promise<void> {\n const root = await navigator.storage.getDirectory();\n await root.removeEntry(this.dirName, { recursive: true });\n this.dirHandle = null;\n }\n}\n\n/**\n * In-memory storage provider for testing.\n */\nexport class InMemoryStorageProvider implements StorageProvider {\n private files = new Map<string, Uint8Array[]>();\n\n async readAll(fileName: string): Promise<Uint8Array> {\n const chunks = this.files.get(fileName);\n if (!chunks || chunks.length === 0) return new Uint8Array(0);\n\n const totalSize = chunks.reduce((sum, c) => sum + c.byteLength, 0);\n const result = new Uint8Array(totalSize);\n let offset = 0;\n for (const chunk of chunks) {\n result.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return result;\n }\n\n async append(fileName: string, data: Uint8Array): Promise<void> {\n if (!this.files.has(fileName)) {\n this.files.set(fileName, []);\n }\n this.files.get(fileName)!.push(new Uint8Array(data));\n }\n\n async write(fileName: string, data: Uint8Array): Promise<void> {\n this.files.set(fileName, [new Uint8Array(data)]);\n }\n\n async destroy(): Promise<void> {\n this.files.clear();\n }\n}\n","/**\n * Pure JavaScript compute functions for vector operations.\n * These serve as the reference implementation and fallback when WASM SIMD is unavailable.\n */\n\n/**\n * Normalizes a vector in-place to unit length.\n * After normalization, cosine similarity reduces to a simple dot product.\n */\nexport function normalize(vec: Float32Array): void {\n let sumSq = 0;\n for (let i = 0; i < vec.length; i++) {\n sumSq += vec[i] * vec[i];\n }\n const mag = Math.sqrt(sumSq);\n if (mag === 0) return;\n const invMag = 1 / mag;\n for (let i = 0; i < vec.length; i++) {\n vec[i] *= invMag;\n }\n}\n\n/**\n * Computes dot products of query against all vectors in the database.\n * Writes scores to the output array.\n *\n * @param query - Normalized query vector (length = dimensions)\n * @param db - Contiguous flat array of normalized vectors (length = dbSize * dimensions)\n * @param scores - Output array for dot product scores (length = dbSize)\n * @param dbSize - Number of vectors in the database\n * @param dimensions - Dimensionality of each vector\n */\nexport function searchAll(\n query: Float32Array,\n db: Float32Array,\n scores: Float32Array,\n dbSize: number,\n dimensions: number,\n): void {\n for (let i = 0; i < dbSize; i++) {\n let dot = 0;\n const offset = i * dimensions;\n for (let j = 0; j < dimensions; j++) {\n dot += query[j] * db[offset + j];\n }\n scores[i] = dot;\n }\n}\n","/**\n * Lexicon: length-prefixed UTF-8 encoding for text strings.\n *\n * Format: Each entry is [4-byte uint32 length][UTF-8 bytes]\n * This allows efficient sequential reading and appending.\n */\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\n/**\n * Encodes an array of strings into a length-prefixed binary format.\n */\nexport function encodeLexicon(texts: string[]): Uint8Array {\n const encoded = texts.map((t) => encoder.encode(t));\n const totalSize = encoded.reduce((sum, e) => sum + 4 + e.byteLength, 0);\n\n const buffer = new ArrayBuffer(totalSize);\n const view = new DataView(buffer);\n const bytes = new Uint8Array(buffer);\n let offset = 0;\n\n for (const e of encoded) {\n view.setUint32(offset, e.byteLength, true); // little-endian\n offset += 4;\n bytes.set(e, offset);\n offset += e.byteLength;\n }\n\n return bytes;\n}\n\n/**\n * Decodes all strings from a length-prefixed binary buffer.\n */\nexport function decodeLexicon(data: Uint8Array): string[] {\n const result: string[] = [];\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n let offset = 0;\n\n while (offset < data.byteLength) {\n const len = view.getUint32(offset, true);\n offset += 4;\n const text = decoder.decode(data.subarray(offset, offset + len));\n result.push(text);\n offset += len;\n }\n\n return result;\n}\n\n/**\n * Decodes a single string at a given index from the lexicon.\n * Returns the string and the byte offset of the next entry.\n */\nexport function decodeLexiconAt(data: Uint8Array, index: number): string {\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n let offset = 0;\n\n for (let i = 0; i < index; i++) {\n const len = view.getUint32(offset, true);\n offset += 4 + len;\n }\n\n const len = view.getUint32(offset, true);\n offset += 4;\n return decoder.decode(data.subarray(offset, offset + len));\n}\n\n/**\n * Builds an index of byte offsets for each entry in the lexicon.\n * Enables O(1) access to any entry by index.\n */\nexport function buildLexiconIndex(data: Uint8Array): Uint32Array {\n const offsets: number[] = [];\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n let offset = 0;\n\n while (offset < data.byteLength) {\n offsets.push(offset);\n const len = view.getUint32(offset, true);\n offset += 4 + len;\n }\n\n return new Uint32Array(offsets);\n}\n\n/**\n * Decodes a string at a given byte offset in the lexicon.\n */\nexport function decodeLexiconAtOffset(data: Uint8Array, byteOffset: number): string {\n const view = new DataView(data.buffer, data.byteOffset, data.byteLength);\n const len = view.getUint32(byteOffset, true);\n return decoder.decode(data.subarray(byteOffset + 4, byteOffset + 4 + len));\n}\n","/**\n * Memory Manager for WASM shared memory.\n *\n * Memory Layout:\n * [ 0x00000 ] -> Query Vector Buffer (Fixed, dimensions * 4 bytes, aligned to 64KB page)\n * [ DB_OFFSET ] -> Vector Database (Grows dynamically)\n * [ Dynamic ] -> Scores Buffer (Mapped after DB during search)\n */\n\n/** WASM page size is 64KB */\nconst PAGE_SIZE = 65536;\n\n/** Maximum WASM memory: ~4GB (65536 pages of 64KB each) */\nconst MAX_PAGES = 65536;\n\nexport class MemoryManager {\n readonly memory: WebAssembly.Memory;\n readonly dimensions: number;\n readonly queryOffset: number;\n readonly dbOffset: number;\n private _vectorCount: number;\n\n constructor(dimensions: number, initialVectorCount: number = 0) {\n this.dimensions = dimensions;\n\n // Query buffer: dimensions * 4 bytes, aligned to page boundary\n this.queryOffset = 0;\n const queryBytes = dimensions * 4;\n this.dbOffset = Math.ceil(queryBytes / PAGE_SIZE) * PAGE_SIZE;\n\n // Calculate initial memory needed\n const dbBytes = initialVectorCount * dimensions * 4;\n const totalBytes = this.dbOffset + dbBytes;\n const initialPages = Math.max(1, Math.ceil(totalBytes / PAGE_SIZE));\n\n this.memory = new WebAssembly.Memory({ initial: initialPages });\n this._vectorCount = initialVectorCount;\n }\n\n /** Current number of vectors stored */\n get vectorCount(): number {\n return this._vectorCount;\n }\n\n /** Byte offset where the scores buffer starts (right after DB) */\n get scoresOffset(): number {\n return this.dbOffset + this._vectorCount * this.dimensions * 4;\n }\n\n /** Total bytes needed for scores buffer */\n get scoresBytes(): number {\n return this._vectorCount * 4;\n }\n\n /**\n * Maximum vectors that can be stored given the 4GB WASM memory limit.\n * Accounts for query buffer, DB space, and scores buffer.\n */\n get maxVectors(): number {\n const availableBytes = MAX_PAGES * PAGE_SIZE - this.dbOffset;\n // Each vector needs: dimensions * 4 bytes (DB) + 4 bytes (score)\n const bytesPerVector = this.dimensions * 4 + 4;\n return Math.floor(availableBytes / bytesPerVector);\n }\n\n /**\n * Ensures memory is large enough for the current DB + scores buffer.\n * Calls memory.grow() if needed.\n */\n ensureCapacity(additionalVectors: number): void {\n const newTotal = this._vectorCount + additionalVectors;\n const requiredBytes =\n this.dbOffset + newTotal * this.dimensions * 4 + newTotal * 4; // DB + scores\n const currentBytes = this.memory.buffer.byteLength;\n\n if (requiredBytes > currentBytes) {\n const pagesNeeded = Math.ceil((requiredBytes - currentBytes) / PAGE_SIZE);\n const currentPages = currentBytes / PAGE_SIZE;\n if (currentPages + pagesNeeded > MAX_PAGES) {\n throw new Error(\"WASM memory limit exceeded\");\n }\n this.memory.grow(pagesNeeded);\n }\n }\n\n /**\n * Write a query vector into the query buffer region.\n */\n writeQuery(vector: Float32Array): void {\n new Float32Array(this.memory.buffer, this.queryOffset, this.dimensions).set(vector);\n }\n\n /**\n * Append vectors to the database region.\n * Returns the byte offset where the new vectors were written.\n */\n appendVectors(vectors: Float32Array[]): number {\n const startOffset = this.dbOffset + this._vectorCount * this.dimensions * 4;\n let offset = startOffset;\n for (const vec of vectors) {\n new Float32Array(this.memory.buffer, offset, this.dimensions).set(vec);\n offset += this.dimensions * 4;\n }\n this._vectorCount += vectors.length;\n return startOffset;\n }\n\n /**\n * Load raw vector bytes directly into the database region.\n * Used for bulk loading from OPFS.\n */\n loadVectorBytes(data: Uint8Array, vectorCount: number): void {\n new Uint8Array(this.memory.buffer, this.dbOffset, data.byteLength).set(data);\n this._vectorCount = vectorCount;\n }\n\n /**\n * Read the scores buffer as a Float32Array view.\n */\n readScores(): Float32Array {\n return new Float32Array(this.memory.buffer, this.scoresOffset, this._vectorCount);\n }\n\n /**\n * Read the DB region for a specific vector index.\n */\n readVector(index: number): Float32Array {\n const offset = this.dbOffset + index * this.dimensions * 4;\n return new Float32Array(this.memory.buffer, offset, this.dimensions);\n }\n\n /**\n * Write a vector to a specific slot in the database region.\n */\n writeVector(index: number, vector: Float32Array): void {\n const offset = this.dbOffset + index * this.dimensions * 4;\n new Float32Array(this.memory.buffer, offset, this.dimensions).set(vector);\n }\n\n /**\n * Reset the vector count to zero, logically clearing the database.\n * WASM memory is not freed but will be overwritten on next writes.\n */\n reset(): void {\n this._vectorCount = 0;\n }\n}\n","/**\n * RESULT HELPERS\n *\n * Utility functions for sorting scores and producing query results.\n * Two modes:\n * 1. topKResults — eagerly materializes a ResultItem[] (default query path)\n * 2. iterableResults — returns a lazy Iterable<ResultItem> where keys are\n * resolved only as each item is consumed (for pagination / streaming)\n */\n\nexport interface ResultItem {\n key: string;\n score: number;\n}\n\nexport type KeyResolver = (index: number) => string;\n\n/**\n * Sort scores descending and return the top K results as a plain array.\n * All keys are resolved eagerly.\n */\nexport function topKResults(scores: Float32Array, resolveKey: KeyResolver, topK: number): ResultItem[] {\n const n = scores.length;\n if (n === 0) return [];\n\n const indices = new Uint32Array(n);\n for (let i = 0; i < n; i++) indices[i] = i;\n indices.sort((a, b) => scores[b] - scores[a]);\n\n const k = Math.min(topK, n);\n const results: ResultItem[] = new Array(k);\n for (let i = 0; i < k; i++) {\n const idx = indices[i];\n results[i] = { key: resolveKey(idx), score: scores[idx] };\n }\n return results;\n}\n\n/**\n * Sort scores descending and return a lazy iterable over the top K results.\n * Keys are resolved only when each item is consumed, saving allocations\n * when the caller iterates partially (e.g., pagination).\n *\n * The returned iterable is re-iterable — each call to [Symbol.iterator]()\n * produces a fresh cursor over the same pre-sorted data.\n */\nexport function iterableResults(scores: Float32Array, resolveKey: KeyResolver, topK: number): Iterable<ResultItem> {\n const n = scores.length;\n if (n === 0) return [];\n\n const indices = new Uint32Array(n);\n for (let i = 0; i < n; i++) indices[i] = i;\n indices.sort((a, b) => scores[b] - scores[a]);\n\n const k = Math.min(topK, n);\n\n return {\n [Symbol.iterator](): Iterator<ResultItem> {\n let i = 0;\n return {\n next(): IteratorResult<ResultItem> {\n if (i >= k) return { done: true, value: undefined };\n const idx = indices[i++];\n return {\n done: false,\n value: { key: resolveKey(idx), score: scores[idx] },\n };\n },\n };\n },\n };\n}\n","// AUTO-GENERATED - Do not edit. Run: npx tsx scripts/compile-wat.ts\nconst SIMD_WASM_BASE64 = \"AGFzbQEAAAABDgJgAn9/AGAFf39/f38AAg8BA2VudgZtZW1vcnkCAAEDAwIAAQcaAglub3JtYWxpemUAAApzZWFyY2hfYWxsAAEKsgQCtQIFAX8BewN9AXsDf/0MAAAAAAAAAAAAAAAAAAAAACEDIAFBfHEhCEEAIQICQANAIAIgCE8NASAAIAJBAnRqIQogAyAK/QAEACAK/QAEAP3mAf3kASEDIAJBBGohAgwACwsgA/0fACAD/R8BkiAD/R8CIAP9HwOSkiEEIAghCQJAA0AgCSABTw0BIAAgCUECdGohCiAEIAoqAgAgCioCAJSSIQQgCUEBaiEJDAALCyAEkSEFIAVDAAAAAFsEQA8LQwAAgD8gBZUhBiAG/RMhB0EAIQICQANAIAIgCE8NASAAIAJBAnRqIQogCiAK/QAEACAH/eYB/QsEACACQQRqIQIMAAsLIAghCQJAA0AgCSABTw0BIAAgCUECdGohCiAKIAoqAgAgBpQ4AgAgCUEBaiEJDAALCwv4AQQCfwF7AX0GfyAEQXxxIQogBEECdCEOQQAhBQJAA0AgBSADTw0BIAEgBSAObGohCf0MAAAAAAAAAAAAAAAAAAAAACEHQQAhBgJAA0AgBiAKTw0BIAAgBkECdGohDCAJIAZBAnRqIQ0gByAM/QAEACAN/QAEAP3mAf3kASEHIAZBBGohBgwACwsgB/0fACAH/R8BkiAH/R8CIAf9HwOSkiEIIAohCwJAA0AgCyAETw0BIAAgC0ECdGohDCAJIAtBAnRqIQ0gCCAMKgIAIA0qAgCUkiEIIAtBAWohCwwACwsgAiAFQQJ0aiAIOAIAIAVBAWohBQwACwsL\";\n\nexport function getSimdWasmBinary(): Uint8Array {\n const binaryString = atob(SIMD_WASM_BASE64);\n const bytes = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n bytes[i] = binaryString.charCodeAt(i);\n }\n return bytes;\n}\n","/**\n * WASM SIMD compute layer.\n * Compiles the hand-written WAT module and provides typed wrappers\n * that operate on shared WebAssembly.Memory.\n */\n\nexport interface WasmExports {\n normalize(ptr: number, dimensions: number): void;\n search_all(queryPtr: number, dbPtr: number, scoresPtr: number, dbSize: number, dimensions: number): void;\n}\n\n/**\n * Instantiates a WASM module with the given memory and returns typed exports.\n */\nexport async function instantiateWasm(wasmBinary: Uint8Array, memory: WebAssembly.Memory): Promise<WasmExports> {\n const importObject = { env: { memory } };\n const result = await WebAssembly.instantiate(wasmBinary, importObject);\n // WebAssembly.instantiate with a buffer returns { instance, module }\n const instance = (result as unknown as { instance: WebAssembly.Instance }).instance;\n return instance.exports as unknown as WasmExports;\n}\n","/**\n * VectorDB — Key-Value Vector Database\n *\n * Decoupled from embedding providers. Users pass pre-computed vectors\n * as number arrays (or Float32Array) with string keys.\n *\n * Supports:\n * - set/get/setMany/getMany for key-value CRUD\n * - query for similarity search (dot product on normalized vectors)\n * - flush to persist, close to flush+release, clear to wipe\n * - Last-write-wins semantics for duplicate keys (append-only storage)\n */\n\nimport { normalize, searchAll } from \"./compute\";\nimport { VectorCapacityExceededError } from \"./errors\";\nimport { decodeLexicon, encodeLexicon } from \"./lexicon\";\nimport { MemoryManager } from \"./memory-manager\";\nimport type { ResultItem } from \"./result-set\";\nimport { iterableResults, topKResults } from \"./result-set\";\nimport { getSimdWasmBinary } from \"./simd-binary\";\nimport type { StorageProvider } from \"./storage\";\nimport { OPFSStorageProvider } from \"./storage\";\nimport type {\n IterableQueryOptions,\n OpenOptions,\n OpenOptionsInternal,\n QueryOptions,\n SetOptions,\n VectorInput,\n} from \"./types\";\nimport { instantiateWasm, type WasmExports } from \"./wasm-compute\";\n\nconst VECTORS_FILE = \"vectors.bin\";\nconst KEYS_FILE = \"keys.bin\";\n\nexport class VectorDB {\n private readonly memoryManager: MemoryManager;\n private readonly storage: StorageProvider;\n private readonly dimensions: number;\n private readonly shouldNormalize: boolean;\n private wasmExports: WasmExports | null;\n\n /** Maps key to its slot index in the vector array */\n private keyToSlot: Map<string, number>;\n\n /** Maps slot index back to its key */\n private slotToKey: string[];\n\n /** Whether this instance has been closed */\n private closed = false;\n\n private constructor(\n memoryManager: MemoryManager,\n storage: StorageProvider,\n dimensions: number,\n shouldNormalize: boolean,\n wasmExports: WasmExports | null,\n keyToSlot: Map<string, number>,\n slotToKey: string[],\n ) {\n this.memoryManager = memoryManager;\n this.storage = storage;\n this.dimensions = dimensions;\n this.shouldNormalize = shouldNormalize;\n this.wasmExports = wasmExports;\n this.keyToSlot = keyToSlot;\n this.slotToKey = slotToKey;\n }\n\n /**\n * Opens a VectorDB instance.\n * Loads existing data from storage into WASM memory.\n */\n static async open(options: OpenOptions): Promise<VectorDB>;\n static async open(options: OpenOptionsInternal): Promise<VectorDB>;\n static async open(options: OpenOptionsInternal): Promise<VectorDB> {\n const name = options.name ?? \"default\";\n const storage = options.storage ?? new OPFSStorageProvider(name);\n const shouldNormalize = options.normalize !== false;\n\n // Load existing data from storage\n const [vectorBytes, keysBytes] = await Promise.all([storage.readAll(VECTORS_FILE), storage.readAll(KEYS_FILE)]);\n\n // Decode stored keys\n const keys = keysBytes.byteLength > 0 ? decodeLexicon(keysBytes) : [];\n const vectorCount = vectorBytes.byteLength / (options.dimensions * 4);\n\n // Build key-to-slot mapping.\n // flush() always writes deduplicated state, so keys are unique on load.\n const keyToSlot = new Map<string, number>();\n const slotToKey: string[] = [];\n\n for (let i = 0; i < keys.length; i++) {\n keyToSlot.set(keys[i], i);\n slotToKey[i] = keys[i];\n }\n\n // Initialize memory manager\n const mm = new MemoryManager(options.dimensions, vectorCount);\n\n if (vectorBytes.byteLength > 0) {\n mm.loadVectorBytes(vectorBytes, vectorCount);\n }\n\n // Try to instantiate WASM SIMD module\n let wasmExports: WasmExports | null = null;\n const wasmBinary = options.wasmBinary !== undefined ? options.wasmBinary : getSimdWasmBinary();\n if (wasmBinary !== null) {\n try {\n wasmExports = await instantiateWasm(wasmBinary, mm.memory);\n } catch {\n // Fall back to JS compute\n }\n }\n\n return new VectorDB(mm, storage, options.dimensions, shouldNormalize, wasmExports, keyToSlot, slotToKey);\n }\n\n /** Total number of key-value pairs in the database */\n get size(): number {\n return this.keyToSlot.size;\n }\n\n /**\n * Set a key-value pair. If the key already exists, its vector is overwritten (last-write-wins).\n * The value is a number[] or Float32Array of length equal to the configured dimensions.\n */\n set(key: string, value: VectorInput, options?: SetOptions): void {\n this.assertOpen();\n\n if (value.length !== this.dimensions) {\n throw new Error(`Vector dimension mismatch: expected ${this.dimensions}, got ${value.length}`);\n }\n\n // Convert to Float32Array (also clones to avoid mutating caller's array)\n const vec = new Float32Array(value);\n\n // Normalize if needed\n const doNormalize = options?.normalize ?? this.shouldNormalize;\n if (doNormalize) {\n this.normalizeVector(vec);\n }\n\n const existingSlot = this.keyToSlot.get(key);\n if (existingSlot !== undefined) {\n // Overwrite existing slot\n this.memoryManager.writeVector(existingSlot, vec);\n } else {\n // Append new entry\n const newTotal = this.memoryManager.vectorCount + 1;\n if (newTotal > this.memoryManager.maxVectors) {\n throw new VectorCapacityExceededError(this.memoryManager.maxVectors);\n }\n this.memoryManager.ensureCapacity(1);\n const slotIndex = this.memoryManager.vectorCount;\n this.memoryManager.appendVectors([vec]);\n this.keyToSlot.set(key, slotIndex);\n this.slotToKey[slotIndex] = key;\n }\n }\n\n /**\n * Get the stored vector for a key. Returns undefined if the key does not exist.\n * Returns a copy of the stored vector as a plain number array.\n */\n get(key: string): number[] | undefined {\n this.assertOpen();\n\n const slot = this.keyToSlot.get(key);\n if (slot === undefined) return undefined;\n\n // Return a plain array copy so callers can't corrupt WASM memory\n return Array.from(this.memoryManager.readVector(slot));\n }\n\n /**\n * Set multiple key-value pairs at once. Last-write-wins applies within the batch.\n */\n setMany(entries: [string, VectorInput][]): void {\n for (const [key, value] of entries) {\n this.set(key, value);\n }\n }\n\n /**\n * Get vectors for multiple keys. Returns undefined for keys that don't exist.\n */\n getMany(keys: string[]): (number[] | undefined)[] {\n return keys.map((key) => this.get(key));\n }\n\n /**\n * Search for the most similar vectors to the given query vector.\n *\n * Default: returns a plain ResultItem[] sorted by descending similarity.\n * With `{ iterable: true }`: returns a lazy Iterable<ResultItem> where keys\n * are resolved only as each item is consumed.\n */\n query(value: VectorInput, options: IterableQueryOptions): Iterable<ResultItem>;\n query(value: VectorInput, options?: QueryOptions): ResultItem[];\n query(value: VectorInput, options?: QueryOptions | IterableQueryOptions): ResultItem[] | Iterable<ResultItem> {\n this.assertOpen();\n\n const k = options?.topK ?? this.size;\n const iterable = options && \"iterable\" in options && options.iterable;\n\n if (this.size === 0) {\n return [];\n }\n\n if (value.length !== this.dimensions) {\n throw new Error(`Query vector dimension mismatch: expected ${this.dimensions}, got ${value.length}`);\n }\n\n // Convert to Float32Array and optionally normalize the query vector\n const queryVec = new Float32Array(value);\n const doNormalize = options?.normalize ?? this.shouldNormalize;\n if (doNormalize) {\n this.normalizeVector(queryVec);\n }\n\n // Write query to WASM memory\n this.memoryManager.writeQuery(queryVec);\n\n // Ensure memory has space for scores buffer\n this.memoryManager.ensureCapacity(0);\n\n // Total vectors in memory\n const totalVectors = this.memoryManager.vectorCount;\n\n // Execute search\n const scoresOffset = this.memoryManager.scoresOffset;\n if (this.wasmExports) {\n this.wasmExports.search_all(\n this.memoryManager.queryOffset,\n this.memoryManager.dbOffset,\n scoresOffset,\n totalVectors,\n this.dimensions,\n );\n } else {\n const queryView = new Float32Array(\n this.memoryManager.memory.buffer,\n this.memoryManager.queryOffset,\n this.dimensions,\n );\n const dbView = new Float32Array(\n this.memoryManager.memory.buffer,\n this.memoryManager.dbOffset,\n totalVectors * this.dimensions,\n );\n const scoresView = new Float32Array(this.memoryManager.memory.buffer, scoresOffset, totalVectors);\n searchAll(queryView, dbView, scoresView, totalVectors, this.dimensions);\n }\n\n // Read scores (make a copy so the buffer can be reused)\n const scores = new Float32Array(this.memoryManager.readScores());\n\n // Resolve key from slot index\n const slotToKey = this.slotToKey;\n const resolveKey = (slotIndex: number): string => {\n return slotToKey[slotIndex];\n };\n\n if (iterable) {\n return iterableResults(scores, resolveKey, k);\n }\n return topKResults(scores, resolveKey, k);\n }\n\n /**\n * Persist the current in-memory state to storage.\n */\n async flush(): Promise<void> {\n this.assertOpen();\n\n const totalVectors = this.memoryManager.vectorCount;\n\n // Serialize vectors from WASM memory\n const vectorBytes = new Uint8Array(totalVectors * this.dimensions * 4);\n if (totalVectors > 0) {\n const src = new Uint8Array(\n this.memoryManager.memory.buffer,\n this.memoryManager.dbOffset,\n totalVectors * this.dimensions * 4,\n );\n vectorBytes.set(src);\n }\n\n // Serialize keys using lexicon format\n const keysBytes = encodeLexicon(this.slotToKey);\n\n await Promise.all([this.storage.write(VECTORS_FILE, vectorBytes), this.storage.write(KEYS_FILE, keysBytes)]);\n }\n\n /**\n * Flush data to storage and release the instance.\n * The instance cannot be used after close.\n */\n async close(): Promise<void> {\n if (this.closed) return;\n await this.flush();\n this.closed = true;\n }\n\n /**\n * Clear all data from the database and storage.\n */\n async clear(): Promise<void> {\n this.assertOpen();\n\n this.keyToSlot.clear();\n this.slotToKey.length = 0;\n this.memoryManager.reset();\n\n await this.storage.destroy();\n }\n\n /**\n * Normalize a vector using WASM (if available) or JS fallback.\n */\n private normalizeVector(vec: Float32Array): void {\n if (this.wasmExports) {\n const ptr = this.memoryManager.queryOffset;\n new Float32Array(this.memoryManager.memory.buffer, ptr, vec.length).set(vec);\n this.wasmExports.normalize(ptr, vec.length);\n const normalized = new Float32Array(this.memoryManager.memory.buffer, ptr, vec.length);\n vec.set(normalized);\n } else {\n normalize(vec);\n }\n }\n\n private assertOpen(): void {\n if (this.closed) {\n throw new Error(\"VectorDB instance has been closed\");\n }\n }\n}\n"],"names":["VectorCapacityExceededError","maxVectors","OPFSStorageProvider","dirName","root","fileName","buffer","data","fileHandle","writable","file","InMemoryStorageProvider","chunks","totalSize","sum","c","result","offset","chunk","normalize","vec","sumSq","i","mag","invMag","searchAll","query","db","scores","dbSize","dimensions","dot","j","encoder","decoder","encodeLexicon","texts","encoded","t","e","view","bytes","decodeLexicon","len","text","PAGE_SIZE","MAX_PAGES","MemoryManager","initialVectorCount","queryBytes","dbBytes","totalBytes","initialPages","availableBytes","bytesPerVector","additionalVectors","newTotal","requiredBytes","currentBytes","pagesNeeded","vector","vectors","startOffset","vectorCount","index","topKResults","resolveKey","topK","n","indices","a","b","k","results","idx","iterableResults","SIMD_WASM_BASE64","getSimdWasmBinary","binaryString","instantiateWasm","wasmBinary","memory","importObject","VECTORS_FILE","KEYS_FILE","VectorDB","memoryManager","storage","shouldNormalize","wasmExports","keyToSlot","slotToKey","options","name","vectorBytes","keysBytes","keys","mm","key","value","existingSlot","slotIndex","slot","entries","iterable","queryVec","totalVectors","scoresOffset","queryView","dbView","scoresView","src","ptr","normalized"],"mappings":"gOAIO,MAAMA,UAAoC,KAAM,CACrD,YAAYC,EAAoB,CAC9B,MAAM,8DAA8DA,CAAU,GAAG,EACjF,KAAK,KAAO,6BACd,CACF,CCcO,MAAMC,CAA+C,CAClD,UAA8C,KAC9C,QAER,YAAYC,EAAiB,CAC3B,KAAK,QAAUA,CACjB,CAEA,MAAc,QAA6C,CACzD,GAAI,CAAC,KAAK,UAAW,CACnB,MAAMC,EAAO,MAAM,UAAU,QAAQ,aAAA,EACrC,KAAK,UAAY,MAAMA,EAAK,mBAAmB,KAAK,QAAS,CAAE,OAAQ,GAAM,CAC/E,CACA,OAAO,KAAK,SACd,CAEA,MAAM,QAAQC,EAAuC,CACnD,GAAI,CAIF,MAAMC,EAAS,MADF,MADM,MADP,MAAM,KAAK,OAAA,GACM,cAAcD,CAAQ,GACrB,QAAA,GACJ,YAAA,EAC1B,OAAO,IAAI,WAAWC,CAAM,CAC9B,MAAQ,CACN,OAAO,IAAI,WAAW,CAAC,CACzB,CACF,CAEA,MAAM,OAAOD,EAAkBE,EAAiC,CAE9D,MAAMC,EAAa,MADP,MAAM,KAAK,OAAA,GACM,cAAcH,EAAU,CAAE,OAAQ,GAAM,EA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