@checktiv/sdk-web 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Checktiv
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,181 @@
1
+ # @checktiv/sdk-web
2
+
3
+ Customer-embed Web SDK for the Checktiv identity verification platform. Published on
4
+ npm as `@checktiv/sdk-web`; the internal workspace name is `@rf/sdk-web`.
5
+
6
+ Two surfaces ship from this package:
7
+
8
+ - **ESM npm package** (`@checktiv/sdk-web` and subpaths) - tree-shakeable ESM
9
+ modules for bundler-based apps. React peer dependency is optional; `react`/`react-dom`
10
+ are not bundled.
11
+ - **CDN IIFE** (`window.Checktiv`) - the self-contained bundle served by `sdk-cdn`
12
+ at `https://sdk.<region>.<apex>/v1/sdk.js`. Includes all modules eagerly so a single
13
+ `<script>` tag is sufficient. A legacy `window.AutohostKyc` alias is kept for
14
+ existing customer snippets; auto-discover attributes `[data-checktiv]` (preferred)
15
+ and `[data-autohost-kyc]` (back-compat) work on both the CDN and npm paths.
16
+
17
+ ## Install (npm)
18
+
19
+ ```bash
20
+ npm install @checktiv/sdk-web
21
+ # or: pnpm add @checktiv/sdk-web
22
+ ```
23
+
24
+ `react` and `react-dom` are **optional peer dependencies**. Install them only when
25
+ using the `./react` subpath.
26
+
27
+ ## CDN snippet
28
+
29
+ ```html
30
+ <!-- Moving pointer - always the latest release. No SRI: content changes on every release. -->
31
+ <script src="https://sdk.us.checktiv.com/v1/sdk.js" crossorigin="anonymous"></script>
32
+ ```
33
+
34
+ This loads the latest release. SRI is not usable on the moving `/v1/sdk.js` pointer
35
+ because its content changes on every release. For production, pin to the immutable
36
+ versioned URL and include a Subresource Integrity hash from the release notes:
37
+
38
+ ```html
39
+ <script
40
+ src="https://sdk.us.checktiv.com/sdk/1.2.3/sdk.js"
41
+ integrity="sha384-<hash-from-release-notes>"
42
+ crossorigin="anonymous"
43
+ ></script>
44
+ ```
45
+
46
+ ## The two-line surface
47
+
48
+ ```js
49
+ import { init } from '@checktiv/sdk-web';
50
+ import '@checktiv/sdk-web/idv'; // self-registers the IDV module
51
+
52
+ const client = init({
53
+ publishableKey: 'ah_pk_us_test_...',
54
+ getSessionToken: async (ctx) => {
55
+ const res = await fetch('/api/checktiv/token', {
56
+ method: 'POST',
57
+ body: JSON.stringify({ reason: ctx.reason }),
58
+ headers: { 'Content-Type': 'application/json' },
59
+ });
60
+ return (await res.json()).token;
61
+ },
62
+ });
63
+
64
+ // Server-driven: renders whatever modules the session declares.
65
+ client.mountProvisioned({
66
+ target: document.getElementById('checktiv-container'),
67
+ onEvent: (event) => console.log(event),
68
+ });
69
+ ```
70
+
71
+ `init()` never makes a network request. `mountProvisioned()` reads the
72
+ server-declared modules from the session (`GET /sdk/v1/sessions/me`) and renders
73
+ each one. Your secret key never appears in client code.
74
+
75
+ ## Published subpaths
76
+
77
+ All subpaths below are part of the published API
78
+ (`publishConfig.exports` in `package.json`):
79
+
80
+ | Subpath | Purpose |
81
+ | ------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
82
+ | `.` / `@checktiv/sdk-web` | `Checktiv.init(opts)` substrate. Returns a `ChecktivClient`. No Zod at runtime; safe for tree-shaking. |
83
+ | `./idv` | Managed IDV module. Import for its self-registration side effect so `mountProvisioned` / `mount('idv')` can resolve it. |
84
+ | `./fraud` | Consent-gated fraud signal collection. Import for its self-registration side effect. |
85
+ | `./custom-form` | Custom form module (server-authored field definitions). Import for self-registration. |
86
+ | `./custom-form/style.css` | Stylesheet for the custom-form module. `<link>` or `import` this in the host page. |
87
+ | `./react` | React wrapper: `ChecktivProvider`, `useChecktiv()`, `ChecktivIdv`. Requires `react`/`react-dom` peer dependencies. |
88
+ | `./capture` | Headless host-side IDV capture controller (`createCaptureController`). Tier-1 - no default UI. |
89
+ | `./capture-ui` | Batteries-included capture renderer (`mount()`). Tier-2 built on `./capture`. |
90
+ | `./cross-device` | Cross-device QR/copy-link handoff overlay. |
91
+ | `./idv/cross-device` | IDV-specific cross-device wiring. |
92
+ | `./agents` | Machine-readable agent steering manifest (`dist/agents/manifest.json`). |
93
+
94
+ The `./agent` subpath is **workspace-only** (not published) - it is omitted from
95
+ `publishConfig.exports`.
96
+
97
+ ## Back-compat surface
98
+
99
+ The following identifiers are kept for existing customer integrations and will not be
100
+ removed without a major version bump:
101
+
102
+ - `window.AutohostKyc` CDN global alias (alongside `window.Checktiv`)
103
+ - `[data-autohost-kyc]` auto-discover attribute (alongside `[data-checktiv]`)
104
+ - `autohost.kyc.complete` postMessage completion event name
105
+
106
+ ## React usage
107
+
108
+ ```tsx
109
+ import { ChecktivProvider, ChecktivIdv } from '@checktiv/sdk-web/react';
110
+ import '@checktiv/sdk-web/idv'; // register the IDV module
111
+
112
+ export function App() {
113
+ return (
114
+ <ChecktivProvider
115
+ publishableKey="ah_pk_us_test_..."
116
+ getSessionToken={async (ctx) => fetchToken(ctx)}
117
+ >
118
+ <ChecktivIdv onEvent={(e) => console.log(e)} />
119
+ </ChecktivProvider>
120
+ );
121
+ }
122
+ ```
123
+
124
+ See the React guide in the docs for the full SSR-safe / Next.js pattern.
125
+
126
+ ## Architecture notes
127
+
128
+ - **No PII, no private API key in the SDK.** The publishable key is operator config,
129
+ not PII. Your server mints `bt_*` browser tokens; the SDK only ever holds those.
130
+ - **Module-load seam.** The `.` entry does not statically import the IDV or fraud
131
+ modules. Each module self-registers via a top-level side effect when its subpath is
132
+ imported. Without the import, `mount('idv')` fails with a clear `sdk_load_failed`
133
+ error message.
134
+ - **Event surface.** Events are `checktiv.<module>.<name>`. The stream is
135
+ forward-open: do not exhaustively switch on `event.type` - unknown types may be
136
+ added without a major bump.
137
+ - **Bundle budget.** The CDN `sdk.js` is gated at 100 KiB gzip by CI.
138
+
139
+ ## Build
140
+
141
+ ```bash
142
+ pnpm --filter @rf/sdk-web build
143
+ # emits dist/ (ESM) and services/sdk-cdn/public/v1/sdk.js (CDN IIFE)
144
+ ```
145
+
146
+ No sourcemaps ship in the npm tarball or the CDN bundle. Maps are CI-only build
147
+ artifacts (they contain internal module names).
148
+
149
+ ## Bundle size checks
150
+
151
+ ```bash
152
+ pnpm --filter @rf/sdk-web size # CDN sdk.js (100 KiB gate)
153
+ pnpm --filter @rf/sdk-web size:host-capture # capture.js
154
+ pnpm --filter @rf/sdk-web size:host-capture-ui # capture-ui.js
155
+ pnpm --filter @rf/sdk-web size:cross-device # cross-device chunk
156
+ pnpm --filter @rf/sdk-web size:npm # per-entry npm tarball sizes
157
+ ```
158
+
159
+ The canonical gate for CI is `pnpm audit:bundle-sizes` (runs all four budgets).
160
+
161
+ ## Publish validation
162
+
163
+ ```bash
164
+ pnpm --filter @rf/sdk-web validate:publint # publint --strict
165
+ pnpm --filter @rf/sdk-web validate:attw # are the types wrong?
166
+ pnpm --filter @rf/sdk-web validate:tarball # publish-boundary gate
167
+ ```
168
+
169
+ The publish-boundary gate (`scripts/audit-sdk-publish-boundary.mjs`) checks for
170
+ internal `@rf/` specifier leaks, vendor names, internal settings sentinels, and
171
+ dependency hygiene in the packed tarball.
172
+
173
+ ## Testing
174
+
175
+ ```bash
176
+ pnpm --filter @rf/sdk-web test
177
+ pnpm --filter @rf/sdk-web typecheck
178
+ ```
179
+
180
+ Tests run under jsdom. Real camera capture and the CDN IIFE are verified against a
181
+ deployed dev cell before each release.
@@ -0,0 +1,56 @@
1
+ # Integrating @checktiv/sdk-web (AI agent steering)
2
+
3
+ This file steers AI coding agents to integrate @checktiv/sdk-web correctly from a single
4
+ prompt. The machine-readable companion (`manifest.json`, same directory, also resolvable
5
+ via the `@checktiv/sdk-web/agents` export) carries the module composition contract and four
6
+ runnable recipes. Read both.
7
+
8
+ ## Rules
9
+
10
+ 1. **The server mints the session, never the browser.** Your backend calls the public API `POST /v1/sessions` with your secret key (`ah_sk_*`) and receives the session. The secret key is server-only: NEVER put `ah_sk_*` in browser code. To hand control to the frontend, your backend mints a short-lived browser token (`bt_*`) by calling `POST /sdk/v1/sessions/:sessionId/browser-token` with the same `ah_sk_*`; that route returns `{ data: { browserToken, expiresAt, modules, scopes } }`. Only the `bt_*` string crosses to the browser.
11
+
12
+ 2. **Use mountProvisioned as the default path.** Call `Checktiv.init({ ... }).mountProvisioned({ target })`. It reads the server-declared `session.modules` from `GET /sdk/v1/sessions/me` and renders exactly what the server composed, so the server drives composition. `mount('idv')` / `mount('fraud')` is the explicit override / escape hatch, not the first choice.
13
+
14
+ 3. **Completion is not a verdict: trust the signed webhook.** The client event `checktiv.idv.submitted` is terminal-for-capture only; it means the applicant finished the capture step, NOT that they passed. The decision arrives on your server through the signed `kyc.session.*` webhook. Trust the signed webhook as the only outcome anchor; never infer a pass/fail from a client event.
15
+
16
+ 4. **Satisfy each applicant-info requirement once, through any one path.** When a session declares applicant-info requirements (name, date of birth, address, and similar fields), each requirement is satisfied by ANY ONE of the supported collection paths, not by all of them. Supply a field through one path and the SDK treats that requirement as met; do not double-collect the same field. Let the server-declared session decide which fields are required rather than hard-coding a form.
17
+
18
+ 5. **Develop local-first with the synthetic driver.** Use a **test-mode publishable key** (`ah_pk_<region>_test_*`) PLUS the synthetic opt-in. Test mode is selected by the key itself, not by a `mode` property on `init`. A test-mode key without the synthetic option renders a BLANK embed on a local origin because the capture license is domain-bound, whereas the synthetic path runs the full `checktiv.idv.*` flow locally with no camera, no license, and no deployed environment. Ensure your own session-mint backend and token endpoint are running before the SDK calls `getSessionToken`. Build and verify locally with the synthetic driver, then graduate to a deployed environment for real capture and ship through the standard npm / CDN path.
19
+
20
+ 6. **getSessionToken supplies a fresh bt_* on demand.** `getSessionToken` is `string | ((ctx: { sessionId; reason: 'initial' | 'expired' | '401' }) => Promise<string>)`. The SDK calls it on mount and again on expiry or a 401, then retries the failed request once. Always return a freshly minted `bt_*` from your backend; never hold a long-lived credential in the browser. If your callback rejects, the SDK emits `token_expired` with `recovery: 'refresh_session'` and halts cleanly.
21
+
22
+ 7. **Add your frontend origin to the publishable key allowlist first.** Each publishable key carries an origin allowlist that you set in the console / dashboard. Your frontend's origin MUST be on that allowlist before the first mount, or EVERY mount fails with `origin_not_allowed` (the `bt_*` data-plane routes reject an off-allowlist `Origin`). Add your origin to the publishable key allowlist before you integrate.
23
+
24
+ 8. **The SDK adds X-Publishable-Key itself on the customer path.** Pass `publishableKey` to `Checktiv.init(...)` and stop there. On the customer (pk-present) path the managed transport attaches the `X-Publishable-Key` header to its own `bt_*` data-plane calls internally. Do NOT also hand-add an `X-Publishable-Key` header yourself; double-adding it is wrong. (The first-party hosted path used internally by the verify app carries no publishable key and sends none.)
25
+
26
+ 9. **Wire cross-device QR handoff via openCrossDeviceOverlay.** Cross-device handoff is wired via STANDALONE exports from the `@checktiv/sdk-web/idv/cross-device` subpath (NOT via an option on `IdvMountOptions` / `mountProvisioned`). Import: `import { openCrossDeviceOverlay, preloadCrossDeviceChunk } from '@checktiv/sdk-web/idv/cross-device';`
27
+
28
+ `openCrossDeviceOverlay(opts: CrossDeviceOverlayOptions)` opens the overlay. Key fields on `CrossDeviceOverlayOptions`:
29
+ • `target: HTMLElement`: the module's root container element.
30
+ • `onOpenCrossDevice: CrossDeviceHandoffHook`: HOST-supplied mint hook. Type: `() => Promise<{ kind: 'ok'; url: string } | { kind: 'unavailable' }>`. Your host calls its own OTL-mint BFF and returns `{ kind: 'ok', url }` with the journey URL, or `{ kind: 'unavailable' }` if the mint fails. The URL MUST be `https:` (the SDK validates this and collapses `javascript:`, `http:`, and `data:` schemes to `'unavailable'`). The hook is re-callable (the overlay has a "refresh link" affordance); cap re-mints with a per-overlay counter on your host.
31
+ • `copy: CrossDeviceCopy`: host-injected copy map; no hardcoded strings.
32
+ • `isMobile: boolean`: `true` suppresses the QR (same-device scan is circular).
33
+ • `emit: (e: ChecktivIdvEvent) => void`: forward to the host's `onEvent` handler.
34
+ • `onClose?: () => void`: called when the applicant closes the overlay or `destroy()` is called.
35
+
36
+ Returns `CrossDeviceOverlayHandle` with:
37
+ • `setCompleting()`: marks the session completing (phone finished; overlay stays mounted with a waiting label instead of disappearing).
38
+ • `destroy()`: tears down the overlay. Idempotent.
39
+
40
+ `preloadCrossDeviceChunk()`: fire-and-forget preload of the lazy CDN chunk. Call it when the IDV module becomes active to reduce perceived latency on open.
41
+
42
+ Events (both are token-free, NEVER contain the url/OTL/short-code):
43
+ • `checktiv.idv.cross_device_opened`: hook returned `ok`, overlay shown.
44
+ • `checktiv.idv.cross_device_unavailable`: hook returned `unavailable` or URL validation failed.
45
+ There is NO `cross_device_completed` event. Completion is the HOST's responsibility: poll your own `/api/idv/cross-device-status` BFF (returns `{ advanced: boolean }`) and call `window.location.reload()` exactly once when `advanced: true`. The SDK module NEVER writes `window.location`. Use `setCompleting()` on the returned handle before reloading so the overlay shows a completing state rather than disappearing abruptly.
46
+
47
+ The browser SDK CANNOT self-mint: `bt_*` bearers are rejected at the OTL-mint route. The host must own a server-side BFF that holds a `vt_*` cookie (HttpOnly, SameSite=Lax) and calls the sdk-api OTL-mint endpoint to produce the handoff URL.
48
+
49
+ ## Runnable recipes
50
+
51
+ Full, copy-pasteable code for each step is in `manifest.json` under `recipes`:
52
+
53
+ - **(a) Backend: mint a session with your secret key**
54
+ - **(b) Backend: mint a bt_* browser token and hand it to the frontend**
55
+ - **(c) Frontend: init and mountProvisioned**
56
+ - **(d) Backend: verify the signed webhook (HMAC) - the only outcome anchor**
@@ -0,0 +1,101 @@
1
+ {
2
+ "package": "@checktiv/sdk-web",
3
+ "modules": {
4
+ "idv": {
5
+ "scopes": [
6
+ "sessions:me:read",
7
+ "idv:capture-token:mint",
8
+ "idv:steps:submit"
9
+ ],
10
+ "eventNamespace": "checktiv.idv"
11
+ },
12
+ "fraud": {
13
+ "scopes": [
14
+ "sessions:me:read",
15
+ "fraud:signal:capture",
16
+ "telemetry:emit"
17
+ ],
18
+ "eventNamespace": "checktiv.fraud"
19
+ },
20
+ "custom_form": {
21
+ "scopes": [
22
+ "sessions:me:read",
23
+ "custom_form:steps:submit"
24
+ ],
25
+ "eventNamespace": "checktiv.custom_form"
26
+ }
27
+ },
28
+ "rules": [
29
+ {
30
+ "id": "server-mints-the-session",
31
+ "title": "The server mints the session, never the browser",
32
+ "body": "Your backend calls the public API `POST /v1/sessions` with your secret key (`ah_sk_*`) and receives the session. The secret key is server-only: NEVER put `ah_sk_*` in browser code. To hand control to the frontend, your backend mints a short-lived browser token (`bt_*`) by calling `POST /sdk/v1/sessions/:sessionId/browser-token` with the same `ah_sk_*`; that route returns `{ data: { browserToken, expiresAt, modules, scopes } }`. Only the `bt_*` string crosses to the browser."
33
+ },
34
+ {
35
+ "id": "mount-provisioned-is-the-default",
36
+ "title": "Use mountProvisioned as the default path",
37
+ "body": "Call `Checktiv.init({ ... }).mountProvisioned({ target })`. It reads the server-declared `session.modules` from `GET /sdk/v1/sessions/me` and renders exactly what the server composed, so the server drives composition. `mount('idv')` / `mount('fraud')` is the explicit override / escape hatch, not the first choice."
38
+ },
39
+ {
40
+ "id": "completion-is-not-a-verdict",
41
+ "title": "Completion is not a verdict: trust the signed webhook",
42
+ "body": "The client event `checktiv.idv.submitted` is terminal-for-capture only; it means the applicant finished the capture step, NOT that they passed. The decision arrives on your server through the signed `kyc.session.*` webhook. Trust the signed webhook as the only outcome anchor; never infer a pass/fail from a client event."
43
+ },
44
+ {
45
+ "id": "applicant-info-satisfaction",
46
+ "title": "Satisfy each applicant-info requirement once, through any one path",
47
+ "body": "When a session declares applicant-info requirements (name, date of birth, address, and similar fields), each requirement is satisfied by ANY ONE of the supported collection paths, not by all of them. Supply a field through one path and the SDK treats that requirement as met; do not double-collect the same field. Let the server-declared session decide which fields are required rather than hard-coding a form."
48
+ },
49
+ {
50
+ "id": "develop-local-first-synthetic",
51
+ "title": "Develop local-first with the synthetic driver",
52
+ "body": "Use a **test-mode publishable key** (`ah_pk_<region>_test_*`) PLUS the synthetic opt-in. Test mode is selected by the key itself, not by a `mode` property on `init`. A test-mode key without the synthetic option renders a BLANK embed on a local origin because the capture license is domain-bound, whereas the synthetic path runs the full `checktiv.idv.*` flow locally with no camera, no license, and no deployed environment. Ensure your own session-mint backend and token endpoint are running before the SDK calls `getSessionToken`. Build and verify locally with the synthetic driver, then graduate to a deployed environment for real capture and ship through the standard npm / CDN path."
53
+ },
54
+ {
55
+ "id": "get-session-token-refresh-contract",
56
+ "title": "getSessionToken supplies a fresh bt_* on demand",
57
+ "body": "`getSessionToken` is `string | ((ctx: { sessionId; reason: 'initial' | 'expired' | '401' }) => Promise<string>)`. The SDK calls it on mount and again on expiry or a 401, then retries the failed request once. Always return a freshly minted `bt_*` from your backend; never hold a long-lived credential in the browser. If your callback rejects, the SDK emits `token_expired` with `recovery: 'refresh_session'` and halts cleanly."
58
+ },
59
+ {
60
+ "id": "origin-allowlist-prerequisite",
61
+ "title": "Add your frontend origin to the publishable key allowlist first",
62
+ "body": "Each publishable key carries an origin allowlist that you set in the console / dashboard. Your frontend's origin MUST be on that allowlist before the first mount, or EVERY mount fails with `origin_not_allowed` (the `bt_*` data-plane routes reject an off-allowlist `Origin`). Add your origin to the publishable key allowlist before you integrate."
63
+ },
64
+ {
65
+ "id": "sdk-adds-publishable-key-internally",
66
+ "title": "The SDK adds X-Publishable-Key itself on the customer path",
67
+ "body": "Pass `publishableKey` to `Checktiv.init(...)` and stop there. On the customer (pk-present) path the managed transport attaches the `X-Publishable-Key` header to its own `bt_*` data-plane calls internally. Do NOT also hand-add an `X-Publishable-Key` header yourself; double-adding it is wrong. (The first-party hosted path used internally by the verify app carries no publishable key and sends none.)"
68
+ },
69
+ {
70
+ "id": "cross-device-handoff-hook",
71
+ "title": "Wire cross-device QR handoff via openCrossDeviceOverlay",
72
+ "body": "Cross-device handoff is wired via STANDALONE exports from the `@checktiv/sdk-web/idv/cross-device` subpath (NOT via an option on `IdvMountOptions` / `mountProvisioned`). Import: `import { openCrossDeviceOverlay, preloadCrossDeviceChunk } from '@checktiv/sdk-web/idv/cross-device';`\n\n`openCrossDeviceOverlay(opts: CrossDeviceOverlayOptions)` opens the overlay. Key fields on `CrossDeviceOverlayOptions`:\n • `target: HTMLElement`: the module's root container element.\n • `onOpenCrossDevice: CrossDeviceHandoffHook`: HOST-supplied mint hook. Type: `() => Promise<{ kind: 'ok'; url: string } | { kind: 'unavailable' }>`. Your host calls its own OTL-mint BFF and returns `{ kind: 'ok', url }` with the journey URL, or `{ kind: 'unavailable' }` if the mint fails. The URL MUST be `https:` (the SDK validates this and collapses `javascript:`, `http:`, and `data:` schemes to `'unavailable'`). The hook is re-callable (the overlay has a \"refresh link\" affordance); cap re-mints with a per-overlay counter on your host.\n • `copy: CrossDeviceCopy`: host-injected copy map; no hardcoded strings.\n • `isMobile: boolean`: `true` suppresses the QR (same-device scan is circular).\n • `emit: (e: ChecktivIdvEvent) => void`: forward to the host's `onEvent` handler.\n • `onClose?: () => void`: called when the applicant closes the overlay or `destroy()` is called.\n\nReturns `CrossDeviceOverlayHandle` with:\n • `setCompleting()`: marks the session completing (phone finished; overlay stays mounted with a waiting label instead of disappearing).\n • `destroy()`: tears down the overlay. Idempotent.\n\n`preloadCrossDeviceChunk()`: fire-and-forget preload of the lazy CDN chunk. Call it when the IDV module becomes active to reduce perceived latency on open.\n\nEvents (both are token-free, NEVER contain the url/OTL/short-code):\n • `checktiv.idv.cross_device_opened`: hook returned `ok`, overlay shown.\n • `checktiv.idv.cross_device_unavailable`: hook returned `unavailable` or URL validation failed.\nThere is NO `cross_device_completed` event. Completion is the HOST's responsibility: poll your own `/api/idv/cross-device-status` BFF (returns `{ advanced: boolean }`) and call `window.location.reload()` exactly once when `advanced: true`. The SDK module NEVER writes `window.location`. Use `setCompleting()` on the returned handle before reloading so the overlay shows a completing state rather than disappearing abruptly.\n\nThe browser SDK CANNOT self-mint: `bt_*` bearers are rejected at the OTL-mint route. The host must own a server-side BFF that holds a `vt_*` cookie (HttpOnly, SameSite=Lax) and calls the sdk-api OTL-mint endpoint to produce the handoff URL."
73
+ }
74
+ ],
75
+ "recipes": [
76
+ {
77
+ "id": "backend-session-mint",
78
+ "title": "(a) Backend: mint a session with your secret key",
79
+ "language": "ts",
80
+ "code": "// Runs on YOUR server. The secret key reads from an env var, never a literal.\n// POST /v1/sessions on the public API creates the durable verification session.\nconst region = process.env.CHECKTIV_REGION ?? \"us\"; // \"us\" | \"eu\"\nconst res = await fetch(`https://api.${region}.checktiv.com/v1/sessions`, {\n method: 'POST',\n headers: {\n // ah_sk_* is server-only. NEVER expose it to the browser.\n Authorization: `Bearer ${process.env.CHECKTIV_SECRET_KEY}`,\n 'Content-Type': 'application/json',\n },\n // applicant_id MUST start with app_; checks is a non-empty list of check types.\n body: JSON.stringify({ applicant_id: 'app_01abc', checks: ['id_verification'] }),\n});\nconst { data: session } = await res.json();\nreturn session.id; // vs_* - store this server-side, keyed to your user.\n\n// curl equivalent:\n// curl -X POST \"https://api.us.checktiv.com/v1/sessions\" \\\n// -H \"Authorization: Bearer $CHECKTIV_SECRET_KEY\" \\\n// -H \"Content-Type: application/json\" \\\n// -d '{\"applicant_id\":\"app_01abc\",\"checks\":[\"id_verification\"]}'"
81
+ },
82
+ {
83
+ "id": "backend-browser-token-mint",
84
+ "title": "(b) Backend: mint a bt_* browser token and hand it to the frontend",
85
+ "language": "ts",
86
+ "code": "// Your own endpoint that getSessionToken (recipe c) fetches. It mints a\n// fresh, short-lived bt_* for a session you already own server-side and\n// returns ONLY the bt_* string. ah_sk_* never leaves the server.\nimport express from 'express';\nconst app = express();\n\napp.post('/checktiv/browser-token', async (req, res) => {\n // Resolve the session id from YOUR session/auth, not from the client body.\n const sessionId = await resolveSessionIdForUser(req);\n const region = process.env.CHECKTIV_REGION ?? \"us\";\n const minted = await fetch(\n `https://api.${region}.checktiv.com/sdk/v1/sessions/${sessionId}/browser-token`,\n {\n method: 'POST',\n headers: { Authorization: `Bearer ${process.env.CHECKTIV_SECRET_KEY}` },\n },\n );\n const { data } = await minted.json(); // { browserToken, expiresAt, modules, scopes }\n res.json({ browserToken: data.browserToken }); // return only the bt_* string\n});"
87
+ },
88
+ {
89
+ "id": "frontend-init-mount-provisioned",
90
+ "title": "(c) Frontend: init and mountProvisioned",
91
+ "language": "ts",
92
+ "code": "import { init } from '@checktiv/sdk-web';\nimport '@checktiv/sdk-web/idv'; // self-registers the idv module\nimport '@checktiv/sdk-web/fraud'; // import every module mountProvisioned may render\n\n// mountProvisioned renders whatever the server declared in session.modules,\n// so import EVERY module the server can select (idv + fraud). A module the\n// server declares but you did not import surfaces a loud, actionable error.\n// Do NOT add an X-Publishable-Key header anywhere: the SDK attaches it itself.\nconst client = init({\n publishableKey: import.meta.env.PUBLIC_CHECKTIV_PK, // ah_pk_* - safe in the browser\n // Called on mount and on expiry/401. Always return a FRESH bt_* from your backend.\n getSessionToken: async (_ctx) => {\n const r = await fetch('/checktiv/browser-token', { method: 'POST' });\n const { browserToken } = await r.json();\n return browserToken;\n },\n});\n\n// mountProvisioned renders whatever the server declared in session.modules.\nclient.mountProvisioned({ target: document.getElementById('checktiv')! });"
93
+ },
94
+ {
95
+ "id": "webhook-verify-hmac",
96
+ "title": "(d) Backend: verify the signed webhook (HMAC) - the only outcome anchor",
97
+ "language": "ts",
98
+ "code": "// The outcome arrives here, signed. This is the ONLY trust anchor for a verdict.\nimport { createHmac, timingSafeEqual } from 'node:crypto';\n\nconst seen = new Set<string>(); // dedupe store; use a durable store in production.\n\nfunction verifyWebhook(rawBody: string, headers: Headers): boolean {\n // Header: X-Webhook-Signature: t=<unix>,v1=<hex HMAC-SHA-256(secret, `${t}.${rawBody}`)>\n const sig = headers.get('x-webhook-signature') ?? '';\n const parts = Object.fromEntries(\n sig.split(',').map((kv) => kv.split('=') as [string, string]),\n );\n // Reject outside the 300s replay window (the platform enforces it symmetrically).\n if (Math.abs(Date.now() / 1000 - Number(parts.t)) > 300) return false;\n // Compute HMAC over the RAW body bytes - never re-serialized JSON.\n const expected = createHmac('sha256', process.env.CHECKTIV_WEBHOOK_SECRET!)\n .update(`${parts.t}.${rawBody}`)\n .digest('hex');\n const a = Buffer.from(expected, 'hex');\n const b = Buffer.from(parts.v1 ?? '', 'hex');\n if (a.length !== b.length || !timingSafeEqual(a, b)) return false; // constant-time\n // Dedupe on X-Webhook-Id (at-least-once delivery resends the same id).\n const id = headers.get('x-webhook-id') ?? '';\n if (seen.has(id)) return false;\n seen.add(id);\n return true;\n}"
99
+ }
100
+ ]
101
+ }
@@ -0,0 +1 @@
1
+ .idv-capture-frame{display:block;width:100%;max-width:28rem;aspect-ratio:3 / 4;margin:0 auto;border:0;border-radius:0.5rem;background:transparent}.idv-capture-frame--biometric{aspect-ratio:auto;height:min(70dvh,520px)}@media(orientation:landscape){.idv-capture-frame,.idv-capture-frame--biometric{aspect-ratio:auto;height:min(55dvh,380px);width:auto}}.idv-capture-active{position:relative}.idv-capture-skeleton{position:absolute;top:0;left:50%;transform:translateX(-50%);z-index:1;width:100%;max-width:28rem;height:min(70dvh,520px);border-radius:0.5rem;overflow:hidden;background:#e5e7eb}.idv-capture-skeleton[data-color-mode=dark]{background:#1f2937}.idv-capture-skeleton::before{content:"";position:absolute;inset:0;background:linear-gradient(100deg,transparent 30%,rgba(255,255,255,0.22) 50%,transparent 70%);background-size:200% 100%;animation:idv-capture-skeleton-sweep 1.4s ease-in-out infinite}@keyframes idv-capture-skeleton-sweep{from{background-position:200% 0}to{background-position:-200% 0}}@media(prefers-reduced-motion:reduce){.idv-capture-skeleton::before{animation:none}}@media(orientation:landscape){.idv-capture-skeleton{height:min(55dvh,380px)}}
@@ -0,0 +1,16 @@
1
+ import { a as CaptureControllerDeps, b as CaptureEvent } from './controller-C4vJ47JI.js';
2
+ import { e as CaptureState } from './machine--zVZIM4F.js';
3
+ import { M as MountCopy } from './copy-DeUly5vr.js';
4
+ export { T as TerminalKind, f as fallbackCopy } from './copy-DeUly5vr.js';
5
+
6
+ interface MountCaptureOptions extends Omit<CaptureControllerDeps, 'getIframe'> {
7
+ copy: MountCopy;
8
+ onState?: (state: CaptureState) => void;
9
+ onControllerEvent?: (event: CaptureEvent) => void;
10
+ }
11
+ interface MountHandle {
12
+ destroy(): void;
13
+ }
14
+ declare function mount(element: HTMLElement, options: MountCaptureOptions): MountHandle;
15
+
16
+ export { type MountCaptureOptions, MountCopy, type MountHandle, mount };
@@ -0,0 +1,6 @@
1
+ export { fallbackCopy, mount } from './chunk-C7H2ZVQT.js';
2
+ import './chunk-HV2QKVJX.js';
3
+ import './chunk-XOGHMNBX.js';
4
+ import './chunk-TRTAZKYV.js';
5
+ import './chunk-QFA3K5ZV.js';
6
+ import './chunk-AIK7CDV6.js';
@@ -0,0 +1,7 @@
1
+ export { C as CaptureController, a as CaptureControllerDeps, b as CaptureEvent, c as CaptureEventType, S as SubmitResult, d as createCaptureController } from './controller-C4vJ47JI.js';
2
+ import { a as CoachingKind } from './machine--zVZIM4F.js';
3
+ export { b as CaptureAction, c as CaptureErrorKind, d as CapturePhase, e as CaptureState, i as isBiometricPhase, n as nextCapturePhaseAfterDocument, r as reducer } from './machine--zVZIM4F.js';
4
+
5
+ declare function coachingKindForState(state: string): CoachingKind;
6
+
7
+ export { CoachingKind, coachingKindForState };
@@ -0,0 +1,3 @@
1
+ export { coachingKindForState, createCaptureController, isBiometricPhase, nextCapturePhaseAfterDocument, reducer } from './chunk-TRTAZKYV.js';
2
+ import './chunk-QFA3K5ZV.js';
3
+ import './chunk-AIK7CDV6.js';
@@ -0,0 +1,3 @@
1
+ var __defProp=Object.defineProperty;var __defNormalProp=(obj,key,value)=>key in obj?__defProp(obj,key,{enumerable:true,configurable:true,writable:true,value}):obj[key]=value;var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:true});};var __publicField=(obj,key,value)=>__defNormalProp(obj,typeof key!=="symbol"?key+"":key,value);
2
+
3
+ export { __export, __publicField };
@@ -0,0 +1,7 @@
1
+ import { resolveSession } from './chunk-CXNPD67Z.js';
2
+ import { resolveApiBaseOrigin, createTokenManager, getModule } from './chunk-FGWZZNAN.js';
3
+ import { createChecktivError } from './chunk-WQCYRLWP.js';
4
+
5
+ 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)}`}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,onBeforeSubmit:opts.onBeforeSubmit,onBehaviorSegment:opts.onBehaviorSegment,synthetic:opts.synthetic})})}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;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 session=await resolveSession2();if(destroyed)return;if(session===null){emit(moduleErrorFor("idv","session_expired"));return}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,onBeforeSubmit:opts.onBeforeSubmit,onBehaviorSegment:opts.onBehaviorSegment,synthetic:opts.synthetic,customFormConfig:opts.customFormConfig,customFormCopy:opts.customFormCopy,session:{sessionId:session.sessionId,stepId:session.stepId}});}catch(err){containerToRemove?.remove();throw err}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();}}}}function init(opts){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}:{},tokens:createTokenManager(opts.getSessionToken,()=>sessionId),getSessionId:()=>sessionId,setSessionId:id=>{sessionId=id;}};function mount(...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}}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}}
6
+
7
+ export { InvalidPublishableKeyError, init, parsePublishableKey };