All files / web/src/lib/vision/opencv loaderV3.ts

0% Statements 0/55
0% Branches 0/1
0% Functions 0/1
0% Lines 0/55

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                                                                                               
'use client'

/**
 * OpenCV.js Loader v3 - NO module-level state, NO type imports.
 * Exactly like the working addScript + waitForCv but combined.
 */

function isReady(): boolean {
  if (typeof window === 'undefined') return false
  const cv = (window as unknown as { cv?: { imread?: unknown } }).cv
  return !!(cv && typeof cv.imread === 'function')
}

function addScript(): void {
  if (typeof window === 'undefined') return
  const existingScript = document.querySelector('script[src="/opencv.js"]')
  if (existingScript) return
  const script = document.createElement('script')
  script.src = '/opencv.js'
  script.async = true
  document.head.appendChild(script)
}

function waitForReady(timeoutMs: number = 30000): Promise<void> {
  return new Promise((resolve, reject) => {
    if (isReady()) {
      resolve()
      return
    }
    const startTime = Date.now()
    const check = () => {
      if (isReady()) {
        resolve()
      } else if (Date.now() - startTime > timeoutMs) {
        reject(new Error('OpenCV.js initialization timed out'))
      } else {
        setTimeout(check, 50)
      }
    }
    check()
  })
}

// NO module-level state - returns fresh each time
export async function loadOpenCVv3(): Promise<unknown> {
  // If already ready, return immediately
  if (isReady()) {
    return (window as unknown as { cv: unknown }).cv
  }

  // Add script and wait
  addScript()
  await waitForReady()
  return (window as unknown as { cv: unknown }).cv
}