@checktiv/sdk-web 1.6.1 → 1.7.2

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.
package/README.md CHANGED
@@ -33,13 +33,13 @@ token-lifecycle code.
33
33
  **Backend** - your server holds the secret key and returns a `clientToken`:
34
34
 
35
35
  ```js
36
- import { sessions } from '@checktiv/sdk-web';
36
+ import { sessions, regionToApiBase } from '@checktiv/sdk-web';
37
37
 
38
38
  // POST /kyc/session (your backend)
39
39
  const { clientToken } = await sessions.create(
40
40
  { templateId: 'wt_...', applicant: { externalId: user.id } },
41
41
  {
42
- apiBase: 'https://api.us.checktiv.com',
42
+ apiBase: regionToApiBase('us'), // or 'eu' for your account's region
43
43
  secretKey: process.env.CHECKTIV_SECRET_KEY, // ah_sk_* - never in the browser
44
44
  idempotencyKey: user.id, // retries and new-device re-entry never double-mint
45
45
  },
@@ -51,6 +51,24 @@ const { clientToken } = await sessions.create(
51
51
  it only from your server. The `clientToken` it returns can resume the applicant's own
52
52
  session; it never reads verification results or applicant data.
53
53
 
54
+ On failure it throws a typed error you can discriminate on `.code` (`unauthorized`,
55
+ `invalid_template`, `rate_limited`, `network`, `server_error`):
56
+
57
+ ```js
58
+ import { sessions, isSessionsCreateError } from '@checktiv/sdk-web';
59
+
60
+ try {
61
+ const { clientToken } = await sessions.create(input, options);
62
+ return Response.json({ clientToken });
63
+ } catch (err) {
64
+ if (isSessionsCreateError(err) && err.code === 'unauthorized') {
65
+ // Wrong or wrong-region secret key. Do NOT surface err.message to the browser.
66
+ return new Response('Server misconfigured', { status: 500 });
67
+ }
68
+ throw err;
69
+ }
70
+ ```
71
+
54
72
  **Frontend** - mount and forget:
55
73
 
56
74
  ```js
@@ -60,7 +78,7 @@ import '@checktiv/sdk-web/fraud'; // omit if the workflow never declares fraud
60
78
  import '@checktiv/sdk-web/capture-ui/style.css'; // REQUIRED: styles the capture surface
61
79
 
