@checktiv/sdk-web 1.9.0 → 1.12.0

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 (64) hide show
  1. package/README.md +16 -1
  2. package/dist/agents/AGENTS.md +8 -0
  3. package/dist/agents/manifest.json +24 -0
  4. package/dist/capture-ui.d.ts +4 -4
  5. package/dist/capture-ui.js +7 -6
  6. package/dist/capture.d.ts +3 -3
  7. package/dist/capture.js +4 -3
  8. package/dist/challenge.js +2 -2
  9. package/dist/chunk-3KEVZCCZ.js +3 -0
  10. package/dist/chunk-4HIQN4KL.js +3 -0
  11. package/dist/chunk-C7GRMEYT.js +3 -0
  12. package/dist/chunk-CAI3JWWU.js +12 -0
  13. package/dist/chunk-EOTGVXW6.js +7 -0
  14. package/dist/{chunk-HV2QKVJX.js → chunk-FQSJUWRP.js} +1 -1
  15. package/dist/{chunk-FL2GCRSI.js → chunk-HWABVMID.js} +4 -4
  16. package/dist/{chunk-MCYAWMYQ.js → chunk-KYV5BPCD.js} +2 -2
  17. package/dist/chunk-MLQ2HMTS.js +3 -0
  18. package/dist/chunk-O3JECGW2.js +3 -0
  19. package/dist/chunk-PB2THQ3P.js +8 -0
  20. package/dist/chunk-TKK5CTVG.js +59 -0
  21. package/dist/chunk-UVTAPUGQ.js +3 -0
  22. package/dist/chunk-VMWTID63.js +3 -0
  23. package/dist/{chunk-WC6TLR42.js → chunk-WALPQ6TH.js} +2 -1
  24. package/dist/chunk-YE2LWN74.js +9 -0
  25. package/dist/{chunk-XSSM5ZB7.js → chunk-ZU4L3NDZ.js} +1 -1
  26. package/dist/collect-user-info.d.ts +4 -4
  27. package/dist/collect-user-info.js +5 -5
  28. package/dist/{controller-Ta5RgFZ4.d.ts → controller-Dh-rSrot.d.ts} +3 -2
  29. package/dist/{copy-CEILzVXc.d.ts → copy-Bsb1n1Wv.d.ts} +1 -1
  30. package/dist/credit-history.d.ts +4 -0
  31. package/dist/credit-history.js +12 -0
  32. package/dist/cross-device.js +2 -2
  33. package/dist/custom-form.css +1 -1
  34. package/dist/custom-form.d.ts +3 -3
  35. package/dist/custom-form.js +7 -8
  36. package/dist/esign/ceremony-runtime.js +7 -0
  37. package/dist/esign.d.ts +16 -0
  38. package/dist/esign.js +427 -0
  39. package/dist/fraud.d.ts +3 -3
  40. package/dist/fraud.js +5 -6
  41. package/dist/idv/cross-device.d.ts +7 -7
  42. package/dist/idv/cross-device.js +4 -5
  43. package/dist/idv.d.ts +3 -3
  44. package/dist/idv.js +13 -13
  45. package/dist/index-CGH7LlPH.d.ts +736 -0
  46. package/dist/{index-G5mVvjNZ.d.ts → index-CZt19Km4.d.ts} +5 -5
  47. package/dist/index.d.ts +6 -6
  48. package/dist/index.js +8 -8
  49. package/dist/{machine-BhPiYmOR.d.ts → machine-EePe2ERe.d.ts} +49 -2
  50. package/dist/react.d.ts +4 -4
  51. package/dist/react.js +11 -11
  52. package/dist/workspace.d.ts +3 -3
  53. package/dist/workspace.js +2 -1
  54. package/package.json +35 -9
  55. package/dist/api-BrQqQbGK.d.ts +0 -342
  56. package/dist/chunk-523TT3PD.js +0 -7
  57. package/dist/chunk-7GP5REM7.js +0 -3
  58. package/dist/chunk-BBO2X73Y.js +0 -9
  59. package/dist/chunk-GFHNOZVO.js +0 -3
  60. package/dist/chunk-NHNGQ5BB.js +0 -66
  61. package/dist/chunk-S2OOEDJS.js +0 -3
  62. package/dist/chunk-T4R5TTE5.js +0 -7
  63. package/dist/chunk-WPMO4FQ2.js +0 -13
  64. package/dist/chunk-XOGHMNBX.js +0 -3
