edgevec 0.9.0

High-performance embedded vector database for Browser, Node, and Edge
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
/**
 * EdgeVec Performance Utilities
 * Debouncing, throttling, lazy loading, and performance monitoring
 * @version 0.6.0
 */

// =============================================================================
// Debounce & Throttle
// =============================================================================

/**
 * Debounces a function - delays execution until after wait milliseconds
 * have elapsed since the last time the debounced function was invoked.
 * @param {Function} func - Function to debounce
 * @param {number} wait - Milliseconds to wait
 * @param {Object} options - Options
 * @returns {Function} Debounced function
 */
export function debounce(func, wait = 250, options = {}) {
  let timeoutId = null;
  let lastArgs = null;
  let lastThis = null;
  let result = null;
  let lastCallTime = null;
  const leading = options.leading ?? false;
  const trailing = options.trailing ?? true;
  const maxWait = options.maxWait ?? null;

  function invokeFunc(time) {
    const args = lastArgs;
    const thisArg = lastThis;
    lastArgs = null;
    lastThis = null;
    lastCallTime = time;
    result = func.apply(thisArg, args);
    return result;
  }

  function shouldInvoke(time) {
    const timeSinceLastCall = lastCallTime === null ? 0 : time - lastCallTime;
    return (
      lastCallTime === null ||
      timeSinceLastCall >= wait ||
      timeSinceLastCall < 0 ||
      (maxWait !== null && timeSinceLastCall >= maxWait)
    );
  }

  function timerExpired() {
    const time = Date.now();
    if (shouldInvoke(time)) {
      return trailingEdge(time);
    }
    const remainingWait = wait - (time - lastCallTime);
    const maxRemaining = maxWait !== null ? maxWait - (time - lastCallTime) : remainingWait;
    timeoutId = setTimeout(timerExpired, Math.min(remainingWait, maxRemaining));
  }

  function trailingEdge(time) {
    timeoutId = null;
    if (trailing && lastArgs) {
      return invokeFunc(time);
    }
    lastArgs = null;
    lastThis = null;
    return result;
  }

  function leadingEdge(time) {
    lastCallTime = time;
    timeoutId = setTimeout(timerExpired, wait);
    return leading ? invokeFunc(time) : result;
  }

  function debounced(...args) {
    const time = Date.now();
    const isInvoking = shouldInvoke(time);

    lastArgs = args;
    lastThis = this;

    if (isInvoking) {
      if (timeoutId === null) {
        return leadingEdge(time);
      }
      if (maxWait !== null) {
        timeoutId = setTimeout(timerExpired, wait);
        return invokeFunc(time);
      }
    }

    if (timeoutId === null) {
      timeoutId = setTimeout(timerExpired, wait);
    }

    return result;
  }

  debounced.cancel = function() {
    if (timeoutId !== null) {
      clearTimeout(timeoutId);
    }
    lastCallTime = null;
    lastArgs = null;
    lastThis = null;
    timeoutId = null;
  };

  debounced.flush = function() {
    return timeoutId === null ? result : trailingEdge(Date.now());
  };

  debounced.pending = function() {
    return timeoutId !== null;
  };

  return debounced;
}

/**
 * Throttles a function - ensures it's called at most once per wait period.
 * @param {Function} func - Function to throttle
 * @param {number} wait - Milliseconds between allowed calls
 * @param {Object} options - Options
 * @returns {Function} Throttled function
 */
export function throttle(func, wait = 100, options = {}) {
  const leading = options.leading ?? true;
  const trailing = options.trailing ?? true;

  return debounce(func, wait, {
    leading,
    trailing,
    maxWait: wait
  });
}

// =============================================================================
// Lazy Loading
// =============================================================================

/**
 * Creates a lazy loader for images and iframes using IntersectionObserver.
 * @param {Object} options - Lazy loading options
 * @returns {Object} Lazy loader instance
 */
