@velion-la/onboarding-sdk-react-native 1.4.0-beta.8 → 1.4.0-beta.9

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.
Files changed (42) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +51 -0
  3. package/lib/commonjs/core/VelionOnboarding.js +104 -2
  4. package/lib/commonjs/core/VelionOnboarding.js.map +1 -1
  5. package/lib/commonjs/index.js +6 -0
  6. package/lib/commonjs/index.js.map +1 -1
  7. package/lib/commonjs/transport/api.js +9 -0
  8. package/lib/commonjs/transport/api.js.map +1 -1
  9. package/lib/commonjs/types/index.js +25 -1
  10. package/lib/commonjs/types/index.js.map +1 -1
  11. package/lib/commonjs/ui/VelionOnboardingScreen.js +20 -3
  12. package/lib/commonjs/ui/VelionOnboardingScreen.js.map +1 -1
  13. package/lib/commonjs/utils/sdkVersion.js +1 -1
  14. package/lib/module/core/VelionOnboarding.js +105 -3
  15. package/lib/module/core/VelionOnboarding.js.map +1 -1
  16. package/lib/module/index.js +1 -1
  17. package/lib/module/index.js.map +1 -1
  18. package/lib/module/transport/api.js +9 -0
  19. package/lib/module/transport/api.js.map +1 -1
  20. package/lib/module/types/index.js +26 -0
  21. package/lib/module/types/index.js.map +1 -1
  22. package/lib/module/ui/VelionOnboardingScreen.js +21 -4
  23. package/lib/module/ui/VelionOnboardingScreen.js.map +1 -1
  24. package/lib/module/utils/sdkVersion.js +1 -1
  25. package/lib/typescript/core/VelionOnboarding.d.ts +31 -0
  26. package/lib/typescript/core/VelionOnboarding.d.ts.map +1 -1
  27. package/lib/typescript/index.d.ts +3 -3
  28. package/lib/typescript/index.d.ts.map +1 -1
  29. package/lib/typescript/transport/api.d.ts +1 -0
  30. package/lib/typescript/transport/api.d.ts.map +1 -1
  31. package/lib/typescript/types/index.d.ts +32 -0
  32. package/lib/typescript/types/index.d.ts.map +1 -1
  33. package/lib/typescript/ui/VelionOnboardingScreen.d.ts +21 -2
  34. package/lib/typescript/ui/VelionOnboardingScreen.d.ts.map +1 -1
  35. package/lib/typescript/utils/sdkVersion.d.ts +1 -1
  36. package/package.json +1 -1
  37. package/src/core/VelionOnboarding.ts +109 -2
  38. package/src/index.ts +3 -0
  39. package/src/transport/api.ts +16 -1
  40. package/src/types/index.ts +34 -0
  41. package/src/ui/VelionOnboardingScreen.tsx +38 -1
  42. package/src/utils/sdkVersion.ts +1 -1
@@ -19,6 +19,9 @@
19
19
  * token with the cancellation, so the SDK closes SSE and stops calling out
20
20
  * - A request rejected with the 401 `VOB-40103` (token revoked by that same
21
21
  * cancellation, SSE event missed) ends the flow exactly like SESSION_CANCELLED
22
+ * - `cancelSession()` (the integrator cancels): once the backend confirms with
23
+ * 204 the flow ends exactly like SESSION_CANCELLED; the SSE event that
24
+ * follows is dropped, so the host hears about the cancellation once
22
25
  * - The step code picks the screen; the step key (`step_key`, else the code)
23
26
  * picks the instance: dedupe, config cache, reversibility and back
24
27
  * navigation all go by key, so two CUSTOM_FORMs in a row are two steps
@@ -71,7 +74,9 @@ import { CustomFormStep } from '../steps/CustomFormStep';
71
74
  import { EntityTypeSelectionStep } from '../steps/EntityTypeSelectionStep';
72
75
  import { unsupportedStepError } from '../steps/unsupportedStep';
