@sekyro/web 0.1.0-rc.28 → 0.1.0-rc.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/barcode-detect-C5IOXMKI.js +1 -0
  3. package/dist/{capture-session-doc-LUA4Y7PZ.js → capture-session-doc-YC4CT2EQ.js} +1 -1
  4. package/dist/{capture-session-v3-ClByT4KN.d.cts → capture-session-v3-CTQL6eFd.d.cts} +1 -1
  5. package/dist/{capture-session-v3-IjQwKfLS.d.ts → capture-session-v3-DHlOE6cS.d.ts} +1 -1
  6. package/dist/{challenge-frame-NUGPTWFP.js → challenge-frame-5GG4NDF5.js} +1 -1
  7. package/dist/{chunk-QP23DM4Z.js → chunk-34IITQFB.js} +1 -1
  8. package/dist/chunk-6AH7FXVC.js +1 -0
  9. package/dist/{chunk-MOOWUPOZ.js → chunk-AL6LIOLW.js} +1 -1
  10. package/dist/chunk-BF7CLNFA.js +1 -0
  11. package/dist/chunk-CKHBGAUA.js +1 -0
  12. package/dist/chunk-EVIGRYOX.js +3 -0
  13. package/dist/chunk-FVWFAO45.js +1 -0
  14. package/dist/{chunk-FSXWIMSG.js → chunk-IA5M34P7.js} +1 -1
  15. package/dist/chunk-JLVZ35QK.js +2 -0
  16. package/dist/{chunk-4DEPREJ3.js → chunk-KXFHVAYQ.js} +1 -1
  17. package/dist/chunk-VVUQ4PFU.js +1 -0
  18. package/dist/{chunk-KLEARRAD.js → chunk-WOVWAJD4.js} +1 -1
  19. package/dist/chunk-XIKMTHHH.js +1 -0
  20. package/dist/chunk-ZKF2XMNX.js +1 -0
  21. package/dist/client/index.cjs +1 -1
  22. package/dist/client/index.d.cts +3 -3
  23. package/dist/client/index.d.ts +3 -3
  24. package/dist/client/index.js +1 -1
  25. package/dist/core/index.cjs +1 -1
  26. package/dist/core/index.d.cts +3 -3
  27. package/dist/core/index.d.ts +3 -3
  28. package/dist/core/index.js +1 -1
  29. package/dist/core/ocr/worker.js +1 -1
  30. package/dist/create-document-capture-O64FR2DA.js +1 -0
  31. package/dist/{create-verification-C4FMWIix.d.ts → create-verification-BvldYuLZ.d.ts} +126 -16
  32. package/dist/{create-verification-BN7ebjC2.d.cts → create-verification-DzPluhA3.d.cts} +126 -16
  33. package/dist/{detector-scanic-23DAYT3H.js → detector-scanic-SE3CL55N.js} +1 -1
  34. package/dist/{icao-gate-CjbKCatx.d.cts → icao-gate-DveU9Cr8.d.ts} +1 -1
  35. package/dist/{icao-gate-CYb-35iH.d.ts → icao-gate-xyWB7dz2.d.cts} +1 -1
  36. package/dist/{icao-policy-D4AZivI8.d.ts → icao-policy-BWu1JLgi.d.cts} +12 -3
  37. package/dist/{icao-policy-CAZZYEJ6.d.cts → icao-policy-OOEQDG9_.d.ts} +12 -3
  38. package/dist/index.cjs +2 -2
  39. package/dist/index.d.cts +40 -8
  40. package/dist/index.d.ts +40 -8
  41. package/dist/index.js +1 -1
  42. package/dist/internal/index.cjs +2 -2
  43. package/dist/internal/index.d.cts +6 -6
  44. package/dist/internal/index.d.ts +6 -6
  45. package/dist/internal/index.js +1 -1
  46. package/dist/plan-runner-WGMNUBWJ.js +1 -0
  47. package/dist/{types-CgHWIEZj.d.ts → types-CezFEXzl.d.cts} +148 -8
  48. package/dist/{types-CgHWIEZj.d.cts → types-CezFEXzl.d.ts} +148 -8
  49. package/package.json +6 -3
  50. package/sbom.cdx.json +125 -10
  51. package/dist/chunk-A3FUGHAH.js +0 -2
  52. package/dist/chunk-CUBNJXZN.js +0 -1
  53. package/dist/chunk-HVW2AB35.js +0 -1
  54. package/dist/chunk-J7D3S5ZJ.js +0 -1
  55. package/dist/chunk-MJUOZH3U.js +0 -1
  56. package/dist/chunk-NFHLJOHW.js +0 -1
  57. package/dist/chunk-R4IQTGF5.js +0 -3
  58. package/dist/chunk-THQWX6EH.js +0 -1
  59. package/dist/create-document-capture-ZTJKSEJB.js +0 -1
  60. package/dist/plan-runner-INQLWFGS.js +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,25 @@
1
1
  # @sekyro/web
2
2
 
