@sekyro/web 0.0.0-stage → 0.1.0-rc.10

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 (89) hide show
  1. package/CHANGELOG.md +220 -0
  2. package/LICENSE +29 -0
  3. package/README.md +136 -2
  4. package/THIRD-PARTY-NOTICES.txt +154 -0
  5. package/dist/background-monitor-A7FKJOAG.js +1 -0
  6. package/dist/capture-constraints-B5omafmk.d.cts +44 -0
  7. package/dist/capture-constraints-B5omafmk.d.ts +44 -0
  8. package/dist/capture-session-doc-GK6G7JOI.js +1 -0
  9. package/dist/capture-session-v3-CmJw_bK0.d.cts +585 -0
  10. package/dist/capture-session-v3-DGG2stO6.d.ts +585 -0
  11. package/dist/chunk-3MSUJYBO.js +1 -0
  12. package/dist/chunk-7ZCZY3ZP.js +1 -0
  13. package/dist/chunk-A3FUGHAH.js +2 -0
  14. package/dist/chunk-BAGSM67V.js +1 -0
  15. package/dist/chunk-BPE5NSQ2.js +1 -0
  16. package/dist/chunk-CJHMFPL6.js +1 -0
  17. package/dist/chunk-DFTCAWMP.js +1 -0
  18. package/dist/chunk-DK5YPBDQ.js +1 -0
  19. package/dist/chunk-ETY6SAAZ.js +1 -0
  20. package/dist/chunk-FFDB6LQN.js +1 -0
  21. package/dist/chunk-FHJ7HO3M.js +1 -0
  22. package/dist/chunk-FPXL63KZ.js +1 -0
  23. package/dist/chunk-FUHDOEBP.js +1 -0
  24. package/dist/chunk-G6LKLN4U.js +1 -0
  25. package/dist/chunk-GI3UFGRQ.js +1 -0
  26. package/dist/chunk-HAO6EQTH.js +1 -0
  27. package/dist/chunk-HWAXEQD5.js +1 -0
  28. package/dist/chunk-MXWLCDFX.js +1 -0
  29. package/dist/chunk-O5WKNZ2C.js +1 -0
  30. package/dist/chunk-OKWG3PVH.js +1 -0
  31. package/dist/chunk-POIQGEZM.js +1 -0
  32. package/dist/chunk-RI3E7GBN.js +1 -0
  33. package/dist/chunk-SEC64KZ3.js +1 -0
  34. package/dist/chunk-SMKCBUJL.js +1 -0
  35. package/dist/chunk-SXZCL5NO.js +1 -0
  36. package/dist/chunk-SZ7YGNUZ.js +1 -0
  37. package/dist/chunk-TDLIXFDT.js +1 -0
  38. package/dist/chunk-UGMHAFEY.js +1 -0
  39. package/dist/chunk-WKJJEPWA.js +1 -0
  40. package/dist/chunk-XR64UFLK.js +1 -0
  41. package/dist/client/index.cjs +1 -0
  42. package/dist/client/index.d.cts +71 -0
  43. package/dist/client/index.d.ts +71 -0
  44. package/dist/client/index.js +1 -0
  45. package/dist/core/index.cjs +1 -0
  46. package/dist/core/index.d.cts +87 -0
  47. package/dist/core/index.d.ts +87 -0
  48. package/dist/core/index.js +1 -0
  49. package/dist/core/ocr/worker.bundle.js +42 -0
  50. package/dist/core/ocr/worker.cjs +42 -0
  51. package/dist/core/ocr/worker.d.cts +84 -0
  52. package/dist/core/ocr/worker.d.ts +84 -0
  53. package/dist/core/ocr/worker.js +41 -0
  54. package/dist/core/v3/detect-worker.cjs +1 -0
  55. package/dist/core/v3/detect-worker.d.cts +1 -0
  56. package/dist/core/v3/detect-worker.d.ts +1 -0
  57. package/dist/core/v3/detect-worker.js +1 -0
  58. package/dist/create-document-capture-IGUQP2NS.js +1 -0
  59. package/dist/create-portrait-capture-RJSFY37D.js +1 -0
  60. package/dist/create-verification-Bb20j6zk.d.ts +2968 -0
  61. package/dist/create-verification-CtqF4A9W.d.cts +2968 -0
  62. package/dist/detect-worker-DclNxkZT.d.cts +111 -0
  63. package/dist/detect-worker-DclNxkZT.d.ts +111 -0
  64. package/dist/detector-scanic-YCDNLCGV.js +1 -0
  65. package/dist/icao-gate-PWBMKRGC.js +1 -0
  66. package/dist/icao-gate-terzKYD7.d.cts +1770 -0
  67. package/dist/icao-gate-terzKYD7.d.ts +1770 -0
  68. package/dist/icao-tuning-4GGVX6B4.js +1 -0
  69. package/dist/index.cjs +1 -0
  70. package/dist/index.d.cts +74 -0
  71. package/dist/index.d.ts +74 -0
  72. package/dist/index.js +1 -0
  73. package/dist/internal/index.cjs +1 -0
  74. package/dist/internal/index.d.cts +462 -0
  75. package/dist/internal/index.d.ts +462 -0
  76. package/dist/internal/index.js +1 -0
  77. package/dist/keyframe-rank-YAJLYJYF.js +1 -0
  78. package/dist/landmarker-KB7LVXAU.js +1 -0
  79. package/dist/mrz-band-VYHOTDHY.js +1 -0
  80. package/dist/plan-runner-QCK2SOGS.js +1 -0
  81. package/dist/popup/index.cjs +1 -0
  82. package/dist/popup/index.d.cts +66 -0
  83. package/dist/popup/index.d.ts +66 -0
  84. package/dist/popup/index.js +1 -0
  85. package/dist/scanic-ml-stub-KW7IZHUT.js +1 -0
  86. package/dist/segmenter-USLNBX65.js +1 -0
  87. package/dist/turnstile-FATNZ4AG.js +1 -0
  88. package/package.json +133 -4
  89. package/sbom.cdx.json +195 -0
