@sekyro/web 0.1.0-rc.19 → 0.1.0-rc.20

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 (54) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +8 -0
  3. package/dist/camera-trait-45MJTW4K.js +1 -0
  4. package/dist/{capture-session-doc-VXWWQEP4.js → capture-session-doc-QA4DOFRF.js} +1 -1
  5. package/dist/{capture-session-v3-Cs4yV3HJ.d.cts → capture-session-v3-CNL-GX11.d.cts} +1 -1
  6. package/dist/{capture-session-v3-CFSVWYzi.d.ts → capture-session-v3-DaBqN8fO.d.ts} +1 -1
  7. package/dist/chunk-5ZKQHFFW.js +1 -0
  8. package/dist/{chunk-ZPXL26BF.js → chunk-FGOVIGGL.js} +1 -1
  9. package/dist/{chunk-RNJA5GDF.js → chunk-IG466TOP.js} +1 -1
  10. package/dist/{chunk-4GJXUVZK.js → chunk-KHR4U2SZ.js} +1 -1
  11. package/dist/chunk-KZBBB5B2.js +1 -0
  12. package/dist/chunk-NJML6FMD.js +1 -0
  13. package/dist/chunk-TQB3URP2.js +1 -0
  14. package/dist/{chunk-ZO6IHP2I.js → chunk-U6S7SCBY.js} +1 -1
  15. package/dist/{chunk-6K4D3U6Q.js → chunk-W2WD7PR2.js} +1 -1
  16. package/dist/chunk-XCKE2MJL.js +1 -0
  17. package/dist/chunk-ZLWH4RBO.js +1 -0
  18. package/dist/client/index.cjs +1 -1
  19. package/dist/client/index.d.cts +6 -71
  20. package/dist/client/index.d.ts +6 -71
  21. package/dist/client/index.js +1 -1
  22. package/dist/core/index.cjs +1 -1
  23. package/dist/core/index.d.cts +3 -3
  24. package/dist/core/index.d.ts +3 -3
  25. package/dist/core/index.js +1 -1
  26. package/dist/{create-document-capture-FVSQPUF6.js → create-document-capture-GJXBQMTC.js} +1 -1
  27. package/dist/{create-portrait-capture-INDCF65X.js → create-portrait-capture-MOS2D7CL.js} +1 -1
  28. package/dist/{create-verification-1BrMZqPJ.d.cts → create-verification-BBOUYpga.d.cts} +113 -22
  29. package/dist/{create-verification-CuoYJ3kj.d.ts → create-verification-COpe2hxf.d.ts} +113 -22
  30. package/dist/{icao-gate-BSbyqLUh.d.ts → icao-gate-CEGvJR3q.d.ts} +19 -9
  31. package/dist/{icao-gate-D-wePfoV.d.cts → icao-gate-l40OU6x1.d.cts} +19 -9
  32. package/dist/icao-policy-BgI1Y870.d.ts +71 -0
  33. package/dist/icao-policy-C7fIdRzo.d.cts +71 -0
  34. package/dist/index.cjs +1 -1
  35. package/dist/index.d.cts +7 -7
  36. package/dist/index.d.ts +7 -7
  37. package/dist/index.js +1 -1
  38. package/dist/internal/index.cjs +1 -1
  39. package/dist/internal/index.d.cts +6 -6
  40. package/dist/internal/index.d.ts +6 -6
  41. package/dist/internal/index.js +1 -1
  42. package/dist/plan-runner-35655N4Z.js +1 -0
  43. package/dist/print-AYSCRSZB.js +1 -0
  44. package/dist/{types-DPl0hsmI.d.cts → types-Dpfg2cO8.d.cts} +149 -11
  45. package/dist/{types-DPl0hsmI.d.ts → types-Dpfg2cO8.d.ts} +149 -11
  46. package/dist/upload-file-UYXOHCRG.js +1 -0
  47. package/package.json +3 -2
  48. package/sbom.cdx.json +46 -7
  49. package/dist/chunk-5Y3UST3W.js +0 -1
  50. package/dist/chunk-64V55KD7.js +0 -1
  51. package/dist/chunk-JUEOHNVW.js +0 -1
  52. package/dist/chunk-L45YTRJJ.js +0 -1
  53. package/dist/chunk-PLH6ZR6J.js +0 -1
  54. package/dist/plan-runner-WEUIMCYU.js +0 -1
