@sekyro/web 0.1.0-rc.6 → 0.1.0-rc.8

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 (118) hide show
  1. package/CHANGELOG.md +114 -0
  2. package/LICENSE +25 -16
  3. package/README.md +6 -8
  4. package/THIRD-PARTY-NOTICES.txt +154 -0
  5. package/dist/background-monitor-A7FKJOAG.js +1 -0
  6. package/dist/capture-session-doc-YBE3UMJJ.js +1 -0
  7. package/dist/{capture-session-v3-Okq0EQHG.d.ts → capture-session-v3-CQK-G-qX.d.ts} +72 -3
  8. package/dist/{capture-session-v3-UQU_WjO2.d.cts → capture-session-v3-Dvob-uH2.d.cts} +72 -3
  9. package/dist/chunk-4RS2YIL4.js +1 -0
  10. package/dist/chunk-7V2M6Y2W.js +1 -0
  11. package/dist/chunk-7ZCZY3ZP.js +1 -0
  12. package/dist/chunk-A3FUGHAH.js +2 -0
  13. package/dist/chunk-BPE5NSQ2.js +1 -0
  14. package/dist/chunk-CJHMFPL6.js +1 -0
  15. package/dist/chunk-DFTCAWMP.js +1 -0
  16. package/dist/chunk-DK5YPBDQ.js +1 -0
  17. package/dist/chunk-DQWW4OCK.js +1 -0
  18. package/dist/chunk-FHJ7HO3M.js +1 -0
  19. package/dist/chunk-FPXL63KZ.js +1 -0
  20. package/dist/chunk-G6LKLN4U.js +1 -0
  21. package/dist/chunk-GI3UFGRQ.js +1 -0
  22. package/dist/chunk-LQ7C44JG.js +1 -0
  23. package/dist/chunk-M43ET4NJ.js +1 -0
  24. package/dist/chunk-MXWLCDFX.js +1 -0
  25. package/dist/chunk-MY6EXEL2.js +1 -0
  26. package/dist/chunk-O5WKNZ2C.js +1 -0
  27. package/dist/chunk-OKWG3PVH.js +1 -0
  28. package/dist/chunk-POIQGEZM.js +1 -0
  29. package/dist/chunk-RI3E7GBN.js +1 -0
  30. package/dist/chunk-RNRFHUJA.js +1 -0
  31. package/dist/chunk-RVHAKRAI.js +1 -0
  32. package/dist/chunk-SMKCBUJL.js +1 -0
  33. package/dist/chunk-SXZCL5NO.js +1 -0
  34. package/dist/chunk-TDLIXFDT.js +1 -0
  35. package/dist/chunk-XLN5OT25.js +1 -0
  36. package/dist/chunk-YDQBVWXG.js +1 -0
  37. package/dist/chunk-YPG7CB4O.js +1 -0
  38. package/dist/client/index.cjs +1 -357
  39. package/dist/client/index.d.cts +13 -3
  40. package/dist/client/index.d.ts +13 -3
  41. package/dist/client/index.js +1 -15
  42. package/dist/core/index.cjs +1 -1639
  43. package/dist/core/index.d.cts +3 -3
  44. package/dist/core/index.d.ts +3 -3
  45. package/dist/core/index.js +1 -139
  46. package/dist/core/ocr/worker.bundle.js +42 -0
  47. package/dist/core/ocr/worker.cjs +42 -0
  48. package/dist/core/ocr/worker.d.cts +84 -0
  49. package/dist/core/ocr/worker.d.ts +84 -0
  50. package/dist/core/ocr/worker.js +41 -0
  51. package/dist/core/v3/detect-worker.cjs +1 -392
  52. package/dist/core/v3/detect-worker.d.cts +1 -1
  53. package/dist/core/v3/detect-worker.d.ts +1 -1
  54. package/dist/core/v3/detect-worker.js +1 -13
  55. package/dist/create-document-capture-T4APHJMY.js +1 -0
  56. package/dist/create-portrait-capture-B57GE5FU.js +1 -0
  57. package/dist/create-verification-C0AVIcVW.d.ts +2787 -0
  58. package/dist/create-verification-DoFpgzok.d.cts +2787 -0
  59. package/dist/{detect-worker-CKXHlXx9.d.cts → detect-worker-DclNxkZT.d.cts} +6 -0
  60. package/dist/{detect-worker-CKXHlXx9.d.ts → detect-worker-DclNxkZT.d.ts} +6 -0
  61. package/dist/detector-scanic-YCDNLCGV.js +1 -0
  62. package/dist/icao-gate-D8qm1O2t.d.cts +1655 -0
  63. package/dist/icao-gate-D8qm1O2t.d.ts +1655 -0
  64. package/dist/icao-gate-PWBMKRGC.js +1 -0
  65. package/dist/icao-tuning-4GGVX6B4.js +1 -0
  66. package/dist/index.cjs +1 -3030
  67. package/dist/index.d.cts +52 -6
  68. package/dist/index.d.ts +52 -6
  69. package/dist/index.js +1 -85
  70. package/dist/internal/index.cjs +1 -4439
  71. package/dist/internal/index.d.cts +352 -312
  72. package/dist/internal/index.d.ts +352 -312
  73. package/dist/internal/index.js +1 -657
  74. package/dist/keyframe-rank-YAJLYJYF.js +1 -0
  75. package/dist/landmarker-KB7LVXAU.js +1 -0
  76. package/dist/mrz-band-VYHOTDHY.js +1 -0
  77. package/dist/plan-runner-UBK4B4CG.js +1 -0
  78. package/dist/popup/index.cjs +1 -76
  79. package/dist/popup/index.js +1 -11
  80. package/dist/scanic-ml-stub-KW7IZHUT.js +1 -0
  81. package/dist/segmenter-USLNBX65.js +1 -0
  82. package/dist/turnstile-FATNZ4AG.js +1 -0
  83. package/package.json +25 -10
  84. package/sbom.cdx.json +195 -0
  85. package/dist/chunk-MWNFSNMP.js +0 -52
  86. package/dist/chunk-MWNFSNMP.js.map +0 -1
  87. package/dist/chunk-NILNKLK6.js +0 -50
  88. package/dist/chunk-NILNKLK6.js.map +0 -1
  89. package/dist/chunk-NWF46H7K.js +0 -359
  90. package/dist/chunk-NWF46H7K.js.map +0 -1
  91. package/dist/chunk-R3SJQHYU.js +0 -1173
  92. package/dist/chunk-R3SJQHYU.js.map +0 -1
  93. package/dist/chunk-TG5IE552.js +0 -1128
  94. package/dist/chunk-TG5IE552.js.map +0 -1
  95. package/dist/chunk-WY6U7AIK.js +0 -193
  96. package/dist/chunk-WY6U7AIK.js.map +0 -1
  97. package/dist/chunk-YVFF4Q4G.js +0 -327
  98. package/dist/chunk-YVFF4Q4G.js.map +0 -1
  99. package/dist/client/index.cjs.map +0 -1
  100. package/dist/client/index.js.map +0 -1
  101. package/dist/core/index.cjs.map +0 -1
  102. package/dist/core/index.js.map +0 -1
  103. package/dist/core/v3/detect-worker.cjs.map +0 -1
  104. package/dist/core/v3/detect-worker.js.map +0 -1
  105. package/dist/create-verification-BKc9NFQj.d.cts +0 -455
  106. package/dist/create-verification-DjcMZHAQ.d.ts +0 -455
  107. package/dist/detector-scanic-4C6IEW2K.js +0 -787
  108. package/dist/detector-scanic-4C6IEW2K.js.map +0 -1
  109. package/dist/hosted-client-DJXq_CB9.d.cts +0 -449
  110. package/dist/hosted-client-DJXq_CB9.d.ts +0 -449
  111. package/dist/index.cjs.map +0 -1
  112. package/dist/index.js.map +0 -1
  113. package/dist/internal/index.cjs.map +0 -1
  114. package/dist/internal/index.js.map +0 -1
  115. package/dist/popup/index.cjs.map +0 -1
  116. package/dist/popup/index.js.map +0 -1
  117. package/dist/scanic-ml-stub-S2OZ6HEF.js +0 -10
  118. package/dist/scanic-ml-stub-S2OZ6HEF.js.map +0 -1
