@checktiv/sdk-web 1.6.1 → 1.7.1
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 +59 -23
- package/dist/{api-DWWQGjxL.d.ts → api-Cjh51lsw.d.ts} +5 -2
- package/dist/{chunk-CGSNIVQF.js → chunk-CSNKMUIP.js} +1 -1
- package/dist/{chunk-7F7ZMYB7.js → chunk-DRNEDARS.js} +1 -1
- package/dist/chunk-DXW36O3Q.js +13 -0
- package/dist/{chunk-EYSE7JJ4.js → chunk-EXC2ZRUH.js} +1 -1
- package/dist/{chunk-YPYFPHOH.js → chunk-F2BDZRAX.js} +3 -3
- package/dist/chunk-HFQJYEGZ.js +5 -0
- package/dist/chunk-JS3Y6T76.js +3 -0
- package/dist/collect-user-info.d.ts +1 -1
- package/dist/collect-user-info.js +4 -4
- package/dist/custom-form.d.ts +1 -1
- package/dist/custom-form.js +3 -3
- package/dist/fraud.d.ts +1 -1
- package/dist/fraud.js +3 -3
- package/dist/idv/cross-device.d.ts +1 -1
- package/dist/idv/cross-device.js +3 -3
- package/dist/idv.d.ts +1 -1
- package/dist/idv.js +4 -4
- package/dist/{index-B9Gc_xWl.d.ts → index-9vcErEYX.d.ts} +1 -1
- package/dist/index.d.ts +15 -5
- package/dist/index.js +5 -5
- package/dist/react.d.ts +2 -2
- package/dist/react.js +6 -6
- package/dist/workspace.d.ts +1 -1
- package/dist/workspace.js +1 -1
- package/package.json +1 -36
- package/dist/chunk-KK66RKPI.js +0 -5
- package/dist/chunk-OC5N6W7T.js +0 -3
- package/dist/chunk-VUBKYUVM.js +0 -13
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: '
|
|
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: '
|
|
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: '
|
|
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: '
|
|
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: '
|
|
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="
|
|
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="
|
|
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:
|
|
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 {
|
|
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,4 +1,4 @@
|
|
|
1
|
-
import { createChecktivError } from './chunk-
|
|
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
|
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { withTokenRetry } from './chunk-S2OOEDJS.js';
|
|
2
|
-
import { sdkPublicSettings, SESSIONS_ME_PATH, dataPlaneHeaders } from './chunk-
|
|
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"}}
|
|
@@ -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.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 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 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_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,4 +1,4 @@
|
|
|
1
|
-
import { WORKING_TOKEN_MINT_PATH, PUBLISHABLE_KEY_HEADER } from './chunk-
|
|
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"&®ion!=="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-
|
|
2
|
-
import { resolveSession, warnWrongTokenPlane } from './chunk-
|
|
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-
|
|
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,9 +1,9 @@
|
|
|
1
|
-
export { collectUserInfo } from './chunk-
|
|
2
|
-
import './chunk-
|
|
3
|
-
import './chunk-
|
|
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-
|
|
6
|
+
import './chunk-HFQJYEGZ.js';
|
|
7
7
|
import './chunk-IQKHRPJR.js';
|
|
8
8
|
import './chunk-QFA3K5ZV.js';
|
|
9
9
|
import './chunk-AIK7CDV6.js';
|
package/dist/custom-form.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export {
|
|
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';
|
package/dist/custom-form.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { registerModule } from './chunk-GFHNOZVO.js';
|
|
2
|
-
import { createChecktivError, mapHttpStatusToError } from './chunk-
|
|
3
|
-
import { warnWrongTokenPlane, isRecord, isJourneyPlaneBody } from './chunk-
|
|
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-
|
|
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,
|
|
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-
|
|
3
|
-
import { resolveSession, warnWrongTokenPlane } from './chunk-
|
|
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-
|
|
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 {
|
|
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';
|
package/dist/idv/cross-device.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { registerCrossDeviceOpener, createChecktivErrorEvent } from '../chunk-
|
|
2
|
-
import { createChecktivError } from '../chunk-
|
|
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-
|
|
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 {
|
|
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,10 +1,10 @@
|
|
|
1
|
-
import { createChecktivErrorEvent, mapStateToEvent, getCrossDeviceOpener } from './chunk-
|
|
1
|
+
import { createChecktivErrorEvent, mapStateToEvent, getCrossDeviceOpener } from './chunk-CSNKMUIP.js';
|
|
2
2
|
import { registerModule } from './chunk-GFHNOZVO.js';
|
|
3
|
-
import { createChecktivError, mapHttpStatusToError } from './chunk-
|
|
4
|
-
import { resolveSession, warnWrongTokenPlane } from './chunk-
|
|
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-
|
|
7
|
+
import { stepSubmitPath, dataPlaneHeaders, CAPTURE_TOKEN_MINT_PATH, isCanonicalOrigin } from './chunk-HFQJYEGZ.js';
|
|
8
8
|
import { mount } from './chunk-5BFT2P4R.js';
|
|
9
9
|
import './chunk-HV2QKVJX.js';
|
|
10
10
|
import './chunk-XOGHMNBX.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,
|
|
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-
|
|
2
|
-
export { c as ChecktivError, d as ChecktivErrorCode, e as ChecktivEvent, f as ChecktivFraudEvent, g as ChecktivIdvEvent, h as CrossDeviceHandoffHook, F as FraudHandle,
|
|
3
|
-
import { S as SelfServiceResendResult } from './index-
|
|
4
|
-
export { C as ChecktivIdvProps, a as ChecktivJourneyHandle, b as ChecktivJourneyProps, c as ChecktivProviderProps } from './index-
|
|
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-
|
|
1
|
+
export { init, isSessionsCreateError, mount, mountButton, sessions, version } from './chunk-DXW36O3Q.js';
|
|
2
2
|
import './chunk-GFHNOZVO.js';
|
|
3
|
-
import './chunk-
|
|
4
|
-
export { InvalidPublishableKeyError, parsePublishableKey } from './chunk-
|
|
5
|
-
import './chunk-
|
|
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
|
-
|
|
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-
|
|
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-
|
|
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-
|
|
1
|
+
import { mount, init } from './chunk-DXW36O3Q.js';
|
|
2
2
|
import './chunk-GFHNOZVO.js';
|
|
3
|
-
import './chunk-
|
|
4
|
-
import { collectUserInfo } from './chunk-
|
|
5
|
-
import './chunk-
|
|
6
|
-
import './chunk-
|
|
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-
|
|
9
|
+
import './chunk-HFQJYEGZ.js';
|
|
10
10
|
import './chunk-XOGHMNBX.js';
|
|
11
11
|
import './chunk-IQKHRPJR.js';
|
|
12
12
|
import './chunk-QFA3K5ZV.js';
|
package/dist/workspace.d.ts
CHANGED
package/dist/workspace.js
CHANGED
package/package.json
CHANGED
|
@@ -1,18 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@checktiv/sdk-web",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.7.1",
|
|
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",
|
package/dist/chunk-KK66RKPI.js
DELETED
|
@@ -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 };
|
package/dist/chunk-OC5N6W7T.js
DELETED
|
@@ -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 };
|
package/dist/chunk-VUBKYUVM.js
DELETED
|
@@ -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 };
|