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
@@ -8,6 +8,8 @@ var sessionStatus = require('../utils/sessionStatus.js');
8
8
  /** Node types that auto-execute and should be skipped when going back */
9
9
  var AUTO_EXECUTING_TYPES = new Set(["external-verification", "condition", "complementary-mandate"]);
10
10
  var COMMITTED_NODE_TYPES = new Set(["selfie-capture", "biometric-capture"]);
11
+ /** Fenêtre pendant laquelle l'écho d'une navigation locale est attendu du serveur. */
12
+ var RECENT_LOCAL_WRITE_MS = 10000;
11
13
  var getNodeTypeAtStep = function (step, template) { var _a; return (_a = sessionService.getOrderedJourneySteps(template)[step - 1]) === null || _a === void 0 ? void 0 : _a.type; };
12
14
  /**
13
15
  * Rebuilds only the reversible part of a path after a committed node.
@@ -41,6 +43,10 @@ var useStepNavigation = function (sessionId, sessionStatus$1, initialStep, templ
41
43
  var _b = React.useState(initialStep !== undefined ? [initialStep] : [0]), history = _b[0], setHistory = _b[1];
42
44
  var hasInitialized = React.useRef(false);
43
45
  var committedNavigationPending = React.useRef(false);
46
+ // PATCH de navigation non confirmés : la synchro distante attend qu'ils soient enregistrés.
47
+ var stepWritesInFlight = React.useRef(0);
48
+ // Étapes enregistrées localement récemment : leur écho différé ne doit pas faire reculer l'appareil.
49
+ var recentLocalWrites = React.useRef([]);
44
50
  var setStep = function (newStep, skipHistory) {
45
51
  var _a;
46
52
  if (skipHistory === void 0) { skipHistory = false; }
@@ -58,12 +64,24 @@ var useStepNavigation = function (sessionId, sessionStatus$1, initialStep, templ
58
64
  var nodeId = template && Number.isInteger(newStep) && newStep >= 1
59
65
  ? (_a = sessionService.getOrderedJourneySteps(template)[newStep - 1]) === null || _a === void 0 ? void 0 : _a.id
60
66
  : undefined;
67
+ stepWritesInFlight.current += 1;
68
+ var now_1 = Date.now();
69
+ recentLocalWrites.current = tslib_es6.__spreadArray(tslib_es6.__spreadArray([], recentLocalWrites.current.filter(function (_a) {
70
+ var at = _a.at;
71
+ return now_1 - at < RECENT_LOCAL_WRITE_MS;
72
+ }), true), [
73
+ { step: newStep, at: now_1 },
74
+ ], false);
61
75
  var update = nodeId
62
76
  ? sessionService.updateSessionCurrentStep(sessionId, newStep, nodeId)
63
77
  : sessionService.updateSessionCurrentStep(sessionId, newStep);
64
- update.catch(function (error) {
78
+ update
79
+ .catch(function (error) {
65
80
  console.error("Failed to update current step in database:", error);
66
81
  // Non-blocking error - the step is still updated locally
82
+ })
83
+ .finally(function () {
84
+ stepWritesInFlight.current -= 1;
67
85
  });
68
86
  }
69
87
  };
@@ -166,6 +184,40 @@ var useStepNavigation = function (sessionId, sessionStatus$1, initialStep, templ
166
184
  console.warn("[useStepNavigation] Could not find next step for node ".concat(currentNodeId, ". Staying on current step."));
167
185
  }
168
186
  };
187
+ /**
188
+ * APP3-2030 — applique une étape atteinte sur un autre appareil. Aucun PATCH : le
189
+ * serveur la connaît déjà. Retour arrière : l'historique est tronqué ; sinon il est
190
+ * reconstruit comme au rechargement, point de non-retour compris.
191
+ */
192
+ var applyRemoteStep = function (remoteStep) {
193
+ committedNavigationPending.current = false;
194
+ setHistory(function (prev) {
195
+ var index = prev.lastIndexOf(remoteStep);
196
+ if (index !== -1)
197
+ return prev.slice(0, index + 1);
198
+ if (template) {
199
+ return trimHistoryAfterCommittedNode(sessionService.reconstructHistoryToStep(remoteStep, template), template);
200
+ }
201
+ return remoteStep > 0 ? [0, remoteStep] : [remoteStep];
202
+ });
203
+ setStepState(remoteStep);
204
+ };
205
+ /** Fin de parcours constatée par le serveur : écran de fin, sans PATCH. */
206
+ var applyRemoteFinish = function () {
207
+ committedNavigationPending.current = false;
208
+ setStepState(100);
209
+ };
210
+ var isPersistingStep = function () { return stepWritesInFlight.current > 0; };
211
+ var getRecentLocalSteps = function () {
212
+ var now = Date.now();
213
+ return recentLocalWrites.current.filter(function (_a) {
214
+ var at = _a.at;
215
+ return now - at < RECENT_LOCAL_WRITE_MS;
216
+ }).map(function (_a) {
217
+ var written = _a.step;
218
+ return written;
219
+ });
220
+ };
169
221
  // Initialize step from session data or status
