@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.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Didit SDK for Web v0.4.0
2
+ * Didit SDK for Web v0.5.1
3
3
  * (c) 2026 Didit
4
4
  * @license MIT
5
5
  */
@@ -7,6 +7,8 @@
7
7
 
8
8
  Object.defineProperty(exports, '__esModule', { value: true });
9
9
 
10
+ var signals = require('@didit-protocol/signals');
11
+
10
12
  const DEFAULT_CONFIG = {
11
13
  zIndex: 9999,
12
14
  showCloseButton: true,
@@ -17,12 +19,22 @@ const CSS_CLASSES = {
17
19
  container: "didit-modal-container",
18
20
  iframe: "didit-verification-iframe",
19
21
  closeButton: "didit-close-button",
22
+ closeIcon: "didit-close-icon",
23
+ closeIconLegacy: "didit-close-icon-legacy",
24
+ flowSized: "didit-flow-sized",
20
25
  loading: "didit-loading",
21
26
  confirmOverlay: "didit-confirm-overlay",
22
27
  confirmBox: "didit-confirm-box",
23
28
  embedded: "didit-embedded"
24
29
  };
25
- const SDK_VERSION = "0.4.0";
30
+ const SDK_VERSION = "0.5.1";
31
+ /**
32
+ * The permissions the verification iframe gets, in a modal and embedded:
33
+ * camera and microphone for capture, clipboard-write for the flow's copy
34
+ * buttons, and digital-credentials-get so the flow can ask a digital ID wallet
35
+ * (Google Wallet) through the W3C Digital Credentials API from inside the iframe.
36
+ */
37
+ const IFRAME_ALLOW = "camera; microphone; fullscreen; autoplay; encrypted-media; geolocation; clipboard-write; digital-credentials-get";
26
38
  /** The verification-URL query parameter each camera option is forwarded as. */
27
39
  const CAMERA_QUERY_PARAMS = {
28
40
  defaultDocumentCamera: "document_camera",
@@ -31,6 +43,25 @@ const CAMERA_QUERY_PARAMS = {
31
43
  showLivenessCameraSwitchButton: "liveness_camera_switch"
32
44
  };
33
45
  const CAMERA_LENSES = ["front", "back"];
46
+ /**
47
+ * The verification-URL query parameters that tell the hosted flow how the SDK
48
+ * presents it: `sdk_presentation=modal|embedded` and, in a modal,
49
+ * `sdk_close_button=true|false` (whether the SDK draws its close button over
50
+ * the flow's top bar).
51
+ */
52
+ const PRESENTATION_QUERY_PARAMS = {
53
+ presentation: "sdk_presentation",
54
+ closeButton: "sdk_close_button"
55
+ };
56
+ /**
57
+ * Posted by the hosted flow when it lays itself out for the modal, with
58
+ * `data: { contentHeight, colorScheme?, dir? }`. The modal then grows to the
59
+ * handoff card on a computer and follows the content height in a narrow
60
+ * window. Handled by the modal and never delivered to `onEvent`.
61
+ */
62
+ const LAYOUT_MESSAGE_TYPE = "didit:layout";
63
+ /** Languages the hosted flow lays out right to left. */
64
+ const RTL_LANGUAGES = ["ar", "fa", "he"];
34
65
  const languages = [
35
66
  "ar",
36
67
  "bg",
@@ -147,16 +178,16 @@ const CAMERA_SWITCH_OPTIONS = ["showDocumentCameraSwitchButton", "showLivenessCa
147
178
  * `defaultLivenessCamera` -> `liveness_camera=<lens>`,
148
179
  * `showDocumentCameraSwitchButton` -> `document_camera_switch=true|false`,
149
180
  * `showLivenessCameraSwitchButton` -> `liveness_camera_switch=true|false`.
181
+ * How the SDK presents the flow is always added: `sdk_presentation=modal|embedded`
182
+ * and, in a modal, `sdk_close_button=true|false`.
150
183
  * Each parameter is set (not appended) so the configuration wins over a value
151
184
  * already on the URL; existing query parameters and the hash are kept. A
152
185
  * value of the wrong shape is ignored with a warning rather than forwarded,
153
186
  * and a URL the browser cannot parse is returned as it came (the modal
154
187
  * reports it when it loads).
155
188
  */
156
- function buildVerificationUrl(url, configuration) {
157
- if (!configuration)
158
- return url;
159
- const params = [];
189
+ function buildVerificationUrl(url, configuration = {}) {
190
+ const params = presentationParams(configuration);
160
191
  for (const option of CAMERA_LENS_OPTIONS) {
161
192
  const value = configuration[option];
162
193
  if (value === undefined)
@@ -177,8 +208,6 @@ function buildVerificationUrl(url, configuration) {
177
208
  }
178
209
  params.push([CAMERA_QUERY_PARAMS[option], value ? "true" : "false"]);
179
210
  }
180
- if (params.length === 0)
181
- return url;
182
211
  try {
183
212
  const parsed = new URL(url);
184
213
  params.forEach(([name, value]) => parsed.searchParams.set(name, value));
@@ -188,6 +217,19 @@ function buildVerificationUrl(url, configuration) {
188
217
  return url;
189
218
  }
190
219
  }
220
+ function presentationParams(configuration) {
221
+ if (configuration.embedded) {
222
+ return [[PRESENTATION_QUERY_PARAMS.presentation, "embedded"]];
223
+ }
224
+ const closeButton = configuration.showCloseButton ?? DEFAULT_CONFIG.showCloseButton;
225
+ return [
226
+ [PRESENTATION_QUERY_PARAMS.presentation, "modal"],
227
+ [PRESENTATION_QUERY_PARAMS.closeButton, closeButton ? "true" : "false"]
228
+ ];
229
+ }
230
+ function isRtlLanguage(language) {
231
+ return RTL_LANGUAGES.includes(language.split("-")[0]);
232
+ }
191
233
  function detectLanguageFromUrl(url) {
192
234
  try {
193
235
  const { pathname } = new URL(url);
@@ -659,8 +701,11 @@ class VerificationModal {
659
701
  this.iframe = null;
660
702
  this.loadingEl = null;
661
703
  this.confirmOverlay = null;
704
+ this.confirmationTrigger = null;
662
705
  this.boundHandleMessage = null;
663
706
  this.boundHandleKeydown = null;
707
+ this.boundHandleFocusChange = null;
708
+ this.confirmationFocusTimeout = null;
664
709
  this.embedded = false;
665
710
  this.embeddedContainer = null;
666
711
  this.language = "en";
@@ -820,6 +865,7 @@ class VerificationModal {
820
865
  transform: scale(0.95);
821
866
  transition: transform 0.15s ease-out;
822
867
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
868
+ outline: none;
823
869
  }
824
870
 
825
871
  .${CSS_CLASSES.confirmOverlay}.active .${CSS_CLASSES.confirmBox} {
@@ -847,7 +893,7 @@ class VerificationModal {
847
893
  gap: 1rem;
848
894
  }
849
895
 
850
- .didit-confirm-actions button {
896
+ .didit-confirm-actions [data-action="continue"] {
851
897
  background: #2563eb;
852
898
  color: #fff;
853
899
  border: none;
@@ -859,11 +905,16 @@ class VerificationModal {
859
905
  transition: background 0.15s ease;
860
906
  }
861
907
 
862
- .didit-confirm-actions button:hover {
908
+ .didit-confirm-actions [data-action="continue"]:hover {
863
909
  background: #1d4ed8;
864
910
  }
865
911
 
866
- .didit-confirm-actions span {
912
+ .didit-confirm-actions [data-action="exit"] {
913
+ background: transparent;
914
+ border: none;
915
+ font-family: inherit;
916
+ font-weight: inherit;
917
+ line-height: inherit;
867
918
  color: #666;
868
919
  font-size: 0.875rem;
869
920
  cursor: pointer;
@@ -871,10 +922,15 @@ class VerificationModal {
871
922
  transition: color 0.15s ease;
872
923
  }
873
924
 
874
- .didit-confirm-actions span:hover {
925
+ .didit-confirm-actions [data-action="exit"]:hover {
875
926
  color: #1a1a2e;
876
927
  }
877
928
 
929
+ .didit-confirm-actions button:focus-visible {
930
+ outline: 2px solid #2567ff;
931
+ outline-offset: 2px;
932
+ }
933
+
878
934
  @media (max-width: 540px) {
879
935
  .${CSS_CLASSES.overlay} {
880
936
  padding: 0;
@@ -894,6 +950,138 @@ class VerificationModal {
894
950
  }
895
951
  }
896
952
 
953
+ /*
954
+ * Once the hosted flow reports its layout (didit:layout), the modal
955
+ * grows to the handoff card on a computer (960 x 660, at most 90% of
956
+ * the window) and follows the flow's content height in a narrow
957
+ * window. Colours are the design system tokens named beside them.
958
+ */
959
+ .${CSS_CLASSES.container}.${CSS_CLASSES.flowSized} {
960
+ --didit-ground: #ffffff; /* site-ground */
961
+ --didit-heading: #1a1a1a; /* c-heading */
962
+ --didit-accent: #2567ff; /* c-accent */
963
+ --didit-hover: rgba(120, 120, 128, 0.08); /* c-hover */
964
+ --didit-close-fill: rgba(0, 0, 0, 0.06);
965
+ --didit-drop: rgba(17, 24, 39, 0.35);
966
+ --didit-ring: rgba(0, 0, 0, 0.06);
967
+ max-width: 500px;
968
+ background: var(--didit-ground);
969
+ box-shadow: 0 30px 80px -24px var(--didit-drop), 0 0 0 1px var(--didit-ring);
970
+ }
971
+
972
+ .${CSS_CLASSES.container}.${CSS_CLASSES.flowSized}[data-didit-theme="dark"] {
973
+ --didit-ground: #0b0b0d;
974
+ --didit-heading: #f5f5f7;
975
+ --didit-accent: #4d8bff;
976
+ --didit-hover: rgba(255, 255, 255, 0.06);
977
+ --didit-close-fill: rgba(255, 255, 255, 0.06);
978
+ --didit-drop: rgba(0, 0, 0, 0.55); /* c-shadow-pop, dark */
979
+ --didit-ring: rgba(255, 255, 255, 0.08); /* c-shadow-pop, dark */
980
+ }
981
+
982
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.iframe} {
983
+ height: var(--didit-flow-height);
984
+ max-height: 90vh;
985
+ max-height: 90dvh;
986
+ }
987
+
988
+ .${CSS_CLASSES.closeIcon} {
989
+ display: none;
990
+ }
991
+
992
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.closeButton} {
993
+ top: 8px;
994
+ right: 8px;
995
+ width: 44px;
996
+ height: 44px;
997
+ display: flex;
998
+ align-items: center;
999
+ justify-content: center;
1000
+ border-radius: 50%;
1001
+ background: var(--didit-close-fill);
1002
+ color: var(--didit-heading);
1003
+ }
1004
+
1005
+ .${CSS_CLASSES.flowSized}[data-didit-dir="rtl"] .${CSS_CLASSES.closeButton} {
1006
+ right: auto;
1007
+ left: 8px;
1008
+ }
1009
+
1010
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.closeButton}:hover,
1011
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.closeButton}:focus {
1012
+ background: var(--didit-close-fill);
1013
+ opacity: 1;
1014
+ }
1015
+
1016
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.closeButton}:hover {
1017
+ background-image: linear-gradient(var(--didit-hover), var(--didit-hover));
1018
+ }
1019
+
1020
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.closeButton}:focus-visible {
1021
+ outline: 2px solid var(--didit-accent);
1022
+ outline-offset: 2px;
1023
+ }
1024
+
1025
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.closeIconLegacy} {
1026
+ display: none;
1027
+ }
1028
+
1029
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.closeButton} .${CSS_CLASSES.closeIcon} {
1030
+ display: block;
1031
+ stroke: currentColor;
1032
+ stroke-width: 1.75;
1033
+ stroke-linejoin: round;
1034
+ }
1035
+
1036
+ /*
1037
+ * The exit confirmation is sized in rem, so with a large text size it
1038
+ * can be taller than a short flow: it scrolls inside the modal instead
1039
+ * of being clipped, and its width and actions follow a larger text size.
1040
+ * It never grows wider than the modal: a long word wraps instead.
1041
+ */
1042
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.confirmOverlay} {
1043
+ padding: 1rem;
1044
+ overflow-y: auto;
1045
+ }
1046
+
1047
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.confirmBox} {
1048
+ min-width: 0;
1049
+ max-width: max(300px, 18.75rem);
1050
+ margin: auto;
1051
+ overflow-wrap: anywhere;
1052
+ /* Focusing the dialog scrolls it into view start-aligned; this keeps
1053
+ * the overlay's top padding visible so the title is never clipped. */
1054
+ scroll-margin-top: 1rem;
1055
+ }
1056
+
1057
+ .${CSS_CLASSES.flowSized} .didit-confirm-actions {
1058
+ flex-wrap: wrap;
1059
+ }
1060
+
1061
+ @media (min-width: 1024px) {
1062
+ .${CSS_CLASSES.container}.${CSS_CLASSES.flowSized} {
1063
+ width: 90vw;
1064
+ max-width: 960px;
1065
+ }
1066
+
1067
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.iframe} {
1068
+ height: 660px;
1069
+ }
1070
+ }
1071
+
1072
+ @media (max-width: 540px) {
1073
+ .${CSS_CLASSES.container}.${CSS_CLASSES.flowSized} {
1074
+ max-width: 100%;
1075
+ box-shadow: none;
1076
+ }
1077
+
1078
+ .${CSS_CLASSES.flowSized} .${CSS_CLASSES.iframe} {
1079
+ height: 100vh;
1080
+ height: 100dvh;
1081
+ max-height: none;
1082
+ }
1083
+ }
1084
+
897
1085
  .${CSS_CLASSES.embedded} {
898
1086
  position: relative;
899
1087
  width: 100%;
@@ -940,28 +1128,33 @@ class VerificationModal {
940
1128
  closeBtn.className = CSS_CLASSES.closeButton;
941
1129
  closeBtn.setAttribute("aria-label", t.ariaLabelClose);
942
1130
  closeBtn.innerHTML = `
943
- <svg width="14" height="14" viewBox="0 0 14 14">
1131
+ <svg class="${CSS_CLASSES.closeIconLegacy}" width="14" height="14" viewBox="0 0 14 14">
944
1132
  <line x1="1" y1="1" x2="13" y2="13" />
945
1133
  <line x1="13" y1="1" x2="1" y2="13" />
946
1134
  </svg>
1135
+ <svg class="${CSS_CLASSES.closeIcon}" width="18" height="18" viewBox="0 0 24 24" fill="none">
1136
+ <path d="M7 7.03882L17 16.9611" />
1137
+ <path d="M7.03968 17L16.9619 7" />
1138
+ </svg>
947
1139
  `;
948
- closeBtn.addEventListener("click", () => this.handleCloseRequest());
1140
+ closeBtn.addEventListener("click", () => this.handleCloseRequest(closeBtn));
949
1141
  this.container.appendChild(closeBtn);
950
1142
  }
951
1143
  this.iframe = document.createElement("iframe");
952
1144
  this.iframe.className = CSS_CLASSES.iframe;
953
- this.iframe.setAttribute("allow", "camera; microphone; fullscreen; autoplay; encrypted-media; geolocation");
1145
+ this.iframe.setAttribute("allow", IFRAME_ALLOW);
954
1146
  this.iframe.setAttribute("title", t.ariaLabelModal);
955
1147
  this.iframe.addEventListener("load", () => this.handleIframeLoad());
956
1148
  this.confirmOverlay = document.createElement("div");
957
1149
  this.confirmOverlay.className = CSS_CLASSES.confirmOverlay;
958
1150
  this.confirmOverlay.innerHTML = `
959
- <div class="${CSS_CLASSES.confirmBox}">
960
- <h3>${t.exitTitle}</h3>
961
- <p>${t.exitMessage}</p>
1151
+ <div class="${CSS_CLASSES.confirmBox}" role="dialog" aria-modal="true" tabindex="-1"
1152
+ aria-labelledby="${this.modalId}-exit-title" aria-describedby="${this.modalId}-exit-message">
1153
+ <h3 id="${this.modalId}-exit-title">${t.exitTitle}</h3>
1154
+ <p id="${this.modalId}-exit-message">${t.exitMessage}</p>
962
1155
  <div class="didit-confirm-actions">
963
1156
  <button type="button" data-action="continue">${t.continueButton}</button>
964
- <span data-action="exit">${t.exitButton}</span>
1157
+ <button type="button" data-action="exit">${t.exitButton}</button>
965
1158
  </div>
966
1159
  </div>
967
1160
  `;
@@ -998,7 +1191,7 @@ class VerificationModal {
998
1191
  `;
999
1192
  this.iframe = document.createElement("iframe");
1000
1193
  this.iframe.className = CSS_CLASSES.iframe;
1001
- this.iframe.setAttribute("allow", "camera; microphone; fullscreen; autoplay; encrypted-media; geolocation");
1194
+ this.iframe.setAttribute("allow", IFRAME_ALLOW);
1002
1195
  this.iframe.setAttribute("title", getTranslations(this.language).ariaLabelModal);
1003
1196
  this.iframe.addEventListener("load", () => this.handleIframeLoad());
1004
1197
  this.container.appendChild(this.loadingEl);
@@ -1016,6 +1209,23 @@ class VerificationModal {
1016
1209
  window.addEventListener("message", this.boundHandleMessage);
1017
1210
  this.boundHandleKeydown = this.handleKeydown.bind(this);
1018
1211
  document.addEventListener("keydown", this.boundHandleKeydown);
1212
+ this.boundHandleFocusChange = () => {
1213
+ if (!this.state.showConfirmation || !this.isTopmost())
1214
+ return;
1215
+ // An iframe can take focus without a focusin event in its parent document.
1216
+ // Wait until its focus transition finishes before moving focus back.
1217
+ if (this.confirmationFocusTimeout !== null)
1218
+ window.clearTimeout(this.confirmationFocusTimeout);
1219
+ this.confirmationFocusTimeout = window.setTimeout(() => {
1220
+ this.confirmationFocusTimeout = null;
1221
+ if (this.state.showConfirmation && this.isTopmost() && !this.confirmOverlay?.contains(document.activeElement)) {
1222
+ this.focusConfirmation();
1223
+ }
1224
+ }, 0);
1225
+ };
1226
+ document.addEventListener("focusin", this.boundHandleFocusChange);
1227
+ document.addEventListener("focusout", this.boundHandleFocusChange);
1228
+ window.addEventListener("blur", this.boundHandleFocusChange);
1019
1229
  }
1020
1230
  removeEventListeners() {
1021
1231
  if (this.boundHandleMessage) {
@@ -1026,6 +1236,12 @@ class VerificationModal {
1026
1236
  document.removeEventListener("keydown", this.boundHandleKeydown);
1027
1237
  this.boundHandleKeydown = null;
1028
1238
  }
1239
+ if (this.boundHandleFocusChange) {
1240
+ document.removeEventListener("focusin", this.boundHandleFocusChange);
1241
+ document.removeEventListener("focusout", this.boundHandleFocusChange);
1242
+ window.removeEventListener("blur", this.boundHandleFocusChange);
1243
+ this.boundHandleFocusChange = null;
1244
+ }
1029
1245
  }
1030
1246
  pushToTop() {
1031
1247
  const modals = VerificationModal.openModals;
@@ -1077,8 +1293,55 @@ class VerificationModal {
1077
1293
  this.handleCloseRequest();
1078
1294
  return;
1079
1295
  }
1296
+ if (messageData.type === LAYOUT_MESSAGE_TYPE) {
1297
+ const layout = this.readFlowLayout(messageData.data);
1298
+ if (layout) {
1299
+ this.applyFlowLayout(layout);
1300
+ }
1301
+ else {
1302
+ SDKLogger.warn("Ignoring a layout message without a positive contentHeight:", messageData.data);
1303
+ }
1304
+ return;
1305
+ }
1080
1306
  this.callbacks.onMessage(messageData);
1081
1307
  }
1308
+ /**
1309
+ * Reads a didit:layout message's data. Without a positive contentHeight the
1310
+ * message is ignored; a missing or unknown colorScheme follows the device,
1311
+ * and a missing or unknown dir follows the verification URL's language.
1312
+ */
1313
+ readFlowLayout(data) {
1314
+ const fields = typeof data === "object" && data !== null ? data : {};
1315
+ const { contentHeight, colorScheme, dir } = fields;
1316
+ if (typeof contentHeight !== "number" || !Number.isFinite(contentHeight) || contentHeight <= 0) {
1317
+ return null;
1318
+ }
1319
+ const prefersDark = window.matchMedia?.("(prefers-color-scheme: dark)").matches ?? false;
1320
+ return {
1321
+ contentHeight: Math.ceil(contentHeight),
1322
+ colorScheme: colorScheme === "light" || colorScheme === "dark" ? colorScheme : prefersDark ? "dark" : "light",
1323
+ dir: dir === "ltr" || dir === "rtl" ? dir : isRtlLanguage(this.language) ? "rtl" : "ltr"
1324
+ };
1325
+ }
1326
+ /** Embedded mode keeps filling the integrator's host element, whatever the flow reports. */
1327
+ applyFlowLayout(layout) {
1328
+ if (this.embedded || !this.container)
1329
+ return;
1330
+ SDKLogger.log("Flow layout:", layout);
1331
+ this.container.classList.add(CSS_CLASSES.flowSized);
1332
+ this.container.style.setProperty("--didit-flow-height", `${layout.contentHeight}px`);
1333
+ this.container.dataset.diditTheme = layout.colorScheme;
1334
+ this.container.dataset.diditDir = layout.dir;
1335
+ }
1336
+ /** Back to the fixed 500 x 700 modal until the newly loaded flow reports its layout. */
1337
+ resetFlowLayout() {
1338
+ if (this.embedded || !this.container)
1339
+ return;
1340
+ this.container.classList.remove(CSS_CLASSES.flowSized);
1341
+ this.container.style.removeProperty("--didit-flow-height");
1342
+ delete this.container.dataset.diditTheme;
1343
+ delete this.container.dataset.diditDir;
1344
+ }
1082
1345
  handleKeydown(event) {
1083
1346
  if (!this.state.isOpen)
1084
1347
  return;
@@ -1088,6 +1351,18 @@ class VerificationModal {
1088
1351
  // of the verification modal underneath it).
1089
1352
  if (!this.isTopmost())
1090
1353
  return;
1354
+ if (event.key === "Tab" && this.state.showConfirmation) {
1355
+ const buttons = Array.from(this.confirmOverlay?.querySelectorAll("button") ?? []);
1356
+ if (buttons.length) {
1357
+ event.preventDefault();
1358
+ const current = buttons.findIndex((button) => button === document.activeElement);
1359
+ const next = event.shiftKey
1360
+ ? (current <= 0 ? buttons.length - 1 : current - 1)
1361
+ : (current + 1) % buttons.length;
1362
+ buttons[next].focus();
1363
+ }
1364
+ return;
1365
+ }
1091
1366
  if (event.key === "Escape") {
1092
1367
  event.preventDefault();
1093
1368
  if (this.state.showConfirmation) {
@@ -1105,22 +1380,67 @@ class VerificationModal {
1105
1380
  this.callbacks.onIframeLoad();
1106
1381
  }
1107
1382
  }
1108
- handleCloseRequest() {
1383
+ handleCloseRequest(trigger) {
1109
1384
  if (this.config.showExitConfirmation) {
1110
- this.showConfirmation();
1385
+ this.showConfirmation(trigger);
1111
1386
  }
1112
1387
  else {
1113
1388
  this.callbacks.onCloseConfirmed();
1114
1389
  }
1115
1390
  }
1116
- showConfirmation() {
1391
+ showConfirmation(trigger) {
1392
+ if (!this.confirmOverlay || this.state.showConfirmation)
1393
+ return;
1394
+ const activeElement = document.activeElement;
1395
+ this.confirmationTrigger = trigger ?? (activeElement instanceof HTMLElement && activeElement !== document.body
1396
+ ? activeElement
1397
+ : this.container?.querySelector(`.${CSS_CLASSES.closeButton}`) ?? this.iframe);
1117
1398
  this.state.showConfirmation = true;
1118
- this.confirmOverlay?.classList.add("active");
1399
+ this.confirmOverlay.classList.add("active");
1400
+ if (this.iframe)
1401
+ this.iframe.inert = true;
1402
+ const close = this.container?.querySelector(`.${CSS_CLASSES.closeButton}`);
1403
+ if (close)
1404
+ close.inert = true;
1405
+ // A confirmation scrolled at a large text size opens again at its title.
1406
+ this.confirmOverlay.scrollTop = 0;
1407
+ if (this.isTopmost())
1408
+ this.focusConfirmation();
1119
1409
  this.callbacks.onClose();
1120
1410
  }
1121
- hideConfirmation() {
1411
+ focusConfirmation() {
1412
+ this.confirmOverlay?.querySelector(`.${CSS_CLASSES.confirmBox}`)?.focus({ preventScroll: true });
1413
+ }
1414
+ hideConfirmation(restoreFocus = true) {
1415
+ if (this.confirmationFocusTimeout !== null) {
1416
+ window.clearTimeout(this.confirmationFocusTimeout);
1417
+ this.confirmationFocusTimeout = null;
1418
+ }
1419
+ if (!this.state.showConfirmation)
1420
+ return;
1122
1421
  this.state.showConfirmation = false;
1123
1422
  this.confirmOverlay?.classList.remove("active");
1423
+ if (this.iframe)
1424
+ this.iframe.inert = false;
1425
+ const close = this.container?.querySelector(`.${CSS_CLASSES.closeButton}`);
1426
+ if (close)
1427
+ close.inert = false;
1428
+ const trigger = this.confirmationTrigger;
1429
+ this.confirmationTrigger = null;
1430
+ if (restoreFocus && this.isTopmost() && trigger?.isConnected) {
1431
+ if (trigger === this.iframe) {
1432
+ // Firefox needs a browser task to reactivate an inert cross-origin frame.
1433
+ this.confirmationFocusTimeout = window.setTimeout(() => {
1434
+ this.confirmationFocusTimeout = null;
1435
+ if (this.state.isOpen && !this.state.showConfirmation && this.isTopmost() && trigger.isConnected) {
1436
+ trigger.focus({ preventScroll: true });
1437
+ }
1438
+ }, 0);
1439
+ }
1440
+ else {
1441
+ trigger.focus({ preventScroll: true });
1442
+ }
1443
+ }
1124
1444
  }
1125
1445
  confirmExit() {
1126
1446
  this.hideConfirmation();
@@ -1142,9 +1462,9 @@ class VerificationModal {
1142
1462
  this.setupEventListeners();
1143
1463
  SDKLogger.log("Opening with URL:", verificationUrl);
1144
1464
  this.state.isLoading = true;
1145
- this.state.showConfirmation = false;
1465
+ this.hideConfirmation();
1146
1466
  this.loadingEl?.classList.remove("hidden");
1147
- this.confirmOverlay?.classList.remove("active");
1467
+ this.resetFlowLayout();
1148
1468
  if (this.iframe) {
1149
1469
  this.iframe.src = verificationUrl;
1150
1470
  }
@@ -1167,11 +1487,13 @@ class VerificationModal {
1167
1487
  }
1168
1488
  close() {
1169
1489
  SDKLogger.log("Closing");
1490
+ this.hideConfirmation(false);
1170
1491
  this.state.isOpen = false;
1171
1492
  this.state.isLoading = true;
1172
1493
  this.state.showConfirmation = false;
1173
1494
  this.removeFromStack();
1174
1495
  this.removeEventListeners();
1496
+ this.resetFlowLayout();
1175
1497
  if (this.iframe) {
1176
1498
  this.iframe.src = "about:blank";
1177
1499
  }
@@ -1213,344 +1535,6 @@ class VerificationModal {
1213
1535
  */
1214
1536
  VerificationModal.openModals = [];
1215
1537
 
1216
- /**
1217
- * Minimal self-contained port of the didit-fp-v2 device fingerprint used by the
1218
- * Didit verification frontend. It collects stable browser signals, hashes them
1219
- * with WebCrypto SHA-256 and persists a random device id in localStorage with a
1220
- * cookie fallback. The payload shape matches the didit-fp-v2 schema so the Didit
1221
- * backend middleware parses it identically to the verification flow:
1222
- *
1223
- * - headers: X-Didit-PID (persistent id) and X-Didit-FP-Hash (composite hash)
1224
- * - body: a top-level `fingerprint_v2` field carrying the full payload
1225
- */
1226
- const PERSISTENT_ID_STORAGE_KEY = "didit-pid-v1";
1227
- const PERSISTENT_ID_COOKIE_NAME = "didit_pid";
1228
- const PERSISTENT_ID_COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 365 * 2;
1229
- const PERSISTENT_ID_BYTE_LENGTH = 16;
1230
- const BASE64URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
1231
- let memoryPersistentId = null;
1232
- let cachedPayload = null;
1233
- let cachedPayloadPromise = null;
1234
- function bytesToBase64Url(bytes) {
1235
- let output = "";
1236
- let i = 0;
1237
- for (; i + 2 < bytes.length; i += 3) {
1238
- const triplet = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];
1239
- output += BASE64URL_ALPHABET[(triplet >> 18) & 0x3f];
1240
- output += BASE64URL_ALPHABET[(triplet >> 12) & 0x3f];
1241
- output += BASE64URL_ALPHABET[(triplet >> 6) & 0x3f];
1242
- output += BASE64URL_ALPHABET[triplet & 0x3f];
1243
- }
1244
- if (i < bytes.length) {
1245
- const remaining = bytes.length - i;
1246
- const a = bytes[i];
1247
- const b = remaining > 1 ? bytes[i + 1] : 0;
1248
- const triplet = (a << 16) | (b << 8);
1249
- output += BASE64URL_ALPHABET[(triplet >> 18) & 0x3f];
1250
- output += BASE64URL_ALPHABET[(triplet >> 12) & 0x3f];
1251
- if (remaining > 1) {
1252
- output += BASE64URL_ALPHABET[(triplet >> 6) & 0x3f];
1253
- }
1254
- }
1255
- return output;
1256
- }
1257
- function randomBytes(length) {
1258
- if (typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function") {
1259
- const buffer = new Uint8Array(length);
1260
- crypto.getRandomValues(buffer);
1261
- return buffer;
1262
- }
1263
- const fallback = new Uint8Array(length);
1264
- for (let i = 0; i < length; i++) {
1265
- fallback[i] = Math.floor(Math.random() * 256);
1266
- }
1267
- return fallback;
1268
- }
1269
- function randomBase64Url(byteLength) {
1270
- return bytesToBase64Url(randomBytes(byteLength));
1271
- }
1272
- // SHA-256 truncated to the leading 128 bits, base64url-encoded (22 chars).
1273
- // Same construction as the didit-fp-v2 composite hash in the verification frontend.
1274
- async function sha256_128(input) {
1275
- if (typeof crypto === "undefined" || !crypto.subtle) {
1276
- throw new Error("WebCrypto SubtleCrypto is not available");
1277
- }
1278
- const bytes = new TextEncoder().encode(input);
1279
- const view = new Uint8Array(bytes.byteLength);
1280
- view.set(bytes);
1281
- const digest = await crypto.subtle.digest("SHA-256", view.buffer);
1282
- return bytesToBase64Url(new Uint8Array(digest).slice(0, 16));
1283
- }
1284
- // FNV-1a 32-bit fallback hash, only used when WebCrypto is unavailable.
1285
- function fnv1a32(value) {
1286
- let hash = 0x811c9dc5;
1287
- for (let i = 0; i < value.length; i++) {
1288
- hash ^= value.charCodeAt(i);
1289
- hash = Math.imul(hash, 0x01000193);
1290
- }
1291
- return (hash >>> 0).toString(16).padStart(8, "0");
1292
- }
1293
- function stableStringify(value) {
1294
- if (value === null || value === undefined)
1295
- return JSON.stringify(value ?? null);
1296
- if (Array.isArray(value))
1297
- return `[${value.map((v) => stableStringify(v)).join(",")}]`;
1298
- if (typeof value === "object") {
1299
- const keys = Object.keys(value).sort();
1300
- const parts = keys.map((k) => `${JSON.stringify(k)}:${stableStringify(value[k])}`);
1301
- return `{${parts.join(",")}}`;
1302
- }
1303
- return JSON.stringify(value);
1304
- }
1305
- function isValidPersistentId(value) {
1306
- return typeof value === "string" && /^[A-Za-z0-9_-]{20,32}$/.test(value);
1307
- }
1308
- function readLocalStorageId() {
1309
- try {
1310
- if (typeof localStorage === "undefined")
1311
- return null;
1312
- const value = localStorage.getItem(PERSISTENT_ID_STORAGE_KEY);
1313
- return isValidPersistentId(value) ? value : null;
1314
- }
1315
- catch {
1316
- return null;
1317
- }
1318
- }
1319
- function writeLocalStorageId(id) {
1320
- try {
1321
- if (typeof localStorage === "undefined")
1322
- return;
1323
- localStorage.setItem(PERSISTENT_ID_STORAGE_KEY, id);
1324
- }
1325
- catch {
1326
- // Storage may be blocked (private mode, storage policies); cookie layer still applies.
1327
- }
1328
- }
1329
- function readCookieId() {
1330
- try {
1331
- if (typeof document === "undefined" || !document.cookie)
1332
- return null;
1333
- const prefix = `${PERSISTENT_ID_COOKIE_NAME}=`;
1334
- for (const part of document.cookie.split(";")) {
1335
- const trimmed = part.trim();
1336
- if (trimmed.startsWith(prefix)) {
1337
- const value = decodeURIComponent(trimmed.substring(prefix.length));
1338
- return isValidPersistentId(value) ? value : null;
1339
- }
1340
- }
1341
- return null;
1342
- }
1343
- catch {
1344
- return null;
1345
- }
1346
- }
1347
- function writeCookieId(id) {
1348
- try {
1349
- if (typeof document === "undefined")
1350
- return;
1351
- const isSecure = typeof location !== "undefined" && location.protocol === "https:";
1352
- const attributes = [
1353
- `${PERSISTENT_ID_COOKIE_NAME}=${encodeURIComponent(id)}`,
1354
- "Path=/",
1355
- `Max-Age=${PERSISTENT_ID_COOKIE_MAX_AGE_SECONDS}`,
1356
- "SameSite=Lax"
1357
- ];
1358
- if (isSecure)
1359
- attributes.push("Secure");
1360
- document.cookie = attributes.join("; ");
1361
- }
1362
- catch {
1363
- // Cookies may be blocked; localStorage layer still applies.
1364
- }
1365
- }
1366
- function loadOrCreatePersistentId() {
1367
- const fromLocalStorage = readLocalStorageId();
1368
- const fromCookie = readCookieId();
1369
- let id;
1370
- let sources;
1371
- let wasCreated = false;
1372
- if (fromLocalStorage) {
1373
- id = fromLocalStorage;
1374
- sources = fromCookie === fromLocalStorage ? ["localStorage", "cookie"] : ["localStorage"];
1375
- }
1376
- else if (fromCookie) {
1377
- id = fromCookie;
1378
- sources = ["cookie"];
1379
- }
1380
- else if (memoryPersistentId && isValidPersistentId(memoryPersistentId)) {
1381
- id = memoryPersistentId;
1382
- sources = ["memory"];
1383
- }
1384
- else {
1385
- id = randomBase64Url(PERSISTENT_ID_BYTE_LENGTH);
1386
- sources = ["fresh"];
1387
- wasCreated = true;
1388
- }
1389
- memoryPersistentId = id;
1390
- // Self-heal any layer that was missing or mismatched.
1391
- if (fromLocalStorage !== id)
1392
- writeLocalStorageId(id);
1393
- if (fromCookie !== id)
1394
- writeCookieId(id);
1395
- return { id, sources, wasCreated };
1396
- }
1397
- function collectNavigatorSignals() {
1398
- const nav = typeof navigator !== "undefined" ? navigator : null;
1399
- const scr = typeof screen !== "undefined" ? screen : null;
1400
- let timeZone = null;
1401
- try {
1402
- timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone ?? null;
1403
- }
1404
- catch {
1405
- timeZone = null;
1406
- }
1407
- const uaData = nav
1408
- ? nav
1409
- .userAgentData
1410
- : undefined;
1411
- return {
1412
- userAgent: nav?.userAgent ?? "",
1413
- platform: nav?.platform ?? null,
1414
- language: nav?.language ?? "",
1415
- languages: nav?.languages ? [...nav.languages] : [],
1416
- hardwareConcurrency: typeof nav?.hardwareConcurrency === "number" ? nav.hardwareConcurrency : null,
1417
- deviceMemory: (() => {
1418
- const memory = nav ? nav.deviceMemory : undefined;
1419
- return typeof memory === "number" ? memory : null;
1420
- })(),
1421
- maxTouchPoints: typeof nav?.maxTouchPoints === "number" ? nav.maxTouchPoints : null,
1422
- devicePixelRatio: typeof window !== "undefined" && typeof window.devicePixelRatio === "number" ? window.devicePixelRatio : null,
1423
- screenWidth: typeof scr?.width === "number" ? scr.width : null,
1424
- screenHeight: typeof scr?.height === "number" ? scr.height : null,
1425
- colorDepth: typeof scr?.colorDepth === "number" ? scr.colorDepth : null,
1426
- timeZone,
1427
- uaDataPlatform: uaData?.platform ?? null,
1428
- uaDataMobile: typeof uaData?.mobile === "boolean" ? uaData.mobile : null,
1429
- uaDataBrands: uaData?.brands ? uaData.brands.map((entry) => `${entry.brand} ${entry.version}`) : []
1430
- };
1431
- }
1432
- function detectWebViewKind(userAgent) {
1433
- if (/;\s?wv\)/.test(userAgent) || /\bVersion\/[\d.]+\s+Chrome\/[\d.]+\s+Mobile\b/.test(userAgent)) {
1434
- return "android-webview";
1435
- }
1436
- if (/FBAN|FBAV|Instagram|Line\/|MicroMessenger|Snapchat|musical_ly|BytedanceWebview/i.test(userAgent)) {
1437
- return "in-app-browser";
1438
- }
1439
- if (/iPhone|iPad|iPod/.test(userAgent) && !/Safari\//.test(userAgent) && !/CriOS|FxiOS|EdgiOS/.test(userAgent)) {
1440
- return "ios-webview";
1441
- }
1442
- return "browser";
1443
- }
1444
- function detectBot(signals) {
1445
- const flags = [];
1446
- const userAgent = signals.navigator.userAgent;
1447
- if (typeof navigator !== "undefined" && navigator.webdriver) {
1448
- flags.push("webdriver");
1449
- }
1450
- if (/HeadlessChrome|PhantomJS|Selenium|puppeteer|playwright/i.test(userAgent)) {
1451
- flags.push("headless-ua");
1452
- }
1453
- if (signals.navigator.uaDataMobile === false && /Android|iPhone|iPad/i.test(userAgent)) {
1454
- flags.push("ua-mobile-mismatch");
1455
- }
1456
- return { score: Math.min(1, flags.length / 4), flags };
1457
- }
1458
- function canonicalizeSignals(signals) {
1459
- // Only drift-resistant fields, serialized with stable key order so the same
1460
- // device always produces the same composite hash.
1461
- const stable = {
1462
- platform: signals.platform,
1463
- navigator: {
1464
- ua: signals.navigator.userAgent,
1465
- platform: signals.navigator.platform,
1466
- lang: signals.navigator.language.split("-")[0],
1467
- languages: [...signals.navigator.languages].sort(),
1468
- concurrency: signals.navigator.hardwareConcurrency,
1469
- memory: signals.navigator.deviceMemory,
1470
- maxTouch: signals.navigator.maxTouchPoints,
1471
- dpr: signals.navigator.devicePixelRatio,
1472
- screen: [signals.navigator.screenWidth, signals.navigator.screenHeight],
1473
- colorDepth: signals.navigator.colorDepth,
1474
- timeZone: signals.navigator.timeZone,
1475
- uaDataPlatform: signals.navigator.uaDataPlatform,
1476
- uaDataBrands: signals.navigator.uaDataBrands
1477
- },
1478
- webview: signals.webview.kind
1479
- };
1480
- return stableStringify(stable);
1481
- }
1482
- async function computeCompositeHash(canonical) {
1483
- try {
1484
- return await sha256_128(canonical);
1485
- }
1486
- catch {
1487
- // Environments without WebCrypto (very old browsers) fall back to a stable FNV-1a pair.
1488
- return `fnv-${fnv1a32(canonical)}${fnv1a32(`${canonical}:fallback`)}`;
1489
- }
1490
- }
1491
- async function buildPayload() {
1492
- const persistent = loadOrCreatePersistentId();
1493
- const navigatorSignals = collectNavigatorSignals();
1494
- const signals = {
1495
- platform: "web",
1496
- navigator: navigatorSignals,
1497
- webview: { kind: detectWebViewKind(navigatorSignals.userAgent) }
1498
- };
1499
- const compositeHash = await computeCompositeHash(canonicalizeSignals(signals));
1500
- return {
1501
- version: 2,
1502
- schema: "didit-fp-v2",
1503
- platform: "web",
1504
- collectedAt: new Date().toISOString(),
1505
- persistentId: persistent.id,
1506
- persistentIdSources: persistent.sources,
1507
- persistentIdWasCreated: persistent.wasCreated,
1508
- signals,
1509
- bot: detectBot(signals),
1510
- compositeHash
1511
- };
1512
- }
1513
- function isBrowserEnvironment() {
1514
- return typeof window !== "undefined" && typeof navigator !== "undefined" && typeof document !== "undefined";
1515
- }
1516
- /**
1517
- * Collects the device fingerprint. Resolves to null outside a browser
1518
- * environment (SSR, Node, workers) so callers degrade to a fingerprint-less
1519
- * request instead of sending junk signals. Never intended to throw into the
1520
- * submit path: callers still guard with .catch(() => null).
1521
- */
1522
- async function getDeviceFingerprintPayload() {
1523
- if (!isBrowserEnvironment())
1524
- return null;
1525
- if (cachedPayload)
1526
- return cachedPayload;
1527
- if (!cachedPayloadPromise) {
1528
- cachedPayloadPromise = buildPayload().then((payload) => {
1529
- cachedPayload = payload;
1530
- return payload;
1531
- }, (error) => {
1532
- // Do not cache failures; a later call may succeed.
1533
- cachedPayloadPromise = null;
1534
- throw error;
1535
- });
1536
- }
1537
- return cachedPayloadPromise;
1538
- }
1539
- function buildFingerprintHeaders(payload) {
1540
- if (!payload)
1541
- return {};
1542
- const headers = { "X-Didit-FP-V2": "1" };
1543
- if (payload.persistentId)
1544
- headers["X-Didit-PID"] = payload.persistentId;
1545
- if (payload.compositeHash)
1546
- headers["X-Didit-FP-Hash"] = payload.compositeHash;
1547
- if (payload.signals.webview.kind)
1548
- headers["X-Didit-FP-Webview"] = payload.signals.webview.kind;
1549
- if (payload.bot.score)
1550
- headers["X-Didit-FP-Bot-Score"] = payload.bot.score.toFixed(2);
1551
- return headers;
1552
- }
1553
-
1554
1538
  const DEFAULT_TRANSACTION_BASE_URL = "https://verification.didit.me";
1555
1539
  const ACTION_POLL_INTERVAL_MS = 1500;
1556
1540
  const ACTION_POLL_MAX_ATTEMPTS = 10;
@@ -1777,7 +1761,7 @@ async function performRequest(url, init) {
1777
1761
  return mapTransactionResponse(body);
1778
1762
  }
1779
1763
  async function submitTransactionRequest(args) {
1780
- const fingerprint = await getDeviceFingerprintPayload().catch(() => null);
1764
+ const fingerprint = await signals.getDeviceFingerprintPayload().catch(() => null);
1781
1765
  const body = buildTransactionRequestBody(args.transaction);
1782
1766
  if (fingerprint) {
1783
1767
  body.fingerprint_v2 = fingerprint;
@@ -1787,7 +1771,7 @@ async function submitTransactionRequest(args) {
1787
1771
  headers: {
1788
1772
  "Content-Type": "application/json",
1789
1773
  "X-Transaction-Token": args.transactionToken,
1790
- ...buildFingerprintHeaders(fingerprint)
1774
+ ...signals.buildFingerprintHeaders(fingerprint)
1791
1775
  },
1792
1776
  body: JSON.stringify(body)
1793
1777
  });
@@ -1852,6 +1836,23 @@ async function pollTransactionAfterAction(args) {
1852
1836
  return latest;
1853
1837
  }
1854
1838
 
1839
+ /**
1840
+ * Embedded mode renders inside an element that already exists on the
1841
+ * integrator's page. Without it the modal never shows anything (embedded mode
1842
+ * never activates the overlay), so the launch fails with a message the
1843
+ * integrator can act on instead of silently presenting nothing.
1844
+ */
1845
+ function assertEmbeddedHostExists(configuration) {
1846
+ if (!configuration?.embedded)
1847
+ return;
1848
+ const containerId = configuration.embeddedContainerId;
1849
+ if (!containerId) {
1850
+ throw new Error("Embedded mode requires embeddedContainerId: the id of the element that hosts the verification.");
1851
+ }
1852
+ if (typeof document === "undefined" || !document.getElementById(containerId)) {
1853
+ throw new Error(`Embedded container "#${containerId}" was not found in the page.`);
1854
+ }
1855
+ }
1855
1856
  class DiditSdk {
1856
1857
  static get shared() {
1857
1858
  if (!DiditSdk._instance) {
@@ -1911,17 +1912,20 @@ class DiditSdk {
1911
1912
  this._modal.destroy();
1912
1913
  this._modal = null;
1913
1914
  }
1914
- this._modal = new VerificationModal(config, {
1915
- onClose: () => this.handleModalClose(),
1916
- onCloseConfirmed: () => this.handleModalCloseConfirmed(),
1917
- onMessage: (event) => this.handleVerificationEvent(event),
1918
- onIframeLoad: () => this.handleIframeLoad()
1919
- });
1915
+ // A new launch is not in an error state any more, whatever the last one did.
1916
+ this._errorMessage = undefined;
1920
1917
  try {
1921
1918
  const { url } = options;
1922
1919
  if (!url || typeof url !== "string") {
1923
1920
  throw new Error("Invalid options: url is required");
1924
1921
  }
1922
+ assertEmbeddedHostExists(config);
1923
+ this._modal = new VerificationModal(config, {
1924
+ onClose: () => this.handleModalClose(),
1925
+ onCloseConfirmed: () => this.handleModalCloseConfirmed(),
1926
+ onMessage: (event) => this.handleVerificationEvent(event),
1927
+ onIframeLoad: () => this.handleIframeLoad()
1928
+ });
1925
1929
  this._url = buildVerificationUrl(url, config);
1926
1930
  this.setState("loading");
1927
1931
  this.emitInternalEvent("didit:started", {});
@@ -1994,6 +1998,30 @@ class DiditSdk {
1994
1998
  }
1995
1999
  return result;
1996
2000
  }
2001
+ /**
2002
+ * Queues an end-user event (sign-up, login, failed login, logout, password
2003
+ * reset, MFA, device change...) for Didit's event monitoring, so it appears
2004
+ * in the console tied to the same person as their verifications and
2005
+ * transactions. Returns the event id.
2006
+ *
2007
+ * The request is authenticated with a short-lived monitoring token minted by
2008
+ * your backend for that person (POST /v3/events/sdk-token/) and sent via the
2009
+ * X-Monitoring-Token header; the person always comes from the token. Events
2010
+ * are batched to /v1/events/batch/ with the device fingerprint attached, and
2011
+ * sent when 25 are waiting, every 5 seconds and when the page is hidden or
2012
+ * closed. Tune the queue with `configureEvents` and send right away with
2013
+ * `flush`, both exported by this package.
2014
+ *
2015
+ * @param options monitoringToken, the event and an optional baseUrl
2016
+ * (defaults to https://verification.didit.me).
2017
+ * @returns The event id: yours when you set event.eventId, otherwise a new UUID.
2018
+ * @throws {DiditEventError} "invalid_token" without a monitoringToken,
2019
+ * "validation" without an event category and action type.
2020
+ */
2021
+ submitEvent(options) {
2022
+ SDKLogger.log("Submitting event:", options?.event?.category, options?.event?.actionType);
2023
+ return signals.submitEvent(options);
2024
+ }
1997
2025
  /**
1998
2026
  * Dismisses everything currently on screen in one deterministic call: a
1999
2027
  * pending transaction action modal is treated as an abort (no follow-up
@@ -2014,6 +2042,7 @@ class DiditSdk {
2014
2042
  this._modal?.destroy();
2015
2043
  this._modal = null;
2016
2044
  this.reset();
2045
+ this.setState("idle");
2017
2046
  }
2018
2047
  async runTransactionAction(baseUrl, transactionToken, submitResult, onActionCompleted) {
2019
2048
  const generation = this._actionGeneration;
@@ -2129,6 +2158,7 @@ class DiditSdk {
2129
2158
  const sessionData = this.buildSessionData();
2130
2159
  this._modal?.close();
2131
2160
  this.reset();
2161
+ this.setState("idle");
2132
2162
  const result = {
2133
2163
  type: "cancelled",
2134
2164
  session: sessionData
@@ -2149,6 +2179,11 @@ class DiditSdk {
2149
2179
  }
2150
2180
  handleVerificationEvent(event) {
2151
2181
  SDKLogger.log("Verification event:", event);
2182
+ // Keep the session the flow told us about so a modal the user closes by
2183
+ // hand still reports the session it belongs to in the cancelled result.
2184
+ if (event.data?.sessionId) {
2185
+ this._sessionId = event.data.sessionId;
2186
+ }
2152
2187
  this.onEvent?.(event);
2153
2188
  switch (event.type) {
2154
2189
  case "didit:ready":
@@ -2204,6 +2239,7 @@ class DiditSdk {
2204
2239
  if (this._configuration?.closeModalOnComplete) {
2205
2240
  this._modal?.close();
2206
2241
  this.reset();
2242
+ this.setState("idle");
2207
2243
  }
2208
2244
  const result = {
2209
2245
  type: "completed",
@@ -2216,6 +2252,7 @@ class DiditSdk {
2216
2252
  const sessionData = this.buildSessionData(event.data);
2217
2253
  this._modal?.close();
2218
2254
  this.reset();
2255
+ this.setState("idle");
2219
2256
  const result = {
2220
2257
  type: "cancelled",
2221
2258
  session: sessionData
@@ -2234,10 +2271,14 @@ class DiditSdk {
2234
2271
  else {
2235
2272
  verificationError = createVerificationError("unknown", "An unknown error occurred");
2236
2273
  }
2237
- this._errorMessage = verificationError.message;
2238
- this.setState("error");
2239
2274
  this._modal?.close();
2275
+ this._modal = null;
2276
+ // Clear what the failed launch left behind, then report the error as the
2277
+ // state the SDK is in: reset() alone would leave callers reading "idle"
2278
+ // with no error message right after onStateChange("error").
2240
2279
  this.reset();
2280
+ this._errorMessage = verificationError.message;
2281
+ this.setState("error");
2241
2282
  const result = {
2242
2283
  type: "failed",
2243
2284
  error: verificationError
@@ -2253,7 +2294,6 @@ class DiditSdk {
2253
2294
  }
2254
2295
  }
2255
2296
  reset() {
2256
- this._state = "idle";
2257
2297
  this._sessionId = undefined;
2258
2298
  this._url = undefined;
2259
2299
  this._errorMessage = undefined;
@@ -2277,4 +2317,10 @@ exports.DiditSdk = DiditSdk;
2277
2317
  exports.DiditTransactionError = DiditTransactionError;
2278
2318
  exports.SDK_VERSION = SDK_VERSION;
2279
2319
  exports.default = DiditSdk;
2320
+ Object.keys(signals).forEach(function (k) {
2321
+ if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, {
2322
+ enumerable: true,
2323
+ get: function () { return signals[k]; }
2324
+ });
2325
+ });
2280
2326
  //# sourceMappingURL=didit-sdk.cjs.js.map