{
  "version": 3,
  "sources": ["../src/errors.ts", "../src/client.ts", "../src/engine/arithmetic.ts", "../src/engine/confidence.ts", "../src/engine/geometry.ts", "../src/engine/controller.ts", "../src/engine/detector.ts", "../src/engine/guidance.ts", "../scripts/parser-stub.ts", "../src/engine/quality.ts", "../src/engine/stability.ts", "../src/engine/engine.ts", "../src/frames.ts", "../src/engine/enhance.ts", "../src/engine/tiles.ts", "../src/image.ts", "../src/camera.ts", "../src/nouns.generated.ts", "../src/nouns.ts", "../src/scanner.ts"],
  "sourcesContent": ["/**\n * One error type for everything the SDK can fail at: the API's own errors\n * (with their type, code and request id), network failures, a camera that\n * cannot start, and a person closing the scanner.\n */\n\nexport type ReceVizErrorType =\n  | \"invalid_request_error\"\n  | \"authentication_error\"\n  | \"permission_error\"\n  | \"not_found_error\"\n  | \"conflict_error\"\n  | \"rate_limit_error\"\n  | \"processing_error\"\n  | \"api_error\"\n  | \"service_unavailable_error\"\n  | \"network_error\"\n  | \"camera_error\"\n  | \"configuration_error\"\n  | \"cancelled\";\n\nexport class ReceVizError extends Error {\n  readonly type: ReceVizErrorType;\n  readonly code: string;\n  readonly status: number | null;\n  readonly requestId: string | null;\n  readonly param: string | null;\n  readonly retryAfter: number | null;\n\n  constructor(\n    type: ReceVizErrorType,\n    code: string,\n    message: string,\n    extra: { status?: number | null; requestId?: string | null; param?: string | null; retryAfter?: number | null } = {}\n  ) {\n    super(message);\n    this.name = \"ReceVizError\";\n    this.type = type;\n    this.code = code;\n    this.status = extra.status ?? null;\n    this.requestId = extra.requestId ?? null;\n    this.param = extra.param ?? null;\n    this.retryAfter = extra.retryAfter ?? null;\n  }\n\n  static cancelled(): ReceVizError {\n    return new ReceVizError(\"cancelled\", \"cancelled\", \"The scan was cancelled.\");\n  }\n}\n\nexport function isReceVizError(value: unknown): value is ReceVizError {\n  return value instanceof ReceVizError;\n}\n", "/**\n * The ReceViz REST client for browsers (and Node 18+, which has fetch).\n *\n * Credentials, safest first:\n *\n *   tokenProvider    a function that asks YOUR server for a client token\n *                    (your server calls POST /v1/client-tokens with its secret\n *                    key). Recommended: nothing permanent reaches the browser.\n *   publishableKey   rv_pk_\u2026 \u2014 exchanged here for a short-lived client token\n *                    (POST /v1/client-sessions); restricted by the key's allowed\n *                    origins. For pages with no server of their own.\n *   token            a client token you already hold (rv_ct_\u2026).\n *\n * A secret key (rv_live_\u2026 / rv_test_\u2026) is refused in a browser: it would be\n * readable by anyone who opens the page.\n */\nimport { ReceVizError, type ReceVizErrorType } from \"./errors.ts\";\nimport type { CredentialContext, DocumentType, Extraction, ExtractOptions } from \"./types.ts\";\n\nexport const SDK_VERSION = \"0.1.0\";\n\n/** Where ReceViz answers today. Override with `baseUrl` (a branded API domain is planned). */\nexport const DEFAULT_BASE_URL = \"https://accounthouse-backend-793493499887.me-central1.run.app/api/receviz/v1\";\n\nexport type ClientOptions = {\n  baseUrl?: string;\n  token?: string;\n  tokenProvider?: () => Promise<string>;\n  publishableKey?: string;\n  /** Restrict a session opened with a publishable key to these document types. */\n  documentTypes?: string[];\n  /** Sent as X-ReceViz-SDK, e.g. \"web/0.1.0\". */\n  sdk?: string;\n  fetch?: typeof fetch;\n};\n\ntype TokenState = { value: string; expiresAt: number };\n\ntype CallInit = { json?: unknown; form?: FormData; headers?: Record<string, string>; signal?: AbortSignal };\n\nconst REFRESH_MARGIN_MS = 30_000;\n\nfunction inBrowser(): boolean {\n  return typeof window !== \"undefined\" && typeof document !== \"undefined\";\n}\n\nexport class Client {\n  readonly baseUrl: string;\n  private readonly options: ClientOptions;\n  private readonly fetchImpl: typeof fetch;\n  private token: TokenState | null = null;\n  private pending: Promise<string> | null = null;\n  /** The document types, asked for once, for the scanner's wording. */\n  private typesOnce: Promise<DocumentType[] | null> | null = null;\n\n  constructor(options: ClientOptions) {\n    this.options = options;\n    this.baseUrl = (options.baseUrl || DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n    const f = options.fetch ?? (typeof fetch !== \"undefined\" ? fetch : undefined);\n    if (!f) throw new ReceVizError(\"configuration_error\", \"no_fetch\", \"No fetch implementation is available.\");\n    this.fetchImpl = f.bind(globalThis);\n    const sources = [options.token, options.tokenProvider, options.publishableKey].filter(Boolean).length;\n    if (sources !== 1) {\n      throw new ReceVizError(\"configuration_error\", \"credentials_required\",\n        \"Give exactly one of token, tokenProvider or publishableKey.\");\n    }\n    if (options.token && /^rv_(live|test)_/.test(options.token) && inBrowser()) {\n      throw new ReceVizError(\n        \"configuration_error\",\n        \"secret_key_in_browser\",\n        \"A secret key must never be used in a browser. Mint a client token on your server \" +\n          \"(POST /v1/client-tokens) and pass a tokenProvider instead.\"\n      );\n    }\n    if (options.publishableKey && !/^rv_pk_(live|test)_/.test(options.publishableKey)) {\n      throw new ReceVizError(\"configuration_error\", \"invalid_publishable_key\", \"That is not a ReceViz publishable key.\");\n    }\n    if (options.token) this.token = { value: options.token, expiresAt: Number.POSITIVE_INFINITY };\n  }\n\n  // \u2500\u2500 credentials \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n  private async credential(force = false): Promise<string> {\n    if (!force && this.token && this.token.expiresAt - REFRESH_MARGIN_MS > Date.now()) return this.token.value;\n    if (this.options.token && !force) return this.options.token;\n    if (this.pending) return this.pending;\n    this.pending = (async () => {\n      try {\n        if (this.options.tokenProvider) {\n          const value = await this.options.tokenProvider();\n          this.token = { value, expiresAt: Date.now() + 9 * 60_000 };\n          return value;\n        }\n        if (this.options.publishableKey) {\n          const session = await this.raw<{ token: string; expires_at: string }>(\"POST\", \"/client-sessions\", {\n            bearer: this.options.publishableKey,\n            json: this.options.documentTypes ? { document_types: this.options.documentTypes } : {},\n          });\n          this.token = { value: session.token, expiresAt: Date.parse(session.expires_at) || Date.now() + 9 * 60_000 };\n          return session.token;\n        }\n        throw new ReceVizError(\"authentication_error\", \"token_expired\", \"The client token has expired.\");\n      } finally {\n        this.pending = null;\n      }\n    })();\n    return this.pending;\n  }\n\n  // \u2500\u2500 transport \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n  private async raw<T>(\n    method: string,\n    path: string,\n    init: CallInit & { bearer: string }\n  ): Promise<T> {\n    const headers: Record<string, string> = {\n      Authorization: `Bearer ${init.bearer}`,\n      \"X-ReceViz-SDK\": this.options.sdk || `web/${SDK_VERSION}`,\n      ...(init.headers || {}),\n    };\n    let body: BodyInit | undefined;\n    if (init.form) body = init.form;\n    else if (init.json !== undefined) {\n      headers[\"Content-Type\"] = \"application/json\";\n      body = JSON.stringify(init.json);\n    }\n    let response: Response;\n    try {\n      response = await this.fetchImpl(`${this.baseUrl}${path}`, { method, headers, body, signal: init.signal });\n    } catch (err) {\n      if ((err as { name?: string })?.name === \"AbortError\") throw ReceVizError.cancelled();\n      throw new ReceVizError(\"network_error\", \"network_error\", \"ReceViz could not be reached. Check the connection.\");\n    }\n    const requestId = response.headers.get(\"x-request-id\");\n    const text = await response.text();\n    let data: any = null;\n    try {\n      data = text ? JSON.parse(text) : null;\n    } catch {\n      data = null;\n    }\n    if (!response.ok) {\n      const error = data?.error ?? {};\n      const retry = Number(response.headers.get(\"retry-after\"));\n      throw new ReceVizError(\n        (error.type as ReceVizErrorType) || (response.status >= 500 ? \"api_error\" : \"invalid_request_error\"),\n        error.code || `http_${response.status}`,\n        error.message || `ReceViz answered ${response.status}.`,\n        { status: response.status, requestId: error.request_id || requestId, param: error.param, retryAfter: Number.isFinite(retry) ? retry : null }\n      );\n    }\n    return data as T;\n  }\n\n  private async call<T>(method: string, path: string, init: CallInit = {}): Promise<T> {\n    try {\n      return await this.raw<T>(method, path, { ...init, bearer: await this.credential() });\n    } catch (err) {\n      if (err instanceof ReceVizError && err.code === \"token_expired\" && !this.options.token) {\n        return this.raw<T>(method, path, { ...init, bearer: await this.credential(true) });\n      }\n      throw err;\n    }\n  }\n\n  // \u2500\u2500 the API \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n  me(): Promise<CredentialContext> {\n    return this.call(\"GET\", \"/me\");\n  }\n\n  async documentTypes(): Promise<DocumentType[]> {\n    const list = await this.call<{ data: DocumentType[] }>(\"GET\", \"/document-types\");\n    return list.data;\n  }\n\n  /**\n   * What a scanner should call this document type (\"invoice\", \"delivery note\"):\n   * the type's own noun as ReceViz reports it, or null when it cannot be\n   * asked (no schemas.read on this credential, offline). Asked once per\n   * client; never throws.\n   */\n  async captureNoun(documentType: string): Promise<string | null> {\n    this.typesOnce ??= this.documentTypes().catch(() => null);\n    const types = await this.typesOnce;\n    const found = types?.find((t) => t.key === documentType || t.id === documentType);\n    return found?.capture?.noun ?? null;\n  }\n\n  getExtraction(id: string, signal?: AbortSignal): Promise<Extraction> {\n    return this.call(\"GET\", `/extractions/${encodeURIComponent(id)}`, { signal });\n  }\n\n  /** Send a document (or on-device text) and get structured data back. */\n  async extract(document: Blob | null, options: ExtractOptions = {}): Promise<Extraction> {\n    const form = new FormData();\n    if (document) {\n      const name = (document as File).name || (document.type === \"application/pdf\" ? \"document.pdf\" : \"document.jpg\");\n      form.append(\"file\", document, name);\n    }\n    if (options.documentType) form.append(\"document_type\", options.documentType);\n    if (options.schemaVersion) form.append(\"schema_version\", String(options.schemaVersion));\n    if (options.mode) form.append(\"mode\", options.mode);\n    if (options.async) form.append(\"async\", \"true\");\n    if (options.options) form.append(\"options\", JSON.stringify(options.options));\n    if (options.metadata) form.append(\"metadata\", JSON.stringify(options.metadata));\n    if (options.clientOcr) form.append(\"client_ocr\", JSON.stringify(options.clientOcr));\n    const headers: Record<string, string> = {};\n    if (options.idempotencyKey) headers[\"Idempotency-Key\"] = options.idempotencyKey;\n    const extraction = await this.call<Extraction>(\"POST\", \"/extractions\", { form, headers, signal: options.signal });\n    if ((extraction.status === \"queued\" || extraction.status === \"processing\") && options.waitForResult !== false) {\n      return this.waitForExtraction(extraction.id, { signal: options.signal });\n    }\n    return extraction;\n  }\n\n  /** Poll an asynchronous extraction until it finishes (or the timeout passes). */\n  async waitForExtraction(\n    id: string,\n    { timeoutMs = 10 * 60_000, signal }: { timeoutMs?: number; signal?: AbortSignal } = {}\n  ): Promise<Extraction> {\n    const deadline = Date.now() + timeoutMs;\n    let delay = 1000;\n    for (;;) {\n      const extraction = await this.getExtraction(id, signal);\n      if (extraction.status === \"succeeded\" || extraction.status === \"failed\") return extraction;\n      if (Date.now() + delay > deadline) {\n        throw new ReceVizError(\"processing_error\", \"wait_timeout\", \"The extraction is still processing. Fetch it later by id.\");\n      }\n      await new Promise((resolve, reject) => {\n        const timer = setTimeout(resolve, delay);\n        signal?.addEventListener(\"abort\", () => {\n          clearTimeout(timer);\n          reject(ReceVizError.cancelled());\n        });\n      });\n      delay = Math.min(8000, Math.round(delay * 1.6));\n    }\n  }\n\n  /** How an on-device reading compared with ReceViz's (counts only \u2014 never values). */\n  sendQualityFeedback(report: {\n    document_type?: string;\n    platform?: string;\n    engine_version?: string;\n    outcomes: Array<{ field: string; device: string; confidence?: number | null; cloud: boolean; agreed?: boolean | null }>;\n    arithmetic?: \"consistent\" | \"inconsistent\" | \"unknown\";\n  }): Promise<{ recorded: boolean }> {\n    return this.call(\"POST\", \"/quality/feedback\", { json: { platform: \"web\", ...report } });\n  }\n}\n", "// AUTO-GENERATED \u2014 DO NOT EDIT.\n// Source: shared/receiptvis-live/core/arithmetic.ts\n// Regenerate: node scripts/sync-receviz-web-sdk.mjs\n/**\n * The receipt checks its own sums.\n *\n * A receipt prints its total two or three times over in effect: the total, the\n * figure before tax (a subtotal or \"taxable amount\"), and the VAT \u2014 and those\n * have to add up. OCR misreads one digit at a time, so a misread total almost\n * never still adds up with the lines that were read correctly. That makes the\n * arithmetic the best witness the phone has:\n *\n *   it ties out      the total is backed by the receipt itself, and counts as a\n *                    second agreeing pass (confidence.ts): believed a pass sooner\n *   it does not      and nothing else on the receipt explains the gap (a\n *                    service charge, a discount, a tip, rounding\u2026), the reading\n *                    is flagged so a person checks the total\n *   it cannot say    no subtotal or no VAT line was read \u2014 most slips \u2014 and\n *                    nothing is claimed either way\n *\n * The relations tried, all to the cent (\u00B12 fils for rounding):\n *\n *   base + tax = total                      subtotal 80 + VAT 4 = 84\n *   base = total, tax = total \u00D7 r/(100+r)   a VAT-inclusive subtotal\n *   tax = total \u00D7 r/(100+r)                 the rate alone (weaker: no base)\n *\n * r is the rate printed on a VAT line (\"VAT @5%\"), or 5 \u2014 the UAE rate \u2014 when\n * none is printed. Two tax lines (CGST + SGST) are also tried as their sum.\n */\nimport type { FieldCandidate, FieldKey, FieldReading } from \"./types.ts\";\n\n/** What one OCR pass read that the sums are made of. Values are canonical (\"84.00\"). */\nexport type ArithmeticFacts = {\n  /** Subtotal and \"taxable amount\" figures, in the order printed. */\n  bases: string[];\n  /** One figure per VAT/tax line, in the order printed. */\n  taxes: string[];\n  /** Percentages printed on the VAT/tax lines. */\n  rates: number[];\n  /**\n   * The receipt charges or takes off something besides the VAT \u2014 a service\n   * charge, a municipality fee, a discount, a tip, rounding \u2014 so a total that\n   * does not equal base + tax is not evidence of a misread.\n   */\n  extras: boolean;\n};\n\nexport const NO_FACTS: ArithmeticFacts = { bases: [], taxes: [], rates: [], extras: false };\n\nexport type ArithmeticRelation = \"base_plus_tax\" | \"tax_inclusive\" | \"rate\";\n\nexport type Relation = {\n  /** \"full\": a base and a tax account for the total; \"rate\": only the VAT rate does. */\n  strength: \"full\" | \"rate\";\n  relation: ArithmeticRelation;\n  base?: string;\n  tax: string;\n};\n\nexport type ArithmeticVerdict = {\n  status: \"consistent\" | \"inconsistent\" | \"unknown\";\n  relation?: ArithmeticRelation;\n  amount?: string;\n  base?: string;\n  tax?: string;\n};\n\n/** The UAE rate: assumed when a VAT line prints no percentage. */\nconst DEFAULT_RATE = 5;\n/** Fils of slack for rounding. */\nconst SLACK = 2;\n\nconst fils = (value: string | number) => Math.round(Number(value) * 100);\n\nfunction taxOptions(facts: ArithmeticFacts): string[] {\n  const unique = [...new Set(facts.taxes)];\n  if (facts.taxes.length >= 2) {\n    const sum = facts.taxes.reduce((s, t) => s + fils(t), 0);\n    const total = (sum / 100).toFixed(2);\n    if (!unique.includes(total)) unique.push(total);\n  }\n  return unique;\n}\n\n/** How the receipt's own figures account for `amount`, if they do. */\nexport function relate(amount: string, facts: ArithmeticFacts): Relation | null {\n  const a = fils(amount);\n  if (!(a > 0)) return null;\n  const taxes = taxOptions(facts).filter((t) => fils(t) > 0 && fils(t) < a);\n  if (!taxes.length) return null;\n  for (const base of facts.bases) {\n    for (const tax of taxes) {\n      if (Math.abs(fils(base) + fils(tax) - a) <= SLACK) {\n        return { strength: \"full\", relation: \"base_plus_tax\", base, tax };\n      }\n    }\n  }\n  const rates = facts.rates.length ? facts.rates : [DEFAULT_RATE];\n  for (const tax of taxes) {\n    for (const rate of rates) {\n      const inclusive = (a * rate) / (100 + rate);\n      if (Math.abs(fils(tax) - inclusive) > SLACK) continue;\n      const base = facts.bases.find((b) => Math.abs(fils(b) - a) <= SLACK);\n      return base\n        ? { strength: \"full\", relation: \"tax_inclusive\", base, tax }\n        : { strength: \"rate\", relation: \"rate\", tax };\n    }\n  }\n  return null;\n}\n\n/**\n * Mark the candidates of one pass that the pass's own sums back up. A total\n * that a base and a tax fully account for is lifted and flagged corroborated\n * (a second witness); one only the VAT rate agrees with is lifted a little.\n */\nexport function corroborate(candidates: FieldCandidate[], facts: ArithmeticFacts): void {\n  if (!facts.taxes.length) return;\n  const lift = (c: FieldCandidate, by: number) => {\n    c.score = Math.min(0.97, c.score + by);\n  };\n  const backed = new Set<string>();\n  const backedTaxes = new Set<string>();\n  for (const c of candidates) {\n    if (c.field !== \"amount\") continue;\n    const relation = relate(c.value, facts);\n    if (!relation) continue;\n    if (relation.strength === \"full\") {\n      lift(c, 0.12);\n      c.corroborated = true;\n      backed.add(c.value);\n      backedTaxes.add(relation.tax);\n    } else {\n      lift(c, 0.04);\n    }\n  }\n  if (!backed.size) return;\n  for (const c of candidates) {\n    if (c.field === \"tax\" && backedTaxes.has(c.value)) {\n      lift(c, 0.08);\n      c.corroborated = true;\n    }\n  }\n}\n\n/**\n * The verdict on what the scan settled on: does the total it read add up with\n * the subtotal and VAT printed on the same receipt?\n */\nexport function checkArithmetic(\n  fields: Partial<Record<FieldKey, FieldReading>>,\n  facts: ArithmeticFacts | null\n): ArithmeticVerdict {\n  const amount = fields.amount?.value;\n  if (!facts || !amount) return { status: \"unknown\" };\n  const relation = relate(amount, facts);\n  if (relation) {\n    return { status: \"consistent\", relation: relation.relation, amount, base: relation.base, tax: relation.tax };\n  }\n  if (facts.extras) return { status: \"unknown\", amount };\n  const tax = fields.tax?.value ?? facts.taxes[facts.taxes.length - 1];\n  if (!tax || !facts.bases.length) return { status: \"unknown\", amount };\n  // The base shown is the one the total should have been built from: the\n  // largest printed below the total (a subtotal before the VAT).\n  const below = facts.bases.filter((b) => fils(b) < fils(amount));\n  const base = (below.length ? below : facts.bases).reduce((m, b) => (fils(b) > fils(m) ? b : m));\n  return { status: \"inconsistent\", amount, base, tax };\n}\n", "// AUTO-GENERATED \u2014 DO NOT EDIT.\n// Source: shared/receiptvis-live/core/confidence.ts\n// Regenerate: node scripts/sync-receviz-web-sdk.mjs\n/**\n * The confidence engine: believe a value only when the passes agree on it.\n *\n * One OCR pass is one witness, and OCR witnesses are unreliable in a\n * particular way \u2014 the same frame read twice agrees with itself, but a 5 read\n * as a 6 in one frame is usually read correctly in the next. So every pass\n * VOTES, and a field's confidence is two things multiplied:\n *\n *   agreement \u2014 the winning value's share of all the weight cast for the field\n *   evidence  \u2014 how much weight there is at all (1 \u2212 e^(\u2212weight)), so one\n *               strong reading is not yet the same as three\n *\n * A value is \"confirmed\" once two passes made it their top reading and it\n * holds two-thirds of the vote, and \"locked\" at three passes and four-fifths.\n * The camera screen draws candidates faintly, confirmed values solidly and\n * locked values with a tick; auto-capture waits for what the scan needs to be\n * at least confirmed.\n *\n * A reading the receipt's own arithmetic backs up in the same pass (subtotal\n * plus VAT equals it \u2014 arithmetic.ts) counts as one more hit: it is confirmed\n * after one pass instead of two, which is where most of a ticked-out total's\n * speed comes from. Locking still needs three hits and four-fifths of the vote.\n *\n * The final high-resolution pass votes with triple weight: it reads a sharper,\n * straightened picture with the provider's accurate mode. When it disagrees\n * with a value the live passes had locked, the disagreement is REPORTED rather\n * than silently resolved \u2014 the review asks a person to look at that field.\n */\nimport type { Box, FieldCandidate, FieldKey, FieldReading, FieldStatus } from \"./types.ts\";\n\ntype Tally = {\n  weight: number;\n  hits: number;\n  bestScore: number;\n  box: Box | null;\n  live: boolean;\n  final: boolean;\n  finalBox: Box | null;\n};\n\nexport type Conflict = { field: FieldKey; live: string; final: string };\n\nexport type VoteOptions = {\n  /** Share of a runner-up candidate's score that still counts as a vote. */\n  runnerUpWeight: number;\n  /** Weight of the final pass relative to a live one. */\n  finalWeight: number;\n  /** Readings below this confidence are not reported at all. */\n  minReportConfidence: number;\n};\n\nexport const DEFAULT_VOTES: VoteOptions = {\n  runnerUpWeight: 0.35,\n  finalWeight: 3,\n  minReportConfidence: 0.2,\n};\n\nexport class FieldVotes {\n  private options: VoteOptions;\n  private tallies = new Map<FieldKey, Map<string, Tally>>();\n  /** What the final pass itself read first, per field. */\n  private finalTop = new Map<FieldKey, string>();\n  private passes = 0;\n\n  constructor(options: VoteOptions = DEFAULT_VOTES) {\n    this.options = options;\n  }\n\n  reset(): void {\n    this.tallies.clear();\n    this.finalTop.clear();\n    this.passes = 0;\n  }\n\n  get passCount(): number {\n    return this.passes;\n  }\n\n  /** Cast one pass's candidates. Returns the fields whose top value changed. */\n  add(candidates: FieldCandidate[], source: \"live\" | \"final\" = \"live\"): FieldKey[] {\n    this.passes++;\n    const before = this.leaders();\n    const weight = source === \"final\" ? this.options.finalWeight : 1;\n\n    const byField = new Map<FieldKey, FieldCandidate[]>();\n    for (const c of candidates) {\n      const list = byField.get(c.field) ?? [];\n      list.push(c);\n      byField.set(c.field, list);\n    }\n    for (const [field, list] of byField) {\n      // One pass may read the same value twice (a total printed twice);\n      // it still casts one vote for it, at its best score.\n      const best = new Map<string, FieldCandidate>();\n      for (const c of list) {\n        const prev = best.get(c.value);\n        const corroborated = !!(prev?.corroborated || c.corroborated);\n        if (!prev || c.score > prev.score) best.set(c.value, { ...c, corroborated });\n        else if (corroborated) prev.corroborated = true;\n      }\n      const ranked = [...best.values()].sort((a, b) => b.score - a.score);\n      if (source === \"final\" && ranked.length) this.finalTop.set(field, ranked[0].value);\n      const tallies = this.tallies.get(field) ?? new Map<string, Tally>();\n      ranked.forEach((c, i) => {\n        const top = i === 0;\n        const t: Tally = tallies.get(c.value) ?? {\n          weight: 0,\n          hits: 0,\n          bestScore: 0,\n          box: null,\n          live: false,\n          final: false,\n          finalBox: null,\n        };\n        t.weight += c.score * weight * (top ? 1 : this.options.runnerUpWeight);\n        // A total the receipt's own sums back up is a second witness from the\n        // same pass (arithmetic.ts): confirmed a pass sooner, never locked\n        // sooner than three hits allow.\n        if (top) t.hits += (source === \"final\" ? 2 : 1) + (c.corroborated ? 1 : 0);\n        if (c.score >= t.bestScore || !t.box) {\n          t.bestScore = Math.max(t.bestScore, c.score);\n          if (c.box) t.box = c.box;\n        }\n        if (source === \"final\") {\n          t.final = true;\n          if (c.box) t.finalBox = c.box;\n        } else {\n          t.live = true;\n        }\n        tallies.set(c.value, t);\n      });\n      this.tallies.set(field, tallies);\n    }\n\n    const after = this.leaders();\n    const changed: FieldKey[] = [];\n    for (const [field, value] of after) if (before.get(field) !== value) changed.push(field);\n    return changed;\n  }\n\n  /** Current top value per field. */\n  private leaders(): Map<FieldKey, string> {\n    const out = new Map<FieldKey, string>();\n    for (const [field, tallies] of this.tallies) {\n      let best: [string, Tally] | null = null;\n      for (const entry of tallies) if (!best || entry[1].weight > best[1].weight) best = entry;\n      if (best) out.set(field, best[0]);\n    }\n    return out;\n  }\n\n  /**\n   * `boxes: \"final\"` returns only boxes read off the final picture: a live box\n   * is in camera-frame coordinates and would sit in the wrong place on the\n   * cropped, straightened photo the review shows.\n   */\n  reading(field: FieldKey, boxes: \"any\" | \"final\" = \"any\"): FieldReading | null {\n    const tallies = this.tallies.get(field);\n    if (!tallies || !tallies.size) return null;\n    let total = 0;\n    let best: [string, Tally] | null = null;\n    for (const entry of tallies) {\n      total += entry[1].weight;\n      if (!best || entry[1].weight > best[1].weight) best = entry;\n    }\n    if (!best || total <= 0) return null;\n    const [value, t] = best;\n    const agreement = t.weight / total;\n    const evidence = 1 - Math.exp(-t.weight / 0.9);\n    const confidence = Math.min(0.99, agreement * evidence);\n    if (confidence < this.options.minReportConfidence) return null;\n    let status: FieldStatus = \"candidate\";\n    if (t.hits >= 3 && agreement >= 0.8 && confidence >= 0.8) status = \"locked\";\n    else if (t.hits >= 2 && agreement >= 0.66) status = \"confirmed\";\n    return {\n      field,\n      value,\n      confidence,\n      status,\n      hits: t.hits,\n      box: boxes === \"final\" ? t.finalBox : t.finalBox ?? t.box,\n      source: t.live && t.final ? \"both\" : t.final ? \"final\" : \"live\",\n    };\n  }\n\n  readings(boxes: \"any\" | \"final\" = \"any\"): Partial<Record<FieldKey, FieldReading>> {\n    const out: Partial<Record<FieldKey, FieldReading>> = {};\n    for (const field of this.tallies.keys()) {\n      const r = this.reading(field, boxes);\n      if (r) out[field] = r;\n    }\n    return out;\n  }\n\n  /**\n   * Fields the final pass read differently from what the live passes had\n   * settled on. Call after `add(\u2026, \"final\")`.\n   */\n  conflicts(liveBefore: Partial<Record<FieldKey, FieldReading>>): Conflict[] {\n    const out: Conflict[] = [];\n    for (const [field, final] of this.finalTop) {\n      const live = liveBefore[field];\n      if (!live || live.status === \"candidate\") continue;\n      if (final !== live.value) out.push({ field, live: live.value, final });\n    }\n    return out;\n  }\n}\n", "// AUTO-GENERATED \u2014 DO NOT EDIT.\n// Source: shared/receiptvis-live/core/geometry.ts\n// Regenerate: node scripts/sync-receviz-web-sdk.mjs\n/**\n * Small geometry and grid helpers the rest of the engine leans on.\n *\n * Everything works in normalised upright coordinates (see types.ts) except\n * where a function says it takes grid cells.\n */\nimport type {\n  Box,\n  FrameSample,\n  Grid,\n  OcrResult,\n  Point,\n  Quad,\n  WireFrame,\n  WireOcr,\n} from \"./types.ts\";\n\n// \u2500\u2500 base64 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nconst B64 = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\nconst LOOKUP = (() => {\n  const table = new Int16Array(128).fill(-1);\n  for (let i = 0; i < B64.length; i++) table[B64.charCodeAt(i)] = i;\n  // URL-safe variants, so an adapter that picks either alphabet still decodes.\n  table[\"-\".charCodeAt(0)] = 62;\n  table[\"_\".charCodeAt(0)] = 63;\n  return table;\n})();\n\n/**\n * Decode base64 without `atob` or `Buffer`: Hermes has neither on every\n * version this code runs on, and Node tests must exercise the same path.\n * Whitespace and padding are skipped; anything else unknown ends the input.\n */\nexport function decodeBase64(input: string): Uint8Array {\n  const out = new Uint8Array(Math.floor((input.length * 3) / 4));\n  let buffer = 0;\n  let bits = 0;\n  let o = 0;\n  for (let i = 0; i < input.length; i++) {\n    const code = input.charCodeAt(i);\n    if (code === 61 /* = */ || code === 10 || code === 13 || code === 32) continue;\n    const value = code < 128 ? LOOKUP[code] : -1;\n    if (value < 0) break;\n    buffer = (buffer << 6) | value;\n    bits += 6;\n    if (bits >= 8) {\n      bits -= 8;\n      out[o++] = (buffer >> bits) & 0xff;\n    }\n  }\n  return out.subarray(0, o);\n}\n\nexport function encodeBase64(bytes: Uint8Array): string {\n  let out = \"\";\n  let i = 0;\n  for (; i + 2 < bytes.length; i += 3) {\n    const n = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];\n    out += B64[(n >> 18) & 63] + B64[(n >> 12) & 63] + B64[(n >> 6) & 63] + B64[n & 63];\n  }\n  const rest = bytes.length - i;\n  if (rest === 1) {\n    const n = bytes[i] << 16;\n    out += B64[(n >> 18) & 63] + B64[(n >> 12) & 63] + \"==\";\n  } else if (rest === 2) {\n    const n = (bytes[i] << 16) | (bytes[i + 1] << 8);\n    out += B64[(n >> 18) & 63] + B64[(n >> 12) & 63] + B64[(n >> 6) & 63] + \"=\";\n  }\n  return out;\n}\n\n/**\n * A grid from its wire form. A short payload is padded with zeros rather than\n * trusted: a half-sent frame should read as \"nothing here\", never index past\n * the end of its buffer.\n */\nexport function gridFromBase64(width: number, height: number, b64: string): Grid {\n  const w = Math.max(0, Math.floor(width));\n  const h = Math.max(0, Math.floor(height));\n  const bytes = decodeBase64(b64 || \"\");\n  if (bytes.length >= w * h) return { width: w, height: h, data: bytes.subarray(0, w * h) };\n  const data = new Uint8Array(w * h);\n  data.set(bytes);\n  return { width: w, height: h, data };\n}\n\nfunction quadFromNumbers(values: number[] | null | undefined): Quad | null {\n  if (!values || values.length !== 8 || values.some((v) => !Number.isFinite(v))) return null;\n  return [\n    { x: values[0], y: values[1] },\n    { x: values[2], y: values[3] },\n    { x: values[4], y: values[5] },\n    { x: values[6], y: values[7] },\n  ];\n}\n\nexport function quadToNumbers(quad: Quad): number[] {\n  return [quad[0].x, quad[0].y, quad[1].x, quad[1].y, quad[2].x, quad[2].y, quad[3].x, quad[3].y];\n}\n\n/** The adapter's event, as the engine wants it. */\nexport function frameSampleFromWire(wire: WireFrame): FrameSample {\n  return {\n    t: Number(wire.t) || 0,\n    frameWidth: Number(wire.frameWidth) || 0,\n    frameHeight: Number(wire.frameHeight) || 0,\n    luma: gridFromBase64(wire.gridWidth, wire.gridHeight, wire.luma),\n    detail: gridFromBase64(wire.detailWidth, wire.detailHeight, wire.detail),\n    nativeQuad: quadFromNumbers(wire.quad),\n    nativeQuadConfidence:\n      typeof wire.quadConfidence === \"number\" ? wire.quadConfidence : undefined,\n    processingMs: typeof wire.processingMs === \"number\" ? wire.processingMs : undefined,\n  };\n}\n\n/** An OCR answer, as the parser wants it. Empty lines are dropped here. */\nexport function ocrResultFromWire(wire: WireOcr): OcrResult {\n  const lines = (wire?.lines ?? [])\n    .filter((line) => typeof line?.text === \"string\" && line.text.trim().length > 0)\n    .map((line) => ({\n      text: line.text,\n      box: {\n        x: clamp01(Number(line.x) || 0),\n        y: clamp01(Number(line.y) || 0),\n        w: clamp01(Number(line.w) || 0),\n        h: clamp01(Number(line.h) || 0),\n      },\n      confidence: typeof line.confidence === \"number\" ? clamp01(line.confidence) : undefined,\n    }));\n  return {\n    lines,\n    width: Number(wire?.width) || 0,\n    height: Number(wire?.height) || 0,\n    ms: typeof wire?.ms === \"number\" ? wire.ms : undefined,\n  };\n}\n\n// \u2500\u2500 numbers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport function clamp(value: number, lo: number, hi: number): number {\n  return value < lo ? lo : value > hi ? hi : value;\n}\n\nexport function clamp01(value: number): number {\n  return clamp(value, 0, 1);\n}\n\n/** The p-th percentile (0..1) of a list; 0 for an empty one. Sorts a copy. */\nexport function percentile(values: ArrayLike<number>, p: number): number {\n  if (!values.length) return 0;\n  const sorted = Array.from(values).sort((a, b) => a - b);\n  const index = clamp(Math.round((sorted.length - 1) * p), 0, sorted.length - 1);\n  return sorted[index];\n}\n\n// \u2500\u2500 quads \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport function quadBounds(quad: Quad): Box {\n  const xs = quad.map((p) => p.x);\n  const ys = quad.map((p) => p.y);\n  const x = Math.min(...xs);\n  const y = Math.min(...ys);\n  return { x, y, w: Math.max(...xs) - x, h: Math.max(...ys) - y };\n}\n\n/** Shoelace area, in normalised units (1 = the whole frame). */\nexport function quadArea(quad: Quad): number {\n  let sum = 0;\n  for (let i = 0; i < 4; i++) {\n    const a = quad[i];\n    const b = quad[(i + 1) % 4];\n    sum += a.x * b.y - b.x * a.y;\n  }\n  return Math.abs(sum) / 2;\n}\n\nexport function quadCentroid(quad: Quad): Point {\n  return {\n    x: (quad[0].x + quad[1].x + quad[2].x + quad[3].x) / 4,\n    y: (quad[0].y + quad[1].y + quad[2].y + quad[3].y) / 4,\n  };\n}\n\nfunction cross(o: Point, a: Point, b: Point): number {\n  return (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);\n}\n\n/** A quad the rest of the engine can trust: convex and not folded over. */\nexport function isConvex(quad: Quad): boolean {\n  let sign = 0;\n  for (let i = 0; i < 4; i++) {\n    const c = cross(quad[i], quad[(i + 1) % 4], quad[(i + 2) % 4]);\n    if (Math.abs(c) < 1e-9) return false;\n    const s = c > 0 ? 1 : -1;\n    if (sign === 0) sign = s;\n    else if (s !== sign) return false;\n  }\n  return true;\n}\n\n/** Inside a convex quad (either winding). */\nexport function pointInQuad(p: Point, quad: Quad): boolean {\n  let sign = 0;\n  for (let i = 0; i < 4; i++) {\n    const c = cross(quad[i], quad[(i + 1) % 4], p);\n    if (c === 0) continue;\n    const s = c > 0 ? 1 : -1;\n    if (sign === 0) sign = s;\n    else if (s !== sign) return false;\n  }\n  return true;\n}\n\n/** Mean distance the four corners moved, in normalised units. */\nexport function cornerMotion(a: Quad, b: Quad): number {\n  let sum = 0;\n  for (let i = 0; i < 4; i++) sum += Math.hypot(a[i].x - b[i].x, a[i].y - b[i].y);\n  return sum / 4;\n}\n\n/** Corner-wise blend: `weight` of `next`, the rest of `prev`. */\nexport function blendQuads(prev: Quad, next: Quad, weight: number): Quad {\n  const k = clamp01(weight);\n  return prev.map((p, i) => ({\n    x: p.x + (next[i].x - p.x) * k,\n    y: p.y + (next[i].y - p.y) * k,\n  })) as Quad;\n}\n\n/** Grow a quad about its centroid; the final crop keeps a little margin. */\nexport function expandQuad(quad: Quad, factor: number): Quad {\n  const c = quadCentroid(quad);\n  return quad.map((p) => ({\n    x: clamp01(c.x + (p.x - c.x) * factor),\n    y: clamp01(c.y + (p.y - c.y) * factor),\n  })) as Quad;\n}\n\n/**\n * Calls `visit` with each cell of `grid` whose centre lies inside `quad`.\n * Falls back to the quad's bounds when it is too thin to contain a centre.\n */\nexport function forEachCellInQuad(\n  grid: Grid,\n  quad: Quad,\n  visit: (value: number, gx: number, gy: number) => void\n): number {\n  const { width, height, data } = grid;\n  if (!width || !height) return 0;\n  const b = quadBounds(quad);\n  const x0 = clamp(Math.floor(b.x * width), 0, width - 1);\n  const x1 = clamp(Math.ceil((b.x + b.w) * width), 0, width);\n  const y0 = clamp(Math.floor(b.y * height), 0, height - 1);\n  const y1 = clamp(Math.ceil((b.y + b.h) * height), 0, height);\n  let visited = 0;\n  for (let gy = y0; gy < y1; gy++) {\n    for (let gx = x0; gx < x1; gx++) {\n      const centre = { x: (gx + 0.5) / width, y: (gy + 0.5) / height };\n      if (!pointInQuad(centre, quad)) continue;\n      visit(data[gy * width + gx], gx, gy);\n      visited++;\n    }\n  }\n  if (visited === 0) {\n    for (let gy = y0; gy < Math.max(y0 + 1, y1); gy++) {\n      for (let gx = x0; gx < Math.max(x0 + 1, x1); gx++) {\n        visit(data[gy * width + gx], gx, gy);\n        visited++;\n      }\n    }\n  }\n  return visited;\n}\n\n// \u2500\u2500 scene fingerprint \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * A 64-bit difference hash of the frame (9x8 block means, left < right), as\n * two unsigned 32-bit halves. Two frames of the same still receipt differ by a\n * few bits of sensor noise; a moved phone or a different receipt by dozens.\n * This is what stops the engine reading essentially the same frame again.\n */\nexport type Fingerprint = [number, number];\n\nexport function fingerprint(grid: Grid): Fingerprint {\n  const { width, height, data } = grid;\n  const cols = 9;\n  const rows = 8;\n  const means = new Float64Array(cols * rows);\n  if (width && height) {\n    for (let r = 0; r < rows; r++) {\n      const y0 = Math.floor((r * height) / rows);\n      const y1 = Math.max(y0 + 1, Math.floor(((r + 1) * height) / rows));\n      for (let c = 0; c < cols; c++) {\n        const x0 = Math.floor((c * width) / cols);\n        const x1 = Math.max(x0 + 1, Math.floor(((c + 1) * width) / cols));\n        let sum = 0;\n        let n = 0;\n        for (let y = y0; y < y1 && y < height; y++) {\n          for (let x = x0; x < x1 && x < width; x++) {\n            sum += data[y * width + x];\n            n++;\n          }\n        }\n        means[r * cols + c] = n ? sum / n : 0;\n      }\n    }\n  }\n  let hi = 0;\n  let lo = 0;\n  let bit = 0;\n  for (let r = 0; r < rows; r++) {\n    for (let c = 0; c < cols - 1; c++) {\n      // A margin of two luma levels: on a flat table two neighbouring blocks\n      // are equal up to sensor noise, and a strict comparison would flip on\n      // every frame. With the margin they read 0 in every frame.\n      const on = means[r * cols + c] + 2 < means[r * cols + c + 1] ? 1 : 0;\n      if (bit < 32) hi = (hi | (on << (31 - bit))) >>> 0;\n      else lo = (lo | (on << (63 - bit))) >>> 0;\n      bit++;\n    }\n  }\n  return [hi >>> 0, lo >>> 0];\n}\n\nfunction popcount(n: number): number {\n  let v = n >>> 0;\n  v = v - ((v >>> 1) & 0x55555555);\n  v = (v & 0x33333333) + ((v >>> 2) & 0x33333333);\n  return (((v + (v >>> 4)) & 0x0f0f0f0f) * 0x01010101) >>> 24;\n}\n\nexport function hamming(a: Fingerprint, b: Fingerprint): number {\n  return popcount(a[0] ^ b[0]) + popcount(a[1] ^ b[1]);\n}\n", "// AUTO-GENERATED \u2014 DO NOT EDIT.\n// Source: shared/receiptvis-live/core/controller.ts\n// Regenerate: node scripts/sync-receviz-web-sdk.mjs\n/**\n * When to read, and when to take the picture.\n *\n * The controller is a small state machine over the frames the adapter reports:\n *\n *   searching  no receipt in view\n *   aligning   a receipt, but something is in the way (too far, dark, glare\u2026)\n *   steadying  a good receipt that has not stopped moving yet\n *   reading    good and still: OCR passes run and fields accumulate\n *   capturing  the final photograph has been asked for; frames are ignored\n *   captured   done \u2014 the scan has its picture\n *\n * Three disciplines keep it from being greedy:\n *\n * * **OCR is rationed.** A pass needs a readable, still frame; at most one is in\n *   flight; passes are spaced (and spaced further once the scan has what it\n *   needs); and a scene that has not changed is read at most twice, so a phone\n *   resting over a receipt does not burn battery re-reading one image.\n * * **The photograph is taken at a peak.** Capture waits for a capturable,\n *   still frame whose quality is close to the best seen in the last few\n *   seconds, and for either the fields the scan needs or a reading budget to\n *   run out \u2014 a slip the live OCR cannot read still gets its final pass.\n * * **It fires once.** A cooldown follows every attempt, failures are counted,\n *   and after a few the controller stops trying and asks for the shutter.\n */\nimport { hamming, type Fingerprint } from \"./geometry.ts\";\nimport type {\n  ControllerPhase,\n  Detection,\n  FieldKey,\n  FieldReading,\n  QualityReport,\n} from \"./types.ts\";\n\nexport type ControllerOptions = {\n  /**\n   * What \"read enough\" means, as groups: every group needs one of its fields\n   * confirmed. [[\"amount\"], [\"date\"]] needs both; [[\"receiptNumber\", \"rrn\"]]\n   * needs either.\n   */\n  required: FieldKey[][];\n  /** Stillness before an OCR pass, ms. */\n  stableForReadMs: number;\n  /** Stillness before the photograph, ms. */\n  stableForCaptureMs: number;\n  /** Spacing between OCR passes while fields are still missing, ms. */\n  ocrIntervalMs: number;\n  /** Spacing once every required field is confirmed, ms. */\n  ocrIntervalSettledMs: number;\n  /** Reads of one unchanged scene. */\n  maxSameSceneReads: number;\n  /** Fingerprint bits that make it a different scene. */\n  sceneChangeBits: number;\n  /** Total OCR passes allowed in one session (battery ceiling). */\n  maxOcrPasses: number;\n  /** Capture anyway after reading this long with a capturable frame, ms. */\n  maxReadMs: number;\n  /** Capture only at this share of the best quality seen recently. */\n  nearBestRatio: number;\n  /** How far back \"recently\" reaches, ms. */\n  bestWindowMs: number;\n  /** Quiet time after any capture attempt, ms. */\n  cooldownMs: number;\n  /** Automatic attempts before handing over to the shutter. */\n  maxAutoAttempts: number;\n  /** Nothing is captured this soon after the camera opens, ms. */\n  armDelayMs: number;\n  /** A receipt out of view this long is a new scan when one reappears, ms. */\n  lostResetMs: number;\n  /** Turn automatic capture off entirely (manual shutter only). */\n  autoCapture: boolean;\n};\n\n/**\n * Tuned for speed without lowering the bar (2026-09-26, \"slower than Google's\n * scanner to start reading and to capture\"). What makes a value believed is\n * unchanged \u2014 two passes agreeing, two-thirds of the vote (confidence.ts) \u2014\n * only the waiting between them is shorter:\n *\n *   first read      after 150 ms of stillness, not 250\n *   next reads      every 400 ms, not 650: confirmation arrives a pass sooner\n *   the photograph  after 300 ms of stillness, not 450, and never in the first\n *                   400 ms (was 700)\n *   reading budget  1.8 s, not 2.6: a receipt the live frames cannot read (a\n *                   long one, held far off) is captured sooner and read from\n *                   the full-resolution photograph, which is where its small\n *                   print is legible anyway\n */\nexport const DEFAULT_CONTROLLER: ControllerOptions = {\n  required: [[\"amount\"]],\n  stableForReadMs: 150,\n  stableForCaptureMs: 300,\n  ocrIntervalMs: 400,\n  ocrIntervalSettledMs: 1200,\n  maxSameSceneReads: 2,\n  sceneChangeBits: 6,\n  maxOcrPasses: 45,\n  maxReadMs: 1800,\n  nearBestRatio: 0.85,\n  bestWindowMs: 2000,\n  cooldownMs: 1200,\n  maxAutoAttempts: 3,\n  armDelayMs: 400,\n  lostResetMs: 2000,\n  autoCapture: true,\n};\n\nexport type ControllerInput = {\n  t: number;\n  detection: Detection;\n  quality: QualityReport;\n  stableMs: number;\n  print: Fingerprint;\n  fields: Partial<Record<FieldKey, FieldReading>>;\n};\n\nexport type ControllerDecision = {\n  phase: ControllerPhase;\n  readText: boolean;\n  capture: boolean;\n  /** The receipt was out of view long enough that what was read is stale. */\n  resetFields: boolean;\n};\n\n/** How much of what the scan needs has been read, 0..1. */\nexport function requirementProgress(\n  required: FieldKey[][],\n  fields: Partial<Record<FieldKey, FieldReading>>\n): { progress: number; satisfied: boolean } {\n  if (!required.length) return { progress: 1, satisfied: true };\n  let sum = 0;\n  let satisfied = true;\n  for (const group of required) {\n    let best = 0;\n    for (const key of group) {\n      const reading = fields[key];\n      if (!reading) continue;\n      const credit = reading.status === \"candidate\" ? 0.4 : 1;\n      best = Math.max(best, credit);\n    }\n    if (best < 1) satisfied = false;\n    sum += best;\n  }\n  return { progress: sum / required.length, satisfied };\n}\n\nexport class CaptureController {\n  private options: ControllerOptions;\n  private phase: ControllerPhase = \"searching\";\n  private openedAt: number | null = null;\n  private lostSince: number | null = null;\n  private readingSince: number | null = null;\n  private lastOcrAt = -Infinity;\n  private lastOcrPrint: Fingerprint | null = null;\n  private sameSceneReads = 0;\n  private ocrInFlight = false;\n  private ocrPasses = 0;\n  private lastAttemptAt = -Infinity;\n  private failedAttempts = 0;\n  private recentScores: Array<{ t: number; score: number }> = [];\n  private hadFields = false;\n\n  constructor(options: ControllerOptions = DEFAULT_CONTROLLER) {\n    this.options = options;\n  }\n\n  get currentPhase(): ControllerPhase {\n    return this.phase;\n  }\n\n  get passes(): number {\n    return this.ocrPasses;\n  }\n\n  /** Auto-capture has given up; only the shutter will take the picture now. */\n  get autoPaused(): boolean {\n    return !this.options.autoCapture || this.failedAttempts >= this.options.maxAutoAttempts;\n  }\n\n  reset(): void {\n    this.phase = \"searching\";\n    this.openedAt = null;\n    this.lostSince = null;\n    this.readingSince = null;\n    this.lastOcrAt = -Infinity;\n    this.lastOcrPrint = null;\n    this.sameSceneReads = 0;\n    this.ocrInFlight = false;\n    this.ocrPasses = 0;\n    this.lastAttemptAt = -Infinity;\n    this.failedAttempts = 0;\n    this.recentScores = [];\n    this.hadFields = false;\n  }\n\n  onFrame(input: ControllerInput): ControllerDecision {\n    const o = this.options;\n    const { t, detection, quality, stableMs, print, fields } = input;\n    if (this.openedAt === null) this.openedAt = t;\n    const idle: ControllerDecision = { phase: this.phase, readText: false, capture: false, resetFields: false };\n    if (this.phase === \"captured\" || this.phase === \"capturing\") return idle;\n\n    this.hadFields = this.hadFields || Object.keys(fields).length > 0;\n\n    if (!detection.found) {\n      if (this.lostSince === null) this.lostSince = t;\n      this.phase = \"searching\";\n      this.readingSince = null;\n      const resetFields = this.hadFields && t - this.lostSince >= o.lostResetMs;\n      if (resetFields) {\n        // A new receipt is a new scan: forget the old scene entirely.\n        this.hadFields = false;\n        this.lastOcrPrint = null;\n        this.sameSceneReads = 0;\n        this.recentScores = [];\n      }\n      return { phase: this.phase, readText: false, capture: false, resetFields };\n    }\n    this.lostSince = null;\n\n    this.recentScores.push({ t, score: quality.score });\n    while (this.recentScores.length && t - this.recentScores[0].t > o.bestWindowMs) {\n      this.recentScores.shift();\n    }\n\n    if (!quality.capturable) {\n      this.phase = \"aligning\";\n      this.readingSince = null;\n    } else if (stableMs < o.stableForReadMs) {\n      this.phase = \"steadying\";\n      this.readingSince = null;\n    } else {\n      this.phase = \"reading\";\n      if (this.readingSince === null) this.readingSince = t;\n    }\n\n    const { satisfied } = requirementProgress(o.required, fields);\n\n    // \u2500\u2500 capture \u2500\u2500\n    let capture = false;\n    if (\n      !this.autoPaused &&\n      this.phase === \"reading\" &&\n      t - (this.openedAt ?? t) >= o.armDelayMs &&\n      stableMs >= o.stableForCaptureMs &&\n      t - this.lastAttemptAt >= o.cooldownMs &&\n      (satisfied || (this.readingSince !== null && t - this.readingSince >= o.maxReadMs))\n    ) {\n      const best = Math.max(...this.recentScores.map((s) => s.score));\n      if (quality.score >= best * o.nearBestRatio) {\n        capture = true;\n        this.phase = \"capturing\";\n        this.lastAttemptAt = t;\n      }\n    }\n\n    // \u2500\u2500 OCR \u2500\u2500\n    let readText = false;\n    const interval = satisfied ? o.ocrIntervalSettledMs : o.ocrIntervalMs;\n    if (\n      !capture &&\n      quality.readable &&\n      stableMs >= o.stableForReadMs &&\n      !this.ocrInFlight &&\n      this.ocrPasses < o.maxOcrPasses &&\n      t - this.lastOcrAt >= interval\n    ) {\n      const newScene =\n        !this.lastOcrPrint || hamming(this.lastOcrPrint, print) >= o.sceneChangeBits;\n      if (newScene || this.sameSceneReads < o.maxSameSceneReads) {\n        readText = true;\n        this.sameSceneReads = newScene ? 1 : this.sameSceneReads + 1;\n        this.lastOcrPrint = print;\n        this.lastOcrAt = t;\n        this.ocrInFlight = true;\n        this.ocrPasses++;\n      }\n    }\n\n    return { phase: this.phase, readText, capture, resetFields: false };\n  }\n\n  /** The adapter finished (or failed) an OCR pass. */\n  ocrFinished(): void {\n    this.ocrInFlight = false;\n  }\n\n  /** The shutter was pressed. Returns false when a capture is already under way. */\n  manualCapture(t: number): boolean {\n    if (this.phase === \"capturing\" || this.phase === \"captured\") return false;\n    this.phase = \"capturing\";\n    this.lastAttemptAt = t;\n    return true;\n  }\n\n  /** The photograph was taken (ok) or could not be (not ok). */\n  captureFinished(ok: boolean, t: number, manual = false): void {\n    if (ok) {\n      this.phase = \"captured\";\n      return;\n    }\n    if (!manual) this.failedAttempts++;\n    this.lastAttemptAt = t;\n    this.phase = \"aligning\";\n    this.readingSince = null;\n  }\n\n  /** Back to live scanning after a capture the person rejected (Rescan). */\n  resume(): void {\n    if (this.phase === \"captured\" || this.phase === \"capturing\") this.phase = \"searching\";\n    this.readingSince = null;\n    this.ocrInFlight = false;\n  }\n}\n", "// AUTO-GENERATED \u2014 DO NOT EDIT.\n// Source: shared/receiptvis-live/core/detector.ts\n// Regenerate: node scripts/sync-receviz-web-sdk.mjs\n/**\n * Is there a receipt in this frame, and where are its four corners?\n *\n * Two sources, one answer. A platform that has a document detector of its own\n * (Apple Vision) sends its outline with the frame, and a confident one is used\n * as it stands. Everywhere else \u2014 and whenever the native outline is missing\n * or unsure \u2014 this file finds the paper in the ~96-cell luma grid itself.\n *\n * The heuristic is the one the main app's live scanner proved out\n * (mobile/src/components/receiptvis/receiptDetectCore.ts), grown from a box to\n * a quad: a receipt reads as a large BRIGHT region that stands out from its\n * surroundings and carries dark print spread down its height. The box finds\n * where the paper is; extreme projections find its corners; a line fitted to\n * each edge refines them, and says how it is turned and how far the phone is\n * tilted over it.\n *\n * Deliberately permissive. A false \"found\" costs one OCR pass that reads\n * nothing; a false \"not found\" costs the person holding the phone time.\n */\nimport {\n  clamp01,\n  isConvex,\n  quadArea,\n  quadBounds,\n} from \"./geometry.ts\";\nimport type { Detection, Grid, Point, Quad } from \"./types.ts\";\n\nexport type DetectorOptions = {\n  /** p95 - p20 luminance below which the scene is too flat to hold paper. */\n  minDynamicRange: number;\n  /** Smallest share of the frame the outline may cover. */\n  minArea: number;\n  /** Confidence at which the luma detector calls it found. */\n  minConfidence: number;\n  /** Confidence at which a native outline is used as it stands. */\n  nativeMinConfidence: number;\n};\n\nexport const DEFAULT_DETECTOR_OPTIONS: DetectorOptions = {\n  minDynamicRange: 38,\n  minArea: 0.05,\n  minConfidence: 0.45,\n  nativeMinConfidence: 0.5,\n};\n\n/** An edge this close to the frame border (normalised) counts as touching it. */\nconst EDGE_TOUCH = 0.02;\n\nexport const NOTHING: Detection = {\n  found: false,\n  quad: null,\n  bounds: null,\n  confidence: 0,\n  source: \"none\",\n  touches: { top: false, right: false, bottom: false, left: false },\n  angleDeg: 0,\n  keystone: 0,\n};\n\n/** Detection from whichever source is trustworthy for this frame. */\nexport function detect(\n  luma: Grid,\n  nativeQuad: Quad | null | undefined,\n  nativeConfidence: number | undefined,\n  options: DetectorOptions = DEFAULT_DETECTOR_OPTIONS\n): Detection {\n  if (nativeQuad && (nativeConfidence ?? 0) >= options.nativeMinConfidence) {\n    const described = describeQuad(nativeQuad, luma.width / Math.max(1, luma.height));\n    if (described && quadArea(nativeQuad) >= options.minArea) {\n      return { ...described, found: true, source: \"native\", confidence: nativeConfidence ?? 0.5 };\n    }\n  }\n  return detectInLuma(luma, options);\n}\n\n/**\n * Geometry of an outline: which borders it runs off, how it is turned and how\n * far from rectangular it is. `aspect` is the frame's width / height, needed\n * because normalised x and y are different lengths on a tall frame.\n */\nexport function describeQuad(\n  quad: Quad,\n  aspect: number\n): Omit<Detection, \"found\" | \"source\" | \"confidence\"> | null {\n  if (!isConvex(quad)) return null;\n  const [tl, tr, br, bl] = quad;\n  const px = (p: Point) => ({ x: p.x * aspect, y: p.y });\n  const len = (a: Point, b: Point) => {\n    const pa = px(a);\n    const pb = px(b);\n    return Math.hypot(pa.x - pb.x, pa.y - pb.y);\n  };\n  const touches = {\n    top: tl.y <= EDGE_TOUCH || tr.y <= EDGE_TOUCH,\n    bottom: bl.y >= 1 - EDGE_TOUCH || br.y >= 1 - EDGE_TOUCH,\n    left: tl.x <= EDGE_TOUCH || bl.x <= EDGE_TOUCH,\n    right: tr.x >= 1 - EDGE_TOUCH || br.x >= 1 - EDGE_TOUCH,\n  };\n\n  // Angle: average of the side edges' lean from vertical and the top/bottom\n  // edges' lean from horizontal, using only edges that are the paper's own\n  // (an edge lying on the frame border says nothing about the paper).\n  const angles: number[] = [];\n  const sideAngle = (top: Point, bottom: Point) => {\n    const a = px(top);\n    const b = px(bottom);\n    // Clockwise paper: the top corner sits right of the bottom one.\n    return (Math.atan2(a.x - b.x, b.y - a.y) * 180) / Math.PI;\n  };\n  const flatAngle = (left: Point, right: Point) => {\n    const a = px(left);\n    const b = px(right);\n    return (Math.atan2(b.y - a.y, b.x - a.x) * 180) / Math.PI;\n  };\n  if (!touches.left) angles.push(sideAngle(tl, bl));\n  if (!touches.right) angles.push(sideAngle(tr, br));\n  if (!touches.top) angles.push(flatAngle(tl, tr));\n  if (!touches.bottom) angles.push(flatAngle(bl, br));\n  const angleDeg = angles.length ? angles.reduce((s, v) => s + v, 0) / angles.length : 0;\n\n  // Keystone: opposite edges of a flat-on rectangle are equal. The far edge\n  // of a tilted shot is shorter; the ratio says how far.\n  const ratios: number[] = [];\n  if (!touches.top && !touches.bottom) {\n    const top = len(tl, tr);\n    const bottom = len(bl, br);\n    if (top > 0 && bottom > 0) ratios.push(1 - Math.min(top, bottom) / Math.max(top, bottom));\n  }\n  if (!touches.left && !touches.right) {\n    const left = len(tl, bl);\n    const right = len(tr, br);\n    if (left > 0 && right > 0) ratios.push(1 - Math.min(left, right) / Math.max(left, right));\n  }\n  const keystone = ratios.length ? Math.max(...ratios) : 0;\n\n  return { quad, bounds: quadBounds(quad), touches, angleDeg, keystone };\n}\n\n// \u2500\u2500 the luma heuristic \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Largest run of indexes whose fraction clears the threshold, bridging small\n * gaps: dense print interrupts the paper's bright profile, and strict\n * contiguity would shatter one receipt into slivers.\n */\nfunction largestRun(fracs: Float32Array, threshold: number): [number, number] | null {\n  const maxGap = Math.round(fracs.length * 0.1) + 2;\n  const runs: [number, number][] = [];\n  let start = -1;\n  for (let i = 0; i <= fracs.length; i++) {\n    const on = i < fracs.length && fracs[i] >= threshold;\n    if (on && start < 0) start = i;\n    if (!on && start >= 0) {\n      runs.push([start, i]);\n      start = -1;\n    }\n  }\n  if (!runs.length) return null;\n  const merged: [number, number][] = [[runs[0][0], runs[0][1]]];\n  for (let i = 1; i < runs.length; i++) {\n    const last = merged[merged.length - 1];\n    if (runs[i][0] - last[1] <= maxGap) last[1] = runs[i][1];\n    else merged.push([runs[i][0], runs[i][1]]);\n  }\n  let best = merged[0];\n  for (const r of merged) if (r[1] - r[0] > best[1] - best[0]) best = r;\n  return best;\n}\n\ntype Line = { slope: number; intercept: number; residual: number; points: number };\n\n/**\n * Least squares for `v = slope * u + intercept`, refitted once without the\n * worst fifth of the points \u2014 a smudge or a finger on the edge of the paper\n * should not bend the whole edge.\n */\nfunction fitLine(us: number[], vs: number[]): Line | null {\n  const fit = (idx: number[]) => {\n    const n = idx.length;\n    if (n < 3) return null;\n    let su = 0;\n    let sv = 0;\n    let suu = 0;\n    let suv = 0;\n    for (const i of idx) {\n      su += us[i];\n      sv += vs[i];\n      suu += us[i] * us[i];\n      suv += us[i] * vs[i];\n    }\n    const denom = n * suu - su * su;\n    const slope = Math.abs(denom) < 1e-9 ? 0 : (n * suv - su * sv) / denom;\n    const intercept = (sv - slope * su) / n;\n    return { slope, intercept };\n  };\n  const all = us.map((_, i) => i);\n  const first = fit(all);\n  if (!first) return null;\n  const residuals = all.map((i) => Math.abs(vs[i] - (first.slope * us[i] + first.intercept)));\n  const cutoff = [...residuals].sort((a, b) => a - b)[Math.floor(residuals.length * 0.8)] ?? 0;\n  const kept = all.filter((i) => residuals[i] <= Math.max(cutoff, 1));\n  const second = fit(kept.length >= 3 ? kept : all) ?? first;\n  let residual = 0;\n  for (const i of kept) residual += Math.abs(vs[i] - (second.slope * us[i] + second.intercept));\n  return { ...second, residual: kept.length ? residual / kept.length : 0, points: kept.length };\n}\n\n/** Where `x = a*y + b` (a side edge) crosses `y = c*x + d` (a top/bottom edge). */\nfunction intersect(side: Line, flat: Line): Point {\n  const a = side.slope;\n  const b = side.intercept;\n  const c = flat.slope;\n  const d = flat.intercept;\n  const denom = 1 - a * c;\n  const x = Math.abs(denom) < 1e-9 ? b : (a * d + b) / denom;\n  return { x, y: c * x + d };\n}\n\nexport function detectInLuma(\n  luma: Grid,\n  options: DetectorOptions = DEFAULT_DETECTOR_OPTIONS\n): Detection {\n  const { width: w, height: h, data } = luma;\n  if (w < 8 || h < 8 || data.length < w * h) return NOTHING;\n\n  const hist = new Uint32Array(256);\n  for (let i = 0; i < w * h; i++) hist[data[i]]++;\n  let acc = 0;\n  let p20 = -1;\n  let p95 = 255;\n  for (let v = 0; v < 256; v++) {\n    acc += hist[v];\n    if (p20 < 0 && acc >= w * h * 0.2) p20 = v;\n    if (acc >= w * h * 0.95) {\n      p95 = v;\n      break;\n    }\n  }\n  // A receipt scene is bimodal (paper against a darker surface); a wall, a\n  // table or a face has almost no spread.\n  if (p95 - Math.max(0, p20) < options.minDynamicRange) return NOTHING;\n\n  // Paper is \"bright relative to this frame\", so dim light still finds it;\n  // too_dark is the quality check's call, with its own guidance.\n  const brightCut = Math.max(70, Math.round(p95 * 0.8));\n  const darkCut = Math.round(brightCut * 0.75);\n\n  const colFrac = new Float32Array(w);\n  const rowFrac = new Float32Array(h);\n  for (let y = 0; y < h; y++) {\n    for (let x = 0; x < w; x++) {\n      if (data[y * w + x] >= brightCut) {\n        colFrac[x] += 1 / h;\n        rowFrac[y] += 1 / w;\n      }\n    }\n  }\n  const colRun = largestRun(colFrac, 0.22);\n  const rowRun = largestRun(rowFrac, 0.18);\n  if (!colRun || !rowRun) return NOTHING;\n  const [bx0, bx1] = colRun;\n  const [by0, by1] = rowRun;\n  const bw = bx1 - bx0;\n  const bh = by1 - by0;\n  if ((bw * bh) / (w * h) < options.minArea) return NOTHING;\n\n  const bright = (x: number, y: number) =>\n    x >= 0 && y >= 0 && x < w && y < h && data[y * w + x] >= brightCut;\n  // A 2x2 all-bright block: a speck of glare or a stray bright pixel is not\n  // paper, and must not become a corner.\n  const solid = (x: number, y: number) =>\n    bright(x, y) && bright(x + 1, y) && bright(x, y + 1) && bright(x + 1, y + 1);\n\n  const margin = 2;\n  const sx0 = Math.max(0, bx0 - margin);\n  const sx1 = Math.min(w, bx1 + margin);\n  const sy0 = Math.max(0, by0 - margin);\n  const sy1 = Math.min(h, by1 + margin);\n\n  // Corners first, from extreme projections: the top-left corner is the paper\n  // point with the smallest x + y, the top-right the largest x - y, and so on.\n  // Exact for any rectangle turned less than 45 degrees \u2014 which a receipt held\n  // for scanning always is \u2014 and immune to how dense the print is.\n  let tl: Point | null = null;\n  let tr: Point | null = null;\n  let br: Point | null = null;\n  let bl: Point | null = null;\n  let minSum = Infinity;\n  let maxSum = -Infinity;\n  let maxDiff = -Infinity;\n  let minDiff = Infinity;\n  for (let y = sy0; y < sy1; y++) {\n    for (let x = sx0; x < sx1; x++) {\n      if (!solid(x, y)) continue;\n      const sum = x + y;\n      const diff = x - y;\n      if (sum < minSum) {\n        minSum = sum;\n        tl = { x, y };\n      }\n      if (sum + 4 > maxSum) {\n        maxSum = sum + 4;\n        br = { x: x + 2, y: y + 2 };\n      }\n      if (diff + 2 > maxDiff) {\n        maxDiff = diff + 2;\n        tr = { x: x + 2, y };\n      }\n      if (diff - 2 < minDiff) {\n        minDiff = diff - 2;\n        bl = { x, y: y + 2 };\n      }\n    }\n  }\n  if (!tl || !tr || !br || !bl) return NOTHING;\n  const rough: Point[] = [tl, tr, br, bl];\n\n  // Then each edge, refined by a line through samples taken only along that\n  // edge's own middle stretch \u2014 so the top edge's samples never wander onto a\n  // side edge of a turned receipt. Where a fit fails, the rough corner stands.\n  const between = (a: number, b: number, k: number) => a + (b - a) * k;\n  const topX: number[] = [];\n  const topY: number[] = [];\n  const bottomX: number[] = [];\n  const bottomY: number[] = [];\n  const leftY: number[] = [];\n  const leftX: number[] = [];\n  const rightY: number[] = [];\n  const rightX: number[] = [];\n  for (let x = Math.ceil(between(tl.x, tr.x, 0.15)); x <= Math.floor(between(tl.x, tr.x, 0.85)); x++) {\n    for (let y = Math.max(0, Math.min(tl.y, tr.y) - margin); y < sy1 - 1; y++) {\n      if (bright(x, y) && bright(x, y + 1)) {\n        topX.push(x + 0.5);\n        topY.push(y);\n        break;\n      }\n    }\n  }\n  for (let x = Math.ceil(between(bl.x, br.x, 0.15)); x <= Math.floor(between(bl.x, br.x, 0.85)); x++) {\n    for (let y = Math.min(h - 1, Math.max(bl.y, br.y) + margin); y > sy0; y--) {\n      if (bright(x, y) && bright(x, y - 1)) {\n        bottomX.push(x + 0.5);\n        bottomY.push(y + 1);\n        break;\n      }\n    }\n  }\n  for (let y = Math.ceil(between(tl.y, bl.y, 0.15)); y <= Math.floor(between(tl.y, bl.y, 0.85)); y++) {\n    for (let x = Math.max(0, Math.min(tl.x, bl.x) - margin); x < sx1 - 1; x++) {\n      if (bright(x, y) && bright(x + 1, y)) {\n        leftY.push(y + 0.5);\n        leftX.push(x);\n        break;\n      }\n    }\n  }\n  for (let y = Math.ceil(between(tr.y, br.y, 0.15)); y <= Math.floor(between(tr.y, br.y, 0.85)); y++) {\n    for (let x = Math.min(w - 1, Math.max(tr.x, br.x) + margin); x > sx0; x--) {\n      if (bright(x, y) && bright(x - 1, y)) {\n        rightY.push(y + 0.5);\n        rightX.push(x + 1);\n        break;\n      }\n    }\n  }\n\n  const left = fitLine(leftY, leftX);\n  const right = fitLine(rightY, rightX);\n  const top = fitLine(topX, topY);\n  const bottom = fitLine(bottomX, bottomY);\n\n  const size = Math.max(Math.hypot(tr.x - tl.x, tr.y - tl.y), Math.hypot(bl.x - tl.x, bl.y - tl.y));\n  const refine = (rough: Point, side: Line | null, flat: Line | null): Point => {\n    if (!side || !flat) return rough;\n    const p = intersect(side, flat);\n    // A refined corner far from the rough one means a fit caught something\n    // that is not the paper's edge; the rough corner is the safer answer.\n    return Math.hypot(p.x - rough.x, p.y - rough.y) <= Math.max(3, size * 0.12) ? p : rough;\n  };\n  const corners = [\n    refine(tl, left, top),\n    refine(tr, right, top),\n    refine(br, right, bottom),\n    refine(bl, left, bottom),\n  ];\n  const toQuad = (pts: Point[]): Quad =>\n    pts.map((p) => ({ x: clamp01(p.x / w), y: clamp01(p.y / h) })) as Quad;\n  let quad = toQuad(corners);\n  if (!isConvex(quad)) quad = toQuad(rough);\n  if (!isConvex(quad)) return NOTHING;\n  const area = quadArea(quad);\n  if (area < options.minArea) return NOTHING;\n\n  // What is inside the outline: paper, print, and how the print is spread.\n  let inside = 0;\n  let brightIn = 0;\n  let darkIn = 0;\n  let sumIn = 0;\n  let textRows = 0;\n  let rowsSeen = 0;\n  const minX = Math.floor(Math.min(quad[0].x, quad[3].x) * w);\n  const maxX = Math.ceil(Math.max(quad[1].x, quad[2].x) * w);\n  const minY = Math.floor(Math.min(quad[0].y, quad[1].y) * h);\n  const maxY = Math.ceil(Math.max(quad[2].y, quad[3].y) * h);\n  for (let y = Math.max(0, minY); y < Math.min(h, maxY); y++) {\n    // Row extent inside the quad: interpolate the side edges at this row.\n    const fy = (y + 0.5) / h;\n    const lx = edgeXAt(quad[0], quad[3], fy) * w;\n    const rx = edgeXAt(quad[1], quad[2], fy) * w;\n    const x0 = Math.max(0, Math.ceil(Math.min(lx, rx)));\n    const x1 = Math.min(w, Math.floor(Math.max(lx, rx)));\n    if (x1 - x0 < 2) continue;\n    rowsSeen++;\n    let rowDark = 0;\n    for (let x = Math.max(minX, x0); x < Math.min(maxX, x1); x++) {\n      const v = data[y * w + x];\n      inside++;\n      sumIn += v;\n      if (v >= brightCut) brightIn++;\n      else if (v <= darkCut) {\n        darkIn++;\n        rowDark++;\n      }\n    }\n    if (rowDark / (x1 - x0) >= 0.03) textRows++;\n  }\n  if (!inside) return NOTHING;\n  const paperFrac = brightIn / inside;\n  const darkFrac = darkIn / inside;\n  const rowSpread = rowsSeen ? textRows / rowsSeen : 0;\n\n  let contrastScore = 1;\n  const outside = w * h - inside;\n  if (area < 0.85 && outside > 0) {\n    let sumAll = 0;\n    for (let v = 0; v < 256; v++) sumAll += hist[v] * v;\n    const meanIn = sumIn / inside;\n    const meanOut = (sumAll - sumIn) / outside;\n    contrastScore = clamp01((meanIn - meanOut - 4) / 36);\n    // Paper darker than its surroundings is not paper on this scene.\n    if (meanIn - meanOut < 6) return NOTHING;\n  }\n\n  // Blank paper, a white wall or a lit screen has no print; a dark object is\n  // not paper at all.\n  if (darkFrac < 0.004 || darkFrac > 0.45 || paperFrac < 0.35) return NOTHING;\n\n  const paperScore = clamp01((paperFrac - 0.35) / 0.4);\n  const textScore = clamp01(rowSpread / 0.3) * clamp01(darkFrac / 0.02);\n  const fits = [left, right, top, bottom].filter((line): line is Line => !!line && line.points > 0);\n  const meanResidual = fits.length\n    ? fits.reduce((s, line) => s + line.residual, 0) / fits.length\n    : 2;\n  const fitScore = 1 - clamp01(meanResidual / 3);\n  const confidence = clamp01(\n    0.35 * paperScore + 0.3 * textScore + 0.2 * contrastScore + 0.15 * fitScore\n  );\n  if (confidence < options.minConfidence) return NOTHING;\n\n  const described = describeQuad(quad, w / h);\n  if (!described) return NOTHING;\n  return { ...described, found: true, source: \"luma\", confidence };\n}\n\n/** x of the line through a and b at height y (normalised). */\nfunction edgeXAt(a: Point, b: Point, y: number): number {\n  if (Math.abs(b.y - a.y) < 1e-9) return (a.x + b.x) / 2;\n  return a.x + ((y - a.y) / (b.y - a.y)) * (b.x - a.x);\n}\n", "// AUTO-GENERATED \u2014 DO NOT EDIT.\n// Source: shared/receiptvis-live/core/guidance.ts\n// Regenerate: node scripts/sync-receviz-web-sdk.mjs\n/**\n * What to tell the person holding the phone \u2014 one short line at a time.\n *\n * The line names the single most useful thing to fix, in a fixed order (light\n * before distance before framing before tilt before glare before focus): fixing\n * the first usually fixes the rest, and naming three problems at once gets\n * none of them fixed.\n *\n * It must also not flicker. A detector that is right 90% of the time is wrong\n * three times a second at eight frames a second, so a new hint has to hold for\n * about half a second before it replaces the one on screen. Progress messages\n * (reading, capturing, got it) are the exception: those appear at once, because\n * they are the system answering what the person just did.\n */\nimport type {\n  ControllerPhase,\n  GuidanceKey,\n  QualityIssue,\n  QualityReport,\n} from \"./types.ts\";\n\nexport const GUIDANCE_TEXT: Record<GuidanceKey, string> = {\n  starting: \"Starting camera\u2026\",\n  point: \"Point at a receipt\",\n  light: \"More light needed\",\n  closer: \"Move closer\",\n  fit: \"Fit the whole width in view\",\n  flat: \"Hold the phone flat over the receipt\",\n  straighten: \"Straighten the receipt\",\n  glare: \"Tilt a little to avoid glare\",\n  shadow: \"Keep your shadow off the receipt\",\n  steady: \"Hold steady\",\n  center: \"Center the receipt\",\n  detected: \"Receipt detected\",\n  reading: \"Reading receipt\u2026\",\n  capturing: \"Capturing\u2026\",\n  captured: \"Got it\",\n  manual: \"Tap the shutter to capture\",\n};\n\nconst ISSUE_GUIDANCE: Array<[QualityIssue, GuidanceKey]> = [\n  [\"too_dark\", \"light\"],\n  [\"too_small\", \"closer\"],\n  [\"cut_off\", \"fit\"],\n  [\"keystone\", \"flat\"],\n  [\"glare\", \"glare\"],\n  [\"blurry\", \"steady\"],\n];\n\nconst HINTS: Array<[QualityIssue, GuidanceKey]> = [\n  [\"shadow\", \"shadow\"],\n  [\"rotated\", \"straighten\"],\n  [\"off_center\", \"center\"],\n];\n\nexport function guidanceFor(\n  phase: ControllerPhase,\n  quality: QualityReport,\n  ocrPasses: number,\n  autoPaused: boolean\n): GuidanceKey {\n  switch (phase) {\n    case \"captured\":\n      return \"captured\";\n    case \"capturing\":\n      return \"capturing\";\n    case \"searching\":\n      return autoPaused ? \"manual\" : \"point\";\n    case \"aligning\": {\n      for (const [issue, key] of ISSUE_GUIDANCE) if (quality.issues.includes(issue)) return key;\n      return \"steady\";\n    }\n    case \"steadying\": {\n      for (const [issue, key] of HINTS) if (quality.issues.includes(issue)) return key;\n      return \"steady\";\n    }\n    case \"reading\":\n      if (autoPaused) return \"manual\";\n      return ocrPasses > 0 ? \"reading\" : \"detected\";\n  }\n}\n\nconst IMMEDIATE: ReadonlySet<GuidanceKey> = new Set<GuidanceKey>([\n  \"reading\",\n  \"capturing\",\n  \"captured\",\n  \"manual\",\n]);\n\n/** Holds a hint on screen until a different one has persisted for `holdMs`. */\nexport class GuidanceSmoother {\n  private shown: GuidanceKey = \"starting\";\n  private pending: GuidanceKey | null = null;\n  private pendingSince = 0;\n  private holdMs: number;\n\n  constructor(holdMs = 550) {\n    this.holdMs = holdMs;\n  }\n\n  reset(): void {\n    this.shown = \"starting\";\n    this.pending = null;\n  }\n\n  update(t: number, next: GuidanceKey): GuidanceKey {\n    if (next === this.shown) {\n      this.pending = null;\n      return this.shown;\n    }\n    if (IMMEDIATE.has(next) || this.shown === \"starting\") {\n      this.shown = next;\n      this.pending = null;\n      return this.shown;\n    }\n    if (this.pending !== next) {\n      this.pending = next;\n      this.pendingSince = t;\n      return this.shown;\n    }\n    if (t - this.pendingSince >= this.holdMs) {\n      this.shown = next;\n      this.pending = null;\n    }\n    return this.shown;\n  }\n}\n", "/**\n * Stands in for engine/parser.ts in the bundle developers download\n * (scripts/build.mjs).\n *\n * The engine is ReceiptVis Live's, copied verbatim, and it imports the receipt\n * parser for the passes in which the phone reads text itself. The web scanner\n * never does (camera.ts: maxOcrPasses 0): ReceViz reads the document on the\n * server. So the parser \u2014 the server's tuned receipt rules, most of the engine's\n * size \u2014 is left out, and this takes its place. Its two constants are the\n * parser's own; tests/parser-stub.test.mjs keeps them equal.\n */\n// Types only: erased from the bundle, so the parser itself is never pulled in.\nimport type { ParserOptions } from \"../src/engine/parser.ts\";\nimport type { FieldKey } from \"../src/engine/types.ts\";\n\nexport const DEFAULT_PARSER_OPTIONS: ParserOptions = { dateOrder: \"DMY\" };\n\nexport const REFERENCE_FIELDS: FieldKey[] = [\"receiptNumber\", \"traceNumber\", \"rrn\"];\n\nexport function parseReceiptDetailed(): never {\n  throw new Error(\"@receviz/web does not read text on the device: ReceViz reads the document on the server.\");\n}\n", "// AUTO-GENERATED \u2014 DO NOT EDIT.\n// Source: shared/receiptvis-live/core/quality.ts\n// Regenerate: node scripts/sync-receviz-web-sdk.mjs\n/**\n * Is this frame worth reading, and worth keeping?\n *\n * Two thresholds, on purpose. `readable` is the bar for spending an on-device\n * OCR pass \u2014 a slightly tilted or slightly soft frame still yields a number or\n * two, and every number read early is one the person sees sooner. `capturable`\n * is the bar for the photograph that goes to the final extraction and the\n * cloud, and there the frame has to be properly good.\n *\n * Every figure here is measured INSIDE the receipt's outline. Sharpness over\n * the whole frame would mostly measure the table.\n */\nimport { clamp01, forEachCellInQuad, percentile, quadCentroid } from \"./geometry.ts\";\nimport type { Detection, FrameSample, QualityIssue, QualityReport } from \"./types.ts\";\n\nexport type QualityThresholds = {\n  /** The receipt's share of the frame below which the phone is too far away. */\n  minCoverage: number;\n  /** Paper brightness (75th percentile of luma inside the outline, 0..255). */\n  minBrightness: number;\n  /** Share of the outline that may be blown out before it is glare. */\n  maxGlare: number;\n  /** Uneven paper brightness (a hand's or the phone's shadow) worth a hint. */\n  maxShading: number;\n  /** Edge energy needed to spend an OCR pass. */\n  minSharpnessRead: number;\n  /** Edge energy needed for the final photograph. */\n  minSharpnessCapture: number;\n  /** 0 = flat-on. Above this, the phone is tilted too far over the paper. */\n  maxKeystone: number;\n  /** In-plane rotation worth a hint (the final crop straightens it anyway). */\n  maxAngleDeg: number;\n  /** Centroid distance from the middle of the frame worth a hint. */\n  maxOffCenter: number;\n};\n\n/**\n * Defaults tuned on the grids' units, not yet on a fleet of phones: the\n * diagnostics overlay (Labs) prints every figure live so they can be tuned on\n * real devices. Sharpness is 2 x mean |Laplacian| \u2014 soft thermal print on a\n * mid-range phone sits around 20-40 when in focus and under 10 when not.\n */\nexport const DEFAULT_THRESHOLDS: QualityThresholds = {\n  minCoverage: 0.14,\n  minBrightness: 95,\n  maxGlare: 0.07,\n  maxShading: 0.3,\n  minSharpnessRead: 9,\n  minSharpnessCapture: 13,\n  maxKeystone: 0.3,\n  maxAngleDeg: 25,\n  maxOffCenter: 0.3,\n};\n\n/** Luma at or above this is treated as blown out. */\nconst SATURATED = 250;\n\n/** Issues that block the photograph. The others are hints. */\nconst BLOCKS_CAPTURE: ReadonlySet<QualityIssue> = new Set<QualityIssue>([\n  \"no_document\",\n  \"too_dark\",\n  \"too_small\",\n  \"cut_off\",\n  \"keystone\",\n  \"glare\",\n  \"blurry\",\n]);\n\nexport const NO_QUALITY: QualityReport = {\n  score: 0,\n  issues: [\"no_document\"],\n  coverage: 0,\n  brightness: 0,\n  glare: 0,\n  shading: 0,\n  sharpness: 0,\n  readable: false,\n  capturable: false,\n};\n\nexport function assessQuality(\n  sample: FrameSample,\n  detection: Detection,\n  thresholds: QualityThresholds = DEFAULT_THRESHOLDS\n): QualityReport {\n  if (!detection.found || !detection.quad) return NO_QUALITY;\n  const quad = detection.quad;\n\n  const lumaValues: number[] = [];\n  let saturated = 0;\n  // Paper level per quarter of the outline: a shadow darkens one side of the\n  // receipt while the rest stays lit, which a single brightness figure hides.\n  const centre = quadCentroid(quad);\n  const quarters: number[][] = [[], [], [], []];\n  forEachCellInQuad(sample.luma, quad, (v, gx, gy) => {\n    lumaValues.push(v);\n    if (v >= SATURATED) saturated++;\n    const right = (gx + 0.5) / sample.luma.width >= centre.x ? 1 : 0;\n    const lower = (gy + 0.5) / sample.luma.height >= centre.y ? 2 : 0;\n    quarters[right + lower].push(v);\n  });\n  const levels = quarters.filter((q) => q.length >= 6).map((q) => percentile(q, 0.75));\n  const shading =\n    levels.length >= 2 ? 1 - Math.min(...levels) / Math.max(1, Math.max(...levels)) : 0;\n  const detailValues: number[] = [];\n  forEachCellInQuad(sample.detail, quad, (v) => detailValues.push(v));\n\n  const brightness = percentile(lumaValues, 0.75);\n  const glare = lumaValues.length ? saturated / lumaValues.length : 0;\n  // The 75th percentile, because blank paper between the lines is flat in\n  // every frame; only the printed cells say whether the lens is in focus.\n  const sharpness = percentile(detailValues, 0.75);\n  const bounds = detection.bounds ?? { x: 0, y: 0, w: 0, h: 0 };\n  const coverage = bounds.w * bounds.h;\n  const offCenter = Math.hypot(centre.x - 0.5, centre.y - 0.5);\n\n  const issues: QualityIssue[] = [];\n  if (brightness < thresholds.minBrightness) issues.push(\"too_dark\");\n  if (coverage < thresholds.minCoverage) issues.push(\"too_small\");\n  // Running off the sides cuts every line of print; running off the top or\n  // the bottom is how a long receipt is held, and the final read copes.\n  if (detection.touches.left || detection.touches.right) issues.push(\"cut_off\");\n  if (detection.keystone > thresholds.maxKeystone) issues.push(\"keystone\");\n  if (Math.abs(detection.angleDeg) > thresholds.maxAngleDeg) issues.push(\"rotated\");\n  if (glare > thresholds.maxGlare) issues.push(\"glare\");\n  if (shading > thresholds.maxShading) issues.push(\"shadow\");\n  if (sharpness < thresholds.minSharpnessCapture) issues.push(\"blurry\");\n  if (offCenter > thresholds.maxOffCenter) issues.push(\"off_center\");\n\n  const sharpScore = clamp01(sharpness / (thresholds.minSharpnessCapture * 2.5));\n  const coverScore = clamp01((coverage - 0.08) / 0.42);\n  // Uneven light counts against the frame, so the best-frame rule prefers an\n  // evenly lit moment when there is one; it does not block the photograph.\n  const lightScore =\n    clamp01((brightness - 70) / 110) * (1 - 0.5 * clamp01((shading - 0.1) / 0.4));\n  const glareScore = 1 - clamp01(glare / (thresholds.maxGlare * 2));\n  const flatScore = 1 - clamp01(detection.keystone / (thresholds.maxKeystone * 1.5));\n  const score = clamp01(\n    0.35 * sharpScore +\n      0.2 * coverScore +\n      0.15 * lightScore +\n      0.1 * glareScore +\n      0.1 * flatScore +\n      0.1 * detection.confidence\n  );\n\n  const readable =\n    brightness >= thresholds.minBrightness * 0.85 &&\n    coverage >= thresholds.minCoverage * 0.75 &&\n    sharpness >= thresholds.minSharpnessRead &&\n    glare < thresholds.maxGlare * 2;\n  const capturable = !issues.some((issue) => BLOCKS_CAPTURE.has(issue));\n\n  return { score, issues, coverage, brightness, glare, shading, sharpness, readable, capturable };\n}\n", "// AUTO-GENERATED \u2014 DO NOT EDIT.\n// Source: shared/receiptvis-live/core/stability.ts\n// Regenerate: node scripts/sync-receviz-web-sdk.mjs\n/**\n * Has the phone stopped moving?\n *\n * Measured from the pictures, not the gyroscope: what matters is whether the\n * RECEIPT is still in the frame, and a phone held still over a receipt that is\n * being slid across a counter is not a steady shot. Two signals, both cheap:\n *\n * * how far the outline's corners moved since the last frame, smoothed so one\n *   noisy detection does not reset a long steady run; and\n * * how many bits of the scene fingerprint changed \u2014 which also catches motion\n *   while the outline is momentarily lost.\n */\nimport { blendQuads, cornerMotion, hamming, type Fingerprint } from \"./geometry.ts\";\nimport type { Quad } from \"./types.ts\";\n\nexport type StabilityOptions = {\n  /** Smoothed corner motion (normalised units per frame) below which it is still. */\n  maxMotion: number;\n  /** Fingerprint bits that may change between two still frames. */\n  maxSceneBits: number;\n  /** Weight of the newest frame in the smoothed motion and outline. */\n  smoothing: number;\n};\n\nexport const DEFAULT_STABILITY: StabilityOptions = {\n  maxMotion: 0.012,\n  maxSceneBits: 10,\n  smoothing: 0.45,\n};\n\nexport class StabilityTracker {\n  private options: StabilityOptions;\n  private lastQuad: Quad | null = null;\n  private lastPrint: Fingerprint | null = null;\n  private motion = 1;\n  private stableSince: number | null = null;\n  private smoothed: Quad | null = null;\n\n  constructor(options: StabilityOptions = DEFAULT_STABILITY) {\n    this.options = options;\n  }\n\n  reset(): void {\n    this.lastQuad = null;\n    this.lastPrint = null;\n    this.motion = 1;\n    this.stableSince = null;\n    this.smoothed = null;\n  }\n\n  /** Feed one frame; returns how long the scene has been still, in ms. */\n  update(t: number, quad: Quad | null, print: Fingerprint): number {\n    const { maxMotion, maxSceneBits, smoothing } = this.options;\n    const sceneBits = this.lastPrint ? hamming(this.lastPrint, print) : 64;\n    this.lastPrint = print;\n\n    if (!quad) {\n      this.lastQuad = null;\n      this.smoothed = null;\n      this.motion = 1;\n      this.stableSince = null;\n      return 0;\n    }\n\n    const step = this.lastQuad ? cornerMotion(this.lastQuad, quad) : 1;\n    this.lastQuad = quad;\n    this.motion = this.motion + (step - this.motion) * smoothing;\n\n    // The outline eases toward the new frame; a big jump (a new receipt, a\n    // fast pan) snaps instead, or the frame would trail behind the paper.\n    this.smoothed =\n      this.smoothed && step < 0.08 ? blendQuads(this.smoothed, quad, smoothing + 0.15) : quad;\n\n    const still = this.motion <= maxMotion && sceneBits <= maxSceneBits;\n    if (!still) {\n      this.stableSince = null;\n      return 0;\n    }\n    if (this.stableSince === null) this.stableSince = t;\n    return t - this.stableSince;\n  }\n\n  /** The outline to draw \u2014 smoothed over recent frames. */\n  outline(): Quad | null {\n    return this.smoothed;\n  }\n}\n", "// AUTO-GENERATED \u2014 DO NOT EDIT.\n// Source: shared/receiptvis-live/core/engine.ts\n// Regenerate: node scripts/sync-receviz-web-sdk.mjs\n/**\n * ReceiptVis Live \u2014 the engine.\n *\n * One object per scan session, fed by whichever platform adapter is running:\n *\n *   frame(sample)    every analysed frame   \u2192 snapshot to draw + what to do next\n *   textRead(ocr)    a live OCR pass came back \u2192 fields vote\n *   captured(\u2026)      the photograph was (or was not) taken\n *   finalize(ocr)    the high-resolution pass over that photograph \u2192 the reading\n *\n * The engine holds no timers and touches no camera: it is a pure function of\n * what it has been told, which is what lets the whole decision layer run in\n * Node tests with synthetic frames and OCR fixtures.\n *\n *   camera frame\n *     \u2192 detection (native outline, else the luma heuristic)   detector.ts\n *     \u2192 quality inside the outline                             quality.ts\n *     \u2192 stillness and a smoothed outline                        stability.ts\n *     \u2192 read? capture?                                          controller.ts\n *   OCR lines\n *     \u2192 candidates                                              parser.ts\n *     \u2192 checked against the receipt's own sums                  arithmetic.ts\n *     \u2192 votes across passes                                     confidence.ts\n *   final photograph (in bands when it is a long receipt)       tiles.ts\n *     \u2192 accurate OCR \u2192 triple-weight vote \u2192 reading + conflicts + sums verdict\n */\nimport { checkArithmetic, type ArithmeticFacts, type ArithmeticVerdict } from \"./arithmetic.ts\";\nimport { FieldVotes, DEFAULT_VOTES, type Conflict, type VoteOptions } from \"./confidence.ts\";\nimport {\n  CaptureController,\n  DEFAULT_CONTROLLER,\n  requirementProgress,\n  type ControllerOptions,\n} from \"./controller.ts\";\nimport { DEFAULT_DETECTOR_OPTIONS, NOTHING, detect, type DetectorOptions } from \"./detector.ts\";\nimport { expandQuad, fingerprint } from \"./geometry.ts\";\nimport { GuidanceSmoother, guidanceFor } from \"./guidance.ts\";\nimport {\n  DEFAULT_PARSER_OPTIONS,\n  REFERENCE_FIELDS,\n  parseReceiptDetailed,\n  type ParsedPass,\n  type ParserOptions,\n} from \"./parser.ts\";\nimport { DEFAULT_THRESHOLDS, NO_QUALITY, assessQuality, type QualityThresholds } from \"./quality.ts\";\nimport { DEFAULT_STABILITY, StabilityTracker, type StabilityOptions } from \"./stability.ts\";\nimport type {\n  EngineActions,\n  EngineSnapshot,\n  FieldKey,\n  FieldReading,\n  FrameSample,\n  OcrResult,\n  Quad,\n} from \"./types.ts\";\n\nexport type EngineConfig = {\n  detector: DetectorOptions;\n  quality: QualityThresholds;\n  stability: StabilityOptions;\n  controller: ControllerOptions;\n  votes: VoteOptions;\n  parser: ParserOptions;\n};\n\nexport const DEFAULT_ENGINE_CONFIG: EngineConfig = {\n  detector: DEFAULT_DETECTOR_OPTIONS,\n  quality: DEFAULT_THRESHOLDS,\n  stability: DEFAULT_STABILITY,\n  controller: DEFAULT_CONTROLLER,\n  votes: DEFAULT_VOTES,\n  parser: DEFAULT_PARSER_OPTIONS,\n};\n\nexport type EngineOverrides = { [K in keyof EngineConfig]?: Partial<EngineConfig[K]> };\n\nexport function engineConfig(overrides: EngineOverrides = {}): EngineConfig {\n  return {\n    detector: { ...DEFAULT_ENGINE_CONFIG.detector, ...overrides.detector },\n    quality: { ...DEFAULT_ENGINE_CONFIG.quality, ...overrides.quality },\n    stability: { ...DEFAULT_ENGINE_CONFIG.stability, ...overrides.stability },\n    controller: { ...DEFAULT_ENGINE_CONFIG.controller, ...overrides.controller },\n    votes: { ...DEFAULT_ENGINE_CONFIG.votes, ...overrides.votes },\n    parser: { ...DEFAULT_ENGINE_CONFIG.parser, ...overrides.parser },\n  };\n}\n\n/** What a finished scan hands the app. */\nexport type FinalReading = {\n  /**\n   * Every field, combining the live passes and the final one. Boxes are on the\n   * captured photograph, and only for fields the final pass itself located.\n   */\n  fields: Partial<Record<FieldKey, FieldReading>>;\n  /** Fields the final pass read differently from what the live passes held. */\n  conflicts: Conflict[];\n  /** The terminal's receipt number, by the server reader's precedence. */\n  reference: FieldReading | null;\n  /** Whether the high-resolution pass ran at all (it can fail; live still counts). */\n  finalRead: boolean;\n  /** How many live passes contributed. */\n  livePasses: number;\n  /**\n   * Whether the total adds up with the subtotal and VAT on the same receipt\n   * (arithmetic.ts). \"inconsistent\" is worth a person's look at the total.\n   */\n  arithmetic: ArithmeticVerdict;\n  /** The final pass's own lines \u2014 what a shared learning sample is made of (feedback.ts). */\n  finalOcr: OcrResult | null;\n};\n\n/** The receipt number by precedence: receipt/invoice no, then trace, then RRN. */\nexport function referenceReading(\n  fields: Partial<Record<FieldKey, FieldReading>>\n): FieldReading | null {\n  for (const key of REFERENCE_FIELDS) {\n    const reading = fields[key];\n    if (reading) return reading;\n  }\n  return null;\n}\n\nexport class ReceiptVisEngine {\n  readonly config: EngineConfig;\n  private votes: FieldVotes;\n  private controller: CaptureController;\n  private stability: StabilityTracker;\n  private guidance = new GuidanceSmoother();\n  private frames = 0;\n  private last: EngineSnapshot;\n  private lastT = 0;\n  private knownMerchants: readonly string[] | undefined;\n  /** The sums of the latest live pass that read any, for a scan with no final pass. */\n  private liveFacts: ArithmeticFacts | null = null;\n\n  constructor(config: EngineConfig = DEFAULT_ENGINE_CONFIG) {\n    this.config = config;\n    this.votes = new FieldVotes(config.votes);\n    this.controller = new CaptureController(config.controller);\n    this.stability = new StabilityTracker(config.stability);\n    this.last = this.emptySnapshot();\n  }\n\n  private emptySnapshot(): EngineSnapshot {\n    return {\n      phase: \"searching\",\n      guidance: \"starting\",\n      detection: NOTHING,\n      outline: null,\n      quality: NO_QUALITY,\n      stableMs: 0,\n      fields: {},\n      progress: 0,\n      ocrPasses: 0,\n      framesAnalysed: 0,\n      autoPaused: false,\n    };\n  }\n\n  reset(): void {\n    this.votes.reset();\n    this.controller.reset();\n    this.stability.reset();\n    this.guidance.reset();\n    this.frames = 0;\n    this.liveFacts = null;\n    this.last = this.emptySnapshot();\n  }\n\n  /**\n   * The businesses this household already knows (parser.ts), which can arrive\n   * after the scan has started: the next pass uses them. Keep passing the same\n   * array \u2014 the parser indexes it once.\n   */\n  setKnownMerchants(list: readonly string[] | null | undefined): void {\n    this.knownMerchants = list && list.length ? list : undefined;\n  }\n\n  private parse(ocr: OcrResult): ParsedPass {\n    const parser = this.knownMerchants\n      ? { ...this.config.parser, knownMerchants: this.knownMerchants }\n      : this.config.parser;\n    return parseReceiptDetailed(ocr, parser);\n  }\n\n  get snapshot(): EngineSnapshot {\n    return this.last;\n  }\n\n  frame(sample: FrameSample): { snapshot: EngineSnapshot; actions: EngineActions } {\n    this.frames++;\n    this.lastT = sample.t;\n    const detection = detect(\n      sample.luma,\n      sample.nativeQuad,\n      sample.nativeQuadConfidence,\n      this.config.detector\n    );\n    const quality = assessQuality(sample, detection, this.config.quality);\n    const print = fingerprint(sample.luma);\n    const stableMs = this.stability.update(sample.t, detection.found ? detection.quad : null, print);\n\n    const decision = this.controller.onFrame({\n      t: sample.t,\n      detection,\n      quality,\n      stableMs,\n      print,\n      fields: this.votes.readings(),\n    });\n    if (decision.resetFields) this.votes.reset();\n\n    const fields = this.votes.readings();\n    const phase = decision.phase;\n    const shown = this.guidance.update(\n      sample.t,\n      guidanceFor(phase, quality, this.controller.passes, this.controller.autoPaused)\n    );\n    this.last = {\n      phase,\n      guidance: shown,\n      detection,\n      outline: this.stability.outline(),\n      quality,\n      stableMs,\n      fields,\n      progress: requirementProgress(this.config.controller.required, fields).progress,\n      ocrPasses: this.controller.passes,\n      framesAnalysed: this.frames,\n      autoPaused: this.controller.autoPaused,\n    };\n    return { snapshot: this.last, actions: { readText: decision.readText, capture: decision.capture } };\n  }\n\n  /** A live OCR pass came back. Returns the fields whose value changed. */\n  textRead(result: OcrResult): FieldKey[] {\n    this.controller.ocrFinished();\n    const pass = this.parse(result);\n    if (pass.facts.taxes.length || pass.facts.bases.length) this.liveFacts = pass.facts;\n    const changed = this.votes.add(pass.candidates, \"live\");\n    const fields = this.votes.readings();\n    this.last = {\n      ...this.last,\n      fields,\n      progress: requirementProgress(this.config.controller.required, fields).progress,\n      ocrPasses: this.controller.passes,\n    };\n    return changed;\n  }\n\n  /** A live OCR pass failed or was abandoned; the next one may start. */\n  textFailed(): void {\n    this.controller.ocrFinished();\n  }\n\n  /** The shutter. False when a capture is already under way. */\n  requestCapture(t: number = this.lastT): boolean {\n    const ok = this.controller.manualCapture(t);\n    if (ok) this.last = { ...this.last, phase: \"capturing\", guidance: \"capturing\" };\n    return ok;\n  }\n\n  /**\n   * The outline the photograph should be cropped to: the smoothed outline,\n   * grown a little so a slightly late shutter never trims the paper's edge.\n   * Null when there is none \u2014 the photograph is then kept whole.\n   */\n  cropQuad(): Quad | null {\n    const outline = this.last.outline ?? this.last.detection.quad;\n    return outline ? expandQuad(outline, 1.04) : null;\n  }\n\n  captured(ok: boolean, t: number = this.lastT, manual = false): void {\n    this.controller.captureFinished(ok, t, manual);\n    const phase = this.controller.currentPhase;\n    this.last = {\n      ...this.last,\n      phase,\n      guidance: ok ? \"captured\" : this.last.guidance === \"capturing\" ? \"steady\" : this.last.guidance,\n      autoPaused: this.controller.autoPaused,\n    };\n  }\n\n  /**\n   * The high-resolution pass over the captured photograph, merged with what\n   * the live passes read. `null` when that pass could not run \u2014 the reading\n   * then rests on the live passes alone, with no boxes on the photograph.\n   */\n  finalize(result: OcrResult | null): FinalReading {\n    const livePasses = this.votes.passCount;\n    const liveFields = this.votes.readings();\n    let conflicts: Conflict[] = [];\n    let facts = this.liveFacts;\n    if (result) {\n      const pass = this.parse(result);\n      this.votes.add(pass.candidates, \"final\");\n      conflicts = this.votes.conflicts(liveFields);\n      // The sharper picture's sums, unless it read none and a live pass did.\n      if (pass.facts.taxes.length || pass.facts.bases.length || !facts) facts = pass.facts;\n    }\n    const fields = this.votes.readings(\"final\");\n    return {\n      fields,\n      conflicts,\n      reference: referenceReading(fields),\n      finalRead: !!result,\n      livePasses,\n      arithmetic: checkArithmetic(fields, facts),\n      finalOcr: result,\n    };\n  }\n\n  /** Back to the live camera after a capture the person rejected. */\n  resume(): void {\n    this.controller.resume();\n    this.last = { ...this.last, phase: \"searching\", guidance: \"point\" };\n  }\n}\n", "/**\n * A camera frame, reduced to what the engine decides on \u2014 the same two grids\n * the phones make (FrameAnalyzer.kt on Android, the Vision adapter on iOS):\n *\n *   luma    96 cells across, each the mean of four samples at its quarter\n *           points: enough to find a sheet of paper and fingerprint the scene\n *   detail  a quarter of that, 2 \u00D7 the mean |Laplacian| inside each cell,\n *           measured on the analysis-resolution plane every 3 px, clipped to\n *           255: blur flattens it, focus restores it\n *\n * The frame is analysed at up to 1280 px on its long side \u2014 the resolution the\n * phones analyse at \u2014 so the sharpness thresholds mean the same thing here.\n * The grids stay in the page: no frame is ever uploaded.\n */\nimport type { FrameSample, Grid } from \"./engine/types.ts\";\n\nexport const GRID_WIDTH = 96;\nexport const ANALYSIS_LONG_SIDE = 1280;\n/** Lattice spacing for the Laplacian, px (FrameAnalyzer.STEP). */\nconst STEP = 3;\n\n/** RGBA \u2192 one byte of luma per pixel, with the integer weights Enhancer.kt uses. */\nexport function lumaPlane(rgba: Uint8ClampedArray | Uint8Array, width: number, height: number, out?: Uint8Array): Uint8Array {\n  const n = width * height;\n  const plane = out && out.length >= n ? out : new Uint8Array(n);\n  for (let i = 0, p = 0; i < n; i++, p += 4) {\n    plane[i] = (rgba[p] * 77 + rgba[p + 1] * 150 + rgba[p + 2] * 29) >> 8;\n  }\n  return plane;\n}\n\n/** The two grids of FrameAnalyzer.analyze, from an upright luma plane. */\nexport function analyzePlane(\n  plane: Uint8Array,\n  width: number,\n  height: number,\n  gridWidth: number = GRID_WIDTH\n): { luma: Grid; detail: Grid } {\n  const gw = gridWidth;\n  const cell = width / gw;\n  const gh = Math.max(1, Math.round(height / cell));\n  const luma = new Uint8Array(gw * gh);\n  for (let gy = 0; gy < gh; gy++) {\n    for (let gx = 0; gx < gw; gx++) {\n      let sum = 0;\n      for (let k = 0; k < 4; k++) {\n        const ux = Math.min(width - 1, Math.trunc((gx + (k % 2 === 0 ? 0.25 : 0.75)) * cell));\n        const uy = Math.min(height - 1, Math.trunc((gy + (k < 2 ? 0.25 : 0.75)) * cell));\n        sum += plane[uy * width + ux];\n      }\n      luma[gy * gw + gx] = sum >> 2;\n    }\n  }\n\n  const dw = Math.max(1, Math.trunc(gw / 4));\n  const dh = Math.max(1, Math.trunc(gh / 4));\n  const sums = new Float64Array(dw * dh);\n  const counts = new Uint32Array(dw * dh);\n  const dCellW = width / dw;\n  const dCellH = height / dh;\n  for (let uy = 1; uy < height - 1; uy += STEP) {\n    const dy = Math.min(dh - 1, Math.trunc(uy / dCellH));\n    const row = uy * width;\n    for (let ux = 1; ux < width - 1; ux += STEP) {\n      const c = row + ux;\n      const lap = Math.abs(4 * plane[c] - plane[c - 1] - plane[c + 1] - plane[c - width] - plane[c + width]);\n      const dx = Math.min(dw - 1, Math.trunc(ux / dCellW));\n      sums[dy * dw + dx] += lap;\n      counts[dy * dw + dx]++;\n    }\n  }\n  const detail = new Uint8Array(dw * dh);\n  for (let i = 0; i < detail.length; i++) {\n    const mean = counts[i] > 0 ? sums[i] / counts[i] : 0;\n    detail[i] = Math.min(255, Math.round(mean * 2));\n  }\n  return {\n    luma: { width: gw, height: gh, data: luma },\n    detail: { width: dw, height: dh, data: detail },\n  };\n}\n\n/** The analysis size for a source of this size: long side at most 1280 px. */\nexport function analysisSize(width: number, height: number): { width: number; height: number } {\n  const scale = Math.min(1, ANALYSIS_LONG_SIDE / Math.max(width, height, 1));\n  return { width: Math.max(1, Math.round(width * scale)), height: Math.max(1, Math.round(height * scale)) };\n}\n\n/**\n * Samples a playing <video> into FrameSamples. One reusable canvas and one\n * reusable luma buffer, so a scan at eight frames a second allocates little.\n */\nexport class FrameSampler {\n  private canvas: HTMLCanvasElement | OffscreenCanvas | null = null;\n  private ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D | null = null;\n  private plane: Uint8Array | undefined;\n\n  sample(video: HTMLVideoElement, t: number): FrameSample | null {\n    const vw = video.videoWidth;\n    const vh = video.videoHeight;\n    if (!vw || !vh || video.readyState < 2) return null;\n    const started = performance.now();\n    const { width, height } = analysisSize(vw, vh);\n    if (!this.canvas || this.canvas.width !== width || this.canvas.height !== height) {\n      if (typeof OffscreenCanvas !== \"undefined\") {\n        this.canvas = new OffscreenCanvas(width, height);\n      } else {\n        const c = document.createElement(\"canvas\");\n        c.width = width;\n        c.height = height;\n        this.canvas = c;\n      }\n      this.ctx = this.canvas.getContext(\"2d\", { willReadFrequently: true } as CanvasRenderingContext2DSettings) as\n        | CanvasRenderingContext2D\n        | OffscreenCanvasRenderingContext2D\n        | null;\n    }\n    const ctx = this.ctx;\n    if (!ctx) return null;\n    ctx.drawImage(video, 0, 0, width, height);\n    const pixels = ctx.getImageData(0, 0, width, height).data;\n    this.plane = lumaPlane(pixels, width, height, this.plane);\n    const { luma, detail } = analyzePlane(this.plane, width, height);\n    return {\n      t,\n      frameWidth: width,\n      frameHeight: height,\n      luma,\n      detail,\n      processingMs: performance.now() - started,\n    };\n  }\n}\n", "// AUTO-GENERATED \u2014 DO NOT EDIT.\n// Source: shared/receiptvis-live/core/enhance.ts\n// Regenerate: node scripts/sync-receviz-web-sdk.mjs\n/**\n * Cleaning up the photograph: white paper, dark print \u2014 the \"document\" look\n * Google's scanner gives its pages, done on the phone after capture.\n *\n * A receipt photographed under a kitchen light is grey paper with a shadow\n * across it and print anywhere from black to thermal-faded. Two steps turn it\n * into a page that reads at a glance (and reads better for OCR, the phone's and\n * the cloud's):\n *\n *   1. even out the light \u2014 the paper's own brightness is measured region by\n *      region (the 90th percentile of each cell: print is the dark minority);\n *      a cell far darker than its neighbours (a logo, a block of dense print)\n *      borrows their paper, and the map is smoothed. Every pixel is divided by the paper behind it, so\n *      paper becomes 1.0 everywhere, shadow or not, and print keeps its\n *      contrast against it.\n *   2. stretch the contrast \u2014 what is no darker than the paper's own grain is\n *      paper (pure white: no grain, no fold marks). The paper sets that line\n *      itself: its typical pixel sits a little under the paper level (grain,\n *      JPEG noise), and the white point sits twice as far \u2014 2% under it on a\n *      clean photograph, never more than 7% on a grainy one. A fixed 7% used to\n *      erase print faded to within 7% of the paper \u2014 a receipt's faded name,\n *      its \"TAX INVOICE\" \u2014 that a person, and the recogniser, can still read.\n *      The ink's own darkness sets the black point: the darkest quarter of the\n *      ink and more goes solid black, the rest ramps up to the paper. Faded\n *      thermal print is therefore darkened a lot and crisp print hardly at all\n *      \u2014 the adaptive stretch scanners do.\n *\n * Colour is kept: every channel is divided by the same paper level and passed\n * through the same curve, so a red logo stays red, only cleaner.\n *\n * This file is the REFERENCE: the rules and constants, on one channel, tested\n * in Node (tests/core.test.mjs). The pixels are done natively after capture \u2014\n * android/\u2026/Enhancer.kt and ios/Enhancer.swift implement exactly these steps\n * with these constants. Change one, change all three.\n *\n * It runs only on a photograph cropped to the receipt's outline. A whole frame\n * has a table in it, and \"evening out the light\" of a table is making it grey\n * paper.\n */\nimport type { Grid } from \"./types.ts\";\n\nexport const ENHANCE = {\n  /** Cells across the long side for the paper map. */\n  cells: 40,\n  /** A cell is never smaller than this, px. */\n  minCell: 8,\n  /** The share of a cell's pixels darker than its paper level. */\n  paperPercentile: 0.9,\n  /**\n   * Passes in which a cell much darker than the brightest of its 3\u00D73\n   * neighbours (below `fillRatio` of it: a logo, a block of dense print) takes\n   * that neighbour's level instead. A cell only a little darker \u2014 the paper\n   * under a gentle shadow \u2014 keeps its own, or the shadow would not be evened\n   * out on its dark side.\n   */\n  fillPasses: 2,\n  fillRatio: 0.8,\n  /** 3\u00D73 box-blur passes over the paper map. */\n  blur: 2,\n  /** No paper level below this share of the median one (a black patch is not paper). */\n  floorRatio: 0.6,\n  /** \u2026nor below this, absolutely. */\n  floorMin: 64,\n  /**\n   * The white point \u2014 normalised brightness at and above which a pixel is paper\n   * (pure white) \u2014 sits `whiteSpread` times as far under the paper level as the\n   * paper's median pixel does (whitePoint), within these bounds.\n   */\n  whiteSpread: 2,\n  whiteMin: 0.93,\n  whiteMax: 0.98,\n  /** Pixels darker than this (normalised) are ink, for the black point; the rest are paper. */\n  inkBelow: 0.9,\n  /**\n   * The black point is this percentile of the ink plus `blackOffset`. A low\n   * percentile, not the median: paper grain and JPEG noise just under the\n   * paper level can outnumber the print, and must not drag the black point\n   * up into the paper.\n   */\n  inkPercentile: 0.25,\n  blackOffset: 0.05,\n  /**\n   * \u2026kept within these bounds. The upper one is what lets a faded thermal\n   * receipt (ink at ~80% of the paper) come out dark; it stays well under\n   * `whiteMin`, so the ramp from ink to paper is never a cliff.\n   */\n  blackMin: 0.2,\n  blackMax: 0.75,\n} as const;\n\n/** The paper brightness map: one level per cell, after widening and smoothing. */\nexport function paperMap(grid: Grid): { cell: number; gw: number; gh: number; level: Float32Array } {\n  const { width: w, height: h, data } = grid;\n  const cell = Math.max(ENHANCE.minCell, Math.floor(Math.max(w, h) / ENHANCE.cells));\n  const gw = Math.ceil(w / cell);\n  const gh = Math.ceil(h / cell);\n  const bins = 64;\n  const hist = new Uint32Array(gw * gh * bins);\n  const counts = new Uint32Array(gw * gh);\n  for (let y = 0; y < h; y++) {\n    const row = Math.floor(y / cell) * gw;\n    for (let x = 0; x < w; x++) {\n      const i = row + Math.floor(x / cell);\n      hist[i * bins + (data[y * w + x] >> 2)]++;\n      counts[i]++;\n    }\n  }\n  let level = new Float32Array(gw * gh);\n  for (let i = 0; i < gw * gh; i++) {\n    const target = counts[i] * ENHANCE.paperPercentile;\n    let seen = 0;\n    let bin = 0;\n    for (; bin < bins; bin++) {\n      seen += hist[i * bins + bin];\n      if (seen >= target) break;\n    }\n    level[i] = Math.min(255, bin * 4 + 2);\n  }\n  const inside = (x: number, y: number) => x >= 0 && y >= 0 && x < gw && y < gh;\n  // `symmetric`: a neighbour counts only with its opposite one, so at the\n  // photograph's edge a shadow's slope is kept instead of being averaged with\n  // the brighter side alone (which left the paper grey along a shadowed edge).\n  const pass = (fn: (own: number, values: number[]) => number, symmetric = false) => {\n    const out = new Float32Array(gw * gh);\n    for (let gy = 0; gy < gh; gy++) {\n      for (let gx = 0; gx < gw; gx++) {\n        const values: number[] = [];\n        for (let dy = -1; dy <= 1; dy++) {\n          for (let dx = -1; dx <= 1; dx++) {\n            const x = gx + dx;\n            const y = gy + dy;\n            if (inside(x, y) && (!symmetric || inside(gx - dx, gy - dy))) values.push(level[y * gw + x]);\n          }\n        }\n        out[gy * gw + gx] = fn(level[gy * gw + gx], values);\n      }\n    }\n    level = out;\n  };\n  for (let i = 0; i < ENHANCE.fillPasses; i++) {\n    pass((own, v) => {\n      const brightest = Math.max(...v);\n      return own < brightest * ENHANCE.fillRatio ? brightest : own;\n    });\n  }\n  for (let i = 0; i < ENHANCE.blur; i++) pass((_own, v) => v.reduce((s, n) => s + n, 0) / v.length, true);\n  const sorted = Array.from(level).sort((a, b) => a - b);\n  const floor = Math.max(ENHANCE.floorMin, sorted[Math.floor(sorted.length / 2)] * ENHANCE.floorRatio);\n  for (let i = 0; i < level.length; i++) level[i] = Math.max(level[i], floor);\n  return { cell, gw, gh, level };\n}\n\n/** The paper level behind pixel (x, y): bilinear between cell centres. */\nexport function paperAt(map: ReturnType<typeof paperMap>, x: number, y: number): number {\n  const { cell, gw, gh, level } = map;\n  const fx = Math.min(Math.max((x + 0.5) / cell - 0.5, 0), gw - 1);\n  const fy = Math.min(Math.max((y + 0.5) / cell - 0.5, 0), gh - 1);\n  const x0 = Math.floor(fx);\n  const y0 = Math.floor(fy);\n  const x1 = Math.min(x0 + 1, gw - 1);\n  const y1 = Math.min(y0 + 1, gh - 1);\n  const ax = fx - x0;\n  const ay = fy - y0;\n  const top = level[y0 * gw + x0] * (1 - ax) + level[y0 * gw + x1] * ax;\n  const bottom = level[y1 * gw + x0] * (1 - ax) + level[y1 * gw + x1] * ax;\n  return top * (1 - ay) + bottom * ay;\n}\n\n/**\n * Where paper ends and print begins (normalised): as far under the paper level\n * as `whiteSpread` times the paper's median pixel, which sits under it by the\n * paper's own grain. Without a paper histogram, `whiteMin`.\n */\nexport function whitePoint(paperHistogram?: Uint32Array): number {\n  let total = 0;\n  if (paperHistogram) for (const n of paperHistogram) total += n;\n  if (!paperHistogram || total === 0) return ENHANCE.whiteMin;\n  let median = 255;\n  let seen = 0;\n  for (let i = 0; i < 256; i++) {\n    seen += paperHistogram[i];\n    if (seen * 2 >= total) {\n      median = i;\n      break;\n    }\n  }\n  const white = 1 - ENHANCE.whiteSpread * (1 - median / 255);\n  return Math.min(ENHANCE.whiteMax, Math.max(ENHANCE.whiteMin, white));\n}\n\n/** The contrast curve, as a 256-entry table over normalised brightness (0..255 = 0..1). */\nexport function contrastCurve(inkHistogram: Uint32Array, paperHistogram?: Uint32Array): Uint8Array {\n  let total = 0;\n  for (const n of inkHistogram) total += n;\n  let black = 0.3;\n  if (total > 0) {\n    let seen = 0;\n    for (let i = 0; i < 256; i++) {\n      seen += inkHistogram[i];\n      if (seen >= total * ENHANCE.inkPercentile) {\n        black = i / 255 + ENHANCE.blackOffset;\n        break;\n      }\n    }\n  }\n  black = Math.min(ENHANCE.blackMax, Math.max(ENHANCE.blackMin, black));\n  const white = whitePoint(paperHistogram);\n  const lut = new Uint8Array(256);\n  for (let i = 0; i < 256; i++) {\n    const v = (i / 255 - black) / (white - black);\n    lut[i] = Math.round(Math.min(1, Math.max(0, v)) * 255);\n  }\n  return lut;\n}\n\n/** One channel, both steps. Native code does the same per colour channel. */\nexport function enhanceGrid(grid: Grid): Grid {\n  const { width: w, height: h, data } = grid;\n  const map = paperMap(grid);\n  const normalised = new Uint8Array(w * h);\n  const ink = new Uint32Array(256);\n  const paper = new Uint32Array(256);\n  const inkBelow = Math.round(ENHANCE.inkBelow * 255);\n  for (let y = 0; y < h; y++) {\n    for (let x = 0; x < w; x++) {\n      const v = Math.min(255, Math.round((data[y * w + x] * 255) / paperAt(map, x, y)));\n      normalised[y * w + x] = v;\n      if (v < inkBelow) ink[v]++;\n      else paper[v]++;\n    }\n  }\n  const lut = contrastCurve(ink, paper);\n  const out = new Uint8Array(w * h);\n  for (let i = 0; i < out.length; i++) out[i] = lut[normalised[i]];\n  return { width: w, height: h, data: out };\n}\n", "// AUTO-GENERATED \u2014 DO NOT EDIT.\n// Source: shared/receiptvis-live/core/tiles.ts\n// Regenerate: node scripts/sync-receviz-web-sdk.mjs\n/**\n * Long receipts: kept at a higher resolution, and read in bands.\n *\n * A supermarket or restaurant receipt can be three or four times as tall as it\n * is wide. Photographed whole, its print is small; capped at the usual 2400 px\n * on the long side, a 60 cm receipt is barely 800 px across \u2014 and a text\n * recogniser that scales its input down further before reading leaves the\n * small print at the bottom (the VAT line, the total) a few pixels high.\n *\n * So, for a tall outline only:\n *\n *   the photograph   is kept at up to LONG_MAX_DIMENSION on its long side\n *                    instead of the usual cap (captureDimension)\n *   the final pass   reads it as two to four overlapping horizontal bands, each\n *                    an image of its own (bandPlan), and the lines are stitched\n *                    back together (mergeBands)\n *\n * Stitching is by ownership: each band owns the stretch up to the middle of\n * its overlap with the next, and a line is kept from the band that owns its\n * centre. A line cut in two by a band's edge has its centre past that middle\n * \u2014 in the stretch the other band owns, which saw it whole \u2014 so every line is\n * kept exactly once, from the band that read it whole.\n */\nimport { ocrResultFromWire } from \"./geometry.ts\";\nimport type { OcrResult, Quad, WireOcrBands } from \"./types.ts\";\n\nexport type Band = { top: number; bottom: number };\n\n/** Taller than this (height \u00F7 width) is a long receipt. */\nexport const LONG_RECEIPT_ASPECT = 1.8;\n/** Long side of a long receipt's photograph, px \u2014 the camera's own resolution. */\nexport const LONG_MAX_DIMENSION = 3264;\n/** Each band overlaps the next by this share of the whole height. */\nconst OVERLAP = 0.06;\n\n/** The outline's height \u00F7 width, in pixels of the frame it was found in. */\nexport function quadAspect(quad: Quad, frameWidth: number, frameHeight: number): number {\n  const dist = (a: Quad[number], b: Quad[number]) =>\n    Math.hypot((a.x - b.x) * frameWidth, (a.y - b.y) * frameHeight);\n  const [tl, tr, br, bl] = quad;\n  const width = (dist(tl, tr) + dist(bl, br)) / 2;\n  const height = (dist(tl, bl) + dist(tr, br)) / 2;\n  return width > 0 ? height / width : 0;\n}\n\n/** How large the photograph of this outline is kept: bigger for a long receipt. */\nexport function captureDimension(\n  quad: Quad | null,\n  frame: { width: number; height: number } | null,\n  base: number\n): number {\n  if (!quad || !frame) return base;\n  return quadAspect(quad, frame.width, frame.height) >= LONG_RECEIPT_ASPECT\n    ? Math.max(base, LONG_MAX_DIMENSION)\n    : base;\n}\n\n/**\n * The bands a photograph of this size is read in: one (the whole picture) for\n * anything short of a long receipt, then one more for every ~0.9 of aspect.\n */\nexport function bandPlan(width: number, height: number): Band[] {\n  const aspect = width > 0 ? height / width : 0;\n  const count = aspect < 1.7 ? 1 : aspect < 2.6 ? 2 : aspect < 3.5 ? 3 : 4;\n  if (count === 1) return [{ top: 0, bottom: 1 }];\n  const step = (1 - OVERLAP) / count;\n  const bands: Band[] = [];\n  for (let i = 0; i < count; i++) {\n    const top = i * step;\n    const bottom = i === count - 1 ? 1 : top + step + OVERLAP;\n    bands.push({ top: round(top), bottom: round(bottom) });\n  }\n  return bands;\n}\n\nfunction round(n: number): number {\n  return Math.round(n * 10000) / 10000;\n}\n\n/** The bands as the flat list the native side takes: top0, bottom0, top1, \u2026 */\nexport function bandsToNumbers(bands: Band[]): number[] {\n  return bands.flatMap((b) => [b.top, b.bottom]);\n}\n\n/** One reading of the whole photograph out of its bands; see the header. */\nexport function mergeBands(wire: WireOcrBands): OcrResult {\n  const bands = [...wire.bands].sort((a, b) => a.top - b.top);\n  const lines: WireOcrBands[\"bands\"][number][\"lines\"] = [];\n  bands.forEach((band, i) => {\n    const from = i === 0 ? 0 : (band.top + bands[i - 1].bottom) / 2;\n    const to = i === bands.length - 1 ? 1 : (band.bottom + bands[i + 1].top) / 2;\n    for (const line of band.lines) {\n      const centre = line.y + line.h / 2;\n      // The last band owns its bottom edge; every other stretch is half-open.\n      if (centre >= from && (centre < to || i === bands.length - 1)) lines.push(line);\n    }\n  });\n  return ocrResultFromWire({ width: wire.width, height: wire.height, ms: wire.ms, lines });\n}\n", "/**\r\n * Preparing a picture in the browser before it is uploaded \u2014 once, never per frame.\r\n *\r\n *   normalizeImage   decode (EXIF orientation applied), scale so the long side\r\n *                    is at most 2400 px \u2014 or 3264 px for a long receipt, whose\r\n *                    small print ReceViz reads with Adaptive Document Tiling\r\n *                    (engine/tiles.ts: the same rule the phones use) \u2014 and\r\n *                    encode as JPEG\r\n *   warpToQuad       straighten a detected outline into a flat rectangle\r\n *                    (a true perspective transform, bilinear sampled)\r\n *   cleanUp          white paper and dark print: the ReceiptVis clean-up\r\n *                    (engine/enhance.ts), applied to every colour channel with\r\n *                    one gain and one curve, exactly as the native Enhancers do\r\n *\r\n * All of it runs on canvases; nothing leaves the page until the caller uploads.\r\n */\r\nimport { ENHANCE, contrastCurve, paperMap } from \"./engine/enhance.ts\";\r\nimport { LONG_MAX_DIMENSION, LONG_RECEIPT_ASPECT } from \"./engine/tiles.ts\";\r\nimport type { Grid, Quad } from \"./engine/types.ts\";\r\n\r\nexport const DEFAULT_MAX_SIDE = 2400;\r\n\r\nexport type Canvasish = HTMLCanvasElement | OffscreenCanvas;\r\n\r\nfunction canvas(width: number, height: number): Canvasish {\r\n  if (typeof OffscreenCanvas !== \"undefined\") return new OffscreenCanvas(width, height);\r\n  const c = document.createElement(\"canvas\");\r\n  c.width = width;\r\n  c.height = height;\r\n  return c;\r\n}\r\n\r\nfunction context2d(c: Canvasish): CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D {\r\n  const ctx = c.getContext(\"2d\", { willReadFrequently: true } as CanvasRenderingContext2DSettings);\r\n  if (!ctx) throw new Error(\"A 2D canvas is not available in this browser.\");\r\n  return ctx as CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D;\r\n}\r\n\r\nexport async function toBlob(c: Canvasish, quality = 0.9): Promise<Blob> {\r\n  if (typeof OffscreenCanvas !== \"undefined\" && c instanceof OffscreenCanvas) {\r\n    return c.convertToBlob({ type: \"image/jpeg\", quality });\r\n  }\r\n  return new Promise((resolve, reject) =>\r\n    (c as HTMLCanvasElement).toBlob((b) => (b ? resolve(b) : reject(new Error(\"Encoding failed\"))), \"image/jpeg\", quality)\r\n  );\r\n}\r\n\r\n/** The long side a document of this size is kept at. */\r\nexport function targetLongSide(width: number, height: number, base = DEFAULT_MAX_SIDE): number {\r\n  const aspect = Math.max(width, height) / Math.max(1, Math.min(width, height));\r\n  return aspect >= LONG_RECEIPT_ASPECT ? Math.max(base, LONG_MAX_DIMENSION) : base;\r\n}\r\n\r\n/**\r\n * A file from an <input type=file> or a drop, ready to send. PDFs pass through\r\n * untouched (ReceViz renders them); images are decoded upright and scaled.\r\n */\r\nexport async function normalizeImage(\r\n  file: Blob,\r\n  { maxSide, cleanUp: clean = false, quality = 0.9 }: { maxSide?: number; cleanUp?: boolean; quality?: number } = {}\r\n): Promise<{ blob: Blob; width: number; height: number; scaled: boolean }> {\r\n  if (file.type === \"application/pdf\") return { blob: file, width: 0, height: 0, scaled: false };\r\n  let bitmap: ImageBitmap;\r\n  try {\r\n    bitmap = await createImageBitmap(file, { imageOrientation: \"from-image\" } as ImageBitmapOptions);\r\n  } catch {\r\n    // A format this browser cannot decode (HEIC outside Safari): ReceViz can,\r\n    // so the file goes as it is.\r\n    return { blob: file, width: 0, height: 0, scaled: false };\r\n  }\r\n  const limit = maxSide ?? targetLongSide(bitmap.width, bitmap.height);\r\n  const scale = Math.min(1, limit / Math.max(bitmap.width, bitmap.height));\r\n  const width = Math.max(1, Math.round(bitmap.width * scale));\r\n  const height = Math.max(1, Math.round(bitmap.height * scale));\r\n  const c = canvas(width, height);\r\n  const ctx = context2d(c);\r\n  ctx.imageSmoothingQuality = \"high\";\r\n  ctx.drawImage(bitmap, 0, 0, width, height);\r\n  bitmap.close?.();\r\n  if (clean) cleanUpContext(ctx, width, height);\r\n  const unchanged = scale === 1 && !clean && file.type === \"image/jpeg\";\r\n  return { blob: unchanged ? file : await toBlob(c, quality), width, height, scaled: scale < 1 };\r\n}\r\n\r\n// \u2500\u2500 perspective \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\n/** The 3\u00D73 homography taking the unit square's corners to `dst` (TL, TR, BR, BL). */\r\nfunction squareToQuad(dst: Array<{ x: number; y: number }>): number[] {\r\n  const [p0, p1, p2, p3] = dst;\r\n  const dx1 = p1.x - p2.x;\r\n  const dx2 = p3.x - p2.x;\r\n  const dx3 = p0.x - p1.x + p2.x - p3.x;\r\n  const dy1 = p1.y - p2.y;\r\n  const dy2 = p3.y - p2.y;\r\n  const dy3 = p0.y - p1.y + p2.y - p3.y;\r\n  let a13 = 0;\r\n  let a23 = 0;\r\n  if (Math.abs(dx3) > 1e-9 || Math.abs(dy3) > 1e-9) {\r\n    const det = dx1 * dy2 - dx2 * dy1;\r\n    a13 = (dx3 * dy2 - dx2 * dy3) / det;\r\n    a23 = (dx1 * dy3 - dx3 * dy1) / det;\r\n  }\r\n  return [\r\n    p1.x - p0.x + a13 * p1.x, p3.x - p0.x + a23 * p3.x, p0.x,\r\n    p1.y - p0.y + a13 * p1.y, p3.y - p0.y + a23 * p3.y, p0.y,\r\n    a13, a23, 1,\r\n  ];\r\n}\r\n\r\n/** Output size for a quad in pixels: the average of opposite edges. */\r\nexport function quadSize(quad: Quad, width: number, height: number): { w: number; h: number } {\r\n  const d = (a: Quad[number], b: Quad[number]) => Math.hypot((a.x - b.x) * width, (a.y - b.y) * height);\r\n  const [tl, tr, br, bl] = quad;\r\n  return { w: Math.round((d(tl, tr) + d(bl, br)) / 2), h: Math.round((d(tl, bl) + d(tr, br)) / 2) };\r\n}\r\n\r\n/**\r\n * Straighten the region `quad` (normalised to the source) into a rectangle.\r\n * Inverse mapping: every output pixel asks where it came from, so there are\r\n * no holes; bilinear sampling keeps thin print legible.\r\n */\r\nexport function warpToQuad(source: ImageData, quad: Quad, maxSide: number): ImageData {\r\n  const size = quadSize(quad, source.width, source.height);\r\n  const scale = Math.min(1, maxSide / Math.max(size.w, size.h, 1));\r\n  const outW = Math.max(1, Math.round(size.w * scale));\r\n  const outH = Math.max(1, Math.round(size.h * scale));\r\n  const H = squareToQuad(quad.map((p) => ({ x: p.x * (source.width - 1), y: p.y * (source.height - 1) })));\r\n  const out = new ImageData(outW, outH);\r\n  const src = source.data;\r\n  const dst = out.data;\r\n  const sw = source.width;\r\n  const sh = source.height;\r\n  for (let y = 0; y < outH; y++) {\r\n    const v = outH === 1 ? 0 : y / (outH - 1);\r\n    for (let x = 0; x < outW; x++) {\r\n      const u = outW === 1 ? 0 : x / (outW - 1);\r\n      const w = H[6] * u + H[7] * v + H[8];\r\n      const sx = (H[0] * u + H[1] * v + H[2]) / w;\r\n      const sy = (H[3] * u + H[4] * v + H[5]) / w;\r\n      const x0 = Math.floor(sx);\r\n      const y0 = Math.floor(sy);\r\n      const ax = sx - x0;\r\n      const ay = sy - y0;\r\n      const xa = Math.min(Math.max(x0, 0), sw - 1);\r\n      const xb = Math.min(Math.max(x0 + 1, 0), sw - 1);\r\n      const ya = Math.min(Math.max(y0, 0), sh - 1);\r\n      const yb = Math.min(Math.max(y0 + 1, 0), sh - 1);\r\n      const i00 = (ya * sw + xa) * 4;\r\n      const i10 = (ya * sw + xb) * 4;\r\n      const i01 = (yb * sw + xa) * 4;\r\n      const i11 = (yb * sw + xb) * 4;\r\n      const o = (y * outW + x) * 4;\r\n      for (let c = 0; c < 3; c++) {\r\n        const top = src[i00 + c] * (1 - ax) + src[i10 + c] * ax;\r\n        const bottom = src[i01 + c] * (1 - ax) + src[i11 + c] * ax;\r\n        dst[o + c] = top * (1 - ay) + bottom * ay;\r\n      }\r\n      dst[o + 3] = 255;\r\n    }\r\n  }\r\n  return out;\r\n}\r\n\r\n// \u2500\u2500 the document clean-up \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\r\n\r\n/** The luma Enhancer.kt uses, integer for integer, so every platform grades the same page. */\r\nfunction lumaOf(r: number, g: number, b: number): number {\r\n  return (r * 77 + g * 150 + b * 29) >> 8;\r\n}\r\n\r\n/** engine/enhance.ts's two steps, on RGBA pixels in place. */\r\nexport function cleanUpPixels(image: ImageData): ImageData {\r\n  const { width: w, height: h, data } = image;\r\n  const luma = new Uint8Array(w * h);\r\n  for (let i = 0, p = 0; i < luma.length; i++, p += 4) luma[i] = lumaOf(data[p], data[p + 1], data[p + 2]);\r\n  const grid: Grid = { width: w, height: h, data: luma };\r\n  const map = paperMap(grid);\r\n  const { cell, gw, gh, level } = map;\r\n  // Column interpolation is the same for every row: precompute it.\r\n  const x0s = new Int32Array(w);\r\n  const x1s = new Int32Array(w);\r\n  const axs = new Float32Array(w);\r\n  for (let x = 0; x < w; x++) {\r\n    const fx = Math.min(Math.max((x + 0.5) / cell - 0.5, 0), gw - 1);\r\n    x0s[x] = Math.floor(fx);\r\n    x1s[x] = Math.min(x0s[x] + 1, gw - 1);\r\n    axs[x] = fx - x0s[x];\r\n  }\r\n  const ink = new Uint32Array(256);\r\n  const paper = new Uint32Array(256);\r\n  const inkBelow = Math.round(ENHANCE.inkBelow * 255);\r\n  for (let y = 0; y < h; y++) {\r\n    const fy = Math.min(Math.max((y + 0.5) / cell - 0.5, 0), gh - 1);\r\n    const y0 = Math.floor(fy);\r\n    const y1 = Math.min(y0 + 1, gh - 1);\r\n    const ay = fy - y0;\r\n    for (let x = 0; x < w; x++) {\r\n      const ax = axs[x];\r\n      const top = level[y0 * gw + x0s[x]] * (1 - ax) + level[y0 * gw + x1s[x]] * ax;\r\n      const bottom = level[y1 * gw + x0s[x]] * (1 - ax) + level[y1 * gw + x1s[x]] * ax;\r\n      const gain = 255 / (top * (1 - ay) + bottom * ay);\r\n      const p = (y * w + x) * 4;\r\n      const r = Math.min(255, Math.round(data[p] * gain));\r\n      const g = Math.min(255, Math.round(data[p + 1] * gain));\r\n      const b = Math.min(255, Math.round(data[p + 2] * gain));\r\n      data[p] = r;\r\n      data[p + 1] = g;\r\n      data[p + 2] = b;\r\n      const l = lumaOf(r, g, b);\r\n      if (l < inkBelow) ink[l]++;\r\n      else paper[l]++;\r\n    }\r\n  }\r\n  const lut = contrastCurve(ink, paper);\r\n  for (let p = 0; p < data.length; p += 4) {\r\n    data[p] = lut[data[p]];\r\n    data[p + 1] = lut[data[p + 1]];\r\n    data[p + 2] = lut[data[p + 2]];\r\n  }\r\n  return image;\r\n}\r\n\r\nfunction cleanUpContext(ctx: CanvasRenderingContext2D | OffscreenCanvasRenderingContext2D, w: number, h: number): void {\r\n  const image = ctx.getImageData(0, 0, w, h);\r\n  ctx.putImageData(cleanUpPixels(image), 0, 0);\r\n}\r\n\r\n/** Crop + straighten + (optionally) clean up a full-resolution frame. */\r\nexport async function documentFromFrame(\r\n  frame: ImageData,\r\n  quad: Quad | null,\r\n  { cleanUp = true, quality = 0.9 }: { cleanUp?: boolean; quality?: number } = {}\r\n): Promise<{ blob: Blob; width: number; height: number; cropped: boolean }> {\r\n  let image = frame;\r\n  let cropped = false;\r\n  if (quad) {\r\n    const size = quadSize(quad, frame.width, frame.height);\r\n    image = warpToQuad(frame, quad, targetLongSide(size.w, size.h));\r\n    cropped = true;\r\n  } else {\r\n    const limit = targetLongSide(frame.width, frame.height);\r\n    if (Math.max(frame.width, frame.height) > limit) {\r\n      const s = limit / Math.max(frame.width, frame.height);\r\n      const c = canvas(frame.width, frame.height);\r\n      context2d(c).putImageData(frame, 0, 0);\r\n      const out = canvas(Math.round(frame.width * s), Math.round(frame.height * s));\r\n      const ctx = context2d(out);\r\n      ctx.drawImage(c as CanvasImageSource, 0, 0, out.width, out.height);\r\n      image = ctx.getImageData(0, 0, out.width, out.height);\r\n    }\r\n  }\r\n  // The clean-up is only for a photo cropped to the document: a whole frame\r\n  // has a table in it, and \"evening out the light\" of a table greys it.\r\n  if (cleanUp && cropped) cleanUpPixels(image);\r\n  const c = canvas(image.width, image.height);\r\n  context2d(c).putImageData(image, 0, 0);\r\n  return { blob: await toBlob(c, quality), width: image.width, height: image.height, cropped };\r\n}\r\n", "/**\n * The camera, without a user interface: for apps that draw their own.\n *\n * DocumentCamera plays the camera into a <video> you place, analyses about\n * eight frames a second in the page, and takes the picture when the document\n * is found, sharp, well lit and still \u2014 the same decisions ReceiptVis Live\n * makes on Android and iOS, from the same engine (./engine, a verbatim copy of\n * shared/receiptvis-live/core). The only difference is reading: phones read\n * text live; a browser does not, so here the scan is complete as soon as the\n * picture is good, and the reading is done once, by ReceViz, on upload.\n *\n * Nothing leaves the page until you upload the CapturedDocument.\n */\nimport { ReceiptVisEngine, engineConfig, type EngineOverrides } from \"./engine/engine.ts\";\nimport type { EngineSnapshot, GuidanceKey, Quad, QualityReport } from \"./engine/types.ts\";\nimport { ReceVizError } from \"./errors.ts\";\nimport { FrameSampler } from \"./frames.ts\";\nimport { documentFromFrame } from \"./image.ts\";\n\n/** What the person is told, with the document named (\"receipt\", \"invoice\"\u2026). */\nexport function guidanceText(key: GuidanceKey, noun = \"document\"): string {\n  const text: Record<GuidanceKey, string> = {\n    starting: \"Starting camera\u2026\",\n    point: `Point the camera at the ${noun}`,\n    light: \"More light needed\",\n    closer: \"Move closer\",\n    fit: `Fit the whole ${noun} in view`,\n    flat: `Hold the camera flat over the ${noun}`,\n    straighten: `Straighten the ${noun}`,\n    glare: \"Tilt a little to avoid glare\",\n    shadow: `Keep your shadow off the ${noun}`,\n    steady: \"Hold steady\",\n    center: `Center the ${noun}`,\n    detected: `${noun.charAt(0).toUpperCase()}${noun.slice(1)} found`,\n    reading: \"Hold steady\",\n    capturing: \"Capturing\u2026\",\n    captured: \"Got it\",\n    manual: \"Take the photo when it looks right\",\n  };\n  return text[key];\n}\n\nexport type CapturedDocument = {\n  /** JPEG, cropped to the document and straightened when an outline was found. */\n  blob: Blob;\n  width: number;\n  height: number;\n  cropped: boolean;\n  /** The outline used, normalised to the camera frame (TL, TR, BR, BL). */\n  quad: Quad | null;\n  /** The frame's quality when the picture was taken. */\n  quality: QualityReport;\n  /** Taken with the shutter rather than automatically. */\n  manual: boolean;\n};\n\nexport type CameraState = {\n  snapshot: EngineSnapshot;\n  guidance: string;\n};\n\nexport type DocumentCameraOptions = {\n  /** Where the preview plays. Muted, inline playback is set for you. */\n  video: HTMLVideoElement;\n  /** Take the picture automatically at the best moment (default true). */\n  autoCapture?: boolean;\n  /** White paper, dark print, as the phones do (default true). */\n  cleanUp?: boolean;\n  /** What to call the document in guidance (default \"document\"). */\n  noun?: string;\n  /** Frames analysed per second (default 8). */\n  fps?: number;\n  facingMode?: \"environment\" | \"user\";\n  onUpdate?: (state: CameraState) => void;\n  onCapture?: (document: CapturedDocument) => void;\n  onError?: (error: ReceVizError) => void;\n  /** Advanced: the engine's thresholds (quality, stability, controller). */\n  engine?: EngineOverrides;\n};\n\nfunction cameraError(err: unknown): ReceVizError {\n  const name = (err as { name?: string })?.name;\n  if (name === \"NotAllowedError\" || name === \"SecurityError\") {\n    return new ReceVizError(\"camera_error\", \"permission_denied\",\n      \"Camera access was not allowed. Allow it in the browser's site settings, or choose a file instead.\");\n  }\n  if (name === \"NotFoundError\" || name === \"OverconstrainedError\") {\n    return new ReceVizError(\"camera_error\", \"no_camera\", \"No camera was found on this device.\");\n  }\n  if (name === \"NotReadableError\" || name === \"AbortError\") {\n    return new ReceVizError(\"camera_error\", \"camera_busy\",\n      \"The camera is in use by another app or tab. Close it and try again.\");\n  }\n  return new ReceVizError(\"camera_error\", \"camera_unavailable\", \"The camera could not be started.\");\n}\n\nexport class DocumentCamera {\n  private readonly options: DocumentCameraOptions;\n  readonly engine: ReceiptVisEngine;\n  private readonly sampler = new FrameSampler();\n  private stream: MediaStream | null = null;\n  private timer: ReturnType<typeof setTimeout> | null = null;\n  private videoCallback: number | null = null;\n  private lastSampleAt = -Infinity;\n  private busy = false;\n  private stopped = true;\n  /** A picture was taken: frames are not analysed until retake(). */\n  private paused = false;\n  /** What guidance calls the document; setNoun() can change it while running. */\n  private noun: string;\n\n  constructor(options: DocumentCameraOptions) {\n    this.options = options;\n    this.noun = options.noun?.trim() || \"document\";\n    const overrides = options.engine ?? {};\n    this.engine = new ReceiptVisEngine(\n      engineConfig({\n        ...overrides,\n        controller: {\n          // No live reading in a browser: the scan needs nothing but a good picture.\n          required: [],\n          maxOcrPasses: 0,\n          autoCapture: options.autoCapture !== false,\n          ...overrides.controller,\n        },\n      })\n    );\n  }\n\n  /**\n   * Call the document something else from now on (the scanner does this when\n   * the document type's own noun arrives). The line on screen follows at once.\n   */\n  setNoun(noun: string): void {\n    const next = noun.trim();\n    if (!next || next === this.noun) return;\n    this.noun = next;\n    this.options.onUpdate?.({ snapshot: this.engine.snapshot, guidance: guidanceText(this.engine.snapshot.guidance, next) });\n  }\n\n  /** Whether this browser can run the camera at all (secure context + getUserMedia). */\n  static isSupported(): boolean {\n    return (\n      typeof navigator !== \"undefined\" &&\n      !!navigator.mediaDevices?.getUserMedia &&\n      (typeof window === \"undefined\" || window.isSecureContext !== false)\n    );\n  }\n\n  async start(): Promise<void> {\n    if (!DocumentCamera.isSupported()) {\n      throw new ReceVizError(\"camera_error\", \"camera_unsupported\",\n        \"This browser cannot use the camera here. Camera access needs a secure (https) page.\");\n    }\n    const video = this.options.video;\n    video.muted = true;\n    video.playsInline = true;\n    video.setAttribute(\"playsinline\", \"\");\n    try {\n      this.stream = await navigator.mediaDevices.getUserMedia({\n        audio: false,\n        video: {\n          facingMode: { ideal: this.options.facingMode ?? \"environment\" },\n          width: { ideal: 1920 },\n          height: { ideal: 1080 },\n        },\n      });\n    } catch (err) {\n      throw cameraError(err);\n    }\n    video.srcObject = this.stream;\n    try {\n      await video.play();\n    } catch (err) {\n      this.stop();\n      throw cameraError(err);\n    }\n    this.stopped = false;\n    this.paused = false;\n    this.engine.reset();\n    this.schedule();\n  }\n\n  stop(): void {\n    this.stopped = true;\n    this.unschedule();\n    this.stream?.getTracks().forEach((track) => track.stop());\n    this.stream = null;\n    this.options.video.srcObject = null;\n  }\n\n  /** Back to live scanning after a picture the person did not keep. */\n  retake(): void {\n    // A fresh scan: the arm delay and the stillness start over, so the same\n    // shot is not taken again the moment the preview closes.\n    this.engine.reset();\n    this.paused = false;\n    if (!this.stopped) this.schedule();\n  }\n\n  /** The shutter. Resolves with the picture, or null when one is already being taken. */\n  async capture(): Promise<CapturedDocument | null> {\n    if (this.stopped || !this.engine.requestCapture(performance.now())) return null;\n    return this.take(true);\n  }\n\n  // \u2500\u2500 the loop \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n  private unschedule(): void {\n    if (this.timer !== null) clearTimeout(this.timer);\n    this.timer = null;\n    const video = this.options.video as HTMLVideoElement & { cancelVideoFrameCallback?: (id: number) => void };\n    if (this.videoCallback !== null) video.cancelVideoFrameCallback?.(this.videoCallback);\n    this.videoCallback = null;\n  }\n\n  private schedule(): void {\n    this.unschedule();\n    if (this.stopped || this.paused) return;\n    const video = this.options.video as HTMLVideoElement & {\n      requestVideoFrameCallback?: (cb: () => void) => number;\n    };\n    if (video.requestVideoFrameCallback) {\n      this.videoCallback = video.requestVideoFrameCallback(() => this.tick());\n    } else {\n      this.timer = setTimeout(() => this.tick(), 1000 / (this.options.fps ?? 8));\n    }\n  }\n\n  private tick(): void {\n    this.videoCallback = null;\n    this.timer = null;\n    if (this.stopped || this.paused) return;\n    const t = performance.now();\n    const interval = 1000 / (this.options.fps ?? 8);\n    const hidden = typeof document !== \"undefined\" && document.visibilityState === \"hidden\";\n    if (!this.busy && !hidden && t - this.lastSampleAt >= interval * 0.9) {\n      this.lastSampleAt = t;\n      const sample = this.sampler.sample(this.options.video, t);\n      if (sample) {\n        const { snapshot, actions } = this.engine.frame(sample);\n        this.options.onUpdate?.({ snapshot, guidance: guidanceText(snapshot.guidance, this.noun) });\n        if (actions.capture) {\n          void this.take(false);\n          return;\n        }\n      }\n    }\n    this.schedule();\n  }\n\n  private async take(manual: boolean): Promise<CapturedDocument | null> {\n    this.busy = true;\n    const video = this.options.video;\n    const t = performance.now();\n    try {\n      const quad = this.engine.cropQuad();\n      const quality = this.engine.snapshot.quality;\n      const width = video.videoWidth;\n      const height = video.videoHeight;\n      const canvas = document.createElement(\"canvas\");\n      canvas.width = width;\n      canvas.height = height;\n      const ctx = canvas.getContext(\"2d\", { willReadFrequently: true });\n      if (!ctx || !width || !height) throw new Error(\"no frame\");\n      ctx.drawImage(video, 0, 0, width, height);\n      const frame = ctx.getImageData(0, 0, width, height);\n      const doc = await documentFromFrame(frame, quad, { cleanUp: this.options.cleanUp !== false });\n      const captured: CapturedDocument = { ...doc, quad, quality, manual };\n      this.paused = true;\n      this.unschedule();\n      this.engine.captured(true, t, manual);\n      this.options.onUpdate?.({\n        snapshot: this.engine.snapshot,\n        guidance: guidanceText(this.engine.snapshot.guidance, this.noun),\n      });\n      this.options.onCapture?.(captured);\n      return captured;\n    } catch {\n      this.engine.captured(false, t, manual);\n      this.options.onError?.(new ReceVizError(\"camera_error\", \"capture_failed\", \"The picture could not be taken. Try again.\"));\n      this.schedule();\n      return null;\n    } finally {\n      this.busy = false;\n    }\n  }\n}\n", "// AUTO-GENERATED \u2014 DO NOT EDIT.\n// Source: shared/receviz-fixtures/capture-nouns.json\n// Regenerate: node scripts/sync-receviz-capture-nouns.mjs\n// The scanner-noun vocabulary as a table; the rule is nouns.ts.\n\nexport const FALLBACK_NOUN = \"document\";\n\nexport const NOUN_PHRASES: ReadonlyArray<readonly [readonly string[], string]> = [\n  [[\"receipt\"], \"receipt\"],\n  [[\"receipts\"], \"receipt\"],\n  [[\"reciept\"], \"receipt\"],\n  [[\"reciepts\"], \"receipt\"],\n  [[\"till\", \"slip\"], \"receipt\"],\n  [[\"sales\", \"slip\"], \"receipt\"],\n  [[\"cash\", \"memo\"], \"receipt\"],\n  [[\"invoice\"], \"invoice\"],\n  [[\"invoices\"], \"invoice\"],\n  [[\"proforma\"], \"invoice\"],\n  [[\"pro\", \"forma\"], \"invoice\"],\n  [[\"credit\", \"note\"], \"credit note\"],\n  [[\"credit\", \"notes\"], \"credit note\"],\n  [[\"debit\", \"note\"], \"debit note\"],\n  [[\"debit\", \"notes\"], \"debit note\"],\n  [[\"delivery\", \"note\"], \"delivery note\"],\n  [[\"delivery\", \"notes\"], \"delivery note\"],\n  [[\"delivery\", \"order\"], \"delivery note\"],\n  [[\"delivery\", \"slip\"], \"delivery note\"],\n  [[\"dispatch\", \"note\"], \"delivery note\"],\n  [[\"goods\", \"received\", \"note\"], \"delivery note\"],\n  [[\"grn\"], \"delivery note\"],\n  [[\"purchase\", \"order\"], \"purchase order\"],\n  [[\"purchase\", \"orders\"], \"purchase order\"],\n  [[\"local\", \"purchase\", \"order\"], \"purchase order\"],\n  [[\"lpo\"], \"purchase order\"],\n  [[\"packing\", \"list\"], \"packing list\"],\n  [[\"packing\", \"slip\"], \"packing list\"],\n  [[\"waybill\"], \"waybill\"],\n  [[\"air\", \"waybill\"], \"waybill\"],\n  [[\"airway\", \"bill\"], \"waybill\"],\n  [[\"awb\"], \"waybill\"],\n  [[\"consignment\", \"note\"], \"waybill\"],\n  [[\"bill\", \"of\", \"lading\"], \"bill of lading\"],\n  [[\"bill\"], \"bill\"],\n  [[\"bills\"], \"bill\"],\n  [[\"bank\", \"statement\"], \"bank statement\"],\n  [[\"bank\", \"statements\"], \"bank statement\"],\n  [[\"statement\"], \"statement\"],\n  [[\"statements\"], \"statement\"],\n  [[\"quote\"], \"quote\"],\n  [[\"quotes\"], \"quote\"],\n  [[\"quotation\"], \"quote\"],\n  [[\"quotations\"], \"quote\"],\n  [[\"estimate\"], \"estimate\"],\n  [[\"estimates\"], \"estimate\"],\n  [[\"business\", \"card\"], \"business card\"],\n  [[\"business\", \"cards\"], \"business card\"],\n  [[\"visiting\", \"card\"], \"business card\"],\n  [[\"contact\", \"card\"], \"business card\"],\n  [[\"id\", \"card\"], \"ID card\"],\n  [[\"identity\", \"card\"], \"ID card\"],\n  [[\"identification\", \"card\"], \"ID card\"],\n  [[\"emirates\", \"id\"], \"ID card\"],\n  [[\"national\", \"id\"], \"ID card\"],\n  [[\"passport\"], \"passport\"],\n  [[\"passports\"], \"passport\"],\n  [[\"visa\"], \"visa\"],\n  [[\"residence\", \"permit\"], \"residence permit\"],\n  [[\"work\", \"permit\"], \"work permit\"],\n  [[\"driving\", \"licence\"], \"driver's license\"],\n  [[\"driving\", \"license\"], \"driver's license\"],\n  [[\"driver\", \"license\"], \"driver's license\"],\n  [[\"drivers\", \"license\"], \"driver's license\"],\n  [[\"driver\", \"s\", \"license\"], \"driver's license\"],\n  [[\"driver\", \"licence\"], \"driver's license\"],\n  [[\"drivers\", \"licence\"], \"driver's license\"],\n  [[\"trade\", \"license\"], \"trade license\"],\n  [[\"trade\", \"licence\"], \"trade license\"],\n  [[\"license\"], \"license\"],\n  [[\"licence\"], \"license\"],\n  [[\"licenses\"], \"license\"],\n  [[\"licences\"], \"license\"],\n  [[\"cheque\"], \"cheque\"],\n  [[\"cheques\"], \"cheque\"],\n  [[\"ticket\"], \"ticket\"],\n  [[\"tickets\"], \"ticket\"],\n  [[\"boarding\", \"pass\"], \"boarding pass\"],\n  [[\"boarding\", \"passes\"], \"boarding pass\"],\n  [[\"prescription\"], \"prescription\"],\n  [[\"prescriptions\"], \"prescription\"],\n  [[\"payslip\"], \"payslip\"],\n  [[\"payslips\"], \"payslip\"],\n  [[\"pay\", \"slip\"], \"payslip\"],\n  [[\"salary\", \"slip\"], \"payslip\"],\n  [[\"paystub\"], \"payslip\"],\n  [[\"pay\", \"stub\"], \"payslip\"],\n  [[\"salary\", \"certificate\"], \"salary certificate\"],\n  [[\"certificate\"], \"certificate\"],\n  [[\"certificates\"], \"certificate\"],\n  [[\"deposit\", \"slip\"], \"deposit slip\"],\n  [[\"deposit\", \"slips\"], \"deposit slip\"],\n  [[\"bank\", \"slip\"], \"bank slip\"],\n  [[\"transfer\", \"slip\"], \"bank slip\"],\n  [[\"remittance\", \"slip\"], \"bank slip\"],\n  [[\"tenancy\", \"contract\"], \"tenancy contract\"],\n  [[\"tenancy\", \"contracts\"], \"tenancy contract\"],\n  [[\"ejari\"], \"tenancy contract\"],\n  [[\"contract\"], \"contract\"],\n  [[\"contracts\"], \"contract\"],\n  [[\"agreement\"], \"agreement\"],\n  [[\"agreements\"], \"agreement\"],\n  [[\"lease\"], \"lease\"],\n  [[\"leases\"], \"lease\"],\n  [[\"form\"], \"form\"],\n  [[\"forms\"], \"form\"],\n  [[\"shipping\", \"label\"], \"shipping label\"],\n  [[\"shipping\", \"labels\"], \"shipping label\"],\n  [[\"label\"], \"label\"],\n  [[\"labels\"], \"label\"],\n  [[\"menu\"], \"menu\"],\n  [[\"menus\"], \"menu\"],\n  [[\"gift\", \"card\"], \"gift card\"],\n  [[\"gift\", \"cards\"], \"gift card\"],\n  [[\"voucher\"], \"voucher\"],\n  [[\"vouchers\"], \"voucher\"],\n  [[\"coupon\"], \"coupon\"],\n  [[\"coupons\"], \"coupon\"],\n  [[\"warranty\"], \"warranty card\"],\n  [[\"warranty\", \"card\"], \"warranty card\"],\n  [[\"warranty\", \"cards\"], \"warranty card\"],\n  [[\"report\"], \"report\"],\n  [[\"reports\"], \"report\"],\n  [[\"letter\"], \"letter\"],\n  [[\"letters\"], \"letter\"],\n  [[\"manifest\"], \"manifest\"],\n  [[\"manifests\"], \"manifest\"],\n  [[\"card\"], \"card\"],\n  [[\"cards\"], \"card\"],\n];\n", "/**\n * What the scanner calls the document: \"Point the camera at the invoice\".\n *\n * The rule is the one ReceViz itself uses (backend doctypes/capture.py), and\n * the Android and iOS SDKs run it too, all against\n * shared/receviz-fixtures/capture-nouns.json: split the document type's key\n * (then its name) into words \u2014 camelCase is split, anything but a-z and 0-9\n * separates \u2014 and take the phrase that ends furthest right, the longer one on a\n * tie. `payment_receipt` is a receipt, `bill_of_lading` a bill of lading.\n *\n * The scanner uses this at once, so it never waits on the network to say\n * something sensible, and then switches to the document type's own noun when\n * the API has one (`capture.noun`, which a developer can set in the console).\n */\nimport { FALLBACK_NOUN, NOUN_PHRASES } from \"./nouns.generated.ts\";\n\nexport function nounWords(text: string | null | undefined): string[] {\n  const spaced = (text ?? \"\").replace(/([a-z0-9])([A-Z])/g, \"$1 $2\");\n  return spaced\n    .toLowerCase()\n    .split(/[^a-z0-9]+/)\n    .filter(Boolean);\n}\n\nexport function matchNoun(tokens: readonly string[]): string | null {\n  let best: { end: number; length: number; noun: string } | null = null;\n  for (let i = 0; i < tokens.length; i++) {\n    for (const [phrase, noun] of NOUN_PHRASES) {\n      const n = phrase.length;\n      if (i + n > tokens.length) continue;\n      let same = true;\n      for (let j = 0; j < n; j++) {\n        if (tokens[i + j] !== phrase[j]) {\n          same = false;\n          break;\n        }\n      }\n      if (!same) continue;\n      const end = i + n;\n      if (!best || end > best.end || (end === best.end && n > best.length)) best = { end, length: n, noun };\n    }\n  }\n  return best ? best.noun : null;\n}\n\n/** A noun someone chose, tidied; null when there is none. */\nexport function cleanNoun(value: string | null | undefined): string | null {\n  const text = (value ?? \"\").trim().replace(/\\s+/g, \" \").slice(0, 40);\n  return text || null;\n}\n\n/** The noun for a document type, from its key and then its name. */\nexport function nounFor(documentType?: string | null, name?: string | null): string {\n  for (const text of [documentType, name]) {\n    const found = matchNoun(nounWords(text));\n    if (found) return found;\n  }\n  return FALLBACK_NOUN;\n}\n\nconst A_BEFORE = [\"uni\", \"use\", \"usu\", \"uti\", \"eu\", \"one\", \"once\", \"ubiq\"];\nconst AN_BEFORE = [\"hour\", \"honest\", \"honor\", \"honour\", \"heir\"];\n\n/** \"a receipt\", \"an invoice\", \"an ID card\", \"a utility bill\": the article goes by sound. */\nexport function withArticle(noun: string): string {\n  const word = noun.trim().toLowerCase();\n  const article = A_BEFORE.some((p) => word.startsWith(p))\n    ? \"a\"\n    : AN_BEFORE.some((p) => word.startsWith(p))\n      ? \"an\"\n      : /^[aeiou]/.test(word)\n        ? \"an\"\n        : \"a\";\n  return `${article} ${noun.trim()}`;\n}\n", "/**\n * A ready-made scanner: camera, guidance, auto-capture, review, upload.\n *\n *   const { document, extraction } = await openScanner({ client, documentType: \"invoice\" });\n *\n * It opens over the page (or inside `container`), guides the person until the\n * picture is good, lets them keep it or retake it, and \u2014 when given a client \u2014\n * uploads that one picture and resolves with ReceViz's extraction. No frame is\n * uploaded while the camera runs. Without a camera (refused, missing, or an\n * http page) it offers a file instead.\n *\n * The markup lives in a shadow root, so the page's styles cannot reach it and\n * its styles cannot leak. Theme it with CSS custom properties on the host:\n * --rv-font, --rv-accent, --rv-highlight, --rv-stage.\n */\nimport type { Client } from \"./client.ts\";\nimport { DocumentCamera, type CameraState, type CapturedDocument } from \"./camera.ts\";\nimport { NO_QUALITY } from \"./engine/quality.ts\";\nimport type { Quad } from \"./engine/types.ts\";\nimport { ReceVizError } from \"./errors.ts\";\nimport { normalizeImage } from \"./image.ts\";\nimport { cleanNoun, nounFor, withArticle } from \"./nouns.ts\";\nimport type { Extraction, ExtractOptions, Mode } from \"./types.ts\";\n\nexport type ScannerOptions = {\n  /** When given, the picture is uploaded and the extraction returned. */\n  client?: Client;\n  documentType?: string;\n  mode?: Mode;\n  /** Anything else for POST /v1/extractions. */\n  extract?: Omit<ExtractOptions, \"documentType\" | \"mode\" | \"signal\">;\n  /**\n   * What to call the document in guidance: \"receipt\", \"invoice\"\u2026 By default the\n   * scanner works it out from `documentType` at once (\"payment_receipt\" \u2192\n   * \"receipt\"), then uses the document type's own noun when the client can\n   * read it (GET /v1/document-types, `capture.noun`).\n   */\n  noun?: string;\n  /** The dialog's heading (default \"Scan a receipt\", \"Scan an invoice\"\u2026). */\n  title?: string;\n  autoCapture?: boolean;\n  cleanUp?: boolean;\n  /** Offer \"Choose a file\" beside the shutter (default true). */\n  allowFileUpload?: boolean;\n  /** Render inside this element instead of over the whole page. */\n  container?: HTMLElement;\n  signal?: AbortSignal;\n  onGuidance?: (text: string) => void;\n};\n\nexport type ScanResult = {\n  document: CapturedDocument;\n  /** Null when no client was given: upload `document.blob` yourself. */\n  extraction: Extraction | null;\n};\n\nconst ACCEPT = \"image/jpeg,image/png,image/heic,image/heif,image/webp,application/pdf\";\n\nconst STYLES = `\n:host { all: initial; }\n* { box-sizing: border-box; }\n.root {\n  --accent: var(--rv-accent, #2B4EEA);\n  --highlight: var(--rv-highlight, #FFD84A);\n  --stage: var(--rv-stage, #16213E);\n  font-family: var(--rv-font, system-ui, -apple-system, \"Segoe UI\", Roboto, sans-serif);\n  font-size: 15px;\n  line-height: 1.4;\n  color: #fff;\n}\n.backdrop { position: fixed; inset: 0; z-index: 2147483000; background: rgba(22, 33, 62, 0.62);\n  display: flex; align-items: center; justify-content: center; }\n.inline { position: relative; width: 100%; height: 100%; min-height: 420px; }\n.dialog { position: relative; display: flex; flex-direction: column; background: var(--stage);\n  width: 100%; height: 100%; overflow: hidden; }\n.backdrop .dialog { width: 100vw; height: 100dvh; }\n@media (min-width: 720px) {\n  .backdrop .dialog { width: min(760px, 92vw); height: min(800px, 92vh); border-radius: 10px; }\n}\nheader { display: flex; align-items: center; gap: 12px; padding: 12px 12px 12px 20px; }\nh2 { margin: 0; flex: 1; font-size: 16px; font-weight: 600; letter-spacing: 0; }\nbutton { font: inherit; color: inherit; cursor: pointer; border: 0; background: none; }\nbutton:focus-visible { outline: 3px solid var(--highlight); outline-offset: 2px; }\n.icon { width: 40px; height: 40px; border-radius: 6px; display: grid; place-items: center; }\n.icon:hover { background: rgba(255, 255, 255, 0.1); }\n.stage { position: relative; flex: 1; min-height: 0; background: #000; overflow: hidden; }\nvideo, canvas.outline { position: absolute; inset: 0; width: 100%; height: 100%; }\nvideo { object-fit: cover; }\ncanvas.outline { pointer-events: none; }\n.guidance { position: absolute; left: 50%; bottom: 16px; transform: translateX(-50%); margin: 0;\n  max-width: calc(100% - 32px); padding: 8px 16px; border-radius: 999px; text-align: center;\n  background: rgba(22, 33, 62, 0.6); -webkit-backdrop-filter: blur(12px); backdrop-filter: blur(12px); }\n.message, .review { position: absolute; inset: 0; display: flex; flex-direction: column; gap: 16px;\n  align-items: center; justify-content: center; padding: 24px; text-align: center; background: var(--stage); }\n.message p { margin: 0; max-width: 34ch; }\n.review img { max-width: 100%; max-height: 100%; object-fit: contain; background: #fff; border-radius: 4px; }\n.review .file { padding: 28px 32px; border-radius: 10px; background: rgba(255, 255, 255, 0.08); }\n.controls { display: flex; align-items: center; justify-content: center; gap: 16px; padding: 16px 20px 20px; min-height: 104px; }\n.controls > * { flex: 1; }\n.controls > .shutter { flex: 0 0 auto; }\n.shutter { width: 68px; height: 68px; border-radius: 50%; border: 4px solid #fff; padding: 4px; }\n.shutter span { display: block; width: 100%; height: 100%; border-radius: 50%; background: #fff; }\n.shutter:disabled { opacity: 0.4; cursor: default; }\n.secondary { padding: 10px 16px; border-radius: 6px; background: rgba(255, 255, 255, 0.1); min-height: 44px; }\n.secondary:hover { background: rgba(255, 255, 255, 0.16); }\n.primary { padding: 10px 18px; border-radius: 6px; background: var(--accent); min-height: 44px; font-weight: 600; }\n.primary:hover { filter: brightness(1.08); }\n.left { text-align: left; } .right { display: flex; justify-content: flex-end; }\n.status { display: flex; flex-direction: column; gap: 10px; align-items: stretch; width: min(320px, 100%); }\n.bar { height: 3px; border-radius: 2px; background: rgba(255, 255, 255, 0.16); overflow: hidden; }\n.bar span { display: block; width: 30%; height: 100%; background: var(--highlight); animation: slide 1.2s linear infinite; }\n@keyframes slide { from { transform: translateX(-100%); } to { transform: translateX(333%); } }\n.error { color: #FFB4B4; }\n.flash { position: absolute; inset: 0; background: #fff; opacity: 0; pointer-events: none; transition: opacity 160ms ease-out; }\n.flash.on { opacity: 0.7; transition: none; }\n[hidden] { display: none !important; }\n@media (prefers-reduced-motion: reduce) {\n  .bar span { animation: none; width: 100%; opacity: 0.6; }\n  .flash { display: none; }\n}\n`;\n\n/** Built with DOM calls, not innerHTML: pages that enforce Trusted Types allow it. */\nfunction closeIcon(): SVGSVGElement {\n  const ns = \"http://www.w3.org/2000/svg\";\n  const svg = document.createElementNS(ns, \"svg\");\n  for (const [k, v] of Object.entries({ width: \"20\", height: \"20\", viewBox: \"0 0 20 20\", \"aria-hidden\": \"true\" })) {\n    svg.setAttribute(k, v);\n  }\n  const path = document.createElementNS(ns, \"path\");\n  for (const [k, v] of Object.entries({\n    d: \"M5 5l10 10M15 5L5 15\", stroke: \"currentColor\", \"stroke-width\": \"2\", \"stroke-linecap\": \"round\",\n  })) {\n    path.setAttribute(k, v);\n  }\n  svg.append(path);\n  return svg;\n}\n\ntype Elements = {\n  dialog: HTMLElement;\n  title: HTMLElement;\n  close: HTMLButtonElement;\n  stage: HTMLElement;\n  video: HTMLVideoElement;\n  outline: HTMLCanvasElement;\n  guidance: HTMLElement;\n  flash: HTMLElement;\n  message: HTMLElement;\n  messageText: HTMLElement;\n  review: HTMLElement;\n  controls: HTMLElement;\n  shutter: HTMLButtonElement;\n  chooseFile: HTMLButtonElement;\n  reviewControls: HTMLElement;\n  retake: HTMLButtonElement;\n  use: HTMLButtonElement;\n  input: HTMLInputElement;\n};\n\nfunction el<K extends keyof HTMLElementTagNameMap>(\n  tag: K,\n  attrs: Record<string, string> = {},\n  text?: string\n): HTMLElementTagNameMap[K] {\n  const node = document.createElement(tag);\n  for (const [k, v] of Object.entries(attrs)) node.setAttribute(k, v);\n  if (text !== undefined) node.textContent = text;\n  return node;\n}\n\nfunction build(shadow: ShadowRoot, options: ScannerOptions, inline: boolean, noun: string): Elements {\n  const style = el(\"style\");\n  style.textContent = STYLES;\n  const root = el(\"div\", { class: `root ${inline ? \"inline\" : \"backdrop\"}` });\n  const dialog = el(\"div\", inline\n    ? { class: \"dialog\", role: \"region\", \"aria-labelledby\": \"rv-title\" }\n    : { class: \"dialog\", role: \"dialog\", \"aria-modal\": \"true\", \"aria-labelledby\": \"rv-title\" });\n  const header = el(\"header\");\n  const title = el(\"h2\", { id: \"rv-title\" }, options.title ?? `Scan ${withArticle(noun)}`);\n  const close = el(\"button\", { class: \"icon\", type: \"button\", \"aria-label\": \"Close the scanner\" });\n  close.append(closeIcon());\n  header.append(title, close);\n\n  const stage = el(\"div\", { class: \"stage\" });\n  const video = el(\"video\", { \"aria-hidden\": \"true\" });\n  const outline = el(\"canvas\", { class: \"outline\", \"aria-hidden\": \"true\" });\n  const guidance = el(\"p\", { class: \"guidance\", \"aria-live\": \"polite\" }, \"Starting camera\u2026\");\n  const flash = el(\"div\", { class: \"flash\", \"aria-hidden\": \"true\" });\n  const message = el(\"div\", { class: \"message\", hidden: \"\" });\n  const messageText = el(\"p\");\n  message.append(messageText);\n  const review = el(\"div\", { class: \"review\", hidden: \"\" });\n  stage.append(video, outline, flash, guidance, message, review);\n\n  const allowFiles = options.allowFileUpload !== false;\n  const controls = el(\"div\", { class: \"controls\" });\n  const left = el(\"div\", { class: \"left\" });\n  const chooseFile = el(\"button\", { class: \"secondary\", type: \"button\" }, \"Choose a file\");\n  if (allowFiles) left.append(chooseFile);\n  const shutter = el(\"button\", { class: \"shutter\", type: \"button\", \"aria-label\": \"Take the photo\" });\n  shutter.append(el(\"span\"));\n  controls.append(left, shutter, el(\"div\", { class: \"right\" }));\n\n  const reviewControls = el(\"div\", { class: \"controls\", hidden: \"\" });\n  const retake = el(\"button\", { class: \"secondary\", type: \"button\" }, \"Retake\");\n  const use = el(\"button\", { class: \"primary\", type: \"button\" }, options.client ? \"Read document\" : \"Use this scan\");\n  const reviewLeft = el(\"div\", { class: \"left\" });\n  reviewLeft.append(retake);\n  const reviewRight = el(\"div\", { class: \"right\" });\n  reviewRight.append(use);\n  reviewControls.append(reviewLeft, reviewRight);\n\n  const input = el(\"input\", { type: \"file\", accept: ACCEPT, hidden: \"\" });\n  dialog.append(header, stage, controls, reviewControls, input);\n  root.append(dialog);\n  shadow.append(style, root);\n  return {\n    dialog, title, close, stage, video, outline, guidance, flash, message, messageText, review,\n    controls, shutter, chooseFile, reviewControls, retake, use, input,\n  };\n}\n\n/** Where a normalised frame point lands in the stage, with object-fit: cover. */\nfunction coverMapper(video: HTMLVideoElement, boxW: number, boxH: number) {\n  const vw = video.videoWidth || boxW;\n  const vh = video.videoHeight || boxH;\n  const scale = Math.max(boxW / vw, boxH / vh);\n  const dx = (boxW - vw * scale) / 2;\n  const dy = (boxH - vh * scale) / 2;\n  return (p: { x: number; y: number }) => ({ x: p.x * vw * scale + dx, y: p.y * vh * scale + dy });\n}\n\n/** The outline as four corner brackets \u2014 the ReceViz detection mark. */\nfunction drawOutline(canvas: HTMLCanvasElement, video: HTMLVideoElement, quad: Quad | null, ready: boolean, highlight: string): void {\n  const ratio = window.devicePixelRatio || 1;\n  const w = canvas.clientWidth;\n  const h = canvas.clientHeight;\n  if (canvas.width !== Math.round(w * ratio) || canvas.height !== Math.round(h * ratio)) {\n    canvas.width = Math.round(w * ratio);\n    canvas.height = Math.round(h * ratio);\n  }\n  const ctx = canvas.getContext(\"2d\");\n  if (!ctx) return;\n  ctx.setTransform(ratio, 0, 0, ratio, 0, 0);\n  ctx.clearRect(0, 0, w, h);\n  if (!quad) return;\n  const map = coverMapper(video, w, h);\n  const pts = quad.map(map);\n  if (ready) {\n    ctx.beginPath();\n    pts.forEach((p, i) => (i ? ctx.lineTo(p.x, p.y) : ctx.moveTo(p.x, p.y)));\n    ctx.closePath();\n    ctx.globalAlpha = 0.12;\n    ctx.fillStyle = highlight;\n    ctx.fill();\n    ctx.globalAlpha = 1;\n  }\n  ctx.strokeStyle = ready ? highlight : \"rgba(255, 255, 255, 0.9)\";\n  ctx.lineWidth = 4;\n  ctx.lineCap = \"round\";\n  ctx.lineJoin = \"round\";\n  for (let i = 0; i < 4; i++) {\n    const p = pts[i];\n    const next = pts[(i + 1) % 4];\n    const prev = pts[(i + 3) % 4];\n    const arm = (to: { x: number; y: number }) => {\n      const len = Math.hypot(to.x - p.x, to.y - p.y);\n      const k = len ? Math.min(0.2 * len, 36) / len : 0;\n      return { x: p.x + (to.x - p.x) * k, y: p.y + (to.y - p.y) * k };\n    };\n    const a = arm(prev);\n    const b = arm(next);\n    ctx.beginPath();\n    ctx.moveTo(a.x, a.y);\n    ctx.lineTo(p.x, p.y);\n    ctx.lineTo(b.x, b.y);\n    ctx.stroke();\n  }\n}\n\nfunction focusables(dialog: HTMLElement): HTMLElement[] {\n  return Array.from(dialog.querySelectorAll<HTMLElement>(\"button, [href], input:not([hidden]), [tabindex]\")).filter(\n    (node) => !node.hasAttribute(\"disabled\") && node.offsetParent !== null\n  );\n}\n\n/** Open the scanner. Rejects with a \"cancelled\" ReceVizError when it is closed. */\nexport function openScanner(options: ScannerOptions = {}): Promise<ScanResult> {\n  if (typeof document === \"undefined\") {\n    return Promise.reject(new ReceVizError(\"configuration_error\", \"no_document\", \"The scanner needs a browser page.\"));\n  }\n  const inline = !!options.container;\n  const host = el(\"div\", { \"data-receviz-scanner\": \"\" });\n  const shadow = host.attachShadow({ mode: \"open\" });\n  // The word guidance uses: chosen, else worked out from the document type\n  // now, and replaced below by the type's own word if the API has one.\n  const chosen = cleanNoun(options.noun);\n  let noun = chosen ?? nounFor(options.documentType);\n  const ui = build(shadow, options, inline, noun);\n  const previousFocus = document.activeElement as HTMLElement | null;\n  const previousOverflow = document.documentElement.style.overflow;\n  (options.container ?? document.body).append(host);\n  if (!inline) document.documentElement.style.overflow = \"hidden\";\n  const highlight = getComputedStyle(host).getPropertyValue(\"--rv-highlight\").trim() || \"#FFD84A\";\n\n  return new Promise<ScanResult>((resolve, reject) => {\n    let current: CapturedDocument | null = null;\n    let previewUrl: string | null = null;\n    let upload: AbortController | null = null;\n    let lastGuidance = \"\";\n    let finished = false;\n    /** Why the camera is not running, when it is not: \"Retake\" goes back to this. */\n    let cameraProblem: string | null = null;\n\n    const camera = new DocumentCamera({\n      video: ui.video,\n      autoCapture: options.autoCapture,\n      cleanUp: options.cleanUp,\n      noun,\n      onUpdate: (state: CameraState) => {\n        const snap = state.snapshot;\n        drawOutline(ui.outline, ui.video, snap.outline, snap.quality.capturable, highlight);\n        if (state.guidance !== lastGuidance) {\n          lastGuidance = state.guidance;\n          ui.guidance.textContent = state.guidance;\n          options.onGuidance?.(state.guidance);\n        }\n      },\n      onCapture: (doc) => showReview(doc),\n      onError: (error) => {\n        ui.guidance.textContent = error.message;\n      },\n    });\n\n    if (!chosen && options.client && options.documentType) {\n      void options.client.captureNoun(options.documentType).then((own) => {\n        const better = cleanNoun(own);\n        if (!better || finished || better === noun) return;\n        noun = better;\n        camera.setNoun(better);\n        if (!options.title) ui.title.textContent = `Scan ${withArticle(better)}`;\n      });\n    }\n\n    const finish = (outcome: { result?: ScanResult; error?: ReceVizError }) => {\n      if (finished) return;\n      finished = true;\n      upload?.abort();\n      camera.stop();\n      if (previewUrl) URL.revokeObjectURL(previewUrl);\n      document.removeEventListener(\"keydown\", onKey, true);\n      options.signal?.removeEventListener(\"abort\", onAbort);\n      host.remove();\n      if (!inline) document.documentElement.style.overflow = previousOverflow;\n      previousFocus?.focus?.();\n      if (outcome.result) resolve(outcome.result);\n      else reject(outcome.error ?? ReceVizError.cancelled());\n    };\n\n    const onAbort = () => finish({ error: ReceVizError.cancelled() });\n    const onKey = (event: KeyboardEvent) => {\n      // Inline, the scanner only answers keys while focus is inside it.\n      if (inline && document.activeElement !== host) return;\n      if (event.key === \"Escape\") {\n        event.preventDefault();\n        finish({ error: ReceVizError.cancelled() });\n      } else if (event.key === \"Tab\" && !inline) {\n        const items = focusables(ui.dialog);\n        if (!items.length) return;\n        const active = shadow.activeElement as HTMLElement | null;\n        const index = active ? items.indexOf(active) : -1;\n        const next = event.shiftKey ? (index <= 0 ? items.length - 1 : index - 1) : (index + 1) % items.length;\n        event.preventDefault();\n        items[next].focus();\n      }\n    };\n\n    function showMessage(text: string, withFile: boolean) {\n      ui.messageText.textContent = text;\n      ui.message.replaceChildren(ui.messageText);\n      if (withFile && options.allowFileUpload !== false) {\n        const button = el(\"button\", { class: \"primary\", type: \"button\" }, \"Choose a file\");\n        button.addEventListener(\"click\", () => ui.input.click());\n        ui.message.append(button);\n        button.focus();\n      }\n      ui.message.hidden = false;\n      ui.guidance.hidden = true;\n      ui.shutter.disabled = true;\n    }\n\n    function showReview(doc: CapturedDocument) {\n      current = doc;\n      ui.flash.classList.add(\"on\");\n      requestAnimationFrame(() => ui.flash.classList.remove(\"on\"));\n      if (previewUrl) URL.revokeObjectURL(previewUrl);\n      previewUrl = null;\n      if (doc.blob.type === \"application/pdf\" || !doc.width) {\n        const name = (doc.blob as File).name || \"Your document\";\n        ui.review.replaceChildren(el(\"p\", { class: \"file\" }, name));\n      } else {\n        previewUrl = URL.createObjectURL(doc.blob);\n        ui.review.replaceChildren(el(\"img\", { src: previewUrl, alt: `The captured ${noun}` }));\n      }\n      ui.review.hidden = false;\n      ui.message.hidden = true;\n      ui.guidance.hidden = true;\n      ui.controls.hidden = true;\n      ui.reviewControls.hidden = false;\n      ui.retake.disabled = false;\n      ui.use.disabled = false;\n      ui.use.focus();\n    }\n\n    function backToCamera() {\n      current = null;\n      ui.review.hidden = true;\n      ui.reviewControls.hidden = true;\n      ui.controls.hidden = false;\n      if (cameraProblem) {\n        showMessage(cameraProblem, true);\n        return;\n      }\n      ui.guidance.hidden = false;\n      ui.shutter.focus();\n      camera.retake();\n    }\n\n    async function useScan() {\n      if (!current) return;\n      const doc = current;\n      if (!options.client) {\n        finish({ result: { document: doc, extraction: null } });\n        return;\n      }\n      ui.use.disabled = true;\n      ui.retake.disabled = true;\n      const status = el(\"div\", { class: \"status\", role: \"status\" });\n      const bar = el(\"div\", { class: \"bar\" });\n      bar.append(el(\"span\"));\n      status.append(el(\"p\", {}, `Reading the ${noun}\u2026`), bar);\n      ui.review.replaceChildren(status);\n      upload = new AbortController();\n      try {\n        const extraction = await options.client.extract(doc.blob, {\n          ...options.extract,\n          documentType: options.documentType,\n          mode: options.mode,\n          signal: upload.signal,\n        });\n        finish({ result: { document: doc, extraction } });\n      } catch (err) {\n        if (finished) return;\n        const error = err instanceof ReceVizError ? err : new ReceVizError(\"api_error\", \"unexpected\", String(err));\n        if (error.type === \"cancelled\") return;\n        const text = el(\"p\", { class: \"error\" }, error.message);\n        const again = el(\"button\", { class: \"primary\", type: \"button\" }, \"Try again\");\n        again.addEventListener(\"click\", () => {\n          ui.review.replaceChildren();\n          void useScan();\n        });\n        ui.review.replaceChildren(text, again);\n        ui.retake.disabled = false;\n        again.focus();\n      }\n    }\n\n    ui.close.addEventListener(\"click\", () => finish({ error: ReceVizError.cancelled() }));\n    ui.shutter.addEventListener(\"click\", () => void camera.capture());\n    ui.chooseFile.addEventListener(\"click\", () => ui.input.click());\n    ui.retake.addEventListener(\"click\", backToCamera);\n    ui.use.addEventListener(\"click\", () => void useScan());\n    ui.input.addEventListener(\"change\", async () => {\n      const file = ui.input.files?.[0];\n      ui.input.value = \"\";\n      if (!file) return;\n      try {\n        const normalized = await normalizeImage(file);\n        const blob = normalized.blob === file ? file : new File([normalized.blob], file.name.replace(/\\.\\w+$/, \".jpg\"), { type: \"image/jpeg\" });\n        showReview({\n          blob,\n          width: normalized.width,\n          height: normalized.height,\n          cropped: false,\n          quad: null,\n          quality: NO_QUALITY,\n          manual: true,\n        });\n      } catch {\n        showMessage(\"That file could not be opened. Choose a JPEG, PNG, HEIC or PDF.\", true);\n      }\n    });\n    document.addEventListener(\"keydown\", onKey, true);\n    if (options.signal?.aborted) {\n      finish({ error: ReceVizError.cancelled() });\n      return;\n    }\n    options.signal?.addEventListener(\"abort\", onAbort);\n    ui.shutter.focus();\n\n    camera.start().catch((err: unknown) => {\n      if (finished) return;\n      const error = err instanceof ReceVizError ? err : new ReceVizError(\"camera_error\", \"camera_unavailable\", \"The camera could not be started.\");\n      cameraProblem = error.message;\n      showMessage(error.message, true);\n    });\n  });\n}\n"],
  "mappings": ";;;;;;AAqBO,IAAM,eAAN,MAAM,sBAAqB,MAAM;AAAA,EAQtC,YACE,MACA,MACA,SACA,QAAkH,CAAC,GACnH;AACA,UAAM,OAAO;AAbf,wBAAS;AACT,wBAAS;AACT,wBAAS;AACT,wBAAS;AACT,wBAAS;AACT,wBAAS;AASP,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK,OAAO;AACZ,SAAK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