package/README.md CHANGED
@@ -21,7 +21,22 @@ npm install @checktiv/sdk-web
21
21
  ```
22
22
 
23
23
  `react` and `react-dom` are **optional peer dependencies**. Install them only if you
24
- use the `./react` subpath. Everything else works without React.
24
+ use the `./react` subpath, which supports React 17, 18, and 19. Everything else works
25
+ without React. One type-only exception: the root `@checktiv/sdk-web` re-exports the React
26
+ wrapper's prop types, so a TypeScript project that imports the root with
27
+ `skipLibCheck: false` also needs `@types/react`.
28
+
29
+ The SDK's types need TypeScript 4.7 or later, with `moduleResolution` set to `node16`, `nodenext`, or `bundler` (TypeScript 5.0 or later).
30
+
31
+ If your app already has React for other reasons, npm checks its version against that
32
+ range even when you do not use `./react`. On React 16 or earlier, add a scoped override
33
+ to your `package.json` so the SDK uses your app's React:
34
+
35
+ ```json
36
+ "overrides": {
37
+ "@checktiv/sdk-web": { "react": "$react", "react-dom": "$react-dom" }
38
+ }
39
+ ```
25
40
 
26
41
  ## Quickstart
27
42
 
@@ -41,6 +41,14 @@ Four token-free overlay events (NONE carries the url / OTL / short-code / expiry
41
41
  • `checktiv.idv.cross_device_capped`: the completion poll hit its total time cap without the phone finishing. NOT an error and NOT a verdict: the QR panel stays mounted so the applicant can still finish on their phone.
42
42
  • `checktiv.idv.cross_device_closed`: the applicant dismissed the overlay (back on desktop, try-again on mobile). Fires only on an applicant-initiated dismissal, never on a `destroy()` you call for an unrelated reason such as tearing the overlay down after the phone already completed.
43
43
 
44
+ 11. **The credit history check renders in a hosted frame your page must not reach into.** The credit-history step renders inside a Checktiv-hosted frame that your page embeds but does not own. Every value the applicant enters (identifiers, address, the authorization itself) is typed into that frame and posted from it, and the frame is sandboxed and origin-pinned, so your page never sees a credit form value. Write the integration accordingly: do NOT try to read, log, screenshot, session-replay, prefill, re-submit or otherwise capture credit form fields from the host page, and do NOT build your own "resume where they left off" store for them. The frame keeps its own per-screen draft and the SDK re-establishes the frame after a reload, so a host-side copy would be a duplicate of regulated data with none of the protection. Render the step by adding the self-registering import `import '@checktiv/sdk-web/credit-history';` (the same side-effect import shape as `/idv` and `/fraud`; the CDN script-tag bundle loads it for you) and give the SDK a container to mount into. There is NO credit-specific option on `Checktiv.mount(...)` or on its React wrapper `<ChecktivJourney>`: the step is composed by the server and takes no host config.
45
+
46
+ The event stream is `checktiv.credit_history.*` and it is STATE ONLY: no member ever carries a field value, an identifier the applicant typed, a score or a finding. Narrow it with the exported `isChecktivCreditHistoryEvent(event)` guard rather than an `event.type === ...` comparison, because the SDK event union is forward-open and a bare equality check does not narrow the payload. Three members are the ones to get right:
47
+ • `checktiv.credit_history.submitted`: the step was submitted. It is NOT a verdict and carries no outcome, score or finding. The decision reaches your server on the signed webhook, exactly like every other check.
48
+ • `checktiv.credit_history.declined`: the applicant declined authorization. Nothing was requested and nothing was billed. This is a normal end state and NOT an error: the link stays valid and the session stays resumable, so give a neutral next step, never a failure screen.
49
+ • `checktiv.credit_history.skipped`: the step ended inside the frame with no request and no charge, for a closed reason code. Also a normal state and NOT an error.
50
+ Only `checktiv.credit_history.error` is a failure, and only it reaches an `onError` callback. Routing declined or skipped to your error path shows the applicant a fault where they made a choice.
51
+
44
52
  ## Runnable recipes
45
53
 
46
54
  Full, copy-pasteable code for each step is in `manifest.json` under `recipes`:
@@ -23,6 +23,25 @@
23
23
  "custom_form:steps:submit"
24
24
  ],
25
25
  "eventNamespace": "checktiv.custom_form"
26
+ },
27
+ "esign": {
28
+ "scopes": [
29
+ "sessions:me:read",
30
+ "esign:bundle:read",
31
+ "esign:context:mint",
32
+ "esign:events:write",
33
+ "esign:steps:submit",
34
+ "esign:consent:withdraw",
35
+ "esign:document:read"
36
+ ],
37
+ "eventNamespace": "checktiv.esign"
38
+ },
39
+ "credit_history": {
40
+ "scopes": [
41
+ "sessions:me:read",
42
+ "credit_history:context-token:mint"
43
+ ],
44
+ "eventNamespace": "checktiv.credit_history"
26
45
  }
27
46
  },
28
47
  "rules": [
@@ -75,6 +94,11 @@
75
94
  "id": "cross-device-handoff-hook",
76
95
  "title": "Cross-device QR handoff is built into the managed IDV module",
77
96
  "body": "Cross-device handoff (a desktop applicant finishes on their phone via a QR + copy-link overlay) is OWNED BY THE MANAGED IDV MODULE. Render it with `client.mount('idv', { crossDeviceCopy, onEvent })` and the returned handle exposes `openCrossDevice()`: calling it opens the overlay OVER the still-live capture frame, runs the completion poll, and emits `checktiv.idv.submitted` when the phone finishes so your host reloads. You MUST `import '@checktiv/sdk-web/idv/cross-device';` to enable the overlay (the CDN script-tag bundle already includes it); without that import `openCrossDevice()` is a graceful, actionable no-op, as it also is before the applicant verification resolves or when no `crossDeviceCopy` was supplied. `IdvMountOptions` carries `crossDeviceCopy` (host-injected strings; the `unavailableMessage` key is required so no arm renders blank) and the OPTIONAL `onOpenCrossDevice` mint override; `IdvHandle` exposes `openCrossDevice?()`, so call it as `handle.openCrossDevice?.()`. The zero-lifecycle `Checktiv.mount(...)` and its React wrapper `<ChecktivJourney>` ALSO expose `openCrossDevice()` on their handle (reach the React handle via a `ref`), carrying the same `crossDeviceCopy` / optional `onOpenCrossDevice` options; on that path the SDK self-mints the handoff on the working-token plane by default (see below), and the CDN script-tag bundle registers the opener too. The trigger is a DESKTOP affordance: `openCrossDevice()` is a graceful warn-no-op on a coarse-pointer (touch) device, because immersive phone capture and the desktop cross-device overlay are mutually exclusive per device, so gate your trigger to desktop.\n\nWho mints the one-time handoff link depends on the token plane:\n • Working-token plane: the module mints the link ITSELF (it calls its own handoff endpoint `POST /sdk/v1/sessions/me/handoff`, authenticated by the applicant's short-lived working token, and caps the per-overlay \"refresh link\" re-mints). Supply `onOpenCrossDevice` ONLY to point the mint at your own backend instead.\n • Browser-token (`bt_*`) plane: the SDK CANNOT self-mint (the handoff route rejects a `bt_*` bearer), so you MUST supply `onOpenCrossDevice` backed by a server-held credential.\n\n`onOpenCrossDevice: CrossDeviceHandoffHook` is `() => Promise<{ kind: 'ok'; url: string } | { kind: 'unavailable' }>`. Return `{ kind: 'ok', url }` with the journey URL (which MUST be `https:`: the SDK collapses `javascript:`, `http:`, and `data:` schemes to `'unavailable'`) or `{ kind: 'unavailable' }` when the mint fails. The hook is re-callable for the overlay's \"refresh link\" affordance; the SDK caps re-mints per overlay.\n\nFor a FULLY CUSTOM IDV renderer built on `@checktiv/sdk-web/capture` (NOT the managed module), the STANDALONE exports drive the overlay yourself and you always supply the mint hook: `@checktiv/sdk-web/idv/cross-device` (`openCrossDeviceOverlay(opts)` opens the overlay, `preloadCrossDeviceChunk()` warms the lazy chunk) and `@checktiv/sdk-web/cross-device` (`mountCrossDevice(target, props)` renders the bare panel on a screen you fully control). `openCrossDeviceOverlay` takes `{ target, onOpenCrossDevice, copy, isMobile, emit, onClose }` plus an optional `poll` config, and returns a handle with `setCompleting()` (keep the QR mounted with a waiting label while your page reloads) and `destroy()` (idempotent). Set `isMobile: true` to suppress the QR on a phone (a same-device scan is circular). The SDK NEVER writes `window.location`; navigation is always the host's, off the emitted event.\n\nFour token-free overlay events (NONE carries the url / OTL / short-code / expiry hint):\n • `checktiv.idv.cross_device_opened`: the mint returned `ok` and the overlay is shown.\n • `checktiv.idv.cross_device_unavailable`: the mint returned `unavailable` or URL validation failed.\n • `checktiv.idv.cross_device_capped`: the completion poll hit its total time cap without the phone finishing. NOT an error and NOT a verdict: the QR panel stays mounted so the applicant can still finish on their phone.\n • `checktiv.idv.cross_device_closed`: the applicant dismissed the overlay (back on desktop, try-again on mobile). Fires only on an applicant-initiated dismissal, never on a `destroy()` you call for an unrelated reason such as tearing the overlay down after the phone already completed."
97
+ },
98
+ {
99
+ "id": "credit-history-is-a-hosted-frame",
100
+ "title": "The credit history check renders in a hosted frame your page must not reach into",
101
+ "body": "The credit-history step renders inside a Checktiv-hosted frame that your page embeds but does not own. Every value the applicant enters (identifiers, address, the authorization itself) is typed into that frame and posted from it, and the frame is sandboxed and origin-pinned, so your page never sees a credit form value. Write the integration accordingly: do NOT try to read, log, screenshot, session-replay, prefill, re-submit or otherwise capture credit form fields from the host page, and do NOT build your own \"resume where they left off\" store for them. The frame keeps its own per-screen draft and the SDK re-establishes the frame after a reload, so a host-side copy would be a duplicate of regulated data with none of the protection. Render the step by adding the self-registering import `import '@checktiv/sdk-web/credit-history';` (the same side-effect import shape as `/idv` and `/fraud`; the CDN script-tag bundle loads it for you) and give the SDK a container to mount into. There is NO credit-specific option on `Checktiv.mount(...)` or on its React wrapper `<ChecktivJourney>`: the step is composed by the server and takes no host config.\n\nThe event stream is `checktiv.credit_history.*` and it is STATE ONLY: no member ever carries a field value, an identifier the applicant typed, a score or a finding. Narrow it with the exported `isChecktivCreditHistoryEvent(event)` guard rather than an `event.type === ...` comparison, because the SDK event union is forward-open and a bare equality check does not narrow the payload. Three members are the ones to get right:\n • `checktiv.credit_history.submitted`: the step was submitted. It is NOT a verdict and carries no outcome, score or finding. The decision reaches your server on the signed webhook, exactly like every other check.\n • `checktiv.credit_history.declined`: the applicant declined authorization. Nothing was requested and nothing was billed. This is a normal end state and NOT an error: the link stays valid and the session stays resumable, so give a neutral next step, never a failure screen.\n • `checktiv.credit_history.skipped`: the step ended inside the frame with no request and no charge, for a closed reason code. Also a normal state and NOT an error.\nOnly `checktiv.credit_history.error` is a failure, and only it reaches an `onError` callback. Routing declined or skipped to your error path shows the applicant a fault where they made a choice."
78
102
  }
79
103
  ],
80
104
  "recipes": [
@@ -1,7 +1,7 @@
1
- import { a as CaptureControllerDeps, b as CaptureEvent } from './controller-Ta5RgFZ4.js';
2
- import { C as CaptureLayout, f as CaptureState } from './machine-BhPiYmOR.js';
3
- import { M as MountCopy } from './copy-CEILzVXc.js';
4
- export { T as TerminalKind, f as fallbackCopy } from './copy-CEILzVXc.js';
1
+ import { a as CaptureControllerDeps, b as CaptureEvent } from './controller-Dh-rSrot.js';
2
+ import { e as CaptureLayout, d as CaptureState } from './machine-EePe2ERe.js';
3
+ import { M as MountCopy } from './copy-Bsb1n1Wv.js';
4
+ export { T as TerminalKind, f as fallbackCopy } from './copy-Bsb1n1Wv.js';
5
5
 
6
6
  interface MountCaptureOptions extends Omit<CaptureControllerDeps, 'getIframe'> {
7
7
  copy: MountCopy;
@@ -1,9 +1,10 @@
1
- export { fallbackCopy, mount } from './chunk-FL2GCRSI.js';
2
- import './chunk-HV2QKVJX.js';
3
- import './chunk-XOGHMNBX.js';
4
- import './chunk-T4R5TTE5.js';
5
- import './chunk-NHNGQ5BB.js';
6
- import './chunk-XSSM5ZB7.js';
1
+ export { fallbackCopy, mount } from './chunk-HWABVMID.js';
2
+ import './chunk-PB2THQ3P.js';
3
+ import './chunk-TKK5CTVG.js';
4
+ import './chunk-ZU4L3NDZ.js';
5
+ import './chunk-FQSJUWRP.js';
6
+ import './chunk-3KEVZCCZ.js';
7
7
  import './chunk-IQKHRPJR.js';
8
+ import './chunk-UBQTPS5J.js';
8
9
  import './chunk-QFA3K5ZV.js';
9
10
  import './chunk-AIK7CDV6.js';
package/dist/capture.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- export { C as CaptureController, a as CaptureControllerDeps, b as CaptureEvent, c as CaptureEventType, S as SubmitResult, d as createCaptureController } from './controller-Ta5RgFZ4.js';
2
- import { b as CoachingKind } from './machine-BhPiYmOR.js';
3
- export { c as CaptureAction, d as CaptureErrorKind, e as CapturePhase, f as CaptureState, i as isBiometricPhase, n as nextCapturePhaseAfterDocument, r as reducer } from './machine-BhPiYmOR.js';
1
+ export { C as CaptureController, a as CaptureControllerDeps, b as CaptureEvent, c as CaptureEventType, S as SubmitResult, d as createCaptureController } from './controller-Dh-rSrot.js';
2
+ import { C as CoachingKind } from './machine-EePe2ERe.js';
3
+ export { a as CaptureAction, b as CaptureErrorKind, c as CapturePhase, d as CaptureState, i as isBiometricPhase, n as nextCapturePhaseAfterDocument, r as reducer } from './machine-EePe2ERe.js';
4
4
 
5
5
  declare function coachingKindForState(state: string): CoachingKind;
6
6
 
package/dist/capture.js CHANGED
@@ -1,6 +1,7 @@
1
- export { coachingKindForState, createCaptureController, isBiometricPhase, nextCapturePhaseAfterDocument, reducer } from './chunk-T4R5TTE5.js';
2
- import './chunk-NHNGQ5BB.js';
3
- import './chunk-XSSM5ZB7.js';
1
+ export { coachingKindForState, createCaptureController, isBiometricPhase, nextCapturePhaseAfterDocument, reducer } from './chunk-PB2THQ3P.js';
2
+ import './chunk-TKK5CTVG.js';
3
+ import './chunk-ZU4L3NDZ.js';
4
4
  import './chunk-IQKHRPJR.js';
5
+ import './chunk-UBQTPS5J.js';
5
6
  import './chunk-QFA3K5ZV.js';
6
7
  import './chunk-AIK7CDV6.js';
package/dist/challenge.js CHANGED
@@ -1,7 +1,7 @@
1
+ import { string, _enum, object, literal, discriminatedUnion } from './chunk-TKK5CTVG.js';
1
2
  import { assertNever } from './chunk-UBQTPS5J.js';
2
- import { external_exports } from './chunk-NHNGQ5BB.js';
3
3
  import './chunk-AIK7CDV6.js';
4
4
 
5
- var canonicalOriginSchema=external_exports.string().min(1).refine(v=>{if(v.includes("*"))return false;try{return new URL(v).origin===v}catch{return false}},"must be a canonical origin (scheme and host[:port], no path / query / fragment / credentials / wildcard)");var challengeErrorCodeEnum=external_exports.enum(["challenge_failed","load_failed","expired","config_error"]);var challengeInitMessageSchema=external_exports.object({type:external_exports.literal("challenge:init"),theme:external_exports.enum(["light","dark"]).optional(),locale:external_exports.string().optional()}).strict();var challengeResetMessageSchema=external_exports.object({type:external_exports.literal("challenge:reset")}).strict();external_exports.discriminatedUnion("type",[challengeInitMessageSchema,challengeResetMessageSchema]);var challengeReadyMessageSchema=external_exports.object({type:external_exports.literal("challenge:ready")}).strict();var challengeTokenMessageSchema=external_exports.object({type:external_exports.literal("challenge:token"),token:external_exports.string().min(1)}).strict();var challengeErrorMessageSchema=external_exports.object({type:external_exports.literal("challenge:error"),code:challengeErrorCodeEnum}).strict();var challengeFromIframeMessageSchema=external_exports.discriminatedUnion("type",[challengeReadyMessageSchema,challengeTokenMessageSchema,challengeErrorMessageSchema]);external_exports.object({challengeContextToken:external_exports.string().min(1),embedOrigin:canonicalOriginSchema}).strict();function createChallengeController(deps){let started=false;let destroyed=false;let resetInFlight=false;let messageListener=null;function postInit(){const iframe=deps.getIframe();if(iframe===null||iframe.contentWindow===null)return;const init={type:"challenge:init",...deps.theme!==void 0?{theme:deps.theme}:{},...deps.locale!==void 0?{locale:deps.locale}:{}};iframe.contentWindow.postMessage(init,deps.embedOrigin);}function postReset(){const iframe=deps.getIframe();if(iframe===null||iframe.contentWindow===null)return;const reset={type:"challenge:reset"};iframe.contentWindow.postMessage(reset,deps.embedOrigin);}function handleMessage(msg){switch(msg.type){case "challenge:ready":{resetInFlight=false;return}case "challenge:token":{resetInFlight=false;deps.onToken(msg.token);return}case "challenge:error":{resetInFlight=false;deps.onError(msg.code);return}default:{return assertNever(msg)}}}function onWindowMessage(event){if(destroyed)return;if(event.origin!==deps.embedOrigin)return;if(event.source!==null&&event.source!==deps.getIframe()?.contentWindow)return;const parsed=challengeFromIframeMessageSchema.safeParse(event.data);if(!parsed.success)return;handleMessage(parsed.data);}return {start(){if(destroyed||started)return;started=true;messageListener=onWindowMessage;window.addEventListener("message",messageListener);postInit();},reset(){if(destroyed||!started)return;if(resetInFlight)return;resetInFlight=true;postReset();},destroy(){if(destroyed)return;destroyed=true;if(messageListener!==null){window.removeEventListener("message",messageListener);messageListener=null;}}}}
5
+ var canonicalOriginSchema=string().min(1).refine(v=>{if(v.includes("*"))return false;try{return new URL(v).origin===v}catch{return false}},"must be a canonical origin (scheme and host[:port], no path / query / fragment / credentials / wildcard)");var challengeErrorCodeEnum=_enum(["challenge_failed","load_failed","expired","config_error"]);var challengeInitMessageSchema=object({type:literal("challenge:init"),theme:_enum(["light","dark"]).optional(),locale:string().optional()}).strict();var challengeResetMessageSchema=object({type:literal("challenge:reset")}).strict();discriminatedUnion("type",[challengeInitMessageSchema,challengeResetMessageSchema]);var challengeReadyMessageSchema=object({type:literal("challenge:ready")}).strict();var challengeTokenMessageSchema=object({type:literal("challenge:token"),token:string().min(1)}).strict();var challengeErrorMessageSchema=object({type:literal("challenge:error"),code:challengeErrorCodeEnum}).strict();var challengeFromIframeMessageSchema=discriminatedUnion("type",[challengeReadyMessageSchema,challengeTokenMessageSchema,challengeErrorMessageSchema]);object({challengeContextToken:string().min(1),embedOrigin:canonicalOriginSchema}).strict();function createChallengeController(deps){let started=false;let destroyed=false;let resetInFlight=false;let messageListener=null;function postInit(){const iframe=deps.getIframe();if(iframe===null||iframe.contentWindow===null)return;const init={type:"challenge:init",...deps.theme!==void 0?{theme:deps.theme}:{},...deps.locale!==void 0?{locale:deps.locale}:{}};iframe.contentWindow.postMessage(init,deps.embedOrigin);}function postReset(){const iframe=deps.getIframe();if(iframe===null||iframe.contentWindow===null)return;const reset={type:"challenge:reset"};iframe.contentWindow.postMessage(reset,deps.embedOrigin);}function handleMessage(msg){switch(msg.type){case "challenge:ready":{resetInFlight=false;return}case "challenge:token":{resetInFlight=false;deps.onToken(msg.token);return}case "challenge:error":{resetInFlight=false;deps.onError(msg.code);return}default:{return assertNever(msg)}}}function onWindowMessage(event){if(destroyed)return;if(event.origin!==deps.embedOrigin)return;if(event.source!==null&&event.source!==deps.getIframe()?.contentWindow)return;const parsed=challengeFromIframeMessageSchema.safeParse(event.data);if(!parsed.success)return;handleMessage(parsed.data);}return {start(){if(destroyed||started)return;started=true;messageListener=onWindowMessage;window.addEventListener("message",messageListener);postInit();},reset(){if(destroyed||!started)return;if(resetInFlight)return;resetInFlight=true;postReset();},destroy(){if(destroyed)return;destroyed=true;if(messageListener!==null){window.removeEventListener("message",messageListener);messageListener=null;}}}}
6
6
 
7
7
  export { createChallengeController };
@@ -0,0 +1,3 @@
1
+ var n;var l;var u;var i;var r;var o;var e;var f;var c;var a;var s;var h;var p;var v;var d={};var w=[];var _=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;var g=Array.isArray;function m(n2,l2){for(var u2 in l2)n2[u2]=l2[u2];return n2}function b(n2){n2&&n2.parentNode&&n2.parentNode.removeChild(n2);}function k(l2,u2,t2){var i2,r2,o2,e2={};for(o2 in u2)"key"==o2?i2=u2[o2]:"ref"==o2?r2=u2[o2]:e2[o2]=u2[o2];if(arguments.length>2&&(e2.children=arguments.length>3?n.call(arguments,2):t2),"function"==typeof l2&&null!=l2.defaultProps)for(o2 in l2.defaultProps) void 0===e2[o2]&&(e2[o2]=l2.defaultProps[o2]);return x(l2,e2,i2,r2,null)}function x(n2,t2,i2,r2,o2){var e2={type:n2,props:t2,key:i2,ref:r2,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:null==o2?++u:o2,__i:-1,__u:0};return null==o2&&null!=l.vnode&&l.vnode(e2),e2}function S(n2){return n2.children}function C(n2,l2){this.props=n2,this.context=l2;}function $(n2,l2){if(null==l2)return n2.__?$(n2.__,n2.__i+1):null;for(var u2;l2<n2.__k.length;l2++)if(null!=(u2=n2.__k[l2])&&null!=u2.__e)return u2.__e;return "function"==typeof n2.type?$(n2):null}function I(n2){if(n2.__P&&n2.__d){var u2=n2.__v,t2=u2.__e,i2=[],r2=[],o2=m({},u2);o2.__v=u2.__v+1,l.vnode&&l.vnode(o2),q(n2.__P,o2,u2,n2.__n,n2.__P.namespaceURI,32&u2.__u?[t2]:null,i2,null==t2?$(u2):t2,!!(32&u2.__u),r2),o2.__v=u2.__v,o2.__.__k[o2.__i]=o2,D(i2,o2,r2),u2.__e=u2.__=null,o2.__e!=t2&&P(o2);}}function P(n2){if(null!=(n2=n2.__)&&null!=n2.__c)return n2.__e=n2.__c.base=null,n2.__k.some(function(l2){if(null!=l2&&null!=l2.__e)return n2.__e=n2.__c.base=l2.__e}),P(n2)}function A(n2){(!n2.__d&&(n2.__d=true)&&i.push(n2)&&!H.__r++||r!=l.debounceRendering)&&((r=l.debounceRendering)||o)(H);}function H(){try{for(var n2,l2=1;i.length;)i.length>l2&&i.sort(e),n2=i.shift(),l2=i.length,I(n2);}finally{i.length=H.__r=0;}}function L(n2,l2,u2,t2,i2,r2,o2,e2,f2,c2,a2){var s2,h2,p2,v2,y2,_2,g2=t2&&t2.__k||w,m2=l2.length;for(f2=T(u2,l2,g2,f2,m2),s2=0;s2<m2;s2++)null!=(p2=u2.__k[s2])&&(h2=-1!=p2.__i&&g2[p2.__i]||d,p2.__i=s2,_2=q(n2,p2,h2,i2,r2,o2,e2,f2,c2,a2),v2=p2.__e,p2.ref&&h2.ref!=p2.ref&&(h2.ref&&J(h2.ref,null,p2),a2.push(p2.ref,p2.__c||v2,p2)),null==y2&&null!=v2&&(y2=v2),4&p2.__u?(f2=j(p2,f2,n2),h2.__e&&(h2.__e=null)):"function"==typeof p2.type&&void 0!==_2?f2=_2:v2&&(f2=v2.nextSibling),p2.__u&=-7);return u2.__e=y2,f2}function T(n2,l2,u2,t2,i2){var r2,o2,e2,f2,c2,a2=u2.length,s2=a2,h2=0;for(n2.__k=new Array(i2),r2=0;r2<i2;r2++)null!=(o2=l2[r2])&&"boolean"!=typeof o2&&"function"!=typeof o2?("string"==typeof o2||"number"==typeof o2||"bigint"==typeof o2||o2.constructor==String?o2=n2.__k[r2]=x(null,o2,null,null,null):g(o2)?o2=n2.__k[r2]=x(S,{children:o2},null,null,null):void 0===o2.constructor&&o2.__b>0?o2=n2.__k[r2]=x(o2.type,o2.props,o2.key,o2.ref?o2.ref:null,o2.__v):n2.__k[r2]=o2,f2=r2+h2,o2.__=n2,o2.__b=n2.__b+1,e2=null,-1!=(c2=o2.__i=O(o2,u2,f2,s2))&&(s2--,(e2=u2[c2])&&(e2.__u|=2)),null==e2||null==e2.__v?(-1==c2&&(i2>a2?h2--:i2<a2&&h2++),"function"!=typeof o2.type&&(o2.__u|=4)):c2!=f2&&(c2==f2-1?h2--:c2==f2+1?h2++:(c2>f2?h2--:h2++,o2.__u|=4))):n2.__k[r2]=null;if(s2)for(r2=0;r2<a2;r2++)null!=(e2=u2[r2])&&0==(2&e2.__u)&&(e2.__e==t2&&(t2=$(e2)),K(e2,e2));return t2}function j(n2,l2,u2){var t2,i2;if("function"==typeof n2.type){for(t2=n2.__k,i2=0;t2&&i2<t2.length;i2++)t2[i2]&&(t2[i2].__=n2,l2=j(t2[i2],l2,u2));return l2}n2.__e!=l2&&(l2&&n2.type&&!l2.parentNode&&(l2=$(n2)),l2=u2.insertBefore(n2.__e,l2||null));do{l2=l2&&l2.nextSibling;}while(null!=l2&&8==l2.nodeType);return l2}function O(n2,l2,u2,t2){var i2,r2,o2,e2=n2.key,f2=n2.type,c2=l2[u2],a2=null!=c2&&0==(2&c2.__u);if(null===c2&&null==e2||a2&&e2==c2.key&&f2==c2.type)return u2;if(t2>(a2?1:0)){for(i2=u2-1,r2=u2+1;i2>=0||r2<l2.length;)if(null!=(c2=l2[o2=i2>=0?i2--:r2++])&&0==(2&c2.__u)&&e2==c2.key&&f2==c2.type)return o2}return -1}function z(n2,l2,u2){"-"==l2[0]?n2.setProperty(l2,null==u2?"":u2):n2[l2]=null==u2?"":"number"!=typeof u2||_.test(l2)?u2:u2+"px";}function N(n2,l2,u2,t2,i2){var r2,o2;n:if("style"==l2)if("string"==typeof u2)n2.style.cssText=u2;else {if("string"==typeof t2&&(n2.style.cssText=t2=""),t2)for(l2 in t2)u2&&l2 in u2||z(n2.style,l2,"");if(u2)for(l2 in u2)t2&&u2[l2]==t2[l2]||z(n2.style,l2,u2[l2]);}else if("o"==l2[0]&&"n"==l2[1])r2=l2!=(l2=l2.replace(s,"$1")),o2=l2.toLowerCase(),l2=o2 in n2||"onFocusOut"==l2||"onFocusIn"==l2?o2.slice(2):l2.slice(2),n2.l||(n2.l={}),n2.l[l2+r2]=u2,u2?t2?u2[a]=t2[a]:(u2[a]=h,n2.addEventListener(l2,r2?v:p,r2)):n2.removeEventListener(l2,r2?v:p,r2);else {if("http://www.w3.org/2000/svg"==i2)l2=l2.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if("width"!=l2&&"height"!=l2&&"href"!=l2&&"list"!=l2&&"form"!=l2&&"tabIndex"!=l2&&"download"!=l2&&"rowSpan"!=l2&&"colSpan"!=l2&&"role"!=l2&&"popover"!=l2&&l2 in n2)try{n2[l2]=null==u2?"":u2;break n}catch(n3){}"function"==typeof u2||(null==u2||false===u2&&"-"!=l2[4]?n2.removeAttribute(l2):n2.setAttribute(l2,"popover"==l2&&1==u2?"":u2));}}function V(n2){return function(u2){if(this.l){var t2=this.l[u2.type+n2];if(null==u2[c])u2[c]=h++;else if(u2[c]<t2[a])return;return t2(l.event?l.event(u2):u2)}}}function q(n2,u2,t2,i2,r2,o2,e2,f2,c2,a2){var s2,h2,p2,v2,y2,d2,_2,k2,x2,M,I2,P2,A2,H2,T2,j2,F=u2.type;if(void 0!==u2.constructor)return null;128&t2.__u&&(c2=!!(32&t2.__u),o2=[f2=u2.__e=t2.__e]),(s2=l.__b)&&s2(u2);n:if("function"==typeof F){h2=e2.length;try{if(x2=u2.props,M=F.prototype&&F.prototype.render,I2=(s2=F.contextType)&&i2[s2.__c],P2=s2?I2?I2.props.value:s2.__:i2,t2.__c?k2=(p2=u2.__c=t2.__c).__=p2.__E:(M?u2.__c=p2=new F(x2,P2):(u2.__c=p2=new C(x2,P2),p2.constructor=F,p2.render=Q),I2&&I2.sub(p2),p2.state||(p2.state={}),p2.__n=i2,v2=p2.__d=true,p2.__h=[],p2._sb=[]),M&&null==p2.__s&&(p2.__s=p2.state),M&&null!=F.getDerivedStateFromProps&&(p2.__s==p2.state&&(p2.__s=m({},p2.__s)),m(p2.__s,F.getDerivedStateFromProps(x2,p2.__s))),y2=p2.props,d2=p2.state,p2.__v=u2,v2)M&&null==F.getDerivedStateFromProps&&null!=p2.componentWillMount&&p2.componentWillMount(),M&&null!=p2.componentDidMount&&p2.__h.push(p2.componentDidMount);else {if(M&&null==F.getDerivedStateFromProps&&x2!==y2&&null!=p2.componentWillReceiveProps&&p2.componentWillReceiveProps(x2,P2),u2.__v==t2.__v||!p2.__e&&null!=p2.shouldComponentUpdate&&false===p2.shouldComponentUpdate(x2,p2.__s,P2)){u2.__v!=t2.__v&&(p2.props=x2,p2.state=p2.__s,p2.__d=false),u2.__e=t2.__e,u2.__k=t2.__k,u2.__k.some(function(n3){n3&&(n3.__=u2);}),w.push.apply(p2.__h,p2._sb),p2._sb=[],p2.__h.length&&e2.push(p2),f2=$(t2);break n}null!=p2.componentWillUpdate&&p2.componentWillUpdate(x2,p2.__s,P2),M&&null!=p2.componentDidUpdate&&p2.__h.push(function(){p2.componentDidUpdate(y2,d2,_2);});}if(p2.context=P2,p2.props=x2,p2.__P=n2,p2.__e=false,A2=l.__r,H2=0,M)p2.state=p2.__s,p2.__d=false,A2&&A2(u2),s2=p2.render(p2.props,p2.state,p2.context),w.push.apply(p2.__h,p2._sb),p2._sb=[];else do{p2.__d=false,A2&&A2(u2),s2=p2.render(p2.props,p2.state,p2.context),p2.state=p2.__s;}while(p2.__d&&++H2<25);p2.state=p2.__s,null!=p2.getChildContext&&(i2=m(m({},i2),p2.getChildContext())),M&&!v2&&null!=p2.getSnapshotBeforeUpdate&&(_2=p2.getSnapshotBeforeUpdate(y2,d2)),T2=null!=s2&&s2.type===S&&null==s2.key?E(s2.props.children):s2,f2=L(n2,g(T2)?T2:[T2],u2,t2,i2,r2,o2,e2,f2,c2,a2),p2.base=u2.__e,u2.__u&=-161,p2.__h.length&&e2.push(p2),k2&&(p2.__E=p2.__=null);}catch(n3){if(e2.length=h2,u2.__v=null,c2||null!=o2){if(n3.then){for(u2.__u|=c2?160:128;f2&&8==f2.nodeType&&f2.nextSibling;)f2=f2.nextSibling;null!=o2&&(o2[o2.indexOf(f2)]=null),u2.__e=f2;}else if(null!=o2)for(j2=o2.length;j2--;)b(o2[j2]);}else u2.__e=t2.__e;null==u2.__k&&(u2.__k=t2.__k||[]),n3.then||B(u2),l.__e(n3,u2,t2);}}else null==o2&&u2.__v==t2.__v?(u2.__k=t2.__k,u2.__e=t2.__e):f2=u2.__e=G(t2.__e,u2,t2,i2,r2,o2,e2,c2,a2);return (s2=l.diffed)&&s2(u2),128&u2.__u?void 0:f2}function B(n2){n2&&(n2.__c&&(n2.__c.__e=true),n2.__k&&n2.__k.some(B));}function D(n2,u2,t2){for(var i2=0;i2<t2.length;i2++)J(t2[i2],t2[++i2],t2[++i2]);l.__c&&l.__c(u2,n2),n2.some(function(u3){try{n2=u3.__h,u3.__h=[],n2.some(function(n3){n3.call(u3);});}catch(n3){l.__e(n3,u3.__v);}});}function E(n2){return "object"!=typeof n2||null==n2||n2.__b>0?n2:g(n2)?n2.map(E):void 0!==n2.constructor?null:m({},n2)}function G(u2,t2,i2,r2,o2,e2,f2,c2,a2){var s2,h2,p2,v2,y2,w2,_2,m2=i2.props||d,k2=t2.props,x2=t2.type;if("svg"==x2?o2="http://www.w3.org/2000/svg":"math"==x2?o2="http://www.w3.org/1998/Math/MathML":o2||(o2="http://www.w3.org/1999/xhtml"),null!=e2){for(s2=0;s2<e2.length;s2++)if((y2=e2[s2])&&"setAttribute"in y2==!!x2&&(x2?y2.localName==x2:3==y2.nodeType)){u2=y2,e2[s2]=null;break}}if(null==u2){if(null==x2)return document.createTextNode(k2);u2=document.createElementNS(o2,x2,k2.is&&k2),c2&&(l.__m&&l.__m(t2,e2),c2=false),e2=null;}if(null==x2)m2===k2||c2&&u2.data==k2||(u2.data=k2);else {if(e2="textarea"==x2&&null!=k2.defaultValue?null:e2&&n.call(u2.childNodes),!c2&&null!=e2)for(m2={},s2=0;s2<u2.attributes.length;s2++)m2[(y2=u2.attributes[s2]).name]=y2.value;for(s2 in m2)y2=m2[s2],"dangerouslySetInnerHTML"==s2?p2=y2:"children"==s2||s2 in k2||"value"==s2&&"defaultValue"in k2||"checked"==s2&&"defaultChecked"in k2||N(u2,s2,null,y2,o2);for(s2 in k2)y2=k2[s2],"children"==s2?v2=y2:"dangerouslySetInnerHTML"==s2?h2=y2:"value"==s2?w2=y2:"checked"==s2?_2=y2:c2&&"function"!=typeof y2||m2[s2]===y2||N(u2,s2,y2,m2[s2],o2);if(h2)c2||p2&&(h2.__html==p2.__html||h2.__html==u2.innerHTML)||(u2.innerHTML=h2.__html),t2.__k=[];else if(p2&&(u2.innerHTML=""),L("template"==t2.type?u2.content:u2,g(v2)?v2:[v2],t2,i2,r2,"foreignObject"==x2?"http://www.w3.org/1999/xhtml":o2,e2,f2,e2?e2[0]:i2.__k&&$(i2,0),c2,a2),null!=e2)for(s2=e2.length;s2--;)b(e2[s2]);c2&&"textarea"!=x2||(s2="value","progress"==x2&&null==w2?u2.removeAttribute("value"):null!=w2&&(w2!==u2[s2]||"progress"==x2&&!w2||"option"==x2&&w2!=m2[s2])&&N(u2,s2,w2,m2[s2],o2),s2="checked",null!=_2&&_2!=u2[s2]&&N(u2,s2,_2,m2[s2],o2));}return u2}function J(n2,u2,t2){try{if("function"==typeof n2){var i2="function"==typeof n2.__u;i2&&n2.__u(),i2&&null==u2||(n2.__u=n2(u2));}else n2.current=u2;}catch(n3){l.__e(n3,t2);}}function K(n2,u2,t2){var i2,r2;if(l.unmount&&l.unmount(n2),(i2=n2.ref)&&(i2.current&&i2.current!=n2.__e||J(i2,null,u2)),null!=(i2=n2.__c)){if(i2.componentWillUnmount)try{i2.componentWillUnmount();}catch(n3){l.__e(n3,u2);}i2.base=i2.__P=i2.__n=null;}if(i2=n2.__k)for(r2=0;r2<i2.length;r2++)i2[r2]&&K(i2[r2],u2,t2||"function"!=typeof n2.type);t2||b(n2.__e),n2.__c=n2.__=n2.__e=void 0;}function Q(n2,l2,u2){return this.constructor(n2,u2)}function R(u2,t2,i2){var r2,o2,e2,f2;t2==document&&(t2=document.documentElement),l.__&&l.__(u2,t2),o2=(r2="function"==typeof i2)?null:i2&&i2.__k||t2.__k,e2=[],f2=[],q(t2,u2=(!r2&&i2||t2).__k=k(S,null,[u2]),o2||d,d,t2.namespaceURI,!r2&&i2?[i2]:o2?null:t2.firstChild?n.call(t2.childNodes):null,e2,!r2&&i2?i2:o2?o2.__e:t2.firstChild,r2,f2),D(e2,u2,f2),u2.props.children=null;}n=w.slice,l={__e:function(n2,l2,u2,t2){for(var i2,r2,o2;l2=l2.__;)if((i2=l2.__c)&&!i2.__)try{if((r2=i2.constructor)&&null!=r2.getDerivedStateFromError&&(i2.setState(r2.getDerivedStateFromError(n2)),o2=i2.__d),null!=i2.componentDidCatch&&(i2.componentDidCatch(n2,t2||{}),o2=i2.__d),o2)return i2.__E=i2}catch(l3){n2=l3;}throw n2}},u=0,C.prototype.setState=function(n2,l2){var u2;u2=null!=this.__s&&this.__s!=this.state?this.__s:this.__s=m({},this.state),"function"==typeof n2&&(n2=n2(m({},u2),this.props)),n2&&m(u2,n2),null!=n2&&this.__v&&(l2&&this._sb.push(l2),A(this));},C.prototype.forceUpdate=function(n2){this.__v&&(this.__e=true,n2&&this.__h.push(n2),A(this));},C.prototype.render=S,i=[],o="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,e=function(n2,l2){return n2.__v.__b-l2.__v.__b},H.__r=0,f=Math.random().toString(8),c="__d"+f,a="__a"+f,s=/(PointerCapture)$|Capture$/i,h=0,p=V(false),v=V(true);
2
+
3
+ export { R, S, k, l };
@@ -0,0 +1,3 @@
1
+ var PLATFORM_BRAND_DEFAULT={primaryColor:"#2563eb",secondaryColor:"#ff5e4d",colorMode:"auto"};var SURFACE={light:{bg:"#fafaf7",surface1:"#ffffff"},dark:{bg:"#0b0c0f",surface1:"#15171c"}};var WHITE="#ffffff";var NEAR_BLACK="#0b0c0f";var ACCENT_TARGET=3;var ADAPT_STEP=.04;var ADAPT_MAX_ITERS=24;var HOVER_DELTA=.08;var SECONDARY_HUE_SHIFT=150;var HEX_RE=/^#[0-9a-fA-F]{6}$/;function toHex(r,g,b){const ch=v=>Math.max(0,Math.min(255,Math.round(v))).toString(16).padStart(2,"0");return `#${ch(r)}${ch(g)}${ch(b)}`}function parseHex(hex){if(typeof hex!=="string"||!HEX_RE.test(hex))return null;const n=Number.parseInt(hex.slice(1),16);return {r:n>>16&255,g:n>>8&255,b:n&255}}function linearize(channel){const s=channel/255;return s<=.03928?s/12.92:Math.pow((s+.055)/1.055,2.4)}function relativeLuminance(rgb){return .2126*linearize(rgb.r)+.7152*linearize(rgb.g)+.0722*linearize(rgb.b)}function assessContrast(fg,bg){const f=parseHex(fg);const b=parseHex(bg);if(!f||!b)return 1;const l1=relativeLuminance(f);const l2=relativeLuminance(b);const hi=Math.max(l1,l2);const lo=Math.min(l1,l2);return (hi+.05)/(lo+.05)}function rgbToHsl({r,g,b}){const rn=r/255;const gn=g/255;const bn=b/255;const max=Math.max(rn,gn,bn);const min=Math.min(rn,gn,bn);const l=(max+min)/2;let h=0;let s=0;if(max!==min){const d=max-min;s=l>.5?d/(2-max-min):d/(max+min);switch(max){case rn:h=(gn-bn)/d+(gn<bn?6:0);break;case gn:h=(bn-rn)/d+2;break;default:h=(rn-gn)/d+4;break}h/=6;}return {h:h*360,s,l}}function hueToRgb(p,q,tRaw){let t=tRaw;if(t<0)t+=1;if(t>1)t-=1;if(t<1/6)return p+(q-p)*6*t;if(t<1/2)return q;if(t<2/3)return p+(q-p)*(2/3-t)*6;return p}function hslToRgb({h,s,l}){const hn=(h%360+360)%360/360;let r;let g;let b;if(s===0){r=g=b=l;}else {const q=l<.5?l*(1+s):l+s-l*s;const p=2*l-q;r=hueToRgb(p,q,hn+1/3);g=hueToRgb(p,q,hn);b=hueToRgb(p,q,hn-1/3);}return {r:Math.round(r*255),g:Math.round(g*255),b:Math.round(b*255)}}function deriveSecondaryHue(hex){const rgb=parseHex(hex);if(!rgb)return PLATFORM_BRAND_DEFAULT.secondaryColor;const hsl=rgbToHsl(rgb);const out=hslToRgb({...hsl,h:(hsl.h+SECONDARY_HUE_SHIFT)%360});return toHex(out.r,out.g,out.b)}function shiftLightness(hex,delta){const rgb=parseHex(hex);if(!rgb)return toHex(0,0,0);const hsl=rgbToHsl(rgb);const out=hslToRgb({...hsl,l:Math.max(0,Math.min(1,hsl.l+delta))});return toHex(out.r,out.g,out.b)}function onColorFor(bg){const white=assessContrast(WHITE,bg);const dark=assessContrast(NEAR_BLACK,bg);return white>=dark?WHITE:NEAR_BLACK}function adaptAccent(hex,surface,target,warnings,field,mode){const rgb=parseHex(hex);if(!rgb){return toHex(0,0,0)}const hsl=rgbToHsl(rgb);const lighten=relativeLuminance(parseHex(surface)??{r:255,g:255,b:255})<.5;const rawRatio=assessContrast(hex,surface);let l=hsl.l;let out=toHex(rgb.r,rgb.g,rgb.b);for(let i=0;i<ADAPT_MAX_ITERS;i+=1){if(assessContrast(out,surface)>=target)break;l=Math.max(0,Math.min(1,l+(lighten?ADAPT_STEP:-ADAPT_STEP)));const o=hslToRgb({h:hsl.h,s:hsl.s,l});out=toHex(o.r,o.g,o.b);}const finalRatio=assessContrast(out,surface);if(rawRatio<target||finalRatio<target){warnings.push({field,mode,ratio:Number(rawRatio.toFixed(2))});}return out}function deriveMode(input,mode,warnings){const surf=SURFACE[mode];const primary=adaptAccent(input.primaryColor,surf.bg,ACCENT_TARGET,warnings,"primary",mode);const rawSecondary=input.secondaryColor??deriveSecondaryHue(input.primaryColor);const secondary=adaptAccent(rawSecondary,surf.bg,ACCENT_TARGET,warnings,"secondary",mode);const primaryHover=shiftLightness(primary,mode==="light"?-HOVER_DELTA:HOVER_DELTA);const onPrimary=onColorFor(primary);const onSecondary=onColorFor(secondary);const ring=primary;return {primary,primaryHover,onPrimary,secondary,onSecondary,ring}}function toSafeBrandColors(input){if(!input||parseHex(input.primaryColor)===null){return {primaryColor:PLATFORM_BRAND_DEFAULT.primaryColor,secondaryColor:PLATFORM_BRAND_DEFAULT.secondaryColor,colorMode:PLATFORM_BRAND_DEFAULT.colorMode}}const secondaryColor=typeof input.secondaryColor==="string"&&parseHex(input.secondaryColor)!==null?input.secondaryColor:null;const colorMode="auto";return {primaryColor:input.primaryColor,secondaryColor,colorMode}}function deriveBrandTokens(input){const safe=toSafeBrandColors(input);const warnings=[];return {light:deriveMode(safe,"light",warnings),dark:deriveMode(safe,"dark",warnings),warnings}}function defaultPrefersDark(){if(typeof window==="undefined"||typeof window.matchMedia!=="function"){return false}try{return window.matchMedia("(prefers-color-scheme: dark)").matches}catch{return false}}function defaultForcedMode(){if(typeof document==="undefined")return null;const dataTheme=document.documentElement.dataset.theme;return dataTheme==="light"||dataTheme==="dark"?dataTheme:null}function brandColorsFrom(primaryColor){return {primaryColor,secondaryColor:PLATFORM_BRAND_DEFAULT.secondaryColor,colorMode:"auto"}}function resolveCaptureTheme(ctxTheme,opts={}){const prefersDark=opts.prefersDark??defaultPrefersDark;const forcedMode=opts.forcedMode??defaultForcedMode;const colorMode=forcedMode()??(prefersDark()?"dark":"light");const primaryColor=ctxTheme?.primaryColor;if(typeof primaryColor!=="string"||primaryColor.length===0){return {colorMode,brandTokens:null}}const brandTokens=deriveBrandTokens(brandColorsFrom(primaryColor))[colorMode];return {colorMode,brandTokens}}
2
+
3
+ export { resolveCaptureTheme };
@@ -0,0 +1,3 @@
1
+ var CREDENTIAL_UNVERIFIABLE_STATUS=401;function isCredentialUnverifiable(result){if(typeof result!=="object"||result===null)return false;if(!("status"in result))return false;return result.status===CREDENTIAL_UNVERIFIABLE_STATUS}function createTokenManager(source,sessionId){const mint=reason=>typeof source==="string"?Promise.resolve(source):source({sessionId:sessionId(),reason});let cached=null;let pending=null;return {get(){if(cached!==null)return cached;const p=mint("initial");cached=p;void p.catch(()=>{if(cached===p)cached=null;});return p},refresh(reason){if(pending!==null)return pending;const p=mint(reason);pending=p;cached=p;void p.then(()=>{if(pending===p)pending=null;},()=>{if(pending===p)pending=null;if(cached===p)cached=null;});return p}}}async function withTokenRetry(tokens,fn,isUnauthorized=isCredentialUnverifiable){const first=await tokens.get();let result;let error;try{result=await fn(first);}catch(err){error=err;}if(error===void 0&&result!==void 0&&!isUnauthorized(result,void 0)){return result}if(error!==void 0&&!isUnauthorized(void 0,error)){throw error}const fresh=await tokens.refresh("401");return fn(fresh)}var CHECKTIV_RECOVERY_STRATEGIES=["retry","cross_device","refresh_session","contact_operator"];var ERROR_TABLE={origin_not_allowed:{recoverable:false,recovery:"contact_operator",message:"This origin is not allowed for the publishable key. Add it to the allowed origins list in the Checktiv console."},token_expired:{recoverable:true,recovery:"retry",message:"The session token expired. The SDK is refreshing it; if this persists, mint a new token from your backend."},session_expired:{recoverable:false,recovery:"refresh_session",message:"The verification session is no longer valid. Start a new verification from your backend."},session_parked:{recoverable:false,recovery:"contact_operator",message:"This verification is not available because of a setup problem on the organization side. Contact the organization that sent you this link."},wrong_token_type:{recoverable:false,recovery:"contact_operator",message:"This verification could not start. Contact the site operator."},protocol_mismatch:{recoverable:false,recovery:"contact_operator",message:"The SDK version is out of date. Update to the latest published version."},camera_denied:{recoverable:true,recovery:"cross_device",message:"Camera access was blocked. Allow camera access, or continue on another device."},camera_policy_blocked:{recoverable:false,recovery:"contact_operator",message:"This page does not allow camera access. Contact the site operator."},camera_unsupported:{recoverable:true,recovery:"cross_device",message:"Your camera does not meet the minimum resolution needed for capture. Try another device, or continue on your phone."},cv_gate_failed:{recoverable:true,recovery:"retry",message:"We could not read the image clearly. Try again with better lighting and a steady hand."},upload_failed:{recoverable:true,recovery:"retry",message:"The upload did not complete. Check the connection and try again."},submit_failed:{recoverable:true,recovery:"retry",message:"The submission did not complete. Your captured images are saved. Check the connection and try again."},sdk_load_failed:{recoverable:true,recovery:"cross_device",message:"Verification could not start on this device. Try again, or continue on another device."},biometric_unsupported:{recoverable:false,recovery:"contact_operator",message:"This capture is not supported on this page. Contact the site operator."},isolation_required:{recoverable:false,recovery:"contact_operator",message:"This page configuration is not supported. Contact the site operator."}};var CHECKTIV_ERROR_CODES=Object.keys(ERROR_TABLE).filter(key=>key in ERROR_TABLE);function createChecktivError(code){const entry=ERROR_TABLE[code];return {code,...entry}}function mapHttpStatusToError(status){if(status===CREDENTIAL_UNVERIFIABLE_STATUS)return "token_expired";if(status===403)return "origin_not_allowed";if(status===429)return "upload_failed";if(status>=500)return "upload_failed";return "session_expired"}function isChecktivErrorCode(value){return CHECKTIV_ERROR_CODES.some(code=>code===value)}function isChecktivRecovery(value){return CHECKTIV_RECOVERY_STRATEGIES.some(recovery=>recovery===value)}function isChecktivError(value){if(typeof value!=="object"||value===null)return false;if(!("code"in value)||!("message"in value)||!("recoverable"in value)||!("recovery"in value)){return false}const{code,message,recoverable,recovery}=value;return typeof code==="string"&&isChecktivErrorCode(code)&&typeof message==="string"&&typeof recoverable==="boolean"&&typeof recovery==="string"&&isChecktivRecovery(recovery)}
2
+
3
+ export { CHECKTIV_ERROR_CODES, CREDENTIAL_UNVERIFIABLE_STATUS, createChecktivError, createTokenManager, isChecktivError, isCredentialUnverifiable, mapHttpStatusToError, withTokenRetry };
@@ -0,0 +1,12 @@
1
+ import { R, k } from './chunk-3KEVZCCZ.js';
2
+ import { parsePublishableKey, createWorkingTokenSource, createWorkingTokenManager } from './chunk-WALPQ6TH.js';
3
+ import { resolveSession, warnWrongTokenPlane } from './chunk-EOTGVXW6.js';
4
+ import { assertNever } from './chunk-UBQTPS5J.js';
5
+ import { getModule, getModuleWarmer } from './chunk-VMWTID63.js';
6
+ import { createTokenManager, createChecktivError, isChecktivError } from './chunk-C7GRMEYT.js';
7
+ import { resolveApiBaseOrigin, sdkPublicSettings, shortCodeRefreshPath, PUBLISHABLE_KEY_HEADER, SESSIONS_ME_REFRESH_LINK_PATH } from './chunk-HFQJYEGZ.js';
8
+ import { getServiceOrigin } from './chunk-QFA3K5ZV.js';
9
+
10
+ var HOST_TAG="checktiv-root";var MOUNTED_FLAG="__checktivMounted";var LEGACY_HOST_ATTR="data-autohost-kyc-host";var HOST_ATTR="data-checktiv-host";var shadowCache=new WeakMap;function mountShadowHost(target){const existing=findExistingHost(target);if(existing){const cached=shadowCache.get(existing);if(cached)return cached}const host=document.createElement("div");host.setAttribute(HOST_ATTR,HOST_TAG);host.setAttribute(LEGACY_HOST_ATTR,HOST_TAG);host[MOUNTED_FLAG]=true;target.appendChild(host);const shadow=host.attachShadow({mode:"closed"});shadowCache.set(host,shadow);return shadow}function findExistingHost(target){for(const child of Array.from(target.children)){if(!(child instanceof HTMLElement))continue;const candidate=child;if(candidate[MOUNTED_FLAG]===true)return candidate}return null}function moduleErrorEvent(name,error){switch(name){case "idv":return {type:"checktiv.idv.error",error};case "fraud":return {type:"checktiv.fraud.error",error};case "custom_form":return {type:"checktiv.custom_form.error",error};case "esign":return {type:"checktiv.esign.error",error};case "credit_history":return {type:"checktiv.credit_history.error",error}}}var MODULE_SUBPATH={idv:"idv",fraud:"fraud",custom_form:"custom-form",esign:"esign",credit_history:"credit-history"};function isSdkModuleName(name){return typeof name==="string"&&Object.hasOwn(MODULE_SUBPATH,name)}function unknownPreloadNameMessage(name){const known=Object.keys(MODULE_SUBPATH).join(", ");return `[Checktiv] preload: ignoring ${JSON.stringify(name)}, which is not a module name. Use one of: ${known}.`}function preloadNotAListMessage(value){return `[Checktiv] preload: expected a list of module names, received the string ${JSON.stringify(value)}. Use preload([${JSON.stringify(value)}]) instead.`}function missingModuleMessage(name){return `This session requires the '${name}' module. Import '@checktiv/sdk-web/${MODULE_SUBPATH[name]}' in your app.`}function missingModuleError(name){const base=createChecktivError("sdk_load_failed");return moduleErrorEvent(name,{...base,message:missingModuleMessage(name)})}function consentGateRequiredError(){const base=createChecktivError("sdk_load_failed");return moduleErrorEvent("fraud",{...base,message:"This session includes the 'fraud' module, which needs a consent gate. Pass onConsent to mountProvisioned() to enable it."})}function customFormConfigRequiredError(){const base=createChecktivError("sdk_load_failed");return moduleErrorEvent("custom_form",{...base,message:"This session includes the 'custom_form' module, which needs its form config. Pass customFormConfig to mountProvisioned() to enable it."})}function unmappedStepTypeError(stepType){const base=createChecktivError("sdk_load_failed");return moduleErrorEvent("idv",{...base,message:`This session's current step ('${stepType}') has no matching visual module in this SDK build. Upgrade '@checktiv/sdk-web' to a version that renders this step.`})}var MODULE_IS_VISUAL={idv:true,fraud:false,custom_form:true,esign:true,credit_history:true};var STEP_TYPE_TO_VISUAL_MODULE={id_verification:"idv",custom_form:"custom_form",esign:"esign",credit_history:"credit_history"};var stepTypeToVisualModuleView=STEP_TYPE_TO_VISUAL_MODULE;function resolveCurrentStepVisualModule(stepType){return stepTypeToVisualModuleView[stepType]}function defaultLoadModule(name){if(name==="idv"){const factory2=getModule("idv");if(factory2===void 0)return Promise.resolve(null);return Promise.resolve({mount:(ctx,opts)=>factory2(ctx,{target:opts.target,onEvent:opts.onEvent,copy:opts.copy,layout:opts.layout,maxWidth:opts.maxWidth,onBeforeSubmit:opts.onBeforeSubmit,onBehaviorSegment:opts.onBehaviorSegment,synthetic:opts.synthetic,crossDeviceCopy:opts.crossDeviceCopy,onOpenCrossDevice:opts.onOpenCrossDevice,session:opts.session})})}if(name==="custom_form"){const factory2=getModule("custom_form");if(factory2===void 0)return Promise.resolve(null);return Promise.resolve({mount:(ctx,opts)=>{if(opts.customFormConfig===void 0){opts.onEvent?.(customFormConfigRequiredError());return {destroy:()=>void 0}}return factory2(ctx,{target:opts.target,config:opts.customFormConfig,copy:opts.customFormCopy,onEvent:opts.onEvent,session:opts.session})}})}if(name==="esign"){const factory2=getModule("esign");if(factory2===void 0)return Promise.resolve(null);return Promise.resolve({mount:(ctx,opts)=>factory2(ctx,{target:opts.target,copy:opts.esignCopy,onEvent:opts.onEvent,session:opts.session,onRequestHelp:opts.onRequestHelp})})}if(name==="credit_history"){const factory2=getModule("credit_history");if(factory2===void 0)return Promise.resolve(null);return Promise.resolve({mount:(ctx,opts)=>factory2(ctx,{target:opts.target,session:opts.session,onEvent:opts.onEvent,copy:opts.creditCopy})})}const factory=getModule("fraud");if(factory===void 0)return Promise.resolve(null);return Promise.resolve({mount:(ctx,opts)=>{const onConsent=opts.onConsent;if(onConsent===void 0){opts.onEvent?.(consentGateRequiredError());return {destroy:()=>void 0}}return factory(ctx,{onConsent,onEvent:opts.onEvent})}})}function moduleErrorFor(name,code){return moduleErrorEvent(name,createChecktivError(code))}function createMountProvisioned(ctx,opts,deps={}){const emit=e=>opts.onEvent?.(e);const fetchImpl=opts.fetchImpl??fetch;const resolveSession2=deps.resolveSession??(()=>resolveSession(ctx,fetchImpl));const loadModule=deps.loadModule??defaultLoadModule;const handles=[];let destroyed=false;let idvOpenCrossDevice=null;void(async()=>{try{await composeModules();}catch(err){if(destroyed)return;console.warn("[Checktiv] mountProvisioned composition failed.",err);emit(moduleErrorFor("idv","sdk_load_failed"));}})();async function composeModules(){const resolution=await resolveSession2();if(destroyed)return;let session;switch(resolution.kind){case "ok":session=resolution.session;break;case "wrong_token":warnWrongTokenPlane();emit(moduleErrorFor("idv","wrong_token_type"));return;case "unresolved":emit(moduleErrorFor("idv","session_expired"));return;case "parked":emit(moduleErrorFor("idv","session_parked"));return;case "nothing_to_render":emit({type:"checktiv.idv.processing",reason:"no_renderable_step"});return;default:return assertNever(resolution)}const currentStepVisualModule=resolveCurrentStepVisualModule(session.stepType);if(currentStepVisualModule===void 0&&session.modules.some(m=>MODULE_IS_VISUAL[m])){emit(unmappedStepTypeError(session.stepType));return}let currentStepModuleDeclared=false;for(const name of session.modules){if(destroyed)return;if(MODULE_IS_VISUAL[name]&&name!==currentStepVisualModule){continue}if(name===currentStepVisualModule)currentStepModuleDeclared=true;if(name==="fraud"&&opts.onConsent===void 0){emit(consentGateRequiredError());continue}const mod=await loadModule(name);if(destroyed)return;if(mod===null){emit(missingModuleError(name));continue}let moduleTarget;let containerToRemove=null;if(MODULE_IS_VISUAL[name]){const resolvedParent=typeof opts.target==="string"?typeof document!=="undefined"?document.querySelector(opts.target):null:opts.target;if(resolvedParent!==null){const container=document.createElement("div");resolvedParent.appendChild(container);containerToRemove=container;moduleTarget=container;}else {moduleTarget=opts.target;}}else {moduleTarget=opts.target;}let innerHandle;try{innerHandle=mod.mount(ctx,{target:moduleTarget,onEvent:opts.onEvent,onConsent:opts.onConsent,copy:opts.copy,layout:opts.layout,maxWidth:opts.maxWidth,onBeforeSubmit:opts.onBeforeSubmit,onBehaviorSegment:opts.onBehaviorSegment,synthetic:opts.synthetic,crossDeviceCopy:opts.crossDeviceCopy,onOpenCrossDevice:opts.onOpenCrossDevice,customFormConfig:opts.customFormConfig,customFormCopy:opts.customFormCopy,esignCopy:opts.esignCopy,creditCopy:opts.creditCopy,onRequestHelp:opts.onRequestHelp,session:{sessionId:session.sessionId,stepId:session.stepId,config:session.config}});}catch(err){containerToRemove?.remove();throw err}if(name==="idv"){idvOpenCrossDevice=innerHandle.openCrossDevice??null;}const capturedContainer=containerToRemove;const handle={destroy(){try{innerHandle.destroy();}finally{capturedContainer?.remove();}}};if(destroyed){handle.destroy();return}handles.push(handle);}if(!destroyed&&currentStepVisualModule!==void 0&&!currentStepModuleDeclared){emit(missingModuleError(currentStepVisualModule));}}return {destroy(){destroyed=true;while(handles.length>0){const handle=handles.pop();handle?.destroy();}},openCrossDevice(){idvOpenCrossDevice?.();}}}function init(opts,deps={}){const scope="publishableKey"in opts?{...parsePublishableKey(opts.publishableKey),publishableKey:opts.publishableKey}:{region:opts.region,mode:opts.mode,publishableKey:void 0};let sessionId="";const apiBaseOrigin=resolveApiBaseOrigin(opts.apiBase,scope.region,scope.mode);const ctx={region:scope.region,mode:scope.mode,publishableKey:scope.publishableKey,apiBaseOrigin,theme:opts.theme,locale:opts.locale??"en",betas:opts.betas??[],...opts.selfiePromptMap!==void 0?{selfiePromptMap:opts.selfiePromptMap}:{},...opts.selfieChromeCopy!==void 0?{selfieChromeCopy:opts.selfieChromeCopy}:{},...opts.beginScanCopy!==void 0?{beginScanCopy:opts.beginScanCopy}:{},tokens:deps.tokens??createTokenManager(opts.getSessionToken,()=>sessionId),getSessionId:()=>sessionId,setSessionId:id=>{sessionId=id;}};function mount2(...args){switch(args[0]){case "idv":{const factory=getModule("idv");if(factory===void 0)return missingIdvHandle(args[1]);return factory(ctx,args[1])}case "custom_form":{const factory=getModule("custom_form");if(factory===void 0)return missingCustomFormHandle(args[1]);return factory(ctx,args[1])}case "esign":{const factory=getModule("esign");if(factory===void 0)return missingEsignHandle(args[1]);return factory(ctx,args[1])}case "credit_history":{const factory=getModule("credit_history");if(factory===void 0)return missingCreditHistoryHandle(args[1]);return factory(ctx,args[1])}case "fraud":{const factory=getModule("fraud");if(factory===void 0)return missingFraudHandle(args[1]);return factory(ctx,args[1])}}}function preload(modules){if(typeof modules==="string"){console.warn(preloadNotAListMessage(modules));return}for(const name of modules){if(!isSdkModuleName(name)){console.warn(unknownPreloadNameMessage(name));continue}getModuleWarmer(name)?.(ctx.region);}}return {mountProvisioned:provOpts=>createMountProvisioned(ctx,provOpts),mount:mount2,preload}}function missingIdvHandle(opts){const base=createChecktivError("sdk_load_failed");opts.onEvent?.({type:"checktiv.idv.error",error:{...base,message:missingModuleMessage("idv")}});return {destroy:()=>void 0,unmount:()=>void 0}}function missingFraudHandle(opts){const base=createChecktivError("sdk_load_failed");opts.onEvent?.({type:"checktiv.fraud.error",error:{...base,message:missingModuleMessage("fraud")}});return {destroy:()=>void 0}}function missingEsignHandle(opts){const base=createChecktivError("sdk_load_failed");const error={type:"checktiv.esign.error",error:{...base,message:missingModuleMessage("esign")}};opts.onEvent?.(error);return {destroy:()=>void 0}}function missingCreditHistoryHandle(opts){const base=createChecktivError("sdk_load_failed");const error={type:"checktiv.credit_history.error",error:{...base,message:missingModuleMessage("credit_history")}};opts.onEvent?.(error);return {destroy:()=>void 0}}function missingCustomFormHandle(opts){const base=createChecktivError("sdk_load_failed");const error={type:"checktiv.custom_form.error",error:{...base,message:missingModuleMessage("custom_form")}};opts.onEvent?.(error);return {destroy:()=>void 0}}var RESUME_CLIENT_TOKEN_KEY_PREFIX="checktiv.rct.";function safeLocalStorage(){try{return globalThis.localStorage??null}catch{return null}}function createClientTokenStore(resumeKey,storage=safeLocalStorage()){const key=RESUME_CLIENT_TOKEN_KEY_PREFIX+resumeKey;return {read(){if(storage===null)return null;try{const raw=storage.getItem(key);return raw!==null&&raw.length>0?raw:null}catch{return null}},write(token){if(storage===null)return;try{storage.setItem(key,token);}catch{}},clear(){if(storage===null)return;try{storage.removeItem(key);}catch{}}}}var SESSIONS_CREATE_ERROR_CODES=["unauthorized","invalid_template","rate_limited","network","server_error"];function createSessionsCreateError(code,message){return {code,message}}function mapHttpStatusToSessionsCreateError(status){if(status===401||status===403)return "unauthorized";if(status===429)return "rate_limited";if(status===400||status===404||status===422)return "invalid_template";return "server_error"}function isSessionsCreateErrorCode(value){return SESSIONS_CREATE_ERROR_CODES.some(code=>code===value)}function isSessionsCreateError(value){if(typeof value!=="object"||value===null)return false;if(!("code"in value)||!("message"in value))return false;const{code,message}=value;return typeof code==="string"&&isSessionsCreateErrorCode(code)&&typeof message==="string"}async function requestSelfServiceResend(params){const fetchImpl=params.fetchImpl??fetch;const body=JSON.stringify({confirmEmail:params.confirmEmail});try{let res;if(params.mode==="short_code"){res=await fetchImpl(params.origin+shortCodeRefreshPath(params.shortCode),{method:"POST",headers:{"content-type":"application/json"},body});}return {requested:res.ok}}catch{return {requested:false}}}var version="1.12.0";var initialised=new WeakSet;function resolveVerifyOrigin(parsed){return getServiceOrigin(sdkPublicSettings.apps.verify.subdomain,"prod",parsed.region,sdkPublicSettings)}function buildPopupUrl(parsed,opts){const origin=resolveVerifyOrigin(parsed);if(opts.applicantLinkToken){return `${origin}/start?lt=${encodeURIComponent(opts.applicantLinkToken)}`}return `${origin}/`}function launchPopup(url){const w=460;const h=760;const left=Math.max(0,Math.floor((window.screen.width-w)/2));const top=Math.max(0,Math.floor((window.screen.height-h)/2));const features=`popup=yes,width=${w},height=${h},left=${left},top=${top}`;const popup=window.open(url,"checktiv",features);if(!popup){window.location.href=url;return null}return popup}var COMPLETE_EVENT_TYPE="autohost.kyc.complete";function isCompletionMessage(data){if(typeof data!=="object"||data===null)return false;if(!("type"in data))return false;return data.type===COMPLETE_EVENT_TYPE}function listenForCompletion(expectedOrigin,onComplete){if(!onComplete)return;const handler=event=>{if(event.origin!==expectedOrigin)return;const data=event.data;if(!isCompletionMessage(data))return;onComplete(data);};window.addEventListener("message",handler);}function buildButton(onClick){const children="Start verification";return k("button",{type:"button",onClick,style:'display: inline-flex; align-items: center; justify-content: center; padding: 10px 20px; font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", sans-serif; font-size: 14px; font-weight: 600; color: #fff; background: #0b5fff; border: none; border-radius: 6px; cursor: pointer;'},children)}function resolveTarget(opts){if(opts.target)return opts.target;return document.querySelector("[data-checktiv]")??document.querySelector("[data-autohost-kyc]")}function mountButton(opts){const parsed=parsePublishableKey(opts.publishableKey);const target=resolveTarget(opts);if(!target){console.warn("[Checktiv] No mount target found. Either pass `target` explicitly or add `<div data-checktiv>` to your page.");return}if(initialised.has(target))return;initialised.add(target);const shadow=mountShadowHost(target);const verifyOrigin=resolveVerifyOrigin(parsed);listenForCompletion(verifyOrigin,opts.onComplete);const onClick=()=>{const popupUrl=buildPopupUrl(parsed,opts);launchPopup(popupUrl);};R(buildButton(onClick),shadow);}var MODULE_COMPLETION_EVENT={idv:"checktiv.idv.submitted",fraud:null,custom_form:"checktiv.custom_form.submitted",esign:"checktiv.esign.submitted",credit_history:"checktiv.credit_history.submitted"};var COMPLETION_EVENT_TYPES=Object.values(MODULE_COMPLETION_EVENT).filter(literal=>literal!==null);function completionSessionId(e){if(!COMPLETION_EVENT_TYPES.some(literal=>literal===e.type))return null;const sid="sessionId"in e?e.sessionId:void 0;return typeof sid==="string"&&sid.length>0?sid:null}function isSessionExpiredEvent(e){if(!e.type.endsWith(".error")||!("error"in e))return false;const err=e.error;if(typeof err!=="object"||err===null||!("code"in err))return false;return err.code==="session_expired"}function checktivErrorFromEvent(e){if(!e.type.endsWith(".error")||!("error"in e))return null;const err=e.error;return isChecktivError(err)?err:null}function mount(target,opts){const fetchImpl=opts.fetchImpl??fetch;const scope="publishableKey"in opts?{...parsePublishableKey(opts.publishableKey),publishableKey:opts.publishableKey}:{region:opts.region,mode:opts.mode,publishableKey:void 0};const mintOrigin=resolveApiBaseOrigin(opts.apiBase,scope.region,scope.mode);const store=opts.resumeKey!==void 0?createClientTokenStore(opts.resumeKey):null;let clientTokenPromise=null;const getClientToken=()=>{if(clientTokenPromise!==null)return clientTokenPromise;const persisted=store?.read()??null;if(persisted!==null){clientTokenPromise=Promise.resolve(persisted);return clientTokenPromise}const p=opts.fetchToken();clientTokenPromise=p;void p.then(tok=>store?.write(tok),()=>{if(clientTokenPromise===p)clientTokenPromise=null;});return p};const mintWorkingToken=createWorkingTokenSource(mintOrigin,getClientToken,scope.publishableKey,fetchImpl);const tokens=createWorkingTokenManager(mintWorkingToken);const base={getSessionToken:()=>tokens.get(),...opts.apiBase!==void 0?{apiBase:opts.apiBase}:{},...opts.theme!==void 0?{theme:opts.theme}:{}};const initOptions=scope.publishableKey!==void 0?{...base,publishableKey:scope.publishableKey}:{...base,region:scope.region,mode:scope.mode};const needsChannel=opts.onEvent!==void 0||opts.onError!==void 0||opts.onComplete!==void 0||store!==null;const safeCall=fn=>{try{fn();}catch{}};const onEvent=needsChannel?e=>{safeCall(()=>opts.onEvent?.(e));const error=checktivErrorFromEvent(e);if(error!==null)safeCall(()=>opts.onError?.(error));const sessionId=completionSessionId(e);if(sessionId!==null){store?.clear();safeCall(()=>opts.onComplete?.({sessionId}));}else if(isSessionExpiredEvent(e)){store?.clear();}}:void 0;const client=init(initOptions,{tokens});const handle=client.mountProvisioned({target,fetchImpl,onEvent,onConsent:opts.onConsent,...opts.layout!==void 0?{layout:opts.layout}:{},...opts.maxWidth!==void 0?{maxWidth:opts.maxWidth}:{},...opts.copy!==void 0?{copy:opts.copy}:{},...opts.crossDeviceCopy!==void 0?{crossDeviceCopy:opts.crossDeviceCopy}:{},...opts.onOpenCrossDevice!==void 0?{onOpenCrossDevice:opts.onOpenCrossDevice}:{}});const requestResend=confirmEmail=>{if(opts.shortCode===void 0)return Promise.resolve({requested:false});return requestSelfServiceResend({mode:"short_code",origin:mintOrigin,shortCode:opts.shortCode,confirmEmail,fetchImpl})};return {destroy(){handle.destroy();tokens.stop();},openCrossDevice:()=>handle.openCrossDevice?.(),requestResend}}function addressToWire(a){const wire={line1:a.line1,city:a.city,country:a.country};if(a.line2!==void 0)wire.line2=a.line2;if(a.region!==void 0)wire.region=a.region;if(a.postalCode!==void 0)wire.postal_code=a.postalCode;if(a.placeId!==void 0)wire.place_id=a.placeId;if(a.formatted!==void 0)wire.formatted=a.formatted;return wire}function applicantToWire(a){return {external_id:a.externalId,email:a.email,phone:a.phone,family_name:a.familyName,given_names:a.givenNames===void 0?void 0:[...a.givenNames],name_suffix:a.nameSuffix,date_of_birth:a.dateOfBirth,address:a.address===void 0?void 0:addressToWire(a.address),reference_name:a.referenceName,booking_name:a.bookingName}}function readCreatedClientToken(body){if(typeof body!=="object"||body===null||!("data"in body))return null;const data=body.data;if(typeof data!=="object"||data===null||!("client_token"in data))return null;const clientToken=data.client_token;return typeof clientToken==="string"&&clientToken.length>0?clientToken:null}var SESSIONS_CREATE_STATUS_HINT={unauthorized:"Verify your secret key (ah_sk_*) and that it matches the apiBase region.",invalid_template:"Verify the templateId (wt_*) and the request body.",rate_limited:"You have hit the rate ceiling. Retry after a short backoff.",network:"Check the apiBase origin and your network connectivity.",server_error:"This looks like a transient server error. Retry after a short backoff."};function sessionsCreateStatusHint(code){return SESSIONS_CREATE_STATUS_HINT[code]}var sessions={async create(input,options){if(typeof window!=="undefined"||typeof document!=="undefined"){throw new Error("checktiv.sessions.create must run on your server: it needs your secret key. Never call it in the browser.")}const fetchImpl=options.fetchImpl??fetch;const headers={Authorization:`Bearer ${options.secretKey}`,"content-type":"application/json"};if(options.idempotencyKey!==void 0)headers["Idempotency-Key"]=options.idempotencyKey;const body=JSON.stringify({workflow_template_id:input.templateId,applicant:applicantToWire(input.applicant)});let res;try{res=await fetchImpl(`${options.apiBase}/v1/sessions`,{method:"POST",headers,body});}catch{throw createSessionsCreateError("network","Checktiv sessions.create could not reach the API. Check the apiBase origin and your network connectivity.")}if(!res.ok){const code=mapHttpStatusToSessionsCreateError(res.status);throw createSessionsCreateError(code,`Checktiv sessions.create failed (status ${res.status}). ${sessionsCreateStatusHint(code)}`)}let parsed;try{parsed=await res.json();}catch{throw createSessionsCreateError("network","Checktiv sessions.create returned a non-JSON response.")}const clientToken=readCreatedClientToken(parsed);if(clientToken===null){throw createSessionsCreateError("server_error","Checktiv sessions.create response carried no client token. Enable the working-token capability for this environment, then retry.")}return {clientToken}}};
11
+
12
+ export { init, isSessionsCreateError, mount, mountButton, sessions, version };
@@ -0,0 +1,7 @@
1
+ import { IDV_DOCUMENT_TYPES } from './chunk-IQKHRPJR.js';
2
+ import { withTokenRetry, isChecktivError } from './chunk-C7GRMEYT.js';
3
+ import { sdkPublicSettings, SESSIONS_ME_PATH, dataPlaneHeaders } from './chunk-HFQJYEGZ.js';
4
+
5
+ var SDK_MODULES=["idv","fraud","custom_form","esign","credit_history"];var BIOMETRIC_MODES=["none","selfie","liveness"];var DOCUMENT_TYPES=IDV_DOCUMENT_TYPES;var SDK_MODES=["live","test"];var DATA_REGIONS=Object.keys(sdkPublicSettings.regions);var COLLECT_USER_INFO_FIELD_VALUES=["email","phone","dob","address"];var COLLECT_USER_INFO_NAME_COMPONENTS_VALUES=["required","requested","optional"];function isRecord(v){return typeof v==="object"&&v!==null}function isNonEmptyString(v){return typeof v==="string"&&v.length>0}function isSdkModule(v){return typeof v==="string"&&SDK_MODULES.includes(v)}function isBiometricMode(v){return typeof v==="string"&&BIOMETRIC_MODES.includes(v)}function isSdkMode(v){return typeof v==="string"&&SDK_MODES.includes(v)}function isSdkRegion(v){return typeof v==="string"&&DATA_REGIONS.includes(v)}function isDocumentType(v){return typeof v==="string"&&DOCUMENT_TYPES.includes(v)}function isCollectUserInfoField(v){return typeof v==="string"&&COLLECT_USER_INFO_FIELD_VALUES.includes(v)}function isNameComponents(v){return typeof v==="string"&&COLLECT_USER_INFO_NAME_COMPONENTS_VALUES.includes(v)}function parseCollectUserInfoConfig(value){if(!isRecord(value))return null;const fields=value.fields;const captureStructuredName=value.capture_structured_name;const nameComponents=value.name_components;if(!Array.isArray(fields))return null;const parsedFields=[];for(const f of fields){if(!isCollectUserInfoField(f))return null;parsedFields.push(f);}if(typeof captureStructuredName!=="boolean")return null;if(!isNameComponents(nameComponents))return null;return {fields:parsedFields,nameComponents,captureStructuredName}}function warnMalformedAllowDocumentUpload(received){console.warn(`[Checktiv] The sessions/me config carried a non-boolean \`allow_document_upload\` (received ${received}). Treating it as false, so this session will not offer document upload even if the template enables it. This is a server or serializer drift, not a client option.`);}function parseIdvConfig(value){if(!isRecord(value))return null;const documentTypes=value.document_types;const biometricMode=value.biometric_mode;const minAge=value.min_age;if(!Array.isArray(documentTypes)||documentTypes.length<1)return null;const types=[];for(const t of documentTypes){if(!isDocumentType(t))return null;types.push(t);}if(!isBiometricMode(biometricMode))return null;if(minAge!==void 0&&typeof minAge!=="number")return null;const rawAllowDocumentUpload=value.allow_document_upload;if(rawAllowDocumentUpload!==void 0&&typeof rawAllowDocumentUpload!=="boolean"){warnMalformedAllowDocumentUpload(typeof rawAllowDocumentUpload);}const allowDocumentUpload=rawAllowDocumentUpload===true;const config={documentTypes:types,biometricMode,allowDocumentUpload};if(typeof minAge==="number")config.minAge=minAge;return config}function parseSessionData(body){if(!isRecord(body)||!isRecord(body.data))return null;const d=body.data;const sessionId=d.session_id;const stepId=d.step_id;const stepType=d.step_type;if(!isNonEmptyString(sessionId)||!isNonEmptyString(stepId)||!isNonEmptyString(stepType)||!isSdkMode(d.mode)||!isSdkRegion(d.region)){return null}if(!Array.isArray(d.modules)||!d.modules.every(isSdkModule))return null;const modules=d.modules;const wantsIdv=stepType==="id_verification";let config=null;if(wantsIdv){config=parseIdvConfig(d.config);if(config===null)return null}const collectUserInfoConfig=stepType==="collect_user_info"?parseCollectUserInfoConfig(d.config)??void 0:void 0;return {sessionId,stepId,stepType,config,mode:d.mode,region:d.region,modules,...collectUserInfoConfig!==void 0?{collectUserInfoConfig}:{}}}function isJourneyPlaneBody(body){if(!isRecord(body)||!isRecord(body.data))return false;const d=body.data;if("session_id"in d)return false;return isRecord(d.session)||isRecord(d.snapshot)}function isNonRenderableMarker(body){if(!isRecord(body)||!isRecord(body.data))return false;return body.data.renderable===false}function warnWrongTokenPlane(){console.warn("[Checktiv] The session token reached the wrong data plane. For the zero-lifecycle APIs (Checktiv.mount() or collectUserInfo), fetchToken must return your durable client token, which the SDK exchanges for a working token. For a customer-embed Checktiv.init(), getSessionToken must return a browser token.");}async function resolveSession(ctx,fetchImpl){const origin=ctx.apiBaseOrigin;let res;try{res=await withTokenRetry(ctx.tokens,token=>fetchImpl(origin+SESSIONS_ME_PATH,{method:"GET",headers:dataPlaneHeaders(ctx,token)}));}catch(err){if(isChecktivError(err)&&err.code==="session_parked")return {kind:"parked"};return {kind:"unresolved"}}if(!res.ok)return {kind:"unresolved"};let body;try{body=await res.json();}catch{return {kind:"unresolved"}}if(isNonRenderableMarker(body))return {kind:"nothing_to_render"};const data=parseSessionData(body);if(data!==null){ctx.setSessionId(data.sessionId);return {kind:"ok",session:data}}if(isJourneyPlaneBody(body))return {kind:"wrong_token"};return {kind:"unresolved"}}
6
+
7
+ export { isJourneyPlaneBody, isRecord, resolveSession, warnWrongTokenPlane };
@@ -1,4 +1,4 @@
1
- import { l } from './chunk-XOGHMNBX.js';
1
+ import { l } from './chunk-3KEVZCCZ.js';
2
2
 
