@exige/web-scanner-sdk 0.2.15 → 0.2.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -212,7 +212,7 @@ await setLicenseKey(licenseKey)
212
212
  </ScannerProvider>
213
213
  ```
214
214
 
215
- `useScanner()` reads the session inside the provider. `useScannerRef()` gives the parent an imperative handle, passed as `apiRef`, the same idea as MUI's `useGridApiRef`. The camera covers the viewport, respects safe areas, shows finder/permission/error states, and keeps the existing auto-capture policies. It requests an ideal 4K rear-camera stream, except Android Chrome where preview negotiation prefers portrait 1080×1920 and caps only `height.max` at 1920. Pairing the same 1920 max on both axes collapsed to a 1920×1920 square stream that center-cropped tall receipts. Capture stills stay at the negotiated stream size. The overlay exposes actual track settings, continuously mirrors the last non-black frame, and synchronously copies the unscaled live frame before shutter/flash/track teardown. Capture never calls `ImageCapture.takePhoto()`, which returns black stills on WebKit: the live copy is used when it has visible pixels, the mirrored frame otherwise, and a genuinely blank capture fails loudly instead of exporting black pixels. Render `ScannerDiagnostics` for a live diagnostics panel with engine/browser, video and track state, luminance, and the chosen capture path; **Copy report** pastes a shutter-time dump for support. Pass `theme` to `ScannerFrame` to recolor the camera. `primaryColorHex` replaces the yellowish-green accents (`#c8ff45`). `seekingColorHex` and `detectingColorHex` are the waiting box colors (both `#ef6a5b` unless set apart), `unstableColorHex` is `#ffbe40`, `readyColorHex` is `#8af25a`, and `capturedColorHex` is `#ffffff`. Omit `theme` or any field to keep that default. The [React camera guide](site/guide/react-camera-overlay.md#theme) lists what each field paints. The demo source screen chooses Default, Ocean, Violet, or Signal before the camera starts and passes that palette as `theme` on `ScannerFrame`. Capture results include the displayed quad and its bounded-analysis dimensions; use `mapDocumentCornersToFrame()` plus `cropDocument()` so the final crop matches what was on screen. The framework-free imperative APIs remain available from the root package.
215
+ `useScanner()` reads the session inside the provider. `useScannerRef()` gives the parent an imperative handle, passed as `apiRef`, the same idea as MUI's `useGridApiRef`. The camera covers the viewport, respects safe areas, shows finder/permission/error states, and keeps the existing auto-capture policies. It requests an ideal 4K rear-camera stream, except Android Chrome where preview negotiation prefers portrait 1080×1920 and caps only `height.max` at 1920. Pairing the same 1920 max on both axes collapsed to a 1920×1920 square stream that center-cropped tall receipts. Chrome can still grant landscape 1920×1080 and display it upright. iOS reports portrait dimensions for the same pose, so only Android was analyzing a 1280×720 frame. The finder now analyzes the viewfinder cover crop (about 608×1080 on a 9:16 phone) and `mapDocumentCornersToFrame()` maps that quad back onto the raw frame. The preview is unchanged: `object-fit: cover`, no extra rotation. Capture stills stay at the negotiated stream size. The overlay exposes actual track settings, continuously mirrors the last non-black frame, and synchronously copies the unscaled live frame before shutter/flash/track teardown. Capture never calls `ImageCapture.takePhoto()`, which returns black stills on WebKit: the live copy is used when it has visible pixels, the mirrored frame otherwise, and a genuinely blank capture fails loudly instead of exporting black pixels. Render `ScannerDiagnostics` for a live diagnostics panel with engine/browser, video and track state, luminance, and the chosen capture path; **Copy report** pastes a shutter-time dump for support. Pass `theme` to `ScannerFrame` to recolor the camera. `primaryColorHex` replaces the yellowish-green accents (`#c8ff45`). `seekingColorHex` and `detectingColorHex` are the waiting box colors (both `#ef6a5b` unless set apart), `unstableColorHex` is `#ffbe40`, `readyColorHex` is `#8af25a`, and `capturedColorHex` is `#ffffff`. Omit `theme` or any field to keep that default. The [React camera guide](site/guide/react-camera-overlay.md#theme) lists what each field paints. The demo source screen chooses Default, Ocean, Violet, or Signal before the camera starts and passes that palette as `theme` on `ScannerFrame`. Capture results include the displayed quad and its bounded-analysis dimensions; use `mapDocumentCornersToFrame()` plus `cropDocument()` so the final crop matches what was on screen. The framework-free imperative APIs remain available from the root package.
216
216
 
217
217
  ## Run the demo
218
218
 
@@ -850,13 +850,59 @@ async function Pe(t, n = {}) {
850
850
  };
851
851
  }
852
852
  //#endregion
853
+ //#region src/sdk/preview-frame.ts
854
+ function Fe(e) {
855
+ let t = e.parentElement?.getBoundingClientRect();
856
+ return t && t.width > 0 && t.height > 0 ? t : e.getBoundingClientRect();
857
+ }
858
+ function Ie(e, t, n, r) {
859
+ let i = Math.max(1, e), a = Math.max(1, t);
860
+ if (n <= 0 || r <= 0) return {
861
+ sx: 0,
862
+ sy: 0,
863
+ sw: i,
864
+ sh: a
865
+ };
866
+ let o = i / a, s = n / r;
867
+ if (o > s) {
868
+ let e = a * s;
869
+ return {
870
+ sx: (i - e) / 2,
871
+ sy: 0,
872
+ sw: e,
873
+ sh: a
874
+ };
875
+ }
876
+ let c = i / s;
877
+ return {
878
+ sx: 0,
879
+ sy: (a - c) / 2,
880
+ sw: i,
881
+ sh: c
882
+ };
883
+ }
884
+ function Le(e, t, n, r, i) {
885
+ let a = Ie(e, t, n, r);
886
+ return {
887
+ crop: a,
888
+ size: Me(a.sw, a.sh, i)
889
+ };
890
+ }
891
+ function Re(e, n, r, i, a, o) {
892
+ let { crop: s, size: c } = Le(n, r, i, a, o), l = document.createElement("canvas");
893
+ l.width = c.width, l.height = c.height;
894
+ let u = l.getContext("2d");
895
+ if (!u) throw t();
896
+ return u.drawImage(e, s.sx, s.sy, s.sw, s.sh, 0, 0, c.width, c.height), l;
897
+ }
898
+ //#endregion
853
899
  //#region src/sdk/lighting.ts