@@ -1 +1 @@
1
- import{b as Jt}from"./chunk-SMKCBUJL.js";import{a as et,b as $t,c as te,e as dt,f as ee}from"./chunk-MXWLCDFX.js";import{d as Yt,h as Zt,k as qt}from"./chunk-G6LKLN4U.js";import{b as Xt,c as jt}from"./chunk-TDLIXFDT.js";import{b as Ht,c as Kt}from"./chunk-POIQGEZM.js";import{k as Nt,m as Qt,n as Ut,o as Wt}from"./chunk-CQ7SKLMC.js";import{b as ut,c as ht,d as j,e as Vt}from"./chunk-FPXL63KZ.js";import{c as Bt}from"./chunk-JUEOHNVW.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 ie(i){return i.framing==="no_document"?"sensing":i.framing==="too_far"?"too_far":i.framing==="too_close"?"too_close":i.framing==="edge_clipped"?"edge_clipped":i.framing==="wrong_shape"?"wrong_shape":i.framing==="tilted"?"tilted":i.lighting==="too_dark"?"too_dark":i.lighting==="too_bright"?"too_bright":i.glare==="glare"?"glare":i.blur==="blurry"?"blurry":"hold_still"}var nt=class{constructor(t=2600,e=.35){this.windowMs=t;this.decayPerSecond=e;this.votes=[];this.current=it.sensing;this.currentSinceMs=null}reset(){this.votes=[],this.current=it.sensing,this.currentSinceMs=null}force(t,e){return this.votes=[],this.current=it[t],this.currentSinceMs=e,this.current}tick(t,e){if(this.currentSinceMs===null&&(this.currentSinceMs=e),this.votes.push({key:t,atMs:e}),this.votes=this.votes.filter(r=>e-r.atMs<=this.windowMs),e-this.currentSinceMs<this.current.minDurationMs)return this.current;let n=new Map;for(let r of this.votes){let c=(e-r.atMs)/1e3,a=this.decayPerSecond**c;n.set(r.key,(n.get(r.key)??0)+a)}let o=this.current.key,s=-1;for(let[r,c]of n)c>s&&(s=c,o=r);return o!==this.current.key&&(this.current=it[o],this.currentSinceMs=e),this.current}};var Ke=Object.freeze({MAX_AREA_FRAC:.92,TILT_MAX_SIDE_RATIO:1.3,GLARE_MAX_SPECULAR_FRAC:.025});function oe(i){let{data:t,width:e,height:n}=i,o=e*n;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 Ve(i){let t=(a,l)=>Math.hypot(l.x-a.x,l.y-a.y),e=t(i.topLeft,i.topRight),n=t(i.bottomLeft,i.bottomRight),o=t(i.topLeft,i.bottomLeft),s=t(i.topRight,i.bottomRight),r=Math.max(e,n)/Math.max(1e-6,Math.min(e,n)),c=Math.max(o,s)/Math.max(1e-6,Math.min(o,s));return Math.max(r,c)}function se(i){let t={...$t,...i.thresholds},e=Ke,{quad:n,frameWidth:o,frameHeight:s,measures:r}=i,c=i.format==="ID-3",a="ok";if(n===null)a="no_document";else if(c){let m=dt(n),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":ne(n,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=te(n,o,s),h=dt(n),f=Math.max(h.width,h.height)/Math.max(1e-6,Math.min(h.width,h.height));m<t.MIN_AREA_FRAC?a="too_far":m>e.MAX_AREA_FRAC?a="too_close":ne(n,o,s,t.EDGE_CLIP_MARGIN_PX)?a="edge_clipped":jt(i.format,f)?Ve(n)>e.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>=e.GLARE_MAX_SPECULAR_FRAC?"glare":"ok";return{framing:a,lighting:l,blur:u,glare:d,acceptable:a==="ok"&&l==="ok"&&u==="ok"&&d==="ok"}}function ne(i,t,e,n){return[i.topLeft,i.topRight,i.bottomRight,i.bottomLeft].some(s=>s.x<=n||s.y<=n||s.x>=t-n||s.y>=e-n)}var ae=Object.freeze({width:1920,height:1080}),Xe=Object.freeze({width:3840,height:2160}),re=4096,je=2560,ce=640,ot=.15,Y=Object.freeze({side:.2,above:.9,below:.3});function E(i){let t=[i.topLeft.x,i.topRight.x,i.bottomRight.x,i.bottomLeft.x],e=[i.topLeft.y,i.topRight.y,i.bottomRight.y,i.bottomLeft.y],n=Math.min(...t),o=Math.min(...e);return{x:n,y:o,width:Math.max(...t)-n,height:Math.max(...e)-o}}function le(i,t){let e=Math.max(0,Math.floor(i.x)),n=Math.max(0,Math.floor(i.y)),o=Math.min(t.width,Math.ceil(i.x+i.width)),s=Math.min(t.height,Math.ceil(i.y+i.height));return o-e<16||s-n<16?null:{x:e,y:n,width:o-e,height:s-n}}function Ye(i,t,e){if(i===null||t.width<=0||t.height<=0)return null;let n=E(i);if(n.width<=0||n.height<=0)return null;let o=e==="ID-3"?{x:n.x-n.width*Y.side,y:n.y-n.width*Y.above,width:n.width*(1+2*Y.side),height:n.height+n.width*(Y.above+Y.below)}:{x:n.x-n.width*ot,y:n.y-n.height*ot,width:n.width*(1+2*ot),height:n.height*(1+2*ot)};return le(o,t)}function mt(i,t,e){let n=Math.max(i,t);return n>0?Math.min(1,e/n):1}function ft(i,t,e,n,o=je){let s=t.width>0?e.width/t.width:1,r=t.height>0?e.height/t.height:1,c=i===null?null:{topLeft:{x:i.topLeft.x*s,y:i.topLeft.y*r},topRight:{x:i.topRight.x*s,y:i.topRight.y*r},bottomRight:{x:i.bottomRight.x*s,y:i.bottomRight.y*r},bottomLeft:{x:i.bottomLeft.x*s,y:i.bottomLeft.y*r}},a=Ye(c,e,n)??{x:0,y:0,width:e.width,height:e.height},l=mt(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=E(c);m=le({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 ue(i,t,e,n=Xe){if(e==="LOW")return null;let o=i?.width?.max,s=i?.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(n.width,n.height)),l=Math.min(c,Math.min(n.width,n.height));return a<=Math.max(t.width,t.height)?null:{width:{ideal:a},height:{ideal:l}}}function he(i){let t={},e=i?.imageWidth,n=i?.imageHeight;if(typeof e?.max=="number"&&e.max>0){let o=typeof n?.max=="number"&&n.max>0?e.max/n.max:1.3333333333333333,s=o>=1?re:re*o,r=Math.min(e.max,Math.floor(s)),c=typeof e.step=="number"&&e.step>0?e.step:1,a=typeof e.min=="number"?e.min:0;r=Math.max(a,a+Math.floor((r-a)/c)*c),t.imageWidth=r}return i?.fillLightMode?.includes("off")===!0&&(t.fillLightMode="off"),t}function de(i,t){if(i.width<=0||i.height<=0||t.width<=0||t.height<=0)return!1;let e=i.width>i.height,n=t.width>t.height;return e!==n&&i.width!==i.height&&t.width!==t.height?!1:Math.max(i.width,i.height)>=1.2*Math.max(t.width,t.height)}function me(i,t,e,n){if(e===null)return!1;let o=E(i),s=E(e);if(t.width<=0||n.width<=0)return!1;let r=o.width/t.width,c=s.width/n.width;return c>0&&r>=.6*c&&r<=1.25*c}var fe=3500,Ze=.92;function ge(){let i=globalThis.ImageCapture;return typeof i=="function"?i:null}function Je(i){return/AppleWebKit\//.test(i)&&!/(Chrome|Chromium|Edg|OPR)\//.test(i)}function be(i,t=typeof navigator>"u"?"":navigator.userAgent){return ge()!==null&&!Je(t)&&i!=null&&i.kind==="video"&&i.readyState==="live"}function pe(i,t){return new Promise((e,n)=>{let o=setTimeout(()=>n(new Error("takePhoto timed out")),t);i.then(s=>{clearTimeout(o),e(s)},s=>{clearTimeout(o),n(s)})})}function pt(i,t){let e=document.createElement("canvas");return e.width=i,e.height=t,e}function qe(i,t){return new Promise((e,n)=>{i.toBlob(o=>o?e(o):n(new Error("toBlob failed")),"image/jpeg",t)})}async function ye(i,t,e,n,o){let s=pt(e,n),r=pt(1,1);try{let c=s.getContext("2d");if(c===null)throw new Error("2d context unavailable");c.imageSmoothingQuality="high",c.drawImage(i,t.x,t.y,t.width,t.height,0,0,e,n);let a=await qe(s,Ze),l=o===null?null:Yt({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:e,height:n},{width:e,height:n}),u=Zt(s,l),d=mt(e,n,ce);return r.width=Math.max(1,Math.round(e*d)),r.height=Math.max(1,Math.round(n*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 $e(i,t){let e=Math.min(1,t/i.width),n=pt(Math.max(1,Math.round(i.width*e)),Math.max(1,Math.round(i.height*e)));try{let o=n.getContext("2d",{willReadFrequently:!0});return o===null?null:(o.imageSmoothingQuality="high",o.drawImage(i,0,0,n.width,n.height),o.getImageData(0,0,n.width,n.height))}finally{n.width=0,n.height=0}}async function Me(i,t,e,n){let o={width:Math.max(1,i.videoWidth),height:Math.max(1,i.videoHeight)},s=ft(t,e,o,n);return{...await ye(i,s.crop,s.width,s.height,s.docRegion),docRegion:s.docRegion,source:"video",width:s.width,height:s.height}}async function ke(i,t,e,n,o){let s=ge();if(s===null)return null;let r=null;try{let c=new s(o.track),a=await pe(c.getPhotoCapabilities?.()??Promise.resolve({}),fe).catch(()=>({})),l=await pe(c.takePhoto(he(a)),fe);r=await createImageBitmap(l);let u={width:i.videoWidth,height:i.videoHeight};if(!de(r,u))return null;let d=$e(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&&!me(m,h,t,e)&&(m=null);let f=ft(m,h,r,n);return{...await ye(r,f.crop,f.width,f.height,f.docRegion),docRegion:f.docRegion,source:"photo",width:f.width,height:f.height}}catch{return null}finally{r?.close()}}var st=Object.freeze({width:3840,height:2160,lensSelection:!0,continuousFocus:!0,refocusBeforePhotoMs:350,zoomMax:2,zoomNoFocusInfo:1.5,zoomMinSourcePx:2160,fillDistanceM:Object.freeze({id1:.11,id3:.15}),focusMarginFrac:.2,stillSharpnessMin:.16,stillRefusalsMax:2,focusFarFillFrac:.45,noDocFarHintMs:1500,zoomFallbackMs:8e3}),S=(i,t,e)=>typeof i=="number"&&Number.isFinite(i)&&i>=t&&i<=e?i:void 0;function Ti(i){let t=st,e=i!==null&&typeof i=="object"?i:{},n=e.fillDistanceM!==null&&typeof e.fillDistanceM=="object"?e.fillDistanceM:{},o=(s,r)=>typeof s=="boolean"?s:r;return{width:S(e.width,640,7680)??t.width,height:S(e.height,480,4320)??t.height,lensSelection:o(e.lensSelection,t.lensSelection),continuousFocus:o(e.continuousFocus,t.continuousFocus),refocusBeforePhotoMs:S(e.refocusBeforePhotoMs,0,2e3)??t.refocusBeforePhotoMs,zoomMax:S(e.zoomMax,1,5)??t.zoomMax,zoomNoFocusInfo:S(e.zoomNoFocusInfo,1,5)??t.zoomNoFocusInfo,zoomMinSourcePx:S(e.zoomMinSourcePx,0,8e3)??t.zoomMinSourcePx,fillDistanceM:{id1:S(n.id1,.03,1)??t.fillDistanceM.id1,id3:S(n.id3,.03,1)??t.fillDistanceM.id3},focusMarginFrac:S(e.focusMarginFrac,0,2)??t.focusMarginFrac,stillSharpnessMin:S(e.stillSharpnessMin,0,10)??t.stillSharpnessMin,stillRefusalsMax:S(e.stillRefusalsMax,0,10)??t.stillRefusalsMax,focusFarFillFrac:S(e.focusFarFillFrac,0,1)??t.focusFarFillFrac,noDocFarHintMs:S(e.noDocFarHintMs,0,6e4)??t.noDocFarHintMs,zoomFallbackMs:S(e.zoomFallbackMs,0,12e4)??t.zoomFallbackMs}}function ti(i){let t=i.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 ei(i){let t=/camera2?\s*(\d+)/i.exec(i);return t?Number(t[1]):Number.POSITIVE_INFINITY}function ii(i){let t={main:0,virtual:1,ultra:9,tele:9,depth:9,front:9,unknown:9};return i.filter(e=>(e.kind===void 0||e.kind==="videoinput")&&e.deviceId!=="").map((e,n)=>({id:e.deviceId,kind:ti(e.label),index:ei(e.label),i:n})).filter(e=>t[e.kind]<9).sort((e,n)=>t[e.kind]-t[n.kind]||e.index-n.index||e.i-n.i).map(e=>e.id)}var gt="sekyro.doc.camera";function ni(){try{let i=globalThis.localStorage?.getItem(gt);return typeof i=="string"&&i!==""?i:null}catch{return null}}function xe(i){try{i===null?globalThis.localStorage?.removeItem(gt):globalThis.localStorage?.setItem(gt,i)}catch{}}var rt=(i,t)=>Array.isArray(i?.focusMode)&&i.focusMode.includes(t);function yt(i,t,e){if(!rt(i,"single-shot"))return null;let n=o=>Math.min(1,Math.max(0,Number.isFinite(o)?o:.5));return{focusMode:"single-shot",pointsOfInterest:[{x:n(t),y:n(e)}]}}function _i(i,t,e,n){if(!Number.isFinite(i)||!Number.isFinite(t)||e.width<=0||e.height<=0||n.width<=0||n.height<=0)return null;let o=Math.max(e.width/n.width,e.height/n.height),s=n.width*o,r=n.height*o,c=(i-e.left+(s-e.width)/2)/s,a=(t-e.top+(r-e.height)/2)/r;return{x:Math.min(1,Math.max(0,c)),y:Math.min(1,Math.max(0,a))}}function we(i,t,e,n=st){let o=i?.zoom?.min,s=i?.zoom?.max;if(typeof s!="number"||s<=1)return 1;let r=e==="ID-3"?n.fillDistanceM.id3:n.fillDistanceM.id1,c=i?.focusDistance?.min,a;if(typeof c=="number"&&c>0&&c<1){if(a=c*(1+n.focusMarginFrac)/r,a<=1.05)return 1}else{if(Math.min(t.width,t.height)<n.zoomMinSourcePx)return 1;a=n.zoomNoFocusInfo}let l=Math.min(a,n.zoomMax,s);typeof o=="number"&&(l=Math.max(l,o));let u=i?.zoom?.step;return typeof u=="number"&&u>0&&(l=Math.round(l/u)*u),l>1.01?Number(l.toFixed(2)):1}function bt(i){try{return i.getVideoTracks?.()[0]}catch{return}}function De(i){if(i!==null)for(let t of i.getTracks())t.stop()}function oi(i){try{let t=bt(i)?.getCapabilities?.();return!Array.isArray(t?.focusMode)||t.focusMode.includes("continuous")}catch{return!0}}var si=3;async function ve(i){let t=s=>({audio:!1,video:{...s,width:{ideal:i.base.width},height:{ideal:i.base.height}}}),e=s=>i.getUserMedia(t({deviceId:{exact:s}})),n=()=>i.getUserMedia(t({facingMode:{ideal:"environment"}}));if(i.lensSelection){let s=ni();if(s!==null)try{return{stream:await e(s),lens:"stored"}}catch{xe(null)}}let o=await n();if(!i.lensSelection||i.enumerateDevices===void 0)return{stream:o,lens:"default"};try{let s=ii(await i.enumerateDevices()).slice(0,si);if(s.length===0)return{stream:o,lens:"default"};let r=null;for(let c of s){let a=o!==null?bt(o)?.getSettings?.().deviceId:void 0;if(o===null||a!==c){De(o),o=null;try{o=await e(c)}catch{continue}}if(r??(r=c),oi(o))return xe(c),{stream:o,lens:"selected"}}if(o!==null&&r!==null&&bt(o)?.getSettings?.().deviceId===r)return{stream:o,lens:"selected"};if(De(o),o=null,r!==null)try{return{stream:await e(r),lens:"selected"}}catch{}return{stream:await n(),lens:"default"}}catch{return{stream:o??await n(),lens:"default"}}}var Z=Object.freeze({brightness:0,glare:0,cardGlare:0,sharpness:0,fill:0,shape:0,content:0,offsetX:0,offsetY:0,edgeConfidence:0,box:null}),L=i=>Math.min(1,Math.max(0,i));function Te(i,t,e,n=.06){let o=Math.max(i.width/e,i.height),s=o*e,r=(i.width-s)/2,c=(i.height-o)/2,a=L((t.x-t.width*n-r)/s),l=L((t.y-t.height*n-c)/o),u=L((t.x+t.width*(1+n)-r)/s),d=L((t.y+t.height*(1+n)-c)/o);return{x:a,y:l,width:u-a,height:d-l}}function _e(i,t,e={}){let n=e.edgePeakFrac??0,{width:o,height:s,data:r}=i;if(o<=0||s<=0)return Z;let c=L(t.x),a=L(t.y),l={x:c,y:a,width:Math.max(0,L(t.x+t.width)-c),height:Math.max(0,L(t.y+t.height)-a)};if(l.width<=0||l.height<=0)return Z;let u=l.x*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,R)=>Math.min(R,Math.max(b,p)),x=y(Math.floor(u-f),0,o-1),w=y(Math.floor(d-g),0,s-1),I=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(I-x,v-w)/320)),M=Math.floor((I-x+D-1)/D),T=Math.floor((v-w+D-1)/D);if(M<3||T<3)return Z;let k=new Int32Array(M*T);for(let p=0;p<T;p++){let b=w+p*D;for(let R=0;R<M;R++){let F=(b*o+x+R*D)*4;k[p*M+R]=(r[F]??0)*77+(r[F+1]??0)*150+(r[F+2]??0)*29>>8}}let C=(p,b)=>(p-b-.5)/D,_=C(u,x),A=C(m,x),B=C(d,w),U=C(h,w),kt=(m-u)/D,xt=(h-d)/D,Dt=y(Math.ceil(_),0,M-1),Ie=y(Math.floor(A),Dt,M-1),wt=y(Math.ceil(B),0,T-1),Oe=y(Math.floor(U),wt,T-1),vt=0,St=0,W=0,Tt=0,_t=0,H=0;for(let p=wt;p<=Oe;p++)for(let b=Dt;b<=Ie;b++){let R=k[p*M+b];if(vt+=R,R>=248&&St++,W++,b>=1&&b<M-1&&p>=1&&p<T-1){let F=k[p*M+b-1]+k[p*M+b+1]+k[(p-1)*M+b]+k[(p+1)*M+b]-4*R;Tt+=F,_t+=F*F,H++}}let Pe=W>0?vt/W:0,Rt=W>0?St/W:0,Ft=H>0?Tt/H:0,Ge=H>0?Math.max(0,_t/H-Ft*Ft):0,K=new Float64Array(M),V=new Float64Array(T);for(let p=0;p<T;p++)for(let b=1;b<M-1;b++)K[b]=K[b]+Math.abs(k[p*M+b+1]-k[p*M+b-1]);for(let p=1;p<T-1;p++)for(let b=0;b<M;b++)V[p]=V[p]+Math.abs(k[(p+1)*M+b]-k[(p-1)*M+b]);let O=at(K,!0,_,n),P=at(K,!1,A,n),G=at(V,!0,B,n),z=at(V,!1,U,n),Ct=(P.position-O.position)/kt,At=(z.position-G.position)/xt,ze=At>0?Ct/At:0,Ne=((O.position+P.position)/2-(_+A)/2)/kt,Qe=((G.position+z.position)/2-(B+U)/2)/xt,Et=Se(K),Lt=Se(V),Be=Et<=0||Lt<=0?0:Math.min(Math.min(O.value,P.value)/Et,Math.min(G.value,z.value)/Lt),$=(p,b)=>b+(p+.5)*D,It=Rt,Ot=0;{let p=(P.position-O.position)*.06,b=(z.position-G.position)*.06,R=y(Math.ceil(O.position+p),0,M-1),F=y(Math.floor(P.position-p),0,M-1),Ue=y(Math.ceil(G.position+b),0,T-1),Pt=y(Math.floor(z.position-b),0,T-1),Gt=0,tt=0,zt=0;for(let N=Ue;N<=Pt;N++)for(let Q=R;Q<=F;Q++){tt++;let X=k[N*M+Q];X>=248&&Gt++;let We=Q+2<=F?k[N*M+Q+2]:X,He=N+2<=Pt?k[(N+2)*M+Q]:X;(Math.abs(We-X)>=24||Math.abs(He-X)>=24)&&zt++}tt>=16&&(It=Gt/tt,Ot=zt/tt)}return{brightness:Pe,glare:Rt,cardGlare:It,sharpness:Ge,fill:Ct,shape:ze,content:Ot,offsetX:Ne,offsetY:Qe,edgeConfidence:Be,box:{left:$(O.position,x),right:$(P.position,x),top:$(G.position,w),bottom:$(z.position,w)}}}function at(i,t,e,n){let o=i.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++)i[h]>i[a]&&(a=h);if(n>0&&n<1){let h=i[a]*n,f=a,g=Math.abs(a-e);for(let y=r;y<=c;y++){let x=i[y];if(x<h||x<(i[y-1]??0)||x<(i[y+1]??0))continue;let w=Math.abs(y-e);w<g&&(f=y,g=w)}a=f}let l=a>0?i[a-1]:0,u=i[a],d=a<o-1?i[a+1]:0,m=l+u+d;return{position:m>0?a+(d-l)/m:a,value:u}}function Se(i){if(i.length<3)return 0;let t=0;for(let e=1;e<i.length-1;e++)t+=i[e];return t/(i.length-2)}function Re(i){let t=i.box;return t===null||t.right-t.left<4||t.bottom-t.top<4?null:{topLeft:{x:t.left,y:t.top},topRight:{x:t.right,y:t.top},bottomRight:{x:t.right,y:t.bottom},bottomLeft:{x:t.left,y:t.bottom}}}var J=Object.freeze({fillMin:.82,fillMax:1.06,offsetMax:.06,glareMax:.025,sharpnessMin:180,edgeConfidenceMin:1.6,darkBrightness:70,lockMs:450,steadyMs:900,steadyFillMin:.45,steadyFillMax:1.3,steadyFillDelta:.06,steadyOffsetDelta:.04,steadyRefMs:100,edgePeakFrac:.4,shapeTolerance:.2,contentMin:.1});function Fi(i){let t=i!==null&&typeof i=="object"?i:{},e={...J};for(let n of Object.keys(J)){let o=t[n];typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=1e6&&(e[n]=o)}return e}var ct=class{constructor(t=J){this.t=t;this.goodSince=null;this.steadySince=null;this.last=null}reset(){this.goodSince=null,this.steadySince=null,this.last=null}tick(t,e){let n=this.t,o=n.shapeTolerance<=0||Math.abs(t.shape-1)<=n.shapeTolerance,s=t.edgeConfidence>=n.edgeConfidenceMin&&o&&t.content>=n.contentMin,r=t.fill>=n.fillMin&&t.fill<=n.fillMax,c=Math.abs(t.offsetX)<=n.offsetMax&&Math.abs(t.offsetY)<=n.offsetMax,a=t.cardGlare<=n.glareMax,l=t.sharpness>=n.sharpnessMin,u=this.last;this.last={fill:t.fill,offsetX:t.offsetX,offsetY:t.offsetY,at:e};let d=u!==null&&n.steadyRefMs>0?Math.min(3,Math.max(1,(e-u.at)/n.steadyRefMs)):1,m=s&&a&&l&&t.fill>=n.steadyFillMin&&t.fill<=n.steadyFillMax&&u!==null&&Math.abs(t.fill-u.fill)<=n.steadyFillDelta*d&&Math.abs(t.offsetX-u.offsetX)<=n.steadyOffsetDelta*d&&Math.abs(t.offsetY-u.offsetY)<=n.steadyOffsetDelta*d,h=s&&r&&c&&a&&l,f;if(s?a?t.fill<n.fillMin?f="too_small":t.fill>n.fillMax?f="too_big":l?c?f="locking":f="off_center":f="blurry":f="glare":f="no_card",h){if(m&&(this.steadySince??(this.steadySince=e)),this.goodSince??(this.goodSince=e),e-this.goodSince>=n.lockMs)return{detected:s,ready:!0,via:"good",blocker:"locking"};let g=this.steadySince!==null&&e-this.steadySince>=n.steadyMs;return{detected:s,ready:g,via:g?"steady":null,blocker:"locking"}}if(this.goodSince=null,m){this.steadySince??(this.steadySince=e);let g=e-this.steadySince>=n.steadyMs;return{detected:s,ready:g,via:g?"steady":null,blocker:g?"locking":"steadying"}}return this.steadySince=null,{detected:s,ready:!1,via:null,blocker:f}}};var q=null;async function ri(i){return q===null&&(q=(await import("./detector-scanic-YCDNLCGV.js")).detectQuad),q(i)}async function ai(i){let t=Jt(i);return t===null?null:{topLeft:{x:t.x,y:t.y},topRight:{x:t.x+t.width,y:t.y},bottomRight:{x:t.x+t.width,y:t.y+t.height},bottomLeft:{x:t.x,y:t.y+t.height}}}function Vi(){q===null&&import("./detector-scanic-YCDNLCGV.js").then(i=>{q=i.detectQuad}).catch(()=>{})}var Fe=4e3,ci=2,Ce=3,li=Object.freeze({LOW:3,MID:5,HIGH:6}),Mt=Object.freeze({manualShutterMs:6e3,detectedNoLockMs:1950});function Xi(i){let t=i!==null&&typeof i=="object"?i:{},e=(n,o,s)=>typeof n=="number"&&Number.isFinite(n)&&n>=o&&n<=s?n:void 0;return{manualShutterMs:e(t.manualShutterMs,1e3,6e4)??Mt.manualShutterMs,detectedNoLockMs:e(t.steadyMs,300,3e4)!==void 0?t.steadyMs+(e(t.lockMs,0,1e4)??450):Mt.detectedNoLockMs}}var Ae=class i{constructor(t){this.torchOn=!1;this.stillRefusals=0;this.zoom=1;this.positioningSince=null;this.detectedSince=null;this.lastSeenAt=null;this.lastGuideQuad=null;this.lastOcrReady=null;this.shutterOffered=!1;this.stats=i.freshStats();this.handlers=new Map;this.stream=null;this.timer=null;this.state="idle";this.lastGuidance=null;this.attempt=0;this.capturing=!1;this.feedback=new nt;this.lastFeedbackKey=null;this.lastQuad=null;this.lastDetect=null;this.frameWatch=null;this.reopened=!1;this.lit=!1;this.blackTicks=0;this.offEnded=null;this.opts=t,this.gate=new ee(t.format??"ID-1",t.thresholds);let e=t.deviceClass??Kt(Ht());this.deviceClass=e,this.camera=t.camera??st,this.shutterTuning=t.shutter??Mt,this.guideTuning=t.guideLock??J,this.guideLock=new ct(this.guideTuning),this.cadenceMs=1e3/li[e]}on(t,e){let n=this.handlers.get(t);return n||(n=new Set,this.handlers.set(t,n)),n.add(e),()=>n?.delete(e)}emit(t,e){for(let n of[...this.handlers.get(t)??[]])n(e)}async start(){let t=this.state==="error"?this.resumePlayback():null,e=++this.attempt;if(this.clearFrameWatch(),this.gate.reset(),this.resetSide(),this.feedback.reset(),this.lastFeedbackKey=null,this.lastGuidance=null,this.capturing=!1,this.lit=!1,this.blackTicks=0,t!==null&&await t&&e===this.attempt){this.setState("positioning"),this.scheduleTick(e),this.watchFrames(e);return}if(e===this.attempt){this.releaseStream(),Wt(),this.setState("preflight");try{let n=this.opts.getUserMedia??(r=>navigator.mediaDevices.getUserMedia(r));this.setState("acquiring");let o=this.opts.enumerateDevices??(this.opts.getUserMedia===void 0&&typeof navigator<"u"&&navigator.mediaDevices?.enumerateDevices?()=>navigator.mediaDevices.enumerateDevices():void 0),s=await ve({getUserMedia:n,...o!==void 0?{enumerateDevices:o}:{},lensSelection:this.camera.lensSelection,base:ae});if(e!==this.attempt){for(let r of s.stream.getTracks())r.stop();return}if(this.stream=s.stream,Bt(this.stream),Ut(this.stream),this.watchEnded(e),this.opts.upgradeResolution!==!1&&await this.upgradeResolution(),e!==this.attempt||(await this.applyFocusAndZoom(),e!==this.attempt)||(this.opts.video.srcObject=this.stream,await this.opts.video.play().catch(()=>{}),e!==this.attempt))return;this.setState("positioning"),this.scheduleTick(e),this.watchFrames(e)}catch(n){if(e!==this.attempt)return;let o=Qt(n),s=Nt(n);this.setState("error"),this.emit("error",{kind:o,retryable:!0,detail:s===void 0?{phase:"acquiring"}:{phase:"acquiring",name:s}})}}}resumePlayback(){let t=this.opts.video,e=this.videoTrack();if(this.stream===null||e===null||e.readyState!=="live"||t.srcObject!==this.stream)return null;try{return Promise.resolve(t.play()).then(()=>this.framesNow(),()=>!1)}catch{return null}}framesNow(){let t=this.opts.video;return this.opts.hasFrames!==void 0?this.opts.hasFrames(t):!t.paused&&t.readyState>=2&&t.videoWidth>0}watchFrames(t){let e=this.opts.firstFrameMs??Fe;e<=0||(this.clearFrameWatch(),this.frameWatch=setTimeout(()=>{if(this.frameWatch=null,!(t!==this.attempt||this.state!=="positioning")){if(this.framesNow()&&this.blackTicks<Ce){this.reopened=!1;return}this.cameraDead(t)}},e))}clearFrameWatch(){this.frameWatch!==null&&clearTimeout(this.frameWatch),this.frameWatch=null}watchEnded(t){this.offEnded?.(),this.offEnded=null;let e=this.videoTrack();if(e===null||typeof e.addEventListener!="function")return;let n=()=>{t===this.attempt&&(this.state==="positioning"||this.state==="acquiring")&&this.cameraDead(t)};e.addEventListener("ended",n),this.offEnded=()=>e.removeEventListener?.("ended",n)}cameraDead(t){if(t!==this.attempt)return;let e=this.videoTrack(),n=e!==null&&e.readyState==="live"&&!e.muted&&this.opts.video.paused&&!this.framesNow();if(!n&&!this.reopened){this.reopened=!0,this.start();return}this.attempt+=1,this.timer!==null&&(this.opts.clearTimer??clearTimeout)(this.timer),this.timer=null,this.clearFrameWatch(),n||this.releaseStream(),this.reopened=!1,this.setState("error"),this.emit("error",{kind:"generic",retryable:!0,detail:{phase:"acquiring"}})}releaseStream(){if(this.offEnded?.(),this.offEnded=null,this.stream)for(let t of this.stream.getTracks())t.stop();this.stream=null,this.opts.video.srcObject!==null&&this.opts.video.srcObject!==void 0&&(this.opts.video.srcObject=null)}rearm(t){t!==void 0&&(this.opts.side=t),this.gate.reset(),this.resetSide(),this.feedback.reset(),this.lastFeedbackKey=null,this.lastGuidance=null,this.capturing=!1,this.stillRefusals=0,this.state==="captured"&&(this.setState("positioning"),this.scheduleTick(this.attempt))}async captureNow(){if(this.state!=="positioning"||this.capturing)return;let t=this.opts.video,e=this.lastDetect?.width??Math.max(1,t.videoWidth),n=this.lastDetect?.height??Math.max(1,t.videoHeight),o=this.lastQuad??this.lastGuideQuad??{topLeft:{x:0,y:0},topRight:{x:e,y:0},bottomRight:{x:e,y:n},bottomLeft:{x:0,y:n}},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:e,height:n,tickSharpness:this.lastDetect?.tickSharpness??0},this.lastOcrReady?.via??"manual")}captureReport(){let t=this.stats;return{...this.opts.side!==void 0?{side:this.opts.side}:{},format:this.opts.format??"ID-1",deviceClass:this.deviceClass,video:{width:this.opts.video.videoWidth||0,height:this.opts.video.videoHeight||0},zoom:this.zoom,...t.zoomFallbackAtMs!==void 0?{zoomFallbackAtMs:t.zoomFallbackAtMs}:{},...t.msToCapture!==void 0?{msToCapture:t.msToCapture}:{},...t.via!==void 0?{via:t.via}:{},...t.shutterAtMs!==void 0?{shutterAtMs:t.shutterAtMs}:{},...t.shutterReason!==void 0?{shutterReason:t.shutterReason}:{},ticks:t.ticks,quadFraming:{...t.quadFraming},qualityBlockers:{...t.qualityBlockers},guideBlockers:{...t.guideBlockers},stillRefusals:t.stillRefusals,...this.ocrReport()}}ocrReport(){let t=this.opts.ocr;if(t===void 0)return{};let e=(this.opts.format??"ID-1")==="ID-3"||this.opts.side==="single"?"single":this.opts.side==="verso"?"verso":"recto",n=t.report(e,this.stats.via,(this.opts.now??(()=>performance.now()))());return n===null?{}:{ocr:n}}static freshStats(){return{ticks:0,quadFraming:{},qualityBlockers:{},guideBlockers:{},stillRefusals:0}}setGuide(t){t===void 0?delete this.opts.guide:this.opts.guide=t,this.guideLock.reset()}guideRegion(t){let e=t.width/Math.max(1,t.height),n=this.opts.guide;if(n!==void 0&&n.viewAspect>0){let c={width:n.viewAspect,height:1},a={x:n.rect.x*n.viewAspect,y:n.rect.y,width:n.rect.width*n.viewAspect,height:n.rect.height};return Te(c,a,e,0)}let o=Xt(this.opts.format??"ID-1").center,s=.86,r=s*e/o;return r>.84&&(r=.84,s=r*o/e),{x:(1-s)/2,y:(1-r)/2,width:s,height:r}}resetSide(){this.positioningSince=null,this.detectedSince=null,this.lastSeenAt=null,this.guideLock.reset(),this.lastGuideQuad=null,this.lastOcrReady=null,this.opts.ocr?.reset(),this.stats=i.freshStats(),this.shutterOffered&&(this.shutterOffered=!1,this.emit("shutter",{available:!1}))}withdrawShutter(){this.shutterOffered&&(this.shutterOffered=!1,this.emit("shutter",{available:!1}))}zoomFallback(t){let e=this.videoTrack();if(e===null||this.zoom<=1)return;let n=this.focusCaps(),o=typeof n?.zoom?.min=="number"?Math.max(n.zoom.min,1):1;this.zoom=o,this.stats.zoomFallbackAtMs=Math.round(t-(this.positioningSince??t)),this.guideLock.reset(),this.gate.reset(),e.applyConstraints({advanced:[{zoom:o}]}).catch(()=>{})}offerShutter(t,e){this.shutterOffered||(this.shutterOffered=!0,this.stats.shutterAtMs=Math.round(e-(this.positioningSince??e)),this.stats.shutterReason=t,this.emit("shutter",{available:!0,reason:t}))}torchAvailable(){try{return this.stream?.getVideoTracks?.()[0]?.getCapabilities?.()?.torch===!0}catch{return!1}}async setTorch(t){this.torchOn=t;try{await this.stream?.getVideoTracks?.()[0]?.applyConstraints({advanced:[{torch:t}]})}catch{}}destroy(){if(this.attempt+=1,this.timer!==null&&(this.opts.clearTimer??clearTimeout)(this.timer),this.timer=null,this.clearFrameWatch(),this.offEnded?.(),this.offEnded=null,this.stream)for(let t of this.stream.getTracks())t.stop();this.stream=null,this.opts.video.srcObject=null}async upgradeResolution(){try{let t=this.stream?.getVideoTracks?.()[0];if(t===void 0)return;let e=t.getSettings?.()??{},n=ue(t.getCapabilities?.(),{width:e.width??0,height:e.height??0},this.deviceClass,{width:this.camera.width,height:this.camera.height});n!==null&&await t.applyConstraints(n)}catch{}}focusCaps(){try{return this.videoTrack()?.getCapabilities?.()??null}catch{return null}}async applyFocusAndZoom(){let t=this.videoTrack();if(t===null)return;let e=this.focusCaps();this.camera.continuousFocus&&rt(e,"continuous")&&await t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{});let n={width:0,height:0};try{let s=t.getSettings?.()??{};n={width:s.width??0,height:s.height??0}}catch{}let o=we(e,n,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,e){let n=this.videoTrack(),o=yt(this.focusCaps(),t,e);if(!(n===null||o===null))try{await n.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,e){let n=this.camera.refocusBeforePhotoMs,o=this.videoTrack();if(n<=0||o===null||e.width<=0||e.height<=0)return;let s=E(t),r=yt(this.focusCaps(),(s.x+s.width/2)/e.width,(s.y+s.height/2)/e.height);if(r!==null)try{await o.applyConstraints({advanced:[r]});let c=this.opts.setTimer??setTimeout;await new Promise(a=>{c(()=>a(),n)})}catch{}}videoTrack(){try{return this.stream?.getVideoTracks?.()[0]??null}catch{return null}}async takeStill(t,e,n){if(this.opts.captureStill!==void 0)return this.opts.captureStill(this.opts.video,t,e);let o=this.opts.format??"ID-1",s=this.videoTrack();if(n&&this.opts.photoCapture!==!1&&this.deviceClass!=="LOW"&&!this.torchOn&&s!==null&&be(s)){await this.refocusOn(t,e);let r=await ke(this.opts.video,t,e,o,{track:s,detect:this.detector(),detectWidth:et});if(this.restoreContinuous(),r!==null)return r}return Me(this.opts.video,t,e,o)}detector(){return this.opts.detect??((this.opts.format??"ID-1")==="ID-3"?ai:ri)}setState(t){this.state=t,this.emit("statechange",{state:t})}scheduleTick(t){let e=this.opts.setTimer??setTimeout;this.timer=e(()=>{this.tick(t)},this.cadenceMs)}async tick(t){if(t!==this.attempt||this.state!=="positioning"||this.capturing)return;let e=this.opts.now??(()=>performance.now()),n=this.opts.grabDetectFrame??Le,o=this.detector(),s=n(this.opts.video,et);if(s===null){this.scheduleTick(t);return}if(!this.lit){if(ht(s)>ci)this.lit=!0,this.blackTicks=0;else if(++this.blackTicks>=Ce&&this.frameWatch===null&&(this.opts.firstFrameMs??Fe)>0){this.cameraDead(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=e(),l={sharpness:j(c),exposure:Vt(c),meanLuma:ht(c),specularFraction:oe(c)},u=se({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"?_e(s,this.guideRegion(s),{edgePeakFrac:this.guideTuning.edgePeakFrac}):Z,f=this.guideLock.tick(h,a);this.lastGuideQuad=f.detected?Re(h):null;let g=this.capturing?null:this.ocrTick(s,r,h,f.detected,u,a);this.positioningSince??(this.positioningSince=a);let y=this.stats;if(y.ticks+=1,y.quadFraming[u.framing]=(y.quadFraming[u.framing]??0)+1,u.framing==="ok"&&!d.ready){let _=u.lighting!=="ok"?u.lighting:u.glare!=="ok"?"glare":u.blur!=="ok"?"blurry":"steadying";y.qualityBlockers[_]=(y.qualityBlockers[_]??0)+1}y.guideBlockers[f.blocker]=(y.guideBlockers[f.blocker]??0)+1,r!==null||f.detected?(this.detectedSince??(this.detectedSince=a),this.lastSeenAt=a):this.detectedSince=null,this.lastSeenAt!==null&&a-this.lastSeenAt<=gi?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 I=a-(this.lastSeenAt??this.positioningSince);this.zoom>1&&this.camera.zoomFallbackMs>0&&I>=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=ie(u);u.framing!=="ok"&&f.detected&&(v=pi(f.blocker,h.brightness<this.guideTuning.darkBrightness)),v==="blurry"&&r!==null&&hi(r,s,this.opts.format??"ID-1")>=this.camera.focusFarFillFrac&&(v="focus_far"),v==="sensing"&&this.zoom>1&&this.camera.noDocFarHintMs>0&&I>=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,T=M&&d.ready&&r!==null,k=M&&f.ready&&this.lastGuideQuad!==null,C=this.lastOcrReady;if(C!==null&&this.opts.autoCapture!==!1){let _=this.feedback.force("processing",a);this.lastFeedbackKey=_.key,this.emit("feedback",_);let A=j(lt(s,C.quad));await this.fire(t,C.quad,{width:s.width,height:s.height,tickSharpness:A},C.via);return}if((T||k)&&this.opts.autoCapture!==!1){let _=this.feedback.force("processing",a);this.lastFeedbackKey=_.key,this.emit("feedback",_);let A=k?this.lastGuideQuad:r,B=k?f.via==="steady"?"guide_steady":"guide_good":"quad",U=k?j(lt(s,A)):l.sharpness;await this.fire(t,A,{width:s.width,height:s.height,tickSharpness:U},B);return}this.scheduleTick(t)}async fire(t,e,n,o){this.capturing=!0;let s=this.opts.grabDetectFrame??Le,r=this.opts.setTimer??setTimeout,c={width:n.width,height:n.height};try{let a={still:await this.takeStill(e,c,!0),sharpness:n.tickSharpness};if(t!==this.attempt)return;let l=a.still.source==="photo"?0:di;for(let m=0;m<l;m++){if(await new Promise(g=>{r(()=>g(),mi)}),t!==this.attempt)return;let h=s(this.opts.video,et);if(h===null)continue;let f=j(lt(h,e));if(f>a.sharpness*fi){let g=await this.takeStill(e,c,!1);if(t!==this.attempt)return;a={still:g,sharpness:f}}}if(t!==this.attempt)return;let u=a.still.sharpness;if(this.opts.autoCapture!==!1&&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,e,n,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&&e!==null?x=ui(E(e),g,y,l,u):x=qt(f,c.bandTop,u);let w=m?s.glare==="ok":n.cardGlare<=this.guideTuning.glareMax,I=m?s.blur==="ok":n.sharpness>=this.guideTuning.sharpnessMin,v=c.tick({atMs:r,video:a,mrzFace:m||this.opts.side==="verso"||this.opts.side==="single",present:m||e!==null||o,card:f,band:x,portrait:u>l,glareOk:w,sharpOk:I});if(v.ready&&v.via!==void 0){let D=m?e??Ee(h,t):this.lastGuideQuad??Ee(h,t);this.lastOcrReady={quad:D,via:v.via}}else this.lastOcrReady=null;return v}};function ui(i,t,e,n,o){let s=Math.min(n,i.width*1.06*t),r=Math.min(o,Math.max(i.height*1.6*e,s/5)),c=(i.y+i.height/2)*e,a=Math.max(0,Math.min(n-s,(i.x-i.width*.03)*t)),l=Math.max(0,Math.min(o-r,c-r/2));return{x:a,y:l,w:s,h:r}}function Ee(i,t){let e=i.x*t.width,n=i.y*t.height,o=(i.x+i.width)*t.width,s=(i.y+i.height)*t.height;return{topLeft:{x:e,y:n},topRight:{x:o,y:n},bottomRight:{x:o,y:s},bottomLeft:{x:e,y:s}}}function hi(i,t,e){let n=E(i);return t.width<=0||t.height<=0?0:e==="ID-3"?n.width/t.width:n.width*n.height/(t.width*t.height)}var di=2,mi=260,fi=1.08;function Le(i,t){let e=i.videoWidth,n=i.videoHeight;if(e===0||n===0)return null;let o=Math.min(1,t/e),s=Math.round(e*o),r=Math.round(n*o),c=document.createElement("canvas");c.width=s,c.height=r;let a=c.getContext("2d",{willReadFrequently:!0});return a===null?null:(e/Math.max(1,s)>4&&(a.imageSmoothingQuality="high"),a.drawImage(i,0,0,s,r),a.getImageData(0,0,s,r))}function lt(i,t){let e=[t.topLeft.x,t.topRight.x,t.bottomRight.x,t.bottomLeft.x],n=[t.topLeft.y,t.topRight.y,t.bottomRight.y,t.bottomLeft.y],o=Math.max(0,Math.floor(Math.min(...e))),s=Math.max(0,Math.floor(Math.min(...n))),r=Math.min(i.width,Math.ceil(Math.max(...e))),c=Math.min(i.height,Math.ceil(Math.max(...n))),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)*i.width+o)*4;u.set(i.data.subarray(m,m+a*4),d*a*4)}return{data:u,width:a,height:l,colorSpace:i.colorSpace}}function pi(i,t){return i==="glare"?"glare":i==="too_small"?"too_far":i==="too_big"?"too_close":t?"too_dark":i==="blurry"?"blurry":i==="off_center"?"edge_clipped":i==="no_card"?"sensing":"hold_still"}var gi=1200;export{it as a,ie as b,nt as c,Ke as d,oe as e,Ve as f,se as g,st as h,Ti as i,ti as j,ii as k,gt as l,ni as m,xe as n,rt as o,yt as p,_i as q,we as r,oi as s,si as t,ve as u,Z as v,Te as w,_e as x,Re as y,J as z,Fi as A,ct as B,Vi as C,Fe as D,ci as E,Ce as F,li as G,Mt as H,Xi as I,Ae as J,ui as K,di as L,mi as M};
1
+ import{b as Jt}from"./chunk-SMKCBUJL.js";import{a as et,b as $t,c as te,e as dt,f as ee}from"./chunk-MXWLCDFX.js";import{d as Yt,h as Zt,k as qt}from"./chunk-G6LKLN4U.js";import{b as Xt,c as jt}from"./chunk-TDLIXFDT.js";import{b as Ht,c as Kt}from"./chunk-POIQGEZM.js";import{k as Nt,m as Qt,n as Ut,o as Wt}from"./chunk-CQ7SKLMC.js";import{b as ut,c as ht,d as j,e as Vt}from"./chunk-FPXL63KZ.js";import{d as Bt}from"./chunk-ZLWH4RBO.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 ie(i){return i.framing==="no_document"?"sensing":i.framing==="too_far"?"too_far":i.framing==="too_close"?"too_close":i.framing==="edge_clipped"?"edge_clipped":i.framing==="wrong_shape"?"wrong_shape":i.framing==="tilted"?"tilted":i.lighting==="too_dark"?"too_dark":i.lighting==="too_bright"?"too_bright":i.glare==="glare"?"glare":i.blur==="blurry"?"blurry":"hold_still"}var nt=class{constructor(t=2600,e=.35){this.windowMs=t;this.decayPerSecond=e;this.votes=[];this.current=it.sensing;this.currentSinceMs=null}reset(){this.votes=[],this.current=it.sensing,this.currentSinceMs=null}force(t,e){return this.votes=[],this.current=it[t],this.currentSinceMs=e,this.current}tick(t,e){if(this.currentSinceMs===null&&(this.currentSinceMs=e),this.votes.push({key:t,atMs:e}),this.votes=this.votes.filter(r=>e-r.atMs<=this.windowMs),e-this.currentSinceMs<this.current.minDurationMs)return this.current;let n=new Map;for(let r of this.votes){let c=(e-r.atMs)/1e3,a=this.decayPerSecond**c;n.set(r.key,(n.get(r.key)??0)+a)}let o=this.current.key,s=-1;for(let[r,c]of n)c>s&&(s=c,o=r);return o!==this.current.key&&(this.current=it[o],this.currentSinceMs=e),this.current}};var Ke=Object.freeze({MAX_AREA_FRAC:.92,TILT_MAX_SIDE_RATIO:1.3,GLARE_MAX_SPECULAR_FRAC:.025});function oe(i){let{data:t,width:e,height:n}=i,o=e*n;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 Ve(i){let t=(a,l)=>Math.hypot(l.x-a.x,l.y-a.y),e=t(i.topLeft,i.topRight),n=t(i.bottomLeft,i.bottomRight),o=t(i.topLeft,i.bottomLeft),s=t(i.topRight,i.bottomRight),r=Math.max(e,n)/Math.max(1e-6,Math.min(e,n)),c=Math.max(o,s)/Math.max(1e-6,Math.min(o,s));return Math.max(r,c)}function se(i){let t={...$t,...i.thresholds},e=Ke,{quad:n,frameWidth:o,frameHeight:s,measures:r}=i,c=i.format==="ID-3",a="ok";if(n===null)a="no_document";else if(c){let m=dt(n),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":ne(n,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=te(n,o,s),h=dt(n),f=Math.max(h.width,h.height)/Math.max(1e-6,Math.min(h.width,h.height));m<t.MIN_AREA_FRAC?a="too_far":m>e.MAX_AREA_FRAC?a="too_close":ne(n,o,s,t.EDGE_CLIP_MARGIN_PX)?a="edge_clipped":jt(i.format,f)?Ve(n)>e.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>=e.GLARE_MAX_SPECULAR_FRAC?"glare":"ok";return{framing:a,lighting:l,blur:u,glare:d,acceptable:a==="ok"&&l==="ok"&&u==="ok"&&d==="ok"}}function ne(i,t,e,n){return[i.topLeft,i.topRight,i.bottomRight,i.bottomLeft].some(s=>s.x<=n||s.y<=n||s.x>=t-n||s.y>=e-n)}var ae=Object.freeze({width:1920,height:1080}),Xe=Object.freeze({width:3840,height:2160}),re=4096,je=2560,ce=640,ot=.15,Y=Object.freeze({side:.2,above:.9,below:.3});function E(i){let t=[i.topLeft.x,i.topRight.x,i.bottomRight.x,i.bottomLeft.x],e=[i.topLeft.y,i.topRight.y,i.bottomRight.y,i.bottomLeft.y],n=Math.min(...t),o=Math.min(...e);return{x:n,y:o,width:Math.max(...t)-n,height:Math.max(...e)-o}}function le(i,t){let e=Math.max(0,Math.floor(i.x)),n=Math.max(0,Math.floor(i.y)),o=Math.min(t.width,Math.ceil(i.x+i.width)),s=Math.min(t.height,Math.ceil(i.y+i.height));return o-e<16||s-n<16?null:{x:e,y:n,width:o-e,height:s-n}}function Ye(i,t,e){if(i===null||t.width<=0||t.height<=0)return null;let n=E(i);if(n.width<=0||n.height<=0)return null;let o=e==="ID-3"?{x:n.x-n.width*Y.side,y:n.y-n.width*Y.above,width:n.width*(1+2*Y.side),height:n.height+n.width*(Y.above+Y.below)}:{x:n.x-n.width*ot,y:n.y-n.height*ot,width:n.width*(1+2*ot),height:n.height*(1+2*ot)};return le(o,t)}function mt(i,t,e){let n=Math.max(i,t);return n>0?Math.min(1,e/n):1}function ft(i,t,e,n,o=je){let s=t.width>0?e.width/t.width:1,r=t.height>0?e.height/t.height:1,c=i===null?null:{topLeft:{x:i.topLeft.x*s,y:i.topLeft.y*r},topRight:{x:i.topRight.x*s,y:i.topRight.y*r},bottomRight:{x:i.bottomRight.x*s,y:i.bottomRight.y*r},bottomLeft:{x:i.bottomLeft.x*s,y:i.bottomLeft.y*r}},a=Ye(c,e,n)??{x:0,y:0,width:e.width,height:e.height},l=mt(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=E(c);m=le({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 ue(i,t,e,n=Xe){if(e==="LOW")return null;let o=i?.width?.max,s=i?.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(n.width,n.height)),l=Math.min(c,Math.min(n.width,n.height));return a<=Math.max(t.width,t.height)?null:{width:{ideal:a},height:{ideal:l}}}function he(i){let t={},e=i?.imageWidth,n=i?.imageHeight;if(typeof e?.max=="number"&&e.max>0){let o=typeof n?.max=="number"&&n.max>0?e.max/n.max:1.3333333333333333,s=o>=1?re:re*o,r=Math.min(e.max,Math.floor(s)),c=typeof e.step=="number"&&e.step>0?e.step:1,a=typeof e.min=="number"?e.min:0;r=Math.max(a,a+Math.floor((r-a)/c)*c),t.imageWidth=r}return i?.fillLightMode?.includes("off")===!0&&(t.fillLightMode="off"),t}function de(i,t){if(i.width<=0||i.height<=0||t.width<=0||t.height<=0)return!1;let e=i.width>i.height,n=t.width>t.height;return e!==n&&i.width!==i.height&&t.width!==t.height?!1:Math.max(i.width,i.height)>=1.2*Math.max(t.width,t.height)}function me(i,t,e,n){if(e===null)return!1;let o=E(i),s=E(e);if(t.width<=0||n.width<=0)return!1;let r=o.width/t.width,c=s.width/n.width;return c>0&&r>=.6*c&&r<=1.25*c}var fe=3500,Ze=.92;function ge(){let i=globalThis.ImageCapture;return typeof i=="function"?i:null}function Je(i){return/AppleWebKit\//.test(i)&&!/(Chrome|Chromium|Edg|OPR)\//.test(i)}function be(i,t=typeof navigator>"u"?"":navigator.userAgent){return ge()!==null&&!Je(t)&&i!=null&&i.kind==="video"&&i.readyState==="live"}function pe(i,t){return new Promise((e,n)=>{let o=setTimeout(()=>n(new Error("takePhoto timed out")),t);i.then(s=>{clearTimeout(o),e(s)},s=>{clearTimeout(o),n(s)})})}function pt(i,t){let e=document.createElement("canvas");return e.width=i,e.height=t,e}function qe(i,t){return new Promise((e,n)=>{i.toBlob(o=>o?e(o):n(new Error("toBlob failed")),"image/jpeg",t)})}async function ye(i,t,e,n,o){let s=pt(e,n),r=pt(1,1);try{let c=s.getContext("2d");if(c===null)throw new Error("2d context unavailable");c.imageSmoothingQuality="high",c.drawImage(i,t.x,t.y,t.width,t.height,0,0,e,n);let a=await qe(s,Ze),l=o===null?null:Yt({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:e,height:n},{width:e,height:n}),u=Zt(s,l),d=mt(e,n,ce);return r.width=Math.max(1,Math.round(e*d)),r.height=Math.max(1,Math.round(n*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 $e(i,t){let e=Math.min(1,t/i.width),n=pt(Math.max(1,Math.round(i.width*e)),Math.max(1,Math.round(i.height*e)));try{let o=n.getContext("2d",{willReadFrequently:!0});return o===null?null:(o.imageSmoothingQuality="high",o.drawImage(i,0,0,n.width,n.height),o.getImageData(0,0,n.width,n.height))}finally{n.width=0,n.height=0}}async function Me(i,t,e,n){let o={width:Math.max(1,i.videoWidth),height:Math.max(1,i.videoHeight)},s=ft(t,e,o,n);return{...await ye(i,s.crop,s.width,s.height,s.docRegion),docRegion:s.docRegion,source:"video",width:s.width,height:s.height}}async function ke(i,t,e,n,o){let s=ge();if(s===null)return null;let r=null;try{let c=new s(o.track),a=await pe(c.getPhotoCapabilities?.()??Promise.resolve({}),fe).catch(()=>({})),l=await pe(c.takePhoto(he(a)),fe);r=await createImageBitmap(l);let u={width:i.videoWidth,height:i.videoHeight};if(!de(r,u))return null;let d=$e(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&&!me(m,h,t,e)&&(m=null);let f=ft(m,h,r,n);return{...await ye(r,f.crop,f.width,f.height,f.docRegion),docRegion:f.docRegion,source:"photo",width:f.width,height:f.height}}catch{return null}finally{r?.close()}}var st=Object.freeze({width:3840,height:2160,lensSelection:!0,continuousFocus:!0,refocusBeforePhotoMs:350,zoomMax:2,zoomNoFocusInfo:1.5,zoomMinSourcePx:2160,fillDistanceM:Object.freeze({id1:.11,id3:.15}),focusMarginFrac:.2,stillSharpnessMin:.16,stillRefusalsMax:2,focusFarFillFrac:.45,noDocFarHintMs:1500,zoomFallbackMs:8e3}),S=(i,t,e)=>typeof i=="number"&&Number.isFinite(i)&&i>=t&&i<=e?i:void 0;function Ti(i){let t=st,e=i!==null&&typeof i=="object"?i:{},n=e.fillDistanceM!==null&&typeof e.fillDistanceM=="object"?e.fillDistanceM:{},o=(s,r)=>typeof s=="boolean"?s:r;return{width:S(e.width,640,7680)??t.width,height:S(e.height,480,4320)??t.height,lensSelection:o(e.lensSelection,t.lensSelection),continuousFocus:o(e.continuousFocus,t.continuousFocus),refocusBeforePhotoMs:S(e.refocusBeforePhotoMs,0,2e3)??t.refocusBeforePhotoMs,zoomMax:S(e.zoomMax,1,5)??t.zoomMax,zoomNoFocusInfo:S(e.zoomNoFocusInfo,1,5)??t.zoomNoFocusInfo,zoomMinSourcePx:S(e.zoomMinSourcePx,0,8e3)??t.zoomMinSourcePx,fillDistanceM:{id1:S(n.id1,.03,1)??t.fillDistanceM.id1,id3:S(n.id3,.03,1)??t.fillDistanceM.id3},focusMarginFrac:S(e.focusMarginFrac,0,2)??t.focusMarginFrac,stillSharpnessMin:S(e.stillSharpnessMin,0,10)??t.stillSharpnessMin,stillRefusalsMax:S(e.stillRefusalsMax,0,10)??t.stillRefusalsMax,focusFarFillFrac:S(e.focusFarFillFrac,0,1)??t.focusFarFillFrac,noDocFarHintMs:S(e.noDocFarHintMs,0,6e4)??t.noDocFarHintMs,zoomFallbackMs:S(e.zoomFallbackMs,0,12e4)??t.zoomFallbackMs}}function ti(i){let t=i.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 ei(i){let t=/camera2?\s*(\d+)/i.exec(i);return t?Number(t[1]):Number.POSITIVE_INFINITY}function ii(i){let t={main:0,virtual:1,ultra:9,tele:9,depth:9,front:9,unknown:9};return i.filter(e=>(e.kind===void 0||e.kind==="videoinput")&&e.deviceId!=="").map((e,n)=>({id:e.deviceId,kind:ti(e.label),index:ei(e.label),i:n})).filter(e=>t[e.kind]<9).sort((e,n)=>t[e.kind]-t[n.kind]||e.index-n.index||e.i-n.i).map(e=>e.id)}var gt="sekyro.doc.camera";function ni(){try{let i=globalThis.localStorage?.getItem(gt);return typeof i=="string"&&i!==""?i:null}catch{return null}}function xe(i){try{i===null?globalThis.localStorage?.removeItem(gt):globalThis.localStorage?.setItem(gt,i)}catch{}}var rt=(i,t)=>Array.isArray(i?.focusMode)&&i.focusMode.includes(t);function yt(i,t,e){if(!rt(i,"single-shot"))return null;let n=o=>Math.min(1,Math.max(0,Number.isFinite(o)?o:.5));return{focusMode:"single-shot",pointsOfInterest:[{x:n(t),y:n(e)}]}}function _i(i,t,e,n){if(!Number.isFinite(i)||!Number.isFinite(t)||e.width<=0||e.height<=0||n.width<=0||n.height<=0)return null;let o=Math.max(e.width/n.width,e.height/n.height),s=n.width*o,r=n.height*o,c=(i-e.left+(s-e.width)/2)/s,a=(t-e.top+(r-e.height)/2)/r;return{x:Math.min(1,Math.max(0,c)),y:Math.min(1,Math.max(0,a))}}function we(i,t,e,n=st){let o=i?.zoom?.min,s=i?.zoom?.max;if(typeof s!="number"||s<=1)return 1;let r=e==="ID-3"?n.fillDistanceM.id3:n.fillDistanceM.id1,c=i?.focusDistance?.min,a;if(typeof c=="number"&&c>0&&c<1){if(a=c*(1+n.focusMarginFrac)/r,a<=1.05)return 1}else{if(Math.min(t.width,t.height)<n.zoomMinSourcePx)return 1;a=n.zoomNoFocusInfo}let l=Math.min(a,n.zoomMax,s);typeof o=="number"&&(l=Math.max(l,o));let u=i?.zoom?.step;return typeof u=="number"&&u>0&&(l=Math.round(l/u)*u),l>1.01?Number(l.toFixed(2)):1}function bt(i){try{return i.getVideoTracks?.()[0]}catch{return}}function De(i){if(i!==null)for(let t of i.getTracks())t.stop()}function oi(i){try{let t=bt(i)?.getCapabilities?.();return!Array.isArray(t?.focusMode)||t.focusMode.includes("continuous")}catch{return!0}}var si=3;async function ve(i){let t=s=>({audio:!1,video:{...s,width:{ideal:i.base.width},height:{ideal:i.base.height}}}),e=s=>i.getUserMedia(t({deviceId:{exact:s}})),n=()=>i.getUserMedia(t({facingMode:{ideal:"environment"}}));if(i.lensSelection){let s=ni();if(s!==null)try{return{stream:await e(s),lens:"stored"}}catch{xe(null)}}let o=await n();if(!i.lensSelection||i.enumerateDevices===void 0)return{stream:o,lens:"default"};try{let s=ii(await i.enumerateDevices()).slice(0,si);if(s.length===0)return{stream:o,lens:"default"};let r=null;for(let c of s){let a=o!==null?bt(o)?.getSettings?.().deviceId:void 0;if(o===null||a!==c){De(o),o=null;try{o=await e(c)}catch{continue}}if(r??(r=c),oi(o))return xe(c),{stream:o,lens:"selected"}}if(o!==null&&r!==null&&bt(o)?.getSettings?.().deviceId===r)return{stream:o,lens:"selected"};if(De(o),o=null,r!==null)try{return{stream:await e(r),lens:"selected"}}catch{}return{stream:await n(),lens:"default"}}catch{return{stream:o??await n(),lens:"default"}}}var Z=Object.freeze({brightness:0,glare:0,cardGlare:0,sharpness:0,fill:0,shape:0,content:0,offsetX:0,offsetY:0,edgeConfidence:0,box:null}),L=i=>Math.min(1,Math.max(0,i));function Te(i,t,e,n=.06){let o=Math.max(i.width/e,i.height),s=o*e,r=(i.width-s)/2,c=(i.height-o)/2,a=L((t.x-t.width*n-r)/s),l=L((t.y-t.height*n-c)/o),u=L((t.x+t.width*(1+n)-r)/s),d=L((t.y+t.height*(1+n)-c)/o);return{x:a,y:l,width:u-a,height:d-l}}function _e(i,t,e={}){let n=e.edgePeakFrac??0,{width:o,height:s,data:r}=i;if(o<=0||s<=0)return Z;let c=L(t.x),a=L(t.y),l={x:c,y:a,width:Math.max(0,L(t.x+t.width)-c),height:Math.max(0,L(t.y+t.height)-a)};if(l.width<=0||l.height<=0)return Z;let u=l.x*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,R)=>Math.min(R,Math.max(b,p)),x=y(Math.floor(u-f),0,o-1),w=y(Math.floor(d-g),0,s-1),I=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(I-x,v-w)/320)),M=Math.floor((I-x+D-1)/D),T=Math.floor((v-w+D-1)/D);if(M<3||T<3)return Z;let k=new Int32Array(M*T);for(let p=0;p<T;p++){let b=w+p*D;for(let R=0;R<M;R++){let F=(b*o+x+R*D)*4;k[p*M+R]=(r[F]??0)*77+(r[F+1]??0)*150+(r[F+2]??0)*29>>8}}let C=(p,b)=>(p-b-.5)/D,_=C(u,x),A=C(m,x),B=C(d,w),U=C(h,w),kt=(m-u)/D,xt=(h-d)/D,Dt=y(Math.ceil(_),0,M-1),Ie=y(Math.floor(A),Dt,M-1),wt=y(Math.ceil(B),0,T-1),Oe=y(Math.floor(U),wt,T-1),vt=0,St=0,W=0,Tt=0,_t=0,H=0;for(let p=wt;p<=Oe;p++)for(let b=Dt;b<=Ie;b++){let R=k[p*M+b];if(vt+=R,R>=248&&St++,W++,b>=1&&b<M-1&&p>=1&&p<T-1){let F=k[p*M+b-1]+k[p*M+b+1]+k[(p-1)*M+b]+k[(p+1)*M+b]-4*R;Tt+=F,_t+=F*F,H++}}let Pe=W>0?vt/W:0,Rt=W>0?St/W:0,Ft=H>0?Tt/H:0,Ge=H>0?Math.max(0,_t/H-Ft*Ft):0,K=new Float64Array(M),V=new Float64Array(T);for(let p=0;p<T;p++)for(let b=1;b<M-1;b++)K[b]=K[b]+Math.abs(k[p*M+b+1]-k[p*M+b-1]);for(let p=1;p<T-1;p++)for(let b=0;b<M;b++)V[p]=V[p]+Math.abs(k[(p+1)*M+b]-k[(p-1)*M+b]);let O=at(K,!0,_,n),P=at(K,!1,A,n),G=at(V,!0,B,n),z=at(V,!1,U,n),Ct=(P.position-O.position)/kt,At=(z.position-G.position)/xt,ze=At>0?Ct/At:0,Ne=((O.position+P.position)/2-(_+A)/2)/kt,Qe=((G.position+z.position)/2-(B+U)/2)/xt,Et=Se(K),Lt=Se(V),Be=Et<=0||Lt<=0?0:Math.min(Math.min(O.value,P.value)/Et,Math.min(G.value,z.value)/Lt),$=(p,b)=>b+(p+.5)*D,It=Rt,Ot=0;{let p=(P.position-O.position)*.06,b=(z.position-G.position)*.06,R=y(Math.ceil(O.position+p),0,M-1),F=y(Math.floor(P.position-p),0,M-1),Ue=y(Math.ceil(G.position+b),0,T-1),Pt=y(Math.floor(z.position-b),0,T-1),Gt=0,tt=0,zt=0;for(let N=Ue;N<=Pt;N++)for(let Q=R;Q<=F;Q++){tt++;let X=k[N*M+Q];X>=248&&Gt++;let We=Q+2<=F?k[N*M+Q+2]:X,He=N+2<=Pt?k[(N+2)*M+Q]:X;(Math.abs(We-X)>=24||Math.abs(He-X)>=24)&&zt++}tt>=16&&(It=Gt/tt,Ot=zt/tt)}return{brightness:Pe,glare:Rt,cardGlare:It,sharpness:Ge,fill:Ct,shape:ze,content:Ot,offsetX:Ne,offsetY:Qe,edgeConfidence:Be,box:{left:$(O.position,x),right:$(P.position,x),top:$(G.position,w),bottom:$(z.position,w)}}}function at(i,t,e,n){let o=i.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++)i[h]>i[a]&&(a=h);if(n>0&&n<1){let h=i[a]*n,f=a,g=Math.abs(a-e);for(let y=r;y<=c;y++){let x=i[y];if(x<h||x<(i[y-1]??0)||x<(i[y+1]??0))continue;let w=Math.abs(y-e);w<g&&(f=y,g=w)}a=f}let l=a>0?i[a-1]:0,u=i[a],d=a<o-1?i[a+1]:0,m=l+u+d;return{position:m>0?a+(d-l)/m:a,value:u}}function Se(i){if(i.length<3)return 0;let t=0;for(let e=1;e<i.length-1;e++)t+=i[e];return t/(i.length-2)}function Re(i){let t=i.box;return t===null||t.right-t.left<4||t.bottom-t.top<4?null:{topLeft:{x:t.left,y:t.top},topRight:{x:t.right,y:t.top},bottomRight:{x:t.right,y:t.bottom},bottomLeft:{x:t.left,y:t.bottom}}}var J=Object.freeze({fillMin:.82,fillMax:1.06,offsetMax:.06,glareMax:.025,sharpnessMin:180,edgeConfidenceMin:1.6,darkBrightness:70,lockMs:450,steadyMs:900,steadyFillMin:.45,steadyFillMax:1.3,steadyFillDelta:.06,steadyOffsetDelta:.04,steadyRefMs:100,edgePeakFrac:.4,shapeTolerance:.2,contentMin:.1});function Fi(i){let t=i!==null&&typeof i=="object"?i:{},e={...J};for(let n of Object.keys(J)){let o=t[n];typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=1e6&&(e[n]=o)}return e}var ct=class{constructor(t=J){this.t=t;this.goodSince=null;this.steadySince=null;this.last=null}reset(){this.goodSince=null,this.steadySince=null,this.last=null}tick(t,e){let n=this.t,o=n.shapeTolerance<=0||Math.abs(t.shape-1)<=n.shapeTolerance,s=t.edgeConfidence>=n.edgeConfidenceMin&&o&&t.content>=n.contentMin,r=t.fill>=n.fillMin&&t.fill<=n.fillMax,c=Math.abs(t.offsetX)<=n.offsetMax&&Math.abs(t.offsetY)<=n.offsetMax,a=t.cardGlare<=n.glareMax,l=t.sharpness>=n.sharpnessMin,u=this.last;this.last={fill:t.fill,offsetX:t.offsetX,offsetY:t.offsetY,at:e};let d=u!==null&&n.steadyRefMs>0?Math.min(3,Math.max(1,(e-u.at)/n.steadyRefMs)):1,m=s&&a&&l&&t.fill>=n.steadyFillMin&&t.fill<=n.steadyFillMax&&u!==null&&Math.abs(t.fill-u.fill)<=n.steadyFillDelta*d&&Math.abs(t.offsetX-u.offsetX)<=n.steadyOffsetDelta*d&&Math.abs(t.offsetY-u.offsetY)<=n.steadyOffsetDelta*d,h=s&&r&&c&&a&&l,f;if(s?a?t.fill<n.fillMin?f="too_small":t.fill>n.fillMax?f="too_big":l?c?f="locking":f="off_center":f="blurry":f="glare":f="no_card",h){if(m&&(this.steadySince??(this.steadySince=e)),this.goodSince??(this.goodSince=e),e-this.goodSince>=n.lockMs)return{detected:s,ready:!0,via:"good",blocker:"locking"};let g=this.steadySince!==null&&e-this.steadySince>=n.steadyMs;return{detected:s,ready:g,via:g?"steady":null,blocker:"locking"}}if(this.goodSince=null,m){this.steadySince??(this.steadySince=e);let g=e-this.steadySince>=n.steadyMs;return{detected:s,ready:g,via:g?"steady":null,blocker:g?"locking":"steadying"}}return this.steadySince=null,{detected:s,ready:!1,via:null,blocker:f}}};var q=null;async function ri(i){return q===null&&(q=(await import("./detector-scanic-YCDNLCGV.js")).detectQuad),q(i)}async function ai(i){let t=Jt(i);return t===null?null:{topLeft:{x:t.x,y:t.y},topRight:{x:t.x+t.width,y:t.y},bottomRight:{x:t.x+t.width,y:t.y+t.height},bottomLeft:{x:t.x,y:t.y+t.height}}}function Vi(){q===null&&import("./detector-scanic-YCDNLCGV.js").then(i=>{q=i.detectQuad}).catch(()=>{})}var Fe=4e3,ci=2,Ce=3,li=Object.freeze({LOW:3,MID:5,HIGH:6}),Mt=Object.freeze({manualShutterMs:6e3,detectedNoLockMs:1950});function Xi(i){let t=i!==null&&typeof i=="object"?i:{},e=(n,o,s)=>typeof n=="number"&&Number.isFinite(n)&&n>=o&&n<=s?n:void 0;return{manualShutterMs:e(t.manualShutterMs,1e3,6e4)??Mt.manualShutterMs,detectedNoLockMs:e(t.steadyMs,300,3e4)!==void 0?t.steadyMs+(e(t.lockMs,0,1e4)??450):Mt.detectedNoLockMs}}var Ae=class i{constructor(t){this.torchOn=!1;this.stillRefusals=0;this.zoom=1;this.positioningSince=null;this.detectedSince=null;this.lastSeenAt=null;this.lastGuideQuad=null;this.lastOcrReady=null;this.shutterOffered=!1;this.stats=i.freshStats();this.handlers=new Map;this.stream=null;this.timer=null;this.state="idle";this.lastGuidance=null;this.attempt=0;this.capturing=!1;this.feedback=new nt;this.lastFeedbackKey=null;this.lastQuad=null;this.lastDetect=null;this.frameWatch=null;this.reopened=!1;this.lit=!1;this.blackTicks=0;this.offEnded=null;this.opts=t,this.gate=new ee(t.format??"ID-1",t.thresholds);let e=t.deviceClass??Kt(Ht());this.deviceClass=e,this.camera=t.camera??st,this.shutterTuning=t.shutter??Mt,this.guideTuning=t.guideLock??J,this.guideLock=new ct(this.guideTuning),this.cadenceMs=1e3/li[e]}on(t,e){let n=this.handlers.get(t);return n||(n=new Set,this.handlers.set(t,n)),n.add(e),()=>n?.delete(e)}emit(t,e){for(let n of[...this.handlers.get(t)??[]])n(e)}async start(){let t=this.state==="error"?this.resumePlayback():null,e=++this.attempt;if(this.clearFrameWatch(),this.gate.reset(),this.resetSide(),this.feedback.reset(),this.lastFeedbackKey=null,this.lastGuidance=null,this.capturing=!1,this.lit=!1,this.blackTicks=0,t!==null&&await t&&e===this.attempt){this.setState("positioning"),this.scheduleTick(e),this.watchFrames(e);return}if(e===this.attempt){this.releaseStream(),Wt(),this.setState("preflight");try{let n=this.opts.getUserMedia??(r=>navigator.mediaDevices.getUserMedia(r));this.setState("acquiring");let o=this.opts.enumerateDevices??(this.opts.getUserMedia===void 0&&typeof navigator<"u"&&navigator.mediaDevices?.enumerateDevices?()=>navigator.mediaDevices.enumerateDevices():void 0),s=await ve({getUserMedia:n,...o!==void 0?{enumerateDevices:o}:{},lensSelection:this.camera.lensSelection,base:ae});if(e!==this.attempt){for(let r of s.stream.getTracks())r.stop();return}if(this.stream=s.stream,Bt(this.stream),Ut(this.stream),this.watchEnded(e),this.opts.upgradeResolution!==!1&&await this.upgradeResolution(),e!==this.attempt||(await this.applyFocusAndZoom(),e!==this.attempt)||(this.opts.video.srcObject=this.stream,await this.opts.video.play().catch(()=>{}),e!==this.attempt))return;this.setState("positioning"),this.scheduleTick(e),this.watchFrames(e)}catch(n){if(e!==this.attempt)return;let o=Qt(n),s=Nt(n);this.setState("error"),this.emit("error",{kind:o,retryable:!0,detail:s===void 0?{phase:"acquiring"}:{phase:"acquiring",name:s}})}}}resumePlayback(){let t=this.opts.video,e=this.videoTrack();if(this.stream===null||e===null||e.readyState!=="live"||t.srcObject!==this.stream)return null;try{return Promise.resolve(t.play()).then(()=>this.framesNow(),()=>!1)}catch{return null}}framesNow(){let t=this.opts.video;return this.opts.hasFrames!==void 0?this.opts.hasFrames(t):!t.paused&&t.readyState>=2&&t.videoWidth>0}watchFrames(t){let e=this.opts.firstFrameMs??Fe;e<=0||(this.clearFrameWatch(),this.frameWatch=setTimeout(()=>{if(this.frameWatch=null,!(t!==this.attempt||this.state!=="positioning")){if(this.framesNow()&&this.blackTicks<Ce){this.reopened=!1;return}this.cameraDead(t)}},e))}clearFrameWatch(){this.frameWatch!==null&&clearTimeout(this.frameWatch),this.frameWatch=null}watchEnded(t){this.offEnded?.(),this.offEnded=null;let e=this.videoTrack();if(e===null||typeof e.addEventListener!="function")return;let n=()=>{t===this.attempt&&(this.state==="positioning"||this.state==="acquiring")&&this.cameraDead(t)};e.addEventListener("ended",n),this.offEnded=()=>e.removeEventListener?.("ended",n)}cameraDead(t){if(t!==this.attempt)return;let e=this.videoTrack(),n=e!==null&&e.readyState==="live"&&!e.muted&&this.opts.video.paused&&!this.framesNow();if(!n&&!this.reopened){this.reopened=!0,this.start();return}this.attempt+=1,this.timer!==null&&(this.opts.clearTimer??clearTimeout)(this.timer),this.timer=null,this.clearFrameWatch(),n||this.releaseStream(),this.reopened=!1,this.setState("error"),this.emit("error",{kind:"generic",retryable:!0,detail:{phase:"acquiring"}})}releaseStream(){if(this.offEnded?.(),this.offEnded=null,this.stream)for(let t of this.stream.getTracks())t.stop();this.stream=null,this.opts.video.srcObject!==null&&this.opts.video.srcObject!==void 0&&(this.opts.video.srcObject=null)}rearm(t){t!==void 0&&(this.opts.side=t),this.gate.reset(),this.resetSide(),this.feedback.reset(),this.lastFeedbackKey=null,this.lastGuidance=null,this.capturing=!1,this.stillRefusals=0,this.state==="captured"&&(this.setState("positioning"),this.scheduleTick(this.attempt))}async captureNow(){if(this.state!=="positioning"||this.capturing)return;let t=this.opts.video,e=this.lastDetect?.width??Math.max(1,t.videoWidth),n=this.lastDetect?.height??Math.max(1,t.videoHeight),o=this.lastQuad??this.lastGuideQuad??{topLeft:{x:0,y:0},topRight:{x:e,y:0},bottomRight:{x:e,y:n},bottomLeft:{x:0,y:n}},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:e,height:n,tickSharpness:this.lastDetect?.tickSharpness??0},this.lastOcrReady?.via??"manual")}captureReport(){let t=this.stats;return{...this.opts.side!==void 0?{side:this.opts.side}:{},format:this.opts.format??"ID-1",deviceClass:this.deviceClass,video:{width:this.opts.video.videoWidth||0,height:this.opts.video.videoHeight||0},zoom:this.zoom,...t.zoomFallbackAtMs!==void 0?{zoomFallbackAtMs:t.zoomFallbackAtMs}:{},...t.msToCapture!==void 0?{msToCapture:t.msToCapture}:{},...t.via!==void 0?{via:t.via}:{},...t.shutterAtMs!==void 0?{shutterAtMs:t.shutterAtMs}:{},...t.shutterReason!==void 0?{shutterReason:t.shutterReason}:{},ticks:t.ticks,quadFraming:{...t.quadFraming},qualityBlockers:{...t.qualityBlockers},guideBlockers:{...t.guideBlockers},stillRefusals:t.stillRefusals,...this.ocrReport()}}ocrReport(){let t=this.opts.ocr;if(t===void 0)return{};let e=(this.opts.format??"ID-1")==="ID-3"||this.opts.side==="single"?"single":this.opts.side==="verso"?"verso":"recto",n=t.report(e,this.stats.via,(this.opts.now??(()=>performance.now()))());return n===null?{}:{ocr:n}}static freshStats(){return{ticks:0,quadFraming:{},qualityBlockers:{},guideBlockers:{},stillRefusals:0}}setGuide(t){t===void 0?delete this.opts.guide:this.opts.guide=t,this.guideLock.reset()}guideRegion(t){let e=t.width/Math.max(1,t.height),n=this.opts.guide;if(n!==void 0&&n.viewAspect>0){let c={width:n.viewAspect,height:1},a={x:n.rect.x*n.viewAspect,y:n.rect.y,width:n.rect.width*n.viewAspect,height:n.rect.height};return Te(c,a,e,0)}let o=Xt(this.opts.format??"ID-1").center,s=.86,r=s*e/o;return r>.84&&(r=.84,s=r*o/e),{x:(1-s)/2,y:(1-r)/2,width:s,height:r}}resetSide(){this.positioningSince=null,this.detectedSince=null,this.lastSeenAt=null,this.guideLock.reset(),this.lastGuideQuad=null,this.lastOcrReady=null,this.opts.ocr?.reset(),this.stats=i.freshStats(),this.shutterOffered&&(this.shutterOffered=!1,this.emit("shutter",{available:!1}))}withdrawShutter(){this.shutterOffered&&(this.shutterOffered=!1,this.emit("shutter",{available:!1}))}zoomFallback(t){let e=this.videoTrack();if(e===null||this.zoom<=1)return;let n=this.focusCaps(),o=typeof n?.zoom?.min=="number"?Math.max(n.zoom.min,1):1;this.zoom=o,this.stats.zoomFallbackAtMs=Math.round(t-(this.positioningSince??t)),this.guideLock.reset(),this.gate.reset(),e.applyConstraints({advanced:[{zoom:o}]}).catch(()=>{})}offerShutter(t,e){this.shutterOffered||(this.shutterOffered=!0,this.stats.shutterAtMs=Math.round(e-(this.positioningSince??e)),this.stats.shutterReason=t,this.emit("shutter",{available:!0,reason:t}))}torchAvailable(){try{return this.stream?.getVideoTracks?.()[0]?.getCapabilities?.()?.torch===!0}catch{return!1}}async setTorch(t){this.torchOn=t;try{await this.stream?.getVideoTracks?.()[0]?.applyConstraints({advanced:[{torch:t}]})}catch{}}destroy(){if(this.attempt+=1,this.timer!==null&&(this.opts.clearTimer??clearTimeout)(this.timer),this.timer=null,this.clearFrameWatch(),this.offEnded?.(),this.offEnded=null,this.stream)for(let t of this.stream.getTracks())t.stop();this.stream=null,this.opts.video.srcObject=null}async upgradeResolution(){try{let t=this.stream?.getVideoTracks?.()[0];if(t===void 0)return;let e=t.getSettings?.()??{},n=ue(t.getCapabilities?.(),{width:e.width??0,height:e.height??0},this.deviceClass,{width:this.camera.width,height:this.camera.height});n!==null&&await t.applyConstraints(n)}catch{}}focusCaps(){try{return this.videoTrack()?.getCapabilities?.()??null}catch{return null}}async applyFocusAndZoom(){let t=this.videoTrack();if(t===null)return;let e=this.focusCaps();this.camera.continuousFocus&&rt(e,"continuous")&&await t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{});let n={width:0,height:0};try{let s=t.getSettings?.()??{};n={width:s.width??0,height:s.height??0}}catch{}let o=we(e,n,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,e){let n=this.videoTrack(),o=yt(this.focusCaps(),t,e);if(!(n===null||o===null))try{await n.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,e){let n=this.camera.refocusBeforePhotoMs,o=this.videoTrack();if(n<=0||o===null||e.width<=0||e.height<=0)return;let s=E(t),r=yt(this.focusCaps(),(s.x+s.width/2)/e.width,(s.y+s.height/2)/e.height);if(r!==null)try{await o.applyConstraints({advanced:[r]});let c=this.opts.setTimer??setTimeout;await new Promise(a=>{c(()=>a(),n)})}catch{}}videoTrack(){try{return this.stream?.getVideoTracks?.()[0]??null}catch{return null}}async takeStill(t,e,n){if(this.opts.captureStill!==void 0)return this.opts.captureStill(this.opts.video,t,e);let o=this.opts.format??"ID-1",s=this.videoTrack();if(n&&this.opts.photoCapture!==!1&&this.deviceClass!=="LOW"&&!this.torchOn&&s!==null&&be(s)){await this.refocusOn(t,e);let r=await ke(this.opts.video,t,e,o,{track:s,detect:this.detector(),detectWidth:et});if(this.restoreContinuous(),r!==null)return r}return Me(this.opts.video,t,e,o)}detector(){return this.opts.detect??((this.opts.format??"ID-1")==="ID-3"?ai:ri)}setState(t){this.state=t,this.emit("statechange",{state:t})}scheduleTick(t){let e=this.opts.setTimer??setTimeout;this.timer=e(()=>{this.tick(t)},this.cadenceMs)}async tick(t){if(t!==this.attempt||this.state!=="positioning"||this.capturing)return;let e=this.opts.now??(()=>performance.now()),n=this.opts.grabDetectFrame??Le,o=this.detector(),s=n(this.opts.video,et);if(s===null){this.scheduleTick(t);return}if(!this.lit){if(ht(s)>ci)this.lit=!0,this.blackTicks=0;else if(++this.blackTicks>=Ce&&this.frameWatch===null&&(this.opts.firstFrameMs??Fe)>0){this.cameraDead(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=e(),l={sharpness:j(c),exposure:Vt(c),meanLuma:ht(c),specularFraction:oe(c)},u=se({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"?_e(s,this.guideRegion(s),{edgePeakFrac:this.guideTuning.edgePeakFrac}):Z,f=this.guideLock.tick(h,a);this.lastGuideQuad=f.detected?Re(h):null;let g=this.capturing?null:this.ocrTick(s,r,h,f.detected,u,a);this.positioningSince??(this.positioningSince=a);let y=this.stats;if(y.ticks+=1,y.quadFraming[u.framing]=(y.quadFraming[u.framing]??0)+1,u.framing==="ok"&&!d.ready){let _=u.lighting!=="ok"?u.lighting:u.glare!=="ok"?"glare":u.blur!=="ok"?"blurry":"steadying";y.qualityBlockers[_]=(y.qualityBlockers[_]??0)+1}y.guideBlockers[f.blocker]=(y.guideBlockers[f.blocker]??0)+1,r!==null||f.detected?(this.detectedSince??(this.detectedSince=a),this.lastSeenAt=a):this.detectedSince=null,this.lastSeenAt!==null&&a-this.lastSeenAt<=gi?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 I=a-(this.lastSeenAt??this.positioningSince);this.zoom>1&&this.camera.zoomFallbackMs>0&&I>=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=ie(u);u.framing!=="ok"&&f.detected&&(v=pi(f.blocker,h.brightness<this.guideTuning.darkBrightness)),v==="blurry"&&r!==null&&hi(r,s,this.opts.format??"ID-1")>=this.camera.focusFarFillFrac&&(v="focus_far"),v==="sensing"&&this.zoom>1&&this.camera.noDocFarHintMs>0&&I>=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,T=M&&d.ready&&r!==null,k=M&&f.ready&&this.lastGuideQuad!==null,C=this.lastOcrReady;if(C!==null&&this.opts.autoCapture!==!1){let _=this.feedback.force("processing",a);this.lastFeedbackKey=_.key,this.emit("feedback",_);let A=j(lt(s,C.quad));await this.fire(t,C.quad,{width:s.width,height:s.height,tickSharpness:A},C.via);return}if((T||k)&&this.opts.autoCapture!==!1){let _=this.feedback.force("processing",a);this.lastFeedbackKey=_.key,this.emit("feedback",_);let A=k?this.lastGuideQuad:r,B=k?f.via==="steady"?"guide_steady":"guide_good":"quad",U=k?j(lt(s,A)):l.sharpness;await this.fire(t,A,{width:s.width,height:s.height,tickSharpness:U},B);return}this.scheduleTick(t)}async fire(t,e,n,o){this.capturing=!0;let s=this.opts.grabDetectFrame??Le,r=this.opts.setTimer??setTimeout,c={width:n.width,height:n.height};try{let a={still:await this.takeStill(e,c,!0),sharpness:n.tickSharpness};if(t!==this.attempt)return;let l=a.still.source==="photo"?0:di;for(let m=0;m<l;m++){if(await new Promise(g=>{r(()=>g(),mi)}),t!==this.attempt)return;let h=s(this.opts.video,et);if(h===null)continue;let f=j(lt(h,e));if(f>a.sharpness*fi){let g=await this.takeStill(e,c,!1);if(t!==this.attempt)return;a={still:g,sharpness:f}}}if(t!==this.attempt)return;let u=a.still.sharpness;if(this.opts.autoCapture!==!1&&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,e,n,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&&e!==null?x=ui(E(e),g,y,l,u):x=qt(f,c.bandTop,u);let w=m?s.glare==="ok":n.cardGlare<=this.guideTuning.glareMax,I=m?s.blur==="ok":n.sharpness>=this.guideTuning.sharpnessMin,v=c.tick({atMs:r,video:a,mrzFace:m||this.opts.side==="verso"||this.opts.side==="single",present:m||e!==null||o,card:f,band:x,portrait:u>l,glareOk:w,sharpOk:I});if(v.ready&&v.via!==void 0){let D=m?e??Ee(h,t):this.lastGuideQuad??Ee(h,t);this.lastOcrReady={quad:D,via:v.via}}else this.lastOcrReady=null;return v}};function ui(i,t,e,n,o){let s=Math.min(n,i.width*1.06*t),r=Math.min(o,Math.max(i.height*1.6*e,s/5)),c=(i.y+i.height/2)*e,a=Math.max(0,Math.min(n-s,(i.x-i.width*.03)*t)),l=Math.max(0,Math.min(o-r,c-r/2));return{x:a,y:l,w:s,h:r}}function Ee(i,t){let e=i.x*t.width,n=i.y*t.height,o=(i.x+i.width)*t.width,s=(i.y+i.height)*t.height;return{topLeft:{x:e,y:n},topRight:{x:o,y:n},bottomRight:{x:o,y:s},bottomLeft:{x:e,y:s}}}function hi(i,t,e){let n=E(i);return t.width<=0||t.height<=0?0:e==="ID-3"?n.width/t.width:n.width*n.height/(t.width*t.height)}var di=2,mi=260,fi=1.08;function Le(i,t){let e=i.videoWidth,n=i.videoHeight;if(e===0||n===0)return null;let o=Math.min(1,t/e),s=Math.round(e*o),r=Math.round(n*o),c=document.createElement("canvas");c.width=s,c.height=r;let a=c.getContext("2d",{willReadFrequently:!0});return a===null?null:(e/Math.max(1,s)>4&&(a.imageSmoothingQuality="high"),a.drawImage(i,0,0,s,r),a.getImageData(0,0,s,r))}function lt(i,t){let e=[t.topLeft.x,t.topRight.x,t.bottomRight.x,t.bottomLeft.x],n=[t.topLeft.y,t.topRight.y,t.bottomRight.y,t.bottomLeft.y],o=Math.max(0,Math.floor(Math.min(...e))),s=Math.max(0,Math.floor(Math.min(...n))),r=Math.min(i.width,Math.ceil(Math.max(...e))),c=Math.min(i.height,Math.ceil(Math.max(...n))),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)*i.width+o)*4;u.set(i.data.subarray(m,m+a*4),d*a*4)}return{data:u,width:a,height:l,colorSpace:i.colorSpace}}function pi(i,t){return i==="glare"?"glare":i==="too_small"?"too_far":i==="too_big"?"too_close":t?"too_dark":i==="blurry"?"blurry":i==="off_center"?"edge_clipped":i==="no_card"?"sensing":"hold_still"}var gi=1200;export{it as a,ie as b,nt as c,Ke as d,oe as e,Ve as f,se as g,st as h,Ti as i,ti as j,ii as k,gt as l,ni as m,xe as n,rt as o,yt as p,_i as q,we as r,oi as s,si as t,ve as u,Z as v,Te as w,_e as x,Re as y,J as z,Fi as A,ct as B,Vi as C,Fe as D,ci as E,Ce as F,li as G,Mt as H,Xi as I,Ae as J,ui as K,di as L,mi as M};
@@ -1 +1 @@
1
- import{a as Z,d as j,e as J}from"./chunk-GT2ZLGF7.js";import{w as Q}from"./chunk-ZPXL26BF.js";import{c as q}from"./chunk-FUHDOEBP.js";import{f as G,l as N}from"./chunk-CQ7SKLMC.js";import{a as $,f as v}from"./chunk-OKWG3PVH.js";var se=12e4,X=13e4,oe=3e3,ie=1200,P=Symbol.for("@sekyro/web.preload.v1");function p(){let e=globalThis;return e[P]??(e[P]=new Map),e[P]}function g(e){let t=(e??$).replace(/\/+$/,"");return t===""?"/":t}function Y(e){let t=p(),r=t.get(e);return r===void 0&&(r={status:"idle",promise:null,scheduled:null,detectorPromise:null,detector:null,listeners:new Set},t.set(e,r)),r}function A(e,t){if(e.status!==t){e.status=t;for(let r of[...e.listeners])r(t)}}var T=e=>v({preferred:["blaze"],v3AssetBaseUrl:e,blazeInitTimeoutMs:se}),x=T;function Se(e){x=e??T}function Ce(){for(let e of p().values())e.detector?.destroy();p().clear(),x=T}function ae(){return typeof window<"u"&&typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"}function ce(){return navigator.connection?.saveData===!0}function de(e){let t=window;if(typeof t.requestIdleCallback=="function"){let s=t.requestIdleCallback(e,{timeout:oe});return()=>t.cancelIdleCallback?.(s)}let r=setTimeout(e,ie);return()=>clearTimeout(r)}function ue(e,t){let r,s=new Promise(o=>{r=o}),u=!1,f=()=>{},d={promise:s,settle:o=>{u||(u=!0,f(),e.scheduled===d&&(e.scheduled=null),r(o))}};return e.scheduled=d,f=de(()=>{u||d.settle(I(e,t))}),s}function I(e,t){if((e.status==="loading"||e.status==="ready")&&e.promise!==null)return e.promise;A(e,"loading");let r=new Promise(o=>o(x(t)));e.detectorPromise=r;let s,u=new Promise((o,h)=>{s=setTimeout(()=>{r.then(S=>S.destroy(),()=>{}),h(new Error(`detector preload exceeded ${X} ms`))},X)}),d=Promise.race([r,u]).then(o=>e.detectorPromise!==r?(o.destroy(),e.status):(e.detector=o,A(e,"ready"),"ready"),o=>(e.detectorPromise===r&&(e.detectorPromise=null,e.detector=null,A(e,"failed"),console.warn("[@sekyro/web] face-detector preload failed:",o)),e.status)).finally(()=>clearTimeout(s));return e.promise=d,e.scheduled?.settle(d),d}function Le(e={}){if(!ae())return Promise.resolve("idle");let t=g(e.assetBaseUrl),r=Y(t);return e.respectSaveData===!0&&ce()?Promise.resolve(r.status):(r.status==="loading"||r.status==="ready")&&r.promise!==null?r.promise:e.idle===!0?r.scheduled?.promise??ue(r,t):I(r,t)}function Ee(e){return p().get(g(e))?.status??"idle"}function ye(e,t){let r=Y(g(t));return r.listeners.add(e),()=>{r.listeners.delete(e)}}function be(e){let t=p().get(g(e));t!==void 0&&(t.scheduled?.settle("idle"),t.detector?.destroy(),t.detector=null,t.detectorPromise=null,t.promise=null,A(t,"idle"))}function le(e){return{get tier(){return e.tier},get fallbackReason(){return e.fallbackReason},detect:(...t)=>e.detect(...t),destroy:()=>{}}}function ee(e){let t=g(e),r=p().get(t);if(!(r===void 0||r.detector===null&&r.detectorPromise===null&&r.scheduled===null))return async()=>{r.scheduled!==null&&I(r,t);let s=r.promise;for(;r.detector===null&&s!==null&&(await s,r.promise!==s);)s=r.promise;return r.detector!==null?le(r.detector):v({v3AssetBaseUrl:t})}}function fe(e){switch(e){case"fcv3.no_face":case"fcv3.center_face":case"fcv3.straighten":return"center";case"fcv3.come_closer":return"closer";case"fcv3.move_back":return"farther";case"fcv3.more_light":case"fcv3.too_bright":return"light";case"fcv3.hold_still":case"fcv3.steady_camera":return"still";case"fcv3.hold_upright":return"upright";default:return null}}function pe(e){switch(e){case"preflight":case"acquiring":return"starting";case"positioning":return"gating";default:return e}}function te(e){switch(e){case"permission":case"notfound":case"inuse":case"insecure":case"unsupported":return e;default:{let t=e;return"generic"}}}function me(e,t,r){if(r===void 0)return{kind:te(e),retryable:t};let s=N(r.name);return{kind:te(e),retryable:t,detail:{...s!==void 0?{name:s}:{},phase:r.phase,engineKind:e}}}function ve(e,t={},r,s=()=>"self",u=()=>{}){let f=t.now??(()=>performance.now()),d=t.canChooseFacing??j,o="user",h=!1,S=n=>(n==="environment"&&!h&&(h=!0,console.warn('[@sekyro/web] facing "environment" ignored: this capture is a self capture (the person films themselves), which uses the front camera only. The back camera is for assisted capture, set in the flow.')),"user"),D=!1,m=s(),c=Z(),H=!G(),U=t.engineOptions,re=U?.createDetector===void 0&&U?.createWorker===void 0?{createDetector:()=>{let n=ee(e.assetBaseUrl);return n!==void 0?n():v({v3AssetBaseUrl:e.assetBaseUrl})}}:{},B={video:e.video,mode:H?"photo":"clip",rankKeyframes:r,facingMode:void 0,v3AssetBaseUrl:e.assetBaseUrl,screenRamp:()=>m==="self"&&c.count("ramp")>0?u():void 0,...t.engineOptions??{},...re},i=t.createEngine?.(B)??new Q(B),C="idle",L=null,E=0,k=!1,M="full",y=null,b=null,_=0,F=0,K=()=>{e.video.videoWidth>0&&e.video.videoHeight>0&&(_=e.video.videoWidth,F=e.video.videoHeight)},V=J({enabled:e.keepScreenAwake!==!1}),z=n=>{C=n,V.setActive(n==="starting"||n==="gating"||n==="recording"),c.emit("state",n)},O=()=>c.emit("gate",{progress:E,hint:L,faceDetected:k}),W=()=>{let n=i.animations??"full";n!==M&&(M=n,c.emit("profile",{animations:M}))},ne=[i.on("statechange",({state:n})=>{let a=pe(n);a==="starting"&&C!=="starting"&&(L=null,E=0,k=!1,y=null,b=null,_=0,F=0),z(a),W(),a==="recording"&&(K(),y=f(),L="hold",E=1,O())}),i.on("checks",n=>{K(),E=n.progress,k=n.factors.presence>0,O(),W()}),i.on("guidance",({key:n})=>{L=fe(n),O()}),i.on("frozen",({previewDataUrl:n})=>{b=f(),c.emit("frozen",{previewDataUrl:n})}),i.on("ramp",n=>c.emit("ramp",n)),i.on("artifacts",n=>{let a=q(),l=y!==null&&b!==null?Math.max(0,Math.round(b-y)):void 0;c.emit("captured",{keyframe:n.keyframe,...n.clip!==void 0?{clip:n.clip}:{},...n.clipMimeType!==void 0?{clipMime:n.clipMimeType}:{},width:e.video.videoWidth||_,height:e.video.videoHeight||F,...l!==void 0?{clipMs:l}:{},captureChannel:a==="desktop"?"desktop":"mobile",formFactor:a,...H?{degraded:"NO_RECORDER"}:{},engine:"v3",facingMode:i.facingMode,mode:m,...n.timing,...n.screenRamp!==void 0?{screenRamp:n.screenRamp}:{},...n.provenance!==void 0?{provenance:n.provenance}:{}})}),i.on("error",({kind:n,retryable:a,detail:l})=>{c.emit("error",me(n,a,l))})];return{handle:{get state(){return C},get captureMode(){return s()},get facingMode(){return i.facingMode??o},on:(n,a)=>c.on(n,a),start:n=>{if(m=s(),m==="self")return S(e.facing),S(n?.facing),D=!0,o="user",i.start({facingMode:"user"});let a=!D;D=!0;let l=n?.facing??(a?e.facing:void 0),R=w=>(o=w,i.start({facingMode:w}));return l!==void 0?R(l):a?d().then(w=>R(w?"environment":"user"),()=>R("user")):i.start({})},retry:()=>i.retry(),switchCamera:()=>s()!=="assisted"?!1:(m="assisted",o=o==="user"?"environment":"user",i.switchCamera(),!0),destroy:()=>{for(let n of ne)n();V.setActive(!1),i.destroy(),c.clear()}},setFlowState:n=>{C!==n&&z(n)}}}function Te(e){return ve(e).handle}export{se as a,X as b,Se as c,Ce as d,Le as e,Ee as f,ye as g,be as h,ee as i,fe as j,pe as k,te as l,me as m,ve as n,Te as o};
1
+ import{a as Z,d as j,e as J}from"./chunk-GT2ZLGF7.js";import{w as Q}from"./chunk-FGOVIGGL.js";import{c as q}from"./chunk-FUHDOEBP.js";import{f as G,l as N}from"./chunk-CQ7SKLMC.js";import{a as $,f as v}from"./chunk-OKWG3PVH.js";var se=12e4,X=13e4,oe=3e3,ie=1200,P=Symbol.for("@sekyro/web.preload.v1");function p(){let e=globalThis;return e[P]??(e[P]=new Map),e[P]}function g(e){let t=(e??$).replace(/\/+$/,"");return t===""?"/":t}function Y(e){let t=p(),r=t.get(e);return r===void 0&&(r={status:"idle",promise:null,scheduled:null,detectorPromise:null,detector:null,listeners:new Set},t.set(e,r)),r}function A(e,t){if(e.status!==t){e.status=t;for(let r of[...e.listeners])r(t)}}var T=e=>v({preferred:["blaze"],v3AssetBaseUrl:e,blazeInitTimeoutMs:se}),x=T;function Se(e){x=e??T}function Ce(){for(let e of p().values())e.detector?.destroy();p().clear(),x=T}function ae(){return typeof window<"u"&&typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"}function ce(){return navigator.connection?.saveData===!0}function de(e){let t=window;if(typeof t.requestIdleCallback=="function"){let s=t.requestIdleCallback(e,{timeout:oe});return()=>t.cancelIdleCallback?.(s)}let r=setTimeout(e,ie);return()=>clearTimeout(r)}function ue(e,t){let r,s=new Promise(o=>{r=o}),u=!1,f=()=>{},d={promise:s,settle:o=>{u||(u=!0,f(),e.scheduled===d&&(e.scheduled=null),r(o))}};return e.scheduled=d,f=de(()=>{u||d.settle(I(e,t))}),s}function I(e,t){if((e.status==="loading"||e.status==="ready")&&e.promise!==null)return e.promise;A(e,"loading");let r=new Promise(o=>o(x(t)));e.detectorPromise=r;let s,u=new Promise((o,h)=>{s=setTimeout(()=>{r.then(S=>S.destroy(),()=>{}),h(new Error(`detector preload exceeded ${X} ms`))},X)}),d=Promise.race([r,u]).then(o=>e.detectorPromise!==r?(o.destroy(),e.status):(e.detector=o,A(e,"ready"),"ready"),o=>(e.detectorPromise===r&&(e.detectorPromise=null,e.detector=null,A(e,"failed"),console.warn("[@sekyro/web] face-detector preload failed:",o)),e.status)).finally(()=>clearTimeout(s));return e.promise=d,e.scheduled?.settle(d),d}function Le(e={}){if(!ae())return Promise.resolve("idle");let t=g(e.assetBaseUrl),r=Y(t);return e.respectSaveData===!0&&ce()?Promise.resolve(r.status):(r.status==="loading"||r.status==="ready")&&r.promise!==null?r.promise:e.idle===!0?r.scheduled?.promise??ue(r,t):I(r,t)}function Ee(e){return p().get(g(e))?.status??"idle"}function ye(e,t){let r=Y(g(t));return r.listeners.add(e),()=>{r.listeners.delete(e)}}function be(e){let t=p().get(g(e));t!==void 0&&(t.scheduled?.settle("idle"),t.detector?.destroy(),t.detector=null,t.detectorPromise=null,t.promise=null,A(t,"idle"))}function le(e){return{get tier(){return e.tier},get fallbackReason(){return e.fallbackReason},detect:(...t)=>e.detect(...t),destroy:()=>{}}}function ee(e){let t=g(e),r=p().get(t);if(!(r===void 0||r.detector===null&&r.detectorPromise===null&&r.scheduled===null))return async()=>{r.scheduled!==null&&I(r,t);let s=r.promise;for(;r.detector===null&&s!==null&&(await s,r.promise!==s);)s=r.promise;return r.detector!==null?le(r.detector):v({v3AssetBaseUrl:t})}}function fe(e){switch(e){case"fcv3.no_face":case"fcv3.center_face":case"fcv3.straighten":return"center";case"fcv3.come_closer":return"closer";case"fcv3.move_back":return"farther";case"fcv3.more_light":case"fcv3.too_bright":return"light";case"fcv3.hold_still":case"fcv3.steady_camera":return"still";case"fcv3.hold_upright":return"upright";default:return null}}function pe(e){switch(e){case"preflight":case"acquiring":return"starting";case"positioning":return"gating";default:return e}}function te(e){switch(e){case"permission":case"notfound":case"inuse":case"insecure":case"unsupported":return e;default:{let t=e;return"generic"}}}function me(e,t,r){if(r===void 0)return{kind:te(e),retryable:t};let s=N(r.name);return{kind:te(e),retryable:t,detail:{...s!==void 0?{name:s}:{},phase:r.phase,engineKind:e}}}function ve(e,t={},r,s=()=>"self",u=()=>{}){let f=t.now??(()=>performance.now()),d=t.canChooseFacing??j,o="user",h=!1,S=n=>(n==="environment"&&!h&&(h=!0,console.warn('[@sekyro/web] facing "environment" ignored: this capture is a self capture (the person films themselves), which uses the front camera only. The back camera is for assisted capture, set in the flow.')),"user"),D=!1,m=s(),c=Z(),H=!G(),U=t.engineOptions,re=U?.createDetector===void 0&&U?.createWorker===void 0?{createDetector:()=>{let n=ee(e.assetBaseUrl);return n!==void 0?n():v({v3AssetBaseUrl:e.assetBaseUrl})}}:{},B={video:e.video,mode:H?"photo":"clip",rankKeyframes:r,facingMode:void 0,v3AssetBaseUrl:e.assetBaseUrl,screenRamp:()=>m==="self"&&c.count("ramp")>0?u():void 0,...t.engineOptions??{},...re},i=t.createEngine?.(B)??new Q(B),C="idle",L=null,E=0,k=!1,M="full",y=null,b=null,_=0,F=0,K=()=>{e.video.videoWidth>0&&e.video.videoHeight>0&&(_=e.video.videoWidth,F=e.video.videoHeight)},V=J({enabled:e.keepScreenAwake!==!1}),z=n=>{C=n,V.setActive(n==="starting"||n==="gating"||n==="recording"),c.emit("state",n)},O=()=>c.emit("gate",{progress:E,hint:L,faceDetected:k}),W=()=>{let n=i.animations??"full";n!==M&&(M=n,c.emit("profile",{animations:M}))},ne=[i.on("statechange",({state:n})=>{let a=pe(n);a==="starting"&&C!=="starting"&&(L=null,E=0,k=!1,y=null,b=null,_=0,F=0),z(a),W(),a==="recording"&&(K(),y=f(),L="hold",E=1,O())}),i.on("checks",n=>{K(),E=n.progress,k=n.factors.presence>0,O(),W()}),i.on("guidance",({key:n})=>{L=fe(n),O()}),i.on("frozen",({previewDataUrl:n})=>{b=f(),c.emit("frozen",{previewDataUrl:n})}),i.on("ramp",n=>c.emit("ramp",n)),i.on("artifacts",n=>{let a=q(),l=y!==null&&b!==null?Math.max(0,Math.round(b-y)):void 0;c.emit("captured",{keyframe:n.keyframe,...n.clip!==void 0?{clip:n.clip}:{},...n.clipMimeType!==void 0?{clipMime:n.clipMimeType}:{},width:e.video.videoWidth||_,height:e.video.videoHeight||F,...l!==void 0?{clipMs:l}:{},captureChannel:a==="desktop"?"desktop":"mobile",formFactor:a,...H?{degraded:"NO_RECORDER"}:{},engine:"v3",facingMode:i.facingMode,mode:m,...n.timing,...n.screenRamp!==void 0?{screenRamp:n.screenRamp}:{},...n.provenance!==void 0?{provenance:n.provenance}:{}})}),i.on("error",({kind:n,retryable:a,detail:l})=>{c.emit("error",me(n,a,l))})];return{handle:{get state(){return C},get captureMode(){return s()},get facingMode(){return i.facingMode??o},on:(n,a)=>c.on(n,a),start:n=>{if(m=s(),m==="self")return S(e.facing),S(n?.facing),D=!0,o="user",i.start({facingMode:"user"});let a=!D;D=!0;let l=n?.facing??(a?e.facing:void 0),R=w=>(o=w,i.start({facingMode:w}));return l!==void 0?R(l):a?d().then(w=>R(w?"environment":"user"),()=>R("user")):i.start({})},retry:()=>i.retry(),switchCamera:()=>s()!=="assisted"?!1:(m="assisted",o=o==="user"?"environment":"user",i.switchCamera(),!0),destroy:()=>{for(let n of ne)n();V.setActive(!1),i.destroy(),c.clear()}},setFlowState:n=>{C!==n&&z(n)}}}function Te(e){return ve(e).handle}export{se as a,X as b,Se as c,Ce as d,Le as e,Ee as f,ye as g,be as h,ee as i,fe as j,pe as k,te as l,me as m,ve as n,Te as o};
@@ -0,0 +1 @@
1
+ import{A as be,C as T,D as Z,h as K,i as X,j as fe,k as he,m as Se,n as ee,p as Q,q as te,s as ge,t as ye}from"./chunk-5ZKQHFFW.js";import{c as le,d as pe,e as me}from"./chunk-FPXL63KZ.js";import{c as F,h as $,i as Ce}from"./chunk-NJML6FMD.js";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 je=["carte_identite","passport","residence_permit"];function Ye(e,t){let n=e.byIssuer?.[t]??e.default;return je.filter(o=>n==="*"||n.includes(o))}function Ht(e,t=Pe){return[...new Set([...t,...Object.keys(e.byIssuer??{})])].filter(o=>Ye(e,o).length>0).sort()}function _e(e){if(e.acceptedDocuments)return e.acceptedDocuments;let t=e.acceptedDocumentTypes?.length?[...e.acceptedDocumentTypes]:["carte_identite","passport"];return{default:[],byIssuer:{MR:t}}}var We=640,Qe=new Set(["network_error","timeout","upload_failed","unknown_error","rate_limit_exceeded"]),ke=6,Re=1500,Me={sharpness:1,exposure:1,meanLuma:128},Ee=null;function $e(e,t){try{Ee??(Ee=document.createElement("canvas"));let n=Ee,o=96/Math.max(1,t.width);n.width=Math.max(1,Math.round(t.width*o)),n.height=Math.max(1,Math.round(t.height*o));let r=n.getContext("2d");if(r===null)return Me;r.drawImage(e,t.x,t.y,t.width,t.height,0,0,n.width,n.height);let c=r.getImageData(0,0,n.width,n.height);return{sharpness:pe(c),exposure:me(c),meanLuma:le(c)}}catch{return Me}}async function qe(e,t){let n=e.source;return"convertToBlob"in n?n.convertToBlob({type:"image/jpeg",quality:t}):new Promise((o,r)=>{n.toBlob(c=>c===null?r(new Error("encode failed")):o(c),"image/jpeg",t)})}function Zt(e,t={}){let n=t.now??(()=>performance.now()),o=t.setTimer??((p,i)=>setTimeout(p,i)),r=t.clearTimer??(p=>clearTimeout(p)),c=t.encode??qe,d=t.quality??$e,u=e.tuningVersion??null,m=new Set,b=!1,y=e.video??null,P=null,g=t.grabFrame??null,_=null,w=1e3/ke,k=null,E=null,L=!1,O=!1,A=Number.NEGATIVE_INFINITY,M=null,H=0,N=null,V=null,D=Promise.all([import("./icao-gate-PWBMKRGC.js"),import("./icao-tuning-4GGVX6B4.js"),import("./create-portrait-capture-MOS2D7CL.js"),import("./landmarker-KB7LVXAU.js"),import("./background-monitor-A7FKJOAG.js")]).then(async([p,i,s,a,l])=>{let h=i.resolveIcaoTuning(e.tuning,e.tuningVersion??void 0);h.background.required&&(E=l.createBackgroundMonitor({tuning:h.backgroundCheck,assetBaseUrl:e.assetBaseUrl??"/models-v3",...t.createSegmenter!==void 0?{createSegmenter:t.createSegmenter}:{},now:n})),P=p.createIcaoGate(h,{policy:e.policy??"reject"}),g??(g=s.defaultGrabber()),_=s.observe,w=1e3/Math.min(ke,h.cadenceHz);let C=(t.createLandmarker??a.createFaceLandmarker)(e.assetBaseUrl??"/models-v3"),S=await new Promise((f,R)=>{let v=setTimeout(()=>{R(new Error("landmarker init timeout")),C.then(I=>I.close(),()=>{})},a.LANDMARKER_INIT_TIMEOUT_MS);C.then(I=>{clearTimeout(v),f(I)},I=>{clearTimeout(v),R(I)})});b?S.close():k=S}).catch(()=>{L=!0}),j=p=>{for(let i of m)i({holding:O||L,update:p})},B=()=>{if(M=null,!(b||k===null||P===null||g===null||_===null||y===null)){if(n()-A>Re){j(null);return}try{let p=g(y,We);if(p!==null){let i=Math.max(n(),H+1);H=i;let s=k.detect(p.source,i),a=y.videoWidth||p.width,l=y.videoHeight||p.height,h=_(s,p,a,l);h.geometry!==null&&E!==null&&(h.backgroundCheck=E.measure(p,h.geometry.box,a,l));let C=P.push(h,n());O=C.ready,j(C)}}catch{}M=o(B,w)}},Y=()=>{let p=n()-A>Re;A=n(),p&&(P?.reset(),O=!1,N=null,V=null),M===null&&k!==null&&!b&&(M=o(B,0))},J=()=>{let p=g===null||y===null?null:g(y,null);if(p===null||P===null||Math.max(p.width,p.height)<e.still.minLongSidePx)return Promise.resolve(null);let i=P.summary();return c(p,e.still.jpegQuality).then(s=>({image:s,width:p.width,height:p.height,gate:i}),()=>null)},W=null;return{engineOptions:{measureQuality:(p,i)=>{y=p,Y();let s=d(p,i);return O||L?s:{...s,sharpness:0}},telemetry:p=>{if(p.type!=="fired"||b)return;N=J();let i=W;i!==null&&N.then(s=>s===null?void 0:i(s).catch(()=>{})),O=!1,M!==null&&r(M),M=null,A=Number.NEGATIVE_INFINITY}},decorate:p=>{let i=new WeakMap,s=new Map,a=S=>{let f=i.get(S);return f===void 0&&(f=(async()=>{let R=await ye(p,"image","image/jpeg",S.image.size,{engine:"portrait"});return await p.uploadToSpaces(R.uploadUrl,S.image,"image/jpeg"),(await p.completeMedia(R.key)).key})(),f.catch(()=>i.delete(S)),i.set(S,f)),f};W=a;let l=async S=>{let f;try{f=await a(S)}catch(R){let v=R?.code;if(typeof v=="string"&&Qe.has(v))throw R;return null}return{media:{portrait:f},gate:Ce(S.gate),...u!==null?{tuningVersion:u}:{}}},h=p.submitCheck.bind(p),C=(async(S,f,R)=>{if(S!=="liveness")return h(S,f,R);let v=R?.idempotencyKey,I=v===void 0?void 0:s.get(v);if(I===void 0){let ue=N;I=ue===null?Promise.resolve(null):ue.then(de=>de===null?null:l(de)),v!==void 0&&(s.set(v,I),I.catch(()=>s.delete(v)))}let z=await I;if(z===null)return h("liveness",f,R);let Ze=await h("liveness",{...f,portraitIcao:z},R);return V=z,Ze});return new Proxy(p,{get(S,f){if(f==="submitCheck")return C;let R=Reflect.get(S,f);return typeof R=="function"?R.bind(S):R}})},onGate:p=>(m.add(p),()=>m.delete(p)),lastPortraitInput:()=>V,destroy:()=>{b=!0,N=null,V=null,M!==null&&r(M),M=null,m.clear(),D.then(()=>{k?.close(),k=null,E?.close(),E=null})}}}function Ae(e){return e.idNumberBound??e.nniBound}function ve(e){return e===void 0?void 0:e.idNumberFromDocument??e.nniFromDocument}function Ie(e){let t=e.idNumberMasked??e.nniMasked;return typeof t=="string"&&t!==""?t:void 0}var Te=Object.freeze({nni_invalid:"id_number_invalid",nni_not_found:"registry_record_not_found",nni_recheck:"id_number_recheck",document_nni_mismatch:"document_id_number_mismatch",nni_locked:"id_number_locked",nni_unbound:"id_number_unbound",sandbox_nni_not_seeded:"sandbox_id_number_not_seeded",missing_nni:"missing_id_number",registry_needs_nni_source:"registry_needs_id_number_source"}),Je=new Map(Object.entries(Te)),Wt=new Map(Object.entries(Te).map(([e,t])=>[t,e]));function we(e){return Je.get(e)??e}var ze=new Set(["phone_otp","email_otp","national_eid","document","nfc","population_registry","supplied_identity","summary_confirm","liveness","portrait","face_match","aml_screening","face_dedup","age_estimation"]),Xe=new Set(["supplied_identity","aml_screening","face_dedup","age_estimation"]),ie=["document","population_registry","national_eid"],oe=["phone_otp","email_otp"],Ne={identity_method:ie,contact:oe},et=["population_registry","document"],Le="platform_unsupported",tt=new Set(["prefilled","user_entered","prefilled_or_entered"]),nt={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 x(e){return e.section??nt[e.checkType]??null}function re(e,t){let n=e.plan?.choice;if(n===void 0||n.locked)return;let o=n.options.find(r=>r.id!==n.selected&&r.available!==!1&&t.includes(r.service));return o===void 0?void 0:{nodeId:n.nodeId,option:o}}function se(e){let t=e.plan,n=t?.choice;if(t===void 0||n===void 0||n.locked||t.current===null||t.current===n.nodeId||ee(e))return null;let o=Ne[n.kind]??[...ie,...oe],r=n.options.flatMap(u=>u.available===!1||!o.includes(u.service)?[]:[u.nationalEid!=null?{id:u.id,service:u.service,nationalEid:u.nationalEid}:{id:u.id,service:u.service}]),c=t.steps.find(u=>u.id===t.current)?.service,d=n.selected??r.find(u=>u.service===c)?.id??null;return r.some(u=>u.id!==d)?{nodeId:n.nodeId,kind:n.kind,current:d,options:r}:null}function Ve(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})),n={sessionId:te(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&&(n.branding=e.branding),e.cameraUnavailableHandled===!0&&(n.cameraUnavailableHandled=!0);let o=se(e);return o!==null&&(n.switchable=o),n}function ot(e){let t={attemptsRemaining:fe(e),attemptsExhausted:e.attemptsExhausted===!0};return e.reason!==void 0&&(t.reason=e.reason),e.retakeHint!==void 0&&(t.retakeHint=e.retakeHint),t}var De={phone_otp:"phone",email_otp:"email"};function rt(e,t){let n=re(e,[t==="phone_otp"?"email_otp":"phone_otp"]);return n===void 0?void 0:De[n.option.service]}function st(e,t,n,o){let r=t.checkType==="email_otp",c=(r?t.emailOtp:t.otp)??{},d=r?t.emailOtp?.emailSource:t.otp?.numberSource,u=d!==void 0&&tt.has(d)?d:r?"prefilled_or_entered":"user_entered",m=typeof c.sentToMasked=="string"&&c.sentToMasked.length>0,b=c.prefilled===!0,y=rt(e,r?"email_otp":"phone_otp"),P={key:t.checkType,context:n,section:x(t),phase:m?"verify":"send",canSwitch:y!==void 0,...o},g=r?{kind:"email_otp",...P,emailSource:u,needsEmail:u!=="prefilled"&&!b}:{kind:"phone_otp",...P,numberSource:u,needsPhone:u!=="prefilled"&&!b,channels:(t.otp?.channels??[]).filter(_=>_==="whatsapp"||_==="sms")};if(y!==void 0&&(g.switchChannel=y),b&&(g.prefilled=!0),m&&(g.sentToMasked=c.sentToMasked),!r&&t.otp?.channel!==void 0&&(g.channel=t.otp.channel),!r&&Array.isArray(t.phoneCountries)&&(g.phoneCountries=t.phoneCountries.filter(_=>typeof _=="string"&&/^[A-Z]{2}$/.test(_))),!r&&Array.isArray(t.phoneRules)){let _=g.phoneCountries??[];g.phoneRules=t.phoneRules.flatMap(w=>{let k=ut(w);return k!==void 0&&_.includes(k.code)?[k]:[]})}return!r&&t.phoneInternational===!0&&(g.phoneInternational=!0),c.expiresAt!==void 0&&(g.codeExpiresAt=c.expiresAt),c.resendAvailableAt!==void 0&&(g.resendAvailableAt=c.resendAvailableAt),g}var at=/^[\d[\]\-|()?:^]{1,64}$/;function ct(e){try{return typeof e=="string"&&at.test(e)&&new RegExp(e)!==null}catch{return!1}}var Oe=e=>typeof e=="number"&&Number.isInteger(e)&&e>=1&&e<=15;function ut(e){let{code:t,dial:n,trunk:o,lengths:r,formats:c}=e??{};if(typeof t!="string"||typeof n!="string"||!/^\d{1,3}$/.test(n)||o!==void 0&&(typeof o!="string"||!/^\d{1,3}$/.test(o))||!Array.isArray(r)||r.length===0||!r.every(Oe))return;let d={code:t,dial:n,lengths:[...r].sort((u,m)=>u-m)};if(o!==void 0&&(d.trunk=o),c!==void 0){if(!(Array.isArray(c)&&c.length<=8&&c.every(m=>ct(m?.leading)&&Array.isArray(m.groups)&&m.groups.every(Oe)&&r.includes(m.groups.reduce((b,y)=>b+y,0)))))return;d.formats=c.map(m=>({leading:m.leading,groups:[...m.groups]}))}return d}function dt(e,t,n,o){let r=Ae(e)===!0?"bound":ve(t)===!0?"document":"typed",c=r==="typed"&&t.state==="input_required"&&t.reason!==void 0&&we(t.reason)==="id_number_recheck",d=Ve(se(e)),u=!o.attemptsExhausted&&d.length===1&&d[0]?.service==="document";return{kind:"registry",key:"registry",context:n,section:x(t),state:t.state==="input_required"?"input_required":"pending",source:r,recheck:c,canUseDocument:u,...o}}function lt(e,t,n,o){let r=[...t.acceptedSides??[]],c={kind:"document",key:"document",context:n,section:x(t),side:r.includes("recto")?"verso":"recto",acceptedSides:r,documents:_e(e),photo:Ge(e.documents),...o};return pt(e)&&(c.ageStepUp=!0),c}function Ge(e,t=!0){let n=e?.source==="upload"||e?.source==="choice"?e.source:"camera",o=e?.sourcePick==="camera"||e?.sourcePick==="upload"?e.sourcePick:null;return{source:n,pick:o,uploadOffered:t&&e?.uploadOffered===!0}}function pt(e){let t=X(e).find(o=>o.checkType==="age_estimation"),n=t?.reason;return t?.state==="failed"&&(n==="age_uncertain"||n==="age_unavailable")}function mt(e){let t=Q(e,"liveness");return t?.state==="passed"||t?.state==="review"}function xe(e,t,n,o,r){let c=t.icao?.report,d=e.portrait,u=r==="capture"?d?.pendingFix??null:null;u!==null&&(r="review");let m=He(e);return{kind:"portrait",key:`portrait:${r}`,context:n,section:x(t),phase:r,report:Array.isArray(c)?c:null,review:t.state==="review",tuning:e.capture?.icao??null,tuningVersion:e.capture?.tuningVersion??null,icao:$(e),retakeOnly:r==="capture"&&t.state==="input_required"&&m===void 0&&e.capture?.livePhoto?.oneCapture===!0&&mt(e),photo:Ge(d,r==="capture"),pendingFix:u,...m!==void 0?{captureMode:m}:{},...d?.reuse?.pending===!0?{reuse:!0}:{},...o}}function He(e){let t=e.portrait?.captureMode;return t==="self"||t==="assisted"||t==="choice"?t:void 0}var ne={minLongSidePx:1280,jpegQuality:.95};function ft(e,t){let n=e.capture?.livePhoto;if(n?.oneCapture!==!0)return null;let o=Q(e,"portrait_icao"),r=n.still??ne;return{icao:t==="liveness"&&$(e)!==null&&He(e)===void 0&&o!==void 0&&o.state==="pending"&&o.reason===void 0,still:{minLongSidePx:r.minLongSidePx??ne.minLongSidePx,jpegQuality:r.jpegQuality??ne.jpegQuality}}}function ht(e,t,n,o){let r=t.eid,c=x(t);if(r===void 0||r.challenge!=="app_code")return{kind:"unsupported",key:"unsupported:eid_auth",context:n,section:c,checkType:"eid_auth",reason:"update_required"};let d=Ve(se(e)),u=d.length===1&&et.includes(d[0]?.service??"")?d[0]:void 0,m=u===void 0?void 0:K[u.service],b=m!==void 0,y={kind:"eid",key:"eid",context:n,section:c,provider:r.provider,providerName:r.providerName,country:r.country,challenge:"app_code",phase:r.awaiting==="code"?"code":"identifier",identifierBound:r.identifierBound===!0,canUseCamera:b,afterPass:r.afterPass==="continue"?"continue":"end",...o};return b&&(y.cameraMethod=m),r.expiresAt!==void 0&&(y.codeExpiresAt=r.expiresAt),r.resendAvailableAt!==void 0&&(y.resendAvailableAt=r.resendAvailableAt),r.resendsRemaining!==void 0&&(y.resendsRemaining=r.resendsRemaining),r.codeAttemptsRemaining!==void 0&&(y.codeAttemptsRemaining=r.codeAttemptsRemaining),y}function St(e,t){if(t.checkType!=="face_match"||t.reason!==void 0)return null;let n=Q(e,"portrait_icao");return n!==void 0&&(n.state==="passed"||n.state==="review")?n:null}function gt(e){return X(e).filter(t=>t.state==="failed").pop()?.attemptsExhausted===!0}function yt(e,t){let n=e.failureReason,o;n===Le?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":n==="device_cooldown"?o="cooldown":n!==void 0?o="policy_stop":gt(e)?o="attempts_exhausted":o="rejected";let r=o==="platform_unsupported"?{sessionId:te(e.sessionId),status:"unavailable"}:ge(e,{autoRetry:!1}),c={kind:"result",key:"result",context:t,section:null,display:o,result:r};return n!==void 0&&(c.failureReason=n),e.retryAfter!==void 0&&(c.retryAfter=e.retryAfter),c}function bt(e,t,n){let o=e.identitySummary;if(o==null)return null;let r={kind:"identity_summary",key:"identity_summary",context:t,section:n??"identity",summaryKind:o.kind==="partial"?"partial":o.kind??"full",source:o.source,portraitAvailable:o.portrait?.available===!0,retakeAvailable:o.retakeAvailable===!0};for(let d of Ct){let u=o[d];typeof u=="string"&&u!==""&&(r[d]=u)}let c=Ie(o);return c!==void 0&&(r.idNumberMasked=c,r.nniMasked=c),r}var Ct=["fullName","birthDate","birthYear","nationality","documentType","documentNumberMasked","expiryDate","retakeTarget"];function G(e,t,n,o){return{kind:"unsupported",key:`unsupported:${n}`,context:e,section:t,checkType:n,reason:o}}function Pt(e){return e.kind==="contact"?"contact":(e.kind==="identity_method","identity")}function _t(e,t){let n=Ne[e.kind]??[...ie,...oe],o=Pt(e),r=e.options.flatMap(d=>{if(d.available===!1||!n.includes(d.service))return[];let u={id:d.id,service:d.service};d.nationalEid!=null&&(u.nationalEid=d.nationalEid);let m=(d.channels??[]).filter(b=>b==="whatsapp"||b==="sms");return d.service==="phone_otp"&&m.length>0&&(u.channels=m),[u]});if(r.length===0){let d=e.options.length>0&&e.options.every(u=>u.service==="nfc");return G(t,o,"choice",d?"platform_unsupported":"update_required")}let c={nodeId:e.nodeId,kind:e.kind,selected:e.selected,options:r};if(e.kind==="identity_method"){let d={kind:"method",key:"method",context:t,section:o,options:r.map(m=>K[m.service]),choice:c},u=r.find(m=>m.nationalEid!==void 0)?.nationalEid;return u!==void 0&&(d.nationalEid=u),d}return e.kind==="contact"?{kind:"contact_choice",key:"contact_choice",context:t,section:o,options:r.map(d=>De[d.service]),selected:null,locked:!1,choice:c}:{kind:"choice",key:`choice:${e.nodeId}`,context:t,section:o,choice:c}}function q(e,t={}){let n=it(e);if(ee(e)||e.failureReason===Le)return yt(e,n);let o=e.plan;if(o===void 0||!Array.isArray(o.sections))return G(n,null,"plan","update_required");let r=he(e);if(r!==null)return _t(r,n);let c=o.current===null?void 0:o.steps.find(P=>P.id===o.current),d=P=>{let g={kind:"processing",key:"processing",context:n,section:P!==void 0?x(P):o.sections.find(_=>_.state==="current")?.id??null,stalled:!1};return typeof P?.service=="string"&&P.service!==""&&(g.service=P.service),g};if(o.current===null)return d(o.steps.find(P=>P.state==="processing"));if(c===void 0)return G(n,null,"step","update_required");if(!ze.has(c.service))return c.interaction==="server"?d(c):G(n,x(c),c.service,"update_required");if(Xe.has(c.service)||!Se(c))return d(c);let u=c,m=ot(u),b=u.checkType,y=x(u);switch(b){case"phone_otp":case"email_otp":return st(e,u,n,m);case"population_registry":return dt(e,u,n,m);case"eid_auth":return ht(e,u,n,m);case"doc_ocr":return lt(e,u,n,m);case"identity_confirm":return bt(e,n,y)??d(u);case"portrait_icao":return xe(e,u,n,m,"capture");case"liveness":case"face_match":{let P=St(e,u);if(P!==null)return xe(e,P,n,m,"match");let g=u.requiresMobile===!0,_=$(e);return g&&t.isMobile===!1?{kind:"mobile_required",key:"mobile_required",context:n,section:y,checkType:b}:{kind:"liveness",key:"biometric",context:n,section:y,mode:b==="face_match"?"selfie":"liveness",requiresMobile:g,instructions:_===null?"standard":"icao",icao:_,livePhoto:ft(e,b),...m}}case"nfc_chip":return G(n,y,b,"platform_unsupported");default:return G(n,y,b,"update_required")}}var kt=/^[A-Z0-9][A-Z0-9 -]{0,39}$/,Rt=Object.freeze({normalize:e=>e.trim().toUpperCase().replace(/\s+/g," "),check:e=>kt.test(e),registrySources:Object.freeze([]),describe:"number must be 1 to 40 letters, digits, spaces or hyphens"});function Mt(e){return typeof e=="string"&&/^\d{10}$/.test(e)&&Number(e)%97===1}var Et=Object.freeze({normalize:e=>e.trim(),check:e=>Mt(e),registrySources:Object.freeze(["MR.anrpts"]),describe:"number must be the 10-digit Mauritanian national ID number with a valid check digit"}),At=Object.freeze({"MR:national_id":Et});function ae(e,t){return At[`${e.toUpperCase()}:${t}`]??Rt}var vt=Object.freeze({MRT:"MR"});function Be(e,t){let n=e.trim().toUpperCase();return ae(vt[n]??n,t)}function Ue(e){let t=Be(e.issuingCountry,e.type);return t.check(t.normalize(e.number))}function Fe(e){return ae("MR","national_id").check(e)}function ce(e){let t="";for(let n of e){let o=n.codePointAt(0)??0;o>=1632&&o<=1641?t+=String(o-1632):o>=1776&&o<=1785?t+=String(o-1776):n!==" "&&n!=="-"&&n!==" "&&(t+=n)}return t}var It=[1e3,2e3,4e3,8e3,15e3],Tt=3e4,wt=/^\+[1-9]\d{6,14}$/,Ot=/^\d{6}$/,xt=/^\d{6}$/,Nt=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,Ke=new Set(["session_not_active","check_not_found","check_already_finalized","check_out_of_order","identity_confirm_required","identity_confirm_locked","choice_locked","choice_option_unavailable","choice_not_found","step_not_on_path","check_not_active"]),Lt=new Set(["network_error","timeout","upload_failed","unknown_error","rate_limit_exceeded"]);function ln(e){let t=!1,n=null,o="",r=!1,c=!1,d=!1,u={},m={},b=new Set,y=!1,P=null,g="idle",_=new Map,w=new Map,k=(i,s,a)=>{let l=`${i}.${s}`,h=_.get(l);if(h!==void 0)return h;let C=w.get(i),S=(C===void 0?a():C.then(a)).finally(()=>{_.delete(l)});_.set(l,S);let f=S.then(()=>{},()=>{});return w.set(i,f),f.then(()=>{w.get(i)===f&&w.delete(i)}),S},E=async(i,s,a)=>{await e.ensureConsent();let l;try{l=await be(e.runtime,s)}catch(C){if(C instanceof F&&Ke.has(C.code)){await e.refreshView();return}throw C}if(a?.(l),e.destroyed())return;let h=l;h.plan!==void 0&&e.setView!==void 0?e.setView(h):await e.refreshView()},L=async i=>{await e.ensureConsent();let s;try{try{s=await i(e.runtime.client)}catch(a){if(!(a instanceof F)||a.code!=="consent_required")throw a;await e.runtime.ensureConsent({force:!0}),s=await i(e.runtime.client)}}catch(a){if(a instanceof F&&Ke.has(a.code)){await e.refreshView();return}throw a}e.destroyed()||(s!==void 0&&e.setView!==void 0?e.setView(s):await e.refreshView())},O=(i,s)=>k("choice",`${i}:${s}`,()=>L(a=>a.choose(i,s))),A=(i,s)=>i.options.some(a=>a.id===s)?O(i.nodeId,s):Promise.reject(new RangeError(`option ${String(s)} is not offered`)),M=(i,s)=>{let a=e.currentView(),l=a===null?void 0:re(a,i);return l===void 0?Promise.reject(new RangeError(`the ${s} is not offered`)):O(l.nodeId,l.option.id)},H=i=>k("identity",i,()=>L(s=>s.confirmIdentity===void 0?Promise.reject(new Error("identity confirmation is not available in this build")):s.confirmIdentity(i))),N=(i,s)=>{let a=i.kind,l=a==="phone_otp",h=l?"phone":"email",C={action:"send"};if(l?i.needsPhone:i.needsEmail){let S=s[h]??m[a],f=l?S?.replace(/[\s().-]/g,""):S?.trim();if(f!==void 0||i.phase!=="verify"){if(f===void 0||!(l?wt:Nt).test(f))return Promise.reject(l?new T("phone","format"):new Z("email","format"));C[h]=f}}if(l){let S=i.channels,f=s.channel??(S.length===1?S[0]:void 0);if(S.length>0){if(f===void 0)return Promise.reject(new Z("channel","required"));if(!S.includes(f))return Promise.reject(new Z("channel","unavailable"))}f!==void 0&&(C.channel=f),C.phoneRules=1}return k(a,"send",()=>E(a,(S,f)=>S.submitCheck(a,C,{idempotencyKey:f}),S=>{Vt(S,a)||(u[a]=e.now(),C[h]!==void 0&&(m[a]=C[h]))}))},V=(i,s)=>Ot.test(s)?k(i,"verify",()=>E(i,(a,l)=>a.submitCheck(i,{action:"verify",code:s},{idempotencyKey:l}))):Promise.reject(new T("code","format")),D=(i,s)=>k("eid_auth",i,()=>E("eid_auth",(a,l)=>a.submitCheck("eid_auth",s,{idempotencyKey:l}))),j=(i,s)=>{if(i.identifierBound)return D("start",{action:"start"});let a=ce(s??"");if(i.country==="MR"){if(!/^\d{10}$/.test(a))return Promise.reject(new T("nni","format"));if(!Fe(a))return Promise.reject(new T("nni","check_digit"))}else if(a==="")return Promise.reject(new T("nni","format"));return D("start",{action:"start",identifier:a})},B=(i,s,a)=>{if(i.source!=="typed")return Promise.reject(new RangeError("this session already holds the ID number"));let l=ce(s);return/^\d{10}$/.test(l)?Ue({type:"national_id",issuingCountry:"MR",number:l})?k("population_registry","submitIdNumber",()=>E("population_registry",(h,C)=>h.submitCheck("population_registry",{idNumber:l,nni:l},{idempotencyKey:C}),()=>{P=`\u2022\u2022\u2022\u2022\u2022\u2022${l.slice(-4)}`})):Promise.reject(new T(a,"check_digit")):Promise.reject(new T(a,"format"))},Y=i=>{switch(i.kind){case"phone_otp":case"email_otp":{let s={...i,send:(l={})=>N(i,l),verify:l=>V(i.kind,l),switchTo:()=>i.canSwitch&&i.switchChannel!==void 0?M([i.switchChannel==="email"?"email_otp":"phone_otp"],"other contact option"):Promise.reject(new RangeError("this session has no other contact option"))},a=u[i.kind];return s.resendAvailableAt===void 0&&a!==void 0&&(s.resendAvailableAt=new Date(a+Tt).toISOString()),s}case"eid":return{...i,start:s=>j(i,s),verify:s=>xt.test(s)?D("verify",{action:"verify",code:s}):Promise.reject(new T("code","format")),resend:()=>i.resendsRemaining===0?Promise.reject(new RangeError("no new code can be sent for this session")):D("resend",{action:"resend"}),useCamera:()=>i.canUseCamera&&i.cameraMethod!==void 0?M(i.cameraMethod==="document_photo"?["document"]:["population_registry"],"camera path"):Promise.reject(new RangeError("the camera path is not offered"))};case"method":return{...i,select:s=>{let a=i.choice.options.find(l=>K[l.service]===s);return a!==void 0?A(i.choice,a.id):Promise.reject(new RangeError(`method ${String(s)} is not offered`))},choose:s=>A(i.choice,s)};case"choice":return{...i,choose:s=>A(i.choice,s)};case"registry":return{...i,submitIdNumber:s=>B(i,s,"idNumber"),submitNni:s=>B(i,s,"nni"),confirm:()=>k("population_registry","confirm",()=>E("population_registry",(s,a)=>s.submitCheck("population_registry",{},{idempotencyKey:a}))),useDocument:()=>i.canUseDocument?M(["document"],"document method"):Promise.reject(new RangeError("the document method is not offered"))};case"document":return e.bindDocument!==void 0?e.bindDocument(i,p):{...i,issuer:null,documentType:null,captureSide:null,selectDocument:()=>{throw new Error("document capture is not available in this build")},capture:()=>{throw new Error("document capture is not available in this build")},uploadDocument:()=>Promise.reject(new Error("document upload is not available in this build"))};case"portrait":return e.bindPortrait!==void 0?e.bindPortrait(i,p):{...i,uploadFailed:!1,resubmit:()=>Promise.resolve(),capture:()=>{throw new Error("portrait capture is not available in this build")},uploadPortrait:()=>Promise.reject(new Error("portrait upload is not available in this build")),confirmFix:()=>Promise.reject(new Error("portrait review is not available in this build"))};case"contact_choice":return{...i,select:s=>{let a=s==="phone"?"phone_otp":s==="email"?"email_otp":void 0,l=i.choice.options.find(h=>h.service===a);return l!==void 0?A(i.choice,l.id):Promise.reject(new RangeError(`contact ${String(s)} is not offered`))},choose:s=>A(i.choice,s)};case"identity_summary":return{...i,...i.idNumberMasked===void 0&&i.summaryKind==="partial"&&P!==null?{idNumberMasked:P,nniMasked:P}:{},portrait:async()=>{let s=e.runtime.client;if(!i.portraitAvailable||s.identityPortrait===void 0)return null;try{return await s.identityPortrait()}catch{return null}},confirm:()=>H("confirm"),retake:()=>i.retakeAvailable?H("retake"):Promise.reject(new RangeError("no retake is left"))};case"liveness":return{...i,capture:s=>e.liveness(s),onLivePhoto:s=>i.livePhoto?.icao===!0&&e.onLivePhoto!==void 0?e.onLivePhoto(s):()=>{}};case"mobile_required":case"processing":return{...i,refresh:async()=>{r=!1,await e.refreshView()}};case"unsupported":case"result":return{...i};default:{let s=i;throw new Error(`runner: unhandled step ${JSON.stringify(s)}`)}}},J=async()=>{if(!c){c=!0;try{for(let i of It){if(await e.sleep(i),!t||e.destroyed())return;let s=await e.refreshView().catch(()=>null);if(s!==null&&q(s,{isMobile:e.isMobile()}).kind!=="processing")return}r=!0,p()}finally{c=!1}}},W=i=>{if(i.kind!=="liveness"||i.mode!=="selfie")return null;let s={kind:"processing",key:"processing",context:i.context,section:i.section,stalled:!1};if(g==="inflight")return s;if(!y||g==="done")return null;let a=e.keptFaceKey?.()??null;return a===null?null:(g="inflight",E("face_match",(l,h)=>l.submitCheck("face_match",{imageKey:a},{idempotencyKey:h}),()=>{g="done"}).then(()=>{g==="inflight"&&(g="done",p())},()=>{g="done",p()}),s)},U=(i,s=!1)=>{if(!t||e.destroyed()||e.chainBusy())return;let a=q(i,{isMobile:e.isMobile()});a.kind==="registry"&&a.recheck&&(y=!0,g="idle"),a=W(a)??a,a.kind==="processing"?a.stalled=r:r=!1;let l=Y(a),h=a.kind==="result"?void 0:a.context.switchable,C=h===void 0?l:{...l,chooseOption:f=>A({nodeId:h.nodeId,kind:h.kind,selected:h.current,options:h.options},f)},S=JSON.stringify(C);a.kind==="registry"&&a.source==="document"&&a.state==="pending"&&!b.has("registry")&&(b.add("registry"),C.confirm().catch(f=>{(!(f instanceof F)||Lt.has(f.code))&&b.delete("registry")})),!(!s&&S===o)&&(o=S,n=C,e.emitStep(C),a.kind==="processing"&&!r&&g!=="inflight"&&J(),a.kind==="result"&&!d&&(d=!0,e.emitResult(a.result)))};function p(){let i=e.currentView();i!==null&&U(i,!0)}return{run:async()=>{if(e.destroyed())throw new Error("verification destroyed");t=!0;let i=await e.ensureView();return n===null&&U(i),n??Y(q(i,{isMobile:e.isMobile()}))},current:()=>n,onView:i=>U(i),onChainIdle:()=>{let i=e.currentView();i!==null&&U(i)},republish:p,submit:E}}function Vt(e,t){let n=e,o=n?.plan?.steps??n?.steps;return Array.isArray(o)?o.some(r=>r.checkType===t&&typeof r.reason=="string"):!1}export{Ye as a,Ht as b,ke as c,Re as d,Zt as e,He as f,q as g,It as h,Tt as i,ln as j};
@@ -0,0 +1 @@
1
+ var m="0.1.0-rc.20";var T=/FBAN|FBAV|FB_IAB|FBIOS|MessengerForiOS|Instagram|WhatsApp|musical_ly|BytedanceWebview|TikTok|Snapchat|\bLine\/|LinkedInApp|Pinterest|MicroMessenger|; wv\)/i;function p(t){let e=t??(typeof navigator>"u"?"":String(navigator.userAgent??""));return T.test(e)}var y="sekyro.did",I=1e4,v=()=>globalThis.process?.versions?.node,h;function b(){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,r=>r.toString(16).padStart(2,"0")).join("")}}catch{}}function w(){try{let t=localStorage.getItem(y);if(t)return t;let e=b();return e!==void 0&&localStorage.setItem(y,e),e}catch{return h??(h=b()),h}}async function P(){let t=globalThis.crypto?.subtle;if(!t)return"";let e=navigator,r=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]),i=await t.digest("SHA-256",new TextEncoder().encode(r));return Array.from(new Uint8Array(i),o=>o.toString(16).padStart(2,"0")).join("").slice(0,32)}function k(t){let e=new TextEncoder().encode(t),r="";for(let i of e)r+=String.fromCharCode(i);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function x(t){let e,r,i,o,a,l,u=()=>l?.readyState==="live",_=()=>{a!==void 0||!globalThis.crypto?.subtle||v()||u()||(a=Promise.race([import("./print-AYSCRSZB.js"),new Promise(n=>setTimeout(n,I))]).then(n=>n?.computePrint(u)).then(n=>{n==="busy"?a=void 0:o=n}).catch(()=>{}))};return{timezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone?.slice(0,64)||void 0}catch{return}},noteCameraLabel(n){n&&(e=n.slice(0,128))},noteCamera(n){r=n},noteCameraTrack(n){l=n},async deviceHeader(){try{i??(i=P().catch(()=>""));let n=[];navigator.webdriver&&n.push("webdriver"),/HeadlessChrome/.test(navigator.userAgent)&&n.push("headless");let g=await i,f=w(),S={v:1,platform:"web",sdk:t.sdk.slice(0,64),ids:[...f?[{kind:"web_local",value:f.slice(0,128)}]:[],...g?[{kind:"web_fp",value:g}]:[]],screen:{w:screen.width,h:screen.height,dpr:globalThis.devicePixelRatio??1},...e?{cameraLabel:e}:{},...n.length?{signals:n}:{},...o?{print:{v:2,...o,...r?{camera:r}:{}}}:{},...p()?{inApp:!0}:{}},C=k(JSON.stringify(S));return _(),C}catch{return}},printReady(){return a??Promise.resolve()}}}var s=Symbol.for("sekyro.web.clientContext"),c=globalThis,d=c[s]??(c[s]=x({sdk:`@sekyro/web@${m}`}));function N(t){try{let e=t.getVideoTracks?.()[0];if(e){if(d.noteCameraLabel(e.label),d.noteCameraTrack(e),v())return;import("./camera-trait-45MJTW4K.js").then(r=>r.noteCameraTrait(e,d)).catch(()=>{})}}catch{}}export{m as a,p as b,d as c,N as d};
@@ -1 +1 @@
1
- "use strict";var f=Object.defineProperty;var H=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var A=Object.prototype.hasOwnProperty;var N=(n,e)=>{for(var o in e)f(n,o,{get:e[o],enumerable:!0})},D=(n,e,o,t)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of M(e))!A.call(n,i)&&i!==o&&f(n,i,{get:()=>e[i],enumerable:!(t=H(e,i))||t.enumerable});return n};var x=n=>D(f({},"__esModule",{value:!0}),n);var Q={};N(Q,{HostedApiError:()=>d,HostedClient:()=>m,KNOWN_CODES:()=>b,SEKYRO_SDK_HEADER:()=>w,icaoPolicyOf:()=>E,isKnownCode:()=>k,portraitIcaoGate:()=>v,stripMimeParams:()=>u});module.exports=x(Q);var y="0.1.0-rc.19";var C="sekyro.did",T;function P(){let n=globalThis.crypto;try{if(typeof n?.randomUUID=="function")return n.randomUUID()}catch{}try{if(typeof n?.getRandomValues=="function"){let e=n.getRandomValues(new Uint8Array(16));return Array.from(e,o=>o.toString(16).padStart(2,"0")).join("")}}catch{}}function V(){try{let n=localStorage.getItem(C);if(n)return n;let e=P();return e!==void 0&&localStorage.setItem(C,e),e}catch{return T??(T=P()),T}}async function K(){let n=globalThis.crypto?.subtle;if(!n)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]),t=await n.digest("SHA-256",new TextEncoder().encode(o));return Array.from(new Uint8Array(t),i=>i.toString(16).padStart(2,"0")).join("").slice(0,32)}function U(n){let e=new TextEncoder().encode(n),o="";for(let t of e)o+=String.fromCharCode(t);return btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function L(n){let e,o;return{timezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone?.slice(0,64)||void 0}catch{return}},noteCameraLabel(t){t&&(e=t.slice(0,128))},async deviceHeader(){try{o??(o=K().catch(()=>""));let t=[];navigator.webdriver&&t.push("webdriver"),/HeadlessChrome/.test(navigator.userAgent)&&t.push("headless");let i=await o,s=V(),a={v:1,platform:"web",sdk:n.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}:{},...t.length?{signals:t}:{}};return U(JSON.stringify(a))}catch{return}}}}var h=Symbol.for("sekyro.web.clientContext"),_=globalThis,g=_[h]??(_[h]=L({sdk:`@sekyro/web@${y}`}));var b=["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","id_number_locked","document_id_number_mismatch"];function k(n){return b.includes(n)}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 F=6e4,I=4,$=3e4,q=9e5,B=200,Y=5,j=400,G=new Set(["server_busy","request_timeout"]),z=3e3;function u(n){return(n.split(";")[0]??"").trim()}var W={liveness:"clipKey",face_match:"imageKey",doc_ocr:"imageKey"},w=`@sekyro/web/${y}`,J=w,m=class{constructor(e){this.sessionId=null;this.bootstrap=null;this.captureNonces=[];this.captureFetch=null;this.reportedIssues=new Set;this.apiOrigin=e.apiOrigin.replace(/\/+$/,""),this.sessionToken=e.sessionToken;let o=e.fetch;this.fetchImpl=(t,i)=>(o??globalThis.fetch).call(globalThis,t,i),this.requestTimeoutMs=e.requestTimeoutMs??$,this.retryAttempts=e.inProgressRetry?.attempts??Y,this.retryDelayMs=e.inProgressRetry?.delayMs??j}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},busyRetry:!0})}async reportCameraUnavailable(e){return this.api("POST","/hosted/camera-unavailable",{body:{cause:e}})}async reportCaptureIssue(e){let o=typeof e.name=="string"?e.name.replace(/[^A-Za-z]/g,"").slice(0,40):"",t=typeof e.engineKind=="string"&&/^[a-z_]{1,32}$/.test(e.engineKind)?e.engineKind:void 0,i=typeof e.attempt=="number"&&Number.isInteger(e.attempt)&&e.attempt>=0&&e.attempt<=1e3?e.attempt:void 0,s=[e.check,i??"",e.kind,o,e.phase??""].join("|");if(this.reportedIssues.has(s))return;this.reportedIssues.add(s);let a={check:e.check,kind:e.kind,...o!==""?{name:o}:{},...e.phase!==void 0?{phase:e.phase}:{},...t!==void 0?{engineKind:t}:{},...i!==void 0?{attempt:i}:{},...e.formFactor!==void 0?{formFactor:e.formFactor}:{}};try{await this.api("POST","/hosted/capture-issue",{body:a,empty:!0})}catch{}}async choose(e,o){let t=await this.api("POST","/hosted/choice",{body:{nodeId:e,option:o},busyRetry:!0});return this.sessionId=t.sessionId,t}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,t){let i=await this.ensureSessionId(),s={kind:e,contentType:u(o),contentLength:t};return this.api("POST",`/sessions/${i}/media`,{body:s})}armCapture(e=2){this.fillCaptureNonces(e)}async presignCapture(e,o,t,i={}){let s=await this.ensureSessionId(),a=await this.takeCaptureNonce(),c=a===void 0?void 0:{nonce:a,...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)))}:{}},r={kind:e,contentType:u(o),contentLength:t,capture:c};return this.api("POST",`/sessions/${s}/media`,{body:r})}async takeCaptureNonce(){let e=()=>{let o=Date.now();return this.captureNonces=this.captureNonces.filter(t=>t.expiresAt-F>o),this.captureNonces.shift()?.nonce};for(let o=0;o<2;o++){let t=e();if(t!==void 0)return t;await this.fillCaptureNonces(1)}return e()}fillCaptureNonces(e){return this.captureFetch??(this.captureFetch=(async()=>{try{let o=await this.ensureSessionId(),t=await this.api("POST",`/sessions/${o}/media/capture-nonces`,{body:{count:Math.min(I,Math.max(1,e))}}),i=Date.now()+Math.max(0,t.expiresIn)*1e3;for(let s of Array.isArray(t.nonces)?t.nonces:[])typeof s=="string"&&s.length>0&&this.captureNonces.push({nonce:s,expiresAt:i});this.captureNonces=this.captureNonces.slice(-I)}catch{}})().finally(()=>{this.captureFetch=null})),this.captureFetch}async uploadToSpaces(e,o,t){let i;try{i=await this.fetchImpl(e,{method:"PUT",headers:{"content-type":u(t)},body:o,signal:AbortSignal.timeout(q)})}catch(s){throw S(s)}if(!i.ok){let s=(await i.text().catch(()=>"")).slice(0,B);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,t={}){let i=await this.ensureSessionId(),s={input:o,forceOutcome:t.forceOutcome};return this.api("POST",`/sessions/${i}/checks/${e}`,{body:s,idempotencyKey:t.idempotencyKey,busyRetry:t.idempotencyKey!==void 0})}async uploadAndSubmit(e,o,t,i={}){let s=u(o.contentType),a=await this.presign(o.kind,s,o.blob.size);await this.uploadToSpaces(a.uploadUrl,o.blob,s);let c=await this.completeMedia(a.key),r={...t,[W[e]]:c.key};return this.submitCheck(e,r,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,t={}){let i=e==="GET"||t.busyRetry===!0,s=`${this.apiOrigin}/api/v2${o}`,a={"x-session-token":this.sessionToken,"x-sekyro-sdk":J};t.body!==void 0&&(a["content-type"]="application/json"),t.idempotencyKey!==void 0&&(a["x-idempotency-key"]=t.idempotencyKey);try{let c=g.timezone();c!==void 0&&(a["sekyro-client-timezone"]=c)}catch{}try{let c=await g.deviceHeader();c!==void 0&&(a["sekyro-client-device"]=c)}catch{}for(let c=0;;c++){let r;try{r=await this.fetchImpl(s,{method:e,headers:a,...t.body!==void 0?{body:JSON.stringify(t.body)}:{},cache:"no-store",signal:AbortSignal.timeout(this.requestTimeoutMs)})}catch(l){throw S(l)}if(r.ok){if(t.empty===!0)return;if(t.blob===!0)try{return await r.blob()}catch(O){throw S(O)}let l;try{l=await r.json()}catch{throw new d({status:r.status,code:"unknown_error",message:`response body was not valid JSON (HTTP ${r.status})`})}return Z(l)}let p=await X(r);if(p.code==="idempotency_in_progress"&&c<this.retryAttempts){this.retryDelayMs>0&&await R(this.retryDelayMs);continue}if(i&&p.status===503&&G.has(p.code)){i=!1,await R(Math.min((p.retryAfterSeconds??2)*1e3,z));continue}throw p}}};function S(n){if((typeof n=="object"&&n!==null?n.name:void 0)==="TimeoutError")return new d({status:0,code:"timeout",message:"request timed out"});let o=n instanceof Error?n.message:String(n);return new d({status:0,code:"network_error",message:`network request failed: ${o}`})}function Z(n){return n!==null&&typeof n=="object"&&"success"in n&&"data"in n?n.data:n}async function X(n){let e="unknown_error",o=`request failed (HTTP ${n.status})`,t=Number.NaN,i;try{let c=await n.json();if(c!==null&&typeof c=="object"){let r=c;typeof r.code=="string"&&r.code.length>0&&(e=r.code),typeof r.message=="string"&&r.message.length>0&&(o=r.message),typeof r.retryAfterSeconds=="number"&&(t=r.retryAfterSeconds),Array.isArray(r.details?.issues)&&(i=r.details)}}catch{}let s=n.headers.get("retry-after"),a=s===null?Math.floor(t):Number.parseInt(s,10);return new d({status:n.status,code:e,message:o,...Number.isFinite(a)&&a>=0?{retryAfterSeconds:a}:{},details:i})}function R(n){return new Promise(e=>setTimeout(e,n))}function E(n){let e=n?.portrait,o=e?.icao,t=e?.purpose==="id_document";return o==null?t?{policy:"reject",profile:"id_document"}:null:{policy:o.policy==="alert"&&!t?"alert":"reject",profile:t||o.profile==="id_document"?"id_document":"selfie"}}function v(n){return{...n.baselineEyeOpenness!==void 0?{baselineEyeOpenness:n.baselineEyeOpenness}:{},criteria:n.verdict??{},...n.backgroundCheck!==void 0?{backgroundCheck:n.backgroundCheck}:{}}}0&&(module.exports={HostedApiError,HostedClient,KNOWN_CODES,SEKYRO_SDK_HEADER,icaoPolicyOf,isKnownCode,portraitIcaoGate,stripMimeParams});
1
+ "use strict";var g=Object.defineProperty;var W=Object.getOwnPropertyDescriptor;var j=Object.getOwnPropertyNames;var G=Object.prototype.hasOwnProperty;var b=(t,e)=>()=>(t&&(e=t(t=0)),e);var I=(t,e)=>{for(var n in e)g(t,n,{get:e[n],enumerable:!0})},z=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of j(e))!G.call(t,o)&&o!==n&&g(t,o,{get:()=>e[o],enumerable:!(i=W(e,o))||i.enumerable});return t};var J=t=>z(g({},"__esModule",{value:!0}),t);var v=b(()=>{"use strict"});function _(t,e){return new Promise(n=>{let i=setTimeout(()=>n(void 0),e),o=r=>{clearTimeout(i),n(r)};try{t().then(o,()=>o(void 0))}catch{o(void 0)}})}async function M(t){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(JSON.stringify(t)));return Array.from(new Uint8Array(e).subarray(0,8),n=>n.toString(16).padStart(2,"0")).join("")}var R=b(()=>{"use strict";v()});var O={};I(O,{computePrint:()=>de,readHints:()=>x});function E(t,e){if(typeof t!="string")return;let n=t.trim();return n.length>0&&n.length<=e?n:void 0}async function x(){let t=navigator.userAgentData;if(typeof t?.getHighEntropyValues!="function")return;let e=await _(()=>t.getHighEntropyValues(["model","platformVersion"]),te);if(e==null)return;let n=E(e.model,ie),i=E(e.platformVersion,oe),o={...n!==void 0?{model:n}:{},...i!==void 0?{platformVersion:i}:{}};return Object.keys(o).length>0?o:void 0}async function ae(){let[t,e]=await Promise.all([new A.Thumbmark({stabilize:["private","iframe"],exclude:["permissions","webrtc","speech"],logging:!1,collect_beacon:!1,timeout:Q}).get(),x()]),n=t?.thumbmark;if(typeof n!="string"||n.length<re||n.length>se)return;let i={};for(let o of Z){let r=t.components?.[o];r==null||r.timeout==="true"||(i[o]=await M(r))}return{hash:n,c:i,...e!==void 0?{hints:e}:{}}}function ce(){return new Promise(t=>{typeof globalThis.requestIdleCallback=="function"?globalThis.requestIdleCallback(()=>t(),{timeout:ne}):t()})}async function de(t){return t()||(await ce(),t())?"busy":_(ae,ee)}var A,Z,Q,ee,te,ne,ie,oe,re,se,H=b(()=>{"use strict";A=require("@thumbmarkjs/thumbmarkjs");R();Z=["canvas","webgl","audio","fonts","hardware","screen","system","locales","math","plugins"],Q=2e3,ee=4e3,te=1e3,ne=2e3,ie=64,oe=32,re=8,se=128});var Me={};I(Me,{HostedApiError:()=>u,HostedClient:()=>h,KNOWN_CODES:()=>P,SEKYRO_SDK_HEADER:()=>k,icaoPolicyOf:()=>B,isInAppBrowser:()=>y,isKnownCode:()=>F,portraitIcaoGate:()=>q,stripMimeParams:()=>p});module.exports=J(Me);var f="0.1.0-rc.20";var X=/FBAN|FBAV|FB_IAB|FBIOS|MessengerForiOS|Instagram|WhatsApp|musical_ly|BytedanceWebview|TikTok|Snapchat|\bLine\/|LinkedInApp|Pinterest|MicroMessenger|; wv\)/i;function y(t){let e=t??(typeof navigator>"u"?"":String(navigator.userAgent??""));return X.test(e)}var N="sekyro.did",ue=1e4,le=()=>globalThis.process?.versions?.node,D;function V(){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,n=>n.toString(16).padStart(2,"0")).join("")}}catch{}}function pe(){try{let t=localStorage.getItem(N);if(t)return t;let e=V();return e!==void 0&&localStorage.setItem(N,e),e}catch{return D??(D=V()),D}}async function me(){let t=globalThis.crypto?.subtle;if(!t)return"";let e=navigator,n=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]),i=await t.digest("SHA-256",new TextEncoder().encode(n));return Array.from(new Uint8Array(i),o=>o.toString(16).padStart(2,"0")).join("").slice(0,32)}function fe(t){let e=new TextEncoder().encode(t),n="";for(let i of e)n+=String.fromCharCode(i);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function ye(t){let e,n,i,o,r,c,d=()=>c?.readyState==="live",s=()=>{r!==void 0||!globalThis.crypto?.subtle||le()||d()||(r=Promise.race([Promise.resolve().then(()=>(H(),O)),new Promise(a=>setTimeout(a,ue))]).then(a=>a?.computePrint(d)).then(a=>{a==="busy"?r=void 0:o=a}).catch(()=>{}))};return{timezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone?.slice(0,64)||void 0}catch{return}},noteCameraLabel(a){a&&(e=a.slice(0,128))},noteCamera(a){n=a},noteCameraTrack(a){c=a},async deviceHeader(){try{i??(i=me().catch(()=>""));let a=[];navigator.webdriver&&a.push("webdriver"),/HeadlessChrome/.test(navigator.userAgent)&&a.push("headless");let l=await i,m=pe(),$={v:1,platform:"web",sdk:t.sdk.slice(0,64),ids:[...m?[{kind:"web_local",value:m.slice(0,128)}]:[],...l?[{kind:"web_fp",value:l}]:[]],screen:{w:screen.width,h:screen.height,dpr:globalThis.devicePixelRatio??1},...e?{cameraLabel:e}:{},...a.length?{signals:a}:{},...o?{print:{v:2,...o,...n?{camera:n}:{}}}:{},...y()?{inApp:!0}:{}},Y=fe(JSON.stringify($));return s(),Y}catch{return}},printReady(){return r??Promise.resolve()}}}var T=Symbol.for("sekyro.web.clientContext"),S=globalThis,w=S[T]??(S[T]=ye({sdk:`@sekyro/web@${f}`}));var P=["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","id_number_locked","document_id_number_mismatch"];function F(t){return P.includes(t)}var u=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)}};function L(t,e,n=Math.random){let i=(t??e)*1e3,o=Math.min(Math.max(i,500),2e4),r=Math.round(o*(1+(n()*2-1)*.25));return Math.min(Math.max(r,500),2e4)}var he=6e4,U=4,ge=3e4,be=9e5,_e=200,Te=5,Se=400,we=new Set(["server_busy","request_timeout"]),Pe=2;function p(t){return(t.split(";")[0]??"").trim()}var Ce={liveness:"clipKey",face_match:"imageKey",doc_ocr:"imageKey"},k=`@sekyro/web/${f}`,ke=k,h=class{constructor(e){this.sessionId=null;this.bootstrap=null;this.captureNonces=[];this.captureFetch=null;this.reportedIssues=new Map;this.apiOrigin=e.apiOrigin.replace(/\/+$/,""),this.sessionToken=e.sessionToken;let n=e.fetch;this.fetchImpl=(i,o)=>(n??globalThis.fetch).call(globalThis,i,o),this.requestTimeoutMs=e.requestTimeoutMs??ge,this.retryAttempts=e.inProgressRetry?.attempts??Te,this.retryDelayMs=e.inProgressRetry?.delayMs??Se,this.random=e.random??Math.random}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},busyRetry:!0})}async reportCameraUnavailable(e){return this.api("POST","/hosted/camera-unavailable",{body:{cause:e}})}async reportCaptureIssue(e){let n=typeof e.name=="string"?e.name.replace(/[^A-Za-z]/g,"").slice(0,40):"",i=typeof e.engineKind=="string"&&/^[a-z_]{1,32}$/.test(e.engineKind)?e.engineKind:void 0,o=typeof e.attempt=="number"&&Number.isInteger(e.attempt)&&e.attempt>=0&&e.attempt<=1e3?e.attempt:void 0,r=[e.check,o??"",e.kind,n,e.phase??""].join("|"),c=this.reportedIssues.get(r);if(c!==void 0)return c;let d={check:e.check,kind:e.kind,...n!==""?{name:n}:{},...e.phase!==void 0?{phase:e.phase}:{},...i!==void 0?{engineKind:i}:{},...o!==void 0?{attempt:o}:{},...e.formFactor!==void 0?{formFactor:e.formFactor}:{}},s=this.api("POST","/hosted/capture-issue",{body:d,empty:!0}).catch(()=>{this.reportedIssues.delete(r)});return this.reportedIssues.set(r,s),s}async choose(e,n){let i=await this.api("POST","/hosted/choice",{body:{nodeId:e,option:n},busyRetry:!0});return this.sessionId=i.sessionId,i}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,n,i,o={}){let r=await this.ensureSessionId(),c={kind:e,contentType:p(n),contentLength:i,...o.source==="upload"?{source:"upload"}:{}};return this.api("POST",`/sessions/${r}/media`,{body:c})}armCapture(e=2){this.fillCaptureNonces(e)}async presignCapture(e,n,i,o={}){let r=await this.ensureSessionId(),c=await this.takeCaptureNonce(),d=c===void 0?void 0:{nonce:c,...o.engine!==void 0?{engine:o.engine.slice(0,32)}:{},...o.durationMs!==void 0&&Number.isFinite(o.durationMs)?{captureMs:Math.min(36e5,Math.max(0,Math.round(o.durationMs)))}:{}},s={kind:e,contentType:p(n),contentLength:i,capture:d};return this.api("POST",`/sessions/${r}/media`,{body:s})}async takeCaptureNonce(){let e=()=>{let n=Date.now();return this.captureNonces=this.captureNonces.filter(i=>i.expiresAt-he>n),this.captureNonces.shift()?.nonce};for(let n=0;n<2;n++){let i=e();if(i!==void 0)return i;await this.fillCaptureNonces(1)}return e()}fillCaptureNonces(e){return this.captureFetch??(this.captureFetch=(async()=>{try{let n=await this.ensureSessionId(),i=await this.api("POST",`/sessions/${n}/media/capture-nonces`,{body:{count:Math.min(U,Math.max(1,e))}}),o=Date.now()+Math.max(0,i.expiresIn)*1e3;for(let r of Array.isArray(i.nonces)?i.nonces:[])typeof r=="string"&&r.length>0&&this.captureNonces.push({nonce:r,expiresAt:o});this.captureNonces=this.captureNonces.slice(-U)}catch{}})().finally(()=>{this.captureFetch=null})),this.captureFetch}async uploadToSpaces(e,n,i){let o;try{o=await this.fetchImpl(e,{method:"PUT",headers:{"content-type":p(i)},body:n,signal:AbortSignal.timeout(be)})}catch(r){throw C(r)}if(!o.ok){let r=(await o.text().catch(()=>"")).slice(0,_e);throw new u({status:o.status,code:"upload_failed",message:`media upload failed (HTTP ${o.status})${r?`: ${r}`:""}`})}}async completeMedia(e){let n=await this.ensureSessionId();return this.api("POST",`/sessions/${n}/media/complete`,{body:{key:e}})}async submitCheck(e,n,i={}){let o=await this.ensureSessionId(),r={input:n,forceOutcome:i.forceOutcome};return this.api("POST",`/sessions/${o}/checks/${e}`,{body:r,idempotencyKey:i.idempotencyKey,busyRetry:i.idempotencyKey!==void 0})}async uploadAndSubmit(e,n,i,o={}){let r=p(n.contentType),c=await this.presign(n.kind,r,n.blob.size);await this.uploadToSpaces(c.uploadUrl,n.blob,r);let d=await this.completeMedia(c.key),s={...i,[Ce[e]]:d.key};return this.submitCheck(e,s,o)}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,n,i={}){let o=e==="GET"||i.busyRetry===!0,r=`${this.apiOrigin}/api/v2${n}`,c={"x-session-token":this.sessionToken,"x-sekyro-sdk":ke};i.body!==void 0&&(c["content-type"]="application/json"),i.idempotencyKey!==void 0&&(c["x-idempotency-key"]=i.idempotencyKey);try{let d=w.timezone();d!==void 0&&(c["sekyro-client-timezone"]=d)}catch{}try{let d=await w.deviceHeader();d!==void 0&&(c["sekyro-client-device"]=d)}catch{}for(let d=0;;d++){let s;try{s=await this.fetchImpl(r,{method:e,headers:c,...i.body!==void 0?{body:JSON.stringify(i.body)}:{},cache:"no-store",signal:AbortSignal.timeout(this.requestTimeoutMs)})}catch(l){throw C(l)}if(s.ok){if(i.empty===!0)return;if(i.blob===!0)try{return await s.blob()}catch(m){throw C(m)}let l;try{l=await s.json()}catch{throw new u({status:s.status,code:"unknown_error",message:`response body was not valid JSON (HTTP ${s.status})`})}return Ie(l)}let a=await ve(s);if(a.code==="idempotency_in_progress"&&d<this.retryAttempts){this.retryDelayMs>0&&await K(this.retryDelayMs);continue}if(o&&a.status===503&&we.has(a.code)){o=!1,await K(L(a.retryAfterSeconds,Pe,this.random));continue}throw a}}};function C(t){if((typeof t=="object"&&t!==null?t.name:void 0)==="TimeoutError")return new u({status:0,code:"timeout",message:"request timed out"});let n=t instanceof Error?t.message:String(t);return new u({status:0,code:"network_error",message:`network request failed: ${n}`})}function Ie(t){return t!==null&&typeof t=="object"&&"success"in t&&"data"in t?t.data:t}async function ve(t){let e="unknown_error",n=`request failed (HTTP ${t.status})`,i=Number.NaN,o;try{let d=await t.json();if(d!==null&&typeof d=="object"){let s=d;typeof s.code=="string"&&s.code.length>0&&(e=s.code),typeof s.message=="string"&&s.message.length>0&&(n=s.message),typeof s.retryAfterSeconds=="number"&&(i=s.retryAfterSeconds),Array.isArray(s.details?.issues)&&(o=s.details)}}catch{}let r=t.headers.get("retry-after"),c=r===null?Math.floor(i):Number.parseInt(r,10);return new u({status:t.status,code:e,message:n,...Number.isFinite(c)&&c>=0?{retryAfterSeconds:c}:{},details:o})}function K(t){return new Promise(e=>setTimeout(e,t))}function B(t){let e=t?.portrait,n=e?.icao,i=e?.purpose==="id_document";return n==null?i?{policy:"reject",profile:"id_document"}:null:{policy:n.policy==="alert"?"alert":"reject",profile:i||n.profile==="id_document"?"id_document":"selfie"}}function q(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,SEKYRO_SDK_HEADER,icaoPolicyOf,isInAppBrowser,isKnownCode,portraitIcaoGate,stripMimeParams});
@@ -1,73 +1,8 @@
1
- import { c as IcaoGateSummary } from '../icao-gate-D-wePfoV.cjs';
2
- export { N as HostedClient, O as HostedClientOptions, Q as MediaCheckType, S as SEKYRO_SDK_HEADER, T as SubmitOptions, U as UploadMedia, V as stripMimeParams } from '../icao-gate-D-wePfoV.cjs';
3
- import { H as HostedSessionView, J as HostedIcaoPolicy, ak as PortraitIcaoInput } from '../types-DPl0hsmI.cjs';
4
- export { A as AcceptedDocumentType, aB as AttestationInput, d as CaptureContext, j as CaptureMode, aC as CaptureNoncesResult, aD as CaptureProof, g as CheckInputByType, l as CheckReason, m as CheckState, f as CheckType, e as CompleteMediaResult, C as ConsentLocale, n as ContactChannel, D as DecisionReason, aE as DocDeviceRead, aF as DocOcrInput, o as DocReason, aG as DocSide, E as EidAfterPass, p as EidAuthInput, q as EidReason, aH as EmailOtpInput, r as EmailOtpReason, aI as FaceMatchInput, F as FaceMatchReason, s as HostedAcceptedDocuments, v as HostedCaptureTuning, a as HostedConsentView, w as HostedDocumentCaptureTuning, x as HostedDocumentScanTuning, y as HostedEidView, z as HostedEmailOtpView, G as HostedFlowRef, K as HostedIntegrity, L as HostedLivePhotoTuning, O as HostedNativeCaptureTuning, Q as HostedOcrTuning, T as HostedOtpView, U as HostedPlanView, V as HostedPortraitView, W as HostedStepView, X as HostedVoiceLocale, Y as HostedVoiceView, h as IcaoCriterion, _ as IcaoReportEntry, I as IdentityConfirmDecision, $ as IdentityMethod, a0 as IdentitySummarySource, a1 as IdentitySummaryView, aJ as LivenessCaptureInput, aK as LivenessInput, a2 as LivenessReason, a3 as MatchReason, M as MediaKind, a4 as MethodChoiceView, a5 as NationalEidOption, a6 as NfcChipReason, a7 as NfcStepView, a8 as OtpChoiceView, a9 as PhoneCountryRule, aa as PhoneFormat, aL as PhoneOtpInput, ab as PhoneOtpReason, ac as PlanAttempts, ad as PlanChoiceKind, ae as PlanChoiceOption, af as PlanChoiceView, ag as PlanSectionView, ah as PlanStepView, ai as PolicyFailureReason, aM as PopulationInput, aj as PopulationReason, al as PortraitIcaoReason, aN as PresignRequest, P as PresignUploadResult, aO as RecordConsentResult, am as ResolvedCaptureMode, ar as SessionFailureReason, as as SessionOutcome, at as SessionStatus, aP as SessionStepView, aQ as SessionView, au as StepSection, aR as SubmitCheckBody, av as VerificationAssurance, aw as VerificationLevel } from '../types-DPl0hsmI.cjs';
1
+ export { H as HostedClient, a as HostedClientOptions, M as MediaCheckType, S as SEKYRO_SDK_HEADER, b as SubmitOptions, U as UploadMedia, s as stripMimeParams } from '../icao-gate-l40OU6x1.cjs';
2
+ export { H as HostedApiError, a as HostedErrorDetails, b as HostedErrorIssue, K as KNOWN_CODES, c as KnownCode, i as icaoPolicyOf, d as isKnownCode, p as portraitIcaoGate } from '../icao-policy-C7fIdRzo.cjs';
3
+ export { A as AcceptedDocumentType, a as AttestationInput, C as CaptureContext, b as CaptureMode, c as CaptureNoncesResult, d as CaptureProof, e as CheckInputByType, f as CheckReason, g as CheckState, h as CheckType, i as CompleteMediaResult, j as ConsentLocale, k as ContactChannel, D as DecisionReason, l as DocDeviceRead, m as DocOcrInput, n as DocReason, o as DocSide, E as EidAfterPass, p as EidAuthInput, q as EidReason, r as EmailOtpInput, s as EmailOtpReason, F as FaceMatchInput, t as FaceMatchReason, H as HostedAcceptedDocuments, u as HostedCaptureTuning, v as HostedConsentView, w as HostedDocumentCaptureTuning, x as HostedDocumentScanTuning, y as HostedDocumentsView, z as HostedEidView, B as HostedEmailOtpView, G as HostedFlowRef, I as HostedIcaoPolicy, J as HostedIntegrity, K as HostedLivePhotoTuning, L as HostedNativeCaptureTuning, M as HostedOcrTuning, N as HostedOtpView, O as HostedPlanView, P as HostedPortraitPendingFix, Q as HostedPortraitView, R as HostedSessionView, S as HostedStepView, T as HostedVoiceLocale, U as HostedVoiceView, V as IcaoCriterion, W as IcaoReportEntry, X as IdentityConfirmDecision, Y as IdentityMethod, Z as IdentitySummarySource, _ as IdentitySummaryView, $ as LivenessCaptureInput, a0 as LivenessInput, a1 as LivenessReason, a2 as MatchReason, a3 as MediaKind, a4 as MethodChoiceView, a5 as NationalEidOption, a6 as NfcChipReason, a7 as NfcStepView, a8 as OtpChoiceView, a9 as PhoneCountryRule, aa as PhoneFormat, ab as PhoneOtpInput, ac as PhoneOtpReason, ad as PhotoSource, ae as PhotoSourcePick, af as PlanAttempts, ag as PlanChoiceKind, ah as PlanChoiceOption, ai as PlanChoiceView, aj as PlanSectionView, ak as PlanStepView, al as PolicyFailureReason, am as PopulationInput, an as PopulationReason, ao as PortraitFix, ap as PortraitFixReviewInput, aq as PortraitIcaoInput, ar as PortraitIcaoReason, as as PortraitOutputFormat, at as PresignRequest, au as PresignUploadResult, av as RecordConsentResult, aw as ResolvedCaptureMode, ax as SessionFailureReason, ay as SessionOutcome, az as SessionStatus, aA as SessionStepView, aB as SessionView, aC as StepSection, aD as SubmitCheckBody, aE as VerificationAssurance, aF as VerificationLevel } from '../types-Dpfg2cO8.cjs';
5
4
 
