@sekyro/web 0.1.0-rc.7 → 0.1.0-rc.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +87 -0
- package/LICENSE +25 -16
- package/README.md +3 -5
- package/THIRD-PARTY-NOTICES.txt +154 -0
- package/dist/background-monitor-A7FKJOAG.js +1 -0
- package/dist/capture-session-doc-YBE3UMJJ.js +1 -0
- package/dist/{capture-session-v3-Okq0EQHG.d.ts → capture-session-v3-CQK-G-qX.d.ts} +72 -3
- package/dist/{capture-session-v3-UQU_WjO2.d.cts → capture-session-v3-Dvob-uH2.d.cts} +72 -3
- package/dist/chunk-4RS2YIL4.js +1 -0
- package/dist/chunk-7V2M6Y2W.js +1 -0
- package/dist/chunk-7ZCZY3ZP.js +1 -0
- package/dist/chunk-A3FUGHAH.js +2 -0
- package/dist/chunk-BPE5NSQ2.js +1 -0
- package/dist/chunk-CJHMFPL6.js +1 -0
- package/dist/chunk-DFTCAWMP.js +1 -0
- package/dist/chunk-DK5YPBDQ.js +1 -0
- package/dist/chunk-DQWW4OCK.js +1 -0
- package/dist/chunk-FHJ7HO3M.js +1 -0
- package/dist/chunk-G6LKLN4U.js +1 -0
- package/dist/chunk-GI3UFGRQ.js +1 -0
- package/dist/{chunk-IYUOYINS.js → chunk-LQ7C44JG.js} +1 -1
- package/dist/chunk-M43ET4NJ.js +1 -0
- package/dist/chunk-MXWLCDFX.js +1 -0
- package/dist/chunk-MY6EXEL2.js +1 -0
- package/dist/chunk-O5WKNZ2C.js +1 -0
- package/dist/chunk-OKWG3PVH.js +1 -0
- package/dist/chunk-POIQGEZM.js +1 -0
- package/dist/chunk-RI3E7GBN.js +1 -0
- package/dist/chunk-RNRFHUJA.js +1 -0
- package/dist/chunk-RVHAKRAI.js +1 -0
- package/dist/chunk-SMKCBUJL.js +1 -0
- package/dist/chunk-TDLIXFDT.js +1 -0
- package/dist/chunk-XLN5OT25.js +1 -0
- package/dist/chunk-YDQBVWXG.js +1 -0
- package/dist/chunk-YPG7CB4O.js +1 -0
- package/dist/client/index.cjs +1 -1
- package/dist/client/index.d.cts +13 -3
- package/dist/client/index.d.ts +13 -3
- package/dist/client/index.js +1 -1
- package/dist/core/index.cjs +1 -1
- package/dist/core/index.d.cts +3 -3
- package/dist/core/index.d.ts +3 -3
- package/dist/core/index.js +1 -1
- package/dist/core/ocr/worker.bundle.js +42 -0
- package/dist/core/ocr/worker.cjs +42 -0
- package/dist/core/ocr/worker.d.cts +84 -0
- package/dist/core/ocr/worker.d.ts +84 -0
- package/dist/core/ocr/worker.js +41 -0
- package/dist/core/v3/detect-worker.cjs +1 -1
- package/dist/core/v3/detect-worker.d.cts +1 -1
- package/dist/core/v3/detect-worker.d.ts +1 -1
- package/dist/core/v3/detect-worker.js +1 -1
- package/dist/create-document-capture-T4APHJMY.js +1 -0
- package/dist/create-portrait-capture-B57GE5FU.js +1 -0
- package/dist/create-verification-C0AVIcVW.d.ts +2787 -0
- package/dist/create-verification-DoFpgzok.d.cts +2787 -0
- package/dist/{detect-worker-CKXHlXx9.d.cts → detect-worker-DclNxkZT.d.cts} +6 -0
- package/dist/{detect-worker-CKXHlXx9.d.ts → detect-worker-DclNxkZT.d.ts} +6 -0
- package/dist/detector-scanic-YCDNLCGV.js +1 -0
- package/dist/icao-gate-D8qm1O2t.d.cts +1655 -0
- package/dist/icao-gate-D8qm1O2t.d.ts +1655 -0
- package/dist/icao-gate-PWBMKRGC.js +1 -0
- package/dist/icao-tuning-4GGVX6B4.js +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +52 -6
- package/dist/index.d.ts +52 -6
- package/dist/index.js +1 -1
- package/dist/internal/index.cjs +1 -1
- package/dist/internal/index.d.cts +345 -308
- package/dist/internal/index.d.ts +345 -308
- package/dist/internal/index.js +1 -1
- package/dist/keyframe-rank-YAJLYJYF.js +1 -0
- package/dist/landmarker-KB7LVXAU.js +1 -0
- package/dist/mrz-band-VYHOTDHY.js +1 -0
- package/dist/plan-runner-UBK4B4CG.js +1 -0
- package/dist/segmenter-USLNBX65.js +1 -0
- package/dist/turnstile-FATNZ4AG.js +1 -0
- package/package.json +22 -4
- package/sbom.cdx.json +8 -8
- package/dist/chunk-B45J4KC3.js +0 -1
- package/dist/chunk-BMA36W2W.js +0 -1
- package/dist/chunk-P7ECRN47.js +0 -1
- package/dist/chunk-YOB4ZTYN.js +0 -1
- package/dist/chunk-YQBK6OIM.js +0 -1
- package/dist/create-verification-C2JhOO6Y.d.cts +0 -533
- package/dist/create-verification-CGazwtAh.d.ts +0 -533
- package/dist/detector-scanic-VQFFXKTL.js +0 -1
- package/dist/hosted-client-kBeq-mnJ.d.cts +0 -602
- package/dist/hosted-client-kBeq-mnJ.d.ts +0 -602
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{b as jt}from"./chunk-SMKCBUJL.js";import{a as et,b as Zt,c as Jt,e as ht,f as $t}from"./chunk-MXWLCDFX.js";import{d as Wt,h as Xt,k as Yt}from"./chunk-G6LKLN4U.js";import{b as Kt,c as Vt}from"./chunk-TDLIXFDT.js";import{b as Qt,c as Bt}from"./chunk-POIQGEZM.js";import{d as zt}from"./chunk-FHJ7HO3M.js";import{b as ut,c as Ut,d as j,e as Ht}from"./chunk-FPXL63KZ.js";import{b as Nt}from"./chunk-LQ7C44JG.js";var it=Object.freeze({sensing:{key:"sensing",reticle:"searching",minDurationMs:900},too_far:{key:"too_far",reticle:"coaching",minDurationMs:1400},too_close:{key:"too_close",reticle:"coaching",minDurationMs:1400},edge_clipped:{key:"edge_clipped",reticle:"coaching",minDurationMs:1400},wrong_shape:{key:"wrong_shape",reticle:"coaching",minDurationMs:1400},tilted:{key:"tilted",reticle:"coaching",minDurationMs:1400},too_dark:{key:"too_dark",reticle:"coaching",minDurationMs:1400},too_bright:{key:"too_bright",reticle:"coaching",minDurationMs:1400},blurry:{key:"blurry",reticle:"coaching",minDurationMs:1400},focus_far:{key:"focus_far",reticle:"coaching",minDurationMs:1600},glare:{key:"glare",reticle:"coaching",minDurationMs:1400},hold_still:{key:"hold_still",reticle:"locking",minDurationMs:900},processing:{key:"processing",reticle:"processing",minDurationMs:800},side_captured:{key:"side_captured",reticle:"flip",minDurationMs:2600},captured:{key:"captured",reticle:"done",minDurationMs:800}});function qt(e){return e.framing==="no_document"?"sensing":e.framing==="too_far"?"too_far":e.framing==="too_close"?"too_close":e.framing==="edge_clipped"?"edge_clipped":e.framing==="wrong_shape"?"wrong_shape":e.framing==="tilted"?"tilted":e.lighting==="too_dark"?"too_dark":e.lighting==="too_bright"?"too_bright":e.glare==="glare"?"glare":e.blur==="blurry"?"blurry":"hold_still"}var nt=class{constructor(t=2600,n=.35){this.windowMs=t;this.decayPerSecond=n;this.votes=[];this.current=it.sensing;this.currentSinceMs=null}reset(){this.votes=[],this.current=it.sensing,this.currentSinceMs=null}force(t,n){return this.votes=[],this.current=it[t],this.currentSinceMs=n,this.current}tick(t,n){if(this.currentSinceMs===null&&(this.currentSinceMs=n),this.votes.push({key:t,atMs:n}),this.votes=this.votes.filter(r=>n-r.atMs<=this.windowMs),n-this.currentSinceMs<this.current.minDurationMs)return this.current;let i=new Map;for(let r of this.votes){let c=(n-r.atMs)/1e3,a=this.decayPerSecond**c;i.set(r.key,(i.get(r.key)??0)+a)}let o=this.current.key,s=-1;for(let[r,c]of i)c>s&&(s=c,o=r);return o!==this.current.key&&(this.current=it[o],this.currentSinceMs=n),this.current}};var Qe=Object.freeze({MAX_AREA_FRAC:.92,TILT_MAX_SIDE_RATIO:1.3,GLARE_MAX_SPECULAR_FRAC:.025});function ee(e){let{data:t,width:n,height:i}=e,o=n*i;if(o===0)return 0;let s=0;for(let r=0;r<o;r++){let c=r*4;.299*(t[c]??0)+.587*(t[c+1]??0)+.114*(t[c+2]??0)>=252&&s++}return s/o}function Be(e){let t=(a,l)=>Math.hypot(l.x-a.x,l.y-a.y),n=t(e.topLeft,e.topRight),i=t(e.bottomLeft,e.bottomRight),o=t(e.topLeft,e.bottomLeft),s=t(e.topRight,e.bottomRight),r=Math.max(n,i)/Math.max(1e-6,Math.min(n,i)),c=Math.max(o,s)/Math.max(1e-6,Math.min(o,s));return Math.max(r,c)}function ie(e){let t={...Zt,...e.thresholds},n=Qe,{quad:i,frameWidth:o,frameHeight:s,measures:r}=e,c=e.format==="ID-3",a="ok";if(i===null)a="no_document";else if(c){let m=ht(i),h=o>0?m.width/o:0,f=m.height>0?m.width/m.height:0;h<t.ID3_BAND_MIN_WIDTH_FRAC?a="too_far":te(i,o,s,t.EDGE_CLIP_MARGIN_PX)?a="edge_clipped":(f<t.ID3_BAND_ASPECT_MIN||f>t.ID3_BAND_ASPECT_MAX)&&(a="wrong_shape")}else{let m=Jt(i,o,s),h=ht(i),f=Math.max(h.width,h.height)/Math.max(1e-6,Math.min(h.width,h.height));m<t.MIN_AREA_FRAC?a="too_far":m>n.MAX_AREA_FRAC?a="too_close":te(i,o,s,t.EDGE_CLIP_MARGIN_PX)?a="edge_clipped":Vt(e.format,f)?Be(i)>n.TILT_MAX_SIDE_RATIO&&(a="tilted"):a="wrong_shape"}let l=r.exposure>=t.GUIDE_EXPOSURE?"ok":r.meanLuma<(ut[0]+ut[1])/2?"too_dark":"too_bright",u=r.sharpness>=t.GUIDE_SHARPNESS?"ok":"blurry",d=r.specularFraction>=n.GLARE_MAX_SPECULAR_FRAC?"glare":"ok";return{framing:a,lighting:l,blur:u,glare:d,acceptable:a==="ok"&&l==="ok"&&u==="ok"&&d==="ok"}}function te(e,t,n,i){return[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft].some(s=>s.x<=i||s.y<=i||s.x>=t-i||s.y>=n-i)}var oe=Object.freeze({width:1920,height:1080}),Ue=Object.freeze({width:3840,height:2160}),ne=4096,He=2560,se=640,ot=.15,Y=Object.freeze({side:.2,above:.9,below:.3});function L(e){let t=[e.topLeft.x,e.topRight.x,e.bottomRight.x,e.bottomLeft.x],n=[e.topLeft.y,e.topRight.y,e.bottomRight.y,e.bottomLeft.y],i=Math.min(...t),o=Math.min(...n);return{x:i,y:o,width:Math.max(...t)-i,height:Math.max(...n)-o}}function re(e,t){let n=Math.max(0,Math.floor(e.x)),i=Math.max(0,Math.floor(e.y)),o=Math.min(t.width,Math.ceil(e.x+e.width)),s=Math.min(t.height,Math.ceil(e.y+e.height));return o-n<16||s-i<16?null:{x:n,y:i,width:o-n,height:s-i}}function Ke(e,t,n){if(e===null||t.width<=0||t.height<=0)return null;let i=L(e);if(i.width<=0||i.height<=0)return null;let o=n==="ID-3"?{x:i.x-i.width*Y.side,y:i.y-i.width*Y.above,width:i.width*(1+2*Y.side),height:i.height+i.width*(Y.above+Y.below)}:{x:i.x-i.width*ot,y:i.y-i.height*ot,width:i.width*(1+2*ot),height:i.height*(1+2*ot)};return re(o,t)}function dt(e,t,n){let i=Math.max(e,t);return i>0?Math.min(1,n/i):1}function mt(e,t,n,i,o=He){let s=t.width>0?n.width/t.width:1,r=t.height>0?n.height/t.height:1,c=e===null?null:{topLeft:{x:e.topLeft.x*s,y:e.topLeft.y*r},topRight:{x:e.topRight.x*s,y:e.topRight.y*r},bottomRight:{x:e.bottomRight.x*s,y:e.bottomRight.y*r},bottomLeft:{x:e.bottomLeft.x*s,y:e.bottomLeft.y*r}},a=Ke(c,n,i)??{x:0,y:0,width:n.width,height:n.height},l=dt(a.width,a.height,o),u=Math.max(1,Math.round(a.width*l)),d=Math.max(1,Math.round(a.height*l)),m=null;if(c!==null){let h=L(c);m=re({x:(h.x-a.x)*l,y:(h.y-a.y)*l,width:h.width*l,height:h.height*l},{width:u,height:d})}return{crop:a,width:u,height:d,docRegion:m}}function ae(e,t,n,i=Ue){if(n==="LOW")return null;let o=e?.width?.max,s=e?.height?.max;if(typeof o!="number"||typeof s!="number"||o<=0||s<=0)return null;let r=Math.max(o,s),c=Math.min(o,s),a=Math.min(r,Math.max(i.width,i.height)),l=Math.min(c,Math.min(i.width,i.height));return a<=Math.max(t.width,t.height)?null:{width:{ideal:a},height:{ideal:l}}}function ce(e){let t={},n=e?.imageWidth,i=e?.imageHeight;if(typeof n?.max=="number"&&n.max>0){let o=typeof i?.max=="number"&&i.max>0?n.max/i.max:1.3333333333333333,s=o>=1?ne:ne*o,r=Math.min(n.max,Math.floor(s)),c=typeof n.step=="number"&&n.step>0?n.step:1,a=typeof n.min=="number"?n.min:0;r=Math.max(a,a+Math.floor((r-a)/c)*c),t.imageWidth=r}return e?.fillLightMode?.includes("off")===!0&&(t.fillLightMode="off"),t}function le(e,t){if(e.width<=0||e.height<=0||t.width<=0||t.height<=0)return!1;let n=e.width>e.height,i=t.width>t.height;return n!==i&&e.width!==e.height&&t.width!==t.height?!1:Math.max(e.width,e.height)>=1.2*Math.max(t.width,t.height)}function ue(e,t,n,i){if(n===null)return!1;let o=L(e),s=L(n);if(t.width<=0||i.width<=0)return!1;let r=o.width/t.width,c=s.width/i.width;return c>0&&r>=.6*c&&r<=1.25*c}var he=3500,Ve=.92;function me(){let e=globalThis.ImageCapture;return typeof e=="function"?e:null}function We(e){return/AppleWebKit\//.test(e)&&!/(Chrome|Chromium|Edg|OPR)\//.test(e)}function fe(e,t=typeof navigator>"u"?"":navigator.userAgent){return me()!==null&&!We(t)&&e!=null&&e.kind==="video"&&e.readyState==="live"}function de(e,t){return new Promise((n,i)=>{let o=setTimeout(()=>i(new Error("takePhoto timed out")),t);e.then(s=>{clearTimeout(o),n(s)},s=>{clearTimeout(o),i(s)})})}function ft(e,t){let n=document.createElement("canvas");return n.width=e,n.height=t,n}function Xe(e,t){return new Promise((n,i)=>{e.toBlob(o=>o?n(o):i(new Error("toBlob failed")),"image/jpeg",t)})}async function pe(e,t,n,i,o){let s=ft(n,i),r=ft(1,1);try{let c=s.getContext("2d");if(c===null)throw new Error("2d context unavailable");c.imageSmoothingQuality="high",c.drawImage(e,t.x,t.y,t.width,t.height,0,0,n,i);let a=await Xe(s,Ve),l=o===null?null:Wt({topLeft:{x:o.x,y:o.y},topRight:{x:o.x+o.width,y:o.y},bottomRight:{x:o.x+o.width,y:o.y+o.height},bottomLeft:{x:o.x,y:o.y+o.height}},{width:n,height:i},{width:n,height:i}),u=Xt(s,l),d=dt(n,i,se);return r.width=Math.max(1,Math.round(n*d)),r.height=Math.max(1,Math.round(i*d)),r.getContext("2d")?.drawImage(s,0,0,r.width,r.height),{blob:a,previewDataUrl:r.toDataURL("image/jpeg",.85),sharpness:u}}finally{s.width=0,s.height=0,r.width=0,r.height=0}}function je(e,t){let n=Math.min(1,t/e.width),i=ft(Math.max(1,Math.round(e.width*n)),Math.max(1,Math.round(e.height*n)));try{let o=i.getContext("2d",{willReadFrequently:!0});return o===null?null:(o.imageSmoothingQuality="high",o.drawImage(e,0,0,i.width,i.height),o.getImageData(0,0,i.width,i.height))}finally{i.width=0,i.height=0}}async function ge(e,t,n,i){let o={width:Math.max(1,e.videoWidth),height:Math.max(1,e.videoHeight)},s=mt(t,n,o,i);return{...await pe(e,s.crop,s.width,s.height,s.docRegion),docRegion:s.docRegion,source:"video",width:s.width,height:s.height}}async function be(e,t,n,i,o){let s=me();if(s===null)return null;let r=null;try{let c=new s(o.track),a=await de(c.getPhotoCapabilities?.()??Promise.resolve({}),he).catch(()=>({})),l=await de(c.takePhoto(ce(a)),he);r=await createImageBitmap(l);let u={width:e.videoWidth,height:e.videoHeight};if(!le(r,u))return null;let d=je(r,o.detectWidth),m=null;d!==null&&t!==null&&(m=await o.detect(d).catch(()=>null));let h=d??{width:r.width,height:r.height};m!==null&&!ue(m,h,t,n)&&(m=null);let f=mt(m,h,r,i);return{...await pe(r,f.crop,f.width,f.height,f.docRegion),docRegion:f.docRegion,source:"photo",width:f.width,height:f.height}}catch{return null}finally{r?.close()}}var st=Object.freeze({width:3840,height:2160,lensSelection:!0,continuousFocus:!0,refocusBeforePhotoMs:350,zoomMax:2,zoomNoFocusInfo:1.5,zoomMinSourcePx:2160,fillDistanceM:Object.freeze({id1:.11,id3:.15}),focusMarginFrac:.2,stillSharpnessMin:.16,stillRefusalsMax:2,focusFarFillFrac:.45,noDocFarHintMs:1500,zoomFallbackMs:8e3}),S=(e,t,n)=>typeof e=="number"&&Number.isFinite(e)&&e>=t&&e<=n?e:void 0;function ki(e){let t=st,n=e!==null&&typeof e=="object"?e:{},i=n.fillDistanceM!==null&&typeof n.fillDistanceM=="object"?n.fillDistanceM:{},o=(s,r)=>typeof s=="boolean"?s:r;return{width:S(n.width,640,7680)??t.width,height:S(n.height,480,4320)??t.height,lensSelection:o(n.lensSelection,t.lensSelection),continuousFocus:o(n.continuousFocus,t.continuousFocus),refocusBeforePhotoMs:S(n.refocusBeforePhotoMs,0,2e3)??t.refocusBeforePhotoMs,zoomMax:S(n.zoomMax,1,5)??t.zoomMax,zoomNoFocusInfo:S(n.zoomNoFocusInfo,1,5)??t.zoomNoFocusInfo,zoomMinSourcePx:S(n.zoomMinSourcePx,0,8e3)??t.zoomMinSourcePx,fillDistanceM:{id1:S(i.id1,.03,1)??t.fillDistanceM.id1,id3:S(i.id3,.03,1)??t.fillDistanceM.id3},focusMarginFrac:S(n.focusMarginFrac,0,2)??t.focusMarginFrac,stillSharpnessMin:S(n.stillSharpnessMin,0,10)??t.stillSharpnessMin,stillRefusalsMax:S(n.stillRefusalsMax,0,10)??t.stillRefusalsMax,focusFarFillFrac:S(n.focusFarFillFrac,0,1)??t.focusFarFillFrac,noDocFarHintMs:S(n.noDocFarHintMs,0,6e4)??t.noDocFarHintMs,zoomFallbackMs:S(n.zoomFallbackMs,0,12e4)??t.zoomFallbackMs}}function Ye(e){let t=e.toLowerCase();return t===""?"unknown":/front|facing front|user|selfie|face ?time/.test(t)?"front":/ultra|0\.5x|wide angle/.test(t)?"ultra":/tele|zoom|periscope|[2-9]x/.test(t)?"tele":/depth|tof|infrared|\bir\b|truedepth|lidar|macro|monochrome|mono\b/.test(t)?"depth":/dual|triple/.test(t)?"virtual":/back|rear|environment|facing back|arrière|خلفية/.test(t)?"main":"unknown"}function Ze(e){let t=/camera2?\s*(\d+)/i.exec(e);return t?Number(t[1]):Number.POSITIVE_INFINITY}function Je(e){let t={main:0,virtual:1,ultra:9,tele:9,depth:9,front:9,unknown:9};return e.filter(n=>(n.kind===void 0||n.kind==="videoinput")&&n.deviceId!=="").map((n,i)=>({id:n.deviceId,kind:Ye(n.label),index:Ze(n.label),i})).filter(n=>t[n.kind]<9).sort((n,i)=>t[n.kind]-t[i.kind]||n.index-i.index||n.i-i.i).map(n=>n.id)}var pt="sekyro.doc.camera";function $e(){try{let e=globalThis.localStorage?.getItem(pt);return typeof e=="string"&&e!==""?e:null}catch{return null}}function ye(e){try{e===null?globalThis.localStorage?.removeItem(pt):globalThis.localStorage?.setItem(pt,e)}catch{}}var rt=(e,t)=>Array.isArray(e?.focusMode)&&e.focusMode.includes(t);function bt(e,t,n){if(!rt(e,"single-shot"))return null;let i=o=>Math.min(1,Math.max(0,Number.isFinite(o)?o:.5));return{focusMode:"single-shot",pointsOfInterest:[{x:i(t),y:i(n)}]}}function xi(e,t,n,i){if(!Number.isFinite(e)||!Number.isFinite(t)||n.width<=0||n.height<=0||i.width<=0||i.height<=0)return null;let o=Math.max(n.width/i.width,n.height/i.height),s=i.width*o,r=i.height*o,c=(e-n.left+(s-n.width)/2)/s,a=(t-n.top+(r-n.height)/2)/r;return{x:Math.min(1,Math.max(0,c)),y:Math.min(1,Math.max(0,a))}}function ke(e,t,n,i=st){let o=e?.zoom?.min,s=e?.zoom?.max;if(typeof s!="number"||s<=1)return 1;let r=n==="ID-3"?i.fillDistanceM.id3:i.fillDistanceM.id1,c=e?.focusDistance?.min,a;if(typeof c=="number"&&c>0&&c<1){if(a=c*(1+i.focusMarginFrac)/r,a<=1.05)return 1}else{if(Math.min(t.width,t.height)<i.zoomMinSourcePx)return 1;a=i.zoomNoFocusInfo}let l=Math.min(a,i.zoomMax,s);typeof o=="number"&&(l=Math.max(l,o));let u=e?.zoom?.step;return typeof u=="number"&&u>0&&(l=Math.round(l/u)*u),l>1.01?Number(l.toFixed(2)):1}function gt(e){try{return e.getVideoTracks?.()[0]}catch{return}}function Me(e){if(e!==null)for(let t of e.getTracks())t.stop()}function qe(e){try{let t=gt(e)?.getCapabilities?.();return!Array.isArray(t?.focusMode)||t.focusMode.includes("continuous")}catch{return!0}}var ti=3;async function xe(e){let t=s=>({audio:!1,video:{...s,width:{ideal:e.base.width},height:{ideal:e.base.height}}}),n=s=>e.getUserMedia(t({deviceId:{exact:s}})),i=()=>e.getUserMedia(t({facingMode:{ideal:"environment"}}));if(e.lensSelection){let s=$e();if(s!==null)try{return{stream:await n(s),lens:"stored"}}catch{ye(null)}}let o=await i();if(!e.lensSelection||e.enumerateDevices===void 0)return{stream:o,lens:"default"};try{let s=Je(await e.enumerateDevices()).slice(0,ti);if(s.length===0)return{stream:o,lens:"default"};let r=null;for(let c of s){let a=o!==null?gt(o)?.getSettings?.().deviceId:void 0;if(o===null||a!==c){Me(o),o=null;try{o=await n(c)}catch{continue}}if(r??(r=c),qe(o))return ye(c),{stream:o,lens:"selected"}}if(o!==null&&r!==null&>(o)?.getSettings?.().deviceId===r)return{stream:o,lens:"selected"};if(Me(o),o=null,r!==null)try{return{stream:await n(r),lens:"selected"}}catch{}return{stream:await i(),lens:"default"}}catch{return{stream:o??await i(),lens:"default"}}}var Z=Object.freeze({brightness:0,glare:0,cardGlare:0,sharpness:0,fill:0,shape:0,content:0,offsetX:0,offsetY:0,edgeConfidence:0,box:null}),I=e=>Math.min(1,Math.max(0,e));function we(e,t,n,i=.06){let o=Math.max(e.width/n,e.height),s=o*n,r=(e.width-s)/2,c=(e.height-o)/2,a=I((t.x-t.width*i-r)/s),l=I((t.y-t.height*i-c)/o),u=I((t.x+t.width*(1+i)-r)/s),d=I((t.y+t.height*(1+i)-c)/o);return{x:a,y:l,width:u-a,height:d-l}}function ve(e,t,n={}){let i=n.edgePeakFrac??0,{width:o,height:s,data:r}=e;if(o<=0||s<=0)return Z;let c=I(t.x),a=I(t.y),l={x:c,y:a,width:Math.max(0,I(t.x+t.width)-c),height:Math.max(0,I(t.y+t.height)-a)};if(l.width<=0||l.height<=0)return Z;let u=l.x*o,d=l.y*s,m=(l.x+l.width)*o,h=(l.y+l.height)*s,f=(m-u)*.15,g=(h-d)*.15,y=(p,b,T)=>Math.min(T,Math.max(b,p)),x=y(Math.floor(u-f),0,o-1),w=y(Math.floor(d-g),0,s-1),E=y(Math.ceil(m+f),x+1,o),v=y(Math.ceil(h+g),w+1,s),D=Math.max(1,Math.ceil(Math.max(E-x,v-w)/320)),M=Math.floor((E-x+D-1)/D),_=Math.floor((v-w+D-1)/D);if(M<3||_<3)return Z;let k=new Int32Array(M*_);for(let p=0;p<_;p++){let b=w+p*D;for(let T=0;T<M;T++){let C=(b*o+x+T*D)*4;k[p*M+T]=(r[C]??0)*77+(r[C+1]??0)*150+(r[C+2]??0)*29>>8}}let F=(p,b)=>(p-b-.5)/D,R=F(u,x),A=F(m,x),B=F(d,w),U=F(h,w),Mt=(m-u)/D,kt=(h-d)/D,xt=y(Math.ceil(R),0,M-1),Ce=y(Math.floor(A),xt,M-1),Dt=y(Math.ceil(B),0,_-1),Fe=y(Math.floor(U),Dt,_-1),wt=0,vt=0,H=0,St=0,_t=0,K=0;for(let p=Dt;p<=Fe;p++)for(let b=xt;b<=Ce;b++){let T=k[p*M+b];if(wt+=T,T>=248&&vt++,H++,b>=1&&b<M-1&&p>=1&&p<_-1){let C=k[p*M+b-1]+k[p*M+b+1]+k[(p-1)*M+b]+k[(p+1)*M+b]-4*T;St+=C,_t+=C*C,K++}}let Ae=H>0?wt/H:0,Rt=H>0?vt/H:0,Tt=K>0?St/K:0,Le=K>0?Math.max(0,_t/K-Tt*Tt):0,V=new Float64Array(M),W=new Float64Array(_);for(let p=0;p<_;p++)for(let b=1;b<M-1;b++)V[b]=V[b]+Math.abs(k[p*M+b+1]-k[p*M+b-1]);for(let p=1;p<_-1;p++)for(let b=0;b<M;b++)W[p]=W[p]+Math.abs(k[(p+1)*M+b]-k[(p-1)*M+b]);let O=at(V,!0,R,i),P=at(V,!1,A,i),G=at(W,!0,B,i),z=at(W,!1,U,i),Ct=(P.position-O.position)/Mt,Ft=(z.position-G.position)/kt,Ie=Ft>0?Ct/Ft:0,Ee=((O.position+P.position)/2-(R+A)/2)/Mt,Oe=((G.position+z.position)/2-(B+U)/2)/kt,At=De(V),Lt=De(W),Pe=At<=0||Lt<=0?0:Math.min(Math.min(O.value,P.value)/At,Math.min(G.value,z.value)/Lt),q=(p,b)=>b+(p+.5)*D,It=Rt,Et=0;{let p=(P.position-O.position)*.06,b=(z.position-G.position)*.06,T=y(Math.ceil(O.position+p),0,M-1),C=y(Math.floor(P.position-p),0,M-1),Ge=y(Math.ceil(G.position+b),0,_-1),Ot=y(Math.floor(z.position-b),0,_-1),Pt=0,tt=0,Gt=0;for(let N=Ge;N<=Ot;N++)for(let Q=T;Q<=C;Q++){tt++;let X=k[N*M+Q];X>=248&&Pt++;let ze=Q+2<=C?k[N*M+Q+2]:X,Ne=N+2<=Ot?k[(N+2)*M+Q]:X;(Math.abs(ze-X)>=24||Math.abs(Ne-X)>=24)&&Gt++}tt>=16&&(It=Pt/tt,Et=Gt/tt)}return{brightness:Ae,glare:Rt,cardGlare:It,sharpness:Le,fill:Ct,shape:Ie,content:Et,offsetX:Ee,offsetY:Oe,edgeConfidence:Pe,box:{left:q(O.position,x),right:q(P.position,x),top:q(G.position,w),bottom:q(z.position,w)}}}function at(e,t,n,i){let o=e.length,s=Math.max(1,Math.floor(o*.45)),r=t?1:Math.max(1,o-1-s),c=t?Math.min(o-2,s):o-2,a=r;for(let h=r;h<=c;h++)e[h]>e[a]&&(a=h);if(i>0&&i<1){let h=e[a]*i,f=a,g=Math.abs(a-n);for(let y=r;y<=c;y++){let x=e[y];if(x<h||x<(e[y-1]??0)||x<(e[y+1]??0))continue;let w=Math.abs(y-n);w<g&&(f=y,g=w)}a=f}let l=a>0?e[a-1]:0,u=e[a],d=a<o-1?e[a+1]:0,m=l+u+d;return{position:m>0?a+(d-l)/m:a,value:u}}function De(e){if(e.length<3)return 0;let t=0;for(let n=1;n<e.length-1;n++)t+=e[n];return t/(e.length-2)}function Se(e){let t=e.box;return t===null||t.right-t.left<4||t.bottom-t.top<4?null:{topLeft:{x:t.left,y:t.top},topRight:{x:t.right,y:t.top},bottomRight:{x:t.right,y:t.bottom},bottomLeft:{x:t.left,y:t.bottom}}}var J=Object.freeze({fillMin:.82,fillMax:1.06,offsetMax:.06,glareMax:.025,sharpnessMin:180,edgeConfidenceMin:1.6,darkBrightness:70,lockMs:450,steadyMs:900,steadyFillMin:.45,steadyFillMax:1.3,steadyFillDelta:.06,steadyOffsetDelta:.04,steadyRefMs:100,edgePeakFrac:.4,shapeTolerance:.2,contentMin:.1});function wi(e){let t=e!==null&&typeof e=="object"?e:{},n={...J};for(let i of Object.keys(J)){let o=t[i];typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=1e6&&(n[i]=o)}return n}var ct=class{constructor(t=J){this.t=t;this.goodSince=null;this.steadySince=null;this.last=null}reset(){this.goodSince=null,this.steadySince=null,this.last=null}tick(t,n){let i=this.t,o=i.shapeTolerance<=0||Math.abs(t.shape-1)<=i.shapeTolerance,s=t.edgeConfidence>=i.edgeConfidenceMin&&o&&t.content>=i.contentMin,r=t.fill>=i.fillMin&&t.fill<=i.fillMax,c=Math.abs(t.offsetX)<=i.offsetMax&&Math.abs(t.offsetY)<=i.offsetMax,a=t.cardGlare<=i.glareMax,l=t.sharpness>=i.sharpnessMin,u=this.last;this.last={fill:t.fill,offsetX:t.offsetX,offsetY:t.offsetY,at:n};let d=u!==null&&i.steadyRefMs>0?Math.min(3,Math.max(1,(n-u.at)/i.steadyRefMs)):1,m=s&&a&&l&&t.fill>=i.steadyFillMin&&t.fill<=i.steadyFillMax&&u!==null&&Math.abs(t.fill-u.fill)<=i.steadyFillDelta*d&&Math.abs(t.offsetX-u.offsetX)<=i.steadyOffsetDelta*d&&Math.abs(t.offsetY-u.offsetY)<=i.steadyOffsetDelta*d,h=s&&r&&c&&a&&l,f;if(s?a?t.fill<i.fillMin?f="too_small":t.fill>i.fillMax?f="too_big":l?c?f="locking":f="off_center":f="blurry":f="glare":f="no_card",h){if(m&&(this.steadySince??(this.steadySince=n)),this.goodSince??(this.goodSince=n),n-this.goodSince>=i.lockMs)return{detected:s,ready:!0,via:"good",blocker:"locking"};let g=this.steadySince!==null&&n-this.steadySince>=i.steadyMs;return{detected:s,ready:g,via:g?"steady":null,blocker:"locking"}}if(this.goodSince=null,m){this.steadySince??(this.steadySince=n);let g=n-this.steadySince>=i.steadyMs;return{detected:s,ready:g,via:g?"steady":null,blocker:g?"locking":"steadying"}}return this.steadySince=null,{detected:s,ready:!1,via:null,blocker:f}}};var $=null;async function ei(e){return $===null&&($=(await import("./detector-scanic-YCDNLCGV.js")).detectQuad),$(e)}async function ii(e){let t=jt(e);return t===null?null:{topLeft:{x:t.x,y:t.y},topRight:{x:t.x+t.width,y:t.y},bottomRight:{x:t.x+t.width,y:t.y+t.height},bottomLeft:{x:t.x,y:t.y+t.height}}}function Ni(){$===null&&import("./detector-scanic-YCDNLCGV.js").then(e=>{$=e.detectQuad}).catch(()=>{})}var ni=Object.freeze({LOW:3,MID:5,HIGH:6}),yt=Object.freeze({manualShutterMs:6e3,detectedNoLockMs:1950});function Qi(e){let t=e!==null&&typeof e=="object"?e:{},n=(i,o,s)=>typeof i=="number"&&Number.isFinite(i)&&i>=o&&i<=s?i:void 0;return{manualShutterMs:n(t.manualShutterMs,1e3,6e4)??yt.manualShutterMs,detectedNoLockMs:n(t.steadyMs,300,3e4)!==void 0?t.steadyMs+(n(t.lockMs,0,1e4)??450):yt.detectedNoLockMs}}var _e=class e{constructor(t){this.torchOn=!1;this.stillRefusals=0;this.zoom=1;this.positioningSince=null;this.detectedSince=null;this.lastSeenAt=null;this.lastGuideQuad=null;this.lastOcrReady=null;this.shutterOffered=!1;this.stats=e.freshStats();this.handlers=new Map;this.stream=null;this.timer=null;this.state="idle";this.lastGuidance=null;this.attempt=0;this.capturing=!1;this.feedback=new nt;this.lastFeedbackKey=null;this.lastQuad=null;this.lastDetect=null;this.opts=t,this.gate=new $t(t.format??"ID-1",t.thresholds);let n=t.deviceClass??Bt(Qt());this.deviceClass=n,this.camera=t.camera??st,this.shutterTuning=t.shutter??yt,this.guideTuning=t.guideLock??J,this.guideLock=new ct(this.guideTuning),this.cadenceMs=1e3/ni[n]}on(t,n){let i=this.handlers.get(t);return i||(i=new Set,this.handlers.set(t,i)),i.add(n),()=>i?.delete(n)}emit(t,n){for(let i of[...this.handlers.get(t)??[]])i(n)}async start(){let t=++this.attempt;this.gate.reset(),this.resetSide(),this.feedback.reset(),this.lastFeedbackKey=null,this.lastGuidance=null,this.capturing=!1,this.setState("preflight");try{let n=this.opts.getUserMedia??(s=>navigator.mediaDevices.getUserMedia(s));this.setState("acquiring");let i=this.opts.enumerateDevices??(this.opts.getUserMedia===void 0&&typeof navigator<"u"&&navigator.mediaDevices?.enumerateDevices?()=>navigator.mediaDevices.enumerateDevices():void 0),o=await xe({getUserMedia:n,...i!==void 0?{enumerateDevices:i}:{},lensSelection:this.camera.lensSelection,base:oe});if(this.stream=o.stream,Nt(this.stream),t!==this.attempt){for(let s of this.stream.getTracks())s.stop();return}if(this.opts.upgradeResolution!==!1&&await this.upgradeResolution(),t!==this.attempt||(await this.applyFocusAndZoom(),t!==this.attempt))return;this.opts.video.srcObject=this.stream,await this.opts.video.play().catch(()=>{}),this.setState("positioning"),this.scheduleTick(t)}catch(n){let i=zt(n);this.setState("error"),this.emit("error",{kind:i,retryable:!0})}}rearm(t){t!==void 0&&(this.opts.side=t),this.gate.reset(),this.resetSide(),this.feedback.reset(),this.lastFeedbackKey=null,this.lastGuidance=null,this.capturing=!1,this.stillRefusals=0,this.state==="captured"&&(this.setState("positioning"),this.scheduleTick(this.attempt))}async captureNow(){if(this.state!=="positioning"||this.capturing)return;let t=this.opts.video,n=this.lastDetect?.width??Math.max(1,t.videoWidth),i=this.lastDetect?.height??Math.max(1,t.videoHeight),o=this.lastQuad??this.lastGuideQuad??{topLeft:{x:0,y:0},topRight:{x:n,y:0},bottomRight:{x:n,y:i},bottomLeft:{x:0,y:i}},s=(this.opts.now??(()=>performance.now()))(),r=this.feedback.force("processing",s);this.lastFeedbackKey=r.key,this.emit("feedback",r),await this.fire(this.attempt,this.lastOcrReady!==null?this.lastOcrReady.quad:o,{width:n,height:i,tickSharpness:this.lastDetect?.tickSharpness??0},this.lastOcrReady?.via??"manual")}captureReport(){let t=this.stats;return{...this.opts.side!==void 0?{side:this.opts.side}:{},format:this.opts.format??"ID-1",deviceClass:this.deviceClass,video:{width:this.opts.video.videoWidth||0,height:this.opts.video.videoHeight||0},zoom:this.zoom,...t.zoomFallbackAtMs!==void 0?{zoomFallbackAtMs:t.zoomFallbackAtMs}:{},...t.msToCapture!==void 0?{msToCapture:t.msToCapture}:{},...t.via!==void 0?{via:t.via}:{},...t.shutterAtMs!==void 0?{shutterAtMs:t.shutterAtMs}:{},...t.shutterReason!==void 0?{shutterReason:t.shutterReason}:{},ticks:t.ticks,quadFraming:{...t.quadFraming},qualityBlockers:{...t.qualityBlockers},guideBlockers:{...t.guideBlockers},stillRefusals:t.stillRefusals,...this.ocrReport()}}ocrReport(){let t=this.opts.ocr;if(t===void 0)return{};let n=(this.opts.format??"ID-1")==="ID-3"||this.opts.side==="single"?"single":this.opts.side==="verso"?"verso":"recto",i=t.report(n,this.stats.via,(this.opts.now??(()=>performance.now()))());return i===null?{}:{ocr:i}}static freshStats(){return{ticks:0,quadFraming:{},qualityBlockers:{},guideBlockers:{},stillRefusals:0}}setGuide(t){t===void 0?delete this.opts.guide:this.opts.guide=t,this.guideLock.reset()}guideRegion(t){let n=t.width/Math.max(1,t.height),i=this.opts.guide;if(i!==void 0&&i.viewAspect>0){let c={width:i.viewAspect,height:1},a={x:i.rect.x*i.viewAspect,y:i.rect.y,width:i.rect.width*i.viewAspect,height:i.rect.height};return we(c,a,n,0)}let o=Kt(this.opts.format??"ID-1").center,s=.86,r=s*n/o;return r>.84&&(r=.84,s=r*o/n),{x:(1-s)/2,y:(1-r)/2,width:s,height:r}}resetSide(){this.positioningSince=null,this.detectedSince=null,this.lastSeenAt=null,this.guideLock.reset(),this.lastGuideQuad=null,this.lastOcrReady=null,this.opts.ocr?.reset(),this.stats=e.freshStats(),this.shutterOffered&&(this.shutterOffered=!1,this.emit("shutter",{available:!1}))}withdrawShutter(){this.shutterOffered&&(this.shutterOffered=!1,this.emit("shutter",{available:!1}))}zoomFallback(t){let n=this.videoTrack();if(n===null||this.zoom<=1)return;let i=this.focusCaps(),o=typeof i?.zoom?.min=="number"?Math.max(i.zoom.min,1):1;this.zoom=o,this.stats.zoomFallbackAtMs=Math.round(t-(this.positioningSince??t)),this.guideLock.reset(),this.gate.reset(),n.applyConstraints({advanced:[{zoom:o}]}).catch(()=>{})}offerShutter(t,n){this.shutterOffered||(this.shutterOffered=!0,this.stats.shutterAtMs=Math.round(n-(this.positioningSince??n)),this.stats.shutterReason=t,this.emit("shutter",{available:!0,reason:t}))}torchAvailable(){try{return this.stream?.getVideoTracks?.()[0]?.getCapabilities?.()?.torch===!0}catch{return!1}}async setTorch(t){this.torchOn=t;try{await this.stream?.getVideoTracks?.()[0]?.applyConstraints({advanced:[{torch:t}]})}catch{}}destroy(){if(this.attempt+=1,this.timer!==null&&(this.opts.clearTimer??clearTimeout)(this.timer),this.timer=null,this.stream)for(let t of this.stream.getTracks())t.stop();this.stream=null,this.opts.video.srcObject=null}async upgradeResolution(){try{let t=this.stream?.getVideoTracks?.()[0];if(t===void 0)return;let n=t.getSettings?.()??{},i=ae(t.getCapabilities?.(),{width:n.width??0,height:n.height??0},this.deviceClass,{width:this.camera.width,height:this.camera.height});i!==null&&await t.applyConstraints(i)}catch{}}focusCaps(){try{return this.videoTrack()?.getCapabilities?.()??null}catch{return null}}async applyFocusAndZoom(){let t=this.videoTrack();if(t===null)return;let n=this.focusCaps();this.camera.continuousFocus&&rt(n,"continuous")&&await t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{});let i={width:0,height:0};try{let s=t.getSettings?.()??{};i={width:s.width??0,height:s.height??0}}catch{}let o=ke(n,i,this.opts.format??"ID-1",this.camera);if(o>1)try{await t.applyConstraints({advanced:[{zoom:o}]}),this.zoom=o}catch{this.zoom=1}}async focusAt(t,n){let i=this.videoTrack(),o=bt(this.focusCaps(),t,n);if(!(i===null||o===null))try{await i.applyConstraints({advanced:[o]}),(this.opts.setTimer??setTimeout)(()=>{this.restoreContinuous()},1500)}catch{}}async restoreContinuous(){let t=this.videoTrack();t===null||!this.camera.continuousFocus||!rt(this.focusCaps(),"continuous")||await t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{})}async refocusOn(t,n){let i=this.camera.refocusBeforePhotoMs,o=this.videoTrack();if(i<=0||o===null||n.width<=0||n.height<=0)return;let s=L(t),r=bt(this.focusCaps(),(s.x+s.width/2)/n.width,(s.y+s.height/2)/n.height);if(r!==null)try{await o.applyConstraints({advanced:[r]});let c=this.opts.setTimer??setTimeout;await new Promise(a=>{c(()=>a(),i)})}catch{}}videoTrack(){try{return this.stream?.getVideoTracks?.()[0]??null}catch{return null}}async takeStill(t,n,i){if(this.opts.captureStill!==void 0)return this.opts.captureStill(this.opts.video,t,n);let o=this.opts.format??"ID-1",s=this.videoTrack();if(i&&this.opts.photoCapture!==!1&&this.deviceClass!=="LOW"&&!this.torchOn&&s!==null&&fe(s)){await this.refocusOn(t,n);let r=await be(this.opts.video,t,n,o,{track:s,detect:this.detector(),detectWidth:et});if(this.restoreContinuous(),r!==null)return r}return ge(this.opts.video,t,n,o)}detector(){return this.opts.detect??((this.opts.format??"ID-1")==="ID-3"?ii:ei)}setState(t){this.state=t,this.emit("statechange",{state:t})}scheduleTick(t){let n=this.opts.setTimer??setTimeout;this.timer=n(()=>{this.tick(t)},this.cadenceMs)}async tick(t){if(t!==this.attempt||this.state!=="positioning"||this.capturing)return;let n=this.opts.now??(()=>performance.now()),i=this.opts.grabDetectFrame??Te,o=this.detector(),s=i(this.opts.video,et);if(s===null){this.scheduleTick(t);return}let r=null;try{r=await o(s)}catch{r=null}if(t!==this.attempt)return;let c=r!==null?lt(s,r):s,a=n(),l={sharpness:j(c),exposure:Ht(c),meanLuma:Ut(c),specularFraction:ee(c)},u=ie({format:this.opts.format??"ID-1",quad:r,frameWidth:s.width,frameHeight:s.height,measures:l,...this.opts.thresholds!==void 0?{thresholds:this.opts.thresholds}:{}}),d=this.gate.tick({timestampMs:a,quad:r,quality:l,frameWidth:s.width,frameHeight:s.height}),h=(this.opts.format??"ID-1")!=="ID-3"?ve(s,this.guideRegion(s),{edgePeakFrac:this.guideTuning.edgePeakFrac}):Z,f=this.guideLock.tick(h,a);this.lastGuideQuad=f.detected?Se(h):null;let g=this.capturing?null:this.ocrTick(s,r,h,f.detected,u,a);this.positioningSince??(this.positioningSince=a);let y=this.stats;if(y.ticks+=1,y.quadFraming[u.framing]=(y.quadFraming[u.framing]??0)+1,u.framing==="ok"&&!d.ready){let R=u.lighting!=="ok"?u.lighting:u.glare!=="ok"?"glare":u.blur!=="ok"?"blurry":"steadying";y.qualityBlockers[R]=(y.qualityBlockers[R]??0)+1}y.guideBlockers[f.blocker]=(y.guideBlockers[f.blocker]??0)+1,r!==null||f.detected?(this.detectedSince??(this.detectedSince=a),this.lastSeenAt=a):this.detectedSince=null,this.lastSeenAt!==null&&a-this.lastSeenAt<=ui?a-this.positioningSince>=this.shutterTuning.manualShutterMs?this.offerShutter("timeout",a):g?.suspendQuality!==!0&&this.detectedSince!==null&&a-this.detectedSince>=this.shutterTuning.detectedNoLockMs&&this.offerShutter("detected_no_lock",a):this.withdrawShutter();let E=a-(this.lastSeenAt??this.positioningSince);this.zoom>1&&this.camera.zoomFallbackMs>0&&E>=this.camera.zoomFallbackMs&&this.zoomFallback(a),this.emit("checks",{engine:"docv1",p:d.p,plausible:d.plausible,stableTicks:d.stableTicks,quad:d.quad,frameWidth:s.width,frameHeight:s.height,analysis:u,ready:g?.suspendQuality!==!0&&(d.ready&&r!==null||f.ready&&this.lastGuideQuad!==null)||this.lastOcrReady!==null,guide:{detected:f.detected,blocker:f.blocker,fill:h.fill,shape:h.shape,content:h.content,offsetX:h.offsetX,offsetY:h.offsetY},...g!==null&&g.mode!=="off"?{ocr:{mode:g.mode,...g.mrz?{mrz:g.mrz}:{},...g.lock?{lock:g.lock}:{}}}:g?.mrz?{ocr:{mode:g.mode,mrz:g.mrz}}:{}}),this.lastQuad=d.plausible?r:null,this.lastDetect={width:s.width,height:s.height,tickSharpness:l.sharpness};let v=qt(u);u.framing!=="ok"&&f.detected&&(v=li(f.blocker,h.brightness<this.guideTuning.darkBrightness)),v==="blurry"&&r!==null&&si(r,s,this.opts.format??"ID-1")>=this.camera.focusFarFillFrac&&(v="focus_far"),v==="sensing"&&this.zoom>1&&this.camera.noDocFarHintMs>0&&E>=this.camera.noDocFarHintMs&&(v="focus_far");let D=this.feedback.tick(v,a);if(D.key!==this.lastFeedbackKey&&(this.lastFeedbackKey=D.key,this.emit("feedback",D)),d.guidanceKey!==this.lastGuidance&&(this.lastGuidance=d.guidanceKey,this.emit("guidance",{key:d.guidanceKey})),this.capturing)return;let M=g?.suspendQuality!==!0,_=M&&d.ready&&r!==null,k=M&&f.ready&&this.lastGuideQuad!==null,F=this.lastOcrReady;if(F!==null&&this.opts.autoCapture!==!1){let R=this.feedback.force("processing",a);this.lastFeedbackKey=R.key,this.emit("feedback",R);let A=j(lt(s,F.quad));await this.fire(t,F.quad,{width:s.width,height:s.height,tickSharpness:A},F.via);return}if((_||k)&&this.opts.autoCapture!==!1){let R=this.feedback.force("processing",a);this.lastFeedbackKey=R.key,this.emit("feedback",R);let A=k?this.lastGuideQuad:r,B=k?f.via==="steady"?"guide_steady":"guide_good":"quad",U=k?j(lt(s,A)):l.sharpness;await this.fire(t,A,{width:s.width,height:s.height,tickSharpness:U},B);return}this.scheduleTick(t)}async fire(t,n,i,o){this.capturing=!0;let s=this.opts.grabDetectFrame??Te,r=this.opts.setTimer??setTimeout,c={width:i.width,height:i.height};try{let a={still:await this.takeStill(n,c,!0),sharpness:i.tickSharpness};if(t!==this.attempt)return;let l=a.still.source==="photo"?0:ri;for(let m=0;m<l;m++){if(await new Promise(g=>{r(()=>g(),ai)}),t!==this.attempt)return;let h=s(this.opts.video,et);if(h===null)continue;let f=j(lt(h,n));if(f>a.sharpness*ci){let g=await this.takeStill(n,c,!1);if(t!==this.attempt)return;a={still:g,sharpness:f}}}if(t!==this.attempt)return;let u=a.still.sharpness;if(this.opts.autoCapture!==!1&&o!=="manual"&&typeof u=="number"&&u>=0&&u<this.camera.stillSharpnessMin&&this.stillRefusals<this.camera.stillRefusalsMax){this.stillRefusals+=1,this.stats.stillRefusals+=1,this.guideLock.reset(),this.lastOcrReady=null,(o==="text_lock"||o==="live_mrz")&&this.opts.ocr?.rearmFace();let m=(this.opts.now??(()=>performance.now()))(),h=this.feedback.force("focus_far",m);this.lastFeedbackKey=h.key,this.emit("feedback",h),this.capturing=!1,this.gate.reset(),this.scheduleTick(t);return}this.stillRefusals=0;let d=(this.opts.now??(()=>performance.now()))();this.stats.via=o,this.stats.msToCapture=Math.round(d-(this.positioningSince??d)),this.shutterOffered&&(this.shutterOffered=!1,this.emit("shutter",{available:!1})),this.setState("captured"),this.emit("artifacts",{keyframe:a.still.blob,previewDataUrl:a.still.previewDataUrl,...this.opts.side!==void 0?{side:this.opts.side}:{},...a.still.docRegion!==void 0?{docRegion:a.still.docRegion}:{},...(()=>{let m=o==="live_mrz"?this.opts.ocr?.liveCapture():null;return m?{liveMrz:m}:{}})()})}catch{if(t!==this.attempt)return;this.capturing=!1,this.gate.reset(),this.guideLock.reset(),this.lastOcrReady=null,(o==="text_lock"||o==="live_mrz")&&this.opts.ocr?.rearmFace(),this.scheduleTick(t)}}ocrTick(t,n,i,o,s,r){let c=this.opts.ocr,a=this.opts.video;if(c===void 0||!c.hasEngine)return this.lastOcrReady=null,null;let l=a.videoWidth,u=a.videoHeight;if(l<=0||u<=0||t.width<=0||t.height<=0)return null;let m=(this.opts.format??"ID-1")==="ID-3",h=this.guideRegion(t),f={x:h.x*l,y:h.y*u,w:h.width*l,h:h.height*u},g=l/t.width,y=u/t.height,x;m&&n!==null?x=oi(L(n),g,y,l,u):x=Yt(f,c.bandTop,u);let w=m?s.glare==="ok":i.cardGlare<=this.guideTuning.glareMax,E=m?s.blur==="ok":i.sharpness>=this.guideTuning.sharpnessMin,v=c.tick({atMs:r,video:a,mrzFace:m||this.opts.side==="verso"||this.opts.side==="single",present:m||n!==null||o,card:f,band:x,portrait:u>l,glareOk:w,sharpOk:E});if(v.ready&&v.via!==void 0){let D=m?n??Re(h,t):this.lastGuideQuad??Re(h,t);this.lastOcrReady={quad:D,via:v.via}}else this.lastOcrReady=null;return v}};function oi(e,t,n,i,o){let s=Math.min(i,e.width*1.06*t),r=Math.min(o,Math.max(e.height*1.6*n,s/5)),c=(e.y+e.height/2)*n,a=Math.max(0,Math.min(i-s,(e.x-e.width*.03)*t)),l=Math.max(0,Math.min(o-r,c-r/2));return{x:a,y:l,w:s,h:r}}function Re(e,t){let n=e.x*t.width,i=e.y*t.height,o=(e.x+e.width)*t.width,s=(e.y+e.height)*t.height;return{topLeft:{x:n,y:i},topRight:{x:o,y:i},bottomRight:{x:o,y:s},bottomLeft:{x:n,y:s}}}function si(e,t,n){let i=L(e);return t.width<=0||t.height<=0?0:n==="ID-3"?i.width/t.width:i.width*i.height/(t.width*t.height)}var ri=2,ai=260,ci=1.08;function Te(e,t){let n=e.videoWidth,i=e.videoHeight;if(n===0||i===0)return null;let o=Math.min(1,t/n),s=Math.round(n*o),r=Math.round(i*o),c=document.createElement("canvas");c.width=s,c.height=r;let a=c.getContext("2d",{willReadFrequently:!0});return a===null?null:(n/Math.max(1,s)>4&&(a.imageSmoothingQuality="high"),a.drawImage(e,0,0,s,r),a.getImageData(0,0,s,r))}function lt(e,t){let n=[t.topLeft.x,t.topRight.x,t.bottomRight.x,t.bottomLeft.x],i=[t.topLeft.y,t.topRight.y,t.bottomRight.y,t.bottomLeft.y],o=Math.max(0,Math.floor(Math.min(...n))),s=Math.max(0,Math.floor(Math.min(...i))),r=Math.min(e.width,Math.ceil(Math.max(...n))),c=Math.min(e.height,Math.ceil(Math.max(...i))),a=Math.max(1,r-o),l=Math.max(1,c-s),u=new Uint8ClampedArray(a*l*4);for(let d=0;d<l;d++){let m=((s+d)*e.width+o)*4;u.set(e.data.subarray(m,m+a*4),d*a*4)}return{data:u,width:a,height:l,colorSpace:e.colorSpace}}function li(e,t){return e==="glare"?"glare":e==="too_small"?"too_far":e==="too_big"?"too_close":t?"too_dark":e==="blurry"?"blurry":e==="off_center"?"edge_clipped":e==="no_card"?"sensing":"hold_still"}var ui=1200;export{it as a,qt as b,nt as c,Qe as d,ee as e,Be as f,ie as g,st as h,ki as i,Ye as j,Je as k,pt as l,$e as m,ye as n,rt as o,bt as p,xi as q,ke as r,qe as s,ti as t,xe as u,Z as v,we as w,ve as x,Se as y,J as z,wi as A,ct as B,Ni as C,ni as D,yt as E,Qi as F,_e as G,oi as H,ri as I,ai as J};
|
package/dist/client/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var y=Object.defineProperty;var
|
|
1
|
+
"use strict";var y=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var v=Object.getOwnPropertyNames;var E=Object.prototype.hasOwnProperty;var M=(t,e)=>{for(var n in e)y(t,n,{get:e[n],enumerable:!0})},N=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of v(e))!E.call(t,i)&&i!==n&&y(t,i,{get:()=>e[i],enumerable:!(o=O(e,i))||o.enumerable});return t};var A=t=>N(y({},"__esModule",{value:!0}),t);var Y={};M(Y,{HostedApiError:()=>c,HostedClient:()=>p,KNOWN_CODES:()=>g,icaoPolicyOf:()=>I,isKnownCode:()=>T,portraitIcaoGate:()=>k,stripMimeParams:()=>u});module.exports=A(Y);var b="0.1.0-rc.8";var S="sekyro.did",C;function w(){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 x(){try{let t=localStorage.getItem(S);if(t)return t;let e=w();return e!==void 0&&localStorage.setItem(S,e),e}catch{return C??(C=w()),C}}async function H(){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]),o=await t.digest("SHA-256",new TextEncoder().encode(n));return Array.from(new Uint8Array(o),i=>i.toString(16).padStart(2,"0")).join("").slice(0,32)}function D(t){let e=new TextEncoder().encode(t),n="";for(let o of e)n+=String.fromCharCode(o);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function V(t){let e,n;return{timezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone?.slice(0,64)||void 0}catch{return}},noteCameraLabel(o){o&&(e=o.slice(0,128))},async deviceHeader(){try{n??(n=H().catch(()=>""));let o=[];navigator.webdriver&&o.push("webdriver"),/HeadlessChrome/.test(navigator.userAgent)&&o.push("headless");let i=await n,s=x(),a={v:1,platform:"web",sdk:t.sdk.slice(0,64),ids:[...s?[{kind:"web_local",value:s.slice(0,128)}]:[],...i?[{kind:"web_fp",value:i}]:[]],screen:{w:screen.width,h:screen.height,dpr:globalThis.devicePixelRatio??1},...e?{cameraLabel:e}:{},...o.length?{signals:o}:{}};return D(JSON.stringify(a))}catch{return}}}}var m=Symbol.for("sekyro.web.clientContext"),f=globalThis,h=f[m]??(f[m]=V({sdk:`@sekyro/web@${b}`}));var g=["session_token_invalid","session_token_required","session_token_session_mismatch","session_not_found","rate_limit_exceeded","consent_required","session_not_active","check_not_found","check_already_finalized","check_out_of_order","check_type_unsupported","force_outcome_forbidden","attestation_invalid","platform_unregistered","app_attest_invalid","too_many_challenges","inference_unavailable","mobile_required","nni_locked","method_required","method_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","method_not_offered","nfc_outcome_not_accepted","contact_locked","identity_confirm_required","identity_confirm_locked"];function T(t){return g.includes(t)}var c=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)}};var K=6e4,P=4,U=3e4,L=9e5,q=200,$=5,B=400;function u(t){return(t.split(";")[0]??"").trim()}var F={liveness:"clipKey",face_match:"imageKey",doc_ocr:"imageKey"},p=class{constructor(e){this.sessionId=null;this.bootstrap=null;this.captureNonces=[];this.captureFetch=null;this.apiOrigin=e.apiOrigin.replace(/\/+$/,""),this.sessionToken=e.sessionToken;let n=e.fetch;this.fetchImpl=(o,i)=>(n??globalThis.fetch).call(globalThis,o,i),this.requestTimeoutMs=e.requestTimeoutMs??U,this.retryAttempts=e.inProgressRetry?.attempts??$,this.retryDelayMs=e.inProgressRetry?.delayMs??B}async getSession(){let e=await this.api("GET","/hosted/session");return this.sessionId=e.sessionId,e}async recordConsent(e){return this.api("POST","/hosted/consent",{body:{locale:e}})}async selectMethod(e){let n=await this.api("POST","/hosted/method",{body:{method:e}});return this.sessionId=n.sessionId,n}async selectContact(e){return this.api("POST","/hosted/contact",{body:{channel:e}})}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,o){let i=await this.ensureSessionId(),s={kind:e,contentType:u(n),contentLength:o};return this.api("POST",`/sessions/${i}/media`,{body:s})}armCapture(e=2){this.fillCaptureNonces(e)}async presignCapture(e,n,o,i={}){let s=await this.ensureSessionId(),a=await this.takeCaptureNonce(),r=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)))}:{}},d={kind:e,contentType:u(n),contentLength:o,...r!==void 0?{capture:r}:{}};return this.api("POST",`/sessions/${s}/media`,{body:d})}async takeCaptureNonce(){let e=()=>{let n=Date.now();return this.captureNonces=this.captureNonces.filter(o=>o.expiresAt-K>n),this.captureNonces.shift()?.nonce};for(let n=0;n<2;n++){let o=e();if(o!==void 0)return o;await this.fillCaptureNonces(1)}return e()}fillCaptureNonces(e){return this.captureFetch??(this.captureFetch=(async()=>{try{let n=await this.ensureSessionId(),o=await this.api("POST",`/sessions/${n}/media/capture-nonces`,{body:{count:Math.min(P,Math.max(1,e))}}),i=Date.now()+Math.max(0,o.expiresIn)*1e3;for(let s of Array.isArray(o.nonces)?o.nonces:[])typeof s=="string"&&s.length>0&&this.captureNonces.push({nonce:s,expiresAt:i});this.captureNonces=this.captureNonces.slice(-P)}catch{}})().finally(()=>{this.captureFetch=null})),this.captureFetch}async uploadToSpaces(e,n,o){let i;try{i=await this.fetchImpl(e,{method:"PUT",headers:{"content-type":u(o)},body:n,signal:AbortSignal.timeout(L)})}catch(s){throw _(s)}if(!i.ok){let s=(await i.text().catch(()=>"")).slice(0,q);throw new c({status:i.status,code:"upload_failed",message:`media upload failed (HTTP ${i.status})${s?`: ${s}`:""}`})}}async completeMedia(e){let n=await this.ensureSessionId();return this.api("POST",`/sessions/${n}/media/complete`,{body:{key:e}})}async submitCheck(e,n,o={}){let i=await this.ensureSessionId(),s={input:n,...o.forceOutcome!==void 0?{forceOutcome:o.forceOutcome}:{}};return this.api("POST",`/sessions/${i}/checks/${e}`,{body:s,...o.idempotencyKey!==void 0?{idempotencyKey:o.idempotencyKey}:{}})}async uploadAndSubmit(e,n,o,i={}){let s=u(n.contentType),a=await this.presign(n.kind,s,n.blob.size);await this.uploadToSpaces(a.uploadUrl,n.blob,s);let r=await this.completeMedia(a.key),d={...o,[F[e]]:r.key};return this.submitCheck(e,d,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,n,o={}){let i=`${this.apiOrigin}/api/v2${n}`,s={"x-session-token":this.sessionToken};o.body!==void 0&&(s["content-type"]="application/json"),o.idempotencyKey!==void 0&&(s["x-idempotency-key"]=o.idempotencyKey);try{let a=h.timezone();a!==void 0&&(s["sekyro-client-timezone"]=a)}catch{}try{let a=await h.deviceHeader();a!==void 0&&(s["sekyro-client-device"]=a)}catch{}for(let a=0;;a++){let r;try{r=await this.fetchImpl(i,{method:e,headers:s,...o.body!==void 0?{body:JSON.stringify(o.body)}:{},cache:"no-store",signal:AbortSignal.timeout(this.requestTimeoutMs)})}catch(l){throw _(l)}if(r.ok){if(o.blob===!0)try{return await r.blob()}catch(R){throw _(R)}let l;try{l=await r.json()}catch{throw new c({status:r.status,code:"unknown_error",message:`response body was not valid JSON (HTTP ${r.status})`})}return j(l)}let d=await G(r);if(d.code==="idempotency_in_progress"&&a<this.retryAttempts){this.retryDelayMs>0&&await z(this.retryDelayMs);continue}throw d}}};function _(t){if((typeof t=="object"&&t!==null?t.name:void 0)==="TimeoutError")return new c({status:0,code:"timeout",message:"request timed out"});let n=t instanceof Error?t.message:String(t);return new c({status:0,code:"network_error",message:`network request failed: ${n}`})}function j(t){return t!==null&&typeof t=="object"&&"success"in t&&"data"in t?t.data:t}async function G(t){let e="unknown_error",n=`request failed (HTTP ${t.status})`,o=Number.NaN;try{let a=await t.json();if(a!==null&&typeof a=="object"){let r=a;typeof r.code=="string"&&r.code.length>0&&(e=r.code),typeof r.message=="string"&&r.message.length>0&&(n=r.message),typeof r.retryAfterSeconds=="number"&&(o=r.retryAfterSeconds)}}catch{}let i=t.headers.get("retry-after"),s=i===null?Math.floor(o):Number.parseInt(i,10);return new c({status:t.status,code:e,message:n,...Number.isFinite(s)&&s>=0?{retryAfterSeconds:s}:{}})}function z(t){return new Promise(e=>setTimeout(e,t))}function I(t){let e=t?.portrait,n=e?.icao,o=e?.purpose==="id_document";return n==null?o?{policy:"reject",profile:"id_document"}:null:{policy:n.policy==="alert"&&!o?"alert":"reject",profile:o||n.profile==="id_document"?"id_document":"selfie"}}function k(t){return{...t.baselineEyeOpenness!==void 0?{baselineEyeOpenness:t.baselineEyeOpenness}:{},criteria:t.verdict??{},...t.backgroundCheck!==void 0?{backgroundCheck:t.backgroundCheck}:{}}}0&&(module.exports={HostedApiError,HostedClient,KNOWN_CODES,icaoPolicyOf,isKnownCode,portraitIcaoGate,stripMimeParams});
|
package/dist/client/index.d.cts
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
|
-
|
|
1
|
+
import { w as HostedSessionView, p as HostedIcaoPolicy, L as IcaoGateSummary, a0 as PortraitIcaoInput } from '../icao-gate-D8qm1O2t.cjs';
|
|
2
|
+
export { A as AcceptedDocumentType, aM as AttestationInput, aN as CaptureContext, aO as CaptureNoncesResult, aP as CaptureProof, aQ as CheckInputByType, C as CheckReason, a as CheckState, b as CheckType, aR as CompleteMediaResult, aS as ConsentLocale, c as ContactChannel, D as DecisionReason, aT as DocDeviceRead, aU as DocOcrInput, d as DocReason, aV as DocSide, E as EidAfterPass, e as EidAuthInput, f as EidReason, aW as EmailOtpInput, g as EmailOtpReason, aX as FaceMatchInput, F as FaceMatchReason, h as HostedAcceptedDocuments, k as HostedCaptureTuning, aL as HostedClient, aY as HostedClientOptions, l as HostedDocumentCaptureTuning, m as HostedDocumentScanTuning, n as HostedEidView, o as HostedEmailOtpView, q as HostedIntegrity, r as HostedLivePhotoTuning, s as HostedNativeCaptureTuning, t as HostedOcrTuning, u as HostedOtpView, v as HostedPortraitView, x as HostedStepView, y as HostedVoiceLocale, z as HostedVoiceView, G as IcaoCriterion, N as IcaoReportEntry, O as IdentityConfirmDecision, P as IdentityMethod, Q as IdentitySummarySource, R as IdentitySummaryView, aZ as LivenessCaptureInput, a_ as LivenessInput, S as LivenessReason, T as MatchReason, a$ as MediaCheckType, b0 as MediaKind, U as MethodChoiceView, V as NationalEidOption, W as NfcChipReason, X as NfcStepView, Y as OtpChoiceView, b1 as PhoneOtpInput, Z as PhoneOtpReason, _ as PolicyFailureReason, b2 as PopulationInput, $ as PopulationReason, a1 as PortraitIcaoReason, b3 as PresignRequest, b4 as PresignUploadResult, b5 as RecordConsentResult, a2 as SessionFailureReason, a3 as SessionOutcome, a4 as SessionStatus, b6 as SessionStepView, a6 as SessionView, a5 as StepSection, b7 as SubmitCheckBody, b8 as SubmitOptions, b9 as UploadMedia, ba as stripMimeParams } from '../icao-gate-D8qm1O2t.cjs';
|
|
2
3
|
|
|
3
4
|
/**
|
|
4
5
|
* Every error code the hosted page can receive from the session-token surface.
|
|
5
6
|
* A closed string-literal union — switch over {@link KnownCode} with a `never`
|
|
6
7
|
* default arm for compile-checked exhaustiveness.
|
|
7
8
|
*/
|
|
8
|
-
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", "inference_unavailable", "mobile_required", "nni_locked", "method_required", "method_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"];
|
|
9
|
+
declare const KNOWN_CODES: readonly ["session_token_invalid", "session_token_required", "session_token_session_mismatch", "session_not_found", "rate_limit_exceeded", "consent_required", "session_not_active", "check_not_found", "check_already_finalized", "check_out_of_order", "check_type_unsupported", "force_outcome_forbidden", "attestation_invalid", "platform_unregistered", "app_attest_invalid", "too_many_challenges", "inference_unavailable", "mobile_required", "nni_locked", "method_required", "method_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", "method_not_offered", "nfc_outcome_not_accepted", "contact_locked", "identity_confirm_required", "identity_confirm_locked"];
|
|
9
10
|
/** Closed union of {@link KNOWN_CODES} — exhaustively switchable. */
|
|
10
11
|
type KnownCode = (typeof KNOWN_CODES)[number];
|
|
11
12
|
/** Narrow an arbitrary wire code to the known union (unknown codes stay `string`). */
|
|
@@ -36,4 +37,13 @@ declare class HostedApiError extends Error {
|
|
|
36
37
|
});
|
|
37
38
|
}
|
|
38
39
|
|
|
39
|
-
|
|
40
|
+
/** The session's ICAO policy and profile, or `null` when the selfie is not ICAO-checked. */
|
|
41
|
+
declare function icaoPolicyOf(view: Pick<HostedSessionView, "portrait"> | null | undefined): HostedIcaoPolicy | null;
|
|
42
|
+
/**
|
|
43
|
+
* The `gate` block of a `portrait_icao` body from the gate's summary: the eye
|
|
44
|
+
* baseline, the device verdict under the server's criterion names, and the
|
|
45
|
+
* background-uniformity numbers (telemetry).
|
|
46
|
+
*/
|
|
47
|
+
declare function portraitIcaoGate(summary: IcaoGateSummary): NonNullable<PortraitIcaoInput["gate"]>;
|
|
48
|
+
|
|
49
|
+
export { HostedApiError, HostedIcaoPolicy, HostedSessionView, KNOWN_CODES, type KnownCode, PortraitIcaoInput, icaoPolicyOf, isKnownCode, portraitIcaoGate };
|
package/dist/client/index.d.ts
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
|
-
|
|
1
|
+
import { w as HostedSessionView, p as HostedIcaoPolicy, L as IcaoGateSummary, a0 as PortraitIcaoInput } from '../icao-gate-D8qm1O2t.js';
|
|
2
|
+
export { A as AcceptedDocumentType, aM as AttestationInput, aN as CaptureContext, aO as CaptureNoncesResult, aP as CaptureProof, aQ as CheckInputByType, C as CheckReason, a as CheckState, b as CheckType, aR as CompleteMediaResult, aS as ConsentLocale, c as ContactChannel, D as DecisionReason, aT as DocDeviceRead, aU as DocOcrInput, d as DocReason, aV as DocSide, E as EidAfterPass, e as EidAuthInput, f as EidReason, aW as EmailOtpInput, g as EmailOtpReason, aX as FaceMatchInput, F as FaceMatchReason, h as HostedAcceptedDocuments, k as HostedCaptureTuning, aL as HostedClient, aY as HostedClientOptions, l as HostedDocumentCaptureTuning, m as HostedDocumentScanTuning, n as HostedEidView, o as HostedEmailOtpView, q as HostedIntegrity, r as HostedLivePhotoTuning, s as HostedNativeCaptureTuning, t as HostedOcrTuning, u as HostedOtpView, v as HostedPortraitView, x as HostedStepView, y as HostedVoiceLocale, z as HostedVoiceView, G as IcaoCriterion, N as IcaoReportEntry, O as IdentityConfirmDecision, P as IdentityMethod, Q as IdentitySummarySource, R as IdentitySummaryView, aZ as LivenessCaptureInput, a_ as LivenessInput, S as LivenessReason, T as MatchReason, a$ as MediaCheckType, b0 as MediaKind, U as MethodChoiceView, V as NationalEidOption, W as NfcChipReason, X as NfcStepView, Y as OtpChoiceView, b1 as PhoneOtpInput, Z as PhoneOtpReason, _ as PolicyFailureReason, b2 as PopulationInput, $ as PopulationReason, a1 as PortraitIcaoReason, b3 as PresignRequest, b4 as PresignUploadResult, b5 as RecordConsentResult, a2 as SessionFailureReason, a3 as SessionOutcome, a4 as SessionStatus, b6 as SessionStepView, a6 as SessionView, a5 as StepSection, b7 as SubmitCheckBody, b8 as SubmitOptions, b9 as UploadMedia, ba as stripMimeParams } from '../icao-gate-D8qm1O2t.js';
|
|
2
3
|
|
|
3
4
|
/**
|
|
4
5
|
* Every error code the hosted page can receive from the session-token surface.
|
|
5
6
|
* A closed string-literal union — switch over {@link KnownCode} with a `never`
|
|
6
7
|
* default arm for compile-checked exhaustiveness.
|
|
7
8
|
*/
|
|
8
|
-
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", "inference_unavailable", "mobile_required", "nni_locked", "method_required", "method_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"];
|
|
9
|
+
declare const KNOWN_CODES: readonly ["session_token_invalid", "session_token_required", "session_token_session_mismatch", "session_not_found", "rate_limit_exceeded", "consent_required", "session_not_active", "check_not_found", "check_already_finalized", "check_out_of_order", "check_type_unsupported", "force_outcome_forbidden", "attestation_invalid", "platform_unregistered", "app_attest_invalid", "too_many_challenges", "inference_unavailable", "mobile_required", "nni_locked", "method_required", "method_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", "method_not_offered", "nfc_outcome_not_accepted", "contact_locked", "identity_confirm_required", "identity_confirm_locked"];
|
|
9
10
|
/** Closed union of {@link KNOWN_CODES} — exhaustively switchable. */
|
|
10
11
|
type KnownCode = (typeof KNOWN_CODES)[number];
|
|
11
12
|
/** Narrow an arbitrary wire code to the known union (unknown codes stay `string`). */
|
|
@@ -36,4 +37,13 @@ declare class HostedApiError extends Error {
|
|
|
36
37
|
});
|
|
37
38
|
}
|
|
38
39
|
|
|
39
|
-
|
|
40
|
+
/** The session's ICAO policy and profile, or `null` when the selfie is not ICAO-checked. */
|
|
41
|
+
declare function icaoPolicyOf(view: Pick<HostedSessionView, "portrait"> | null | undefined): HostedIcaoPolicy | null;
|
|
42
|
+
/**
|
|
43
|
+
* The `gate` block of a `portrait_icao` body from the gate's summary: the eye
|
|
44
|
+
* baseline, the device verdict under the server's criterion names, and the
|
|
45
|
+
* background-uniformity numbers (telemetry).
|
|
46
|
+
*/
|
|
47
|
+
declare function portraitIcaoGate(summary: IcaoGateSummary): NonNullable<PortraitIcaoInput["gate"]>;
|
|
48
|
+
|
|
49
|
+
export { HostedApiError, HostedIcaoPolicy, HostedSessionView, KNOWN_CODES, type KnownCode, PortraitIcaoInput, icaoPolicyOf, isKnownCode, portraitIcaoGate };
|
package/dist/client/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as e,b as t,c as o,d as
|
|
1
|
+
import{a as e,b as t,c as o,d as i,e as n,f as s,g as a}from"../chunk-4RS2YIL4.js";import"../chunk-LQ7C44JG.js";export{o as HostedApiError,n as HostedClient,e as KNOWN_CODES,s as icaoPolicyOf,t as isKnownCode,a as portraitIcaoGate,i as stripMimeParams};
|
package/dist/core/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var De=Object.create;var w=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var xe=Object.getOwnPropertyNames;var Te=Object.getPrototypeOf,Ce=Object.prototype.hasOwnProperty;var Ie=(i,e)=>{for(var t in e)w(i,t,{get:e[t],enumerable:!0})},te=(i,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of xe(e))!Ce.call(i,r)&&r!==t&&w(i,r,{get:()=>e[r],enumerable:!(n=Se(e,r))||n.enumerable});return i};var we=(i,e,t)=>(t=i!=null?De(Te(i)):{},te(e||!i||!i.__esModule?w(t,"default",{value:i,enumerable:!0}):t,i)),Oe=i=>te(w({},"__esModule",{value:!0}),i);var Je={};Ie(Je,{CENTERED_FACTOR:()=>Fe,CIRCLE_RADIUS_FACTOR:()=>Le,CLIP_MS:()=>ne,CaptureSessionV3:()=>ee,ClipError:()=>f,ClipRecorder:()=>D,DEFAULT_CLIP_MIME:()=>O,DEFAULT_TIER_ORDER:()=>ue,DEFAULT_V3_ASSET_BASE_URL:()=>ce,DEVICE_PROFILES:()=>me,DetectScheduler:()=>I,DetectorLadderError:()=>y,DeviceProfiler:()=>C,EXPOSURE_BAND:()=>x,FaceGateV3:()=>T,IN_CIRCLE_FACTOR:()=>Pe,KEYFRAME_CANDIDATES:()=>V,KEYFRAME_WINDOW_MS:()=>_e,MAX_CLIP_BYTES:()=>M,MIME_CANDIDATES:()=>re,SHARP_REF:()=>ht,STOP_GRACE_MS:()=>se,TIMESLICE_MS:()=>ie,V3_GATE_DEFAULTS:()=>le,VIDEO_BPS:()=>z,buildCaptureConstraints:()=>K,buildLivenessV2FormData:()=>ke,cameraPreflight:()=>H,captureMirroredKeyframe:()=>B,classifyDevice:()=>j,createDetector:()=>b,detectIsMobile:()=>X,errorCopy:()=>Re,exposure:()=>Z,extForMime:()=>G,intrinsicSize:()=>v,isClipTooLarge:()=>_,isMediaRecorderSupported:()=>Me,mapGetUserMediaError:()=>U,meanLuma:()=>L,pickMimeType:()=>W,probeDevice:()=>Q,sharpness:()=>P,toStreamPixels:()=>S,uiCopy:()=>Ae});module.exports=Oe(Je);var re=["video/mp4;codecs=avc1.42E01E,mp4a.40.2","video/mp4;codecs=avc1.42E01E","video/mp4","video/webm;codecs=vp9,opus","video/webm;codecs=vp9","video/webm;codecs=vp8,opus","video/webm;codecs=vp8","video/webm"];function W(){let i=globalThis.MediaRecorder;return!i||typeof i.isTypeSupported!="function"?"":re.find(e=>i.isTypeSupported(e))??""}var O="video/webm";function U(i){if(i instanceof TypeError)return"insecure";switch(i?.name??""){case"NotAllowedError":case"PermissionDeniedError":return"permission";case"NotFoundError":case"DevicesNotFoundError":return"notfound";case"NotReadableError":case"TrackStartError":return"inuse";case"OverconstrainedError":case"ConstraintNotSatisfiedError":return"overconstrained";default:return"generic"}}function H(){let i=globalThis;if(typeof i.window<"u"&&i.window.isSecureContext===!1)return"INSECURE_CONTEXT";let e=i.navigator?.mediaDevices;return!e||typeof e.getUserMedia!="function"?"UNSUPPORTED":"OK"}function Me(){let i=globalThis.MediaRecorder;return typeof i<"u"&&typeof i.isTypeSupported=="function"}var M=8*1024*1024;function _(i){return i.size>M}function G(i){let e=(i||"").toLowerCase();return e.startsWith("image/jpeg")?"jpg":e.startsWith("video/mp4")?"mp4":(e.startsWith("video/webm"),"webm")}function ke(i){let{token:e,clip:t,keyframe:n}=i,r=i.ts??Date.now(),s=t.type||O,a=n.type||"image/jpeg",o=new FormData;return o.append("token",e),o.append("clip",new File([t],`liveness-${r}.${G(s)}`,{type:s})),o.append("keyframe",new File([n],`keyframe-${r}.${G(a)}`,{type:a})),o}function B(i,e,t=.92){return new Promise((n,r)=>{let s=i.videoWidth,a=i.videoHeight;if(!s||!a){r(new Error("video-not-ready"));return}let o=e.getContext("2d");if(!o){r(new Error("no-2d-context"));return}e.width=s,e.height=a,o.scale(-1,1),o.drawImage(i,-s,0),e.toBlob(c=>c?n(c):r(new Error("empty-keyframe")),"image/jpeg",t)})}var Re={permission:{key:"fcv2.err.permission",fr:"Autorisez la cam\xE9ra dans les r\xE9glages du navigateur (ic\xF4ne cam\xE9ra dans la barre d\u2019adresse), puis r\xE9essayez."},notfound:{key:"fcv2.err.notfound",fr:"Aucune cam\xE9ra d\xE9tect\xE9e. Branchez ou activez une cam\xE9ra, puis r\xE9essayez."},inuse:{key:"fcv2.err.inuse",fr:"La cam\xE9ra est utilis\xE9e par une autre application. Fermez-la puis r\xE9essayez."},overconstrained:{key:"fcv2.err.overconstrained",fr:"La cam\xE9ra ne prend pas en charge les r\xE9glages demand\xE9s. Nouvel essai en cours\u2026"},insecure:{key:"fcv2.err.insecure",fr:"La cam\xE9ra n\xE9cessite une connexion s\xE9curis\xE9e (HTTPS). Ouvrez la page en HTTPS."},unsupported:{key:"fcv2.err.unsupported",fr:"Votre navigateur ne prend pas en charge l\u2019enregistrement vid\xE9o. Utilisez un navigateur r\xE9cent."},generic:{key:"fcv2.err.generic",fr:"Cam\xE9ra indisponible. R\xE9essayez ou contactez le support."}},Ae={recording:{key:"fcv2.recording",fr:"Enregistrement en cours\u2026"},uploading:{key:"fcv2.uploading",fr:"Envoi en cours\u2026"},clipTooLarge:{key:"fcv2.err.cliptoolarge",fr:"La vid\xE9o est trop volumineuse. R\xE9essayez dans un endroit mieux \xE9clair\xE9."},retry:{key:"fcv2.retry",fr:"R\xE9essayer"},listen:{key:"fcv2.listen",fr:"\xC9couter"}};var ne=2500,ie=1e3,se=1500,z=25e5,f=class extends Error{constructor(e,t){super(t??e),this.kind=e}},D=class{constructor(){this.recorder=null;this.stream=null;this.chunks=[];this.bytes=0;this.hardStopTimer=null;this.graceTimer=null;this.settled=!1}clearTimers(){this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.graceTimer&&clearTimeout(this.graceTimer),this.hardStopTimer=null,this.graceTimer=null}record(e,t){if(this.recorder&&!this.settled)return Promise.reject(new f("generic","record() called while a recording is in flight \u2014 ClipRecorder handles one recording at a time"));this.recorder=null,this.clearTimers(),this.chunks=[],this.bytes=0,this.settled=!1,this.stream=e;let n=W();return new Promise((r,s)=>{let a;try{a=new MediaRecorder(e,n?{mimeType:n,videoBitsPerSecond:z}:{videoBitsPerSecond:z})}catch{try{a=new MediaRecorder(e)}catch{s(new f("unsupported"));return}}this.recorder=a;let o=l=>{this.settled||(this.settled=!0,this.clearTimers(),l())},c=()=>o(()=>{let l=a.mimeType||n||O,u=new Blob(this.chunks,{type:l});if(_(u)){s(new f("cliptoolarge"));return}r({blob:u,mimeType:l})});a.ondataavailable=l=>{l.data&&l.data.size&&(this.chunks.push(l.data),this.bytes+=l.data.size,this.bytes>M&&o(()=>{try{a.state!=="inactive"&&a.stop()}catch{}s(new f("cliptoolarge"))}))},a.onstop=c,a.onerror=()=>o(()=>s(new f("generic")));try{a.start(ie)}catch{o(()=>s(new f("generic")));return}this.hardStopTimer=setTimeout(()=>{if(this.settled||t?.(),a.state!=="inactive"){try{a.stop()}catch{c()}this.graceTimer=setTimeout(c,se)}else c()},ne)})}stop(e){this.clearTimers();let t=this.recorder;if(t&&t.state!=="inactive")try{t.stop()}catch{}this.recorder=null,(e??this.stream)?.getTracks().forEach(r=>r.stop()),this.stream=null}};function K(i,e){return{video:{width:{ideal:1280,max:1280},height:{ideal:720,max:720},facingMode:e,frameRate:{ideal:24,max:30}},audio:!1}}function X(){return typeof window>"u"||typeof navigator>"u"?!1:window.innerWidth<=768||/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(String(navigator.userAgent??""))}var Le=.45,Pe=.9,Fe=.4;var ae=1e4,k=class i{constructor(e,t){this.tier="blaze";this.inner=e,t!==void 0&&(this.fallbackReason=t)}static async create(e,t){let n=await import("@mediapipe/tasks-vision"),r=await n.FilesetResolver.forVisionTasks(e),s=await n.FaceDetector.createFromOptions(r,{baseOptions:{modelAssetPath:`${e}/blaze_face_short_range.tflite`,delegate:"CPU"},runningMode:"IMAGE"});return new i(s,t)}async detect(e,t,n){let r;try{r=this.inner.detect(e).detections}catch{return null}let s=Ve(r);if(s?.boundingBox===void 0)return null;let a=v(e),o=Ne(s.keypoints,a),c={box:{x:s.boundingBox.originX,y:s.boundingBox.originY,width:s.boundingBox.width,height:s.boundingBox.height},...o!==void 0?{eyes:o}:{},score:s.categories[0]?.score??0};return S(c,e,t,n)}destroy(){try{this.inner.close()}catch{}}};function Ve(i){let e,t=-1;for(let n of i){let r=n.categories[0]?.score??0;r>t&&(e=n,t=r)}return e}function Ne(i,e){let t=i?.[0],n=i?.[1];if(t===void 0||n===void 0)return;let r=o=>({x:o.x*e.width,y:o.y*e.height}),[s,a]=[r(t),r(n)];return s.x<=a.x?{left:s,right:a}:{left:a,right:s}}function Ge(){if(typeof OffscreenCanvas=="function")return new OffscreenCanvas(2,2);let i=document.createElement("canvas");return i.width=2,i.height=2,i}async function oe(){let i=globalThis.FaceDetector;if(typeof i!="function")return{ok:!1,reason:"unsupported"};try{let e=new i({fastMode:!0,maxDetectedFaces:1});return await e.detect(Ge()),{ok:!0,instance:e}}catch(e){return{ok:!1,reason:`smoke_failed:${e instanceof Error?e.message:String(e)}`}}}var R=class{constructor(e,t){this.tier="native";this.inner=e,t!==void 0&&(this.fallbackReason=t)}async detect(e,t,n){let r;try{r=await this.inner.detect(e)}catch{return null}let s=r[0];if(s===void 0)return null;let a=We(s.landmarks),o={box:{x:s.boundingBox.x,y:s.boundingBox.y,width:s.boundingBox.width,height:s.boundingBox.height},...a!==void 0?{eyes:a}:{},score:1};return S(o,e,t,n)}destroy(){}};function We(i){if(i===void 0)return;let e=i.filter(r=>r.type==="eye").map(r=>r.locations[0]).filter(r=>r!==void 0),[t,n]=e;if(!(t===void 0||n===void 0))return t.x<=n.x?{left:t,right:n}:{left:n,right:t}}var ce="/models-v3",ue=["native","blaze"],y=class extends Error{constructor(e){super(`no detector tier available (${e})`),this.name="DetectorLadderError",this.fallbackReason=e}};function v(i){let e=i;if(typeof e.videoWidth=="number"&&e.videoWidth>0)return{width:e.videoWidth,height:e.videoHeight??0};if(typeof e.naturalWidth=="number"&&e.naturalWidth>0)return{width:e.naturalWidth,height:e.naturalHeight??0};let t=typeof e.width=="number"?e.width:0,n=typeof e.height=="number"?e.height:0;return{width:t,height:n}}function S(i,e,t,n){let r=v(e),s=r.width>0?t/r.width:1,a=r.height>0?n/r.height:1,o=c=>({x:c.x*s,y:c.y*a});return{box:{x:i.box.x*s,y:i.box.y*a,width:i.box.width*s,height:i.box.height*a},...i.eyes!==void 0?{eyes:{left:o(i.eyes.left),right:o(i.eyes.right)}}:{},score:i.score}}function Ue(i){return i instanceof Error?i.message:String(i)}async function b(i){let e=i.preferred??ue,t=[];for(let n of e){if(n==="native"){let r=await oe();if(r.ok)return new R(r.instance,q(t));t.push(`native:${r.reason}`);continue}try{return await He(k.create(i.v3AssetBaseUrl??ce,q(t)),i.blazeInitTimeoutMs??ae)}catch(r){t.push(r instanceof A?"blaze:blaze_init_timeout":`blaze:${Ue(r)}`)}}throw new y(q(t)??"no_tier_available")}function q(i){return i.length>0?i.join("; "):void 0}var A=class extends Error{};function He(i,e){return new Promise((t,n)=>{let r=setTimeout(()=>{n(new A(`init exceeded ${e}ms`)),i.then(s=>s.destroy(),()=>{})},e);i.then(s=>{clearTimeout(r),t(s)},s=>{clearTimeout(r),n(s)})})}var ht=180,x=[100,190],Be=64;function de(i,e){return .299*(i[e]??0)+.587*(i[e+1]??0)+.114*(i[e+2]??0)}function L(i){let{data:e,width:t,height:n}=i,r=t*n;if(r===0)return 0;let s=0;for(let a=0;a<r;a+=1)s+=de(e,a*4);return s/r}function P(i){let{data:e,width:t,height:n}=i;if(t<3||n<3)return 0;let r=new Float32Array(t*n);for(let u=0;u<r.length;u+=1)r[u]=de(e,u*4);let s=0,a=0,o=0;for(let u=1;u<n-1;u+=1)for(let d=1;d<t-1;d+=1){let m=u*t+d,p=(r[m-t]??0)+(r[m-1]??0)+(r[m+1]??0)+(r[m+t]??0)-4*(r[m]??0);s+=p,a+=p*p,o+=1}if(o===0)return 0;let c=s/o,l=a/o-c*c;return Math.min(1,Math.max(0,l)/180)}function Z(i){let e=L(i),[t,n]=x,r=e<t?t-e:e>n?e-n:0;return Math.max(0,1-r/Be)}var le=Object.freeze({Q_GOOD:.6,RISE_PER_S:.9,FALL_PER_S:.25,CENTER_FALLOFF_IOD_MULTIPLE:1.35,BOX_EYE_OFFSET_FACTOR:.12,IOD_BOX_PROXY_FACTOR:.42,SIZE_IDEAL_MIN:.12,SIZE_IDEAL_MAX:.3,SIZE_HARD_MIN:.08,SIZE_HARD_MAX:.45,ROLL_MAX_DEG:25,MOTION_VELOCITY_IOD_PER_S:.5,MOTION_TAU_S:.4,MOTION_DEADBAND_IOD_PER_S:.1,READY_WINDOW_MS:500,GUIDE_SIZE:.6,GUIDE_CENTERING:.6,GUIDE_POSE:.6,GUIDE_EXPOSURE:.6,GUIDE_SHARPNESS:.35,GUIDE_MOTION:.5}),E=i=>Math.min(1,Math.max(0,i)),T=class{constructor(e={}){this.p=0;this.lastTickAt=null;this.lastCenter=null;this.velocityEma=0;this.qWindow=[];this.lastSizeDirection="ideal";this.t={...le,...e}}reset(){this.p=0,this.lastTickAt=null,this.lastCenter=null,this.velocityEma=0,this.qWindow=[],this.lastSizeDirection="ideal"}tick(e){let{observation:t,quality:n,timestampMs:r}=e,s=this.lastTickAt===null?0:Math.max(0,(r-this.lastTickAt)/1e3);this.lastTickAt=r;let a={presence:0,centering:0,size:0,pose:0,sharpness:E(n.sharpness),exposure:E(n.exposure),motion:1};if(t!==null){a.presence=1;let u=this.geometryOf(t,e);a.centering=u.centering,a.size=u.size,a.pose=u.pose,a.motion=this.motionOf(u.center,u.iod,r)}else this.lastCenter=null,this.velocityEma=0;let o=Math.min(a.presence,a.centering,a.size,a.pose,a.sharpness,a.exposure,a.motion);this.p=E(this.p+(o>=this.t.Q_GOOD?this.t.RISE_PER_S*o:-this.t.FALL_PER_S*(1-o))*s),this.qWindow.push({at:r,q:o}),this.qWindow=this.qWindow.filter(u=>u.at>=r-this.t.READY_WINDOW_MS);let c=this.qWindow.map(u=>u.q);if(c.length>=3){let u=Math.min(...c),d=c.indexOf(u);c=c.filter((m,p)=>p!==d)}let l=this.p>=1&&c.every(u=>u>=this.t.Q_GOOD);return{at:r,q:o,p:this.p,factors:a,guidanceKey:this.guidanceOf(a,n,o),ready:l,accepted:o>=this.t.Q_GOOD}}geometryOf(e,t){let{box:n,eyes:r}=e,s={x:t.frameWidth/2,y:t.frameHeight/2},a=Math.min(t.frameWidth,t.frameHeight),o=r!==void 0?{x:(r.left.x+r.right.x)/2,y:(r.left.y+r.right.y)/2}:{x:n.x+n.width/2,y:n.y+n.height/2-this.t.BOX_EYE_OFFSET_FACTOR*n.height},c=r!==void 0?Math.hypot(r.right.x-r.left.x,r.right.y-r.left.y):this.t.IOD_BOX_PROXY_FACTOR*n.width,l=Math.hypot(o.x-s.x,o.y-s.y),u=c<=0?0:1-E(l/(this.t.CENTER_FALLOFF_IOD_MULTIPLE*c)),d=a>0?c/a:0;this.lastSizeDirection=d<this.t.SIZE_IDEAL_MIN?"far":d>this.t.SIZE_IDEAL_MAX?"close":"ideal";let m;d<this.t.SIZE_HARD_MIN||d>this.t.SIZE_HARD_MAX?m=0:d<this.t.SIZE_IDEAL_MIN?m=(d-this.t.SIZE_HARD_MIN)/(this.t.SIZE_IDEAL_MIN-this.t.SIZE_HARD_MIN):d>this.t.SIZE_IDEAL_MAX?m=(this.t.SIZE_HARD_MAX-d)/(this.t.SIZE_HARD_MAX-this.t.SIZE_IDEAL_MAX):m=1;let p=1;if(r!==void 0){let h=Math.abs(Math.atan2(r.right.y-r.left.y,r.right.x-r.left.x))*180/Math.PI;p=1-E(h/this.t.ROLL_MAX_DEG)}return{center:o,iod:c,centering:u,size:m,pose:p}}motionOf(e,t,n){let r=this.lastCenter;if(this.lastCenter={...e,at:n},r===null||t<=0)return 1;let s=(n-r.at)/1e3;if(s<=0)return 1;let a=Math.hypot(e.x-r.x,e.y-r.y)/t/s;a<=this.t.MOTION_DEADBAND_IOD_PER_S&&(a=0);let o=1-Math.exp(-s/this.t.MOTION_TAU_S);return this.velocityEma=o*a+(1-o)*this.velocityEma,1-E(this.velocityEma/this.t.MOTION_VELOCITY_IOD_PER_S)}guidanceOf(e,t,n){if(e.presence<=0)return"fcv3.no_face";if(e.size<this.t.GUIDE_SIZE)return this.sizeGuidance();if(e.centering<this.t.GUIDE_CENTERING)return"fcv3.center_face";if(e.pose<this.t.GUIDE_POSE)return"fcv3.straighten";if(e.exposure<this.t.GUIDE_EXPOSURE)return this.exposureGuidance(t);if(e.sharpness<this.t.GUIDE_SHARPNESS)return"fcv3.steady_camera";if(e.motion<this.t.GUIDE_MOTION)return"fcv3.hold_still";if(n<this.t.Q_GOOD){let r=[["size",this.sizeGuidance()],["centering","fcv3.center_face"],["pose","fcv3.straighten"],["exposure",this.exposureGuidance(t)],["sharpness","fcv3.steady_camera"],["motion","fcv3.hold_still"]],s=r[0];for(let a of r)e[a[0]]<e[s[0]]&&(s=a);return s[1]}return"fcv3.hold_still"}sizeGuidance(){return this.lastSizeDirection==="far"?"fcv3.come_closer":"fcv3.move_back"}exposureGuidance(e){let t=(x[0]+x[1])/2;return e.meanLuma<t?"fcv3.more_light":"fcv3.too_bright"}};var me=Object.freeze({LOW:Object.freeze({cadenceHz:5,inputWidth:128,animations:"reduced"}),MID:Object.freeze({cadenceHz:8,inputWidth:160,animations:"full"}),HIGH:Object.freeze({cadenceHz:10,inputWidth:192,animations:"full"})}),ze=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]);function Q(){let i=typeof navigator>"u"?void 0:navigator,e=!1;try{e=typeof WebAssembly<"u"&&WebAssembly.validate(ze)}catch{e=!1}return{cores:i?.hardwareConcurrency??2,memGB:i?.deviceMemory??null,simd:e}}function j(i){let e=i.memGB??4;return i.cores<4||e<3?"LOW":i.cores>=8&&e>=6?"HIGH":"MID"}var Y=["LOW","MID","HIGH"],C=class{constructor(e){this.samples=[];this.adjusted=!1;this.current=e}get deviceClass(){return this.current}get profile(){return me[this.current]}record(e){if(this.adjusted||this.samples.length>=10)return this.current;if(this.samples.push(e),this.samples.length<10)return this.current;this.adjusted=!0;let t=this.samples.reduce((n,r)=>n+r,0)/this.samples.length;if(t>70)this.current="LOW";else if(t<25){let n=Y.indexOf(this.current);this.current=Y[Math.min(Y.length-1,n+1)]??this.current}return this.current}};var I=class{constructor(e){this.timer=null;this.frameCallbackId=null;this.running=!1;this.busy=!1;this.lastRunAt=Number.NEGATIVE_INFINITY;this.degradeCount=0;this.durations=[];this.options=e,this.periodMs=1e3/e.cadenceHz}start(){if(this.running)return;this.running=!0;let e=this.options.video;if(typeof e?.requestVideoFrameCallback=="function"){let t=()=>{this.running&&(this.frameCallbackId=e.requestVideoFrameCallback?.(()=>{this.frameCallbackId=null,this.now()-this.lastRunAt>=this.periodMs&&this.tick(),t()}))};t();return}this.timer=setInterval(()=>this.tick(),this.periodMs)}stop(){this.running=!1,this.timer!==null&&(clearInterval(this.timer),this.timer=null),this.frameCallbackId!==null&&(this.options.video?.cancelVideoFrameCallback?.(this.frameCallbackId),this.frameCallbackId=null)}stats(){let e=this.durations.length===0?0:this.durations.reduce((t,n)=>t+n,0)/this.durations.length;return{degradeCount:this.degradeCount,meanDetectMs:e}}now(){return this.options.now?.()??performance.now()}tick(){if(!this.running)return;if(this.busy){this.degradeCount+=1;return}this.busy=!0,this.lastRunAt=this.now();let e=this.now();this.options.run().catch(()=>{}).finally(()=>{this.busy=!1,this.durations.push(this.now()-e),this.durations.length>20&&this.durations.shift()})}};var pe="0.1.0-rc.7";var he="sekyro.did",fe;function ge(){let i=globalThis.crypto;try{if(typeof i?.randomUUID=="function")return i.randomUUID()}catch{}try{if(typeof i?.getRandomValues=="function"){let e=i.getRandomValues(new Uint8Array(16));return Array.from(e,t=>t.toString(16).padStart(2,"0")).join("")}}catch{}}function Ke(){try{let i=localStorage.getItem(he);if(i)return i;let e=ge();return e!==void 0&&localStorage.setItem(he,e),e}catch{return fe??(fe=ge()),fe}}async function Xe(){let i=globalThis.crypto?.subtle;if(!i)return"";let e=navigator,t=JSON.stringify([e.userAgent,e.platform,e.hardwareConcurrency??null,e.deviceMemory??null,e.maxTouchPoints??0,screen.width,screen.height,screen.colorDepth,globalThis.devicePixelRatio??1,Intl.DateTimeFormat().resolvedOptions().timeZone,e.languages?.join(",")??e.language]),n=await i.digest("SHA-256",new TextEncoder().encode(t));return Array.from(new Uint8Array(n),r=>r.toString(16).padStart(2,"0")).join("").slice(0,32)}function qe(i){let e=new TextEncoder().encode(i),t="";for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Ze(i){let e,t;return{timezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone?.slice(0,64)||void 0}catch{return}},noteCameraLabel(n){n&&(e=n.slice(0,128))},async deviceHeader(){try{t??(t=Xe().catch(()=>""));let n=[];navigator.webdriver&&n.push("webdriver"),/HeadlessChrome/.test(navigator.userAgent)&&n.push("headless");let r=await t,s=Ke(),a={v:1,platform:"web",sdk:i.sdk.slice(0,64),ids:[...s?[{kind:"web_local",value:s.slice(0,128)}]:[],...r?[{kind:"web_fp",value:r}]:[]],screen:{w:screen.width,h:screen.height,dpr:globalThis.devicePixelRatio??1},...e?{cameraLabel:e}:{},...n.length?{signals:n}:{}};return qe(JSON.stringify(a))}catch{return}}}}var $=Symbol.for("sekyro.web.clientContext"),J=globalThis,Ye=J[$]??(J[$]=Ze({sdk:`@sekyro/web@${pe}`}));function ve(i){try{let e=i.getVideoTracks?.()[0];e&&Ye.noteCameraLabel(e.label)}catch{}}var g=1;function ye(){return typeof OffscreenCanvas=="function"&&typeof createImageBitmap=="function"&&typeof Worker=="function"}function Qe(i,e={}){let t=e.createDetector??b,n=null;i.onmessage=r=>{let s=r.data;if(s.v!==g){s.bitmap?.close?.();return}if(s.type==="init"){t(s.options).then(a=>{n=a;let o={v:g,type:"ready",tier:a.tier,...a.fallbackReason!==void 0?{fallbackReason:a.fallbackReason}:{}};i.postMessage(o)});return}if(s.type==="detect"){let a=o=>{let c={v:g,type:"result",id:s.id,observation:o};i.postMessage(c),s.bitmap.close?.()};if(n===null){a(null);return}n.detect(s.bitmap,s.streamWidth,s.streamHeight).then(a,()=>a(null))}}}typeof self<"u"&&typeof self.importScripts=="function"&&Qe(self);var F=class i{constructor(e,t){this.pending=new Map;this.nextId=1;this.worker=e,this.tier=t.tier,t.fallbackReason!==void 0&&(this.fallbackReason=t.fallbackReason),e.addEventListener("message",n=>{let r=n.data;if(r.v!==g||r.type!=="result")return;let s=this.pending.get(r.id);this.pending.delete(r.id),s?.(r.observation)})}static create(e,t,n=1e4){return new Promise((r,s)=>{let a=setTimeout(()=>{e.removeEventListener("message",o),e.terminate(),s(new Error(`worker detector not ready within ${n}ms`))},n),o=l=>{let u=l.data;u.v!==g||u.type!=="ready"||(clearTimeout(a),e.removeEventListener("message",o),r(new i(e,u)))};e.addEventListener("message",o);let c={v:g,type:"init",options:t};e.postMessage(c)})}async detect(e,t,n){let r;try{typeof ImageBitmap<"u"&&e instanceof ImageBitmap?r=e:typeof createImageBitmap=="function"?r=await createImageBitmap(e):r=e}catch{return null}let s=this.nextId;return this.nextId+=1,new Promise(a=>{this.pending.set(s,a);let o={v:g,type:"detect",id:s,bitmap:r,streamWidth:t,streamHeight:n};this.worker.postMessage(o,[r])})}destroy(){for(let e of this.pending.values())e(null);this.pending.clear(),this.worker.terminate()}};var V=4,_e=600,be={sharpness:1,exposure:1,meanLuma:128},ee=class{constructor(e){this.handlers=new Map;this.stateValue="idle";this.attempt=0;this.stream=null;this.detector=null;this.scheduler=null;this.gate=null;this.profiler=null;this.lastGuidanceKey=null;this.positioningStartedAt=0;this.cameraRequestedAt=null;this.cameraReadyAt=null;this.faceAcquiredAt=null;this.captureCompleteAt=null;this.fired=!1;this.carriedDegrade=0;this.carriedMeans=[];this.snapshotCanvas=null;this.options=e,this.facing=e.facingMode??"user"}get state(){return this.stateValue}on(e,t){let n=this.handlers.get(e);return n||(n=new Set,this.handlers.set(e,n)),n.add(t),()=>n?.delete(t)}emit(e,t){for(let n of[...this.handlers.get(e)??[]])n(t)}async start(e={}){e.facingMode!==void 0&&(this.facing=e.facingMode),this.attempt+=1,await this.run(this.attempt)}get facingMode(){return this.facing}retry(){this.teardownAttempt(),this.start()}switchCamera(){this.facing=this.facing==="user"?"environment":"user",this.teardownAttempt(),this.start()}destroy(){this.attempt+=1,this.teardownAttempt(),this.detector?.destroy(),this.detector=null,this.options.video.srcObject=null}async run(e){let{options:t}=this;this.fired=!1,this.lastGuidanceKey=null,this.carriedDegrade=0,this.carriedMeans=[],this.cameraRequestedAt=null,this.cameraReadyAt=null,this.faceAcquiredAt=null,this.captureCompleteAt=null,this.setState("preflight");let n=H();if(n!=="OK"){this.fail(n==="INSECURE_CONTEXT"?"insecure":"unsupported");return}this.setState("acquiring");let r=t.getUserMedia??(c=>navigator.mediaDevices.getUserMedia(c)),s;this.cameraRequestedAt=this.now();try{s=await r(K(X(),this.facing))}catch(c){if(e!==this.attempt)return;this.fail(U(c));return}if(ve(s),e!==this.attempt){for(let c of s.getTracks())c.stop();return}if(this.stream=s,t.video.srcObject=s,await t.video.play().catch(()=>{}),e!==this.attempt)return;if(this.cameraReadyAt=this.now(),this.detector===null){let c={...t.v3AssetBaseUrl!==void 0?{v3AssetBaseUrl:t.v3AssetBaseUrl}:{}},l=t.createDetector??(t.createWorker!==void 0&&ye()?async()=>{try{return await F.create(t.createWorker(),c)}catch{return b(c)}}:()=>b(c)),u;try{u=await l()}catch(d){e===this.attempt&&this.fail("models",d instanceof y?d.fallbackReason:$e(d));return}if(e!==this.attempt){u.destroy();return}this.detector=u,this.options.telemetry?.({type:"detector",tier:u.tier,...u.fallbackReason!==void 0?{fallbackReason:u.fallbackReason}:{}})}let a=Q(),o=t.deviceClass??j(a);this.profiler=new C(o),this.options.telemetry?.({type:"profile",staticClass:o,activeClass:this.profiler.deviceClass,simd:a.simd}),this.gate=new T(t.thresholds??{}),this.setState("positioning"),this.positioningStartedAt=this.now(),this.startScheduler(e)}get animations(){return this.profiler?.profile.animations??"full"}startScheduler(e){let t=this.profiler;if(t===null)return;if(this.scheduler!==null){let r=this.scheduler.stats();this.carriedDegrade+=r.degradeCount,r.meanDetectMs>0&&this.carriedMeans.push(r.meanDetectMs),this.scheduler.stop()}let n=new I({cadenceHz:t.profile.cadenceHz,video:this.options.video,...this.options.now!==void 0?{now:this.options.now}:{},run:()=>this.detectTick(e)});this.scheduler=n,n.start()}async detectTick(e){let{detector:t,gate:n,profiler:r}=this,s=this.options.video;if(e!==this.attempt||t===null||n===null||r===null||this.fired||s.videoWidth===0)return;let a=r.deviceClass,o=this.now(),c=this.options.makeSnapshot?.(s,r.profile.inputWidth)??this.defaultSnapshot(s,r.profile.inputWidth),l=null;try{l=await t.detect(c,s.videoWidth,s.videoHeight)}catch{l=null}if(e!==this.attempt||this.fired)return;r.record(this.now()-o),r.deviceClass!==a&&this.startScheduler(e);let u=l===null?be:this.options.measureQuality?.(s,l.box)??this.defaultQuality(s,l.box),d=n.tick({timestampMs:this.now(),observation:l,quality:u,frameWidth:s.videoWidth,frameHeight:s.videoHeight});d.accepted&&this.faceAcquiredAt===null&&(this.faceAcquiredAt=d.at),this.emit("checks",{engine:"v3",progress:d.p,q:d.q,factors:d.factors,attempt:e}),d.guidanceKey!==this.lastGuidanceKey&&(this.lastGuidanceKey=d.guidanceKey,this.emit("guidance",{key:d.guidanceKey})),d.ready&&this.stateValue==="positioning"&&(this.fired=!0,this.captureCompleteAt=d.at,this.fire(e))}async fire(e){let{options:t}=this,n=this.scheduler;n?.stop();let r=n?.stats()??{degradeCount:0,meanDetectMs:0},s=[...this.carriedMeans,...r.meanDetectMs>0?[r.meanDetectMs]:[]];t.telemetry?.({type:"fired",timeToGateMs:this.now()-this.positioningStartedAt,degradeCount:this.carriedDegrade+r.degradeCount,meanDetectMs:s.length===0?0:s.reduce((h,N)=>h+N,0)/s.length});let a=t.mode??"clip",o=this.collectKeyframes(e);if(a==="photo"){let h=await o;if(e!==this.attempt)return;if(h===null){this.fail("generic");return}this.finishCapture({keyframe:h.blob,previewDataUrl:h.previewDataUrl});return}this.setState("recording");let c=t.createRecorder?.()??new D,l=this.stream;if(l===null){this.fail("generic");return}let u=null;o.then(h=>{u=h},()=>{});let d=()=>{e===this.attempt&&u!==null&&this.emit("frozen",{previewDataUrl:u.previewDataUrl})},m,p;try{[m,p]=await Promise.all([c.record(l,d),o])}catch(h){if(e!==this.attempt)return;let N=h.kind;this.fail(N==="cliptoolarge"?"cliptoolarge":"recorder");return}if(e===this.attempt){if(_(m.blob)){this.fail("cliptoolarge");return}if(p===null){this.fail("generic");return}this.finishCapture({clip:m.blob,clipMimeType:m.mimeType,keyframe:p.blob,previewDataUrl:p.previewDataUrl})}}async collectKeyframes(e){let t=this.options.captureKeyframe??(s=>this.defaultKeyframe(s)),n=_e/(V-1),r=null;for(let s=0;s<V;s+=1){if(e!==this.attempt)return r;try{let a=await t(this.options.video);(r===null||a.sharpness>r.sharpness)&&(r=a)}catch{}s<V-1&&await je(n)}return r}finishCapture(e){this.stopTracks(),this.setState("captured");let t=this.captureTiming();this.emit("artifacts",t===void 0?e:{...e,timing:t})}captureTiming(){let e=(a,o)=>a!==null&&o!==null?Math.max(0,Math.round(o-a)):void 0,t=e(this.cameraRequestedAt,this.cameraReadyAt),n=e(this.cameraReadyAt,this.faceAcquiredAt),r=e(this.faceAcquiredAt,this.captureCompleteAt),s={...t!==void 0?{cameraReadyMs:t}:{},...n!==void 0?{faceAcquireMs:n}:{},...r!==void 0?{captureMs:r}:{}};return Object.keys(s).length>0?s:void 0}async defaultKeyframe(e){let t=document.createElement("canvas"),n=await B(e,t),r=t.toDataURL("image/jpeg",.92);return{blob:n,previewDataUrl:r,sharpness:this.centerSharpness(e)}}defaultSnapshot(e,t){try{let n=this.snapshotCanvas??document.createElement("canvas"),r=t/Math.max(1,e.videoWidth),s=Math.max(1,Math.round(e.videoWidth*r)),a=Math.max(1,Math.round(e.videoHeight*r)),o=n.getContext("2d");return o===null?e:(n.width!==s&&(n.width=s),n.height!==a&&(n.height=a),o.drawImage(e,0,0,s,a),this.snapshotCanvas=n,n)}catch{return e}}defaultQuality(e,t){let n=Ee(e,t,96);return n===null?be:{sharpness:P(n),exposure:Z(n),meanLuma:L(n)}}centerSharpness(e){let t=v(e),n=Ee(e,{x:t.width*.25,y:t.height*.25,width:t.width*.5,height:t.height*.5},96);return n===null?0:P(n)}teardownAttempt(){this.scheduler?.stop(),this.scheduler=null,this.gate=null,this.stopTracks()}stopTracks(){if(this.stream!==null){for(let e of this.stream.getTracks())e.stop();this.stream=null}}fail(e,t){this.scheduler?.stop(),this.stopTracks(),this.setState("error"),this.options.telemetry?.({type:"error",kind:e,...t!==void 0?{fallbackReason:t}:{}}),this.emit("error",{kind:e,retryable:e!=="insecure"&&e!=="unsupported"})}setState(e){this.stateValue=e,this.emit("statechange",{state:e})}now(){return this.options.now?.()??performance.now()}};function je(i){return new Promise(e=>setTimeout(e,i))}function $e(i){return i instanceof Error?i.message:String(i)}function Ee(i,e,t){try{let n=document.createElement("canvas"),r=t/Math.max(1,e.width);n.width=Math.max(1,Math.round(e.width*r)),n.height=Math.max(1,Math.round(e.height*r));let s=n.getContext("2d");return s===null?null:(s.drawImage(i,e.x,e.y,e.width,e.height,0,0,n.width,n.height),s.getImageData(0,0,n.width,n.height))}catch{return null}}0&&(module.exports={CENTERED_FACTOR,CIRCLE_RADIUS_FACTOR,CLIP_MS,CaptureSessionV3,ClipError,ClipRecorder,DEFAULT_CLIP_MIME,DEFAULT_TIER_ORDER,DEFAULT_V3_ASSET_BASE_URL,DEVICE_PROFILES,DetectScheduler,DetectorLadderError,DeviceProfiler,EXPOSURE_BAND,FaceGateV3,IN_CIRCLE_FACTOR,KEYFRAME_CANDIDATES,KEYFRAME_WINDOW_MS,MAX_CLIP_BYTES,MIME_CANDIDATES,SHARP_REF,STOP_GRACE_MS,TIMESLICE_MS,V3_GATE_DEFAULTS,VIDEO_BPS,buildCaptureConstraints,buildLivenessV2FormData,cameraPreflight,captureMirroredKeyframe,classifyDevice,createDetector,detectIsMobile,errorCopy,exposure,extForMime,intrinsicSize,isClipTooLarge,isMediaRecorderSupported,mapGetUserMediaError,meanLuma,pickMimeType,probeDevice,sharpness,toStreamPixels,uiCopy});
|
|
1
|
+
"use strict";var Xe=Object.create;var P=Object.defineProperty;var qe=Object.getOwnPropertyDescriptor;var Ye=Object.getOwnPropertyNames;var Ze=Object.getPrototypeOf,Qe=Object.prototype.hasOwnProperty;var je=(t,e)=>()=>(t&&(e=t(t=0)),e);var ue=(t,e)=>{for(var r in e)P(t,r,{get:e[r],enumerable:!0})},le=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Ye(e))!Qe.call(t,n)&&n!==r&&P(t,n,{get:()=>e[n],enumerable:!(i=qe(e,n))||i.enumerable});return t};var $e=(t,e,r)=>(r=t!=null?Xe(Ze(t)):{},le(e||!t||!t.__esModule?P(r,"default",{value:t,enumerable:!0}):r,t)),Je=t=>le(P({},"__esModule",{value:!0}),t);var Fe={};ue(Fe,{RANK_CANDIDATES:()=>xt,RANK_TOLERANCE:()=>B,RANK_WINDOW_MS:()=>St,ROLL_ZERO_DEG:()=>kt,SHARPNESS_REPORT_MAX:()=>Pe,YAW_REPORT_MAX:()=>Ae,YAW_ZERO_IOD:()=>Dt,collectRankedKeyframes:()=>Le,default:()=>Ct,featuresOf:()=>Ie,frontalOf:()=>Oe,rankKeyframes:()=>Re});function Oe(t){let e=t.eyes;if(e===void 0)return{frontal:1,yaw:null,roll:null};let r=e.right.x-e.left.x,i=e.right.y-e.left.y,n=r*r+i*i;if(n===0)return{frontal:1,yaw:null,roll:null};let a=Math.abs(Math.atan2(i,Math.abs(r))*180/Math.PI),s=we(1-a/30),o=null,c=t.nose;if(c!==void 0){let d=(e.left.x+e.right.x)/2,u=(e.left.y+e.right.y)/2;o=Math.abs(((c.x-d)*r+(c.y-u)*i)/n),s*=we(1-o/.5)}return{frontal:s,yaw:o,roll:a}}function Ie(t,e){return t===null?{face:!1,frontal:0,yaw:null,roll:null,eyes:null,score:0,sharpness:e}:{face:!0,...Oe(t),eyes:null,score:t.score,sharpness:e}}function Re(t){let e=t.map((n,a)=>a),r=(n,a)=>{let s=Number.NEGATIVE_INFINITY;for(let o of e)s=Math.max(s,n(t[o]));e=e.filter(o=>n(t[o])>=s-a)};r(n=>n.frontal,B.frontal),r(n=>n.eyes??1,B.eyes),r(n=>n.score,B.score);let i=-1;for(let n of e)(i===-1||t[n].sharpness>t[i].sharpness)&&(i=n);return i}function Tt(t){return{face:t.face,frontal:x(t.frontal),...t.yaw!==null?{yaw:Math.min(x(t.yaw),Ae)}:{},...t.roll!==null?{roll:x(t.roll)}:{},...t.eyes!==null?{eyes:x(t.eyes)}:{},score:x(t.score),sharpness:Math.min(x(t.sharpness),Pe)}}async function Le(t,e){let{options:r}=t,i=r.video,n=r.now??(()=>performance.now()),a=r.captureKeyframe??(m=>t.defaultKeyframe(m)),s=600/3,o=[],c=[],d=0;for(let m=0;m<4;m+=1){if(e!==t.attempt)return null;let p=t.detector,h=Promise.resolve(null),y,I=0;try{if(p!==null){let A=t.profiler?.profile.inputWidth??160,Ue=r.makeSnapshot?.(i,A)??t.defaultSnapshot(i,A);y=a(i).then(z=>(I=n(),z));let ze=n();h=p.detect(Ue,i.videoWidth,i.videoHeight).then(z=>(d+=n()-ze,z),()=>null)}else y=a(i).then(A=>(I=n(),A));let[R,Be]=await Promise.all([y,h]);o.push(R),c.push(Ie(Be,R.sharpness))}catch{y?.catch(()=>{})}let He=I>0?Math.max(0,n()-I):0;m<3&&await new Promise(R=>setTimeout(R,Math.max(0,s-He)))}if(e!==t.attempt)return null;let u=Re(c);if(u===-1)return null;let l=0;c.forEach((m,p)=>{m.sharpness>c[l].sharpness&&(l=p)});try{r.telemetry?.({type:"keyframe",tier:t.detector?.tier??null,chosen:u,sharpest:l,detectMs:Math.round(d),candidates:c.map(Tt)})}catch{}return o[u]??null}var xt,St,Dt,kt,B,we,x,Ae,Pe,Ct,Ne=je(()=>{"use strict";xt=4,St=600,Dt=.5,kt=30,B={frontal:.1,eyes:.1,score:.05},we=t=>t<0?0:t>1?1:t;x=t=>Number.isFinite(t)?Math.round(t*1e3)/1e3:0,Ae=99,Pe=999999;Ct=Le});var Ot={};ue(Ot,{CENTERED_FACTOR:()=>st,CIRCLE_RADIUS_FACTOR:()=>it,CLIP_MS:()=>me,CaptureSessionV3:()=>ce,ClipError:()=>f,ClipRecorder:()=>D,DEFAULT_CLIP_MIME:()=>L,DEFAULT_TIER_ORDER:()=>ge,DEFAULT_V3_ASSET_BASE_URL:()=>be,DEVICE_PROFILES:()=>_e,DetectScheduler:()=>w,DetectorLadderError:()=>v,DeviceProfiler:()=>M,EXPOSURE_BAND:()=>T,FaceGateV3:()=>C,GATE_SNAPSHOT_MS:()=>We,GateBlockStats:()=>O,IN_CIRCLE_FACTOR:()=>at,KEYFRAME_CANDIDATES:()=>U,KEYFRAME_WINDOW_MS:()=>Ke,MAX_CLIP_BYTES:()=>F,MIME_CANDIDATES:()=>de,SHARP_REF:()=>zt,STOP_GRACE_MS:()=>he,TIMESLICE_MS:()=>pe,V3_GATE_DEFAULTS:()=>Ee,VIDEO_BPS:()=>j,blockReasonOf:()=>Me,buildCaptureConstraints:()=>$,buildLivenessV2FormData:()=>tt,cameraPreflight:()=>Z,captureMirroredKeyframe:()=>Q,classifyDevice:()=>ie,createDetector:()=>E,detectIsMobile:()=>J,errorCopy:()=>rt,exposure:()=>te,extForMime:()=>X,intrinsicSize:()=>g,isClipTooLarge:()=>S,isMediaRecorderSupported:()=>et,mapGetUserMediaError:()=>Y,meanLuma:()=>W,pickMimeType:()=>q,probeDevice:()=>ne,sharpness:()=>K,toStreamPixels:()=>k,uiCopy:()=>nt});module.exports=Je(Ot);var de=["video/mp4;codecs=avc1.42E01E,mp4a.40.2","video/mp4;codecs=avc1.42E01E","video/mp4","video/webm;codecs=vp9,opus","video/webm;codecs=vp9","video/webm;codecs=vp8,opus","video/webm;codecs=vp8","video/webm"];function q(){let t=globalThis.MediaRecorder;return!t||typeof t.isTypeSupported!="function"?"":de.find(e=>t.isTypeSupported(e))??""}var L="video/webm";function Y(t){if(t instanceof TypeError)return"insecure";switch(t?.name??""){case"NotAllowedError":case"PermissionDeniedError":return"permission";case"NotFoundError":case"DevicesNotFoundError":return"notfound";case"NotReadableError":case"TrackStartError":return"inuse";case"OverconstrainedError":case"ConstraintNotSatisfiedError":return"overconstrained";default:return"generic"}}function Z(){let t=globalThis;if(typeof t.window<"u"&&t.window.isSecureContext===!1)return"INSECURE_CONTEXT";let e=t.navigator?.mediaDevices;return!e||typeof e.getUserMedia!="function"?"UNSUPPORTED":"OK"}function et(){let t=globalThis.MediaRecorder;return typeof t<"u"&&typeof t.isTypeSupported=="function"}var F=8*1024*1024;function S(t){return t.size>F}function X(t){let e=(t||"").toLowerCase();return e.startsWith("image/jpeg")?"jpg":e.startsWith("video/mp4")?"mp4":(e.startsWith("video/webm"),"webm")}function tt(t){let{token:e,clip:r,keyframe:i}=t,n=t.ts??Date.now(),a=r.type||L,s=i.type||"image/jpeg",o=new FormData;return o.append("token",e),o.append("clip",new File([r],`liveness-${n}.${X(a)}`,{type:a})),o.append("keyframe",new File([i],`keyframe-${n}.${X(s)}`,{type:s})),o}function Q(t,e,r=.92){return new Promise((i,n)=>{let a=t.videoWidth,s=t.videoHeight;if(!a||!s){n(new Error("video-not-ready"));return}let o=e.getContext("2d");if(!o){n(new Error("no-2d-context"));return}e.width=a,e.height=s,o.scale(-1,1),o.drawImage(t,-a,0),e.toBlob(c=>c?i(c):n(new Error("empty-keyframe")),"image/jpeg",r)})}var rt={permission:{key:"fcv2.err.permission",fr:"Autorisez la cam\xE9ra dans les r\xE9glages du navigateur (ic\xF4ne cam\xE9ra dans la barre d\u2019adresse), puis r\xE9essayez."},notfound:{key:"fcv2.err.notfound",fr:"Aucune cam\xE9ra d\xE9tect\xE9e. Branchez ou activez une cam\xE9ra, puis r\xE9essayez."},inuse:{key:"fcv2.err.inuse",fr:"La cam\xE9ra est utilis\xE9e par une autre application. Fermez-la puis r\xE9essayez."},overconstrained:{key:"fcv2.err.overconstrained",fr:"La cam\xE9ra ne prend pas en charge les r\xE9glages demand\xE9s. Nouvel essai en cours\u2026"},insecure:{key:"fcv2.err.insecure",fr:"La cam\xE9ra n\xE9cessite une connexion s\xE9curis\xE9e (HTTPS). Ouvrez la page en HTTPS."},unsupported:{key:"fcv2.err.unsupported",fr:"Votre navigateur ne prend pas en charge l\u2019enregistrement vid\xE9o. Utilisez un navigateur r\xE9cent."},generic:{key:"fcv2.err.generic",fr:"Cam\xE9ra indisponible. R\xE9essayez ou contactez le support."}},nt={recording:{key:"fcv2.recording",fr:"Enregistrement en cours\u2026"},uploading:{key:"fcv2.uploading",fr:"Envoi en cours\u2026"},clipTooLarge:{key:"fcv2.err.cliptoolarge",fr:"La vid\xE9o est trop volumineuse. R\xE9essayez dans un endroit mieux \xE9clair\xE9."},retry:{key:"fcv2.retry",fr:"R\xE9essayer"},listen:{key:"fcv2.listen",fr:"\xC9couter"}};var me=2500,pe=1e3,he=1500,j=25e5,f=class extends Error{constructor(e,r){super(r??e),this.kind=e}},D=class{constructor(){this.recorder=null;this.stream=null;this.chunks=[];this.bytes=0;this.hardStopTimer=null;this.graceTimer=null;this.settled=!1}clearTimers(){this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.graceTimer&&clearTimeout(this.graceTimer),this.hardStopTimer=null,this.graceTimer=null}record(e,r){if(this.recorder&&!this.settled)return Promise.reject(new f("generic","record() called while a recording is in flight \u2014 ClipRecorder handles one recording at a time"));this.recorder=null,this.clearTimers(),this.chunks=[],this.bytes=0,this.settled=!1,this.stream=e;let i=q();return new Promise((n,a)=>{let s;try{s=new MediaRecorder(e,i?{mimeType:i,videoBitsPerSecond:j}:{videoBitsPerSecond:j})}catch{try{s=new MediaRecorder(e)}catch{a(new f("unsupported"));return}}this.recorder=s;let o=d=>{this.settled||(this.settled=!0,this.clearTimers(),d())},c=()=>o(()=>{let d=s.mimeType||i||L,u=new Blob(this.chunks,{type:d});if(u.size===0){a(new f("generic","empty clip"));return}if(S(u)){a(new f("cliptoolarge"));return}n({blob:u,mimeType:d})});s.ondataavailable=d=>{d.data&&d.data.size&&(this.chunks.push(d.data),this.bytes+=d.data.size,this.bytes>F&&o(()=>{try{s.state!=="inactive"&&s.stop()}catch{}a(new f("cliptoolarge"))}))},s.onstop=c,s.onerror=()=>o(()=>a(new f("generic")));try{s.start(pe)}catch{o(()=>a(new f("generic")));return}this.hardStopTimer=setTimeout(()=>{if(this.settled||r?.(),s.state!=="inactive"){try{s.stop()}catch{c()}this.graceTimer=setTimeout(c,he)}else c()},me)})}stop(e){this.clearTimers();let r=this.recorder;if(r&&r.state!=="inactive")try{r.stop()}catch{}this.recorder=null,(e??this.stream)?.getTracks().forEach(n=>n.stop()),this.stream=null}};function $(t,e){return{video:{width:{ideal:1280,max:1280},height:{ideal:720,max:720},facingMode:e,frameRate:{ideal:24,max:30}},audio:!1}}function J(){return typeof window>"u"||typeof navigator>"u"?!1:window.innerWidth<=768||/Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(String(navigator.userAgent??""))}var it=.45,at=.9,st=.4;var fe=1e4,N=class t{constructor(e,r){this.tier="blaze";this.inner=e,r!==void 0&&(this.fallbackReason=r)}static async create(e,r){let i=await import("@mediapipe/tasks-vision"),n=await i.FilesetResolver.forVisionTasks(e),a=await i.FaceDetector.createFromOptions(n,{baseOptions:{modelAssetPath:`${e}/blaze_face_short_range.tflite`,delegate:"CPU"},runningMode:"IMAGE"});return new t(a,r)}async detect(e,r,i){let n;try{n=this.inner.detect(e).detections}catch{return null}let a=ot(n);if(a?.boundingBox===void 0)return null;let s=g(e),o=ct(a.keypoints,s),c=a.keypoints?.[2],d={box:{x:a.boundingBox.originX,y:a.boundingBox.originY,width:a.boundingBox.width,height:a.boundingBox.height},...o!==void 0?{eyes:o}:{},...c!==void 0?{nose:{x:c.x*s.width,y:c.y*s.height}}:{},score:a.categories[0]?.score??0};return k(d,e,r,i)}destroy(){try{this.inner.close()}catch{}}};function ot(t){let e,r=-1;for(let i of t){let n=i.categories[0]?.score??0;n>r&&(e=i,r=n)}return e}function ct(t,e){let r=t?.[0],i=t?.[1];if(r===void 0||i===void 0)return;let n=o=>({x:o.x*e.width,y:o.y*e.height}),[a,s]=[n(r),n(i)];return a.x<=s.x?{left:a,right:s}:{left:s,right:a}}function ut(){if(typeof OffscreenCanvas=="function")return new OffscreenCanvas(2,2);let t=document.createElement("canvas");return t.width=2,t.height=2,t}async function ye(){let t=globalThis.FaceDetector;if(typeof t!="function")return{ok:!1,reason:"unsupported"};try{let e=new t({fastMode:!0,maxDetectedFaces:1});return await e.detect(ut()),{ok:!0,instance:e}}catch(e){return{ok:!1,reason:`smoke_failed:${e instanceof Error?e.message:String(e)}`}}}var G=class{constructor(e,r){this.tier="native";this.inner=e,r!==void 0&&(this.fallbackReason=r)}async detect(e,r,i){let n;try{n=await this.inner.detect(e)}catch{return null}let a=n[0];if(a===void 0)return null;let s=lt(a.landmarks),o={box:{x:a.boundingBox.x,y:a.boundingBox.y,width:a.boundingBox.width,height:a.boundingBox.height},...s!==void 0?{eyes:s}:{},score:1};return k(o,e,r,i)}destroy(){}};function lt(t){if(t===void 0)return;let e=t.filter(n=>n.type==="eye").map(n=>n.locations[0]).filter(n=>n!==void 0),[r,i]=e;if(!(r===void 0||i===void 0))return r.x<=i.x?{left:r,right:i}:{left:i,right:r}}var be="/models-v3",ge=["native","blaze"],v=class extends Error{constructor(e){super(`no detector tier available (${e})`),this.name="DetectorLadderError",this.fallbackReason=e}};function g(t){let e=t;if(typeof e.videoWidth=="number"&&e.videoWidth>0)return{width:e.videoWidth,height:e.videoHeight??0};if(typeof e.naturalWidth=="number"&&e.naturalWidth>0)return{width:e.naturalWidth,height:e.naturalHeight??0};let r=typeof e.width=="number"?e.width:0,i=typeof e.height=="number"?e.height:0;return{width:r,height:i}}function k(t,e,r,i){let n=g(e),a=n.width>0?r/n.width:1,s=n.height>0?i/n.height:1,o=c=>({x:c.x*a,y:c.y*s});return{box:{x:t.box.x*a,y:t.box.y*s,width:t.box.width*a,height:t.box.height*s},...t.eyes!==void 0?{eyes:{left:o(t.eyes.left),right:o(t.eyes.right)}}:{},...t.nose!==void 0?{nose:o(t.nose)}:{},score:t.score}}function dt(t){return t instanceof Error?t.message:String(t)}async function E(t){let e=t.preferred??ge,r=[];for(let i of e){if(i==="native"){let n=await ye();if(n.ok)return new G(n.instance,ee(r));r.push(`native:${n.reason}`);continue}try{return await mt(N.create(t.v3AssetBaseUrl??be,ee(r)),t.blazeInitTimeoutMs??fe)}catch(n){r.push(n instanceof V?"blaze:blaze_init_timeout":`blaze:${dt(n)}`)}}throw new v(ee(r)??"no_tier_available")}function ee(t){return t.length>0?t.join("; "):void 0}var V=class extends Error{};function mt(t,e){return new Promise((r,i)=>{let n=setTimeout(()=>{i(new V(`init exceeded ${e}ms`)),t.then(a=>a.destroy(),()=>{})},e);t.then(a=>{clearTimeout(n),r(a)},a=>{clearTimeout(n),i(a)})})}var zt=180,T=[100,190],pt=64;function ve(t,e){return .299*(t[e]??0)+.587*(t[e+1]??0)+.114*(t[e+2]??0)}function W(t){let{data:e,width:r,height:i}=t,n=r*i;if(n===0)return 0;let a=0;for(let s=0;s<n;s+=1)a+=ve(e,s*4);return a/n}function K(t){let{data:e,width:r,height:i}=t;if(r<3||i<3)return 0;let n=new Float32Array(r*i);for(let u=0;u<n.length;u+=1)n[u]=ve(e,u*4);let a=0,s=0,o=0;for(let u=1;u<i-1;u+=1)for(let l=1;l<r-1;l+=1){let m=u*r+l,p=(n[m-r]??0)+(n[m-1]??0)+(n[m+1]??0)+(n[m+r]??0)-4*(n[m]??0);a+=p,s+=p*p,o+=1}if(o===0)return 0;let c=a/o,d=s/o-c*c;return Math.min(1,Math.max(0,d)/180)}function te(t){let e=W(t),[r,i]=T,n=e<r?r-e:e>i?e-i:0;return Math.max(0,1-n/pt)}var Ee=Object.freeze({Q_GOOD:.6,RISE_PER_S:.9,FALL_PER_S:.25,CENTER_FALLOFF_IOD_MULTIPLE:1.35,BOX_EYE_OFFSET_FACTOR:.12,IOD_BOX_PROXY_FACTOR:.42,SIZE_IDEAL_MIN:.12,SIZE_IDEAL_MAX:.3,SIZE_HARD_MIN:.08,SIZE_HARD_MAX:.45,ROLL_MAX_DEG:25,MOTION_VELOCITY_IOD_PER_S:.5,MOTION_TAU_S:.4,MOTION_DEADBAND_IOD_PER_S:.1,READY_WINDOW_MS:500,GUIDE_SIZE:.6,GUIDE_CENTERING:.6,GUIDE_POSE:.6,GUIDE_EXPOSURE:.6,GUIDE_SHARPNESS:.35,GUIDE_MOTION:.5}),_=t=>Math.min(1,Math.max(0,t)),C=class{constructor(e={}){this.p=0;this.lastTickAt=null;this.lastCenter=null;this.velocityEma=0;this.qWindow=[];this.lastSizeDirection="ideal";this.t={...Ee,...e}}reset(){this.p=0,this.lastTickAt=null,this.lastCenter=null,this.velocityEma=0,this.qWindow=[],this.lastSizeDirection="ideal"}tick(e){let{observation:r,quality:i,timestampMs:n}=e,a=this.lastTickAt===null?0:Math.max(0,(n-this.lastTickAt)/1e3);this.lastTickAt=n;let s={presence:0,centering:0,size:0,pose:0,sharpness:_(i.sharpness),exposure:_(i.exposure),motion:1};if(r!==null){s.presence=1;let u=this.geometryOf(r,e);s.centering=u.centering,s.size=u.size,s.pose=u.pose,s.motion=this.motionOf(u.center,u.iod,n)}else this.lastCenter=null,this.velocityEma=0;let o=Math.min(s.presence,s.centering,s.size,s.pose,s.sharpness,s.exposure,s.motion);this.p=_(this.p+(o>=this.t.Q_GOOD?this.t.RISE_PER_S*o:-this.t.FALL_PER_S*(1-o))*a),this.qWindow.push({at:n,q:o}),this.qWindow=this.qWindow.filter(u=>u.at>=n-this.t.READY_WINDOW_MS);let c=this.qWindow.map(u=>u.q);if(c.length>=3){let u=Math.min(...c),l=c.indexOf(u);c=c.filter((m,p)=>p!==l)}let d=this.p>=1&&c.every(u=>u>=this.t.Q_GOOD);return{at:n,q:o,p:this.p,factors:s,guidanceKey:this.guidanceOf(s,i,o),ready:d,accepted:o>=this.t.Q_GOOD}}geometryOf(e,r){let{box:i,eyes:n}=e,a={x:r.frameWidth/2,y:r.frameHeight/2},s=Math.min(r.frameWidth,r.frameHeight),o=n!==void 0?{x:(n.left.x+n.right.x)/2,y:(n.left.y+n.right.y)/2}:{x:i.x+i.width/2,y:i.y+i.height/2-this.t.BOX_EYE_OFFSET_FACTOR*i.height},c=n!==void 0?Math.hypot(n.right.x-n.left.x,n.right.y-n.left.y):this.t.IOD_BOX_PROXY_FACTOR*i.width,d=Math.hypot(o.x-a.x,o.y-a.y),u=c<=0?0:1-_(d/(this.t.CENTER_FALLOFF_IOD_MULTIPLE*c)),l=s>0?c/s:0;this.lastSizeDirection=l<this.t.SIZE_IDEAL_MIN?"far":l>this.t.SIZE_IDEAL_MAX?"close":"ideal";let m;l<this.t.SIZE_HARD_MIN||l>this.t.SIZE_HARD_MAX?m=0:l<this.t.SIZE_IDEAL_MIN?m=(l-this.t.SIZE_HARD_MIN)/(this.t.SIZE_IDEAL_MIN-this.t.SIZE_HARD_MIN):l>this.t.SIZE_IDEAL_MAX?m=(this.t.SIZE_HARD_MAX-l)/(this.t.SIZE_HARD_MAX-this.t.SIZE_IDEAL_MAX):m=1;let p=1;if(n!==void 0){let h=Math.abs(Math.atan2(n.right.y-n.left.y,n.right.x-n.left.x))*180/Math.PI;p=1-_(h/this.t.ROLL_MAX_DEG)}return{center:o,iod:c,centering:u,size:m,pose:p}}motionOf(e,r,i){let n=this.lastCenter;if(this.lastCenter={...e,at:i},n===null||r<=0)return 1;let a=(i-n.at)/1e3;if(a<=0)return 1;let s=Math.hypot(e.x-n.x,e.y-n.y)/r/a;s<=this.t.MOTION_DEADBAND_IOD_PER_S&&(s=0);let o=1-Math.exp(-a/this.t.MOTION_TAU_S);return this.velocityEma=o*s+(1-o)*this.velocityEma,1-_(this.velocityEma/this.t.MOTION_VELOCITY_IOD_PER_S)}guidanceOf(e,r,i){if(e.presence<=0)return"fcv3.no_face";if(e.size<this.t.GUIDE_SIZE)return this.sizeGuidance();if(e.centering<this.t.GUIDE_CENTERING)return"fcv3.center_face";if(e.pose<this.t.GUIDE_POSE)return"fcv3.straighten";if(e.exposure<this.t.GUIDE_EXPOSURE)return this.exposureGuidance(r);if(e.sharpness<this.t.GUIDE_SHARPNESS)return"fcv3.steady_camera";if(e.motion<this.t.GUIDE_MOTION)return"fcv3.hold_still";if(i<this.t.Q_GOOD){let n=[["size",this.sizeGuidance()],["centering","fcv3.center_face"],["pose","fcv3.straighten"],["exposure",this.exposureGuidance(r)],["sharpness","fcv3.steady_camera"],["motion","fcv3.hold_still"]],a=n[0];for(let s of n)e[s[0]]<e[a[0]]&&(a=s);return a[1]}return"fcv3.hold_still"}sizeGuidance(){return this.lastSizeDirection==="far"?"fcv3.come_closer":"fcv3.move_back"}exposureGuidance(e){let r=(T[0]+T[1])/2;return e.meanLuma<r?"fcv3.more_light":"fcv3.too_bright"}};var _e=Object.freeze({LOW:Object.freeze({cadenceHz:5,inputWidth:128,animations:"reduced"}),MID:Object.freeze({cadenceHz:8,inputWidth:160,animations:"full"}),HIGH:Object.freeze({cadenceHz:10,inputWidth:192,animations:"full"})}),ht=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]);function ne(){let t=typeof navigator>"u"?void 0:navigator,e=!1;try{e=typeof WebAssembly<"u"&&WebAssembly.validate(ht)}catch{e=!1}return{cores:t?.hardwareConcurrency??2,memGB:t?.deviceMemory??null,simd:e}}function ie(t){let e=t.memGB??4;return t.cores<4||e<3?"LOW":t.cores>=8&&e>=6?"HIGH":"MID"}var re=["LOW","MID","HIGH"],M=class{constructor(e){this.samples=[];this.adjusted=!1;this.current=e}get deviceClass(){return this.current}get profile(){return _e[this.current]}record(e){if(this.adjusted||this.samples.length>=10)return this.current;if(this.samples.push(e),this.samples.length<10)return this.current;this.adjusted=!0;let r=this.samples.reduce((i,n)=>i+n,0)/this.samples.length;if(r>70)this.current="LOW";else if(r<25){let i=re.indexOf(this.current);this.current=re[Math.min(re.length-1,i+1)]??this.current}return this.current}};var w=class{constructor(e){this.timer=null;this.frameCallbackId=null;this.running=!1;this.busy=!1;this.lastRunAt=Number.NEGATIVE_INFINITY;this.degradeCount=0;this.durations=[];this.options=e,this.periodMs=1e3/e.cadenceHz}start(){if(this.running)return;this.running=!0;let e=this.options.video;if(typeof e?.requestVideoFrameCallback=="function"){let r=()=>{this.running&&(this.frameCallbackId=e.requestVideoFrameCallback?.(()=>{this.frameCallbackId=null,this.now()-this.lastRunAt>=this.periodMs&&this.tick(),r()}))};r();return}this.timer=setInterval(()=>this.tick(),this.periodMs)}stop(){this.running=!1,this.timer!==null&&(clearInterval(this.timer),this.timer=null),this.frameCallbackId!==null&&(this.options.video?.cancelVideoFrameCallback?.(this.frameCallbackId),this.frameCallbackId=null)}stats(){let e=this.durations.length===0?0:this.durations.reduce((r,i)=>r+i,0)/this.durations.length;return{degradeCount:this.degradeCount,meanDetectMs:e}}now(){return this.options.now?.()??performance.now()}tick(){if(!this.running)return;if(this.busy){this.degradeCount+=1;return}this.busy=!0,this.lastRunAt=this.now();let e=this.now();this.options.run().catch(()=>{}).finally(()=>{this.busy=!1,this.durations.push(this.now()-e),this.durations.length>20&&this.durations.shift()})}};var xe="0.1.0-rc.8";var Se="sekyro.did",De;function ke(){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 ft(){try{let t=localStorage.getItem(Se);if(t)return t;let e=ke();return e!==void 0&&localStorage.setItem(Se,e),e}catch{return De??(De=ke()),De}}async function yt(){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),n=>n.toString(16).padStart(2,"0")).join("").slice(0,32)}function bt(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 gt(t){let e,r;return{timezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone?.slice(0,64)||void 0}catch{return}},noteCameraLabel(i){i&&(e=i.slice(0,128))},async deviceHeader(){try{r??(r=yt().catch(()=>""));let i=[];navigator.webdriver&&i.push("webdriver"),/HeadlessChrome/.test(navigator.userAgent)&&i.push("headless");let n=await r,a=ft(),s={v:1,platform:"web",sdk:t.sdk.slice(0,64),ids:[...a?[{kind:"web_local",value:a.slice(0,128)}]:[],...n?[{kind:"web_fp",value:n}]:[]],screen:{w:screen.width,h:screen.height,dpr:globalThis.devicePixelRatio??1},...e?{cameraLabel:e}:{},...i.length?{signals:i}:{}};return bt(JSON.stringify(s))}catch{return}}}}var ae=Symbol.for("sekyro.web.clientContext"),se=globalThis,vt=se[ae]??(se[ae]=gt({sdk:`@sekyro/web@${xe}`}));function Te(t){try{let e=t.getVideoTracks?.()[0];e&&vt.noteCameraLabel(e.label)}catch{}}var b=1;function Ce(){return typeof OffscreenCanvas=="function"&&typeof createImageBitmap=="function"&&typeof Worker=="function"}function Et(t,e={}){let r=e.createDetector??E,i=null;t.onmessage=n=>{let a=n.data;if(a.v!==b){a.bitmap?.close?.();return}if(a.type==="init"){r(a.options).then(s=>{i=s;let o={v:b,type:"ready",tier:s.tier,...s.fallbackReason!==void 0?{fallbackReason:s.fallbackReason}:{}};t.postMessage(o)});return}if(a.type==="detect"){let s=o=>{let c={v:b,type:"result",id:a.id,observation:o};t.postMessage(c),a.bitmap.close?.()};if(i===null){s(null);return}i.detect(a.bitmap,a.streamWidth,a.streamHeight).then(s,()=>s(null))}}}typeof self<"u"&&typeof self.importScripts=="function"&&Et(self);var H=class t{constructor(e,r){this.pending=new Map;this.nextId=1;this.worker=e,this.tier=r.tier,r.fallbackReason!==void 0&&(this.fallbackReason=r.fallbackReason),e.addEventListener("message",i=>{let n=i.data;if(n.v!==b||n.type!=="result")return;let a=this.pending.get(n.id);this.pending.delete(n.id),a?.(n.observation)})}static create(e,r,i=1e4){return new Promise((n,a)=>{let s=setTimeout(()=>{e.removeEventListener("message",o),e.terminate(),a(new Error(`worker detector not ready within ${i}ms`))},i),o=d=>{let u=d.data;u.v!==b||u.type!=="ready"||(clearTimeout(s),e.removeEventListener("message",o),n(new t(e,u)))};e.addEventListener("message",o);let c={v:b,type:"init",options:r};e.postMessage(c)})}async detect(e,r,i){let n;try{typeof ImageBitmap<"u"&&e instanceof ImageBitmap?n=e:typeof createImageBitmap=="function"?n=await createImageBitmap(e):n=e}catch{return null}let a=this.nextId;return this.nextId+=1,new Promise(s=>{this.pending.set(a,s);let o={v:b,type:"detect",id:a,bitmap:n,streamWidth:r,streamHeight:i};this.worker.postMessage(o,[n])})}destroy(){for(let e of this.pending.values())e(null);this.pending.clear(),this.worker.terminate()}};var _t=["size","centering","pose","exposure","sharpness","motion"];function Me(t){if(t.accepted)return null;if(t.factors.presence<=0)return"no_face";let e="size";for(let r of _t)t.factors[r]<t.factors[e]&&(e=r);return e}var O=class{constructor(){this.blocked={};this.acceptedMs=0;this.ticks=0;this.lastAt=null}record(e){let r=this.lastAt===null?0:Math.max(0,e.at-this.lastAt);this.lastAt=e.at,this.ticks+=1;let i=Me(e);if(i===null){this.acceptedMs+=r;return}let n=this.blocked[i]??{count:0,ms:0};n.count+=1,n.ms+=r,this.blocked[i]=n}summary(){let e={};for(let[r,i]of Object.entries(this.blocked))e[r]={count:i.count,ms:Math.round(i.ms)};return{blocked:e,acceptedMs:Math.round(this.acceptedMs),ticks:this.ticks}}};var We=1e3,U=4,Ke=600,Ge={sharpness:1,exposure:1,meanLuma:128},ce=class{constructor(e){this.handlers=new Map;this.stateValue="idle";this.attempt=0;this.stream=null;this.detector=null;this.scheduler=null;this.gate=null;this.profiler=null;this.lastGuidanceKey=null;this.positioningStartedAt=0;this.cameraRequestedAt=null;this.cameraReadyAt=null;this.faceAcquiredAt=null;this.captureCompleteAt=null;this.fired=!1;this.carriedDegrade=0;this.carriedMeans=[];this.blockStats=null;this.lastGateSnapshotAt=Number.NEGATIVE_INFINITY;this.snapshotCanvas=null;this.options=e,this.facing=e.facingMode??"user"}get state(){return this.stateValue}on(e,r){let i=this.handlers.get(e);return i||(i=new Set,this.handlers.set(e,i)),i.add(r),()=>i?.delete(r)}emit(e,r){for(let i of[...this.handlers.get(e)??[]])i(r)}async start(e={}){e.facingMode!==void 0&&(this.facing=e.facingMode),this.attempt+=1,await this.run(this.attempt)}get facingMode(){return this.facing}retry(){this.teardownAttempt(),this.start()}switchCamera(){this.facing=this.facing==="user"?"environment":"user",this.teardownAttempt(),this.start()}destroy(){this.attempt+=1,this.teardownAttempt(),this.detector?.destroy(),this.detector=null,this.options.video.srcObject=null}async run(e){let{options:r}=this;this.fired=!1,this.lastGuidanceKey=null,this.carriedDegrade=0,this.carriedMeans=[],this.cameraRequestedAt=null,this.cameraReadyAt=null,this.faceAcquiredAt=null,this.captureCompleteAt=null,this.setState("preflight");let i=Z();if(i!=="OK"){this.fail(i==="INSECURE_CONTEXT"?"insecure":"unsupported");return}this.setState("acquiring");let n=r.getUserMedia??(c=>navigator.mediaDevices.getUserMedia(c)),a;this.cameraRequestedAt=this.now();try{a=await n($(J(),this.facing))}catch(c){if(e!==this.attempt)return;this.fail(Y(c));return}if(Te(a),e!==this.attempt){for(let c of a.getTracks())c.stop();return}if(this.stream=a,r.video.srcObject=a,await r.video.play().catch(()=>{}),e!==this.attempt)return;if(this.cameraReadyAt=this.now(),this.detector===null){let c={...r.v3AssetBaseUrl!==void 0?{v3AssetBaseUrl:r.v3AssetBaseUrl}:{}},d=r.createDetector??(r.createWorker!==void 0&&Ce()?async()=>{try{return await H.create(r.createWorker(),c)}catch{return E(c)}}:()=>E(c)),u;try{u=await d()}catch(l){e===this.attempt&&this.fail("models",l instanceof v?l.fallbackReason:wt(l));return}if(e!==this.attempt){u.destroy();return}this.detector=u,this.options.telemetry?.({type:"detector",tier:u.tier,fallbackReason:u.fallbackReason})}let s=ne(),o=r.deviceClass??ie(s);this.profiler=new M(o),this.options.telemetry?.({type:"profile",staticClass:o,activeClass:this.profiler.deviceClass,simd:s.simd}),this.gate=new C(r.thresholds??{}),this.blockStats=new O,this.lastGateSnapshotAt=this.now(),r.rankKeyframes?.()&&Promise.resolve().then(()=>(Ne(),Fe)).then(c=>oe=c,()=>{}),this.setState("positioning"),this.positioningStartedAt=this.now(),this.startScheduler(e)}get animations(){return this.profiler?.profile.animations??"full"}startScheduler(e){let r=this.profiler;if(r===null)return;if(this.scheduler!==null){let n=this.scheduler.stats();this.carriedDegrade+=n.degradeCount,n.meanDetectMs>0&&this.carriedMeans.push(n.meanDetectMs),this.scheduler.stop()}let i=new w({cadenceHz:r.profile.cadenceHz,video:this.options.video,now:this.options.now,run:()=>this.detectTick(e)});this.scheduler=i,i.start()}async detectTick(e){let{detector:r,gate:i,profiler:n}=this,a=this.options.video;if(e!==this.attempt||r===null||i===null||n===null||this.fired||a.videoWidth===0)return;let s=n.deviceClass,o=this.now(),c=this.options.makeSnapshot?.(a,n.profile.inputWidth)??this.defaultSnapshot(a,n.profile.inputWidth),d=null;try{d=await r.detect(c,a.videoWidth,a.videoHeight)}catch{d=null}if(e!==this.attempt||this.fired)return;n.record(this.now()-o),n.deviceClass!==s&&this.startScheduler(e);let u=d===null?Ge:this.options.measureQuality?.(a,d.box)??this.defaultQuality(a,d.box),l=i.tick({timestampMs:this.now(),observation:d,quality:u,frameWidth:a.videoWidth,frameHeight:a.videoHeight});l.accepted&&this.faceAcquiredAt===null&&(this.faceAcquiredAt=l.at),this.blockStats?.record(l),!l.ready&&l.at-this.lastGateSnapshotAt>=We&&(this.lastGateSnapshotAt=l.at,this.reportGate(!1)),this.emit("checks",{engine:"v3",progress:l.p,q:l.q,factors:l.factors,attempt:e}),l.guidanceKey!==this.lastGuidanceKey&&(this.lastGuidanceKey=l.guidanceKey,this.emit("guidance",{key:l.guidanceKey})),l.ready&&this.stateValue==="positioning"&&(this.fired=!0,this.captureCompleteAt=l.at,this.fire(e))}async fire(e){let{options:r}=this,i=this.scheduler;i?.stop(),this.reportGate(!0);let n=i?.stats()??{degradeCount:0,meanDetectMs:0},a=[...this.carriedMeans,...n.meanDetectMs>0?[n.meanDetectMs]:[]];r.telemetry?.({type:"fired",timeToGateMs:this.now()-this.positioningStartedAt,degradeCount:this.carriedDegrade+n.degradeCount,meanDetectMs:a.length===0?0:a.reduce((h,y)=>h+y,0)/a.length});let s=r.mode??"clip",o=r.rankKeyframes?.()&&oe?oe.default(this,e).catch(()=>this.collectKeyframes(e)):this.collectKeyframes(e);if(s==="photo"){let h=await o;if(e!==this.attempt)return;if(h===null){this.fail("generic");return}this.finishCapture({keyframe:h.blob,previewDataUrl:h.previewDataUrl});return}this.setState("recording");let c=r.createRecorder?.()??new D,d=this.stream;if(d===null){this.fail("generic");return}let u=null;o.then(h=>{u=h},()=>{});let l=()=>{e===this.attempt&&u!==null&&this.emit("frozen",{previewDataUrl:u.previewDataUrl})},m,p;try{[m,p]=await Promise.all([c.record(d,l),o])}catch(h){if(e!==this.attempt)return;let y=h.kind;this.fail(y==="cliptoolarge"?"cliptoolarge":"recorder");return}if(e===this.attempt){if(S(m.blob)){this.fail("cliptoolarge");return}if(p===null){this.fail("generic");return}this.finishCapture({clip:m.blob,clipMimeType:m.mimeType,keyframe:p.blob,previewDataUrl:p.previewDataUrl})}}async collectKeyframes(e){let r=this.options.captureKeyframe??(a=>this.defaultKeyframe(a)),i=Ke/(U-1),n=null;for(let a=0;a<U;a+=1){if(e!==this.attempt)return n;try{let s=await r(this.options.video);(n===null||s.sharpness>n.sharpness)&&(n=s)}catch{}a<U-1&&await Mt(i)}return n}finishCapture(e){this.stopTracks(),this.setState("captured");let r=this.captureTiming();this.emit("artifacts",r===void 0?e:{...e,timing:r})}captureTiming(){let e=(s,o)=>s!==null&&o!==null?Math.max(0,Math.round(o-s)):void 0,r=e(this.cameraRequestedAt,this.cameraReadyAt),i=e(this.cameraReadyAt,this.faceAcquiredAt),n=e(this.faceAcquiredAt,this.captureCompleteAt),a={...r!==void 0?{cameraReadyMs:r}:{},...i!==void 0?{faceAcquireMs:i}:{},...n!==void 0?{captureMs:n}:{}};return Object.keys(a).length>0?a:void 0}async defaultKeyframe(e){let r=document.createElement("canvas"),i=await Q(e,r),n=r.toDataURL("image/jpeg",.92);return{blob:i,previewDataUrl:n,sharpness:this.centerSharpness(e)}}defaultSnapshot(e,r){try{let i=this.snapshotCanvas??document.createElement("canvas"),n=r/Math.max(1,e.videoWidth),a=Math.max(1,Math.round(e.videoWidth*n)),s=Math.max(1,Math.round(e.videoHeight*n)),o=i.getContext("2d");return o===null?e:(i.width!==a&&(i.width=a),i.height!==s&&(i.height=s),o.drawImage(e,0,0,a,s),this.snapshotCanvas=i,i)}catch{return e}}defaultQuality(e,r){let i=Ve(e,r,96);return i===null?Ge:{sharpness:K(i),exposure:te(i),meanLuma:W(i)}}centerSharpness(e){let r=g(e),i=Ve(e,{x:r.width*.25,y:r.height*.25,width:r.width*.5,height:r.height*.5},96);return i===null?0:K(i)}teardownAttempt(){this.scheduler?.stop(),this.scheduler=null,this.reportGate(!0),this.gate=null,this.stopTracks()}reportGate(e){let r=this.blockStats,i=this.profiler;if(r===null||i===null)return;let n=r.summary();e&&(this.blockStats=null),n.ticks!==0&&this.options.telemetry?.({type:"gate",final:e,activeClass:i.deviceClass,cadenceHz:i.profile.cadenceHz,...n})}stopTracks(){if(this.stream!==null){for(let e of this.stream.getTracks())e.stop();this.stream=null}}fail(e,r){this.scheduler?.stop(),this.reportGate(!0),this.stopTracks(),this.setState("error"),this.options.telemetry?.({type:"error",kind:e,fallbackReason:r}),this.emit("error",{kind:e,retryable:e!=="insecure"&&e!=="unsupported"})}setState(e){this.stateValue=e,this.emit("statechange",{state:e})}now(){return this.options.now?.()??performance.now()}},oe;function Mt(t){return new Promise(e=>setTimeout(e,t))}function wt(t){return t instanceof Error?t.message:String(t)}function Ve(t,e,r){try{let i=document.createElement("canvas"),n=r/Math.max(1,e.width);i.width=Math.max(1,Math.round(e.width*n)),i.height=Math.max(1,Math.round(e.height*n));let a=i.getContext("2d");return a===null?null:(a.drawImage(t,e.x,e.y,e.width,e.height,0,0,i.width,i.height),a.getImageData(0,0,i.width,i.height))}catch{return null}}0&&(module.exports={CENTERED_FACTOR,CIRCLE_RADIUS_FACTOR,CLIP_MS,CaptureSessionV3,ClipError,ClipRecorder,DEFAULT_CLIP_MIME,DEFAULT_TIER_ORDER,DEFAULT_V3_ASSET_BASE_URL,DEVICE_PROFILES,DetectScheduler,DetectorLadderError,DeviceProfiler,EXPOSURE_BAND,FaceGateV3,GATE_SNAPSHOT_MS,GateBlockStats,IN_CIRCLE_FACTOR,KEYFRAME_CANDIDATES,KEYFRAME_WINDOW_MS,MAX_CLIP_BYTES,MIME_CANDIDATES,SHARP_REF,STOP_GRACE_MS,TIMESLICE_MS,V3_GATE_DEFAULTS,VIDEO_BPS,blockReasonOf,buildCaptureConstraints,buildLivenessV2FormData,cameraPreflight,captureMirroredKeyframe,classifyDevice,createDetector,detectIsMobile,errorCopy,exposure,extForMime,intrinsicSize,isClipTooLarge,isMediaRecorderSupported,mapGetUserMediaError,meanLuma,pickMimeType,probeDevice,sharpness,toStreamPixels,uiCopy});
|
package/dist/core/index.d.cts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { C as CameraErrorKind } from '../capture-session-v3-
|
|
2
|
-
export { a as CLIP_MS, b as CaptureArtifacts, c as CaptureErrorKind, d as CaptureSessionEvents, e as CaptureSessionV3, f as CaptureSessionV3Events, g as CaptureSessionV3Options, h as CaptureSessionV3StartOptions, i as CaptureState, j as CaptureTiming, k as ClipError, l as ClipErrorKind, m as ClipRecorder, n as ClipResult, D as DEFAULT_CLIP_MIME, o as DEVICE_PROFILES, p as DeviceClass, q as DeviceProbe, r as DeviceProfile, s as DeviceProfiler, E as EscalationClipArtifact, t as EscalationHook, F as FaceGateV3, G as GateChecks, K as KEYFRAME_CANDIDATES,
|
|
1
|
+
import { C as CameraErrorKind } from '../capture-session-v3-Dvob-uH2.cjs';
|
|
2
|
+
export { a as CLIP_MS, b as CaptureArtifacts, c as CaptureErrorKind, d as CaptureSessionEvents, e as CaptureSessionV3, f as CaptureSessionV3Events, g as CaptureSessionV3Options, h as CaptureSessionV3StartOptions, i as CaptureState, j as CaptureTiming, k as ClipError, l as ClipErrorKind, m as ClipRecorder, n as ClipResult, D as DEFAULT_CLIP_MIME, o as DEVICE_PROFILES, p as DeviceClass, q as DeviceProbe, r as DeviceProfile, s as DeviceProfiler, E as EscalationClipArtifact, t as EscalationHook, F as FaceGateV3, G as GATE_SNAPSHOT_MS, u as GateBlockEntry, v as GateBlockReason, w as GateBlockStats, x as GateBlockSummary, y as GateChecks, K as KEYFRAME_CANDIDATES, z as KEYFRAME_WINDOW_MS, M as MAX_CLIP_BYTES, A as MIME_CANDIDATES, S as STOP_GRACE_MS, T as TIMESLICE_MS, V as V3ChecksPayload, B as V3GateFactor, H as V3GateQuality, I as V3GateThresholds, J as V3GateTick, L as V3GateTickInput, N as V3TelemetryEvent, O as V3_GATE_DEFAULTS, P as VIDEO_BPS, Q as blockReasonOf, R as buildLivenessV2FormData, U as cameraPreflight, W as classifyDevice, X as extForMime, Y as isClipTooLarge, Z as isMediaRecorderSupported, _ as mapGetUserMediaError, $ as pickMimeType, a0 as probeDevice } from '../capture-session-v3-Dvob-uH2.cjs';
|
|
3
3
|
export { C as CENTERED_FACTOR, a as CIRCLE_RADIUS_FACTOR, I as IN_CIRCLE_FACTOR, b as buildCaptureConstraints, d as detectIsMobile } from '../capture-constraints-BujkZcfb.cjs';
|
|
4
|
-
export { C as CreateDetectorOptions, D as DEFAULT_TIER_ORDER, a as DEFAULT_V3_ASSET_BASE_URL, b as Detector, c as DetectorLadderError, F as FaceObservation, d as createDetector, i as intrinsicSize, t as toStreamPixels } from '../detect-worker-
|
|
4
|
+
export { C as CreateDetectorOptions, D as DEFAULT_TIER_ORDER, a as DEFAULT_V3_ASSET_BASE_URL, b as Detector, c as DetectorLadderError, F as FaceObservation, d as createDetector, i as intrinsicSize, t as toStreamPixels } from '../detect-worker-DclNxkZT.cjs';
|
|
5
5
|
|
|
6
6
|
declare function captureMirroredKeyframe(video: HTMLVideoElement, canvas: HTMLCanvasElement, quality?: number): Promise<Blob>;
|
|
7
7
|
|
package/dist/core/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { C as CameraErrorKind } from '../capture-session-v3-
|
|
2
|
-
export { a as CLIP_MS, b as CaptureArtifacts, c as CaptureErrorKind, d as CaptureSessionEvents, e as CaptureSessionV3, f as CaptureSessionV3Events, g as CaptureSessionV3Options, h as CaptureSessionV3StartOptions, i as CaptureState, j as CaptureTiming, k as ClipError, l as ClipErrorKind, m as ClipRecorder, n as ClipResult, D as DEFAULT_CLIP_MIME, o as DEVICE_PROFILES, p as DeviceClass, q as DeviceProbe, r as DeviceProfile, s as DeviceProfiler, E as EscalationClipArtifact, t as EscalationHook, F as FaceGateV3, G as GateChecks, K as KEYFRAME_CANDIDATES,
|
|
1
|
+
import { C as CameraErrorKind } from '../capture-session-v3-CQK-G-qX.js';
|
|
2
|
+
export { a as CLIP_MS, b as CaptureArtifacts, c as CaptureErrorKind, d as CaptureSessionEvents, e as CaptureSessionV3, f as CaptureSessionV3Events, g as CaptureSessionV3Options, h as CaptureSessionV3StartOptions, i as CaptureState, j as CaptureTiming, k as ClipError, l as ClipErrorKind, m as ClipRecorder, n as ClipResult, D as DEFAULT_CLIP_MIME, o as DEVICE_PROFILES, p as DeviceClass, q as DeviceProbe, r as DeviceProfile, s as DeviceProfiler, E as EscalationClipArtifact, t as EscalationHook, F as FaceGateV3, G as GATE_SNAPSHOT_MS, u as GateBlockEntry, v as GateBlockReason, w as GateBlockStats, x as GateBlockSummary, y as GateChecks, K as KEYFRAME_CANDIDATES, z as KEYFRAME_WINDOW_MS, M as MAX_CLIP_BYTES, A as MIME_CANDIDATES, S as STOP_GRACE_MS, T as TIMESLICE_MS, V as V3ChecksPayload, B as V3GateFactor, H as V3GateQuality, I as V3GateThresholds, J as V3GateTick, L as V3GateTickInput, N as V3TelemetryEvent, O as V3_GATE_DEFAULTS, P as VIDEO_BPS, Q as blockReasonOf, R as buildLivenessV2FormData, U as cameraPreflight, W as classifyDevice, X as extForMime, Y as isClipTooLarge, Z as isMediaRecorderSupported, _ as mapGetUserMediaError, $ as pickMimeType, a0 as probeDevice } from '../capture-session-v3-CQK-G-qX.js';
|
|
3
3
|
export { C as CENTERED_FACTOR, a as CIRCLE_RADIUS_FACTOR, I as IN_CIRCLE_FACTOR, b as buildCaptureConstraints, d as detectIsMobile } from '../capture-constraints-BujkZcfb.js';
|
|
4
|
-
export { C as CreateDetectorOptions, D as DEFAULT_TIER_ORDER, a as DEFAULT_V3_ASSET_BASE_URL, b as Detector, c as DetectorLadderError, F as FaceObservation, d as createDetector, i as intrinsicSize, t as toStreamPixels } from '../detect-worker-
|
|
4
|
+
export { C as CreateDetectorOptions, D as DEFAULT_TIER_ORDER, a as DEFAULT_V3_ASSET_BASE_URL, b as Detector, c as DetectorLadderError, F as FaceObservation, d as createDetector, i as intrinsicSize, t as toStreamPixels } from '../detect-worker-DclNxkZT.js';
|
|
5
5
|
|
|
6
6
|
declare function captureMirroredKeyframe(video: HTMLVideoElement, canvas: HTMLCanvasElement, quality?: number): Promise<Blob>;
|
|
7
7
|
|
package/dist/core/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{a as e,b as r,c as o,d as n,e as a,f as v,g as y,h as g,i as x,j as k,k as z,l as C,m as S,n as V,o as j,p as q,q as w,r as D,s as G,t as I,u as J}from"../chunk-DQWW4OCK.js";import{a as A,b as H,c as K,d as P}from"../chunk-POIQGEZM.js";import{a as s,b as t,c as i,d as c,e as p,f as u,g as f,h as m,i as d,j as l}from"../chunk-FHJ7HO3M.js";import{a as B,b as F,c as N,d as O,e as U}from"../chunk-FPXL63KZ.js";import"../chunk-LQ7C44JG.js";import{a as L,b as T,c as E,d as R,e as h,f as b}from"../chunk-OKWG3PVH.js";var M={permission:{key:"fcv2.err.permission",fr:"Autorisez la cam\xE9ra dans les r\xE9glages du navigateur (ic\xF4ne cam\xE9ra dans la barre d\u2019adresse), puis r\xE9essayez."},notfound:{key:"fcv2.err.notfound",fr:"Aucune cam\xE9ra d\xE9tect\xE9e. Branchez ou activez une cam\xE9ra, puis r\xE9essayez."},inuse:{key:"fcv2.err.inuse",fr:"La cam\xE9ra est utilis\xE9e par une autre application. Fermez-la puis r\xE9essayez."},overconstrained:{key:"fcv2.err.overconstrained",fr:"La cam\xE9ra ne prend pas en charge les r\xE9glages demand\xE9s. Nouvel essai en cours\u2026"},insecure:{key:"fcv2.err.insecure",fr:"La cam\xE9ra n\xE9cessite une connexion s\xE9curis\xE9e (HTTPS). Ouvrez la page en HTTPS."},unsupported:{key:"fcv2.err.unsupported",fr:"Votre navigateur ne prend pas en charge l\u2019enregistrement vid\xE9o. Utilisez un navigateur r\xE9cent."},generic:{key:"fcv2.err.generic",fr:"Cam\xE9ra indisponible. R\xE9essayez ou contactez le support."}},Q={recording:{key:"fcv2.recording",fr:"Enregistrement en cours\u2026"},uploading:{key:"fcv2.uploading",fr:"Envoi en cours\u2026"},clipTooLarge:{key:"fcv2.err.cliptoolarge",fr:"La vid\xE9o est trop volumineuse. R\xE9essayez dans un endroit mieux \xE9clair\xE9."},retry:{key:"fcv2.retry",fr:"R\xE9essayer"},listen:{key:"fcv2.listen",fr:"\xC9couter"}};export{a as CENTERED_FACTOR,o as CIRCLE_RADIUS_FACTOR,v as CLIP_MS,J as CaptureSessionV3,k as ClipError,z as ClipRecorder,i as DEFAULT_CLIP_MIME,T as DEFAULT_TIER_ORDER,L as DEFAULT_V3_ASSET_BASE_URL,A as DEVICE_PROFILES,S as DetectScheduler,E as DetectorLadderError,P as DeviceProfiler,F as EXPOSURE_BAND,j as FaceGateV3,D as GATE_SNAPSHOT_MS,w as GateBlockStats,n as IN_CIRCLE_FACTOR,G as KEYFRAME_CANDIDATES,I as KEYFRAME_WINDOW_MS,f as MAX_CLIP_BYTES,s as MIME_CANDIDATES,B as SHARP_REF,g as STOP_GRACE_MS,y as TIMESLICE_MS,V as V3_GATE_DEFAULTS,x as VIDEO_BPS,q as blockReasonOf,e as buildCaptureConstraints,l as buildLivenessV2FormData,p as cameraPreflight,C as captureMirroredKeyframe,K as classifyDevice,b as createDetector,r as detectIsMobile,M as errorCopy,U as exposure,d as extForMime,R as intrinsicSize,m as isClipTooLarge,u as isMediaRecorderSupported,c as mapGetUserMediaError,N as meanLuma,t as pickMimeType,H as probeDevice,O as sharpness,h as toStreamPixels,Q as uiCopy};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
var Y={fp12:"08390000c48a",engine:"sekyro-ocr-1",precision:"fp32",files:{"sekyro-ocr.wasm":{bytes:3550608,sha256:"c15968a6de3d2225e2fdbf36d71a9214c2910419056c6878444fd2d0567bb748",tier:"live",contentType:"application/wasm"},"sekyro-ocr.mjs":{bytes:4270,sha256:"209a78d96ca53344996a0c2300aed4ff8a5c69e142713216975a2840eec08cac",tier:"bundled",contentType:"text/javascript"},"det.param":{bytes:24252,sha256:"c39ba0b1195e8ad37cfc5bdd7acedcfc1d9cb901e7b8eb1c9c4f6e5a66c04eb3",tier:"live",contentType:"text/plain"},"det.bin":{bytes:4685856,sha256:"652bafe366565109a1a5766caf482bc46f01481f8044d3a785bd9a1be67c63bb",tier:"live",contentType:"application/octet-stream"},"mrz-rec.param":{bytes:3510,sha256:"bc69b1b9683e35f6605b21001fadeb81468063459c00c0fc83c67c139f23df01",tier:"live",contentType:"text/plain"},"mrz-rec.bin":{bytes:494196,sha256:"de93a2aa2f08670cc7dedd17ba378d2f5d7cf6ae409054a9eac863a02c2febae",tier:"live",contentType:"application/octet-stream"},"mrz_dict.txt":{bytes:73,sha256:"b19858a4de2ccbbbdd4b53982188ea2c7664013183bbd1ae9d20ab52c661f97f",tier:"live",contentType:"text/plain"},"latin-rec.param":{bytes:19602,sha256:"2ae30dfdc7ee482c6cbbc0419c16ee125e880e9eaf69053d61953694bb0fcf4c",tier:"lazy",contentType:"text/plain"},"latin-rec.bin":{bytes:10750388,sha256:"f91ebdcf4d6b58c58a87704160e59d07ae56bc2d5021eae09d095c5a20bf7525",tier:"lazy",contentType:"application/octet-stream"},"ppocr_keys_v1.txt":{bytes:26249,sha256:"28b2362ad4ab2dc38769aa72feb535e3a9ddb3fd2a7585a05920e6393b1dc7f7",tier:"lazy",contentType:"text/plain"},"arabic-rec.param":{bytes:9858,sha256:"4e5cc85667dfaaa0c67d3f308400645a578c08bd43f952cab6c55b7bce143ea9",tier:"lazy",contentType:"text/plain"},"arabic-rec.bin":{bytes:8853572,sha256:"5acc3265a1738dc31316258383830d5dbdfa5e8ebc2e710f9001f832ecfbffb0",tier:"lazy",contentType:"application/octet-stream"},"arabic_dict.txt":{bytes:405,sha256:"637c27c88512c22089bef927b34ada08f748dc132ac70facd68d8202384c2726",tier:"lazy",contentType:"text/plain"}}};var ut="sekyro-mrz-1";function dt(e){return Array.from(new Uint8Array(e),t=>t.toString(16).padStart(2,"0")).join("")}async function be(e){return dt(await crypto.subtle.digest("SHA-256",e))}function Ne(e,t){return be(new TextEncoder().encode(`${ut}\0${e}\0${t.join(`
|
|
2
|
+
`)}`))}var G=class extends Error{constructor(t){super(t),this.name="AssetFailure",this.reason=t}},_e=Object.keys(Y.files).filter(e=>Y.files[e].tier==="live"),rn=Object.keys(Y.files).filter(e=>Y.files[e].tier==="lazy");function ft(e,t){return`${e.replace(/\/+$/,"")}/${Y.fp12}/${t}`}async function mt(e,t,n,s=fetch,r=()=>performance.now()){let o=Y.files[t],i=r(),l=async b=>{try{let f=await s(ft(e,t),{cache:b,signal:n,credentials:"omit"});if(!f.ok)throw new G("download");return await f.arrayBuffer()}catch(f){throw f instanceof G?f:new G("download")}},a=async b=>b.byteLength===o.bytes&&await be(b)===o.sha256,d=await l("force-cache");if(!await a(d)&&(d=await l("reload"),!await a(d)))throw new G("integrity");return{bytes:d,ms:r()-i}}async function Te(e,t,n,s=fetch,r=()=>performance.now()){let o=new AbortController,i=new Map,l=t.reduce((f,p)=>f+Y.files[p].bytes,0),a=r(),d=!0,b=0;for(let f of t){let p=await mt(e,f,o.signal,s,r);i.set(f,p.bytes),p.ms>=50&&(d=!1),b+=p.bytes.byteLength;let y=r()-a;if(b<l&&y>0&&y*l/b>n)throw o.abort(),new G("download")}return{files:i,downloadMs:Math.round(r()-a),cached:d}}var I=class extends Error{constructor(t){super(t),this.name="OcrFailure",this.code=t}};function Oe(e){return[...e.split(`
|
|
3
|
+
`)," "]}function Le(e,t,n,s,r){if(n<2||e.length===0||e.length!==t.length||s.length<n-1)throw new I("OCR_INFERENCE_FAILED");let o="",i=-1,l=0,a=0;for(let b=0;b<e.length;b++){let f=e[b];if(!Number.isInteger(f)||f<0||f>=n)throw new I("OCR_INFERENCE_FAILED");f!==0&&f!==i&&(o+=s[f-1],l+=Math.fround(t[b]),a++),i=f}return{text:r?Array.from(o).reverse().join(""):o,score:a===0?0:l/a}}var we=e=>e.reduce((t,n)=>t+n,0)/e.length;function De(e){let t=e.filter(r=>r.score>=.5);if(t.length===0)return[];if(t.some(r=>r.box.length!==4||!Number.isFinite(r.score)||r.box.some(o=>!Number.isFinite(o.x)||!Number.isFinite(o.y))))throw new I("OCR_INFERENCE_FAILED");let n=we(t.map(r=>r.box[2].y-r.box[0].y)),s=[];for(let r of t){let o=(r.box[0].y+r.box[2].y)/2,i=s.find(l=>Math.abs((l[0].box[0].y+l[0].box[2].y)/2-o)<n/2);i===void 0?s.push([r]):i.push(r)}for(let r of s)r.sort((o,i)=>o.box[0].x-i.box[0].x);return s.sort((r,o)=>r[0].box[0].y-o[0].box[0].y),s.map(r=>{let o=r[0].box,i=r[r.length-1].box,l=[o[0],i[1],i[2],o[3]];return{text:r.map(a=>a.text).join(" "),x:Math.min(...l.map(a=>a.x)),y:Math.min(...l.map(a=>a.y)),x2:Math.max(...l.map(a=>a.x)),y2:Math.max(...l.map(a=>a.y)),score:we(r.map(a=>a.score))}})}var j={of(e,t,n){return!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(n)||t<1||t>12||n<1||n>new Date(Date.UTC(e,t,0)).getUTCDate()?null:{year:e,month:t,day:n}},iso(e){return`${String(e.year).padStart(4,"0")}-${String(e.month).padStart(2,"0")}-${String(e.day).padStart(2,"0")}`},parse(e){let[t,n,s]=e.split("-").map(Number);return{year:t,month:n,day:s}},today(){let e=new Date;return{year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate()}}},ve=30,Pe=36,Ue=44,ge="MRT",bt=[7,3,1],gt=/^[0-9]{6}$/,ye=/^[0-9]{10}$/,Fe=e=>e!==void 0&&e.length===1&&e>="0"&&e<="9";function pt(e){return e>="0"&&e<="9"?e.charCodeAt(0)-48:e>="A"&&e<="Z"?e.charCodeAt(0)-55:0}function ue(e){let t=0;for(let n=0;n<e.length;n++)t+=pt(e[n])*bt[n%3];return String(t%10)}function D(e,t){return t==="<"?null:Fe(t)?ue(e)===t:!1}function ce(e){return e.trim().toUpperCase().replaceAll(" ","")}function yt(e,t){return(ce(e)+"<".repeat(t)).slice(0,t)}function k(e){return e.replace(/^<+|<+$/g,"")}var ht=new Set(`ABW AFG AGO AIA ALA ALB AND ARE ARG ARM ASM ATA ATF ATG AUS AUT AZE BDI BEL BEN BES BFA BGD BGR BHR
|
|
4
|
+
BHS BIH BLM BLR BLZ BMU BOL BRA BRB BRN BTN BVT BWA CAF CAN CCK CHE CHL CHN CIV CMR COD COG COK COL
|
|
5
|
+
COM CPV CRI CUB CUW CXR CYM CYP CZE DEU DJI DMA DNK DOM DZA ECU EGY ERI ESH ESP EST ETH FIN FJI FLK
|
|
6
|
+
FRA FRO FSM GAB GBR GEO GGY GHA GIB GIN GLP GMB GNB GNQ GRC GRD GRL GTM GUF GUM GUY HKG HMD HND HRV
|
|
7
|
+
HTI HUN IDN IMN IND IOT IRL IRN IRQ ISL ISR ITA JAM JEY JOR JPN KAZ KEN KGZ KHM KIR KNA KOR KWT LAO
|
|
8
|
+
LBN LBR LBY LCA LIE LKA LSO LTU LUX LVA MAC MAF MAR MCO MDA MDG MDV MEX MHL MKD MLI MLT MMR MNE MNG
|
|
9
|
+
MNP MOZ MRT MSR MTQ MUS MWI MYS MYT NAM NCL NER NFK NGA NIC NIU NLD NOR NPL NRU NZL OMN PAK PAN PCN
|
|
10
|
+
PER PHL PLW PNG POL PRI PRK PRT PRY PSE PYF QAT REU ROU RUS RWA SAU SDN SEN SGP SGS SHN SJM SLB SLE
|
|
11
|
+
SLV SMR SOM SPM SRB SSD STP SUR SVK SVN SWE SWZ SXM SYC SYR TCA TCD TGO THA TJK TKL TKM TLS TON TTO
|
|
12
|
+
TUN TUR TUV TWN TZA UGA UKR UMI URY USA UZB VAT VCT VEN VGB VIR VNM VUT WLF WSM XKK YEM ZAF ZMB ZWE`.trim().split(/\s+/)),At=new Set(`D GBD GBN GBO GBP GBS RKS UNK UNO UNA EUE XBA XIM XCC XCE XCO XDC XEC XES XMP XOM XPO XXA XXB XXC
|
|
13
|
+
XXX ANT NTZ UTO`.trim().split(/\s+/));function xt(e){return ht.has(e)||At.has(e)}var Mt="012568",Rt="OIZSGB",St="OQDILZSGB",It="000112568";function pe(e){let t=Mt.indexOf(e);return e.length!==1||t<0?e:Rt[t]}function Ct(e){let t=St.indexOf(e);return e.length!==1||t<0?e:It[t]}var Et=[["\xAB","<<"],["\u2039","<"],["\uFF1C","<"],["\u3008","<"],["\xD7","X"]],Ge=[`aaccc${"x".repeat(9)}n${"x".repeat(15)}`,`${"n".repeat(7)}x${"n".repeat(7)}ccc${"x".repeat(11)}n`,"a".repeat(30)],Ke=[`aaccc${"a".repeat(31)}`,`${"x".repeat(9)}nccc${"n".repeat(7)}x${"n".repeat(7)}${"x".repeat(7)}n`],ze=[`aaccc${"a".repeat(39)}`,`${"x".repeat(9)}nccc${"n".repeat(7)}x${"n".repeat(7)}${"x".repeat(14)}nn`];function Nt(e,t){let n="",s=0;for(;s<t.length;){let r=t[s];if(r==="c"){let i=e.substring(s,s+3),l=Array.from(i,pe).join("");n+=l!==i&&xt(l.replaceAll("<",""))?l:i,s+=3;continue}let o=e[s];n+=r==="a"?pe(o):r==="n"?Ct(o):o,s++}return n}function ee(e,t,n){return n.slice(0,e.length).map((s,r)=>{let o=Et.reduce((i,[l,a])=>i.replaceAll(l,a),ce(e[r]));return Nt(yt(o,t),s)})}function He(e,t){let n=e.filter(s=>s.trim().length>0);return t==="TD1"?ee(n.slice(0,3),ve,Ge):t==="TD2"?ee(n.slice(0,2),Pe,Ke):ee(n.slice(0,2),Ue,ze)}function he(e){let t=`${e.toUpperCase()}<<`.slice(0,2);return t==="AC"?"unknown":t==="IR"||t==="AR"||t[0]==="A"||t[0]==="C"?"residence_permit":t[0]==="P"?"passport":t[0]==="I"?"carte_identite":"unknown"}function _t(e){return ye.test(e)&&Number(e)%97===1}function Tt(e,t,n){if(!gt.test(e))return null;let s=Number(e.slice(0,2)),r=t?2e3+s:s>n.year%100?1900+s:2e3+s;return j.of(r,Number(e.slice(2,4)),Number(e.slice(4,6)))}function te(e,t,n){let s=Tt(e,t,n);return s?j.iso(s):""}function Ae(e){let t=e.split("<<").filter(n=>k(n).length>0);return[(t[0]??"").replaceAll("<"," ").trim(),(t[1]??"").replaceAll("<"," ").trim()]}var xe=e=>e==="M"||e==="F"?e:"",Ot=e=>e.substring(0,2).replaceAll("<",""),oe=e=>e.substring(2,5).replaceAll("<","");function We(e,t,n){if(t==="<"&&k(n).length>0){let s=n.indexOf("<"),r=s<0?n:n.slice(0,s);if(r.length>=2){let o=e+r.slice(0,-1);if(D(o,r[r.length-1])===!0)return{value:k(o),ok:!0,warn:null}}return{value:k(e),ok:!1,warn:"docnum_cd_mismatch"}}return{value:k(e),ok:D(e,t),warn:null}}var K=(e,t)=>({success:!1,error:e,fields:{},checkDigits:{},hardCdFail:!1,warns:[],...t===void 0?{}:{linesCount:t}});function Me(e,t,n,s,r,o,i){return{success:!0,documentType:e,format:t,documentCode:Ot(n),fields:s,checkDigits:r,hardCdFail:o,warns:i}}function Lt(e,t){if(e.length<3)return K("mrz_incomplete");let[n,s,r]=ee(e.slice(0,3),ve,Ge),o=oe(n)===ge||s.substring(15,18)===ge||_t(n.substring(15,25)),i=[],l={},a,d,b=!1;if(o){a=k(n.substring(5,14));let A=n[14];Fe(A)?(d=ue(n.substring(5,14))===A,d||i.push("td1_docnum_cd_mismatch")):d=null}else{let A=We(n.substring(5,14),n[14],n.substring(15,30));if(A.ok===null)return K("mrz_incomplete");a=A.value,d=A.ok,b=A.ok===!1&&A.warn===null,A.warn!==null&&i.push(A.warn)}l.document_number=d;let f=D(s.substring(0,6),s[6]),p=D(s.substring(8,14),s[14]);if(l.birth_date=f,l.expiry_date=p,f===null||p===null)return K("mrz_incomplete");let y=D(n.substring(5,30)+s.substring(0,7)+s.substring(8,15)+s.substring(18,29),s[29]);l.composite=y,y===!1&&i.push("composite_cd_mismatch");let m=o?n.substring(15,25):"",[u,R]=Ae(r),S=f===!1||p===!1||b;return Me(he(n.substring(0,2)),"TD1",n,{issuing_state:oe(n),document_number:a,nni:ye.test(m)?m:"",birth_date:te(s.substring(0,6),!1,t),expiry_date:te(s.substring(8,14),!0,t),sex:xe(s[7]),nationality:k(s.substring(15,18)),surname:u,given_names:R},l,S,i)}function wt(e,t){if(e.length<2)return K("mrz_incomplete");let[n,s]=ee(e.slice(0,2),Pe,Ke),r=[],o=We(s.substring(0,9),s[9],s.substring(28,35));o.warn!==null&&r.push(o.warn);let i=D(s.substring(13,19),s[19]),l=D(s.substring(21,27),s[27]),a={document_number:o.ok,birth_date:i,expiry_date:l};if(o.ok===null||i===null||l===null)return K("mrz_incomplete");let d=D(s.substring(0,10)+s.substring(13,20)+s.substring(21,35),s[35]);a.composite=d,d===!1&&r.push("composite_cd_mismatch");let[b,f]=Ae(n.substring(5,36)),p=o.ok===!1&&o.warn===null||i===!1||l===!1;return Me(he(n.substring(0,2)),"TD2",n,{issuing_state:oe(n),document_number:o.value,nni:"",birth_date:te(s.substring(13,19),!1,t),expiry_date:te(s.substring(21,27),!0,t),sex:xe(s[20]),nationality:k(s.substring(10,13)),surname:b,given_names:f},a,p,r)}function ke(e,t){if(e.length<2)return K("mrz_incomplete");let[n,s]=ee(e.slice(0,2),Ue,ze),r=oe(n)===ge,o=[],i={},l=s.substring(0,9),a=D(l,s[9]),d=D(s.substring(13,19),s[19]),b=D(s.substring(21,27),s[27]);if(i.document_number=a,i.birth_date=d,i.expiry_date=b,a===null||d===null||b===null)return K("mrz_incomplete");let f=s.substring(28,42),p="";if(k(f).length>0){let S=D(f,s[42]);i.personal_number=S;let A=k(f);r&&S!==!1&&ye.test(A)&&(p=A)}let y=D(s.substring(0,10)+s.substring(13,20)+s.substring(21,43),s[43]);i.composite=y,y===!1&&o.push("composite_cd_mismatch");let[m,u]=Ae(n.substring(5,44)),R=a===!1||d===!1||b===!1;return Me(he(n.substring(0,2)),"TD3",n,{issuing_state:oe(n),document_number:k(l),nni_candidate:p,birth_date:te(s.substring(13,19),!1,t),expiry_date:te(s.substring(21,27),!0,t),sex:xe(s[20]),nationality:k(s.substring(10,13)),surname:m,given_names:u},i,R,o)}var Be=new Set(["A","C","I"]);function Ve(e,t=j.today()){let n=e.filter(r=>r.trim().length>0);if(n.length===0)return K("mrz_unrecognized",0);let s=Array.from(ce(n[0]).slice(0,1),pe).join("");return n.length===3&&Be.has(s)?Lt(n,t):n.length===2&&s==="P"?ke(n,t):n.length===2&&Be.has(s)?Math.max(...n.map(r=>ce(r).length))>40?ke(n,t):wt(n,t):K("mrz_unrecognized",n.length)}var Dt=new Map([...(`ABWAW AFGAF AGOAO AIAAI ALAAX ALBAL ANDAD AREAE ARGAR ARMAM ASMAS ATAAQ
|
|
14
|
+
ATFTF ATGAG AUSAU AUTAT AZEAZ BDIBI BELBE BENBJ BESBQ BFABF BGDBD BGRBG
|
|
15
|
+
BHRBH BHSBS BIHBA BLMBL BLRBY BLZBZ BMUBM BOLBO BRABR BRBBB BRNBN BTNBT
|
|
16
|
+
BVTBV BWABW CAFCF CANCA CCKCC CHECH CHLCL CHNCN CIVCI CMRCM CODCD COGCG
|
|
17
|
+
COKCK COLCO COMKM CPVCV CRICR CUBCU CUWCW CXRCX CYMKY CYPCY CZECZ DEUDE
|
|
18
|
+
DJIDJ DMADM DNKDK DOMDO DZADZ ECUEC EGYEG ERIER ESHEH ESPES ESTEE ETHET
|
|
19
|
+
FINFI FJIFJ FLKFK FRAFR FROFO FSMFM GABGA GBRGB GEOGE GGYGG GHAGH GIBGI
|
|
20
|
+
GINGN GLPGP GMBGM GNBGW GNQGQ GRCGR GRDGD GRLGL GTMGT GUFGF GUMGU GUYGY
|
|
21
|
+
HKGHK HMDHM HNDHN HRVHR HTIHT HUNHU IDNID IMNIM INDIN IOTIO IRLIE IRNIR
|
|
22
|
+
IRQIQ ISLIS ISRIL ITAIT JAMJM JEYJE JORJO JPNJP KAZKZ KENKE KGZKG KHMKH
|
|
23
|
+
KIRKI KNAKN KORKR KWTKW LAOLA LBNLB LBRLR LBYLY LCALC LIELI LKALK LSOLS
|
|
24
|
+
LTULT LUXLU LVALV MACMO MAFMF MARMA MCOMC MDAMD MDGMG MDVMV MEXMX MHLMH
|
|
25
|
+
MKDMK MLIML MLTMT MMRMM MNEME MNGMN MNPMP MOZMZ MRTMR MSRMS MTQMQ MUSMU
|
|
26
|
+
MWIMW MYSMY MYTYT NAMNA NCLNC NERNE NFKNF NGANG NICNI NIUNU NLDNL NORNO
|
|
27
|
+
NPLNP NRUNR NZLNZ OMNOM PAKPK PANPA PCNPN PERPE PHLPH PLWPW PNGPG POLPL
|
|
28
|
+
PRIPR PRKKP PRTPT PRYPY PSEPS PYFPF QATQA REURE ROURO RUSRU RWARW SAUSA
|
|
29
|
+
SDNSD SENSN SGPSG SGSGS SHNSH SJMSJ SLBSB SLESL SLVSV SMRSM SOMSO SPMPM
|
|
30
|
+
SRBRS SSDSS STPST SURSR SVKSK SVNSI SWESE SWZSZ SXMSX SYCSC SYRSY TCATC
|
|
31
|
+
TCDTD TGOTG THATH TJKTJ TKLTK TKMTM TLSTL TONTO TTOTT TUNTN TURTR TUVTV
|
|
32
|
+
TWNTW TZATZ UGAUG UKRUA UMIUM URYUY USAUS UZBUZ VATVA VCTVC VENVE VGBVG
|
|
33
|
+
VIRVI VNMVN VUTVU WLFWF WSMWS YEMYE ZAFZA ZMBZM ZWEZW`.match(/[A-Z]{5}/g)??[]).map(e=>[e.slice(0,3),e.slice(3)]),["D","DE"]]),Ye={of(e){return Dt.get(e.replaceAll("<",""))??null}};var Se=e=>ue(e);function Qe(e){return e.slice(0,5e4).split(/\r?\n/).slice(0,200).map(t=>t.toUpperCase().replace(/[«‹〈]/g,"<").replace(/[^A-Z0-9<]/g,"")).filter(t=>t.length>0)}var Ze=e=>e.replace(/[OQ]/g,"0").replace(/[IL]/g,"1").replaceAll("Z","2").replaceAll("S","5").replaceAll("B","8");function Xe(e,t){let n=Ze(e),s=Ze(t);if(!/^\d{6}$/.test(n)||Se(n)!==s)return null;let r=2e3+Number(n.slice(0,2)),o=Number(n.slice(2,4)),i=Number(n.slice(4,6));return o>=1&&o<=12&&i>=1&&i<=new Date(Date.UTC(r,o,0)).getUTCDate()?n:null}function Re(e,t){let n=e.replace(/<+$/,"");return/^[A-Z0-9]+$/.test(n)&&Se(e)===t?n:null}function kt(e){if(e.length<15)return null;if(e[14]!=="<")return Re(e.substring(5,14),e[14]);let t=/^([A-Z0-9]+)</.exec(e.substring(15,Math.min(30,e.length)))?.[1];return t===void 0||t.length<2?null:Re(e.substring(5,14)+t.slice(0,-1),t[t.length-1])}var x=(e,t,n)=>t>=e.length?"":e.substring(t,Math.min(n,e.length)),Z=(e,t)=>t<e.length?e[t]:"",$e=/^[IAC][A-Z<][A-Z<]{3}/,Bt=/^P[A-Z<][A-Z<]{3}/,qe=/^[PIAC][A-Z<][A-Z<]{3}/;function vt(e){let t=Qe(e),n=[],s=[];for(let o=0;o<t.length;o++){let i="",l=0;for(;l<6&&o+l<t.length&&(i+=t[o+l],!(i.length>300));)s.push(i),l++}let r=(o,i,l)=>{if(i.length<(l?15:28))return;let a=new Map,d=l?kt(o):Re(x(i,0,9),Z(i,9)),b=Xe(l?x(i,0,6):x(i,13,19),l?Z(i,6):Z(i,19)),f=Xe(l?x(i,8,14):x(i,21,27),l?Z(i,14):Z(i,27));d!==null&&a.set("docNumber",d),b!==null&&a.set("dob6",b),f!==null&&a.set("expiry6",f),a.size>0&&n.push({fields:a,country:Ye.of(x(o,2,5))})};for(let o of s)$e.test(o)&&(o.length>=45&&r(o.substring(0,30),o.substring(30),!0),o.length>=64&&r(o.substring(0,36),o.substring(36),!1)),Bt.test(o)&&o.length>=72&&r(o.substring(0,44),o.substring(44),!1);for(let o=0;o<t.length-1;o++){let i=t[o],l=t[o+1];$e.test(i)&&i.length>=15&&i.length<=30&&r(i,l,!0),qe.test(i)&&i.length>=5&&i.length<=44&&r(i,l,!1)}return n}function Pt(e){let t=vt(e);if(t.length===0)return{};let n=Math.max(...t.map(o=>o.fields.size)),s=t.filter(o=>o.fields.size===n),r={};for(let o of["docNumber","dob6","expiry6"]){let i=new Set(s.map(l=>l.fields.get(o)).filter(l=>l!==void 0));i.size===1&&s.every(l=>l.fields.has(o))&&(r[o]=[...i][0])}return r}function Ut(e){let t=Pt(e),n=t.docNumber,s=t.dob6,r=t.expiry6;return n!==void 0&&s!==void 0&&r!==void 0?{docNumber:n,dob6:s,expiry6:r}:null}function et(e){let t=Gt(e);return t.length===1?t[0]:null}var Ft=e=>JSON.stringify([e.documentNumber,e.nationality,e.dob,e.sex,e.expiry,e.primaryIdentifier,e.secondaryIdentifier,e.optional]);function Gt(e){let t=Qe(e),n=[];for(let r=0;r<t.length;r++){let o=t[r];if(!qe.test(o))continue;let i=o.startsWith("P")?[44]:[30,36];for(let l of i){let a=l===30?3:2,d=t.slice(r,Math.min(t.length,r+a));d.length===a&&d.every(p=>p.length<=l)&&n.push(d.map(p=>p.padEnd(l,"<")).join(`
|
|
34
|
+
`));let b="",f=0;for(;f<6&&r+f<t.length&&(b+=t[r+f],b.length===l*a&&n.push(b),!(b.length>=l*a));)f++}}let s=new Map;for(let r of n){let o=Ut(r);if(o===null)continue;let i=r.includes(`
|
|
35
|
+
`)?r.split(`
|
|
36
|
+
`):r.match(r.length===90?/.{30}/g:r.length===88?/.{44}/g:/.{36}/g)??[],l=i[0]??"",a=i[1]??"",d=i.length===3,b=d?x(l,5,30)+x(a,0,7)+x(a,8,15)+x(a,18,29):x(a,0,10)+x(a,13,20)+x(a,21,a.length-1),f=d?Z(a,29):Z(a,a.length-1);if(!/^[0-9]$/.test(f)||Se(b)!==f)continue;let p=Kt(r);if(p===null||p.primaryIdentifier.length===0&&p.secondaryIdentifier.length===0||!/^[MFX]?$/.test(p.sex))continue;let y={...p,documentNumber:o.docNumber,dob:o.dob6,expiry:o.expiry6};s.set(Ft(y),{fields:y,mrzLines:i})}return[...s.values()]}var P=e=>e.replaceAll("<"," ").replace(/\s+/g," ").trim();function Je(e){let t=e.split("<<");return[P(t[0]??""),P(t.slice(1).join("<<"))]}var je=e=>e.length===0?null:e;function Kt(e){let t=e.split(/\r?\n/).map(s=>s.replace(/\s+$/,"")).filter(s=>s.length>0),n=e.replace(/[\r\n]/g,"");if(t.length===1&&(n.length===90?t=[n.substring(0,30),n.substring(30,60),n.substring(60,90)]:n.length===72?t=[n.substring(0,36),n.substring(36,72)]:n.length===88&&(t=[n.substring(0,44),n.substring(44,88)])),t.length===3){let[s,r,o]=t,i=Z(s,14)==="<"?/^([A-Z0-9]+)</.exec(x(s,15,30))?.[1]:void 0,l=P(x(s,5,14)+(i!==void 0&&i.length>1?i.slice(0,-1):"")),[a,d]=Je(o),b=P(`${x(s,15,30)}<${x(r,18,29)}`);return{documentNumber:l,nationality:P(x(r,15,18)),dob:x(r,0,6),sex:P(x(r,7,8)),expiry:x(r,8,14),primaryIdentifier:a,secondaryIdentifier:d,optional:je(b)}}if(t.length===2){let[s,r]=t,o=s.length>=44,[i,l]=Je(x(s,5,o?44:36));return{documentNumber:P(x(r,0,9)),nationality:P(x(r,10,13)),dob:x(r,13,19),sex:P(x(r,20,21)),expiry:x(r,21,27),primaryIdentifier:i,secondaryIdentifier:l,optional:je(P(o?x(r,28,42):x(r,28,35)))}}return null}function tt(e,t=j.today()){let n=Ve(e,t),s=n.format??null,r=s==="TD1"||s==="TD2"||s==="TD3"?He(e,s):[...e];return{format:s,documentCode:n.documentCode??null,lines:r,valid:n.success&&!n.hardCdFail}}var zt=/^[A-Z0-9<]{25,}$/;function Ht(e){return e.toUpperCase().replaceAll(" ","").replaceAll("\xAB","<").replaceAll("\u2039","<")}var Ie=(e,t,n)=>e.length>=t&&e.length<=n;function nt(e){let t=e.map(Ht).filter(n=>zt.test(n));for(let n=0;n+3<=t.length;n++){let s=t.slice(n,n+3);if(s.every(r=>Ie(r,28,32))&&"IAC".includes(s[0][0]))return s}for(let n=0;n+2<=t.length;n++){let s=t.slice(n,n+2);if(s.every(r=>Ie(r,40,46))&&s[0].startsWith("P")||s.every(r=>Ie(r,34,38))&&"IACPV".includes(s[0][0]))return s}return[]}var ne={SIZE:80,SCRIPT:64,OFFSET:68,STEPS:72},L={DETECTOR:0,LATIN:1,ARABIC:2},U={NONE:0,LATIN:1,ARABIC:2,BOTH:3},de=3;var X=e=>Math.round(Math.min(1,Math.max(0,e))*1e4)/1e4;async function Ce(e,t,n,s,r){let o=r.now??(()=>performance.now()),i=o(),a=e.read(t,n,s,r.region??[0,0,1,1],1,de,U.LATIN,r.detectorLimit).map(u=>({text:u.latin.text,score:u.latin.score,box:[0,1,2,3].map(R=>({x:u.box[2*R],y:u.box[2*R+1]}))})),d=De([...a].reverse()),b=d.map(u=>u.text),f=[...et(b.join(`
|
|
37
|
+
`))?.mrzLines??nt(b)],p=d.map(u=>[X(u.x/n),X(u.y/s),X((u.x2-u.x)/n),X((u.y2-u.y)/s)]),y={kind:"band",ms:0,lineBoxes:p,lineCount:f.length,valid:!1},m=Vt(d.map(u=>u.text),p,f);if(m!==null&&(y.mrzBox=m),f.length>0){let u=tt(f,r.today??j.today());u.format&&(y.format=u.format),u.documentCode&&/^[A-Z<]{1,2}$/.test(u.documentCode)&&(y.documentCode=u.documentCode),u.valid&&(y.valid=!0,y.digest=await Ne(r.salt,u.lines))}return y.ms=Math.round(o()-i),y}var rt=e=>e.toUpperCase().replace(/\s+/g,"");function Wt(e,t){let n=Math.max(e.length,t.length);if(n===0)return 0;let s=0;for(let r=0;r<Math.min(e.length,t.length);r++)e[r]===t[r]&&s++;return s/n}function Vt(e,t,n){if(n.length===0||e.length===0)return null;let s=new Set,r=[];for(let d of n){let b=-1,f=.5;if(e.forEach((p,y)=>{let m=s.has(y)?0:Wt(rt(p),rt(d));m>f&&(f=m,b=y)}),b<0)return null;s.add(b),r.push(t[b])}let o=Math.min(...r.map(d=>d[0])),i=Math.min(...r.map(d=>d[1])),l=Math.max(...r.map(d=>d[0]+d[2])),a=Math.max(...r.map(d=>d[1]+d[3]));return[X(o),X(i),X(l-o),X(a-i)]}var Sn=Object.freeze({minLines:4,fillMin:.55,fillMax:.98,offsetMax:.12,steadyFillDelta:.04,steadyOffsetDelta:.03,layoutShiftMax:.025,lineCountDelta:1,lockMs:600,steadyMs:900,minFrames:3});function st(e,t,n){let s=r=>Math.round(Math.min(1,Math.max(0,r))*1e4)/1e4;return e.map(r=>{let o=[r[0],r[2],r[4],r[6]],i=[r[1],r[3],r[5],r[7]],l=Math.min(...o),a=Math.min(...i);return[s(l/t),s(a/n),s((Math.max(...o)-l)/t),s((Math.max(...i)-a)/n)]}).sort((r,o)=>r[1]-o[1]||r[0]-o[0])}async function Yt(e={}){var t,n=e,s=import.meta.url,r="",o,i;try{r=new URL(".",s).href}catch{}i=c=>{var h=new XMLHttpRequest;return h.open("GET",c,!1),h.responseType="arraybuffer",h.send(null),new Uint8Array(h.response)},o=async c=>{if(c=await fetch(c,{credentials:"same-origin"}),c.ok)return c.arrayBuffer();throw Error(c.status+" : "+c.url)};var l=console.log.bind(console),a=console.error.bind(console),d=!1,b,f,p,y,m,u=!1;function R(){var c=ae.buffer;new Int8Array(c),new Int16Array(c),n.HEAPU8=p=new Uint8Array(c),new Uint16Array(c),new Int32Array(c),y=new Uint32Array(c),new Float32Array(c),new Float64Array(c),m=new BigInt64Array(c),new BigUint64Array(c)}function S(c){throw c="Aborted("+c+")",a(c),d=!0,c+=". Build with -sASSERTIONS for more info.",u&&Q(),c=new WebAssembly.RuntimeError(c),f?.(c),c}var A;async function w(c){try{var h=await o(c);return new Uint8Array(h)}catch{}if(i)c=i(c);else throw"both async and sync fetching of the wasm failed";return c}async function B(c,h){try{var g=await w(c);return await WebAssembly.instantiate(g,h)}catch(C){a(`failed to asynchronously prepare wasm: ${C}`),S(C)}}async function z(c){var h=A;try{var g=fetch(h,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(g,c)}catch(C){a(`wasm streaming compile failed: ${C}`),a("falling back to ArrayBuffer instantiation")}return B(h,c)}var H={},W=()=>{if(!$){var c={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"},h;for(h in H)H[h]===void 0?delete c[h]:c[h]=H[h];var g=[];for(h in c)g.push(`${h}=${c[h]}`);$=g}return $},$,J=[null,[],[]],ie=globalThis.TextDecoder&&new TextDecoder,Q,ae,ct={i:()=>S(""),b:function(c,h,g){return 0<=c&&3>=c?(m[g>>3]=BigInt(Math.round(1e6*(c===0?Date.now():performance.now()))),0):28},d:()=>1073741824,c:c=>{var h=p.length;if(c>>>=0,1073741824<c)return!1;for(var g=1;4>=g;g*=2){var C=h*(1+.2/g);C=Math.min(C,c+100663296);e:{C=(Math.min(1073741824,65536*Math.ceil(Math.max(c,C)/65536))-ae.buffer.byteLength+65535)/65536|0;try{ae.grow(C),R();var _=1;break e}catch{}_=void 0}if(_)return!0}return!1},f:(c,h)=>{var g=0,C=0,_;for(_ of W()){var M=h+g;y[c+C>>2]=M;for(var q=_,O=p,re=M,F=M+1/0-1,E=0;E<q.length;++E){var N=q.codePointAt(E);if(127>=N){if(M>=F)break;O[M++]=N}else if(2047>=N){if(M+1>=F)break;O[M++]=192|N>>6,O[M++]=128|N&63}else if(65535>=N){if(M+2>=F)break;O[M++]=224|N>>12,O[M++]=128|N>>6&63,O[M++]=128|N&63}else{if(M+3>=F)break;O[M++]=240|N>>18,O[M++]=128|N>>12&63,O[M++]=128|N>>6&63,O[M++]=128|N&63,E++}}O[M]=0,q=M-re,g+=q+1,C+=4}return 0},g:(c,h)=>{var g=W();y[c>>2]=g.length,c=0;for(var C of g){for(var _=g=0;_<C.length;++_){var M=C.charCodeAt(_);127>=M?g++:2047>=M?g+=2:55296<=M&&57343>=M?(g+=4,++_):g+=3}c+=g+1}return y[h>>2]=c,0},j:()=>52,h:()=>52,e:function(){return 70},a:(c,h,g,C)=>{for(var _=0,M=0;M<g;M++){var q=y[h>>2],O=y[h+4>>2];h+=8;for(var re=0;re<O;re++){var F=c,E=p[q+re],N=J[F];if(E===0||E===10){F=F===1?l:a,E=N;for(var V=0,se=E,v=V,T=v+void 0;se[v]&&!(v>=T);)++v;if(se=v,16<se-V&&E.buffer&&ie)E=ie.decode(E.subarray(V,se));else{for(v="";V<se;)if(T=E[V++],T&128){var me=E[V++]&63;if((T&224)==192)v+=String.fromCharCode((T&31)<<6|me);else{var Ee=E[V++]&63;T=(T&240)==224?(T&15)<<12|me<<6|Ee:(T&7)<<18|me<<12|Ee<<6|E[V++]&63,65536>T?v+=String.fromCharCode(T):(T-=65536,v+=String.fromCharCode(55296|T>>10,56320|T&1023))}}else v+=String.fromCharCode(T);E=v}F(E),N.length=0}else N.push(E)}_+=O}return y[C>>2]=_,0}},le;return le=await(async function(){function c(g){return g=le=g.exports,n._skw_engine_id=g.m,n._skw_load=g.n,n._skw_unload=g.o,n._skw_set_detector_limit=g.p,n._skw_read=g.q,n._skw_line_count=g.r,n._skw_lines=g.s,n._skw_best=g.t,n._skw_values=g.u,n._skw_sharpness=g.v,n._free=g.w,n._malloc=g.x,Q=g.y,ae=g.k,R(),le}var h={a:ct};return n.instantiateWasm?new Promise(g=>{n.instantiateWasm(h,(C,_)=>{g(c(C,_))})}):(A??(A=n.locateFile?n.locateFile?n.locateFile("sekyro-ocr.wasm",r):r+"sekyro-ocr.wasm":new URL("sekyro-ocr.wasm",import.meta.url).href),c((await z(h)).instance))})(),n.calledRun=!0,d||(u=!0,le.l(),b?.(n)),u?t=n:t=new Promise((c,h)=>{b=c,f=h}),t}var ot=Yt;function it(e){return e===1||e===5?new I("OCR_IMAGE_INVALID"):e===2?new I("OCR_ASSET_INVALID"):e===4?new I("OCR_CANCELLED"):e===6?new I("OCR_BUSY"):e===7?new I("OCR_UNAVAILABLE"):new I("OCR_INFERENCE_FAILED")}var fe=class{constructor(t){this.m=t;this.px=0;this.pxBytes=0;this.dicts=[null,null,null];this.classes=[0,0,0];this.held=[[],[],[]];this.latinKind="latin"}engineId(){let t=this.m._skw_engine_id(),n="";for(let s=t;this.m.HEAPU8[s]!==0&&s<t+64;s++)n+=String.fromCharCode(this.m.HEAPU8[s]);return n}put(t){let n=this.m._malloc(t.length);if(!n)throw new I("OCR_UNAVAILABLE");return this.m.HEAPU8.set(t,n),n}load(t,n,s,r,o={}){this.unload(t);let i=new Uint8Array(n),l=new Uint8Array(i.byteLength+1);l.set(i);let a=r===void 0?null:Oe(r),d=r===void 0?0:at(r);if(o.mrz===!0){if(t!==L.LATIN||r===void 0||!$t(r))throw new I("OCR_ASSET_INVALID")}else if(t===L.LATIN&&(r===void 0||r.endsWith(`
|
|
38
|
+
`)||d!==6625))throw new I("OCR_ASSET_INVALID");if(t===L.ARABIC&&(r===void 0||!r.endsWith(`
|
|
39
|
+
`)||d!==163||a[161]!==""))throw new I("OCR_ASSET_INVALID");let b=new Uint8Array(s),f=this.put(l),p=this.put(b);this.held[t]=[f,p];let y=this.m._skw_load(t,f,l.length,p,b.byteLength,d);if(y!==0)throw this.unload(t),it(y);this.dicts[t]=a,this.classes[t]=d,t===L.LATIN&&(this.latinKind=o.mrz===!0?"mrz":"latin")}recognizer(){return this.loaded(L.LATIN)?this.latinKind:null}unload(t){this.held[t].length&&this.m._skw_unload(t);for(let n of this.held[t])this.m._free(n);this.held[t]=[],this.dicts[t]=null}loaded(t){return this.held[t].length>0}pixels(t){if(t.length>this.pxBytes){if(this.px&&this.m._free(this.px),this.px=this.m._malloc(t.length),!this.px)throw new I("OCR_UNAVAILABLE");this.pxBytes=t.length}return this.m.HEAPU8.set(t,this.px),this.px}sharpness(t,n,s){let r=this.m._skw_sharpness(this.pixels(t),n,s);return r>=0&&Number.isFinite(r)?r:null}read(t,n,s,r,o,i,l,a){if(!Zt(l))throw new I("OCR_IMAGE_INVALID");if(l&U.LATIN&&!this.dicts[L.LATIN]||l&U.ARABIC&&!this.dicts[L.ARABIC]||!this.loaded(0))throw new I("OCR_UNAVAILABLE");let d=this.pixels(t);this.m._skw_set_detector_limit(a);let b=this.m._skw_read(d,n,s,r[0],r[1],r[2],r[3],o,i,l);if(b!==0)throw it(b);let f=this.m._skw_line_count(),p=this.m.HEAPU8.buffer,y=new DataView(p,this.m._skw_lines(),f*ne.SIZE),m=new Int32Array(p,this.m._skw_best()),u=new Float32Array(p,this.m._skw_values()),R=[];for(let S=0;S<f;S++){let A=S*ne.SIZE,w=y.getInt32(A+ne.SCRIPT,!0),B=y.getInt32(A+ne.OFFSET,!0),z=y.getInt32(A+ne.STEPS,!0);if(l===U.NONE){R.push({box:Array.from({length:8},(ie,Q)=>y.getFloat64(A+8*Q,!0))});continue}let H=this.dicts[w];if(!H)throw new I("OCR_INFERENCE_FAILED");let W=Le(m.subarray(B,B+z),u.subarray(B,B+z),this.classes[w],H,w===L.ARABIC),$=Array.from({length:8},(ie,Q)=>y.getFloat64(A+8*Q,!0)),J=R[R.length-1];w===L.ARABIC&&J&&J.arabic===void 0&&J.latin!==void 0&&Xt(J.box,$)?J.arabic=W:R.push(w===L.ARABIC?{box:$,arabic:W}:{box:$,latin:W})}return R}heapBytes(){return this.m.HEAPU8.length}dispose(){for(let t of[0,1,2])this.unload(t);this.px&&this.m._free(this.px),this.px=0,this.pxBytes=0}};function at(e){return(e.endsWith(`
|
|
40
|
+
`)?e.slice(0,-1):e).split(`
|
|
41
|
+
`).length+2}var Zt=e=>Number.isInteger(e)&&e>=U.NONE&&e<=U.BOTH,Xt=(e,t)=>e.every((n,s)=>n===t[s]);function $t(e){let t=e.split(`
|
|
42
|
+
`);return t.length===37&&new Set(t).size===37&&t.every(n=>/^[0-9A-Z<]$/.test(n))&&at(e)===39}async function lt(e){let t=await ot({instantiateWasm:(n,s)=>(WebAssembly.instantiate(e,n).then(r=>s(r,e)),{})});return new fe(t)}function Jt(){let e=null,t=null;return(n,s)=>{if(typeof OffscreenCanvas!="function"||(e||(e=new OffscreenCanvas(n,s),t=e.getContext("2d",{willReadFrequently:!0})),!t))return null;(e.width!==n||e.height!==s)&&(e.width=n,e.height=s);let r=t;return{draw(o){return r.clearRect(0,0,n,s),r.drawImage(o,0,0),r.getImageData(0,0,n,s).data}}}}function jt(){return{fetch:(...e)=>fetch(...e),now:()=>performance.now(),canvas:Jt(),instantiate:lt}}function Qt(e,t=jt()){let n=null,s="",r=960,o=0,i=!1,l=Promise.resolve(),a=m=>e.postMessage(m);async function d(m){if(t.canvas(1,1)===null)return a({id:m.id,kind:"failed",reason:"unsupported"});s=m.salt,r=m.detectorLimit;try{let u=await Te(m.baseUrl,_e,m.maxDownloadMs,t.fetch,t.now);o=u.downloadMs,i=u.cached;let R=await WebAssembly.compile(u.files.get("sekyro-ocr.wasm")),S=await t.instantiate(R),A=new TextDecoder("utf-8",{fatal:!0}).decode(u.files.get("mrz_dict.txt"));S.load(L.DETECTOR,u.files.get("det.param"),u.files.get("det.bin")),S.load(L.LATIN,u.files.get("mrz-rec.param"),u.files.get("mrz-rec.bin"),A,{mrz:!0}),u.files.clear(),n=S,a({id:m.id,kind:"ready",warmupMs:0,downloadMs:o,cached:i})}catch(u){a({id:m.id,kind:"failed",reason:u instanceof G?u.reason:"error"})}}async function b(m,u,R,S){if(!n)return u.close(),a({id:m,kind:"error",code:"not_ready"});let A=u.width,w=u.height,B=t.canvas(A,w);if(!B)return u.close(),a({id:m,kind:"failed",reason:"unsupported"});let z=B.draw(u);u.close();try{a({id:m,...await Ce(n,z,A,w,{detectorLimit:S,salt:s,region:R,now:t.now})})}catch{a({id:m,kind:"error",code:"OCR_INFERENCE_FAILED"})}}async function f(m,u,R){if(!n)return u.close(),a({id:m,kind:"error",code:"not_ready"});let S=u.width,A=u.height,w=t.canvas(S,A);if(!w)return u.close(),a({id:m,kind:"failed",reason:"unsupported"});let B=w.draw(u);u.close();try{let z=t.now(),H=n.read(B,S,A,[0,0,1,1],1,de,U.NONE,R);a({id:m,kind:"layout",ms:Math.round(t.now()-z),lineBoxes:st(H.map(W=>W.box),S,A)})}catch{a({id:m,kind:"error",code:"OCR_INFERENCE_FAILED"})}}async function p(m){if(!n)return a({id:m,kind:"error",code:"not_ready"});let u=t.now(),R=960,S=200,A=new Uint8Array(R*S*4).fill(255);try{await Ce(n,A,R,S,{detectorLimit:r,salt:s,now:t.now})}catch{return a({id:m,kind:"error",code:"OCR_INFERENCE_FAILED"})}a({id:m,kind:"ready",warmupMs:Math.round(t.now()-u),downloadMs:o,cached:i})}async function y(m){switch(m.kind){case"init":return d(m);case"warmup":return p(m.id);case"band":return b(m.id,m.bitmap,void 0,m.detectorLimit);case"still":return b(m.id,m.bitmap,m.region,m.detectorLimit);case"layout":return f(m.id,m.bitmap,m.detectorLimit);case"dispose":n?.dispose(),n=null,e.close();return}}e.onmessage=m=>{let u=m.data;l=l.then(()=>y(u)).catch(()=>a({id:u.id,kind:"error",code:"OCR_INFERENCE_FAILED"}))}}typeof WorkerGlobalScope<"u"&&typeof self<"u"&&self instanceof WorkerGlobalScope&&Qt(self);export{jt as defaultDeps,Qt as installOcrWorkerHost};
|