@sekyro/web 0.1.0-rc.10 → 0.1.0-rc.12

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 (55) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/{capture-session-doc-GK6G7JOI.js → capture-session-doc-KW5VR4IR.js} +1 -1
  3. package/dist/{capture-session-v3-DGG2stO6.d.ts → capture-session-v3-DqUUcIU-.d.ts} +34 -3
  4. package/dist/{capture-session-v3-CmJw_bK0.d.cts → capture-session-v3-xNtY5m-7.d.cts} +34 -3
  5. package/dist/{chunk-BAGSM67V.js → chunk-4IVRXJR2.js} +1 -1
  6. package/dist/chunk-6DPFJNGL.js +1 -0
  7. package/dist/{chunk-SEC64KZ3.js → chunk-73M7LS4H.js} +1 -1
  8. package/dist/chunk-EF52BRBD.js +1 -0
  9. package/dist/chunk-GT2ZLGF7.js +1 -0
  10. package/dist/chunk-IF6YOFFO.js +1 -0
  11. package/dist/chunk-MUVEJRGK.js +1 -0
  12. package/dist/{chunk-UGMHAFEY.js → chunk-OBLQOE66.js} +1 -1
  13. package/dist/chunk-U6TYL2IJ.js +1 -0
  14. package/dist/{chunk-FFDB6LQN.js → chunk-U6YQAQBD.js} +1 -1
  15. package/dist/chunk-Y7S7LYCL.js +1 -0
  16. package/dist/chunk-YZH5PR5R.js +1 -0
  17. package/dist/client/index.cjs +1 -1
  18. package/dist/client/index.d.cts +5 -3
  19. package/dist/client/index.d.ts +5 -3
  20. package/dist/client/index.js +1 -1
  21. package/dist/core/index.cjs +1 -1
  22. package/dist/core/index.d.cts +3 -2
  23. package/dist/core/index.d.ts +3 -2
  24. package/dist/core/index.js +1 -1
  25. package/dist/{create-document-capture-IGUQP2NS.js → create-document-capture-PXOJHLWV.js} +1 -1
  26. package/dist/{create-portrait-capture-RJSFY37D.js → create-portrait-capture-C462EIB6.js} +1 -1
  27. package/dist/{create-verification-Bb20j6zk.d.ts → create-verification-CDOTGHQj.d.ts} +87 -9
  28. package/dist/{create-verification-CtqF4A9W.d.cts → create-verification-D4749F6L.d.cts} +87 -9
  29. package/dist/icao-gate-BRuIgOE2.d.cts +503 -0
  30. package/dist/icao-gate-CphntEQ2.d.ts +503 -0
  31. package/dist/index.cjs +1 -1
  32. package/dist/index.d.cts +16 -5
  33. package/dist/index.d.ts +16 -5
  34. package/dist/index.js +1 -1
  35. package/dist/internal/index.cjs +1 -1
  36. package/dist/internal/index.d.cts +17 -8
  37. package/dist/internal/index.d.ts +17 -8
  38. package/dist/internal/index.js +1 -1
  39. package/dist/{plan-runner-QCK2SOGS.js → plan-runner-2FJLUALJ.js} +1 -1
  40. package/dist/popup/index.cjs +1 -1
  41. package/dist/popup/index.d.cts +7 -1
  42. package/dist/popup/index.d.ts +7 -1
  43. package/dist/popup/index.js +1 -1
  44. package/dist/{icao-gate-terzKYD7.d.cts → types-4rgeNIlz.d.cts} +179 -498
  45. package/dist/{icao-gate-terzKYD7.d.ts → types-4rgeNIlz.d.ts} +179 -498
  46. package/package.json +1 -1
  47. package/sbom.cdx.json +7 -7
  48. package/dist/chunk-3MSUJYBO.js +0 -1
  49. package/dist/chunk-ETY6SAAZ.js +0 -1
  50. package/dist/chunk-HAO6EQTH.js +0 -1
  51. package/dist/chunk-HWAXEQD5.js +0 -1
  52. package/dist/chunk-SXZCL5NO.js +0 -1
  53. package/dist/chunk-SZ7YGNUZ.js +0 -1
  54. package/dist/chunk-WKJJEPWA.js +0 -1
  55. package/dist/chunk-XR64UFLK.js +0 -1
