@sekyro/web 0.1.0-rc.20 → 0.1.0-rc.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/{capture-session-doc-QA4DOFRF.js → capture-session-doc-XBZGXWOP.js} +1 -1
  3. package/dist/{capture-session-v3-CNL-GX11.d.cts → capture-session-v3-26FgzBIl.d.cts} +1 -1
  4. package/dist/{capture-session-v3-DaBqN8fO.d.ts → capture-session-v3-ZO0QOeQH.d.ts} +1 -1
  5. package/dist/chunk-234OZEDB.js +1 -0
  6. package/dist/chunk-33KKMPJ5.js +1 -0
  7. package/dist/chunk-53POX7U4.js +1 -0
  8. package/dist/{chunk-FGOVIGGL.js → chunk-7Q4YPMAF.js} +1 -1
  9. package/dist/chunk-B2X33ZW2.js +1 -0
  10. package/dist/{chunk-5ZKQHFFW.js → chunk-H3HVCWLF.js} +1 -1
  11. package/dist/{chunk-W2WD7PR2.js → chunk-P3H3D33O.js} +1 -1
  12. package/dist/{chunk-U6S7SCBY.js → chunk-P6UP4UQY.js} +1 -1
  13. package/dist/{chunk-IG466TOP.js → chunk-QYYJLXKA.js} +1 -1
  14. package/dist/{chunk-ZLWH4RBO.js → chunk-VIAT4DEA.js} +1 -1
  15. package/dist/chunk-ZADZTM3M.js +1 -0
  16. package/dist/chunk-ZNIZACXD.js +1 -0
  17. package/dist/client/index.cjs +1 -1
  18. package/dist/client/index.d.cts +3 -3
  19. package/dist/client/index.d.ts +3 -3
  20. package/dist/client/index.js +1 -1
  21. package/dist/core/index.cjs +1 -1
  22. package/dist/core/index.d.cts +3 -3
  23. package/dist/core/index.d.ts +3 -3
  24. package/dist/core/index.js +1 -1
  25. package/dist/{create-document-capture-GJXBQMTC.js → create-document-capture-23R2F47A.js} +1 -1
  26. package/dist/{create-portrait-capture-MOS2D7CL.js → create-portrait-capture-AGFHECK7.js} +1 -1
  27. package/dist/{create-verification-BBOUYpga.d.cts → create-verification-CXhXxknV.d.cts} +44 -5
  28. package/dist/{create-verification-COpe2hxf.d.ts → create-verification-KlHIU4Fy.d.ts} +44 -5
  29. package/dist/{icao-gate-CEGvJR3q.d.ts → icao-gate-DI8VePWd.d.ts} +36 -4
  30. package/dist/{icao-gate-l40OU6x1.d.cts → icao-gate-DvzOzHq6.d.cts} +36 -4
  31. package/dist/icao-gate-T3BTOKFJ.js +1 -0
  32. package/dist/{icao-policy-BgI1Y870.d.ts → icao-policy-DztbA50-.d.ts} +3 -3
  33. package/dist/{icao-policy-C7fIdRzo.d.cts → icao-policy-MRB8NMAu.d.cts} +3 -3
  34. package/dist/icao-tuning-4ETMF53W.js +1 -0
  35. package/dist/index.cjs +1 -1
  36. package/dist/index.d.cts +7 -7
  37. package/dist/index.d.ts +7 -7
  38. package/dist/index.js +1 -1
  39. package/dist/internal/index.cjs +1 -1
  40. package/dist/internal/index.d.cts +10 -6
  41. package/dist/internal/index.d.ts +10 -6
  42. package/dist/internal/index.js +1 -1
  43. package/dist/plan-runner-NUWONT7F.js +1 -0
  44. package/dist/popup/index.d.cts +1 -1
  45. package/dist/popup/index.d.ts +1 -1
  46. package/dist/popup/index.js +1 -1
  47. package/dist/{types-Dpfg2cO8.d.cts → types-C_XP92JQ.d.cts} +40 -7
  48. package/dist/{types-Dpfg2cO8.d.ts → types-C_XP92JQ.d.ts} +40 -7
  49. package/package.json +1 -1
  50. package/sbom.cdx.json +10 -10
  51. package/dist/chunk-7ZCZY3ZP.js +0 -1
  52. package/dist/chunk-BPE5NSQ2.js +0 -1
  53. package/dist/chunk-KHR4U2SZ.js +0 -1
  54. package/dist/chunk-KZBBB5B2.js +0 -1
  55. package/dist/chunk-NJML6FMD.js +0 -1
  56. package/dist/chunk-XCKE2MJL.js +0 -1
  57. package/dist/icao-gate-PWBMKRGC.js +0 -1
  58. package/dist/icao-tuning-4GGVX6B4.js +0 -1
  59. package/dist/plan-runner-35655N4Z.js +0 -1
  60. /package/dist/{chunk-U6TYL2IJ.js → chunk-SNACCYTL.js} +0 -0
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # @sekyro/web
2
2
 