export function createLazyLoader(options = {}) {
  const rootMargin = options.rootMargin ?? '100px';
  const threshold = options.threshold ?? 0;
  const selector = options.selector ?? '[data-lazy]';
  const loadedClass = options.loadedClass ?? 'lazy-loaded';
  const errorClass = options.errorClass ?? 'lazy-error';
  const onLoad = options.onLoad ?? null;
  const onError = options.onError ?? null;

  const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        const element = entry.target;
        loadElement(element);
        observer.unobserve(element);
      }
    });
  }, {
    rootMargin,
    threshold
  });

  function loadElement(element) {
    const src = element.dataset.src || element.dataset.lazy;
    const srcset = element.dataset.srcset;
    const bgImage = element.dataset.bgImage;

    if (src) {
      if (element.tagName === 'IMG') {
        element.onload = () => {
          element.classList.add(loadedClass);
          if (onLoad) onLoad(element);
        };
        element.onerror = () => {
          element.classList.add(errorClass);
          if (onError) onError(element);
        };
        element.src = src;
        if (srcset) {
          element.srcset = srcset;
        }
      } else if (element.tagName === 'IFRAME') {
        element.onload = () => {
          element.classList.add(loadedClass);
          if (onLoad) onLoad(element);
        };
        element.src = src;
      }
    }

    if (bgImage) {
      const img = new Image();
      img.onload = () => {
        element.style.backgroundImage = `url(${bgImage})`;
        element.classList.add(loadedClass);
        if (onLoad) onLoad(element);
      };
      img.onerror = () => {
        element.classList.add(errorClass);
        if (onError) onError(element);
      };
      img.src = bgImage;
    }

    // Remove data attributes
    delete element.dataset.src;
    delete element.dataset.srcset;
    delete element.dataset.bgImage;
    delete element.dataset.lazy;
  }

  function observe(element) {
    observer.observe(element);
  }

  function observeAll() {
    document.querySelectorAll(selector).forEach(el => {
      observer.observe(el);
    });
  }

  function disconnect() {
    observer.disconnect();
  }

  return {
    observe,
    observeAll,
    disconnect,
    loadElement
  };
}

// =============================================================================
// Performance Monitoring
// =============================================================================

/**
 * Performance monitor for tracking operation timing.
 */
export class PerformanceMonitor {
  constructor(options = {}) {
    this.metrics = new Map();
    this.enabled = options.enabled ?? true;
    this.maxSamples = options.maxSamples ?? 100;
    this.onMetric = options.onMetric ?? null;
  }

  /**
   * Start timing an operation.
   * @param {string} name - Operation name
   * @returns {Function} End function to call when operation completes
   */
  start(name) {
    if (!this.enabled) {
      return () => 0;
    }

    const startTime = performance.now();

    return () => {
      const duration = performance.now() - startTime;
      this.record(name, duration);
      return duration;
    };
  }

  /**
   * Record a metric value.
   * @param {string} name - Metric name
   * @param {number} value - Metric value
   */
  record(name, value) {
    if (!this.enabled) return;

    if (!this.metrics.has(name)) {
      this.metrics.set(name, []);
    }

    const samples = this.metrics.get(name);
    samples.push(value);

    // Keep only the last maxSamples
    if (samples.length > this.maxSamples) {
      samples.shift();
    }

    if (this.onMetric) {
      this.onMetric(name, value, this.getStats(name));
    }
  }

  /**
   * Get statistics for a metric.
   * @param {string} name - Metric name
   * @returns {Object} Statistics
   */
  getStats(name) {
    const samples = this.metrics.get(name);
    if (!samples || samples.length === 0) {
      return null;
    }

    const sorted = [...samples].sort((a, b) => a - b);
    const sum = samples.reduce((a, b) => a + b, 0);
    const count = samples.length;

    return {
      count,
      min: sorted[0],
      max: sorted[count - 1],
      mean: sum / count,
      median: sorted[Math.floor(count / 2)],
      p95: sorted[Math.floor(count * 0.95)],
      p99: sorted[Math.floor(count * 0.99)],
      sum,
      samples: [...samples]
    };
  }

  /**
   * Get all metrics.
   * @returns {Object} All metrics with statistics
   */
  getAll() {
    const result = {};
    for (const [name] of this.metrics) {
      result[name] = this.getStats(name);
    }
    return result;
  }

