@sekyro/web 0.1.0-rc.39 → 0.1.0-rc.40
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 +6 -0
- package/dist/{capture-session-doc-J4MIDQOS.js → capture-session-doc-DFLSX6BB.js} +1 -1
- package/dist/{capture-session-v3-DjWqEJG0.d.cts → capture-session-v3-C-9FB_vX.d.cts} +1 -1
- package/dist/{capture-session-v3-BnRN9WuV.d.ts → capture-session-v3-DEpGJ_fI.d.ts} +1 -1
- package/dist/{chunk-HMOOVRKA.js → chunk-22AW4NJD.js} +1 -1
- package/dist/{chunk-WI7GAUCH.js → chunk-4NO6MQPH.js} +1 -1
- package/dist/{chunk-P5OIQXVM.js → chunk-BPAGOPYL.js} +1 -1
- package/dist/{chunk-7FGOUBAN.js → chunk-FYU7J2DC.js} +1 -1
- package/dist/{chunk-TGSMTRG5.js → chunk-L3TNFMQK.js} +1 -1
- package/dist/{chunk-UKYJYZZS.js → chunk-M3637QGB.js} +1 -1
- package/dist/{chunk-PNOGF72U.js → chunk-QZUFICG3.js} +1 -1
- package/dist/{chunk-3565JBSZ.js → chunk-SJ5OJ677.js} +1 -1
- package/dist/chunk-Y5GRT27C.js +3 -0
- 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-SMEKDBGF.js → create-document-capture-4ZOSBL3Y.js} +1 -1
- package/dist/{create-verification-C6Hoh_0h.d.ts → create-verification-B8c9xBnz.d.ts} +6 -4
- package/dist/{create-verification-BSOb3N6w.d.cts → create-verification-BadlGBh3.d.cts} +6 -4
- package/dist/{icao-gate-C-fkVe6r.d.cts → icao-gate-BqXxEAq6.d.cts} +1 -1
- package/dist/{icao-gate-Bux2CcJc.d.ts → icao-gate-C7D7Lce7.d.ts} +1 -1
- package/dist/{icao-policy-C5XcEwqj.d.ts → icao-policy-Bo7TQyTd.d.ts} +2 -2
- package/dist/{icao-policy-B_daycJk.d.cts → icao-policy-CgSI4oFo.d.cts} +2 -2
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +7 -7
- package/dist/index.d.ts +7 -7
- package/dist/index.js +1 -1
- package/dist/internal/index.cjs +2 -2
- package/dist/internal/index.d.cts +6 -6
- package/dist/internal/index.d.ts +6 -6
- package/dist/internal/index.js +1 -1
- package/dist/{plan-runner-ZVYJ3UI3.js → plan-runner-3BLEJWHF.js} +1 -1
- package/dist/{types-BUnFqG97.d.cts → types-BAAj6TOZ.d.cts} +11 -1
- package/dist/{types-BUnFqG97.d.ts → types-BAAj6TOZ.d.ts} +11 -1
- package/package.json +1 -1
- package/sbom.cdx.json +19 -19
- package/dist/chunk-26XZRWBD.js +0 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
# @sekyro/web
|
|
2
2
|
|
|
3
|
+
## 0.1.0-rc.40
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 4f4bd85: The tester gate says why it did not recognise the person. `verification.testerGate()` resolves `missReason` when the server sends it (`retake`: the face could not be checked clearly, film again, the try does not count; `liveness`: the liveness check failed; `no_match`: no enrolled tester matched), typed `TesterGateMissReason` (also on `TesterGateResponse`). `<SekyroVerification>` shows the matching copy in the six locales and always offers to film again after a retake.
|
|
8
|
+
|
|
3
9
|
## 0.1.0-rc.39
|
|
4
10
|
|
|
5
11
|
### Patch Changes
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{A as b,B as c,C as d,D as e,E as f,F as g,G as h,H as i,I as j,J as k,z as a}from"./chunk-
|
|
1
|
+
import{A as b,B as c,C as d,D as e,E as f,F as g,G as h,H as i,I as j,J as k,z as a}from"./chunk-L3TNFMQK.js";import"./chunk-MQHTFHSN.js";import"./chunk-SMKCBUJL.js";import"./chunk-3WQJI7UL.js";import"./chunk-BRLQIJYF.js";import"./chunk-POIQGEZM.js";import"./chunk-CPUECYAJ.js";import"./chunk-FPXL63KZ.js";import"./chunk-22AW4NJD.js";import"./chunk-WNBEOK5Q.js";export{k as CAPTURE_CANDIDATE_SPACING_MS,j as CAPTURE_EXTRA_CANDIDATES,h as CaptureSessionDoc,c as DOC_BLACK_FRAME_LUMA,d as DOC_BLACK_FRAME_TICKS,e as DOC_CADENCE_HZ,b as DOC_FIRST_FRAME_MS,f as DOC_SHUTTER_DEFAULTS,i as passportBandOf,g as resolveDocShutterTuning,a as warmDocDetector};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { bu as ScreenRampReport, bl as CaptureProvenance, br as ScreenRampChallenge, bs as ScreenRampPaint } from './types-BAAj6TOZ.cjs';
|
|
2
2
|
import { F as FaceObservation, b as Detector, W as WorkerLike } from './detect-worker-CHqsPJoM.cjs';
|
|
3
3
|
|
|
4
4
|
/** MP4-first ladder: one container (H.264 MP4) covers iOS/macOS Safari + Chrome 130+.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { bu as ScreenRampReport, bl as CaptureProvenance, br as ScreenRampChallenge, bs as ScreenRampPaint } from './types-BAAj6TOZ.js';
|
|
2
2
|
import { F as FaceObservation, b as Detector, W as WorkerLike } from './detect-worker-CHqsPJoM.js';
|
|
3
3
|
|
|
4
4
|
/** MP4-first ladder: one container (H.264 MP4) covers iOS/macOS Safari + Chrome 130+.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var g="0.1.0-rc.
|
|
1
|
+
var g="0.1.0-rc.40";var T=/FBAN|FBAV|FB_IAB|FBIOS|MessengerForiOS|Instagram|WhatsApp|musical_ly|BytedanceWebview|TikTok|Snapchat|\bLine\/|LinkedInApp|Pinterest|MicroMessenger|; wv\)/i;function p(t){let e=t??(typeof navigator>"u"?"":String(navigator.userAgent??""));return T.test(e)}var h="sekyro.did",P=1e4,v=()=>globalThis.process?.versions?.node,y;function b(){let t=globalThis.crypto;try{if(typeof t?.randomUUID=="function")return t.randomUUID()}catch{}try{if(typeof t?.getRandomValues=="function"){let e=t.getRandomValues(new Uint8Array(16));return Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}}catch{}}function I(){try{let t=localStorage.getItem(h);if(t)return t;let e=b();return e!==void 0&&localStorage.setItem(h,e),e}catch{return y??(y=b()),y}}async function w(){let t=globalThis.crypto?.subtle;if(!t)return"";let e=navigator,r=JSON.stringify([e.userAgent,e.platform,e.hardwareConcurrency??null,e.deviceMemory??null,e.maxTouchPoints??0,screen.width,screen.height,screen.colorDepth,globalThis.devicePixelRatio??1,Intl.DateTimeFormat().resolvedOptions().timeZone,e.languages?.join(",")??e.language]),i=await t.digest("SHA-256",new TextEncoder().encode(r));return Array.from(new Uint8Array(i),o=>o.toString(16).padStart(2,"0")).join("").slice(0,32)}function k(){try{let t=Number(navigator.maxTouchPoints);return Number.isFinite(t)&&t>=0?{touch:Math.min(64,Math.trunc(t))}:{}}catch{return{}}}function x(t){let e=new TextEncoder().encode(t),r="";for(let i of e)r+=String.fromCharCode(i);return btoa(r).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function A(t){let e,r,i,o,a,l,u=()=>l?.readyState==="live",_=()=>{a!==void 0||!globalThis.crypto?.subtle||v()||u()||(a=Promise.race([import("./print-DCYX3CZD.js"),new Promise(n=>setTimeout(n,P))]).then(n=>n?.computePrint(u)).then(n=>{n==="busy"?a=void 0:o=n}).catch(()=>{}))};return{timezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone?.slice(0,64)||void 0}catch{return}},noteCameraLabel(n){n&&(e=n.slice(0,128))},noteCamera(n){r=n},noteCameraTrack(n){l=n},async deviceHeader(){try{i??(i=w().catch(()=>""));let n=[];navigator.webdriver&&n.push("webdriver"),/HeadlessChrome/.test(navigator.userAgent)&&n.push("headless");let m=await i,f=I(),S={v:1,platform:"web",sdk:t.sdk.slice(0,64),caps:["session_proof"],rampAtArm:!0,ids:[...f?[{kind:"web_local",value:f.slice(0,128)}]:[],...m?[{kind:"web_fp",value:m}]:[]],screen:{w:screen.width,h:screen.height,dpr:globalThis.devicePixelRatio??1},...k(),...e?{cameraLabel:e}:{},...n.length?{signals:n}:{},...o?{print:{v:2,...o,...r?{camera:r}:{}}}:{},...p()?{inApp:!0}:{}},C=x(JSON.stringify(S));return _(),C}catch{return}},printReady(){return a??Promise.resolve()}}}var s=Symbol.for("sekyro.web.clientContext"),c=globalThis,d=c[s]??(c[s]=A({sdk:`@sekyro/web@${g}`}));function M(t){try{let e=t.getVideoTracks?.()[0];if(e){if(d.noteCameraLabel(e.label),d.noteCameraTrack(e),v())return;import("./camera-trait-DELAK3YN.js").then(r=>r.noteCameraTrait(e,d)).catch(()=>{})}}catch{}}export{g as a,p as b,d as c,M as d};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{d as ae,h as _e,i as Ae,j as Be,l as Ie}from"./chunk-MQHTFHSN.js";import{a as oe,e as Te,g as Le}from"./chunk-BRLQIJYF.js";import{m as J}from"./chunk-P5OIQXVM.js";import{a as Re,g as Pe}from"./chunk-7QZWBDI5.js";import{k as re}from"./chunk-CPUECYAJ.js";import{d as Oe,g as Ee}from"./chunk-WNBEOK5Q.js";function Fe(e,t){let n=new Set(e.flatMap(o=>o.sides.filter(i=>i[t]!==null).map(i=>i.side)));return n.size===1?[...n][0]:null}function pt(e){let t=Te.find(o=>o.docType===e),n=t.mrz==="none"?null:t.mrz==="td3"?"single":"verso";return{sides:t.sides,format:Le(e),mrz:t.mrz==="none"?"none":"required",mrzSide:n,barcodeSide:null,portraitSide:t.portraitSide,scripts:null}}function ft(e){let t=[];for(let n of e)for(let o of n.sides){if(!Array.isArray(o.scripts))return null;for(let i of o.scripts)t.includes(i)||t.push(i)}return t}function We(e,t){if(t.length===0)return pt(e);let n=t.some(u=>u.sides.length>1),o=new Set(t.map(u=>u.format)),i=o.size===1?[...o][0]:"card",l=t.filter(u=>u.sides.some(m=>m.mrz!==null)).length,s=t.find(u=>u.sides.length>1===n)?.sides.find(u=>u.portrait)?.side;return{sides:n?["recto","verso"]:["single"],format:i,mrz:l===t.length?"required":l===0?"none":"optional",mrzSide:Fe(t,"mrz"),barcodeSide:Fe(t,"barcode"),portraitSide:s??(n?"recto":"single"),scripts:ft(t)}}function ze(e,t){if(e===void 0)return[];let n=e.toUpperCase();return Object.prototype.hasOwnProperty.call(oe,n)?oe[n]?.[t]??[]:[]}async function Ue(e,t,n){return await e(t)?n:n==="recto"?"verso":"recto"}function Ne(e,t,n){return e!==t&&t==="verso"&&n.recto!==void 0&&n.verso===void 0?"verso":e}var gt={low:{maxLongEdge:1920,payloadTargetBytes:7e5,qMin:.7,qMax:.92},mid:{maxLongEdge:2240,payloadTargetBytes:12e5,qMin:.7,qMax:.92},good:{maxLongEdge:2560,payloadTargetBytes:16e5,qMin:.7,qMax:.92}};function ht(e){let{deviceMemory:t,effectiveType:n,saveData:o,downlinkMbps:i,sourceLongEdge:l}=e,s=o===!0||n==="slow-2g"||n==="2g"||i!=null&&i>0&&i<1,u=t!=null&&t<=2,m=n==="4g"||i!=null&&i>=5,c=t!=null&&t>=6,b;s||u?b="low":m&&c?b="good":b="mid";let f=gt[b],L=l&&l>0?Math.min(f.maxLongEdge,l):f.maxLongEdge;return{tier:b,...f,maxLongEdge:L}}function Ge(e){let t={};try{let n=navigator;typeof n.deviceMemory=="number"&&(t.deviceMemory=n.deviceMemory);let o=n.connection;o&&(t.effectiveType=o.effectiveType,t.saveData=o.saveData,t.downlinkMbps=o.downlink)}catch{}return typeof e=="number"&&e>0&&(t.sourceLongEdge=e),ht(t)}function bt(e,t,n){let o=Math.min(1,Math.max(0,(e-.28)/.21999999999999997)),i=(t+n)/2;return Math.max(t,n-o*(n-i))}function St(e,t,n){let o=Math.max(e,t),i=o>0?Math.min(1,n/o):1;return{width:Math.max(1,Math.round(e*i)),height:Math.max(1,Math.round(t*i))}}async function yt(e,t){let n=t.startQ,o=await e(n);for(let i=0;i<4&&!(o.size<=t.budgetBytes||n<=t.qMin);i++)n=Math.max(t.qMin,n-.08),o=await e(n);return{blob:o,quality:n}}async function qe(e,t,n,o,i){if(t<=0||n<=0)return null;let{width:l,height:s}=St(t,n,o.maxLongEdge),u=document.createElement("canvas");u.width=l,u.height=s;let m=u.getContext("2d");if(!m)return null;m.drawImage(e,0,0,l,s);let c=k=>new Promise((S,v)=>{u.toBlob(p=>p?S(p):v(new Error("canvas toBlob returned null")),"image/jpeg",k)}),b=bt(i,o.qMin,o.qMax),{blob:f,quality:L}=await yt(c,{startQ:b,qMin:o.qMin,budgetBytes:o.payloadTargetBytes}).finally(()=>{u.width=0,u.height=0});if(f.size>5242880)throw new Error("encoded document exceeds the 5242880-byte media cap");return{blob:f,quality:L,width:l,height:s}}async function ie(e){let t=Ge(Math.max(e.width,e.height)),n=await qe(e,e.width,e.height,t,.5);if(n===null)throw new Error("canvas encode unavailable");return{blob:n.blob,width:n.width,height:n.height}}async function Ht(e){let t=await createImageBitmap(e);try{return await ie(t)}finally{t.close()}}var Yt=250,Vt=.6,Qt=1800,Kt=6e3,jt=2e3,He=.16;function ue(e,t){return{layout:e,phase:"framing",captured:{},pending:[],lastCaptureAt:t,lastReportAt:t,manualShutter:!1,restPhase:"framing",readSides:[],needFlip:!1,flipped:!1,flipTimeoutSpent:!1,timeoutCapture:!1,lastShotByTimeout:!1}}var Xe=e=>e==="recto"?"verso":"recto",Ye=e=>e.phase==="framing"||e.phase==="locking"||e.phase==="flipCue"||e.phase==="reaskRecto",le=e=>(e.captured.recto!==void 0?1:0)+(e.captured.verso!==void 0?1:0)+e.pending.length;function se(e,t){return e.lastCaptureAt>=0&&e.lastReportAt>=0?e:{...e,lastCaptureAt:e.lastCaptureAt<0?t:e.lastCaptureAt,lastReportAt:e.lastReportAt<0?t:e.lastReportAt}}function Mt(e,t,n){if(e.phase==="result")return{...e,lastReportAt:n};let o=!t.present||e.captureArea!==void 0&&t.areaFrac<.6*e.captureArea,{flipped:i,awaySince:l}=e;o&&(l=l??n),l!==void 0&&n-l>=250&&(i=!0),o||(l=void 0);let s=e.flipTimeoutSpent&&!(i&&!e.flipped),u=e.notice==="same_face"&&i&&!e.flipped?void 0:e.notice,m={...e,lastReportAt:n,flipped:i,awaySince:l,flipTimeoutSpent:s,notice:u,lastArea:t.areaFrac};if(!Ye(e))return m;if(e.needFlip&&!i){if(!t.ready)return{...m,phase:e.restPhase,goodSince:void 0};let c=e.lastShot!==void 0&&e.pending.includes(e.lastShot);if(s||c)return{...m,goodSince:void 0,phase:e.restPhase};let b=e.goodSince??n;return n-b>=1800?{...m,goodSince:b,phase:"capturing",flipTimeoutSpent:!0,timeoutCapture:!0}:{...m,goodSince:b,phase:e.restPhase}}return t.ready?{...m,phase:"capturing",goodSince:e.goodSince??n}:{...m,goodSince:void 0,phase:t.locking?"locking":e.restPhase}}function Dt(e,t){if(!Ye(e)||e.manualShutter)return e;let n=t-e.lastReportAt>=2e3,o=t-e.lastCaptureAt>=6e3;return n||o?{...e,manualShutter:!0}:e}function wt(e,t,n){let o=e.layout==="singlePage",i=o?{recto:t}:e.captured,l=o?[]:[...e.pending,t],s={...e,captured:i,pending:l,lastShot:t,lastCaptureAt:n,lastReportAt:-1,manualShutter:!1,goodSince:void 0,notice:void 0,awaySince:void 0,flipped:!1,lastShotByTimeout:e.timeoutCapture,timeoutCapture:!1,captureArea:e.lastArea};return o||le({captured:i,pending:l})>=2?{...s,phase:"reading",restPhase:"framing",current:void 0,needFlip:!1}:{...s,phase:"flipCue",restPhase:"flipCue",current:void 0,needFlip:!0}}function Ve(e,t,n){return e.pending.includes(t)?{...e,pending:e.pending.filter(o=>o!==t),lastShot:e.lastShot===t?void 0:e.lastShot,phase:e.phase==="capturing"?e.phase:"flipCue",restPhase:"flipCue",current:Xe(n),needFlip:!0,flipTimeoutSpent:!1,goodSince:void 0,manualShutter:!0,notice:"same_face",lastCaptureAt:-1,lastReportAt:-1}:e}function kt(e,t,n){if(!e.pending.includes(t))return e;if(e.captured[n]!==void 0)return Ve(e,t,n);let o=e.pending.filter(m=>m!==t),i={...e,pending:o,captured:{...e.captured,[n]:t}};if(le(i)!==1||e.layout==="singlePage")return i;let l=Xe(n),s=l==="recto"&&e.restPhase==="reaskRecto"?"reaskRecto":"flipCue",u=e.phase==="flipCue"||e.phase==="reaskRecto"||e.phase==="framing";return{...i,restPhase:s,current:l,phase:u?s:e.phase}}function Ct(e,t){let n=t.id??e.captured[t.side],o={...e.captured};(t.id===void 0||o[t.side]===t.id)&&delete o[t.side];let i=e.pending.filter(c=>c!==n),l=e.layout==="twoSided"&&le({captured:o,pending:i})>0,s=e.lastShotByTimeout||n===e.lastShot!==e.flipped,u=l&&!s,m=u?t.side==="recto"?"reaskRecto":"flipCue":"framing";return{...e,captured:o,pending:i,readSides:e.readSides.filter(c=>c!==t.side),lastShot:e.lastShot===n?void 0:e.lastShot,notice:t.issue,goodSince:void 0,manualShutter:!1,phase:m,restPhase:m,current:t.side,needFlip:u,flipped:!1,flipTimeoutSpent:!1,awaySince:void 0,lastCaptureAt:-1,lastReportAt:-1}}function Qe(e,t){switch(t.type){case"report":return Mt(se(e,t.at),t.report,t.at);case"tick":return Dt(se(e,t.at),t.at);case"captured":return wt(se(e,t.at),t.id,t.at);case"captureFailed":return{...e,phase:e.restPhase,goodSince:void 0,lastCaptureAt:t.at,manualShutter:!0,timeoutCapture:!1};case"classified":return kt(e,t.id,t.side);case"duplicate":return Ve(e,t.id,t.side);case"readOk":{let n=e.readSides.includes(t.side)?e.readSides:[...e.readSides,t.side],o=["recto","verso"].filter(l=>e.captured[l]!==void 0),i=e.phase==="reading"&&e.pending.length===0&&o.every(l=>n.includes(l));return{...e,readSides:n,flipTimeoutSpent:!1,phase:i?"result":e.phase}}case"readFailed":return Ct(e,t);case"clockRestart":return e.lastCaptureAt<0&&e.lastReportAt<0&&e.awaySince===void 0?e:{...e,awaySince:void 0,lastCaptureAt:-1,lastReportAt:-1};case"retake":return{...ue(e.layout,-1),lastCaptureAt:-1,lastReportAt:-1};default:return e}}function xt(e,t,n=!1){let o=e(t);return o===null?"recto":!n||o.y+o.height/2>=t.height/2?"verso":"recto"}async function vt(e,t=!1){let{detectMrzBand:n}=await import("./mrz-band-VYHOTDHY.js");return xt(n,e,t)}async function ce(e,t=480,n,o=n!=null){let i=n??{x:0,y:0,width:e.width,height:e.height},l=Math.max(1,Math.round(i.height/i.width*t)),s=document.createElement("canvas");s.width=t,s.height=l;try{let u=s.getContext("2d");return u===null?"recto":(u.drawImage(e,i.x,i.y,i.width,i.height,0,0,t,l),await vt(u.getImageData(0,0,t,l),o))}finally{s.width=0,s.height=0}}async function Jt(e,t=480){try{let n=await createImageBitmap(e),o=Math.max(1,Math.round(n.height/n.width*t)),i=document.createElement("canvas");i.width=t,i.height=o;let l=i.getContext("2d");return l===null?(n.close(),null):(l.drawImage(n,0,0,t,o),n.close(),l.getImageData(0,0,t,o))}catch{return null}}var de=(e,t,n)=>Math.min(n,Math.max(t,Math.round(e))),Z=e=>Math.round(Math.min(1,Math.max(0,e))*1e4)/1e4;async function Ke(e,t,n,o){let i=o.decode??(m=>createImageBitmap(m)),l=async()=>e.stillRead(await i(t),o.region??[0,0,1,1],o.detectorLimit),s;try{s=await l()}catch{try{await new Promise(m=>setTimeout(m,o.retryMs??300)),s=await l()}catch{return null}}let u=s.mrzBox;return u===void 0?null:{engine:o.engine,source:"live_mrz",format:n.format,lineCount:de(n.lineCount,2,3),checkDigitsValid:!0,stillConfirmed:s.valid&&s.digest===n.digest,band:[Z(u[0]),Z(u[1]),Z(Math.min(u[2],1-u[0])),Z(Math.min(u[3],1-u[1]))],digest:n.digest,framesToValid:de(n.framesToValid,1,1e3),msToValid:de(n.msToValid,0,12e4)}}function en(e){let t=null;return e?.then(n=>{t=n}),()=>t}var Rt=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]),Pt=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,7,1,5,0,6,64,11,11]);function je(e=globalThis){let t=e.WebAssembly?.validate;if(typeof t!="function")return{ok:!1,reason:"simd"};try{if(!t.call(e.WebAssembly,Rt)||!t.call(e.WebAssembly,Pt))return{ok:!1,reason:"simd"}}catch{return{ok:!1,reason:"simd"}}return typeof e.Worker!="function"?{ok:!1,reason:"worker"}:typeof e.createImageBitmap!="function"?{ok:!1,reason:"bitmap"}:{ok:!0}}function $e(e=globalThis){let t=e.navigator?.connection;return t?.saveData===!0||["slow-2g","2g","3g"].includes(t?.effectiveType??"")}var E=class extends Error{constructor(t){super(t),this.name="OcrEngineError",this.code=t}};function Je(){let e=t=>(t.close(),Promise.reject(new E("unsupported")));return{ready:Promise.resolve("unsupported"),busy:!1,bandRead:e,stillRead:e,layoutRead:e,dispose:()=>{}}}function Ze(e){let t;try{if(e.createWorker)t=e.createWorker();else if(e.workerUrl!==void 0)t=new Worker(e.workerUrl,{type:"module",name:"sekyro-ocr"});else return Je()}catch{return Je()}let n=new Map,o=0,i=!1,l=!1,s=!1;t.addEventListener("message",p=>{let g=p.data,M=n.get(g.id);M&&(n.delete(g.id),M.resolve(g))});let u=()=>{for(let p of n.values())p.reject(new E("error"));n.clear(),c()};t.addEventListener("error",u),t.addEventListener("messageerror",u);function m(p,g=[]){if(i)return Promise.reject(new E("disposed"));let M=++o;return new Promise((I,z)=>{n.set(M,{resolve:I,reject:z});try{t.postMessage({...p,id:M},g)}catch{n.delete(M),z(new E("error"))}})}function c(){if(!i){i=!0;try{t.postMessage({id:++o,kind:"dispose"})}catch{}t.terminate();for(let p of n.values())p.reject(new E("disposed"));n.clear()}}let b=(async()=>{let p=await m({kind:"init",baseUrl:e.baseUrl,salt:e.salt,detectorLimit:e.tuning.detectorLimit,maxDownloadMs:e.tuning.maxDownloadMs});if(p.kind==="failed")return p.reason;if(p.kind!=="ready")return"error";let g=await m({kind:"warmup"});if(g.kind!=="ready")return"error";let M=g.benchMs??g.warmupMs,I=e.deviceMemoryGb===void 0?Ee():e.deviceMemoryGb;return{warmupMs:g.warmupMs,downloadMs:p.downloadMs,cached:p.cached,benchMs:M,tier:Oe(M,I)}})().catch(()=>"error"),f,L=new Promise(p=>{f=setTimeout(()=>p("timeout"),e.tuning.loadTimeoutMs)}),k=Promise.race([b,L]).then(p=>(clearTimeout(f),typeof p=="string"?c():s=!0,i&&typeof p!="string"?"error":p));(e.page===void 0?globalThis.addEventListener?globalThis:null:e.page)?.addEventListener("pagehide",c,{once:!0});async function v(p,g,M){if(i)throw g.close(),new E("disposed");if(!s)throw g.close(),new E("not_ready");if(l)throw g.close(),new E("busy");l=!0;let I;try{let z=new Promise((N,G)=>{I=setTimeout(()=>{G(new E("timeout")),c()},e.tuning.readTimeoutMs??1e4)}),B=await Promise.race([m(p,[g]),z]);if(B.kind===M){let{id:N,...G}=B;return G}throw new E(B.kind==="error"?B.code:B.kind==="failed"?B.reason:"error")}finally{clearTimeout(I),l=!1}}return{ready:k,get busy(){return l},bandRead:(p,g=e.tuning.detectorLimit)=>v({kind:"band",bitmap:p,detectorLimit:g},p,"band"),stillRead:(p,g,M=e.tuning.detectorLimit)=>v({kind:"still",bitmap:p,region:g,detectorLimit:M},p,"band"),layoutRead:(p,g)=>v({kind:"layout",bitmap:p,detectorLimit:g},p,"layout"),dispose:c}}var V="sekyro-ocr-1",me=e=>e!==null&&typeof e=="object"?e:{},O=(e,t,n,o)=>typeof e=="number"&&Number.isFinite(e)&&e>=t&&e<=n?e:o,et=(e,t)=>typeof e=="boolean"?e:t,tt=e=>{let t=typeof e=="string"?/^sekyro-ocr-(\d{1,4})$/.exec(e):null;return t?Number(t[1]):Number.POSITIVE_INFINITY};function nt(e,t={}){let n=me(e),o=me(n.liveMrz),i=me(n.frontLock),l=tt(t.engine??V),s=t.mode==="off",u=p=>p.enabled===!0?p.arm==="live"?"live":"control":null,m=u(o),c=u(i),b=(p,g)=>!s&&g==="live"&&tt(p.minEngine??V)<=l,f=Be,L=b(o,m)?{detectorLimit:O(o.detectorLimit,320,1600,f.detectorLimit),bandMaxWidthPx:O(o.bandMaxWidthPx,320,4096,f.bandMaxWidthPx),minBandWidthPx:O(o.minBandWidthPx,0,4096,f.minBandWidthPx),bandTop:O(o.bandTop,0,.95,f.bandTop),minIntervalMs:O(o.minIntervalMs,0,5e3,f.minIntervalMs),stableReads:Math.round(O(o.stableReads,1,10,f.stableReads)),profileReads:Math.round(O(o.profileReads,1,100,f.profileReads)),maxReadMs:O(o.maxReadMs,50,6e4,f.maxReadMs),searchTimeoutMs:O(o.searchTimeoutMs,1e3,12e4,f.searchTimeoutMs),hint:et(o.hint,!0),stillConfirm:et(o.stillConfirm,!0)}:null,k=Ae,S=(p,g,M)=>O(i[p],g,M,k[p]),v=b(i,c)?{minLines:Math.round(S("minLines",1,50)),fillMin:S("fillMin",0,1),fillMax:S("fillMax",0,2),offsetMax:S("offsetMax",0,1),steadyFillDelta:S("steadyFillDelta",0,1),steadyOffsetDelta:S("steadyOffsetDelta",0,1),layoutShiftMax:S("layoutShiftMax",0,1),lineCountDelta:Math.round(S("lineCountDelta",0,50)),lockMs:S("lockMs",0,3e4),steadyMs:S("steadyMs",0,3e4),minFrames:Math.round(S("minFrames",1,100)),minIntervalMs:S("minIntervalMs",0,5e3),maxWidthPx:S("maxWidthPx",160,2048),detectorLimit:S("detectorLimit",320,1600),searchTimeoutMs:S("searchTimeoutMs",1e3,12e4)}:null;return{enabled:L!==null||v!==null,liveMrz:L,textLock:v,liveMrzArm:m,frontLockArm:c,load:{detectorLimit:L?.detectorLimit??v?.detectorLimit??f.detectorLimit,loadTimeoutMs:O(o.loadTimeoutMs,1e3,12e4,2e4),maxDownloadMs:O(o.maxDownloadMs,1e3,12e4,2e4)},reportSampleRate:O(o.reportSampleRate,0,1,1)}}function rt(e,t){return e.enabled?!(t.probe??je)().ok||(t.slow??$e)()?{ok:!1,reason:"unsupported"}:{ok:!0,engine:Ze({baseUrl:t.baseUrl,salt:t.salt,tuning:{detectorLimit:e.load.detectorLimit,maxDownloadMs:e.load.maxDownloadMs,loadTimeoutMs:e.load.loadTimeoutMs},...t.workerUrl!==void 0?{workerUrl:t.workerUrl}:{},...t.createWorker!==void 0?{createWorker:t.createWorker}:{},...t.page!==void 0?{page:t.page}:{},...t.deviceMemoryGb!==void 0?{deviceMemoryGb:t.deviceMemoryGb}:{}})}:{ok:!1,reason:"off"}}function Tt(e=typeof navigator<"u"?navigator.userAgent:""){return/SamsungBrowser\//.test(e)?"samsung":/Firefox\/|FxiOS\//.test(e)?"firefox":/Chrome\/|CriOS\/|Chromium\//.test(e)&&!/Edg\/|OPR\//.test(e)?"chrome":/Safari\//.test(e)&&/Version\/|Mobile\//.test(e)&&!/Chrome\/|CriOS\//.test(e)?"safari":"other"}var W=e=>e===void 0||!Number.isFinite(e)?void 0:Math.min(6e5,Math.max(0,Math.round(e))),pe=(e,t,n)=>e===void 0||!Number.isFinite(e)?void 0:Math.min(n,Math.max(t,Math.round(e)));function ot(e){let t=e.assist??null,n=e.load!==null&&e.load!==void 0&&typeof e.load=="object"?e.load:null,o=typeof e.load=="string"?e.load:null,i=t!==null?t.outcome:o==="unsupported"||o==="download"||o==="integrity"?o:o==="error"||o==="timeout"?"error":"off",l={kind:"live_mrz",platform:"web",engine:e.engine??V,arm:e.arm,capture:e.capture,outcome:i,reads:pe(t?.reads??0,0,1e4)??0,browser:e.browser??Tt()},s=(u,m)=>{m!==void 0&&(l[u]=m)};return s("format",t?.format),s("framesToValid",pe(t?.framesToValid,1,1e4)),s("msToValid",W(t?.msToValid)),s("framesToLock",pe(t?.framesToLock,1,1e4)),s("msToLock",W(t?.msToLock)),s("msToCapture",W(e.msToCapture)),s("readP50Ms",W(t?.readP50Ms)),s("readP90Ms",W(t?.readP90Ms)),s("deviceClass",t?.deviceClass),n!==null&&(s("warmupMs",W(n.warmupMs)),s("downloadMs",W(n.downloadMs)),s("cached",n.cached),s("tier",n.tier),s("benchMs",W(n.benchMs))),s("stillConfirmed",e.stillConfirmed),s("typeMismatch",e.typeMismatch),l}function fe(e,t){return e===void 0?!1:t==="passport"?e!=="TD3":e==="TD3"}var Lt=2,_t=1500;async function Ot(e){let t=await import("./capture-session-doc-J4MIDQOS.js");return new t.CaptureSessionDoc(e)}function Et(e){return{topLeft:{x:e.x,y:e.y},topRight:{x:e.x+e.width,y:e.y},bottomRight:{x:e.x+e.width,y:e.y+e.height},bottomLeft:{x:e.x,y:e.y+e.height}}}function At(e,t,n){let o=[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft],i=0;for(let l=0;l<o.length;l+=1){let s=o[l],u=o[(l+1)%o.length];i+=s.x*u.y-u.x*s.y}return t>0&&n>0?Math.abs(i)/2/(t*n):0}function kn(){import("./capture-session-doc-J4MIDQOS.js").then(e=>e.warmDocDetector()).catch(()=>{})}function Cn(e){return Bt(e,{}).handle}function Bt(e,t){let n=Re(),o=Pe({enabled:e.keepScreenAwake!==!1}),i=t.decode??(r=>createImageBitmap(r)),l=t.blurRefuseSharpnessMax??.16,s=t.now??(()=>performance.now()),u=We(e.documentType,t.catalogCapture===!0?t.captureSeries??ze(e.issuer,e.documentType):[]),m=u.sides.length===1||e.side==="single",c=ue(m?"singlePage":"twoSided",s());if(!m&&(e.side==="recto"||e.side==="verso")){let r=e.side==="recto"?"verso":"recto";c={...c,captured:{[r]:"server"},readSides:[r],current:e.side,phase:"flipCue",restPhase:"flipCue"}}let b="idle",f=null,L=null,k=!0,S=0,v=0,p=null,g=!1,M=!1,I="",z=null,B,N=null,G=[],ge=u.mrz==="none",at=u.barcodeSide==="recto"||u.barcodeSide==="verso"?u.barcodeSide:null,q=ge&&!m?t.barcode?.side??at:null,he=e.barcodeAssetBaseUrl??t.barcode?.assetBaseUrl,be=null,Se=()=>q===null||he===void 0||t.barcode?.seen!==void 0?Promise.resolve(null):(be??(be=import("./barcode-detect-C5IOXMKI.js").then(r=>r.loadBarcodeDetect(he)).catch(()=>null)),be),it=(r,a)=>{if(q===null)return Promise.resolve(null);let d,h=new Promise(D=>{d=setTimeout(()=>D(null),t.barcode?.budgetMs??_t)});return Promise.race([st(r,a,q),h]).finally(()=>clearTimeout(d))},st=async(r,a,d)=>{let h=d==="recto"?"verso":"recto";try{let D=t.barcode?.seen;if(D!==void 0)return await D(r)?d:h;let[_,x]=await Promise.all([Se(),a()]);if(_===null||x===null)return null;let y=Math.min(1600,x.width),w=document.createElement("canvas");w.width=y,w.height=Math.max(1,Math.round(x.height/x.width*y));try{let A=w.getContext("2d");return A===null?null:(A.drawImage(x,0,0,w.width,w.height),await Ue(_,A.getImageData(0,0,w.width,w.height),d))}finally{w.width=0,w.height=0}}catch{return null}},C=t.webOcr!==void 0&&!ge?nt(t.webOcr.captureDocument,{mode:e.liveMrz?.mode??"auto"}):null,X=null,F=C===null||!C.enabled?"off":null,Q=null,K=null,ye=new WeakMap,ee="";if(C!==null&&C.enabled&&t.webOcr!==void 0){let r=t.webOcr,a=rt(C,{baseUrl:e.liveMrz?.assetBaseUrl??r.baseUrl,salt:r.salt,...e.liveMrz?.workerUrl!==void 0?{workerUrl:e.liveMrz.workerUrl}:{},...r.createWorker!==void 0?{createWorker:r.createWorker}:{}});if(a.ok){X=a.engine;let d=new Ie({textLock:C.textLock,liveMrz:C.liveMrz});Q=d;let h=a.engine;h.ready.then(D=>{F=D,typeof D!="string"&&k&&d.setEngine(h,D.tier)})}else F=a.reason}let H=r=>{let a=JSON.stringify(r);a!==ee&&(ee=a,n.emit("mrz",r))},Me=(r,a)=>{let d=t.webOcr?.reports;if(d===void 0||C===null||r===void 0)return;let h=r.format==="ID-3"||r.side==="single"?"single":r.side==="verso"?"verso":"recto",D=h!=="recto"?C.liveMrzArm??C.frontLockArm:C.frontLockArm;if(D===null||Math.random()>=C.reportSampleRate)return;let _=r.via==="live_mrz"?K:null,x=()=>{let y=_?.value??null;d([ot({arm:D,capture:h,assist:r.ocr??null,load:D==="control"?"off":F,...r.msToCapture!==void 0?{msToCapture:r.msToCapture}:{},...y!==null&&y.stillConfirmed!==void 0?{stillConfirmed:y.stillConfirmed}:{},...a!==void 0?{typeMismatch:fe(a.format,u.format==="ID-3"?"passport":"card")}:{}})])};_!==null&&_.value===null?Promise.race([_.promise,new Promise(y=>setTimeout(y,3e3))]).then(x):x()},U=r=>{!k||r===b||(b=r,o.setActive(r==="starting"||r==="scanning"),n.emit("state",r))},ut=(r,a)=>a===void 0?null:m?"single":r.captured.recto===a?"recto":r.captured.verso===a?"verso":null,lt=r=>({phase:r.phase,captured:m?r.captured.recto!==void 0?["single"]:[]:["recto","verso"].filter(a=>r.captured[a]!==void 0),expected:m?null:r.current??null,notice:r.notice??null,lastShot:ut(r,r.lastShot),manualShutter:r.manualShutter,torchAvailable:f?.torchAvailable()??!1,torch:M}),De=()=>{let r=f;r!==null&&r.captureNow().catch(()=>R({type:"captureFailed",at:s()}))};function R(r){if(!k)return;let a=c;c=Qe(c,r),c.phase==="capturing"&&a.phase!=="capturing"&&Promise.resolve().then(De),c.phase==="result"&&a.phase!=="result"&&(U("done"),we());let d=lt(c),h=JSON.stringify(d);h!==I&&(I=h,n.emit("scan",d))}function we(){N!==null&&clearInterval(N),N=null;for(let r of G.splice(0))r();f?.destroy(),f=null,o.setActive(!1)}let ke=()=>f?.captureReport?.(),te=!1,Ce=(r,a)=>{if(!(r===void 0||t.onFaceReport===void 0))try{t.onFaceReport(r,a)}catch{}},j=r=>{ee="",!(f===null||c.phase==="reading"||c.phase==="result")&&(te=!1,p=m?"single":c.current??r,f.rearm(p))},ct=async(r,a,d,h)=>{K=null;let D=F!==null&&typeof F=="object"&&F.tier==="low";if(h!==void 0&&X!==null&&C?.liveMrz?.hint===!0&&!D){let A={promise:Ke(X,r,h,{engine:V,detectorLimit:C.liveMrz.detectorLimit}).catch(()=>null),value:null};A.promise.then(P=>{A.value=P}),K=A}h!==void 0&&fe(h.format,u.format==="ID-3"?"passport":"card")&&H({state:"mismatch",format:h.format});let _=ke();Ce(_,"captured"),te=!0,Me(_,h);let x=d===void 0?z:d===null?null:{quad:Et(d),frameWidth:0,frameHeight:0,inStill:!0},y={decoded:null},w=()=>(y.decoded??(y.decoded=Promise.resolve().then(()=>i(r)).catch(()=>null)),y.decoded);try{await dt(r,a,x,w,K,h)}finally{y.decoded!==null&&(await y.decoded)?.close()}},dt=async(r,a,d,h,D,_)=>{let x=`shot-${S+=1}`,y=c.current;if(R({type:"captured",id:x,at:s()}),e.haptics!==!1)try{globalThis.navigator?.vibrate?.(30)}catch{}if(!g&&l>0){let P=await(t.measureSharpness!==void 0?t.measureSharpness(r,d):h().then(T=>T===null?-1:_e(T,ae(d?.quad??null,d?.inStill===!0?T:{width:d?.frameWidth??0,height:d?.frameHeight??0},T)))).catch(()=>-1);if(!k)return;if(Number.isFinite(P)&&P>=0&&P<l){g=!0;let T=m?"recto":c.current??(c.captured.recto===void 0?"recto":"verso");R({type:"readFailed",side:T,id:x,issue:"blurry"}),j(T);return}}g=!1;let w;if(m)w="single";else{let P=_!==void 0&&_.format!=="TD3"&&(u.mrzSide==="recto"||u.mrzSide==="verso")?u.mrzSide:null,T=P===null&&t.classify===void 0?await it(r,h):null,xe=T===null||q===null?T:Ne(T,q,c.captured),Y=P??xe??(xe===null&&q!==null&&y!==void 0?y:null)??await(t.classify!==void 0?t.classify(r):h().then($=>$===null?y??"recto":d?.inStill===!0?ce($,480,null,!0):ce($,480,ae(d?.quad??null,{width:d?.frameWidth??0,height:d?.frameHeight??0},$)))).catch(()=>y??"recto");if(!k)return;if(c.captured[Y]!==void 0&&v<Lt){v+=1,R({type:"duplicate",id:x,side:Y}),j(Y==="recto"?"verso":"recto");return}let ve=c.captured.recto===void 0?"recto":c.captured.verso===void 0?"verso":void 0;w=c.captured[Y]!==void 0&&ve!==void 0?ve:Y,v=0,R({type:"classified",id:x,side:w})}let A=w==="verso"?"verso":"recto";try{let P=t.encode!==void 0?await t.encode(r):await h().then(T=>{if(T===null)throw new Error("the still could not be decoded");return ie(T)});if(!k)return;D!==null&&ye.set(P.blob,D),n.emit("captured",{image:P.blob,side:w,documentType:e.documentType,...e.issuer!==void 0?{issuer:e.issuer}:{},width:P.width,height:P.height,previewDataUrl:a}),t.deferRead!==!0&&R({type:"readOk",side:A})}catch(P){R({type:"readFailed",side:A,id:x,issue:"technical"}),n.emit("error",J("generic",!0,{phase:"keyframes",name:re(P)}))}j(A==="recto"?"verso":"recto")},mt=r=>{G.push(r.on("statechange",({state:a})=>{a==="preflight"||a==="acquiring"?U("starting"):a==="positioning"?U("scanning"):a==="captured"?U("captured"):a==="error"&&U("error")}),r.on("feedback",({key:a,reticle:d})=>n.emit("feedback",{key:a,reticle:d})),r.on("checks",a=>{n.emit("gate",{progress:a.p,quad:a.quad,frameWidth:a.frameWidth,frameHeight:a.frameHeight,...a.guide!==void 0?{guide:{detected:a.guide.detected,fill:a.guide.fill,offsetX:a.guide.offsetX??0,offsetY:a.guide.offsetY??0}}:{}});let d=a.ocr?.mrz;d!==void 0&&(d.state==="fallback"?H({state:"fallback",reason:d.reason}):d.state==="valid"?H({state:"valid",format:d.format}):d.state==="reading"?H({state:"reading",...d.format?{format:d.format}:{},...d.coach?{coach:d.coach}:{}}):H({state:"searching"}));let h=a.quad===null?0:At(a.quad,a.frameWidth,a.frameHeight);z=a.quad===null?null:{quad:a.quad,frameWidth:a.frameWidth,frameHeight:a.frameHeight},R({type:"report",report:{present:a.quad!==null&&a.plausible||a.guide?.detected===!0,ready:a.ready===!0,locking:a.p>=.5,areaFrac:h},at:s()})}),r.on("error",({kind:a,retryable:d,detail:h})=>n.emit("error",J(a,d,h))),r.on("artifacts",a=>{ct(a.keyframe,a.previewDataUrl,a.docRegion,a.liveMrz)}))},ne=()=>(L??(L=(async()=>{if(k){if(Se(),f===null){let r;try{r=await(t.createEngine??Ot)({...t.engineOptions??{},...B!==void 0?{guide:B}:{},video:e.video,format:u.format,side:m?"single":e.side??"recto",autoCapture:!1,...Q!==null?{ocr:Q}:{}})}catch(d){U("error"),n.emit("error",J("models",!0,{phase:"models",name:re(d)}));return}if(!k){r.destroy();return}f=r,p=m?"single":e.side??"recto",mt(r);let a=t.tickMs??500;a>0&&(N=setInterval(()=>R({type:"tick",at:s()}),a))}R({type:"clockRestart"}),C!==null&&C.liveMrzArm==="live"&&(F==="unsupported"||F==="off")&&H({state:"fallback",reason:F}),await f.start()}})().finally(()=>{L=null})),L);return{handle:{get state(){return b},on:(r,a)=>n.on(r,a),start:ne,retry:()=>{if(f===null&&c.phase==="result"){R({type:"retake"}),v=0,g=!1,ne();return}if(f!==null&&b!=="error"){R({type:"retake"}),v=0,g=!1,p=m?"single":null,f.rearm(m?"single":void 0);return}ne()},setSide:r=>{m||r==="single"||f!==null&&c.current===r&&p===r&&c.phase!=="reading"&&c.phase!=="result"||(c.current!==r&&(c={...c,current:r}),R({type:"clockRestart"}),c.phase!=="reading"&&c.phase!=="result"&&f!==null&&(p=r,f.rearm(r)))},shutter:De,focusAt:(r,a)=>{f?.focusAt?.(r,a)},setGuide:r=>{B=r,f?.setGuide?.(r)},setTorch:r=>{M=r,f?.setTorch(r),R({type:"tick",at:s()})},destroy:()=>{if(k&&f!==null&&b!=="done"){let r=ke();!te&&r!==void 0&&r.ticks>0&&Ce(r,"abandoned"),Me(r,void 0)}k=!1,we(),Q?.setEngine(null),X?.dispose(),X=null,n.clear()}},plan:u,setFlowState:r=>{(c.phase==="reading"||c.phase==="result")&&U(r==="done"&&c.phase!=="result"?"scanning":r)},settle:(r,a)=>{let d=r==="verso"?"verso":"recto";R(a.ok?{type:"readOk",side:d}:{type:"readFailed",side:d,issue:a.issue}),a.ok||j(d)},takeDeviceRead:r=>ye.get(r.image)?.value??null}}export{Ht as a,Yt as b,Vt as c,Qt as d,Kt as e,jt as f,He as g,ue as h,Qe as i,xt as j,vt as k,Jt as l,Ke as m,en as n,V as o,nt as p,rt as q,Tt as r,ot as s,fe as t,Lt as u,_t as v,kn as w,Cn as x,Bt as y};
|
|
1
|
+
import{d as ae,h as _e,i as Ae,j as Be,l as Ie}from"./chunk-MQHTFHSN.js";import{a as oe,e as Te,g as Le}from"./chunk-BRLQIJYF.js";import{m as J}from"./chunk-BPAGOPYL.js";import{a as Re,g as Pe}from"./chunk-7QZWBDI5.js";import{k as re}from"./chunk-CPUECYAJ.js";import{d as Oe,g as Ee}from"./chunk-WNBEOK5Q.js";function Fe(e,t){let n=new Set(e.flatMap(o=>o.sides.filter(i=>i[t]!==null).map(i=>i.side)));return n.size===1?[...n][0]:null}function pt(e){let t=Te.find(o=>o.docType===e),n=t.mrz==="none"?null:t.mrz==="td3"?"single":"verso";return{sides:t.sides,format:Le(e),mrz:t.mrz==="none"?"none":"required",mrzSide:n,barcodeSide:null,portraitSide:t.portraitSide,scripts:null}}function ft(e){let t=[];for(let n of e)for(let o of n.sides){if(!Array.isArray(o.scripts))return null;for(let i of o.scripts)t.includes(i)||t.push(i)}return t}function We(e,t){if(t.length===0)return pt(e);let n=t.some(u=>u.sides.length>1),o=new Set(t.map(u=>u.format)),i=o.size===1?[...o][0]:"card",l=t.filter(u=>u.sides.some(m=>m.mrz!==null)).length,s=t.find(u=>u.sides.length>1===n)?.sides.find(u=>u.portrait)?.side;return{sides:n?["recto","verso"]:["single"],format:i,mrz:l===t.length?"required":l===0?"none":"optional",mrzSide:Fe(t,"mrz"),barcodeSide:Fe(t,"barcode"),portraitSide:s??(n?"recto":"single"),scripts:ft(t)}}function ze(e,t){if(e===void 0)return[];let n=e.toUpperCase();return Object.prototype.hasOwnProperty.call(oe,n)?oe[n]?.[t]??[]:[]}async function Ue(e,t,n){return await e(t)?n:n==="recto"?"verso":"recto"}function Ne(e,t,n){return e!==t&&t==="verso"&&n.recto!==void 0&&n.verso===void 0?"verso":e}var gt={low:{maxLongEdge:1920,payloadTargetBytes:7e5,qMin:.7,qMax:.92},mid:{maxLongEdge:2240,payloadTargetBytes:12e5,qMin:.7,qMax:.92},good:{maxLongEdge:2560,payloadTargetBytes:16e5,qMin:.7,qMax:.92}};function ht(e){let{deviceMemory:t,effectiveType:n,saveData:o,downlinkMbps:i,sourceLongEdge:l}=e,s=o===!0||n==="slow-2g"||n==="2g"||i!=null&&i>0&&i<1,u=t!=null&&t<=2,m=n==="4g"||i!=null&&i>=5,c=t!=null&&t>=6,b;s||u?b="low":m&&c?b="good":b="mid";let f=gt[b],L=l&&l>0?Math.min(f.maxLongEdge,l):f.maxLongEdge;return{tier:b,...f,maxLongEdge:L}}function Ge(e){let t={};try{let n=navigator;typeof n.deviceMemory=="number"&&(t.deviceMemory=n.deviceMemory);let o=n.connection;o&&(t.effectiveType=o.effectiveType,t.saveData=o.saveData,t.downlinkMbps=o.downlink)}catch{}return typeof e=="number"&&e>0&&(t.sourceLongEdge=e),ht(t)}function bt(e,t,n){let o=Math.min(1,Math.max(0,(e-.28)/.21999999999999997)),i=(t+n)/2;return Math.max(t,n-o*(n-i))}function St(e,t,n){let o=Math.max(e,t),i=o>0?Math.min(1,n/o):1;return{width:Math.max(1,Math.round(e*i)),height:Math.max(1,Math.round(t*i))}}async function yt(e,t){let n=t.startQ,o=await e(n);for(let i=0;i<4&&!(o.size<=t.budgetBytes||n<=t.qMin);i++)n=Math.max(t.qMin,n-.08),o=await e(n);return{blob:o,quality:n}}async function qe(e,t,n,o,i){if(t<=0||n<=0)return null;let{width:l,height:s}=St(t,n,o.maxLongEdge),u=document.createElement("canvas");u.width=l,u.height=s;let m=u.getContext("2d");if(!m)return null;m.drawImage(e,0,0,l,s);let c=k=>new Promise((S,v)=>{u.toBlob(p=>p?S(p):v(new Error("canvas toBlob returned null")),"image/jpeg",k)}),b=bt(i,o.qMin,o.qMax),{blob:f,quality:L}=await yt(c,{startQ:b,qMin:o.qMin,budgetBytes:o.payloadTargetBytes}).finally(()=>{u.width=0,u.height=0});if(f.size>5242880)throw new Error("encoded document exceeds the 5242880-byte media cap");return{blob:f,quality:L,width:l,height:s}}async function ie(e){let t=Ge(Math.max(e.width,e.height)),n=await qe(e,e.width,e.height,t,.5);if(n===null)throw new Error("canvas encode unavailable");return{blob:n.blob,width:n.width,height:n.height}}async function Ht(e){let t=await createImageBitmap(e);try{return await ie(t)}finally{t.close()}}var Yt=250,Vt=.6,Qt=1800,Kt=6e3,jt=2e3,He=.16;function ue(e,t){return{layout:e,phase:"framing",captured:{},pending:[],lastCaptureAt:t,lastReportAt:t,manualShutter:!1,restPhase:"framing",readSides:[],needFlip:!1,flipped:!1,flipTimeoutSpent:!1,timeoutCapture:!1,lastShotByTimeout:!1}}var Xe=e=>e==="recto"?"verso":"recto",Ye=e=>e.phase==="framing"||e.phase==="locking"||e.phase==="flipCue"||e.phase==="reaskRecto",le=e=>(e.captured.recto!==void 0?1:0)+(e.captured.verso!==void 0?1:0)+e.pending.length;function se(e,t){return e.lastCaptureAt>=0&&e.lastReportAt>=0?e:{...e,lastCaptureAt:e.lastCaptureAt<0?t:e.lastCaptureAt,lastReportAt:e.lastReportAt<0?t:e.lastReportAt}}function Mt(e,t,n){if(e.phase==="result")return{...e,lastReportAt:n};let o=!t.present||e.captureArea!==void 0&&t.areaFrac<.6*e.captureArea,{flipped:i,awaySince:l}=e;o&&(l=l??n),l!==void 0&&n-l>=250&&(i=!0),o||(l=void 0);let s=e.flipTimeoutSpent&&!(i&&!e.flipped),u=e.notice==="same_face"&&i&&!e.flipped?void 0:e.notice,m={...e,lastReportAt:n,flipped:i,awaySince:l,flipTimeoutSpent:s,notice:u,lastArea:t.areaFrac};if(!Ye(e))return m;if(e.needFlip&&!i){if(!t.ready)return{...m,phase:e.restPhase,goodSince:void 0};let c=e.lastShot!==void 0&&e.pending.includes(e.lastShot);if(s||c)return{...m,goodSince:void 0,phase:e.restPhase};let b=e.goodSince??n;return n-b>=1800?{...m,goodSince:b,phase:"capturing",flipTimeoutSpent:!0,timeoutCapture:!0}:{...m,goodSince:b,phase:e.restPhase}}return t.ready?{...m,phase:"capturing",goodSince:e.goodSince??n}:{...m,goodSince:void 0,phase:t.locking?"locking":e.restPhase}}function Dt(e,t){if(!Ye(e)||e.manualShutter)return e;let n=t-e.lastReportAt>=2e3,o=t-e.lastCaptureAt>=6e3;return n||o?{...e,manualShutter:!0}:e}function wt(e,t,n){let o=e.layout==="singlePage",i=o?{recto:t}:e.captured,l=o?[]:[...e.pending,t],s={...e,captured:i,pending:l,lastShot:t,lastCaptureAt:n,lastReportAt:-1,manualShutter:!1,goodSince:void 0,notice:void 0,awaySince:void 0,flipped:!1,lastShotByTimeout:e.timeoutCapture,timeoutCapture:!1,captureArea:e.lastArea};return o||le({captured:i,pending:l})>=2?{...s,phase:"reading",restPhase:"framing",current:void 0,needFlip:!1}:{...s,phase:"flipCue",restPhase:"flipCue",current:void 0,needFlip:!0}}function Ve(e,t,n){return e.pending.includes(t)?{...e,pending:e.pending.filter(o=>o!==t),lastShot:e.lastShot===t?void 0:e.lastShot,phase:e.phase==="capturing"?e.phase:"flipCue",restPhase:"flipCue",current:Xe(n),needFlip:!0,flipTimeoutSpent:!1,goodSince:void 0,manualShutter:!0,notice:"same_face",lastCaptureAt:-1,lastReportAt:-1}:e}function kt(e,t,n){if(!e.pending.includes(t))return e;if(e.captured[n]!==void 0)return Ve(e,t,n);let o=e.pending.filter(m=>m!==t),i={...e,pending:o,captured:{...e.captured,[n]:t}};if(le(i)!==1||e.layout==="singlePage")return i;let l=Xe(n),s=l==="recto"&&e.restPhase==="reaskRecto"?"reaskRecto":"flipCue",u=e.phase==="flipCue"||e.phase==="reaskRecto"||e.phase==="framing";return{...i,restPhase:s,current:l,phase:u?s:e.phase}}function Ct(e,t){let n=t.id??e.captured[t.side],o={...e.captured};(t.id===void 0||o[t.side]===t.id)&&delete o[t.side];let i=e.pending.filter(c=>c!==n),l=e.layout==="twoSided"&&le({captured:o,pending:i})>0,s=e.lastShotByTimeout||n===e.lastShot!==e.flipped,u=l&&!s,m=u?t.side==="recto"?"reaskRecto":"flipCue":"framing";return{...e,captured:o,pending:i,readSides:e.readSides.filter(c=>c!==t.side),lastShot:e.lastShot===n?void 0:e.lastShot,notice:t.issue,goodSince:void 0,manualShutter:!1,phase:m,restPhase:m,current:t.side,needFlip:u,flipped:!1,flipTimeoutSpent:!1,awaySince:void 0,lastCaptureAt:-1,lastReportAt:-1}}function Qe(e,t){switch(t.type){case"report":return Mt(se(e,t.at),t.report,t.at);case"tick":return Dt(se(e,t.at),t.at);case"captured":return wt(se(e,t.at),t.id,t.at);case"captureFailed":return{...e,phase:e.restPhase,goodSince:void 0,lastCaptureAt:t.at,manualShutter:!0,timeoutCapture:!1};case"classified":return kt(e,t.id,t.side);case"duplicate":return Ve(e,t.id,t.side);case"readOk":{let n=e.readSides.includes(t.side)?e.readSides:[...e.readSides,t.side],o=["recto","verso"].filter(l=>e.captured[l]!==void 0),i=e.phase==="reading"&&e.pending.length===0&&o.every(l=>n.includes(l));return{...e,readSides:n,flipTimeoutSpent:!1,phase:i?"result":e.phase}}case"readFailed":return Ct(e,t);case"clockRestart":return e.lastCaptureAt<0&&e.lastReportAt<0&&e.awaySince===void 0?e:{...e,awaySince:void 0,lastCaptureAt:-1,lastReportAt:-1};case"retake":return{...ue(e.layout,-1),lastCaptureAt:-1,lastReportAt:-1};default:return e}}function xt(e,t,n=!1){let o=e(t);return o===null?"recto":!n||o.y+o.height/2>=t.height/2?"verso":"recto"}async function vt(e,t=!1){let{detectMrzBand:n}=await import("./mrz-band-VYHOTDHY.js");return xt(n,e,t)}async function ce(e,t=480,n,o=n!=null){let i=n??{x:0,y:0,width:e.width,height:e.height},l=Math.max(1,Math.round(i.height/i.width*t)),s=document.createElement("canvas");s.width=t,s.height=l;try{let u=s.getContext("2d");return u===null?"recto":(u.drawImage(e,i.x,i.y,i.width,i.height,0,0,t,l),await vt(u.getImageData(0,0,t,l),o))}finally{s.width=0,s.height=0}}async function Jt(e,t=480){try{let n=await createImageBitmap(e),o=Math.max(1,Math.round(n.height/n.width*t)),i=document.createElement("canvas");i.width=t,i.height=o;let l=i.getContext("2d");return l===null?(n.close(),null):(l.drawImage(n,0,0,t,o),n.close(),l.getImageData(0,0,t,o))}catch{return null}}var de=(e,t,n)=>Math.min(n,Math.max(t,Math.round(e))),Z=e=>Math.round(Math.min(1,Math.max(0,e))*1e4)/1e4;async function Ke(e,t,n,o){let i=o.decode??(m=>createImageBitmap(m)),l=async()=>e.stillRead(await i(t),o.region??[0,0,1,1],o.detectorLimit),s;try{s=await l()}catch{try{await new Promise(m=>setTimeout(m,o.retryMs??300)),s=await l()}catch{return null}}let u=s.mrzBox;return u===void 0?null:{engine:o.engine,source:"live_mrz",format:n.format,lineCount:de(n.lineCount,2,3),checkDigitsValid:!0,stillConfirmed:s.valid&&s.digest===n.digest,band:[Z(u[0]),Z(u[1]),Z(Math.min(u[2],1-u[0])),Z(Math.min(u[3],1-u[1]))],digest:n.digest,framesToValid:de(n.framesToValid,1,1e3),msToValid:de(n.msToValid,0,12e4)}}function en(e){let t=null;return e?.then(n=>{t=n}),()=>t}var Rt=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]),Pt=new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,7,1,5,0,6,64,11,11]);function je(e=globalThis){let t=e.WebAssembly?.validate;if(typeof t!="function")return{ok:!1,reason:"simd"};try{if(!t.call(e.WebAssembly,Rt)||!t.call(e.WebAssembly,Pt))return{ok:!1,reason:"simd"}}catch{return{ok:!1,reason:"simd"}}return typeof e.Worker!="function"?{ok:!1,reason:"worker"}:typeof e.createImageBitmap!="function"?{ok:!1,reason:"bitmap"}:{ok:!0}}function $e(e=globalThis){let t=e.navigator?.connection;return t?.saveData===!0||["slow-2g","2g","3g"].includes(t?.effectiveType??"")}var E=class extends Error{constructor(t){super(t),this.name="OcrEngineError",this.code=t}};function Je(){let e=t=>(t.close(),Promise.reject(new E("unsupported")));return{ready:Promise.resolve("unsupported"),busy:!1,bandRead:e,stillRead:e,layoutRead:e,dispose:()=>{}}}function Ze(e){let t;try{if(e.createWorker)t=e.createWorker();else if(e.workerUrl!==void 0)t=new Worker(e.workerUrl,{type:"module",name:"sekyro-ocr"});else return Je()}catch{return Je()}let n=new Map,o=0,i=!1,l=!1,s=!1;t.addEventListener("message",p=>{let g=p.data,M=n.get(g.id);M&&(n.delete(g.id),M.resolve(g))});let u=()=>{for(let p of n.values())p.reject(new E("error"));n.clear(),c()};t.addEventListener("error",u),t.addEventListener("messageerror",u);function m(p,g=[]){if(i)return Promise.reject(new E("disposed"));let M=++o;return new Promise((I,z)=>{n.set(M,{resolve:I,reject:z});try{t.postMessage({...p,id:M},g)}catch{n.delete(M),z(new E("error"))}})}function c(){if(!i){i=!0;try{t.postMessage({id:++o,kind:"dispose"})}catch{}t.terminate();for(let p of n.values())p.reject(new E("disposed"));n.clear()}}let b=(async()=>{let p=await m({kind:"init",baseUrl:e.baseUrl,salt:e.salt,detectorLimit:e.tuning.detectorLimit,maxDownloadMs:e.tuning.maxDownloadMs});if(p.kind==="failed")return p.reason;if(p.kind!=="ready")return"error";let g=await m({kind:"warmup"});if(g.kind!=="ready")return"error";let M=g.benchMs??g.warmupMs,I=e.deviceMemoryGb===void 0?Ee():e.deviceMemoryGb;return{warmupMs:g.warmupMs,downloadMs:p.downloadMs,cached:p.cached,benchMs:M,tier:Oe(M,I)}})().catch(()=>"error"),f,L=new Promise(p=>{f=setTimeout(()=>p("timeout"),e.tuning.loadTimeoutMs)}),k=Promise.race([b,L]).then(p=>(clearTimeout(f),typeof p=="string"?c():s=!0,i&&typeof p!="string"?"error":p));(e.page===void 0?globalThis.addEventListener?globalThis:null:e.page)?.addEventListener("pagehide",c,{once:!0});async function v(p,g,M){if(i)throw g.close(),new E("disposed");if(!s)throw g.close(),new E("not_ready");if(l)throw g.close(),new E("busy");l=!0;let I;try{let z=new Promise((N,G)=>{I=setTimeout(()=>{G(new E("timeout")),c()},e.tuning.readTimeoutMs??1e4)}),B=await Promise.race([m(p,[g]),z]);if(B.kind===M){let{id:N,...G}=B;return G}throw new E(B.kind==="error"?B.code:B.kind==="failed"?B.reason:"error")}finally{clearTimeout(I),l=!1}}return{ready:k,get busy(){return l},bandRead:(p,g=e.tuning.detectorLimit)=>v({kind:"band",bitmap:p,detectorLimit:g},p,"band"),stillRead:(p,g,M=e.tuning.detectorLimit)=>v({kind:"still",bitmap:p,region:g,detectorLimit:M},p,"band"),layoutRead:(p,g)=>v({kind:"layout",bitmap:p,detectorLimit:g},p,"layout"),dispose:c}}var V="sekyro-ocr-1",me=e=>e!==null&&typeof e=="object"?e:{},O=(e,t,n,o)=>typeof e=="number"&&Number.isFinite(e)&&e>=t&&e<=n?e:o,et=(e,t)=>typeof e=="boolean"?e:t,tt=e=>{let t=typeof e=="string"?/^sekyro-ocr-(\d{1,4})$/.exec(e):null;return t?Number(t[1]):Number.POSITIVE_INFINITY};function nt(e,t={}){let n=me(e),o=me(n.liveMrz),i=me(n.frontLock),l=tt(t.engine??V),s=t.mode==="off",u=p=>p.enabled===!0?p.arm==="live"?"live":"control":null,m=u(o),c=u(i),b=(p,g)=>!s&&g==="live"&&tt(p.minEngine??V)<=l,f=Be,L=b(o,m)?{detectorLimit:O(o.detectorLimit,320,1600,f.detectorLimit),bandMaxWidthPx:O(o.bandMaxWidthPx,320,4096,f.bandMaxWidthPx),minBandWidthPx:O(o.minBandWidthPx,0,4096,f.minBandWidthPx),bandTop:O(o.bandTop,0,.95,f.bandTop),minIntervalMs:O(o.minIntervalMs,0,5e3,f.minIntervalMs),stableReads:Math.round(O(o.stableReads,1,10,f.stableReads)),profileReads:Math.round(O(o.profileReads,1,100,f.profileReads)),maxReadMs:O(o.maxReadMs,50,6e4,f.maxReadMs),searchTimeoutMs:O(o.searchTimeoutMs,1e3,12e4,f.searchTimeoutMs),hint:et(o.hint,!0),stillConfirm:et(o.stillConfirm,!0)}:null,k=Ae,S=(p,g,M)=>O(i[p],g,M,k[p]),v=b(i,c)?{minLines:Math.round(S("minLines",1,50)),fillMin:S("fillMin",0,1),fillMax:S("fillMax",0,2),offsetMax:S("offsetMax",0,1),steadyFillDelta:S("steadyFillDelta",0,1),steadyOffsetDelta:S("steadyOffsetDelta",0,1),layoutShiftMax:S("layoutShiftMax",0,1),lineCountDelta:Math.round(S("lineCountDelta",0,50)),lockMs:S("lockMs",0,3e4),steadyMs:S("steadyMs",0,3e4),minFrames:Math.round(S("minFrames",1,100)),minIntervalMs:S("minIntervalMs",0,5e3),maxWidthPx:S("maxWidthPx",160,2048),detectorLimit:S("detectorLimit",320,1600),searchTimeoutMs:S("searchTimeoutMs",1e3,12e4)}:null;return{enabled:L!==null||v!==null,liveMrz:L,textLock:v,liveMrzArm:m,frontLockArm:c,load:{detectorLimit:L?.detectorLimit??v?.detectorLimit??f.detectorLimit,loadTimeoutMs:O(o.loadTimeoutMs,1e3,12e4,2e4),maxDownloadMs:O(o.maxDownloadMs,1e3,12e4,2e4)},reportSampleRate:O(o.reportSampleRate,0,1,1)}}function rt(e,t){return e.enabled?!(t.probe??je)().ok||(t.slow??$e)()?{ok:!1,reason:"unsupported"}:{ok:!0,engine:Ze({baseUrl:t.baseUrl,salt:t.salt,tuning:{detectorLimit:e.load.detectorLimit,maxDownloadMs:e.load.maxDownloadMs,loadTimeoutMs:e.load.loadTimeoutMs},...t.workerUrl!==void 0?{workerUrl:t.workerUrl}:{},...t.createWorker!==void 0?{createWorker:t.createWorker}:{},...t.page!==void 0?{page:t.page}:{},...t.deviceMemoryGb!==void 0?{deviceMemoryGb:t.deviceMemoryGb}:{}})}:{ok:!1,reason:"off"}}function Tt(e=typeof navigator<"u"?navigator.userAgent:""){return/SamsungBrowser\//.test(e)?"samsung":/Firefox\/|FxiOS\//.test(e)?"firefox":/Chrome\/|CriOS\/|Chromium\//.test(e)&&!/Edg\/|OPR\//.test(e)?"chrome":/Safari\//.test(e)&&/Version\/|Mobile\//.test(e)&&!/Chrome\/|CriOS\//.test(e)?"safari":"other"}var W=e=>e===void 0||!Number.isFinite(e)?void 0:Math.min(6e5,Math.max(0,Math.round(e))),pe=(e,t,n)=>e===void 0||!Number.isFinite(e)?void 0:Math.min(n,Math.max(t,Math.round(e)));function ot(e){let t=e.assist??null,n=e.load!==null&&e.load!==void 0&&typeof e.load=="object"?e.load:null,o=typeof e.load=="string"?e.load:null,i=t!==null?t.outcome:o==="unsupported"||o==="download"||o==="integrity"?o:o==="error"||o==="timeout"?"error":"off",l={kind:"live_mrz",platform:"web",engine:e.engine??V,arm:e.arm,capture:e.capture,outcome:i,reads:pe(t?.reads??0,0,1e4)??0,browser:e.browser??Tt()},s=(u,m)=>{m!==void 0&&(l[u]=m)};return s("format",t?.format),s("framesToValid",pe(t?.framesToValid,1,1e4)),s("msToValid",W(t?.msToValid)),s("framesToLock",pe(t?.framesToLock,1,1e4)),s("msToLock",W(t?.msToLock)),s("msToCapture",W(e.msToCapture)),s("readP50Ms",W(t?.readP50Ms)),s("readP90Ms",W(t?.readP90Ms)),s("deviceClass",t?.deviceClass),n!==null&&(s("warmupMs",W(n.warmupMs)),s("downloadMs",W(n.downloadMs)),s("cached",n.cached),s("tier",n.tier),s("benchMs",W(n.benchMs))),s("stillConfirmed",e.stillConfirmed),s("typeMismatch",e.typeMismatch),l}function fe(e,t){return e===void 0?!1:t==="passport"?e!=="TD3":e==="TD3"}var Lt=2,_t=1500;async function Ot(e){let t=await import("./capture-session-doc-DFLSX6BB.js");return new t.CaptureSessionDoc(e)}function Et(e){return{topLeft:{x:e.x,y:e.y},topRight:{x:e.x+e.width,y:e.y},bottomRight:{x:e.x+e.width,y:e.y+e.height},bottomLeft:{x:e.x,y:e.y+e.height}}}function At(e,t,n){let o=[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft],i=0;for(let l=0;l<o.length;l+=1){let s=o[l],u=o[(l+1)%o.length];i+=s.x*u.y-u.x*s.y}return t>0&&n>0?Math.abs(i)/2/(t*n):0}function kn(){import("./capture-session-doc-DFLSX6BB.js").then(e=>e.warmDocDetector()).catch(()=>{})}function Cn(e){return Bt(e,{}).handle}function Bt(e,t){let n=Re(),o=Pe({enabled:e.keepScreenAwake!==!1}),i=t.decode??(r=>createImageBitmap(r)),l=t.blurRefuseSharpnessMax??.16,s=t.now??(()=>performance.now()),u=We(e.documentType,t.catalogCapture===!0?t.captureSeries??ze(e.issuer,e.documentType):[]),m=u.sides.length===1||e.side==="single",c=ue(m?"singlePage":"twoSided",s());if(!m&&(e.side==="recto"||e.side==="verso")){let r=e.side==="recto"?"verso":"recto";c={...c,captured:{[r]:"server"},readSides:[r],current:e.side,phase:"flipCue",restPhase:"flipCue"}}let b="idle",f=null,L=null,k=!0,S=0,v=0,p=null,g=!1,M=!1,I="",z=null,B,N=null,G=[],ge=u.mrz==="none",at=u.barcodeSide==="recto"||u.barcodeSide==="verso"?u.barcodeSide:null,q=ge&&!m?t.barcode?.side??at:null,he=e.barcodeAssetBaseUrl??t.barcode?.assetBaseUrl,be=null,Se=()=>q===null||he===void 0||t.barcode?.seen!==void 0?Promise.resolve(null):(be??(be=import("./barcode-detect-C5IOXMKI.js").then(r=>r.loadBarcodeDetect(he)).catch(()=>null)),be),it=(r,a)=>{if(q===null)return Promise.resolve(null);let d,h=new Promise(D=>{d=setTimeout(()=>D(null),t.barcode?.budgetMs??_t)});return Promise.race([st(r,a,q),h]).finally(()=>clearTimeout(d))},st=async(r,a,d)=>{let h=d==="recto"?"verso":"recto";try{let D=t.barcode?.seen;if(D!==void 0)return await D(r)?d:h;let[_,x]=await Promise.all([Se(),a()]);if(_===null||x===null)return null;let y=Math.min(1600,x.width),w=document.createElement("canvas");w.width=y,w.height=Math.max(1,Math.round(x.height/x.width*y));try{let A=w.getContext("2d");return A===null?null:(A.drawImage(x,0,0,w.width,w.height),await Ue(_,A.getImageData(0,0,w.width,w.height),d))}finally{w.width=0,w.height=0}}catch{return null}},C=t.webOcr!==void 0&&!ge?nt(t.webOcr.captureDocument,{mode:e.liveMrz?.mode??"auto"}):null,X=null,F=C===null||!C.enabled?"off":null,Q=null,K=null,ye=new WeakMap,ee="";if(C!==null&&C.enabled&&t.webOcr!==void 0){let r=t.webOcr,a=rt(C,{baseUrl:e.liveMrz?.assetBaseUrl??r.baseUrl,salt:r.salt,...e.liveMrz?.workerUrl!==void 0?{workerUrl:e.liveMrz.workerUrl}:{},...r.createWorker!==void 0?{createWorker:r.createWorker}:{}});if(a.ok){X=a.engine;let d=new Ie({textLock:C.textLock,liveMrz:C.liveMrz});Q=d;let h=a.engine;h.ready.then(D=>{F=D,typeof D!="string"&&k&&d.setEngine(h,D.tier)})}else F=a.reason}let H=r=>{let a=JSON.stringify(r);a!==ee&&(ee=a,n.emit("mrz",r))},Me=(r,a)=>{let d=t.webOcr?.reports;if(d===void 0||C===null||r===void 0)return;let h=r.format==="ID-3"||r.side==="single"?"single":r.side==="verso"?"verso":"recto",D=h!=="recto"?C.liveMrzArm??C.frontLockArm:C.frontLockArm;if(D===null||Math.random()>=C.reportSampleRate)return;let _=r.via==="live_mrz"?K:null,x=()=>{let y=_?.value??null;d([ot({arm:D,capture:h,assist:r.ocr??null,load:D==="control"?"off":F,...r.msToCapture!==void 0?{msToCapture:r.msToCapture}:{},...y!==null&&y.stillConfirmed!==void 0?{stillConfirmed:y.stillConfirmed}:{},...a!==void 0?{typeMismatch:fe(a.format,u.format==="ID-3"?"passport":"card")}:{}})])};_!==null&&_.value===null?Promise.race([_.promise,new Promise(y=>setTimeout(y,3e3))]).then(x):x()},U=r=>{!k||r===b||(b=r,o.setActive(r==="starting"||r==="scanning"),n.emit("state",r))},ut=(r,a)=>a===void 0?null:m?"single":r.captured.recto===a?"recto":r.captured.verso===a?"verso":null,lt=r=>({phase:r.phase,captured:m?r.captured.recto!==void 0?["single"]:[]:["recto","verso"].filter(a=>r.captured[a]!==void 0),expected:m?null:r.current??null,notice:r.notice??null,lastShot:ut(r,r.lastShot),manualShutter:r.manualShutter,torchAvailable:f?.torchAvailable()??!1,torch:M}),De=()=>{let r=f;r!==null&&r.captureNow().catch(()=>R({type:"captureFailed",at:s()}))};function R(r){if(!k)return;let a=c;c=Qe(c,r),c.phase==="capturing"&&a.phase!=="capturing"&&Promise.resolve().then(De),c.phase==="result"&&a.phase!=="result"&&(U("done"),we());let d=lt(c),h=JSON.stringify(d);h!==I&&(I=h,n.emit("scan",d))}function we(){N!==null&&clearInterval(N),N=null;for(let r of G.splice(0))r();f?.destroy(),f=null,o.setActive(!1)}let ke=()=>f?.captureReport?.(),te=!1,Ce=(r,a)=>{if(!(r===void 0||t.onFaceReport===void 0))try{t.onFaceReport(r,a)}catch{}},j=r=>{ee="",!(f===null||c.phase==="reading"||c.phase==="result")&&(te=!1,p=m?"single":c.current??r,f.rearm(p))},ct=async(r,a,d,h)=>{K=null;let D=F!==null&&typeof F=="object"&&F.tier==="low";if(h!==void 0&&X!==null&&C?.liveMrz?.hint===!0&&!D){let A={promise:Ke(X,r,h,{engine:V,detectorLimit:C.liveMrz.detectorLimit}).catch(()=>null),value:null};A.promise.then(P=>{A.value=P}),K=A}h!==void 0&&fe(h.format,u.format==="ID-3"?"passport":"card")&&H({state:"mismatch",format:h.format});let _=ke();Ce(_,"captured"),te=!0,Me(_,h);let x=d===void 0?z:d===null?null:{quad:Et(d),frameWidth:0,frameHeight:0,inStill:!0},y={decoded:null},w=()=>(y.decoded??(y.decoded=Promise.resolve().then(()=>i(r)).catch(()=>null)),y.decoded);try{await dt(r,a,x,w,K,h)}finally{y.decoded!==null&&(await y.decoded)?.close()}},dt=async(r,a,d,h,D,_)=>{let x=`shot-${S+=1}`,y=c.current;if(R({type:"captured",id:x,at:s()}),e.haptics!==!1)try{globalThis.navigator?.vibrate?.(30)}catch{}if(!g&&l>0){let P=await(t.measureSharpness!==void 0?t.measureSharpness(r,d):h().then(T=>T===null?-1:_e(T,ae(d?.quad??null,d?.inStill===!0?T:{width:d?.frameWidth??0,height:d?.frameHeight??0},T)))).catch(()=>-1);if(!k)return;if(Number.isFinite(P)&&P>=0&&P<l){g=!0;let T=m?"recto":c.current??(c.captured.recto===void 0?"recto":"verso");R({type:"readFailed",side:T,id:x,issue:"blurry"}),j(T);return}}g=!1;let w;if(m)w="single";else{let P=_!==void 0&&_.format!=="TD3"&&(u.mrzSide==="recto"||u.mrzSide==="verso")?u.mrzSide:null,T=P===null&&t.classify===void 0?await it(r,h):null,xe=T===null||q===null?T:Ne(T,q,c.captured),Y=P??xe??(xe===null&&q!==null&&y!==void 0?y:null)??await(t.classify!==void 0?t.classify(r):h().then($=>$===null?y??"recto":d?.inStill===!0?ce($,480,null,!0):ce($,480,ae(d?.quad??null,{width:d?.frameWidth??0,height:d?.frameHeight??0},$)))).catch(()=>y??"recto");if(!k)return;if(c.captured[Y]!==void 0&&v<Lt){v+=1,R({type:"duplicate",id:x,side:Y}),j(Y==="recto"?"verso":"recto");return}let ve=c.captured.recto===void 0?"recto":c.captured.verso===void 0?"verso":void 0;w=c.captured[Y]!==void 0&&ve!==void 0?ve:Y,v=0,R({type:"classified",id:x,side:w})}let A=w==="verso"?"verso":"recto";try{let P=t.encode!==void 0?await t.encode(r):await h().then(T=>{if(T===null)throw new Error("the still could not be decoded");return ie(T)});if(!k)return;D!==null&&ye.set(P.blob,D),n.emit("captured",{image:P.blob,side:w,documentType:e.documentType,...e.issuer!==void 0?{issuer:e.issuer}:{},width:P.width,height:P.height,previewDataUrl:a}),t.deferRead!==!0&&R({type:"readOk",side:A})}catch(P){R({type:"readFailed",side:A,id:x,issue:"technical"}),n.emit("error",J("generic",!0,{phase:"keyframes",name:re(P)}))}j(A==="recto"?"verso":"recto")},mt=r=>{G.push(r.on("statechange",({state:a})=>{a==="preflight"||a==="acquiring"?U("starting"):a==="positioning"?U("scanning"):a==="captured"?U("captured"):a==="error"&&U("error")}),r.on("feedback",({key:a,reticle:d})=>n.emit("feedback",{key:a,reticle:d})),r.on("checks",a=>{n.emit("gate",{progress:a.p,quad:a.quad,frameWidth:a.frameWidth,frameHeight:a.frameHeight,...a.guide!==void 0?{guide:{detected:a.guide.detected,fill:a.guide.fill,offsetX:a.guide.offsetX??0,offsetY:a.guide.offsetY??0}}:{}});let d=a.ocr?.mrz;d!==void 0&&(d.state==="fallback"?H({state:"fallback",reason:d.reason}):d.state==="valid"?H({state:"valid",format:d.format}):d.state==="reading"?H({state:"reading",...d.format?{format:d.format}:{},...d.coach?{coach:d.coach}:{}}):H({state:"searching"}));let h=a.quad===null?0:At(a.quad,a.frameWidth,a.frameHeight);z=a.quad===null?null:{quad:a.quad,frameWidth:a.frameWidth,frameHeight:a.frameHeight},R({type:"report",report:{present:a.quad!==null&&a.plausible||a.guide?.detected===!0,ready:a.ready===!0,locking:a.p>=.5,areaFrac:h},at:s()})}),r.on("error",({kind:a,retryable:d,detail:h})=>n.emit("error",J(a,d,h))),r.on("artifacts",a=>{ct(a.keyframe,a.previewDataUrl,a.docRegion,a.liveMrz)}))},ne=()=>(L??(L=(async()=>{if(k){if(Se(),f===null){let r;try{r=await(t.createEngine??Ot)({...t.engineOptions??{},...B!==void 0?{guide:B}:{},video:e.video,format:u.format,side:m?"single":e.side??"recto",autoCapture:!1,...Q!==null?{ocr:Q}:{}})}catch(d){U("error"),n.emit("error",J("models",!0,{phase:"models",name:re(d)}));return}if(!k){r.destroy();return}f=r,p=m?"single":e.side??"recto",mt(r);let a=t.tickMs??500;a>0&&(N=setInterval(()=>R({type:"tick",at:s()}),a))}R({type:"clockRestart"}),C!==null&&C.liveMrzArm==="live"&&(F==="unsupported"||F==="off")&&H({state:"fallback",reason:F}),await f.start()}})().finally(()=>{L=null})),L);return{handle:{get state(){return b},on:(r,a)=>n.on(r,a),start:ne,retry:()=>{if(f===null&&c.phase==="result"){R({type:"retake"}),v=0,g=!1,ne();return}if(f!==null&&b!=="error"){R({type:"retake"}),v=0,g=!1,p=m?"single":null,f.rearm(m?"single":void 0);return}ne()},setSide:r=>{m||r==="single"||f!==null&&c.current===r&&p===r&&c.phase!=="reading"&&c.phase!=="result"||(c.current!==r&&(c={...c,current:r}),R({type:"clockRestart"}),c.phase!=="reading"&&c.phase!=="result"&&f!==null&&(p=r,f.rearm(r)))},shutter:De,focusAt:(r,a)=>{f?.focusAt?.(r,a)},setGuide:r=>{B=r,f?.setGuide?.(r)},setTorch:r=>{M=r,f?.setTorch(r),R({type:"tick",at:s()})},destroy:()=>{if(k&&f!==null&&b!=="done"){let r=ke();!te&&r!==void 0&&r.ticks>0&&Ce(r,"abandoned"),Me(r,void 0)}k=!1,we(),Q?.setEngine(null),X?.dispose(),X=null,n.clear()}},plan:u,setFlowState:r=>{(c.phase==="reading"||c.phase==="result")&&U(r==="done"&&c.phase!=="result"?"scanning":r)},settle:(r,a)=>{let d=r==="verso"?"verso":"recto";R(a.ok?{type:"readOk",side:d}:{type:"readFailed",side:d,issue:a.issue}),a.ok||j(d)},takeDeviceRead:r=>ye.get(r.image)?.value??null}}export{Ht as a,Yt as b,Vt as c,Qt as d,Kt as e,jt as f,He as g,ue as h,Qe as i,xt as j,vt as k,Jt as l,Ke as m,en as n,V as o,nt as p,rt as q,Tt as r,ot as s,fe as t,Lt as u,_t as v,kn as w,Cn as x,Bt as y};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as re,d as ne,e as B,f as se,g as oe}from"./chunk-7QZWBDI5.js";import{A as te,a as X}from"./chunk-
|
|
1
|
+
import{a as re,d as ne,e as B,f as se,g as oe}from"./chunk-7QZWBDI5.js";import{A as te,a as X}from"./chunk-FYU7J2DC.js";import{f as j,l as J}from"./chunk-CPUECYAJ.js";import{c as Z}from"./chunk-TSA6GHUG.js";import{c as ee,h as L}from"./chunk-FSSMUAKC.js";var ve=12e4,ie=13e4,ge=3e3,he=1200,D=Symbol.for("@sekyro/web.preload.v1");function h(){let e=globalThis;return e[D]??(e[D]=new Map),e[D]}function b(e){let r=(e??ee).replace(/\/+$/,"");return r===""?"/":r}function ae(e){let r=h(),n=r.get(e);return n===void 0&&(n={status:"idle",promise:null,scheduled:null,detectorPromise:null,detector:null,listeners:new Set},r.set(e,n)),n}function k(e,r){if(e.status!==r){e.status=r;for(let n of[...e.listeners])n(r)}}var K=e=>L({preferred:["blaze"],v3AssetBaseUrl:e,blazeInitTimeoutMs:ve}),H=K;function Te(e){H=e??K}function Oe(){for(let e of h().values())e.detector?.destroy();h().clear(),H=K}function Ce(){return typeof window<"u"&&typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"}function Se(){return navigator.connection?.saveData===!0}function Ee(e){let r=window;if(typeof r.requestIdleCallback=="function"){let s=r.requestIdleCallback(e,{timeout:ge});return()=>r.cancelIdleCallback?.(s)}let n=setTimeout(e,he);return()=>clearTimeout(n)}function ye(e,r){let n,s=new Promise(d=>{n=d}),m=!1,u=()=>{},c={promise:s,settle:d=>{m||(m=!0,u(),e.scheduled===c&&(e.scheduled=null),n(d))}};return e.scheduled=c,u=Ee(()=>{m||c.settle(U(e,r))}),s}function U(e,r){if((e.status==="loading"||e.status==="ready")&&e.promise!==null)return e.promise;k(e,"loading");let n=new Promise(d=>d(H(r)));e.detectorPromise=n;let s,m=new Promise((d,f)=>{s=setTimeout(()=>{n.then(C=>C.destroy(),()=>{}),f(new Error(`detector preload exceeded ${ie} ms`))},ie)}),c=Promise.race([n,m]).then(d=>e.detectorPromise!==n?(d.destroy(),e.status):(e.detector=d,k(e,"ready"),"ready"),d=>(e.detectorPromise===n&&(e.detectorPromise=null,e.detector=null,k(e,"failed"),console.warn("[@sekyro/web] face-detector preload failed:",d)),e.status)).finally(()=>clearTimeout(s));return e.promise=c,e.scheduled?.settle(c),c}function xe(e={}){if(!Ce())return Promise.resolve("idle");let r=b(e.assetBaseUrl),n=ae(r);return e.respectSaveData===!0&&Se()?Promise.resolve(n.status):(n.status==="loading"||n.status==="ready")&&n.promise!==null?n.promise:e.idle===!0?n.scheduled?.promise??ye(n,r):U(n,r)}function Fe(e){return h().get(b(e))?.status??"idle"}function Ie(e,r){let n=ae(b(r));return n.listeners.add(e),()=>{n.listeners.delete(e)}}function Be(e){let r=h().get(b(e));r!==void 0&&(r.scheduled?.settle("idle"),r.detector?.destroy(),r.detector=null,r.detectorPromise=null,r.promise=null,k(r,"idle"))}function Le(e){return{get tier(){return e.tier},get fallbackReason(){return e.fallbackReason},detect:(...r)=>e.detect(...r),destroy:()=>{}}}function de(e){let r=b(e),n=h().get(r);if(!(n===void 0||n.detector===null&&n.detectorPromise===null&&n.scheduled===null))return async()=>{n.scheduled!==null&&U(n,r);let s=n.promise;for(;n.detector===null&&s!==null&&(await s,n.promise!==s);)s=n.promise;return n.detector!==null?Le(n.detector):L({v3AssetBaseUrl:r})}}var be=new Set(["inuse","overconstrained","notfound"]),Me=[500,1500];function Ae(e){switch(e){case"fcv3.no_face":case"fcv3.center_face":case"fcv3.straighten":return"center";case"fcv3.come_closer":return"closer";case"fcv3.move_back":return"farther";case"fcv3.more_light":case"fcv3.too_bright":return"light";case"fcv3.hold_still":case"fcv3.steady_camera":return"still";case"fcv3.hold_upright":return"upright";case"fcv3.one_face":return"one_face";default:return null}}function Pe(e){switch(e){case"preflight":case"acquiring":return"starting";case"positioning":return"gating";default:return e}}function ue(e){switch(e){case"permission":case"notfound":case"inuse":case"insecure":case"unsupported":return e;case"backcamera":return"notfound";default:{let r=e;return"generic"}}}function we(e,r,n){if(n===void 0)return{kind:ue(e),retryable:r};let s=J(n.name);return{kind:ue(e),retryable:r,detail:{...s!==void 0?{name:s}:{},phase:n.phase,engineKind:e}}}var _e=new Set(["captured","uploading","checking"]);function De(e,r={},n,s=()=>"self",m=()=>{},u){let c=r.now??(()=>performance.now()),d=r.canChooseFacing??ne,f="user",C=se(),p=s(),l=re(),V=!j(),G=r.engineOptions,ce=G?.createDetector===void 0&&G?.createWorker===void 0?{createDetector:()=>{let t=de(e.assetBaseUrl);return t!==void 0?t():L({v3AssetBaseUrl:e.assetBaseUrl})}}:{},z={video:e.video,mode:V?"photo":"clip",rankKeyframes:n,facingMode:void 0,v3AssetBaseUrl:e.assetBaseUrl,screenRamp:()=>p==="self"&&l.count("ramp")>0?m():void 0,...r.engineOptions??{},...ce},a=r.createEngine?.(z)??new te(z),v="idle",M=null,A=0,R=!1,T="full",P=null,w=null,O=0,x=0,W=()=>{e.video.videoWidth>0&&e.video.videoHeight>0&&(O=e.video.videoWidth,x=e.video.videoHeight)},q=oe({enabled:e.keepScreenAwake!==!1}),S=t=>{v=t,q.setActive(t==="starting"||t==="gating"||t==="recording"),l.emit("state",t)},F=()=>l.emit("gate",{progress:A,hint:M,faceDetected:R}),I=()=>{let t=a.animations??"full";t!==T&&(T=t,l.emit("profile",{animations:T}))},g=0,_=null,le=r.schedule??((t,o)=>{let i=setTimeout(t,o);return()=>clearTimeout(i)}),E=()=>{_?.(),_=null},fe=(t,o)=>{if(y||!be.has(t)||o?.phase!=="acquiring")return!1;let i=Me[g];return i===void 0?!1:(g+=1,E(),_=le(()=>{_=null,y||a.retry()},i),!0)},pe=[a.on("statechange",({state:t})=>{if(t==="error")return;let o=Pe(t);o==="gating"&&(g=0),o==="starting"&&v!=="starting"&&(M=null,A=0,R=!1,P=null,w=null,O=0,x=0),S(o),I(),o==="recording"&&(W(),P=c(),M="hold",A=1,F())}),a.on("checks",t=>{W(),A=t.progress,R=t.factors.presence>0,F(),I()}),a.on("guidance",({key:t})=>{M=Ae(t),F()}),a.on("frozen",({previewDataUrl:t})=>{w=c(),l.emit("frozen",{previewDataUrl:t})}),a.on("ramp",t=>l.emit("ramp",t)),a.on("artifacts",t=>{if(v!=="captured")return;let o=Z(),i=t.clipStats,Q=i!==void 0?Math.round(i.durationMs):P!==null&&w!==null?Math.max(0,Math.round(w-P)):void 0,Y=i!==void 0&&i.frames>1&&i.durationMs>0?Math.round(i.frames*1e4/i.durationMs)/10:void 0;l.emit("captured",{keyframe:t.keyframe,...t.clip!==void 0?{clip:t.clip}:{},...t.clipMimeType!==void 0?{clipMime:t.clipMimeType}:{},width:e.video.videoWidth||O,height:e.video.videoHeight||x,...Q!==void 0?{clipMs:Q}:{},...i!==void 0?{clipFrames:i.frames}:{},...Y!==void 0?{fps:Y}:{},...t.clipRetakes!==void 0?{clipRetakes:t.clipRetakes}:{},...t.clipMimeType!==void 0?{codec:X(t.clipMimeType)}:{},captureChannel:o==="desktop"?"desktop":"mobile",formFactor:o,...V?{degraded:"NO_RECORDER"}:{},engine:"v3",facingMode:a.facingMode,mode:p,...t.timing,...t.screenRamp!==void 0?{screenRamp:t.screenRamp}:{},...t.provenance!==void 0?{provenance:t.provenance}:{}})}),a.on("error",({kind:t,retryable:o,detail:i})=>{t==="backcamera"&&me()||fe(t,i)||(S("error"),I(),l.emit("error",we(t,o,i)))})],N=!1;function me(){return y||N||p!=="assisted"||u===void 0||u.session()!=="choice"?!1:(N=!0,u.onModeChange("self"),p="self",f=B("self"),S("mode_switch"),a.restart(f),!0)}let $=async()=>u!==void 0&&u.session()==="choice"&&await d().catch(()=>!1),y=!1;return{handle:{get state(){return v},get captureMode(){return s()},get facingMode(){return a.facingMode??f},on:(t,o)=>l.on(t,o),start:t=>(p=s(),C.facing(p,e.facing),f=C.facing(p,t?.facing),E(),g=0,a.start({facingMode:f})),retry:()=>{E(),g=0,a.retry()},switchCamera:()=>C.refuseSwitch(s()),canSwitchCaptureMode:$,setCaptureMode:async t=>{if(t===s()||!await $()||y||_e.has(v)||u===void 0)return!1;u.onModeChange(t),p=t;let o=B(t);return f=o,v==="idle"||(S("mode_switch"),E(),g=0,a.restart(o)),!0},destroy:()=>{y=!0,E();for(let t of pe)t();q.setActive(!1),a.destroy(),l.clear()}},setFlowState:t=>{v!==t&&S(t)}}}function Ze(e){return De(e).handle}export{ve as a,ie as b,Te as c,Oe as d,xe as e,Fe as f,Ie as g,Be as h,de as i,Ae as j,Pe as k,ue as l,we as m,De as n,Ze as o};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as se,b as oe}from"./chunk-SX7TUC3V.js";import{b as J,c as ee}from"./chunk-W357WDNU.js";import{b as pe,c as he,d as me}from"./chunk-POIQGEZM.js";import{a as Z,c as Q,e as Y,g as j,h as R,k,m as $,n as re}from"./chunk-CPUECYAJ.js";import{b as x,c as fe,d as G,e as ve}from"./chunk-FPXL63KZ.js";import{c as ie,d as ne,e as ae}from"./chunk-U5TL63CG.js";import{a as W,c as q,d as z,e as X}from"./chunk-TSA6GHUG.js";import{d as te}from"./chunk-HMOOVRKA.js";import{e as le,f as ce,h as P,j as ue,l as de}from"./chunk-FSSMUAKC.js";var Oe=[...Z.filter(n=>n.startsWith("video/mp4")),"video/webm;codecs=h264","video/webm;codecs=avc1","video/webm;codecs=vp8","video/webm;codecs=vp9","video/webm"],ge=new Set;function Pe(n){let e=/(?:Chrome|Chromium)\/(\d+)\./.exec(n??"");return e?Number(e[1]):null}function be(n=xe(),e=globalThis.navigator?.userAgent){if(n===void 0)return"";let t=Pe(e)===126;for(let r of Oe)if(!(ge.has(r)||t&&r.startsWith("video/mp4")))try{if(n(r))return r}catch{}return""}function L(n){n!==""&&ge.add(n)}function ye(n){return n.replace(/^video\/x-matroska/i,"video/webm")}function lt(n){let e=/codecs=["']?([^,;"']+)/i.exec(n);return e?e[1].trim():n.split(";")[0].trim()}function xe(){let n=globalThis.MediaRecorder;return n&&typeof n.isTypeSupported=="function"?e=>n.isTypeSupported(e):void 0}var V=2500,Ge=1e3,Le=1500,Te=25e5,Fe=100,Ve=700,Ne=20,Ue=1500,F=null;function He(){return F??(F=import("./clip-inspect-DLJXVKV6.js").catch(n=>{throw F=null,n})),F.catch(()=>null)}var T=class extends Error{constructor(e,t){super(t??e),this.kind=e}},Ke=100;function N(n,e){return n.stats===void 0?!1:n.stats===null?!0:n.stats.durationMs<e-Ke}function Ee(n,e){return n.stats?e.stats?n.stats.durationMs>e.stats.durationMs:!0:!1}var A=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,i=V,a){let s=be(),o=He();return this.recordRaw(e,t,r,i,a,s).then(c=>Be(c,o),c=>{throw c instanceof T&&(c.requestedMimeType=s),c})}recordRaw(e,t,r,i,a,s){return this.recorder&&!this.settled?Promise.reject(new T("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:Te}:{videoBitsPerSecond:Te})}catch{try{l=new MediaRecorder(e)}catch{c(new T("unsupported"));return}}this.recorder=l;let d=h=>{this.settled||(this.settled=!0,this.clearTimers(),h())},u=()=>d(()=>{let h=ye(l.mimeType||s||Q),b=new Blob(this.chunks,{type:h});if(b.size===0){c(new T("generic","empty clip"));return}if(R(b)){c(new T("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>j&&d(()=>{try{l.state!=="inactive"&&l.stop()}catch{}c(new T("cliptoolarge"))}))},l.onstop=u,l.onerror=()=>d(()=>c(new T("generic")));let p=this.now();if(r!==void 0||a!==void 0){let h=!1;l.onstart=()=>{if(!(h||this.settled)&&(h=!0,p=this.now(),r!==void 0))try{r()}catch{}}}try{l.start(Ge)}catch{d(()=>c(new T("generic")));return}let m=()=>{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,Le)}else u()},f=this.now();if(a===void 0){this.hardStopTimer=setTimeout(m,i);return}let g=null,M=!1;this.hardStopTimer=setTimeout(m,i+Ve),this.pollTimer=setInterval(()=>{if(this.settled||M)return;let h=null;try{h=a.latest()}catch{h=null}let b=h?.presentationTimeMs;b!==void 0&&Number.isFinite(b)&&b>=p&&g===null&&(g=b);let S=g!==null&&b!==void 0&&b-g>=i,I=g===null&&this.now()-f>=i;if(!(!S&&!I)){if(M=!0,this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=null,I){m();return}this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.hardStopTimer=setTimeout(m,Fe)}},Ne)}))}stop(e){this.clearTimers();let t=this.recorder;if(t&&t.state!=="inactive")try{t.stop()}catch{}this.recorder=null,(e??this.stream)?.getTracks().forEach(i=>i.stop()),this.stream=null}};async function Be(n,e){let t,r=new Promise(l=>{t=setTimeout(()=>l(null),Ue)}),i=await Promise.race([e,r]);if(clearTimeout(t),i===null)return n;let a;try{a=await i.blobBytes(n.blob)}catch{return{...n,stats:null}}let s=i.inspectClipBytes(a);if(s?.container!=="webm")return{...n,stats:s};let o=i.withWebmDuration(a,s.durationMs);if(o===null)return{...n,stats:s};let c=i.inspectClipBytes(o);return c===null||c.frames!==s.frames||c.durationMs!==s.durationMs?{...n,stats:s}:{...n,blob:new Blob([o],{type:n.blob.type}),stats:s}}function Me(n,e,t=.92){return new Promise((r,i)=>{let a=n.videoWidth,s=n.videoHeight;if(!a||!s){i(new Error("video-not-ready"));return}let o=e.getContext("2d");if(!o){i(new Error("no-2d-context"));return}e.width=a,e.height=s,o.scale(-1,1),o.drawImage(n,-a,0),e.toBlob(c=>c?r(c):i(new Error("empty-keyframe")),"image/jpeg",t)})}var D=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 We=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}),C=n=>Math.min(1,Math.max(0,n)),_=class{constructor(e={}){this.p=0;this.lastTickAt=null;this.lastCenter=null;this.velocityEma=0;this.qWindow=[];this.lastSizeDirection="ideal";this.t={...We,...e}}reset(){this.p=0,this.lastTickAt=null,this.lastCenter=null,this.velocityEma=0,this.qWindow=[],this.lastSizeDirection="ideal"}tick(e){let{observation:t,quality:r,timestampMs:i}=e,a=this.lastTickAt===null?0:Math.max(0,(i-this.lastTickAt)/1e3);this.lastTickAt=i;let s={presence:0,single:1,centering:0,size:0,pose:0,sharpness:C(r.sharpness),exposure:C(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,i)}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=C(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:i,q:o}),this.qWindow=this.qWindow.filter(d=>d.at>=i-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((p,m)=>m!==u)}let l=this.p>=1&&c.every(d=>d>=this.t.Q_GOOD);return{at:i,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:i}=e,a={x:t.frameWidth/2,y:t.frameHeight/2},s=Math.min(t.frameWidth,t.frameHeight),o=i!==void 0?{x:(i.left.x+i.right.x)/2,y:(i.left.y+i.right.y)/2}:{x:r.x+r.width/2,y:r.y+r.height/2-this.t.BOX_EYE_OFFSET_FACTOR*r.height},c=i!==void 0?Math.hypot(i.right.x-i.left.x,i.right.y-i.left.y):this.t.IOD_BOX_PROXY_FACTOR*r.width,l=Math.hypot(o.x-a.x,o.y-a.y),d=c<=0?0:1-C(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 p;u<this.t.SIZE_HARD_MIN||u>this.t.SIZE_HARD_MAX?p=0:u<this.t.SIZE_IDEAL_MIN?p=(u-this.t.SIZE_HARD_MIN)/(this.t.SIZE_IDEAL_MIN-this.t.SIZE_HARD_MIN):u>this.t.SIZE_IDEAL_MAX?p=(this.t.SIZE_HARD_MAX-u)/(this.t.SIZE_HARD_MAX-this.t.SIZE_IDEAL_MAX):p=1;let m=1;if(i!==void 0){let f=Math.abs(Math.atan2(i.right.y-i.left.y,i.right.x-i.left.x))*180/Math.PI;m=1-C(f/this.t.ROLL_MAX_DEG)}return{center:o,iod:c,centering:d,size:p,pose:m}}motionOf(e,t,r){let i=this.lastCenter;if(this.lastCenter={...e,at:r},i===null||t<=0)return 1;let a=(r-i.at)/1e3;if(a<=0)return 1;let s=Math.hypot(e.x-i.x,e.y-i.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-C(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 i=[["size",this.sizeGuidance()],["centering","fcv3.center_face"],["pose","fcv3.straighten"],["exposure",this.exposureGuidance(t)],["sharpness","fcv3.steady_camera"],["motion","fcv3.hold_still"]],a=i[0];for(let s of i)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=(x[0]+x[1])/2;return e.meanLuma<t?"fcv3.more_light":"fcv3.too_bright"}};var qe=["single","size","centering","pose","exposure","sharpness","motion"];function ze(n){if(n.accepted)return null;if(n.factors.presence<=0)return"no_face";let e="single";for(let t of qe)n.factors[t]<n.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 i=this.blocked[r]??{count:0,ms:0};i.count+=1,i.ms+=t,this.blocked[r]=i}summary(){let e={};for(let[t,r]of Object.entries(this.blocked))e[t]={count:r.count,ms:Math.round(r.ms)};return{blocked:e,acceptedMs:Math.round(this.acceptedMs),ticks:this.ticks}}};var Xe=["obs","manycam","virtual","snap camera","xsplit","droidcam","iriun","camo","fake_device","fake-capture-device"],Ze=[/^(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 Qe(n){let e=(n??"").trim().toLowerCase();return e.length===0?"unknown":Xe.some(t=>e.includes(t))?"known_virtual":Ze.some(t=>t.test(e))?"platform":"unknown"}function Ce(n){if(typeof n!="function")return!1;try{return/\{\s*\[native code\]\s*\}\s*$/.test(Function.prototype.toString.call(n))}catch{return!1}}function Ye(n=globalThis){return Ce(n.navigator?.mediaDevices?.getUserMedia)&&Ce(n.MediaStreamTrack?.prototype?.getSettings)}async function je(n,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(n)));return Array.from(r.subarray(0,8),i=>i.toString(16).padStart(2,"0")).join("")}catch{return}}async function Se(n,e=globalThis){let t={};try{t=typeof n.getSettings=="function"?n.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 i;try{i=n.label}catch{i=void 0}return{trackSettings:r,capabilitiesPresent:typeof n.getCapabilities=="function",labelClass:Qe(i),prototypesIntact:Ye(e)}}var U=n=>Math.round(n*100)/100;function ke(n){let e=n,t=typeof e?.requestVideoFrameCallback=="function",r=null,i=null,a=0,s=0,o=0,c=0,l=0,d=0,u=()=>{!t||e?.requestVideoFrameCallback===void 0||(r=e.requestVideoFrameCallback((p,m)=>{if(r=null,!t)return;let f=m.presentationTime;if(i!==null){let g=f-i.presentationTimeMs;s+=1;let M=g-o;o+=M/s,c+=M*(g-o)}typeof m.captureTime=="number"&&Number.isFinite(m.captureTime)&&(l+=f-m.captureTime,d+=1),a+=1,i={mediaTimeMs:m.mediaTime*1e3,presentationTimeMs:f},u()}))};return u(),{latest:()=>i,stats:()=>({n:a,meanGapMs:s===0?0:U(o),stdGapMs:s<2?0:U(Math.sqrt(c/(s-1))),captureLatencyMs:d===0?null:U(l/d)}),stop:()=>{t&&(t=!1,r!==null&&e?.cancelVideoFrameCallback?.(r),r=null)}}}function _e(n,e,t){return{...n,rvfc:e,rampPainter:t}}var $e=1e3,H="fcv3.hold_upright",Je=200,K=4,et=600,tt=1e3,we={sharpness:1,exposure:1,meanLuma:128};function rt(n,e){return e.width=n.videoWidth,e.height=n.videoHeight,e.getContext("2d").drawImage(n,0,0),new Promise((t,r)=>e.toBlob(i=>i?t(i):r(new Error("empty-keyframe")),"image/jpeg",.92))}function it(){return q()==="phone"}var Ie=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.openEnvironment=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??it)(),this.setState("preflight");let r=Y();if(r!=="OK"){this.fail(r==="INSECURE_CONTEXT"?"insecure":"unsupported",{phase:"preflight"});return}this.setState("acquiring");let i=t.getUserMedia??(l=>navigator.mediaDevices.getUserMedia(l)),a;this.cameraRequestedAt=this.now();try{let{facingMode:l,...d}=W(z(),this.facing).video;a=await oe(this.facing,d,{getUserMedia:i,enumerateDevices:st(t)})}catch(l){if(e!==this.attempt)return;if(l instanceof se){this.fail("backcamera",{phase:"acquiring",name:k(l)});return}this.fail($(l),{phase:"acquiring",name:k(l)});return}if(te(a),re(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:Se(s).catch(()=>null),this.openEnvironment=s===void 0?null:J(s).catch(()=>({})),this.facing=X(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&&ue()?async()=>{try{return await de.create(t.createWorker(),l)}catch{return P(l)}}:()=>P(l)),u;try{u=await d()}catch(p){e===this.attempt&&this.fail("models",{phase:"models",name:k(p)},p instanceof le?p.fallbackReason:at(p));return}if(e!==this.attempt){u.destroy();return}this.detector=u,this.options.telemetry?.({type:"detector",tier:u.tier,fallbackReason:u.fallbackReason})}let o=pe(),c=t.deviceClass??he(o);this.profiler=new me(c),this.options.telemetry?.({type:"profile",staticClass:c,activeClass:this.profiler.deviceClass,simd:o.simd}),this.gate=new _(t.thresholds??{}),this.blockStats=new w,this.lastGateSnapshotAt=this.now(),t.rankKeyframes?.()&&import("./keyframe-rank-YAJLYJYF.js").then(l=>B=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 i=this.scheduler.stats();this.carriedDegrade+=i.degradeCount,i.meanDetectMs>0&&this.carriedMeans.push(i.meanDetectMs),this.scheduler.stop()}let r=new D({cadenceHz:t.profile.cadenceHz,video:this.options.video,now:this.options.now,run:()=>this.detectTick(e)});this.scheduler=r,r.start()}async detectTick(e){let{detector:t,gate:r,profiler:i}=this,a=this.options.video;if(e!==this.attempt||t===null||r===null||i===null||this.fired||a.videoWidth===0)return;if(this.isLandscape()){this.holdUpright(e);return}let s=i.deviceClass,o=this.now(),c=this.options.makeSnapshot?.(a,i.profile.inputWidth)??this.defaultSnapshot(a,i.profile.inputWidth),l=null;try{l=await t.detect(c,a.videoWidth,a.videoHeight)}catch{l=null}if(e!==this.attempt||this.fired)return;i.record(this.now()-o),i.deviceClass!==s&&this.startScheduler(e);let d=l===null?we: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>=$e&&(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 i=r?.stats()??{degradeCount:0,meanDetectMs:0},a=[...this.carriedMeans,...i.meanDetectMs>0?[i.meanDetectMs]:[]];t.telemetry?.({type:"fired",timeToGateMs:this.now()-this.positioningStartedAt,degradeCount:this.carriedDegrade+i.degradeCount,meanDetectMs:a.length===0?0:a.reduce((y,v)=>y+v,0)/a.length});let s=t.mode??"clip",o=t.rankKeyframes?.()&&B?B.default(this,e).catch(()=>this.collectKeyframes(e)):this.collectKeyframes(e);if(s==="photo"){let y=this.watchRotation(e,null),v=await o;if(y(),e!==this.attempt)return;if(v===null){this.fail("generic",{phase:"keyframes"});return}let O=await this.provenance({n:0,meanGapMs:0,stdGapMs:0,captureLatencyMs:null},!1);if(e!==this.attempt)return;this.finishCapture({keyframe:v.blob,previewDataUrl:v.previewDataUrl,...O});return}this.setState("recording");let c=this.stream;if(c===null){this.fail("generic",{phase:"recording"});return}let l=t.screenRamp?.(),d=ie(l),u=null;o.then(y=>{u=y},()=>{});let p=()=>{e===this.attempt&&u!==null&&this.emit("frozen",{previewDataUrl:u.previewDataUrl})},m=ne(l,V),f=null,g,M=0;try{let y=this.recordTake(e,c,l,m,void 0).then(E=>E,E=>({failed:E})),[v,O]=await Promise.all([y,o]);if(g=O,e!==this.attempt)return;if("failed"in v){if(v.failed.kind==="cliptoolarge")throw v.failed;L(v.failed.requestedMimeType??"")}else f=v,N(v.clip,m)?v.clip.stats===null&&L(v.clip.requestedMimeType??""):p();if(f===null||N(f.clip,m)){M=1,t.telemetry?.({type:"clip_retake",reason:f===null?"error":f.clip.stats===null?"unreadable":"short"});let E=null;try{E=await this.recordTake(e,c,l,m,p)}catch(De){if(f===null)throw De}if(e!==this.attempt)return;E!==null&&(f===null||Ee(E.clip,f.clip))&&(f=E),E===null&&p()}}catch(y){if(e!==this.attempt)return;let v=y.kind;this.fail(v==="cliptoolarge"?"cliptoolarge":"recorder",{phase:"recording",name:k(y)});return}if(f===null){this.fail("recorder",{phase:"recording"});return}let{clip:h,rvfc:b,report:S,watched:I}=f;if(R(h.blob)){this.fail("cliptoolarge",{phase:"recording"});return}if(g===null){this.fail("generic",{phase:"keyframes"});return}let Ae=await this.provenance(b,d,I);e===this.attempt&&this.finishCapture({clip:h.blob,clipMimeType:h.mimeType,...h.stats?{clipStats:h.stats}:{},clipRetakes:M,keyframe:g.blob,previewDataUrl:g.previewDataUrl,...S!==void 0&&S.rendered.length>0?{screenRamp:S}:{},...Ae})}async recordTake(e,t,r,i,a){let s=this.options.createRecorder?.()??new A({now:()=>this.now()}),o=ke(this.options.video),c=ae(r,{paint:p=>{(p===null||e===this.attempt)&&this.emit("ramp",{colour:p})},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),u=ee();try{return{clip:await s.record(t,a,()=>c.started(this.now()),i,o),rvfc:o.stats(),report:c.report(),watched:u.stop()}}finally{u.stop(),d(),l()}}async provenance(e,t,r={}){let i=this.trackProvenance;if(i===null)return{};let a,s=new Promise(d=>{a=setTimeout(()=>d(null),tt)}),o=await Promise.race([i,s]),c=o===null?null:await Promise.race([this.openEnvironment,s]);if(clearTimeout(a),o===null)return{};let l={...c,...r};return{provenance:{..._e(o,e,t),...Object.keys(l).length>0?{env:l}:{}}}}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!==H&&(this.lastGuidanceKey=H,this.emit("guidance",{key:H}))}watchRotation(e,t){if(!this.uprightGuard)return()=>{};let r=this.options.video,i=()=>{if(e!==this.attempt||t!==null&&this.stateValue!=="recording"){o();return}r.videoWidth>0&&this.isLandscape()&&(o(),this.abortRecording(e,t))},a=setInterval(i,Je);r.addEventListener?.("resize",i);let s=!1;function o(){s||(s=!0,clearInterval(a),r.removeEventListener?.("resize",i))}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 _(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=et/(K-1),i=null;for(let a=0;a<K;a+=1){if(e!==this.attempt)return i;try{let s=await t(this.options.video);(i===null||s.sharpness>i.sharpness)&&(i=s)}catch{}a<K-1&&await nt(r)}return i}finishCapture(e){this.stopTracks(),this.setState("captured");let t=this.captureTiming();this.emit("artifacts",t===void 0?e:{...e,timing:t})}captureTiming(){let e={},t=(r,i,a)=>{i!==null&&a!==null&&(e[r]=Math.max(0,Math.round(a-i)))};return t("cameraReadyMs",this.cameraRequestedAt,this.cameraReadyAt),t("faceAcquireMs",this.cameraReadyAt,this.faceAcquiredAt),t("captureMs",this.faceAcquiredAt,this.captureCompleteAt),Object.keys(e).length>0?e:void 0}async defaultKeyframe(e){let t=document.createElement("canvas"),r=await(this.facing==="user"?Me:rt)(e,t),i=t.toDataURL("image/jpeg",.92);return{blob:r,previewDataUrl:i,sharpness:this.centerSharpness(e)}}defaultSnapshot(e,t){try{let r=this.snapshotCanvas??document.createElement("canvas"),i=t/Math.max(1,e.videoWidth),a=Math.max(1,Math.round(e.videoWidth*i)),s=Math.max(1,Math.round(e.videoHeight*i)),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=Re(e,t,96);return r===null?we:{sharpness:G(r),exposure:ve(r),meanLuma:fe(r)}}centerSharpness(e){let t=ce(e),r=Re(e,{x:t.width*.25,y:t.height*.25,width:t.width*.5,height:t.height*.5},96);return r===null?0:G(r)}teardownAttempt(){this.scheduler?.stop(),this.scheduler=null,this.reportGate(!0),this.gate=null,this.ramp?.stop(),this.ramp=null,this.stopTracks()}reportGate(e){let t=this.blockStats,r=this.profiler;if(t===null||r===null)return;let i=t.summary();e&&(this.blockStats=null),i.ticks!==0&&this.options.telemetry?.({type:"gate",final:e,activeClass:r.deviceClass,cadenceHz:r.profile.cadenceHz,...i})}stopTracks(){if(this.stream!==null){for(let e of this.stream.getTracks())e.stop();this.stream=null}}fail(e,t,r){this.scheduler?.stop(),this.reportGate(!0),this.stopTracks(),this.setState("error"),this.options.telemetry?.({type:"error",kind:e,fallbackReason:r});let{phase:i,name:a}=t;this.emit("error",{kind:e,retryable:e!=="insecure"&&e!=="unsupported",detail:a===void 0?{phase:i}:{phase:i,name:a}})}setState(e){this.stateValue=e,this.emit("statechange",{state:e})}now(){return this.options.now?.()??performance.now()}},B;function nt(n){return new Promise(e=>setTimeout(e,n))}function at(n){return n instanceof Error?n.message:String(n)}function Re(n,e,t){try{let r=document.createElement("canvas"),i=t/Math.max(1,e.width);r.width=Math.max(1,Math.round(e.width*i)),r.height=Math.max(1,Math.round(e.height*i));let a=r.getContext("2d");return a===null?null:(a.drawImage(n,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 st(n){if(n.enumerateDevices!==void 0)return n.enumerateDevices;if(n.getUserMedia===void 0&&!(typeof navigator>"u"||typeof navigator.mediaDevices?.enumerateDevices!="function"))return()=>navigator.mediaDevices.enumerateDevices()}export{lt as a,V as b,Ge as c,Le as d,Te as e,Fe as f,Ve as g,Ne as h,Ue as i,T as j,Ke as k,N as l,Ee as m,A as n,Me as o,D as p,We as q,_ as r,ze as s,w as t,$e as u,H as v,Je as w,K as x,et as y,tt as z,Ie as A};
|
|
1
|
+
import{a as se,b as oe}from"./chunk-SX7TUC3V.js";import{b as J,c as ee}from"./chunk-W357WDNU.js";import{b as pe,c as he,d as me}from"./chunk-POIQGEZM.js";import{a as Z,c as Q,e as Y,g as j,h as R,k,m as $,n as re}from"./chunk-CPUECYAJ.js";import{b as x,c as fe,d as G,e as ve}from"./chunk-FPXL63KZ.js";import{c as ie,d as ne,e as ae}from"./chunk-U5TL63CG.js";import{a as W,c as q,d as z,e as X}from"./chunk-TSA6GHUG.js";import{d as te}from"./chunk-22AW4NJD.js";import{e as le,f as ce,h as P,j as ue,l as de}from"./chunk-FSSMUAKC.js";var Oe=[...Z.filter(n=>n.startsWith("video/mp4")),"video/webm;codecs=h264","video/webm;codecs=avc1","video/webm;codecs=vp8","video/webm;codecs=vp9","video/webm"],ge=new Set;function Pe(n){let e=/(?:Chrome|Chromium)\/(\d+)\./.exec(n??"");return e?Number(e[1]):null}function be(n=xe(),e=globalThis.navigator?.userAgent){if(n===void 0)return"";let t=Pe(e)===126;for(let r of Oe)if(!(ge.has(r)||t&&r.startsWith("video/mp4")))try{if(n(r))return r}catch{}return""}function L(n){n!==""&&ge.add(n)}function ye(n){return n.replace(/^video\/x-matroska/i,"video/webm")}function lt(n){let e=/codecs=["']?([^,;"']+)/i.exec(n);return e?e[1].trim():n.split(";")[0].trim()}function xe(){let n=globalThis.MediaRecorder;return n&&typeof n.isTypeSupported=="function"?e=>n.isTypeSupported(e):void 0}var V=2500,Ge=1e3,Le=1500,Te=25e5,Fe=100,Ve=700,Ne=20,Ue=1500,F=null;function He(){return F??(F=import("./clip-inspect-DLJXVKV6.js").catch(n=>{throw F=null,n})),F.catch(()=>null)}var T=class extends Error{constructor(e,t){super(t??e),this.kind=e}},Ke=100;function N(n,e){return n.stats===void 0?!1:n.stats===null?!0:n.stats.durationMs<e-Ke}function Ee(n,e){return n.stats?e.stats?n.stats.durationMs>e.stats.durationMs:!0:!1}var A=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,i=V,a){let s=be(),o=He();return this.recordRaw(e,t,r,i,a,s).then(c=>Be(c,o),c=>{throw c instanceof T&&(c.requestedMimeType=s),c})}recordRaw(e,t,r,i,a,s){return this.recorder&&!this.settled?Promise.reject(new T("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:Te}:{videoBitsPerSecond:Te})}catch{try{l=new MediaRecorder(e)}catch{c(new T("unsupported"));return}}this.recorder=l;let d=h=>{this.settled||(this.settled=!0,this.clearTimers(),h())},u=()=>d(()=>{let h=ye(l.mimeType||s||Q),b=new Blob(this.chunks,{type:h});if(b.size===0){c(new T("generic","empty clip"));return}if(R(b)){c(new T("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>j&&d(()=>{try{l.state!=="inactive"&&l.stop()}catch{}c(new T("cliptoolarge"))}))},l.onstop=u,l.onerror=()=>d(()=>c(new T("generic")));let p=this.now();if(r!==void 0||a!==void 0){let h=!1;l.onstart=()=>{if(!(h||this.settled)&&(h=!0,p=this.now(),r!==void 0))try{r()}catch{}}}try{l.start(Ge)}catch{d(()=>c(new T("generic")));return}let m=()=>{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,Le)}else u()},f=this.now();if(a===void 0){this.hardStopTimer=setTimeout(m,i);return}let g=null,M=!1;this.hardStopTimer=setTimeout(m,i+Ve),this.pollTimer=setInterval(()=>{if(this.settled||M)return;let h=null;try{h=a.latest()}catch{h=null}let b=h?.presentationTimeMs;b!==void 0&&Number.isFinite(b)&&b>=p&&g===null&&(g=b);let S=g!==null&&b!==void 0&&b-g>=i,I=g===null&&this.now()-f>=i;if(!(!S&&!I)){if(M=!0,this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=null,I){m();return}this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.hardStopTimer=setTimeout(m,Fe)}},Ne)}))}stop(e){this.clearTimers();let t=this.recorder;if(t&&t.state!=="inactive")try{t.stop()}catch{}this.recorder=null,(e??this.stream)?.getTracks().forEach(i=>i.stop()),this.stream=null}};async function Be(n,e){let t,r=new Promise(l=>{t=setTimeout(()=>l(null),Ue)}),i=await Promise.race([e,r]);if(clearTimeout(t),i===null)return n;let a;try{a=await i.blobBytes(n.blob)}catch{return{...n,stats:null}}let s=i.inspectClipBytes(a);if(s?.container!=="webm")return{...n,stats:s};let o=i.withWebmDuration(a,s.durationMs);if(o===null)return{...n,stats:s};let c=i.inspectClipBytes(o);return c===null||c.frames!==s.frames||c.durationMs!==s.durationMs?{...n,stats:s}:{...n,blob:new Blob([o],{type:n.blob.type}),stats:s}}function Me(n,e,t=.92){return new Promise((r,i)=>{let a=n.videoWidth,s=n.videoHeight;if(!a||!s){i(new Error("video-not-ready"));return}let o=e.getContext("2d");if(!o){i(new Error("no-2d-context"));return}e.width=a,e.height=s,o.scale(-1,1),o.drawImage(n,-a,0),e.toBlob(c=>c?r(c):i(new Error("empty-keyframe")),"image/jpeg",t)})}var D=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 We=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}),C=n=>Math.min(1,Math.max(0,n)),_=class{constructor(e={}){this.p=0;this.lastTickAt=null;this.lastCenter=null;this.velocityEma=0;this.qWindow=[];this.lastSizeDirection="ideal";this.t={...We,...e}}reset(){this.p=0,this.lastTickAt=null,this.lastCenter=null,this.velocityEma=0,this.qWindow=[],this.lastSizeDirection="ideal"}tick(e){let{observation:t,quality:r,timestampMs:i}=e,a=this.lastTickAt===null?0:Math.max(0,(i-this.lastTickAt)/1e3);this.lastTickAt=i;let s={presence:0,single:1,centering:0,size:0,pose:0,sharpness:C(r.sharpness),exposure:C(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,i)}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=C(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:i,q:o}),this.qWindow=this.qWindow.filter(d=>d.at>=i-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((p,m)=>m!==u)}let l=this.p>=1&&c.every(d=>d>=this.t.Q_GOOD);return{at:i,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:i}=e,a={x:t.frameWidth/2,y:t.frameHeight/2},s=Math.min(t.frameWidth,t.frameHeight),o=i!==void 0?{x:(i.left.x+i.right.x)/2,y:(i.left.y+i.right.y)/2}:{x:r.x+r.width/2,y:r.y+r.height/2-this.t.BOX_EYE_OFFSET_FACTOR*r.height},c=i!==void 0?Math.hypot(i.right.x-i.left.x,i.right.y-i.left.y):this.t.IOD_BOX_PROXY_FACTOR*r.width,l=Math.hypot(o.x-a.x,o.y-a.y),d=c<=0?0:1-C(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 p;u<this.t.SIZE_HARD_MIN||u>this.t.SIZE_HARD_MAX?p=0:u<this.t.SIZE_IDEAL_MIN?p=(u-this.t.SIZE_HARD_MIN)/(this.t.SIZE_IDEAL_MIN-this.t.SIZE_HARD_MIN):u>this.t.SIZE_IDEAL_MAX?p=(this.t.SIZE_HARD_MAX-u)/(this.t.SIZE_HARD_MAX-this.t.SIZE_IDEAL_MAX):p=1;let m=1;if(i!==void 0){let f=Math.abs(Math.atan2(i.right.y-i.left.y,i.right.x-i.left.x))*180/Math.PI;m=1-C(f/this.t.ROLL_MAX_DEG)}return{center:o,iod:c,centering:d,size:p,pose:m}}motionOf(e,t,r){let i=this.lastCenter;if(this.lastCenter={...e,at:r},i===null||t<=0)return 1;let a=(r-i.at)/1e3;if(a<=0)return 1;let s=Math.hypot(e.x-i.x,e.y-i.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-C(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 i=[["size",this.sizeGuidance()],["centering","fcv3.center_face"],["pose","fcv3.straighten"],["exposure",this.exposureGuidance(t)],["sharpness","fcv3.steady_camera"],["motion","fcv3.hold_still"]],a=i[0];for(let s of i)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=(x[0]+x[1])/2;return e.meanLuma<t?"fcv3.more_light":"fcv3.too_bright"}};var qe=["single","size","centering","pose","exposure","sharpness","motion"];function ze(n){if(n.accepted)return null;if(n.factors.presence<=0)return"no_face";let e="single";for(let t of qe)n.factors[t]<n.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 i=this.blocked[r]??{count:0,ms:0};i.count+=1,i.ms+=t,this.blocked[r]=i}summary(){let e={};for(let[t,r]of Object.entries(this.blocked))e[t]={count:r.count,ms:Math.round(r.ms)};return{blocked:e,acceptedMs:Math.round(this.acceptedMs),ticks:this.ticks}}};var Xe=["obs","manycam","virtual","snap camera","xsplit","droidcam","iriun","camo","fake_device","fake-capture-device"],Ze=[/^(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 Qe(n){let e=(n??"").trim().toLowerCase();return e.length===0?"unknown":Xe.some(t=>e.includes(t))?"known_virtual":Ze.some(t=>t.test(e))?"platform":"unknown"}function Ce(n){if(typeof n!="function")return!1;try{return/\{\s*\[native code\]\s*\}\s*$/.test(Function.prototype.toString.call(n))}catch{return!1}}function Ye(n=globalThis){return Ce(n.navigator?.mediaDevices?.getUserMedia)&&Ce(n.MediaStreamTrack?.prototype?.getSettings)}async function je(n,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(n)));return Array.from(r.subarray(0,8),i=>i.toString(16).padStart(2,"0")).join("")}catch{return}}async function Se(n,e=globalThis){let t={};try{t=typeof n.getSettings=="function"?n.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 i;try{i=n.label}catch{i=void 0}return{trackSettings:r,capabilitiesPresent:typeof n.getCapabilities=="function",labelClass:Qe(i),prototypesIntact:Ye(e)}}var U=n=>Math.round(n*100)/100;function ke(n){let e=n,t=typeof e?.requestVideoFrameCallback=="function",r=null,i=null,a=0,s=0,o=0,c=0,l=0,d=0,u=()=>{!t||e?.requestVideoFrameCallback===void 0||(r=e.requestVideoFrameCallback((p,m)=>{if(r=null,!t)return;let f=m.presentationTime;if(i!==null){let g=f-i.presentationTimeMs;s+=1;let M=g-o;o+=M/s,c+=M*(g-o)}typeof m.captureTime=="number"&&Number.isFinite(m.captureTime)&&(l+=f-m.captureTime,d+=1),a+=1,i={mediaTimeMs:m.mediaTime*1e3,presentationTimeMs:f},u()}))};return u(),{latest:()=>i,stats:()=>({n:a,meanGapMs:s===0?0:U(o),stdGapMs:s<2?0:U(Math.sqrt(c/(s-1))),captureLatencyMs:d===0?null:U(l/d)}),stop:()=>{t&&(t=!1,r!==null&&e?.cancelVideoFrameCallback?.(r),r=null)}}}function _e(n,e,t){return{...n,rvfc:e,rampPainter:t}}var $e=1e3,H="fcv3.hold_upright",Je=200,K=4,et=600,tt=1e3,we={sharpness:1,exposure:1,meanLuma:128};function rt(n,e){return e.width=n.videoWidth,e.height=n.videoHeight,e.getContext("2d").drawImage(n,0,0),new Promise((t,r)=>e.toBlob(i=>i?t(i):r(new Error("empty-keyframe")),"image/jpeg",.92))}function it(){return q()==="phone"}var Ie=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.openEnvironment=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??it)(),this.setState("preflight");let r=Y();if(r!=="OK"){this.fail(r==="INSECURE_CONTEXT"?"insecure":"unsupported",{phase:"preflight"});return}this.setState("acquiring");let i=t.getUserMedia??(l=>navigator.mediaDevices.getUserMedia(l)),a;this.cameraRequestedAt=this.now();try{let{facingMode:l,...d}=W(z(),this.facing).video;a=await oe(this.facing,d,{getUserMedia:i,enumerateDevices:st(t)})}catch(l){if(e!==this.attempt)return;if(l instanceof se){this.fail("backcamera",{phase:"acquiring",name:k(l)});return}this.fail($(l),{phase:"acquiring",name:k(l)});return}if(te(a),re(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:Se(s).catch(()=>null),this.openEnvironment=s===void 0?null:J(s).catch(()=>({})),this.facing=X(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&&ue()?async()=>{try{return await de.create(t.createWorker(),l)}catch{return P(l)}}:()=>P(l)),u;try{u=await d()}catch(p){e===this.attempt&&this.fail("models",{phase:"models",name:k(p)},p instanceof le?p.fallbackReason:at(p));return}if(e!==this.attempt){u.destroy();return}this.detector=u,this.options.telemetry?.({type:"detector",tier:u.tier,fallbackReason:u.fallbackReason})}let o=pe(),c=t.deviceClass??he(o);this.profiler=new me(c),this.options.telemetry?.({type:"profile",staticClass:c,activeClass:this.profiler.deviceClass,simd:o.simd}),this.gate=new _(t.thresholds??{}),this.blockStats=new w,this.lastGateSnapshotAt=this.now(),t.rankKeyframes?.()&&import("./keyframe-rank-YAJLYJYF.js").then(l=>B=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 i=this.scheduler.stats();this.carriedDegrade+=i.degradeCount,i.meanDetectMs>0&&this.carriedMeans.push(i.meanDetectMs),this.scheduler.stop()}let r=new D({cadenceHz:t.profile.cadenceHz,video:this.options.video,now:this.options.now,run:()=>this.detectTick(e)});this.scheduler=r,r.start()}async detectTick(e){let{detector:t,gate:r,profiler:i}=this,a=this.options.video;if(e!==this.attempt||t===null||r===null||i===null||this.fired||a.videoWidth===0)return;if(this.isLandscape()){this.holdUpright(e);return}let s=i.deviceClass,o=this.now(),c=this.options.makeSnapshot?.(a,i.profile.inputWidth)??this.defaultSnapshot(a,i.profile.inputWidth),l=null;try{l=await t.detect(c,a.videoWidth,a.videoHeight)}catch{l=null}if(e!==this.attempt||this.fired)return;i.record(this.now()-o),i.deviceClass!==s&&this.startScheduler(e);let d=l===null?we: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>=$e&&(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 i=r?.stats()??{degradeCount:0,meanDetectMs:0},a=[...this.carriedMeans,...i.meanDetectMs>0?[i.meanDetectMs]:[]];t.telemetry?.({type:"fired",timeToGateMs:this.now()-this.positioningStartedAt,degradeCount:this.carriedDegrade+i.degradeCount,meanDetectMs:a.length===0?0:a.reduce((y,v)=>y+v,0)/a.length});let s=t.mode??"clip",o=t.rankKeyframes?.()&&B?B.default(this,e).catch(()=>this.collectKeyframes(e)):this.collectKeyframes(e);if(s==="photo"){let y=this.watchRotation(e,null),v=await o;if(y(),e!==this.attempt)return;if(v===null){this.fail("generic",{phase:"keyframes"});return}let O=await this.provenance({n:0,meanGapMs:0,stdGapMs:0,captureLatencyMs:null},!1);if(e!==this.attempt)return;this.finishCapture({keyframe:v.blob,previewDataUrl:v.previewDataUrl,...O});return}this.setState("recording");let c=this.stream;if(c===null){this.fail("generic",{phase:"recording"});return}let l=t.screenRamp?.(),d=ie(l),u=null;o.then(y=>{u=y},()=>{});let p=()=>{e===this.attempt&&u!==null&&this.emit("frozen",{previewDataUrl:u.previewDataUrl})},m=ne(l,V),f=null,g,M=0;try{let y=this.recordTake(e,c,l,m,void 0).then(E=>E,E=>({failed:E})),[v,O]=await Promise.all([y,o]);if(g=O,e!==this.attempt)return;if("failed"in v){if(v.failed.kind==="cliptoolarge")throw v.failed;L(v.failed.requestedMimeType??"")}else f=v,N(v.clip,m)?v.clip.stats===null&&L(v.clip.requestedMimeType??""):p();if(f===null||N(f.clip,m)){M=1,t.telemetry?.({type:"clip_retake",reason:f===null?"error":f.clip.stats===null?"unreadable":"short"});let E=null;try{E=await this.recordTake(e,c,l,m,p)}catch(De){if(f===null)throw De}if(e!==this.attempt)return;E!==null&&(f===null||Ee(E.clip,f.clip))&&(f=E),E===null&&p()}}catch(y){if(e!==this.attempt)return;let v=y.kind;this.fail(v==="cliptoolarge"?"cliptoolarge":"recorder",{phase:"recording",name:k(y)});return}if(f===null){this.fail("recorder",{phase:"recording"});return}let{clip:h,rvfc:b,report:S,watched:I}=f;if(R(h.blob)){this.fail("cliptoolarge",{phase:"recording"});return}if(g===null){this.fail("generic",{phase:"keyframes"});return}let Ae=await this.provenance(b,d,I);e===this.attempt&&this.finishCapture({clip:h.blob,clipMimeType:h.mimeType,...h.stats?{clipStats:h.stats}:{},clipRetakes:M,keyframe:g.blob,previewDataUrl:g.previewDataUrl,...S!==void 0&&S.rendered.length>0?{screenRamp:S}:{},...Ae})}async recordTake(e,t,r,i,a){let s=this.options.createRecorder?.()??new A({now:()=>this.now()}),o=ke(this.options.video),c=ae(r,{paint:p=>{(p===null||e===this.attempt)&&this.emit("ramp",{colour:p})},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),u=ee();try{return{clip:await s.record(t,a,()=>c.started(this.now()),i,o),rvfc:o.stats(),report:c.report(),watched:u.stop()}}finally{u.stop(),d(),l()}}async provenance(e,t,r={}){let i=this.trackProvenance;if(i===null)return{};let a,s=new Promise(d=>{a=setTimeout(()=>d(null),tt)}),o=await Promise.race([i,s]),c=o===null?null:await Promise.race([this.openEnvironment,s]);if(clearTimeout(a),o===null)return{};let l={...c,...r};return{provenance:{..._e(o,e,t),...Object.keys(l).length>0?{env:l}:{}}}}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!==H&&(this.lastGuidanceKey=H,this.emit("guidance",{key:H}))}watchRotation(e,t){if(!this.uprightGuard)return()=>{};let r=this.options.video,i=()=>{if(e!==this.attempt||t!==null&&this.stateValue!=="recording"){o();return}r.videoWidth>0&&this.isLandscape()&&(o(),this.abortRecording(e,t))},a=setInterval(i,Je);r.addEventListener?.("resize",i);let s=!1;function o(){s||(s=!0,clearInterval(a),r.removeEventListener?.("resize",i))}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 _(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=et/(K-1),i=null;for(let a=0;a<K;a+=1){if(e!==this.attempt)return i;try{let s=await t(this.options.video);(i===null||s.sharpness>i.sharpness)&&(i=s)}catch{}a<K-1&&await nt(r)}return i}finishCapture(e){this.stopTracks(),this.setState("captured");let t=this.captureTiming();this.emit("artifacts",t===void 0?e:{...e,timing:t})}captureTiming(){let e={},t=(r,i,a)=>{i!==null&&a!==null&&(e[r]=Math.max(0,Math.round(a-i)))};return t("cameraReadyMs",this.cameraRequestedAt,this.cameraReadyAt),t("faceAcquireMs",this.cameraReadyAt,this.faceAcquiredAt),t("captureMs",this.faceAcquiredAt,this.captureCompleteAt),Object.keys(e).length>0?e:void 0}async defaultKeyframe(e){let t=document.createElement("canvas"),r=await(this.facing==="user"?Me:rt)(e,t),i=t.toDataURL("image/jpeg",.92);return{blob:r,previewDataUrl:i,sharpness:this.centerSharpness(e)}}defaultSnapshot(e,t){try{let r=this.snapshotCanvas??document.createElement("canvas"),i=t/Math.max(1,e.videoWidth),a=Math.max(1,Math.round(e.videoWidth*i)),s=Math.max(1,Math.round(e.videoHeight*i)),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=Re(e,t,96);return r===null?we:{sharpness:G(r),exposure:ve(r),meanLuma:fe(r)}}centerSharpness(e){let t=ce(e),r=Re(e,{x:t.width*.25,y:t.height*.25,width:t.width*.5,height:t.height*.5},96);return r===null?0:G(r)}teardownAttempt(){this.scheduler?.stop(),this.scheduler=null,this.reportGate(!0),this.gate=null,this.ramp?.stop(),this.ramp=null,this.stopTracks()}reportGate(e){let t=this.blockStats,r=this.profiler;if(t===null||r===null)return;let i=t.summary();e&&(this.blockStats=null),i.ticks!==0&&this.options.telemetry?.({type:"gate",final:e,activeClass:r.deviceClass,cadenceHz:r.profile.cadenceHz,...i})}stopTracks(){if(this.stream!==null){for(let e of this.stream.getTracks())e.stop();this.stream=null}}fail(e,t,r){this.scheduler?.stop(),this.reportGate(!0),this.stopTracks(),this.setState("error"),this.options.telemetry?.({type:"error",kind:e,fallbackReason:r});let{phase:i,name:a}=t;this.emit("error",{kind:e,retryable:e!=="insecure"&&e!=="unsupported",detail:a===void 0?{phase:i}:{phase:i,name:a}})}setState(e){this.stateValue=e,this.emit("statechange",{state:e})}now(){return this.options.now?.()??performance.now()}},B;function nt(n){return new Promise(e=>setTimeout(e,n))}function at(n){return n instanceof Error?n.message:String(n)}function Re(n,e,t){try{let r=document.createElement("canvas"),i=t/Math.max(1,e.width);r.width=Math.max(1,Math.round(e.width*i)),r.height=Math.max(1,Math.round(e.height*i));let a=r.getContext("2d");return a===null?null:(a.drawImage(n,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 st(n){if(n.enumerateDevices!==void 0)return n.enumerateDevices;if(n.getUserMedia===void 0&&!(typeof navigator>"u"||typeof navigator.mediaDevices?.enumerateDevices!="function"))return()=>navigator.mediaDevices.enumerateDevices()}export{lt as a,V as b,Ge as c,Le as d,Te as e,Fe as f,Ve as g,Ne as h,Ue as i,T as j,Ke as k,N as l,Ee as m,A as n,Me as o,D as p,We as q,_ as r,ze as s,w as t,$e as u,H as v,Je as w,K as x,et as y,tt as z,Ie as A};
|