3
+ ## 0.1.0-rc.21
4
+
5
+ ### Minor Changes
6
+
7
+ - f3f4313: `PortraitIcaoReason` no longer has `portrait_recaptured`: the server no longer checks a portrait photo for a photo of a screen or a print, so a portrait step never ends with that reason. `@sekyro/react` drops its wording (`reasons.portrait_recaptured`) in every language.
8
+
9
+ ### Patch Changes
10
+
11
+ - ff2011d: The document country picker lists the person's own country first, as detected from their network, when the session accepts a document from it. `HostedSessionView.detectedCountry` and the document step's `detectedCountry` carry it (ISO 3166-1 alpha-2), absent when unknown. The search still covers every accepted country.
12
+ - 5f9503f: Headless flows (`verification.run()`) now report the camera errors of the portrait step to the session, as `<SekyroVerification>` does, with no code change on your side. The reports and the `error` event of a portrait capture now carry `detail` (the failing phase and the thrown error's name), as liveness and document do. A flow that uses both sends one report. This is a diagnostic only: it does not change what the step offers.
13
+ - 74477bc: ID photo gate: a relaxed narrow mouth no longer fails "Neutral expression" (the pucker limit is 0.48 on the device), and each eye is now judged against its own usual openness, so one eye that is always less open passes while a blink or a closed eye still fails. The gate submits a baseline per eye (`gate.baselineEyeOpennessLeft` and `Right`) next to the existing one. The gate also reports its mouth scores (numbers only, no image) for Sekyro staff diagnostics. No code change on your side.
14
+ - bb79da6: Simulated Sandbox sessions now say so in the flow. `<SekyroVerification>` replaces "We sent a code" with a test-session message that shows the code to enter, and offers "Skip with test data" on the document, chip, live photo and portrait steps, before the camera opens and on the camera screen. Headless flows read `step.context.simulation` (`{ otpCode, skipCapture }`) and call `step.skipCapture()` on those steps. Nothing changes on a Live session or a session bound to a tester: the block and the action are absent.
15
+
3
16
  ## 0.1.0-rc.20
4
17
 
5
18
  ### Minor Changes
@@ -1 +1 @@
1
- import{C as a,D as b,E as c,F as d,G as e,H as f,I as g,J as h,K as i,L as j,M as k}from"./chunk-U6S7SCBY.js";import"./chunk-SMKCBUJL.js";import"./chunk-MXWLCDFX.js";import"./chunk-G6LKLN4U.js";import"./chunk-TDLIXFDT.js";import"./chunk-POIQGEZM.js";import"./chunk-CQ7SKLMC.js";import"./chunk-FPXL63KZ.js";import"./chunk-ZLWH4RBO.js";import"./chunk-DK5YPBDQ.js";export{k as CAPTURE_CANDIDATE_SPACING_MS,j as CAPTURE_EXTRA_CANDIDATES,h as CaptureSessionDoc,c as DOC_BLACK_FRAME_LUMA,d as DOC_BLACK_FRAME_TICKS,e as DOC_CADENCE_HZ,b as DOC_FIRST_FRAME_MS,f as DOC_SHUTTER_DEFAULTS,i as passportBandOf,g as resolveDocShutterTuning,a as warmDocDetector};
1
+ import{C as a,D as b,E as c,F as d,G as e,H as f,I as g,J as h,K as i,L as j,M as k}from"./chunk-P6UP4UQY.js";import"./chunk-SMKCBUJL.js";import"./chunk-MXWLCDFX.js";import"./chunk-G6LKLN4U.js";import"./chunk-TDLIXFDT.js";import"./chunk-POIQGEZM.js";import"./chunk-CQ7SKLMC.js";import"./chunk-FPXL63KZ.js";import"./chunk-VIAT4DEA.js";import"./chunk-DK5YPBDQ.js";export{k as CAPTURE_CANDIDATE_SPACING_MS,j as CAPTURE_EXTRA_CANDIDATES,h as CaptureSessionDoc,c as DOC_BLACK_FRAME_LUMA,d as DOC_BLACK_FRAME_TICKS,e as DOC_CADENCE_HZ,b as DOC_FIRST_FRAME_MS,f as DOC_SHUTTER_DEFAULTS,i as passportBandOf,g as resolveDocShutterTuning,a as warmDocDetector};
@@ -1,4 +1,4 @@
1
- import { aS as ScreenRampReport, aK as CaptureProvenance, aQ as ScreenRampChallenge, aG as ScreenRampColour } from './types-Dpfg2cO8.cjs';
1
+ import { aU as ScreenRampReport, aM as CaptureProvenance, aS as ScreenRampChallenge, aI as ScreenRampColour } from './types-C_XP92JQ.cjs';
2
2
  import { F as FaceObservation, b as Detector, W as WorkerLike } from './detect-worker-DclNxkZT.cjs';
3
3
 
4
4
  /** MP4-first ladder: one container (H.264 MP4) covers iOS/macOS Safari + Chrome 130+.
@@ -1,4 +1,4 @@
1
- import { aS as ScreenRampReport, aK as CaptureProvenance, aQ as ScreenRampChallenge, aG as ScreenRampColour } from './types-Dpfg2cO8.js';
1
+ import { aU as ScreenRampReport, aM as CaptureProvenance, aS as ScreenRampChallenge, aI as ScreenRampColour } from './types-C_XP92JQ.js';
2
2
  import { F as FaceObservation, b as Detector, W as WorkerLike } from './detect-worker-DclNxkZT.js';
3
3
 
4
4
  /** MP4-first ladder: one container (H.264 MP4) covers iOS/macOS Safari + Chrome 130+.
@@ -0,0 +1 @@
1
+ import{A as be,C as w,D as K,h as F,i as z,j as fe,k as he,m as Se,n as X,p as W,q as ee,s as ge,t as ye}from"./chunk-H3HVCWLF.js";import{c as le,d as pe,e as me}from"./chunk-FPXL63KZ.js";import{c as U,h as Q,i as Ce}from"./chunk-B2X33ZW2.js";var ke=["AD","AE","AF","AG","AI","AL","AM","AO","AQ","AR","AS","AT","AU","AW","AX","AZ","BA","BB","BD","BE","BF","BG","BH","BI","BJ","BL","BM","BN","BO","BQ","BR","BS","BT","BV","BW","BY","BZ","CA","CC","CD","CF","CG","CH","CI","CK","CL","CM","CN","CO","CR","CU","CV","CW","CX","CY","CZ","DE","DJ","DK","DM","DO","DZ","EC","EE","EG","EH","ER","ES","ET","FI","FJ","FK","FM","FO","FR","GA","GB","GD","GE","GF","GG","GH","GI","GL","GM","GN","GP","GQ","GR","GS","GT","GU","GW","GY","HK","HM","HN","HR","HT","HU","ID","IE","IL","IM","IN","IO","IQ","IR","IS","IT","JE","JM","JO","JP","KE","KG","KH","KI","KM","KN","KP","KR","KW","KY","KZ","LA","LB","LC","LI","LK","LR","LS","LT","LU","LV","LY","MA","MC","MD","ME","MF","MG","MH","MK","ML","MM","MN","MO","MP","MQ","MR","MS","MT","MU","MV","MW","MX","MY","MZ","NA","NC","NE","NF","NG","NI","NL","NO","NP","NR","NU","NZ","OM","PA","PE","PF","PG","PH","PK","PL","PM","PN","PR","PS","PT","PW","PY","QA","RE","RO","RS","RU","RW","SA","SB","SC","SD","SE","SG","SH","SI","SJ","SK","SL","SM","SN","SO","SR","SS","ST","SV","SX","SY","SZ","TC","TD","TF","TG","TH","TJ","TK","TL","TM","TN","TO","TR","TT","TV","TW","TZ","UA","UG","UM","US","UY","UZ","VA","VC","VE","VG","VI","VN","VU","WF","WS","XK","YE","YT","ZA","ZM","ZW"];var Ze=["carte_identite","passport","residence_permit"];function Ye(e,t){let i=e.byIssuer?.[t]??e.default;return Ze.filter(o=>i==="*"||i.includes(o))}function Ft(e,t=ke){return[...new Set([...t,...Object.keys(e.byIssuer??{})])].filter(o=>Ye(e,o).length>0).sort()}function _e(e){if(e.acceptedDocuments)return e.acceptedDocuments;let t=e.acceptedDocumentTypes?.length?[...e.acceptedDocumentTypes]:["carte_identite","passport"];return{default:[],byIssuer:{MR:t}}}var We=640,Qe=new Set(["network_error","timeout","upload_failed","unknown_error","rate_limit_exceeded"]),Pe=6,Re=1500,Me={sharpness:1,exposure:1,meanLuma:128},Ee=null;function qe(e,t){try{Ee??(Ee=document.createElement("canvas"));let i=Ee,o=96/Math.max(1,t.width);i.width=Math.max(1,Math.round(t.width*o)),i.height=Math.max(1,Math.round(t.height*o));let r=i.getContext("2d");if(r===null)return Me;r.drawImage(e,t.x,t.y,t.width,t.height,0,0,i.width,i.height);let c=r.getImageData(0,0,i.width,i.height);return{sharpness:pe(c),exposure:me(c),meanLuma:le(c)}}catch{return Me}}async function $e(e,t){let i=e.source;return"convertToBlob"in i?i.convertToBlob({type:"image/jpeg",quality:t}):new Promise((o,r)=>{i.toBlob(c=>c===null?r(new Error("encode failed")):o(c),"image/jpeg",t)})}function Wt(e,t={}){let i=t.now??(()=>performance.now()),o=t.setTimer??((m,P)=>setTimeout(m,P)),r=t.clearTimer??(m=>clearTimeout(m)),c=t.encode??$e,l=t.quality??qe,u=e.tuningVersion??null,p=new Set,y=!1,g=e.video??null,k=null,b=t.grabFrame??null,C=null,O=1e3/Pe,E=null,A=null,T=!1,x=!1,V=Number.NEGATIVE_INFINITY,M=null,H=0,N=null,G=null,$=Promise.all([import("./icao-gate-T3BTOKFJ.js"),import("./icao-tuning-4ETMF53W.js"),import("./create-portrait-capture-AGFHECK7.js"),import("./landmarker-KB7LVXAU.js"),import("./background-monitor-A7FKJOAG.js")]).then(async([m,P,R,v,I])=>{let n=P.resolveIcaoTuning(e.tuning,e.tuningVersion??void 0);n.background.required&&(A=I.createBackgroundMonitor({tuning:n.backgroundCheck,assetBaseUrl:e.assetBaseUrl??"/models-v3",...t.createSegmenter!==void 0?{createSegmenter:t.createSegmenter}:{},now:i})),k=m.createIcaoGate(n,{policy:e.policy??"reject"}),b??(b=R.defaultGrabber()),C=R.observe,O=1e3/Math.min(Pe,n.cadenceHz);let s=(t.createLandmarker??v.createFaceLandmarker)(e.assetBaseUrl??"/models-v3"),a=await new Promise((d,f)=>{let h=setTimeout(()=>{f(new Error("landmarker init timeout")),s.then(S=>S.close(),()=>{})},v.LANDMARKER_INIT_TIMEOUT_MS);s.then(S=>{clearTimeout(h),d(S)},S=>{clearTimeout(h),f(S)})});y?a.close():E=a}).catch(()=>{T=!0}),D=m=>{for(let P of p)P({holding:x||T,update:m})},j=()=>{if(M=null,!(y||E===null||k===null||b===null||C===null||g===null)){if(i()-V>Re){D(null);return}try{let m=b(g,We);if(m!==null){let P=Math.max(i(),H+1);H=P;let R=E.detect(m.source,P),v=g.videoWidth||m.width,I=g.videoHeight||m.height,n=C(R,m,v,I);n.geometry!==null&&A!==null&&(n.backgroundCheck=A.measure(m,n.geometry.box,v,I));let s=k.push(n,i());x=s.ready,D(s)}}catch{}M=o(j,O)}},Z=()=>{let m=i()-V>Re;V=i(),m&&(k?.reset(),x=!1,N=null,G=null),M===null&&E!==null&&!y&&(M=o(j,0))},J=()=>{let m=b===null||g===null?null:b(g,null);if(m===null||k===null||Math.max(m.width,m.height)<e.still.minLongSidePx)return Promise.resolve(null);let P=k.summary();return c(m,e.still.jpegQuality).then(R=>({image:R,width:m.width,height:m.height,gate:P}),()=>null)},Y=null;return{engineOptions:{measureQuality:(m,P)=>{g=m,Z();let R=l(m,P);return x||T?R:{...R,sharpness:0}},telemetry:m=>{if(m.type!=="fired"||y)return;N=J();let P=Y;P!==null&&N.then(R=>R===null?void 0:P(R).catch(()=>{})),x=!1,M!==null&&r(M),M=null,V=Number.NEGATIVE_INFINITY}},decorate:m=>{let P=new WeakMap,R=new Map,v=a=>{let d=P.get(a);return d===void 0&&(d=(async()=>{let f=await ye(m,"image","image/jpeg",a.image.size,{engine:"portrait"});return await m.uploadToSpaces(f.uploadUrl,a.image,"image/jpeg"),(await m.completeMedia(f.key)).key})(),d.catch(()=>P.delete(a)),P.set(a,d)),d};Y=v;let I=async a=>{let d;try{d=await v(a)}catch(f){let h=f?.code;if(typeof h=="string"&&Qe.has(h))throw f;return null}return{media:{portrait:d},gate:Ce(a.gate),...u!==null?{tuningVersion:u}:{}}},n=m.submitCheck.bind(m),s=(async(a,d,f)=>{if(a!=="liveness")return n(a,d,f);let h=f?.idempotencyKey,S=h===void 0?void 0:R.get(h);if(S===void 0){let ue=N;S=ue===null?Promise.resolve(null):ue.then(de=>de===null?null:I(de)),h!==void 0&&(R.set(h,S),S.catch(()=>R.delete(h)))}let _=await S;if(_===null)return n("liveness",d,f);let je=await n("liveness",{...d,portraitIcao:_},f);return G=_,je});return new Proxy(m,{get(a,d){if(d==="submitCheck")return s;let f=Reflect.get(a,d);return typeof f=="function"?f.bind(a):f}})},onGate:m=>(p.add(m),()=>p.delete(m)),lastPortraitInput:()=>G,destroy:()=>{y=!0,N=null,G=null,M!==null&&r(M),M=null,p.clear(),$.then(()=>{E?.close(),E=null,A?.close(),A=null})}}}function Ae(e){return e.idNumberBound??e.nniBound}function ve(e){return e===void 0?void 0:e.idNumberFromDocument??e.nniFromDocument}function Ie(e){let t=e.idNumberMasked??e.nniMasked;return typeof t=="string"&&t!==""?t:void 0}var Te=Object.freeze({nni_invalid:"id_number_invalid",nni_not_found:"registry_record_not_found",nni_recheck:"id_number_recheck",document_nni_mismatch:"document_id_number_mismatch",nni_locked:"id_number_locked",nni_unbound:"id_number_unbound",sandbox_nni_not_seeded:"sandbox_id_number_not_seeded",missing_nni:"missing_id_number",registry_needs_nni_source:"registry_needs_id_number_source"}),Je=new Map(Object.entries(Te)),$t=new Map(Object.entries(Te).map(([e,t])=>[t,e]));function we(e){return Je.get(e)??e}var ze=new Set(["phone_otp","email_otp","national_eid","document","nfc","population_registry","supplied_identity","summary_confirm","liveness","portrait","face_match","aml_screening","face_dedup","age_estimation"]),Xe=new Set(["supplied_identity","aml_screening","face_dedup","age_estimation"]),ne=["document","population_registry","national_eid"],ie=["phone_otp","email_otp"],Ne={identity_method:ne,contact:ie},et=["population_registry","document"],Le="platform_unsupported",tt=new Set(["prefilled","user_entered","prefilled_or_entered"]),nt={phone_otp:"contact",email_otp:"contact",eid_auth:"identity",doc_ocr:"identity",nfc_chip:"identity",population_registry:"identity",liveness:"live_photo",portrait_icao:"live_photo",face_match:"live_photo"};function L(e){return e.section??nt[e.checkType]??null}function oe(e,t){let i=e.plan?.choice;if(i===void 0||i.locked)return;let o=i.options.find(r=>r.id!==i.selected&&r.available!==!1&&t.includes(r.service));return o===void 0?void 0:{nodeId:i.nodeId,option:o}}function re(e){let t=e.plan,i=t?.choice;if(t===void 0||i===void 0||i.locked||t.current===null||t.current===i.nodeId||X(e))return null;let o=Ne[i.kind]??[...ne,...ie],r=i.options.flatMap(u=>u.available===!1||!o.includes(u.service)?[]:[u.nationalEid!=null?{id:u.id,service:u.service,nationalEid:u.nationalEid}:{id:u.id,service:u.service}]),c=t.steps.find(u=>u.id===t.current)?.service,l=i.selected??r.find(u=>u.service===c)?.id??null;return r.some(u=>u.id!==l)?{nodeId:i.nodeId,kind:i.kind,current:l,options:r}:null}function Ve(e){return e==null?[]:e.options.filter(t=>t.id!==e.current)}function it(e){let t=e.simulation;if(typeof t!="object"||t===null)return;let{otpCode:i,skipCapture:o}=t;return typeof i=="string"&&i!==""&&typeof o=="boolean"?{otpCode:i,skipCapture:o}:void 0}function ot(e){let t=(e.plan?.sections??[]).map(c=>({id:c.id,state:c.state})),i={sessionId:ee(e.sessionId),orgName:e.orgName,returning:e.returning===!0,consentRecorded:e.consentRecorded,expiresAt:e.expiresAt,sections:t.map(c=>c.id),progress:t,purpose:e.purpose??"identity"};e.branding!==void 0&&(i.branding=e.branding),e.cameraUnavailableHandled===!0&&(i.cameraUnavailableHandled=!0);let o=it(e);o!==void 0&&(i.simulation=o);let r=re(e);return r!==null&&(i.switchable=r),i}function rt(e){let t={attemptsRemaining:fe(e),attemptsExhausted:e.attemptsExhausted===!0};return e.reason!==void 0&&(t.reason=e.reason),e.retakeHint!==void 0&&(t.retakeHint=e.retakeHint),t}var De={phone_otp:"phone",email_otp:"email"};function st(e,t){let i=oe(e,[t==="phone_otp"?"email_otp":"phone_otp"]);return i===void 0?void 0:De[i.option.service]}function at(e,t,i,o){let r=t.checkType==="email_otp",c=(r?t.emailOtp:t.otp)??{},l=r?t.emailOtp?.emailSource:t.otp?.numberSource,u=l!==void 0&&tt.has(l)?l:r?"prefilled_or_entered":"user_entered",p=typeof c.sentToMasked=="string"&&c.sentToMasked.length>0,y=c.prefilled===!0,g=st(e,r?"email_otp":"phone_otp"),k={key:t.checkType,context:i,section:L(t),phase:p?"verify":"send",canSwitch:g!==void 0,...o},b=r?{kind:"email_otp",...k,emailSource:u,needsEmail:u!=="prefilled"&&!y}:{kind:"phone_otp",...k,numberSource:u,needsPhone:u!=="prefilled"&&!y,channels:(t.otp?.channels??[]).filter(C=>C==="whatsapp"||C==="sms")};if(g!==void 0&&(b.switchChannel=g),y&&(b.prefilled=!0),p&&(b.sentToMasked=c.sentToMasked),!r&&t.otp?.channel!==void 0&&(b.channel=t.otp.channel),!r&&Array.isArray(t.phoneCountries)&&(b.phoneCountries=t.phoneCountries.filter(C=>typeof C=="string"&&/^[A-Z]{2}$/.test(C))),!r&&Array.isArray(t.phoneRules)){let C=b.phoneCountries??[];b.phoneRules=t.phoneRules.flatMap(O=>{let E=dt(O);return E!==void 0&&C.includes(E.code)?[E]:[]})}return!r&&t.phoneInternational===!0&&(b.phoneInternational=!0),c.expiresAt!==void 0&&(b.codeExpiresAt=c.expiresAt),c.resendAvailableAt!==void 0&&(b.resendAvailableAt=c.resendAvailableAt),b}var ct=/^[\d[\]\-|()?:^]{1,64}$/;function ut(e){try{return typeof e=="string"&&ct.test(e)&&new RegExp(e)!==null}catch{return!1}}var Oe=e=>typeof e=="number"&&Number.isInteger(e)&&e>=1&&e<=15;function dt(e){let{code:t,dial:i,trunk:o,lengths:r,formats:c}=e??{};if(typeof t!="string"||typeof i!="string"||!/^\d{1,3}$/.test(i)||o!==void 0&&(typeof o!="string"||!/^\d{1,3}$/.test(o))||!Array.isArray(r)||r.length===0||!r.every(Oe))return;let l={code:t,dial:i,lengths:[...r].sort((u,p)=>u-p)};if(o!==void 0&&(l.trunk=o),c!==void 0){if(!(Array.isArray(c)&&c.length<=8&&c.every(p=>ut(p?.leading)&&Array.isArray(p.groups)&&p.groups.every(Oe)&&r.includes(p.groups.reduce((y,g)=>y+g,0)))))return;l.formats=c.map(p=>({leading:p.leading,groups:[...p.groups]}))}return l}function lt(e,t,i,o){let r=Ae(e)===!0?"bound":ve(t)===!0?"document":"typed",c=r==="typed"&&t.state==="input_required"&&t.reason!==void 0&&we(t.reason)==="id_number_recheck",l=Ve(re(e)),u=!o.attemptsExhausted&&l.length===1&&l[0]?.service==="document";return{kind:"registry",key:"registry",context:i,section:L(t),state:t.state==="input_required"?"input_required":"pending",source:r,recheck:c,canUseDocument:u,...o}}function pt(e,t,i,o){let r=[...t.acceptedSides??[]],c={kind:"document",key:"document",context:i,section:L(t),side:r.includes("recto")?"verso":"recto",acceptedSides:r,documents:_e(e),photo:He(e.documents),...o};return e.detectedCountry!==void 0&&(c.detectedCountry=e.detectedCountry),mt(e)&&(c.ageStepUp=!0),c}function He(e,t=!0){let i=e?.source==="upload"||e?.source==="choice"?e.source:"camera",o=e?.sourcePick==="camera"||e?.sourcePick==="upload"?e.sourcePick:null;return{source:i,pick:o,uploadOffered:t&&e?.uploadOffered===!0}}function mt(e){let t=z(e).find(o=>o.checkType==="age_estimation"),i=t?.reason;return t?.state==="failed"&&(i==="age_uncertain"||i==="age_unavailable")}function ft(e){let t=W(e,"liveness");return t?.state==="passed"||t?.state==="review"}function xe(e,t,i,o,r){let c=t.icao?.report,l=e.portrait,u=r==="capture"?l?.pendingFix??null:null;u!==null&&(r="review");let p=Ge(e);return{kind:"portrait",key:`portrait:${r}`,context:i,section:L(t),phase:r,report:Array.isArray(c)?c:null,review:t.state==="review",tuning:e.capture?.icao??null,tuningVersion:e.capture?.tuningVersion??null,icao:Q(e),retakeOnly:r==="capture"&&t.state==="input_required"&&p===void 0&&e.capture?.livePhoto?.oneCapture===!0&&ft(e),photo:He(l,r==="capture"),pendingFix:u,...p!==void 0?{captureMode:p}:{},...l?.reuse?.pending===!0?{reuse:!0}:{},...o}}function Ge(e){let t=e.portrait?.captureMode;return t==="self"||t==="assisted"||t==="choice"?t:void 0}var te={minLongSidePx:1280,jpegQuality:.95};function ht(e,t){let i=e.capture?.livePhoto;if(i?.oneCapture!==!0)return null;let o=W(e,"portrait_icao"),r=i.still??te;return{icao:t==="liveness"&&Q(e)!==null&&Ge(e)===void 0&&o!==void 0&&o.state==="pending"&&o.reason===void 0,still:{minLongSidePx:r.minLongSidePx??te.minLongSidePx,jpegQuality:r.jpegQuality??te.jpegQuality}}}function St(e,t,i,o){let r=t.eid,c=L(t);if(r===void 0||r.challenge!=="app_code")return{kind:"unsupported",key:"unsupported:eid_auth",context:i,section:c,checkType:"eid_auth",reason:"update_required"};let l=Ve(re(e)),u=l.length===1&&et.includes(l[0]?.service??"")?l[0]:void 0,p=u===void 0?void 0:F[u.service],y=p!==void 0,g={kind:"eid",key:"eid",context:i,section:c,provider:r.provider,providerName:r.providerName,country:r.country,challenge:"app_code",phase:r.awaiting==="code"?"code":"identifier",identifierBound:r.identifierBound===!0,canUseCamera:y,afterPass:r.afterPass==="continue"?"continue":"end",...o};return y&&(g.cameraMethod=p),r.expiresAt!==void 0&&(g.codeExpiresAt=r.expiresAt),r.resendAvailableAt!==void 0&&(g.resendAvailableAt=r.resendAvailableAt),r.resendsRemaining!==void 0&&(g.resendsRemaining=r.resendsRemaining),r.codeAttemptsRemaining!==void 0&&(g.codeAttemptsRemaining=r.codeAttemptsRemaining),g}function gt(e,t){if(t.checkType!=="face_match"||t.reason!==void 0)return null;let i=W(e,"portrait_icao");return i!==void 0&&(i.state==="passed"||i.state==="review")?i:null}function yt(e){return z(e).filter(t=>t.state==="failed").pop()?.attemptsExhausted===!0}function bt(e,t){let i=e.failureReason,o;i===Le?o="platform_unsupported":e.status==="expired"?o="expired":e.status==="review_pending"?o="review":e.status==="completed"&&e.outcome==="approved"?o="approved":e.status==="completed"&&e.outcome==="review"?o="review":i==="device_cooldown"?o="cooldown":i!==void 0?o="policy_stop":yt(e)?o="attempts_exhausted":o="rejected";let r=o==="platform_unsupported"?{sessionId:ee(e.sessionId),status:"unavailable"}:ge(e,{autoRetry:!1}),c={kind:"result",key:"result",context:t,section:null,display:o,result:r};return i!==void 0&&(c.failureReason=i),e.retryAfter!==void 0&&(c.retryAfter=e.retryAfter),c}function Ct(e,t,i){let o=e.identitySummary;if(o==null)return null;let r={kind:"identity_summary",key:"identity_summary",context:t,section:i??"identity",summaryKind:o.kind==="partial"?"partial":o.kind??"full",source:o.source,portraitAvailable:o.portrait?.available===!0,retakeAvailable:o.retakeAvailable===!0};for(let l of kt){let u=o[l];typeof u=="string"&&u!==""&&(r[l]=u)}let c=Ie(o);return c!==void 0&&(r.idNumberMasked=c,r.nniMasked=c),r}var kt=["fullName","birthDate","birthYear","nationality","documentType","documentNumberMasked","expiryDate","retakeTarget"];function B(e,t,i,o){return{kind:"unsupported",key:`unsupported:${i}`,context:e,section:t,checkType:i,reason:o}}function _t(e){return e.kind==="contact"?"contact":(e.kind==="identity_method","identity")}function Pt(e,t){let i=Ne[e.kind]??[...ne,...ie],o=_t(e),r=e.options.flatMap(l=>{if(l.available===!1||!i.includes(l.service))return[];let u={id:l.id,service:l.service};l.nationalEid!=null&&(u.nationalEid=l.nationalEid);let p=(l.channels??[]).filter(y=>y==="whatsapp"||y==="sms");return l.service==="phone_otp"&&p.length>0&&(u.channels=p),[u]});if(r.length===0){let l=e.options.length>0&&e.options.every(u=>u.service==="nfc");return B(t,o,"choice",l?"platform_unsupported":"update_required")}let c={nodeId:e.nodeId,kind:e.kind,selected:e.selected,options:r};if(e.kind==="identity_method"){let l={kind:"method",key:"method",context:t,section:o,options:r.map(p=>F[p.service]),choice:c},u=r.find(p=>p.nationalEid!==void 0)?.nationalEid;return u!==void 0&&(l.nationalEid=u),l}return e.kind==="contact"?{kind:"contact_choice",key:"contact_choice",context:t,section:o,options:r.map(l=>De[l.service]),selected:null,locked:!1,choice:c}:{kind:"choice",key:`choice:${e.nodeId}`,context:t,section:o,choice:c}}function q(e,t={}){let i=ot(e);if(X(e)||e.failureReason===Le)return bt(e,i);let o=e.plan;if(o===void 0||!Array.isArray(o.sections))return B(i,null,"plan","update_required");let r=he(e);if(r!==null)return Pt(r,i);let c=o.current===null?void 0:o.steps.find(k=>k.id===o.current),l=k=>{let b={kind:"processing",key:"processing",context:i,section:k!==void 0?L(k):o.sections.find(C=>C.state==="current")?.id??null,stalled:!1};return typeof k?.service=="string"&&k.service!==""&&(b.service=k.service),b};if(o.current===null)return l(o.steps.find(k=>k.state==="processing"));if(c===void 0)return B(i,null,"step","update_required");if(!ze.has(c.service))return c.interaction==="server"?l(c):B(i,L(c),c.service,"update_required");if(Xe.has(c.service)||!Se(c))return l(c);let u=c,p=rt(u),y=u.checkType,g=L(u);switch(y){case"phone_otp":case"email_otp":return at(e,u,i,p);case"population_registry":return lt(e,u,i,p);case"eid_auth":return St(e,u,i,p);case"doc_ocr":return pt(e,u,i,p);case"identity_confirm":return Ct(e,i,g)??l(u);case"portrait_icao":return xe(e,u,i,p,"capture");case"liveness":case"face_match":{let k=gt(e,u);if(k!==null)return xe(e,k,i,p,"match");let b=u.requiresMobile===!0,C=Q(e);return b&&t.isMobile===!1?{kind:"mobile_required",key:"mobile_required",context:i,section:g,checkType:y}:{kind:"liveness",key:"biometric",context:i,section:g,mode:y==="face_match"?"selfie":"liveness",requiresMobile:b,instructions:C===null?"standard":"icao",icao:C,livePhoto:ht(e,y),...p}}case"nfc_chip":return B(i,g,y,"platform_unsupported");default:return B(i,g,y,"update_required")}}var Rt=/^[A-Z0-9][A-Z0-9 -]{0,39}$/,Mt=Object.freeze({normalize:e=>e.trim().toUpperCase().replace(/\s+/g," "),check:e=>Rt.test(e),registrySources:Object.freeze([]),describe:"number must be 1 to 40 letters, digits, spaces or hyphens"});function Et(e){return typeof e=="string"&&/^\d{10}$/.test(e)&&Number(e)%97===1}var At=Object.freeze({normalize:e=>e.trim(),check:e=>Et(e),registrySources:Object.freeze(["MR.anrpts"]),describe:"number must be the 10-digit Mauritanian national ID number with a valid check digit"}),vt=Object.freeze({"MR:national_id":At});function se(e,t){return vt[`${e.toUpperCase()}:${t}`]??Mt}var It=Object.freeze({MRT:"MR"});function Be(e,t){let i=e.trim().toUpperCase();return se(It[i]??i,t)}function Ue(e){let t=Be(e.issuingCountry,e.type);return t.check(t.normalize(e.number))}function Fe(e){return se("MR","national_id").check(e)}function ae(e){let t="";for(let i of e){let o=i.codePointAt(0)??0;o>=1632&&o<=1641?t+=String(o-1632):o>=1776&&o<=1785?t+=String(o-1776):i!==" "&&i!=="-"&&i!==" "&&(t+=i)}return t}var Tt=[1e3,2e3,4e3,8e3,15e3],wt=3e4,Ot=/^\+[1-9]\d{6,14}$/,xt=/^\d{6}$/,Nt=/^\d{6}$/,Lt=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,Ke=new Set(["session_not_active","check_not_found","check_already_finalized","check_out_of_order","identity_confirm_required","identity_confirm_locked","choice_locked","choice_option_unavailable","choice_not_found","step_not_on_path","check_not_active"]),Vt={simulatedCapture:!0},Dt=new Set(["network_error","timeout","upload_failed","unknown_error","rate_limit_exceeded"]);function fn(e){let t=!1,i=null,o="",r=!1,c=!1,l=!1,u={},p={},y=new Set,g=!1,k=!1,b=null,C="idle",O=new Map,E=new Map,A=(n,s,a)=>{let d=`${n}.${s}`,f=O.get(d);if(f!==void 0)return f;let h=E.get(n),S=(h===void 0?a():h.then(a)).finally(()=>{O.delete(d)});O.set(d,S);let _=S.then(()=>{},()=>{});return E.set(n,_),_.then(()=>{E.get(n)===_&&E.delete(n)}),S},T=async(n,s,a)=>{await e.ensureConsent();let d;try{d=await be(e.runtime,s)}catch(h){if(h instanceof U&&Ke.has(h.code)){await e.refreshView();return}throw h}if(a?.(d),e.destroyed())return;let f=d;f.plan!==void 0&&e.setView!==void 0?e.setView(f):await e.refreshView()},x=async n=>{await e.ensureConsent();let s;try{try{s=await n(e.runtime.client)}catch(a){if(!(a instanceof U)||a.code!=="consent_required")throw a;await e.runtime.ensureConsent({force:!0}),s=await n(e.runtime.client)}}catch(a){if(a instanceof U&&Ke.has(a.code)){await e.refreshView();return}throw a}e.destroyed()||(s!==void 0&&e.setView!==void 0?e.setView(s):await e.refreshView())},V=(n,s)=>A("choice",`${n}:${s}`,()=>x(a=>a.choose(n,s))),M=(n,s)=>n.options.some(a=>a.id===s)?V(n.nodeId,s):Promise.reject(new RangeError(`option ${String(s)} is not offered`)),H=(n,s)=>{let a=e.currentView(),d=a===null?void 0:oe(a,n);return d===void 0?Promise.reject(new RangeError(`the ${s} is not offered`)):V(d.nodeId,d.option.id)},N=n=>A("identity",n,()=>x(s=>s.confirmIdentity===void 0?Promise.reject(new Error("identity confirmation is not available in this build")):s.confirmIdentity(n))),G=(n,s)=>{let a=n.kind,d=a==="phone_otp",f=d?"phone":"email",h={action:"send"};if(d?n.needsPhone:n.needsEmail){let S=s[f]??p[a],_=d?S?.replace(/[\s().-]/g,""):S?.trim();if(_!==void 0||n.phase!=="verify"){if(_===void 0||!(d?Ot:Lt).test(_))return Promise.reject(d?new w("phone","format"):new K("email","format"));h[f]=_}}if(d){let S=n.channels,_=s.channel??(S.length===1?S[0]:void 0);if(S.length>0){if(_===void 0)return Promise.reject(new K("channel","required"));if(!S.includes(_))return Promise.reject(new K("channel","unavailable"))}_!==void 0&&(h.channel=_),h.phoneRules=1}return A(a,"send",()=>T(a,(S,_)=>S.submitCheck(a,h,{idempotencyKey:_}),S=>{Gt(S,a)||(u[a]=e.now(),h[f]!==void 0&&(p[a]=h[f]))}))},$=(n,s)=>xt.test(s)?A(n,"verify",()=>T(n,(a,d)=>a.submitCheck(n,{action:"verify",code:s},{idempotencyKey:d}))):Promise.reject(new w("code","format")),D=(n,s)=>A("eid_auth",n,()=>T("eid_auth",(a,d)=>a.submitCheck("eid_auth",s,{idempotencyKey:d}))),j=(n,s)=>{if(n.identifierBound)return D("start",{action:"start"});let a=ae(s??"");if(n.country==="MR"){if(!/^\d{10}$/.test(a))return Promise.reject(new w("nni","format"));if(!Fe(a))return Promise.reject(new w("nni","check_digit"))}else if(a==="")return Promise.reject(new w("nni","format"));return D("start",{action:"start",identifier:a})},Z=(n,s,a)=>{if(n.source!=="typed")return Promise.reject(new RangeError("this session already holds the ID number"));let d=ae(s);return/^\d{10}$/.test(d)?Ue({type:"national_id",issuingCountry:"MR",number:d})?A("population_registry","submitIdNumber",()=>T("population_registry",(f,h)=>f.submitCheck("population_registry",{idNumber:d,nni:d},{idempotencyKey:h}),()=>{b=`\u2022\u2022\u2022\u2022\u2022\u2022${d.slice(-4)}`})):Promise.reject(new w(a,"check_digit")):Promise.reject(new w(a,"format"))},J=n=>(e.stopCameras?.(),A(n,"skipCapture",()=>T(n,(s,a)=>s.submitCheck(n,Vt,{idempotencyKey:a}),()=>{(n==="liveness"||n==="portrait_icao")&&(g=!0)}))),Y=n=>{if(n.kind==="result"||n.context.simulation?.skipCapture!==!0)return n;let s=Ht(n);return s===null?n:{...n,skipCapture:()=>J(s)}},ce=n=>{switch(n.kind){case"phone_otp":case"email_otp":{let s={...n,send:(d={})=>G(n,d),verify:d=>$(n.kind,d),switchTo:()=>n.canSwitch&&n.switchChannel!==void 0?H([n.switchChannel==="email"?"email_otp":"phone_otp"],"other contact option"):Promise.reject(new RangeError("this session has no other contact option"))},a=u[n.kind];return s.resendAvailableAt===void 0&&a!==void 0&&(s.resendAvailableAt=new Date(a+wt).toISOString()),s}case"eid":return{...n,start:s=>j(n,s),verify:s=>Nt.test(s)?D("verify",{action:"verify",code:s}):Promise.reject(new w("code","format")),resend:()=>n.resendsRemaining===0?Promise.reject(new RangeError("no new code can be sent for this session")):D("resend",{action:"resend"}),useCamera:()=>n.canUseCamera&&n.cameraMethod!==void 0?H(n.cameraMethod==="document_photo"?["document"]:["population_registry"],"camera path"):Promise.reject(new RangeError("the camera path is not offered"))};case"method":return{...n,select:s=>{let a=n.choice.options.find(d=>F[d.service]===s);return a!==void 0?M(n.choice,a.id):Promise.reject(new RangeError(`method ${String(s)} is not offered`))},choose:s=>M(n.choice,s)};case"choice":return{...n,choose:s=>M(n.choice,s)};case"registry":return{...n,submitIdNumber:s=>Z(n,s,"idNumber"),submitNni:s=>Z(n,s,"nni"),confirm:()=>A("population_registry","confirm",()=>T("population_registry",(s,a)=>s.submitCheck("population_registry",{},{idempotencyKey:a}))),useDocument:()=>n.canUseDocument?H(["document"],"document method"):Promise.reject(new RangeError("the document method is not offered"))};case"document":return e.bindDocument!==void 0?e.bindDocument(n,I):{...n,issuer:null,documentType:null,captureSide:null,selectDocument:()=>{throw new Error("document capture is not available in this build")},capture:()=>{throw new Error("document capture is not available in this build")},uploadDocument:()=>Promise.reject(new Error("document upload is not available in this build"))};case"portrait":return e.bindPortrait!==void 0?e.bindPortrait(n,I):{...n,uploadFailed:!1,resubmit:()=>Promise.resolve(),capture:()=>{throw new Error("portrait capture is not available in this build")},uploadPortrait:()=>Promise.reject(new Error("portrait upload is not available in this build")),confirmFix:()=>Promise.reject(new Error("portrait review is not available in this build"))};case"contact_choice":return{...n,select:s=>{let a=s==="phone"?"phone_otp":s==="email"?"email_otp":void 0,d=n.choice.options.find(f=>f.service===a);return d!==void 0?M(n.choice,d.id):Promise.reject(new RangeError(`contact ${String(s)} is not offered`))},choose:s=>M(n.choice,s)};case"identity_summary":return{...n,...n.idNumberMasked===void 0&&n.summaryKind==="partial"&&b!==null?{idNumberMasked:b,nniMasked:b}:{},portrait:async()=>{let s=e.runtime.client;if(!n.portraitAvailable||s.identityPortrait===void 0)return null;try{return await s.identityPortrait()}catch{return null}},confirm:()=>N("confirm"),retake:()=>n.retakeAvailable?N("retake"):Promise.reject(new RangeError("no retake is left"))};case"liveness":return{...n,capture:s=>e.liveness(s),onLivePhoto:s=>n.livePhoto?.icao===!0&&e.onLivePhoto!==void 0?e.onLivePhoto(s):()=>{}};case"mobile_required":case"processing":return{...n,refresh:async()=>{r=!1,await e.refreshView()}};case"unsupported":case"result":return{...n};default:{let s=n;throw new Error(`runner: unhandled step ${JSON.stringify(s)}`)}}},m=n=>Y(ce(n)),P=async()=>{if(!c){c=!0;try{for(let n of Tt){if(await e.sleep(n),!t||e.destroyed())return;let s=await e.refreshView().catch(()=>null);if(s!==null&&q(s,{isMobile:e.isMobile()}).kind!=="processing")return}r=!0,I()}finally{c=!1}}},R=n=>{if(n.kind!=="liveness"||n.mode!=="selfie")return null;let s={kind:"processing",key:"processing",context:n.context,section:n.section,stalled:!1};if(C==="inflight")return s;if(!k||C==="done")return null;let a=e.keptFaceKey?.()??null;return a===null?null:(C="inflight",T("face_match",(d,f)=>d.submitCheck("face_match",{imageKey:a},{idempotencyKey:f}),()=>{C="done"}).then(()=>{C==="inflight"&&(C="done",I())},()=>{C="done",I()}),s)},v=(n,s=!1)=>{if(!t||e.destroyed()||e.chainBusy())return;let a=q(n,{isMobile:e.isMobile()});a.kind==="registry"&&a.recheck&&(k=!0,C="idle"),a=R(a)??a,a.kind==="processing"?a.stalled=r:r=!1;let d=m(a),f=a.kind==="result"?void 0:a.context.switchable,h=f===void 0?d:{...d,chooseOption:_=>M({nodeId:f.nodeId,kind:f.kind,selected:f.current,options:f.options},_)},S=JSON.stringify(h);a.kind==="registry"&&a.source==="document"&&a.state==="pending"&&!y.has("registry")&&(y.add("registry"),h.confirm().catch(_=>{(!(_ instanceof U)||Dt.has(_.code))&&y.delete("registry")})),!(!s&&S===o)&&(o=S,i=h,e.emitStep(h),a.kind==="processing"&&!r&&C!=="inflight"&&P(),a.kind==="result"&&!l&&(l=!0,e.emitResult(a.result)))};function I(){let n=e.currentView();n!==null&&v(n,!0)}return{run:async()=>{if(e.destroyed())throw new Error("verification destroyed");t=!0;let n=await e.ensureView();return i===null&&v(n),i??m(q(n,{isMobile:e.isMobile()}))},current:()=>i,onView:n=>v(n),onChainIdle:()=>{let n=e.currentView();n!==null&&v(n)},republish:I,submit:T,faceProbeSkipped:()=>g}}function Ht(e){switch(e.kind){case"document":return"doc_ocr";case"liveness":return e.mode==="selfie"?"face_match":"liveness";case"portrait":return e.phase==="capture"?"portrait_icao":null;case"mobile_required":return e.checkType;case"unsupported":return e.checkType==="nfc_chip"?"nfc_chip":null;default:return null}}function Gt(e,t){let i=e,o=i?.plan?.steps??i?.steps;return Array.isArray(o)?o.some(r=>r.checkType===t&&typeof r.reason=="string"):!1}export{Ye as a,Ft as b,Pe as c,Re as d,Wt as e,Ge as f,q as g,Tt as h,wt as i,fn as j};
@@ -0,0 +1 @@
1
+ import{a as d,c as p}from"./chunk-GI3UFGRQ.js";var f={id_document:{pose:{yawDeg:7,pitchDeg:7,rollDeg:5,pitchOffsetDeg:4},eyes:{relativeMin:.62,blinkMax:.48,lowerEyeMin:.32},mouth:{jawOpenMax:.13,smileMax:.28,puckerMax:.48},lighting:{faceLuma:[95,185],halfRatio:[.77,1.31],clippedMax:.015},background:{required:!0,lumaMin:165,lumaSdMax:20},resolution:{minIodPx:110,minWidth:480,minHeight:640}},selfie:{pose:{yawDeg:7,pitchDeg:7,rollDeg:7,pitchOffsetDeg:4},eyes:{relativeMin:.62,blinkMax:.48,lowerEyeMin:.32},mouth:{jawOpenMax:.13,smileMax:.28,puckerMax:.28},lighting:{faceLuma:[95,185],halfRatio:[.77,1.31],clippedMax:.015},background:{required:!1,lumaMin:165,lumaSdMax:20},resolution:{minIodPx:100,minWidth:480,minHeight:640}}};function k(a){let i=f[a];return{profile:a,backgroundCheck:d,...i.pose,holdMs:500,alertGraceMs:3e3,eyes:{...i.eyes},mouth:{...i.mouth},lighting:{...i.lighting,faceLuma:[i.lighting.faceLuma[0],i.lighting.faceLuma[1]],halfRatio:[i.lighting.halfRatio[0],i.lighting.halfRatio[1]]},background:{...i.background},resolution:{...i.resolution},holdFrames:3,cadenceHz:10,baseline:{windowMs:3e3,minSamples:6,percentile:.8},sharpnessMin:.25,glare:{specularMax:.01},softGraceMs:4e3,cropMargin:1.25,camera:{width:1920,height:1080}}}var y=k("id_document"),I=/^[A-Za-z0-9._-]{1,64}$/;function n(a,i,r,u){return typeof a=="number"&&Number.isFinite(a)&&a>=r&&a<=u?a:i}function x(a,i,r,u){if(!Array.isArray(a)||a.length!==2)return[i[0],i[1]];let[e,l]=a,t=n(e,Number.NaN,r,u),m=n(l,Number.NaN,r,u);return Number.isNaN(t)||Number.isNaN(m)||t>m?[i[0],i[1]]:[t,m]}function o(a){return typeof a=="object"&&a!==null&&!Array.isArray(a)?a:{}}function R(a,i){let r=o(a),u=r.profile==="selfie"?"selfie":"id_document",e=u==="selfie"?k(u):y,l=o(r.eyes),t=o(r.mouth),m=o(r.lighting),s=o(r.background),c=o(r.resolution),g=o(r.baseline),w=o(r.glare),b=o(r.camera),h=typeof s.required=="boolean"?s.required:e.background.required,M=p(r.backgroundCheck);return{profile:u,yawDeg:n(r.yawDeg,e.yawDeg,1,45),pitchDeg:n(r.pitchDeg,e.pitchDeg,1,45),pitchOffsetDeg:n(r.pitchOffsetDeg,e.pitchOffsetDeg,-20,20),rollDeg:n(r.rollDeg,e.rollDeg,1,45),holdMs:n(r.holdMs,e.holdMs,0,5e3),alertGraceMs:n(r.alertGraceMs,e.alertGraceMs,0,6e4),eyes:{relativeMin:n(l.relativeMin,e.eyes.relativeMin,0,1),blinkMax:n(l.blinkMax,e.eyes.blinkMax,0,1),lowerEyeMin:n(l.lowerEyeMin,e.eyes.lowerEyeMin,0,1)},mouth:{jawOpenMax:n(t.jawOpenMax,e.mouth.jawOpenMax,0,1),smileMax:n(t.smileMax,e.mouth.smileMax,0,1),puckerMax:n(t.puckerMax,e.mouth.puckerMax,0,1)},lighting:{faceLuma:x(m.faceLuma,e.lighting.faceLuma,0,255),halfRatio:x(m.halfRatio,e.lighting.halfRatio,0,10),clippedMax:n(m.clippedMax,e.lighting.clippedMax,0,1)},background:{required:h,lumaMin:n(s.lumaMin,e.background.lumaMin,0,255),lumaSdMax:n(s.lumaSdMax,e.background.lumaSdMax,0,255)},resolution:{minIodPx:n(c.minIodPx,e.resolution.minIodPx,1,2e3),minWidth:n(c.minWidth,e.resolution.minWidth,1,8e3),minHeight:n(c.minHeight,e.resolution.minHeight,1,8e3)},holdFrames:Math.round(n(r.holdFrames,e.holdFrames,1,60)),cadenceHz:n(r.cadenceHz,e.cadenceHz,1,30),baseline:{windowMs:n(g.windowMs,e.baseline.windowMs,200,3e4),minSamples:Math.round(n(g.minSamples,e.baseline.minSamples,1,300)),percentile:n(g.percentile,e.baseline.percentile,.5,1)},sharpnessMin:n(r.sharpnessMin,e.sharpnessMin,0,1),glare:{specularMax:n(w.specularMax,e.glare.specularMax,0,1)},softGraceMs:n(r.softGraceMs,e.softGraceMs,0,6e4),cropMargin:n(r.cropMargin,e.cropMargin,1,2),camera:{width:Math.round(n(b.width,e.camera.width,320,4096)),height:Math.round(n(b.height,e.camera.height,240,4096))},backgroundCheck:h?M:{...M,enabled:!1},tuningVersion:typeof i=="string"&&I.test(i)?i:null}}export{y as a,R as b};
@@ -0,0 +1 @@
1
+ var L=[468,473],$=[[33,133],[362,263]],ee=[[33,7,163,144,145,153,154,155,133,173,157,158,159,160,161,246],[362,382,381,380,374,373,390,249,263,466,388,387,386,385,384,398]],ne=1;function j(e){let n=Number.POSITIVE_INFINITY,o=Number.POSITIVE_INFINITY,a=Number.NEGATIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(let l of e)l.x<n&&(n=l.x),l.y<o&&(o=l.y),l.x>a&&(a=l.x),l.y>r&&(r=l.y);return e.length===0?{x:0,y:0,width:0,height:0}:{x:n,y:o,width:a-n,height:r-o}}var A=(e,n)=>({x:(e.x+n.x)/2,y:(e.y+n.y)/2});function se(e,n,o){if(e.length<468)return null;let a=f=>{let y=e[f];return{x:y.x*n,y:y.y*o}},r=[0,1].map(f=>{let y=e.length>L[1]?a(L[f]):null,[i,s]=$[f];return y??A(a(i),a(s))}),l=ee.map(f=>j(f.map(a))),c=[];for(let f=0;f<Math.min(e.length,468);f+=1)c.push(a(f));let[b,h]=r,u=b.x>h.x,g=u?h:b,p=u?b:h;return{leftEye:g,rightEye:p,iod:Math.hypot(p.x-g.x,p.y-g.y),box:j(c),nose:a(ne),leftEyeBox:u?l[1]:l[0],rightEyeBox:u?l[0]:l[1]}}var P=180/Math.PI;function W(e,n="column"){if(e.length<16||e.some(f=>!Number.isFinite(f)))return null;let o=(f,y)=>n==="column"?e[y*4+f]:e[f*4+y],a=Math.hypot(o(0,0),o(1,0),o(2,0))||1,r=o(0,0)/a,l=o(1,0)/a,c=o(2,0)/a,b=o(2,1)/a,h=o(2,2)/a,u=Math.asin(Math.max(-1,Math.min(1,-c)))*P,g=Math.atan2(b,h)*P,p=Math.atan2(l,r)*P;return{yaw:u,pitch:g,roll:p}}function U(e){return Math.atan2(e.rightEye.y-e.leftEye.y,e.rightEye.x-e.leftEye.x)*P}var _={width:480,height:640,eyeX:240,eyeY:289,iodMin:120,iodMax:160};function F(e){let n=_,o=e.iod>=n.iodMin&&e.iod<=n.iodMax?1:n.iodMin/Math.max(e.iod,1e-6),a=n.width/o,r=n.height/o,l=A(e.leftEye,e.rightEye);return{x:l.x-n.eyeX/n.width*a,y:l.y-n.eyeY/n.height*r,width:a,height:r}}function Y(e,n,o){let a=Math.max(0,-e.x),r=Math.max(0,-e.y),l=Math.max(0,e.x+e.width-n),c=Math.max(0,e.y+e.height-o);return Math.max((a+l)/e.width,(r+c)/e.height)}function ue(e,n,o,a){let r=F(e),l=r.x+r.width/2,c=r.y+r.height/2,b=_.width/_.height,h=Math.max(r.height*a.margin,a.minHeight,a.minWidth/b);h=Math.min(h,o,n/b);let u=h*b,g=Math.min(Math.max(l-u/2,0),Math.max(0,n-u)),p=Math.min(Math.max(c-h/2,0),Math.max(0,o-h));return{x:Math.round(g),y:Math.round(p),width:Math.round(u),height:Math.round(h)}}var G=["face","framing","pose","eyes","mouth","glare","lighting","background","resolution","sharpness"],K=new Set(["glare","background"]),k=e=>({pass:!0,value:e,coach:null}),x=(e,n)=>({pass:!1,value:e,coach:n}),O=(e,n)=>({pass:e,value:null,coach:e?null:n,none:!0});function te(e,n){let o=e.pose,a;if(o!==null){let i=o.pitch-n.pitchOffsetDeg,s=Math.max(Math.abs(o.yaw),Math.abs(i),Math.abs(o.roll));a=Math.abs(o.yaw)<=n.yawDeg&&Math.abs(i)<=n.pitchDeg&&Math.abs(o.roll)<=n.rollDeg?k(s):x(s,"pose")}else a={...O(!1,"pose"),value:e.eyeLineRoll??null};let r=O(!1,"eyes");if(e.eyes!==null){let{left:i,right:s}=e.eyes,d=Math.min(i,s),m=e.baselines,R=1-n.eyes.blinkMax;if(m!=null&&m.left>0&&m.left<=1&&m.right>0&&m.right<=1){let M=Math.max(i,s)>=R-1e-9&&d>=n.eyes.lowerEyeMin-1e-9&&i>=n.eyes.relativeMin*m.left-1e-9&&s>=n.eyes.relativeMin*m.right-1e-9,E=Math.min(i/m.left,s/m.right);r=M?k(E):x(E,"eyes")}else{let M=e.baseline,E=Math.max(R,M!==null&&M>0&&M<=1?n.eyes.relativeMin*M:0),w=M!==null&&M>0?d/M:null;r=d>=E-1e-9?k(w):x(w,"eyes")}}let l=O(!1,"mouth");if(e.mouth!==null){let{jawOpen:i,smile:s,pucker:d}=e.mouth,m=Math.max(i/n.mouth.jawOpenMax,s/n.mouth.smileMax,d/n.mouth.puckerMax);l=i<=n.mouth.jawOpenMax&&s<=n.mouth.smileMax&&d<=n.mouth.puckerMax?k(m):x(m,"mouth")}let c=e.lighting,b=O(!0,"lighting");if(c!==null){let[i,s]=n.lighting.faceLuma,[d,m]=n.lighting.halfRatio;b=c.faceLuma<i||c.faceLuma>s||c.clipped>n.lighting.clippedMax?x(c.faceLuma,"lighting"):c.halfRatio<d||c.halfRatio>m?x(c.halfRatio,"lighting_side"):k(c.faceLuma)}let h=e.uniformity,u=e.background,g=n.background.required?h!=null&&n.backgroundCheck.enabled?h.uniform?k(h.colorStd):x(h.colorStd,"background"):u===null?O(!0,"background"):u.luma>=n.background.lumaMin&&u.sd<=n.background.lumaSdMax?k(u.luma):x(u.luma,"background"):O(!0,"background"),p=n.resolution,f=Math.min(e.frameWidth,e.frameHeight)>=p.minWidth&&Math.max(e.frameWidth,e.frameHeight)>=p.minHeight,y=e.iod>=p.minIodPx&&f?k(e.iod):x(e.iod,"resolution");return{pose:a,eyes:r,mouth:l,lighting:b,background:g,resolution:y}}function D(e){let n=e?.eyeBlinkLeft,o=e?.eyeBlinkRight;return typeof n!="number"||typeof o!="number"?null:{left:1-n,right:1-o,blinkLeft:n,blinkRight:o}}function oe(e,n){if(e.length===0)return null;let o=[...e].sort((r,l)=>r-l),a=Math.min(o.length-1,Math.max(0,Math.ceil(n*o.length)-1));return o[a]}function V(e,n,o,a=null){let r={},l=e.geometry;if(e.faces!==1||l===null){let s=e.faces>1?x(e.faces,"multiple_faces"):x(e.faces,"no_face");for(let d of G)r[d]=d==="face"?s:O(!1,"no_face");return{results:r,pose:null}}r.face=k(1);let c=F(l),b=Y(c,e.frameWidth,e.frameHeight);r.framing=c.height>e.frameHeight*1.02||c.width>e.frameWidth*1.02?x(b,"too_close"):b>.02?x(b,"center"):k(b);let h=e.matrix!=null?W(e.matrix):null,u=D(e.blendshapes),g=e.blendshapes,p=e.stats??null,f=te({pose:h,eyeLineRoll:Math.abs(U(l)),eyes:u,baseline:o,baselines:a,mouth:g==null?null:{jawOpen:g.jawOpen??0,smile:Math.max(g.mouthSmileLeft??0,g.mouthSmileRight??0),pucker:g.mouthPucker??0},lighting:p?.lighting??null,background:p?.background??null,uniformity:e.backgroundCheck??null,iod:l.iod,frameWidth:e.frameWidth,frameHeight:e.frameHeight},n);Object.assign(r,f);let y=p?.eyeSpecular??null;r.glare=y===null?O(!0,"glare"):y<=n.glare.specularMax?k(y):x(y,"glare");let i=p?.sharpness??null;return r.sharpness=i===null||i>=n.sharpnessMin?k(i):x(i,"hold_still"),{results:r,pose:h}}var ae={pose:"pose",eyes:"eyes",mouth:"mouth",glare:"glare",lighting:"lighting",background:"background",framing:"resolution",resolution:"resolution"};function me(e,n={}){let o=n.policy==="alert",a=new Map,r=0,l=null,c=null,b={},h=[],u=null,g=null,p=null,f=0,y=i=>{let s=oe(h.map(i),e.baseline.percentile);return s===null||s<=0?null:Math.min(1,s)};return{push(i,s){let d=V(i,e,null),m=i.blendshapes;if(d.results.face.pass&&m!=null){let t=Z=>Math.round(Math.min(1,Math.max(0,Z??0))*1e3)/1e3,I={jawOpen:t(m.jawOpen),smile:t(Math.max(m.mouthSmileLeft??0,m.mouthSmileRight??0)),pucker:t(m.mouthPucker)};p===null&&(f=s);let S=p?.lowest??I;p={elapsedMs:Math.round(s-f),latest:I,lowest:{jawOpen:Math.min(S.jawOpen,I.jawOpen),smile:Math.min(S.smile,I.smile),pucker:Math.min(S.pucker,I.pucker)}}}let R=D(i.blendshapes);R!==null&&d.results.face.pass&&d.results.pose.pass&&h.push({at:s,left:R.left,right:R.right}),h=h.filter(t=>s-t.at<=e.baseline.windowMs);let M=h.length>=e.baseline.minSamples,E=M?y(t=>(t.left+t.right)/2):null,w=M?y(t=>t.left):null,B=M?y(t=>t.right):null,N=w!==null&&B!==null?{left:w,right:B}:null,{results:C,pose:q}=V(i,e,E,N);for(let t of G)C[t].pass&&(t!=="eyes"||E!==null)?a.has(t)||a.set(t,s):a.delete(t);let H=t=>{let I=a.get(t);return I!==void 0&&s-I>=e.holdMs};G.filter(t=>!K.has(t)).every(H)?l??(l=s):l=null;let X=t=>t==="background"&&i.backgroundCheck!=null?e.backgroundCheck.timeoutMs:e.softGraceMs,J=t=>K.has(t)&&!C[t].pass&&l!==null&&s-l>=X(t),v=G.map(t=>({criterion:t,pass:C[t].pass,held:H(t),waived:J(t),value:C[t].value,coach:C[t].pass?null:C[t].coach}));r=v.every(t=>t.pass||t.waived)?r+1:0;let T=v.find(t=>!t.pass&&!t.waived)??null,z=v.filter(t=>t.held||t.waived).length;C.face.pass&&C.framing.pass?c??(c=s):c=null;let Q=v.every(t=>t.held||t.waived)&&r>=e.holdFrames||o&&c!==null&&s-c>=e.alertGraceMs;b={};for(let t of G){let I=ae[t];I!==void 0&&C[t].none!==!0&&(b[I]=(b[I]??!0)&&C[t].pass)}return g=i.backgroundCheck??null,u={criteria:v,coach:T?.coach??"hold",failing:T?.criterion??null,progress:z/v.length,ready:Q,baseline:E,baselines:N,pose:q},u},last:()=>u,scores:()=>p,summary(){let i={criteria:{}};if(u===null)return i;i.verdict={...b},u.baseline!==null&&Math.round(u.baseline*1e3)>0&&(i.baselineEyeOpenness=Math.round(u.baseline*1e3)/1e3);let s=u.baselines;s!==null&&Math.round(s.left*1e3)>0&&Math.round(s.right*1e3)>0&&(i.baselineEyeOpennessLeft=Math.round(s.left*1e3)/1e3,i.baselineEyeOpennessRight=Math.round(s.right*1e3)/1e3);for(let d of u.criteria){let m=d.value===null||!Number.isFinite(d.value)?null:Math.round(d.value*1e3)/1e3;i.criteria[d.criterion]=d.waived?{pass:d.pass,value:m,waived:!0}:{pass:d.pass,value:m}}if(g!==null&&e.background.required){let{pixels:d,...m}=g;i.backgroundCheck=m}return i},reset(){a.clear(),r=0,l=null,c=null,b={},u=null,g=null,p=null}}}export{se as a,W as b,U as c,_ as d,F as e,Y as f,ue as g,G as h,te as i,D as j,oe as k,V as l,me as m};
@@ -1 +1 @@
1
- import{a as F,c as N,d as H,e as U}from"./chunk-FUHDOEBP.js";import{b as J,c as ee,d as te}from"./chunk-POIQGEZM.js";import{b as K,c as B,e as W,g as z,h as R,k,m as q,n as Z}from"./chunk-CQ7SKLMC.js";import{b as O,c as re,d as x,e as ie}from"./chunk-FPXL63KZ.js";import{d as X}from"./chunk-ZLWH4RBO.js";import{c as Q,d as Y,f as w,h as j,j as $}from"./chunk-OKWG3PVH.js";var ge=2500,be=1e3,ye=1500,ne=25e5,b=class extends Error{constructor(e,t){super(t??e),this.kind=e}},A=class{constructor(){this.recorder=null;this.stream=null;this.chunks=[];this.bytes=0;this.hardStopTimer=null;this.graceTimer=null;this.settled=!1}clearTimers(){this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.graceTimer&&clearTimeout(this.graceTimer),this.hardStopTimer=null,this.graceTimer=null}record(e,t,r){if(this.recorder&&!this.settled)return Promise.reject(new b("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=K();return new Promise((n,a)=>{let s;try{s=new MediaRecorder(e,i?{mimeType:i,videoBitsPerSecond:ne}:{videoBitsPerSecond:ne})}catch{try{s=new MediaRecorder(e)}catch{a(new b("unsupported"));return}}this.recorder=s;let d=c=>{this.settled||(this.settled=!0,this.clearTimers(),c())},u=()=>d(()=>{let c=s.mimeType||i||B,l=new Blob(this.chunks,{type:c});if(l.size===0){a(new b("generic","empty clip"));return}if(R(l)){a(new b("cliptoolarge"));return}n({blob:l,mimeType:c})});if(s.ondataavailable=c=>{c.data&&c.data.size&&(this.chunks.push(c.data),this.bytes+=c.data.size,this.bytes>z&&d(()=>{try{s.state!=="inactive"&&s.stop()}catch{}a(new b("cliptoolarge"))}))},s.onstop=u,s.onerror=()=>d(()=>a(new b("generic"))),r!==void 0){let c=!1;s.onstart=()=>{if(!(c||this.settled)){c=!0;try{r()}catch{}}}}try{s.start(be)}catch{d(()=>a(new b("generic")));return}this.hardStopTimer=setTimeout(()=>{if(this.settled||t?.(),s.state!=="inactive"){try{s.stop()}catch{u()}this.graceTimer=setTimeout(u,ye)}else u()},ge)})}stop(e){this.clearTimers();let t=this.recorder;if(t&&t.state!=="inactive")try{t.stop()}catch{}this.recorder=null,(e??this.stream)?.getTracks().forEach(i=>i.stop()),this.stream=null}};var Be=400,We=2e3,Se=["rose","peach","sand","mint","sky","lilac"],Ee={rose:"rgb(255, 185, 205)",peach:"rgb(245, 193, 159)",sand:"rgb(195, 210, 158)",mint:"rgb(139, 219, 203)",sky:"rgb(140, 214, 249)",lilac:"rgb(208, 197, 249)"};function ze(o){return Ee[o]}var Me=4,_e=4;function Ce(o){if(typeof o!="object"||o===null)return!1;let e=o;if(typeof e.nonce!="string"||e.nonce.length===0||!Array.isArray(e.colours)||e.colours.length!==3||!e.colours.every(r=>Se.includes(r))||!Array.isArray(e.onsetsMs)||e.onsetsMs.length!==3)return!1;let t=-1;for(let r of e.onsetsMs){if(typeof r!="number"||!Number.isFinite(r)||r<=t||r>=2e3)return!1;t=r}return!0}function ae(o,e){let t=e.now??(()=>performance.now()),r=Ce(o)?o:void 0,i=[],n=null,a=null,s=null,d=!1,u=null,c=p=>{u=p;try{e.paint(p)}catch{}},l=p=>{let m=e.frames?.()??null;return m!==null&&s!==null?m.mediaTimeMs+(p-m.presentationTimeMs)-s:p-(a??p)},f=(p,m,v=0)=>{if(d)return;let E=Math.max(0,p-l(t()));n=setTimeout(()=>{if(n=null,!d){if(v<Me&&l(t())<p-_e){f(p,m,v+1);return}m()}},E)},h=p=>{if(r!==void 0){if(p>=3){f(2e3,()=>c(null));return}f(r.onsetsMs[p],()=>{let m=l(t());if(m>2e3){u!==null&&c(null);return}let v=r.colours[p];c(v);let E=i.length===0?0:i[i.length-1].tMs;i.push({tMs:Math.max(E,Math.round(m)),colour:v}),h(p+1)})}};return{started(p){if(r===void 0||d||a!==null)return;a=p;let m=e.frames?.()??null;s=m===null?null:m.mediaTimeMs+(p-m.presentationTimeMs),h(0)},stop(){d||(d=!0,n!==null&&clearTimeout(n),n=null,u!==null&&c(null))},report(){return r===void 0?void 0:{nonce:r.nonce,rendered:[...i]}}}}function se(o,e,t=.92){return new Promise((r,i)=>{let n=o.videoWidth,a=o.videoHeight;if(!n||!a){i(new Error("video-not-ready"));return}let s=e.getContext("2d");if(!s){i(new Error("no-2d-context"));return}e.width=n,e.height=a,s.scale(-1,1),s.drawImage(o,-n,0),e.toBlob(d=>d?r(d):i(new Error("empty-keyframe")),"image/jpeg",t)})}var I=class{constructor(e){this.timer=null;this.frameCallbackId=null;this.running=!1;this.busy=!1;this.lastRunAt=Number.NEGATIVE_INFINITY;this.degradeCount=0;this.durations=[];this.options=e,this.periodMs=1e3/e.cadenceHz}start(){if(this.running)return;this.running=!0;let e=this.options.video;if(typeof e?.requestVideoFrameCallback=="function"){let t=()=>{this.running&&(this.frameCallbackId=e.requestVideoFrameCallback?.(()=>{this.frameCallbackId=null,this.now()-this.lastRunAt>=this.periodMs&&this.tick(),t()}))};t();return}this.timer=setInterval(()=>this.tick(),this.periodMs)}stop(){this.running=!1,this.timer!==null&&(clearInterval(this.timer),this.timer=null),this.frameCallbackId!==null&&(this.options.video?.cancelVideoFrameCallback?.(this.frameCallbackId),this.frameCallbackId=null)}stats(){let e=this.durations.length===0?0:this.durations.reduce((t,r)=>t+r,0)/this.durations.length;return{degradeCount:this.degradeCount,meanDetectMs:e}}now(){return this.options.now?.()??performance.now()}tick(){if(!this.running)return;if(this.busy){this.degradeCount+=1;return}this.busy=!0,this.lastRunAt=this.now();let e=this.now();this.options.run().catch(()=>{}).finally(()=>{this.busy=!1,this.durations.push(this.now()-e),this.durations.length>20&&this.durations.shift()})}};var Te=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}),S=o=>Math.min(1,Math.max(0,o)),M=class{constructor(e={}){this.p=0;this.lastTickAt=null;this.lastCenter=null;this.velocityEma=0;this.qWindow=[];this.lastSizeDirection="ideal";this.t={...Te,...e}}reset(){this.p=0,this.lastTickAt=null,this.lastCenter=null,this.velocityEma=0,this.qWindow=[],this.lastSizeDirection="ideal"}tick(e){let{observation:t,quality:r,timestampMs:i}=e,n=this.lastTickAt===null?0:Math.max(0,(i-this.lastTickAt)/1e3);this.lastTickAt=i;let a={presence:0,centering:0,size:0,pose:0,sharpness:S(r.sharpness),exposure:S(r.exposure),motion:1};if(t!==null){a.presence=1;let c=this.geometryOf(t,e);a.centering=c.centering,a.size=c.size,a.pose=c.pose,a.motion=this.motionOf(c.center,c.iod,i)}else this.lastCenter=null,this.velocityEma=0;let s=Math.min(a.presence,a.centering,a.size,a.pose,a.sharpness,a.exposure,a.motion);this.p=S(this.p+(s>=this.t.Q_GOOD?this.t.RISE_PER_S*s:-this.t.FALL_PER_S*(1-s))*n),this.qWindow.push({at:i,q:s}),this.qWindow=this.qWindow.filter(c=>c.at>=i-this.t.READY_WINDOW_MS);let d=this.qWindow.map(c=>c.q);if(d.length>=3){let c=Math.min(...d),l=d.indexOf(c);d=d.filter((f,h)=>h!==l)}let u=this.p>=1&&d.every(c=>c>=this.t.Q_GOOD);return{at:i,q:s,p:this.p,factors:a,guidanceKey:this.guidanceOf(a,r,s),ready:u,accepted:s>=this.t.Q_GOOD}}geometryOf(e,t){let{box:r,eyes:i}=e,n={x:t.frameWidth/2,y:t.frameHeight/2},a=Math.min(t.frameWidth,t.frameHeight),s=i!==void 0?{x:(i.left.x+i.right.x)/2,y:(i.left.y+i.right.y)/2}:{x:r.x+r.width/2,y:r.y+r.height/2-this.t.BOX_EYE_OFFSET_FACTOR*r.height},d=i!==void 0?Math.hypot(i.right.x-i.left.x,i.right.y-i.left.y):this.t.IOD_BOX_PROXY_FACTOR*r.width,u=Math.hypot(s.x-n.x,s.y-n.y),c=d<=0?0:1-S(u/(this.t.CENTER_FALLOFF_IOD_MULTIPLE*d)),l=a>0?d/a:0;this.lastSizeDirection=l<this.t.SIZE_IDEAL_MIN?"far":l>this.t.SIZE_IDEAL_MAX?"close":"ideal";let f;l<this.t.SIZE_HARD_MIN||l>this.t.SIZE_HARD_MAX?f=0:l<this.t.SIZE_IDEAL_MIN?f=(l-this.t.SIZE_HARD_MIN)/(this.t.SIZE_IDEAL_MIN-this.t.SIZE_HARD_MIN):l>this.t.SIZE_IDEAL_MAX?f=(this.t.SIZE_HARD_MAX-l)/(this.t.SIZE_HARD_MAX-this.t.SIZE_IDEAL_MAX):f=1;let h=1;if(i!==void 0){let p=Math.abs(Math.atan2(i.right.y-i.left.y,i.right.x-i.left.x))*180/Math.PI;h=1-S(p/this.t.ROLL_MAX_DEG)}return{center:s,iod:d,centering:c,size:f,pose:h}}motionOf(e,t,r){let i=this.lastCenter;if(this.lastCenter={...e,at:r},i===null||t<=0)return 1;let n=(r-i.at)/1e3;if(n<=0)return 1;let a=Math.hypot(e.x-i.x,e.y-i.y)/t/n;a<=this.t.MOTION_DEADBAND_IOD_PER_S&&(a=0);let s=1-Math.exp(-n/this.t.MOTION_TAU_S);return this.velocityEma=s*a+(1-s)*this.velocityEma,1-S(this.velocityEma/this.t.MOTION_VELOCITY_IOD_PER_S)}guidanceOf(e,t,r){if(e.presence<=0)return"fcv3.no_face";if(e.size<this.t.GUIDE_SIZE)return this.sizeGuidance();if(e.centering<this.t.GUIDE_CENTERING)return"fcv3.center_face";if(e.pose<this.t.GUIDE_POSE)return"fcv3.straighten";if(e.exposure<this.t.GUIDE_EXPOSURE)return this.exposureGuidance(t);if(e.sharpness<this.t.GUIDE_SHARPNESS)return"fcv3.steady_camera";if(e.motion<this.t.GUIDE_MOTION)return"fcv3.hold_still";if(r<this.t.Q_GOOD){let i=[["size",this.sizeGuidance()],["centering","fcv3.center_face"],["pose","fcv3.straighten"],["exposure",this.exposureGuidance(t)],["sharpness","fcv3.steady_camera"],["motion","fcv3.hold_still"]],n=i[0];for(let a of i)e[a[0]]<e[n[0]]&&(n=a);return n[1]}return"fcv3.hold_still"}sizeGuidance(){return this.lastSizeDirection==="far"?"fcv3.come_closer":"fcv3.move_back"}exposureGuidance(e){let t=(O[0]+O[1])/2;return e.meanLuma<t?"fcv3.more_light":"fcv3.too_bright"}};var Re=["size","centering","pose","exposure","sharpness","motion"];function ke(o){if(o.accepted)return null;if(o.factors.presence<=0)return"no_face";let e="size";for(let t of Re)o.factors[t]<o.factors[e]&&(e=t);return e}var _=class{constructor(){this.blocked={};this.acceptedMs=0;this.ticks=0;this.lastAt=null}record(e){let t=this.lastAt===null?0:Math.max(0,e.at-this.lastAt);this.lastAt=e.at,this.ticks+=1;let r=ke(e);if(r===null){this.acceptedMs+=t;return}let i=this.blocked[r]??{count:0,ms:0};i.count+=1,i.ms+=t,this.blocked[r]=i}summary(){let e={};for(let[t,r]of Object.entries(this.blocked))e[t]={count:r.count,ms:Math.round(r.ms)};return{blocked:e,acceptedMs:Math.round(this.acceptedMs),ticks:this.ticks}}};var Ae=["obs","manycam","virtual","snap camera","xsplit","droidcam","iriun","camo"],Ie=[/^(front|back|rear)( [a-z ]+)? camera$/i,/^camera2? ?\d+, facing (front|back|external)/i,/facetime/i,/\b(integrated|built-in|builtin) (web)?cam(era)?\b/i,/\b(hd )?web ?cam\b/i,/\([0-9a-f]{4}:[0-9a-f]{4}\)\s*$/i];function De(o){let e=(o??"").trim().toLowerCase();return e.length===0?"unknown":Ae.some(t=>e.includes(t))?"known_virtual":Ie.some(t=>t.test(e))?"platform":"unknown"}function oe(o){if(typeof o!="function")return!1;try{return/\{\s*\[native code\]\s*\}\s*$/.test(Function.prototype.toString.call(o))}catch{return!1}}function we(o=globalThis){return oe(o.navigator?.mediaDevices?.getUserMedia)&&oe(o.MediaStreamTrack?.prototype?.getSettings)}async function Oe(o,e=globalThis){let t=e.crypto?.subtle?.digest;if(typeof t=="function")try{let r=new Uint8Array(await t.call(e.crypto?.subtle,"SHA-256",new TextEncoder().encode(o)));return Array.from(r.subarray(0,8),i=>i.toString(16).padStart(2,"0")).join("")}catch{return}}async function ce(o,e=globalThis){let t={};try{t=typeof o.getSettings=="function"?o.getSettings()??{}:{}}catch{t={}}let r={};if((t.facingMode==="user"||t.facingMode==="environment"||t.facingMode==="left"||t.facingMode==="right")&&(r.facingMode=t.facingMode),typeof t.frameRate=="number"&&Number.isFinite(t.frameRate)&&(r.frameRate=t.frameRate),typeof t.width=="number"&&Number.isFinite(t.width)&&(r.width=t.width),typeof t.height=="number"&&Number.isFinite(t.height)&&(r.height=t.height),typeof t.deviceId=="string"&&t.deviceId.length>0){let n=await Oe(t.deviceId,e);n!==void 0&&(r.deviceIdHash=n)}let i;try{i=o.label}catch{i=void 0}return{trackSettings:r,capabilitiesPresent:typeof o.getCapabilities=="function",labelClass:De(i),prototypesIntact:we(e)}}var P=o=>Math.round(o*100)/100;function le(o){let e=o,t=typeof e?.requestVideoFrameCallback=="function",r=null,i=null,n=0,a=0,s=0,d=0,u=0,c=0,l=()=>{!t||e?.requestVideoFrameCallback===void 0||(r=e.requestVideoFrameCallback((f,h)=>{if(r=null,!t)return;let p=h.presentationTime;if(i!==null){let m=p-i.presentationTimeMs;a+=1;let v=m-s;s+=v/a,d+=v*(m-s)}typeof h.captureTime=="number"&&Number.isFinite(h.captureTime)&&(u+=p-h.captureTime,c+=1),n+=1,i={mediaTimeMs:h.mediaTime*1e3,presentationTimeMs:p},l()}))};return l(),{latest:()=>i,stats:()=>({n,meanGapMs:a===0?0:P(s),stdGapMs:a<2?0:P(Math.sqrt(d/(a-1))),captureLatencyMs:c===0?null:P(u/c)}),stop:()=>{t&&(t=!1,r!==null&&e?.cancelVideoFrameCallback?.(r),r=null)}}}function ue(o,e,t){return{...o,rvfc:e,rampPainter:t}}var xe=1e3,G="fcv3.hold_upright",Pe=200,L=4,Ge=600,Le=1e3,de={sharpness:1,exposure:1,meanLuma:128};function Ve(o,e){return e.width=o.videoWidth,e.height=o.videoHeight,e.getContext("2d").drawImage(o,0,0),new Promise((t,r)=>e.toBlob(i=>i?t(i):r(new Error("empty-keyframe")),"image/jpeg",.92))}function Fe(){return N()==="phone"}var pe=class{constructor(e){this.handlers=new Map;this.stateValue="idle";this.attempt=0;this.stream=null;this.detector=null;this.scheduler=null;this.gate=null;this.profiler=null;this.lastGuidanceKey=null;this.positioningStartedAt=0;this.cameraRequestedAt=null;this.cameraReadyAt=null;this.faceAcquiredAt=null;this.captureCompleteAt=null;this.fired=!1;this.carriedDegrade=0;this.carriedMeans=[];this.blockStats=null;this.lastGateSnapshotAt=Number.NEGATIVE_INFINITY;this.uprightGuard=!1;this.trackProvenance=null;this.ramp=null;this.snapshotCanvas=null;this.options=e,this.facing=e.facingMode??"user"}get state(){return this.stateValue}on(e,t){let r=this.handlers.get(e);return r||(r=new Set,this.handlers.set(e,r)),r.add(t),()=>r?.delete(t)}emit(e,t){for(let r of[...this.handlers.get(e)??[]])r(t)}async start(e={}){e.facingMode!==void 0&&(this.facing=e.facingMode),this.attempt+=1,await this.run(this.attempt)}get facingMode(){return this.facing}retry(){this.teardownAttempt(),this.start()}switchCamera(){this.facing=this.facing==="user"?"environment":"user",this.teardownAttempt(),this.start()}destroy(){this.attempt+=1,this.teardownAttempt(),this.detector?.destroy(),this.detector=null,this.options.video.srcObject=null}async run(e){let{options:t}=this;this.fired=!1,this.lastGuidanceKey=null,this.carriedDegrade=0,this.carriedMeans=[],this.cameraRequestedAt=null,this.cameraReadyAt=null,this.faceAcquiredAt=null,this.captureCompleteAt=null,this.uprightGuard=(t.isPhone??Fe)(),this.setState("preflight");let r=W();if(r!=="OK"){this.fail(r==="INSECURE_CONTEXT"?"insecure":"unsupported",{phase:"preflight"});return}this.setState("acquiring");let i=t.getUserMedia??(u=>navigator.mediaDevices.getUserMedia(u)),n;this.cameraRequestedAt=this.now();try{n=await i(F(H(),this.facing))}catch(u){if(e!==this.attempt)return;this.fail(q(u),{phase:"acquiring",name:k(u)});return}if(X(n),Z(n),e!==this.attempt){for(let u of n.getTracks())u.stop();return}this.stream=n;let a=n.getVideoTracks?.()[0];if(this.trackProvenance=a===void 0?null:ce(a).catch(()=>null),this.facing=U(n)??this.facing,t.video.srcObject=n,await t.video.play().catch(()=>{}),e!==this.attempt)return;if(this.cameraReadyAt=this.now(),this.detector===null){let u={v3AssetBaseUrl:t.v3AssetBaseUrl},c=t.createDetector??(t.createWorker!==void 0&&j()?async()=>{try{return await $.create(t.createWorker(),u)}catch{return w(u)}}:()=>w(u)),l;try{l=await c()}catch(f){e===this.attempt&&this.fail("models",{phase:"models",name:k(f)},f instanceof Q?f.fallbackReason:He(f));return}if(e!==this.attempt){l.destroy();return}this.detector=l,this.options.telemetry?.({type:"detector",tier:l.tier,fallbackReason:l.fallbackReason})}let s=J(),d=t.deviceClass??ee(s);this.profiler=new te(d),this.options.telemetry?.({type:"profile",staticClass:d,activeClass:this.profiler.deviceClass,simd:s.simd}),this.gate=new M(t.thresholds??{}),this.blockStats=new _,this.lastGateSnapshotAt=this.now(),t.rankKeyframes?.()&&import("./keyframe-rank-YAJLYJYF.js").then(u=>V=u,()=>{}),this.setState("positioning"),this.positioningStartedAt=this.now(),this.startScheduler(e)}get animations(){return this.profiler?.profile.animations??"full"}startScheduler(e){let t=this.profiler;if(t===null)return;if(this.scheduler!==null){let i=this.scheduler.stats();this.carriedDegrade+=i.degradeCount,i.meanDetectMs>0&&this.carriedMeans.push(i.meanDetectMs),this.scheduler.stop()}let r=new I({cadenceHz:t.profile.cadenceHz,video:this.options.video,now:this.options.now,run:()=>this.detectTick(e)});this.scheduler=r,r.start()}async detectTick(e){let{detector:t,gate:r,profiler:i}=this,n=this.options.video;if(e!==this.attempt||t===null||r===null||i===null||this.fired||n.videoWidth===0)return;if(this.isLandscape()){this.holdUpright(e);return}let a=i.deviceClass,s=this.now(),d=this.options.makeSnapshot?.(n,i.profile.inputWidth)??this.defaultSnapshot(n,i.profile.inputWidth),u=null;try{u=await t.detect(d,n.videoWidth,n.videoHeight)}catch{u=null}if(e!==this.attempt||this.fired)return;i.record(this.now()-s),i.deviceClass!==a&&this.startScheduler(e);let c=u===null?de:this.options.measureQuality?.(n,u.box)??this.defaultQuality(n,u.box),l=r.tick({timestampMs:this.now(),observation:u,quality:c,frameWidth:n.videoWidth,frameHeight:n.videoHeight});l.accepted&&this.faceAcquiredAt===null&&(this.faceAcquiredAt=l.at),this.blockStats?.record(l),!l.ready&&l.at-this.lastGateSnapshotAt>=xe&&(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:t}=this,r=this.scheduler;r?.stop(),this.reportGate(!0);let i=r?.stats()??{degradeCount:0,meanDetectMs:0},n=[...this.carriedMeans,...i.meanDetectMs>0?[i.meanDetectMs]:[]];t.telemetry?.({type:"fired",timeToGateMs:this.now()-this.positioningStartedAt,degradeCount:this.carriedDegrade+i.degradeCount,meanDetectMs:n.length===0?0:n.reduce((g,y)=>g+y,0)/n.length});let a=t.mode??"clip",s=t.rankKeyframes?.()&&V?V.default(this,e).catch(()=>this.collectKeyframes(e)):this.collectKeyframes(e);if(a==="photo"){let g=this.watchRotation(e,null),y=await s;if(g(),e!==this.attempt)return;if(y===null){this.fail("generic",{phase:"keyframes"});return}let ve=await this.provenance({n:0,meanGapMs:0,stdGapMs:0,captureLatencyMs:null},!1);if(e!==this.attempt)return;this.finishCapture({keyframe:y.blob,previewDataUrl:y.previewDataUrl,...ve});return}this.setState("recording");let d=t.createRecorder?.()??new A,u=this.stream;if(u===null){this.fail("generic",{phase:"recording"});return}let c=le(t.video),l=t.screenRamp?.(),f=l!==void 0,h=ae(l,{paint:g=>{(g===null||e===this.attempt)&&this.emit("ramp",{colour:g})},now:()=>this.now(),frames:c.latest});this.ramp=h;let p=()=>{c.stop(),h.stop(),this.ramp===h&&(this.ramp=null)},m=this.watchRotation(e,d),v=null;s.then(g=>{v=g},()=>{});let E=()=>{e===this.attempt&&v!==null&&this.emit("frozen",{previewDataUrl:v.previewDataUrl})},C,T;try{[C,T]=await Promise.all([d.record(u,E,()=>h.started(this.now())),s])}catch(g){if(m(),p(),e!==this.attempt)return;let y=g.kind;this.fail(y==="cliptoolarge"?"cliptoolarge":"recorder",{phase:"recording",name:k(g)});return}m();let me=c.stats();if(p(),e!==this.attempt)return;if(R(C.blob)){this.fail("cliptoolarge",{phase:"recording"});return}if(T===null){this.fail("generic",{phase:"keyframes"});return}let D=h.report(),fe=await this.provenance(me,f);e===this.attempt&&this.finishCapture({clip:C.blob,clipMimeType:C.mimeType,keyframe:T.blob,previewDataUrl:T.previewDataUrl,...D!==void 0&&D.rendered.length>0?{screenRamp:D}:{},...fe})}async provenance(e,t){let r=this.trackProvenance;if(r===null)return{};let i,n=new Promise(s=>{i=setTimeout(()=>s(null),Le)}),a=await Promise.race([r,n]);return clearTimeout(i),a===null?{}:{provenance:ue(a,e,t)}}isLandscape(){let e=this.options.video;return this.uprightGuard&&e.videoWidth>e.videoHeight}holdUpright(e){this.gate?.reset(),this.emit("checks",{engine:"v3",progress:0,q:0,factors:{presence:0,centering:0,size:0,pose:0,sharpness:0,exposure:0,motion:0},attempt:e}),this.lastGuidanceKey!==G&&(this.lastGuidanceKey=G,this.emit("guidance",{key:G}))}watchRotation(e,t){if(!this.uprightGuard)return()=>{};let r=this.options.video,i=()=>{if(e!==this.attempt||t!==null&&this.stateValue!=="recording"){s();return}r.videoWidth>0&&this.isLandscape()&&(s(),this.abortRecording(e,t))},n=setInterval(i,Pe);r.addEventListener?.("resize",i);let a=!1;function s(){a||(a=!0,clearInterval(n),r.removeEventListener?.("resize",i))}return s}abortRecording(e,t){if(e!==this.attempt)return;this.attempt+=1;let r=this.attempt;try{t?.stop()}catch{}this.ramp?.stop(),this.ramp=null,this.fired=!1,this.captureCompleteAt=null,this.gate=new M(this.options.thresholds??{}),this.blockStats=new _,this.lastGateSnapshotAt=this.now(),this.lastGuidanceKey=null,this.setState("positioning"),this.positioningStartedAt=this.now(),this.holdUpright(r),this.startScheduler(r)}async collectKeyframes(e){let t=this.options.captureKeyframe??(n=>this.defaultKeyframe(n)),r=Ge/(L-1),i=null;for(let n=0;n<L;n+=1){if(e!==this.attempt)return i;try{let a=await t(this.options.video);(i===null||a.sharpness>i.sharpness)&&(i=a)}catch{}n<L-1&&await Ne(r)}return i}finishCapture(e){this.stopTracks(),this.setState("captured");let t=this.captureTiming();this.emit("artifacts",t===void 0?e:{...e,timing:t})}captureTiming(){let e={},t=(r,i,n)=>{i!==null&&n!==null&&(e[r]=Math.max(0,Math.round(n-i)))};return t("cameraReadyMs",this.cameraRequestedAt,this.cameraReadyAt),t("faceAcquireMs",this.cameraReadyAt,this.faceAcquiredAt),t("captureMs",this.faceAcquiredAt,this.captureCompleteAt),Object.keys(e).length>0?e:void 0}async defaultKeyframe(e){let t=document.createElement("canvas"),r=await(this.facing==="user"?se:Ve)(e,t),i=t.toDataURL("image/jpeg",.92);return{blob:r,previewDataUrl:i,sharpness:this.centerSharpness(e)}}defaultSnapshot(e,t){try{let r=this.snapshotCanvas??document.createElement("canvas"),i=t/Math.max(1,e.videoWidth),n=Math.max(1,Math.round(e.videoWidth*i)),a=Math.max(1,Math.round(e.videoHeight*i)),s=r.getContext("2d");return s===null?e:(r.width!==n&&(r.width=n),r.height!==a&&(r.height=a),s.drawImage(e,0,0,n,a),this.snapshotCanvas=r,r)}catch{return e}}defaultQuality(e,t){let r=he(e,t,96);return r===null?de:{sharpness:x(r),exposure:ie(r),meanLuma:re(r)}}centerSharpness(e){let t=Y(e),r=he(e,{x:t.width*.25,y:t.height*.25,width:t.width*.5,height:t.height*.5},96);return r===null?0:x(r)}teardownAttempt(){this.scheduler?.stop(),this.scheduler=null,this.reportGate(!0),this.gate=null,this.ramp?.stop(),this.ramp=null,this.stopTracks()}reportGate(e){let t=this.blockStats,r=this.profiler;if(t===null||r===null)return;let i=t.summary();e&&(this.blockStats=null),i.ticks!==0&&this.options.telemetry?.({type:"gate",final:e,activeClass:r.deviceClass,cadenceHz:r.profile.cadenceHz,...i})}stopTracks(){if(this.stream!==null){for(let e of this.stream.getTracks())e.stop();this.stream=null}}fail(e,t,r){this.scheduler?.stop(),this.reportGate(!0),this.stopTracks(),this.setState("error"),this.options.telemetry?.({type:"error",kind:e,fallbackReason:r});let{phase:i,name:n}=t;this.emit("error",{kind:e,retryable:e!=="insecure"&&e!=="unsupported",detail:n===void 0?{phase:i}:{phase:i,name:n}})}setState(e){this.stateValue=e,this.emit("statechange",{state:e})}now(){return this.options.now?.()??performance.now()}},V;function Ne(o){return new Promise(e=>setTimeout(e,o))}function He(o){return o instanceof Error?o.message:String(o)}function he(o,e,t){try{let r=document.createElement("canvas"),i=t/Math.max(1,e.width);r.width=Math.max(1,Math.round(e.width*i)),r.height=Math.max(1,Math.round(e.height*i));let n=r.getContext("2d");return n===null?null:(n.drawImage(o,e.x,e.y,e.width,e.height,0,0,r.width,r.height),n.getImageData(0,0,r.width,r.height))}catch{return null}}export{ge as a,be as b,ye as c,ne as d,b as e,A as f,Be as g,We as h,Se as i,ze as j,se as k,I as l,Te as m,M as n,ke as o,_ as p,xe as q,G as r,Pe as s,L as t,Ge as u,Le as v,pe as w};
1
+ import{a as F,c as N,d as H,e as U}from"./chunk-FUHDOEBP.js";import{b as J,c as ee,d as te}from"./chunk-POIQGEZM.js";import{b as K,c as B,e as W,g as z,h as R,k,m as q,n as Z}from"./chunk-CQ7SKLMC.js";import{b as O,c as re,d as x,e as ie}from"./chunk-FPXL63KZ.js";import{d as X}from"./chunk-VIAT4DEA.js";import{c as Q,d as Y,f as w,h as j,j as $}from"./chunk-OKWG3PVH.js";var ge=2500,be=1e3,ye=1500,ne=25e5,b=class extends Error{constructor(e,t){super(t??e),this.kind=e}},A=class{constructor(){this.recorder=null;this.stream=null;this.chunks=[];this.bytes=0;this.hardStopTimer=null;this.graceTimer=null;this.settled=!1}clearTimers(){this.hardStopTimer&&clearTimeout(this.hardStopTimer),this.graceTimer&&clearTimeout(this.graceTimer),this.hardStopTimer=null,this.graceTimer=null}record(e,t,r){if(this.recorder&&!this.settled)return Promise.reject(new b("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=K();return new Promise((n,a)=>{let s;try{s=new MediaRecorder(e,i?{mimeType:i,videoBitsPerSecond:ne}:{videoBitsPerSecond:ne})}catch{try{s=new MediaRecorder(e)}catch{a(new b("unsupported"));return}}this.recorder=s;let d=c=>{this.settled||(this.settled=!0,this.clearTimers(),c())},u=()=>d(()=>{let c=s.mimeType||i||B,l=new Blob(this.chunks,{type:c});if(l.size===0){a(new b("generic","empty clip"));return}if(R(l)){a(new b("cliptoolarge"));return}n({blob:l,mimeType:c})});if(s.ondataavailable=c=>{c.data&&c.data.size&&(this.chunks.push(c.data),this.bytes+=c.data.size,this.bytes>z&&d(()=>{try{s.state!=="inactive"&&s.stop()}catch{}a(new b("cliptoolarge"))}))},s.onstop=u,s.onerror=()=>d(()=>a(new b("generic"))),r!==void 0){let c=!1;s.onstart=()=>{if(!(c||this.settled)){c=!0;try{r()}catch{}}}}try{s.start(be)}catch{d(()=>a(new b("generic")));return}this.hardStopTimer=setTimeout(()=>{if(this.settled||t?.(),s.state!=="inactive"){try{s.stop()}catch{u()}this.graceTimer=setTimeout(u,ye)}else u()},ge)})}stop(e){this.clearTimers();let t=this.recorder;if(t&&t.state!=="inactive")try{t.stop()}catch{}this.recorder=null,(e??this.stream)?.getTracks().forEach(i=>i.stop()),this.stream=null}};var Be=400,We=2e3,Se=["rose","peach","sand","mint","sky","lilac"],Ee={rose:"rgb(255, 185, 205)",peach:"rgb(245, 193, 159)",sand:"rgb(195, 210, 158)",mint:"rgb(139, 219, 203)",sky:"rgb(140, 214, 249)",lilac:"rgb(208, 197, 249)"};function ze(o){return Ee[o]}var Me=4,_e=4;function Ce(o){if(typeof o!="object"||o===null)return!1;let e=o;if(typeof e.nonce!="string"||e.nonce.length===0||!Array.isArray(e.colours)||e.colours.length!==3||!e.colours.every(r=>Se.includes(r))||!Array.isArray(e.onsetsMs)||e.onsetsMs.length!==3)return!1;let t=-1;for(let r of e.onsetsMs){if(typeof r!="number"||!Number.isFinite(r)||r<=t||r>=2e3)return!1;t=r}return!0}function ae(o,e){let t=e.now??(()=>performance.now()),r=Ce(o)?o:void 0,i=[],n=null,a=null,s=null,d=!1,u=null,c=p=>{u=p;try{e.paint(p)}catch{}},l=p=>{let m=e.frames?.()??null;return m!==null&&s!==null?m.mediaTimeMs+(p-m.presentationTimeMs)-s:p-(a??p)},f=(p,m,v=0)=>{if(d)return;let E=Math.max(0,p-l(t()));n=setTimeout(()=>{if(n=null,!d){if(v<Me&&l(t())<p-_e){f(p,m,v+1);return}m()}},E)},h=p=>{if(r!==void 0){if(p>=3){f(2e3,()=>c(null));return}f(r.onsetsMs[p],()=>{let m=l(t());if(m>2e3){u!==null&&c(null);return}let v=r.colours[p];c(v);let E=i.length===0?0:i[i.length-1].tMs;i.push({tMs:Math.max(E,Math.round(m)),colour:v}),h(p+1)})}};return{started(p){if(r===void 0||d||a!==null)return;a=p;let m=e.frames?.()??null;s=m===null?null:m.mediaTimeMs+(p-m.presentationTimeMs),h(0)},stop(){d||(d=!0,n!==null&&clearTimeout(n),n=null,u!==null&&c(null))},report(){return r===void 0?void 0:{nonce:r.nonce,rendered:[...i]}}}}function se(o,e,t=.92){return new Promise((r,i)=>{let n=o.videoWidth,a=o.videoHeight;if(!n||!a){i(new Error("video-not-ready"));return}let s=e.getContext("2d");if(!s){i(new Error("no-2d-context"));return}e.width=n,e.height=a,s.scale(-1,1),s.drawImage(o,-n,0),e.toBlob(d=>d?r(d):i(new Error("empty-keyframe")),"image/jpeg",t)})}var I=class{constructor(e){this.timer=null;this.frameCallbackId=null;this.running=!1;this.busy=!1;this.lastRunAt=Number.NEGATIVE_INFINITY;this.degradeCount=0;this.durations=[];this.options=e,this.periodMs=1e3/e.cadenceHz}start(){if(this.running)return;this.running=!0;let e=this.options.video;if(typeof e?.requestVideoFrameCallback=="function"){let t=()=>{this.running&&(this.frameCallbackId=e.requestVideoFrameCallback?.(()=>{this.frameCallbackId=null,this.now()-this.lastRunAt>=this.periodMs&&this.tick(),t()}))};t();return}this.timer=setInterval(()=>this.tick(),this.periodMs)}stop(){this.running=!1,this.timer!==null&&(clearInterval(this.timer),this.timer=null),this.frameCallbackId!==null&&(this.options.video?.cancelVideoFrameCallback?.(this.frameCallbackId),this.frameCallbackId=null)}stats(){let e=this.durations.length===0?0:this.durations.reduce((t,r)=>t+r,0)/this.durations.length;return{degradeCount:this.degradeCount,meanDetectMs:e}}now(){return this.options.now?.()??performance.now()}tick(){if(!this.running)return;if(this.busy){this.degradeCount+=1;return}this.busy=!0,this.lastRunAt=this.now();let e=this.now();this.options.run().catch(()=>{}).finally(()=>{this.busy=!1,this.durations.push(this.now()-e),this.durations.length>20&&this.durations.shift()})}};var Te=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}),S=o=>Math.min(1,Math.max(0,o)),M=class{constructor(e={}){this.p=0;this.lastTickAt=null;this.lastCenter=null;this.velocityEma=0;this.qWindow=[];this.lastSizeDirection="ideal";this.t={...Te,...e}}reset(){this.p=0,this.lastTickAt=null,this.lastCenter=null,this.velocityEma=0,this.qWindow=[],this.lastSizeDirection="ideal"}tick(e){let{observation:t,quality:r,timestampMs:i}=e,n=this.lastTickAt===null?0:Math.max(0,(i-this.lastTickAt)/1e3);this.lastTickAt=i;let a={presence:0,centering:0,size:0,pose:0,sharpness:S(r.sharpness),exposure:S(r.exposure),motion:1};if(t!==null){a.presence=1;let c=this.geometryOf(t,e);a.centering=c.centering,a.size=c.size,a.pose=c.pose,a.motion=this.motionOf(c.center,c.iod,i)}else this.lastCenter=null,this.velocityEma=0;let s=Math.min(a.presence,a.centering,a.size,a.pose,a.sharpness,a.exposure,a.motion);this.p=S(this.p+(s>=this.t.Q_GOOD?this.t.RISE_PER_S*s:-this.t.FALL_PER_S*(1-s))*n),this.qWindow.push({at:i,q:s}),this.qWindow=this.qWindow.filter(c=>c.at>=i-this.t.READY_WINDOW_MS);let d=this.qWindow.map(c=>c.q);if(d.length>=3){let c=Math.min(...d),l=d.indexOf(c);d=d.filter((f,h)=>h!==l)}let u=this.p>=1&&d.every(c=>c>=this.t.Q_GOOD);return{at:i,q:s,p:this.p,factors:a,guidanceKey:this.guidanceOf(a,r,s),ready:u,accepted:s>=this.t.Q_GOOD}}geometryOf(e,t){let{box:r,eyes:i}=e,n={x:t.frameWidth/2,y:t.frameHeight/2},a=Math.min(t.frameWidth,t.frameHeight),s=i!==void 0?{x:(i.left.x+i.right.x)/2,y:(i.left.y+i.right.y)/2}:{x:r.x+r.width/2,y:r.y+r.height/2-this.t.BOX_EYE_OFFSET_FACTOR*r.height},d=i!==void 0?Math.hypot(i.right.x-i.left.x,i.right.y-i.left.y):this.t.IOD_BOX_PROXY_FACTOR*r.width,u=Math.hypot(s.x-n.x,s.y-n.y),c=d<=0?0:1-S(u/(this.t.CENTER_FALLOFF_IOD_MULTIPLE*d)),l=a>0?d/a:0;this.lastSizeDirection=l<this.t.SIZE_IDEAL_MIN?"far":l>this.t.SIZE_IDEAL_MAX?"close":"ideal";let f;l<this.t.SIZE_HARD_MIN||l>this.t.SIZE_HARD_MAX?f=0:l<this.t.SIZE_IDEAL_MIN?f=(l-this.t.SIZE_HARD_MIN)/(this.t.SIZE_IDEAL_MIN-this.t.SIZE_HARD_MIN):l>this.t.SIZE_IDEAL_MAX?f=(this.t.SIZE_HARD_MAX-l)/(this.t.SIZE_HARD_MAX-this.t.SIZE_IDEAL_MAX):f=1;let h=1;if(i!==void 0){let p=Math.abs(Math.atan2(i.right.y-i.left.y,i.right.x-i.left.x))*180/Math.PI;h=1-S(p/this.t.ROLL_MAX_DEG)}return{center:s,iod:d,centering:c,size:f,pose:h}}motionOf(e,t,r){let i=this.lastCenter;if(this.lastCenter={...e,at:r},i===null||t<=0)return 1;let n=(r-i.at)/1e3;if(n<=0)return 1;let a=Math.hypot(e.x-i.x,e.y-i.y)/t/n;a<=this.t.MOTION_DEADBAND_IOD_PER_S&&(a=0);let s=1-Math.exp(-n/this.t.MOTION_TAU_S);return this.velocityEma=s*a+(1-s)*this.velocityEma,1-S(this.velocityEma/this.t.MOTION_VELOCITY_IOD_PER_S)}guidanceOf(e,t,r){if(e.presence<=0)return"fcv3.no_face";if(e.size<this.t.GUIDE_SIZE)return this.sizeGuidance();if(e.centering<this.t.GUIDE_CENTERING)return"fcv3.center_face";if(e.pose<this.t.GUIDE_POSE)return"fcv3.straighten";if(e.exposure<this.t.GUIDE_EXPOSURE)return this.exposureGuidance(t);if(e.sharpness<this.t.GUIDE_SHARPNESS)return"fcv3.steady_camera";if(e.motion<this.t.GUIDE_MOTION)return"fcv3.hold_still";if(r<this.t.Q_GOOD){let i=[["size",this.sizeGuidance()],["centering","fcv3.center_face"],["pose","fcv3.straighten"],["exposure",this.exposureGuidance(t)],["sharpness","fcv3.steady_camera"],["motion","fcv3.hold_still"]],n=i[0];for(let a of i)e[a[0]]<e[n[0]]&&(n=a);return n[1]}return"fcv3.hold_still"}sizeGuidance(){return this.lastSizeDirection==="far"?"fcv3.come_closer":"fcv3.move_back"}exposureGuidance(e){let t=(O[0]+O[1])/2;return e.meanLuma<t?"fcv3.more_light":"fcv3.too_bright"}};var Re=["size","centering","pose","exposure","sharpness","motion"];function ke(o){if(o.accepted)return null;if(o.factors.presence<=0)return"no_face";let e="size";for(let t of Re)o.factors[t]<o.factors[e]&&(e=t);return e}var _=class{constructor(){this.blocked={};this.acceptedMs=0;this.ticks=0;this.lastAt=null}record(e){let t=this.lastAt===null?0:Math.max(0,e.at-this.lastAt);this.lastAt=e.at,this.ticks+=1;let r=ke(e);if(r===null){this.acceptedMs+=t;return}let i=this.blocked[r]??{count:0,ms:0};i.count+=1,i.ms+=t,this.blocked[r]=i}summary(){let e={};for(let[t,r]of Object.entries(this.blocked))e[t]={count:r.count,ms:Math.round(r.ms)};return{blocked:e,acceptedMs:Math.round(this.acceptedMs),ticks:this.ticks}}};var Ae=["obs","manycam","virtual","snap camera","xsplit","droidcam","iriun","camo"],Ie=[/^(front|back|rear)( [a-z ]+)? camera$/i,/^camera2? ?\d+, facing (front|back|external)/i,/facetime/i,/\b(integrated|built-in|builtin) (web)?cam(era)?\b/i,/\b(hd )?web ?cam\b/i,/\([0-9a-f]{4}:[0-9a-f]{4}\)\s*$/i];function De(o){let e=(o??"").trim().toLowerCase();return e.length===0?"unknown":Ae.some(t=>e.includes(t))?"known_virtual":Ie.some(t=>t.test(e))?"platform":"unknown"}function oe(o){if(typeof o!="function")return!1;try{return/\{\s*\[native code\]\s*\}\s*$/.test(Function.prototype.toString.call(o))}catch{return!1}}function we(o=globalThis){return oe(o.navigator?.mediaDevices?.getUserMedia)&&oe(o.MediaStreamTrack?.prototype?.getSettings)}async function Oe(o,e=globalThis){let t=e.crypto?.subtle?.digest;if(typeof t=="function")try{let r=new Uint8Array(await t.call(e.crypto?.subtle,"SHA-256",new TextEncoder().encode(o)));return Array.from(r.subarray(0,8),i=>i.toString(16).padStart(2,"0")).join("")}catch{return}}async function ce(o,e=globalThis){let t={};try{t=typeof o.getSettings=="function"?o.getSettings()??{}:{}}catch{t={}}let r={};if((t.facingMode==="user"||t.facingMode==="environment"||t.facingMode==="left"||t.facingMode==="right")&&(r.facingMode=t.facingMode),typeof t.frameRate=="number"&&Number.isFinite(t.frameRate)&&(r.frameRate=t.frameRate),typeof t.width=="number"&&Number.isFinite(t.width)&&(r.width=t.width),typeof t.height=="number"&&Number.isFinite(t.height)&&(r.height=t.height),typeof t.deviceId=="string"&&t.deviceId.length>0){let n=await Oe(t.deviceId,e);n!==void 0&&(r.deviceIdHash=n)}let i;try{i=o.label}catch{i=void 0}return{trackSettings:r,capabilitiesPresent:typeof o.getCapabilities=="function",labelClass:De(i),prototypesIntact:we(e)}}var P=o=>Math.round(o*100)/100;function le(o){let e=o,t=typeof e?.requestVideoFrameCallback=="function",r=null,i=null,n=0,a=0,s=0,d=0,u=0,c=0,l=()=>{!t||e?.requestVideoFrameCallback===void 0||(r=e.requestVideoFrameCallback((f,h)=>{if(r=null,!t)return;let p=h.presentationTime;if(i!==null){let m=p-i.presentationTimeMs;a+=1;let v=m-s;s+=v/a,d+=v*(m-s)}typeof h.captureTime=="number"&&Number.isFinite(h.captureTime)&&(u+=p-h.captureTime,c+=1),n+=1,i={mediaTimeMs:h.mediaTime*1e3,presentationTimeMs:p},l()}))};return l(),{latest:()=>i,stats:()=>({n,meanGapMs:a===0?0:P(s),stdGapMs:a<2?0:P(Math.sqrt(d/(a-1))),captureLatencyMs:c===0?null:P(u/c)}),stop:()=>{t&&(t=!1,r!==null&&e?.cancelVideoFrameCallback?.(r),r=null)}}}function ue(o,e,t){return{...o,rvfc:e,rampPainter:t}}var xe=1e3,G="fcv3.hold_upright",Pe=200,L=4,Ge=600,Le=1e3,de={sharpness:1,exposure:1,meanLuma:128};function Ve(o,e){return e.width=o.videoWidth,e.height=o.videoHeight,e.getContext("2d").drawImage(o,0,0),new Promise((t,r)=>e.toBlob(i=>i?t(i):r(new Error("empty-keyframe")),"image/jpeg",.92))}function Fe(){return N()==="phone"}var pe=class{constructor(e){this.handlers=new Map;this.stateValue="idle";this.attempt=0;this.stream=null;this.detector=null;this.scheduler=null;this.gate=null;this.profiler=null;this.lastGuidanceKey=null;this.positioningStartedAt=0;this.cameraRequestedAt=null;this.cameraReadyAt=null;this.faceAcquiredAt=null;this.captureCompleteAt=null;this.fired=!1;this.carriedDegrade=0;this.carriedMeans=[];this.blockStats=null;this.lastGateSnapshotAt=Number.NEGATIVE_INFINITY;this.uprightGuard=!1;this.trackProvenance=null;this.ramp=null;this.snapshotCanvas=null;this.options=e,this.facing=e.facingMode??"user"}get state(){return this.stateValue}on(e,t){let r=this.handlers.get(e);return r||(r=new Set,this.handlers.set(e,r)),r.add(t),()=>r?.delete(t)}emit(e,t){for(let r of[...this.handlers.get(e)??[]])r(t)}async start(e={}){e.facingMode!==void 0&&(this.facing=e.facingMode),this.attempt+=1,await this.run(this.attempt)}get facingMode(){return this.facing}retry(){this.teardownAttempt(),this.start()}switchCamera(){this.facing=this.facing==="user"?"environment":"user",this.teardownAttempt(),this.start()}destroy(){this.attempt+=1,this.teardownAttempt(),this.detector?.destroy(),this.detector=null,this.options.video.srcObject=null}async run(e){let{options:t}=this;this.fired=!1,this.lastGuidanceKey=null,this.carriedDegrade=0,this.carriedMeans=[],this.cameraRequestedAt=null,this.cameraReadyAt=null,this.faceAcquiredAt=null,this.captureCompleteAt=null,this.uprightGuard=(t.isPhone??Fe)(),this.setState("preflight");let r=W();if(r!=="OK"){this.fail(r==="INSECURE_CONTEXT"?"insecure":"unsupported",{phase:"preflight"});return}this.setState("acquiring");let i=t.getUserMedia??(u=>navigator.mediaDevices.getUserMedia(u)),n;this.cameraRequestedAt=this.now();try{n=await i(F(H(),this.facing))}catch(u){if(e!==this.attempt)return;this.fail(q(u),{phase:"acquiring",name:k(u)});return}if(X(n),Z(n),e!==this.attempt){for(let u of n.getTracks())u.stop();return}this.stream=n;let a=n.getVideoTracks?.()[0];if(this.trackProvenance=a===void 0?null:ce(a).catch(()=>null),this.facing=U(n)??this.facing,t.video.srcObject=n,await t.video.play().catch(()=>{}),e!==this.attempt)return;if(this.cameraReadyAt=this.now(),this.detector===null){let u={v3AssetBaseUrl:t.v3AssetBaseUrl},c=t.createDetector??(t.createWorker!==void 0&&j()?async()=>{try{return await $.create(t.createWorker(),u)}catch{return w(u)}}:()=>w(u)),l;try{l=await c()}catch(f){e===this.attempt&&this.fail("models",{phase:"models",name:k(f)},f instanceof Q?f.fallbackReason:He(f));return}if(e!==this.attempt){l.destroy();return}this.detector=l,this.options.telemetry?.({type:"detector",tier:l.tier,fallbackReason:l.fallbackReason})}let s=J(),d=t.deviceClass??ee(s);this.profiler=new te(d),this.options.telemetry?.({type:"profile",staticClass:d,activeClass:this.profiler.deviceClass,simd:s.simd}),this.gate=new M(t.thresholds??{}),this.blockStats=new _,this.lastGateSnapshotAt=this.now(),t.rankKeyframes?.()&&import("./keyframe-rank-YAJLYJYF.js").then(u=>V=u,()=>{}),this.setState("positioning"),this.positioningStartedAt=this.now(),this.startScheduler(e)}get animations(){return this.profiler?.profile.animations??"full"}startScheduler(e){let t=this.profiler;if(t===null)return;if(this.scheduler!==null){let i=this.scheduler.stats();this.carriedDegrade+=i.degradeCount,i.meanDetectMs>0&&this.carriedMeans.push(i.meanDetectMs),this.scheduler.stop()}let r=new I({cadenceHz:t.profile.cadenceHz,video:this.options.video,now:this.options.now,run:()=>this.detectTick(e)});this.scheduler=r,r.start()}async detectTick(e){let{detector:t,gate:r,profiler:i}=this,n=this.options.video;if(e!==this.attempt||t===null||r===null||i===null||this.fired||n.videoWidth===0)return;if(this.isLandscape()){this.holdUpright(e);return}let a=i.deviceClass,s=this.now(),d=this.options.makeSnapshot?.(n,i.profile.inputWidth)??this.defaultSnapshot(n,i.profile.inputWidth),u=null;try{u=await t.detect(d,n.videoWidth,n.videoHeight)}catch{u=null}if(e!==this.attempt||this.fired)return;i.record(this.now()-s),i.deviceClass!==a&&this.startScheduler(e);let c=u===null?de:this.options.measureQuality?.(n,u.box)??this.defaultQuality(n,u.box),l=r.tick({timestampMs:this.now(),observation:u,quality:c,frameWidth:n.videoWidth,frameHeight:n.videoHeight});l.accepted&&this.faceAcquiredAt===null&&(this.faceAcquiredAt=l.at),this.blockStats?.record(l),!l.ready&&l.at-this.lastGateSnapshotAt>=xe&&(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:t}=this,r=this.scheduler;r?.stop(),this.reportGate(!0);let i=r?.stats()??{degradeCount:0,meanDetectMs:0},n=[...this.carriedMeans,...i.meanDetectMs>0?[i.meanDetectMs]:[]];t.telemetry?.({type:"fired",timeToGateMs:this.now()-this.positioningStartedAt,degradeCount:this.carriedDegrade+i.degradeCount,meanDetectMs:n.length===0?0:n.reduce((g,y)=>g+y,0)/n.length});let a=t.mode??"clip",s=t.rankKeyframes?.()&&V?V.default(this,e).catch(()=>this.collectKeyframes(e)):this.collectKeyframes(e);if(a==="photo"){let g=this.watchRotation(e,null),y=await s;if(g(),e!==this.attempt)return;if(y===null){this.fail("generic",{phase:"keyframes"});return}let ve=await this.provenance({n:0,meanGapMs:0,stdGapMs:0,captureLatencyMs:null},!1);if(e!==this.attempt)return;this.finishCapture({keyframe:y.blob,previewDataUrl:y.previewDataUrl,...ve});return}this.setState("recording");let d=t.createRecorder?.()??new A,u=this.stream;if(u===null){this.fail("generic",{phase:"recording"});return}let c=le(t.video),l=t.screenRamp?.(),f=l!==void 0,h=ae(l,{paint:g=>{(g===null||e===this.attempt)&&this.emit("ramp",{colour:g})},now:()=>this.now(),frames:c.latest});this.ramp=h;let p=()=>{c.stop(),h.stop(),this.ramp===h&&(this.ramp=null)},m=this.watchRotation(e,d),v=null;s.then(g=>{v=g},()=>{});let E=()=>{e===this.attempt&&v!==null&&this.emit("frozen",{previewDataUrl:v.previewDataUrl})},C,T;try{[C,T]=await Promise.all([d.record(u,E,()=>h.started(this.now())),s])}catch(g){if(m(),p(),e!==this.attempt)return;let y=g.kind;this.fail(y==="cliptoolarge"?"cliptoolarge":"recorder",{phase:"recording",name:k(g)});return}m();let me=c.stats();if(p(),e!==this.attempt)return;if(R(C.blob)){this.fail("cliptoolarge",{phase:"recording"});return}if(T===null){this.fail("generic",{phase:"keyframes"});return}let D=h.report(),fe=await this.provenance(me,f);e===this.attempt&&this.finishCapture({clip:C.blob,clipMimeType:C.mimeType,keyframe:T.blob,previewDataUrl:T.previewDataUrl,...D!==void 0&&D.rendered.length>0?{screenRamp:D}:{},...fe})}async provenance(e,t){let r=this.trackProvenance;if(r===null)return{};let i,n=new Promise(s=>{i=setTimeout(()=>s(null),Le)}),a=await Promise.race([r,n]);return clearTimeout(i),a===null?{}:{provenance:ue(a,e,t)}}isLandscape(){let e=this.options.video;return this.uprightGuard&&e.videoWidth>e.videoHeight}holdUpright(e){this.gate?.reset(),this.emit("checks",{engine:"v3",progress:0,q:0,factors:{presence:0,centering:0,size:0,pose:0,sharpness:0,exposure:0,motion:0},attempt:e}),this.lastGuidanceKey!==G&&(this.lastGuidanceKey=G,this.emit("guidance",{key:G}))}watchRotation(e,t){if(!this.uprightGuard)return()=>{};let r=this.options.video,i=()=>{if(e!==this.attempt||t!==null&&this.stateValue!=="recording"){s();return}r.videoWidth>0&&this.isLandscape()&&(s(),this.abortRecording(e,t))},n=setInterval(i,Pe);r.addEventListener?.("resize",i);let a=!1;function s(){a||(a=!0,clearInterval(n),r.removeEventListener?.("resize",i))}return s}abortRecording(e,t){if(e!==this.attempt)return;this.attempt+=1;let r=this.attempt;try{t?.stop()}catch{}this.ramp?.stop(),this.ramp=null,this.fired=!1,this.captureCompleteAt=null,this.gate=new M(this.options.thresholds??{}),this.blockStats=new _,this.lastGateSnapshotAt=this.now(),this.lastGuidanceKey=null,this.setState("positioning"),this.positioningStartedAt=this.now(),this.holdUpright(r),this.startScheduler(r)}async collectKeyframes(e){let t=this.options.captureKeyframe??(n=>this.defaultKeyframe(n)),r=Ge/(L-1),i=null;for(let n=0;n<L;n+=1){if(e!==this.attempt)return i;try{let a=await t(this.options.video);(i===null||a.sharpness>i.sharpness)&&(i=a)}catch{}n<L-1&&await Ne(r)}return i}finishCapture(e){this.stopTracks(),this.setState("captured");let t=this.captureTiming();this.emit("artifacts",t===void 0?e:{...e,timing:t})}captureTiming(){let e={},t=(r,i,n)=>{i!==null&&n!==null&&(e[r]=Math.max(0,Math.round(n-i)))};return t("cameraReadyMs",this.cameraRequestedAt,this.cameraReadyAt),t("faceAcquireMs",this.cameraReadyAt,this.faceAcquiredAt),t("captureMs",this.faceAcquiredAt,this.captureCompleteAt),Object.keys(e).length>0?e:void 0}async defaultKeyframe(e){let t=document.createElement("canvas"),r=await(this.facing==="user"?se:Ve)(e,t),i=t.toDataURL("image/jpeg",.92);return{blob:r,previewDataUrl:i,sharpness:this.centerSharpness(e)}}defaultSnapshot(e,t){try{let r=this.snapshotCanvas??document.createElement("canvas"),i=t/Math.max(1,e.videoWidth),n=Math.max(1,Math.round(e.videoWidth*i)),a=Math.max(1,Math.round(e.videoHeight*i)),s=r.getContext("2d");return s===null?e:(r.width!==n&&(r.width=n),r.height!==a&&(r.height=a),s.drawImage(e,0,0,n,a),this.snapshotCanvas=r,r)}catch{return e}}defaultQuality(e,t){let r=he(e,t,96);return r===null?de:{sharpness:x(r),exposure:ie(r),meanLuma:re(r)}}centerSharpness(e){let t=Y(e),r=he(e,{x:t.width*.25,y:t.height*.25,width:t.width*.5,height:t.height*.5},96);return r===null?0:x(r)}teardownAttempt(){this.scheduler?.stop(),this.scheduler=null,this.reportGate(!0),this.gate=null,this.ramp?.stop(),this.ramp=null,this.stopTracks()}reportGate(e){let t=this.blockStats,r=this.profiler;if(t===null||r===null)return;let i=t.summary();e&&(this.blockStats=null),i.ticks!==0&&this.options.telemetry?.({type:"gate",final:e,activeClass:r.deviceClass,cadenceHz:r.profile.cadenceHz,...i})}stopTracks(){if(this.stream!==null){for(let e of this.stream.getTracks())e.stop();this.stream=null}}fail(e,t,r){this.scheduler?.stop(),this.reportGate(!0),this.stopTracks(),this.setState("error"),this.options.telemetry?.({type:"error",kind:e,fallbackReason:r});let{phase:i,name:n}=t;this.emit("error",{kind:e,retryable:e!=="insecure"&&e!=="unsupported",detail:n===void 0?{phase:i}:{phase:i,name:n}})}setState(e){this.stateValue=e,this.emit("statechange",{state:e})}now(){return this.options.now?.()??performance.now()}},V;function Ne(o){return new Promise(e=>setTimeout(e,o))}function He(o){return o instanceof Error?o.message:String(o)}function he(o,e,t){try{let r=document.createElement("canvas"),i=t/Math.max(1,e.width);r.width=Math.max(1,Math.round(e.width*i)),r.height=Math.max(1,Math.round(e.height*i));let n=r.getContext("2d");return n===null?null:(n.drawImage(o,e.x,e.y,e.width,e.height,0,0,r.width,r.height),n.getImageData(0,0,r.width,r.height))}catch{return null}}export{ge as a,be as b,ye as c,ne as d,b as e,A as f,Be as g,We as h,Se as i,ze as j,se as k,I as l,Te as m,M as n,ke as o,_ as p,xe as q,G as r,Pe as s,L as t,Ge as u,Le as v,pe as w};
@@ -0,0 +1 @@
1
+ import{a as f,c as y}from"./chunk-VIAT4DEA.js";var S=["session_token_invalid","session_token_required","session_token_session_mismatch","session_not_found","rate_limit_exceeded","consent_required","session_not_active","check_not_found","check_already_finalized","check_out_of_order","check_type_unsupported","force_outcome_forbidden","attestation_invalid","platform_unregistered","app_attest_invalid","too_many_challenges","inference_unavailable","mobile_required","nni_locked","document_nni_mismatch","media_content_type_not_allowed","media_too_large","media_key_invalid","media_key_forbidden","media_not_found","media_unreadable","media_session_invalid","idempotency_key_collision","idempotency_in_progress","idempotency_key_required","validation_error","internal_error","unknown_error","upload_failed","network_error","timeout","nfc_outcome_not_accepted","identity_confirm_required","identity_confirm_locked","choice_not_found","choice_locked","choice_option_unavailable","step_not_on_path","check_not_active","sekyro_app_not_allowed","sekyro_app_unverified","id_number_locked","document_id_number_mismatch","simulated_capture_forbidden"];function x(s){return S.includes(s)}var c=class extends Error{constructor(e){super(e.message),this.name="HostedApiError",this.status=e.status,this.code=e.code,e.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=e.retryAfterSeconds),e.details&&(this.details=e.details)}};function _(s,e,n=Math.random){let t=(s??e)*1e3,i=Math.min(Math.max(t,500),2e4),o=Math.round(i*(1+(n()*2-1)*.25));return Math.min(Math.max(o,500),2e4)}var w=6e4,h=4,k=3e4,R=9e5,I=200,E=5,P=400,M=new Set(["server_busy","request_timeout"]),C=2;function l(s){return(s.split(";")[0]??"").trim()}var A={liveness:"clipKey",face_match:"imageKey",doc_ocr:"imageKey"},v=`@sekyro/web/${f}`,O=v,b=class{constructor(e){this.sessionId=null;this.bootstrap=null;this.captureNonces=[];this.captureFetch=null;this.reportedIssues=new Map;this.apiOrigin=e.apiOrigin.replace(/\/+$/,""),this.sessionToken=e.sessionToken;let n=e.fetch;this.fetchImpl=(t,i)=>(n??globalThis.fetch).call(globalThis,t,i),this.requestTimeoutMs=e.requestTimeoutMs??k,this.retryAttempts=e.inProgressRetry?.attempts??E,this.retryDelayMs=e.inProgressRetry?.delayMs??P,this.random=e.random??Math.random}async getSession(){let e=await this.api("GET","/hosted/session");return this.sessionId=e.sessionId,e}async recordConsent(e){return this.api("POST","/hosted/consent",{body:{locale:e},busyRetry:!0})}async reportCameraUnavailable(e){return this.api("POST","/hosted/camera-unavailable",{body:{cause:e}})}async reportCaptureIssue(e){let n=typeof e.name=="string"?e.name.replace(/[^A-Za-z]/g,"").slice(0,40):"",t=typeof e.engineKind=="string"&&/^[a-z_]{1,32}$/.test(e.engineKind)?e.engineKind:void 0,i=typeof e.attempt=="number"&&Number.isInteger(e.attempt)&&e.attempt>=0&&e.attempt<=1e3?e.attempt:void 0,o=[e.check,i??"",e.kind,n,e.phase??""].join("|"),a=this.reportedIssues.get(o);if(a!==void 0)return a;let d={check:e.check,kind:e.kind,...n!==""?{name:n}:{},...e.phase!==void 0?{phase:e.phase}:{},...t!==void 0?{engineKind:t}:{},...i!==void 0?{attempt:i}:{},...e.formFactor!==void 0?{formFactor:e.formFactor}:{}},r=this.api("POST","/hosted/capture-issue",{body:d,empty:!0}).catch(()=>{this.reportedIssues.delete(o)});return this.reportedIssues.set(o,r),r}async choose(e,n){let t=await this.api("POST","/hosted/choice",{body:{nodeId:e,option:n},busyRetry:!0});return this.sessionId=t.sessionId,t}async confirmIdentity(e){return this.api("POST","/hosted/identity/confirm",{body:{decision:e}})}async identityPortrait(){return this.api("GET","/hosted/identity/portrait",{blob:!0})}async presign(e,n,t,i={}){let o=await this.ensureSessionId(),a={kind:e,contentType:l(n),contentLength:t,...i.source==="upload"?{source:"upload"}:{}};return this.api("POST",`/sessions/${o}/media`,{body:a})}armCapture(e=2){this.fillCaptureNonces(e)}async presignCapture(e,n,t,i={}){let o=await this.ensureSessionId(),a=await this.takeCaptureNonce(),d=a===void 0?void 0:{nonce:a,...i.engine!==void 0?{engine:i.engine.slice(0,32)}:{},...i.durationMs!==void 0&&Number.isFinite(i.durationMs)?{captureMs:Math.min(36e5,Math.max(0,Math.round(i.durationMs)))}:{}},r={kind:e,contentType:l(n),contentLength:t,capture:d};return this.api("POST",`/sessions/${o}/media`,{body:r})}async takeCaptureNonce(){let e=()=>{let n=Date.now();return this.captureNonces=this.captureNonces.filter(t=>t.expiresAt-w>n),this.captureNonces.shift()?.nonce};for(let n=0;n<2;n++){let t=e();if(t!==void 0)return t;await this.fillCaptureNonces(1)}return e()}fillCaptureNonces(e){return this.captureFetch??(this.captureFetch=(async()=>{try{let n=await this.ensureSessionId(),t=await this.api("POST",`/sessions/${n}/media/capture-nonces`,{body:{count:Math.min(h,Math.max(1,e))}}),i=Date.now()+Math.max(0,t.expiresIn)*1e3;for(let o of Array.isArray(t.nonces)?t.nonces:[])typeof o=="string"&&o.length>0&&this.captureNonces.push({nonce:o,expiresAt:i});this.captureNonces=this.captureNonces.slice(-h)}catch{}})().finally(()=>{this.captureFetch=null})),this.captureFetch}async uploadToSpaces(e,n,t){let i;try{i=await this.fetchImpl(e,{method:"PUT",headers:{"content-type":l(t)},body:n,signal:AbortSignal.timeout(R)})}catch(o){throw m(o)}if(!i.ok){let o=(await i.text().catch(()=>"")).slice(0,I);throw new c({status:i.status,code:"upload_failed",message:`media upload failed (HTTP ${i.status})${o?`: ${o}`:""}`})}}async completeMedia(e){let n=await this.ensureSessionId();return this.api("POST",`/sessions/${n}/media/complete`,{body:{key:e}})}async submitCheck(e,n,t={}){let i=await this.ensureSessionId(),o={input:n,forceOutcome:t.forceOutcome};return this.api("POST",`/sessions/${i}/checks/${e}`,{body:o,idempotencyKey:t.idempotencyKey,busyRetry:t.idempotencyKey!==void 0})}async uploadAndSubmit(e,n,t,i={}){let o=l(n.contentType),a=await this.presign(n.kind,o,n.blob.size);await this.uploadToSpaces(a.uploadUrl,n.blob,o);let d=await this.completeMedia(a.key),r={...t,[A[e]]:d.key};return this.submitCheck(e,r,i)}async ensureSessionId(){return this.sessionId!==null?this.sessionId:(this.bootstrap??(this.bootstrap=this.getSession().finally(()=>{this.bootstrap=null})),(await this.bootstrap).sessionId)}async api(e,n,t={}){let i=e==="GET"||t.busyRetry===!0,o=`${this.apiOrigin}/api/v2${n}`,a={"x-session-token":this.sessionToken,"x-sekyro-sdk":O};t.body!==void 0&&(a["content-type"]="application/json"),t.idempotencyKey!==void 0&&(a["x-idempotency-key"]=t.idempotencyKey);try{let d=y.timezone();d!==void 0&&(a["sekyro-client-timezone"]=d)}catch{}try{let d=await y.deviceHeader();d!==void 0&&(a["sekyro-client-device"]=d)}catch{}for(let d=0;;d++){let r;try{r=await this.fetchImpl(o,{method:e,headers:a,...t.body!==void 0?{body:JSON.stringify(t.body)}:{},cache:"no-store",signal:AbortSignal.timeout(this.requestTimeoutMs)})}catch(p){throw m(p)}if(r.ok){if(t.empty===!0)return;if(t.blob===!0)try{return await r.blob()}catch(T){throw m(T)}let p;try{p=await r.json()}catch{throw new c({status:r.status,code:"unknown_error",message:`response body was not valid JSON (HTTP ${r.status})`})}return N(p)}let u=await H(r);if(u.code==="idempotency_in_progress"&&d<this.retryAttempts){this.retryDelayMs>0&&await g(this.retryDelayMs);continue}if(i&&u.status===503&&M.has(u.code)){i=!1,await g(_(u.retryAfterSeconds,C,this.random));continue}throw u}}};function m(s){if((typeof s=="object"&&s!==null?s.name:void 0)==="TimeoutError")return new c({status:0,code:"timeout",message:"request timed out"});let n=s instanceof Error?s.message:String(s);return new c({status:0,code:"network_error",message:`network request failed: ${n}`})}function N(s){return s!==null&&typeof s=="object"&&"success"in s&&"data"in s?s.data:s}async function H(s){let e="unknown_error",n=`request failed (HTTP ${s.status})`,t=Number.NaN,i;try{let d=await s.json();if(d!==null&&typeof d=="object"){let r=d;typeof r.code=="string"&&r.code.length>0&&(e=r.code),typeof r.message=="string"&&r.message.length>0&&(n=r.message),typeof r.retryAfterSeconds=="number"&&(t=r.retryAfterSeconds),Array.isArray(r.details?.issues)&&(i=r.details)}}catch{}let o=s.headers.get("retry-after"),a=o===null?Math.floor(t):Number.parseInt(o,10);return new c({status:s.status,code:e,message:n,...Number.isFinite(a)&&a>=0?{retryAfterSeconds:a}:{},details:i})}function g(s){return new Promise(e=>setTimeout(e,s))}function F(s){let e=s?.portrait,n=e?.icao,t=e?.purpose==="id_document";return n==null?t?{policy:"reject",profile:"id_document"}:null:{policy:n.policy==="alert"?"alert":"reject",profile:t||n.profile==="id_document"?"id_document":"selfie"}}function L(s){return{...s.baselineEyeOpenness!==void 0?{baselineEyeOpenness:s.baselineEyeOpenness}:{},...s.baselineEyeOpennessLeft!==void 0&&s.baselineEyeOpennessRight!==void 0?{baselineEyeOpennessLeft:s.baselineEyeOpennessLeft,baselineEyeOpennessRight:s.baselineEyeOpennessRight}:{},criteria:s.verdict??{},...s.backgroundCheck!==void 0?{backgroundCheck:s.backgroundCheck}:{}}}export{S as a,x as b,c,_ as d,l as e,v as f,b as g,F as h,L as i};
@@ -1 +1 @@
1
- import{c as v,d as V,e as A}from"./chunk-NJML6FMD.js";var j=new Set(["nni_unbound","id_number_unbound","method_required","mobile_required","portrait_required"]);function we(e){return j.has(e)}function be(e,n,t){let i=n.detail;return{check:e,kind:n.kind,...i?.name!==void 0?{name:i.name}:{},...i?.phase!==void 0?{phase:i.phase}:{},...i?.engineKind!==void 0?{engineKind:i.engineKind}:{},attempt:Math.max(0,Math.min(1e3,t))}}function ke(){let e=-1,n="";return{note(t){t==="starting"&&n!=="starting"&&(e+=1),n=t},newHandle(){n=""},noteError(){e<0&&(e=0)},get value(){return e}}}var H=Object.freeze({nni_invalid:"id_number_invalid",nni_not_found:"registry_record_not_found",nni_recheck:"id_number_recheck",document_nni_mismatch:"document_id_number_mismatch",nni_locked:"id_number_locked",nni_unbound:"id_number_unbound",sandbox_nni_not_seeded:"sandbox_id_number_not_seeded",missing_nni:"missing_id_number",registry_needs_nni_source:"registry_needs_id_number_source"}),I=new Map(Object.entries(H)),$=new Map(Object.entries(H).map(([e,n])=>[n,e]));function ve(e){return I.get(e)??e}function z(e){let n=I.get(e)??$.get(e);return n===void 0?[e]:[e,n]}function T(e){let n=[];for(let t of e)for(let i of z(t))n.includes(i)||n.push(i);return n}var W=new Set(T(["no_face","media_unreadable","clip_too_short","no_face_source","side_missing","unreadable","registry_unavailable","otp_mismatch","otp_expired","otp_send_failed","document_type_not_accepted","age_unverifiable","nationality_unreadable","liveness_inconclusive","match_inconclusive","document_authenticity","probe_not_from_liveness","capture_back_camera","capture_not_upright","chip_read_failed","chip_access_denied","chip_parse_failed","icao_pose","icao_eyes","icao_mouth","icao_occlusion","icao_lighting","icao_background","icao_resolution","portrait_not_from_liveness","nni_recheck","device_integrity_failed","eid_identifier_invalid","eid_code_invalid","eid_code_expired","eid_unavailable","eid_resend_too_soon"])),X={document:"document_photo",nfc:"document_chip",population_registry:"national_number",national_eid:"national_eid"};function p(e){return e.plan?.steps??[]}function O(e){return Math.max(0,e.attempts.max-e.attempts.used)}function G(e){let n=e.plan?.choice;return n!==void 0&&e.plan?.current===n.nodeId?n:null}function Me(e){let n=G(e);if(n?.kind!=="identity_method")return null;let t=n.options.map(o=>X[o.service]).filter(o=>o!==void 0),i=n.options.find(o=>o.nationalEid)?.nationalEid;return i?{available:!0,selected:null,options:t,nationalEid:i}:{available:!0,selected:null,options:t}}var J=new Set(["liveness","face_match"]);function x(e){return e!==void 0&&(e.state==="pending"||e.state==="input_required")}function L(e){return e.status!=="created"&&e.status!=="in_progress"}function E(e){let n=e.plan?.current,t=n==null?void 0:p(e).find(i=>i.id===n);return x(t)?t:void 0}function y(e,n){return p(e).find(t=>t.checkType===n)}function g(e){let n=p(e),t=n.findIndex(i=>i.checkType==="liveness");return n.find((i,o)=>o>t&&i.checkType==="face_match")}function N(e,n){let t=y(n,"liveness")?.state,i=g(n)?.state;return(g(e)?.state??"pending")==="pending"&&(t==="passed"||t==="review")&&i!==void 0&&i!=="pending"&&i!=="skipped"}function M(e,n){let t=new Map(p(e).map(i=>[i.id,i.state]));return p(n).filter(i=>i.checkType==="face_match"&&(t.get(i.id)??"pending")==="pending"&&i.state!=="pending"&&i.state!=="skipped").map(i=>i.id)}var Q=/^[0-9a-f]{24}$/i;function b(e){return Q.test(e)?`ses_${e}`:e}function w(e,n){let t=b(e);return n===void 0?{sessionId:t,status:"unavailable"}:{sessionId:t,status:"unavailable",reason:n}}function _(e,n,t){let i=b(e);return t===void 0?{sessionId:i,status:n}:{sessionId:i,status:n,reason:t}}function Pe(e,n){let{sessionId:t}=e;switch(e.status){case"completed":case"failed":case"review_pending":return ee(e,ne(e));case"expired":return w(t);case"created":case"in_progress":break;default:{let i=e.status;throw new Error(`mapSessionResult: unhandled status ${i}`)}}return ie(e,n)}var Z=new Set([0,1,2,3]);function ee(e,n){return Z.has(e.level)&&(n.level=e.level),typeof e.assurance=="string"&&e.assurance.length>0&&(n.assurance=e.assurance),n}function ne(e){let n=b(e.sessionId);switch(e.status){case"completed":return e.outcome==="approved"?{sessionId:n,status:"approved"}:e.outcome==="review"?_(n,"review",h(e,"review")):_(n,"rejected",h(e,"failed"));case"failed":{let t=_(n,"rejected",e.failureReason??h(e,"failed"));return e.failureReason==="device_cooldown"&&e.retryAfter!==void 0&&(t.retryAfter=e.retryAfter),t}default:return _(n,"review",h(e,"review"))}}function te(e,n){if(n===void 0)return!1;let t=p(n).find(i=>i.id===e.id);return t!==void 0&&t.attempts.used===e.attempts.used}function ie(e,n){let t=b(e.sessionId),i=p(e).find(s=>J.has(s.checkType)&&s.state==="input_required"&&s.reason!==void 0);if(i?.reason==="mobile_required")return w(t,"mobile_required");if(i?.reason!==void 0){let s=n.autoRetry&&O(i)>0&&(W.has(i.reason)||te(i,n.previous)),d={sessionId:t,status:s?"retry":"rejected",reason:i.reason,attemptsRemaining:O(i)};return i.retakeHint!==void 0&&(d.retakeHint=i.retakeHint),d}let o=E(e);return o===void 0&&p(e).some(s=>s.state==="review")?_(t,"review",h(e,"review")):o?.checkType==="portrait_icao"?w(t,"portrait_required"):w(t)}function h(e,n){let t=p(e).filter(i=>i.state===n&&i.reason!==void 0);return t[n==="failed"?t.length-1:0]?.reason}function K(e,n,t,i,o){return e.presignCapture!==void 0?e.presignCapture(n,t,i,o):e.presign(n,t,i)}function q(e){return{engine:e?.engine,durationMs:e?.clipMs}}var oe=["video/webm","video/mp4"],F="image/jpeg",se=2,re=1e3,ae=1e4,de=3,ue=10,ce=3,le=new Set(["network_error","timeout","upload_failed","unknown_error","rate_limit_exceeded"]),pe=new Set(["session_not_active","check_not_found","check_already_finalized","check_out_of_order","identity_confirm_required","check_not_active","step_not_on_path"]),S=class extends Error{constructor(){super("verification destroyed"),this.name="FlowCancelledError"}};function fe(e){let n=g(e);return y(e,"portrait_icao")?.state!=="pending"&&(n!==void 0?x(n):e.capture?.livePhoto?.oneCapture===!0)}var R=class extends Error{constructor(n){super(n),this.name="AttestationError"}};async function D(e,n,t={}){let i=e.uuid(),o=!1,s=!1,d=0,u=0;for(;;)try{return await n(e.client,i)}catch(r){if(r instanceof R){if(s)throw r;s=!0,t.onAttestationInvalid?.(),i=e.uuid();continue}if(!(r instanceof v))throw r;if(r.code==="consent_required"&&!o){o=!0,await e.ensureConsent({force:!0}),i=e.uuid();continue}if(r.code==="attestation_invalid"&&!s){s=!0,t.onAttestationInvalid?.(),i=e.uuid();continue}if(r.code==="inference_unavailable"&&u<de){u+=1;let a=V(r.retryAfterSeconds,ue,e.random??Math.random);e.onBusy?.({attempt:u,retryAfterSeconds:a/1e3}),await e.sleep(a),t.onAttestationInvalid?.(),i=e.uuid();continue}if(le.has(r.code)&&d<se){d+=1;let a=r.retryAfterSeconds!==void 0?r.retryAfterSeconds*1e3:void 0;await e.sleep(a!==void 0?Math.min(a,ae):re);continue}throw r}}var me=new Set(["passed","review","processing","skipped"]);async function Oe(e){let{artifacts:n}=e,t=n.clip,i=A(n.clipMime??"");if(n.degraded==="NO_RECORDER"||t===void 0||!oe.includes(i))return{kind:"unavailable",reason:"no_recorder"};e.client.armCapture?.(2);let o=_e(e,n.keyframe),s=he(e,t,i,o),d=ge(e,o),u=!1,r=new Set,a=!0,m=0;for(;;){if(e.isCancelled())return{kind:"cancelled"};let l=e.getView();if(L(l))return{kind:"settled"};let k=E(l),P=k?.checkType,C=P==="liveness"&&!u?"liveness":P==="face_match"&&!r.has(k?.id)&&r.size<2&&a?"face_match":null;if(C===null)return{kind:"settled"};if(C==="liveness"&&n.captureChannel==="desktop"&&y(l,"liveness")?.requiresMobile===!0)return{kind:"unavailable",reason:"mobile_required"};try{if(C==="liveness"){u=!0;let c=await s();if(e.isCancelled())return{kind:"cancelled"};N(l,c)&&r.add(g(c)?.id);for(let B of M(l,c))r.add(B);await e.applySubmit(c,"liveness");let f=y(e.getView(),"liveness")?.state;a=f===void 0||me.has(f)}else{r.add(k?.id);let c=await d();if(e.isCancelled())return{kind:"cancelled"};for(let f of M(l,c))r.add(f);await e.applySubmit(c,"face_match")}}catch(c){if(e.isCancelled()||c instanceof S)return{kind:"cancelled"};let f=Re(c);if(f.kind!=="resync"||m>=ce)return f;m+=1,await e.refreshView()}}}function _e(e,n){let t=null,i=null,o=()=>t!==null?Promise.resolve(t):(i??(i=(async()=>{let s=await K(e.client,"image",F,n.size,q(e.artifacts));return await e.client.uploadToSpaces(s.uploadUrl,n,F),t=(await e.client.completeMedia(s.key)).key,e.onKeyframePromoted?.(t),t})().finally(()=>{i=null})),i);return{ensure:o,attempt:()=>o().catch(()=>null),current:()=>t}}function he(e,n,t,i){let o=null,s,d=null;return()=>D(e,async(u,r)=>{if(o===null||s===void 0){if(e.isCancelled())throw new S;s===void 0&&!fe(e.getView())&&(s=null),e.onPhase("uploading");let[a,m]=await Promise.all([o!==null?Promise.resolve(o):(async()=>{let l=await K(u,"clip",t,n.size,q(e.artifacts));return await u.uploadToSpaces(l.uploadUrl,n,t),(await u.completeMedia(l.key)).key})(),s!==void 0?Promise.resolve(s===null?null:s.imageKey):i.attempt()]);o=a,s===void 0&&(s=m===null?null:{imageKey:m})}if(d===null)try{d=await e.getAttestation()}catch(a){throw new R(a instanceof Error?a.message:String(a))}return e.onPhase("checking"),u.submitCheck("liveness",{clipKey:o,attestation:d,captureChannel:e.artifacts.captureChannel,capture:ye(e.artifacts),...s!==null?{faceMatch:s}:{}},{idempotencyKey:r})},{onAttestationInvalid:()=>{d=null}})}function ge(e,n){return()=>D(e,async(t,i)=>{if(n.current()===null){if(e.isCancelled())throw new S;e.onPhase("uploading")}let o=await n.ensure();return e.onPhase("checking"),t.submitCheck("face_match",{imageKey:o},{idempotencyKey:i})})}function ye(e){let n={width:e.width,height:e.height};for(let t of Se)e[t]!==void 0&&(n[t]=e[t]);return n}var Se=["engine","facingMode","mode","formFactor","clipMs","cameraReadyMs","faceAcquireMs","captureMs","screenRamp","provenance"];function Re(e){if(e instanceof R)return{kind:"unavailable",reason:"attestation"};if(e instanceof v){if(e.code==="attestation_invalid")return{kind:"unavailable",reason:"attestation"};if(e.code==="inference_unavailable")return{kind:"unavailable",reason:"inference_unavailable"};if(e.code==="mobile_required")return{kind:"unavailable",reason:"mobile_required"};if(pe.has(e.code))return{kind:"resync"}}return{kind:"unavailable",reason:"network"}}var U=class extends Error{constructor(n,t){super(`invalid ${n} (${t})`),this.name="InvalidInputError",this.field=n,this.kind=t}},Y=class extends Error{constructor(n,t){super(`invalid ${n} (${t})`),this.name="OtpInputError",this.field=n,this.kind=t}};function Fe(e){let n=e?.capture,t=n?.mode;return t==="assisted"||t==="self"||t==="choice"?t:n?.cameraSwitch===!0?"assisted":"self"}function Ke(e,n){return e==="choice"?n??"self":e}export{we as a,be as b,ke as c,Fe as d,Ke as e,ve as f,W as g,X as h,p as i,O as j,G as k,Me as l,x as m,L as n,E as o,y as p,b as q,w as r,Pe as s,K as t,oe as u,se as v,re as w,de as x,ue as y,R as z,D as A,Oe as B,U as C,Y as D};
1
+ import{c as v,d as V,e as A}from"./chunk-B2X33ZW2.js";var j=new Set(["nni_unbound","id_number_unbound","method_required","mobile_required","portrait_required"]);function we(e){return j.has(e)}function be(e,n,t){let i=n.detail;return{check:e,kind:n.kind,...i?.name!==void 0?{name:i.name}:{},...i?.phase!==void 0?{phase:i.phase}:{},...i?.engineKind!==void 0?{engineKind:i.engineKind}:{},attempt:Math.max(0,Math.min(1e3,t))}}function ke(){let e=-1,n="";return{note(t){t==="starting"&&n!=="starting"&&(e+=1),n=t},newHandle(){n=""},noteError(){e<0&&(e=0)},get value(){return e}}}var H=Object.freeze({nni_invalid:"id_number_invalid",nni_not_found:"registry_record_not_found",nni_recheck:"id_number_recheck",document_nni_mismatch:"document_id_number_mismatch",nni_locked:"id_number_locked",nni_unbound:"id_number_unbound",sandbox_nni_not_seeded:"sandbox_id_number_not_seeded",missing_nni:"missing_id_number",registry_needs_nni_source:"registry_needs_id_number_source"}),I=new Map(Object.entries(H)),$=new Map(Object.entries(H).map(([e,n])=>[n,e]));function ve(e){return I.get(e)??e}function z(e){let n=I.get(e)??$.get(e);return n===void 0?[e]:[e,n]}function T(e){let n=[];for(let t of e)for(let i of z(t))n.includes(i)||n.push(i);return n}var W=new Set(T(["no_face","media_unreadable","clip_too_short","no_face_source","side_missing","unreadable","registry_unavailable","otp_mismatch","otp_expired","otp_send_failed","document_type_not_accepted","age_unverifiable","nationality_unreadable","liveness_inconclusive","match_inconclusive","document_authenticity","probe_not_from_liveness","capture_back_camera","capture_not_upright","chip_read_failed","chip_access_denied","chip_parse_failed","icao_pose","icao_eyes","icao_mouth","icao_occlusion","icao_lighting","icao_background","icao_resolution","portrait_not_from_liveness","nni_recheck","device_integrity_failed","eid_identifier_invalid","eid_code_invalid","eid_code_expired","eid_unavailable","eid_resend_too_soon"])),X={document:"document_photo",nfc:"document_chip",population_registry:"national_number",national_eid:"national_eid"};function p(e){return e.plan?.steps??[]}function O(e){return Math.max(0,e.attempts.max-e.attempts.used)}function G(e){let n=e.plan?.choice;return n!==void 0&&e.plan?.current===n.nodeId?n:null}function Me(e){let n=G(e);if(n?.kind!=="identity_method")return null;let t=n.options.map(o=>X[o.service]).filter(o=>o!==void 0),i=n.options.find(o=>o.nationalEid)?.nationalEid;return i?{available:!0,selected:null,options:t,nationalEid:i}:{available:!0,selected:null,options:t}}var J=new Set(["liveness","face_match"]);function x(e){return e!==void 0&&(e.state==="pending"||e.state==="input_required")}function L(e){return e.status!=="created"&&e.status!=="in_progress"}function E(e){let n=e.plan?.current,t=n==null?void 0:p(e).find(i=>i.id===n);return x(t)?t:void 0}function y(e,n){return p(e).find(t=>t.checkType===n)}function g(e){let n=p(e),t=n.findIndex(i=>i.checkType==="liveness");return n.find((i,o)=>o>t&&i.checkType==="face_match")}function N(e,n){let t=y(n,"liveness")?.state,i=g(n)?.state;return(g(e)?.state??"pending")==="pending"&&(t==="passed"||t==="review")&&i!==void 0&&i!=="pending"&&i!=="skipped"}function M(e,n){let t=new Map(p(e).map(i=>[i.id,i.state]));return p(n).filter(i=>i.checkType==="face_match"&&(t.get(i.id)??"pending")==="pending"&&i.state!=="pending"&&i.state!=="skipped").map(i=>i.id)}var Q=/^[0-9a-f]{24}$/i;function b(e){return Q.test(e)?`ses_${e}`:e}function w(e,n){let t=b(e);return n===void 0?{sessionId:t,status:"unavailable"}:{sessionId:t,status:"unavailable",reason:n}}function _(e,n,t){let i=b(e);return t===void 0?{sessionId:i,status:n}:{sessionId:i,status:n,reason:t}}function Pe(e,n){let{sessionId:t}=e;switch(e.status){case"completed":case"failed":case"review_pending":return ee(e,ne(e));case"expired":return w(t);case"created":case"in_progress":break;default:{let i=e.status;throw new Error(`mapSessionResult: unhandled status ${i}`)}}return ie(e,n)}var Z=new Set([0,1,2,3]);function ee(e,n){return Z.has(e.level)&&(n.level=e.level),typeof e.assurance=="string"&&e.assurance.length>0&&(n.assurance=e.assurance),n}function ne(e){let n=b(e.sessionId);switch(e.status){case"completed":return e.outcome==="approved"?{sessionId:n,status:"approved"}:e.outcome==="review"?_(n,"review",h(e,"review")):_(n,"rejected",h(e,"failed"));case"failed":{let t=_(n,"rejected",e.failureReason??h(e,"failed"));return e.failureReason==="device_cooldown"&&e.retryAfter!==void 0&&(t.retryAfter=e.retryAfter),t}default:return _(n,"review",h(e,"review"))}}function te(e,n){if(n===void 0)return!1;let t=p(n).find(i=>i.id===e.id);return t!==void 0&&t.attempts.used===e.attempts.used}function ie(e,n){let t=b(e.sessionId),i=p(e).find(s=>J.has(s.checkType)&&s.state==="input_required"&&s.reason!==void 0);if(i?.reason==="mobile_required")return w(t,"mobile_required");if(i?.reason!==void 0){let s=n.autoRetry&&O(i)>0&&(W.has(i.reason)||te(i,n.previous)),d={sessionId:t,status:s?"retry":"rejected",reason:i.reason,attemptsRemaining:O(i)};return i.retakeHint!==void 0&&(d.retakeHint=i.retakeHint),d}let o=E(e);return o===void 0&&p(e).some(s=>s.state==="review")?_(t,"review",h(e,"review")):o?.checkType==="portrait_icao"?w(t,"portrait_required"):w(t)}function h(e,n){let t=p(e).filter(i=>i.state===n&&i.reason!==void 0);return t[n==="failed"?t.length-1:0]?.reason}function K(e,n,t,i,o){return e.presignCapture!==void 0?e.presignCapture(n,t,i,o):e.presign(n,t,i)}function q(e){return{engine:e?.engine,durationMs:e?.clipMs}}var oe=["video/webm","video/mp4"],F="image/jpeg",se=2,re=1e3,ae=1e4,de=3,ue=10,ce=3,le=new Set(["network_error","timeout","upload_failed","unknown_error","rate_limit_exceeded"]),pe=new Set(["session_not_active","check_not_found","check_already_finalized","check_out_of_order","identity_confirm_required","check_not_active","step_not_on_path"]),S=class extends Error{constructor(){super("verification destroyed"),this.name="FlowCancelledError"}};function fe(e){let n=g(e);return y(e,"portrait_icao")?.state!=="pending"&&(n!==void 0?x(n):e.capture?.livePhoto?.oneCapture===!0)}var R=class extends Error{constructor(n){super(n),this.name="AttestationError"}};async function D(e,n,t={}){let i=e.uuid(),o=!1,s=!1,d=0,u=0;for(;;)try{return await n(e.client,i)}catch(r){if(r instanceof R){if(s)throw r;s=!0,t.onAttestationInvalid?.(),i=e.uuid();continue}if(!(r instanceof v))throw r;if(r.code==="consent_required"&&!o){o=!0,await e.ensureConsent({force:!0}),i=e.uuid();continue}if(r.code==="attestation_invalid"&&!s){s=!0,t.onAttestationInvalid?.(),i=e.uuid();continue}if(r.code==="inference_unavailable"&&u<de){u+=1;let a=V(r.retryAfterSeconds,ue,e.random??Math.random);e.onBusy?.({attempt:u,retryAfterSeconds:a/1e3}),await e.sleep(a),t.onAttestationInvalid?.(),i=e.uuid();continue}if(le.has(r.code)&&d<se){d+=1;let a=r.retryAfterSeconds!==void 0?r.retryAfterSeconds*1e3:void 0;await e.sleep(a!==void 0?Math.min(a,ae):re);continue}throw r}}var me=new Set(["passed","review","processing","skipped"]);async function Oe(e){let{artifacts:n}=e,t=n.clip,i=A(n.clipMime??"");if(n.degraded==="NO_RECORDER"||t===void 0||!oe.includes(i))return{kind:"unavailable",reason:"no_recorder"};e.client.armCapture?.(2);let o=_e(e,n.keyframe),s=he(e,t,i,o),d=ge(e,o),u=!1,r=new Set,a=!0,m=0;for(;;){if(e.isCancelled())return{kind:"cancelled"};let l=e.getView();if(L(l))return{kind:"settled"};let k=E(l),P=k?.checkType,C=P==="liveness"&&!u?"liveness":P==="face_match"&&!r.has(k?.id)&&r.size<2&&a?"face_match":null;if(C===null)return{kind:"settled"};if(C==="liveness"&&n.captureChannel==="desktop"&&y(l,"liveness")?.requiresMobile===!0)return{kind:"unavailable",reason:"mobile_required"};try{if(C==="liveness"){u=!0;let c=await s();if(e.isCancelled())return{kind:"cancelled"};N(l,c)&&r.add(g(c)?.id);for(let B of M(l,c))r.add(B);await e.applySubmit(c,"liveness");let f=y(e.getView(),"liveness")?.state;a=f===void 0||me.has(f)}else{r.add(k?.id);let c=await d();if(e.isCancelled())return{kind:"cancelled"};for(let f of M(l,c))r.add(f);await e.applySubmit(c,"face_match")}}catch(c){if(e.isCancelled()||c instanceof S)return{kind:"cancelled"};let f=Re(c);if(f.kind!=="resync"||m>=ce)return f;m+=1,await e.refreshView()}}}function _e(e,n){let t=null,i=null,o=()=>t!==null?Promise.resolve(t):(i??(i=(async()=>{let s=await K(e.client,"image",F,n.size,q(e.artifacts));return await e.client.uploadToSpaces(s.uploadUrl,n,F),t=(await e.client.completeMedia(s.key)).key,e.onKeyframePromoted?.(t),t})().finally(()=>{i=null})),i);return{ensure:o,attempt:()=>o().catch(()=>null),current:()=>t}}function he(e,n,t,i){let o=null,s,d=null;return()=>D(e,async(u,r)=>{if(o===null||s===void 0){if(e.isCancelled())throw new S;s===void 0&&!fe(e.getView())&&(s=null),e.onPhase("uploading");let[a,m]=await Promise.all([o!==null?Promise.resolve(o):(async()=>{let l=await K(u,"clip",t,n.size,q(e.artifacts));return await u.uploadToSpaces(l.uploadUrl,n,t),(await u.completeMedia(l.key)).key})(),s!==void 0?Promise.resolve(s===null?null:s.imageKey):i.attempt()]);o=a,s===void 0&&(s=m===null?null:{imageKey:m})}if(d===null)try{d=await e.getAttestation()}catch(a){throw new R(a instanceof Error?a.message:String(a))}return e.onPhase("checking"),u.submitCheck("liveness",{clipKey:o,attestation:d,captureChannel:e.artifacts.captureChannel,capture:ye(e.artifacts),...s!==null?{faceMatch:s}:{}},{idempotencyKey:r})},{onAttestationInvalid:()=>{d=null}})}function ge(e,n){return()=>D(e,async(t,i)=>{if(n.current()===null){if(e.isCancelled())throw new S;e.onPhase("uploading")}let o=await n.ensure();return e.onPhase("checking"),t.submitCheck("face_match",{imageKey:o},{idempotencyKey:i})})}function ye(e){let n={width:e.width,height:e.height};for(let t of Se)e[t]!==void 0&&(n[t]=e[t]);return n}var Se=["engine","facingMode","mode","formFactor","clipMs","cameraReadyMs","faceAcquireMs","captureMs","screenRamp","provenance"];function Re(e){if(e instanceof R)return{kind:"unavailable",reason:"attestation"};if(e instanceof v){if(e.code==="attestation_invalid")return{kind:"unavailable",reason:"attestation"};if(e.code==="inference_unavailable")return{kind:"unavailable",reason:"inference_unavailable"};if(e.code==="mobile_required")return{kind:"unavailable",reason:"mobile_required"};if(pe.has(e.code))return{kind:"resync"}}return{kind:"unavailable",reason:"network"}}var U=class extends Error{constructor(n,t){super(`invalid ${n} (${t})`),this.name="InvalidInputError",this.field=n,this.kind=t}},Y=class extends Error{constructor(n,t){super(`invalid ${n} (${t})`),this.name="OtpInputError",this.field=n,this.kind=t}};function Fe(e){let n=e?.capture,t=n?.mode;return t==="assisted"||t==="self"||t==="choice"?t:n?.cameraSwitch===!0?"assisted":"self"}function Ke(e,n){return e==="choice"?n??"self":e}export{we as a,be as b,ke as c,Fe as d,Ke as e,ve as f,W as g,X as h,p as i,O as j,G as k,Me as l,x as m,L as n,E as o,y as p,b as q,w as r,Pe as s,K as t,oe as u,se as v,re as w,de as x,ue as y,R as z,D as A,Oe as B,U as C,Y as D};
@@ -1 +1 @@
1
- import{a as Z,d as j,e as J}from"./chunk-GT2ZLGF7.js";import{w as Q}from"./chunk-FGOVIGGL.js";import{c as q}from"./chunk-FUHDOEBP.js";import{f as G,l as N}from"./chunk-CQ7SKLMC.js";import{a as $,f as v}from"./chunk-OKWG3PVH.js";var se=12e4,X=13e4,oe=3e3,ie=1200,P=Symbol.for("@sekyro/web.preload.v1");function p(){let e=globalThis;return e[P]??(e[P]=new Map),e[P]}function g(e){let t=(e??$).replace(/\/+$/,"");return t===""?"/":t}function Y(e){let t=p(),r=t.get(e);return r===void 0&&(r={status:"idle",promise:null,scheduled:null,detectorPromise:null,detector:null,listeners:new Set},t.set(e,r)),r}function A(e,t){if(e.status!==t){e.status=t;for(let r of[...e.listeners])r(t)}}var T=e=>v({preferred:["blaze"],v3AssetBaseUrl:e,blazeInitTimeoutMs:se}),x=T;function Se(e){x=e??T}function Ce(){for(let e of p().values())e.detector?.destroy();p().clear(),x=T}function ae(){return typeof window<"u"&&typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"}function ce(){return navigator.connection?.saveData===!0}function de(e){let t=window;if(typeof t.requestIdleCallback=="function"){let s=t.requestIdleCallback(e,{timeout:oe});return()=>t.cancelIdleCallback?.(s)}let r=setTimeout(e,ie);return()=>clearTimeout(r)}function ue(e,t){let r,s=new Promise(o=>{r=o}),u=!1,f=()=>{},d={promise:s,settle:o=>{u||(u=!0,f(),e.scheduled===d&&(e.scheduled=null),r(o))}};return e.scheduled=d,f=de(()=>{u||d.settle(I(e,t))}),s}function I(e,t){if((e.status==="loading"||e.status==="ready")&&e.promise!==null)return e.promise;A(e,"loading");let r=new Promise(o=>o(x(t)));e.detectorPromise=r;let s,u=new Promise((o,h)=>{s=setTimeout(()=>{r.then(S=>S.destroy(),()=>{}),h(new Error(`detector preload exceeded ${X} ms`))},X)}),d=Promise.race([r,u]).then(o=>e.detectorPromise!==r?(o.destroy(),e.status):(e.detector=o,A(e,"ready"),"ready"),o=>(e.detectorPromise===r&&(e.detectorPromise=null,e.detector=null,A(e,"failed"),console.warn("[@sekyro/web] face-detector preload failed:",o)),e.status)).finally(()=>clearTimeout(s));return e.promise=d,e.scheduled?.settle(d),d}function Le(e={}){if(!ae())return Promise.resolve("idle");let t=g(e.assetBaseUrl),r=Y(t);return e.respectSaveData===!0&&ce()?Promise.resolve(r.status):(r.status==="loading"||r.status==="ready")&&r.promise!==null?r.promise:e.idle===!0?r.scheduled?.promise??ue(r,t):I(r,t)}function Ee(e){return p().get(g(e))?.status??"idle"}function ye(e,t){let r=Y(g(t));return r.listeners.add(e),()=>{r.listeners.delete(e)}}function be(e){let t=p().get(g(e));t!==void 0&&(t.scheduled?.settle("idle"),t.detector?.destroy(),t.detector=null,t.detectorPromise=null,t.promise=null,A(t,"idle"))}function le(e){return{get tier(){return e.tier},get fallbackReason(){return e.fallbackReason},detect:(...t)=>e.detect(...t),destroy:()=>{}}}function ee(e){let t=g(e),r=p().get(t);if(!(r===void 0||r.detector===null&&r.detectorPromise===null&&r.scheduled===null))return async()=>{r.scheduled!==null&&I(r,t);let s=r.promise;for(;r.detector===null&&s!==null&&(await s,r.promise!==s);)s=r.promise;return r.detector!==null?le(r.detector):v({v3AssetBaseUrl:t})}}function fe(e){switch(e){case"fcv3.no_face":case"fcv3.center_face":case"fcv3.straighten":return"center";case"fcv3.come_closer":return"closer";case"fcv3.move_back":return"farther";case"fcv3.more_light":case"fcv3.too_bright":return"light";case"fcv3.hold_still":case"fcv3.steady_camera":return"still";case"fcv3.hold_upright":return"upright";default:return null}}function pe(e){switch(e){case"preflight":case"acquiring":return"starting";case"positioning":return"gating";default:return e}}function te(e){switch(e){case"permission":case"notfound":case"inuse":case"insecure":case"unsupported":return e;default:{let t=e;return"generic"}}}function me(e,t,r){if(r===void 0)return{kind:te(e),retryable:t};let s=N(r.name);return{kind:te(e),retryable:t,detail:{...s!==void 0?{name:s}:{},phase:r.phase,engineKind:e}}}function ve(e,t={},r,s=()=>"self",u=()=>{}){let f=t.now??(()=>performance.now()),d=t.canChooseFacing??j,o="user",h=!1,S=n=>(n==="environment"&&!h&&(h=!0,console.warn('[@sekyro/web] facing "environment" ignored: this capture is a self capture (the person films themselves), which uses the front camera only. The back camera is for assisted capture, set in the flow.')),"user"),D=!1,m=s(),c=Z(),H=!G(),U=t.engineOptions,re=U?.createDetector===void 0&&U?.createWorker===void 0?{createDetector:()=>{let n=ee(e.assetBaseUrl);return n!==void 0?n():v({v3AssetBaseUrl:e.assetBaseUrl})}}:{},B={video:e.video,mode:H?"photo":"clip",rankKeyframes:r,facingMode:void 0,v3AssetBaseUrl:e.assetBaseUrl,screenRamp:()=>m==="self"&&c.count("ramp")>0?u():void 0,...t.engineOptions??{},...re},i=t.createEngine?.(B)??new Q(B),C="idle",L=null,E=0,k=!1,M="full",y=null,b=null,_=0,F=0,K=()=>{e.video.videoWidth>0&&e.video.videoHeight>0&&(_=e.video.videoWidth,F=e.video.videoHeight)},V=J({enabled:e.keepScreenAwake!==!1}),z=n=>{C=n,V.setActive(n==="starting"||n==="gating"||n==="recording"),c.emit("state",n)},O=()=>c.emit("gate",{progress:E,hint:L,faceDetected:k}),W=()=>{let n=i.animations??"full";n!==M&&(M=n,c.emit("profile",{animations:M}))},ne=[i.on("statechange",({state:n})=>{let a=pe(n);a==="starting"&&C!=="starting"&&(L=null,E=0,k=!1,y=null,b=null,_=0,F=0),z(a),W(),a==="recording"&&(K(),y=f(),L="hold",E=1,O())}),i.on("checks",n=>{K(),E=n.progress,k=n.factors.presence>0,O(),W()}),i.on("guidance",({key:n})=>{L=fe(n),O()}),i.on("frozen",({previewDataUrl:n})=>{b=f(),c.emit("frozen",{previewDataUrl:n})}),i.on("ramp",n=>c.emit("ramp",n)),i.on("artifacts",n=>{let a=q(),l=y!==null&&b!==null?Math.max(0,Math.round(b-y)):void 0;c.emit("captured",{keyframe:n.keyframe,...n.clip!==void 0?{clip:n.clip}:{},...n.clipMimeType!==void 0?{clipMime:n.clipMimeType}:{},width:e.video.videoWidth||_,height:e.video.videoHeight||F,...l!==void 0?{clipMs:l}:{},captureChannel:a==="desktop"?"desktop":"mobile",formFactor:a,...H?{degraded:"NO_RECORDER"}:{},engine:"v3",facingMode:i.facingMode,mode:m,...n.timing,...n.screenRamp!==void 0?{screenRamp:n.screenRamp}:{},...n.provenance!==void 0?{provenance:n.provenance}:{}})}),i.on("error",({kind:n,retryable:a,detail:l})=>{c.emit("error",me(n,a,l))})];return{handle:{get state(){return C},get captureMode(){return s()},get facingMode(){return i.facingMode??o},on:(n,a)=>c.on(n,a),start:n=>{if(m=s(),m==="self")return S(e.facing),S(n?.facing),D=!0,o="user",i.start({facingMode:"user"});let a=!D;D=!0;let l=n?.facing??(a?e.facing:void 0),R=w=>(o=w,i.start({facingMode:w}));return l!==void 0?R(l):a?d().then(w=>R(w?"environment":"user"),()=>R("user")):i.start({})},retry:()=>i.retry(),switchCamera:()=>s()!=="assisted"?!1:(m="assisted",o=o==="user"?"environment":"user",i.switchCamera(),!0),destroy:()=>{for(let n of ne)n();V.setActive(!1),i.destroy(),c.clear()}},setFlowState:n=>{C!==n&&z(n)}}}function Te(e){return ve(e).handle}export{se as a,X as b,Se as c,Ce as d,Le as e,Ee as f,ye as g,be as h,ee as i,fe as j,pe as k,te as l,me as m,ve as n,Te as o};
1
+ import{a as Z,d as j,e as J}from"./chunk-GT2ZLGF7.js";import{w as Q}from"./chunk-7Q4YPMAF.js";import{c as q}from"./chunk-FUHDOEBP.js";import{f as G,l as N}from"./chunk-CQ7SKLMC.js";import{a as $,f as v}from"./chunk-OKWG3PVH.js";var se=12e4,X=13e4,oe=3e3,ie=1200,P=Symbol.for("@sekyro/web.preload.v1");function p(){let e=globalThis;return e[P]??(e[P]=new Map),e[P]}function g(e){let t=(e??$).replace(/\/+$/,"");return t===""?"/":t}function Y(e){let t=p(),r=t.get(e);return r===void 0&&(r={status:"idle",promise:null,scheduled:null,detectorPromise:null,detector:null,listeners:new Set},t.set(e,r)),r}function A(e,t){if(e.status!==t){e.status=t;for(let r of[...e.listeners])r(t)}}var T=e=>v({preferred:["blaze"],v3AssetBaseUrl:e,blazeInitTimeoutMs:se}),x=T;function Se(e){x=e??T}function Ce(){for(let e of p().values())e.detector?.destroy();p().clear(),x=T}function ae(){return typeof window<"u"&&typeof navigator<"u"&&typeof navigator.mediaDevices?.getUserMedia=="function"}function ce(){return navigator.connection?.saveData===!0}function de(e){let t=window;if(typeof t.requestIdleCallback=="function"){let s=t.requestIdleCallback(e,{timeout:oe});return()=>t.cancelIdleCallback?.(s)}let r=setTimeout(e,ie);return()=>clearTimeout(r)}function ue(e,t){let r,s=new Promise(o=>{r=o}),u=!1,f=()=>{},d={promise:s,settle:o=>{u||(u=!0,f(),e.scheduled===d&&(e.scheduled=null),r(o))}};return e.scheduled=d,f=de(()=>{u||d.settle(I(e,t))}),s}function I(e,t){if((e.status==="loading"||e.status==="ready")&&e.promise!==null)return e.promise;A(e,"loading");let r=new Promise(o=>o(x(t)));e.detectorPromise=r;let s,u=new Promise((o,h)=>{s=setTimeout(()=>{r.then(S=>S.destroy(),()=>{}),h(new Error(`detector preload exceeded ${X} ms`))},X)}),d=Promise.race([r,u]).then(o=>e.detectorPromise!==r?(o.destroy(),e.status):(e.detector=o,A(e,"ready"),"ready"),o=>(e.detectorPromise===r&&(e.detectorPromise=null,e.detector=null,A(e,"failed"),console.warn("[@sekyro/web] face-detector preload failed:",o)),e.status)).finally(()=>clearTimeout(s));return e.promise=d,e.scheduled?.settle(d),d}function Le(e={}){if(!ae())return Promise.resolve("idle");let t=g(e.assetBaseUrl),r=Y(t);return e.respectSaveData===!0&&ce()?Promise.resolve(r.status):(r.status==="loading"||r.status==="ready")&&r.promise!==null?r.promise:e.idle===!0?r.scheduled?.promise??ue(r,t):I(r,t)}function Ee(e){return p().get(g(e))?.status??"idle"}function ye(e,t){let r=Y(g(t));return r.listeners.add(e),()=>{r.listeners.delete(e)}}function be(e){let t=p().get(g(e));t!==void 0&&(t.scheduled?.settle("idle"),t.detector?.destroy(),t.detector=null,t.detectorPromise=null,t.promise=null,A(t,"idle"))}function le(e){return{get tier(){return e.tier},get fallbackReason(){return e.fallbackReason},detect:(...t)=>e.detect(...t),destroy:()=>{}}}function ee(e){let t=g(e),r=p().get(t);if(!(r===void 0||r.detector===null&&r.detectorPromise===null&&r.scheduled===null))return async()=>{r.scheduled!==null&&I(r,t);let s=r.promise;for(;r.detector===null&&s!==null&&(await s,r.promise!==s);)s=r.promise;return r.detector!==null?le(r.detector):v({v3AssetBaseUrl:t})}}function fe(e){switch(e){case"fcv3.no_face":case"fcv3.center_face":case"fcv3.straighten":return"center";case"fcv3.come_closer":return"closer";case"fcv3.move_back":return"farther";case"fcv3.more_light":case"fcv3.too_bright":return"light";case"fcv3.hold_still":case"fcv3.steady_camera":return"still";case"fcv3.hold_upright":return"upright";default:return null}}function pe(e){switch(e){case"preflight":case"acquiring":return"starting";case"positioning":return"gating";default:return e}}function te(e){switch(e){case"permission":case"notfound":case"inuse":case"insecure":case"unsupported":return e;default:{let t=e;return"generic"}}}function me(e,t,r){if(r===void 0)return{kind:te(e),retryable:t};let s=N(r.name);return{kind:te(e),retryable:t,detail:{...s!==void 0?{name:s}:{},phase:r.phase,engineKind:e}}}function ve(e,t={},r,s=()=>"self",u=()=>{}){let f=t.now??(()=>performance.now()),d=t.canChooseFacing??j,o="user",h=!1,S=n=>(n==="environment"&&!h&&(h=!0,console.warn('[@sekyro/web] facing "environment" ignored: this capture is a self capture (the person films themselves), which uses the front camera only. The back camera is for assisted capture, set in the flow.')),"user"),D=!1,m=s(),c=Z(),H=!G(),U=t.engineOptions,re=U?.createDetector===void 0&&U?.createWorker===void 0?{createDetector:()=>{let n=ee(e.assetBaseUrl);return n!==void 0?n():v({v3AssetBaseUrl:e.assetBaseUrl})}}:{},B={video:e.video,mode:H?"photo":"clip",rankKeyframes:r,facingMode:void 0,v3AssetBaseUrl:e.assetBaseUrl,screenRamp:()=>m==="self"&&c.count("ramp")>0?u():void 0,...t.engineOptions??{},...re},i=t.createEngine?.(B)??new Q(B),C="idle",L=null,E=0,k=!1,M="full",y=null,b=null,_=0,F=0,K=()=>{e.video.videoWidth>0&&e.video.videoHeight>0&&(_=e.video.videoWidth,F=e.video.videoHeight)},V=J({enabled:e.keepScreenAwake!==!1}),z=n=>{C=n,V.setActive(n==="starting"||n==="gating"||n==="recording"),c.emit("state",n)},O=()=>c.emit("gate",{progress:E,hint:L,faceDetected:k}),W=()=>{let n=i.animations??"full";n!==M&&(M=n,c.emit("profile",{animations:M}))},ne=[i.on("statechange",({state:n})=>{let a=pe(n);a==="starting"&&C!=="starting"&&(L=null,E=0,k=!1,y=null,b=null,_=0,F=0),z(a),W(),a==="recording"&&(K(),y=f(),L="hold",E=1,O())}),i.on("checks",n=>{K(),E=n.progress,k=n.factors.presence>0,O(),W()}),i.on("guidance",({key:n})=>{L=fe(n),O()}),i.on("frozen",({previewDataUrl:n})=>{b=f(),c.emit("frozen",{previewDataUrl:n})}),i.on("ramp",n=>c.emit("ramp",n)),i.on("artifacts",n=>{let a=q(),l=y!==null&&b!==null?Math.max(0,Math.round(b-y)):void 0;c.emit("captured",{keyframe:n.keyframe,...n.clip!==void 0?{clip:n.clip}:{},...n.clipMimeType!==void 0?{clipMime:n.clipMimeType}:{},width:e.video.videoWidth||_,height:e.video.videoHeight||F,...l!==void 0?{clipMs:l}:{},captureChannel:a==="desktop"?"desktop":"mobile",formFactor:a,...H?{degraded:"NO_RECORDER"}:{},engine:"v3",facingMode:i.facingMode,mode:m,...n.timing,...n.screenRamp!==void 0?{screenRamp:n.screenRamp}:{},...n.provenance!==void 0?{provenance:n.provenance}:{}})}),i.on("error",({kind:n,retryable:a,detail:l})=>{c.emit("error",me(n,a,l))})];return{handle:{get state(){return C},get captureMode(){return s()},get facingMode(){return i.facingMode??o},on:(n,a)=>c.on(n,a),start:n=>{if(m=s(),m==="self")return S(e.facing),S(n?.facing),D=!0,o="user",i.start({facingMode:"user"});let a=!D;D=!0;let l=n?.facing??(a?e.facing:void 0),R=w=>(o=w,i.start({facingMode:w}));return l!==void 0?R(l):a?d().then(w=>R(w?"environment":"user"),()=>R("user")):i.start({})},retry:()=>i.retry(),switchCamera:()=>s()!=="assisted"?!1:(m="assisted",o=o==="user"?"environment":"user",i.switchCamera(),!0),destroy:()=>{for(let n of ne)n();V.setActive(!1),i.destroy(),c.clear()}},setFlowState:n=>{C!==n&&z(n)}}}function Te(e){return ve(e).handle}export{se as a,X as b,Se as c,Ce as d,Le as e,Ee as f,ye as g,be as h,ee as i,fe as j,pe as k,te as l,me as m,ve as n,Te as o};