  /**
   * Clear all metrics.
   */
  clear() {
    this.metrics.clear();
  }

  /**
   * Clear a specific metric.
   * @param {string} name - Metric name
   */
  clearMetric(name) {
    this.metrics.delete(name);
  }
}

// =============================================================================
// Frame Rate Monitor
// =============================================================================

/**
 * Monitors frame rate (FPS) for performance debugging.
 */
export class FPSMonitor {
  constructor(options = {}) {
    this.samples = [];
    this.maxSamples = options.maxSamples ?? 60;
    this.lastFrameTime = 0;
    this.animationId = null;
    this.isRunning = false;
    this.onUpdate = options.onUpdate ?? null;
    this.updateInterval = options.updateInterval ?? 500;
    this.lastUpdateTime = 0;
  }

  start() {
    if (this.isRunning) return;
    this.isRunning = true;
    this.lastFrameTime = performance.now();
    this.lastUpdateTime = performance.now();
    this.tick();
  }

  tick() {
    if (!this.isRunning) return;

    const now = performance.now();
    const delta = now - this.lastFrameTime;
    this.lastFrameTime = now;

    // Calculate FPS for this frame
    const fps = 1000 / delta;
    this.samples.push(fps);

    // Keep only last N samples
    if (this.samples.length > this.maxSamples) {
      this.samples.shift();
    }

    // Call onUpdate at specified interval
    if (this.onUpdate && now - this.lastUpdateTime >= this.updateInterval) {
      this.lastUpdateTime = now;
      this.onUpdate(this.getStats());
    }

    this.animationId = requestAnimationFrame(() => this.tick());
  }

  stop() {
    this.isRunning = false;
    if (this.animationId) {
      cancelAnimationFrame(this.animationId);
      this.animationId = null;
    }
  }

  getStats() {
    if (this.samples.length === 0) {
      return { current: 0, average: 0, min: 0, max: 0 };
    }

    const current = this.samples[this.samples.length - 1];
    const sum = this.samples.reduce((a, b) => a + b, 0);
    const average = sum / this.samples.length;
    const min = Math.min(...this.samples);
    const max = Math.max(...this.samples);

    return {
      current: Math.round(current),
      average: Math.round(average),
      min: Math.round(min),
      max: Math.round(max)
    };
  }
}

// =============================================================================
// Memory Monitor (WASM Specific)
// =============================================================================

/**
 * Monitors WASM memory usage.
 */
export class MemoryMonitor {
  constructor(options = {}) {
    this.wasmMemory = options.wasmMemory ?? null;
    this.intervalId = null;
    this.interval = options.interval ?? 1000;
    this.onUpdate = options.onUpdate ?? null;
    this.history = [];
    this.maxHistory = options.maxHistory ?? 60;
  }

  setWasmMemory(memory) {
    this.wasmMemory = memory;
  }

  start() {
    if (this.intervalId) return;

    this.intervalId = setInterval(() => {
      const stats = this.getStats();
      this.history.push({
        timestamp: Date.now(),
        ...stats
      });

      if (this.history.length > this.maxHistory) {
        this.history.shift();
      }

      if (this.onUpdate) {
        this.onUpdate(stats);
      }
    }, this.interval);
  }

  stop() {
    if (this.intervalId) {
      clearInterval(this.intervalId);
      this.intervalId = null;
    }
  }

  getStats() {
    const result = {
      wasmBytes: 0,
      wasmMB: 0,
      jsHeapBytes: 0,
      jsHeapMB: 0,
      jsHeapLimit: 0,
      jsHeapUsedPercent: 0
    };

    // WASM memory
    if (this.wasmMemory) {
      result.wasmBytes = this.wasmMemory.buffer.byteLength;
      result.wasmMB = result.wasmBytes / (1024 * 1024);
    }

    // JS heap (if available)
    if (performance.memory) {
      result.jsHeapBytes = performance.memory.usedJSHeapSize;
      result.jsHeapMB = result.jsHeapBytes / (1024 * 1024);
      result.jsHeapLimit = performance.memory.jsHeapSizeLimit / (1024 * 1024);
      result.jsHeapUsedPercent = (result.jsHeapBytes / performance.memory.jsHeapSizeLimit) * 100;
    }

    return result;
  }

