@magicfeedback/popup-sdk 1.17.2 → 1.19.0

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 (55) hide show
  1. package/MagicfeedbackPopupSdk.podspec +18 -0
  2. package/README.md +33 -1
  3. package/dist/2.2.38-CCK7SF4A.mjs +2343 -0
  4. package/dist/2.2.38-CCK7SF4A.mjs.map +1 -0
  5. package/dist/2.2.38-LGZRM7GX.mjs +2343 -0
  6. package/dist/2.2.38-LGZRM7GX.mjs.map +1 -0
  7. package/dist/2.2.39-BJJ3YRJ4.mjs +2344 -0
  8. package/dist/2.2.39-BJJ3YRJ4.mjs.map +1 -0
  9. package/dist/2.2.39-HPNDYUPP.mjs +2344 -0
  10. package/dist/2.2.39-HPNDYUPP.mjs.map +1 -0
  11. package/dist/assets/assets/style.css +165 -1
  12. package/dist/assets/assets/survey-css/2.2.38.css +2335 -0
  13. package/dist/assets/assets/survey-css/2.2.39.css +2336 -0
  14. package/dist/chunk-3QS3WKRC.mjs +31 -0
  15. package/dist/chunk-3QS3WKRC.mjs.map +1 -0
  16. package/dist/chunk-7ZQOAKXR.mjs +3335 -0
  17. package/dist/chunk-7ZQOAKXR.mjs.map +1 -0
  18. package/dist/chunk-BJTO5JO5.mjs +11 -0
  19. package/dist/chunk-BJTO5JO5.mjs.map +1 -0
  20. package/dist/{chunk-AFRHPS3K.mjs → chunk-EW2ARDEY.mjs} +591 -51
  21. package/dist/chunk-EW2ARDEY.mjs.map +1 -0
  22. package/dist/{chunk-VHTN5UXD.mjs → chunk-XOEEBDBJ.mjs} +630 -10
  23. package/dist/chunk-XOEEBDBJ.mjs.map +1 -0
  24. package/dist/index.d.mts +159 -10
  25. package/dist/index.d.ts +159 -10
  26. package/dist/index.js +7275 -1466
  27. package/dist/index.js.map +1 -1
  28. package/dist/index.mjs +318 -41
  29. package/dist/index.mjs.map +1 -1
  30. package/dist/index.native.d.mts +1616 -0
  31. package/dist/index.native.d.ts +1616 -0
  32. package/dist/index.native.js +15853 -0
  33. package/dist/index.native.js.map +1 -0
  34. package/dist/index.native.mjs +3914 -0
  35. package/dist/index.native.mjs.map +1 -0
  36. package/dist/react-native.d.mts +105 -8
  37. package/dist/react-native.d.ts +105 -8
  38. package/dist/react-native.js +5827 -132
  39. package/dist/react-native.js.map +1 -1
  40. package/dist/react-native.mjs +313 -43
  41. package/dist/react-native.mjs.map +1 -1
  42. package/dist/renderPopup-2Y4QMWR7.mjs +3847 -0
  43. package/dist/renderPopup-2Y4QMWR7.mjs.map +1 -0
  44. package/dist/renderPopup-YDJUON42.mjs +3847 -0
  45. package/dist/renderPopup-YDJUON42.mjs.map +1 -0
  46. package/dist/{renderPopup-L2Q3KJAZ.mjs → renderPopup-ZHTRMFO2.mjs} +142 -9
  47. package/dist/renderPopup-ZHTRMFO2.mjs.map +1 -0
  48. package/ios/DeepdotsBackgroundTask.m +71 -0
  49. package/package.json +14 -5
  50. package/react-native.config.js +9 -0
  51. package/dist/chunk-AFRHPS3K.mjs.map +0 -1
  52. package/dist/chunk-VHTN5UXD.mjs.map +0 -1
  53. package/dist/renderPopup-L2Q3KJAZ.mjs.map +0 -1
  54. package/dist/renderPopup-PQWJSBOY.mjs +0 -3622
  55. package/dist/renderPopup-PQWJSBOY.mjs.map +0 -1