170
222
  React.useEffect(function () {
171
223
  if (!sessionId) {
@@ -212,6 +264,10 @@ var useStepNavigation = function (sessionId, sessionStatus$1, initialStep, templ
212
264
  goToNextStep: goToNextStep,
213
265
  skipToNextStep: skipToNextStep,
214
266
  goToNextStepCommitted: goToNextStepCommitted,
267
+ applyRemoteStep: applyRemoteStep,
268
+ applyRemoteFinish: applyRemoteFinish,
269
+ isPersistingStep: isPersistingStep,
270
+ getRecentLocalSteps: getRecentLocalSteps,
215
271
  stepObject: stepObject,
216
272
  history: history,
217
273
  };
@@ -134,6 +134,7 @@ var user_guidance = {
134
134
  "2.4": "The photo is not clear. Avoid any blur or reflection",
135
135
  "2.6": "The document submitted is not the expected one",
136
136
  QUOTA_EXCEEDED: "Your organisation has reached its verification quota. Please try again later or contact the organisation that sent you this link.",
137
+ TEST_ACCOUNT_CREDITS_EXHAUSTED: "This organisation's test credits are used up. Please contact them to continue the verification.",
137
138
  INSUFFICIENT_CREDITS: "The organisation that sent you this link has run out of verification credits. Please contact them to complete your verification."
138
139
  };
139
140
  var validation_points = {
@@ -908,6 +909,15 @@ var session = {
908
909
  description: "This session is no longer valid, please restart.",
909
910
  retry: "Retry"
910
911
  },
912
+ abandoned: {
913
+ title: "Session abandoned",
914
+ description: "This session has been closed and can no longer be continued."
915
+ },
916
+ continued_elsewhere: {
917
+ title: "Journey continued on another device",
918
+ description: "This step is in progress on another device. You can continue it here if you prefer.",
919
+ resume: "Continue on this device"
920
+ },
911
921
  end: {
912
922
  button_redirecting: "Redirecting...",
913
923
  button_finalizing: "Finalizing...",
@@ -134,6 +134,7 @@ var user_guidance = {
134
134
  "2.4": "La foto no es clara. Evita desenfoques y reflejos",
135
135
  "2.6": "El documento enviado no es el esperado",
136
136
  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.",
137
+ 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.",
137
138
  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."
138
139
  };
139
140
  var validation_points = {
@@ -908,6 +909,15 @@ var session = {
908
909
  description: "Esta sesión ya no es válida. Reinicia el proceso.",
909
910
  retry: "Reintentar"
910
911
  },
912
+ abandoned: {
913
+ title: "Sesión abandonada",
914
+ description: "Esta sesión se ha cerrado y ya no se puede continuar."
915
+ },
916
+ continued_elsewhere: {
917
+ title: "Recorrido continuado en otro dispositivo",
918
+ description: "Este paso está en curso en otro dispositivo. Puede continuarlo aquí si lo prefiere.",
919
+ resume: "Continuar en este dispositivo"
920
+ },
911
921
  end: {
912
922
  button_redirecting: "Redirigiendo...",
913
923
  button_finalizing: "Finalizando...",
@@ -134,6 +134,7 @@ var user_guidance = {
134
134
  "2.4": "La photo n'est pas nette. Évitez tout flou ou reflet",
135
135
  "2.6": "Le document déposé n'est pas celui attendu",
136
136
  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.",
137
+ TEST_ACCOUNT_CREDITS_EXHAUSTED: "Les crédits de test de cette organisation sont épuisés. Veuillez la contacter pour poursuivre la vérification.",
137
138
  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."
138
139
  };
139
140
  var validation_points = {
@@ -908,6 +909,15 @@ var session = {
908
909
  description: "Cette session n'est plus valide, veuillez recommencer.",
909
910
  retry: "Réessayer"
910
911
  },
912
+ abandoned: {
913
+ title: "Session abandonnée",
914
+ description: "Cette session a été clôturée et ne peut plus être poursuivie."
915
+ },
916
+ continued_elsewhere: {
917
+ title: "Parcours poursuivi sur un autre appareil",
918
+ description: "Cette étape est en cours sur un autre appareil. Vous pouvez la poursuivre ici si vous le souhaitez.",
919
+ resume: "Continuer sur cet appareil"
920
+ },
911
921
  end: {
912
922
  button_redirecting: "Redirection...",
913
923
  button_finalizing: "Finalisation...",
@@ -0,0 +1,106 @@
1
+ 'use strict';
2
+
3
+ var sessionService = require('../sessionService.js');
4
+ var sessionStatus = require('../../utils/sessionStatus.js');
5
+
6
+ /**
7
+ * Nœuds jamais rejoints par synchro : ils s'exécutent seuls (condition, appel INPI, PDF,
8
+ * mandat, fin) sur l'appareil qui y arrive. L'autre appareil attend l'événement suivant,
9
+ * qui porte leur résultat, plutôt que de les ré-exécuter.
10
+ */
11
+ var SYNC_SKIPPED_TYPES = new Set([
12
+ "condition",
13
+ "external-verification",
14
+ "complementary-mandate",
15
+ "pdf-generation",
16
+ "end",
17
+ ]);
18
+ var COMMITTED_NODE_TYPES = new Set(["selfie-capture", "biometric-capture"]);
19
+ /**
20
+ * Nœuds de capture ou de signature : les monter a des effets (appel Unissey `iad/prepare`,
21
+ * demande caméra, audit d'ouverture DocuSeal). L'appareil passif les rejoint en attente
22
+ * (« poursuivi sur un autre appareil ») et ne les monte que si l'usager le demande.
23
+ */
24
+ var STANDBY_NODE_TYPES = new Set(["selfie-capture", "biometric-capture", "signature-electronic", "video-capture"]);
25
+ /** Seuls ces types sont traités ; un type ajouté plus tard au contrat est ignoré par ce SDK. */
26
+ var HANDLED_EVENT_TYPES = new Set(["session.snapshot", "session.progress.updated", "session.status.changed", "session.deleted"]);
27
+ var ignore = function (reason) { return ({ action: "ignore", reason: reason }); };
28
+ /** Le chemin (première branche, comme au rechargement) jusqu'à `step` franchit un point de non-retour. */
29
+ function isPastCommit(step, template) {
30
+ if (step < 1)
31
+ return false;
32
+ var ordered = sessionService.getOrderedJourneySteps(template);
33
+ return sessionService.reconstructHistoryToStep(step, template)
34
+ .slice(0, -1)
35
+ .some(function (visited) { var _a, _b; return COMMITTED_NODE_TYPES.has((_b = (_a = ordered[visited - 1]) === null || _a === void 0 ? void 0 : _a.type) !== null && _b !== void 0 ? _b : ""); });
36
+ }
37
+ function resolveTarget(data, template) {
38
+ var ordered = sessionService.getOrderedJourneySteps(template);
39
+ if (data.currentNodeId) {
40
+ var index = ordered.findIndex(function (node) { return node.id === data.currentNodeId; });
41
+ return index === -1 ? null : { step: index + 1, nodeId: data.currentNodeId };
42
+ }
43
+ var step = data.currentStep;
44
+ if (step === 0 || step === 0.5)
45
+ return { step: step, nodeId: null };
46
+ if (step !== null && Number.isInteger(step) && step >= 1 && step <= ordered.length) {
47
+ return { step: step, nodeId: ordered[step - 1].id };
48
+ }
49
+ return null;
50
+ }
51
+ /**
52
+ * Décide quoi faire d'un événement temps réel reçu pour la session (fonction pure).
53
+ * Le serveur est la référence ; l'appareil n'applique jamais un état plus ancien que
54
+ * celui déjà traité et ne renvoie rien au serveur.
55
+ */
56
+ function decideRemoteSync(state, event, template) {
57
+ if (state.lastRevision !== null && event.revision <= state.lastRevision)
58
+ return ignore("stale");
59
+ if (!HANDLED_EVENT_TYPES.has(event.type))
60
+ return ignore("unsupported");
61
+ if (state.localNavigationInFlight)
62
+ return { action: "defer" };
63
+ if (event.type === "session.deleted")
64
+ return { action: "close" };
65
+ if (event.type === "session.nfc.updated" || !event.data)
66
+ return ignore("unsupported");
67
+ var status = event.data.status;
68
+ var target = resolveTarget(event.data, template);
69
+ var node = target && target.step >= 1 ? sessionService.getOrderedJourneySteps(template)[target.step - 1] : undefined;
70
+ // Seul `ended` signe la fin à coup sûr. Un statut consolidé (verify, ai_*, user_*) peut être
71
+ // écrit en plein parcours (échec NFC définitif, réversible par `nfc-reset`) : il ne termine
72
+ // que s'il accompagne le nœud `end`.
73
+ if (status === "ended" || (sessionStatus.isSessionFinished(status) && (node === null || node === void 0 ? void 0 : node.type) === "end"))
74
+ return { action: "finish" };
75
+ if (status === "expired")
76
+ return { action: "expire" };
77
+ if (status === "abandoned")
78
+ return { action: "abandon" };
79
+ if (state.step === 100)
80
+ return ignore("finished");
81
+ if (state.handoffLocked && state.step === 0.5)
82
+ return ignore("handoff-locked");
83
+ if (!target)
84
+ return ignore("unknown-node");
85
+ if (node && SYNC_SKIPPED_TYPES.has(node.type))
86
+ return ignore("auto-executing");
87
+ if (target.step === state.step)
88
+ return ignore("same-node");
89
+ if (state.recentLocalSteps.includes(target.step))
90
+ return ignore("own-echo");
91
+ if (isPastCommit(state.step, template) && !isPastCommit(target.step, template))
92
+ return ignore("behind-commit");
93
+ return { action: "navigate", step: target.step, nodeId: target.nodeId, standby: Boolean(node && STANDBY_NODE_TYPES.has(node.type)) };
94
+ }
95
+ /** Le flux se ferme définitivement après ces événements. */
96
+ function isTerminalSessionEvent(event) {
97
+ if (event.type === "session.deleted")
98
+ return true;
99
+ if (event.type === "session.nfc.updated" || !HANDLED_EVENT_TYPES.has(event.type) || !event.data)
100
+ return false;
101
+ var status = event.data.status;
102
+ return status === "ended" || status === "expired" || status === "abandoned";
103
+ }
104
+
105
+ exports.decideRemoteSync = decideRemoteSync;
106
+ exports.isTerminalSessionEvent = isTerminalSessionEvent;
@@ -0,0 +1,127 @@
1
+ 'use strict';
2
+
3
+ var tslib_es6 = require('../../node_modules/tslib/tslib.es6.js');
4
+ var sseParser = require('./sseParser.js');
5
+
6
+ var FATAL_STATUSES = new Set([401, 403, 404]);
7
+ /**
8
+ * Client SSE sur `fetch` : contrairement à EventSource, il envoie des headers, donc le
9
+ * credential de session ne passe jamais dans l'URL (ni dans les logs des proxys).
10
+ * Reconnexion avec backoff exponentiel + jitter, reprise par `Last-Event-ID`.
11
+ */
12
+ function openSseStream(_a) {
13
+ var url = _a.url, headers = _a.headers, onMessage = _a.onMessage, onFatal = _a.onFatal, _b = _a.fetchImpl, fetchImpl = _b === void 0 ? function () {
14
+ var args = [];
15
+ for (var _i = 0; _i < arguments.length; _i++) {
16
+ args[_i] = arguments[_i];
17
+ }
18
+ return fetch.apply(void 0, args);
19
+ } : _b, _c = _a.initialRetryMs, initialRetryMs = _c === void 0 ? 1000 : _c, _d = _a.maxRetryMs, maxRetryMs = _d === void 0 ? 30000 : _d, _e = _a.idleTimeoutMs, idleTimeoutMs = _e === void 0 ? 60000 : _e, _f = _a.random, random = _f === void 0 ? Math.random : _f;
20
+ var closed = false;
21
+ var controller = null;
22
+ var timer;
23
+ var attempt = 0;
24
+ var lastEventId;
25
+ var schedule = function () {
26
+ var base = Math.min(maxRetryMs, initialRetryMs * Math.pow(2, attempt));
27
+ attempt += 1;
28
+ timer = setTimeout(connect, base * (0.5 + random()));
29
+ };
30
+ function connect() {
31
+ return tslib_es6.__awaiter(this, void 0, void 0, function () {
32
+ var current, received, idleTimer, armIdleTimer, response, reader, decoder, parser, _a, done, value;
33
+ return tslib_es6.__generator(this, function (_c) {
34
+ switch (_c.label) {
35
+ case 0:
36
+ clearTimeout(timer);
37
+ controller === null || controller === void 0 ? void 0 : controller.abort();
38
+ current = new AbortController();
39
+ controller = current;
40
+ received = false;
41
+ armIdleTimer = function () {
42
+ clearTimeout(idleTimer);
43
+ idleTimer = setTimeout(function () {
44
+ // Connexion à moitié morte (ni données ni heartbeat) : on la remplace.
45
+ current.abort();
46
+ if (current === controller && !closed)
47
+ schedule();
48
+ }, idleTimeoutMs);
49
+ };
50
+ _c.label = 1;
51
+ case 1:
52
+ _c.trys.push([1, 7, 8, 9]);
53
+ return [4 /*yield*/, fetchImpl(url, {
54
+ method: "GET",
55
+ headers: tslib_es6.__assign(tslib_es6.__assign({ Accept: "text/event-stream" }, headers()), (lastEventId ? { "Last-Event-ID": lastEventId } : {})),
56
+ cache: "no-store",
57
+ credentials: "omit",
58
+ signal: current.signal,
59
+ })];
60
+ case 2:
61
+ response = _c.sent();
62
+ if (current !== controller || closed)
63
+ return [2 /*return*/];
64
+ if (FATAL_STATUSES.has(response.status)) {
65
+ closed = true;
66
+ onFatal === null || onFatal === void 0 ? void 0 : onFatal(response.status);
67
+ return [2 /*return*/];
68
+ }
69
+ if (!response.ok || !response.body)
70
+ throw new Error("SSE HTTP ".concat(response.status));
71
+ reader = response.body.getReader();
72
+ decoder = new TextDecoder();
73
+ parser = sseParser.createSseParser(function (message) {
74
+ // Un `event: error` (refus après ouverture : plafond, session disparue) n'est pas une
75
+ // connexion réussie : le backoff continue de croître.
76
+ if (message.event !== "error")
77
+ received = true;
78
+ if (message.id !== undefined)
79
+ lastEventId = message.id;
80
+ onMessage(message);
81
+ });
82
+ armIdleTimer();
83
+ _c.label = 3;
84
+ case 3: return [4 /*yield*/, reader.read()];
85
+ case 4:
86
+ _a = _c.sent(), done = _a.done, value = _a.value;
87
+ armIdleTimer();
88
+ if (done || current.signal.aborted)
89
+ return [3 /*break*/, 6];
90
+ parser.push(decoder.decode(value, { stream: true }));
91
+ _c.label = 5;
92
+ case 5: return [3 /*break*/, 3];
93
+ case 6: return [3 /*break*/, 9];
94
+ case 7:
95
+ _c.sent();
96
+ return [3 /*break*/, 9];
97
+ case 8:
98
+ clearTimeout(idleTimer);
99
+ return [7 /*endfinally*/];
100
+ case 9:
101
+ if (current !== controller || closed || current.signal.aborted)
102
+ return [2 /*return*/];
103
+ if (received)
104
+ attempt = 0;
105
+ schedule();
106
+ return [2 /*return*/];
107
+ }
108
+ });
109
+ });
110
+ }
111
+ void connect();
112
+ return {
113
+ close: function () {
114
+ closed = true;
115
+ clearTimeout(timer);
116
+ controller === null || controller === void 0 ? void 0 : controller.abort();
117
+ },
118
+ reconnect: function () {
119
+ if (closed)
120
+ return;
121
+ attempt = 0;
122
+ void connect();
123
+ },
124
+ };
125
+ }
126
+
127
+ exports.openSseStream = openSseStream;
@@ -0,0 +1,58 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Parseur incrémental du format text/event-stream (spécification HTML).
5
+ * Reçoit des chunks texte arbitraires et émet un message par bloc terminé.
6
+ */
7
+ function createSseParser(onMessage, onRetry) {
8
+ var buffer = "";
9
+ var id;
10
+ var event = "";
11
+ var data = [];
12
+ var dispatch = function () {
13
+ if (data.length > 0)
14
+ onMessage({ id: id, event: event || "message", data: data.join("\n") });
15
+ event = "";
16
+ data = [];
17
+ };
18
+ var line = function (raw) {
19
+ if (raw === "") {
20
+ dispatch();
21
+ return;
22
+ }
23
+ if (raw.startsWith(":"))
24
+ return;
25
+ var colon = raw.indexOf(":");
26
+ var field = colon === -1 ? raw : raw.slice(0, colon);
27
+ var value = colon === -1 ? "" : raw.slice(colon + 1);
28
+ if (value.startsWith(" "))
29
+ value = value.slice(1);
30
+ if (field === "data")
31
+ data.push(value);
32
+ else if (field === "event")
33
+ event = value;
34
+ else if (field === "id")
35
+ id = value;
36
+ else ;
37
+ };
38
+ // Un \r en fin de chunk termine la ligne ; le \n qui suivrait au chunk suivant appartient au même \r\n.
39
+ var skipLeadingLf = false;
40
+ return {
41
+ push: function (chunk) {
42
+ buffer += skipLeadingLf && chunk.startsWith("\n") ? chunk.slice(1) : chunk;
43
+ skipLeadingLf = false;
44
+ var newline = /\r\n|\n|\r/g;
45
+ var consumed = 0;
46
+ var match;
47
+ while ((match = newline.exec(buffer)) !== null) {
48
+ line(buffer.slice(consumed, match.index));
49
+ consumed = match.index + match[0].length;
50
+ if (match[0] === "\r" && consumed === buffer.length)
51
+ skipLeadingLf = true;
52
+ }
53
+ buffer = buffer.slice(consumed);
54
+ },
55
+ };
56
+ }
57
+
58
+ exports.createSseParser = createSseParser;
@@ -31,7 +31,15 @@ var QUOTA_EXCEEDED_CODE = "QUOTA_EXCEEDED";
31
31
  // Must stay aligned with INSUFFICIENT_CREDITS_CODE in the backend
32
32
  // (src/common/constants/quota-exceeded.constant.ts): overdraft cap reached.
33
33
  var INSUFFICIENT_CREDITS_CODE = "INSUFFICIENT_CREDITS";
34
- var SERVICE_ERROR_CODES = [QUOTA_EXCEEDED_CODE, INSUFFICIENT_CREDITS_CODE];
34
+ // Must stay aligned with TEST_ACCOUNT_CREDITS_EXHAUSTED_CODE in the backend:
35
+ // a Test account (no overdraft) has used up its credits. Polled analyses carry
36
+ // the `insufficient_credits` codeName instead (same backend fallback document).
37
+ var TEST_ACCOUNT_CREDITS_EXHAUSTED_CODE = "TEST_ACCOUNT_CREDITS_EXHAUSTED";
38
+ var SERVICE_ERROR_CODES = [
39
+ QUOTA_EXCEEDED_CODE,
40
+ INSUFFICIENT_CREDITS_CODE,
41
+ TEST_ACCOUNT_CREDITS_EXHAUSTED_CODE,
42
+ ];
35
43
  // codeName of the backend fallback document (origin api_failure) returned by
36
44
  // analysis-status polling when the async analysis was refused.
37
45
  var SERVICE_ERROR_CODE_NAMES = {
@@ -64,6 +72,7 @@ exports.ANALYSIS_FAILED_CODE = ANALYSIS_FAILED_CODE;
64
72
  exports.INSUFFICIENT_CREDITS_CODE = INSUFFICIENT_CREDITS_CODE;
65
73
  exports.QUOTA_EXCEEDED_CODE = QUOTA_EXCEEDED_CODE;
66
74
  exports.S3_UPLOAD_NOT_CONFIRMED_CODE = S3_UPLOAD_NOT_CONFIRMED_CODE;
75
+ exports.TEST_ACCOUNT_CREDITS_EXHAUSTED_CODE = TEST_ACCOUNT_CREDITS_EXHAUSTED_CODE;
67
76
  exports.getServiceErrorCode = getServiceErrorCode;
68
77
  exports.getServiceErrorCodeFromCodeName = getServiceErrorCodeFromCodeName;
69
78
  exports.isAnalysisFailedError = isAnalysisFailedError;
@@ -1,17 +1,19 @@
1
1
  import { __assign } from '../node_modules/tslib/tslib.es6.js';
2
2
  import { jsx, jsxs } from 'react/jsx-runtime';
3
3
  import { setSessionCredential } from '../services/sessionCredentials.js';
4
- import { useLayoutEffect, useEffect, useRef, useState, useMemo } from 'react';
4
+ import { useLayoutEffect, useState, useEffect, useRef, useMemo } from 'react';
5
5
  import Paper from './ui/Paper.js';
6
6
  import useIsMobile from '../hooks/useIsMobile.js';
7
7
  import PoweredBy from './ui/PoweredBy.js';
8
8
  import SessionExpired from './session/SessionExpired.js';
9
+ import SessionAbandoned from './session/SessionAbandoned.js';
9
10
  import { useRouteCSS } from '../hooks/useRouteCSS.js';
10
11
  import { DocumentProvider } from '../context/DocumentContext.js';
11
12
  import { ConfigProvider } from '../context/ConfigContext.js';
12
13
  import { setSessionStore } from '../context/SessionContext.js';
13
14
  import { useSessionData } from '../hooks/useSessionData.js';
14
15
  import { useStepNavigation } from '../hooks/useStepNavigation.js';
16
+ import { useRemoteSessionSync } from '../hooks/useRemoteSessionSync.js';
15
17
  import { useStepCSS } from '../hooks/useStepCSS.js';
16
18
  import { useTemplateLoader } from '../hooks/useTemplateLoader.js';
17
19
  import { useClientInfo } from '../hooks/useClientInfo.js';
@@ -43,7 +45,7 @@ import SessionContent from './session/SessionContent.js';
43
45
  */
44
46
  var DatakeenSession = function (_a) {
45
47
  var _b, _c, _d;
46
- var _e, _f, _g, _h, _j, _k, _l, _m, _o;
48
+ var _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
47
49
  var sessionId = _a.sessionId, sessionToken = _a.sessionToken, sessionConfig = _a.sessionConfig, apiBaseUrl = _a.apiBaseUrl;
48
50
  useLayoutEffect(function () {
49
51
  var fragmentToken = typeof window !== 'undefined' ? new URLSearchParams(window.location.hash.slice(1)).get('sessionToken') : null;
@@ -51,14 +53,44 @@ var DatakeenSession = function (_a) {
51
53
  return function () { return setSessionCredential(sessionId); };
52
54
  }, [sessionId, sessionToken, sessionConfig === null || sessionConfig === void 0 ? void 0 : sessionConfig.sessionToken]);
53
55
  var isMobile = useIsMobile();
54
- var _p = useClientInfo(), clientInfo = _p.info, clientInfoLoaded = _p.isLoaded;
56
+ var _q = useClientInfo(), clientInfo = _q.info, clientInfoLoaded = _q.isLoaded;
55
57
  var currentLanguage = useI18n().currentLanguage;
56
58
  // Load base CSS and UI components CSS that are always needed
57
59
  useRouteCSS("ui-components");
58
60
  // Session data management
59
- var _q = useSessionData(sessionId, clientInfo, clientInfoLoaded), session = _q.session, setSession = _q.setSession, loading = _q.loading, setLoading = _q.setLoading, error = _q.error, isExpired = _q.isExpired, userInput = _q.userInput, setUserInput = _q.setUserInput, contactInfo = _q.contactInfo, setContactInfo = _q.setContactInfo, loadSession = _q.loadSession, handleRetrySession = _q.handleRetrySession;
61
+ var _r = useSessionData(sessionId, clientInfo, clientInfoLoaded), session = _r.session, setSession = _r.setSession, loading = _r.loading, setLoading = _r.setLoading, error = _r.error, isExpired = _r.isExpired, userInput = _r.userInput, setUserInput = _r.setUserInput, contactInfo = _r.contactInfo, setContactInfo = _r.setContactInfo, loadSession = _r.loadSession, handleRetrySession = _r.handleRetrySession, applyRemoteSession = _r.applyRemoteSession;
60
62
  // Step navigation management
61
- var _r = useStepNavigation(sessionId, session === null || session === void 0 ? void 0 : session.status, session === null || session === void 0 ? void 0 : session.currentStep, session === null || session === void 0 ? void 0 : session.template), step = _r.step, stepObject = _r.stepObject, history = _r.history;
63
+ var _s = useStepNavigation(sessionId, session === null || session === void 0 ? void 0 : session.status, session === null || session === void 0 ? void 0 : session.currentStep, session === null || session === void 0 ? void 0 : session.template), step = _s.step, stepObject = _s.stepObject, history = _s.history, applyRemoteStep = _s.applyRemoteStep, applyRemoteFinish = _s.applyRemoteFinish, isPersistingStep = _s.isPersistingStep, getRecentLocalSteps = _s.getRecentLocalSteps;
64
+ // APP3-2030 — suit la progression faite sur un autre appareil ou onglet.
65
+ var _t = useState(false), remotelyFinished = _t[0], setRemotelyFinished = _t[1];
66
+ var _u = useState(null), remoteClosure = _u[0], setRemoteClosure = _u[1];
67
+ var _v = useState(null), standbyStep = _v[0], setStandbyStep = _v[1];
68
+ useEffect(function () {
69
+ if (standbyStep !== null && step !== standbyStep)
70
+ setStandbyStep(null);
71
+ }, [step, standbyStep]);
72
+ var platforms = (_e = session === null || session === void 0 ? void 0 : session.template) === null || _e === void 0 ? void 0 : _e.platforms;
73
+ var handoffLocked = !isMobile && ((sessionConfig === null || sessionConfig === void 0 ? void 0 : sessionConfig.requireMobile) === true || ((platforms === null || platforms === void 0 ? void 0 : platforms.mobile) === true && (platforms === null || platforms === void 0 ? void 0 : platforms.desktop) !== true));
74
+ useRemoteSessionSync({
75
+ sessionId: sessionId,
76
+ enabled: Boolean(session) && !loading && !error && (sessionConfig === null || sessionConfig === void 0 ? void 0 : sessionConfig.realtimeSync) !== false,
77
+ template: session === null || session === void 0 ? void 0 : session.template,
78
+ step: step,
79
+ handoffLocked: handoffLocked,
80
+ isPersistingStep: isPersistingStep,
81
+ getRecentLocalSteps: getRecentLocalSteps,
82
+ applyRemoteStep: applyRemoteStep,
83
+ applyRemoteFinish: applyRemoteFinish,
84
+ onSessionRefreshed: applyRemoteSession,
85
+ onStandby: setStandbyStep,
86
+ onFinished: function (finishedSession) {
87
+ setRemotelyFinished(true);
88
+ setSession(finishedSession);
89
+ },
90
+ onExpired: function () { return setRemoteClosure("expired"); },
91
+ onAbandoned: function () { return setRemoteClosure("abandoned"); },
92
+ apiBaseUrl: apiBaseUrl,
93
+ });
62
94
  // Load route-specific CSS based on current step
63
95
  useStepCSS(step, session);
64
96
  // Template loading logic
@@ -90,7 +122,8 @@ var DatakeenSession = function (_a) {
90
122
  // resserre les dépendances pour ne pas se re-déclencher à chaque mutation de session
91
123
  // (userInput, retryCounts, polling…) — ce qui relançait la boucle.
92
124
  useEffect(function () {
93
- if ((session === null || session === void 0 ? void 0 : session.status) !== "ended" || !session.template) {
125
+ // Fin venue d'un autre appareil : l'écran de fin s'affiche sans repositionner (ni PATCH).
126
+ if ((session === null || session === void 0 ? void 0 : session.status) !== "ended" || !session.template || remotelyFinished) {
94
127
  return;
95
128
  }
96
129
  var orderedSteps = getOrderedJourneySteps(session.template);
@@ -103,7 +136,7 @@ var DatakeenSession = function (_a) {
103
136
  }
104
137
  // Dépendances volontairement resserrées à status + template.id (cf. commentaire
105
138
  // ci-dessus) : ne pas inclure `session`/`stepObject` qui relanceraient la boucle.
106
- }, [session === null || session === void 0 ? void 0 : session.status, (_e = session === null || session === void 0 ? void 0 : session.template) === null || _e === void 0 ? void 0 : _e.id]);
139
+ }, [session === null || session === void 0 ? void 0 : session.status, (_f = session === null || session === void 0 ? void 0 : session.template) === null || _f === void 0 ? void 0 : _f.id]);
107
140
  if (!sessionId) {
108
141
  return jsx(NoSessionIdState, {});
109
142
  }
@@ -112,7 +145,7 @@ var DatakeenSession = function (_a) {
112
145
  var showMobilePoweredBy = isMobile && (loading || !!error || isExpired);
113
146
  var showDesktopPoweredBy = !isMobile && !loading && !error && !isExpired;
114
147
  var poweredByRef = useRef(null);
115
- var _s = useState(0), poweredByHeight = _s[0], setPoweredByHeight = _s[1];
148
+ var _w = useState(0), poweredByHeight = _w[0], setPoweredByHeight = _w[1];
116
149
  useLayoutEffect(function () {
117
150
  if (typeof window === "undefined" || !showMobilePoweredBy) {
118
151
  setPoweredByHeight(0);
@@ -139,10 +172,13 @@ var DatakeenSession = function (_a) {
139
172
  if (error) {
140
173
  return jsx(ErrorState, { error: error });
141
174
  }
142
- if (isExpired) {
175
+ if (isExpired || remoteClosure === "expired") {
143
176
  return jsx(SessionExpired, { onRetry: handleRetrySession });
144
177
  }
145
- return (jsx(SessionContent, { step: step, loading: loading, session: session, sessionId: sessionId, stepObject: stepObject, stepHistory: history, userInput: userInput, setUserInput: setUserInput, contactInfo: contactInfo, setContactInfo: setContactInfo }));
178
+ if (remoteClosure === "abandoned") {
179
+ return jsx(SessionAbandoned, {});
180
+ }
181
+ return (jsx(SessionContent, { step: step, loading: loading, session: session, sessionId: sessionId, stepObject: stepObject, stepHistory: history, userInput: userInput, setUserInput: setUserInput, contactInfo: contactInfo, setContactInfo: setContactInfo, remotelyFinished: remotelyFinished, standbyStep: standbyStep, onResumeHere: function () { return setStandbyStep(null); } }));
146
182
  };
147
183
  var mobileScrollPadding = showMobilePoweredBy
148
184
  ? "calc(".concat(poweredByHeight, "px + env(safe-area-inset-bottom, 0px))")
@@ -158,7 +194,7 @@ var DatakeenSession = function (_a) {
158
194
  var shouldUseWideDesktopLayout = (currentTemplateNode === null || currentTemplateNode === void 0 ? void 0 : currentTemplateNode.type) === "information-input" &&
159
195
  currentTemplateNode.informationType === "custom" &&
160
196
  (currentTemplateNode.customFields || []).some(function (field) { return field.valueType === "list"; });
161
- var _t = useState(false), isRecordingSelfie = _t[0], setIsRecordingSelfie = _t[1];
197
+ var _x = useState(false), isRecordingSelfie = _x[0], setIsRecordingSelfie = _x[1];
162
198
  useEffect(function () {
163
199
  if (typeof document === "undefined")
164
200
  return;
@@ -177,8 +213,8 @@ var DatakeenSession = function (_a) {
177
213
  (currentTemplateNode === null || currentTemplateNode === void 0 ? void 0 : currentTemplateNode.type) === "selfie-capture" ||
178
214
  (currentTemplateNode === null || currentTemplateNode === void 0 ? void 0 : currentTemplateNode.type) === "document-collection" || // Could be upload, but safer to allow full height
179
215
  (currentTemplateNode === null || currentTemplateNode === void 0 ? void 0 : currentTemplateNode.type) === "controle-jdi";
180
- var btnBg = (_g = (_f = session === null || session === void 0 ? void 0 : session.template) === null || _f === void 0 ? void 0 : _f.buttonBgColor) !== null && _g !== void 0 ? _g : "#11E5C5";
181
- var btnText = (_j = (_h = session === null || session === void 0 ? void 0 : session.template) === null || _h === void 0 ? void 0 : _h.buttonTextColor) !== null && _j !== void 0 ? _j : "#3C3C40";
216
+ var btnBg = (_h = (_g = session === null || session === void 0 ? void 0 : session.template) === null || _g === void 0 ? void 0 : _g.buttonBgColor) !== null && _h !== void 0 ? _h : "#11E5C5";
217
+ var btnText = (_k = (_j = session === null || session === void 0 ? void 0 : session.template) === null || _j === void 0 ? void 0 : _j.buttonTextColor) !== null && _k !== void 0 ? _k : "#3C3C40";
182
218
  return (jsx(ConfigProvider, { apiBaseUrl: apiBaseUrl, children: jsx(DocumentProvider, { children: jsx("div", { className: "sdk-session notranslate flex-1 flex flex-col", lang: currentLanguage, translate: "no", style: __assign((_c = {}, _c["--dk-btn-bg"] = btnBg, _c["--dk-btn-text"] = btnText, _c), (isMobile
183
219
  ? (_d = {},
184
220
  _d["--dk-mobile-scroll-padding"] = mobileScrollPadding,
@@ -188,13 +224,13 @@ var DatakeenSession = function (_a) {
188
224
  : "var(--dk-mobile-scroll-padding, env(safe-area-inset-bottom, 0px))",
189
225
  }, children: jsx("div", { className: "flex flex-1 flex-col min-h-0", children: renderSessionContent() }) }), showMobilePoweredBy && (jsx("div", { className: "bg-white px-4 pt-3 pb-4 sm:px-6 sm:pt-6 sm:pb-6", style: {
190
226
  paddingBottom: "calc(env(safe-area-inset-bottom, 0px) + 0.5rem)",
191
- }, ref: poweredByRef, children: jsx(PoweredBy, { logo: (_k = session === null || session === void 0 ? void 0 : session.template) === null || _k === void 0 ? void 0 : _k.logo, text: ((_l = session === null || session === void 0 ? void 0 : session.template) === null || _l === void 0 ? void 0 : _l.logo) ? "par" : undefined }) }))] })) : (jsx("div", { className: "flex items-center justify-center w-full min-h-screen bg-gray-100 py-12", children: jsxs("div", { className: "flex flex-col items-center justify-center", children: [jsx(Paper, { className: "dk-session-paper flex flex-col h-[800px] px-8 py-10 bg-white rounded-2xl shadow-xl z-10 ".concat(isRecordingSelfie
227
+ }, ref: poweredByRef, children: jsx(PoweredBy, { logo: (_l = session === null || session === void 0 ? void 0 : session.template) === null || _l === void 0 ? void 0 : _l.logo, text: ((_m = session === null || session === void 0 ? void 0 : session.template) === null || _m === void 0 ? void 0 : _m.logo) ? "par" : undefined }) }))] })) : (jsx("div", { className: "flex items-center justify-center w-full min-h-screen bg-gray-100 py-12", children: jsxs("div", { className: "flex flex-col items-center justify-center", children: [jsx(Paper, { className: "dk-session-paper flex flex-col h-[800px] px-8 py-10 bg-white rounded-2xl shadow-xl z-10 ".concat(isRecordingSelfie
192
228
  ? ""
193
229
  : shouldUseWideDesktopLayout
194
230
  ? "w-[98vw] max-w-[1500px]"
195
231
  : "w-[600px]"), style: isRecordingSelfie
196
232
  ? { width: "min(66vw, 942px)" }
197
- : undefined, children: jsx("div", { className: "flex-1 w-full h-full overflow-y-auto", children: renderSessionContent() }) }), showDesktopPoweredBy && (jsx("div", { className: "pt-6 text-center", children: jsx(PoweredBy, { logo: (_m = session === null || session === void 0 ? void 0 : session.template) === null || _m === void 0 ? void 0 : _m.logo, text: ((_o = session === null || session === void 0 ? void 0 : session.template) === null || _o === void 0 ? void 0 : _o.logo) ? "par" : undefined }) }))] }) })) }) }) }));
233
+ : undefined, children: jsx("div", { className: "flex-1 w-full h-full overflow-y-auto", children: renderSessionContent() }) }), showDesktopPoweredBy && (jsx("div", { className: "pt-6 text-center", children: jsx(PoweredBy, { logo: (_o = session === null || session === void 0 ? void 0 : session.template) === null || _o === void 0 ? void 0 : _o.logo, text: ((_p = session === null || session === void 0 ? void 0 : session.template) === null || _p === void 0 ? void 0 : _p.logo) ? "par" : undefined }) }))] }) })) }) }) }));
198
234
  };
199
235
 
200
236
  export { DatakeenSession as default };