@didit-protocol/sdk-web 0.4.0 → 0.5.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.
@@ -0,0 +1,2313 @@
1
+ /**
2
+ * Didit SDK for Web v0.5.1
3
+ * (c) 2026 Didit
4
+ * @license MIT
5
+ */
6
+ import { getDeviceFingerprintPayload, buildFingerprintHeaders, submitEvent } from '@didit-protocol/signals';
7
+ export * from '@didit-protocol/signals';
8
+
9
+ const DEFAULT_CONFIG = {
10
+ zIndex: 9999,
11
+ showCloseButton: true,
12
+ showExitConfirmation: true,
13
+ loggingEnabled: false};
14
+ const CSS_CLASSES = {
15
+ overlay: "didit-modal-overlay",
16
+ container: "didit-modal-container",
17
+ iframe: "didit-verification-iframe",
18
+ closeButton: "didit-close-button",
19
+ closeIcon: "didit-close-icon",
20
+ closeIconLegacy: "didit-close-icon-legacy",
21
+ flowSized: "didit-flow-sized",
22
+ loading: "didit-loading",
23
+ confirmOverlay: "didit-confirm-overlay",
24
+ confirmBox: "didit-confirm-box",
25
+ embedded: "didit-embedded"
26
+ };
27
+ const SDK_VERSION = "0.5.1";
28
+ /**
29
+ * The permissions the verification iframe gets, in a modal and embedded:
30
+ * camera and microphone for capture, clipboard-write for the flow's copy
31
+ * buttons, and digital-credentials-get so the flow can ask a digital ID wallet
32
+ * (Google Wallet) through the W3C Digital Credentials API from inside the iframe.
33
+ */
34
+ const IFRAME_ALLOW = "camera; microphone; fullscreen; autoplay; encrypted-media; geolocation; clipboard-write; digital-credentials-get";
35
+ /** The verification-URL query parameter each camera option is forwarded as. */
36
+ const CAMERA_QUERY_PARAMS = {
37
+ defaultDocumentCamera: "document_camera",
38
+ defaultLivenessCamera: "liveness_camera",
39
+ showDocumentCameraSwitchButton: "document_camera_switch",
40
+ showLivenessCameraSwitchButton: "liveness_camera_switch"
41
+ };
42
+ const CAMERA_LENSES = ["front", "back"];
43
+ /**
44
+ * The verification-URL query parameters that tell the hosted flow how the SDK
45
+ * presents it: `sdk_presentation=modal|embedded` and, in a modal,
46
+ * `sdk_close_button=true|false` (whether the SDK draws its close button over
47
+ * the flow's top bar).
48
+ */
49
+ const PRESENTATION_QUERY_PARAMS = {
50
+ presentation: "sdk_presentation",
51
+ closeButton: "sdk_close_button"
52
+ };
53
+ /**
54
+ * Posted by the hosted flow when it lays itself out for the modal, with
55
+ * `data: { contentHeight, colorScheme?, dir? }`. The modal then grows to the
56
+ * handoff card on a computer and follows the content height in a narrow
57
+ * window. Handled by the modal and never delivered to `onEvent`.
58
+ */
59
+ const LAYOUT_MESSAGE_TYPE = "didit:layout";
60
+ /** Languages the hosted flow lays out right to left. */
61
+ const RTL_LANGUAGES = ["ar", "fa", "he"];
62
+ const languages = [
63
+ "ar",
64
+ "bg",
65
+ "bn",
66
+ "ca",
67
+ "cnr",
68
+ "cs",
69
+ "da",
70
+ "de",
71
+ "el",
72
+ "en",
73
+ "es",
74
+ "et",
75
+ "fa",
76
+ "fi",
77
+ "fr",
78
+ "he",
79
+ "hi",
80
+ "hr",
81
+ "hu",
82
+ "hy",
83
+ "id",
84
+ "it",
85
+ "ja",
86
+ "ka",
87
+ "ko",
88
+ "lt",
89
+ "lv",
90
+ "mk",
91
+ "mn",
92
+ "ms",
93
+ "nl",
94
+ "no",
95
+ "pl",
96
+ "pt-BR",
97
+ "pt",
98
+ "ro",
99
+ "ru",
100
+ "sk",
101
+ "sl",
102
+ "so",
103
+ "sr",
104
+ "sv",
105
+ "th",
106
+ "tr",
107
+ "uk",
108
+ "uz",
109
+ "vi",
110
+ "zh-CN",
111
+ "zh-TW",
112
+ "zh",
113
+ ];
114
+
115
+ class SDKLogger {
116
+ static get isEnabled() {
117
+ return this._enabled;
118
+ }
119
+ static set isEnabled(value) {
120
+ this._enabled = value;
121
+ }
122
+ static log(...args) {
123
+ if (this._enabled) {
124
+ console.log("[DiditSDK]", ...args);
125
+ }
126
+ }
127
+ static warn(...args) {
128
+ if (this._enabled) {
129
+ console.warn("[DiditSDK]", ...args);
130
+ }
131
+ }
132
+ static error(...args) {
133
+ if (this._enabled) {
134
+ console.error("[DiditSDK]", ...args);
135
+ }
136
+ }
137
+ }
138
+ SDKLogger._enabled = false;
139
+ function generateModalId() {
140
+ return `didit-modal-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
141
+ }
142
+ function isAllowedOrigin(origin, url) {
143
+ try {
144
+ const originURL = new URL(origin);
145
+ const urlURL = new URL(url);
146
+ return originURL.hostname.endsWith(".didit.me") || originURL.hostname === urlURL.hostname;
147
+ }
148
+ catch {
149
+ return false;
150
+ }
151
+ }
152
+ function createVerificationError(type, customMessage) {
153
+ const messages = {
154
+ sessionExpired: "Your verification session has expired.",
155
+ networkError: "A network error occurred. Please try again.",
156
+ cameraAccessDenied: "Camera access is required for verification.",
157
+ unknown: customMessage || "An unknown error occurred."
158
+ };
159
+ return {
160
+ type,
161
+ message: customMessage || messages[type]
162
+ };
163
+ }
164
+ function isCameraLens(value) {
165
+ return CAMERA_LENSES.includes(value);
166
+ }
167
+ const CAMERA_LENS_OPTIONS = ["defaultDocumentCamera", "defaultLivenessCamera"];
168
+ const CAMERA_SWITCH_OPTIONS = ["showDocumentCameraSwitchButton", "showLivenessCameraSwitchButton"];
169
+ /**
170
+ * The URL the verification iframe loads: the integrator's URL with the
171
+ * configuration options the hosted page reads from its query string.
172
+ *
173
+ * The camera options (the same four the native SDKs expose) become query
174
+ * parameters: `defaultDocumentCamera` -> `document_camera=<lens>`,
175
+ * `defaultLivenessCamera` -> `liveness_camera=<lens>`,
176
+ * `showDocumentCameraSwitchButton` -> `document_camera_switch=true|false`,
177
+ * `showLivenessCameraSwitchButton` -> `liveness_camera_switch=true|false`.
178
+ * How the SDK presents the flow is always added: `sdk_presentation=modal|embedded`
179
+ * and, in a modal, `sdk_close_button=true|false`.
180
+ * Each parameter is set (not appended) so the configuration wins over a value
181
+ * already on the URL; existing query parameters and the hash are kept. A
182
+ * value of the wrong shape is ignored with a warning rather than forwarded,
183
+ * and a URL the browser cannot parse is returned as it came (the modal
184
+ * reports it when it loads).
185
+ */
186
+ function buildVerificationUrl(url, configuration = {}) {
187
+ const params = presentationParams(configuration);
188
+ for (const option of CAMERA_LENS_OPTIONS) {
189
+ const value = configuration[option];
190
+ if (value === undefined)
191
+ continue;
192
+ if (!isCameraLens(value)) {
193
+ SDKLogger.warn(`Ignoring ${option}: expected "front" or "back", got`, value);
194
+ continue;
195
+ }
196
+ params.push([CAMERA_QUERY_PARAMS[option], value]);
197
+ }
198
+ for (const option of CAMERA_SWITCH_OPTIONS) {
199
+ const value = configuration[option];
200
+ if (value === undefined)
201
+ continue;
202
+ if (typeof value !== "boolean") {
203
+ SDKLogger.warn(`Ignoring ${option}: expected a boolean, got`, value);
204
+ continue;
205
+ }
206
+ params.push([CAMERA_QUERY_PARAMS[option], value ? "true" : "false"]);
207
+ }
208
+ try {
209
+ const parsed = new URL(url);
210
+ params.forEach(([name, value]) => parsed.searchParams.set(name, value));
211
+ return parsed.toString();
212
+ }
213
+ catch {
214
+ return url;
215
+ }
216
+ }
217
+ function presentationParams(configuration) {
218
+ if (configuration.embedded) {
219
+ return [[PRESENTATION_QUERY_PARAMS.presentation, "embedded"]];
220
+ }
221
+ const closeButton = configuration.showCloseButton ?? DEFAULT_CONFIG.showCloseButton;
222
+ return [
223
+ [PRESENTATION_QUERY_PARAMS.presentation, "modal"],
224
+ [PRESENTATION_QUERY_PARAMS.closeButton, closeButton ? "true" : "false"]
225
+ ];
226
+ }
227
+ function isRtlLanguage(language) {
228
+ return RTL_LANGUAGES.includes(language.split("-")[0]);
229
+ }
230
+ function detectLanguageFromUrl(url) {
231
+ try {
232
+ const { pathname } = new URL(url);
233
+ const firstSegment = pathname.split("/").filter(Boolean)[0];
234
+ if (firstSegment && languages.includes(firstSegment)) {
235
+ return firstSegment;
236
+ }
237
+ }
238
+ catch {
239
+ // we get it from the browser
240
+ }
241
+ const browserLang = navigator.language;
242
+ if (languages.includes(browserLang))
243
+ return browserLang;
244
+ const baseLang = browserLang.split("-")[0];
245
+ if (languages.includes(baseLang))
246
+ return baseLang;
247
+ return "en";
248
+ }
249
+
250
+ const EN = {
251
+ exitTitle: "Exit verification?",
252
+ exitMessage: "Exiting will end your verification process. Are you sure?",
253
+ continueButton: "Continue",
254
+ exitButton: "Exit",
255
+ ariaLabelModal: "Didit Verification",
256
+ ariaLabelClose: "Close verification"
257
+ };
258
+ const translationsMap = {
259
+ ar: {
260
+ exitTitle: "الخروج من التحقق؟",
261
+ exitMessage: "سيؤدي الخروج إلى إنهاء عملية التحقق الخاصة بك. هل أنت متأكد؟",
262
+ continueButton: "متابعة",
263
+ exitButton: "خروج",
264
+ ariaLabelModal: "التحقق من Didit",
265
+ ariaLabelClose: "إغلاق التحقق"
266
+ },
267
+ bg: {
268
+ exitTitle: "Излизане от верификацията?",
269
+ exitMessage: "Излизането ще прекрати процеса на верификация. Сигурни ли сте?",
270
+ continueButton: "Продължи",
271
+ exitButton: "Изход",
272
+ ariaLabelModal: "Верификация Didit",
273
+ ariaLabelClose: "Затваряне на верификацията"
274
+ },
275
+ bn: {
276
+ exitTitle: "যাচাইকরণ থেকে বের হবেন?",
277
+ exitMessage: "বের হলে আপনার যাচাইকরণ প্রক্রিয়া শেষ হয়ে যাবে। আপনি কি নিশ্চিত?",
278
+ continueButton: "চালিয়ে যান",
279
+ exitButton: "বের হন",
280
+ ariaLabelModal: "Didit যাচাইকরণ",
281
+ ariaLabelClose: "যাচাইকরণ বন্ধ করুন"
282
+ },
283
+ bs: {
284
+ exitTitle: "Izaći iz verifikacije?",
285
+ exitMessage: "Izlaskom ćete prekinuti proces verifikacije. Jeste li sigurni?",
286
+ continueButton: "Nastavi",
287
+ exitButton: "Izađi",
288
+ ariaLabelModal: "Didit verifikacija",
289
+ ariaLabelClose: "Zatvori verifikaciju"
290
+ },
291
+ ca: {
292
+ exitTitle: "Sortir de la verificació?",
293
+ exitMessage: "Sortir finalitzarà el procés de verificació. N'esteu segur?",
294
+ continueButton: "Continua",
295
+ exitButton: "Sortir",
296
+ ariaLabelModal: "Verificació Didit",
297
+ ariaLabelClose: "Tancar verificació"
298
+ },
299
+ cnr: {
300
+ exitTitle: "Izaći iz verifikacije?",
301
+ exitMessage: "Izlaskom ćete prekinuti proces verifikacije. Jeste li sigurni?",
302
+ continueButton: "Nastavi",
303
+ exitButton: "Izađi",
304
+ ariaLabelModal: "Didit verifikacija",
305
+ ariaLabelClose: "Zatvori verifikaciju"
306
+ },
307
+ cs: {
308
+ exitTitle: "Opravdu chcete odejít?",
309
+ exitMessage: "Když odejdete, proces ověření se přeruší. Opravdu chcete skončit?",
310
+ continueButton: "Zůstat",
311
+ exitButton: "Odejít",
312
+ ariaLabelModal: "Ověření Didit",
313
+ ariaLabelClose: "Zavřít ověření"
314
+ },
315
+ da: {
316
+ exitTitle: "Forlad verifikation?",
317
+ exitMessage: "Hvis du forlader, afsluttes din verifikationsproces. Er du sikker?",
318
+ continueButton: "Fortsæt",
319
+ exitButton: "Forlad",
320
+ ariaLabelModal: "Didit-verifikation",
321
+ ariaLabelClose: "Luk verifikation"
322
+ },
323
+ de: {
324
+ exitTitle: "Verifizierung verlassen?",
325
+ exitMessage: "Das Verlassen beendet Ihren Verifizierungsprozess. Sind Sie sicher?",
326
+ continueButton: "Fortfahren",
327
+ exitButton: "Verlassen",
328
+ ariaLabelModal: "Didit-Verifizierung",
329
+ ariaLabelClose: "Verifizierung schließen"
330
+ },
331
+ el: {
332
+ exitTitle: "Έξοδος από την επαλήθευση;",
333
+ exitMessage: "Η έξοδος θα τερματίσει τη διαδικασία επαλήθευσης. Είστε σίγουροι;",
334
+ continueButton: "Συνέχεια",
335
+ exitButton: "Έξοδος",
336
+ ariaLabelModal: "Επαλήθευση Didit",
337
+ ariaLabelClose: "Κλείσιμο επαλήθευσης"
338
+ },
339
+ en: EN,
340
+ es: {
341
+ exitTitle: "¿Salir de la verificación?",
342
+ exitMessage: "Salir terminará tu proceso de verificación. ¿Estás seguro?",
343
+ continueButton: "Continuar",
344
+ exitButton: "Salir",
345
+ ariaLabelModal: "Verificación Didit",
346
+ ariaLabelClose: "Cerrar verificación"
347
+ },
348
+ et: {
349
+ exitTitle: "Lahkuda kinnitamisest?",
350
+ exitMessage: "Lahkumine lõpetab teie kinnitamisprotsessi. Kas olete kindel?",
351
+ continueButton: "Jätka",
352
+ exitButton: "Lahku",
353
+ ariaLabelModal: "Didit kinnitus",
354
+ ariaLabelClose: "Sulge kinnitus"
355
+ },
356
+ fa: {
357
+ exitTitle: "خروج از تأیید هویت؟",
358
+ exitMessage: "خروج باعث پایان فرآیند تأیید هویت شما می‌شود. آیا مطمئن هستید؟",
359
+ continueButton: "ادامه",
360
+ exitButton: "خروج",
361
+ ariaLabelModal: "تأیید هویت Didit",
362
+ ariaLabelClose: "بستن تأیید هویت"
363
+ },
364
+ fi: {
365
+ exitTitle: "Poistu vahvistuksesta?",
366
+ exitMessage: "Poistuminen päättää vahvistusprosessisi. Oletko varma?",
367
+ continueButton: "Jatka",
368
+ exitButton: "Poistu",
369
+ ariaLabelModal: "Didit-vahvistus",
370
+ ariaLabelClose: "Sulje vahvistus"
371
+ },
372
+ fr: {
373
+ exitTitle: "Quitter la vérification ?",
374
+ exitMessage: "Quitter mettra fin à votre processus de vérification. Êtes-vous sûr ?",
375
+ continueButton: "Continuer",
376
+ exitButton: "Quitter",
377
+ ariaLabelModal: "Vérification Didit",
378
+ ariaLabelClose: "Fermer la vérification"
379
+ },
380
+ he: {
381
+ exitTitle: "לצאת מהאימות?",
382
+ exitMessage: "יציאה תסיים את תהליך האימות שלך. האם אתה בטוח?",
383
+ continueButton: "המשך",
384
+ exitButton: "יציאה",
385
+ ariaLabelModal: "אימות Didit",
386
+ ariaLabelClose: "סגירת אימות"
387
+ },
388
+ hi: {
389
+ exitTitle: "सत्यापन से बाहर निकलें?",
390
+ exitMessage: "बाहर निकलने से आपकी सत्यापन प्रक्रिया समाप्त हो जाएगी। क्या आप सुनिश्चित हैं?",
391
+ continueButton: "जारी रखें",
392
+ exitButton: "बाहर निकलें",
393
+ ariaLabelModal: "Didit सत्यापन",
394
+ ariaLabelClose: "सत्यापन बंद करें"
395
+ },
396
+ hr: {
397
+ exitTitle: "Izaći iz verifikacije?",
398
+ exitMessage: "Izlaskom ćete prekinuti proces verifikacije. Jeste li sigurni?",
399
+ continueButton: "Nastavi",
400
+ exitButton: "Izađi",
401
+ ariaLabelModal: "Didit verifikacija",
402
+ ariaLabelClose: "Zatvori verifikaciju"
403
+ },
404
+ hu: {
405
+ exitTitle: "Kilépés az ellenőrzésből?",
406
+ exitMessage: "A kilépés befejezi az ellenőrzési folyamatot. Biztos benne?",
407
+ continueButton: "Folytatás",
408
+ exitButton: "Kilépés",
409
+ ariaLabelModal: "Didit ellenőrzés",
410
+ ariaLabelClose: "Ellenőrzés bezárása"
411
+ },
412
+ hy: {
413
+ exitTitle: "Դուրս գա՞լ ստուգումից",
414
+ exitMessage: "Դուրս գալը կավարտի ձեր ստուգման գործընթացը։ Համոզված ե՞ք?",
415
+ continueButton: "Շարունակել",
416
+ exitButton: "Դուրս գալ",
417
+ ariaLabelModal: "Didit ստուգում",
418
+ ariaLabelClose: "Փակել ստուգումը"
419
+ },
420
+ id: {
421
+ exitTitle: "Keluar dari verifikasi?",
422
+ exitMessage: "Keluar akan mengakhiri proses verifikasi Anda. Apakah Anda yakin?",
423
+ continueButton: "Lanjutkan",
424
+ exitButton: "Keluar",
425
+ ariaLabelModal: "Verifikasi Didit",
426
+ ariaLabelClose: "Tutup verifikasi"
427
+ },
428
+ it: {
429
+ exitTitle: "Uscire dalla verifica?",
430
+ exitMessage: "L'uscita terminerà il processo di verifica. Sei sicuro?",
431
+ continueButton: "Continua",
432
+ exitButton: "Esci",
433
+ ariaLabelModal: "Verifica Didit",
434
+ ariaLabelClose: "Chiudi verifica"
435
+ },
436
+ ja: {
437
+ exitTitle: "認証を終了しますか?",
438
+ exitMessage: "終了すると認証プロセスが中断されます。よろしいですか?",
439
+ continueButton: "続ける",
440
+ exitButton: "終了",
441
+ ariaLabelModal: "Didit 認証",
442
+ ariaLabelClose: "認証を閉じる"
443
+ },
444
+ ka: {
445
+ exitTitle: "გამოსვლა შემოწმებიდან?",
446
+ exitMessage: "გამოსვლა დაასრულებს თქვენს შემოწმების პროცესს. დარწმუნებული ხართ?",
447
+ continueButton: "გაგრძელება",
448
+ exitButton: "გამოსვლა",
449
+ ariaLabelModal: "Didit შემოწმება",
450
+ ariaLabelClose: "შემოწმების დახურვა"
451
+ },
452
+ kk: {
453
+ exitTitle: "Растаудан шығасыз ба?",
454
+ exitMessage: "Шығу растау процесін аяқтайды. Сенімдісіз бе?",
455
+ continueButton: "Жалғастыру",
456
+ exitButton: "Шығу",
457
+ ariaLabelModal: "Didit растауы",
458
+ ariaLabelClose: "Растауды жабу"
459
+ },
460
+ ko: {
461
+ exitTitle: "인증을 종료하시겠습니까?",
462
+ exitMessage: "종료하면 인증 절차가 중단됩니다. 확실하십니까?",
463
+ continueButton: "계속",
464
+ exitButton: "종료",
465
+ ariaLabelModal: "Didit 인증",
466
+ ariaLabelClose: "인증 닫기"
467
+ },
468
+ ky: {
469
+ exitTitle: "Текшерүүдөн чыгасызбы?",
470
+ exitMessage: "Чыгуу текшерүү процессин токтотот. Ишенесизби?",
471
+ continueButton: "Улантуу",
472
+ exitButton: "Чыгуу",
473
+ ariaLabelModal: "Didit текшерүүсү",
474
+ ariaLabelClose: "Текшерүүнү жабуу"
475
+ },
476
+ lt: {
477
+ exitTitle: "Išeiti iš patvirtinimo?",
478
+ exitMessage: "Išėjimas nutrauks jūsų patvirtinimo procesą. Ar esate tikri?",
479
+ continueButton: "Tęsti",
480
+ exitButton: "Išeiti",
481
+ ariaLabelModal: "Didit patvirtinimas",
482
+ ariaLabelClose: "Uždaryti patvirtinimą"
483
+ },
484
+ lv: {
485
+ exitTitle: "Iziet no verifikācijas?",
486
+ exitMessage: "Iziešana pārtrauks jūsu verifikācijas procesu. Vai esat pārliecināts?",
487
+ continueButton: "Turpināt",
488
+ exitButton: "Iziet",
489
+ ariaLabelModal: "Didit verifikācija",
490
+ ariaLabelClose: "Aizvērt verifikāciju"
491
+ },
492
+ mk: {
493
+ exitTitle: "Излези од верификацијата?",
494
+ exitMessage: "Излегувањето ќе го прекине процесот на верификација. Дали сте сигурни?",
495
+ continueButton: "Продолжи",
496
+ exitButton: "Излези",
497
+ ariaLabelModal: "Верификација Didit",
498
+ ariaLabelClose: "Затвори верификација"
499
+ },
500
+ mn: {
501
+ exitTitle: "Баталгаажуулалтаас гарах уу?",
502
+ exitMessage: "Гарвал таны баталгаажуулалтын процесс дуусна. Та итгэлтэй байна уу?",
503
+ continueButton: "Үргэлжлүүлэх",
504
+ exitButton: "Гарах",
505
+ ariaLabelModal: "Didit баталгаажуулалт",
506
+ ariaLabelClose: "Баталгаажуулалтыг хаах"
507
+ },
508
+ ms: {
509
+ exitTitle: "Keluar dari pengesahan?",
510
+ exitMessage: "Keluar akan menamatkan proses pengesahan anda. Adakah anda pasti?",
511
+ continueButton: "Teruskan",
512
+ exitButton: "Keluar",
513
+ ariaLabelModal: "Pengesahan Didit",
514
+ ariaLabelClose: "Tutup pengesahan"
515
+ },
516
+ nl: {
517
+ exitTitle: "Verificatie verlaten?",
518
+ exitMessage: "Verlaten beëindigt uw verificatieproces. Weet u het zeker?",
519
+ continueButton: "Doorgaan",
520
+ exitButton: "Verlaten",
521
+ ariaLabelModal: "Didit-verificatie",
522
+ ariaLabelClose: "Verificatie sluiten"
523
+ },
524
+ no: {
525
+ exitTitle: "Forlat verifisering?",
526
+ exitMessage: "Å forlate vil avslutte verifiseringsprosessen. Er du sikker?",
527
+ continueButton: "Fortsett",
528
+ exitButton: "Forlat",
529
+ ariaLabelModal: "Didit-verifisering",
530
+ ariaLabelClose: "Lukk verifisering"
531
+ },
532
+ pl: {
533
+ exitTitle: "Czy wyjść z weryfikacji?",
534
+ exitMessage: "Wyjście zakończy proces weryfikacji. Czy na pewno?",
535
+ continueButton: "Kontynuuj",
536
+ exitButton: "Wyjdź",
537
+ ariaLabelModal: "Weryfikacja Didit",
538
+ ariaLabelClose: "Zamknij weryfikację"
539
+ },
540
+ "pt-BR": {
541
+ exitTitle: "Sair da verificação?",
542
+ exitMessage: "Sair encerrará seu processo de verificação. Tem certeza?",
543
+ continueButton: "Continuar",
544
+ exitButton: "Sair",
545
+ ariaLabelModal: "Verificação Didit",
546
+ ariaLabelClose: "Fechar verificação"
547
+ },
548
+ pt: {
549
+ exitTitle: "Sair da verificação?",
550
+ exitMessage: "Sair terminará o seu processo de verificação. Tem a certeza?",
551
+ continueButton: "Continuar",
552
+ exitButton: "Sair",
553
+ ariaLabelModal: "Verificação Didit",
554
+ ariaLabelClose: "Fechar verificação"
555
+ },
556
+ ro: {
557
+ exitTitle: "Ieși din verificare?",
558
+ exitMessage: "Ieșirea va încheia procesul de verificare. Ești sigur?",
559
+ continueButton: "Continuă",
560
+ exitButton: "Ieși",
561
+ ariaLabelModal: "Verificare Didit",
562
+ ariaLabelClose: "Închide verificarea"
563
+ },
564
+ ru: {
565
+ exitTitle: "Выйти из верификации?",
566
+ exitMessage: "Выход завершит процесс верификации. Вы уверены?",
567
+ continueButton: "Продолжить",
568
+ exitButton: "Выйти",
569
+ ariaLabelModal: "Верификация Didit",
570
+ ariaLabelClose: "Закрыть верификацию"
571
+ },
572
+ sk: {
573
+ exitTitle: "Opustiť overenie?",
574
+ exitMessage: "Odchodom ukončíte proces overenia. Ste si istí?",
575
+ continueButton: "Pokračovať",
576
+ exitButton: "Odísť",
577
+ ariaLabelModal: "Overenie Didit",
578
+ ariaLabelClose: "Zavrieť overenie"
579
+ },
580
+ sl: {
581
+ exitTitle: "Zapustiti preverjanje?",
582
+ exitMessage: "Izhod bo prekinil postopek preverjanja. Ali ste prepričani?",
583
+ continueButton: "Nadaljuj",
584
+ exitButton: "Izhod",
585
+ ariaLabelModal: "Preverjanje Didit",
586
+ ariaLabelClose: "Zapri preverjanje"
587
+ },
588
+ so: {
589
+ exitTitle: "Ka baxdo xaqiijinta?",
590
+ exitMessage: "Ka bixitaanku wuxuu dhammayn doonaa habka xaqiijintaada. Ma hubtaa?",
591
+ continueButton: "Sii wad",
592
+ exitButton: "Ka bax",
593
+ ariaLabelModal: "Xaqiijinta Didit",
594
+ ariaLabelClose: "Xir xaqiijinta"
595
+ },
596
+ sq: {
597
+ exitTitle: "Dilni nga verifikimi?",
598
+ exitMessage: "Dalja do të përfundojë procesin tuaj të verifikimit. A jeni të sigurt?",
599
+ continueButton: "Vazhdo",
600
+ exitButton: "Dil",
601
+ ariaLabelModal: "Verifikimi Didit",
602
+ ariaLabelClose: "Mbyll verifikimin"
603
+ },
604
+ sr: {
605
+ exitTitle: "Изаћи из верификације?",
606
+ exitMessage: "Изласком ћете прекинути процес верификације. Да ли сте сигурни?",
607
+ continueButton: "Настави",
608
+ exitButton: "Изађи",
609
+ ariaLabelModal: "Верификација Didit",
610
+ ariaLabelClose: "Затвори верификацију"
611
+ },
612
+ sv: {
613
+ exitTitle: "Lämna verifiering?",
614
+ exitMessage: "Att lämna avslutar din verifieringsprocess. Är du säker?",
615
+ continueButton: "Fortsätt",
616
+ exitButton: "Lämna",
617
+ ariaLabelModal: "Didit-verifiering",
618
+ ariaLabelClose: "Stäng verifiering"
619
+ },
620
+ th: {
621
+ exitTitle: "ออกจากการยืนยันตัวตน?",
622
+ exitMessage: "การออกจะสิ้นสุดกระบวนการยืนยันตัวตนของคุณ คุณแน่ใจหรือไม่?",
623
+ continueButton: "ดำเนินการต่อ",
624
+ exitButton: "ออก",
625
+ ariaLabelModal: "การยืนยันตัวตน Didit",
626
+ ariaLabelClose: "ปิดการยืนยันตัวตน"
627
+ },
628
+ tr: {
629
+ exitTitle: "Doğrulamadan çıkmak istiyor musunuz?",
630
+ exitMessage: "Çıkış, doğrulama sürecinizi sonlandıracak. Emin misiniz?",
631
+ continueButton: "Devam et",
632
+ exitButton: "Çıkış",
633
+ ariaLabelModal: "Didit doğrulama",
634
+ ariaLabelClose: "Doğrulamayı kapat"
635
+ },
636
+ uk: {
637
+ exitTitle: "Вийти з верифікації?",
638
+ exitMessage: "Вихід завершить процес верифікації. Ви впевнені?",
639
+ continueButton: "Продовжити",
640
+ exitButton: "Вийти",
641
+ ariaLabelModal: "Верифікація Didit",
642
+ ariaLabelClose: "Закрити верифікацію"
643
+ },
644
+ uz: {
645
+ exitTitle: "Tekshiruvdan chiqasizmi?",
646
+ exitMessage: "Chiqish tekshiruv jarayonini tugatadi. Ishonchingiz komilmi?",
647
+ continueButton: "Davom etish",
648
+ exitButton: "Chiqish",
649
+ ariaLabelModal: "Didit tekshiruvi",
650
+ ariaLabelClose: "Tekshiruvni yopish"
651
+ },
652
+ vi: {
653
+ exitTitle: "Thoát khỏi xác minh?",
654
+ exitMessage: "Thoát sẽ kết thúc quá trình xác minh của bạn. Bạn có chắc không?",
655
+ continueButton: "Tiếp tục",
656
+ exitButton: "Thoát",
657
+ ariaLabelModal: "Xác minh Didit",
658
+ ariaLabelClose: "Đóng xác minh"
659
+ },
660
+ "zh-CN": {
661
+ exitTitle: "退出验证?",
662
+ exitMessage: "退出将结束您的验证流程。确定要退出吗?",
663
+ continueButton: "继续",
664
+ exitButton: "退出",
665
+ ariaLabelModal: "Didit 验证",
666
+ ariaLabelClose: "关闭验证"
667
+ },
668
+ "zh-TW": {
669
+ exitTitle: "退出驗證?",
670
+ exitMessage: "退出將結束您的驗證流程。確定要退出嗎?",
671
+ continueButton: "繼續",
672
+ exitButton: "退出",
673
+ ariaLabelModal: "Didit 驗證",
674
+ ariaLabelClose: "關閉驗證"
675
+ },
676
+ zh: {
677
+ exitTitle: "退出验证?",
678
+ exitMessage: "退出将结束您的验证流程。确定要退出吗?",
679
+ continueButton: "继续",
680
+ exitButton: "退出",
681
+ ariaLabelModal: "Didit 验证",
682
+ ariaLabelClose: "关闭验证"
683
+ }
684
+ };
685
+ function getTranslations(language) {
686
+ return translationsMap[language] ?? EN;
687
+ }
688
+
689
+ class VerificationModal {
690
+ constructor(configuration, callbacks) {
691
+ this.state = {
692
+ isOpen: false,
693
+ isLoading: true,
694
+ showConfirmation: false
695
+ };
696
+ this.overlay = null;
697
+ this.container = null;
698
+ this.iframe = null;
699
+ this.loadingEl = null;
700
+ this.confirmOverlay = null;
701
+ this.confirmationTrigger = null;
702
+ this.boundHandleMessage = null;
703
+ this.boundHandleKeydown = null;
704
+ this.boundHandleFocusChange = null;
705
+ this.confirmationFocusTimeout = null;
706
+ this.embedded = false;
707
+ this.embeddedContainer = null;
708
+ this.language = "en";
709
+ /** body.style.overflow value observed right before this modal locked scroll, restored on close(). */
710
+ this.previousBodyOverflow = null;
711
+ this.modalId = generateModalId();
712
+ this.config = {
713
+ zIndex: configuration?.zIndex ?? DEFAULT_CONFIG.zIndex,
714
+ showCloseButton: configuration?.showCloseButton ?? DEFAULT_CONFIG.showCloseButton,
715
+ showExitConfirmation: configuration?.showExitConfirmation ?? DEFAULT_CONFIG.showExitConfirmation
716
+ };
717
+ this.callbacks = callbacks;
718
+ this.containerElement = configuration?.containerElement ?? document.body;
719
+ this.embedded = configuration?.embedded ?? false;
720
+ if (this.embedded && configuration?.embeddedContainerId) {
721
+ this.embeddedContainer = document.getElementById(configuration.embeddedContainerId);
722
+ }
723
+ }
724
+ injectStyles() {
725
+ const styleId = "didit-sdk-styles";
726
+ if (document.getElementById(styleId)) {
727
+ return;
728
+ }
729
+ const styles = document.createElement("style");
730
+ styles.id = styleId;
731
+ styles.textContent = `
732
+ .${CSS_CLASSES.overlay} {
733
+ display: none;
734
+ position: fixed;
735
+ inset: 0;
736
+ background: rgba(0, 0, 0, 0.6);
737
+ z-index: ${this.config.zIndex};
738
+ justify-content: center;
739
+ align-items: center;
740
+ padding: 1rem;
741
+ opacity: 0;
742
+ transition: opacity 0.2s ease-out;
743
+ }
744
+
745
+ .${CSS_CLASSES.overlay}.active {
746
+ display: flex;
747
+ opacity: 1;
748
+ }
749
+
750
+ .${CSS_CLASSES.container} {
751
+ position: relative;
752
+ width: 100%;
753
+ max-width: 500px;
754
+ max-height: 90vh;
755
+ max-height: 90dvh;
756
+ border-radius: 16px;
757
+ overflow: hidden;
758
+ background: transparent;
759
+ }
760
+
761
+ .${CSS_CLASSES.overlay}.active .${CSS_CLASSES.container} {
762
+ transform: scale(1);
763
+ }
764
+
765
+ .${CSS_CLASSES.iframe} {
766
+ width: 100%;
767
+ height: 90vh;
768
+ height: 90dvh;
769
+ max-height: 700px;
770
+ border: none;
771
+ display: block;
772
+ }
773
+
774
+ .${CSS_CLASSES.closeButton} {
775
+ position: absolute;
776
+ top: 4px;
777
+ right: 4px;
778
+ width: 24px;
779
+ height: 24px;
780
+ background: transparent;
781
+ border: none;
782
+ cursor: pointer;
783
+ padding: 0;
784
+ z-index: 10;
785
+ outline: none;
786
+ }
787
+
788
+ .${CSS_CLASSES.closeButton}:hover,
789
+ .${CSS_CLASSES.closeButton}:focus {
790
+ background: transparent;
791
+ opacity: 0.5;
792
+ }
793
+
794
+ .${CSS_CLASSES.closeButton} svg {
795
+ stroke: #666;
796
+ stroke-width: 2;
797
+ stroke-linecap: round;
798
+ }
799
+
800
+ .${CSS_CLASSES.loading} {
801
+ position: absolute;
802
+ inset: 0;
803
+ display: flex;
804
+ align-items: center;
805
+ justify-content: center;
806
+ background: #fafafa;
807
+ z-index: 5;
808
+ }
809
+
810
+ .${CSS_CLASSES.loading}.hidden {
811
+ display: none;
812
+ }
813
+
814
+ .${CSS_CLASSES.loading} svg {
815
+ width: 4rem;
816
+ height: 4rem;
817
+ animation: didit-spin 1s linear infinite;
818
+ }
819
+
820
+ .${CSS_CLASSES.loading} circle {
821
+ stroke: #e5e5e5;
822
+ stroke-width: 2.5;
823
+ fill: none;
824
+ }
825
+
826
+ .${CSS_CLASSES.loading} path {
827
+ stroke: #525252;
828
+ stroke-width: 2.5;
829
+ stroke-linecap: round;
830
+ fill: none;
831
+ }
832
+
833
+ @keyframes didit-spin {
834
+ from { transform: rotate(0deg); }
835
+ to { transform: rotate(360deg); }
836
+ }
837
+
838
+ .${CSS_CLASSES.confirmOverlay} {
839
+ display: none;
840
+ position: absolute;
841
+ inset: 0;
842
+ background: rgba(0, 0, 0, 0.5);
843
+ z-index: 20;
844
+ justify-content: center;
845
+ align-items: center;
846
+ opacity: 0;
847
+ transition: opacity 0.15s ease-out;
848
+ }
849
+
850
+ .${CSS_CLASSES.confirmOverlay}.active {
851
+ display: flex;
852
+ opacity: 1;
853
+ }
854
+
855
+ .${CSS_CLASSES.confirmBox} {
856
+ background: #fff;
857
+ border-radius: 12px;
858
+ padding: 1.5rem;
859
+ text-align: center;
860
+ max-width: 300px;
861
+ margin: 1rem;
862
+ transform: scale(0.95);
863
+ transition: transform 0.15s ease-out;
864
+ box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
865
+ outline: none;
866
+ }
867
+
868
+ .${CSS_CLASSES.confirmOverlay}.active .${CSS_CLASSES.confirmBox} {
869
+ transform: scale(1);
870
+ }
871
+
872
+ .${CSS_CLASSES.confirmBox} h3 {
873
+ color: #1a1a2e;
874
+ margin: 0 0 0.5rem 0;
875
+ font-size: 1.125rem;
876
+ font-weight: 600;
877
+ }
878
+
879
+ .${CSS_CLASSES.confirmBox} p {
880
+ color: #666;
881
+ font-size: 0.875rem;
882
+ margin: 0 0 1.25rem 0;
883
+ line-height: 1.5;
884
+ }
885
+
886
+ .didit-confirm-actions {
887
+ display: flex;
888
+ align-items: center;
889
+ justify-content: center;
890
+ gap: 1rem;
891
+ }
892
+
893
+ .didit-confirm-actions [data-action="continue"] {
894
+ background: #2563eb;
895
+ color: #fff;
896
+ border: none;
897
+ padding: 0.625rem 1.25rem;
898
+ border-radius: 8px;
899
+ font-size: 0.875rem;
900
+ font-weight: 500;
901
+ cursor: pointer;
902
+ transition: background 0.15s ease;
903
+ }
904
+
905
+ .didit-confirm-actions [data-action="continue"]:hover {
906
+ background: #1d4ed8;
907
+ }
908
+
909
+ .didit-confirm-actions [data-action="exit"] {
910
+ background: transparent;
911
+ border: none;
912
+ font-family: inherit;
913
+ font-weight: inherit;
914
+ line-height: inherit;
915
+ color: #666;
916
+ font-size: 0.875rem;
917
+ cursor: pointer;
918
+ padding: 0.625rem;
919
+ transition: color 0.15s ease;
920
+ }
921
+
922
+ .didit-confirm-actions [data-action="exit"]:hover {
923
+ color: #1a1a2e;
924
+ }
925
+
926
+ .didit-confirm-actions button:focus-visible {
927
+ outline: 2px solid #2567ff;
928
+ outline-offset: 2px;
929
+ }
930
+
931
+ @media (max-width: 540px) {
932
+ .${CSS_CLASSES.overlay} {
933
+ padding: 0;
934
+ }
935
+
936
+ .${CSS_CLASSES.container} {
937
+ max-width: 100%;
938
+ max-height: 100vh;
939
+ max-height: 100dvh;
940
+ border-radius: 0;
941
+ }
942
+
943
+ .${CSS_CLASSES.iframe} {
944
+ height: 100vh;
945
+ height: 100dvh;
946
+ max-height: none;
947
+ }
948
+ }
949
+
950
+ /*
951
+ * Once the hosted flow reports its layout (didit:layout), the modal
952
+ * grows to the handoff card on a computer (960 x 660, at most 90% of
953
+ * the window) and follows the flow's content height in a narrow
954
+ * window. Colours are the design system tokens named beside them.
955
+ */
956
+ .${CSS_CLASSES.container}.${CSS_CLASSES.flowSized} {
957
+ --didit-ground: #ffffff; /* site-ground */
958
+ --didit-heading: #1a1a1a; /* c-heading */
959
+ --didit-accent: #2567ff; /* c-accent */
960
+ --didit-hover: rgba(120, 120, 128, 0.08); /* c-hover */
961
+ --didit-close-fill: rgba(0, 0, 0, 0.06);
962
+ --didit-drop: rgba(17, 24, 39, 0.35);
963
+ --didit-ring: rgba(0, 0, 0, 0.06);
964
+ max-width: 500px;
965
+ background: var(--didit-ground);
966
+ box-shadow: 0 30px 80px -24px var(--didit-drop), 0 0 0 1px var(--didit-ring);
967
+ }
968
+
969
+ .${CSS_CLASSES.container}.${CSS_CLASSES.flowSized}[data-didit-theme="dark"] {
970
+ --didit-ground: #0b0b0d;
971
+ --didit-heading: #f5f5f7;
972
+ --didit-accent: #4d8bff;
973
+ --didit-hover: rgba(255, 255, 255, 0.06);
974
+ --didit-close-fill: rgba(255, 255, 255, 0.06);
975
+ --didit-drop: rgba(0, 0, 0, 0.55); /* c-shadow-pop, dark */
976
+ --didit-ring: rgba(255, 255, 255, 0.08); /* c-shadow-pop, dark */
977
+ }
978
+
979
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.iframe} {
980
+ height: var(--didit-flow-height);
981
+ max-height: 90vh;
982
+ max-height: 90dvh;
983
+ }
984
+
985
+ .${CSS_CLASSES.closeIcon} {
986
+ display: none;
987
+ }
988
+
989
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.closeButton} {
990
+ top: 8px;
991
+ right: 8px;
992
+ width: 44px;
993
+ height: 44px;
994
+ display: flex;
995
+ align-items: center;
996
+ justify-content: center;
997
+ border-radius: 50%;
998
+ background: var(--didit-close-fill);
999
+ color: var(--didit-heading);
1000
+ }
1001
+
1002
+ .${CSS_CLASSES.flowSized}[data-didit-dir="rtl"] .${CSS_CLASSES.closeButton} {
1003
+ right: auto;
1004
+ left: 8px;
1005
+ }
1006
+
1007
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.closeButton}:hover,
1008
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.closeButton}:focus {
1009
+ background: var(--didit-close-fill);
1010
+ opacity: 1;
1011
+ }
1012
+
1013
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.closeButton}:hover {
1014
+ background-image: linear-gradient(var(--didit-hover), var(--didit-hover));
1015
+ }
1016
+
1017
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.closeButton}:focus-visible {
1018
+ outline: 2px solid var(--didit-accent);
1019
+ outline-offset: 2px;
1020
+ }
1021
+
1022
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.closeIconLegacy} {
1023
+ display: none;
1024
+ }
1025
+
1026
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.closeButton} .${CSS_CLASSES.closeIcon} {
1027
+ display: block;
1028
+ stroke: currentColor;
1029
+ stroke-width: 1.75;
1030
+ stroke-linejoin: round;
1031
+ }
1032
+
1033
+ /*
1034
+ * The exit confirmation is sized in rem, so with a large text size it
1035
+ * can be taller than a short flow: it scrolls inside the modal instead
1036
+ * of being clipped, and its width and actions follow a larger text size.
1037
+ * It never grows wider than the modal: a long word wraps instead.
1038
+ */
1039
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.confirmOverlay} {
1040
+ padding: 1rem;
1041
+ overflow-y: auto;
1042
+ }
1043
+
1044
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.confirmBox} {
1045
+ min-width: 0;
1046
+ max-width: max(300px, 18.75rem);
1047
+ margin: auto;
1048
+ overflow-wrap: anywhere;
1049
+ /* Focusing the dialog scrolls it into view start-aligned; this keeps
1050
+ * the overlay's top padding visible so the title is never clipped. */
1051
+ scroll-margin-top: 1rem;
1052
+ }
1053
+
1054
+ .${CSS_CLASSES.flowSized} .didit-confirm-actions {
1055
+ flex-wrap: wrap;
1056
+ }
1057
+
1058
+ @media (min-width: 1024px) {
1059
+ .${CSS_CLASSES.container}.${CSS_CLASSES.flowSized} {
1060
+ width: 90vw;
1061
+ max-width: 960px;
1062
+ }
1063
+
1064
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.iframe} {
1065
+ height: 660px;
1066
+ }
1067
+ }
1068
+
1069
+ @media (max-width: 540px) {
1070
+ .${CSS_CLASSES.container}.${CSS_CLASSES.flowSized} {
1071
+ max-width: 100%;
1072
+ box-shadow: none;
1073
+ }
1074
+
1075
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.iframe} {
1076
+ height: 100vh;
1077
+ height: 100dvh;
1078
+ max-height: none;
1079
+ }
1080
+ }
1081
+
1082
+ .${CSS_CLASSES.embedded} {
1083
+ position: relative;
1084
+ width: 100%;
1085
+ height: 100%;
1086
+ }
1087
+
1088
+ .${CSS_CLASSES.embedded} .${CSS_CLASSES.iframe} {
1089
+ width: 100%;
1090
+ height: 100%;
1091
+ max-height: none;
1092
+ }
1093
+
1094
+ .${CSS_CLASSES.embedded} .${CSS_CLASSES.loading} {
1095
+ border-radius: 0;
1096
+ }
1097
+ `;
1098
+ document.head.appendChild(styles);
1099
+ }
1100
+ createDOM() {
1101
+ this.injectStyles();
1102
+ if (this.embedded && this.embeddedContainer) {
1103
+ this.createEmbeddedDOM();
1104
+ return;
1105
+ }
1106
+ const t = getTranslations(this.language);
1107
+ this.overlay = document.createElement("div");
1108
+ this.overlay.id = this.modalId;
1109
+ this.overlay.className = CSS_CLASSES.overlay;
1110
+ this.overlay.setAttribute("role", "dialog");
1111
+ this.overlay.setAttribute("aria-modal", "true");
1112
+ this.overlay.setAttribute("aria-label", t.ariaLabelModal);
1113
+ this.container = document.createElement("div");
1114
+ this.container.className = CSS_CLASSES.container;
1115
+ this.loadingEl = document.createElement("div");
1116
+ this.loadingEl.className = CSS_CLASSES.loading;
1117
+ this.loadingEl.innerHTML = `
1118
+ <svg viewBox="0 0 24 24">
1119
+ <circle cx="12" cy="12" r="10" />
1120
+ <path d="M12 2a10 10 0 0 1 10 10" />
1121
+ </svg>
1122
+ `;
1123
+ if (this.config.showCloseButton) {
1124
+ const closeBtn = document.createElement("button");
1125
+ closeBtn.className = CSS_CLASSES.closeButton;
1126
+ closeBtn.setAttribute("aria-label", t.ariaLabelClose);
1127
+ closeBtn.innerHTML = `
1128
+ <svg class="${CSS_CLASSES.closeIconLegacy}" width="14" height="14" viewBox="0 0 14 14">
1129
+ <line x1="1" y1="1" x2="13" y2="13" />
1130
+ <line x1="13" y1="1" x2="1" y2="13" />
1131
+ </svg>
1132
+ <svg class="${CSS_CLASSES.closeIcon}" width="18" height="18" viewBox="0 0 24 24" fill="none">
1133
+ <path d="M7 7.03882L17 16.9611" />
1134
+ <path d="M7.03968 17L16.9619 7" />
1135
+ </svg>
1136
+ `;
1137
+ closeBtn.addEventListener("click", () => this.handleCloseRequest(closeBtn));
1138
+ this.container.appendChild(closeBtn);
1139
+ }
1140
+ this.iframe = document.createElement("iframe");
1141
+ this.iframe.className = CSS_CLASSES.iframe;
1142
+ this.iframe.setAttribute("allow", IFRAME_ALLOW);
1143
+ this.iframe.setAttribute("title", t.ariaLabelModal);
1144
+ this.iframe.addEventListener("load", () => this.handleIframeLoad());
1145
+ this.confirmOverlay = document.createElement("div");
1146
+ this.confirmOverlay.className = CSS_CLASSES.confirmOverlay;
1147
+ this.confirmOverlay.innerHTML = `
1148
+ <div class="${CSS_CLASSES.confirmBox}" role="dialog" aria-modal="true" tabindex="-1"
1149
+ aria-labelledby="${this.modalId}-exit-title" aria-describedby="${this.modalId}-exit-message">
1150
+ <h3 id="${this.modalId}-exit-title">${t.exitTitle}</h3>
1151
+ <p id="${this.modalId}-exit-message">${t.exitMessage}</p>
1152
+ <div class="didit-confirm-actions">
1153
+ <button type="button" data-action="continue">${t.continueButton}</button>
1154
+ <button type="button" data-action="exit">${t.exitButton}</button>
1155
+ </div>
1156
+ </div>
1157
+ `;
1158
+ this.confirmOverlay.querySelector('[data-action="continue"]')?.addEventListener("click", () => {
1159
+ this.hideConfirmation();
1160
+ });
1161
+ this.confirmOverlay.querySelector('[data-action="exit"]')?.addEventListener("click", () => {
1162
+ this.confirmExit();
1163
+ });
1164
+ this.container.appendChild(this.loadingEl);
1165
+ this.container.appendChild(this.iframe);
1166
+ this.container.appendChild(this.confirmOverlay);
1167
+ this.overlay.appendChild(this.container);
1168
+ this.overlay.addEventListener("click", (e) => {
1169
+ if (e.target === this.overlay) {
1170
+ this.handleCloseRequest();
1171
+ }
1172
+ });
1173
+ this.containerElement.appendChild(this.overlay);
1174
+ }
1175
+ createEmbeddedDOM() {
1176
+ if (!this.embeddedContainer)
1177
+ return;
1178
+ this.container = document.createElement("div");
1179
+ this.container.id = this.modalId;
1180
+ this.container.className = CSS_CLASSES.embedded;
1181
+ this.loadingEl = document.createElement("div");
1182
+ this.loadingEl.className = CSS_CLASSES.loading;
1183
+ this.loadingEl.innerHTML = `
1184
+ <svg viewBox="0 0 24 24">
1185
+ <circle cx="12" cy="12" r="10" />
1186
+ <path d="M12 2a10 10 0 0 1 10 10" />
1187
+ </svg>
1188
+ `;
1189
+ this.iframe = document.createElement("iframe");
1190
+ this.iframe.className = CSS_CLASSES.iframe;
1191
+ this.iframe.setAttribute("allow", IFRAME_ALLOW);
1192
+ this.iframe.setAttribute("title", getTranslations(this.language).ariaLabelModal);
1193
+ this.iframe.addEventListener("load", () => this.handleIframeLoad());
1194
+ this.container.appendChild(this.loadingEl);
1195
+ this.container.appendChild(this.iframe);
1196
+ this.embeddedContainer.appendChild(this.container);
1197
+ }
1198
+ setupEventListeners() {
1199
+ // Idempotent: open() calls this every time it presents the modal, but a
1200
+ // modal that was already open (or re-opened without an intervening
1201
+ // close()) must not accumulate duplicate listeners.
1202
+ if (this.boundHandleMessage || this.boundHandleKeydown) {
1203
+ return;
1204
+ }
1205
+ this.boundHandleMessage = this.handleMessage.bind(this);
1206
+ window.addEventListener("message", this.boundHandleMessage);
1207
+ this.boundHandleKeydown = this.handleKeydown.bind(this);
1208
+ document.addEventListener("keydown", this.boundHandleKeydown);
1209
+ this.boundHandleFocusChange = () => {
1210
+ if (!this.state.showConfirmation || !this.isTopmost())
1211
+ return;
1212
+ // An iframe can take focus without a focusin event in its parent document.
1213
+ // Wait until its focus transition finishes before moving focus back.
1214
+ if (this.confirmationFocusTimeout !== null)
1215
+ window.clearTimeout(this.confirmationFocusTimeout);
1216
+ this.confirmationFocusTimeout = window.setTimeout(() => {
1217
+ this.confirmationFocusTimeout = null;
1218
+ if (this.state.showConfirmation && this.isTopmost() && !this.confirmOverlay?.contains(document.activeElement)) {
1219
+ this.focusConfirmation();
1220
+ }
1221
+ }, 0);
1222
+ };
1223
+ document.addEventListener("focusin", this.boundHandleFocusChange);
1224
+ document.addEventListener("focusout", this.boundHandleFocusChange);
1225
+ window.addEventListener("blur", this.boundHandleFocusChange);
1226
+ }
1227
+ removeEventListeners() {
1228
+ if (this.boundHandleMessage) {
1229
+ window.removeEventListener("message", this.boundHandleMessage);
1230
+ this.boundHandleMessage = null;
1231
+ }
1232
+ if (this.boundHandleKeydown) {
1233
+ document.removeEventListener("keydown", this.boundHandleKeydown);
1234
+ this.boundHandleKeydown = null;
1235
+ }
1236
+ if (this.boundHandleFocusChange) {
1237
+ document.removeEventListener("focusin", this.boundHandleFocusChange);
1238
+ document.removeEventListener("focusout", this.boundHandleFocusChange);
1239
+ window.removeEventListener("blur", this.boundHandleFocusChange);
1240
+ this.boundHandleFocusChange = null;
1241
+ }
1242
+ }
1243
+ pushToTop() {
1244
+ const modals = VerificationModal.openModals;
1245
+ const existingIndex = modals.indexOf(this);
1246
+ if (existingIndex !== -1) {
1247
+ modals.splice(existingIndex, 1);
1248
+ }
1249
+ modals.push(this);
1250
+ }
1251
+ removeFromStack() {
1252
+ const modals = VerificationModal.openModals;
1253
+ const existingIndex = modals.indexOf(this);
1254
+ if (existingIndex !== -1) {
1255
+ modals.splice(existingIndex, 1);
1256
+ }
1257
+ }
1258
+ isTopmost() {
1259
+ const modals = VerificationModal.openModals;
1260
+ return modals.length > 0 && modals[modals.length - 1] === this;
1261
+ }
1262
+ handleMessage(event) {
1263
+ if (!this.iframe?.src)
1264
+ return;
1265
+ if (!isAllowedOrigin(event.origin, this.iframe.src)) {
1266
+ return SDKLogger.warn("Received postMessage from unallowed origin:", event.origin);
1267
+ }
1268
+ // Scope every message to this modal's own iframe. Without this check, a
1269
+ // second VerificationModal open at the same time (e.g. a transaction
1270
+ // action modal stacked over the verification modal) would also react to
1271
+ // postMessages meant for the other iframe.
1272
+ if (!this.iframe || event.source !== this.iframe.contentWindow) {
1273
+ return;
1274
+ }
1275
+ SDKLogger.log("Received postMessage:", event.data);
1276
+ let messageData;
1277
+ try {
1278
+ if (typeof event.data === "string") {
1279
+ messageData = JSON.parse(event.data);
1280
+ }
1281
+ else {
1282
+ messageData = event.data;
1283
+ }
1284
+ }
1285
+ catch {
1286
+ SDKLogger.warn("Failed to parse postMessage:", event.data);
1287
+ return;
1288
+ }
1289
+ if (messageData.type === "didit:close_request") {
1290
+ this.handleCloseRequest();
1291
+ return;
1292
+ }
1293
+ if (messageData.type === LAYOUT_MESSAGE_TYPE) {
1294
+ const layout = this.readFlowLayout(messageData.data);
1295
+ if (layout) {
1296
+ this.applyFlowLayout(layout);
1297
+ }
1298
+ else {
1299
+ SDKLogger.warn("Ignoring a layout message without a positive contentHeight:", messageData.data);
1300
+ }
1301
+ return;
1302
+ }
1303
+ this.callbacks.onMessage(messageData);
1304
+ }
1305
+ /**
1306
+ * Reads a didit:layout message's data. Without a positive contentHeight the
1307
+ * message is ignored; a missing or unknown colorScheme follows the device,
1308
+ * and a missing or unknown dir follows the verification URL's language.
1309
+ */
1310
+ readFlowLayout(data) {
1311
+ const fields = typeof data === "object" && data !== null ? data : {};
1312
+ const { contentHeight, colorScheme, dir } = fields;
1313
+ if (typeof contentHeight !== "number" || !Number.isFinite(contentHeight) || contentHeight <= 0) {
1314
+ return null;
1315
+ }
1316
+ const prefersDark = window.matchMedia?.("(prefers-color-scheme: dark)").matches ?? false;
1317
+ return {
1318
+ contentHeight: Math.ceil(contentHeight),
1319
+ colorScheme: colorScheme === "light" || colorScheme === "dark" ? colorScheme : prefersDark ? "dark" : "light",
1320
+ dir: dir === "ltr" || dir === "rtl" ? dir : isRtlLanguage(this.language) ? "rtl" : "ltr"
1321
+ };
1322
+ }
1323
+ /** Embedded mode keeps filling the integrator's host element, whatever the flow reports. */
1324
+ applyFlowLayout(layout) {
1325
+ if (this.embedded || !this.container)
1326
+ return;
1327
+ SDKLogger.log("Flow layout:", layout);
1328
+ this.container.classList.add(CSS_CLASSES.flowSized);
1329
+ this.container.style.setProperty("--didit-flow-height", `${layout.contentHeight}px`);
1330
+ this.container.dataset.diditTheme = layout.colorScheme;
1331
+ this.container.dataset.diditDir = layout.dir;
1332
+ }
1333
+ /** Back to the fixed 500 x 700 modal until the newly loaded flow reports its layout. */
1334
+ resetFlowLayout() {
1335
+ if (this.embedded || !this.container)
1336
+ return;
1337
+ this.container.classList.remove(CSS_CLASSES.flowSized);
1338
+ this.container.style.removeProperty("--didit-flow-height");
1339
+ delete this.container.dataset.diditTheme;
1340
+ delete this.container.dataset.diditDir;
1341
+ }
1342
+ handleKeydown(event) {
1343
+ if (!this.state.isOpen)
1344
+ return;
1345
+ // When multiple modals are open at once, only the topmost one should
1346
+ // react to a keypress aimed at it (e.g. Escape closing a stacked
1347
+ // transaction action modal must not also trigger the exit confirmation
1348
+ // of the verification modal underneath it).
1349
+ if (!this.isTopmost())
1350
+ return;
1351
+ if (event.key === "Tab" && this.state.showConfirmation) {
1352
+ const buttons = Array.from(this.confirmOverlay?.querySelectorAll("button") ?? []);
1353
+ if (buttons.length) {
1354
+ event.preventDefault();
1355
+ const current = buttons.findIndex((button) => button === document.activeElement);
1356
+ const next = event.shiftKey
1357
+ ? (current <= 0 ? buttons.length - 1 : current - 1)
1358
+ : (current + 1) % buttons.length;
1359
+ buttons[next].focus();
1360
+ }
1361
+ return;
1362
+ }
1363
+ if (event.key === "Escape") {
1364
+ event.preventDefault();
1365
+ if (this.state.showConfirmation) {
1366
+ this.hideConfirmation();
1367
+ }
1368
+ else {
1369
+ this.handleCloseRequest();
1370
+ }
1371
+ }
1372
+ }
1373
+ handleIframeLoad() {
1374
+ if (this.iframe?.src && this.iframe.src !== "about:blank") {
1375
+ this.state.isLoading = false;
1376
+ this.loadingEl?.classList.add("hidden");
1377
+ this.callbacks.onIframeLoad();
1378
+ }
1379
+ }
1380
+ handleCloseRequest(trigger) {
1381
+ if (this.config.showExitConfirmation) {
1382
+ this.showConfirmation(trigger);
1383
+ }
1384
+ else {
1385
+ this.callbacks.onCloseConfirmed();
1386
+ }
1387
+ }
1388
+ showConfirmation(trigger) {
1389
+ if (!this.confirmOverlay || this.state.showConfirmation)
1390
+ return;
1391
+ const activeElement = document.activeElement;
1392
+ this.confirmationTrigger = trigger ?? (activeElement instanceof HTMLElement && activeElement !== document.body
1393
+ ? activeElement
1394
+ : this.container?.querySelector(`.${CSS_CLASSES.closeButton}`) ?? this.iframe);
1395
+ this.state.showConfirmation = true;
1396
+ this.confirmOverlay.classList.add("active");
1397
+ if (this.iframe)
1398
+ this.iframe.inert = true;
1399
+ const close = this.container?.querySelector(`.${CSS_CLASSES.closeButton}`);
1400
+ if (close)
1401
+ close.inert = true;
1402
+ // A confirmation scrolled at a large text size opens again at its title.
1403
+ this.confirmOverlay.scrollTop = 0;
1404
+ if (this.isTopmost())
1405
+ this.focusConfirmation();
1406
+ this.callbacks.onClose();
1407
+ }
1408
+ focusConfirmation() {
1409
+ this.confirmOverlay?.querySelector(`.${CSS_CLASSES.confirmBox}`)?.focus({ preventScroll: true });
1410
+ }
1411
+ hideConfirmation(restoreFocus = true) {
1412
+ if (this.confirmationFocusTimeout !== null) {
1413
+ window.clearTimeout(this.confirmationFocusTimeout);
1414
+ this.confirmationFocusTimeout = null;
1415
+ }
1416
+ if (!this.state.showConfirmation)
1417
+ return;
1418
+ this.state.showConfirmation = false;
1419
+ this.confirmOverlay?.classList.remove("active");
1420
+ if (this.iframe)
1421
+ this.iframe.inert = false;
1422
+ const close = this.container?.querySelector(`.${CSS_CLASSES.closeButton}`);
1423
+ if (close)
1424
+ close.inert = false;
1425
+ const trigger = this.confirmationTrigger;
1426
+ this.confirmationTrigger = null;
1427
+ if (restoreFocus && this.isTopmost() && trigger?.isConnected) {
1428
+ if (trigger === this.iframe) {
1429
+ // Firefox needs a browser task to reactivate an inert cross-origin frame.
1430
+ this.confirmationFocusTimeout = window.setTimeout(() => {
1431
+ this.confirmationFocusTimeout = null;
1432
+ if (this.state.isOpen && !this.state.showConfirmation && this.isTopmost() && trigger.isConnected) {
1433
+ trigger.focus({ preventScroll: true });
1434
+ }
1435
+ }, 0);
1436
+ }
1437
+ else {
1438
+ trigger.focus({ preventScroll: true });
1439
+ }
1440
+ }
1441
+ }
1442
+ confirmExit() {
1443
+ this.hideConfirmation();
1444
+ this.callbacks.onCloseConfirmed();
1445
+ }
1446
+ open(verificationUrl) {
1447
+ // Whether this modal already held its scroll lock before this call. Re-opening
1448
+ // an already-open instance must not re-capture previousBodyOverflow, or it
1449
+ // would record this modal's own "hidden" lock and close() could never restore
1450
+ // the real pre-lock value.
1451
+ const wasAlreadyOpen = this.state.isOpen;
1452
+ this.language = detectLanguageFromUrl(verificationUrl);
1453
+ if (!this.overlay && !this.container) {
1454
+ this.createDOM();
1455
+ }
1456
+ // Re-attach listeners every open() (idempotent) since close() now tears
1457
+ // them down; this lets the same instance be re-opened without a
1458
+ // destroy()/re-create cycle.
1459
+ this.setupEventListeners();
1460
+ SDKLogger.log("Opening with URL:", verificationUrl);
1461
+ this.state.isLoading = true;
1462
+ this.hideConfirmation();
1463
+ this.loadingEl?.classList.remove("hidden");
1464
+ this.resetFlowLayout();
1465
+ if (this.iframe) {
1466
+ this.iframe.src = verificationUrl;
1467
+ }
1468
+ this.state.isOpen = true;
1469
+ this.pushToTop();
1470
+ if (this.embedded) {
1471
+ return;
1472
+ }
1473
+ this.overlay?.classList.add("active");
1474
+ // Capture whatever overflow value is currently in effect (which may
1475
+ // already be "hidden" because another modal is open) so close() can
1476
+ // restore exactly that value instead of clobbering a scroll lock owned
1477
+ // by a concurrently open modal. Skip the capture on a re-open: the value
1478
+ // in effect is this modal's own lock, and previousBodyOverflow already
1479
+ // holds the correct pre-lock value.
1480
+ if (!wasAlreadyOpen) {
1481
+ this.previousBodyOverflow = document.body.style.overflow;
1482
+ }
1483
+ document.body.style.overflow = "hidden";
1484
+ }
1485
+ close() {
1486
+ SDKLogger.log("Closing");
1487
+ this.hideConfirmation(false);
1488
+ this.state.isOpen = false;
1489
+ this.state.isLoading = true;
1490
+ this.state.showConfirmation = false;
1491
+ this.removeFromStack();
1492
+ this.removeEventListeners();
1493
+ this.resetFlowLayout();
1494
+ if (this.iframe) {
1495
+ this.iframe.src = "about:blank";
1496
+ }
1497
+ if (this.embedded) {
1498
+ return;
1499
+ }
1500
+ this.overlay?.classList.remove("active");
1501
+ document.body.style.overflow = this.previousBodyOverflow ?? "";
1502
+ this.previousBodyOverflow = null;
1503
+ }
1504
+ destroy() {
1505
+ SDKLogger.log("Destroying");
1506
+ this.close();
1507
+ this.removeEventListeners();
1508
+ if (this.embedded && this.container && this.container.parentNode) {
1509
+ this.container.parentNode.removeChild(this.container);
1510
+ }
1511
+ else if (this.overlay && this.overlay.parentNode) {
1512
+ this.overlay.parentNode.removeChild(this.overlay);
1513
+ }
1514
+ this.overlay = null;
1515
+ this.container = null;
1516
+ this.iframe = null;
1517
+ this.loadingEl = null;
1518
+ this.confirmOverlay = null;
1519
+ }
1520
+ isOpen() {
1521
+ return this.state.isOpen;
1522
+ }
1523
+ isLoading() {
1524
+ return this.state.isLoading;
1525
+ }
1526
+ }
1527
+ /**
1528
+ * Every currently-open modal, oldest first. Used so a single Escape
1529
+ * keypress (or other document-level shortcut) only acts on the topmost
1530
+ * modal when multiple VerificationModal instances are open at once (e.g.
1531
+ * a transaction action modal stacked over the verification modal).
1532
+ */
1533
+ VerificationModal.openModals = [];
1534
+
1535
+ const DEFAULT_TRANSACTION_BASE_URL = "https://verification.didit.me";
1536
+ const ACTION_POLL_INTERVAL_MS = 1500;
1537
+ const ACTION_POLL_MAX_ATTEMPTS = 10;
1538
+ const TRANSACTION_ERROR_MESSAGES = {
1539
+ invalid_token: "The transaction token is invalid.",
1540
+ expired_token: "The transaction token has expired.",
1541
+ validation: "The transaction payload failed validation.",
1542
+ network: "A network error occurred while contacting the Didit API."
1543
+ };
1544
+ /**
1545
+ * Typed error thrown by DiditSdk.submitTransaction.
1546
+ *
1547
+ * - "invalid_token": the X-Transaction-Token was rejected (missing, revoked, over max uses)
1548
+ * - "expired_token": the transaction token TTL has elapsed
1549
+ * - "validation": the payload failed validation; see fieldErrors for per-field details
1550
+ * - "network": the request could not complete or the API returned an unexpected error
1551
+ */
1552
+ class DiditTransactionError extends Error {
1553
+ constructor(type, message, options) {
1554
+ super(message || TRANSACTION_ERROR_MESSAGES[type]);
1555
+ this.name = "DiditTransactionError";
1556
+ this.type = type;
1557
+ this.status = options?.status;
1558
+ this.fieldErrors = options?.fieldErrors;
1559
+ }
1560
+ }
1561
+ function isPlainRecord(value) {
1562
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1563
+ }
1564
+ function compact(record) {
1565
+ const result = {};
1566
+ for (const [key, value] of Object.entries(record)) {
1567
+ if (value !== undefined)
1568
+ result[key] = value;
1569
+ }
1570
+ return result;
1571
+ }
1572
+ function mapDetails(details) {
1573
+ return compact({
1574
+ direction: details.direction,
1575
+ amount: details.amount,
1576
+ currency: details.currency,
1577
+ currencyType: details.currencyType,
1578
+ amountInDefaultCurrency: details.amountInDefaultCurrency,
1579
+ defaultCurrencyCode: details.defaultCurrencyCode,
1580
+ paymentDetails: details.paymentDetails,
1581
+ paymentTxnId: details.paymentTxnId,
1582
+ type: details.actionType,
1583
+ cryptoParams: details.cryptoParams
1584
+ });
1585
+ }
1586
+ function mapParticipant(participant) {
1587
+ if (!participant)
1588
+ return undefined;
1589
+ return compact({
1590
+ type: participant.type,
1591
+ externalUserId: participant.externalUserId,
1592
+ fullName: participant.fullName,
1593
+ firstName: participant.firstName,
1594
+ lastName: participant.lastName,
1595
+ dob: participant.dob,
1596
+ address: participant.address,
1597
+ institutionInfo: participant.institutionInfo,
1598
+ device: participant.device,
1599
+ paymentMethod: participant.paymentMethod
1600
+ ? compact({
1601
+ type: participant.paymentMethod.type,
1602
+ accountId: participant.paymentMethod.accountId,
1603
+ issuingCountry: participant.paymentMethod.issuingCountry
1604
+ })
1605
+ : undefined
1606
+ });
1607
+ }
1608
+ function mapTravelRule(travelRule) {
1609
+ if (!travelRule)
1610
+ return undefined;
1611
+ return compact({
1612
+ status: travelRule.status,
1613
+ protocol: travelRule.protocol,
1614
+ required: travelRule.required,
1615
+ obligationsCount: travelRule.obligationsCount,
1616
+ originatorData: travelRule.originatorData,
1617
+ beneficiaryData: travelRule.beneficiaryData,
1618
+ metadata: travelRule.metadata
1619
+ });
1620
+ }
1621
+ /**
1622
+ * Maps the SDK-friendly camelCase payload onto the wire aliases accepted by the
1623
+ * Didit transactions API (txnId, txnDate, zoneId, type, info, subject,
1624
+ * counterparty, props, travelRule, includeCryptoScreening).
1625
+ */
1626
+ function buildTransactionRequestBody(transaction) {
1627
+ return compact({
1628
+ txnId: transaction.txnId,
1629
+ txnDate: transaction.txnDate,
1630
+ zoneId: transaction.zoneId,
1631
+ type: transaction.category,
1632
+ info: mapDetails(transaction.details),
1633
+ subject: mapParticipant(transaction.subject),
1634
+ counterparty: mapParticipant(transaction.counterparty),
1635
+ props: transaction.customProperties,
1636
+ travelRule: mapTravelRule(transaction.travelRule),
1637
+ includeCryptoScreening: transaction.includeCryptoScreening
1638
+ });
1639
+ }
1640
+ function pickString(record, ...keys) {
1641
+ for (const key of keys) {
1642
+ const value = record[key];
1643
+ if (typeof value === "string" && value)
1644
+ return value;
1645
+ }
1646
+ return undefined;
1647
+ }
1648
+ function mapActionRequired(raw) {
1649
+ if (!isPlainRecord(raw))
1650
+ return undefined;
1651
+ const type = pickString(raw, "type");
1652
+ const url = pickString(raw, "url");
1653
+ if (!type || !url)
1654
+ return undefined;
1655
+ const action = { type, url };
1656
+ const sessionId = pickString(raw, "session_id", "sessionId");
1657
+ if (sessionId)
1658
+ action.sessionId = sessionId;
1659
+ const sessionToken = pickString(raw, "session_token", "sessionToken");
1660
+ if (sessionToken)
1661
+ action.sessionToken = sessionToken;
1662
+ const status = pickString(raw, "status");
1663
+ if (status)
1664
+ action.status = status;
1665
+ const widgetSessionId = pickString(raw, "widget_session_id", "widgetSessionId");
1666
+ if (widgetSessionId)
1667
+ action.widgetSessionId = widgetSessionId;
1668
+ const expiresAt = pickString(raw, "expires_at", "expiresAt");
1669
+ if (expiresAt)
1670
+ action.expiresAt = expiresAt;
1671
+ return action;
1672
+ }
1673
+ function mapTravelRuleStatus(raw) {
1674
+ const travelRule = raw.travel_rule ?? raw.travelRule;
1675
+ if (isPlainRecord(travelRule)) {
1676
+ const status = pickString(travelRule, "status");
1677
+ if (status)
1678
+ return status;
1679
+ }
1680
+ const props = raw.props;
1681
+ if (isPlainRecord(props)) {
1682
+ const status = pickString(props, "travel_rule_status", "travelRuleStatus");
1683
+ if (status)
1684
+ return status;
1685
+ }
1686
+ return pickString(raw, "travel_rule_status", "travelRuleStatus");
1687
+ }
1688
+ function mapTransactionResponse(raw) {
1689
+ const transactionId = pickString(raw, "uuid", "transaction_id", "transactionId");
1690
+ const status = pickString(raw, "status");
1691
+ if (!transactionId || !status) {
1692
+ // A missing id/status is not a valid transaction snapshot: fabricating
1693
+ // empty strings here would let a malformed response (envelope,
1694
+ // intercepting proxy, contract drift) look like a real result to
1695
+ // callers - e.g. the poll's statusMoved early-exit would trigger on an
1696
+ // empty status that merely differs from a real initialStatus.
1697
+ throw new DiditTransactionError("network", "Unexpected response shape from the Didit API: missing transaction id or status.");
1698
+ }
1699
+ const result = { transactionId, status };
1700
+ const travelRuleStatus = mapTravelRuleStatus(raw);
1701
+ if (travelRuleStatus)
1702
+ result.travelRuleStatus = travelRuleStatus;
1703
+ const actionRequired = mapActionRequired(raw.action_required ?? raw.actionRequired);
1704
+ if (actionRequired)
1705
+ result.actionRequired = actionRequired;
1706
+ return result;
1707
+ }
1708
+ function extractDetailMessage(body) {
1709
+ if (!isPlainRecord(body))
1710
+ return undefined;
1711
+ return pickString(body, "detail", "message", "error");
1712
+ }
1713
+ function classifyTransactionError(status, body) {
1714
+ const detail = extractDetailMessage(body);
1715
+ if (status === 401 || status === 403) {
1716
+ const serialized = `${detail ?? ""} ${pickString(isPlainRecord(body) ? body : {}, "code") ?? ""}`;
1717
+ if (/expired/i.test(serialized)) {
1718
+ return new DiditTransactionError("expired_token", detail, { status });
1719
+ }
1720
+ return new DiditTransactionError("invalid_token", detail, { status });
1721
+ }
1722
+ if (status === 400 || status === 422) {
1723
+ return new DiditTransactionError("validation", detail, {
1724
+ status,
1725
+ fieldErrors: isPlainRecord(body) ? body : undefined
1726
+ });
1727
+ }
1728
+ return new DiditTransactionError("network", `Request failed with status ${status}.`, { status });
1729
+ }
1730
+ async function readJsonBody(response) {
1731
+ try {
1732
+ return await response.json();
1733
+ }
1734
+ catch {
1735
+ return null;
1736
+ }
1737
+ }
1738
+ async function performRequest(url, init) {
1739
+ if (typeof fetch !== "function") {
1740
+ throw new DiditTransactionError("network", "fetch is not available in this environment.");
1741
+ }
1742
+ let response;
1743
+ try {
1744
+ response = await fetch(url, init);
1745
+ }
1746
+ catch {
1747
+ throw new DiditTransactionError("network");
1748
+ }
1749
+ const body = await readJsonBody(response);
1750
+ if (!response.ok) {
1751
+ throw classifyTransactionError(response.status, body);
1752
+ }
1753
+ if (!isPlainRecord(body)) {
1754
+ throw new DiditTransactionError("network", "Unexpected empty response from the Didit API.", {
1755
+ status: response.status
1756
+ });
1757
+ }
1758
+ return mapTransactionResponse(body);
1759
+ }
1760
+ async function submitTransactionRequest(args) {
1761
+ const fingerprint = await getDeviceFingerprintPayload().catch(() => null);
1762
+ const body = buildTransactionRequestBody(args.transaction);
1763
+ if (fingerprint) {
1764
+ body.fingerprint_v2 = fingerprint;
1765
+ }
1766
+ return performRequest(`${args.baseUrl}/v1/transactions/`, {
1767
+ method: "POST",
1768
+ headers: {
1769
+ "Content-Type": "application/json",
1770
+ "X-Transaction-Token": args.transactionToken,
1771
+ ...buildFingerprintHeaders(fingerprint)
1772
+ },
1773
+ body: JSON.stringify(body)
1774
+ });
1775
+ }
1776
+ async function fetchTransaction(args) {
1777
+ return performRequest(`${args.baseUrl}/v1/transactions/${args.transactionId}/`, {
1778
+ method: "GET",
1779
+ headers: { "X-Transaction-Token": args.transactionToken }
1780
+ });
1781
+ }
1782
+ function delay(ms) {
1783
+ return new Promise((resolve) => setTimeout(resolve, ms));
1784
+ }
1785
+ /** Terminal auth failures that will never succeed on retry: keep polling would just burn the token's remaining uses. */
1786
+ function isTerminalPollError(error) {
1787
+ return error instanceof DiditTransactionError && (error.type === "invalid_token" || error.type === "expired_token");
1788
+ }
1789
+ /**
1790
+ * Re-fetches the transaction after an action flow finished or its modal was
1791
+ * closed. Polls with a bounded retry (never relies on a single event/attempt)
1792
+ * and stops early once the required action is cleared or the status moved on.
1793
+ * Returns the latest successfully fetched result, or null when every attempt
1794
+ * failed.
1795
+ *
1796
+ * A terminal auth failure (invalid_token/expired_token - e.g. a maxUses
1797
+ * token exhausted by the poll's own GETs, or the token TTL elapsing while
1798
+ * the user was in the action flow) aborts immediately instead of retrying:
1799
+ * it can never succeed, and each attempt would otherwise still count
1800
+ * against the token's use_count server-side. The error is rethrown so the
1801
+ * caller can surface it instead of silently returning a stale result.
1802
+ *
1803
+ * `isAborted` is polled between attempts so a caller that tears down (e.g.
1804
+ * DiditSdk.destroy()) can stop the loop from making further network calls.
1805
+ */
1806
+ async function pollTransactionAfterAction(args) {
1807
+ const intervalMs = args.intervalMs ?? ACTION_POLL_INTERVAL_MS;
1808
+ const maxAttempts = Math.max(1, args.maxAttempts ?? ACTION_POLL_MAX_ATTEMPTS);
1809
+ let latest = null;
1810
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
1811
+ if (args.isAborted?.())
1812
+ return latest;
1813
+ if (attempt > 0) {
1814
+ await delay(intervalMs);
1815
+ }
1816
+ if (args.isAborted?.())
1817
+ return latest;
1818
+ try {
1819
+ latest = await fetchTransaction(args);
1820
+ const actionResolved = !latest.actionRequired;
1821
+ const statusMoved = args.initialStatus !== undefined && latest.status !== args.initialStatus;
1822
+ if (actionResolved || statusMoved) {
1823
+ return latest;
1824
+ }
1825
+ }
1826
+ catch (error) {
1827
+ if (isTerminalPollError(error)) {
1828
+ throw error;
1829
+ }
1830
+ // Transient failure; keep polling until the bound is reached.
1831
+ }
1832
+ }
1833
+ return latest;
1834
+ }
1835
+
1836
+ /**
1837
+ * Embedded mode renders inside an element that already exists on the
1838
+ * integrator's page. Without it the modal never shows anything (embedded mode
1839
+ * never activates the overlay), so the launch fails with a message the
1840
+ * integrator can act on instead of silently presenting nothing.
1841
+ */
1842
+ function assertEmbeddedHostExists(configuration) {
1843
+ if (!configuration?.embedded)
1844
+ return;
1845
+ const containerId = configuration.embeddedContainerId;
1846
+ if (!containerId) {
1847
+ throw new Error("Embedded mode requires embeddedContainerId: the id of the element that hosts the verification.");
1848
+ }
1849
+ if (typeof document === "undefined" || !document.getElementById(containerId)) {
1850
+ throw new Error(`Embedded container "#${containerId}" was not found in the page.`);
1851
+ }
1852
+ }
1853
+ class DiditSdk {
1854
+ static get shared() {
1855
+ if (!DiditSdk._instance) {
1856
+ DiditSdk._instance = new DiditSdk();
1857
+ }
1858
+ return DiditSdk._instance;
1859
+ }
1860
+ static reset() {
1861
+ if (DiditSdk._instance) {
1862
+ DiditSdk._instance.destroy();
1863
+ DiditSdk._instance = null;
1864
+ }
1865
+ }
1866
+ get state() {
1867
+ return this._state;
1868
+ }
1869
+ get configuration() {
1870
+ return this._configuration;
1871
+ }
1872
+ get isPresented() {
1873
+ return this._modal?.isOpen() ?? false;
1874
+ }
1875
+ /**
1876
+ * True while a transaction's wallet-ownership action modal (auto-launched
1877
+ * by submitTransaction) is on screen. verification_session actions are
1878
+ * never auto-launched, so they never affect this flag - see
1879
+ * {@link submitTransaction}. Tracked separately from {@link isPresented},
1880
+ * which reflects the verification modal only.
1881
+ */
1882
+ get isActionModalPresented() {
1883
+ return this._actionModal?.isOpen() ?? false;
1884
+ }
1885
+ get errorMessage() {
1886
+ return this._errorMessage;
1887
+ }
1888
+ constructor() {
1889
+ this._state = "idle";
1890
+ this._modal = null;
1891
+ this._actionModal = null;
1892
+ this._actionModalSettle = null;
1893
+ /**
1894
+ * Bumped by destroy() to invalidate any transaction action in flight
1895
+ * (pending action modal and/or its follow-up poll) so a torn-down SDK
1896
+ * instance can never deliver a late onActionCompleted. A new
1897
+ * submitTransaction call always reads the current generation, so it is
1898
+ * unaffected by a destroy() that happened before it started.
1899
+ */
1900
+ this._actionGeneration = 0;
1901
+ SDKLogger.log("DiditSdk initialized");
1902
+ }
1903
+ async startVerification(options) {
1904
+ const config = options.configuration;
1905
+ this._configuration = config;
1906
+ SDKLogger.isEnabled = config?.loggingEnabled ?? DEFAULT_CONFIG.loggingEnabled;
1907
+ SDKLogger.log("Starting verification with options:", options);
1908
+ if (this._modal) {
1909
+ this._modal.destroy();
1910
+ this._modal = null;
1911
+ }
1912
+ // A new launch is not in an error state any more, whatever the last one did.
1913
+ this._errorMessage = undefined;
1914
+ try {
1915
+ const { url } = options;
1916
+ if (!url || typeof url !== "string") {
1917
+ throw new Error("Invalid options: url is required");
1918
+ }
1919
+ assertEmbeddedHostExists(config);
1920
+ this._modal = new VerificationModal(config, {
1921
+ onClose: () => this.handleModalClose(),
1922
+ onCloseConfirmed: () => this.handleModalCloseConfirmed(),
1923
+ onMessage: (event) => this.handleVerificationEvent(event),
1924
+ onIframeLoad: () => this.handleIframeLoad()
1925
+ });
1926
+ this._url = buildVerificationUrl(url, config);
1927
+ this.setState("loading");
1928
+ this.emitInternalEvent("didit:started", {});
1929
+ this._modal?.open(this._url);
1930
+ }
1931
+ catch (error) {
1932
+ this.handleError(error);
1933
+ }
1934
+ }
1935
+ /**
1936
+ * Submits a transaction (including travel-rule and crypto-monitoring payloads)
1937
+ * directly from the end-user device.
1938
+ *
1939
+ * The request is authenticated with a short-lived transaction token minted by
1940
+ * your backend (POST /v3/transactions/sdk-token/) and sent via the
1941
+ * X-Transaction-Token header. Device intelligence is attached automatically:
1942
+ * the SDK collects a didit-fp-v2 fingerprint and sends it as the X-Didit-PID /
1943
+ * X-Didit-FP-Hash headers plus a `fingerprint_v2` body field.
1944
+ *
1945
+ * When the response contains an `actionRequired` block, the contract differs
1946
+ * by type:
1947
+ * - `wallet_ownership` (a same-origin, Didit-hosted widget): when
1948
+ * `autoLaunchAction` is not false, the SDK opens the action URL in the
1949
+ * verification modal itself. Once the flow completes or the modal is
1950
+ * closed, the transaction is re-fetched with a bounded poll (never a
1951
+ * single event) and `onActionCompleted` is invoked with the refreshed
1952
+ * result.
1953
+ * - `verification_session` (a biometric verification session): never
1954
+ * auto-launched, regardless of `autoLaunchAction`. It is only ever
1955
+ * returned in `result.actionRequired` for the host application to launch
1956
+ * with its own verification integration (e.g. `startVerification`).
1957
+ *
1958
+ * @param options Submission options: transactionToken, transaction payload,
1959
+ * optional baseUrl (defaults to https://verification.didit.me),
1960
+ * autoLaunchAction (defaults to true, applies to wallet_ownership actions
1961
+ * only) and onActionCompleted callback.
1962
+ * @returns The created transaction: transactionId, status, travelRuleStatus
1963
+ * and actionRequired when a user action is pending.
1964
+ * @throws {DiditTransactionError} Typed as "invalid_token", "expired_token",
1965
+ * "validation" (with fieldErrors) or "network".
1966
+ */
1967
+ async submitTransaction(options) {
1968
+ if (!options?.transactionToken || typeof options.transactionToken !== "string") {
1969
+ throw new DiditTransactionError("invalid_token", "transactionToken is required.");
1970
+ }
1971
+ if (!options.transaction || typeof options.transaction !== "object") {
1972
+ throw new DiditTransactionError("validation", "transaction payload is required.");
1973
+ }
1974
+ if (!options.transaction.txnId || typeof options.transaction.txnId !== "string") {
1975
+ throw new DiditTransactionError("validation", "transaction.txnId is required.");
1976
+ }
1977
+ if (!options.transaction.details || typeof options.transaction.details !== "object") {
1978
+ throw new DiditTransactionError("validation", "transaction.details is required.");
1979
+ }
1980
+ const baseUrl = (options.baseUrl ?? DEFAULT_TRANSACTION_BASE_URL).replace(/\/+$/, "");
1981
+ SDKLogger.log("Submitting transaction:", options.transaction.txnId);
1982
+ const result = await submitTransactionRequest({
1983
+ baseUrl,
1984
+ transactionToken: options.transactionToken,
1985
+ transaction: options.transaction
1986
+ });
1987
+ SDKLogger.log("Transaction submitted:", result);
1988
+ // Only wallet_ownership is a same-origin, Didit-hosted widget that is
1989
+ // safe for the SDK to open on the integrator's behalf. verification_session
1990
+ // is never auto-launched: it is already returned in result.actionRequired
1991
+ // above for the host to launch with its own verification integration.
1992
+ const autoLaunchAction = options.autoLaunchAction ?? true;
1993
+ if (autoLaunchAction && result.actionRequired?.type === "wallet_ownership" && result.actionRequired.url) {
1994
+ void this.runTransactionAction(baseUrl, options.transactionToken, result, options.onActionCompleted);
1995
+ }
1996
+ return result;
1997
+ }
1998
+ /**
1999
+ * Queues an end-user event (sign-up, login, failed login, logout, password
2000
+ * reset, MFA, device change...) for Didit's event monitoring, so it appears
2001
+ * in the console tied to the same person as their verifications and
2002
+ * transactions. Returns the event id.
2003
+ *
2004
+ * The request is authenticated with a short-lived monitoring token minted by
2005
+ * your backend for that person (POST /v3/events/sdk-token/) and sent via the
2006
+ * X-Monitoring-Token header; the person always comes from the token. Events
2007
+ * are batched to /v1/events/batch/ with the device fingerprint attached, and
2008
+ * sent when 25 are waiting, every 5 seconds and when the page is hidden or
2009
+ * closed. Tune the queue with `configureEvents` and send right away with
2010
+ * `flush`, both exported by this package.
2011
+ *
2012
+ * @param options monitoringToken, the event and an optional baseUrl
2013
+ * (defaults to https://verification.didit.me).
2014
+ * @returns The event id: yours when you set event.eventId, otherwise a new UUID.
2015
+ * @throws {DiditEventError} "invalid_token" without a monitoringToken,
2016
+ * "validation" without an event category and action type.
2017
+ */
2018
+ submitEvent(options) {
2019
+ SDKLogger.log("Submitting event:", options?.event?.category, options?.event?.actionType);
2020
+ return submitEvent(options);
2021
+ }
2022
+ /**
2023
+ * Dismisses everything currently on screen in one deterministic call: a
2024
+ * pending transaction action modal is treated as an abort (no follow-up
2025
+ * poll, no onActionCompleted) and the verification modal is always closed
2026
+ * afterwards, regardless of whether an action modal was present.
2027
+ */
2028
+ close() {
2029
+ SDKLogger.log("Closing verification programmatically");
2030
+ this._actionModalSettle?.("aborted");
2031
+ this.handleModalCloseConfirmed();
2032
+ }
2033
+ destroy() {
2034
+ SDKLogger.log("Destroying SDK instance");
2035
+ // Invalidate any transaction action in flight so a poll that is already
2036
+ // running cannot deliver onActionCompleted after teardown.
2037
+ this._actionGeneration++;
2038
+ this._actionModalSettle?.("aborted");
2039
+ this._modal?.destroy();
2040
+ this._modal = null;
2041
+ this.reset();
2042
+ this.setState("idle");
2043
+ }
2044
+ async runTransactionAction(baseUrl, transactionToken, submitResult, onActionCompleted) {
2045
+ const generation = this._actionGeneration;
2046
+ let delivered = false;
2047
+ // Guarantees at-most-once delivery: a throwing integrator callback must
2048
+ // not be re-invoked by a surrounding catch, and a destroy() that
2049
+ // happened while we were awaiting the modal/poll must suppress delivery
2050
+ // entirely rather than calling back into a torn-down integration.
2051
+ const deliver = (result, error) => {
2052
+ if (delivered || generation !== this._actionGeneration)
2053
+ return;
2054
+ delivered = true;
2055
+ try {
2056
+ onActionCompleted?.(result, error);
2057
+ }
2058
+ catch (callbackError) {
2059
+ SDKLogger.error("onActionCompleted callback threw:", callbackError);
2060
+ }
2061
+ };
2062
+ try {
2063
+ const outcome = await this.presentTransactionActionModal(submitResult.actionRequired.url);
2064
+ if (outcome === "aborted" || generation !== this._actionGeneration) {
2065
+ return;
2066
+ }
2067
+ if (!submitResult.transactionId) {
2068
+ deliver(submitResult);
2069
+ return;
2070
+ }
2071
+ let refreshed = null;
2072
+ let pollError;
2073
+ try {
2074
+ refreshed = await pollTransactionAfterAction({
2075
+ baseUrl,
2076
+ transactionToken,
2077
+ transactionId: submitResult.transactionId,
2078
+ initialStatus: submitResult.status,
2079
+ isAborted: () => generation !== this._actionGeneration
2080
+ });
2081
+ }
2082
+ catch (error) {
2083
+ if (error instanceof DiditTransactionError) {
2084
+ pollError = error;
2085
+ }
2086
+ else {
2087
+ throw error;
2088
+ }
2089
+ }
2090
+ if (pollError) {
2091
+ // Terminal auth failure (invalid_token/expired_token): surface it
2092
+ // instead of silently handing back the stale pre-action result.
2093
+ deliver(submitResult, { type: pollError.type, message: pollError.message });
2094
+ return;
2095
+ }
2096
+ deliver(refreshed ?? submitResult);
2097
+ }
2098
+ catch (error) {
2099
+ SDKLogger.error("Transaction action follow-up failed:", error);
2100
+ deliver(submitResult);
2101
+ }
2102
+ }
2103
+ presentTransactionActionModal(url) {
2104
+ // Abort any previous action modal before opening a new one.
2105
+ this._actionModalSettle?.("aborted");
2106
+ return new Promise((resolve) => {
2107
+ let settled = false;
2108
+ const settle = (outcome) => {
2109
+ if (settled)
2110
+ return;
2111
+ settled = true;
2112
+ const modal = this._actionModal;
2113
+ this._actionModal = null;
2114
+ this._actionModalSettle = null;
2115
+ modal?.destroy();
2116
+ resolve(outcome);
2117
+ };
2118
+ // this._actionModalSettle is assigned only after the modal is
2119
+ // successfully constructed and opened. If either throws (e.g. no
2120
+ // `document` in Node/SSR, or document.body not ready yet), the
2121
+ // settle callback must not be left dangling: a later close() would
2122
+ // otherwise find a stale this._actionModalSettle for a modal that
2123
+ // was never presented, "settle" it, and return early without ever
2124
+ // closing the actual verification modal.
2125
+ let modal;
2126
+ try {
2127
+ modal = new VerificationModal(undefined, {
2128
+ onClose: () => { },
2129
+ onCloseConfirmed: () => settle("finished"),
2130
+ onMessage: (event) => {
2131
+ this.onEvent?.(event);
2132
+ if (event.type === "didit:completed" || event.type === "didit:cancelled") {
2133
+ settle("finished");
2134
+ }
2135
+ },
2136
+ onIframeLoad: () => { }
2137
+ });
2138
+ SDKLogger.log("Launching required transaction action:", url);
2139
+ modal.open(url);
2140
+ }
2141
+ catch (error) {
2142
+ this._actionModal = null;
2143
+ this._actionModalSettle = null;
2144
+ throw error;
2145
+ }
2146
+ this._actionModal = modal;
2147
+ this._actionModalSettle = settle;
2148
+ });
2149
+ }
2150
+ handleModalClose() {
2151
+ SDKLogger.log("Modal close requested");
2152
+ }
2153
+ handleModalCloseConfirmed() {
2154
+ SDKLogger.log("Modal close confirmed");
2155
+ const sessionData = this.buildSessionData();
2156
+ this._modal?.close();
2157
+ this.reset();
2158
+ this.setState("idle");
2159
+ const result = {
2160
+ type: "cancelled",
2161
+ session: sessionData
2162
+ };
2163
+ this.onComplete?.(result);
2164
+ }
2165
+ handleIframeLoad() {
2166
+ SDKLogger.log("Iframe loaded");
2167
+ }
2168
+ emitInternalEvent(type, data) {
2169
+ const event = {
2170
+ type,
2171
+ data,
2172
+ timestamp: Date.now()
2173
+ };
2174
+ SDKLogger.log("Emitting internal event:", event);
2175
+ this.onEvent?.(event);
2176
+ }
2177
+ handleVerificationEvent(event) {
2178
+ SDKLogger.log("Verification event:", event);
2179
+ // Keep the session the flow told us about so a modal the user closes by
2180
+ // hand still reports the session it belongs to in the cancelled result.
2181
+ if (event.data?.sessionId) {
2182
+ this._sessionId = event.data.sessionId;
2183
+ }
2184
+ this.onEvent?.(event);
2185
+ switch (event.type) {
2186
+ case "didit:ready":
2187
+ SDKLogger.log("Verification iframe ready");
2188
+ break;
2189
+ case "didit:started":
2190
+ SDKLogger.log("User started verification");
2191
+ break;
2192
+ case "didit:step_started":
2193
+ SDKLogger.log("Step started:", event.data?.step);
2194
+ break;
2195
+ case "didit:step_completed":
2196
+ SDKLogger.log("Step completed:", event.data?.step, "-> next:", event.data?.nextStep);
2197
+ break;
2198
+ case "didit:media_started":
2199
+ SDKLogger.log("Media started:", event.data?.mediaType, "for step:", event.data?.step);
2200
+ break;
2201
+ case "didit:media_captured":
2202
+ SDKLogger.log("Media captured for step:", event.data?.step, "isAuto:", event.data?.isAuto);
2203
+ break;
2204
+ case "didit:document_selected":
2205
+ SDKLogger.log("Document selected:", event.data?.documentType, "country:", event.data?.country);
2206
+ break;
2207
+ case "didit:verification_submitted":
2208
+ SDKLogger.log("Verification submitted for step:", event.data?.step);
2209
+ break;
2210
+ case "didit:code_sent":
2211
+ SDKLogger.log("Code sent via:", event.data?.channel, "codeSize:", event.data?.codeSize);
2212
+ break;
2213
+ case "didit:code_verified":
2214
+ SDKLogger.log("Code verified via:", event.data?.channel);
2215
+ break;
2216
+ case "didit:status_updated":
2217
+ SDKLogger.log("Status updated:", event.data?.status, "step:", event.data?.step);
2218
+ break;
2219
+ case "didit:completed":
2220
+ this.handleVerificationCompleted(event);
2221
+ break;
2222
+ case "didit:cancelled":
2223
+ this.handleVerificationCancelled(event);
2224
+ break;
2225
+ case "didit:error":
2226
+ this.handleVerificationError(event);
2227
+ break;
2228
+ case "didit:step_changed":
2229
+ SDKLogger.log("Step changed:", event.data?.step);
2230
+ break;
2231
+ }
2232
+ }
2233
+ handleVerificationCompleted(event) {
2234
+ SDKLogger.log("Verification completed:", event.data);
2235
+ const sessionData = this.buildSessionData(event.data);
2236
+ if (this._configuration?.closeModalOnComplete) {
2237
+ this._modal?.close();
2238
+ this.reset();
2239
+ this.setState("idle");
2240
+ }
2241
+ const result = {
2242
+ type: "completed",
2243
+ session: sessionData
2244
+ };
2245
+ this.onComplete?.(result);
2246
+ }
2247
+ handleVerificationCancelled(event) {
2248
+ SDKLogger.log("Verification cancelled:", event.data);
2249
+ const sessionData = this.buildSessionData(event.data);
2250
+ this._modal?.close();
2251
+ this.reset();
2252
+ this.setState("idle");
2253
+ const result = {
2254
+ type: "cancelled",
2255
+ session: sessionData
2256
+ };
2257
+ this.onComplete?.(result);
2258
+ }
2259
+ handleVerificationError(event) {
2260
+ SDKLogger.log("Verification error:", event.data);
2261
+ }
2262
+ handleError(error) {
2263
+ SDKLogger.error("SDK error:", error);
2264
+ let verificationError;
2265
+ if (error instanceof Error) {
2266
+ verificationError = createVerificationError("unknown", error.message);
2267
+ }
2268
+ else {
2269
+ verificationError = createVerificationError("unknown", "An unknown error occurred");
2270
+ }
2271
+ this._modal?.close();
2272
+ this._modal = null;
2273
+ // Clear what the failed launch left behind, then report the error as the
2274
+ // state the SDK is in: reset() alone would leave callers reading "idle"
2275
+ // with no error message right after onStateChange("error").
2276
+ this.reset();
2277
+ this._errorMessage = verificationError.message;
2278
+ this.setState("error");
2279
+ const result = {
2280
+ type: "failed",
2281
+ error: verificationError
2282
+ };
2283
+ this.onComplete?.(result);
2284
+ }
2285
+ setState(state) {
2286
+ const previousState = this._state;
2287
+ this._state = state;
2288
+ if (previousState !== state) {
2289
+ SDKLogger.log("State changed:", previousState, "->", state);
2290
+ this.onStateChange?.(state, this._errorMessage);
2291
+ }
2292
+ }
2293
+ reset() {
2294
+ this._sessionId = undefined;
2295
+ this._url = undefined;
2296
+ this._errorMessage = undefined;
2297
+ this._configuration = undefined;
2298
+ }
2299
+ buildSessionData(eventData) {
2300
+ const sessionId = eventData?.sessionId || this._sessionId;
2301
+ if (!sessionId) {
2302
+ return undefined;
2303
+ }
2304
+ return {
2305
+ sessionId,
2306
+ status: (eventData?.status || "Pending")
2307
+ };
2308
+ }
2309
+ }
2310
+ DiditSdk._instance = null;
2311
+
2312
+ export { DEFAULT_TRANSACTION_BASE_URL, DiditSdk, DiditTransactionError, SDK_VERSION, DiditSdk as default };
2313
+ //# sourceMappingURL=didit-sdk.module.js.map