62
80
  const handle = mount(document.getElementById('checktiv-container'), {
63
- publishableKey: 'ah_pk_us_test_...', // safe to expose - origin-pinned, no scopes
81
+ publishableKey: 'ah_pk_us_live_...', // safe to expose - origin-pinned, no scopes
64
82
  // Called ONCE for the cold start (or a new device), never on every expiry.
65
83
  fetchToken: () =>
66
84
  fetch('/kyc/session', { method: 'POST' })
@@ -68,6 +86,13 @@ const handle = mount(document.getElementById('checktiv-container'), {
68
86
  .then((data) => data.clientToken),
69
87
  onConsent: () => showConsentPrompt(), // required only if the session declares fraud
70
88
  onEvent: (event) => console.log(event),
89
+ onError: (error) => {
90
+ // Fires for any failure the journey emits, across every module (identity
91
+ // verification, fraud, custom forms). `error.code` is a stable discriminant.
92
+ if (error.recovery === 'refresh_session')
93
+ showMessage('Your session expired. Please start again.');
94
+ else showMessage(error.message);
95
+ },
71
96
  onComplete: ({ sessionId }) => {
72
97
  // Capture is complete. Wait for the webhook verdict before acting.
73
98
  showMessage('Verification submitted. You will hear from us shortly.');
@@ -149,7 +174,7 @@ import '@checktiv/sdk-web/idv';
149
174
  import '@checktiv/sdk-web/capture-ui/style.css'; // REQUIRED for the managed capture surface
150
175
 
151
176
  const client = init({
152
- publishableKey: 'ah_pk_us_test_...',
177
+ publishableKey: 'ah_pk_us_live_...',
153
178
  getSessionToken: async (ctx) => {
154
179
  // Your server mints a short-lived browser token from its secret key.
155
180
  const res = await fetch('/api/checktiv/token', {
@@ -177,21 +202,21 @@ side effect so `mount()` / `mountProvisioned()` / `mount('idv')` can resolve tha
177
202
  module. If a session needs a module you did not import, the SDK throws a clear,
178
203
  actionable error telling you which subpath to add, instead of failing silently.
179
204
 
180
- | Subpath | Purpose |
181
- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
182
- | `.` / `@checktiv/sdk-web` | Core entry: the zero-lifecycle `mount(target, opts)` + `sessions.create`, plus the `init(opts)` client. Tree-shakeable and lightweight. |
183
- | `./idv` | Managed identity-verification module. Import for its self-registration side effect so `mount()` / `mount('idv')` resolve it. |
184
- | `./fraud` | Consent-gated fraud-signal collection. Import for its self-registration side effect. |
185
- | `./custom-form` | Custom intake-form module (server-authored field definitions). Import for its self-registration side effect. |
186
- | `./custom-form/style.css` | Stylesheet for the custom-form module. `<link>` or `import` this into the host page. |
187
- | `./collect-user-info` | `collectUserInfo({ session })` - satisfy a `collect_user_info` step from your own form. No UI, no registration import. Zero-lifecycle. |
188
- | `./capture-ui/style.css` | Stylesheet for the managed IDV capture surface. Import it (the managed module renders through it) or the capture screen is unstyled. |
189
- | `./react` | React wrappers: `ChecktivJourney` (zero-lifecycle `mount`), plus `ChecktivProvider` / `useChecktiv()` / `ChecktivIdv` (the `init()` path). |
190
- | `./capture` | Advanced: headless host-side capture controller (`createCaptureController`). No default UI. |
191
- | `./capture-ui` | Advanced: batteries-included capture renderer (`mount()`), built on `./capture`. |
192
- | `./cross-device` | Cross-device QR / copy-link handoff overlay (`mountCrossDevice`). |
193
- | `./idv/cross-device` | Cross-device wiring for the managed IDV module. |
194
- | `./agents` | Machine-readable steering manifest (JSON) for coding-agent tooling. |
205
+ | Subpath | Purpose |
206
+ | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
207
+ | `.` / `@checktiv/sdk-web` | Core entry: the zero-lifecycle `mount(target, opts)` + `sessions.create`, plus the `init(opts)` client. Tree-shakeable and lightweight. |
208
+ | `./idv` | Managed identity-verification module. Import for its self-registration side effect so `mount()` / `mount('idv')` resolve it. Heavier than `.` / `./react` (see "Bundle size" below). |
209
+ | `./fraud` | Consent-gated fraud-signal collection. Import for its self-registration side effect. |
210
+ | `./custom-form` | Custom intake-form module (server-authored field definitions). Import for its self-registration side effect. |
211
+ | `./custom-form/style.css` | Stylesheet for the custom-form module. `<link>` or `import` this into the host page. |
212
+ | `./collect-user-info` | `collectUserInfo({ session })` - satisfy a `collect_user_info` step from your own form. No UI, no registration import. Zero-lifecycle. |
213
+ | `./capture-ui/style.css` | Stylesheet for the managed IDV capture surface. Import it (the managed module renders through it) or the capture screen is unstyled. |
214
+ | `./react` | React wrappers: `ChecktivJourney` (zero-lifecycle `mount`), plus `ChecktivProvider` / `useChecktiv()` / `ChecktivIdv` (the `init()` path). |
215
+ | `./capture` | Advanced: headless host-side capture controller (`createCaptureController`). No default UI. |
216
+ | `./capture-ui` | Advanced: batteries-included capture renderer (`mount()`), built on `./capture`. |
217
+ | `./cross-device` | Cross-device QR / copy-link handoff overlay (`mountCrossDevice`). |
218
+ | `./idv/cross-device` | Cross-device wiring for the managed IDV module. |
219
+ | `./agents` | Machine-readable steering manifest (JSON) for coding-agent tooling. |
195
220
 
196
221
  ## Managed IDV module (`./idv`)
197
222
 
@@ -209,6 +234,17 @@ stream is forward-open: new event types can appear over time, so handle the ones
209
234
  care about and ignore the rest - do not write an exhaustive switch that assumes a
210
235
  fixed set.
211
236
 
237
+ ### Bundle size
238
+
239
+ `./idv` is heavier than the `.` and `./react` entries: importing it adds a runtime
240
+ schema-validation layer, about 70 KiB gzipped, that those entries do not carry. It
241
+ exists because `./idv` parses capture result messages that cross an origin boundary
242
+ (the capture surface posting results back to your page), and that boundary carries
243
+ untrusted input, so it is validated at runtime rather than trusted to a compile-time
244
+ type alone. Every real identity-verification integration imports `./idv`, so plan
245
+ for this when sizing your bundle; it is called out here so it is not a surprise when
246
+ you inspect your bundle analyzer output.
247
+
212
248
  ## Fraud module (`./fraud`)
213
249
 
214
250
  Fraud-signal collection is **consent-gated and default-deny**: it collects nothing
@@ -257,7 +293,7 @@ import { collectUserInfo } from '@checktiv/sdk-web/collect-user-info';
257
293
 
258
294
  const collector = collectUserInfo({
259
295
  session: {
260
- publishableKey: 'ah_pk_us_test_...',
296
+ publishableKey: 'ah_pk_us_live_...',
261
297
  fetchToken: () =>
262
298
  fetch('/kyc/session', { method: 'POST' })
263
299
  .then((res) => res.json())
@@ -311,7 +347,7 @@ In React, the `./react` subpath exposes the same collector through the
311
347
  ```jsx
312
348
  import { useCollectUserInfo } from '@checktiv/sdk-web/react';
313
349
 
314
- const collector = useCollectUserInfo({ publishableKey: 'ah_pk_us_test_...', fetchToken });
350
+ const collector = useCollectUserInfo({ publishableKey: 'ah_pk_us_live_...', fetchToken });
315
351
  // collector.describe() and collector.submit(...) work exactly as above.
316
352
  ```
317
353
 
@@ -339,7 +375,7 @@ import '@checktiv/sdk-web/capture-ui/style.css';
339
375
  export function CheckIn() {
340
376
  return (
341
377
  <ChecktivJourney
342
- publishableKey="ah_pk_us_test_..."
378
+ publishableKey="ah_pk_us_live_..."
343
379
  fetchToken={() => fetchClientToken()} // returns your durable clientToken
344
380
  onConsent={() => showConsent()} // required only if the session declares fraud
345
381
  onEvent={(e) => console.log(e)}
@@ -367,7 +403,7 @@ import '@checktiv/sdk-web/capture-ui/style.css';
367
403
  export function App() {
368
404
  return (
369
405
  <ChecktivProvider
370
- publishableKey="ah_pk_us_test_..."
406
+ publishableKey="ah_pk_us_live_..."
371
407
  getSessionToken={async (ctx) => fetchToken(ctx)}
372
408
  >
373
409
  <ChecktivIdv onEvent={(e) => console.log(e)} />
@@ -8,10 +8,12 @@ declare const DataRegions: readonly ["us", "eu"];
8
8
  type DataRegion = (typeof DataRegions)[number];
9
9
 
10
10
  type ChecktivErrorCode = 'origin_not_allowed' | 'token_expired' | 'session_expired' | 'wrong_token_type' | 'protocol_mismatch' | 'camera_denied' | 'camera_unsupported' | 'cv_gate_failed' | 'upload_failed' | 'sdk_load_failed' | 'biometric_unsupported' | 'isolation_required';
11
+ declare const CHECKTIV_RECOVERY_STRATEGIES: readonly ["retry", "cross_device", "refresh_session", "contact_operator"];
12
+ type ChecktivRecovery = (typeof CHECKTIV_RECOVERY_STRATEGIES)[number];
11
13
  interface ChecktivError {
12
14
  code: ChecktivErrorCode;
13
15
  recoverable: boolean;
14
- recovery: 'retry' | 'cross_device' | 'refresh_session' | 'contact_operator';
16
+ recovery: ChecktivRecovery;
15
17
  message: string;
16
18
  }
17
19
 
@@ -273,6 +275,7 @@ type MountOptions = MountScope & {
273
275
  readonly fetchToken: () => Promise<string>;
274
276
  readonly onComplete?: (result: MountCompleteResult) => void;
275
277
  readonly onEvent?: (e: ChecktivEvent) => void;
278
+ readonly onError?: (e: ChecktivError) => void;
276
279
  readonly onConsent?: () => boolean | Promise<boolean>;
277
280
  readonly apiBase?: string;
278
281
  readonly fetchImpl?: typeof fetch;
@@ -334,4 +337,4 @@ declare class InvalidPublishableKeyError extends Error {
334
337
  }
335
338
  declare function parsePublishableKey(key: string): ParsedPublishableKey;
336
339
 
337
- export { type ChecktivInitScope as A, type SubstrateContext as B, type ChecktivInitOptions as C, REMINT_READY_TIMEOUT_MS as D, createIdv as E, type FraudHandle as F, type GetSessionToken as G, type ChecktivCustomFormEvent as H, type InitOptions as I, type CustomFormCopy as J, type CustomFormFieldCopy as K, type CustomFormHandle as L, type MountOptions as M, type CustomFormMountOptions as N, createCustomForm as O, type ProvisionedHandle as P, createFraud as Q, type ResolvedIdvConfig as R, type SdkMode as S, type TokenManager as T, type ChecktivClient as a, type ChecktivSessions as b, type ChecktivError as c, type ChecktivErrorCode as d, type ChecktivEvent as e, type ChecktivFraudEvent as f, type ChecktivIdvEvent as g, type CrossDeviceHandoffHook as h, type FraudMountOptions as i, type GetSessionTokenContext as j, type IdvCoachingHint as k, type IdvHandle as l, type IdvMountOptions as m, InvalidPublishableKeyError as n, type MountCompleteResult as o, type MountProvisionedOptions as p, type MountScope as q, type ParsedPublishableKey as r, type SdkRegion as s, type SessionsCreateApplicant as t, type SessionsCreateApplicantAddress as u, type SessionsCreateInput as v, type SessionsCreateOptions as w, type SessionsCreateResult as x, type SyntheticIdvScript as y, parsePublishableKey as z };
340
+ export { parsePublishableKey as A, type ChecktivInitScope as B, type ChecktivInitOptions as C, type SubstrateContext as D, REMINT_READY_TIMEOUT_MS as E, type FraudHandle as F, type GetSessionToken as G, createIdv as H, type InitOptions as I, type ChecktivCustomFormEvent as J, type CustomFormCopy as K, type CustomFormFieldCopy as L, type MountOptions as M, type CustomFormHandle as N, type CustomFormMountOptions as O, type ProvisionedHandle as P, createCustomForm as Q, type ResolvedIdvConfig as R, type SdkRegion as S, type TokenManager as T, createFraud as U, type ChecktivClient as a, type ChecktivSessions as b, type ChecktivError as c, type ChecktivErrorCode as d, type ChecktivEvent as e, type ChecktivFraudEvent as f, type ChecktivIdvEvent as g, type ChecktivRecovery as h, type CrossDeviceHandoffHook as i, type FraudMountOptions as j, type GetSessionTokenContext as k, type IdvCoachingHint as l, type IdvHandle as m, type IdvMountOptions as n, InvalidPublishableKeyError as o, type MountCompleteResult as p, type MountProvisionedOptions as q, type MountScope as r, type ParsedPublishableKey as s, type SdkMode as t, type SessionsCreateApplicant as u, type SessionsCreateApplicantAddress as v, type SessionsCreateInput as w, type SessionsCreateOptions as x, type SessionsCreateResult as y, type SyntheticIdvScript as z };
@@ -1,7 +1,7 @@
1
- export { fallbackCopy, mount } from './chunk-5BFT2P4R.js';
1
+ export { fallbackCopy, mount } from './chunk-KGVV6QY6.js';
2
2
  import './chunk-HV2QKVJX.js';
3
3
  import './chunk-XOGHMNBX.js';
4
- import './chunk-OTBL3KBS.js';
4
+ import './chunk-ZNTQ6D5W.js';
5
5
  import './chunk-NHNGQ5BB.js';
6
6
  import './chunk-IQKHRPJR.js';
7
7
  import './chunk-QFA3K5ZV.js';
package/dist/capture.js CHANGED
@@ -1,4 +1,4 @@
1
- export { coachingKindForState, createCaptureController, isBiometricPhase, nextCapturePhaseAfterDocument, reducer } from './chunk-OTBL3KBS.js';
1
+ export { coachingKindForState, createCaptureController, isBiometricPhase, nextCapturePhaseAfterDocument, reducer } from './chunk-ZNTQ6D5W.js';
2
2
  import './chunk-NHNGQ5BB.js';
3
3
  import './chunk-IQKHRPJR.js';
4
4
  import './chunk-QFA3K5ZV.js';
@@ -1,4 +1,4 @@
1
- import { createChecktivError } from './chunk-OC5N6W7T.js';
1
+ import { createChecktivError } from './chunk-JS3Y6T76.js';
2
2
 
3
3
  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 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("upload_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(CAPTURE_ERROR_CODE[state.errorKind]);default:return null}}var opener=null;function registerCrossDeviceOpener(fn){opener=fn;}function getCrossDeviceOpener(){return opener}
4
4
 
@@ -0,0 +1,13 @@
1
+ import { getModule } from './chunk-GFHNOZVO.js';
2
+ import { createChecktivError, isChecktivError } from './chunk-JS3Y6T76.js';
3
+ import { parsePublishableKey, createWorkingTokenSource, createWorkingTokenManager } from './chunk-EXC2ZRUH.js';
4
+ import { resolveSession, warnWrongTokenPlane } from './chunk-DRNEDARS.js';
5
+ import { assertNever } from './chunk-UBQTPS5J.js';
6
+ import { createTokenManager } from './chunk-S2OOEDJS.js';
7
+ import { resolveApiBaseOrigin, sdkPublicSettings, shortCodeRefreshPath, PUBLISHABLE_KEY_HEADER, SESSIONS_ME_REFRESH_LINK_PATH } from './chunk-HFQJYEGZ.js';
8
+ import { R, k } from './chunk-XOGHMNBX.js';
9
+ import { getServiceOrigin } from './chunk-QFA3K5ZV.js';
10
+
11
+ 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}}}function missingModuleMessage(name){return `This session requires the '${name}' module. Import '@checktiv/sdk-web/${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};var STEP_TYPE_TO_VISUAL_MODULE={id_verification:"idv",custom_form:"custom_form"};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})})}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})}})}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 "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}for(const name of session.modules){if(destroyed)return;if(MODULE_IS_VISUAL[name]&&name!==currentStepVisualModule){continue}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,session:{sessionId:session.sessionId,stepId:session.stepId}});}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);}}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}:{},tokens:deps.tokens??createTokenManager(opts.getSessionToken,()=>sessionId),getSessionId:()=>sessionId,setSessionId:id=>{sessionId=id;}};function mount2(...args){if(args[0]==="idv"){const factory2=getModule("idv");if(factory2===void 0)return missingIdvHandle(args[1]);return factory2(ctx,args[1])}if(args[0]==="custom_form"){const factory2=getModule("custom_form");if(factory2===void 0)return missingCustomFormHandle(args[1]);return factory2(ctx,args[1])}const factory=getModule("fraud");if(factory===void 0)return missingFraudHandle(args[1]);return factory(ctx,args[1])}return {mountProvisioned:provOpts=>createMountProvisioned(ctx,provOpts),mount:mount2}}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 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.7.2";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);}function completionSessionId(e){if(e.type!=="checktiv.idv.submitted"&&e.type!=="checktiv.custom_form.submitted"){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){const wire={};if(a.externalId!==void 0)wire.external_id=a.externalId;if(a.email!==void 0)wire.email=a.email;if(a.phone!==void 0)wire.phone=a.phone;if(a.firstName!==void 0)wire.first_name=a.firstName;if(a.middleName!==void 0)wire.middle_name=a.middleName;if(a.lastName!==void 0)wire.last_name=a.lastName;if(a.legalName!==void 0)wire.legal_name=a.legalName;if(a.dateOfBirth!==void 0)wire.date_of_birth=a.dateOfBirth;if(a.address!==void 0)wire.address=addressToWire(a.address);if(a.referenceName!==void 0)wire.reference_name=a.referenceName;return wire}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}}};
12
+
13
+ export { init, isSessionsCreateError, mount, mountButton, sessions, version };
@@ -1,5 +1,5 @@
1
1
  import { withTokenRetry } from './chunk-S2OOEDJS.js';
2
- import { sdkPublicSettings, SESSIONS_ME_PATH, dataPlaneHeaders } from './chunk-KK66RKPI.js';
2
+ import { sdkPublicSettings, SESSIONS_ME_PATH, dataPlaneHeaders } from './chunk-HFQJYEGZ.js';
3
3
  import { IDV_DOCUMENT_TYPES } from './chunk-IQKHRPJR.js';
4
4
 
5
5
  var SDK_MODULES=["idv","fraud","custom_form"];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"];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 parseCollectUserInfoConfig(value){if(!isRecord(value))return null;const fields=value.fields;const captureStructuredName=value.capture_structured_name;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;return {fields:parsedFields,captureStructuredName}}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 config={documentTypes:types,biometricMode};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)}),result=>result?.status===401);}catch{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"}}
@@ -1,4 +1,4 @@
1
- import { WORKING_TOKEN_MINT_PATH, PUBLISHABLE_KEY_HEADER } from './chunk-KK66RKPI.js';
1
+ import { WORKING_TOKEN_MINT_PATH, PUBLISHABLE_KEY_HEADER } from './chunk-HFQJYEGZ.js';
2
2
 
3
3
  var PUBLISHABLE_KEY_REGEX=/^ah_pk_(us|eu)_(live|test)_[A-Za-z0-9_-]{8,}$/;var InvalidPublishableKeyError=class extends Error{constructor(message){super(message);this.name="InvalidPublishableKeyError";}};function parsePublishableKey(key){const match=PUBLISHABLE_KEY_REGEX.exec(key);if(!match){throw new InvalidPublishableKeyError(`Invalid publishable key format. Expected ah_pk_<us|eu>_<live|test>_<token>, got: ${maskKey(key)}`)}const region=match[1];const mode=match[2];if(region!=="us"&&region!=="eu"){throw new InvalidPublishableKeyError(`Invalid region in publishable key: ${maskKey(key)}`)}if(mode!=="test"&&mode!=="live"){throw new InvalidPublishableKeyError(`Invalid mode in publishable key: ${maskKey(key)}`)}return {region,mode}}function maskKey(key){if(key.length<=8)return "***";return `${key.slice(0,6)}...${key.slice(-2)}`}var DEFAULT_REFRESH_MARGIN_MS=6e4;function createWorkingTokenManager(source,deps={}){const now=deps.now??(()=>Date.now());const setTimer=deps.setTimer??((fn,ms)=>setTimeout(fn,ms));const clearTimer=deps.clearTimer??(handle=>clearTimeout(handle));const marginMs=deps.marginMs??DEFAULT_REFRESH_MARGIN_MS;const onProactiveError=deps.onProactiveError;let cached=null;let pending=null;let timer=null;let stopped=false;const clearScheduled=()=>{if(timer!==null){clearTimer(timer);timer=null;}};const scheduleProactive=expiresAt=>{clearScheduled();if(stopped)return;const expiryMs=Date.parse(expiresAt);if(Number.isNaN(expiryMs))return;const delay=expiryMs-now()-marginMs;if(delay<=0)return;timer=setTimer(()=>{timer=null;void doRefresh("expired").catch(err=>onProactiveError?.(err));},delay);};const mintOnce=reason=>source(reason).then(minted=>{scheduleProactive(minted.expiresAt);return minted.token});const doRefresh=reason=>{if(pending!==null)return pending;const p=mintOnce(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};return {get(){if(cached!==null)return cached;const p=mintOnce("initial");cached=p;void p.catch(()=>{if(cached===p)cached=null;});return p},refresh(reason){return doRefresh(reason)},stop(){stopped=true;clearScheduled();}}}function parseWorkingTokenMintResponse(body){if(typeof body!=="object"||body===null)return null;if(!("workingToken"in body)||!("expiresAt"in body))return null;const workingToken=body.workingToken;const expiresAt=body.expiresAt;if(typeof workingToken!=="string"||workingToken.length===0)return null;if(typeof expiresAt!=="string"||expiresAt.length===0)return null;return {workingToken,expiresAt}}async function mintWorkingTokenFacet(origin,clientToken,publishableKey,fetchImpl){const headers={Authorization:`Bearer ${clientToken}`};if(publishableKey!==void 0)headers[PUBLISHABLE_KEY_HEADER]=publishableKey;const res=await fetchImpl(origin+WORKING_TOKEN_MINT_PATH,{method:"POST",headers});if(!res.ok){throw new Error(`Checktiv working-token mint failed (status ${res.status}).`)}let body;try{body=await res.json();}catch{throw new Error("Checktiv working-token mint returned a non-JSON body.")}const parsed=parseWorkingTokenMintResponse(body);if(parsed===null)throw new Error("Checktiv working-token mint returned a malformed body.");return parsed}function createWorkingTokenSource(origin,getClientToken,publishableKey,fetchImpl){return async()=>{const clientToken=await getClientToken();const minted=await mintWorkingTokenFacet(origin,clientToken,publishableKey,fetchImpl);return {token:minted.workingToken,expiresAt:minted.expiresAt}}}
4
4
 
@@ -1,8 +1,8 @@
1
- import { parsePublishableKey, createWorkingTokenSource, createWorkingTokenManager } from './chunk-EYSE7JJ4.js';
2
- import { resolveSession, warnWrongTokenPlane } from './chunk-7F7ZMYB7.js';
1
+ import { parsePublishableKey, createWorkingTokenSource, createWorkingTokenManager } from './chunk-EXC2ZRUH.js';
2
+ import { resolveSession, warnWrongTokenPlane } from './chunk-DRNEDARS.js';
3
3
  import { assertNever } from './chunk-UBQTPS5J.js';
4
4
  import { withTokenRetry } from './chunk-S2OOEDJS.js';
5
- import { stepSubmitPath, dataPlaneHeaders, resolveApiBaseOrigin } from './chunk-KK66RKPI.js';
5
+ import { stepSubmitPath, dataPlaneHeaders, resolveApiBaseOrigin } from './chunk-HFQJYEGZ.js';
6
6
 
7
7
  var ERROR_MESSAGES={not_collect_step:"The current step does not collect user info. Mount the verification journey to continue.",validation_failed:"The submitted information was rejected. Check the required fields and try again.",token_expired:"The verification session expired. Create a new session so fetchToken returns a fresh client token, then try again.",origin_not_allowed:"This origin is not allowed for the publishable key. Add it to the allowed origins list in the Checktiv console.",rate_limited:"Too many requests. Wait a moment and try again.",service_unavailable:"The service is temporarily unavailable. Try again in a few seconds.",session_expired:"The verification session is no longer valid. Start a new verification from your backend.",wrong_token_type:"This verification could not start. Make sure fetchToken returns the client token, the same one you pass to Checktiv.mount().",network_error:"The request could not be completed. Check the connection and try again."};function fail(code){return {ok:false,code,message:ERROR_MESSAGES[code]}}function mapSubmitStatus(status){if(status===400||status===422)return "validation_failed";if(status===401)return "token_expired";if(status===403)return "origin_not_allowed";if(status===404)return "session_expired";if(status===429)return "rate_limited";if(status>=500)return "service_unavailable";return "session_expired"}function buildSubmitBody(input){const body={legalName:input.legalName};if(input.name!==void 0)body.name=input.name;if(input.email!==void 0)body.email=input.email;if(input.phone!==void 0)body.phone=input.phone;if(input.dateOfBirth!==void 0)body.dateOfBirth=input.dateOfBirth;if(input.address!==void 0)body.address=input.address;return body}function buildContext(session,fetchImpl){const scope="publishableKey"in session?{...parsePublishableKey(session.publishableKey),publishableKey:session.publishableKey}:{region:session.region,mode:session.mode,publishableKey:void 0};const apiBaseOrigin=resolveApiBaseOrigin(session.apiBase,scope.region,scope.mode);let clientTokenPromise=null;const getClientToken=()=>{if(clientTokenPromise!==null)return clientTokenPromise;const p=session.fetchToken();clientTokenPromise=p;void p.catch(()=>{if(clientTokenPromise===p)clientTokenPromise=null;});return p};const mintWorkingToken=createWorkingTokenSource(apiBaseOrigin,getClientToken,scope.publishableKey,fetchImpl);const tokens=createWorkingTokenManager(mintWorkingToken);let sessionId="";const ctx={region:scope.region,mode:scope.mode,publishableKey:scope.publishableKey,apiBaseOrigin,locale:"en",betas:[],tokens,getSessionId:()=>sessionId,setSessionId:id=>{sessionId=id;}};return {ctx,tokens}}function collectUserInfo(opts){const{session}=opts;const fetchImpl=session.fetchImpl??fetch;const{ctx,tokens}=buildContext(session,fetchImpl);return {async submit(input){try{const resolution=await resolveSession(ctx,fetchImpl);switch(resolution.kind){case "wrong_token":warnWrongTokenPlane();return fail("wrong_token_type");case "unresolved":return fail("session_expired");case "nothing_to_render":return fail("not_collect_step");case "ok":break;default:return assertNever(resolution)}const resolved=resolution.session;if(resolved.stepType!=="collect_user_info"){return fail("not_collect_step")}const body=buildSubmitBody(input);let res;try{res=await withTokenRetry(ctx.tokens,token=>fetchImpl(ctx.apiBaseOrigin+stepSubmitPath(resolved.sessionId,resolved.stepId),{method:"POST",headers:dataPlaneHeaders(ctx,token,{withJsonBody:true}),body:JSON.stringify(body)}),result=>result?.status===401);}catch{return fail("network_error")}if(res.ok)return {ok:true};return fail(mapSubmitStatus(res.status))}finally{tokens.stop();}},async describe(){const fresh=buildContext(session,fetchImpl);try{const resolution=await resolveSession(fresh.ctx,fetchImpl);switch(resolution.kind){case "wrong_token":warnWrongTokenPlane();return {ok:false,code:"wrong_token_type"};case "unresolved":return {ok:false,code:"session_expired"};case "nothing_to_render":return {ok:false,code:"not_collect_step"};case "ok":break;default:return assertNever(resolution)}const resolved=resolution.session;if(resolved.stepType!=="collect_user_info"){return {ok:false,code:"not_collect_step"}}const config=resolved.collectUserInfoConfig;if(config===void 0){return {ok:true,fields:[],captureStructuredName:false}}return {ok:true,fields:config.fields,captureStructuredName:config.captureStructuredName}}finally{fresh.tokens.stop();}}}}
8
8
 
@@ -0,0 +1,5 @@
1
+ import { getServiceOrigin } from './chunk-QFA3K5ZV.js';
2
+
3
+ var sdkPublicSettings={"project":{"marketingApex":"checktiv.com"},"apps":{"verify":{"subdomain":"verify"},"workspace-embed":{"subdomain":"workspace"}},"services":{"sdk-api":{"subdomain":"sdk-api"},"sdk-cdn":{"subdomain":"sdk"},"public-api":{"subdomain":"api"}},"regions":{"us":{"apex":"us.checktiv.com"},"eu":{"apex":"eu.checktiv.com"}}};var PUBLISHABLE_KEY_HEADER="X-Publishable-Key";function dataPlaneHeaders(ctx,token,opts={}){const headers={Authorization:`Bearer ${token}`};if(ctx.publishableKey!==void 0){headers[PUBLISHABLE_KEY_HEADER]=ctx.publishableKey;}if(opts.withJsonBody)headers["content-type"]="application/json";return headers}function resolveSdkApiOrigin(region,_mode,_hostname){return getServiceOrigin(sdkPublicSettings.services["sdk-api"].subdomain,"prod",region,sdkPublicSettings)}function regionToApiBase(region){return getServiceOrigin(sdkPublicSettings.services["public-api"].subdomain,"prod",region,sdkPublicSettings)}function isCanonicalOrigin(value){if(typeof value!=="string"||value.length===0)return false;try{return new URL(value).origin===value}catch{return false}}function resolveApiBaseOrigin(apiBase,region,mode,hostname){if(isCanonicalOrigin(apiBase))return apiBase;return resolveSdkApiOrigin(region)}var SESSIONS_ME_PATH="/sdk/v1/sessions/me";var SESSIONS_CROSS_DEVICE_STATUS_PATH=`${SESSIONS_ME_PATH}/cross-device-status`;var WORKING_TOKEN_MINT_PATH="/sdk/v1/working-token";var CAPTURE_TOKEN_MINT_PATH="/sdk/v1/idv/capture-token";function stepSubmitPath(_sessionId,stepId){return `${SESSIONS_ME_PATH}/steps/${encodeURIComponent(stepId)}/submit`}var TELEMETRY_PATH="/sdk/v1/telemetry";var SESSIONS_ME_REFRESH_LINK_PATH="/sdk/v1/sessions/me/refresh-link";function shortCodeRefreshPath(code){return `/sdk/v1/short-codes/${encodeURIComponent(code)}/refresh`}function formUploadUrlPath(stepId){return `${SESSIONS_ME_PATH}/steps/${encodeURIComponent(stepId)}/form-upload-url`}
4
+
5
+ export { CAPTURE_TOKEN_MINT_PATH, PUBLISHABLE_KEY_HEADER, SESSIONS_CROSS_DEVICE_STATUS_PATH, SESSIONS_ME_PATH, SESSIONS_ME_REFRESH_LINK_PATH, TELEMETRY_PATH, WORKING_TOKEN_MINT_PATH, dataPlaneHeaders, formUploadUrlPath, isCanonicalOrigin, regionToApiBase, resolveApiBaseOrigin, sdkPublicSettings, shortCodeRefreshPath, stepSubmitPath };
@@ -0,0 +1,3 @@
1
+ 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."},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_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."},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===401)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 { createChecktivError, isChecktivError, mapHttpStatusToError };
@@ -1,6 +1,6 @@
1
1
  import { u } from './chunk-HV2QKVJX.js';
2
2
  import { R, k } from './chunk-XOGHMNBX.js';
3
- import { createCaptureController, isBiometricPhase, coachingKindForState } from './chunk-OTBL3KBS.js';
3
+ import { createCaptureController, isBiometricPhase, coachingKindForState } from './chunk-ZNTQ6D5W.js';
4
4
 
5
5
  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."}}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,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 terminal=errorKind==="protocol_mismatch";return u("div",{className:"idv-capture-error",role:"alert",children:[u("p",{children:(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();}}}
6
6
 
@@ -0,0 +1,6 @@
1
+ import { external_exports } from './chunk-NHNGQ5BB.js';
2
+ import { IDV_DOCUMENT_TYPES, isTwoSidedDocumentType } from './chunk-IQKHRPJR.js';
3
+
4
+ var behaviorTraitsSchema=external_exports.object({webdriver:external_exports.boolean(),maxTouchPoints:external_exports.number().int().min(0).max(512),timezone:external_exports.string().max(64).nullable(),pluginCount:external_exports.number().int().min(0).max(256),deviceModelHint:external_exports.string().max(120).nullable()}).strict();var behaviorStepSchema=external_exports.object({stepId:external_exports.string().max(80),seconds:external_exports.number().min(0).max(86400),pasteCount:external_exports.number().int().min(0).max(1e4)}).strict();var behaviorSurfaceEnum=external_exports.enum(["parent","embed"]);var behaviorCapturedPayloadSchema=external_exports.object({steps:external_exports.array(behaviorStepSchema).max(50),traits:behaviorTraitsSchema,segments:external_exports.array(external_exports.object({surface:behaviorSurfaceEnum,steps:external_exports.array(behaviorStepSchema).max(50),traits:behaviorTraitsSchema}).strict()).max(4).optional()}).strict();behaviorCapturedPayloadSchema.extend({ingress:external_exports.enum(["hosted","embedded"]).optional(),stepId:external_exports.string().max(128).optional()}).strict();var REGION_IDS=["us","eu"];var SystemModes=["live","test"];var DataRegions=REGION_IDS;var CURRENT_PROTOCOL_VERSION=1;var LivenessAwsRegions=["us-east-1","eu-west-1"];({us:LivenessAwsRegions[0],eu:LivenessAwsRegions[1]});external_exports.uuid();external_exports.email().toLowerCase();external_exports.object({createdAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()});var dataRegionEnum=external_exports.enum(DataRegions);var dataModeEnum=external_exports.enum(SystemModes);external_exports.object({orgId:external_exports.string().min(1),mode:dataModeEnum,region:dataRegionEnum});external_exports.object({orgId:external_exports.string().min(1),actorId:external_exports.string().min(1),mode:dataModeEnum,region:dataRegionEnum,traceId:external_exports.string().optional()});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)");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 MAX_FIELDS_PER_SCREEN=8;var MAX_RULES_PER_SCREEN=10;var MAX_LOCALES=5;var MAX_LABEL_LEN=600;var bcp47LocaleSchema=external_exports.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=external_exports.record(bcp47LocaleSchema,external_exports.string().max(MAX_LABEL_LEN)).refine(map=>Object.keys(map).length<=MAX_LOCALES,{message:`at most ${MAX_LOCALES} locales per label`});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=external_exports.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=external_exports.object({minLength:external_exports.number().int().nonnegative().optional(),maxLength:external_exports.number().int().positive().optional(),min:external_exports.number().optional(),max:external_exports.number().optional(),minSelections:external_exports.number().int().nonnegative().optional(),maxSelections:external_exports.number().int().positive().optional()}).strict();var formFieldOptionSchema=external_exports.object({value:external_exports.string().min(1).max(200),label:bcp47I18nLabelSchema}).strict();var formFieldSchema=external_exports.object({id:formFieldSlugSchema,type:external_exports.enum(FORM_FIELD_TYPES),label:bcp47I18nLabelSchema,helpText:bcp47I18nLabelSchema.optional(),required:external_exports.boolean().default(false),validation:formFieldValidationSchema.optional(),options:external_exports.array(formFieldOptionSchema).max(50).optional()}).strict();var formRuleOpEnum=external_exports.enum(["eq","neq","in"]);var formRuleActionEnum=external_exports.enum(["flag_for_review","notify_email"]);var formRuleValueSchema=external_exports.union([external_exports.string(),external_exports.number(),external_exports.boolean(),external_exports.array(external_exports.union([external_exports.string(),external_exports.number(),external_exports.boolean()]))]);var formRuleSchema=external_exports.object({id:formFieldSlugSchema,when:external_exports.object({fieldId:formFieldSlugSchema,op:formRuleOpEnum,value:formRuleValueSchema}).strict(),actions:external_exports.array(formRuleActionEnum).min(1),notifyOrgMemberIds:external_exports.array(external_exports.string().min(1)).max(25).optional()}).strict();var customFormScreenConfigSchema=external_exports.object({supportedLocales:external_exports.array(bcp47LocaleSchema).min(1).max(MAX_LOCALES),fields:external_exports.array(formFieldSchema).min(1).max(MAX_FIELDS_PER_SCREEN),rules:external_exports.array(formRuleSchema).max(MAX_RULES_PER_SCREEN).default([])}).strict();var hexColorSchema=external_exports.string().regex(/^#[0-9a-fA-F]{6}$/,"Must be a 6-digit hex color, e.g. #2563eb");var colorModeSchema=external_exports.enum(["auto","light","dark"]);external_exports.object({primaryColor:hexColorSchema,secondaryColor:hexColorSchema.nullable().default(null),colorMode:colorModeSchema.default("auto")});var organizationBrandingSchema=external_exports.object({brandName:external_exports.string().min(1).max(120).optional(),primaryColor:hexColorSchema.optional(),secondaryColor:hexColorSchema.nullable().optional(),colorMode:colorModeSchema.optional(),logoUrl:external_exports.url().optional()});organizationBrandingSchema.omit({logoUrl:true});var checkTypeEnum=external_exports.enum(["collect_user_info","watchlist","background_us_criminal","background_global","id_verification","custom_form"]);var testHintEnum=external_exports.enum(["pass","review","fail","doc_quality"]);var STEP_ID_REGEX=/^step_[0-9A-Za-z_-]{1,64}$/;var ADDRESS_TEXT_REGEX=/^[^\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069<>]+$/;var safeAddressText=max=>external_exports.string().min(1).max(max).regex(ADDRESS_TEXT_REGEX,"invalid characters");var postalCodeField=external_exports.string().max(20).regex(/^[A-Za-z0-9 \-]*$/);var countryField=external_exports.string().length(2).regex(/^[A-Z]{2}$/);var placeIdField=external_exports.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"};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){return issue=>{if(issue.code!=="unrecognized_keys")return void 0;return issue.keys.map(key=>{const suggestion=nearestKnownKey(key,knownKeys);return suggestion?`Unknown field "${key}". Did you mean "${suggestion}"?`:`Unknown field "${key}".`}).join(" ")}}external_exports.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()};external_exports.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=external_exports.object({minAttemptsBeforeShown:external_exports.number().int().nonnegative().default(0),requireReason:external_exports.boolean().default(false)}).loose();var i18nLabelSchema=external_exports.record(external_exports.string(),external_exports.string());var stepConditionSchema=external_exports.object({field:external_exports.string(),operator:external_exports.enum(["eq","neq","in","not_in"]),value:external_exports.union([external_exports.string(),external_exports.array(external_exports.string())])}).optional();var workflowStepSchema=external_exports.object({checkType:checkTypeEnum,isRequired:external_exports.boolean().default(true),order:external_exports.number().int(),maxAttempts:external_exports.number().int().default(3),condition:stepConditionSchema,label:external_exports.string().optional()});external_exports.array(workflowStepSchema).min(1);var baseStepFields={id:external_exports.string().regex(STEP_ID_REGEX),order:external_exports.number().int().nonnegative(),isRequired:external_exports.boolean().default(true),applicantSkippable:external_exports.boolean().default(false),applicantSkipPolicy:applicantSkipPolicySchema.optional(),maxAttempts:external_exports.number().int().positive().default(3),label:i18nLabelSchema.optional(),description:i18nLabelSchema.optional(),dependsOn:external_exports.array(external_exports.string()).optional(),condition:external_exports.unknown().nullable().optional()};var backgroundConfigSchema=external_exports.object({jurisdictionScope:external_exports.enum(["us","eu","global"]).default("global"),recordTypesIncluded:external_exports.array(external_exports.enum(["criminal","sex_offender","adverse_media"])).min(1).default(["criminal"])}).default({jurisdictionScope:"global",recordTypesIncluded:["criminal"]});var watchlistConfigSchema=external_exports.object({lists:external_exports.array(external_exports.enum(["pep","ofac","eu","un"])).default([]),confidenceThreshold:external_exports.number().min(0).max(1).default(.8)}).default({lists:[],confidenceThreshold:.8});var COLLECT_USER_INFO_FIELDS=["email","phone","dob","address"];var collectUserInfoConfigSchema=external_exports.object({fields:external_exports.preprocess(raw=>{if(!Array.isArray(raw))return raw;return raw.filter(v=>v!=="name")},external_exports.array(external_exports.enum(COLLECT_USER_INFO_FIELDS))).default(["email","phone"]),captureStructuredName:external_exports.boolean().default(false)}).default({fields:["email","phone"],captureStructuredName:false});var idvDocumentTypeEnum=external_exports.enum(IDV_DOCUMENT_TYPES);var idVerificationConfigSchema=external_exports.object({documentTypes:idvDocumentTypeEnum.array().min(1).default([...IDV_DOCUMENT_TYPES]),biometricMode:external_exports.enum(["none","selfie","liveness"]).default("none"),requireMrzMatch:external_exports.boolean().default(false),requireExpiryValid:external_exports.boolean().default(true),requireNameMatch:external_exports.boolean().default(false),documentAuthenticity:external_exports.boolean().default(false),minAge:external_exports.number().int().min(0).max(150).optional()}).strict().default({documentTypes:[...IDV_DOCUMENT_TYPES],biometricMode:"none",requireMrzMatch:false,requireExpiryValid:true,requireNameMatch:false,documentAuthenticity:false});var watchlistStepSchema=external_exports.object({...baseStepFields,type:external_exports.literal("watchlist"),config:watchlistConfigSchema});var backgroundUsCriminalStepSchema=external_exports.object({...baseStepFields,type:external_exports.literal("background_us_criminal"),config:backgroundConfigSchema});var backgroundGlobalStepSchema=external_exports.object({...baseStepFields,type:external_exports.literal("background_global"),config:backgroundConfigSchema});var collectUserInfoStepSchema=external_exports.object({...baseStepFields,type:external_exports.literal("collect_user_info"),config:collectUserInfoConfigSchema});var idVerificationStepSchema=external_exports.object({...baseStepFields,type:external_exports.literal("id_verification"),config:idVerificationConfigSchema});var customFormScreenStepSchema=external_exports.object({...baseStepFields,type:external_exports.literal("custom_form"),config:customFormScreenConfigSchema});external_exports.discriminatedUnion("type",[watchlistStepSchema,backgroundUsCriminalStepSchema,backgroundGlobalStepSchema,collectUserInfoStepSchema,idVerificationStepSchema,customFormScreenStepSchema]);var captureBrandTokensSchema=external_exports.object({primary:hexColorSchema,primaryHover:hexColorSchema,onPrimary:hexColorSchema,secondary:hexColorSchema,onSecondary:hexColorSchema,ring:hexColorSchema}).strict();var captureThemeSchema=external_exports.object({colorMode:external_exports.enum(["light","dark"]),brandTokens:captureBrandTokensSchema.nullable().default(null)}).strict();var captureDocumentSideEnum=external_exports.enum(["front","back"]);var captureDocumentGroupEnum=external_exports.enum(["unknown","dl","id","passport","passport-card","visa"]);var captureErrorCodeEnum=external_exports.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"]);external_exports.enum(["no_face","multiple_faces","too_dark","move_closer","not_centered","hold_still","ready"]);var selfiePromptMapSchema=external_exports.object({no_face:external_exports.string().min(1).max(120).optional(),multiple_faces:external_exports.string().min(1).max(120).optional(),too_dark:external_exports.string().min(1).max(120).optional(),move_closer:external_exports.string().min(1).max(120).optional(),not_centered:external_exports.string().min(1).max(120).optional(),hold_still:external_exports.string().min(1).max(120).optional(),ready:external_exports.string().min(1).max(120).optional()}).strict();var selfieChromeCopySchema=external_exports.object({shutterLabel:external_exports.string().min(1).max(80).optional(),shutterHint:external_exports.string().min(1).max(120).optional(),confirm:external_exports.string().min(1).max(80).optional(),retake:external_exports.string().min(1).max(80).optional()}).strict();var captureInitMessageSchema=external_exports.object({type:external_exports.literal("capture:init"),captureToken:external_exports.string().min(1),config:idVerificationConfigSchema,locale:external_exports.string().min(2).max(35),theme:captureThemeSchema,mode:dataModeEnum.optional(),testHint:testHintEnum.optional(),protocolVersion:external_exports.number().int().min(1).optional(),beginScanPrompt:external_exports.string().min(1).max(200).optional(),beginScanLabel:external_exports.string().min(1).max(80).optional(),selfiePromptMap:selfiePromptMapSchema.optional(),selfieChromeCopy:selfieChromeCopySchema.optional()}).strict();external_exports.object({data:external_exports.object({captureToken:external_exports.string().min(1),embedOrigin:canonicalOriginSchema,runIndex:external_exports.number().int().min(0),expiresAt:external_exports.iso.datetime({offset:true}),embedContextToken:external_exports.string().min(1),mode:dataModeEnum.optional(),testHint:testHintEnum.optional()}).strict()}).strict();var captureReadyMessageSchema=external_exports.object({type:external_exports.literal("capture:ready")}).strict();var captureDocumentCompleteMessageSchema=external_exports.object({type:external_exports.literal("capture:document-complete"),side:captureDocumentSideEnum,r2Key:external_exports.string().min(1)}).strict();var captureSelfieCompleteMessageSchema=external_exports.object({type:external_exports.literal("capture:selfie-complete"),r2Key:external_exports.string().min(1)}).strict();var captureCoachingMessageSchema=external_exports.object({type:external_exports.literal("capture:coaching"),state:external_exports.string().min(1).max(120),attemptIndex:external_exports.number().int().min(0)}).strict();var captureSelfieCvRejectMessageSchema=external_exports.object({type:external_exports.literal("capture:selfie-cv-reject"),retryReason:external_exports.string().min(1).max(120).optional(),attemptIndex:external_exports.number().int().min(0)}).strict();var captureErrorMessageSchema=external_exports.object({type:external_exports.literal("capture:error"),code:captureErrorCodeEnum}).strict();var captureBiometricCameraLiveMessageSchema=external_exports.object({type:external_exports.literal("capture:biometric_camera_live"),timestamp:external_exports.number().optional()}).strict();var idvR2KeysSchema=external_exports.object({front:external_exports.string().min(1),back:external_exports.string().min(1).optional(),selfie:external_exports.string().min(1).optional()}).strict();var captureAllCompleteMessageSchema=external_exports.object({type:external_exports.literal("capture:all-complete"),r2Keys:idvR2KeysSchema,documentGroup:captureDocumentGroupEnum.optional()}).strict();external_exports.object({stepId:external_exports.string().min(1),runIndex:external_exports.number().int().min(0),r2Keys:idvR2KeysSchema,traceId:external_exports.string().optional()}).strict();external_exports.object({stepId:external_exports.string().min(1).optional()}).strict();var idvLivenessStsCredentialsSchema=external_exports.object({accessKeyId:external_exports.string().min(1),secretAccessKey:external_exports.string().min(1),sessionToken:external_exports.string().min(1),expiration:external_exports.string().min(1)}).strict();var livenessAwsRegionEnum=external_exports.enum(LivenessAwsRegions);external_exports.object({awsSessionId:external_exports.string().min(1),awsRegion:livenessAwsRegionEnum,credentials:idvLivenessStsCredentialsSchema}).strict();var captureBehaviorMessageSchema=external_exports.object({type:external_exports.literal("capture:behavior"),steps:external_exports.array(behaviorStepSchema).max(50),traits:behaviorTraitsSchema}).strict();var captureFromIframeMessageSchema=external_exports.discriminatedUnion("type",[captureReadyMessageSchema,captureDocumentCompleteMessageSchema,captureSelfieCompleteMessageSchema,captureCoachingMessageSchema,captureSelfieCvRejectMessageSchema,captureErrorMessageSchema,captureAllCompleteMessageSchema,captureBehaviorMessageSchema,captureBiometricCameraLiveMessageSchema]);external_exports.discriminatedUnion("type",[captureInitMessageSchema]);var idvCvGateRetryReasonEnum=external_exports.enum(["no_face_detected","multiple_faces","low_confidence","no_id_document","image_read_failed"]);external_exports.object({ok:external_exports.boolean(),retryReason:idvCvGateRetryReasonEnum.optional()}).strict();external_exports.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};default:return state}}function nextCapturePhaseAfterDocument(side,documentTypes,biometricMode){if(side==="front"&&documentTypes.some(isTwoSidedDocumentType))return "document_back";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 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 postInit(){if(destroyed||captureToken===null||pinnedOrigin===null)return false;const iframe=deps.getIframe();if(iframe===null||iframe.contentWindow===null)return false;const init={type:"capture:init",captureToken,...deps.initPayload()};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});return}case "capture:all-complete":{void submitCapture(msg.r2Keys);return}case "capture:behavior":{deps.onBehaviorSegment?.({steps:msg.steps,traits:msg.traits});return}case "capture:biometric_camera_live":{dispatch({type:"biometric_camera_live"});return}default:{const _exhaustive=msg;return _exhaustive}}}async function submitCapture(r2Keys){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;try{result=await deps.submit(runIndex,r2Keys);}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;messageListener=onWindowMessage;window.addEventListener("message",messageListener);dispatch({type:"mint_ok",...minted});}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;}}}}
5
+
6
+ export { CURRENT_PROTOCOL_VERSION, coachingKindForState, createCaptureController, isBiometricPhase, nextCapturePhaseAfterDocument, reducer };
@@ -1,4 +1,4 @@
1
- import { A as ChecktivInitScope } from './api-DWWQGjxL.js';
1
+ import { B as ChecktivInitScope } from './api-Cjh51lsw.js';
2
2
  import './machine-DZPN-A44.js';
3
3
  import './copy-CC_mrlVV.js';
4
4
  import './copy-DCeQ4JKx.js';
@@ -1,9 +1,9 @@
1
- export { collectUserInfo } from './chunk-YPYFPHOH.js';
2
- import './chunk-EYSE7JJ4.js';
3
- import './chunk-7F7ZMYB7.js';
1
+ export { collectUserInfo } from './chunk-F2BDZRAX.js';
2
+ import './chunk-EXC2ZRUH.js';
3
+ import './chunk-DRNEDARS.js';
4
4
  import './chunk-UBQTPS5J.js';
5
5
  import './chunk-S2OOEDJS.js';
6
- import './chunk-KK66RKPI.js';
6
+ import './chunk-HFQJYEGZ.js';
7
7
  import './chunk-IQKHRPJR.js';
8
8
  import './chunk-QFA3K5ZV.js';
9
9
  import './chunk-AIK7CDV6.js';
@@ -1,4 +1,4 @@
1
- export { H as ChecktivCustomFormEvent, J as CustomFormCopy, K as CustomFormFieldCopy, L as CustomFormHandle, N as CustomFormMountOptions, O as createCustomForm } from './api-DWWQGjxL.js';
1
+ export { J as ChecktivCustomFormEvent, K as CustomFormCopy, L as CustomFormFieldCopy, N as CustomFormHandle, O as CustomFormMountOptions, Q as createCustomForm } from './api-Cjh51lsw.js';
2
2
  import './machine-DZPN-A44.js';
3
3
  import './copy-CC_mrlVV.js';
4
4
  import './copy-DCeQ4JKx.js';
@@ -1,9 +1,9 @@
1
1
  import { registerModule } from './chunk-GFHNOZVO.js';
2
- import { createChecktivError, mapHttpStatusToError } from './chunk-OC5N6W7T.js';
3
- import { warnWrongTokenPlane, isRecord, isJourneyPlaneBody } from './chunk-7F7ZMYB7.js';
2
+ import { createChecktivError, mapHttpStatusToError } from './chunk-JS3Y6T76.js';
3
+ import { warnWrongTokenPlane, isRecord, isJourneyPlaneBody } from './chunk-DRNEDARS.js';
4
4
  import { assertNever } from './chunk-UBQTPS5J.js';
5
5
  import { withTokenRetry } from './chunk-S2OOEDJS.js';
6
- import { SESSIONS_ME_PATH, dataPlaneHeaders, stepSubmitPath, formUploadUrlPath } from './chunk-KK66RKPI.js';
6
+ import { SESSIONS_ME_PATH, dataPlaneHeaders, stepSubmitPath, formUploadUrlPath } from './chunk-HFQJYEGZ.js';
7
7
  import { u } from './chunk-HV2QKVJX.js';
8
8
  import { R, k, S } from './chunk-XOGHMNBX.js';
9
9
  import './chunk-IQKHRPJR.js';
package/dist/fraud.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { f as ChecktivFraudEvent, F as FraudHandle, i as FraudMountOptions, Q as createFraud } from './api-DWWQGjxL.js';
1
+ export { f as ChecktivFraudEvent, F as FraudHandle, j as FraudMountOptions, U as createFraud } from './api-Cjh51lsw.js';
2
2
  import './machine-DZPN-A44.js';
3
3
  import './copy-CC_mrlVV.js';
4
4
  import './copy-DCeQ4JKx.js';
package/dist/fraud.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { registerModule } from './chunk-GFHNOZVO.js';
2
- import { createChecktivError } from './chunk-OC5N6W7T.js';
3
- import { resolveSession, warnWrongTokenPlane } from './chunk-7F7ZMYB7.js';
2
+ import { createChecktivError } from './chunk-JS3Y6T76.js';
3
+ import { resolveSession, warnWrongTokenPlane } from './chunk-DRNEDARS.js';
4
4
  import { assertNever } from './chunk-UBQTPS5J.js';
5
5
  import { withTokenRetry } from './chunk-S2OOEDJS.js';
6
- import { TELEMETRY_PATH, dataPlaneHeaders } from './chunk-KK66RKPI.js';
6
+ import { TELEMETRY_PATH, dataPlaneHeaders } from './chunk-HFQJYEGZ.js';
7
7
  import './chunk-IQKHRPJR.js';
8
8
  import './chunk-QFA3K5ZV.js';
9
9
  import { __publicField } from './chunk-AIK7CDV6.js';
@@ -1,5 +1,5 @@
1
1
  import { S as SdkCrossDeviceStatusResponse } from '../machine-DZPN-A44.js';
2
- import { B as SubstrateContext, h as CrossDeviceHandoffHook, g as ChecktivIdvEvent } from '../api-DWWQGjxL.js';
2
+ import { D as SubstrateContext, i as CrossDeviceHandoffHook, g as ChecktivIdvEvent } from '../api-Cjh51lsw.js';
3
3
  import { C as CrossDeviceCopy } from '../copy-DCeQ4JKx.js';
4
4
  import { CrossDevicePanelProps, CrossDeviceHandle } from '../cross-device.js';
5
5
  import '../copy-CC_mrlVV.js';
@@ -1,7 +1,7 @@
1
- import { registerCrossDeviceOpener, createChecktivErrorEvent } from '../chunk-CGSNIVQF.js';
2
- import { createChecktivError } from '../chunk-OC5N6W7T.js';
1
+ import { registerCrossDeviceOpener, createChecktivErrorEvent } from '../chunk-CSNKMUIP.js';
2
+ import { createChecktivError } from '../chunk-JS3Y6T76.js';
3
3
  import { withTokenRetry } from '../chunk-S2OOEDJS.js';
4
- import { SESSIONS_ME_PATH, dataPlaneHeaders, SESSIONS_CROSS_DEVICE_STATUS_PATH } from '../chunk-KK66RKPI.js';
4
+ import { SESSIONS_ME_PATH, dataPlaneHeaders, SESSIONS_CROSS_DEVICE_STATUS_PATH } from '../chunk-HFQJYEGZ.js';
5
5
  import '../chunk-QFA3K5ZV.js';
6
6
  import '../chunk-AIK7CDV6.js';
7
7
 
package/dist/idv.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  import './machine-DZPN-A44.js';
2
2
  import './copy-CC_mrlVV.js';
3
- export { h as CrossDeviceHandoffHook, l as IdvHandle, m as IdvMountOptions, D as REMINT_READY_TIMEOUT_MS, E as createIdv } from './api-DWWQGjxL.js';
3
+ export { i as CrossDeviceHandoffHook, m as IdvHandle, n as IdvMountOptions, E as REMINT_READY_TIMEOUT_MS, H as createIdv } from './api-Cjh51lsw.js';
4
4
  import './copy-DCeQ4JKx.js';
package/dist/idv.js CHANGED
@@ -1,14 +1,14 @@
1
- import { createChecktivErrorEvent, mapStateToEvent, getCrossDeviceOpener } from './chunk-CGSNIVQF.js';
1
+ import { createChecktivErrorEvent, mapStateToEvent, getCrossDeviceOpener } from './chunk-CSNKMUIP.js';
2
2
  import { registerModule } from './chunk-GFHNOZVO.js';
3
- import { createChecktivError, mapHttpStatusToError } from './chunk-OC5N6W7T.js';
4
- import { resolveSession, warnWrongTokenPlane } from './chunk-7F7ZMYB7.js';
3
+ import { createChecktivError, mapHttpStatusToError } from './chunk-JS3Y6T76.js';
4
+ import { resolveSession, warnWrongTokenPlane } from './chunk-DRNEDARS.js';
5
5
  import { assertNever } from './chunk-UBQTPS5J.js';
6
6
  import { withTokenRetry } from './chunk-S2OOEDJS.js';
7
- import { stepSubmitPath, dataPlaneHeaders, CAPTURE_TOKEN_MINT_PATH, isCanonicalOrigin } from './chunk-KK66RKPI.js';
8
- import { mount } from './chunk-5BFT2P4R.js';
7
+ import { stepSubmitPath, dataPlaneHeaders, CAPTURE_TOKEN_MINT_PATH, isCanonicalOrigin } from './chunk-HFQJYEGZ.js';
8
+ import { mount } from './chunk-KGVV6QY6.js';
9
9
  import './chunk-HV2QKVJX.js';
10
10
  import './chunk-XOGHMNBX.js';
11
- import { CURRENT_PROTOCOL_VERSION } from './chunk-OTBL3KBS.js';
11
+ import { CURRENT_PROTOCOL_VERSION } from './chunk-ZNTQ6D5W.js';
12
12
  import './chunk-NHNGQ5BB.js';
13
13
  import './chunk-IQKHRPJR.js';
14
14
  import './chunk-QFA3K5ZV.js';
@@ -1,7 +1,7 @@
1
1
  import * as react from 'react';
2
2
  import { ReactNode, ReactElement } from 'react';
3
3
  import { CollectUserInfoSession, CollectUserInfoCollector } from './collect-user-info.js';
4
- import { g as ChecktivIdvEvent, M as MountOptions, C as ChecktivInitOptions, A as ChecktivInitScope, a as ChecktivClient } from './api-DWWQGjxL.js';
4
+ import { g as ChecktivIdvEvent, M as MountOptions, C as ChecktivInitOptions, B as ChecktivInitScope, a as ChecktivClient } from './api-Cjh51lsw.js';
5
5
  import { C as CaptureLayout, a as CaptureBehaviorMessage } from './machine-DZPN-A44.js';
6
6
  import { M as MountCopy } from './copy-CC_mrlVV.js';
7
7
 
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { C as ChecktivInitOptions, T as TokenManager, a as ChecktivClient, P as ProvisionedHandle, M as MountOptions, I as InitOptions, b as ChecktivSessions } from './api-DWWQGjxL.js';
2
- export { c as ChecktivError, d as ChecktivErrorCode, e as ChecktivEvent, f as ChecktivFraudEvent, g as ChecktivIdvEvent, h as CrossDeviceHandoffHook, F as FraudHandle, i as FraudMountOptions, G as GetSessionToken, j as GetSessionTokenContext, k as IdvCoachingHint, l as IdvHandle, m as IdvMountOptions, n as InvalidPublishableKeyError, o as MountCompleteResult, p as MountProvisionedOptions, q as MountScope, r as ParsedPublishableKey, R as ResolvedIdvConfig, S as SdkMode, s as SdkRegion, t as SessionsCreateApplicant, u as SessionsCreateApplicantAddress, v as SessionsCreateInput, w as SessionsCreateOptions, x as SessionsCreateResult, y as SyntheticIdvScript, z as parsePublishableKey } from './api-DWWQGjxL.js';
3
- import { S as SelfServiceResendResult } from './index-B9Gc_xWl.js';
4
- export { C as ChecktivIdvProps, a as ChecktivJourneyHandle, b as ChecktivJourneyProps, c as ChecktivProviderProps } from './index-B9Gc_xWl.js';
1
+ import { C as ChecktivInitOptions, T as TokenManager, a as ChecktivClient, S as SdkRegion, P as ProvisionedHandle, M as MountOptions, I as InitOptions, b as ChecktivSessions } from './api-Cjh51lsw.js';
2
+ export { c as ChecktivError, d as ChecktivErrorCode, e as ChecktivEvent, f as ChecktivFraudEvent, g as ChecktivIdvEvent, h as ChecktivRecovery, i as CrossDeviceHandoffHook, F as FraudHandle, j as FraudMountOptions, G as GetSessionToken, k as GetSessionTokenContext, l as IdvCoachingHint, m as IdvHandle, n as IdvMountOptions, o as InvalidPublishableKeyError, p as MountCompleteResult, q as MountProvisionedOptions, r as MountScope, s as ParsedPublishableKey, R as ResolvedIdvConfig, t as SdkMode, u as SessionsCreateApplicant, v as SessionsCreateApplicantAddress, w as SessionsCreateInput, x as SessionsCreateOptions, y as SessionsCreateResult, z as SyntheticIdvScript, A as parsePublishableKey } from './api-Cjh51lsw.js';
3
+ import { S as SelfServiceResendResult } from './index-9vcErEYX.js';
4
+ export { C as ChecktivIdvProps, a as ChecktivJourneyHandle, b as ChecktivJourneyProps, c as ChecktivProviderProps } from './index-9vcErEYX.js';
5
5
  export { C as CrossDeviceCopy } from './copy-DCeQ4JKx.js';
6
6
  import './machine-DZPN-A44.js';
7
7
  import './copy-CC_mrlVV.js';
@@ -13,6 +13,16 @@ interface InitDeps {
13
13
  }
14
14
  declare function init(opts: ChecktivInitOptions, deps?: InitDeps): ChecktivClient;
15
15
 
16
+ declare const SESSIONS_CREATE_ERROR_CODES: readonly ["unauthorized", "invalid_template", "rate_limited", "network", "server_error"];
17
+ type SessionsCreateErrorCode = (typeof SESSIONS_CREATE_ERROR_CODES)[number];
18
+ interface SessionsCreateError {
19
+ readonly code: SessionsCreateErrorCode;
20
+ readonly message: string;
21
+ }
22
+ declare function isSessionsCreateError(value: unknown): value is SessionsCreateError;
23
+
24
+ declare function regionToApiBase(region: SdkRegion): string;
25
+
16
26
  declare const version: string;
17
27
  declare function mountButton(opts: InitOptions): void;
18
28
  interface MountHandle extends ProvisionedHandle {
@@ -22,4 +32,4 @@ interface MountHandle extends ProvisionedHandle {
22
32
  declare function mount(target: HTMLElement | string, opts: MountOptions): MountHandle;
23
33
  declare const sessions: ChecktivSessions;
24
34
 
25
- export { ChecktivClient, ChecktivInitOptions, ChecktivSessions, InitOptions, type MountHandle, MountOptions, ProvisionedHandle, SelfServiceResendResult, init, mount, mountButton, sessions, version };
35
+ export { ChecktivClient, ChecktivInitOptions, ChecktivSessions, InitOptions, type MountHandle, MountOptions, ProvisionedHandle, SdkRegion, SelfServiceResendResult, type SessionsCreateError, type SessionsCreateErrorCode, init, isSessionsCreateError, mount, mountButton, regionToApiBase, sessions, version };
package/dist/index.js CHANGED
@@ -1,11 +1,11 @@
1
- export { init, mount, mountButton, sessions, version } from './chunk-VUBKYUVM.js';
1
+ export { init, isSessionsCreateError, mount, mountButton, sessions, version } from './chunk-D3ODHPCF.js';
2
2
  import './chunk-GFHNOZVO.js';
3
- import './chunk-OC5N6W7T.js';
4
- export { InvalidPublishableKeyError, parsePublishableKey } from './chunk-EYSE7JJ4.js';
5
- import './chunk-7F7ZMYB7.js';
3
+ import './chunk-JS3Y6T76.js';
4
+ export { InvalidPublishableKeyError, parsePublishableKey } from './chunk-EXC2ZRUH.js';
5
+ import './chunk-DRNEDARS.js';
6
6
  import './chunk-UBQTPS5J.js';
7
7
  import './chunk-S2OOEDJS.js';
8
- import './chunk-KK66RKPI.js';
8
+ export { regionToApiBase } from './chunk-HFQJYEGZ.js';
9
9
  import './chunk-XOGHMNBX.js';
10
10
  import './chunk-IQKHRPJR.js';
11
11
  import './chunk-QFA3K5ZV.js';
package/dist/react.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import 'react';
2
2
  import './collect-user-info.js';
3
- import './api-DWWQGjxL.js';
3
+ import './api-Cjh51lsw.js';
4
4
  import './machine-DZPN-A44.js';
5
5
  import './copy-CC_mrlVV.js';
6
- export { d as ChecktivIdv, C as ChecktivIdvProps, e as ChecktivJourney, a as ChecktivJourneyHandle, b as ChecktivJourneyProps, f as ChecktivProvider, c as ChecktivProviderProps, g as ChecktivProviderPropsBase, u as useChecktiv, h as useCollectUserInfo } from './index-B9Gc_xWl.js';
6
+ export { d as ChecktivIdv, C as ChecktivIdvProps, e as ChecktivJourney, a as ChecktivJourneyHandle, b as ChecktivJourneyProps, f as ChecktivProvider, c as ChecktivProviderProps, g as ChecktivProviderPropsBase, u as useChecktiv, h as useCollectUserInfo } from './index-9vcErEYX.js';
7
7
  import './copy-DCeQ4JKx.js';
package/dist/react.js CHANGED
@@ -1,12 +1,12 @@
1
- import { mount, init } from './chunk-VUBKYUVM.js';
1
+ import { mount, init } from './chunk-D3ODHPCF.js';
2
2
  import './chunk-GFHNOZVO.js';
3
- import './chunk-OC5N6W7T.js';
4
- import { collectUserInfo } from './chunk-YPYFPHOH.js';
5
- import './chunk-EYSE7JJ4.js';
6
- import './chunk-7F7ZMYB7.js';
3
+ import './chunk-JS3Y6T76.js';
4
+ import { collectUserInfo } from './chunk-F2BDZRAX.js';
5
+ import './chunk-EXC2ZRUH.js';
6
+ import './chunk-DRNEDARS.js';
7
7
  import './chunk-UBQTPS5J.js';
8
8
  import './chunk-S2OOEDJS.js';
9
- import './chunk-KK66RKPI.js';
9
+ import './chunk-HFQJYEGZ.js';
10
10
  import './chunk-XOGHMNBX.js';
11
11
  import './chunk-IQKHRPJR.js';
12
12
  import './chunk-QFA3K5ZV.js';
@@ -1,4 +1,4 @@
1
- import { s as SdkRegion } from './api-DWWQGjxL.js';
1
+ import { S as SdkRegion } from './api-Cjh51lsw.js';
2
2
  import './machine-DZPN-A44.js';
3
3
  import './copy-CC_mrlVV.js';
4
4
  import './copy-DCeQ4JKx.js';
package/dist/workspace.js CHANGED
@@ -1,4 +1,4 @@
1
- import { isCanonicalOrigin, sdkPublicSettings } from './chunk-KK66RKPI.js';
1
+ import { isCanonicalOrigin, sdkPublicSettings } from './chunk-HFQJYEGZ.js';
2
2
  import { getServiceOrigin } from './chunk-QFA3K5ZV.js';
3
3
  import './chunk-AIK7CDV6.js';
4
4
 
package/package.json CHANGED
@@ -1,18 +1,13 @@
1
1
  {
2
2
  "name": "@checktiv/sdk-web",
3
- "version": "1.6.1",
3
+ "version": "1.7.2",
4
4
  "private": false,
5
5
  "license": "Apache-2.0",
6
- "//publishConfigNameNote": "pnpm does NOT apply `publishConfig.name` (the publishConfig override list at https://pnpm.io/package_json#publishconfig excludes `name`; `pnpm pack` leaves the tarball `name` as the workspace name). The published `name` rewrite to `@checktiv/sdk-web` happens in the root `.pnpmfile.cjs` `beforePacking` hook (pnpm >= 10.28) instead — see that file's header. This field is retained ONLY as documentation of intent; the hook deletes it from the packed manifest. The packed-name gate in __tests__/dist-shape.test.ts reads the REAL extracted tarball, not this field.",
7
6
  "publishConfig": {
8
7
  "access": "public"
9
8
  },
10
- "//publishConfigExportsNote": "pnpm applies this `publishConfig.exports` override on `pnpm pack`/`pnpm publish` (NOT `npm pack`), so it defines the PUBLISHED npm shape while the top-level `exports` stays the in-repo (workspace) shape. Differences, both required: (1) every `types` target points at the built `./dist/*.d.ts` (the workspace map points `types` at `./src/*.ts` so in-repo consumers type-check against source with no build; those `.ts` files are NOT in the `files: [dist]` tarball, so publint --strict --pack would error on them). (2) `./agent` is OMITTED: it is a workspace-only export (not a customer API; keystone §5.1) that pulls the licensed, publishable-key-bound `@fingerprint/agent`, which must NEVER ship in the npm tarball (the C3 tarball guard's FORBIDDEN list proves it). `./agents` (the C13 machine-readable steering manifest -> ./dist/agents/manifest.json) IS published: C13's `scripts/generate-agent-steering.mjs` (chained into `build` after tsup) generates `dist/agents/manifest.json`, so it resolves in both the workspace map and this override; the dist-shape tarball test asserts `dist/agents/{AGENTS.md,manifest.json}` ship. publint --strict + attw (esm-only, against the pnpm-packed tarball) both validate THIS map.",
11
9
  "description": "Customer-embed Web SDK (Checktiv): tsup dual build — (A) ESM npm package (`@checktiv/sdk-web`) with per-subpath tree-shaking and Checktiv.init substrate for managed IDV / fraud modules, React wrapper; (B) CDN IIFE assigned to window.Checktiv (with legacy window.AutohostKyc alias for existing snippets). Published dist/ is built by tsup; CDN IIFE lands at services/sdk-cdn/public/v1/sdk.js.",
12
10
  "type": "module",
13
- "//exportsNote": "Dual conditions: `types` resolves to the source `.ts` file so in-repo consumers (verify, console) type-check against source without a build step (mirrors @rf/schemas pattern). `import` resolves to the compiled `dist/*.js` for the published npm package. `./agent` is a SOURCE-ONLY interim export (tsup profile A does not build a dist/agent.js yet; the verify app consumes it via its own bundler). `./agents` ships the C13 machine-readable steering manifest; `AGENTS.md` lives alongside it in dist/agents/ (discoverable via the file tree, no export entry to avoid publint resolution warnings). `src/cdn.ts` is the CDN-IIFE-only entry (tsup profile B) and is NOT a published subpath.",
14
- "//customFormStyleNote": "`./custom-form/style.css` exports the custom-form module's field stylesheet so the verify host can `import '@rf/sdk-web/custom-form/style.css'` from its island: the module renders REAL DOM field controls into the host document (unlike the IDV iframe), so its CSS must be injected into the host page. The workspace map points at the SOURCE css so verify's Vite processes + injects it WITHOUT a prior sdk-web dist build (dev-friendly); the publishConfig override points at the extracted `dist/custom-form.css` for CDN customers (who `<link>` it, like `capture-ui.css`). ONE stylesheet, single-sourced in `src/custom-form/custom-form.css`, theme-aware via `@rf/theme` tokens.",
15
- "//captureUiStyleNote": "`./capture-ui/style.css` exports the Tier-2 capture-frame stylesheet (`src/capture-ui/capture-ui.css`: frame sizing, biometric height, the C6 landscape clamp, and the phone immersive `layout` overlay) for the SAME reason as `./custom-form/style.css`. tsup EXTRACTS `capture-ui.css` to `dist/capture-ui.css` and STRIPS the source `import './capture-ui.css'` from the built JS, so an in-repo consumer bundling the `import`-condition `dist/*.js` (verify's PROD build) never auto-pulls the stylesheet and the frame ships UNSTYLED on deployed cells (local dev resolves the `types`/source condition, where the import IS followed — which is why it only regressed on a deployed cell). Verify imports `@rf/sdk-web/capture-ui/style.css` from `SdkIdVerificationIsland` (workspace map -> SOURCE, so Vite bundles it build-independently); the publishConfig override points at `dist/capture-ui.css` for CDN customers who `<link>` it.",
16
11
  "exports": {
17
12
  ".": {
18
13
  "types": "./dist/index.d.ts",
@@ -63,8 +58,6 @@
63
58
  "./agents": "./dist/agents/manifest.json",
64
59
  "./package.json": "./package.json"
65
60
  },
66
- "//challengeExportNote": "The `./challenge` subpath (top-level `exports` only, ABSENT from `publishConfig.exports`) is the generic parent-side challenge relay kernel consumed by `apps/verify` (ChallengeIframe). It stays OFF the npm-publish boundary (no schema-mirror / dist-shape / bundle-budget / CDN build), like `./agent`. tsup emits `dist/challenge.js` from the entry map for the in-repo `import` condition.",
67
- "//sideEffectsNote": "The module-load seam (src/substrate/module-registry.ts) makes the `./idv`, `./fraud`, and `./custom-form` entries SIDE-EFFECTFUL: each calls registerModule(...) at import-eval time so the substrate's mount('idv'|'fraud'|'custom_form')/mountProvisioned can resolve it. `./idv/cross-device` is ALSO side-effectful: it calls registerCrossDeviceOpener(...) (src/idv/cross-device-registry.ts) so createIdv().openCrossDevice() (S13/B2) resolves the overlay WITHOUT idv/index.ts importing the heavy orchestrator (keeps the CDN sdk.js flat). `src/idv/cross-device-cdn.ts` is the CDN-ONLY counterpart (imported for its side effect by src/cdn.ts, NOT a published subpath so it has no dist form): it registers a wrapper opener that injects a runtime chunk-URL importer so the CDN IIFE (window.Checktiv.mount) resolves the overlay by loading the pre-built /v1/cross-device.js chunk by URL instead of inlining the QR panel into sdk.js. Its registration side effect MUST be listed here or esbuild tree-shakes the side-effect-only `import './idv/cross-device-cdn.js'` in src/cdn.ts, leaving getCrossDeviceOpener() null in the IIFE. A blanket `sideEffects: false` would let a consumer's bundler tree-shake those registrations away (breaking the seams), so this lists ONLY the side-effectful entry files (src + published dist forms). Everything else still tree-shakes, so the `.` and `./react` entries stay Zod-free and per-subpath tree-shaking holds. When plan-C rewrites this manifest, KEEP this array (do NOT replace it with `false`).",
68
61
  "sideEffects": [
69
62
  "./src/idv/index.ts",
70
63
  "./src/idv/cross-device.ts",
@@ -96,32 +89,6 @@
96
89
  "optional": true
97
90
  }
98
91
  },
99
- "devDependencies": {
100
- "@arethetypeswrong/cli": "^0.18.0",
101
- "@aws-amplify/core": "6.16.4",
102
- "@aws-amplify/ui-react": "6.15.4",
103
- "@aws-amplify/ui-react-liveness": "3.6.7",
104
- "@fingerprint/agent": "4.1.0",
105
- "@microblink/capture": "^1.2.3",
106
- "@tensorflow/tfjs-backend-wasm": "4.11.0",
107
- "@tensorflow/tfjs-converter": "4.11.0",
108
- "@tensorflow/tfjs-core": "4.11.0",
109
- "@types/node": "^25.9.3",
110
- "@types/react": "^19.2.17",
111
- "@types/react-dom": "^19.2.3",
112
- "aws-amplify": "6.18.0",
113
- "esbuild": "^0.28.1",
114
- "jsdom": "^29.1.1",
115
- "preact": "^10.29.2",
116
- "publint": "^0.3.0",
117
- "tsup": "^8.5.0",
118
- "typescript": "5.9.3",
119
- "vitest": "^4.1.9",
120
- "@rf/config": "0.0.0",
121
- "@rf/iam-core": "0.0.1",
122
- "@rf/theme": "0.1.0",
123
- "@rf/schemas": "0.1.0"
124
- },
125
92
  "scripts": {
126
93
  "build": "tsup && node scripts/generate-agent-steering.mjs && pnpm run build:embed-capture && pnpm run build:embed-challenge && pnpm run build:host-capture && pnpm run build:cross-device",
127
94
  "build:embed-capture": "node scripts/build-embed-capture.mjs",
@@ -132,10 +99,8 @@
132
99
  "typecheck": "tsc --noEmit",
133
100
  "lint": "echo 'lint via tsc'",
134
101
  "size": "node ../../scripts/audit-bundle-size.mjs ../../services/sdk-cdn/public/v1/sdk.js 106496",
135
- "//sizeNote:host-capture": "MIRROR of the canonical gate scripts/audit-bundle-sizes.mjs (run by `pnpm audit:bundle-sizes` in the pre-push battery) - keep the limits in sync. Both host bundles rose one KiB to the next clean ceiling (capture.js 79->80, capture-ui.js 85->86) for the IDV branch: the new capture:biometric_camera_live wire-schema member is validated by safeParse in BOTH bundles (the controller ships in both) - an irreducible shared @rf/schemas/sdk contract - plus the controller's onBeforeSubmit SOC 2 fraud-flush hook (capture.js) and the biometric loading skeleton + MountCopy copy-seam + submit_pending render (capture-ui.js). The controller dispatch is already gzip-optimal (restructuring measurably worsens gzip).",
136
102
  "size:host-capture": "node ../../scripts/audit-bundle-size.mjs ../../services/sdk-cdn/public/v1/capture.js 82944",
137
103
  "size:host-capture-ui": "node ../../scripts/audit-bundle-size.mjs ../../services/sdk-cdn/public/v1/capture-ui.js 89088",
138
- "//sizeNote:cross-device": "MIRROR of the canonical gate scripts/audit-bundle-sizes.mjs cross-device line. The cross-device chunk is hash-named by esbuild; this script globs for the current artifact. The limit (20 KiB = 20480 B) is a headroom-padded ceiling over the qrcode-generator + Preact fragment weight at gzip.",
139
104
  "size:cross-device": "node ../../scripts/audit-bundle-size.mjs ../../services/sdk-cdn/public/v1/cross-device.js 20480",
140
105
  "size:npm": "node ../../scripts/audit-sdk-entry-size.mjs",
141
106
  "validate:publint": "publint --strict",
@@ -1,5 +0,0 @@
1
- import { getServiceOrigin } from './chunk-QFA3K5ZV.js';
2
-
3
- var sdkPublicSettings={"project":{"marketingApex":"checktiv.com"},"apps":{"verify":{"subdomain":"verify"},"workspace-embed":{"subdomain":"workspace"}},"services":{"sdk-api":{"subdomain":"sdk-api"},"sdk-cdn":{"subdomain":"sdk"}},"regions":{"us":{"apex":"us.checktiv.com"},"eu":{"apex":"eu.checktiv.com"}}};var PUBLISHABLE_KEY_HEADER="X-Publishable-Key";function dataPlaneHeaders(ctx,token,opts={}){const headers={Authorization:`Bearer ${token}`};if(ctx.publishableKey!==void 0){headers[PUBLISHABLE_KEY_HEADER]=ctx.publishableKey;}if(opts.withJsonBody)headers["content-type"]="application/json";return headers}function resolveSdkApiOrigin(region,_mode,_hostname){return getServiceOrigin(sdkPublicSettings.services["sdk-api"].subdomain,"prod",region,sdkPublicSettings)}function isCanonicalOrigin(value){if(typeof value!=="string"||value.length===0)return false;try{return new URL(value).origin===value}catch{return false}}function resolveApiBaseOrigin(apiBase,region,mode,hostname){if(isCanonicalOrigin(apiBase))return apiBase;return resolveSdkApiOrigin(region)}var SESSIONS_ME_PATH="/sdk/v1/sessions/me";var SESSIONS_CROSS_DEVICE_STATUS_PATH=`${SESSIONS_ME_PATH}/cross-device-status`;var WORKING_TOKEN_MINT_PATH="/sdk/v1/working-token";var CAPTURE_TOKEN_MINT_PATH="/sdk/v1/idv/capture-token";function stepSubmitPath(_sessionId,stepId){return `${SESSIONS_ME_PATH}/steps/${encodeURIComponent(stepId)}/submit`}var TELEMETRY_PATH="/sdk/v1/telemetry";var SESSIONS_ME_REFRESH_LINK_PATH="/sdk/v1/sessions/me/refresh-link";function shortCodeRefreshPath(code){return `/sdk/v1/short-codes/${encodeURIComponent(code)}/refresh`}function formUploadUrlPath(stepId){return `${SESSIONS_ME_PATH}/steps/${encodeURIComponent(stepId)}/form-upload-url`}
4
-
5
- export { CAPTURE_TOKEN_MINT_PATH, PUBLISHABLE_KEY_HEADER, SESSIONS_CROSS_DEVICE_STATUS_PATH, SESSIONS_ME_PATH, SESSIONS_ME_REFRESH_LINK_PATH, TELEMETRY_PATH, WORKING_TOKEN_MINT_PATH, dataPlaneHeaders, formUploadUrlPath, isCanonicalOrigin, resolveApiBaseOrigin, sdkPublicSettings, shortCodeRefreshPath, stepSubmitPath };
@@ -1,3 +0,0 @@
1
- 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."},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_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."},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."}};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===401)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"}
2
-
3
- export { createChecktivError, mapHttpStatusToError };
@@ -1,6 +0,0 @@
1
- import { external_exports } from './chunk-NHNGQ5BB.js';
2
- import { IDV_DOCUMENT_TYPES, isTwoSidedDocumentType } from './chunk-IQKHRPJR.js';
3
-
4
- var behaviorTraitsSchema=external_exports.object({webdriver:external_exports.boolean(),maxTouchPoints:external_exports.number().int().min(0).max(512),timezone:external_exports.string().max(64).nullable(),pluginCount:external_exports.number().int().min(0).max(256),deviceModelHint:external_exports.string().max(120).nullable()}).strict();var behaviorStepSchema=external_exports.object({stepId:external_exports.string().max(80),seconds:external_exports.number().min(0).max(86400),pasteCount:external_exports.number().int().min(0).max(1e4)}).strict();var behaviorSurfaceEnum=external_exports.enum(["parent","embed"]);var behaviorCapturedPayloadSchema=external_exports.object({steps:external_exports.array(behaviorStepSchema).max(50),traits:behaviorTraitsSchema,segments:external_exports.array(external_exports.object({surface:behaviorSurfaceEnum,steps:external_exports.array(behaviorStepSchema).max(50),traits:behaviorTraitsSchema}).strict()).max(4).optional()}).strict();behaviorCapturedPayloadSchema.extend({ingress:external_exports.enum(["hosted","embedded"]).optional(),stepId:external_exports.string().max(128).optional()}).strict();var REGION_IDS=["us","eu"];var SystemModes=["live","test"];var DataRegions=REGION_IDS;var CURRENT_PROTOCOL_VERSION=1;var LivenessAwsRegions=["us-east-1","eu-west-1"];({us:LivenessAwsRegions[0],eu:LivenessAwsRegions[1]});external_exports.uuid();external_exports.email().toLowerCase();external_exports.object({createdAt:external_exports.iso.datetime(),updatedAt:external_exports.iso.datetime()});var dataRegionEnum=external_exports.enum(DataRegions);var dataModeEnum=external_exports.enum(SystemModes);external_exports.object({orgId:external_exports.string().min(1),mode:dataModeEnum,region:dataRegionEnum});external_exports.object({orgId:external_exports.string().min(1),actorId:external_exports.string().min(1),mode:dataModeEnum,region:dataRegionEnum,traceId:external_exports.string().optional()});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)");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 MAX_FIELDS_PER_SCREEN=8;var MAX_RULES_PER_SCREEN=10;var MAX_LOCALES=5;var MAX_LABEL_LEN=600;var bcp47LocaleSchema=external_exports.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=external_exports.record(bcp47LocaleSchema,external_exports.string().max(MAX_LABEL_LEN)).refine(map=>Object.keys(map).length<=MAX_LOCALES,{message:`at most ${MAX_LOCALES} locales per label`});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=external_exports.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=external_exports.object({minLength:external_exports.number().int().nonnegative().optional(),maxLength:external_exports.number().int().positive().optional(),min:external_exports.number().optional(),max:external_exports.number().optional(),minSelections:external_exports.number().int().nonnegative().optional(),maxSelections:external_exports.number().int().positive().optional()}).strict();var formFieldOptionSchema=external_exports.object({value:external_exports.string().min(1).max(200),label:bcp47I18nLabelSchema}).strict();var formFieldSchema=external_exports.object({id:formFieldSlugSchema,type:external_exports.enum(FORM_FIELD_TYPES),label:bcp47I18nLabelSchema,helpText:bcp47I18nLabelSchema.optional(),required:external_exports.boolean().default(false),validation:formFieldValidationSchema.optional(),options:external_exports.array(formFieldOptionSchema).max(50).optional()}).strict();var formRuleOpEnum=external_exports.enum(["eq","neq","in"]);var formRuleActionEnum=external_exports.enum(["flag_for_review","notify_email"]);var formRuleValueSchema=external_exports.union([external_exports.string(),external_exports.number(),external_exports.boolean(),external_exports.array(external_exports.union([external_exports.string(),external_exports.number(),external_exports.boolean()]))]);var formRuleSchema=external_exports.object({id:formFieldSlugSchema,when:external_exports.object({fieldId:formFieldSlugSchema,op:formRuleOpEnum,value:formRuleValueSchema}).strict(),actions:external_exports.array(formRuleActionEnum).min(1),notifyOrgMemberIds:external_exports.array(external_exports.string().min(1)).max(25).optional()}).strict();var customFormScreenConfigSchema=external_exports.object({supportedLocales:external_exports.array(bcp47LocaleSchema).min(1).max(MAX_LOCALES),fields:external_exports.array(formFieldSchema).min(1).max(MAX_FIELDS_PER_SCREEN),rules:external_exports.array(formRuleSchema).max(MAX_RULES_PER_SCREEN).default([])}).strict();var hexColorSchema=external_exports.string().regex(/^#[0-9a-fA-F]{6}$/,"Must be a 6-digit hex color, e.g. #2563eb");var colorModeSchema=external_exports.enum(["auto","light","dark"]);external_exports.object({primaryColor:hexColorSchema,secondaryColor:hexColorSchema.nullable().default(null),colorMode:colorModeSchema.default("auto")});var organizationBrandingSchema=external_exports.object({brandName:external_exports.string().min(1).max(120).optional(),primaryColor:hexColorSchema.optional(),secondaryColor:hexColorSchema.nullable().optional(),colorMode:colorModeSchema.optional(),logoUrl:external_exports.url().optional()});organizationBrandingSchema.omit({logoUrl:true});var checkTypeEnum=external_exports.enum(["collect_user_info","watchlist","background_us_criminal","background_global","id_verification","custom_form"]);var testHintEnum=external_exports.enum(["pass","review","fail","doc_quality"]);var STEP_ID_REGEX=/^step_[0-9A-Za-z_-]{1,64}$/;var ADDRESS_TEXT_REGEX=/^[^\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069<>]+$/;var safeAddressText=max=>external_exports.string().min(1).max(max).regex(ADDRESS_TEXT_REGEX,"invalid characters");external_exports.object({line1:safeAddressText(120),line2:safeAddressText(120).optional(),city:safeAddressText(80),region:safeAddressText(80).optional(),postalCode:external_exports.string().max(20).regex(/^[A-Za-z0-9 \-]*$/).optional(),country:external_exports.string().length(2).regex(/^[A-Z]{2}$/),placeId:external_exports.string().max(255).regex(/^[A-Za-z0-9_\-:]+$/).optional(),formatted:safeAddressText(500).optional()});var applicantSkipPolicySchema=external_exports.object({minAttemptsBeforeShown:external_exports.number().int().nonnegative().default(0),requireReason:external_exports.boolean().default(false)}).loose();var i18nLabelSchema=external_exports.record(external_exports.string(),external_exports.string());var stepConditionSchema=external_exports.object({field:external_exports.string(),operator:external_exports.enum(["eq","neq","in","not_in"]),value:external_exports.union([external_exports.string(),external_exports.array(external_exports.string())])}).optional();var workflowStepSchema=external_exports.object({checkType:checkTypeEnum,isRequired:external_exports.boolean().default(true),order:external_exports.number().int(),maxAttempts:external_exports.number().int().default(3),condition:stepConditionSchema,label:external_exports.string().optional()});external_exports.array(workflowStepSchema).min(1);var baseStepFields={id:external_exports.string().regex(STEP_ID_REGEX),order:external_exports.number().int().nonnegative(),isRequired:external_exports.boolean().default(true),applicantSkippable:external_exports.boolean().default(false),applicantSkipPolicy:applicantSkipPolicySchema.optional(),maxAttempts:external_exports.number().int().positive().default(3),label:i18nLabelSchema.optional(),description:i18nLabelSchema.optional(),dependsOn:external_exports.array(external_exports.string()).optional(),condition:external_exports.unknown().nullable().optional()};var backgroundConfigSchema=external_exports.object({jurisdictionScope:external_exports.enum(["us","eu","global"]).default("global"),recordTypesIncluded:external_exports.array(external_exports.enum(["criminal","sex_offender","adverse_media"])).min(1).default(["criminal"])}).default({jurisdictionScope:"global",recordTypesIncluded:["criminal"]});var watchlistConfigSchema=external_exports.object({lists:external_exports.array(external_exports.enum(["pep","ofac","eu","un"])).default([]),confidenceThreshold:external_exports.number().min(0).max(1).default(.8)}).default({lists:[],confidenceThreshold:.8});var COLLECT_USER_INFO_FIELDS=["email","phone","dob","address"];var collectUserInfoConfigSchema=external_exports.object({fields:external_exports.preprocess(raw=>{if(!Array.isArray(raw))return raw;return raw.filter(v=>v!=="name")},external_exports.array(external_exports.enum(COLLECT_USER_INFO_FIELDS))).default(["email","phone"]),captureStructuredName:external_exports.boolean().default(false)}).default({fields:["email","phone"],captureStructuredName:false});var idvDocumentTypeEnum=external_exports.enum(IDV_DOCUMENT_TYPES);var idVerificationConfigSchema=external_exports.object({documentTypes:idvDocumentTypeEnum.array().min(1).default([...IDV_DOCUMENT_TYPES]),biometricMode:external_exports.enum(["none","selfie","liveness"]).default("none"),requireMrzMatch:external_exports.boolean().default(false),requireExpiryValid:external_exports.boolean().default(true),requireNameMatch:external_exports.boolean().default(false),documentAuthenticity:external_exports.boolean().default(false),minAge:external_exports.number().int().min(0).max(150).optional()}).strict().default({documentTypes:[...IDV_DOCUMENT_TYPES],biometricMode:"none",requireMrzMatch:false,requireExpiryValid:true,requireNameMatch:false,documentAuthenticity:false});var watchlistStepSchema=external_exports.object({...baseStepFields,type:external_exports.literal("watchlist"),config:watchlistConfigSchema});var backgroundUsCriminalStepSchema=external_exports.object({...baseStepFields,type:external_exports.literal("background_us_criminal"),config:backgroundConfigSchema});var backgroundGlobalStepSchema=external_exports.object({...baseStepFields,type:external_exports.literal("background_global"),config:backgroundConfigSchema});var collectUserInfoStepSchema=external_exports.object({...baseStepFields,type:external_exports.literal("collect_user_info"),config:collectUserInfoConfigSchema});var idVerificationStepSchema=external_exports.object({...baseStepFields,type:external_exports.literal("id_verification"),config:idVerificationConfigSchema});var customFormScreenStepSchema=external_exports.object({...baseStepFields,type:external_exports.literal("custom_form"),config:customFormScreenConfigSchema});external_exports.discriminatedUnion("type",[watchlistStepSchema,backgroundUsCriminalStepSchema,backgroundGlobalStepSchema,collectUserInfoStepSchema,idVerificationStepSchema,customFormScreenStepSchema]);var captureBrandTokensSchema=external_exports.object({primary:hexColorSchema,primaryHover:hexColorSchema,onPrimary:hexColorSchema,secondary:hexColorSchema,onSecondary:hexColorSchema,ring:hexColorSchema}).strict();var captureThemeSchema=external_exports.object({colorMode:external_exports.enum(["light","dark"]),brandTokens:captureBrandTokensSchema.nullable().default(null)}).strict();var captureDocumentSideEnum=external_exports.enum(["front","back"]);var captureDocumentGroupEnum=external_exports.enum(["unknown","dl","id","passport","passport-card","visa"]);var captureErrorCodeEnum=external_exports.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"]);external_exports.enum(["no_face","multiple_faces","too_dark","move_closer","not_centered","hold_still","ready"]);var selfiePromptMapSchema=external_exports.object({no_face:external_exports.string().min(1).max(120).optional(),multiple_faces:external_exports.string().min(1).max(120).optional(),too_dark:external_exports.string().min(1).max(120).optional(),move_closer:external_exports.string().min(1).max(120).optional(),not_centered:external_exports.string().min(1).max(120).optional(),hold_still:external_exports.string().min(1).max(120).optional(),ready:external_exports.string().min(1).max(120).optional()}).strict();var selfieChromeCopySchema=external_exports.object({shutterLabel:external_exports.string().min(1).max(80).optional(),shutterHint:external_exports.string().min(1).max(120).optional(),confirm:external_exports.string().min(1).max(80).optional(),retake:external_exports.string().min(1).max(80).optional()}).strict();var captureInitMessageSchema=external_exports.object({type:external_exports.literal("capture:init"),captureToken:external_exports.string().min(1),config:idVerificationConfigSchema,locale:external_exports.string().min(2).max(35),theme:captureThemeSchema,mode:dataModeEnum.optional(),testHint:testHintEnum.optional(),protocolVersion:external_exports.number().int().min(1).optional(),beginScanPrompt:external_exports.string().min(1).max(200).optional(),beginScanLabel:external_exports.string().min(1).max(80).optional(),selfiePromptMap:selfiePromptMapSchema.optional(),selfieChromeCopy:selfieChromeCopySchema.optional()}).strict();external_exports.object({data:external_exports.object({captureToken:external_exports.string().min(1),embedOrigin:canonicalOriginSchema,runIndex:external_exports.number().int().min(0),expiresAt:external_exports.iso.datetime({offset:true}),embedContextToken:external_exports.string().min(1),mode:dataModeEnum.optional(),testHint:testHintEnum.optional()}).strict()}).strict();var captureReadyMessageSchema=external_exports.object({type:external_exports.literal("capture:ready")}).strict();var captureDocumentCompleteMessageSchema=external_exports.object({type:external_exports.literal("capture:document-complete"),side:captureDocumentSideEnum,r2Key:external_exports.string().min(1)}).strict();var captureSelfieCompleteMessageSchema=external_exports.object({type:external_exports.literal("capture:selfie-complete"),r2Key:external_exports.string().min(1)}).strict();var captureCoachingMessageSchema=external_exports.object({type:external_exports.literal("capture:coaching"),state:external_exports.string().min(1).max(120),attemptIndex:external_exports.number().int().min(0)}).strict();var captureSelfieCvRejectMessageSchema=external_exports.object({type:external_exports.literal("capture:selfie-cv-reject"),retryReason:external_exports.string().min(1).max(120).optional(),attemptIndex:external_exports.number().int().min(0)}).strict();var captureErrorMessageSchema=external_exports.object({type:external_exports.literal("capture:error"),code:captureErrorCodeEnum}).strict();var captureBiometricCameraLiveMessageSchema=external_exports.object({type:external_exports.literal("capture:biometric_camera_live"),timestamp:external_exports.number().optional()}).strict();var idvR2KeysSchema=external_exports.object({front:external_exports.string().min(1),back:external_exports.string().min(1).optional(),selfie:external_exports.string().min(1).optional()}).strict();var captureAllCompleteMessageSchema=external_exports.object({type:external_exports.literal("capture:all-complete"),r2Keys:idvR2KeysSchema,documentGroup:captureDocumentGroupEnum.optional()}).strict();external_exports.object({stepId:external_exports.string().min(1),runIndex:external_exports.number().int().min(0),r2Keys:idvR2KeysSchema,traceId:external_exports.string().optional()}).strict();external_exports.object({stepId:external_exports.string().min(1).optional()}).strict();var idvLivenessStsCredentialsSchema=external_exports.object({accessKeyId:external_exports.string().min(1),secretAccessKey:external_exports.string().min(1),sessionToken:external_exports.string().min(1),expiration:external_exports.string().min(1)}).strict();var livenessAwsRegionEnum=external_exports.enum(LivenessAwsRegions);external_exports.object({awsSessionId:external_exports.string().min(1),awsRegion:livenessAwsRegionEnum,credentials:idvLivenessStsCredentialsSchema}).strict();var captureBehaviorMessageSchema=external_exports.object({type:external_exports.literal("capture:behavior"),steps:external_exports.array(behaviorStepSchema).max(50),traits:behaviorTraitsSchema}).strict();var captureFromIframeMessageSchema=external_exports.discriminatedUnion("type",[captureReadyMessageSchema,captureDocumentCompleteMessageSchema,captureSelfieCompleteMessageSchema,captureCoachingMessageSchema,captureSelfieCvRejectMessageSchema,captureErrorMessageSchema,captureAllCompleteMessageSchema,captureBehaviorMessageSchema,captureBiometricCameraLiveMessageSchema]);external_exports.discriminatedUnion("type",[captureInitMessageSchema]);var idvCvGateRetryReasonEnum=external_exports.enum(["no_face_detected","multiple_faces","low_confidence","no_id_document","image_read_failed"]);external_exports.object({ok:external_exports.boolean(),retryReason:idvCvGateRetryReasonEnum.optional()}).strict();external_exports.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};default:return state}}function nextCapturePhaseAfterDocument(side,documentTypes,biometricMode){if(side==="front"&&documentTypes.some(isTwoSidedDocumentType))return "document_back";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 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 postInit(){if(destroyed||captureToken===null||pinnedOrigin===null)return false;const iframe=deps.getIframe();if(iframe===null||iframe.contentWindow===null)return false;const init={type:"capture:init",captureToken,...deps.initPayload()};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});return}case "capture:all-complete":{void submitCapture(msg.r2Keys);return}case "capture:behavior":{deps.onBehaviorSegment?.({steps:msg.steps,traits:msg.traits});return}case "capture:biometric_camera_live":{dispatch({type:"biometric_camera_live"});return}default:{const _exhaustive=msg;return _exhaustive}}}async function submitCapture(r2Keys){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;try{result=await deps.submit(runIndex,r2Keys);}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;messageListener=onWindowMessage;window.addEventListener("message",messageListener);dispatch({type:"mint_ok",...minted});}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;}}}}
5
-
6
- export { CURRENT_PROTOCOL_VERSION, coachingKindForState, createCaptureController, isBiometricPhase, nextCapturePhaseAfterDocument, reducer };
@@ -1,13 +0,0 @@
1
- import { getModule } from './chunk-GFHNOZVO.js';
2
- import { createChecktivError } from './chunk-OC5N6W7T.js';
3
- import { parsePublishableKey, createWorkingTokenSource, createWorkingTokenManager } from './chunk-EYSE7JJ4.js';
4
- import { resolveSession, warnWrongTokenPlane } from './chunk-7F7ZMYB7.js';
5
- import { assertNever } from './chunk-UBQTPS5J.js';
6
- import { createTokenManager } from './chunk-S2OOEDJS.js';
7
- import { resolveApiBaseOrigin, sdkPublicSettings, shortCodeRefreshPath, PUBLISHABLE_KEY_HEADER, SESSIONS_ME_REFRESH_LINK_PATH } from './chunk-KK66RKPI.js';
8
- import { R, k } from './chunk-XOGHMNBX.js';
9
- import { getServiceOrigin } from './chunk-QFA3K5ZV.js';
10
-
11
- 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}}}function missingModuleMessage(name){return `This session requires the '${name}' module. Import '@checktiv/sdk-web/${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};var STEP_TYPE_TO_VISUAL_MODULE={id_verification:"idv",custom_form:"custom_form"};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})})}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})}})}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 "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}for(const name of session.modules){if(destroyed)return;if(MODULE_IS_VISUAL[name]&&name!==currentStepVisualModule){continue}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,session:{sessionId:session.sessionId,stepId:session.stepId}});}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);}}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}:{},tokens:deps.tokens??createTokenManager(opts.getSessionToken,()=>sessionId),getSessionId:()=>sessionId,setSessionId:id=>{sessionId=id;}};function mount2(...args){if(args[0]==="idv"){const factory2=getModule("idv");if(factory2===void 0)return missingIdvHandle(args[1]);return factory2(ctx,args[1])}if(args[0]==="custom_form"){const factory2=getModule("custom_form");if(factory2===void 0)return missingCustomFormHandle(args[1]);return factory2(ctx,args[1])}const factory=getModule("fraud");if(factory===void 0)return missingFraudHandle(args[1]);return factory(ctx,args[1])}return {mountProvisioned:provOpts=>createMountProvisioned(ctx,provOpts),mount:mount2}}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 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{}}}}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.6.1";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);}function completionSessionId(e){if(e.type!=="checktiv.idv.submitted"&&e.type!=="checktiv.custom_form.submitted"){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 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.onComplete!==void 0||store!==null;const onEvent=needsChannel?e=>{opts.onEvent?.(e);const sessionId=completionSessionId(e);if(sessionId!==null){store?.clear();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 applicantToWire(a){const wire={};if(a.externalId!==void 0)wire.external_id=a.externalId;if(a.email!==void 0)wire.email=a.email;if(a.phone!==void 0)wire.phone=a.phone;if(a.firstName!==void 0)wire.first_name=a.firstName;if(a.middleName!==void 0)wire.middle_name=a.middleName;if(a.lastName!==void 0)wire.last_name=a.lastName;if(a.legalName!==void 0)wire.legal_name=a.legalName;if(a.dateOfBirth!==void 0)wire.date_of_birth=a.dateOfBirth;if(a.address!==void 0)wire.address=a.address;if(a.referenceName!==void 0)wire.reference_name=a.referenceName;return wire}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={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)});const res=await fetchImpl(`${options.apiBase}/v1/sessions`,{method:"POST",headers,body});if(!res.ok){throw new Error(`Checktiv sessions.create failed (status ${res.status}). Verify the apiBase origin and secret key.`)}let parsed;try{parsed=await res.json();}catch{throw new Error("Checktiv sessions.create returned a non-JSON response.")}const clientToken=readCreatedClientToken(parsed);if(clientToken===null){throw new Error("Checktiv sessions.create response carried no client token. Enable the working-token capability for this environment, then retry.")}return {clientToken}}};
12
-
13
- export { init, mount, mountButton, sessions, version };