datakeen-session-react 1.1.202-dev.11 → 1.1.202-dev.13

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 (34) hide show
  1. package/dist/cjs/components/DatakeenSession.js +50 -14
  2. package/dist/cjs/components/session/ContinuedElsewhere.js +20 -0
  3. package/dist/cjs/components/session/SessionAbandoned.js +18 -0
  4. package/dist/cjs/components/session/SessionContent.js +7 -3
  5. package/dist/cjs/hooks/useNfcSseStatus.js +31 -77
  6. package/dist/cjs/hooks/useRemoteSessionSync.js +135 -0
  7. package/dist/cjs/hooks/useSessionData.js +28 -2
  8. package/dist/cjs/hooks/useSessionEventStream.js +88 -0
  9. package/dist/cjs/hooks/useStepNavigation.js +57 -1
  10. package/dist/cjs/i18n/en.json.js +10 -0
  11. package/dist/cjs/i18n/es.json.js +10 -0
  12. package/dist/cjs/i18n/fr.json.js +10 -0
  13. package/dist/cjs/services/realtime/sessionSyncReducer.js +106 -0
  14. package/dist/cjs/services/realtime/sseClient.js +127 -0
  15. package/dist/cjs/services/realtime/sseParser.js +58 -0
  16. package/dist/cjs/utils/analysisErrors.js +10 -1
  17. package/dist/esm/components/DatakeenSession.js +51 -15
  18. package/dist/esm/components/session/ContinuedElsewhere.js +16 -0
  19. package/dist/esm/components/session/SessionAbandoned.js +14 -0
  20. package/dist/esm/components/session/SessionContent.js +7 -3
  21. package/dist/esm/hooks/useNfcSseStatus.js +31 -77
  22. package/dist/esm/hooks/useRemoteSessionSync.js +133 -0
  23. package/dist/esm/hooks/useSessionData.js +28 -2
  24. package/dist/esm/hooks/useSessionEventStream.js +86 -0
  25. package/dist/esm/hooks/useStepNavigation.js +57 -1
  26. package/dist/esm/i18n/en.json.js +10 -0
  27. package/dist/esm/i18n/es.json.js +10 -0
  28. package/dist/esm/i18n/fr.json.js +10 -0
  29. package/dist/esm/services/realtime/sessionSyncReducer.js +103 -0
  30. package/dist/esm/services/realtime/sseClient.js +125 -0
  31. package/dist/esm/services/realtime/sseParser.js +56 -0
  32. package/dist/esm/utils/analysisErrors.js +10 -2
  33. package/dist/types/types/session.d.ts +5 -0
  34. package/package.json +1 -1
@@ -0,0 +1,16 @@
1
+ import { jsxs, jsx } from 'react/jsx-runtime';
2
+ import Button from '../ui/Button.js';
3
+ import { useI18n } from '../../hooks/useI18n.js';
4
+
5
+ /**
6
+ * APP3-2030 — une étape de capture ou de signature a été atteinte sur un autre appareil.
7
+ * Elle n'est montée ici (caméra, appel de vivacité, ouverture du document) que si
8
+ * l'usager choisit de poursuivre sur cet appareil.
9
+ */
10
+ var ContinuedElsewhere = function (_a) {
11
+ var onResume = _a.onResume;
12
+ var t = useI18n().t;
13
+ return (jsxs("div", { className: "flex flex-col items-center justify-center h-full text-center p-6", role: "status", children: [jsx("h2", { className: "text-2xl font-bold mb-4", children: t("session.continued_elsewhere.title") }), jsx("p", { className: "text-gray-600 mb-6", children: t("session.continued_elsewhere.description") }), jsx(Button, { onClick: onResume, className: "w-full", children: t("session.continued_elsewhere.resume") })] }));
14
+ };
15
+
16
+ export { ContinuedElsewhere as default };
@@ -0,0 +1,14 @@
1
+ import { jsxs, jsx } from 'react/jsx-runtime';
2
+ import shieldIcon from '../../assets/icons/shield_magic_link.svg.js';
3
+ import { useI18n } from '../../hooks/useI18n.js';
4
+
5
+ /**
6
+ * Session clôturée côté serveur pour abandon (APP3-2030 : annoncé en direct aux appareils
7
+ * encore ouverts). Contrairement à l'expiration, rien à réessayer : la session est terminée.
8
+ */
9
+ var SessionAbandoned = function () {
10
+ var t = useI18n().t;
11
+ return (jsxs("div", { className: "flex flex-col items-center justify-center h-full text-center p-6", role: "status", children: [jsx("div", { className: "mb-6", children: jsx("img", { src: shieldIcon, alt: "", "aria-hidden": "true" }) }), jsx("h2", { className: "text-2xl font-bold text-red-600 mb-4", children: t("session.abandoned.title") }), jsx("p", { className: "text-gray-600 mb-6", children: t("session.abandoned.description") })] }));
12
+ };
13
+
14
+ export { SessionAbandoned as default };
@@ -3,6 +3,7 @@ import { useEffect } from 'react';
3
3
  import StartSession from './StartSession.js';
