@sekyro/web 0.1.0-rc.21 → 0.1.0-rc.22.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (118) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/README.md +12 -11
  3. package/dist/background-monitor-GCMNCJMG.js +1 -0
  4. package/dist/camera-trait-HVV5ZEDI.js +1 -0
  5. package/dist/{capture-constraints-B5omafmk.d.cts → capture-constraints-CVqpMNGA.d.cts} +7 -3
  6. package/dist/{capture-constraints-B5omafmk.d.ts → capture-constraints-CVqpMNGA.d.ts} +7 -3
  7. package/dist/capture-session-doc-VSUEDAEN.js +1 -0
  8. package/dist/{capture-session-v3-26FgzBIl.d.cts → capture-session-v3-C-Q-21Fm.d.ts} +90 -13
  9. package/dist/{capture-session-v3-ZO0QOeQH.d.ts → capture-session-v3-DD-MXSU4.d.cts} +90 -13
  10. package/dist/chunk-6RJTKX5I.js +1 -0
  11. package/dist/chunk-7KXJEF7P.js +1 -0
  12. package/dist/chunk-7TGVXBW6.js +1 -0
  13. package/dist/chunk-ACP2ZOVW.js +1 -0
  14. package/dist/{chunk-MXWLCDFX.js → chunk-AXJ2VWIK.js} +1 -1
  15. package/dist/chunk-CDDYFUER.js +1 -0
  16. package/dist/chunk-CPK5FYNJ.js +1 -0
  17. package/dist/{chunk-G6LKLN4U.js → chunk-EKEHAFEK.js} +1 -1
  18. package/dist/{chunk-QYYJLXKA.js → chunk-FSJPKOCC.js} +1 -1
  19. package/dist/chunk-H6REKPZ4.js +1 -0
  20. package/dist/{chunk-A3FUGHAH.js → chunk-HFCVN6AG.js} +1 -1
  21. package/dist/chunk-J5IQ6THP.js +1 -0
  22. package/dist/chunk-NHXLIDQJ.js +1 -0
  23. package/dist/chunk-PVSYKKMP.js +1 -0
  24. package/dist/chunk-RJZ5SARR.js +1 -0
  25. package/dist/chunk-TTD5LQG2.js +1 -0
  26. package/dist/{chunk-RI3E7GBN.js → chunk-TYJA2XJR.js} +1 -1
  27. package/dist/chunk-UBRNDTTD.js +1 -0
  28. package/dist/chunk-V4VFZ7NQ.js +1 -0
  29. package/dist/chunk-XB4KLBHY.js +1 -0
  30. package/dist/chunk-XK4CCTLL.js +1 -0
  31. package/dist/{chunk-33KKMPJ5.js → chunk-XLYHT4ZQ.js} +1 -1
  32. package/dist/chunk-ZGDUIZC2.js +1 -0
  33. package/dist/client/index.cjs +1 -1
  34. package/dist/client/index.d.cts +3 -3
  35. package/dist/client/index.d.ts +3 -3
  36. package/dist/client/index.js +1 -1
  37. package/dist/clip-inspect-HZ7N2YOP.js +1 -0
  38. package/dist/core/index.cjs +1 -1
  39. package/dist/core/index.d.cts +5 -5
  40. package/dist/core/index.d.ts +5 -5
  41. package/dist/core/index.js +1 -1
  42. package/dist/core/ocr/worker.js +1 -1
  43. package/dist/core/v3/detect-worker.cjs +1 -1
  44. package/dist/core/v3/detect-worker.d.cts +1 -1
  45. package/dist/core/v3/detect-worker.d.ts +1 -1
  46. package/dist/core/v3/detect-worker.js +1 -1
  47. package/dist/create-document-capture-D7GUVFWF.js +1 -0
  48. package/dist/create-portrait-capture-VRZZOMJS.js +1 -0
  49. package/dist/{create-verification-KlHIU4Fy.d.ts → create-verification-BsZ038gI.d.cts} +175 -80
  50. package/dist/{create-verification-CXhXxknV.d.cts → create-verification-CfSZiPSN.d.ts} +175 -80
  51. package/dist/{detect-worker-DclNxkZT.d.ts → detect-worker-CHqsPJoM.d.cts} +19 -2
  52. package/dist/{detect-worker-DclNxkZT.d.cts → detect-worker-CHqsPJoM.d.ts} +19 -2
  53. package/dist/{detector-scanic-YCDNLCGV.js → detector-scanic-F3Y5X3DF.js} +1 -1
  54. package/dist/{icao-gate-DI8VePWd.d.ts → icao-gate-BrnPW_gd.d.ts} +1 -1
  55. package/dist/{icao-gate-DvzOzHq6.d.cts → icao-gate-Bw0Fxd30.d.cts} +1 -1
  56. package/dist/icao-gate-SO6YJ7RV.js +1 -0
  57. package/dist/{icao-policy-DztbA50-.d.ts → icao-policy-C14ZKZ7r.d.ts} +2 -2
  58. package/dist/{icao-policy-MRB8NMAu.d.cts → icao-policy-DcaumEDt.d.cts} +2 -2
  59. package/dist/icao-tuning-DCZCMCEQ.js +1 -0
  60. package/dist/index.cjs +1 -1
  61. package/dist/index.d.cts +11 -15
  62. package/dist/index.d.ts +11 -15
  63. package/dist/index.js +1 -1
  64. package/dist/internal/index.cjs +1 -1
  65. package/dist/internal/index.d.cts +52 -33
  66. package/dist/internal/index.d.ts +52 -33
  67. package/dist/internal/index.js +1 -1
  68. package/dist/{landmarker-KB7LVXAU.js → landmarker-3BBP3RBY.js} +1 -1
  69. package/dist/mrz-band-DCXFWDBD.js +1 -0
  70. package/dist/plan-runner-5UZYQ2XH.js +1 -0
  71. package/dist/popup/index.cjs +1 -1
  72. package/dist/popup/index.d.cts +2 -2
  73. package/dist/popup/index.d.ts +2 -2
  74. package/dist/popup/index.js +1 -1
  75. package/dist/{print-AYSCRSZB.js → print-4WOMNRBE.js} +1 -1
  76. package/dist/{turnstile-FATNZ4AG.js → turnstile-MX6YN4YH.js} +1 -1
  77. package/dist/{types-C_XP92JQ.d.ts → types-ChKVytm_.d.cts} +129 -74
  78. package/dist/{types-C_XP92JQ.d.cts → types-ChKVytm_.d.ts} +129 -74
  79. package/package.json +1 -1
  80. package/sbom.cdx.json +10 -10
  81. package/dist/background-monitor-A7FKJOAG.js +0 -1
  82. package/dist/camera-trait-45MJTW4K.js +0 -1
  83. package/dist/capture-session-doc-XBZGXWOP.js +0 -1
  84. package/dist/chunk-234OZEDB.js +0 -1
  85. package/dist/chunk-7Q4YPMAF.js +0 -1
  86. package/dist/chunk-B2X33ZW2.js +0 -1
  87. package/dist/chunk-CQ7SKLMC.js +0 -1
  88. package/dist/chunk-FUHDOEBP.js +0 -1
  89. package/dist/chunk-GT2ZLGF7.js +0 -1
  90. package/dist/chunk-H3HVCWLF.js +0 -1
  91. package/dist/chunk-O5WKNZ2C.js +0 -1
  92. package/dist/chunk-OKWG3PVH.js +0 -1
  93. package/dist/chunk-P3H3D33O.js +0 -1
  94. package/dist/chunk-P6UP4UQY.js +0 -1
  95. package/dist/chunk-SNACCYTL.js +0 -1
  96. package/dist/chunk-TQB3URP2.js +0 -1
  97. package/dist/chunk-VIAT4DEA.js +0 -1
  98. package/dist/chunk-ZADZTM3M.js +0 -1
  99. package/dist/chunk-ZNIZACXD.js +0 -1
  100. package/dist/create-document-capture-23R2F47A.js +0 -1
  101. package/dist/create-portrait-capture-AGFHECK7.js +0 -1
  102. package/dist/icao-gate-T3BTOKFJ.js +0 -1
  103. package/dist/icao-tuning-4ETMF53W.js +0 -1
  104. package/dist/mrz-band-VYHOTDHY.js +0 -1
  105. package/dist/plan-runner-NUWONT7F.js +0 -1
  106. /package/dist/{chunk-53POX7U4.js → chunk-25TEJBSB.js} +0 -0
  107. /package/dist/{chunk-TDLIXFDT.js → chunk-BPKDXDDH.js} +0 -0
  108. /package/dist/{chunk-FPXL63KZ.js → chunk-FK2DJADA.js} +0 -0
  109. /package/dist/{chunk-GI3UFGRQ.js → chunk-LL3YYUKR.js} +0 -0
  110. /package/dist/{chunk-DK5YPBDQ.js → chunk-LYYLXNA4.js} +0 -0
  111. /package/dist/{chunk-SMKCBUJL.js → chunk-NYRFUVAR.js} +0 -0
  112. /package/dist/{chunk-POIQGEZM.js → chunk-V5P5P3HY.js} +0 -0
  113. /package/dist/{chunk-DFTCAWMP.js → chunk-VP37FW6C.js} +0 -0
  114. /package/dist/{chunk-CJHMFPL6.js → chunk-YH7DR3PF.js} +0 -0
  115. /package/dist/{keyframe-rank-YAJLYJYF.js → keyframe-rank-R4NPQGN3.js} +0 -0
  116. /package/dist/{scanic-ml-stub-KW7IZHUT.js → scanic-ml-stub-XPNKT2N3.js} +0 -0
  117. /package/dist/{segmenter-USLNBX65.js → segmenter-3CVPTZMM.js} +0 -0
  118. /package/dist/{upload-file-UYXOHCRG.js → upload-file-C4MFKLT3.js} +0 -0