3
3
  var f=0;function u(e,t,n,o,i,u2){t||(t={});var a,c,p=t;if("ref"in p)for(c in p={},t)"ref"==c?a=t[c]:p[c]=t[c];var l2={type:e,props:p,key:n,ref:a,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:--f,__i:-1,__u:0,__source:i,__self:u2};if("function"==typeof e&&(a=e.defaultProps))for(c in a) void 0===p[c]&&(p[c]=a[c]);return l.vnode&&l.vnode(l2),l2}
4
4
 
@@ -1,7 +1,7 @@
1
- import { u } from './chunk-HV2QKVJX.js';
2
- import { R, k } from './chunk-XOGHMNBX.js';
3
- import { createCaptureController, isBiometricPhase, coachingKindForState } from './chunk-T4R5TTE5.js';
4
- import { isCameraPolicyRelabelable } from './chunk-XSSM5ZB7.js';
1
+ import { createCaptureController, isBiometricPhase, coachingKindForState } from './chunk-PB2THQ3P.js';
2
+ import { isCameraPolicyRelabelable } from './chunk-ZU4L3NDZ.js';
3
+ import { u } from './chunk-FQSJUWRP.js';
4
+ import { R, k } from './chunk-3KEVZCCZ.js';
5
5
 
6
6
  function coachingFallback(kind){switch(kind){case "move_closer":return "Move a little closer.";case "move_farther":return "Move a little farther away.";case "reduce_glare":return "Reduce glare: tilt away from bright light.";case "too_dark":return "Find a brighter, well-lit spot.";case "wrong_side":return "Show the other side of your document.";case "hold_steady":return "Hold steady and keep everything in frame."}}function statusFallback(phase){switch(phase){case "ready":return "Getting the camera ready.";case "document_front":return "Position the front of your document in the frame.";case "document_back":return "Now show the back of your document.";case "selfie":return "Center your face in the frame.";case "liveness":return "Follow the on-screen prompts to confirm it is you.";case "uploading":return "Uploading. This takes a few seconds.";case "coaching":return "Hold steady and keep everything in frame."}}var CAMERA_POLICY_BLOCKED_TEXT="This page is not allowing camera access, so verification cannot continue. This is a setup problem on the site, not a problem with your device, and another device will not help. Please contact the operator to continue.";function errorFallback(kind){switch(kind){case "cv_gate_failed":return "We could not read that capture. Please try again in good lighting.";case "upload_failed":return "The upload did not finish. Check your connection and try again.";case "sdk_load_failed":return "The capture tools could not load. Refresh, or continue on your phone.";case "biometric_unsupported":return "This device cannot run the selfie check. Please continue on your phone.";case "camera_unsupported":return "Your camera does not meet the minimum resolution for capture. Please continue on your phone.";case "selfie_camera_denied":return "Camera access was blocked. Allow the camera, or continue on your phone.";case "liveness_camera_denied":return "Camera access was blocked. Allow the camera, or continue on your phone.";case "liveness_timeout":return "The check timed out. Please try again.";case "liveness_server_error":return "Something went wrong on our side. Please try again.";case "liveness_runtime_error":return "The check could not run. Refresh and try again.";case "liveness_cancelled":return "The check was canceled. Please try again when you are ready.";case "protocol_mismatch":return "This version of the verification tool is no longer supported. Please contact the operator to continue.";default:{const _exhaustive=kind;return _exhaustive}}}function terminalFallback(kind){switch(kind){case "mint_error":return "We could not start verification. Please try again.";case "submit_error":return "We could not submit your capture. Please try again.";case "token_expired":return "This step expired for your security. Please refresh to start again.";case "capture_superseded":return "Verification is active on another device. Finish there, or select Try again to continue here.";default:{const _exhaustive=kind;return _exhaustive}}}var fallbackCopy={cvReject:(_attemptIndex,kind)=>`We could not use that photo. ${coachingFallback(kind)}`,error:errorFallback,status:statusFallback,coaching:coachingFallback,terminal:terminalFallback,cameraPolicyBlocked:()=>CAMERA_POLICY_BLOCKED_TEXT,tryAgain:()=>"Try again",frameTitle:()=>"Identity verification capture"};var CSS_LENGTH_PATTERN=/^\d+(?:\.\d+)?(?:px|rem|em|vw|vh|%|ch)$/;function isValidCssLength(value){return CSS_LENGTH_PATTERN.test(value)}function maxWidthStyle(maxWidth){if(maxWidth===void 0||!isValidCssLength(maxWidth))return void 0;return `--idv-capture-max-width: ${maxWidth};`}var IFRAME_SANDBOX="allow-scripts allow-same-origin";function phaseOf(state){if(state.kind==="capturing")return state.phase;return "ready"}function statusLine(state,copy){if(state.kind==="capturing"&&state.phase==="coaching"&&state.coaching!==null){return (copy.coaching??fallbackCopy.coaching)(state.coaching)}return (copy.status??fallbackCopy.status)(phaseOf(state))}function CvRejectAlert({reason,attemptIndex,copy}){const kind=coachingKindForState(reason);const text=(copy.cvReject??fallbackCopy.cvReject)(attemptIndex,kind);return u("div",{role:"status","data-testid":"idv-cv-reject-alert",className:"idv-capture-cv-reject",style:"margin-bottom: 0.75rem;",children:text})}function CaptureFrame(props){const{colorMode="light",maxWidth}=props;const style=maxWidthStyle(maxWidth);return u("div",{className:"idv-capture-root","data-color-mode":colorMode,style,children:renderCaptureArm(props)})}function renderCaptureArm({state,attemptIndex,getEmbedSrc,onTryAgain,copy,layout="inline",immersiveActive=false,colorMode="light"}){switch(state.kind){case "minting":return u("div",{children:[u("div",{"data-testid":"idv-capture-skeleton","data-color-mode":colorMode,className:"idv-capture-skeleton idv-capture-skeleton--document idv-capture-skeleton--standalone","aria-hidden":"true"}),u("p",{className:"idv-capture-status","aria-live":"polite",children:(copy.status??fallbackCopy.status)("ready")})]});case "mint_error":case "submit_error":case "token_expired":case "capture_superseded":return u("div",{className:"idv-capture-error",role:"alert",children:[u("p",{children:(copy.terminal??fallbackCopy.terminal)(state.kind)}),u("button",{type:"button",onClick:onTryAgain,className:"idv-capture-retry",children:copy.tryAgain??fallbackCopy.tryAgain()})]});case "capture_error":{const errorKind=state.errorKind;const cameraPolicyBlocked=state.cameraPolicyBlocked===true&&isCameraPolicyRelabelable(errorKind);const terminal=errorKind==="protocol_mismatch"||cameraPolicyBlocked;return u("div",{className:"idv-capture-error",role:"alert",children:[u("p",{children:cameraPolicyBlocked?(copy.cameraPolicyBlocked??fallbackCopy.cameraPolicyBlocked)():(copy.error??fallbackCopy.error)(errorKind)}),!terminal&&u("button",{type:"button",onClick:onTryAgain,className:"idv-capture-retry",children:copy.tryAgain??fallbackCopy.tryAgain()})]})}case "submitting":case "submit_pending":return u("p",{className:"idv-capture-status",children:(copy.status??fallbackCopy.status)("uploading")});case "waiting_for_init":case "ready":case "capturing":{const phase=phaseOf(state);const biometric=isBiometricPhase(phase);const frameClass=biometric?"idv-capture-frame idv-capture-frame--biometric":"idv-capture-frame";const reason=state.kind==="capturing"?state.lastCvRejectReason:null;const biometricLoading=biometric&&state.kind==="capturing"&&state.biometricLoading;const initialLoading=state.kind==="waiting_for_init";const showSkeleton=biometricLoading||initialLoading;const skeletonClass=initialLoading?"idv-capture-skeleton idv-capture-skeleton--document":"idv-capture-skeleton";const embedSrc=getEmbedSrc(state.embedOrigin);const immersive=layout==="immersive";const wrapperClass=immersive?"idv-capture-active idv-capture-immersive":"idv-capture-active";const frameTitle=copy.frameTitle??fallbackCopy.frameTitle();let iframeEl=null;const focusFrame=()=>iframeEl?.focus();return u("div",{className:wrapperClass,"data-color-mode":colorMode,role:immersiveActive?"dialog":void 0,"aria-modal":immersiveActive?"true":void 0,"aria-label":immersiveActive?frameTitle:void 0,children:[reason!==null&&u(CvRejectAlert,{reason,attemptIndex,copy}),showSkeleton&&u("div",{"data-testid":"idv-capture-skeleton","data-color-mode":colorMode,className:skeletonClass,"aria-hidden":"true"}),immersiveActive&&u("div",{className:"idv-capture-sentinel",tabIndex:0,onFocus:focusFrame}),u("iframe",{ref:el=>{iframeEl=el;},className:frameClass,title:frameTitle,src:embedSrc,allow:"camera",sandbox:IFRAME_SANDBOX}),immersiveActive&&u("div",{className:"idv-capture-sentinel",tabIndex:0,onFocus:focusFrame}),u("p",{className:"idv-capture-status","aria-live":"polite",children:statusLine(state,copy)})]})}default:{const _exhaustive=state;return _exhaustive}}}var IMMERSIVE_MEDIA="(pointer: coarse) and (max-width: 640px), (pointer: coarse) and (max-height: 640px)";function matchesImmersive(){return typeof window!=="undefined"&&typeof window.matchMedia==="function"&&window.matchMedia(IMMERSIVE_MEDIA).matches}function subscribeImmersive(cb){if(typeof window==="undefined"||typeof window.matchMedia!=="function"){return ()=>{}}const mql=window.matchMedia(IMMERSIVE_MEDIA);mql.addEventListener("change",cb);return ()=>{mql.removeEventListener("change",cb);}}function mount(element,options){const{copy,layout,maxWidth,onState,onControllerEvent,...deps}=options;const resolvedInitPayload=deps.initPayload();const controller=createCaptureController({...deps,initPayload:()=>resolvedInitPayload,getIframe:()=>element.querySelector("iframe.idv-capture-frame")});let destroyed=false;let state={kind:"minting"};let attemptIndex=0;const computeImmersiveActive=()=>layout==="immersive"&&matchesImmersive();let immersiveActive=computeImmersiveActive();let prevFocusable=false;let prevStateKind=state.kind;const IMMERSIVE_FILL_TOLERANCE_PX=2;let selfCheckRaf;let selfCheckWarned=false;const scheduleImmersiveSelfCheck=()=>{if(typeof requestAnimationFrame!=="function")return;if(selfCheckRaf!==void 0&&typeof cancelAnimationFrame==="function"){cancelAnimationFrame(selfCheckRaf);}selfCheckRaf=requestAnimationFrame(()=>{selfCheckRaf=void 0;if(destroyed||selfCheckWarned||typeof window==="undefined")return;const overlay=element.querySelector(".idv-capture-immersive");if(overlay===null)return;const rect=overlay.getBoundingClientRect();const vw=window.innerWidth;const vh=window.innerHeight;if(Math.abs(rect.width-vw)>IMMERSIVE_FILL_TOLERANCE_PX||Math.abs(rect.height-vh)>IMMERSIVE_FILL_TOLERANCE_PX){selfCheckWarned=true;console.warn("[Checktiv] immersive capture overlay does not fill the viewport",rect.width,rect.height,vw,vh);}});};const ERROR_ARM_KINDS={minting:false,mint_error:true,waiting_for_init:false,ready:false,capturing:false,submitting:false,submit_error:true,submit_pending:false,capture_superseded:true,token_expired:true,capture_error:true};const isErrorArm=kind=>ERROR_ARM_KINDS[kind];const onTryAgain=()=>{if(typeof window!=="undefined")window.location.reload();};const paint=()=>{if(destroyed)return;R(k(CaptureFrame,{state,attemptIndex,getEmbedSrc:deps.getEmbedSrc,onTryAgain,copy,layout,maxWidth,immersiveActive,colorMode:resolvedInitPayload.theme.colorMode}),element);const iframeEl=element.querySelector("iframe.idv-capture-frame");const iframePresent=iframeEl!==null;const focusable=immersiveActive&&iframePresent;if(focusable&&!prevFocusable&&!destroyed){iframeEl?.focus();scheduleImmersiveSelfCheck();}if(isErrorArm(state.kind)&&state.kind!==prevStateKind){element.querySelector(".idv-capture-retry")?.focus();}prevFocusable=focusable;prevStateKind=state.kind;};const rerender=()=>{if(destroyed)return;immersiveActive=computeImmersiveActive();paint();};const unsubImmersive=layout==="immersive"?subscribeImmersive(rerender):void 0;const safeObserve=(fn,arg)=>{if(fn===void 0)return;try{fn(arg);}catch(err){console.warn("[Checktiv] capture observer threw; ignoring (observational only).",err);}};const unsubState=controller.subscribe(next=>{state=next;paint();safeObserve(onState,next);});const offReject=controller.on("selfie-cv-reject",event=>{if(event.type==="selfie-cv-reject"){attemptIndex=event.attemptIndex;paint();}safeObserve(onControllerEvent,event);});const offComplete=controller.on("all-complete",event=>{safeObserve(onControllerEvent,event);});controller.start();return {destroy(){if(destroyed)return;destroyed=true;unsubState();offReject();offComplete();if(unsubImmersive!==void 0)unsubImmersive();if(selfCheckRaf!==void 0&&typeof cancelAnimationFrame==="function"){cancelAnimationFrame(selfCheckRaf);}R(null,element);controller.destroy();}}}
