@sekyro/web 0.1.0-rc.25 → 0.1.0-rc.26
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 +10 -0
- package/dist/{capture-session-doc-O33KRXH7.js → capture-session-doc-WZMI5XPE.js} +1 -1
- package/dist/{capture-session-v3-BoGn8vLv.d.cts → capture-session-v3-BKSjJ6L0.d.cts} +1 -1
- package/dist/{capture-session-v3-C0bbHvDc.d.ts → capture-session-v3-C1I_GLC9.d.ts} +1 -1
- package/dist/{chunk-MXWLCDFX.js → chunk-4DEPREJ3.js} +1 -1
- package/dist/{chunk-DIKSFEYQ.js → chunk-65JZHKVG.js} +1 -1
- package/dist/{chunk-24F6JCVH.js → chunk-7MZW3FFH.js} +1 -1
- package/dist/chunk-DVTK2DGX.js +1 -0
- package/dist/chunk-GPFAPAS6.js +3 -0
- package/dist/{chunk-EHKCOBE2.js → chunk-LLX2CKZ3.js} +1 -1
- package/dist/chunk-LV23FCYP.js +1 -0
- package/dist/{chunk-TDLIXFDT.js → chunk-NFHLJOHW.js} +1 -1
- package/dist/{chunk-J4S3QMK6.js → chunk-OVP7FAMJ.js} +1 -1
- package/dist/{chunk-7HV77AOV.js → chunk-XOTKATN6.js} +1 -1
- package/dist/{chunk-4ESM6SSR.js → chunk-ZCW6PNUX.js} +1 -1
- package/dist/client/index.cjs +1 -1
- package/dist/client/index.d.cts +3 -3
- package/dist/client/index.d.ts +3 -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/create-document-capture-OXPLKHOF.js +1 -0
- package/dist/{create-verification-DOBYRCV_.d.ts → create-verification-7wPXJN_P.d.ts} +232 -121
- package/dist/{create-verification-D5CrT5f5.d.cts → create-verification-YeuI7_B0.d.cts} +232 -121
- package/dist/{detector-scanic-YCDNLCGV.js → detector-scanic-23DAYT3H.js} +1 -1
- package/dist/{icao-gate-CJPTgKFb.d.ts → icao-gate-BK8TGaCk.d.ts} +1 -1
- package/dist/{icao-gate-DGtY696t.d.cts → icao-gate-pD2dUV3P.d.cts} +1 -1
- package/dist/{icao-policy-Bm0rG91t.d.cts → icao-policy-CdR6PFHS.d.cts} +2 -2
- package/dist/{icao-policy-D8domgld.d.ts → icao-policy-qJpZOOOu.d.ts} +2 -2
- package/dist/index.cjs +3 -3
- package/dist/index.d.cts +9 -9
- package/dist/index.d.ts +9 -9
- package/dist/index.js +1 -1
- package/dist/internal/index.cjs +3 -3
- package/dist/internal/index.d.cts +68 -64
- package/dist/internal/index.d.ts +68 -64
- package/dist/internal/index.js +1 -1
- package/dist/plan-runner-EP26JU6A.js +1 -0
- package/dist/{types-ZBcpvLdo.d.ts → types-DB-cZTSn.d.cts} +127 -11
- package/dist/{types-ZBcpvLdo.d.cts → types-DB-cZTSn.d.ts} +127 -11
- package/dist/upload-file-EGXXM6TQ.js +1 -0
- package/package.json +1 -1
- package/sbom.cdx.json +10 -10
- package/dist/chunk-6XXMWK72.js +0 -1
- package/dist/chunk-GLXOSYBH.js +0 -3
- package/dist/chunk-MGO2ME5X.js +0 -1
- package/dist/create-document-capture-OLKNUVTU.js +0 -1
- package/dist/plan-runner-VKPRZ3AD.js +0 -1
- package/dist/upload-file-UYXOHCRG.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as re,b as ne}from"./chunk-SX7TUC3V.js";import{b as le,c as ce,d as ue}from"./chunk-POIQGEZM.js";import{a as Q,c as Y,e as j,g as $,h as A,k as R,m as J,n as te}from"./chunk-CPUECYAJ.js";import{b as G,c as de,d as L,e as pe}from"./chunk-FPXL63KZ.js";import{a as q,c as z,d as X,e as Z}from"./chunk-TSA6GHUG.js";import{d as ee}from"./chunk-EHKCOBE2.js";import{e as ie,f as ae,h as x,j as se,l as oe}from"./chunk-FSSMUAKC.js";var Ie=[...Q.filter(i=>i.startsWith("video/mp4")),"video/webm;codecs=h264","video/webm;codecs=avc1","video/webm;codecs=vp8","video/webm;codecs=vp9","video/webm"],me=new Set;function De(i){let e=/(?:Chrome|Chromium)\/(\d+)\./.exec(i??"");return e?Number(e[1]):null}function he(i=Oe(),e=globalThis.navigator?.userAgent){if(i===void 0)return"";let t=De(e)===126;for(let r of Ie)if(!(me.has(r)||t&&r.startsWith("video/mp4")))try{if(i(r))return r}catch{}return""}function F(i){i!==""&&me.add(i)}function fe(i){return i.replace(/^video\/x-matroska/i,"video/webm")}function ut(i){let e=/codecs=["']?([^,;"']+)/i.exec(i);return e?e[1].trim():i.split(";")[0].trim()}function Oe(){let i=globalThis.MediaRecorder;return i&&typeof i.isTypeSupported=="function"?e=>i.isTypeSupported(e):void 0}var N=2500,Pe=1e3,xe=1500,ve=25e5,Ge=100,Le=700,Fe=20,Ve=1500,V=null;function Ne(){return V??(V=import("./clip-inspect-DLJXVKV6.js").catch(i=>{throw V=null,i})),V.catch(()=>null)}var S=class extends Error{constructor(e,t){super(t??e),this.kind=e}},Ue=100;function U(i,e){return i.stats===void 0?!1:i.stats===null?!0:i.stats.durationMs<e-Ue}function ge(i,e){return i.stats?e.stats?i.stats.durationMs>e.stats.durationMs:!0:!1}var I=class{constructor(e={}){this.recorder=null;this.stream=null;this.chunks=[];this.bytes=0;this.hardStopTimer=null;this.graceTimer=null;this.pollTimer=null;this.settled=!1;this.now=e.now??(()=>globalThis.performance?.now?.()??Date.now())}clearTimers(){this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.graceTimer&&clearTimeout(this.graceTimer),this.pollTimer&&clearInterval(this.pollTimer),this.hardStopTimer=null,this.graceTimer=null,this.pollTimer=null}record(e,t,r,n=N,a){let s=he(),o=Ne();return this.recordRaw(e,t,r,n,a,s).then(c=>He(c,o),c=>{throw c instanceof S&&(c.requestedMimeType=s),c})}recordRaw(e,t,r,n,a,s){return this.recorder&&!this.settled?Promise.reject(new S("generic","record() called while a recording is in flight \u2014 ClipRecorder handles one recording at a time")):(this.recorder=null,this.clearTimers(),this.chunks=[],this.bytes=0,this.settled=!1,this.stream=e,new Promise((o,c)=>{let l;try{l=new MediaRecorder(e,s?{mimeType:s,videoBitsPerSecond:ve}:{videoBitsPerSecond:ve})}catch{try{l=new MediaRecorder(e)}catch{c(new S("unsupported"));return}}this.recorder=l;let d=h=>{this.settled||(this.settled=!0,this.clearTimers(),h())},u=()=>d(()=>{let h=fe(l.mimeType||s||Y),b=new Blob(this.chunks,{type:h});if(b.size===0){c(new S("generic","empty clip"));return}if(A(b)){c(new S("cliptoolarge"));return}o({blob:b,mimeType:h,requestedMimeType:s})});l.ondataavailable=h=>{h.data&&h.data.size&&(this.chunks.push(h.data),this.bytes+=h.data.size,this.bytes>$&&d(()=>{try{l.state!=="inactive"&&l.stop()}catch{}c(new S("cliptoolarge"))}))},l.onstop=u,l.onerror=()=>d(()=>c(new S("generic")));let f=this.now();if(r!==void 0||a!==void 0){let h=!1;l.onstart=()=>{if(!(h||this.settled)&&(h=!0,f=this.now(),r!==void 0))try{r()}catch{}}}try{l.start(Pe)}catch{d(()=>c(new S("generic")));return}let v=()=>{if(this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=null,this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.hardStopTimer=null,this.settled||t?.(),l.state!=="inactive"){try{l.stop()}catch{u()}this.graceTimer=setTimeout(u,xe)}else u()},p=this.now();if(a===void 0){this.hardStopTimer=setTimeout(v,n);return}let m=null,y=!1;this.hardStopTimer=setTimeout(v,n+Le),this.pollTimer=setInterval(()=>{if(this.settled||y)return;let h=null;try{h=a.latest()}catch{h=null}let b=h?.presentationTimeMs;b!==void 0&&Number.isFinite(b)&&b>=f&&m===null&&(m=b);let C=m!==null&&b!==void 0&&b-m>=n,E=m===null&&this.now()-p>=n;if(!(!C&&!E)){if(y=!0,this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=null,E){v();return}this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.hardStopTimer=setTimeout(v,Ge)}},Fe)}))}stop(e){this.clearTimers();let t=this.recorder;if(t&&t.state!=="inactive")try{t.stop()}catch{}this.recorder=null,(e??this.stream)?.getTracks().forEach(n=>n.stop()),this.stream=null}};async function He(i,e){let t,r=new Promise(l=>{t=setTimeout(()=>l(null),Ve)}),n=await Promise.race([e,r]);if(clearTimeout(t),n===null)return i;let a;try{a=await n.blobBytes(i.blob)}catch{return{...i,stats:null}}let s=n.inspectClipBytes(a);if(s?.container!=="webm")return{...i,stats:s};let o=n.withWebmDuration(a,s.durationMs);if(o===null)return{...i,stats:s};let c=n.inspectClipBytes(o);return c===null||c.frames!==s.frames||c.durationMs!==s.durationMs?{...i,stats:s}:{...i,blob:new Blob([o],{type:i.blob.type}),stats:s}}var Ke=["magenta","yellow","green","blue"];var Be={magenta:"rgb(255, 72, 150)",yellow:"rgb(255, 190, 0)",green:"rgb(0, 238, 175)",blue:"rgb(25, 150, 255)",dark:"rgb(0, 0, 0)"};function ft(i){return Be[i]}var We=4,qe=4,D=i=>typeof i=="number"&&Number.isFinite(i);function be(i){if(typeof i!="object"||i===null)return!1;let e=i;if(typeof e.nonce!="string"||e.nonce.length===0||!Array.isArray(e.colours)||e.colours.length<1||e.colours.length>8||!e.colours.every(r=>Ke.includes(r))||!Array.isArray(e.onsetsMs)||e.onsetsMs.length!==e.colours.length)return!1;let t=-1;for(let r of e.onsetsMs){if(!D(r)||r<0||r<=t)return!1;t=r}return!(!D(e.holdMs)||e.holdMs<=0||!D(e.endMs)||e.endMs<=t||!D(e.clipMs)||e.clipMs<e.endMs||e.clipMs>8e3)}function ye(i,e){return be(i)?Math.max(e,Math.ceil(i.clipMs)):e}function Me(i,e){let t=e.now??(()=>performance.now()),r=be(i)?i:void 0,n=[],a=null,s=null,o=null,c=!1,l=null,d=p=>{l=p;try{e.paint(p)}catch{}},u=p=>{let m=e.frames?.()??null;return m!==null&&o!==null?m.mediaTimeMs+(p-m.presentationTimeMs)-o:p-(s??p)},f=(p,m,y=0)=>{if(c)return;let h=Math.max(0,p-u(t()));a=setTimeout(()=>{if(a=null,!c){if(y<We&&u(t())<p-qe){f(p,m,y+1);return}m()}},h)},v=p=>{if(r===void 0)return;let m=r.endMs;if(p>=r.colours.length){f(m,()=>d(null));return}let y=r.onsetsMs[p],h=p+1<r.onsetsMs.length?r.onsetsMs[p+1]:m;f(y,()=>{let b=u(t());if(b>m){l!==null&&d(null);return}let C=r.colours[p];d(C);let E=n.length===0?0:n[n.length-1].tMs;n.push({tMs:Math.max(E,Math.round(b)),colour:C});let M=y+r.holdMs;if(M<h){f(M,()=>{if(u(t())>m){l!==null&&d(null);return}d("dark"),v(p+1)});return}v(p+1)})};return{started(p){if(r===void 0||c||s!==null)return;s=p;let m=e.frames?.()??null;o=m===null?null:m.mediaTimeMs+(p-m.presentationTimeMs),v(0)},stop(){c||(c=!0,a!==null&&clearTimeout(a),a=null,l!==null&&d(null))},report(){return r===void 0?void 0:{nonce:r.nonce,rendered:[...n]}}}}function Se(i,e,t=.92){return new Promise((r,n)=>{let a=i.videoWidth,s=i.videoHeight;if(!a||!s){n(new Error("video-not-ready"));return}let o=e.getContext("2d");if(!o){n(new Error("no-2d-context"));return}e.width=a,e.height=s,o.scale(-1,1),o.drawImage(i,-a,0),e.toBlob(c=>c?r(c):n(new Error("empty-keyframe")),"image/jpeg",t)})}var O=class{constructor(e){this.timer=null;this.frameCallbackId=null;this.running=!1;this.busy=!1;this.lastRunAt=Number.NEGATIVE_INFINITY;this.degradeCount=0;this.durations=[];this.options=e,this.periodMs=1e3/e.cadenceHz}start(){if(this.running)return;this.running=!0;let e=this.options.video;if(typeof e?.requestVideoFrameCallback=="function"){let t=()=>{this.running&&(this.frameCallbackId=e.requestVideoFrameCallback?.(()=>{this.frameCallbackId=null,this.now()-this.lastRunAt>=this.periodMs&&this.tick(),t()}))};t();return}this.timer=setInterval(()=>this.tick(),this.periodMs)}stop(){this.running=!1,this.timer!==null&&(clearInterval(this.timer),this.timer=null),this.frameCallbackId!==null&&(this.options.video?.cancelVideoFrameCallback?.(this.frameCallbackId),this.frameCallbackId=null)}stats(){let e=this.durations.length===0?0:this.durations.reduce((t,r)=>t+r,0)/this.durations.length;return{degradeCount:this.degradeCount,meanDetectMs:e}}now(){return this.options.now?.()??performance.now()}tick(){if(!this.running)return;if(this.busy){this.degradeCount+=1;return}this.busy=!0,this.lastRunAt=this.now();let e=this.now();this.options.run().catch(()=>{}).finally(()=>{this.busy=!1,this.durations.push(this.now()-e),this.durations.length>20&&this.durations.shift()})}};var ze=Object.freeze({Q_GOOD:.6,RISE_PER_S:.9,FALL_PER_S:.25,CENTER_FALLOFF_IOD_MULTIPLE:1.35,BOX_EYE_OFFSET_FACTOR:.12,IOD_BOX_PROXY_FACTOR:.42,SIZE_IDEAL_MIN:.12,SIZE_IDEAL_MAX:.3,SIZE_HARD_MIN:.08,SIZE_HARD_MAX:.45,ROLL_MAX_DEG:25,MOTION_VELOCITY_IOD_PER_S:.5,MOTION_TAU_S:.4,MOTION_DEADBAND_IOD_PER_S:.1,READY_WINDOW_MS:500,GUIDE_SIZE:.6,GUIDE_CENTERING:.6,GUIDE_POSE:.6,GUIDE_EXPOSURE:.6,GUIDE_SHARPNESS:.35,GUIDE_MOTION:.5}),_=i=>Math.min(1,Math.max(0,i)),k=class{constructor(e={}){this.p=0;this.lastTickAt=null;this.lastCenter=null;this.velocityEma=0;this.qWindow=[];this.lastSizeDirection="ideal";this.t={...ze,...e}}reset(){this.p=0,this.lastTickAt=null,this.lastCenter=null,this.velocityEma=0,this.qWindow=[],this.lastSizeDirection="ideal"}tick(e){let{observation:t,quality:r,timestampMs:n}=e,a=this.lastTickAt===null?0:Math.max(0,(n-this.lastTickAt)/1e3);this.lastTickAt=n;let s={presence:0,single:1,centering:0,size:0,pose:0,sharpness:_(r.sharpness),exposure:_(r.exposure),motion:1};if(t!==null){s.presence=1,s.single=(t.extraFaces??0)>0?0:1;let d=this.geometryOf(t,e);s.centering=d.centering,s.size=d.size,s.pose=d.pose,s.motion=this.motionOf(d.center,d.iod,n)}else this.lastCenter=null,this.velocityEma=0;let o=Math.min(s.presence,s.single,s.centering,s.size,s.pose,s.sharpness,s.exposure,s.motion);this.p=_(this.p+(o>=this.t.Q_GOOD?this.t.RISE_PER_S*o:-this.t.FALL_PER_S*(1-o))*a),this.qWindow.push({at:n,q:o}),this.qWindow=this.qWindow.filter(d=>d.at>=n-this.t.READY_WINDOW_MS);let c=this.qWindow.map(d=>d.q);if(c.length>=3){let d=Math.min(...c),u=c.indexOf(d);c=c.filter((f,v)=>v!==u)}let l=this.p>=1&&c.every(d=>d>=this.t.Q_GOOD);return{at:n,q:o,p:this.p,factors:s,guidanceKey:this.guidanceOf(s,r,o),ready:l,accepted:o>=this.t.Q_GOOD}}geometryOf(e,t){let{box:r,eyes:n}=e,a={x:t.frameWidth/2,y:t.frameHeight/2},s=Math.min(t.frameWidth,t.frameHeight),o=n!==void 0?{x:(n.left.x+n.right.x)/2,y:(n.left.y+n.right.y)/2}:{x:r.x+r.width/2,y:r.y+r.height/2-this.t.BOX_EYE_OFFSET_FACTOR*r.height},c=n!==void 0?Math.hypot(n.right.x-n.left.x,n.right.y-n.left.y):this.t.IOD_BOX_PROXY_FACTOR*r.width,l=Math.hypot(o.x-a.x,o.y-a.y),d=c<=0?0:1-_(l/(this.t.CENTER_FALLOFF_IOD_MULTIPLE*c)),u=s>0?c/s:0;this.lastSizeDirection=u<this.t.SIZE_IDEAL_MIN?"far":u>this.t.SIZE_IDEAL_MAX?"close":"ideal";let f;u<this.t.SIZE_HARD_MIN||u>this.t.SIZE_HARD_MAX?f=0:u<this.t.SIZE_IDEAL_MIN?f=(u-this.t.SIZE_HARD_MIN)/(this.t.SIZE_IDEAL_MIN-this.t.SIZE_HARD_MIN):u>this.t.SIZE_IDEAL_MAX?f=(this.t.SIZE_HARD_MAX-u)/(this.t.SIZE_HARD_MAX-this.t.SIZE_IDEAL_MAX):f=1;let v=1;if(n!==void 0){let p=Math.abs(Math.atan2(n.right.y-n.left.y,n.right.x-n.left.x))*180/Math.PI;v=1-_(p/this.t.ROLL_MAX_DEG)}return{center:o,iod:c,centering:d,size:f,pose:v}}motionOf(e,t,r){let n=this.lastCenter;if(this.lastCenter={...e,at:r},n===null||t<=0)return 1;let a=(r-n.at)/1e3;if(a<=0)return 1;let s=Math.hypot(e.x-n.x,e.y-n.y)/t/a;s<=this.t.MOTION_DEADBAND_IOD_PER_S&&(s=0);let o=1-Math.exp(-a/this.t.MOTION_TAU_S);return this.velocityEma=o*s+(1-o)*this.velocityEma,1-_(this.velocityEma/this.t.MOTION_VELOCITY_IOD_PER_S)}guidanceOf(e,t,r){if(e.presence<=0)return"fcv3.no_face";if(e.single<=0)return"fcv3.one_face";if(e.size<this.t.GUIDE_SIZE)return this.sizeGuidance();if(e.centering<this.t.GUIDE_CENTERING)return"fcv3.center_face";if(e.pose<this.t.GUIDE_POSE)return"fcv3.straighten";if(e.exposure<this.t.GUIDE_EXPOSURE)return this.exposureGuidance(t);if(e.sharpness<this.t.GUIDE_SHARPNESS)return"fcv3.steady_camera";if(e.motion<this.t.GUIDE_MOTION)return"fcv3.hold_still";if(r<this.t.Q_GOOD){let n=[["size",this.sizeGuidance()],["centering","fcv3.center_face"],["pose","fcv3.straighten"],["exposure",this.exposureGuidance(t)],["sharpness","fcv3.steady_camera"],["motion","fcv3.hold_still"]],a=n[0];for(let s of n)e[s[0]]<e[a[0]]&&(a=s);return a[1]}return"fcv3.hold_still"}sizeGuidance(){return this.lastSizeDirection==="far"?"fcv3.come_closer":"fcv3.move_back"}exposureGuidance(e){let t=(G[0]+G[1])/2;return e.meanLuma<t?"fcv3.more_light":"fcv3.too_bright"}};var Xe=["single","size","centering","pose","exposure","sharpness","motion"];function Ze(i){if(i.accepted)return null;if(i.factors.presence<=0)return"no_face";let e="single";for(let t of Xe)i.factors[t]<i.factors[e]&&(e=t);return e}var w=class{constructor(){this.blocked={};this.acceptedMs=0;this.ticks=0;this.lastAt=null}record(e){let t=this.lastAt===null?0:Math.max(0,e.at-this.lastAt);this.lastAt=e.at,this.ticks+=1;let r=Ze(e);if(r===null){this.acceptedMs+=t;return}let n=this.blocked[r]??{count:0,ms:0};n.count+=1,n.ms+=t,this.blocked[r]=n}summary(){let e={};for(let[t,r]of Object.entries(this.blocked))e[t]={count:r.count,ms:Math.round(r.ms)};return{blocked:e,acceptedMs:Math.round(this.acceptedMs),ticks:this.ticks}}};var Qe=["obs","manycam","virtual","snap camera","xsplit","droidcam","iriun","camo"],Ye=[/^(front|back|rear)( [a-z ]+)? camera$/i,/^caméra (avant|arrière)\b/i,/^cámara (frontal|trasera|delantera)\b/i,/^câmera (frontal|traseira)\b/i,/^(front|rück)kamera\b/i,/^الكاميرا (الأمامية|الخلفية)/,/^camera2? ?\d+, facing (front|back|external)/i,/facetime/i,/\b(integrated|built-in|builtin) (web)?cam(era)?\b/i,/\b(hd )?web ?cam\b/i,/\([0-9a-f]{4}:[0-9a-f]{4}\)\s*$/i];function je(i){let e=(i??"").trim().toLowerCase();return e.length===0?"unknown":Qe.some(t=>e.includes(t))?"known_virtual":Ye.some(t=>t.test(e))?"platform":"unknown"}function Te(i){if(typeof i!="function")return!1;try{return/\{\s*\[native code\]\s*\}\s*$/.test(Function.prototype.toString.call(i))}catch{return!1}}function $e(i=globalThis){return Te(i.navigator?.mediaDevices?.getUserMedia)&&Te(i.MediaStreamTrack?.prototype?.getSettings)}async function Je(i,e=globalThis){let t=e.crypto?.subtle?.digest;if(typeof t=="function")try{let r=new Uint8Array(await t.call(e.crypto?.subtle,"SHA-256",new TextEncoder().encode(i)));return Array.from(r.subarray(0,8),n=>n.toString(16).padStart(2,"0")).join("")}catch{return}}async function Ce(i,e=globalThis){let t={};try{t=typeof i.getSettings=="function"?i.getSettings()??{}:{}}catch{t={}}let r={};if((t.facingMode==="user"||t.facingMode==="environment"||t.facingMode==="left"||t.facingMode==="right")&&(r.facingMode=t.facingMode),typeof t.frameRate=="number"&&Number.isFinite(t.frameRate)&&(r.frameRate=t.frameRate),typeof t.width=="number"&&Number.isFinite(t.width)&&(r.width=t.width),typeof t.height=="number"&&Number.isFinite(t.height)&&(r.height=t.height),typeof t.deviceId=="string"&&t.deviceId.length>0){let a=await Je(t.deviceId,e);a!==void 0&&(r.deviceIdHash=a)}let n;try{n=i.label}catch{n=void 0}return{trackSettings:r,capabilitiesPresent:typeof i.getCapabilities=="function",labelClass:je(n),prototypesIntact:$e(e)}}var H=i=>Math.round(i*100)/100;function Ee(i){let e=i,t=typeof e?.requestVideoFrameCallback=="function",r=null,n=null,a=0,s=0,o=0,c=0,l=0,d=0,u=()=>{!t||e?.requestVideoFrameCallback===void 0||(r=e.requestVideoFrameCallback((f,v)=>{if(r=null,!t)return;let p=v.presentationTime;if(n!==null){let m=p-n.presentationTimeMs;s+=1;let y=m-o;o+=y/s,c+=y*(m-o)}typeof v.captureTime=="number"&&Number.isFinite(v.captureTime)&&(l+=p-v.captureTime,d+=1),a+=1,n={mediaTimeMs:v.mediaTime*1e3,presentationTimeMs:p},u()}))};return u(),{latest:()=>n,stats:()=>({n:a,meanGapMs:s===0?0:H(o),stdGapMs:s<2?0:H(Math.sqrt(c/(s-1))),captureLatencyMs:d===0?null:H(l/d)}),stop:()=>{t&&(t=!1,r!==null&&e?.cancelVideoFrameCallback?.(r),r=null)}}}function _e(i,e,t){return{...i,rvfc:e,rampPainter:t}}var et=1e3,K="fcv3.hold_upright",tt=200,B=4,rt=600,nt=1e3,Re={sharpness:1,exposure:1,meanLuma:128};function it(i,e){return e.width=i.videoWidth,e.height=i.videoHeight,e.getContext("2d").drawImage(i,0,0),new Promise((t,r)=>e.toBlob(n=>n?t(n):r(new Error("empty-keyframe")),"image/jpeg",.92))}function at(){return z()==="phone"}var ke=class{constructor(e){this.handlers=new Map;this.stateValue="idle";this.attempt=0;this.stream=null;this.detector=null;this.scheduler=null;this.gate=null;this.profiler=null;this.lastGuidanceKey=null;this.positioningStartedAt=0;this.cameraRequestedAt=null;this.cameraReadyAt=null;this.faceAcquiredAt=null;this.captureCompleteAt=null;this.fired=!1;this.carriedDegrade=0;this.carriedMeans=[];this.blockStats=null;this.lastGateSnapshotAt=Number.NEGATIVE_INFINITY;this.uprightGuard=!1;this.trackProvenance=null;this.ramp=null;this.snapshotCanvas=null;this.options=e,this.facing=e.facingMode??"user"}get state(){return this.stateValue}on(e,t){let r=this.handlers.get(e);return r||(r=new Set,this.handlers.set(e,r)),r.add(t),()=>r?.delete(t)}emit(e,t){for(let r of[...this.handlers.get(e)??[]])r(t)}async start(e={}){e.facingMode!==void 0&&(this.facing=e.facingMode),this.attempt+=1,await this.run(this.attempt)}get facingMode(){return this.facing}retry(){this.teardownAttempt(),this.start()}switchCamera(){this.facing=this.facing==="user"?"environment":"user",this.teardownAttempt(),this.start()}restart(e){this.facing=e,this.teardownAttempt(),this.start()}destroy(){this.attempt+=1,this.teardownAttempt(),this.detector?.destroy(),this.detector=null,this.options.video.srcObject=null}async run(e){let{options:t}=this;this.fired=!1,this.lastGuidanceKey=null,this.carriedDegrade=0,this.carriedMeans=[],this.cameraRequestedAt=null,this.cameraReadyAt=null,this.faceAcquiredAt=null,this.captureCompleteAt=null,this.uprightGuard=(t.isPhone??at)(),this.setState("preflight");let r=j();if(r!=="OK"){this.fail(r==="INSECURE_CONTEXT"?"insecure":"unsupported",{phase:"preflight"});return}this.setState("acquiring");let n=t.getUserMedia??(l=>navigator.mediaDevices.getUserMedia(l)),a;this.cameraRequestedAt=this.now();try{let{facingMode:l,...d}=q(X(),this.facing).video;a=await ne(this.facing,d,{getUserMedia:n,enumerateDevices:lt(t)})}catch(l){if(e!==this.attempt)return;if(l instanceof re){this.fail("backcamera",{phase:"acquiring",name:R(l)});return}this.fail(J(l),{phase:"acquiring",name:R(l)});return}if(ee(a),te(a),e!==this.attempt){for(let l of a.getTracks())l.stop();return}this.stream=a;let s=a.getVideoTracks?.()[0];if(this.trackProvenance=s===void 0?null:Ce(s).catch(()=>null),this.facing=Z(a)??this.facing,t.video.srcObject=a,await t.video.play().catch(()=>{}),e!==this.attempt)return;if(this.cameraReadyAt=this.now(),this.detector===null){let l={v3AssetBaseUrl:t.v3AssetBaseUrl},d=t.createDetector??(t.createWorker!==void 0&&se()?async()=>{try{return await oe.create(t.createWorker(),l)}catch{return x(l)}}:()=>x(l)),u;try{u=await d()}catch(f){e===this.attempt&&this.fail("models",{phase:"models",name:R(f)},f instanceof ie?f.fallbackReason:ot(f));return}if(e!==this.attempt){u.destroy();return}this.detector=u,this.options.telemetry?.({type:"detector",tier:u.tier,fallbackReason:u.fallbackReason})}let o=le(),c=t.deviceClass??ce(o);this.profiler=new ue(c),this.options.telemetry?.({type:"profile",staticClass:c,activeClass:this.profiler.deviceClass,simd:o.simd}),this.gate=new k(t.thresholds??{}),this.blockStats=new w,this.lastGateSnapshotAt=this.now(),t.rankKeyframes?.()&&import("./keyframe-rank-YAJLYJYF.js").then(l=>W=l,()=>{}),this.setState("positioning"),this.positioningStartedAt=this.now(),this.startScheduler(e)}get animations(){return this.profiler?.profile.animations??"full"}startScheduler(e){let t=this.profiler;if(t===null)return;if(this.scheduler!==null){let n=this.scheduler.stats();this.carriedDegrade+=n.degradeCount,n.meanDetectMs>0&&this.carriedMeans.push(n.meanDetectMs),this.scheduler.stop()}let r=new O({cadenceHz:t.profile.cadenceHz,video:this.options.video,now:this.options.now,run:()=>this.detectTick(e)});this.scheduler=r,r.start()}async detectTick(e){let{detector:t,gate:r,profiler:n}=this,a=this.options.video;if(e!==this.attempt||t===null||r===null||n===null||this.fired||a.videoWidth===0)return;if(this.isLandscape()){this.holdUpright(e);return}let s=n.deviceClass,o=this.now(),c=this.options.makeSnapshot?.(a,n.profile.inputWidth)??this.defaultSnapshot(a,n.profile.inputWidth),l=null;try{l=await t.detect(c,a.videoWidth,a.videoHeight)}catch{l=null}if(e!==this.attempt||this.fired)return;n.record(this.now()-o),n.deviceClass!==s&&this.startScheduler(e);let d=l===null?Re:this.options.measureQuality?.(a,l.box)??this.defaultQuality(a,l.box),u=r.tick({timestampMs:this.now(),observation:l,quality:d,frameWidth:a.videoWidth,frameHeight:a.videoHeight});u.accepted&&this.faceAcquiredAt===null&&(this.faceAcquiredAt=u.at),this.blockStats?.record(u),!u.ready&&u.at-this.lastGateSnapshotAt>=et&&(this.lastGateSnapshotAt=u.at,this.reportGate(!1)),this.emit("checks",{engine:"v3",progress:u.p,q:u.q,factors:u.factors,attempt:e}),u.guidanceKey!==this.lastGuidanceKey&&(this.lastGuidanceKey=u.guidanceKey,this.emit("guidance",{key:u.guidanceKey})),u.ready&&this.stateValue==="positioning"&&(this.fired=!0,this.captureCompleteAt=u.at,this.fire(e))}async fire(e){let{options:t}=this,r=this.scheduler;r?.stop(),this.reportGate(!0);let n=r?.stats()??{degradeCount:0,meanDetectMs:0},a=[...this.carriedMeans,...n.meanDetectMs>0?[n.meanDetectMs]:[]];t.telemetry?.({type:"fired",timeToGateMs:this.now()-this.positioningStartedAt,degradeCount:this.carriedDegrade+n.degradeCount,meanDetectMs:a.length===0?0:a.reduce((M,g)=>M+g,0)/a.length});let s=t.mode??"clip",o=t.rankKeyframes?.()&&W?W.default(this,e).catch(()=>this.collectKeyframes(e)):this.collectKeyframes(e);if(s==="photo"){let M=this.watchRotation(e,null),g=await o;if(M(),e!==this.attempt)return;if(g===null){this.fail("generic",{phase:"keyframes"});return}let P=await this.provenance({n:0,meanGapMs:0,stdGapMs:0,captureLatencyMs:null},!1);if(e!==this.attempt)return;this.finishCapture({keyframe:g.blob,previewDataUrl:g.previewDataUrl,...P});return}this.setState("recording");let c=this.stream;if(c===null){this.fail("generic",{phase:"recording"});return}let l=t.screenRamp?.(),d=l!==void 0,u=null;o.then(M=>{u=M},()=>{});let f=()=>{e===this.attempt&&u!==null&&this.emit("frozen",{previewDataUrl:u.previewDataUrl})},v=ye(l,N),p=null,m,y=0;try{let M=this.recordTake(e,c,l,v,void 0).then(T=>T,T=>({failed:T})),[g,P]=await Promise.all([M,o]);if(m=P,e!==this.attempt)return;if("failed"in g){if(g.failed.kind==="cliptoolarge")throw g.failed;F(g.failed.requestedMimeType??"")}else p=g,U(g.clip,v)?g.clip.stats===null&&F(g.clip.requestedMimeType??""):f();if(p===null||U(p.clip,v)){y=1,t.telemetry?.({type:"clip_retake",reason:p===null?"error":p.clip.stats===null?"unreadable":"short"});let T=null;try{T=await this.recordTake(e,c,l,v,f)}catch(Ae){if(p===null)throw Ae}if(e!==this.attempt)return;T!==null&&(p===null||ge(T.clip,p.clip))&&(p=T),T===null&&f()}}catch(M){if(e!==this.attempt)return;let g=M.kind;this.fail(g==="cliptoolarge"?"cliptoolarge":"recorder",{phase:"recording",name:R(M)});return}if(p===null){this.fail("recorder",{phase:"recording"});return}let{clip:h,rvfc:b,report:C}=p;if(A(h.blob)){this.fail("cliptoolarge",{phase:"recording"});return}if(m===null){this.fail("generic",{phase:"keyframes"});return}let E=await this.provenance(b,d);e===this.attempt&&this.finishCapture({clip:h.blob,clipMimeType:h.mimeType,...h.stats?{clipStats:h.stats}:{},clipRetakes:y,keyframe:m.blob,previewDataUrl:m.previewDataUrl,...C!==void 0&&C.rendered.length>0?{screenRamp:C}:{},...E})}async recordTake(e,t,r,n,a){let s=this.options.createRecorder?.()??new I({now:()=>this.now()}),o=Ee(this.options.video),c=Me(r,{paint:u=>{(u===null||e===this.attempt)&&this.emit("ramp",{colour:u})},now:()=>this.now(),frames:o.latest});this.ramp=c;let l=()=>{o.stop(),c.stop(),this.ramp===c&&(this.ramp=null)},d=this.watchRotation(e,s);try{return{clip:await s.record(t,a,()=>c.started(this.now()),n,o),rvfc:o.stats(),report:c.report()}}finally{d(),l()}}async provenance(e,t){let r=this.trackProvenance;if(r===null)return{};let n,a=new Promise(o=>{n=setTimeout(()=>o(null),nt)}),s=await Promise.race([r,a]);return clearTimeout(n),s===null?{}:{provenance:_e(s,e,t)}}isLandscape(){let e=this.options.video;return this.uprightGuard&&e.videoWidth>e.videoHeight}holdUpright(e){this.gate?.reset(),this.emit("checks",{engine:"v3",progress:0,q:0,factors:{presence:0,single:1,centering:0,size:0,pose:0,sharpness:0,exposure:0,motion:0},attempt:e}),this.lastGuidanceKey!==K&&(this.lastGuidanceKey=K,this.emit("guidance",{key:K}))}watchRotation(e,t){if(!this.uprightGuard)return()=>{};let r=this.options.video,n=()=>{if(e!==this.attempt||t!==null&&this.stateValue!=="recording"){o();return}r.videoWidth>0&&this.isLandscape()&&(o(),this.abortRecording(e,t))},a=setInterval(n,tt);r.addEventListener?.("resize",n);let s=!1;function o(){s||(s=!0,clearInterval(a),r.removeEventListener?.("resize",n))}return o}abortRecording(e,t){if(e!==this.attempt)return;this.attempt+=1;let r=this.attempt;try{t?.stop()}catch{}this.ramp?.stop(),this.ramp=null,this.fired=!1,this.captureCompleteAt=null,this.gate=new k(this.options.thresholds??{}),this.blockStats=new w,this.lastGateSnapshotAt=this.now(),this.lastGuidanceKey=null,this.setState("positioning"),this.positioningStartedAt=this.now(),this.holdUpright(r),this.startScheduler(r)}async collectKeyframes(e){let t=this.options.captureKeyframe??(a=>this.defaultKeyframe(a)),r=rt/(B-1),n=null;for(let a=0;a<B;a+=1){if(e!==this.attempt)return n;try{let s=await t(this.options.video);(n===null||s.sharpness>n.sharpness)&&(n=s)}catch{}a<B-1&&await st(r)}return n}finishCapture(e){this.stopTracks(),this.setState("captured");let t=this.captureTiming();this.emit("artifacts",t===void 0?e:{...e,timing:t})}captureTiming(){let e={},t=(r,n,a)=>{n!==null&&a!==null&&(e[r]=Math.max(0,Math.round(a-n)))};return t("cameraReadyMs",this.cameraRequestedAt,this.cameraReadyAt),t("faceAcquireMs",this.cameraReadyAt,this.faceAcquiredAt),t("captureMs",this.faceAcquiredAt,this.captureCompleteAt),Object.keys(e).length>0?e:void 0}async defaultKeyframe(e){let t=document.createElement("canvas"),r=await(this.facing==="user"?Se:it)(e,t),n=t.toDataURL("image/jpeg",.92);return{blob:r,previewDataUrl:n,sharpness:this.centerSharpness(e)}}defaultSnapshot(e,t){try{let r=this.snapshotCanvas??document.createElement("canvas"),n=t/Math.max(1,e.videoWidth),a=Math.max(1,Math.round(e.videoWidth*n)),s=Math.max(1,Math.round(e.videoHeight*n)),o=r.getContext("2d");return o===null?e:(r.width!==a&&(r.width=a),r.height!==s&&(r.height=s),o.drawImage(e,0,0,a,s),this.snapshotCanvas=r,r)}catch{return e}}defaultQuality(e,t){let r=we(e,t,96);return r===null?Re:{sharpness:L(r),exposure:pe(r),meanLuma:de(r)}}centerSharpness(e){let t=ae(e),r=we(e,{x:t.width*.25,y:t.height*.25,width:t.width*.5,height:t.height*.5},96);return r===null?0:L(r)}teardownAttempt(){this.scheduler?.stop(),this.scheduler=null,this.reportGate(!0),this.gate=null,this.ramp?.stop(),this.ramp=null,this.stopTracks()}reportGate(e){let t=this.blockStats,r=this.profiler;if(t===null||r===null)return;let n=t.summary();e&&(this.blockStats=null),n.ticks!==0&&this.options.telemetry?.({type:"gate",final:e,activeClass:r.deviceClass,cadenceHz:r.profile.cadenceHz,...n})}stopTracks(){if(this.stream!==null){for(let e of this.stream.getTracks())e.stop();this.stream=null}}fail(e,t,r){this.scheduler?.stop(),this.reportGate(!0),this.stopTracks(),this.setState("error"),this.options.telemetry?.({type:"error",kind:e,fallbackReason:r});let{phase:n,name:a}=t;this.emit("error",{kind:e,retryable:e!=="insecure"&&e!=="unsupported",detail:a===void 0?{phase:n}:{phase:n,name:a}})}setState(e){this.stateValue=e,this.emit("statechange",{state:e})}now(){return this.options.now?.()??performance.now()}},W;function st(i){return new Promise(e=>setTimeout(e,i))}function ot(i){return i instanceof Error?i.message:String(i)}function we(i,e,t){try{let r=document.createElement("canvas"),n=t/Math.max(1,e.width);r.width=Math.max(1,Math.round(e.width*n)),r.height=Math.max(1,Math.round(e.height*n));let a=r.getContext("2d");return a===null?null:(a.drawImage(i,e.x,e.y,e.width,e.height,0,0,r.width,r.height),a.getImageData(0,0,r.width,r.height))}catch{return null}}function lt(i){if(i.enumerateDevices!==void 0)return i.enumerateDevices;if(i.getUserMedia===void 0&&!(typeof navigator>"u"||typeof navigator.mediaDevices?.enumerateDevices!="function"))return()=>navigator.mediaDevices.enumerateDevices()}export{ut as a,N as b,Pe as c,xe as d,ve as e,Ge as f,Le as g,Fe as h,Ve as i,S as j,Ue as k,U as l,ge as m,I as n,Ke as o,ft as p,Se as q,O as r,ze as s,k as t,Ze as u,w as v,et as w,K as x,tt as y,B as z,rt as A,nt as B,ke as C};
|
|
1
|
+
import{a as re,b as ne}from"./chunk-SX7TUC3V.js";import{b as le,c as ce,d as ue}from"./chunk-POIQGEZM.js";import{a as Q,c as Y,e as j,g as $,h as A,k as R,m as J,n as te}from"./chunk-CPUECYAJ.js";import{b as G,c as de,d as L,e as pe}from"./chunk-FPXL63KZ.js";import{a as q,c as z,d as X,e as Z}from"./chunk-TSA6GHUG.js";import{d as ee}from"./chunk-LLX2CKZ3.js";import{e as ie,f as ae,h as x,j as se,l as oe}from"./chunk-FSSMUAKC.js";var Ie=[...Q.filter(i=>i.startsWith("video/mp4")),"video/webm;codecs=h264","video/webm;codecs=avc1","video/webm;codecs=vp8","video/webm;codecs=vp9","video/webm"],me=new Set;function De(i){let e=/(?:Chrome|Chromium)\/(\d+)\./.exec(i??"");return e?Number(e[1]):null}function he(i=Oe(),e=globalThis.navigator?.userAgent){if(i===void 0)return"";let t=De(e)===126;for(let r of Ie)if(!(me.has(r)||t&&r.startsWith("video/mp4")))try{if(i(r))return r}catch{}return""}function F(i){i!==""&&me.add(i)}function fe(i){return i.replace(/^video\/x-matroska/i,"video/webm")}function ut(i){let e=/codecs=["']?([^,;"']+)/i.exec(i);return e?e[1].trim():i.split(";")[0].trim()}function Oe(){let i=globalThis.MediaRecorder;return i&&typeof i.isTypeSupported=="function"?e=>i.isTypeSupported(e):void 0}var N=2500,Pe=1e3,xe=1500,ve=25e5,Ge=100,Le=700,Fe=20,Ve=1500,V=null;function Ne(){return V??(V=import("./clip-inspect-DLJXVKV6.js").catch(i=>{throw V=null,i})),V.catch(()=>null)}var S=class extends Error{constructor(e,t){super(t??e),this.kind=e}},Ue=100;function U(i,e){return i.stats===void 0?!1:i.stats===null?!0:i.stats.durationMs<e-Ue}function ge(i,e){return i.stats?e.stats?i.stats.durationMs>e.stats.durationMs:!0:!1}var I=class{constructor(e={}){this.recorder=null;this.stream=null;this.chunks=[];this.bytes=0;this.hardStopTimer=null;this.graceTimer=null;this.pollTimer=null;this.settled=!1;this.now=e.now??(()=>globalThis.performance?.now?.()??Date.now())}clearTimers(){this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.graceTimer&&clearTimeout(this.graceTimer),this.pollTimer&&clearInterval(this.pollTimer),this.hardStopTimer=null,this.graceTimer=null,this.pollTimer=null}record(e,t,r,n=N,a){let s=he(),o=Ne();return this.recordRaw(e,t,r,n,a,s).then(c=>He(c,o),c=>{throw c instanceof S&&(c.requestedMimeType=s),c})}recordRaw(e,t,r,n,a,s){return this.recorder&&!this.settled?Promise.reject(new S("generic","record() called while a recording is in flight \u2014 ClipRecorder handles one recording at a time")):(this.recorder=null,this.clearTimers(),this.chunks=[],this.bytes=0,this.settled=!1,this.stream=e,new Promise((o,c)=>{let l;try{l=new MediaRecorder(e,s?{mimeType:s,videoBitsPerSecond:ve}:{videoBitsPerSecond:ve})}catch{try{l=new MediaRecorder(e)}catch{c(new S("unsupported"));return}}this.recorder=l;let d=h=>{this.settled||(this.settled=!0,this.clearTimers(),h())},u=()=>d(()=>{let h=fe(l.mimeType||s||Y),b=new Blob(this.chunks,{type:h});if(b.size===0){c(new S("generic","empty clip"));return}if(A(b)){c(new S("cliptoolarge"));return}o({blob:b,mimeType:h,requestedMimeType:s})});l.ondataavailable=h=>{h.data&&h.data.size&&(this.chunks.push(h.data),this.bytes+=h.data.size,this.bytes>$&&d(()=>{try{l.state!=="inactive"&&l.stop()}catch{}c(new S("cliptoolarge"))}))},l.onstop=u,l.onerror=()=>d(()=>c(new S("generic")));let f=this.now();if(r!==void 0||a!==void 0){let h=!1;l.onstart=()=>{if(!(h||this.settled)&&(h=!0,f=this.now(),r!==void 0))try{r()}catch{}}}try{l.start(Pe)}catch{d(()=>c(new S("generic")));return}let v=()=>{if(this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=null,this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.hardStopTimer=null,this.settled||t?.(),l.state!=="inactive"){try{l.stop()}catch{u()}this.graceTimer=setTimeout(u,xe)}else u()},p=this.now();if(a===void 0){this.hardStopTimer=setTimeout(v,n);return}let m=null,y=!1;this.hardStopTimer=setTimeout(v,n+Le),this.pollTimer=setInterval(()=>{if(this.settled||y)return;let h=null;try{h=a.latest()}catch{h=null}let b=h?.presentationTimeMs;b!==void 0&&Number.isFinite(b)&&b>=f&&m===null&&(m=b);let C=m!==null&&b!==void 0&&b-m>=n,E=m===null&&this.now()-p>=n;if(!(!C&&!E)){if(y=!0,this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=null,E){v();return}this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.hardStopTimer=setTimeout(v,Ge)}},Fe)}))}stop(e){this.clearTimers();let t=this.recorder;if(t&&t.state!=="inactive")try{t.stop()}catch{}this.recorder=null,(e??this.stream)?.getTracks().forEach(n=>n.stop()),this.stream=null}};async function He(i,e){let t,r=new Promise(l=>{t=setTimeout(()=>l(null),Ve)}),n=await Promise.race([e,r]);if(clearTimeout(t),n===null)return i;let a;try{a=await n.blobBytes(i.blob)}catch{return{...i,stats:null}}let s=n.inspectClipBytes(a);if(s?.container!=="webm")return{...i,stats:s};let o=n.withWebmDuration(a,s.durationMs);if(o===null)return{...i,stats:s};let c=n.inspectClipBytes(o);return c===null||c.frames!==s.frames||c.durationMs!==s.durationMs?{...i,stats:s}:{...i,blob:new Blob([o],{type:i.blob.type}),stats:s}}var Ke=["magenta","yellow","green","blue"];var Be={magenta:"rgb(255, 72, 150)",yellow:"rgb(255, 190, 0)",green:"rgb(0, 238, 175)",blue:"rgb(25, 150, 255)",dark:"rgb(0, 0, 0)"};function ft(i){return Be[i]}var We=4,qe=4,D=i=>typeof i=="number"&&Number.isFinite(i);function be(i){if(typeof i!="object"||i===null)return!1;let e=i;if(typeof e.nonce!="string"||e.nonce.length===0||!Array.isArray(e.colours)||e.colours.length<1||e.colours.length>8||!e.colours.every(r=>Ke.includes(r))||!Array.isArray(e.onsetsMs)||e.onsetsMs.length!==e.colours.length)return!1;let t=-1;for(let r of e.onsetsMs){if(!D(r)||r<0||r<=t)return!1;t=r}return!(!D(e.holdMs)||e.holdMs<=0||!D(e.endMs)||e.endMs<=t||!D(e.clipMs)||e.clipMs<e.endMs||e.clipMs>8e3)}function ye(i,e){return be(i)?Math.max(e,Math.ceil(i.clipMs)):e}function Me(i,e){let t=e.now??(()=>performance.now()),r=be(i)?i:void 0,n=[],a=null,s=null,o=null,c=!1,l=null,d=p=>{l=p;try{e.paint(p)}catch{}},u=p=>{let m=e.frames?.()??null;return m!==null&&o!==null?m.mediaTimeMs+(p-m.presentationTimeMs)-o:p-(s??p)},f=(p,m,y=0)=>{if(c)return;let h=Math.max(0,p-u(t()));a=setTimeout(()=>{if(a=null,!c){if(y<We&&u(t())<p-qe){f(p,m,y+1);return}m()}},h)},v=p=>{if(r===void 0)return;let m=r.endMs;if(p>=r.colours.length){f(m,()=>d(null));return}let y=r.onsetsMs[p],h=p+1<r.onsetsMs.length?r.onsetsMs[p+1]:m;f(y,()=>{let b=u(t());if(b>m){l!==null&&d(null);return}let C=r.colours[p];d(C);let E=n.length===0?0:n[n.length-1].tMs;n.push({tMs:Math.max(E,Math.round(b)),colour:C});let M=y+r.holdMs;if(M<h){f(M,()=>{if(u(t())>m){l!==null&&d(null);return}d("dark"),v(p+1)});return}v(p+1)})};return{started(p){if(r===void 0||c||s!==null)return;s=p;let m=e.frames?.()??null;o=m===null?null:m.mediaTimeMs+(p-m.presentationTimeMs),v(0)},stop(){c||(c=!0,a!==null&&clearTimeout(a),a=null,l!==null&&d(null))},report(){return r===void 0?void 0:{nonce:r.nonce,rendered:[...n]}}}}function Se(i,e,t=.92){return new Promise((r,n)=>{let a=i.videoWidth,s=i.videoHeight;if(!a||!s){n(new Error("video-not-ready"));return}let o=e.getContext("2d");if(!o){n(new Error("no-2d-context"));return}e.width=a,e.height=s,o.scale(-1,1),o.drawImage(i,-a,0),e.toBlob(c=>c?r(c):n(new Error("empty-keyframe")),"image/jpeg",t)})}var O=class{constructor(e){this.timer=null;this.frameCallbackId=null;this.running=!1;this.busy=!1;this.lastRunAt=Number.NEGATIVE_INFINITY;this.degradeCount=0;this.durations=[];this.options=e,this.periodMs=1e3/e.cadenceHz}start(){if(this.running)return;this.running=!0;let e=this.options.video;if(typeof e?.requestVideoFrameCallback=="function"){let t=()=>{this.running&&(this.frameCallbackId=e.requestVideoFrameCallback?.(()=>{this.frameCallbackId=null,this.now()-this.lastRunAt>=this.periodMs&&this.tick(),t()}))};t();return}this.timer=setInterval(()=>this.tick(),this.periodMs)}stop(){this.running=!1,this.timer!==null&&(clearInterval(this.timer),this.timer=null),this.frameCallbackId!==null&&(this.options.video?.cancelVideoFrameCallback?.(this.frameCallbackId),this.frameCallbackId=null)}stats(){let e=this.durations.length===0?0:this.durations.reduce((t,r)=>t+r,0)/this.durations.length;return{degradeCount:this.degradeCount,meanDetectMs:e}}now(){return this.options.now?.()??performance.now()}tick(){if(!this.running)return;if(this.busy){this.degradeCount+=1;return}this.busy=!0,this.lastRunAt=this.now();let e=this.now();this.options.run().catch(()=>{}).finally(()=>{this.busy=!1,this.durations.push(this.now()-e),this.durations.length>20&&this.durations.shift()})}};var ze=Object.freeze({Q_GOOD:.6,RISE_PER_S:.9,FALL_PER_S:.25,CENTER_FALLOFF_IOD_MULTIPLE:1.35,BOX_EYE_OFFSET_FACTOR:.12,IOD_BOX_PROXY_FACTOR:.42,SIZE_IDEAL_MIN:.12,SIZE_IDEAL_MAX:.3,SIZE_HARD_MIN:.08,SIZE_HARD_MAX:.45,ROLL_MAX_DEG:25,MOTION_VELOCITY_IOD_PER_S:.5,MOTION_TAU_S:.4,MOTION_DEADBAND_IOD_PER_S:.1,READY_WINDOW_MS:500,GUIDE_SIZE:.6,GUIDE_CENTERING:.6,GUIDE_POSE:.6,GUIDE_EXPOSURE:.6,GUIDE_SHARPNESS:.35,GUIDE_MOTION:.5}),_=i=>Math.min(1,Math.max(0,i)),k=class{constructor(e={}){this.p=0;this.lastTickAt=null;this.lastCenter=null;this.velocityEma=0;this.qWindow=[];this.lastSizeDirection="ideal";this.t={...ze,...e}}reset(){this.p=0,this.lastTickAt=null,this.lastCenter=null,this.velocityEma=0,this.qWindow=[],this.lastSizeDirection="ideal"}tick(e){let{observation:t,quality:r,timestampMs:n}=e,a=this.lastTickAt===null?0:Math.max(0,(n-this.lastTickAt)/1e3);this.lastTickAt=n;let s={presence:0,single:1,centering:0,size:0,pose:0,sharpness:_(r.sharpness),exposure:_(r.exposure),motion:1};if(t!==null){s.presence=1,s.single=(t.extraFaces??0)>0?0:1;let d=this.geometryOf(t,e);s.centering=d.centering,s.size=d.size,s.pose=d.pose,s.motion=this.motionOf(d.center,d.iod,n)}else this.lastCenter=null,this.velocityEma=0;let o=Math.min(s.presence,s.single,s.centering,s.size,s.pose,s.sharpness,s.exposure,s.motion);this.p=_(this.p+(o>=this.t.Q_GOOD?this.t.RISE_PER_S*o:-this.t.FALL_PER_S*(1-o))*a),this.qWindow.push({at:n,q:o}),this.qWindow=this.qWindow.filter(d=>d.at>=n-this.t.READY_WINDOW_MS);let c=this.qWindow.map(d=>d.q);if(c.length>=3){let d=Math.min(...c),u=c.indexOf(d);c=c.filter((f,v)=>v!==u)}let l=this.p>=1&&c.every(d=>d>=this.t.Q_GOOD);return{at:n,q:o,p:this.p,factors:s,guidanceKey:this.guidanceOf(s,r,o),ready:l,accepted:o>=this.t.Q_GOOD}}geometryOf(e,t){let{box:r,eyes:n}=e,a={x:t.frameWidth/2,y:t.frameHeight/2},s=Math.min(t.frameWidth,t.frameHeight),o=n!==void 0?{x:(n.left.x+n.right.x)/2,y:(n.left.y+n.right.y)/2}:{x:r.x+r.width/2,y:r.y+r.height/2-this.t.BOX_EYE_OFFSET_FACTOR*r.height},c=n!==void 0?Math.hypot(n.right.x-n.left.x,n.right.y-n.left.y):this.t.IOD_BOX_PROXY_FACTOR*r.width,l=Math.hypot(o.x-a.x,o.y-a.y),d=c<=0?0:1-_(l/(this.t.CENTER_FALLOFF_IOD_MULTIPLE*c)),u=s>0?c/s:0;this.lastSizeDirection=u<this.t.SIZE_IDEAL_MIN?"far":u>this.t.SIZE_IDEAL_MAX?"close":"ideal";let f;u<this.t.SIZE_HARD_MIN||u>this.t.SIZE_HARD_MAX?f=0:u<this.t.SIZE_IDEAL_MIN?f=(u-this.t.SIZE_HARD_MIN)/(this.t.SIZE_IDEAL_MIN-this.t.SIZE_HARD_MIN):u>this.t.SIZE_IDEAL_MAX?f=(this.t.SIZE_HARD_MAX-u)/(this.t.SIZE_HARD_MAX-this.t.SIZE_IDEAL_MAX):f=1;let v=1;if(n!==void 0){let p=Math.abs(Math.atan2(n.right.y-n.left.y,n.right.x-n.left.x))*180/Math.PI;v=1-_(p/this.t.ROLL_MAX_DEG)}return{center:o,iod:c,centering:d,size:f,pose:v}}motionOf(e,t,r){let n=this.lastCenter;if(this.lastCenter={...e,at:r},n===null||t<=0)return 1;let a=(r-n.at)/1e3;if(a<=0)return 1;let s=Math.hypot(e.x-n.x,e.y-n.y)/t/a;s<=this.t.MOTION_DEADBAND_IOD_PER_S&&(s=0);let o=1-Math.exp(-a/this.t.MOTION_TAU_S);return this.velocityEma=o*s+(1-o)*this.velocityEma,1-_(this.velocityEma/this.t.MOTION_VELOCITY_IOD_PER_S)}guidanceOf(e,t,r){if(e.presence<=0)return"fcv3.no_face";if(e.single<=0)return"fcv3.one_face";if(e.size<this.t.GUIDE_SIZE)return this.sizeGuidance();if(e.centering<this.t.GUIDE_CENTERING)return"fcv3.center_face";if(e.pose<this.t.GUIDE_POSE)return"fcv3.straighten";if(e.exposure<this.t.GUIDE_EXPOSURE)return this.exposureGuidance(t);if(e.sharpness<this.t.GUIDE_SHARPNESS)return"fcv3.steady_camera";if(e.motion<this.t.GUIDE_MOTION)return"fcv3.hold_still";if(r<this.t.Q_GOOD){let n=[["size",this.sizeGuidance()],["centering","fcv3.center_face"],["pose","fcv3.straighten"],["exposure",this.exposureGuidance(t)],["sharpness","fcv3.steady_camera"],["motion","fcv3.hold_still"]],a=n[0];for(let s of n)e[s[0]]<e[a[0]]&&(a=s);return a[1]}return"fcv3.hold_still"}sizeGuidance(){return this.lastSizeDirection==="far"?"fcv3.come_closer":"fcv3.move_back"}exposureGuidance(e){let t=(G[0]+G[1])/2;return e.meanLuma<t?"fcv3.more_light":"fcv3.too_bright"}};var Xe=["single","size","centering","pose","exposure","sharpness","motion"];function Ze(i){if(i.accepted)return null;if(i.factors.presence<=0)return"no_face";let e="single";for(let t of Xe)i.factors[t]<i.factors[e]&&(e=t);return e}var w=class{constructor(){this.blocked={};this.acceptedMs=0;this.ticks=0;this.lastAt=null}record(e){let t=this.lastAt===null?0:Math.max(0,e.at-this.lastAt);this.lastAt=e.at,this.ticks+=1;let r=Ze(e);if(r===null){this.acceptedMs+=t;return}let n=this.blocked[r]??{count:0,ms:0};n.count+=1,n.ms+=t,this.blocked[r]=n}summary(){let e={};for(let[t,r]of Object.entries(this.blocked))e[t]={count:r.count,ms:Math.round(r.ms)};return{blocked:e,acceptedMs:Math.round(this.acceptedMs),ticks:this.ticks}}};var Qe=["obs","manycam","virtual","snap camera","xsplit","droidcam","iriun","camo"],Ye=[/^(front|back|rear)( [a-z ]+)? camera$/i,/^caméra (avant|arrière)\b/i,/^cámara (frontal|trasera|delantera)\b/i,/^câmera (frontal|traseira)\b/i,/^(front|rück)kamera\b/i,/^الكاميرا (الأمامية|الخلفية)/,/^camera2? ?\d+, facing (front|back|external)/i,/facetime/i,/\b(integrated|built-in|builtin) (web)?cam(era)?\b/i,/\b(hd )?web ?cam\b/i,/\([0-9a-f]{4}:[0-9a-f]{4}\)\s*$/i];function je(i){let e=(i??"").trim().toLowerCase();return e.length===0?"unknown":Qe.some(t=>e.includes(t))?"known_virtual":Ye.some(t=>t.test(e))?"platform":"unknown"}function Te(i){if(typeof i!="function")return!1;try{return/\{\s*\[native code\]\s*\}\s*$/.test(Function.prototype.toString.call(i))}catch{return!1}}function $e(i=globalThis){return Te(i.navigator?.mediaDevices?.getUserMedia)&&Te(i.MediaStreamTrack?.prototype?.getSettings)}async function Je(i,e=globalThis){let t=e.crypto?.subtle?.digest;if(typeof t=="function")try{let r=new Uint8Array(await t.call(e.crypto?.subtle,"SHA-256",new TextEncoder().encode(i)));return Array.from(r.subarray(0,8),n=>n.toString(16).padStart(2,"0")).join("")}catch{return}}async function Ce(i,e=globalThis){let t={};try{t=typeof i.getSettings=="function"?i.getSettings()??{}:{}}catch{t={}}let r={};if((t.facingMode==="user"||t.facingMode==="environment"||t.facingMode==="left"||t.facingMode==="right")&&(r.facingMode=t.facingMode),typeof t.frameRate=="number"&&Number.isFinite(t.frameRate)&&(r.frameRate=t.frameRate),typeof t.width=="number"&&Number.isFinite(t.width)&&(r.width=t.width),typeof t.height=="number"&&Number.isFinite(t.height)&&(r.height=t.height),typeof t.deviceId=="string"&&t.deviceId.length>0){let a=await Je(t.deviceId,e);a!==void 0&&(r.deviceIdHash=a)}let n;try{n=i.label}catch{n=void 0}return{trackSettings:r,capabilitiesPresent:typeof i.getCapabilities=="function",labelClass:je(n),prototypesIntact:$e(e)}}var H=i=>Math.round(i*100)/100;function Ee(i){let e=i,t=typeof e?.requestVideoFrameCallback=="function",r=null,n=null,a=0,s=0,o=0,c=0,l=0,d=0,u=()=>{!t||e?.requestVideoFrameCallback===void 0||(r=e.requestVideoFrameCallback((f,v)=>{if(r=null,!t)return;let p=v.presentationTime;if(n!==null){let m=p-n.presentationTimeMs;s+=1;let y=m-o;o+=y/s,c+=y*(m-o)}typeof v.captureTime=="number"&&Number.isFinite(v.captureTime)&&(l+=p-v.captureTime,d+=1),a+=1,n={mediaTimeMs:v.mediaTime*1e3,presentationTimeMs:p},u()}))};return u(),{latest:()=>n,stats:()=>({n:a,meanGapMs:s===0?0:H(o),stdGapMs:s<2?0:H(Math.sqrt(c/(s-1))),captureLatencyMs:d===0?null:H(l/d)}),stop:()=>{t&&(t=!1,r!==null&&e?.cancelVideoFrameCallback?.(r),r=null)}}}function _e(i,e,t){return{...i,rvfc:e,rampPainter:t}}var et=1e3,K="fcv3.hold_upright",tt=200,B=4,rt=600,nt=1e3,Re={sharpness:1,exposure:1,meanLuma:128};function it(i,e){return e.width=i.videoWidth,e.height=i.videoHeight,e.getContext("2d").drawImage(i,0,0),new Promise((t,r)=>e.toBlob(n=>n?t(n):r(new Error("empty-keyframe")),"image/jpeg",.92))}function at(){return z()==="phone"}var ke=class{constructor(e){this.handlers=new Map;this.stateValue="idle";this.attempt=0;this.stream=null;this.detector=null;this.scheduler=null;this.gate=null;this.profiler=null;this.lastGuidanceKey=null;this.positioningStartedAt=0;this.cameraRequestedAt=null;this.cameraReadyAt=null;this.faceAcquiredAt=null;this.captureCompleteAt=null;this.fired=!1;this.carriedDegrade=0;this.carriedMeans=[];this.blockStats=null;this.lastGateSnapshotAt=Number.NEGATIVE_INFINITY;this.uprightGuard=!1;this.trackProvenance=null;this.ramp=null;this.snapshotCanvas=null;this.options=e,this.facing=e.facingMode??"user"}get state(){return this.stateValue}on(e,t){let r=this.handlers.get(e);return r||(r=new Set,this.handlers.set(e,r)),r.add(t),()=>r?.delete(t)}emit(e,t){for(let r of[...this.handlers.get(e)??[]])r(t)}async start(e={}){e.facingMode!==void 0&&(this.facing=e.facingMode),this.attempt+=1,await this.run(this.attempt)}get facingMode(){return this.facing}retry(){this.teardownAttempt(),this.start()}switchCamera(){this.facing=this.facing==="user"?"environment":"user",this.teardownAttempt(),this.start()}restart(e){this.facing=e,this.teardownAttempt(),this.start()}destroy(){this.attempt+=1,this.teardownAttempt(),this.detector?.destroy(),this.detector=null,this.options.video.srcObject=null}async run(e){let{options:t}=this;this.fired=!1,this.lastGuidanceKey=null,this.carriedDegrade=0,this.carriedMeans=[],this.cameraRequestedAt=null,this.cameraReadyAt=null,this.faceAcquiredAt=null,this.captureCompleteAt=null,this.uprightGuard=(t.isPhone??at)(),this.setState("preflight");let r=j();if(r!=="OK"){this.fail(r==="INSECURE_CONTEXT"?"insecure":"unsupported",{phase:"preflight"});return}this.setState("acquiring");let n=t.getUserMedia??(l=>navigator.mediaDevices.getUserMedia(l)),a;this.cameraRequestedAt=this.now();try{let{facingMode:l,...d}=q(X(),this.facing).video;a=await ne(this.facing,d,{getUserMedia:n,enumerateDevices:lt(t)})}catch(l){if(e!==this.attempt)return;if(l instanceof re){this.fail("backcamera",{phase:"acquiring",name:R(l)});return}this.fail(J(l),{phase:"acquiring",name:R(l)});return}if(ee(a),te(a),e!==this.attempt){for(let l of a.getTracks())l.stop();return}this.stream=a;let s=a.getVideoTracks?.()[0];if(this.trackProvenance=s===void 0?null:Ce(s).catch(()=>null),this.facing=Z(a)??this.facing,t.video.srcObject=a,await t.video.play().catch(()=>{}),e!==this.attempt)return;if(this.cameraReadyAt=this.now(),this.detector===null){let l={v3AssetBaseUrl:t.v3AssetBaseUrl},d=t.createDetector??(t.createWorker!==void 0&&se()?async()=>{try{return await oe.create(t.createWorker(),l)}catch{return x(l)}}:()=>x(l)),u;try{u=await d()}catch(f){e===this.attempt&&this.fail("models",{phase:"models",name:R(f)},f instanceof ie?f.fallbackReason:ot(f));return}if(e!==this.attempt){u.destroy();return}this.detector=u,this.options.telemetry?.({type:"detector",tier:u.tier,fallbackReason:u.fallbackReason})}let o=le(),c=t.deviceClass??ce(o);this.profiler=new ue(c),this.options.telemetry?.({type:"profile",staticClass:c,activeClass:this.profiler.deviceClass,simd:o.simd}),this.gate=new k(t.thresholds??{}),this.blockStats=new w,this.lastGateSnapshotAt=this.now(),t.rankKeyframes?.()&&import("./keyframe-rank-YAJLYJYF.js").then(l=>W=l,()=>{}),this.setState("positioning"),this.positioningStartedAt=this.now(),this.startScheduler(e)}get animations(){return this.profiler?.profile.animations??"full"}startScheduler(e){let t=this.profiler;if(t===null)return;if(this.scheduler!==null){let n=this.scheduler.stats();this.carriedDegrade+=n.degradeCount,n.meanDetectMs>0&&this.carriedMeans.push(n.meanDetectMs),this.scheduler.stop()}let r=new O({cadenceHz:t.profile.cadenceHz,video:this.options.video,now:this.options.now,run:()=>this.detectTick(e)});this.scheduler=r,r.start()}async detectTick(e){let{detector:t,gate:r,profiler:n}=this,a=this.options.video;if(e!==this.attempt||t===null||r===null||n===null||this.fired||a.videoWidth===0)return;if(this.isLandscape()){this.holdUpright(e);return}let s=n.deviceClass,o=this.now(),c=this.options.makeSnapshot?.(a,n.profile.inputWidth)??this.defaultSnapshot(a,n.profile.inputWidth),l=null;try{l=await t.detect(c,a.videoWidth,a.videoHeight)}catch{l=null}if(e!==this.attempt||this.fired)return;n.record(this.now()-o),n.deviceClass!==s&&this.startScheduler(e);let d=l===null?Re:this.options.measureQuality?.(a,l.box)??this.defaultQuality(a,l.box),u=r.tick({timestampMs:this.now(),observation:l,quality:d,frameWidth:a.videoWidth,frameHeight:a.videoHeight});u.accepted&&this.faceAcquiredAt===null&&(this.faceAcquiredAt=u.at),this.blockStats?.record(u),!u.ready&&u.at-this.lastGateSnapshotAt>=et&&(this.lastGateSnapshotAt=u.at,this.reportGate(!1)),this.emit("checks",{engine:"v3",progress:u.p,q:u.q,factors:u.factors,attempt:e}),u.guidanceKey!==this.lastGuidanceKey&&(this.lastGuidanceKey=u.guidanceKey,this.emit("guidance",{key:u.guidanceKey})),u.ready&&this.stateValue==="positioning"&&(this.fired=!0,this.captureCompleteAt=u.at,this.fire(e))}async fire(e){let{options:t}=this,r=this.scheduler;r?.stop(),this.reportGate(!0);let n=r?.stats()??{degradeCount:0,meanDetectMs:0},a=[...this.carriedMeans,...n.meanDetectMs>0?[n.meanDetectMs]:[]];t.telemetry?.({type:"fired",timeToGateMs:this.now()-this.positioningStartedAt,degradeCount:this.carriedDegrade+n.degradeCount,meanDetectMs:a.length===0?0:a.reduce((M,g)=>M+g,0)/a.length});let s=t.mode??"clip",o=t.rankKeyframes?.()&&W?W.default(this,e).catch(()=>this.collectKeyframes(e)):this.collectKeyframes(e);if(s==="photo"){let M=this.watchRotation(e,null),g=await o;if(M(),e!==this.attempt)return;if(g===null){this.fail("generic",{phase:"keyframes"});return}let P=await this.provenance({n:0,meanGapMs:0,stdGapMs:0,captureLatencyMs:null},!1);if(e!==this.attempt)return;this.finishCapture({keyframe:g.blob,previewDataUrl:g.previewDataUrl,...P});return}this.setState("recording");let c=this.stream;if(c===null){this.fail("generic",{phase:"recording"});return}let l=t.screenRamp?.(),d=l!==void 0,u=null;o.then(M=>{u=M},()=>{});let f=()=>{e===this.attempt&&u!==null&&this.emit("frozen",{previewDataUrl:u.previewDataUrl})},v=ye(l,N),p=null,m,y=0;try{let M=this.recordTake(e,c,l,v,void 0).then(T=>T,T=>({failed:T})),[g,P]=await Promise.all([M,o]);if(m=P,e!==this.attempt)return;if("failed"in g){if(g.failed.kind==="cliptoolarge")throw g.failed;F(g.failed.requestedMimeType??"")}else p=g,U(g.clip,v)?g.clip.stats===null&&F(g.clip.requestedMimeType??""):f();if(p===null||U(p.clip,v)){y=1,t.telemetry?.({type:"clip_retake",reason:p===null?"error":p.clip.stats===null?"unreadable":"short"});let T=null;try{T=await this.recordTake(e,c,l,v,f)}catch(Ae){if(p===null)throw Ae}if(e!==this.attempt)return;T!==null&&(p===null||ge(T.clip,p.clip))&&(p=T),T===null&&f()}}catch(M){if(e!==this.attempt)return;let g=M.kind;this.fail(g==="cliptoolarge"?"cliptoolarge":"recorder",{phase:"recording",name:R(M)});return}if(p===null){this.fail("recorder",{phase:"recording"});return}let{clip:h,rvfc:b,report:C}=p;if(A(h.blob)){this.fail("cliptoolarge",{phase:"recording"});return}if(m===null){this.fail("generic",{phase:"keyframes"});return}let E=await this.provenance(b,d);e===this.attempt&&this.finishCapture({clip:h.blob,clipMimeType:h.mimeType,...h.stats?{clipStats:h.stats}:{},clipRetakes:y,keyframe:m.blob,previewDataUrl:m.previewDataUrl,...C!==void 0&&C.rendered.length>0?{screenRamp:C}:{},...E})}async recordTake(e,t,r,n,a){let s=this.options.createRecorder?.()??new I({now:()=>this.now()}),o=Ee(this.options.video),c=Me(r,{paint:u=>{(u===null||e===this.attempt)&&this.emit("ramp",{colour:u})},now:()=>this.now(),frames:o.latest});this.ramp=c;let l=()=>{o.stop(),c.stop(),this.ramp===c&&(this.ramp=null)},d=this.watchRotation(e,s);try{return{clip:await s.record(t,a,()=>c.started(this.now()),n,o),rvfc:o.stats(),report:c.report()}}finally{d(),l()}}async provenance(e,t){let r=this.trackProvenance;if(r===null)return{};let n,a=new Promise(o=>{n=setTimeout(()=>o(null),nt)}),s=await Promise.race([r,a]);return clearTimeout(n),s===null?{}:{provenance:_e(s,e,t)}}isLandscape(){let e=this.options.video;return this.uprightGuard&&e.videoWidth>e.videoHeight}holdUpright(e){this.gate?.reset(),this.emit("checks",{engine:"v3",progress:0,q:0,factors:{presence:0,single:1,centering:0,size:0,pose:0,sharpness:0,exposure:0,motion:0},attempt:e}),this.lastGuidanceKey!==K&&(this.lastGuidanceKey=K,this.emit("guidance",{key:K}))}watchRotation(e,t){if(!this.uprightGuard)return()=>{};let r=this.options.video,n=()=>{if(e!==this.attempt||t!==null&&this.stateValue!=="recording"){o();return}r.videoWidth>0&&this.isLandscape()&&(o(),this.abortRecording(e,t))},a=setInterval(n,tt);r.addEventListener?.("resize",n);let s=!1;function o(){s||(s=!0,clearInterval(a),r.removeEventListener?.("resize",n))}return o}abortRecording(e,t){if(e!==this.attempt)return;this.attempt+=1;let r=this.attempt;try{t?.stop()}catch{}this.ramp?.stop(),this.ramp=null,this.fired=!1,this.captureCompleteAt=null,this.gate=new k(this.options.thresholds??{}),this.blockStats=new w,this.lastGateSnapshotAt=this.now(),this.lastGuidanceKey=null,this.setState("positioning"),this.positioningStartedAt=this.now(),this.holdUpright(r),this.startScheduler(r)}async collectKeyframes(e){let t=this.options.captureKeyframe??(a=>this.defaultKeyframe(a)),r=rt/(B-1),n=null;for(let a=0;a<B;a+=1){if(e!==this.attempt)return n;try{let s=await t(this.options.video);(n===null||s.sharpness>n.sharpness)&&(n=s)}catch{}a<B-1&&await st(r)}return n}finishCapture(e){this.stopTracks(),this.setState("captured");let t=this.captureTiming();this.emit("artifacts",t===void 0?e:{...e,timing:t})}captureTiming(){let e={},t=(r,n,a)=>{n!==null&&a!==null&&(e[r]=Math.max(0,Math.round(a-n)))};return t("cameraReadyMs",this.cameraRequestedAt,this.cameraReadyAt),t("faceAcquireMs",this.cameraReadyAt,this.faceAcquiredAt),t("captureMs",this.faceAcquiredAt,this.captureCompleteAt),Object.keys(e).length>0?e:void 0}async defaultKeyframe(e){let t=document.createElement("canvas"),r=await(this.facing==="user"?Se:it)(e,t),n=t.toDataURL("image/jpeg",.92);return{blob:r,previewDataUrl:n,sharpness:this.centerSharpness(e)}}defaultSnapshot(e,t){try{let r=this.snapshotCanvas??document.createElement("canvas"),n=t/Math.max(1,e.videoWidth),a=Math.max(1,Math.round(e.videoWidth*n)),s=Math.max(1,Math.round(e.videoHeight*n)),o=r.getContext("2d");return o===null?e:(r.width!==a&&(r.width=a),r.height!==s&&(r.height=s),o.drawImage(e,0,0,a,s),this.snapshotCanvas=r,r)}catch{return e}}defaultQuality(e,t){let r=we(e,t,96);return r===null?Re:{sharpness:L(r),exposure:pe(r),meanLuma:de(r)}}centerSharpness(e){let t=ae(e),r=we(e,{x:t.width*.25,y:t.height*.25,width:t.width*.5,height:t.height*.5},96);return r===null?0:L(r)}teardownAttempt(){this.scheduler?.stop(),this.scheduler=null,this.reportGate(!0),this.gate=null,this.ramp?.stop(),this.ramp=null,this.stopTracks()}reportGate(e){let t=this.blockStats,r=this.profiler;if(t===null||r===null)return;let n=t.summary();e&&(this.blockStats=null),n.ticks!==0&&this.options.telemetry?.({type:"gate",final:e,activeClass:r.deviceClass,cadenceHz:r.profile.cadenceHz,...n})}stopTracks(){if(this.stream!==null){for(let e of this.stream.getTracks())e.stop();this.stream=null}}fail(e,t,r){this.scheduler?.stop(),this.reportGate(!0),this.stopTracks(),this.setState("error"),this.options.telemetry?.({type:"error",kind:e,fallbackReason:r});let{phase:n,name:a}=t;this.emit("error",{kind:e,retryable:e!=="insecure"&&e!=="unsupported",detail:a===void 0?{phase:n}:{phase:n,name:a}})}setState(e){this.stateValue=e,this.emit("statechange",{state:e})}now(){return this.options.now?.()??performance.now()}},W;function st(i){return new Promise(e=>setTimeout(e,i))}function ot(i){return i instanceof Error?i.message:String(i)}function we(i,e,t){try{let r=document.createElement("canvas"),n=t/Math.max(1,e.width);r.width=Math.max(1,Math.round(e.width*n)),r.height=Math.max(1,Math.round(e.height*n));let a=r.getContext("2d");return a===null?null:(a.drawImage(i,e.x,e.y,e.width,e.height,0,0,r.width,r.height),a.getImageData(0,0,r.width,r.height))}catch{return null}}function lt(i){if(i.enumerateDevices!==void 0)return i.enumerateDevices;if(i.getUserMedia===void 0&&!(typeof navigator>"u"||typeof navigator.mediaDevices?.enumerateDevices!="function"))return()=>navigator.mediaDevices.enumerateDevices()}export{ut as a,N as b,Pe as c,xe as d,ve as e,Ge as f,Le as g,Fe as h,Ve as i,S as j,Ue as k,U as l,ge as m,I as n,Ke as o,ft as p,Se as q,O as r,ze as s,k as t,Ze as u,w as v,et as w,K as x,tt as y,B as z,rt as A,nt as B,ke as C};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as f}from"./chunk-TSA6GHUG.js";import{a as h,c as y}from"./chunk-
|
|
1
|
+
import{c as f}from"./chunk-TSA6GHUG.js";import{a as h,c as y}from"./chunk-LLX2CKZ3.js";var w=["session_token_invalid","session_token_required","session_token_session_mismatch","session_not_found","rate_limit_exceeded","consent_required","session_not_active","check_not_found","check_already_finalized","check_out_of_order","check_type_unsupported","force_outcome_forbidden","attestation_invalid","platform_unregistered","app_attest_invalid","too_many_challenges","inference_unavailable","mobile_required","nni_locked","document_nni_mismatch","media_content_type_not_allowed","media_too_large","media_key_invalid","media_key_forbidden","media_not_found","media_unreadable","media_session_invalid","idempotency_key_collision","idempotency_in_progress","idempotency_key_required","validation_error","internal_error","unknown_error","upload_failed","network_error","timeout","nfc_outcome_not_accepted","identity_confirm_required","identity_confirm_locked","choice_not_found","choice_locked","choice_option_unavailable","step_not_on_path","check_not_active","sekyro_app_not_allowed","sekyro_app_unverified","id_number_locked","document_id_number_mismatch","simulated_capture_forbidden"];function D(s){return w.includes(s)}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),e.details&&(this.details=e.details)}};function _(s,e,n=Math.random){let t=(s??e)*1e3,o=Math.min(Math.max(t,500),2e4),i=Math.round(o*(1+(n()*2-1)*.25));return Math.min(Math.max(i,500),2e4)}var k=6e4,b=4,R=3e4,I=9e5,P=200,E=5,M=400,C=new Set(["server_busy","request_timeout"]),A=2;function l(s){return(s.split(";")[0]??"").trim()}var O={liveness:"clipKey",face_match:"imageKey",doc_ocr:"imageKey"},v=`@sekyro/web/${h}`,N=v,g=class{constructor(e){this.sessionId=null;this.bootstrap=null;this.captureNonces=[];this.captureFetch=null;this.reportedIssues=new Map;this.apiOrigin=e.apiOrigin.replace(/\/+$/,""),this.sessionToken=e.sessionToken;let n=e.fetch;this.fetchImpl=(t,o)=>(n??globalThis.fetch).call(globalThis,t,o),this.requestTimeoutMs=e.requestTimeoutMs??R,this.retryAttempts=e.inProgressRetry?.attempts??E,this.retryDelayMs=e.inProgressRetry?.delayMs??M,this.random=e.random??Math.random}async getSession(){let e=await this.api("GET","/hosted/session");return this.sessionId=e.sessionId,e}async recordConsent(e){return this.api("POST","/hosted/consent",{body:{locale:e},busyRetry:!0})}async reportCameraUnavailable(e){return this.api("POST","/hosted/camera-unavailable",{body:{cause:e}})}async testerGate(e){return this.api("POST","/hosted/tester-gate",{body:{input:e}})}async reportCaptureIssue(e){let n=typeof e.name=="string"?e.name.replace(/[^A-Za-z]/g,"").slice(0,40):"",t=typeof e.engineKind=="string"&&/^[a-z_]{1,32}$/.test(e.engineKind)?e.engineKind:void 0,o=typeof e.attempt=="number"&&Number.isInteger(e.attempt)&&e.attempt>=0&&e.attempt<=1e3?e.attempt:void 0,i=[e.check,o??"",e.kind,n,e.phase??""].join("|"),a=this.reportedIssues.get(i);if(a!==void 0)return a;let d={check:e.check,kind:e.kind,...n!==""?{name:n}:{},...e.phase!==void 0?{phase:e.phase}:{},...t!==void 0?{engineKind:t}:{},...o!==void 0?{attempt:o}:{},...e.formFactor!==void 0?{formFactor:e.formFactor}:{}},r=this.api("POST","/hosted/capture-issue",{body:d,empty:!0}).catch(()=>{this.reportedIssues.delete(i)});return this.reportedIssues.set(i,r),r}async choose(e,n){let t=await this.api("POST","/hosted/choice",{body:{nodeId:e,option:n},busyRetry:!0});return this.sessionId=t.sessionId,t}async confirmIdentity(e){return this.api("POST","/hosted/identity/confirm",{body:{decision:e}})}async identityPortrait(){return this.api("GET","/hosted/identity/portrait",{blob:!0})}async presign(e,n,t,o={}){let i=await this.ensureSessionId(),a={kind:e,contentType:l(n),contentLength:t,...o.source==="upload"?{source:"upload"}:{}};return this.api("POST",`/sessions/${i}/media`,{body:a})}armCapture(e=2){this.fillCaptureNonces(e)}async presignCapture(e,n,t,o={}){let i=await this.ensureSessionId(),a=await this.takeCaptureNonce(),d=a===void 0?void 0:{nonce:a,...o.engine!==void 0?{engine:o.engine.slice(0,32)}:{},...o.durationMs!==void 0&&Number.isFinite(o.durationMs)?{captureMs:Math.min(36e5,Math.max(0,Math.round(o.durationMs)))}:{}},r={kind:e,contentType:l(n),contentLength:t,capture:d};return this.api("POST",`/sessions/${i}/media`,{body:r})}async takeCaptureNonce(){let e=()=>{let n=Date.now();return this.captureNonces=this.captureNonces.filter(t=>t.expiresAt-k>n),this.captureNonces.shift()?.nonce};for(let n=0;n<2;n++){let t=e();if(t!==void 0)return t;await this.fillCaptureNonces(1)}return e()}fillCaptureNonces(e){return this.captureFetch??(this.captureFetch=(async()=>{try{let n=await this.ensureSessionId(),t=await this.api("POST",`/sessions/${n}/media/capture-nonces`,{body:{count:Math.min(b,Math.max(1,e))}}),o=Date.now()+Math.max(0,t.expiresIn)*1e3;for(let i of Array.isArray(t.nonces)?t.nonces:[])typeof i=="string"&&i.length>0&&this.captureNonces.push({nonce:i,expiresAt:o});this.captureNonces=this.captureNonces.slice(-b)}catch{}})().finally(()=>{this.captureFetch=null})),this.captureFetch}async uploadToSpaces(e,n,t){let o;try{o=await this.fetchImpl(e,{method:"PUT",headers:{"content-type":l(t)},body:n,signal:AbortSignal.timeout(I)})}catch(i){throw m(i)}if(!o.ok){let i=(await o.text().catch(()=>"")).slice(0,P);throw new c({status:o.status,code:"upload_failed",message:`media upload failed (HTTP ${o.status})${i?`: ${i}`:""}`})}}async completeMedia(e){let n=await this.ensureSessionId();return this.api("POST",`/sessions/${n}/media/complete`,{body:{key:e}})}async submitCheck(e,n,t={}){let o=await this.ensureSessionId(),i={input:n,forceOutcome:t.forceOutcome};return this.api("POST",`/sessions/${o}/checks/${e}`,{body:i,idempotencyKey:t.idempotencyKey,busyRetry:t.idempotencyKey!==void 0})}async uploadAndSubmit(e,n,t,o={}){let i=l(n.contentType),a=await this.presign(n.kind,i,n.blob.size);await this.uploadToSpaces(a.uploadUrl,n.blob,i);let d=await this.completeMedia(a.key),r={...t,[O[e]]:d.key};return this.submitCheck(e,r,o)}async ensureSessionId(){return this.sessionId!==null?this.sessionId:(this.bootstrap??(this.bootstrap=this.getSession().finally(()=>{this.bootstrap=null})),(await this.bootstrap).sessionId)}async api(e,n,t={}){let o=e==="GET"||t.busyRetry===!0,i=`${this.apiOrigin}/api/v2${n}`,a={"x-session-token":this.sessionToken,"x-sekyro-sdk":N};t.body!==void 0&&(a["content-type"]="application/json"),t.idempotencyKey!==void 0&&(a["x-idempotency-key"]=t.idempotencyKey);try{let d=y.timezone();d!==void 0&&(a["sekyro-client-timezone"]=d)}catch{}a["sekyro-client-form-factor"]=f();try{let d=await y.deviceHeader();d!==void 0&&(a["sekyro-client-device"]=d)}catch{}for(let d=0;;d++){let r;try{r=await this.fetchImpl(i,{method:e,headers:a,...t.body!==void 0?{body:JSON.stringify(t.body)}:{},cache:"no-store",signal:AbortSignal.timeout(this.requestTimeoutMs)})}catch(p){throw m(p)}if(r.ok){if(t.empty===!0)return;if(t.blob===!0)try{return await r.blob()}catch(S){throw m(S)}let p;try{p=await r.json()}catch{throw new c({status:r.status,code:"unknown_error",message:`response body was not valid JSON (HTTP ${r.status})`})}return H(p)}let u=await x(r);if(u.code==="idempotency_in_progress"&&d<this.retryAttempts){this.retryDelayMs>0&&await T(this.retryDelayMs);continue}if(o&&u.status===503&&C.has(u.code)){o=!1,await T(_(u.retryAfterSeconds,A,this.random));continue}throw u}}};function m(s){if((typeof s=="object"&&s!==null?s.name:void 0)==="TimeoutError")return new c({status:0,code:"timeout",message:"request timed out"});let n=s instanceof Error?s.message:String(s);return new c({status:0,code:"network_error",message:`network request failed: ${n}`})}function H(s){return s!==null&&typeof s=="object"&&"success"in s&&"data"in s?s.data:s}async function x(s){let e="unknown_error",n=`request failed (HTTP ${s.status})`,t=Number.NaN,o;try{let d=await s.json();if(d!==null&&typeof d=="object"){let r=d;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"&&(t=r.retryAfterSeconds),Array.isArray(r.details?.issues)&&(o=r.details)}}catch{}let i=s.headers.get("retry-after"),a=i===null?Math.floor(t):Number.parseInt(i,10);return new c({status:s.status,code:e,message:n,...Number.isFinite(a)&&a>=0?{retryAfterSeconds:a}:{},details:o})}function T(s){return new Promise(e=>setTimeout(e,s))}function L(s){let e=s?.portrait,n=e?.icao,t=e?.purpose==="id_document";return n==null?t?{policy:"reject",profile:"id_document"}:null:{policy:n.policy==="alert"?"alert":"reject",profile:t||n.profile==="id_document"?"id_document":"selfie"}}function j(s){return{...s.baselineEyeOpenness!==void 0?{baselineEyeOpenness:s.baselineEyeOpenness}:{},...s.baselineEyeOpennessLeft!==void 0&&s.baselineEyeOpennessRight!==void 0?{baselineEyeOpennessLeft:s.baselineEyeOpennessLeft,baselineEyeOpennessRight:s.baselineEyeOpennessRight}:{},criteria:s.verdict??{},...s.backgroundCheck!==void 0?{backgroundCheck:s.backgroundCheck}:{}}}export{w as a,D as b,c,_ as d,l as e,v as f,g,L as h,j as i};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{c as P,d as E,e as H}from"./chunk-7HV77AOV.js";var Y=new Set(["nni_unbound","id_number_unbound","method_required","mobile_required","portrait_required"]);function _e(e){return Y.has(e)}function ge(e,n,t){let i=n.detail;return{check:e,kind:n.kind,...i?.name!==void 0?{name:i.name}:{},...i?.phase!==void 0?{phase:i.phase}:{},...i?.engineKind!==void 0?{engineKind:i.engineKind}:{},attempt:Math.max(0,Math.min(1e3,t))}}function Ce(){let e=-1,n="";return{note(t){t==="starting"&&n!=="starting"&&(e+=1),n=t},newHandle(){n=""},noteError(){e<0&&(e=0)},get value(){return e}}}var $={document:"document_photo",nfc:"document_chip",population_registry:"national_number",national_eid:"national_eid"};function p(e){return e.plan?.steps??[]}function V(e){return Math.max(0,e.attempts.max-e.attempts.used)}function j(e){let n=e.plan?.choice;return n!==void 0&&e.plan?.current===n.nodeId?n:null}function ke(e){let n=j(e);if(n?.kind!=="identity_method")return null;let t=n.options.map(o=>$[o.service]).filter(o=>o!==void 0),i=n.options.find(o=>o.nationalEid)?.nationalEid;return i?{available:!0,selected:null,options:t,nationalEid:i}:{available:!0,selected:null,options:t}}var z=new Set(["liveness","face_match"]);function _(e){return e!==void 0&&(e.state==="pending"||e.state==="input_required")}function I(e){return e.status!=="created"&&e.status!=="in_progress"}function x(e){let n=e.plan?.current,t=n==null?void 0:p(e).find(i=>i.id===n);return _(t)?t:void 0}function h(e,n){return p(e).find(t=>t.checkType===n)}function S(e){let n=p(e),t=n.findIndex(i=>i.checkType==="liveness");return n.find((i,o)=>o>t&&i.checkType==="face_match")}function A(e,n){let t=h(n,"liveness")?.state,i=S(n)?.state;return(S(e)?.state??"pending")==="pending"&&(t==="passed"||t==="review")&&i!==void 0&&i!=="pending"&&i!=="skipped"}function M(e,n){let t=new Map(p(e).map(i=>[i.id,i.state]));return p(n).filter(i=>i.checkType==="face_match"&&(t.get(i.id)??"pending")==="pending"&&i.state!=="pending"&&i.state!=="skipped").map(i=>i.id)}var G=/^[0-9a-f]{24}$/i;function g(e){return G.test(e)?`ses_${e}`:e}function R(e,n){let t=g(e);return n===void 0?{sessionId:t,status:"unavailable"}:{sessionId:t,status:"unavailable",reasonCode:n}}function T(e,n,t){let i=g(e);return t===void 0?{sessionId:i,status:n}:{sessionId:i,status:n,reasonCode:t}}function Re(e,n){let t=g(e.sessionId);switch(e.status){case"created":case"in_progress":return Z(e,n);case"verified":return v(e,{sessionId:t,status:"verified"});case"review_pending":return v(e,T(t,"review",L(e,"review")));case"not_verified":return v(e,X(e));default:return v(e,{sessionId:t,status:"not_verified"})}}var W=new Set([0,1,2,3]);function v(e,n){return W.has(e.level)&&(n.level=e.level),typeof e.assurance=="string"&&e.assurance.length>0&&(n.assurance=e.assurance),n}function X(e){let n={sessionId:g(e.sessionId),status:"not_verified"};return e.reason!==void 0&&(n.reason=e.reason),e.reasonCode!==void 0&&(n.reasonCode=e.reasonCode),e.reasonCode==="device_cooldown"&&e.retryAfter!==void 0&&(n.retryAfter=e.retryAfter),n}function J(e){return e==="rejected"?"rejected":e==="unavailable"?"unavailable":"inconclusive"}function Q(e,n){if(n===void 0)return!1;let t=p(n).find(i=>i.id===e.id);return t!==void 0&&t.attempts.used===e.attempts.used}function Z(e,n){let t=g(e.sessionId),i=p(e).find(r=>z.has(r.checkType)&&r.state==="input_required"&&r.reason!==void 0);if(i?.reason==="mobile_required")return R(t,"mobile_required");if(i?.reason!==void 0){if(i.result==="unavailable")return R(t,i.reason);let u=n.autoRetry&&(V(i)>0||Q(i,n.previous))?{sessionId:t,status:"retry",reasonCode:i.reason,attemptsRemaining:V(i)}:{sessionId:t,status:"not_verified",reason:J(i.result),reasonCode:i.reason,attemptsRemaining:V(i)};return i.retakeHint!==void 0&&(u.retakeHint=i.retakeHint),u}let o=x(e);return o===void 0&&p(e).some(r=>r.state==="review")?T(t,"review",L(e,"review")):o?.checkType==="portrait_icao"?R(t,"portrait_required"):R(t)}function L(e,n){return p(e).find(t=>t.state===n&&t.reason!==void 0)?.reason}function F(e,n,t,i,o){return e.presignCapture!==void 0?e.presignCapture(n,t,i,o):e.presign(n,t,i)}function K(e){return{engine:e?.engine,durationMs:e?.clipMs}}var ee=["video/webm","video/mp4"],O="image/jpeg",ne=2,te=1e3,ie=1e4,oe=3,re=10,se=3,ae=new Set(["network_error","timeout","upload_failed","unknown_error","rate_limit_exceeded"]),ue=new Set(["session_not_active","check_not_found","check_already_finalized","check_out_of_order","identity_confirm_required","check_not_active","step_not_on_path"]),C=class extends Error{constructor(){super("verification destroyed"),this.name="FlowCancelledError"}};function de(e){let n=S(e);return h(e,"portrait_icao")?.state!=="pending"&&(n!==void 0?_(n):e.capture?.livePhoto?.oneCapture===!0)}var w=class extends Error{constructor(n){super(n),this.name="AttestationError"}};async function N(e,n,t={}){let i=e.uuid(),o=!1,r=!1,u=0,l=0;for(;;)try{return await n(e.client,i)}catch(s){if(s instanceof w){if(r)throw s;r=!0,t.onAttestationInvalid?.(),i=e.uuid();continue}if(!(s instanceof P))throw s;if(s.code==="consent_required"&&!o){o=!0,await e.ensureConsent({force:!0}),i=e.uuid();continue}if(s.code==="attestation_invalid"&&!r){r=!0,t.onAttestationInvalid?.(),i=e.uuid();continue}if(s.code==="inference_unavailable"&&l<oe){l+=1;let a=E(s.retryAfterSeconds,re,e.random??Math.random);e.onBusy?.({attempt:l,retryAfterSeconds:a/1e3}),await e.sleep(a),t.onAttestationInvalid?.(),i=e.uuid();continue}if(ae.has(s.code)&&u<ne){u+=1;let a=s.retryAfterSeconds!==void 0?s.retryAfterSeconds*1e3:void 0;await e.sleep(a!==void 0?Math.min(a,ie):te);continue}throw s}}var ce=new Set(["passed","review","processing","skipped"]);async function Me(e){let{artifacts:n}=e,t=n.clip,i=H(n.clipMime??"");if(n.degraded==="NO_RECORDER"||t===void 0||!ee.includes(i))return{kind:"unavailable",reason:"no_recorder"};e.client.armCapture?.(2);let o=le(e,n.keyframe),r=fe(e,t,i,o),u=pe(e,o),l=!1,s=new Set,a=!0,k=0;for(;;){if(e.isCancelled())return{kind:"cancelled"};let f=e.getView();if(I(f))return{kind:"settled"};let d=x(f),y=d?.checkType,b=y==="liveness"&&!l?"liveness":y==="face_match"&&!s.has(d?.id)&&s.size<2&&a?"face_match":null;if(b===null)return{kind:"settled"};if(b==="liveness"&&n.captureChannel==="desktop")return{kind:"unavailable",reason:"mobile_required"};try{if(b==="liveness"){l=!0;let c=await r();if(e.isCancelled())return{kind:"cancelled"};A(f,c)&&s.add(S(c)?.id);for(let D of M(f,c))s.add(D);await e.applySubmit(c,"liveness");let m=h(e.getView(),"liveness")?.state;a=m===void 0||ce.has(m)}else{s.add(d?.id);let c=await u();if(e.isCancelled())return{kind:"cancelled"};for(let m of M(f,c))s.add(m);await e.applySubmit(c,"face_match")}}catch(c){if(e.isCancelled()||c instanceof C)return{kind:"cancelled"};let m=ye(c);if(m.kind!=="resync"||k>=se)return m;k+=1,await e.refreshView()}}}function le(e,n){let t=null,i=null,o=()=>t!==null?Promise.resolve(t):(i??(i=(async()=>{let r=await F(e.client,"image",O,n.size,K(e.artifacts));return await e.client.uploadToSpaces(r.uploadUrl,n,O),t=(await e.client.completeMedia(r.key)).key,e.onKeyframePromoted?.(t),t})().finally(()=>{i=null})),i);return{ensure:o,attempt:()=>o().catch(()=>null),current:()=>t}}function fe(e,n,t,i){let o=null,r,u=null,l=0,s;return()=>N(e,async(a,k)=>{if(o===null||r===void 0){if(e.isCancelled())throw new C;r===void 0&&!de(e.getView())&&(r=null),e.onPhase("uploading");let[f,d]=await Promise.all([o!==null?Promise.resolve(o):(async()=>{let y=await F(a,"clip",t,n.size,K(e.artifacts));return await a.uploadToSpaces(y.uploadUrl,n,t),(await a.completeMedia(y.key)).key})(),r!==void 0?Promise.resolve(r===null?null:r.imageKey):i.attempt()]);o=f,r===void 0&&(r=d===null?null:{imageKey:d})}if(u===null){let f=performance.now();try{u=await e.getAttestation(),s=e.attestationError?.()}catch(d){throw new w(d instanceof Error?d.message:String(d))}l=Math.round(performance.now()-f)}return e.onPhase("checking"),a.submitCheck("liveness",{clipKey:o,attestation:u,captureChannel:e.artifacts.captureChannel,capture:{...me(e.artifacts),attestationMs:l,attestationError:s},...r!==null?{faceMatch:r}:{}},{idempotencyKey:k})},{onAttestationInvalid:()=>{u=null}})}function pe(e,n){return()=>N(e,async(t,i)=>{if(n.current()===null){if(e.isCancelled())throw new C;e.onPhase("uploading")}let o=await n.ensure();return e.onPhase("checking"),t.submitCheck("face_match",{imageKey:o},{idempotencyKey:i})})}function me(e){let n={width:e.width,height:e.height};for(let t of he)e[t]!==void 0&&(n[t]=e[t]);return n}var he=["engine","facingMode","mode","formFactor","clipMs","clipFrames","fps","clipRetakes","codec","cameraReadyMs","faceAcquireMs","captureMs","screenRamp","provenance"];function ye(e){if(e instanceof w)return{kind:"unavailable",reason:"attestation"};if(e instanceof P){if(e.code==="attestation_invalid")return{kind:"unavailable",reason:"attestation"};if(e.code==="inference_unavailable")return{kind:"unavailable",reason:"inference_unavailable"};if(e.code==="mobile_required")return{kind:"unavailable",reason:"mobile_required"};if(ue.has(e.code))return{kind:"resync"}}return{kind:"unavailable",reason:"network"}}var q=class extends Error{constructor(n,t){super(`invalid ${n} (${t})`),this.name="InvalidInputError",this.field=n,this.kind=t}},U=class extends Error{constructor(n,t){super(`invalid ${n} (${t})`),this.name="OtpInputError",this.field=n,this.kind=t}};function B(e){return e?.source==="upload"?null:e?.source==="choice"&&e.sourcePick!=="camera"?"upload_or_phone":"phone"}function Ae(e,n){if(n===void 0||!_(n)||n.requiresMobile!==!0)return null;switch(n.checkType){case"liveness":return"phone";case"face_match":{if(n.reason!==void 0)return"phone";let t=h(e,"portrait_icao");return t?.state==="passed"||t?.state==="review"?null:"phone"}case"doc_ocr":return B(e.documents);case"portrait_icao":{let t=e.portrait;return t?.pendingFix!==void 0||t?.reuse?.pending===!0?null:B(t)}default:return null}}function Se(e){let n=e?.capture,t=n?.mode;return t==="assisted"||t==="self"||t==="choice"?t:n?.cameraSwitch===!0?"assisted":"self"}function Le(e){let n=e?.capture?.pick;return Se(e)==="choice"&&(n==="self"||n==="assisted")?n:null}function Oe(e,n,t=null){return e==="choice"?n??t??"self":e}export{_e as a,ge as b,Ce as c,$ as d,p as e,V as f,j as g,ke as h,_ as i,I as j,x as k,h as l,g as m,R as n,Re as o,Ae as p,Se as q,Le as r,Oe as s,F as t,ee as u,ne as v,te as w,oe as x,re as y,w as z,N as A,Me as B,me as C,q as D,U as E};
|
|
1
|
+
import{c as P,d as H,e as A}from"./chunk-XOTKATN6.js";var Y=new Set(["nni_unbound","id_number_unbound","method_required","mobile_required","portrait_required"]);function _e(e){return Y.has(e)}function ge(e,n,t){let i=n.detail;return{check:e,kind:n.kind,...i?.name!==void 0?{name:i.name}:{},...i?.phase!==void 0?{phase:i.phase}:{},...i?.engineKind!==void 0?{engineKind:i.engineKind}:{},attempt:Math.max(0,Math.min(1e3,t))}}function Ce(){let e=-1,n="";return{note(t){t==="starting"&&n!=="starting"&&(e+=1),n=t},newHandle(){n=""},noteError(){e<0&&(e=0)},get value(){return e}}}var $={document:"document_photo",nfc:"document_chip",population_registry:"national_number",national_eid:"national_eid"};function p(e){return e.plan?.steps??[]}function V(e){return Math.max(0,e.attempts.max-e.attempts.used)}function j(e){let n=e.plan?.choice;return n!==void 0&&e.plan?.current===n.nodeId?n:null}function ke(e){let n=j(e);if(n?.kind!=="identity_method")return null;let t=n.options.map(o=>$[o.service]).filter(o=>o!==void 0),i=n.options.find(o=>o.nationalEid)?.nationalEid;return i?{available:!0,selected:null,options:t,nationalEid:i}:{available:!0,selected:null,options:t}}var z=new Set(["liveness","face_match"]);function _(e){return e!==void 0&&(e.state==="pending"||e.state==="input_required")}function I(e){return e.status!=="created"&&e.status!=="in_progress"}function x(e){let n=e.plan?.current,t=n==null?void 0:p(e).find(i=>i.id===n);return _(t)?t:void 0}function h(e,n){return p(e).find(t=>t.checkType===n)}function S(e){let n=p(e),t=n.findIndex(i=>i.checkType==="liveness");return n.find((i,o)=>o>t&&i.checkType==="face_match")}function T(e,n){let t=h(n,"liveness")?.state,i=S(n)?.state;return(S(e)?.state??"pending")==="pending"&&(t==="passed"||t==="review")&&i!==void 0&&i!=="pending"&&i!=="skipped"}function M(e,n){let t=new Map(p(e).map(i=>[i.id,i.state]));return p(n).filter(i=>i.checkType==="face_match"&&(t.get(i.id)??"pending")==="pending"&&i.state!=="pending"&&i.state!=="skipped").map(i=>i.id)}var G=/^[0-9a-f]{24}$/i;function g(e){return G.test(e)?`ses_${e}`:e}function R(e,n){let t=g(e);return n===void 0?{sessionId:t,status:"unavailable"}:{sessionId:t,status:"unavailable",reasonCode:n}}function O(e,n,t){let i=g(e);return t===void 0?{sessionId:i,status:n}:{sessionId:i,status:n,reasonCode:t}}function Re(e,n){let t=g(e.sessionId);switch(e.status){case"created":case"in_progress":return Z(e,n);case"verified":return v(e,{sessionId:t,status:"verified"});case"review_pending":return v(e,O(t,"review",L(e,"review")));case"not_verified":return v(e,X(e));default:return v(e,{sessionId:t,status:"not_verified"})}}var W=new Set([0,1,2,3]);function v(e,n){return W.has(e.level)&&(n.level=e.level),typeof e.assurance=="string"&&e.assurance.length>0&&(n.assurance=e.assurance),n}function X(e){let n={sessionId:g(e.sessionId),status:"not_verified"};return e.reason!==void 0&&(n.reason=e.reason),e.reasonCode!==void 0&&(n.reasonCode=e.reasonCode),e.reasonCode==="device_cooldown"&&e.retryAfter!==void 0&&(n.retryAfter=e.retryAfter),n}function J(e){return e==="rejected"?"rejected":e==="unavailable"?"unavailable":"inconclusive"}function Q(e,n){if(n===void 0)return!1;let t=p(n).find(i=>i.id===e.id);return t!==void 0&&t.attempts.used===e.attempts.used}function Z(e,n){let t=g(e.sessionId),i=p(e).find(r=>z.has(r.checkType)&&r.state==="input_required"&&r.reason!==void 0);if(i?.reason==="mobile_required")return R(t,"mobile_required");if(i?.reason!==void 0){if(i.result==="unavailable")return R(t,i.reason);let u=n.autoRetry&&(V(i)>0||Q(i,n.previous))?{sessionId:t,status:"retry",reasonCode:i.reason,attemptsRemaining:V(i)}:{sessionId:t,status:"not_verified",reason:J(i.result),reasonCode:i.reason,attemptsRemaining:V(i)};return i.retakeHint!==void 0&&(u.retakeHint=i.retakeHint),u}let o=x(e);return o===void 0&&p(e).some(r=>r.state==="review")?O(t,"review",L(e,"review")):o?.checkType==="portrait_icao"?R(t,"portrait_required"):R(t)}function L(e,n){return p(e).find(t=>t.state===n&&t.reason!==void 0)?.reason}function K(e,n,t,i,o){return e.presignCapture!==void 0?e.presignCapture(n,t,i,o):e.presign(n,t,i)}function N(e){return{engine:e?.engine,durationMs:e?.clipMs}}var ee=["video/webm","video/mp4"],F="image/jpeg",ne=2,te=1e3,ie=1e4,oe=3,re=10,se=3,ae=new Set(["network_error","timeout","upload_failed","unknown_error","rate_limit_exceeded"]),ue=new Set(["session_not_active","check_not_found","check_already_finalized","check_out_of_order","identity_confirm_required","check_not_active","step_not_on_path"]),C=class extends Error{constructor(){super("verification destroyed"),this.name="FlowCancelledError"}};function de(e){let n=S(e);return h(e,"portrait_icao")?.state!=="pending"&&(n!==void 0?_(n):e.capture?.livePhoto?.oneCapture===!0)}var w=class extends Error{constructor(n){super(n),this.name="AttestationError"}};async function q(e,n,t={}){let i=e.uuid(),o=!1,r=!1,u=0,l=0;for(;;)try{return await n(e.client,i)}catch(s){if(s instanceof w){if(r)throw s;r=!0,t.onAttestationInvalid?.(),i=e.uuid();continue}if(!(s instanceof P))throw s;if(s.code==="consent_required"&&!o){o=!0,await e.ensureConsent({force:!0}),i=e.uuid();continue}if(s.code==="attestation_invalid"&&!r){r=!0,t.onAttestationInvalid?.(),i=e.uuid();continue}if(s.code==="inference_unavailable"&&l<oe){l+=1;let a=H(s.retryAfterSeconds,re,e.random??Math.random);e.onBusy?.({attempt:l,retryAfterSeconds:a/1e3}),await e.sleep(a),t.onAttestationInvalid?.(),i=e.uuid();continue}if(ae.has(s.code)&&u<ne){u+=1;let a=s.retryAfterSeconds!==void 0?s.retryAfterSeconds*1e3:void 0;await e.sleep(a!==void 0?Math.min(a,ie):te);continue}throw s}}var ce=new Set(["passed","review","processing","skipped"]);async function Me(e){let{artifacts:n}=e,t=n.clip,i=A(n.clipMime??"");if(n.degraded==="NO_RECORDER"||t===void 0||!ee.includes(i))return{kind:"unavailable",reason:"no_recorder"};e.client.armCapture?.(2);let o=le(e,n.keyframe),r=fe(e,t,i,o),u=pe(e,o),l=!1,s=new Set,a=!0,k=0;for(;;){if(e.isCancelled())return{kind:"cancelled"};let f=e.getView();if(I(f))return{kind:"settled"};let d=x(f),y=d?.checkType,b=y==="liveness"&&!l?"liveness":y==="face_match"&&!s.has(d?.id)&&s.size<2&&a?"face_match":null;if(b===null)return{kind:"settled"};if(b==="liveness"&&n.captureChannel==="desktop")return{kind:"unavailable",reason:"mobile_required"};try{if(b==="liveness"){l=!0;let c=await r();if(e.isCancelled())return{kind:"cancelled"};T(f,c)&&s.add(S(c)?.id);for(let D of M(f,c))s.add(D);await e.applySubmit(c,"liveness");let m=h(e.getView(),"liveness")?.state;a=m===void 0||ce.has(m)}else{s.add(d?.id);let c=await u();if(e.isCancelled())return{kind:"cancelled"};for(let m of M(f,c))s.add(m);await e.applySubmit(c,"face_match")}}catch(c){if(e.isCancelled()||c instanceof C)return{kind:"cancelled"};let m=ye(c);if(m.kind!=="resync"||k>=se)return m;k+=1,await e.refreshView()}}}function le(e,n){let t=null,i=null,o=()=>t!==null?Promise.resolve(t):(i??(i=(async()=>{let r=await K(e.client,"image",F,n.size,N(e.artifacts));return await e.client.uploadToSpaces(r.uploadUrl,n,F),t=(await e.client.completeMedia(r.key)).key,e.onKeyframePromoted?.(t),t})().finally(()=>{i=null})),i);return{ensure:o,attempt:()=>o().catch(()=>null),current:()=>t}}function fe(e,n,t,i){let o=null,r,u=null,l=0,s;return()=>q(e,async(a,k)=>{if(o===null||r===void 0){if(e.isCancelled())throw new C;r===void 0&&!de(e.getView())&&(r=null),e.onPhase("uploading");let[f,d]=await Promise.all([o!==null?Promise.resolve(o):(async()=>{let y=await K(a,"clip",t,n.size,N(e.artifacts));return await a.uploadToSpaces(y.uploadUrl,n,t),(await a.completeMedia(y.key)).key})(),r!==void 0?Promise.resolve(r===null?null:r.imageKey):i.attempt()]);o=f,r===void 0&&(r=d===null?null:{imageKey:d})}if(u===null){let f=performance.now();try{u=await e.getAttestation(),s=e.attestationError?.()}catch(d){throw new w(d instanceof Error?d.message:String(d))}l=Math.round(performance.now()-f)}return e.onPhase("checking"),a.submitCheck("liveness",{clipKey:o,attestation:u,captureChannel:e.artifacts.captureChannel,capture:{...me(e.artifacts),attestationMs:l,attestationError:s},...r!==null?{faceMatch:r}:{}},{idempotencyKey:k})},{onAttestationInvalid:()=>{u=null}})}function pe(e,n){return()=>q(e,async(t,i)=>{if(n.current()===null){if(e.isCancelled())throw new C;e.onPhase("uploading")}let o=await n.ensure();return e.onPhase("checking"),t.submitCheck("face_match",{imageKey:o},{idempotencyKey:i})})}function me(e){let n={width:e.width,height:e.height};for(let t of he)e[t]!==void 0&&(n[t]=e[t]);return n}var he=["engine","facingMode","mode","formFactor","clipMs","clipFrames","fps","clipRetakes","codec","cameraReadyMs","faceAcquireMs","captureMs","screenRamp","provenance"];function ye(e){if(e instanceof w)return{kind:"unavailable",reason:"attestation"};if(e instanceof P){if(e.code==="attestation_invalid")return{kind:"unavailable",reason:"attestation"};if(e.code==="inference_unavailable")return{kind:"unavailable",reason:"inference_unavailable"};if(e.code==="mobile_required")return{kind:"unavailable",reason:"mobile_required"};if(ue.has(e.code))return{kind:"resync"}}return{kind:"unavailable",reason:"network"}}var B=class extends Error{constructor(n,t){super(`invalid ${n} (${t})`),this.name="InvalidInputError",this.field=n,this.kind=t}},U=class extends Error{constructor(n,t){super(`invalid ${n} (${t})`),this.name="OtpInputError",this.field=n,this.kind=t}};function E(e){return e?.source==="upload"?null:e?.source==="choice"&&e.sourcePick!=="camera"?"upload_or_phone":"phone"}function Ie(e,n){if(n===void 0||!_(n)||n.requiresMobile!==!0)return null;switch(n.checkType){case"liveness":return"phone";case"face_match":{if(n.reason!==void 0)return"phone";let t=h(e,"portrait_icao");return t?.state==="passed"||t?.state==="review"?null:"phone"}case"doc_ocr":return E(e.documents);case"poa":return E(e.proofOfAddress);case"portrait_icao":{let t=e.portrait;return t?.pendingFix!==void 0||t?.reuse?.pending===!0?null:E(t)}default:return null}}function Se(e){let n=e?.capture,t=n?.mode;return t==="assisted"||t==="self"||t==="choice"?t:n?.cameraSwitch===!0?"assisted":"self"}function Oe(e){let n=e?.capture?.pick;return Se(e)==="choice"&&(n==="self"||n==="assisted")?n:null}function Le(e,n,t=null){return e==="choice"?n??t??"self":e}export{_e as a,ge as b,Ce as c,$ as d,p as e,V as f,j as g,ke as h,_ as i,I as j,x as k,h as l,g as m,R as n,Re as o,Ie as p,Se as q,Oe as r,Le as s,K as t,ee as u,ne as v,te as w,oe as x,re as y,w as z,q as A,Me as B,me as C,B as D,U as E};
|
package/dist/client/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var g=Object.defineProperty;var W=Object.getOwnPropertyDescriptor;var j=Object.getOwnPropertyNames;var z=Object.prototype.hasOwnProperty;var b=(t,e)=>()=>(t&&(e=t(t=0)),e);var M=(t,e)=>{for(var n in e)g(t,n,{get:e[n],enumerable:!0})},X=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of j(e))!z.call(t,r)&&r!==n&&g(t,r,{get:()=>e[r],enumerable:!(i=W(e,r))||i.enumerable});return t};var J=t=>X(g({},"__esModule",{value:!0}),t);var v=b(()=>{"use strict"});function _(t,e){return new Promise(n=>{let i=setTimeout(()=>n(void 0),e),r=o=>{clearTimeout(i),n(o)};try{t().then(r,()=>r(void 0))}catch{r(void 0)}})}async function R(t){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(JSON.stringify(t)));return Array.from(new Uint8Array(e).subarray(0,8),n=>n.toString(16).padStart(2,"0")).join("")}var E=b(()=>{"use strict";v()});var H={};M(H,{computePrint:()=>me,readHints:()=>O});function A(t,e){if(typeof t!="string")return;let n=t.trim();return n.length>0&&n.length<=e?n:void 0}async function O(){let t=navigator.userAgentData;if(typeof t?.getHighEntropyValues!="function")return;let e=await _(()=>t.getHighEntropyValues(["model","platformVersion"]),oe);if(e==null)return;let n=A(e.model,ae),i=A(e.platformVersion,ce),r={...n!==void 0?{model:n}:{},...i!==void 0?{platformVersion:i}:{}};return Object.keys(r).length>0?r:void 0}async function le(){let[t,e]=await Promise.all([new x.Thumbmark({stabilize:["private","iframe"],exclude:["permissions","webrtc","speech"],logging:!1,collect_beacon:!1,timeout:ie}).get(),O()]),n=t?.thumbmark;if(typeof n!="string"||n.length<de||n.length>ue)return;let i={};for(let r of ne){let o=t.components?.[r];o==null||o.timeout==="true"||(i[r]=await R(o))}return{hash:n,c:i,...e!==void 0?{hints:e}:{}}}function pe(){return new Promise(t=>{typeof globalThis.requestIdleCallback=="function"?globalThis.requestIdleCallback(()=>t(),{timeout:se}):t()})}async function me(t){return t()||(await pe(),t())?"busy":_(le,re)}var x,ne,ie,re,oe,se,ae,ce,de,ue,N=b(()=>{"use strict";x=require("@thumbmarkjs/thumbmarkjs");E();ne=["canvas","webgl","audio","fonts","hardware","screen","system","locales","math","plugins"],ie=2e3,re=4e3,oe=1e3,se=2e3,ae=64,ce=32,de=8,ue=128});var Oe={};M(Oe,{HostedApiError:()=>u,HostedClient:()=>h,KNOWN_CODES:()=>P,SEKYRO_SDK_HEADER:()=>k,icaoPolicyOf:()=>q,isInAppBrowser:()=>y,isKnownCode:()=>L,portraitIcaoGate:()=>G,stripMimeParams:()=>p});module.exports=J(Oe);var Z=600;function I(){if(typeof window>"u"||typeof navigator>"u")return"desktop";let t=navigator.userAgentData,e=t?.mobile||/Android|i(Pad)?OS/.test(String(t?.platform)),n=String(navigator.userAgent??"");if(/iPhone|iPod/i.test(n))return"phone";if(/iPad/i.test(n))return"tablet";if(/Android/i.test(n))return/Mobile/i.test(n)?"phone":"tablet";if(/BlackBerry|IEMobile|Opera Mini/i.test(n))return"phone";if(!e){if(Number(navigator.maxTouchPoints??0)<=1)return"desktop";if(/Macintosh/.test(n))return"tablet";if(/Windows NT|CrOS/.test(n)||!ee())return"desktop"}let i=Q();return i>0&&i<Z?"phone":"tablet"}function Q(){try{let t=window.screen,e=Number(t?.width??0),n=Number(t?.height??0);return e>0&&n>0?Math.min(e,n):0}catch{return 0}}function ee(){try{return typeof window.matchMedia=="function"&&window.matchMedia("(pointer: coarse)").matches}catch{return!1}}var f="0.1.0-rc.25";var te=/FBAN|FBAV|FB_IAB|FBIOS|MessengerForiOS|Instagram|WhatsApp|musical_ly|BytedanceWebview|TikTok|Snapchat|\bLine\/|LinkedInApp|Pinterest|MicroMessenger|; wv\)/i;function y(t){let e=t??(typeof navigator>"u"?"":String(navigator.userAgent??""));return te.test(e)}var D="sekyro.did",fe=1e4,ye=()=>globalThis.process?.versions?.node,V;function F(){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 he(){try{let t=localStorage.getItem(D);if(t)return t;let e=F();return e!==void 0&&localStorage.setItem(D,e),e}catch{return V??(V=F()),V}}async function ge(){let t=globalThis.crypto?.subtle;if(!t)return"";let e=navigator,n=JSON.stringify([e.userAgent,e.platform,e.hardwareConcurrency??null,e.deviceMemory??null,e.maxTouchPoints??0,screen.width,screen.height,screen.colorDepth,globalThis.devicePixelRatio??1,Intl.DateTimeFormat().resolvedOptions().timeZone,e.languages?.join(",")??e.language]),i=await t.digest("SHA-256",new TextEncoder().encode(n));return Array.from(new Uint8Array(i),r=>r.toString(16).padStart(2,"0")).join("").slice(0,32)}function be(){try{let t=Number(navigator.maxTouchPoints);return Number.isFinite(t)&&t>=0?{touch:Math.min(64,Math.trunc(t))}:{}}catch{return{}}}function _e(t){let e=new TextEncoder().encode(t),n="";for(let i of e)n+=String.fromCharCode(i);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Te(t){let e,n,i,r,o,a,d=()=>a?.readyState==="live",s=()=>{o!==void 0||!globalThis.crypto?.subtle||ye()||d()||(o=Promise.race([Promise.resolve().then(()=>(N(),H)),new Promise(c=>setTimeout(c,fe))]).then(c=>c?.computePrint(d)).then(c=>{c==="busy"?o=void 0:r=c}).catch(()=>{}))};return{timezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone?.slice(0,64)||void 0}catch{return}},noteCameraLabel(c){c&&(e=c.slice(0,128))},noteCamera(c){n=c},noteCameraTrack(c){a=c},async deviceHeader(){try{i??(i=ge().catch(()=>""));let c=[];navigator.webdriver&&c.push("webdriver"),/HeadlessChrome/.test(navigator.userAgent)&&c.push("headless");let l=await i,m=he(),$={v:1,platform:"web",sdk:t.sdk.slice(0,64),ids:[...m?[{kind:"web_local",value:m.slice(0,128)}]:[],...l?[{kind:"web_fp",value:l}]:[]],screen:{w:screen.width,h:screen.height,dpr:globalThis.devicePixelRatio??1},...be(),...e?{cameraLabel:e}:{},...c.length?{signals:c}:{},...r?{print:{v:2,...r,...n?{camera:n}:{}}}:{},...y()?{inApp:!0}:{}},Y=_e(JSON.stringify($));return s(),Y}catch{return}},printReady(){return o??Promise.resolve()}}}var T=Symbol.for("sekyro.web.clientContext"),S=globalThis,w=S[T]??(S[T]=Te({sdk:`@sekyro/web@${f}`}));var P=["session_token_invalid","session_token_required","session_token_session_mismatch","session_not_found","rate_limit_exceeded","consent_required","session_not_active","check_not_found","check_already_finalized","check_out_of_order","check_type_unsupported","force_outcome_forbidden","attestation_invalid","platform_unregistered","app_attest_invalid","too_many_challenges","inference_unavailable","mobile_required","nni_locked","document_nni_mismatch","media_content_type_not_allowed","media_too_large","media_key_invalid","media_key_forbidden","media_not_found","media_unreadable","media_session_invalid","idempotency_key_collision","idempotency_in_progress","idempotency_key_required","validation_error","internal_error","unknown_error","upload_failed","network_error","timeout","nfc_outcome_not_accepted","identity_confirm_required","identity_confirm_locked","choice_not_found","choice_locked","choice_option_unavailable","step_not_on_path","check_not_active","sekyro_app_not_allowed","sekyro_app_unverified","id_number_locked","document_id_number_mismatch","simulated_capture_forbidden"];function L(t){return P.includes(t)}var u=class extends Error{constructor(e){super(e.message),this.name="HostedApiError",this.status=e.status,this.code=e.code,e.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=e.retryAfterSeconds),e.details&&(this.details=e.details)}};function U(t,e,n=Math.random){let i=(t??e)*1e3,r=Math.min(Math.max(i,500),2e4),o=Math.round(r*(1+(n()*2-1)*.25));return Math.min(Math.max(o,500),2e4)}var Se=6e4,K=4,we=3e4,Pe=9e5,Ce=200,ke=5,Me=400,Ie=new Set(["server_busy","request_timeout"]),ve=2;function p(t){return(t.split(";")[0]??"").trim()}var Re={liveness:"clipKey",face_match:"imageKey",doc_ocr:"imageKey"},k=`@sekyro/web/${f}`,Ee=k,h=class{constructor(e){this.sessionId=null;this.bootstrap=null;this.captureNonces=[];this.captureFetch=null;this.reportedIssues=new Map;this.apiOrigin=e.apiOrigin.replace(/\/+$/,""),this.sessionToken=e.sessionToken;let n=e.fetch;this.fetchImpl=(i,r)=>(n??globalThis.fetch).call(globalThis,i,r),this.requestTimeoutMs=e.requestTimeoutMs??we,this.retryAttempts=e.inProgressRetry?.attempts??ke,this.retryDelayMs=e.inProgressRetry?.delayMs??Me,this.random=e.random??Math.random}async getSession(){let e=await this.api("GET","/hosted/session");return this.sessionId=e.sessionId,e}async recordConsent(e){return this.api("POST","/hosted/consent",{body:{locale:e},busyRetry:!0})}async reportCameraUnavailable(e){return this.api("POST","/hosted/camera-unavailable",{body:{cause:e}})}async testerGate(e){return this.api("POST","/hosted/tester-gate",{body:{input:e}})}async reportCaptureIssue(e){let n=typeof e.name=="string"?e.name.replace(/[^A-Za-z]/g,"").slice(0,40):"",i=typeof e.engineKind=="string"&&/^[a-z_]{1,32}$/.test(e.engineKind)?e.engineKind:void 0,r=typeof e.attempt=="number"&&Number.isInteger(e.attempt)&&e.attempt>=0&&e.attempt<=1e3?e.attempt:void 0,o=[e.check,r??"",e.kind,n,e.phase??""].join("|"),a=this.reportedIssues.get(o);if(a!==void 0)return a;let d={check:e.check,kind:e.kind,...n!==""?{name:n}:{},...e.phase!==void 0?{phase:e.phase}:{},...i!==void 0?{engineKind:i}:{},...r!==void 0?{attempt:r}:{},...e.formFactor!==void 0?{formFactor:e.formFactor}:{}},s=this.api("POST","/hosted/capture-issue",{body:d,empty:!0}).catch(()=>{this.reportedIssues.delete(o)});return this.reportedIssues.set(o,s),s}async choose(e,n){let i=await this.api("POST","/hosted/choice",{body:{nodeId:e,option:n},busyRetry:!0});return this.sessionId=i.sessionId,i}async confirmIdentity(e){return this.api("POST","/hosted/identity/confirm",{body:{decision:e}})}async identityPortrait(){return this.api("GET","/hosted/identity/portrait",{blob:!0})}async presign(e,n,i,r={}){let o=await this.ensureSessionId(),a={kind:e,contentType:p(n),contentLength:i,...r.source==="upload"?{source:"upload"}:{}};return this.api("POST",`/sessions/${o}/media`,{body:a})}armCapture(e=2){this.fillCaptureNonces(e)}async presignCapture(e,n,i,r={}){let o=await this.ensureSessionId(),a=await this.takeCaptureNonce(),d=a===void 0?void 0:{nonce:a,...r.engine!==void 0?{engine:r.engine.slice(0,32)}:{},...r.durationMs!==void 0&&Number.isFinite(r.durationMs)?{captureMs:Math.min(36e5,Math.max(0,Math.round(r.durationMs)))}:{}},s={kind:e,contentType:p(n),contentLength:i,capture:d};return this.api("POST",`/sessions/${o}/media`,{body:s})}async takeCaptureNonce(){let e=()=>{let n=Date.now();return this.captureNonces=this.captureNonces.filter(i=>i.expiresAt-Se>n),this.captureNonces.shift()?.nonce};for(let n=0;n<2;n++){let i=e();if(i!==void 0)return i;await this.fillCaptureNonces(1)}return e()}fillCaptureNonces(e){return this.captureFetch??(this.captureFetch=(async()=>{try{let n=await this.ensureSessionId(),i=await this.api("POST",`/sessions/${n}/media/capture-nonces`,{body:{count:Math.min(K,Math.max(1,e))}}),r=Date.now()+Math.max(0,i.expiresIn)*1e3;for(let o of Array.isArray(i.nonces)?i.nonces:[])typeof o=="string"&&o.length>0&&this.captureNonces.push({nonce:o,expiresAt:r});this.captureNonces=this.captureNonces.slice(-K)}catch{}})().finally(()=>{this.captureFetch=null})),this.captureFetch}async uploadToSpaces(e,n,i){let r;try{r=await this.fetchImpl(e,{method:"PUT",headers:{"content-type":p(i)},body:n,signal:AbortSignal.timeout(Pe)})}catch(o){throw C(o)}if(!r.ok){let o=(await r.text().catch(()=>"")).slice(0,Ce);throw new u({status:r.status,code:"upload_failed",message:`media upload failed (HTTP ${r.status})${o?`: ${o}`:""}`})}}async completeMedia(e){let n=await this.ensureSessionId();return this.api("POST",`/sessions/${n}/media/complete`,{body:{key:e}})}async submitCheck(e,n,i={}){let r=await this.ensureSessionId(),o={input:n,forceOutcome:i.forceOutcome};return this.api("POST",`/sessions/${r}/checks/${e}`,{body:o,idempotencyKey:i.idempotencyKey,busyRetry:i.idempotencyKey!==void 0})}async uploadAndSubmit(e,n,i,r={}){let o=p(n.contentType),a=await this.presign(n.kind,o,n.blob.size);await this.uploadToSpaces(a.uploadUrl,n.blob,o);let d=await this.completeMedia(a.key),s={...i,[Re[e]]:d.key};return this.submitCheck(e,s,r)}async ensureSessionId(){return this.sessionId!==null?this.sessionId:(this.bootstrap??(this.bootstrap=this.getSession().finally(()=>{this.bootstrap=null})),(await this.bootstrap).sessionId)}async api(e,n,i={}){let r=e==="GET"||i.busyRetry===!0,o=`${this.apiOrigin}/api/v2${n}`,a={"x-session-token":this.sessionToken,"x-sekyro-sdk":Ee};i.body!==void 0&&(a["content-type"]="application/json"),i.idempotencyKey!==void 0&&(a["x-idempotency-key"]=i.idempotencyKey);try{let d=w.timezone();d!==void 0&&(a["sekyro-client-timezone"]=d)}catch{}a["sekyro-client-form-factor"]=I();try{let d=await w.deviceHeader();d!==void 0&&(a["sekyro-client-device"]=d)}catch{}for(let d=0;;d++){let s;try{s=await this.fetchImpl(o,{method:e,headers:a,...i.body!==void 0?{body:JSON.stringify(i.body)}:{},cache:"no-store",signal:AbortSignal.timeout(this.requestTimeoutMs)})}catch(l){throw C(l)}if(s.ok){if(i.empty===!0)return;if(i.blob===!0)try{return await s.blob()}catch(m){throw C(m)}let l;try{l=await s.json()}catch{throw new u({status:s.status,code:"unknown_error",message:`response body was not valid JSON (HTTP ${s.status})`})}return Ae(l)}let c=await xe(s);if(c.code==="idempotency_in_progress"&&d<this.retryAttempts){this.retryDelayMs>0&&await B(this.retryDelayMs);continue}if(r&&c.status===503&&Ie.has(c.code)){r=!1,await B(U(c.retryAfterSeconds,ve,this.random));continue}throw c}}};function C(t){if((typeof t=="object"&&t!==null?t.name:void 0)==="TimeoutError")return new u({status:0,code:"timeout",message:"request timed out"});let n=t instanceof Error?t.message:String(t);return new u({status:0,code:"network_error",message:`network request failed: ${n}`})}function Ae(t){return t!==null&&typeof t=="object"&&"success"in t&&"data"in t?t.data:t}async function xe(t){let e="unknown_error",n=`request failed (HTTP ${t.status})`,i=Number.NaN,r;try{let d=await t.json();if(d!==null&&typeof d=="object"){let s=d;typeof s.code=="string"&&s.code.length>0&&(e=s.code),typeof s.message=="string"&&s.message.length>0&&(n=s.message),typeof s.retryAfterSeconds=="number"&&(i=s.retryAfterSeconds),Array.isArray(s.details?.issues)&&(r=s.details)}}catch{}let o=t.headers.get("retry-after"),a=o===null?Math.floor(i):Number.parseInt(o,10);return new u({status:t.status,code:e,message:n,...Number.isFinite(a)&&a>=0?{retryAfterSeconds:a}:{},details:r})}function B(t){return new Promise(e=>setTimeout(e,t))}function q(t){let e=t?.portrait,n=e?.icao,i=e?.purpose==="id_document";return n==null?i?{policy:"reject",profile:"id_document"}:null:{policy:n.policy==="alert"?"alert":"reject",profile:i||n.profile==="id_document"?"id_document":"selfie"}}function G(t){return{...t.baselineEyeOpenness!==void 0?{baselineEyeOpenness:t.baselineEyeOpenness}:{},...t.baselineEyeOpennessLeft!==void 0&&t.baselineEyeOpennessRight!==void 0?{baselineEyeOpennessLeft:t.baselineEyeOpennessLeft,baselineEyeOpennessRight:t.baselineEyeOpennessRight}:{},criteria:t.verdict??{},...t.backgroundCheck!==void 0?{backgroundCheck:t.backgroundCheck}:{}}}0&&(module.exports={HostedApiError,HostedClient,KNOWN_CODES,SEKYRO_SDK_HEADER,icaoPolicyOf,isInAppBrowser,isKnownCode,portraitIcaoGate,stripMimeParams});
|
|
1
|
+
"use strict";var g=Object.defineProperty;var W=Object.getOwnPropertyDescriptor;var j=Object.getOwnPropertyNames;var z=Object.prototype.hasOwnProperty;var b=(t,e)=>()=>(t&&(e=t(t=0)),e);var I=(t,e)=>{for(var n in e)g(t,n,{get:e[n],enumerable:!0})},X=(t,e,n,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of j(e))!z.call(t,o)&&o!==n&&g(t,o,{get:()=>e[o],enumerable:!(i=W(e,o))||i.enumerable});return t};var J=t=>X(g({},"__esModule",{value:!0}),t);var v=b(()=>{"use strict"});function _(t,e){return new Promise(n=>{let i=setTimeout(()=>n(void 0),e),o=r=>{clearTimeout(i),n(r)};try{t().then(o,()=>o(void 0))}catch{o(void 0)}})}async function R(t){let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(JSON.stringify(t)));return Array.from(new Uint8Array(e).subarray(0,8),n=>n.toString(16).padStart(2,"0")).join("")}var E=b(()=>{"use strict";v()});var H={};I(H,{computePrint:()=>me,readHints:()=>O});function A(t,e){if(typeof t!="string")return;let n=t.trim();return n.length>0&&n.length<=e?n:void 0}async function O(){let t=navigator.userAgentData;if(typeof t?.getHighEntropyValues!="function")return;let e=await _(()=>t.getHighEntropyValues(["model","platformVersion"]),re);if(e==null)return;let n=A(e.model,ae),i=A(e.platformVersion,ce),o={...n!==void 0?{model:n}:{},...i!==void 0?{platformVersion:i}:{}};return Object.keys(o).length>0?o:void 0}async function le(){let[t,e]=await Promise.all([new x.Thumbmark({stabilize:["private","iframe"],exclude:["permissions","webrtc","speech"],logging:!1,collect_beacon:!1,timeout:ie}).get(),O()]),n=t?.thumbmark;if(typeof n!="string"||n.length<de||n.length>ue)return;let i={};for(let o of ne){let r=t.components?.[o];r==null||r.timeout==="true"||(i[o]=await R(r))}return{hash:n,c:i,...e!==void 0?{hints:e}:{}}}function pe(){return new Promise(t=>{typeof globalThis.requestIdleCallback=="function"?globalThis.requestIdleCallback(()=>t(),{timeout:se}):t()})}async function me(t){return t()||(await pe(),t())?"busy":_(le,oe)}var x,ne,ie,oe,re,se,ae,ce,de,ue,N=b(()=>{"use strict";x=require("@thumbmarkjs/thumbmarkjs");E();ne=["canvas","webgl","audio","fonts","hardware","screen","system","locales","math","plugins"],ie=2e3,oe=4e3,re=1e3,se=2e3,ae=64,ce=32,de=8,ue=128});var Oe={};I(Oe,{HostedApiError:()=>u,HostedClient:()=>h,KNOWN_CODES:()=>P,SEKYRO_SDK_HEADER:()=>k,icaoPolicyOf:()=>q,isInAppBrowser:()=>y,isKnownCode:()=>L,portraitIcaoGate:()=>G,stripMimeParams:()=>p});module.exports=J(Oe);var Z=600;function M(){if(typeof window>"u"||typeof navigator>"u")return"desktop";let t=navigator.userAgentData,e=t?.mobile||/Android|i(Pad)?OS/.test(String(t?.platform)),n=String(navigator.userAgent??"");if(/iPhone|iPod/i.test(n))return"phone";if(/iPad/i.test(n))return"tablet";if(/Android/i.test(n))return/Mobile/i.test(n)?"phone":"tablet";if(/BlackBerry|IEMobile|Opera Mini/i.test(n))return"phone";if(!e){if(Number(navigator.maxTouchPoints??0)<=1)return"desktop";if(/Macintosh/.test(n))return"tablet";if(/Windows NT|CrOS/.test(n)||!ee())return"desktop"}let i=Q();return i>0&&i<Z?"phone":"tablet"}function Q(){try{let t=window.screen,e=Number(t?.width??0),n=Number(t?.height??0);return e>0&&n>0?Math.min(e,n):0}catch{return 0}}function ee(){try{return typeof window.matchMedia=="function"&&window.matchMedia("(pointer: coarse)").matches}catch{return!1}}var f="0.1.0-rc.26";var te=/FBAN|FBAV|FB_IAB|FBIOS|MessengerForiOS|Instagram|WhatsApp|musical_ly|BytedanceWebview|TikTok|Snapchat|\bLine\/|LinkedInApp|Pinterest|MicroMessenger|; wv\)/i;function y(t){let e=t??(typeof navigator>"u"?"":String(navigator.userAgent??""));return te.test(e)}var D="sekyro.did",fe=1e4,ye=()=>globalThis.process?.versions?.node,V;function F(){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 he(){try{let t=localStorage.getItem(D);if(t)return t;let e=F();return e!==void 0&&localStorage.setItem(D,e),e}catch{return V??(V=F()),V}}async function ge(){let t=globalThis.crypto?.subtle;if(!t)return"";let e=navigator,n=JSON.stringify([e.userAgent,e.platform,e.hardwareConcurrency??null,e.deviceMemory??null,e.maxTouchPoints??0,screen.width,screen.height,screen.colorDepth,globalThis.devicePixelRatio??1,Intl.DateTimeFormat().resolvedOptions().timeZone,e.languages?.join(",")??e.language]),i=await t.digest("SHA-256",new TextEncoder().encode(n));return Array.from(new Uint8Array(i),o=>o.toString(16).padStart(2,"0")).join("").slice(0,32)}function be(){try{let t=Number(navigator.maxTouchPoints);return Number.isFinite(t)&&t>=0?{touch:Math.min(64,Math.trunc(t))}:{}}catch{return{}}}function _e(t){let e=new TextEncoder().encode(t),n="";for(let i of e)n+=String.fromCharCode(i);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Te(t){let e,n,i,o,r,a,d=()=>a?.readyState==="live",s=()=>{r!==void 0||!globalThis.crypto?.subtle||ye()||d()||(r=Promise.race([Promise.resolve().then(()=>(N(),H)),new Promise(c=>setTimeout(c,fe))]).then(c=>c?.computePrint(d)).then(c=>{c==="busy"?r=void 0:o=c}).catch(()=>{}))};return{timezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone?.slice(0,64)||void 0}catch{return}},noteCameraLabel(c){c&&(e=c.slice(0,128))},noteCamera(c){n=c},noteCameraTrack(c){a=c},async deviceHeader(){try{i??(i=ge().catch(()=>""));let c=[];navigator.webdriver&&c.push("webdriver"),/HeadlessChrome/.test(navigator.userAgent)&&c.push("headless");let l=await i,m=he(),$={v:1,platform:"web",sdk:t.sdk.slice(0,64),ids:[...m?[{kind:"web_local",value:m.slice(0,128)}]:[],...l?[{kind:"web_fp",value:l}]:[]],screen:{w:screen.width,h:screen.height,dpr:globalThis.devicePixelRatio??1},...be(),...e?{cameraLabel:e}:{},...c.length?{signals:c}:{},...o?{print:{v:2,...o,...n?{camera:n}:{}}}:{},...y()?{inApp:!0}:{}},Y=_e(JSON.stringify($));return s(),Y}catch{return}},printReady(){return r??Promise.resolve()}}}var T=Symbol.for("sekyro.web.clientContext"),S=globalThis,w=S[T]??(S[T]=Te({sdk:`@sekyro/web@${f}`}));var P=["session_token_invalid","session_token_required","session_token_session_mismatch","session_not_found","rate_limit_exceeded","consent_required","session_not_active","check_not_found","check_already_finalized","check_out_of_order","check_type_unsupported","force_outcome_forbidden","attestation_invalid","platform_unregistered","app_attest_invalid","too_many_challenges","inference_unavailable","mobile_required","nni_locked","document_nni_mismatch","media_content_type_not_allowed","media_too_large","media_key_invalid","media_key_forbidden","media_not_found","media_unreadable","media_session_invalid","idempotency_key_collision","idempotency_in_progress","idempotency_key_required","validation_error","internal_error","unknown_error","upload_failed","network_error","timeout","nfc_outcome_not_accepted","identity_confirm_required","identity_confirm_locked","choice_not_found","choice_locked","choice_option_unavailable","step_not_on_path","check_not_active","sekyro_app_not_allowed","sekyro_app_unverified","id_number_locked","document_id_number_mismatch","simulated_capture_forbidden"];function L(t){return P.includes(t)}var u=class extends Error{constructor(e){super(e.message),this.name="HostedApiError",this.status=e.status,this.code=e.code,e.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=e.retryAfterSeconds),e.details&&(this.details=e.details)}};function K(t,e,n=Math.random){let i=(t??e)*1e3,o=Math.min(Math.max(i,500),2e4),r=Math.round(o*(1+(n()*2-1)*.25));return Math.min(Math.max(r,500),2e4)}var Se=6e4,U=4,we=3e4,Pe=9e5,Ce=200,ke=5,Ie=400,Me=new Set(["server_busy","request_timeout"]),ve=2;function p(t){return(t.split(";")[0]??"").trim()}var Re={liveness:"clipKey",face_match:"imageKey",doc_ocr:"imageKey"},k=`@sekyro/web/${f}`,Ee=k,h=class{constructor(e){this.sessionId=null;this.bootstrap=null;this.captureNonces=[];this.captureFetch=null;this.reportedIssues=new Map;this.apiOrigin=e.apiOrigin.replace(/\/+$/,""),this.sessionToken=e.sessionToken;let n=e.fetch;this.fetchImpl=(i,o)=>(n??globalThis.fetch).call(globalThis,i,o),this.requestTimeoutMs=e.requestTimeoutMs??we,this.retryAttempts=e.inProgressRetry?.attempts??ke,this.retryDelayMs=e.inProgressRetry?.delayMs??Ie,this.random=e.random??Math.random}async getSession(){let e=await this.api("GET","/hosted/session");return this.sessionId=e.sessionId,e}async recordConsent(e){return this.api("POST","/hosted/consent",{body:{locale:e},busyRetry:!0})}async reportCameraUnavailable(e){return this.api("POST","/hosted/camera-unavailable",{body:{cause:e}})}async testerGate(e){return this.api("POST","/hosted/tester-gate",{body:{input:e}})}async reportCaptureIssue(e){let n=typeof e.name=="string"?e.name.replace(/[^A-Za-z]/g,"").slice(0,40):"",i=typeof e.engineKind=="string"&&/^[a-z_]{1,32}$/.test(e.engineKind)?e.engineKind:void 0,o=typeof e.attempt=="number"&&Number.isInteger(e.attempt)&&e.attempt>=0&&e.attempt<=1e3?e.attempt:void 0,r=[e.check,o??"",e.kind,n,e.phase??""].join("|"),a=this.reportedIssues.get(r);if(a!==void 0)return a;let d={check:e.check,kind:e.kind,...n!==""?{name:n}:{},...e.phase!==void 0?{phase:e.phase}:{},...i!==void 0?{engineKind:i}:{},...o!==void 0?{attempt:o}:{},...e.formFactor!==void 0?{formFactor:e.formFactor}:{}},s=this.api("POST","/hosted/capture-issue",{body:d,empty:!0}).catch(()=>{this.reportedIssues.delete(r)});return this.reportedIssues.set(r,s),s}async choose(e,n){let i=await this.api("POST","/hosted/choice",{body:{nodeId:e,option:n},busyRetry:!0});return this.sessionId=i.sessionId,i}async confirmIdentity(e){return this.api("POST","/hosted/identity/confirm",{body:{decision:e}})}async identityPortrait(){return this.api("GET","/hosted/identity/portrait",{blob:!0})}async presign(e,n,i,o={}){let r=await this.ensureSessionId(),a={kind:e,contentType:p(n),contentLength:i,...o.source==="upload"?{source:"upload"}:{}};return this.api("POST",`/sessions/${r}/media`,{body:a})}armCapture(e=2){this.fillCaptureNonces(e)}async presignCapture(e,n,i,o={}){let r=await this.ensureSessionId(),a=await this.takeCaptureNonce(),d=a===void 0?void 0:{nonce:a,...o.engine!==void 0?{engine:o.engine.slice(0,32)}:{},...o.durationMs!==void 0&&Number.isFinite(o.durationMs)?{captureMs:Math.min(36e5,Math.max(0,Math.round(o.durationMs)))}:{}},s={kind:e,contentType:p(n),contentLength:i,capture:d};return this.api("POST",`/sessions/${r}/media`,{body:s})}async takeCaptureNonce(){let e=()=>{let n=Date.now();return this.captureNonces=this.captureNonces.filter(i=>i.expiresAt-Se>n),this.captureNonces.shift()?.nonce};for(let n=0;n<2;n++){let i=e();if(i!==void 0)return i;await this.fillCaptureNonces(1)}return e()}fillCaptureNonces(e){return this.captureFetch??(this.captureFetch=(async()=>{try{let n=await this.ensureSessionId(),i=await this.api("POST",`/sessions/${n}/media/capture-nonces`,{body:{count:Math.min(U,Math.max(1,e))}}),o=Date.now()+Math.max(0,i.expiresIn)*1e3;for(let r of Array.isArray(i.nonces)?i.nonces:[])typeof r=="string"&&r.length>0&&this.captureNonces.push({nonce:r,expiresAt:o});this.captureNonces=this.captureNonces.slice(-U)}catch{}})().finally(()=>{this.captureFetch=null})),this.captureFetch}async uploadToSpaces(e,n,i){let o;try{o=await this.fetchImpl(e,{method:"PUT",headers:{"content-type":p(i)},body:n,signal:AbortSignal.timeout(Pe)})}catch(r){throw C(r)}if(!o.ok){let r=(await o.text().catch(()=>"")).slice(0,Ce);throw new u({status:o.status,code:"upload_failed",message:`media upload failed (HTTP ${o.status})${r?`: ${r}`:""}`})}}async completeMedia(e){let n=await this.ensureSessionId();return this.api("POST",`/sessions/${n}/media/complete`,{body:{key:e}})}async submitCheck(e,n,i={}){let o=await this.ensureSessionId(),r={input:n,forceOutcome:i.forceOutcome};return this.api("POST",`/sessions/${o}/checks/${e}`,{body:r,idempotencyKey:i.idempotencyKey,busyRetry:i.idempotencyKey!==void 0})}async uploadAndSubmit(e,n,i,o={}){let r=p(n.contentType),a=await this.presign(n.kind,r,n.blob.size);await this.uploadToSpaces(a.uploadUrl,n.blob,r);let d=await this.completeMedia(a.key),s={...i,[Re[e]]:d.key};return this.submitCheck(e,s,o)}async ensureSessionId(){return this.sessionId!==null?this.sessionId:(this.bootstrap??(this.bootstrap=this.getSession().finally(()=>{this.bootstrap=null})),(await this.bootstrap).sessionId)}async api(e,n,i={}){let o=e==="GET"||i.busyRetry===!0,r=`${this.apiOrigin}/api/v2${n}`,a={"x-session-token":this.sessionToken,"x-sekyro-sdk":Ee};i.body!==void 0&&(a["content-type"]="application/json"),i.idempotencyKey!==void 0&&(a["x-idempotency-key"]=i.idempotencyKey);try{let d=w.timezone();d!==void 0&&(a["sekyro-client-timezone"]=d)}catch{}a["sekyro-client-form-factor"]=M();try{let d=await w.deviceHeader();d!==void 0&&(a["sekyro-client-device"]=d)}catch{}for(let d=0;;d++){let s;try{s=await this.fetchImpl(r,{method:e,headers:a,...i.body!==void 0?{body:JSON.stringify(i.body)}:{},cache:"no-store",signal:AbortSignal.timeout(this.requestTimeoutMs)})}catch(l){throw C(l)}if(s.ok){if(i.empty===!0)return;if(i.blob===!0)try{return await s.blob()}catch(m){throw C(m)}let l;try{l=await s.json()}catch{throw new u({status:s.status,code:"unknown_error",message:`response body was not valid JSON (HTTP ${s.status})`})}return Ae(l)}let c=await xe(s);if(c.code==="idempotency_in_progress"&&d<this.retryAttempts){this.retryDelayMs>0&&await B(this.retryDelayMs);continue}if(o&&c.status===503&&Me.has(c.code)){o=!1,await B(K(c.retryAfterSeconds,ve,this.random));continue}throw c}}};function C(t){if((typeof t=="object"&&t!==null?t.name:void 0)==="TimeoutError")return new u({status:0,code:"timeout",message:"request timed out"});let n=t instanceof Error?t.message:String(t);return new u({status:0,code:"network_error",message:`network request failed: ${n}`})}function Ae(t){return t!==null&&typeof t=="object"&&"success"in t&&"data"in t?t.data:t}async function xe(t){let e="unknown_error",n=`request failed (HTTP ${t.status})`,i=Number.NaN,o;try{let d=await t.json();if(d!==null&&typeof d=="object"){let s=d;typeof s.code=="string"&&s.code.length>0&&(e=s.code),typeof s.message=="string"&&s.message.length>0&&(n=s.message),typeof s.retryAfterSeconds=="number"&&(i=s.retryAfterSeconds),Array.isArray(s.details?.issues)&&(o=s.details)}}catch{}let r=t.headers.get("retry-after"),a=r===null?Math.floor(i):Number.parseInt(r,10);return new u({status:t.status,code:e,message:n,...Number.isFinite(a)&&a>=0?{retryAfterSeconds:a}:{},details:o})}function B(t){return new Promise(e=>setTimeout(e,t))}function q(t){let e=t?.portrait,n=e?.icao,i=e?.purpose==="id_document";return n==null?i?{policy:"reject",profile:"id_document"}:null:{policy:n.policy==="alert"?"alert":"reject",profile:i||n.profile==="id_document"?"id_document":"selfie"}}function G(t){return{...t.baselineEyeOpenness!==void 0?{baselineEyeOpenness:t.baselineEyeOpenness}:{},...t.baselineEyeOpennessLeft!==void 0&&t.baselineEyeOpennessRight!==void 0?{baselineEyeOpennessLeft:t.baselineEyeOpennessLeft,baselineEyeOpennessRight:t.baselineEyeOpennessRight}:{},criteria:t.verdict??{},...t.backgroundCheck!==void 0?{backgroundCheck:t.backgroundCheck}:{}}}0&&(module.exports={HostedApiError,HostedClient,KNOWN_CODES,SEKYRO_SDK_HEADER,icaoPolicyOf,isInAppBrowser,isKnownCode,portraitIcaoGate,stripMimeParams});
|
package/dist/client/index.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
export { H as HostedClient, a as HostedClientOptions, M as MediaCheckType, S as SEKYRO_SDK_HEADER, b as SubmitOptions, U as UploadMedia, s as stripMimeParams } from '../icao-gate-
|
|
2
|
-
export { H as HostedApiError, a as HostedErrorDetails, b as HostedErrorIssue, K as KNOWN_CODES, c as KnownCode, i as icaoPolicyOf, d as isKnownCode, p as portraitIcaoGate } from '../icao-policy-
|
|
3
|
-
export { A as AcceptedDocumentType, a as AttestationInput, C as CaptureContext, b as CaptureMode, c as CaptureNoncesResult, d as CaptureProof, e as CheckInputByType, f as CheckReason, g as CheckState, h as CheckType, i as ClosedBy, j as CompleteMediaResult, k as ConsentLocale, l as ContactChannel, D as DecisionReason, m as DocDeviceRead, n as DocOcrInput, o as DocReason, p as DocSide, E as EidAfterPass, q as EidAuthInput, r as EidReason, s as EmailOtpInput, t as EmailOtpReason, F as FaceMatchInput, u as FaceMatchReason, H as HostedAcceptedDocuments, v as HostedCaptureTuning, w as HostedChallengeView, x as HostedConsentView, y as HostedDocumentCaptureTuning, z as HostedDocumentScanTuning, B as HostedDocumentsView, G as HostedEidView, I as HostedEmailOtpView, J as HostedFlowRef, K as HostedIcaoPolicy, L as HostedIntegrity, M as HostedLivePhotoTuning, N as HostedNativeCaptureTuning, O as HostedOcrTuning, P as HostedOtpView, Q as HostedPlanView, R as
|
|
1
|
+
export { H as HostedClient, a as HostedClientOptions, M as MediaCheckType, S as SEKYRO_SDK_HEADER, b as SubmitOptions, U as UploadMedia, s as stripMimeParams } from '../icao-gate-pD2dUV3P.cjs';
|
|
2
|
+
export { H as HostedApiError, a as HostedErrorDetails, b as HostedErrorIssue, K as KNOWN_CODES, c as KnownCode, i as icaoPolicyOf, d as isKnownCode, p as portraitIcaoGate } from '../icao-policy-CdR6PFHS.cjs';
|
|
3
|
+
export { A as AcceptedDocumentType, a as AttestationInput, C as CaptureContext, b as CaptureMode, c as CaptureNoncesResult, d as CaptureProof, e as CheckInputByType, f as CheckReason, g as CheckState, h as CheckType, i as ClosedBy, j as CompleteMediaResult, k as ConsentLocale, l as ContactChannel, D as DecisionReason, m as DocDeviceRead, n as DocOcrInput, o as DocReason, p as DocSide, E as EidAfterPass, q as EidAuthInput, r as EidReason, s as EmailOtpInput, t as EmailOtpReason, F as FaceMatchInput, u as FaceMatchReason, H as HostedAcceptedDocuments, v as HostedCaptureTuning, w as HostedChallengeView, x as HostedConsentView, y as HostedDocumentCaptureTuning, z as HostedDocumentScanTuning, B as HostedDocumentsView, G as HostedEidView, I as HostedEmailOtpView, J as HostedFlowRef, K as HostedIcaoPolicy, L as HostedIntegrity, M as HostedLivePhotoTuning, N as HostedNativeCaptureTuning, O as HostedOcrTuning, P as HostedOtpView, Q as HostedPlanView, R as HostedPoaRuleKindView, S as HostedPoaRuleView, T as HostedPortraitPendingFix, U as HostedPortraitView, V as HostedProofOfAddressView, W as HostedSessionView, X as HostedSimulationView, Y as HostedStepView, Z as HostedTesterGateView, _ as HostedVoiceLocale, $ as HostedVoiceView, a0 as IcaoCriterion, a1 as IcaoReportEntry, a2 as IdentityConfirmDecision, a3 as IdentityMethod, a4 as IdentitySummarySource, a5 as IdentitySummaryView, a6 as LivenessCaptureInput, a7 as LivenessInput, a8 as LivenessReason, a9 as MatchReason, aa as MediaKind, ab as MethodChoiceView, ac as NationalEidOption, ad as NfcChipReason, ae as NfcStepView, af as OtpChoiceView, ag as PhoneCountryRule, ah as PhoneFormat, ai as PhoneOtpInput, aj as PhoneOtpReason, ak as PhotoSource, al as PhotoSourcePick, am as PlanAttempts, an as PlanChoiceKind, ao as PlanChoiceOption, ap as PlanChoiceView, aq as PlanSectionView, ar as PlanStepView, as as PoaImagesInput, at as PoaInput, au as PoaKind, av as PoaLicenceInput, aw as PoaNameMatchMode, ax as PoaPdfInput, ay as PoaReason, az as PoaRuleSource, aA as PopulationInput, aB as PopulationReason, aC as PortraitFix, aD as PortraitFixReviewInput, aE as PortraitIcaoInput, aF as PortraitIcaoReason, aG as PortraitOutputFormat, aH as PresignRequest, aI as PresignUploadResult, aJ as RecordConsentResult, aK as ResolvedCaptureMode, aL as SessionDecidingStep, aM as SessionFailureReason, aN as SessionReason, aO as SessionStatus, aP as SessionStepView, aQ as SessionView, aR as SimulatedCaptureInput, aS as StepResult, aT as StepSection, aU as SubmitCheckBody, aV as TesterGateInput, aW as TesterGateResponse, aX as VerificationAssurance, aY as VerificationLevel } from '../types-DB-cZTSn.cjs';
|
|
4
4
|
|
|
5
5
|
/** The page runs inside an app's WebView (WhatsApp, Instagram, Facebook, TikTok, Snapchat, LINE, LinkedIn, WeChat, an Android WebView…). */
|
|
6
6
|
declare function isInAppBrowser(userAgent?: string): boolean;
|
package/dist/client/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
export { H as HostedClient, a as HostedClientOptions, M as MediaCheckType, S as SEKYRO_SDK_HEADER, b as SubmitOptions, U as UploadMedia, s as stripMimeParams } from '../icao-gate-
|
|
2
|
-
export { H as HostedApiError, a as HostedErrorDetails, b as HostedErrorIssue, K as KNOWN_CODES, c as KnownCode, i as icaoPolicyOf, d as isKnownCode, p as portraitIcaoGate } from '../icao-policy-
|
|
3
|
-
export { A as AcceptedDocumentType, a as AttestationInput, C as CaptureContext, b as CaptureMode, c as CaptureNoncesResult, d as CaptureProof, e as CheckInputByType, f as CheckReason, g as CheckState, h as CheckType, i as ClosedBy, j as CompleteMediaResult, k as ConsentLocale, l as ContactChannel, D as DecisionReason, m as DocDeviceRead, n as DocOcrInput, o as DocReason, p as DocSide, E as EidAfterPass, q as EidAuthInput, r as EidReason, s as EmailOtpInput, t as EmailOtpReason, F as FaceMatchInput, u as FaceMatchReason, H as HostedAcceptedDocuments, v as HostedCaptureTuning, w as HostedChallengeView, x as HostedConsentView, y as HostedDocumentCaptureTuning, z as HostedDocumentScanTuning, B as HostedDocumentsView, G as HostedEidView, I as HostedEmailOtpView, J as HostedFlowRef, K as HostedIcaoPolicy, L as HostedIntegrity, M as HostedLivePhotoTuning, N as HostedNativeCaptureTuning, O as HostedOcrTuning, P as HostedOtpView, Q as HostedPlanView, R as
|
|
1
|
+
export { H as HostedClient, a as HostedClientOptions, M as MediaCheckType, S as SEKYRO_SDK_HEADER, b as SubmitOptions, U as UploadMedia, s as stripMimeParams } from '../icao-gate-BK8TGaCk.js';
|
|
2
|
+
export { H as HostedApiError, a as HostedErrorDetails, b as HostedErrorIssue, K as KNOWN_CODES, c as KnownCode, i as icaoPolicyOf, d as isKnownCode, p as portraitIcaoGate } from '../icao-policy-qJpZOOOu.js';
|
|
3
|
+
export { A as AcceptedDocumentType, a as AttestationInput, C as CaptureContext, b as CaptureMode, c as CaptureNoncesResult, d as CaptureProof, e as CheckInputByType, f as CheckReason, g as CheckState, h as CheckType, i as ClosedBy, j as CompleteMediaResult, k as ConsentLocale, l as ContactChannel, D as DecisionReason, m as DocDeviceRead, n as DocOcrInput, o as DocReason, p as DocSide, E as EidAfterPass, q as EidAuthInput, r as EidReason, s as EmailOtpInput, t as EmailOtpReason, F as FaceMatchInput, u as FaceMatchReason, H as HostedAcceptedDocuments, v as HostedCaptureTuning, w as HostedChallengeView, x as HostedConsentView, y as HostedDocumentCaptureTuning, z as HostedDocumentScanTuning, B as HostedDocumentsView, G as HostedEidView, I as HostedEmailOtpView, J as HostedFlowRef, K as HostedIcaoPolicy, L as HostedIntegrity, M as HostedLivePhotoTuning, N as HostedNativeCaptureTuning, O as HostedOcrTuning, P as HostedOtpView, Q as HostedPlanView, R as HostedPoaRuleKindView, S as HostedPoaRuleView, T as HostedPortraitPendingFix, U as HostedPortraitView, V as HostedProofOfAddressView, W as HostedSessionView, X as HostedSimulationView, Y as HostedStepView, Z as HostedTesterGateView, _ as HostedVoiceLocale, $ as HostedVoiceView, a0 as IcaoCriterion, a1 as IcaoReportEntry, a2 as IdentityConfirmDecision, a3 as IdentityMethod, a4 as IdentitySummarySource, a5 as IdentitySummaryView, a6 as LivenessCaptureInput, a7 as LivenessInput, a8 as LivenessReason, a9 as MatchReason, aa as MediaKind, ab as MethodChoiceView, ac as NationalEidOption, ad as NfcChipReason, ae as NfcStepView, af as OtpChoiceView, ag as PhoneCountryRule, ah as PhoneFormat, ai as PhoneOtpInput, aj as PhoneOtpReason, ak as PhotoSource, al as PhotoSourcePick, am as PlanAttempts, an as PlanChoiceKind, ao as PlanChoiceOption, ap as PlanChoiceView, aq as PlanSectionView, ar as PlanStepView, as as PoaImagesInput, at as PoaInput, au as PoaKind, av as PoaLicenceInput, aw as PoaNameMatchMode, ax as PoaPdfInput, ay as PoaReason, az as PoaRuleSource, aA as PopulationInput, aB as PopulationReason, aC as PortraitFix, aD as PortraitFixReviewInput, aE as PortraitIcaoInput, aF as PortraitIcaoReason, aG as PortraitOutputFormat, aH as PresignRequest, aI as PresignUploadResult, aJ as RecordConsentResult, aK as ResolvedCaptureMode, aL as SessionDecidingStep, aM as SessionFailureReason, aN as SessionReason, aO as SessionStatus, aP as SessionStepView, aQ as SessionView, aR as SimulatedCaptureInput, aS as StepResult, aT as StepSection, aU as SubmitCheckBody, aV as TesterGateInput, aW as TesterGateResponse, aX as VerificationAssurance, aY as VerificationLevel } from '../types-DB-cZTSn.js';
|
|
4
4
|
|
|
5
5
|
/** The page runs inside an app's WebView (WhatsApp, Instagram, Facebook, TikTok, Snapchat, LINE, LinkedIn, WeChat, an Android WebView…). */
|
|
6
6
|
declare function isInAppBrowser(userAgent?: string): boolean;
|
package/dist/client/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as t,b as o,c as i,e as n,f as s,g as a,h as
|
|
1
|
+
import{a as t,b as o,c as i,e as n,f as s,g as a,h as p,i as r}from"../chunk-XOTKATN6.js";import"../chunk-TSA6GHUG.js";import{b as e}from"../chunk-LLX2CKZ3.js";export{i as HostedApiError,a as HostedClient,t as KNOWN_CODES,s as SEKYRO_SDK_HEADER,p as icaoPolicyOf,e as isInAppBrowser,o as isKnownCode,r as portraitIcaoGate,n as stripMimeParams};
|