73
76
  import {
77
+ CancelSessionErrorCode,
74
78
  SdkErrorCode,
79
+ type CancelSessionError,
75
80
  type VelionConfig as WebVelionConfig,
76
81
  type SdkStatus,
77
82
  type SdkEventMap,
@@ -182,6 +187,11 @@ function cancelledEventFromDto(): OnboardingSessionEvent {
182
187
  * A request got the 401 `VOB-40103`: the same cancellation SSE would have
183
188
  * announced, rebuilt with the reason the 401 body carries.
184
189
  */
190
+ /** The integrator cancelled through `cancelSession()`; the 204 carries no reason. */
191
+ function cancelledEventFromIntegrator(): OnboardingSessionEvent {
192
+ return { event_type: 'SESSION_CANCELLED', session_status: 'CANCELLED' };
193
+ }
194
+
185
195
  function cancelledEventFromRevokedToken(reason: string | undefined): OnboardingSessionEvent {
186
196
  return {
187
197
  event_type: 'SESSION_CANCELLED',
@@ -190,6 +200,45 @@ function cancelledEventFromRevokedToken(reason: string | undefined): OnboardingS
190
200
  };
191
201
  }
192
202
 
203
+ /** Backend code of the 409 for a cancel on a session that is no longer open. */
204
+ const SESSION_NOT_OPEN_BACKEND_CODE = 'VOB-40913';
205
+
206
+ /** Maps a failed `POST /sessions/:id/cancel` to the error `cancelSession()` rejects with. */
207
+ function toCancelSessionError(err: unknown): CancelSessionError {
208
+ const sdkErr = (err ?? {}) as Partial<SdkError>;
209
+ const httpStatus = sdkErr.httpStatus;
210
+ const backendCode = (sdkErr.cause as { code?: unknown } | undefined)?.code;
211
+ const withStatus = httpStatus !== undefined ? { httpStatus } : {};
212
+ if (httpStatus === 409 || backendCode === SESSION_NOT_OPEN_BACKEND_CODE) {
213
+ return {
214
+ code: CancelSessionErrorCode.SESSION_NOT_OPEN,
215
+ message: 'The session is no longer open; there is nothing to cancel.',
216
+ ...withStatus,
217
+ cause: err,
218
+ };
219
+ }
220
+ if (
221
+ httpStatus === 401 ||
222
+ httpStatus === 403 ||
223
+ sdkErr.code === SdkErrorCode.SESSION_EXPIRED ||
224
+ sdkErr.code === SdkErrorCode.SESSION_INVALID
225
+ ) {
226
+ return {
227
+ code: CancelSessionErrorCode.UNAUTHORIZED,
228
+ message:
229
+ 'The session token was rejected. Rotate it with refreshSessionToken() and call cancelSession() again.',
230
+ ...withStatus,
231
+ cause: err,
232
+ };
233
+ }
234
+ return {
235
+ code: CancelSessionErrorCode.NETWORK,
236
+ message: sdkErr.message ?? 'The cancel request did not get through.',
237
+ ...withStatus,
238
+ cause: err,
239
+ };
240
+ }
241
+
193
242
  function isSessionTokenAuthSdkError(err: unknown): err is SdkError {
194
243
  return (
195
244
  err != null &&
@@ -263,6 +312,10 @@ export class VelionOnboarding {
263
312
  private pendingSessionDeclined: OnboardingSessionEvent | null = null;
264
313
  private pendingTerminalEvent: OnboardingSessionEvent | null = null;
265
314
  private sessionEnded = false;
315
+ /** Set once the session is known to be cancelled, however the SDK learned it. */
316
+ private sessionCancelled = false;
317
+ /** In-flight `cancelSession()`, shared by concurrent calls. */
318
+ private cancelRequest: Promise<void> | null = null;
266
319
 
267
320
  constructor(config: VelionConfig) {
268
321
  const apiUrl = config.apiUrl ?? DEFAULT_API_URL;
@@ -332,6 +385,31 @@ export class VelionOnboarding {
332
385
  }
333
386
  }
334
387
 
388
+ /**
389
+ * Cancels the session on the integrator's behalf (`POST /sessions/:id/cancel`).
390
+ *
391
+ * Once the backend confirms, the flow ends exactly as when it cancels the
392
+ * session itself: `onSessionEvent` with `SESSION_CANCELLED`, then `onError`
393
+ * with `SdkErrorCode.SESSION_CANCELLED` and the cancelled screen. SSE is
394
+ * closed and the `SESSION_CANCELLED` event that follows is ignored, so the
395
+ * host is told once. Resolves after that; resolves at once when the session
396
+ * was already cancelled. Concurrent calls share one request.
397
+ *
398
+ * On failure the flow keeps running and the promise rejects with a
399
+ * {@link CancelSessionError}: `SESSION_NOT_OPEN` (409 `VOB-40913`),
400
+ * `UNAUTHORIZED` (401/403 — rotate the token with
401
+ * {@link refreshSessionToken} and call again) or `NETWORK`.
402
+ */
403
+ cancelSession(): Promise<void> {
404
+ if (this.sessionCancelled) return Promise.resolve();
405
+ if (this.cancelRequest === null) {
406
+ this.cancelRequest = this.requestCancellation().finally(() => {
407
+ this.cancelRequest = null;
408
+ });
409
+ }
410
+ return this.cancelRequest;
411
+ }
412
+
335
413
  async start(): Promise<void> {
336
414
  if (this.status === 'DESTROYED') {
337
415
  this.emitError({
@@ -386,6 +464,21 @@ export class VelionOnboarding {
386
464
  this.retryDialogResolve = null;
387
465
  }
388
466
 
467
+ private async requestCancellation(): Promise<void> {
468
+ try {
469
+ await this.api.postEmpty<void>(`/sessions/${this.config.sessionId}/cancel`);
470
+ } catch (err) {
471
+ // A 401 `VOB-40103` (or a caller already closed) means the session was
472
+ // cancelled meanwhile, and that path has already ended the flow.
473
+ if (this.sessionCancelled) return;
474
+ throw toCancelSessionError(err);
475
+ }
476
+ log.info('[Flow] Session cancelled by the integrator', {
477
+ sessionId: this.config.sessionId,
478
+ });
479
+ this.endFlowWithLocalCancellation(cancelledEventFromIntegrator());
480
+ }
481
+
389
482
  // ── Initialization ────────────────────────────────────────────────────────
390
483
 
391
484
  private async initialize(): Promise<void> {
@@ -953,6 +1046,7 @@ export class VelionOnboarding {
953
1046
  * SESSION_DECLINED — carrying the localized cancelled copy.
954
1047
  */
955
1048
  private endFlowWithSessionCancelled(event: OnboardingSessionEvent): void {
1049
+ this.sessionCancelled = true;
956
1050
  if (this.sessionEnded) return;
957
1051
  this.sessionEnded = true;
958
1052
  this.stopTalkingToBackend();
@@ -987,8 +1081,21 @@ export class VelionOnboarding {
987
1081
  * refresh a token that belongs to a closed session.
988
1082
  */
989
1083
  private endFlowWithRevokedToken(reason: string | undefined): void {
990
- if (this.sessionEnded || this.status === 'DESTROYED') return;
991
- const event = cancelledEventFromRevokedToken(reason);
1084
+ this.endFlowWithLocalCancellation(cancelledEventFromRevokedToken(reason));
1085
+ }
1086
+
1087
+ /**
1088
+ * The SDK learned of the cancellation from a request (a 401 `VOB-40103`, or
1089
+ * the 204 of `cancelSession()`) rather than from SSE. Reports it as if SSE
1090
+ * had delivered `event`. After the flow already ended (e.g. the user backed
1091
+ * out) it only stops talking to the backend: the host was told how it ended.
1092
+ */
1093
+ private endFlowWithLocalCancellation(event: OnboardingSessionEvent): void {
1094
+ if (this.sessionEnded || this.status === 'DESTROYED') {
1095
+ this.sessionCancelled = true;
1096
+ this.stopTalkingToBackend();
1097
+ return;
1098
+ }
992
1099
  this.showLoading(null);
993
1100
  this.config.onSessionEvent?.(event);
994
1101
  this.endFlowWithSessionCancelled(event);
package/src/index.ts CHANGED
@@ -25,6 +25,7 @@ export {
25
25
  } from './ui/VelionOnboardingScreen';
26
26
  export type {
27
27
  VelionOnboardingScreenProps,
28
+ VelionOnboardingScreenHandle,
28
29
  } from './ui/VelionOnboardingScreen';
29
30
 
30
31
  // Theme + design primitives — consumers may want to render adjacent UI in
@@ -95,6 +96,7 @@ export { getStrings, resolveLocale, type SupportedLocale } from './i18n';
95
96
  export {
96
97
  SdkErrorCode,
97
98
  CameraErrorCode,
99
+ CancelSessionErrorCode,
98
100
  } from './types';
99
101
  export type {
100
102
  OnboardingStep,
@@ -107,6 +109,7 @@ export type {
107
109
  OnboardingDtoResponse,
108
110
  SessionState,
109
111
  SdkError,
112
+ CancelSessionError,
110
113
  SdkStatus,
111
114
  VelionTheme,
112
115
  VelionFinalResultScreenTexts,
@@ -303,6 +303,21 @@ export function createApiCaller(
303
303
  );
304
304
  }
305
305
 
306
+ /** Authenticated POST without a body (e.g. `POST /sessions/:id/cancel`). */
307
+ async function postEmpty<TResponse>(
308
+ endpoint: string,
309
+ options?: ApiCallOptions,
310
+ ): Promise<TResponse> {
311
+ return call<TResponse>(
312
+ endpoint,
313
+ {
314
+ method: 'POST',
315
+ headers: buildAuthHeaders(options?.extraHeaders),
316
+ },
317
+ options,
318
+ );
319
+ }
320
+
306
321
  /**
307
322
  * Authenticated POST with a `FormData` body. RN's `fetch` mirrors the
308
323
  * standard contract: don't set `Content-Type` so the runtime injects the
@@ -324,7 +339,7 @@ export function createApiCaller(
324
339
  );
325
340
  }
326
341
 
327
- return { get, post, postFormData, setSessionToken, close } as const;
342
+ return { get, post, postEmpty, postFormData, setSessionToken, close } as const;
328
343
  }
329
344
 
330
345
  /** The type of the object returned by `createApiCaller`. */
@@ -497,6 +497,40 @@ export interface SdkError {
497
497
  readonly cause?: unknown;
498
498
  }
499
499
 
500
+ /**
501
+ * Why `cancelSession()` rejected. The flow keeps running in every case: only a
502
+ * cancellation the backend confirmed ends it.
503
+ */
504
+ export enum CancelSessionErrorCode {
505
+ /**
506
+ * The session is no longer open (409 `VOB-40913`): it already reached a
507
+ * verdict or was closed. Nothing to cancel.
508
+ */
509
+ SESSION_NOT_OPEN = 'SESSION_NOT_OPEN',
510
+ /**
511
+ * The session token was rejected (401/403) or has expired. Rotate it with
512
+ * `refreshSessionToken()` and call `cancelSession()` again.
513
+ */
514
+ UNAUTHORIZED = 'UNAUTHORIZED',
515
+ /**
516
+ * The request did not get through: no connectivity, or the backend answered
517
+ * with an unexpected status (`httpStatus` is set when it answered). Safe to
518
+ * retry.
519
+ */
520
+ NETWORK = 'NETWORK',
521
+ }
522
+
523
+ /** Rejection value of `cancelSession()`. */
524
+ export interface CancelSessionError {
525
+ readonly code: CancelSessionErrorCode;
526
+ /** Developer-facing description. Not intended for end users. */
527
+ readonly message: string;
528
+ /** HTTP status of the backend answer, when there was one. */
529
+ readonly httpStatus?: number;
530
+ /** The underlying error, for debugging. */
531
+ readonly cause?: unknown;
532
+ }
533
+
500
534
  // ─────────────────────────────────────────────────────────────────────────────
501
535
  // THEMING
502
536
  // ─────────────────────────────────────────────────────────────────────────────
@@ -10,10 +10,12 @@
10
10
  import React, {
11
11
  useCallback,
12
12
  useEffect,
13
+ useImperativeHandle,
13
14
  useMemo,
14
15
  useRef,
15
16
  useState,
16
17
  type ReactNode,
18
+ type Ref,
17
19
  } from 'react';
18
20
  import {
19
21
  StyleSheet,
@@ -58,6 +60,24 @@ function SafeAreaBoundary({ children }: { children: ReactNode }) {
58
60
  }
59
61
  }
60
62
 
63
+ /**
64
+ * Imperative handle exposed through the `ref` of `VelionOnboardingScreen`.
65
+ *
66
+ * @example
67
+ * const ref = useRef<VelionOnboardingScreenHandle>(null);
68
+ * <VelionOnboardingScreen ref={ref} config={config} onFail={onFail} />;
69
+ * await ref.current?.cancelSession();
70
+ */
71
+ export interface VelionOnboardingScreenHandle {
72
+ /** See {@link VelionOnboarding.cancelSession}. */
73
+ cancelSession(): Promise<void>;
74
+ /**
75
+ * See {@link VelionOnboarding.refreshSessionToken}. Rotate the token after
76
+ * `cancelSession()` rejected with `UNAUTHORIZED`, then call it again.
77
+ */
78
+ refreshSessionToken(token: string, expiresAt?: string): void;
79
+ }
80
+
61
81
  export interface VelionOnboardingScreenProps {
62
82
  config: VelionConfig;
63
83
  onComplete?: ((result: OnboardingResult) => void) | undefined;
@@ -69,6 +89,8 @@ export interface VelionOnboardingScreenProps {
69
89
  * context. Mirrors `VelionConfig.onExit`.
70
90
  */
71
91
  onExit?: ((exit: OnboardingExit) => void) | undefined;
92
+ /** Receives the {@link VelionOnboardingScreenHandle} (e.g. `cancelSession()`). */
93
+ ref?: Ref<VelionOnboardingScreenHandle> | undefined;
72
94
  }
73
95
 
74
96
  interface ViewState {
@@ -93,6 +115,7 @@ export function VelionOnboardingScreen({
93
115
  onComplete,
94
116
  onFail,
95
117
  onExit,
118
+ ref,
96
119
  }: VelionOnboardingScreenProps) {
97
120
  return (
98
121
  <SafeAreaBoundary>
@@ -106,6 +129,7 @@ export function VelionOnboardingScreen({
106
129
  onComplete={onComplete}
107
130
  onFail={onFail}
108
131
  onExit={onExit}
132
+ handleRef={ref}
109
133
  />
110
134
  </ThemeProvider>
111
135
  </KeyboardBoundary>
@@ -118,7 +142,10 @@ function VelionOnboardingInner({
118
142
  onComplete,
119
143
  onFail,
120
144
  onExit,
121
- }: VelionOnboardingScreenProps) {
145
+ handleRef,
146
+ }: Omit<VelionOnboardingScreenProps, 'ref'> & {
147
+ handleRef: Ref<VelionOnboardingScreenHandle> | undefined;
148
+ }) {
122
149
  const theme = useTheme();
123
150
  const insets = useScreenInsets();
124
151
  const t = getStrings(config.locale);
@@ -136,6 +163,16 @@ function VelionOnboardingInner({
136
163
  const sdkRef = useRef(sdk);
137
164
  sdkRef.current = sdk;
138
165
 
166
+ useImperativeHandle(
167
+ handleRef,
168
+ () => ({
169
+ cancelSession: () => sdkRef.current.cancelSession(),
170
+ refreshSessionToken: (token: string, expiresAt?: string) =>
171
+ sdkRef.current.refreshSessionToken(token, expiresAt),
172
+ }),
173
+ [],
174
+ );
175
+
139
176
  const onCompleteRef = useRef(onComplete);
140
177
  const onFailRef = useRef(onFail);
141
178
  const onExitRef = useRef(onExit);
@@ -5,4 +5,4 @@
5
5
  * GENERATED by `sdk/scripts/sync-sdk-version.js` from `sdk/package.json`:
6
6
  * do not edit by hand. The build and the CI version bump regenerate it.
7
7
  */
8
- export const SDK_VERSION = '1.4.0-beta.8' as const;
8
+ export const SDK_VERSION = '1.4.0-beta.9' as const;