@@ -0,0 +1 @@
1
+ var m=["video/mp4;codecs=avc1.42E01E,mp4a.40.2","video/mp4;codecs=avc1.42E01E","video/mp4","video/webm;codecs=vp9,opus","video/webm;codecs=vp9","video/webm;codecs=vp8,opus","video/webm;codecs=vp8","video/webm"];function v(){let e=globalThis.MediaRecorder;return!e||typeof e.isTypeSupported!="function"?"":m.find(r=>e.isTypeSupported(r))??""}var l="video/webm";function f(e){if(e instanceof TypeError)return"insecure";switch(e?.name??""){case"NotAllowedError":case"PermissionDeniedError":return"permission";case"NotFoundError":case"DevicesNotFoundError":return"notfound";case"NotReadableError":case"TrackStartError":return"inuse";case"OverconstrainedError":case"ConstraintNotSatisfiedError":return"overconstrained";default:return"generic"}}function x(){let e=globalThis;if(typeof e.window<"u"&&e.window.isSecureContext===!1)return"INSECURE_CONTEXT";let r=e.navigator?.mediaDevices;return!r||typeof r.getUserMedia!="function"?"UNSUPPORTED":"OK"}function S(){let e=globalThis.MediaRecorder;return typeof e<"u"&&typeof e.isTypeSupported=="function"}var g=8*1024*1024;function T(e){return e.size>g}function p(e){let r=(e||"").toLowerCase();return r.startsWith("image/jpeg")?"jpg":r.startsWith("video/mp4")?"mp4":(r.startsWith("video/webm"),"webm")}function h(e){let{token:r,clip:n,keyframe:t}=e,d=e.ts??Date.now(),u=n.type||l,c=t.type||"image/jpeg",o=new FormData;return o.append("token",r),o.append("clip",new File([n],`liveness-${d}.${p(u)}`,{type:u})),o.append("keyframe",new File([t],`keyframe-${d}.${p(c)}`,{type:c})),o}var w=40;function E(e){if(e===null||typeof e!="object"&&typeof e!="function")return;let r;try{r=e.name}catch{return}return k(r)}function k(e){if(typeof e!="string")return;let r=e.replace(/[^A-Za-z]/g,"").slice(0,w);return r===""?void 0:r}function N(e){let r=f(e);if(r!=="generic")return r;switch(E(e)){case"AbortError":return"inuse";case"SecurityError":return"permission";default:return r}}var i=Symbol.for("sekyro.web.cameraStreams"),a=globalThis,s=a[i]??(a[i]=new Set);function I(e){try{s.add(e)}catch{}}function D(e){let r=0;for(let n of[...s])if(n!==e){s.delete(n);try{for(let t of n.getTracks())t.readyState!=="ended"&&(t.stop(),r+=1)}catch{}}return r}var A=3;function y(e){let r=e.toLowerCase();return r===""?"unknown":/front|facing front|user|selfie|face ?time/.test(r)?"front":/ultra|0\.5x|wide angle/.test(r)?"ultra":/tele|zoom|periscope|[2-9]x/.test(r)?"tele":/depth|tof|infrared|\bir\b|truedepth|lidar|macro|monochrome|mono\b/.test(r)?"depth":/dual|triple/.test(r)?"virtual":/back|rear|environment|facing back|arrière|خلفية/.test(r)?"main":"unknown"}function b(e){let r=/camera2?\s*(\d+)/i.exec(e);return r?Number(r[1]):Number.POSITIVE_INFINITY}function L(e){let r={main:0,virtual:1,ultra:9,tele:9,depth:9,front:9,unknown:9};return e.filter(n=>(n.kind===void 0||n.kind==="videoinput")&&n.deviceId!=="").map((n,t)=>({id:n.deviceId,kind:y(n.label),index:b(n.label),i:t})).filter(n=>r[n.kind]<9).sort((n,t)=>r[n.kind]-r[t.kind]||n.index-t.index||n.i-t.i).map(n=>n.id)}export{m as a,v as b,l as c,f as d,x as e,S as f,g,T as h,p as i,h as j,E as k,k as l,N as m,I as n,D as o,A as p,y as q,L as r};
@@ -0,0 +1 @@
1
+ var l=["session.verified","session.not_verified","session.review_pending","session.cancelled"],u=new Set([0,1,2,3]),E="sekyro-verify",a="width=480,height=720,noopener=false",f=new Set(l);function y(e){if(e===null||typeof e!="object")return!1;let n=e;return n.source==="sekyro"&&n.version===1&&typeof n.sessionId=="string"&&typeof n.event=="string"&&f.has(n.event)}function S(e){let n=new URL(e.hostedUrl).origin,t=window.open(e.hostedUrl,E,a);if(!t)return{error:"popup_blocked"};let r=o=>{if(o.source!==t||o.origin!==n||!y(o.data))return;let{source:p,version:d,event:c,sessionId:v,level:s}=o.data,i={source:p,version:d,event:c,sessionId:v};u.has(s)&&(i.level=s),e.onEvent(i)};return window.addEventListener("message",r),{close(){window.removeEventListener("message",r),t.close()}}}function k(e,n){return n.mode==="redirect"?(window.location.assign(e),{close(){}}):S({hostedUrl:e,onEvent:n.onEvent??(()=>{})})}export{l as a,S as b,k as c};
@@ -0,0 +1 @@
1
+ import{a as G,e as me,g as fe,m as he}from"./chunk-25TEJBSB.js";import{b as ge}from"./chunk-XLYHT4ZQ.js";import{a as pe,d as ye}from"./chunk-YH7DR3PF.js";import{a as be}from"./chunk-TYJA2XJR.js";import{a as ce,d as ue,e as K,f as le,g as de}from"./chunk-CPK5FYNJ.js";import{a as V,b as se}from"./chunk-RJZ5SARR.js";import{k as N,m as oe,n as ie}from"./chunk-7KXJEF7P.js";import{e as ae}from"./chunk-CDDYFUER.js";var Ee=250,Ie=180,Re=96;function xe(n){let{data:e,width:t,height:a}=n,r=new Uint8Array(t*a);for(let o=0,s=0;o<r.length;o+=1,s+=4)r[o]=Math.round(.299*(e[s]??0)+.587*(e[s+1]??0)+.114*(e[s+2]??0));return{data:r,width:t,height:a}}function W(n,e){return{x0:Math.max(0,Math.floor(n.x)),y0:Math.max(0,Math.floor(n.y)),x1:Math.min(e.width,Math.ceil(n.x+n.width)),y1:Math.min(e.height,Math.ceil(n.y+n.height))}}function T(n,e,t){let a=W(e,n),r=t===void 0?null:W(t,n),o=0,s=0,l=0,m=0;for(let c=a.y0;c<a.y1;c+=1)for(let b=a.x0;b<a.x1;b+=1){if(r!==null&&b>=r.x0&&b<r.x1&&c>=r.y0&&c<r.y1)continue;let L=n.data[c*n.width+b];o+=1,s+=L,l+=L*L,L>=Ee&&(m+=1)}if(o===0)return{mean:0,sd:0,clipped:0,count:0};let d=s/o;return{mean:d,sd:Math.sqrt(Math.max(0,l/o-d*d)),clipped:m/o,count:o}}function ve(n){let{box:e}=n,a=(n.leftEye.y+n.rightEye.y)/2-.1*e.height,r=e.y+.85*e.height;return{x:e.x+.15*e.width,y:a,width:.7*e.width,height:Math.max(1,r-a)}}function Be(n,e){let t=ve(e),a=T(n,t);if(a.count===0)return null;let r=Math.min(Math.max(e.nose.x,t.x+1),t.x+t.width-1),o=T(n,{x:t.x,y:t.y,width:r-t.x,height:t.height}),s=T(n,{x:r,y:t.y,width:t.x+t.width-r,height:t.height}),l=s.mean>0?o.mean/s.mean:o.mean>0?Number.POSITIVE_INFINITY:1;return{faceLuma:a.mean,halfRatio:l,clipped:a.clipped}}function Ge(n,e){let t=0,a=0;for(let r of[e.leftEyeBox,e.rightEyeBox]){let o=r.width*.15,s=r.height*.5,l=T(n,{x:r.x-o,y:r.y-s,width:r.width+2*o,height:r.height+2*s});t+=l.count,a+=l.clipped*l.count}return t===0?null:a/t}function Ae(n,e){let t=me(e),{box:a}=e,r={x:a.x-.2*a.width,y:t.y,width:1.4*a.width,height:a.y+a.height-t.y},o=0,s=0,l=0;for(let d of[t.x,t.x+.8*t.width]){let c=T(n,{x:d,y:t.y+.04*t.height,width:.2*t.width,height:.25*t.height},r);o+=c.count,s+=c.mean*c.count,l+=(c.sd*c.sd+c.mean*c.mean)*c.count}if(o===0)return null;let m=s/o;return{luma:m,sd:Math.sqrt(Math.max(0,l/o-m*m)),count:o}}function Oe(n,e){let t=W(ve(e),n),a=Math.max(1,Math.floor(Math.max(t.x1-t.x0,t.y1-t.y0)/Re)),r=(d,c)=>n.data[c*n.width+d],o=0,s=0,l=0;for(let d=t.y0+a;d<t.y1-a;d+=a)for(let c=t.x0+a;c<t.x1-a;c+=a){let b=r(c,d-a)+r(c-a,d)+r(c+a,d)+r(c,d+a)-4*r(c,d);o+=1,s+=b,l+=b*b}if(o===0)return null;let m=s/o;return Math.min(1,Math.max(0,l/o-m*m)/Ie)}function we(n,e){return{lighting:Be(n,e),eyeSpecular:Ge(n,e),background:Ae(n,e),sharpness:Oe(n,e)}}var Ue="/models-v3",De=640,_e=.92;function Y(n){return{width:n.videoWidth||0,height:n.videoHeight||0}}function j(n,e){if(typeof document<"u"){let t=document.createElement("canvas");return t.width=n,t.height=e,t}return typeof OffscreenCanvas=="function"?new OffscreenCanvas(n,e):null}function He(){let n=null;return(e,t)=>{let{width:a,height:r}=Y(e);if(a===0||r===0)return null;let o=t===null?1:Math.min(1,t/Math.max(a,r)),s=Math.round(a*o),l=Math.round(r*o),m;t===null?m=j(s,l):((n===null||n.width!==s||n.height!==l)&&(n=j(s,l)),m=n);let d=m?.getContext("2d",{willReadFrequently:!0});if(m==null||d==null)return null;d.drawImage(e,0,0,s,l);let c=null;try{c=d.getImageData(0,0,s,l)}catch{c=null}return{source:m,width:s,height:l,pixels:c}}}async function qe(n,e,t,a){let r=Math.round(t*e.width/e.height),o=j(r,t),s=o?.getContext("2d");if(o==null||s==null)throw new Error("canvas unavailable");return s.fillStyle="#fff",s.fillRect(0,0,r,t),s.drawImage(n.source,e.x,e.y,e.width,e.height,0,0,r,t),"convertToBlob"in o?o.convertToBlob({type:"image/jpeg",quality:a}):new Promise((l,m)=>{o.toBlob(d=>d===null?m(new Error("encode failed")):l(d),"image/jpeg",a)})}var z=class extends Error{};function Ne(n,e,t){return new Promise((a,r)=>{let o=setTimeout(()=>{r(new z(`init exceeded ${e}ms`)),n.then(t,()=>{})},e);n.then(s=>{clearTimeout(o),a(s)},s=>{clearTimeout(o),r(s)})})}function Ve(n){if(n instanceof V)return{kind:"notfound",retryable:!0,detail:{name:n.name,phase:"acquiring",engineKind:"backcamera"}};let e=oe(n),t=e==="overconstrained"?"generic":e,a=N(n);return{kind:t,retryable:t!=="insecure"&&t!=="unsupported",detail:{...a!==void 0?{name:a}:{},phase:"acquiring",engineKind:e}}}function Ke(n,e,t,a){let r=n.length===1?n[0]:void 0,o=r===void 0?null:G(r.landmarks,t,a),s=null;if(r!==void 0&&e.pixels!==null){let l=G(r.landmarks,e.width,e.height),m=xe(e.pixels);l!==null&&(s=we(m,l))}return{frameWidth:t,frameHeight:a,faces:n.length,geometry:o,matrix:r?.matrix??null,blendshapes:r?.blendshapes??null,stats:s}}function ct(n,e={},t=()=>"self",a){let r=ge(n.tuning,n.tuningVersion),o=ce(),s=e.now??(()=>performance.now()),l=e.setTimer??((i,u)=>setTimeout(i,u)),m=e.clearTimer??(i=>clearTimeout(i)),d=e.grabFrame??He(),c=e.encodeRegion??qe,b=e.getUserMedia??(i=>navigator.mediaDevices.getUserMedia(i)),L=e.enumerateDevices??(e.getUserMedia===void 0&&typeof navigator<"u"&&typeof navigator.mediaDevices?.enumerateDevices=="function"?()=>navigator.mediaDevices.enumerateDevices():void 0),Ce=e.createLandmarker??ye,J=n.assetBaseUrl??Ue,Q=de({enabled:n.keepScreenAwake!==!1}),S=he(r,{policy:n.policy??"reject"}),w=n.video,X=be({tuning:r.backgroundCheck,assetBaseUrl:J,...e.createSegmenter!==void 0?{createSegmenter:e.createSegmenter}:{},now:s}),f="idle",C=null,x=null,E=null,A=!1,g=!1,p=0,$=0,O=[],v="user",U=le(),Z=!1,ke=e.canChooseFacing??ue,k=i=>{f===i||g||(f=i,Q.setActive(i==="starting"||i==="gating"),o.emit("state",i))},D=()=>{E!==null&&m(E),E=null},I=()=>{D();for(let i of C?.getTracks()??[])i.stop();C=null;try{w.srcObject=null}catch{}},_=i=>{I(),k("error"),o.emit("error",i)},ee=()=>{let i=Math.max(s(),$+1);return $=i,i},Me=async i=>{let u=d(w,null),{width:M,height:P}=u??Y(w);if(u===null||x===null){S.reset();return}let h=x.detect(u.source,ee()),y=(h.length===1?h:O.length===1?O:[])[0],F=y===void 0?null:G(y.landmarks,M,P);if(F===null){S.reset();return}let B=fe(F,M,P,{margin:r.cropMargin,minWidth:r.resolution.minWidth,minHeight:r.resolution.minHeight}),q=Math.max(r.resolution.minHeight,B.height),Te=await c(u,B,q,_e);if(g||i!==p)return;let re={image:Te,width:Math.round(q*B.width/B.height),height:q,gate:S.summary(),facingMode:v};r.tuningVersion!==null&&(re.tuningVersion=r.tuningVersion),D(),k("captured"),o.emit("captured",re)},H=async i=>{if(!(g||i!==p||f!=="gating"||x===null)){if(!A){A=!0;try{let u=d(w,De);if(u!==null){let{width:M,height:P}=Y(w),h=x.detect(u.source,ee());O=h;let y=Ke(h,u,M||u.width,P||u.height);y.geometry!==null&&r.background.required&&(y.backgroundCheck=X.measure(u,y.geometry.box,M||u.width,P||u.height));let F=S.push(y,s());if(g||i!==p||(o.emit("gate",F),F.ready&&(await Me(i),f!=="gating")))return}}catch{}finally{A=!1}}!g&&i===p&&f==="gating"&&(E=l(()=>{H(i)},1e3/r.cadenceHz))}},Pe=()=>Ne(Ce(J),2e4,i=>i.close()),Le=i=>{let u=t()==="assisted"?"assisted":"self";return Z||U.facing(u,n.facing),U.facing(u,i)},te=!1;function Se(){return te||a===void 0||a.session()!=="choice"||t()!=="assisted"?!1:(te=!0,a.onModeChange("self"),v=K("self"),k("mode_switch"),R({facing:v}),!0)}let R=async i=>{if(g||f==="starting"||f==="gating")return;p+=1;let u=p;S.reset(),k("starting");let M=Le(i?.facing);if(C!==null&&M!==v&&I(),v=M,Z=!0,C===null&&e.getUserMedia===void 0&&(typeof navigator>"u"||typeof navigator.mediaDevices?.getUserMedia!="function")){let h=typeof window<"u"&&window.isSecureContext===!1?"insecure":"unsupported";_({kind:h,retryable:!1,detail:{phase:"preflight",engineKind:h}});return}let P=x!==null?Promise.resolve(x):Pe();P.catch(()=>{});try{if(C===null){let h=await se(v,{width:{ideal:r.camera.width},height:{ideal:r.camera.height}},{getUserMedia:b,...L!==void 0?{enumerateDevices:L}:{}});if(g||u!==p){for(let y of h.getTracks())y.stop();return}C=h,ie(h),v=ae(h)??v,w.srcObject=C,w.muted=!0,w.playsInline=!0,await w.play().catch(()=>{})}}catch(h){if(g||u!==p||h instanceof V&&Se())return;_(Ve(h));return}try{x=await P}catch(h){if(!g&&u===p){let y=N(h);_({kind:"generic",retryable:!0,detail:{...y!==void 0?{name:y}:{},phase:"models",engineKind:"models"}})}return}g||u!==p||(k("gating"),H(u))},ne=async()=>a!==void 0&&a.session()==="choice"&&await ke().catch(()=>!1),Fe=()=>f==="idle"||f==="starting"||f==="gating"||f==="error";return{handle:{get state(){return f},get captureMode(){return t()},get facingMode(){return v},on:(i,u)=>o.on(i,u),start:R,retry:()=>{if(!g){if(C!==null&&x!==null&&f!=="error"){p+=1;let i=p;D(),S.reset(),k("gating"),H(i);return}f="idle",R()}},switchCamera:()=>U.refuseSwitch(t()==="assisted"?"assisted":"self"),canSwitchCaptureMode:ne,setCaptureMode:async i=>{if(g||a===void 0||i===t()||!await ne()||g||!Fe())return!1;a.onModeChange(i);let u=K(i);return f==="idle"&&C===null||(p+=1,I(),v=u,k("mode_switch"),R({facing:u})),!0},destroy:()=>{g||(p+=1,I(),Q.setActive(!1),g=!0,x?.close(),x=null,X.close(),o.clear())}},gateScores:()=>S.scores(),setFlowState:i=>{(f==="captured"||f==="uploading"||f==="checking"||f==="done"&&i==="done")&&k(i)}}}function ut(){import("@mediapipe/tasks-vision").catch(()=>{})}export{Ee as a,Ie as b,xe as c,T as d,Be as e,Ge as f,Ae as g,Oe as h,we as i,De as j,_e as k,He as l,Ke as m,ct as n,ut as o};
@@ -1 +1 @@
1
- import{c as x}from"./chunk-TDLIXFDT.js";import{b}from"./chunk-FPXL63KZ.js";var T=480,y=Object.freeze({MIN_AREA_FRAC:.15,EDGE_CLIP_MARGIN_PX:4,STABLE_TICKS:3,IOU_STABLE_MIN:.85,RISE_PER_S:.9,FALL_PER_S:.25,GUIDE_EXPOSURE:.6,GUIDE_SHARPNESS:.35,ID3_BAND_MIN_WIDTH_FRAC:.55,ID3_BAND_ASPECT_MIN:4,ID3_BAND_ASPECT_MAX:40}),p=e=>Math.min(1,Math.max(0,e));function E(e,o,t){let n=[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft],i=0;for(let s=0;s<4;s++){let r=n[s],c=n[(s+1)%4];i+=r.x*c.y-c.x*r.y}let a=o*t;return a>0?Math.abs(i/2)/a:0}function I(e,o){let t=D(e),n=D(o),i=Math.max(t.x1,n.x1),a=Math.max(t.y1,n.y1),s=Math.min(t.x2,n.x2),r=Math.min(t.y2,n.y2),c=Math.max(0,s-i)*Math.max(0,r-a),u=(t.x2-t.x1)*(t.y2-t.y1),_=(n.x2-n.x1)*(n.y2-n.y1),m=u+_-c;return m>0?c/m:0}function R(e){let o=D(e);return{width:o.x2-o.x1,height:o.y2-o.y1}}function D(e){let o=[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft];return{x1:Math.min(...o.map(t=>t.x)),y1:Math.min(...o.map(t=>t.y)),x2:Math.max(...o.map(t=>t.x)),y2:Math.max(...o.map(t=>t.y))}}function M(e){let o=Math.hypot(e.topRight.x-e.topLeft.x,e.topRight.y-e.topLeft.y),t=Math.hypot(e.bottomRight.x-e.bottomLeft.x,e.bottomRight.y-e.bottomLeft.y),n=Math.hypot(e.bottomLeft.x-e.topLeft.x,e.bottomLeft.y-e.topLeft.y),i=Math.hypot(e.bottomRight.x-e.topRight.x,e.bottomRight.y-e.topRight.y),a=(o+t)/2,s=(n+i)/2;return a<=0||s<=0?0:Math.max(a,s)/Math.min(a,s)}var d=class{constructor(o,t={}){this.p=0;this.lastTickAt=null;this.lastQuad=null;this.streak=0;this.format=o,this.t={...y,...t}}reset(){this.p=0,this.lastTickAt=null,this.lastQuad=null,this.streak=0}tick(o){let{quad:t,quality:n,timestampMs:i}=o,a=this.lastTickAt===null?0:Math.max(0,(i-this.lastTickAt)/1e3);this.lastTickAt=i;let s=null;if(t===null)s="dcv1.no_doc";else if(this.format==="ID-3"){let h=R(t),f=h.height>0?h.width/h.height:0;h.width<this.t.ID3_BAND_MIN_WIDTH_FRAC*o.frameWidth?s="dcv1.come_closer":this.edgeClipped(t,o.frameWidth,o.frameHeight)?s="dcv1.fit_document":(f<this.t.ID3_BAND_ASPECT_MIN||f>this.t.ID3_BAND_ASPECT_MAX)&&(s="dcv1.wrong_shape")}else E(t,o.frameWidth,o.frameHeight)<this.t.MIN_AREA_FRAC?s="dcv1.come_closer":this.edgeClipped(t,o.frameWidth,o.frameHeight)?s="dcv1.fit_document":x(this.format,M(t))||(s="dcv1.wrong_shape");let r=s===null,c=p(n.exposure)>=this.t.GUIDE_EXPOSURE,u=p(n.sharpness)>=this.t.GUIDE_SHARPNESS,_=c&&u;if(r&&_&&t!==null){let h=this.lastQuad===null||I(t,this.lastQuad)>=this.t.IOU_STABLE_MIN;this.streak=h?this.streak+1:1}else this.streak=0;this.lastQuad=t;let m=r&&_;this.p=p(this.p+(m?this.t.RISE_PER_S:-this.t.FALL_PER_S)*a);let A=m&&this.streak>=this.t.STABLE_TICKS,l;if(s!==null)l=s;else if(c)u?l="dcv1.hold_still":l="dcv1.steady";else{let h=(b[0]+b[1])/2;l=n.meanLuma<h?"dcv1.more_light":"dcv1.too_bright"}return{at:i,quad:t,plausible:r,p:this.p,guidanceKey:l,ready:A,stableTicks:this.streak}}edgeClipped(o,t,n){let i=this.t.EDGE_CLIP_MARGIN_PX;return[o.topLeft,o.topRight,o.bottomRight,o.bottomLeft].some(s=>s.x<=i||s.y<=i||s.x>=t-i||s.y>=n-i)}};export{T as a,y as b,E as c,I as d,R as e,d as f};
1
+ import{c as x}from"./chunk-BPKDXDDH.js";import{b}from"./chunk-FK2DJADA.js";var T=480,y=Object.freeze({MIN_AREA_FRAC:.15,EDGE_CLIP_MARGIN_PX:4,STABLE_TICKS:3,IOU_STABLE_MIN:.85,RISE_PER_S:.9,FALL_PER_S:.25,GUIDE_EXPOSURE:.6,GUIDE_SHARPNESS:.35,ID3_BAND_MIN_WIDTH_FRAC:.55,ID3_BAND_ASPECT_MIN:4,ID3_BAND_ASPECT_MAX:40}),p=e=>Math.min(1,Math.max(0,e));function E(e,o,t){let n=[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft],i=0;for(let s=0;s<4;s++){let r=n[s],c=n[(s+1)%4];i+=r.x*c.y-c.x*r.y}let a=o*t;return a>0?Math.abs(i/2)/a:0}function I(e,o){let t=D(e),n=D(o),i=Math.max(t.x1,n.x1),a=Math.max(t.y1,n.y1),s=Math.min(t.x2,n.x2),r=Math.min(t.y2,n.y2),c=Math.max(0,s-i)*Math.max(0,r-a),u=(t.x2-t.x1)*(t.y2-t.y1),_=(n.x2-n.x1)*(n.y2-n.y1),m=u+_-c;return m>0?c/m:0}function R(e){let o=D(e);return{width:o.x2-o.x1,height:o.y2-o.y1}}function D(e){let o=[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft];return{x1:Math.min(...o.map(t=>t.x)),y1:Math.min(...o.map(t=>t.y)),x2:Math.max(...o.map(t=>t.x)),y2:Math.max(...o.map(t=>t.y))}}function M(e){let o=Math.hypot(e.topRight.x-e.topLeft.x,e.topRight.y-e.topLeft.y),t=Math.hypot(e.bottomRight.x-e.bottomLeft.x,e.bottomRight.y-e.bottomLeft.y),n=Math.hypot(e.bottomLeft.x-e.topLeft.x,e.bottomLeft.y-e.topLeft.y),i=Math.hypot(e.bottomRight.x-e.topRight.x,e.bottomRight.y-e.topRight.y),a=(o+t)/2,s=(n+i)/2;return a<=0||s<=0?0:Math.max(a,s)/Math.min(a,s)}var d=class{constructor(o,t={}){this.p=0;this.lastTickAt=null;this.lastQuad=null;this.streak=0;this.format=o,this.t={...y,...t}}reset(){this.p=0,this.lastTickAt=null,this.lastQuad=null,this.streak=0}tick(o){let{quad:t,quality:n,timestampMs:i}=o,a=this.lastTickAt===null?0:Math.max(0,(i-this.lastTickAt)/1e3);this.lastTickAt=i;let s=null;if(t===null)s="dcv1.no_doc";else if(this.format==="ID-3"){let h=R(t),f=h.height>0?h.width/h.height:0;h.width<this.t.ID3_BAND_MIN_WIDTH_FRAC*o.frameWidth?s="dcv1.come_closer":this.edgeClipped(t,o.frameWidth,o.frameHeight)?s="dcv1.fit_document":(f<this.t.ID3_BAND_ASPECT_MIN||f>this.t.ID3_BAND_ASPECT_MAX)&&(s="dcv1.wrong_shape")}else E(t,o.frameWidth,o.frameHeight)<this.t.MIN_AREA_FRAC?s="dcv1.come_closer":this.edgeClipped(t,o.frameWidth,o.frameHeight)?s="dcv1.fit_document":x(this.format,M(t))||(s="dcv1.wrong_shape");let r=s===null,c=p(n.exposure)>=this.t.GUIDE_EXPOSURE,u=p(n.sharpness)>=this.t.GUIDE_SHARPNESS,_=c&&u;if(r&&_&&t!==null){let h=this.lastQuad===null||I(t,this.lastQuad)>=this.t.IOU_STABLE_MIN;this.streak=h?this.streak+1:1}else this.streak=0;this.lastQuad=t;let m=r&&_;this.p=p(this.p+(m?this.t.RISE_PER_S:-this.t.FALL_PER_S)*a);let A=m&&this.streak>=this.t.STABLE_TICKS,l;if(s!==null)l=s;else if(c)u?l="dcv1.hold_still":l="dcv1.steady";else{let h=(b[0]+b[1])/2;l=n.meanLuma<h?"dcv1.more_light":"dcv1.too_bright"}return{at:i,quad:t,plausible:r,p:this.p,guidanceKey:l,ready:A,stableTicks:this.streak}}edgeClipped(o,t,n){let i=this.t.EDGE_CLIP_MARGIN_PX;return[o.topLeft,o.topRight,o.bottomRight,o.bottomLeft].some(s=>s.x<=i||s.y<=i||s.x>=t-i||s.y>=n-i)}};export{T as a,y as b,E as c,I as d,R as e,d as f};
@@ -0,0 +1 @@
1
+ function c(e,n){return{video:{width:{ideal:1280,max:1280},height:{ideal:720,max:720},facingMode:n,frameRate:{ideal:24,max:30}},audio:!1}}var o=600;function i(){if(typeof window>"u"||typeof navigator>"u")return"desktop";let e=navigator.userAgentData,n=e?.mobile||/Android|i(Pad)?OS/.test(String(e?.platform)),t=String(navigator.userAgent??"");if(/iPhone|iPod/i.test(t))return"phone";if(/iPad/i.test(t))return"tablet";if(/Android/i.test(t))return/Mobile/i.test(t)?"phone":"tablet";if(/BlackBerry|IEMobile|Opera Mini/i.test(t))return"phone";if(!n){if(Number(navigator.maxTouchPoints??0)<=1)return"desktop";if(/Macintosh/.test(t))return"tablet";if(/Windows NT|CrOS/.test(t)||!s())return"desktop"}let r=a();return r>0&&r<o?"phone":"tablet"}function u(){return i()!=="desktop"}function a(){try{let e=window.screen,n=Number(e?.width??0),t=Number(e?.height??0);return n>0&&t>0?Math.min(n,t):0}catch{return 0}}function d(e){try{let t=e?.getVideoTracks?.()[0]?.getSettings?.().facingMode;return t==="user"||t==="environment"?t:null}catch{return null}}function s(){try{return typeof window.matchMedia=="function"&&window.matchMedia("(pointer: coarse)").matches}catch{return!1}}var l=.45,f=.9,p=.4;export{c as a,o as b,i as c,u as d,d as e,l as f,f as g,p as h};
@@ -0,0 +1 @@
1
+ function y(){let e=new Map;return{on(i,n){let t=e.get(i);t===void 0&&(t=new Set,e.set(i,t));let r=n;return t.add(r),()=>{t?.delete(r)}},emit(i,n){let t=e.get(i);if(t!==void 0)for(let r of[...t])r(n)},count(i){return e.get(i)?.size??0},clear(){e.clear()}}}async function f(){try{return typeof navigator>"u"||typeof navigator.permissions?.query!="function"?null:await navigator.permissions.query({name:"camera"})}catch{return null}}function c(e){return e==="granted"||e==="prompt"||e==="denied"?e:"unknown"}async function k(){let e=await f();return e===null?"unknown":c(e.state)}function w(e){let i=!1,n=null,t=()=>{!i&&n!==null&&e(c(n.state))};return f().then(r=>{i||(n=r,e(r===null?"unknown":c(r.state)),r?.addEventListener?.("change",t))}),()=>{i=!0,n?.removeEventListener?.("change",t)}}async function b(){if(typeof navigator>"u")return!1;let e=String(navigator.userAgent??"");if(/Android|iPhone|iPad|iPod/i.test(e)||/Macintosh/.test(e)&&(navigator.maxTouchPoints??0)>1)return!0;try{return(await navigator.mediaDevices?.enumerateDevices?.()??[]).filter(n=>n.kind==="videoinput").length>=2}catch{return!1}}var h=e=>e==="self"?"user":"environment";function S(){let e=!1,i=t=>{e||(e=!0,console.warn(`[@sekyro/web] ${t}`))},n=t=>t==="self"?"this capture is a self capture (the person films themselves), which uses the front camera only. The back camera is for assisted capture, set in the flow.":"this capture is an assisted capture (another person films the face), which uses the back camera only. The front camera is for self capture, set in the flow.";return{facing:(t,r)=>{let o=h(t);return r!==void 0&&r!==o&&i(`facing "${r}" ignored: ${n(t)}`),o},refuseSwitch:t=>(i(`switchCamera() ignored: ${n(t)}`),!1)}}function v(){if(typeof navigator>"u"||!("wakeLock"in navigator))return null;let e=navigator.wakeLock;return typeof e?.request=="function"?e:null}function m(){return typeof document>"u"||document.visibilityState==="visible"}function p(e){try{e.release().catch(()=>{})}catch{}}function P(e={}){if(e.enabled===!1)return{setActive:()=>{}};let i=!1,n=null,t=!1,r=!1,o=()=>{if(!i||t||n!==null&&!n.released)return;let a=v();if(a===null||!m())return;let s;try{s=a.request("screen")}catch{return}t=!0,s.then(u=>{if(t=!1,!i){p(u);return}n=u,u.addEventListener?.("release",()=>{n===u&&(n=null)})},()=>{t=!1})},l=()=>{m()&&o()},d=a=>{typeof document>"u"||a===r||(r=a,a?document.addEventListener("visibilitychange",l):document.removeEventListener("visibilitychange",l))};return{setActive:a=>{if(i=a,a){if(v()===null)return;d(!0),o();return}if(d(!1),n!==null){let s=n;n=null,p(s)}}}}export{y as a,k as b,w as c,b as d,h as e,S as f,P as g};
@@ -1 +1 @@
1
- import{a as T,b as R}from"./chunk-DK5YPBDQ.js";var N=1e3,_=[[1,0],[0,1],[1,1],[1,-1]];function w(i){let{width:t,height:e,data:r}=i;if(t<16||e<16)return-1;let s=new Uint8Array(t*e);for(let n=0,a=0;n<s.length;n+=1,a+=4)s[n]=Math.round(.299*(r[a]??0)+.587*(r[a+1]??0)+.114*(r[a+2]??0));let o=-1;for(let[n,a]of _){let l=new Uint32Array(256),c=new Float64Array(256),p=0;for(let h=1;h<e-1;h+=1){let u=h*t,S=(h+a)*t,A=(h-a)*t;for(let g=1;g<t-1;g+=1){let y=s[S+g+n]??0,z=s[A+g-n]??0,v=Math.abs(y-z);l[v]=(l[v]??0)+1,c[v]=(c[v]??0)+Math.abs(y+z-2*(s[u+g]??0)),p+=1}}let M=Math.max(1,Math.floor(p/20)),m=0,d=0,f=0;for(let h=255;h>=0&&m<M;h-=1){let u=l[h]??0;m+=u,d+=u*h,f+=c[h]??0}if(d===0)return 0;let b=f/d;o=o<0?b:Math.min(o,b)}return o}var I=.06;function P(i,t,e,r=I){if(i===null||t.width<=0||t.height<=0)return null;let s=[i.topLeft,i.topRight,i.bottomRight,i.bottomLeft],o=e.width/t.width,n=e.height/t.height,a=Math.min(...s.map(u=>u.x))*o,l=Math.max(...s.map(u=>u.x))*o,c=Math.min(...s.map(u=>u.y))*n,p=Math.max(...s.map(u=>u.y))*n,M=(l-a)*r,m=(p-c)*r,d=Math.max(0,Math.floor(a-M)),f=Math.max(0,Math.floor(c-m)),b=Math.min(e.width,Math.ceil(l+M)),h=Math.min(e.height,Math.ceil(p+m));return b-d<16||h-f<16?null:{x:d,y:f,width:b-d,height:h-f}}function F(i,t){let e=new Uint8ClampedArray(t.width*t.height*4);for(let r=0;r<t.height;r+=1)for(let s=0;s<t.width*4;s+=1)e[r*t.width*4+s]=i.data[((t.y+r)*i.width+t.x)*4+s]??0;return{data:e,width:t.width,height:t.height}}function E(i,t=1e3){let e=t/Math.max(i.width,i.height);if(e>=1)return i;let r=Math.max(1,Math.round(i.width*e)),s=Math.max(1,Math.round(i.height*e)),o=new Uint8ClampedArray(r*s*4);for(let n=0;n<s;n+=1){let a=Math.floor(n/e),l=Math.min(i.height,Math.max(a+1,Math.floor((n+1)/e)));for(let c=0;c<r;c+=1){let p=Math.floor(c/e),M=Math.min(i.width,Math.max(p+1,Math.floor((c+1)/e)));for(let m=0;m<3;m+=1){let d=0;for(let f=a;f<l;f+=1)for(let b=p;b<M;b+=1)d+=i.data[(f*i.width+b)*4+m]??0;o[(n*r+c)*4+m]=d/((l-a)*(M-p))}o[(n*r+c)*4+3]=255}}return{data:o,width:r,height:s}}function V(i,t){return w(E(t===null?i:F(i,t)))}function B(i,t){let e=t??{x:0,y:0,width:i.width,height:i.height},r=Math.min(1,1e3/Math.max(e.width,e.height)),s=Math.max(1,Math.round(e.width*r)),o=Math.max(1,Math.round(e.height*r)),n=document.createElement("canvas");n.width=s,n.height=o;try{let a=n.getContext("2d",{willReadFrequently:!0});return a===null?-1:(a.imageSmoothingQuality="high",a.drawImage(i,e.x,e.y,e.width,e.height,0,0,s,o),w(a.getImageData(0,0,s,o)))}catch{return-1}finally{n.width=0,n.height=0}}var k=class{constructor(t=2){this.stableReads=t;this.last=null;this.run=0}offer(t){return t===null?(this.reset(),!1):(this.run=t===this.last?this.run+1:1,this.last=t,this.run>=this.stableReads)}reset(){this.last=null,this.run=0}};var D=Object.freeze({...T,minIntervalMs:150,maxWidthPx:480,detectorLimit:960,searchTimeoutMs:12e3}),O=Object.freeze({detectorLimit:960,bandMaxWidthPx:1280,minBandWidthPx:900,bandTop:.55,minIntervalMs:150,stableReads:2,profileReads:5,maxReadMs:1200,searchTimeoutMs:12e3}),C=(i,t,e)=>createImageBitmap(i,Math.round(t.x),Math.round(t.y),Math.max(1,Math.round(t.w)),Math.max(1,Math.round(t.h)),{resizeWidth:Math.max(1,Math.round(Math.min(t.w,e))),resizeQuality:"high"}),x=(i,t)=>{if(i.length===0)return 0;let e=[...i].sort((r,s)=>r-s);return e[Math.min(e.length-1,Math.floor(e.length*t))]};function G(i){return i<=250?"fast":i<=600?"mid":"slow"}function Y(i,t,e){let r=i.y+i.h*t,s=Math.min(e,i.y+i.h*1.05);return{x:i.x,y:r,w:i.w,h:Math.max(1,s-r)}}var L=class{constructor(t){this.o=t;this.engine=null;this.gen=0;this.inFlight=!1;this.lastReadAt=Number.NEGATIVE_INFINITY;this.firstSeen=null;this.reads=0;this.times=[];this.mrzState={state:"searching"};this.lockState={state:"searching"};this.fallback=null;this.lockOff=!1;this.lockError=!1;this.fired=null;this.valid=null;this.faceMode="off";this.disabled=!1;this.crop=t.crop??C,this.mrzGate=new k(t.liveMrz?.stableReads??2),this.lockGate=new R(t.textLock??D)}setEngine(t){this.engine=t}get bandTop(){return this.o.liveMrz?.bandTop??O.bandTop}get hasEngine(){return this.engine!==null&&!this.disabled}reset(){this.gen++,this.inFlight=!1,this.lastReadAt=Number.NEGATIVE_INFINITY,this.firstSeen=null,this.reads=0,this.times=[],this.mrzGate.reset(),this.lockGate.reset(),this.mrzState={state:"searching"},this.lockState={state:"searching"},this.fallback=null,this.lockOff=!1,this.lockError=!1,this.fired=null,this.valid=null,this.faceMode="off"}rearmFace(){this.gen++,this.inFlight=!1,this.lastReadAt=Number.NEGATIVE_INFINITY,this.mrzGate.reset(),this.lockGate.reset(),this.fired=null,this.valid=null,this.fallback===null&&(this.mrzState={state:"searching"}),this.lockOff||(this.lockState={state:"searching"})}liveCapture(){return this.fired?.via==="live_mrz"?this.valid:null}modeFor(t){return this.engine===null||this.disabled?"off":t.mrzFace&&this.o.liveMrz!==null&&this.fallback===null?"live_mrz":this.o.textLock!==null&&!this.lockOff?"text_lock":"off"}tick(t){let e=this.modeFor(t);return e!=="off"&&(this.faceMode=e),this.fired!==null?{ready:!0,via:this.fired.via,suspendQuality:this.fired.via==="live_mrz",mode:e,...this.states()}:e==="live_mrz"?this.liveTick(t,this.o.liveMrz):e==="text_lock"?this.lockTick(t,this.o.textLock):{ready:!1,suspendQuality:!1,mode:e,...this.states()}}states(){return{...this.faceMode==="live_mrz"||this.fallback!==null?{mrz:this.fallback!==null?{state:"fallback",reason:this.fallback}:this.mrzState}:{},...this.faceMode==="text_lock"?{lock:this.lockState}:{}}}canRead(t,e){let r=this.engine;return r!==null&&!this.inFlight&&!r.busy&&t-this.lastReadAt>=e}fall(t){this.fallback=t,this.mrzGate.reset()}liveTick(t,e){let r=()=>this.fallback!==null?{ready:!1,suspendQuality:!1,mode:"live_mrz",mrz:{state:"fallback",reason:this.fallback}}:{ready:!1,suspendQuality:!0,mode:"live_mrz",mrz:this.mrzState};if(!t.present||t.band===null)return this.mrzGate.reset(),this.mrzState={state:"searching"},r();if(this.firstSeen??(this.firstSeen=t.atMs),t.atMs-this.firstSeen>e.searchTimeoutMs)return this.fall("timeout"),r();if(t.band.w<e.minBandWidthPx)return t.card!==null&&t.card.w<e.minBandWidthPx?(this.fall("unsupported"),r()):(this.mrzState={state:"reading",coach:t.portrait?"turnSideways":"moveCloser"},{ready:!1,suspendQuality:!1,mode:"live_mrz",mrz:this.mrzState});if(!this.canRead(t.atMs,e.minIntervalMs))return r();this.inFlight=!0,this.lastReadAt=t.atMs;let s=this.gen,o=this.engine,n=t.glareOk?t.sharpOk?void 0:"holdStill":"glare";return this.crop(t.video,t.band,e.bandMaxWidthPx).then(a=>o.bandRead(a,e.detectorLimit)).then(a=>{if(s===this.gen){if(this.reads++,this.times.push(a.ms),this.times.length>8&&this.times.shift(),this.reads>=e.profileReads&&x(this.times,.5)>e.maxReadMs)return this.fall("slow");if(this.mrzGate.offer(a.valid?a.digest??null:null)&&a.format&&a.digest){this.valid={format:a.format,...a.documentCode!==void 0?{documentCode:a.documentCode}:{},digest:a.digest,lineCount:a.lineCount,framesToValid:this.reads,msToValid:Math.round(t.atMs-(this.firstSeen??t.atMs))},this.mrzState={state:"valid",format:a.format},this.fired={via:"live_mrz",at:t.atMs};return}this.mrzState={state:"reading",...n?{coach:n}:{},...a.format?{format:a.format}:{}}}}).catch(()=>{s===this.gen&&this.fall("error")}).finally(()=>{s===this.gen&&(this.inFlight=!1)}),r()}lockTick(t,e){let r=()=>({ready:!1,suspendQuality:!1,mode:"text_lock",lock:this.lockState,...this.fallback!==null?{mrz:{state:"fallback",reason:this.fallback}}:{}});if(!t.present||t.card===null)return this.lockGate.reset(),this.lockState={state:"searching"},r();if(this.firstSeen??(this.firstSeen=t.atMs),t.atMs-this.firstSeen>e.searchTimeoutMs)return this.lockOff=!0,r();if(!this.canRead(t.atMs,e.minIntervalMs))return r();this.inFlight=!0,this.lastReadAt=t.atMs;let s=this.gen,o=this.engine,n={glareOk:t.glareOk,sharpOk:t.sharpOk};return this.crop(t.video,t.card,e.maxWidthPx).then(a=>o.layoutRead(a,e.detectorLimit)).then(a=>{if(s!==this.gen)return;this.reads++,this.times.push(a.ms),this.times.length>8&&this.times.shift();let l=this.lockGate.offer(a,t.atMs,n);this.lockState=l.state==="locked"?{state:"locked"}:{state:l.state,...l.hint?{hint:l.hint}:{}},l.state==="locked"&&(this.fired={via:"text_lock",at:t.atMs})}).catch(()=>{s===this.gen&&(this.lockOff=!0,this.lockError=!0)}).finally(()=>{s===this.gen&&(this.inFlight=!1)}),r()}disable(){this.disabled=!0,this.reset()}report(t,e,r){let s=this.faceMode;if(s==="off")return null;let o=x(this.times,.5),n={capture:t,mode:s,reads:this.reads,...this.times.length>0?{readP50Ms:Math.round(o),readP90Ms:Math.round(x(this.times,.9)),deviceClass:G(o)}:{}};return s==="live_mrz"?this.fired?.via==="live_mrz"&&this.valid!==null&&e==="live_mrz"?{...n,outcome:"valid",format:this.valid.format,framesToValid:this.valid.framesToValid,msToValid:this.valid.msToValid}:this.fallback!==null?{...n,outcome:this.fallback}:{...n,outcome:r-(this.firstSeen??r)>=(this.o.liveMrz?.searchTimeoutMs??1/0)?"timeout":"off"}:this.fired?.via==="text_lock"?{...n,outcome:"locked",framesToLock:Math.max(1,this.reads),msToLock:Math.round(this.fired.at-(this.firstSeen??this.fired.at))}:{...n,outcome:this.lockError?"error":this.lockOff?"timeout":"off"}}};export{N as a,w as b,I as c,P as d,F as e,E as f,V as g,B as h,D as i,O as j,Y as k,L as l};
1
+ import{a as T,b as R}from"./chunk-LYYLXNA4.js";var N=1e3,_=[[1,0],[0,1],[1,1],[1,-1]];function w(i){let{width:t,height:e,data:r}=i;if(t<16||e<16)return-1;let s=new Uint8Array(t*e);for(let n=0,a=0;n<s.length;n+=1,a+=4)s[n]=Math.round(.299*(r[a]??0)+.587*(r[a+1]??0)+.114*(r[a+2]??0));let o=-1;for(let[n,a]of _){let l=new Uint32Array(256),c=new Float64Array(256),p=0;for(let h=1;h<e-1;h+=1){let u=h*t,S=(h+a)*t,A=(h-a)*t;for(let g=1;g<t-1;g+=1){let y=s[S+g+n]??0,z=s[A+g-n]??0,v=Math.abs(y-z);l[v]=(l[v]??0)+1,c[v]=(c[v]??0)+Math.abs(y+z-2*(s[u+g]??0)),p+=1}}let M=Math.max(1,Math.floor(p/20)),m=0,d=0,f=0;for(let h=255;h>=0&&m<M;h-=1){let u=l[h]??0;m+=u,d+=u*h,f+=c[h]??0}if(d===0)return 0;let b=f/d;o=o<0?b:Math.min(o,b)}return o}var I=.06;function P(i,t,e,r=I){if(i===null||t.width<=0||t.height<=0)return null;let s=[i.topLeft,i.topRight,i.bottomRight,i.bottomLeft],o=e.width/t.width,n=e.height/t.height,a=Math.min(...s.map(u=>u.x))*o,l=Math.max(...s.map(u=>u.x))*o,c=Math.min(...s.map(u=>u.y))*n,p=Math.max(...s.map(u=>u.y))*n,M=(l-a)*r,m=(p-c)*r,d=Math.max(0,Math.floor(a-M)),f=Math.max(0,Math.floor(c-m)),b=Math.min(e.width,Math.ceil(l+M)),h=Math.min(e.height,Math.ceil(p+m));return b-d<16||h-f<16?null:{x:d,y:f,width:b-d,height:h-f}}function F(i,t){let e=new Uint8ClampedArray(t.width*t.height*4);for(let r=0;r<t.height;r+=1)for(let s=0;s<t.width*4;s+=1)e[r*t.width*4+s]=i.data[((t.y+r)*i.width+t.x)*4+s]??0;return{data:e,width:t.width,height:t.height}}function E(i,t=1e3){let e=t/Math.max(i.width,i.height);if(e>=1)return i;let r=Math.max(1,Math.round(i.width*e)),s=Math.max(1,Math.round(i.height*e)),o=new Uint8ClampedArray(r*s*4);for(let n=0;n<s;n+=1){let a=Math.floor(n/e),l=Math.min(i.height,Math.max(a+1,Math.floor((n+1)/e)));for(let c=0;c<r;c+=1){let p=Math.floor(c/e),M=Math.min(i.width,Math.max(p+1,Math.floor((c+1)/e)));for(let m=0;m<3;m+=1){let d=0;for(let f=a;f<l;f+=1)for(let b=p;b<M;b+=1)d+=i.data[(f*i.width+b)*4+m]??0;o[(n*r+c)*4+m]=d/((l-a)*(M-p))}o[(n*r+c)*4+3]=255}}return{data:o,width:r,height:s}}function V(i,t){return w(E(t===null?i:F(i,t)))}function B(i,t){let e=t??{x:0,y:0,width:i.width,height:i.height},r=Math.min(1,1e3/Math.max(e.width,e.height)),s=Math.max(1,Math.round(e.width*r)),o=Math.max(1,Math.round(e.height*r)),n=document.createElement("canvas");n.width=s,n.height=o;try{let a=n.getContext("2d",{willReadFrequently:!0});return a===null?-1:(a.imageSmoothingQuality="high",a.drawImage(i,e.x,e.y,e.width,e.height,0,0,s,o),w(a.getImageData(0,0,s,o)))}catch{return-1}finally{n.width=0,n.height=0}}var k=class{constructor(t=2){this.stableReads=t;this.last=null;this.run=0}offer(t){return t===null?(this.reset(),!1):(this.run=t===this.last?this.run+1:1,this.last=t,this.run>=this.stableReads)}reset(){this.last=null,this.run=0}};var D=Object.freeze({...T,minIntervalMs:150,maxWidthPx:480,detectorLimit:960,searchTimeoutMs:12e3}),O=Object.freeze({detectorLimit:960,bandMaxWidthPx:1280,minBandWidthPx:900,bandTop:.55,minIntervalMs:150,stableReads:2,profileReads:5,maxReadMs:1200,searchTimeoutMs:12e3}),C=(i,t,e)=>createImageBitmap(i,Math.round(t.x),Math.round(t.y),Math.max(1,Math.round(t.w)),Math.max(1,Math.round(t.h)),{resizeWidth:Math.max(1,Math.round(Math.min(t.w,e))),resizeQuality:"high"}),x=(i,t)=>{if(i.length===0)return 0;let e=[...i].sort((r,s)=>r-s);return e[Math.min(e.length-1,Math.floor(e.length*t))]};function G(i){return i<=250?"fast":i<=600?"mid":"slow"}function Y(i,t,e){let r=i.y+i.h*t,s=Math.min(e,i.y+i.h*1.05);return{x:i.x,y:r,w:i.w,h:Math.max(1,s-r)}}var L=class{constructor(t){this.o=t;this.engine=null;this.gen=0;this.inFlight=!1;this.lastReadAt=Number.NEGATIVE_INFINITY;this.firstSeen=null;this.reads=0;this.times=[];this.mrzState={state:"searching"};this.lockState={state:"searching"};this.fallback=null;this.lockOff=!1;this.lockError=!1;this.fired=null;this.valid=null;this.faceMode="off";this.disabled=!1;this.crop=t.crop??C,this.mrzGate=new k(t.liveMrz?.stableReads??2),this.lockGate=new R(t.textLock??D)}setEngine(t){this.engine=t}get bandTop(){return this.o.liveMrz?.bandTop??O.bandTop}get hasEngine(){return this.engine!==null&&!this.disabled}reset(){this.gen++,this.inFlight=!1,this.lastReadAt=Number.NEGATIVE_INFINITY,this.firstSeen=null,this.reads=0,this.times=[],this.mrzGate.reset(),this.lockGate.reset(),this.mrzState={state:"searching"},this.lockState={state:"searching"},this.fallback=null,this.lockOff=!1,this.lockError=!1,this.fired=null,this.valid=null,this.faceMode="off"}rearmFace(){this.gen++,this.inFlight=!1,this.lastReadAt=Number.NEGATIVE_INFINITY,this.mrzGate.reset(),this.lockGate.reset(),this.fired=null,this.valid=null,this.fallback===null&&(this.mrzState={state:"searching"}),this.lockOff||(this.lockState={state:"searching"})}liveCapture(){return this.fired?.via==="live_mrz"?this.valid:null}modeFor(t){return this.engine===null||this.disabled?"off":t.mrzFace&&this.o.liveMrz!==null&&this.fallback===null?"live_mrz":this.o.textLock!==null&&!this.lockOff?"text_lock":"off"}tick(t){let e=this.modeFor(t);return e!=="off"&&(this.faceMode=e),this.fired!==null?{ready:!0,via:this.fired.via,suspendQuality:this.fired.via==="live_mrz",mode:e,...this.states()}:e==="live_mrz"?this.liveTick(t,this.o.liveMrz):e==="text_lock"?this.lockTick(t,this.o.textLock):{ready:!1,suspendQuality:!1,mode:e,...this.states()}}states(){return{...this.faceMode==="live_mrz"||this.fallback!==null?{mrz:this.fallback!==null?{state:"fallback",reason:this.fallback}:this.mrzState}:{},...this.faceMode==="text_lock"?{lock:this.lockState}:{}}}canRead(t,e){let r=this.engine;return r!==null&&!this.inFlight&&!r.busy&&t-this.lastReadAt>=e}fall(t){this.fallback=t,this.mrzGate.reset()}liveTick(t,e){let r=()=>this.fallback!==null?{ready:!1,suspendQuality:!1,mode:"live_mrz",mrz:{state:"fallback",reason:this.fallback}}:{ready:!1,suspendQuality:!0,mode:"live_mrz",mrz:this.mrzState};if(!t.present||t.band===null)return this.mrzGate.reset(),this.mrzState={state:"searching"},r();if(this.firstSeen??(this.firstSeen=t.atMs),t.atMs-this.firstSeen>e.searchTimeoutMs)return this.fall("timeout"),r();if(t.band.w<e.minBandWidthPx)return t.card!==null&&t.card.w<e.minBandWidthPx?(this.fall("unsupported"),r()):(this.mrzState={state:"reading",coach:t.portrait?"turnSideways":"moveCloser"},{ready:!1,suspendQuality:!1,mode:"live_mrz",mrz:this.mrzState});if(!this.canRead(t.atMs,e.minIntervalMs))return r();this.inFlight=!0,this.lastReadAt=t.atMs;let s=this.gen,o=this.engine,n=t.glareOk?t.sharpOk?void 0:"holdStill":"glare";return this.crop(t.video,t.band,e.bandMaxWidthPx).then(a=>o.bandRead(a,e.detectorLimit)).then(a=>{if(s===this.gen){if(this.reads++,this.times.push(a.ms),this.times.length>8&&this.times.shift(),this.reads>=e.profileReads&&x(this.times,.5)>e.maxReadMs)return this.fall("slow");if(this.mrzGate.offer(a.valid?a.digest??null:null)&&a.format&&a.digest){this.valid={format:a.format,...a.documentCode!==void 0?{documentCode:a.documentCode}:{},digest:a.digest,lineCount:a.lineCount,framesToValid:this.reads,msToValid:Math.round(t.atMs-(this.firstSeen??t.atMs))},this.mrzState={state:"valid",format:a.format},this.fired={via:"live_mrz",at:t.atMs};return}this.mrzState={state:"reading",...n?{coach:n}:{},...a.format?{format:a.format}:{}}}}).catch(()=>{s===this.gen&&this.fall("error")}).finally(()=>{s===this.gen&&(this.inFlight=!1)}),r()}lockTick(t,e){let r=()=>({ready:!1,suspendQuality:!1,mode:"text_lock",lock:this.lockState,...this.fallback!==null?{mrz:{state:"fallback",reason:this.fallback}}:{}});if(!t.present||t.card===null)return this.lockGate.reset(),this.lockState={state:"searching"},r();if(this.firstSeen??(this.firstSeen=t.atMs),t.atMs-this.firstSeen>e.searchTimeoutMs)return this.lockOff=!0,r();if(!this.canRead(t.atMs,e.minIntervalMs))return r();this.inFlight=!0,this.lastReadAt=t.atMs;let s=this.gen,o=this.engine,n={glareOk:t.glareOk,sharpOk:t.sharpOk};return this.crop(t.video,t.card,e.maxWidthPx).then(a=>o.layoutRead(a,e.detectorLimit)).then(a=>{if(s!==this.gen)return;this.reads++,this.times.push(a.ms),this.times.length>8&&this.times.shift();let l=this.lockGate.offer(a,t.atMs,n);this.lockState=l.state==="locked"?{state:"locked"}:{state:l.state,...l.hint?{hint:l.hint}:{}},l.state==="locked"&&(this.fired={via:"text_lock",at:t.atMs})}).catch(()=>{s===this.gen&&(this.lockOff=!0,this.lockError=!0)}).finally(()=>{s===this.gen&&(this.inFlight=!1)}),r()}disable(){this.disabled=!0,this.reset()}report(t,e,r){let s=this.faceMode;if(s==="off")return null;let o=x(this.times,.5),n={capture:t,mode:s,reads:this.reads,...this.times.length>0?{readP50Ms:Math.round(o),readP90Ms:Math.round(x(this.times,.9)),deviceClass:G(o)}:{}};return s==="live_mrz"?this.fired?.via==="live_mrz"&&this.valid!==null&&e==="live_mrz"?{...n,outcome:"valid",format:this.valid.format,framesToValid:this.valid.framesToValid,msToValid:this.valid.msToValid}:this.fallback!==null?{...n,outcome:this.fallback}:{...n,outcome:r-(this.firstSeen??r)>=(this.o.liveMrz?.searchTimeoutMs??1/0)?"timeout":"off"}:this.fired?.via==="text_lock"?{...n,outcome:"locked",framesToLock:Math.max(1,this.reads),msToLock:Math.round(this.fired.at-(this.firstSeen??this.fired.at))}:{...n,outcome:this.lockError?"error":this.lockOff?"timeout":"off"}}};export{N as a,w as b,I as c,P as d,F as e,E as f,V as g,B as h,D as i,O as j,Y as k,L as l};
@@ -1 +1 @@
1
- import{d as J,h as he,i as ye,j as Se,l as Me}from"./chunk-G6LKLN4U.js";import{f as be}from"./chunk-TDLIXFDT.js";import{m as V}from"./chunk-P3H3D33O.js";import{a as fe,e as ge}from"./chunk-GT2ZLGF7.js";import{k as $}from"./chunk-CQ7SKLMC.js";var qe={low:{maxLongEdge:1920,payloadTargetBytes:7e5,qMin:.7,qMax:.92},mid:{maxLongEdge:2240,payloadTargetBytes:12e5,qMin:.7,qMax:.92},good:{maxLongEdge:2560,payloadTargetBytes:16e5,qMin:.7,qMax:.92}};function He(e){let{deviceMemory:t,effectiveType:n,saveData:r,downlinkMbps:i,sourceLongEdge:l}=e,s=r===!0||n==="slow-2g"||n==="2g"||i!=null&&i>0&&i<1,u=t!=null&&t<=2,c=n==="4g"||i!=null&&i>=5,f=t!=null&&t>=6,p;s||u?p="low":c&&f?p="good":p="mid";let b=qe[p],S=l&&l>0?Math.min(b.maxLongEdge,l):b.maxLongEdge;return{tier:p,...b,maxLongEdge:S}}function ke(e){let t={};try{let n=navigator;typeof n.deviceMemory=="number"&&(t.deviceMemory=n.deviceMemory);let r=n.connection;r&&(t.effectiveType=r.effectiveType,t.saveData=r.saveData,t.downlinkMbps=r.downlink)}catch{}return typeof e=="number"&&e>0&&(t.sourceLongEdge=e),He(t)}function Xe(e,t,n){let r=Math.min(1,Math.max(0,(e-.28)/.21999999999999997)),i=(t+n)/2;return Math.max(t,n-r*(n-i))}function Ve(e,t,n){let r=Math.max(e,t),i=r>0?Math.min(1,n/r):1;return{width:Math.max(1,Math.round(e*i)),height:Math.max(1,Math.round(t*i))}}async function Ye(e,t){let n=t.startQ,r=await e(n);for(let i=0;i<4&&!(r.size<=t.budgetBytes||n<=t.qMin);i++)n=Math.max(t.qMin,n-.08),r=await e(n);return{blob:r,quality:n}}async function De(e,t,n,r,i){if(t<=0||n<=0)return null;let{width:l,height:s}=Ve(t,n,r.maxLongEdge),u=document.createElement("canvas");u.width=l,u.height=s;let c=u.getContext("2d");if(!c)return null;c.drawImage(e,0,0,l,s);let f=I=>new Promise((h,w)=>{u.toBlob(d=>d?h(d):w(new Error("canvas toBlob returned null")),"image/jpeg",I)}),p=Xe(i,r.qMin,r.qMax),{blob:b,quality:S}=await Ye(f,{startQ:p,qMin:r.qMin,budgetBytes:r.payloadTargetBytes}).finally(()=>{u.width=0,u.height=0});if(b.size>5242880)throw new Error("encoded document exceeds the 5242880-byte media cap");return{blob:b,quality:S,width:l,height:s}}async function Z(e){let t=ke(Math.max(e.width,e.height)),n=await De(e,e.width,e.height,t,.5);if(n===null)throw new Error("canvas encode unavailable");return{blob:n.blob,width:n.width,height:n.height}}async function mt(e){let t=await createImageBitmap(e);try{return await Z(t)}finally{t.close()}}var ft=250,gt=.6,bt=1800,ht=6e3,yt=2e3,we=.16;function te(e,t){return{layout:e,phase:"framing",captured:{},pending:[],lastCaptureAt:t,lastReportAt:t,manualShutter:!1,restPhase:"framing",readSides:[],needFlip:!1,flipped:!1,flipTimeoutSpent:!1,timeoutCapture:!1,lastShotByTimeout:!1}}var Ce=e=>e==="recto"?"verso":"recto",Re=e=>e.phase==="framing"||e.phase==="locking"||e.phase==="flipCue"||e.phase==="reaskRecto",ne=e=>(e.captured.recto!==void 0?1:0)+(e.captured.verso!==void 0?1:0)+e.pending.length;function ee(e,t){return e.lastCaptureAt>=0&&e.lastReportAt>=0?e:{...e,lastCaptureAt:e.lastCaptureAt<0?t:e.lastCaptureAt,lastReportAt:e.lastReportAt<0?t:e.lastReportAt}}function Qe(e,t,n){if(e.phase==="result")return{...e,lastReportAt:n};let r=!t.present||e.captureArea!==void 0&&t.areaFrac<.6*e.captureArea,{flipped:i,awaySince:l}=e;r&&(l=l??n),l!==void 0&&n-l>=250&&(i=!0),r||(l=void 0);let s=e.flipTimeoutSpent&&!(i&&!e.flipped),u={...e,lastReportAt:n,flipped:i,awaySince:l,flipTimeoutSpent:s,lastArea:t.areaFrac};if(!Re(e))return u;if(e.needFlip&&!i){if(!t.ready)return{...u,phase:e.restPhase,goodSince:void 0};let c=e.lastShot!==void 0&&e.pending.includes(e.lastShot);if(s||c)return{...u,goodSince:void 0,phase:e.restPhase};let f=e.goodSince??n;return n-f>=1800?{...u,goodSince:f,phase:"capturing",flipTimeoutSpent:!0,timeoutCapture:!0}:{...u,goodSince:f,phase:e.restPhase}}return t.ready?{...u,phase:"capturing",goodSince:e.goodSince??n}:{...u,goodSince:void 0,phase:t.locking?"locking":e.restPhase}}function Ke(e,t){if(!Re(e)||e.manualShutter)return e;let n=t-e.lastReportAt>=2e3,r=t-e.lastCaptureAt>=6e3;return n||r?{...e,manualShutter:!0}:e}function je(e,t,n){let r=e.layout==="singlePage",i=r?{recto:t}:e.captured,l=r?[]:[...e.pending,t],s={...e,captured:i,pending:l,lastShot:t,lastCaptureAt:n,lastReportAt:-1,manualShutter:!1,goodSince:void 0,notice:void 0,awaySince:void 0,flipped:!1,lastShotByTimeout:e.timeoutCapture,timeoutCapture:!1,captureArea:e.lastArea};return r||ne({captured:i,pending:l})>=2?{...s,phase:"reading",restPhase:"framing",current:void 0,needFlip:!1}:{...s,phase:"flipCue",restPhase:"flipCue",current:void 0,needFlip:!0}}function xe(e,t,n){return e.pending.includes(t)?{...e,pending:e.pending.filter(r=>r!==t),lastShot:e.lastShot===t?void 0:e.lastShot,phase:e.phase==="capturing"?e.phase:"flipCue",restPhase:"flipCue",current:Ce(n),needFlip:!0,flipTimeoutSpent:!0,goodSince:void 0,manualShutter:!0,notice:"same_face",lastCaptureAt:-1,lastReportAt:-1}:e}function $e(e,t,n){if(!e.pending.includes(t))return e;if(e.captured[n]!==void 0)return xe(e,t,n);let r=e.pending.filter(c=>c!==t),i={...e,pending:r,captured:{...e.captured,[n]:t}};if(ne(i)!==1||e.layout==="singlePage")return i;let l=Ce(n),s=l==="recto"&&e.restPhase==="reaskRecto"?"reaskRecto":"flipCue",u=e.phase==="flipCue"||e.phase==="reaskRecto"||e.phase==="framing";return{...i,restPhase:s,current:l,phase:u?s:e.phase}}function Je(e,t){let n=t.id??e.captured[t.side],r={...e.captured};(t.id===void 0||r[t.side]===t.id)&&delete r[t.side];let i=e.pending.filter(f=>f!==n),l=e.layout==="twoSided"&&ne({captured:r,pending:i})>0,s=e.lastShotByTimeout||n===e.lastShot!==e.flipped,u=l&&!s,c=u?t.side==="recto"?"reaskRecto":"flipCue":"framing";return{...e,captured:r,pending:i,readSides:e.readSides.filter(f=>f!==t.side),lastShot:e.lastShot===n?void 0:e.lastShot,notice:t.issue,goodSince:void 0,manualShutter:!1,phase:c,restPhase:c,current:t.side,needFlip:u,flipped:!1,flipTimeoutSpent:!1,awaySince:void 0,lastCaptureAt:-1,lastReportAt:-1}}function ve(e,t){switch(t.type){case"report":return Qe(ee(e,t.at),t.report,t.at);case"tick":return Ke(ee(e,t.at),t.at);case"captured":return je(ee(e,t.at),t.id,t.at);case"captureFailed":return{...e,phase:e.restPhase,goodSince:void 0,lastCaptureAt:t.at,manualShutter:!0,timeoutCapture:!1};case"classified":return $e(e,t.id,t.side);case"duplicate":return xe(e,t.id,t.side);case"readOk":{let n=e.readSides.includes(t.side)?e.readSides:[...e.readSides,t.side],r=["recto","verso"].filter(l=>e.captured[l]!==void 0),i=e.phase==="reading"&&e.pending.length===0&&r.every(l=>n.includes(l));return{...e,readSides:n,flipTimeoutSpent:!1,phase:i?"result":e.phase}}case"readFailed":return Je(e,t);case"clockRestart":return e.lastCaptureAt<0&&e.lastReportAt<0&&e.awaySince===void 0?e:{...e,awaySince:void 0,lastCaptureAt:-1,lastReportAt:-1};case"retake":return{...te(e.layout,-1),lastCaptureAt:-1,lastReportAt:-1};default:return e}}function Ze(e,t,n=!1){let r=e(t);return r===null?"recto":!n||r.y+r.height/2>=t.height/2?"verso":"recto"}async function et(e,t=!1){let{detectMrzBand:n}=await import("./mrz-band-VYHOTDHY.js");return Ze(n,e,t)}async function re(e,t=480,n,r=n!=null){let i=n??{x:0,y:0,width:e.width,height:e.height},l=Math.max(1,Math.round(i.height/i.width*t)),s=document.createElement("canvas");s.width=t,s.height=l;try{let u=s.getContext("2d");return u===null?"recto":(u.drawImage(e,i.x,i.y,i.width,i.height,0,0,t,l),await et(u.getImageData(0,0,t,l),r))}finally{s.width=0,s.height=0}}async function Mt(e,t=480){try{let n=await createImageBitmap(e),r=Math.max(1,Math.round(n.height/n.width*t)),i=document.createElement("canvas");i.width=t,i.height=r;let l=i.getContext("2d");return l===null?(n.close(),null):(l.drawImage(n,0,0,t,r),n.close(),l.getImageData(0,0,t,r))}catch{return null}}var oe=(e,t,n)=>Math.min(n,Math.max(t,Math.round(e))),Y=e=>Math.round(Math.min(1,Math.max(0,e))*1e4)/1e4;async function Le(e,t,n,r){let i=r.decode??(c=>createImageBitmap(c)),l=async()=>e.stillRead(await i(t),r.region??[0,0,1,1],r.detectorLimit),s;try{s=await l()}catch{try{await new Promise(c=>setTimeout(c,r.retryMs??300)),s=await l()}catch{return null}}let u=s.mrzBox;return u===void 0?null:{engine:r.engine,source:"live_mrz",format:n.format,lineCount:oe(n.lineCount,2,3),checkDigitsValid:!0,stillConfirmed:s.valid&&s.digest===n.digest,band:[Y(u[0]),Y(u[1]),Y(Math.min(u[2],1-u[0])),Y(Math.min(u[3],1-u[1]))],digest:n.digest,framesToValid:oe(n.framesToValid,1,1e3),msToValid:oe(n.msToValid,0,12e4)}}function Dt(e){let t=null;return e?.then(n=>{t=n}),()=>t}var tt=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]),nt=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,7,1,5,0,6,64,11,11]);function _e(e,t=globalThis){let n=t.WebAssembly?.validate;if(typeof n!="function")return{ok:!1,reason:"simd"};try{if(!n.call(t.WebAssembly,tt)||!n.call(t.WebAssembly,nt))return{ok:!1,reason:"simd"}}catch{return{ok:!1,reason:"simd"}}if(typeof t.Worker!="function")return{ok:!1,reason:"worker"};if(typeof t.createImageBitmap!="function")return{ok:!1,reason:"bitmap"};let r=t.navigator?.deviceMemory;return typeof r=="number"&&r<e.minDeviceMemoryGb?{ok:!1,reason:"memory"}:{ok:!0}}function Te(e=globalThis){let t=e.navigator?.connection;return t?.saveData===!0||["slow-2g","2g","3g"].includes(t?.effectiveType??"")}var T=class extends Error{constructor(t){super(t),this.name="OcrEngineError",this.code=t}};function Ee(){let e=t=>(t.close(),Promise.reject(new T("unsupported")));return{ready:Promise.resolve("unsupported"),busy:!1,bandRead:e,stillRead:e,layoutRead:e,dispose:()=>{}}}function Oe(e){let t;try{if(e.createWorker)t=e.createWorker();else if(e.workerUrl!==void 0)t=new Worker(e.workerUrl,{type:"module",name:"sekyro-ocr"});else return Ee()}catch{return Ee()}let n=new Map,r=0,i=!1,l=!1,s=!1;t.addEventListener("message",d=>{let g=d.data,C=n.get(g.id);C&&(n.delete(g.id),C.resolve(g))});let u=()=>{for(let d of n.values())d.reject(new T("error"));n.clear(),f()};t.addEventListener("error",u),t.addEventListener("messageerror",u);function c(d,g=[]){if(i)return Promise.reject(new T("disposed"));let C=++r;return new Promise((B,O)=>{n.set(C,{resolve:B,reject:O});try{t.postMessage({...d,id:C},g)}catch{n.delete(C),O(new T("error"))}})}function f(){if(!i){i=!0;try{t.postMessage({id:++r,kind:"dispose"})}catch{}t.terminate();for(let d of n.values())d.reject(new T("disposed"));n.clear()}}let p=(async()=>{let d=await c({kind:"init",baseUrl:e.baseUrl,salt:e.salt,detectorLimit:e.tuning.detectorLimit,maxDownloadMs:e.tuning.maxDownloadMs});if(d.kind==="failed")return d.reason;if(d.kind!=="ready")return"error";let g=await c({kind:"warmup"});return g.kind!=="ready"?"error":{warmupMs:g.warmupMs,downloadMs:d.downloadMs,cached:d.cached}})().catch(()=>"error"),b,S=new Promise(d=>{b=setTimeout(()=>d("timeout"),e.tuning.loadTimeoutMs)}),I=Promise.race([p,S]).then(d=>(clearTimeout(b),typeof d=="string"?f():s=!0,i&&typeof d!="string"?"error":d));(e.page===void 0?globalThis.addEventListener?globalThis:null:e.page)?.addEventListener("pagehide",f,{once:!0});async function w(d,g,C){if(i)throw g.close(),new T("disposed");if(!s)throw g.close(),new T("not_ready");if(l)throw g.close(),new T("busy");l=!0;let B;try{let O=new Promise((k,A)=>{B=setTimeout(()=>{A(new T("timeout")),f()},e.tuning.readTimeoutMs??1e4)}),P=await Promise.race([c(d,[g]),O]);if(P.kind===C){let{id:k,...A}=P;return A}throw new T(P.kind==="error"?P.code:P.kind==="failed"?P.reason:"error")}finally{clearTimeout(B),l=!1}}return{ready:I,get busy(){return l},bandRead:(d,g=e.tuning.detectorLimit)=>w({kind:"band",bitmap:d,detectorLimit:g},d,"band"),stillRead:(d,g,C=e.tuning.detectorLimit)=>w({kind:"still",bitmap:d,region:g,detectorLimit:C},d,"band"),layoutRead:(d,g)=>w({kind:"layout",bitmap:d,detectorLimit:g},d,"layout"),dispose:f}}var U="sekyro-ocr-1",ae=e=>e!==null&&typeof e=="object"?e:{},v=(e,t,n,r)=>typeof e=="number"&&Number.isFinite(e)&&e>=t&&e<=n?e:r,Pe=(e,t)=>typeof e=="boolean"?e:t,Ae=e=>{let t=typeof e=="string"?/^sekyro-ocr-(\d{1,4})$/.exec(e):null;return t?Number(t[1]):Number.POSITIVE_INFINITY};function Be(e,t={}){let n=ae(e),r=ae(n.liveMrz),i=ae(n.frontLock),l=Ae(t.engine??U),s=t.mode==="off",u=d=>d.enabled===!0?d.arm==="live"?"live":"control":null,c=u(r),f=u(i),p=(d,g)=>!s&&g==="live"&&Ae(d.minEngine??U)<=l,b=Se,S=p(r,c)?{detectorLimit:v(r.detectorLimit,320,1600,b.detectorLimit),bandMaxWidthPx:v(r.bandMaxWidthPx,320,4096,b.bandMaxWidthPx),minBandWidthPx:v(r.minBandWidthPx,0,4096,b.minBandWidthPx),bandTop:v(r.bandTop,0,.95,b.bandTop),minIntervalMs:v(r.minIntervalMs,0,5e3,b.minIntervalMs),stableReads:Math.round(v(r.stableReads,1,10,b.stableReads)),profileReads:Math.round(v(r.profileReads,1,100,b.profileReads)),maxReadMs:v(r.maxReadMs,50,6e4,b.maxReadMs),searchTimeoutMs:v(r.searchTimeoutMs,1e3,12e4,b.searchTimeoutMs),hint:Pe(r.hint,!0),stillConfirm:Pe(r.stillConfirm,!0)}:null,I=ye,h=(d,g,C)=>v(i[d],g,C,I[d]),w=p(i,f)?{minLines:Math.round(h("minLines",1,50)),fillMin:h("fillMin",0,1),fillMax:h("fillMax",0,2),offsetMax:h("offsetMax",0,1),steadyFillDelta:h("steadyFillDelta",0,1),steadyOffsetDelta:h("steadyOffsetDelta",0,1),layoutShiftMax:h("layoutShiftMax",0,1),lineCountDelta:Math.round(h("lineCountDelta",0,50)),lockMs:h("lockMs",0,3e4),steadyMs:h("steadyMs",0,3e4),minFrames:Math.round(h("minFrames",1,100)),minIntervalMs:h("minIntervalMs",0,5e3),maxWidthPx:h("maxWidthPx",160,2048),detectorLimit:h("detectorLimit",320,1600),searchTimeoutMs:h("searchTimeoutMs",1e3,12e4)}:null;return{enabled:S!==null||w!==null,liveMrz:S,textLock:w,liveMrzArm:c,frontLockArm:f,load:{detectorLimit:S?.detectorLimit??w?.detectorLimit??b.detectorLimit,loadTimeoutMs:v(r.loadTimeoutMs,1e3,12e4,2e4),maxDownloadMs:v(r.maxDownloadMs,1e3,12e4,2e4),minDeviceMemoryGb:v(r.minDeviceMemoryGb,0,64,2)},reportSampleRate:v(r.reportSampleRate,0,1,1)}}function Ie(e,t){return e.enabled?!(t.probe??_e)({minDeviceMemoryGb:e.load.minDeviceMemoryGb}).ok||(t.slow??Te)()?{ok:!1,reason:"unsupported"}:{ok:!0,engine:Oe({baseUrl:t.baseUrl,salt:t.salt,tuning:{detectorLimit:e.load.detectorLimit,maxDownloadMs:e.load.maxDownloadMs,loadTimeoutMs:e.load.loadTimeoutMs},...t.workerUrl!==void 0?{workerUrl:t.workerUrl}:{},...t.createWorker!==void 0?{createWorker:t.createWorker}:{},...t.page!==void 0?{page:t.page}:{}})}:{ok:!1,reason:"off"}}function rt(e=typeof navigator<"u"?navigator.userAgent:""){return/SamsungBrowser\//.test(e)?"samsung":/Firefox\/|FxiOS\//.test(e)?"firefox":/Chrome\/|CriOS\/|Chromium\//.test(e)&&!/Edg\/|OPR\//.test(e)?"chrome":/Safari\//.test(e)&&/Version\/|Mobile\//.test(e)&&!/Chrome\/|CriOS\//.test(e)?"safari":"other"}var F=e=>e===void 0||!Number.isFinite(e)?void 0:Math.min(6e5,Math.max(0,Math.round(e))),ie=(e,t,n)=>e===void 0||!Number.isFinite(e)?void 0:Math.min(n,Math.max(t,Math.round(e)));function We(e){let t=e.assist??null,n=e.load!==null&&e.load!==void 0&&typeof e.load=="object"?e.load:null,r=typeof e.load=="string"?e.load:null,i=t!==null?t.outcome:r==="unsupported"||r==="download"||r==="integrity"?r:r==="error"||r==="timeout"?"error":"off",l={kind:"live_mrz",platform:"web",engine:e.engine??U,arm:e.arm,capture:e.capture,outcome:i,reads:ie(t?.reads??0,0,1e4)??0,browser:e.browser??rt()},s=(u,c)=>{c!==void 0&&(l[u]=c)};return s("format",t?.format),s("framesToValid",ie(t?.framesToValid,1,1e4)),s("msToValid",F(t?.msToValid)),s("framesToLock",ie(t?.framesToLock,1,1e4)),s("msToLock",F(t?.msToLock)),s("msToCapture",F(e.msToCapture)),s("readP50Ms",F(t?.readP50Ms)),s("readP90Ms",F(t?.readP90Ms)),s("deviceClass",t?.deviceClass),n!==null&&(s("warmupMs",F(n.warmupMs)),s("downloadMs",F(n.downloadMs)),s("cached",n.cached)),s("stillConfirmed",e.stillConfirmed),s("typeMismatch",e.typeMismatch),l}function se(e,t){return e===void 0?!1:t==="passport"?e!=="TD3":e==="TD3"}var ot=2;async function at(e){let t=await import("./capture-session-doc-XBZGXWOP.js");return new t.CaptureSessionDoc(e)}function it(e){return{topLeft:{x:e.x,y:e.y},topRight:{x:e.x+e.width,y:e.y},bottomRight:{x:e.x+e.width,y:e.y+e.height},bottomLeft:{x:e.x,y:e.y+e.height}}}function st(e,t,n){let r=[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft],i=0;for(let l=0;l<r.length;l+=1){let s=r[l],u=r[(l+1)%r.length];i+=s.x*u.y-u.x*s.y}return t>0&&n>0?Math.abs(i)/2/(t*n):0}function Gt(){import("./capture-session-doc-XBZGXWOP.js").then(e=>e.warmDocDetector()).catch(()=>{})}function qt(e){return ut(e,{}).handle}function ut(e,t){let n=fe(),r=ge({enabled:e.keepScreenAwake!==!1}),i=t.decode??(o=>createImageBitmap(o)),l=t.blurRefuseSharpnessMax??.16,s=t.now??(()=>performance.now()),u=e.documentType==="passport"||e.side==="single",c=te(u?"singlePage":"twoSided",s());if(!u&&(e.side==="recto"||e.side==="verso")){let o=e.side==="recto"?"verso":"recto";c={...c,captured:{[o]:"server"},readSides:[o],current:e.side,phase:"flipCue",restPhase:"flipCue"}}let f="idle",p=null,b=null,S=!0,I=0,h=0,w=!1,d=!1,g="",C=null,B,O=null,P=[],k=t.webOcr!==void 0?Be(t.webOcr.captureDocument,{mode:e.liveMrz?.mode??"auto"}):null,A=null,z=k===null||!k.enabled?"off":null,G=null,q=null,ue=new WeakMap,Q="";if(k!==null&&k.enabled&&t.webOcr!==void 0){let o=t.webOcr,a=Ie(k,{baseUrl:e.liveMrz?.assetBaseUrl??o.baseUrl,salt:o.salt,...e.liveMrz?.workerUrl!==void 0?{workerUrl:e.liveMrz.workerUrl}:{},...o.createWorker!==void 0?{createWorker:o.createWorker}:{}});if(a.ok){A=a.engine;let m=new Me({textLock:k.textLock,liveMrz:k.liveMrz});G=m;let y=a.engine;y.ready.then(L=>{z=L,typeof L!="string"&&S&&m.setEngine(y)})}else z=a.reason}let N=o=>{let a=JSON.stringify(o);a!==Q&&(Q=a,n.emit("mrz",o))},le=(o,a)=>{let m=t.webOcr?.reports;if(m===void 0||k===null||o===void 0)return;let y=o.format==="ID-3"||o.side==="single"?"single":o.side==="verso"?"verso":"recto",L=y!=="recto"?k.liveMrzArm??k.frontLockArm:k.frontLockArm;if(L===null||Math.random()>=k.reportSampleRate)return;let _=o.via==="live_mrz"?q:null,x=()=>{let E=_?.value??null;m([We({arm:L,capture:y,assist:o.ocr??null,load:L==="control"?"off":z,...o.msToCapture!==void 0?{msToCapture:o.msToCapture}:{},...E!==null&&E.stillConfirmed!==void 0?{stillConfirmed:E.stillConfirmed}:{},...a!==void 0?{typeMismatch:se(a.format,e.documentType==="passport"?"passport":"card")}:{}})])};_!==null&&_.value===null?Promise.race([_.promise,new Promise(E=>setTimeout(E,3e3))]).then(x):x()},W=o=>{!S||o===f||(f=o,r.setActive(o==="starting"||o==="scanning"),n.emit("state",o))},Fe=(o,a)=>a===void 0?null:u?"single":o.captured.recto===a?"recto":o.captured.verso===a?"verso":null,ze=o=>({phase:o.phase,captured:u?o.captured.recto!==void 0?["single"]:[]:["recto","verso"].filter(a=>o.captured[a]!==void 0),expected:u?null:o.current??null,notice:o.notice??null,lastShot:Fe(o,o.lastShot),manualShutter:o.manualShutter,torchAvailable:p?.torchAvailable()??!1,torch:d}),ce=()=>{let o=p;o!==null&&o.captureNow().catch(()=>R({type:"captureFailed",at:s()}))};function R(o){if(!S)return;let a=c;c=ve(c,o),c.phase==="capturing"&&a.phase!=="capturing"&&Promise.resolve().then(ce),c.phase==="result"&&a.phase!=="result"&&(W("done"),de());let m=ze(c),y=JSON.stringify(m);y!==g&&(g=y,n.emit("scan",m))}function de(){O!==null&&clearInterval(O),O=null;for(let o of P.splice(0))o();p?.destroy(),p=null,r.setActive(!1)}let me=()=>p?.captureReport?.(),K=!1,pe=(o,a)=>{if(!(o===void 0||t.onFaceReport===void 0))try{t.onFaceReport(o,a)}catch{}},H=o=>{Q="",!(p===null||c.phase==="reading"||c.phase==="result")&&(K=!1,p.rearm(u?"single":c.current??o))},Ne=async(o,a,m,y)=>{if(q=null,y!==void 0&&A!==null&&k?.liveMrz?.hint===!0){let M={promise:Le(A,o,y,{engine:U,detectorLimit:k.liveMrz.detectorLimit}).catch(()=>null),value:null};M.promise.then(D=>{M.value=D}),q=M}y!==void 0&&se(y.format,e.documentType==="passport"?"passport":"card")&&N({state:"mismatch",format:y.format});let L=me();pe(L,"captured"),K=!0,le(L,y);let _=m===void 0?C:m===null?null:{quad:it(m),frameWidth:0,frameHeight:0,inStill:!0},x={decoded:null},E=()=>(x.decoded??(x.decoded=Promise.resolve().then(()=>i(o)).catch(()=>null)),x.decoded);try{await Ue(o,a,_,E,q)}finally{x.decoded!==null&&(await x.decoded)?.close()}},Ue=async(o,a,m,y,L)=>{let _=`shot-${I+=1}`;if(R({type:"captured",id:_,at:s()}),e.haptics!==!1)try{globalThis.navigator?.vibrate?.(30)}catch{}if(!w&&l>0){let M=await(t.measureSharpness!==void 0?t.measureSharpness(o,m):y().then(D=>D===null?-1:he(D,J(m?.quad??null,m?.inStill===!0?D:{width:m?.frameWidth??0,height:m?.frameHeight??0},D)))).catch(()=>-1);if(!S)return;if(Number.isFinite(M)&&M>=0&&M<l){w=!0;let D=u?"recto":c.current??(c.captured.recto===void 0?"recto":"verso");R({type:"readFailed",side:D,id:_,issue:"blurry"}),H(D);return}}w=!1;let x;if(u)x="single";else{let M=c.current,D=await(t.classify!==void 0?t.classify(o):y().then(X=>X===null?M??"recto":m?.inStill===!0?re(X,480,null,!0):re(X,480,J(m?.quad??null,{width:m?.frameWidth??0,height:m?.frameHeight??0},X)))).catch(()=>M??"recto");if(!S)return;if(c.captured[D]!==void 0&&h<ot){h+=1,R({type:"duplicate",id:_,side:D}),H(D==="recto"?"verso":"recto");return}x=c.captured[D]!==void 0&&M!==void 0?M:D,h=0,R({type:"classified",id:_,side:x})}let E=x==="verso"?"verso":"recto";try{let M=t.encode!==void 0?await t.encode(o):await y().then(D=>{if(D===null)throw new Error("the still could not be decoded");return Z(D)});if(!S)return;L!==null&&ue.set(M.blob,L),n.emit("captured",{image:M.blob,side:x,documentType:e.documentType,...e.issuer!==void 0?{issuer:e.issuer}:{},width:M.width,height:M.height,previewDataUrl:a}),t.deferRead!==!0&&R({type:"readOk",side:E})}catch(M){R({type:"readFailed",side:E,id:_,issue:"technical"}),n.emit("error",V("generic",!0,{phase:"keyframes",name:$(M)}))}H(E==="recto"?"verso":"recto")},Ge=o=>{P.push(o.on("statechange",({state:a})=>{a==="preflight"||a==="acquiring"?W("starting"):a==="positioning"?W("scanning"):a==="captured"?W("captured"):a==="error"&&W("error")}),o.on("feedback",({key:a,reticle:m})=>n.emit("feedback",{key:a,reticle:m})),o.on("checks",a=>{n.emit("gate",{progress:a.p,quad:a.quad,frameWidth:a.frameWidth,frameHeight:a.frameHeight,...a.guide!==void 0?{guide:{detected:a.guide.detected,fill:a.guide.fill,offsetX:a.guide.offsetX??0,offsetY:a.guide.offsetY??0}}:{}});let m=a.ocr?.mrz;m!==void 0&&(m.state==="fallback"?N({state:"fallback",reason:m.reason}):m.state==="valid"?N({state:"valid",format:m.format}):m.state==="reading"?N({state:"reading",...m.format?{format:m.format}:{},...m.coach?{coach:m.coach}:{}}):N({state:"searching"}));let y=a.quad===null?0:st(a.quad,a.frameWidth,a.frameHeight);C=a.quad===null?null:{quad:a.quad,frameWidth:a.frameWidth,frameHeight:a.frameHeight},R({type:"report",report:{present:a.quad!==null&&a.plausible||a.guide?.detected===!0,ready:a.ready===!0,locking:a.p>=.5,areaFrac:y},at:s()})}),o.on("error",({kind:a,retryable:m,detail:y})=>n.emit("error",V(a,m,y))),o.on("artifacts",a=>{Ne(a.keyframe,a.previewDataUrl,a.docRegion,a.liveMrz)}))},j=()=>(b??(b=(async()=>{if(S){if(p===null){let o;try{o=await(t.createEngine??at)({...t.engineOptions??{},...B!==void 0?{guide:B}:{},video:e.video,format:be(e.documentType),side:u?"single":e.side??"recto",autoCapture:!1,...G!==null?{ocr:G}:{}})}catch(m){W("error"),n.emit("error",V("models",!0,{phase:"models",name:$(m)}));return}if(!S){o.destroy();return}p=o,Ge(o);let a=t.tickMs??500;a>0&&(O=setInterval(()=>R({type:"tick",at:s()}),a))}R({type:"clockRestart"}),k!==null&&k.liveMrzArm==="live"&&(z==="unsupported"||z==="off")&&N({state:"fallback",reason:z}),await p.start()}})().finally(()=>{b=null})),b);return{handle:{get state(){return f},on:(o,a)=>n.on(o,a),start:j,retry:()=>{if(p===null&&c.phase==="result"){R({type:"retake"}),h=0,w=!1,j();return}if(p!==null&&f!=="error"){R({type:"retake"}),h=0,w=!1,p.rearm(u?"single":void 0);return}j()},setSide:o=>{u||o==="single"||(c.current!==o&&(c={...c,current:o}),R({type:"clockRestart"}),c.phase!=="reading"&&c.phase!=="result"&&p?.rearm(o))},shutter:ce,focusAt:(o,a)=>{p?.focusAt?.(o,a)},setGuide:o=>{B=o,p?.setGuide?.(o)},setTorch:o=>{d=o,p?.setTorch(o),R({type:"tick",at:s()})},destroy:()=>{if(S&&p!==null&&f!=="done"){let o=me();!K&&o!==void 0&&o.ticks>0&&pe(o,"abandoned"),le(o,void 0)}S=!1,de(),G?.setEngine(null),A?.dispose(),A=null,n.clear()}},setFlowState:o=>{(c.phase==="reading"||c.phase==="result")&&W(o==="done"&&c.phase!=="result"?"scanning":o)},settle:(o,a)=>{let m=o==="verso"?"verso":"recto";R(a.ok?{type:"readOk",side:m}:{type:"readFailed",side:m,issue:a.issue}),a.ok||H(m)},takeDeviceRead:o=>ue.get(o.image)?.value??null}}export{mt as a,ft as b,gt as c,bt as d,ht as e,yt as f,we as g,te as h,ve as i,Ze as j,et as k,Mt as l,Le as m,Dt as n,U as o,Be as p,Ie as q,rt as r,We as s,se as t,ot as u,Gt as v,qt as w,ut as x};
1
+ import{d as J,h as he,i as ye,j as Se,l as Me}from"./chunk-EKEHAFEK.js";import{f as be}from"./chunk-BPKDXDDH.js";import{m as V}from"./chunk-NHXLIDQJ.js";import{a as fe,g as ge}from"./chunk-CPK5FYNJ.js";import{k as $}from"./chunk-7KXJEF7P.js";var qe={low:{maxLongEdge:1920,payloadTargetBytes:7e5,qMin:.7,qMax:.92},mid:{maxLongEdge:2240,payloadTargetBytes:12e5,qMin:.7,qMax:.92},good:{maxLongEdge:2560,payloadTargetBytes:16e5,qMin:.7,qMax:.92}};function He(e){let{deviceMemory:t,effectiveType:n,saveData:r,downlinkMbps:i,sourceLongEdge:l}=e,s=r===!0||n==="slow-2g"||n==="2g"||i!=null&&i>0&&i<1,u=t!=null&&t<=2,c=n==="4g"||i!=null&&i>=5,f=t!=null&&t>=6,p;s||u?p="low":c&&f?p="good":p="mid";let b=qe[p],S=l&&l>0?Math.min(b.maxLongEdge,l):b.maxLongEdge;return{tier:p,...b,maxLongEdge:S}}function ke(e){let t={};try{let n=navigator;typeof n.deviceMemory=="number"&&(t.deviceMemory=n.deviceMemory);let r=n.connection;r&&(t.effectiveType=r.effectiveType,t.saveData=r.saveData,t.downlinkMbps=r.downlink)}catch{}return typeof e=="number"&&e>0&&(t.sourceLongEdge=e),He(t)}function Xe(e,t,n){let r=Math.min(1,Math.max(0,(e-.28)/.21999999999999997)),i=(t+n)/2;return Math.max(t,n-r*(n-i))}function Ve(e,t,n){let r=Math.max(e,t),i=r>0?Math.min(1,n/r):1;return{width:Math.max(1,Math.round(e*i)),height:Math.max(1,Math.round(t*i))}}async function Ye(e,t){let n=t.startQ,r=await e(n);for(let i=0;i<4&&!(r.size<=t.budgetBytes||n<=t.qMin);i++)n=Math.max(t.qMin,n-.08),r=await e(n);return{blob:r,quality:n}}async function De(e,t,n,r,i){if(t<=0||n<=0)return null;let{width:l,height:s}=Ve(t,n,r.maxLongEdge),u=document.createElement("canvas");u.width=l,u.height=s;let c=u.getContext("2d");if(!c)return null;c.drawImage(e,0,0,l,s);let f=I=>new Promise((h,w)=>{u.toBlob(d=>d?h(d):w(new Error("canvas toBlob returned null")),"image/jpeg",I)}),p=Xe(i,r.qMin,r.qMax),{blob:b,quality:S}=await Ye(f,{startQ:p,qMin:r.qMin,budgetBytes:r.payloadTargetBytes}).finally(()=>{u.width=0,u.height=0});if(b.size>5242880)throw new Error("encoded document exceeds the 5242880-byte media cap");return{blob:b,quality:S,width:l,height:s}}async function Z(e){let t=ke(Math.max(e.width,e.height)),n=await De(e,e.width,e.height,t,.5);if(n===null)throw new Error("canvas encode unavailable");return{blob:n.blob,width:n.width,height:n.height}}async function mt(e){let t=await createImageBitmap(e);try{return await Z(t)}finally{t.close()}}var ft=250,gt=.6,bt=1800,ht=6e3,yt=2e3,we=.16;function te(e,t){return{layout:e,phase:"framing",captured:{},pending:[],lastCaptureAt:t,lastReportAt:t,manualShutter:!1,restPhase:"framing",readSides:[],needFlip:!1,flipped:!1,flipTimeoutSpent:!1,timeoutCapture:!1,lastShotByTimeout:!1}}var Ce=e=>e==="recto"?"verso":"recto",Re=e=>e.phase==="framing"||e.phase==="locking"||e.phase==="flipCue"||e.phase==="reaskRecto",ne=e=>(e.captured.recto!==void 0?1:0)+(e.captured.verso!==void 0?1:0)+e.pending.length;function ee(e,t){return e.lastCaptureAt>=0&&e.lastReportAt>=0?e:{...e,lastCaptureAt:e.lastCaptureAt<0?t:e.lastCaptureAt,lastReportAt:e.lastReportAt<0?t:e.lastReportAt}}function Qe(e,t,n){if(e.phase==="result")return{...e,lastReportAt:n};let r=!t.present||e.captureArea!==void 0&&t.areaFrac<.6*e.captureArea,{flipped:i,awaySince:l}=e;r&&(l=l??n),l!==void 0&&n-l>=250&&(i=!0),r||(l=void 0);let s=e.flipTimeoutSpent&&!(i&&!e.flipped),u={...e,lastReportAt:n,flipped:i,awaySince:l,flipTimeoutSpent:s,lastArea:t.areaFrac};if(!Re(e))return u;if(e.needFlip&&!i){if(!t.ready)return{...u,phase:e.restPhase,goodSince:void 0};let c=e.lastShot!==void 0&&e.pending.includes(e.lastShot);if(s||c)return{...u,goodSince:void 0,phase:e.restPhase};let f=e.goodSince??n;return n-f>=1800?{...u,goodSince:f,phase:"capturing",flipTimeoutSpent:!0,timeoutCapture:!0}:{...u,goodSince:f,phase:e.restPhase}}return t.ready?{...u,phase:"capturing",goodSince:e.goodSince??n}:{...u,goodSince:void 0,phase:t.locking?"locking":e.restPhase}}function Ke(e,t){if(!Re(e)||e.manualShutter)return e;let n=t-e.lastReportAt>=2e3,r=t-e.lastCaptureAt>=6e3;return n||r?{...e,manualShutter:!0}:e}function je(e,t,n){let r=e.layout==="singlePage",i=r?{recto:t}:e.captured,l=r?[]:[...e.pending,t],s={...e,captured:i,pending:l,lastShot:t,lastCaptureAt:n,lastReportAt:-1,manualShutter:!1,goodSince:void 0,notice:void 0,awaySince:void 0,flipped:!1,lastShotByTimeout:e.timeoutCapture,timeoutCapture:!1,captureArea:e.lastArea};return r||ne({captured:i,pending:l})>=2?{...s,phase:"reading",restPhase:"framing",current:void 0,needFlip:!1}:{...s,phase:"flipCue",restPhase:"flipCue",current:void 0,needFlip:!0}}function xe(e,t,n){return e.pending.includes(t)?{...e,pending:e.pending.filter(r=>r!==t),lastShot:e.lastShot===t?void 0:e.lastShot,phase:e.phase==="capturing"?e.phase:"flipCue",restPhase:"flipCue",current:Ce(n),needFlip:!0,flipTimeoutSpent:!0,goodSince:void 0,manualShutter:!0,notice:"same_face",lastCaptureAt:-1,lastReportAt:-1}:e}function $e(e,t,n){if(!e.pending.includes(t))return e;if(e.captured[n]!==void 0)return xe(e,t,n);let r=e.pending.filter(c=>c!==t),i={...e,pending:r,captured:{...e.captured,[n]:t}};if(ne(i)!==1||e.layout==="singlePage")return i;let l=Ce(n),s=l==="recto"&&e.restPhase==="reaskRecto"?"reaskRecto":"flipCue",u=e.phase==="flipCue"||e.phase==="reaskRecto"||e.phase==="framing";return{...i,restPhase:s,current:l,phase:u?s:e.phase}}function Je(e,t){let n=t.id??e.captured[t.side],r={...e.captured};(t.id===void 0||r[t.side]===t.id)&&delete r[t.side];let i=e.pending.filter(f=>f!==n),l=e.layout==="twoSided"&&ne({captured:r,pending:i})>0,s=e.lastShotByTimeout||n===e.lastShot!==e.flipped,u=l&&!s,c=u?t.side==="recto"?"reaskRecto":"flipCue":"framing";return{...e,captured:r,pending:i,readSides:e.readSides.filter(f=>f!==t.side),lastShot:e.lastShot===n?void 0:e.lastShot,notice:t.issue,goodSince:void 0,manualShutter:!1,phase:c,restPhase:c,current:t.side,needFlip:u,flipped:!1,flipTimeoutSpent:!1,awaySince:void 0,lastCaptureAt:-1,lastReportAt:-1}}function ve(e,t){switch(t.type){case"report":return Qe(ee(e,t.at),t.report,t.at);case"tick":return Ke(ee(e,t.at),t.at);case"captured":return je(ee(e,t.at),t.id,t.at);case"captureFailed":return{...e,phase:e.restPhase,goodSince:void 0,lastCaptureAt:t.at,manualShutter:!0,timeoutCapture:!1};case"classified":return $e(e,t.id,t.side);case"duplicate":return xe(e,t.id,t.side);case"readOk":{let n=e.readSides.includes(t.side)?e.readSides:[...e.readSides,t.side],r=["recto","verso"].filter(l=>e.captured[l]!==void 0),i=e.phase==="reading"&&e.pending.length===0&&r.every(l=>n.includes(l));return{...e,readSides:n,flipTimeoutSpent:!1,phase:i?"result":e.phase}}case"readFailed":return Je(e,t);case"clockRestart":return e.lastCaptureAt<0&&e.lastReportAt<0&&e.awaySince===void 0?e:{...e,awaySince:void 0,lastCaptureAt:-1,lastReportAt:-1};case"retake":return{...te(e.layout,-1),lastCaptureAt:-1,lastReportAt:-1};default:return e}}function Ze(e,t,n=!1){let r=e(t);return r===null?"recto":!n||r.y+r.height/2>=t.height/2?"verso":"recto"}async function et(e,t=!1){let{detectMrzBand:n}=await import("./mrz-band-DCXFWDBD.js");return Ze(n,e,t)}async function re(e,t=480,n,r=n!=null){let i=n??{x:0,y:0,width:e.width,height:e.height},l=Math.max(1,Math.round(i.height/i.width*t)),s=document.createElement("canvas");s.width=t,s.height=l;try{let u=s.getContext("2d");return u===null?"recto":(u.drawImage(e,i.x,i.y,i.width,i.height,0,0,t,l),await et(u.getImageData(0,0,t,l),r))}finally{s.width=0,s.height=0}}async function Mt(e,t=480){try{let n=await createImageBitmap(e),r=Math.max(1,Math.round(n.height/n.width*t)),i=document.createElement("canvas");i.width=t,i.height=r;let l=i.getContext("2d");return l===null?(n.close(),null):(l.drawImage(n,0,0,t,r),n.close(),l.getImageData(0,0,t,r))}catch{return null}}var oe=(e,t,n)=>Math.min(n,Math.max(t,Math.round(e))),Y=e=>Math.round(Math.min(1,Math.max(0,e))*1e4)/1e4;async function Le(e,t,n,r){let i=r.decode??(c=>createImageBitmap(c)),l=async()=>e.stillRead(await i(t),r.region??[0,0,1,1],r.detectorLimit),s;try{s=await l()}catch{try{await new Promise(c=>setTimeout(c,r.retryMs??300)),s=await l()}catch{return null}}let u=s.mrzBox;return u===void 0?null:{engine:r.engine,source:"live_mrz",format:n.format,lineCount:oe(n.lineCount,2,3),checkDigitsValid:!0,stillConfirmed:s.valid&&s.digest===n.digest,band:[Y(u[0]),Y(u[1]),Y(Math.min(u[2],1-u[0])),Y(Math.min(u[3],1-u[1]))],digest:n.digest,framesToValid:oe(n.framesToValid,1,1e3),msToValid:oe(n.msToValid,0,12e4)}}function Dt(e){let t=null;return e?.then(n=>{t=n}),()=>t}var tt=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]),nt=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,7,1,5,0,6,64,11,11]);function _e(e,t=globalThis){let n=t.WebAssembly?.validate;if(typeof n!="function")return{ok:!1,reason:"simd"};try{if(!n.call(t.WebAssembly,tt)||!n.call(t.WebAssembly,nt))return{ok:!1,reason:"simd"}}catch{return{ok:!1,reason:"simd"}}if(typeof t.Worker!="function")return{ok:!1,reason:"worker"};if(typeof t.createImageBitmap!="function")return{ok:!1,reason:"bitmap"};let r=t.navigator?.deviceMemory;return typeof r=="number"&&r<e.minDeviceMemoryGb?{ok:!1,reason:"memory"}:{ok:!0}}function Te(e=globalThis){let t=e.navigator?.connection;return t?.saveData===!0||["slow-2g","2g","3g"].includes(t?.effectiveType??"")}var T=class extends Error{constructor(t){super(t),this.name="OcrEngineError",this.code=t}};function Ee(){let e=t=>(t.close(),Promise.reject(new T("unsupported")));return{ready:Promise.resolve("unsupported"),busy:!1,bandRead:e,stillRead:e,layoutRead:e,dispose:()=>{}}}function Oe(e){let t;try{if(e.createWorker)t=e.createWorker();else if(e.workerUrl!==void 0)t=new Worker(e.workerUrl,{type:"module",name:"sekyro-ocr"});else return Ee()}catch{return Ee()}let n=new Map,r=0,i=!1,l=!1,s=!1;t.addEventListener("message",d=>{let g=d.data,C=n.get(g.id);C&&(n.delete(g.id),C.resolve(g))});let u=()=>{for(let d of n.values())d.reject(new T("error"));n.clear(),f()};t.addEventListener("error",u),t.addEventListener("messageerror",u);function c(d,g=[]){if(i)return Promise.reject(new T("disposed"));let C=++r;return new Promise((B,O)=>{n.set(C,{resolve:B,reject:O});try{t.postMessage({...d,id:C},g)}catch{n.delete(C),O(new T("error"))}})}function f(){if(!i){i=!0;try{t.postMessage({id:++r,kind:"dispose"})}catch{}t.terminate();for(let d of n.values())d.reject(new T("disposed"));n.clear()}}let p=(async()=>{let d=await c({kind:"init",baseUrl:e.baseUrl,salt:e.salt,detectorLimit:e.tuning.detectorLimit,maxDownloadMs:e.tuning.maxDownloadMs});if(d.kind==="failed")return d.reason;if(d.kind!=="ready")return"error";let g=await c({kind:"warmup"});return g.kind!=="ready"?"error":{warmupMs:g.warmupMs,downloadMs:d.downloadMs,cached:d.cached}})().catch(()=>"error"),b,S=new Promise(d=>{b=setTimeout(()=>d("timeout"),e.tuning.loadTimeoutMs)}),I=Promise.race([p,S]).then(d=>(clearTimeout(b),typeof d=="string"?f():s=!0,i&&typeof d!="string"?"error":d));(e.page===void 0?globalThis.addEventListener?globalThis:null:e.page)?.addEventListener("pagehide",f,{once:!0});async function w(d,g,C){if(i)throw g.close(),new T("disposed");if(!s)throw g.close(),new T("not_ready");if(l)throw g.close(),new T("busy");l=!0;let B;try{let O=new Promise((k,A)=>{B=setTimeout(()=>{A(new T("timeout")),f()},e.tuning.readTimeoutMs??1e4)}),P=await Promise.race([c(d,[g]),O]);if(P.kind===C){let{id:k,...A}=P;return A}throw new T(P.kind==="error"?P.code:P.kind==="failed"?P.reason:"error")}finally{clearTimeout(B),l=!1}}return{ready:I,get busy(){return l},bandRead:(d,g=e.tuning.detectorLimit)=>w({kind:"band",bitmap:d,detectorLimit:g},d,"band"),stillRead:(d,g,C=e.tuning.detectorLimit)=>w({kind:"still",bitmap:d,region:g,detectorLimit:C},d,"band"),layoutRead:(d,g)=>w({kind:"layout",bitmap:d,detectorLimit:g},d,"layout"),dispose:f}}var U="sekyro-ocr-1",ae=e=>e!==null&&typeof e=="object"?e:{},v=(e,t,n,r)=>typeof e=="number"&&Number.isFinite(e)&&e>=t&&e<=n?e:r,Pe=(e,t)=>typeof e=="boolean"?e:t,Ae=e=>{let t=typeof e=="string"?/^sekyro-ocr-(\d{1,4})$/.exec(e):null;return t?Number(t[1]):Number.POSITIVE_INFINITY};function Be(e,t={}){let n=ae(e),r=ae(n.liveMrz),i=ae(n.frontLock),l=Ae(t.engine??U),s=t.mode==="off",u=d=>d.enabled===!0?d.arm==="live"?"live":"control":null,c=u(r),f=u(i),p=(d,g)=>!s&&g==="live"&&Ae(d.minEngine??U)<=l,b=Se,S=p(r,c)?{detectorLimit:v(r.detectorLimit,320,1600,b.detectorLimit),bandMaxWidthPx:v(r.bandMaxWidthPx,320,4096,b.bandMaxWidthPx),minBandWidthPx:v(r.minBandWidthPx,0,4096,b.minBandWidthPx),bandTop:v(r.bandTop,0,.95,b.bandTop),minIntervalMs:v(r.minIntervalMs,0,5e3,b.minIntervalMs),stableReads:Math.round(v(r.stableReads,1,10,b.stableReads)),profileReads:Math.round(v(r.profileReads,1,100,b.profileReads)),maxReadMs:v(r.maxReadMs,50,6e4,b.maxReadMs),searchTimeoutMs:v(r.searchTimeoutMs,1e3,12e4,b.searchTimeoutMs),hint:Pe(r.hint,!0),stillConfirm:Pe(r.stillConfirm,!0)}:null,I=ye,h=(d,g,C)=>v(i[d],g,C,I[d]),w=p(i,f)?{minLines:Math.round(h("minLines",1,50)),fillMin:h("fillMin",0,1),fillMax:h("fillMax",0,2),offsetMax:h("offsetMax",0,1),steadyFillDelta:h("steadyFillDelta",0,1),steadyOffsetDelta:h("steadyOffsetDelta",0,1),layoutShiftMax:h("layoutShiftMax",0,1),lineCountDelta:Math.round(h("lineCountDelta",0,50)),lockMs:h("lockMs",0,3e4),steadyMs:h("steadyMs",0,3e4),minFrames:Math.round(h("minFrames",1,100)),minIntervalMs:h("minIntervalMs",0,5e3),maxWidthPx:h("maxWidthPx",160,2048),detectorLimit:h("detectorLimit",320,1600),searchTimeoutMs:h("searchTimeoutMs",1e3,12e4)}:null;return{enabled:S!==null||w!==null,liveMrz:S,textLock:w,liveMrzArm:c,frontLockArm:f,load:{detectorLimit:S?.detectorLimit??w?.detectorLimit??b.detectorLimit,loadTimeoutMs:v(r.loadTimeoutMs,1e3,12e4,2e4),maxDownloadMs:v(r.maxDownloadMs,1e3,12e4,2e4),minDeviceMemoryGb:v(r.minDeviceMemoryGb,0,64,2)},reportSampleRate:v(r.reportSampleRate,0,1,1)}}function Ie(e,t){return e.enabled?!(t.probe??_e)({minDeviceMemoryGb:e.load.minDeviceMemoryGb}).ok||(t.slow??Te)()?{ok:!1,reason:"unsupported"}:{ok:!0,engine:Oe({baseUrl:t.baseUrl,salt:t.salt,tuning:{detectorLimit:e.load.detectorLimit,maxDownloadMs:e.load.maxDownloadMs,loadTimeoutMs:e.load.loadTimeoutMs},...t.workerUrl!==void 0?{workerUrl:t.workerUrl}:{},...t.createWorker!==void 0?{createWorker:t.createWorker}:{},...t.page!==void 0?{page:t.page}:{}})}:{ok:!1,reason:"off"}}function rt(e=typeof navigator<"u"?navigator.userAgent:""){return/SamsungBrowser\//.test(e)?"samsung":/Firefox\/|FxiOS\//.test(e)?"firefox":/Chrome\/|CriOS\/|Chromium\//.test(e)&&!/Edg\/|OPR\//.test(e)?"chrome":/Safari\//.test(e)&&/Version\/|Mobile\//.test(e)&&!/Chrome\/|CriOS\//.test(e)?"safari":"other"}var F=e=>e===void 0||!Number.isFinite(e)?void 0:Math.min(6e5,Math.max(0,Math.round(e))),ie=(e,t,n)=>e===void 0||!Number.isFinite(e)?void 0:Math.min(n,Math.max(t,Math.round(e)));function We(e){let t=e.assist??null,n=e.load!==null&&e.load!==void 0&&typeof e.load=="object"?e.load:null,r=typeof e.load=="string"?e.load:null,i=t!==null?t.outcome:r==="unsupported"||r==="download"||r==="integrity"?r:r==="error"||r==="timeout"?"error":"off",l={kind:"live_mrz",platform:"web",engine:e.engine??U,arm:e.arm,capture:e.capture,outcome:i,reads:ie(t?.reads??0,0,1e4)??0,browser:e.browser??rt()},s=(u,c)=>{c!==void 0&&(l[u]=c)};return s("format",t?.format),s("framesToValid",ie(t?.framesToValid,1,1e4)),s("msToValid",F(t?.msToValid)),s("framesToLock",ie(t?.framesToLock,1,1e4)),s("msToLock",F(t?.msToLock)),s("msToCapture",F(e.msToCapture)),s("readP50Ms",F(t?.readP50Ms)),s("readP90Ms",F(t?.readP90Ms)),s("deviceClass",t?.deviceClass),n!==null&&(s("warmupMs",F(n.warmupMs)),s("downloadMs",F(n.downloadMs)),s("cached",n.cached)),s("stillConfirmed",e.stillConfirmed),s("typeMismatch",e.typeMismatch),l}function se(e,t){return e===void 0?!1:t==="passport"?e!=="TD3":e==="TD3"}var ot=2;async function at(e){let t=await import("./capture-session-doc-VSUEDAEN.js");return new t.CaptureSessionDoc(e)}function it(e){return{topLeft:{x:e.x,y:e.y},topRight:{x:e.x+e.width,y:e.y},bottomRight:{x:e.x+e.width,y:e.y+e.height},bottomLeft:{x:e.x,y:e.y+e.height}}}function st(e,t,n){let r=[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft],i=0;for(let l=0;l<r.length;l+=1){let s=r[l],u=r[(l+1)%r.length];i+=s.x*u.y-u.x*s.y}return t>0&&n>0?Math.abs(i)/2/(t*n):0}function Gt(){import("./capture-session-doc-VSUEDAEN.js").then(e=>e.warmDocDetector()).catch(()=>{})}function qt(e){return ut(e,{}).handle}function ut(e,t){let n=fe(),r=ge({enabled:e.keepScreenAwake!==!1}),i=t.decode??(o=>createImageBitmap(o)),l=t.blurRefuseSharpnessMax??.16,s=t.now??(()=>performance.now()),u=e.documentType==="passport"||e.side==="single",c=te(u?"singlePage":"twoSided",s());if(!u&&(e.side==="recto"||e.side==="verso")){let o=e.side==="recto"?"verso":"recto";c={...c,captured:{[o]:"server"},readSides:[o],current:e.side,phase:"flipCue",restPhase:"flipCue"}}let f="idle",p=null,b=null,S=!0,I=0,h=0,w=!1,d=!1,g="",C=null,B,O=null,P=[],k=t.webOcr!==void 0?Be(t.webOcr.captureDocument,{mode:e.liveMrz?.mode??"auto"}):null,A=null,z=k===null||!k.enabled?"off":null,G=null,q=null,ue=new WeakMap,Q="";if(k!==null&&k.enabled&&t.webOcr!==void 0){let o=t.webOcr,a=Ie(k,{baseUrl:e.liveMrz?.assetBaseUrl??o.baseUrl,salt:o.salt,...e.liveMrz?.workerUrl!==void 0?{workerUrl:e.liveMrz.workerUrl}:{},...o.createWorker!==void 0?{createWorker:o.createWorker}:{}});if(a.ok){A=a.engine;let m=new Me({textLock:k.textLock,liveMrz:k.liveMrz});G=m;let y=a.engine;y.ready.then(L=>{z=L,typeof L!="string"&&S&&m.setEngine(y)})}else z=a.reason}let N=o=>{let a=JSON.stringify(o);a!==Q&&(Q=a,n.emit("mrz",o))},le=(o,a)=>{let m=t.webOcr?.reports;if(m===void 0||k===null||o===void 0)return;let y=o.format==="ID-3"||o.side==="single"?"single":o.side==="verso"?"verso":"recto",L=y!=="recto"?k.liveMrzArm??k.frontLockArm:k.frontLockArm;if(L===null||Math.random()>=k.reportSampleRate)return;let _=o.via==="live_mrz"?q:null,x=()=>{let E=_?.value??null;m([We({arm:L,capture:y,assist:o.ocr??null,load:L==="control"?"off":z,...o.msToCapture!==void 0?{msToCapture:o.msToCapture}:{},...E!==null&&E.stillConfirmed!==void 0?{stillConfirmed:E.stillConfirmed}:{},...a!==void 0?{typeMismatch:se(a.format,e.documentType==="passport"?"passport":"card")}:{}})])};_!==null&&_.value===null?Promise.race([_.promise,new Promise(E=>setTimeout(E,3e3))]).then(x):x()},W=o=>{!S||o===f||(f=o,r.setActive(o==="starting"||o==="scanning"),n.emit("state",o))},Fe=(o,a)=>a===void 0?null:u?"single":o.captured.recto===a?"recto":o.captured.verso===a?"verso":null,ze=o=>({phase:o.phase,captured:u?o.captured.recto!==void 0?["single"]:[]:["recto","verso"].filter(a=>o.captured[a]!==void 0),expected:u?null:o.current??null,notice:o.notice??null,lastShot:Fe(o,o.lastShot),manualShutter:o.manualShutter,torchAvailable:p?.torchAvailable()??!1,torch:d}),ce=()=>{let o=p;o!==null&&o.captureNow().catch(()=>R({type:"captureFailed",at:s()}))};function R(o){if(!S)return;let a=c;c=ve(c,o),c.phase==="capturing"&&a.phase!=="capturing"&&Promise.resolve().then(ce),c.phase==="result"&&a.phase!=="result"&&(W("done"),de());let m=ze(c),y=JSON.stringify(m);y!==g&&(g=y,n.emit("scan",m))}function de(){O!==null&&clearInterval(O),O=null;for(let o of P.splice(0))o();p?.destroy(),p=null,r.setActive(!1)}let me=()=>p?.captureReport?.(),K=!1,pe=(o,a)=>{if(!(o===void 0||t.onFaceReport===void 0))try{t.onFaceReport(o,a)}catch{}},H=o=>{Q="",!(p===null||c.phase==="reading"||c.phase==="result")&&(K=!1,p.rearm(u?"single":c.current??o))},Ne=async(o,a,m,y)=>{if(q=null,y!==void 0&&A!==null&&k?.liveMrz?.hint===!0){let M={promise:Le(A,o,y,{engine:U,detectorLimit:k.liveMrz.detectorLimit}).catch(()=>null),value:null};M.promise.then(D=>{M.value=D}),q=M}y!==void 0&&se(y.format,e.documentType==="passport"?"passport":"card")&&N({state:"mismatch",format:y.format});let L=me();pe(L,"captured"),K=!0,le(L,y);let _=m===void 0?C:m===null?null:{quad:it(m),frameWidth:0,frameHeight:0,inStill:!0},x={decoded:null},E=()=>(x.decoded??(x.decoded=Promise.resolve().then(()=>i(o)).catch(()=>null)),x.decoded);try{await Ue(o,a,_,E,q)}finally{x.decoded!==null&&(await x.decoded)?.close()}},Ue=async(o,a,m,y,L)=>{let _=`shot-${I+=1}`;if(R({type:"captured",id:_,at:s()}),e.haptics!==!1)try{globalThis.navigator?.vibrate?.(30)}catch{}if(!w&&l>0){let M=await(t.measureSharpness!==void 0?t.measureSharpness(o,m):y().then(D=>D===null?-1:he(D,J(m?.quad??null,m?.inStill===!0?D:{width:m?.frameWidth??0,height:m?.frameHeight??0},D)))).catch(()=>-1);if(!S)return;if(Number.isFinite(M)&&M>=0&&M<l){w=!0;let D=u?"recto":c.current??(c.captured.recto===void 0?"recto":"verso");R({type:"readFailed",side:D,id:_,issue:"blurry"}),H(D);return}}w=!1;let x;if(u)x="single";else{let M=c.current,D=await(t.classify!==void 0?t.classify(o):y().then(X=>X===null?M??"recto":m?.inStill===!0?re(X,480,null,!0):re(X,480,J(m?.quad??null,{width:m?.frameWidth??0,height:m?.frameHeight??0},X)))).catch(()=>M??"recto");if(!S)return;if(c.captured[D]!==void 0&&h<ot){h+=1,R({type:"duplicate",id:_,side:D}),H(D==="recto"?"verso":"recto");return}x=c.captured[D]!==void 0&&M!==void 0?M:D,h=0,R({type:"classified",id:_,side:x})}let E=x==="verso"?"verso":"recto";try{let M=t.encode!==void 0?await t.encode(o):await y().then(D=>{if(D===null)throw new Error("the still could not be decoded");return Z(D)});if(!S)return;L!==null&&ue.set(M.blob,L),n.emit("captured",{image:M.blob,side:x,documentType:e.documentType,...e.issuer!==void 0?{issuer:e.issuer}:{},width:M.width,height:M.height,previewDataUrl:a}),t.deferRead!==!0&&R({type:"readOk",side:E})}catch(M){R({type:"readFailed",side:E,id:_,issue:"technical"}),n.emit("error",V("generic",!0,{phase:"keyframes",name:$(M)}))}H(E==="recto"?"verso":"recto")},Ge=o=>{P.push(o.on("statechange",({state:a})=>{a==="preflight"||a==="acquiring"?W("starting"):a==="positioning"?W("scanning"):a==="captured"?W("captured"):a==="error"&&W("error")}),o.on("feedback",({key:a,reticle:m})=>n.emit("feedback",{key:a,reticle:m})),o.on("checks",a=>{n.emit("gate",{progress:a.p,quad:a.quad,frameWidth:a.frameWidth,frameHeight:a.frameHeight,...a.guide!==void 0?{guide:{detected:a.guide.detected,fill:a.guide.fill,offsetX:a.guide.offsetX??0,offsetY:a.guide.offsetY??0}}:{}});let m=a.ocr?.mrz;m!==void 0&&(m.state==="fallback"?N({state:"fallback",reason:m.reason}):m.state==="valid"?N({state:"valid",format:m.format}):m.state==="reading"?N({state:"reading",...m.format?{format:m.format}:{},...m.coach?{coach:m.coach}:{}}):N({state:"searching"}));let y=a.quad===null?0:st(a.quad,a.frameWidth,a.frameHeight);C=a.quad===null?null:{quad:a.quad,frameWidth:a.frameWidth,frameHeight:a.frameHeight},R({type:"report",report:{present:a.quad!==null&&a.plausible||a.guide?.detected===!0,ready:a.ready===!0,locking:a.p>=.5,areaFrac:y},at:s()})}),o.on("error",({kind:a,retryable:m,detail:y})=>n.emit("error",V(a,m,y))),o.on("artifacts",a=>{Ne(a.keyframe,a.previewDataUrl,a.docRegion,a.liveMrz)}))},j=()=>(b??(b=(async()=>{if(S){if(p===null){let o;try{o=await(t.createEngine??at)({...t.engineOptions??{},...B!==void 0?{guide:B}:{},video:e.video,format:be(e.documentType),side:u?"single":e.side??"recto",autoCapture:!1,...G!==null?{ocr:G}:{}})}catch(m){W("error"),n.emit("error",V("models",!0,{phase:"models",name:$(m)}));return}if(!S){o.destroy();return}p=o,Ge(o);let a=t.tickMs??500;a>0&&(O=setInterval(()=>R({type:"tick",at:s()}),a))}R({type:"clockRestart"}),k!==null&&k.liveMrzArm==="live"&&(z==="unsupported"||z==="off")&&N({state:"fallback",reason:z}),await p.start()}})().finally(()=>{b=null})),b);return{handle:{get state(){return f},on:(o,a)=>n.on(o,a),start:j,retry:()=>{if(p===null&&c.phase==="result"){R({type:"retake"}),h=0,w=!1,j();return}if(p!==null&&f!=="error"){R({type:"retake"}),h=0,w=!1,p.rearm(u?"single":void 0);return}j()},setSide:o=>{u||o==="single"||(c.current!==o&&(c={...c,current:o}),R({type:"clockRestart"}),c.phase!=="reading"&&c.phase!=="result"&&p?.rearm(o))},shutter:ce,focusAt:(o,a)=>{p?.focusAt?.(o,a)},setGuide:o=>{B=o,p?.setGuide?.(o)},setTorch:o=>{d=o,p?.setTorch(o),R({type:"tick",at:s()})},destroy:()=>{if(S&&p!==null&&f!=="done"){let o=me();!K&&o!==void 0&&o.ticks>0&&pe(o,"abandoned"),le(o,void 0)}S=!1,de(),G?.setEngine(null),A?.dispose(),A=null,n.clear()}},setFlowState:o=>{(c.phase==="reading"||c.phase==="result")&&W(o==="done"&&c.phase!=="result"?"scanning":o)},settle:(o,a)=>{let m=o==="verso"?"verso":"recto";R(a.ok?{type:"readOk",side:m}:{type:"readFailed",side:m,issue:a.issue}),a.ok||H(m)},takeDeviceRead:o=>ue.get(o.image)?.value??null}}export{mt as a,ft as b,gt as c,bt as d,ht as e,yt as f,we as g,te as h,ve as i,Ze as j,et as k,Mt as l,Le as m,Dt as n,U as o,Be as p,Ie as q,rt as r,We as s,se as t,ot as u,Gt as v,qt as w,ut as x};
@@ -0,0 +1 @@
1
+ import{d as Jt,h as qt,k as te}from"./chunk-EKEHAFEK.js";import{b as $t}from"./chunk-NYRFUVAR.js";import{a as et,b as ee,c as ie,e as mt,f as oe}from"./chunk-AXJ2VWIK.js";import{b as Yt,c as Zt}from"./chunk-BPKDXDDH.js";import{b as Vt,c as Xt}from"./chunk-V5P5P3HY.js";import{k as Qt,m as Bt,n as Wt,o as Ht,p as Kt,r as ut}from"./chunk-7KXJEF7P.js";import{b as ht,c as dt,d as j,e as jt}from"./chunk-FK2DJADA.js";import{d as Ut}from"./chunk-XK4CCTLL.js";var it=Object.freeze({sensing:{key:"sensing",reticle:"searching",minDurationMs:900},too_far:{key:"too_far",reticle:"coaching",minDurationMs:1400},too_close:{key:"too_close",reticle:"coaching",minDurationMs:1400},edge_clipped:{key:"edge_clipped",reticle:"coaching",minDurationMs:1400},wrong_shape:{key:"wrong_shape",reticle:"coaching",minDurationMs:1400},tilted:{key:"tilted",reticle:"coaching",minDurationMs:1400},too_dark:{key:"too_dark",reticle:"coaching",minDurationMs:1400},too_bright:{key:"too_bright",reticle:"coaching",minDurationMs:1400},blurry:{key:"blurry",reticle:"coaching",minDurationMs:1400},focus_far:{key:"focus_far",reticle:"coaching",minDurationMs:1600},glare:{key:"glare",reticle:"coaching",minDurationMs:1400},hold_still:{key:"hold_still",reticle:"locking",minDurationMs:900},processing:{key:"processing",reticle:"processing",minDurationMs:800},side_captured:{key:"side_captured",reticle:"flip",minDurationMs:2600},captured:{key:"captured",reticle:"done",minDurationMs:800}});function ne(i){return i.framing==="no_document"?"sensing":i.framing==="too_far"?"too_far":i.framing==="too_close"?"too_close":i.framing==="edge_clipped"?"edge_clipped":i.framing==="wrong_shape"?"wrong_shape":i.framing==="tilted"?"tilted":i.lighting==="too_dark"?"too_dark":i.lighting==="too_bright"?"too_bright":i.glare==="glare"?"glare":i.blur==="blurry"?"blurry":"hold_still"}var ot=class{constructor(t=2600,e=.35){this.windowMs=t;this.decayPerSecond=e;this.votes=[];this.current=it.sensing;this.currentSinceMs=null}reset(){this.votes=[],this.current=it.sensing,this.currentSinceMs=null}force(t,e){return this.votes=[],this.current=it[t],this.currentSinceMs=e,this.current}tick(t,e){if(this.currentSinceMs===null&&(this.currentSinceMs=e),this.votes.push({key:t,atMs:e}),this.votes=this.votes.filter(r=>e-r.atMs<=this.windowMs),e-this.currentSinceMs<this.current.minDurationMs)return this.current;let o=new Map;for(let r of this.votes){let c=(e-r.atMs)/1e3,a=this.decayPerSecond**c;o.set(r.key,(o.get(r.key)??0)+a)}let n=this.current.key,s=-1;for(let[r,c]of o)c>s&&(s=c,n=r);return n!==this.current.key&&(this.current=it[n],this.currentSinceMs=e),this.current}};var Xe=Object.freeze({MAX_AREA_FRAC:.92,TILT_MAX_SIDE_RATIO:1.3,GLARE_MAX_SPECULAR_FRAC:.025});function re(i){let{data:t,width:e,height:o}=i,n=e*o;if(n===0)return 0;let s=0;for(let r=0;r<n;r++){let c=r*4;.299*(t[c]??0)+.587*(t[c+1]??0)+.114*(t[c+2]??0)>=252&&s++}return s/n}function je(i){let t=(a,l)=>Math.hypot(l.x-a.x,l.y-a.y),e=t(i.topLeft,i.topRight),o=t(i.bottomLeft,i.bottomRight),n=t(i.topLeft,i.bottomLeft),s=t(i.topRight,i.bottomRight),r=Math.max(e,o)/Math.max(1e-6,Math.min(e,o)),c=Math.max(n,s)/Math.max(1e-6,Math.min(n,s));return Math.max(r,c)}function ae(i){let t={...ee,...i.thresholds},e=Xe,{quad:o,frameWidth:n,frameHeight:s,measures:r}=i,c=i.format==="ID-3",a="ok";if(o===null)a="no_document";else if(c){let m=mt(o),h=n>0?m.width/n:0,f=m.height>0?m.width/m.height:0;h<t.ID3_BAND_MIN_WIDTH_FRAC?a="too_far":se(o,n,s,t.EDGE_CLIP_MARGIN_PX)?a="edge_clipped":(f<t.ID3_BAND_ASPECT_MIN||f>t.ID3_BAND_ASPECT_MAX)&&(a="wrong_shape")}else{let m=ie(o,n,s),h=mt(o),f=Math.max(h.width,h.height)/Math.max(1e-6,Math.min(h.width,h.height));m<t.MIN_AREA_FRAC?a="too_far":m>e.MAX_AREA_FRAC?a="too_close":se(o,n,s,t.EDGE_CLIP_MARGIN_PX)?a="edge_clipped":Zt(i.format,f)?je(o)>e.TILT_MAX_SIDE_RATIO&&(a="tilted"):a="wrong_shape"}let l=r.exposure>=t.GUIDE_EXPOSURE?"ok":r.meanLuma<(ht[0]+ht[1])/2?"too_dark":"too_bright",u=r.sharpness>=t.GUIDE_SHARPNESS?"ok":"blurry",d=r.specularFraction>=e.GLARE_MAX_SPECULAR_FRAC?"glare":"ok";return{framing:a,lighting:l,blur:u,glare:d,acceptable:a==="ok"&&l==="ok"&&u==="ok"&&d==="ok"}}function se(i,t,e,o){return[i.topLeft,i.topRight,i.bottomRight,i.bottomLeft].some(s=>s.x<=o||s.y<=o||s.x>=t-o||s.y>=e-o)}var le=Object.freeze({width:1920,height:1080}),Ye=Object.freeze({width:3840,height:2160}),ce=4096,Ze=2560,ue=640,nt=.15,Y=Object.freeze({side:.2,above:.9,below:.3});function E(i){let t=[i.topLeft.x,i.topRight.x,i.bottomRight.x,i.bottomLeft.x],e=[i.topLeft.y,i.topRight.y,i.bottomRight.y,i.bottomLeft.y],o=Math.min(...t),n=Math.min(...e);return{x:o,y:n,width:Math.max(...t)-o,height:Math.max(...e)-n}}function he(i,t){let e=Math.max(0,Math.floor(i.x)),o=Math.max(0,Math.floor(i.y)),n=Math.min(t.width,Math.ceil(i.x+i.width)),s=Math.min(t.height,Math.ceil(i.y+i.height));return n-e<16||s-o<16?null:{x:e,y:o,width:n-e,height:s-o}}function Je(i,t,e){if(i===null||t.width<=0||t.height<=0)return null;let o=E(i);if(o.width<=0||o.height<=0)return null;let n=e==="ID-3"?{x:o.x-o.width*Y.side,y:o.y-o.width*Y.above,width:o.width*(1+2*Y.side),height:o.height+o.width*(Y.above+Y.below)}:{x:o.x-o.width*nt,y:o.y-o.height*nt,width:o.width*(1+2*nt),height:o.height*(1+2*nt)};return he(n,t)}function ft(i,t,e){let o=Math.max(i,t);return o>0?Math.min(1,e/o):1}function pt(i,t,e,o,n=Ze){let s=t.width>0?e.width/t.width:1,r=t.height>0?e.height/t.height:1,c=i===null?null:{topLeft:{x:i.topLeft.x*s,y:i.topLeft.y*r},topRight:{x:i.topRight.x*s,y:i.topRight.y*r},bottomRight:{x:i.bottomRight.x*s,y:i.bottomRight.y*r},bottomLeft:{x:i.bottomLeft.x*s,y:i.bottomLeft.y*r}},a=Je(c,e,o)??{x:0,y:0,width:e.width,height:e.height},l=ft(a.width,a.height,n),u=Math.max(1,Math.round(a.width*l)),d=Math.max(1,Math.round(a.height*l)),m=null;if(c!==null){let h=E(c);m=he({x:(h.x-a.x)*l,y:(h.y-a.y)*l,width:h.width*l,height:h.height*l},{width:u,height:d})}return{crop:a,width:u,height:d,docRegion:m}}function de(i,t,e,o=Ye){if(e==="LOW")return null;let n=i?.width?.max,s=i?.height?.max;if(typeof n!="number"||typeof s!="number"||n<=0||s<=0)return null;let r=Math.max(n,s),c=Math.min(n,s),a=Math.min(r,Math.max(o.width,o.height)),l=Math.min(c,Math.min(o.width,o.height));return a<=Math.max(t.width,t.height)?null:{width:{ideal:a},height:{ideal:l}}}function me(i){let t={},e=i?.imageWidth,o=i?.imageHeight;if(typeof e?.max=="number"&&e.max>0){let n=typeof o?.max=="number"&&o.max>0?e.max/o.max:1.3333333333333333,s=n>=1?ce:ce*n,r=Math.min(e.max,Math.floor(s)),c=typeof e.step=="number"&&e.step>0?e.step:1,a=typeof e.min=="number"?e.min:0;r=Math.max(a,a+Math.floor((r-a)/c)*c),t.imageWidth=r}return i?.fillLightMode?.includes("off")===!0&&(t.fillLightMode="off"),t}function fe(i,t){if(i.width<=0||i.height<=0||t.width<=0||t.height<=0)return!1;let e=i.width>i.height,o=t.width>t.height;return e!==o&&i.width!==i.height&&t.width!==t.height?!1:Math.max(i.width,i.height)>=1.2*Math.max(t.width,t.height)}function pe(i,t,e,o){if(e===null)return!1;let n=E(i),s=E(e);if(t.width<=0||o.width<=0)return!1;let r=n.width/t.width,c=s.width/o.width;return c>0&&r>=.6*c&&r<=1.25*c}var ge=3500,qe=.92;function ye(){let i=globalThis.ImageCapture;return typeof i=="function"?i:null}function $e(i){return/AppleWebKit\//.test(i)&&!/(Chrome|Chromium|Edg|OPR)\//.test(i)}function Me(i,t=typeof navigator>"u"?"":navigator.userAgent){return ye()!==null&&!$e(t)&&i!=null&&i.kind==="video"&&i.readyState==="live"}function be(i,t){return new Promise((e,o)=>{let n=setTimeout(()=>o(new Error("takePhoto timed out")),t);i.then(s=>{clearTimeout(n),e(s)},s=>{clearTimeout(n),o(s)})})}function gt(i,t){let e=document.createElement("canvas");return e.width=i,e.height=t,e}function ti(i,t){return new Promise((e,o)=>{i.toBlob(n=>n?e(n):o(new Error("toBlob failed")),"image/jpeg",t)})}async function ke(i,t,e,o,n){let s=gt(e,o),r=gt(1,1);try{let c=s.getContext("2d");if(c===null)throw new Error("2d context unavailable");c.imageSmoothingQuality="high",c.drawImage(i,t.x,t.y,t.width,t.height,0,0,e,o);let a=await ti(s,qe),l=n===null?null:Jt({topLeft:{x:n.x,y:n.y},topRight:{x:n.x+n.width,y:n.y},bottomRight:{x:n.x+n.width,y:n.y+n.height},bottomLeft:{x:n.x,y:n.y+n.height}},{width:e,height:o},{width:e,height:o}),u=qt(s,l),d=ft(e,o,ue);return r.width=Math.max(1,Math.round(e*d)),r.height=Math.max(1,Math.round(o*d)),r.getContext("2d")?.drawImage(s,0,0,r.width,r.height),{blob:a,previewDataUrl:r.toDataURL("image/jpeg",.85),sharpness:u}}finally{s.width=0,s.height=0,r.width=0,r.height=0}}function ei(i,t){let e=Math.min(1,t/i.width),o=gt(Math.max(1,Math.round(i.width*e)),Math.max(1,Math.round(i.height*e)));try{let n=o.getContext("2d",{willReadFrequently:!0});return n===null?null:(n.imageSmoothingQuality="high",n.drawImage(i,0,0,o.width,o.height),n.getImageData(0,0,o.width,o.height))}finally{o.width=0,o.height=0}}async function De(i,t,e,o){let n={width:Math.max(1,i.videoWidth),height:Math.max(1,i.videoHeight)},s=pt(t,e,n,o);return{...await ke(i,s.crop,s.width,s.height,s.docRegion),docRegion:s.docRegion,source:"video",width:s.width,height:s.height}}async function xe(i,t,e,o,n){let s=ye();if(s===null)return null;let r=null;try{let c=new s(n.track),a=await be(c.getPhotoCapabilities?.()??Promise.resolve({}),ge).catch(()=>({})),l=await be(c.takePhoto(me(a)),ge);r=await createImageBitmap(l);let u={width:i.videoWidth,height:i.videoHeight};if(!fe(r,u))return null;let d=ei(r,n.detectWidth),m=null;d!==null&&t!==null&&(m=await n.detect(d).catch(()=>null));let h=d??{width:r.width,height:r.height};m!==null&&!pe(m,h,t,e)&&(m=null);let f=pt(m,h,r,o);return{...await ke(r,f.crop,f.width,f.height,f.docRegion),docRegion:f.docRegion,source:"photo",width:f.width,height:f.height}}catch{return null}finally{r?.close()}}var st=Object.freeze({width:3840,height:2160,lensSelection:!0,continuousFocus:!0,refocusBeforePhotoMs:350,zoomMax:2,zoomNoFocusInfo:1.5,zoomMinSourcePx:2160,fillDistanceM:Object.freeze({id1:.11,id3:.15}),focusMarginFrac:.2,stillSharpnessMin:.16,stillRefusalsMax:2,focusFarFillFrac:.45,noDocFarHintMs:1500,zoomFallbackMs:8e3}),S=(i,t,e)=>typeof i=="number"&&Number.isFinite(i)&&i>=t&&i<=e?i:void 0;function Si(i){let t=st,e=i!==null&&typeof i=="object"?i:{},o=e.fillDistanceM!==null&&typeof e.fillDistanceM=="object"?e.fillDistanceM:{},n=(s,r)=>typeof s=="boolean"?s:r;return{width:S(e.width,640,7680)??t.width,height:S(e.height,480,4320)??t.height,lensSelection:n(e.lensSelection,t.lensSelection),continuousFocus:n(e.continuousFocus,t.continuousFocus),refocusBeforePhotoMs:S(e.refocusBeforePhotoMs,0,2e3)??t.refocusBeforePhotoMs,zoomMax:S(e.zoomMax,1,5)??t.zoomMax,zoomNoFocusInfo:S(e.zoomNoFocusInfo,1,5)??t.zoomNoFocusInfo,zoomMinSourcePx:S(e.zoomMinSourcePx,0,8e3)??t.zoomMinSourcePx,fillDistanceM:{id1:S(o.id1,.03,1)??t.fillDistanceM.id1,id3:S(o.id3,.03,1)??t.fillDistanceM.id3},focusMarginFrac:S(e.focusMarginFrac,0,2)??t.focusMarginFrac,stillSharpnessMin:S(e.stillSharpnessMin,0,10)??t.stillSharpnessMin,stillRefusalsMax:S(e.stillRefusalsMax,0,10)??t.stillRefusalsMax,focusFarFillFrac:S(e.focusFarFillFrac,0,1)??t.focusFarFillFrac,noDocFarHintMs:S(e.noDocFarHintMs,0,6e4)??t.noDocFarHintMs,zoomFallbackMs:S(e.zoomFallbackMs,0,12e4)??t.zoomFallbackMs}}var bt="sekyro.doc.camera";function ii(){try{let i=globalThis.localStorage?.getItem(bt);return typeof i=="string"&&i!==""?i:null}catch{return null}}function we(i){try{i===null?globalThis.localStorage?.removeItem(bt):globalThis.localStorage?.setItem(bt,i)}catch{}}var rt=(i,t)=>Array.isArray(i?.focusMode)&&i.focusMode.includes(t);function Mt(i,t,e){if(!rt(i,"single-shot"))return null;let o=n=>Math.min(1,Math.max(0,Number.isFinite(n)?n:.5));return{focusMode:"single-shot",pointsOfInterest:[{x:o(t),y:o(e)}]}}function _i(i,t,e,o){if(!Number.isFinite(i)||!Number.isFinite(t)||e.width<=0||e.height<=0||o.width<=0||o.height<=0)return null;let n=Math.max(e.width/o.width,e.height/o.height),s=o.width*n,r=o.height*n,c=(i-e.left+(s-e.width)/2)/s,a=(t-e.top+(r-e.height)/2)/r;return{x:Math.min(1,Math.max(0,c)),y:Math.min(1,Math.max(0,a))}}function Se(i,t,e,o=st){let n=i?.zoom?.min,s=i?.zoom?.max;if(typeof s!="number"||s<=1)return 1;let r=e==="ID-3"?o.fillDistanceM.id3:o.fillDistanceM.id1,c=i?.focusDistance?.min,a;if(typeof c=="number"&&c>0&&c<1){if(a=c*(1+o.focusMarginFrac)/r,a<=1.05)return 1}else{if(Math.min(t.width,t.height)<o.zoomMinSourcePx)return 1;a=o.zoomNoFocusInfo}let l=Math.min(a,o.zoomMax,s);typeof n=="number"&&(l=Math.max(l,n));let u=i?.zoom?.step;return typeof u=="number"&&u>0&&(l=Math.round(l/u)*u),l>1.01?Number(l.toFixed(2)):1}function yt(i){try{return i.getVideoTracks?.()[0]}catch{return}}function ve(i){if(i!==null)for(let t of i.getTracks())t.stop()}function oi(i){try{let t=yt(i)?.getCapabilities?.();return!Array.isArray(t?.focusMode)||t.focusMode.includes("continuous")}catch{return!0}}async function Te(i){let t=s=>({audio:!1,video:{...s,width:{ideal:i.base.width},height:{ideal:i.base.height}}}),e=s=>i.getUserMedia(t({deviceId:{exact:s}})),o=()=>i.getUserMedia(t({facingMode:{ideal:"environment"}}));if(i.lensSelection){let s=ii();if(s!==null)try{return{stream:await e(s),lens:"stored"}}catch{we(null)}}let n=await o();if(!i.lensSelection||i.enumerateDevices===void 0)return{stream:n,lens:"default"};try{let s=ut(await i.enumerateDevices()).slice(0,3);if(s.length===0)return{stream:n,lens:"default"};let r=null;for(let c of s){let a=n!==null?yt(n)?.getSettings?.().deviceId:void 0;if(n===null||a!==c){ve(n),n=null;try{n=await e(c)}catch{continue}}if(r??(r=c),oi(n))return we(c),{stream:n,lens:"selected"}}if(n!==null&&r!==null&&yt(n)?.getSettings?.().deviceId===r)return{stream:n,lens:"selected"};if(ve(n),n=null,r!==null)try{return{stream:await e(r),lens:"selected"}}catch{}return{stream:await o(),lens:"default"}}catch{return{stream:n??await o(),lens:"default"}}}var Z=Object.freeze({brightness:0,glare:0,cardGlare:0,sharpness:0,fill:0,shape:0,content:0,offsetX:0,offsetY:0,edgeConfidence:0,box:null}),L=i=>Math.min(1,Math.max(0,i));function Re(i,t,e,o=.06){let n=Math.max(i.width/e,i.height),s=n*e,r=(i.width-s)/2,c=(i.height-n)/2,a=L((t.x-t.width*o-r)/s),l=L((t.y-t.height*o-c)/n),u=L((t.x+t.width*(1+o)-r)/s),d=L((t.y+t.height*(1+o)-c)/n);return{x:a,y:l,width:u-a,height:d-l}}function Fe(i,t,e={}){let o=e.edgePeakFrac??0,{width:n,height:s,data:r}=i;if(n<=0||s<=0)return Z;let c=L(t.x),a=L(t.y),l={x:c,y:a,width:Math.max(0,L(t.x+t.width)-c),height:Math.max(0,L(t.y+t.height)-a)};if(l.width<=0||l.height<=0)return Z;let u=l.x*n,d=l.y*s,m=(l.x+l.width)*n,h=(l.y+l.height)*s,f=(m-u)*.15,g=(h-d)*.15,y=(p,b,R)=>Math.min(R,Math.max(b,p)),D=y(Math.floor(u-f),0,n-1),w=y(Math.floor(d-g),0,s-1),O=y(Math.ceil(m+f),D+1,n),v=y(Math.ceil(h+g),w+1,s),x=Math.max(1,Math.ceil(Math.max(O-D,v-w)/320)),M=Math.floor((O-D+x-1)/x),T=Math.floor((v-w+x-1)/x);if(M<3||T<3)return Z;let k=new Int32Array(M*T);for(let p=0;p<T;p++){let b=w+p*x;for(let R=0;R<M;R++){let F=(b*n+D+R*x)*4;k[p*M+R]=(r[F]??0)*77+(r[F+1]??0)*150+(r[F+2]??0)*29>>8}}let C=(p,b)=>(p-b-.5)/x,_=C(u,D),A=C(m,D),B=C(d,w),U=C(h,w),Dt=(m-u)/x,xt=(h-d)/x,wt=y(Math.ceil(_),0,M-1),Ie=y(Math.floor(A),wt,M-1),vt=y(Math.ceil(B),0,T-1),Ge=y(Math.floor(U),vt,T-1),St=0,Tt=0,W=0,_t=0,Rt=0,H=0;for(let p=vt;p<=Ge;p++)for(let b=wt;b<=Ie;b++){let R=k[p*M+b];if(St+=R,R>=248&&Tt++,W++,b>=1&&b<M-1&&p>=1&&p<T-1){let F=k[p*M+b-1]+k[p*M+b+1]+k[(p-1)*M+b]+k[(p+1)*M+b]-4*R;_t+=F,Rt+=F*F,H++}}let ze=W>0?St/W:0,Ft=W>0?Tt/W:0,Ct=H>0?_t/H:0,Ne=H>0?Math.max(0,Rt/H-Ct*Ct):0,K=new Float64Array(M),V=new Float64Array(T);for(let p=0;p<T;p++)for(let b=1;b<M-1;b++)K[b]=K[b]+Math.abs(k[p*M+b+1]-k[p*M+b-1]);for(let p=1;p<T-1;p++)for(let b=0;b<M;b++)V[p]=V[p]+Math.abs(k[(p+1)*M+b]-k[(p-1)*M+b]);let P=at(K,!0,_,o),I=at(K,!1,A,o),G=at(V,!0,B,o),z=at(V,!1,U,o),At=(I.position-P.position)/Dt,Et=(z.position-G.position)/xt,Qe=Et>0?At/Et:0,Be=((P.position+I.position)/2-(_+A)/2)/Dt,Ue=((G.position+z.position)/2-(B+U)/2)/xt,Lt=_e(K),Ot=_e(V),We=Lt<=0||Ot<=0?0:Math.min(Math.min(P.value,I.value)/Lt,Math.min(G.value,z.value)/Ot),$=(p,b)=>b+(p+.5)*x,Pt=Ft,It=0;{let p=(I.position-P.position)*.06,b=(z.position-G.position)*.06,R=y(Math.ceil(P.position+p),0,M-1),F=y(Math.floor(I.position-p),0,M-1),He=y(Math.ceil(G.position+b),0,T-1),Gt=y(Math.floor(z.position-b),0,T-1),zt=0,tt=0,Nt=0;for(let N=He;N<=Gt;N++)for(let Q=R;Q<=F;Q++){tt++;let X=k[N*M+Q];X>=248&&zt++;let Ke=Q+2<=F?k[N*M+Q+2]:X,Ve=N+2<=Gt?k[(N+2)*M+Q]:X;(Math.abs(Ke-X)>=24||Math.abs(Ve-X)>=24)&&Nt++}tt>=16&&(Pt=zt/tt,It=Nt/tt)}return{brightness:ze,glare:Ft,cardGlare:Pt,sharpness:Ne,fill:At,shape:Qe,content:It,offsetX:Be,offsetY:Ue,edgeConfidence:We,box:{left:$(P.position,D),right:$(I.position,D),top:$(G.position,w),bottom:$(z.position,w)}}}function at(i,t,e,o){let n=i.length,s=Math.max(1,Math.floor(n*.45)),r=t?1:Math.max(1,n-1-s),c=t?Math.min(n-2,s):n-2,a=r;for(let h=r;h<=c;h++)i[h]>i[a]&&(a=h);if(o>0&&o<1){let h=i[a]*o,f=a,g=Math.abs(a-e);for(let y=r;y<=c;y++){let D=i[y];if(D<h||D<(i[y-1]??0)||D<(i[y+1]??0))continue;let w=Math.abs(y-e);w<g&&(f=y,g=w)}a=f}let l=a>0?i[a-1]:0,u=i[a],d=a<n-1?i[a+1]:0,m=l+u+d;return{position:m>0?a+(d-l)/m:a,value:u}}function _e(i){if(i.length<3)return 0;let t=0;for(let e=1;e<i.length-1;e++)t+=i[e];return t/(i.length-2)}function Ce(i){let t=i.box;return t===null||t.right-t.left<4||t.bottom-t.top<4?null:{topLeft:{x:t.left,y:t.top},topRight:{x:t.right,y:t.top},bottomRight:{x:t.right,y:t.bottom},bottomLeft:{x:t.left,y:t.bottom}}}var J=Object.freeze({fillMin:.82,fillMax:1.06,offsetMax:.06,glareMax:.025,sharpnessMin:180,edgeConfidenceMin:1.6,darkBrightness:70,lockMs:450,steadyMs:900,steadyFillMin:.45,steadyFillMax:1.3,steadyFillDelta:.06,steadyOffsetDelta:.04,steadyRefMs:100,edgePeakFrac:.4,shapeTolerance:.2,contentMin:.1});function Ai(i){let t=i!==null&&typeof i=="object"?i:{},e={...J};for(let o of Object.keys(J)){let n=t[o];typeof n=="number"&&Number.isFinite(n)&&n>=0&&n<=1e6&&(e[o]=n)}return e}var ct=class{constructor(t=J){this.t=t;this.goodSince=null;this.steadySince=null;this.last=null}reset(){this.goodSince=null,this.steadySince=null,this.last=null}tick(t,e){let o=this.t,n=o.shapeTolerance<=0||Math.abs(t.shape-1)<=o.shapeTolerance,s=t.edgeConfidence>=o.edgeConfidenceMin&&n&&t.content>=o.contentMin,r=t.fill>=o.fillMin&&t.fill<=o.fillMax,c=Math.abs(t.offsetX)<=o.offsetMax&&Math.abs(t.offsetY)<=o.offsetMax,a=t.cardGlare<=o.glareMax,l=t.sharpness>=o.sharpnessMin,u=this.last;this.last={fill:t.fill,offsetX:t.offsetX,offsetY:t.offsetY,at:e};let d=u!==null&&o.steadyRefMs>0?Math.min(3,Math.max(1,(e-u.at)/o.steadyRefMs)):1,m=s&&a&&l&&t.fill>=o.steadyFillMin&&t.fill<=o.steadyFillMax&&u!==null&&Math.abs(t.fill-u.fill)<=o.steadyFillDelta*d&&Math.abs(t.offsetX-u.offsetX)<=o.steadyOffsetDelta*d&&Math.abs(t.offsetY-u.offsetY)<=o.steadyOffsetDelta*d,h=s&&r&&c&&a&&l,f;if(s?a?t.fill<o.fillMin?f="too_small":t.fill>o.fillMax?f="too_big":l?c?f="locking":f="off_center":f="blurry":f="glare":f="no_card",h){if(m&&(this.steadySince??(this.steadySince=e)),this.goodSince??(this.goodSince=e),e-this.goodSince>=o.lockMs)return{detected:s,ready:!0,via:"good",blocker:"locking"};let g=this.steadySince!==null&&e-this.steadySince>=o.steadyMs;return{detected:s,ready:g,via:g?"steady":null,blocker:"locking"}}if(this.goodSince=null,m){this.steadySince??(this.steadySince=e);let g=e-this.steadySince>=o.steadyMs;return{detected:s,ready:g,via:g?"steady":null,blocker:g?"locking":"steadying"}}return this.steadySince=null,{detected:s,ready:!1,via:null,blocker:f}}};var q=null;async function ni(i){return q===null&&(q=(await import("./detector-scanic-F3Y5X3DF.js")).detectQuad),q(i)}async function si(i){let t=$t(i);return t===null?null:{topLeft:{x:t.x,y:t.y},topRight:{x:t.x+t.width,y:t.y},bottomRight:{x:t.x+t.width,y:t.y+t.height},bottomLeft:{x:t.x,y:t.y+t.height}}}function ji(){q===null&&import("./detector-scanic-F3Y5X3DF.js").then(i=>{q=i.detectQuad}).catch(()=>{})}var Ae=4e3,ri=2,Ee=3,ai=Object.freeze({LOW:3,MID:5,HIGH:6}),kt=Object.freeze({manualShutterMs:6e3,detectedNoLockMs:1950});function Yi(i){let t=i!==null&&typeof i=="object"?i:{},e=(o,n,s)=>typeof o=="number"&&Number.isFinite(o)&&o>=n&&o<=s?o:void 0;return{manualShutterMs:e(t.manualShutterMs,1e3,6e4)??kt.manualShutterMs,detectedNoLockMs:e(t.steadyMs,300,3e4)!==void 0?t.steadyMs+(e(t.lockMs,0,1e4)??450):kt.detectedNoLockMs}}var Le=class i{constructor(t){this.torchOn=!1;this.stillRefusals=0;this.zoom=1;this.positioningSince=null;this.detectedSince=null;this.lastSeenAt=null;this.lastGuideQuad=null;this.lastOcrReady=null;this.shutterOffered=!1;this.stats=i.freshStats();this.handlers=new Map;this.stream=null;this.timer=null;this.state="idle";this.lastGuidance=null;this.attempt=0;this.capturing=!1;this.feedback=new ot;this.lastFeedbackKey=null;this.lastQuad=null;this.lastDetect=null;this.frameWatch=null;this.reopened=!1;this.lit=!1;this.blackTicks=0;this.offEnded=null;this.opts=t,this.gate=new oe(t.format??"ID-1",t.thresholds);let e=t.deviceClass??Xt(Vt());this.deviceClass=e,this.camera=t.camera??st,this.shutterTuning=t.shutter??kt,this.guideTuning=t.guideLock??J,this.guideLock=new ct(this.guideTuning),this.cadenceMs=1e3/ai[e]}on(t,e){let o=this.handlers.get(t);return o||(o=new Set,this.handlers.set(t,o)),o.add(e),()=>o?.delete(e)}emit(t,e){for(let o of[...this.handlers.get(t)??[]])o(e)}async start(){let t=this.state==="error"?this.resumePlayback():null,e=++this.attempt;if(this.clearFrameWatch(),this.gate.reset(),this.resetSide(),this.feedback.reset(),this.lastFeedbackKey=null,this.lastGuidance=null,this.capturing=!1,this.lit=!1,this.blackTicks=0,t!==null&&await t&&e===this.attempt){this.setState("positioning"),this.scheduleTick(e),this.watchFrames(e);return}if(e===this.attempt){this.releaseStream(),Ht(),this.setState("preflight");try{let o=this.opts.getUserMedia??(r=>navigator.mediaDevices.getUserMedia(r));this.setState("acquiring");let n=this.opts.enumerateDevices??(this.opts.getUserMedia===void 0&&typeof navigator<"u"&&navigator.mediaDevices?.enumerateDevices?()=>navigator.mediaDevices.enumerateDevices():void 0),s=await Te({getUserMedia:o,...n!==void 0?{enumerateDevices:n}:{},lensSelection:this.camera.lensSelection,base:le});if(e!==this.attempt){for(let r of s.stream.getTracks())r.stop();return}if(this.stream=s.stream,Ut(this.stream),Wt(this.stream),this.watchEnded(e),this.opts.upgradeResolution!==!1&&await this.upgradeResolution(),e!==this.attempt||(await this.applyFocusAndZoom(),e!==this.attempt)||(this.opts.video.srcObject=this.stream,await this.opts.video.play().catch(()=>{}),e!==this.attempt))return;this.setState("positioning"),this.scheduleTick(e),this.watchFrames(e)}catch(o){if(e!==this.attempt)return;let n=Bt(o),s=Qt(o);this.setState("error"),this.emit("error",{kind:n,retryable:!0,detail:s===void 0?{phase:"acquiring"}:{phase:"acquiring",name:s}})}}}resumePlayback(){let t=this.opts.video,e=this.videoTrack();if(this.stream===null||e===null||e.readyState!=="live"||t.srcObject!==this.stream)return null;try{return Promise.resolve(t.play()).then(()=>this.framesNow(),()=>!1)}catch{return null}}framesNow(){let t=this.opts.video;return this.opts.hasFrames!==void 0?this.opts.hasFrames(t):!t.paused&&t.readyState>=2&&t.videoWidth>0}watchFrames(t){let e=this.opts.firstFrameMs??Ae;e<=0||(this.clearFrameWatch(),this.frameWatch=setTimeout(()=>{if(this.frameWatch=null,!(t!==this.attempt||this.state!=="positioning")){if(this.framesNow()&&this.blackTicks<Ee){this.reopened=!1;return}this.cameraDead(t)}},e))}clearFrameWatch(){this.frameWatch!==null&&clearTimeout(this.frameWatch),this.frameWatch=null}watchEnded(t){this.offEnded?.(),this.offEnded=null;let e=this.videoTrack();if(e===null||typeof e.addEventListener!="function")return;let o=()=>{t===this.attempt&&(this.state==="positioning"||this.state==="acquiring")&&this.cameraDead(t)};e.addEventListener("ended",o),this.offEnded=()=>e.removeEventListener?.("ended",o)}cameraDead(t){if(t!==this.attempt)return;let e=this.videoTrack(),o=e!==null&&e.readyState==="live"&&!e.muted&&this.opts.video.paused&&!this.framesNow();if(!o&&!this.reopened){this.reopened=!0,this.start();return}this.attempt+=1,this.timer!==null&&(this.opts.clearTimer??clearTimeout)(this.timer),this.timer=null,this.clearFrameWatch(),o||this.releaseStream(),this.reopened=!1,this.setState("error"),this.emit("error",{kind:"generic",retryable:!0,detail:{phase:"acquiring"}})}releaseStream(){if(this.offEnded?.(),this.offEnded=null,this.stream)for(let t of this.stream.getTracks())t.stop();this.stream=null,this.opts.video.srcObject!==null&&this.opts.video.srcObject!==void 0&&(this.opts.video.srcObject=null)}rearm(t){t!==void 0&&(this.opts.side=t),this.gate.reset(),this.resetSide(),this.feedback.reset(),this.lastFeedbackKey=null,this.lastGuidance=null,this.capturing=!1,this.stillRefusals=0,this.state==="captured"&&(this.setState("positioning"),this.scheduleTick(this.attempt))}async captureNow(){if(this.state!=="positioning"||this.capturing)return;let t=this.opts.video,e=this.lastDetect?.width??Math.max(1,t.videoWidth),o=this.lastDetect?.height??Math.max(1,t.videoHeight),n=this.lastQuad??this.lastGuideQuad??{topLeft:{x:0,y:0},topRight:{x:e,y:0},bottomRight:{x:e,y:o},bottomLeft:{x:0,y:o}},s=(this.opts.now??(()=>performance.now()))(),r=this.feedback.force("processing",s);this.lastFeedbackKey=r.key,this.emit("feedback",r),await this.fire(this.attempt,this.lastOcrReady!==null?this.lastOcrReady.quad:n,{width:e,height:o,tickSharpness:this.lastDetect?.tickSharpness??0},this.lastOcrReady?.via??"manual")}captureReport(){let t=this.stats;return{...this.opts.side!==void 0?{side:this.opts.side}:{},format:this.opts.format??"ID-1",deviceClass:this.deviceClass,video:{width:this.opts.video.videoWidth||0,height:this.opts.video.videoHeight||0},zoom:this.zoom,...t.zoomFallbackAtMs!==void 0?{zoomFallbackAtMs:t.zoomFallbackAtMs}:{},...t.msToCapture!==void 0?{msToCapture:t.msToCapture}:{},...t.via!==void 0?{via:t.via}:{},...t.shutterAtMs!==void 0?{shutterAtMs:t.shutterAtMs}:{},...t.shutterReason!==void 0?{shutterReason:t.shutterReason}:{},ticks:t.ticks,quadFraming:{...t.quadFraming},qualityBlockers:{...t.qualityBlockers},guideBlockers:{...t.guideBlockers},stillRefusals:t.stillRefusals,...this.ocrReport()}}ocrReport(){let t=this.opts.ocr;if(t===void 0)return{};let e=(this.opts.format??"ID-1")==="ID-3"||this.opts.side==="single"?"single":this.opts.side==="verso"?"verso":"recto",o=t.report(e,this.stats.via,(this.opts.now??(()=>performance.now()))());return o===null?{}:{ocr:o}}static freshStats(){return{ticks:0,quadFraming:{},qualityBlockers:{},guideBlockers:{},stillRefusals:0}}setGuide(t){t===void 0?delete this.opts.guide:this.opts.guide=t,this.guideLock.reset()}guideRegion(t){let e=t.width/Math.max(1,t.height),o=this.opts.guide;if(o!==void 0&&o.viewAspect>0){let c={width:o.viewAspect,height:1},a={x:o.rect.x*o.viewAspect,y:o.rect.y,width:o.rect.width*o.viewAspect,height:o.rect.height};return Re(c,a,e,0)}let n=Yt(this.opts.format??"ID-1").center,s=.86,r=s*e/n;return r>.84&&(r=.84,s=r*n/e),{x:(1-s)/2,y:(1-r)/2,width:s,height:r}}resetSide(){this.positioningSince=null,this.detectedSince=null,this.lastSeenAt=null,this.guideLock.reset(),this.lastGuideQuad=null,this.lastOcrReady=null,this.opts.ocr?.reset(),this.stats=i.freshStats(),this.shutterOffered&&(this.shutterOffered=!1,this.emit("shutter",{available:!1}))}withdrawShutter(){this.shutterOffered&&(this.shutterOffered=!1,this.emit("shutter",{available:!1}))}zoomFallback(t){let e=this.videoTrack();if(e===null||this.zoom<=1)return;let o=this.focusCaps(),n=typeof o?.zoom?.min=="number"?Math.max(o.zoom.min,1):1;this.zoom=n,this.stats.zoomFallbackAtMs=Math.round(t-(this.positioningSince??t)),this.guideLock.reset(),this.gate.reset(),e.applyConstraints({advanced:[{zoom:n}]}).catch(()=>{})}offerShutter(t,e){this.shutterOffered||(this.shutterOffered=!0,this.stats.shutterAtMs=Math.round(e-(this.positioningSince??e)),this.stats.shutterReason=t,this.emit("shutter",{available:!0,reason:t}))}torchAvailable(){try{return this.stream?.getVideoTracks?.()[0]?.getCapabilities?.()?.torch===!0}catch{return!1}}async setTorch(t){this.torchOn=t;try{await this.stream?.getVideoTracks?.()[0]?.applyConstraints({advanced:[{torch:t}]})}catch{}}destroy(){if(this.attempt+=1,this.timer!==null&&(this.opts.clearTimer??clearTimeout)(this.timer),this.timer=null,this.clearFrameWatch(),this.offEnded?.(),this.offEnded=null,this.stream)for(let t of this.stream.getTracks())t.stop();this.stream=null,this.opts.video.srcObject=null}async upgradeResolution(){try{let t=this.stream?.getVideoTracks?.()[0];if(t===void 0)return;let e=t.getSettings?.()??{},o=de(t.getCapabilities?.(),{width:e.width??0,height:e.height??0},this.deviceClass,{width:this.camera.width,height:this.camera.height});o!==null&&await t.applyConstraints(o)}catch{}}focusCaps(){try{return this.videoTrack()?.getCapabilities?.()??null}catch{return null}}async applyFocusAndZoom(){let t=this.videoTrack();if(t===null)return;let e=this.focusCaps();this.camera.continuousFocus&&rt(e,"continuous")&&await t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{});let o={width:0,height:0};try{let s=t.getSettings?.()??{};o={width:s.width??0,height:s.height??0}}catch{}let n=Se(e,o,this.opts.format??"ID-1",this.camera);if(n>1)try{await t.applyConstraints({advanced:[{zoom:n}]}),this.zoom=n}catch{this.zoom=1}}async focusAt(t,e){let o=this.videoTrack(),n=Mt(this.focusCaps(),t,e);if(!(o===null||n===null))try{await o.applyConstraints({advanced:[n]}),(this.opts.setTimer??setTimeout)(()=>{this.restoreContinuous()},1500)}catch{}}async restoreContinuous(){let t=this.videoTrack();t===null||!this.camera.continuousFocus||!rt(this.focusCaps(),"continuous")||await t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{})}async refocusOn(t,e){let o=this.camera.refocusBeforePhotoMs,n=this.videoTrack();if(o<=0||n===null||e.width<=0||e.height<=0)return;let s=E(t),r=Mt(this.focusCaps(),(s.x+s.width/2)/e.width,(s.y+s.height/2)/e.height);if(r!==null)try{await n.applyConstraints({advanced:[r]});let c=this.opts.setTimer??setTimeout;await new Promise(a=>{c(()=>a(),o)})}catch{}}videoTrack(){try{return this.stream?.getVideoTracks?.()[0]??null}catch{return null}}async takeStill(t,e,o){if(this.opts.captureStill!==void 0)return this.opts.captureStill(this.opts.video,t,e);let n=this.opts.format??"ID-1",s=this.videoTrack();if(o&&this.opts.photoCapture!==!1&&this.deviceClass!=="LOW"&&!this.torchOn&&s!==null&&Me(s)){await this.refocusOn(t,e);let r=await xe(this.opts.video,t,e,n,{track:s,detect:this.detector(),detectWidth:et});if(this.restoreContinuous(),r!==null)return r}return De(this.opts.video,t,e,n)}detector(){return this.opts.detect??((this.opts.format??"ID-1")==="ID-3"?si:ni)}setState(t){this.state=t,this.emit("statechange",{state:t})}scheduleTick(t){let e=this.opts.setTimer??setTimeout;this.timer=e(()=>{this.tick(t)},this.cadenceMs)}async tick(t){if(t!==this.attempt||this.state!=="positioning"||this.capturing)return;let e=this.opts.now??(()=>performance.now()),o=this.opts.grabDetectFrame??Pe,n=this.detector(),s=o(this.opts.video,et);if(s===null){this.scheduleTick(t);return}if(!this.lit){if(dt(s)>ri)this.lit=!0,this.blackTicks=0;else if(++this.blackTicks>=Ee&&this.frameWatch===null&&(this.opts.firstFrameMs??Ae)>0){this.cameraDead(t);return}}let r=null;try{r=await n(s)}catch{r=null}if(t!==this.attempt)return;let c=r!==null?lt(s,r):s,a=e(),l={sharpness:j(c),exposure:jt(c),meanLuma:dt(c),specularFraction:re(c)},u=ae({format:this.opts.format??"ID-1",quad:r,frameWidth:s.width,frameHeight:s.height,measures:l,...this.opts.thresholds!==void 0?{thresholds:this.opts.thresholds}:{}}),d=this.gate.tick({timestampMs:a,quad:r,quality:l,frameWidth:s.width,frameHeight:s.height}),h=(this.opts.format??"ID-1")!=="ID-3"?Fe(s,this.guideRegion(s),{edgePeakFrac:this.guideTuning.edgePeakFrac}):Z,f=this.guideLock.tick(h,a);this.lastGuideQuad=f.detected?Ce(h):null;let g=this.capturing?null:this.ocrTick(s,r,h,f.detected,u,a);this.positioningSince??(this.positioningSince=a);let y=this.stats;if(y.ticks+=1,y.quadFraming[u.framing]=(y.quadFraming[u.framing]??0)+1,u.framing==="ok"&&!d.ready){let _=u.lighting!=="ok"?u.lighting:u.glare!=="ok"?"glare":u.blur!=="ok"?"blurry":"steadying";y.qualityBlockers[_]=(y.qualityBlockers[_]??0)+1}y.guideBlockers[f.blocker]=(y.guideBlockers[f.blocker]??0)+1,r!==null||f.detected?(this.detectedSince??(this.detectedSince=a),this.lastSeenAt=a):this.detectedSince=null,this.lastSeenAt!==null&&a-this.lastSeenAt<=fi?a-this.positioningSince>=this.shutterTuning.manualShutterMs?this.offerShutter("timeout",a):g?.suspendQuality!==!0&&this.detectedSince!==null&&a-this.detectedSince>=this.shutterTuning.detectedNoLockMs&&this.offerShutter("detected_no_lock",a):this.withdrawShutter();let O=a-(this.lastSeenAt??this.positioningSince);this.zoom>1&&this.camera.zoomFallbackMs>0&&O>=this.camera.zoomFallbackMs&&this.zoomFallback(a),this.emit("checks",{engine:"docv1",p:d.p,plausible:d.plausible,stableTicks:d.stableTicks,quad:d.quad,frameWidth:s.width,frameHeight:s.height,analysis:u,ready:g?.suspendQuality!==!0&&(d.ready&&r!==null||f.ready&&this.lastGuideQuad!==null)||this.lastOcrReady!==null,guide:{detected:f.detected,blocker:f.blocker,fill:h.fill,shape:h.shape,content:h.content,offsetX:h.offsetX,offsetY:h.offsetY},...g!==null&&g.mode!=="off"?{ocr:{mode:g.mode,...g.mrz?{mrz:g.mrz}:{},...g.lock?{lock:g.lock}:{}}}:g?.mrz?{ocr:{mode:g.mode,mrz:g.mrz}}:{}}),this.lastQuad=d.plausible?r:null,this.lastDetect={width:s.width,height:s.height,tickSharpness:l.sharpness};let v=ne(u);u.framing!=="ok"&&f.detected&&(v=mi(f.blocker,h.brightness<this.guideTuning.darkBrightness)),v==="blurry"&&r!==null&&li(r,s,this.opts.format??"ID-1")>=this.camera.focusFarFillFrac&&(v="focus_far"),v==="sensing"&&this.zoom>1&&this.camera.noDocFarHintMs>0&&O>=this.camera.noDocFarHintMs&&(v="focus_far");let x=this.feedback.tick(v,a);if(x.key!==this.lastFeedbackKey&&(this.lastFeedbackKey=x.key,this.emit("feedback",x)),d.guidanceKey!==this.lastGuidance&&(this.lastGuidance=d.guidanceKey,this.emit("guidance",{key:d.guidanceKey})),this.capturing)return;let M=g?.suspendQuality!==!0,T=M&&d.ready&&r!==null,k=M&&f.ready&&this.lastGuideQuad!==null,C=this.lastOcrReady;if(C!==null&&this.opts.autoCapture!==!1){let _=this.feedback.force("processing",a);this.lastFeedbackKey=_.key,this.emit("feedback",_);let A=j(lt(s,C.quad));await this.fire(t,C.quad,{width:s.width,height:s.height,tickSharpness:A},C.via);return}if((T||k)&&this.opts.autoCapture!==!1){let _=this.feedback.force("processing",a);this.lastFeedbackKey=_.key,this.emit("feedback",_);let A=k?this.lastGuideQuad:r,B=k?f.via==="steady"?"guide_steady":"guide_good":"quad",U=k?j(lt(s,A)):l.sharpness;await this.fire(t,A,{width:s.width,height:s.height,tickSharpness:U},B);return}this.scheduleTick(t)}async fire(t,e,o,n){this.capturing=!0;let s=this.opts.grabDetectFrame??Pe,r=this.opts.setTimer??setTimeout,c={width:o.width,height:o.height};try{let a={still:await this.takeStill(e,c,!0),sharpness:o.tickSharpness};if(t!==this.attempt)return;let l=a.still.source==="photo"?0:ui;for(let m=0;m<l;m++){if(await new Promise(g=>{r(()=>g(),hi)}),t!==this.attempt)return;let h=s(this.opts.video,et);if(h===null)continue;let f=j(lt(h,e));if(f>a.sharpness*di){let g=await this.takeStill(e,c,!1);if(t!==this.attempt)return;a={still:g,sharpness:f}}}if(t!==this.attempt)return;let u=a.still.sharpness;if(this.opts.autoCapture!==!1&&n!=="manual"&&typeof u=="number"&&u>=0&&u<this.camera.stillSharpnessMin&&this.stillRefusals<this.camera.stillRefusalsMax){this.stillRefusals+=1,this.stats.stillRefusals+=1,this.guideLock.reset(),this.lastOcrReady=null,(n==="text_lock"||n==="live_mrz")&&this.opts.ocr?.rearmFace();let m=(this.opts.now??(()=>performance.now()))(),h=this.feedback.force("focus_far",m);this.lastFeedbackKey=h.key,this.emit("feedback",h),this.capturing=!1,this.gate.reset(),this.scheduleTick(t);return}this.stillRefusals=0;let d=(this.opts.now??(()=>performance.now()))();this.stats.via=n,this.stats.msToCapture=Math.round(d-(this.positioningSince??d)),this.shutterOffered&&(this.shutterOffered=!1,this.emit("shutter",{available:!1})),this.setState("captured"),this.emit("artifacts",{keyframe:a.still.blob,previewDataUrl:a.still.previewDataUrl,...this.opts.side!==void 0?{side:this.opts.side}:{},...a.still.docRegion!==void 0?{docRegion:a.still.docRegion}:{},...(()=>{let m=n==="live_mrz"?this.opts.ocr?.liveCapture():null;return m?{liveMrz:m}:{}})()})}catch{if(t!==this.attempt)return;this.capturing=!1,this.gate.reset(),this.guideLock.reset(),this.lastOcrReady=null,(n==="text_lock"||n==="live_mrz")&&this.opts.ocr?.rearmFace(),this.scheduleTick(t)}}ocrTick(t,e,o,n,s,r){let c=this.opts.ocr,a=this.opts.video;if(c===void 0||!c.hasEngine)return this.lastOcrReady=null,null;let l=a.videoWidth,u=a.videoHeight;if(l<=0||u<=0||t.width<=0||t.height<=0)return null;let m=(this.opts.format??"ID-1")==="ID-3",h=this.guideRegion(t),f={x:h.x*l,y:h.y*u,w:h.width*l,h:h.height*u},g=l/t.width,y=u/t.height,D;m&&e!==null?D=ci(E(e),g,y,l,u):D=te(f,c.bandTop,u);let w=m?s.glare==="ok":o.cardGlare<=this.guideTuning.glareMax,O=m?s.blur==="ok":o.sharpness>=this.guideTuning.sharpnessMin,v=c.tick({atMs:r,video:a,mrzFace:m||this.opts.side==="verso"||this.opts.side==="single",present:m||e!==null||n,card:f,band:D,portrait:u>l,glareOk:w,sharpOk:O});if(v.ready&&v.via!==void 0){let x=m?e??Oe(h,t):this.lastGuideQuad??Oe(h,t);this.lastOcrReady={quad:x,via:v.via}}else this.lastOcrReady=null;return v}};function ci(i,t,e,o,n){let s=Math.min(o,i.width*1.06*t),r=Math.min(n,Math.max(i.height*1.6*e,s/5)),c=(i.y+i.height/2)*e,a=Math.max(0,Math.min(o-s,(i.x-i.width*.03)*t)),l=Math.max(0,Math.min(n-r,c-r/2));return{x:a,y:l,w:s,h:r}}function Oe(i,t){let e=i.x*t.width,o=i.y*t.height,n=(i.x+i.width)*t.width,s=(i.y+i.height)*t.height;return{topLeft:{x:e,y:o},topRight:{x:n,y:o},bottomRight:{x:n,y:s},bottomLeft:{x:e,y:s}}}function li(i,t,e){let o=E(i);return t.width<=0||t.height<=0?0:e==="ID-3"?o.width/t.width:o.width*o.height/(t.width*t.height)}var ui=2,hi=260,di=1.08;function Pe(i,t){let e=i.videoWidth,o=i.videoHeight;if(e===0||o===0)return null;let n=Math.min(1,t/e),s=Math.round(e*n),r=Math.round(o*n),c=document.createElement("canvas");c.width=s,c.height=r;let a=c.getContext("2d",{willReadFrequently:!0});return a===null?null:(e/Math.max(1,s)>4&&(a.imageSmoothingQuality="high"),a.drawImage(i,0,0,s,r),a.getImageData(0,0,s,r))}function lt(i,t){let e=[t.topLeft.x,t.topRight.x,t.bottomRight.x,t.bottomLeft.x],o=[t.topLeft.y,t.topRight.y,t.bottomRight.y,t.bottomLeft.y],n=Math.max(0,Math.floor(Math.min(...e))),s=Math.max(0,Math.floor(Math.min(...o))),r=Math.min(i.width,Math.ceil(Math.max(...e))),c=Math.min(i.height,Math.ceil(Math.max(...o))),a=Math.max(1,r-n),l=Math.max(1,c-s),u=new Uint8ClampedArray(a*l*4);for(let d=0;d<l;d++){let m=((s+d)*i.width+n)*4;u.set(i.data.subarray(m,m+a*4),d*a*4)}return{data:u,width:a,height:l,colorSpace:i.colorSpace}}function mi(i,t){return i==="glare"?"glare":i==="too_small"?"too_far":i==="too_big"?"too_close":t?"too_dark":i==="blurry"?"blurry":i==="off_center"?"edge_clipped":i==="no_card"?"sensing":"hold_still"}var fi=1200;export{it as a,ne as b,ot as c,Xe as d,re as e,je as f,ae as g,st as h,Si as i,bt as j,ii as k,we as l,rt as m,Mt as n,_i as o,Se as p,oi as q,Te as r,Z as s,Re as t,Fe as u,Ce as v,J as w,Ai as x,ct as y,ji as z,Ae as A,ri as B,Ee as C,ai as D,kt as E,Yi as F,Le as G,ci as H,ui as I,hi as J};
@@ -1,2 +1,2 @@
1
- import{a as o}from"./chunk-DFTCAWMP.js";var A="sekyro-mrz-1";function w(e){return Array.from(new Uint8Array(e),t=>t.toString(16).padStart(2,"0")).join("")}async function m(e){return w(await crypto.subtle.digest("SHA-256",e))}function x(e,t){return m(new TextEncoder().encode(`${A}\0${e}\0${t.join(`
1
+ import{a as o}from"./chunk-VP37FW6C.js";var A="sekyro-mrz-1";function w(e){return Array.from(new Uint8Array(e),t=>t.toString(16).padStart(2,"0")).join("")}async function m(e){return w(await crypto.subtle.digest("SHA-256",e))}function x(e,t){return m(new TextEncoder().encode(`${A}\0${e}\0${t.join(`
2
2
  `)}`))}var i=class extends Error{constructor(t){super(t),this.name="AssetFailure",this.reason=t}},B=Object.keys(o.files).filter(e=>o.files[e].tier==="live"),N=Object.keys(o.files).filter(e=>o.files[e].tier==="lazy");function g(e,t){return`${e.replace(/\/+$/,"")}/${o.fp12}/${t}`}async function b(e,t,d,p=fetch,n=()=>performance.now()){let c=o.files[t],y=n(),f=async s=>{try{let r=await p(g(e,t),{cache:s,signal:d,credentials:"omit"});if(!r.ok)throw new i("download");return await r.arrayBuffer()}catch(r){throw r instanceof i?r:new i("download")}},l=async s=>s.byteLength===c.bytes&&await m(s)===c.sha256,a=await f("force-cache");if(!await l(a)&&(a=await f("reload"),!await l(a)))throw new i("integrity");return{bytes:a,ms:n()-y}}async function T(e,t,d,p=fetch,n=()=>performance.now()){let c=new AbortController,y=new Map,f=t.reduce((r,u)=>r+o.files[u].bytes,0),l=n(),a=!0,s=0;for(let r of t){let u=await b(e,r,c.signal,p,n);y.set(r,u.bytes),u.ms>=50&&(a=!1),s+=u.bytes.byteLength;let h=n()-l;if(s<f&&h>0&&h*f/s>d)throw c.abort(),new i("download")}return{files:y,downloadMs:Math.round(n()-l),cached:a}}function _(e,t){return e==="hosted"?"/models-ocr":t==="live"?"https://assets.sekyro.ai/sdk/web/ocr":"https://assets-staging.sekyro.ai/sdk/web/ocr"}export{x as a,i as b,B as c,T as d,_ as e};
@@ -0,0 +1 @@
1
+ import{a as re,b as ne}from"./chunk-RJZ5SARR.js";import{b as le,c as ce,d as ue}from"./chunk-V5P5P3HY.js";import{a as Q,c as Y,e as j,g as $,h as A,k as R,m as J,n as te}from"./chunk-7KXJEF7P.js";import{b as G,c as de,d as L,e as pe}from"./chunk-FK2DJADA.js";import{a as q,c as z,d as X,e as Z}from"./chunk-CDDYFUER.js";import{d as ee}from"./chunk-XK4CCTLL.js";import{e as ie,f as ae,h as x,j as se,l as oe}from"./chunk-UBRNDTTD.js";var Ie=[...Q.filter(i=>i.startsWith("video/mp4")),"video/webm;codecs=h264","video/webm;codecs=avc1","video/webm;codecs=vp8","video/webm;codecs=vp9","video/webm"],me=new Set;function De(i){let e=/(?:Chrome|Chromium)\/(\d+)\./.exec(i??"");return e?Number(e[1]):null}function he(i=Oe(),e=globalThis.navigator?.userAgent){if(i===void 0)return"";let t=De(e)===126;for(let r of Ie)if(!(me.has(r)||t&&r.startsWith("video/mp4")))try{if(i(r))return r}catch{}return""}function F(i){i!==""&&me.add(i)}function fe(i){return i.replace(/^video\/x-matroska/i,"video/webm")}function ut(i){let e=/codecs=["']?([^,;"']+)/i.exec(i);return e?e[1].trim():i.split(";")[0].trim()}function Oe(){let i=globalThis.MediaRecorder;return i&&typeof i.isTypeSupported=="function"?e=>i.isTypeSupported(e):void 0}var N=2500,Pe=1e3,xe=1500,ve=25e5,Ge=100,Le=700,Fe=20,Ve=1500,V=null;function Ne(){return V??(V=import("./clip-inspect-HZ7N2YOP.js").catch(i=>{throw V=null,i})),V.catch(()=>null)}var S=class extends Error{constructor(e,t){super(t??e),this.kind=e}},Ue=100;function U(i,e){return i.stats===void 0?!1:i.stats===null?!0:i.stats.durationMs<e-Ue}function ge(i,e){return i.stats?e.stats?i.stats.durationMs>e.stats.durationMs:!0:!1}var I=class{constructor(e={}){this.recorder=null;this.stream=null;this.chunks=[];this.bytes=0;this.hardStopTimer=null;this.graceTimer=null;this.pollTimer=null;this.settled=!1;this.now=e.now??(()=>globalThis.performance?.now?.()??Date.now())}clearTimers(){this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.graceTimer&&clearTimeout(this.graceTimer),this.pollTimer&&clearInterval(this.pollTimer),this.hardStopTimer=null,this.graceTimer=null,this.pollTimer=null}record(e,t,r,n=N,a){let s=he(),o=Ne();return this.recordRaw(e,t,r,n,a,s).then(c=>He(c,o),c=>{throw c instanceof S&&(c.requestedMimeType=s),c})}recordRaw(e,t,r,n,a,s){return this.recorder&&!this.settled?Promise.reject(new S("generic","record() called while a recording is in flight \u2014 ClipRecorder handles one recording at a time")):(this.recorder=null,this.clearTimers(),this.chunks=[],this.bytes=0,this.settled=!1,this.stream=e,new Promise((o,c)=>{let l;try{l=new MediaRecorder(e,s?{mimeType:s,videoBitsPerSecond:ve}:{videoBitsPerSecond:ve})}catch{try{l=new MediaRecorder(e)}catch{c(new S("unsupported"));return}}this.recorder=l;let d=h=>{this.settled||(this.settled=!0,this.clearTimers(),h())},u=()=>d(()=>{let h=fe(l.mimeType||s||Y),b=new Blob(this.chunks,{type:h});if(b.size===0){c(new S("generic","empty clip"));return}if(A(b)){c(new S("cliptoolarge"));return}o({blob:b,mimeType:h,requestedMimeType:s})});l.ondataavailable=h=>{h.data&&h.data.size&&(this.chunks.push(h.data),this.bytes+=h.data.size,this.bytes>$&&d(()=>{try{l.state!=="inactive"&&l.stop()}catch{}c(new S("cliptoolarge"))}))},l.onstop=u,l.onerror=()=>d(()=>c(new S("generic")));let f=this.now();if(r!==void 0||a!==void 0){let h=!1;l.onstart=()=>{if(!(h||this.settled)&&(h=!0,f=this.now(),r!==void 0))try{r()}catch{}}}try{l.start(Pe)}catch{d(()=>c(new S("generic")));return}let v=()=>{if(this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=null,this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.hardStopTimer=null,this.settled||t?.(),l.state!=="inactive"){try{l.stop()}catch{u()}this.graceTimer=setTimeout(u,xe)}else u()},p=this.now();if(a===void 0){this.hardStopTimer=setTimeout(v,n);return}let m=null,y=!1;this.hardStopTimer=setTimeout(v,n+Le),this.pollTimer=setInterval(()=>{if(this.settled||y)return;let h=null;try{h=a.latest()}catch{h=null}let b=h?.presentationTimeMs;b!==void 0&&Number.isFinite(b)&&b>=f&&m===null&&(m=b);let C=m!==null&&b!==void 0&&b-m>=n,E=m===null&&this.now()-p>=n;if(!(!C&&!E)){if(y=!0,this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=null,E){v();return}this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.hardStopTimer=setTimeout(v,Ge)}},Fe)}))}stop(e){this.clearTimers();let t=this.recorder;if(t&&t.state!=="inactive")try{t.stop()}catch{}this.recorder=null,(e??this.stream)?.getTracks().forEach(n=>n.stop()),this.stream=null}};async function He(i,e){let t,r=new Promise(l=>{t=setTimeout(()=>l(null),Ve)}),n=await Promise.race([e,r]);if(clearTimeout(t),n===null)return i;let a;try{a=await n.blobBytes(i.blob)}catch{return{...i,stats:null}}let s=n.inspectClipBytes(a);if(s?.container!=="webm")return{...i,stats:s};let o=n.withWebmDuration(a,s.durationMs);if(o===null)return{...i,stats:s};let c=n.inspectClipBytes(o);return c===null||c.frames!==s.frames||c.durationMs!==s.durationMs?{...i,stats:s}:{...i,blob:new Blob([o],{type:i.blob.type}),stats:s}}var Ke=["magenta","yellow","green","blue"];var Be={magenta:"rgb(255, 72, 150)",yellow:"rgb(255, 190, 0)",green:"rgb(0, 238, 175)",blue:"rgb(25, 150, 255)",dark:"rgb(0, 0, 0)"};function ft(i){return Be[i]}var We=4,qe=4,D=i=>typeof i=="number"&&Number.isFinite(i);function be(i){if(typeof i!="object"||i===null)return!1;let e=i;if(typeof e.nonce!="string"||e.nonce.length===0||!Array.isArray(e.colours)||e.colours.length<1||e.colours.length>8||!e.colours.every(r=>Ke.includes(r))||!Array.isArray(e.onsetsMs)||e.onsetsMs.length!==e.colours.length)return!1;let t=-1;for(let r of e.onsetsMs){if(!D(r)||r<0||r<=t)return!1;t=r}return!(!D(e.holdMs)||e.holdMs<=0||!D(e.endMs)||e.endMs<=t||!D(e.clipMs)||e.clipMs<e.endMs||e.clipMs>8e3)}function ye(i,e){return be(i)?Math.max(e,Math.ceil(i.clipMs)):e}function Me(i,e){let t=e.now??(()=>performance.now()),r=be(i)?i:void 0,n=[],a=null,s=null,o=null,c=!1,l=null,d=p=>{l=p;try{e.paint(p)}catch{}},u=p=>{let m=e.frames?.()??null;return m!==null&&o!==null?m.mediaTimeMs+(p-m.presentationTimeMs)-o:p-(s??p)},f=(p,m,y=0)=>{if(c)return;let h=Math.max(0,p-u(t()));a=setTimeout(()=>{if(a=null,!c){if(y<We&&u(t())<p-qe){f(p,m,y+1);return}m()}},h)},v=p=>{if(r===void 0)return;let m=r.endMs;if(p>=r.colours.length){f(m,()=>d(null));return}let y=r.onsetsMs[p],h=p+1<r.onsetsMs.length?r.onsetsMs[p+1]:m;f(y,()=>{let b=u(t());if(b>m){l!==null&&d(null);return}let C=r.colours[p];d(C);let E=n.length===0?0:n[n.length-1].tMs;n.push({tMs:Math.max(E,Math.round(b)),colour:C});let M=y+r.holdMs;if(M<h){f(M,()=>{if(u(t())>m){l!==null&&d(null);return}d("dark"),v(p+1)});return}v(p+1)})};return{started(p){if(r===void 0||c||s!==null)return;s=p;let m=e.frames?.()??null;o=m===null?null:m.mediaTimeMs+(p-m.presentationTimeMs),v(0)},stop(){c||(c=!0,a!==null&&clearTimeout(a),a=null,l!==null&&d(null))},report(){return r===void 0?void 0:{nonce:r.nonce,rendered:[...n]}}}}function Se(i,e,t=.92){return new Promise((r,n)=>{let a=i.videoWidth,s=i.videoHeight;if(!a||!s){n(new Error("video-not-ready"));return}let o=e.getContext("2d");if(!o){n(new Error("no-2d-context"));return}e.width=a,e.height=s,o.scale(-1,1),o.drawImage(i,-a,0),e.toBlob(c=>c?r(c):n(new Error("empty-keyframe")),"image/jpeg",t)})}var O=class{constructor(e){this.timer=null;this.frameCallbackId=null;this.running=!1;this.busy=!1;this.lastRunAt=Number.NEGATIVE_INFINITY;this.degradeCount=0;this.durations=[];this.options=e,this.periodMs=1e3/e.cadenceHz}start(){if(this.running)return;this.running=!0;let e=this.options.video;if(typeof e?.requestVideoFrameCallback=="function"){let t=()=>{this.running&&(this.frameCallbackId=e.requestVideoFrameCallback?.(()=>{this.frameCallbackId=null,this.now()-this.lastRunAt>=this.periodMs&&this.tick(),t()}))};t();return}this.timer=setInterval(()=>this.tick(),this.periodMs)}stop(){this.running=!1,this.timer!==null&&(clearInterval(this.timer),this.timer=null),this.frameCallbackId!==null&&(this.options.video?.cancelVideoFrameCallback?.(this.frameCallbackId),this.frameCallbackId=null)}stats(){let e=this.durations.length===0?0:this.durations.reduce((t,r)=>t+r,0)/this.durations.length;return{degradeCount:this.degradeCount,meanDetectMs:e}}now(){return this.options.now?.()??performance.now()}tick(){if(!this.running)return;if(this.busy){this.degradeCount+=1;return}this.busy=!0,this.lastRunAt=this.now();let e=this.now();this.options.run().catch(()=>{}).finally(()=>{this.busy=!1,this.durations.push(this.now()-e),this.durations.length>20&&this.durations.shift()})}};var ze=Object.freeze({Q_GOOD:.6,RISE_PER_S:.9,FALL_PER_S:.25,CENTER_FALLOFF_IOD_MULTIPLE:1.35,BOX_EYE_OFFSET_FACTOR:.12,IOD_BOX_PROXY_FACTOR:.42,SIZE_IDEAL_MIN:.12,SIZE_IDEAL_MAX:.3,SIZE_HARD_MIN:.08,SIZE_HARD_MAX:.45,ROLL_MAX_DEG:25,MOTION_VELOCITY_IOD_PER_S:.5,MOTION_TAU_S:.4,MOTION_DEADBAND_IOD_PER_S:.1,READY_WINDOW_MS:500,GUIDE_SIZE:.6,GUIDE_CENTERING:.6,GUIDE_POSE:.6,GUIDE_EXPOSURE:.6,GUIDE_SHARPNESS:.35,GUIDE_MOTION:.5}),_=i=>Math.min(1,Math.max(0,i)),k=class{constructor(e={}){this.p=0;this.lastTickAt=null;this.lastCenter=null;this.velocityEma=0;this.qWindow=[];this.lastSizeDirection="ideal";this.t={...ze,...e}}reset(){this.p=0,this.lastTickAt=null,this.lastCenter=null,this.velocityEma=0,this.qWindow=[],this.lastSizeDirection="ideal"}tick(e){let{observation:t,quality:r,timestampMs:n}=e,a=this.lastTickAt===null?0:Math.max(0,(n-this.lastTickAt)/1e3);this.lastTickAt=n;let s={presence:0,single:1,centering:0,size:0,pose:0,sharpness:_(r.sharpness),exposure:_(r.exposure),motion:1};if(t!==null){s.presence=1,s.single=(t.extraFaces??0)>0?0:1;let d=this.geometryOf(t,e);s.centering=d.centering,s.size=d.size,s.pose=d.pose,s.motion=this.motionOf(d.center,d.iod,n)}else this.lastCenter=null,this.velocityEma=0;let o=Math.min(s.presence,s.single,s.centering,s.size,s.pose,s.sharpness,s.exposure,s.motion);this.p=_(this.p+(o>=this.t.Q_GOOD?this.t.RISE_PER_S*o:-this.t.FALL_PER_S*(1-o))*a),this.qWindow.push({at:n,q:o}),this.qWindow=this.qWindow.filter(d=>d.at>=n-this.t.READY_WINDOW_MS);let c=this.qWindow.map(d=>d.q);if(c.length>=3){let d=Math.min(...c),u=c.indexOf(d);c=c.filter((f,v)=>v!==u)}let l=this.p>=1&&c.every(d=>d>=this.t.Q_GOOD);return{at:n,q:o,p:this.p,factors:s,guidanceKey:this.guidanceOf(s,r,o),ready:l,accepted:o>=this.t.Q_GOOD}}geometryOf(e,t){let{box:r,eyes:n}=e,a={x:t.frameWidth/2,y:t.frameHeight/2},s=Math.min(t.frameWidth,t.frameHeight),o=n!==void 0?{x:(n.left.x+n.right.x)/2,y:(n.left.y+n.right.y)/2}:{x:r.x+r.width/2,y:r.y+r.height/2-this.t.BOX_EYE_OFFSET_FACTOR*r.height},c=n!==void 0?Math.hypot(n.right.x-n.left.x,n.right.y-n.left.y):this.t.IOD_BOX_PROXY_FACTOR*r.width,l=Math.hypot(o.x-a.x,o.y-a.y),d=c<=0?0:1-_(l/(this.t.CENTER_FALLOFF_IOD_MULTIPLE*c)),u=s>0?c/s:0;this.lastSizeDirection=u<this.t.SIZE_IDEAL_MIN?"far":u>this.t.SIZE_IDEAL_MAX?"close":"ideal";let f;u<this.t.SIZE_HARD_MIN||u>this.t.SIZE_HARD_MAX?f=0:u<this.t.SIZE_IDEAL_MIN?f=(u-this.t.SIZE_HARD_MIN)/(this.t.SIZE_IDEAL_MIN-this.t.SIZE_HARD_MIN):u>this.t.SIZE_IDEAL_MAX?f=(this.t.SIZE_HARD_MAX-u)/(this.t.SIZE_HARD_MAX-this.t.SIZE_IDEAL_MAX):f=1;let v=1;if(n!==void 0){let p=Math.abs(Math.atan2(n.right.y-n.left.y,n.right.x-n.left.x))*180/Math.PI;v=1-_(p/this.t.ROLL_MAX_DEG)}return{center:o,iod:c,centering:d,size:f,pose:v}}motionOf(e,t,r){let n=this.lastCenter;if(this.lastCenter={...e,at:r},n===null||t<=0)return 1;let a=(r-n.at)/1e3;if(a<=0)return 1;let s=Math.hypot(e.x-n.x,e.y-n.y)/t/a;s<=this.t.MOTION_DEADBAND_IOD_PER_S&&(s=0);let o=1-Math.exp(-a/this.t.MOTION_TAU_S);return this.velocityEma=o*s+(1-o)*this.velocityEma,1-_(this.velocityEma/this.t.MOTION_VELOCITY_IOD_PER_S)}guidanceOf(e,t,r){if(e.presence<=0)return"fcv3.no_face";if(e.single<=0)return"fcv3.one_face";if(e.size<this.t.GUIDE_SIZE)return this.sizeGuidance();if(e.centering<this.t.GUIDE_CENTERING)return"fcv3.center_face";if(e.pose<this.t.GUIDE_POSE)return"fcv3.straighten";if(e.exposure<this.t.GUIDE_EXPOSURE)return this.exposureGuidance(t);if(e.sharpness<this.t.GUIDE_SHARPNESS)return"fcv3.steady_camera";if(e.motion<this.t.GUIDE_MOTION)return"fcv3.hold_still";if(r<this.t.Q_GOOD){let n=[["size",this.sizeGuidance()],["centering","fcv3.center_face"],["pose","fcv3.straighten"],["exposure",this.exposureGuidance(t)],["sharpness","fcv3.steady_camera"],["motion","fcv3.hold_still"]],a=n[0];for(let s of n)e[s[0]]<e[a[0]]&&(a=s);return a[1]}return"fcv3.hold_still"}sizeGuidance(){return this.lastSizeDirection==="far"?"fcv3.come_closer":"fcv3.move_back"}exposureGuidance(e){let t=(G[0]+G[1])/2;return e.meanLuma<t?"fcv3.more_light":"fcv3.too_bright"}};var Xe=["single","size","centering","pose","exposure","sharpness","motion"];function Ze(i){if(i.accepted)return null;if(i.factors.presence<=0)return"no_face";let e="single";for(let t of Xe)i.factors[t]<i.factors[e]&&(e=t);return e}var w=class{constructor(){this.blocked={};this.acceptedMs=0;this.ticks=0;this.lastAt=null}record(e){let t=this.lastAt===null?0:Math.max(0,e.at-this.lastAt);this.lastAt=e.at,this.ticks+=1;let r=Ze(e);if(r===null){this.acceptedMs+=t;return}let n=this.blocked[r]??{count:0,ms:0};n.count+=1,n.ms+=t,this.blocked[r]=n}summary(){let e={};for(let[t,r]of Object.entries(this.blocked))e[t]={count:r.count,ms:Math.round(r.ms)};return{blocked:e,acceptedMs:Math.round(this.acceptedMs),ticks:this.ticks}}};var Qe=["obs","manycam","virtual","snap camera","xsplit","droidcam","iriun","camo"],Ye=[/^(front|back|rear)( [a-z ]+)? camera$/i,/^caméra (avant|arrière)\b/i,/^cámara (frontal|trasera|delantera)\b/i,/^câmera (frontal|traseira)\b/i,/^(front|rück)kamera\b/i,/^الكاميرا (الأمامية|الخلفية)/,/^camera2? ?\d+, facing (front|back|external)/i,/facetime/i,/\b(integrated|built-in|builtin) (web)?cam(era)?\b/i,/\b(hd )?web ?cam\b/i,/\([0-9a-f]{4}:[0-9a-f]{4}\)\s*$/i];function je(i){let e=(i??"").trim().toLowerCase();return e.length===0?"unknown":Qe.some(t=>e.includes(t))?"known_virtual":Ye.some(t=>t.test(e))?"platform":"unknown"}function Te(i){if(typeof i!="function")return!1;try{return/\{\s*\[native code\]\s*\}\s*$/.test(Function.prototype.toString.call(i))}catch{return!1}}function $e(i=globalThis){return Te(i.navigator?.mediaDevices?.getUserMedia)&&Te(i.MediaStreamTrack?.prototype?.getSettings)}async function Je(i,e=globalThis){let t=e.crypto?.subtle?.digest;if(typeof t=="function")try{let r=new Uint8Array(await t.call(e.crypto?.subtle,"SHA-256",new TextEncoder().encode(i)));return Array.from(r.subarray(0,8),n=>n.toString(16).padStart(2,"0")).join("")}catch{return}}async function Ce(i,e=globalThis){let t={};try{t=typeof i.getSettings=="function"?i.getSettings()??{}:{}}catch{t={}}let r={};if((t.facingMode==="user"||t.facingMode==="environment"||t.facingMode==="left"||t.facingMode==="right")&&(r.facingMode=t.facingMode),typeof t.frameRate=="number"&&Number.isFinite(t.frameRate)&&(r.frameRate=t.frameRate),typeof t.width=="number"&&Number.isFinite(t.width)&&(r.width=t.width),typeof t.height=="number"&&Number.isFinite(t.height)&&(r.height=t.height),typeof t.deviceId=="string"&&t.deviceId.length>0){let a=await Je(t.deviceId,e);a!==void 0&&(r.deviceIdHash=a)}let n;try{n=i.label}catch{n=void 0}return{trackSettings:r,capabilitiesPresent:typeof i.getCapabilities=="function",labelClass:je(n),prototypesIntact:$e(e)}}var H=i=>Math.round(i*100)/100;function Ee(i){let e=i,t=typeof e?.requestVideoFrameCallback=="function",r=null,n=null,a=0,s=0,o=0,c=0,l=0,d=0,u=()=>{!t||e?.requestVideoFrameCallback===void 0||(r=e.requestVideoFrameCallback((f,v)=>{if(r=null,!t)return;let p=v.presentationTime;if(n!==null){let m=p-n.presentationTimeMs;s+=1;let y=m-o;o+=y/s,c+=y*(m-o)}typeof v.captureTime=="number"&&Number.isFinite(v.captureTime)&&(l+=p-v.captureTime,d+=1),a+=1,n={mediaTimeMs:v.mediaTime*1e3,presentationTimeMs:p},u()}))};return u(),{latest:()=>n,stats:()=>({n:a,meanGapMs:s===0?0:H(o),stdGapMs:s<2?0:H(Math.sqrt(c/(s-1))),captureLatencyMs:d===0?null:H(l/d)}),stop:()=>{t&&(t=!1,r!==null&&e?.cancelVideoFrameCallback?.(r),r=null)}}}function _e(i,e,t){return{...i,rvfc:e,rampPainter:t}}var et=1e3,K="fcv3.hold_upright",tt=200,B=4,rt=600,nt=1e3,Re={sharpness:1,exposure:1,meanLuma:128};function it(i,e){return e.width=i.videoWidth,e.height=i.videoHeight,e.getContext("2d").drawImage(i,0,0),new Promise((t,r)=>e.toBlob(n=>n?t(n):r(new Error("empty-keyframe")),"image/jpeg",.92))}function at(){return z()==="phone"}var ke=class{constructor(e){this.handlers=new Map;this.stateValue="idle";this.attempt=0;this.stream=null;this.detector=null;this.scheduler=null;this.gate=null;this.profiler=null;this.lastGuidanceKey=null;this.positioningStartedAt=0;this.cameraRequestedAt=null;this.cameraReadyAt=null;this.faceAcquiredAt=null;this.captureCompleteAt=null;this.fired=!1;this.carriedDegrade=0;this.carriedMeans=[];this.blockStats=null;this.lastGateSnapshotAt=Number.NEGATIVE_INFINITY;this.uprightGuard=!1;this.trackProvenance=null;this.ramp=null;this.snapshotCanvas=null;this.options=e,this.facing=e.facingMode??"user"}get state(){return this.stateValue}on(e,t){let r=this.handlers.get(e);return r||(r=new Set,this.handlers.set(e,r)),r.add(t),()=>r?.delete(t)}emit(e,t){for(let r of[...this.handlers.get(e)??[]])r(t)}async start(e={}){e.facingMode!==void 0&&(this.facing=e.facingMode),this.attempt+=1,await this.run(this.attempt)}get facingMode(){return this.facing}retry(){this.teardownAttempt(),this.start()}switchCamera(){this.facing=this.facing==="user"?"environment":"user",this.teardownAttempt(),this.start()}restart(e){this.facing=e,this.teardownAttempt(),this.start()}destroy(){this.attempt+=1,this.teardownAttempt(),this.detector?.destroy(),this.detector=null,this.options.video.srcObject=null}async run(e){let{options:t}=this;this.fired=!1,this.lastGuidanceKey=null,this.carriedDegrade=0,this.carriedMeans=[],this.cameraRequestedAt=null,this.cameraReadyAt=null,this.faceAcquiredAt=null,this.captureCompleteAt=null,this.uprightGuard=(t.isPhone??at)(),this.setState("preflight");let r=j();if(r!=="OK"){this.fail(r==="INSECURE_CONTEXT"?"insecure":"unsupported",{phase:"preflight"});return}this.setState("acquiring");let n=t.getUserMedia??(l=>navigator.mediaDevices.getUserMedia(l)),a;this.cameraRequestedAt=this.now();try{let{facingMode:l,...d}=q(X(),this.facing).video;a=await ne(this.facing,d,{getUserMedia:n,enumerateDevices:lt(t)})}catch(l){if(e!==this.attempt)return;if(l instanceof re){this.fail("backcamera",{phase:"acquiring",name:R(l)});return}this.fail(J(l),{phase:"acquiring",name:R(l)});return}if(ee(a),te(a),e!==this.attempt){for(let l of a.getTracks())l.stop();return}this.stream=a;let s=a.getVideoTracks?.()[0];if(this.trackProvenance=s===void 0?null:Ce(s).catch(()=>null),this.facing=Z(a)??this.facing,t.video.srcObject=a,await t.video.play().catch(()=>{}),e!==this.attempt)return;if(this.cameraReadyAt=this.now(),this.detector===null){let l={v3AssetBaseUrl:t.v3AssetBaseUrl},d=t.createDetector??(t.createWorker!==void 0&&se()?async()=>{try{return await oe.create(t.createWorker(),l)}catch{return x(l)}}:()=>x(l)),u;try{u=await d()}catch(f){e===this.attempt&&this.fail("models",{phase:"models",name:R(f)},f instanceof ie?f.fallbackReason:ot(f));return}if(e!==this.attempt){u.destroy();return}this.detector=u,this.options.telemetry?.({type:"detector",tier:u.tier,fallbackReason:u.fallbackReason})}let o=le(),c=t.deviceClass??ce(o);this.profiler=new ue(c),this.options.telemetry?.({type:"profile",staticClass:c,activeClass:this.profiler.deviceClass,simd:o.simd}),this.gate=new k(t.thresholds??{}),this.blockStats=new w,this.lastGateSnapshotAt=this.now(),t.rankKeyframes?.()&&import("./keyframe-rank-R4NPQGN3.js").then(l=>W=l,()=>{}),this.setState("positioning"),this.positioningStartedAt=this.now(),this.startScheduler(e)}get animations(){return this.profiler?.profile.animations??"full"}startScheduler(e){let t=this.profiler;if(t===null)return;if(this.scheduler!==null){let n=this.scheduler.stats();this.carriedDegrade+=n.degradeCount,n.meanDetectMs>0&&this.carriedMeans.push(n.meanDetectMs),this.scheduler.stop()}let r=new O({cadenceHz:t.profile.cadenceHz,video:this.options.video,now:this.options.now,run:()=>this.detectTick(e)});this.scheduler=r,r.start()}async detectTick(e){let{detector:t,gate:r,profiler:n}=this,a=this.options.video;if(e!==this.attempt||t===null||r===null||n===null||this.fired||a.videoWidth===0)return;if(this.isLandscape()){this.holdUpright(e);return}let s=n.deviceClass,o=this.now(),c=this.options.makeSnapshot?.(a,n.profile.inputWidth)??this.defaultSnapshot(a,n.profile.inputWidth),l=null;try{l=await t.detect(c,a.videoWidth,a.videoHeight)}catch{l=null}if(e!==this.attempt||this.fired)return;n.record(this.now()-o),n.deviceClass!==s&&this.startScheduler(e);let d=l===null?Re:this.options.measureQuality?.(a,l.box)??this.defaultQuality(a,l.box),u=r.tick({timestampMs:this.now(),observation:l,quality:d,frameWidth:a.videoWidth,frameHeight:a.videoHeight});u.accepted&&this.faceAcquiredAt===null&&(this.faceAcquiredAt=u.at),this.blockStats?.record(u),!u.ready&&u.at-this.lastGateSnapshotAt>=et&&(this.lastGateSnapshotAt=u.at,this.reportGate(!1)),this.emit("checks",{engine:"v3",progress:u.p,q:u.q,factors:u.factors,attempt:e}),u.guidanceKey!==this.lastGuidanceKey&&(this.lastGuidanceKey=u.guidanceKey,this.emit("guidance",{key:u.guidanceKey})),u.ready&&this.stateValue==="positioning"&&(this.fired=!0,this.captureCompleteAt=u.at,this.fire(e))}async fire(e){let{options:t}=this,r=this.scheduler;r?.stop(),this.reportGate(!0);let n=r?.stats()??{degradeCount:0,meanDetectMs:0},a=[...this.carriedMeans,...n.meanDetectMs>0?[n.meanDetectMs]:[]];t.telemetry?.({type:"fired",timeToGateMs:this.now()-this.positioningStartedAt,degradeCount:this.carriedDegrade+n.degradeCount,meanDetectMs:a.length===0?0:a.reduce((M,g)=>M+g,0)/a.length});let s=t.mode??"clip",o=t.rankKeyframes?.()&&W?W.default(this,e).catch(()=>this.collectKeyframes(e)):this.collectKeyframes(e);if(s==="photo"){let M=this.watchRotation(e,null),g=await o;if(M(),e!==this.attempt)return;if(g===null){this.fail("generic",{phase:"keyframes"});return}let P=await this.provenance({n:0,meanGapMs:0,stdGapMs:0,captureLatencyMs:null},!1);if(e!==this.attempt)return;this.finishCapture({keyframe:g.blob,previewDataUrl:g.previewDataUrl,...P});return}this.setState("recording");let c=this.stream;if(c===null){this.fail("generic",{phase:"recording"});return}let l=t.screenRamp?.(),d=l!==void 0,u=null;o.then(M=>{u=M},()=>{});let f=()=>{e===this.attempt&&u!==null&&this.emit("frozen",{previewDataUrl:u.previewDataUrl})},v=ye(l,N),p=null,m,y=0;try{let M=this.recordTake(e,c,l,v,void 0).then(T=>T,T=>({failed:T})),[g,P]=await Promise.all([M,o]);if(m=P,e!==this.attempt)return;if("failed"in g){if(g.failed.kind==="cliptoolarge")throw g.failed;F(g.failed.requestedMimeType??"")}else p=g,U(g.clip,v)?g.clip.stats===null&&F(g.clip.requestedMimeType??""):f();if(p===null||U(p.clip,v)){y=1,t.telemetry?.({type:"clip_retake",reason:p===null?"error":p.clip.stats===null?"unreadable":"short"});let T=null;try{T=await this.recordTake(e,c,l,v,f)}catch(Ae){if(p===null)throw Ae}if(e!==this.attempt)return;T!==null&&(p===null||ge(T.clip,p.clip))&&(p=T),T===null&&f()}}catch(M){if(e!==this.attempt)return;let g=M.kind;this.fail(g==="cliptoolarge"?"cliptoolarge":"recorder",{phase:"recording",name:R(M)});return}if(p===null){this.fail("recorder",{phase:"recording"});return}let{clip:h,rvfc:b,report:C}=p;if(A(h.blob)){this.fail("cliptoolarge",{phase:"recording"});return}if(m===null){this.fail("generic",{phase:"keyframes"});return}let E=await this.provenance(b,d);e===this.attempt&&this.finishCapture({clip:h.blob,clipMimeType:h.mimeType,...h.stats?{clipStats:h.stats}:{},clipRetakes:y,keyframe:m.blob,previewDataUrl:m.previewDataUrl,...C!==void 0&&C.rendered.length>0?{screenRamp:C}:{},...E})}async recordTake(e,t,r,n,a){let s=this.options.createRecorder?.()??new I({now:()=>this.now()}),o=Ee(this.options.video),c=Me(r,{paint:u=>{(u===null||e===this.attempt)&&this.emit("ramp",{colour:u})},now:()=>this.now(),frames:o.latest});this.ramp=c;let l=()=>{o.stop(),c.stop(),this.ramp===c&&(this.ramp=null)},d=this.watchRotation(e,s);try{return{clip:await s.record(t,a,()=>c.started(this.now()),n,o),rvfc:o.stats(),report:c.report()}}finally{d(),l()}}async provenance(e,t){let r=this.trackProvenance;if(r===null)return{};let n,a=new Promise(o=>{n=setTimeout(()=>o(null),nt)}),s=await Promise.race([r,a]);return clearTimeout(n),s===null?{}:{provenance:_e(s,e,t)}}isLandscape(){let e=this.options.video;return this.uprightGuard&&e.videoWidth>e.videoHeight}holdUpright(e){this.gate?.reset(),this.emit("checks",{engine:"v3",progress:0,q:0,factors:{presence:0,single:1,centering:0,size:0,pose:0,sharpness:0,exposure:0,motion:0},attempt:e}),this.lastGuidanceKey!==K&&(this.lastGuidanceKey=K,this.emit("guidance",{key:K}))}watchRotation(e,t){if(!this.uprightGuard)return()=>{};let r=this.options.video,n=()=>{if(e!==this.attempt||t!==null&&this.stateValue!=="recording"){o();return}r.videoWidth>0&&this.isLandscape()&&(o(),this.abortRecording(e,t))},a=setInterval(n,tt);r.addEventListener?.("resize",n);let s=!1;function o(){s||(s=!0,clearInterval(a),r.removeEventListener?.("resize",n))}return o}abortRecording(e,t){if(e!==this.attempt)return;this.attempt+=1;let r=this.attempt;try{t?.stop()}catch{}this.ramp?.stop(),this.ramp=null,this.fired=!1,this.captureCompleteAt=null,this.gate=new k(this.options.thresholds??{}),this.blockStats=new w,this.lastGateSnapshotAt=this.now(),this.lastGuidanceKey=null,this.setState("positioning"),this.positioningStartedAt=this.now(),this.holdUpright(r),this.startScheduler(r)}async collectKeyframes(e){let t=this.options.captureKeyframe??(a=>this.defaultKeyframe(a)),r=rt/(B-1),n=null;for(let a=0;a<B;a+=1){if(e!==this.attempt)return n;try{let s=await t(this.options.video);(n===null||s.sharpness>n.sharpness)&&(n=s)}catch{}a<B-1&&await st(r)}return n}finishCapture(e){this.stopTracks(),this.setState("captured");let t=this.captureTiming();this.emit("artifacts",t===void 0?e:{...e,timing:t})}captureTiming(){let e={},t=(r,n,a)=>{n!==null&&a!==null&&(e[r]=Math.max(0,Math.round(a-n)))};return t("cameraReadyMs",this.cameraRequestedAt,this.cameraReadyAt),t("faceAcquireMs",this.cameraReadyAt,this.faceAcquiredAt),t("captureMs",this.faceAcquiredAt,this.captureCompleteAt),Object.keys(e).length>0?e:void 0}async defaultKeyframe(e){let t=document.createElement("canvas"),r=await(this.facing==="user"?Se:it)(e,t),n=t.toDataURL("image/jpeg",.92);return{blob:r,previewDataUrl:n,sharpness:this.centerSharpness(e)}}defaultSnapshot(e,t){try{let r=this.snapshotCanvas??document.createElement("canvas"),n=t/Math.max(1,e.videoWidth),a=Math.max(1,Math.round(e.videoWidth*n)),s=Math.max(1,Math.round(e.videoHeight*n)),o=r.getContext("2d");return o===null?e:(r.width!==a&&(r.width=a),r.height!==s&&(r.height=s),o.drawImage(e,0,0,a,s),this.snapshotCanvas=r,r)}catch{return e}}defaultQuality(e,t){let r=we(e,t,96);return r===null?Re:{sharpness:L(r),exposure:pe(r),meanLuma:de(r)}}centerSharpness(e){let t=ae(e),r=we(e,{x:t.width*.25,y:t.height*.25,width:t.width*.5,height:t.height*.5},96);return r===null?0:L(r)}teardownAttempt(){this.scheduler?.stop(),this.scheduler=null,this.reportGate(!0),this.gate=null,this.ramp?.stop(),this.ramp=null,this.stopTracks()}reportGate(e){let t=this.blockStats,r=this.profiler;if(t===null||r===null)return;let n=t.summary();e&&(this.blockStats=null),n.ticks!==0&&this.options.telemetry?.({type:"gate",final:e,activeClass:r.deviceClass,cadenceHz:r.profile.cadenceHz,...n})}stopTracks(){if(this.stream!==null){for(let e of this.stream.getTracks())e.stop();this.stream=null}}fail(e,t,r){this.scheduler?.stop(),this.reportGate(!0),this.stopTracks(),this.setState("error"),this.options.telemetry?.({type:"error",kind:e,fallbackReason:r});let{phase:n,name:a}=t;this.emit("error",{kind:e,retryable:e!=="insecure"&&e!=="unsupported",detail:a===void 0?{phase:n}:{phase:n,name:a}})}setState(e){this.stateValue=e,this.emit("statechange",{state:e})}now(){return this.options.now?.()??performance.now()}},W;function st(i){return new Promise(e=>setTimeout(e,i))}function ot(i){return i instanceof Error?i.message:String(i)}function we(i,e,t){try{let r=document.createElement("canvas"),n=t/Math.max(1,e.width);r.width=Math.max(1,Math.round(e.width*n)),r.height=Math.max(1,Math.round(e.height*n));let a=r.getContext("2d");return a===null?null:(a.drawImage(i,e.x,e.y,e.width,e.height,0,0,r.width,r.height),a.getImageData(0,0,r.width,r.height))}catch{return null}}function lt(i){if(i.enumerateDevices!==void 0)return i.enumerateDevices;if(i.getUserMedia===void 0&&!(typeof navigator>"u"||typeof navigator.mediaDevices?.enumerateDevices!="function"))return()=>navigator.mediaDevices.enumerateDevices()}export{ut as a,N as b,Pe as c,xe as d,ve as e,Ge as f,Le as g,Fe as h,Ve as i,S as j,Ue as k,U as l,ge as m,I as n,Ke as o,ft as p,Se as q,O as r,ze as s,k as t,Ze as u,w as v,et as w,K as x,tt as y,B as z,rt as A,nt as B,ke as C};
@@ -0,0 +1 @@
1
+ import{a as Y,d as ee,e as O,f as te,g as ne}from"./chunk-CPK5FYNJ.js";import{C as X,a as j}from"./chunk-J5IQ6THP.js";import{f as Q,l as Z}from"./chunk-7KXJEF7P.js";import{c as $}from"./chunk-CDDYFUER.js";import{c as J,h as C}from"./chunk-UBRNDTTD.js";var ue=12e4,re=13e4,le=3e3,fe=1200,P=Symbol.for("@sekyro/web.preload.v1");function g(){let e=globalThis;return e[P]??(e[P]=new Map),e[P]}function S(e){let n=(e??J).replace(/\/+$/,"");return n===""?"/":n}function se(e){let n=g(),r=n.get(e);return r===void 0&&(r={status:"idle",promise:null,scheduled:null,detectorPromise:null,detector:null,listeners:new Set},n.set(e,r)),r}function A(e,n){if(e.status!==n){e.status=n;for(let r of[...e.listeners])r(n)}}var x=e=>C({preferred:["blaze"],v3AssetBaseUrl:e,blazeInitTimeoutMs:ue}),F=x;function Pe(e){F=e??x}function Ae(){for(let e of g().values())e.detector?.destroy();g().clear(),F=x}function pe(){return typeof window<"u"&&typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"}function me(){return navigator.connection?.saveData===!0}function ve(e){let n=window;if(typeof n.requestIdleCallback=="function"){let s=n.requestIdleCallback(e,{timeout:le});return()=>n.cancelIdleCallback?.(s)}let r=setTimeout(e,fe);return()=>clearTimeout(r)}function ge(e,n){let r,s=new Promise(i=>{r=i}),m=!1,d=()=>{},u={promise:s,settle:i=>{m||(m=!0,d(),e.scheduled===u&&(e.scheduled=null),r(i))}};return e.scheduled=u,d=ve(()=>{m||u.settle(I(e,n))}),s}function I(e,n){if((e.status==="loading"||e.status==="ready")&&e.promise!==null)return e.promise;A(e,"loading");let r=new Promise(i=>i(F(n)));e.detectorPromise=r;let s,m=new Promise((i,f)=>{s=setTimeout(()=>{r.then(h=>h.destroy(),()=>{}),f(new Error(`detector preload exceeded ${re} ms`))},re)}),u=Promise.race([r,m]).then(i=>e.detectorPromise!==r?(i.destroy(),e.status):(e.detector=i,A(e,"ready"),"ready"),i=>(e.detectorPromise===r&&(e.detectorPromise=null,e.detector=null,A(e,"failed"),console.warn("[@sekyro/web] face-detector preload failed:",i)),e.status)).finally(()=>clearTimeout(s));return e.promise=u,e.scheduled?.settle(u),u}function we(e={}){if(!pe())return Promise.resolve("idle");let n=S(e.assetBaseUrl),r=se(n);return e.respectSaveData===!0&&me()?Promise.resolve(r.status):(r.status==="loading"||r.status==="ready")&&r.promise!==null?r.promise:e.idle===!0?r.scheduled?.promise??ge(r,n):I(r,n)}function ke(e){return g().get(S(e))?.status??"idle"}function De(e,n){let r=se(S(n));return r.listeners.add(e),()=>{r.listeners.delete(e)}}function _e(e){let n=g().get(S(e));n!==void 0&&(n.scheduled?.settle("idle"),n.detector?.destroy(),n.detector=null,n.detectorPromise=null,n.promise=null,A(n,"idle"))}function he(e){return{get tier(){return e.tier},get fallbackReason(){return e.fallbackReason},detect:(...n)=>e.detect(...n),destroy:()=>{}}}function oe(e){let n=S(e),r=g().get(n);if(!(r===void 0||r.detector===null&&r.detectorPromise===null&&r.scheduled===null))return async()=>{r.scheduled!==null&&I(r,n);let s=r.promise;for(;r.detector===null&&s!==null&&(await s,r.promise!==s);)s=r.promise;return r.detector!==null?he(r.detector):C({v3AssetBaseUrl:n})}}function Ce(e){switch(e){case"fcv3.no_face":case"fcv3.center_face":case"fcv3.straighten":return"center";case"fcv3.come_closer":return"closer";case"fcv3.move_back":return"farther";case"fcv3.more_light":case"fcv3.too_bright":return"light";case"fcv3.hold_still":case"fcv3.steady_camera":return"still";case"fcv3.hold_upright":return"upright";case"fcv3.one_face":return"one_face";default:return null}}function Se(e){switch(e){case"preflight":case"acquiring":return"starting";case"positioning":return"gating";default:return e}}function ie(e){switch(e){case"permission":case"notfound":case"inuse":case"insecure":case"unsupported":return e;case"backcamera":return"notfound";default:{let n=e;return"generic"}}}function Le(e,n,r){if(r===void 0)return{kind:ie(e),retryable:n};let s=Z(r.name);return{kind:ie(e),retryable:n,detail:{...s!==void 0?{name:s}:{},phase:r.phase,engineKind:e}}}var ye=new Set(["captured","uploading","checking"]);function Ee(e,n={},r,s=()=>"self",m=()=>{},d){let u=n.now??(()=>performance.now()),i=n.canChooseFacing??ee,f="user",h=te(),p=s(),l=Y(),B=!Q(),H=n.engineOptions,ae=H?.createDetector===void 0&&H?.createWorker===void 0?{createDetector:()=>{let t=oe(e.assetBaseUrl);return t!==void 0?t():C({v3AssetBaseUrl:e.assetBaseUrl})}}:{},U={video:e.video,mode:B?"photo":"clip",rankKeyframes:r,facingMode:void 0,v3AssetBaseUrl:e.assetBaseUrl,screenRamp:()=>p==="self"&&l.count("ramp")>0?m():void 0,...n.engineOptions??{},...ae},o=n.createEngine?.(U)??new X(U),v="idle",L=null,y=0,w=!1,k="full",E=null,b=null,D=0,_=0,K=()=>{e.video.videoWidth>0&&e.video.videoHeight>0&&(D=e.video.videoWidth,_=e.video.videoHeight)},V=ne({enabled:e.keepScreenAwake!==!1}),M=t=>{v=t,V.setActive(t==="starting"||t==="gating"||t==="recording"),l.emit("state",t)},R=()=>l.emit("gate",{progress:y,hint:L,faceDetected:w}),G=()=>{let t=o.animations??"full";t!==k&&(k=t,l.emit("profile",{animations:k}))},de=[o.on("statechange",({state:t})=>{let a=Se(t);a==="starting"&&v!=="starting"&&(L=null,y=0,w=!1,E=null,b=null,D=0,_=0),M(a),G(),a==="recording"&&(K(),E=u(),L="hold",y=1,R())}),o.on("checks",t=>{K(),y=t.progress,w=t.factors.presence>0,R(),G()}),o.on("guidance",({key:t})=>{L=Ce(t),R()}),o.on("frozen",({previewDataUrl:t})=>{b=u(),l.emit("frozen",{previewDataUrl:t})}),o.on("ramp",t=>l.emit("ramp",t)),o.on("artifacts",t=>{if(v!=="captured")return;let a=$(),c=t.clipStats,q=c!==void 0?Math.round(c.durationMs):E!==null&&b!==null?Math.max(0,Math.round(b-E)):void 0,N=c!==void 0&&c.frames>1&&c.durationMs>0?Math.round(c.frames*1e4/c.durationMs)/10:void 0;l.emit("captured",{keyframe:t.keyframe,...t.clip!==void 0?{clip:t.clip}:{},...t.clipMimeType!==void 0?{clipMime:t.clipMimeType}:{},width:e.video.videoWidth||D,height:e.video.videoHeight||_,...q!==void 0?{clipMs:q}:{},...c!==void 0?{clipFrames:c.frames}:{},...N!==void 0?{fps:N}:{},...t.clipRetakes!==void 0?{clipRetakes:t.clipRetakes}:{},...t.clipMimeType!==void 0?{codec:j(t.clipMimeType)}:{},captureChannel:a==="desktop"?"desktop":"mobile",formFactor:a,...B?{degraded:"NO_RECORDER"}:{},engine:"v3",facingMode:o.facingMode,mode:p,...t.timing,...t.screenRamp!==void 0?{screenRamp:t.screenRamp}:{},...t.provenance!==void 0?{provenance:t.provenance}:{}})}),o.on("error",({kind:t,retryable:a,detail:c})=>{t==="backcamera"&&ce()||l.emit("error",Le(t,a,c))})],z=!1;function ce(){return T||z||p!=="assisted"||d===void 0||d.session()!=="choice"?!1:(z=!0,d.onModeChange("self"),p="self",f=O("self"),M("mode_switch"),o.restart(f),!0)}let W=async()=>d!==void 0&&d.session()==="choice"&&await i().catch(()=>!1),T=!1;return{handle:{get state(){return v},get captureMode(){return s()},get facingMode(){return o.facingMode??f},on:(t,a)=>l.on(t,a),start:t=>(p=s(),h.facing(p,e.facing),f=h.facing(p,t?.facing),o.start({facingMode:f})),retry:()=>o.retry(),switchCamera:()=>h.refuseSwitch(s()),canSwitchCaptureMode:W,setCaptureMode:async t=>{if(t===s()||!await W()||T||ye.has(v)||d===void 0)return!1;d.onModeChange(t),p=t;let a=O(t);return f=a,v==="idle"||(M("mode_switch"),o.restart(a)),!0},destroy:()=>{T=!0;for(let t of de)t();V.setActive(!1),o.destroy(),l.clear()}},setFlowState:t=>{v!==t&&M(t)}}}function ze(e){return Ee(e).handle}export{ue as a,re as b,Pe as c,Ae as d,we as e,ke as f,De as g,_e as h,oe as i,Ce as j,Se as k,ie as l,Le as m,Ee as n,ze as o};
@@ -0,0 +1 @@
1
+ import{A as Fe,B as Be,a as Te,b as Ve,c as De,d as L,e as W,f as j,g as Ne,h as V,i as He,j as R,k as D,l as O,m as se,n as E,o as U,p as F,q as Z,r as Le,s as Ue}from"./chunk-6RJTKX5I.js";import{n as we}from"./chunk-NHXLIDQJ.js";import{a as Me}from"./chunk-CPK5FYNJ.js";import{c as re,g as Ee,h as $}from"./chunk-ZGDUIZC2.js";import{c as Ie,d as ie}from"./chunk-CDDYFUER.js";function J(e){return e.idNumberBound??e.nniBound}function B(e){return e===void 0?void 0:e.idNumberFromDocument??e.nniFromDocument}function Ge(e){let t=e.idNumberMasked??e.nniMasked;return typeof t=="string"&&t!==""?t:void 0}var ht="https://api.sekyro.ai",St=5e3,yt=24e4,gt=3e4,_t=1500,Ct=10;function kt(e){return new Promise(t=>setTimeout(t,e))}function Pt(){let e=globalThis.crypto;if(e!==void 0&&typeof e.randomUUID=="function")return e.randomUUID();let t=new Uint8Array(16);if(e!==void 0&&typeof e.getRandomValues=="function")e.getRandomValues(t);else for(let r=0;r<16;r+=1)t[r]=Math.floor(Math.random()*256);t[6]=(t[6]??0)&15|64,t[8]=(t[8]??0)&63|128;let o=[...t].map(r=>r.toString(16).padStart(2,"0")).join("");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}function hn(e){return bt(e,{})}function bt(e,t){let o=e.apiOrigin??ht,r=e.autoRetry??!0,i=e.rearm??"auto",s=t.client??new Ee({apiOrigin:o,sessionToken:e.clientToken,fetch:e.fetch}),u=t.sleep??kt,c=t.uuid??Pt,p=t.getTurnstileToken??((n,a)=>import("./turnstile-MX6YN4YH.js").then(l=>l.executeTurnstile(n,a))),m=Me(),S=null,x=null,d=!1,_=new AbortController,f=null,M=null,G=null,K=()=>G??Le(f),pe=()=>Ue(Z(f),K()),v=n=>{f=n,m.emit("view",n),S?.onView(n)},C=()=>f!==null?Promise.resolve(f):(M??(M=s.getSession().then(n=>(v(n),n)).finally(()=>{M=null})),M),A=async()=>{let n=await s.getSession();return v(n),n},Q=async(n,a)=>{n.plan!==void 0?v(n):await A()},X=null,fe=async n=>{let a=await C();if(n||!a.consentRecorded){let l=await s.recordConsent(e.locale);l.plan!==void 0?v(l):f!==null&&v({...f,consentRecorded:!0})}Re(a.turnstileSiteKey)},w=n=>n?.force===!0?fe(!0):(X??(X=fe(!1).finally(()=>{X=null})),X),z={client:s,ensureConsent:n=>w(n),sleep:u,uuid:c,...t.random!==void 0?{random:t.random}:{},onBusy:n=>{d||m.emit("busy",n)}},me=!1,he=null,ee=n=>{if(n.status==="verified"||n.status==="not_verified"||n.status==="review"){if(me)return;me=!0}he=JSON.stringify(n),m.emit("result",n)},tt=n=>{he!==JSON.stringify(n)&&ee(n)},Se=async n=>{let a=f;n&&(a=await A().catch(()=>f));let l=a===null?null:V(a);return l!==null&&!d&&m.emit("method",l),l!==null},ye=null,ge=!1,_e=!1,Ce=()=>Fe(z,(n,a)=>n.submitCheck("population_registry",{},{idempotencyKey:a})),ke=n=>J(n)===!0||B(O(n,"population_registry"))===!0,nt=async()=>{try{let n=await C();if(R(n)||V(n)!==null||D(n)?.checkType!=="population_registry")return;if(!ke(n)&&B(O(n,"population_registry"))===void 0&&(n=await A()),!ke(n)){_e=!0;return}await w(),await Q(await Ce(),"population_registry");let a=f===null?void 0:O(f,"population_registry");if(a?.state==="input_required"&&a.reason==="registry_unavailable"&&j(a)>0){if(await u(St),d)return;await Q(await Ce(),"population_registry")}}catch(n){if(n instanceof re&&(n.code==="check_not_active"||n.code==="step_not_on_path")){await A().catch(()=>{});return}ge=!0;return}f!==null&&R(f)&&ee(U(f,{autoRetry:r}))},Pe=()=>(ye??(ye=nt()),ye),te=t.now??Date.now,T=null,ne=n=>p(n,{signal:_.signal}),be=(n,a)=>n!==null&&n.siteKey===a&&te()-n.at<yt,Re=n=>{if(n===null||d||be(T,n))return;let a=ne(n);a.catch(()=>{}),T={siteKey:n,at:te(),token:a}},ot=async n=>{let a=T;T=null;let l=be(a,n),g=l?a.at:te(),h=l?a.token.catch(()=>ne(n)):ne(n);h.catch(()=>{});let b,Y=new Promise(P=>{b=setTimeout(()=>P("late"),gt)});try{let P=await Promise.race([h.then(y=>({value:y}),()=>null),Y]);return P==="late"?(!d&&T===null&&(T={siteKey:n,at:g,token:h}),null):P===null?null:P.value}finally{clearTimeout(b)}},it=async()=>{let a=(await C()).turnstileSiteKey;if(a===null)return{sandbox:!0};let l=await ot(a);return l===null?{channel:"hosted_web",siteKey:a}:{channel:"hosted_web",siteKey:a,turnstileToken:l}},q=n=>{if(d)return;let a=s.reportCaptureIssue;if(a===void 0)return;let l=n.formFactor;try{l??(l=Ie())}catch{}try{Promise.resolve(a.call(s,{...n,...l!==void 0?{formFactor:l}:{}})).catch(()=>{})}catch{}},k=null,xe=Promise.resolve(),H=0,rt=async()=>{let n=await C();for(let a=0;a<Ct&&!d&&!R(n)&&D(n)===void 0&&W(n).some(l=>l.state==="processing")&&(await u(_t),!d);a+=1)n=await A();return n},st=async(n,a,l)=>{let{capture:g}=n,h=()=>d,b=()=>n.alive&&n.attempt===l,Y=y=>{b()&&g.setFlowState(y)},P=y=>{if(!h()&&(y.status==="unavailable"&&y.reasonCode!==void 0&&!Te(y.reasonCode)&&q({check:"liveness",kind:"unavailable",phase:"upload",engineKind:y.reasonCode,attempt:Math.max(0,n.issues.value)}),ee(y),!!b())){if(y.status==="retry"&&i==="auto"){g.handle.retry();return}g.setFlowState("done")}};if(a.degraded==="NO_RECORDER"){let y=f?.sessionId??(await C().catch(()=>null))?.sessionId??"";P(E(y,"no_recorder"));return}Y("uploading");try{if(await Pe(),h())return;let y=await C(),Ae;if(!R(y)&&V(y)!==null){await Se(!1),P(E(y.sessionId,"method_required"));return}if(!R(y)){if(D(y)?.checkType==="population_registry"){P(E(y.sessionId,_e?"nni_unbound":ge?"network":"registry_unavailable"));return}if(await w(),h())return;Ae=f??y;let oe=await Be({...z,artifacts:a,getAttestation:it,getView:()=>f??y,refreshView:A,applySubmit:Q,onPhase:Y,isCancelled:h,onKeyframePromoted:mt=>{x=mt}});if(h())return;if(oe.kind==="unavailable"){P(E(y.sessionId,oe.reason));return}if(oe.kind==="resync"&&await A(),f!==null&&V(f)!==null){await Se(!1),P(E(y.sessionId,"method_required"));return}y=await rt()}P(U(y,{autoRetry:r,previous:Ae}))}catch{if(h())return;P(E(f?.sessionId??"","network"))}},at=(n,a)=>{let l=n.attempt;H>0&&n.alive&&n.capture.setFlowState("uploading"),H+=1,xe=xe.then(()=>st(n,a,l)).finally(()=>{H-=1,H===0&&S?.onChainIdle()}).catch(()=>{})},Oe=n=>{k?.capture.handle.destroy(),k!==null&&(k.alive=!1);let a=we(n,S?.captureInternals?.(n)??t.capture,()=>f?.capture?.liveness?.keyframe?.rank===!0,pe,()=>f?.capture?.liveness?.screenRamp,{session:()=>Z(f),onModeChange:h=>{G=h}}),l={capture:a,alive:!0,attempt:0,issues:De()};k=l,a.handle.on("error",h=>{q(Ve("liveness",h,l.issues.value))}),a.handle.on("state",h=>{if(l.issues.note(h),h==="starting"){l.attempt+=1,Re(f?.turnstileSiteKey??null);let b=f===null?void 0:D(f)?.checkType;(b==="liveness"||b==="face_match")&&w().catch(()=>{})}}),a.handle.on("captured",h=>{Promise.resolve().then(()=>at(l,h))});let g=a.handle;return{get state(){return g.state},get captureMode(){return g.captureMode},get facingMode(){return g.facingMode},on:(h,b)=>g.on(h,b),start:async h=>{if(f===null&&await C().catch(()=>{}),!!l.alive)return g.start(h)},retry:()=>g.retry(),switchCamera:()=>g.switchCamera(),canSwitchCaptureMode:()=>g.canSwitchCaptureMode(),setCaptureMode:h=>g.setCaptureMode(h),destroy:()=>{l.alive=!1,k===l&&(k=null),g.destroy()}}},ct=async()=>{if(d)return null;try{let n=await C();return d?null:V(n)}catch{return null}},ut=async()=>{if(d)return"self";try{let n=await C();if(d)return"self";let a=Z(n);return a==="choice"?K()??a:a}catch{return"self"}},dt=async()=>{if(d)return!1;try{let n=await C();return d||R(n)||ie()?!1:F(n,D(n))==="phone"||F(n,O(n,"liveness"))==="phone"}catch{return!1}},lt=async()=>{if(d)return!1;try{let n=await C();return!d&&n.returning===!0}catch{return!1}},pt=async n=>{let a=(await C()).plan?.choice,l=a?.options.find(h=>L[h.service]===n);if(!l)throw new RangeError(`method ${String(n)} is not offered`);let g=await s.choose(a.nodeId,l.id);d||v(g)},ve=null,ft=()=>(ve??(ve=import("./plan-runner-5UZYQ2XH.js").then(n=>{let a=n.createPlanRunner({runtime:z,currentView:()=>f,cameraMode:pe,captureModeSwitch:{pick:K,choose:l=>{G=l}},ensureView:C,refreshView:A,ensureConsent:()=>w(),liveness:Oe,stopLiveness:()=>{k!==null&&(k.alive=!1,k.capture.handle.destroy(),k=null)},chainBusy:()=>H>0,destroyed:()=>d,sleep:u,isMobile:ie,now:t.now??Date.now,keptFaceKey:()=>x,setView:v,baseCapture:t.capture,emitStep:l=>{d||m.emit("step",l)},emitResult:tt,reportCaptureIssue:q,documentInternals:t.document,portraitInternals:t.portrait,livePhotoInternals:t.livePhoto,uploadInternals:t.upload});return S=a,a})),ve);return{consent:()=>w(),startRegistry:Pe,methodChoice:ct,selectMethod:pt,reportCameraUnavailable:async n=>{await w();let a=s.reportCameraUnavailable;if(a===void 0)throw new TypeError("this client cannot report a missing camera");let l=await a.call(s,n).catch(g=>{if(g instanceof re&&g.code==="check_out_of_order")return s.getSession();throw g});d||v(l)},reportCaptureIssue:q,mobileRequired:dt,captureMode:ut,chooseCaptureMode:n=>{G=n},get captureChoice(){return K()},returning:lt,liveness:Oe,run:async()=>{if(d)throw new Error("verification destroyed");return(await ft()).run()},currentStep:()=>S?.current()??null,voiceClips:async()=>{if(d)return null;try{let n=await C();return d?null:n.voice??null}catch{return null}},on:(n,a)=>m.on(n,a),destroy:()=>{d=!0,_.abort(),S?.destroy(),k!==null&&(k.alive=!1,k.capture.handle.destroy(),k=null),m.clear()}}}var Ke=["AD","AE","AF","AG","AI","AL","AM","AO","AQ","AR","AS","AT","AU","AW","AX","AZ","BA","BB","BD","BE","BF","BG","BH","BI","BJ","BL","BM","BN","BO","BQ","BR","BS","BT","BV","BW","BY","BZ","CA","CC","CD","CF","CG","CH","CI","CK","CL","CM","CN","CO","CR","CU","CV","CW","CX","CY","CZ","DE","DJ","DK","DM","DO","DZ","EC","EE","EG","EH","ER","ES","ET","FI","FJ","FK","FM","FO","FR","GA","GB","GD","GE","GF","GG","GH","GI","GL","GM","GN","GP","GQ","GR","GS","GT","GU","GW","GY","HK","HM","HN","HR","HT","HU","ID","IE","IL","IM","IN","IO","IQ","IR","IS","IT","JE","JM","JO","JP","KE","KG","KH","KI","KM","KN","KP","KR","KW","KY","KZ","LA","LB","LC","LI","LK","LR","LS","LT","LU","LV","LY","MA","MC","MD","ME","MF","MG","MH","MK","ML","MM","MN","MO","MP","MQ","MR","MS","MT","MU","MV","MW","MX","MY","MZ","NA","NC","NE","NF","NG","NI","NL","NO","NP","NR","NU","NZ","OM","PA","PE","PF","PG","PH","PK","PL","PM","PN","PR","PS","PT","PW","PY","QA","RE","RO","RS","RU","RW","SA","SB","SC","SD","SE","SG","SH","SI","SJ","SK","SL","SM","SN","SO","SR","SS","ST","SV","SX","SY","SZ","TC","TD","TF","TG","TH","TJ","TK","TL","TM","TN","TO","TR","TT","TV","TW","TZ","UA","UG","UM","US","UY","UZ","VA","VC","VE","VG","VI","VN","VU","WF","WS","XK","YE","YT","ZA","ZM","ZW"];var Rt=["carte_identite","passport","residence_permit"];function xt(e,t){let o=e.byIssuer?.[t]??e.default;return Rt.filter(r=>o==="*"||o.includes(r))}function _n(e,t=Ke){return[...new Set([...t,...Object.keys(e.byIssuer??{})])].filter(r=>xt(e,r).length>0).sort()}function qe(e){if(e.acceptedDocuments)return e.acceptedDocuments;let t=e.acceptedDocumentTypes?.length?[...e.acceptedDocumentTypes]:["carte_identite","passport"];return{default:[],byIssuer:{MR:t}}}function Cn(e){return/^[A-Z]{2}$/.test(e)?String.fromCodePoint(...[...e].map(t=>127462+t.charCodeAt(0)-65)):""}var Ye=Object.freeze({nni_invalid:"id_number_invalid",nni_not_found:"registry_record_not_found",nni_recheck:"id_number_recheck",document_nni_mismatch:"document_id_number_mismatch",nni_locked:"id_number_locked",nni_unbound:"id_number_unbound",sandbox_nni_not_seeded:"sandbox_id_number_not_seeded",missing_nni:"missing_id_number",registry_needs_nni_source:"registry_needs_id_number_source"}),Ot=new Map(Object.entries(Ye)),Pn=new Map(Object.entries(Ye).map(([e,t])=>[t,e]));function We(e){return Ot.get(e)??e}var Mn=["national_number","document_photo","national_eid"],vt=new Set(["phone_otp","email_otp","national_eid","document","nfc","population_registry","supplied_identity","summary_confirm","liveness","portrait","face_match","aml_screening","face_dedup","age_estimation"]),At=new Set(["supplied_identity","aml_screening","face_dedup","age_estimation"]),ce=["document","population_registry","national_eid"],ue=["phone_otp","email_otp"],$e={identity_method:ce,contact:ue},It=["population_registry","document"],de="platform_unsupported",Mt=new Set(["prefilled","user_entered","prefilled_or_entered"]),wt={phone_otp:"contact",email_otp:"contact",eid_auth:"identity",doc_ocr:"identity",nfc_chip:"identity",population_registry:"identity",liveness:"live_photo",portrait_icao:"live_photo",face_match:"live_photo"};function I(e){return e.section??wt[e.checkType]??null}function Et(e,t){let o=e.plan?.choice;if(o===void 0||o.locked)return;let r=o.options.find(i=>i.id!==o.selected&&i.available!==!1&&t.includes(i.service));return r===void 0?void 0:{nodeId:o.nodeId,option:r}}function le(e){let t=e.plan,o=t?.choice;if(t===void 0||o===void 0||o.locked||t.current===null||t.current===o.nodeId||R(e))return null;let r=$e[o.kind]??[...ce,...ue],i=o.options.flatMap(c=>c.available===!1||!r.includes(c.service)?[]:[c.nationalEid!=null?{id:c.id,service:c.service,nationalEid:c.nationalEid}:{id:c.id,service:c.service}]),s=t.steps.find(c=>c.id===t.current)?.service,u=o.selected??i.find(c=>c.service===s)?.id??null;return i.some(c=>c.id!==u)?{nodeId:o.nodeId,kind:o.kind,current:u,options:i}:null}function Je(e){return e==null?[]:e.options.filter(t=>t.id!==e.current)}function Tt(e){let t=e.simulation;if(typeof t!="object"||t===null)return;let{otpCode:o,skipCapture:r}=t;return typeof o=="string"&&o!==""&&typeof r=="boolean"?{otpCode:o,skipCapture:r}:void 0}function Vt(e){let t=(e.plan?.sections??[]).map(s=>({id:s.id,state:s.state})),o={sessionId:se(e.sessionId),orgName:e.orgName,returning:e.returning===!0,consentRecorded:e.consentRecorded,expiresAt:e.expiresAt,sections:t.map(s=>s.id),progress:t,purpose:e.purpose??"identity"};e.branding!==void 0&&(o.branding=e.branding),e.cameraUnavailableHandled===!0&&(o.cameraUnavailableHandled=!0);let r=Tt(e);r!==void 0&&(o.simulation=r);let i=le(e);return i!==null&&(o.switchable=i),o}function Dt(e){let t={attemptsRemaining:j(e),attemptsExhausted:e.attempts.used>=e.attempts.max};return e.reason!==void 0&&(t.reason=e.reason),e.retakeHint!==void 0&&(t.retakeHint=e.retakeHint),t}var Qe={phone_otp:"phone",email_otp:"email"};function Nt(e,t){let o=Et(e,[t==="phone_otp"?"email_otp":"phone_otp"]);return o===void 0?void 0:Qe[o.option.service]}function Ht(e,t,o,r){let i=t.checkType==="email_otp",s=(i?t.emailOtp:t.otp)??{},u=i?t.emailOtp?.emailSource:t.otp?.numberSource,c=u!==void 0&&Mt.has(u)?u:i?"prefilled_or_entered":"user_entered",p=typeof s.sentToMasked=="string"&&s.sentToMasked.length>0,m=s.prefilled===!0,S=Nt(e,i?"email_otp":"phone_otp"),x={key:t.checkType,context:o,section:I(t),phase:p?"verify":"send",canSwitch:S!==void 0,...r},d=i?{kind:"email_otp",...x,emailSource:c,needsEmail:c!=="prefilled"&&!m}:{kind:"phone_otp",...x,numberSource:c,needsPhone:c!=="prefilled"&&!m,channels:(t.otp?.channels??[]).filter(_=>_==="whatsapp"||_==="sms")};if(S!==void 0&&(d.switchChannel=S),m&&(d.prefilled=!0),p&&(d.sentToMasked=s.sentToMasked),!i&&t.otp?.channel!==void 0&&(d.channel=t.otp.channel),!i&&Array.isArray(t.phoneCountries)&&(d.phoneCountries=t.phoneCountries.filter(_=>typeof _=="string"&&/^[A-Z]{2}$/.test(_))),!i&&Array.isArray(t.phoneRules)){let _=d.phoneCountries??[];d.phoneRules=t.phoneRules.flatMap(f=>{let M=Ft(f);return M!==void 0&&_.includes(M.code)?[M]:[]})}return!i&&t.phoneInternational===!0&&(d.phoneInternational=!0),s.expiresAt!==void 0&&(d.codeExpiresAt=s.expiresAt),s.resendAvailableAt!==void 0&&(d.resendAvailableAt=s.resendAvailableAt),d}var Lt=/^[\d[\]\-|()?:^]{1,64}$/;function Ut(e){try{return typeof e=="string"&&Lt.test(e)&&new RegExp(e)!==null}catch{return!1}}var je=e=>typeof e=="number"&&Number.isInteger(e)&&e>=1&&e<=15;function Ft(e){let{code:t,dial:o,trunk:r,lengths:i,formats:s}=e??{};if(typeof t!="string"||typeof o!="string"||!/^\d{1,3}$/.test(o)||r!==void 0&&(typeof r!="string"||!/^\d{1,3}$/.test(r))||!Array.isArray(i)||i.length===0||!i.every(je))return;let u={code:t,dial:o,lengths:[...i].sort((c,p)=>c-p)};if(r!==void 0&&(u.trunk=r),s!==void 0){if(!(Array.isArray(s)&&s.length<=8&&s.every(p=>Ut(p?.leading)&&Array.isArray(p.groups)&&p.groups.every(je)&&i.includes(p.groups.reduce((m,S)=>m+S,0)))))return;u.formats=s.map(p=>({leading:p.leading,groups:[...p.groups]}))}return u}function Bt(e,t,o,r){let i=J(e)===!0?"bound":B(t)===!0?"document":"typed",s=i==="typed"&&t.state==="input_required"&&t.reason!==void 0&&We(t.reason)==="id_number_recheck",u=Je(le(e)),c=!r.attemptsExhausted&&u.length===1&&u[0]?.service==="document";return{kind:"registry",key:"registry",context:o,section:I(t),state:t.state==="input_required"?"input_required":"pending",source:i,recheck:s,canUseDocument:c,...r}}function Gt(e,t,o,r,i){let s=[...t.acceptedSides??[]],u={kind:"document",key:"document",context:o,section:I(t),side:s.includes("recto")?"verso":"recto",acceptedSides:s,documents:qe(e),photo:ze(Xe(e.documents),i),...r};return e.detectedCountry!==void 0&&(u.detectedCountry=e.detectedCountry),Kt(e)&&(u.ageStepUp=!0),u}function Xe(e,t=!0){let o=e?.source==="upload"||e?.source==="choice"?e.source:"camera",r=e?.sourcePick==="camera"||e?.sourcePick==="upload"?e.sourcePick:null;return{source:o,pick:r,uploadOffered:t&&e?.uploadOffered===!0}}function ze(e,t){return t?{...e,cameraOnPhone:!0}:e}function Kt(e){let t=W(e).find(r=>r.checkType==="age_estimation"),o=t?.reason;return t?.state==="failed"&&(o==="age_uncertain"||o==="age_unavailable")}function qt(e){let t=O(e,"liveness");return t?.state==="passed"||t?.state==="review"}function Ze(e,t,o,r,i,s=!1){let u=t.icao?.report,c=e.portrait,p=i==="capture"?c?.pendingFix??null:null;p!==null&&(i="review");let m=et(e);return{kind:"portrait",key:`portrait:${i}`,context:o,section:I(t),phase:i,report:Array.isArray(u)?u:null,review:t.state==="review",tuning:e.capture?.icao??null,tuningVersion:e.capture?.tuningVersion??null,icao:$(e),retakeOnly:i==="capture"&&t.state==="input_required"&&m===void 0&&e.capture?.livePhoto?.oneCapture===!0&&qt(e),photo:ze(Xe(c,i==="capture"),s&&i==="capture"),pendingFix:p,...m!==void 0?{captureMode:m}:{},...c?.reuse?.pending===!0?{reuse:!0}:{},...r}}function et(e){let t=e.portrait?.captureMode;return t==="self"||t==="assisted"||t==="choice"?t:void 0}var ae={minLongSidePx:1280,jpegQuality:.95};function Yt(e,t){let o=e.capture?.livePhoto;if(o?.oneCapture!==!0)return null;let r=O(e,"portrait_icao"),i=o.still??ae;return{icao:t==="liveness"&&$(e)!==null&&et(e)===void 0&&r!==void 0&&r.state==="pending"&&r.reason===void 0,still:{minLongSidePx:i.minLongSidePx??ae.minLongSidePx,jpegQuality:i.jpegQuality??ae.jpegQuality}}}function Wt(e,t,o,r){let i=t.eid,s=I(t);if(i===void 0||i.challenge!=="app_code")return{kind:"unsupported",key:"unsupported:eid_auth",context:o,section:s,checkType:"eid_auth",reason:"update_required"};let u=Je(le(e)),c=u.length===1&&It.includes(u[0]?.service??"")?u[0]:void 0,p=c===void 0?void 0:L[c.service],m=p!==void 0,S={kind:"eid",key:"eid",context:o,section:s,provider:i.provider,providerName:i.providerName,country:i.country,challenge:"app_code",phase:i.awaiting==="code"?"code":"identifier",identifierBound:i.identifierBound===!0,canUseCamera:m,afterPass:i.afterPass==="continue"?"continue":"end",...r};return m&&(S.cameraMethod=p),i.expiresAt!==void 0&&(S.codeExpiresAt=i.expiresAt),i.resendAvailableAt!==void 0&&(S.resendAvailableAt=i.resendAvailableAt),i.resendsRemaining!==void 0&&(S.resendsRemaining=i.resendsRemaining),i.codeAttemptsRemaining!==void 0&&(S.codeAttemptsRemaining=i.codeAttemptsRemaining),S}function jt(e,t){if(t.checkType!=="face_match"||t.reason!==void 0)return null;let o=O(e,"portrait_icao");return o!==void 0&&(o.state==="passed"||o.state==="review")?o:null}var Zt={rejected:"rejected",inconclusive:"inconclusive",unavailable:"unavailable",abandoned:"expired",not_opened:"expired",cancelled:"expired",superseded:"expired",policy:"policy"};function $t(e){return e.reasonCode===de?"platform_unsupported":e.status==="review_pending"?"review":e.status==="verified"?"verified":e.reasonCode==="device_cooldown"?"cooldown":e.reasonCode==="starter_credit_claimed"?"policy":(e.status==="not_verified"&&e.reason!==void 0?Zt[e.reason]:void 0)??"rejected"}function Jt(e,t){let o=$t(e),r=o==="platform_unsupported"?{sessionId:se(e.sessionId),status:"unavailable",reasonCode:de}:U(e,{autoRetry:!1}),i={kind:"result",key:"result",context:t,section:null,display:o,result:r};return e.status==="not_verified"&&e.reason!==void 0&&(i.reason=e.reason),e.reasonCode!==void 0&&(i.reasonCode=e.reasonCode),e.status==="not_verified"&&e.step!==void 0&&(i.step=e.step),e.retryAfter!==void 0&&(i.retryAfter=e.retryAfter),i}function Qt(e,t,o){let r=e.identitySummary;if(r==null)return null;let i={kind:"identity_summary",key:"identity_summary",context:t,section:o??"identity",summaryKind:r.kind==="partial"?"partial":r.kind??"full",source:r.source,portraitAvailable:r.portrait?.available===!0,retakeAvailable:r.retakeAvailable===!0};for(let u of Xt){let c=r[u];typeof c=="string"&&c!==""&&(i[u]=c)}let s=Ge(r);return s!==void 0&&(i.idNumberMasked=s,i.nniMasked=s),i}var Xt=["fullName","birthDate","birthYear","nationality","documentType","documentNumberMasked","expiryDate","retakeTarget"];function N(e,t,o,r){return{kind:"unsupported",key:`unsupported:${o}`,context:e,section:t,checkType:o,reason:r}}function zt(e){return e.kind==="contact"?"contact":(e.kind==="identity_method","identity")}function en(e,t){let o=$e[e.kind]??[...ce,...ue],r=zt(e),i=e.options.flatMap(u=>{if(u.available===!1||!o.includes(u.service))return[];let c={id:u.id,service:u.service};u.nationalEid!=null&&(c.nationalEid=u.nationalEid);let p=(u.channels??[]).filter(m=>m==="whatsapp"||m==="sms");return u.service==="phone_otp"&&p.length>0&&(c.channels=p),[c]});if(i.length===0){let u=e.options.length>0&&e.options.every(c=>c.service==="nfc");return N(t,r,"choice",u?"platform_unsupported":"update_required")}let s={nodeId:e.nodeId,kind:e.kind,selected:e.selected,options:i};if(e.kind==="identity_method"){let u={kind:"method",key:"method",context:t,section:r,options:i.map(p=>L[p.service]),choice:s},c=i.find(p=>p.nationalEid!==void 0)?.nationalEid;return c!==void 0&&(u.nationalEid=c),u}return e.kind==="contact"?{kind:"contact_choice",key:"contact_choice",context:t,section:r,options:i.map(u=>Qe[u.service]),selected:null,locked:!1,choice:s}:{kind:"choice",key:`choice:${e.nodeId}`,context:t,section:r,choice:s}}function wn(e,t={}){let o=Vt(e);if(R(e)||e.reasonCode===de)return Jt(e,o);let r=e.plan;if(r===void 0||!Array.isArray(r.sections))return N(o,null,"plan","update_required");let i=Ne(e);if(i!==null)return en(i,o);let s=r.current===null?void 0:r.steps.find(d=>d.id===r.current),u=d=>{let _={kind:"processing",key:"processing",context:o,section:d!==void 0?I(d):r.sections.find(f=>f.state==="current")?.id??null,stalled:!1};return typeof d?.service=="string"&&d.service!==""&&(_.service=d.service),_};if(r.current===null)return u(r.steps.find(d=>d.state==="processing"));if(s===void 0)return N(o,null,"step","update_required");if(!vt.has(s.service))return s.interaction==="server"?u(s):N(o,I(s),s.service,"update_required");if(At.has(s.service)||!He(s))return u(s);let c=s,p=Dt(c),m=c.checkType,S=I(c),x=t.isMobile===!1?F(e,c):null;if(x==="phone")return{kind:"mobile_required",key:"mobile_required",context:o,section:S,checkType:m};switch(m){case"phone_otp":case"email_otp":return Ht(e,c,o,p);case"population_registry":return Bt(e,c,o,p);case"eid_auth":return Wt(e,c,o,p);case"doc_ocr":return Gt(e,c,o,p,x==="upload_or_phone");case"identity_confirm":return Qt(e,o,S)??u(c);case"portrait_icao":return Ze(e,c,o,p,"capture",x==="upload_or_phone");case"liveness":case"face_match":{let d=jt(e,c);if(d!==null)return Ze(e,d,o,p,"match");let _=c.requiresMobile===!0,f=$(e);return{kind:"liveness",key:"biometric",context:o,section:S,mode:m==="face_match"?"selfie":"liveness",requiresMobile:_,instructions:f===null?"standard":"icao",icao:f,livePhoto:Yt(e,m),...p}}case"nfc_chip":return N(o,S,m,"platform_unsupported");default:return N(o,S,m,"update_required")}}export{ht as a,St as b,_t as c,Ct as d,Pt as e,hn as f,bt as g,Ke as h,Rt as i,xt as j,_n as k,qe as l,Cn as m,Mn as n,de as o,I as p,le as q,Je as r,jt as s,wn as t};
@@ -0,0 +1 @@
1
+ import{p as k,r as w}from"./chunk-7KXJEF7P.js";import{e as M}from"./chunk-CDDYFUER.js";var u=class extends Error{constructor(){super("the back camera could not be opened");this.name="BackCameraUnavailableError"}},S=new Set(["NotAllowedError","PermissionDeniedError","SecurityError"]);function h(r){try{return String(r?.name??"")}catch{return""}}function c(r){if(r!==null)for(let t of r.getTracks())t.stop()}async function C(r,t,n){let a=e=>({video:{...t,...e},audio:!1});if(r==="user")return n.getUserMedia(a({facingMode:"user"}));let o=e=>M(e)!=="user";try{let e=await n.getUserMedia(a({facingMode:{exact:"environment"}}));if(o(e))return e;c(e)}catch(e){if(S.has(h(e)))throw e}let d=!1,l=async()=>{if(n.enumerateDevices===void 0||d)return null;let e;try{e=w(await n.enumerateDevices()).slice(0,3)}catch{return null}d=e.length>0;for(let v of e){let i;try{i=await n.getUserMedia(a({deviceId:{exact:v}}))}catch(g){if(S.has(h(g)))throw g;continue}if(o(i))return i;c(i)}return null},m=await l();if(m!==null)return m;let s=await n.getUserMedia(a({facingMode:"environment"}));if(o(s))return s;c(s);let f=await l();if(f!==null)return f;throw new u}export{u as a,C as b};