7
7
 
@@ -1,5 +1,5 @@
1
- import { createChecktivError } from './chunk-7GP5REM7.js';
2
- import { isCameraPolicyRelabelable } from './chunk-XSSM5ZB7.js';
1
+ import { isCameraPolicyRelabelable } from './chunk-ZU4L3NDZ.js';
2
+ import { createChecktivError } from './chunk-C7GRMEYT.js';
3
3
 
4
4
  function createChecktivErrorEvent(code){return {type:"checktiv.idv.error",error:createChecktivError(code)}}var CAPTURE_ERROR_CODE={cv_gate_failed:"cv_gate_failed",upload_failed:"upload_failed",sdk_load_failed:"sdk_load_failed",biometric_unsupported:"biometric_unsupported",camera_unsupported:"camera_unsupported",selfie_camera_denied:"camera_denied",liveness_camera_denied:"camera_denied",liveness_runtime_error:"sdk_load_failed",liveness_timeout:"sdk_load_failed",liveness_server_error:"sdk_load_failed",liveness_cancelled:"sdk_load_failed",protocol_mismatch:"protocol_mismatch"};function captureErrorCode(state){if(state.cameraPolicyBlocked===true&&isCameraPolicyRelabelable(state.errorKind)){return "camera_policy_blocked"}return CAPTURE_ERROR_CODE[state.errorKind]}function mapStateToEvent(state,ctx){switch(state.kind){case "minting":case "waiting_for_init":case "submitting":return null;case "ready":return {type:"checktiv.idv.ready",config:ctx.config};case "capturing":if(state.phase==="coaching"&&state.coaching!==null){return {type:"checktiv.idv.coaching",hint:state.coaching}}return {type:"checktiv.idv.phase",phase:state.phase};case "mint_error":return createChecktivErrorEvent("session_expired");case "submit_error":return createChecktivErrorEvent("submit_failed");case "submit_pending":return {type:"checktiv.idv.processing",reason:"signal_pending"};case "capture_superseded":return {type:"checktiv.idv.capture_superseded"};case "token_expired":return createChecktivErrorEvent("token_expired");case "capture_error":return createChecktivErrorEvent(captureErrorCode(state));default:{return null}}}var opener=null;function registerCrossDeviceOpener(fn){opener=fn;}function getCrossDeviceOpener(){return opener}