@@ -0,0 +1,3914 @@
1
+ import {
2
+ BUNDLED_SURVEY_SDK_VERSION,
3
+ BUSY_JS,
4
+ InMemoryStorage,
5
+ LABELS,
6
+ PRIMARY_COLOR_JS,
7
+ RESOLVE_LOCALE_JS,
8
+ REVEAL_TIMEOUT_MS,
9
+ RTL_LOCALES,
10
+ SDK_IDENTIFIER,
11
+ STORAGE_KEYS,
12
+ SUBMIT_ERROR_JS,
13
+ SUPPORTED_LANGUAGES,
14
+ TrackingManager,
15
+ buildFontFaceCss,
16
+ buildFontFamilyValue,
17
+ buildSurveyIdentity,
18
+ chooseSurveySdkVersion,
19
+ createDefaultStorage,
20
+ describeSurveySdkChoice,
21
+ directionFor,
22
+ getLabels,
23
+ isRtlLanguage,
24
+ resolveActionLabels,
25
+ resolveLocale,
26
+ sdkLog,
27
+ sdkWarn,
28
+ setLogger,
29
+ style_default,
30
+ surveySdkCssUrls,
31
+ surveySdkUrls
32
+ } from "./chunk-7ZQOAKXR.mjs";
33
+ import "./chunk-3QS3WKRC.mjs";
34
+
35
+ // src/index.native.ts
36
+ import { AppState, NativeModules, Platform } from "react-native";
37
+
38
+ // src/platform/react-native-platform.ts
39
+ var registered = null;
40
+ function registerReactNativePlatform(platform) {
41
+ registered = platform;
42
+ }
43
+ function getReactNativePlatform() {
44
+ return registered;
45
+ }
46
+ function nativeModuleTask(mod) {
47
+ let seq = 0;
48
+ return (name) => {
49
+ const token = `dd-${Date.now().toString(36)}-${(seq++).toString(36)}`;
50
+ mod.begin(token, name);
51
+ let ended = false;
52
+ return () => {
53
+ if (ended) return;
54
+ ended = true;
55
+ mod.end(token);
56
+ };
57
+ };
58
+ }
59
+ function resolveBackgroundTask(explicit, platform) {
60
+ if (explicit) return explicit;
61
+ const mod = platform?.backgroundTaskModule;
62
+ if (platform?.os === "ios" && mod && typeof mod.begin === "function" && typeof mod.end === "function") {
63
+ return nativeModuleTask(mod);
64
+ }
65
+ return void 0;
66
+ }
67
+
68
+ // src/types/index.ts
69
+ var POPUP_TRIGGER_CONDITION_STATUSES = [
70
+ "SHOWED",
71
+ "PARTIAL",
72
+ "COMPLETED"
73
+ ];
74
+
75
+ // src/triggers/index.ts
76
+ function toNumericValue(value, fallback) {
77
+ const n = Number(value);
78
+ return Number.isFinite(n) ? n : fallback;
79
+ }
80
+ function setupTrigger(popups, trigger) {
81
+ switch (trigger.type) {
82
+ case "time":
83
+ setupTimeTrigger(popups, trigger);
84
+ break;
85
+ case "scroll":
86
+ setupScrollTrigger(popups, trigger);
87
+ break;
88
+ case "exit":
89
+ setupExitTrigger(popups, trigger);
90
+ break;
91
+ case "event":
92
+ setupEventTrigger(popups, trigger);
93
+ break;
94
+ case "click":
95
+ setupClickTrigger(popups, trigger);
96
+ break;
97
+ }
98
+ }
99
+ function setupTimeTrigger(popups, trigger) {
100
+ const delay = toNumericValue(trigger.value, 5e3);
101
+ setTimeout(() => {
102
+ popups.triggerSurvey(trigger.surveyId, trigger.popupId, { delaySeconds: trigger.delaySeconds });
103
+ }, delay);
104
+ popups.debug(`Time trigger set for ${delay}ms`);
105
+ }
106
+ function setupScrollTrigger(popups, trigger) {
107
+ const threshold = toNumericValue(trigger.value, 50);
108
+ const handler = () => {
109
+ const scrollPercentage = window.scrollY / (document.documentElement.scrollHeight - window.innerHeight) * 100;
110
+ if (scrollPercentage >= threshold) {
111
+ popups.triggerSurvey(trigger.surveyId, trigger.popupId, { delaySeconds: trigger.delaySeconds });
112
+ window.removeEventListener("scroll", handler);
113
+ }
114
+ };
115
+ window.addEventListener("scroll", handler);
116
+ popups.debug(`Scroll trigger set for ${threshold}%`);
117
+ }
118
+ function setupExitTrigger(popups, trigger) {
119
+ if (typeof window === "undefined") return;
120
+ const delaySeconds = typeof trigger.delaySeconds === "number" && trigger.delaySeconds > 0 ? trigger.delaySeconds : parseExitDelaySeconds(trigger.value);
121
+ const historyRef = window.history;
122
+ const originalPushState = historyRef.pushState.bind(historyRef);
123
+ const originalReplaceState = historyRef.replaceState.bind(historyRef);
124
+ let lastUrl = normalizeUrl(window.location.href);
125
+ let lastQueuedKey = "";
126
+ let lastQueuedAt = 0;
127
+ const queueLeave = (fromRaw, toRaw) => {
128
+ const from = normalizeUrl(fromRaw);
129
+ const to = normalizeUrl(toRaw);
130
+ if (!from || !to || from === to) return;
131
+ const key = `${from}=>${to}`;
132
+ const now = Date.now();
133
+ if (key === lastQueuedKey && now - lastQueuedAt < 150) return;
134
+ lastQueuedKey = key;
135
+ lastQueuedAt = now;
136
+ popups.queueExitPopup(trigger.surveyId, delaySeconds, from, trigger.popupId);
137
+ };
138
+ const handleNavigation = (to) => {
139
+ const from = lastUrl;
140
+ queueLeave(from, to);
141
+ lastUrl = normalizeUrl(to);
142
+ };
143
+ const handleDocumentClick = (event) => {
144
+ if (event.defaultPrevented) return;
145
+ if (event.button !== 0) return;
146
+ if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return;
147
+ const anchor = event.target?.closest?.("a");
148
+ if (!(anchor instanceof HTMLAnchorElement)) return;
149
+ const href = anchor.getAttribute("href");
150
+ if (!href || href.startsWith("javascript:") || href.startsWith("mailto:") || href.startsWith("tel:")) {
151
+ return;
152
+ }
153
+ const target = anchor.getAttribute("target");
154
+ if (target && target !== "_self") return;
155
+ let destination;
156
+ try {
157
+ destination = new URL(href, window.location.href);
158
+ } catch {
159
+ return;
160
+ }
161
+ if (destination.origin !== window.location.origin) return;
162
+ queueLeave(window.location.href, destination.href);
163
+ };
164
+ const handleHashChange = (event) => {
165
+ const to = event.newURL || window.location.href;
166
+ const from = event.oldURL || lastUrl;
167
+ queueLeave(from, to);
168
+ lastUrl = normalizeUrl(to);
169
+ };
170
+ const handlePopState = () => {
171
+ handleNavigation(window.location.href);
172
+ };
173
+ historyRef.pushState = function(data, unused, url) {
174
+ const from = window.location.href;
175
+ const result = originalPushState(data, unused, url);
176
+ queueLeave(from, window.location.href);
177
+ lastUrl = normalizeUrl(window.location.href);
178
+ return result;
179
+ };
180
+ historyRef.replaceState = function(data, unused, url) {
181
+ const from = window.location.href;
182
+ const result = originalReplaceState(data, unused, url);
183
+ queueLeave(from, window.location.href);
184
+ lastUrl = normalizeUrl(window.location.href);
185
+ return result;
186
+ };
187
+ document.addEventListener("click", handleDocumentClick, true);
188
+ window.addEventListener("hashchange", handleHashChange);
189
+ window.addEventListener("popstate", handlePopState);
190
+ popups.debug("Exit trigger set (deferred to next route)", {
191
+ surveyId: trigger.surveyId,
192
+ delaySeconds
193
+ });
194
+ }
195
+ function setupEventTrigger(popups, trigger) {
196
+ popups.debug("Event trigger registered", {
197
+ popupId: trigger.popupId,
198
+ surveyId: trigger.surveyId,
199
+ eventName: String(trigger.value || "")
200
+ });
201
+ }
202
+ function parseExitDelaySeconds(value) {
203
+ if (typeof value === "number" && Number.isFinite(value)) {
204
+ return Math.max(0, value);
205
+ }
206
+ if (typeof value === "string" && value.trim()) {
207
+ const parsed = Number(value);
208
+ if (Number.isFinite(parsed)) return Math.max(0, parsed);
209
+ }
210
+ return 0;
211
+ }
212
+ function normalizeUrl(value) {
213
+ if (!value) return "";
214
+ const withoutIndex = value.replace(/\/index\.html(?=($|[?#]))/i, "");
215
+ return withoutIndex.length > 1 && withoutIndex.endsWith("/") ? withoutIndex.slice(0, -1) : withoutIndex;
216
+ }
217
+ function setupClickTrigger(popups, trigger) {
218
+ const targetId = typeof trigger.value === "string" ? trigger.value : "";
219
+ if (!targetId) {
220
+ popups.debug("Click trigger missing element id", trigger);
221
+ return;
222
+ }
223
+ const attach = () => {
224
+ const el = document.getElementById(targetId);
225
+ if (!el) {
226
+ popups.debug("Click trigger target not found", targetId);
227
+ return false;
228
+ }
229
+ const handler = (e) => {
230
+ if (e.defaultPrevented) return;
231
+ popups.triggerSurvey(trigger.surveyId, trigger.popupId, { delaySeconds: trigger.delaySeconds });
232
+ el.removeEventListener("click", handler);
233
+ };
234
+ el.addEventListener("click", handler);
235
+ popups.debug(`Click trigger set for #${targetId}`);
236
+ return true;
237
+ };
238
+ if (typeof document === "undefined") return;
239
+ if (attach()) return;
240
+ window.addEventListener("DOMContentLoaded", () => attach(), { once: true });
241
+ }
242
+
243
+ // src/config/env.ts
244
+ var ENVIRONMENT_MAP = {
245
+ development: {
246
+ apiBaseUrl: "https://api-dev.deepdots.com"
247
+ },
248
+ production: {
249
+ apiBaseUrl: "https://api.deepdots.com"
250
+ }
251
+ };
252
+ function resolveEnvironment(nodeEnv) {
253
+ return ENVIRONMENT_MAP[nodeEnv || "production"];
254
+ }
255
+
256
+ // src/ui/surveyHtml.ts
257
+ var REVEAL_JS = `
258
+ function ddCreateReveal(popup, onReveal, timeoutMs){
259
+ var revealed=false, timer=null;
260
+ function reveal(){
261
+ if(revealed){ return; }
262
+ revealed=true;
263
+ if(timer){ clearTimeout(timer); timer=null; }
264
+ onReveal();
265
+ }
266
+ function revealWhenPainted(){
267
+ if(revealed){ return; }
268
+ var imgs=popup.querySelectorAll('img'), pending=[];
269
+ for(var i=0;i<imgs.length;i++){ if(!imgs[i].complete){ pending.push(imgs[i]); } }
270
+ if(!pending.length){ reveal(); return; }
271
+ var left=pending.length;
272
+ function onSettled(){ left--; if(left<=0){ reveal(); } }
273
+ for(var j=0;j<pending.length;j++){
274
+ pending[j].addEventListener('load', onSettled);
275
+ pending[j].addEventListener('error', onSettled);
276
+ }
277
+ }
278
+ timer=setTimeout(reveal, timeoutMs);
279
+ return { reveal: reveal, whenPainted: revealWhenPainted };
280
+ }`;
281
+ var POSITION_MAP = {
282
+ center: { justifyContent: "center", alignItems: "center", padding: "0", background: "rgba(0,0,0,0.5)" },
283
+ bottom: { justifyContent: "center", alignItems: "flex-end", padding: "16px", background: "transparent" },
284
+ "bottom-right": { justifyContent: "flex-end", alignItems: "flex-end", padding: "16px", background: "transparent" },
285
+ "bottom-left": { justifyContent: "flex-start", alignItems: "flex-end", padding: "16px", background: "transparent" },
286
+ top: { justifyContent: "center", alignItems: "flex-start", padding: "16px", background: "transparent" },
287
+ "top-right": { justifyContent: "flex-end", alignItems: "flex-start", padding: "16px", background: "transparent" },
288
+ "top-left": { justifyContent: "flex-start", alignItems: "flex-start", padding: "16px", background: "transparent" }
289
+ };
290
+ function jsonForScript(value) {
291
+ return JSON.stringify(value ?? null).replace(/</g, "\\u003C").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
292
+ }
293
+ function trimmedOrNull(value) {
294
+ const trimmed = typeof value === "string" ? value.trim() : "";
295
+ return trimmed ? value : null;
296
+ }
297
+ function buildSurveyHtml(opts) {
298
+ const env = opts.env === "development" ? "dev" : "prod";
299
+ const version = opts.version ?? BUNDLED_SURVEY_SDK_VERSION;
300
+ const assigned = version !== BUNDLED_SURVEY_SDK_VERSION ? { version, css: surveySdkCssUrls(version), js: surveySdkUrls(version) } : null;
301
+ const bundledJs = surveySdkUrls(BUNDLED_SURVEY_SDK_VERSION);
302
+ const sid = jsonForScript(opts.surveyId);
303
+ const pid = jsonForScript(opts.productId);
304
+ const profileJson = jsonForScript(opts.profile ?? []);
305
+ const metaJson = jsonForScript(opts.metadata ?? []);
306
+ const fontFaceCss = opts.font ? buildFontFaceCss(opts.font.family, opts.font.url) : "";
307
+ const fontFamilyValue = opts.font ? buildFontFamilyValue(opts.font.family) : "-apple-system,system-ui,sans-serif";
308
+ const popupClass = opts.font?.family ? "deepdots-popup deepdots-has-font" : "deepdots-popup";
309
+ const isDark = opts.theme === "dark";
310
+ const popupBg = isDark ? "#1e1e1e" : "#fff";
311
+ const colorScheme = isDark ? "dark" : "light";
312
+ const textPrimary = isDark ? "#f0f0f0" : "#111";
313
+ const textMuted = isDark ? "#9ca3af" : "#6b7280";
314
+ const trackBg = isDark ? "#3f3f46" : "#e5e7eb";
315
+ const pos = POSITION_MAP[opts.position ?? "center"] ?? POSITION_MAP.center;
316
+ const chrome = opts.chrome !== false;
317
+ const bodyBg = chrome ? pos.background : "transparent";
318
+ const bodyPadding = chrome ? pos.padding : "0";
319
+ const bodyDisplay = chrome ? "flex" : "block";
320
+ const cardBg = chrome ? popupBg : "transparent";
321
+ const cardShadow = chrome ? "0 4px 6px rgba(0,0,0,0.1)" : "none";
322
+ const cardRadius = chrome ? "8px" : "0";
323
+ const cardMaxWidth = chrome ? "600px" : "none";
324
+ const cardWidth = chrome ? "90%" : "100%";
325
+ const cardMinHeight = chrome ? "200px" : "0";
326
+ const cardHeight = chrome ? "auto" : "100%";
327
+ const cardMaxHeight = chrome ? "90vh" : "100%";
328
+ const mobileCard = chrome ? `.deepdots-popup{width:calc(100% - 24px);max-width:calc(100% - 24px);border-radius:12px;padding:calc(16px + env(safe-area-inset-top)) 16px calc(16px + env(safe-area-inset-bottom)) 16px}` : `.deepdots-popup{width:100%;max-width:100%;border-radius:0;padding:16px}`;
329
+ const titleJson = jsonForScript(opts.title ?? "");
330
+ const customCss = (opts.surveyCss ?? "").replace(/<\/\s*style/gi, "<\\/style");
331
+ const progressPref = opts.showProgressBar === void 0 ? "null" : String(opts.showProgressBar);
332
+ const initLabels = getLabels(opts.language);
333
+ const initActionLabels = resolveActionLabels(opts.actions, opts.language);
334
+ const backLabel = jsonForScript(initActionLabels.back);
335
+ const startLabel = jsonForScript(initActionLabels.start);
336
+ const completeLabel = jsonForScript(initActionLabels.complete);
337
+ const submitLabel = jsonForScript(initActionLabels.accept);
338
+ const cancelLabel = jsonForScript(initActionLabels.decline);
339
+ const labelsTableJson = jsonForScript(LABELS);
340
+ const actionOverridesJson = jsonForScript({
341
+ accept: trimmedOrNull(opts.actions?.accept?.label),
342
+ start: trimmedOrNull(opts.actions?.start?.label),
343
+ complete: trimmedOrNull(opts.actions?.complete?.label),
344
+ back: trimmedOrNull(opts.actions?.back?.label),
345
+ decline: trimmedOrNull(opts.actions?.decline?.label)
346
+ });
347
+ const initLangJson = jsonForScript(opts.language ?? "");
348
+ const initDirection = directionFor(opts.language);
349
+ const rtlLocalesJson = jsonForScript(RTL_LOCALES);
350
+ return `<!DOCTYPE html><html><head>
351
+ <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
352
+ <meta name="color-scheme" content="${colorScheme}"/>
353
+ <style id="dd-survey-css">
354
+ ${style_default}
355
+ </style>
356
+ <style>
357
+ ${fontFaceCss}
358
+ html,body{margin:0;padding:0;height:100%;font-family:${fontFamilyValue}}
359
+ /* Apertura diferida: ni la tarjeta ni el velo se pintan hasta que el survey est\xE1 listo
360
+ (\`dd-ready\`). Si el fondo entrara antes, en RN se ver\xEDa el velo oscuro varios cientos de ms
361
+ antes que el contenido, que es la misma mala sensaci\xF3n que el spinner. */
362
+ body{display:${bodyDisplay};justify-content:${pos.justifyContent};align-items:${pos.alignItems};background:transparent;padding:${bodyPadding};box-sizing:border-box}
363
+ body.dd-ready{background:${bodyBg}}
364
+ #dd-popup{visibility:hidden}
365
+ body.dd-ready #dd-popup{visibility:visible}
366
+ .deepdots-popup{position:relative;display:flex;flex-direction:column;justify-content:flex-start;background:${cardBg};color-scheme:${colorScheme};border-radius:${cardRadius};padding:24px;box-shadow:${cardShadow};max-width:${cardMaxWidth};width:${cardWidth};min-height:${cardMinHeight};height:${cardHeight};max-height:${cardMaxHeight};box-sizing:border-box}
367
+ .deepdots-popup-header{display:flex;justify-content:space-between;align-items:center;gap:12px;width:100%;flex:0 0 auto}
368
+ /* Neutraliza la regla \`.deepdots-popup h2\` del CSS del survey (uppercase, centrado y
369
+ margin-bottom 40px), pensada para los enunciados y no para el t\xEDtulo de la cabecera. */
370
+ #dd-title{margin:0;font-family:var(--deepdots-font,'Montserrat',inherit);font-size:17px;font-weight:600;line-height:1.3;color:${textPrimary};text-transform:none;text-align:start;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
371
+ #dd-close{background:transparent;border:none;width:32px;height:32px;display:flex;align-items:center;justify-content:center;border-radius:8px;cursor:pointer;color:${textPrimary};padding:4px;flex:0 0 auto;margin-inline-start:auto}
372
+ /* Progreso alineado con la cabecera: sin padding horizontal propio, lo marca la tarjeta.
373
+ El vertical es el mismo arriba y abajo, y del mismo valor que el padding de la tarjeta. */
374
+ .deepdots-progress{display:none;flex-direction:column;gap:8px;width:100%;flex:0 0 auto;padding:16px 0;box-sizing:border-box}
375
+ .deepdots-progress-head{display:flex;flex-direction:row;justify-content:space-between;align-items:center;width:100%;gap:8px}
376
+ #dd-progress-label{font-size:13px;line-height:1.2}
377
+ /* "Question 1" en negrita y "of 3" en regular gris, como el mockup. */
378
+ #dd-progress-current{font-weight:700;color:${textPrimary}}
379
+ #dd-progress-total{font-weight:400;color:${textMuted}}
380
+ #dd-progress-followup{display:none;font-size:12px;font-weight:600;color:#fff;background:rgba(59,130,246,0.44);border-radius:999px;padding:2px 10px}
381
+ .deepdots-progress-track{width:100%;height:4px;border-radius:999px;background:${trackBg};overflow:hidden}
382
+ #dd-progress-bar{height:100%;width:0%;background:#22C55E;border-radius:999px;transition:width 450ms ease}
383
+ /* El popup es una columna: solo el bloque de preguntas hace scroll, para que el footer
384
+ con las acciones quede siempre visible en el borde inferior (antes viv\xEDa dentro del
385
+ \xE1rea scrollable y hab\xEDa que bajar hasta el final para ver "Send"). */
386
+ /* Sin sangrado extra: el contenido se alinea con el t\xEDtulo y con la barra de progreso (antes
387
+ sumaba 20px a los lados sobre el padding de la tarjeta y quedaba m\xE1s adentro que la cabecera). */
388
+ /* Sin barra de progreso, este padding-top es el que separa la cabecera de la pregunta. Con
389
+ barra, el JS lo pone a 0 y el hueco lo aporta el padding inferior del bloque de progreso,
390
+ de modo que el espacio por arriba y por abajo de la barra es id\xE9ntico. */
391
+ .deepdots-popup-container-content{display:flex;flex-direction:column;flex:1 1 auto;min-height:0;padding:16px 0 0 0;overflow:hidden;box-sizing:border-box}
392
+ /* El enunciado trae margin-top:20px del CSS de surveys, que sumaba al hueco de la barra y
393
+ descompensaba la simetr\xEDa. Solo se anula en el primero: entre preguntas sigue separando. */
394
+ .deepdots-popup .magicfeedback-questions .magicfeedback-div:first-child .magicfeedback-label{margin-top:0}
395
+ .deepdots-popup-main{display:flex;flex-direction:column;width:100%;flex:1 1 auto;min-height:0;overflow-y:auto;overflow-x:hidden;position:relative}
396
+ #dd-form-wrapper{width:100%;flex:1 1 auto}
397
+ #mf{width:100%;box-sizing:border-box;visibility:hidden}
398
+ .deepdots-popup-main *{max-width:100%;box-sizing:border-box}
399
+ /* El margen lateral lo pone la tarjeta: el CSS del survey lo a\xF1ade otra vez en el contenedor, en
400
+ el formulario y en el bloque de cada pregunta, y eso deja el enunciado y las opciones m\xE1s
401
+ adentro que el logo, el t\xEDtulo y la barra de progreso. Solo el lateral; el vertical separa las
402
+ preguntas. Mismas reglas que en el popup DOM (renderPopup.ts). */
403
+ .deepdots-popup .magicfeedback-container,
404
+ .deepdots-popup .magicfeedback-form,
405
+ .deepdots-popup .magicfeedback-div{padding-left:0;padding-right:0}
406
+ #dd-logo{max-height:40px;max-width:100%;object-fit:contain;display:block;margin:12px 0 0 0}
407
+ .deepdots-error-hint{display:none;margin:12px 0 0 0;padding:10px 12px;border-radius:6px;background:#FEF3C7;color:#92400E;border:1px solid #FCD34D;font-size:13px}
408
+ /* Pantalla final: el HTML del editor de la plataforma (imagen + texto), centrado. */
409
+ .deepdots-load-error{display:none;width:100%;text-align:center;padding:24px 0;font-size:15px;color:${textPrimary}}
410
+ .deepdots-success{display:none;width:100%;text-align:center;padding:24px 0;color:${textPrimary}}
411
+ .deepdots-success img{max-width:100%;height:auto;margin:0 auto 16px auto;display:block}
412
+ .deepdots-success p{margin:0;font-size:16px;font-weight:600;line-height:1.4}
413
+ .deepdots-popup-footer{display:flex;flex-direction:row-reverse;justify-content:space-between;align-items:center;gap:4px;margin-top:auto;width:100%;padding-top:12px}
414
+ .dd-nav-btn{display:none;border:none;min-height:44px;padding:12px 24px;border-radius:999px;cursor:pointer;font-size:15px;font-weight:600;align-items:center;justify-content:center;text-align:center}
415
+ /* Secundario como bot\xF3n de texto: sin borde ni fondo, para que el primario sea la \xFAnica CTA. */
416
+ #dd-back{background:transparent;color:${textMuted};border:none}
417
+ #dd-start,#dd-complete,#dd-submit,#dd-cancel{background:#1E293B;color:#fff;border:none}
418
+ #dd-submit:disabled,#dd-start:disabled,#dd-back:disabled,#dd-complete:disabled{opacity:0.6;cursor:not-allowed}
419
+ .mf-spinner{display:none;position:absolute;top:50%;left:50%;transform:translate(-50%,-50%)}
420
+ .mf-spinner-circle{width:28px;height:28px;border:3px solid #e0e6ed;border-top-color:#1E293B;border-radius:50%;animation:ddspin 0.9s linear infinite}
421
+ @keyframes ddspin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}
422
+ @media (max-width:640px){
423
+ ${mobileCard}
424
+ /* Apilados: la acci\xF3n principal (Send/Start/Complete) arriba y Back debajo. El orden del
425
+ DOM ya es ese, as\xED que \`column\` (no \`column-reverse\`) es lo que lo respeta. */
426
+ .deepdots-popup-footer{flex-direction:column;gap:4px}
427
+ .dd-nav-btn{width:100%}
428
+ .magicfeedback-checkbox-container,.magicfeedback-radio-container{margin:4px 0;padding:4px 8px}
429
+ .magicfeedback-checkbox label,.magicfeedback-radio-container label{font-size:15px}
430
+ .deepdots-popup input[type="radio"]{margin:6px 0 6px 8px}
431
+ .deepdots-popup input[type="checkbox"]{width:16px;height:16px}
432
+ }
433
+ ${customCss}
434
+ </style>
435
+ </head><body>
436
+ <div class="${popupClass}" id="dd-popup" dir="${initDirection}">
437
+ <div class="deepdots-popup-header">
438
+ <h2 id="dd-title" class="deepdots-popup-title" hidden></h2>
439
+ <button type="button" id="dd-close" aria-label="${initLabels.closeAria}">
440
+ <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
441
+ <path d="M5 5L19 19M5 19L19 5" stroke="currentColor" stroke-width="1.5" stroke-linecap="butt"/>
442
+ </svg>
443
+ </button>
444
+ </div>
445
+ <div class="deepdots-progress" id="dd-progress">
446
+ <div class="deepdots-progress-head">
447
+ <span id="dd-progress-label"><span id="dd-progress-current"></span><span id="dd-progress-total"></span></span>
448
+ <span id="dd-progress-followup">${initLabels.followUp}</span>
449
+ </div>
450
+ <div class="deepdots-progress-track"><div id="dd-progress-bar"></div></div>
451
+ </div>
452
+ <div class="deepdots-popup-container-content" id="dd-content">
453
+ <div class="deepdots-popup-main" id="dd-main">
454
+ <div id="dd-form-wrapper">
455
+ <div class="mf-spinner" id="dd-spinner" role="status" aria-label="${initLabels.loadingAria}"><div class="mf-spinner-circle"></div></div>
456
+ <div id="mf"></div>
457
+ </div>
458
+ <div class="deepdots-load-error" id="dd-load-error" role="alert"></div>
459
+ <div class="deepdots-error-hint" id="dd-error" role="alert" aria-live="polite"></div>
460
+ </div>
461
+ <div class="deepdots-popup-footer" id="dd-footer">
462
+ <button type="button" class="dd-nav-btn" id="dd-submit"></button>
463
+ <button type="button" class="dd-nav-btn" id="dd-back"></button>
464
+ <button type="button" class="dd-nav-btn" id="dd-complete"></button>
465
+ <button type="button" class="dd-nav-btn" id="dd-start"></button>
466
+ <button type="button" class="dd-nav-btn" id="dd-cancel"></button>
467
+ </div>
468
+ </div>
469
+ </div>
470
+ <script>
471
+ (function(){
472
+ function emit(s){ try{ if(window.ReactNativeWebView){ window.ReactNativeWebView.postMessage(s); } }catch(e){} }
473
+ function emitJSON(n,p){ try{ emit(JSON.stringify({name:n,payload:p||{}})); }catch(e){} }
474
+ var ddLastReportedError=null;
475
+ window.DeepdotsClose = function(){ emitJSON('popup_close'); };
476
+ var chromeOn=${chrome ? "true" : "false"};
477
+
478
+ var popup=document.getElementById('dd-popup');
479
+ var main=document.getElementById('dd-main');
480
+ var content=document.getElementById('dd-content');
481
+ var footer=document.getElementById('dd-footer');
482
+ var spinner=document.getElementById('dd-spinner');
483
+ var formHost=document.getElementById('mf');
484
+ var formWrapper=document.getElementById('dd-form-wrapper');
485
+ var errorHint=document.getElementById('dd-error');
486
+ var backBtn=document.getElementById('dd-back');
487
+ var startBtn=document.getElementById('dd-start');
488
+ var completeBtn=document.getElementById('dd-complete');
489
+ var submitBtn=document.getElementById('dd-submit');
490
+ var cancelBtn=document.getElementById('dd-cancel');
491
+ var loadErrorEl=document.getElementById('dd-load-error');
492
+ var titleEl=document.getElementById('dd-title');
493
+ var progressEl=document.getElementById('dd-progress');
494
+ var progressLabel=document.getElementById('dd-progress-label');
495
+ var progressCurrent=document.getElementById('dd-progress-current');
496
+ var progressTotal=document.getElementById('dd-progress-total');
497
+ var progressFollowUp=document.getElementById('dd-progress-followup');
498
+ var progressBar=document.getElementById('dd-progress-bar');
499
+ var closeEl=document.getElementById('dd-close');
500
+
501
+ // --- i18n del chrome -------------------------------------------------------------------
502
+ // La tabla completa viaja embebida porque el idioma del survey (\`formData.lang[0]\`) solo se
503
+ // conoce ya dentro del WebView. \`ddResolveLocale\` es el espejo del \`resolveLocale\` de TS
504
+ // (paridad cubierta por test).
505
+ var DD_LABELS=${labelsTableJson};
506
+ var DD_ACTION_OVERRIDES=${actionOverridesJson};
507
+ ${RESOLVE_LOCALE_JS}
508
+ var DD_LABELS_ACTIVE=DD_LABELS[ddResolveLocale(${initLangJson})];
509
+ var DD_RTL=${rtlLocalesJson};
510
+ function ddIsRtl(lang){ return DD_RTL.indexOf(ddResolveLocale(lang))!==-1; }
511
+ function ddApplyLabels(lang){
512
+ var next=DD_LABELS[ddResolveLocale(lang)];
513
+ if(!next) return;
514
+ DD_LABELS_ACTIVE=next;
515
+ // El survey ya se ha volteado a s\xED mismo: el chrome tiene que acompa\xF1arlo.
516
+ popup.setAttribute('dir', ddIsRtl(lang) ? 'rtl' : 'ltr');
517
+ backBtn.textContent=DD_ACTION_OVERRIDES.back||next.back;
518
+ startBtn.textContent=DD_ACTION_OVERRIDES.start||next.start;
519
+ completeBtn.textContent=DD_ACTION_OVERRIDES.complete||next.complete;
520
+ submitBtn.textContent=DD_ACTION_OVERRIDES.accept||next.accept;
521
+ cancelBtn.textContent=DD_ACTION_OVERRIDES.decline||next.decline;
522
+ loadErrorEl.textContent=next.errorLoad;
523
+ if(closeEl){ closeEl.setAttribute('aria-label',next.closeAria); }
524
+ if(spinner){ spinner.setAttribute('aria-label',next.loadingAria); }
525
+ progressFollowUp.textContent=next.followUp;
526
+ }
527
+
528
+ function setTitle(t){
529
+ if(!t) return;
530
+ titleEl.textContent=t;
531
+ titleEl.hidden=false;
532
+ }
533
+ setTitle(${titleJson});
534
+
535
+ // Estado de la barra de progreso. \`progressPref\` null = manda la plataforma (style).
536
+ var progressPref=${progressPref};
537
+ var progressEnabled=progressPref===true;
538
+ var progressShowUnit=true;
539
+ var progressUnit='fraction';
540
+ var onStartPage=false;
541
+
542
+ function updateProgress(p){
543
+ var total=p&&typeof p.total==='number'?p.total:0;
544
+ var progress=p&&typeof p.progress==='number'?p.progress:0;
545
+ // Solo tiene sentido con m\xE1s de una p\xE1gina, fuera de la pantalla de inicio y sin completar.
546
+ if(!progressEnabled||onStartPage||p&&p.completed||total<=1){
547
+ progressEl.style.display='none';
548
+ // Sin barra, el hueco cabecera\u2192pregunta lo pone el contenido.
549
+ content.style.paddingTop='16px';
550
+ return;
551
+ }
552
+ progressEl.style.display='flex';
553
+ // Con barra, el hueco inferior ya lo pone el bloque de progreso: no duplicarlo.
554
+ content.style.paddingTop='0';
555
+ // Espejo de LineProgressQuestion (MagicSurvey): la barra usa el valor real (las follow-up
556
+ // suman +0.5 y avanzan media casilla) y la etiqueta redondea hacia abajo, porque una
557
+ // follow-up es un paso DENTRO de la misma pregunta, no la siguiente.
558
+ var current=Math.min(total,Math.max(1,progress+1));
559
+ var pct=Math.min(100,Math.max(0,(current/total)*100));
560
+ progressBar.style.width=pct+'%';
561
+ var label=Math.min(total,Math.max(1,Math.floor(progress)+1));
562
+ progressLabel.style.display=progressShowUnit?'block':'none';
563
+ if(progressUnit==='percentage'){
564
+ progressCurrent.textContent=Math.round(pct)+'%';
565
+ progressTotal.textContent='';
566
+ } else {
567
+ progressCurrent.textContent=DD_LABELS_ACTIVE.question+' '+label;
568
+ progressTotal.textContent=' '+DD_LABELS_ACTIVE.of+' '+total;
569
+ }
570
+ progressFollowUp.style.display=p&&p.followup?'inline-block':'none';
571
+ }
572
+
573
+ backBtn.textContent=${backLabel};
574
+ startBtn.textContent=${startLabel};
575
+ completeBtn.textContent=${completeLabel};
576
+ submitBtn.textContent=${submitLabel};
577
+ cancelBtn.textContent=${cancelLabel};
578
+
579
+ closeEl.onclick=function(){ emitJSON('popup_close'); };
580
+ backBtn.onclick=function(){ if(window.DeepdotsForm && window.DeepdotsForm.back){ window.DeepdotsForm.back(); } };
581
+ startBtn.onclick=function(){
582
+ if(window.DeepdotsForm && window.DeepdotsForm.startForm){
583
+ window.DeepdotsForm.startForm();
584
+ onStartPage=false;
585
+ updateProgress({ progress:window.DeepdotsForm.progress, total:window.DeepdotsForm.total, completed:false, followup:false });
586
+ }
587
+ };
588
+ completeBtn.onclick=function(){ emitJSON('popup_close'); };
589
+ // \xDAnica acci\xF3n del survey que no carga: cierra igual que la X.
590
+ cancelBtn.onclick=function(){ emitJSON('popup_close'); };
591
+ var surveyCompletedEmitted=false;
592
+ submitBtn.onclick=function(){
593
+ if(surveyCompletedEmitted) return;
594
+ if(window.DeepdotsForm && window.DeepdotsForm.send){ window.DeepdotsForm.send(); }
595
+ };
596
+
597
+ // Mensaje final configurado en la plataforma (\`style.successMessage\`). Se guarda al cargar
598
+ // y se pinta al completar. Va por innerHTML porque es HTML del editor de la plataforma
599
+ // (imagen + texto), igual que ya hace \`renderStartMessage\` con el mensaje de inicio.
600
+ var successMessageHtml='';
601
+ function showSuccessScreen(){
602
+ progressEl.style.display='none';
603
+ var wrapper=document.getElementById('dd-form-wrapper');
604
+ if(wrapper){ wrapper.style.display='none'; }
605
+ var done=document.getElementById('dd-success');
606
+ if(!done){
607
+ done=document.createElement('div');
608
+ done.id='dd-success';
609
+ done.className='deepdots-success';
610
+ main.insertBefore(done, errorHint);
611
+ }
612
+ done.innerHTML=successMessageHtml || '<p>Thank you for your feedback!</p>';
613
+ done.style.display='block';
614
+ }
615
+
616
+ // Profundidad de navegaci\xF3n DENTRO del survey: +1 por p\xE1gina avanzada, -1 al volver.
617
+ // Sustituye a la condici\xF3n \`total>1 && progress>0 && progress<total\`, que escond\xEDa el
618
+ // Back siempre que la siguiente pantalla era una follow-up din\xE1mica: las follow-up no
619
+ // entran en el grafo (suman +0.5 al progress y no tocan el total), as\xED que un survey de
620
+ // una pregunta con follow-up tiene total=1 y nunca cumpl\xEDa \`total>1\`.
621
+ var pageDepth=0;
622
+
623
+ function updateNavButtons(){
624
+ updateButtons(pageDepth>0?'in_progress_next':'in_progress_first');
625
+ }
626
+
627
+ function updateButtons(state){
628
+ backBtn.style.display='none';
629
+ startBtn.style.display='none';
630
+ submitBtn.style.display='none';
631
+ completeBtn.style.display='none';
632
+ cancelBtn.style.display='none';
633
+ backBtn.style.width='';
634
+ startBtn.style.width='';
635
+ submitBtn.style.width='';
636
+ completeBtn.style.width='';
637
+ if(state==='start'){
638
+ startBtn.style.display='inline-flex';
639
+ startBtn.style.width='100%';
640
+ } else if(state==='in_progress_first'){
641
+ submitBtn.style.display='inline-flex';
642
+ } else if(state==='in_progress_next'){
643
+ backBtn.style.display='inline-flex';
644
+ submitBtn.style.display='inline-flex';
645
+ } else if(state==='completed'){
646
+ completeBtn.style.display='inline-flex';
647
+ completeBtn.style.width='100%';
648
+ } else if(state==='load_error'){
649
+ cancelBtn.style.display='inline-flex';
650
+ }
651
+ }
652
+
653
+ ${PRIMARY_COLOR_JS}
654
+ ${BUSY_JS}
655
+ ${SUBMIT_ERROR_JS}
656
+ ${REVEAL_JS}
657
+ // Foco en la primera pregunta si es de escribir. Al navegar lo pone @magicfeedback/native
658
+ // (autofocus:'navigation'); la apertura la decide el popup, que es quien sabe cu\xE1ndo se revela.
659
+ // Necesita el popup revelado y el survey cargado, que llegan en cualquier orden, y solo con
660
+ // rat\xF3n o trackpad: en t\xE1ctil sacar\xEDa el teclado sin que el usuario haya tocado nada.
661
+ var ddRevealed=false, ddSurveyLoaded=false, ddOpenFocusDone=false;
662
+ function ddAutofocusOnOpen(){
663
+ if(ddOpenFocusDone || !ddRevealed || !ddSurveyLoaded){ return; }
664
+ ddOpenFocusDone=true;
665
+ var fine=typeof window.matchMedia==='function' && window.matchMedia('(pointer: fine)').matches;
666
+ var f=window.DeepdotsForm;
667
+ if(fine && f && typeof f.focusFirstQuestion==='function'){ f.focusFirstQuestion(); }
668
+ }
669
+ // El popup se ense\xF1a cuando el survey est\xE1 pintado; \`ready\` deja al host abrir su propio
670
+ // Modal en ese momento en vez de montar un WebView en blanco.
671
+ var ddReveal=ddCreateReveal(popup, function(){
672
+ document.body.classList.add('dd-ready');
673
+ emitJSON('ready');
674
+ ddRevealed=true;
675
+ ddAutofocusOnOpen();
676
+ }, ${REVEAL_TIMEOUT_MS});
677
+
678
+ function setLoading(isLoading){
679
+ spinner.style.display=isLoading?'flex':'none';
680
+ // El spinner no tapa el survey (28px en posicion absoluta), asi que sin esto el usuario
681
+ // puede seguir cambiando de opcion mientras se envia la pagina, y ese cambio ya no viaja
682
+ // con ella. Se bloquea el wrapper, que es el elemento estable: el div de dentro lo
683
+ // sustituye @magicfeedback/native por su propio contenedor al generar el survey.
684
+ ddSetSurveyBusy(formWrapper, isLoading);
685
+ if(!isLoading){
686
+ formHost.style.visibility='visible';
687
+ // Fin de la carga, sea por survey cargado o por error. Entre p\xE1ginas es no-op: la
688
+ // revelaci\xF3n solo act\xFAa la primera vez.
689
+ ddReveal.whenPainted();
690
+ }
691
+ footer.style.display=isLoading?'none':'flex';
692
+ backBtn.disabled=isLoading; startBtn.disabled=isLoading; completeBtn.disabled=isLoading; submitBtn.disabled=isLoading;
693
+ if(isLoading){ updateButtons(null); }
694
+ }
695
+ setLoading(true);
696
+
697
+ // Survey que no ha cargado (406 de /info, sin red, bundle del CDN ca\xEDdo). Antes se emit\xEDa
698
+ // \`loaded\` y se pintaba un Send sobre un survey vac\xEDo. Espejo de KMP: aviso traducido, la X
699
+ // sigue, un \xFAnico Cancel, y se revela ya (manda \`ready\`): no hay nada m\xE1s que esperar.
700
+ // No es interacci\xF3n del usuario: el renderer no lo convierte en popup_clicked.
701
+ var ddLoadFailed=false;
702
+ function ddShowLoadError(name, reason){
703
+ if(ddLoadFailed){ return; }
704
+ ddLoadFailed=true;
705
+ var why=(reason && reason.message) ? reason.message : String(reason);
706
+ emitJSON(name, { message: why });
707
+ progressEl.style.display='none';
708
+ formWrapper.style.display='none';
709
+ errorHint.style.display='none';
710
+ loadErrorEl.textContent=DD_LABELS_ACTIVE.errorLoad;
711
+ loadErrorEl.style.display='block';
712
+ setLoading(false);
713
+ updateButtons('load_error');
714
+ ddReveal.reveal();
715
+ }
716
+
717
+ var initialized=false;
718
+ function initMF(){
719
+ if(initialized || !window.magicfeedback) return initialized;
720
+ initialized=true;
721
+ try{
722
+ window.magicfeedback.init({ debug:false, env:'${env}' });
723
+ var form = window.magicfeedback.form(${sid}, ${pid}, ${profileJson}, ${metaJson});
724
+ window.DeepdotsForm = form;
725
+ var stylesInjected=false;
726
+ form.generate('mf', {
727
+ addButton:false,
728
+ getMetaData:true,
729
+ // La pantalla final la pinta el popup: renderSuccess de @magicfeedback/native usa
730
+ // textContent, as\xED que el mensaje de la plataforma (HTML con imagen) no se ver\xEDa, y su
731
+ // fallback es un literal gen\xE9rico que ignora style.successMessage.
732
+ addSuccessScreen:false,
733
+ // Surveys multi-idioma: native pide a la API este idioma (el del init o el del
734
+ // dispositivo); si el survey no lo tiene, la API sirve el idioma por defecto.
735
+ lang:${initLangJson}||undefined,
736
+ // Foco en la primera pregunta de escribir tras Start, Siguiente o Atr\xE1s. Las versiones
737
+ // de native sin esta opci\xF3n la ignoran.
738
+ autofocus:'navigation',
739
+ onLoadedEvent:function(args){
740
+ if(args && args.error){ ddShowLoadError('error:load', args.error); return; }
741
+ // Idioma en el que native muestra el survey: manda sobre el del init para que el
742
+ // chrome no se quede en ingl\xE9s delante de un survey traducido. Native < 2.3 no lo
743
+ // env\xEDa: entonces el primero de formData.lang (el idioma por defecto).
744
+ var shown=args && typeof args.lang==='string' && args.lang.trim() ? args.lang : null;
745
+ var langs=shown ? [shown] : (args && args.formData ? args.formData.lang : null);
746
+ if(langs && langs.length){
747
+ for(var li=0;li<langs.length;li++){
748
+ if(typeof langs[li]==='string' && langs[li].trim()){ ddApplyLabels(langs[li]); break; }
749
+ }
750
+ }
751
+ var s=args && args.formData ? args.formData.style : null;
752
+ if(s && !stylesInjected){
753
+ stylesInjected=true;
754
+ if(s.successMessage){ successMessageHtml=s.successMessage; }
755
+ // La barra de progreso la decide el host (init) y, si no se pronuncia, la plataforma.
756
+ if(progressPref===null){ progressEnabled=s.showProgressBar===true; }
757
+ if(s.showProgressUnit!==undefined){ progressShowUnit=s.showProgressUnit!==false; }
758
+ if(s.progressUnit){ progressUnit=s.progressUnit; }
759
+ if(s.loadingBarColor){ progressBar.style.background=s.loadingBarColor; progressFollowUp.style.background=s.loadingBarColor; }
760
+ if(chromeOn && s.boxBackgroundColor){ popup.style.background=s.boxBackgroundColor; }
761
+ if(s.contentAlign){ main.style.justifyContent = s.contentAlign==='center' ? 'center' : 'flex-start'; }
762
+ // El survey pinta sus controles con --mf-primary, que sale de primaryColor; si la
763
+ // integraci\xF3n solo configura el del bot\xF3n, el popup mezclar\xEDa el color de la marca
764
+ // con el gris azulado por defecto del paquete.
765
+ ddApplySurveyPrimaryColor(popup, s);
766
+ if(s.buttonPrimaryColor){
767
+ submitBtn.style.background=s.buttonPrimaryColor; submitBtn.style.border='none'; submitBtn.style.color='#fff';
768
+ startBtn.style.background=s.buttonPrimaryColor; startBtn.style.border='none'; startBtn.style.color='#fff';
769
+ completeBtn.style.background=s.buttonPrimaryColor; completeBtn.style.border='none'; completeBtn.style.color='#fff';
770
+ }
771
+ if(s.buttonSecondaryColor){
772
+ // Bot\xF3n de texto: solo ti\xF1e la etiqueta, sin recuperar fondo ni borde.
773
+ backBtn.style.background='transparent'; backBtn.style.color=s.buttonSecondaryColor; backBtn.style.border='none';
774
+ }
775
+ if(s.logo && !document.getElementById('dd-logo')){
776
+ var logoImg=document.createElement('img');
777
+ logoImg.id='dd-logo'; logoImg.src=s.logo; logoImg.alt='Logo';
778
+ if(s.logoSize==='small'){ logoImg.style.maxHeight='30px'; }
779
+ else if(s.logoSize==='medium'){ logoImg.style.maxHeight='50px'; }
780
+ else if(s.logoSize==='large'){ logoImg.style.maxHeight='70px'; }
781
+ // M\xE1rgenes l\xF3gicos: con un survey RTL el popup va con dir="rtl" y el logo
782
+ // tiene que acompa\xF1ar al chrome. En LTR el resultado es el mismo de antes.
783
+ if(s.logoPosition==='left'){ logoImg.style.margin='12px 0 0 0'; logoImg.style.setProperty('margin-inline-start','0'); logoImg.style.setProperty('margin-inline-end','16px'); }
784
+ else if(s.logoPosition==='right'){ logoImg.style.margin='12px 0 0 0'; logoImg.style.setProperty('margin-inline-start','auto'); logoImg.style.setProperty('margin-inline-end','0'); }
785
+ else if(s.logoPosition==='center'){ logoImg.style.margin='12px auto 0 auto'; }
786
+ // Encima de la barra de progreso, como hermano del header (espejo de ui/logo.ts en
787
+ // web). Fuera de #dd-main, as\xED el logo no se va con el scroll del formulario.
788
+ popup.insertBefore(logoImg, progressEl);
789
+ }
790
+ if(s.startMessage && s.startMessage!==''){ onStartPage=true; updateButtons('start'); }
791
+ else { updateButtons('in_progress_first'); }
792
+ } else {
793
+ updateButtons('in_progress_first');
794
+ }
795
+ // El total solo se conoce una vez montado el form; sin \xE9l no hay barra que pintar.
796
+ updateProgress({ progress:form.progress, total:form.total, completed:false, followup:false });
797
+ emitJSON('loaded');
798
+ setLoading(false);
799
+ // La primera carga es la apertura; las siguientes (tras Start) las enfoca native.
800
+ if(!ddSurveyLoaded){ ddSurveyLoaded=true; ddAutofocusOnOpen(); }
801
+ },
802
+ beforeSubmitEvent:function(){
803
+ setLoading(true);
804
+ emitJSON('before_submit');
805
+ },
806
+ afterSubmitEvent:function(p){
807
+ if(p && p.error){
808
+ setLoading(false);
809
+ var ddErr=ddClassifySubmitError(p.error);
810
+ if(ddErr.reason==='required' || ddErr.reason==='invalid_email'){
811
+ // La p\xE1gina no ha cambiado: el estado de navegaci\xF3n se queda como estaba.
812
+ errorHint.textContent=ddErr.reason==='invalid_email' ? DD_LABELS_ACTIVE.errorInvalidEmail : DD_LABELS_ACTIVE.errorRequired;
813
+ errorHint.style.display='block';
814
+ updateNavButtons();
815
+ return;
816
+ }
817
+ errorHint.textContent=DD_LABELS_ACTIVE.errorSubmit;
818
+ errorHint.style.display='block';
819
+ // Un solo aviso por fallo: native repite el mismo objeto al cerrar el survey.
820
+ if(p.error!==ddLastReportedError){
821
+ ddLastReportedError=p.error;
822
+ emitJSON('survey_error', ddErr);
823
+ }
824
+ return;
825
+ }
826
+ errorHint.style.display='none';
827
+ setLoading(false);
828
+ if(p && p.completed){
829
+ surveyCompletedEmitted=true;
830
+ showSuccessScreen();
831
+ updateButtons('completed');
832
+ updateProgress(p);
833
+ emitJSON('survey_completed', p);
834
+ return;
835
+ }
836
+ pageDepth++;
837
+ updateNavButtons();
838
+ updateProgress(p);
839
+ emitJSON('after_submit', p);
840
+ },
841
+ onBackEvent:function(p){
842
+ // Con error ("No page found") no hubo navegaci\xF3n: la profundidad no se toca.
843
+ if(!(p&&p.error)){ pageDepth=Math.max(0,pageDepth-1); }
844
+ updateNavButtons();
845
+ // onBackEvent no trae \`total\`: se lee del form, que es su due\xF1o.
846
+ updateProgress({ progress:p&&p.progress, total:form.total, completed:false, followup:p&&p.followup });
847
+ emitJSON('back', p);
848
+ }
849
+ }).catch(function(e){ ddShowLoadError('error:init', e); });
850
+ }catch(e){ ddShowLoadError('error:exception', e); }
851
+ return true;
852
+ }
853
+ // DD-70: versi\xF3n asignada (hoja + JS) y, si algo falla, la empaquetada (hoja + JS).
854
+ var ddAssigned=${jsonForScript(assigned)}, ddBundledJs=${jsonForScript(bundledJs)};
855
+ var ddCssEl=document.getElementById('dd-survey-css'), ddBundledCss=ddCssEl?ddCssEl.textContent:'';
856
+ function ddMark(v){ try{ document.documentElement.setAttribute('data-survey-sdk', v); }catch(_){} }
857
+ function ddLoadScripts(urls, i, onFail){
858
+ if(i>=urls.length){ onFail(); return; }
859
+ var s=document.createElement('script'); s.src=urls[i]; s.async=true;
860
+ s.onload=function(){ initMF(); };
861
+ s.onerror=function(){
862
+ try{ console.warn('[Deepdots] survey SDK failed from '+urls[i]); }catch(_){}
863
+ ddLoadScripts(urls, i+1, onFail);
864
+ };
865
+ document.head.appendChild(s);
866
+ }
867
+ function ddLoadBundled(){
868
+ if(ddCssEl){ ddCssEl.textContent=ddBundledCss; }
869
+ ddMark(${jsonForScript(BUNDLED_SURVEY_SDK_VERSION + " bundled")});
870
+ ddLoadScripts(ddBundledJs, 0, function(){ ddShowLoadError('error:load', 'survey script failed to load'); });
871
+ }
872
+ function ddFetchCss(urls, i, ok, fail){
873
+ if(i>=urls.length || typeof fetch!=='function'){ fail(); return; }
874
+ fetch(urls[i]).then(function(r){ if(!r.ok) throw new Error('HTTP '+r.status); return r.text(); })
875
+ .then(function(css){ if(!css) throw new Error('empty'); ok(css); })
876
+ .catch(function(){ ddFetchCss(urls, i+1, ok, fail); });
877
+ }
878
+ if(ddAssigned){
879
+ ddFetchCss(ddAssigned.css, 0, function(css){
880
+ if(ddCssEl){ ddCssEl.textContent=css; }
881
+ ddMark(ddAssigned.version+' assigned');
882
+ ddLoadScripts(ddAssigned.js, 0, function(){
883
+ try{ console.warn('[Deepdots] survey SDK '+ddAssigned.version+' failed, using bundled'); }catch(_){}
884
+ ddLoadBundled();
885
+ });
886
+ }, function(){
887
+ try{ console.warn('[Deepdots] survey CSS '+ddAssigned.version+' failed, using bundled'); }catch(_){}
888
+ ddLoadBundled();
889
+ });
890
+ } else {
891
+ ddLoadBundled();
892
+ }
893
+ var tries=0, t=setInterval(function(){ if(initMF()||++tries>40){ clearInterval(t); } },150);
894
+ })();
895
+ </script>
896
+ </body></html>`;
897
+ }
898
+
899
+ // src/platform/react-native-renderer.ts
900
+ var NATIVE_READY_GRACE_MS = 500;
901
+ var ReactNativePopupRenderer = class {
902
+ constructor(options = {}) {
903
+ this.options = options;
904
+ this.emitFn = null;
905
+ this.onCloseFn = null;
906
+ this.currentSurveyId = null;
907
+ this.partialEmitted = false;
908
+ this.readyEmitted = false;
909
+ this.readyTimer = null;
910
+ }
911
+ init() {
912
+ }
913
+ show(surveyId, productId, actions, emit, onClose, env = "production", userId, style, sessionId, miniService, analyticsFeedbackSessionId, renderChrome, options) {
914
+ this.emitFn = emit;
915
+ this.onCloseFn = onClose;
916
+ this.currentSurveyId = surveyId;
917
+ this.partialEmitted = false;
918
+ this.readyEmitted = false;
919
+ this.armReadyFallback(surveyId);
920
+ const { profile, metadata } = buildSurveyIdentity(userId ?? null, sessionId ?? null, miniService ?? null, analyticsFeedbackSessionId ?? null);
921
+ const surveySdk = chooseSurveySdkVersion(options?.surveySdkVersion);
922
+ logRnSurveySdkChoice(surveySdk, options?.debug);
923
+ const html = buildSurveyHtml({
924
+ surveyId,
925
+ productId,
926
+ version: surveySdk.version,
927
+ env,
928
+ profile,
929
+ metadata,
930
+ font: style?.font,
931
+ theme: style?.theme,
932
+ position: style?.position,
933
+ actions,
934
+ // renderChrome:false (init) → HTML sin tarjeta/overlay: el host lo envuelve en su Modal.
935
+ chrome: renderChrome,
936
+ title: options?.title,
937
+ showProgressBar: options?.showProgressBar,
938
+ surveyCss: options?.surveyCss,
939
+ language: options?.language
940
+ });
941
+ if (this.options.onShow) {
942
+ this.options.onShow({ surveyId, productId, html });
943
+ } else {
944
+ sdkWarn(
945
+ "[Deepdots] ReactNativePopupRenderer has no onShow: pass { onShow } to new ReactNativePopupRenderer({...}) to mount the survey WebView."
946
+ );
947
+ }
948
+ }
949
+ hide() {
950
+ this.clearReadyFallback();
951
+ this.options.onHide?.();
952
+ this.currentSurveyId = null;
953
+ }
954
+ /** Respaldo del aviso de listo por si el WebView no llega a ejecutar el HTML. */
955
+ armReadyFallback(surveyId) {
956
+ this.clearReadyFallback();
957
+ if (!this.options.onReady) return;
958
+ this.readyTimer = setTimeout(() => {
959
+ this.readyTimer = null;
960
+ this.emitReady(surveyId);
961
+ }, REVEAL_TIMEOUT_MS + NATIVE_READY_GRACE_MS);
962
+ }
963
+ clearReadyFallback() {
964
+ if (this.readyTimer !== null) {
965
+ clearTimeout(this.readyTimer);
966
+ this.readyTimer = null;
967
+ }
968
+ }
969
+ /** Idempotente: el WebView puede avisar a la vez que vence el respaldo. */
970
+ emitReady(surveyId) {
971
+ if (this.readyEmitted) return;
972
+ this.readyEmitted = true;
973
+ this.clearReadyFallback();
974
+ this.options.onReady?.({ surveyId });
975
+ }
976
+ /**
977
+ * El host la conecta al `onMessage` del WebView. Traduce los mensajes del survey a
978
+ * eventos del SDK: primera interacción → `popup_clicked` (PARTIAL), completado →
979
+ * `survey_completed` (COMPLETED) y cierra el popup.
980
+ */
981
+ handleMessage(raw) {
982
+ const surveyId = this.currentSurveyId;
983
+ if (!surveyId || !this.emitFn) return;
984
+ let name;
985
+ let payload;
986
+ try {
987
+ ({ name, payload } = JSON.parse(raw));
988
+ } catch {
989
+ name = raw;
990
+ }
991
+ switch (name) {
992
+ case "ready":
993
+ this.emitReady(surveyId);
994
+ break;
995
+ case "loaded":
996
+ break;
997
+ case "before_submit":
998
+ case "after_submit":
999
+ case "back":
1000
+ if (!this.partialEmitted) {
1001
+ this.partialEmitted = true;
1002
+ this.emitFn("popup_clicked", surveyId, { action: "partial" });
1003
+ }
1004
+ break;
1005
+ case "survey_completed":
1006
+ this.emitFn("survey_completed", surveyId);
1007
+ break;
1008
+ case "survey_error":
1009
+ this.emitFn("survey_error", surveyId, { reason: payload?.reason, message: payload?.message });
1010
+ break;
1011
+ case "popup_close":
1012
+ this.onCloseFn?.();
1013
+ break;
1014
+ default:
1015
+ if (typeof name === "string" && name.startsWith("error:")) this.emitReady(surveyId);
1016
+ break;
1017
+ }
1018
+ }
1019
+ };
1020
+ function isReactNativeEnv() {
1021
+ return typeof navigator !== "undefined" && navigator.product === "ReactNative";
1022
+ }
1023
+ function createReactNativeRenderer() {
1024
+ return new ReactNativePopupRenderer();
1025
+ }
1026
+ function logRnSurveySdkChoice(choice, debug) {
1027
+ const problem = choice.source === "bundled" && choice.reason === "invalid";
1028
+ if (problem) sdkWarn(`[Deepdots] ${describeSurveySdkChoice(choice)}`);
1029
+ else if (debug) sdkLog(`[Deepdots] ${describeSurveySdkChoice(choice)}`);
1030
+ }
1031
+
1032
+ // src/ui/preload.ts
1033
+ var defaultLoader = () => import("./renderPopup-YDJUON42.mjs");
1034
+ var pending = null;
1035
+ function preloadRenderPopup(loader = defaultLoader) {
1036
+ if (pending) return pending;
1037
+ try {
1038
+ pending = loader().then(() => void 0).catch(() => {
1039
+ pending = null;
1040
+ });
1041
+ } catch {
1042
+ pending = null;
1043
+ return Promise.resolve();
1044
+ }
1045
+ return pending;
1046
+ }
1047
+ function schedulePreloadRenderPopup(loader) {
1048
+ const run = () => {
1049
+ void preloadRenderPopup(loader);
1050
+ };
1051
+ const idle = globalThis.requestIdleCallback;
1052
+ if (typeof idle === "function") {
1053
+ idle(run, { timeout: 2e3 });
1054
+ return;
1055
+ }
1056
+ setTimeout(run, 0);
1057
+ }
1058
+
1059
+ // src/platform/renderer.ts
1060
+ var NoopPopupRenderer = class {
1061
+ show() {
1062
+ }
1063
+ hide() {
1064
+ }
1065
+ };
1066
+ var BrowserPopupRenderer = class {
1067
+ constructor() {
1068
+ this.container = null;
1069
+ this.visible = false;
1070
+ }
1071
+ init() {
1072
+ if (typeof document === "undefined") return;
1073
+ if (!this.container) {
1074
+ this.container = document.createElement("div");
1075
+ this.container.id = "deepdots-popup-container";
1076
+ this.container.style.cssText = `
1077
+ position: fixed;
1078
+ top: 0;
1079
+ left: 0;
1080
+ width: 100%;
1081
+ height: 100%;
1082
+ display: none;
1083
+ z-index: 999999;
1084
+ background: rgba(0, 0, 0, 0.5);
1085
+ justify-content: center;
1086
+ align-items: center;
1087
+ `;
1088
+ }
1089
+ if (!document.body.contains(this.container)) {
1090
+ document.body.appendChild(this.container);
1091
+ }
1092
+ }
1093
+ /**
1094
+ * Descarga el chunk de `renderPopup` antes de que ningún trigger dispare, para que abrir el
1095
+ * popup no empiece por esperar ~238 KB de JS.
1096
+ */
1097
+ preload() {
1098
+ schedulePreloadRenderPopup();
1099
+ }
1100
+ show(surveyId, productId, actions, emit, onClose, env = "production", userId, style, sessionId, miniService, analyticsFeedbackSessionId, _renderChrome, options) {
1101
+ if (this.visible) return;
1102
+ if (!this.container || !document.body.contains(this.container)) this.init();
1103
+ if (!this.container) return;
1104
+ this.visible = true;
1105
+ const container = this.container;
1106
+ void import("./renderPopup-YDJUON42.mjs").then(
1107
+ ({ renderPopup }) => {
1108
+ renderPopup(container, surveyId, productId, actions, emit, onClose, env, userId, style, sessionId, miniService, analyticsFeedbackSessionId, options);
1109
+ },
1110
+ (error) => {
1111
+ this.visible = false;
1112
+ sdkWarn("[Deepdots] popup renderer failed to load:", error);
1113
+ }
1114
+ );
1115
+ }
1116
+ isShowing() {
1117
+ return this.visible;
1118
+ }
1119
+ hide() {
1120
+ this.visible = false;
1121
+ if (this.container) {
1122
+ this.container.style.display = "none";
1123
+ this.container.style.visibility = "";
1124
+ this.container.style.pointerEvents = "";
1125
+ this.container.innerHTML = "";
1126
+ }
1127
+ }
1128
+ };
1129
+ function createDefaultRenderer() {
1130
+ if (typeof document === "undefined") {
1131
+ if (isReactNativeEnv()) return createReactNativeRenderer();
1132
+ return new NoopPopupRenderer();
1133
+ }
1134
+ if (isReactNativeEnv()) return createReactNativeRenderer();
1135
+ return new BrowserPopupRenderer();
1136
+ }
1137
+
1138
+ // src/analytics/analytics-manager.ts
1139
+ function createDryRunSink(log = console.log) {
1140
+ return (payload, meta) => {
1141
+ if (meta?.resetSession) return;
1142
+ log(
1143
+ "[DeepdotsAnalytics] (dry-run \xB7 NOT sent \xB7 no init.analytics) POST /sdk/feedback \u2192",
1144
+ JSON.stringify(payload, null, 2)
1145
+ );
1146
+ };
1147
+ }
1148
+ var dryRunSink = createDryRunSink();
1149
+ var AnalyticsManager = class {
1150
+ constructor(options = {}) {
1151
+ this.events = [];
1152
+ this.attributes = {};
1153
+ /** Métricas del host (valores medibles persistentes). Sobrescriben por key; se reenvían en cada flush. */
1154
+ this.metrics = {};
1155
+ /** Mini-services activos: nombre → timestamp de entrada. El orden de inserción marca el "más reciente". */
1156
+ this.activeMiniServices = /* @__PURE__ */ new Map();
1157
+ this.sink = options.sink ?? dryRunSink;
1158
+ this.now = options.now ?? (() => Date.now());
1159
+ this.publicKey = options.publicKey;
1160
+ this.language = options.language;
1161
+ this.device = options.device;
1162
+ this.platform = options.platform ?? "web";
1163
+ this.maxBatchSize = options.maxBatchSize ?? 20;
1164
+ this.maxBufferedEvents = options.maxBufferedEvents ?? 200;
1165
+ this.onFlushNeeded = options.onFlushNeeded;
1166
+ }
1167
+ /** Actualiza campos de device en runtime (p.ej. country/city tras resolver geo). */
1168
+ updateDevice(partial) {
1169
+ this.device = { ...this.device, ...partial };
1170
+ }
1171
+ /** Mezcla user attributes (se coercionan a string). Mutable en runtime. */
1172
+ setUserAttributes(attrs) {
1173
+ for (const [k, v] of Object.entries(attrs)) {
1174
+ if (!k) continue;
1175
+ this.attributes[k] = String(v);
1176
+ }
1177
+ }
1178
+ /**
1179
+ * Registra/actualiza una métrica (valor medible). Persistente: se reenvía en cada flush.
1180
+ * Repetir la misma key SOBRESCRIBE; el valor se coerciona a string; ignora key vacía.
1181
+ */
1182
+ setMetric(key, value) {
1183
+ if (!key) return;
1184
+ this.metrics[key] = String(value);
1185
+ }
1186
+ /**
1187
+ * Marca el inicio de un mini-service; etiqueta los eventos siguientes con `mini_service`.
1188
+ * Admite varios activos a la vez (concurrencia); el "actual" para etiquetar es el más reciente.
1189
+ * Reentrar con un nombre ya activo refresca su orden y su tiempo de entrada.
1190
+ */
1191
+ enterMiniService(name, entryPointType) {
1192
+ this.activeMiniServices.delete(name);
1193
+ this.activeMiniServices.set(name, this.now());
1194
+ this.track("deepdots_mini_service_enter", { entry_point_type: entryPointType ?? null });
1195
+ }
1196
+ /**
1197
+ * Cierra el mini-service `name` emitiendo `mini_service_exit` con su duración (#27).
1198
+ * No-op si ese nombre no está activo. Cierre coherente con concurrencia.
1199
+ */
1200
+ exitMiniService(name) {
1201
+ const enteredAt = this.activeMiniServices.get(name);
1202
+ if (enteredAt === void 0) return;
1203
+ const durationSeconds = Math.max(0, Math.round((this.now() - enteredAt) / 1e3));
1204
+ this.activeMiniServices.delete(name);
1205
+ this.track("deepdots_mini_service_exit", { mini_service: name, duration_seconds: durationSeconds });
1206
+ }
1207
+ /** Cierra TODOS los mini-services activos (orden LIFO). Para el cierre por lifecycle (background/cierre). */
1208
+ exitAllMiniServices() {
1209
+ for (const name of Array.from(this.activeMiniServices.keys()).reverse()) {
1210
+ this.exitMiniService(name);
1211
+ }
1212
+ }
1213
+ /**
1214
+ * Olvida la sesión en curso SIN emitir nada: vacía el buffer y los mini-services activos
1215
+ * (sin `mini_service_exit`). Para una sesión que el backend ya cerró por inactividad: lo
1216
+ * que quedara pendiente pertenecía a ella y no debe llegar con la sesión nueva.
1217
+ */
1218
+ discardSession(identity) {
1219
+ this.events = [];
1220
+ this.activeMiniServices.clear();
1221
+ try {
1222
+ void this.sink({ ...this.buildPayload(identity), events: [] }, { resetSession: true });
1223
+ } catch {
1224
+ }
1225
+ }
1226
+ /**
1227
+ * Olvida lo que pertenecía al usuario anterior (user attributes + métricas) al cambiar de
1228
+ * usuario. NO toca el buffer de eventos: el cierre de sesión ya lo vació con la identidad
1229
+ * vieja, y lo que llegue después es del usuario nuevo.
1230
+ */
1231
+ resetUserScope() {
1232
+ this.attributes = {};
1233
+ this.metrics = {};
1234
+ }
1235
+ /** Registra un evento de analítica (modelo GA: nombre + params). */
1236
+ track(name, params) {
1237
+ const current = this.getMiniService();
1238
+ const merged = {
1239
+ ...current ? { mini_service: current } : {},
1240
+ ...params ?? {}
1241
+ };
1242
+ this.events.push({
1243
+ name,
1244
+ timestamp: this.now(),
1245
+ params: Object.keys(merged).length ? merged : void 0
1246
+ });
1247
+ this.enforceBufferCap();
1248
+ if (this.events.length >= this.maxBatchSize) {
1249
+ this.onFlushNeeded?.();
1250
+ }
1251
+ }
1252
+ /** Mini-service actual (el más reciente aún activo) para etiquetar eventos + metadata del survey (#33). */
1253
+ getMiniService() {
1254
+ let last = null;
1255
+ for (const name of this.activeMiniServices.keys()) last = name;
1256
+ return last;
1257
+ }
1258
+ /** Nº de eventos pendientes de flush. */
1259
+ pending() {
1260
+ return this.events.length;
1261
+ }
1262
+ /** Construye el envelope que se enviaría al endpoint de analytics. */
1263
+ buildPayload(identity) {
1264
+ return {
1265
+ publicKey: this.publicKey,
1266
+ userId: identity.userId,
1267
+ sessionId: identity.sessionId,
1268
+ context: {
1269
+ platform: this.platform,
1270
+ sdk: SDK_IDENTIFIER,
1271
+ language: this.language,
1272
+ device: this.device,
1273
+ attributes: { ...this.attributes },
1274
+ metrics: { ...this.metrics }
1275
+ },
1276
+ events: [...this.events]
1277
+ };
1278
+ }
1279
+ /**
1280
+ * Envía (vía sink) el lote acumulado y vacía el buffer. No-op si no hay eventos.
1281
+ *
1282
+ * Si el sink falla de forma transitoria (promesa rechazada o excepción síncrona) el lote
1283
+ * se **re-encola** al principio del buffer y se reintenta en el siguiente flush: un error
1284
+ * de red o un 5xx no debe hacer desaparecer los eventos.
1285
+ */
1286
+ flush(identity, meta) {
1287
+ if (this.events.length === 0) return null;
1288
+ const batch = this.events;
1289
+ const payload = this.buildPayload(identity);
1290
+ this.events = [];
1291
+ let result;
1292
+ try {
1293
+ result = meta ? this.sink(payload, meta) : this.sink(payload);
1294
+ } catch {
1295
+ this.requeue(batch);
1296
+ return payload;
1297
+ }
1298
+ if (result && typeof result.then === "function") {
1299
+ result.catch(() => this.requeue(batch));
1300
+ }
1301
+ return payload;
1302
+ }
1303
+ /**
1304
+ * Devuelve un lote fallido al buffer, delante de lo que haya llegado mientras se enviaba
1305
+ * (orden cronológico). Con el buffer lleno se descartan los eventos más antiguos.
1306
+ */
1307
+ requeue(batch) {
1308
+ this.events = [...batch, ...this.events];
1309
+ this.enforceBufferCap();
1310
+ }
1311
+ /** Techo del buffer: si el envío lleva rato fallando, se sacrifica lo más antiguo. */
1312
+ enforceBufferCap() {
1313
+ const overflow = this.events.length - this.maxBufferedEvents;
1314
+ if (overflow > 0) this.events.splice(0, overflow);
1315
+ }
1316
+ };
1317
+
1318
+ // src/analytics/background-task.ts
1319
+ var BACKGROUND_TASK_MAX_MS = 25e3;
1320
+ async function runInBackgroundTask(begin, name, work, maxMs = BACKGROUND_TASK_MAX_MS) {
1321
+ let end;
1322
+ try {
1323
+ end = begin?.(name);
1324
+ } catch {
1325
+ end = void 0;
1326
+ }
1327
+ if (typeof end !== "function") return work();
1328
+ let ended = false;
1329
+ const finish = () => {
1330
+ if (ended) return;
1331
+ ended = true;
1332
+ clearTimeout(timer);
1333
+ try {
1334
+ end();
1335
+ } catch {
1336
+ }
1337
+ };
1338
+ const timer = setTimeout(finish, maxMs);
1339
+ try {
1340
+ return await work();
1341
+ } finally {
1342
+ finish();
1343
+ }
1344
+ }
1345
+ function backgroundTimerTask(timer) {
1346
+ let open = 0;
1347
+ return () => {
1348
+ if (open === 0) timer.start(0);
1349
+ open++;
1350
+ let closed = false;
1351
+ return () => {
1352
+ if (closed) return;
1353
+ closed = true;
1354
+ open--;
1355
+ if (open === 0) timer.stop();
1356
+ };
1357
+ };
1358
+ }
1359
+
1360
+ // src/analytics/feedback-payload.ts
1361
+ function pushKV(list, key, value) {
1362
+ if (value === void 0 || value === null || value === "") return;
1363
+ list.push({ key, value: [String(value)] });
1364
+ }
1365
+ function buildAnalyticsFeedbackBody(envelope, keys, feedbackSessionId, options) {
1366
+ const { context } = envelope;
1367
+ const profile = [];
1368
+ pushKV(profile, "external-user-id", envelope.userId);
1369
+ const metadata = [];
1370
+ pushKV(metadata, "deepdots_user_id", envelope.userId);
1371
+ pushKV(metadata, "deepdots_session_id", envelope.sessionId);
1372
+ pushKV(metadata, "deepdots_platform", context.platform);
1373
+ pushKV(metadata, "deepdots_sdk", context.sdk);
1374
+ pushKV(metadata, "deepdots_language", context.language);
1375
+ if (context.device) {
1376
+ const d = context.device;
1377
+ pushKV(metadata, "deepdots_device_type", d.device_type);
1378
+ pushKV(metadata, "deepdots_os_version", d.os_version);
1379
+ pushKV(metadata, "deepdots_device_model", d.device_model);
1380
+ pushKV(metadata, "deepdots_app_version", d.app_version);
1381
+ pushKV(metadata, "deepdots_user_agent", d.user_agent);
1382
+ pushKV(metadata, "deepdots_timezone", d.timezone);
1383
+ pushKV(metadata, "deepdots_referrer", d.referrer);
1384
+ pushKV(metadata, "deepdots_viewport_size", d.viewport_size);
1385
+ pushKV(metadata, "deepdots_screen_resolution", d.screen_resolution);
1386
+ pushKV(metadata, "deepdots_pixel_ratio", d.pixel_ratio);
1387
+ pushKV(metadata, "deepdots_entry_type", d.entry_type);
1388
+ pushKV(metadata, "deepdots_page_load_ms", d.page_load_ms);
1389
+ pushKV(metadata, "deepdots_connection_type", d.connection_type);
1390
+ pushKV(metadata, "deepdots_country", d.country);
1391
+ pushKV(metadata, "deepdots_city", d.city);
1392
+ }
1393
+ for (const [k, v] of Object.entries(context.attributes ?? {})) {
1394
+ pushKV(metadata, k, v);
1395
+ }
1396
+ for (const e of envelope.events) {
1397
+ metadata.push({
1398
+ key: e.name,
1399
+ value: [JSON.stringify({ timestamp: e.timestamp, ...e.params ?? {} })]
1400
+ });
1401
+ }
1402
+ const metrics = [];
1403
+ for (const [k, v] of Object.entries(context.metrics ?? {})) {
1404
+ pushKV(metrics, k, v);
1405
+ }
1406
+ return {
1407
+ feedback: {
1408
+ text: "",
1409
+ answers: [],
1410
+ metrics,
1411
+ metadata,
1412
+ profile,
1413
+ finished: false
1414
+ },
1415
+ publicKey: keys.publicKey,
1416
+ integration: keys.integration,
1417
+ // Único marcador de cierre acordado con backend: el último lote de la sesión.
1418
+ completed: options?.sessionEnd === true,
1419
+ ...feedbackSessionId ? { sessionId: feedbackSessionId } : {}
1420
+ };
1421
+ }
1422
+ var KEEPALIVE_MAX_BYTES = 6e4;
1423
+ function isRetryableStatus(status) {
1424
+ return status >= 500 || status === 408 || status === 429;
1425
+ }
1426
+ async function safeBodyText(res) {
1427
+ try {
1428
+ return (await res.text()).slice(0, 500);
1429
+ } catch {
1430
+ return "";
1431
+ }
1432
+ }
1433
+ var PENDING_MAX = 50;
1434
+ var PENDING_MAX_AGE_MS = 24 * 60 * 60 * 1e3;
1435
+ var POST_TIMEOUT_MS = 2e4;
1436
+ function pendingKey(integration) {
1437
+ return `__deepdots_analytics_pending__:${integration}`;
1438
+ }
1439
+ function generateSessionId() {
1440
+ const c = globalThis.crypto;
1441
+ if (typeof c?.randomUUID === "function") return c.randomUUID();
1442
+ const b = new Uint8Array(16);
1443
+ if (typeof c?.getRandomValues === "function") c.getRandomValues(b);
1444
+ else for (let i = 0; i < 16; i++) b[i] = Math.floor(Math.random() * 256);
1445
+ b[6] = b[6] & 15 | 64;
1446
+ b[8] = b[8] & 63 | 128;
1447
+ const h = Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
1448
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
1449
+ }
1450
+ function createFeedbackSink(options) {
1451
+ const url = `${options.baseUrl}/sdk/feedback`;
1452
+ const newSessionId = options.newSessionId ?? generateSessionId;
1453
+ const now = options.now ?? (() => Date.now());
1454
+ const storageKey = pendingKey(options.keys.integration);
1455
+ let feedbackSessionId = options.initialSessionId || void 0;
1456
+ let announcedId = feedbackSessionId;
1457
+ const pending2 = loadPending();
1458
+ let draining = null;
1459
+ function loadPending() {
1460
+ if (!options.storage) return [];
1461
+ try {
1462
+ const raw = options.storage.getItem(storageKey);
1463
+ const list = raw ? JSON.parse(raw) : [];
1464
+ return Array.isArray(list) ? list.filter((p) => p?.body && now() - p.at <= PENDING_MAX_AGE_MS) : [];
1465
+ } catch {
1466
+ return [];
1467
+ }
1468
+ }
1469
+ function savePending() {
1470
+ if (!options.storage) return;
1471
+ try {
1472
+ if (pending2.length) options.storage.setItem(storageKey, JSON.stringify(pending2));
1473
+ else options.storage.removeItem(storageKey);
1474
+ } catch {
1475
+ }
1476
+ }
1477
+ function addPending(batch) {
1478
+ pending2.push(batch);
1479
+ if (pending2.length > PENDING_MAX) pending2.splice(0, pending2.length - PENDING_MAX);
1480
+ savePending();
1481
+ }
1482
+ function removePending(batch) {
1483
+ const i = pending2.indexOf(batch);
1484
+ if (i >= 0) pending2.splice(i, 1);
1485
+ savePending();
1486
+ }
1487
+ async function post(body, final) {
1488
+ const json = JSON.stringify(body);
1489
+ const small = json.length <= KEEPALIVE_MAX_BYTES;
1490
+ if (final) options.log?.("[DeepdotsAnalytics] final flush via fetch keepalive");
1491
+ const f = options.fetchImpl ?? (typeof fetch !== "undefined" ? fetch : void 0);
1492
+ if (!f) {
1493
+ options.log?.("[DeepdotsAnalytics] no fetch available; payload not sent", body);
1494
+ return "drop";
1495
+ }
1496
+ let timer;
1497
+ try {
1498
+ const request = f(url, {
1499
+ method: "POST",
1500
+ headers: { "Content-Type": "application/json" },
1501
+ body: json,
1502
+ // La API autentica por `publicKey` en el body y responde `Allow-Origin: *`: una
1503
+ // petición con credenciales fallaría el CORS. Explícito para no depender del default.
1504
+ credentials: "omit",
1505
+ // keepalive: el POST sobrevive a la navegación mientras el body sea pequeño.
1506
+ ...small ? { keepalive: true } : {}
1507
+ });
1508
+ const timeout = new Promise((_, reject) => {
1509
+ timer = setTimeout(() => reject(new Error("timeout")), POST_TIMEOUT_MS);
1510
+ });
1511
+ const res = await Promise.race([request, timeout]);
1512
+ if (res.ok) return "ok";
1513
+ const detail = await safeBodyText(res);
1514
+ if (isRetryableStatus(res.status)) {
1515
+ options.log?.(`[DeepdotsAnalytics] POST /sdk/feedback ${res.status} (retryable): ${detail}`);
1516
+ return "retry";
1517
+ }
1518
+ options.log?.(
1519
+ `[DeepdotsAnalytics] POST /sdk/feedback rejected with ${res.status}; batch DISCARDED:`,
1520
+ detail
1521
+ );
1522
+ return "drop";
1523
+ } catch (error) {
1524
+ options.log?.("[DeepdotsAnalytics] POST /sdk/feedback failed (will retry):", error);
1525
+ return "retry";
1526
+ } finally {
1527
+ clearTimeout(timer);
1528
+ }
1529
+ }
1530
+ function delivered(body) {
1531
+ const id = body.sessionId;
1532
+ if (!id) return;
1533
+ try {
1534
+ if (body.completed) {
1535
+ options.onSessionClosed?.(id);
1536
+ } else if (id === feedbackSessionId && id !== announcedId) {
1537
+ announcedId = id;
1538
+ options.log?.("[DeepdotsAnalytics] feedback session open:", id);
1539
+ options.onSessionId?.(id);
1540
+ }
1541
+ } catch {
1542
+ }
1543
+ }
1544
+ async function send(batch, final, alreadyPending) {
1545
+ const result = await post(batch.body, final);
1546
+ if (result === "retry") {
1547
+ if (!alreadyPending) addPending(batch);
1548
+ return;
1549
+ }
1550
+ if (alreadyPending) removePending(batch);
1551
+ if (result === "ok") delivered(batch.body);
1552
+ }
1553
+ function drain() {
1554
+ const run = async () => {
1555
+ for (let i = 0; i < pending2.length; ) {
1556
+ const batch = pending2[i];
1557
+ await send(batch, false, true);
1558
+ if (pending2[i] === batch) return;
1559
+ }
1560
+ };
1561
+ const next = draining ? draining.then(run) : run();
1562
+ draining = next;
1563
+ void next.finally(() => {
1564
+ if (draining === next) draining = null;
1565
+ });
1566
+ return next;
1567
+ }
1568
+ if (pending2.length) {
1569
+ savePending();
1570
+ setTimeout(() => void drain(), 0);
1571
+ }
1572
+ const sink = (envelope, meta) => runInBackgroundTask(options.backgroundTask, "deepdots-analytics", () => deliver(envelope, meta));
1573
+ return sink;
1574
+ async function deliver(envelope, meta) {
1575
+ if (meta?.resetSession) {
1576
+ feedbackSessionId = void 0;
1577
+ options.onSessionReset?.();
1578
+ return;
1579
+ }
1580
+ const final = meta?.final === true;
1581
+ const sessionEnd = meta?.sessionEnd === true;
1582
+ if (!feedbackSessionId) feedbackSessionId = newSessionId();
1583
+ const body = buildAnalyticsFeedbackBody(envelope, options.keys, feedbackSessionId, { sessionEnd });
1584
+ options.log?.("[DeepdotsAnalytics] POST /sdk/feedback \u2192", body);
1585
+ const batch = { body, at: now() };
1586
+ if (sessionEnd) {
1587
+ feedbackSessionId = void 0;
1588
+ options.onSessionReset?.();
1589
+ addPending(batch);
1590
+ await drain();
1591
+ return;
1592
+ }
1593
+ const retries = pending2.length ? drain() : null;
1594
+ await Promise.all([retries, send(batch, final, false)]);
1595
+ }
1596
+ }
1597
+
1598
+ // src/analytics/suspended-session.ts
1599
+ var SUSPENDED_SESSION_KEY = "deepdots.analytics.suspended";
1600
+ function getSessionStorage() {
1601
+ try {
1602
+ return typeof window !== "undefined" && window.sessionStorage ? window.sessionStorage : null;
1603
+ } catch {
1604
+ return null;
1605
+ }
1606
+ }
1607
+ function writeSuspendedSession(storage, session) {
1608
+ try {
1609
+ storage.setItem(SUSPENDED_SESSION_KEY, JSON.stringify(session));
1610
+ return true;
1611
+ } catch {
1612
+ return false;
1613
+ }
1614
+ }
1615
+ function clearSuspendedSession(storage) {
1616
+ try {
1617
+ storage.removeItem(SUSPENDED_SESSION_KEY);
1618
+ } catch {
1619
+ }
1620
+ }
1621
+ function takeSuspendedSession(storage, match, now, windowMs) {
1622
+ let raw = null;
1623
+ try {
1624
+ raw = storage.getItem(SUSPENDED_SESSION_KEY);
1625
+ } catch {
1626
+ return null;
1627
+ }
1628
+ if (!raw) return null;
1629
+ clearSuspendedSession(storage);
1630
+ try {
1631
+ const s = JSON.parse(raw);
1632
+ if (typeof s.sessionId !== "string" || !s.sessionId) return null;
1633
+ if (typeof s.at !== "number" || now - s.at < 0 || now - s.at > windowMs) return null;
1634
+ if (s.integration !== match.integration) return null;
1635
+ if ((s.userId ?? null) !== match.userId) return null;
1636
+ return { sessionId: s.sessionId, integration: s.integration, userId: s.userId ?? null, at: s.at };
1637
+ } catch {
1638
+ return null;
1639
+ }
1640
+ }
1641
+
1642
+ // src/tracking/navigation-observer.ts
1643
+ var UUID_PREFIX = /^[0-9a-f]{8}-[0-9a-f]{4}-/i;
1644
+ function screenPath(href) {
1645
+ let pathAndHash;
1646
+ try {
1647
+ const u = new URL(href, "http://deepdots.local");
1648
+ pathAndHash = u.pathname + (u.hash || "");
1649
+ } catch {
1650
+ pathAndHash = href;
1651
+ }
1652
+ return pathAndHash.replace(/\?[^#]*/g, "") || "/";
1653
+ }
1654
+ function normalizeScreen(href) {
1655
+ const pathAndHash = screenPath(href);
1656
+ const collapsed = pathAndHash.split("/").map((seg) => /^[0-9]+$/.test(seg) || UUID_PREFIX.test(seg) ? ":id" : seg).join("/");
1657
+ return collapsed || "/";
1658
+ }
1659
+ var NavigationObserver = class {
1660
+ constructor(options = {}) {
1661
+ this.listeners = /* @__PURE__ */ new Set();
1662
+ this.currentScreen = null;
1663
+ this.currentPath = null;
1664
+ this.entryAt = 0;
1665
+ this.installed = false;
1666
+ this.domHandlers = [];
1667
+ this.now = options.now ?? (() => Date.now());
1668
+ }
1669
+ onVisit(listener) {
1670
+ this.listeners.add(listener);
1671
+ }
1672
+ /** Fija la pantalla inicial (sin emitir visita; su duración se cierra al salir). */
1673
+ begin(href) {
1674
+ this.currentScreen = normalizeScreen(href);
1675
+ this.currentPath = screenPath(href);
1676
+ this.entryAt = this.now();
1677
+ }
1678
+ /** Navega a una pantalla nueva: cierra la anterior (emite visita) y abre la nueva. */
1679
+ visit(href) {
1680
+ const nextPath = screenPath(href);
1681
+ if (this.currentScreen != null && nextPath === this.currentPath) return;
1682
+ this.closeCurrent();
1683
+ this.currentScreen = normalizeScreen(href);
1684
+ this.currentPath = nextPath;
1685
+ this.entryAt = this.now();
1686
+ }
1687
+ /** Cierra la pantalla actual emitiendo su visita (p. ej. al cerrar la app/pestaña). */
1688
+ stop() {
1689
+ this.closeCurrent();
1690
+ this.currentScreen = null;
1691
+ this.currentPath = null;
1692
+ }
1693
+ /**
1694
+ * Olvida la pantalla actual SIN emitir su visita. Para una sesión que el backend ya dio
1695
+ * por cerrada: su visita no tiene dónde ir, y mandarla con la sesión nueva la contaría
1696
+ * donde no ocurrió. Después, `restart()` vuelve a empezar en la pantalla actual.
1697
+ */
1698
+ discard() {
1699
+ this.currentScreen = null;
1700
+ this.currentPath = null;
1701
+ }
1702
+ /**
1703
+ * Retoma el seguimiento en la pantalla actual tras un `stop()`, cuando se abre una sesión
1704
+ * nueva sin navegar (cambio de usuario, vuelta de la bfcache). No-op si nunca se instaló
1705
+ * (navegación manual por `setScreen`, RN) o si ya hay pantalla en curso.
1706
+ */
1707
+ restart() {
1708
+ if (!this.installed || this.currentScreen != null || typeof window === "undefined") return;
1709
+ this.begin(window.location.href);
1710
+ }
1711
+ /**
1712
+ * La pantalla en curso, sin cerrarla ni emitir nada; null si no hay (antes de `begin`, tras
1713
+ * `stop`/`discard`). Para que el `user_engagement` lleve la pantalla: si el cierre de la
1714
+ * sesión no llega nunca (pestaña dormida y descartada, app matada), la última pantalla no
1715
+ * tiene `page_view` y solo queda esto.
1716
+ */
1717
+ current() {
1718
+ if (this.currentScreen == null) return null;
1719
+ return {
1720
+ screen: this.currentScreen,
1721
+ path: this.currentPath ?? this.currentScreen,
1722
+ seconds: this.secondsSinceEntry(this.now())
1723
+ };
1724
+ }
1725
+ secondsSinceEntry(at) {
1726
+ return Math.max(0, Math.round((at - this.entryAt) / 1e3));
1727
+ }
1728
+ closeCurrent() {
1729
+ if (this.currentScreen == null) return;
1730
+ const exit = this.now();
1731
+ const visit = {
1732
+ screen: this.currentScreen,
1733
+ path: this.currentPath ?? this.currentScreen,
1734
+ entry: this.entryAt,
1735
+ exit,
1736
+ durationSeconds: this.secondsSinceEntry(exit)
1737
+ };
1738
+ this.listeners.forEach((l) => {
1739
+ try {
1740
+ l(visit);
1741
+ } catch {
1742
+ }
1743
+ });
1744
+ }
1745
+ /** Instala los hooks de History en el navegador y registra la pantalla actual. */
1746
+ install() {
1747
+ if (this.installed || typeof window === "undefined" || typeof history === "undefined") return;
1748
+ this.installed = true;
1749
+ const handle = () => this.visit(window.location.href);
1750
+ const originalPush = history.pushState.bind(history);
1751
+ const originalReplace = history.replaceState.bind(history);
1752
+ history.pushState = (data, unused, url) => {
1753
+ const r = originalPush(data, unused, url);
1754
+ handle();
1755
+ return r;
1756
+ };
1757
+ history.replaceState = (data, unused, url) => {
1758
+ const r = originalReplace(data, unused, url);
1759
+ handle();
1760
+ return r;
1761
+ };
1762
+ window.addEventListener("popstate", handle);
1763
+ window.addEventListener("hashchange", handle);
1764
+ this.domHandlers.push(() => {
1765
+ history.pushState = originalPush;
1766
+ history.replaceState = originalReplace;
1767
+ window.removeEventListener("popstate", handle);
1768
+ window.removeEventListener("hashchange", handle);
1769
+ });
1770
+ this.begin(window.location.href);
1771
+ }
1772
+ uninstall() {
1773
+ this.domHandlers.forEach((off) => off());
1774
+ this.domHandlers = [];
1775
+ this.installed = false;
1776
+ }
1777
+ };
1778
+
1779
+ // src/analytics/device-info.ts
1780
+ function parseDeviceType(ua) {
1781
+ const s = (ua || "").toLowerCase();
1782
+ if (/ipad|tablet|playbook|silk/.test(s) || /android/.test(s) && !/mobile/.test(s)) {
1783
+ return "tablet";
1784
+ }
1785
+ if (/mobi|iphone|ipod|windows phone/.test(s) || /android/.test(s) && /mobile/.test(s)) {
1786
+ return "mobile";
1787
+ }
1788
+ return "desktop";
1789
+ }
1790
+ function getEntryType() {
1791
+ if (typeof performance === "undefined") return void 0;
1792
+ const entries = performance.getEntriesByType("navigation");
1793
+ if (!entries.length) return void 0;
1794
+ return entries[0].type;
1795
+ }
1796
+ function getPageLoadMs() {
1797
+ if (typeof performance === "undefined") return void 0;
1798
+ const entries = performance.getEntriesByType("navigation");
1799
+ if (!entries.length) return void 0;
1800
+ const load = entries[0].loadEventEnd;
1801
+ return load > 0 ? Math.round(load) : void 0;
1802
+ }
1803
+ function getConnectionType() {
1804
+ if (typeof navigator === "undefined") return void 0;
1805
+ return navigator.connection?.effectiveType ?? void 0;
1806
+ }
1807
+ function collectDeviceInfo(appVersion) {
1808
+ const ua = typeof navigator !== "undefined" ? navigator.userAgent : "";
1809
+ return {
1810
+ device_type: parseDeviceType(ua),
1811
+ user_agent: ua || void 0,
1812
+ app_version: appVersion,
1813
+ timezone: typeof Intl !== "undefined" ? Intl.DateTimeFormat().resolvedOptions().timeZone : void 0,
1814
+ referrer: typeof document !== "undefined" && document.referrer ? document.referrer : void 0,
1815
+ viewport_size: typeof window !== "undefined" ? `${window.innerWidth}x${window.innerHeight}` : void 0,
1816
+ screen_resolution: typeof screen !== "undefined" ? `${screen.width}x${screen.height}` : void 0,
1817
+ pixel_ratio: typeof window !== "undefined" ? window.devicePixelRatio : void 0,
1818
+ entry_type: getEntryType(),
1819
+ page_load_ms: getPageLoadMs(),
1820
+ connection_type: getConnectionType()
1821
+ };
1822
+ }
1823
+
1824
+ // src/analytics/geo-info.ts
1825
+ var GEO_STORAGE_KEY = "deepdots.geo";
1826
+ var GEO_TTL_MS = 30 * 24 * 60 * 60 * 1e3;
1827
+ var GEO_TIMEOUT_MS = 3e3;
1828
+ function readCachedGeo(storage, now) {
1829
+ try {
1830
+ const raw = storage.getItem(GEO_STORAGE_KEY);
1831
+ if (!raw) return null;
1832
+ const cached = JSON.parse(raw);
1833
+ if (typeof cached.ts !== "number" || now - cached.ts > GEO_TTL_MS) return null;
1834
+ const geo = {};
1835
+ if (cached.country) geo.country = cached.country;
1836
+ if (cached.city) geo.city = cached.city;
1837
+ return geo.country || geo.city ? geo : null;
1838
+ } catch {
1839
+ return null;
1840
+ }
1841
+ }
1842
+ function writeCachedGeo(storage, geo, now) {
1843
+ try {
1844
+ const payload = { ...geo, ts: now };
1845
+ storage.setItem(GEO_STORAGE_KEY, JSON.stringify(payload));
1846
+ } catch {
1847
+ }
1848
+ }
1849
+ var DEFAULT_GEO_PROVIDERS = [
1850
+ {
1851
+ // https://ipapi.co/json/
1852
+ url: "https://ipapi.co/json/",
1853
+ parse: (d) => geoFrom(d.country_code, d.city)
1854
+ },
1855
+ {
1856
+ // https://ipwho.is/ (devuelve success:false con 200 en errores)
1857
+ url: "https://ipwho.is/",
1858
+ parse: (d) => d.success === false ? null : geoFrom(d.country_code, d.city)
1859
+ },
1860
+ {
1861
+ // https://ipinfo.io/json (country = código ISO)
1862
+ url: "https://ipinfo.io/json",
1863
+ parse: (d) => geoFrom(d.country, d.city)
1864
+ }
1865
+ ];
1866
+ function geoFrom(country, city) {
1867
+ const c = typeof country === "string" && country ? country : void 0;
1868
+ const t = typeof city === "string" && city ? city : void 0;
1869
+ if (!c && !t) return null;
1870
+ return { country: c, city: t };
1871
+ }
1872
+ async function fetchOne(provider, f, timeoutMs) {
1873
+ const controller = new AbortController();
1874
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
1875
+ try {
1876
+ const res = await f(provider.url, { signal: controller.signal });
1877
+ if (!res.ok) return null;
1878
+ const data = await res.json();
1879
+ return provider.parse(data);
1880
+ } catch {
1881
+ return null;
1882
+ } finally {
1883
+ clearTimeout(timer);
1884
+ }
1885
+ }
1886
+ async function fetchGeo(options = {}) {
1887
+ const f = options.fetchImpl ?? (typeof fetch !== "undefined" ? fetch : void 0);
1888
+ if (!f) return null;
1889
+ const providers = options.providers ?? DEFAULT_GEO_PROVIDERS;
1890
+ const timeoutMs = options.timeoutMs ?? GEO_TIMEOUT_MS;
1891
+ for (const provider of providers) {
1892
+ const geo = await fetchOne(provider, f, timeoutMs);
1893
+ if (geo) return geo;
1894
+ }
1895
+ return null;
1896
+ }
1897
+
1898
+ // src/analytics/language.ts
1899
+ function clean(value) {
1900
+ const trimmed = value?.trim();
1901
+ return trimmed ? trimmed : void 0;
1902
+ }
1903
+ function resolveLanguage(sources) {
1904
+ const explicit = clean(sources.explicit);
1905
+ if (explicit) return explicit;
1906
+ const navLang = clean(sources.navigator?.language);
1907
+ if (navLang) return navLang;
1908
+ try {
1909
+ const locale = clean(sources.intl?.DateTimeFormat().resolvedOptions().locale);
1910
+ if (locale) return locale;
1911
+ } catch {
1912
+ }
1913
+ return void 0;
1914
+ }
1915
+
1916
+ // src/analytics/engagement-tracker.ts
1917
+ var EngagementTracker = class {
1918
+ constructor(now = () => Date.now()) {
1919
+ this.activeMs = 0;
1920
+ this.lastResumeAt = null;
1921
+ this.now = now;
1922
+ }
1923
+ /** Reanuda el conteo (pestaña visible / app en foreground). Idempotente. */
1924
+ resume() {
1925
+ if (this.lastResumeAt === null) this.lastResumeAt = this.now();
1926
+ }
1927
+ /** Pausa el conteo (pestaña oculta / app en background), acumulando el tramo activo. */
1928
+ pause() {
1929
+ if (this.lastResumeAt !== null) {
1930
+ this.activeMs += this.now() - this.lastResumeAt;
1931
+ this.lastResumeAt = null;
1932
+ }
1933
+ }
1934
+ /** Devuelve los ms activos acumulados desde la última lectura y reinicia (sin parar el timer). */
1935
+ consume() {
1936
+ if (this.lastResumeAt !== null) {
1937
+ const t = this.now();
1938
+ this.activeMs += t - this.lastResumeAt;
1939
+ this.lastResumeAt = t;
1940
+ }
1941
+ const ms = this.activeMs;
1942
+ this.activeMs = 0;
1943
+ return ms;
1944
+ }
1945
+ isActive() {
1946
+ return this.lastResumeAt !== null;
1947
+ }
1948
+ };
1949
+
1950
+ // src/contact/contact-manager.ts
1951
+ function stableSerialize(userId, attrs) {
1952
+ const sorted = {};
1953
+ for (const key of Object.keys(attrs).sort()) {
1954
+ sorted[key] = attrs[key];
1955
+ }
1956
+ return JSON.stringify({ userId, attributes: sorted });
1957
+ }
1958
+ var ContactManager = class {
1959
+ constructor(options) {
1960
+ this.storage = options.storage;
1961
+ this.publicKey = options.publicKey;
1962
+ this.userId = options.userId;
1963
+ this.post = options.post;
1964
+ }
1965
+ /**
1966
+ * Envía los atributos si cambiaron respecto a lo último enviado. La caché solo se guarda
1967
+ * cuando la API acepta el envío; si falla, la llamada siguiente reintenta. Nunca rechaza.
1968
+ * @returns `true` si se envió, `false` si no hubo cambios o el envío falló.
1969
+ */
1970
+ async setAttributes(attributes) {
1971
+ const serialized = stableSerialize(this.userId, attributes);
1972
+ const last = this.storage.getItem(STORAGE_KEYS.contactAttributes);
1973
+ if (last === serialized) return false;
1974
+ try {
1975
+ await this.post({
1976
+ publicKey: this.publicKey,
1977
+ userId: this.userId,
1978
+ userAttributes: attributes
1979
+ });
1980
+ } catch {
1981
+ return false;
1982
+ }
1983
+ this.storage.setItem(STORAGE_KEYS.contactAttributes, serialized);
1984
+ return true;
1985
+ }
1986
+ };
1987
+
1988
+ // src/analytics/crash-reporter.ts
1989
+ var STACK_MAX = 8e3;
1990
+ var QUEUE_KEY = "deepdots.crash.queue";
1991
+ var MAX_QUEUED = 20;
1992
+ function crashRecordToParams(r) {
1993
+ const params = {
1994
+ crashed_at: r.crashedAt,
1995
+ crash_type: r.crashType,
1996
+ message: r.message,
1997
+ stack: r.stack,
1998
+ fatal: r.fatal,
1999
+ handled: r.handled,
2000
+ severity: r.severity
2001
+ };
2002
+ if (r.sessionId) params.crashed_session_id = r.sessionId;
2003
+ if (r.appVersion) params.crashed_app_version = r.appVersion;
2004
+ if (r.osVersion) params.crashed_os_version = r.osVersion;
2005
+ if (r.deviceModel) params.crashed_device_model = r.deviceModel;
2006
+ if (r.context) {
2007
+ for (const [k, v] of Object.entries(r.context)) params[`ctx_${k}`] = v;
2008
+ }
2009
+ return params;
2010
+ }
2011
+ var CrashReporter = class {
2012
+ constructor(options) {
2013
+ /** Los handlers de `window` ya están puestos: `install()` es idempotente. */
2014
+ this.windowInstalled = false;
2015
+ /** ErrorUtils ya enganchados: engancharlos dos veces capturaría cada error dos veces. */
2016
+ this.hookedErrorUtils = /* @__PURE__ */ new Set();
2017
+ this.options = options;
2018
+ this.now = options.now ?? (() => Date.now());
2019
+ }
2020
+ isEnabled() {
2021
+ return this.options.enabled ? this.options.enabled() : true;
2022
+ }
2023
+ /** Construye un CrashRecord capturando contexto en el momento del crash. */
2024
+ buildRecord(error, severity, handled, fatal, context) {
2025
+ const err = error;
2026
+ const isErr = error instanceof Error;
2027
+ const dev = this.options.device();
2028
+ const ctx = context ? Object.fromEntries(Object.entries(context).map(([k, v]) => [k, String(v)])) : void 0;
2029
+ return {
2030
+ crashedAt: this.now(),
2031
+ crashType: isErr && err.name || "Error",
2032
+ message: isErr ? String(err.message ?? "") : String(error),
2033
+ stack: (isErr && typeof err.stack === "string" ? err.stack : "").slice(0, STACK_MAX),
2034
+ fatal,
2035
+ handled,
2036
+ severity,
2037
+ sessionId: this.options.sessionId(),
2038
+ appVersion: dev.appVersion,
2039
+ osVersion: dev.osVersion,
2040
+ deviceModel: dev.deviceModel,
2041
+ context: ctx
2042
+ };
2043
+ }
2044
+ /** API pública del host: reporta un error (app viva) → emite el evento ya. */
2045
+ reportError(error, options = {}) {
2046
+ if (!this.isEnabled()) return;
2047
+ const severity = options.severity ?? "error";
2048
+ const handled = options.handled ?? true;
2049
+ const fatal = severity === "fatal";
2050
+ const record = this.buildRecord(error, severity, handled, fatal, options.context);
2051
+ this.options.emit(crashRecordToParams(record));
2052
+ }
2053
+ /** Captura un error no manejado (fatal) → persiste a disco para replay en el siguiente arranque. */
2054
+ captureUnhandled(error) {
2055
+ this.persist(this.buildRecord(error, "fatal", false, true));
2056
+ }
2057
+ /** Persiste un crash no capturado a disco para reenviarlo en el siguiente arranque. */
2058
+ persist(record) {
2059
+ let queue = [];
2060
+ try {
2061
+ const raw = this.options.storage.getItem(QUEUE_KEY);
2062
+ if (raw) queue = JSON.parse(raw);
2063
+ if (!Array.isArray(queue)) queue = [];
2064
+ } catch {
2065
+ queue = [];
2066
+ }
2067
+ queue.push(record);
2068
+ if (queue.length > MAX_QUEUED) queue = queue.slice(queue.length - MAX_QUEUED);
2069
+ try {
2070
+ this.options.storage.setItem(QUEUE_KEY, JSON.stringify(queue));
2071
+ } catch {
2072
+ }
2073
+ }
2074
+ /** Lee y vacía la cola de crashes pendientes (llamado en init para el replay). */
2075
+ drainPendingCrashes() {
2076
+ let queue = [];
2077
+ try {
2078
+ const raw = this.options.storage.getItem(QUEUE_KEY);
2079
+ if (raw) queue = JSON.parse(raw);
2080
+ if (!Array.isArray(queue)) queue = [];
2081
+ } catch {
2082
+ queue = [];
2083
+ }
2084
+ if (queue.length) {
2085
+ try {
2086
+ this.options.storage.removeItem(QUEUE_KEY);
2087
+ } catch {
2088
+ }
2089
+ }
2090
+ return queue;
2091
+ }
2092
+ /** Instala los handlers globales de errores no capturados (no-op sin `window`). Idempotente. */
2093
+ install() {
2094
+ if (this.windowInstalled) return;
2095
+ if (typeof window === "undefined" || typeof window.addEventListener !== "function") return;
2096
+ this.windowInstalled = true;
2097
+ window.addEventListener("error", (e) => {
2098
+ if (!this.isEnabled()) return;
2099
+ this.captureUnhandled(e.error ?? e.message ?? "error");
2100
+ });
2101
+ window.addEventListener("unhandledrejection", (e) => {
2102
+ if (!this.isEnabled()) return;
2103
+ this.captureUnhandled(e.reason ?? "unhandledrejection");
2104
+ });
2105
+ }
2106
+ /** Engancha `global.ErrorUtils` de RN (no hay `window`): persiste y encadena al handler previo. Idempotente por instancia de ErrorUtils. */
2107
+ installReactNative(errorUtils) {
2108
+ if (this.hookedErrorUtils.has(errorUtils)) return;
2109
+ this.hookedErrorUtils.add(errorUtils);
2110
+ const previous = errorUtils.getGlobalHandler?.();
2111
+ errorUtils.setGlobalHandler((error, isFatal) => {
2112
+ if (this.isEnabled()) this.captureUnhandled(error);
2113
+ previous?.(error, isFatal);
2114
+ });
2115
+ }
2116
+ /** @internal Test seam: ejercita el camino de persistencia (window handlers no son testeables en vitest). */
2117
+ _persistForTest(error) {
2118
+ this.captureUnhandled(error);
2119
+ }
2120
+ };
2121
+
2122
+ // src/core/popup-state-store.ts
2123
+ var POPUP_STATE_STORAGE_KEY = "deepdots.popups.state";
2124
+ var MAX_TRACKED_POPUP_ENTRIES = 200;
2125
+ function emptyState() {
2126
+ return { lastShown: {}, progress: {} };
2127
+ }
2128
+ function isValidTimestamp(value) {
2129
+ return typeof value === "number" && Number.isFinite(value);
2130
+ }
2131
+ function capEntries(entries, timestampOf) {
2132
+ if (entries.length <= MAX_TRACKED_POPUP_ENTRIES) return entries;
2133
+ return [...entries].sort((a, b) => timestampOf(b[1]) - timestampOf(a[1])).slice(0, MAX_TRACKED_POPUP_ENTRIES);
2134
+ }
2135
+ function readPopupState(storage) {
2136
+ let raw = null;
2137
+ try {
2138
+ raw = storage.getItem(POPUP_STATE_STORAGE_KEY);
2139
+ } catch {
2140
+ return emptyState();
2141
+ }
2142
+ if (!raw) return emptyState();
2143
+ let parsed;
2144
+ try {
2145
+ parsed = JSON.parse(raw);
2146
+ } catch {
2147
+ return emptyState();
2148
+ }
2149
+ if (typeof parsed !== "object" || parsed === null) return emptyState();
2150
+ const source = parsed;
2151
+ const state = emptyState();
2152
+ if (typeof source.lastShown === "object" && source.lastShown !== null) {
2153
+ const valid = Object.entries(source.lastShown).filter((entry) => isValidTimestamp(entry[1]));
2154
+ capEntries(valid, (timestamp) => timestamp).forEach(([popupId, timestamp]) => {
2155
+ state.lastShown[popupId] = timestamp;
2156
+ });
2157
+ }
2158
+ if (typeof source.progress === "object" && source.progress !== null) {
2159
+ const valid = Object.entries(source.progress).filter((entry) => {
2160
+ const value = entry[1];
2161
+ if (typeof value !== "object" || value === null) return false;
2162
+ const candidate = value;
2163
+ return POPUP_TRIGGER_CONDITION_STATUSES.includes(candidate.status) && isValidTimestamp(candidate.timestamp);
2164
+ });
2165
+ capEntries(valid, (entry) => entry.timestamp).forEach(([surveyId, entry]) => {
2166
+ state.progress[surveyId] = { status: entry.status, timestamp: entry.timestamp };
2167
+ });
2168
+ }
2169
+ return state;
2170
+ }
2171
+ function writePopupState(storage, state) {
2172
+ const capped = emptyState();
2173
+ capEntries(Object.entries(state.lastShown), (timestamp) => timestamp).forEach(([popupId, timestamp]) => {
2174
+ capped.lastShown[popupId] = timestamp;
2175
+ });
2176
+ capEntries(Object.entries(state.progress), (entry) => entry.timestamp).forEach(([surveyId, entry]) => {
2177
+ capped.progress[surveyId] = entry;
2178
+ });
2179
+ try {
2180
+ storage.setItem(POPUP_STATE_STORAGE_KEY, JSON.stringify(capped));
2181
+ } catch {
2182
+ }
2183
+ }
2184
+ function clearPopupState(storage) {
2185
+ try {
2186
+ storage.removeItem(POPUP_STATE_STORAGE_KEY);
2187
+ } catch {
2188
+ }
2189
+ }
2190
+
2191
+ // src/analytics/messaging.ts
2192
+ var MESSAGE_CHANNELS = ["push", "in_app"];
2193
+ function buildMessageParams(stage, o) {
2194
+ const p = {
2195
+ stage,
2196
+ message_id: o.id,
2197
+ message_title: o.title,
2198
+ channel: o.channel
2199
+ };
2200
+ if (o.campaign) p.campaign = o.campaign;
2201
+ if (o.value !== void 0) p.value = o.value;
2202
+ if (o.currency) p.currency = o.currency;
2203
+ return { ...p, ...o.params ?? {} };
2204
+ }
2205
+ var MAX_TRACKED_MESSAGES = 500;
2206
+ var MessageGuard = class {
2207
+ constructor(maxTrackedMessages = MAX_TRACKED_MESSAGES) {
2208
+ this.maxTrackedMessages = maxTrackedMessages;
2209
+ /** message_id → canal fijado + stages ya emitidos. El orden de inserción marca la eviction. */
2210
+ this.seen = /* @__PURE__ */ new Map();
2211
+ }
2212
+ evaluate(stage, options) {
2213
+ const channel = options.channel;
2214
+ if (!MESSAGE_CHANNELS.includes(channel)) {
2215
+ return {
2216
+ emit: false,
2217
+ reason: "invalid_channel",
2218
+ detail: `invalid channel "${channel}" (expected ${MESSAGE_CHANNELS.join(" | ")})`
2219
+ };
2220
+ }
2221
+ const entry = this.seen.get(options.id);
2222
+ if (!entry) {
2223
+ this.remember(options.id, channel, stage);
2224
+ return { emit: true };
2225
+ }
2226
+ if (entry.channel !== channel) {
2227
+ return {
2228
+ emit: false,
2229
+ reason: "channel_conflict",
2230
+ detail: `message_id "${options.id}" was already reported on channel "${entry.channel}"; discarding "${channel}"`
2231
+ };
2232
+ }
2233
+ if (entry.stages.has(stage)) {
2234
+ return {
2235
+ emit: false,
2236
+ reason: "duplicate_stage",
2237
+ detail: `stage "${stage}" was already sent for message_id "${options.id}"`
2238
+ };
2239
+ }
2240
+ entry.stages.add(stage);
2241
+ return { emit: true };
2242
+ }
2243
+ /** Olvida todo lo vigilado (nueva sesión). */
2244
+ reset() {
2245
+ this.seen.clear();
2246
+ }
2247
+ remember(id, channel, stage) {
2248
+ this.seen.set(id, { channel, stages: /* @__PURE__ */ new Set([stage]) });
2249
+ while (this.seen.size > this.maxTrackedMessages) {
2250
+ const oldest = this.seen.keys().next();
2251
+ if (oldest.done) break;
2252
+ this.seen.delete(oldest.value);
2253
+ }
2254
+ }
2255
+ };
2256
+
2257
+ // src/core/deepdots-popups.ts
2258
+ var EXIT_QUEUE_STORAGE_KEY = "__deepdots_exit_popup_queue__";
2259
+ var DAY_IN_MS = 24 * 60 * 60 * 1e3;
2260
+ var ANALYTICS_MAX_BATCH_SIZE = 20;
2261
+ var ANALYTICS_FLUSH_INTERVAL_MS = 3e4;
2262
+ var ANALYTICS_HEARTBEAT_MS = 5 * 6e4;
2263
+ var ANALYTICS_SESSION_TIMEOUT_MS = 30 * 6e4;
2264
+ var ANALYTICS_SERVER_IDLE_MS = 60 * 6e4;
2265
+ var ANALYTICS_SESSION_DISCARD_MS = ANALYTICS_SERVER_IDLE_MS - 10 * 6e4;
2266
+ var ANALYTICS_RESUME_WINDOW_MS = 6e4;
2267
+ var RESERVED_EVENT_PREFIX = "deepdots_";
2268
+ var CUSTOM_EVENT_PREFIX = "deepdots_event_";
2269
+ var MAX_PENDING_TRIGGERS = 20;
2270
+ function triggerDelayMs(delaySeconds) {
2271
+ const n = typeof delaySeconds === "number" ? delaySeconds : Number(delaySeconds);
2272
+ return Number.isFinite(n) && n > 0 ? Math.round(n * 1e3) : 0;
2273
+ }
2274
+ var DeepdotsPopups = class {
2275
+ constructor() {
2276
+ this.config = null;
2277
+ this.listeners = /* @__PURE__ */ new Map();
2278
+ this.triggers = [];
2279
+ this.initialized = false;
2280
+ this.renderer = createDefaultRenderer();
2281
+ /** Logger para el output de debug. Default `console`; el host puede inyectar el suyo en init(). */
2282
+ this.logger = console;
2283
+ this.popupDefinitions = [];
2284
+ this.popupsLoaded = false;
2285
+ /**
2286
+ * `true` mientras el `GET /sdk/{apiKey}/popups` de `init()` está en vuelo. En esa ventana los
2287
+ * disparos del host (`triggerEvent`, `triggerSurvey`) no tienen contra qué evaluarse, así que
2288
+ * se guardan en `pendingTriggers` y se reproducen al cargar. Click, scroll, time y exit no
2289
+ * hacen falta: son listeners que `autoLaunch` instala ya con las definiciones cargadas.
2290
+ */
2291
+ this.awaitingPopups = false;
2292
+ this.pendingTriggers = [];
2293
+ this.pendingAutoLaunch = false;
2294
+ // Estado que alimenta las reglas de redisplay. Copia de trabajo en memoria; la fuente
2295
+ // duradera es el storage (`popup-state-store`), rehidratada en `init()` — sin eso, una
2296
+ // recarga reiniciaba el cooldown y el popup volvía a salir. `answeredSurveys` se deriva
2297
+ // de las entradas COMPLETED de `surveyProgress` (los dos los escribe `markSurveyAnswered`).
2298
+ this.answeredSurveys = /* @__PURE__ */ new Set();
2299
+ this.surveyProgress = /* @__PURE__ */ new Map();
2300
+ this.lastShown = /* @__PURE__ */ new Map();
2301
+ // popupId -> timestamp mostrado
2302
+ this.surveyToPopupId = /* @__PURE__ */ new Map();
2303
+ // surveyId -> popupId
2304
+ this.deferredExitTimers = [];
2305
+ /** Popups esperando su `delaySeconds` (uno por popup). */
2306
+ this.delayedPopups = /* @__PURE__ */ new Map();
2307
+ /** Última pantalla de `setScreen` (React Native). */
2308
+ this.currentScreen = null;
2309
+ this.baseUrl = "";
2310
+ this.env = "production";
2311
+ /** Si el SDK pinta el "modal" del popup (RN). Default true; false = el host lo envuelve. */
2312
+ this.renderChrome = true;
2313
+ /** Barra de progreso. undefined = la decide la plataforma (style.showProgressBar). */
2314
+ this.showProgressBar = void 0;
2315
+ /** CSS del host inyectado al final de los estilos del popup. */
2316
+ this.surveyCss = void 0;
2317
+ this.cspNonce = void 0;
2318
+ /** Identidad + sesión (Fase 1 tracking). Null hasta init(). */
2319
+ this.tracking = null;
2320
+ /** Capa de analytics (canal separado del feedback). Null hasta init(). */
2321
+ this.analytics = null;
2322
+ /** feedbackSessionId cacheado del canal de analytics (devuelto por POST /sdk/feedback). */
2323
+ this.analyticsFeedbackSessionId = void 0;
2324
+ /** `init({ onFeedbackSession })`: avisa al host al abrir y cerrar cada registro. */
2325
+ this.onFeedbackSession = void 0;
2326
+ /** Timer del flush periódico de analytics (cada ANALYTICS_FLUSH_INTERVAL_MS). */
2327
+ this.analyticsFlushTimer = void 0;
2328
+ /** Crash & error reporting (#14–17). Null hasta init(). */
2329
+ this.crashReporter = null;
2330
+ /** ErrorUtils de RN recibido del host (o del Provider); se engancha en cuanto haya consentimiento. */
2331
+ this.rnErrorUtils = null;
2332
+ /** Protecciones del funnel de Messaging (#18–22). Vigencia de sesión: se reinicia en init(). */
2333
+ this.messageGuard = new MessageGuard();
2334
+ /** Observador de navegación (Fase 2): emite page_view por el canal de analytics. */
2335
+ this.navObserver = null;
2336
+ /** Tiempo activo (engagement time, #8). */
2337
+ this.engagement = null;
2338
+ /** Atributos internos del usuario identificado → POST /sdk/popups/contact. Null si no hay userId. */
2339
+ this.contact = null;
2340
+ /** Storage resuelto en init() (inyectado por el host o localStorage). Reusado al cambiar de usuario. */
2341
+ this.storage = null;
2342
+ /** Marca si ya se inició la navegación manual (setScreen) — para RN sin History API. */
2343
+ this.navStarted = false;
2344
+ /**
2345
+ * `true` entre `session_start` y `session_end`. Hace idempotente tanto la apertura como
2346
+ * el cierre (p. ej. `visibilitychange` + `pagehide` seguidos) y permite abrir una sesión
2347
+ * nueva al volver a foreground o al conceder el consentimiento más tarde.
2348
+ */
2349
+ this.sessionOpen = false;
2350
+ /** Último `user_engagement` emitido (ms epoch): marca el latido. */
2351
+ this.lastEngagementAt = 0;
2352
+ /** Cuándo se ocultó la pestaña por última vez (ms epoch); null si está visible. */
2353
+ this.hiddenAt = null;
2354
+ /** Suscripción automática a AppState (React Native, `autoTrack.lifecycle`). */
2355
+ this.appStateSubscription = void 0;
2356
+ /**
2357
+ * Sesión suspendida por un `pagehide` (ms epoch y `deepdots_user_id`); null si no hay.
2358
+ * `openSession` la reanuda si sigue a tiempo (ver ANALYTICS_RESUME_WINDOW_MS).
2359
+ */
2360
+ this.suspended = null;
2361
+ /** Integración de analytics del init: la sesión suspendida solo la hereda la misma. */
2362
+ this.analyticsIntegration = void 0;
2363
+ /**
2364
+ * Idioma resuelto en init() (explícito > navigator.language > Intl). Única fuente de
2365
+ * verdad para el context de analytics Y para la segmentación por idioma de los popups.
2366
+ */
2367
+ this.language = void 0;
2368
+ /** `geolocation` del init: si es false no se usa ni la caché ni el lookup. */
2369
+ this.geoEnabled = true;
2370
+ /** Solo se consulta a terceros si el país/ciudad se va a enviar (analytics configurado). */
2371
+ this.geoWanted = false;
2372
+ /** Evita más de un lookup por instancia (el consentimiento puede ir y venir). */
2373
+ this.geoLookupStarted = false;
2374
+ }
2375
+ /** Initialize the SDK with configuration */
2376
+ init(config) {
2377
+ this.logger = config.logger ?? console;
2378
+ setLogger(this.logger);
2379
+ if (this.initialized) {
2380
+ const nextUserId = config.userId || void 0;
2381
+ if (nextUserId !== this.config?.userId) {
2382
+ this.setUserId(nextUserId);
2383
+ return;
2384
+ }
2385
+ this.log("SDK already initialized");
2386
+ return;
2387
+ }
2388
+ const rn = getReactNativePlatform();
2389
+ if (!config.platform && (rn?.os === "ios" || rn?.os === "android")) {
2390
+ config = { ...config, platform: rn.os };
2391
+ }
2392
+ const env = resolveEnvironment(config.nodeEnv);
2393
+ this.baseUrl = env.apiBaseUrl;
2394
+ this.env = config.nodeEnv || "production";
2395
+ this.renderChrome = config.renderChrome ?? true;
2396
+ this.showProgressBar = config.showProgressBar;
2397
+ this.surveyCss = config.surveyCss;
2398
+ this.cspNonce = config.cspNonce;
2399
+ this.onFeedbackSession = config.onFeedbackSession;
2400
+ this.config = {
2401
+ apiKey: config.apiKey || void 0,
2402
+ debug: config.debug || false,
2403
+ userId: config.userId || void 0
2404
+ };
2405
+ const storage = config.storage ?? createDefaultStorage();
2406
+ this.storage = storage;
2407
+ this.loadPopupState(storage);
2408
+ this.tracking = new TrackingManager({
2409
+ storage,
2410
+ clientUserId: this.config.userId,
2411
+ enabled: config.trackingEnabled ?? true
2412
+ });
2413
+ if (this.config.userId) {
2414
+ const userId = this.config.userId;
2415
+ const publicKey = this.config.apiKey ?? "";
2416
+ this.contact = new ContactManager({
2417
+ storage,
2418
+ publicKey,
2419
+ userId,
2420
+ post: (body) => this.postContact(body)
2421
+ });
2422
+ if (config.contactAttributes) {
2423
+ void this.setContactAttributes(config.contactAttributes);
2424
+ }
2425
+ }
2426
+ this.log("tracking \xB7 user_id:", this.tracking.getUserId(), "\xB7 new_user:", this.tracking.isNewUser(), "\xB7 enabled:", this.tracking.isTrackingEnabled());
2427
+ this.analyticsIntegration = config.analytics?.integration;
2428
+ const resumable = this.readResumableSession();
2429
+ if (resumable) {
2430
+ this.analyticsFeedbackSessionId = resumable.sessionId;
2431
+ this.suspended = { at: resumable.at, userId: resumable.userId };
2432
+ }
2433
+ const analyticsSink = config.analytics ? createFeedbackSink({
2434
+ baseUrl: this.baseUrl,
2435
+ keys: config.analytics,
2436
+ log: (...a) => this.log(...a),
2437
+ initialSessionId: resumable?.sessionId,
2438
+ // En móvil (RN) la app puede morir con el lote de cierre sin entregar: se
2439
+ // persiste y se reenvía en el arranque siguiente. En web el cierre sale con
2440
+ // `keepalive` y varias pestañas compartirían el mismo storage.
2441
+ storage: (config.platform ?? "web") !== "web" ? storage : void 0,
2442
+ // iOS suspende la app con el POST de cierre en vuelo: el host puede darle
2443
+ // tiempo de background (DD-55). El reenvío del arranque siguiente sigue igual.
2444
+ // La del host o, en iOS, la del módulo nativo del paquete (autolinking).
2445
+ backgroundTask: resolveBackgroundTask(config.backgroundTask, rn),
2446
+ onSessionId: (id) => {
2447
+ this.analyticsFeedbackSessionId = id;
2448
+ this.notifyFeedbackSession(id, "open");
2449
+ },
2450
+ onSessionClosed: (id) => this.notifyFeedbackSession(id, "closed"),
2451
+ onSessionReset: () => {
2452
+ this.analyticsFeedbackSessionId = void 0;
2453
+ }
2454
+ }) : createDryRunSink((...a) => {
2455
+ if (this.config?.debug) this.logger.log(...a);
2456
+ });
2457
+ const device = config.device ?? collectDeviceInfo(config.appVersion);
2458
+ this.language = resolveLanguage({
2459
+ explicit: config.language,
2460
+ navigator: typeof navigator !== "undefined" ? navigator : void 0,
2461
+ intl: typeof Intl !== "undefined" ? Intl : void 0
2462
+ });
2463
+ this.messageGuard.reset();
2464
+ this.analytics = new AnalyticsManager({
2465
+ sink: analyticsSink,
2466
+ publicKey: config.analytics?.publicKey ?? this.config.apiKey,
2467
+ language: this.language,
2468
+ platform: config.platform ?? "web",
2469
+ device,
2470
+ maxBatchSize: ANALYTICS_MAX_BATCH_SIZE,
2471
+ onFlushNeeded: () => this.flushAnalytics()
2472
+ });
2473
+ this.crashReporter = new CrashReporter({
2474
+ storage,
2475
+ emit: (params) => this.track("deepdots_app_crash", params),
2476
+ device: () => ({ appVersion: device.app_version, osVersion: device.os_version, deviceModel: device.device_model }),
2477
+ sessionId: () => this.tracking?.getSessionId() ?? null,
2478
+ now: () => Date.now(),
2479
+ enabled: () => this.tracking?.isTrackingEnabled() ?? false
2480
+ });
2481
+ this.installCrashHandlers();
2482
+ this.geoEnabled = config.geolocation ?? true;
2483
+ this.geoWanted = this.geoEnabled && !!config.analytics;
2484
+ this.resolveGeo();
2485
+ this.navObserver = new NavigationObserver();
2486
+ this.navObserver.onVisit(
2487
+ (v) => this.track("deepdots_page_view", { screen: v.screen, path: v.path, duration_seconds: v.durationSeconds })
2488
+ );
2489
+ this.navObserver.install();
2490
+ this.engagement = new EngagementTracker();
2491
+ this.setupAnalyticsFlush();
2492
+ this.openSession("cold_start");
2493
+ if (resumable && this.analyticsFeedbackSessionId === resumable.sessionId) {
2494
+ this.notifyFeedbackSession(resumable.sessionId, "open");
2495
+ }
2496
+ const pendingCrashes = this.crashReporter.drainPendingCrashes();
2497
+ if (this.tracking?.isTrackingEnabled()) {
2498
+ for (const rec of pendingCrashes) {
2499
+ this.track("deepdots_app_crash", crashRecordToParams(rec));
2500
+ }
2501
+ }
2502
+ this.initialized = true;
2503
+ this.installAutoLifecycle(rn, config);
2504
+ this.log("SDK initialized", this.config);
2505
+ if (this.renderer.init) this.renderer.init();
2506
+ this.awaitingPopups = Boolean(this.config.apiKey && this.baseUrl);
2507
+ this.fetchPopupsFromServer().then((defs) => {
2508
+ if (!defs) this.dropPendingTriggers();
2509
+ this.popupDefinitions = this.validatePopupDefinitions(defs ?? []);
2510
+ this.popupsLoaded = true;
2511
+ this.log("Popups loaded from API", this.popupDefinitions);
2512
+ if (this.popupDefinitions.length) this.renderer.preload?.();
2513
+ this.configureTriggersFromDefinitions();
2514
+ this.processDeferredExitQueue();
2515
+ if (this.pendingAutoLaunch) {
2516
+ this.startTriggers();
2517
+ }
2518
+ this.replayPendingTriggers();
2519
+ });
2520
+ }
2521
+ /** User id actual (generado por el SDK o provisto por el cliente). Null si tracking off. */
2522
+ getUserId() {
2523
+ return this.tracking?.getUserId() ?? null;
2524
+ }
2525
+ /** Session id de navegación actual. Null si tracking off. */
2526
+ getSessionId() {
2527
+ return this.tracking?.getSessionId() ?? null;
2528
+ }
2529
+ /**
2530
+ * Id del registro de analytics abierto: el `sessionId` que devolvió `POST /sdk/feedback`,
2531
+ * que la API guarda como `sdkSessionId` en el Feedback en que se convierte la sesión. No es
2532
+ * `getSessionId()`. Null hasta que el backend acepta el primer lote y de nuevo al cerrar la
2533
+ * sesión: para saber también qué registro se cerró, usa `init({ onFeedbackSession })`.
2534
+ */
2535
+ getFeedbackSessionId() {
2536
+ return this.analyticsFeedbackSessionId ?? null;
2537
+ }
2538
+ /** Avisa al host del registro abierto o cerrado; un fallo del host no corta el envío. */
2539
+ notifyFeedbackSession(sessionId, status) {
2540
+ try {
2541
+ this.onFeedbackSession?.({ sessionId, status });
2542
+ } catch (error) {
2543
+ this.log("analytics \xB7 onFeedbackSession threw:", error);
2544
+ }
2545
+ }
2546
+ /** Activa/desactiva el tracking (identidad + sesión + analytics). Kill-switch del contrato §7bis. */
2547
+ setTrackingEnabled(enabled) {
2548
+ if (!enabled) this.closeSession("tracking_disabled");
2549
+ this.tracking?.setTrackingEnabled(enabled);
2550
+ if (enabled) this.openSession("tracking_enabled");
2551
+ if (enabled) this.installCrashHandlers();
2552
+ if (enabled) this.resolveGeo();
2553
+ this.log("tracking \xB7 setTrackingEnabled:", enabled, "\xB7 session_id:", this.tracking?.getSessionId() ?? null);
2554
+ }
2555
+ // ───────── Analytics (canal separado del feedback, vinculado por user_id) ─────────
2556
+ /** Registra un evento de analítica (modelo GA: nombre + params). No-op si tracking off. */
2557
+ track(name, params) {
2558
+ if (!this.tracking?.isTrackingEnabled()) return;
2559
+ const eventName = name.startsWith(RESERVED_EVENT_PREFIX) ? name : `${CUSTOM_EVENT_PREFIX}${name}`;
2560
+ this.analytics?.track(eventName, params);
2561
+ this.log("analytics \xB7 track:", eventName, params ?? {});
2562
+ }
2563
+ /** User attributes para breakdowns (registration_status, pass_type, sector, pass_status…). */
2564
+ setUserAttributes(attributes) {
2565
+ if (!this.tracking?.isTrackingEnabled()) return;
2566
+ this.analytics?.setUserAttributes(attributes);
2567
+ }
2568
+ /**
2569
+ * Registra/actualiza una métrica (valor medible) → `feedback.metrics` del body.
2570
+ * Persistente y sobrescribe por key. No-op si tracking off.
2571
+ */
2572
+ setMetric(key, value) {
2573
+ if (!this.tracking?.isTrackingEnabled()) return;
2574
+ this.analytics?.setMetric(key, value);
2575
+ this.log("analytics \xB7 setMetric:", key, value);
2576
+ }
2577
+ /** Reporta un error del host (manejado o no) → evento `deepdots_app_crash`. No-op si tracking off. */
2578
+ reportError(error, options) {
2579
+ if (!this.tracking?.isTrackingEnabled()) return;
2580
+ this.crashReporter?.reportError(error, options);
2581
+ }
2582
+ /**
2583
+ * Engancha `global.ErrorUtils` de RN para capturar errores JS no manejados. Con tracking off
2584
+ * se recuerda y se engancha cuando se conceda el consentimiento (`setTrackingEnabled(true)`).
2585
+ */
2586
+ installReactNativeCrashHandler(errorUtils) {
2587
+ this.rnErrorUtils = errorUtils;
2588
+ this.installCrashHandlers();
2589
+ }
2590
+ /**
2591
+ * Pone los handlers de errores no capturados: `window` en web y `ErrorUtils` en RN (el que
2592
+ * pasó el host o, si no pasó ninguno, `globalThis.ErrorUtils`, para que un `init()` sin
2593
+ * `setupReactNative` también capture). Solo con consentimiento; idempotente, así que se
2594
+ * llama en `init()` y cada vez que se activa el tracking.
2595
+ */
2596
+ installCrashHandlers() {
2597
+ if (!this.crashReporter || !this.tracking?.isTrackingEnabled()) return;
2598
+ this.crashReporter.install();
2599
+ const errorUtils = this.rnErrorUtils ?? globalThis.ErrorUtils;
2600
+ if (errorUtils && typeof errorUtils.setGlobalHandler === "function") {
2601
+ this.crashReporter.installReactNative(errorUtils);
2602
+ }
2603
+ }
2604
+ /**
2605
+ * Info interna del usuario que solo conoce el host (idioma, edad, plan…), persistida en el
2606
+ * Contact del backend para segmentación/targeting de popups. Identificada por el `userId` del
2607
+ * init. Solo envía si los atributos cambiaron (diff en storage). No-op si tracking off o sin userId.
2608
+ * @returns `true` si se envió al backend, `false` si no hubo cambios o está deshabilitado.
2609
+ */
2610
+ async setContactAttributes(attributes) {
2611
+ if (!this.tracking?.isTrackingEnabled()) return false;
2612
+ if (!this.contact) return false;
2613
+ return this.contact.setAttributes(attributes);
2614
+ }
2615
+ /** Marca el inicio de un mini-service; etiqueta los eventos siguientes. No-op si tracking off. */
2616
+ enterMiniService(name, entryPointType) {
2617
+ if (!this.tracking?.isTrackingEnabled()) return;
2618
+ this.analytics?.enterMiniService(name, entryPointType);
2619
+ this.log("analytics \xB7 enterMiniService:", name, entryPointType ?? "");
2620
+ }
2621
+ /** Cierra el mini-service `name` (emite `mini_service_exit` con duración, #27). No-op si tracking off o si ese no está activo. */
2622
+ exitMiniService(name) {
2623
+ if (!this.tracking?.isTrackingEnabled()) return;
2624
+ this.analytics?.exitMiniService(name);
2625
+ this.log("analytics \xB7 exitMiniService:", name);
2626
+ }
2627
+ /** Findability (#31/#35): registra una búsqueda. `has_results` se deriva de `resultsCount`. */
2628
+ trackSearch(query, resultsCount, params) {
2629
+ this.track("deepdots_search", { query, results_count: resultsCount, has_results: resultsCount > 0, ...params ?? {} });
2630
+ }
2631
+ /** Findability friction (#34/#35): señal de fricción con su `friction_topic`. */
2632
+ trackFindabilityFriction(frictionTopic, params) {
2633
+ this.track("deepdots_findability_friction", { friction_topic: frictionTopic, ...params ?? {} });
2634
+ }
2635
+ /** Funnel: un paso del embudo, correlacionado por `taskId`. El backend reconstruye conversión/drop-off/tiempo. */
2636
+ trackFunnelStep(funnel, step, taskId, params) {
2637
+ this.track("deepdots_funnel_step", { funnel, step, task_id: taskId, ...params ?? {} });
2638
+ }
2639
+ /**
2640
+ * Product Effectiveness: una interacción significativa del usuario (`interaction_type` es la
2641
+ * dimensión de agrupación, p. ej. `get_help`, `homepage`, `contact_support`).
2642
+ *
2643
+ * Existe como evento RESERVADO para que la convención no la invente cada host: un `track()`
2644
+ * custom acaba como `deepdots_event_…` y no lo cuenta la analítica de effectiveness.
2645
+ * Un `interactionType` vacío se descarta con warning (no aporta dato agrupable).
2646
+ */
2647
+ trackMeaningfulInteraction(interactionType, params) {
2648
+ const type = typeof interactionType === "string" ? interactionType.trim() : "";
2649
+ if (!type) {
2650
+ console.warn("[DeepdotsPopups] trackMeaningfulInteraction discarded: empty interaction_type");
2651
+ return;
2652
+ }
2653
+ this.track("deepdots_meaningful_interaction", { interaction_type: type, ...params ?? {} });
2654
+ }
2655
+ /**
2656
+ * Messaging (#18–22): registra una etapa del funnel de una notificación (push/in-app).
2657
+ * No-op si tracking off. El evento se descarta (con warning) si el `channel` no es válido,
2658
+ * si ese `(message_id, stage)` ya se emitió en la sesión, o si el `message_id` ya se reportó
2659
+ * en otro canal — ver `MessageGuard`.
2660
+ */
2661
+ trackMessage(stage, options) {
2662
+ const verdict = this.messageGuard.evaluate(stage, options);
2663
+ if (!verdict.emit) {
2664
+ console.warn(`[DeepdotsPopups] trackMessage discarded (${verdict.reason}): ${verdict.detail}`);
2665
+ return;
2666
+ }
2667
+ this.track("deepdots_message", buildMessageParams(stage, options));
2668
+ }
2669
+ /**
2670
+ * Navegación MANUAL (entornos sin History API, p. ej. React Native con React Navigation).
2671
+ * El host la llama en cada cambio de pantalla; emite `page_view` al salir de la anterior.
2672
+ */
2673
+ setScreen(name) {
2674
+ const screen2 = typeof name === "string" ? name.trim() : "";
2675
+ if (screen2) {
2676
+ this.cancelDelayedPopups("screen change", (entry) => entry.screen !== screen2);
2677
+ this.currentScreen = screen2;
2678
+ }
2679
+ if (!this.navObserver) return;
2680
+ if (!this.navStarted) {
2681
+ this.navObserver.begin(name);
2682
+ this.navStarted = true;
2683
+ } else {
2684
+ this.navObserver.visit(name);
2685
+ }
2686
+ }
2687
+ /** App a foreground (RN: AppState 'active'): reanuda el engagement time y abre sesión nueva. */
2688
+ onForeground() {
2689
+ this.engagement?.resume();
2690
+ this.openSession("foreground");
2691
+ }
2692
+ /**
2693
+ * App a background (RN: AppState 'background'): FIN DE SESIÓN. Cierra pantalla actual
2694
+ * (page_view), mini-services (mini_service_exit), emite engagement + `session_end` y
2695
+ * envía el último lote con `completed:true`.
2696
+ *
2697
+ * Es la única señal disponible en móvil: el kill de la app (swipe) NO da callback.
2698
+ */
2699
+ onBackground() {
2700
+ this.cancelDelayedPopups("app to background");
2701
+ this.closeSession("background");
2702
+ this.engagement?.pause();
2703
+ }
2704
+ /**
2705
+ * App a `inactive` (RN, iOS: centro de control, llamada, app switcher, y SIEMPRE justo antes
2706
+ * de `background`). NO cierra la sesión (es transitorio), pero envía lo acumulado con un
2707
+ * `user_engagement` que lleva la pantalla en curso, como web al ocultar la pestaña: si el
2708
+ * lote de cierre de `background` no llega a salir (iOS suspende la app), el backend ya
2709
+ * tiene el tiempo activo y la última pantalla. El contador sigue en marcha.
2710
+ */
2711
+ onInactive() {
2712
+ if (this.sessionOpen) this.flushEngagement();
2713
+ this.flushAnalytics();
2714
+ }
2715
+ /**
2716
+ * Ciclo de vida automático en React Native (contrato de detección automática): el SDK escucha
2717
+ * AppState él mismo, así que el host no tiene que llamar a `onForeground`/`onInactive`/
2718
+ * `onBackground`. Si el host los llama además (integraciones anteriores), no se duplica nada:
2719
+ * abrir o cerrar una sesión ya abierta o cerrada no hace nada, y el engagement se consume.
2720
+ * `autoTrack.lifecycle: false` lo apaga.
2721
+ */
2722
+ installAutoLifecycle(rn, config) {
2723
+ if (config.autoTrack?.lifecycle === false) return;
2724
+ const appState = rn?.appState;
2725
+ if (!appState || typeof appState.addEventListener !== "function" || this.appStateSubscription) return;
2726
+ try {
2727
+ this.appStateSubscription = appState.addEventListener("change", (state) => {
2728
+ if (state === "active") this.onForeground();
2729
+ else if (state === "background") this.onBackground();
2730
+ else this.onInactive();
2731
+ });
2732
+ this.log("lifecycle \xB7 AppState wired automatically");
2733
+ } catch {
2734
+ }
2735
+ }
2736
+ /**
2737
+ * Cierre EXPLÍCITO de la sesión por parte del host (logout, fin de flujo…): emite
2738
+ * `session_end` y envía el último lote con `completed:true`.
2739
+ */
2740
+ endSession() {
2741
+ this.closeSession("manual");
2742
+ }
2743
+ /**
2744
+ * Cambio de usuario (login / logout / cambio de cuenta). Cierra la sesión del usuario
2745
+ * anterior (`session_end` con `reason: 'user_change'` + `completed:true`), cambia la
2746
+ * identidad y abre una sesión nueva. Sin `userId` vuelve al id anónimo del SDK.
2747
+ *
2748
+ * Equivale a llamar a `init()` otra vez con otro `userId`.
2749
+ */
2750
+ setUserId(userId) {
2751
+ const next = userId || void 0;
2752
+ if (!this.initialized || !this.config || next === this.config.userId) return;
2753
+ this.closeSession("user_change");
2754
+ const enabled = this.tracking?.isTrackingEnabled() ?? true;
2755
+ const storage = this.storage ?? createDefaultStorage();
2756
+ this.config.userId = next;
2757
+ this.tracking = new TrackingManager({ storage, clientUserId: next, enabled });
2758
+ this.contact = next ? new ContactManager({
2759
+ storage,
2760
+ publicKey: this.config.apiKey ?? "",
2761
+ userId: next,
2762
+ post: (body) => this.postContact(body)
2763
+ }) : null;
2764
+ this.analytics?.resetUserScope();
2765
+ this.messageGuard.reset();
2766
+ this.lastShown.clear();
2767
+ this.surveyProgress.clear();
2768
+ this.answeredSurveys.clear();
2769
+ clearPopupState(storage);
2770
+ this.log("tracking \xB7 user_change \xB7 user_id:", this.tracking.getUserId());
2771
+ this.openSession("user_change");
2772
+ }
2773
+ /**
2774
+ * Cierra la sesión actual: vuelca todo lo que quedaba abierto y envía el último lote
2775
+ * marcado con `completed:true`, para que el backend cierre el registro. El `sessionId`
2776
+ * cacheado se olvida → el lote siguiente abre un registro nuevo.
2777
+ *
2778
+ * Idempotente: dos cierres seguidos (p. ej. `visibilitychange` + `pagehide`) no duplican
2779
+ * el `session_end`.
2780
+ */
2781
+ closeSession(reason) {
2782
+ if (!this.sessionOpen) return;
2783
+ if (!this.tracking?.isTrackingEnabled()) return;
2784
+ this.sessionOpen = false;
2785
+ this.navObserver?.stop();
2786
+ this.navStarted = false;
2787
+ this.analytics?.exitAllMiniServices();
2788
+ this.flushEngagement();
2789
+ this.engagement?.pause();
2790
+ this.track("deepdots_session_end", { reason });
2791
+ this.flushAnalytics({ final: reason === "page_hide", sessionEnd: true });
2792
+ this.analyticsFeedbackSessionId = void 0;
2793
+ this.tracking?.setSessionId(null);
2794
+ this.log("tracking \xB7 session_end:", reason);
2795
+ }
2796
+ /**
2797
+ * Abre sesión (`session_start`) si no hay una abierta y el tracking está activo. Idempotente.
2798
+ * El `reason` dice por qué empieza (ver `SessionStartReason`):
2799
+ * - `cold_start`: init() (carga de la página / arranque de la app RN).
2800
+ * - `foreground`: onForeground() tras un cierre (RN).
2801
+ * - `tracking_enabled`: setTrackingEnabled(true).
2802
+ * - `user_change`: setUserId() o init() con otro userId.
2803
+ * - `idle_timeout`: la pestaña vuelve a verse tras más de 30 min oculta.
2804
+ * - `bfcache_restore`: vuelta desde la bfcache fuera de la ventana de reanudación.
2805
+ * Si hay una sesión suspendida a tiempo emite `deepdots_session_resume` en su lugar, sin reason.
2806
+ */
2807
+ openSession(reason) {
2808
+ if (this.sessionOpen) return;
2809
+ if (!this.tracking?.isTrackingEnabled()) return;
2810
+ const suspendedMs = this.takeSuspendedSession();
2811
+ this.sessionOpen = true;
2812
+ this.lastEngagementAt = Date.now();
2813
+ if (suspendedMs === null) {
2814
+ this.track("deepdots_session_start", { reason });
2815
+ } else {
2816
+ this.track("deepdots_session_resume", { suspended_ms: suspendedMs });
2817
+ this.log("tracking \xB7 session resumed after", suspendedMs, "ms:", this.analyticsFeedbackSessionId);
2818
+ }
2819
+ this.navObserver?.restart();
2820
+ if (this.isDocumentVisible()) this.engagement?.resume();
2821
+ }
2822
+ /** Web: si la pestaña se ve. Sin `document` (RN) manda AppState vía onForeground/onBackground. */
2823
+ isDocumentVisible() {
2824
+ return typeof document === "undefined" || document.visibilityState !== "hidden";
2825
+ }
2826
+ /** Payload que se ENVIARÍA al endpoint de analytics (no envía ni vacía el buffer). */
2827
+ previewAnalytics() {
2828
+ return this.analytics?.buildPayload(this.analyticsIdentity()) ?? {
2829
+ userId: null,
2830
+ sessionId: null,
2831
+ context: { platform: "web", attributes: {} },
2832
+ events: []
2833
+ };
2834
+ }
2835
+ /**
2836
+ * Envía el lote acumulado de analytics y vacía el buffer.
2837
+ * `final: true` (cierre de página/app): el lote no espera al primer POST en vuelo, porque
2838
+ * el documento se muere; un lote que falle por red o 5xx se re-encola para el siguiente flush.
2839
+ */
2840
+ flushAnalytics(options) {
2841
+ if (!this.tracking?.isTrackingEnabled()) return;
2842
+ this.analytics?.flush(this.analyticsIdentity(), options);
2843
+ }
2844
+ /**
2845
+ * Emite un evento `user_engagement` con el tiempo activo acumulado (#8) y la pantalla en
2846
+ * curso: `screen` y `path` (los mismos que llevará su `page_view`) y `screen_seconds` (lo
2847
+ * que lleva en ella, medido como el `duration_seconds` del `page_view`).
2848
+ *
2849
+ * El `page_view` sale al SALIR de la pantalla; si el cierre no llega nunca (pestaña dormida
2850
+ * y descartada al volver, pestaña o app matada en segundo plano), la última pantalla de la
2851
+ * sesión se perdía y una visita de una sola pantalla se quedaba sin ninguna. Con la pantalla
2852
+ * en el latido y en el engagement de ocultar la pestaña, el backend la reconstruye.
2853
+ *
2854
+ * En los cierres (`closeSession`, `suspendSession`) el observador ya emitió el `page_view`
2855
+ * y no tiene pantalla, así que ese engagement va sin `screen`: nunca se cuenta dos veces.
2856
+ * Tampoco se emite un `page_view` aquí, por lo mismo.
2857
+ */
2858
+ flushEngagement() {
2859
+ if (!this.tracking?.isTrackingEnabled()) return;
2860
+ const ms = this.engagement?.consume() ?? 0;
2861
+ if (ms > 0) {
2862
+ const current = this.navObserver?.current();
2863
+ this.track("deepdots_user_engagement", {
2864
+ engagement_time_msec: ms,
2865
+ ...current ? { screen: current.screen, path: current.path, screen_seconds: current.seconds } : {}
2866
+ });
2867
+ this.lastEngagementAt = Date.now();
2868
+ }
2869
+ }
2870
+ /** Tick del flush periódico: latido de engagement si toca, y envío de lo acumulado. */
2871
+ onAnalyticsFlushTick() {
2872
+ if (this.sessionOpen && this.isDocumentVisible() && Date.now() - this.lastEngagementAt >= ANALYTICS_HEARTBEAT_MS) {
2873
+ this.flushEngagement();
2874
+ }
2875
+ this.flushAnalytics();
2876
+ }
2877
+ /**
2878
+ * La pestaña vuelve a verse. Tras más de ANALYTICS_SESSION_TIMEOUT_MS oculta, la sesión
2879
+ * anterior termina y empieza otra: seguir con el mismo sessionId mezclaba dos visitas y,
2880
+ * si el backend ya la había cerrado por inactividad, la partía en dos feedbacks.
2881
+ * - Oculta menos de ANALYTICS_SESSION_DISCARD_MS: el backend aún la tiene abierta → se
2882
+ * cierra con normalidad (page_view de la pantalla, session_end `idle_timeout`, completed).
2883
+ * - Más: ya la cerró el backend → se descarta sin enviar nada.
2884
+ */
2885
+ onDocumentVisible() {
2886
+ const hiddenFor = this.hiddenAt === null ? 0 : Date.now() - this.hiddenAt;
2887
+ this.hiddenAt = null;
2888
+ if (!this.sessionOpen) return;
2889
+ if (hiddenFor < ANALYTICS_SESSION_TIMEOUT_MS) {
2890
+ this.engagement?.resume();
2891
+ return;
2892
+ }
2893
+ if (hiddenFor < ANALYTICS_SESSION_DISCARD_MS) {
2894
+ this.closeSession("idle_timeout");
2895
+ } else {
2896
+ this.discardSession();
2897
+ }
2898
+ this.openSession("idle_timeout");
2899
+ }
2900
+ /**
2901
+ * `pagehide` en web: SUSPENDE la sesión en vez de cerrarla, porque el navegador lo lanza
2902
+ * igual al recargar que al cerrar la pestaña. Vuelca lo pendiente (page_view de la
2903
+ * pantalla, mini-services, engagement) con un `deepdots_session_suspend` y SIN
2904
+ * `completed`, y deja el registro en `sessionStorage` (ver `suspended-session.ts`):
2905
+ * - si la página vuelve a cargar en esta pestaña, `init()` sigue en el mismo registro;
2906
+ * - si la pestaña se cerró, el backend lo cierra a los pocos minutos sin otro lote.
2907
+ *
2908
+ * Devuelve false cuando no se puede suspender — aún no se conoce el registro (el primer
2909
+ * POST sigue en vuelo) o no hay `sessionStorage` — y entonces el caller cierra como antes.
2910
+ */
2911
+ suspendSession() {
2912
+ if (!this.sessionOpen || !this.tracking?.isTrackingEnabled()) return false;
2913
+ const sessionId = this.analyticsFeedbackSessionId;
2914
+ const integration = this.analyticsIntegration;
2915
+ const storage = getSessionStorage();
2916
+ if (!sessionId || !integration || !storage) return false;
2917
+ const at = Date.now();
2918
+ const userId = this.tracking.getUserId();
2919
+ if (!writeSuspendedSession(storage, { sessionId, integration, userId, at })) return false;
2920
+ this.sessionOpen = false;
2921
+ this.suspended = { at, userId };
2922
+ this.navObserver?.stop();
2923
+ this.navStarted = false;
2924
+ this.analytics?.exitAllMiniServices();
2925
+ this.flushEngagement();
2926
+ this.engagement?.pause();
2927
+ this.track("deepdots_session_suspend", { reason: "page_hide" });
2928
+ this.flushAnalytics({ final: true });
2929
+ this.log("tracking \xB7 session suspended:", sessionId);
2930
+ return true;
2931
+ }
2932
+ /**
2933
+ * Recoge la sesión que dejó suspendida la carga anterior de esta pestaña (ver
2934
+ * `suspendSession`). Solo con analytics configurado y el tracking activo: sin ellos no hay
2935
+ * registro en el que seguir.
2936
+ */
2937
+ readResumableSession() {
2938
+ const integration = this.analyticsIntegration;
2939
+ const storage = getSessionStorage();
2940
+ if (!integration || !storage || !this.tracking?.isTrackingEnabled()) return null;
2941
+ return takeSuspendedSession(
2942
+ storage,
2943
+ { integration, userId: this.tracking.getUserId() },
2944
+ Date.now(),
2945
+ ANALYTICS_RESUME_WINDOW_MS
2946
+ );
2947
+ }
2948
+ /**
2949
+ * Consume la sesión suspendida al abrir: los ms que estuvo suspendida si se puede seguir en
2950
+ * ella (mismo usuario, dentro de ANALYTICS_RESUME_WINDOW_MS); null si no había o ya no toca.
2951
+ * En ese caso se olvida su registro sin enviar nada: lo cierra el backend, y la sesión que
2952
+ * se abre ahora va a uno nuevo.
2953
+ */
2954
+ takeSuspendedSession() {
2955
+ const suspended = this.suspended;
2956
+ if (!suspended) return null;
2957
+ this.suspended = null;
2958
+ const storage = getSessionStorage();
2959
+ if (storage) clearSuspendedSession(storage);
2960
+ const suspendedMs = Math.max(0, Date.now() - suspended.at);
2961
+ if (this.analyticsFeedbackSessionId && suspendedMs <= ANALYTICS_RESUME_WINDOW_MS && suspended.userId === (this.tracking?.getUserId() ?? null)) {
2962
+ return suspendedMs;
2963
+ }
2964
+ this.analytics?.discardSession(this.analyticsIdentity());
2965
+ this.analyticsFeedbackSessionId = void 0;
2966
+ this.tracking?.setSessionId(null);
2967
+ return null;
2968
+ }
2969
+ /** Olvida la sesión abierta sin enviar nada (ver onDocumentVisible). */
2970
+ discardSession() {
2971
+ this.sessionOpen = false;
2972
+ this.navObserver?.discard();
2973
+ this.analytics?.discardSession(this.analyticsIdentity());
2974
+ this.engagement?.consume();
2975
+ this.engagement?.pause();
2976
+ this.analyticsFeedbackSessionId = void 0;
2977
+ this.tracking?.setSessionId(null);
2978
+ this.log("tracking \xB7 session discarded after", ANALYTICS_SESSION_DISCARD_MS / 6e4, "min hidden");
2979
+ }
2980
+ /**
2981
+ * Geolocalización por IP (país/ciudad para analytics). La caché persistente es local y se
2982
+ * aplica siempre que `geolocation` no esté desactivado. El lookup a terceros (ipapi.co →
2983
+ * ipwho.is → ipinfo.io, fallback con timeout) solo se hace si el dato se va a ENVIAR:
2984
+ * analytics configurado + tracking activo + caché ausente o caducada. Una vez por instancia.
2985
+ */
2986
+ resolveGeo() {
2987
+ const storage = this.storage;
2988
+ if (!this.geoEnabled || !storage || !this.analytics) return;
2989
+ const cachedGeo = readCachedGeo(storage, Date.now());
2990
+ if (cachedGeo) {
2991
+ this.analytics.updateDevice(cachedGeo);
2992
+ return;
2993
+ }
2994
+ if (!this.geoWanted || this.geoLookupStarted) return;
2995
+ if (!this.tracking?.isTrackingEnabled()) return;
2996
+ this.geoLookupStarted = true;
2997
+ fetchGeo().then((geo) => {
2998
+ if (geo) {
2999
+ this.analytics?.updateDevice(geo);
3000
+ writeCachedGeo(storage, geo, Date.now());
3001
+ }
3002
+ }).catch(() => {
3003
+ });
3004
+ }
3005
+ analyticsIdentity() {
3006
+ return {
3007
+ userId: this.tracking?.getUserId() ?? null,
3008
+ sessionId: this.tracking?.getSessionId() ?? null
3009
+ };
3010
+ }
3011
+ /** Flush automático al ocultar/cerrar la página (no perder el lote pendiente). */
3012
+ setupAnalyticsFlush() {
3013
+ this.startAnalyticsFlushTimer();
3014
+ if (typeof document === "undefined" || typeof window === "undefined") return;
3015
+ window.addEventListener("pagehide", () => {
3016
+ clearInterval(this.analyticsFlushTimer);
3017
+ if (!this.suspendSession()) this.closeSession("page_hide");
3018
+ });
3019
+ window.addEventListener("pageshow", (event) => {
3020
+ if (!event.persisted) return;
3021
+ this.startAnalyticsFlushTimer();
3022
+ this.openSession("bfcache_restore");
3023
+ });
3024
+ document.addEventListener("visibilitychange", () => {
3025
+ if (document.visibilityState === "hidden") {
3026
+ this.flushEngagement();
3027
+ this.engagement?.pause();
3028
+ this.flushAnalytics();
3029
+ this.hiddenAt = Date.now();
3030
+ } else if (document.visibilityState === "visible") {
3031
+ this.onDocumentVisible();
3032
+ }
3033
+ });
3034
+ }
3035
+ startAnalyticsFlushTimer() {
3036
+ clearInterval(this.analyticsFlushTimer);
3037
+ this.analyticsFlushTimer = setInterval(() => this.onAnalyticsFlushTick(), ANALYTICS_FLUSH_INTERVAL_MS);
3038
+ }
3039
+ /** Enable auto-launch functionality with configured triggers */
3040
+ autoLaunch() {
3041
+ if (!this.initialized) {
3042
+ throw new Error("SDK not initialized. Call init() first.");
3043
+ }
3044
+ if (!this.popupsLoaded) {
3045
+ this.pendingAutoLaunch = true;
3046
+ this.log("Auto-launch deferred until popups are loaded");
3047
+ return;
3048
+ }
3049
+ this.startTriggers();
3050
+ }
3051
+ /** Inicia los triggers configurados */
3052
+ startTriggers() {
3053
+ this.log("Auto-launch enabled");
3054
+ this.triggers.forEach((trigger) => setupTrigger(this, trigger));
3055
+ }
3056
+ /** Configure triggers for auto-launching popups (manual) */
3057
+ configureTriggers(triggers) {
3058
+ if (!this.initialized) {
3059
+ throw new Error("SDK not initialized. Call init() first.");
3060
+ }
3061
+ this.triggers = triggers;
3062
+ this.log("Triggers configured", triggers);
3063
+ }
3064
+ /** Deriva triggers desde las definiciones de popup */
3065
+ configureTriggersFromDefinitions() {
3066
+ const derived = [];
3067
+ this.debug("Validated popup definitions", this.popupDefinitions);
3068
+ this.popupDefinitions.forEach((def) => {
3069
+ def.triggers.forEach((trigger) => {
3070
+ const type = this.mapPopupTriggerType(trigger.type);
3071
+ if (!type) {
3072
+ this.debug("Unsupported trigger type", trigger.type);
3073
+ return;
3074
+ }
3075
+ const value = type === "time" && typeof trigger.value === "number" ? trigger.value * 1e3 : trigger.value;
3076
+ derived.push({ type, value, surveyId: def.surveyId, popupId: def.id, delaySeconds: trigger.delaySeconds });
3077
+ });
3078
+ });
3079
+ if (derived.length) {
3080
+ this.configureTriggers(derived);
3081
+ }
3082
+ }
3083
+ /**
3084
+ * Lógica para evaluar condiciones antes de mostrar una encuesta. `options.delaySeconds`
3085
+ * (lo pasan los triggers time/scroll/click con el "Delay" del Admin) espera ese tiempo y
3086
+ * vuelve a evaluar antes de mostrar; sin él, al momento como siempre.
3087
+ */
3088
+ triggerSurvey(surveyId, popupId, options) {
3089
+ const delaySeconds = options?.delaySeconds;
3090
+ if (this.bufferIfAwaitingPopups({ kind: "survey", surveyId, popupId, delaySeconds })) return;
3091
+ const def = this.findPopupDefinition(surveyId, popupId);
3092
+ if (!def) {
3093
+ this.debug("No popup definition for trigger", { surveyId, popupId });
3094
+ return;
3095
+ }
3096
+ if (!this.shouldShow(def)) {
3097
+ this.debug("Conditions prevented showing popup", def.id);
3098
+ return;
3099
+ }
3100
+ this.showAfterDelay(def, delaySeconds);
3101
+ }
3102
+ /** Trigger popups configured with trigger.type = 'event' and matching trigger.value */
3103
+ triggerEvent(eventName) {
3104
+ if (!this.initialized) {
3105
+ throw new Error("SDK not initialized. Call init() first.");
3106
+ }
3107
+ const normalized = String(eventName || "").trim();
3108
+ if (!normalized) {
3109
+ this.debug("Ignoring empty event trigger name");
3110
+ return;
3111
+ }
3112
+ if (this.bufferIfAwaitingPopups({ kind: "event", name: normalized })) return;
3113
+ this.evaluateEvent(normalized);
3114
+ }
3115
+ evaluateEvent(normalized) {
3116
+ const candidates = this.popupDefinitions.filter((def) => {
3117
+ return def.triggers.some((trigger2) => {
3118
+ const triggerValue = String(trigger2.value ?? "").trim();
3119
+ return trigger2.type === "event" && triggerValue === normalized;
3120
+ });
3121
+ });
3122
+ if (!candidates.length) {
3123
+ this.debug("No event popup definitions found", { eventName: normalized });
3124
+ return;
3125
+ }
3126
+ const matched = candidates.find((def) => this.shouldShow(def));
3127
+ if (!matched) {
3128
+ this.debug("Event popup blocked by conditions/segments", { eventName: normalized });
3129
+ return;
3130
+ }
3131
+ const trigger = matched.triggers.find(
3132
+ (t) => t.type === "event" && String(t.value ?? "").trim() === normalized
3133
+ );
3134
+ this.showAfterDelay(matched, trigger?.delaySeconds);
3135
+ }
3136
+ /**
3137
+ * Muestra `def` ya, o tras su "Delay (seconds)" del Admin. Mientras espera:
3138
+ * - el mismo popup no se programa dos veces (el primer vencimiento manda);
3139
+ * - cambiar de ruta/pantalla o pasar a background lo cancela;
3140
+ * y al vencer se vuelve a evaluar todo (segmentos, idioma, cooldowns) como un disparo nuevo.
3141
+ * Si entonces hay otro popup abierto, `showDefinition` lo salta sin efectos, igual que hoy.
3142
+ */
3143
+ showAfterDelay(def, delaySeconds) {
3144
+ const delayMs = triggerDelayMs(delaySeconds);
3145
+ if (delayMs <= 0) {
3146
+ this.showDefinition(def);
3147
+ return;
3148
+ }
3149
+ if (this.delayedPopups.has(def.id)) {
3150
+ this.debug("Popup already waiting for its delay", def.id);
3151
+ return;
3152
+ }
3153
+ const entry = {
3154
+ popupId: def.id,
3155
+ timer: setTimeout(() => this.showDelayedPopup(def.id), delayMs),
3156
+ firedAt: Date.now(),
3157
+ href: this.currentHref(),
3158
+ screen: this.currentScreen
3159
+ };
3160
+ this.delayedPopups.set(def.id, entry);
3161
+ this.debug(`Popup delayed ${delayMs}ms`, def.id);
3162
+ }
3163
+ showDelayedPopup(popupId) {
3164
+ const entry = this.delayedPopups.get(popupId);
3165
+ if (!entry) return;
3166
+ this.delayedPopups.delete(popupId);
3167
+ const def = this.popupDefinitions.find((popup) => popup.id === popupId);
3168
+ if (!def) return;
3169
+ if (this.currentHref() !== entry.href || this.currentScreen !== entry.screen) {
3170
+ this.debug("Delayed popup dropped: route changed", popupId);
3171
+ return;
3172
+ }
3173
+ if (!this.shouldShow(def)) {
3174
+ this.debug("Delayed popup dropped by conditions at due time", popupId);
3175
+ return;
3176
+ }
3177
+ if ((this.lastShown.get(popupId) ?? 0) >= entry.firedAt) {
3178
+ this.debug("Delayed popup dropped: already shown while waiting", popupId);
3179
+ return;
3180
+ }
3181
+ this.showDefinition(def);
3182
+ }
3183
+ cancelDelayedPopups(reason, predicate = () => true) {
3184
+ this.delayedPopups.forEach((entry, popupId) => {
3185
+ if (!predicate(entry)) return;
3186
+ clearTimeout(entry.timer);
3187
+ this.delayedPopups.delete(popupId);
3188
+ this.debug(`Delayed popup cancelled (${reason})`, popupId);
3189
+ });
3190
+ }
3191
+ currentHref() {
3192
+ if (typeof window === "undefined" || !window.location) return "";
3193
+ return this.normalizeUrl(window.location.href || "");
3194
+ }
3195
+ /**
3196
+ * Guarda `trigger` si las definiciones aún no han llegado. Devuelve `true` si lo guardó (el
3197
+ * llamador no debe evaluarlo ahora) y `false` si no hay carga en vuelo (se evalúa ya, como
3198
+ * siempre: tras cargar, tras un fallo o sin apiKey).
3199
+ */
3200
+ bufferIfAwaitingPopups(trigger) {
3201
+ if (!this.awaitingPopups) return false;
3202
+ if (this.pendingTriggers.length >= MAX_PENDING_TRIGGERS) {
3203
+ const dropped = this.pendingTriggers.shift();
3204
+ this.debug("Pending trigger buffer full; dropped oldest", dropped);
3205
+ }
3206
+ this.pendingTriggers.push(trigger);
3207
+ this.debug("Popups not loaded yet; trigger buffered", trigger);
3208
+ return true;
3209
+ }
3210
+ /** La carga falló: sin definiciones no hay nada que reproducir, se descarta todo. */
3211
+ dropPendingTriggers() {
3212
+ const dropped = this.pendingTriggers.length;
3213
+ this.awaitingPopups = false;
3214
+ this.pendingTriggers = [];
3215
+ if (dropped > 0) this.debug("Popups failed to load; dropped pending triggers", dropped);
3216
+ }
3217
+ /** Reproduce en orden por la evaluación normal (segmentos, cooldowns y condiciones de AHORA). */
3218
+ replayPendingTriggers() {
3219
+ this.awaitingPopups = false;
3220
+ const replay = this.pendingTriggers;
3221
+ this.pendingTriggers = [];
3222
+ if (!replay.length) return;
3223
+ this.debug("Replaying triggers received before popups loaded", replay.length);
3224
+ replay.forEach((trigger) => {
3225
+ if (trigger.kind === "event") this.evaluateEvent(trigger.name);
3226
+ else this.triggerSurvey(trigger.surveyId, trigger.popupId, { delaySeconds: trigger.delaySeconds });
3227
+ });
3228
+ }
3229
+ showDefinition(def) {
3230
+ if (this.renderer.isShowing?.()) {
3231
+ this.debug("Popup skipped: another popup is already open", def.id);
3232
+ return;
3233
+ }
3234
+ this.log("Showing popup (definition)", def);
3235
+ this.surveyToPopupId.set(def.surveyId, def.id);
3236
+ this.lastShown.set(def.id, Date.now());
3237
+ this.persistPopupState();
3238
+ this.renderPopup(def.surveyId, def.productId, def.actions, def.style, def.title, def.surveyFrontend?.sdkVersion);
3239
+ this.emitEvent("popup_shown", def.surveyId, { popupId: def.id });
3240
+ }
3241
+ shouldShow(def, pathUrl, skipPathCheck = false) {
3242
+ if (this.storage) this.loadPopupState(this.storage);
3243
+ if (this.isPathExcluded(def, pathUrl)) {
3244
+ return false;
3245
+ }
3246
+ if (!skipPathCheck && !this.matchesSegmentsPath(def, pathUrl)) {
3247
+ return false;
3248
+ }
3249
+ if (!this.matchesSegmentsLang(def)) {
3250
+ return false;
3251
+ }
3252
+ const cooldowns = def.cooldown || [];
3253
+ if (cooldowns.length && !cooldowns.every((cooldown) => this.evaluateCooldown(def, cooldown))) {
3254
+ return false;
3255
+ }
3256
+ const legacyConditions = def.legacyConditions || [];
3257
+ if (!legacyConditions.length) return true;
3258
+ return legacyConditions.every((condition) => this.evaluateLegacyCondition(def, condition));
3259
+ }
3260
+ matchesSegmentsLang(def) {
3261
+ const langs = def.segments?.lang;
3262
+ if (!langs || langs.length === 0) return true;
3263
+ const currentLang = (this.language ?? "").toLowerCase();
3264
+ if (!currentLang) {
3265
+ this.debug("No language available for lang comparison", { popupId: def.id, langs });
3266
+ return true;
3267
+ }
3268
+ const matches = langs.some(
3269
+ (lang) => typeof lang === "string" && currentLang.startsWith(lang.toLowerCase())
3270
+ );
3271
+ if (!matches) {
3272
+ this.debug("Lang mismatch for popup", { popupId: def.id, langs, currentLang });
3273
+ }
3274
+ return matches;
3275
+ }
3276
+ /** `segments.path`: rutas donde el popup PUEDE mostrarse. Sin lista, en todas. */
3277
+ matchesSegmentsPath(def, pathUrl) {
3278
+ const paths = def.segments?.path;
3279
+ if (!Array.isArray(paths) || paths.length === 0) return true;
3280
+ const location = this.resolveCurrentLocation(pathUrl);
3281
+ if (!location) {
3282
+ this.debug("No window.location available for path comparison", { popupId: def.id, paths });
3283
+ return true;
3284
+ }
3285
+ const matches = paths.some((rawCandidate) => {
3286
+ const match = this.matchesPathCandidate(rawCandidate, location);
3287
+ this.debug("Path comparison", {
3288
+ popupId: def.id,
3289
+ candidate: rawCandidate,
3290
+ currentPath: location.path,
3291
+ currentHref: location.href,
3292
+ match
3293
+ });
3294
+ return match;
3295
+ });
3296
+ if (!matches) {
3297
+ this.debug("No path match for popup", { popupId: def.id, paths, currentPath: location.path });
3298
+ }
3299
+ return matches;
3300
+ }
3301
+ /**
3302
+ * `segments.excludedPaths`: rutas donde el popup NO debe mostrarse. Gana sobre
3303
+ * `segments.path` (`path: ['/']` + `excludedPaths: ['/cart']` = en todas menos el
3304
+ * carrito) y se aplica también cuando no hay `path` (= en todas menos las excluidas).
3305
+ */
3306
+ isPathExcluded(def, pathUrl) {
3307
+ const excluded = def.segments?.excludedPaths;
3308
+ if (!Array.isArray(excluded) || excluded.length === 0) return false;
3309
+ const location = this.resolveCurrentLocation(pathUrl);
3310
+ if (!location) {
3311
+ this.debug("No window.location available for excluded path comparison", { popupId: def.id, excluded });
3312
+ return false;
3313
+ }
3314
+ const hit = excluded.find((rawCandidate) => this.matchesPathCandidate(rawCandidate, location));
3315
+ if (hit !== void 0) {
3316
+ this.debug("Popup excluded by path", {
3317
+ popupId: def.id,
3318
+ candidate: hit,
3319
+ currentPath: location.path,
3320
+ currentHref: location.href
3321
+ });
3322
+ return true;
3323
+ }
3324
+ return false;
3325
+ }
3326
+ /**
3327
+ * Compara UN candidato de `segments.path`/`segments.excludedPaths` con la ruta
3328
+ * actual. Mismas reglas para incluir y para excluir:
3329
+ * - URL absoluta → href completo exacto
3330
+ * - empieza por / → subcadena del href (así entran las rutas con hash: `/#/home`)
3331
+ * - resto → pathname exacto
3332
+ * Ignora entradas que no sean string: el backend puede colar un `null` en la lista
3333
+ * y no puede tumbar la evaluación del trigger entero (mismo fallo que hubo con
3334
+ * `segments.lang`).
3335
+ */
3336
+ matchesPathCandidate(rawCandidate, location) {
3337
+ if (typeof rawCandidate !== "string") return false;
3338
+ const candidate = this.normalizeUrl(rawCandidate);
3339
+ if (!candidate) return false;
3340
+ if (candidate.startsWith("http://") || candidate.startsWith("https://")) {
3341
+ return location.href === candidate;
3342
+ }
3343
+ if (candidate.startsWith("/")) {
3344
+ return location.href.includes(candidate);
3345
+ }
3346
+ return location.path === candidate;
3347
+ }
3348
+ /** href + pathname normalizados de la ruta a evaluar, o null si no hay `window.location`. */
3349
+ resolveCurrentLocation(pathUrl) {
3350
+ if (typeof window === "undefined" || !window.location) return null;
3351
+ const href = this.normalizeUrl(pathUrl || window.location.href || "");
3352
+ const parsed = this.safeParseUrl(href);
3353
+ return { href, path: this.normalizeUrl(parsed?.pathname || window.location.pathname || "") };
3354
+ }
3355
+ evaluateCooldown(def, condition) {
3356
+ switch (condition.answered) {
3357
+ case "SHOWED":
3358
+ return this.hasCooldownElapsed(this.lastShown.get(def.id), condition.cooldownDays);
3359
+ case "PARTIAL":
3360
+ case "COMPLETED": {
3361
+ const progress = this.surveyProgress.get(def.surveyId);
3362
+ if (!progress || progress.status !== condition.answered) {
3363
+ return true;
3364
+ }
3365
+ return this.hasCooldownElapsed(progress.timestamp, condition.cooldownDays);
3366
+ }
3367
+ default:
3368
+ return true;
3369
+ }
3370
+ }
3371
+ evaluateLegacyCondition(def, condition) {
3372
+ if (!condition.answered && this.answeredSurveys.has(def.surveyId)) {
3373
+ return false;
3374
+ }
3375
+ return this.hasCooldownElapsed(this.lastShown.get(def.id), condition.cooldownDays);
3376
+ }
3377
+ hasCooldownElapsed(timestamp, cooldownDays) {
3378
+ if (!timestamp || !cooldownDays) {
3379
+ return true;
3380
+ }
3381
+ return Date.now() - timestamp >= cooldownDays * DAY_IN_MS;
3382
+ }
3383
+ /** Marcar encuesta como contestada externamente */
3384
+ markSurveyAnswered(surveyId) {
3385
+ this.answeredSurveys.add(surveyId);
3386
+ this.markSurveyProgress(surveyId, "COMPLETED");
3387
+ }
3388
+ /** Queue an exit popup so it can render after navigation */
3389
+ queueExitPopup(surveyId, delaySeconds, sourceUrl, popupId) {
3390
+ const def = this.findPopupDefinition(surveyId, popupId);
3391
+ if (!def) {
3392
+ this.debug("No popup definition for exit trigger", { surveyId, popupId });
3393
+ return;
3394
+ }
3395
+ const originUrl = sourceUrl || (typeof window !== "undefined" ? window.location.href : "");
3396
+ if (!originUrl) {
3397
+ this.debug("Exit popup skipped: missing source URL", { surveyId });
3398
+ return;
3399
+ }
3400
+ if (!this.shouldShow(def, originUrl)) {
3401
+ this.debug("Exit popup skipped by conditions/path", { popupId: def.id, sourceUrl: originUrl });
3402
+ return;
3403
+ }
3404
+ const safeDelayMs = Number.isFinite(delaySeconds) ? Math.max(0, delaySeconds * 1e3) : 0;
3405
+ const deferred = {
3406
+ id: def.id,
3407
+ surveyId: def.surveyId,
3408
+ sourceUrl: this.normalizeUrl(originUrl),
3409
+ dueAt: Date.now() + safeDelayMs
3410
+ };
3411
+ const queue = this.getDeferredExitQueue().filter((item) => !(item.id === deferred.id && item.sourceUrl === deferred.sourceUrl));
3412
+ queue.push(deferred);
3413
+ this.setDeferredExitQueue(queue);
3414
+ this.scheduleDeferredExitPopup(deferred);
3415
+ this.debug("Exit popup queued", deferred);
3416
+ }
3417
+ processDeferredExitQueue() {
3418
+ const queue = this.getDeferredExitQueue();
3419
+ if (!queue.length) return;
3420
+ const pending2 = [];
3421
+ const now = Date.now();
3422
+ queue.forEach((item) => {
3423
+ const def = this.popupDefinitions.find((popup) => popup.id === item.id && popup.surveyId === item.surveyId);
3424
+ if (!def) {
3425
+ return;
3426
+ }
3427
+ if (item.dueAt <= now) {
3428
+ this.tryShowDeferredExitPopup(item);
3429
+ return;
3430
+ }
3431
+ pending2.push(item);
3432
+ this.scheduleDeferredExitPopup(item);
3433
+ });
3434
+ this.setDeferredExitQueue(pending2);
3435
+ }
3436
+ scheduleDeferredExitPopup(item) {
3437
+ if (typeof window === "undefined") return;
3438
+ const delay = Math.max(0, item.dueAt - Date.now());
3439
+ const timer = window.setTimeout(() => this.tryShowDeferredExitPopup(item), delay);
3440
+ this.deferredExitTimers.push(timer);
3441
+ }
3442
+ tryShowDeferredExitPopup(item) {
3443
+ const def = this.popupDefinitions.find((popup) => popup.id === item.id && popup.surveyId === item.surveyId);
3444
+ if (!def) {
3445
+ this.removeDeferredExitPopup(item);
3446
+ return;
3447
+ }
3448
+ const currentUrl = typeof window !== "undefined" ? this.normalizeUrl(window.location.href || "") : "";
3449
+ if (!currentUrl || currentUrl === this.normalizeUrl(item.sourceUrl)) {
3450
+ this.removeDeferredExitPopup(item);
3451
+ this.debug("Exit popup dropped because route did not change", item);
3452
+ return;
3453
+ }
3454
+ if (!this.shouldShow(def, void 0, true)) {
3455
+ this.removeDeferredExitPopup(item);
3456
+ this.debug("Exit popup skipped at render-time conditions", item);
3457
+ return;
3458
+ }
3459
+ this.showDefinition(def);
3460
+ this.removeDeferredExitPopup(item);
3461
+ }
3462
+ findPopupDefinition(surveyId, popupId) {
3463
+ if (popupId) {
3464
+ const byId = this.popupDefinitions.find((popup) => popup.id === popupId);
3465
+ if (byId) return byId;
3466
+ }
3467
+ return this.popupDefinitions.find((popup) => popup.surveyId === surveyId);
3468
+ }
3469
+ removeDeferredExitPopup(item) {
3470
+ const queue = this.getDeferredExitQueue().filter((entry) => !(entry.id === item.id && entry.sourceUrl === item.sourceUrl));
3471
+ this.setDeferredExitQueue(queue);
3472
+ }
3473
+ getDeferredExitQueue() {
3474
+ if (typeof window === "undefined") return [];
3475
+ try {
3476
+ const raw = window.sessionStorage.getItem(EXIT_QUEUE_STORAGE_KEY);
3477
+ if (!raw) return [];
3478
+ const parsed = JSON.parse(raw);
3479
+ if (!Array.isArray(parsed)) return [];
3480
+ return parsed.filter((entry) => {
3481
+ if (typeof entry !== "object" || entry === null) return false;
3482
+ const item = entry;
3483
+ return typeof item.id === "string" && typeof item.surveyId === "string" && typeof item.sourceUrl === "string" && typeof item.dueAt === "number" && Number.isFinite(item.dueAt);
3484
+ }).map((item) => ({
3485
+ ...item,
3486
+ sourceUrl: this.normalizeUrl(item.sourceUrl)
3487
+ }));
3488
+ } catch {
3489
+ return [];
3490
+ }
3491
+ }
3492
+ setDeferredExitQueue(queue) {
3493
+ if (typeof window === "undefined") return;
3494
+ try {
3495
+ if (!queue.length) {
3496
+ window.sessionStorage.removeItem(EXIT_QUEUE_STORAGE_KEY);
3497
+ return;
3498
+ }
3499
+ window.sessionStorage.setItem(EXIT_QUEUE_STORAGE_KEY, JSON.stringify(queue));
3500
+ } catch {
3501
+ }
3502
+ }
3503
+ /** Fetch al servidor para obtener popups. `null` si la carga falló (red, no-2xx, payload inválido). */
3504
+ async fetchPopupsFromServer() {
3505
+ const apiKey = this.config?.apiKey;
3506
+ const baseUrl = this.baseUrl;
3507
+ const userId = this.tracking?.getUserId() ?? this.config?.userId;
3508
+ if (!apiKey || !baseUrl) {
3509
+ this.log("Missing apiKey or baseUrl. Skipping popups fetch.");
3510
+ return [];
3511
+ }
3512
+ const filter = userId ? { where: { userId } } : null;
3513
+ const query = filter ? `?filter=${encodeURIComponent(JSON.stringify(filter))}` : "";
3514
+ const endpoint = `${baseUrl}/sdk/${encodeURIComponent(apiKey)}/popups${query}`;
3515
+ try {
3516
+ const response = await fetch(endpoint);
3517
+ if (!response.ok) {
3518
+ this.log("Failed to fetch popups", response.status, response.statusText);
3519
+ return null;
3520
+ }
3521
+ const raw = await response.text();
3522
+ const parsed = JSON.parse(raw);
3523
+ if (!Array.isArray(parsed)) {
3524
+ this.log("Unexpected popups payload", parsed);
3525
+ return null;
3526
+ }
3527
+ this.debug("Fetched popups payload", parsed);
3528
+ return parsed;
3529
+ } catch (error) {
3530
+ this.log("Error fetching popups", error);
3531
+ return null;
3532
+ }
3533
+ }
3534
+ /**
3535
+ * Envía los atributos de contact a la API (`POST /sdk/popups/contact`). Rechaza si no se
3536
+ * pudo enviar (sin red o respuesta no-2xx), para que `ContactManager` no guarde la caché
3537
+ * y la llamada siguiente reintente.
3538
+ */
3539
+ async postContact(body) {
3540
+ const baseUrl = this.baseUrl;
3541
+ if (!baseUrl) throw new Error("no base URL");
3542
+ const endpoint = `${baseUrl}/sdk/popups/contact`;
3543
+ let response;
3544
+ try {
3545
+ response = await fetch(endpoint, {
3546
+ method: "POST",
3547
+ headers: { "Content-Type": "application/json" },
3548
+ body: JSON.stringify(body)
3549
+ });
3550
+ } catch (error) {
3551
+ this.log("Error posting contact", error);
3552
+ throw error;
3553
+ }
3554
+ if (!response.ok) {
3555
+ this.log("Failed to post contact", response.status, response.statusText);
3556
+ throw new Error(`HTTP ${response.status}`);
3557
+ }
3558
+ this.log("contact \xB7 sent attributes for user:", body.userId);
3559
+ }
3560
+ /** Notifica eventos de popup a la API */
3561
+ async postPopupEvent(status, popupId, userId) {
3562
+ const apiKey = this.config?.apiKey;
3563
+ const baseUrl = this.baseUrl;
3564
+ if (!apiKey || !baseUrl) {
3565
+ return;
3566
+ }
3567
+ const endpoint = `${baseUrl}/sdk/popups`;
3568
+ try {
3569
+ const response = await fetch(endpoint, {
3570
+ method: "POST",
3571
+ headers: { "Content-Type": "application/json" },
3572
+ body: JSON.stringify({
3573
+ publicKey: apiKey,
3574
+ status,
3575
+ popupId,
3576
+ userId: userId || void 0
3577
+ })
3578
+ });
3579
+ if (!response.ok) {
3580
+ this.log("Failed to post popup event", response.status, response.statusText);
3581
+ return;
3582
+ }
3583
+ try {
3584
+ const data = await response.json();
3585
+ if (data && typeof data.sessionId === "string") {
3586
+ this.tracking?.setSessionId(data.sessionId);
3587
+ this.log("tracking \xB7 session_id from backend:", data.sessionId);
3588
+ }
3589
+ } catch {
3590
+ }
3591
+ } catch (error) {
3592
+ this.log("Error posting popup event", error);
3593
+ }
3594
+ }
3595
+ /** Add an event listener */
3596
+ on(eventType, listener) {
3597
+ if (!this.listeners.has(eventType)) {
3598
+ this.listeners.set(eventType, /* @__PURE__ */ new Set());
3599
+ }
3600
+ this.listeners.get(eventType).add(listener);
3601
+ }
3602
+ /** Remove an event listener */
3603
+ off(eventType, listener) {
3604
+ const listeners = this.listeners.get(eventType);
3605
+ if (listeners) {
3606
+ listeners.delete(listener);
3607
+ }
3608
+ }
3609
+ /** Render the popup UI */
3610
+ renderPopup(surveyId, productId, actions, style, title, surveySdkVersion) {
3611
+ const userId = this.tracking?.getUserId() ?? this.config?.userId;
3612
+ const sessionId = this.tracking?.getSessionId() ?? void 0;
3613
+ const miniService = this.analytics?.getMiniService() ?? void 0;
3614
+ const analyticsFeedbackSessionId = this.analyticsFeedbackSessionId;
3615
+ this.log("tracking \xB7 survey identity \u2192", { userId: userId ?? null, sessionId: sessionId ?? null, miniService: miniService ?? null, analyticsFeedbackSessionId: analyticsFeedbackSessionId ?? null });
3616
+ this.renderer.show(
3617
+ surveyId,
3618
+ productId,
3619
+ actions,
3620
+ (type, id, payload) => this.emitEvent(type, id, payload),
3621
+ () => this.hidePopup(),
3622
+ this.env,
3623
+ userId,
3624
+ style,
3625
+ sessionId,
3626
+ miniService,
3627
+ analyticsFeedbackSessionId,
3628
+ this.renderChrome,
3629
+ { title, showProgressBar: this.showProgressBar, surveyCss: this.surveyCss, language: this.language, cspNonce: this.cspNonce, surveySdkVersion, debug: this.config?.debug }
3630
+ );
3631
+ }
3632
+ /** Hide the popup */
3633
+ hidePopup() {
3634
+ this.renderer.hide();
3635
+ }
3636
+ /** Emit an event */
3637
+ emitEvent(type, surveyId, data) {
3638
+ const event = { type, surveyId, timestamp: Date.now(), data };
3639
+ this.log("Event emitted", event);
3640
+ if (type === "survey_error") {
3641
+ const popupId = data?.popupId || this.surveyToPopupId.get(surveyId);
3642
+ this.track("deepdots_survey_error", {
3643
+ survey_id: surveyId,
3644
+ ...popupId ? { popup_id: popupId } : {},
3645
+ reason: data?.reason,
3646
+ message: data?.message
3647
+ });
3648
+ }
3649
+ const isPartialClick = type === "popup_clicked" && data?.action === "partial";
3650
+ if (isPartialClick) {
3651
+ this.markSurveyProgress(surveyId, "PARTIAL");
3652
+ }
3653
+ if (type === "survey_completed") {
3654
+ this.markSurveyAnswered(surveyId);
3655
+ }
3656
+ if (type === "popup_shown" || type === "survey_completed" || isPartialClick) {
3657
+ const popupIdFromData = data?.popupId;
3658
+ const popupId = popupIdFromData || this.surveyToPopupId.get(surveyId);
3659
+ if (popupId) {
3660
+ const userIdFromData = data?.userId;
3661
+ const status = type === "popup_shown" ? "SHOWED" /* SHOWED */ : type === "survey_completed" ? "COMPLETED" /* COMPLETED */ : "PARTIAL" /* PARTIAL */;
3662
+ void this.postPopupEvent(status, popupId, userIdFromData || this.tracking?.getUserId() || this.config?.userId);
3663
+ } else {
3664
+ this.debug("No popupId available to post event", { type, surveyId });
3665
+ }
3666
+ }
3667
+ const listeners = this.listeners.get(type);
3668
+ if (listeners) {
3669
+ listeners.forEach((listener) => {
3670
+ try {
3671
+ listener(event);
3672
+ } catch (error) {
3673
+ if (this.logger.error) this.logger.error("Error in event listener:", error);
3674
+ else this.logger.log("Error in event listener:", error);
3675
+ }
3676
+ });
3677
+ }
3678
+ }
3679
+ /** Log debug messages */
3680
+ log(...args) {
3681
+ if (this.config?.debug) {
3682
+ this.logger.log("[DeepdotsPopups]", ...args);
3683
+ }
3684
+ }
3685
+ /** External debug method for triggers */
3686
+ debug(...args) {
3687
+ this.log(...args);
3688
+ }
3689
+ /** Set a custom renderer */
3690
+ setRenderer(renderer) {
3691
+ this.renderer = renderer;
3692
+ if (this.initialized && this.renderer.init) {
3693
+ this.renderer.init();
3694
+ }
3695
+ }
3696
+ normalizeUrl(value) {
3697
+ if (!value) return "";
3698
+ const withoutIndex = value.replace(/\/index\.html(?=($|[?#]))/i, "");
3699
+ return withoutIndex.length > 1 && withoutIndex.endsWith("/") ? withoutIndex.slice(0, -1) : withoutIndex;
3700
+ }
3701
+ safeParseUrl(url) {
3702
+ if (!url) return null;
3703
+ try {
3704
+ return new URL(url, typeof window !== "undefined" ? window.location.href : void 0);
3705
+ } catch {
3706
+ return null;
3707
+ }
3708
+ }
3709
+ mapPopupTriggerType(type) {
3710
+ switch (type) {
3711
+ case "time_on_page":
3712
+ return "time";
3713
+ case "scroll":
3714
+ return "scroll";
3715
+ case "exit":
3716
+ return "exit";
3717
+ case "click":
3718
+ return "click";
3719
+ case "event":
3720
+ return "event";
3721
+ default:
3722
+ return null;
3723
+ }
3724
+ }
3725
+ markSurveyProgress(surveyId, status) {
3726
+ const current = this.surveyProgress.get(surveyId);
3727
+ if (current?.status === "COMPLETED" && status !== "COMPLETED") {
3728
+ return;
3729
+ }
3730
+ this.surveyProgress.set(surveyId, { status, timestamp: Date.now() });
3731
+ this.persistPopupState();
3732
+ }
3733
+ /**
3734
+ * Fusiona el estado de redisplay del storage con el de memoria: por cada popup/survey gana
3735
+ * la entrada MÁS RECIENTE. Fusionar y no sustituir es lo que hace convivir a varias
3736
+ * pestañas sobre el mismo `localStorage`: se llama en el `init()`, antes de cada decisión
3737
+ * de mostrar y antes de cada escritura. `answeredSurveys` se reconstruye desde las
3738
+ * entradas COMPLETED: es exactamente lo que persiste `markSurveyAnswered`.
3739
+ */
3740
+ loadPopupState(storage) {
3741
+ const state = readPopupState(storage);
3742
+ Object.entries(state.lastShown).forEach(([popupId, timestamp]) => {
3743
+ if (timestamp > (this.lastShown.get(popupId) ?? -Infinity)) this.lastShown.set(popupId, timestamp);
3744
+ });
3745
+ Object.entries(state.progress).forEach(([surveyId, entry]) => {
3746
+ const current = this.surveyProgress.get(surveyId);
3747
+ if (current && current.timestamp >= entry.timestamp) return;
3748
+ this.surveyProgress.set(surveyId, { status: entry.status, timestamp: entry.timestamp });
3749
+ if (entry.status === "COMPLETED") this.answeredSurveys.add(surveyId);
3750
+ });
3751
+ }
3752
+ /**
3753
+ * Vuelca el estado de redisplay al storage. Sin storage (o bloqueado) degrada a memoria.
3754
+ * Fusiona antes de escribir: escribir solo la foto en memoria borraba lo que otra pestaña
3755
+ * hubiese guardado desde nuestro `init()`.
3756
+ */
3757
+ persistPopupState() {
3758
+ if (!this.storage) return;
3759
+ this.loadPopupState(this.storage);
3760
+ writePopupState(this.storage, {
3761
+ lastShown: Object.fromEntries(this.lastShown),
3762
+ progress: Object.fromEntries(this.surveyProgress)
3763
+ });
3764
+ }
3765
+ isPopupDefinition(value) {
3766
+ if (typeof value !== "object" || value === null) return false;
3767
+ const popup = value;
3768
+ return typeof popup.id === "string" && typeof popup.title === "string" && typeof popup.message === "string" && typeof popup.surveyId === "string" && typeof popup.productId === "string" && Array.isArray(popup.triggers) && popup.triggers.length > 0 && popup.triggers.every((trigger) => this.isPopupTrigger(trigger)) && (!popup.cooldown || popup.cooldown.every((condition) => this.isPopupTriggerCondition(condition)));
3769
+ }
3770
+ isPopupTrigger(value) {
3771
+ if (typeof value !== "object" || value === null) return false;
3772
+ const trigger = value;
3773
+ return this.isPopupTriggerType(trigger.type) && (typeof trigger.value === "number" || typeof trigger.value === "string");
3774
+ }
3775
+ isPopupTriggerType(value) {
3776
+ return value === "time_on_page" || value === "scroll" || value === "exit" || value === "click" || value === "event";
3777
+ }
3778
+ isPopupTriggerCondition(value) {
3779
+ if (typeof value !== "object" || value === null) return false;
3780
+ const condition = value;
3781
+ return POPUP_TRIGGER_CONDITION_STATUSES.includes(condition.answered) && typeof condition.cooldownDays === "number" && Number.isFinite(condition.cooldownDays) && condition.cooldownDays >= 0;
3782
+ }
3783
+ isLegacyPopupTriggerCondition(value) {
3784
+ if (typeof value !== "object" || value === null) return false;
3785
+ const condition = value;
3786
+ if (condition.answered !== void 0 && typeof condition.answered !== "boolean") {
3787
+ return false;
3788
+ }
3789
+ if (condition.cooldownDays !== void 0) {
3790
+ return typeof condition.cooldownDays === "number" && Number.isFinite(condition.cooldownDays) && condition.cooldownDays >= 0;
3791
+ }
3792
+ return true;
3793
+ }
3794
+ normalizeTriggers(value) {
3795
+ const items = Array.isArray(value) ? value : value ? [value] : [];
3796
+ return items.filter((trigger) => this.isPopupTrigger(trigger)).map((trigger) => {
3797
+ const delayMs = triggerDelayMs(trigger.delaySeconds);
3798
+ return delayMs > 0 ? { type: trigger.type, value: trigger.value, delaySeconds: delayMs / 1e3 } : { type: trigger.type, value: trigger.value };
3799
+ });
3800
+ }
3801
+ normalizeCooldown(value) {
3802
+ if (!Array.isArray(value)) return [];
3803
+ return value.filter((condition) => this.isPopupTriggerCondition(condition));
3804
+ }
3805
+ normalizeLegacyConditions(value) {
3806
+ if (!Array.isArray(value)) return [];
3807
+ return value.filter((condition) => this.isLegacyPopupTriggerCondition(condition));
3808
+ }
3809
+ normalizePopupDefinition(def) {
3810
+ if (typeof def !== "object" || def === null) return null;
3811
+ const raw = def;
3812
+ const rawTriggers = raw.triggers ?? raw.trigger;
3813
+ const triggers = this.normalizeTriggers(rawTriggers);
3814
+ if (!triggers.length) return null;
3815
+ const rawTriggerList = Array.isArray(rawTriggers) ? rawTriggers : rawTriggers ? [rawTriggers] : [];
3816
+ const legacyConditions = [
3817
+ ...this.normalizeLegacyConditions(raw.conditions),
3818
+ ...rawTriggerList.flatMap((trigger) => this.normalizeLegacyConditions(trigger.condition))
3819
+ ];
3820
+ const cooldown = this.normalizeCooldown(raw.cooldown);
3821
+ return {
3822
+ ...raw,
3823
+ triggers,
3824
+ cooldown,
3825
+ legacyConditions
3826
+ };
3827
+ }
3828
+ validatePopupDefinitions(defs) {
3829
+ return defs.map((def) => this.normalizePopupDefinition(def)).filter((def) => !!def && this.isPopupDefinition(def));
3830
+ }
3831
+ };
3832
+
3833
+ // src/react-native/setup.ts
3834
+ function mmkvStorage(mmkv) {
3835
+ return {
3836
+ getItem: (k) => mmkv.getString(k) ?? null,
3837
+ setItem: (k, v) => mmkv.set(k, v),
3838
+ removeItem: (k) => mmkv.delete(k)
3839
+ };
3840
+ }
3841
+ function collectRnDevice(d) {
3842
+ return {
3843
+ device_type: d.isTablet?.() ? "tablet" : "mobile",
3844
+ os_version: d.getSystemVersion?.(),
3845
+ device_model: d.getDeviceId?.(),
3846
+ app_version: d.getVersion?.()
3847
+ };
3848
+ }
3849
+ function setupReactNative(sdk, config, deps = {}) {
3850
+ if (deps.renderer) sdk.setRenderer(deps.renderer);
3851
+ const storage = deps.mmkv ? mmkvStorage(deps.mmkv) : config.storage;
3852
+ const device = deps.deviceInfo ? collectRnDevice(deps.deviceInfo) : config.device;
3853
+ const platform = deps.platform ?? config.platform;
3854
+ const backgroundTask = config.backgroundTask ?? deps.backgroundTask ?? void 0;
3855
+ const autoTrack = deps.appState?.addEventListener ? { ...config.autoTrack, lifecycle: false } : config.autoTrack;
3856
+ sdk.init({ ...config, storage, device, platform, backgroundTask, autoTrack });
3857
+ const errorUtils = deps.errorUtils ?? globalThis.ErrorUtils;
3858
+ if (errorUtils && typeof errorUtils.setGlobalHandler === "function") {
3859
+ sdk.installReactNativeCrashHandler(errorUtils);
3860
+ }
3861
+ let subscription;
3862
+ if (deps.appState?.addEventListener) {
3863
+ subscription = deps.appState.addEventListener("change", (state) => {
3864
+ if (state === "active") sdk.onForeground();
3865
+ else if (state === "background") sdk.onBackground();
3866
+ else sdk.onInactive();
3867
+ });
3868
+ }
3869
+ return () => {
3870
+ if (subscription && typeof subscription.remove === "function") subscription.remove();
3871
+ };
3872
+ }
3873
+
3874
+ // src/index.native.ts
3875
+ registerReactNativePlatform({
3876
+ os: Platform.OS,
3877
+ appState: AppState,
3878
+ backgroundTaskModule: NativeModules?.DeepdotsBackgroundTask ?? null
3879
+ });
3880
+ export {
3881
+ BACKGROUND_TASK_MAX_MS,
3882
+ BrowserPopupRenderer,
3883
+ ContactManager,
3884
+ CrashReporter,
3885
+ DeepdotsPopups,
3886
+ InMemoryStorage,
3887
+ LABELS,
3888
+ MAX_TRACKED_MESSAGES,
3889
+ MESSAGE_CHANNELS,
3890
+ MessageGuard,
3891
+ NATIVE_READY_GRACE_MS,
3892
+ NoopPopupRenderer,
3893
+ POPUP_TRIGGER_CONDITION_STATUSES,
3894
+ REVEAL_TIMEOUT_MS,
3895
+ RTL_LOCALES,
3896
+ ReactNativePopupRenderer,
3897
+ SUPPORTED_LANGUAGES,
3898
+ backgroundTimerTask,
3899
+ buildAnalyticsFeedbackBody,
3900
+ buildMessageParams,
3901
+ buildSurveyHtml,
3902
+ collectRnDevice,
3903
+ crashRecordToParams,
3904
+ createDefaultRenderer,
3905
+ createFeedbackSink,
3906
+ directionFor,
3907
+ getLabels,
3908
+ isRtlLanguage,
3909
+ mmkvStorage,
3910
+ resolveActionLabels,
3911
+ resolveLocale,
3912
+ setupReactNative
3913
+ };
3914
+ //# sourceMappingURL=index.native.mjs.map