3
+ ## 0.1.0-rc.29
4
+
5
+ ### Minor Changes
6
+
7
+ - 1e6001c: Two new document reasons. `document_sides_mismatch` (`DocReason`): the front and the back of the card are from two different cards. It is retryable and not billed. When the front was read first the server keeps it (`acceptedSides: ["recto"]`) and the camera asks for the back only; when the back was read first both faces are dropped and the camera starts the card again. `@sekyro/react` shows `doc.reason_document_sides_mismatch` (six languages) without the photo tips. `document_photo_mismatch` (`DocReason` and `NfcChipReason`): the portrait on the document, or in its chip, is a different person from the registry's photo for its identity number. It is final: the session ends rejected.
8
+ - 06d8764: New document step reason `document_type_not_supported`: the document type chosen cannot be used in this flow (it has no machine-readable zone the flow accepts, or the session does not offer it). It is retryable and not billed. The step comes back with `documentType: null`, so the picker reopens, and the refused type is no longer in `step.documents`; when no other type is left, the step fails with this reason. `@sekyro/react` shows `doc.reason_document_type_not_supported` (six languages) without the photo tips. `identity.document.evidence` says what the identity was read from (`mrz`, `barcode`, `visual` or `chip`).
9
+ - 1c7c752: The Form step's contract (planned: no flow can contain it yet). `CheckType` gains `form` and `StepSection` gains `form`; an open Form step carries `form` on its plan step (`HostedFormView`: the client's text in one `locale`, the questions, the consents and the prefill), and `CheckInputByType.form` is the submission (`FormInput`: answers by question id, consents by id). New types: `HostedFormView`, `FormQuestionView`, `FormFieldQuestionView`, `FormCustomQuestionView`, `FormChoiceView`, `FormQuestionOptions`, `FormConsentView`, `FormAddressValue`, `FormAnswerValue`, `FormInput`, `FormIssueCode`, `FormLocale`, `FormFieldName`, `FormQuestionType`. Until the step is rendered, a Form step still shows "update required".
10
+ - 030c9dc: The Form step (planned: no flow can contain it yet). A plan step of the `form` service is the new `form` step (`FormStepHandle`): `form` holds the partner's questions and consents in one language (`dir` says its direction) and the prefill. `validate(input)` lists the refused answers by question id (`FormIssue`), and `submit(input)` checks them, then submits `form`; a refusal, by this client or by the server (422 `form_answers_invalid`, such as a card number typed into a text answer), rejects with `FormAnswersError` and uses no attempt. A question type or field this version does not know is still "update required". New exports: `FormStepHandle`, `FormSnapshot`, `FormIssue`, `FormAnswersError`, `formIssues`, `containsCardNumber`, `directionOf`, `isFormDate`, `isFormNumber`, `todayIso`, `FORM_ANSWER_LIMITS`, `FORM_ANSWERS_INVALID`.
11
+ - 4581cc5: `HostedSessionView.demo`: present (`true`) on a Sekyro AI website demo session that shows the visitor's own name as `orgName`. The hosted verification page uses it to show "Demo by Sekyro AI" in its header; SDK hosts never run the website demo app and can ignore it.
12
+ - 1b8395d: Flows that take their photos in a native app only. When a flow's Device & Network step is set to capture on "Native app or SDK only", its camera steps carry `requiresNativeApp` and the view carries `nativeApp` (`HostedNativeAppView`: whether the Sekyro AI app is allowed, the session link and the Sekyro AI app link). In a browser such a step is the new `native_app_required` step (`NativeAppRequiredStepHandle`, with `refresh`) instead of the camera. A submission from a browser answers `409 native_app_required` (new in `KNOWN_CODES`); the SDK re-reads the session and shows that step. `@sekyro/react` renders it: the partner's app and, when allowed, the Sekyro AI app (open link on a phone, store links, the session QR on a desktop), in six languages (`needsApp.capture.*`).
13
+ - 43ae1ec: Document capture labels the faces of a document without an MRZ from its barcode. When the session's capture plan says which face carries a barcode (PDF417, QR, Data Matrix or Aztec), the capture decodes it on the device to tell the front from the back; only that yes or no is used, and the server's read still decides. The decoder (`zxing-wasm`) loads by `import()` on such a document only, and its binary is fetched from Sekyro AI's asset host and checked against the sha256 built into the SDK before it runs. New option `barcodeAssetBaseUrl` on `createDocumentCapture` and on the document step's `capture()` to self-host that binary (`<base>/<sha12>/zxing_reader.wasm`, where `<sha12>` is the first 12 hex characters of the file's sha256). When the binary cannot be fetched or checked, capture works as before.
14
+ - 80fbf3d: The document step now tells the server which document type and issuing country the person picked, on every side (camera and upload). A document that is not the one picked is refused with `document_type_mismatch`.
15
+
16
+ ### Patch Changes
17
+
18
+ - a63d45e: In a verification's document step, the camera capture can follow the document catalog for the picked country: the sides to capture, the frame's shape, and whether the document has a machine-readable zone. A document without one is captured like a driving licence (both faces, no live MRZ reader). It applies only when the session asks for it; otherwise capture is unchanged.
19
+ - 98f6752: The document catalog and the identity number rules now come from the shared document catalog. No behaviour change.
20
+ - 567f41a: A refused Form submit now shows which questions to change. The client reads the server's `details.errors` (one `{ id, code }` per refused question) and turns each server code into its own `FormIssue` code, with the limit its message names, so every error appears under its question; a card number keeps its own message. `HostedErrorDetails` gains the optional `errors` list. With no details, the client's own check runs again on what was sent. When a refusal names no question of the form, the Form screen says the answers could not be sent instead of staying silent.
21
+ - a75a33e: The liveness submission is never sent without a security check token. The server refuses every hosted web liveness without one, so a slow or failed check used to cost a certain `attestation_invalid` and the capture's only attestation retry. The SDK now waits for the running check after the uploads and, when a check fails, starts a fresh one after a short pause (at most 3, all within 2 minutes). Only then does the capture end `unavailable` with `reasonCode: "attestation"` and the check's `attestationError`, with nothing submitted. A check still running then serves the next capture. A token the server refuses still gets its one retry with a fresh token. The `attestation` capture issue now also carries Cloudflare's numeric error code (`detail`), the check's duration (`challengeMs`), how long the check frame took to load (`readyMs`) and whether the page runs in an app's WebView (`inApp`). It is also sent once for each failed check.
22
+
3
23
  ## 0.1.0-rc.28
4
24
 
5
25
  ### Minor Changes
@@ -0,0 +1 @@
1
+ import{a as c}from"./chunk-JLVZ35QK.js";var a={name:"zxing_reader.wasm",bytes:928265,sha256:"5bb3ce7aeedc314e24afb873bebcf366a01c27a00b21cdf2fa98b819c005c16b",sha12:"5bb3ce7aeedc"};var i=["PDF417","QRCode","DataMatrix","Aztec"];function f(r){return`${r.replace(/\/+$/,"")}/${a.sha12}/${a.name}`}async function d(r,o=fetch){let t=await o(f(r),{cache:"force-cache",credentials:"omit"});if(!t.ok)throw new Error("barcode wasm download");let e=await t.arrayBuffer();if(e.byteLength!==a.bytes||await c(e)!==a.sha256)throw new Error("barcode wasm integrity");return e}async function h(r,o=fetch){let t=await d(r,o),e=await import("zxing-wasm/reader");return await e.prepareZXingModule({overrides:{wasmBinary:t},fireImmediately:!0}),async s=>(await e.readBarcodes(s,{formats:[...i],tryHarder:!0,maxNumberOfSymbols:1})).some(n=>n.isValid)}export{f as barcodeWasmUrl,d as fetchBarcodeWasm,h as loadBarcodeDetect};
@@ -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-KLEARRAD.js";import"./chunk-G6LKLN4U.js";import"./chunk-SMKCBUJL.js";import"./chunk-4DEPREJ3.js";import"./chunk-NFHLJOHW.js";import"./chunk-POIQGEZM.js";import"./chunk-CPUECYAJ.js";import"./chunk-FPXL63KZ.js";import"./chunk-FSXWIMSG.js";import"./chunk-DK5YPBDQ.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
+ 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-WOVWAJD4.js";import"./chunk-G6LKLN4U.js";import"./chunk-SMKCBUJL.js";import"./chunk-KXFHVAYQ.js";import"./chunk-VVUQ4PFU.js";import"./chunk-POIQGEZM.js";import"./chunk-CPUECYAJ.js";import"./chunk-FPXL63KZ.js";import"./chunk-IA5M34P7.js";import"./chunk-DK5YPBDQ.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 { bc as ScreenRampReport, b3 as CaptureProvenance, b9 as ScreenRampChallenge, ba as ScreenRampPaint } from './types-CgHWIEZj.cjs';
1
+ import { br as ScreenRampReport, bi as CaptureProvenance, bo as ScreenRampChallenge, bp as ScreenRampPaint } from './types-CezFEXzl.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 { bc as ScreenRampReport, b3 as CaptureProvenance, b9 as ScreenRampChallenge, ba as ScreenRampPaint } from './types-CgHWIEZj.js';
1
+ import { br as ScreenRampReport, bi as CaptureProvenance, bo as ScreenRampChallenge, bp as ScreenRampPaint } from './types-CezFEXzl.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
- import{a,b,c,d,e}from"./chunk-HVW2AB35.js";export{c as CHALLENGE_EXECUTE_TIMEOUT_MS,b as CHALLENGE_READY_TIMEOUT_MS,a as ChallengeError,e as executeChallenge,d as resetChallengeFrameForTests};
1
+ import{a,b,c,d,e}from"./chunk-FVWFAO45.js";export{c as CHALLENGE_EXECUTE_TIMEOUT_MS,b as CHALLENGE_READY_TIMEOUT_MS,a as ChallengeError,e as executeChallenge,d as resetChallengeFrameForTests};
@@ -1 +1 @@
1
- import{a as Y,d as ee,e as O,f as te,g as ne}from"./chunk-7QZWBDI5.js";import{C as X,a as j}from"./chunk-MOOWUPOZ.js";import{f as Q,l as Z}from"./chunk-CPUECYAJ.js";import{c as $}from"./chunk-TSA6GHUG.js";import{c as J,h as C}from"./chunk-FSSMUAKC.js";var ue=12e4,re=13e4,le=3e3,fe=1200,P=Symbol.for("@sekyro/web.preload.v1");function g(){let e=globalThis;return e[P]??(e[P]=new Map),e[P]}function S(e){let n=(e??J).replace(/\/+$/,"");return n===""?"/":n}function se(e){let n=g(),r=n.get(e);return r===void 0&&(r={status:"idle",promise:null,scheduled:null,detectorPromise:null,detector:null,listeners:new Set},n.set(e,r)),r}function A(e,n){if(e.status!==n){e.status=n;for(let r of[...e.listeners])r(n)}}var x=e=>C({preferred:["blaze"],v3AssetBaseUrl:e,blazeInitTimeoutMs:ue}),F=x;function Pe(e){F=e??x}function Ae(){for(let e of g().values())e.detector?.destroy();g().clear(),F=x}function pe(){return typeof window<"u"&&typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"}function me(){return navigator.connection?.saveData===!0}function ve(e){let n=window;if(typeof n.requestIdleCallback=="function"){let s=n.requestIdleCallback(e,{timeout:le});return()=>n.cancelIdleCallback?.(s)}let r=setTimeout(e,fe);return()=>clearTimeout(r)}function ge(e,n){let r,s=new Promise(i=>{r=i}),m=!1,d=()=>{},u={promise:s,settle:i=>{m||(m=!0,d(),e.scheduled===u&&(e.scheduled=null),r(i))}};return e.scheduled=u,d=ve(()=>{m||u.settle(I(e,n))}),s}function I(e,n){if((e.status==="loading"||e.status==="ready")&&e.promise!==null)return e.promise;A(e,"loading");let r=new Promise(i=>i(F(n)));e.detectorPromise=r;let s,m=new Promise((i,f)=>{s=setTimeout(()=>{r.then(h=>h.destroy(),()=>{}),f(new Error(`detector preload exceeded ${re} ms`))},re)}),u=Promise.race([r,m]).then(i=>e.detectorPromise!==r?(i.destroy(),e.status):(e.detector=i,A(e,"ready"),"ready"),i=>(e.detectorPromise===r&&(e.detectorPromise=null,e.detector=null,A(e,"failed"),console.warn("[@sekyro/web] face-detector preload failed:",i)),e.status)).finally(()=>clearTimeout(s));return e.promise=u,e.scheduled?.settle(u),u}function we(e={}){if(!pe())return Promise.resolve("idle");let n=S(e.assetBaseUrl),r=se(n);return e.respectSaveData===!0&&me()?Promise.resolve(r.status):(r.status==="loading"||r.status==="ready")&&r.promise!==null?r.promise:e.idle===!0?r.scheduled?.promise??ge(r,n):I(r,n)}function ke(e){return g().get(S(e))?.status??"idle"}function De(e,n){let r=se(S(n));return r.listeners.add(e),()=>{r.listeners.delete(e)}}function _e(e){let n=g().get(S(e));n!==void 0&&(n.scheduled?.settle("idle"),n.detector?.destroy(),n.detector=null,n.detectorPromise=null,n.promise=null,A(n,"idle"))}function he(e){return{get tier(){return e.tier},get fallbackReason(){return e.fallbackReason},detect:(...n)=>e.detect(...n),destroy:()=>{}}}function oe(e){let n=S(e),r=g().get(n);if(!(r===void 0||r.detector===null&&r.detectorPromise===null&&r.scheduled===null))return async()=>{r.scheduled!==null&&I(r,n);let s=r.promise;for(;r.detector===null&&s!==null&&(await s,r.promise!==s);)s=r.promise;return r.detector!==null?he(r.detector):C({v3AssetBaseUrl:n})}}function Ce(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 Se(e){switch(e){case"preflight":case"acquiring":return"starting";case"positioning":return"gating";default:return e}}function ie(e){switch(e){case"permission":case"notfound":case"inuse":case"insecure":case"unsupported":return e;case"backcamera":return"notfound";default:{let n=e;return"generic"}}}function Le(e,n,r){if(r===void 0)return{kind:ie(e),retryable:n};let s=Z(r.name);return{kind:ie(e),retryable:n,detail:{...s!==void 0?{name:s}:{},phase:r.phase,engineKind:e}}}var ye=new Set(["captured","uploading","checking"]);function Ee(e,n={},r,s=()=>"self",m=()=>{},d){let u=n.now??(()=>performance.now()),i=n.canChooseFacing??ee,f="user",h=te(),p=s(),l=Y(),B=!Q(),H=n.engineOptions,ae=H?.createDetector===void 0&&H?.createWorker===void 0?{createDetector:()=>{let t=oe(e.assetBaseUrl);return t!==void 0?t():C({v3AssetBaseUrl:e.assetBaseUrl})}}:{},U={video:e.video,mode:B?"photo":"clip",rankKeyframes:r,facingMode:void 0,v3AssetBaseUrl:e.assetBaseUrl,screenRamp:()=>p==="self"&&l.count("ramp")>0?m():void 0,...n.engineOptions??{},...ae},o=n.createEngine?.(U)??new X(U),v="idle",L=null,y=0,w=!1,k="full",E=null,b=null,D=0,_=0,K=()=>{e.video.videoWidth>0&&e.video.videoHeight>0&&(D=e.video.videoWidth,_=e.video.videoHeight)},V=ne({enabled:e.keepScreenAwake!==!1}),M=t=>{v=t,V.setActive(t==="starting"||t==="gating"||t==="recording"),l.emit("state",t)},R=()=>l.emit("gate",{progress:y,hint:L,faceDetected:w}),G=()=>{let t=o.animations??"full";t!==k&&(k=t,l.emit("profile",{animations:k}))},de=[o.on("statechange",({state:t})=>{let a=Se(t);a==="starting"&&v!=="starting"&&(L=null,y=0,w=!1,E=null,b=null,D=0,_=0),M(a),G(),a==="recording"&&(K(),E=u(),L="hold",y=1,R())}),o.on("checks",t=>{K(),y=t.progress,w=t.factors.presence>0,R(),G()}),o.on("guidance",({key:t})=>{L=Ce(t),R()}),o.on("frozen",({previewDataUrl:t})=>{b=u(),l.emit("frozen",{previewDataUrl:t})}),o.on("ramp",t=>l.emit("ramp",t)),o.on("artifacts",t=>{if(v!=="captured")return;let a=$(),c=t.clipStats,q=c!==void 0?Math.round(c.durationMs):E!==null&&b!==null?Math.max(0,Math.round(b-E)):void 0,N=c!==void 0&&c.frames>1&&c.durationMs>0?Math.round(c.frames*1e4/c.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||D,height:e.video.videoHeight||_,...q!==void 0?{clipMs:q}:{},...c!==void 0?{clipFrames:c.frames}:{},...N!==void 0?{fps:N}:{},...t.clipRetakes!==void 0?{clipRetakes:t.clipRetakes}:{},...t.clipMimeType!==void 0?{codec:j(t.clipMimeType)}:{},captureChannel:a==="desktop"?"desktop":"mobile",formFactor:a,...B?{degraded:"NO_RECORDER"}:{},engine:"v3",facingMode:o.facingMode,mode:p,...t.timing,...t.screenRamp!==void 0?{screenRamp:t.screenRamp}:{},...t.provenance!==void 0?{provenance:t.provenance}:{}})}),o.on("error",({kind:t,retryable:a,detail:c})=>{t==="backcamera"&&ce()||l.emit("error",Le(t,a,c))})],z=!1;function ce(){return T||z||p!=="assisted"||d===void 0||d.session()!=="choice"?!1:(z=!0,d.onModeChange("self"),p="self",f=O("self"),M("mode_switch"),o.restart(f),!0)}let W=async()=>d!==void 0&&d.session()==="choice"&&await i().catch(()=>!1),T=!1;return{handle:{get state(){return v},get captureMode(){return s()},get facingMode(){return o.facingMode??f},on:(t,a)=>l.on(t,a),start:t=>(p=s(),h.facing(p,e.facing),f=h.facing(p,t?.facing),o.start({facingMode:f})),retry:()=>o.retry(),switchCamera:()=>h.refuseSwitch(s()),canSwitchCaptureMode:W,setCaptureMode:async t=>{if(t===s()||!await W()||T||ye.has(v)||d===void 0)return!1;d.onModeChange(t),p=t;let a=O(t);return f=a,v==="idle"||(M("mode_switch"),o.restart(a)),!0},destroy:()=>{T=!0;for(let t of de)t();V.setActive(!1),o.destroy(),l.clear()}},setFlowState:t=>{v!==t&&M(t)}}}function ze(e){return Ee(e).handle}export{ue as a,re as b,Pe as c,Ae as d,we as e,ke as f,De as g,_e as h,oe as i,Ce as j,Se as k,ie as l,Le as m,Ee as n,ze as o};
1
+ import{a as Y,d as ee,e as O,f as te,g as ne}from"./chunk-7QZWBDI5.js";import{C as X,a as j}from"./chunk-AL6LIOLW.js";import{f as Q,l as Z}from"./chunk-CPUECYAJ.js";import{c as $}from"./chunk-TSA6GHUG.js";import{c as J,h as C}from"./chunk-FSSMUAKC.js";var ue=12e4,re=13e4,le=3e3,fe=1200,P=Symbol.for("@sekyro/web.preload.v1");function g(){let e=globalThis;return e[P]??(e[P]=new Map),e[P]}function S(e){let n=(e??J).replace(/\/+$/,"");return n===""?"/":n}function se(e){let n=g(),r=n.get(e);return r===void 0&&(r={status:"idle",promise:null,scheduled:null,detectorPromise:null,detector:null,listeners:new Set},n.set(e,r)),r}function A(e,n){if(e.status!==n){e.status=n;for(let r of[...e.listeners])r(n)}}var x=e=>C({preferred:["blaze"],v3AssetBaseUrl:e,blazeInitTimeoutMs:ue}),F=x;function Pe(e){F=e??x}function Ae(){for(let e of g().values())e.detector?.destroy();g().clear(),F=x}function pe(){return typeof window<"u"&&typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"}function me(){return navigator.connection?.saveData===!0}function ve(e){let n=window;if(typeof n.requestIdleCallback=="function"){let s=n.requestIdleCallback(e,{timeout:le});return()=>n.cancelIdleCallback?.(s)}let r=setTimeout(e,fe);return()=>clearTimeout(r)}function ge(e,n){let r,s=new Promise(i=>{r=i}),m=!1,d=()=>{},u={promise:s,settle:i=>{m||(m=!0,d(),e.scheduled===u&&(e.scheduled=null),r(i))}};return e.scheduled=u,d=ve(()=>{m||u.settle(I(e,n))}),s}function I(e,n){if((e.status==="loading"||e.status==="ready")&&e.promise!==null)return e.promise;A(e,"loading");let r=new Promise(i=>i(F(n)));e.detectorPromise=r;let s,m=new Promise((i,f)=>{s=setTimeout(()=>{r.then(h=>h.destroy(),()=>{}),f(new Error(`detector preload exceeded ${re} ms`))},re)}),u=Promise.race([r,m]).then(i=>e.detectorPromise!==r?(i.destroy(),e.status):(e.detector=i,A(e,"ready"),"ready"),i=>(e.detectorPromise===r&&(e.detectorPromise=null,e.detector=null,A(e,"failed"),console.warn("[@sekyro/web] face-detector preload failed:",i)),e.status)).finally(()=>clearTimeout(s));return e.promise=u,e.scheduled?.settle(u),u}function we(e={}){if(!pe())return Promise.resolve("idle");let n=S(e.assetBaseUrl),r=se(n);return e.respectSaveData===!0&&me()?Promise.resolve(r.status):(r.status==="loading"||r.status==="ready")&&r.promise!==null?r.promise:e.idle===!0?r.scheduled?.promise??ge(r,n):I(r,n)}function ke(e){return g().get(S(e))?.status??"idle"}function De(e,n){let r=se(S(n));return r.listeners.add(e),()=>{r.listeners.delete(e)}}function _e(e){let n=g().get(S(e));n!==void 0&&(n.scheduled?.settle("idle"),n.detector?.destroy(),n.detector=null,n.detectorPromise=null,n.promise=null,A(n,"idle"))}function he(e){return{get tier(){return e.tier},get fallbackReason(){return e.fallbackReason},detect:(...n)=>e.detect(...n),destroy:()=>{}}}function oe(e){let n=S(e),r=g().get(n);if(!(r===void 0||r.detector===null&&r.detectorPromise===null&&r.scheduled===null))return async()=>{r.scheduled!==null&&I(r,n);let s=r.promise;for(;r.detector===null&&s!==null&&(await s,r.promise!==s);)s=r.promise;return r.detector!==null?he(r.detector):C({v3AssetBaseUrl:n})}}function Ce(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 Se(e){switch(e){case"preflight":case"acquiring":return"starting";case"positioning":return"gating";default:return e}}function ie(e){switch(e){case"permission":case"notfound":case"inuse":case"insecure":case"unsupported":return e;case"backcamera":return"notfound";default:{let n=e;return"generic"}}}function Le(e,n,r){if(r===void 0)return{kind:ie(e),retryable:n};let s=Z(r.name);return{kind:ie(e),retryable:n,detail:{...s!==void 0?{name:s}:{},phase:r.phase,engineKind:e}}}var ye=new Set(["captured","uploading","checking"]);function Ee(e,n={},r,s=()=>"self",m=()=>{},d){let u=n.now??(()=>performance.now()),i=n.canChooseFacing??ee,f="user",h=te(),p=s(),l=Y(),B=!Q(),H=n.engineOptions,ae=H?.createDetector===void 0&&H?.createWorker===void 0?{createDetector:()=>{let t=oe(e.assetBaseUrl);return t!==void 0?t():C({v3AssetBaseUrl:e.assetBaseUrl})}}:{},U={video:e.video,mode:B?"photo":"clip",rankKeyframes:r,facingMode:void 0,v3AssetBaseUrl:e.assetBaseUrl,screenRamp:()=>p==="self"&&l.count("ramp")>0?m():void 0,...n.engineOptions??{},...ae},o=n.createEngine?.(U)??new X(U),v="idle",L=null,y=0,w=!1,k="full",E=null,b=null,D=0,_=0,K=()=>{e.video.videoWidth>0&&e.video.videoHeight>0&&(D=e.video.videoWidth,_=e.video.videoHeight)},V=ne({enabled:e.keepScreenAwake!==!1}),M=t=>{v=t,V.setActive(t==="starting"||t==="gating"||t==="recording"),l.emit("state",t)},R=()=>l.emit("gate",{progress:y,hint:L,faceDetected:w}),G=()=>{let t=o.animations??"full";t!==k&&(k=t,l.emit("profile",{animations:k}))},de=[o.on("statechange",({state:t})=>{let a=Se(t);a==="starting"&&v!=="starting"&&(L=null,y=0,w=!1,E=null,b=null,D=0,_=0),M(a),G(),a==="recording"&&(K(),E=u(),L="hold",y=1,R())}),o.on("checks",t=>{K(),y=t.progress,w=t.factors.presence>0,R(),G()}),o.on("guidance",({key:t})=>{L=Ce(t),R()}),o.on("frozen",({previewDataUrl:t})=>{b=u(),l.emit("frozen",{previewDataUrl:t})}),o.on("ramp",t=>l.emit("ramp",t)),o.on("artifacts",t=>{if(v!=="captured")return;let a=$(),c=t.clipStats,q=c!==void 0?Math.round(c.durationMs):E!==null&&b!==null?Math.max(0,Math.round(b-E)):void 0,N=c!==void 0&&c.frames>1&&c.durationMs>0?Math.round(c.frames*1e4/c.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||D,height:e.video.videoHeight||_,...q!==void 0?{clipMs:q}:{},...c!==void 0?{clipFrames:c.frames}:{},...N!==void 0?{fps:N}:{},...t.clipRetakes!==void 0?{clipRetakes:t.clipRetakes}:{},...t.clipMimeType!==void 0?{codec:j(t.clipMimeType)}:{},captureChannel:a==="desktop"?"desktop":"mobile",formFactor:a,...B?{degraded:"NO_RECORDER"}:{},engine:"v3",facingMode:o.facingMode,mode:p,...t.timing,...t.screenRamp!==void 0?{screenRamp:t.screenRamp}:{},...t.provenance!==void 0?{provenance:t.provenance}:{}})}),o.on("error",({kind:t,retryable:a,detail:c})=>{t==="backcamera"&&ce()||l.emit("error",Le(t,a,c))})],z=!1;function ce(){return T||z||p!=="assisted"||d===void 0||d.session()!=="choice"?!1:(z=!0,d.onModeChange("self"),p="self",f=O("self"),M("mode_switch"),o.restart(f),!0)}let W=async()=>d!==void 0&&d.session()==="choice"&&await i().catch(()=>!1),T=!1;return{handle:{get state(){return v},get captureMode(){return s()},get facingMode(){return o.facingMode??f},on:(t,a)=>l.on(t,a),start:t=>(p=s(),h.facing(p,e.facing),f=h.facing(p,t?.facing),o.start({facingMode:f})),retry:()=>o.retry(),switchCamera:()=>h.refuseSwitch(s()),canSwitchCaptureMode:W,setCaptureMode:async t=>{if(t===s()||!await W()||T||ye.has(v)||d===void 0)return!1;d.onModeChange(t),p=t;let a=O(t);return f=a,v==="idle"||(M("mode_switch"),o.restart(a)),!0},destroy:()=>{T=!0;for(let t of de)t();V.setActive(!1),o.destroy(),l.clear()}},setFlowState:t=>{v!==t&&M(t)}}}function ze(e){return Ee(e).handle}export{ue as a,re as b,Pe as c,Ae as d,we as e,ke as f,De as g,_e as h,oe as i,Ce as j,Se as k,ie as l,Le as m,Ee as n,ze as o};
@@ -0,0 +1 @@
1
+ import{c as f}from"./chunk-TSA6GHUG.js";import{a as h,c as y}from"./chunk-IA5M34P7.js";var k=["session_token_invalid","session_token_required","session_token_session_mismatch","session_not_found","rate_limit_exceeded","consent_required","session_not_active","check_not_found","check_already_finalized","check_out_of_order","check_type_unsupported","force_outcome_forbidden","attestation_invalid","platform_unregistered","app_attest_invalid","too_many_challenges","inference_unavailable","mobile_required","nni_locked","document_nni_mismatch","media_content_type_not_allowed","media_too_large","media_key_invalid","media_key_forbidden","media_not_found","media_unreadable","media_session_invalid","idempotency_key_collision","idempotency_in_progress","idempotency_key_required","validation_error","internal_error","unknown_error","upload_failed","network_error","timeout","nfc_outcome_not_accepted","identity_confirm_required","identity_confirm_locked","choice_not_found","choice_locked","choice_option_unavailable","step_not_on_path","check_not_active","sekyro_app_not_allowed","sekyro_app_unverified","id_number_locked","document_id_number_mismatch","simulated_capture_forbidden","native_app_required"];function K(t){return k.includes(t)}var c=class extends Error{constructor(e){super(e.message),this.name="HostedApiError",this.status=e.status,this.code=e.code,e.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=e.retryAfterSeconds),e.details&&(this.details=e.details)}};function _(t,e,s=Math.random){let n=(t??e)*1e3,o=Math.min(Math.max(n,500),2e4),i=Math.round(o*(1+(s()*2-1)*.25));return Math.min(Math.max(i,500),2e4)}var R=6e4,b=4,I=3e4,M=9e5,E=200,P=5,C=400,A=new Set(["server_busy","request_timeout"]),v=2;function l(t){return(t.split(";")[0]??"").trim()}var O={liveness:"clipKey",face_match:"imageKey",doc_ocr:"imageKey"},N=`@sekyro/web/${h}`,H=N,g=class{constructor(e){this.sessionId=null;this.bootstrap=null;this.captureNonces=[];this.captureFetch=null;this.reportedIssues=new Map;this.apiOrigin=e.apiOrigin.replace(/\/+$/,""),this.sessionToken=e.sessionToken;let s=e.fetch;this.fetchImpl=(n,o)=>(s??globalThis.fetch).call(globalThis,n,o),this.requestTimeoutMs=e.requestTimeoutMs??I,this.retryAttempts=e.inProgressRetry?.attempts??P,this.retryDelayMs=e.inProgressRetry?.delayMs??C,this.random=e.random??Math.random}async getSession(){let e=await this.api("GET","/hosted/session");return this.sessionId=e.sessionId,e}async recordConsent(e){return this.api("POST","/hosted/consent",{body:{locale:e},busyRetry:!0})}async reportCameraUnavailable(e){return this.api("POST","/hosted/camera-unavailable",{body:{cause:e}})}async testerGate(e){return this.api("POST","/hosted/tester-gate",{body:{input:e}})}async reportCaptureIssue(e){let s=typeof e.name=="string"?e.name.replace(/[^A-Za-z]/g,"").slice(0,40):"",n=typeof e.engineKind=="string"&&/^[a-z_]{1,32}$/.test(e.engineKind)?e.engineKind:void 0,o=typeof e.attempt=="number"&&Number.isInteger(e.attempt)&&e.attempt>=0&&e.attempt<=1e3?e.attempt:void 0,i=[e.check,o??"",e.kind,s,e.phase??""].join("|"),a=this.reportedIssues.get(i);if(a!==void 0)return a;let d={check:e.check,kind:e.kind,...s!==""?{name:s}:{},...e.phase!==void 0?{phase:e.phase}:{},...n!==void 0?{engineKind:n}:{},...o!==void 0?{attempt:o}:{},...e.formFactor!==void 0?{formFactor:e.formFactor}:{},...typeof e.detail=="string"&&/^\d{1,10}$/.test(e.detail)?{detail:e.detail}:{},...T(e.challengeMs)?{challengeMs:e.challengeMs}:{},...T(e.readyMs)?{readyMs:e.readyMs}:{},...e.inApp===!0?{inApp:!0}:{}},r=this.api("POST","/hosted/capture-issue",{body:d,empty:!0}).catch(()=>{this.reportedIssues.delete(i)});return this.reportedIssues.set(i,r),r}async choose(e,s){let n=await this.api("POST","/hosted/choice",{body:{nodeId:e,option:s},busyRetry:!0});return this.sessionId=n.sessionId,n}async confirmIdentity(e){return this.api("POST","/hosted/identity/confirm",{body:{decision:e}})}async identityPortrait(){return this.api("GET","/hosted/identity/portrait",{blob:!0})}async presign(e,s,n,o={}){let i=await this.ensureSessionId(),a={kind:e,contentType:l(s),contentLength:n,...o.source==="upload"?{source:"upload"}:{}};return this.api("POST",`/sessions/${i}/media`,{body:a})}armCapture(e=2){this.fillCaptureNonces(e)}async presignCapture(e,s,n,o={}){let i=await this.ensureSessionId(),a=await this.takeCaptureNonce(),d=a===void 0?void 0:{nonce:a,...o.engine!==void 0?{engine:o.engine.slice(0,32)}:{},...o.durationMs!==void 0&&Number.isFinite(o.durationMs)?{captureMs:Math.min(36e5,Math.max(0,Math.round(o.durationMs)))}:{}},r={kind:e,contentType:l(s),contentLength:n,capture:d};return this.api("POST",`/sessions/${i}/media`,{body:r})}async takeCaptureNonce(){let e=()=>{let s=Date.now();return this.captureNonces=this.captureNonces.filter(n=>n.expiresAt-R>s),this.captureNonces.shift()?.nonce};for(let s=0;s<2;s++){let n=e();if(n!==void 0)return n;await this.fillCaptureNonces(1)}return e()}fillCaptureNonces(e){return this.captureFetch??(this.captureFetch=(async()=>{try{let s=await this.ensureSessionId(),n=await this.api("POST",`/sessions/${s}/media/capture-nonces`,{body:{count:Math.min(b,Math.max(1,e))}}),o=Date.now()+Math.max(0,n.expiresIn)*1e3;for(let i of Array.isArray(n.nonces)?n.nonces:[])typeof i=="string"&&i.length>0&&this.captureNonces.push({nonce:i,expiresAt:o});this.captureNonces=this.captureNonces.slice(-b)}catch{}})().finally(()=>{this.captureFetch=null})),this.captureFetch}async uploadToSpaces(e,s,n){let o;try{o=await this.fetchImpl(e,{method:"PUT",headers:{"content-type":l(n)},body:s,signal:AbortSignal.timeout(M)})}catch(i){throw m(i)}if(!o.ok){let i=(await o.text().catch(()=>"")).slice(0,E);throw new c({status:o.status,code:"upload_failed",message:`media upload failed (HTTP ${o.status})${i?`: ${i}`:""}`})}}async completeMedia(e){let s=await this.ensureSessionId();return this.api("POST",`/sessions/${s}/media/complete`,{body:{key:e}})}async submitCheck(e,s,n={}){let o=await this.ensureSessionId(),i={input:s,forceOutcome:n.forceOutcome};return this.api("POST",`/sessions/${o}/checks/${e}`,{body:i,idempotencyKey:n.idempotencyKey,busyRetry:n.idempotencyKey!==void 0})}async uploadAndSubmit(e,s,n,o={}){let i=l(s.contentType),a=await this.presign(s.kind,i,s.blob.size);await this.uploadToSpaces(a.uploadUrl,s.blob,i);let d=await this.completeMedia(a.key),r={...n,[O[e]]:d.key};return this.submitCheck(e,r,o)}async ensureSessionId(){return this.sessionId!==null?this.sessionId:(this.bootstrap??(this.bootstrap=this.getSession().finally(()=>{this.bootstrap=null})),(await this.bootstrap).sessionId)}async api(e,s,n={}){let o=e==="GET"||n.busyRetry===!0,i=`${this.apiOrigin}/api/v2${s}`,a={"x-session-token":this.sessionToken,"x-sekyro-sdk":H};n.body!==void 0&&(a["content-type"]="application/json"),n.idempotencyKey!==void 0&&(a["x-idempotency-key"]=n.idempotencyKey);try{let d=y.timezone();d!==void 0&&(a["sekyro-client-timezone"]=d)}catch{}a["sekyro-client-form-factor"]=f();try{let d=await y.deviceHeader();d!==void 0&&(a["sekyro-client-device"]=d)}catch{}for(let d=0;;d++){let r;try{r=await this.fetchImpl(i,{method:e,headers:a,...n.body!==void 0?{body:JSON.stringify(n.body)}:{},cache:"no-store",signal:AbortSignal.timeout(this.requestTimeoutMs)})}catch(p){throw m(p)}if(r.ok){if(n.empty===!0)return;if(n.blob===!0)try{return await r.blob()}catch(w){throw m(w)}let p;try{p=await r.json()}catch{throw new c({status:r.status,code:"unknown_error",message:`response body was not valid JSON (HTTP ${r.status})`})}return x(p)}let u=await D(r);if(u.code==="idempotency_in_progress"&&d<this.retryAttempts){this.retryDelayMs>0&&await S(this.retryDelayMs);continue}if(o&&u.status===503&&A.has(u.code)){o=!1,await S(_(u.retryAfterSeconds,v,this.random));continue}throw u}}};function T(t){return typeof t=="number"&&Number.isInteger(t)&&t>=0&&t<=6e5}function m(t){if((typeof t=="object"&&t!==null?t.name:void 0)==="TimeoutError")return new c({status:0,code:"timeout",message:"request timed out"});let s=t instanceof Error?t.message:String(t);return new c({status:0,code:"network_error",message:`network request failed: ${s}`})}function x(t){return t!==null&&typeof t=="object"&&"success"in t&&"data"in t?t.data:t}async function D(t){let e="unknown_error",s=`request failed (HTTP ${t.status})`,n=Number.NaN,o;try{let d=await t.json();if(d!==null&&typeof d=="object"){let r=d;typeof r.code=="string"&&r.code.length>0&&(e=r.code),typeof r.message=="string"&&r.message.length>0&&(s=r.message),typeof r.retryAfterSeconds=="number"&&(n=r.retryAfterSeconds),Array.isArray(r.details?.issues)?o=r.details:Array.isArray(r.details?.errors)&&(o={...r.details,issues:[]})}}catch{}let i=t.headers.get("retry-after"),a=i===null?Math.floor(n):Number.parseInt(i,10);return new c({status:t.status,code:e,message:s,...Number.isFinite(a)&&a>=0?{retryAfterSeconds:a}:{},details:o})}function S(t){return new Promise(e=>setTimeout(e,t))}function j(t){let e=t?.portrait,s=e?.icao,n=e?.purpose==="id_document";return s==null?n?{policy:"reject",profile:"id_document"}:null:{policy:s.policy==="alert"?"alert":"reject",profile:n||s.profile==="id_document"?"id_document":"selfie"}}function B(t){return{...t.baselineEyeOpenness!==void 0?{baselineEyeOpenness:t.baselineEyeOpenness}:{},...t.baselineEyeOpennessLeft!==void 0&&t.baselineEyeOpennessRight!==void 0?{baselineEyeOpennessLeft:t.baselineEyeOpennessLeft,baselineEyeOpennessRight:t.baselineEyeOpennessRight}:{},criteria:t.verdict??{},...t.backgroundCheck!==void 0?{backgroundCheck:t.backgroundCheck}:{}}}export{k as a,K as b,c,_ as d,l as e,N as f,g,j as h,B as i};
@@ -1 +1 @@
1
- import{a as ne,b as ie}from"./chunk-SX7TUC3V.js";import{b as ce,c as ue,d as de}from"./chunk-POIQGEZM.js";import{a as Y,c as j,e as $,g as J,h as A,k as R,m as ee,n as re}from"./chunk-CPUECYAJ.js";import{b as L,c as pe,d as F,e as me}from"./chunk-FPXL63KZ.js";import{a as z,c as X,d as Z,e as Q}from"./chunk-TSA6GHUG.js";import{d as te}from"./chunk-FSXWIMSG.js";import{e as ae,f as se,h as G,j as oe,l as le}from"./chunk-FSSMUAKC.js";var Ie=[...Y.filter(i=>i.startsWith("video/mp4")),"video/webm;codecs=h264","video/webm;codecs=avc1","video/webm;codecs=vp8","video/webm;codecs=vp9","video/webm"],he=new Set;function De(i){let e=/(?:Chrome|Chromium)\/(\d+)\./.exec(i??"");return e?Number(e[1]):null}function fe(i=Oe(),e=globalThis.navigator?.userAgent){if(i===void 0)return"";let t=De(e)===126;for(let r of Ie)if(!(he.has(r)||t&&r.startsWith("video/mp4")))try{if(i(r))return r}catch{}return""}function V(i){i!==""&&he.add(i)}function ge(i){return i.replace(/^video\/x-matroska/i,"video/webm")}function ut(i){let e=/codecs=["']?([^,;"']+)/i.exec(i);return e?e[1].trim():i.split(";")[0].trim()}function Oe(){let i=globalThis.MediaRecorder;return i&&typeof i.isTypeSupported=="function"?e=>i.isTypeSupported(e):void 0}var U=2500,Pe=1e3,xe=1500,ve=25e5,Ge=100,Le=700,Fe=20,Ve=1500,N=null;function Ne(){return N??(N=import("./clip-inspect-DLJXVKV6.js").catch(i=>{throw N=null,i})),N.catch(()=>null)}var S=class extends Error{constructor(e,t){super(t??e),this.kind=e}},Ue=100;function H(i,e){return i.stats===void 0?!1:i.stats===null?!0:i.stats.durationMs<e-Ue}function be(i,e){return i.stats?e.stats?i.stats.durationMs>e.stats.durationMs:!0:!1}var I=class{constructor(e={}){this.recorder=null;this.stream=null;this.chunks=[];this.bytes=0;this.hardStopTimer=null;this.graceTimer=null;this.pollTimer=null;this.settled=!1;this.now=e.now??(()=>globalThis.performance?.now?.()??Date.now())}clearTimers(){this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.graceTimer&&clearTimeout(this.graceTimer),this.pollTimer&&clearInterval(this.pollTimer),this.hardStopTimer=null,this.graceTimer=null,this.pollTimer=null}record(e,t,r,n=U,a){let s=fe(),o=Ne();return this.recordRaw(e,t,r,n,a,s).then(c=>He(c,o),c=>{throw c instanceof S&&(c.requestedMimeType=s),c})}recordRaw(e,t,r,n,a,s){return this.recorder&&!this.settled?Promise.reject(new S("generic","record() called while a recording is in flight \u2014 ClipRecorder handles one recording at a time")):(this.recorder=null,this.clearTimers(),this.chunks=[],this.bytes=0,this.settled=!1,this.stream=e,new Promise((o,c)=>{let l;try{l=new MediaRecorder(e,s?{mimeType:s,videoBitsPerSecond:ve}:{videoBitsPerSecond:ve})}catch{try{l=new MediaRecorder(e)}catch{c(new S("unsupported"));return}}this.recorder=l;let d=h=>{this.settled||(this.settled=!0,this.clearTimers(),h())},u=()=>d(()=>{let h=ge(l.mimeType||s||j),b=new Blob(this.chunks,{type:h});if(b.size===0){c(new S("generic","empty clip"));return}if(A(b)){c(new S("cliptoolarge"));return}o({blob:b,mimeType:h,requestedMimeType:s})});l.ondataavailable=h=>{h.data&&h.data.size&&(this.chunks.push(h.data),this.bytes+=h.data.size,this.bytes>J&&d(()=>{try{l.state!=="inactive"&&l.stop()}catch{}c(new S("cliptoolarge"))}))},l.onstop=u,l.onerror=()=>d(()=>c(new S("generic")));let f=this.now();if(r!==void 0||a!==void 0){let h=!1;l.onstart=()=>{if(!(h||this.settled)&&(h=!0,f=this.now(),r!==void 0))try{r()}catch{}}}try{l.start(Pe)}catch{d(()=>c(new S("generic")));return}let g=()=>{if(this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=null,this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.hardStopTimer=null,this.settled||t?.(),l.state!=="inactive"){try{l.stop()}catch{u()}this.graceTimer=setTimeout(u,xe)}else u()},p=this.now();if(a===void 0){this.hardStopTimer=setTimeout(g,n);return}let m=null,y=!1;this.hardStopTimer=setTimeout(g,n+Le),this.pollTimer=setInterval(()=>{if(this.settled||y)return;let h=null;try{h=a.latest()}catch{h=null}let b=h?.presentationTimeMs;b!==void 0&&Number.isFinite(b)&&b>=f&&m===null&&(m=b);let C=m!==null&&b!==void 0&&b-m>=n,E=m===null&&this.now()-p>=n;if(!(!C&&!E)){if(y=!0,this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=null,E){g();return}this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.hardStopTimer=setTimeout(g,Ge)}},Fe)}))}stop(e){this.clearTimers();let t=this.recorder;if(t&&t.state!=="inactive")try{t.stop()}catch{}this.recorder=null,(e??this.stream)?.getTracks().forEach(n=>n.stop()),this.stream=null}};async function He(i,e){let t,r=new Promise(l=>{t=setTimeout(()=>l(null),Ve)}),n=await Promise.race([e,r]);if(clearTimeout(t),n===null)return i;let a;try{a=await n.blobBytes(i.blob)}catch{return{...i,stats:null}}let s=n.inspectClipBytes(a);if(s?.container!=="webm")return{...i,stats:s};let o=n.withWebmDuration(a,s.durationMs);if(o===null)return{...i,stats:s};let c=n.inspectClipBytes(o);return c===null||c.frames!==s.frames||c.durationMs!==s.durationMs?{...i,stats:s}:{...i,blob:new Blob([o],{type:i.blob.type}),stats:s}}var Ke=["magenta","yellow","green","blue"];var Be={magenta:"rgb(255, 72, 150)",yellow:"rgb(255, 190, 0)",green:"rgb(0, 238, 175)",blue:"rgb(25, 150, 255)",dark:"rgb(0, 0, 0)"};function ft(i){return Be[i]}var We=4,qe=4,D=i=>typeof i=="number"&&Number.isFinite(i);function O(i){if(typeof i!="object"||i===null)return!1;let e=i;if(typeof e.nonce!="string"||e.nonce.length===0||!Array.isArray(e.colours)||e.colours.length<1||e.colours.length>8||!e.colours.every(r=>Ke.includes(r))||!Array.isArray(e.onsetsMs)||e.onsetsMs.length!==e.colours.length)return!1;let t=-1;for(let r of e.onsetsMs){if(!D(r)||r<0||r<=t)return!1;t=r}return!(!D(e.holdMs)||e.holdMs<=0||!D(e.endMs)||e.endMs<=t||!D(e.clipMs)||e.clipMs<e.endMs||e.clipMs>8e3)}function ye(i,e){return O(i)?Math.max(e,Math.ceil(i.clipMs)):e}function Me(i,e){let t=e.now??(()=>performance.now()),r=O(i)?i:void 0,n=[],a=null,s=null,o=null,c=!1,l=null,d=p=>{l=p;try{e.paint(p)}catch{}},u=p=>{let m=e.frames?.()??null;return m!==null&&o!==null?m.mediaTimeMs+(p-m.presentationTimeMs)-o:p-(s??p)},f=(p,m,y=0)=>{if(c)return;let h=Math.max(0,p-u(t()));a=setTimeout(()=>{if(a=null,!c){if(y<We&&u(t())<p-qe){f(p,m,y+1);return}m()}},h)},g=p=>{if(r===void 0)return;let m=r.endMs;if(p>=r.colours.length){f(m,()=>d(null));return}let y=r.onsetsMs[p],h=p+1<r.onsetsMs.length?r.onsetsMs[p+1]:m;f(y,()=>{let b=u(t());if(b>m){l!==null&&d(null);return}let C=r.colours[p];d(C);let E=n.length===0?0:n[n.length-1].tMs;n.push({tMs:Math.max(E,Math.round(b)),colour:C});let M=y+r.holdMs;if(M<h){f(M,()=>{if(u(t())>m){l!==null&&d(null);return}d("dark"),g(p+1)});return}g(p+1)})};return{started(p){if(r===void 0||c||s!==null)return;s=p;let m=e.frames?.()??null;o=m===null?null:m.mediaTimeMs+(p-m.presentationTimeMs),g(0)},stop(){c||(c=!0,a!==null&&clearTimeout(a),a=null,l!==null&&d(null))},report(){return r===void 0?void 0:{nonce:r.nonce,rendered:[...n]}}}}function Se(i,e,t=.92){return new Promise((r,n)=>{let a=i.videoWidth,s=i.videoHeight;if(!a||!s){n(new Error("video-not-ready"));return}let o=e.getContext("2d");if(!o){n(new Error("no-2d-context"));return}e.width=a,e.height=s,o.scale(-1,1),o.drawImage(i,-a,0),e.toBlob(c=>c?r(c):n(new Error("empty-keyframe")),"image/jpeg",t)})}var P=class{constructor(e){this.timer=null;this.frameCallbackId=null;this.running=!1;this.busy=!1;this.lastRunAt=Number.NEGATIVE_INFINITY;this.degradeCount=0;this.durations=[];this.options=e,this.periodMs=1e3/e.cadenceHz}start(){if(this.running)return;this.running=!0;let e=this.options.video;if(typeof e?.requestVideoFrameCallback=="function"){let t=()=>{this.running&&(this.frameCallbackId=e.requestVideoFrameCallback?.(()=>{this.frameCallbackId=null,this.now()-this.lastRunAt>=this.periodMs&&this.tick(),t()}))};t();return}this.timer=setInterval(()=>this.tick(),this.periodMs)}stop(){this.running=!1,this.timer!==null&&(clearInterval(this.timer),this.timer=null),this.frameCallbackId!==null&&(this.options.video?.cancelVideoFrameCallback?.(this.frameCallbackId),this.frameCallbackId=null)}stats(){let e=this.durations.length===0?0:this.durations.reduce((t,r)=>t+r,0)/this.durations.length;return{degradeCount:this.degradeCount,meanDetectMs:e}}now(){return this.options.now?.()??performance.now()}tick(){if(!this.running)return;if(this.busy){this.degradeCount+=1;return}this.busy=!0,this.lastRunAt=this.now();let e=this.now();this.options.run().catch(()=>{}).finally(()=>{this.busy=!1,this.durations.push(this.now()-e),this.durations.length>20&&this.durations.shift()})}};var ze=Object.freeze({Q_GOOD:.6,RISE_PER_S:.9,FALL_PER_S:.25,CENTER_FALLOFF_IOD_MULTIPLE:1.35,BOX_EYE_OFFSET_FACTOR:.12,IOD_BOX_PROXY_FACTOR:.42,SIZE_IDEAL_MIN:.12,SIZE_IDEAL_MAX:.3,SIZE_HARD_MIN:.08,SIZE_HARD_MAX:.45,ROLL_MAX_DEG:25,MOTION_VELOCITY_IOD_PER_S:.5,MOTION_TAU_S:.4,MOTION_DEADBAND_IOD_PER_S:.1,READY_WINDOW_MS:500,GUIDE_SIZE:.6,GUIDE_CENTERING:.6,GUIDE_POSE:.6,GUIDE_EXPOSURE:.6,GUIDE_SHARPNESS:.35,GUIDE_MOTION:.5}),_=i=>Math.min(1,Math.max(0,i)),k=class{constructor(e={}){this.p=0;this.lastTickAt=null;this.lastCenter=null;this.velocityEma=0;this.qWindow=[];this.lastSizeDirection="ideal";this.t={...ze,...e}}reset(){this.p=0,this.lastTickAt=null,this.lastCenter=null,this.velocityEma=0,this.qWindow=[],this.lastSizeDirection="ideal"}tick(e){let{observation:t,quality:r,timestampMs:n}=e,a=this.lastTickAt===null?0:Math.max(0,(n-this.lastTickAt)/1e3);this.lastTickAt=n;let s={presence:0,single:1,centering:0,size:0,pose:0,sharpness:_(r.sharpness),exposure:_(r.exposure),motion:1};if(t!==null){s.presence=1,s.single=(t.extraFaces??0)>0?0:1;let d=this.geometryOf(t,e);s.centering=d.centering,s.size=d.size,s.pose=d.pose,s.motion=this.motionOf(d.center,d.iod,n)}else this.lastCenter=null,this.velocityEma=0;let o=Math.min(s.presence,s.single,s.centering,s.size,s.pose,s.sharpness,s.exposure,s.motion);this.p=_(this.p+(o>=this.t.Q_GOOD?this.t.RISE_PER_S*o:-this.t.FALL_PER_S*(1-o))*a),this.qWindow.push({at:n,q:o}),this.qWindow=this.qWindow.filter(d=>d.at>=n-this.t.READY_WINDOW_MS);let c=this.qWindow.map(d=>d.q);if(c.length>=3){let d=Math.min(...c),u=c.indexOf(d);c=c.filter((f,g)=>g!==u)}let l=this.p>=1&&c.every(d=>d>=this.t.Q_GOOD);return{at:n,q:o,p:this.p,factors:s,guidanceKey:this.guidanceOf(s,r,o),ready:l,accepted:o>=this.t.Q_GOOD}}geometryOf(e,t){let{box:r,eyes:n}=e,a={x:t.frameWidth/2,y:t.frameHeight/2},s=Math.min(t.frameWidth,t.frameHeight),o=n!==void 0?{x:(n.left.x+n.right.x)/2,y:(n.left.y+n.right.y)/2}:{x:r.x+r.width/2,y:r.y+r.height/2-this.t.BOX_EYE_OFFSET_FACTOR*r.height},c=n!==void 0?Math.hypot(n.right.x-n.left.x,n.right.y-n.left.y):this.t.IOD_BOX_PROXY_FACTOR*r.width,l=Math.hypot(o.x-a.x,o.y-a.y),d=c<=0?0:1-_(l/(this.t.CENTER_FALLOFF_IOD_MULTIPLE*c)),u=s>0?c/s:0;this.lastSizeDirection=u<this.t.SIZE_IDEAL_MIN?"far":u>this.t.SIZE_IDEAL_MAX?"close":"ideal";let f;u<this.t.SIZE_HARD_MIN||u>this.t.SIZE_HARD_MAX?f=0:u<this.t.SIZE_IDEAL_MIN?f=(u-this.t.SIZE_HARD_MIN)/(this.t.SIZE_IDEAL_MIN-this.t.SIZE_HARD_MIN):u>this.t.SIZE_IDEAL_MAX?f=(this.t.SIZE_HARD_MAX-u)/(this.t.SIZE_HARD_MAX-this.t.SIZE_IDEAL_MAX):f=1;let g=1;if(n!==void 0){let p=Math.abs(Math.atan2(n.right.y-n.left.y,n.right.x-n.left.x))*180/Math.PI;g=1-_(p/this.t.ROLL_MAX_DEG)}return{center:o,iod:c,centering:d,size:f,pose:g}}motionOf(e,t,r){let n=this.lastCenter;if(this.lastCenter={...e,at:r},n===null||t<=0)return 1;let a=(r-n.at)/1e3;if(a<=0)return 1;let s=Math.hypot(e.x-n.x,e.y-n.y)/t/a;s<=this.t.MOTION_DEADBAND_IOD_PER_S&&(s=0);let o=1-Math.exp(-a/this.t.MOTION_TAU_S);return this.velocityEma=o*s+(1-o)*this.velocityEma,1-_(this.velocityEma/this.t.MOTION_VELOCITY_IOD_PER_S)}guidanceOf(e,t,r){if(e.presence<=0)return"fcv3.no_face";if(e.single<=0)return"fcv3.one_face";if(e.size<this.t.GUIDE_SIZE)return this.sizeGuidance();if(e.centering<this.t.GUIDE_CENTERING)return"fcv3.center_face";if(e.pose<this.t.GUIDE_POSE)return"fcv3.straighten";if(e.exposure<this.t.GUIDE_EXPOSURE)return this.exposureGuidance(t);if(e.sharpness<this.t.GUIDE_SHARPNESS)return"fcv3.steady_camera";if(e.motion<this.t.GUIDE_MOTION)return"fcv3.hold_still";if(r<this.t.Q_GOOD){let n=[["size",this.sizeGuidance()],["centering","fcv3.center_face"],["pose","fcv3.straighten"],["exposure",this.exposureGuidance(t)],["sharpness","fcv3.steady_camera"],["motion","fcv3.hold_still"]],a=n[0];for(let s of n)e[s[0]]<e[a[0]]&&(a=s);return a[1]}return"fcv3.hold_still"}sizeGuidance(){return this.lastSizeDirection==="far"?"fcv3.come_closer":"fcv3.move_back"}exposureGuidance(e){let t=(L[0]+L[1])/2;return e.meanLuma<t?"fcv3.more_light":"fcv3.too_bright"}};var Xe=["single","size","centering","pose","exposure","sharpness","motion"];function Ze(i){if(i.accepted)return null;if(i.factors.presence<=0)return"no_face";let e="single";for(let t of Xe)i.factors[t]<i.factors[e]&&(e=t);return e}var w=class{constructor(){this.blocked={};this.acceptedMs=0;this.ticks=0;this.lastAt=null}record(e){let t=this.lastAt===null?0:Math.max(0,e.at-this.lastAt);this.lastAt=e.at,this.ticks+=1;let r=Ze(e);if(r===null){this.acceptedMs+=t;return}let n=this.blocked[r]??{count:0,ms:0};n.count+=1,n.ms+=t,this.blocked[r]=n}summary(){let e={};for(let[t,r]of Object.entries(this.blocked))e[t]={count:r.count,ms:Math.round(r.ms)};return{blocked:e,acceptedMs:Math.round(this.acceptedMs),ticks:this.ticks}}};var Qe=["obs","manycam","virtual","snap camera","xsplit","droidcam","iriun","camo"],Ye=[/^(front|back|rear)( [a-z ]+)? camera$/i,/^caméra (avant|arrière)\b/i,/^cámara (frontal|trasera|delantera)\b/i,/^câmera (frontal|traseira)\b/i,/^(front|rück)kamera\b/i,/^الكاميرا (الأمامية|الخلفية)/,/^camera2? ?\d+, facing (front|back|external)/i,/facetime/i,/\b(integrated|built-in|builtin) (web)?cam(era)?\b/i,/\b(hd )?web ?cam\b/i,/\([0-9a-f]{4}:[0-9a-f]{4}\)\s*$/i];function je(i){let e=(i??"").trim().toLowerCase();return e.length===0?"unknown":Qe.some(t=>e.includes(t))?"known_virtual":Ye.some(t=>t.test(e))?"platform":"unknown"}function Te(i){if(typeof i!="function")return!1;try{return/\{\s*\[native code\]\s*\}\s*$/.test(Function.prototype.toString.call(i))}catch{return!1}}function $e(i=globalThis){return Te(i.navigator?.mediaDevices?.getUserMedia)&&Te(i.MediaStreamTrack?.prototype?.getSettings)}async function Je(i,e=globalThis){let t=e.crypto?.subtle?.digest;if(typeof t=="function")try{let r=new Uint8Array(await t.call(e.crypto?.subtle,"SHA-256",new TextEncoder().encode(i)));return Array.from(r.subarray(0,8),n=>n.toString(16).padStart(2,"0")).join("")}catch{return}}async function Ce(i,e=globalThis){let t={};try{t=typeof i.getSettings=="function"?i.getSettings()??{}:{}}catch{t={}}let r={};if((t.facingMode==="user"||t.facingMode==="environment"||t.facingMode==="left"||t.facingMode==="right")&&(r.facingMode=t.facingMode),typeof t.frameRate=="number"&&Number.isFinite(t.frameRate)&&(r.frameRate=t.frameRate),typeof t.width=="number"&&Number.isFinite(t.width)&&(r.width=t.width),typeof t.height=="number"&&Number.isFinite(t.height)&&(r.height=t.height),typeof t.deviceId=="string"&&t.deviceId.length>0){let a=await Je(t.deviceId,e);a!==void 0&&(r.deviceIdHash=a)}let n;try{n=i.label}catch{n=void 0}return{trackSettings:r,capabilitiesPresent:typeof i.getCapabilities=="function",labelClass:je(n),prototypesIntact:$e(e)}}var K=i=>Math.round(i*100)/100;function Ee(i){let e=i,t=typeof e?.requestVideoFrameCallback=="function",r=null,n=null,a=0,s=0,o=0,c=0,l=0,d=0,u=()=>{!t||e?.requestVideoFrameCallback===void 0||(r=e.requestVideoFrameCallback((f,g)=>{if(r=null,!t)return;let p=g.presentationTime;if(n!==null){let m=p-n.presentationTimeMs;s+=1;let y=m-o;o+=y/s,c+=y*(m-o)}typeof g.captureTime=="number"&&Number.isFinite(g.captureTime)&&(l+=p-g.captureTime,d+=1),a+=1,n={mediaTimeMs:g.mediaTime*1e3,presentationTimeMs:p},u()}))};return u(),{latest:()=>n,stats:()=>({n:a,meanGapMs:s===0?0:K(o),stdGapMs:s<2?0:K(Math.sqrt(c/(s-1))),captureLatencyMs:d===0?null:K(l/d)}),stop:()=>{t&&(t=!1,r!==null&&e?.cancelVideoFrameCallback?.(r),r=null)}}}function _e(i,e,t){return{...i,rvfc:e,rampPainter:t}}var et=1e3,B="fcv3.hold_upright",tt=200,W=4,rt=600,nt=1e3,Re={sharpness:1,exposure:1,meanLuma:128};function it(i,e){return e.width=i.videoWidth,e.height=i.videoHeight,e.getContext("2d").drawImage(i,0,0),new Promise((t,r)=>e.toBlob(n=>n?t(n):r(new Error("empty-keyframe")),"image/jpeg",.92))}function at(){return X()==="phone"}var ke=class{constructor(e){this.handlers=new Map;this.stateValue="idle";this.attempt=0;this.stream=null;this.detector=null;this.scheduler=null;this.gate=null;this.profiler=null;this.lastGuidanceKey=null;this.positioningStartedAt=0;this.cameraRequestedAt=null;this.cameraReadyAt=null;this.faceAcquiredAt=null;this.captureCompleteAt=null;this.fired=!1;this.carriedDegrade=0;this.carriedMeans=[];this.blockStats=null;this.lastGateSnapshotAt=Number.NEGATIVE_INFINITY;this.uprightGuard=!1;this.trackProvenance=null;this.ramp=null;this.snapshotCanvas=null;this.options=e,this.facing=e.facingMode??"user"}get state(){return this.stateValue}on(e,t){let r=this.handlers.get(e);return r||(r=new Set,this.handlers.set(e,r)),r.add(t),()=>r?.delete(t)}emit(e,t){for(let r of[...this.handlers.get(e)??[]])r(t)}async start(e={}){e.facingMode!==void 0&&(this.facing=e.facingMode),this.attempt+=1,await this.run(this.attempt)}get facingMode(){return this.facing}retry(){this.teardownAttempt(),this.start()}switchCamera(){this.facing=this.facing==="user"?"environment":"user",this.teardownAttempt(),this.start()}restart(e){this.facing=e,this.teardownAttempt(),this.start()}destroy(){this.attempt+=1,this.teardownAttempt(),this.detector?.destroy(),this.detector=null,this.options.video.srcObject=null}async run(e){let{options:t}=this;this.fired=!1,this.lastGuidanceKey=null,this.carriedDegrade=0,this.carriedMeans=[],this.cameraRequestedAt=null,this.cameraReadyAt=null,this.faceAcquiredAt=null,this.captureCompleteAt=null,this.uprightGuard=(t.isPhone??at)(),this.setState("preflight");let r=$();if(r!=="OK"){this.fail(r==="INSECURE_CONTEXT"?"insecure":"unsupported",{phase:"preflight"});return}this.setState("acquiring");let n=t.getUserMedia??(l=>navigator.mediaDevices.getUserMedia(l)),a;this.cameraRequestedAt=this.now();try{let{facingMode:l,...d}=z(Z(),this.facing).video;a=await ie(this.facing,d,{getUserMedia:n,enumerateDevices:lt(t)})}catch(l){if(e!==this.attempt)return;if(l instanceof ne){this.fail("backcamera",{phase:"acquiring",name:R(l)});return}this.fail(ee(l),{phase:"acquiring",name:R(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:Ce(s).catch(()=>null),this.facing=Q(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&&oe()?async()=>{try{return await le.create(t.createWorker(),l)}catch{return G(l)}}:()=>G(l)),u;try{u=await d()}catch(f){e===this.attempt&&this.fail("models",{phase:"models",name:R(f)},f instanceof ae?f.fallbackReason:ot(f));return}if(e!==this.attempt){u.destroy();return}this.detector=u,this.options.telemetry?.({type:"detector",tier:u.tier,fallbackReason:u.fallbackReason})}let o=ce(),c=t.deviceClass??ue(o);this.profiler=new de(c),this.options.telemetry?.({type:"profile",staticClass:c,activeClass:this.profiler.deviceClass,simd:o.simd}),this.gate=new k(t.thresholds??{}),this.blockStats=new w,this.lastGateSnapshotAt=this.now(),t.rankKeyframes?.()&&import("./keyframe-rank-YAJLYJYF.js").then(l=>q=l,()=>{}),this.setState("positioning"),this.positioningStartedAt=this.now(),this.startScheduler(e)}get animations(){return this.profiler?.profile.animations??"full"}startScheduler(e){let t=this.profiler;if(t===null)return;if(this.scheduler!==null){let n=this.scheduler.stats();this.carriedDegrade+=n.degradeCount,n.meanDetectMs>0&&this.carriedMeans.push(n.meanDetectMs),this.scheduler.stop()}let r=new P({cadenceHz:t.profile.cadenceHz,video:this.options.video,now:this.options.now,run:()=>this.detectTick(e)});this.scheduler=r,r.start()}async detectTick(e){let{detector:t,gate:r,profiler:n}=this,a=this.options.video;if(e!==this.attempt||t===null||r===null||n===null||this.fired||a.videoWidth===0)return;if(this.isLandscape()){this.holdUpright(e);return}let s=n.deviceClass,o=this.now(),c=this.options.makeSnapshot?.(a,n.profile.inputWidth)??this.defaultSnapshot(a,n.profile.inputWidth),l=null;try{l=await t.detect(c,a.videoWidth,a.videoHeight)}catch{l=null}if(e!==this.attempt||this.fired)return;n.record(this.now()-o),n.deviceClass!==s&&this.startScheduler(e);let d=l===null?Re:this.options.measureQuality?.(a,l.box)??this.defaultQuality(a,l.box),u=r.tick({timestampMs:this.now(),observation:l,quality:d,frameWidth:a.videoWidth,frameHeight:a.videoHeight});u.accepted&&this.faceAcquiredAt===null&&(this.faceAcquiredAt=u.at),this.blockStats?.record(u),!u.ready&&u.at-this.lastGateSnapshotAt>=et&&(this.lastGateSnapshotAt=u.at,this.reportGate(!1)),this.emit("checks",{engine:"v3",progress:u.p,q:u.q,factors:u.factors,attempt:e}),u.guidanceKey!==this.lastGuidanceKey&&(this.lastGuidanceKey=u.guidanceKey,this.emit("guidance",{key:u.guidanceKey})),u.ready&&this.stateValue==="positioning"&&(this.fired=!0,this.captureCompleteAt=u.at,this.fire(e))}async fire(e){let{options:t}=this,r=this.scheduler;r?.stop(),this.reportGate(!0);let n=r?.stats()??{degradeCount:0,meanDetectMs:0},a=[...this.carriedMeans,...n.meanDetectMs>0?[n.meanDetectMs]:[]];t.telemetry?.({type:"fired",timeToGateMs:this.now()-this.positioningStartedAt,degradeCount:this.carriedDegrade+n.degradeCount,meanDetectMs:a.length===0?0:a.reduce((M,v)=>M+v,0)/a.length});let s=t.mode??"clip",o=t.rankKeyframes?.()&&q?q.default(this,e).catch(()=>this.collectKeyframes(e)):this.collectKeyframes(e);if(s==="photo"){let M=this.watchRotation(e,null),v=await o;if(M(),e!==this.attempt)return;if(v===null){this.fail("generic",{phase:"keyframes"});return}let x=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,...x});return}this.setState("recording");let c=this.stream;if(c===null){this.fail("generic",{phase:"recording"});return}let l=t.screenRamp?.(),d=O(l),u=null;o.then(M=>{u=M},()=>{});let f=()=>{e===this.attempt&&u!==null&&this.emit("frozen",{previewDataUrl:u.previewDataUrl})},g=ye(l,U),p=null,m,y=0;try{let M=this.recordTake(e,c,l,g,void 0).then(T=>T,T=>({failed:T})),[v,x]=await Promise.all([M,o]);if(m=x,e!==this.attempt)return;if("failed"in v){if(v.failed.kind==="cliptoolarge")throw v.failed;V(v.failed.requestedMimeType??"")}else p=v,H(v.clip,g)?v.clip.stats===null&&V(v.clip.requestedMimeType??""):f();if(p===null||H(p.clip,g)){y=1,t.telemetry?.({type:"clip_retake",reason:p===null?"error":p.clip.stats===null?"unreadable":"short"});let T=null;try{T=await this.recordTake(e,c,l,g,f)}catch(Ae){if(p===null)throw Ae}if(e!==this.attempt)return;T!==null&&(p===null||be(T.clip,p.clip))&&(p=T),T===null&&f()}}catch(M){if(e!==this.attempt)return;let v=M.kind;this.fail(v==="cliptoolarge"?"cliptoolarge":"recorder",{phase:"recording",name:R(M)});return}if(p===null){this.fail("recorder",{phase:"recording"});return}let{clip:h,rvfc:b,report:C}=p;if(A(h.blob)){this.fail("cliptoolarge",{phase:"recording"});return}if(m===null){this.fail("generic",{phase:"keyframes"});return}let E=await this.provenance(b,d);e===this.attempt&&this.finishCapture({clip:h.blob,clipMimeType:h.mimeType,...h.stats?{clipStats:h.stats}:{},clipRetakes:y,keyframe:m.blob,previewDataUrl:m.previewDataUrl,...C!==void 0&&C.rendered.length>0?{screenRamp:C}:{},...E})}async recordTake(e,t,r,n,a){let s=this.options.createRecorder?.()??new I({now:()=>this.now()}),o=Ee(this.options.video),c=Me(r,{paint:u=>{(u===null||e===this.attempt)&&this.emit("ramp",{colour:u})},now:()=>this.now(),frames:o.latest});this.ramp=c;let l=()=>{o.stop(),c.stop(),this.ramp===c&&(this.ramp=null)},d=this.watchRotation(e,s);try{return{clip:await s.record(t,a,()=>c.started(this.now()),n,o),rvfc:o.stats(),report:c.report()}}finally{d(),l()}}async provenance(e,t){let r=this.trackProvenance;if(r===null)return{};let n,a=new Promise(o=>{n=setTimeout(()=>o(null),nt)}),s=await Promise.race([r,a]);return clearTimeout(n),s===null?{}:{provenance:_e(s,e,t)}}isLandscape(){let e=this.options.video;return this.uprightGuard&&e.videoWidth>e.videoHeight}holdUpright(e){this.gate?.reset(),this.emit("checks",{engine:"v3",progress:0,q:0,factors:{presence:0,single:1,centering:0,size:0,pose:0,sharpness:0,exposure:0,motion:0},attempt:e}),this.lastGuidanceKey!==B&&(this.lastGuidanceKey=B,this.emit("guidance",{key:B}))}watchRotation(e,t){if(!this.uprightGuard)return()=>{};let r=this.options.video,n=()=>{if(e!==this.attempt||t!==null&&this.stateValue!=="recording"){o();return}r.videoWidth>0&&this.isLandscape()&&(o(),this.abortRecording(e,t))},a=setInterval(n,tt);r.addEventListener?.("resize",n);let s=!1;function o(){s||(s=!0,clearInterval(a),r.removeEventListener?.("resize",n))}return o}abortRecording(e,t){if(e!==this.attempt)return;this.attempt+=1;let r=this.attempt;try{t?.stop()}catch{}this.ramp?.stop(),this.ramp=null,this.fired=!1,this.captureCompleteAt=null,this.gate=new k(this.options.thresholds??{}),this.blockStats=new w,this.lastGateSnapshotAt=this.now(),this.lastGuidanceKey=null,this.setState("positioning"),this.positioningStartedAt=this.now(),this.holdUpright(r),this.startScheduler(r)}async collectKeyframes(e){let t=this.options.captureKeyframe??(a=>this.defaultKeyframe(a)),r=rt/(W-1),n=null;for(let a=0;a<W;a+=1){if(e!==this.attempt)return n;try{let s=await t(this.options.video);(n===null||s.sharpness>n.sharpness)&&(n=s)}catch{}a<W-1&&await st(r)}return n}finishCapture(e){this.stopTracks(),this.setState("captured");let t=this.captureTiming();this.emit("artifacts",t===void 0?e:{...e,timing:t})}captureTiming(){let e={},t=(r,n,a)=>{n!==null&&a!==null&&(e[r]=Math.max(0,Math.round(a-n)))};return t("cameraReadyMs",this.cameraRequestedAt,this.cameraReadyAt),t("faceAcquireMs",this.cameraReadyAt,this.faceAcquiredAt),t("captureMs",this.faceAcquiredAt,this.captureCompleteAt),Object.keys(e).length>0?e:void 0}async defaultKeyframe(e){let t=document.createElement("canvas"),r=await(this.facing==="user"?Se:it)(e,t),n=t.toDataURL("image/jpeg",.92);return{blob:r,previewDataUrl:n,sharpness:this.centerSharpness(e)}}defaultSnapshot(e,t){try{let r=this.snapshotCanvas??document.createElement("canvas"),n=t/Math.max(1,e.videoWidth),a=Math.max(1,Math.round(e.videoWidth*n)),s=Math.max(1,Math.round(e.videoHeight*n)),o=r.getContext("2d");return o===null?e:(r.width!==a&&(r.width=a),r.height!==s&&(r.height=s),o.drawImage(e,0,0,a,s),this.snapshotCanvas=r,r)}catch{return e}}defaultQuality(e,t){let r=we(e,t,96);return r===null?Re:{sharpness:F(r),exposure:me(r),meanLuma:pe(r)}}centerSharpness(e){let t=se(e),r=we(e,{x:t.width*.25,y:t.height*.25,width:t.width*.5,height:t.height*.5},96);return r===null?0:F(r)}teardownAttempt(){this.scheduler?.stop(),this.scheduler=null,this.reportGate(!0),this.gate=null,this.ramp?.stop(),this.ramp=null,this.stopTracks()}reportGate(e){let t=this.blockStats,r=this.profiler;if(t===null||r===null)return;let n=t.summary();e&&(this.blockStats=null),n.ticks!==0&&this.options.telemetry?.({type:"gate",final:e,activeClass:r.deviceClass,cadenceHz:r.profile.cadenceHz,...n})}stopTracks(){if(this.stream!==null){for(let e of this.stream.getTracks())e.stop();this.stream=null}}fail(e,t,r){this.scheduler?.stop(),this.reportGate(!0),this.stopTracks(),this.setState("error"),this.options.telemetry?.({type:"error",kind:e,fallbackReason:r});let{phase:n,name:a}=t;this.emit("error",{kind:e,retryable:e!=="insecure"&&e!=="unsupported",detail:a===void 0?{phase:n}:{phase:n,name:a}})}setState(e){this.stateValue=e,this.emit("statechange",{state:e})}now(){return this.options.now?.()??performance.now()}},q;function st(i){return new Promise(e=>setTimeout(e,i))}function ot(i){return i instanceof Error?i.message:String(i)}function we(i,e,t){try{let r=document.createElement("canvas"),n=t/Math.max(1,e.width);r.width=Math.max(1,Math.round(e.width*n)),r.height=Math.max(1,Math.round(e.height*n));let a=r.getContext("2d");return a===null?null:(a.drawImage(i,e.x,e.y,e.width,e.height,0,0,r.width,r.height),a.getImageData(0,0,r.width,r.height))}catch{return null}}function lt(i){if(i.enumerateDevices!==void 0)return i.enumerateDevices;if(i.getUserMedia===void 0&&!(typeof navigator>"u"||typeof navigator.mediaDevices?.enumerateDevices!="function"))return()=>navigator.mediaDevices.enumerateDevices()}export{ut as a,U as b,Pe as c,xe as d,ve as e,Ge as f,Le as g,Fe as h,Ve as i,S as j,Ue as k,H as l,be as m,I as n,Ke as o,ft as p,Se as q,P as r,ze as s,k as t,Ze as u,w as v,et as w,B as x,tt as y,W as z,rt as A,nt as B,ke as C};
1
+ import{a as ne,b as ie}from"./chunk-SX7TUC3V.js";import{b as ce,c as ue,d as de}from"./chunk-POIQGEZM.js";import{a as Y,c as j,e as $,g as J,h as A,k as R,m as ee,n as re}from"./chunk-CPUECYAJ.js";import{b as L,c as pe,d as F,e as me}from"./chunk-FPXL63KZ.js";import{a as z,c as X,d as Z,e as Q}from"./chunk-TSA6GHUG.js";import{d as te}from"./chunk-IA5M34P7.js";import{e as ae,f as se,h as G,j as oe,l as le}from"./chunk-FSSMUAKC.js";var Ie=[...Y.filter(i=>i.startsWith("video/mp4")),"video/webm;codecs=h264","video/webm;codecs=avc1","video/webm;codecs=vp8","video/webm;codecs=vp9","video/webm"],he=new Set;function De(i){let e=/(?:Chrome|Chromium)\/(\d+)\./.exec(i??"");return e?Number(e[1]):null}function fe(i=Oe(),e=globalThis.navigator?.userAgent){if(i===void 0)return"";let t=De(e)===126;for(let r of Ie)if(!(he.has(r)||t&&r.startsWith("video/mp4")))try{if(i(r))return r}catch{}return""}function V(i){i!==""&&he.add(i)}function ge(i){return i.replace(/^video\/x-matroska/i,"video/webm")}function ut(i){let e=/codecs=["']?([^,;"']+)/i.exec(i);return e?e[1].trim():i.split(";")[0].trim()}function Oe(){let i=globalThis.MediaRecorder;return i&&typeof i.isTypeSupported=="function"?e=>i.isTypeSupported(e):void 0}var U=2500,Pe=1e3,xe=1500,ve=25e5,Ge=100,Le=700,Fe=20,Ve=1500,N=null;function Ne(){return N??(N=import("./clip-inspect-DLJXVKV6.js").catch(i=>{throw N=null,i})),N.catch(()=>null)}var S=class extends Error{constructor(e,t){super(t??e),this.kind=e}},Ue=100;function H(i,e){return i.stats===void 0?!1:i.stats===null?!0:i.stats.durationMs<e-Ue}function be(i,e){return i.stats?e.stats?i.stats.durationMs>e.stats.durationMs:!0:!1}var I=class{constructor(e={}){this.recorder=null;this.stream=null;this.chunks=[];this.bytes=0;this.hardStopTimer=null;this.graceTimer=null;this.pollTimer=null;this.settled=!1;this.now=e.now??(()=>globalThis.performance?.now?.()??Date.now())}clearTimers(){this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.graceTimer&&clearTimeout(this.graceTimer),this.pollTimer&&clearInterval(this.pollTimer),this.hardStopTimer=null,this.graceTimer=null,this.pollTimer=null}record(e,t,r,n=U,a){let s=fe(),o=Ne();return this.recordRaw(e,t,r,n,a,s).then(c=>He(c,o),c=>{throw c instanceof S&&(c.requestedMimeType=s),c})}recordRaw(e,t,r,n,a,s){return this.recorder&&!this.settled?Promise.reject(new S("generic","record() called while a recording is in flight \u2014 ClipRecorder handles one recording at a time")):(this.recorder=null,this.clearTimers(),this.chunks=[],this.bytes=0,this.settled=!1,this.stream=e,new Promise((o,c)=>{let l;try{l=new MediaRecorder(e,s?{mimeType:s,videoBitsPerSecond:ve}:{videoBitsPerSecond:ve})}catch{try{l=new MediaRecorder(e)}catch{c(new S("unsupported"));return}}this.recorder=l;let d=h=>{this.settled||(this.settled=!0,this.clearTimers(),h())},u=()=>d(()=>{let h=ge(l.mimeType||s||j),b=new Blob(this.chunks,{type:h});if(b.size===0){c(new S("generic","empty clip"));return}if(A(b)){c(new S("cliptoolarge"));return}o({blob:b,mimeType:h,requestedMimeType:s})});l.ondataavailable=h=>{h.data&&h.data.size&&(this.chunks.push(h.data),this.bytes+=h.data.size,this.bytes>J&&d(()=>{try{l.state!=="inactive"&&l.stop()}catch{}c(new S("cliptoolarge"))}))},l.onstop=u,l.onerror=()=>d(()=>c(new S("generic")));let f=this.now();if(r!==void 0||a!==void 0){let h=!1;l.onstart=()=>{if(!(h||this.settled)&&(h=!0,f=this.now(),r!==void 0))try{r()}catch{}}}try{l.start(Pe)}catch{d(()=>c(new S("generic")));return}let g=()=>{if(this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=null,this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.hardStopTimer=null,this.settled||t?.(),l.state!=="inactive"){try{l.stop()}catch{u()}this.graceTimer=setTimeout(u,xe)}else u()},p=this.now();if(a===void 0){this.hardStopTimer=setTimeout(g,n);return}let m=null,y=!1;this.hardStopTimer=setTimeout(g,n+Le),this.pollTimer=setInterval(()=>{if(this.settled||y)return;let h=null;try{h=a.latest()}catch{h=null}let b=h?.presentationTimeMs;b!==void 0&&Number.isFinite(b)&&b>=f&&m===null&&(m=b);let C=m!==null&&b!==void 0&&b-m>=n,E=m===null&&this.now()-p>=n;if(!(!C&&!E)){if(y=!0,this.pollTimer&&clearInterval(this.pollTimer),this.pollTimer=null,E){g();return}this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.hardStopTimer=setTimeout(g,Ge)}},Fe)}))}stop(e){this.clearTimers();let t=this.recorder;if(t&&t.state!=="inactive")try{t.stop()}catch{}this.recorder=null,(e??this.stream)?.getTracks().forEach(n=>n.stop()),this.stream=null}};async function He(i,e){let t,r=new Promise(l=>{t=setTimeout(()=>l(null),Ve)}),n=await Promise.race([e,r]);if(clearTimeout(t),n===null)return i;let a;try{a=await n.blobBytes(i.blob)}catch{return{...i,stats:null}}let s=n.inspectClipBytes(a);if(s?.container!=="webm")return{...i,stats:s};let o=n.withWebmDuration(a,s.durationMs);if(o===null)return{...i,stats:s};let c=n.inspectClipBytes(o);return c===null||c.frames!==s.frames||c.durationMs!==s.durationMs?{...i,stats:s}:{...i,blob:new Blob([o],{type:i.blob.type}),stats:s}}var Ke=["magenta","yellow","green","blue"];var Be={magenta:"rgb(255, 72, 150)",yellow:"rgb(255, 190, 0)",green:"rgb(0, 238, 175)",blue:"rgb(25, 150, 255)",dark:"rgb(0, 0, 0)"};function ft(i){return Be[i]}var We=4,qe=4,D=i=>typeof i=="number"&&Number.isFinite(i);function O(i){if(typeof i!="object"||i===null)return!1;let e=i;if(typeof e.nonce!="string"||e.nonce.length===0||!Array.isArray(e.colours)||e.colours.length<1||e.colours.length>8||!e.colours.every(r=>Ke.includes(r))||!Array.isArray(e.onsetsMs)||e.onsetsMs.length!==e.colours.length)return!1;let t=-1;for(let r of e.onsetsMs){if(!D(r)||r<0||r<=t)return!1;t=r}return!(!D(e.holdMs)||e.holdMs<=0||!D(e.endMs)||e.endMs<=t||!D(e.clipMs)||e.clipMs<e.endMs||e.clipMs>8e3)}function ye(i,e){return O(i)?Math.max(e,Math.ceil(i.clipMs)):e}function Me(i,e){let t=e.now??(()=>performance.now()),r=O(i)?i:void 0,n=[],a=null,s=null,o=null,c=!1,l=null,d=p=>{l=p;try{e.paint(p)}catch{}},u=p=>{let m=e.frames?.()??null;return m!==null&&o!==null?m.mediaTimeMs+(p-m.presentationTimeMs)-o:p-(s??p)},f=(p,m,y=0)=>{if(c)return;let h=Math.max(0,p-u(t()));a=setTimeout(()=>{if(a=null,!c){if(y<We&&u(t())<p-qe){f(p,m,y+1);return}m()}},h)},g=p=>{if(r===void 0)return;let m=r.endMs;if(p>=r.colours.length){f(m,()=>d(null));return}let y=r.onsetsMs[p],h=p+1<r.onsetsMs.length?r.onsetsMs[p+1]:m;f(y,()=>{let b=u(t());if(b>m){l!==null&&d(null);return}let C=r.colours[p];d(C);let E=n.length===0?0:n[n.length-1].tMs;n.push({tMs:Math.max(E,Math.round(b)),colour:C});let M=y+r.holdMs;if(M<h){f(M,()=>{if(u(t())>m){l!==null&&d(null);return}d("dark"),g(p+1)});return}g(p+1)})};return{started(p){if(r===void 0||c||s!==null)return;s=p;let m=e.frames?.()??null;o=m===null?null:m.mediaTimeMs+(p-m.presentationTimeMs),g(0)},stop(){c||(c=!0,a!==null&&clearTimeout(a),a=null,l!==null&&d(null))},report(){return r===void 0?void 0:{nonce:r.nonce,rendered:[...n]}}}}function Se(i,e,t=.92){return new Promise((r,n)=>{let a=i.videoWidth,s=i.videoHeight;if(!a||!s){n(new Error("video-not-ready"));return}let o=e.getContext("2d");if(!o){n(new Error("no-2d-context"));return}e.width=a,e.height=s,o.scale(-1,1),o.drawImage(i,-a,0),e.toBlob(c=>c?r(c):n(new Error("empty-keyframe")),"image/jpeg",t)})}var P=class{constructor(e){this.timer=null;this.frameCallbackId=null;this.running=!1;this.busy=!1;this.lastRunAt=Number.NEGATIVE_INFINITY;this.degradeCount=0;this.durations=[];this.options=e,this.periodMs=1e3/e.cadenceHz}start(){if(this.running)return;this.running=!0;let e=this.options.video;if(typeof e?.requestVideoFrameCallback=="function"){let t=()=>{this.running&&(this.frameCallbackId=e.requestVideoFrameCallback?.(()=>{this.frameCallbackId=null,this.now()-this.lastRunAt>=this.periodMs&&this.tick(),t()}))};t();return}this.timer=setInterval(()=>this.tick(),this.periodMs)}stop(){this.running=!1,this.timer!==null&&(clearInterval(this.timer),this.timer=null),this.frameCallbackId!==null&&(this.options.video?.cancelVideoFrameCallback?.(this.frameCallbackId),this.frameCallbackId=null)}stats(){let e=this.durations.length===0?0:this.durations.reduce((t,r)=>t+r,0)/this.durations.length;return{degradeCount:this.degradeCount,meanDetectMs:e}}now(){return this.options.now?.()??performance.now()}tick(){if(!this.running)return;if(this.busy){this.degradeCount+=1;return}this.busy=!0,this.lastRunAt=this.now();let e=this.now();this.options.run().catch(()=>{}).finally(()=>{this.busy=!1,this.durations.push(this.now()-e),this.durations.length>20&&this.durations.shift()})}};var ze=Object.freeze({Q_GOOD:.6,RISE_PER_S:.9,FALL_PER_S:.25,CENTER_FALLOFF_IOD_MULTIPLE:1.35,BOX_EYE_OFFSET_FACTOR:.12,IOD_BOX_PROXY_FACTOR:.42,SIZE_IDEAL_MIN:.12,SIZE_IDEAL_MAX:.3,SIZE_HARD_MIN:.08,SIZE_HARD_MAX:.45,ROLL_MAX_DEG:25,MOTION_VELOCITY_IOD_PER_S:.5,MOTION_TAU_S:.4,MOTION_DEADBAND_IOD_PER_S:.1,READY_WINDOW_MS:500,GUIDE_SIZE:.6,GUIDE_CENTERING:.6,GUIDE_POSE:.6,GUIDE_EXPOSURE:.6,GUIDE_SHARPNESS:.35,GUIDE_MOTION:.5}),_=i=>Math.min(1,Math.max(0,i)),k=class{constructor(e={}){this.p=0;this.lastTickAt=null;this.lastCenter=null;this.velocityEma=0;this.qWindow=[];this.lastSizeDirection="ideal";this.t={...ze,...e}}reset(){this.p=0,this.lastTickAt=null,this.lastCenter=null,this.velocityEma=0,this.qWindow=[],this.lastSizeDirection="ideal"}tick(e){let{observation:t,quality:r,timestampMs:n}=e,a=this.lastTickAt===null?0:Math.max(0,(n-this.lastTickAt)/1e3);this.lastTickAt=n;let s={presence:0,single:1,centering:0,size:0,pose:0,sharpness:_(r.sharpness),exposure:_(r.exposure),motion:1};if(t!==null){s.presence=1,s.single=(t.extraFaces??0)>0?0:1;let d=this.geometryOf(t,e);s.centering=d.centering,s.size=d.size,s.pose=d.pose,s.motion=this.motionOf(d.center,d.iod,n)}else this.lastCenter=null,this.velocityEma=0;let o=Math.min(s.presence,s.single,s.centering,s.size,s.pose,s.sharpness,s.exposure,s.motion);this.p=_(this.p+(o>=this.t.Q_GOOD?this.t.RISE_PER_S*o:-this.t.FALL_PER_S*(1-o))*a),this.qWindow.push({at:n,q:o}),this.qWindow=this.qWindow.filter(d=>d.at>=n-this.t.READY_WINDOW_MS);let c=this.qWindow.map(d=>d.q);if(c.length>=3){let d=Math.min(...c),u=c.indexOf(d);c=c.filter((f,g)=>g!==u)}let l=this.p>=1&&c.every(d=>d>=this.t.Q_GOOD);return{at:n,q:o,p:this.p,factors:s,guidanceKey:this.guidanceOf(s,r,o),ready:l,accepted:o>=this.t.Q_GOOD}}geometryOf(e,t){let{box:r,eyes:n}=e,a={x:t.frameWidth/2,y:t.frameHeight/2},s=Math.min(t.frameWidth,t.frameHeight),o=n!==void 0?{x:(n.left.x+n.right.x)/2,y:(n.left.y+n.right.y)/2}:{x:r.x+r.width/2,y:r.y+r.height/2-this.t.BOX_EYE_OFFSET_FACTOR*r.height},c=n!==void 0?Math.hypot(n.right.x-n.left.x,n.right.y-n.left.y):this.t.IOD_BOX_PROXY_FACTOR*r.width,l=Math.hypot(o.x-a.x,o.y-a.y),d=c<=0?0:1-_(l/(this.t.CENTER_FALLOFF_IOD_MULTIPLE*c)),u=s>0?c/s:0;this.lastSizeDirection=u<this.t.SIZE_IDEAL_MIN?"far":u>this.t.SIZE_IDEAL_MAX?"close":"ideal";let f;u<this.t.SIZE_HARD_MIN||u>this.t.SIZE_HARD_MAX?f=0:u<this.t.SIZE_IDEAL_MIN?f=(u-this.t.SIZE_HARD_MIN)/(this.t.SIZE_IDEAL_MIN-this.t.SIZE_HARD_MIN):u>this.t.SIZE_IDEAL_MAX?f=(this.t.SIZE_HARD_MAX-u)/(this.t.SIZE_HARD_MAX-this.t.SIZE_IDEAL_MAX):f=1;let g=1;if(n!==void 0){let p=Math.abs(Math.atan2(n.right.y-n.left.y,n.right.x-n.left.x))*180/Math.PI;g=1-_(p/this.t.ROLL_MAX_DEG)}return{center:o,iod:c,centering:d,size:f,pose:g}}motionOf(e,t,r){let n=this.lastCenter;if(this.lastCenter={...e,at:r},n===null||t<=0)return 1;let a=(r-n.at)/1e3;if(a<=0)return 1;let s=Math.hypot(e.x-n.x,e.y-n.y)/t/a;s<=this.t.MOTION_DEADBAND_IOD_PER_S&&(s=0);let o=1-Math.exp(-a/this.t.MOTION_TAU_S);return this.velocityEma=o*s+(1-o)*this.velocityEma,1-_(this.velocityEma/this.t.MOTION_VELOCITY_IOD_PER_S)}guidanceOf(e,t,r){if(e.presence<=0)return"fcv3.no_face";if(e.single<=0)return"fcv3.one_face";if(e.size<this.t.GUIDE_SIZE)return this.sizeGuidance();if(e.centering<this.t.GUIDE_CENTERING)return"fcv3.center_face";if(e.pose<this.t.GUIDE_POSE)return"fcv3.straighten";if(e.exposure<this.t.GUIDE_EXPOSURE)return this.exposureGuidance(t);if(e.sharpness<this.t.GUIDE_SHARPNESS)return"fcv3.steady_camera";if(e.motion<this.t.GUIDE_MOTION)return"fcv3.hold_still";if(r<this.t.Q_GOOD){let n=[["size",this.sizeGuidance()],["centering","fcv3.center_face"],["pose","fcv3.straighten"],["exposure",this.exposureGuidance(t)],["sharpness","fcv3.steady_camera"],["motion","fcv3.hold_still"]],a=n[0];for(let s of n)e[s[0]]<e[a[0]]&&(a=s);return a[1]}return"fcv3.hold_still"}sizeGuidance(){return this.lastSizeDirection==="far"?"fcv3.come_closer":"fcv3.move_back"}exposureGuidance(e){let t=(L[0]+L[1])/2;return e.meanLuma<t?"fcv3.more_light":"fcv3.too_bright"}};var Xe=["single","size","centering","pose","exposure","sharpness","motion"];function Ze(i){if(i.accepted)return null;if(i.factors.presence<=0)return"no_face";let e="single";for(let t of Xe)i.factors[t]<i.factors[e]&&(e=t);return e}var w=class{constructor(){this.blocked={};this.acceptedMs=0;this.ticks=0;this.lastAt=null}record(e){let t=this.lastAt===null?0:Math.max(0,e.at-this.lastAt);this.lastAt=e.at,this.ticks+=1;let r=Ze(e);if(r===null){this.acceptedMs+=t;return}let n=this.blocked[r]??{count:0,ms:0};n.count+=1,n.ms+=t,this.blocked[r]=n}summary(){let e={};for(let[t,r]of Object.entries(this.blocked))e[t]={count:r.count,ms:Math.round(r.ms)};return{blocked:e,acceptedMs:Math.round(this.acceptedMs),ticks:this.ticks}}};var Qe=["obs","manycam","virtual","snap camera","xsplit","droidcam","iriun","camo"],Ye=[/^(front|back|rear)( [a-z ]+)? camera$/i,/^caméra (avant|arrière)\b/i,/^cámara (frontal|trasera|delantera)\b/i,/^câmera (frontal|traseira)\b/i,/^(front|rück)kamera\b/i,/^الكاميرا (الأمامية|الخلفية)/,/^camera2? ?\d+, facing (front|back|external)/i,/facetime/i,/\b(integrated|built-in|builtin) (web)?cam(era)?\b/i,/\b(hd )?web ?cam\b/i,/\([0-9a-f]{4}:[0-9a-f]{4}\)\s*$/i];function je(i){let e=(i??"").trim().toLowerCase();return e.length===0?"unknown":Qe.some(t=>e.includes(t))?"known_virtual":Ye.some(t=>t.test(e))?"platform":"unknown"}function Te(i){if(typeof i!="function")return!1;try{return/\{\s*\[native code\]\s*\}\s*$/.test(Function.prototype.toString.call(i))}catch{return!1}}function $e(i=globalThis){return Te(i.navigator?.mediaDevices?.getUserMedia)&&Te(i.MediaStreamTrack?.prototype?.getSettings)}async function Je(i,e=globalThis){let t=e.crypto?.subtle?.digest;if(typeof t=="function")try{let r=new Uint8Array(await t.call(e.crypto?.subtle,"SHA-256",new TextEncoder().encode(i)));return Array.from(r.subarray(0,8),n=>n.toString(16).padStart(2,"0")).join("")}catch{return}}async function Ce(i,e=globalThis){let t={};try{t=typeof i.getSettings=="function"?i.getSettings()??{}:{}}catch{t={}}let r={};if((t.facingMode==="user"||t.facingMode==="environment"||t.facingMode==="left"||t.facingMode==="right")&&(r.facingMode=t.facingMode),typeof t.frameRate=="number"&&Number.isFinite(t.frameRate)&&(r.frameRate=t.frameRate),typeof t.width=="number"&&Number.isFinite(t.width)&&(r.width=t.width),typeof t.height=="number"&&Number.isFinite(t.height)&&(r.height=t.height),typeof t.deviceId=="string"&&t.deviceId.length>0){let a=await Je(t.deviceId,e);a!==void 0&&(r.deviceIdHash=a)}let n;try{n=i.label}catch{n=void 0}return{trackSettings:r,capabilitiesPresent:typeof i.getCapabilities=="function",labelClass:je(n),prototypesIntact:$e(e)}}var K=i=>Math.round(i*100)/100;function Ee(i){let e=i,t=typeof e?.requestVideoFrameCallback=="function",r=null,n=null,a=0,s=0,o=0,c=0,l=0,d=0,u=()=>{!t||e?.requestVideoFrameCallback===void 0||(r=e.requestVideoFrameCallback((f,g)=>{if(r=null,!t)return;let p=g.presentationTime;if(n!==null){let m=p-n.presentationTimeMs;s+=1;let y=m-o;o+=y/s,c+=y*(m-o)}typeof g.captureTime=="number"&&Number.isFinite(g.captureTime)&&(l+=p-g.captureTime,d+=1),a+=1,n={mediaTimeMs:g.mediaTime*1e3,presentationTimeMs:p},u()}))};return u(),{latest:()=>n,stats:()=>({n:a,meanGapMs:s===0?0:K(o),stdGapMs:s<2?0:K(Math.sqrt(c/(s-1))),captureLatencyMs:d===0?null:K(l/d)}),stop:()=>{t&&(t=!1,r!==null&&e?.cancelVideoFrameCallback?.(r),r=null)}}}function _e(i,e,t){return{...i,rvfc:e,rampPainter:t}}var et=1e3,B="fcv3.hold_upright",tt=200,W=4,rt=600,nt=1e3,Re={sharpness:1,exposure:1,meanLuma:128};function it(i,e){return e.width=i.videoWidth,e.height=i.videoHeight,e.getContext("2d").drawImage(i,0,0),new Promise((t,r)=>e.toBlob(n=>n?t(n):r(new Error("empty-keyframe")),"image/jpeg",.92))}function at(){return X()==="phone"}var ke=class{constructor(e){this.handlers=new Map;this.stateValue="idle";this.attempt=0;this.stream=null;this.detector=null;this.scheduler=null;this.gate=null;this.profiler=null;this.lastGuidanceKey=null;this.positioningStartedAt=0;this.cameraRequestedAt=null;this.cameraReadyAt=null;this.faceAcquiredAt=null;this.captureCompleteAt=null;this.fired=!1;this.carriedDegrade=0;this.carriedMeans=[];this.blockStats=null;this.lastGateSnapshotAt=Number.NEGATIVE_INFINITY;this.uprightGuard=!1;this.trackProvenance=null;this.ramp=null;this.snapshotCanvas=null;this.options=e,this.facing=e.facingMode??"user"}get state(){return this.stateValue}on(e,t){let r=this.handlers.get(e);return r||(r=new Set,this.handlers.set(e,r)),r.add(t),()=>r?.delete(t)}emit(e,t){for(let r of[...this.handlers.get(e)??[]])r(t)}async start(e={}){e.facingMode!==void 0&&(this.facing=e.facingMode),this.attempt+=1,await this.run(this.attempt)}get facingMode(){return this.facing}retry(){this.teardownAttempt(),this.start()}switchCamera(){this.facing=this.facing==="user"?"environment":"user",this.teardownAttempt(),this.start()}restart(e){this.facing=e,this.teardownAttempt(),this.start()}destroy(){this.attempt+=1,this.teardownAttempt(),this.detector?.destroy(),this.detector=null,this.options.video.srcObject=null}async run(e){let{options:t}=this;this.fired=!1,this.lastGuidanceKey=null,this.carriedDegrade=0,this.carriedMeans=[],this.cameraRequestedAt=null,this.cameraReadyAt=null,this.faceAcquiredAt=null,this.captureCompleteAt=null,this.uprightGuard=(t.isPhone??at)(),this.setState("preflight");let r=$();if(r!=="OK"){this.fail(r==="INSECURE_CONTEXT"?"insecure":"unsupported",{phase:"preflight"});return}this.setState("acquiring");let n=t.getUserMedia??(l=>navigator.mediaDevices.getUserMedia(l)),a;this.cameraRequestedAt=this.now();try{let{facingMode:l,...d}=z(Z(),this.facing).video;a=await ie(this.facing,d,{getUserMedia:n,enumerateDevices:lt(t)})}catch(l){if(e!==this.attempt)return;if(l instanceof ne){this.fail("backcamera",{phase:"acquiring",name:R(l)});return}this.fail(ee(l),{phase:"acquiring",name:R(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:Ce(s).catch(()=>null),this.facing=Q(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&&oe()?async()=>{try{return await le.create(t.createWorker(),l)}catch{return G(l)}}:()=>G(l)),u;try{u=await d()}catch(f){e===this.attempt&&this.fail("models",{phase:"models",name:R(f)},f instanceof ae?f.fallbackReason:ot(f));return}if(e!==this.attempt){u.destroy();return}this.detector=u,this.options.telemetry?.({type:"detector",tier:u.tier,fallbackReason:u.fallbackReason})}let o=ce(),c=t.deviceClass??ue(o);this.profiler=new de(c),this.options.telemetry?.({type:"profile",staticClass:c,activeClass:this.profiler.deviceClass,simd:o.simd}),this.gate=new k(t.thresholds??{}),this.blockStats=new w,this.lastGateSnapshotAt=this.now(),t.rankKeyframes?.()&&import("./keyframe-rank-YAJLYJYF.js").then(l=>q=l,()=>{}),this.setState("positioning"),this.positioningStartedAt=this.now(),this.startScheduler(e)}get animations(){return this.profiler?.profile.animations??"full"}startScheduler(e){let t=this.profiler;if(t===null)return;if(this.scheduler!==null){let n=this.scheduler.stats();this.carriedDegrade+=n.degradeCount,n.meanDetectMs>0&&this.carriedMeans.push(n.meanDetectMs),this.scheduler.stop()}let r=new P({cadenceHz:t.profile.cadenceHz,video:this.options.video,now:this.options.now,run:()=>this.detectTick(e)});this.scheduler=r,r.start()}async detectTick(e){let{detector:t,gate:r,profiler:n}=this,a=this.options.video;if(e!==this.attempt||t===null||r===null||n===null||this.fired||a.videoWidth===0)return;if(this.isLandscape()){this.holdUpright(e);return}let s=n.deviceClass,o=this.now(),c=this.options.makeSnapshot?.(a,n.profile.inputWidth)??this.defaultSnapshot(a,n.profile.inputWidth),l=null;try{l=await t.detect(c,a.videoWidth,a.videoHeight)}catch{l=null}if(e!==this.attempt||this.fired)return;n.record(this.now()-o),n.deviceClass!==s&&this.startScheduler(e);let d=l===null?Re:this.options.measureQuality?.(a,l.box)??this.defaultQuality(a,l.box),u=r.tick({timestampMs:this.now(),observation:l,quality:d,frameWidth:a.videoWidth,frameHeight:a.videoHeight});u.accepted&&this.faceAcquiredAt===null&&(this.faceAcquiredAt=u.at),this.blockStats?.record(u),!u.ready&&u.at-this.lastGateSnapshotAt>=et&&(this.lastGateSnapshotAt=u.at,this.reportGate(!1)),this.emit("checks",{engine:"v3",progress:u.p,q:u.q,factors:u.factors,attempt:e}),u.guidanceKey!==this.lastGuidanceKey&&(this.lastGuidanceKey=u.guidanceKey,this.emit("guidance",{key:u.guidanceKey})),u.ready&&this.stateValue==="positioning"&&(this.fired=!0,this.captureCompleteAt=u.at,this.fire(e))}async fire(e){let{options:t}=this,r=this.scheduler;r?.stop(),this.reportGate(!0);let n=r?.stats()??{degradeCount:0,meanDetectMs:0},a=[...this.carriedMeans,...n.meanDetectMs>0?[n.meanDetectMs]:[]];t.telemetry?.({type:"fired",timeToGateMs:this.now()-this.positioningStartedAt,degradeCount:this.carriedDegrade+n.degradeCount,meanDetectMs:a.length===0?0:a.reduce((M,v)=>M+v,0)/a.length});let s=t.mode??"clip",o=t.rankKeyframes?.()&&q?q.default(this,e).catch(()=>this.collectKeyframes(e)):this.collectKeyframes(e);if(s==="photo"){let M=this.watchRotation(e,null),v=await o;if(M(),e!==this.attempt)return;if(v===null){this.fail("generic",{phase:"keyframes"});return}let x=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,...x});return}this.setState("recording");let c=this.stream;if(c===null){this.fail("generic",{phase:"recording"});return}let l=t.screenRamp?.(),d=O(l),u=null;o.then(M=>{u=M},()=>{});let f=()=>{e===this.attempt&&u!==null&&this.emit("frozen",{previewDataUrl:u.previewDataUrl})},g=ye(l,U),p=null,m,y=0;try{let M=this.recordTake(e,c,l,g,void 0).then(T=>T,T=>({failed:T})),[v,x]=await Promise.all([M,o]);if(m=x,e!==this.attempt)return;if("failed"in v){if(v.failed.kind==="cliptoolarge")throw v.failed;V(v.failed.requestedMimeType??"")}else p=v,H(v.clip,g)?v.clip.stats===null&&V(v.clip.requestedMimeType??""):f();if(p===null||H(p.clip,g)){y=1,t.telemetry?.({type:"clip_retake",reason:p===null?"error":p.clip.stats===null?"unreadable":"short"});let T=null;try{T=await this.recordTake(e,c,l,g,f)}catch(Ae){if(p===null)throw Ae}if(e!==this.attempt)return;T!==null&&(p===null||be(T.clip,p.clip))&&(p=T),T===null&&f()}}catch(M){if(e!==this.attempt)return;let v=M.kind;this.fail(v==="cliptoolarge"?"cliptoolarge":"recorder",{phase:"recording",name:R(M)});return}if(p===null){this.fail("recorder",{phase:"recording"});return}let{clip:h,rvfc:b,report:C}=p;if(A(h.blob)){this.fail("cliptoolarge",{phase:"recording"});return}if(m===null){this.fail("generic",{phase:"keyframes"});return}let E=await this.provenance(b,d);e===this.attempt&&this.finishCapture({clip:h.blob,clipMimeType:h.mimeType,...h.stats?{clipStats:h.stats}:{},clipRetakes:y,keyframe:m.blob,previewDataUrl:m.previewDataUrl,...C!==void 0&&C.rendered.length>0?{screenRamp:C}:{},...E})}async recordTake(e,t,r,n,a){let s=this.options.createRecorder?.()??new I({now:()=>this.now()}),o=Ee(this.options.video),c=Me(r,{paint:u=>{(u===null||e===this.attempt)&&this.emit("ramp",{colour:u})},now:()=>this.now(),frames:o.latest});this.ramp=c;let l=()=>{o.stop(),c.stop(),this.ramp===c&&(this.ramp=null)},d=this.watchRotation(e,s);try{return{clip:await s.record(t,a,()=>c.started(this.now()),n,o),rvfc:o.stats(),report:c.report()}}finally{d(),l()}}async provenance(e,t){let r=this.trackProvenance;if(r===null)return{};let n,a=new Promise(o=>{n=setTimeout(()=>o(null),nt)}),s=await Promise.race([r,a]);return clearTimeout(n),s===null?{}:{provenance:_e(s,e,t)}}isLandscape(){let e=this.options.video;return this.uprightGuard&&e.videoWidth>e.videoHeight}holdUpright(e){this.gate?.reset(),this.emit("checks",{engine:"v3",progress:0,q:0,factors:{presence:0,single:1,centering:0,size:0,pose:0,sharpness:0,exposure:0,motion:0},attempt:e}),this.lastGuidanceKey!==B&&(this.lastGuidanceKey=B,this.emit("guidance",{key:B}))}watchRotation(e,t){if(!this.uprightGuard)return()=>{};let r=this.options.video,n=()=>{if(e!==this.attempt||t!==null&&this.stateValue!=="recording"){o();return}r.videoWidth>0&&this.isLandscape()&&(o(),this.abortRecording(e,t))},a=setInterval(n,tt);r.addEventListener?.("resize",n);let s=!1;function o(){s||(s=!0,clearInterval(a),r.removeEventListener?.("resize",n))}return o}abortRecording(e,t){if(e!==this.attempt)return;this.attempt+=1;let r=this.attempt;try{t?.stop()}catch{}this.ramp?.stop(),this.ramp=null,this.fired=!1,this.captureCompleteAt=null,this.gate=new k(this.options.thresholds??{}),this.blockStats=new w,this.lastGateSnapshotAt=this.now(),this.lastGuidanceKey=null,this.setState("positioning"),this.positioningStartedAt=this.now(),this.holdUpright(r),this.startScheduler(r)}async collectKeyframes(e){let t=this.options.captureKeyframe??(a=>this.defaultKeyframe(a)),r=rt/(W-1),n=null;for(let a=0;a<W;a+=1){if(e!==this.attempt)return n;try{let s=await t(this.options.video);(n===null||s.sharpness>n.sharpness)&&(n=s)}catch{}a<W-1&&await st(r)}return n}finishCapture(e){this.stopTracks(),this.setState("captured");let t=this.captureTiming();this.emit("artifacts",t===void 0?e:{...e,timing:t})}captureTiming(){let e={},t=(r,n,a)=>{n!==null&&a!==null&&(e[r]=Math.max(0,Math.round(a-n)))};return t("cameraReadyMs",this.cameraRequestedAt,this.cameraReadyAt),t("faceAcquireMs",this.cameraReadyAt,this.faceAcquiredAt),t("captureMs",this.faceAcquiredAt,this.captureCompleteAt),Object.keys(e).length>0?e:void 0}async defaultKeyframe(e){let t=document.createElement("canvas"),r=await(this.facing==="user"?Se:it)(e,t),n=t.toDataURL("image/jpeg",.92);return{blob:r,previewDataUrl:n,sharpness:this.centerSharpness(e)}}defaultSnapshot(e,t){try{let r=this.snapshotCanvas??document.createElement("canvas"),n=t/Math.max(1,e.videoWidth),a=Math.max(1,Math.round(e.videoWidth*n)),s=Math.max(1,Math.round(e.videoHeight*n)),o=r.getContext("2d");return o===null?e:(r.width!==a&&(r.width=a),r.height!==s&&(r.height=s),o.drawImage(e,0,0,a,s),this.snapshotCanvas=r,r)}catch{return e}}defaultQuality(e,t){let r=we(e,t,96);return r===null?Re:{sharpness:F(r),exposure:me(r),meanLuma:pe(r)}}centerSharpness(e){let t=se(e),r=we(e,{x:t.width*.25,y:t.height*.25,width:t.width*.5,height:t.height*.5},96);return r===null?0:F(r)}teardownAttempt(){this.scheduler?.stop(),this.scheduler=null,this.reportGate(!0),this.gate=null,this.ramp?.stop(),this.ramp=null,this.stopTracks()}reportGate(e){let t=this.blockStats,r=this.profiler;if(t===null||r===null)return;let n=t.summary();e&&(this.blockStats=null),n.ticks!==0&&this.options.telemetry?.({type:"gate",final:e,activeClass:r.deviceClass,cadenceHz:r.profile.cadenceHz,...n})}stopTracks(){if(this.stream!==null){for(let e of this.stream.getTracks())e.stop();this.stream=null}}fail(e,t,r){this.scheduler?.stop(),this.reportGate(!0),this.stopTracks(),this.setState("error"),this.options.telemetry?.({type:"error",kind:e,fallbackReason:r});let{phase:n,name:a}=t;this.emit("error",{kind:e,retryable:e!=="insecure"&&e!=="unsupported",detail:a===void 0?{phase:n}:{phase:n,name:a}})}setState(e){this.stateValue=e,this.emit("statechange",{state:e})}now(){return this.options.now?.()??performance.now()}},q;function st(i){return new Promise(e=>setTimeout(e,i))}function ot(i){return i instanceof Error?i.message:String(i)}function we(i,e,t){try{let r=document.createElement("canvas"),n=t/Math.max(1,e.width);r.width=Math.max(1,Math.round(e.width*n)),r.height=Math.max(1,Math.round(e.height*n));let a=r.getContext("2d");return a===null?null:(a.drawImage(i,e.x,e.y,e.width,e.height,0,0,r.width,r.height),a.getImageData(0,0,r.width,r.height))}catch{return null}}function lt(i){if(i.enumerateDevices!==void 0)return i.enumerateDevices;if(i.getUserMedia===void 0&&!(typeof navigator>"u"||typeof navigator.mediaDevices?.enumerateDevices!="function"))return()=>navigator.mediaDevices.enumerateDevices()}export{ut as a,U as b,Pe as c,xe as d,ve as e,Ge as f,Le as g,Fe as h,Ve as i,S as j,Ue as k,H as l,be as m,I as n,Ke as o,ft as p,Se as q,P as r,ze as s,k as t,Ze as u,w as v,et as w,B as x,tt as y,W as z,rt as A,nt as B,ke as C};
@@ -0,0 +1 @@
1
+ import{c as P,d as H,e as A}from"./chunk-6AH7FXVC.js";var z=new Set(["nni_unbound","id_number_unbound","method_required","mobile_required","portrait_required"]);function Ce(e){return z.has(e)}function be(e,n,t){let i=n.detail;return{check:e,kind:n.kind,...i?.name!==void 0?{name:i.name}:{},...i?.phase!==void 0?{phase:i.phase}:{},...i?.engineKind!==void 0?{engineKind:i.engineKind}:{},attempt:Math.max(0,Math.min(1e3,t))}}function ve(){let e=-1,n="";return{note(t){t==="starting"&&n!=="starting"&&(e+=1),n=t},newHandle(){n=""},noteError(){e<0&&(e=0)},get value(){return e}}}var j={document:"document_photo",nfc:"document_chip",population_registry:"national_number",national_eid:"national_eid"};function f(e){return e.plan?.steps??[]}function x(e){return Math.max(0,e.attempts.max-e.attempts.used)}function W(e){let n=e.plan?.choice;return n!==void 0&&e.plan?.current===n.nodeId?n:null}function xe(e){let n=W(e);if(n?.kind!=="identity_method")return null;let t=n.options.map(r=>j[r.service]).filter(r=>r!==void 0),i=n.options.find(r=>r.nationalEid)?.nationalEid;return i?{available:!0,selected:null,options:t,nationalEid:i}:{available:!0,selected:null,options:t}}var G=new Set(["liveness","face_match"]);function g(e){return e!==void 0&&(e.state==="pending"||e.state==="input_required")}function T(e){return e.status!=="created"&&e.status!=="in_progress"}function V(e){let n=e.plan?.current,t=n==null?void 0:f(e).find(i=>i.id===n);return g(t)?t:void 0}function _(e,n){return f(e).find(t=>t.checkType===n)}function y(e){let n=f(e),t=n.findIndex(i=>i.checkType==="liveness");return n.find((i,r)=>r>t&&i.checkType==="face_match")}function O(e,n){let t=_(n,"liveness")?.state,i=y(n)?.state;return(y(e)?.state??"pending")==="pending"&&(t==="passed"||t==="review")&&i!==void 0&&i!=="pending"&&i!=="skipped"}function M(e,n){let t=new Map(f(e).map(i=>[i.id,i.state]));return f(n).filter(i=>i.checkType==="face_match"&&(t.get(i.id)??"pending")==="pending"&&i.state!=="pending"&&i.state!=="skipped").map(i=>i.id)}var X=/^[0-9a-f]{24}$/i;function R(e){return X.test(e)?`ses_${e}`:e}function C(e,n){let t=R(e);return n===void 0?{sessionId:t,status:"unavailable"}:{sessionId:t,status:"unavailable",reasonCode:n}}function F(e,n,t){let i=R(e);return t===void 0?{sessionId:i,status:n}:{sessionId:i,status:n,reasonCode:t}}function Ve(e,n){let t=Z(e,n),i=Q(e);return i!==void 0&&(t.sandbox={simulated:!0,reason:i}),t}var J=new Set(["no_testers","tester_gate_not_used","tester_gate_missed"]);function Q(e){if(e.sandbox!==!0)return;let n=e.simulation?.reason;return J.has(n)?n:void 0}function Z(e,n){let t=R(e.sessionId);switch(e.status){case"created":case"in_progress":return re(e,n);case"verified":return b(e,{sessionId:t,status:"verified"});case"review_pending":return b(e,F(t,"review",L(e,"review")));case"not_verified":return b(e,ne(e));default:return b(e,{sessionId:t,status:"not_verified"})}}var ee=new Set([0,1,2,3]);function b(e,n){return ee.has(e.level)&&(n.level=e.level),typeof e.assurance=="string"&&e.assurance.length>0&&(n.assurance=e.assurance),n}function ne(e){let n={sessionId:R(e.sessionId),status:"not_verified"};return e.reason!==void 0&&(n.reason=e.reason),e.reasonCode!==void 0&&(n.reasonCode=e.reasonCode),e.reasonCode==="device_cooldown"&&e.retryAfter!==void 0&&(n.retryAfter=e.retryAfter),n}function te(e){return e==="rejected"?"rejected":e==="unavailable"?"unavailable":"inconclusive"}function ie(e,n){if(n===void 0)return!1;let t=f(n).find(i=>i.id===e.id);return t!==void 0&&t.attempts.used===e.attempts.used}function re(e,n){let t=R(e.sessionId),i=f(e).find(o=>G.has(o.checkType)&&o.state==="input_required"&&o.reason!==void 0);if(i?.reason==="mobile_required")return C(t,"mobile_required");if(i?.reason!==void 0){if(i.result==="unavailable")return C(t,i.reason);let u=n.autoRetry&&(x(i)>0||ie(i,n.previous))?{sessionId:t,status:"retry",reasonCode:i.reason,attemptsRemaining:x(i)}:{sessionId:t,status:"not_verified",reason:te(i.result),reasonCode:i.reason,attemptsRemaining:x(i)};return i.retakeHint!==void 0&&(u.retakeHint=i.retakeHint),u}let r=V(e);return r===void 0&&f(e).some(o=>o.state==="review")?F(t,"review",L(e,"review")):r?.checkType==="portrait_icao"?C(t,"portrait_required"):C(t)}function L(e,n){return f(e).find(t=>t.state===n&&t.reason!==void 0)?.reason}function K(e,n,t,i,r){return e.presignCapture!==void 0?e.presignCapture(n,t,i,r):e.presign(n,t,i)}function q(e){return{engine:e?.engine,durationMs:e?.clipMs}}var oe=["video/webm","video/mp4"],N="image/jpeg",se=2,ae=1e3,ue=1e4,de=3,ce=10,le=3,pe=new Set(["network_error","timeout","upload_failed","unknown_error","rate_limit_exceeded"]),fe=new Set(["session_not_active","check_not_found","check_already_finalized","check_out_of_order","identity_confirm_required","check_not_active","step_not_on_path","native_app_required"]),w=class extends Error{constructor(){super("verification destroyed"),this.name="FlowCancelledError"}};function me(e){let n=y(e);return _(e,"portrait_icao")?.state!=="pending"&&(n!==void 0?g(n):e.capture?.livePhoto?.oneCapture===!0)}var h=class extends Error{constructor(n){super(n),this.name="AttestationError"}},E=class extends h{constructor(n){super(`no attestation token: ${n}`),this.name="AttestationUnavailableError",this.code=n}};async function D(e,n,t={}){let i=e.uuid(),r=!1,o=!1,u=0,l=0;for(;;)try{return await n(e.client,i)}catch(s){if(s instanceof h){if(o||s instanceof E)throw s;o=!0,t.onAttestationInvalid?.(),i=e.uuid();continue}if(!(s instanceof P))throw s;if(s.code==="consent_required"&&!r){r=!0,await e.ensureConsent({force:!0}),i=e.uuid();continue}if(s.code==="attestation_invalid"&&!o){o=!0,t.onAttestationInvalid?.(),i=e.uuid();continue}if(s.code==="inference_unavailable"&&l<de){l+=1;let a=H(s.retryAfterSeconds,ce,e.random??Math.random);e.onBusy?.({attempt:l,retryAfterSeconds:a/1e3}),await e.sleep(a),t.onAttestationInvalid?.(),i=e.uuid();continue}if(pe.has(s.code)&&u<se){u+=1;let a=s.retryAfterSeconds!==void 0?s.retryAfterSeconds*1e3:void 0;await e.sleep(a!==void 0?Math.min(a,ue):ae);continue}throw s}}var he=new Set(["passed","review","processing","skipped"]);async function Te(e){let{artifacts:n}=e,t=n.clip,i=A(n.clipMime??"");if(n.degraded==="NO_RECORDER"||t===void 0||!oe.includes(i))return{kind:"unavailable",reason:"no_recorder"};e.client.armCapture?.(2);let r=_e(e,n.keyframe),o=Se(e,t,i,r),u=ye(e,r),l=!1,s=new Set,a=!0,k=0;for(;;){if(e.isCancelled())return{kind:"cancelled"};let p=e.getView();if(T(p))return{kind:"settled"};let d=V(p),S=d?.checkType,v=S==="liveness"&&!l?"liveness":S==="face_match"&&!s.has(d?.id)&&s.size<2&&a?"face_match":null;if(v===null)return{kind:"settled"};if(v==="liveness"&&n.captureChannel==="desktop")return{kind:"unavailable",reason:"mobile_required"};try{if(v==="liveness"){l=!0;let c=await o();if(e.isCancelled())return{kind:"cancelled"};O(p,c)&&s.add(y(c)?.id);for(let Y of M(p,c))s.add(Y);await e.applySubmit(c,"liveness");let m=_(e.getView(),"liveness")?.state;a=m===void 0||he.has(m)}else{s.add(d?.id);let c=await u();if(e.isCancelled())return{kind:"cancelled"};for(let m of M(p,c))s.add(m);await e.applySubmit(c,"face_match")}}catch(c){if(e.isCancelled()||c instanceof w)return{kind:"cancelled"};let m=we(c);if(m.kind!=="resync"||k>=le)return m;k+=1,await e.refreshView()}}}function _e(e,n){let t=null,i=null,r=()=>t!==null?Promise.resolve(t):(i??(i=(async()=>{let o=await K(e.client,"image",N,n.size,q(e.artifacts));return await e.client.uploadToSpaces(o.uploadUrl,n,N),t=(await e.client.completeMedia(o.key)).key,e.onKeyframePromoted?.(t),t})().finally(()=>{i=null})),i);return{ensure:r,attempt:()=>r().catch(()=>null),current:()=>t}}function Se(e,n,t,i){let r=null,o,u=null,l=0,s;return()=>D(e,async(a,k)=>{if(r===null||o===void 0){if(e.isCancelled())throw new w;o===void 0&&!me(e.getView())&&(o=null),e.onPhase("uploading");let[p,d]=await Promise.all([r!==null?Promise.resolve(r):(async()=>{let S=await K(a,"clip",t,n.size,q(e.artifacts));return await a.uploadToSpaces(S.uploadUrl,n,t),(await a.completeMedia(S.key)).key})(),o!==void 0?Promise.resolve(o===null?null:o.imageKey):i.attempt()]);r=p,o===void 0&&(o=d===null?null:{imageKey:d})}if(u===null){let p=performance.now();try{u=await e.getAttestation(),s=e.attestationError?.()}catch(d){throw d instanceof h?d:new h(d instanceof Error?d.message:String(d))}l=Math.round(performance.now()-p)}return e.onPhase("checking"),a.submitCheck("liveness",{clipKey:r,attestation:u,captureChannel:e.artifacts.captureChannel,capture:{...ge(e.artifacts),attestationMs:l,attestationError:s},...o!==null?{faceMatch:o}:{}},{idempotencyKey:k})},{onAttestationInvalid:()=>{u=null}})}function ye(e,n){return()=>D(e,async(t,i)=>{if(n.current()===null){if(e.isCancelled())throw new w;e.onPhase("uploading")}let r=await n.ensure();return e.onPhase("checking"),t.submitCheck("face_match",{imageKey:r},{idempotencyKey:i})})}function ge(e){let n={width:e.width,height:e.height};for(let t of Re)e[t]!==void 0&&(n[t]=e[t]);return n}var Re=["engine","facingMode","mode","formFactor","clipMs","clipFrames","fps","clipRetakes","codec","cameraReadyMs","faceAcquireMs","captureMs","screenRamp","provenance"];function we(e){if(e instanceof h)return{kind:"unavailable",reason:"attestation"};if(e instanceof P){if(e.code==="attestation_invalid")return{kind:"unavailable",reason:"attestation"};if(e.code==="inference_unavailable")return{kind:"unavailable",reason:"inference_unavailable"};if(e.code==="mobile_required")return{kind:"unavailable",reason:"mobile_required"};if(fe.has(e.code))return{kind:"resync"}}return{kind:"unavailable",reason:"network"}}var Fe="form_answers_invalid",U=class extends Error{constructor(n,t){super(`form answers refused (${n.map(i=>`${i.id}: ${i.code}`).join(", ")})`),this.name="FormAnswersError",this.issues=n,this.source=t}};var B=class extends Error{constructor(n,t){super(`invalid ${n} (${t})`),this.name="InvalidInputError",this.field=n,this.kind=t}},$=class extends Error{constructor(n,t){super(`invalid ${n} (${t})`),this.name="OtpInputError",this.field=n,this.kind=t}};function I(e){return e?.source==="upload"?null:e?.source==="choice"&&e.sourcePick!=="camera"?"upload_or_phone":"phone"}function qe(e,n){if(n===void 0||!g(n)||n.requiresMobile!==!0)return null;switch(n.checkType){case"liveness":return"phone";case"face_match":{if(n.reason!==void 0)return"phone";let t=_(e,"portrait_icao");return t?.state==="passed"||t?.state==="review"?null:"phone"}case"doc_ocr":return I(e.documents);case"poa":return I(e.proofOfAddress);case"portrait_icao":{let t=e.portrait;return t?.pendingFix!==void 0||t?.reuse?.pending===!0?null:I(t)}default:return null}}function ke(e){let n=e?.capture,t=n?.mode;return t==="assisted"||t==="self"||t==="choice"?t:n?.cameraSwitch===!0?"assisted":"self"}function Ue(e){let n=e?.capture?.pick;return ke(e)==="choice"&&(n==="self"||n==="assisted")?n:null}function Be(e,n,t=null){return e==="choice"?n??t??"self":e}var Ye={"MR:drivers_license":{normalize:"upper_no_space_or_hyphen",pattern:"^[0-9]{8}$",check:null,registrySources:[],describe:"number must be the 8-digit Mauritanian driver's license number"},"MR:national_id":{normalize:"trim",pattern:"^[0-9]{10}$",check:"mr_nni_mod97",registrySources:["MR.anrpts"],describe:"number must be the 10-digit Mauritanian national ID number with a valid check digit"}};export{Ce as a,be as b,ve as c,j as d,f as e,x as f,W as g,xe as h,g as i,T as j,V as k,_ as l,R as m,C as n,Ve as o,Q as p,qe as q,ke as r,Ue as s,Be as t,K as u,oe as v,se as w,ae as x,de as y,ce as z,h as A,E as B,D as C,Te as D,ge as E,Fe as F,U as G,Ye as H,B as I,$ as J};
@@ -0,0 +1 @@
1
+ import{d as re,h as Re,i as ve,j as Le,l as Te}from"./chunk-G6LKLN4U.js";import{a as ne,e as Ce,g as xe}from"./chunk-VVUQ4PFU.js";import{m as j}from"./chunk-34IITQFB.js";import{a as we,g as ke}from"./chunk-7QZWBDI5.js";import{k as te}from"./chunk-CPUECYAJ.js";function _e(e,t){let n=new Set(e.flatMap(r=>r.sides.filter(i=>i[t]!==null).map(i=>i.side)));return n.size===1?[...n][0]:null}function ot(e){let t=Ce.find(r=>r.docType===e),n=t.mrz==="none"?null:t.mrz==="td3"?"single":"verso";return{sides:t.sides,format:xe(e),mrz:t.mrz==="none"?"none":"required",mrzSide:n,barcodeSide:null,portraitSide:t.portraitSide}}function Pe(e,t){if(t.length===0)return ot(e);let n=t.some(s=>s.sides.length>1),r=new Set(t.map(s=>s.format)),i=r.size===1?[...r][0]:"card",c=t.filter(s=>s.sides.some(p=>p.mrz!==null)).length,u=t.find(s=>s.sides.length>1===n)?.sides.find(s=>s.portrait)?.side;return{sides:n?["recto","verso"]:["single"],format:i,mrz:c===t.length?"required":c===0?"none":"optional",mrzSide:_e(t,"mrz"),barcodeSide:_e(t,"barcode"),portraitSide:u??(n?"recto":"single")}}function Ee(e,t){if(e===void 0)return[];let n=e.toUpperCase();return Object.prototype.hasOwnProperty.call(ne,n)?ne[n]?.[t]??[]:[]}async function Oe(e,t,n){return await e(t)?n:n==="recto"?"verso":"recto"}var at={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 it(e){let{deviceMemory:t,effectiveType:n,saveData:r,downlinkMbps:i,sourceLongEdge:c}=e,u=r===!0||n==="slow-2g"||n==="2g"||i!=null&&i>0&&i<1,s=t!=null&&t<=2,p=n==="4g"||i!=null&&i>=5,d=t!=null&&t>=6,M;u||s?M="low":p&&d?M="good":M="mid";let f=at[M],_=c&&c>0?Math.min(f.maxLongEdge,c):f.maxLongEdge;return{tier:M,...f,maxLongEdge:_}}function Ae(e){let t={};try{let n=navigator;typeof n.deviceMemory=="number"&&(t.deviceMemory=n.deviceMemory);let r=n.connection;r&&(t.effectiveType=r.effectiveType,t.saveData=r.saveData,t.downlinkMbps=r.downlink)}catch{}return typeof e=="number"&&e>0&&(t.sourceLongEdge=e),it(t)}function st(e,t,n){let r=Math.min(1,Math.max(0,(e-.28)/.21999999999999997)),i=(t+n)/2;return Math.max(t,n-r*(n-i))}function ut(e,t,n){let r=Math.max(e,t),i=r>0?Math.min(1,n/r):1;return{width:Math.max(1,Math.round(e*i)),height:Math.max(1,Math.round(t*i))}}async function ct(e,t){let n=t.startQ,r=await e(n);for(let i=0;i<4&&!(r.size<=t.budgetBytes||n<=t.qMin);i++)n=Math.max(t.qMin,n-.08),r=await e(n);return{blob:r,quality:n}}async function Be(e,t,n,r,i){if(t<=0||n<=0)return null;let{width:c,height:u}=ut(t,n,r.maxLongEdge),s=document.createElement("canvas");s.width=c,s.height=u;let p=s.getContext("2d");if(!p)return null;p.drawImage(e,0,0,c,u);let d=k=>new Promise((S,x)=>{s.toBlob(l=>l?S(l):x(new Error("canvas toBlob returned null")),"image/jpeg",k)}),M=st(i,r.qMin,r.qMax),{blob:f,quality:_}=await ct(d,{startQ:M,qMin:r.qMin,budgetBytes:r.payloadTargetBytes}).finally(()=>{s.width=0,s.height=0});if(f.size>5242880)throw new Error("encoded document exceeds the 5242880-byte media cap");return{blob:f,quality:_,width:c,height:u}}async function oe(e){let t=Ae(Math.max(e.width,e.height)),n=await Be(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 Et(e){let t=await createImageBitmap(e);try{return await oe(t)}finally{t.close()}}var At=250,Bt=.6,It=1800,Ft=6e3,Wt=2e3,Ie=.16;function ie(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 Fe=e=>e==="recto"?"verso":"recto",We=e=>e.phase==="framing"||e.phase==="locking"||e.phase==="flipCue"||e.phase==="reaskRecto",se=e=>(e.captured.recto!==void 0?1:0)+(e.captured.verso!==void 0?1:0)+e.pending.length;function ae(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 lt(e,t,n){if(e.phase==="result")return{...e,lastReportAt:n};let r=!t.present||e.captureArea!==void 0&&t.areaFrac<.6*e.captureArea,{flipped:i,awaySince:c}=e;r&&(c=c??n),c!==void 0&&n-c>=250&&(i=!0),r||(c=void 0);let u=e.flipTimeoutSpent&&!(i&&!e.flipped),s={...e,lastReportAt:n,flipped:i,awaySince:c,flipTimeoutSpent:u,lastArea:t.areaFrac};if(!We(e))return s;if(e.needFlip&&!i){if(!t.ready)return{...s,phase:e.restPhase,goodSince:void 0};let p=e.lastShot!==void 0&&e.pending.includes(e.lastShot);if(u||p)return{...s,goodSince:void 0,phase:e.restPhase};let d=e.goodSince??n;return n-d>=1800?{...s,goodSince:d,phase:"capturing",flipTimeoutSpent:!0,timeoutCapture:!0}:{...s,goodSince:d,phase:e.restPhase}}return t.ready?{...s,phase:"capturing",goodSince:e.goodSince??n}:{...s,goodSince:void 0,phase:t.locking?"locking":e.restPhase}}function dt(e,t){if(!We(e)||e.manualShutter)return e;let n=t-e.lastReportAt>=2e3,r=t-e.lastCaptureAt>=6e3;return n||r?{...e,manualShutter:!0}:e}function mt(e,t,n){let r=e.layout==="singlePage",i=r?{recto:t}:e.captured,c=r?[]:[...e.pending,t],u={...e,captured:i,pending:c,lastShot:t,lastCaptureAt:n,lastReportAt:-1,manualShutter:!1,goodSince:void 0,notice:void 0,awaySince:void 0,flipped:!1,lastShotByTimeout:e.timeoutCapture,timeoutCapture:!1,captureArea:e.lastArea};return r||se({captured:i,pending:c})>=2?{...u,phase:"reading",restPhase:"framing",current:void 0,needFlip:!1}:{...u,phase:"flipCue",restPhase:"flipCue",current:void 0,needFlip:!0}}function ze(e,t,n){return e.pending.includes(t)?{...e,pending:e.pending.filter(r=>r!==t),lastShot:e.lastShot===t?void 0:e.lastShot,phase:e.phase==="capturing"?e.phase:"flipCue",restPhase:"flipCue",current:Fe(n),needFlip:!0,flipTimeoutSpent:!0,goodSince:void 0,manualShutter:!0,notice:"same_face",lastCaptureAt:-1,lastReportAt:-1}:e}function pt(e,t,n){if(!e.pending.includes(t))return e;if(e.captured[n]!==void 0)return ze(e,t,n);let r=e.pending.filter(p=>p!==t),i={...e,pending:r,captured:{...e.captured,[n]:t}};if(se(i)!==1||e.layout==="singlePage")return i;let c=Fe(n),u=c==="recto"&&e.restPhase==="reaskRecto"?"reaskRecto":"flipCue",s=e.phase==="flipCue"||e.phase==="reaskRecto"||e.phase==="framing";return{...i,restPhase:u,current:c,phase:s?u:e.phase}}function ft(e,t){let n=t.id??e.captured[t.side],r={...e.captured};(t.id===void 0||r[t.side]===t.id)&&delete r[t.side];let i=e.pending.filter(d=>d!==n),c=e.layout==="twoSided"&&se({captured:r,pending:i})>0,u=e.lastShotByTimeout||n===e.lastShot!==e.flipped,s=c&&!u,p=s?t.side==="recto"?"reaskRecto":"flipCue":"framing";return{...e,captured:r,pending:i,readSides:e.readSides.filter(d=>d!==t.side),lastShot:e.lastShot===n?void 0:e.lastShot,notice:t.issue,goodSince:void 0,manualShutter:!1,phase:p,restPhase:p,current:t.side,needFlip:s,flipped:!1,flipTimeoutSpent:!1,awaySince:void 0,lastCaptureAt:-1,lastReportAt:-1}}function Ue(e,t){switch(t.type){case"report":return lt(ae(e,t.at),t.report,t.at);case"tick":return dt(ae(e,t.at),t.at);case"captured":return mt(ae(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 pt(e,t.id,t.side);case"duplicate":return ze(e,t.id,t.side);case"readOk":{let n=e.readSides.includes(t.side)?e.readSides:[...e.readSides,t.side],r=["recto","verso"].filter(c=>e.captured[c]!==void 0),i=e.phase==="reading"&&e.pending.length===0&&r.every(c=>n.includes(c));return{...e,readSides:n,flipTimeoutSpent:!1,phase:i?"result":e.phase}}case"readFailed":return ft(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{...ie(e.layout,-1),lastCaptureAt:-1,lastReportAt:-1};default:return e}}function gt(e,t,n=!1){let r=e(t);return r===null?"recto":!n||r.y+r.height/2>=t.height/2?"verso":"recto"}async function ht(e,t=!1){let{detectMrzBand:n}=await import("./mrz-band-VYHOTDHY.js");return gt(n,e,t)}async function ue(e,t=480,n,r=n!=null){let i=n??{x:0,y:0,width:e.width,height:e.height},c=Math.max(1,Math.round(i.height/i.width*t)),u=document.createElement("canvas");u.width=t,u.height=c;try{let s=u.getContext("2d");return s===null?"recto":(s.drawImage(e,i.x,i.y,i.width,i.height,0,0,t,c),await ht(s.getImageData(0,0,t,c),r))}finally{u.width=0,u.height=0}}async function Ut(e,t=480){try{let n=await createImageBitmap(e),r=Math.max(1,Math.round(n.height/n.width*t)),i=document.createElement("canvas");i.width=t,i.height=r;let c=i.getContext("2d");return c===null?(n.close(),null):(c.drawImage(n,0,0,t,r),n.close(),c.getImageData(0,0,t,r))}catch{return null}}var ce=(e,t,n)=>Math.min(n,Math.max(t,Math.round(e))),$=e=>Math.round(Math.min(1,Math.max(0,e))*1e4)/1e4;async function Ne(e,t,n,r){let i=r.decode??(p=>createImageBitmap(p)),c=async()=>e.stillRead(await i(t),r.region??[0,0,1,1],r.detectorLimit),u;try{u=await c()}catch{try{await new Promise(p=>setTimeout(p,r.retryMs??300)),u=await c()}catch{return null}}let s=u.mrzBox;return s===void 0?null:{engine:r.engine,source:"live_mrz",format:n.format,lineCount:ce(n.lineCount,2,3),checkDigitsValid:!0,stillConfirmed:u.valid&&u.digest===n.digest,band:[$(s[0]),$(s[1]),$(Math.min(s[2],1-s[0])),$(Math.min(s[3],1-s[1]))],digest:n.digest,framesToValid:ce(n.framesToValid,1,1e3),msToValid:ce(n.msToValid,0,12e4)}}function Gt(e){let t=null;return e?.then(n=>{t=n}),()=>t}var bt=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]),yt=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 Ge(e,t=globalThis){let n=t.WebAssembly?.validate;if(typeof n!="function")return{ok:!1,reason:"simd"};try{if(!n.call(t.WebAssembly,bt)||!n.call(t.WebAssembly,yt))return{ok:!1,reason:"simd"}}catch{return{ok:!1,reason:"simd"}}if(typeof t.Worker!="function")return{ok:!1,reason:"worker"};if(typeof t.createImageBitmap!="function")return{ok:!1,reason:"bitmap"};let r=t.navigator?.deviceMemory;return typeof r=="number"&&r<e.minDeviceMemoryGb?{ok:!1,reason:"memory"}:{ok:!0}}function qe(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 He(){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 Xe(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 He()}catch{return He()}let n=new Map,r=0,i=!1,c=!1,u=!1;t.addEventListener("message",l=>{let h=l.data,R=n.get(h.id);R&&(n.delete(h.id),R.resolve(h))});let s=()=>{for(let l of n.values())l.reject(new E("error"));n.clear(),d()};t.addEventListener("error",s),t.addEventListener("messageerror",s);function p(l,h=[]){if(i)return Promise.reject(new E("disposed"));let R=++r;return new Promise((B,A)=>{n.set(R,{resolve:B,reject:A});try{t.postMessage({...l,id:R},h)}catch{n.delete(R),A(new E("error"))}})}function d(){if(!i){i=!0;try{t.postMessage({id:++r,kind:"dispose"})}catch{}t.terminate();for(let l of n.values())l.reject(new E("disposed"));n.clear()}}let M=(async()=>{let l=await p({kind:"init",baseUrl:e.baseUrl,salt:e.salt,detectorLimit:e.tuning.detectorLimit,maxDownloadMs:e.tuning.maxDownloadMs});if(l.kind==="failed")return l.reason;if(l.kind!=="ready")return"error";let h=await p({kind:"warmup"});return h.kind!=="ready"?"error":{warmupMs:h.warmupMs,downloadMs:l.downloadMs,cached:l.cached}})().catch(()=>"error"),f,_=new Promise(l=>{f=setTimeout(()=>l("timeout"),e.tuning.loadTimeoutMs)}),k=Promise.race([M,_]).then(l=>(clearTimeout(f),typeof l=="string"?d():u=!0,i&&typeof l!="string"?"error":l));(e.page===void 0?globalThis.addEventListener?globalThis:null:e.page)?.addEventListener("pagehide",d,{once:!0});async function x(l,h,R){if(i)throw h.close(),new E("disposed");if(!u)throw h.close(),new E("not_ready");if(c)throw h.close(),new E("busy");c=!0;let B;try{let A=new Promise((X,W)=>{B=setTimeout(()=>{W(new E("timeout")),d()},e.tuning.readTimeoutMs??1e4)}),O=await Promise.race([p(l,[h]),A]);if(O.kind===R){let{id:X,...W}=O;return W}throw new E(O.kind==="error"?O.code:O.kind==="failed"?O.reason:"error")}finally{clearTimeout(B),c=!1}}return{ready:k,get busy(){return c},bandRead:(l,h=e.tuning.detectorLimit)=>x({kind:"band",bitmap:l,detectorLimit:h},l,"band"),stillRead:(l,h,R=e.tuning.detectorLimit)=>x({kind:"still",bitmap:l,region:h,detectorLimit:R},l,"band"),layoutRead:(l,h)=>x({kind:"layout",bitmap:l,detectorLimit:h},l,"layout"),dispose:d}}var H="sekyro-ocr-1",le=e=>e!==null&&typeof e=="object"?e:{},T=(e,t,n,r)=>typeof e=="number"&&Number.isFinite(e)&&e>=t&&e<=n?e:r,Ye=(e,t)=>typeof e=="boolean"?e:t,Ve=e=>{let t=typeof e=="string"?/^sekyro-ocr-(\d{1,4})$/.exec(e):null;return t?Number(t[1]):Number.POSITIVE_INFINITY};function Qe(e,t={}){let n=le(e),r=le(n.liveMrz),i=le(n.frontLock),c=Ve(t.engine??H),u=t.mode==="off",s=l=>l.enabled===!0?l.arm==="live"?"live":"control":null,p=s(r),d=s(i),M=(l,h)=>!u&&h==="live"&&Ve(l.minEngine??H)<=c,f=Le,_=M(r,p)?{detectorLimit:T(r.detectorLimit,320,1600,f.detectorLimit),bandMaxWidthPx:T(r.bandMaxWidthPx,320,4096,f.bandMaxWidthPx),minBandWidthPx:T(r.minBandWidthPx,0,4096,f.minBandWidthPx),bandTop:T(r.bandTop,0,.95,f.bandTop),minIntervalMs:T(r.minIntervalMs,0,5e3,f.minIntervalMs),stableReads:Math.round(T(r.stableReads,1,10,f.stableReads)),profileReads:Math.round(T(r.profileReads,1,100,f.profileReads)),maxReadMs:T(r.maxReadMs,50,6e4,f.maxReadMs),searchTimeoutMs:T(r.searchTimeoutMs,1e3,12e4,f.searchTimeoutMs),hint:Ye(r.hint,!0),stillConfirm:Ye(r.stillConfirm,!0)}:null,k=ve,S=(l,h,R)=>T(i[l],h,R,k[l]),x=M(i,d)?{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:_!==null||x!==null,liveMrz:_,textLock:x,liveMrzArm:p,frontLockArm:d,load:{detectorLimit:_?.detectorLimit??x?.detectorLimit??f.detectorLimit,loadTimeoutMs:T(r.loadTimeoutMs,1e3,12e4,2e4),maxDownloadMs:T(r.maxDownloadMs,1e3,12e4,2e4),minDeviceMemoryGb:T(r.minDeviceMemoryGb,0,64,2)},reportSampleRate:T(r.reportSampleRate,0,1,1)}}function Ke(e,t){return e.enabled?!(t.probe??Ge)({minDeviceMemoryGb:e.load.minDeviceMemoryGb}).ok||(t.slow??qe)()?{ok:!1,reason:"unsupported"}:{ok:!0,engine:Xe({baseUrl:t.baseUrl,salt:t.salt,tuning:{detectorLimit:e.load.detectorLimit,maxDownloadMs:e.load.maxDownloadMs,loadTimeoutMs:e.load.loadTimeoutMs},...t.workerUrl!==void 0?{workerUrl:t.workerUrl}:{},...t.createWorker!==void 0?{createWorker:t.createWorker}:{},...t.page!==void 0?{page:t.page}:{}})}:{ok:!1,reason:"off"}}function St(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 F=e=>e===void 0||!Number.isFinite(e)?void 0:Math.min(6e5,Math.max(0,Math.round(e))),de=(e,t,n)=>e===void 0||!Number.isFinite(e)?void 0:Math.min(n,Math.max(t,Math.round(e)));function je(e){let t=e.assist??null,n=e.load!==null&&e.load!==void 0&&typeof e.load=="object"?e.load:null,r=typeof e.load=="string"?e.load:null,i=t!==null?t.outcome:r==="unsupported"||r==="download"||r==="integrity"?r:r==="error"||r==="timeout"?"error":"off",c={kind:"live_mrz",platform:"web",engine:e.engine??H,arm:e.arm,capture:e.capture,outcome:i,reads:de(t?.reads??0,0,1e4)??0,browser:e.browser??St()},u=(s,p)=>{p!==void 0&&(c[s]=p)};return u("format",t?.format),u("framesToValid",de(t?.framesToValid,1,1e4)),u("msToValid",F(t?.msToValid)),u("framesToLock",de(t?.framesToLock,1,1e4)),u("msToLock",F(t?.msToLock)),u("msToCapture",F(e.msToCapture)),u("readP50Ms",F(t?.readP50Ms)),u("readP90Ms",F(t?.readP90Ms)),u("deviceClass",t?.deviceClass),n!==null&&(u("warmupMs",F(n.warmupMs)),u("downloadMs",F(n.downloadMs)),u("cached",n.cached)),u("stillConfirmed",e.stillConfirmed),u("typeMismatch",e.typeMismatch),c}function me(e,t){return e===void 0?!1:t==="passport"?e!=="TD3":e==="TD3"}var Mt=2;async function Dt(e){let t=await import("./capture-session-doc-YC4CT2EQ.js");return new t.CaptureSessionDoc(e)}function wt(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 kt(e,t,n){let r=[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft],i=0;for(let c=0;c<r.length;c+=1){let u=r[c],s=r[(c+1)%r.length];i+=u.x*s.y-s.x*u.y}return t>0&&n>0?Math.abs(i)/2/(t*n):0}function ln(){import("./capture-session-doc-YC4CT2EQ.js").then(e=>e.warmDocDetector()).catch(()=>{})}function dn(e){return Ct(e,{}).handle}function Ct(e,t){let n=we(),r=ke({enabled:e.keepScreenAwake!==!1}),i=t.decode??(o=>createImageBitmap(o)),c=t.blurRefuseSharpnessMax??.16,u=t.now??(()=>performance.now()),s=Pe(e.documentType,t.catalogCapture===!0?Ee(e.issuer,e.documentType):[]),p=s.sides.length===1||e.side==="single",d=ie(p?"singlePage":"twoSided",u());if(!p&&(e.side==="recto"||e.side==="verso")){let o=e.side==="recto"?"verso":"recto";d={...d,captured:{[o]:"server"},readSides:[o],current:e.side,phase:"flipCue",restPhase:"flipCue"}}let M="idle",f=null,_=null,k=!0,S=0,x=0,l=!1,h=!1,R="",B=null,A,O=null,X=[],W=s.mrz==="none",$e=s.barcodeSide==="recto"||s.barcodeSide==="verso"?s.barcodeSide:null,N=W&&!p?t.barcode?.side??$e:null,pe=e.barcodeAssetBaseUrl??t.barcode?.assetBaseUrl,fe=null,ge=()=>N===null||pe===void 0||t.barcode?.seen!==void 0?Promise.resolve(null):(fe??(fe=import("./barcode-detect-C5IOXMKI.js").then(o=>o.loadBarcodeDetect(pe)).catch(()=>null)),fe),Je=async(o,a)=>{if(N===null)return null;let m=N==="recto"?"verso":"recto";try{let g=t.barcode?.seen;if(g!==void 0)return await g(o)?N:m;let[L,D]=await Promise.all([ge(),a()]);if(L===null||D===null)return null;let w=Math.min(1600,D.width),y=document.createElement("canvas");y.width=w,y.height=Math.max(1,Math.round(D.height/D.width*w));try{let b=y.getContext("2d");return b===null?null:(b.drawImage(D,0,0,y.width,y.height),await Oe(L,b.getImageData(0,0,y.width,y.height),N))}finally{y.width=0,y.height=0}}catch{return null}},C=t.webOcr!==void 0&&!W?Qe(t.webOcr.captureDocument,{mode:e.liveMrz?.mode??"auto"}):null,G=null,z=C===null||!C.enabled?"off":null,Y=null,V=null,he=new WeakMap,J="";if(C!==null&&C.enabled&&t.webOcr!==void 0){let o=t.webOcr,a=Ke(C,{baseUrl:e.liveMrz?.assetBaseUrl??o.baseUrl,salt:o.salt,...e.liveMrz?.workerUrl!==void 0?{workerUrl:e.liveMrz.workerUrl}:{},...o.createWorker!==void 0?{createWorker:o.createWorker}:{}});if(a.ok){G=a.engine;let m=new Te({textLock:C.textLock,liveMrz:C.liveMrz});Y=m;let g=a.engine;g.ready.then(L=>{z=L,typeof L!="string"&&k&&m.setEngine(g)})}else z=a.reason}let U=o=>{let a=JSON.stringify(o);a!==J&&(J=a,n.emit("mrz",o))},be=(o,a)=>{let m=t.webOcr?.reports;if(m===void 0||C===null||o===void 0)return;let g=o.format==="ID-3"||o.side==="single"?"single":o.side==="verso"?"verso":"recto",L=g!=="recto"?C.liveMrzArm??C.frontLockArm:C.frontLockArm;if(L===null||Math.random()>=C.reportSampleRate)return;let D=o.via==="live_mrz"?V:null,w=()=>{let y=D?.value??null;m([je({arm:L,capture:g,assist:o.ocr??null,load:L==="control"?"off":z,...o.msToCapture!==void 0?{msToCapture:o.msToCapture}:{},...y!==null&&y.stillConfirmed!==void 0?{stillConfirmed:y.stillConfirmed}:{},...a!==void 0?{typeMismatch:me(a.format,s.format==="ID-3"?"passport":"card")}:{}})])};D!==null&&D.value===null?Promise.race([D.promise,new Promise(y=>setTimeout(y,3e3))]).then(w):w()},I=o=>{!k||o===M||(M=o,r.setActive(o==="starting"||o==="scanning"),n.emit("state",o))},Ze=(o,a)=>a===void 0?null:p?"single":o.captured.recto===a?"recto":o.captured.verso===a?"verso":null,et=o=>({phase:o.phase,captured:p?o.captured.recto!==void 0?["single"]:[]:["recto","verso"].filter(a=>o.captured[a]!==void 0),expected:p?null:o.current??null,notice:o.notice??null,lastShot:Ze(o,o.lastShot),manualShutter:o.manualShutter,torchAvailable:f?.torchAvailable()??!1,torch:h}),ye=()=>{let o=f;o!==null&&o.captureNow().catch(()=>v({type:"captureFailed",at:u()}))};function v(o){if(!k)return;let a=d;d=Ue(d,o),d.phase==="capturing"&&a.phase!=="capturing"&&Promise.resolve().then(ye),d.phase==="result"&&a.phase!=="result"&&(I("done"),Se());let m=et(d),g=JSON.stringify(m);g!==R&&(R=g,n.emit("scan",m))}function Se(){O!==null&&clearInterval(O),O=null;for(let o of X.splice(0))o();f?.destroy(),f=null,r.setActive(!1)}let Me=()=>f?.captureReport?.(),Z=!1,De=(o,a)=>{if(!(o===void 0||t.onFaceReport===void 0))try{t.onFaceReport(o,a)}catch{}},Q=o=>{J="",!(f===null||d.phase==="reading"||d.phase==="result")&&(Z=!1,f.rearm(p?"single":d.current??o))},tt=async(o,a,m,g)=>{if(V=null,g!==void 0&&G!==null&&C?.liveMrz?.hint===!0){let b={promise:Ne(G,o,g,{engine:H,detectorLimit:C.liveMrz.detectorLimit}).catch(()=>null),value:null};b.promise.then(P=>{b.value=P}),V=b}g!==void 0&&me(g.format,s.format==="ID-3"?"passport":"card")&&U({state:"mismatch",format:g.format});let L=Me();De(L,"captured"),Z=!0,be(L,g);let D=m===void 0?B:m===null?null:{quad:wt(m),frameWidth:0,frameHeight:0,inStill:!0},w={decoded:null},y=()=>(w.decoded??(w.decoded=Promise.resolve().then(()=>i(o)).catch(()=>null)),w.decoded);try{await nt(o,a,D,y,V)}finally{w.decoded!==null&&(await w.decoded)?.close()}},nt=async(o,a,m,g,L)=>{let D=`shot-${S+=1}`;if(v({type:"captured",id:D,at:u()}),e.haptics!==!1)try{globalThis.navigator?.vibrate?.(30)}catch{}if(!l&&c>0){let b=await(t.measureSharpness!==void 0?t.measureSharpness(o,m):g().then(P=>P===null?-1:Re(P,re(m?.quad??null,m?.inStill===!0?P:{width:m?.frameWidth??0,height:m?.frameHeight??0},P)))).catch(()=>-1);if(!k)return;if(Number.isFinite(b)&&b>=0&&b<c){l=!0;let P=p?"recto":d.current??(d.captured.recto===void 0?"recto":"verso");v({type:"readFailed",side:P,id:D,issue:"blurry"}),Q(P);return}}l=!1;let w;if(p)w="single";else{let b=d.current,q=(t.classify===void 0?await Je(o,g):null)??await(t.classify!==void 0?t.classify(o):g().then(K=>K===null?b??"recto":m?.inStill===!0?ue(K,480,null,!0):ue(K,480,re(m?.quad??null,{width:m?.frameWidth??0,height:m?.frameHeight??0},K)))).catch(()=>b??"recto");if(!k)return;if(d.captured[q]!==void 0&&x<Mt){x+=1,v({type:"duplicate",id:D,side:q}),Q(q==="recto"?"verso":"recto");return}w=d.captured[q]!==void 0&&b!==void 0?b:q,x=0,v({type:"classified",id:D,side:w})}let y=w==="verso"?"verso":"recto";try{let b=t.encode!==void 0?await t.encode(o):await g().then(P=>{if(P===null)throw new Error("the still could not be decoded");return oe(P)});if(!k)return;L!==null&&he.set(b.blob,L),n.emit("captured",{image:b.blob,side:w,documentType:e.documentType,...e.issuer!==void 0?{issuer:e.issuer}:{},width:b.width,height:b.height,previewDataUrl:a}),t.deferRead!==!0&&v({type:"readOk",side:y})}catch(b){v({type:"readFailed",side:y,id:D,issue:"technical"}),n.emit("error",j("generic",!0,{phase:"keyframes",name:te(b)}))}Q(y==="recto"?"verso":"recto")},rt=o=>{X.push(o.on("statechange",({state:a})=>{a==="preflight"||a==="acquiring"?I("starting"):a==="positioning"?I("scanning"):a==="captured"?I("captured"):a==="error"&&I("error")}),o.on("feedback",({key:a,reticle:m})=>n.emit("feedback",{key:a,reticle:m})),o.on("checks",a=>{n.emit("gate",{progress:a.p,quad:a.quad,frameWidth:a.frameWidth,frameHeight:a.frameHeight,...a.guide!==void 0?{guide:{detected:a.guide.detected,fill:a.guide.fill,offsetX:a.guide.offsetX??0,offsetY:a.guide.offsetY??0}}:{}});let m=a.ocr?.mrz;m!==void 0&&(m.state==="fallback"?U({state:"fallback",reason:m.reason}):m.state==="valid"?U({state:"valid",format:m.format}):m.state==="reading"?U({state:"reading",...m.format?{format:m.format}:{},...m.coach?{coach:m.coach}:{}}):U({state:"searching"}));let g=a.quad===null?0:kt(a.quad,a.frameWidth,a.frameHeight);B=a.quad===null?null:{quad:a.quad,frameWidth:a.frameWidth,frameHeight:a.frameHeight},v({type:"report",report:{present:a.quad!==null&&a.plausible||a.guide?.detected===!0,ready:a.ready===!0,locking:a.p>=.5,areaFrac:g},at:u()})}),o.on("error",({kind:a,retryable:m,detail:g})=>n.emit("error",j(a,m,g))),o.on("artifacts",a=>{tt(a.keyframe,a.previewDataUrl,a.docRegion,a.liveMrz)}))},ee=()=>(_??(_=(async()=>{if(k){if(ge(),f===null){let o;try{o=await(t.createEngine??Dt)({...t.engineOptions??{},...A!==void 0?{guide:A}:{},video:e.video,format:s.format,side:p?"single":e.side??"recto",autoCapture:!1,...Y!==null?{ocr:Y}:{}})}catch(m){I("error"),n.emit("error",j("models",!0,{phase:"models",name:te(m)}));return}if(!k){o.destroy();return}f=o,rt(o);let a=t.tickMs??500;a>0&&(O=setInterval(()=>v({type:"tick",at:u()}),a))}v({type:"clockRestart"}),C!==null&&C.liveMrzArm==="live"&&(z==="unsupported"||z==="off")&&U({state:"fallback",reason:z}),await f.start()}})().finally(()=>{_=null})),_);return{handle:{get state(){return M},on:(o,a)=>n.on(o,a),start:ee,retry:()=>{if(f===null&&d.phase==="result"){v({type:"retake"}),x=0,l=!1,ee();return}if(f!==null&&M!=="error"){v({type:"retake"}),x=0,l=!1,f.rearm(p?"single":void 0);return}ee()},setSide:o=>{p||o==="single"||(d.current!==o&&(d={...d,current:o}),v({type:"clockRestart"}),d.phase!=="reading"&&d.phase!=="result"&&f?.rearm(o))},shutter:ye,focusAt:(o,a)=>{f?.focusAt?.(o,a)},setGuide:o=>{A=o,f?.setGuide?.(o)},setTorch:o=>{h=o,f?.setTorch(o),v({type:"tick",at:u()})},destroy:()=>{if(k&&f!==null&&M!=="done"){let o=Me();!Z&&o!==void 0&&o.ticks>0&&De(o,"abandoned"),be(o,void 0)}k=!1,Se(),Y?.setEngine(null),G?.dispose(),G=null,n.clear()}},setFlowState:o=>{(d.phase==="reading"||d.phase==="result")&&I(o==="done"&&d.phase!=="result"?"scanning":o)},settle:(o,a)=>{let m=o==="verso"?"verso":"recto";v(a.ok?{type:"readOk",side:m}:{type:"readFailed",side:m,issue:a.issue}),a.ok||Q(m)},takeDeviceRead:o=>he.get(o.image)?.value??null}}export{Et as a,At as b,Bt as c,It as d,Ft as e,Wt as f,Ie as g,ie as h,Ue as i,gt as j,ht as k,Ut as l,Ne as m,Gt as n,H as o,Qe as p,Ke as q,St as r,je as s,me as t,Mt as u,ln as v,dn as w,Ct as x};
@@ -0,0 +1,3 @@
1
+ import{B as tt,C as nt,D as ot,E as rt,a as je,b as Ye,c as $e,d as K,e as X,f as z,g as We,h as L,i as Qe,j as P,k as D,l as E,m as U,n as N,o as j,p as Ze,q as Y,r as ee,s as Je,t as Xe,u as ze,v as et}from"./chunk-BF7CLNFA.js";import{n as qe}from"./chunk-34IITQFB.js";import{a as Be}from"./chunk-7QZWBDI5.js";import{c as fe,e as Ge,g as Ke,h as te}from"./chunk-6AH7FXVC.js";import{c as De,d as pe}from"./chunk-TSA6GHUG.js";import{b as Ue}from"./chunk-IA5M34P7.js";function ne(e){return e.idNumberBound??e.nniBound}function $(e){return e===void 0?void 0:e.idNumberFromDocument??e.nniFromDocument}function it(e){let t=e.idNumberMasked??e.nniMasked;return typeof t=="string"&&t!==""?t:void 0}var Ft="https://api.sekyro.ai",Ht=5e3,Lt=24e4,Dt=12e4,Ut=3,Bt=3e3,qt=1500,Gt=10;function st(e){return e instanceof Error&&e.name==="ChallengeError"&&e.code||"challenge_failed"}var Kt=new Set(["aborted","embedder_opaque","site_key_rejected"]);function jt(e){return new Promise(t=>setTimeout(t,e))}function Yt(){let e=globalThis.crypto;if(e!==void 0&&typeof e.randomUUID=="function")return e.randomUUID();let t=new Uint8Array(16);if(e!==void 0&&typeof e.getRandomValues=="function")e.getRandomValues(t);else for(let i=0;i<16;i+=1)t[i]=Math.floor(Math.random()*256);t[6]=(t[6]??0)&15|64,t[8]=(t[8]??0)&63|128;let n=[...t].map(i=>i.toString(16).padStart(2,"0")).join("");return`${n.slice(0,8)}-${n.slice(8,12)}-${n.slice(12,16)}-${n.slice(16,20)}-${n.slice(20)}`}function so(e){return $t(e,{})}function $t(e,t){let n=e.apiOrigin??Ft,i=e.autoRetry??!0,o=e.rearm??"auto",s=t.client??new Ke({apiOrigin:n,sessionToken:e.clientToken,fetch:e.fetch}),a=t.sleep??jt,c=t.uuid??Yt,p=t.getChallengeToken??((r,u)=>import("./challenge-frame-5GG4NDF5.js").then(l=>l.executeChallenge({frameUrl:r.url,siteKey:r.siteKey,action:"liveness",subject:u.subject,signal:u.signal}))),y=Be(),S=null,A=null,d=!1,k=new AbortController,f=null,T=null,W=null,Q=()=>W??Je(f),ke=()=>Xe(ee(f),Q()),R=r=>{f=r,y.emit("view",r),S?.onView(r)},b=()=>f!==null?Promise.resolve(f):(T??(T=s.getSession().then(r=>(R(r),r)).finally(()=>{T=null})),T),I=async()=>{let r=await s.getSession();return R(r),r},re=async(r,u)=>{r.plan!==void 0?R(r):await I()},ie=null,be=async r=>{let u=await b();if(r||!u.consentRecorded){let l=await s.recordConsent(e.locale);l.plan!==void 0?R(l):f!==null&&R({...f,consentRecorded:!0})}Ve(u)},V=r=>r?.force===!0?be(!0):(ie??(ie=be(!1).finally(()=>{ie=null})),ie),se={client:s,ensureConsent:r=>V(r),sleep:a,uuid:c,...t.random!==void 0?{random:t.random}:{},onBusy:r=>{d||y.emit("busy",r)}},xe=!1,we=null,ae=r=>{if(r.status==="verified"||r.status==="not_verified"||r.status==="review"){if(xe)return;xe=!0}we=JSON.stringify(r),y.emit("result",r)},bt=r=>{we!==JSON.stringify(r)&&ae(r)},Ae=async r=>{let u=f;r&&(u=await I().catch(()=>f));let l=u===null?null:L(u);return l!==null&&!d&&y.emit("method",l),l!==null},Pe=null,Re=!1,Ie=!1,Oe=()=>nt(se,(r,u)=>r.submitCheck("population_registry",{},{idempotencyKey:u})),Me=r=>ne(r)===!0||$(E(r,"population_registry"))===!0,xt=async()=>{try{let r=await b();if(P(r)||L(r)!==null||D(r)?.checkType!=="population_registry")return;if(!Me(r)&&$(E(r,"population_registry"))===void 0&&(r=await I()),!Me(r)){Ie=!0;return}await V(),await re(await Oe(),"population_registry");let u=f===null?void 0:E(f,"population_registry");if(u?.state==="input_required"&&u.reason==="registry_unavailable"&&z(u)>0){if(await a(Ht),d)return;await re(await Oe(),"population_registry")}}catch(r){if(r instanceof fe&&(r.code==="check_not_active"||r.code==="step_not_on_path")){await I().catch(()=>{});return}Re=!0;return}f!==null&&P(f)&&ae(j(f,{autoRetry:i}))},Ee=()=>(Pe??(Pe=xt()),Pe),ue=t.now??Date.now,H=null,B,ce,wt=0,de=(r,u)=>`${r.url}
2
+ ${r.siteKey}
3
+ ${u}`,le=(r,u)=>{let l=ue(),g=p(r,{signal:k.signal,subject:u});return g.then(()=>{ce=void 0},m=>{let C=st(m);if(d||C==="aborted")return;ce=C;let{detail:O,readyMs:w}=m;q({check:"attestation",kind:"unavailable",engineKind:C,attempt:wt++,challengeMs:ue()-l,readyMs:w,detail:O,inApp:Ue()})}),g.catch(()=>{}),{key:de(r,u),at:l,token:g}},ve=(r,u)=>r!==null&&r.key===u&&ue()-r.at<Lt,Ve=r=>{let u=r?.challenge??null;if(r===null||u===null||d)return;let l=U(r.sessionId);ve(H,de(u,l))||(H=le(u,l))},At=async(r,u)=>{let l=de(r,u),g=H;H=null;let m=ve(g,l)?g:le(r,u),C=m===g?0:1,O,w=new Promise(h=>{O=setTimeout(()=>h("late"),Dt)});try{for(;;){let h=await Promise.race([m.token.then(M=>({token:M}),M=>({error:st(M)})),w]);if(h==="late")return!d&&H===null&&(H=m),{error:ce??"timeout"};if("token"in h||d||Kt.has(h.error)||C>=Ut||C>0&&await Promise.race([a(Bt*C),w])==="late")return h;if(d)return{error:"aborted"};C+=1,m=le(r,u)}}finally{clearTimeout(O)}},Te=async()=>{B=void 0;let r=await b(),u=r.challenge;if(u==null)return{};let l=await At(u,U(r.sessionId));if("token"in l)return{channel:"hosted_web",turnstileToken:l.token};if(B=l.error,r.simulation!==void 0)return{channel:"hosted_web"};throw new tt(l.error)},Pt=()=>B,q=r=>{if(d)return;let u=s.reportCaptureIssue;if(u===void 0)return;let l=r.formFactor;try{l??(l=De())}catch{}try{Promise.resolve(u.call(s,{...r,...l!==void 0?{formFactor:l}:{}})).catch(()=>{})}catch{}},x=null,Ne=Promise.resolve(),G=0,Rt=async()=>{let r=await b();for(let u=0;u<Gt&&!d&&!P(r)&&D(r)===void 0&&X(r).some(l=>l.state==="processing")&&(await a(qt),!d);u+=1)r=await I();return r},It=async(r,u,l)=>{let{capture:g}=r,m=()=>d,C=()=>r.alive&&r.attempt===l,O=h=>{C()&&g.setFlowState(h)},w=h=>{if(!m()&&(h.status==="unavailable"&&h.reasonCode!==void 0&&!je(h.reasonCode)&&q({check:"liveness",kind:"unavailable",phase:"upload",engineKind:h.reasonCode,attempt:Math.max(0,r.issues.value)}),ae(h),!!C())){if(h.status==="retry"&&o==="auto"){g.handle.retry();return}g.setFlowState("done")}};if(u.degraded==="NO_RECORDER"){let h=f?.sessionId??(await b().catch(()=>null))?.sessionId??"";w(N(h,"no_recorder"));return}O("uploading");try{if(await Ee(),m())return;let h=await b(),M;if(!P(h)&&L(h)!==null){await Ae(!1),w(N(h.sessionId,"method_required"));return}if(!P(h)){if(D(h)?.checkType==="population_registry"){w(N(h.sessionId,Ie?"nni_unbound":Re?"network":"registry_unavailable"));return}if(await V(),m())return;M=f??h;let Z=await ot({...se,artifacts:u,getAttestation:Te,attestationError:Pt,getView:()=>f??h,refreshView:I,applySubmit:re,onPhase:O,isCancelled:m,onKeyframePromoted:J=>{A=J}});if(m())return;if(Z.kind==="unavailable"){let J=N(h.sessionId,Z.reason),Le=Z.reason==="attestation"?B:void 0;w(Le!==void 0?{...J,attestationError:Le}:J);return}if(Z.kind==="resync"&&await I(),f!==null&&L(f)!==null){await Ae(!1),w(N(h.sessionId,"method_required"));return}h=await Rt()}w(j(h,{autoRetry:i,previous:M}))}catch{if(m())return;w(N(f?.sessionId??"","network"))}},Ot=(r,u)=>{let l=r.attempt;G>0&&r.alive&&r.capture.setFlowState("uploading"),G+=1,Ne=Ne.then(()=>It(r,u,l)).finally(()=>{G-=1,G===0&&S?.onChainIdle()}).catch(()=>{})},Fe=r=>{x?.capture.handle.destroy(),x!==null&&(x.alive=!1);let u=qe(r,S?.captureInternals?.(r)??t.capture,()=>f?.capture?.liveness?.keyframe?.rank===!0,ke,()=>f?.capture?.liveness?.screenRamp,{session:()=>ee(f),onModeChange:m=>{W=m}}),l={capture:u,alive:!0,attempt:0,issues:$e()};x=l,u.handle.on("error",m=>{q(Ye("liveness",m,l.issues.value))}),u.handle.on("state",m=>{if(l.issues.note(m),m==="starting"){l.attempt+=1,Ve(f);let C=f===null?void 0:D(f)?.checkType;(C==="liveness"||C==="face_match")&&V().catch(()=>{})}}),u.handle.on("captured",m=>{Promise.resolve().then(()=>Ot(l,m))});let g=u.handle;return{get state(){return g.state},get captureMode(){return g.captureMode},get facingMode(){return g.facingMode},on:(m,C)=>g.on(m,C),start:async m=>{if(f===null&&await b().catch(()=>{}),!!l.alive)return g.start(m)},retry:()=>g.retry(),switchCamera:()=>g.switchCamera(),canSwitchCaptureMode:()=>g.canSwitchCaptureMode(),setCaptureMode:m=>g.setCaptureMode(m),destroy:()=>{l.alive=!1,x===l&&(x=null),g.destroy()}}},Mt=async()=>{if(d)return null;try{let r=await b();return d?null:L(r)}catch{return null}},Et=async()=>{if(d)return"self";try{let r=await b();if(d)return"self";let u=ee(r);return u==="choice"?Q()??u:u}catch{return"self"}},vt=async()=>{if(d)return!1;try{let r=await b();return d||P(r)||pe()?!1:Y(r,D(r))==="phone"||Y(r,E(r,"liveness"))==="phone"}catch{return!1}},Vt=async()=>{if(d)return!1;try{let r=await b();return!d&&r.returning===!0}catch{return!1}},Tt=async r=>{let u=(await b()).plan?.choice,l=u?.options.find(m=>K[m.service]===r);if(!l)throw new RangeError(`method ${String(r)} is not offered`);let g=await s.choose(u.nodeId,l.id);d||R(g)},He=null,Nt=()=>(He??(He=import("./plan-runner-WGMNUBWJ.js").then(r=>{let u=r.createPlanRunner({runtime:se,currentView:()=>f,cameraMode:ke,captureModeSwitch:{pick:Q,choose:l=>{W=l}},ensureView:b,refreshView:I,ensureConsent:()=>V(),liveness:Fe,stopLiveness:()=>{x!==null&&(x.alive=!1,x.capture.handle.destroy(),x=null)},chainBusy:()=>G>0,destroyed:()=>d,sleep:a,isMobile:pe,now:t.now??Date.now,keptFaceKey:()=>A,setView:R,baseCapture:t.capture,emitStep:l=>{d||y.emit("step",l)},emitResult:bt,reportCaptureIssue:q,documentInternals:t.document,portraitInternals:t.portrait,livePhotoInternals:t.livePhoto,uploadInternals:t.upload,pageCameraInternals:t.pageCamera});return S=u,u})),He);return{consent:()=>V(),startRegistry:Ee,methodChoice:Mt,selectMethod:Tt,reportCameraUnavailable:async r=>{await V();let u=s.reportCameraUnavailable;if(u===void 0)throw new TypeError("this client cannot report a missing camera");let l=await u.call(s,r).catch(g=>{if(g instanceof fe&&g.code==="check_out_of_order")return s.getSession();throw g});d||R(l)},reportCaptureIssue:q,testerGate:async r=>{let u=s.testerGate;if(u===void 0)throw new TypeError("this client cannot run the tester gate");let l=r.clip,g=Ge(r.clipMime??"");if(l===void 0||!et.includes(g))throw new TypeError("the capture has no clip");await V();let m=await ze(s,"clip",g,l.size,{engine:r.engine,durationMs:r.clipMs});await s.uploadToSpaces(m.uploadUrl,l,g);let{key:C}=await s.completeMedia(m.key),O=await Te(),w=await u.call(s,{clipKey:C,attestation:O,captureChannel:r.captureChannel,capture:{...rt(r),attestationError:B}}),{bound:h,...M}=w;return d||(M.plan!==void 0?R(M):await I()),{bound:h===!0}},mobileRequired:vt,captureMode:Et,chooseCaptureMode:r=>{W=r},get captureChoice(){return Q()},returning:Vt,liveness:Fe,run:async()=>{if(d)throw new Error("verification destroyed");return(await Nt()).run()},currentStep:()=>S?.current()??null,voiceClips:async()=>{if(d)return null;try{let r=await b();return d?null:r.voice??null}catch{return null}},on:(r,u)=>y.on(r,u),destroy:()=>{d=!0,k.abort(),S?.destroy(),x!==null&&(x.alive=!1,x.capture.handle.destroy(),x=null),y.clear()}}}var at=["AD","AE","AF","AG","AI","AL","AM","AO","AQ","AR","AS","AT","AU","AW","AX","AZ","BA","BB","BD","BE","BF","BG","BH","BI","BJ","BL","BM","BN","BO","BQ","BR","BS","BT","BV","BW","BY","BZ","CA","CC","CD","CF","CG","CH","CI","CK","CL","CM","CN","CO","CR","CU","CV","CW","CX","CY","CZ","DE","DJ","DK","DM","DO","DZ","EC","EE","EG","EH","ER","ES","ET","FI","FJ","FK","FM","FO","FR","GA","GB","GD","GE","GF","GG","GH","GI","GL","GM","GN","GP","GQ","GR","GS","GT","GU","GW","GY","HK","HM","HN","HR","HT","HU","ID","IE","IL","IM","IN","IO","IQ","IR","IS","IT","JE","JM","JO","JP","KE","KG","KH","KI","KM","KN","KP","KR","KW","KY","KZ","LA","LB","LC","LI","LK","LR","LS","LT","LU","LV","LY","MA","MC","MD","ME","MF","MG","MH","MK","ML","MM","MN","MO","MP","MQ","MR","MS","MT","MU","MV","MW","MX","MY","MZ","NA","NC","NE","NF","NG","NI","NL","NO","NP","NR","NU","NZ","OM","PA","PE","PF","PG","PH","PK","PL","PM","PN","PR","PS","PT","PW","PY","QA","RE","RO","RS","RU","RW","SA","SB","SC","SD","SE","SG","SH","SI","SJ","SK","SL","SM","SN","SO","SR","SS","ST","SV","SX","SY","SZ","TC","TD","TF","TG","TH","TJ","TK","TL","TM","TN","TO","TR","TT","TV","TW","TZ","UA","UG","UM","US","UY","UZ","VA","VC","VE","VG","VI","VN","VU","WF","WS","XK","YE","YT","ZA","ZM","ZW"];var Wt=["carte_identite","passport","residence_permit","drivers_license"],Qt=["carte_identite","passport","residence_permit"];function Zt(e,t){let n=e.byIssuer?.[t]??e.default;return Wt.filter(i=>n==="*"?Qt.includes(i):n.includes(i))}function lo(e,t=at){return[...new Set([...t,...Object.keys(e.byIssuer??{})])].filter(i=>Zt(e,i).length>0).sort()}function ut(e){if(e.acceptedDocuments)return e.acceptedDocuments;let t=e.acceptedDocumentTypes?.length?[...e.acceptedDocumentTypes]:["carte_identite","passport"];return{default:[],byIssuer:{MR:t}}}function po(e){return/^[A-Z]{2}$/.test(e)?String.fromCodePoint(...[...e].map(t=>127462+t.charCodeAt(0)-65)):""}var _={fullNameMin:2,fullName:200,email:254,occupation:120,shortText:120,longText:1e3,addressLine:120,addressLines:4,city:80,postcode:16,number:1e12,dateMin:"1900-01-01",dateMax:"2100-12-31"},Jt=new Set(["full_name","birth_date","email","phone","address","country","occupation"]),Xt=new Set(["short_text","long_text","single_choice","multiple_choice","yes_no","date","number"]),zt=new Set(["ar","fa","he","ur"]);function ct(e){return zt.has(e.split("-")[0]?.toLowerCase()??"")?"rtl":"ltr"}function dt(e){if(typeof e!="object"||e===null)return null;let t=e;if(typeof t.locale!="string"||!Array.isArray(t.questions)||t.questions.length===0)return null;let n=t.consents??[];if(!Array.isArray(n))return null;for(let o of t.questions)if(!en(o))return null;for(let o of n)if(!tn(o))return null;let i={locale:t.locale,questions:t.questions,consents:n};return typeof t.title=="string"&&t.title.trim()!==""&&(i.title=t.title),typeof t.intro=="string"&&t.intro.trim()!==""&&(i.intro=t.intro),typeof t.prefill=="object"&&t.prefill!==null&&!Array.isArray(t.prefill)&&(i.prefill=t.prefill),i}function en(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.id!="string"||typeof t.required!="boolean"?!1:t.kind==="field"?typeof t.field=="string"&&Jt.has(t.field):t.kind!=="custom"||typeof t.type!="string"||!Xt.has(t.type)||typeof t.label!="string"?!1:t.type==="single_choice"||t.type==="multiple_choice"?Array.isArray(t.choices)&&t.choices.length>=2&&t.choices.every(n=>typeof n=="object"&&n!==null&&typeof n.value=="string"&&typeof n.label=="string"):!0}function tn(e){if(typeof e!="object"||e===null)return!1;let t=e;if(typeof t.id!="string"||typeof t.required!="boolean"||typeof t.text!="string")return!1;if(t.link===void 0)return!0;let n=t.link;return typeof n=="object"&&n!==null&&typeof n.url=="string"&&/^https:\/\//.test(n.url)&&typeof n.label=="string"}var nn=/^(\d{4})-(\d{2})-(\d{2})$/;function on(e){if(typeof e!="string")return!1;let t=nn.exec(e);return t===null?!1:new Date(Date.UTC(Number(t[1]),Number(t[2])-1,Number(t[3]))).toISOString().slice(0,10)===e&&e>=_.dateMin&&e<=_.dateMax}function rn(e){return typeof e=="number"&&Number.isFinite(e)&&Math.abs(e)<_.number&&Math.round(e*100)/100===e}function lt(e){for(let t of e.matchAll(/\d[\d -]{11,}\d/g)){let n=t[0].replace(/[ -]/g,"");if(n.length>=13&&n.length<=19&&sn(n))return!0}return!1}function sn(e){let t=0;for(let n=0;n<e.length;n++){let i=Number(e[e.length-1-n]);n%2===1&&(i*=2,i>9&&(i-=9)),t+=i}return t%10===0}var an=/^[^\s@]+@[^\s@.]+(\.[^\s@.]+)+$/,un=/^\+[1-9]\d{6,14}$/,pt=/^[A-Z]{2}$/,cn=e=>e===void 0||typeof e=="string"&&e.trim()===""||Array.isArray(e)&&e.length===0;function dn(e=Date.now()){return new Date(e).toISOString().slice(0,10)}function mo(e,t,n=dn()){let i=[];for(let o of e.questions){let s=t.answers[o.id];if(cn(s)){o.required&&i.push({id:o.id,code:"required"});continue}let a=o.kind==="field"?ln(o.field,s,n):fn(o,s,n);a!==null&&i.push({id:o.id,...a})}for(let o of e.consents)o.required&&t.consents[o.id]!==!0&&i.push({id:o.id,code:"consent_required"});return i}function oe(e,t,n=1){if(typeof e!="string")return{code:"required"};let i=e.trim();return[...i].length>t?{code:"too_long",params:{max:t}}:[...i].length<n?{code:"too_short",params:{min:n}}:lt(i)?{code:"card_number"}:null}function ft(e,t,n={}){return on(e)?n.period==="past"&&e>=t?{code:"date_not_past"}:n.period==="future"&&e<=t?{code:"date_not_future"}:n.min!==void 0&&e<n.min?{code:"date_too_early",params:{date:n.min}}:n.max!==void 0&&e>n.max?{code:"date_too_late",params:{date:n.max}}:null:{code:"date_invalid"}}function ln(e,t,n){switch(e){case"full_name":return oe(t,_.fullName,_.fullNameMin);case"occupation":return oe(t,_.occupation);case"birth_date":return ft(t,n,{period:"past"});case"email":return typeof t=="string"&&t.trim().length<=_.email&&an.test(t.trim())?null:{code:"email_invalid"};case"phone":return typeof t=="string"&&un.test(t)?null:{code:"phone_invalid"};case"country":return typeof t=="string"&&pt.test(t)?null:{code:"choice_invalid"};case"address":return pn(t)?null:{code:"address_invalid"};default:return null}}function pn(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e,n=Array.isArray(t.lines)?t.lines.filter(i=>typeof i=="string"&&i.trim()!==""):[];return typeof t.country=="string"&&pt.test(t.country)&&typeof t.city=="string"&&t.city.trim()!==""&&t.city.trim().length<=_.city&&n.length>=1&&n.length<=_.addressLines&&n.every(i=>i.trim().length<=_.addressLine&&!lt(i))&&(t.postcode===void 0||typeof t.postcode=="string"&&t.postcode.trim().length<=_.postcode)}function fn(e,t,n){let i=new Set((e.choices??[]).map(o=>o.value));switch(e.type){case"short_text":return oe(t,_.shortText);case"long_text":return oe(t,_.longText);case"single_choice":return typeof t=="string"&&i.has(t)?null:{code:"choice_invalid"};case"multiple_choice":return Array.isArray(t)&&t.length>0&&new Set(t).size===t.length&&t.every(o=>i.has(o))?null:{code:"choice_invalid"};case"yes_no":return typeof t=="boolean"?null:{code:"choice_invalid"};case"date":{let o=e.options??{};return ft(t,n,{...typeof o.min=="string"?{min:o.min}:{},...typeof o.max=="string"?{max:o.max}:{},...o.period==="past"||o.period==="future"?{period:o.period}:{}})}case"number":{if(typeof t!="number"||!Number.isFinite(t)||Math.abs(t)>=_.number)return{code:"number_invalid"};let o=e.options??{};return o.integer===!0&&!Number.isInteger(t)?{code:"number_not_integer"}:rn(t)?typeof o.min=="number"&&t<o.min?{code:"number_too_small",params:{min:o.min}}:typeof o.max=="number"&&t>o.max?{code:"number_too_large",params:{max:o.max}}:null:{code:"number_decimals"}}default:return null}}var ho={full_name:_.fullName,occupation:_.occupation,email:_.email,short_text:_.shortText,long_text:_.longText};var mt=Object.freeze({nni_invalid:"id_number_invalid",nni_not_found:"registry_record_not_found",nni_recheck:"id_number_recheck",document_nni_mismatch:"document_id_number_mismatch",nni_locked:"id_number_locked",nni_unbound:"id_number_unbound",missing_nni:"missing_id_number",registry_needs_nni_source:"registry_needs_id_number_source"}),mn=new Map(Object.entries(mt)),go=new Map(Object.entries(mt).map(([e,t])=>[t,e]));function ht(e){return mn.get(e)??e}var Po=["national_number","document_photo","national_eid"],hn=new Set(["phone_otp","email_otp","national_eid","document","nfc","population_registry","supplied_identity","summary_confirm","liveness","portrait","face_match","aml_screening","face_dedup","age_estimation","proof_of_address","form"]),yn=new Set(["supplied_identity","aml_screening","face_dedup","age_estimation"]),he=["document","population_registry","national_eid"],ye=["phone_otp","email_otp"],St={identity_method:he,contact:ye},gn=["population_registry","document"],ge="platform_unsupported",Sn=new Set(["prefilled","user_entered","prefilled_or_entered"]),_n={phone_otp:"contact",email_otp:"contact",eid_auth:"identity",doc_ocr:"identity",nfc_chip:"identity",population_registry:"identity",liveness:"live_photo",portrait_icao:"live_photo",face_match:"live_photo",poa:"documents",form:"form"};function v(e){return e.section??_n[e.checkType]??null}function Cn(e,t){let n=e.plan?.choice;if(n===void 0||n.locked)return;let i=n.options.find(o=>o.id!==n.selected&&o.available!==!1&&t.includes(o.service));return i===void 0?void 0:{nodeId:n.nodeId,option:i}}function Se(e){let t=e.plan,n=t?.choice;if(t===void 0||n===void 0||n.locked||t.current===null||t.current===n.nodeId||P(e))return null;let i=St[n.kind]??[...he,...ye],o=n.options.flatMap(c=>c.available===!1||!i.includes(c.service)?[]:[c.nationalEid!=null?{id:c.id,service:c.service,nationalEid:c.nationalEid}:{id:c.id,service:c.service}]),s=t.steps.find(c=>c.id===t.current)?.service,a=n.selected??o.find(c=>c.service===s)?.id??null;return o.some(c=>c.id!==a)?{nodeId:n.nodeId,kind:n.kind,current:a,options:o}:null}function _t(e){return e==null?[]:e.options.filter(t=>t.id!==e.current)}function kn(e){let t=e.simulation;if(typeof t!="object"||t===null)return;let{otpCode:n,skipCapture:i}=t;if(typeof n!="string"||n===""||typeof i!="boolean")return;let o=Ze(e);return o!==void 0?{otpCode:n,skipCapture:i,reason:o}:{otpCode:n,skipCapture:i}}function bn(e){let t=(e.plan?.sections??[]).map(a=>({id:a.id,state:a.state})),n={sessionId:U(e.sessionId),orgName:e.orgName,sandbox:e.sandbox===!0,returning:e.returning===!0,consentRecorded:e.consentRecorded,expiresAt:e.expiresAt,sections:t.map(a=>a.id),progress:t,purpose:e.purpose??"identity"};e.branding!==void 0&&(n.branding=e.branding),e.cameraUnavailableHandled===!0&&(n.cameraUnavailableHandled=!0);let i=kn(e);i!==void 0&&(n.simulation=i);let o=e.testerGate;o?.offered===!0&&typeof o.attemptsLeft=="number"&&o.attemptsLeft>0&&(n.testerGate={attemptsLeft:o.attemptsLeft});let s=Se(e);return s!==null&&(n.switchable=s),n}function xn(e){let t={attemptsRemaining:z(e),attemptsExhausted:e.attempts.used>=e.attempts.max};return e.reason!==void 0&&(t.reason=e.reason),e.retakeHint!==void 0&&(t.retakeHint=e.retakeHint),t}var Ct={phone_otp:"phone",email_otp:"email"};function wn(e,t){let n=Cn(e,[t==="phone_otp"?"email_otp":"phone_otp"]);return n===void 0?void 0:Ct[n.option.service]}function An(e,t,n,i){let o=t.checkType==="email_otp",s=(o?t.emailOtp:t.otp)??{},a=o?t.emailOtp?.emailSource:t.otp?.numberSource,c=a!==void 0&&Sn.has(a)?a:o?"prefilled_or_entered":"user_entered",p=typeof s.sentToMasked=="string"&&s.sentToMasked.length>0,y=s.prefilled===!0,S=wn(e,o?"email_otp":"phone_otp"),A={key:t.checkType,context:n,section:v(t),phase:p?"verify":"send",canSwitch:S!==void 0,...i},d=o?{kind:"email_otp",...A,emailSource:c,needsEmail:c!=="prefilled"&&!y}:{kind:"phone_otp",...A,numberSource:c,needsPhone:c!=="prefilled"&&!y,channels:(t.otp?.channels??[]).filter(k=>k==="whatsapp"||k==="sms")};if(S!==void 0&&(d.switchChannel=S),y&&(d.prefilled=!0),p&&(d.sentToMasked=s.sentToMasked),!o&&t.otp?.channel!==void 0&&(d.channel=t.otp.channel),!o&&Array.isArray(t.phoneCountries)&&(d.phoneCountries=t.phoneCountries.filter(k=>typeof k=="string"&&/^[A-Z]{2}$/.test(k))),!o&&Array.isArray(t.phoneRules)){let k=d.phoneCountries??[];d.phoneRules=t.phoneRules.flatMap(f=>{let T=In(f);return T!==void 0&&k.includes(T.code)?[T]:[]})}return!o&&t.phoneInternational===!0&&(d.phoneInternational=!0),s.expiresAt!==void 0&&(d.codeExpiresAt=s.expiresAt),s.resendAvailableAt!==void 0&&(d.resendAvailableAt=s.resendAvailableAt),d}var Pn=/^[\d[\]\-|()?:^]{1,64}$/;function Rn(e){try{return typeof e=="string"&&Pn.test(e)&&new RegExp(e)!==null}catch{return!1}}var yt=e=>typeof e=="number"&&Number.isInteger(e)&&e>=1&&e<=15;function In(e){let{code:t,dial:n,trunk:i,lengths:o,formats:s}=e??{};if(typeof t!="string"||typeof n!="string"||!/^\d{1,3}$/.test(n)||i!==void 0&&(typeof i!="string"||!/^\d{1,3}$/.test(i))||!Array.isArray(o)||o.length===0||!o.every(yt))return;let a={code:t,dial:n,lengths:[...o].sort((c,p)=>c-p)};if(i!==void 0&&(a.trunk=i),s!==void 0){if(!(Array.isArray(s)&&s.length<=8&&s.every(p=>Rn(p?.leading)&&Array.isArray(p.groups)&&p.groups.every(yt)&&o.includes(p.groups.reduce((y,S)=>y+S,0)))))return;a.formats=s.map(p=>({leading:p.leading,groups:[...p.groups]}))}return a}function On(e,t,n,i){let o=ne(e)===!0?"bound":$(t)===!0?"document":"typed",s=o==="typed"&&t.state==="input_required"&&t.reason!==void 0&&ht(t.reason)==="id_number_recheck",a=_t(Se(e)),c=!i.attemptsExhausted&&a.length===1&&a[0]?.service==="document";return{kind:"registry",key:"registry",context:n,section:v(t),state:t.state==="input_required"?"input_required":"pending",source:o,recheck:s,canUseDocument:c,...i}}function Mn(e,t,n,i,o){let s=[...t.acceptedSides??[]],a={kind:"document",key:"document",context:n,section:v(t),side:s.includes("recto")?"verso":"recto",acceptedSides:s,documents:ut(e),photo:Ce(_e(e.documents),o),...i};return e.detectedCountry!==void 0&&(a.detectedCountry=e.detectedCountry),Vn(e)&&(a.ageStepUp=!0),a}function _e(e,t=!0){let n=e?.source==="upload"||e?.source==="choice"?e.source:"camera",i=e?.sourcePick==="camera"||e?.sourcePick==="upload"?e.sourcePick:null;return{source:n,pick:i,uploadOffered:t&&e?.uploadOffered===!0}}function Ce(e,t){return t?{...e,cameraOnPhone:!0}:e}var En=10*1024*1024;function vn(e,t,n,i,o){let s=e.proofOfAddress,a=s?.pdf?.maxBytes,c=s?.phase==="holder_letter"?"holder_letter":"document";return{kind:"proof_of_address",key:"proof_of_address",context:n,section:v(t),phase:c,rule:s?.rule??{country:null,countryFrom:"global",source:"preset_global",kinds:[]},nameMatch:s?.nameMatch??"exact_person",photo:Ce(_e(s),o),maxPages:3,pdf:{maxBytes:typeof a=="number"&&a>0?a:En,maxPages:3},licenceAddressAccepted:c==="document"&&s?.licenceAddressAccepted===!0,...i}}function Vn(e){let t=X(e).find(i=>i.checkType==="age_estimation"),n=t?.reason;return t?.state==="failed"&&(n==="age_uncertain"||n==="age_unavailable")}function Tn(e){let t=E(e,"liveness");return t?.state==="passed"||t?.state==="review"}function gt(e,t,n,i,o,s=!1){let a=t.icao?.report,c=e.portrait,p=o==="capture"?c?.pendingFix??null:null;p!==null&&(o="review");let y=kt(e);return{kind:"portrait",key:`portrait:${o}`,context:n,section:v(t),phase:o,report:Array.isArray(a)?a:null,review:t.state==="review",tuning:e.capture?.icao??null,tuningVersion:e.capture?.tuningVersion??null,icao:te(e),retakeOnly:o==="capture"&&t.state==="input_required"&&y===void 0&&e.capture?.livePhoto?.oneCapture===!0&&Tn(e),photo:Ce(_e(c,o==="capture"),s&&o==="capture"),pendingFix:p,...y!==void 0?{captureMode:y}:{},...c?.reuse?.pending===!0?{reuse:!0}:{},...i}}function kt(e){let t=e.portrait?.captureMode;return t==="self"||t==="assisted"||t==="choice"?t:void 0}var me={minLongSidePx:1280,jpegQuality:.95};function Nn(e,t){let n=e.capture?.livePhoto;if(n?.oneCapture!==!0)return null;let i=E(e,"portrait_icao"),o=n.still??me;return{icao:t==="liveness"&&te(e)!==null&&kt(e)===void 0&&i!==void 0&&i.state==="pending"&&i.reason===void 0,still:{minLongSidePx:o.minLongSidePx??me.minLongSidePx,jpegQuality:o.jpegQuality??me.jpegQuality}}}function Fn(e,t,n,i){let o=t.eid,s=v(t);if(o===void 0||o.challenge!=="app_code")return{kind:"unsupported",key:"unsupported:eid_auth",context:n,section:s,checkType:"eid_auth",reason:"update_required"};let a=_t(Se(e)),c=a.length===1&&gn.includes(a[0]?.service??"")?a[0]:void 0,p=c===void 0?void 0:K[c.service],y=p!==void 0,S={kind:"eid",key:"eid",context:n,section:s,provider:o.provider,providerName:o.providerName,country:o.country,challenge:"app_code",phase:o.awaiting==="code"?"code":"identifier",identifierBound:o.identifierBound===!0,canUseCamera:y,afterPass:o.afterPass==="continue"?"continue":"end",...i};return y&&(S.cameraMethod=p),o.expiresAt!==void 0&&(S.codeExpiresAt=o.expiresAt),o.resendAvailableAt!==void 0&&(S.resendAvailableAt=o.resendAvailableAt),o.resendsRemaining!==void 0&&(S.resendsRemaining=o.resendsRemaining),o.codeAttemptsRemaining!==void 0&&(S.codeAttemptsRemaining=o.codeAttemptsRemaining),S}function Hn(e,t){if(t.checkType!=="face_match"||t.reason!==void 0)return null;let n=E(e,"portrait_icao");return n!==void 0&&(n.state==="passed"||n.state==="review")?n:null}var Ln={rejected:"rejected",inconclusive:"inconclusive",unavailable:"unavailable",abandoned:"expired",not_opened:"expired",cancelled:"expired",superseded:"expired",policy:"policy"};function Dn(e){return e.reasonCode===ge?"platform_unsupported":e.status==="review_pending"?"review":e.status==="verified"?"verified":e.reasonCode==="device_cooldown"?"cooldown":e.reasonCode==="starter_credit_claimed"?"policy":(e.status==="not_verified"&&e.reason!==void 0?Ln[e.reason]:void 0)??"rejected"}function Un(e,t){let n=Dn(e),i=n==="platform_unsupported"?{sessionId:U(e.sessionId),status:"unavailable",reasonCode:ge}:j(e,{autoRetry:!1}),o={kind:"result",key:"result",context:t,section:null,display:n,result:i};return e.status==="not_verified"&&e.reason!==void 0&&(o.reason=e.reason),e.reasonCode!==void 0&&(o.reasonCode=e.reasonCode),e.status==="not_verified"&&e.step!==void 0&&(o.step=e.step),e.retryAfter!==void 0&&(o.retryAfter=e.retryAfter),o}function Bn(e,t,n){let i=e.identitySummary;if(i==null)return null;let o={kind:"identity_summary",key:"identity_summary",context:t,section:n??"identity",summaryKind:i.kind==="partial"?"partial":i.kind??"full",source:i.source,portraitAvailable:i.portrait?.available===!0,retakeAvailable:i.retakeAvailable===!0};for(let a of qn){let c=i[a];typeof c=="string"&&c!==""&&(o[a]=c)}let s=it(i);return s!==void 0&&(o.idNumberMasked=s,o.nniMasked=s),o}var qn=["fullName","birthDate","birthYear","nationality","documentType","documentNumberMasked","expiryDate","retakeTarget"];function F(e,t,n,i){return{kind:"unsupported",key:`unsupported:${n}`,context:e,section:t,checkType:n,reason:i}}function Gn(e){return e.kind==="contact"?"contact":(e.kind==="identity_method","identity")}function Kn(e,t){let n=St[e.kind]??[...he,...ye],i=Gn(e),o=e.options.flatMap(a=>{if(a.available===!1||!n.includes(a.service))return[];let c={id:a.id,service:a.service};a.nationalEid!=null&&(c.nationalEid=a.nationalEid);let p=(a.channels??[]).filter(y=>y==="whatsapp"||y==="sms");return a.service==="phone_otp"&&p.length>0&&(c.channels=p),[c]});if(o.length===0){let a=e.options.length>0&&e.options.every(c=>c.service==="nfc");return F(t,i,"choice",a?"platform_unsupported":"update_required")}let s={nodeId:e.nodeId,kind:e.kind,selected:e.selected,options:o};if(e.kind==="identity_method"){let a={kind:"method",key:"method",context:t,section:i,options:o.map(p=>K[p.service]),choice:s},c=o.find(p=>p.nationalEid!==void 0)?.nationalEid;return c!==void 0&&(a.nationalEid=c),a}return e.kind==="contact"?{kind:"contact_choice",key:"contact_choice",context:t,section:i,options:o.map(a=>Ct[a.service]),selected:null,locked:!1,choice:s}:{kind:"choice",key:`choice:${e.nodeId}`,context:t,section:i,choice:s}}function jn(e,t,n,i){let o=e.nativeApp,s=typeof o=="object"&&o!==null?o:{},a={sekyroApp:s.sekyroApp===!0};return typeof s.link=="string"&&s.link!==""&&(a.link=s.link),a.sekyroApp&&typeof s.sekyroAppLink=="string"&&s.sekyroAppLink.startsWith("sekyro://")&&(a.sekyroAppLink=s.sekyroAppLink),{kind:"native_app_required",key:`native_app_required:${i}`,context:t,section:n,checkType:i,nativeApp:a}}function Ro(e,t={}){let n=bn(e);if(P(e)||e.reasonCode===ge)return Un(e,n);let i=e.plan;if(i===void 0||!Array.isArray(i.sections))return F(n,null,"plan","update_required");let o=We(e);if(o!==null)return Kn(o,n);let s=i.current===null?void 0:i.steps.find(d=>d.id===i.current),a=d=>{let k={kind:"processing",key:"processing",context:n,section:d!==void 0?v(d):i.sections.find(f=>f.state==="current")?.id??null,stalled:!1};return typeof d?.service=="string"&&d.service!==""&&(k.service=d.service),k};if(i.current===null)return a(i.steps.find(d=>d.state==="processing"));if(s===void 0)return F(n,null,"step","update_required");if(!hn.has(s.service))return s.interaction==="server"?a(s):F(n,v(s),s.service,"update_required");if(yn.has(s.service)||!Qe(s))return a(s);let c=s,p=xn(c),y=c.checkType,S=v(c);if(c.requiresNativeApp===!0)return jn(e,n,S,y);let A=t.isMobile===!1?Y(e,c):null;if(A==="phone")return{kind:"mobile_required",key:"mobile_required",context:n,section:S,checkType:y};switch(y){case"phone_otp":case"email_otp":return An(e,c,n,p);case"population_registry":return On(e,c,n,p);case"eid_auth":return Fn(e,c,n,p);case"doc_ocr":return Mn(e,c,n,p,A==="upload_or_phone");case"identity_confirm":return Bn(e,n,S)??a(c);case"portrait_icao":return gt(e,c,n,p,"capture",A==="upload_or_phone");case"liveness":case"face_match":{let d=Hn(e,c);if(d!==null)return gt(e,d,n,p,"match");let k=c.requiresMobile===!0,f=te(e);return{kind:"liveness",key:"biometric",context:n,section:S,mode:y==="face_match"?"selfie":"liveness",requiresMobile:k,instructions:f===null?"standard":"icao",icao:f,livePhoto:Nn(e,y),...p}}case"poa":return vn(e,c,n,p,A==="upload_or_phone");case"form":{let d=dt(c.form);return d===null?F(n,S,y,"update_required"):{kind:"form",key:"form",context:n,section:S,form:d,dir:ct(d.locale),...p}}case"nfc_chip":return F(n,S,y,"platform_unsupported");default:return F(n,S,y,"update_required")}}export{Ft as a,Ht as b,qt as c,Gt as d,Yt as e,so as f,$t as g,at as h,Wt as i,Zt as j,lo as k,ut as l,po as m,_ as n,ct as o,on as p,rn as q,lt as r,dn as s,mo as t,Po as u,ge as v,v as w,Se as x,_t as y,Hn as z,Ro as A};
@@ -0,0 +1 @@
1
+ var b=new Set(["challenge_frame_blocked","challenge_script_blocked","site_key_rejected","challenge_failed","timeout","embedder_opaque"]),i=class extends Error{constructor(n,t){super(`Sekyro challenge failed: ${n}${t!==void 0?` (${t})`:""}`),this.name="ChallengeError",this.code=n,t!==void 0&&(this.detail=t)}},E=1e4,_=3e4,p="sekyro.challenge.",v="position:fixed;width:1px;height:1px;inset-block-start:0;inset-inline-start:0;opacity:0;pointer-events:none;border:0",d=null,g=Promise.resolve();function F(){u(),g=Promise.resolve(),m=!1}function c(){return new i("aborted")}function C(){let e=globalThis.crypto;return e!==void 0&&typeof e.randomUUID=="function"?e.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function h(e){return new URL(e,document.baseURI).origin}function u(){let e=d;if(e!==null){d=null,window.removeEventListener("message",e.listener),e.iframe.remove();for(let n of e.waiters.values())n.reject(new i("challenge_frame_blocked"));e.waiters.clear()}}function M(e,n){if(n.source!==e.iframe.contentWindow||n.origin!==e.origin)return;let t=n.data;if(typeof t!="object"||t===null)return;let r=t;if(typeof r.type!="string"||!r.type.startsWith(p)||r.v!==1)return;if(r.type==="sekyro.challenge.ready"){e.readyMs??(e.readyMs=Date.now()-e.insertedAt),e.isReady=!0,e.onReady?.();return}if(typeof r.id!="string")return;let a=e.waiters.get(r.id);if(a!==void 0){if(r.type==="sekyro.challenge.token"&&typeof r.token=="string"&&r.token!=="")e.waiters.delete(r.id),a.resolve(r.token);else if(r.type==="sekyro.challenge.error"){e.waiters.delete(r.id);let o=typeof r.code=="string"&&b.has(r.code)?r.code:"challenge_failed",s=typeof r.detail=="string"||typeof r.detail=="number"?String(r.detail).slice(0,32):void 0;a.reject(new i(o,s))}}}function k(e){if(d!==null&&d.url===e)return d;u();let n=document.createElement("iframe");n.setAttribute("title","Security check"),n.setAttribute("aria-hidden","true"),n.setAttribute("tabindex","-1"),n.setAttribute("referrerpolicy","no-referrer"),n.setAttribute("style",v);let t={url:e,origin:h(e),iframe:n,isReady:!1,insertedAt:Date.now(),onReady:null,waiters:new Map,listener:r=>M(t,r)};return window.addEventListener("message",t.listener),n.src=e,document.body.appendChild(n),d=t,t}function A(e,n,t){return e.isReady?Promise.resolve():new Promise((r,a)=>{let o=()=>{clearTimeout(l),t?.removeEventListener("abort",s),e.onReady=null},s=()=>{o(),a(c())},l=setTimeout(()=>{o(),a(new i("challenge_frame_blocked"))},n);t?.addEventListener("abort",s,{once:!0}),e.onReady=()=>{o(),r()}})}async function y(e){if(e.signal?.aborted)throw c();let n=k(e.frameUrl);try{return await x(n,e)}catch(t){throw t instanceof i&&n.readyMs!==void 0&&(t.readyMs??(t.readyMs=n.readyMs)),t}}async function x(e,n){let t=n.signal;await A(e,n.readyTimeoutMs??E,t);let r=e.iframe.contentWindow;if(r===null)throw new i("challenge_frame_blocked");let a=n.timeoutMs??_,o=C(),s,l;try{return await new Promise((w,f)=>{e.waiters.set(o,{resolve:w,reject:f}),s=setTimeout(()=>f(new i("timeout")),a),t!==void 0&&(l=()=>f(c()),t.addEventListener("abort",l,{once:!0})),r.postMessage({type:"sekyro.challenge.request",v:1,id:o,siteKey:n.siteKey,action:n.action,subject:n.subject},e.origin)})}finally{clearTimeout(s),t!==void 0&&l!==void 0&&t.removeEventListener("abort",l),e.waiters.delete(o)}}var m=!1;function R(e,n){if(m)return;let t;if(n==="challenge_frame_blocked"){let r=e;try{r=h(e)}catch{}t=`Sekyro: the security check frame could not load. Allow \`frame-src ${r}\` in your Content-Security-Policy.`}else if(n==="embedder_opaque")t="Sekyro: the security check needs a page with an origin. Do not run the SDK in a sandboxed or data: document.";else return;m=!0,console.warn(t)}async function S(e){if(globalThis.origin==="null")throw new i("embedder_opaque");if(e.signal?.aborted)throw c();try{return await y(e)}catch(n){if(u(),e.signal?.aborted||n instanceof i&&n.code==="aborted")throw c();try{return await y(e)}catch(t){throw u(),e.signal?.aborted?c():t instanceof i?t:new i("challenge_failed")}}}function T(e){let n=()=>S(e).catch(r=>{throw r instanceof i&&R(e.frameUrl,r.code),r}),t=g.then(n,n);return g=t.catch(()=>{}),t}export{i as a,E as b,_ as c,F as d,T as e};
@@ -1 +1 @@
1
- var f="0.1.0-rc.28";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-SEWS3VHQ.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 g=await i,m=I(),S={v:1,platform:"web",sdk:t.sdk.slice(0,64),ids:[...m?[{kind:"web_local",value:m.slice(0,128)}]:[],...g?[{kind:"web_fp",value:g}]:[]],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@${f}`}));function M(t){try{let e=t.getVideoTracks?.()[0];if(e){if(d.noteCameraLabel(e.label),d.noteCameraTrack(e),v())return;import("./camera-trait-V4UAOPIQ.js").then(r=>r.noteCameraTrait(e,d)).catch(()=>{})}}catch{}}export{f as a,p as b,d as c,M as d};
1
+ var f="0.1.0-rc.29";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-SEWS3VHQ.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 g=await i,m=I(),S={v:1,platform:"web",sdk:t.sdk.slice(0,64),ids:[...m?[{kind:"web_local",value:m.slice(0,128)}]:[],...g?[{kind:"web_fp",value:g}]:[]],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@${f}`}));function M(t){try{let e=t.getVideoTracks?.()[0];if(e){if(d.noteCameraLabel(e.label),d.noteCameraTrack(e),v())return;import("./camera-trait-V4UAOPIQ.js").then(r=>r.noteCameraTrait(e,d)).catch(()=>{})}}catch{}}export{f as a,p as b,d as c,M as d};
@@ -0,0 +1,2 @@
1
+ var n="sekyro-mrz-1";function e(r){return Array.from(new Uint8Array(r),t=>t.toString(16).padStart(2,"0")).join("")}async function o(r){return e(await crypto.subtle.digest("SHA-256",r))}function i(r,t){return o(new TextEncoder().encode(`${n}\0${r}\0${t.join(`
2
+ `)}`))}export{o as a,i as b};
@@ -1 +1 @@
1
- import{c as x}from"./chunk-NFHLJOHW.js";import{b}from"./chunk-FPXL63KZ.js";var T=480,y=Object.freeze({MIN_AREA_FRAC:.15,EDGE_CLIP_MARGIN_PX:4,STABLE_TICKS:3,IOU_STABLE_MIN:.85,RISE_PER_S:.9,FALL_PER_S:.25,GUIDE_EXPOSURE:.6,GUIDE_SHARPNESS:.35,ID3_BAND_MIN_WIDTH_FRAC:.55,ID3_BAND_ASPECT_MIN:4,ID3_BAND_ASPECT_MAX:40}),p=e=>Math.min(1,Math.max(0,e));function E(e,o,t){let n=[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft],i=0;for(let s=0;s<4;s++){let r=n[s],c=n[(s+1)%4];i+=r.x*c.y-c.x*r.y}let a=o*t;return a>0?Math.abs(i/2)/a:0}function I(e,o){let t=D(e),n=D(o),i=Math.max(t.x1,n.x1),a=Math.max(t.y1,n.y1),s=Math.min(t.x2,n.x2),r=Math.min(t.y2,n.y2),c=Math.max(0,s-i)*Math.max(0,r-a),u=(t.x2-t.x1)*(t.y2-t.y1),_=(n.x2-n.x1)*(n.y2-n.y1),m=u+_-c;return m>0?c/m:0}function R(e){let o=D(e);return{width:o.x2-o.x1,height:o.y2-o.y1}}function D(e){let o=[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft];return{x1:Math.min(...o.map(t=>t.x)),y1:Math.min(...o.map(t=>t.y)),x2:Math.max(...o.map(t=>t.x)),y2:Math.max(...o.map(t=>t.y))}}function M(e){let o=Math.hypot(e.topRight.x-e.topLeft.x,e.topRight.y-e.topLeft.y),t=Math.hypot(e.bottomRight.x-e.bottomLeft.x,e.bottomRight.y-e.bottomLeft.y),n=Math.hypot(e.bottomLeft.x-e.topLeft.x,e.bottomLeft.y-e.topLeft.y),i=Math.hypot(e.bottomRight.x-e.topRight.x,e.bottomRight.y-e.topRight.y),a=(o+t)/2,s=(n+i)/2;return a<=0||s<=0?0:Math.max(a,s)/Math.min(a,s)}var d=class{constructor(o,t={}){this.p=0;this.lastTickAt=null;this.lastQuad=null;this.streak=0;this.format=o,this.t={...y,...t}}reset(){this.p=0,this.lastTickAt=null,this.lastQuad=null,this.streak=0}tick(o){let{quad:t,quality:n,timestampMs:i}=o,a=this.lastTickAt===null?0:Math.max(0,(i-this.lastTickAt)/1e3);this.lastTickAt=i;let s=null;if(t===null)s="dcv1.no_doc";else if(this.format==="ID-3"){let h=R(t),f=h.height>0?h.width/h.height:0;h.width<this.t.ID3_BAND_MIN_WIDTH_FRAC*o.frameWidth?s="dcv1.come_closer":this.edgeClipped(t,o.frameWidth,o.frameHeight)?s="dcv1.fit_document":(f<this.t.ID3_BAND_ASPECT_MIN||f>this.t.ID3_BAND_ASPECT_MAX)&&(s="dcv1.wrong_shape")}else E(t,o.frameWidth,o.frameHeight)<this.t.MIN_AREA_FRAC?s="dcv1.come_closer":this.edgeClipped(t,o.frameWidth,o.frameHeight)?s="dcv1.fit_document":x(this.format,M(t))||(s="dcv1.wrong_shape");let r=s===null,c=p(n.exposure)>=this.t.GUIDE_EXPOSURE,u=p(n.sharpness)>=this.t.GUIDE_SHARPNESS,_=c&&u;if(r&&_&&t!==null){let h=this.lastQuad===null||I(t,this.lastQuad)>=this.t.IOU_STABLE_MIN;this.streak=h?this.streak+1:1}else this.streak=0;this.lastQuad=t;let m=r&&_;this.p=p(this.p+(m?this.t.RISE_PER_S:-this.t.FALL_PER_S)*a);let A=m&&this.streak>=this.t.STABLE_TICKS,l;if(s!==null)l=s;else if(c)u?l="dcv1.hold_still":l="dcv1.steady";else{let h=(b[0]+b[1])/2;l=n.meanLuma<h?"dcv1.more_light":"dcv1.too_bright"}return{at:i,quad:t,plausible:r,p:this.p,guidanceKey:l,ready:A,stableTicks:this.streak}}edgeClipped(o,t,n){let i=this.t.EDGE_CLIP_MARGIN_PX;return[o.topLeft,o.topRight,o.bottomRight,o.bottomLeft].some(s=>s.x<=i||s.y<=i||s.x>=t-i||s.y>=n-i)}};export{T as a,y as b,E as c,I as d,R as e,d as f};
1
+ import{d as x}from"./chunk-VVUQ4PFU.js";import{b}from"./chunk-FPXL63KZ.js";var T=480,y=Object.freeze({MIN_AREA_FRAC:.15,EDGE_CLIP_MARGIN_PX:4,STABLE_TICKS:3,IOU_STABLE_MIN:.85,RISE_PER_S:.9,FALL_PER_S:.25,GUIDE_EXPOSURE:.6,GUIDE_SHARPNESS:.35,ID3_BAND_MIN_WIDTH_FRAC:.55,ID3_BAND_ASPECT_MIN:4,ID3_BAND_ASPECT_MAX:40}),p=e=>Math.min(1,Math.max(0,e));function E(e,o,t){let n=[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft],i=0;for(let s=0;s<4;s++){let r=n[s],c=n[(s+1)%4];i+=r.x*c.y-c.x*r.y}let a=o*t;return a>0?Math.abs(i/2)/a:0}function I(e,o){let t=D(e),n=D(o),i=Math.max(t.x1,n.x1),a=Math.max(t.y1,n.y1),s=Math.min(t.x2,n.x2),r=Math.min(t.y2,n.y2),c=Math.max(0,s-i)*Math.max(0,r-a),u=(t.x2-t.x1)*(t.y2-t.y1),_=(n.x2-n.x1)*(n.y2-n.y1),m=u+_-c;return m>0?c/m:0}function R(e){let o=D(e);return{width:o.x2-o.x1,height:o.y2-o.y1}}function D(e){let o=[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft];return{x1:Math.min(...o.map(t=>t.x)),y1:Math.min(...o.map(t=>t.y)),x2:Math.max(...o.map(t=>t.x)),y2:Math.max(...o.map(t=>t.y))}}function M(e){let o=Math.hypot(e.topRight.x-e.topLeft.x,e.topRight.y-e.topLeft.y),t=Math.hypot(e.bottomRight.x-e.bottomLeft.x,e.bottomRight.y-e.bottomLeft.y),n=Math.hypot(e.bottomLeft.x-e.topLeft.x,e.bottomLeft.y-e.topLeft.y),i=Math.hypot(e.bottomRight.x-e.topRight.x,e.bottomRight.y-e.topRight.y),a=(o+t)/2,s=(n+i)/2;return a<=0||s<=0?0:Math.max(a,s)/Math.min(a,s)}var d=class{constructor(o,t={}){this.p=0;this.lastTickAt=null;this.lastQuad=null;this.streak=0;this.format=o,this.t={...y,...t}}reset(){this.p=0,this.lastTickAt=null,this.lastQuad=null,this.streak=0}tick(o){let{quad:t,quality:n,timestampMs:i}=o,a=this.lastTickAt===null?0:Math.max(0,(i-this.lastTickAt)/1e3);this.lastTickAt=i;let s=null;if(t===null)s="dcv1.no_doc";else if(this.format==="ID-3"){let h=R(t),f=h.height>0?h.width/h.height:0;h.width<this.t.ID3_BAND_MIN_WIDTH_FRAC*o.frameWidth?s="dcv1.come_closer":this.edgeClipped(t,o.frameWidth,o.frameHeight)?s="dcv1.fit_document":(f<this.t.ID3_BAND_ASPECT_MIN||f>this.t.ID3_BAND_ASPECT_MAX)&&(s="dcv1.wrong_shape")}else E(t,o.frameWidth,o.frameHeight)<this.t.MIN_AREA_FRAC?s="dcv1.come_closer":this.edgeClipped(t,o.frameWidth,o.frameHeight)?s="dcv1.fit_document":x(this.format,M(t))||(s="dcv1.wrong_shape");let r=s===null,c=p(n.exposure)>=this.t.GUIDE_EXPOSURE,u=p(n.sharpness)>=this.t.GUIDE_SHARPNESS,_=c&&u;if(r&&_&&t!==null){let h=this.lastQuad===null||I(t,this.lastQuad)>=this.t.IOU_STABLE_MIN;this.streak=h?this.streak+1:1}else this.streak=0;this.lastQuad=t;let m=r&&_;this.p=p(this.p+(m?this.t.RISE_PER_S:-this.t.FALL_PER_S)*a);let A=m&&this.streak>=this.t.STABLE_TICKS,l;if(s!==null)l=s;else if(c)u?l="dcv1.hold_still":l="dcv1.steady";else{let h=(b[0]+b[1])/2;l=n.meanLuma<h?"dcv1.more_light":"dcv1.too_bright"}return{at:i,quad:t,plausible:r,p:this.p,guidanceKey:l,ready:A,stableTicks:this.streak}}edgeClipped(o,t,n){let i=this.t.EDGE_CLIP_MARGIN_PX;return[o.topLeft,o.topRight,o.bottomRight,o.bottomLeft].some(s=>s.x<=i||s.y<=i||s.x>=t-i||s.y>=n-i)}};export{T as a,y as b,E as c,I as d,R as e,d as f};