5
5
 
@@ -0,0 +1,3 @@
1
+ var ESIGN_STATES=["preparing","consent","read","scroll_incomplete","adopt","age_gate","explain","sign","decline","withdraw","obscured","frame_blocked","age_blocked","conflict","token_expired","protocol_mismatch","error","submit_error","terminal_signed","terminal_declined","terminal_voided","terminal_expired","terminal_withdrawn"];var ESIGN_FRAME_FATAL_STATES=["conflict","protocol_mismatch","error"];function isEsignFrameFatalState(state){return ESIGN_FRAME_FATAL_STATES.includes(state)}var TERMINAL_STATUS_TO_STATE={signed:"terminal_signed",declined:"terminal_declined",voided:"terminal_voided",expired:"terminal_expired"};function isTerminalEnvelopeStatus(status){return Object.prototype.hasOwnProperty.call(TERMINAL_STATUS_TO_STATE,status)}var ESIGN_CONSENT_ACTIONS=["withdraw_consent","request_paper_copy"];var ESIGN_DOCUMENT_ACTIONS=["download"];var ESIGN_STATE_RIGHTS={preparing:"none",consent:"both",read:"both",scroll_incomplete:"both",adopt:"both",age_gate:"both",explain:"both",sign:"both",decline:"both",withdraw:"both",obscured:"both",age_blocked:"none",frame_blocked:"none",conflict:"none",token_expired:"none",protocol_mismatch:"none",error:"none",submit_error:"none",terminal_signed:"none",terminal_declined:"none",terminal_voided:"none",terminal_expired:"none",terminal_withdrawn:"none"};function esignStateOffersRights(state){return ESIGN_STATE_RIGHTS[state]!=="none"}var ESIGN_PREPARING_MAX_INTERVAL_MS=5e3;var ESIGN_PREPARING_MAX_ATTEMPTS=12;var ESIGN_PREPARING_STALL_MS=2e4;var ESIGN_FRAME_ANNOUNCE_TIMEOUT_MS=2e4;var ESIGN_PREPARING_DEFAULT_INTERVAL_MS=1500;function esignPreparingDelayMs(retryAfterMs){const floor=typeof retryAfterMs==="number"&&Number.isFinite(retryAfterMs)&&retryAfterMs>0?retryAfterMs:ESIGN_PREPARING_DEFAULT_INTERVAL_MS;return Math.min(floor,ESIGN_PREPARING_MAX_INTERVAL_MS)}var ESIGN_SCROLL_TARGET_MARGIN_PX=24;var ESIGN_LOAD_FAILED_MESSAGE="Something went wrong loading your document. Reload the page to try again. If it keeps happening, contact the company that sent you this link.";var ESIGN_COPY_FALLBACKS={preparing:"Your documents are being prepared. This page will update on its own in a moment.",consent:"Select the signature line in the document to add your signature. Confirming it also records your agreement to use electronic records.",read:"Read the full document below. Scroll to the end to continue.",scroll_incomplete:"You have not reached the end of the document yet. Scroll to the bottom and the Finish button turns on.",adopt:"Select the signature line in the document. Adding your signature also records your agreement to use electronic records.",age_gate:"Confirm that you meet the minimum age for this document, then continue.",explain:"Selecting Finish applies the signature you adopted to the document above and records the date and time. Read the document once more if you want to, then select Finish.",sign:"Select Finish to apply your signature to the document above.",decline:"Tell us why you do not want to sign, then select Send my decline. You can close this window afterward.",withdraw:"You can stop using electronic records for this document. Confirm below to stop here, and nothing will be signed. Asking for a mailed paper copy is a separate control, and it stays available afterward.",obscured:"The Finish button is covered by something else on this page, so it is turned off for now. Open your signing link directly in a new window to continue.",frame_blocked:"The signing window did not open. Reload the page to try again. If it still does not open, try a different browser, or ask the company that sent you this link for help.",conflict:"This document changed while you had it open. Reload the page to get the current version before you sign.",token_expired:"This signing page needs a fresh connection. Reload the page to pick up where you left off.",protocol_mismatch:"This page is out of date and cannot show the document safely. Reload the page. If it keeps happening, contact the company that sent you this link.",error:ESIGN_LOAD_FAILED_MESSAGE,submit_error:"We could not confirm that your signature was recorded. Reload the page to see whether it went through, and sign again if it did not.",terminal_signed:"This document is signed. Nothing else is needed here, so you can close this window.",terminal_declined:"You declined to sign this document. If that was a mistake, contact the company that sent you this link.",terminal_voided:"This document was canceled and can no longer be signed. Contact the company that sent you this link if you still need to sign it.",terminal_expired:"The time to sign this document has passed. Contact the company that sent you this link to ask for a new one.",terminal_withdrawn:"You withdrew your agreement to sign electronically, so nothing was signed. The company that sent you this link has been told. Contact them to ask for this document on paper, or for a new signing link if you change your mind.",age_blocked:"This document can only be signed by someone above a minimum age, so it cannot be signed here. Nothing was signed. You can decline to sign from More actions, or contact the company that sent you this link if you think this is wrong.",frameTitle:"Document signing"};var ESIGN_LABELS=["finish","adopt","cancel","change","tryAgain","reload","reloadToCheck","getHelp","moreActions","jumpToEnd","readNotice","signatureBlock","signatureBlockDone","finishLater","printAndSign","decline","declineSubmit","declineCancel","signatureName","signatureStyle","declineReason","ageConfirm","documentHeading","signatureHeading"];var ESIGN_LABEL_FALLBACKS={finish:"Finish",adopt:"Use this signature",cancel:"Cancel",change:"Change",tryAgain:"Try again",reload:"Reload the page",reloadToCheck:"Reload to check",getHelp:"Get help",moreActions:"More actions",readNotice:"Notice and your rights",jumpToEnd:"Jump to the end",signatureBlock:"Add your signature here. Required.",signatureBlockDone:"Your signature. Select to change it.",finishLater:"Finish later",printAndSign:"Print and sign",decline:"Decline to sign",declineSubmit:"Send my decline",declineCancel:"Go back",signatureName:"Your full legal name",signatureStyle:"Signature style",declineReason:"Why are you declining?",ageConfirm:"I meet the minimum age",documentHeading:"Document",signatureHeading:"Your signature"};var ESIGN_RIGHTS_KEYS=["heading","intro","withdraw","paperCopy","working","error","confirmTitle","confirmBody","confirmSubmit","confirmCancel","withdrawnBeforeSigning","withdrawnAfterSigning","paperCopyRequested","paperCopyAlreadyOutstanding"];var ESIGN_RIGHTS_FALLBACKS={heading:"Your rights",intro:"You do not have to use electronic records. You can stop using them for this document, or ask for a paper copy in the mail. Neither costs anything.",withdraw:"Stop using electronic records",paperCopy:"Ask for a mailed paper copy",working:"Working on your request.",error:"Your request did not go through. Select it again. If it keeps failing, contact the company that sent you this link.",confirmTitle:"Withdraw your consent?",confirmBody:"This ends the signing session and no electronic signature is recorded for you. The company that sent you this link is told that you withdrew. This costs nothing and no penalty applies, and you can still ask for a mailed paper copy afterward.",confirmSubmit:"Yes, withdraw consent",confirmCancel:"Go back",withdrawnBeforeSigning:"You withdrew your consent to use electronic records, and nothing was signed. The company that sent you this link has been told. If you want this document on paper, ask for a copy below. You can close this window.",withdrawnAfterSigning:"You withdrew your consent to use electronic records. The document you already signed still stands, because a signature cannot be taken back after the fact. The company that sent you this link has been told. If you want this document on paper, ask them to send you a copy.",paperCopyRequested:"We asked the company that sent you this link to send you a paper copy. There is no fee.",paperCopyAlreadyOutstanding:"A paper copy is already on its way to you, so there was nothing new to request."};var ESIGN_OUTCOME_RIGHTS_KEY={consent_withdrawn_before_signing:"withdrawnBeforeSigning",consent_withdrawn_after_signing:"withdrawnAfterSigning",paper_copy_requested:"paperCopyRequested",paper_copy_already_outstanding:"paperCopyAlreadyOutstanding"};function isEsignConsentOutcome(value){return Object.prototype.hasOwnProperty.call(ESIGN_OUTCOME_RIGHTS_KEY,value)}var ESIGN_DOCUMENT_KEYS=["download","printAndSignStarted","downloadFailed","downloadRemoved"];var ESIGN_DOCUMENT_FALLBACKS={download:"Download a copy",printAndSignStarted:"Print your copy, sign it by hand, and send it to the company that sent you this link. You cannot return a printed page through this page.",downloadFailed:"We could not download that document. Select it again. If it keeps failing, contact the company that sent you this link.",downloadRemoved:"This copy is no longer stored. Ask the company that sent you this link to send you a new copy or a printed record."};var ESIGN_COUNT_TOKEN="{count}";var ESIGN_SHELL_KEYS=["stepsBlocked","gateRead","gateSignature","gateAge","consentTermsLink","consentTermsNewWindow","consentAgeAttest","consentError","adoptTitle","adoptConsent","adoptFinePrint","declineTitle","declineBody","finishLaterTitle","finishLaterBody","disclosureTitle","disclosureVersionLabel","disclosurePublicCopy","disclosureBack","statusSigned","statusDeclined","statusVoided","statusExpired","statusWithdrawn"];var ESIGN_SHELL_FALLBACKS={stepsBlocked:"Not finished yet. Taking you to what is left.",gateRead:"Please read to the end",gateSignature:"Please sign above",gateAge:"Please confirm your age",consentTermsLink:"See terms.",consentTermsNewWindow:"Opens in a new window.",consentAgeAttest:"I am {count} or older.",consentError:"We could not record your agreement, so your signature was not added. Select the signature line in the document to try again.",adoptTitle:"Add your signature",adoptConsent:"Selecting Use this signature also records your agreement to sign and to get records for this document electronically.",adoptFinePrint:"Use this signature adopts what you see above as your signature. Selecting Finish signs the document.",declineTitle:"Decline to sign?",declineBody:"This ends your signing session and tells the company that sent you this link. No penalty applies. You can ask them for a new link later.",finishLaterTitle:"Finish later?",finishLaterBody:"Come back to this same link any time before the deadline. What you have done is kept.",disclosureTitle:"Using electronic records",disclosureVersionLabel:"Notice version",disclosurePublicCopy:"Open this notice in a new window",disclosureBack:"Back to the document",statusSigned:"Signed",statusDeclined:"Declined",statusVoided:"Canceled",statusExpired:"Expired",statusWithdrawn:"Withdrawn"};var ESIGN_TERMINAL_STATUS_KEY={terminal_signed:"statusSigned",terminal_declined:"statusDeclined",terminal_voided:"statusVoided",terminal_expired:"statusExpired",terminal_withdrawn:"statusWithdrawn"};function resolveEsignDocumentCopy(copy,key){const injected=copy?.documents?.[key];if(typeof injected==="string"&&injected.length>0)return injected;return ESIGN_DOCUMENT_FALLBACKS[key]}function resolveEsignShellCopy(copy,key){const injected=copy?.shell?.[key];if(typeof injected==="string"&&injected.length>0)return injected;return ESIGN_SHELL_FALLBACKS[key]}function resolveEsignTerminalStatus(copy,state){return resolveEsignShellCopy(copy,ESIGN_TERMINAL_STATUS_KEY[state])}function resolveEsignRightsCopy(copy,key){const injected=copy?.rights?.[key];if(typeof injected==="string"&&injected.length>0)return injected;return ESIGN_RIGHTS_FALLBACKS[key]}function resolveEsignOutcomeCopy(copy,outcome){return resolveEsignRightsCopy(copy,ESIGN_OUTCOME_RIGHTS_KEY[outcome])}function resolveEsignLabel(copy,label){const injected=copy?.labels?.[label];if(typeof injected==="string"&&injected.length>0)return injected;return ESIGN_LABEL_FALLBACKS[label]}function resolveEsignCopy(copy,state){const injected=copy?.[state];if(typeof injected==="string"&&injected.length>0)return injected;return ESIGN_COPY_FALLBACKS[state]}function resolveEsignFrameTitle(copy){const injected=copy?.frameTitle;if(typeof injected==="string"&&injected.length>0)return injected;return ESIGN_COPY_FALLBACKS.frameTitle}var ESIGN_COPY_STATE_KEYS=ESIGN_STATES;
2
+
3
+ export { ESIGN_CONSENT_ACTIONS, ESIGN_COPY_FALLBACKS, ESIGN_COPY_STATE_KEYS, ESIGN_COUNT_TOKEN, ESIGN_DOCUMENT_ACTIONS, ESIGN_DOCUMENT_FALLBACKS, ESIGN_DOCUMENT_KEYS, ESIGN_FRAME_ANNOUNCE_TIMEOUT_MS, ESIGN_LABELS, ESIGN_LABEL_FALLBACKS, ESIGN_OUTCOME_RIGHTS_KEY, ESIGN_PREPARING_MAX_ATTEMPTS, ESIGN_PREPARING_STALL_MS, ESIGN_RIGHTS_FALLBACKS, ESIGN_RIGHTS_KEYS, ESIGN_SCROLL_TARGET_MARGIN_PX, ESIGN_SHELL_FALLBACKS, ESIGN_SHELL_KEYS, ESIGN_STATES, ESIGN_STATE_RIGHTS, ESIGN_TERMINAL_STATUS_KEY, TERMINAL_STATUS_TO_STATE, esignPreparingDelayMs, esignStateOffersRights, isEsignConsentOutcome, isEsignFrameFatalState, isTerminalEnvelopeStatus, resolveEsignCopy, resolveEsignDocumentCopy, resolveEsignFrameTitle, resolveEsignLabel, resolveEsignOutcomeCopy, resolveEsignRightsCopy, resolveEsignShellCopy, resolveEsignTerminalStatus };
@@ -0,0 +1,3 @@
1
+ var CREDIT_HISTORY_EVENT_TYPES=["checktiv.credit_history.ready","checktiv.credit_history.screen","checktiv.credit_history.reconnecting","checktiv.credit_history.submitted","checktiv.credit_history.declined","checktiv.credit_history.skipped","checktiv.credit_history.error"];function isChecktivCreditHistoryEvent(event){return CREDIT_HISTORY_EVENT_TYPES.some(literal=>literal===event.type)}
2
+
3
+ export { CREDIT_HISTORY_EVENT_TYPES, isChecktivCreditHistoryEvent };
@@ -0,0 +1,8 @@
1
+ import { ZodISOTime, ZodISODuration, ZodISODateTime, ZodISODate, _isoDateTime, _isoDate, _isoTime, _isoDuration, object, string, number, boolean, _enum, array, uuid, email, strictObject, record, union, unknown, preprocess, literal, discriminatedUnion } from './chunk-TKK5CTVG.js';
2
+ import { detectCameraPolicyBlock, warnCameraPolicyBlock } from './chunk-ZU4L3NDZ.js';
3
+ import { IDV_DOCUMENT_TYPES, isTwoSidedDocumentType } from './chunk-IQKHRPJR.js';
4
+ import { __export } from './chunk-AIK7CDV6.js';
5
+
6
+ var iso_exports={};__export(iso_exports,{ZodISODate:()=>ZodISODate,ZodISODateTime:()=>ZodISODateTime,ZodISODuration:()=>ZodISODuration,ZodISOTime:()=>ZodISOTime,date:()=>date,datetime:()=>datetime,duration:()=>duration,time:()=>time});function datetime(params){return _isoDateTime(ZodISODateTime,params)}function date(params){return _isoDate(ZodISODate,params)}function time(params){return _isoTime(ZodISOTime,params)}function duration(params){return _isoDuration(ZodISODuration,params)}var behaviorTraitsSchema=object({webdriver:boolean(),maxTouchPoints:number().int().min(0).max(512),timezone:string().max(64).nullable(),pluginCount:number().int().min(0).max(256),deviceModelHint:string().max(120).nullable()}).strict();var behaviorStepSchema=object({stepId:string().max(80),seconds:number().min(0).max(86400),pasteCount:number().int().min(0).max(1e4)}).strict();var behaviorSurfaceEnum=_enum(["parent","embed"]);var behaviorCapturedPayloadSchema=object({steps:array(behaviorStepSchema).max(50),traits:behaviorTraitsSchema,segments:array(object({surface:behaviorSurfaceEnum,steps:array(behaviorStepSchema).max(50),traits:behaviorTraitsSchema}).strict()).max(4).optional()}).strict();behaviorCapturedPayloadSchema.extend({ingress:_enum(["hosted","embedded"]).optional(),stepId:string().max(128).optional()}).strict();var REGION_IDS=["us","eu"];var SystemModes=["live","test"];var DataRegions=REGION_IDS;var CURRENT_PROTOCOL_VERSION=3;var IDV_ACQUISITION_WHEN_ABSENT="camera";var LivenessAwsRegions=["us-east-1","eu-west-1"];({us:LivenessAwsRegions[0],eu:LivenessAwsRegions[1]});uuid();email().toLowerCase();object({createdAt:iso_exports.datetime(),updatedAt:iso_exports.datetime()});var dataRegionEnum=_enum(DataRegions);var dataModeEnum=_enum(SystemModes);object({orgId:string().min(1),mode:dataModeEnum,region:dataRegionEnum});object({orgId:string().min(1),actorId:string().min(1),mode:dataModeEnum,region:dataRegionEnum,traceId:string().optional()});var DICTIONARY_KEY_LABELS={locale:"Language code",openTail:"Additional property"};function keyRowMeta(title){return {propertyNames:{type:"string",title}}}var LOCALE_KEY_ROW_META=keyRowMeta(DICTIONARY_KEY_LABELS.locale);var OPEN_TAIL_KEY_ROW_META=keyRowMeta(DICTIONARY_KEY_LABELS.openTail);var STEP_ID_REGEX=/^step_[0-9A-Za-z_-]{1,64}$/;var hexColorSchema=string().regex(/^#[0-9a-fA-F]{6}$/,"Must be a 6-digit hex color, e.g. #2563eb");_enum(["auto","light","dark"]);var ADDRESS_TEXT_REGEX=/^[^\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069<>]+$/;var safeAddressText=max=>string().min(1).max(max).regex(ADDRESS_TEXT_REGEX,"invalid characters");var postalCodeField=string().max(20).regex(/^[A-Za-z0-9 \-]*$/);var countryField=string().length(2).regex(/^[A-Z]{2}$/);var placeIdField=string().max(255).regex(/^[A-Za-z0-9_\-:]+$/);function levenshtein(a,b){const m=a.length;const n=b.length;let prev=Array.from({length:n+1},(_,j)=>j);let curr=new Array(n+1).fill(0);for(let i=1;i<=m;i++){curr[0]=i;for(let j=1;j<=n;j++){const cost=a[i-1]===b[j-1]?0:1;curr[j]=Math.min(prev[j]+1,curr[j-1]+1,prev[j-1]+cost);}[prev,curr]=[curr,prev];}return prev[n]}var normalizeKey=key=>key.toLowerCase().replace(/[^a-z0-9]/g,"");var CURATED_KEY_SYNONYMS={zip:"postal_code",zipcode:"postal_code",postcode:"postal_code",templateid:"workflow_template_id",suffix:"name_suffix"};function nearestKnownKey(key,knownKeys){const target=normalizeKey(key);if(target.length===0)return null;const curated=Object.hasOwn(CURATED_KEY_SYNONYMS,target)?CURATED_KEY_SYNONYMS[target]:void 0;if(curated!==void 0){const curatedNormalized=normalizeKey(curated);const match=knownKeys.find(candidate=>normalizeKey(candidate)===curatedNormalized);if(match!==void 0)return match}let best=null;let bestDistance=Number.POSITIVE_INFINITY;for(const candidate of knownKeys){const normalized=normalizeKey(candidate);const distance=normalized===target?0:levenshtein(target,normalized);if(distance<bestDistance){bestDistance=distance;best=candidate;}}const threshold=Math.max(1,Math.ceil(target.length/2));return bestDistance<=threshold?best:null}function unknownKeyErrorMap(knownKeys,retiredKeys={}){const retiredByNormalizedKey=new Map(Object.entries(retiredKeys).map(([retired,message])=>[normalizeKey(retired),message]));return issue=>{if(issue.code!=="unrecognized_keys")return void 0;return issue.keys.map(key=>{const migration=retiredByNormalizedKey.get(normalizeKey(key));if(migration!==void 0)return `Unknown field "${key}". ${migration}`;const suggestion=nearestKnownKey(key,knownKeys);return suggestion?`Unknown field "${key}". Did you mean "${suggestion}"?`:`Unknown field "${key}".`}).join(" ")}}object({line1:safeAddressText(120),line2:safeAddressText(120).optional(),city:safeAddressText(80),region:safeAddressText(80).optional(),postalCode:postalCodeField.optional(),country:countryField,placeId:placeIdField.optional(),formatted:safeAddressText(500).optional()});var wireAddressShape={line1:safeAddressText(120),line2:safeAddressText(120).optional(),city:safeAddressText(80),region:safeAddressText(80).optional(),postal_code:postalCodeField.optional(),country:countryField,place_id:placeIdField.optional(),formatted:safeAddressText(500).optional()};strictObject(wireAddressShape,{error:unknownKeyErrorMap(Object.keys(wireAddressShape))}).transform(wire=>({line1:wire.line1,line2:wire.line2,city:wire.city,region:wire.region,postalCode:wire.postal_code,country:wire.country,placeId:wire.place_id,formatted:wire.formatted}));var applicantSkipPolicySchema=object({minAttemptsBeforeShown:number().int().nonnegative().default(0),requireReason:boolean().default(false)}).loose().meta(OPEN_TAIL_KEY_ROW_META);var i18nLabelSchema=record(string(),string()).meta(LOCALE_KEY_ROW_META);var canonicalOriginSchema=string().min(1).refine(v=>{if(v.includes("*"))return false;try{return new URL(v).origin===v}catch{return false}},"must be a canonical origin (scheme and host[:port], no path / query / fragment / credentials / wildcard)");canonicalOriginSchema.refine(v=>{try{return new URL(v).protocol==="https:"}catch{return false}},"must be a canonical https-only origin (scheme https: and host[:port], no path / query / fragment / credentials / wildcard)");var creditPurposeEnum=_enum(["residency","employment"]).meta({description:"Permissible purpose for a consumer-report pull. A settings key selecting the provisioned vendor group an order is placed under, never a field sent on the order."});var MAX_FIELDS_PER_SCREEN=8;var MAX_RULES_PER_SCREEN=10;var MAX_LOCALES=5;var MAX_LABEL_LEN=600;var bcp47LocaleSchema=string().regex(/^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|[0-9]{3}))?$/,"must be a BCP-47 locale tag");var bcp47I18nLabelSchema=record(bcp47LocaleSchema,string().max(MAX_LABEL_LEN)).refine(map=>Object.keys(map).length<=MAX_LOCALES,{message:`at most ${MAX_LOCALES} locales per label`}).meta(LOCALE_KEY_ROW_META);var CREDIT_HISTORY_PREVIOUS_NAMES_MAX=10;var CREDIT_HISTORY_DEFAULT_MAX_PREVIOUS_NAMES=3;var CREDIT_HISTORY_DEFAULT_ADDRESS_HISTORY_MONTHS=6;var CREDIT_HISTORY_ADDRESS_HISTORY_MONTHS_MIN=1;var CREDIT_HISTORY_ADDRESS_HISTORY_MONTHS_MAX=120;var CREDIT_HISTORY_ADDENDUM_MAX_LENGTH=2e3;var CREDIT_HISTORY_ADDENDUM_MAX_LOCALES=5;var CREDIT_HISTORY_MINIMUM_SCORE_FLOOR=300;var CREDIT_HISTORY_MINIMUM_SCORE_CEILING=900;var creditNationalIdPolicyEnum=_enum(["optional","required"]);var creditUnsupportedJurisdictionEnum=_enum(["review","pass"]);var creditDisclosureAddendumSchema=record(bcp47LocaleSchema,string().max(CREDIT_HISTORY_ADDENDUM_MAX_LENGTH)).refine(map=>Object.keys(map).length<=CREDIT_HISTORY_ADDENDUM_MAX_LOCALES,{message:`at most ${CREDIT_HISTORY_ADDENDUM_MAX_LOCALES} locales per disclosure addendum`}).meta(LOCALE_KEY_ROW_META);var creditHistoryConfigSchema=object({purpose:creditPurposeEnum,includePreviousNames:boolean().default(false),maxPreviousNames:number().int().min(0).max(CREDIT_HISTORY_PREVIOUS_NAMES_MAX).default(CREDIT_HISTORY_DEFAULT_MAX_PREVIOUS_NAMES),nationalId:creditNationalIdPolicyEnum.default("optional"),addressHistoryMonths:number().int().min(CREDIT_HISTORY_ADDRESS_HISTORY_MONTHS_MIN).max(CREDIT_HISTORY_ADDRESS_HISTORY_MONTHS_MAX).default(CREDIT_HISTORY_DEFAULT_ADDRESS_HISTORY_MONTHS),unsupportedJurisdiction:creditUnsupportedJurisdictionEnum.default("review"),noFileRequiresReview:boolean().default(false),minimumCreditScore:number().int().min(CREDIT_HISTORY_MINIMUM_SCORE_FLOOR).max(CREDIT_HISTORY_MINIMUM_SCORE_CEILING).optional(),disclosureAddendum:creditDisclosureAddendumSchema.optional()}).strict();var checkTypeEnum=_enum(["collect_user_info","watchlist","background_us_criminal","background_global","id_verification","custom_form","esign","credit_history"]);_enum(["pending","awaiting_input","processing","completed","failed","expired"]);_enum(["pass","fail","review","error"]);var testHintEnum=_enum(["pass","review","fail","doc_quality"]);var idvAcquisitionEnum=_enum(["camera","upload"]);var FORM_FIELD_TYPES=["short_text","long_text","number","email","phone","date","single_select","multi_select","boolean","file_upload","content_heading","content_paragraph"];var RESERVED_SLUGS=new Set(["__proto__","constructor","prototype"]);var formFieldSlugSchema=string().regex(/^[a-z][a-z0-9_]{0,63}$/,"must be a lowercase slug").refine(s=>!RESERVED_SLUGS.has(s),{message:"reserved slug is not allowed"});var formFieldValidationSchema=object({minLength:number().int().nonnegative().optional(),maxLength:number().int().positive().optional(),min:number().optional(),max:number().optional(),minSelections:number().int().nonnegative().optional(),maxSelections:number().int().positive().optional()}).strict();var formFieldOptionSchema=object({value:string().min(1).max(200),label:bcp47I18nLabelSchema}).strict();var formFieldSchema=object({id:formFieldSlugSchema,type:_enum(FORM_FIELD_TYPES),label:bcp47I18nLabelSchema,helpText:bcp47I18nLabelSchema.optional(),required:boolean().default(false),validation:formFieldValidationSchema.optional(),options:array(formFieldOptionSchema).max(50).optional()}).strict();var formRuleOpEnum=_enum(["eq","neq","in","gt","gte","lt","lte","includes","not_includes","ends_with"]);var formRuleActionEnum=_enum(["flag_for_review","notify_email"]);var formRuleValueSchema=union([string(),number(),boolean(),array(union([string(),number(),boolean()]))]);var formRuleSchema=object({id:formFieldSlugSchema,when:object({fieldId:formFieldSlugSchema,op:formRuleOpEnum,value:formRuleValueSchema}).strict(),actions:array(formRuleActionEnum).min(1),notifyOrgMemberIds:array(string().min(1)).max(25).optional()}).strict();var customFormScreenConfigSchema=object({supportedLocales:array(bcp47LocaleSchema).min(1).max(MAX_LOCALES),fields:array(formFieldSchema).min(1).max(MAX_FIELDS_PER_SCREEN),rules:array(formRuleSchema).max(MAX_RULES_PER_SCREEN).default([])}).strict();var esignStepConfigSchema=object({documentTemplateVersionIds:array(uuid()).max(1).default([]),requireScrollToEnd:boolean().default(false),minimumAgeYears:number().int().min(0).max(150).optional(),allowFullIdDocumentNumber:boolean().default(false),sendCopyToApplicant:boolean().default(true),sendCopyToOperator:boolean().default(true)}).strict();var stepConditionSchema=object({field:string(),operator:_enum(["eq","neq","in","not_in"]),value:union([string(),array(string())])}).optional();var workflowStepSchema=object({checkType:checkTypeEnum,isRequired:boolean().default(true),order:number().int(),maxAttempts:number().int().default(3),condition:stepConditionSchema,label:string().optional()});array(workflowStepSchema).min(1);var baseStepFields={id:string().regex(STEP_ID_REGEX),order:number().int().nonnegative(),isRequired:boolean().default(true),applicantSkippable:boolean().default(false),applicantSkipPolicy:applicantSkipPolicySchema.optional(),maxAttempts:number().int().positive().default(3),label:i18nLabelSchema.optional(),description:i18nLabelSchema.optional(),dependsOn:array(string()).optional(),condition:unknown().nullable().optional()};var backgroundConfigSchema=object({jurisdictionScope:_enum(["us","eu","global"]).default("global"),recordTypesIncluded:array(_enum(["criminal","sex_offender","adverse_media"])).min(1).default(["criminal"])}).default({jurisdictionScope:"global",recordTypesIncluded:["criminal"]});var watchlistConfigSchema=object({lists:array(_enum(["pep","ofac","eu","un"])).default([]),confidenceThreshold:number().min(0).max(1).default(.8)}).default({lists:[],confidenceThreshold:.8});var COLLECT_USER_INFO_FIELDS=["email","phone","dob","address"];var collectUserInfoConfigSchema=object({fields:preprocess(raw=>{if(!Array.isArray(raw))return raw;return raw.filter(v=>v!=="name")},array(_enum(COLLECT_USER_INFO_FIELDS))).default(["email","phone"]),captureStructuredName:boolean().default(false)}).default({fields:["email","phone"],captureStructuredName:false});var idvDocumentTypeEnum=_enum(IDV_DOCUMENT_TYPES);var idVerificationConfigSchema=object({documentTypes:idvDocumentTypeEnum.array().min(1).default([...IDV_DOCUMENT_TYPES]),biometricMode:_enum(["none","selfie","liveness"]).default("none"),requireMrzMatch:boolean().default(false),requireExpiryValid:boolean().default(true),requireNameMatch:boolean().default(false),documentAuthenticity:boolean().default(false),minAge:number().int().min(0).max(150).optional(),allowDocumentUpload:boolean().default(false).describe("Lets the applicant upload an existing photo of their identity document instead of scanning it with the camera, so a device without a working camera can still supply the document (a template with face match or liveness still requires the camera for that step). Uploaded photos are checked the same way as camera scans and can pass automatically. Every result records which method - scan or upload - produced the document.")}).strict().default({documentTypes:[...IDV_DOCUMENT_TYPES],biometricMode:"none",requireMrzMatch:false,requireExpiryValid:true,requireNameMatch:false,documentAuthenticity:false,allowDocumentUpload:false});var watchlistStepSchema=object({...baseStepFields,type:literal("watchlist"),config:watchlistConfigSchema});var backgroundUsCriminalStepSchema=object({...baseStepFields,type:literal("background_us_criminal"),config:backgroundConfigSchema});var backgroundGlobalStepSchema=object({...baseStepFields,type:literal("background_global"),config:backgroundConfigSchema});var collectUserInfoStepSchema=object({...baseStepFields,type:literal("collect_user_info"),config:collectUserInfoConfigSchema});var idVerificationStepSchema=object({...baseStepFields,type:literal("id_verification"),config:idVerificationConfigSchema});var customFormScreenStepSchema=object({...baseStepFields,type:literal("custom_form"),config:customFormScreenConfigSchema});var esignStepSchema=object({...baseStepFields,type:literal("esign"),config:esignStepConfigSchema});var creditHistoryStepSchema=object({...baseStepFields,type:literal("credit_history"),config:creditHistoryConfigSchema});discriminatedUnion("type",[watchlistStepSchema,backgroundUsCriminalStepSchema,backgroundGlobalStepSchema,collectUserInfoStepSchema,idVerificationStepSchema,customFormScreenStepSchema,esignStepSchema,creditHistoryStepSchema]);var captureBrandTokensSchema=object({primary:hexColorSchema,primaryHover:hexColorSchema,onPrimary:hexColorSchema,secondary:hexColorSchema,onSecondary:hexColorSchema,ring:hexColorSchema}).strict();var captureThemeSchema=object({colorMode:_enum(["light","dark"]),brandTokens:captureBrandTokensSchema.nullable().default(null)}).strict();var captureDocumentSideEnum=_enum(["front","back"]);var captureDocumentGroupEnum=_enum(["unknown","dl","id","passport","passport-card","visa"]);var captureErrorCodeEnum=_enum(["cv_gate_failed","upload_failed","sdk_load_failed","token_expired","biometric_unsupported","camera_unsupported","selfie_camera_denied","liveness_camera_denied","liveness_timeout","liveness_server_error","liveness_runtime_error","liveness_cancelled","protocol_mismatch"]);_enum(["no_face","multiple_faces","too_dark","move_closer","not_centered","hold_still","ready"]);var selfiePromptMapSchema=object({no_face:string().min(1).max(120).optional(),multiple_faces:string().min(1).max(120).optional(),too_dark:string().min(1).max(120).optional(),move_closer:string().min(1).max(120).optional(),not_centered:string().min(1).max(120).optional(),hold_still:string().min(1).max(120).optional(),ready:string().min(1).max(120).optional()}).strict();var selfieChromeCopySchema=object({shutterLabel:string().min(1).max(80).optional(),shutterHint:string().min(1).max(120).optional(),confirm:string().min(1).max(80).optional(),retake:string().min(1).max(80).optional()}).strict();var beginScanCopySchema=object({prompt:string().min(1).max(200).optional(),label:string().min(1).max(80).optional(),progressSlowLabel:string().min(1).max(200).optional(),cameraStartingLabel:string().min(1).max(80).optional(),cameraUnavailableNotice:string().min(1).max(200).optional(),uploadPrompt:string().min(1).max(200).optional(),uploadLabel:string().min(1).max(80).optional(),uploadSingleSideLabel:string().min(1).max(80).optional(),uploadFrontLabel:string().min(1).max(80).optional(),uploadBackLabel:string().min(1).max(80).optional(),uploadEntryLabel:string().min(1).max(80).optional(),uploadBackAction:string().min(1).max(80).optional(),uploadChangeDocumentAction:string().min(1).max(80).optional(),uploadChooseDocumentPrompt:string().min(1).max(200).optional(),documentTypePassport:string().min(1).max(80).optional(),documentTypeDriversLicense:string().min(1).max(80).optional(),documentTypeIdCard:string().min(1).max(80).optional(),documentTypeResidencePermit:string().min(1).max(80).optional(),documentTypeVisa:string().min(1).max(80).optional(),documentTypeWorkPermit:string().min(1).max(80).optional(),uploadPickAction:string().min(1).max(80).optional(),uploadReplaceAction:string().min(1).max(80).optional(),uploadKeepAction:string().min(1).max(80).optional(),uploadPreparingLabel:string().min(1).max(80).optional(),uploadAddedNotice:string().min(1).max(80).optional(),uploadBusyLabel:string().min(1).max(200).optional(),uploadIncompleteNotice:string().min(1).max(200).optional(),uploadIncompleteSingleNotice:string().min(1).max(200).optional(),uploadTooLargeNotice:string().min(1).max(200).optional(),uploadUnsupportedNotice:string().min(1).max(200).optional(),uploadUnreadableNotice:string().min(1).max(200).optional()}).strict();var captureInitMessageSchema=object({type:literal("capture:init"),captureToken:string().min(1),config:idVerificationConfigSchema,locale:string().min(2).max(35),theme:captureThemeSchema,mode:dataModeEnum.optional(),testHint:testHintEnum.optional(),protocolVersion:number().int().min(1).optional(),beginScanCopy:beginScanCopySchema.optional(),beginScanPrompt:string().min(1).max(200).optional(),beginScanLabel:string().min(1).max(80).optional(),selfiePromptMap:selfiePromptMapSchema.optional(),selfieChromeCopy:selfieChromeCopySchema.optional()}).strict();object({data:object({captureToken:string().min(1),embedOrigin:canonicalOriginSchema,runIndex:number().int().min(0),expiresAt:iso_exports.datetime({offset:true}),embedContextToken:string().min(1),mode:dataModeEnum.optional(),testHint:testHintEnum.optional()}).strict()}).strict();var captureReadyMessageSchema=object({type:literal("capture:ready")}).strict();var captureDocumentCompleteMessageSchema=object({type:literal("capture:document-complete"),side:captureDocumentSideEnum,r2Key:string().min(1)}).strict();var captureSelfieCompleteMessageSchema=object({type:literal("capture:selfie-complete"),r2Key:string().min(1)}).strict();var captureCoachingMessageSchema=object({type:literal("capture:coaching"),state:string().min(1).max(120),attemptIndex:number().int().min(0)}).strict();var captureSelfieCvRejectMessageSchema=object({type:literal("capture:selfie-cv-reject"),retryReason:string().min(1).max(120).optional(),attemptIndex:number().int().min(0)}).strict();var captureErrorMessageSchema=object({type:literal("capture:error"),code:captureErrorCodeEnum}).strict();var captureBiometricCameraLiveMessageSchema=object({type:literal("capture:biometric_camera_live"),timestamp:number().optional()}).strict();var idvR2KeysSchema=object({front:string().min(1),back:string().min(1).optional(),selfie:string().min(1).optional()}).strict();var captureAllCompleteMessageSchema=object({type:literal("capture:all-complete"),r2Keys:idvR2KeysSchema,documentGroup:captureDocumentGroupEnum.optional(),acquisition:idvAcquisitionEnum.optional()}).strict();object({stepId:string().min(1),runIndex:number().int().min(0),r2Keys:idvR2KeysSchema,acquisition:idvAcquisitionEnum.optional(),traceId:string().optional()}).strict();object({stepId:string().min(1).optional()}).strict();var idvLivenessStsCredentialsSchema=object({accessKeyId:string().min(1),secretAccessKey:string().min(1),sessionToken:string().min(1),expiration:string().min(1)}).strict();var livenessAwsRegionEnum=_enum(LivenessAwsRegions);object({awsSessionId:string().min(1),awsRegion:livenessAwsRegionEnum,credentials:idvLivenessStsCredentialsSchema}).strict();var captureBehaviorMessageSchema=object({type:literal("capture:behavior"),steps:array(behaviorStepSchema).max(50),traits:behaviorTraitsSchema}).strict();var captureTimingMessageSchema=object({type:literal("capture:timing"),providerImportMs:number().int().nonnegative().max(6e5).optional(),gateDwellMs:number().int().nonnegative().max(6e5).optional(),captureUiMs:number().int().nonnegative().max(6e5).optional()}).strict();var captureFromIframeMessageSchema=discriminatedUnion("type",[captureReadyMessageSchema,captureDocumentCompleteMessageSchema,captureSelfieCompleteMessageSchema,captureCoachingMessageSchema,captureSelfieCvRejectMessageSchema,captureErrorMessageSchema,captureAllCompleteMessageSchema,captureBehaviorMessageSchema,captureBiometricCameraLiveMessageSchema,captureTimingMessageSchema]);discriminatedUnion("type",[captureInitMessageSchema]);var idvCvGateRetryReasonEnum=_enum(["no_face_detected","multiple_faces","low_confidence","no_id_document","image_read_failed"]);object({ok:boolean(),retryReason:idvCvGateRetryReasonEnum.optional()}).strict();_enum(["front","back","selfie"]);function reducer(state,action){switch(action.type){case "mint_ok":return {kind:"waiting_for_init",captureToken:action.captureToken,embedOrigin:action.embedOrigin,runIndex:action.runIndex};case "mint_failed":return {kind:"mint_error"};case "iframe_ready":if(state.kind==="waiting_for_init"){return {kind:"ready",embedOrigin:state.embedOrigin,runIndex:state.runIndex}}return state;case "phase":if(state.kind==="ready"||state.kind==="capturing"){return {kind:"capturing",embedOrigin:state.embedOrigin,runIndex:state.runIndex,phase:action.phase,coaching:null,lastCvRejectReason:action.phase==="selfie"&&state.kind==="capturing"?state.lastCvRejectReason:null,biometricLoading:isBiometricPhase(action.phase)}}return state;case "coaching":if(state.kind==="ready"||state.kind==="capturing"){return {kind:"capturing",embedOrigin:state.embedOrigin,runIndex:state.runIndex,phase:"coaching",coaching:action.coaching,lastCvRejectReason:state.kind==="capturing"?state.lastCvRejectReason:null,biometricLoading:state.kind==="capturing"?state.biometricLoading:false}}return state;case "selfie_cv_reject":if(state.kind==="ready"||state.kind==="capturing"){return {kind:"capturing",embedOrigin:state.embedOrigin,runIndex:state.runIndex,phase:state.kind==="capturing"?state.phase:"selfie",coaching:state.kind==="capturing"?state.coaching:null,lastCvRejectReason:action.reason,biometricLoading:false}}return state;case "biometric_camera_live":if(state.kind==="capturing"){return {...state,biometricLoading:false}}return state;case "submitting":return {kind:"submitting"};case "submit_failed":return {kind:"submit_error"};case "submit_pending":return {kind:"submit_pending"};case "capture_superseded":return {kind:"capture_superseded"};case "token_expired":return {kind:"token_expired"};case "capture_error":return {kind:"capture_error",errorKind:action.errorKind,...action.cameraPolicyBlocked===true?{cameraPolicyBlocked:true}:{}};default:return state}}function nextCapturePhaseAfterDocument(side,documentTypes,biometricMode){if(side==="front"&&documentTypes.some(isTwoSidedDocumentType))return "uploading";if(biometricMode==="liveness")return "liveness";if(biometricMode==="selfie")return "selfie";return "uploading"}function isBiometricPhase(phase){return phase==="selfie"||phase==="liveness"}var RETRY_REASON_COACHING={no_face_detected:"hold_steady",multiple_faces:"hold_steady",low_confidence:"move_closer",no_id_document:"hold_steady",image_read_failed:"hold_steady"};function coachingKindForState(state){const retryParsed=idvCvGateRetryReasonEnum.safeParse(state);if(retryParsed.success)return RETRY_REASON_COACHING[retryParsed.data];switch(state){case "camera-too-far":return "move_closer";case "camera-too-close":case "document-too-close-to-frame-edge":return "move_farther";case "glare-detected":return "reduce_glare";case "too-dark":case "lighting-too-dark":return "too_dark";case "wrong-side":return "wrong_side";case "selfie_move_closer":return "move_closer";case "selfie_too_dark":return "too_dark";case "selfie_no_face":case "selfie_multiple_faces":case "selfie_not_centered":return "hold_steady";default:return "hold_steady"}}function createCaptureController(deps){let state={kind:"minting"};const stateListeners=new Set;const eventListeners=new Map;let captureToken=null;let pinnedOrigin=null;let runIndex=null;let mintMode;let mintTestHint;let cameraPolicyChecked=false;let cameraPolicyBlocked=false;let started=false;let destroyed=false;let cancelled=false;let submitStarted=false;let messageListener=null;function setState(next){state=next;for(const listener of stateListeners)listener(state);}function dispatch(action){setState(reducer(state,action));}function emit(event){const listeners=eventListeners.get(event.type);if(listeners===void 0)return;for(const listener of listeners)listener(event);}function checkCameraPolicy(iframe,origin){if(cameraPolicyChecked)return;cameraPolicyChecked=true;try{const block=detectCameraPolicyBlock(iframe,origin);if(block===null)return;warnCameraPolicyBlock(block);cameraPolicyBlocked=true;}catch{}}function postInit(){if(destroyed||captureToken===null||pinnedOrigin===null)return false;const iframe=deps.getIframe();if(iframe===null||iframe.contentWindow===null)return false;checkCameraPolicy(iframe,pinnedOrigin);const mintFields={...mintMode!==void 0?{mode:mintMode}:{},...mintTestHint!==void 0?{testHint:mintTestHint}:{}};const init={type:"capture:init",captureToken,...deps.initPayload(),...mintFields};iframe.contentWindow.postMessage(init,pinnedOrigin);return true}function handleMessage(msg){switch(msg.type){case "capture:ready":{const posted=postInit();if(posted&&state.kind==="waiting_for_init"){dispatch({type:"iframe_ready"});}return}case "capture:coaching":{dispatch({type:"coaching",coaching:coachingKindForState(msg.state)});deps.onCoaching?.(msg.state,msg.attemptIndex);return}case "capture:selfie-cv-reject":{const reason=msg.retryReason??null;dispatch({type:"selfie_cv_reject",reason});emit({type:"selfie-cv-reject",attemptIndex:msg.attemptIndex,reason});return}case "capture:document-complete":{const{config}=deps.initPayload();dispatch({type:"phase",phase:nextCapturePhaseAfterDocument(msg.side,config.documentTypes,config.biometricMode)});return}case "capture:selfie-complete":{dispatch({type:"phase",phase:"uploading"});return}case "capture:error":{if(msg.code==="token_expired"){dispatch({type:"token_expired"});return}dispatch({type:"capture_error",errorKind:msg.code,...cameraPolicyBlocked?{cameraPolicyBlocked:true}:{}});return}case "capture:all-complete":{void submitCapture(msg.r2Keys,msg.acquisition??IDV_ACQUISITION_WHEN_ABSENT);return}case "capture:behavior":{deps.onBehaviorSegment?.({steps:msg.steps,traits:msg.traits});return}case "capture:timing":{try{deps.onEmbedTiming?.({providerImportMs:msg.providerImportMs,gateDwellMs:msg.gateDwellMs,captureUiMs:msg.captureUiMs});}catch{}return}case "capture:biometric_camera_live":{dispatch({type:"biometric_camera_live"});return}default:{const _exhaustive=msg;return _exhaustive}}}async function submitCapture(r2Keys,acquisition){if(submitStarted)return;submitStarted=true;if(runIndex===null){dispatch({type:"submit_failed"});return}if(deps.onBeforeSubmit){try{await deps.onBeforeSubmit();}catch{if(!destroyed)dispatch({type:"submit_failed"});return}if(destroyed)return}dispatch({type:"submitting"});let result;const submitWithAcquisition=deps.submit;try{result=await submitWithAcquisition(runIndex,r2Keys,acquisition);}catch{if(!destroyed)dispatch({type:"submit_failed"});return}if(destroyed)return;if(result.ok){emit({type:"all-complete",runIndex});return}if(result.reason==="token_expired"){dispatch({type:"token_expired"});return}if(result.reason==="signal_pending"){dispatch({type:"submit_pending"});return}if(result.reason==="capture_superseded"){dispatch({type:"capture_superseded"});return}dispatch({type:"submit_failed"});}function onWindowMessage(event){if(destroyed||pinnedOrigin===null)return;if(event.origin!==pinnedOrigin)return;if(event.source!==null&&event.source!==deps.getIframe()?.contentWindow)return;const parsed=captureFromIframeMessageSchema.safeParse(event.data);if(!parsed.success)return;handleMessage(parsed.data);}return {start(){if(destroyed||started)return;started=true;void(async()=>{try{const minted=await deps.mintToken();if(cancelled||destroyed)return;captureToken=minted.captureToken;pinnedOrigin=minted.embedOrigin;runIndex=minted.runIndex;mintMode=minted.mode;mintTestHint=minted.testHint;messageListener=onWindowMessage;window.addEventListener("message",messageListener);dispatch({type:"mint_ok",captureToken:minted.captureToken,embedOrigin:minted.embedOrigin,runIndex:minted.runIndex});}catch{if(cancelled||destroyed)return;dispatch({type:"mint_failed"});}})();},on(type,cb){let listeners=eventListeners.get(type);if(listeners===void 0){listeners=new Set;eventListeners.set(type,listeners);}listeners.add(cb);return ()=>{listeners?.delete(cb);}},subscribe(cb){stateListeners.add(cb);cb(state);return ()=>{stateListeners.delete(cb);}},handleReady(){if(destroyed)return;postInit();},destroy(){if(destroyed)return;destroyed=true;cancelled=true;if(messageListener!==null){window.removeEventListener("message",messageListener);messageListener=null;}}}}
7
+
8
+ export { CURRENT_PROTOCOL_VERSION, IDV_ACQUISITION_WHEN_ABSENT, coachingKindForState, createCaptureController, isBiometricPhase, nextCapturePhaseAfterDocument, reducer };