@velion-la/onboarding-sdk-react-native 1.3.0-beta.1 → 1.3.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,6 +8,8 @@
8
8
  * Invariants:
9
9
  * - SSE dedupe by `event_id` (monotonic)
10
10
  * - Suppress duplicate `NEXT_STEP` for the just-completed step
11
+ * - Post-step routing wait (SSE + 30 s GET fallback cycles) is bounded by
12
+ * `routingTimeoutMs` → `ROUTING_TIMEOUT`
11
13
  * - `RETRY_STEP` shows a retry dialog (Retry re-mounts the step, Cancel exits);
12
14
  * once the retry quota is exhausted the backend emits SESSION_DECLINED instead
13
15
  * - 45 s watchdog for terminal SSE event after final step → fallback GET
@@ -67,6 +69,7 @@ import {
67
69
  import type { StepModule, StepUiHandle } from '../steps/types';
68
70
  import { createElement, type ReactNode } from 'react';
69
71
  import { RetryDialog } from '../ui/overlays/RetryDialog';
72
+ import { getStrings } from '../i18n';
70
73
 
71
74
  // ─────────────────────────────────────────────────────────────────────────────
72
75
  // PUBLIC CONFIG (RN flavor)
@@ -96,6 +99,12 @@ interface NextStepCommand {
96
99
  canGoBack?: boolean;
97
100
  }
98
101
 
102
+ /** Result of one routing cycle (SSE wait + fallback GET) after a completed step. */
103
+ type RoutingResolution =
104
+ | { kind: 'routed'; command: NextStepCommand }
105
+ | { kind: 'terminal' }
106
+ | { kind: 'unresolved' };
107
+
99
108
  /** Result of awaiting an active step module (see {@link VelionOnboarding.awaitModuleOutcome}). */
100
109
  type ModuleOutcome =
101
110
  | { kind: 'completed' }
@@ -107,6 +116,11 @@ const BACKEND_ONLY_ORCHESTRATED_STEPS = new Set<string>(['FACE_MATCH', 'AML_SCRE
107
116
 
108
117
  const DEFAULT_API_URL = 'https://sdk.velion.la/onboarding';
109
118
 
119
+ /** SSE wait per routing cycle before falling back to `GET /sessions/:id`. */
120
+ const ROUTING_SSE_WAIT_MS = 30_000;
121
+ /** Default total wait for the backend to route after a completed step (OSDKR-26). */
122
+ const DEFAULT_ROUTING_TIMEOUT_MS = 120_000;
123
+
110
124
  function isBackendOnlyOrchestratedStep(step: string | undefined): boolean {
111
125
  if (typeof step !== 'string' || step.trim() === '') return false;
112
126
  return BACKEND_ONLY_ORCHESTRATED_STEPS.has(step.trim().toUpperCase());
@@ -519,51 +533,17 @@ export class VelionOnboarding {
519
533
  index += 1;
520
534
 
521
535
  this.showLoading('');
522
- let next: NextStepCommand | null;
536
+ let next: NextStepCommand;
523
537
  try {
524
- const nextOutcome = await this.withSessionDeclineRace(
525
- this.resolveNextStepAfterCompletion(),
526
- );
527
- if (await this.consumePendingTerminalEvent()) {
528
- this.showLoading(null);
529
- return;
530
- }
531
- if (nextOutcome.declined) {
532
- this.endFlowWithSessionDeclined(nextOutcome.event);
533
- return;
534
- }
535
- next = nextOutcome.value;
538
+ const routed = await this.awaitRoutingAfterStep(currentStep);
539
+ if (routed.kind === 'ended') return;
540
+ if (routed.kind === 'verdict-pending') break;
541
+ next = routed.command;
536
542
  } catch (err) {
537
543
  this.showLoading(null);
538
544
  throw err;
539
545
  }
540
-
541
- while (
542
- next?.step &&
543
- next.action === 'NEXT_STEP' &&
544
- next.step === currentStep
545
- ) {
546
- log.warn('[Flow] Dropping duplicate NEXT_STEP for just-completed step', {
547
- step: currentStep,
548
- });
549
- const retryOutcome = await this.withSessionDeclineRace(
550
- this.resolveNextStepAfterCompletion(),
551
- );
552
- if (await this.consumePendingTerminalEvent()) {
553
- this.showLoading(null);
554
- return;
555
- }
556
- if (retryOutcome.declined) {
557
- this.endFlowWithSessionDeclined(retryOutcome.event);
558
- return;
559
- }
560
- next = retryOutcome.value;
561
- }
562
-
563
- if (next?.step) {
564
- this.showLoading(null);
565
- }
566
- if (!next?.step) break;
546
+ this.showLoading(null);
567
547
 
568
548
  // RETRY_STEP: the step failed but the retry quota is not exhausted. Show a
569
549
  // retry dialog before re-presenting the step. "Retry" re-mounts the same
@@ -1049,60 +1029,135 @@ export class VelionOnboarding {
1049
1029
 
1050
1030
  // ── Wait helpers ──────────────────────────────────────────────────────────
1051
1031
 
1032
+ /** Effective bound for post-step routing (`routingTimeoutMs`, default 120 s). */
1033
+ private routingTimeoutMs(): number {
1034
+ const configured = this.config.routingTimeoutMs;
1035
+ return typeof configured === 'number' && Number.isFinite(configured) && configured > 0
1036
+ ? configured
1037
+ : DEFAULT_ROUTING_TIMEOUT_MS;
1038
+ }
1039
+
1052
1040
  /**
1053
- * Wait for the next ROUTING_COMMAND. The orchestrator races this with a 30 s
1054
- * timeout that, on fire, falls back to a fresh GET /sessions/:id to recover
1055
- * if SSE was missed.
1041
+ * Waits for the backend to route the session after `completedStep`, bounded
1042
+ * by {@link routingTimeoutMs} (OSDKR-26).
1043
+ *
1044
+ * Each cycle is {@link resolveNextStepAfterCompletion}: SSE wait, then a
1045
+ * fallback GET. A cycle that yields nothing, or a duplicate `NEXT_STEP` for
1046
+ * the step just completed, used to restart the wait with no bound, so a
1047
+ * stalled worker left the user on the loading screen for ever and the host
1048
+ * without any callback. The cycles now share one deadline: past it the flow
1049
+ * fails with `ROUTING_TIMEOUT`, and after the first empty cycle the loading
1050
+ * screen tells the user the processing is taking longer than usual.
1051
+ *
1052
+ * `verdict-pending` means there is no step to mount (the fallback GET found
1053
+ * the session already terminal), so the step machine proceeds to the
1054
+ * finalization wait. `ended` means the flow was closed here (declined,
1055
+ * terminal event or destroyed) and the caller must return.
1056
1056
  */
1057
- private resolveNextStepAfterCompletion(): Promise<NextStepCommand | null> {
1058
- if (this.queuedNextStepCommand) {
1059
- const next = this.queuedNextStepCommand;
1060
- this.queuedNextStepCommand = null;
1061
- return Promise.resolve(next);
1057
+ private async awaitRoutingAfterStep(
1058
+ completedStep: OnboardingStep,
1059
+ ): Promise<
1060
+ | { kind: 'routed'; command: NextStepCommand }
1061
+ | { kind: 'verdict-pending' }
1062
+ | { kind: 'ended' }
1063
+ > {
1064
+ const timeoutMs = this.routingTimeoutMs();
1065
+ const deadline = Date.now() + timeoutMs;
1066
+ let emptyCycles = 0;
1067
+ for (;;) {
1068
+ const outcome = await this.withSessionDeclineRace(
1069
+ this.resolveNextStepAfterCompletion(Math.max(0, deadline - Date.now())),
1070
+ );
1071
+ if (await this.consumePendingTerminalEvent()) {
1072
+ this.showLoading(null);
1073
+ return { kind: 'ended' };
1074
+ }
1075
+ if (outcome.declined) {
1076
+ this.endFlowWithSessionDeclined(outcome.event);
1077
+ return { kind: 'ended' };
1078
+ }
1079
+ if (this.sessionEnded || this.status === 'DESTROYED') return { kind: 'ended' };
1080
+
1081
+ const resolution = outcome.value;
1082
+ if (resolution.kind === 'terminal') return { kind: 'verdict-pending' };
1083
+ if (resolution.kind === 'routed') {
1084
+ const { command } = resolution;
1085
+ // Defensive: drop a NEXT_STEP that points at the step we just
1086
+ // completed. Observed in production when the backend re-publishes a
1087
+ // NextStepRequestedEvent (Kafka re-delivery, late ack, double command
1088
+ // dispatch); it is also what the fallback GET returns while the worker
1089
+ // has not advanced the session yet. RETRY_STEP for the same step is
1090
+ // intentional and is allowed through.
1091
+ if (command.action !== 'NEXT_STEP' || command.step !== completedStep) {
1092
+ return { kind: 'routed', command };
1093
+ }
1094
+ log.warn('[Flow] Dropping duplicate NEXT_STEP for just-completed step', {
1095
+ step: completedStep,
1096
+ });
1097
+ }
1098
+
1099
+ emptyCycles += 1;
1100
+ const remainingMs = deadline - Date.now();
1101
+ if (remainingMs <= 0) {
1102
+ log.warn('[Flow] Backend never routed the session after the completed step; giving up', {
1103
+ step: completedStep,
1104
+ timeoutMs,
1105
+ cycles: emptyCycles,
1106
+ });
1107
+ throw {
1108
+ code: SdkErrorCode.ROUTING_TIMEOUT,
1109
+ message:
1110
+ `Backend did not route the session after step ${String(completedStep)} within ${timeoutMs} ms: ` +
1111
+ 'no ROUTING_COMMAND arrived over SSE and GET /sessions/:id kept reporting the completed step. ' +
1112
+ 'The onboarding worker may be delayed; start a new instance once the session advances.',
1113
+ stepCode: completedStep,
1114
+ } satisfies SdkError;
1115
+ }
1116
+ log.warn('[Flow] Routing after the completed step is still unresolved; waiting again', {
1117
+ step: completedStep,
1118
+ cycles: emptyCycles,
1119
+ remainingMs,
1120
+ });
1121
+ this.showLoading(getStrings(this.config.locale).common.routingDelayed);
1062
1122
  }
1123
+ }
1063
1124
 
1064
- return new Promise<NextStepCommand | null>((resolve) => {
1065
- const timeout = setTimeout(async () => {
1066
- if (this.sseNextStepResolve) {
1067
- this.sseNextStepResolve = null;
1068
- }
1069
- log.warn(
1070
- '[Flow] No ROUTING_COMMAND within 30 s — falling back to GET /sessions for next step',
1071
- );
1072
- try {
1073
- const dto = await this.api.get<OnboardingDtoResponse>(
1074
- `/sessions/${this.config.sessionId}`,
1075
- {
1076
- extraHeaders: {
1077
- 'Cache-Control': 'no-cache, no-store, must-revalidate',
1078
- },
1079
- },
1080
- );
1081
- if (isTerminalSessionStatusFromDto(dto.status)) {
1082
- resolve(null);
1083
- return;
1084
- }
1085
- const state = mapOnboardingDtoToSessionState(dto);
1086
- if (state.currentStep) {
1087
- resolve({
1088
- step: state.currentStep,
1089
- action: 'NEXT_STEP',
1090
- ...(state.currentStepConfig !== undefined && {
1091
- stepConfig: state.currentStepConfig,
1092
- }),
1093
- ...(state.canGoBack !== undefined && {
1094
- canGoBack: state.canGoBack,
1095
- }),
1096
- });
1097
- return;
1098
- }
1099
- resolve(null);
1100
- } catch (err) {
1101
- log.error('[Flow] Fallback GET /sessions failed', err);
1102
- resolve(null);
1103
- }
1104
- }, 30_000);
1125
+ /**
1126
+ * One routing cycle: queued command → SSE wait for the next ROUTING_COMMAND
1127
+ * (30 s, capped by `budgetMs`) → fallback `GET /sessions/:id` to recover if
1128
+ * SSE was missed.
1129
+ */
1130
+ private async resolveNextStepAfterCompletion(
1131
+ budgetMs: number,
1132
+ ): Promise<RoutingResolution> {
1133
+ const queued = this.consumeQueuedNextStepCommand();
1134
+ if (queued) return { kind: 'routed', command: queued };
1135
+
1136
+ const sseNext = await this.waitForNextStepCommand(
1137
+ Math.min(ROUTING_SSE_WAIT_MS, budgetMs),
1138
+ );
1139
+ if (sseNext) return { kind: 'routed', command: sseNext };
1140
+ // A terminal event interrupted the wait: the caller consumes it.
1141
+ if (this.pendingTerminalEvent) return { kind: 'terminal' };
1142
+ const afterWait = this.consumeQueuedNextStepCommand();
1143
+ if (afterWait) return { kind: 'routed', command: afterWait };
1144
+
1145
+ log.warn('[Flow] No ROUTING_COMMAND in time — falling back to GET /sessions for next step');
1146
+ const fetched = await this.fetchCurrentStepFromSession();
1147
+ if (fetched.kind !== 'unresolved') return fetched;
1148
+ // A ROUTING_COMMAND may have landed while the GET was in flight.
1149
+ const afterFetch = this.consumeQueuedNextStepCommand();
1150
+ if (afterFetch) return { kind: 'routed', command: afterFetch };
1151
+ return this.pendingTerminalEvent ? { kind: 'terminal' } : { kind: 'unresolved' };
1152
+ }
1105
1153
 
1154
+ /** Resolves with the next ROUTING_COMMAND from SSE, or null after `timeoutMs`. */
1155
+ private waitForNextStepCommand(timeoutMs: number): Promise<NextStepCommand | null> {
1156
+ return new Promise<NextStepCommand | null>((resolve) => {
1157
+ const timeout = setTimeout(() => {
1158
+ this.sseNextStepResolve = null;
1159
+ resolve(null);
1160
+ }, timeoutMs);
1106
1161
  this.sseNextStepResolve = (cmd) => {
1107
1162
  clearTimeout(timeout);
1108
1163
  resolve(cmd);
@@ -1110,8 +1165,58 @@ export class VelionOnboarding {
1110
1165
  });
1111
1166
  }
1112
1167
 
1113
- private waitForRoutingAfterBackendOnlyStep(): Promise<NextStepCommand | null> {
1114
- return this.resolveNextStepAfterCompletion();
1168
+ /** Returns and clears {@link queuedNextStepCommand} when present. */
1169
+ private consumeQueuedNextStepCommand(): NextStepCommand | null {
1170
+ const next = this.queuedNextStepCommand;
1171
+ this.queuedNextStepCommand = null;
1172
+ return next;
1173
+ }
1174
+
1175
+ /**
1176
+ * Fallback `GET /sessions/:id`. A missing `current_step` or a failed request
1177
+ * is `unresolved` — never "every step is done" (OSDKR-26).
1178
+ */
1179
+ private async fetchCurrentStepFromSession(): Promise<RoutingResolution> {
1180
+ let dto: OnboardingDtoResponse;
1181
+ try {
1182
+ dto = await this.api.get<OnboardingDtoResponse>(
1183
+ `/sessions/${this.config.sessionId}`,
1184
+ {
1185
+ extraHeaders: {
1186
+ 'Cache-Control': 'no-cache, no-store, must-revalidate',
1187
+ },
1188
+ },
1189
+ );
1190
+ } catch (err) {
1191
+ log.error('[Flow] Fallback GET /sessions failed', err);
1192
+ return { kind: 'unresolved' };
1193
+ }
1194
+ if (isTerminalSessionStatusFromDto(dto.status)) return { kind: 'terminal' };
1195
+ const state = mapOnboardingDtoToSessionState(dto);
1196
+ if (!state.currentStep) {
1197
+ log.warn('[Flow] Fallback GET /sessions returned no current_step');
1198
+ return { kind: 'unresolved' };
1199
+ }
1200
+ return {
1201
+ kind: 'routed',
1202
+ command: {
1203
+ step: state.currentStep,
1204
+ // GET fallback represents "advance to current step" — equivalent to
1205
+ // a NEXT_STEP routing command. Retries always come over SSE.
1206
+ action: 'NEXT_STEP',
1207
+ ...(state.currentStepConfig !== undefined && {
1208
+ stepConfig: state.currentStepConfig,
1209
+ }),
1210
+ ...(state.canGoBack !== undefined && {
1211
+ canGoBack: state.canGoBack,
1212
+ }),
1213
+ },
1214
+ };
1215
+ }
1216
+
1217
+ private async waitForRoutingAfterBackendOnlyStep(): Promise<NextStepCommand | null> {
1218
+ const resolution = await this.resolveNextStepAfterCompletion(ROUTING_SSE_WAIT_MS);
1219
+ return resolution.kind === 'routed' ? resolution.command : null;
1115
1220
  }
1116
1221
 
1117
1222
  private waitForTerminalSseEvent(
@@ -6,6 +6,7 @@ export const EN: StringsTable = {
6
6
  submitting: 'Submitting…',
7
7
  processingVerification: 'Processing your verification…',
8
8
  finalizing: 'Processing your information…',
9
+ routingDelayed: 'We are processing your information, this may take a few seconds…',
9
10
  continue: 'Continue',
10
11
  cancel: 'Cancel',
11
12
  retry: 'Try again',
@@ -9,6 +9,7 @@ export const ES = {
9
9
  submitting: 'Enviando…',
10
10
  processingVerification: 'Procesando tu verificación…',
11
11
  finalizing: 'Procesando tu información…',
12
+ routingDelayed: 'Estamos procesando tu información, puede demorar unos segundos…',
12
13
  continue: 'Continuar',
13
14
  cancel: 'Cancelar',
14
15
  retry: 'Reintentar',
@@ -293,6 +293,14 @@ export enum SdkErrorCode {
293
293
  SESSION_FETCH_FAILED = 'SESSION_FETCH_FAILED',
294
294
  /** Backend sent SESSION_DECLINED over SSE; session ended before completion. */
295
295
  SESSION_DECLINED = 'SESSION_DECLINED',
296
+ /**
297
+ * A step was completed but the backend did not route the session to the
298
+ * next one within `routingTimeoutMs` (default 120 s): no `ROUTING_COMMAND`
299
+ * arrived over SSE and `GET /sessions/:id` kept reporting the completed
300
+ * step. The session is still alive on the backend; `stepCode` names the
301
+ * completed step. Typical cause: a delayed or stalled onboarding worker.
302
+ */
303
+ ROUTING_TIMEOUT = 'ROUTING_TIMEOUT',
296
304
 
297
305
  // ── Modules ──────────────────────────────────────────────────────────────
298
306
  /** FingerprintJS failed to generate the visitor ID. */
@@ -364,7 +372,10 @@ export interface SdkError {
364
372
  readonly message: string;
365
373
  /** Present when `code === SdkErrorCode.SESSION_DECLINED` (SSE `reason`). */
366
374
  readonly declineReason?: string;
367
- /** Present when `code === SdkErrorCode.SESSION_DECLINED` (SSE `step_code`). */
375
+ /**
376
+ * Step the error refers to. For `SESSION_DECLINED` it is the SSE `step_code`;
377
+ * for `ROUTING_TIMEOUT` it is the step that was completed and never routed.
378
+ */
368
379
  readonly stepCode?: string;
369
380
  /**
370
381
  * Localized headline resolved by the SDK for SESSION_DECLINED.
@@ -780,6 +791,18 @@ export interface VelionConfig extends VelionCallbacks {
780
791
  */
781
792
  fingerprintTimeoutMs?: number;
782
793
 
794
+ /**
795
+ * Total wait, in milliseconds, for the backend to route the session after a
796
+ * step is completed. The SDK waits for the SSE `ROUTING_COMMAND` and falls
797
+ * back to `GET /sessions/:id` every 30 s; when the backend keeps reporting
798
+ * the completed step (delayed or stalled worker) those cycles used to repeat
799
+ * for ever. Past this bound the flow fails with `ROUTING_TIMEOUT` so the host
800
+ * gets a callback instead of an endless loading screen.
801
+ *
802
+ * @default 120000
803
+ */
804
+ routingTimeoutMs?: number;
805
+
783
806
  /**
784
807
  * Google Maps Platform API key (Maps JavaScript API + Places). Required for the
785
808
  * {@code ADDRESS_INFO} step to show the map, search, and geocoding. Omit only if