@@ -1 +1 @@
1
- import{b as jt}from"./chunk-SMKCBUJL.js";import{a as et,b as Zt,c as Jt,e as ht,f as $t}from"./chunk-MXWLCDFX.js";import{d as Wt,h as Xt,k as Yt}from"./chunk-G6LKLN4U.js";import{b as Kt,c as Vt}from"./chunk-TDLIXFDT.js";import{b as Qt,c as Bt}from"./chunk-POIQGEZM.js";import{d as zt}from"./chunk-FHJ7HO3M.js";import{b as ut,c as Ut,d as j,e as Ht}from"./chunk-FPXL63KZ.js";import{b as Nt}from"./chunk-BAGSM67V.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 qt(e){return e.framing==="no_document"?"sensing":e.framing==="too_far"?"too_far":e.framing==="too_close"?"too_close":e.framing==="edge_clipped"?"edge_clipped":e.framing==="wrong_shape"?"wrong_shape":e.framing==="tilted"?"tilted":e.lighting==="too_dark"?"too_dark":e.lighting==="too_bright"?"too_bright":e.glare==="glare"?"glare":e.blur==="blurry"?"blurry":"hold_still"}var nt=class{constructor(t=2600,n=.35){this.windowMs=t;this.decayPerSecond=n;this.votes=[];this.current=it.sensing;this.currentSinceMs=null}reset(){this.votes=[],this.current=it.sensing,this.currentSinceMs=null}force(t,n){return this.votes=[],this.current=it[t],this.currentSinceMs=n,this.current}tick(t,n){if(this.currentSinceMs===null&&(this.currentSinceMs=n),this.votes.push({key:t,atMs:n}),this.votes=this.votes.filter(r=>n-r.atMs<=this.windowMs),n-this.currentSinceMs<this.current.minDurationMs)return this.current;let i=new Map;for(let r of this.votes){let c=(n-r.atMs)/1e3,a=this.decayPerSecond**c;i.set(r.key,(i.get(r.key)??0)+a)}let o=this.current.key,s=-1;for(let[r,c]of i)c>s&&(s=c,o=r);return o!==this.current.key&&(this.current=it[o],this.currentSinceMs=n),this.current}};var Qe=Object.freeze({MAX_AREA_FRAC:.92,TILT_MAX_SIDE_RATIO:1.3,GLARE_MAX_SPECULAR_FRAC:.025});function ee(e){let{data:t,width:n,height:i}=e,o=n*i;if(o===0)return 0;let s=0;for(let r=0;r<o;r++){let c=r*4;.299*(t[c]??0)+.587*(t[c+1]??0)+.114*(t[c+2]??0)>=252&&s++}return s/o}function Be(e){let t=(a,l)=>Math.hypot(l.x-a.x,l.y-a.y),n=t(e.topLeft,e.topRight),i=t(e.bottomLeft,e.bottomRight),o=t(e.topLeft,e.bottomLeft),s=t(e.topRight,e.bottomRight),r=Math.max(n,i)/Math.max(1e-6,Math.min(n,i)),c=Math.max(o,s)/Math.max(1e-6,Math.min(o,s));return Math.max(r,c)}function ie(e){let t={...Zt,...e.thresholds},n=Qe,{quad:i,frameWidth:o,frameHeight:s,measures:r}=e,c=e.format==="ID-3",a="ok";if(i===null)a="no_document";else if(c){let m=ht(i),h=o>0?m.width/o:0,f=m.height>0?m.width/m.height:0;h<t.ID3_BAND_MIN_WIDTH_FRAC?a="too_far":te(i,o,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=Jt(i,o,s),h=ht(i),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>n.MAX_AREA_FRAC?a="too_close":te(i,o,s,t.EDGE_CLIP_MARGIN_PX)?a="edge_clipped":Vt(e.format,f)?Be(i)>n.TILT_MAX_SIDE_RATIO&&(a="tilted"):a="wrong_shape"}let l=r.exposure>=t.GUIDE_EXPOSURE?"ok":r.meanLuma<(ut[0]+ut[1])/2?"too_dark":"too_bright",u=r.sharpness>=t.GUIDE_SHARPNESS?"ok":"blurry",d=r.specularFraction>=n.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 te(e,t,n,i){return[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft].some(s=>s.x<=i||s.y<=i||s.x>=t-i||s.y>=n-i)}var oe=Object.freeze({width:1920,height:1080}),Ue=Object.freeze({width:3840,height:2160}),ne=4096,He=2560,se=640,ot=.15,Y=Object.freeze({side:.2,above:.9,below:.3});function L(e){let t=[e.topLeft.x,e.topRight.x,e.bottomRight.x,e.bottomLeft.x],n=[e.topLeft.y,e.topRight.y,e.bottomRight.y,e.bottomLeft.y],i=Math.min(...t),o=Math.min(...n);return{x:i,y:o,width:Math.max(...t)-i,height:Math.max(...n)-o}}function re(e,t){let n=Math.max(0,Math.floor(e.x)),i=Math.max(0,Math.floor(e.y)),o=Math.min(t.width,Math.ceil(e.x+e.width)),s=Math.min(t.height,Math.ceil(e.y+e.height));return o-n<16||s-i<16?null:{x:n,y:i,width:o-n,height:s-i}}function Ke(e,t,n){if(e===null||t.width<=0||t.height<=0)return null;let i=L(e);if(i.width<=0||i.height<=0)return null;let o=n==="ID-3"?{x:i.x-i.width*Y.side,y:i.y-i.width*Y.above,width:i.width*(1+2*Y.side),height:i.height+i.width*(Y.above+Y.below)}:{x:i.x-i.width*ot,y:i.y-i.height*ot,width:i.width*(1+2*ot),height:i.height*(1+2*ot)};return re(o,t)}function dt(e,t,n){let i=Math.max(e,t);return i>0?Math.min(1,n/i):1}function mt(e,t,n,i,o=He){let s=t.width>0?n.width/t.width:1,r=t.height>0?n.height/t.height:1,c=e===null?null:{topLeft:{x:e.topLeft.x*s,y:e.topLeft.y*r},topRight:{x:e.topRight.x*s,y:e.topRight.y*r},bottomRight:{x:e.bottomRight.x*s,y:e.bottomRight.y*r},bottomLeft:{x:e.bottomLeft.x*s,y:e.bottomLeft.y*r}},a=Ke(c,n,i)??{x:0,y:0,width:n.width,height:n.height},l=dt(a.width,a.height,o),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=L(c);m=re({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 ae(e,t,n,i=Ue){if(n==="LOW")return null;let o=e?.width?.max,s=e?.height?.max;if(typeof o!="number"||typeof s!="number"||o<=0||s<=0)return null;let r=Math.max(o,s),c=Math.min(o,s),a=Math.min(r,Math.max(i.width,i.height)),l=Math.min(c,Math.min(i.width,i.height));return a<=Math.max(t.width,t.height)?null:{width:{ideal:a},height:{ideal:l}}}function ce(e){let t={},n=e?.imageWidth,i=e?.imageHeight;if(typeof n?.max=="number"&&n.max>0){let o=typeof i?.max=="number"&&i.max>0?n.max/i.max:1.3333333333333333,s=o>=1?ne:ne*o,r=Math.min(n.max,Math.floor(s)),c=typeof n.step=="number"&&n.step>0?n.step:1,a=typeof n.min=="number"?n.min:0;r=Math.max(a,a+Math.floor((r-a)/c)*c),t.imageWidth=r}return e?.fillLightMode?.includes("off")===!0&&(t.fillLightMode="off"),t}function le(e,t){if(e.width<=0||e.height<=0||t.width<=0||t.height<=0)return!1;let n=e.width>e.height,i=t.width>t.height;return n!==i&&e.width!==e.height&&t.width!==t.height?!1:Math.max(e.width,e.height)>=1.2*Math.max(t.width,t.height)}function ue(e,t,n,i){if(n===null)return!1;let o=L(e),s=L(n);if(t.width<=0||i.width<=0)return!1;let r=o.width/t.width,c=s.width/i.width;return c>0&&r>=.6*c&&r<=1.25*c}var he=3500,Ve=.92;function me(){let e=globalThis.ImageCapture;return typeof e=="function"?e:null}function We(e){return/AppleWebKit\//.test(e)&&!/(Chrome|Chromium|Edg|OPR)\//.test(e)}function fe(e,t=typeof navigator>"u"?"":navigator.userAgent){return me()!==null&&!We(t)&&e!=null&&e.kind==="video"&&e.readyState==="live"}function de(e,t){return new Promise((n,i)=>{let o=setTimeout(()=>i(new Error("takePhoto timed out")),t);e.then(s=>{clearTimeout(o),n(s)},s=>{clearTimeout(o),i(s)})})}function ft(e,t){let n=document.createElement("canvas");return n.width=e,n.height=t,n}function Xe(e,t){return new Promise((n,i)=>{e.toBlob(o=>o?n(o):i(new Error("toBlob failed")),"image/jpeg",t)})}async function pe(e,t,n,i,o){let s=ft(n,i),r=ft(1,1);try{let c=s.getContext("2d");if(c===null)throw new Error("2d context unavailable");c.imageSmoothingQuality="high",c.drawImage(e,t.x,t.y,t.width,t.height,0,0,n,i);let a=await Xe(s,Ve),l=o===null?null:Wt({topLeft:{x:o.x,y:o.y},topRight:{x:o.x+o.width,y:o.y},bottomRight:{x:o.x+o.width,y:o.y+o.height},bottomLeft:{x:o.x,y:o.y+o.height}},{width:n,height:i},{width:n,height:i}),u=Xt(s,l),d=dt(n,i,se);return r.width=Math.max(1,Math.round(n*d)),r.height=Math.max(1,Math.round(i*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 je(e,t){let n=Math.min(1,t/e.width),i=ft(Math.max(1,Math.round(e.width*n)),Math.max(1,Math.round(e.height*n)));try{let o=i.getContext("2d",{willReadFrequently:!0});return o===null?null:(o.imageSmoothingQuality="high",o.drawImage(e,0,0,i.width,i.height),o.getImageData(0,0,i.width,i.height))}finally{i.width=0,i.height=0}}async function ge(e,t,n,i){let o={width:Math.max(1,e.videoWidth),height:Math.max(1,e.videoHeight)},s=mt(t,n,o,i);return{...await pe(e,s.crop,s.width,s.height,s.docRegion),docRegion:s.docRegion,source:"video",width:s.width,height:s.height}}async function be(e,t,n,i,o){let s=me();if(s===null)return null;let r=null;try{let c=new s(o.track),a=await de(c.getPhotoCapabilities?.()??Promise.resolve({}),he).catch(()=>({})),l=await de(c.takePhoto(ce(a)),he);r=await createImageBitmap(l);let u={width:e.videoWidth,height:e.videoHeight};if(!le(r,u))return null;let d=je(r,o.detectWidth),m=null;d!==null&&t!==null&&(m=await o.detect(d).catch(()=>null));let h=d??{width:r.width,height:r.height};m!==null&&!ue(m,h,t,n)&&(m=null);let f=mt(m,h,r,i);return{...await pe(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=(e,t,n)=>typeof e=="number"&&Number.isFinite(e)&&e>=t&&e<=n?e:void 0;function ki(e){let t=st,n=e!==null&&typeof e=="object"?e:{},i=n.fillDistanceM!==null&&typeof n.fillDistanceM=="object"?n.fillDistanceM:{},o=(s,r)=>typeof s=="boolean"?s:r;return{width:S(n.width,640,7680)??t.width,height:S(n.height,480,4320)??t.height,lensSelection:o(n.lensSelection,t.lensSelection),continuousFocus:o(n.continuousFocus,t.continuousFocus),refocusBeforePhotoMs:S(n.refocusBeforePhotoMs,0,2e3)??t.refocusBeforePhotoMs,zoomMax:S(n.zoomMax,1,5)??t.zoomMax,zoomNoFocusInfo:S(n.zoomNoFocusInfo,1,5)??t.zoomNoFocusInfo,zoomMinSourcePx:S(n.zoomMinSourcePx,0,8e3)??t.zoomMinSourcePx,fillDistanceM:{id1:S(i.id1,.03,1)??t.fillDistanceM.id1,id3:S(i.id3,.03,1)??t.fillDistanceM.id3},focusMarginFrac:S(n.focusMarginFrac,0,2)??t.focusMarginFrac,stillSharpnessMin:S(n.stillSharpnessMin,0,10)??t.stillSharpnessMin,stillRefusalsMax:S(n.stillRefusalsMax,0,10)??t.stillRefusalsMax,focusFarFillFrac:S(n.focusFarFillFrac,0,1)??t.focusFarFillFrac,noDocFarHintMs:S(n.noDocFarHintMs,0,6e4)??t.noDocFarHintMs,zoomFallbackMs:S(n.zoomFallbackMs,0,12e4)??t.zoomFallbackMs}}function Ye(e){let t=e.toLowerCase();return t===""?"unknown":/front|facing front|user|selfie|face ?time/.test(t)?"front":/ultra|0\.5x|wide angle/.test(t)?"ultra":/tele|zoom|periscope|[2-9]x/.test(t)?"tele":/depth|tof|infrared|\bir\b|truedepth|lidar|macro|monochrome|mono\b/.test(t)?"depth":/dual|triple/.test(t)?"virtual":/back|rear|environment|facing back|arrière|خلفية/.test(t)?"main":"unknown"}function Ze(e){let t=/camera2?\s*(\d+)/i.exec(e);return t?Number(t[1]):Number.POSITIVE_INFINITY}function Je(e){let t={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,i)=>({id:n.deviceId,kind:Ye(n.label),index:Ze(n.label),i})).filter(n=>t[n.kind]<9).sort((n,i)=>t[n.kind]-t[i.kind]||n.index-i.index||n.i-i.i).map(n=>n.id)}var pt="sekyro.doc.camera";function $e(){try{let e=globalThis.localStorage?.getItem(pt);return typeof e=="string"&&e!==""?e:null}catch{return null}}function ye(e){try{e===null?globalThis.localStorage?.removeItem(pt):globalThis.localStorage?.setItem(pt,e)}catch{}}var rt=(e,t)=>Array.isArray(e?.focusMode)&&e.focusMode.includes(t);function bt(e,t,n){if(!rt(e,"single-shot"))return null;let i=o=>Math.min(1,Math.max(0,Number.isFinite(o)?o:.5));return{focusMode:"single-shot",pointsOfInterest:[{x:i(t),y:i(n)}]}}function xi(e,t,n,i){if(!Number.isFinite(e)||!Number.isFinite(t)||n.width<=0||n.height<=0||i.width<=0||i.height<=0)return null;let o=Math.max(n.width/i.width,n.height/i.height),s=i.width*o,r=i.height*o,c=(e-n.left+(s-n.width)/2)/s,a=(t-n.top+(r-n.height)/2)/r;return{x:Math.min(1,Math.max(0,c)),y:Math.min(1,Math.max(0,a))}}function ke(e,t,n,i=st){let o=e?.zoom?.min,s=e?.zoom?.max;if(typeof s!="number"||s<=1)return 1;let r=n==="ID-3"?i.fillDistanceM.id3:i.fillDistanceM.id1,c=e?.focusDistance?.min,a;if(typeof c=="number"&&c>0&&c<1){if(a=c*(1+i.focusMarginFrac)/r,a<=1.05)return 1}else{if(Math.min(t.width,t.height)<i.zoomMinSourcePx)return 1;a=i.zoomNoFocusInfo}let l=Math.min(a,i.zoomMax,s);typeof o=="number"&&(l=Math.max(l,o));let u=e?.zoom?.step;return typeof u=="number"&&u>0&&(l=Math.round(l/u)*u),l>1.01?Number(l.toFixed(2)):1}function gt(e){try{return e.getVideoTracks?.()[0]}catch{return}}function Me(e){if(e!==null)for(let t of e.getTracks())t.stop()}function qe(e){try{let t=gt(e)?.getCapabilities?.();return!Array.isArray(t?.focusMode)||t.focusMode.includes("continuous")}catch{return!0}}var ti=3;async function xe(e){let t=s=>({audio:!1,video:{...s,width:{ideal:e.base.width},height:{ideal:e.base.height}}}),n=s=>e.getUserMedia(t({deviceId:{exact:s}})),i=()=>e.getUserMedia(t({facingMode:{ideal:"environment"}}));if(e.lensSelection){let s=$e();if(s!==null)try{return{stream:await n(s),lens:"stored"}}catch{ye(null)}}let o=await i();if(!e.lensSelection||e.enumerateDevices===void 0)return{stream:o,lens:"default"};try{let s=Je(await e.enumerateDevices()).slice(0,ti);if(s.length===0)return{stream:o,lens:"default"};let r=null;for(let c of s){let a=o!==null?gt(o)?.getSettings?.().deviceId:void 0;if(o===null||a!==c){Me(o),o=null;try{o=await n(c)}catch{continue}}if(r??(r=c),qe(o))return ye(c),{stream:o,lens:"selected"}}if(o!==null&&r!==null&&gt(o)?.getSettings?.().deviceId===r)return{stream:o,lens:"selected"};if(Me(o),o=null,r!==null)try{return{stream:await n(r),lens:"selected"}}catch{}return{stream:await i(),lens:"default"}}catch{return{stream:o??await i(),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}),I=e=>Math.min(1,Math.max(0,e));function we(e,t,n,i=.06){let o=Math.max(e.width/n,e.height),s=o*n,r=(e.width-s)/2,c=(e.height-o)/2,a=I((t.x-t.width*i-r)/s),l=I((t.y-t.height*i-c)/o),u=I((t.x+t.width*(1+i)-r)/s),d=I((t.y+t.height*(1+i)-c)/o);return{x:a,y:l,width:u-a,height:d-l}}function ve(e,t,n={}){let i=n.edgePeakFrac??0,{width:o,height:s,data:r}=e;if(o<=0||s<=0)return Z;let c=I(t.x),a=I(t.y),l={x:c,y:a,width:Math.max(0,I(t.x+t.width)-c),height:Math.max(0,I(t.y+t.height)-a)};if(l.width<=0||l.height<=0)return Z;let u=l.x*o,d=l.y*s,m=(l.x+l.width)*o,h=(l.y+l.height)*s,f=(m-u)*.15,g=(h-d)*.15,y=(p,b,T)=>Math.min(T,Math.max(b,p)),x=y(Math.floor(u-f),0,o-1),w=y(Math.floor(d-g),0,s-1),E=y(Math.ceil(m+f),x+1,o),v=y(Math.ceil(h+g),w+1,s),D=Math.max(1,Math.ceil(Math.max(E-x,v-w)/320)),M=Math.floor((E-x+D-1)/D),_=Math.floor((v-w+D-1)/D);if(M<3||_<3)return Z;let k=new Int32Array(M*_);for(let p=0;p<_;p++){let b=w+p*D;for(let T=0;T<M;T++){let C=(b*o+x+T*D)*4;k[p*M+T]=(r[C]??0)*77+(r[C+1]??0)*150+(r[C+2]??0)*29>>8}}let F=(p,b)=>(p-b-.5)/D,R=F(u,x),A=F(m,x),B=F(d,w),U=F(h,w),Mt=(m-u)/D,kt=(h-d)/D,xt=y(Math.ceil(R),0,M-1),Ce=y(Math.floor(A),xt,M-1),Dt=y(Math.ceil(B),0,_-1),Fe=y(Math.floor(U),Dt,_-1),wt=0,vt=0,H=0,St=0,_t=0,K=0;for(let p=Dt;p<=Fe;p++)for(let b=xt;b<=Ce;b++){let T=k[p*M+b];if(wt+=T,T>=248&&vt++,H++,b>=1&&b<M-1&&p>=1&&p<_-1){let C=k[p*M+b-1]+k[p*M+b+1]+k[(p-1)*M+b]+k[(p+1)*M+b]-4*T;St+=C,_t+=C*C,K++}}let Ae=H>0?wt/H:0,Rt=H>0?vt/H:0,Tt=K>0?St/K:0,Le=K>0?Math.max(0,_t/K-Tt*Tt):0,V=new Float64Array(M),W=new Float64Array(_);for(let p=0;p<_;p++)for(let b=1;b<M-1;b++)V[b]=V[b]+Math.abs(k[p*M+b+1]-k[p*M+b-1]);for(let p=1;p<_-1;p++)for(let b=0;b<M;b++)W[p]=W[p]+Math.abs(k[(p+1)*M+b]-k[(p-1)*M+b]);let O=at(V,!0,R,i),P=at(V,!1,A,i),G=at(W,!0,B,i),z=at(W,!1,U,i),Ct=(P.position-O.position)/Mt,Ft=(z.position-G.position)/kt,Ie=Ft>0?Ct/Ft:0,Ee=((O.position+P.position)/2-(R+A)/2)/Mt,Oe=((G.position+z.position)/2-(B+U)/2)/kt,At=De(V),Lt=De(W),Pe=At<=0||Lt<=0?0:Math.min(Math.min(O.value,P.value)/At,Math.min(G.value,z.value)/Lt),q=(p,b)=>b+(p+.5)*D,It=Rt,Et=0;{let p=(P.position-O.position)*.06,b=(z.position-G.position)*.06,T=y(Math.ceil(O.position+p),0,M-1),C=y(Math.floor(P.position-p),0,M-1),Ge=y(Math.ceil(G.position+b),0,_-1),Ot=y(Math.floor(z.position-b),0,_-1),Pt=0,tt=0,Gt=0;for(let N=Ge;N<=Ot;N++)for(let Q=T;Q<=C;Q++){tt++;let X=k[N*M+Q];X>=248&&Pt++;let ze=Q+2<=C?k[N*M+Q+2]:X,Ne=N+2<=Ot?k[(N+2)*M+Q]:X;(Math.abs(ze-X)>=24||Math.abs(Ne-X)>=24)&&Gt++}tt>=16&&(It=Pt/tt,Et=Gt/tt)}return{brightness:Ae,glare:Rt,cardGlare:It,sharpness:Le,fill:Ct,shape:Ie,content:Et,offsetX:Ee,offsetY:Oe,edgeConfidence:Pe,box:{left:q(O.position,x),right:q(P.position,x),top:q(G.position,w),bottom:q(z.position,w)}}}function at(e,t,n,i){let o=e.length,s=Math.max(1,Math.floor(o*.45)),r=t?1:Math.max(1,o-1-s),c=t?Math.min(o-2,s):o-2,a=r;for(let h=r;h<=c;h++)e[h]>e[a]&&(a=h);if(i>0&&i<1){let h=e[a]*i,f=a,g=Math.abs(a-n);for(let y=r;y<=c;y++){let x=e[y];if(x<h||x<(e[y-1]??0)||x<(e[y+1]??0))continue;let w=Math.abs(y-n);w<g&&(f=y,g=w)}a=f}let l=a>0?e[a-1]:0,u=e[a],d=a<o-1?e[a+1]:0,m=l+u+d;return{position:m>0?a+(d-l)/m:a,value:u}}function De(e){if(e.length<3)return 0;let t=0;for(let n=1;n<e.length-1;n++)t+=e[n];return t/(e.length-2)}function Se(e){let t=e.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 wi(e){let t=e!==null&&typeof e=="object"?e:{},n={...J};for(let i of Object.keys(J)){let o=t[i];typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=1e6&&(n[i]=o)}return n}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,n){let i=this.t,o=i.shapeTolerance<=0||Math.abs(t.shape-1)<=i.shapeTolerance,s=t.edgeConfidence>=i.edgeConfidenceMin&&o&&t.content>=i.contentMin,r=t.fill>=i.fillMin&&t.fill<=i.fillMax,c=Math.abs(t.offsetX)<=i.offsetMax&&Math.abs(t.offsetY)<=i.offsetMax,a=t.cardGlare<=i.glareMax,l=t.sharpness>=i.sharpnessMin,u=this.last;this.last={fill:t.fill,offsetX:t.offsetX,offsetY:t.offsetY,at:n};let d=u!==null&&i.steadyRefMs>0?Math.min(3,Math.max(1,(n-u.at)/i.steadyRefMs)):1,m=s&&a&&l&&t.fill>=i.steadyFillMin&&t.fill<=i.steadyFillMax&&u!==null&&Math.abs(t.fill-u.fill)<=i.steadyFillDelta*d&&Math.abs(t.offsetX-u.offsetX)<=i.steadyOffsetDelta*d&&Math.abs(t.offsetY-u.offsetY)<=i.steadyOffsetDelta*d,h=s&&r&&c&&a&&l,f;if(s?a?t.fill<i.fillMin?f="too_small":t.fill>i.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=n)),this.goodSince??(this.goodSince=n),n-this.goodSince>=i.lockMs)return{detected:s,ready:!0,via:"good",blocker:"locking"};let g=this.steadySince!==null&&n-this.steadySince>=i.steadyMs;return{detected:s,ready:g,via:g?"steady":null,blocker:"locking"}}if(this.goodSince=null,m){this.steadySince??(this.steadySince=n);let g=n-this.steadySince>=i.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 $=null;async function ei(e){return $===null&&($=(await import("./detector-scanic-YCDNLCGV.js")).detectQuad),$(e)}async function ii(e){let t=jt(e);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 Ni(){$===null&&import("./detector-scanic-YCDNLCGV.js").then(e=>{$=e.detectQuad}).catch(()=>{})}var ni=Object.freeze({LOW:3,MID:5,HIGH:6}),yt=Object.freeze({manualShutterMs:6e3,detectedNoLockMs:1950});function Qi(e){let t=e!==null&&typeof e=="object"?e:{},n=(i,o,s)=>typeof i=="number"&&Number.isFinite(i)&&i>=o&&i<=s?i:void 0;return{manualShutterMs:n(t.manualShutterMs,1e3,6e4)??yt.manualShutterMs,detectedNoLockMs:n(t.steadyMs,300,3e4)!==void 0?t.steadyMs+(n(t.lockMs,0,1e4)??450):yt.detectedNoLockMs}}var _e=class e{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=e.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 nt;this.lastFeedbackKey=null;this.lastQuad=null;this.lastDetect=null;this.opts=t,this.gate=new $t(t.format??"ID-1",t.thresholds);let n=t.deviceClass??Bt(Qt());this.deviceClass=n,this.camera=t.camera??st,this.shutterTuning=t.shutter??yt,this.guideTuning=t.guideLock??J,this.guideLock=new ct(this.guideTuning),this.cadenceMs=1e3/ni[n]}on(t,n){let i=this.handlers.get(t);return i||(i=new Set,this.handlers.set(t,i)),i.add(n),()=>i?.delete(n)}emit(t,n){for(let i of[...this.handlers.get(t)??[]])i(n)}async start(){let t=++this.attempt;this.gate.reset(),this.resetSide(),this.feedback.reset(),this.lastFeedbackKey=null,this.lastGuidance=null,this.capturing=!1,this.setState("preflight");try{let n=this.opts.getUserMedia??(s=>navigator.mediaDevices.getUserMedia(s));this.setState("acquiring");let i=this.opts.enumerateDevices??(this.opts.getUserMedia===void 0&&typeof navigator<"u"&&navigator.mediaDevices?.enumerateDevices?()=>navigator.mediaDevices.enumerateDevices():void 0),o=await xe({getUserMedia:n,...i!==void 0?{enumerateDevices:i}:{},lensSelection:this.camera.lensSelection,base:oe});if(this.stream=o.stream,Nt(this.stream),t!==this.attempt){for(let s of this.stream.getTracks())s.stop();return}if(this.opts.upgradeResolution!==!1&&await this.upgradeResolution(),t!==this.attempt||(await this.applyFocusAndZoom(),t!==this.attempt))return;this.opts.video.srcObject=this.stream,await this.opts.video.play().catch(()=>{}),this.setState("positioning"),this.scheduleTick(t)}catch(n){let i=zt(n);this.setState("error"),this.emit("error",{kind:i,retryable:!0})}}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,n=this.lastDetect?.width??Math.max(1,t.videoWidth),i=this.lastDetect?.height??Math.max(1,t.videoHeight),o=this.lastQuad??this.lastGuideQuad??{topLeft:{x:0,y:0},topRight:{x:n,y:0},bottomRight:{x:n,y:i},bottomLeft:{x:0,y:i}},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:o,{width:n,height:i,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 n=(this.opts.format??"ID-1")==="ID-3"||this.opts.side==="single"?"single":this.opts.side==="verso"?"verso":"recto",i=t.report(n,this.stats.via,(this.opts.now??(()=>performance.now()))());return i===null?{}:{ocr:i}}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 n=t.width/Math.max(1,t.height),i=this.opts.guide;if(i!==void 0&&i.viewAspect>0){let c={width:i.viewAspect,height:1},a={x:i.rect.x*i.viewAspect,y:i.rect.y,width:i.rect.width*i.viewAspect,height:i.rect.height};return we(c,a,n,0)}let o=Kt(this.opts.format??"ID-1").center,s=.86,r=s*n/o;return r>.84&&(r=.84,s=r*o/n),{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=e.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 n=this.videoTrack();if(n===null||this.zoom<=1)return;let i=this.focusCaps(),o=typeof i?.zoom?.min=="number"?Math.max(i.zoom.min,1):1;this.zoom=o,this.stats.zoomFallbackAtMs=Math.round(t-(this.positioningSince??t)),this.guideLock.reset(),this.gate.reset(),n.applyConstraints({advanced:[{zoom:o}]}).catch(()=>{})}offerShutter(t,n){this.shutterOffered||(this.shutterOffered=!0,this.stats.shutterAtMs=Math.round(n-(this.positioningSince??n)),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.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 n=t.getSettings?.()??{},i=ae(t.getCapabilities?.(),{width:n.width??0,height:n.height??0},this.deviceClass,{width:this.camera.width,height:this.camera.height});i!==null&&await t.applyConstraints(i)}catch{}}focusCaps(){try{return this.videoTrack()?.getCapabilities?.()??null}catch{return null}}async applyFocusAndZoom(){let t=this.videoTrack();if(t===null)return;let n=this.focusCaps();this.camera.continuousFocus&&rt(n,"continuous")&&await t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{});let i={width:0,height:0};try{let s=t.getSettings?.()??{};i={width:s.width??0,height:s.height??0}}catch{}let o=ke(n,i,this.opts.format??"ID-1",this.camera);if(o>1)try{await t.applyConstraints({advanced:[{zoom:o}]}),this.zoom=o}catch{this.zoom=1}}async focusAt(t,n){let i=this.videoTrack(),o=bt(this.focusCaps(),t,n);if(!(i===null||o===null))try{await i.applyConstraints({advanced:[o]}),(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,n){let i=this.camera.refocusBeforePhotoMs,o=this.videoTrack();if(i<=0||o===null||n.width<=0||n.height<=0)return;let s=L(t),r=bt(this.focusCaps(),(s.x+s.width/2)/n.width,(s.y+s.height/2)/n.height);if(r!==null)try{await o.applyConstraints({advanced:[r]});let c=this.opts.setTimer??setTimeout;await new Promise(a=>{c(()=>a(),i)})}catch{}}videoTrack(){try{return this.stream?.getVideoTracks?.()[0]??null}catch{return null}}async takeStill(t,n,i){if(this.opts.captureStill!==void 0)return this.opts.captureStill(this.opts.video,t,n);let o=this.opts.format??"ID-1",s=this.videoTrack();if(i&&this.opts.photoCapture!==!1&&this.deviceClass!=="LOW"&&!this.torchOn&&s!==null&&fe(s)){await this.refocusOn(t,n);let r=await be(this.opts.video,t,n,o,{track:s,detect:this.detector(),detectWidth:et});if(this.restoreContinuous(),r!==null)return r}return ge(this.opts.video,t,n,o)}detector(){return this.opts.detect??((this.opts.format??"ID-1")==="ID-3"?ii:ei)}setState(t){this.state=t,this.emit("statechange",{state:t})}scheduleTick(t){let n=this.opts.setTimer??setTimeout;this.timer=n(()=>{this.tick(t)},this.cadenceMs)}async tick(t){if(t!==this.attempt||this.state!=="positioning"||this.capturing)return;let n=this.opts.now??(()=>performance.now()),i=this.opts.grabDetectFrame??Te,o=this.detector(),s=i(this.opts.video,et);if(s===null){this.scheduleTick(t);return}let r=null;try{r=await o(s)}catch{r=null}if(t!==this.attempt)return;let c=r!==null?lt(s,r):s,a=n(),l={sharpness:j(c),exposure:Ht(c),meanLuma:Ut(c),specularFraction:ee(c)},u=ie({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"?ve(s,this.guideRegion(s),{edgePeakFrac:this.guideTuning.edgePeakFrac}):Z,f=this.guideLock.tick(h,a);this.lastGuideQuad=f.detected?Se(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 R=u.lighting!=="ok"?u.lighting:u.glare!=="ok"?"glare":u.blur!=="ok"?"blurry":"steadying";y.qualityBlockers[R]=(y.qualityBlockers[R]??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<=ui?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 E=a-(this.lastSeenAt??this.positioningSince);this.zoom>1&&this.camera.zoomFallbackMs>0&&E>=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=qt(u);u.framing!=="ok"&&f.detected&&(v=li(f.blocker,h.brightness<this.guideTuning.darkBrightness)),v==="blurry"&&r!==null&&si(r,s,this.opts.format??"ID-1")>=this.camera.focusFarFillFrac&&(v="focus_far"),v==="sensing"&&this.zoom>1&&this.camera.noDocFarHintMs>0&&E>=this.camera.noDocFarHintMs&&(v="focus_far");let D=this.feedback.tick(v,a);if(D.key!==this.lastFeedbackKey&&(this.lastFeedbackKey=D.key,this.emit("feedback",D)),d.guidanceKey!==this.lastGuidance&&(this.lastGuidance=d.guidanceKey,this.emit("guidance",{key:d.guidanceKey})),this.capturing)return;let M=g?.suspendQuality!==!0,_=M&&d.ready&&r!==null,k=M&&f.ready&&this.lastGuideQuad!==null,F=this.lastOcrReady;if(F!==null&&this.opts.autoCapture!==!1){let R=this.feedback.force("processing",a);this.lastFeedbackKey=R.key,this.emit("feedback",R);let A=j(lt(s,F.quad));await this.fire(t,F.quad,{width:s.width,height:s.height,tickSharpness:A},F.via);return}if((_||k)&&this.opts.autoCapture!==!1){let R=this.feedback.force("processing",a);this.lastFeedbackKey=R.key,this.emit("feedback",R);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,n,i,o){this.capturing=!0;let s=this.opts.grabDetectFrame??Te,r=this.opts.setTimer??setTimeout,c={width:i.width,height:i.height};try{let a={still:await this.takeStill(n,c,!0),sharpness:i.tickSharpness};if(t!==this.attempt)return;let l=a.still.source==="photo"?0:ri;for(let m=0;m<l;m++){if(await new Promise(g=>{r(()=>g(),ai)}),t!==this.attempt)return;let h=s(this.opts.video,et);if(h===null)continue;let f=j(lt(h,n));if(f>a.sharpness*ci){let g=await this.takeStill(n,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&&o!=="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,(o==="text_lock"||o==="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=o,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=o==="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,(o==="text_lock"||o==="live_mrz")&&this.opts.ocr?.rearmFace(),this.scheduleTick(t)}}ocrTick(t,n,i,o,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,x;m&&n!==null?x=oi(L(n),g,y,l,u):x=Yt(f,c.bandTop,u);let w=m?s.glare==="ok":i.cardGlare<=this.guideTuning.glareMax,E=m?s.blur==="ok":i.sharpness>=this.guideTuning.sharpnessMin,v=c.tick({atMs:r,video:a,mrzFace:m||this.opts.side==="verso"||this.opts.side==="single",present:m||n!==null||o,card:f,band:x,portrait:u>l,glareOk:w,sharpOk:E});if(v.ready&&v.via!==void 0){let D=m?n??Re(h,t):this.lastGuideQuad??Re(h,t);this.lastOcrReady={quad:D,via:v.via}}else this.lastOcrReady=null;return v}};function oi(e,t,n,i,o){let s=Math.min(i,e.width*1.06*t),r=Math.min(o,Math.max(e.height*1.6*n,s/5)),c=(e.y+e.height/2)*n,a=Math.max(0,Math.min(i-s,(e.x-e.width*.03)*t)),l=Math.max(0,Math.min(o-r,c-r/2));return{x:a,y:l,w:s,h:r}}function Re(e,t){let n=e.x*t.width,i=e.y*t.height,o=(e.x+e.width)*t.width,s=(e.y+e.height)*t.height;return{topLeft:{x:n,y:i},topRight:{x:o,y:i},bottomRight:{x:o,y:s},bottomLeft:{x:n,y:s}}}function si(e,t,n){let i=L(e);return t.width<=0||t.height<=0?0:n==="ID-3"?i.width/t.width:i.width*i.height/(t.width*t.height)}var ri=2,ai=260,ci=1.08;function Te(e,t){let n=e.videoWidth,i=e.videoHeight;if(n===0||i===0)return null;let o=Math.min(1,t/n),s=Math.round(n*o),r=Math.round(i*o),c=document.createElement("canvas");c.width=s,c.height=r;let a=c.getContext("2d",{willReadFrequently:!0});return a===null?null:(n/Math.max(1,s)>4&&(a.imageSmoothingQuality="high"),a.drawImage(e,0,0,s,r),a.getImageData(0,0,s,r))}function lt(e,t){let n=[t.topLeft.x,t.topRight.x,t.bottomRight.x,t.bottomLeft.x],i=[t.topLeft.y,t.topRight.y,t.bottomRight.y,t.bottomLeft.y],o=Math.max(0,Math.floor(Math.min(...n))),s=Math.max(0,Math.floor(Math.min(...i))),r=Math.min(e.width,Math.ceil(Math.max(...n))),c=Math.min(e.height,Math.ceil(Math.max(...i))),a=Math.max(1,r-o),l=Math.max(1,c-s),u=new Uint8ClampedArray(a*l*4);for(let d=0;d<l;d++){let m=((s+d)*e.width+o)*4;u.set(e.data.subarray(m,m+a*4),d*a*4)}return{data:u,width:a,height:l,colorSpace:e.colorSpace}}function li(e,t){return e==="glare"?"glare":e==="too_small"?"too_far":e==="too_big"?"too_close":t?"too_dark":e==="blurry"?"blurry":e==="off_center"?"edge_clipped":e==="no_card"?"sensing":"hold_still"}var ui=1200;export{it as a,qt as b,nt as c,Qe as d,ee as e,Be as f,ie as g,st as h,ki as i,Ye as j,Je as k,pt as l,$e as m,ye as n,rt as o,bt as p,xi as q,ke as r,qe as s,ti as t,xe as u,Z as v,we as w,ve as x,Se as y,J as z,wi as A,ct as B,Ni as C,ni as D,yt as E,Qi as F,_e as G,oi as H,ri as I,ai as J};
1
+ import{b as jt}from"./chunk-SMKCBUJL.js";import{a as et,b as Zt,c as Jt,e as ht,f as $t}from"./chunk-MXWLCDFX.js";import{d as Wt,h as Xt,k as Yt}from"./chunk-G6LKLN4U.js";import{b as Kt,c as Vt}from"./chunk-TDLIXFDT.js";import{b as Qt,c as Bt}from"./chunk-POIQGEZM.js";import{d as zt}from"./chunk-FHJ7HO3M.js";import{b as ut,c as Ut,d as j,e as Ht}from"./chunk-FPXL63KZ.js";import{b as Nt}from"./chunk-4IVRXJR2.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 qt(e){return e.framing==="no_document"?"sensing":e.framing==="too_far"?"too_far":e.framing==="too_close"?"too_close":e.framing==="edge_clipped"?"edge_clipped":e.framing==="wrong_shape"?"wrong_shape":e.framing==="tilted"?"tilted":e.lighting==="too_dark"?"too_dark":e.lighting==="too_bright"?"too_bright":e.glare==="glare"?"glare":e.blur==="blurry"?"blurry":"hold_still"}var nt=class{constructor(t=2600,n=.35){this.windowMs=t;this.decayPerSecond=n;this.votes=[];this.current=it.sensing;this.currentSinceMs=null}reset(){this.votes=[],this.current=it.sensing,this.currentSinceMs=null}force(t,n){return this.votes=[],this.current=it[t],this.currentSinceMs=n,this.current}tick(t,n){if(this.currentSinceMs===null&&(this.currentSinceMs=n),this.votes.push({key:t,atMs:n}),this.votes=this.votes.filter(r=>n-r.atMs<=this.windowMs),n-this.currentSinceMs<this.current.minDurationMs)return this.current;let i=new Map;for(let r of this.votes){let c=(n-r.atMs)/1e3,a=this.decayPerSecond**c;i.set(r.key,(i.get(r.key)??0)+a)}let o=this.current.key,s=-1;for(let[r,c]of i)c>s&&(s=c,o=r);return o!==this.current.key&&(this.current=it[o],this.currentSinceMs=n),this.current}};var Qe=Object.freeze({MAX_AREA_FRAC:.92,TILT_MAX_SIDE_RATIO:1.3,GLARE_MAX_SPECULAR_FRAC:.025});function ee(e){let{data:t,width:n,height:i}=e,o=n*i;if(o===0)return 0;let s=0;for(let r=0;r<o;r++){let c=r*4;.299*(t[c]??0)+.587*(t[c+1]??0)+.114*(t[c+2]??0)>=252&&s++}return s/o}function Be(e){let t=(a,l)=>Math.hypot(l.x-a.x,l.y-a.y),n=t(e.topLeft,e.topRight),i=t(e.bottomLeft,e.bottomRight),o=t(e.topLeft,e.bottomLeft),s=t(e.topRight,e.bottomRight),r=Math.max(n,i)/Math.max(1e-6,Math.min(n,i)),c=Math.max(o,s)/Math.max(1e-6,Math.min(o,s));return Math.max(r,c)}function ie(e){let t={...Zt,...e.thresholds},n=Qe,{quad:i,frameWidth:o,frameHeight:s,measures:r}=e,c=e.format==="ID-3",a="ok";if(i===null)a="no_document";else if(c){let m=ht(i),h=o>0?m.width/o:0,f=m.height>0?m.width/m.height:0;h<t.ID3_BAND_MIN_WIDTH_FRAC?a="too_far":te(i,o,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=Jt(i,o,s),h=ht(i),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>n.MAX_AREA_FRAC?a="too_close":te(i,o,s,t.EDGE_CLIP_MARGIN_PX)?a="edge_clipped":Vt(e.format,f)?Be(i)>n.TILT_MAX_SIDE_RATIO&&(a="tilted"):a="wrong_shape"}let l=r.exposure>=t.GUIDE_EXPOSURE?"ok":r.meanLuma<(ut[0]+ut[1])/2?"too_dark":"too_bright",u=r.sharpness>=t.GUIDE_SHARPNESS?"ok":"blurry",d=r.specularFraction>=n.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 te(e,t,n,i){return[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft].some(s=>s.x<=i||s.y<=i||s.x>=t-i||s.y>=n-i)}var oe=Object.freeze({width:1920,height:1080}),Ue=Object.freeze({width:3840,height:2160}),ne=4096,He=2560,se=640,ot=.15,Y=Object.freeze({side:.2,above:.9,below:.3});function L(e){let t=[e.topLeft.x,e.topRight.x,e.bottomRight.x,e.bottomLeft.x],n=[e.topLeft.y,e.topRight.y,e.bottomRight.y,e.bottomLeft.y],i=Math.min(...t),o=Math.min(...n);return{x:i,y:o,width:Math.max(...t)-i,height:Math.max(...n)-o}}function re(e,t){let n=Math.max(0,Math.floor(e.x)),i=Math.max(0,Math.floor(e.y)),o=Math.min(t.width,Math.ceil(e.x+e.width)),s=Math.min(t.height,Math.ceil(e.y+e.height));return o-n<16||s-i<16?null:{x:n,y:i,width:o-n,height:s-i}}function Ke(e,t,n){if(e===null||t.width<=0||t.height<=0)return null;let i=L(e);if(i.width<=0||i.height<=0)return null;let o=n==="ID-3"?{x:i.x-i.width*Y.side,y:i.y-i.width*Y.above,width:i.width*(1+2*Y.side),height:i.height+i.width*(Y.above+Y.below)}:{x:i.x-i.width*ot,y:i.y-i.height*ot,width:i.width*(1+2*ot),height:i.height*(1+2*ot)};return re(o,t)}function dt(e,t,n){let i=Math.max(e,t);return i>0?Math.min(1,n/i):1}function mt(e,t,n,i,o=He){let s=t.width>0?n.width/t.width:1,r=t.height>0?n.height/t.height:1,c=e===null?null:{topLeft:{x:e.topLeft.x*s,y:e.topLeft.y*r},topRight:{x:e.topRight.x*s,y:e.topRight.y*r},bottomRight:{x:e.bottomRight.x*s,y:e.bottomRight.y*r},bottomLeft:{x:e.bottomLeft.x*s,y:e.bottomLeft.y*r}},a=Ke(c,n,i)??{x:0,y:0,width:n.width,height:n.height},l=dt(a.width,a.height,o),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=L(c);m=re({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 ae(e,t,n,i=Ue){if(n==="LOW")return null;let o=e?.width?.max,s=e?.height?.max;if(typeof o!="number"||typeof s!="number"||o<=0||s<=0)return null;let r=Math.max(o,s),c=Math.min(o,s),a=Math.min(r,Math.max(i.width,i.height)),l=Math.min(c,Math.min(i.width,i.height));return a<=Math.max(t.width,t.height)?null:{width:{ideal:a},height:{ideal:l}}}function ce(e){let t={},n=e?.imageWidth,i=e?.imageHeight;if(typeof n?.max=="number"&&n.max>0){let o=typeof i?.max=="number"&&i.max>0?n.max/i.max:1.3333333333333333,s=o>=1?ne:ne*o,r=Math.min(n.max,Math.floor(s)),c=typeof n.step=="number"&&n.step>0?n.step:1,a=typeof n.min=="number"?n.min:0;r=Math.max(a,a+Math.floor((r-a)/c)*c),t.imageWidth=r}return e?.fillLightMode?.includes("off")===!0&&(t.fillLightMode="off"),t}function le(e,t){if(e.width<=0||e.height<=0||t.width<=0||t.height<=0)return!1;let n=e.width>e.height,i=t.width>t.height;return n!==i&&e.width!==e.height&&t.width!==t.height?!1:Math.max(e.width,e.height)>=1.2*Math.max(t.width,t.height)}function ue(e,t,n,i){if(n===null)return!1;let o=L(e),s=L(n);if(t.width<=0||i.width<=0)return!1;let r=o.width/t.width,c=s.width/i.width;return c>0&&r>=.6*c&&r<=1.25*c}var he=3500,Ve=.92;function me(){let e=globalThis.ImageCapture;return typeof e=="function"?e:null}function We(e){return/AppleWebKit\//.test(e)&&!/(Chrome|Chromium|Edg|OPR)\//.test(e)}function fe(e,t=typeof navigator>"u"?"":navigator.userAgent){return me()!==null&&!We(t)&&e!=null&&e.kind==="video"&&e.readyState==="live"}function de(e,t){return new Promise((n,i)=>{let o=setTimeout(()=>i(new Error("takePhoto timed out")),t);e.then(s=>{clearTimeout(o),n(s)},s=>{clearTimeout(o),i(s)})})}function ft(e,t){let n=document.createElement("canvas");return n.width=e,n.height=t,n}function Xe(e,t){return new Promise((n,i)=>{e.toBlob(o=>o?n(o):i(new Error("toBlob failed")),"image/jpeg",t)})}async function pe(e,t,n,i,o){let s=ft(n,i),r=ft(1,1);try{let c=s.getContext("2d");if(c===null)throw new Error("2d context unavailable");c.imageSmoothingQuality="high",c.drawImage(e,t.x,t.y,t.width,t.height,0,0,n,i);let a=await Xe(s,Ve),l=o===null?null:Wt({topLeft:{x:o.x,y:o.y},topRight:{x:o.x+o.width,y:o.y},bottomRight:{x:o.x+o.width,y:o.y+o.height},bottomLeft:{x:o.x,y:o.y+o.height}},{width:n,height:i},{width:n,height:i}),u=Xt(s,l),d=dt(n,i,se);return r.width=Math.max(1,Math.round(n*d)),r.height=Math.max(1,Math.round(i*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 je(e,t){let n=Math.min(1,t/e.width),i=ft(Math.max(1,Math.round(e.width*n)),Math.max(1,Math.round(e.height*n)));try{let o=i.getContext("2d",{willReadFrequently:!0});return o===null?null:(o.imageSmoothingQuality="high",o.drawImage(e,0,0,i.width,i.height),o.getImageData(0,0,i.width,i.height))}finally{i.width=0,i.height=0}}async function ge(e,t,n,i){let o={width:Math.max(1,e.videoWidth),height:Math.max(1,e.videoHeight)},s=mt(t,n,o,i);return{...await pe(e,s.crop,s.width,s.height,s.docRegion),docRegion:s.docRegion,source:"video",width:s.width,height:s.height}}async function be(e,t,n,i,o){let s=me();if(s===null)return null;let r=null;try{let c=new s(o.track),a=await de(c.getPhotoCapabilities?.()??Promise.resolve({}),he).catch(()=>({})),l=await de(c.takePhoto(ce(a)),he);r=await createImageBitmap(l);let u={width:e.videoWidth,height:e.videoHeight};if(!le(r,u))return null;let d=je(r,o.detectWidth),m=null;d!==null&&t!==null&&(m=await o.detect(d).catch(()=>null));let h=d??{width:r.width,height:r.height};m!==null&&!ue(m,h,t,n)&&(m=null);let f=mt(m,h,r,i);return{...await pe(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=(e,t,n)=>typeof e=="number"&&Number.isFinite(e)&&e>=t&&e<=n?e:void 0;function ki(e){let t=st,n=e!==null&&typeof e=="object"?e:{},i=n.fillDistanceM!==null&&typeof n.fillDistanceM=="object"?n.fillDistanceM:{},o=(s,r)=>typeof s=="boolean"?s:r;return{width:S(n.width,640,7680)??t.width,height:S(n.height,480,4320)??t.height,lensSelection:o(n.lensSelection,t.lensSelection),continuousFocus:o(n.continuousFocus,t.continuousFocus),refocusBeforePhotoMs:S(n.refocusBeforePhotoMs,0,2e3)??t.refocusBeforePhotoMs,zoomMax:S(n.zoomMax,1,5)??t.zoomMax,zoomNoFocusInfo:S(n.zoomNoFocusInfo,1,5)??t.zoomNoFocusInfo,zoomMinSourcePx:S(n.zoomMinSourcePx,0,8e3)??t.zoomMinSourcePx,fillDistanceM:{id1:S(i.id1,.03,1)??t.fillDistanceM.id1,id3:S(i.id3,.03,1)??t.fillDistanceM.id3},focusMarginFrac:S(n.focusMarginFrac,0,2)??t.focusMarginFrac,stillSharpnessMin:S(n.stillSharpnessMin,0,10)??t.stillSharpnessMin,stillRefusalsMax:S(n.stillRefusalsMax,0,10)??t.stillRefusalsMax,focusFarFillFrac:S(n.focusFarFillFrac,0,1)??t.focusFarFillFrac,noDocFarHintMs:S(n.noDocFarHintMs,0,6e4)??t.noDocFarHintMs,zoomFallbackMs:S(n.zoomFallbackMs,0,12e4)??t.zoomFallbackMs}}function Ye(e){let t=e.toLowerCase();return t===""?"unknown":/front|facing front|user|selfie|face ?time/.test(t)?"front":/ultra|0\.5x|wide angle/.test(t)?"ultra":/tele|zoom|periscope|[2-9]x/.test(t)?"tele":/depth|tof|infrared|\bir\b|truedepth|lidar|macro|monochrome|mono\b/.test(t)?"depth":/dual|triple/.test(t)?"virtual":/back|rear|environment|facing back|arrière|خلفية/.test(t)?"main":"unknown"}function Ze(e){let t=/camera2?\s*(\d+)/i.exec(e);return t?Number(t[1]):Number.POSITIVE_INFINITY}function Je(e){let t={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,i)=>({id:n.deviceId,kind:Ye(n.label),index:Ze(n.label),i})).filter(n=>t[n.kind]<9).sort((n,i)=>t[n.kind]-t[i.kind]||n.index-i.index||n.i-i.i).map(n=>n.id)}var pt="sekyro.doc.camera";function $e(){try{let e=globalThis.localStorage?.getItem(pt);return typeof e=="string"&&e!==""?e:null}catch{return null}}function ye(e){try{e===null?globalThis.localStorage?.removeItem(pt):globalThis.localStorage?.setItem(pt,e)}catch{}}var rt=(e,t)=>Array.isArray(e?.focusMode)&&e.focusMode.includes(t);function bt(e,t,n){if(!rt(e,"single-shot"))return null;let i=o=>Math.min(1,Math.max(0,Number.isFinite(o)?o:.5));return{focusMode:"single-shot",pointsOfInterest:[{x:i(t),y:i(n)}]}}function xi(e,t,n,i){if(!Number.isFinite(e)||!Number.isFinite(t)||n.width<=0||n.height<=0||i.width<=0||i.height<=0)return null;let o=Math.max(n.width/i.width,n.height/i.height),s=i.width*o,r=i.height*o,c=(e-n.left+(s-n.width)/2)/s,a=(t-n.top+(r-n.height)/2)/r;return{x:Math.min(1,Math.max(0,c)),y:Math.min(1,Math.max(0,a))}}function ke(e,t,n,i=st){let o=e?.zoom?.min,s=e?.zoom?.max;if(typeof s!="number"||s<=1)return 1;let r=n==="ID-3"?i.fillDistanceM.id3:i.fillDistanceM.id1,c=e?.focusDistance?.min,a;if(typeof c=="number"&&c>0&&c<1){if(a=c*(1+i.focusMarginFrac)/r,a<=1.05)return 1}else{if(Math.min(t.width,t.height)<i.zoomMinSourcePx)return 1;a=i.zoomNoFocusInfo}let l=Math.min(a,i.zoomMax,s);typeof o=="number"&&(l=Math.max(l,o));let u=e?.zoom?.step;return typeof u=="number"&&u>0&&(l=Math.round(l/u)*u),l>1.01?Number(l.toFixed(2)):1}function gt(e){try{return e.getVideoTracks?.()[0]}catch{return}}function Me(e){if(e!==null)for(let t of e.getTracks())t.stop()}function qe(e){try{let t=gt(e)?.getCapabilities?.();return!Array.isArray(t?.focusMode)||t.focusMode.includes("continuous")}catch{return!0}}var ti=3;async function xe(e){let t=s=>({audio:!1,video:{...s,width:{ideal:e.base.width},height:{ideal:e.base.height}}}),n=s=>e.getUserMedia(t({deviceId:{exact:s}})),i=()=>e.getUserMedia(t({facingMode:{ideal:"environment"}}));if(e.lensSelection){let s=$e();if(s!==null)try{return{stream:await n(s),lens:"stored"}}catch{ye(null)}}let o=await i();if(!e.lensSelection||e.enumerateDevices===void 0)return{stream:o,lens:"default"};try{let s=Je(await e.enumerateDevices()).slice(0,ti);if(s.length===0)return{stream:o,lens:"default"};let r=null;for(let c of s){let a=o!==null?gt(o)?.getSettings?.().deviceId:void 0;if(o===null||a!==c){Me(o),o=null;try{o=await n(c)}catch{continue}}if(r??(r=c),qe(o))return ye(c),{stream:o,lens:"selected"}}if(o!==null&&r!==null&&gt(o)?.getSettings?.().deviceId===r)return{stream:o,lens:"selected"};if(Me(o),o=null,r!==null)try{return{stream:await n(r),lens:"selected"}}catch{}return{stream:await i(),lens:"default"}}catch{return{stream:o??await i(),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}),I=e=>Math.min(1,Math.max(0,e));function we(e,t,n,i=.06){let o=Math.max(e.width/n,e.height),s=o*n,r=(e.width-s)/2,c=(e.height-o)/2,a=I((t.x-t.width*i-r)/s),l=I((t.y-t.height*i-c)/o),u=I((t.x+t.width*(1+i)-r)/s),d=I((t.y+t.height*(1+i)-c)/o);return{x:a,y:l,width:u-a,height:d-l}}function ve(e,t,n={}){let i=n.edgePeakFrac??0,{width:o,height:s,data:r}=e;if(o<=0||s<=0)return Z;let c=I(t.x),a=I(t.y),l={x:c,y:a,width:Math.max(0,I(t.x+t.width)-c),height:Math.max(0,I(t.y+t.height)-a)};if(l.width<=0||l.height<=0)return Z;let u=l.x*o,d=l.y*s,m=(l.x+l.width)*o,h=(l.y+l.height)*s,f=(m-u)*.15,g=(h-d)*.15,y=(p,b,T)=>Math.min(T,Math.max(b,p)),x=y(Math.floor(u-f),0,o-1),w=y(Math.floor(d-g),0,s-1),E=y(Math.ceil(m+f),x+1,o),v=y(Math.ceil(h+g),w+1,s),D=Math.max(1,Math.ceil(Math.max(E-x,v-w)/320)),M=Math.floor((E-x+D-1)/D),_=Math.floor((v-w+D-1)/D);if(M<3||_<3)return Z;let k=new Int32Array(M*_);for(let p=0;p<_;p++){let b=w+p*D;for(let T=0;T<M;T++){let C=(b*o+x+T*D)*4;k[p*M+T]=(r[C]??0)*77+(r[C+1]??0)*150+(r[C+2]??0)*29>>8}}let F=(p,b)=>(p-b-.5)/D,R=F(u,x),A=F(m,x),B=F(d,w),U=F(h,w),Mt=(m-u)/D,kt=(h-d)/D,xt=y(Math.ceil(R),0,M-1),Ce=y(Math.floor(A),xt,M-1),Dt=y(Math.ceil(B),0,_-1),Fe=y(Math.floor(U),Dt,_-1),wt=0,vt=0,H=0,St=0,_t=0,K=0;for(let p=Dt;p<=Fe;p++)for(let b=xt;b<=Ce;b++){let T=k[p*M+b];if(wt+=T,T>=248&&vt++,H++,b>=1&&b<M-1&&p>=1&&p<_-1){let C=k[p*M+b-1]+k[p*M+b+1]+k[(p-1)*M+b]+k[(p+1)*M+b]-4*T;St+=C,_t+=C*C,K++}}let Ae=H>0?wt/H:0,Rt=H>0?vt/H:0,Tt=K>0?St/K:0,Le=K>0?Math.max(0,_t/K-Tt*Tt):0,V=new Float64Array(M),W=new Float64Array(_);for(let p=0;p<_;p++)for(let b=1;b<M-1;b++)V[b]=V[b]+Math.abs(k[p*M+b+1]-k[p*M+b-1]);for(let p=1;p<_-1;p++)for(let b=0;b<M;b++)W[p]=W[p]+Math.abs(k[(p+1)*M+b]-k[(p-1)*M+b]);let O=at(V,!0,R,i),P=at(V,!1,A,i),G=at(W,!0,B,i),z=at(W,!1,U,i),Ct=(P.position-O.position)/Mt,Ft=(z.position-G.position)/kt,Ie=Ft>0?Ct/Ft:0,Ee=((O.position+P.position)/2-(R+A)/2)/Mt,Oe=((G.position+z.position)/2-(B+U)/2)/kt,At=De(V),Lt=De(W),Pe=At<=0||Lt<=0?0:Math.min(Math.min(O.value,P.value)/At,Math.min(G.value,z.value)/Lt),q=(p,b)=>b+(p+.5)*D,It=Rt,Et=0;{let p=(P.position-O.position)*.06,b=(z.position-G.position)*.06,T=y(Math.ceil(O.position+p),0,M-1),C=y(Math.floor(P.position-p),0,M-1),Ge=y(Math.ceil(G.position+b),0,_-1),Ot=y(Math.floor(z.position-b),0,_-1),Pt=0,tt=0,Gt=0;for(let N=Ge;N<=Ot;N++)for(let Q=T;Q<=C;Q++){tt++;let X=k[N*M+Q];X>=248&&Pt++;let ze=Q+2<=C?k[N*M+Q+2]:X,Ne=N+2<=Ot?k[(N+2)*M+Q]:X;(Math.abs(ze-X)>=24||Math.abs(Ne-X)>=24)&&Gt++}tt>=16&&(It=Pt/tt,Et=Gt/tt)}return{brightness:Ae,glare:Rt,cardGlare:It,sharpness:Le,fill:Ct,shape:Ie,content:Et,offsetX:Ee,offsetY:Oe,edgeConfidence:Pe,box:{left:q(O.position,x),right:q(P.position,x),top:q(G.position,w),bottom:q(z.position,w)}}}function at(e,t,n,i){let o=e.length,s=Math.max(1,Math.floor(o*.45)),r=t?1:Math.max(1,o-1-s),c=t?Math.min(o-2,s):o-2,a=r;for(let h=r;h<=c;h++)e[h]>e[a]&&(a=h);if(i>0&&i<1){let h=e[a]*i,f=a,g=Math.abs(a-n);for(let y=r;y<=c;y++){let x=e[y];if(x<h||x<(e[y-1]??0)||x<(e[y+1]??0))continue;let w=Math.abs(y-n);w<g&&(f=y,g=w)}a=f}let l=a>0?e[a-1]:0,u=e[a],d=a<o-1?e[a+1]:0,m=l+u+d;return{position:m>0?a+(d-l)/m:a,value:u}}function De(e){if(e.length<3)return 0;let t=0;for(let n=1;n<e.length-1;n++)t+=e[n];return t/(e.length-2)}function Se(e){let t=e.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 wi(e){let t=e!==null&&typeof e=="object"?e:{},n={...J};for(let i of Object.keys(J)){let o=t[i];typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=1e6&&(n[i]=o)}return n}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,n){let i=this.t,o=i.shapeTolerance<=0||Math.abs(t.shape-1)<=i.shapeTolerance,s=t.edgeConfidence>=i.edgeConfidenceMin&&o&&t.content>=i.contentMin,r=t.fill>=i.fillMin&&t.fill<=i.fillMax,c=Math.abs(t.offsetX)<=i.offsetMax&&Math.abs(t.offsetY)<=i.offsetMax,a=t.cardGlare<=i.glareMax,l=t.sharpness>=i.sharpnessMin,u=this.last;this.last={fill:t.fill,offsetX:t.offsetX,offsetY:t.offsetY,at:n};let d=u!==null&&i.steadyRefMs>0?Math.min(3,Math.max(1,(n-u.at)/i.steadyRefMs)):1,m=s&&a&&l&&t.fill>=i.steadyFillMin&&t.fill<=i.steadyFillMax&&u!==null&&Math.abs(t.fill-u.fill)<=i.steadyFillDelta*d&&Math.abs(t.offsetX-u.offsetX)<=i.steadyOffsetDelta*d&&Math.abs(t.offsetY-u.offsetY)<=i.steadyOffsetDelta*d,h=s&&r&&c&&a&&l,f;if(s?a?t.fill<i.fillMin?f="too_small":t.fill>i.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=n)),this.goodSince??(this.goodSince=n),n-this.goodSince>=i.lockMs)return{detected:s,ready:!0,via:"good",blocker:"locking"};let g=this.steadySince!==null&&n-this.steadySince>=i.steadyMs;return{detected:s,ready:g,via:g?"steady":null,blocker:"locking"}}if(this.goodSince=null,m){this.steadySince??(this.steadySince=n);let g=n-this.steadySince>=i.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 $=null;async function ei(e){return $===null&&($=(await import("./detector-scanic-YCDNLCGV.js")).detectQuad),$(e)}async function ii(e){let t=jt(e);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 Ni(){$===null&&import("./detector-scanic-YCDNLCGV.js").then(e=>{$=e.detectQuad}).catch(()=>{})}var ni=Object.freeze({LOW:3,MID:5,HIGH:6}),yt=Object.freeze({manualShutterMs:6e3,detectedNoLockMs:1950});function Qi(e){let t=e!==null&&typeof e=="object"?e:{},n=(i,o,s)=>typeof i=="number"&&Number.isFinite(i)&&i>=o&&i<=s?i:void 0;return{manualShutterMs:n(t.manualShutterMs,1e3,6e4)??yt.manualShutterMs,detectedNoLockMs:n(t.steadyMs,300,3e4)!==void 0?t.steadyMs+(n(t.lockMs,0,1e4)??450):yt.detectedNoLockMs}}var _e=class e{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=e.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 nt;this.lastFeedbackKey=null;this.lastQuad=null;this.lastDetect=null;this.opts=t,this.gate=new $t(t.format??"ID-1",t.thresholds);let n=t.deviceClass??Bt(Qt());this.deviceClass=n,this.camera=t.camera??st,this.shutterTuning=t.shutter??yt,this.guideTuning=t.guideLock??J,this.guideLock=new ct(this.guideTuning),this.cadenceMs=1e3/ni[n]}on(t,n){let i=this.handlers.get(t);return i||(i=new Set,this.handlers.set(t,i)),i.add(n),()=>i?.delete(n)}emit(t,n){for(let i of[...this.handlers.get(t)??[]])i(n)}async start(){let t=++this.attempt;this.gate.reset(),this.resetSide(),this.feedback.reset(),this.lastFeedbackKey=null,this.lastGuidance=null,this.capturing=!1,this.setState("preflight");try{let n=this.opts.getUserMedia??(s=>navigator.mediaDevices.getUserMedia(s));this.setState("acquiring");let i=this.opts.enumerateDevices??(this.opts.getUserMedia===void 0&&typeof navigator<"u"&&navigator.mediaDevices?.enumerateDevices?()=>navigator.mediaDevices.enumerateDevices():void 0),o=await xe({getUserMedia:n,...i!==void 0?{enumerateDevices:i}:{},lensSelection:this.camera.lensSelection,base:oe});if(this.stream=o.stream,Nt(this.stream),t!==this.attempt){for(let s of this.stream.getTracks())s.stop();return}if(this.opts.upgradeResolution!==!1&&await this.upgradeResolution(),t!==this.attempt||(await this.applyFocusAndZoom(),t!==this.attempt))return;this.opts.video.srcObject=this.stream,await this.opts.video.play().catch(()=>{}),this.setState("positioning"),this.scheduleTick(t)}catch(n){let i=zt(n);this.setState("error"),this.emit("error",{kind:i,retryable:!0})}}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,n=this.lastDetect?.width??Math.max(1,t.videoWidth),i=this.lastDetect?.height??Math.max(1,t.videoHeight),o=this.lastQuad??this.lastGuideQuad??{topLeft:{x:0,y:0},topRight:{x:n,y:0},bottomRight:{x:n,y:i},bottomLeft:{x:0,y:i}},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:o,{width:n,height:i,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 n=(this.opts.format??"ID-1")==="ID-3"||this.opts.side==="single"?"single":this.opts.side==="verso"?"verso":"recto",i=t.report(n,this.stats.via,(this.opts.now??(()=>performance.now()))());return i===null?{}:{ocr:i}}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 n=t.width/Math.max(1,t.height),i=this.opts.guide;if(i!==void 0&&i.viewAspect>0){let c={width:i.viewAspect,height:1},a={x:i.rect.x*i.viewAspect,y:i.rect.y,width:i.rect.width*i.viewAspect,height:i.rect.height};return we(c,a,n,0)}let o=Kt(this.opts.format??"ID-1").center,s=.86,r=s*n/o;return r>.84&&(r=.84,s=r*o/n),{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=e.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 n=this.videoTrack();if(n===null||this.zoom<=1)return;let i=this.focusCaps(),o=typeof i?.zoom?.min=="number"?Math.max(i.zoom.min,1):1;this.zoom=o,this.stats.zoomFallbackAtMs=Math.round(t-(this.positioningSince??t)),this.guideLock.reset(),this.gate.reset(),n.applyConstraints({advanced:[{zoom:o}]}).catch(()=>{})}offerShutter(t,n){this.shutterOffered||(this.shutterOffered=!0,this.stats.shutterAtMs=Math.round(n-(this.positioningSince??n)),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.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 n=t.getSettings?.()??{},i=ae(t.getCapabilities?.(),{width:n.width??0,height:n.height??0},this.deviceClass,{width:this.camera.width,height:this.camera.height});i!==null&&await t.applyConstraints(i)}catch{}}focusCaps(){try{return this.videoTrack()?.getCapabilities?.()??null}catch{return null}}async applyFocusAndZoom(){let t=this.videoTrack();if(t===null)return;let n=this.focusCaps();this.camera.continuousFocus&&rt(n,"continuous")&&await t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{});let i={width:0,height:0};try{let s=t.getSettings?.()??{};i={width:s.width??0,height:s.height??0}}catch{}let o=ke(n,i,this.opts.format??"ID-1",this.camera);if(o>1)try{await t.applyConstraints({advanced:[{zoom:o}]}),this.zoom=o}catch{this.zoom=1}}async focusAt(t,n){let i=this.videoTrack(),o=bt(this.focusCaps(),t,n);if(!(i===null||o===null))try{await i.applyConstraints({advanced:[o]}),(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,n){let i=this.camera.refocusBeforePhotoMs,o=this.videoTrack();if(i<=0||o===null||n.width<=0||n.height<=0)return;let s=L(t),r=bt(this.focusCaps(),(s.x+s.width/2)/n.width,(s.y+s.height/2)/n.height);if(r!==null)try{await o.applyConstraints({advanced:[r]});let c=this.opts.setTimer??setTimeout;await new Promise(a=>{c(()=>a(),i)})}catch{}}videoTrack(){try{return this.stream?.getVideoTracks?.()[0]??null}catch{return null}}async takeStill(t,n,i){if(this.opts.captureStill!==void 0)return this.opts.captureStill(this.opts.video,t,n);let o=this.opts.format??"ID-1",s=this.videoTrack();if(i&&this.opts.photoCapture!==!1&&this.deviceClass!=="LOW"&&!this.torchOn&&s!==null&&fe(s)){await this.refocusOn(t,n);let r=await be(this.opts.video,t,n,o,{track:s,detect:this.detector(),detectWidth:et});if(this.restoreContinuous(),r!==null)return r}return ge(this.opts.video,t,n,o)}detector(){return this.opts.detect??((this.opts.format??"ID-1")==="ID-3"?ii:ei)}setState(t){this.state=t,this.emit("statechange",{state:t})}scheduleTick(t){let n=this.opts.setTimer??setTimeout;this.timer=n(()=>{this.tick(t)},this.cadenceMs)}async tick(t){if(t!==this.attempt||this.state!=="positioning"||this.capturing)return;let n=this.opts.now??(()=>performance.now()),i=this.opts.grabDetectFrame??Te,o=this.detector(),s=i(this.opts.video,et);if(s===null){this.scheduleTick(t);return}let r=null;try{r=await o(s)}catch{r=null}if(t!==this.attempt)return;let c=r!==null?lt(s,r):s,a=n(),l={sharpness:j(c),exposure:Ht(c),meanLuma:Ut(c),specularFraction:ee(c)},u=ie({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"?ve(s,this.guideRegion(s),{edgePeakFrac:this.guideTuning.edgePeakFrac}):Z,f=this.guideLock.tick(h,a);this.lastGuideQuad=f.detected?Se(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 R=u.lighting!=="ok"?u.lighting:u.glare!=="ok"?"glare":u.blur!=="ok"?"blurry":"steadying";y.qualityBlockers[R]=(y.qualityBlockers[R]??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<=ui?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 E=a-(this.lastSeenAt??this.positioningSince);this.zoom>1&&this.camera.zoomFallbackMs>0&&E>=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=qt(u);u.framing!=="ok"&&f.detected&&(v=li(f.blocker,h.brightness<this.guideTuning.darkBrightness)),v==="blurry"&&r!==null&&si(r,s,this.opts.format??"ID-1")>=this.camera.focusFarFillFrac&&(v="focus_far"),v==="sensing"&&this.zoom>1&&this.camera.noDocFarHintMs>0&&E>=this.camera.noDocFarHintMs&&(v="focus_far");let D=this.feedback.tick(v,a);if(D.key!==this.lastFeedbackKey&&(this.lastFeedbackKey=D.key,this.emit("feedback",D)),d.guidanceKey!==this.lastGuidance&&(this.lastGuidance=d.guidanceKey,this.emit("guidance",{key:d.guidanceKey})),this.capturing)return;let M=g?.suspendQuality!==!0,_=M&&d.ready&&r!==null,k=M&&f.ready&&this.lastGuideQuad!==null,F=this.lastOcrReady;if(F!==null&&this.opts.autoCapture!==!1){let R=this.feedback.force("processing",a);this.lastFeedbackKey=R.key,this.emit("feedback",R);let A=j(lt(s,F.quad));await this.fire(t,F.quad,{width:s.width,height:s.height,tickSharpness:A},F.via);return}if((_||k)&&this.opts.autoCapture!==!1){let R=this.feedback.force("processing",a);this.lastFeedbackKey=R.key,this.emit("feedback",R);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,n,i,o){this.capturing=!0;let s=this.opts.grabDetectFrame??Te,r=this.opts.setTimer??setTimeout,c={width:i.width,height:i.height};try{let a={still:await this.takeStill(n,c,!0),sharpness:i.tickSharpness};if(t!==this.attempt)return;let l=a.still.source==="photo"?0:ri;for(let m=0;m<l;m++){if(await new Promise(g=>{r(()=>g(),ai)}),t!==this.attempt)return;let h=s(this.opts.video,et);if(h===null)continue;let f=j(lt(h,n));if(f>a.sharpness*ci){let g=await this.takeStill(n,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&&o!=="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,(o==="text_lock"||o==="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=o,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=o==="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,(o==="text_lock"||o==="live_mrz")&&this.opts.ocr?.rearmFace(),this.scheduleTick(t)}}ocrTick(t,n,i,o,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,x;m&&n!==null?x=oi(L(n),g,y,l,u):x=Yt(f,c.bandTop,u);let w=m?s.glare==="ok":i.cardGlare<=this.guideTuning.glareMax,E=m?s.blur==="ok":i.sharpness>=this.guideTuning.sharpnessMin,v=c.tick({atMs:r,video:a,mrzFace:m||this.opts.side==="verso"||this.opts.side==="single",present:m||n!==null||o,card:f,band:x,portrait:u>l,glareOk:w,sharpOk:E});if(v.ready&&v.via!==void 0){let D=m?n??Re(h,t):this.lastGuideQuad??Re(h,t);this.lastOcrReady={quad:D,via:v.via}}else this.lastOcrReady=null;return v}};function oi(e,t,n,i,o){let s=Math.min(i,e.width*1.06*t),r=Math.min(o,Math.max(e.height*1.6*n,s/5)),c=(e.y+e.height/2)*n,a=Math.max(0,Math.min(i-s,(e.x-e.width*.03)*t)),l=Math.max(0,Math.min(o-r,c-r/2));return{x:a,y:l,w:s,h:r}}function Re(e,t){let n=e.x*t.width,i=e.y*t.height,o=(e.x+e.width)*t.width,s=(e.y+e.height)*t.height;return{topLeft:{x:n,y:i},topRight:{x:o,y:i},bottomRight:{x:o,y:s},bottomLeft:{x:n,y:s}}}function si(e,t,n){let i=L(e);return t.width<=0||t.height<=0?0:n==="ID-3"?i.width/t.width:i.width*i.height/(t.width*t.height)}var ri=2,ai=260,ci=1.08;function Te(e,t){let n=e.videoWidth,i=e.videoHeight;if(n===0||i===0)return null;let o=Math.min(1,t/n),s=Math.round(n*o),r=Math.round(i*o),c=document.createElement("canvas");c.width=s,c.height=r;let a=c.getContext("2d",{willReadFrequently:!0});return a===null?null:(n/Math.max(1,s)>4&&(a.imageSmoothingQuality="high"),a.drawImage(e,0,0,s,r),a.getImageData(0,0,s,r))}function lt(e,t){let n=[t.topLeft.x,t.topRight.x,t.bottomRight.x,t.bottomLeft.x],i=[t.topLeft.y,t.topRight.y,t.bottomRight.y,t.bottomLeft.y],o=Math.max(0,Math.floor(Math.min(...n))),s=Math.max(0,Math.floor(Math.min(...i))),r=Math.min(e.width,Math.ceil(Math.max(...n))),c=Math.min(e.height,Math.ceil(Math.max(...i))),a=Math.max(1,r-o),l=Math.max(1,c-s),u=new Uint8ClampedArray(a*l*4);for(let d=0;d<l;d++){let m=((s+d)*e.width+o)*4;u.set(e.data.subarray(m,m+a*4),d*a*4)}return{data:u,width:a,height:l,colorSpace:e.colorSpace}}function li(e,t){return e==="glare"?"glare":e==="too_small"?"too_far":e==="too_big"?"too_close":t?"too_dark":e==="blurry"?"blurry":e==="off_center"?"edge_clipped":e==="no_card"?"sensing":"hold_still"}var ui=1200;export{it as a,qt as b,nt as c,Qe as d,ee as e,Be as f,ie as g,st as h,ki as i,Ye as j,Je as k,pt as l,$e as m,ye as n,rt as o,bt as p,xi as q,ke as r,qe as s,ti as t,xe as u,Z as v,we as w,ve as x,Se as y,J as z,wi as A,ct as B,Ni as C,ni as D,yt as E,Qi as F,_e as G,oi as H,ri as I,ai as J};
@@ -0,0 +1 @@
1
+ var v=["session.completed","session.failed","session.review_pending","session.expired","session.cancelled"],u=new Set([0,1,2,3]),a="sekyro-verify",E="width=480,height=720,noopener=false",f=new Set(v);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,a,E);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:l,level:s}=o.data,i={source:p,version:d,event:c,sessionId:l};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{v as a,S as b,k as c};
@@ -1 +1 @@
1
- import{d as j,h as be,i as he,j as ye,l as Se}from"./chunk-G6LKLN4U.js";import{f as ge}from"./chunk-TDLIXFDT.js";import{l as fe}from"./chunk-ETY6SAAZ.js";import{a as me,e as pe}from"./chunk-HAO6EQTH.js";var Ge={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 qe(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=Ge[p],S=l&&l>0?Math.min(b.maxLongEdge,l):b.maxLongEdge;return{tier:p,...b,maxLongEdge:S}}function Me(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),qe(t)}function He(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 Xe(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 Ve(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 ke(e,t,n,r,i){if(t<=0||n<=0)return null;let{width:l,height:s}=Xe(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=He(i,r.qMin,r.qMax),{blob:b,quality:S}=await Ve(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 $(e){let t=Me(Math.max(e.width,e.height)),n=await ke(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 dt(e){let t=await createImageBitmap(e);try{return await $(t)}finally{t.close()}}var pt=250,ft=.6,gt=1800,bt=6e3,ht=2e3,De=.16;function Z(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 we=e=>e==="recto"?"verso":"recto",Ce=e=>e.phase==="framing"||e.phase==="locking"||e.phase==="flipCue"||e.phase==="reaskRecto",ee=e=>(e.captured.recto!==void 0?1:0)+(e.captured.verso!==void 0?1:0)+e.pending.length;function J(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 Ye(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(!Ce(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 Qe(e,t){if(!Ce(e)||e.manualShutter)return e;let n=t-e.lastReportAt>=2e3,r=t-e.lastCaptureAt>=6e3;return n||r?{...e,manualShutter:!0}:e}function Ke(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||ee({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 Re(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:we(n),needFlip:!0,flipTimeoutSpent:!0,goodSince:void 0,manualShutter:!0,notice:"same_face",lastCaptureAt:-1,lastReportAt:-1}:e}function je(e,t,n){if(!e.pending.includes(t))return e;if(e.captured[n]!==void 0)return Re(e,t,n);let r=e.pending.filter(c=>c!==t),i={...e,pending:r,captured:{...e.captured,[n]:t}};if(ee(i)!==1||e.layout==="singlePage")return i;let l=we(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 $e(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"&&ee({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 xe(e,t){switch(t.type){case"report":return Ye(J(e,t.at),t.report,t.at);case"tick":return Qe(J(e,t.at),t.at);case"captured":return Ke(J(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 je(e,t.id,t.side);case"duplicate":return Re(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 $e(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{...Z(e.layout,-1),lastCaptureAt:-1,lastReportAt:-1};default:return e}}function Je(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 Ze(e,t=!1){let{detectMrzBand:n}=await import("./mrz-band-VYHOTDHY.js");return Je(n,e,t)}async function te(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 Ze(u.getImageData(0,0,t,l),r))}finally{s.width=0,s.height=0}}async function St(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 ne=(e,t,n)=>Math.min(n,Math.max(t,Math.round(e))),V=e=>Math.round(Math.min(1,Math.max(0,e))*1e4)/1e4;async function ve(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:ne(n.lineCount,2,3),checkDigitsValid:!0,stillConfirmed:s.valid&&s.digest===n.digest,band:[V(u[0]),V(u[1]),V(Math.min(u[2],1-u[0])),V(Math.min(u[3],1-u[1]))],digest:n.digest,framesToValid:ne(n.framesToValid,1,1e3),msToValid:ne(n.msToValid,0,12e4)}}function kt(e){let t=null;return e?.then(n=>{t=n}),()=>t}var et=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]),tt=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 Le(e,t=globalThis){let n=t.WebAssembly?.validate;if(typeof n!="function")return{ok:!1,reason:"simd"};try{if(!n.call(t.WebAssembly,et)||!n.call(t.WebAssembly,tt))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 _e(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 Te(){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 Ee(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 Te()}catch{return Te()}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((M,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:M,...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",re=e=>e!==null&&typeof e=="object"?e:{},v=(e,t,n,r)=>typeof e=="number"&&Number.isFinite(e)&&e>=t&&e<=n?e:r,Oe=(e,t)=>typeof e=="boolean"?e:t,Pe=e=>{let t=typeof e=="string"?/^sekyro-ocr-(\d{1,4})$/.exec(e):null;return t?Number(t[1]):Number.POSITIVE_INFINITY};function Ae(e,t={}){let n=re(e),r=re(n.liveMrz),i=re(n.frontLock),l=Pe(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"&&Pe(d.minEngine??U)<=l,b=ye,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:Oe(r.hint,!0),stillConfirm:Oe(r.stillConfirm,!0)}:null,I=he,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 Be(e,t){return e.enabled?!(t.probe??Le)({minDeviceMemoryGb:e.load.minDeviceMemoryGb}).ok||(t.slow??_e)()?{ok:!1,reason:"unsupported"}:{ok:!0,engine:Ee({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 nt(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 W=e=>e===void 0||!Number.isFinite(e)?void 0:Math.min(6e5,Math.max(0,Math.round(e))),oe=(e,t,n)=>e===void 0||!Number.isFinite(e)?void 0:Math.min(n,Math.max(t,Math.round(e)));function Ie(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:oe(t?.reads??0,0,1e4)??0,browser:e.browser??nt()},s=(u,c)=>{c!==void 0&&(l[u]=c)};return s("format",t?.format),s("framesToValid",oe(t?.framesToValid,1,1e4)),s("msToValid",W(t?.msToValid)),s("framesToLock",oe(t?.framesToLock,1,1e4)),s("msToLock",W(t?.msToLock)),s("msToCapture",W(e.msToCapture)),s("readP50Ms",W(t?.readP50Ms)),s("readP90Ms",W(t?.readP90Ms)),s("deviceClass",t?.deviceClass),n!==null&&(s("warmupMs",W(n.warmupMs)),s("downloadMs",W(n.downloadMs)),s("cached",n.cached)),s("stillConfirmed",e.stillConfirmed),s("typeMismatch",e.typeMismatch),l}function ae(e,t){return e===void 0?!1:t==="passport"?e!=="TD3":e==="TD3"}var rt=2;async function ot(e){let t=await import("./capture-session-doc-GK6G7JOI.js");return new t.CaptureSessionDoc(e)}function at(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 it(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 Nt(){import("./capture-session-doc-GK6G7JOI.js").then(e=>e.warmDocDetector()).catch(()=>{})}function Ut(e){return st(e,{}).handle}function st(e,t){let n=me(),r=pe({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=Z(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=[],M=t.webOcr!==void 0?Ae(t.webOcr.captureDocument,{mode:e.liveMrz?.mode??"auto"}):null,A=null,F=M===null||!M.enabled?"off":null,G=null,q=null,ie=new WeakMap,Y="";if(M!==null&&M.enabled&&t.webOcr!==void 0){let o=t.webOcr,a=Be(M,{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 Se({textLock:M.textLock,liveMrz:M.liveMrz});G=m;let y=a.engine;y.ready.then(L=>{F=L,typeof L!="string"&&S&&m.setEngine(y)})}else F=a.reason}let z=o=>{let a=JSON.stringify(o);a!==Y&&(Y=a,n.emit("mrz",o))},se=(o,a)=>{let m=t.webOcr?.reports;if(m===void 0||M===null||o===void 0)return;let y=o.format==="ID-3"||o.side==="single"?"single":o.side==="verso"?"verso":"recto",L=y!=="recto"?M.liveMrzArm??M.frontLockArm:M.frontLockArm;if(L===null||Math.random()>=M.reportSampleRate)return;let _=o.via==="live_mrz"?q:null,x=()=>{let E=_?.value??null;m([Ie({arm:L,capture:y,assist:o.ocr??null,load:L==="control"?"off":F,...o.msToCapture!==void 0?{msToCapture:o.msToCapture}:{},...E!==null&&E.stillConfirmed!==void 0?{stillConfirmed:E.stillConfirmed}:{},...a!==void 0?{typeMismatch:ae(a.format,e.documentType==="passport"?"passport":"card")}:{}})])};_!==null&&_.value===null?Promise.race([_.promise,new Promise(E=>setTimeout(E,3e3))]).then(x):x()},N=o=>{!S||o===f||(f=o,r.setActive(o==="starting"||o==="scanning"),n.emit("state",o))},We=(o,a)=>a===void 0?null:u?"single":o.captured.recto===a?"recto":o.captured.verso===a?"verso":null,Fe=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:We(o,o.lastShot),manualShutter:o.manualShutter,torchAvailable:p?.torchAvailable()??!1,torch:d}),ue=()=>{let o=p;o!==null&&o.captureNow().catch(()=>R({type:"captureFailed",at:s()}))};function R(o){if(!S)return;let a=c;c=xe(c,o),c.phase==="capturing"&&a.phase!=="capturing"&&Promise.resolve().then(ue),c.phase==="result"&&a.phase!=="result"&&(N("done"),le());let m=Fe(c),y=JSON.stringify(m);y!==g&&(g=y,n.emit("scan",m))}function le(){O!==null&&clearInterval(O),O=null;for(let o of P.splice(0))o();p?.destroy(),p=null,r.setActive(!1)}let ce=()=>p?.captureReport?.(),Q=!1,de=(o,a)=>{if(!(o===void 0||t.onFaceReport===void 0))try{t.onFaceReport(o,a)}catch{}},H=o=>{Y="",!(p===null||c.phase==="reading"||c.phase==="result")&&(Q=!1,p.rearm(u?"single":c.current??o))},ze=async(o,a,m,y)=>{if(q=null,y!==void 0&&A!==null&&M?.liveMrz?.hint===!0){let D={promise:ve(A,o,y,{engine:U,detectorLimit:M.liveMrz.detectorLimit}).catch(()=>null),value:null};D.promise.then(k=>{D.value=k}),q=D}y!==void 0&&ae(y.format,e.documentType==="passport"?"passport":"card")&&z({state:"mismatch",format:y.format});let L=ce();de(L,"captured"),Q=!0,se(L,y);let _=m===void 0?C:m===null?null:{quad:at(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 Ne(o,a,_,E,q)}finally{x.decoded!==null&&(await x.decoded)?.close()}},Ne=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 D=await(t.measureSharpness!==void 0?t.measureSharpness(o,m):y().then(k=>k===null?-1:be(k,j(m?.quad??null,m?.inStill===!0?k:{width:m?.frameWidth??0,height:m?.frameHeight??0},k)))).catch(()=>-1);if(!S)return;if(Number.isFinite(D)&&D>=0&&D<l){w=!0;let k=u?"recto":c.current??(c.captured.recto===void 0?"recto":"verso");R({type:"readFailed",side:k,id:_,issue:"blurry"}),H(k);return}}w=!1;let x;if(u)x="single";else{let D=c.current,k=await(t.classify!==void 0?t.classify(o):y().then(X=>X===null?D??"recto":m?.inStill===!0?te(X,480,null,!0):te(X,480,j(m?.quad??null,{width:m?.frameWidth??0,height:m?.frameHeight??0},X)))).catch(()=>D??"recto");if(!S)return;if(c.captured[k]!==void 0&&h<rt){h+=1,R({type:"duplicate",id:_,side:k}),H(k==="recto"?"verso":"recto");return}x=c.captured[k]!==void 0&&D!==void 0?D:k,h=0,R({type:"classified",id:_,side:x})}let E=x==="verso"?"verso":"recto";try{let D=t.encode!==void 0?await t.encode(o):await y().then(k=>{if(k===null)throw new Error("the still could not be decoded");return $(k)});if(!S)return;L!==null&&ie.set(D.blob,L),n.emit("captured",{image:D.blob,side:x,documentType:e.documentType,...e.issuer!==void 0?{issuer:e.issuer}:{},width:D.width,height:D.height,previewDataUrl:a}),t.deferRead!==!0&&R({type:"readOk",side:E})}catch{R({type:"readFailed",side:E,id:_,issue:"technical"}),n.emit("error",{kind:"generic",retryable:!0})}H(E==="recto"?"verso":"recto")},Ue=o=>{P.push(o.on("statechange",({state:a})=>{a==="preflight"||a==="acquiring"?N("starting"):a==="positioning"?N("scanning"):a==="captured"?N("captured"):a==="error"&&N("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"?z({state:"fallback",reason:m.reason}):m.state==="valid"?z({state:"valid",format:m.format}):m.state==="reading"?z({state:"reading",...m.format?{format:m.format}:{},...m.coach?{coach:m.coach}:{}}):z({state:"searching"}));let y=a.quad===null?0:it(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})=>n.emit("error",{kind:fe(a),retryable:m})),o.on("artifacts",a=>{ze(a.keyframe,a.previewDataUrl,a.docRegion,a.liveMrz)}))},K=()=>(b??(b=(async()=>{if(S){if(p===null){let o=await(t.createEngine??ot)({...t.engineOptions??{},...B!==void 0?{guide:B}:{},video:e.video,format:ge(e.documentType),side:u?"single":e.side??"recto",autoCapture:!1,...G!==null?{ocr:G}:{}});if(!S){o.destroy();return}p=o,Ue(o);let a=t.tickMs??500;a>0&&(O=setInterval(()=>R({type:"tick",at:s()}),a))}R({type:"clockRestart"}),M!==null&&M.liveMrzArm==="live"&&(F==="unsupported"||F==="off")&&z({state:"fallback",reason:F}),await p.start()}})().finally(()=>{b=null})),b);return{handle:{get state(){return f},on:(o,a)=>n.on(o,a),start:K,retry:()=>{if(p===null&&c.phase==="result"){R({type:"retake"}),h=0,w=!1,K();return}if(p!==null&&f!=="error"){R({type:"retake"}),h=0,w=!1,p.rearm(u?"single":void 0);return}K()},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:ue,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=ce();!Q&&o!==void 0&&o.ticks>0&&de(o,"abandoned"),se(o,void 0)}S=!1,le(),G?.setEngine(null),A?.dispose(),A=null,n.clear()}},setFlowState:o=>{(c.phase==="reading"||c.phase==="result")&&N(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=>ie.get(o.image)?.value??null}}export{dt as a,pt as b,ft as c,gt as d,bt as e,ht as f,De as g,Z as h,xe as i,Je as j,Ze as k,St as l,ve as m,kt as n,U as o,Ae as p,Be as q,nt as r,Ie as s,ae as t,rt as u,Nt as v,Ut as w,st as x};
1
+ import{d as j,h as be,i as he,j as ye,l as Se}from"./chunk-G6LKLN4U.js";import{f as ge}from"./chunk-TDLIXFDT.js";import{l as fe}from"./chunk-EF52BRBD.js";import{a as me,e as pe}from"./chunk-GT2ZLGF7.js";var Ge={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 qe(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=Ge[p],S=l&&l>0?Math.min(b.maxLongEdge,l):b.maxLongEdge;return{tier:p,...b,maxLongEdge:S}}function Me(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),qe(t)}function He(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 Xe(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 Ve(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 ke(e,t,n,r,i){if(t<=0||n<=0)return null;let{width:l,height:s}=Xe(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=He(i,r.qMin,r.qMax),{blob:b,quality:S}=await Ve(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 $(e){let t=Me(Math.max(e.width,e.height)),n=await ke(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 dt(e){let t=await createImageBitmap(e);try{return await $(t)}finally{t.close()}}var pt=250,ft=.6,gt=1800,bt=6e3,ht=2e3,De=.16;function Z(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 we=e=>e==="recto"?"verso":"recto",Ce=e=>e.phase==="framing"||e.phase==="locking"||e.phase==="flipCue"||e.phase==="reaskRecto",ee=e=>(e.captured.recto!==void 0?1:0)+(e.captured.verso!==void 0?1:0)+e.pending.length;function J(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 Ye(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(!Ce(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 Qe(e,t){if(!Ce(e)||e.manualShutter)return e;let n=t-e.lastReportAt>=2e3,r=t-e.lastCaptureAt>=6e3;return n||r?{...e,manualShutter:!0}:e}function Ke(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||ee({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 Re(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:we(n),needFlip:!0,flipTimeoutSpent:!0,goodSince:void 0,manualShutter:!0,notice:"same_face",lastCaptureAt:-1,lastReportAt:-1}:e}function je(e,t,n){if(!e.pending.includes(t))return e;if(e.captured[n]!==void 0)return Re(e,t,n);let r=e.pending.filter(c=>c!==t),i={...e,pending:r,captured:{...e.captured,[n]:t}};if(ee(i)!==1||e.layout==="singlePage")return i;let l=we(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 $e(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"&&ee({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 xe(e,t){switch(t.type){case"report":return Ye(J(e,t.at),t.report,t.at);case"tick":return Qe(J(e,t.at),t.at);case"captured":return Ke(J(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 je(e,t.id,t.side);case"duplicate":return Re(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 $e(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{...Z(e.layout,-1),lastCaptureAt:-1,lastReportAt:-1};default:return e}}function Je(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 Ze(e,t=!1){let{detectMrzBand:n}=await import("./mrz-band-VYHOTDHY.js");return Je(n,e,t)}async function te(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 Ze(u.getImageData(0,0,t,l),r))}finally{s.width=0,s.height=0}}async function St(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 ne=(e,t,n)=>Math.min(n,Math.max(t,Math.round(e))),V=e=>Math.round(Math.min(1,Math.max(0,e))*1e4)/1e4;async function ve(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:ne(n.lineCount,2,3),checkDigitsValid:!0,stillConfirmed:s.valid&&s.digest===n.digest,band:[V(u[0]),V(u[1]),V(Math.min(u[2],1-u[0])),V(Math.min(u[3],1-u[1]))],digest:n.digest,framesToValid:ne(n.framesToValid,1,1e3),msToValid:ne(n.msToValid,0,12e4)}}function kt(e){let t=null;return e?.then(n=>{t=n}),()=>t}var et=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]),tt=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 Le(e,t=globalThis){let n=t.WebAssembly?.validate;if(typeof n!="function")return{ok:!1,reason:"simd"};try{if(!n.call(t.WebAssembly,et)||!n.call(t.WebAssembly,tt))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 _e(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 Te(){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 Ee(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 Te()}catch{return Te()}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((M,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:M,...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",re=e=>e!==null&&typeof e=="object"?e:{},v=(e,t,n,r)=>typeof e=="number"&&Number.isFinite(e)&&e>=t&&e<=n?e:r,Oe=(e,t)=>typeof e=="boolean"?e:t,Pe=e=>{let t=typeof e=="string"?/^sekyro-ocr-(\d{1,4})$/.exec(e):null;return t?Number(t[1]):Number.POSITIVE_INFINITY};function Ae(e,t={}){let n=re(e),r=re(n.liveMrz),i=re(n.frontLock),l=Pe(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"&&Pe(d.minEngine??U)<=l,b=ye,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:Oe(r.hint,!0),stillConfirm:Oe(r.stillConfirm,!0)}:null,I=he,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 Be(e,t){return e.enabled?!(t.probe??Le)({minDeviceMemoryGb:e.load.minDeviceMemoryGb}).ok||(t.slow??_e)()?{ok:!1,reason:"unsupported"}:{ok:!0,engine:Ee({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 nt(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 W=e=>e===void 0||!Number.isFinite(e)?void 0:Math.min(6e5,Math.max(0,Math.round(e))),oe=(e,t,n)=>e===void 0||!Number.isFinite(e)?void 0:Math.min(n,Math.max(t,Math.round(e)));function Ie(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:oe(t?.reads??0,0,1e4)??0,browser:e.browser??nt()},s=(u,c)=>{c!==void 0&&(l[u]=c)};return s("format",t?.format),s("framesToValid",oe(t?.framesToValid,1,1e4)),s("msToValid",W(t?.msToValid)),s("framesToLock",oe(t?.framesToLock,1,1e4)),s("msToLock",W(t?.msToLock)),s("msToCapture",W(e.msToCapture)),s("readP50Ms",W(t?.readP50Ms)),s("readP90Ms",W(t?.readP90Ms)),s("deviceClass",t?.deviceClass),n!==null&&(s("warmupMs",W(n.warmupMs)),s("downloadMs",W(n.downloadMs)),s("cached",n.cached)),s("stillConfirmed",e.stillConfirmed),s("typeMismatch",e.typeMismatch),l}function ae(e,t){return e===void 0?!1:t==="passport"?e!=="TD3":e==="TD3"}var rt=2;async function ot(e){let t=await import("./capture-session-doc-KW5VR4IR.js");return new t.CaptureSessionDoc(e)}function at(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 it(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 Nt(){import("./capture-session-doc-KW5VR4IR.js").then(e=>e.warmDocDetector()).catch(()=>{})}function Ut(e){return st(e,{}).handle}function st(e,t){let n=me(),r=pe({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=Z(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=[],M=t.webOcr!==void 0?Ae(t.webOcr.captureDocument,{mode:e.liveMrz?.mode??"auto"}):null,A=null,F=M===null||!M.enabled?"off":null,G=null,q=null,ie=new WeakMap,Y="";if(M!==null&&M.enabled&&t.webOcr!==void 0){let o=t.webOcr,a=Be(M,{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 Se({textLock:M.textLock,liveMrz:M.liveMrz});G=m;let y=a.engine;y.ready.then(L=>{F=L,typeof L!="string"&&S&&m.setEngine(y)})}else F=a.reason}let z=o=>{let a=JSON.stringify(o);a!==Y&&(Y=a,n.emit("mrz",o))},se=(o,a)=>{let m=t.webOcr?.reports;if(m===void 0||M===null||o===void 0)return;let y=o.format==="ID-3"||o.side==="single"?"single":o.side==="verso"?"verso":"recto",L=y!=="recto"?M.liveMrzArm??M.frontLockArm:M.frontLockArm;if(L===null||Math.random()>=M.reportSampleRate)return;let _=o.via==="live_mrz"?q:null,x=()=>{let E=_?.value??null;m([Ie({arm:L,capture:y,assist:o.ocr??null,load:L==="control"?"off":F,...o.msToCapture!==void 0?{msToCapture:o.msToCapture}:{},...E!==null&&E.stillConfirmed!==void 0?{stillConfirmed:E.stillConfirmed}:{},...a!==void 0?{typeMismatch:ae(a.format,e.documentType==="passport"?"passport":"card")}:{}})])};_!==null&&_.value===null?Promise.race([_.promise,new Promise(E=>setTimeout(E,3e3))]).then(x):x()},N=o=>{!S||o===f||(f=o,r.setActive(o==="starting"||o==="scanning"),n.emit("state",o))},We=(o,a)=>a===void 0?null:u?"single":o.captured.recto===a?"recto":o.captured.verso===a?"verso":null,Fe=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:We(o,o.lastShot),manualShutter:o.manualShutter,torchAvailable:p?.torchAvailable()??!1,torch:d}),ue=()=>{let o=p;o!==null&&o.captureNow().catch(()=>R({type:"captureFailed",at:s()}))};function R(o){if(!S)return;let a=c;c=xe(c,o),c.phase==="capturing"&&a.phase!=="capturing"&&Promise.resolve().then(ue),c.phase==="result"&&a.phase!=="result"&&(N("done"),le());let m=Fe(c),y=JSON.stringify(m);y!==g&&(g=y,n.emit("scan",m))}function le(){O!==null&&clearInterval(O),O=null;for(let o of P.splice(0))o();p?.destroy(),p=null,r.setActive(!1)}let ce=()=>p?.captureReport?.(),Q=!1,de=(o,a)=>{if(!(o===void 0||t.onFaceReport===void 0))try{t.onFaceReport(o,a)}catch{}},H=o=>{Y="",!(p===null||c.phase==="reading"||c.phase==="result")&&(Q=!1,p.rearm(u?"single":c.current??o))},ze=async(o,a,m,y)=>{if(q=null,y!==void 0&&A!==null&&M?.liveMrz?.hint===!0){let D={promise:ve(A,o,y,{engine:U,detectorLimit:M.liveMrz.detectorLimit}).catch(()=>null),value:null};D.promise.then(k=>{D.value=k}),q=D}y!==void 0&&ae(y.format,e.documentType==="passport"?"passport":"card")&&z({state:"mismatch",format:y.format});let L=ce();de(L,"captured"),Q=!0,se(L,y);let _=m===void 0?C:m===null?null:{quad:at(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 Ne(o,a,_,E,q)}finally{x.decoded!==null&&(await x.decoded)?.close()}},Ne=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 D=await(t.measureSharpness!==void 0?t.measureSharpness(o,m):y().then(k=>k===null?-1:be(k,j(m?.quad??null,m?.inStill===!0?k:{width:m?.frameWidth??0,height:m?.frameHeight??0},k)))).catch(()=>-1);if(!S)return;if(Number.isFinite(D)&&D>=0&&D<l){w=!0;let k=u?"recto":c.current??(c.captured.recto===void 0?"recto":"verso");R({type:"readFailed",side:k,id:_,issue:"blurry"}),H(k);return}}w=!1;let x;if(u)x="single";else{let D=c.current,k=await(t.classify!==void 0?t.classify(o):y().then(X=>X===null?D??"recto":m?.inStill===!0?te(X,480,null,!0):te(X,480,j(m?.quad??null,{width:m?.frameWidth??0,height:m?.frameHeight??0},X)))).catch(()=>D??"recto");if(!S)return;if(c.captured[k]!==void 0&&h<rt){h+=1,R({type:"duplicate",id:_,side:k}),H(k==="recto"?"verso":"recto");return}x=c.captured[k]!==void 0&&D!==void 0?D:k,h=0,R({type:"classified",id:_,side:x})}let E=x==="verso"?"verso":"recto";try{let D=t.encode!==void 0?await t.encode(o):await y().then(k=>{if(k===null)throw new Error("the still could not be decoded");return $(k)});if(!S)return;L!==null&&ie.set(D.blob,L),n.emit("captured",{image:D.blob,side:x,documentType:e.documentType,...e.issuer!==void 0?{issuer:e.issuer}:{},width:D.width,height:D.height,previewDataUrl:a}),t.deferRead!==!0&&R({type:"readOk",side:E})}catch{R({type:"readFailed",side:E,id:_,issue:"technical"}),n.emit("error",{kind:"generic",retryable:!0})}H(E==="recto"?"verso":"recto")},Ue=o=>{P.push(o.on("statechange",({state:a})=>{a==="preflight"||a==="acquiring"?N("starting"):a==="positioning"?N("scanning"):a==="captured"?N("captured"):a==="error"&&N("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"?z({state:"fallback",reason:m.reason}):m.state==="valid"?z({state:"valid",format:m.format}):m.state==="reading"?z({state:"reading",...m.format?{format:m.format}:{},...m.coach?{coach:m.coach}:{}}):z({state:"searching"}));let y=a.quad===null?0:it(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})=>n.emit("error",{kind:fe(a),retryable:m})),o.on("artifacts",a=>{ze(a.keyframe,a.previewDataUrl,a.docRegion,a.liveMrz)}))},K=()=>(b??(b=(async()=>{if(S){if(p===null){let o=await(t.createEngine??ot)({...t.engineOptions??{},...B!==void 0?{guide:B}:{},video:e.video,format:ge(e.documentType),side:u?"single":e.side??"recto",autoCapture:!1,...G!==null?{ocr:G}:{}});if(!S){o.destroy();return}p=o,Ue(o);let a=t.tickMs??500;a>0&&(O=setInterval(()=>R({type:"tick",at:s()}),a))}R({type:"clockRestart"}),M!==null&&M.liveMrzArm==="live"&&(F==="unsupported"||F==="off")&&z({state:"fallback",reason:F}),await p.start()}})().finally(()=>{b=null})),b);return{handle:{get state(){return f},on:(o,a)=>n.on(o,a),start:K,retry:()=>{if(p===null&&c.phase==="result"){R({type:"retake"}),h=0,w=!1,K();return}if(p!==null&&f!=="error"){R({type:"retake"}),h=0,w=!1,p.rearm(u?"single":void 0);return}K()},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:ue,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=ce();!Q&&o!==void 0&&o.ticks>0&&de(o,"abandoned"),se(o,void 0)}S=!1,le(),G?.setEngine(null),A?.dispose(),A=null,n.clear()}},setFlowState:o=>{(c.phase==="reading"||c.phase==="result")&&N(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=>ie.get(o.image)?.value??null}}export{dt as a,pt as b,ft as c,gt as d,bt as e,ht as f,De as g,Z as h,xe as i,Je as j,Ze as k,St as l,ve as m,kt as n,U as o,Ae as p,Be as q,nt as r,Ie as s,ae as t,rt as u,Nt as v,Ut as w,st as x};
@@ -0,0 +1 @@
1
+ import{a as j,c as V,d as L,e as N,f as Ce,g as O,h as U,i as P,j as B,k as x,l as w,m as D,u as _e,v as ke}from"./chunk-IF6YOFFO.js";import{m as ye}from"./chunk-EF52BRBD.js";import{a as he}from"./chunk-GT2ZLGF7.js";import{d as J}from"./chunk-FUHDOEBP.js";import{c as Q,e as ge,f as F}from"./chunk-MUVEJRGK.js";var Ge="https://api.sekyro.ai",Ke=5e3,qe=1500,Ye=10;function We(e){return new Promise(t=>setTimeout(t,e))}function Ze(){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 o=0;o<16;o+=1)t[o]=Math.floor(Math.random()*256);t[6]=(t[6]??0)&15|64,t[8]=(t[8]??0)&63|128;let i=[...t].map(o=>o.toString(16).padStart(2,"0")).join("");return`${i.slice(0,8)}-${i.slice(8,12)}-${i.slice(12,16)}-${i.slice(16,20)}-${i.slice(20)}`}function It(e){return Je(e,{})}function Je(e,t){let i=e.apiOrigin??Ge,o=e.autoRetry??!0,r=e.rearm??"auto",s=t.client??new ge({apiOrigin:i,sessionToken:e.clientToken,fetch:e.fetch}),l=t.sleep??We,a=t.uuid??Ze,h=t.getTurnstileToken??((n,c)=>import("./turnstile-FATNZ4AG.js").then(d=>d.executeTurnstile(n,c))),S=he(),f=null,m=null,u=!1,I=new AbortController,p=null,G=null,v=n=>{p=n,S.emit("view",n),f?.onView(n)},_=()=>p!==null?Promise.resolve(p):(G??(G=s.getSession().then(n=>(v(n),n)).finally(()=>{G=null})),G),b=async()=>{let n=await s.getSession();return v(n),n},K=async(n,c)=>{n.plan!==void 0?v(n):await b()},q=null,te=async n=>{let c=await _();if(!n&&c.consentRecorded)return;let d=await s.recordConsent(e.locale);d.plan!==void 0?v(d):p!==null&&v({...p,consentRecorded:!0})},E=n=>n?.force===!0?te(!0):(q??(q=te(!1).finally(()=>{q=null})),q),Y={client:s,ensureConsent:n=>E(n),sleep:l,uuid:a,onBusy:n=>{u||S.emit("busy",n)}},ne=!1,ie=null,W=n=>{if(n.status==="approved"||n.status==="rejected"||n.status==="review"){if(ne)return;ne=!0}ie=JSON.stringify(n),S.emit("result",n)},we=n=>{ie!==JSON.stringify(n)&&W(n)},oe=async n=>{let c=p;n&&(c=await b().catch(()=>p));let d=c===null?null:O(c);return d!==null&&!u&&S.emit("method",d),d!==null},re=null,se=!1,ae=!1,ce=()=>_e(Y,(n,c)=>n.submitCheck("population_registry",{},{idempotencyKey:c})),le=n=>n.nniBound===!0||x(n,"population_registry")?.nniFromDocument===!0,Ee=async()=>{try{let n=await _();if(P(n)||O(n)!==null||B(n)?.checkType!=="population_registry")return;if(!le(n)&&x(n,"population_registry")?.nniFromDocument===void 0&&(n=await b()),!le(n)){ae=!0;return}await E(),await K(await ce(),"population_registry");let c=p===null?void 0:x(p,"population_registry");if(c?.state==="input_required"&&c.reason==="registry_unavailable"&&N(c)>0){if(await l(Ke),u)return;await K(await ce(),"population_registry")}}catch(n){if(n instanceof Q&&(n.code==="check_not_active"||n.code==="step_not_on_path")){await b().catch(()=>{});return}se=!0;return}p!==null&&P(p)&&W(D(p,{autoRetry:o}))},ue=()=>(re??(re=Ee()),re),Oe=async()=>{let c=(await _()).turnstileSiteKey;return c===null?{sandbox:!0}:{channel:"hosted_web",siteKey:c,turnstileToken:await h(c,{signal:I.signal})}},k=null,de=Promise.resolve(),M=0,Te=async()=>{let n=await _();for(let c=0;c<Ye&&!u&&!P(n)&&B(n)===void 0&&L(n).some(d=>d.state==="processing")&&(await l(qe),!u);c+=1)n=await b();return n},Me=async(n,c,d)=>{let{capture:g}=n,C=()=>u,H=()=>n.alive&&n.attempt===d,me=y=>{H()&&g.setFlowState(y)},A=y=>{if(!C()&&(W(y),!!H())){if(y.status==="retry"&&r==="auto"){g.handle.retry();return}g.setFlowState("done")}};if(c.degraded==="NO_RECORDER"){let y=p?.sessionId??(await _().catch(()=>null))?.sessionId??"";A(w(y,"no_recorder"));return}me("uploading");try{if(await ue(),C())return;let y=await _(),Se;if(!P(y)&&O(y)!==null){await oe(!1),A(w(y.sessionId,"method_required"));return}if(!P(y)){if(B(y)?.checkType==="population_registry"){A(w(y.sessionId,ae?"nni_unbound":se?"network":"registry_unavailable"));return}if(await E(),C())return;Se=p??y;let Z=await ke({...Y,artifacts:c,getAttestation:Oe,getView:()=>p??y,refreshView:b,applySubmit:K,onPhase:me,isCancelled:C,onKeyframePromoted:Fe=>{m=Fe}});if(C())return;if(Z.kind==="unavailable"){A(w(y.sessionId,Z.reason));return}if(Z.kind==="resync"&&await b(),p!==null&&O(p)!==null){await oe(!1),A(w(y.sessionId,"method_required"));return}y=await Te()}A(D(y,{autoRetry:o,previous:Se}))}catch{if(C())return;A(w(p?.sessionId??"","network"))}},Ve=(n,c)=>{let d=n.attempt;M>0&&n.alive&&n.capture.setFlowState("uploading"),M+=1,de=de.then(()=>Me(n,c,d)).finally(()=>{M-=1,M===0&&f?.onChainIdle()}).catch(()=>{})},pe=n=>{k?.capture.handle.destroy(),k!==null&&(k.alive=!1);let c=ye(n,f?.captureInternals?.(n)??t.capture,()=>p?.capture?.liveness?.keyframe?.rank===!0,()=>j(p),()=>p?.capture?.liveness?.screenRamp),d={capture:c,alive:!0,attempt:0};k=d,c.handle.on("state",C=>{C==="starting"&&(d.attempt+=1)}),c.handle.on("captured",C=>{Promise.resolve().then(()=>Ve(d,C))});let g=c.handle;return{get state(){return g.state},get captureMode(){return g.captureMode},get facingMode(){return g.facingMode},on:(C,H)=>g.on(C,H),start:async C=>{if(p===null&&await _().catch(()=>{}),!!d.alive)return g.start(C)},retry:()=>g.retry(),switchCamera:()=>g.switchCamera(),destroy:()=>{d.alive=!1,k===d&&(k=null),g.destroy()}}},De=async()=>{if(u)return null;try{let n=await _();return u?null:O(n)}catch{return null}},He=async()=>{if(u)return"self";try{let n=await _();return u?"self":j(n)}catch{return"self"}},Le=async()=>{if(u)return!1;try{let n=await _();if(u||P(n))return!1;let c=x(n,"liveness");return U(c)&&c?.requiresMobile===!0&&!J()}catch{return!1}},Ne=async()=>{if(u)return!1;try{let n=await _();return!u&&n.returning===!0}catch{return!1}},Ue=async n=>{let c=(await _()).plan?.choice,d=c?.options.find(C=>V[C.service]===n);if(!d)throw new RangeError(`method ${String(n)} is not offered`);let g=await s.choose(c.nodeId,d.id);u||v(g)},fe=null,Be=()=>(fe??(fe=import("./plan-runner-2FJLUALJ.js").then(n=>{let c=n.createPlanRunner({runtime:Y,currentView:()=>p,ensureView:_,refreshView:b,ensureConsent:()=>E(),liveness:pe,chainBusy:()=>M>0,destroyed:()=>u,sleep:l,isMobile:J,now:t.now??Date.now,keptFaceKey:()=>m,setView:v,baseCapture:t.capture,emitStep:d=>{u||S.emit("step",d)},emitResult:we,documentInternals:t.document,portraitInternals:t.portrait,livePhotoInternals:t.livePhoto});return f=c,c})),fe);return{consent:()=>E(),startRegistry:ue,methodChoice:De,selectMethod:Ue,reportCameraUnavailable:async n=>{await E();let c=s.reportCameraUnavailable;if(c===void 0)throw new TypeError("this client cannot report a missing camera");let d=await c.call(s,n).catch(g=>{if(g instanceof Q&&g.code==="check_out_of_order")return s.getSession();throw g});u||v(d)},mobileRequired:Le,captureMode:He,returning:Ne,liveness:pe,run:async()=>{if(u)throw new Error("verification destroyed");return(await Be()).run()},currentStep:()=>f?.current()??null,voiceClips:async()=>{if(u)return null;try{let n=await _();return u?null:n.voice??null}catch{return null}},on:(n,c)=>S.on(n,c),destroy:()=>{u=!0,I.abort(),f?.destroy(),k!==null&&(k.alive=!1,k.capture.handle.destroy(),k=null),S.clear()}}}var Pe=["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 Qe=["carte_identite","passport","residence_permit"];function je(e,t){let i=e.byIssuer?.[t]??e.default;return Qe.filter(o=>i==="*"||i.includes(o))}function Ot(e,t=Pe){return[...new Set([...t,...Object.keys(e.byIssuer??{})])].filter(o=>je(e,o).length>0).sort()}function xe(e){if(e.acceptedDocuments)return e.acceptedDocuments;let t=e.acceptedDocumentTypes?.length?[...e.acceptedDocumentTypes]:["carte_identite","passport"];return{default:[],byIssuer:{MR:t}}}function Tt(e){return/^[A-Z]{2}$/.test(e)?String.fromCodePoint(...[...e].map(t=>127462+t.charCodeAt(0)-65)):""}var Lt=["national_number","document_photo","national_eid"],$e=new Set(["phone_otp","email_otp","national_eid","document","nfc","population_registry","supplied_identity","summary_confirm","liveness","face_match","aml_screening","face_dedup","age_estimation"]),Xe=new Set(["supplied_identity","aml_screening","face_dedup","age_estimation"]),X=["document","population_registry","national_eid"],z=["phone_otp","email_otp"],be={identity_method:X,contact:z},ze=["population_registry","document"],Re="platform_unsupported",et=new Set(["prefilled","user_entered","prefilled_or_entered"]),tt={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 R(e){return e.section??tt[e.checkType]??null}function nt(e,t){let i=e.plan?.choice;if(i===void 0||i.locked)return;let o=i.options.find(r=>r.id!==i.selected&&r.available!==!1&&t.includes(r.service));return o===void 0?void 0:{nodeId:i.nodeId,option:o}}function ee(e){let t=e.plan,i=t?.choice;if(t===void 0||i===void 0||i.locked||t.current===null||t.current===i.nodeId||P(e))return null;let o=be[i.kind]??[...X,...z],r=i.options.flatMap(a=>a.available===!1||!o.includes(a.service)?[]:[a.nationalEid!=null?{id:a.id,service:a.service,nationalEid:a.nationalEid}:{id:a.id,service:a.service}]),s=t.steps.find(a=>a.id===t.current)?.service,l=i.selected??r.find(a=>a.service===s)?.id??null;return r.some(a=>a.id!==l)?{nodeId:i.nodeId,kind:i.kind,current:l,options:r}:null}function Ie(e){return e==null?[]:e.options.filter(t=>t.id!==e.current)}function it(e){let t=(e.plan?.sections??[]).map(r=>({id:r.id,state:r.state})),i={sessionId:e.sessionId,orgName:e.orgName,returning:e.returning===!0,consentRecorded:e.consentRecorded,expiresAt:e.expiresAt,sections:t.map(r=>r.id),progress:t,purpose:e.purpose??"identity"};e.branding!==void 0&&(i.branding=e.branding),e.cameraUnavailableHandled===!0&&(i.cameraUnavailableHandled=!0);let o=ee(e);return o!==null&&(i.switchable=o),i}function ot(e){let t={attemptsRemaining:N(e),attemptsExhausted:e.attemptsExhausted===!0};return e.reason!==void 0&&(t.reason=e.reason),e.retakeHint!==void 0&&(t.retakeHint=e.retakeHint),t}var Ae={phone_otp:"phone",email_otp:"email"};function rt(e,t){let i=nt(e,[t==="phone_otp"?"email_otp":"phone_otp"]);return i===void 0?void 0:Ae[i.option.service]}function st(e,t,i,o){let r=t.checkType==="email_otp",s=(r?t.emailOtp:t.otp)??{},l=r?t.emailOtp?.emailSource:t.otp?.numberSource,a=l!==void 0&&et.has(l)?l:r?"prefilled_or_entered":"user_entered",h=typeof s.sentToMasked=="string"&&s.sentToMasked.length>0,S=rt(e,r?"email_otp":"phone_otp"),f={key:t.checkType,context:i,section:R(t),phase:h?"verify":"send",canSwitch:S!==void 0,...o},m=r?{kind:"email_otp",...f,emailSource:a,needsEmail:a!=="prefilled"}:{kind:"phone_otp",...f,numberSource:a,needsPhone:a!=="prefilled",channels:(t.otp?.channels??[]).filter(u=>u==="whatsapp"||u==="sms")};return S!==void 0&&(m.switchChannel=S),h&&(m.sentToMasked=s.sentToMasked),!r&&t.otp?.channel!==void 0&&(m.channel=t.otp.channel),s.expiresAt!==void 0&&(m.codeExpiresAt=s.expiresAt),s.resendAvailableAt!==void 0&&(m.resendAvailableAt=s.resendAvailableAt),m}function at(e,t,i,o){let r=e.nniBound===!0?"bound":t.nniFromDocument===!0?"document":"typed",s=r==="typed"&&t.state==="input_required"&&t.reason==="nni_recheck",l=Ie(ee(e)),a=!o.attemptsExhausted&&l.length===1&&l[0]?.service==="document";return{kind:"registry",key:"registry",context:i,section:R(t),state:t.state==="input_required"?"input_required":"pending",source:r,recheck:s,canUseDocument:a,...o}}function ct(e,t,i,o){let r=[...t.acceptedSides??[]];return{kind:"document",key:"document",context:i,section:R(t),side:r.includes("recto")?"verso":"recto",acceptedSides:r,documents:xe(e),...o}}function lt(e){let t=x(e,"liveness");return t?.state==="passed"||t?.state==="review"}function ve(e,t,i,o,r){let s=t.icao?.report;return{kind:"portrait",key:`portrait:${r}`,context:i,section:R(t),phase:r,report:Array.isArray(s)?s:null,review:t.state==="review",tuning:e.capture?.icao??null,tuningVersion:e.capture?.tuningVersion??null,icao:F(e),retakeOnly:r==="capture"&&t.state==="input_required"&&e.capture?.livePhoto?.oneCapture===!0&&lt(e),...o}}var $={minLongSidePx:1280,jpegQuality:.95};function ut(e,t){let i=e.capture?.livePhoto;if(i?.oneCapture!==!0)return null;let o=x(e,"portrait_icao"),r=i.still??$;return{icao:t==="liveness"&&F(e)!==null&&o!==void 0&&o.state==="pending"&&o.reason===void 0,still:{minLongSidePx:r.minLongSidePx??$.minLongSidePx,jpegQuality:r.jpegQuality??$.jpegQuality}}}function dt(e,t,i,o){let r=t.eid,s=R(t);if(r===void 0||r.challenge!=="app_code")return{kind:"unsupported",key:"unsupported:eid_auth",context:i,section:s,checkType:"eid_auth",reason:"update_required"};let l=Ie(ee(e)),a=l.length===1&&ze.includes(l[0]?.service??"")?l[0]:void 0,h=a===void 0?void 0:V[a.service],S=h!==void 0,f={kind:"eid",key:"eid",context:i,section:s,provider:r.provider,providerName:r.providerName,country:r.country,challenge:"app_code",phase:r.awaiting==="code"?"code":"identifier",identifierBound:r.identifierBound===!0,canUseCamera:S,afterPass:r.afterPass==="continue"?"continue":"end",...o};return S&&(f.cameraMethod=h),r.expiresAt!==void 0&&(f.codeExpiresAt=r.expiresAt),r.resendAvailableAt!==void 0&&(f.resendAvailableAt=r.resendAvailableAt),r.resendsRemaining!==void 0&&(f.resendsRemaining=r.resendsRemaining),r.codeAttemptsRemaining!==void 0&&(f.codeAttemptsRemaining=r.codeAttemptsRemaining),f}function pt(e,t){if(t.checkType!=="face_match"||t.reason!==void 0)return null;let i=x(e,"portrait_icao");return i!==void 0&&(i.state==="passed"||i.state==="review")?i:null}function ft(e){return L(e).filter(t=>t.state==="failed").pop()?.attemptsExhausted===!0}function mt(e,t){let i=e.failureReason,o;i===Re?o="platform_unsupported":e.status==="expired"?o="expired":e.status==="review_pending"?o="review":e.status==="completed"&&e.outcome==="approved"?o="approved":e.status==="completed"&&e.outcome==="review"?o="review":i==="device_cooldown"?o="cooldown":i!==void 0?o="policy_stop":ft(e)?o="attempts_exhausted":o="rejected";let r=o==="platform_unsupported"?{sessionId:e.sessionId,status:"unavailable"}:D(e,{autoRetry:!1}),s={kind:"result",key:"result",context:t,section:null,display:o,result:r};return i!==void 0&&(s.failureReason=i),e.retryAfter!==void 0&&(s.retryAfter=e.retryAfter),s}function St(e,t,i){let o=e.identitySummary;if(o==null)return null;let r={kind:"identity_summary",key:"identity_summary",context:t,section:i??"identity",summaryKind:o.kind==="partial"?"partial":o.kind??"full",source:o.source,portraitAvailable:o.portrait?.available===!0,retakeAvailable:o.retakeAvailable===!0};for(let s of ht){let l=o[s];typeof l=="string"&&l!==""&&(r[s]=l)}return r}var ht=["fullName","birthDate","birthYear","nationality","documentType","documentNumberMasked","nniMasked","expiryDate","retakeTarget"];function T(e,t,i,o){return{kind:"unsupported",key:`unsupported:${i}`,context:e,section:t,checkType:i,reason:o}}function yt(e){return e.kind==="contact"?"contact":(e.kind==="identity_method","identity")}function gt(e,t){let i=be[e.kind]??[...X,...z],o=yt(e),r=e.options.flatMap(l=>{if(l.available===!1||!i.includes(l.service))return[];let a={id:l.id,service:l.service};return l.nationalEid!=null&&(a.nationalEid=l.nationalEid),[a]});if(r.length===0){let l=e.options.length>0&&e.options.every(a=>a.service==="nfc");return T(t,o,"choice",l?"platform_unsupported":"update_required")}let s={nodeId:e.nodeId,kind:e.kind,selected:e.selected,options:r};if(e.kind==="identity_method"){let l={kind:"method",key:"method",context:t,section:o,options:r.map(h=>V[h.service]),choice:s},a=r.find(h=>h.nationalEid!==void 0)?.nationalEid;return a!==void 0&&(l.nationalEid=a),l}return e.kind==="contact"?{kind:"contact_choice",key:"contact_choice",context:t,section:o,options:r.map(l=>Ae[l.service]),selected:null,locked:!1,choice:s}:{kind:"choice",key:`choice:${e.nodeId}`,context:t,section:o,choice:s}}function Nt(e,t={}){let i=it(e);if(P(e)||e.failureReason===Re)return mt(e,i);let o=e.plan;if(o===void 0||!Array.isArray(o.sections))return T(i,null,"plan","update_required");let r=Ce(e);if(r!==null)return gt(r,i);let s=o.current===null?void 0:o.steps.find(m=>m.id===o.current),l=m=>{let u={kind:"processing",key:"processing",context:i,section:m!==void 0?R(m):o.sections.find(I=>I.state==="current")?.id??null,stalled:!1};return typeof m?.service=="string"&&m.service!==""&&(u.service=m.service),u};if(o.current===null)return l(o.steps.find(m=>m.state==="processing"));if(s===void 0)return T(i,null,"step","update_required");if(!$e.has(s.service))return s.interaction==="server"?l(s):T(i,R(s),s.service,"update_required");if(Xe.has(s.service)||!U(s))return l(s);let a=s,h=ot(a),S=a.checkType,f=R(a);switch(S){case"phone_otp":case"email_otp":return st(e,a,i,h);case"population_registry":return at(e,a,i,h);case"eid_auth":return dt(e,a,i,h);case"doc_ocr":return ct(e,a,i,h);case"identity_confirm":return St(e,i,f)??l(a);case"portrait_icao":return ve(e,a,i,h,"capture");case"liveness":case"face_match":{let m=pt(e,a);if(m!==null)return ve(e,m,i,h,"match");let u=a.requiresMobile===!0,I=F(e);return u&&t.isMobile===!1?{kind:"mobile_required",key:"mobile_required",context:i,section:f,checkType:S}:{kind:"liveness",key:"biometric",context:i,section:f,mode:S==="face_match"?"selfie":"liveness",requiresMobile:u,instructions:I===null?"standard":"icao",icao:I,livePhoto:ut(e,S),...h}}case"nfc_chip":return T(i,f,S,"platform_unsupported");default:return T(i,f,S,"update_required")}}export{Ge as a,Ke as b,qe as c,Ye as d,Ze as e,It as f,Je as g,Pe as h,Qe as i,je as j,Ot as k,xe as l,Tt as m,Lt as n,Re as o,R as p,ee as q,Ie as r,pt as s,Nt as t};
@@ -0,0 +1 @@
1
+ import{a as V,c as F,d as N,e as H}from"./chunk-FUHDOEBP.js";import{b as j,c as $,d as J}from"./chunk-POIQGEZM.js";import{b as U,c as K,d as B,e as W,g as z,h as R}from"./chunk-FHJ7HO3M.js";import{b as D,c as ee,d as O,e as te}from"./chunk-FPXL63KZ.js";import{b as q}from"./chunk-4IVRXJR2.js";import{c as X,d as Z,f as w,h as Q,j as Y}from"./chunk-OKWG3PVH.js";var fe=2500,ve=1e3,ge=1500,re=25e5,b=class extends Error{constructor(e,t){super(t??e),this.kind=e}},k=class{constructor(){this.recorder=null;this.stream=null;this.chunks=[];this.bytes=0;this.hardStopTimer=null;this.graceTimer=null;this.settled=!1}clearTimers(){this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.graceTimer&&clearTimeout(this.graceTimer),this.hardStopTimer=null,this.graceTimer=null}record(e,t,r){if(this.recorder&&!this.settled)return Promise.reject(new b("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;let i=U();return new Promise((n,a)=>{let s;try{s=new MediaRecorder(e,i?{mimeType:i,videoBitsPerSecond:re}:{videoBitsPerSecond:re})}catch{try{s=new MediaRecorder(e)}catch{a(new b("unsupported"));return}}this.recorder=s;let d=c=>{this.settled||(this.settled=!0,this.clearTimers(),c())},u=()=>d(()=>{let c=s.mimeType||i||K,l=new Blob(this.chunks,{type:c});if(l.size===0){a(new b("generic","empty clip"));return}if(R(l)){a(new b("cliptoolarge"));return}n({blob:l,mimeType:c})});if(s.ondataavailable=c=>{c.data&&c.data.size&&(this.chunks.push(c.data),this.bytes+=c.data.size,this.bytes>z&&d(()=>{try{s.state!=="inactive"&&s.stop()}catch{}a(new b("cliptoolarge"))}))},s.onstop=u,s.onerror=()=>d(()=>a(new b("generic"))),r!==void 0){let c=!1;s.onstart=()=>{if(!(c||this.settled)){c=!0;try{r()}catch{}}}}try{s.start(ve)}catch{d(()=>a(new b("generic")));return}this.hardStopTimer=setTimeout(()=>{if(this.settled||t?.(),s.state!=="inactive"){try{s.stop()}catch{u()}this.graceTimer=setTimeout(u,ge)}else u()},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(i=>i.stop()),this.stream=null}};var Ue=400,Ke=2e3,be=["rose","peach","sand","mint","sky","lilac"],ye={rose:"rgb(255, 185, 205)",peach:"rgb(245, 193, 159)",sand:"rgb(195, 210, 158)",mint:"rgb(139, 219, 203)",sky:"rgb(140, 214, 249)",lilac:"rgb(208, 197, 249)"};function Be(o){return ye[o]}var Se=4,Ee=4;function Me(o){if(typeof o!="object"||o===null)return!1;let e=o;if(typeof e.nonce!="string"||e.nonce.length===0||!Array.isArray(e.colours)||e.colours.length!==3||!e.colours.every(r=>be.includes(r))||!Array.isArray(e.onsetsMs)||e.onsetsMs.length!==3)return!1;let t=-1;for(let r of e.onsetsMs){if(typeof r!="number"||!Number.isFinite(r)||r<=t||r>=2e3)return!1;t=r}return!0}function ie(o,e){let t=e.now??(()=>performance.now()),r=Me(o)?o:void 0,i=[],n=null,a=null,s=null,d=!1,u=null,c=p=>{u=p;try{e.paint(p)}catch{}},l=p=>{let m=e.frames?.()??null;return m!==null&&s!==null?m.mediaTimeMs+(p-m.presentationTimeMs)-s:p-(a??p)},f=(p,m,v=0)=>{if(d)return;let E=Math.max(0,p-l(t()));n=setTimeout(()=>{if(n=null,!d){if(v<Se&&l(t())<p-Ee){f(p,m,v+1);return}m()}},E)},h=p=>{if(r!==void 0){if(p>=3){f(2e3,()=>c(null));return}f(r.onsetsMs[p],()=>{let m=l(t());if(m>2e3){u!==null&&c(null);return}let v=r.colours[p];c(v);let E=i.length===0?0:i[i.length-1].tMs;i.push({tMs:Math.max(E,Math.round(m)),colour:v}),h(p+1)})}};return{started(p){if(r===void 0||d||a!==null)return;a=p;let m=e.frames?.()??null;s=m===null?null:m.mediaTimeMs+(p-m.presentationTimeMs),h(0)},stop(){d||(d=!0,n!==null&&clearTimeout(n),n=null,u!==null&&c(null))},report(){return r===void 0?void 0:{nonce:r.nonce,rendered:[...i]}}}}function ne(o,e,t=.92){return new Promise((r,i)=>{let n=o.videoWidth,a=o.videoHeight;if(!n||!a){i(new Error("video-not-ready"));return}let s=e.getContext("2d");if(!s){i(new Error("no-2d-context"));return}e.width=n,e.height=a,s.scale(-1,1),s.drawImage(o,-n,0),e.toBlob(d=>d?r(d):i(new Error("empty-keyframe")),"image/jpeg",t)})}var A=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 _e=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}),S=o=>Math.min(1,Math.max(0,o)),M=class{constructor(e={}){this.p=0;this.lastTickAt=null;this.lastCenter=null;this.velocityEma=0;this.qWindow=[];this.lastSizeDirection="ideal";this.t={..._e,...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:i}=e,n=this.lastTickAt===null?0:Math.max(0,(i-this.lastTickAt)/1e3);this.lastTickAt=i;let a={presence:0,centering:0,size:0,pose:0,sharpness:S(r.sharpness),exposure:S(r.exposure),motion:1};if(t!==null){a.presence=1;let c=this.geometryOf(t,e);a.centering=c.centering,a.size=c.size,a.pose=c.pose,a.motion=this.motionOf(c.center,c.iod,i)}else this.lastCenter=null,this.velocityEma=0;let s=Math.min(a.presence,a.centering,a.size,a.pose,a.sharpness,a.exposure,a.motion);this.p=S(this.p+(s>=this.t.Q_GOOD?this.t.RISE_PER_S*s:-this.t.FALL_PER_S*(1-s))*n),this.qWindow.push({at:i,q:s}),this.qWindow=this.qWindow.filter(c=>c.at>=i-this.t.READY_WINDOW_MS);let d=this.qWindow.map(c=>c.q);if(d.length>=3){let c=Math.min(...d),l=d.indexOf(c);d=d.filter((f,h)=>h!==l)}let u=this.p>=1&&d.every(c=>c>=this.t.Q_GOOD);return{at:i,q:s,p:this.p,factors:a,guidanceKey:this.guidanceOf(a,r,s),ready:u,accepted:s>=this.t.Q_GOOD}}geometryOf(e,t){let{box:r,eyes:i}=e,n={x:t.frameWidth/2,y:t.frameHeight/2},a=Math.min(t.frameWidth,t.frameHeight),s=i!==void 0?{x:(i.left.x+i.right.x)/2,y:(i.left.y+i.right.y)/2}:{x:r.x+r.width/2,y:r.y+r.height/2-this.t.BOX_EYE_OFFSET_FACTOR*r.height},d=i!==void 0?Math.hypot(i.right.x-i.left.x,i.right.y-i.left.y):this.t.IOD_BOX_PROXY_FACTOR*r.width,u=Math.hypot(s.x-n.x,s.y-n.y),c=d<=0?0:1-S(u/(this.t.CENTER_FALLOFF_IOD_MULTIPLE*d)),l=a>0?d/a:0;this.lastSizeDirection=l<this.t.SIZE_IDEAL_MIN?"far":l>this.t.SIZE_IDEAL_MAX?"close":"ideal";let f;l<this.t.SIZE_HARD_MIN||l>this.t.SIZE_HARD_MAX?f=0:l<this.t.SIZE_IDEAL_MIN?f=(l-this.t.SIZE_HARD_MIN)/(this.t.SIZE_IDEAL_MIN-this.t.SIZE_HARD_MIN):l>this.t.SIZE_IDEAL_MAX?f=(this.t.SIZE_HARD_MAX-l)/(this.t.SIZE_HARD_MAX-this.t.SIZE_IDEAL_MAX):f=1;let h=1;if(i!==void 0){let p=Math.abs(Math.atan2(i.right.y-i.left.y,i.right.x-i.left.x))*180/Math.PI;h=1-S(p/this.t.ROLL_MAX_DEG)}return{center:s,iod:d,centering:c,size:f,pose:h}}motionOf(e,t,r){let i=this.lastCenter;if(this.lastCenter={...e,at:r},i===null||t<=0)return 1;let n=(r-i.at)/1e3;if(n<=0)return 1;let a=Math.hypot(e.x-i.x,e.y-i.y)/t/n;a<=this.t.MOTION_DEADBAND_IOD_PER_S&&(a=0);let s=1-Math.exp(-n/this.t.MOTION_TAU_S);return this.velocityEma=s*a+(1-s)*this.velocityEma,1-S(this.velocityEma/this.t.MOTION_VELOCITY_IOD_PER_S)}guidanceOf(e,t,r){if(e.presence<=0)return"fcv3.no_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 i=[["size",this.sizeGuidance()],["centering","fcv3.center_face"],["pose","fcv3.straighten"],["exposure",this.exposureGuidance(t)],["sharpness","fcv3.steady_camera"],["motion","fcv3.hold_still"]],n=i[0];for(let a of i)e[a[0]]<e[n[0]]&&(n=a);return n[1]}return"fcv3.hold_still"}sizeGuidance(){return this.lastSizeDirection==="far"?"fcv3.come_closer":"fcv3.move_back"}exposureGuidance(e){let t=(D[0]+D[1])/2;return e.meanLuma<t?"fcv3.more_light":"fcv3.too_bright"}};var Ce=["size","centering","pose","exposure","sharpness","motion"];function Te(o){if(o.accepted)return null;if(o.factors.presence<=0)return"no_face";let e="size";for(let t of Ce)o.factors[t]<o.factors[e]&&(e=t);return e}var _=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=Te(e);if(r===null){this.acceptedMs+=t;return}let i=this.blocked[r]??{count:0,ms:0};i.count+=1,i.ms+=t,this.blocked[r]=i}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 Re=["obs","manycam","virtual","snap camera","xsplit","droidcam","iriun","camo"],ke=[/^(front|back|rear)( [a-z ]+)? camera$/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 Ae(o){let e=(o??"").trim().toLowerCase();return e.length===0?"unknown":Re.some(t=>e.includes(t))?"known_virtual":ke.some(t=>t.test(e))?"platform":"unknown"}function ae(o){if(typeof o!="function")return!1;try{return/\{\s*\[native code\]\s*\}\s*$/.test(Function.prototype.toString.call(o))}catch{return!1}}function Ie(o=globalThis){return ae(o.navigator?.mediaDevices?.getUserMedia)&&ae(o.MediaStreamTrack?.prototype?.getSettings)}async function we(o,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(o)));return Array.from(r.subarray(0,8),i=>i.toString(16).padStart(2,"0")).join("")}catch{return}}async function se(o,e=globalThis){let t={};try{t=typeof o.getSettings=="function"?o.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 n=await we(t.deviceId,e);n!==void 0&&(r.deviceIdHash=n)}let i;try{i=o.label}catch{i=void 0}return{trackSettings:r,capabilitiesPresent:typeof o.getCapabilities=="function",labelClass:Ae(i),prototypesIntact:Ie(e)}}var x=o=>Math.round(o*100)/100;function oe(o){let e=o,t=typeof e?.requestVideoFrameCallback=="function",r=null,i=null,n=0,a=0,s=0,d=0,u=0,c=0,l=()=>{!t||e?.requestVideoFrameCallback===void 0||(r=e.requestVideoFrameCallback((f,h)=>{if(r=null,!t)return;let p=h.presentationTime;if(i!==null){let m=p-i.presentationTimeMs;a+=1;let v=m-s;s+=v/a,d+=v*(m-s)}typeof h.captureTime=="number"&&Number.isFinite(h.captureTime)&&(u+=p-h.captureTime,c+=1),n+=1,i={mediaTimeMs:h.mediaTime*1e3,presentationTimeMs:p},l()}))};return l(),{latest:()=>i,stats:()=>({n,meanGapMs:a===0?0:x(s),stdGapMs:a<2?0:x(Math.sqrt(d/(a-1))),captureLatencyMs:c===0?null:x(u/c)}),stop:()=>{t&&(t=!1,r!==null&&e?.cancelVideoFrameCallback?.(r),r=null)}}}function ce(o,e,t){return{...o,rvfc:e,rampPainter:t}}var De=1e3,P="fcv3.hold_upright",Oe=200,G=4,xe=600,Pe=1e3,le={sharpness:1,exposure:1,meanLuma:128};function Ge(o,e){return e.width=o.videoWidth,e.height=o.videoHeight,e.getContext("2d").drawImage(o,0,0),new Promise((t,r)=>e.toBlob(i=>i?t(i):r(new Error("empty-keyframe")),"image/jpeg",.92))}function Le(){return F()==="phone"}var ue=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()}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??Le)(),this.setState("preflight");let r=W();if(r!=="OK"){this.fail(r==="INSECURE_CONTEXT"?"insecure":"unsupported");return}this.setState("acquiring");let i=t.getUserMedia??(u=>navigator.mediaDevices.getUserMedia(u)),n;this.cameraRequestedAt=this.now();try{n=await i(V(N(),this.facing))}catch(u){if(e!==this.attempt)return;this.fail(B(u));return}if(q(n),e!==this.attempt){for(let u of n.getTracks())u.stop();return}this.stream=n;let a=n.getVideoTracks?.()[0];if(this.trackProvenance=a===void 0?null:se(a).catch(()=>null),this.facing=H(n)??this.facing,t.video.srcObject=n,await t.video.play().catch(()=>{}),e!==this.attempt)return;if(this.cameraReadyAt=this.now(),this.detector===null){let u={v3AssetBaseUrl:t.v3AssetBaseUrl},c=t.createDetector??(t.createWorker!==void 0&&Q()?async()=>{try{return await Y.create(t.createWorker(),u)}catch{return w(u)}}:()=>w(u)),l;try{l=await c()}catch(f){e===this.attempt&&this.fail("models",f instanceof X?f.fallbackReason:Fe(f));return}if(e!==this.attempt){l.destroy();return}this.detector=l,this.options.telemetry?.({type:"detector",tier:l.tier,fallbackReason:l.fallbackReason})}let s=j(),d=t.deviceClass??$(s);this.profiler=new J(d),this.options.telemetry?.({type:"profile",staticClass:d,activeClass:this.profiler.deviceClass,simd:s.simd}),this.gate=new M(t.thresholds??{}),this.blockStats=new _,this.lastGateSnapshotAt=this.now(),t.rankKeyframes?.()&&import("./keyframe-rank-YAJLYJYF.js").then(u=>L=u,()=>{}),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 i=this.scheduler.stats();this.carriedDegrade+=i.degradeCount,i.meanDetectMs>0&&this.carriedMeans.push(i.meanDetectMs),this.scheduler.stop()}let r=new A({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:i}=this,n=this.options.video;if(e!==this.attempt||t===null||r===null||i===null||this.fired||n.videoWidth===0)return;if(this.isLandscape()){this.holdUpright(e);return}let a=i.deviceClass,s=this.now(),d=this.options.makeSnapshot?.(n,i.profile.inputWidth)??this.defaultSnapshot(n,i.profile.inputWidth),u=null;try{u=await t.detect(d,n.videoWidth,n.videoHeight)}catch{u=null}if(e!==this.attempt||this.fired)return;i.record(this.now()-s),i.deviceClass!==a&&this.startScheduler(e);let c=u===null?le:this.options.measureQuality?.(n,u.box)??this.defaultQuality(n,u.box),l=r.tick({timestampMs:this.now(),observation:u,quality:c,frameWidth:n.videoWidth,frameHeight:n.videoHeight});l.accepted&&this.faceAcquiredAt===null&&(this.faceAcquiredAt=l.at),this.blockStats?.record(l),!l.ready&&l.at-this.lastGateSnapshotAt>=De&&(this.lastGateSnapshotAt=l.at,this.reportGate(!1)),this.emit("checks",{engine:"v3",progress:l.p,q:l.q,factors:l.factors,attempt:e}),l.guidanceKey!==this.lastGuidanceKey&&(this.lastGuidanceKey=l.guidanceKey,this.emit("guidance",{key:l.guidanceKey})),l.ready&&this.stateValue==="positioning"&&(this.fired=!0,this.captureCompleteAt=l.at,this.fire(e))}async fire(e){let{options:t}=this,r=this.scheduler;r?.stop(),this.reportGate(!0);let i=r?.stats()??{degradeCount:0,meanDetectMs:0},n=[...this.carriedMeans,...i.meanDetectMs>0?[i.meanDetectMs]:[]];t.telemetry?.({type:"fired",timeToGateMs:this.now()-this.positioningStartedAt,degradeCount:this.carriedDegrade+i.degradeCount,meanDetectMs:n.length===0?0:n.reduce((g,y)=>g+y,0)/n.length});let a=t.mode??"clip",s=t.rankKeyframes?.()&&L?L.default(this,e).catch(()=>this.collectKeyframes(e)):this.collectKeyframes(e);if(a==="photo"){let g=this.watchRotation(e,null),y=await s;if(g(),e!==this.attempt)return;if(y===null){this.fail("generic");return}let me=await this.provenance({n:0,meanGapMs:0,stdGapMs:0,captureLatencyMs:null},!1);if(e!==this.attempt)return;this.finishCapture({keyframe:y.blob,previewDataUrl:y.previewDataUrl,...me});return}this.setState("recording");let d=t.createRecorder?.()??new k,u=this.stream;if(u===null){this.fail("generic");return}let c=oe(t.video),l=t.screenRamp?.(),f=l!==void 0,h=ie(l,{paint:g=>{(g===null||e===this.attempt)&&this.emit("ramp",{colour:g})},now:()=>this.now(),frames:c.latest});this.ramp=h;let p=()=>{c.stop(),h.stop(),this.ramp===h&&(this.ramp=null)},m=this.watchRotation(e,d),v=null;s.then(g=>{v=g},()=>{});let E=()=>{e===this.attempt&&v!==null&&this.emit("frozen",{previewDataUrl:v.previewDataUrl})},C,T;try{[C,T]=await Promise.all([d.record(u,E,()=>h.started(this.now())),s])}catch(g){if(m(),p(),e!==this.attempt)return;let y=g.kind;this.fail(y==="cliptoolarge"?"cliptoolarge":"recorder");return}m();let pe=c.stats();if(p(),e!==this.attempt)return;if(R(C.blob)){this.fail("cliptoolarge");return}if(T===null){this.fail("generic");return}let I=h.report(),he=await this.provenance(pe,f);e===this.attempt&&this.finishCapture({clip:C.blob,clipMimeType:C.mimeType,keyframe:T.blob,previewDataUrl:T.previewDataUrl,...I!==void 0&&I.rendered.length>0?{screenRamp:I}:{},...he})}async provenance(e,t){let r=this.trackProvenance;if(r===null)return{};let i,n=new Promise(s=>{i=setTimeout(()=>s(null),Pe)}),a=await Promise.race([r,n]);return clearTimeout(i),a===null?{}:{provenance:ce(a,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,centering:0,size:0,pose:0,sharpness:0,exposure:0,motion:0},attempt:e}),this.lastGuidanceKey!==P&&(this.lastGuidanceKey=P,this.emit("guidance",{key:P}))}watchRotation(e,t){if(!this.uprightGuard)return()=>{};let r=this.options.video,i=()=>{if(e!==this.attempt||t!==null&&this.stateValue!=="recording"){s();return}r.videoWidth>0&&this.isLandscape()&&(s(),this.abortRecording(e,t))},n=setInterval(i,Oe);r.addEventListener?.("resize",i);let a=!1;function s(){a||(a=!0,clearInterval(n),r.removeEventListener?.("resize",i))}return s}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 M(this.options.thresholds??{}),this.blockStats=new _,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??(n=>this.defaultKeyframe(n)),r=xe/(G-1),i=null;for(let n=0;n<G;n+=1){if(e!==this.attempt)return i;try{let a=await t(this.options.video);(i===null||a.sharpness>i.sharpness)&&(i=a)}catch{}n<G-1&&await Ve(r)}return i}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,i,n)=>{i!==null&&n!==null&&(e[r]=Math.max(0,Math.round(n-i)))};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"?ne:Ge)(e,t),i=t.toDataURL("image/jpeg",.92);return{blob:r,previewDataUrl:i,sharpness:this.centerSharpness(e)}}defaultSnapshot(e,t){try{let r=this.snapshotCanvas??document.createElement("canvas"),i=t/Math.max(1,e.videoWidth),n=Math.max(1,Math.round(e.videoWidth*i)),a=Math.max(1,Math.round(e.videoHeight*i)),s=r.getContext("2d");return s===null?e:(r.width!==n&&(r.width=n),r.height!==a&&(r.height=a),s.drawImage(e,0,0,n,a),this.snapshotCanvas=r,r)}catch{return e}}defaultQuality(e,t){let r=de(e,t,96);return r===null?le:{sharpness:O(r),exposure:te(r),meanLuma:ee(r)}}centerSharpness(e){let t=Z(e),r=de(e,{x:t.width*.25,y:t.height*.25,width:t.width*.5,height:t.height*.5},96);return r===null?0:O(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 i=t.summary();e&&(this.blockStats=null),i.ticks!==0&&this.options.telemetry?.({type:"gate",final:e,activeClass:r.deviceClass,cadenceHz:r.profile.cadenceHz,...i})}stopTracks(){if(this.stream!==null){for(let e of this.stream.getTracks())e.stop();this.stream=null}}fail(e,t){this.scheduler?.stop(),this.reportGate(!0),this.stopTracks(),this.setState("error"),this.options.telemetry?.({type:"error",kind:e,fallbackReason:t}),this.emit("error",{kind:e,retryable:e!=="insecure"&&e!=="unsupported"})}setState(e){this.stateValue=e,this.emit("statechange",{state:e})}now(){return this.options.now?.()??performance.now()}},L;function Ve(o){return new Promise(e=>setTimeout(e,o))}function Fe(o){return o instanceof Error?o.message:String(o)}function de(o,e,t){try{let r=document.createElement("canvas"),i=t/Math.max(1,e.width);r.width=Math.max(1,Math.round(e.width*i)),r.height=Math.max(1,Math.round(e.height*i));let n=r.getContext("2d");return n===null?null:(n.drawImage(o,e.x,e.y,e.width,e.height,0,0,r.width,r.height),n.getImageData(0,0,r.width,r.height))}catch{return null}}export{fe as a,ve as b,ge as c,re as d,b as e,k as f,Ue as g,Ke as h,be as i,Be as j,ne as k,A as l,_e as m,M as n,Te as o,_ as p,De as q,P as r,Oe as s,G as t,xe as u,Pe as v,ue as w};
@@ -1 +1 @@
1
- "use strict";var y=Object.defineProperty;var R=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var v=Object.prototype.hasOwnProperty;var H=(t,e)=>{for(var o in e)y(t,o,{get:e[o],enumerable:!0})},M=(t,e,o,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of O(e))!v.call(t,i)&&i!==o&&y(t,i,{get:()=>e[i],enumerable:!(n=R(e,i))||n.enumerable});return t};var A=t=>M(y({},"__esModule",{value:!0}),t);var Y={};H(Y,{HostedApiError:()=>d,HostedClient:()=>p,KNOWN_CODES:()=>g,icaoPolicyOf:()=>I,isKnownCode:()=>T,portraitIcaoGate:()=>k,stripMimeParams:()=>u});module.exports=A(Y);var b="0.1.0-rc.10";var w="sekyro.did",S;function C(){let t=globalThis.crypto;try{if(typeof t?.randomUUID=="function")return t.randomUUID()}catch{}try{if(typeof t?.getRandomValues=="function"){let e=t.getRandomValues(new Uint8Array(16));return Array.from(e,o=>o.toString(16).padStart(2,"0")).join("")}}catch{}}function N(){try{let t=localStorage.getItem(w);if(t)return t;let e=C();return e!==void 0&&localStorage.setItem(w,e),e}catch{return S??(S=C()),S}}async function x(){let t=globalThis.crypto?.subtle;if(!t)return"";let e=navigator,o=JSON.stringify([e.userAgent,e.platform,e.hardwareConcurrency??null,e.deviceMemory??null,e.maxTouchPoints??0,screen.width,screen.height,screen.colorDepth,globalThis.devicePixelRatio??1,Intl.DateTimeFormat().resolvedOptions().timeZone,e.languages?.join(",")??e.language]),n=await t.digest("SHA-256",new TextEncoder().encode(o));return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("").slice(0,32)}function D(t){let e=new TextEncoder().encode(t),o="";for(let n of e)o+=String.fromCharCode(n);return btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function V(t){let e,o;return{timezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone?.slice(0,64)||void 0}catch{return}},noteCameraLabel(n){n&&(e=n.slice(0,128))},async deviceHeader(){try{o??(o=x().catch(()=>""));let n=[];navigator.webdriver&&n.push("webdriver"),/HeadlessChrome/.test(navigator.userAgent)&&n.push("headless");let i=await o,s=N(),r={v:1,platform:"web",sdk:t.sdk.slice(0,64),ids:[...s?[{kind:"web_local",value:s.slice(0,128)}]:[],...i?[{kind:"web_fp",value:i}]:[]],screen:{w:screen.width,h:screen.height,dpr:globalThis.devicePixelRatio??1},...e?{cameraLabel:e}:{},...n.length?{signals:n}:{}};return D(JSON.stringify(r))}catch{return}}}}var m=Symbol.for("sekyro.web.clientContext"),f=globalThis,h=f[m]??(f[m]=V({sdk:`@sekyro/web@${b}`}));var g=["session_token_invalid","session_token_required","session_token_session_mismatch","session_not_found","rate_limit_exceeded","consent_required","session_not_active","check_not_found","check_already_finalized","check_out_of_order","check_type_unsupported","force_outcome_forbidden","attestation_invalid","platform_unregistered","app_attest_invalid","too_many_challenges","inference_unavailable","mobile_required","nni_locked","document_nni_mismatch","media_content_type_not_allowed","media_too_large","media_key_invalid","media_key_forbidden","media_not_found","media_unreadable","media_session_invalid","idempotency_key_collision","idempotency_in_progress","idempotency_key_required","validation_error","internal_error","unknown_error","upload_failed","network_error","timeout","nfc_outcome_not_accepted","identity_confirm_required","identity_confirm_locked","choice_not_found","choice_locked","choice_option_unavailable","step_not_on_path","check_not_active"];function T(t){return g.includes(t)}var d=class extends Error{constructor(e){super(e.message),this.name="HostedApiError",this.status=e.status,this.code=e.code,e.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=e.retryAfterSeconds),e.details&&(this.details=e.details)}};var K=6e4,P=4,U=3e4,L=9e5,q=200,F=5,$=400;function u(t){return(t.split(";")[0]??"").trim()}var B={liveness:"clipKey",face_match:"imageKey",doc_ocr:"imageKey"},p=class{constructor(e){this.sessionId=null;this.bootstrap=null;this.captureNonces=[];this.captureFetch=null;this.apiOrigin=e.apiOrigin.replace(/\/+$/,""),this.sessionToken=e.sessionToken;let o=e.fetch;this.fetchImpl=(n,i)=>(o??globalThis.fetch).call(globalThis,n,i),this.requestTimeoutMs=e.requestTimeoutMs??U,this.retryAttempts=e.inProgressRetry?.attempts??F,this.retryDelayMs=e.inProgressRetry?.delayMs??$}async getSession(){let e=await this.api("GET","/hosted/session");return this.sessionId=e.sessionId,e}async recordConsent(e){return this.api("POST","/hosted/consent",{body:{locale:e}})}async choose(e,o){let n=await this.api("POST","/hosted/choice",{body:{nodeId:e,option:o}});return this.sessionId=n.sessionId,n}async confirmIdentity(e){return this.api("POST","/hosted/identity/confirm",{body:{decision:e}})}async identityPortrait(){return this.api("GET","/hosted/identity/portrait",{blob:!0})}async presign(e,o,n){let i=await this.ensureSessionId(),s={kind:e,contentType:u(o),contentLength:n};return this.api("POST",`/sessions/${i}/media`,{body:s})}armCapture(e=2){this.fillCaptureNonces(e)}async presignCapture(e,o,n,i={}){let s=await this.ensureSessionId(),r=await this.takeCaptureNonce(),c=r===void 0?void 0:{nonce:r,...i.engine!==void 0?{engine:i.engine.slice(0,32)}:{},...i.durationMs!==void 0&&Number.isFinite(i.durationMs)?{captureMs:Math.min(36e5,Math.max(0,Math.round(i.durationMs)))}:{}},a={kind:e,contentType:u(o),contentLength:n,capture:c};return this.api("POST",`/sessions/${s}/media`,{body:a})}async takeCaptureNonce(){let e=()=>{let o=Date.now();return this.captureNonces=this.captureNonces.filter(n=>n.expiresAt-K>o),this.captureNonces.shift()?.nonce};for(let o=0;o<2;o++){let n=e();if(n!==void 0)return n;await this.fillCaptureNonces(1)}return e()}fillCaptureNonces(e){return this.captureFetch??(this.captureFetch=(async()=>{try{let o=await this.ensureSessionId(),n=await this.api("POST",`/sessions/${o}/media/capture-nonces`,{body:{count:Math.min(P,Math.max(1,e))}}),i=Date.now()+Math.max(0,n.expiresIn)*1e3;for(let s of Array.isArray(n.nonces)?n.nonces:[])typeof s=="string"&&s.length>0&&this.captureNonces.push({nonce:s,expiresAt:i});this.captureNonces=this.captureNonces.slice(-P)}catch{}})().finally(()=>{this.captureFetch=null})),this.captureFetch}async uploadToSpaces(e,o,n){let i;try{i=await this.fetchImpl(e,{method:"PUT",headers:{"content-type":u(n)},body:o,signal:AbortSignal.timeout(L)})}catch(s){throw _(s)}if(!i.ok){let s=(await i.text().catch(()=>"")).slice(0,q);throw new d({status:i.status,code:"upload_failed",message:`media upload failed (HTTP ${i.status})${s?`: ${s}`:""}`})}}async completeMedia(e){let o=await this.ensureSessionId();return this.api("POST",`/sessions/${o}/media/complete`,{body:{key:e}})}async submitCheck(e,o,n={}){let i=await this.ensureSessionId(),s={input:o,forceOutcome:n.forceOutcome};return this.api("POST",`/sessions/${i}/checks/${e}`,{body:s,idempotencyKey:n.idempotencyKey})}async uploadAndSubmit(e,o,n,i={}){let s=u(o.contentType),r=await this.presign(o.kind,s,o.blob.size);await this.uploadToSpaces(r.uploadUrl,o.blob,s);let c=await this.completeMedia(r.key),a={...n,[B[e]]:c.key};return this.submitCheck(e,a,i)}async ensureSessionId(){return this.sessionId!==null?this.sessionId:(this.bootstrap??(this.bootstrap=this.getSession().finally(()=>{this.bootstrap=null})),(await this.bootstrap).sessionId)}async api(e,o,n={}){let i=`${this.apiOrigin}/api/v2${o}`,s={"x-session-token":this.sessionToken};n.body!==void 0&&(s["content-type"]="application/json"),n.idempotencyKey!==void 0&&(s["x-idempotency-key"]=n.idempotencyKey);try{let r=h.timezone();r!==void 0&&(s["sekyro-client-timezone"]=r)}catch{}try{let r=await h.deviceHeader();r!==void 0&&(s["sekyro-client-device"]=r)}catch{}for(let r=0;;r++){let c;try{c=await this.fetchImpl(i,{method:e,headers:s,...n.body!==void 0?{body:JSON.stringify(n.body)}:{},cache:"no-store",signal:AbortSignal.timeout(this.requestTimeoutMs)})}catch(l){throw _(l)}if(c.ok){if(n.blob===!0)try{return await c.blob()}catch(E){throw _(E)}let l;try{l=await c.json()}catch{throw new d({status:c.status,code:"unknown_error",message:`response body was not valid JSON (HTTP ${c.status})`})}return j(l)}let a=await G(c);if(a.code==="idempotency_in_progress"&&r<this.retryAttempts){this.retryDelayMs>0&&await z(this.retryDelayMs);continue}throw a}}};function _(t){if((typeof t=="object"&&t!==null?t.name:void 0)==="TimeoutError")return new d({status:0,code:"timeout",message:"request timed out"});let o=t instanceof Error?t.message:String(t);return new d({status:0,code:"network_error",message:`network request failed: ${o}`})}function j(t){return t!==null&&typeof t=="object"&&"success"in t&&"data"in t?t.data:t}async function G(t){let e="unknown_error",o=`request failed (HTTP ${t.status})`,n=Number.NaN,i;try{let c=await t.json();if(c!==null&&typeof c=="object"){let a=c;typeof a.code=="string"&&a.code.length>0&&(e=a.code),typeof a.message=="string"&&a.message.length>0&&(o=a.message),typeof a.retryAfterSeconds=="number"&&(n=a.retryAfterSeconds),Array.isArray(a.details?.issues)&&(i=a.details)}}catch{}let s=t.headers.get("retry-after"),r=s===null?Math.floor(n):Number.parseInt(s,10);return new d({status:t.status,code:e,message:o,...Number.isFinite(r)&&r>=0?{retryAfterSeconds:r}:{},details:i})}function z(t){return new Promise(e=>setTimeout(e,t))}function I(t){let e=t?.portrait,o=e?.icao,n=e?.purpose==="id_document";return o==null?n?{policy:"reject",profile:"id_document"}:null:{policy:o.policy==="alert"&&!n?"alert":"reject",profile:n||o.profile==="id_document"?"id_document":"selfie"}}function k(t){return{...t.baselineEyeOpenness!==void 0?{baselineEyeOpenness:t.baselineEyeOpenness}:{},criteria:t.verdict??{},...t.backgroundCheck!==void 0?{backgroundCheck:t.backgroundCheck}:{}}}0&&(module.exports={HostedApiError,HostedClient,KNOWN_CODES,icaoPolicyOf,isKnownCode,portraitIcaoGate,stripMimeParams});
1
+ "use strict";var y=Object.defineProperty;var E=Object.getOwnPropertyDescriptor;var R=Object.getOwnPropertyNames;var O=Object.prototype.hasOwnProperty;var H=(t,e)=>{for(var o in e)y(t,o,{get:e[o],enumerable:!0})},M=(t,e,o,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of R(e))!O.call(t,i)&&i!==o&&y(t,i,{get:()=>e[i],enumerable:!(n=E(e,i))||n.enumerable});return t};var A=t=>M(y({},"__esModule",{value:!0}),t);var Y={};H(Y,{HostedApiError:()=>d,HostedClient:()=>p,KNOWN_CODES:()=>g,icaoPolicyOf:()=>I,isKnownCode:()=>T,portraitIcaoGate:()=>k,stripMimeParams:()=>u});module.exports=A(Y);var b="0.1.0-rc.12";var w="sekyro.did",S;function C(){let t=globalThis.crypto;try{if(typeof t?.randomUUID=="function")return t.randomUUID()}catch{}try{if(typeof t?.getRandomValues=="function"){let e=t.getRandomValues(new Uint8Array(16));return Array.from(e,o=>o.toString(16).padStart(2,"0")).join("")}}catch{}}function N(){try{let t=localStorage.getItem(w);if(t)return t;let e=C();return e!==void 0&&localStorage.setItem(w,e),e}catch{return S??(S=C()),S}}async function x(){let t=globalThis.crypto?.subtle;if(!t)return"";let e=navigator,o=JSON.stringify([e.userAgent,e.platform,e.hardwareConcurrency??null,e.deviceMemory??null,e.maxTouchPoints??0,screen.width,screen.height,screen.colorDepth,globalThis.devicePixelRatio??1,Intl.DateTimeFormat().resolvedOptions().timeZone,e.languages?.join(",")??e.language]),n=await t.digest("SHA-256",new TextEncoder().encode(o));return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("").slice(0,32)}function V(t){let e=new TextEncoder().encode(t),o="";for(let n of e)o+=String.fromCharCode(n);return btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function D(t){let e,o;return{timezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone?.slice(0,64)||void 0}catch{return}},noteCameraLabel(n){n&&(e=n.slice(0,128))},async deviceHeader(){try{o??(o=x().catch(()=>""));let n=[];navigator.webdriver&&n.push("webdriver"),/HeadlessChrome/.test(navigator.userAgent)&&n.push("headless");let i=await o,s=N(),r={v:1,platform:"web",sdk:t.sdk.slice(0,64),ids:[...s?[{kind:"web_local",value:s.slice(0,128)}]:[],...i?[{kind:"web_fp",value:i}]:[]],screen:{w:screen.width,h:screen.height,dpr:globalThis.devicePixelRatio??1},...e?{cameraLabel:e}:{},...n.length?{signals:n}:{}};return V(JSON.stringify(r))}catch{return}}}}var m=Symbol.for("sekyro.web.clientContext"),f=globalThis,h=f[m]??(f[m]=D({sdk:`@sekyro/web@${b}`}));var g=["session_token_invalid","session_token_required","session_token_session_mismatch","session_not_found","rate_limit_exceeded","consent_required","session_not_active","check_not_found","check_already_finalized","check_out_of_order","check_type_unsupported","force_outcome_forbidden","attestation_invalid","platform_unregistered","app_attest_invalid","too_many_challenges","inference_unavailable","mobile_required","nni_locked","document_nni_mismatch","media_content_type_not_allowed","media_too_large","media_key_invalid","media_key_forbidden","media_not_found","media_unreadable","media_session_invalid","idempotency_key_collision","idempotency_in_progress","idempotency_key_required","validation_error","internal_error","unknown_error","upload_failed","network_error","timeout","nfc_outcome_not_accepted","identity_confirm_required","identity_confirm_locked","choice_not_found","choice_locked","choice_option_unavailable","step_not_on_path","check_not_active","sekyro_app_not_allowed","sekyro_app_unverified"];function T(t){return g.includes(t)}var d=class extends Error{constructor(e){super(e.message),this.name="HostedApiError",this.status=e.status,this.code=e.code,e.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=e.retryAfterSeconds),e.details&&(this.details=e.details)}};var U=6e4,P=4,K=3e4,L=9e5,q=200,F=5,$=400;function u(t){return(t.split(";")[0]??"").trim()}var B={liveness:"clipKey",face_match:"imageKey",doc_ocr:"imageKey"},p=class{constructor(e){this.sessionId=null;this.bootstrap=null;this.captureNonces=[];this.captureFetch=null;this.apiOrigin=e.apiOrigin.replace(/\/+$/,""),this.sessionToken=e.sessionToken;let o=e.fetch;this.fetchImpl=(n,i)=>(o??globalThis.fetch).call(globalThis,n,i),this.requestTimeoutMs=e.requestTimeoutMs??K,this.retryAttempts=e.inProgressRetry?.attempts??F,this.retryDelayMs=e.inProgressRetry?.delayMs??$}async getSession(){let e=await this.api("GET","/hosted/session");return this.sessionId=e.sessionId,e}async recordConsent(e){return this.api("POST","/hosted/consent",{body:{locale:e}})}async reportCameraUnavailable(e){return this.api("POST","/hosted/camera-unavailable",{body:{cause:e}})}async choose(e,o){let n=await this.api("POST","/hosted/choice",{body:{nodeId:e,option:o}});return this.sessionId=n.sessionId,n}async confirmIdentity(e){return this.api("POST","/hosted/identity/confirm",{body:{decision:e}})}async identityPortrait(){return this.api("GET","/hosted/identity/portrait",{blob:!0})}async presign(e,o,n){let i=await this.ensureSessionId(),s={kind:e,contentType:u(o),contentLength:n};return this.api("POST",`/sessions/${i}/media`,{body:s})}armCapture(e=2){this.fillCaptureNonces(e)}async presignCapture(e,o,n,i={}){let s=await this.ensureSessionId(),r=await this.takeCaptureNonce(),c=r===void 0?void 0:{nonce:r,...i.engine!==void 0?{engine:i.engine.slice(0,32)}:{},...i.durationMs!==void 0&&Number.isFinite(i.durationMs)?{captureMs:Math.min(36e5,Math.max(0,Math.round(i.durationMs)))}:{}},a={kind:e,contentType:u(o),contentLength:n,capture:c};return this.api("POST",`/sessions/${s}/media`,{body:a})}async takeCaptureNonce(){let e=()=>{let o=Date.now();return this.captureNonces=this.captureNonces.filter(n=>n.expiresAt-U>o),this.captureNonces.shift()?.nonce};for(let o=0;o<2;o++){let n=e();if(n!==void 0)return n;await this.fillCaptureNonces(1)}return e()}fillCaptureNonces(e){return this.captureFetch??(this.captureFetch=(async()=>{try{let o=await this.ensureSessionId(),n=await this.api("POST",`/sessions/${o}/media/capture-nonces`,{body:{count:Math.min(P,Math.max(1,e))}}),i=Date.now()+Math.max(0,n.expiresIn)*1e3;for(let s of Array.isArray(n.nonces)?n.nonces:[])typeof s=="string"&&s.length>0&&this.captureNonces.push({nonce:s,expiresAt:i});this.captureNonces=this.captureNonces.slice(-P)}catch{}})().finally(()=>{this.captureFetch=null})),this.captureFetch}async uploadToSpaces(e,o,n){let i;try{i=await this.fetchImpl(e,{method:"PUT",headers:{"content-type":u(n)},body:o,signal:AbortSignal.timeout(L)})}catch(s){throw _(s)}if(!i.ok){let s=(await i.text().catch(()=>"")).slice(0,q);throw new d({status:i.status,code:"upload_failed",message:`media upload failed (HTTP ${i.status})${s?`: ${s}`:""}`})}}async completeMedia(e){let o=await this.ensureSessionId();return this.api("POST",`/sessions/${o}/media/complete`,{body:{key:e}})}async submitCheck(e,o,n={}){let i=await this.ensureSessionId(),s={input:o,forceOutcome:n.forceOutcome};return this.api("POST",`/sessions/${i}/checks/${e}`,{body:s,idempotencyKey:n.idempotencyKey})}async uploadAndSubmit(e,o,n,i={}){let s=u(o.contentType),r=await this.presign(o.kind,s,o.blob.size);await this.uploadToSpaces(r.uploadUrl,o.blob,s);let c=await this.completeMedia(r.key),a={...n,[B[e]]:c.key};return this.submitCheck(e,a,i)}async ensureSessionId(){return this.sessionId!==null?this.sessionId:(this.bootstrap??(this.bootstrap=this.getSession().finally(()=>{this.bootstrap=null})),(await this.bootstrap).sessionId)}async api(e,o,n={}){let i=`${this.apiOrigin}/api/v2${o}`,s={"x-session-token":this.sessionToken};n.body!==void 0&&(s["content-type"]="application/json"),n.idempotencyKey!==void 0&&(s["x-idempotency-key"]=n.idempotencyKey);try{let r=h.timezone();r!==void 0&&(s["sekyro-client-timezone"]=r)}catch{}try{let r=await h.deviceHeader();r!==void 0&&(s["sekyro-client-device"]=r)}catch{}for(let r=0;;r++){let c;try{c=await this.fetchImpl(i,{method:e,headers:s,...n.body!==void 0?{body:JSON.stringify(n.body)}:{},cache:"no-store",signal:AbortSignal.timeout(this.requestTimeoutMs)})}catch(l){throw _(l)}if(c.ok){if(n.blob===!0)try{return await c.blob()}catch(v){throw _(v)}let l;try{l=await c.json()}catch{throw new d({status:c.status,code:"unknown_error",message:`response body was not valid JSON (HTTP ${c.status})`})}return j(l)}let a=await G(c);if(a.code==="idempotency_in_progress"&&r<this.retryAttempts){this.retryDelayMs>0&&await z(this.retryDelayMs);continue}throw a}}};function _(t){if((typeof t=="object"&&t!==null?t.name:void 0)==="TimeoutError")return new d({status:0,code:"timeout",message:"request timed out"});let o=t instanceof Error?t.message:String(t);return new d({status:0,code:"network_error",message:`network request failed: ${o}`})}function j(t){return t!==null&&typeof t=="object"&&"success"in t&&"data"in t?t.data:t}async function G(t){let e="unknown_error",o=`request failed (HTTP ${t.status})`,n=Number.NaN,i;try{let c=await t.json();if(c!==null&&typeof c=="object"){let a=c;typeof a.code=="string"&&a.code.length>0&&(e=a.code),typeof a.message=="string"&&a.message.length>0&&(o=a.message),typeof a.retryAfterSeconds=="number"&&(n=a.retryAfterSeconds),Array.isArray(a.details?.issues)&&(i=a.details)}}catch{}let s=t.headers.get("retry-after"),r=s===null?Math.floor(n):Number.parseInt(s,10);return new d({status:t.status,code:e,message:o,...Number.isFinite(r)&&r>=0?{retryAfterSeconds:r}:{},details:i})}function z(t){return new Promise(e=>setTimeout(e,t))}function I(t){let e=t?.portrait,o=e?.icao,n=e?.purpose==="id_document";return o==null?n?{policy:"reject",profile:"id_document"}:null:{policy:o.policy==="alert"&&!n?"alert":"reject",profile:n||o.profile==="id_document"?"id_document":"selfie"}}function k(t){return{...t.baselineEyeOpenness!==void 0?{baselineEyeOpenness:t.baselineEyeOpenness}:{},criteria:t.verdict??{},...t.backgroundCheck!==void 0?{backgroundCheck:t.backgroundCheck}:{}}}0&&(module.exports={HostedApiError,HostedClient,KNOWN_CODES,icaoPolicyOf,isKnownCode,portraitIcaoGate,stripMimeParams});
@@ -1,12 +1,14 @@
1
- import { B as HostedSessionView, s as HostedIcaoPolicy, P as IcaoGateSummary, aa as PortraitIcaoInput } from '../icao-gate-terzKYD7.cjs';
2
- export { A as AcceptedDocumentType, aV as AttestationInput, aW as CaptureContext, C as CaptureMode, aX as CaptureNoncesResult, aY as CaptureProof, aZ as CheckInputByType, a as CheckReason, b as CheckState, c as CheckType, a_ as CompleteMediaResult, a$ as ConsentLocale, d as ContactChannel, D as DecisionReason, b0 as DocDeviceRead, b1 as DocOcrInput, e as DocReason, b2 as DocSide, E as EidAfterPass, f as EidAuthInput, g as EidReason, b3 as EmailOtpInput, h as EmailOtpReason, b4 as FaceMatchInput, F as FaceMatchReason, i as HostedAcceptedDocuments, l as HostedCaptureTuning, aU as HostedClient, b5 as HostedClientOptions, m as HostedConsentView, n as HostedDocumentCaptureTuning, o as HostedDocumentScanTuning, p as HostedEidView, q as HostedEmailOtpView, r as HostedFlowRef, t as HostedIntegrity, u as HostedLivePhotoTuning, v as HostedNativeCaptureTuning, w as HostedOcrTuning, x as HostedOtpView, y as HostedPlanView, z as HostedPortraitView, G as HostedStepView, I as HostedVoiceLocale, J as HostedVoiceView, M as IcaoCriterion, R as IcaoReportEntry, S as IdentityConfirmDecision, T as IdentityMethod, U as IdentitySummarySource, V as IdentitySummaryView, b6 as LivenessCaptureInput, b7 as LivenessInput, W as LivenessReason, X as MatchReason, b8 as MediaCheckType, b9 as MediaKind, Y as MethodChoiceView, Z as NationalEidOption, _ as NfcChipReason, $ as NfcStepView, a0 as OtpChoiceView, ba as PhoneOtpInput, a1 as PhoneOtpReason, a2 as PlanAttempts, a3 as PlanChoiceKind, a4 as PlanChoiceOption, a5 as PlanChoiceView, a6 as PlanSectionView, a7 as PlanStepView, a8 as PolicyFailureReason, bb as PopulationInput, a9 as PopulationReason, ab as PortraitIcaoReason, bc as PresignRequest, bd as PresignUploadResult, be as RecordConsentResult, ac as SessionFailureReason, ad as SessionOutcome, ae as SessionStatus, bf as SessionStepView, bg as SessionView, af as StepSection, bh as SubmitCheckBody, bi as SubmitOptions, bj as UploadMedia, bk as stripMimeParams } from '../icao-gate-terzKYD7.cjs';
1
+ import { c as IcaoGateSummary } from '../icao-gate-BRuIgOE2.cjs';
2
+ export { N as HostedClient, O as HostedClientOptions, Q as MediaCheckType, S as SubmitOptions, U as UploadMedia, T as stripMimeParams } from '../icao-gate-BRuIgOE2.cjs';
3
+ import { H as HostedSessionView, G as HostedIcaoPolicy, ah as PortraitIcaoInput } from '../types-4rgeNIlz.cjs';
4
+ export { A as AcceptedDocumentType, ax as AttestationInput, c as CaptureContext, i as CaptureMode, ay as CaptureNoncesResult, az as CaptureProof, f as CheckInputByType, k as CheckReason, l as CheckState, e as CheckType, d as CompleteMediaResult, C as ConsentLocale, m as ContactChannel, D as DecisionReason, aA as DocDeviceRead, aB as DocOcrInput, n as DocReason, aC as DocSide, E as EidAfterPass, o as EidAuthInput, p as EidReason, aD as EmailOtpInput, q as EmailOtpReason, aE as FaceMatchInput, F as FaceMatchReason, r as HostedAcceptedDocuments, u as HostedCaptureTuning, a as HostedConsentView, v as HostedDocumentCaptureTuning, w as HostedDocumentScanTuning, x as HostedEidView, y as HostedEmailOtpView, z as HostedFlowRef, J as HostedIntegrity, K as HostedLivePhotoTuning, N as HostedNativeCaptureTuning, O as HostedOcrTuning, Q as HostedOtpView, T as HostedPlanView, U as HostedPortraitView, V as HostedStepView, W as HostedVoiceLocale, X as HostedVoiceView, g as IcaoCriterion, Z as IcaoReportEntry, I as IdentityConfirmDecision, _ as IdentityMethod, $ as IdentitySummarySource, a0 as IdentitySummaryView, aF as LivenessCaptureInput, aG as LivenessInput, a1 as LivenessReason, a2 as MatchReason, M as MediaKind, a3 as MethodChoiceView, a4 as NationalEidOption, a5 as NfcChipReason, a6 as NfcStepView, a7 as OtpChoiceView, aH as PhoneOtpInput, a8 as PhoneOtpReason, a9 as PlanAttempts, aa as PlanChoiceKind, ab as PlanChoiceOption, ac as PlanChoiceView, ad as PlanSectionView, ae as PlanStepView, af as PolicyFailureReason, aI as PopulationInput, ag as PopulationReason, ai as PortraitIcaoReason, aJ as PresignRequest, P as PresignUploadResult, aK as RecordConsentResult, an as SessionFailureReason, ao as SessionOutcome, ap as SessionStatus, aL as SessionStepView, aM as SessionView, aq as StepSection, aN as SubmitCheckBody, ar as VerificationAssurance, as as VerificationLevel } from '../types-4rgeNIlz.cjs';
3
5
 
4
6
  /**
5
7
  * Every error code the hosted page can receive from the session-token surface.
6
8
  * A closed string-literal union — switch over {@link KnownCode} with a `never`
7
9
  * default arm for compile-checked exhaustiveness.
8
10
  */
9
- declare const KNOWN_CODES: readonly ["session_token_invalid", "session_token_required", "session_token_session_mismatch", "session_not_found", "rate_limit_exceeded", "consent_required", "session_not_active", "check_not_found", "check_already_finalized", "check_out_of_order", "check_type_unsupported", "force_outcome_forbidden", "attestation_invalid", "platform_unregistered", "app_attest_invalid", "too_many_challenges", "inference_unavailable", "mobile_required", "nni_locked", "document_nni_mismatch", "media_content_type_not_allowed", "media_too_large", "media_key_invalid", "media_key_forbidden", "media_not_found", "media_unreadable", "media_session_invalid", "idempotency_key_collision", "idempotency_in_progress", "idempotency_key_required", "validation_error", "internal_error", "unknown_error", "upload_failed", "network_error", "timeout", "nfc_outcome_not_accepted", "identity_confirm_required", "identity_confirm_locked", "choice_not_found", "choice_locked", "choice_option_unavailable", "step_not_on_path", "check_not_active"];
11
+ declare const KNOWN_CODES: readonly ["session_token_invalid", "session_token_required", "session_token_session_mismatch", "session_not_found", "rate_limit_exceeded", "consent_required", "session_not_active", "check_not_found", "check_already_finalized", "check_out_of_order", "check_type_unsupported", "force_outcome_forbidden", "attestation_invalid", "platform_unregistered", "app_attest_invalid", "too_many_challenges", "inference_unavailable", "mobile_required", "nni_locked", "document_nni_mismatch", "media_content_type_not_allowed", "media_too_large", "media_key_invalid", "media_key_forbidden", "media_not_found", "media_unreadable", "media_session_invalid", "idempotency_key_collision", "idempotency_in_progress", "idempotency_key_required", "validation_error", "internal_error", "unknown_error", "upload_failed", "network_error", "timeout", "nfc_outcome_not_accepted", "identity_confirm_required", "identity_confirm_locked", "choice_not_found", "choice_locked", "choice_option_unavailable", "step_not_on_path", "check_not_active", "sekyro_app_not_allowed", "sekyro_app_unverified"];
10
12
  /** Closed union of {@link KNOWN_CODES} — exhaustively switchable. */
11
13
  type KnownCode = (typeof KNOWN_CODES)[number];
12
14
  /** Narrow an arbitrary wire code to the known union (unknown codes stay `string`). */
@@ -1,12 +1,14 @@
1
- import { B as HostedSessionView, s as HostedIcaoPolicy, P as IcaoGateSummary, aa as PortraitIcaoInput } from '../icao-gate-terzKYD7.js';
2
- export { A as AcceptedDocumentType, aV as AttestationInput, aW as CaptureContext, C as CaptureMode, aX as CaptureNoncesResult, aY as CaptureProof, aZ as CheckInputByType, a as CheckReason, b as CheckState, c as CheckType, a_ as CompleteMediaResult, a$ as ConsentLocale, d as ContactChannel, D as DecisionReason, b0 as DocDeviceRead, b1 as DocOcrInput, e as DocReason, b2 as DocSide, E as EidAfterPass, f as EidAuthInput, g as EidReason, b3 as EmailOtpInput, h as EmailOtpReason, b4 as FaceMatchInput, F as FaceMatchReason, i as HostedAcceptedDocuments, l as HostedCaptureTuning, aU as HostedClient, b5 as HostedClientOptions, m as HostedConsentView, n as HostedDocumentCaptureTuning, o as HostedDocumentScanTuning, p as HostedEidView, q as HostedEmailOtpView, r as HostedFlowRef, t as HostedIntegrity, u as HostedLivePhotoTuning, v as HostedNativeCaptureTuning, w as HostedOcrTuning, x as HostedOtpView, y as HostedPlanView, z as HostedPortraitView, G as HostedStepView, I as HostedVoiceLocale, J as HostedVoiceView, M as IcaoCriterion, R as IcaoReportEntry, S as IdentityConfirmDecision, T as IdentityMethod, U as IdentitySummarySource, V as IdentitySummaryView, b6 as LivenessCaptureInput, b7 as LivenessInput, W as LivenessReason, X as MatchReason, b8 as MediaCheckType, b9 as MediaKind, Y as MethodChoiceView, Z as NationalEidOption, _ as NfcChipReason, $ as NfcStepView, a0 as OtpChoiceView, ba as PhoneOtpInput, a1 as PhoneOtpReason, a2 as PlanAttempts, a3 as PlanChoiceKind, a4 as PlanChoiceOption, a5 as PlanChoiceView, a6 as PlanSectionView, a7 as PlanStepView, a8 as PolicyFailureReason, bb as PopulationInput, a9 as PopulationReason, ab as PortraitIcaoReason, bc as PresignRequest, bd as PresignUploadResult, be as RecordConsentResult, ac as SessionFailureReason, ad as SessionOutcome, ae as SessionStatus, bf as SessionStepView, bg as SessionView, af as StepSection, bh as SubmitCheckBody, bi as SubmitOptions, bj as UploadMedia, bk as stripMimeParams } from '../icao-gate-terzKYD7.js';
1
+ import { c as IcaoGateSummary } from '../icao-gate-CphntEQ2.js';
2
+ export { N as HostedClient, O as HostedClientOptions, Q as MediaCheckType, S as SubmitOptions, U as UploadMedia, T as stripMimeParams } from '../icao-gate-CphntEQ2.js';
3
+ import { H as HostedSessionView, G as HostedIcaoPolicy, ah as PortraitIcaoInput } from '../types-4rgeNIlz.js';
4
+ export { A as AcceptedDocumentType, ax as AttestationInput, c as CaptureContext, i as CaptureMode, ay as CaptureNoncesResult, az as CaptureProof, f as CheckInputByType, k as CheckReason, l as CheckState, e as CheckType, d as CompleteMediaResult, C as ConsentLocale, m as ContactChannel, D as DecisionReason, aA as DocDeviceRead, aB as DocOcrInput, n as DocReason, aC as DocSide, E as EidAfterPass, o as EidAuthInput, p as EidReason, aD as EmailOtpInput, q as EmailOtpReason, aE as FaceMatchInput, F as FaceMatchReason, r as HostedAcceptedDocuments, u as HostedCaptureTuning, a as HostedConsentView, v as HostedDocumentCaptureTuning, w as HostedDocumentScanTuning, x as HostedEidView, y as HostedEmailOtpView, z as HostedFlowRef, J as HostedIntegrity, K as HostedLivePhotoTuning, N as HostedNativeCaptureTuning, O as HostedOcrTuning, Q as HostedOtpView, T as HostedPlanView, U as HostedPortraitView, V as HostedStepView, W as HostedVoiceLocale, X as HostedVoiceView, g as IcaoCriterion, Z as IcaoReportEntry, I as IdentityConfirmDecision, _ as IdentityMethod, $ as IdentitySummarySource, a0 as IdentitySummaryView, aF as LivenessCaptureInput, aG as LivenessInput, a1 as LivenessReason, a2 as MatchReason, M as MediaKind, a3 as MethodChoiceView, a4 as NationalEidOption, a5 as NfcChipReason, a6 as NfcStepView, a7 as OtpChoiceView, aH as PhoneOtpInput, a8 as PhoneOtpReason, a9 as PlanAttempts, aa as PlanChoiceKind, ab as PlanChoiceOption, ac as PlanChoiceView, ad as PlanSectionView, ae as PlanStepView, af as PolicyFailureReason, aI as PopulationInput, ag as PopulationReason, ai as PortraitIcaoReason, aJ as PresignRequest, P as PresignUploadResult, aK as RecordConsentResult, an as SessionFailureReason, ao as SessionOutcome, ap as SessionStatus, aL as SessionStepView, aM as SessionView, aq as StepSection, aN as SubmitCheckBody, ar as VerificationAssurance, as as VerificationLevel } from '../types-4rgeNIlz.js';
3
5
 
4
6
  /**
5
7
  * Every error code the hosted page can receive from the session-token surface.
6
8
  * A closed string-literal union — switch over {@link KnownCode} with a `never`
7
9
  * default arm for compile-checked exhaustiveness.
8
10
  */
9
- declare const KNOWN_CODES: readonly ["session_token_invalid", "session_token_required", "session_token_session_mismatch", "session_not_found", "rate_limit_exceeded", "consent_required", "session_not_active", "check_not_found", "check_already_finalized", "check_out_of_order", "check_type_unsupported", "force_outcome_forbidden", "attestation_invalid", "platform_unregistered", "app_attest_invalid", "too_many_challenges", "inference_unavailable", "mobile_required", "nni_locked", "document_nni_mismatch", "media_content_type_not_allowed", "media_too_large", "media_key_invalid", "media_key_forbidden", "media_not_found", "media_unreadable", "media_session_invalid", "idempotency_key_collision", "idempotency_in_progress", "idempotency_key_required", "validation_error", "internal_error", "unknown_error", "upload_failed", "network_error", "timeout", "nfc_outcome_not_accepted", "identity_confirm_required", "identity_confirm_locked", "choice_not_found", "choice_locked", "choice_option_unavailable", "step_not_on_path", "check_not_active"];
11
+ declare const KNOWN_CODES: readonly ["session_token_invalid", "session_token_required", "session_token_session_mismatch", "session_not_found", "rate_limit_exceeded", "consent_required", "session_not_active", "check_not_found", "check_already_finalized", "check_out_of_order", "check_type_unsupported", "force_outcome_forbidden", "attestation_invalid", "platform_unregistered", "app_attest_invalid", "too_many_challenges", "inference_unavailable", "mobile_required", "nni_locked", "document_nni_mismatch", "media_content_type_not_allowed", "media_too_large", "media_key_invalid", "media_key_forbidden", "media_not_found", "media_unreadable", "media_session_invalid", "idempotency_key_collision", "idempotency_in_progress", "idempotency_key_required", "validation_error", "internal_error", "unknown_error", "upload_failed", "network_error", "timeout", "nfc_outcome_not_accepted", "identity_confirm_required", "identity_confirm_locked", "choice_not_found", "choice_locked", "choice_option_unavailable", "step_not_on_path", "check_not_active", "sekyro_app_not_allowed", "sekyro_app_unverified"];
10
12
  /** Closed union of {@link KNOWN_CODES} — exhaustively switchable. */
11
13
  type KnownCode = (typeof KNOWN_CODES)[number];
12
14
  /** Narrow an arbitrary wire code to the known union (unknown codes stay `string`). */