@@ -0,0 +1 @@
1
+ import{b as R,c as le,d as x,e as T,f as w,g as de,h as E,i as V,q as pe,r as me}from"./chunk-YDQBVWXG.js";import{m as ae}from"./chunk-RVHAKRAI.js";import{a as se}from"./chunk-7V2M6Y2W.js";import{b as F}from"./chunk-DQWW4OCK.js";import{c as ce,e as ue,f as L}from"./chunk-4RS2YIL4.js";var Ee="https://api.sekyro.ai",ve=5e3,Me=1500,we=10;function Ve(e){return new Promise(t=>setTimeout(t,e))}function Oe(){let e=globalThis.crypto;if(e!==void 0&&typeof e.randomUUID=="function")return e.randomUUID();let t=new Uint8Array(16);if(e!==void 0&&typeof e.getRandomValues=="function")e.getRandomValues(t);else for(let i=0;i<16;i+=1)t[i]=Math.floor(Math.random()*256);t[6]=(t[6]??0)&15|64,t[8]=(t[8]??0)&63|128;let o=[...t].map(i=>i.toString(16).padStart(2,"0")).join("");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}function lt(e){return De(e,{})}function De(e,t){let o=e.apiOrigin??Ee,i=e.autoRetry??!0,r=e.rearm??"auto",s=t.client??new ue({apiOrigin:o,sessionToken:e.clientToken,...e.fetch!==void 0?{fetch:e.fetch}:{}}),d=t.sleep??Ve,f=t.uuid??Oe,g=t.getTurnstileToken??((n,a)=>import("./turnstile-FATNZ4AG.js").then(m=>m.executeTurnstile(n,a))),c=se(),u=null,y=null,l=!1,q=new AbortController,p=null,H=null,P=n=>{p=n,c.emit("view",n),u?.onView(n)},C=()=>p!==null?Promise.resolve(p):(H??(H=s.getSession().then(n=>(P(n),n)).finally(()=>{H=null})),H),b=async()=>{let n=await s.getSession();return P(n),n},N=(n,a)=>{p!==null&&P(de(p,n,a))},B=null,Y=async n=>{let a=await C();!n&&a.consentRecorded||(await s.recordConsent(e.locale),p!==null&&P({...p,consentRecorded:!0}))},v=n=>n?.force===!0?Y(!0):(B??(B=Y(!1).finally(()=>{B=null})),B),U={client:s,ensureConsent:n=>v(n),sleep:d,uuid:f,onBusy:n=>{l||c.emit("busy",n)}},W=!1,Z=null,G=n=>{if(n.status==="approved"||n.status==="rejected"||n.status==="review"){if(W)return;W=!0}Z=JSON.stringify(n),c.emit("result",n)},ge=n=>{Z!==JSON.stringify(n)&&G(n)},J=async n=>{let a=p;n&&(a=await b().catch(()=>p));let m=a===null?null:R(a);return m!==null&&!l&&c.emit("method",m),m!==null},Q=null,j=!1,$=!1,X=()=>pe(U,(n,a)=>n.submitCheck("population_registry",{},{idempotencyKey:a})),z=n=>n.nniBound===!0||w(n,"population_registry")?.nniFromDocument===!0,Ce=async()=>{try{let n=await C();if(x(n)||R(n)!==null||T(n)?.checkType!=="population_registry")return;if(!z(n)&&w(n,"population_registry")?.nniFromDocument===void 0&&(n=await b()),!z(n)){$=!0;return}await v(),N(await X(),"population_registry");let a=p===null?void 0:w(p,"population_registry");if(a?.state==="input_required"&&a.reason==="registry_unavailable"&&a.attemptsRemaining>0){if(await d(ve),l)return;N(await X(),"population_registry")}}catch(n){if(n instanceof ce&&n.code==="method_required"){await b().catch(()=>{});return}j=!0;return}p!==null&&x(p)&&G(V(p,{autoRetry:i}))},ee=()=>(Q??(Q=Ce()),Q),_e=async()=>{let a=(await C()).turnstileSiteKey;return a===null?{sandbox:!0}:{channel:"hosted_web",siteKey:a,turnstileToken:await g(a,{signal:q.signal})}},_=null,te=Promise.resolve(),M=0,ke=async()=>{let n=await C();for(let a=0;a<we&&!l&&!x(n)&&T(n)===void 0&&n.steps.some(m=>m.state==="processing")&&(await d(Me),!l);a+=1)n=await b();return n},xe=async(n,a,m)=>{let{capture:k}=n,h=()=>l,O=()=>n.alive&&n.attempt===m,re=S=>{O()&&k.setFlowState(S)},I=S=>{if(!h()&&(G(S),!!O())){if(S.status==="retry"&&r==="auto"){k.handle.retry();return}k.setFlowState("done")}};if(a.degraded==="NO_RECORDER"){let S=p?.sessionId??(await C().catch(()=>null))?.sessionId??"";I(E(S,"no_recorder"));return}re("uploading");try{if(await ee(),h())return;let S=await C();if(!x(S)&&R(S)!==null){await J(!1),I(E(S.sessionId,"method_required"));return}if(!x(S)){if(T(S)?.checkType==="population_registry"){I(E(S.sessionId,$?"nni_unbound":j?"network":"registry_unavailable"));return}if(await v(),h())return;let D=await me({...U,artifacts:a,getAttestation:_e,getView:()=>p??S,refreshView:b,applySubmit:N,onPhase:re,isCancelled:h,onKeyframePromoted:Te=>{y=Te}});if(h())return;if(D.kind==="unavailable"){if(D.reason==="method_required"&&await J(!0),h())return;I(E(S.sessionId,D.reason));return}D.kind==="resync"&&await b(),S=await ke()}I(V(S,{autoRetry:i}))}catch{if(h())return;I(E(p?.sessionId??"","network"))}},Ae=(n,a)=>{let m=n.attempt;M>0&&n.alive&&n.capture.setFlowState("uploading"),M+=1,te=te.then(()=>xe(n,a,m)).finally(()=>{M-=1,M===0&&u?.onChainIdle()}).catch(()=>{})},ne=n=>{_?.capture.handle.destroy(),_!==null&&(_.alive=!1);let a=ae(n,u?.captureInternals?.(n)??t.capture,()=>p?.capture?.liveness?.keyframe?.rank===!0),m={capture:a,alive:!0,attempt:0};_=m,a.handle.on("state",h=>{h==="starting"&&(m.attempt+=1)}),a.handle.on("captured",h=>{Promise.resolve().then(()=>Ae(m,h))});let k=a.handle;return{get state(){return k.state},on:(h,O)=>k.on(h,O),start:h=>k.start(h),retry:()=>k.retry(),switchCamera:()=>k.switchCamera(),destroy:()=>{m.alive=!1,_===m&&(_=null),k.destroy()}}},be=async()=>{if(l)return null;try{let n=await C();return l?null:R(n)}catch{return null}},Re=async()=>{if(l)return!1;try{let n=await C();if(l||x(n))return!1;let a=w(n,"liveness");return le(a)&&a?.requiresMobile===!0&&!F()}catch{return!1}},Pe=async()=>{if(l)return!1;try{let n=await C();return!l&&n.returning===!0}catch{return!1}},oe=async n=>{let a=await s.selectMethod(n);l||P(a)},ie=null,Ie=()=>(ie??(ie=import("./plan-runner-UBK4B4CG.js").then(n=>{let a=n.createPlanRunner({runtime:U,currentView:()=>p,ensureView:C,refreshView:b,ensureConsent:()=>v(),selectMethod:oe,liveness:ne,chainBusy:()=>M>0,destroyed:()=>l,sleep:d,isMobile:F,now:t.now??Date.now,keptFaceKey:()=>y,setView:P,baseCapture:t.capture,emitStep:m=>{l||c.emit("step",m)},emitResult:ge,...t.document!==void 0?{documentInternals:t.document}:{},...t.portrait!==void 0?{portraitInternals:t.portrait}:{},livePhotoInternals:t.livePhoto});return u=a,a})),ie);return{consent:()=>v(),startRegistry:ee,methodChoice:be,selectMethod:oe,mobileRequired:Re,returning:Pe,liveness:ne,run:async()=>{if(l)throw new Error("verification destroyed");return(await Ie()).run()},currentStep:()=>u?.current()??null,voiceClips:async()=>{if(l)return null;try{let n=await C();return l?null:n.voice??null}catch{return null}},on:(n,a)=>c.on(n,a),destroy:()=>{l=!0,q.abort(),u?.destroy(),_!==null&&(_.alive=!1,_.capture.handle.destroy(),_=null),c.clear()}}}var fe=["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 Le=["carte_identite","passport","residence_permit"];function He(e,t){let o=e.byIssuer?.[t]??e.default;return Le.filter(i=>o==="*"||o.includes(i))}function ft(e,t=fe){return[...new Set([...t,...Object.keys(e.byIssuer??{})])].filter(i=>He(e,i).length>0).sort()}function Se(e){if(e.acceptedDocuments)return e.acceptedDocuments;let t=e.acceptedDocumentTypes?.length?[...e.acceptedDocumentTypes]:["carte_identite","passport"];return{default:[],byIssuer:{MR:t}}}function St(e){return/^[A-Z]{2}$/.test(e)?String.fromCodePoint(...[...e].map(t=>127462+t.charCodeAt(0)-65)):""}var Ne=["national_number","document_photo","national_eid"],Be=["national_number","document_photo"],Ue=new Set(["eid_not_enrolled","eid_unavailable","eid_locked"]),ye="platform_unsupported",Ge=new Set(["prefilled","user_entered","prefilled_or_entered"]),Fe={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 A(e){return e.section??Fe[e.checkType]??null}function Ke(e){let t={sessionId:e.sessionId,orgName:e.orgName,returning:e.returning===!0,consentRecorded:e.consentRecorded,expiresAt:e.expiresAt,sections:[]};for(let o of e.steps){let i=A(o);i!==null&&!t.sections.includes(i)&&t.sections.push(i)}return e.branding!==void 0&&(t.branding=e.branding),t}function qe(e){let t={attemptsRemaining:e.attemptsRemaining,attemptsExhausted:e.attemptsExhausted===!0};return e.reason!==void 0&&(t.reason=e.reason),t}function Ye(e,t){let o=e.otpChoice;if(o===void 0||o.locked||o.selected===null)return;let i=t==="phone_otp"?"email":"phone";return o.options.includes(i)?i:void 0}function We(e,t,o,i){let r=t.checkType==="email_otp",s=(r?t.emailOtp:t.otp)??{},d=r?t.emailOtp?.emailSource:t.otp?.numberSource,f=d!==void 0&&Ge.has(d)?d:r?"prefilled_or_entered":"user_entered",g=typeof s.sentToMasked=="string"&&s.sentToMasked.length>0,c=Ye(e,r?"email_otp":"phone_otp"),u={key:t.checkType,context:o,section:A(t),phase:g?"verify":"send",canSwitch:c!==void 0,...i},y=r?{kind:"email_otp",...u,emailSource:f,needsEmail:f!=="prefilled"}:{kind:"phone_otp",...u,numberSource:f,needsPhone:f!=="prefilled",channels:(t.otp?.channels??[]).filter(l=>l==="whatsapp"||l==="sms")};return c!==void 0&&(y.switchChannel=c),g&&(y.sentToMasked=s.sentToMasked),!r&&t.otp?.channel!==void 0&&(y.channel=t.otp.channel),s.expiresAt!==void 0&&(y.codeExpiresAt=s.expiresAt),s.resendAvailableAt!==void 0&&(y.resendAvailableAt=s.resendAvailableAt),y}function Ze(e,t,o,i){let r=e.nniBound===!0?"bound":t.nniFromDocument===!0?"document":"typed",s=r==="typed"&&t.state==="input_required"&&t.reason==="nni_recheck",d=t.reason==="nni_not_found"&&t.state==="input_required"&&!i.attemptsExhausted&&e.methodChoice?.available===!0&&e.methodChoice.options.includes("document_photo");return{kind:"registry",key:"registry",context:o,section:A(t),state:t.state==="input_required"?"input_required":"pending",source:r,recheck:s,canUseDocument:d,...i}}function Je(e,t,o,i){let r=[...t.acceptedSides??[]];return{kind:"document",key:"document",context:o,section:A(t),side:r.includes("recto")?"verso":"recto",acceptedSides:r,documents:Se(e),...i}}function Qe(e){let t=e.steps.find(o=>o.checkType==="liveness");return t?.state==="passed"||t?.state==="review"}function he(e,t,o,i,r){let s=t.icao?.report;return{kind:"portrait",key:`portrait:${r}`,context:o,section:A(t),phase:r,report:Array.isArray(s)?s:null,review:t.state==="review",tuning:e.capture?.icao??null,tuningVersion:e.capture?.tuningVersion??null,icao:L(e),retakeOnly:r==="capture"&&t.state==="input_required"&&e.capture?.livePhoto?.oneCapture===!0&&Qe(e),...i}}var K={minLongSidePx:1280,jpegQuality:.95};function je(e,t){let o=e.capture?.livePhoto;if(o?.oneCapture!==!0)return null;let i=e.steps.find(s=>s.checkType==="portrait_icao"),r=o.still??K;return{icao:t==="liveness"&&L(e)!==null&&i!==void 0&&i.state==="pending"&&i.reason===void 0,still:{minLongSidePx:r.minLongSidePx??K.minLongSidePx,jpegQuality:r.jpegQuality??K.jpegQuality}}}function $e(e,t,o,i){let r=t.eid,s=A(t);if(r===void 0||r.challenge!=="app_code")return{kind:"unsupported",key:"unsupported:eid_auth",context:o,section:s,checkType:"eid_auth",reason:"update_required"};let d=e.methodChoice,f=d?.available===!0?d.options.find(u=>Be.includes(u)):void 0,g=f!==void 0&&t.state==="input_required"&&(t.reason!==void 0&&Ue.has(t.reason)||t.attemptsExhausted===!0||t.attemptsRemaining===0||t.reason==="eid_resend_limit"&&r.awaiting!=="code"),c={kind:"eid",key:"eid",context:o,section:s,provider:r.provider,providerName:r.providerName,country:r.country,challenge:"app_code",phase:r.awaiting==="code"?"code":"identifier",identifierBound:r.identifierBound===!0,canUseCamera:g,afterPass:r.afterPass==="continue"?"continue":"end",...i};return g&&(c.cameraMethod=f),r.expiresAt!==void 0&&(c.codeExpiresAt=r.expiresAt),r.resendAvailableAt!==void 0&&(c.resendAvailableAt=r.resendAvailableAt),r.resendsRemaining!==void 0&&(c.resendsRemaining=r.resendsRemaining),r.codeAttemptsRemaining!==void 0&&(c.codeAttemptsRemaining=r.codeAttemptsRemaining),c}function Xe(e,t){if(t.checkType!=="face_match"||t.reason!==void 0)return null;let o=e.steps.find(i=>i.checkType==="portrait_icao");return o!==void 0&&(o.state==="passed"||o.state==="review")?o:null}function ze(e){return e.steps.some(t=>t.attemptsExhausted===!0)}function et(e,t){let o=e.failureReason,i;o===ye?i="platform_unsupported":e.status==="expired"?i="expired":e.status==="review_pending"?i="review":e.status==="completed"&&e.outcome==="approved"?i="approved":e.status==="completed"&&e.outcome==="review"?i="review":o==="device_cooldown"?i="cooldown":o!==void 0?i="policy_stop":ze(e)?i="attempts_exhausted":i="rejected";let r=i==="platform_unsupported"?{sessionId:e.sessionId,status:"unavailable"}:V(e,{autoRetry:!1}),s={kind:"result",key:"result",context:t,section:null,display:i,result:r};return o!==void 0&&(s.failureReason=o),e.retryAfter!==void 0&&(s.retryAfter=e.retryAfter),s}function tt(e,t){let o=e.identitySummary;if(o==null)return null;let i={kind:"identity_summary",key:"identity_summary",context:t,section:"identity",summaryKind:o.kind==="partial"?"partial":o.kind??"full",source:o.source,portraitAvailable:o.portrait?.available===!0,retakeAvailable:o.retakeAvailable===!0};for(let r of nt){let s=o[r];typeof s=="string"&&s!==""&&(i[r]=s)}return i}var nt=["fullName","birthDate","birthYear","nationality","documentType","documentNumberMasked","nniMasked","expiryDate","retakeTarget"];function _t(e,t={}){let o=Ke(e);if(x(e)||e.failureReason===ye)return et(e,o);let i=tt(e,o);if(i!==null)return i;let r=R(e);if(r!==null){let c=r.options.filter(y=>Ne.includes(y));if(c.length===0)return{kind:"unsupported",key:"unsupported:method",context:o,section:"identity",checkType:"method",reason:"platform_unsupported"};let u={kind:"method",key:"method",context:o,section:"identity",options:c};return c.includes("national_eid")&&r.nationalEid!==void 0&&(u.nationalEid=r.nationalEid),u}let s=T(e);if(s===void 0){let c=e.steps.find(u=>u.state==="processing");return{kind:"processing",key:"processing",context:o,section:c===void 0?null:A(c),stalled:!1}}let d=qe(s),f=s.checkType,g=A(s);switch(f){case"phone_otp":case"email_otp":{let c=e.otpChoice;return c!==void 0&&c.selected===null&&!c.locked?{kind:"contact_choice",key:"contact_choice",context:o,section:g,options:c.options.filter(u=>u==="phone"||u==="email"),selected:null,locked:!1}:We(e,s,o,d)}case"population_registry":return Ze(e,s,o,d);case"eid_auth":return $e(e,s,o,d);case"doc_ocr":return Je(e,s,o,d);case"portrait_icao":return he(e,s,o,d,"capture");case"liveness":case"face_match":{let c=Xe(e,s);if(c!==null)return he(e,c,o,d,"match");let u=s.requiresMobile===!0,y=L(e);return u&&t.isMobile===!1?{kind:"mobile_required",key:"mobile_required",context:o,section:g,checkType:f}:{kind:"liveness",key:"biometric",context:o,section:g,mode:f==="face_match"?"selfie":"liveness",requiresMobile:u,instructions:y===null?"standard":"icao",icao:y,livePhoto:je(e,f),...d}}default:return{kind:"unsupported",key:`unsupported:${f}`,context:o,section:g,checkType:f,reason:f==="nfc_chip"?"platform_unsupported":"update_required"}}}export{Ee as a,ve as b,Me as c,we as d,Oe as e,lt as f,De as g,fe as h,Le as i,He as j,ft as k,Se as l,St as m,Ne as n,ye as o,A as p,Xe as q,_t as r};
@@ -0,0 +1 @@
1
+ import{c as v,d as E}from"./chunk-4RS2YIL4.js";var L=new Set(["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","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"]);function Z(e){let t=e.methodChoice;if(t===void 0||!t.available||t.selected!==null)return null;let n=w(e)?.checkType;return n==="phone_otp"||n==="email_otp"?null:t}var F=new Set(["liveness","face_match"]);function C(e){return e!==void 0&&(e.state==="pending"||e.state==="input_required")}function M(e){return e.status!=="created"&&e.status!=="in_progress"}function w(e){return e.steps.find(t=>C(t))}function S(e,t){return e.steps.find(n=>n.checkType===t)}function R(e,t){let n=t.steps.find(o=>o.checkType==="liveness"),i=t.steps.find(o=>o.checkType==="face_match");return S(e,"face_match")?.state==="pending"&&(n?.state==="passed"||n?.state==="review")&&i!==void 0&&i.state!=="pending"&&i.state!=="skipped"}function ee(e,t,n){let i=new Map(e.steps.map(r=>[r.checkType,r])),o=n==="liveness"&&R(e,t),s=t.steps.map(r=>{let u=i.get(r.checkType),a=u?.attemptsRemaining??0,c={...u??{},checkType:r.checkType,state:r.state,attemptsRemaining:r.checkType===n||r.checkType==="face_match"&&o?Math.max(0,a-1):a};return r.reason!==void 0?c.reason=r.reason:delete c.reason,r.attemptsExhausted!==void 0?c.attemptsExhausted=r.attemptsExhausted:delete c.attemptsExhausted,c});return{...e,status:t.status,outcome:t.outcome,failureReason:t.failureReason,steps:s,expiresAt:t.expiresAt}}function g(e,t){return t===void 0?{sessionId:e,status:"unavailable"}:{sessionId:e,status:"unavailable",reason:t}}function m(e,t,n){return n===void 0?{sessionId:e,status:t}:{sessionId:e,status:t,reason:n}}function te(e,t){let{sessionId:n}=e;switch(e.status){case"completed":return e.outcome==="approved"?{sessionId:n,status:"approved"}:e.outcome==="review"?m(n,"review",h(e,"review")):m(n,"rejected",h(e,"failed"));case"failed":{let s=m(n,"rejected",e.failureReason??h(e,"failed"));return e.failureReason==="device_cooldown"&&e.retryAfter!==void 0&&(s.retryAfter=e.retryAfter),s}case"review_pending":return m(n,"review",h(e,"review"));case"expired":return g(n);case"created":case"in_progress":break;default:{let s=e.status;throw new Error(`mapSessionResult: unhandled status ${s}`)}}let i=e.steps.find(s=>F.has(s.checkType)&&s.state==="input_required"&&s.reason!==void 0);if(i?.reason==="mobile_required")return g(n,"mobile_required");if(i?.reason!==void 0){let s=t.autoRetry&&L.has(i.reason)&&i.attemptsRemaining>0;return{sessionId:n,status:s?"retry":"rejected",reason:i.reason,attemptsRemaining:i.attemptsRemaining}}let o=w(e);return o===void 0&&e.steps.some(s=>s.state==="review")?m(n,"review",h(e,"review")):o?.checkType==="portrait_icao"?g(n,"portrait_required"):g(n)}function h(e,t){return e.steps.find(n=>n.state===t&&n.reason!==void 0)?.reason}function T(e,t,n,i,o){return e.presignCapture!==void 0?e.presignCapture(t,n,i,o):e.presign(t,n,i)}function V(e){return{...e?.engine!==void 0?{engine:e.engine}:{},...e?.clipMs!==void 0?{durationMs:e.clipMs}:{}}}var I=["video/webm","video/mp4"],x="image/jpeg",q=2,K=1e3,O=1e4,N=3,Y=10,B=30,D=3,U=new Set(["network_error","timeout","upload_failed","unknown_error","rate_limit_exceeded"]),$=new Set(["session_not_active","check_not_found","check_already_finalized","check_out_of_order","identity_confirm_required"]),_=class extends Error{constructor(){super("verification destroyed"),this.name="FlowCancelledError"}};function j(e){let t=e.steps.findIndex(i=>i.checkType==="liveness");return t<0?!1:e.steps.slice(t+1).find(i=>C(i))?.checkType==="face_match"}var y=class extends Error{constructor(t){super(t),this.name="AttestationError"}};async function A(e,t,n={}){let i=e.uuid(),o=!1,s=!1,r=0,u=0;for(;;)try{return await t(e.client,i)}catch(a){if(a instanceof y){if(s)throw a;s=!0,n.onAttestationInvalid?.(),i=e.uuid();continue}if(!(a instanceof v))throw a;if(a.code==="consent_required"&&!o){o=!0,await e.ensureConsent({force:!0}),i=e.uuid();continue}if(a.code==="attestation_invalid"&&!s){s=!0,n.onAttestationInvalid?.(),i=e.uuid();continue}if(a.code==="inference_unavailable"&&u<N){u+=1;let c=Math.min(a.retryAfterSeconds??Y,B);e.onBusy?.({attempt:u,retryAfterSeconds:c}),await e.sleep(c*1e3),n.onAttestationInvalid?.(),i=e.uuid();continue}if(U.has(a.code)&&r<q){r+=1;let c=a.retryAfterSeconds!==void 0?a.retryAfterSeconds*1e3:void 0;await e.sleep(c!==void 0?Math.min(c,O):K);continue}throw a}}var z=new Set(["passed","review","processing","skipped"]);async function re(e){let{artifacts:t}=e,n=t.clip,i=E(t.clipMime??"");if(t.degraded==="NO_RECORDER"||n===void 0||!I.includes(i))return{kind:"unavailable",reason:"no_recorder"};e.client.armCapture?.(2);let o=X(e,t.keyframe),s=W(e,n,i,o),r=G(e,o),u=!1,a=!1,c=!0,f=0;for(;;){if(e.isCancelled())return{kind:"cancelled"};let l=e.getView();if(M(l))return{kind:"settled"};let b=w(l)?.checkType,k=b==="liveness"&&!u?"liveness":b==="face_match"&&!a&&c?"face_match":null;if(k===null)return{kind:"settled"};if(k==="liveness"&&t.captureChannel==="desktop"&&S(l,"liveness")?.requiresMobile===!0)return{kind:"unavailable",reason:"mobile_required"};try{if(k==="liveness"){u=!0;let d=await s();if(e.isCancelled())return{kind:"cancelled"};a=R(l,d),e.applySubmit(d,"liveness");let p=S(e.getView(),"liveness")?.state;c=p===void 0||z.has(p)}else{a=!0;let d=await r();if(e.isCancelled())return{kind:"cancelled"};e.applySubmit(d,"face_match")}}catch(d){if(e.isCancelled()||d instanceof _)return{kind:"cancelled"};let p=Q(d);if(p.kind!=="resync"||f>=D)return p;f+=1,await e.refreshView()}}}function X(e,t){let n=null,i=null,o=()=>n!==null?Promise.resolve(n):(i??(i=(async()=>{let s=await T(e.client,"image",x,t.size,V(e.artifacts));return await e.client.uploadToSpaces(s.uploadUrl,t,x),n=(await e.client.completeMedia(s.key)).key,e.onKeyframePromoted?.(n),n})().finally(()=>{i=null})),i);return{ensure:o,attempt:()=>o().catch(()=>null),current:()=>n}}function W(e,t,n,i){let o=null,s,r=null;return()=>A(e,async(u,a)=>{if(o===null||s===void 0){if(e.isCancelled())throw new _;s===void 0&&!j(e.getView())&&(s=null),e.onPhase("uploading");let[c,f]=await Promise.all([o!==null?Promise.resolve(o):(async()=>{let l=await T(u,"clip",n,t.size,V(e.artifacts));return await u.uploadToSpaces(l.uploadUrl,t,n),(await u.completeMedia(l.key)).key})(),s!==void 0?Promise.resolve(s===null?null:s.imageKey):i.attempt()]);o=c,s===void 0&&(s=f===null?null:{imageKey:f})}if(r===null)try{r=await e.getAttestation()}catch(c){throw new y(c instanceof Error?c.message:String(c))}return e.onPhase("checking"),u.submitCheck("liveness",{clipKey:o,attestation:r,captureChannel:e.artifacts.captureChannel,capture:J(e.artifacts),...s!==null?{faceMatch:s}:{}},{idempotencyKey:a})},{onAttestationInvalid:()=>{r=null}})}function G(e,t){return()=>A(e,async(n,i)=>{if(t.current()===null){if(e.isCancelled())throw new _;e.onPhase("uploading")}let o=await t.ensure();return e.onPhase("checking"),n.submitCheck("face_match",{imageKey:o},{idempotencyKey:i})})}function J(e){return{...e.engine!==void 0?{engine:e.engine}:{},width:e.width,height:e.height,...e.clipMs!==void 0?{clipMs:e.clipMs}:{},...e.cameraReadyMs!==void 0?{cameraReadyMs:e.cameraReadyMs}:{},...e.faceAcquireMs!==void 0?{faceAcquireMs:e.faceAcquireMs}:{},...e.captureMs!==void 0?{captureMs:e.captureMs}:{}}}function Q(e){if(e instanceof y)return{kind:"unavailable",reason:"attestation"};if(e instanceof v){if(e.code==="attestation_invalid")return{kind:"unavailable",reason:"attestation"};if(e.code==="method_required")return{kind:"unavailable",reason:"method_required"};if(e.code==="inference_unavailable")return{kind:"unavailable",reason:"inference_unavailable"};if(e.code==="mobile_required")return{kind:"unavailable",reason:"mobile_required"};if($.has(e.code))return{kind:"resync"}}return{kind:"unavailable",reason:"network"}}var P=class extends Error{constructor(t,n){super(`invalid ${t} (${n})`),this.name="InvalidInputError",this.field=t,this.kind=n}},H=class extends Error{constructor(t,n){super(`invalid ${t} (${n})`),this.name="OtpInputError",this.field=t,this.kind=n}};export{L as a,Z as b,C as c,M as d,w as e,S as f,ee as g,g as h,te as i,T as j,I as k,q as l,K as m,N as n,Y as o,y as p,A as q,re as r,P as s,H as t};
@@ -0,0 +1 @@
1
+ import{b as jt}from"./chunk-SMKCBUJL.js";import{a as et,b as Zt,c as Jt,e as ht,f as $t}from"./chunk-MXWLCDFX.js";import{d as Wt,h as Xt,k as Yt}from"./chunk-G6LKLN4U.js";import{b as Kt,c as Vt}from"./chunk-TDLIXFDT.js";import{b as Qt,c as Bt}from"./chunk-POIQGEZM.js";import{d as zt}from"./chunk-FHJ7HO3M.js";import{b as ut,c as Ut,d as j,e as Ht}from"./chunk-FPXL63KZ.js";import{b as Nt}from"./chunk-LQ7C44JG.js";var it=Object.freeze({sensing:{key:"sensing",reticle:"searching",minDurationMs:900},too_far:{key:"too_far",reticle:"coaching",minDurationMs:1400},too_close:{key:"too_close",reticle:"coaching",minDurationMs:1400},edge_clipped:{key:"edge_clipped",reticle:"coaching",minDurationMs:1400},wrong_shape:{key:"wrong_shape",reticle:"coaching",minDurationMs:1400},tilted:{key:"tilted",reticle:"coaching",minDurationMs:1400},too_dark:{key:"too_dark",reticle:"coaching",minDurationMs:1400},too_bright:{key:"too_bright",reticle:"coaching",minDurationMs:1400},blurry:{key:"blurry",reticle:"coaching",minDurationMs:1400},focus_far:{key:"focus_far",reticle:"coaching",minDurationMs:1600},glare:{key:"glare",reticle:"coaching",minDurationMs:1400},hold_still:{key:"hold_still",reticle:"locking",minDurationMs:900},processing:{key:"processing",reticle:"processing",minDurationMs:800},side_captured:{key:"side_captured",reticle:"flip",minDurationMs:2600},captured:{key:"captured",reticle:"done",minDurationMs:800}});function qt(e){return e.framing==="no_document"?"sensing":e.framing==="too_far"?"too_far":e.framing==="too_close"?"too_close":e.framing==="edge_clipped"?"edge_clipped":e.framing==="wrong_shape"?"wrong_shape":e.framing==="tilted"?"tilted":e.lighting==="too_dark"?"too_dark":e.lighting==="too_bright"?"too_bright":e.glare==="glare"?"glare":e.blur==="blurry"?"blurry":"hold_still"}var nt=class{constructor(t=2600,n=.35){this.windowMs=t;this.decayPerSecond=n;this.votes=[];this.current=it.sensing;this.currentSinceMs=null}reset(){this.votes=[],this.current=it.sensing,this.currentSinceMs=null}force(t,n){return this.votes=[],this.current=it[t],this.currentSinceMs=n,this.current}tick(t,n){if(this.currentSinceMs===null&&(this.currentSinceMs=n),this.votes.push({key:t,atMs:n}),this.votes=this.votes.filter(r=>n-r.atMs<=this.windowMs),n-this.currentSinceMs<this.current.minDurationMs)return this.current;let i=new Map;for(let r of this.votes){let c=(n-r.atMs)/1e3,a=this.decayPerSecond**c;i.set(r.key,(i.get(r.key)??0)+a)}let o=this.current.key,s=-1;for(let[r,c]of i)c>s&&(s=c,o=r);return o!==this.current.key&&(this.current=it[o],this.currentSinceMs=n),this.current}};var Qe=Object.freeze({MAX_AREA_FRAC:.92,TILT_MAX_SIDE_RATIO:1.3,GLARE_MAX_SPECULAR_FRAC:.025});function ee(e){let{data:t,width:n,height:i}=e,o=n*i;if(o===0)return 0;let s=0;for(let r=0;r<o;r++){let c=r*4;.299*(t[c]??0)+.587*(t[c+1]??0)+.114*(t[c+2]??0)>=252&&s++}return s/o}function Be(e){let t=(a,l)=>Math.hypot(l.x-a.x,l.y-a.y),n=t(e.topLeft,e.topRight),i=t(e.bottomLeft,e.bottomRight),o=t(e.topLeft,e.bottomLeft),s=t(e.topRight,e.bottomRight),r=Math.max(n,i)/Math.max(1e-6,Math.min(n,i)),c=Math.max(o,s)/Math.max(1e-6,Math.min(o,s));return Math.max(r,c)}function ie(e){let t={...Zt,...e.thresholds},n=Qe,{quad:i,frameWidth:o,frameHeight:s,measures:r}=e,c=e.format==="ID-3",a="ok";if(i===null)a="no_document";else if(c){let m=ht(i),h=o>0?m.width/o:0,f=m.height>0?m.width/m.height:0;h<t.ID3_BAND_MIN_WIDTH_FRAC?a="too_far":te(i,o,s,t.EDGE_CLIP_MARGIN_PX)?a="edge_clipped":(f<t.ID3_BAND_ASPECT_MIN||f>t.ID3_BAND_ASPECT_MAX)&&(a="wrong_shape")}else{let m=Jt(i,o,s),h=ht(i),f=Math.max(h.width,h.height)/Math.max(1e-6,Math.min(h.width,h.height));m<t.MIN_AREA_FRAC?a="too_far":m>n.MAX_AREA_FRAC?a="too_close":te(i,o,s,t.EDGE_CLIP_MARGIN_PX)?a="edge_clipped":Vt(e.format,f)?Be(i)>n.TILT_MAX_SIDE_RATIO&&(a="tilted"):a="wrong_shape"}let l=r.exposure>=t.GUIDE_EXPOSURE?"ok":r.meanLuma<(ut[0]+ut[1])/2?"too_dark":"too_bright",u=r.sharpness>=t.GUIDE_SHARPNESS?"ok":"blurry",d=r.specularFraction>=n.GLARE_MAX_SPECULAR_FRAC?"glare":"ok";return{framing:a,lighting:l,blur:u,glare:d,acceptable:a==="ok"&&l==="ok"&&u==="ok"&&d==="ok"}}function te(e,t,n,i){return[e.topLeft,e.topRight,e.bottomRight,e.bottomLeft].some(s=>s.x<=i||s.y<=i||s.x>=t-i||s.y>=n-i)}var oe=Object.freeze({width:1920,height:1080}),Ue=Object.freeze({width:3840,height:2160}),ne=4096,He=2560,se=640,ot=.15,Y=Object.freeze({side:.2,above:.9,below:.3});function L(e){let t=[e.topLeft.x,e.topRight.x,e.bottomRight.x,e.bottomLeft.x],n=[e.topLeft.y,e.topRight.y,e.bottomRight.y,e.bottomLeft.y],i=Math.min(...t),o=Math.min(...n);return{x:i,y:o,width:Math.max(...t)-i,height:Math.max(...n)-o}}function re(e,t){let n=Math.max(0,Math.floor(e.x)),i=Math.max(0,Math.floor(e.y)),o=Math.min(t.width,Math.ceil(e.x+e.width)),s=Math.min(t.height,Math.ceil(e.y+e.height));return o-n<16||s-i<16?null:{x:n,y:i,width:o-n,height:s-i}}function Ke(e,t,n){if(e===null||t.width<=0||t.height<=0)return null;let i=L(e);if(i.width<=0||i.height<=0)return null;let o=n==="ID-3"?{x:i.x-i.width*Y.side,y:i.y-i.width*Y.above,width:i.width*(1+2*Y.side),height:i.height+i.width*(Y.above+Y.below)}:{x:i.x-i.width*ot,y:i.y-i.height*ot,width:i.width*(1+2*ot),height:i.height*(1+2*ot)};return re(o,t)}function dt(e,t,n){let i=Math.max(e,t);return i>0?Math.min(1,n/i):1}function mt(e,t,n,i,o=He){let s=t.width>0?n.width/t.width:1,r=t.height>0?n.height/t.height:1,c=e===null?null:{topLeft:{x:e.topLeft.x*s,y:e.topLeft.y*r},topRight:{x:e.topRight.x*s,y:e.topRight.y*r},bottomRight:{x:e.bottomRight.x*s,y:e.bottomRight.y*r},bottomLeft:{x:e.bottomLeft.x*s,y:e.bottomLeft.y*r}},a=Ke(c,n,i)??{x:0,y:0,width:n.width,height:n.height},l=dt(a.width,a.height,o),u=Math.max(1,Math.round(a.width*l)),d=Math.max(1,Math.round(a.height*l)),m=null;if(c!==null){let h=L(c);m=re({x:(h.x-a.x)*l,y:(h.y-a.y)*l,width:h.width*l,height:h.height*l},{width:u,height:d})}return{crop:a,width:u,height:d,docRegion:m}}function ae(e,t,n,i=Ue){if(n==="LOW")return null;let o=e?.width?.max,s=e?.height?.max;if(typeof o!="number"||typeof s!="number"||o<=0||s<=0)return null;let r=Math.max(o,s),c=Math.min(o,s),a=Math.min(r,Math.max(i.width,i.height)),l=Math.min(c,Math.min(i.width,i.height));return a<=Math.max(t.width,t.height)?null:{width:{ideal:a},height:{ideal:l}}}function ce(e){let t={},n=e?.imageWidth,i=e?.imageHeight;if(typeof n?.max=="number"&&n.max>0){let o=typeof i?.max=="number"&&i.max>0?n.max/i.max:1.3333333333333333,s=o>=1?ne:ne*o,r=Math.min(n.max,Math.floor(s)),c=typeof n.step=="number"&&n.step>0?n.step:1,a=typeof n.min=="number"?n.min:0;r=Math.max(a,a+Math.floor((r-a)/c)*c),t.imageWidth=r}return e?.fillLightMode?.includes("off")===!0&&(t.fillLightMode="off"),t}function le(e,t){if(e.width<=0||e.height<=0||t.width<=0||t.height<=0)return!1;let n=e.width>e.height,i=t.width>t.height;return n!==i&&e.width!==e.height&&t.width!==t.height?!1:Math.max(e.width,e.height)>=1.2*Math.max(t.width,t.height)}function ue(e,t,n,i){if(n===null)return!1;let o=L(e),s=L(n);if(t.width<=0||i.width<=0)return!1;let r=o.width/t.width,c=s.width/i.width;return c>0&&r>=.6*c&&r<=1.25*c}var he=3500,Ve=.92;function me(){let e=globalThis.ImageCapture;return typeof e=="function"?e:null}function We(e){return/AppleWebKit\//.test(e)&&!/(Chrome|Chromium|Edg|OPR)\//.test(e)}function fe(e,t=typeof navigator>"u"?"":navigator.userAgent){return me()!==null&&!We(t)&&e!=null&&e.kind==="video"&&e.readyState==="live"}function de(e,t){return new Promise((n,i)=>{let o=setTimeout(()=>i(new Error("takePhoto timed out")),t);e.then(s=>{clearTimeout(o),n(s)},s=>{clearTimeout(o),i(s)})})}function ft(e,t){let n=document.createElement("canvas");return n.width=e,n.height=t,n}function Xe(e,t){return new Promise((n,i)=>{e.toBlob(o=>o?n(o):i(new Error("toBlob failed")),"image/jpeg",t)})}async function pe(e,t,n,i,o){let s=ft(n,i),r=ft(1,1);try{let c=s.getContext("2d");if(c===null)throw new Error("2d context unavailable");c.imageSmoothingQuality="high",c.drawImage(e,t.x,t.y,t.width,t.height,0,0,n,i);let a=await Xe(s,Ve),l=o===null?null:Wt({topLeft:{x:o.x,y:o.y},topRight:{x:o.x+o.width,y:o.y},bottomRight:{x:o.x+o.width,y:o.y+o.height},bottomLeft:{x:o.x,y:o.y+o.height}},{width:n,height:i},{width:n,height:i}),u=Xt(s,l),d=dt(n,i,se);return r.width=Math.max(1,Math.round(n*d)),r.height=Math.max(1,Math.round(i*d)),r.getContext("2d")?.drawImage(s,0,0,r.width,r.height),{blob:a,previewDataUrl:r.toDataURL("image/jpeg",.85),sharpness:u}}finally{s.width=0,s.height=0,r.width=0,r.height=0}}function je(e,t){let n=Math.min(1,t/e.width),i=ft(Math.max(1,Math.round(e.width*n)),Math.max(1,Math.round(e.height*n)));try{let o=i.getContext("2d",{willReadFrequently:!0});return o===null?null:(o.imageSmoothingQuality="high",o.drawImage(e,0,0,i.width,i.height),o.getImageData(0,0,i.width,i.height))}finally{i.width=0,i.height=0}}async function ge(e,t,n,i){let o={width:Math.max(1,e.videoWidth),height:Math.max(1,e.videoHeight)},s=mt(t,n,o,i);return{...await pe(e,s.crop,s.width,s.height,s.docRegion),docRegion:s.docRegion,source:"video",width:s.width,height:s.height}}async function be(e,t,n,i,o){let s=me();if(s===null)return null;let r=null;try{let c=new s(o.track),a=await de(c.getPhotoCapabilities?.()??Promise.resolve({}),he).catch(()=>({})),l=await de(c.takePhoto(ce(a)),he);r=await createImageBitmap(l);let u={width:e.videoWidth,height:e.videoHeight};if(!le(r,u))return null;let d=je(r,o.detectWidth),m=null;d!==null&&t!==null&&(m=await o.detect(d).catch(()=>null));let h=d??{width:r.width,height:r.height};m!==null&&!ue(m,h,t,n)&&(m=null);let f=mt(m,h,r,i);return{...await pe(r,f.crop,f.width,f.height,f.docRegion),docRegion:f.docRegion,source:"photo",width:f.width,height:f.height}}catch{return null}finally{r?.close()}}var st=Object.freeze({width:3840,height:2160,lensSelection:!0,continuousFocus:!0,refocusBeforePhotoMs:350,zoomMax:2,zoomNoFocusInfo:1.5,zoomMinSourcePx:2160,fillDistanceM:Object.freeze({id1:.11,id3:.15}),focusMarginFrac:.2,stillSharpnessMin:.16,stillRefusalsMax:2,focusFarFillFrac:.45,noDocFarHintMs:1500,zoomFallbackMs:8e3}),S=(e,t,n)=>typeof e=="number"&&Number.isFinite(e)&&e>=t&&e<=n?e:void 0;function ki(e){let t=st,n=e!==null&&typeof e=="object"?e:{},i=n.fillDistanceM!==null&&typeof n.fillDistanceM=="object"?n.fillDistanceM:{},o=(s,r)=>typeof s=="boolean"?s:r;return{width:S(n.width,640,7680)??t.width,height:S(n.height,480,4320)??t.height,lensSelection:o(n.lensSelection,t.lensSelection),continuousFocus:o(n.continuousFocus,t.continuousFocus),refocusBeforePhotoMs:S(n.refocusBeforePhotoMs,0,2e3)??t.refocusBeforePhotoMs,zoomMax:S(n.zoomMax,1,5)??t.zoomMax,zoomNoFocusInfo:S(n.zoomNoFocusInfo,1,5)??t.zoomNoFocusInfo,zoomMinSourcePx:S(n.zoomMinSourcePx,0,8e3)??t.zoomMinSourcePx,fillDistanceM:{id1:S(i.id1,.03,1)??t.fillDistanceM.id1,id3:S(i.id3,.03,1)??t.fillDistanceM.id3},focusMarginFrac:S(n.focusMarginFrac,0,2)??t.focusMarginFrac,stillSharpnessMin:S(n.stillSharpnessMin,0,10)??t.stillSharpnessMin,stillRefusalsMax:S(n.stillRefusalsMax,0,10)??t.stillRefusalsMax,focusFarFillFrac:S(n.focusFarFillFrac,0,1)??t.focusFarFillFrac,noDocFarHintMs:S(n.noDocFarHintMs,0,6e4)??t.noDocFarHintMs,zoomFallbackMs:S(n.zoomFallbackMs,0,12e4)??t.zoomFallbackMs}}function Ye(e){let t=e.toLowerCase();return t===""?"unknown":/front|facing front|user|selfie|face ?time/.test(t)?"front":/ultra|0\.5x|wide angle/.test(t)?"ultra":/tele|zoom|periscope|[2-9]x/.test(t)?"tele":/depth|tof|infrared|\bir\b|truedepth|lidar|macro|monochrome|mono\b/.test(t)?"depth":/dual|triple/.test(t)?"virtual":/back|rear|environment|facing back|arrière|خلفية/.test(t)?"main":"unknown"}function Ze(e){let t=/camera2?\s*(\d+)/i.exec(e);return t?Number(t[1]):Number.POSITIVE_INFINITY}function Je(e){let t={main:0,virtual:1,ultra:9,tele:9,depth:9,front:9,unknown:9};return e.filter(n=>(n.kind===void 0||n.kind==="videoinput")&&n.deviceId!=="").map((n,i)=>({id:n.deviceId,kind:Ye(n.label),index:Ze(n.label),i})).filter(n=>t[n.kind]<9).sort((n,i)=>t[n.kind]-t[i.kind]||n.index-i.index||n.i-i.i).map(n=>n.id)}var pt="sekyro.doc.camera";function $e(){try{let e=globalThis.localStorage?.getItem(pt);return typeof e=="string"&&e!==""?e:null}catch{return null}}function ye(e){try{e===null?globalThis.localStorage?.removeItem(pt):globalThis.localStorage?.setItem(pt,e)}catch{}}var rt=(e,t)=>Array.isArray(e?.focusMode)&&e.focusMode.includes(t);function bt(e,t,n){if(!rt(e,"single-shot"))return null;let i=o=>Math.min(1,Math.max(0,Number.isFinite(o)?o:.5));return{focusMode:"single-shot",pointsOfInterest:[{x:i(t),y:i(n)}]}}function xi(e,t,n,i){if(!Number.isFinite(e)||!Number.isFinite(t)||n.width<=0||n.height<=0||i.width<=0||i.height<=0)return null;let o=Math.max(n.width/i.width,n.height/i.height),s=i.width*o,r=i.height*o,c=(e-n.left+(s-n.width)/2)/s,a=(t-n.top+(r-n.height)/2)/r;return{x:Math.min(1,Math.max(0,c)),y:Math.min(1,Math.max(0,a))}}function ke(e,t,n,i=st){let o=e?.zoom?.min,s=e?.zoom?.max;if(typeof s!="number"||s<=1)return 1;let r=n==="ID-3"?i.fillDistanceM.id3:i.fillDistanceM.id1,c=e?.focusDistance?.min,a;if(typeof c=="number"&&c>0&&c<1){if(a=c*(1+i.focusMarginFrac)/r,a<=1.05)return 1}else{if(Math.min(t.width,t.height)<i.zoomMinSourcePx)return 1;a=i.zoomNoFocusInfo}let l=Math.min(a,i.zoomMax,s);typeof o=="number"&&(l=Math.max(l,o));let u=e?.zoom?.step;return typeof u=="number"&&u>0&&(l=Math.round(l/u)*u),l>1.01?Number(l.toFixed(2)):1}function gt(e){try{return e.getVideoTracks?.()[0]}catch{return}}function Me(e){if(e!==null)for(let t of e.getTracks())t.stop()}function qe(e){try{let t=gt(e)?.getCapabilities?.();return!Array.isArray(t?.focusMode)||t.focusMode.includes("continuous")}catch{return!0}}var ti=3;async function xe(e){let t=s=>({audio:!1,video:{...s,width:{ideal:e.base.width},height:{ideal:e.base.height}}}),n=s=>e.getUserMedia(t({deviceId:{exact:s}})),i=()=>e.getUserMedia(t({facingMode:{ideal:"environment"}}));if(e.lensSelection){let s=$e();if(s!==null)try{return{stream:await n(s),lens:"stored"}}catch{ye(null)}}let o=await i();if(!e.lensSelection||e.enumerateDevices===void 0)return{stream:o,lens:"default"};try{let s=Je(await e.enumerateDevices()).slice(0,ti);if(s.length===0)return{stream:o,lens:"default"};let r=null;for(let c of s){let a=o!==null?gt(o)?.getSettings?.().deviceId:void 0;if(o===null||a!==c){Me(o),o=null;try{o=await n(c)}catch{continue}}if(r??(r=c),qe(o))return ye(c),{stream:o,lens:"selected"}}if(o!==null&&r!==null&&gt(o)?.getSettings?.().deviceId===r)return{stream:o,lens:"selected"};if(Me(o),o=null,r!==null)try{return{stream:await n(r),lens:"selected"}}catch{}return{stream:await i(),lens:"default"}}catch{return{stream:o??await i(),lens:"default"}}}var Z=Object.freeze({brightness:0,glare:0,cardGlare:0,sharpness:0,fill:0,shape:0,content:0,offsetX:0,offsetY:0,edgeConfidence:0,box:null}),I=e=>Math.min(1,Math.max(0,e));function we(e,t,n,i=.06){let o=Math.max(e.width/n,e.height),s=o*n,r=(e.width-s)/2,c=(e.height-o)/2,a=I((t.x-t.width*i-r)/s),l=I((t.y-t.height*i-c)/o),u=I((t.x+t.width*(1+i)-r)/s),d=I((t.y+t.height*(1+i)-c)/o);return{x:a,y:l,width:u-a,height:d-l}}function ve(e,t,n={}){let i=n.edgePeakFrac??0,{width:o,height:s,data:r}=e;if(o<=0||s<=0)return Z;let c=I(t.x),a=I(t.y),l={x:c,y:a,width:Math.max(0,I(t.x+t.width)-c),height:Math.max(0,I(t.y+t.height)-a)};if(l.width<=0||l.height<=0)return Z;let u=l.x*o,d=l.y*s,m=(l.x+l.width)*o,h=(l.y+l.height)*s,f=(m-u)*.15,g=(h-d)*.15,y=(p,b,T)=>Math.min(T,Math.max(b,p)),x=y(Math.floor(u-f),0,o-1),w=y(Math.floor(d-g),0,s-1),E=y(Math.ceil(m+f),x+1,o),v=y(Math.ceil(h+g),w+1,s),D=Math.max(1,Math.ceil(Math.max(E-x,v-w)/320)),M=Math.floor((E-x+D-1)/D),_=Math.floor((v-w+D-1)/D);if(M<3||_<3)return Z;let k=new Int32Array(M*_);for(let p=0;p<_;p++){let b=w+p*D;for(let T=0;T<M;T++){let C=(b*o+x+T*D)*4;k[p*M+T]=(r[C]??0)*77+(r[C+1]??0)*150+(r[C+2]??0)*29>>8}}let F=(p,b)=>(p-b-.5)/D,R=F(u,x),A=F(m,x),B=F(d,w),U=F(h,w),Mt=(m-u)/D,kt=(h-d)/D,xt=y(Math.ceil(R),0,M-1),Ce=y(Math.floor(A),xt,M-1),Dt=y(Math.ceil(B),0,_-1),Fe=y(Math.floor(U),Dt,_-1),wt=0,vt=0,H=0,St=0,_t=0,K=0;for(let p=Dt;p<=Fe;p++)for(let b=xt;b<=Ce;b++){let T=k[p*M+b];if(wt+=T,T>=248&&vt++,H++,b>=1&&b<M-1&&p>=1&&p<_-1){let C=k[p*M+b-1]+k[p*M+b+1]+k[(p-1)*M+b]+k[(p+1)*M+b]-4*T;St+=C,_t+=C*C,K++}}let Ae=H>0?wt/H:0,Rt=H>0?vt/H:0,Tt=K>0?St/K:0,Le=K>0?Math.max(0,_t/K-Tt*Tt):0,V=new Float64Array(M),W=new Float64Array(_);for(let p=0;p<_;p++)for(let b=1;b<M-1;b++)V[b]=V[b]+Math.abs(k[p*M+b+1]-k[p*M+b-1]);for(let p=1;p<_-1;p++)for(let b=0;b<M;b++)W[p]=W[p]+Math.abs(k[(p+1)*M+b]-k[(p-1)*M+b]);let O=at(V,!0,R,i),P=at(V,!1,A,i),G=at(W,!0,B,i),z=at(W,!1,U,i),Ct=(P.position-O.position)/Mt,Ft=(z.position-G.position)/kt,Ie=Ft>0?Ct/Ft:0,Ee=((O.position+P.position)/2-(R+A)/2)/Mt,Oe=((G.position+z.position)/2-(B+U)/2)/kt,At=De(V),Lt=De(W),Pe=At<=0||Lt<=0?0:Math.min(Math.min(O.value,P.value)/At,Math.min(G.value,z.value)/Lt),q=(p,b)=>b+(p+.5)*D,It=Rt,Et=0;{let p=(P.position-O.position)*.06,b=(z.position-G.position)*.06,T=y(Math.ceil(O.position+p),0,M-1),C=y(Math.floor(P.position-p),0,M-1),Ge=y(Math.ceil(G.position+b),0,_-1),Ot=y(Math.floor(z.position-b),0,_-1),Pt=0,tt=0,Gt=0;for(let N=Ge;N<=Ot;N++)for(let Q=T;Q<=C;Q++){tt++;let X=k[N*M+Q];X>=248&&Pt++;let ze=Q+2<=C?k[N*M+Q+2]:X,Ne=N+2<=Ot?k[(N+2)*M+Q]:X;(Math.abs(ze-X)>=24||Math.abs(Ne-X)>=24)&&Gt++}tt>=16&&(It=Pt/tt,Et=Gt/tt)}return{brightness:Ae,glare:Rt,cardGlare:It,sharpness:Le,fill:Ct,shape:Ie,content:Et,offsetX:Ee,offsetY:Oe,edgeConfidence:Pe,box:{left:q(O.position,x),right:q(P.position,x),top:q(G.position,w),bottom:q(z.position,w)}}}function at(e,t,n,i){let o=e.length,s=Math.max(1,Math.floor(o*.45)),r=t?1:Math.max(1,o-1-s),c=t?Math.min(o-2,s):o-2,a=r;for(let h=r;h<=c;h++)e[h]>e[a]&&(a=h);if(i>0&&i<1){let h=e[a]*i,f=a,g=Math.abs(a-n);for(let y=r;y<=c;y++){let x=e[y];if(x<h||x<(e[y-1]??0)||x<(e[y+1]??0))continue;let w=Math.abs(y-n);w<g&&(f=y,g=w)}a=f}let l=a>0?e[a-1]:0,u=e[a],d=a<o-1?e[a+1]:0,m=l+u+d;return{position:m>0?a+(d-l)/m:a,value:u}}function De(e){if(e.length<3)return 0;let t=0;for(let n=1;n<e.length-1;n++)t+=e[n];return t/(e.length-2)}function Se(e){let t=e.box;return t===null||t.right-t.left<4||t.bottom-t.top<4?null:{topLeft:{x:t.left,y:t.top},topRight:{x:t.right,y:t.top},bottomRight:{x:t.right,y:t.bottom},bottomLeft:{x:t.left,y:t.bottom}}}var J=Object.freeze({fillMin:.82,fillMax:1.06,offsetMax:.06,glareMax:.025,sharpnessMin:180,edgeConfidenceMin:1.6,darkBrightness:70,lockMs:450,steadyMs:900,steadyFillMin:.45,steadyFillMax:1.3,steadyFillDelta:.06,steadyOffsetDelta:.04,steadyRefMs:100,edgePeakFrac:.4,shapeTolerance:.2,contentMin:.1});function wi(e){let t=e!==null&&typeof e=="object"?e:{},n={...J};for(let i of Object.keys(J)){let o=t[i];typeof o=="number"&&Number.isFinite(o)&&o>=0&&o<=1e6&&(n[i]=o)}return n}var ct=class{constructor(t=J){this.t=t;this.goodSince=null;this.steadySince=null;this.last=null}reset(){this.goodSince=null,this.steadySince=null,this.last=null}tick(t,n){let i=this.t,o=i.shapeTolerance<=0||Math.abs(t.shape-1)<=i.shapeTolerance,s=t.edgeConfidence>=i.edgeConfidenceMin&&o&&t.content>=i.contentMin,r=t.fill>=i.fillMin&&t.fill<=i.fillMax,c=Math.abs(t.offsetX)<=i.offsetMax&&Math.abs(t.offsetY)<=i.offsetMax,a=t.cardGlare<=i.glareMax,l=t.sharpness>=i.sharpnessMin,u=this.last;this.last={fill:t.fill,offsetX:t.offsetX,offsetY:t.offsetY,at:n};let d=u!==null&&i.steadyRefMs>0?Math.min(3,Math.max(1,(n-u.at)/i.steadyRefMs)):1,m=s&&a&&l&&t.fill>=i.steadyFillMin&&t.fill<=i.steadyFillMax&&u!==null&&Math.abs(t.fill-u.fill)<=i.steadyFillDelta*d&&Math.abs(t.offsetX-u.offsetX)<=i.steadyOffsetDelta*d&&Math.abs(t.offsetY-u.offsetY)<=i.steadyOffsetDelta*d,h=s&&r&&c&&a&&l,f;if(s?a?t.fill<i.fillMin?f="too_small":t.fill>i.fillMax?f="too_big":l?c?f="locking":f="off_center":f="blurry":f="glare":f="no_card",h){if(m&&(this.steadySince??(this.steadySince=n)),this.goodSince??(this.goodSince=n),n-this.goodSince>=i.lockMs)return{detected:s,ready:!0,via:"good",blocker:"locking"};let g=this.steadySince!==null&&n-this.steadySince>=i.steadyMs;return{detected:s,ready:g,via:g?"steady":null,blocker:"locking"}}if(this.goodSince=null,m){this.steadySince??(this.steadySince=n);let g=n-this.steadySince>=i.steadyMs;return{detected:s,ready:g,via:g?"steady":null,blocker:g?"locking":"steadying"}}return this.steadySince=null,{detected:s,ready:!1,via:null,blocker:f}}};var $=null;async function ei(e){return $===null&&($=(await import("./detector-scanic-YCDNLCGV.js")).detectQuad),$(e)}async function ii(e){let t=jt(e);return t===null?null:{topLeft:{x:t.x,y:t.y},topRight:{x:t.x+t.width,y:t.y},bottomRight:{x:t.x+t.width,y:t.y+t.height},bottomLeft:{x:t.x,y:t.y+t.height}}}function Ni(){$===null&&import("./detector-scanic-YCDNLCGV.js").then(e=>{$=e.detectQuad}).catch(()=>{})}var ni=Object.freeze({LOW:3,MID:5,HIGH:6}),yt=Object.freeze({manualShutterMs:6e3,detectedNoLockMs:1950});function Qi(e){let t=e!==null&&typeof e=="object"?e:{},n=(i,o,s)=>typeof i=="number"&&Number.isFinite(i)&&i>=o&&i<=s?i:void 0;return{manualShutterMs:n(t.manualShutterMs,1e3,6e4)??yt.manualShutterMs,detectedNoLockMs:n(t.steadyMs,300,3e4)!==void 0?t.steadyMs+(n(t.lockMs,0,1e4)??450):yt.detectedNoLockMs}}var _e=class e{constructor(t){this.torchOn=!1;this.stillRefusals=0;this.zoom=1;this.positioningSince=null;this.detectedSince=null;this.lastSeenAt=null;this.lastGuideQuad=null;this.lastOcrReady=null;this.shutterOffered=!1;this.stats=e.freshStats();this.handlers=new Map;this.stream=null;this.timer=null;this.state="idle";this.lastGuidance=null;this.attempt=0;this.capturing=!1;this.feedback=new nt;this.lastFeedbackKey=null;this.lastQuad=null;this.lastDetect=null;this.opts=t,this.gate=new $t(t.format??"ID-1",t.thresholds);let n=t.deviceClass??Bt(Qt());this.deviceClass=n,this.camera=t.camera??st,this.shutterTuning=t.shutter??yt,this.guideTuning=t.guideLock??J,this.guideLock=new ct(this.guideTuning),this.cadenceMs=1e3/ni[n]}on(t,n){let i=this.handlers.get(t);return i||(i=new Set,this.handlers.set(t,i)),i.add(n),()=>i?.delete(n)}emit(t,n){for(let i of[...this.handlers.get(t)??[]])i(n)}async start(){let t=++this.attempt;this.gate.reset(),this.resetSide(),this.feedback.reset(),this.lastFeedbackKey=null,this.lastGuidance=null,this.capturing=!1,this.setState("preflight");try{let n=this.opts.getUserMedia??(s=>navigator.mediaDevices.getUserMedia(s));this.setState("acquiring");let i=this.opts.enumerateDevices??(this.opts.getUserMedia===void 0&&typeof navigator<"u"&&navigator.mediaDevices?.enumerateDevices?()=>navigator.mediaDevices.enumerateDevices():void 0),o=await xe({getUserMedia:n,...i!==void 0?{enumerateDevices:i}:{},lensSelection:this.camera.lensSelection,base:oe});if(this.stream=o.stream,Nt(this.stream),t!==this.attempt){for(let s of this.stream.getTracks())s.stop();return}if(this.opts.upgradeResolution!==!1&&await this.upgradeResolution(),t!==this.attempt||(await this.applyFocusAndZoom(),t!==this.attempt))return;this.opts.video.srcObject=this.stream,await this.opts.video.play().catch(()=>{}),this.setState("positioning"),this.scheduleTick(t)}catch(n){let i=zt(n);this.setState("error"),this.emit("error",{kind:i,retryable:!0})}}rearm(t){t!==void 0&&(this.opts.side=t),this.gate.reset(),this.resetSide(),this.feedback.reset(),this.lastFeedbackKey=null,this.lastGuidance=null,this.capturing=!1,this.stillRefusals=0,this.state==="captured"&&(this.setState("positioning"),this.scheduleTick(this.attempt))}async captureNow(){if(this.state!=="positioning"||this.capturing)return;let t=this.opts.video,n=this.lastDetect?.width??Math.max(1,t.videoWidth),i=this.lastDetect?.height??Math.max(1,t.videoHeight),o=this.lastQuad??this.lastGuideQuad??{topLeft:{x:0,y:0},topRight:{x:n,y:0},bottomRight:{x:n,y:i},bottomLeft:{x:0,y:i}},s=(this.opts.now??(()=>performance.now()))(),r=this.feedback.force("processing",s);this.lastFeedbackKey=r.key,this.emit("feedback",r),await this.fire(this.attempt,this.lastOcrReady!==null?this.lastOcrReady.quad:o,{width:n,height:i,tickSharpness:this.lastDetect?.tickSharpness??0},this.lastOcrReady?.via??"manual")}captureReport(){let t=this.stats;return{...this.opts.side!==void 0?{side:this.opts.side}:{},format:this.opts.format??"ID-1",deviceClass:this.deviceClass,video:{width:this.opts.video.videoWidth||0,height:this.opts.video.videoHeight||0},zoom:this.zoom,...t.zoomFallbackAtMs!==void 0?{zoomFallbackAtMs:t.zoomFallbackAtMs}:{},...t.msToCapture!==void 0?{msToCapture:t.msToCapture}:{},...t.via!==void 0?{via:t.via}:{},...t.shutterAtMs!==void 0?{shutterAtMs:t.shutterAtMs}:{},...t.shutterReason!==void 0?{shutterReason:t.shutterReason}:{},ticks:t.ticks,quadFraming:{...t.quadFraming},qualityBlockers:{...t.qualityBlockers},guideBlockers:{...t.guideBlockers},stillRefusals:t.stillRefusals,...this.ocrReport()}}ocrReport(){let t=this.opts.ocr;if(t===void 0)return{};let n=(this.opts.format??"ID-1")==="ID-3"||this.opts.side==="single"?"single":this.opts.side==="verso"?"verso":"recto",i=t.report(n,this.stats.via,(this.opts.now??(()=>performance.now()))());return i===null?{}:{ocr:i}}static freshStats(){return{ticks:0,quadFraming:{},qualityBlockers:{},guideBlockers:{},stillRefusals:0}}setGuide(t){t===void 0?delete this.opts.guide:this.opts.guide=t,this.guideLock.reset()}guideRegion(t){let n=t.width/Math.max(1,t.height),i=this.opts.guide;if(i!==void 0&&i.viewAspect>0){let c={width:i.viewAspect,height:1},a={x:i.rect.x*i.viewAspect,y:i.rect.y,width:i.rect.width*i.viewAspect,height:i.rect.height};return we(c,a,n,0)}let o=Kt(this.opts.format??"ID-1").center,s=.86,r=s*n/o;return r>.84&&(r=.84,s=r*o/n),{x:(1-s)/2,y:(1-r)/2,width:s,height:r}}resetSide(){this.positioningSince=null,this.detectedSince=null,this.lastSeenAt=null,this.guideLock.reset(),this.lastGuideQuad=null,this.lastOcrReady=null,this.opts.ocr?.reset(),this.stats=e.freshStats(),this.shutterOffered&&(this.shutterOffered=!1,this.emit("shutter",{available:!1}))}withdrawShutter(){this.shutterOffered&&(this.shutterOffered=!1,this.emit("shutter",{available:!1}))}zoomFallback(t){let n=this.videoTrack();if(n===null||this.zoom<=1)return;let i=this.focusCaps(),o=typeof i?.zoom?.min=="number"?Math.max(i.zoom.min,1):1;this.zoom=o,this.stats.zoomFallbackAtMs=Math.round(t-(this.positioningSince??t)),this.guideLock.reset(),this.gate.reset(),n.applyConstraints({advanced:[{zoom:o}]}).catch(()=>{})}offerShutter(t,n){this.shutterOffered||(this.shutterOffered=!0,this.stats.shutterAtMs=Math.round(n-(this.positioningSince??n)),this.stats.shutterReason=t,this.emit("shutter",{available:!0,reason:t}))}torchAvailable(){try{return this.stream?.getVideoTracks?.()[0]?.getCapabilities?.()?.torch===!0}catch{return!1}}async setTorch(t){this.torchOn=t;try{await this.stream?.getVideoTracks?.()[0]?.applyConstraints({advanced:[{torch:t}]})}catch{}}destroy(){if(this.attempt+=1,this.timer!==null&&(this.opts.clearTimer??clearTimeout)(this.timer),this.timer=null,this.stream)for(let t of this.stream.getTracks())t.stop();this.stream=null,this.opts.video.srcObject=null}async upgradeResolution(){try{let t=this.stream?.getVideoTracks?.()[0];if(t===void 0)return;let n=t.getSettings?.()??{},i=ae(t.getCapabilities?.(),{width:n.width??0,height:n.height??0},this.deviceClass,{width:this.camera.width,height:this.camera.height});i!==null&&await t.applyConstraints(i)}catch{}}focusCaps(){try{return this.videoTrack()?.getCapabilities?.()??null}catch{return null}}async applyFocusAndZoom(){let t=this.videoTrack();if(t===null)return;let n=this.focusCaps();this.camera.continuousFocus&&rt(n,"continuous")&&await t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{});let i={width:0,height:0};try{let s=t.getSettings?.()??{};i={width:s.width??0,height:s.height??0}}catch{}let o=ke(n,i,this.opts.format??"ID-1",this.camera);if(o>1)try{await t.applyConstraints({advanced:[{zoom:o}]}),this.zoom=o}catch{this.zoom=1}}async focusAt(t,n){let i=this.videoTrack(),o=bt(this.focusCaps(),t,n);if(!(i===null||o===null))try{await i.applyConstraints({advanced:[o]}),(this.opts.setTimer??setTimeout)(()=>{this.restoreContinuous()},1500)}catch{}}async restoreContinuous(){let t=this.videoTrack();t===null||!this.camera.continuousFocus||!rt(this.focusCaps(),"continuous")||await t.applyConstraints({advanced:[{focusMode:"continuous"}]}).catch(()=>{})}async refocusOn(t,n){let i=this.camera.refocusBeforePhotoMs,o=this.videoTrack();if(i<=0||o===null||n.width<=0||n.height<=0)return;let s=L(t),r=bt(this.focusCaps(),(s.x+s.width/2)/n.width,(s.y+s.height/2)/n.height);if(r!==null)try{await o.applyConstraints({advanced:[r]});let c=this.opts.setTimer??setTimeout;await new Promise(a=>{c(()=>a(),i)})}catch{}}videoTrack(){try{return this.stream?.getVideoTracks?.()[0]??null}catch{return null}}async takeStill(t,n,i){if(this.opts.captureStill!==void 0)return this.opts.captureStill(this.opts.video,t,n);let o=this.opts.format??"ID-1",s=this.videoTrack();if(i&&this.opts.photoCapture!==!1&&this.deviceClass!=="LOW"&&!this.torchOn&&s!==null&&fe(s)){await this.refocusOn(t,n);let r=await be(this.opts.video,t,n,o,{track:s,detect:this.detector(),detectWidth:et});if(this.restoreContinuous(),r!==null)return r}return ge(this.opts.video,t,n,o)}detector(){return this.opts.detect??((this.opts.format??"ID-1")==="ID-3"?ii:ei)}setState(t){this.state=t,this.emit("statechange",{state:t})}scheduleTick(t){let n=this.opts.setTimer??setTimeout;this.timer=n(()=>{this.tick(t)},this.cadenceMs)}async tick(t){if(t!==this.attempt||this.state!=="positioning"||this.capturing)return;let n=this.opts.now??(()=>performance.now()),i=this.opts.grabDetectFrame??Te,o=this.detector(),s=i(this.opts.video,et);if(s===null){this.scheduleTick(t);return}let r=null;try{r=await o(s)}catch{r=null}if(t!==this.attempt)return;let c=r!==null?lt(s,r):s,a=n(),l={sharpness:j(c),exposure:Ht(c),meanLuma:Ut(c),specularFraction:ee(c)},u=ie({format:this.opts.format??"ID-1",quad:r,frameWidth:s.width,frameHeight:s.height,measures:l,...this.opts.thresholds!==void 0?{thresholds:this.opts.thresholds}:{}}),d=this.gate.tick({timestampMs:a,quad:r,quality:l,frameWidth:s.width,frameHeight:s.height}),h=(this.opts.format??"ID-1")!=="ID-3"?ve(s,this.guideRegion(s),{edgePeakFrac:this.guideTuning.edgePeakFrac}):Z,f=this.guideLock.tick(h,a);this.lastGuideQuad=f.detected?Se(h):null;let g=this.capturing?null:this.ocrTick(s,r,h,f.detected,u,a);this.positioningSince??(this.positioningSince=a);let y=this.stats;if(y.ticks+=1,y.quadFraming[u.framing]=(y.quadFraming[u.framing]??0)+1,u.framing==="ok"&&!d.ready){let R=u.lighting!=="ok"?u.lighting:u.glare!=="ok"?"glare":u.blur!=="ok"?"blurry":"steadying";y.qualityBlockers[R]=(y.qualityBlockers[R]??0)+1}y.guideBlockers[f.blocker]=(y.guideBlockers[f.blocker]??0)+1,r!==null||f.detected?(this.detectedSince??(this.detectedSince=a),this.lastSeenAt=a):this.detectedSince=null,this.lastSeenAt!==null&&a-this.lastSeenAt<=ui?a-this.positioningSince>=this.shutterTuning.manualShutterMs?this.offerShutter("timeout",a):g?.suspendQuality!==!0&&this.detectedSince!==null&&a-this.detectedSince>=this.shutterTuning.detectedNoLockMs&&this.offerShutter("detected_no_lock",a):this.withdrawShutter();let E=a-(this.lastSeenAt??this.positioningSince);this.zoom>1&&this.camera.zoomFallbackMs>0&&E>=this.camera.zoomFallbackMs&&this.zoomFallback(a),this.emit("checks",{engine:"docv1",p:d.p,plausible:d.plausible,stableTicks:d.stableTicks,quad:d.quad,frameWidth:s.width,frameHeight:s.height,analysis:u,ready:g?.suspendQuality!==!0&&(d.ready&&r!==null||f.ready&&this.lastGuideQuad!==null)||this.lastOcrReady!==null,guide:{detected:f.detected,blocker:f.blocker,fill:h.fill,shape:h.shape,content:h.content,offsetX:h.offsetX,offsetY:h.offsetY},...g!==null&&g.mode!=="off"?{ocr:{mode:g.mode,...g.mrz?{mrz:g.mrz}:{},...g.lock?{lock:g.lock}:{}}}:g?.mrz?{ocr:{mode:g.mode,mrz:g.mrz}}:{}}),this.lastQuad=d.plausible?r:null,this.lastDetect={width:s.width,height:s.height,tickSharpness:l.sharpness};let v=qt(u);u.framing!=="ok"&&f.detected&&(v=li(f.blocker,h.brightness<this.guideTuning.darkBrightness)),v==="blurry"&&r!==null&&si(r,s,this.opts.format??"ID-1")>=this.camera.focusFarFillFrac&&(v="focus_far"),v==="sensing"&&this.zoom>1&&this.camera.noDocFarHintMs>0&&E>=this.camera.noDocFarHintMs&&(v="focus_far");let D=this.feedback.tick(v,a);if(D.key!==this.lastFeedbackKey&&(this.lastFeedbackKey=D.key,this.emit("feedback",D)),d.guidanceKey!==this.lastGuidance&&(this.lastGuidance=d.guidanceKey,this.emit("guidance",{key:d.guidanceKey})),this.capturing)return;let M=g?.suspendQuality!==!0,_=M&&d.ready&&r!==null,k=M&&f.ready&&this.lastGuideQuad!==null,F=this.lastOcrReady;if(F!==null&&this.opts.autoCapture!==!1){let R=this.feedback.force("processing",a);this.lastFeedbackKey=R.key,this.emit("feedback",R);let A=j(lt(s,F.quad));await this.fire(t,F.quad,{width:s.width,height:s.height,tickSharpness:A},F.via);return}if((_||k)&&this.opts.autoCapture!==!1){let R=this.feedback.force("processing",a);this.lastFeedbackKey=R.key,this.emit("feedback",R);let A=k?this.lastGuideQuad:r,B=k?f.via==="steady"?"guide_steady":"guide_good":"quad",U=k?j(lt(s,A)):l.sharpness;await this.fire(t,A,{width:s.width,height:s.height,tickSharpness:U},B);return}this.scheduleTick(t)}async fire(t,n,i,o){this.capturing=!0;let s=this.opts.grabDetectFrame??Te,r=this.opts.setTimer??setTimeout,c={width:i.width,height:i.height};try{let a={still:await this.takeStill(n,c,!0),sharpness:i.tickSharpness};if(t!==this.attempt)return;let l=a.still.source==="photo"?0:ri;for(let m=0;m<l;m++){if(await new Promise(g=>{r(()=>g(),ai)}),t!==this.attempt)return;let h=s(this.opts.video,et);if(h===null)continue;let f=j(lt(h,n));if(f>a.sharpness*ci){let g=await this.takeStill(n,c,!1);if(t!==this.attempt)return;a={still:g,sharpness:f}}}if(t!==this.attempt)return;let u=a.still.sharpness;if(this.opts.autoCapture!==!1&&o!=="manual"&&typeof u=="number"&&u>=0&&u<this.camera.stillSharpnessMin&&this.stillRefusals<this.camera.stillRefusalsMax){this.stillRefusals+=1,this.stats.stillRefusals+=1,this.guideLock.reset(),this.lastOcrReady=null,(o==="text_lock"||o==="live_mrz")&&this.opts.ocr?.rearmFace();let m=(this.opts.now??(()=>performance.now()))(),h=this.feedback.force("focus_far",m);this.lastFeedbackKey=h.key,this.emit("feedback",h),this.capturing=!1,this.gate.reset(),this.scheduleTick(t);return}this.stillRefusals=0;let d=(this.opts.now??(()=>performance.now()))();this.stats.via=o,this.stats.msToCapture=Math.round(d-(this.positioningSince??d)),this.shutterOffered&&(this.shutterOffered=!1,this.emit("shutter",{available:!1})),this.setState("captured"),this.emit("artifacts",{keyframe:a.still.blob,previewDataUrl:a.still.previewDataUrl,...this.opts.side!==void 0?{side:this.opts.side}:{},...a.still.docRegion!==void 0?{docRegion:a.still.docRegion}:{},...(()=>{let m=o==="live_mrz"?this.opts.ocr?.liveCapture():null;return m?{liveMrz:m}:{}})()})}catch{if(t!==this.attempt)return;this.capturing=!1,this.gate.reset(),this.guideLock.reset(),this.lastOcrReady=null,(o==="text_lock"||o==="live_mrz")&&this.opts.ocr?.rearmFace(),this.scheduleTick(t)}}ocrTick(t,n,i,o,s,r){let c=this.opts.ocr,a=this.opts.video;if(c===void 0||!c.hasEngine)return this.lastOcrReady=null,null;let l=a.videoWidth,u=a.videoHeight;if(l<=0||u<=0||t.width<=0||t.height<=0)return null;let m=(this.opts.format??"ID-1")==="ID-3",h=this.guideRegion(t),f={x:h.x*l,y:h.y*u,w:h.width*l,h:h.height*u},g=l/t.width,y=u/t.height,x;m&&n!==null?x=oi(L(n),g,y,l,u):x=Yt(f,c.bandTop,u);let w=m?s.glare==="ok":i.cardGlare<=this.guideTuning.glareMax,E=m?s.blur==="ok":i.sharpness>=this.guideTuning.sharpnessMin,v=c.tick({atMs:r,video:a,mrzFace:m||this.opts.side==="verso"||this.opts.side==="single",present:m||n!==null||o,card:f,band:x,portrait:u>l,glareOk:w,sharpOk:E});if(v.ready&&v.via!==void 0){let D=m?n??Re(h,t):this.lastGuideQuad??Re(h,t);this.lastOcrReady={quad:D,via:v.via}}else this.lastOcrReady=null;return v}};function oi(e,t,n,i,o){let s=Math.min(i,e.width*1.06*t),r=Math.min(o,Math.max(e.height*1.6*n,s/5)),c=(e.y+e.height/2)*n,a=Math.max(0,Math.min(i-s,(e.x-e.width*.03)*t)),l=Math.max(0,Math.min(o-r,c-r/2));return{x:a,y:l,w:s,h:r}}function Re(e,t){let n=e.x*t.width,i=e.y*t.height,o=(e.x+e.width)*t.width,s=(e.y+e.height)*t.height;return{topLeft:{x:n,y:i},topRight:{x:o,y:i},bottomRight:{x:o,y:s},bottomLeft:{x:n,y:s}}}function si(e,t,n){let i=L(e);return t.width<=0||t.height<=0?0:n==="ID-3"?i.width/t.width:i.width*i.height/(t.width*t.height)}var ri=2,ai=260,ci=1.08;function Te(e,t){let n=e.videoWidth,i=e.videoHeight;if(n===0||i===0)return null;let o=Math.min(1,t/n),s=Math.round(n*o),r=Math.round(i*o),c=document.createElement("canvas");c.width=s,c.height=r;let a=c.getContext("2d",{willReadFrequently:!0});return a===null?null:(n/Math.max(1,s)>4&&(a.imageSmoothingQuality="high"),a.drawImage(e,0,0,s,r),a.getImageData(0,0,s,r))}function lt(e,t){let n=[t.topLeft.x,t.topRight.x,t.bottomRight.x,t.bottomLeft.x],i=[t.topLeft.y,t.topRight.y,t.bottomRight.y,t.bottomLeft.y],o=Math.max(0,Math.floor(Math.min(...n))),s=Math.max(0,Math.floor(Math.min(...i))),r=Math.min(e.width,Math.ceil(Math.max(...n))),c=Math.min(e.height,Math.ceil(Math.max(...i))),a=Math.max(1,r-o),l=Math.max(1,c-s),u=new Uint8ClampedArray(a*l*4);for(let d=0;d<l;d++){let m=((s+d)*e.width+o)*4;u.set(e.data.subarray(m,m+a*4),d*a*4)}return{data:u,width:a,height:l,colorSpace:e.colorSpace}}function li(e,t){return e==="glare"?"glare":e==="too_small"?"too_far":e==="too_big"?"too_close":t?"too_dark":e==="blurry"?"blurry":e==="off_center"?"edge_clipped":e==="no_card"?"sensing":"hold_still"}var ui=1200;export{it as a,qt as b,nt as c,Qe as d,ee as e,Be as f,ie as g,st as h,ki as i,Ye as j,Je as k,pt as l,$e as m,ye as n,rt as o,bt as p,xi as q,ke as r,qe as s,ti as t,xe as u,Z as v,we as w,ve as x,Se as y,J as z,wi as A,ct as B,Ni as C,ni as D,yt as E,Qi as F,_e as G,oi as H,ri as I,ai as J};
@@ -1,357 +1 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/client/index.ts
21
- var client_exports = {};
22
- __export(client_exports, {
23
- HostedApiError: () => HostedApiError,
24
- HostedClient: () => HostedClient,
25
- KNOWN_CODES: () => KNOWN_CODES,
26
- isKnownCode: () => isKnownCode,
27
- stripMimeParams: () => stripMimeParams
28
- });
29
- module.exports = __toCommonJS(client_exports);
30
-
31
- // src/client/errors.ts
32
- var KNOWN_CODES = [
33
- // auth / addressing (session-token.guard, controllers' own-session guards)
34
- "session_token_invalid",
35
- // 401 — missing/invalid/expired/revoked token
36
- "session_token_required",
37
- // 403 — non-session-token principal on a hosted route (defensive)
38
- "session_token_session_mismatch",
39
- // 403 — route :id differs from the token's bound session
40
- "session_not_found",
41
- // 404 — token's session missing/foreign (findOwned)
42
- // rate limiting (session-token.guard — per-token + per-IP buckets)
43
- "rate_limit_exceeded",
44
- // 429 + Retry-After header (seconds)
45
- // consent gate (Task 0 — submit AND media presign/complete)
46
- "consent_required",
47
- // 409 — record consent before uploading/submitting
48
- // submit flow (sessions.service.submitCheck)
49
- "session_not_active",
50
- // 409 — session is terminal/review; no further submissions
51
- "check_not_found",
52
- // 404 — session has no such checkType
53
- "check_already_finalized",
54
- // 409 — re-submit of a terminal/review check
55
- "check_out_of_order",
56
- // 409 — only the frontier check accepts a submission
57
- "check_type_unsupported",
58
- // 400 — no registered executor for the checkType
59
- "force_outcome_forbidden",
60
- // 403 — forceOutcome on a live session (plan D-C)
61
- "attestation_invalid",
62
- // 400 (Task 1) — Turnstile/attestation failed; reload and retry
63
- "nni_locked",
64
- // 409 (Plan A Task 2) — session is bound to a server-provided NNI; a different client NNI was sent
65
- // media (media.service)
66
- "media_content_type_not_allowed",
67
- // 400 — outside the per-kind MIME allowlist
68
- "media_too_large",
69
- // 413 — over the per-kind byte cap
70
- "media_key_invalid",
71
- // 400 — not a well-formed pending key
72
- "media_key_forbidden",
73
- // 403 — key names another session's pending space
74
- "media_not_found",
75
- // 404 — no uploaded object behind the key
76
- "media_unreadable",
77
- // 422 — magic-byte sniff rejected the object
78
- "media_session_invalid",
79
- // 400 — sessionId unusable as a key segment (never in practice)
80
- // idempotency (idempotency.interceptor — Task 2)
81
- "idempotency_key_collision",
82
- // 409 — same key, different body hash
83
- "idempotency_in_progress",
84
- // 409 — concurrent identical request mid-flight (client auto-retries)
85
- "idempotency_key_required",
86
- // 400 — only on @Idempotent({required:true}) routes (none hosted yet)
87
- // validation + fallback
88
- "validation_error",
89
- // 400 — ValibotPipe rejection (camelToSnake of 'ValidationError')
90
- "internal_error",
91
- // 500 — unhandled server error
92
- // client-synthesized (never sent by the backend)
93
- "unknown_error",
94
- // unparseable (non-JSON) response body — error OR 2xx (defensive)
95
- "upload_failed",
96
- // the bare Spaces PUT answered non-2xx
97
- "network_error",
98
- // fetch rejected: connection drop / DNS / CORS / mid-transfer (status 0)
99
- "timeout"
100
- // AbortSignal.timeout fired — API calls 30 s default, Spaces PUT 15 min (status 0)
101
- ];
102
- function isKnownCode(code) {
103
- return KNOWN_CODES.includes(code);
104
- }
105
- var HostedApiError = class extends Error {
106
- constructor(args) {
107
- super(args.message);
108
- this.name = "HostedApiError";
109
- this.status = args.status;
110
- this.code = args.code;
111
- if (args.retryAfterSeconds !== void 0) this.retryAfterSeconds = args.retryAfterSeconds;
112
- }
113
- };
114
-
115
- // src/client/hosted-client.ts
116
- var DEFAULT_REQUEST_TIMEOUT_MS = 3e4;
117
- var SPACES_PUT_TIMEOUT_MS = 9e5;
118
- var UPLOAD_ERROR_SNIPPET_CHARS = 200;
119
- var IN_PROGRESS_RETRY_ATTEMPTS = 5;
120
- var IN_PROGRESS_RETRY_DELAY_MS = 400;
121
- function stripMimeParams(contentType) {
122
- return (contentType.split(";")[0] ?? "").trim();
123
- }
124
- var MEDIA_INPUT_FIELD = {
125
- liveness: "clipKey",
126
- face_match: "imageKey",
127
- doc_ocr: "imageKey"
128
- };
129
- var HostedClient = class {
130
- constructor(opts) {
131
- this.sessionId = null;
132
- this.bootstrap = null;
133
- this.apiOrigin = opts.apiOrigin.replace(/\/+$/, "");
134
- this.sessionToken = opts.sessionToken;
135
- const impl = opts.fetch;
136
- this.fetchImpl = (input, init) => (impl ?? globalThis.fetch).call(globalThis, input, init);
137
- this.requestTimeoutMs = opts.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
138
- this.retryAttempts = opts.inProgressRetry?.attempts ?? IN_PROGRESS_RETRY_ATTEMPTS;
139
- this.retryDelayMs = opts.inProgressRetry?.delayMs ?? IN_PROGRESS_RETRY_DELAY_MS;
140
- }
141
- /** Token-addressed bootstrap — the hosted page's first call. Caches the sessionId. */
142
- async getSession() {
143
- const view = await this.api("GET", "/hosted/session");
144
- this.sessionId = view.sessionId;
145
- return view;
146
- }
147
- /**
148
- * Record consent once (201; an idempotent replay answers 200 with
149
- * `alreadyRecorded: true`). Until recorded, media presign/complete AND check
150
- * submission answer 409 `consent_required`.
151
- */
152
- async recordConsent(locale) {
153
- return this.api("POST", "/hosted/consent", { body: { locale } });
154
- }
155
- /**
156
- * Presign a Spaces PUT for a new pending object. `contentType` is stripped of
157
- * MIME parameters defensively (the allowlist holds bare types; the engine's
158
- * `clipMimeType` carries codec params) — PUT with the SAME bare type, or the
159
- * signed-header check rejects the upload.
160
- */
161
- async presign(kind, contentType, contentLength) {
162
- const id = await this.ensureSessionId();
163
- const body = { kind, contentType: stripMimeParams(contentType), contentLength };
164
- return this.api("POST", `/sessions/${id}/media`, { body });
165
- }
166
- /**
167
- * Bare PUT to the presigned Spaces URL: EXACTLY the signed headers — the
168
- * declared Content-Type and the blob body. NO `x-session-token` (the
169
- * signature IS the credential; an extra header breaks nothing but leaks the
170
- * token to a third-party host) and no JSON envelope.
171
- *
172
- * `contentType` is param-stripped here too (idempotent for bare types): the
173
- * presign strips internally, so a caller composing manually with the engine's
174
- * parameterful `clipMimeType` would otherwise sign `video/webm` but PUT
175
- * `video/webm;codecs=…` — a signed-header mismatch S3 rejects at runtime.
176
- *
177
- * Timeout: 15 min (`AbortSignal.timeout(900_000)`, matching the presign TTL)
178
- * rather than the API calls' 30 s — a 15 MB clip on a slow link legitimately
179
- * exceeds 30 s, but a stalled in-flight socket must still be bounded (the TTL
180
- * alone only bounds when a PUT can START).
181
- *
182
- * Failures are ALWAYS typed: non-2xx throws {@link HostedApiError} with the
183
- * client-synthesized `upload_failed` (message carries a truncated S3 body
184
- * snippet — e.g. SignatureDoesNotMatch); a mid-transfer drop → `network_error`;
185
- * the timeout → `timeout`.
186
- */
187
- async uploadToSpaces(uploadUrl, blob, contentType) {
188
- let res;
189
- try {
190
- res = await this.fetchImpl(uploadUrl, {
191
- method: "PUT",
192
- headers: { "content-type": stripMimeParams(contentType) },
193
- body: blob,
194
- signal: AbortSignal.timeout(SPACES_PUT_TIMEOUT_MS)
195
- });
196
- } catch (err) {
197
- throw asTransportError(err);
198
- }
199
- if (!res.ok) {
200
- const snippet = (await res.text().catch(() => "")).slice(0, UPLOAD_ERROR_SNIPPET_CHARS);
201
- throw new HostedApiError({
202
- status: res.status,
203
- code: "upload_failed",
204
- message: `media upload failed (HTTP ${res.status})${snippet ? `: ${snippet}` : ""}`
205
- });
206
- }
207
- }
208
- /** Finalize an upload: the backend sniffs + promotes; returns the PROMOTED key to submit. */
209
- async completeMedia(key) {
210
- const id = await this.ensureSessionId();
211
- return this.api("POST", `/sessions/${id}/media/complete`, {
212
- body: { key }
213
- });
214
- }
215
- /**
216
- * Submit one check. Sends `{input, forceOutcome?}` (SubmitCheckSchema) and the
217
- * optional `x-idempotency-key` header. Returns the whitelisted SessionView.
218
- */
219
- async submitCheck(checkType, input, opts = {}) {
220
- const id = await this.ensureSessionId();
221
- const body = {
222
- input,
223
- ...opts.forceOutcome !== void 0 ? { forceOutcome: opts.forceOutcome } : {}
224
- };
225
- return this.api("POST", `/sessions/${id}/checks/${checkType}`, {
226
- body,
227
- ...opts.idempotencyKey !== void 0 ? { idempotencyKey: opts.idempotencyKey } : {}
228
- });
229
- }
230
- /**
231
- * Convenience composition: presign → PUT → complete → submit, passing the
232
- * PROMOTED key (from complete's response — never the pending presign key)
233
- * into the check's media input field (`clipKey` for liveness, `imageKey` for
234
- * face_match/doc_ocr). `extraInput` carries the remaining input fields
235
- * (liveness `attestation`, doc_ocr `side`). The media content type is
236
- * param-stripped ONCE and used for both presign and PUT, so the signed
237
- * header always matches.
238
- */
239
- async uploadAndSubmit(checkType, media, extraInput, opts = {}) {
240
- const bareType = stripMimeParams(media.contentType);
241
- const presigned = await this.presign(media.kind, bareType, media.blob.size);
242
- await this.uploadToSpaces(presigned.uploadUrl, media.blob, bareType);
243
- const completed = await this.completeMedia(presigned.key);
244
- const input = {
245
- ...extraInput,
246
- [MEDIA_INPUT_FIELD[checkType]]: completed.key
247
- };
248
- return this.submitCheck(checkType, input, opts);
249
- }
250
- // ── transport ──────────────────────────────────────────────────────────────
251
- /** The token's own sessionId — cached from getSession(), lazily bootstrapped. */
252
- async ensureSessionId() {
253
- if (this.sessionId !== null) return this.sessionId;
254
- this.bootstrap ?? (this.bootstrap = this.getSession().finally(() => {
255
- this.bootstrap = null;
256
- }));
257
- return (await this.bootstrap).sessionId;
258
- }
259
- /**
260
- * One API request: `${apiOrigin}/api/v2${path}`, `x-session-token` always,
261
- * AbortSignal timeout (30 s default), `{success, data}` unwrap on 2xx, flat
262
- * `{code, message}` → {@link HostedApiError} on non-2xx. EVERY failure is
263
- * typed: a rejected fetch → `network_error`, the timeout → `timeout`, an
264
- * unparseable 2xx body → `unknown_error` — the page never sees a raw
265
- * TypeError/DOMException. The ONLY automatic retry is 409
266
- * `idempotency_in_progress` (bounded, short delay).
267
- */
268
- async api(method, path, opts = {}) {
269
- const url = `${this.apiOrigin}/api/v2${path}`;
270
- const headers = { "x-session-token": this.sessionToken };
271
- if (opts.body !== void 0) headers["content-type"] = "application/json";
272
- if (opts.idempotencyKey !== void 0) headers["x-idempotency-key"] = opts.idempotencyKey;
273
- for (let attempt = 0; ; attempt++) {
274
- let res;
275
- try {
276
- res = await this.fetchImpl(url, {
277
- method,
278
- headers,
279
- ...opts.body !== void 0 ? { body: JSON.stringify(opts.body) } : {},
280
- signal: AbortSignal.timeout(this.requestTimeoutMs)
281
- });
282
- } catch (err2) {
283
- throw asTransportError(err2);
284
- }
285
- if (res.ok) {
286
- let raw;
287
- try {
288
- raw = await res.json();
289
- } catch {
290
- throw new HostedApiError({
291
- status: res.status,
292
- code: "unknown_error",
293
- message: `response body was not valid JSON (HTTP ${res.status})`
294
- });
295
- }
296
- return unwrap(raw);
297
- }
298
- const err = await parseErrorResponse(res);
299
- if (err.code === "idempotency_in_progress" && attempt < this.retryAttempts) {
300
- if (this.retryDelayMs > 0) await sleep(this.retryDelayMs);
301
- continue;
302
- }
303
- throw err;
304
- }
305
- }
306
- };
307
- function asTransportError(err) {
308
- const name = typeof err === "object" && err !== null ? err.name : void 0;
309
- if (name === "TimeoutError") {
310
- return new HostedApiError({ status: 0, code: "timeout", message: "request timed out" });
311
- }
312
- const detail = err instanceof Error ? err.message : String(err);
313
- return new HostedApiError({
314
- status: 0,
315
- code: "network_error",
316
- message: `network request failed: ${detail}`
317
- });
318
- }
319
- function unwrap(raw) {
320
- if (raw !== null && typeof raw === "object" && "success" in raw && "data" in raw) {
321
- return raw.data;
322
- }
323
- return raw;
324
- }
325
- async function parseErrorResponse(res) {
326
- let code = "unknown_error";
327
- let message = `request failed (HTTP ${res.status})`;
328
- try {
329
- const body = await res.json();
330
- if (body !== null && typeof body === "object") {
331
- const env = body;
332
- if (typeof env.code === "string" && env.code.length > 0) code = env.code;
333
- if (typeof env.message === "string" && env.message.length > 0) message = env.message;
334
- }
335
- } catch {
336
- }
337
- const retryAfterRaw = res.headers.get("retry-after");
338
- const retryAfter = retryAfterRaw === null ? Number.NaN : Number.parseInt(retryAfterRaw, 10);
339
- return new HostedApiError({
340
- status: res.status,
341
- code,
342
- message,
343
- ...Number.isFinite(retryAfter) && retryAfter >= 0 ? { retryAfterSeconds: retryAfter } : {}
344
- });
345
- }
346
- function sleep(ms) {
347
- return new Promise((resolve) => setTimeout(resolve, ms));
348
- }
349
- // Annotate the CommonJS export names for ESM import in node:
350
- 0 && (module.exports = {
351
- HostedApiError,
352
- HostedClient,
353
- KNOWN_CODES,
354
- isKnownCode,
355
- stripMimeParams
356
- });
357
- //# sourceMappingURL=index.cjs.map
1
+ "use strict";var y=Object.defineProperty;var O=Object.getOwnPropertyDescriptor;var v=Object.getOwnPropertyNames;var E=Object.prototype.hasOwnProperty;var M=(t,e)=>{for(var n in e)y(t,n,{get:e[n],enumerable:!0})},N=(t,e,n,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of v(e))!E.call(t,i)&&i!==n&&y(t,i,{get:()=>e[i],enumerable:!(o=O(e,i))||o.enumerable});return t};var A=t=>N(y({},"__esModule",{value:!0}),t);var Y={};M(Y,{HostedApiError:()=>c,HostedClient:()=>p,KNOWN_CODES:()=>g,icaoPolicyOf:()=>I,isKnownCode:()=>T,portraitIcaoGate:()=>k,stripMimeParams:()=>u});module.exports=A(Y);var b="0.1.0-rc.8";var S="sekyro.did",C;function w(){let t=globalThis.crypto;try{if(typeof t?.randomUUID=="function")return t.randomUUID()}catch{}try{if(typeof t?.getRandomValues=="function"){let e=t.getRandomValues(new Uint8Array(16));return Array.from(e,n=>n.toString(16).padStart(2,"0")).join("")}}catch{}}function x(){try{let t=localStorage.getItem(S);if(t)return t;let e=w();return e!==void 0&&localStorage.setItem(S,e),e}catch{return C??(C=w()),C}}async function H(){let t=globalThis.crypto?.subtle;if(!t)return"";let e=navigator,n=JSON.stringify([e.userAgent,e.platform,e.hardwareConcurrency??null,e.deviceMemory??null,e.maxTouchPoints??0,screen.width,screen.height,screen.colorDepth,globalThis.devicePixelRatio??1,Intl.DateTimeFormat().resolvedOptions().timeZone,e.languages?.join(",")??e.language]),o=await t.digest("SHA-256",new TextEncoder().encode(n));return Array.from(new Uint8Array(o),i=>i.toString(16).padStart(2,"0")).join("").slice(0,32)}function D(t){let e=new TextEncoder().encode(t),n="";for(let o of e)n+=String.fromCharCode(o);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function V(t){let e,n;return{timezone(){try{return Intl.DateTimeFormat().resolvedOptions().timeZone?.slice(0,64)||void 0}catch{return}},noteCameraLabel(o){o&&(e=o.slice(0,128))},async deviceHeader(){try{n??(n=H().catch(()=>""));let o=[];navigator.webdriver&&o.push("webdriver"),/HeadlessChrome/.test(navigator.userAgent)&&o.push("headless");let i=await n,s=x(),a={v:1,platform:"web",sdk:t.sdk.slice(0,64),ids:[...s?[{kind:"web_local",value:s.slice(0,128)}]:[],...i?[{kind:"web_fp",value:i}]:[]],screen:{w:screen.width,h:screen.height,dpr:globalThis.devicePixelRatio??1},...e?{cameraLabel:e}:{},...o.length?{signals:o}:{}};return D(JSON.stringify(a))}catch{return}}}}var m=Symbol.for("sekyro.web.clientContext"),f=globalThis,h=f[m]??(f[m]=V({sdk:`@sekyro/web@${b}`}));var g=["session_token_invalid","session_token_required","session_token_session_mismatch","session_not_found","rate_limit_exceeded","consent_required","session_not_active","check_not_found","check_already_finalized","check_out_of_order","check_type_unsupported","force_outcome_forbidden","attestation_invalid","platform_unregistered","app_attest_invalid","too_many_challenges","inference_unavailable","mobile_required","nni_locked","method_required","method_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","method_not_offered","nfc_outcome_not_accepted","contact_locked","identity_confirm_required","identity_confirm_locked"];function T(t){return g.includes(t)}var c=class extends Error{constructor(e){super(e.message),this.name="HostedApiError",this.status=e.status,this.code=e.code,e.retryAfterSeconds!==void 0&&(this.retryAfterSeconds=e.retryAfterSeconds)}};var K=6e4,P=4,U=3e4,L=9e5,q=200,$=5,B=400;function u(t){return(t.split(";")[0]??"").trim()}var F={liveness:"clipKey",face_match:"imageKey",doc_ocr:"imageKey"},p=class{constructor(e){this.sessionId=null;this.bootstrap=null;this.captureNonces=[];this.captureFetch=null;this.apiOrigin=e.apiOrigin.replace(/\/+$/,""),this.sessionToken=e.sessionToken;let n=e.fetch;this.fetchImpl=(o,i)=>(n??globalThis.fetch).call(globalThis,o,i),this.requestTimeoutMs=e.requestTimeoutMs??U,this.retryAttempts=e.inProgressRetry?.attempts??$,this.retryDelayMs=e.inProgressRetry?.delayMs??B}async getSession(){let e=await this.api("GET","/hosted/session");return this.sessionId=e.sessionId,e}async recordConsent(e){return this.api("POST","/hosted/consent",{body:{locale:e}})}async selectMethod(e){let n=await this.api("POST","/hosted/method",{body:{method:e}});return this.sessionId=n.sessionId,n}async selectContact(e){return this.api("POST","/hosted/contact",{body:{channel:e}})}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,o){let i=await this.ensureSessionId(),s={kind:e,contentType:u(n),contentLength:o};return this.api("POST",`/sessions/${i}/media`,{body:s})}armCapture(e=2){this.fillCaptureNonces(e)}async presignCapture(e,n,o,i={}){let s=await this.ensureSessionId(),a=await this.takeCaptureNonce(),r=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)))}:{}},d={kind:e,contentType:u(n),contentLength:o,...r!==void 0?{capture:r}:{}};return this.api("POST",`/sessions/${s}/media`,{body:d})}async takeCaptureNonce(){let e=()=>{let n=Date.now();return this.captureNonces=this.captureNonces.filter(o=>o.expiresAt-K>n),this.captureNonces.shift()?.nonce};for(let n=0;n<2;n++){let o=e();if(o!==void 0)return o;await this.fillCaptureNonces(1)}return e()}fillCaptureNonces(e){return this.captureFetch??(this.captureFetch=(async()=>{try{let n=await this.ensureSessionId(),o=await this.api("POST",`/sessions/${n}/media/capture-nonces`,{body:{count:Math.min(P,Math.max(1,e))}}),i=Date.now()+Math.max(0,o.expiresIn)*1e3;for(let s of Array.isArray(o.nonces)?o.nonces:[])typeof s=="string"&&s.length>0&&this.captureNonces.push({nonce:s,expiresAt:i});this.captureNonces=this.captureNonces.slice(-P)}catch{}})().finally(()=>{this.captureFetch=null})),this.captureFetch}async uploadToSpaces(e,n,o){let i;try{i=await this.fetchImpl(e,{method:"PUT",headers:{"content-type":u(o)},body:n,signal:AbortSignal.timeout(L)})}catch(s){throw _(s)}if(!i.ok){let s=(await i.text().catch(()=>"")).slice(0,q);throw new c({status:i.status,code:"upload_failed",message:`media upload failed (HTTP ${i.status})${s?`: ${s}`:""}`})}}async completeMedia(e){let n=await this.ensureSessionId();return this.api("POST",`/sessions/${n}/media/complete`,{body:{key:e}})}async submitCheck(e,n,o={}){let i=await this.ensureSessionId(),s={input:n,...o.forceOutcome!==void 0?{forceOutcome:o.forceOutcome}:{}};return this.api("POST",`/sessions/${i}/checks/${e}`,{body:s,...o.idempotencyKey!==void 0?{idempotencyKey:o.idempotencyKey}:{}})}async uploadAndSubmit(e,n,o,i={}){let s=u(n.contentType),a=await this.presign(n.kind,s,n.blob.size);await this.uploadToSpaces(a.uploadUrl,n.blob,s);let r=await this.completeMedia(a.key),d={...o,[F[e]]:r.key};return this.submitCheck(e,d,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,o={}){let i=`${this.apiOrigin}/api/v2${n}`,s={"x-session-token":this.sessionToken};o.body!==void 0&&(s["content-type"]="application/json"),o.idempotencyKey!==void 0&&(s["x-idempotency-key"]=o.idempotencyKey);try{let a=h.timezone();a!==void 0&&(s["sekyro-client-timezone"]=a)}catch{}try{let a=await h.deviceHeader();a!==void 0&&(s["sekyro-client-device"]=a)}catch{}for(let a=0;;a++){let r;try{r=await this.fetchImpl(i,{method:e,headers:s,...o.body!==void 0?{body:JSON.stringify(o.body)}:{},cache:"no-store",signal:AbortSignal.timeout(this.requestTimeoutMs)})}catch(l){throw _(l)}if(r.ok){if(o.blob===!0)try{return await r.blob()}catch(R){throw _(R)}let l;try{l=await r.json()}catch{throw new c({status:r.status,code:"unknown_error",message:`response body was not valid JSON (HTTP ${r.status})`})}return j(l)}let d=await G(r);if(d.code==="idempotency_in_progress"&&a<this.retryAttempts){this.retryDelayMs>0&&await z(this.retryDelayMs);continue}throw d}}};function _(t){if((typeof t=="object"&&t!==null?t.name:void 0)==="TimeoutError")return new c({status:0,code:"timeout",message:"request timed out"});let n=t instanceof Error?t.message:String(t);return new c({status:0,code:"network_error",message:`network request failed: ${n}`})}function j(t){return t!==null&&typeof t=="object"&&"success"in t&&"data"in t?t.data:t}async function G(t){let e="unknown_error",n=`request failed (HTTP ${t.status})`,o=Number.NaN;try{let a=await t.json();if(a!==null&&typeof a=="object"){let r=a;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"&&(o=r.retryAfterSeconds)}}catch{}let i=t.headers.get("retry-after"),s=i===null?Math.floor(o):Number.parseInt(i,10);return new c({status:t.status,code:e,message:n,...Number.isFinite(s)&&s>=0?{retryAfterSeconds:s}:{}})}function z(t){return new Promise(e=>setTimeout(e,t))}function I(t){let e=t?.portrait,n=e?.icao,o=e?.purpose==="id_document";return n==null?o?{policy:"reject",profile:"id_document"}:null:{policy:n.policy==="alert"&&!o?"alert":"reject",profile:o||n.profile==="id_document"?"id_document":"selfie"}}function k(t){return{...t.baselineEyeOpenness!==void 0?{baselineEyeOpenness:t.baselineEyeOpenness}:{},criteria:t.verdict??{},...t.backgroundCheck!==void 0?{backgroundCheck:t.backgroundCheck}:{}}}0&&(module.exports={HostedApiError,HostedClient,KNOWN_CODES,icaoPolicyOf,isKnownCode,portraitIcaoGate,stripMimeParams});
@@ -1,11 +1,12 @@
1
- export { A as AttestationInput, k as CheckInputByType, C as CheckReason, a as CheckState, b as CheckType, l as CompleteMediaResult, m as ConsentLocale, n as DocOcrInput, D as DocReason, o as DocSide, p as FaceMatchInput, F as FaceMatchReason, i as HostedClient, q as HostedClientOptions, H as HostedOtpView, c as HostedSessionView, d as HostedStepView, e as HostedVoiceLocale, f as HostedVoiceView, r as LivenessCaptureInput, s as LivenessInput, L as LivenessReason, M as MediaCheckType, t as MediaKind, u as PhoneOtpInput, P as PhoneOtpReason, v as PopulationInput, g as PopulationReason, w as PresignRequest, x as PresignUploadResult, R as RecordConsentResult, S as SessionOutcome, h as SessionStatus, y as SessionStepView, j as SessionView, z as SubmitCheckBody, B as SubmitOptions, U as UploadMedia, E as stripMimeParams } from '../hosted-client-DJXq_CB9.cjs';
1
+ import { w as HostedSessionView, p as HostedIcaoPolicy, L as IcaoGateSummary, a0 as PortraitIcaoInput } from '../icao-gate-D8qm1O2t.cjs';
2
+ export { A as AcceptedDocumentType, aM as AttestationInput, aN as CaptureContext, aO as CaptureNoncesResult, aP as CaptureProof, aQ as CheckInputByType, C as CheckReason, a as CheckState, b as CheckType, aR as CompleteMediaResult, aS as ConsentLocale, c as ContactChannel, D as DecisionReason, aT as DocDeviceRead, aU as DocOcrInput, d as DocReason, aV as DocSide, E as EidAfterPass, e as EidAuthInput, f as EidReason, aW as EmailOtpInput, g as EmailOtpReason, aX as FaceMatchInput, F as FaceMatchReason, h as HostedAcceptedDocuments, k as HostedCaptureTuning, aL as HostedClient, aY as HostedClientOptions, l as HostedDocumentCaptureTuning, m as HostedDocumentScanTuning, n as HostedEidView, o as HostedEmailOtpView, q as HostedIntegrity, r as HostedLivePhotoTuning, s as HostedNativeCaptureTuning, t as HostedOcrTuning, u as HostedOtpView, v as HostedPortraitView, x as HostedStepView, y as HostedVoiceLocale, z as HostedVoiceView, G as IcaoCriterion, N as IcaoReportEntry, O as IdentityConfirmDecision, P as IdentityMethod, Q as IdentitySummarySource, R as IdentitySummaryView, aZ as LivenessCaptureInput, a_ as LivenessInput, S as LivenessReason, T as MatchReason, a$ as MediaCheckType, b0 as MediaKind, U as MethodChoiceView, V as NationalEidOption, W as NfcChipReason, X as NfcStepView, Y as OtpChoiceView, b1 as PhoneOtpInput, Z as PhoneOtpReason, _ as PolicyFailureReason, b2 as PopulationInput, $ as PopulationReason, a1 as PortraitIcaoReason, b3 as PresignRequest, b4 as PresignUploadResult, b5 as RecordConsentResult, a2 as SessionFailureReason, a3 as SessionOutcome, a4 as SessionStatus, b6 as SessionStepView, a6 as SessionView, a5 as StepSection, b7 as SubmitCheckBody, b8 as SubmitOptions, b9 as UploadMedia, ba as stripMimeParams } from '../icao-gate-D8qm1O2t.cjs';
2
3
 
3
4
  /**
4
5
  * Every error code the hosted page can receive from the session-token surface.
5
6
  * A closed string-literal union — switch over {@link KnownCode} with a `never`
6
7
  * default arm for compile-checked exhaustiveness.
7
8
  */
8
- declare const KNOWN_CODES: readonly ["session_token_invalid", "session_token_required", "session_token_session_mismatch", "session_not_found", "rate_limit_exceeded", "consent_required", "session_not_active", "check_not_found", "check_already_finalized", "check_out_of_order", "check_type_unsupported", "force_outcome_forbidden", "attestation_invalid", "nni_locked", "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"];
9
+ declare const KNOWN_CODES: readonly ["session_token_invalid", "session_token_required", "session_token_session_mismatch", "session_not_found", "rate_limit_exceeded", "consent_required", "session_not_active", "check_not_found", "check_already_finalized", "check_out_of_order", "check_type_unsupported", "force_outcome_forbidden", "attestation_invalid", "platform_unregistered", "app_attest_invalid", "too_many_challenges", "inference_unavailable", "mobile_required", "nni_locked", "method_required", "method_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", "method_not_offered", "nfc_outcome_not_accepted", "contact_locked", "identity_confirm_required", "identity_confirm_locked"];
9
10
  /** Closed union of {@link KNOWN_CODES} — exhaustively switchable. */
10
11
  type KnownCode = (typeof KNOWN_CODES)[number];
11
12
  /** Narrow an arbitrary wire code to the known union (unknown codes stay `string`). */
@@ -36,4 +37,13 @@ declare class HostedApiError extends Error {
36
37
  });
37
38
  }
38
39
 
39
- export { HostedApiError, KNOWN_CODES, type KnownCode, isKnownCode };
40
+ /** The session's ICAO policy and profile, or `null` when the selfie is not ICAO-checked. */
41
+ declare function icaoPolicyOf(view: Pick<HostedSessionView, "portrait"> | null | undefined): HostedIcaoPolicy | null;
42
+ /**
43
+ * The `gate` block of a `portrait_icao` body from the gate's summary: the eye
44
+ * baseline, the device verdict under the server's criterion names, and the
45
+ * background-uniformity numbers (telemetry).
46
+ */
47
+ declare function portraitIcaoGate(summary: IcaoGateSummary): NonNullable<PortraitIcaoInput["gate"]>;
48
+
49
+ export { HostedApiError, HostedIcaoPolicy, HostedSessionView, KNOWN_CODES, type KnownCode, PortraitIcaoInput, icaoPolicyOf, isKnownCode, portraitIcaoGate };
@@ -1,11 +1,12 @@
1
- export { A as AttestationInput, k as CheckInputByType, C as CheckReason, a as CheckState, b as CheckType, l as CompleteMediaResult, m as ConsentLocale, n as DocOcrInput, D as DocReason, o as DocSide, p as FaceMatchInput, F as FaceMatchReason, i as HostedClient, q as HostedClientOptions, H as HostedOtpView, c as HostedSessionView, d as HostedStepView, e as HostedVoiceLocale, f as HostedVoiceView, r as LivenessCaptureInput, s as LivenessInput, L as LivenessReason, M as MediaCheckType, t as MediaKind, u as PhoneOtpInput, P as PhoneOtpReason, v as PopulationInput, g as PopulationReason, w as PresignRequest, x as PresignUploadResult, R as RecordConsentResult, S as SessionOutcome, h as SessionStatus, y as SessionStepView, j as SessionView, z as SubmitCheckBody, B as SubmitOptions, U as UploadMedia, E as stripMimeParams } from '../hosted-client-DJXq_CB9.js';
1
+ import { w as HostedSessionView, p as HostedIcaoPolicy, L as IcaoGateSummary, a0 as PortraitIcaoInput } from '../icao-gate-D8qm1O2t.js';
2
+ export { A as AcceptedDocumentType, aM as AttestationInput, aN as CaptureContext, aO as CaptureNoncesResult, aP as CaptureProof, aQ as CheckInputByType, C as CheckReason, a as CheckState, b as CheckType, aR as CompleteMediaResult, aS as ConsentLocale, c as ContactChannel, D as DecisionReason, aT as DocDeviceRead, aU as DocOcrInput, d as DocReason, aV as DocSide, E as EidAfterPass, e as EidAuthInput, f as EidReason, aW as EmailOtpInput, g as EmailOtpReason, aX as FaceMatchInput, F as FaceMatchReason, h as HostedAcceptedDocuments, k as HostedCaptureTuning, aL as HostedClient, aY as HostedClientOptions, l as HostedDocumentCaptureTuning, m as HostedDocumentScanTuning, n as HostedEidView, o as HostedEmailOtpView, q as HostedIntegrity, r as HostedLivePhotoTuning, s as HostedNativeCaptureTuning, t as HostedOcrTuning, u as HostedOtpView, v as HostedPortraitView, x as HostedStepView, y as HostedVoiceLocale, z as HostedVoiceView, G as IcaoCriterion, N as IcaoReportEntry, O as IdentityConfirmDecision, P as IdentityMethod, Q as IdentitySummarySource, R as IdentitySummaryView, aZ as LivenessCaptureInput, a_ as LivenessInput, S as LivenessReason, T as MatchReason, a$ as MediaCheckType, b0 as MediaKind, U as MethodChoiceView, V as NationalEidOption, W as NfcChipReason, X as NfcStepView, Y as OtpChoiceView, b1 as PhoneOtpInput, Z as PhoneOtpReason, _ as PolicyFailureReason, b2 as PopulationInput, $ as PopulationReason, a1 as PortraitIcaoReason, b3 as PresignRequest, b4 as PresignUploadResult, b5 as RecordConsentResult, a2 as SessionFailureReason, a3 as SessionOutcome, a4 as SessionStatus, b6 as SessionStepView, a6 as SessionView, a5 as StepSection, b7 as SubmitCheckBody, b8 as SubmitOptions, b9 as UploadMedia, ba as stripMimeParams } from '../icao-gate-D8qm1O2t.js';
2
3
 
3
4
  /**
4
5
  * Every error code the hosted page can receive from the session-token surface.
5
6
  * A closed string-literal union — switch over {@link KnownCode} with a `never`
6
7
  * default arm for compile-checked exhaustiveness.
7
8
  */
8
- declare const KNOWN_CODES: readonly ["session_token_invalid", "session_token_required", "session_token_session_mismatch", "session_not_found", "rate_limit_exceeded", "consent_required", "session_not_active", "check_not_found", "check_already_finalized", "check_out_of_order", "check_type_unsupported", "force_outcome_forbidden", "attestation_invalid", "nni_locked", "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"];
9
+ declare const KNOWN_CODES: readonly ["session_token_invalid", "session_token_required", "session_token_session_mismatch", "session_not_found", "rate_limit_exceeded", "consent_required", "session_not_active", "check_not_found", "check_already_finalized", "check_out_of_order", "check_type_unsupported", "force_outcome_forbidden", "attestation_invalid", "platform_unregistered", "app_attest_invalid", "too_many_challenges", "inference_unavailable", "mobile_required", "nni_locked", "method_required", "method_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", "method_not_offered", "nfc_outcome_not_accepted", "contact_locked", "identity_confirm_required", "identity_confirm_locked"];
9
10
  /** Closed union of {@link KNOWN_CODES} — exhaustively switchable. */
10
11
  type KnownCode = (typeof KNOWN_CODES)[number];
11
12
  /** Narrow an arbitrary wire code to the known union (unknown codes stay `string`). */
@@ -36,4 +37,13 @@ declare class HostedApiError extends Error {
36
37
  });
37
38
  }
38
39
 
39
- export { HostedApiError, KNOWN_CODES, type KnownCode, isKnownCode };
40
+ /** The session's ICAO policy and profile, or `null` when the selfie is not ICAO-checked. */
41
+ declare function icaoPolicyOf(view: Pick<HostedSessionView, "portrait"> | null | undefined): HostedIcaoPolicy | null;
42
+ /**
43
+ * The `gate` block of a `portrait_icao` body from the gate's summary: the eye
44
+ * baseline, the device verdict under the server's criterion names, and the
45
+ * background-uniformity numbers (telemetry).
46
+ */
47
+ declare function portraitIcaoGate(summary: IcaoGateSummary): NonNullable<PortraitIcaoInput["gate"]>;
48
+
49
+ export { HostedApiError, HostedIcaoPolicy, HostedSessionView, KNOWN_CODES, type KnownCode, PortraitIcaoInput, icaoPolicyOf, isKnownCode, portraitIcaoGate };