4
4
  import MobileRedirect from './MobileRedirect.js';
5
5
  import EndFlow from './EndFlow.js';
6
+ import ContinuedElsewhere from './ContinuedElsewhere.js';
6
7
  import LoadingState from '../states/LoadingState.js';
7
8
  import TemplateNodeRenderer from '../template/TemplateNodeRenderer.js';
8
9
  import { getOrderedJourneySteps } from '../../services/sessionService.js';
@@ -11,8 +12,8 @@ import { useI18n } from '../../hooks/useI18n.js';
11
12
 
12
13
  var SessionContent = function (_a) {
13
14
  var _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
14
- var step = _a.step, loading = _a.loading, session = _a.session, sessionId = _a.sessionId, stepObject = _a.stepObject, stepHistory = _a.stepHistory, userInput = _a.userInput, setUserInput = _a.setUserInput, contactInfo = _a.contactInfo, setContactInfo = _a.setContactInfo;
15
- var _o = useI18n(), setLanguage = _o.setLanguage, currentLanguage = _o.currentLanguage, t = _o.t;
15
+ var step = _a.step, loading = _a.loading, session = _a.session, sessionId = _a.sessionId, stepObject = _a.stepObject, stepHistory = _a.stepHistory, userInput = _a.userInput, setUserInput = _a.setUserInput, contactInfo = _a.contactInfo, setContactInfo = _a.setContactInfo, _o = _a.remotelyFinished, remotelyFinished = _o === void 0 ? false : _o, _p = _a.standbyStep, standbyStep = _p === void 0 ? null : _p, onResumeHere = _a.onResumeHere;
16
+ var _q = useI18n(), setLanguage = _q.setLanguage, currentLanguage = _q.currentLanguage, t = _q.t;
16
17
  // If is mobile template, isMobileCapture should be true for document-selection nodes
17
18
  var isMobileTemplate = ((_c = (_b = session === null || session === void 0 ? void 0 : session.template) === null || _b === void 0 ? void 0 : _b.platforms) === null || _c === void 0 ? void 0 : _c.mobile) === true;
18
19
  var showQRCodeInstructions = isMobileTemplate && ((_d = session === null || session === void 0 ? void 0 : session.template) === null || _d === void 0 ? void 0 : _d.showQRCode) === true;
@@ -67,7 +68,7 @@ var SessionContent = function (_a) {
67
68
  // Special check: if the session is already finished, display EndFlow
68
69
  // directly (raw "ended" or a consolidated result status).
69
70
  if (isSessionFinished(session === null || session === void 0 ? void 0 : session.status)) {
70
- return (jsx(EndFlow, { sessionId: sessionId, sessionStatus: session === null || session === void 0 ? void 0 : session.status, callbackURL: session === null || session === void 0 ? void 0 : session.callbackURL, compliantCase: (_k = (_j = session === null || session === void 0 ? void 0 : session.template) === null || _j === void 0 ? void 0 : _j.endScreenConfig) === null || _k === void 0 ? void 0 : _k.compliant, nonCompliantCase: (_m = (_l = session === null || session === void 0 ? void 0 : session.template) === null || _l === void 0 ? void 0 : _l.endScreenConfig) === null || _m === void 0 ? void 0 : _m.nonCompliant, alreadyFinished: (session === null || session === void 0 ? void 0 : session.status) !== "ended" }));
71
+ return (jsx(EndFlow, { sessionId: sessionId, sessionStatus: session === null || session === void 0 ? void 0 : session.status, callbackURL: session === null || session === void 0 ? void 0 : session.callbackURL, compliantCase: (_k = (_j = session === null || session === void 0 ? void 0 : session.template) === null || _j === void 0 ? void 0 : _j.endScreenConfig) === null || _k === void 0 ? void 0 : _k.compliant, nonCompliantCase: (_m = (_l = session === null || session === void 0 ? void 0 : session.template) === null || _l === void 0 ? void 0 : _l.endScreenConfig) === null || _m === void 0 ? void 0 : _m.nonCompliant, alreadyFinished: remotelyFinished || (session === null || session === void 0 ? void 0 : session.status) !== "ended" }));
71
72
  }
72
73
  // Render step content
73
74
  switch (step) {
@@ -77,6 +78,9 @@ var SessionContent = function (_a) {
77
78
  // MobileRedirect step - only shown if showQRCodeInstructions is true
78
79
  return (jsx(MobileRedirect, { sessionId: sessionId, onBack: function () { return stepObject.setStep(0); }, onContinueOnPC: handleContinueOnPC, isDesktopAllowed: isDesktopAllowed, title: qrCodeTitle, subtitle: qrCodeDescription }));
79
80
  default:
81
+ if (standbyStep !== null && step === standbyStep && onResumeHere) {
82
+ return jsx(ContinuedElsewhere, { onResume: onResumeHere });
83
+ }
80
84
  // From step 1 onwards, use dynamic logic based on template
81
85
  if (step >= 1) {
82
86
  if (loading) {
@@ -1,88 +1,42 @@
1
1
  import { useState, useRef, useEffect } from 'react';
2
+ import { useSessionEventStream } from './useSessionEventStream.js';
2
3
 
3
4
  var SUCCESS_DISPLAY_DURATION_MS = 2500;
4
- var RECONNECT_DELAY_MS = 2000;
5
+ var isTerminal = function (data) { return (data === null || data === void 0 ? void 0 : data.status) === "completed" || (data === null || data === void 0 ? void 0 : data.status) === "failed"; };
6
+ /**
7
+ * Suit le scan NFC fait dans l'app native via `GET /session/sdk/:id/nfc-status`.
8
+ *
9
+ * APP3-2030 : passe par le client SSE commun (fetch + `X-Session-Token`) au lieu
10
+ * d'EventSource, qui ne pouvait pas envoyer le credential. Le cycle de vie mobile
11
+ * (arrière-plan pendant le scan, retour, bfcache) est géré par `useSessionEventStream`.
12
+ */
5
13
  function useNfcSseStatus(_a) {
6
14
  var sessionId = _a.sessionId, apiBaseUrl = _a.apiBaseUrl, onCompleted = _a.onCompleted;
7
15
  var _b = useState("pending"), status = _b[0], setStatus = _b[1];
8
16
  var onCompletedRef = useRef(onCompleted);
9
17
  onCompletedRef.current = onCompleted;
10
- useEffect(function () {
11
- if (!sessionId || !apiBaseUrl)
12
- return;
13
- var url = "".concat(apiBaseUrl, "/session/sdk/").concat(sessionId, "/nfc-status");
14
- var source = null;
15
- // Statut terminal reçu : plus aucune (re)connexion, et `onCompleted` n'est appelé qu'une fois.
16
- var finished = false;
17
- var reconnectTimer;
18
- var open = function () {
19
- clearTimeout(reconnectTimer);
20
- source === null || source === void 0 ? void 0 : source.close();
21
- var current = new EventSource(url);
22
- source = current;
23
- current.onmessage = function (event) {
24
- if (finished)
25
- return;
26
- try {
27
- var data = JSON.parse(event.data);
28
- if (data.status === "completed") {
29
- finished = true;
30
- current.close();
31
- setStatus("success");
32
- setTimeout(function () {
33
- setStatus("completed");
34
- onCompletedRef.current();
35
- }, SUCCESS_DISPLAY_DURATION_MS);
36
- }
37
- else {
38
- // `failed` est terminal : le serveur ferme le flux, inutile de le rouvrir en boucle.
39
- if (data.status === "failed")
40
- finished = true;
41
- setStatus(data.status);
42
- }
43
- }
44
- catch (_a) {
45
- // message malformé, on ignore
46
- }
47
- };
48
- // EventSource se reconnecte seul tant qu'il est CONNECTING. Mais iOS coupe le flux quand
49
- // Safari passe en arrière-plan pendant le scan dans l'app, et une réponse non-200 à la
50
- // reconnexion le ferme définitivement (CLOSED) : on le rouvre alors nous-mêmes.
51
- current.onerror = function () {
52
- if (!finished && current.readyState === EventSource.CLOSED) {
53
- reconnectTimer = setTimeout(open, RECONNECT_DELAY_MS);
54
- }
55
- };
56
- };
57
- // Retour sur la page (depuis l'app de scan, ou restauration bfcache) : le flux a pu mourir
58
- // pendant la suspension et l'event `completed` être perdu. On rouvre : le serveur renvoie le
59
- // statut courant dès la connexion, donc le parcours avance sans recharger la page.
60
- var reopenIfVisible = function () {
61
- if (!finished && document.visibilityState === "visible")
62
- open();
63
- };
64
- // Fermer le flux uniquement quand la page se ferme réellement, sinon le SSE reste ouvert côté
65
- // serveur (heartbeat + listener qui fuient). `pagehide` couvre la fermeture d'onglet/navigation
66
- // (plus fiable que `beforeunload` sur mobile).
67
- //
68
- // NE PAS fermer sur `visibilitychange`/`hidden` : le passage en arrière-plan est le geste
69
- // NORMAL de l'utilisateur qui bascule vers son téléphone pour scanner le QR. On se contente de
70
- // ROUVRIR au retour (`visible`), ce qui ne coupe jamais un flux encore utile.
71
- var closeSource = function () {
72
- clearTimeout(reconnectTimer);
73
- source === null || source === void 0 ? void 0 : source.close();
74
- };
75
- open();
76
- window.addEventListener("pagehide", closeSource);
77
- window.addEventListener("pageshow", reopenIfVisible);
78
- document.addEventListener("visibilitychange", reopenIfVisible);
79
- return function () {
80
- window.removeEventListener("pagehide", closeSource);
81
- window.removeEventListener("pageshow", reopenIfVisible);
82
- document.removeEventListener("visibilitychange", reopenIfVisible);
83
- closeSource();
84
- };
85
- }, [sessionId, apiBaseUrl]);
18
+ var successTimer = useRef();
19
+ useEffect(function () { return function () { return clearTimeout(successTimer.current); }; }, []);
20
+ useSessionEventStream({
21
+ sessionId: sessionId,
22
+ path: "nfc-status",
23
+ apiBaseUrl: apiBaseUrl,
24
+ enabled: Boolean(sessionId && apiBaseUrl),
25
+ isTerminal: isTerminal,
26
+ onEvent: function (data) {
27
+ if (!(data === null || data === void 0 ? void 0 : data.status))
28
+ return;
29
+ if (data.status === "completed") {
30
+ setStatus("success");
31
+ successTimer.current = setTimeout(function () {
32
+ setStatus("completed");
33
+ onCompletedRef.current();
34
+ }, SUCCESS_DISPLAY_DURATION_MS);
35
+ return;
36
+ }
37
+ setStatus(data.status);
38
+ },
39
+ });
86
40
  return { status: status };
87
41
  }
88
42
 
@@ -0,0 +1,133 @@
1
+ import { __awaiter, __generator } from '../node_modules/tslib/tslib.es6.js';
2
+ import { useRef, useCallback, useEffect } from 'react';
3
+ import { useSessionEventStream } from './useSessionEventStream.js';
4
+ import { fetchSessionById } from '../services/sessionService.js';
5
+ import { decideRemoteSync, isTerminalSessionEvent } from '../services/realtime/sessionSyncReducer.js';
6
+
7
+ /** Délai avant de réessayer un événement reçu pendant une navigation locale non confirmée. */
8
+ var DEFER_RETRY_MS = 250;
9
+ /**
10
+ * APP3-2030 — suit la progression de la session faite sur d'autres appareils/onglets.
11
+ * N'envoie jamais rien au serveur : `decideRemoteSync` décide, puis des primitives de
12
+ * navigation sans PATCH appliquent. Les événements sont traités un par un, dans l'ordre.
13
+ */
14
+ function useRemoteSessionSync(options) {
15
+ var _this = this;
16
+ var optionsRef = useRef(options);
17
+ optionsRef.current = options;
18
+ var lastRevision = useRef(null);
19
+ var deferred = useRef(null);
20
+ var retryTimer = useRef();
21
+ var queue = useRef(Promise.resolve());
22
+ var disposed = useRef(false);
23
+ var process = useCallback(function (event) { return __awaiter(_this, void 0, void 0, function () {
24
+ var current, decision, _a, fresh, error_1, session, error_2;
25
+ return __generator(this, function (_b) {
26
+ switch (_b.label) {
27
+ case 0:
28
+ current = optionsRef.current;
29
+ if (disposed.current || !current.template)
30
+ return [2 /*return*/];
31
+ decision = decideRemoteSync({
32
+ lastRevision: lastRevision.current,
33
+ step: current.step,
34
+ localNavigationInFlight: current.isPersistingStep(),
35
+ handoffLocked: current.handoffLocked,
36
+ recentLocalSteps: current.getRecentLocalSteps(),
37
+ }, event, current.template);
38
+ if (decision.action === "defer") {
39
+ if (!deferred.current || event.revision > deferred.current.revision)
40
+ deferred.current = event;
41
+ clearTimeout(retryTimer.current);
42
+ retryTimer.current = setTimeout(function () {
43
+ var pending = deferred.current;
44
+ deferred.current = null;
45
+ if (pending)
46
+ enqueue(pending);
47
+ }, DEFER_RETRY_MS);
48
+ return [2 /*return*/];
49
+ }
50
+ if (decision.action === "ignore" && decision.reason === "stale")
51
+ return [2 /*return*/];
52
+ lastRevision.current = event.revision;
53
+ if (deferred.current && deferred.current.revision <= event.revision)
54
+ deferred.current = null;
55
+ _a = decision.action;
56
+ switch (_a) {
57
+ case "navigate": return [3 /*break*/, 1];
58
+ case "finish": return [3 /*break*/, 5];
59
+ case "expire": return [3 /*break*/, 10];
60
+ case "close": return [3 /*break*/, 10];
61
+ case "abandon": return [3 /*break*/, 11];
62
+ }
63
+ return [3 /*break*/, 12];
64
+ case 1:
65
+ _b.trys.push([1, 3, , 4]);
66
+ return [4 /*yield*/, fetchSessionById(current.sessionId)];
67
+ case 2:
68
+ fresh = _b.sent();
69
+ if (disposed.current)
70
+ return [2 /*return*/];
71
+ if (fresh)
72
+ optionsRef.current.onSessionRefreshed(fresh);
73
+ return [3 /*break*/, 4];
74
+ case 3:
75
+ error_1 = _b.sent();
76
+ console.error("Failed to reload the session before a remote navigation:", error_1);
77
+ return [3 /*break*/, 4];
78
+ case 4:
79
+ if (decision.standby)
80
+ optionsRef.current.onStandby(decision.step);
81
+ optionsRef.current.applyRemoteStep(decision.step);
82
+ return [3 /*break*/, 13];
83
+ case 5:
84
+ current.applyRemoteFinish();
85
+ _b.label = 6;
86
+ case 6:
87
+ _b.trys.push([6, 8, , 9]);
88
+ return [4 /*yield*/, fetchSessionById(current.sessionId)];
89
+ case 7:
90
+ session = _b.sent();
91
+ if (session && !disposed.current)
92
+ optionsRef.current.onFinished(session);
93
+ return [3 /*break*/, 9];
94
+ case 8:
95
+ error_2 = _b.sent();
96
+ console.error("Failed to reload the finished session:", error_2);
97
+ return [3 /*break*/, 9];
98
+ case 9: return [3 /*break*/, 13];
99
+ case 10:
100
+ // Session supprimée : plus rien à poursuivre, même écran qu'une expiration.
101
+ current.onExpired();
102
+ return [3 /*break*/, 13];
103
+ case 11:
104
+ current.onAbandoned();
105
+ return [3 /*break*/, 13];
106
+ case 12: return [3 /*break*/, 13];
107
+ case 13: return [2 /*return*/];
108
+ }
109
+ });
110
+ }); }, []);
111
+ var enqueue = useCallback(function (event) {
112
+ queue.current = queue.current.then(function () { return process(event); }).catch(function (error) {
113
+ console.error("Remote session sync failed:", error);
114
+ });
115
+ }, [process]);
116
+ useEffect(function () {
117
+ disposed.current = false;
118
+ return function () {
119
+ disposed.current = true;
120
+ clearTimeout(retryTimer.current);
121
+ };
122
+ }, []);
123
+ useSessionEventStream({
124
+ sessionId: options.sessionId,
125
+ path: "events",
126
+ enabled: options.enabled && Boolean(options.template),
127
+ apiBaseUrl: options.apiBaseUrl,
128
+ onEvent: enqueue,
129
+ isTerminal: isTerminalSessionEvent,
130
+ });
131
+ }
132
+
133
+ export { useRemoteSessionSync };
@@ -170,6 +170,24 @@ var useSessionData = function (sessionId, clientInfo, clientInfoLoaded) {
170
170
  });
171
171
  }); };
172
172
  var userInputSyncInitialized = useRef(false);
173
+ // Saisies venues du serveur (synchro multi-appareils) : à appliquer localement sans les renvoyer.
174
+ var skipNextUserInputSync = useRef(false);
175
+ /**
176
+ * APP3-2030 — remplace la session par celle relue au serveur après un changement fait sur un
177
+ * autre appareil. Les saisies serveur priment sur les saisies locales : sans cela, le prochain
178
+ * envoi de `userInput` (fusion au premier niveau côté serveur) écraserait celles de l'autre appareil.
179
+ */
180
+ var applyRemoteSession = function (freshSession) {
181
+ setSession(freshSession);
182
+ var serverInput = freshSession.userInput && typeof freshSession.userInput === "object" && !Array.isArray(freshSession.userInput)
183
+ ? freshSession.userInput
184
+ : {};
185
+ if (Object.keys(serverInput).length === 0)
186
+ return;
187
+ skipNextUserInputSync.current = true;
188
+ setUserInput(function (prev) { return (__assign(__assign({}, prev), serverInput)); });
189
+ setSessionMemoryUserInput(sessionId, __assign(__assign({}, getSessionMemoryUserInput(sessionId)), serverInput));
190
+ };
173
191
  // Update user input in backend and in-memory store
174
192
  useEffect(function () {
175
193
  if (!sessionId) {
@@ -189,6 +207,10 @@ var useSessionData = function (sessionId, clientInfo, clientInfoLoaded) {
189
207
  userInputSyncInitialized.current = true;
190
208
  return;
191
209
  }
210
+ if (skipNextUserInputSync.current) {
211
+ skipNextUserInputSync.current = false;
212
+ return;
213
+ }
192
214
  if (entries.length === 0) {
193
215
  return;
194
216
  }
@@ -261,9 +283,12 @@ var useSessionData = function (sessionId, clientInfo, clientInfoLoaded) {
261
283
  updateContactData();
262
284
  }
263
285
  }, [contactInfo, sessionId]);
264
- // Send client info when it becomes available
286
+ // Send client info when it becomes available — once per session id: the session object
287
+ // is replaced on every remote refresh (APP3-2030) and must not re-log "session started".
288
+ var startEffectsSentFor = useRef(null);
265
289
  useEffect(function () {
266
- if (clientInfoLoaded && clientInfo && session) {
290
+ if (clientInfoLoaded && clientInfo && session && startEffectsSentFor.current !== sessionId) {
291
+ startEffectsSentFor.current = sessionId;
267
292
  console.log("Sending client info to backend:", maskClientInfoForLog(clientInfo));
268
293
  var sendClientInfoAsync = function () { return __awaiter(void 0, void 0, void 0, function () {
269
294
  var e_1;
@@ -365,6 +390,7 @@ var useSessionData = function (sessionId, clientInfo, clientInfoLoaded) {
365
390
  setContactInfo: setContactInfo,
366
391
  loadSession: loadSession,
367
392
  handleRetrySession: handleRetrySession,
393
+ applyRemoteSession: applyRemoteSession,
368
394
  };
369
395
  };
370
396
 
@@ -0,0 +1,86 @@
1
+ import { useRef, useEffect } from 'react';
2
+ import { getBaseURL } from '../services/api.js';
3
+ import { getSessionCredential } from '../services/sessionCredentials.js';
4
+ import { openSseStream } from '../services/realtime/sseClient.js';
5
+
6
+ /**
7
+ * Flux SSE d'une session, authentifié par le header `X-Session-Token` (jamais d'URL).
8
+ *
9
+ * Cycle de vie mobile : le flux reste ouvert quand la page passe en arrière-plan (geste
10
+ * normal pour scanner un QR avec le téléphone), se reconnecte au retour au premier plan
11
+ * ou à la restauration bfcache (le serveur renvoie alors l'état courant), et se ferme
12
+ * quand la page est réellement quittée (`pagehide`).
13
+ */
14
+ function useSessionEventStream(_a) {
15
+ var sessionId = _a.sessionId, path = _a.path, onEvent = _a.onEvent, isTerminal = _a.isTerminal, _b = _a.enabled, enabled = _b === void 0 ? true : _b, apiBaseUrl = _a.apiBaseUrl;
16
+ var onEventRef = useRef(onEvent);
17
+ onEventRef.current = onEvent;
18
+ var isTerminalRef = useRef(isTerminal);
19
+ isTerminalRef.current = isTerminal;
20
+ useEffect(function () {
21
+ if (!enabled || !sessionId)
22
+ return;
23
+ var baseUrl = apiBaseUrl !== null && apiBaseUrl !== void 0 ? apiBaseUrl : getBaseURL();
24
+ if (!baseUrl)
25
+ return;
26
+ var finished = false;
27
+ var leftPage = false;
28
+ var stream;
29
+ var open = function () {
30
+ return openSseStream({
31
+ url: "".concat(baseUrl, "/session/sdk/").concat(encodeURIComponent(sessionId), "/").concat(path),
32
+ headers: function () {
33
+ var token = getSessionCredential(sessionId);
34
+ return token ? { "X-Session-Token": token } : {};
35
+ },
36
+ onMessage: function (message) {
37
+ var _a;
38
+ if (finished || message.event === "heartbeat")
39
+ return;
40
+ var data;
41
+ try {
42
+ data = JSON.parse(message.data);
43
+ }
44
+ catch (_b) {
45
+ return;
46
+ }
47
+ onEventRef.current(data);
48
+ if ((_a = isTerminalRef.current) === null || _a === void 0 ? void 0 : _a.call(isTerminalRef, data)) {
49
+ finished = true;
50
+ stream.close();
51
+ }
52
+ },
53
+ onFatal: function () {
54
+ finished = true;
55
+ },
56
+ });
57
+ };
58
+ var resume = function () {
59
+ if (finished || document.visibilityState !== "visible")
60
+ return;
61
+ if (leftPage) {
62
+ leftPage = false;
63
+ stream = open();
64
+ }
65
+ else {
66
+ stream.reconnect();
67
+ }
68
+ };
69
+ var leave = function () {
70
+ leftPage = true;
71
+ stream.close();
72
+ };
73
+ stream = open();
74
+ window.addEventListener("pagehide", leave);
75
+ window.addEventListener("pageshow", resume);
76
+ document.addEventListener("visibilitychange", resume);
77
+ return function () {
78
+ window.removeEventListener("pagehide", leave);
79
+ window.removeEventListener("pageshow", resume);
80
+ document.removeEventListener("visibilitychange", resume);
81
+ stream.close();
82
+ };
83
+ }, [sessionId, path, enabled, apiBaseUrl]);
84
+ }
85
+
86
+ export { useSessionEventStream };
@@ -6,6 +6,8 @@ import { isSessionFinished } from '../utils/sessionStatus.js';
6
6
  /** Node types that auto-execute and should be skipped when going back */
7
7
  var AUTO_EXECUTING_TYPES = new Set(["external-verification", "condition", "complementary-mandate"]);
8
8
  var COMMITTED_NODE_TYPES = new Set(["selfie-capture", "biometric-capture"]);
9
+ /** Fenêtre pendant laquelle l'écho d'une navigation locale est attendu du serveur. */
10
+ var RECENT_LOCAL_WRITE_MS = 10000;
9
11
  var getNodeTypeAtStep = function (step, template) { var _a; return (_a = getOrderedJourneySteps(template)[step - 1]) === null || _a === void 0 ? void 0 : _a.type; };
10
12
  /**
11
13
  * Rebuilds only the reversible part of a path after a committed node.
@@ -39,6 +41,10 @@ var useStepNavigation = function (sessionId, sessionStatus, initialStep, templat
39
41
  var _b = useState(initialStep !== undefined ? [initialStep] : [0]), history = _b[0], setHistory = _b[1];
40
42
  var hasInitialized = useRef(false);
41
43
  var committedNavigationPending = useRef(false);
44
+ // PATCH de navigation non confirmés : la synchro distante attend qu'ils soient enregistrés.
45
+ var stepWritesInFlight = useRef(0);
46
+ // Étapes enregistrées localement récemment : leur écho différé ne doit pas faire reculer l'appareil.
47
+ var recentLocalWrites = useRef([]);
42
48
  var setStep = function (newStep, skipHistory) {
43
49
  var _a;
44
50
  if (skipHistory === void 0) { skipHistory = false; }
@@ -56,12 +62,24 @@ var useStepNavigation = function (sessionId, sessionStatus, initialStep, templat
56
62
  var nodeId = template && Number.isInteger(newStep) && newStep >= 1
57
63
  ? (_a = getOrderedJourneySteps(template)[newStep - 1]) === null || _a === void 0 ? void 0 : _a.id
58
64
  : undefined;
65
+ stepWritesInFlight.current += 1;
66
+ var now_1 = Date.now();
67
+ recentLocalWrites.current = __spreadArray(__spreadArray([], recentLocalWrites.current.filter(function (_a) {
68
+ var at = _a.at;
69
+ return now_1 - at < RECENT_LOCAL_WRITE_MS;
70
+ }), true), [
71
+ { step: newStep, at: now_1 },
72
+ ], false);
59
73
  var update = nodeId
60
74
  ? updateSessionCurrentStep(sessionId, newStep, nodeId)
61
75
  : updateSessionCurrentStep(sessionId, newStep);
62
- update.catch(function (error) {
76
+ update
77
+ .catch(function (error) {
63
78
  console.error("Failed to update current step in database:", error);
64
79
  // Non-blocking error - the step is still updated locally
80
+ })
81
+ .finally(function () {
82
+ stepWritesInFlight.current -= 1;
65
83
  });
66
84
  }
67
85
  };
@@ -164,6 +182,40 @@ var useStepNavigation = function (sessionId, sessionStatus, initialStep, templat
164
182
  console.warn("[useStepNavigation] Could not find next step for node ".concat(currentNodeId, ". Staying on current step."));
165
183
  }
166
184
  };
185
+ /**
186
+ * APP3-2030 — applique une étape atteinte sur un autre appareil. Aucun PATCH : le
187
+ * serveur la connaît déjà. Retour arrière : l'historique est tronqué ; sinon il est
188
+ * reconstruit comme au rechargement, point de non-retour compris.
189
+ */
190
+ var applyRemoteStep = function (remoteStep) {
191
+ committedNavigationPending.current = false;
192
+ setHistory(function (prev) {
193
+ var index = prev.lastIndexOf(remoteStep);
194
+ if (index !== -1)
195
+ return prev.slice(0, index + 1);
196
+ if (template) {
197
+ return trimHistoryAfterCommittedNode(reconstructHistoryToStep(remoteStep, template), template);
198
+ }
199
+ return remoteStep > 0 ? [0, remoteStep] : [remoteStep];
200
+ });
201
+ setStepState(remoteStep);
202
+ };
203
+ /** Fin de parcours constatée par le serveur : écran de fin, sans PATCH. */
204
+ var applyRemoteFinish = function () {
205
+ committedNavigationPending.current = false;
206
+ setStepState(100);
207
+ };
208
+ var isPersistingStep = function () { return stepWritesInFlight.current > 0; };
209
+ var getRecentLocalSteps = function () {
210
+ var now = Date.now();
211
+ return recentLocalWrites.current.filter(function (_a) {
212
+ var at = _a.at;
213
+ return now - at < RECENT_LOCAL_WRITE_MS;
214
+ }).map(function (_a) {
215
+ var written = _a.step;
216
+ return written;
217
+ });
218
+ };
167
219
  // Initialize step from session data or status
168
220
  useEffect(function () {
169
221
  if (!sessionId) {
@@ -210,6 +262,10 @@ var useStepNavigation = function (sessionId, sessionStatus, initialStep, templat
210
262
  goToNextStep: goToNextStep,
211
263
  skipToNextStep: skipToNextStep,
212
264
  goToNextStepCommitted: goToNextStepCommitted,
265
+ applyRemoteStep: applyRemoteStep,
266
+ applyRemoteFinish: applyRemoteFinish,
267
+ isPersistingStep: isPersistingStep,
268
+ getRecentLocalSteps: getRecentLocalSteps,
213
269
  stepObject: stepObject,
214
270
  history: history,
215
271
  };
@@ -130,6 +130,7 @@ var user_guidance = {
130
130
  "2.4": "The photo is not clear. Avoid any blur or reflection",
131
131
  "2.6": "The document submitted is not the expected one",
132
132
  QUOTA_EXCEEDED: "Your organisation has reached its verification quota. Please try again later or contact the organisation that sent you this link.",
133
+ TEST_ACCOUNT_CREDITS_EXHAUSTED: "This organisation's test credits are used up. Please contact them to continue the verification.",
133
134
  INSUFFICIENT_CREDITS: "The organisation that sent you this link has run out of verification credits. Please contact them to complete your verification."
134
135
  };
135
136
  var validation_points = {
@@ -904,6 +905,15 @@ var session = {
904
905
  description: "This session is no longer valid, please restart.",
905
906
  retry: "Retry"
906
907
  },
908
+ abandoned: {
909
+ title: "Session abandoned",
910
+ description: "This session has been closed and can no longer be continued."
911
+ },
912
+ continued_elsewhere: {
913
+ title: "Journey continued on another device",
914
+ description: "This step is in progress on another device. You can continue it here if you prefer.",
915
+ resume: "Continue on this device"
916
+ },
907
917
  end: {
908
918
  button_redirecting: "Redirecting...",
909
919
  button_finalizing: "Finalizing...",
@@ -130,6 +130,7 @@ var user_guidance = {
130
130
  "2.4": "La foto no es clara. Evita desenfoques y reflejos",
131
131
  "2.6": "El documento enviado no es el esperado",
132
132
  QUOTA_EXCEEDED: "Su organización ha alcanzado su cuota de verificaciones. Inténtelo de nuevo más tarde o póngase en contacto con la organización que le envió este enlace.",
133
+ TEST_ACCOUNT_CREDITS_EXHAUSTED: "Los créditos de prueba de esta organización se han agotado. Póngase en contacto con ella para continuar la verificación.",
133
134
  INSUFFICIENT_CREDITS: "La organización que le envió este enlace no tiene más créditos de verificación. Póngase en contacto con ella para completar su trámite."
134
135
  };
135
136
  var validation_points = {
@@ -904,6 +905,15 @@ var session = {
904
905
  description: "Esta sesión ya no es válida. Reinicia el proceso.",
905
906
  retry: "Reintentar"
906
907
  },
908
+ abandoned: {
909
+ title: "Sesión abandonada",
910
+ description: "Esta sesión se ha cerrado y ya no se puede continuar."
911
+ },
912
+ continued_elsewhere: {
913
+ title: "Recorrido continuado en otro dispositivo",
914
+ description: "Este paso está en curso en otro dispositivo. Puede continuarlo aquí si lo prefiere.",
915
+ resume: "Continuar en este dispositivo"
916
+ },
907
917
  end: {
908
918
  button_redirecting: "Redirigiendo...",
909
919
  button_finalizing: "Finalizando...",
@@ -130,6 +130,7 @@ var user_guidance = {
130
130
  "2.4": "La photo n'est pas nette. Évitez tout flou ou reflet",
131
131
  "2.6": "Le document déposé n'est pas celui attendu",
132
132
  QUOTA_EXCEEDED: "Le quota de vérifications de votre organisation est atteint. Veuillez réessayer plus tard ou contacter l'organisation qui vous a envoyé ce lien.",
133
+ TEST_ACCOUNT_CREDITS_EXHAUSTED: "Les crédits de test de cette organisation sont épuisés. Veuillez la contacter pour poursuivre la vérification.",
133
134
  INSUFFICIENT_CREDITS: "L'organisation qui vous a envoyé ce lien n'a plus de crédits de vérification. Veuillez la contacter pour finaliser votre démarche."
134
135
  };
135
136
  var validation_points = {
@@ -904,6 +905,15 @@ var session = {
904
905
  description: "Cette session n'est plus valide, veuillez recommencer.",
905
906
  retry: "Réessayer"
906
907
  },
908
+ abandoned: {
909
+ title: "Session abandonnée",
910
+ description: "Cette session a été clôturée et ne peut plus être poursuivie."
911
+ },
912
+ continued_elsewhere: {
913
+ title: "Parcours poursuivi sur un autre appareil",
914
+ description: "Cette étape est en cours sur un autre appareil. Vous pouvez la poursuivre ici si vous le souhaitez.",
915
+ resume: "Continuer sur cet appareil"
916
+ },
907
917
  end: {
908
918
  button_redirecting: "Redirection...",
909
919
  button_finalizing: "Finalisation...",