  getHistory() {
    return [...this.history];
  }
}

// =============================================================================
// Request Idle Callback Polyfill
// =============================================================================

/**
 * Schedules work during browser idle periods.
 * Falls back to setTimeout if requestIdleCallback is not available.
 * @param {Function} callback - Work to perform
 * @param {Object} options - Options
 * @returns {number} Handle for cancellation
 */
export function scheduleIdleWork(callback, options = {}) {
  const timeout = options.timeout ?? 1000;

  if (typeof requestIdleCallback !== 'undefined') {
    return requestIdleCallback(callback, { timeout });
  }

  // Fallback for Safari
  return setTimeout(() => {
    callback({
      didTimeout: false,
      timeRemaining: () => 50
    });
  }, 1);
}

/**
 * Cancels scheduled idle work.
 * @param {number} handle - Handle from scheduleIdleWork
 */
export function cancelIdleWork(handle) {
  if (typeof cancelIdleCallback !== 'undefined') {
    cancelIdleCallback(handle);
  } else {
    clearTimeout(handle);
  }
}

// =============================================================================
// Batch DOM Updates
// =============================================================================

/**
 * Batches DOM updates to avoid layout thrashing.
 */
export class DOMBatcher {
  constructor() {
    this.reads = [];
    this.writes = [];
    this.scheduled = false;
  }

  read(fn) {
    this.reads.push(fn);
    this.scheduleFlush();
    return this;
  }

  write(fn) {
    this.writes.push(fn);
    this.scheduleFlush();
    return this;
  }

  scheduleFlush() {
    if (this.scheduled) return;
    this.scheduled = true;

    requestAnimationFrame(() => {
      this.flush();
    });
  }

  flush() {
    // Execute all reads first
    const reads = this.reads;
    this.reads = [];
    reads.forEach(fn => fn());

    // Then execute all writes
    const writes = this.writes;
    this.writes = [];
    writes.forEach(fn => fn());

    this.scheduled = false;

    // If new work was added during flush, schedule again
    if (this.reads.length > 0 || this.writes.length > 0) {
      this.scheduleFlush();
    }
  }
}

// Global instance for convenience
export const domBatcher = new DOMBatcher();

// =============================================================================
// Resource Timing
// =============================================================================

/**
 * Gets timing information for loaded resources.
 * @param {Object} options - Filter options
 * @returns {Array} Resource timing entries
 */
export function getResourceTimings(options = {}) {
  const type = options.type ?? null;
  const minDuration = options.minDuration ?? 0;

  let entries = performance.getEntriesByType('resource');

  if (type) {
    entries = entries.filter(e => e.initiatorType === type);
  }

  if (minDuration > 0) {
    entries = entries.filter(e => e.duration >= minDuration);
  }

  return entries.map(e => ({
    name: e.name,
    type: e.initiatorType,
    duration: Math.round(e.duration),
    size: e.transferSize,
    cached: e.transferSize === 0 && e.decodedBodySize > 0
  }));
}

/**
 * Gets navigation timing metrics.
 * @returns {Object} Navigation timing
 */
export function getNavigationTiming() {
  const nav = performance.getEntriesByType('navigation')[0];
  if (!nav) return null;

  return {
    dns: Math.round(nav.domainLookupEnd - nav.domainLookupStart),
    tcp: Math.round(nav.connectEnd - nav.connectStart),
    ttfb: Math.round(nav.responseStart - nav.requestStart),
    download: Math.round(nav.responseEnd - nav.responseStart),
    domParse: Math.round(nav.domInteractive - nav.responseEnd),
    domContentLoaded: Math.round(nav.domContentLoadedEventEnd - nav.fetchStart),
    load: Math.round(nav.loadEventEnd - nav.fetchStart)
  };
}