6
- /**
7
- * Every error code the hosted page can receive from the session-token surface.
8
- * A closed string-literal union — switch over {@link KnownCode} with a `never`
9
- * default arm for compile-checked exhaustiveness.
10
- */
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", "id_number_locked", "document_id_number_mismatch"];
12
- /** Closed union of {@link KNOWN_CODES} — exhaustively switchable. */
13
- type KnownCode = (typeof KNOWN_CODES)[number];
14
- /** Narrow an arbitrary wire code to the known union (unknown codes stay `string`). */
15
- declare function isKnownCode(code: string): code is KnownCode;
16
- /** One machine-readable problem of an error's `details` (Sekyro flows spec §9.4). */
17
- interface HostedErrorIssue {
18
- code: string;
19
- message: string;
20
- /** The request field (`option`, `nodeId`, …). */
21
- path?: string;
22
- /** A node of the flow. */
23
- nodeId?: string;
24
- service?: string;
25
- field?: string;
26
- }
27
- /** `details` of a flow error envelope (`choice_*`, `step_not_on_path`, …): the issues, and more per code. */
28
- interface HostedErrorDetails {
29
- issues: HostedErrorIssue[];
30
- /** `override_widens_flow`: the widened fields. */
31
- fields?: string[];
32
- [key: string]: unknown;
33
- }
34
- /**
35
- * Typed transport error: EVERY failure surfaces as one of these — non-2xx
36
- * responses, rejected fetches, timeouts, and unparseable bodies alike. The
37
- * hosted page never sees a raw TypeError/DOMException from the client.
38
- *
39
- * - `code` — the public envelope's `code`, or a client-synthesized fallback
40
- * ('unknown_error' / 'upload_failed' / 'network_error' / 'timeout'). Typed
41
- * `string` because the wire may grow codes; narrow with {@link isKnownCode}
42
- * before an exhaustive switch.
43
- * - `status` — the HTTP status, or 0 when no response arrived at all
44
- * ('network_error' / 'timeout').
45
- * - `retryAfterSeconds` — parsed from the `Retry-After` header when present
46
- * (rate-limit 429s always set it).
47
- * - `details` — the envelope's machine-readable `details` when present (flow
48
- * errors: `issues[]`).
49
- */
50
- declare class HostedApiError extends Error {
51
- readonly status: number;
52
- readonly code: string;
53
- readonly retryAfterSeconds?: number;
54
- readonly details?: HostedErrorDetails;
55
- constructor(args: {
56
- status: number;
57
- code: string;
58
- message: string;
59
- retryAfterSeconds?: number;
60
- details?: HostedErrorDetails | undefined;
61
- });
62
- }
5
+ /** The page runs inside an app's WebView (WhatsApp, Instagram, Facebook, TikTok, Snapchat, LINE, LinkedIn, WeChat, an Android WebView…). */
6
+ declare function isInAppBrowser(userAgent?: string): boolean;
63
7
 
64
- /** The session's ICAO policy and profile, or `null` when the selfie is not ICAO-checked. */
65
- declare function icaoPolicyOf(view: Pick<HostedSessionView, "portrait"> | null | undefined): HostedIcaoPolicy | null;
66
- /**
67
- * The `gate` block of a `portrait_icao` body from the gate's summary: the eye
68
- * baseline, the device verdict under the server's criterion names, and the
69
- * background-uniformity numbers (telemetry).
70
- */
71
- declare function portraitIcaoGate(summary: IcaoGateSummary): NonNullable<PortraitIcaoInput["gate"]>;
72
-
73
- export { HostedApiError, type HostedErrorDetails, type HostedErrorIssue, HostedIcaoPolicy, HostedSessionView, KNOWN_CODES, type KnownCode, PortraitIcaoInput, icaoPolicyOf, isKnownCode, portraitIcaoGate };
8
+ export { isInAppBrowser };