854
- function Fe(e, t) {
900
+ function ze(e, t) {
855
901
  if (!e.length) return 0;
856
902
  let n = [...e].sort((e, t) => e - t);
857
903
  return n[Math.min(n.length - 1, Math.floor(n.length * t))];
858
904
  }
859
- function Ie(e, t, n, r = 12) {
905
+ function Be(e, t, n, r = 12) {
860
906
  if (!t || !n || e.length < t * n) return {
861
907
  strong: !1,
862
908
  strength: 0,
@@ -879,7 +925,7 @@ function Ie(e, t, n, r = 12) {
879
925
  });
880
926
  }
881
927
  }
882
- let s = Fe(o.map((e) => e.mean), .8), c = o.map((e) => s - e.mean >= 24 && e.mean >= 35), l = new Uint8Array(o.length), u = [];
928
+ let s = ze(o.map((e) => e.mean), .8), c = o.map((e) => s - e.mean >= 24 && e.mean >= 35), l = new Uint8Array(o.length), u = [];
883
929
  for (let e = 0; e < o.length; e += 1) {
884
930
  if (!c[e] || l[e]) continue;
885
931
  let t = [], n = [e];
@@ -927,7 +973,7 @@ function Ie(e, t, n, r = 12) {
927
973
  }
928
974
  return d;
929
975
  }
930
- function Le(e, t, n, r = Math.max(12, Math.round(Math.max(t, n) / 32))) {
976
+ function Ve(e, t, n, r = Math.max(12, Math.round(Math.max(t, n) / 32))) {
931
977
  let i = t + 1, a = new Uint32Array((t + 1) * (n + 1));
932
978
  for (let r = 1; r <= n; r += 1) {
933
979
  let n = 0;
@@ -943,7 +989,7 @@ function Le(e, t, n, r = Math.max(12, Math.round(Math.max(t, n) / 32))) {
943
989
  }
944
990
  return o;
945
991
  }
946
- function Re(e, t, n) {
992
+ function He(e, t, n) {
947
993
  let r = [
948
994
  e.topLeft,
949
995
  e.topRight,
@@ -957,8 +1003,8 @@ function Re(e, t, n) {
957
1003
  height: s - a
958
1004
  };
959
1005
  }
960
- function ze(e, t) {
961
- let n = Re(t, e.width, e.height);
1006
+ function Ue(e, t) {
1007
+ let n = He(t, e.width, e.height);
962
1008
  if (n.width <= 0 || n.height <= 0) return {
963
1009
  strong: !1,
964
1010
  strength: 0,
@@ -977,18 +1023,18 @@ function ze(e, t) {
977
1023
  i.drawImage(e, n.left, n.top, n.width, n.height, 0, 0, r.width, r.height);
978
1024
  let a = i.getImageData(0, 0, r.width, r.height).data, o = new Uint8Array(r.width * r.height);
979
1025
  for (let e = 0, t = 0; e < o.length; e += 1, t += 4) o[e] = Math.round(a[t] * .299 + a[t + 1] * .587 + a[t + 2] * .114);
980
- return Ie(o, r.width, r.height);
1026
+ return Be(o, r.width, r.height);
981
1027
  }
982
1028
  //#endregion
983
1029
  //#region src/sdk/finder.ts
984
- function Be(e, t) {
1030
+ function We(e, t) {
985
1031
  return t.castShadow && (e.reason === "hold-still" || e.reason === "ready") ? t.hint ?? e.hint : e.hint;
986
1032
  }
987
- async function Ve(e, t) {
1033
+ async function Ge(e, t) {
988
1034
  let n = await e();
989
1035
  return t(), n;
990
1036
  }
991
- function He(e) {
1037
+ function Ke(e) {
992
1038
  return e === "alwaysOn" || e === "only" ? {
993
1039
  visible: !1,
994
1040
  checked: !0,
@@ -1011,11 +1057,11 @@ function X(e) {
1011
1057
  e.bottomLeft
1012
1058
  ];
1013
1059
  }
1014
- var Ue = 1600;
1015
- function We(e = H()) {
1016
- return U(e) ? Ee : Ue;
1060
+ var qe = 1600;
1061
+ function Je(e = H()) {
1062
+ return U(e) ? Ee : qe;
1017
1063
  }
1018
- function Ge(e) {
1064
+ function Ye(e) {
1019
1065
  let t = 0;
1020
1066
  for (let n = 0; n < e.length; n += 1) {
1021
1067
  let r = e[n], i = e[(n + 1) % e.length];
@@ -1033,23 +1079,23 @@ var Q = {
1033
1079
  areaFill: 0,
1034
1080
  aspectRatio: 1
1035
1081
  };
1036
- function Ke(e, t, n) {
1082
+ function Xe(e, t, n) {
1037
1083
  let r = X(e), i = r.map(({ x: e }) => e), a = r.map(({ y: e }) => e), o = (Math.max(...i) - Math.min(...i)) / Math.max(1, t), s = (Math.max(...a) - Math.min(...a)) / Math.max(1, n), [c, l, u, d] = r, f = Math.max(Z(c, l), Z(d, u)), p = Math.max(Z(c, d), Z(l, u));
1038
1084
  return {
1039
1085
  widthFill: o,
1040
1086
  heightFill: s,
1041
1087
  limitingFill: Math.max(o, s),
1042
- areaFill: Ge(r) / Math.max(1, t * n),
1088
+ areaFill: Ye(r) / Math.max(1, t * n),
1043
1089
  aspectRatio: Math.max(f, p) / Math.max(1, Math.min(f, p))
1044
1090
  };
1045
1091
  }
1046
- function qe(e, t, n, r = {}) {
1092
+ function Ze(e, t, n, r = {}) {
1047
1093
  let i = t ? r.exitFillRatio ?? .64 : r.minFillRatio ?? .72, a = r.highAspectRatio ?? 2.2;
1048
1094
  if (e.aspectRatio < a) return i;
1049
1095
  let o = t ? r.highAspectExitFillRatio : r.highAspectFillRatio;
1050
1096
  return Math.min(o ?? i + .08, 1 - n * 2);
1051
1097
  }
1052
- function Je(e, t, n = {}) {
1098
+ function Qe(e, t, n = {}) {
1053
1099
  let r = n.confidenceThreshold ?? .72;
1054
1100
  if (e.status !== "success" || !e.quad || e.confidence < r || !e.sourceWidth || !e.sourceHeight) return {
1055
1101
  hint: "Place the document in the frame",
@@ -1058,7 +1104,7 @@ function Je(e, t, n = {}) {
1058
1104
  fill: Q,
1059
1105
  readyForAutoCapture: !1
1060
1106
  };
1061
- let i = X(e.quad), a = Ke(e.quad, e.sourceWidth, e.sourceHeight), o = a.limitingFill, s = t.previouslyReady ? n.exitEdgeMarginRatio ?? .005 : n.edgeMarginRatio ?? .015, c = e.sourceWidth * s, l = e.sourceHeight * s;
1107
+ let i = X(e.quad), a = Xe(e.quad, e.sourceWidth, e.sourceHeight), o = a.limitingFill, s = t.previouslyReady ? n.exitEdgeMarginRatio ?? .005 : n.edgeMarginRatio ?? .015, c = e.sourceWidth * s, l = e.sourceHeight * s;
1062
1108
  if (i.some(({ x: t, y: n }) => t <= c || t >= e.sourceWidth - c || n <= l || n >= e.sourceHeight - l)) return {
1063
1109
  hint: "Move farther away",
1064
1110
  reason: "move-farther-away",
@@ -1073,7 +1119,7 @@ function Je(e, t, n = {}) {
1073
1119
  fillRatio: o,
1074
1120
  fill: a,
1075
1121
  readyForAutoCapture: !1
1076
- } : o < qe(a, t.previouslyReady === !0, s, n) ? {
1122
+ } : o < Ze(a, t.previouslyReady === !0, s, n) ? {
1077
1123
  hint: "Move closer",
1078
1124
  reason: "move-closer",
1079
1125
  fillRatio: o,
@@ -1115,14 +1161,13 @@ var $ = class {
1115
1161
  };
1116
1162
  }
1117
1163
  };
1118
- function Ye(e, n) {
1119
- let r = Me(e.width, e.height, n), i = document.createElement("canvas");
1120
- i.width = r.width, i.height = r.height;
1121
- let a = i.getContext("2d");
1122
- if (!a) throw t();
1123
- return a.drawImage(e, 0, 0, i.width, i.height), i;
1164
+ function $e(e, t) {
1165
+ let n = e instanceof HTMLVideoElement ? e.videoWidth : e.width, r = e instanceof HTMLVideoElement ? e.videoHeight : e.height;
1166
+ if (!n || !r) throw Error("The camera is not ready to capture a frame.");
1167
+ let i = Fe(e);
1168
+ return Re(e, n, r, i.width, i.height, t);
1124
1169
  }
1125
- function Xe() {
1170
+ function et() {
1126
1171
  let e = window.AudioContext ?? window.webkitAudioContext;
1127
1172
  if (!e) return;
1128
1173
  let t = new e(), n = Math.round(t.sampleRate * .09), r = t.createBuffer(1, n, t.sampleRate), i = r.getChannelData(0);
@@ -1133,22 +1178,22 @@ function Xe() {
1133
1178
  let a = t.createBufferSource(), o = t.createBiquadFilter(), s = t.createGain();
1134
1179
  o.type = "bandpass", o.frequency.value = 1400, s.gain.value = .42, a.buffer = r, a.connect(o).connect(s).connect(t.destination), a.start(), a.onended = () => void t.close();
1135
1180
  }
1136
- async function Ze(e) {
1181
+ async function tt(e) {
1137
1182
  let t = document.createElement("video");
1138
1183
  return t.muted = !0, t.autoplay = !0, t.playsInline = !0, t.srcObject = e, await t.play(), t;
1139
1184
  }
1140
- async function Qe(t) {
1185
+ async function nt(t) {
1141
1186
  await x("scan");
1142
- let n = He(t.autoCapture), r = new $({
1187
+ let n = Ke(t.autoCapture), r = new $({
1143
1188
  stableFrames: t.stableFrames ?? 4,
1144
1189
  confidenceThreshold: t.confidenceThreshold ?? .72,
1145
1190
  cornerTolerance: t.cornerTolerance ?? .024,
1146
1191
  exitCornerTolerance: t.exitCornerTolerance ?? .036
1147
- }), i = t.maxFrameDimension ?? We(), a = t.intervalMs ?? 140, o = {
1192
+ }), i = t.maxFrameDimension ?? Je(), a = t.intervalMs ?? 140, o = {
1148
1193
  minDimension: 220,
1149
1194
  maxAnalysisDimension: i,
1150
1195
  ...t.detection
1151
- }, s = typeof MediaStream < "u" && t.source instanceof MediaStream ? await Ze(t.source) : t.source, c = !0, l = !1, u = !1, d = 0, f, p = {
1196
+ }, s = typeof MediaStream < "u" && t.source instanceof MediaStream ? await tt(t.source) : t.source, c = !0, l = !1, u = !1, d = 0, f, p = {
1152
1197
  state: "detecting",
1153
1198
  confidence: 0,
1154
1199
  guidance: {
@@ -1165,7 +1210,7 @@ async function Qe(t) {
1165
1210
  stableFrames: 0,
1166
1211
  requiredStableFrames: t.stableFrames ?? 4,
1167
1212
  autoCapture: { ...n }
1168
- }, m = () => s instanceof HTMLCanvasElement ? Ye(s, i) : Y(s, i), h = (e) => {
1213
+ }, m = () => $e(s, i), h = (e) => {
1169
1214
  p = e, t.onStatus?.(e);
1170
1215
  }, g = () => {
1171
1216
  c = !1, window.clearTimeout(d), s instanceof HTMLVideoElement && s !== t.source && (s.srcObject = null);
@@ -1174,11 +1219,11 @@ async function Qe(t) {
1174
1219
  l = !0;
1175
1220
  let n;
1176
1221
  try {
1177
- n = await Ve(t.captureFrame ?? m, () => {
1222
+ n = await Ge(t.captureFrame ?? m, () => {
1178
1223
  h({
1179
1224
  ...p,
1180
1225
  state: "captured"
1181
- }), t.playShutterSound !== !1 && Xe(), g();
1226
+ }), t.playShutterSound !== !1 && et(), g();
1182
1227
  });
1183
1228
  } catch (e) {
1184
1229
  throw l = !1, e instanceof Error ? e : /* @__PURE__ */ Error("The camera frame could not be captured.");
@@ -1194,7 +1239,7 @@ async function Qe(t) {
1194
1239
  try {
1195
1240
  let e = m(), i = await B(e, o);
1196
1241
  f = i;
1197
- let a = i.quad ? ze(e, i.quad) : {
1242
+ let a = i.quad ? Ue(e, i.quad) : {
1198
1243
  strong: !1,
1199
1244
  strength: 0
1200
1245
  }, s = a.strong ? {
@@ -1204,7 +1249,7 @@ async function Qe(t) {
1204
1249
  } : {
1205
1250
  castShadow: !1,
1206
1251
  strength: a.strength
1207
- }, c = r.update(i), l = Je(i, {
1252
+ }, c = r.update(i), l = Qe(i, {
1208
1253
  ...c,
1209
1254
  previouslyReady: u
1210
1255
  }, {
@@ -1278,6 +1323,6 @@ async function Qe(t) {
1278
1323
  };
1279
1324
  }
1280
1325
  //#endregion
1281
- export { a as A, M as C, j as D, de as E, e as F, t as I, x as M, b as N, ie as O, y as P, B as S, ue as T, J as _, Je as a, fe as b, Ie as c, De as d, Y as f, K as g, Oe as h, Ke as i, o as j, ne as k, Le as l, Se as m, He as n, Be as o, H as p, qe as r, Qe as s, $ as t, W as u, Pe as v, xe as w, be as x, G as y };
1326
+ export { a as A, M as C, j as D, de as E, e as F, t as I, x as M, b as N, ie as O, y as P, B as S, ue as T, J as _, Qe as a, fe as b, Be as c, De as d, Y as f, K as g, Oe as h, Xe as i, o as j, ne as k, Ve as l, Se as m, Ke as n, We as o, H as p, Ze as r, nt as s, $ as t, W as u, Pe as v, xe as w, be as x, G as y };
1282
1327
 
1283
- //# sourceMappingURL=finder-Bjo3TAHi.js.map
1328
+ //# sourceMappingURL=finder-D0Wgl-6-.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"finder-D0Wgl-6-.js","names":[],"sources":["../src/sdk/errors.ts","../src/sdk/license-codec.ts","../src/sdk/license-public-key.ts","../src/sdk/license-runtime.ts","../src/sdk/license.ts","../src/sdk/model-download.ts","../src/sdk/ort-runtime.ts","../src/sdk/image.ts","../src/sdk/scan.ts","../src/sdk/camera.ts","../src/sdk/preview-frame.ts","../src/sdk/lighting.ts","../src/sdk/finder.ts"],"sourcesContent":["/**\n * Operational failure from the scanner runtime.\n *\n * Scan quality stays a returned status (`success`, `no-document`,\n * `low-confidence`, or `low-quality`). Redaction match quality stays\n * `success`, `partial`, or `unmatched`. Neither of those outcomes uses this error.\n * A bad image does not throw.\n */\nexport type ScannerErrorCode =\n | 'secure-context'\n | 'worker'\n | 'model-http'\n | 'language'\n | 'canvas'\n\nexport class ScannerError extends Error {\n readonly code: ScannerErrorCode\n\n constructor(code: ScannerErrorCode, message: string) {\n super(message)\n this.name = 'ScannerError'\n this.code = code\n }\n}\n\nexport function canvasUnavailable(): ScannerError {\n return new ScannerError('canvas', 'Canvas 2D is unavailable in this browser.')\n}\n","export function bytesToBase64Url(bytes: Uint8Array): string {\n let binary = ''\n for (const byte of bytes) binary += String.fromCharCode(byte)\n return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/u, '')\n}\n\nexport function base64UrlToBytes(value: string): Uint8Array {\n const normalized = value.replaceAll('-', '+').replaceAll('_', '/')\n const padded = normalized + '='.repeat((4 - (normalized.length % 4)) % 4)\n const binary = atob(padded)\n const bytes = new Uint8Array(binary.length)\n for (let index = 0; index < binary.length; index += 1) {\n bytes[index] = binary.charCodeAt(index)\n }\n return bytes\n}\n","/**\n * Raw Ed25519 public key: 32 bytes, base64url, no padding.\n *\n * The license portal signs with `LICENSE_SIGNING_PRIVATE_KEY`.\n * Generate a pair with `npm run generate-keypair --prefix license-portal`,\n * then replace this constant with the printed public key and rebuild the\n * library. Never commit the private key.\n */\nexport const LICENSE_PUBLIC_KEY_BASE64 = 'uFpA_UXGk-1AjjG31cFP6cqXOQX0w2TnuR7Bl-msZ6I'\n","import { base64UrlToBytes } from './license-codec'\nimport { LICENSE_PUBLIC_KEY_BASE64 } from './license-public-key'\n\n/** Public key embedded in the published package. Tests replace this module. */\nexport function embeddedLicensePublicKey(): Uint8Array {\n return base64UrlToBytes(LICENSE_PUBLIC_KEY_BASE64)\n}\n","import { base64UrlToBytes } from './license-codec'\nimport { embeddedLicensePublicKey } from './license-runtime'\n\n/**\n * Hosts that may use the SDK before a paid license exists.\n * Add a production hostname here when it should run without a signed key.\n *\n * An entry is either an exact hostname or a single `*.suffix` pattern.\n * `*.exige.io` matches `exige.io` and any host that ends with `.exige.io`.\n * It does not match `exige.io.evil.com`. `*.localhost` is the only\n * single-label suffix; `app.localhost` is allowed. Ngrok tunnel suffixes\n * are allowed. Nothing here allows `*.vercel.app`. Paid license `domains`\n * stay exact hostnames.\n */\nexport const DEV_LICENSE_HOSTS = [\n 'localhost',\n '127.0.0.1',\n 'exige-scanner-sdk.vercel.app',\n '*.localhost',\n '*.exige.io',\n '*.ngrok.io',\n '*.ngrok.app',\n '*.ngrok.dev',\n '*.ngrok-free.app',\n '*.ngrok-free.dev',\n] as const\n\nexport const LICENSE_FEATURES = ['scan', 'ocr', 'redaction', 'vehicles', 'torch'] as const\n\nexport type LicenseFeature = (typeof LICENSE_FEATURES)[number]\n\nexport type LicenseErrorCode =\n | 'missing'\n | 'malformed'\n | 'invalid-signature'\n | 'expired'\n | 'domain'\n | 'feature'\n\nexport interface LicenseFeatures {\n scan: boolean\n ocr: boolean\n redaction: boolean\n /**\n * Kept so existing signed keys still verify.\n * No camera, finder, scan, OCR, or redaction entry point asserts this flag.\n */\n vehicles: boolean\n torch: boolean\n}\n\nexport interface LicenseClaims {\n customerId: string\n /** Exact hostnames. `localhost` and `127.0.0.1` are included only when listed. */\n domains: string[]\n /** Unix expiry in seconds. The key is valid while `now < exp`. */\n exp: number\n features: LicenseFeatures\n}\n\n/**\n * Compact signed payload: `base64url(json).base64url(ed25519 signature)`.\n * The signature covers the raw JSON bytes. Public APIs do not accept a\n * caller-supplied public key or hostname.\n */\nexport interface LicenseVerification {\n publicKey: Uint8Array\n /** Injected only for Node tests. Browsers use `location.hostname`. */\n hostname: string\n /** Unix time in seconds. */\n now: number\n}\n\nexport class LicenseError extends Error {\n readonly code: LicenseErrorCode\n\n constructor(code: LicenseErrorCode, message: string) {\n super(message)\n this.name = 'LicenseError'\n this.code = code\n }\n}\n\nlet activeToken: string | undefined\nlet activeClaims: LicenseClaims | undefined\n\nexport function normalizeHostname(value: string): string {\n return value.trim().toLowerCase().replace(/\\.$/u, '')\n}\n\n/**\n * Canonical JSON signed by the license portal. Key order is part of the\n * signature bytes. Keep this in lockstep with `license-portal/lib/license-token.ts`.\n */\nexport function canonicalLicensePayload(claims: LicenseClaims): string {\n const domains = [...new Set(claims.domains.map(normalizeHostname).filter(Boolean))].sort()\n const features = {\n ocr: claims.features.ocr === true,\n redaction: claims.features.redaction === true,\n scan: claims.features.scan === true,\n torch: claims.features.torch === true,\n vehicles: claims.features.vehicles === true,\n }\n return JSON.stringify({\n customerId: claims.customerId,\n domains,\n exp: claims.exp,\n features,\n })\n}\n\nfunction readBrowserHostname(): string | undefined {\n const host = (globalThis as { location?: { hostname?: string } }).location?.hostname\n if (typeof host !== 'string') return undefined\n const normalized = normalizeHostname(host)\n return normalized || undefined\n}\n\nfunction unixNow(): number {\n return Math.floor(Date.now() / 1000)\n}\n\nfunction matchesDevLicenseEntry(hostname: string, entry: string): boolean {\n const pattern = normalizeHostname(entry)\n if (pattern.startsWith('*.')) {\n const suffix = pattern.slice(2)\n const allowSingleLabel = suffix === 'localhost'\n if ((!suffix.includes('.') && !allowSingleLabel) || suffix.startsWith('.') || suffix.includes('*')) {\n return false\n }\n return hostname === suffix || hostname.endsWith(`.${suffix}`)\n }\n return hostname === pattern\n}\n\nfunction isDevLicenseHost(hostname: string): boolean {\n const host = normalizeHostname(hostname)\n if (!host || host.includes('*')) return false\n return DEV_LICENSE_HOSTS.some((entry) => matchesDevLicenseEntry(host, entry))\n}\n\n/** All features, only for the host that matched `DEV_LICENSE_HOSTS`. */\nfunction developmentLicense(hostname: string): LicenseClaims {\n return {\n customerId: 'dev',\n domains: [hostname],\n exp: 4_102_444_800,\n features: {\n scan: true,\n ocr: true,\n redaction: true,\n vehicles: true,\n torch: true,\n },\n }\n}\n\nfunction copyClaims(claims: LicenseClaims): LicenseClaims {\n return {\n customerId: claims.customerId,\n domains: [...claims.domains],\n exp: claims.exp,\n features: { ...claims.features },\n }\n}\n\nfunction malformed(message = 'This license key is not a signed payload.'): LicenseError {\n return new LicenseError('malformed', message)\n}\n\nfunction parseClaims(payload: unknown): LicenseClaims {\n if (!payload || typeof payload !== 'object' || Array.isArray(payload)) throw malformed()\n const record = payload as Record<string, unknown>\n if (typeof record.customerId !== 'string' || record.customerId.trim() === '' || record.customerId.length > 200) {\n throw malformed('This license key is missing a customer id.')\n }\n if (!Array.isArray(record.domains) || record.domains.some((domain) => typeof domain !== 'string')) {\n throw malformed('This license key is missing a domain list.')\n }\n if (typeof record.exp !== 'number' || !Number.isSafeInteger(record.exp) || record.exp <= 0) {\n throw malformed('This license key is missing a Unix expiry.')\n }\n if (!record.features || typeof record.features !== 'object' || Array.isArray(record.features)) {\n throw malformed('This license key is missing feature flags.')\n }\n const flags = record.features as Record<string, unknown>\n const domains = [...new Set(record.domains.map((domain) => normalizeHostname(domain)).filter(Boolean))].sort()\n return {\n customerId: record.customerId.trim(),\n domains,\n exp: record.exp,\n features: {\n scan: flags.scan === true,\n ocr: flags.ocr === true,\n redaction: flags.redaction === true,\n vehicles: flags.vehicles === true,\n torch: flags.torch === true,\n },\n }\n}\n\n/**\n * Verifies a compact license. Hostname and public key are explicit so Node\n * tests can inject them. Published entry points call `assertLicense`, which\n * always uses the embedded public key and `location.hostname`.\n */\nexport async function verifyLicenseToken(\n licenseKey: string,\n verification: LicenseVerification,\n): Promise<LicenseClaims> {\n const parts = licenseKey.trim().split('.')\n if (parts.length !== 2 || !parts[0] || !parts[1]) throw malformed()\n let payloadBytes: Uint8Array\n let signature: Uint8Array\n try {\n payloadBytes = base64UrlToBytes(parts[0])\n signature = base64UrlToBytes(parts[1])\n } catch {\n throw malformed()\n }\n let key: CryptoKey\n let valid = false\n try {\n key = await crypto.subtle.importKey(\n 'raw',\n verification.publicKey as BufferSource,\n { name: 'Ed25519' },\n false,\n ['verify'],\n )\n valid = await crypto.subtle.verify('Ed25519', key, signature as BufferSource, payloadBytes as BufferSource)\n } catch {\n valid = false\n }\n if (!valid) {\n throw new LicenseError('invalid-signature', 'This license key signature does not match the SDK public key.')\n }\n let parsed: unknown\n try {\n parsed = JSON.parse(new TextDecoder().decode(payloadBytes))\n } catch {\n throw malformed()\n }\n const claims = parseClaims(parsed)\n if (claims.exp <= verification.now) {\n throw new LicenseError('expired', 'This license key has expired.')\n }\n const hostname = normalizeHostname(verification.hostname)\n if (!hostname || !claims.domains.includes(hostname)) {\n throw new LicenseError('domain', `This license key is not valid for ${hostname || 'this host'}.`)\n }\n return claims\n}\n\n/**\n * Verifies `licenseKey` for the current page and keeps it for later calls.\n *\n * @throws {LicenseError} LicenseError when the key is missing, malformed, badly signed,\n * expired, or not issued for `location.hostname`.\n */\nexport async function setLicenseKey(licenseKey: string): Promise<LicenseClaims> {\n const hostname = readBrowserHostname()\n if (!hostname) {\n throw new LicenseError('domain', 'The license check requires a browser hostname.')\n }\n const claims = await verifyLicenseToken(licenseKey, {\n publicKey: embeddedLicensePublicKey(),\n hostname,\n now: unixNow(),\n })\n activeToken = licenseKey.trim()\n activeClaims = claims\n return copyClaims(claims)\n}\n\n/**\n * Feature flags from the key most recently accepted by `setLicenseKey`.\n * Returns null when no key is loaded, the key is expired, or this hostname\n * is not on the key. Enforcement still re-checks the signature in `assertLicense`.\n */\nexport function getLicense(): LicenseClaims | null {\n const hostname = readBrowserHostname()\n if (activeClaims && hostname && activeClaims.domains.includes(hostname) && activeClaims.exp > unixNow()) {\n return copyClaims(activeClaims)\n }\n if (!activeToken && hostname && isDevLicenseHost(hostname)) return copyClaims(developmentLicense(hostname))\n return null\n}\n\n/**\n * Fail-closed gate used by the public camera, finder, scan, OCR, and\n * redaction entry points.\n *\n * @throws {LicenseError} LicenseError before those APIs do any work, when the key is\n * missing, invalid, or missing `feature`.\n */\nexport async function assertLicense(feature: LicenseFeature): Promise<LicenseClaims> {\n const hostname = readBrowserHostname()\n if (!hostname) {\n throw new LicenseError('domain', 'The license check requires a browser hostname.')\n }\n if (!activeToken) {\n if (isDevLicenseHost(hostname)) return copyClaims(developmentLicense(hostname))\n throw new LicenseError(\n 'missing',\n 'A license key is required. Call setLicenseKey() before using the scanner SDK.',\n )\n }\n const claims = await verifyLicenseToken(activeToken, {\n publicKey: embeddedLicensePublicKey(),\n hostname,\n now: unixNow(),\n })\n activeClaims = claims\n if (!claims.features[feature]) {\n throw new LicenseError('feature', `This license key does not include the ${feature} feature.`)\n }\n return copyClaims(claims)\n}\n\n/** Drops the in-memory key. Not part of the published package entry. */\nexport function clearLicenseForTests(): void {\n activeToken = undefined\n activeClaims = undefined\n}\n","import { ScannerError } from './errors'\n\nexport interface ModelDownloadProgress {\n loaded: number\n /** Byte length from Content-Length. Null when that header is absent. */\n total: number | null\n done?: boolean\n}\n\nexport interface ModelDownloadSnapshot {\n downloading: boolean\n loaded: number\n /** Sum of Content-Length values when every active transfer has one. */\n total: number | null\n}\n\nconst STORE = Symbol.for('exige.web-scanner-sdk.model-downloads')\n\ninterface ModelDownloadStore {\n active: Map<string, { loaded: number; total: number | null }>\n listeners: Set<(snapshot: ModelDownloadSnapshot) => void>\n cache: Map<string, ArrayBuffer>\n inflight: Map<string, Promise<ArrayBuffer>>\n}\n\n/** One store across the package entry and the React entry. */\nfunction store(): ModelDownloadStore {\n const scope = globalThis as typeof globalThis & { [STORE]?: ModelDownloadStore }\n if (!scope[STORE]) {\n scope[STORE] = {\n active: new Map(),\n listeners: new Set(),\n cache: new Map(),\n inflight: new Map(),\n }\n }\n return scope[STORE]\n}\n\nconst active = store().active\nconst listeners = store().listeners\nconst cache = store().cache\nconst inflight = store().inflight\n\nfunction contentLength(response: Response) {\n const parsed = Number(response.headers.get('content-length'))\n return Number.isFinite(parsed) && parsed > 0 ? parsed : null\n}\n\nexport function modelDownloadSnapshot(): ModelDownloadSnapshot {\n if (active.size === 0) return { downloading: false, loaded: 0, total: null }\n let loaded = 0\n let total = 0\n let known = true\n for (const item of active.values()) {\n loaded += item.loaded\n if (item.total == null) known = false\n else total += item.total\n }\n return { downloading: true, loaded, total: known ? total : null }\n}\n\nfunction emit() {\n const snapshot = modelDownloadSnapshot()\n for (const listener of listeners) listener(snapshot)\n}\n\n/** Subscribing does not fetch. The document worker and `downloadModelBytes` report into the same snapshot. */\nexport function subscribeModelDownloads(listener: (snapshot: ModelDownloadSnapshot) => void) {\n listener(modelDownloadSnapshot())\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n}\n\n/** Progress reported from another realm, such as the document worker. */\nexport function reportModelDownload(url: string, progress: ModelDownloadProgress) {\n if (progress.done) active.delete(url)\n else active.set(url, { loaded: progress.loaded, total: progress.total })\n emit()\n}\n\nexport async function readResponseBytes(\n response: Response,\n onProgress?: (progress: ModelDownloadProgress) => void,\n) {\n const total = contentLength(response)\n if (!response.body) {\n const bytes = await response.arrayBuffer()\n onProgress?.({ loaded: bytes.byteLength, total: total ?? bytes.byteLength })\n return bytes\n }\n const reader = response.body.getReader()\n const chunks: Uint8Array[] = []\n let loaded = 0\n for (;;) {\n const { done, value } = await reader.read()\n if (done) break\n if (!value?.byteLength) continue\n chunks.push(value)\n loaded += value.byteLength\n onProgress?.({ loaded, total })\n }\n const bytes = new Uint8Array(loaded)\n let offset = 0\n for (const chunk of chunks) {\n bytes.set(chunk, offset)\n offset += chunk.byteLength\n }\n if (loaded === 0) onProgress?.({ loaded: 0, total })\n return bytes.buffer\n}\n\n/**\n * Fetch a model file and report loaded/total while the body transfers.\n * A second call for the same URL reuses the cached bytes and does not fetch.\n */\nexport async function downloadModelBytes(url: string, init?: { cache?: RequestCache }) {\n const cached = cache.get(url)\n if (cached) return cached.slice(0)\n const existing = inflight.get(url)\n if (existing) return existing.then((bytes) => bytes.slice(0))\n const request = (async () => {\n reportModelDownload(url, { loaded: 0, total: null })\n const response = await fetch(url, { cache: init?.cache })\n if (!response.ok) {\n throw new ScannerError('model-http', `Model request failed with HTTP ${response.status}.`)\n }\n return readResponseBytes(response, (progress) => reportModelDownload(url, progress))\n })()\n inflight.set(url, request)\n try {\n const bytes = await request\n cache.set(url, bytes)\n return bytes.slice(0)\n } finally {\n inflight.delete(url)\n if (active.has(url)) {\n active.delete(url)\n emit()\n }\n }\n}\n","/**\n * ONNX Runtime Web 1.30 extern-wasm JSEP build (WebGPU, then WASM).\n * Literal `new URL` calls are what Webpack and Turbopack copy.\n */\nexport const packagedOrtWasmFile = new URL(\n './runtime/ort-wasm-simd-threaded.jsep.wasm',\n import.meta.url,\n)\nexport const packagedOrtWasmGlue = new URL(\n './runtime/ort-wasm-simd-threaded.jsep.mjs',\n import.meta.url,\n)\n\nexport type {\n OrtLoadSource,\n OrtImporter,\n OrtModule,\n OrtWasmPaths,\n PackagedOrtWasmPaths,\n} from './ort-cdn'\nexport {\n LAST_RESORT_ORT_CDN_BASE,\n ORT_JS_FILENAME,\n ORT_WASM_FILENAME,\n ORT_WASM_MJS_FILENAME,\n PINNED_ONNXRUNTIME_WEB_VERSION,\n PREFERRED_ORT_CDN_BASE,\n SIBLING_ORT_MODULE,\n expandOrtWasmPaths,\n importOrtSpecifier,\n joinOrtCdnUrl,\n loadOrtJsFromPinnedCdn,\n loadOrtRuntime,\n pinnedOrtJsUrls,\n pinnedOrtWasmPaths,\n probeHttpUrl,\n probeOrtWasmPaths,\n resolveUsableOrtWasmPaths,\n siblingOrtUrl,\n} from './ort-cdn'\n\nimport { type OrtWasmPaths, type PackagedOrtWasmPaths } from './ort-cdn'\n\nexport function packagedOrtWasmPaths(): PackagedOrtWasmPaths {\n return {\n wasm: packagedOrtWasmFile.href,\n mjs: packagedOrtWasmGlue.href,\n }\n}\n\n/** Uses the packaged wasm pair when the override is missing or blank. */\nexport function resolveOrtWasmPaths(value?: OrtWasmPaths): OrtWasmPaths {\n if (typeof value === 'string') {\n const trimmed = value.trim()\n if (trimmed) return trimmed\n return packagedOrtWasmPaths()\n }\n if (value?.wasm.trim() && value.mjs.trim()) {\n return { wasm: value.wasm.trim(), mjs: value.mjs.trim() }\n }\n return packagedOrtWasmPaths()\n}\n","import { canvasUnavailable } from './errors'\nimport type { ImageSource } from './types'\n\nexport interface CanvasSourceOptions {\n cloneCanvas?: boolean\n maxDimension?: number\n}\n\nfunction scaledSize(width: number, height: number, maxDimension?: number) {\n const scale = maxDimension ? Math.min(1, maxDimension / Math.max(width, height)) : 1\n return {\n width: Math.max(1, Math.round(width * scale)),\n height: Math.max(1, Math.round(height * scale)),\n }\n}\n\nasync function blobToImage(blob: Blob) {\n const url = URL.createObjectURL(blob)\n try {\n const image = new Image()\n image.src = url\n await image.decode()\n return image\n } finally {\n URL.revokeObjectURL(url)\n }\n}\n\nexport async function sourceToCanvas(\n source: ImageSource,\n options: CanvasSourceOptions = {},\n): Promise<HTMLCanvasElement> {\n if (source instanceof HTMLCanvasElement && options.cloneCanvas === false && !options.maxDimension) {\n return source\n }\n const canvas = document.createElement('canvas')\n const context = canvas.getContext('2d', { willReadFrequently: true })\n if (!context) throw canvasUnavailable()\n\n if (source instanceof Blob) {\n if ('createImageBitmap' in window) {\n try {\n const bitmap = await createImageBitmap(source)\n const size = scaledSize(bitmap.width, bitmap.height, options.maxDimension)\n canvas.width = size.width\n canvas.height = size.height\n context.drawImage(bitmap, 0, 0, size.width, size.height)\n bitmap.close()\n return canvas\n } catch {\n // Fall through to HTMLImageElement decoding for iOS/WebKit formats.\n }\n }\n source = await blobToImage(source)\n }\n\n const width = source instanceof HTMLImageElement ? source.naturalWidth : source.width\n const height = source instanceof HTMLImageElement ? source.naturalHeight : source.height\n if (!width || !height) throw new Error('The image has no readable dimensions.')\n const size = scaledSize(width, height, options.maxDimension)\n canvas.width = size.width\n canvas.height = size.height\n context.drawImage(source, 0, 0, size.width, size.height)\n return canvas\n}\n\nexport function canvasToBlob(\n canvas: HTMLCanvasElement,\n type = 'image/png',\n quality = 0.92,\n): Promise<Blob> {\n return new Promise((resolve, reject) =>\n canvas.toBlob(\n (blob) => (blob ? resolve(blob) : reject(new Error('Could not encode the image.'))),\n type,\n quality,\n ),\n )\n}\n\nexport function clampBox(\n box: { x: number; y: number; width: number; height: number },\n width: number,\n height: number,\n) {\n const x = Math.max(0, Math.min(width, box.x))\n const y = Math.max(0, Math.min(height, box.y))\n return {\n x,\n y,\n width: Math.max(0, Math.min(width - x, box.width)),\n height: Math.max(0, Math.min(height - y, box.height)),\n }\n}\n","import { canvasUnavailable, ScannerError } from './errors'\nimport { assertLicense } from './license'\nimport { reportModelDownload } from './model-download'\nimport { resolveOrtWasmPaths, type OrtWasmPaths } from './ort-runtime'\nimport { sourceToCanvas } from './image'\nimport type {\n DocumentCorners,\n DocumentDetectionResult,\n DocumentModelStatus,\n DocumentQuad,\n ImageSource,\n Point,\n ScanResult,\n} from './types'\n\nexport interface ScanOptions {\n minDimension?: number\n minConfidence?: number\n maxAnalysisDimension?: number\n maxOutputDimension?: number\n useWorker?: boolean\n /**\n * DocAligner checkpoint URL. Omit this. The default is the Exige CDN\n * DocAligner model (`DEFAULT_DOCUMENT_MODEL_URL`).\n */\n modelUrl?: string\n /** Heatmap threshold used before largest-component corner centroids. */\n heatmapThreshold?: number\n /** Reuse model bytes through the browser HTTP cache. */\n cacheModel?: boolean\n /**\n * ONNX Runtime wasm override. Omit this. The default is the packaged\n * `ort-wasm-simd-threaded.jsep.wasm` and `.mjs` files.\n * A string is a directory that contains both files. An object sets each URL.\n */\n ortWasmPaths?: OrtWasmPaths\n}\n\nexport const DEFAULT_DOCUMENT_MODEL_URL =\n 'https://exige-scanner-sdk.vercel.app/models/docaligner-lcnet100-f4117b78.onnx'\nexport const TALL_PAGE_ASPECT = 1.6\nexport const TALL_PAGE_ANALYSIS_DIMENSION = 1280\n\nexport function analysisDimensionForSource(\n width: number,\n height: number,\n requested?: number,\n) {\n if (requested) return requested\n const longEdge = Math.max(width, height)\n const shortEdge = Math.max(1, Math.min(width, height))\n const aspect = longEdge / shortEdge\n const base = isMobileClassDevice() ? 560 : 900\n if (aspect >= TALL_PAGE_ASPECT) {\n return Math.min(longEdge, Math.max(base, TALL_PAGE_ANALYSIS_DIMENSION))\n }\n return base\n}\n\nexport function resolveDocumentModelUrl(modelUrl?: string) {\n return modelUrl?.trim() || DEFAULT_DOCUMENT_MODEL_URL\n}\n\ninterface WorkerAnalysis {\n sharpness: number\n candidate?: { corners: DocumentCorners; confidence: number }\n detector?: 'ml'\n modelStatus?: DocumentModelStatus\n modelProvider?: 'webgpu' | 'wasm'\n modelError?: string\n inferenceMs?: number\n}\n\nconst MIN_DOCUMENT_SHARPNESS = 3\n\nlet analysisWorker: Worker | undefined\nlet analysisRequestId = 0\nconst analysisRequests = new Map<number, {\n resolve: (analysis: WorkerAnalysis) => void\n reject: (error: Error) => void\n}>()\n\nfunction distance(a: Point, b: Point) {\n return Math.hypot(a.x - b.x, a.y - b.y)\n}\n\nfunction toQuad(corners: DocumentCorners): DocumentQuad {\n return {\n ...corners,\n edges: {\n top: { start: corners.topLeft, end: corners.topRight },\n right: { start: corners.topRight, end: corners.bottomRight },\n bottom: { start: corners.bottomRight, end: corners.bottomLeft },\n left: { start: corners.bottomLeft, end: corners.topLeft },\n },\n }\n}\n\nfunction scaleCorners(corners: DocumentCorners, scale: number): DocumentCorners {\n const resize = (point: Point) => ({ x: point.x / scale, y: point.y / scale })\n return {\n topLeft: resize(corners.topLeft),\n topRight: resize(corners.topRight),\n bottomRight: resize(corners.bottomRight),\n bottomLeft: resize(corners.bottomLeft),\n }\n}\n\nfunction isMobileClassDevice() {\n if (typeof navigator === 'undefined') return false\n return navigator.maxTouchPoints > 0 || navigator.hardwareConcurrency <= 4 ||\n (typeof matchMedia === 'function' && matchMedia('(pointer: coarse)').matches)\n}\n\nfunction analyzeInWorker(\n pixels: Uint8ClampedArray,\n width: number,\n height: number,\n options: ScanOptions,\n): Promise<WorkerAnalysis> {\n return new Promise((resolve, reject) => {\n if (!analysisWorker) {\n analysisWorker = new Worker(new URL('./document-worker.ts', import.meta.url), { type: 'module' })\n analysisWorker.onmessage = (event: MessageEvent<{\n id: number\n result?: WorkerAnalysis\n error?: string\n errorCode?: ScannerError['code']\n download?: { url: string; loaded: number; total: number | null; done?: boolean }\n }>) => {\n if (event.data.download?.url) {\n reportModelDownload(event.data.download.url, event.data.download)\n return\n }\n const pending = analysisRequests.get(event.data.id)\n if (!pending) return\n analysisRequests.delete(event.data.id)\n if (event.data.error) {\n pending.reject(event.data.errorCode\n ? new ScannerError(event.data.errorCode, event.data.error)\n : new Error(event.data.error))\n }\n else if (event.data.result) pending.resolve(event.data.result)\n else pending.reject(new Error('The document worker returned no result.'))\n }\n analysisWorker.onerror = () => {\n const error = new ScannerError('worker', 'The document worker could not start.')\n for (const pending of analysisRequests.values()) pending.reject(error)\n analysisRequests.clear()\n analysisWorker?.terminate()\n analysisWorker = undefined\n }\n }\n const id = ++analysisRequestId\n analysisRequests.set(id, { resolve, reject })\n const transferable = pixels.slice().buffer\n analysisWorker.postMessage({\n id,\n pixels: transferable,\n width,\n height,\n modelUrl: resolveDocumentModelUrl(options.modelUrl),\n heatmapThreshold: options.heatmapThreshold,\n cacheModel: options.cacheModel,\n ortWasmPaths: resolveOrtWasmPaths(options.ortWasmPaths),\n }, [transferable])\n })\n}\n\nasync function analyzeCanvas(\n canvas: HTMLCanvasElement,\n options: ScanOptions,\n): Promise<DocumentDetectionResult> {\n const { width, height } = canvas\n const minDimension = options.minDimension ?? 360\n if (Math.min(width, height) < minDimension) {\n return {\n status: 'low-quality',\n confidence: 0,\n message: `Use an image at least ${minDimension}px on its shortest side.`,\n sourceWidth: width,\n sourceHeight: height,\n }\n }\n\n const analysisDimension = analysisDimensionForSource(\n width,\n height,\n options.maxAnalysisDimension,\n )\n const scale = Math.min(1, analysisDimension / Math.max(width, height))\n const sample = document.createElement('canvas')\n sample.width = Math.max(1, Math.round(width * scale))\n sample.height = Math.max(1, Math.round(height * scale))\n const context = sample.getContext('2d', { willReadFrequently: true })\n if (!context) throw canvasUnavailable()\n context.drawImage(canvas, 0, 0, sample.width, sample.height)\n const pixels = context.getImageData(0, 0, sample.width, sample.height).data\n let analysis: WorkerAnalysis\n if (options.useWorker !== false && typeof Worker !== 'undefined') {\n try {\n analysis = await analyzeInWorker(\n pixels,\n sample.width,\n sample.height,\n options,\n )\n } catch (error) {\n if (\n error instanceof ScannerError &&\n (error.code === 'worker' || error.code === 'model-http')\n ) {\n throw error\n }\n const message = error instanceof Error ? error.message : 'Document worker failed.'\n analysis = {\n sharpness: 20,\n detector: 'ml',\n modelStatus: 'failed',\n modelError: message,\n }\n }\n } else {\n analysis = {\n sharpness: 20,\n detector: 'ml',\n modelStatus: 'failed',\n modelError: 'ML detection requires a Web Worker.',\n }\n }\n const {\n sharpness,\n candidate,\n detector,\n modelStatus,\n modelProvider,\n modelError,\n inferenceMs,\n } = analysis\n const detectorMetadata = {\n detector,\n modelStatus,\n modelProvider,\n modelError,\n inferenceMs,\n }\n if (sharpness < MIN_DOCUMENT_SHARPNESS) {\n return {\n status: 'low-quality',\n confidence: Math.min(0.3, sharpness / 18),\n message: 'The image is too soft or dark to resolve four document edges.',\n sourceWidth: width,\n sourceHeight: height,\n ...detectorMetadata,\n }\n }\n\n if (!candidate) {\n return {\n status: 'no-document',\n confidence: 0,\n message: 'No document corners found. Place all four edges on a contrasting surface.',\n sourceWidth: width,\n sourceHeight: height,\n ...detectorMetadata,\n }\n }\n\n const corners = scaleCorners(candidate.corners, scale)\n const quad = toQuad(corners)\n const minimumConfidence = options.minConfidence ?? 0.58\n if (candidate.confidence < minimumConfidence) {\n return {\n status: 'low-confidence',\n quad,\n corners,\n confidence: candidate.confidence,\n message: 'Four possible corners were found, but the geometry is not reliable enough to crop.',\n sourceWidth: width,\n sourceHeight: height,\n ...detectorMetadata,\n }\n }\n return {\n status: 'success',\n quad,\n corners,\n confidence: candidate.confidence,\n message: 'Four document edges detected.',\n sourceWidth: width,\n sourceHeight: height,\n ...detectorMetadata,\n }\n}\n\nexport function perspectiveOutputSize(corners: DocumentCorners, maxDimension: number) {\n const naturalWidth = Math.max(\n 1,\n Math.round(Math.max(\n distance(corners.topLeft, corners.topRight),\n distance(corners.bottomLeft, corners.bottomRight),\n )),\n )\n const naturalHeight = Math.max(\n 1,\n Math.round(Math.max(\n distance(corners.topLeft, corners.bottomLeft),\n distance(corners.topRight, corners.bottomRight),\n )),\n )\n const outputScale = Math.min(1, maxDimension / Math.max(naturalWidth, naturalHeight))\n return {\n width: Math.max(1, Math.round(naturalWidth * outputScale)),\n height: Math.max(1, Math.round(naturalHeight * outputScale)),\n }\n}\n\nfunction perspectiveWarp(source: HTMLCanvasElement, corners: DocumentCorners, maxDimension: number) {\n const { width, height } = perspectiveOutputSize(corners, maxDimension)\n const sourceContext = source.getContext('2d', { willReadFrequently: true })\n if (!sourceContext) throw canvasUnavailable()\n const sourcePixels = sourceContext.getImageData(0, 0, source.width, source.height)\n const output = document.createElement('canvas')\n output.width = width\n output.height = height\n const outputContext = output.getContext('2d')\n if (!outputContext) throw canvasUnavailable()\n const outputPixels = outputContext.createImageData(width, height)\n const { topLeft: tl, topRight: tr, bottomRight: br, bottomLeft: bl } = corners\n const dx1 = tr.x - br.x\n const dx2 = bl.x - br.x\n const dy1 = tr.y - br.y\n const dy2 = bl.y - br.y\n const sx = tl.x - tr.x + br.x - bl.x\n const sy = tl.y - tr.y + br.y - bl.y\n const denominator = dx1 * dy2 - dx2 * dy1\n const projectiveX = Math.abs(denominator) < 0.0001 ? 0 : (sx * dy2 - dx2 * sy) / denominator\n const projectiveY = Math.abs(denominator) < 0.0001 ? 0 : (dx1 * sy - sx * dy1) / denominator\n const a = tr.x - tl.x + projectiveX * tr.x\n const b = bl.x - tl.x + projectiveY * bl.x\n const d = tr.y - tl.y + projectiveX * tr.y\n const e = bl.y - tl.y + projectiveY * bl.y\n\n for (let y = 0; y < height; y += 1) {\n const v = y / Math.max(1, height - 1)\n for (let x = 0; x < width; x += 1) {\n const u = x / Math.max(1, width - 1)\n const divisor = projectiveX * u + projectiveY * v + 1\n const sourceX = Math.max(0, Math.min(source.width - 1, Math.round((a * u + b * v + tl.x) / divisor)))\n const sourceY = Math.max(0, Math.min(source.height - 1, Math.round((d * u + e * v + tl.y) / divisor)))\n const sourceOffset = (sourceY * source.width + sourceX) * 4\n const outputOffset = (y * width + x) * 4\n outputPixels.data[outputOffset] = sourcePixels.data[sourceOffset]\n outputPixels.data[outputOffset + 1] = sourcePixels.data[sourceOffset + 1]\n outputPixels.data[outputOffset + 2] = sourcePixels.data[sourceOffset + 2]\n outputPixels.data[outputOffset + 3] = sourcePixels.data[sourceOffset + 3]\n }\n }\n outputContext.putImageData(outputPixels, 0, 0)\n return output\n}\n\n/**\n * Finds document corners. Returns `success`, `no-document`, `low-confidence`,\n * or `low-quality`. A bad image is one of those statuses and does not throw.\n * Inference or geometry failure is `modelStatus: 'failed'`, not a throw.\n *\n * @throws {LicenseError} LicenseError when the scan feature is not licensed. Detection does not start.\n * @throws {ScannerError} ScannerError `canvas` when canvas 2D is unavailable.\n * `worker` when the document worker cannot start.\n * `model-http` when the DocAligner file returns a failed HTTP response.\n */\nexport async function detectDocument(\n source: ImageSource,\n options: ScanOptions = {},\n): Promise<DocumentDetectionResult> {\n await assertLicense('scan')\n return analyzeCanvas(await sourceToCanvas(source, { cloneCanvas: false }), options)\n}\n\n/**\n * Perspective-crops `corners` onto a new canvas.\n * Resolves with `status: 'success'`. It does not score image quality.\n *\n * @throws {LicenseError} LicenseError when the scan feature is not licensed.\n * @throws {ScannerError} ScannerError `canvas` when canvas 2D is unavailable.\n */\nexport async function cropDocument(\n source: ImageSource,\n corners: DocumentCorners,\n options: Pick<ScanOptions, 'maxOutputDimension'> = {},\n): Promise<ScanResult> {\n await assertLicense('scan')\n const canvas = await sourceToCanvas(source, { cloneCanvas: false })\n const maxOutputDimension = options.maxOutputDimension ?? (isMobileClassDevice() ? 2048 : 4096)\n return {\n status: 'success',\n corners,\n quad: toQuad(corners),\n confidence: 1,\n message: 'Captured with the document edges shown in the finder.',\n sourceWidth: canvas.width,\n sourceHeight: canvas.height,\n canvas: perspectiveWarp(canvas, corners, maxOutputDimension),\n }\n}\n\n/**\n * Detects a document and perspective-crops it.\n * Returns `success`, `no-document`, `low-confidence`, or `low-quality`.\n * A bad image is one of those statuses and does not throw.\n * Inference or geometry failure is `modelStatus: 'failed'`, not a throw.\n *\n * @throws {LicenseError} LicenseError when the scan feature is not licensed. Detection does not start.\n * @throws {ScannerError} ScannerError `canvas` when canvas 2D is unavailable.\n * `worker` when the document worker cannot start.\n * `model-http` when the DocAligner file returns a failed HTTP response.\n */\nexport async function scanDocument(\n source: ImageSource,\n options: ScanOptions = {},\n): Promise<ScanResult> {\n await assertLicense('scan')\n const canvas = await sourceToCanvas(source, { cloneCanvas: false })\n const detection = await analyzeCanvas(canvas, options)\n if (detection.status !== 'success' || !detection.corners) return detection\n const maxOutputDimension = options.maxOutputDimension ?? (isMobileClassDevice() ? 2048 : 4096)\n return {\n ...detection,\n canvas: perspectiveWarp(canvas, detection.corners, maxOutputDimension),\n message: 'Four document edges detected and perspective-corrected.',\n }\n}\n","import { canvasUnavailable, ScannerError } from './errors'\nimport { assertLicense } from './license'\n\nexport interface CameraOptions {\n facingMode?: 'environment' | 'user'\n idealWidth?: number\n idealHeight?: number\n maxWidth?: number\n /**\n * Hard `getUserMedia` height cap. On Android Chrome the SDK prefers a\n * portrait ideal (1080×1920) and applies this only as `height.max` (default\n * 1920). It does not copy the cap onto `width.max` — that pair collapsed to\n * a 1920×1920 square stream. Capture stills stay at the negotiated size.\n * Hosts should not set this to work around Android 4K.\n */\n maxHeight?: number\n maxFrameRate?: number\n /** Rear-camera torch policy. Defaults to `alwaysOff`. */\n torch?: TorchMode\n}\n\nexport type TorchMode =\n | 'defaultOn'\n | 'defaultOff'\n | 'alwaysOn'\n | 'alwaysOff'\n | 'auto'\n\nexport interface TorchStatus {\n mode: TorchMode\n supported: boolean\n on: boolean\n /** Whether the camera UI should show a torch control. */\n visible: boolean\n /** Whether an end user can change the control with `setTorch()`. */\n mutable: boolean\n /** True when luminance hysteresis, rather than an end user, owns the state. */\n automatic: boolean\n}\n\nexport interface CameraSession {\n stream: MediaStream\n readonly torchMode: TorchMode\n readonly torchSupported: boolean\n readonly torchOn: boolean\n capture: (maxDimension?: number) => HTMLCanvasElement\n capturePhoto: () => Promise<CameraPhoto>\n getSettings: () => MediaTrackSettings\n getDiagnostics: () => CameraDiagnostics\n getTorchStatus: () => TorchStatus\n /**\n * Changes torch state only for `defaultOn` and `defaultOff`.\n * Returns false, without throwing, for unsupported or immutable modes.\n */\n setTorch: (enabled: boolean) => Promise<boolean>\n stop: () => void\n}\n\nexport type CapturePath = 'video-frame' | 'live-mirror'\n\nexport interface CameraPhoto {\n frame: HTMLCanvasElement\n method: CapturePath\n settings: MediaTrackSettings\n fallbackReason?: 'video-frame-empty'\n luminance: number\n diagnostics: CameraDiagnostics\n}\n\nexport interface CameraDiagnostics {\n videoWidth: number\n videoHeight: number\n readyState: number\n paused: boolean\n connected: boolean\n rendered: boolean\n trackReadyState: MediaStreamTrackState | 'missing'\n trackEnabled: boolean\n trackMuted: boolean\n liveLuminance: number\n mirrorLuminance: number\n mirrorAgeMs: number\n /**\n * Whether the browser exposes `ImageCapture`. Reported for support triage\n * only: capture never calls `takePhoto()`. WebKit exposes the constructor\n * but returns an all-black still from it.\n */\n hasImageCapture: boolean\n torchMode: TorchMode\n torchSupported: boolean\n torchOn: boolean\n torch: TorchStatus\n engine: BrowserEngine\n}\n\nexport interface CaptureDiagnosticsReport {\n capturedAt?: string\n error?: string\n captureMethod?: CapturePath\n luminance?: number\n fallbackReason?: CameraPhoto['fallbackReason']\n shutter?: CameraDiagnostics\n live?: CameraDiagnostics\n finder?: {\n state?: string\n confidence?: number\n stableFrames?: number\n requiredStableFrames?: number\n detector?: string\n modelStatus?: string\n sourceWidth?: number\n sourceHeight?: number\n }\n}\n\nfunction formatDiagnosticsBlock(label: string, diagnostics: CameraDiagnostics) {\n const { engine } = diagnostics\n return [\n `${label}:`,\n ` engine: ${engine.engine}/${engine.browser}${engine.iosWebKit ? ' ios-webkit' : ''}`,\n ` ua: ${engine.userAgent}`,\n ` video: ${diagnostics.videoWidth}x${diagnostics.videoHeight} readyState=${diagnostics.readyState}${diagnostics.paused ? ' paused' : ''}${diagnostics.rendered ? '' : ' hidden'}${diagnostics.connected ? '' : ' disconnected'}`,\n ` track: ${diagnostics.trackReadyState}${diagnostics.trackEnabled ? '' : ' disabled'}${diagnostics.trackMuted ? ' muted' : ''}`,\n ` liveLuma: ${diagnostics.liveLuminance.toFixed(1)}`,\n ` mirrorLuma: ${diagnostics.mirrorLuminance.toFixed(1)}`,\n ` mirrorAgeMs: ${Number.isFinite(diagnostics.mirrorAgeMs) ? Math.round(diagnostics.mirrorAgeMs) : 'none'}`,\n ` hasImageCapture: ${diagnostics.hasImageCapture} (never used)`,\n ` torch: ${diagnostics.torch.mode} supported=${diagnostics.torch.supported} on=${diagnostics.torch.on}`,\n ].join('\\n')\n}\n\n/** Plain-text dump safe to paste into chat or a ticket. */\nexport function formatCaptureDiagnosticsReport(report: CaptureDiagnosticsReport) {\n const lines = [\n 'Exige scanner capture report',\n `time: ${report.capturedAt ?? new Date().toISOString()}`,\n ]\n if (report.error) lines.push(`error: ${report.error}`)\n if (report.captureMethod) lines.push(`method: ${report.captureMethod}`)\n if (report.luminance !== undefined) lines.push(`luminance: ${report.luminance.toFixed(1)}`)\n if (report.fallbackReason) lines.push(`fallback: ${report.fallbackReason}`)\n if (report.shutter) lines.push(formatDiagnosticsBlock('shutter', report.shutter))\n if (report.live) lines.push(formatDiagnosticsBlock('live', report.live))\n if (report.finder) {\n const finder = report.finder\n lines.push(\n [\n 'finder:',\n ` state: ${finder.state ?? 'unknown'}`,\n ` confidence: ${finder.confidence === undefined ? '—' : finder.confidence.toFixed(3)}`,\n ` stable: ${finder.stableFrames ?? '—'}/${finder.requiredStableFrames ?? '—'}`,\n ` detector: ${finder.detector ?? '—'} ${finder.modelStatus ?? ''}`.trim(),\n ` source: ${finder.sourceWidth ?? '—'}x${finder.sourceHeight ?? '—'}`,\n ].join('\\n'),\n )\n }\n return `${lines.join('\\n')}\\n`\n}\n\nexport interface BrowserEngine {\n /** Engine actually executing, not the vendor shell around it. */\n engine: 'webkit' | 'blink' | 'gecko' | 'unknown'\n /** Vendor shell, which on iOS is only a wrapper around WebKit. */\n browser: string\n iosWebKit: boolean\n userAgent: string\n}\n\n/**\n * Identifies the rendering engine by capability plus the vendor shell by name.\n * Every iOS browser is WebKit, so behavior must never be gated on Safari alone.\n */\nexport function detectBrowserEngine(\n userAgent = typeof navigator === 'undefined' ? '' : navigator.userAgent,\n maxTouchPoints = typeof navigator === 'undefined' ? 0 : navigator.maxTouchPoints,\n): BrowserEngine {\n const browser = /CriOS|Chrome/i.test(userAgent)\n ? 'chrome'\n : /EdgiOS|Edg/i.test(userAgent)\n ? 'edge'\n : /FxiOS|Firefox/i.test(userAgent)\n ? 'firefox'\n : /Safari/i.test(userAgent)\n ? 'safari'\n : 'unknown'\n const iosDevice = /iPhone|iPad|iPod/i.test(userAgent) ||\n (/Macintosh/i.test(userAgent) && maxTouchPoints > 1)\n const iosShell = /CriOS|EdgiOS|FxiOS|OPiOS|Mercury/i.test(userAgent)\n const iosWebKit = iosDevice || iosShell\n const engine = iosWebKit || (/AppleWebKit/i.test(userAgent) && !/Chrome|Chromium|Edg/i.test(userAgent))\n ? 'webkit'\n : /Chrome|Chromium|Edg/i.test(userAgent)\n ? 'blink'\n : /Gecko\\//i.test(userAgent)\n ? 'gecko'\n : 'unknown'\n return { engine, browser, iosWebKit, userAgent }\n}\n\n/** Android Chrome preview: prefer portrait so a tall receipt keeps four edges. */\nexport const ANDROID_CHROME_PREVIEW_IDEAL_WIDTH = 1080\nexport const ANDROID_CHROME_PREVIEW_IDEAL_HEIGHT = 1920\n/**\n * Height cap only. 0.2.14 set the same max on width and height (and clipped\n * both ideals to 1920), so Chrome granted a 1920×1920 square stream.\n */\nexport const ANDROID_CHROME_PREVIEW_MAX_HEIGHT = 1920\n/** @deprecated Same value as `ANDROID_CHROME_PREVIEW_MAX_HEIGHT`. */\nexport const ANDROID_CHROME_PREVIEW_MAX_EDGE = ANDROID_CHROME_PREVIEW_MAX_HEIGHT\n/** Finder analysis cap for the same engine. Capture stills stay unscaled. */\nexport const ANDROID_CHROME_FINDER_MAX_FRAME_DIMENSION = 1280\n\n/**\n * True only for Chrome on Android. iOS Chrome is WebKit and must not match.\n * Other Android browsers that mention Chrome in their UA are excluded.\n */\nexport function isAndroidChrome(engine?: BrowserEngine) {\n const detected = engine ?? detectBrowserEngine()\n return !detected.iosWebKit &&\n detected.browser === 'chrome' &&\n /Android/i.test(detected.userAgent) &&\n !/Edg|OPR|SamsungBrowser/i.test(detected.userAgent)\n}\n\n/** Mean luminance below this is treated as an empty/black frame. */\nexport const NEAR_BLACK_LUMINANCE = 10\n\nexport interface AutoTorchOptions {\n /** Luminance at or below which dark samples accumulate. */\n turnOnLuminance?: number\n /** Luminance at or above which bright samples accumulate. */\n turnOffLuminance?: number\n /** Consecutive dark samples required before enabling the torch. */\n darkSamples?: number\n /** Consecutive bright samples required before disabling the torch. */\n brightSamples?: number\n}\n\n/**\n * Stateful automatic torch policy. The wide threshold gap and consecutive\n * sample counts prevent exposure changes and hand movement from flickering the\n * LED. `update()` returns a new requested state only when the state changes.\n */\nexport class AutoTorchController {\n private on = false\n private darkCount = 0\n private brightCount = 0\n private readonly turnOnLuminance: number\n private readonly turnOffLuminance: number\n private readonly darkSamples: number\n private readonly brightSamples: number\n\n constructor(options: AutoTorchOptions = {}) {\n this.turnOnLuminance = options.turnOnLuminance ?? 62\n this.turnOffLuminance = options.turnOffLuminance ?? 155\n this.darkSamples = options.darkSamples ?? 3\n this.brightSamples = options.brightSamples ?? 8\n }\n\n update(luminance: number) {\n if (!Number.isFinite(luminance) || luminance <= NEAR_BLACK_LUMINANCE) {\n this.darkCount = 0\n this.brightCount = 0\n return undefined\n }\n if (!this.on) {\n this.brightCount = 0\n this.darkCount = luminance <= this.turnOnLuminance ? this.darkCount + 1 : 0\n if (this.darkCount < this.darkSamples) return undefined\n this.darkCount = 0\n this.on = true\n return true\n }\n this.darkCount = 0\n this.brightCount = luminance >= this.turnOffLuminance ? this.brightCount + 1 : 0\n if (this.brightCount < this.brightSamples) return undefined\n this.brightCount = 0\n this.on = false\n return false\n }\n\n getState() {\n return this.on\n }\n}\n\nexport function torchControl(\n mode: TorchMode,\n supported: boolean,\n): TorchStatus {\n if (!supported) {\n return {\n mode,\n supported: false,\n on: false,\n visible: false,\n mutable: false,\n automatic: mode === 'auto',\n }\n }\n if (mode === 'alwaysOn' || mode === 'alwaysOff') {\n return {\n mode,\n supported: true,\n on: mode === 'alwaysOn',\n visible: false,\n mutable: false,\n automatic: false,\n }\n }\n return {\n mode,\n supported: true,\n on: mode === 'defaultOn',\n visible: true,\n mutable: mode !== 'auto',\n automatic: mode === 'auto',\n }\n}\n\nexport function meanFrameLuminance(pixels: Uint8ClampedArray) {\n const pixelCount = Math.floor(pixels.length / 4)\n if (!pixelCount) return 0\n let luminance = 0\n for (let offset = 0; offset < pixelCount * 4; offset += 4) {\n luminance += pixels[offset] * 0.299 +\n pixels[offset + 1] * 0.587 +\n pixels[offset + 2] * 0.114\n }\n return luminance / pixelCount\n}\n\nexport function isNearBlackFrame(\n pixels: Uint8ClampedArray,\n blackThreshold = NEAR_BLACK_LUMINANCE,\n) {\n if (pixels.length < 4) return true\n const pixelCount = Math.floor(pixels.length / 4)\n let visiblePixels = 0\n for (let offset = 0; offset < pixelCount * 4; offset += 4) {\n const value = pixels[offset] * 0.299 +\n pixels[offset + 1] * 0.587 +\n pixels[offset + 2] * 0.114\n if (value > blackThreshold * 2) visiblePixels += 1\n }\n return meanFrameLuminance(pixels) <= blackThreshold &&\n visiblePixels / pixelCount < 0.01\n}\n\nfunction sampleCanvasLuminance(source: CanvasImageSource, width: number, height: number) {\n if (!width || !height) return 0\n const sample = document.createElement('canvas')\n sample.width = Math.min(32, width)\n sample.height = Math.min(32, height)\n const context = sample.getContext('2d', { willReadFrequently: true })\n if (!context) return 0\n context.drawImage(source, 0, 0, sample.width, sample.height)\n return meanFrameLuminance(context.getImageData(0, 0, sample.width, sample.height).data)\n}\n\nfunction canvasLuminance(canvas: HTMLCanvasElement) {\n return sampleCanvasLuminance(canvas, canvas.width, canvas.height)\n}\n\ntype VideoFrameCallbackElement = HTMLVideoElement & Partial<{\n requestVideoFrameCallback: (callback: () => void) => number\n cancelVideoFrameCallback: (handle: number) => void\n}>\n\n/**\n * Keeps an offscreen copy of the most recent non-black video frame. WebKit can\n * blank a `<video>` at the moment of a tap, teardown, or compositing change, so\n * capture must not depend on the pixels available at that exact instant.\n */\nfunction startFrameMirror(video: VideoFrameCallbackElement, minIntervalMs = 120) {\n const canvas = document.createElement('canvas')\n const context = canvas.getContext('2d')\n const supportsFrameCallback = typeof video.requestVideoFrameCallback === 'function'\n let running = true\n let handle = 0\n let lastCopyAt = 0\n let lastGoodAt = 0\n let liveLuminance = 0\n let mirrorLuminance = 0\n\n const schedule = () => {\n if (!running) return\n handle = supportsFrameCallback\n ? video.requestVideoFrameCallback!(grab)\n : requestAnimationFrame(grab)\n }\n\n function grab() {\n if (!running) return\n const { videoWidth, videoHeight } = video\n const now = performance.now()\n if (context && videoWidth && videoHeight && now - lastCopyAt >= minIntervalMs) {\n lastCopyAt = now\n liveLuminance = sampleCanvasLuminance(video, videoWidth, videoHeight)\n if (liveLuminance > NEAR_BLACK_LUMINANCE) {\n if (canvas.width !== videoWidth || canvas.height !== videoHeight) {\n canvas.width = videoWidth\n canvas.height = videoHeight\n }\n context.drawImage(video, 0, 0, videoWidth, videoHeight)\n mirrorLuminance = liveLuminance\n lastGoodAt = now\n }\n }\n schedule()\n }\n\n schedule()\n return {\n stop() {\n running = false\n if (supportsFrameCallback) video.cancelVideoFrameCallback?.(handle)\n else cancelAnimationFrame(handle)\n },\n getFrame: () => lastGoodAt ? canvas : undefined,\n getLiveLuminance: () => liveLuminance,\n getMirrorLuminance: () => mirrorLuminance,\n getMirrorAgeMs: () => lastGoodAt ? performance.now() - lastGoodAt : Infinity,\n }\n}\n\nfunction cloneFrame(source: HTMLCanvasElement) {\n const copy = document.createElement('canvas')\n copy.width = source.width\n copy.height = source.height\n copy.getContext('2d')?.drawImage(source, 0, 0)\n return copy\n}\n\nexport function previewMaxEdge(\n options: CameraOptions = {},\n engine = detectBrowserEngine(),\n) {\n if (options.maxHeight) return options.maxHeight\n if (options.maxWidth) return options.maxWidth\n if (isAndroidChrome(engine)) return ANDROID_CHROME_PREVIEW_MAX_HEIGHT\n return undefined\n}\n\nexport function previewMaxHeight(\n options: CameraOptions = {},\n engine = detectBrowserEngine(),\n) {\n return previewMaxEdge(options, engine)\n}\n\nexport function mobileCameraConstraints(\n options: CameraOptions = {},\n engine = detectBrowserEngine(),\n): MediaStreamConstraints {\n const androidChrome = isAndroidChrome(engine)\n const idealWidth = options.idealWidth ?? (\n androidChrome ? ANDROID_CHROME_PREVIEW_IDEAL_WIDTH : 3840\n )\n const idealHeight = options.idealHeight ?? (\n androidChrome ? ANDROID_CHROME_PREVIEW_IDEAL_HEIGHT : 2160\n )\n const width: ConstrainULongRange = { ideal: idealWidth }\n const height: ConstrainULongRange = { ideal: idealHeight }\n if (options.maxWidth) width.max = options.maxWidth\n if (options.maxHeight) height.max = options.maxHeight\n else if (androidChrome && options.maxWidth === undefined) {\n height.max = ANDROID_CHROME_PREVIEW_MAX_HEIGHT\n }\n return {\n audio: false,\n video: {\n facingMode: { ideal: options.facingMode ?? 'environment' },\n width,\n height,\n frameRate: { ideal: options.maxFrameRate ?? 30, max: options.maxFrameRate ?? 30 },\n },\n }\n}\n\n/** Long-edge cap that keeps the source aspect. A 1080×1920 preview at 1280 stays 720×1280. */\nexport function scaledFrameSize(\n width: number,\n height: number,\n maxDimension?: number,\n) {\n const scale = maxDimension\n ? Math.min(1, maxDimension / Math.max(width, height))\n : 1\n return {\n width: Math.max(1, Math.round(width * scale)),\n height: Math.max(1, Math.round(height * scale)),\n }\n}\n\nexport function captureVideoFrame(video: HTMLVideoElement, maxDimension?: number) {\n if (!video.videoWidth || !video.videoHeight) {\n throw new Error('The camera is not ready to capture a frame.')\n }\n const size = scaledFrameSize(video.videoWidth, video.videoHeight, maxDimension)\n const canvas = document.createElement('canvas')\n canvas.width = size.width\n canvas.height = size.height\n const context = canvas.getContext('2d')\n if (!context) throw canvasUnavailable()\n context.drawImage(video, 0, 0, canvas.width, canvas.height)\n return canvas\n}\n\nfunction cameraConstraintCandidates(options: CameraOptions) {\n const engine = detectBrowserEngine()\n if (options.idealWidth || options.idealHeight || options.maxWidth || options.maxHeight) {\n return [mobileCameraConstraints(options, engine)]\n }\n if (isAndroidChrome(engine)) {\n return [\n mobileCameraConstraints({\n ...options,\n idealWidth: ANDROID_CHROME_PREVIEW_IDEAL_WIDTH,\n idealHeight: ANDROID_CHROME_PREVIEW_IDEAL_HEIGHT,\n }, engine),\n mobileCameraConstraints({ ...options, idealWidth: 720, idealHeight: 1280 }, engine),\n mobileCameraConstraints({ ...options, idealWidth: 1920, idealHeight: 1080 }, engine),\n ]\n }\n return [\n mobileCameraConstraints({ ...options, idealWidth: 3840, idealHeight: 2160 }, engine),\n mobileCameraConstraints({ ...options, idealWidth: 2560, idealHeight: 1440 }, engine),\n mobileCameraConstraints({ ...options, idealWidth: 1920, idealHeight: 1080 }, engine),\n ]\n}\n\n/**\n * Opens the rear camera on `video`.\n *\n * @throws {LicenseError} LicenseError when scan is not licensed. Torch mode other than\n * `alwaysOff` also requires the torch feature. The camera does not start.\n * @throws {ScannerError} ScannerError `secure-context` when the page is not HTTPS.\n * `localhost` is allowed. `canvas` when a captured frame cannot get canvas 2D.\n */\nexport async function startCamera(\n video: HTMLVideoElement,\n options: CameraOptions = {},\n): Promise<CameraSession> {\n await assertLicense('scan')\n const torchMode = options.torch ?? 'alwaysOff'\n if (torchMode !== 'alwaysOff') await assertLicense('torch')\n if (!window.isSecureContext && location.hostname !== 'localhost') {\n throw new ScannerError('secure-context', 'Camera access requires HTTPS.')\n }\n if (!navigator.mediaDevices?.getUserMedia) {\n throw new Error('Live camera access is unavailable. Use the native camera picker instead.')\n }\n video.muted = true\n video.autoplay = true\n video.playsInline = true\n video.setAttribute('playsinline', '')\n let stream: MediaStream | undefined\n let resolutionError: unknown\n for (const constraints of cameraConstraintCandidates(options)) {\n try {\n stream = await navigator.mediaDevices.getUserMedia(constraints)\n break\n } catch (cause) {\n resolutionError = cause\n if (!(cause instanceof DOMException) || cause.name !== 'OverconstrainedError') throw cause\n }\n }\n if (!stream) throw resolutionError ?? new Error('No rear camera resolution is available.')\n video.srcObject = stream\n await video.play()\n const track = stream.getVideoTracks()[0]\n if (!track) {\n for (const streamTrack of stream.getTracks()) streamTrack.stop()\n throw new Error('The camera did not provide a video track.')\n }\n const mirror = startFrameMirror(video)\n const hasImageCapture = 'ImageCapture' in globalThis\n const capabilities = typeof track.getCapabilities === 'function'\n ? track.getCapabilities() as MediaTrackCapabilities & { torch?: boolean }\n : undefined\n let torchStatus = torchControl(torchMode, capabilities?.torch === true)\n let torchUpdatePending = false\n const applyTorch = async (enabled: boolean) => {\n if (!torchStatus.supported || track.readyState !== 'live') return false\n try {\n await track.applyConstraints({\n advanced: [{ torch: enabled } as MediaTrackConstraintSet],\n })\n torchStatus = { ...torchStatus, on: enabled }\n return true\n } catch {\n // Some browsers report a torch capability but reject its constraint.\n // Fail closed and hide the control without disturbing the live track.\n torchStatus = {\n ...torchStatus,\n supported: false,\n on: false,\n visible: false,\n mutable: false,\n }\n return false\n }\n }\n\n if (torchStatus.on) await applyTorch(true)\n\n const autoTorch = torchMode === 'auto' && torchStatus.supported\n ? new AutoTorchController()\n : undefined\n const autoTorchTimer = autoTorch\n ? window.setInterval(() => {\n if (torchUpdatePending || !torchStatus.supported) return\n const requested = autoTorch.update(mirror.getLiveLuminance())\n if (requested === undefined || requested === torchStatus.on) return\n torchUpdatePending = true\n void applyTorch(requested).finally(() => {\n torchUpdatePending = false\n })\n }, 350)\n : 0\n\n const diagnostics = (): CameraDiagnostics => {\n const bounds = video.getBoundingClientRect()\n return {\n videoWidth: video.videoWidth,\n videoHeight: video.videoHeight,\n readyState: video.readyState,\n paused: video.paused,\n connected: video.isConnected,\n rendered: bounds.width > 0 && bounds.height > 0,\n trackReadyState: track.readyState ?? 'missing',\n trackEnabled: track.enabled,\n trackMuted: track.muted,\n liveLuminance: mirror.getLiveLuminance(),\n mirrorLuminance: mirror.getMirrorLuminance(),\n mirrorAgeMs: mirror.getMirrorAgeMs(),\n hasImageCapture,\n torchMode: torchStatus.mode,\n torchSupported: torchStatus.supported,\n torchOn: torchStatus.on,\n torch: { ...torchStatus },\n engine: detectBrowserEngine(),\n }\n }\n\n return {\n stream,\n get torchMode() {\n return torchStatus.mode\n },\n get torchSupported() {\n return torchStatus.supported\n },\n get torchOn() {\n return torchStatus.on\n },\n capture: (maxDimension) => captureVideoFrame(video, maxDimension),\n // The document capture path never calls `ImageCapture.takePhoto()`. WebKit\n // exposes the constructor and resolves it with an all-black still, and the\n // preview frames are already the negotiated stream size. Android Chrome\n // prefers a portrait getUserMedia ideal; this still copies that stream unscaled.\n async capturePhoto() {\n // Copy before any await: WebKit can blank the element during the tap\n // that triggers capture, so fall back to the last known-good frame.\n let liveFrame: HTMLCanvasElement | undefined\n let liveLuminance = 0\n try {\n liveFrame = captureVideoFrame(video)\n liveLuminance = canvasLuminance(liveFrame)\n } catch {\n liveFrame = undefined\n }\n const mirrorFrame = mirror.getFrame()\n const usableLive = liveFrame && liveLuminance > NEAR_BLACK_LUMINANCE\n ? liveFrame\n : undefined\n const snapshot = usableLive ?? (mirrorFrame ? cloneFrame(mirrorFrame) : undefined)\n if (!snapshot) {\n throw new Error(\n 'The camera preview produced no visible pixels. Keep the scanner on screen, wait for the preview, and retake.',\n )\n }\n return {\n frame: snapshot,\n method: usableLive ? 'video-frame' : 'live-mirror',\n settings: track.getSettings(),\n fallbackReason: usableLive ? undefined : 'video-frame-empty',\n luminance: usableLive ? liveLuminance : mirror.getMirrorLuminance(),\n diagnostics: diagnostics(),\n }\n },\n getSettings: () => track.getSettings(),\n getDiagnostics: diagnostics,\n getTorchStatus: () => ({ ...torchStatus }),\n async setTorch(enabled) {\n if (!torchStatus.mutable) return false\n return applyTorch(enabled)\n },\n stop() {\n if (autoTorchTimer) window.clearInterval(autoTorchTimer)\n mirror.stop()\n for (const track of stream.getTracks()) track.stop()\n if (video.srcObject === stream) video.srcObject = null\n },\n }\n}\n","import { scaledFrameSize } from './camera'\nimport { canvasUnavailable } from './errors'\n\nexport interface CoverCrop {\n sx: number\n sy: number\n sw: number\n sh: number\n}\n\n/**\n * The overlay box the user is looking at. Prefer the parent so a later\n * layout tweak on the video element cannot change which pixels are analyzed.\n */\nexport function viewfinderBox(element: HTMLElement) {\n const stage = element.parentElement\n const stageBox = stage?.getBoundingClientRect()\n if (stageBox && stageBox.width > 0 && stageBox.height > 0) return stageBox\n return element.getBoundingClientRect()\n}\n\n/**\n * Center crop matching `object-fit: cover`. A 1920×1080 buffer in a portrait\n * viewfinder loses the left and right, which is the upright image already on\n * screen. The pixels are not rotated: Android Chrome paints the preview\n * upright even when `videoWidth` × `videoHeight` stay landscape.\n */\nexport function coverCropRect(\n frameWidth: number,\n frameHeight: number,\n viewportWidth: number,\n viewportHeight: number,\n): CoverCrop {\n const frameW = Math.max(1, frameWidth)\n const frameH = Math.max(1, frameHeight)\n if (viewportWidth <= 0 || viewportHeight <= 0) {\n return { sx: 0, sy: 0, sw: frameW, sh: frameH }\n }\n const frameAspect = frameW / frameH\n const viewAspect = viewportWidth / viewportHeight\n if (frameAspect > viewAspect) {\n const sw = frameH * viewAspect\n return { sx: (frameW - sw) / 2, sy: 0, sw, sh: frameH }\n }\n const sh = frameW / viewAspect\n return { sx: 0, sy: (frameH - sh) / 2, sw: frameW, sh }\n}\n\n/** Long-edge cap of the cover crop. A 9:16 crop of 1920×1080 is already 608×1080. */\nexport function coverAnalysisSize(\n frameWidth: number,\n frameHeight: number,\n viewportWidth: number,\n viewportHeight: number,\n maxDimension?: number,\n) {\n const crop = coverCropRect(frameWidth, frameHeight, viewportWidth, viewportHeight)\n return {\n crop,\n size: scaledFrameSize(crop.sw, crop.sh, maxDimension),\n }\n}\n\nexport function drawVisibleFrame(\n source: CanvasImageSource,\n sourceWidth: number,\n sourceHeight: number,\n viewportWidth: number,\n viewportHeight: number,\n maxDimension?: number,\n) {\n const { crop, size } = coverAnalysisSize(\n sourceWidth,\n sourceHeight,\n viewportWidth,\n viewportHeight,\n maxDimension,\n )\n const canvas = document.createElement('canvas')\n canvas.width = size.width\n canvas.height = size.height\n const context = canvas.getContext('2d')\n if (!context) throw canvasUnavailable()\n context.drawImage(\n source,\n crop.sx,\n crop.sy,\n crop.sw,\n crop.sh,\n 0,\n 0,\n size.width,\n size.height,\n )\n return canvas\n}\n","import type { DocumentQuad } from './types'\n\nexport interface CastShadowRegion {\n x: number\n y: number\n width: number\n height: number\n}\n\nexport interface CastShadowAnalysis {\n strong: boolean\n strength: number\n darkness: number\n areaRatio: number\n region?: CastShadowRegion\n}\n\nfunction percentile(values: number[], fraction: number) {\n if (!values.length) return 0\n const sorted = [...values].sort((first, second) => first - second)\n return sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * fraction))]\n}\n\n/**\n * Finds a connected, page-sized dark blob in any direction. A component must\n * cover meaningful area and contain local contrast, distinguishing cast\n * shadows over printed paper from a dark border or isolated illustration.\n */\nexport function analyzeCastShadowLuminance(\n luminance: Uint8Array,\n width: number,\n height: number,\n gridSize = 12,\n): CastShadowAnalysis {\n if (!width || !height || luminance.length < width * height) {\n return { strong: false, strength: 0, darkness: 0, areaRatio: 0 }\n }\n const columns = Math.min(gridSize, width)\n const rows = Math.min(gridSize, height)\n const cells: Array<{ mean: number; deviation: number }> = []\n for (let row = 0; row < rows; row += 1) {\n const top = Math.floor(row * height / rows)\n const bottom = Math.max(top + 1, Math.floor((row + 1) * height / rows))\n for (let column = 0; column < columns; column += 1) {\n const left = Math.floor(column * width / columns)\n const right = Math.max(left + 1, Math.floor((column + 1) * width / columns))\n let sum = 0\n let squared = 0\n let count = 0\n for (let y = top; y < bottom; y += 1) {\n for (let x = left; x < right; x += 1) {\n const value = luminance[y * width + x]\n sum += value\n squared += value * value\n count += 1\n }\n }\n const mean = sum / count\n cells.push({\n mean,\n deviation: Math.sqrt(Math.max(0, squared / count - mean * mean)),\n })\n }\n }\n\n const brightPaper = percentile(cells.map((cell) => cell.mean), 0.8)\n const dark = cells.map((cell) =>\n brightPaper - cell.mean >= 24 &&\n cell.mean >= 35,\n )\n const visited = new Uint8Array(cells.length)\n const components: number[][] = []\n for (let start = 0; start < cells.length; start += 1) {\n if (!dark[start] || visited[start]) continue\n const component: number[] = []\n const queue = [start]\n visited[start] = 1\n while (queue.length) {\n const index = queue.shift()!\n component.push(index)\n const row = Math.floor(index / columns)\n const column = index % columns\n for (const [nextColumn, nextRow] of [\n [column - 1, row],\n [column + 1, row],\n [column, row - 1],\n [column, row + 1],\n ]) {\n if (\n nextColumn < 0 ||\n nextColumn >= columns ||\n nextRow < 0 ||\n nextRow >= rows\n ) continue\n const next = nextRow * columns + nextColumn\n if (dark[next] && !visited[next]) {\n visited[next] = 1\n queue.push(next)\n }\n }\n }\n components.push(component)\n }\n\n let best: CastShadowAnalysis = {\n strong: false,\n strength: 0,\n darkness: 0,\n areaRatio: 0,\n }\n for (const component of components) {\n const areaRatio = component.length / cells.length\n if (areaRatio < 0.06 || areaRatio > 0.75) continue\n const darkness = component.reduce(\n (total, index) => total + brightPaper - cells[index].mean,\n 0,\n ) / component.length\n const printedCells = component.filter((index) => cells[index].deviation >= 9).length\n const printRatio = printedCells / component.length\n if (printRatio < 0.08 && darkness < 42) continue\n const columnsInComponent = component.map((index) => index % columns)\n const rowsInComponent = component.map((index) => Math.floor(index / columns))\n const minColumn = Math.min(...columnsInComponent)\n const maxColumn = Math.max(...columnsInComponent)\n const minRow = Math.min(...rowsInComponent)\n const maxRow = Math.max(...rowsInComponent)\n const padding = 1\n const left = Math.max(0, minColumn - padding) / columns\n const top = Math.max(0, minRow - padding) / rows\n const right = Math.min(columns, maxColumn + padding + 1) / columns\n const bottom = Math.min(rows, maxRow + padding + 1) / rows\n const strength = darkness * Math.sqrt(areaRatio) * (0.75 + Math.min(0.25, printRatio))\n if (strength > best.strength) {\n best = {\n strong: strength >= 10,\n strength,\n darkness,\n areaRatio,\n region: {\n x: left,\n y: top,\n width: right - left,\n height: bottom - top,\n },\n }\n }\n }\n return best\n}\n\nexport function flattenIlluminationLuminance(\n luminance: Uint8Array,\n width: number,\n height: number,\n radius = Math.max(12, Math.round(Math.max(width, height) / 32)),\n) {\n const stride = width + 1\n const integral = new Uint32Array((width + 1) * (height + 1))\n for (let y = 1; y <= height; y += 1) {\n let row = 0\n for (let x = 1; x <= width; x += 1) {\n row += luminance[(y - 1) * width + x - 1]\n integral[y * stride + x] = integral[(y - 1) * stride + x] + row\n }\n }\n const output = new Uint8Array(luminance.length)\n for (let y = 0; y < height; y += 1) {\n const top = Math.max(0, y - radius)\n const bottom = Math.min(height, y + radius + 1)\n for (let x = 0; x < width; x += 1) {\n const left = Math.max(0, x - radius)\n const right = Math.min(width, x + radius + 1)\n const area = (right - left) * (bottom - top)\n const background = (\n integral[bottom * stride + right] -\n integral[top * stride + right] -\n integral[bottom * stride + left] +\n integral[top * stride + left]\n ) / area\n output[y * width + x] = Math.max(\n 0,\n Math.min(255, Math.round(luminance[y * width + x] * 235 / Math.max(24, background))),\n )\n }\n }\n return output\n}\n\nfunction quadBounds(quad: DocumentQuad, width: number, height: number) {\n const points = [quad.topLeft, quad.topRight, quad.bottomRight, quad.bottomLeft]\n const left = Math.max(0, Math.min(...points.map((point) => point.x)))\n const top = Math.max(0, Math.min(...points.map((point) => point.y)))\n const right = Math.min(width, Math.max(...points.map((point) => point.x)))\n const bottom = Math.min(height, Math.max(...points.map((point) => point.y)))\n return { left, top, width: right - left, height: bottom - top }\n}\n\nexport function analyzeCanvasCastShadow(\n canvas: HTMLCanvasElement,\n quad: DocumentQuad,\n): CastShadowAnalysis {\n const bounds = quadBounds(quad, canvas.width, canvas.height)\n if (bounds.width <= 0 || bounds.height <= 0) {\n return { strong: false, strength: 0, darkness: 0, areaRatio: 0 }\n }\n const sample = document.createElement('canvas')\n sample.width = 60\n sample.height = 60\n const context = sample.getContext('2d', { willReadFrequently: true })\n if (!context) return { strong: false, strength: 0, darkness: 0, areaRatio: 0 }\n context.drawImage(\n canvas,\n bounds.left,\n bounds.top,\n bounds.width,\n bounds.height,\n 0,\n 0,\n sample.width,\n sample.height,\n )\n const pixels = context.getImageData(0, 0, sample.width, sample.height).data\n const luminance = new Uint8Array(sample.width * sample.height)\n for (let pixel = 0, offset = 0; pixel < luminance.length; pixel += 1, offset += 4) {\n luminance[pixel] = Math.round(\n pixels[offset] * 0.299 +\n pixels[offset + 1] * 0.587 +\n pixels[offset + 2] * 0.114,\n )\n }\n return analyzeCastShadowLuminance(luminance, sample.width, sample.height)\n}\n","import {\n ANDROID_CHROME_FINDER_MAX_FRAME_DIMENSION,\n detectBrowserEngine,\n isAndroidChrome,\n} from './camera'\nimport { drawVisibleFrame, viewfinderBox } from './preview-frame'\nimport { ScannerError } from './errors'\nimport { assertLicense } from './license'\nimport { detectDocument, type ScanOptions } from './scan'\nimport { analyzeCanvasCastShadow } from './lighting'\nimport type {\n DocumentDetectionResult,\n DocumentModelStatus,\n DocumentQuad,\n Point,\n} from './types'\n\nexport type AutoCaptureMode = 'defaultOn' | 'defaultOff' | 'alwaysOn' | 'alwaysOff' | 'only'\nexport type FinderSource = HTMLVideoElement | MediaStream | HTMLCanvasElement\nexport type FinderState = 'seeking' | 'detecting' | 'unstable' | 'ready' | 'captured'\nexport type FinderGuidanceReason =\n | 'place-document'\n | 'move-closer'\n | 'move-farther-away'\n | 'straighten-camera'\n | 'hold-still'\n | 'ready'\n\nexport interface QuadFill {\n /** Raw quad bounds width divided by the analysis frame width. */\n widthFill: number\n /** Raw quad bounds height divided by the analysis frame height. */\n heightFill: number\n /** Fill on the limiting axis: `max(widthFill, heightFill)`. */\n limitingFill: number\n /** Shoelace polygon area divided by the analysis frame area. Diagnostic only. */\n areaFill: number\n /** Long side divided by short side of the raw quad. */\n aspectRatio: number\n}\n\nexport interface FinderGuidance {\n hint: string\n reason: FinderGuidanceReason\n /**\n * Fill on the limiting axis of the raw quad: the larger of its width and\n * height fill. A tall receipt that fills the frame height is fully framed\n * even though its bounding box covers little frame area.\n */\n fillRatio: number\n /** Component fills, polygon area fill, and aspect ratio behind `fillRatio`. */\n fill: QuadFill\n readyForAutoCapture: boolean\n}\n\nexport interface FinderLighting {\n castShadow: boolean\n strength: number\n hint?: string\n}\n\nexport function selectFinderHint(\n guidance: FinderGuidance,\n lighting: FinderLighting,\n) {\n return lighting.castShadow &&\n (guidance.reason === 'hold-still' || guidance.reason === 'ready')\n ? lighting.hint ?? guidance.hint\n : guidance.hint\n}\n\nexport interface AutoCaptureControl {\n visible: boolean\n checked: boolean\n mutable: boolean\n}\n\nexport interface FinderStatus {\n state: FinderState\n confidence: number\n quad?: DocumentQuad\n guidance: FinderGuidance\n lighting: FinderLighting\n stableFrames: number\n requiredStableFrames: number\n autoCapture: AutoCaptureControl\n sourceWidth?: number\n sourceHeight?: number\n detector?: DocumentDetectionResult['detector']\n modelStatus?: DocumentModelStatus\n modelProvider?: DocumentDetectionResult['modelProvider']\n modelError?: string\n inferenceMs?: number\n}\n\nexport interface FinderCapture {\n frame: HTMLCanvasElement\n detection?: DocumentDetectionResult\n reason: 'auto' | 'manual'\n}\n\nexport interface FinderOptions {\n source: FinderSource\n autoCapture: AutoCaptureMode\n /** Supplies the final full-resolution frame while finder analysis stays bounded. */\n captureFrame?: () => HTMLCanvasElement | Promise<HTMLCanvasElement>\n onStatus?: (status: FinderStatus) => void\n onCapture?: (capture: FinderCapture) => void | Promise<void>\n /** Reports capture failures, including automatic captures, instead of swallowing them. */\n onCaptureError?: (error: Error) => void\n /** Consecutive stable raw detections required. Defaults to 4. */\n stableFrames?: number\n /** Minimum detector confidence on the normalized 0–1 scale. Defaults to 0.72. */\n confidenceThreshold?: number\n /** Maximum normalized corner movement while entering ready. Defaults to 0.024. */\n cornerTolerance?: number\n /** Movement allowed after ready before dropping out. Defaults to 0.036. */\n exitCornerTolerance?: number\n intervalMs?: number\n /**\n * Maximum analysis-frame dimension. Defaults to 1600, or 1280 on Android\n * Chrome. Detection uses the same long-edge cap so a 1280 frame is not\n * crushed to 520 before letterbox. The analysis canvas is the viewfinder\n * cover crop, so a landscape 1920×1080 grant on a portrait phone is\n * analyzed upright (about 608×1080 on a 9:16 phone) instead of 1280×720.\n * Capture stills\n * use `captureFrame` / the unscaled video frame. Map those corners back\n * with `mapDocumentCornersToFrame`.\n */\n maxFrameDimension?: number\n guidance?: FinderGuidanceOptions\n detection?: ScanOptions\n playShutterSound?: boolean\n}\n\nexport interface FinderSession {\n stop: () => void\n capture: () => Promise<FinderCapture>\n setAutoCapture: (enabled: boolean) => boolean\n getStatus: () => FinderStatus\n}\n\nexport async function snapshotBeforeCaptureFeedback<T>(\n snapshot: () => T | Promise<T>,\n feedback: () => void,\n) {\n const captured = await snapshot()\n feedback()\n return captured\n}\n\nexport function autoCaptureControl(mode: AutoCaptureMode): AutoCaptureControl {\n if (mode === 'alwaysOn' || mode === 'only') return { visible: false, checked: true, mutable: false }\n if (mode === 'alwaysOff') return { visible: false, checked: false, mutable: false }\n return {\n visible: true,\n checked: mode === 'defaultOn',\n mutable: true,\n }\n}\n\nfunction cornerList(quad: DocumentQuad): Point[] {\n return [quad.topLeft, quad.topRight, quad.bottomRight, quad.bottomLeft]\n}\n\nexport interface StabilityOptions {\n stableFrames: number\n confidenceThreshold: number\n cornerTolerance: number\n exitCornerTolerance?: number\n}\n\nexport interface FinderGuidanceOptions {\n confidenceThreshold?: number\n /** Limiting-axis fill required to enter ready. Defaults to 0.72. */\n minFillRatio?: number\n /** Limiting-axis fill allowed after ready before exiting. Defaults to 0.64. */\n exitFillRatio?: number\n /** Long-to-short side ratio that makes a document high-aspect. Defaults to 2.2. */\n highAspectRatio?: number\n /** Long-side fill required to enter ready on a high-aspect document. Defaults to 0.8. */\n highAspectFillRatio?: number\n /** Long-side fill allowed after ready on a high-aspect document. Defaults to 0.72. */\n highAspectExitFillRatio?: number\n /** Edge clearance required to enter ready. Defaults to 0.015. */\n edgeMarginRatio?: number\n /** Edge clearance allowed after ready. Defaults to 0.005. */\n exitEdgeMarginRatio?: number\n /** Opposite-edge ratio required to enter ready. Defaults to 0.48. */\n minPerspectiveRatio?: number\n /** Opposite-edge ratio allowed after ready. Defaults to 0.4. */\n exitMinPerspectiveRatio?: number\n}\n\nexport const DEFAULT_FINDER_STABLE_FRAMES = 4\nexport const DEFAULT_FINDER_CONFIDENCE_THRESHOLD = 0.72\nexport const DEFAULT_FINDER_CORNER_TOLERANCE = 0.024\nexport const DEFAULT_FINDER_EXIT_CORNER_TOLERANCE = 0.036\nexport const DEFAULT_FINDER_MIN_FILL_RATIO = 0.72\nexport const DEFAULT_FINDER_EXIT_FILL_RATIO = 0.64\nexport const DEFAULT_FINDER_HIGH_ASPECT_RATIO = 2.2\n/** Extra long-side fill asked of a high-aspect document, above the base target. */\nexport const DEFAULT_FINDER_HIGH_ASPECT_FILL_MARGIN = 0.08\nexport const DEFAULT_FINDER_EDGE_MARGIN_RATIO = 0.015\nexport const DEFAULT_FINDER_EXIT_EDGE_MARGIN_RATIO = 0.005\nexport const DEFAULT_FINDER_MIN_PERSPECTIVE_RATIO = 0.48\nexport const DEFAULT_FINDER_EXIT_MIN_PERSPECTIVE_RATIO = 0.40\nexport const DEFAULT_FINDER_MAX_FRAME_DIMENSION = 1600\n\nexport function defaultFinderMaxFrameDimension(\n engine = detectBrowserEngine(),\n) {\n return isAndroidChrome(engine)\n ? ANDROID_CHROME_FINDER_MAX_FRAME_DIMENSION\n : DEFAULT_FINDER_MAX_FRAME_DIMENSION\n}\n\nfunction polygonArea(points: Point[]) {\n let area = 0\n for (let index = 0; index < points.length; index += 1) {\n const current = points[index]\n const next = points[(index + 1) % points.length]\n area += current.x * next.y - next.x * current.y\n }\n return Math.abs(area) / 2\n}\n\nfunction distance(first: Point, second: Point) {\n return Math.hypot(first.x - second.x, first.y - second.y)\n}\n\nconst EMPTY_FILL: QuadFill = {\n widthFill: 0,\n heightFill: 0,\n limitingFill: 0,\n areaFill: 0,\n aspectRatio: 1,\n}\n\n/**\n * Measures how much of each frame axis the raw quad occupies. A document can\n * only grow until its limiting axis reaches a frame edge, so the larger of the\n * two axis fills — not the bounding-box area — describes how well it is framed.\n */\nexport function measureQuadFill(\n quad: DocumentQuad,\n frameWidth: number,\n frameHeight: number,\n): QuadFill {\n const points = cornerList(quad)\n const xs = points.map(({ x }) => x)\n const ys = points.map(({ y }) => y)\n const widthFill = (Math.max(...xs) - Math.min(...xs)) / Math.max(1, frameWidth)\n const heightFill = (Math.max(...ys) - Math.min(...ys)) / Math.max(1, frameHeight)\n const [topLeft, topRight, bottomRight, bottomLeft] = points\n const horizontal = Math.max(\n distance(topLeft, topRight),\n distance(bottomLeft, bottomRight),\n )\n const vertical = Math.max(\n distance(topLeft, bottomLeft),\n distance(topRight, bottomRight),\n )\n return {\n widthFill,\n heightFill,\n limitingFill: Math.max(widthFill, heightFill),\n areaFill: polygonArea(points) / Math.max(1, frameWidth * frameHeight),\n aspectRatio: Math.max(horizontal, vertical) /\n Math.max(1, Math.min(horizontal, vertical)),\n }\n}\n\n/**\n * Fill the limiting axis must reach. High-aspect documents are asked for a\n * little more of the long side, because their short side can never fill and\n * the long side is the only axis carrying resolution. The target never exceeds\n * what the edge margin physically allows.\n */\nexport function limitingFillTarget(\n fill: QuadFill,\n previouslyReady: boolean,\n edgeMarginRatio: number,\n options: FinderGuidanceOptions = {},\n) {\n const base = previouslyReady\n ? options.exitFillRatio ?? DEFAULT_FINDER_EXIT_FILL_RATIO\n : options.minFillRatio ?? DEFAULT_FINDER_MIN_FILL_RATIO\n const highAspectRatio = options.highAspectRatio ?? DEFAULT_FINDER_HIGH_ASPECT_RATIO\n if (fill.aspectRatio < highAspectRatio) return base\n const configured = previouslyReady\n ? options.highAspectExitFillRatio\n : options.highAspectFillRatio\n return Math.min(\n configured ?? base + DEFAULT_FINDER_HIGH_ASPECT_FILL_MARGIN,\n 1 - edgeMarginRatio * 2,\n )\n}\n\nexport function selectFinderGuidance(\n detection: DocumentDetectionResult,\n stability: { ready: boolean; previouslyReady?: boolean },\n options: FinderGuidanceOptions = {},\n): FinderGuidance {\n const confidenceThreshold =\n options.confidenceThreshold ?? DEFAULT_FINDER_CONFIDENCE_THRESHOLD\n if (\n detection.status !== 'success' ||\n !detection.quad ||\n detection.confidence < confidenceThreshold ||\n !detection.sourceWidth ||\n !detection.sourceHeight\n ) {\n return {\n hint: 'Place the document in the frame',\n reason: 'place-document',\n fillRatio: 0,\n fill: EMPTY_FILL,\n readyForAutoCapture: false,\n }\n }\n\n const points = cornerList(detection.quad)\n const fill = measureQuadFill(\n detection.quad,\n detection.sourceWidth,\n detection.sourceHeight,\n )\n const fillRatio = fill.limitingFill\n const edgeMarginRatio = stability.previouslyReady\n ? options.exitEdgeMarginRatio ?? DEFAULT_FINDER_EXIT_EDGE_MARGIN_RATIO\n : options.edgeMarginRatio ?? DEFAULT_FINDER_EDGE_MARGIN_RATIO\n const marginX = detection.sourceWidth * edgeMarginRatio\n const marginY = detection.sourceHeight * edgeMarginRatio\n const clippingRisk = points.some(({ x, y }) =>\n x <= marginX ||\n x >= detection.sourceWidth - marginX ||\n y <= marginY ||\n y >= detection.sourceHeight - marginY,\n )\n if (clippingRisk) {\n return {\n hint: 'Move farther away',\n reason: 'move-farther-away',\n fillRatio,\n fill,\n readyForAutoCapture: false,\n }\n }\n\n const [topLeft, topRight, bottomRight, bottomLeft] = points\n const top = distance(topLeft, topRight)\n const right = distance(topRight, bottomRight)\n const bottom = distance(bottomRight, bottomLeft)\n const left = distance(bottomLeft, topLeft)\n const oppositeRatio = Math.min(\n Math.min(top, bottom) / Math.max(1, Math.max(top, bottom)),\n Math.min(left, right) / Math.max(1, Math.max(left, right)),\n )\n const minPerspectiveRatio = stability.previouslyReady\n ? options.exitMinPerspectiveRatio ?? DEFAULT_FINDER_EXIT_MIN_PERSPECTIVE_RATIO\n : options.minPerspectiveRatio ?? DEFAULT_FINDER_MIN_PERSPECTIVE_RATIO\n if (oppositeRatio < minPerspectiveRatio) {\n return {\n hint: 'Hold the camera straight',\n reason: 'straighten-camera',\n fillRatio,\n fill,\n readyForAutoCapture: false,\n }\n }\n\n // Both axes have slack only when the limiting one does, so a skinny document\n // that already fills its long axis is never told to move closer.\n const fillTarget = limitingFillTarget(\n fill,\n stability.previouslyReady === true,\n edgeMarginRatio,\n options,\n )\n if (fillRatio < fillTarget) {\n return {\n hint: 'Move closer',\n reason: 'move-closer',\n fillRatio,\n fill,\n readyForAutoCapture: false,\n }\n }\n\n return {\n hint: 'Hold still',\n reason: stability.ready ? 'ready' : 'hold-still',\n fillRatio,\n fill,\n readyForAutoCapture: stability.ready,\n }\n}\n\nexport class QuadStabilityTracker {\n private previous?: DocumentQuad\n private count = 0\n private ready = false\n private readonly options: StabilityOptions\n\n constructor(options: StabilityOptions) {\n this.options = options\n }\n\n reset() {\n this.previous = undefined\n this.count = 0\n this.ready = false\n }\n\n update(detection: DocumentDetectionResult) {\n if (\n detection.status !== 'success' ||\n !detection.quad ||\n detection.confidence < this.options.confidenceThreshold\n ) {\n this.reset()\n return { stableFrames: 0, ready: false, movement: Infinity }\n }\n const diagonal = Math.hypot(detection.sourceWidth, detection.sourceHeight)\n const movement = this.previous\n ? Math.max(...cornerList(detection.quad).map((point, index) => {\n const previous = cornerList(this.previous!)[index]\n return Math.hypot(point.x - previous.x, point.y - previous.y) / Math.max(1, diagonal)\n }))\n : Infinity\n const exitTolerance = this.options.exitCornerTolerance ??\n Math.max(this.options.cornerTolerance, DEFAULT_FINDER_EXIT_CORNER_TOLERANCE)\n if (this.ready && this.previous && movement <= exitTolerance) {\n this.count = Math.max(this.options.stableFrames, this.count + 1)\n } else {\n this.ready = false\n this.count = this.previous && movement <= this.options.cornerTolerance\n ? this.count + 1\n : 1\n if (this.count >= this.options.stableFrames) this.ready = true\n }\n this.previous = detection.quad\n return {\n stableFrames: this.count,\n ready: this.ready,\n movement,\n }\n }\n}\n\nfunction analysisFrame(\n source: HTMLVideoElement | HTMLCanvasElement,\n maxDimension: number,\n) {\n const width = source instanceof HTMLVideoElement ? source.videoWidth : source.width\n const height = source instanceof HTMLVideoElement ? source.videoHeight : source.height\n if (!width || !height) throw new Error('The camera is not ready to capture a frame.')\n const box = viewfinderBox(source)\n return drawVisibleFrame(source, width, height, box.width, box.height, maxDimension)\n}\n\nfunction playShutter() {\n const AudioContextClass = window.AudioContext ??\n (window as typeof window & { webkitAudioContext?: typeof AudioContext }).webkitAudioContext\n if (!AudioContextClass) return\n const context = new AudioContextClass()\n const length = Math.round(context.sampleRate * 0.09)\n const buffer = context.createBuffer(1, length, context.sampleRate)\n const channel = buffer.getChannelData(0)\n for (let index = 0; index < length; index += 1) {\n const envelope = Math.exp(-index / (context.sampleRate * 0.018))\n channel[index] = (Math.random() * 2 - 1) * envelope\n }\n const source = context.createBufferSource()\n const filter = context.createBiquadFilter()\n const gain = context.createGain()\n filter.type = 'bandpass'\n filter.frequency.value = 1400\n gain.gain.value = 0.42\n source.buffer = buffer\n source.connect(filter).connect(gain).connect(context.destination)\n source.start()\n source.onended = () => void context.close()\n}\n\nasync function videoForStream(stream: MediaStream) {\n const video = document.createElement('video')\n video.muted = true\n video.autoplay = true\n video.playsInline = true\n video.srcObject = stream\n await video.play()\n return video\n}\n\n/**\n * Watches a camera or canvas for a stable document.\n * Detection quality is reported on `FinderStatus`, not thrown.\n * Worker startup and DocAligner HTTP failures are caught on each tick and\n * reported as `modelStatus: 'failed'` with `modelError`. The camera stays up.\n *\n * @throws {LicenseError} LicenseError when the scan feature is not licensed. The finder does not start.\n */\nexport async function startFinder(options: FinderOptions): Promise<FinderSession> {\n await assertLicense('scan')\n const control = autoCaptureControl(options.autoCapture)\n const tracker = new QuadStabilityTracker({\n stableFrames: options.stableFrames ?? DEFAULT_FINDER_STABLE_FRAMES,\n confidenceThreshold:\n options.confidenceThreshold ?? DEFAULT_FINDER_CONFIDENCE_THRESHOLD,\n cornerTolerance: options.cornerTolerance ?? DEFAULT_FINDER_CORNER_TOLERANCE,\n exitCornerTolerance:\n options.exitCornerTolerance ?? DEFAULT_FINDER_EXIT_CORNER_TOLERANCE,\n })\n const maxDimension = options.maxFrameDimension ?? defaultFinderMaxFrameDimension()\n const interval = options.intervalMs ?? 140\n const detectionOptions: ScanOptions = {\n minDimension: 220,\n maxAnalysisDimension: maxDimension,\n ...options.detection,\n }\n const source: HTMLVideoElement | HTMLCanvasElement =\n typeof MediaStream !== 'undefined' && options.source instanceof MediaStream\n ? await videoForStream(options.source)\n : options.source as HTMLVideoElement | HTMLCanvasElement\n let running = true\n let captureStarted = false\n let guidanceReady = false\n let timer = 0\n let latestDetection: DocumentDetectionResult | undefined\n let status: FinderStatus = {\n state: 'detecting',\n confidence: 0,\n guidance: {\n hint: 'Place the document in the frame',\n reason: 'place-document',\n fillRatio: 0,\n fill: EMPTY_FILL,\n readyForAutoCapture: false,\n },\n lighting: { castShadow: false, strength: 0 },\n stableFrames: 0,\n requiredStableFrames: options.stableFrames ?? DEFAULT_FINDER_STABLE_FRAMES,\n autoCapture: { ...control },\n }\n\n const frame = () => analysisFrame(source, maxDimension)\n const emit = (next: FinderStatus) => {\n status = next\n options.onStatus?.(next)\n }\n const stop = () => {\n running = false\n window.clearTimeout(timer)\n if (source instanceof HTMLVideoElement && source !== options.source) source.srcObject = null\n }\n const capture = async (reason: FinderCapture['reason'] = 'manual') => {\n if (captureStarted) throw new Error('A finder capture is already in progress.')\n captureStarted = true\n let capturedFrame: HTMLCanvasElement\n try {\n capturedFrame = await snapshotBeforeCaptureFeedback(\n options.captureFrame ?? frame,\n () => {\n emit({ ...status, state: 'captured' })\n if (options.playShutterSound !== false) playShutter()\n stop()\n },\n )\n } catch (error) {\n // Leave the finder usable so the end user can retake after a blank frame.\n captureStarted = false\n throw error instanceof Error ? error : new Error('The camera frame could not be captured.')\n }\n const result: FinderCapture = { frame: capturedFrame, detection: latestDetection, reason }\n await options.onCapture?.(result)\n return result\n }\n const tick = async () => {\n if (!running || captureStarted) return\n try {\n const current = frame()\n const detection = await detectDocument(current, detectionOptions)\n latestDetection = detection\n const shadow = detection.quad\n ? analyzeCanvasCastShadow(current, detection.quad)\n : { strong: false, strength: 0 }\n const lighting: FinderLighting = shadow.strong\n ? {\n castShadow: true,\n strength: shadow.strength,\n hint: 'Tilt to move the shadow off the page',\n }\n : { castShadow: false, strength: shadow.strength }\n const stability = tracker.update(detection)\n const guidance = selectFinderGuidance(detection, {\n ...stability,\n previouslyReady: guidanceReady,\n }, {\n confidenceThreshold:\n options.confidenceThreshold ?? DEFAULT_FINDER_CONFIDENCE_THRESHOLD,\n ...options.guidance,\n })\n guidanceReady = guidance.readyForAutoCapture\n const nextState: FinderState =\n detection.status !== 'success' || guidance.reason === 'place-document'\n ? 'seeking'\n : guidance.readyForAutoCapture\n ? 'ready'\n : 'unstable'\n emit({\n state: nextState,\n confidence: detection.confidence,\n quad: detection.quad,\n guidance,\n lighting,\n stableFrames: stability.stableFrames,\n requiredStableFrames: status.requiredStableFrames,\n autoCapture: { ...control },\n sourceWidth: detection.sourceWidth,\n sourceHeight: detection.sourceHeight,\n detector: detection.detector,\n modelStatus: detection.modelStatus,\n modelProvider: detection.modelProvider,\n modelError: detection.modelError,\n inferenceMs: detection.inferenceMs,\n })\n if (guidance.readyForAutoCapture && control.checked) {\n try {\n await capture('auto')\n return\n } catch (error) {\n tracker.reset()\n guidanceReady = false\n options.onCaptureError?.(\n error instanceof Error ? error : new Error('Automatic capture failed.'),\n )\n }\n }\n } catch (error) {\n tracker.reset()\n guidanceReady = false\n const failure = error instanceof ScannerError\n ? {\n detector: 'ml' as const,\n modelStatus: 'failed' as const,\n modelError: error.message,\n }\n : {}\n emit({\n state: 'seeking',\n confidence: 0,\n guidance: {\n hint: 'Place the document in the frame',\n reason: 'place-document',\n fillRatio: 0,\n fill: EMPTY_FILL,\n readyForAutoCapture: false,\n },\n lighting: { castShadow: false, strength: 0 },\n stableFrames: 0,\n requiredStableFrames: status.requiredStableFrames,\n autoCapture: { ...control },\n ...failure,\n })\n }\n if (running) timer = window.setTimeout(() => void tick(), interval)\n }\n\n options.onStatus?.(status)\n void tick()\n return {\n stop,\n capture: () => capture('manual'),\n setAutoCapture(enabled) {\n if (!control.mutable || captureStarted) return false\n control.checked = enabled\n emit({ ...status, autoCapture: { ...control } })\n return true\n },\n getStatus: () => status,\n }\n}\n"],"mappings":";AAeA,IAAa,IAAb,cAAkC,MAAM;CACtC;CAEA,YAAY,GAAwB,GAAiB;EAGnD,AAFA,MAAM,CAAO,GACb,KAAK,OAAO,gBAC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MAAM,EAAQ,MAAM;KACpB;IACF,SAAS,GAAO;KAGd,AAFA,EAAQ,MAAM,GACd,IAAgB,IAChB,EAAQ,iBACN,aAAiB,QAAQ,IAAQ,gBAAI,MAAM,2BAA2B,CACxE;IACF;GAEJ,SAAS,GAAO;IAEd,AADA,EAAQ,MAAM,GACd,IAAgB;IAChB,IAAM,IAAU,aAAiB,IAC7B;KACA,UAAU;KACV,aAAa;KACb,YAAY,EAAM;IACpB,IACE,CAAC;IACL,EAAK;KACH,OAAO;KACP,YAAY;KACZ,UAAU;MACR,MAAM;MACN,QAAQ;MACR,WAAW;MACX,MAAM;MACN,qBAAqB;KACvB;KACA,UAAU;MAAE,YAAY;MAAO,UAAU;KAAE;KAC3C,cAAc;KACd,sBAAsB,EAAO;KAC7B,aAAa,EAAE,GAAG,EAAQ;KAC1B,GAAG;IACL,CAAC;GACH;GACA,AAAI,MAAS,IAAQ,OAAO,iBAAiB,KAAK,EAAK,GAAG,CAAQ;EADlE;CAEF;CAIA,OAFA,EAAQ,WAAW,CAAM,GACzB,EAAU,GACH;EACL;EACA,eAAe,EAAQ,QAAQ;EAC/B,eAAe,GAAS;GAItB,OAHI,CAAC,EAAQ,WAAW,IAAuB,MAC/C,EAAQ,UAAU,GAClB,EAAK;IAAE,GAAG;IAAQ,aAAa,EAAE,GAAG,EAAQ;GAAE,CAAC,GACxC;EACT;EACA,iBAAiB;CACnB;AACF"}
package/dist/react.js CHANGED
@@ -1,5 +1,5 @@
1
1
  "use client";
2
- import { k as e, m as t, o as n, p as r, s as i, v as a } from "./finder-Bjo3TAHi.js";
2
+ import { k as e, m as t, o as n, p as r, s as i, v as a } from "./finder-D0Wgl-6-.js";
3
3
  import { createContext as o, useCallback as s, useContext as c, useEffect as l, useMemo as u, useRef as d, useState as f } from "react";
4
4
  import { Fragment as p, jsx as m, jsxs as h } from "react/jsx-runtime";
5
5
  //#region src/sdk/display-quad.ts