@@ -0,0 +1 @@
1
+ "use strict";var y=Object.defineProperty;var R=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var v=Object.prototype.hasOwnProperty;var H=(t,e)=>{for(var o in e)y(t,o,{get:e[o],enumerable:!0})},M=(t,e,o,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of O(e))!v.call(t,i)&&i!==o&&y(t,i,{get:()=>e[i],enumerable:!(n=R(e,i))||n.enumerable});return t};var A=t=>M(y({},"__esModule",{value:!0}),t);var Y={};H(Y,{HostedApiError:()=>d,HostedClient:()=>p,KNOWN_CODES:()=>g,icaoPolicyOf:()=>I,isKnownCode:()=>T,portraitIcaoGate:()=>k,stripMimeParams:()=>u});module.exports=A(Y);var b="0.1.0-rc.10";var w="sekyro.did",S;function C(){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,o=>o.toString(16).padStart(2,"0")).join("")}}catch{}}function N(){try{let t=localStorage.getItem(w);if(t)return t;let e=C();return e!==void 0&&localStorage.setItem(w,e),e}catch{return S??(S=C()),S}}async function x(){let t=globalThis.crypto?.subtle;if(!t)return"";let e=navigator,o=JSON.stringify([e.userAgent,e.platform,e.hardwareConcurrency??null,e.deviceMemory??null,e.maxTouchPoints??0,screen.width,screen.height,screen.colorDepth,globalThis.devicePixelRatio??1,Intl.DateTimeFormat().resolvedOptions().timeZone,e.languages?.join(",")??e.language]),n=await t.digest("SHA-256",new TextEncoder().encode(o));return Array.from(new Uint8Array(n),i=>i.toString(16).padStart(2,"0")).join("").slice(0,32)}function D(t){let e=new TextEncoder().encode(t),o="";for(let n of e)o+=String.fromCharCode(n);return btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function V(t){let e,o;return{timezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone?.slice(0,64)||void 0}catch{return}},noteCameraLabel(n){n&&(e=n.slice(0,128))},async deviceHeader(){try{o??(o=x().catch(()=>""));let n=[];navigator.webdriver&&n.push("webdriver"),/HeadlessChrome/.test(navigator.userAgent)&&n.push("headless");let i=await o,s=N(),r={v:1,platform:"web",sdk:t.sdk.slice(0,64),ids:[...s?[{kind:"web_local",value:s.slice(0,128)}]:[],...i?[{kind:"web_fp",value:i}]:[]],screen:{w:screen.width,h:screen.height,dpr:globalThis.devicePixelRatio??1},...e?{cameraLabel:e}:{},...n.length?{signals:n}:{}};return D(JSON.stringify(r))}catch{return}}}}var m=Symbol.for("sekyro.web.clientContext"),f=globalThis,h=f[m]??(f[m]=V({sdk:`@sekyro/web@${b}`}));var g=["session_token_invalid","session_token_required","session_token_session_mismatch","session_not_found","rate_limit_exceeded","consent_required","session_not_active","check_not_found","check_already_finalized","check_out_of_order","check_type_unsupported","force_outcome_forbidden","attestation_invalid","platform_unregistered","app_attest_invalid","too_many_challenges","inference_unavailable","mobile_required","nni_locked","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"];function T(t){return g.includes(t)}var d=class extends Error{constructor(e){super(e.message),this.name="HostedApiError",this.status=e.status,this.code=e.code,e.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=e.retryAfterSeconds),e.details&&(this.details=e.details)}};var K=6e4,P=4,U=3e4,L=9e5,q=200,F=5,$=400;function u(t){return(t.split(";")[0]??"").trim()}var B={liveness:"clipKey",face_match:"imageKey",doc_ocr:"imageKey"},p=class{constructor(e){this.sessionId=null;this.bootstrap=null;this.captureNonces=[];this.captureFetch=null;this.apiOrigin=e.apiOrigin.replace(/\/+$/,""),this.sessionToken=e.sessionToken;let o=e.fetch;this.fetchImpl=(n,i)=>(o??globalThis.fetch).call(globalThis,n,i),this.requestTimeoutMs=e.requestTimeoutMs??U,this.retryAttempts=e.inProgressRetry?.attempts??F,this.retryDelayMs=e.inProgressRetry?.delayMs??$}async getSession(){let e=await this.api("GET","/hosted/session");return this.sessionId=e.sessionId,e}async recordConsent(e){return this.api("POST","/hosted/consent",{body:{locale:e}})}async choose(e,o){let n=await this.api("POST","/hosted/choice",{body:{nodeId:e,option:o}});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,o,n){let i=await this.ensureSessionId(),s={kind:e,contentType:u(o),contentLength:n};return this.api("POST",`/sessions/${i}/media`,{body:s})}armCapture(e=2){this.fillCaptureNonces(e)}async presignCapture(e,o,n,i={}){let s=await this.ensureSessionId(),r=await this.takeCaptureNonce(),c=r===void 0?void 0:{nonce:r,...i.engine!==void 0?{engine:i.engine.slice(0,32)}:{},...i.durationMs!==void 0&&Number.isFinite(i.durationMs)?{captureMs:Math.min(36e5,Math.max(0,Math.round(i.durationMs)))}:{}},a={kind:e,contentType:u(o),contentLength:n,capture:c};return this.api("POST",`/sessions/${s}/media`,{body:a})}async takeCaptureNonce(){let e=()=>{let o=Date.now();return this.captureNonces=this.captureNonces.filter(n=>n.expiresAt-K>o),this.captureNonces.shift()?.nonce};for(let o=0;o<2;o++){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 o=await this.ensureSessionId(),n=await this.api("POST",`/sessions/${o}/media/capture-nonces`,{body:{count:Math.min(P,Math.max(1,e))}}),i=Date.now()+Math.max(0,n.expiresIn)*1e3;for(let s of Array.isArray(n.nonces)?n.nonces:[])typeof s=="string"&&s.length>0&&this.captureNonces.push({nonce:s,expiresAt:i});this.captureNonces=this.captureNonces.slice(-P)}catch{}})().finally(()=>{this.captureFetch=null})),this.captureFetch}async uploadToSpaces(e,o,n){let i;try{i=await this.fetchImpl(e,{method:"PUT",headers:{"content-type":u(n)},body:o,signal:AbortSignal.timeout(L)})}catch(s){throw _(s)}if(!i.ok){let s=(await i.text().catch(()=>"")).slice(0,q);throw new d({status:i.status,code:"upload_failed",message:`media upload failed (HTTP ${i.status})${s?`: ${s}`:""}`})}}async completeMedia(e){let o=await this.ensureSessionId();return this.api("POST",`/sessions/${o}/media/complete`,{body:{key:e}})}async submitCheck(e,o,n={}){let i=await this.ensureSessionId(),s={input:o,forceOutcome:n.forceOutcome};return this.api("POST",`/sessions/${i}/checks/${e}`,{body:s,idempotencyKey:n.idempotencyKey})}async uploadAndSubmit(e,o,n,i={}){let s=u(o.contentType),r=await this.presign(o.kind,s,o.blob.size);await this.uploadToSpaces(r.uploadUrl,o.blob,s);let c=await this.completeMedia(r.key),a={...n,[B[e]]:c.key};return this.submitCheck(e,a,i)}async ensureSessionId(){return this.sessionId!==null?this.sessionId:(this.bootstrap??(this.bootstrap=this.getSession().finally(()=>{this.bootstrap=null})),(await this.bootstrap).sessionId)}async api(e,o,n={}){let i=`${this.apiOrigin}/api/v2${o}`,s={"x-session-token":this.sessionToken};n.body!==void 0&&(s["content-type"]="application/json"),n.idempotencyKey!==void 0&&(s["x-idempotency-key"]=n.idempotencyKey);try{let r=h.timezone();r!==void 0&&(s["sekyro-client-timezone"]=r)}catch{}try{let r=await h.deviceHeader();r!==void 0&&(s["sekyro-client-device"]=r)}catch{}for(let r=0;;r++){let c;try{c=await this.fetchImpl(i,{method:e,headers:s,...n.body!==void 0?{body:JSON.stringify(n.body)}:{},cache:"no-store",signal:AbortSignal.timeout(this.requestTimeoutMs)})}catch(l){throw _(l)}if(c.ok){if(n.blob===!0)try{return await c.blob()}catch(E){throw _(E)}let l;try{l=await c.json()}catch{throw new d({status:c.status,code:"unknown_error",message:`response body was not valid JSON (HTTP ${c.status})`})}return j(l)}let a=await G(c);if(a.code==="idempotency_in_progress"&&r<this.retryAttempts){this.retryDelayMs>0&&await z(this.retryDelayMs);continue}throw a}}};function _(t){if((typeof t=="object"&&t!==null?t.name:void 0)==="TimeoutError")return new d({status:0,code:"timeout",message:"request timed out"});let o=t instanceof Error?t.message:String(t);return new d({status:0,code:"network_error",message:`network request failed: ${o}`})}function j(t){return t!==null&&typeof t=="object"&&"success"in t&&"data"in t?t.data:t}async function G(t){let e="unknown_error",o=`request failed (HTTP ${t.status})`,n=Number.NaN,i;try{let c=await t.json();if(c!==null&&typeof c=="object"){let a=c;typeof a.code=="string"&&a.code.length>0&&(e=a.code),typeof a.message=="string"&&a.message.length>0&&(o=a.message),typeof a.retryAfterSeconds=="number"&&(n=a.retryAfterSeconds),Array.isArray(a.details?.issues)&&(i=a.details)}}catch{}let s=t.headers.get("retry-after"),r=s===null?Math.floor(n):Number.parseInt(s,10);return new d({status:t.status,code:e,message:o,...Number.isFinite(r)&&r>=0?{retryAfterSeconds:r}:{},details:i})}function z(t){return new Promise(e=>setTimeout(e,t))}function I(t){let e=t?.portrait,o=e?.icao,n=e?.purpose==="id_document";return o==null?n?{policy:"reject",profile:"id_document"}:null:{policy:o.policy==="alert"&&!n?"alert":"reject",profile:n||o.profile==="id_document"?"id_document":"selfie"}}function k(t){return{...t.baselineEyeOpenness!==void 0?{baselineEyeOpenness:t.baselineEyeOpenness}:{},criteria:t.verdict??{},...t.backgroundCheck!==void 0?{backgroundCheck:t.backgroundCheck}:{}}}0&&(module.exports={HostedApiError,HostedClient,KNOWN_CODES,icaoPolicyOf,isKnownCode,portraitIcaoGate,stripMimeParams});
@@ -0,0 +1,71 @@
1
+ import { B as HostedSessionView, s as HostedIcaoPolicy, P as IcaoGateSummary, aa as PortraitIcaoInput } from '../icao-gate-terzKYD7.cjs';
2
+ export { A as AcceptedDocumentType, aV as AttestationInput, aW as CaptureContext, C as CaptureMode, aX as CaptureNoncesResult, aY as CaptureProof, aZ as CheckInputByType, a as CheckReason, b as CheckState, c as CheckType, a_ as CompleteMediaResult, a$ as ConsentLocale, d as ContactChannel, D as DecisionReason, b0 as DocDeviceRead, b1 as DocOcrInput, e as DocReason, b2 as DocSide, E as EidAfterPass, f as EidAuthInput, g as EidReason, b3 as EmailOtpInput, h as EmailOtpReason, b4 as FaceMatchInput, F as FaceMatchReason, i as HostedAcceptedDocuments, l as HostedCaptureTuning, aU as HostedClient, b5 as HostedClientOptions, m as HostedConsentView, n as HostedDocumentCaptureTuning, o as HostedDocumentScanTuning, p as HostedEidView, q as HostedEmailOtpView, r as HostedFlowRef, t as HostedIntegrity, u as HostedLivePhotoTuning, v as HostedNativeCaptureTuning, w as HostedOcrTuning, x as HostedOtpView, y as HostedPlanView, z as HostedPortraitView, G as HostedStepView, I as HostedVoiceLocale, J as HostedVoiceView, M as IcaoCriterion, R as IcaoReportEntry, S as IdentityConfirmDecision, T as IdentityMethod, U as IdentitySummarySource, V as IdentitySummaryView, b6 as LivenessCaptureInput, b7 as LivenessInput, W as LivenessReason, X as MatchReason, b8 as MediaCheckType, b9 as MediaKind, Y as MethodChoiceView, Z as NationalEidOption, _ as NfcChipReason, $ as NfcStepView, a0 as OtpChoiceView, ba as PhoneOtpInput, a1 as PhoneOtpReason, a2 as PlanAttempts, a3 as PlanChoiceKind, a4 as PlanChoiceOption, a5 as PlanChoiceView, a6 as PlanSectionView, a7 as PlanStepView, a8 as PolicyFailureReason, bb as PopulationInput, a9 as PopulationReason, ab as PortraitIcaoReason, bc as PresignRequest, bd as PresignUploadResult, be as RecordConsentResult, ac as SessionFailureReason, ad as SessionOutcome, ae as SessionStatus, bf as SessionStepView, bg as SessionView, af as StepSection, bh as SubmitCheckBody, bi as SubmitOptions, bj as UploadMedia, bk as stripMimeParams } from '../icao-gate-terzKYD7.cjs';
3
+
4
+ /**
5
+ * Every error code the hosted page can receive from the session-token surface.
6
+ * A closed string-literal union — switch over {@link KnownCode} with a `never`
7
+ * default arm for compile-checked exhaustiveness.
8
+ */
9
+ declare const KNOWN_CODES: readonly ["session_token_invalid", "session_token_required", "session_token_session_mismatch", "session_not_found", "rate_limit_exceeded", "consent_required", "session_not_active", "check_not_found", "check_already_finalized", "check_out_of_order", "check_type_unsupported", "force_outcome_forbidden", "attestation_invalid", "platform_unregistered", "app_attest_invalid", "too_many_challenges", "inference_unavailable", "mobile_required", "nni_locked", "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"];
10
+ /** Closed union of {@link KNOWN_CODES} — exhaustively switchable. */
11
+ type KnownCode = (typeof KNOWN_CODES)[number];
12
+ /** Narrow an arbitrary wire code to the known union (unknown codes stay `string`). */
13
+ declare function isKnownCode(code: string): code is KnownCode;
14
+ /** One machine-readable problem of an error's `details` (Sekyro flows spec §9.4). */
15
+ interface HostedErrorIssue {
16
+ code: string;
17
+ message: string;
18
+ /** The request field (`option`, `nodeId`, …). */
19
+ path?: string;
20
+ /** A node of the flow. */
21
+ nodeId?: string;
22
+ service?: string;
23
+ field?: string;
24
+ }
25
+ /** `details` of a flow error envelope (`choice_*`, `step_not_on_path`, …): the issues, and more per code. */
26
+ interface HostedErrorDetails {
27
+ issues: HostedErrorIssue[];
28
+ /** `override_widens_flow`: the widened fields. */
29
+ fields?: string[];
30
+ [key: string]: unknown;
31
+ }
32
+ /**
33
+ * Typed transport error: EVERY failure surfaces as one of these — non-2xx
34
+ * responses, rejected fetches, timeouts, and unparseable bodies alike. The
35
+ * hosted page never sees a raw TypeError/DOMException from the client.
36
+ *
37
+ * - `code` — the public envelope's `code`, or a client-synthesized fallback
38
+ * ('unknown_error' / 'upload_failed' / 'network_error' / 'timeout'). Typed
39
+ * `string` because the wire may grow codes; narrow with {@link isKnownCode}
40
+ * before an exhaustive switch.
41
+ * - `status` — the HTTP status, or 0 when no response arrived at all
42
+ * ('network_error' / 'timeout').
43
+ * - `retryAfterSeconds` — parsed from the `Retry-After` header when present
44
+ * (rate-limit 429s always set it).
45
+ * - `details` — the envelope's machine-readable `details` when present (flow
46
+ * errors: `issues[]`).
47
+ */
48
+ declare class HostedApiError extends Error {
49
+ readonly status: number;
50
+ readonly code: string;
51
+ readonly retryAfterSeconds?: number;
52
+ readonly details?: HostedErrorDetails;
53
+ constructor(args: {
54
+ status: number;
55
+ code: string;
56
+ message: string;
57
+ retryAfterSeconds?: number;
58
+ details?: HostedErrorDetails | undefined;
59
+ });
60
+ }
61
+
62
+ /** The session's ICAO policy and profile, or `null` when the selfie is not ICAO-checked. */
63
+ declare function icaoPolicyOf(view: Pick<HostedSessionView, "portrait"> | null | undefined): HostedIcaoPolicy | null;
64
+ /**
65
+ * The `gate` block of a `portrait_icao` body from the gate's summary: the eye
66
+ * baseline, the device verdict under the server's criterion names, and the
67
+ * background-uniformity numbers (telemetry).
68
+ */
69
+ declare function portraitIcaoGate(summary: IcaoGateSummary): NonNullable<PortraitIcaoInput["gate"]>;
70
+
71
+ export { HostedApiError, type HostedErrorDetails, type HostedErrorIssue, HostedIcaoPolicy, HostedSessionView, KNOWN_CODES, type KnownCode, PortraitIcaoInput, icaoPolicyOf, isKnownCode, portraitIcaoGate };
@@ -0,0 +1,71 @@
1
+ import { B as HostedSessionView, s as HostedIcaoPolicy, P as IcaoGateSummary, aa as PortraitIcaoInput } from '../icao-gate-terzKYD7.js';
2
+ export { A as AcceptedDocumentType, aV as AttestationInput, aW as CaptureContext, C as CaptureMode, aX as CaptureNoncesResult, aY as CaptureProof, aZ as CheckInputByType, a as CheckReason, b as CheckState, c as CheckType, a_ as CompleteMediaResult, a$ as ConsentLocale, d as ContactChannel, D as DecisionReason, b0 as DocDeviceRead, b1 as DocOcrInput, e as DocReason, b2 as DocSide, E as EidAfterPass, f as EidAuthInput, g as EidReason, b3 as EmailOtpInput, h as EmailOtpReason, b4 as FaceMatchInput, F as FaceMatchReason, i as HostedAcceptedDocuments, l as HostedCaptureTuning, aU as HostedClient, b5 as HostedClientOptions, m as HostedConsentView, n as HostedDocumentCaptureTuning, o as HostedDocumentScanTuning, p as HostedEidView, q as HostedEmailOtpView, r as HostedFlowRef, t as HostedIntegrity, u as HostedLivePhotoTuning, v as HostedNativeCaptureTuning, w as HostedOcrTuning, x as HostedOtpView, y as HostedPlanView, z as HostedPortraitView, G as HostedStepView, I as HostedVoiceLocale, J as HostedVoiceView, M as IcaoCriterion, R as IcaoReportEntry, S as IdentityConfirmDecision, T as IdentityMethod, U as IdentitySummarySource, V as IdentitySummaryView, b6 as LivenessCaptureInput, b7 as LivenessInput, W as LivenessReason, X as MatchReason, b8 as MediaCheckType, b9 as MediaKind, Y as MethodChoiceView, Z as NationalEidOption, _ as NfcChipReason, $ as NfcStepView, a0 as OtpChoiceView, ba as PhoneOtpInput, a1 as PhoneOtpReason, a2 as PlanAttempts, a3 as PlanChoiceKind, a4 as PlanChoiceOption, a5 as PlanChoiceView, a6 as PlanSectionView, a7 as PlanStepView, a8 as PolicyFailureReason, bb as PopulationInput, a9 as PopulationReason, ab as PortraitIcaoReason, bc as PresignRequest, bd as PresignUploadResult, be as RecordConsentResult, ac as SessionFailureReason, ad as SessionOutcome, ae as SessionStatus, bf as SessionStepView, bg as SessionView, af as StepSection, bh as SubmitCheckBody, bi as SubmitOptions, bj as UploadMedia, bk as stripMimeParams } from '../icao-gate-terzKYD7.js';
3
+
4
+ /**
5
+ * Every error code the hosted page can receive from the session-token surface.
6
+ * A closed string-literal union — switch over {@link KnownCode} with a `never`
7
+ * default arm for compile-checked exhaustiveness.
8
+ */
9
+ declare const KNOWN_CODES: readonly ["session_token_invalid", "session_token_required", "session_token_session_mismatch", "session_not_found", "rate_limit_exceeded", "consent_required", "session_not_active", "check_not_found", "check_already_finalized", "check_out_of_order", "check_type_unsupported", "force_outcome_forbidden", "attestation_invalid", "platform_unregistered", "app_attest_invalid", "too_many_challenges", "inference_unavailable", "mobile_required", "nni_locked", "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"];
10
+ /** Closed union of {@link KNOWN_CODES} — exhaustively switchable. */
11
+ type KnownCode = (typeof KNOWN_CODES)[number];
12
+ /** Narrow an arbitrary wire code to the known union (unknown codes stay `string`). */
13
+ declare function isKnownCode(code: string): code is KnownCode;
14
+ /** One machine-readable problem of an error's `details` (Sekyro flows spec §9.4). */
15
+ interface HostedErrorIssue {
16
+ code: string;
17
+ message: string;
18
+ /** The request field (`option`, `nodeId`, …). */
19
+ path?: string;
20
+ /** A node of the flow. */
21
+ nodeId?: string;
22
+ service?: string;
23
+ field?: string;
24
+ }
25
+ /** `details` of a flow error envelope (`choice_*`, `step_not_on_path`, …): the issues, and more per code. */
26
+ interface HostedErrorDetails {
27
+ issues: HostedErrorIssue[];
28
+ /** `override_widens_flow`: the widened fields. */
29
+ fields?: string[];
30
+ [key: string]: unknown;
31
+ }
32
+ /**
33
+ * Typed transport error: EVERY failure surfaces as one of these — non-2xx
34
+ * responses, rejected fetches, timeouts, and unparseable bodies alike. The
35
+ * hosted page never sees a raw TypeError/DOMException from the client.
36
+ *
37
+ * - `code` — the public envelope's `code`, or a client-synthesized fallback
38
+ * ('unknown_error' / 'upload_failed' / 'network_error' / 'timeout'). Typed
39
+ * `string` because the wire may grow codes; narrow with {@link isKnownCode}
40
+ * before an exhaustive switch.
41
+ * - `status` — the HTTP status, or 0 when no response arrived at all
42
+ * ('network_error' / 'timeout').
43
+ * - `retryAfterSeconds` — parsed from the `Retry-After` header when present
44
+ * (rate-limit 429s always set it).
45
+ * - `details` — the envelope's machine-readable `details` when present (flow
46
+ * errors: `issues[]`).
47
+ */
48
+ declare class HostedApiError extends Error {
49
+ readonly status: number;
50
+ readonly code: string;
51
+ readonly retryAfterSeconds?: number;
52
+ readonly details?: HostedErrorDetails;
53
+ constructor(args: {
54
+ status: number;
55
+ code: string;
56
+ message: string;
57
+ retryAfterSeconds?: number;
58
+ details?: HostedErrorDetails | undefined;
59
+ });
60
+ }
61
+
62
+ /** The session's ICAO policy and profile, or `null` when the selfie is not ICAO-checked. */
63
+ declare function icaoPolicyOf(view: Pick<HostedSessionView, "portrait"> | null | undefined): HostedIcaoPolicy | null;
64
+ /**
65
+ * The `gate` block of a `portrait_icao` body from the gate's summary: the eye
66
+ * baseline, the device verdict under the server's criterion names, and the
67
+ * background-uniformity numbers (telemetry).
68
+ */
69
+ declare function portraitIcaoGate(summary: IcaoGateSummary): NonNullable<PortraitIcaoInput["gate"]>;
70
+
71
+ export { HostedApiError, type HostedErrorDetails, type HostedErrorIssue, HostedIcaoPolicy, HostedSessionView, KNOWN_CODES, type KnownCode, PortraitIcaoInput, icaoPolicyOf, isKnownCode, portraitIcaoGate };
@@ -0,0 +1 @@
1
+ import{a as e,b as t,c as o,d as i,e as n,f as s,g as a}from"../chunk-HWAXEQD5.js";import"../chunk-BAGSM67V.js";export{o as HostedApiError,n as HostedClient,e as KNOWN_CODES,s as icaoPolicyOf,t as isKnownCode,a as portraitIcaoGate,i as stripMimeParams};
@@ -0,0 +1 @@
1
+ "use strict";var je=Object.create;var P=Object.defineProperty;var $e=Object.getOwnPropertyDescriptor;var Je=Object.getOwnPropertyNames;var et=Object.getPrototypeOf,tt=Object.prototype.hasOwnProperty;var rt=(t,e)=>()=>(t&&(e=t(t=0)),e);var me=(t,e)=>{for(var r in e)P(t,r,{get:e[r],enumerable:!0})},pe=(t,e,r,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Je(e))!tt.call(t,n)&&n!==r&&P(t,n,{get:()=>e[n],enumerable:!(i=$e(e,n))||i.enumerable});return t};var nt=(t,e,r)=>(r=t!=null?je(et(t)):{},pe(e||!t||!t.__esModule?P(r,"default",{value:t,enumerable:!0}):r,t)),it=t=>pe(P({},"__esModule",{value:!0}),t);var Ke={};me(Ke,{RANK_CANDIDATES:()=>Ct,RANK_TOLERANCE:()=>B,RANK_WINDOW_MS:()=>It,ROLL_ZERO_DEG:()=>Rt,SHARPNESS_REPORT_MAX:()=>Ne,YAW_REPORT_MAX:()=>Ge,YAW_ZERO_IOD:()=>Ot,collectRankedKeyframes:()=>Ve,default:()=>Pt,featuresOf:()=>Le,frontalOf:()=>Pe,rankKeyframes:()=>Fe});function Pe(t){let e=t.eyes;if(e===void 0)return{frontal:1,yaw:null,roll:null};let r=e.right.x-e.left.x,i=e.right.y-e.left.y,n=r*r+i*i;if(n===0)return{frontal:1,yaw:null,roll:null};let s=Math.abs(Math.atan2(i,Math.abs(r))*180/Math.PI),a=Ae(1-s/30),o=null,c=t.nose;if(c!==void 0){let d=(e.left.x+e.right.x)/2,u=(e.left.y+e.right.y)/2;o=Math.abs(((c.x-d)*r+(c.y-u)*i)/n),a*=Ae(1-o/.5)}return{frontal:a,yaw:o,roll:s}}function Le(t,e){return t===null?{face:!1,frontal:0,yaw:null,roll:null,eyes:null,score:0,sharpness:e}:{face:!0,...Pe(t),eyes:null,score:t.score,sharpness:e}}function Fe(t){let e=t.map((n,s)=>s),r=(n,s)=>{let a=Number.NEGATIVE_INFINITY;for(let o of e)a=Math.max(a,n(t[o]));e=e.filter(o=>n(t[o])>=a-s)};r(n=>n.frontal,B.frontal),r(n=>n.eyes??1,B.eyes),r(n=>n.score,B.score);let i=-1;for(let n of e)(i===-1||t[n].sharpness>t[i].sharpness)&&(i=n);return i}function At(t){return{face:t.face,frontal:D(t.frontal),...t.yaw!==null?{yaw:Math.min(D(t.yaw),Ge)}:{},...t.roll!==null?{roll:D(t.roll)}:{},...t.eyes!==null?{eyes:D(t.eyes)}:{},score:D(t.score),sharpness:Math.min(D(t.sharpness),Ne)}}async function Ve(t,e){let{options:r}=t,i=r.video,n=r.now??(()=>performance.now()),s=r.captureKeyframe??(m=>t.defaultKeyframe(m)),a=600/3,o=[],c=[],d=0;for(let m=0;m<4;m+=1){if(e!==t.attempt)return null;let p=t.detector,g=Promise.resolve(null),h,f=0;try{if(p!==null){let A=t.profiler?.profile.inputWidth??160,Ze=r.makeSnapshot?.(i,A)??t.defaultSnapshot(i,A);h=s(i).then(q=>(f=n(),q));let Qe=n();g=p.detect(Ze,i.videoWidth,i.videoHeight).then(q=>(d+=n()-Qe,q),()=>null)}else h=s(i).then(A=>(f=n(),A));let[R,Ye]=await Promise.all([h,g]);o.push(R),c.push(Le(Ye,R.sharpness))}catch{h?.catch(()=>{})}let qe=f>0?Math.max(0,n()-f):0;m<3&&await new Promise(R=>setTimeout(R,Math.max(0,a-qe)))}if(e!==t.attempt)return null;let u=Fe(c);if(u===-1)return null;let l=0;c.forEach((m,p)=>{m.sharpness>c[l].sharpness&&(l=p)});try{r.telemetry?.({type:"keyframe",tier:t.detector?.tier??null,chosen:u,sharpest:l,detectMs:Math.round(d),candidates:c.map(At)})}catch{}return o[u]??null}var Ct,It,Ot,Rt,B,Ae,D,Ge,Ne,Pt,We=rt(()=>{"use strict";Ct=4,It=600,Ot=.5,Rt=30,B={frontal:.1,eyes:.1,score:.05},Ae=t=>t<0?0:t>1?1:t;D=t=>Number.isFinite(t)?Math.round(t*1e3)/1e3:0,Ge=99,Ne=999999;Pt=Ve});var Vt={};me(Vt,{CENTERED_FACTOR:()=>pt,CIRCLE_RADIUS_FACTOR:()=>dt,CLIP_MS:()=>fe,CaptureSessionV3:()=>de,ClipError:()=>y,ClipRecorder:()=>T,DEFAULT_CLIP_MIME:()=>L,DEFAULT_TIER_ORDER:()=>xe,DEFAULT_V3_ASSET_BASE_URL:()=>_e,DEVICE_PROFILES:()=>De,DetectScheduler:()=>O,DetectorLadderError:()=>E,DeviceProfiler:()=>I,EXPOSURE_BAND:()=>C,FaceGateV3:()=>S,GATE_SNAPSHOT_MS:()=>Be,GateBlockStats:()=>k,HOLD_UPRIGHT_KEY:()=>z,IN_CIRCLE_FACTOR:()=>mt,KEYFRAME_CANDIDATES:()=>X,KEYFRAME_WINDOW_MS:()=>Xe,MAX_CLIP_BYTES:()=>F,MIME_CANDIDATES:()=>he,PHONE_MAX_SHORT_SIDE:()=>be,SHARP_REF:()=>er,STOP_GRACE_MS:()=>ge,TIMESLICE_MS:()=>ye,UPRIGHT_WATCH_MS:()=>ze,V3_GATE_DEFAULTS:()=>ke,VIDEO_BPS:()=>J,blockReasonOf:()=>Re,buildCaptureConstraints:()=>ee,buildLivenessV2FormData:()=>at,cameraPreflight:()=>j,captureMirroredKeyframe:()=>$,classifyDevice:()=>oe,createDetector:()=>_,detectFormFactor:()=>G,detectIsMobile:()=>te,errorCopy:()=>ot,exposure:()=>ie,extForMime:()=>Y,intrinsicSize:()=>v,isClipTooLarge:()=>w,isMediaRecorderSupported:()=>st,mapGetUserMediaError:()=>Q,meanLuma:()=>W,pickMimeType:()=>Z,probeDevice:()=>ae,sharpness:()=>H,toStreamPixels:()=>M,trackFacingMode:()=>re,uiCopy:()=>ct});module.exports=it(Vt);var he=["video/mp4;codecs=avc1.42E01E,mp4a.40.2","video/mp4;codecs=avc1.42E01E","video/mp4","video/webm;codecs=vp9,opus","video/webm;codecs=vp9","video/webm;codecs=vp8,opus","video/webm;codecs=vp8","video/webm"];function Z(){let t=globalThis.MediaRecorder;return!t||typeof t.isTypeSupported!="function"?"":he.find(e=>t.isTypeSupported(e))??""}var L="video/webm";function Q(t){if(t instanceof TypeError)return"insecure";switch(t?.name??""){case"NotAllowedError":case"PermissionDeniedError":return"permission";case"NotFoundError":case"DevicesNotFoundError":return"notfound";case"NotReadableError":case"TrackStartError":return"inuse";case"OverconstrainedError":case"ConstraintNotSatisfiedError":return"overconstrained";default:return"generic"}}function j(){let t=globalThis;if(typeof t.window<"u"&&t.window.isSecureContext===!1)return"INSECURE_CONTEXT";let e=t.navigator?.mediaDevices;return!e||typeof e.getUserMedia!="function"?"UNSUPPORTED":"OK"}function st(){let t=globalThis.MediaRecorder;return typeof t<"u"&&typeof t.isTypeSupported=="function"}var F=8*1024*1024;function w(t){return t.size>F}function Y(t){let e=(t||"").toLowerCase();return e.startsWith("image/jpeg")?"jpg":e.startsWith("video/mp4")?"mp4":(e.startsWith("video/webm"),"webm")}function at(t){let{token:e,clip:r,keyframe:i}=t,n=t.ts??Date.now(),s=r.type||L,a=i.type||"image/jpeg",o=new FormData;return o.append("token",e),o.append("clip",new File([r],`liveness-${n}.${Y(s)}`,{type:s})),o.append("keyframe",new File([i],`keyframe-${n}.${Y(a)}`,{type:a})),o}function $(t,e,r=.92){return new Promise((i,n)=>{let s=t.videoWidth,a=t.videoHeight;if(!s||!a){n(new Error("video-not-ready"));return}let o=e.getContext("2d");if(!o){n(new Error("no-2d-context"));return}e.width=s,e.height=a,o.scale(-1,1),o.drawImage(t,-s,0),e.toBlob(c=>c?i(c):n(new Error("empty-keyframe")),"image/jpeg",r)})}var ot={permission:{key:"fcv2.err.permission",fr:"Autorisez la cam\xE9ra dans les r\xE9glages du navigateur (ic\xF4ne cam\xE9ra dans la barre d\u2019adresse), puis r\xE9essayez."},notfound:{key:"fcv2.err.notfound",fr:"Aucune cam\xE9ra d\xE9tect\xE9e. Branchez ou activez une cam\xE9ra, puis r\xE9essayez."},inuse:{key:"fcv2.err.inuse",fr:"La cam\xE9ra est utilis\xE9e par une autre application. Fermez-la puis r\xE9essayez."},overconstrained:{key:"fcv2.err.overconstrained",fr:"La cam\xE9ra ne prend pas en charge les r\xE9glages demand\xE9s. Nouvel essai en cours\u2026"},insecure:{key:"fcv2.err.insecure",fr:"La cam\xE9ra n\xE9cessite une connexion s\xE9curis\xE9e (HTTPS). Ouvrez la page en HTTPS."},unsupported:{key:"fcv2.err.unsupported",fr:"Votre navigateur ne prend pas en charge l\u2019enregistrement vid\xE9o. Utilisez un navigateur r\xE9cent."},generic:{key:"fcv2.err.generic",fr:"Cam\xE9ra indisponible. R\xE9essayez ou contactez le support."}},ct={recording:{key:"fcv2.recording",fr:"Enregistrement en cours\u2026"},uploading:{key:"fcv2.uploading",fr:"Envoi en cours\u2026"},clipTooLarge:{key:"fcv2.err.cliptoolarge",fr:"La vid\xE9o est trop volumineuse. R\xE9essayez dans un endroit mieux \xE9clair\xE9."},retry:{key:"fcv2.retry",fr:"R\xE9essayer"},listen:{key:"fcv2.listen",fr:"\xC9couter"}};var fe=2500,ye=1e3,ge=1500,J=25e5,y=class extends Error{constructor(e,r){super(r??e),this.kind=e}},T=class{constructor(){this.recorder=null;this.stream=null;this.chunks=[];this.bytes=0;this.hardStopTimer=null;this.graceTimer=null;this.settled=!1}clearTimers(){this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.graceTimer&&clearTimeout(this.graceTimer),this.hardStopTimer=null,this.graceTimer=null}record(e,r){if(this.recorder&&!this.settled)return Promise.reject(new y("generic","record() called while a recording is in flight \u2014 ClipRecorder handles one recording at a time"));this.recorder=null,this.clearTimers(),this.chunks=[],this.bytes=0,this.settled=!1,this.stream=e;let i=Z();return new Promise((n,s)=>{let a;try{a=new MediaRecorder(e,i?{mimeType:i,videoBitsPerSecond:J}:{videoBitsPerSecond:J})}catch{try{a=new MediaRecorder(e)}catch{s(new y("unsupported"));return}}this.recorder=a;let o=d=>{this.settled||(this.settled=!0,this.clearTimers(),d())},c=()=>o(()=>{let d=a.mimeType||i||L,u=new Blob(this.chunks,{type:d});if(u.size===0){s(new y("generic","empty clip"));return}if(w(u)){s(new y("cliptoolarge"));return}n({blob:u,mimeType:d})});a.ondataavailable=d=>{d.data&&d.data.size&&(this.chunks.push(d.data),this.bytes+=d.data.size,this.bytes>F&&o(()=>{try{a.state!=="inactive"&&a.stop()}catch{}s(new y("cliptoolarge"))}))},a.onstop=c,a.onerror=()=>o(()=>s(new y("generic")));try{a.start(ye)}catch{o(()=>s(new y("generic")));return}this.hardStopTimer=setTimeout(()=>{if(this.settled||r?.(),a.state!=="inactive"){try{a.stop()}catch{c()}this.graceTimer=setTimeout(c,ge)}else c()},fe)})}stop(e){this.clearTimers();let r=this.recorder;if(r&&r.state!=="inactive")try{r.stop()}catch{}this.recorder=null,(e??this.stream)?.getTracks().forEach(n=>n.stop()),this.stream=null}};function ee(t,e){return{video:{width:{ideal:1280,max:1280},height:{ideal:720,max:720},facingMode:e,frameRate:{ideal:24,max:30}},audio:!1}}var be=600;function G(){if(typeof window>"u"||typeof navigator>"u")return"desktop";let t=String(navigator.userAgent??"");if(/iPhone|iPod/i.test(t))return"phone";if(/iPad/i.test(t))return"tablet";if(/Android/i.test(t))return/Mobile/i.test(t)?"phone":"tablet";if(/BlackBerry|IEMobile|Opera Mini/i.test(t))return"phone";if(Number(navigator.maxTouchPoints??0)<=1)return"desktop";if(/Macintosh/.test(t))return"tablet";if(!lt())return"desktop";let r=ut();return r>0&&r<be?"phone":"tablet"}function te(){return G()!=="desktop"}function ut(){try{let t=window.screen,e=Number(t?.width??0),r=Number(t?.height??0);return e>0&&r>0?Math.min(e,r):0}catch{return 0}}function re(t){try{let r=t?.getVideoTracks?.()[0]?.getSettings?.().facingMode;return r==="user"||r==="environment"?r:null}catch{return null}}function lt(){try{return typeof window.matchMedia=="function"&&window.matchMedia("(pointer: coarse)").matches}catch{return!1}}var dt=.45,mt=.9,pt=.4;var ve=1e4,N=class t{constructor(e,r){this.tier="blaze";this.inner=e,r!==void 0&&(this.fallbackReason=r)}static async create(e,r){let i=await import("@mediapipe/tasks-vision"),n=await i.FilesetResolver.forVisionTasks(e),s=await i.FaceDetector.createFromOptions(n,{baseOptions:{modelAssetPath:`${e}/blaze_face_short_range.tflite`,delegate:"CPU"},runningMode:"IMAGE"});return new t(s,r)}async detect(e,r,i){let n;try{n=this.inner.detect(e).detections}catch{return null}let s=ht(n);if(s?.boundingBox===void 0)return null;let a=v(e),o=ft(s.keypoints,a),c=s.keypoints?.[2],d={box:{x:s.boundingBox.originX,y:s.boundingBox.originY,width:s.boundingBox.width,height:s.boundingBox.height},...o!==void 0?{eyes:o}:{},...c!==void 0?{nose:{x:c.x*a.width,y:c.y*a.height}}:{},score:s.categories[0]?.score??0};return M(d,e,r,i)}destroy(){try{this.inner.close()}catch{}}};function ht(t){let e,r=-1;for(let i of t){let n=i.categories[0]?.score??0;n>r&&(e=i,r=n)}return e}function ft(t,e){let r=t?.[0],i=t?.[1];if(r===void 0||i===void 0)return;let n=o=>({x:o.x*e.width,y:o.y*e.height}),[s,a]=[n(r),n(i)];return s.x<=a.x?{left:s,right:a}:{left:a,right:s}}function yt(){if(typeof OffscreenCanvas=="function")return new OffscreenCanvas(2,2);let t=document.createElement("canvas");return t.width=2,t.height=2,t}async function Ee(){let t=globalThis.FaceDetector;if(typeof t!="function")return{ok:!1,reason:"unsupported"};try{let e=new t({fastMode:!0,maxDetectedFaces:1});return await e.detect(yt()),{ok:!0,instance:e}}catch(e){return{ok:!1,reason:`smoke_failed:${e instanceof Error?e.message:String(e)}`}}}var V=class{constructor(e,r){this.tier="native";this.inner=e,r!==void 0&&(this.fallbackReason=r)}async detect(e,r,i){let n;try{n=await this.inner.detect(e)}catch{return null}let s=n[0];if(s===void 0)return null;let a=gt(s.landmarks),o={box:{x:s.boundingBox.x,y:s.boundingBox.y,width:s.boundingBox.width,height:s.boundingBox.height},...a!==void 0?{eyes:a}:{},score:1};return M(o,e,r,i)}destroy(){}};function gt(t){if(t===void 0)return;let e=t.filter(n=>n.type==="eye").map(n=>n.locations[0]).filter(n=>n!==void 0),[r,i]=e;if(!(r===void 0||i===void 0))return r.x<=i.x?{left:r,right:i}:{left:i,right:r}}var _e="/models-v3",xe=["native","blaze"],E=class extends Error{constructor(e){super(`no detector tier available (${e})`),this.name="DetectorLadderError",this.fallbackReason=e}};function v(t){let e=t;if(typeof e.videoWidth=="number"&&e.videoWidth>0)return{width:e.videoWidth,height:e.videoHeight??0};if(typeof e.naturalWidth=="number"&&e.naturalWidth>0)return{width:e.naturalWidth,height:e.naturalHeight??0};let r=typeof e.width=="number"?e.width:0,i=typeof e.height=="number"?e.height:0;return{width:r,height:i}}function M(t,e,r,i){let n=v(e),s=n.width>0?r/n.width:1,a=n.height>0?i/n.height:1,o=c=>({x:c.x*s,y:c.y*a});return{box:{x:t.box.x*s,y:t.box.y*a,width:t.box.width*s,height:t.box.height*a},...t.eyes!==void 0?{eyes:{left:o(t.eyes.left),right:o(t.eyes.right)}}:{},...t.nose!==void 0?{nose:o(t.nose)}:{},score:t.score}}function bt(t){return t instanceof Error?t.message:String(t)}async function _(t){let e=t.preferred??xe,r=[];for(let i of e){if(i==="native"){let n=await Ee();if(n.ok)return new V(n.instance,ne(r));r.push(`native:${n.reason}`);continue}try{return await vt(N.create(t.v3AssetBaseUrl??_e,ne(r)),t.blazeInitTimeoutMs??ve)}catch(n){r.push(n instanceof K?"blaze:blaze_init_timeout":`blaze:${bt(n)}`)}}throw new E(ne(r)??"no_tier_available")}function ne(t){return t.length>0?t.join("; "):void 0}var K=class extends Error{};function vt(t,e){return new Promise((r,i)=>{let n=setTimeout(()=>{i(new K(`init exceeded ${e}ms`)),t.then(s=>s.destroy(),()=>{})},e);t.then(s=>{clearTimeout(n),r(s)},s=>{clearTimeout(n),i(s)})})}var er=180,C=[100,190],Et=64;function Se(t,e){return .299*(t[e]??0)+.587*(t[e+1]??0)+.114*(t[e+2]??0)}function W(t){let{data:e,width:r,height:i}=t,n=r*i;if(n===0)return 0;let s=0;for(let a=0;a<n;a+=1)s+=Se(e,a*4);return s/n}function H(t){let{data:e,width:r,height:i}=t;if(r<3||i<3)return 0;let n=new Float32Array(r*i);for(let u=0;u<n.length;u+=1)n[u]=Se(e,u*4);let s=0,a=0,o=0;for(let u=1;u<i-1;u+=1)for(let l=1;l<r-1;l+=1){let m=u*r+l,p=(n[m-r]??0)+(n[m-1]??0)+(n[m+1]??0)+(n[m+r]??0)-4*(n[m]??0);s+=p,a+=p*p,o+=1}if(o===0)return 0;let c=s/o,d=a/o-c*c;return Math.min(1,Math.max(0,d)/180)}function ie(t){let e=W(t),[r,i]=C,n=e<r?r-e:e>i?e-i:0;return Math.max(0,1-n/Et)}var ke=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}),x=t=>Math.min(1,Math.max(0,t)),S=class{constructor(e={}){this.p=0;this.lastTickAt=null;this.lastCenter=null;this.velocityEma=0;this.qWindow=[];this.lastSizeDirection="ideal";this.t={...ke,...e}}reset(){this.p=0,this.lastTickAt=null,this.lastCenter=null,this.velocityEma=0,this.qWindow=[],this.lastSizeDirection="ideal"}tick(e){let{observation:r,quality:i,timestampMs:n}=e,s=this.lastTickAt===null?0:Math.max(0,(n-this.lastTickAt)/1e3);this.lastTickAt=n;let a={presence:0,centering:0,size:0,pose:0,sharpness:x(i.sharpness),exposure:x(i.exposure),motion:1};if(r!==null){a.presence=1;let u=this.geometryOf(r,e);a.centering=u.centering,a.size=u.size,a.pose=u.pose,a.motion=this.motionOf(u.center,u.iod,n)}else this.lastCenter=null,this.velocityEma=0;let o=Math.min(a.presence,a.centering,a.size,a.pose,a.sharpness,a.exposure,a.motion);this.p=x(this.p+(o>=this.t.Q_GOOD?this.t.RISE_PER_S*o:-this.t.FALL_PER_S*(1-o))*s),this.qWindow.push({at:n,q:o}),this.qWindow=this.qWindow.filter(u=>u.at>=n-this.t.READY_WINDOW_MS);let c=this.qWindow.map(u=>u.q);if(c.length>=3){let u=Math.min(...c),l=c.indexOf(u);c=c.filter((m,p)=>p!==l)}let d=this.p>=1&&c.every(u=>u>=this.t.Q_GOOD);return{at:n,q:o,p:this.p,factors:a,guidanceKey:this.guidanceOf(a,i,o),ready:d,accepted:o>=this.t.Q_GOOD}}geometryOf(e,r){let{box:i,eyes:n}=e,s={x:r.frameWidth/2,y:r.frameHeight/2},a=Math.min(r.frameWidth,r.frameHeight),o=n!==void 0?{x:(n.left.x+n.right.x)/2,y:(n.left.y+n.right.y)/2}:{x:i.x+i.width/2,y:i.y+i.height/2-this.t.BOX_EYE_OFFSET_FACTOR*i.height},c=n!==void 0?Math.hypot(n.right.x-n.left.x,n.right.y-n.left.y):this.t.IOD_BOX_PROXY_FACTOR*i.width,d=Math.hypot(o.x-s.x,o.y-s.y),u=c<=0?0:1-x(d/(this.t.CENTER_FALLOFF_IOD_MULTIPLE*c)),l=a>0?c/a:0;this.lastSizeDirection=l<this.t.SIZE_IDEAL_MIN?"far":l>this.t.SIZE_IDEAL_MAX?"close":"ideal";let m;l<this.t.SIZE_HARD_MIN||l>this.t.SIZE_HARD_MAX?m=0:l<this.t.SIZE_IDEAL_MIN?m=(l-this.t.SIZE_HARD_MIN)/(this.t.SIZE_IDEAL_MIN-this.t.SIZE_HARD_MIN):l>this.t.SIZE_IDEAL_MAX?m=(this.t.SIZE_HARD_MAX-l)/(this.t.SIZE_HARD_MAX-this.t.SIZE_IDEAL_MAX):m=1;let p=1;if(n!==void 0){let g=Math.abs(Math.atan2(n.right.y-n.left.y,n.right.x-n.left.x))*180/Math.PI;p=1-x(g/this.t.ROLL_MAX_DEG)}return{center:o,iod:c,centering:u,size:m,pose:p}}motionOf(e,r,i){let n=this.lastCenter;if(this.lastCenter={...e,at:i},n===null||r<=0)return 1;let s=(i-n.at)/1e3;if(s<=0)return 1;let a=Math.hypot(e.x-n.x,e.y-n.y)/r/s;a<=this.t.MOTION_DEADBAND_IOD_PER_S&&(a=0);let o=1-Math.exp(-s/this.t.MOTION_TAU_S);return this.velocityEma=o*a+(1-o)*this.velocityEma,1-x(this.velocityEma/this.t.MOTION_VELOCITY_IOD_PER_S)}guidanceOf(e,r,i){if(e.presence<=0)return"fcv3.no_face";if(e.size<this.t.GUIDE_SIZE)return this.sizeGuidance();if(e.centering<this.t.GUIDE_CENTERING)return"fcv3.center_face";if(e.pose<this.t.GUIDE_POSE)return"fcv3.straighten";if(e.exposure<this.t.GUIDE_EXPOSURE)return this.exposureGuidance(r);if(e.sharpness<this.t.GUIDE_SHARPNESS)return"fcv3.steady_camera";if(e.motion<this.t.GUIDE_MOTION)return"fcv3.hold_still";if(i<this.t.Q_GOOD){let n=[["size",this.sizeGuidance()],["centering","fcv3.center_face"],["pose","fcv3.straighten"],["exposure",this.exposureGuidance(r)],["sharpness","fcv3.steady_camera"],["motion","fcv3.hold_still"]],s=n[0];for(let a of n)e[a[0]]<e[s[0]]&&(s=a);return s[1]}return"fcv3.hold_still"}sizeGuidance(){return this.lastSizeDirection==="far"?"fcv3.come_closer":"fcv3.move_back"}exposureGuidance(e){let r=(C[0]+C[1])/2;return e.meanLuma<r?"fcv3.more_light":"fcv3.too_bright"}};var De=Object.freeze({LOW:Object.freeze({cadenceHz:5,inputWidth:128,animations:"reduced"}),MID:Object.freeze({cadenceHz:8,inputWidth:160,animations:"full"}),HIGH:Object.freeze({cadenceHz:10,inputWidth:192,animations:"full"})}),_t=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]);function ae(){let t=typeof navigator>"u"?void 0:navigator,e=!1;try{e=typeof WebAssembly<"u"&&WebAssembly.validate(_t)}catch{e=!1}return{cores:t?.hardwareConcurrency??2,memGB:t?.deviceMemory??null,simd:e}}function oe(t){let e=t.memGB??4;return t.cores<4||e<3?"LOW":t.cores>=8&&e>=6?"HIGH":"MID"}var se=["LOW","MID","HIGH"],I=class{constructor(e){this.samples=[];this.adjusted=!1;this.current=e}get deviceClass(){return this.current}get profile(){return De[this.current]}record(e){if(this.adjusted||this.samples.length>=10)return this.current;if(this.samples.push(e),this.samples.length<10)return this.current;this.adjusted=!0;let r=this.samples.reduce((i,n)=>i+n,0)/this.samples.length;if(r>70)this.current="LOW";else if(r<25){let i=se.indexOf(this.current);this.current=se[Math.min(se.length-1,i+1)]??this.current}return this.current}};var O=class{constructor(e){this.timer=null;this.frameCallbackId=null;this.running=!1;this.busy=!1;this.lastRunAt=Number.NEGATIVE_INFINITY;this.degradeCount=0;this.durations=[];this.options=e,this.periodMs=1e3/e.cadenceHz}start(){if(this.running)return;this.running=!0;let e=this.options.video;if(typeof e?.requestVideoFrameCallback=="function"){let r=()=>{this.running&&(this.frameCallbackId=e.requestVideoFrameCallback?.(()=>{this.frameCallbackId=null,this.now()-this.lastRunAt>=this.periodMs&&this.tick(),r()}))};r();return}this.timer=setInterval(()=>this.tick(),this.periodMs)}stop(){this.running=!1,this.timer!==null&&(clearInterval(this.timer),this.timer=null),this.frameCallbackId!==null&&(this.options.video?.cancelVideoFrameCallback?.(this.frameCallbackId),this.frameCallbackId=null)}stats(){let e=this.durations.length===0?0:this.durations.reduce((r,i)=>r+i,0)/this.durations.length;return{degradeCount:this.degradeCount,meanDetectMs:e}}now(){return this.options.now?.()??performance.now()}tick(){if(!this.running)return;if(this.busy){this.degradeCount+=1;return}this.busy=!0,this.lastRunAt=this.now();let e=this.now();this.options.run().catch(()=>{}).finally(()=>{this.busy=!1,this.durations.push(this.now()-e),this.durations.length>20&&this.durations.shift()})}};var we="0.1.0-rc.10";var Te="sekyro.did",Me;function Ce(){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 xt(){try{let t=localStorage.getItem(Te);if(t)return t;let e=Ce();return e!==void 0&&localStorage.setItem(Te,e),e}catch{return Me??(Me=Ce()),Me}}async function St(){let t=globalThis.crypto?.subtle;if(!t)return"";let e=navigator,r=JSON.stringify([e.userAgent,e.platform,e.hardwareConcurrency??null,e.deviceMemory??null,e.maxTouchPoints??0,screen.width,screen.height,screen.colorDepth,globalThis.devicePixelRatio??1,Intl.DateTimeFormat().resolvedOptions().timeZone,e.languages?.join(",")??e.language]),i=await t.digest("SHA-256",new TextEncoder().encode(r));return Array.from(new Uint8Array(i),n=>n.toString(16).padStart(2,"0")).join("").slice(0,32)}function kt(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 Dt(t){let e,r;return{timezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone?.slice(0,64)||void 0}catch{return}},noteCameraLabel(i){i&&(e=i.slice(0,128))},async deviceHeader(){try{r??(r=St().catch(()=>""));let i=[];navigator.webdriver&&i.push("webdriver"),/HeadlessChrome/.test(navigator.userAgent)&&i.push("headless");let n=await r,s=xt(),a={v:1,platform:"web",sdk:t.sdk.slice(0,64),ids:[...s?[{kind:"web_local",value:s.slice(0,128)}]:[],...n?[{kind:"web_fp",value:n}]:[]],screen:{w:screen.width,h:screen.height,dpr:globalThis.devicePixelRatio??1},...e?{cameraLabel:e}:{},...i.length?{signals:i}:{}};return kt(JSON.stringify(a))}catch{return}}}}var ce=Symbol.for("sekyro.web.clientContext"),ue=globalThis,wt=ue[ce]??(ue[ce]=Dt({sdk:`@sekyro/web@${we}`}));function Ie(t){try{let e=t.getVideoTracks?.()[0];e&&wt.noteCameraLabel(e.label)}catch{}}var b=1;function Oe(){return typeof OffscreenCanvas=="function"&&typeof createImageBitmap=="function"&&typeof Worker=="function"}function Tt(t,e={}){let r=e.createDetector??_,i=null;t.onmessage=n=>{let s=n.data;if(s.v!==b){s.bitmap?.close?.();return}if(s.type==="init"){r(s.options).then(a=>{i=a;let o={v:b,type:"ready",tier:a.tier,...a.fallbackReason!==void 0?{fallbackReason:a.fallbackReason}:{}};t.postMessage(o)});return}if(s.type==="detect"){let a=o=>{let c={v:b,type:"result",id:s.id,observation:o};t.postMessage(c),s.bitmap.close?.()};if(i===null){a(null);return}i.detect(s.bitmap,s.streamWidth,s.streamHeight).then(a,()=>a(null))}}}typeof self<"u"&&typeof self.importScripts=="function"&&Tt(self);var U=class t{constructor(e,r){this.pending=new Map;this.nextId=1;this.worker=e,this.tier=r.tier,r.fallbackReason!==void 0&&(this.fallbackReason=r.fallbackReason),e.addEventListener("message",i=>{let n=i.data;if(n.v!==b||n.type!=="result")return;let s=this.pending.get(n.id);this.pending.delete(n.id),s?.(n.observation)})}static create(e,r,i=1e4){return new Promise((n,s)=>{let a=setTimeout(()=>{e.removeEventListener("message",o),e.terminate(),s(new Error(`worker detector not ready within ${i}ms`))},i),o=d=>{let u=d.data;u.v!==b||u.type!=="ready"||(clearTimeout(a),e.removeEventListener("message",o),n(new t(e,u)))};e.addEventListener("message",o);let c={v:b,type:"init",options:r};e.postMessage(c)})}async detect(e,r,i){let n;try{typeof ImageBitmap<"u"&&e instanceof ImageBitmap?n=e:typeof createImageBitmap=="function"?n=await createImageBitmap(e):n=e}catch{return null}let s=this.nextId;return this.nextId+=1,new Promise(a=>{this.pending.set(s,a);let o={v:b,type:"detect",id:s,bitmap:n,streamWidth:r,streamHeight:i};this.worker.postMessage(o,[n])})}destroy(){for(let e of this.pending.values())e(null);this.pending.clear(),this.worker.terminate()}};var Mt=["size","centering","pose","exposure","sharpness","motion"];function Re(t){if(t.accepted)return null;if(t.factors.presence<=0)return"no_face";let e="size";for(let r of Mt)t.factors[r]<t.factors[e]&&(e=r);return e}var k=class{constructor(){this.blocked={};this.acceptedMs=0;this.ticks=0;this.lastAt=null}record(e){let r=this.lastAt===null?0:Math.max(0,e.at-this.lastAt);this.lastAt=e.at,this.ticks+=1;let i=Re(e);if(i===null){this.acceptedMs+=r;return}let n=this.blocked[i]??{count:0,ms:0};n.count+=1,n.ms+=r,this.blocked[i]=n}summary(){let e={};for(let[r,i]of Object.entries(this.blocked))e[r]={count:i.count,ms:Math.round(i.ms)};return{blocked:e,acceptedMs:Math.round(this.acceptedMs),ticks:this.ticks}}};var Be=1e3,z="fcv3.hold_upright",ze=200,X=4,Xe=600,He={sharpness:1,exposure:1,meanLuma:128};function Lt(t,e){return e.width=t.videoWidth,e.height=t.videoHeight,e.getContext("2d").drawImage(t,0,0),new Promise((r,i)=>e.toBlob(n=>n?r(n):i(new Error("empty-keyframe")),"image/jpeg",.92))}function Ft(){return G()==="phone"}var de=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.snapshotCanvas=null;this.options=e,this.facing=e.facingMode??"user"}get state(){return this.stateValue}on(e,r){let i=this.handlers.get(e);return i||(i=new Set,this.handlers.set(e,i)),i.add(r),()=>i?.delete(r)}emit(e,r){for(let i of[...this.handlers.get(e)??[]])i(r)}async start(e={}){e.facingMode!==void 0&&(this.facing=e.facingMode),this.attempt+=1,await this.run(this.attempt)}get facingMode(){return this.facing}retry(){this.teardownAttempt(),this.start()}switchCamera(){this.facing=this.facing==="user"?"environment":"user",this.teardownAttempt(),this.start()}destroy(){this.attempt+=1,this.teardownAttempt(),this.detector?.destroy(),this.detector=null,this.options.video.srcObject=null}async run(e){let{options:r}=this;this.fired=!1,this.lastGuidanceKey=null,this.carriedDegrade=0,this.carriedMeans=[],this.cameraRequestedAt=null,this.cameraReadyAt=null,this.faceAcquiredAt=null,this.captureCompleteAt=null,this.uprightGuard=(r.isPhone??Ft)(),this.setState("preflight");let i=j();if(i!=="OK"){this.fail(i==="INSECURE_CONTEXT"?"insecure":"unsupported");return}this.setState("acquiring");let n=r.getUserMedia??(c=>navigator.mediaDevices.getUserMedia(c)),s;this.cameraRequestedAt=this.now();try{s=await n(ee(te(),this.facing))}catch(c){if(e!==this.attempt)return;this.fail(Q(c));return}if(Ie(s),e!==this.attempt){for(let c of s.getTracks())c.stop();return}if(this.stream=s,this.facing=re(s)??this.facing,r.video.srcObject=s,await r.video.play().catch(()=>{}),e!==this.attempt)return;if(this.cameraReadyAt=this.now(),this.detector===null){let c={v3AssetBaseUrl:r.v3AssetBaseUrl},d=r.createDetector??(r.createWorker!==void 0&&Oe()?async()=>{try{return await U.create(r.createWorker(),c)}catch{return _(c)}}:()=>_(c)),u;try{u=await d()}catch(l){e===this.attempt&&this.fail("models",l instanceof E?l.fallbackReason:Nt(l));return}if(e!==this.attempt){u.destroy();return}this.detector=u,this.options.telemetry?.({type:"detector",tier:u.tier,fallbackReason:u.fallbackReason})}let a=ae(),o=r.deviceClass??oe(a);this.profiler=new I(o),this.options.telemetry?.({type:"profile",staticClass:o,activeClass:this.profiler.deviceClass,simd:a.simd}),this.gate=new S(r.thresholds??{}),this.blockStats=new k,this.lastGateSnapshotAt=this.now(),r.rankKeyframes?.()&&Promise.resolve().then(()=>(We(),Ke)).then(c=>le=c,()=>{}),this.setState("positioning"),this.positioningStartedAt=this.now(),this.startScheduler(e)}get animations(){return this.profiler?.profile.animations??"full"}startScheduler(e){let r=this.profiler;if(r===null)return;if(this.scheduler!==null){let n=this.scheduler.stats();this.carriedDegrade+=n.degradeCount,n.meanDetectMs>0&&this.carriedMeans.push(n.meanDetectMs),this.scheduler.stop()}let i=new O({cadenceHz:r.profile.cadenceHz,video:this.options.video,now:this.options.now,run:()=>this.detectTick(e)});this.scheduler=i,i.start()}async detectTick(e){let{detector:r,gate:i,profiler:n}=this,s=this.options.video;if(e!==this.attempt||r===null||i===null||n===null||this.fired||s.videoWidth===0)return;if(this.isLandscape()){this.holdUpright(e);return}let a=n.deviceClass,o=this.now(),c=this.options.makeSnapshot?.(s,n.profile.inputWidth)??this.defaultSnapshot(s,n.profile.inputWidth),d=null;try{d=await r.detect(c,s.videoWidth,s.videoHeight)}catch{d=null}if(e!==this.attempt||this.fired)return;n.record(this.now()-o),n.deviceClass!==a&&this.startScheduler(e);let u=d===null?He:this.options.measureQuality?.(s,d.box)??this.defaultQuality(s,d.box),l=i.tick({timestampMs:this.now(),observation:d,quality:u,frameWidth:s.videoWidth,frameHeight:s.videoHeight});l.accepted&&this.faceAcquiredAt===null&&(this.faceAcquiredAt=l.at),this.blockStats?.record(l),!l.ready&&l.at-this.lastGateSnapshotAt>=Be&&(this.lastGateSnapshotAt=l.at,this.reportGate(!1)),this.emit("checks",{engine:"v3",progress:l.p,q:l.q,factors:l.factors,attempt:e}),l.guidanceKey!==this.lastGuidanceKey&&(this.lastGuidanceKey=l.guidanceKey,this.emit("guidance",{key:l.guidanceKey})),l.ready&&this.stateValue==="positioning"&&(this.fired=!0,this.captureCompleteAt=l.at,this.fire(e))}async fire(e){let{options:r}=this,i=this.scheduler;i?.stop(),this.reportGate(!0);let n=i?.stats()??{degradeCount:0,meanDetectMs:0},s=[...this.carriedMeans,...n.meanDetectMs>0?[n.meanDetectMs]:[]];r.telemetry?.({type:"fired",timeToGateMs:this.now()-this.positioningStartedAt,degradeCount:this.carriedDegrade+n.degradeCount,meanDetectMs:s.length===0?0:s.reduce((h,f)=>h+f,0)/s.length});let a=r.mode??"clip",o=r.rankKeyframes?.()&&le?le.default(this,e).catch(()=>this.collectKeyframes(e)):this.collectKeyframes(e);if(a==="photo"){let h=this.watchRotation(e,null),f=await o;if(h(),e!==this.attempt)return;if(f===null){this.fail("generic");return}this.finishCapture({keyframe:f.blob,previewDataUrl:f.previewDataUrl});return}this.setState("recording");let c=r.createRecorder?.()??new T,d=this.stream;if(d===null){this.fail("generic");return}let u=this.watchRotation(e,c),l=null;o.then(h=>{l=h},()=>{});let m=()=>{e===this.attempt&&l!==null&&this.emit("frozen",{previewDataUrl:l.previewDataUrl})},p,g;try{[p,g]=await Promise.all([c.record(d,m),o])}catch(h){if(u(),e!==this.attempt)return;let f=h.kind;this.fail(f==="cliptoolarge"?"cliptoolarge":"recorder");return}if(u(),e===this.attempt){if(w(p.blob)){this.fail("cliptoolarge");return}if(g===null){this.fail("generic");return}this.finishCapture({clip:p.blob,clipMimeType:p.mimeType,keyframe:g.blob,previewDataUrl:g.previewDataUrl})}}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,centering:0,size:0,pose:0,sharpness:0,exposure:0,motion:0},attempt:e}),this.lastGuidanceKey!==z&&(this.lastGuidanceKey=z,this.emit("guidance",{key:z}))}watchRotation(e,r){if(!this.uprightGuard)return()=>{};let i=this.options.video,n=()=>{if(e!==this.attempt||r!==null&&this.stateValue!=="recording"){o();return}i.videoWidth>0&&this.isLandscape()&&(o(),this.abortRecording(e,r))},s=setInterval(n,ze);i.addEventListener?.("resize",n);let a=!1;function o(){a||(a=!0,clearInterval(s),i.removeEventListener?.("resize",n))}return o}abortRecording(e,r){if(e!==this.attempt)return;this.attempt+=1;let i=this.attempt;try{r?.stop()}catch{}this.fired=!1,this.captureCompleteAt=null,this.gate=new S(this.options.thresholds??{}),this.blockStats=new k,this.lastGateSnapshotAt=this.now(),this.lastGuidanceKey=null,this.setState("positioning"),this.positioningStartedAt=this.now(),this.holdUpright(i),this.startScheduler(i)}async collectKeyframes(e){let r=this.options.captureKeyframe??(s=>this.defaultKeyframe(s)),i=Xe/(X-1),n=null;for(let s=0;s<X;s+=1){if(e!==this.attempt)return n;try{let a=await r(this.options.video);(n===null||a.sharpness>n.sharpness)&&(n=a)}catch{}s<X-1&&await Gt(i)}return n}finishCapture(e){this.stopTracks(),this.setState("captured");let r=this.captureTiming();this.emit("artifacts",r===void 0?e:{...e,timing:r})}captureTiming(){let e={},r=(i,n,s)=>{n!==null&&s!==null&&(e[i]=Math.max(0,Math.round(s-n)))};return r("cameraReadyMs",this.cameraRequestedAt,this.cameraReadyAt),r("faceAcquireMs",this.cameraReadyAt,this.faceAcquiredAt),r("captureMs",this.faceAcquiredAt,this.captureCompleteAt),Object.keys(e).length>0?e:void 0}async defaultKeyframe(e){let r=document.createElement("canvas"),i=await(this.facing==="user"?$:Lt)(e,r),n=r.toDataURL("image/jpeg",.92);return{blob:i,previewDataUrl:n,sharpness:this.centerSharpness(e)}}defaultSnapshot(e,r){try{let i=this.snapshotCanvas??document.createElement("canvas"),n=r/Math.max(1,e.videoWidth),s=Math.max(1,Math.round(e.videoWidth*n)),a=Math.max(1,Math.round(e.videoHeight*n)),o=i.getContext("2d");return o===null?e:(i.width!==s&&(i.width=s),i.height!==a&&(i.height=a),o.drawImage(e,0,0,s,a),this.snapshotCanvas=i,i)}catch{return e}}defaultQuality(e,r){let i=Ue(e,r,96);return i===null?He:{sharpness:H(i),exposure:ie(i),meanLuma:W(i)}}centerSharpness(e){let r=v(e),i=Ue(e,{x:r.width*.25,y:r.height*.25,width:r.width*.5,height:r.height*.5},96);return i===null?0:H(i)}teardownAttempt(){this.scheduler?.stop(),this.scheduler=null,this.reportGate(!0),this.gate=null,this.stopTracks()}reportGate(e){let r=this.blockStats,i=this.profiler;if(r===null||i===null)return;let n=r.summary();e&&(this.blockStats=null),n.ticks!==0&&this.options.telemetry?.({type:"gate",final:e,activeClass:i.deviceClass,cadenceHz:i.profile.cadenceHz,...n})}stopTracks(){if(this.stream!==null){for(let e of this.stream.getTracks())e.stop();this.stream=null}}fail(e,r){this.scheduler?.stop(),this.reportGate(!0),this.stopTracks(),this.setState("error"),this.options.telemetry?.({type:"error",kind:e,fallbackReason:r}),this.emit("error",{kind:e,retryable:e!=="insecure"&&e!=="unsupported"})}setState(e){this.stateValue=e,this.emit("statechange",{state:e})}now(){return this.options.now?.()??performance.now()}},le;function Gt(t){return new Promise(e=>setTimeout(e,t))}function Nt(t){return t instanceof Error?t.message:String(t)}function Ue(t,e,r){try{let i=document.createElement("canvas"),n=r/Math.max(1,e.width);i.width=Math.max(1,Math.round(e.width*n)),i.height=Math.max(1,Math.round(e.height*n));let s=i.getContext("2d");return s===null?null:(s.drawImage(t,e.x,e.y,e.width,e.height,0,0,i.width,i.height),s.getImageData(0,0,i.width,i.height))}catch{return null}}0&&(module.exports={CENTERED_FACTOR,CIRCLE_RADIUS_FACTOR,CLIP_MS,CaptureSessionV3,ClipError,ClipRecorder,DEFAULT_CLIP_MIME,DEFAULT_TIER_ORDER,DEFAULT_V3_ASSET_BASE_URL,DEVICE_PROFILES,DetectScheduler,DetectorLadderError,DeviceProfiler,EXPOSURE_BAND,FaceGateV3,GATE_SNAPSHOT_MS,GateBlockStats,HOLD_UPRIGHT_KEY,IN_CIRCLE_FACTOR,KEYFRAME_CANDIDATES,KEYFRAME_WINDOW_MS,MAX_CLIP_BYTES,MIME_CANDIDATES,PHONE_MAX_SHORT_SIDE,SHARP_REF,STOP_GRACE_MS,TIMESLICE_MS,UPRIGHT_WATCH_MS,V3_GATE_DEFAULTS,VIDEO_BPS,blockReasonOf,buildCaptureConstraints,buildLivenessV2FormData,cameraPreflight,captureMirroredKeyframe,classifyDevice,createDetector,detectFormFactor,detectIsMobile,errorCopy,exposure,extForMime,intrinsicSize,isClipTooLarge,isMediaRecorderSupported,mapGetUserMediaError,meanLuma,pickMimeType,probeDevice,sharpness,toStreamPixels,trackFacingMode,uiCopy});
@@ -0,0 +1,87 @@
1
+ import { C as CameraErrorKind } from '../capture-session-v3-CmJw_bK0.cjs';
2
+ export { a as CLIP_MS, b as CaptureArtifacts, c as CaptureErrorKind, d as CaptureSessionEvents, e as CaptureSessionV3, f as CaptureSessionV3Events, g as CaptureSessionV3Options, h as CaptureSessionV3StartOptions, i as CaptureState, j as CaptureTiming, k as ClipError, l as ClipErrorKind, m as ClipRecorder, n as ClipResult, D as DEFAULT_CLIP_MIME, o as DEVICE_PROFILES, p as DeviceClass, q as DeviceProbe, r as DeviceProfile, s as DeviceProfiler, E as EscalationClipArtifact, t as EscalationHook, F as FaceGateV3, G as GATE_SNAPSHOT_MS, u as GateBlockEntry, v as GateBlockReason, w as GateBlockStats, x as GateBlockSummary, y as GateChecks, H as HOLD_UPRIGHT_KEY, K as KEYFRAME_CANDIDATES, z as KEYFRAME_WINDOW_MS, M as MAX_CLIP_BYTES, A as MIME_CANDIDATES, S as STOP_GRACE_MS, T as TIMESLICE_MS, U as UPRIGHT_WATCH_MS, V as V3ChecksPayload, B as V3GateFactor, I as V3GateQuality, J as V3GateThresholds, L as V3GateTick, N as V3GateTickInput, O as V3TelemetryEvent, P as V3_GATE_DEFAULTS, Q as VIDEO_BPS, R as blockReasonOf, W as buildLivenessV2FormData, X as cameraPreflight, Y as classifyDevice, Z as extForMime, _ as isClipTooLarge, $ as isMediaRecorderSupported, a0 as mapGetUserMediaError, a1 as pickMimeType, a2 as probeDevice } from '../capture-session-v3-CmJw_bK0.cjs';
3
+ export { C as CENTERED_FACTOR, a as CIRCLE_RADIUS_FACTOR, F as FormFactor, I as IN_CIRCLE_FACTOR, P as PHONE_MAX_SHORT_SIDE, b as buildCaptureConstraints, d as detectFormFactor, c as detectIsMobile, t as trackFacingMode } from '../capture-constraints-B5omafmk.cjs';
4
+ export { C as CreateDetectorOptions, D as DEFAULT_TIER_ORDER, a as DEFAULT_V3_ASSET_BASE_URL, b as Detector, c as DetectorLadderError, F as FaceObservation, d as createDetector, i as intrinsicSize, t as toStreamPixels } from '../detect-worker-DclNxkZT.cjs';
5
+
6
+ declare function captureMirroredKeyframe(video: HTMLVideoElement, canvas: HTMLCanvasElement, quality?: number): Promise<Blob>;
7
+
8
+ /** i18n key + inline French fallback (repo convention: t(key, frenchFallback)). */
9
+ declare const errorCopy: Record<CameraErrorKind, {
10
+ key: string;
11
+ fr: string;
12
+ }>;
13
+ declare const uiCopy: {
14
+ readonly recording: {
15
+ readonly key: "fcv2.recording";
16
+ readonly fr: "Enregistrement en cours…";
17
+ };
18
+ readonly uploading: {
19
+ readonly key: "fcv2.uploading";
20
+ readonly fr: "Envoi en cours…";
21
+ };
22
+ readonly clipTooLarge: {
23
+ readonly key: "fcv2.err.cliptoolarge";
24
+ readonly fr: "La vidéo est trop volumineuse. Réessayez dans un endroit mieux éclairé.";
25
+ };
26
+ readonly retry: {
27
+ readonly key: "fcv2.retry";
28
+ readonly fr: "Réessayer";
29
+ };
30
+ readonly listen: {
31
+ readonly key: "fcv2.listen";
32
+ readonly fr: "Écouter";
33
+ };
34
+ };
35
+
36
+ /** Laplacian-variance normalization reference — crops whose edge variance
37
+ * reaches this value (or beyond) count as fully sharp. */
38
+ declare const SHARP_REF = 180;
39
+ /** Mean-luma comfort band: inside → exposure 1; outside → linear falloff.
40
+ * Dark bound raised 70→100 (operator ruling 2026-07-07): face crops in the
41
+ * 70–100 range passed the gate but kept drawing dark-face review verdicts —
42
+ * gating them here converts that into pre-capture more_light coaching. */
43
+ declare const EXPOSURE_BAND: readonly [number, number];
44
+ declare function meanLuma(image: ImageData): number;
45
+ /**
46
+ * Sharpness = variance of the 3×3 Laplacian (∇² kernel [0,1,0;1,−4,1;0,1,0])
47
+ * over the interior pixels, normalized 0..1 against SHARP_REF. Flat crop → 0;
48
+ * hard edges → 1 (clamped).
49
+ */
50
+ declare function sharpness(image: ImageData): number;
51
+ /** Exposure factor: 1 inside the band; linear falloff to 0 over
52
+ * EXPOSURE_FALLOFF luma outside it. */
53
+ declare function exposure(image: ImageData): number;
54
+
55
+ interface DetectSchedulerOptions {
56
+ /** Ticks per second (profile cadenceHz). */
57
+ cadenceHz: number;
58
+ /** One detection pass — the scheduler awaits it and measures wall time. */
59
+ run: () => Promise<void>;
60
+ /** When provided AND it exposes requestVideoFrameCallback, ticks ride real
61
+ * camera frames (throttled to the cadence) instead of a timer. */
62
+ video?: HTMLVideoElement;
63
+ /** Injectable clock (tests) — defaults to performance.now. */
64
+ now?: () => number;
65
+ }
66
+ declare class DetectScheduler {
67
+ private readonly options;
68
+ private readonly periodMs;
69
+ private timer;
70
+ private frameCallbackId;
71
+ private running;
72
+ private busy;
73
+ private lastRunAt;
74
+ private degradeCount;
75
+ private readonly durations;
76
+ constructor(options: DetectSchedulerOptions);
77
+ start(): void;
78
+ stop(): void;
79
+ stats(): {
80
+ degradeCount: number;
81
+ meanDetectMs: number;
82
+ };
83
+ private now;
84
+ private tick;
85
+ }
86
+
87
+ export { CameraErrorKind, DetectScheduler, type DetectSchedulerOptions, EXPOSURE_BAND, SHARP_REF, captureMirroredKeyframe, errorCopy, exposure, meanLuma, sharpness, uiCopy };
@@ -0,0 +1,87 @@
1
+ import { C as CameraErrorKind } from '../capture-session-v3-DGG2stO6.js';
2
+ export { a as CLIP_MS, b as CaptureArtifacts, c as CaptureErrorKind, d as CaptureSessionEvents, e as CaptureSessionV3, f as CaptureSessionV3Events, g as CaptureSessionV3Options, h as CaptureSessionV3StartOptions, i as CaptureState, j as CaptureTiming, k as ClipError, l as ClipErrorKind, m as ClipRecorder, n as ClipResult, D as DEFAULT_CLIP_MIME, o as DEVICE_PROFILES, p as DeviceClass, q as DeviceProbe, r as DeviceProfile, s as DeviceProfiler, E as EscalationClipArtifact, t as EscalationHook, F as FaceGateV3, G as GATE_SNAPSHOT_MS, u as GateBlockEntry, v as GateBlockReason, w as GateBlockStats, x as GateBlockSummary, y as GateChecks, H as HOLD_UPRIGHT_KEY, K as KEYFRAME_CANDIDATES, z as KEYFRAME_WINDOW_MS, M as MAX_CLIP_BYTES, A as MIME_CANDIDATES, S as STOP_GRACE_MS, T as TIMESLICE_MS, U as UPRIGHT_WATCH_MS, V as V3ChecksPayload, B as V3GateFactor, I as V3GateQuality, J as V3GateThresholds, L as V3GateTick, N as V3GateTickInput, O as V3TelemetryEvent, P as V3_GATE_DEFAULTS, Q as VIDEO_BPS, R as blockReasonOf, W as buildLivenessV2FormData, X as cameraPreflight, Y as classifyDevice, Z as extForMime, _ as isClipTooLarge, $ as isMediaRecorderSupported, a0 as mapGetUserMediaError, a1 as pickMimeType, a2 as probeDevice } from '../capture-session-v3-DGG2stO6.js';
3
+ export { C as CENTERED_FACTOR, a as CIRCLE_RADIUS_FACTOR, F as FormFactor, I as IN_CIRCLE_FACTOR, P as PHONE_MAX_SHORT_SIDE, b as buildCaptureConstraints, d as detectFormFactor, c as detectIsMobile, t as trackFacingMode } from '../capture-constraints-B5omafmk.js';
4
+ export { C as CreateDetectorOptions, D as DEFAULT_TIER_ORDER, a as DEFAULT_V3_ASSET_BASE_URL, b as Detector, c as DetectorLadderError, F as FaceObservation, d as createDetector, i as intrinsicSize, t as toStreamPixels } from '../detect-worker-DclNxkZT.js';
5
+
6
+ declare function captureMirroredKeyframe(video: HTMLVideoElement, canvas: HTMLCanvasElement, quality?: number): Promise<Blob>;
7
+
8
+ /** i18n key + inline French fallback (repo convention: t(key, frenchFallback)). */
9
+ declare const errorCopy: Record<CameraErrorKind, {
10
+ key: string;
11
+ fr: string;
12
+ }>;
13
+ declare const uiCopy: {
14
+ readonly recording: {
15
+ readonly key: "fcv2.recording";
16
+ readonly fr: "Enregistrement en cours…";
17
+ };
18
+ readonly uploading: {
19
+ readonly key: "fcv2.uploading";
20
+ readonly fr: "Envoi en cours…";
21
+ };
22
+ readonly clipTooLarge: {
23
+ readonly key: "fcv2.err.cliptoolarge";
24
+ readonly fr: "La vidéo est trop volumineuse. Réessayez dans un endroit mieux éclairé.";
25
+ };
26
+ readonly retry: {
27
+ readonly key: "fcv2.retry";
28
+ readonly fr: "Réessayer";
29
+ };
30
+ readonly listen: {
31
+ readonly key: "fcv2.listen";
32
+ readonly fr: "Écouter";
33
+ };
34
+ };
35
+
36
+ /** Laplacian-variance normalization reference — crops whose edge variance
37
+ * reaches this value (or beyond) count as fully sharp. */
38
+ declare const SHARP_REF = 180;
39
+ /** Mean-luma comfort band: inside → exposure 1; outside → linear falloff.
40
+ * Dark bound raised 70→100 (operator ruling 2026-07-07): face crops in the
41
+ * 70–100 range passed the gate but kept drawing dark-face review verdicts —
42
+ * gating them here converts that into pre-capture more_light coaching. */
43
+ declare const EXPOSURE_BAND: readonly [number, number];
44
+ declare function meanLuma(image: ImageData): number;
45
+ /**
46
+ * Sharpness = variance of the 3×3 Laplacian (∇² kernel [0,1,0;1,−4,1;0,1,0])
47
+ * over the interior pixels, normalized 0..1 against SHARP_REF. Flat crop → 0;
48
+ * hard edges → 1 (clamped).
49
+ */
50
+ declare function sharpness(image: ImageData): number;
51
+ /** Exposure factor: 1 inside the band; linear falloff to 0 over
52
+ * EXPOSURE_FALLOFF luma outside it. */
53
+ declare function exposure(image: ImageData): number;
54
+
55
+ interface DetectSchedulerOptions {
56
+ /** Ticks per second (profile cadenceHz). */
57
+ cadenceHz: number;
58
+ /** One detection pass — the scheduler awaits it and measures wall time. */
59
+ run: () => Promise<void>;
60
+ /** When provided AND it exposes requestVideoFrameCallback, ticks ride real
61
+ * camera frames (throttled to the cadence) instead of a timer. */
62
+ video?: HTMLVideoElement;
63
+ /** Injectable clock (tests) — defaults to performance.now. */
64
+ now?: () => number;
65
+ }
66
+ declare class DetectScheduler {
67
+ private readonly options;
68
+ private readonly periodMs;
69
+ private timer;
70
+ private frameCallbackId;
71
+ private running;
72
+ private busy;
73
+ private lastRunAt;
74
+ private degradeCount;
75
+ private readonly durations;
76
+ constructor(options: DetectSchedulerOptions);
77
+ start(): void;
78
+ stop(): void;
79
+ stats(): {
80
+ degradeCount: number;
81
+ meanDetectMs: number;
82
+ };
83
+ private now;
84
+ private tick;
85
+ }
86
+
87
+ export { CameraErrorKind, DetectScheduler, type DetectSchedulerOptions, EXPOSURE_BAND, SHARP_REF, captureMirroredKeyframe, errorCopy, exposure, meanLuma, sharpness, uiCopy };
@@ -0,0 +1 @@
1
+ import{a as x,b as k,c as z,d as C,e as L,f as T,g as E,h as N,i as w,j as D,k as G,l as I,m as J,n as M,o as Q,p as W,q as X,r as Y}from"../chunk-SZ7YGNUZ.js";import{a as e,b as r,c as o,d as n,e as a,f as s,g as t,h as i}from"../chunk-FUHDOEBP.js";import{a as P,b as S,c as B,d as F}from"../chunk-POIQGEZM.js";import{a as c,b as p,c as u,d as f,e as m,f as d,g as l,h as v,i as y,j as g}from"../chunk-FHJ7HO3M.js";import{a as O,b as U,c as V,d as j,e as q}from"../chunk-FPXL63KZ.js";import"../chunk-BAGSM67V.js";import{a as R,b as h,c as b,d as A,e as H,f as K}from"../chunk-OKWG3PVH.js";var Z={permission:{key:"fcv2.err.permission",fr:"Autorisez la cam\xE9ra dans les r\xE9glages du navigateur (ic\xF4ne cam\xE9ra dans la barre d\u2019adresse), puis r\xE9essayez."},notfound:{key:"fcv2.err.notfound",fr:"Aucune cam\xE9ra d\xE9tect\xE9e. Branchez ou activez une cam\xE9ra, puis r\xE9essayez."},inuse:{key:"fcv2.err.inuse",fr:"La cam\xE9ra est utilis\xE9e par une autre application. Fermez-la puis r\xE9essayez."},overconstrained:{key:"fcv2.err.overconstrained",fr:"La cam\xE9ra ne prend pas en charge les r\xE9glages demand\xE9s. Nouvel essai en cours\u2026"},insecure:{key:"fcv2.err.insecure",fr:"La cam\xE9ra n\xE9cessite une connexion s\xE9curis\xE9e (HTTPS). Ouvrez la page en HTTPS."},unsupported:{key:"fcv2.err.unsupported",fr:"Votre navigateur ne prend pas en charge l\u2019enregistrement vid\xE9o. Utilisez un navigateur r\xE9cent."},generic:{key:"fcv2.err.generic",fr:"Cam\xE9ra indisponible. R\xE9essayez ou contactez le support."}},_={recording:{key:"fcv2.recording",fr:"Enregistrement en cours\u2026"},uploading:{key:"fcv2.uploading",fr:"Envoi en cours\u2026"},clipTooLarge:{key:"fcv2.err.cliptoolarge",fr:"La vid\xE9o est trop volumineuse. R\xE9essayez dans un endroit mieux \xE9clair\xE9."},retry:{key:"fcv2.retry",fr:"R\xE9essayer"},listen:{key:"fcv2.listen",fr:"\xC9couter"}};export{i as CENTERED_FACTOR,s as CIRCLE_RADIUS_FACTOR,x as CLIP_MS,Y as CaptureSessionV3,L as ClipError,T as ClipRecorder,u as DEFAULT_CLIP_MIME,h as DEFAULT_TIER_ORDER,R as DEFAULT_V3_ASSET_BASE_URL,P as DEVICE_PROFILES,N as DetectScheduler,b as DetectorLadderError,F as DeviceProfiler,U as EXPOSURE_BAND,D as FaceGateV3,J as GATE_SNAPSHOT_MS,I as GateBlockStats,M as HOLD_UPRIGHT_KEY,t as IN_CIRCLE_FACTOR,W as KEYFRAME_CANDIDATES,X as KEYFRAME_WINDOW_MS,l as MAX_CLIP_BYTES,c as MIME_CANDIDATES,r as PHONE_MAX_SHORT_SIDE,O as SHARP_REF,z as STOP_GRACE_MS,k as TIMESLICE_MS,Q as UPRIGHT_WATCH_MS,w as V3_GATE_DEFAULTS,C as VIDEO_BPS,G as blockReasonOf,e as buildCaptureConstraints,g as buildLivenessV2FormData,m as cameraPreflight,E as captureMirroredKeyframe,B as classifyDevice,K as createDetector,o as detectFormFactor,n as detectIsMobile,Z as errorCopy,q as exposure,y as extForMime,A as intrinsicSize,v as isClipTooLarge,d as isMediaRecorderSupported,f as mapGetUserMediaError,V as meanLuma,p as pickMimeType,S as probeDevice,j as sharpness,H as toStreamPixels,a as trackFacingMode,_ as uiCopy};
@@ -0,0 +1,42 @@
1
+ var Y={fp12:"08390000c48a",engine:"sekyro-ocr-1",precision:"fp32",files:{"sekyro-ocr.wasm":{bytes:3550608,sha256:"c15968a6de3d2225e2fdbf36d71a9214c2910419056c6878444fd2d0567bb748",tier:"live",contentType:"application/wasm"},"sekyro-ocr.mjs":{bytes:4270,sha256:"209a78d96ca53344996a0c2300aed4ff8a5c69e142713216975a2840eec08cac",tier:"bundled",contentType:"text/javascript"},"det.param":{bytes:24252,sha256:"c39ba0b1195e8ad37cfc5bdd7acedcfc1d9cb901e7b8eb1c9c4f6e5a66c04eb3",tier:"live",contentType:"text/plain"},"det.bin":{bytes:4685856,sha256:"652bafe366565109a1a5766caf482bc46f01481f8044d3a785bd9a1be67c63bb",tier:"live",contentType:"application/octet-stream"},"mrz-rec.param":{bytes:3510,sha256:"bc69b1b9683e35f6605b21001fadeb81468063459c00c0fc83c67c139f23df01",tier:"live",contentType:"text/plain"},"mrz-rec.bin":{bytes:494196,sha256:"de93a2aa2f08670cc7dedd17ba378d2f5d7cf6ae409054a9eac863a02c2febae",tier:"live",contentType:"application/octet-stream"},"mrz_dict.txt":{bytes:73,sha256:"b19858a4de2ccbbbdd4b53982188ea2c7664013183bbd1ae9d20ab52c661f97f",tier:"live",contentType:"text/plain"},"latin-rec.param":{bytes:19602,sha256:"2ae30dfdc7ee482c6cbbc0419c16ee125e880e9eaf69053d61953694bb0fcf4c",tier:"lazy",contentType:"text/plain"},"latin-rec.bin":{bytes:10750388,sha256:"f91ebdcf4d6b58c58a87704160e59d07ae56bc2d5021eae09d095c5a20bf7525",tier:"lazy",contentType:"application/octet-stream"},"ppocr_keys_v1.txt":{bytes:26249,sha256:"28b2362ad4ab2dc38769aa72feb535e3a9ddb3fd2a7585a05920e6393b1dc7f7",tier:"lazy",contentType:"text/plain"},"arabic-rec.param":{bytes:9858,sha256:"4e5cc85667dfaaa0c67d3f308400645a578c08bd43f952cab6c55b7bce143ea9",tier:"lazy",contentType:"text/plain"},"arabic-rec.bin":{bytes:8853572,sha256:"5acc3265a1738dc31316258383830d5dbdfa5e8ebc2e710f9001f832ecfbffb0",tier:"lazy",contentType:"application/octet-stream"},"arabic_dict.txt":{bytes:405,sha256:"637c27c88512c22089bef927b34ada08f748dc132ac70facd68d8202384c2726",tier:"lazy",contentType:"text/plain"}}};var ut="sekyro-mrz-1";function dt(e){return Array.from(new Uint8Array(e),t=>t.toString(16).padStart(2,"0")).join("")}async function be(e){return dt(await crypto.subtle.digest("SHA-256",e))}function Ne(e,t){return be(new TextEncoder().encode(`${ut}\0${e}\0${t.join(`
2
+ `)}`))}var G=class extends Error{constructor(t){super(t),this.name="AssetFailure",this.reason=t}},_e=Object.keys(Y.files).filter(e=>Y.files[e].tier==="live"),rn=Object.keys(Y.files).filter(e=>Y.files[e].tier==="lazy");function ft(e,t){return`${e.replace(/\/+$/,"")}/${Y.fp12}/${t}`}async function mt(e,t,n,s=fetch,r=()=>performance.now()){let o=Y.files[t],i=r(),l=async b=>{try{let f=await s(ft(e,t),{cache:b,signal:n,credentials:"omit"});if(!f.ok)throw new G("download");return await f.arrayBuffer()}catch(f){throw f instanceof G?f:new G("download")}},a=async b=>b.byteLength===o.bytes&&await be(b)===o.sha256,d=await l("force-cache");if(!await a(d)&&(d=await l("reload"),!await a(d)))throw new G("integrity");return{bytes:d,ms:r()-i}}async function Te(e,t,n,s=fetch,r=()=>performance.now()){let o=new AbortController,i=new Map,l=t.reduce((f,p)=>f+Y.files[p].bytes,0),a=r(),d=!0,b=0;for(let f of t){let p=await mt(e,f,o.signal,s,r);i.set(f,p.bytes),p.ms>=50&&(d=!1),b+=p.bytes.byteLength;let y=r()-a;if(b<l&&y>0&&y*l/b>n)throw o.abort(),new G("download")}return{files:i,downloadMs:Math.round(r()-a),cached:d}}var I=class extends Error{constructor(t){super(t),this.name="OcrFailure",this.code=t}};function Oe(e){return[...e.split(`
3
+ `)," "]}function Le(e,t,n,s,r){if(n<2||e.length===0||e.length!==t.length||s.length<n-1)throw new I("OCR_INFERENCE_FAILED");let o="",i=-1,l=0,a=0;for(let b=0;b<e.length;b++){let f=e[b];if(!Number.isInteger(f)||f<0||f>=n)throw new I("OCR_INFERENCE_FAILED");f!==0&&f!==i&&(o+=s[f-1],l+=Math.fround(t[b]),a++),i=f}return{text:r?Array.from(o).reverse().join(""):o,score:a===0?0:l/a}}var we=e=>e.reduce((t,n)=>t+n,0)/e.length;function De(e){let t=e.filter(r=>r.score>=.5);if(t.length===0)return[];if(t.some(r=>r.box.length!==4||!Number.isFinite(r.score)||r.box.some(o=>!Number.isFinite(o.x)||!Number.isFinite(o.y))))throw new I("OCR_INFERENCE_FAILED");let n=we(t.map(r=>r.box[2].y-r.box[0].y)),s=[];for(let r of t){let o=(r.box[0].y+r.box[2].y)/2,i=s.find(l=>Math.abs((l[0].box[0].y+l[0].box[2].y)/2-o)<n/2);i===void 0?s.push([r]):i.push(r)}for(let r of s)r.sort((o,i)=>o.box[0].x-i.box[0].x);return s.sort((r,o)=>r[0].box[0].y-o[0].box[0].y),s.map(r=>{let o=r[0].box,i=r[r.length-1].box,l=[o[0],i[1],i[2],o[3]];return{text:r.map(a=>a.text).join(" "),x:Math.min(...l.map(a=>a.x)),y:Math.min(...l.map(a=>a.y)),x2:Math.max(...l.map(a=>a.x)),y2:Math.max(...l.map(a=>a.y)),score:we(r.map(a=>a.score))}})}var j={of(e,t,n){return!Number.isInteger(e)||!Number.isInteger(t)||!Number.isInteger(n)||t<1||t>12||n<1||n>new Date(Date.UTC(e,t,0)).getUTCDate()?null:{year:e,month:t,day:n}},iso(e){return`${String(e.year).padStart(4,"0")}-${String(e.month).padStart(2,"0")}-${String(e.day).padStart(2,"0")}`},parse(e){let[t,n,s]=e.split("-").map(Number);return{year:t,month:n,day:s}},today(){let e=new Date;return{year:e.getFullYear(),month:e.getMonth()+1,day:e.getDate()}}},ve=30,Pe=36,Ue=44,ge="MRT",bt=[7,3,1],gt=/^[0-9]{6}$/,ye=/^[0-9]{10}$/,Fe=e=>e!==void 0&&e.length===1&&e>="0"&&e<="9";function pt(e){return e>="0"&&e<="9"?e.charCodeAt(0)-48:e>="A"&&e<="Z"?e.charCodeAt(0)-55:0}function ue(e){let t=0;for(let n=0;n<e.length;n++)t+=pt(e[n])*bt[n%3];return String(t%10)}function D(e,t){return t==="<"?null:Fe(t)?ue(e)===t:!1}function ce(e){return e.trim().toUpperCase().replaceAll(" ","")}function yt(e,t){return(ce(e)+"<".repeat(t)).slice(0,t)}function k(e){return e.replace(/^<+|<+$/g,"")}var ht=new Set(`ABW AFG AGO AIA ALA ALB AND ARE ARG ARM ASM ATA ATF ATG AUS AUT AZE BDI BEL BEN BES BFA BGD BGR BHR
4
+ BHS BIH BLM BLR BLZ BMU BOL BRA BRB BRN BTN BVT BWA CAF CAN CCK CHE CHL CHN CIV CMR COD COG COK COL
5
+ COM CPV CRI CUB CUW CXR CYM CYP CZE DEU DJI DMA DNK DOM DZA ECU EGY ERI ESH ESP EST ETH FIN FJI FLK
6
+ FRA FRO FSM GAB GBR GEO GGY GHA GIB GIN GLP GMB GNB GNQ GRC GRD GRL GTM GUF GUM GUY HKG HMD HND HRV
7
+ HTI HUN IDN IMN IND IOT IRL IRN IRQ ISL ISR ITA JAM JEY JOR JPN KAZ KEN KGZ KHM KIR KNA KOR KWT LAO
8
+ LBN LBR LBY LCA LIE LKA LSO LTU LUX LVA MAC MAF MAR MCO MDA MDG MDV MEX MHL MKD MLI MLT MMR MNE MNG
9
+ MNP MOZ MRT MSR MTQ MUS MWI MYS MYT NAM NCL NER NFK NGA NIC NIU NLD NOR NPL NRU NZL OMN PAK PAN PCN
10
+ PER PHL PLW PNG POL PRI PRK PRT PRY PSE PYF QAT REU ROU RUS RWA SAU SDN SEN SGP SGS SHN SJM SLB SLE
11
+ SLV SMR SOM SPM SRB SSD STP SUR SVK SVN SWE SWZ SXM SYC SYR TCA TCD TGO THA TJK TKL TKM TLS TON TTO
12
+ TUN TUR TUV TWN TZA UGA UKR UMI URY USA UZB VAT VCT VEN VGB VIR VNM VUT WLF WSM XKK YEM ZAF ZMB ZWE`.trim().split(/\s+/)),At=new Set(`D GBD GBN GBO GBP GBS RKS UNK UNO UNA EUE XBA XIM XCC XCE XCO XDC XEC XES XMP XOM XPO XXA XXB XXC
13
+ XXX ANT NTZ UTO`.trim().split(/\s+/));function xt(e){return ht.has(e)||At.has(e)}var Mt="012568",Rt="OIZSGB",St="OQDILZSGB",It="000112568";function pe(e){let t=Mt.indexOf(e);return e.length!==1||t<0?e:Rt[t]}function Ct(e){let t=St.indexOf(e);return e.length!==1||t<0?e:It[t]}var Et=[["\xAB","<<"],["\u2039","<"],["\uFF1C","<"],["\u3008","<"],["\xD7","X"]],Ge=[`aaccc${"x".repeat(9)}n${"x".repeat(15)}`,`${"n".repeat(7)}x${"n".repeat(7)}ccc${"x".repeat(11)}n`,"a".repeat(30)],Ke=[`aaccc${"a".repeat(31)}`,`${"x".repeat(9)}nccc${"n".repeat(7)}x${"n".repeat(7)}${"x".repeat(7)}n`],ze=[`aaccc${"a".repeat(39)}`,`${"x".repeat(9)}nccc${"n".repeat(7)}x${"n".repeat(7)}${"x".repeat(14)}nn`];function Nt(e,t){let n="",s=0;for(;s<t.length;){let r=t[s];if(r==="c"){let i=e.substring(s,s+3),l=Array.from(i,pe).join("");n+=l!==i&&xt(l.replaceAll("<",""))?l:i,s+=3;continue}let o=e[s];n+=r==="a"?pe(o):r==="n"?Ct(o):o,s++}return n}function ee(e,t,n){return n.slice(0,e.length).map((s,r)=>{let o=Et.reduce((i,[l,a])=>i.replaceAll(l,a),ce(e[r]));return Nt(yt(o,t),s)})}function He(e,t){let n=e.filter(s=>s.trim().length>0);return t==="TD1"?ee(n.slice(0,3),ve,Ge):t==="TD2"?ee(n.slice(0,2),Pe,Ke):ee(n.slice(0,2),Ue,ze)}function he(e){let t=`${e.toUpperCase()}<<`.slice(0,2);return t==="AC"?"unknown":t==="IR"||t==="AR"||t[0]==="A"||t[0]==="C"?"residence_permit":t[0]==="P"?"passport":t[0]==="I"?"carte_identite":"unknown"}function _t(e){return ye.test(e)&&Number(e)%97===1}function Tt(e,t,n){if(!gt.test(e))return null;let s=Number(e.slice(0,2)),r=t?2e3+s:s>n.year%100?1900+s:2e3+s;return j.of(r,Number(e.slice(2,4)),Number(e.slice(4,6)))}function te(e,t,n){let s=Tt(e,t,n);return s?j.iso(s):""}function Ae(e){let t=e.split("<<").filter(n=>k(n).length>0);return[(t[0]??"").replaceAll("<"," ").trim(),(t[1]??"").replaceAll("<"," ").trim()]}var xe=e=>e==="M"||e==="F"?e:"",Ot=e=>e.substring(0,2).replaceAll("<",""),oe=e=>e.substring(2,5).replaceAll("<","");function We(e,t,n){if(t==="<"&&k(n).length>0){let s=n.indexOf("<"),r=s<0?n:n.slice(0,s);if(r.length>=2){let o=e+r.slice(0,-1);if(D(o,r[r.length-1])===!0)return{value:k(o),ok:!0,warn:null}}return{value:k(e),ok:!1,warn:"docnum_cd_mismatch"}}return{value:k(e),ok:D(e,t),warn:null}}var K=(e,t)=>({success:!1,error:e,fields:{},checkDigits:{},hardCdFail:!1,warns:[],...t===void 0?{}:{linesCount:t}});function Me(e,t,n,s,r,o,i){return{success:!0,documentType:e,format:t,documentCode:Ot(n),fields:s,checkDigits:r,hardCdFail:o,warns:i}}function Lt(e,t){if(e.length<3)return K("mrz_incomplete");let[n,s,r]=ee(e.slice(0,3),ve,Ge),o=oe(n)===ge||s.substring(15,18)===ge||_t(n.substring(15,25)),i=[],l={},a,d,b=!1;if(o){a=k(n.substring(5,14));let A=n[14];Fe(A)?(d=ue(n.substring(5,14))===A,d||i.push("td1_docnum_cd_mismatch")):d=null}else{let A=We(n.substring(5,14),n[14],n.substring(15,30));if(A.ok===null)return K("mrz_incomplete");a=A.value,d=A.ok,b=A.ok===!1&&A.warn===null,A.warn!==null&&i.push(A.warn)}l.document_number=d;let f=D(s.substring(0,6),s[6]),p=D(s.substring(8,14),s[14]);if(l.birth_date=f,l.expiry_date=p,f===null||p===null)return K("mrz_incomplete");let y=D(n.substring(5,30)+s.substring(0,7)+s.substring(8,15)+s.substring(18,29),s[29]);l.composite=y,y===!1&&i.push("composite_cd_mismatch");let m=o?n.substring(15,25):"",[u,R]=Ae(r),S=f===!1||p===!1||b;return Me(he(n.substring(0,2)),"TD1",n,{issuing_state:oe(n),document_number:a,nni:ye.test(m)?m:"",birth_date:te(s.substring(0,6),!1,t),expiry_date:te(s.substring(8,14),!0,t),sex:xe(s[7]),nationality:k(s.substring(15,18)),surname:u,given_names:R},l,S,i)}function wt(e,t){if(e.length<2)return K("mrz_incomplete");let[n,s]=ee(e.slice(0,2),Pe,Ke),r=[],o=We(s.substring(0,9),s[9],s.substring(28,35));o.warn!==null&&r.push(o.warn);let i=D(s.substring(13,19),s[19]),l=D(s.substring(21,27),s[27]),a={document_number:o.ok,birth_date:i,expiry_date:l};if(o.ok===null||i===null||l===null)return K("mrz_incomplete");let d=D(s.substring(0,10)+s.substring(13,20)+s.substring(21,35),s[35]);a.composite=d,d===!1&&r.push("composite_cd_mismatch");let[b,f]=Ae(n.substring(5,36)),p=o.ok===!1&&o.warn===null||i===!1||l===!1;return Me(he(n.substring(0,2)),"TD2",n,{issuing_state:oe(n),document_number:o.value,nni:"",birth_date:te(s.substring(13,19),!1,t),expiry_date:te(s.substring(21,27),!0,t),sex:xe(s[20]),nationality:k(s.substring(10,13)),surname:b,given_names:f},a,p,r)}function ke(e,t){if(e.length<2)return K("mrz_incomplete");let[n,s]=ee(e.slice(0,2),Ue,ze),r=oe(n)===ge,o=[],i={},l=s.substring(0,9),a=D(l,s[9]),d=D(s.substring(13,19),s[19]),b=D(s.substring(21,27),s[27]);if(i.document_number=a,i.birth_date=d,i.expiry_date=b,a===null||d===null||b===null)return K("mrz_incomplete");let f=s.substring(28,42),p="";if(k(f).length>0){let S=D(f,s[42]);i.personal_number=S;let A=k(f);r&&S!==!1&&ye.test(A)&&(p=A)}let y=D(s.substring(0,10)+s.substring(13,20)+s.substring(21,43),s[43]);i.composite=y,y===!1&&o.push("composite_cd_mismatch");let[m,u]=Ae(n.substring(5,44)),R=a===!1||d===!1||b===!1;return Me(he(n.substring(0,2)),"TD3",n,{issuing_state:oe(n),document_number:k(l),nni_candidate:p,birth_date:te(s.substring(13,19),!1,t),expiry_date:te(s.substring(21,27),!0,t),sex:xe(s[20]),nationality:k(s.substring(10,13)),surname:m,given_names:u},i,R,o)}var Be=new Set(["A","C","I"]);function Ve(e,t=j.today()){let n=e.filter(r=>r.trim().length>0);if(n.length===0)return K("mrz_unrecognized",0);let s=Array.from(ce(n[0]).slice(0,1),pe).join("");return n.length===3&&Be.has(s)?Lt(n,t):n.length===2&&s==="P"?ke(n,t):n.length===2&&Be.has(s)?Math.max(...n.map(r=>ce(r).length))>40?ke(n,t):wt(n,t):K("mrz_unrecognized",n.length)}var Dt=new Map([...(`ABWAW AFGAF AGOAO AIAAI ALAAX ALBAL ANDAD AREAE ARGAR ARMAM ASMAS ATAAQ
14
+ ATFTF ATGAG AUSAU AUTAT AZEAZ BDIBI BELBE BENBJ BESBQ BFABF BGDBD BGRBG
15
+ BHRBH BHSBS BIHBA BLMBL BLRBY BLZBZ BMUBM BOLBO BRABR BRBBB BRNBN BTNBT
16
+ BVTBV BWABW CAFCF CANCA CCKCC CHECH CHLCL CHNCN CIVCI CMRCM CODCD COGCG
17
+ COKCK COLCO COMKM CPVCV CRICR CUBCU CUWCW CXRCX CYMKY CYPCY CZECZ DEUDE
18
+ DJIDJ DMADM DNKDK DOMDO DZADZ ECUEC EGYEG ERIER ESHEH ESPES ESTEE ETHET
19
+ FINFI FJIFJ FLKFK FRAFR FROFO FSMFM GABGA GBRGB GEOGE GGYGG GHAGH GIBGI
20
+ GINGN GLPGP GMBGM GNBGW GNQGQ GRCGR GRDGD GRLGL GTMGT GUFGF GUMGU GUYGY
21
+ HKGHK HMDHM HNDHN HRVHR HTIHT HUNHU IDNID IMNIM INDIN IOTIO IRLIE IRNIR
22
+ IRQIQ ISLIS ISRIL ITAIT JAMJM JEYJE JORJO JPNJP KAZKZ KENKE KGZKG KHMKH
23
+ KIRKI KNAKN KORKR KWTKW LAOLA LBNLB LBRLR LBYLY LCALC LIELI LKALK LSOLS
24
+ LTULT LUXLU LVALV MACMO MAFMF MARMA MCOMC MDAMD MDGMG MDVMV MEXMX MHLMH
25
+ MKDMK MLIML MLTMT MMRMM MNEME MNGMN MNPMP MOZMZ MRTMR MSRMS MTQMQ MUSMU
26
+ MWIMW MYSMY MYTYT NAMNA NCLNC NERNE NFKNF NGANG NICNI NIUNU NLDNL NORNO
27
+ NPLNP NRUNR NZLNZ OMNOM PAKPK PANPA PCNPN PERPE PHLPH PLWPW PNGPG POLPL
28
+ PRIPR PRKKP PRTPT PRYPY PSEPS PYFPF QATQA REURE ROURO RUSRU RWARW SAUSA
29
+ SDNSD SENSN SGPSG SGSGS SHNSH SJMSJ SLBSB SLESL SLVSV SMRSM SOMSO SPMPM
30
+ SRBRS SSDSS STPST SURSR SVKSK SVNSI SWESE SWZSZ SXMSX SYCSC SYRSY TCATC
31
+ TCDTD TGOTG THATH TJKTJ TKLTK TKMTM TLSTL TONTO TTOTT TUNTN TURTR TUVTV
32
+ TWNTW TZATZ UGAUG UKRUA UMIUM URYUY USAUS UZBUZ VATVA VCTVC VENVE VGBVG
33
+ VIRVI VNMVN VUTVU WLFWF WSMWS YEMYE ZAFZA ZMBZM ZWEZW`.match(/[A-Z]{5}/g)??[]).map(e=>[e.slice(0,3),e.slice(3)]),["D","DE"]]),Ye={of(e){return Dt.get(e.replaceAll("<",""))??null}};var Se=e=>ue(e);function Qe(e){return e.slice(0,5e4).split(/\r?\n/).slice(0,200).map(t=>t.toUpperCase().replace(/[«‹〈]/g,"<").replace(/[^A-Z0-9<]/g,"")).filter(t=>t.length>0)}var Ze=e=>e.replace(/[OQ]/g,"0").replace(/[IL]/g,"1").replaceAll("Z","2").replaceAll("S","5").replaceAll("B","8");function Xe(e,t){let n=Ze(e),s=Ze(t);if(!/^\d{6}$/.test(n)||Se(n)!==s)return null;let r=2e3+Number(n.slice(0,2)),o=Number(n.slice(2,4)),i=Number(n.slice(4,6));return o>=1&&o<=12&&i>=1&&i<=new Date(Date.UTC(r,o,0)).getUTCDate()?n:null}function Re(e,t){let n=e.replace(/<+$/,"");return/^[A-Z0-9]+$/.test(n)&&Se(e)===t?n:null}function kt(e){if(e.length<15)return null;if(e[14]!=="<")return Re(e.substring(5,14),e[14]);let t=/^([A-Z0-9]+)</.exec(e.substring(15,Math.min(30,e.length)))?.[1];return t===void 0||t.length<2?null:Re(e.substring(5,14)+t.slice(0,-1),t[t.length-1])}var x=(e,t,n)=>t>=e.length?"":e.substring(t,Math.min(n,e.length)),Z=(e,t)=>t<e.length?e[t]:"",$e=/^[IAC][A-Z<][A-Z<]{3}/,Bt=/^P[A-Z<][A-Z<]{3}/,qe=/^[PIAC][A-Z<][A-Z<]{3}/;function vt(e){let t=Qe(e),n=[],s=[];for(let o=0;o<t.length;o++){let i="",l=0;for(;l<6&&o+l<t.length&&(i+=t[o+l],!(i.length>300));)s.push(i),l++}let r=(o,i,l)=>{if(i.length<(l?15:28))return;let a=new Map,d=l?kt(o):Re(x(i,0,9),Z(i,9)),b=Xe(l?x(i,0,6):x(i,13,19),l?Z(i,6):Z(i,19)),f=Xe(l?x(i,8,14):x(i,21,27),l?Z(i,14):Z(i,27));d!==null&&a.set("docNumber",d),b!==null&&a.set("dob6",b),f!==null&&a.set("expiry6",f),a.size>0&&n.push({fields:a,country:Ye.of(x(o,2,5))})};for(let o of s)$e.test(o)&&(o.length>=45&&r(o.substring(0,30),o.substring(30),!0),o.length>=64&&r(o.substring(0,36),o.substring(36),!1)),Bt.test(o)&&o.length>=72&&r(o.substring(0,44),o.substring(44),!1);for(let o=0;o<t.length-1;o++){let i=t[o],l=t[o+1];$e.test(i)&&i.length>=15&&i.length<=30&&r(i,l,!0),qe.test(i)&&i.length>=5&&i.length<=44&&r(i,l,!1)}return n}function Pt(e){let t=vt(e);if(t.length===0)return{};let n=Math.max(...t.map(o=>o.fields.size)),s=t.filter(o=>o.fields.size===n),r={};for(let o of["docNumber","dob6","expiry6"]){let i=new Set(s.map(l=>l.fields.get(o)).filter(l=>l!==void 0));i.size===1&&s.every(l=>l.fields.has(o))&&(r[o]=[...i][0])}return r}function Ut(e){let t=Pt(e),n=t.docNumber,s=t.dob6,r=t.expiry6;return n!==void 0&&s!==void 0&&r!==void 0?{docNumber:n,dob6:s,expiry6:r}:null}function et(e){let t=Gt(e);return t.length===1?t[0]:null}var Ft=e=>JSON.stringify([e.documentNumber,e.nationality,e.dob,e.sex,e.expiry,e.primaryIdentifier,e.secondaryIdentifier,e.optional]);function Gt(e){let t=Qe(e),n=[];for(let r=0;r<t.length;r++){let o=t[r];if(!qe.test(o))continue;let i=o.startsWith("P")?[44]:[30,36];for(let l of i){let a=l===30?3:2,d=t.slice(r,Math.min(t.length,r+a));d.length===a&&d.every(p=>p.length<=l)&&n.push(d.map(p=>p.padEnd(l,"<")).join(`
34
+ `));let b="",f=0;for(;f<6&&r+f<t.length&&(b+=t[r+f],b.length===l*a&&n.push(b),!(b.length>=l*a));)f++}}let s=new Map;for(let r of n){let o=Ut(r);if(o===null)continue;let i=r.includes(`
35
+ `)?r.split(`
36
+ `):r.match(r.length===90?/.{30}/g:r.length===88?/.{44}/g:/.{36}/g)??[],l=i[0]??"",a=i[1]??"",d=i.length===3,b=d?x(l,5,30)+x(a,0,7)+x(a,8,15)+x(a,18,29):x(a,0,10)+x(a,13,20)+x(a,21,a.length-1),f=d?Z(a,29):Z(a,a.length-1);if(!/^[0-9]$/.test(f)||Se(b)!==f)continue;let p=Kt(r);if(p===null||p.primaryIdentifier.length===0&&p.secondaryIdentifier.length===0||!/^[MFX]?$/.test(p.sex))continue;let y={...p,documentNumber:o.docNumber,dob:o.dob6,expiry:o.expiry6};s.set(Ft(y),{fields:y,mrzLines:i})}return[...s.values()]}var P=e=>e.replaceAll("<"," ").replace(/\s+/g," ").trim();function Je(e){let t=e.split("<<");return[P(t[0]??""),P(t.slice(1).join("<<"))]}var je=e=>e.length===0?null:e;function Kt(e){let t=e.split(/\r?\n/).map(s=>s.replace(/\s+$/,"")).filter(s=>s.length>0),n=e.replace(/[\r\n]/g,"");if(t.length===1&&(n.length===90?t=[n.substring(0,30),n.substring(30,60),n.substring(60,90)]:n.length===72?t=[n.substring(0,36),n.substring(36,72)]:n.length===88&&(t=[n.substring(0,44),n.substring(44,88)])),t.length===3){let[s,r,o]=t,i=Z(s,14)==="<"?/^([A-Z0-9]+)</.exec(x(s,15,30))?.[1]:void 0,l=P(x(s,5,14)+(i!==void 0&&i.length>1?i.slice(0,-1):"")),[a,d]=Je(o),b=P(`${x(s,15,30)}<${x(r,18,29)}`);return{documentNumber:l,nationality:P(x(r,15,18)),dob:x(r,0,6),sex:P(x(r,7,8)),expiry:x(r,8,14),primaryIdentifier:a,secondaryIdentifier:d,optional:je(b)}}if(t.length===2){let[s,r]=t,o=s.length>=44,[i,l]=Je(x(s,5,o?44:36));return{documentNumber:P(x(r,0,9)),nationality:P(x(r,10,13)),dob:x(r,13,19),sex:P(x(r,20,21)),expiry:x(r,21,27),primaryIdentifier:i,secondaryIdentifier:l,optional:je(P(o?x(r,28,42):x(r,28,35)))}}return null}function tt(e,t=j.today()){let n=Ve(e,t),s=n.format??null,r=s==="TD1"||s==="TD2"||s==="TD3"?He(e,s):[...e];return{format:s,documentCode:n.documentCode??null,lines:r,valid:n.success&&!n.hardCdFail}}var zt=/^[A-Z0-9<]{25,}$/;function Ht(e){return e.toUpperCase().replaceAll(" ","").replaceAll("\xAB","<").replaceAll("\u2039","<")}var Ie=(e,t,n)=>e.length>=t&&e.length<=n;function nt(e){let t=e.map(Ht).filter(n=>zt.test(n));for(let n=0;n+3<=t.length;n++){let s=t.slice(n,n+3);if(s.every(r=>Ie(r,28,32))&&"IAC".includes(s[0][0]))return s}for(let n=0;n+2<=t.length;n++){let s=t.slice(n,n+2);if(s.every(r=>Ie(r,40,46))&&s[0].startsWith("P")||s.every(r=>Ie(r,34,38))&&"IACPV".includes(s[0][0]))return s}return[]}var ne={SIZE:80,SCRIPT:64,OFFSET:68,STEPS:72},L={DETECTOR:0,LATIN:1,ARABIC:2},U={NONE:0,LATIN:1,ARABIC:2,BOTH:3},de=3;var X=e=>Math.round(Math.min(1,Math.max(0,e))*1e4)/1e4;async function Ce(e,t,n,s,r){let o=r.now??(()=>performance.now()),i=o(),a=e.read(t,n,s,r.region??[0,0,1,1],1,de,U.LATIN,r.detectorLimit).map(u=>({text:u.latin.text,score:u.latin.score,box:[0,1,2,3].map(R=>({x:u.box[2*R],y:u.box[2*R+1]}))})),d=De([...a].reverse()),b=d.map(u=>u.text),f=[...et(b.join(`
37
+ `))?.mrzLines??nt(b)],p=d.map(u=>[X(u.x/n),X(u.y/s),X((u.x2-u.x)/n),X((u.y2-u.y)/s)]),y={kind:"band",ms:0,lineBoxes:p,lineCount:f.length,valid:!1},m=Vt(d.map(u=>u.text),p,f);if(m!==null&&(y.mrzBox=m),f.length>0){let u=tt(f,r.today??j.today());u.format&&(y.format=u.format),u.documentCode&&/^[A-Z<]{1,2}$/.test(u.documentCode)&&(y.documentCode=u.documentCode),u.valid&&(y.valid=!0,y.digest=await Ne(r.salt,u.lines))}return y.ms=Math.round(o()-i),y}var rt=e=>e.toUpperCase().replace(/\s+/g,"");function Wt(e,t){let n=Math.max(e.length,t.length);if(n===0)return 0;let s=0;for(let r=0;r<Math.min(e.length,t.length);r++)e[r]===t[r]&&s++;return s/n}function Vt(e,t,n){if(n.length===0||e.length===0)return null;let s=new Set,r=[];for(let d of n){let b=-1,f=.5;if(e.forEach((p,y)=>{let m=s.has(y)?0:Wt(rt(p),rt(d));m>f&&(f=m,b=y)}),b<0)return null;s.add(b),r.push(t[b])}let o=Math.min(...r.map(d=>d[0])),i=Math.min(...r.map(d=>d[1])),l=Math.max(...r.map(d=>d[0]+d[2])),a=Math.max(...r.map(d=>d[1]+d[3]));return[X(o),X(i),X(l-o),X(a-i)]}var Sn=Object.freeze({minLines:4,fillMin:.55,fillMax:.98,offsetMax:.12,steadyFillDelta:.04,steadyOffsetDelta:.03,layoutShiftMax:.025,lineCountDelta:1,lockMs:600,steadyMs:900,minFrames:3});function st(e,t,n){let s=r=>Math.round(Math.min(1,Math.max(0,r))*1e4)/1e4;return e.map(r=>{let o=[r[0],r[2],r[4],r[6]],i=[r[1],r[3],r[5],r[7]],l=Math.min(...o),a=Math.min(...i);return[s(l/t),s(a/n),s((Math.max(...o)-l)/t),s((Math.max(...i)-a)/n)]}).sort((r,o)=>r[1]-o[1]||r[0]-o[0])}async function Yt(e={}){var t,n=e,s=import.meta.url,r="",o,i;try{r=new URL(".",s).href}catch{}i=c=>{var h=new XMLHttpRequest;return h.open("GET",c,!1),h.responseType="arraybuffer",h.send(null),new Uint8Array(h.response)},o=async c=>{if(c=await fetch(c,{credentials:"same-origin"}),c.ok)return c.arrayBuffer();throw Error(c.status+" : "+c.url)};var l=console.log.bind(console),a=console.error.bind(console),d=!1,b,f,p,y,m,u=!1;function R(){var c=ae.buffer;new Int8Array(c),new Int16Array(c),n.HEAPU8=p=new Uint8Array(c),new Uint16Array(c),new Int32Array(c),y=new Uint32Array(c),new Float32Array(c),new Float64Array(c),m=new BigInt64Array(c),new BigUint64Array(c)}function S(c){throw c="Aborted("+c+")",a(c),d=!0,c+=". Build with -sASSERTIONS for more info.",u&&Q(),c=new WebAssembly.RuntimeError(c),f?.(c),c}var A;async function w(c){try{var h=await o(c);return new Uint8Array(h)}catch{}if(i)c=i(c);else throw"both async and sync fetching of the wasm failed";return c}async function B(c,h){try{var g=await w(c);return await WebAssembly.instantiate(g,h)}catch(C){a(`failed to asynchronously prepare wasm: ${C}`),S(C)}}async function z(c){var h=A;try{var g=fetch(h,{credentials:"same-origin"});return await WebAssembly.instantiateStreaming(g,c)}catch(C){a(`wasm streaming compile failed: ${C}`),a("falling back to ArrayBuffer instantiation")}return B(h,c)}var H={},W=()=>{if(!$){var c={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:(globalThis.navigator?.language??"C").replace("-","_")+".UTF-8",_:"./this.program"},h;for(h in H)H[h]===void 0?delete c[h]:c[h]=H[h];var g=[];for(h in c)g.push(`${h}=${c[h]}`);$=g}return $},$,J=[null,[],[]],ie=globalThis.TextDecoder&&new TextDecoder,Q,ae,ct={i:()=>S(""),b:function(c,h,g){return 0<=c&&3>=c?(m[g>>3]=BigInt(Math.round(1e6*(c===0?Date.now():performance.now()))),0):28},d:()=>1073741824,c:c=>{var h=p.length;if(c>>>=0,1073741824<c)return!1;for(var g=1;4>=g;g*=2){var C=h*(1+.2/g);C=Math.min(C,c+100663296);e:{C=(Math.min(1073741824,65536*Math.ceil(Math.max(c,C)/65536))-ae.buffer.byteLength+65535)/65536|0;try{ae.grow(C),R();var _=1;break e}catch{}_=void 0}if(_)return!0}return!1},f:(c,h)=>{var g=0,C=0,_;for(_ of W()){var M=h+g;y[c+C>>2]=M;for(var q=_,O=p,re=M,F=M+1/0-1,E=0;E<q.length;++E){var N=q.codePointAt(E);if(127>=N){if(M>=F)break;O[M++]=N}else if(2047>=N){if(M+1>=F)break;O[M++]=192|N>>6,O[M++]=128|N&63}else if(65535>=N){if(M+2>=F)break;O[M++]=224|N>>12,O[M++]=128|N>>6&63,O[M++]=128|N&63}else{if(M+3>=F)break;O[M++]=240|N>>18,O[M++]=128|N>>12&63,O[M++]=128|N>>6&63,O[M++]=128|N&63,E++}}O[M]=0,q=M-re,g+=q+1,C+=4}return 0},g:(c,h)=>{var g=W();y[c>>2]=g.length,c=0;for(var C of g){for(var _=g=0;_<C.length;++_){var M=C.charCodeAt(_);127>=M?g++:2047>=M?g+=2:55296<=M&&57343>=M?(g+=4,++_):g+=3}c+=g+1}return y[h>>2]=c,0},j:()=>52,h:()=>52,e:function(){return 70},a:(c,h,g,C)=>{for(var _=0,M=0;M<g;M++){var q=y[h>>2],O=y[h+4>>2];h+=8;for(var re=0;re<O;re++){var F=c,E=p[q+re],N=J[F];if(E===0||E===10){F=F===1?l:a,E=N;for(var V=0,se=E,v=V,T=v+void 0;se[v]&&!(v>=T);)++v;if(se=v,16<se-V&&E.buffer&&ie)E=ie.decode(E.subarray(V,se));else{for(v="";V<se;)if(T=E[V++],T&128){var me=E[V++]&63;if((T&224)==192)v+=String.fromCharCode((T&31)<<6|me);else{var Ee=E[V++]&63;T=(T&240)==224?(T&15)<<12|me<<6|Ee:(T&7)<<18|me<<12|Ee<<6|E[V++]&63,65536>T?v+=String.fromCharCode(T):(T-=65536,v+=String.fromCharCode(55296|T>>10,56320|T&1023))}}else v+=String.fromCharCode(T);E=v}F(E),N.length=0}else N.push(E)}_+=O}return y[C>>2]=_,0}},le;return le=await(async function(){function c(g){return g=le=g.exports,n._skw_engine_id=g.m,n._skw_load=g.n,n._skw_unload=g.o,n._skw_set_detector_limit=g.p,n._skw_read=g.q,n._skw_line_count=g.r,n._skw_lines=g.s,n._skw_best=g.t,n._skw_values=g.u,n._skw_sharpness=g.v,n._free=g.w,n._malloc=g.x,Q=g.y,ae=g.k,R(),le}var h={a:ct};return n.instantiateWasm?new Promise(g=>{n.instantiateWasm(h,(C,_)=>{g(c(C,_))})}):(A??(A=n.locateFile?n.locateFile?n.locateFile("sekyro-ocr.wasm",r):r+"sekyro-ocr.wasm":new URL("sekyro-ocr.wasm",import.meta.url).href),c((await z(h)).instance))})(),n.calledRun=!0,d||(u=!0,le.l(),b?.(n)),u?t=n:t=new Promise((c,h)=>{b=c,f=h}),t}var ot=Yt;function it(e){return e===1||e===5?new I("OCR_IMAGE_INVALID"):e===2?new I("OCR_ASSET_INVALID"):e===4?new I("OCR_CANCELLED"):e===6?new I("OCR_BUSY"):e===7?new I("OCR_UNAVAILABLE"):new I("OCR_INFERENCE_FAILED")}var fe=class{constructor(t){this.m=t;this.px=0;this.pxBytes=0;this.dicts=[null,null,null];this.classes=[0,0,0];this.held=[[],[],[]];this.latinKind="latin"}engineId(){let t=this.m._skw_engine_id(),n="";for(let s=t;this.m.HEAPU8[s]!==0&&s<t+64;s++)n+=String.fromCharCode(this.m.HEAPU8[s]);return n}put(t){let n=this.m._malloc(t.length);if(!n)throw new I("OCR_UNAVAILABLE");return this.m.HEAPU8.set(t,n),n}load(t,n,s,r,o={}){this.unload(t);let i=new Uint8Array(n),l=new Uint8Array(i.byteLength+1);l.set(i);let a=r===void 0?null:Oe(r),d=r===void 0?0:at(r);if(o.mrz===!0){if(t!==L.LATIN||r===void 0||!$t(r))throw new I("OCR_ASSET_INVALID")}else if(t===L.LATIN&&(r===void 0||r.endsWith(`
38
+ `)||d!==6625))throw new I("OCR_ASSET_INVALID");if(t===L.ARABIC&&(r===void 0||!r.endsWith(`
39
+ `)||d!==163||a[161]!==""))throw new I("OCR_ASSET_INVALID");let b=new Uint8Array(s),f=this.put(l),p=this.put(b);this.held[t]=[f,p];let y=this.m._skw_load(t,f,l.length,p,b.byteLength,d);if(y!==0)throw this.unload(t),it(y);this.dicts[t]=a,this.classes[t]=d,t===L.LATIN&&(this.latinKind=o.mrz===!0?"mrz":"latin")}recognizer(){return this.loaded(L.LATIN)?this.latinKind:null}unload(t){this.held[t].length&&this.m._skw_unload(t);for(let n of this.held[t])this.m._free(n);this.held[t]=[],this.dicts[t]=null}loaded(t){return this.held[t].length>0}pixels(t){if(t.length>this.pxBytes){if(this.px&&this.m._free(this.px),this.px=this.m._malloc(t.length),!this.px)throw new I("OCR_UNAVAILABLE");this.pxBytes=t.length}return this.m.HEAPU8.set(t,this.px),this.px}sharpness(t,n,s){let r=this.m._skw_sharpness(this.pixels(t),n,s);return r>=0&&Number.isFinite(r)?r:null}read(t,n,s,r,o,i,l,a){if(!Zt(l))throw new I("OCR_IMAGE_INVALID");if(l&U.LATIN&&!this.dicts[L.LATIN]||l&U.ARABIC&&!this.dicts[L.ARABIC]||!this.loaded(0))throw new I("OCR_UNAVAILABLE");let d=this.pixels(t);this.m._skw_set_detector_limit(a);let b=this.m._skw_read(d,n,s,r[0],r[1],r[2],r[3],o,i,l);if(b!==0)throw it(b);let f=this.m._skw_line_count(),p=this.m.HEAPU8.buffer,y=new DataView(p,this.m._skw_lines(),f*ne.SIZE),m=new Int32Array(p,this.m._skw_best()),u=new Float32Array(p,this.m._skw_values()),R=[];for(let S=0;S<f;S++){let A=S*ne.SIZE,w=y.getInt32(A+ne.SCRIPT,!0),B=y.getInt32(A+ne.OFFSET,!0),z=y.getInt32(A+ne.STEPS,!0);if(l===U.NONE){R.push({box:Array.from({length:8},(ie,Q)=>y.getFloat64(A+8*Q,!0))});continue}let H=this.dicts[w];if(!H)throw new I("OCR_INFERENCE_FAILED");let W=Le(m.subarray(B,B+z),u.subarray(B,B+z),this.classes[w],H,w===L.ARABIC),$=Array.from({length:8},(ie,Q)=>y.getFloat64(A+8*Q,!0)),J=R[R.length-1];w===L.ARABIC&&J&&J.arabic===void 0&&J.latin!==void 0&&Xt(J.box,$)?J.arabic=W:R.push(w===L.ARABIC?{box:$,arabic:W}:{box:$,latin:W})}return R}heapBytes(){return this.m.HEAPU8.length}dispose(){for(let t of[0,1,2])this.unload(t);this.px&&this.m._free(this.px),this.px=0,this.pxBytes=0}};function at(e){return(e.endsWith(`
40
+ `)?e.slice(0,-1):e).split(`
41
+ `).length+2}var Zt=e=>Number.isInteger(e)&&e>=U.NONE&&e<=U.BOTH,Xt=(e,t)=>e.every((n,s)=>n===t[s]);function $t(e){let t=e.split(`
42
+ `);return t.length===37&&new Set(t).size===37&&t.every(n=>/^[0-9A-Z<]$/.test(n))&&at(e)===39}async function lt(e){let t=await ot({instantiateWasm:(n,s)=>(WebAssembly.instantiate(e,n).then(r=>s(r,e)),{})});return new fe(t)}function Jt(){let e=null,t=null;return(n,s)=>{if(typeof OffscreenCanvas!="function"||(e||(e=new OffscreenCanvas(n,s),t=e.getContext("2d",{willReadFrequently:!0})),!t))return null;(e.width!==n||e.height!==s)&&(e.width=n,e.height=s);let r=t;return{draw(o){return r.clearRect(0,0,n,s),r.drawImage(o,0,0),r.getImageData(0,0,n,s).data}}}}function jt(){return{fetch:(...e)=>fetch(...e),now:()=>performance.now(),canvas:Jt(),instantiate:lt}}function Qt(e,t=jt()){let n=null,s="",r=960,o=0,i=!1,l=Promise.resolve(),a=m=>e.postMessage(m);async function d(m){if(t.canvas(1,1)===null)return a({id:m.id,kind:"failed",reason:"unsupported"});s=m.salt,r=m.detectorLimit;try{let u=await Te(m.baseUrl,_e,m.maxDownloadMs,t.fetch,t.now);o=u.downloadMs,i=u.cached;let R=await WebAssembly.compile(u.files.get("sekyro-ocr.wasm")),S=await t.instantiate(R),A=new TextDecoder("utf-8",{fatal:!0}).decode(u.files.get("mrz_dict.txt"));S.load(L.DETECTOR,u.files.get("det.param"),u.files.get("det.bin")),S.load(L.LATIN,u.files.get("mrz-rec.param"),u.files.get("mrz-rec.bin"),A,{mrz:!0}),u.files.clear(),n=S,a({id:m.id,kind:"ready",warmupMs:0,downloadMs:o,cached:i})}catch(u){a({id:m.id,kind:"failed",reason:u instanceof G?u.reason:"error"})}}async function b(m,u,R,S){if(!n)return u.close(),a({id:m,kind:"error",code:"not_ready"});let A=u.width,w=u.height,B=t.canvas(A,w);if(!B)return u.close(),a({id:m,kind:"failed",reason:"unsupported"});let z=B.draw(u);u.close();try{a({id:m,...await Ce(n,z,A,w,{detectorLimit:S,salt:s,region:R,now:t.now})})}catch{a({id:m,kind:"error",code:"OCR_INFERENCE_FAILED"})}}async function f(m,u,R){if(!n)return u.close(),a({id:m,kind:"error",code:"not_ready"});let S=u.width,A=u.height,w=t.canvas(S,A);if(!w)return u.close(),a({id:m,kind:"failed",reason:"unsupported"});let B=w.draw(u);u.close();try{let z=t.now(),H=n.read(B,S,A,[0,0,1,1],1,de,U.NONE,R);a({id:m,kind:"layout",ms:Math.round(t.now()-z),lineBoxes:st(H.map(W=>W.box),S,A)})}catch{a({id:m,kind:"error",code:"OCR_INFERENCE_FAILED"})}}async function p(m){if(!n)return a({id:m,kind:"error",code:"not_ready"});let u=t.now(),R=960,S=200,A=new Uint8Array(R*S*4).fill(255);try{await Ce(n,A,R,S,{detectorLimit:r,salt:s,now:t.now})}catch{return a({id:m,kind:"error",code:"OCR_INFERENCE_FAILED"})}a({id:m,kind:"ready",warmupMs:Math.round(t.now()-u),downloadMs:o,cached:i})}async function y(m){switch(m.kind){case"init":return d(m);case"warmup":return p(m.id);case"band":return b(m.id,m.bitmap,void 0,m.detectorLimit);case"still":return b(m.id,m.bitmap,m.region,m.detectorLimit);case"layout":return f(m.id,m.bitmap,m.detectorLimit);case"dispose":n?.dispose(),n=null,e.close();return}}e.onmessage=m=>{let u=m.data;l=l.then(()=>y(u)).catch(()=>a({id:u.id,kind:"error",code:"OCR_INFERENCE_FAILED"}))}}typeof WorkerGlobalScope<"u"&&typeof self<"u"&&self instanceof WorkerGlobalScope&&Qt(self);export{jt as defaultDeps,Qt as installOcrWorkerHost};