@magicfeedback/popup-sdk 1.18.0 → 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 +23 -0
  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 +107 -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-DNBFTJCA.mjs → chunk-EW2ARDEY.mjs} +496 -52
  21. package/dist/chunk-EW2ARDEY.mjs.map +1 -0
  22. package/dist/{chunk-7ZVOPIWE.mjs → chunk-XOEEBDBJ.mjs} +535 -11
  23. package/dist/chunk-XOEEBDBJ.mjs.map +1 -0
  24. package/dist/index.d.mts +152 -9
  25. package/dist/index.d.ts +152 -9
  26. package/dist/index.js +7139 -1511
  27. package/dist/index.js.map +1 -1
  28. package/dist/index.mjs +294 -38
  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 +98 -7
  37. package/dist/react-native.d.ts +98 -7
  38. package/dist/react-native.js +5725 -157
  39. package/dist/react-native.js.map +1 -1
  40. package/dist/react-native.mjs +289 -40
  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-B6VIV4VS.mjs → renderPopup-ZHTRMFO2.mjs} +133 -6
  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-7ZVOPIWE.mjs.map +0 -1
  52. package/dist/chunk-DNBFTJCA.mjs.map +0 -1
  53. package/dist/renderPopup-B6VIV4VS.mjs.map +0 -1
  54. package/dist/renderPopup-BKZPAZZG.mjs +0 -3682
  55. package/dist/renderPopup-BKZPAZZG.mjs.map +0 -1
@@ -1,29 +1,38 @@
1
1
  import {
2
+ BUNDLED_SURVEY_SDK_VERSION,
2
3
  BUSY_JS,
3
4
  LABELS,
4
5
  PRIMARY_COLOR_JS,
5
6
  RESOLVE_LOCALE_JS,
6
7
  REVEAL_TIMEOUT_MS,
7
8
  RTL_LOCALES,
9
+ SDK_IDENTIFIER,
8
10
  STORAGE_KEYS,
9
11
  SUBMIT_ERROR_JS,
10
12
  TrackingManager,
11
- __require,
12
13
  buildFontFaceCss,
13
14
  buildFontFamilyValue,
14
15
  buildSurveyIdentity,
16
+ chooseSurveySdkVersion,
15
17
  createDefaultStorage,
18
+ describeSurveySdkChoice,
16
19
  directionFor,
17
20
  getLabels,
18
21
  resolveActionLabels,
22
+ sdkLog,
19
23
  sdkWarn,
20
24
  setLogger,
21
- style_default
22
- } from "./chunk-7ZVOPIWE.mjs";
25
+ style_default,
26
+ surveySdkCssUrls,
27
+ surveySdkUrls
28
+ } from "./chunk-EW2ARDEY.mjs";
29
+ import {
30
+ __require
31
+ } from "./chunk-BJTO5JO5.mjs";
23
32
 
24
33
  // src/react-native/index.tsx
25
34
  import { createContext, useContext, useEffect, useRef, useState } from "react";
26
- import { AppState, Modal, Platform, View } from "react-native";
35
+ import { AppState, Modal, NativeModules, Platform, View } from "react-native";
27
36
  import { WebView } from "react-native-webview";
28
37
 
29
38
  // src/types/index.ts
@@ -60,7 +69,7 @@ function setupTrigger(popups, trigger) {
60
69
  function setupTimeTrigger(popups, trigger) {
61
70
  const delay = toNumericValue(trigger.value, 5e3);
62
71
  setTimeout(() => {
63
- popups.triggerSurvey(trigger.surveyId, trigger.popupId);
72
+ popups.triggerSurvey(trigger.surveyId, trigger.popupId, { delaySeconds: trigger.delaySeconds });
64
73
  }, delay);
65
74
  popups.debug(`Time trigger set for ${delay}ms`);
66
75
  }
@@ -69,7 +78,7 @@ function setupScrollTrigger(popups, trigger) {
69
78
  const handler = () => {
70
79
  const scrollPercentage = window.scrollY / (document.documentElement.scrollHeight - window.innerHeight) * 100;
71
80
  if (scrollPercentage >= threshold) {
72
- popups.triggerSurvey(trigger.surveyId, trigger.popupId);
81
+ popups.triggerSurvey(trigger.surveyId, trigger.popupId, { delaySeconds: trigger.delaySeconds });
73
82
  window.removeEventListener("scroll", handler);
74
83
  }
75
84
  };
@@ -78,7 +87,7 @@ function setupScrollTrigger(popups, trigger) {
78
87
  }
79
88
  function setupExitTrigger(popups, trigger) {
80
89
  if (typeof window === "undefined") return;
81
- const delaySeconds = parseExitDelaySeconds(trigger.value);
90
+ const delaySeconds = typeof trigger.delaySeconds === "number" && trigger.delaySeconds > 0 ? trigger.delaySeconds : parseExitDelaySeconds(trigger.value);
82
91
  const historyRef = window.history;
83
92
  const originalPushState = historyRef.pushState.bind(historyRef);
84
93
  const originalReplaceState = historyRef.replaceState.bind(historyRef);
@@ -189,7 +198,7 @@ function setupClickTrigger(popups, trigger) {
189
198
  }
190
199
  const handler = (e) => {
191
200
  if (e.defaultPrevented) return;
192
- popups.triggerSurvey(trigger.surveyId, trigger.popupId);
201
+ popups.triggerSurvey(trigger.surveyId, trigger.popupId, { delaySeconds: trigger.delaySeconds });
193
202
  el.removeEventListener("click", handler);
194
203
  };
195
204
  el.addEventListener("click", handler);
@@ -257,8 +266,9 @@ function trimmedOrNull(value) {
257
266
  }
258
267
  function buildSurveyHtml(opts) {
259
268
  const env = opts.env === "development" ? "dev" : "prod";
260
- const version = opts.version ?? "2.2.37";
261
- const cdn = `https://cdn.jsdelivr.net/npm/@magicfeedback/native@${version}/dist/magicfeedback-sdk.browser.js`;
269
+ const version = opts.version ?? BUNDLED_SURVEY_SDK_VERSION;
270
+ const assigned = version !== BUNDLED_SURVEY_SDK_VERSION ? { version, css: surveySdkCssUrls(version), js: surveySdkUrls(version) } : null;
271
+ const bundledJs = surveySdkUrls(BUNDLED_SURVEY_SDK_VERSION);
262
272
  const sid = jsonForScript(opts.surveyId);
263
273
  const pid = jsonForScript(opts.productId);
264
274
  const profileJson = jsonForScript(opts.profile ?? []);
@@ -310,8 +320,10 @@ function buildSurveyHtml(opts) {
310
320
  return `<!DOCTYPE html><html><head>
311
321
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
312
322
  <meta name="color-scheme" content="${colorScheme}"/>
313
- <style>
323
+ <style id="dd-survey-css">
314
324
  ${style_default}
325
+ </style>
326
+ <style>
315
327
  ${fontFaceCss}
316
328
  html,body{margin:0;padding:0;height:100%;font-family:${fontFamilyValue}}
317
329
  /* Apertura diferida: ni la tarjeta ni el velo se pintan hasta que el survey est\xE1 listo
@@ -765,9 +777,9 @@ ${REVEAL_JS}
765
777
  if(p && p.error){
766
778
  setLoading(false);
767
779
  var ddErr=ddClassifySubmitError(p.error);
768
- if(ddErr.reason==='required'){
780
+ if(ddErr.reason==='required' || ddErr.reason==='invalid_email'){
769
781
  // La p\xE1gina no ha cambiado: el estado de navegaci\xF3n se queda como estaba.
770
- errorHint.textContent=DD_LABELS_ACTIVE.errorRequired;
782
+ errorHint.textContent=ddErr.reason==='invalid_email' ? DD_LABELS_ACTIVE.errorInvalidEmail : DD_LABELS_ACTIVE.errorRequired;
771
783
  errorHint.style.display='block';
772
784
  updateNavButtons();
773
785
  return;
@@ -808,10 +820,46 @@ ${REVEAL_JS}
808
820
  }catch(e){ ddShowLoadError('error:exception', e); }
809
821
  return true;
810
822
  }
811
- var s=document.createElement('script'); s.src=${JSON.stringify(cdn)}; s.async=true;
812
- s.onload=function(){ initMF(); };
813
- s.onerror=function(){ ddShowLoadError('error:load', 'survey script failed to load'); };
814
- document.head.appendChild(s);
823
+ // DD-70: versi\xF3n asignada (hoja + JS) y, si algo falla, la empaquetada (hoja + JS).
824
+ var ddAssigned=${jsonForScript(assigned)}, ddBundledJs=${jsonForScript(bundledJs)};
825
+ var ddCssEl=document.getElementById('dd-survey-css'), ddBundledCss=ddCssEl?ddCssEl.textContent:'';
826
+ function ddMark(v){ try{ document.documentElement.setAttribute('data-survey-sdk', v); }catch(_){} }
827
+ function ddLoadScripts(urls, i, onFail){
828
+ if(i>=urls.length){ onFail(); return; }
829
+ var s=document.createElement('script'); s.src=urls[i]; s.async=true;
830
+ s.onload=function(){ initMF(); };
831
+ s.onerror=function(){
832
+ try{ console.warn('[Deepdots] survey SDK failed from '+urls[i]); }catch(_){}
833
+ ddLoadScripts(urls, i+1, onFail);
834
+ };
835
+ document.head.appendChild(s);
836
+ }
837
+ function ddLoadBundled(){
838
+ if(ddCssEl){ ddCssEl.textContent=ddBundledCss; }
839
+ ddMark(${jsonForScript(BUNDLED_SURVEY_SDK_VERSION + " bundled")});
840
+ ddLoadScripts(ddBundledJs, 0, function(){ ddShowLoadError('error:load', 'survey script failed to load'); });
841
+ }
842
+ function ddFetchCss(urls, i, ok, fail){
843
+ if(i>=urls.length || typeof fetch!=='function'){ fail(); return; }
844
+ fetch(urls[i]).then(function(r){ if(!r.ok) throw new Error('HTTP '+r.status); return r.text(); })
845
+ .then(function(css){ if(!css) throw new Error('empty'); ok(css); })
846
+ .catch(function(){ ddFetchCss(urls, i+1, ok, fail); });
847
+ }
848
+ if(ddAssigned){
849
+ ddFetchCss(ddAssigned.css, 0, function(css){
850
+ if(ddCssEl){ ddCssEl.textContent=css; }
851
+ ddMark(ddAssigned.version+' assigned');
852
+ ddLoadScripts(ddAssigned.js, 0, function(){
853
+ try{ console.warn('[Deepdots] survey SDK '+ddAssigned.version+' failed, using bundled'); }catch(_){}
854
+ ddLoadBundled();
855
+ });
856
+ }, function(){
857
+ try{ console.warn('[Deepdots] survey CSS '+ddAssigned.version+' failed, using bundled'); }catch(_){}
858
+ ddLoadBundled();
859
+ });
860
+ } else {
861
+ ddLoadBundled();
862
+ }
815
863
  var tries=0, t=setInterval(function(){ if(initMF()||++tries>40){ clearInterval(t); } },150);
816
864
  })();
817
865
  </script>
@@ -840,9 +888,12 @@ var ReactNativePopupRenderer = class {
840
888
  this.readyEmitted = false;
841
889
  this.armReadyFallback(surveyId);
842
890
  const { profile, metadata } = buildSurveyIdentity(userId ?? null, sessionId ?? null, miniService ?? null, analyticsFeedbackSessionId ?? null);
891
+ const surveySdk = chooseSurveySdkVersion(options?.surveySdkVersion);
892
+ logRnSurveySdkChoice(surveySdk, options?.debug);
843
893
  const html = buildSurveyHtml({
844
894
  surveyId,
845
895
  productId,
896
+ version: surveySdk.version,
846
897
  env,
847
898
  profile,
848
899
  metadata,
@@ -942,9 +993,14 @@ function isReactNativeEnv() {
942
993
  function createReactNativeRenderer() {
943
994
  return new ReactNativePopupRenderer();
944
995
  }
996
+ function logRnSurveySdkChoice(choice, debug) {
997
+ const problem = choice.source === "bundled" && choice.reason === "invalid";
998
+ if (problem) sdkWarn(`[Deepdots] ${describeSurveySdkChoice(choice)}`);
999
+ else if (debug) sdkLog(`[Deepdots] ${describeSurveySdkChoice(choice)}`);
1000
+ }
945
1001
 
946
1002
  // src/ui/preload.ts
947
- var defaultLoader = () => import("./renderPopup-B6VIV4VS.mjs");
1003
+ var defaultLoader = () => import("./renderPopup-ZHTRMFO2.mjs");
948
1004
  var pending = null;
949
1005
  function preloadRenderPopup(loader = defaultLoader) {
950
1006
  if (pending) return pending;
@@ -1017,7 +1073,7 @@ var BrowserPopupRenderer = class {
1017
1073
  if (!this.container) return;
1018
1074
  this.visible = true;
1019
1075
  const container = this.container;
1020
- void import("./renderPopup-B6VIV4VS.mjs").then(
1076
+ void import("./renderPopup-ZHTRMFO2.mjs").then(
1021
1077
  ({ renderPopup }) => {
1022
1078
  renderPopup(container, surveyId, productId, actions, emit, onClose, env, userId, style, sessionId, miniService, analyticsFeedbackSessionId, options);
1023
1079
  },
@@ -1181,6 +1237,7 @@ var AnalyticsManager = class {
1181
1237
  sessionId: identity.sessionId,
1182
1238
  context: {
1183
1239
  platform: this.platform,
1240
+ sdk: SDK_IDENTIFIER,
1184
1241
  language: this.language,
1185
1242
  device: this.device,
1186
1243
  attributes: { ...this.attributes },
@@ -1228,6 +1285,34 @@ var AnalyticsManager = class {
1228
1285
  }
1229
1286
  };
1230
1287
 
1288
+ // src/analytics/background-task.ts
1289
+ var BACKGROUND_TASK_MAX_MS = 25e3;
1290
+ async function runInBackgroundTask(begin, name, work, maxMs = BACKGROUND_TASK_MAX_MS) {
1291
+ let end;
1292
+ try {
1293
+ end = begin?.(name);
1294
+ } catch {
1295
+ end = void 0;
1296
+ }
1297
+ if (typeof end !== "function") return work();
1298
+ let ended = false;
1299
+ const finish = () => {
1300
+ if (ended) return;
1301
+ ended = true;
1302
+ clearTimeout(timer);
1303
+ try {
1304
+ end();
1305
+ } catch {
1306
+ }
1307
+ };
1308
+ const timer = setTimeout(finish, maxMs);
1309
+ try {
1310
+ return await work();
1311
+ } finally {
1312
+ finish();
1313
+ }
1314
+ }
1315
+
1231
1316
  // src/analytics/feedback-payload.ts
1232
1317
  function pushKV(list, key, value) {
1233
1318
  if (value === void 0 || value === null || value === "") return;
@@ -1241,6 +1326,7 @@ function buildAnalyticsFeedbackBody(envelope, keys, feedbackSessionId, options)
1241
1326
  pushKV(metadata, "deepdots_user_id", envelope.userId);
1242
1327
  pushKV(metadata, "deepdots_session_id", envelope.sessionId);
1243
1328
  pushKV(metadata, "deepdots_platform", context.platform);
1329
+ pushKV(metadata, "deepdots_sdk", context.sdk);
1244
1330
  pushKV(metadata, "deepdots_language", context.language);
1245
1331
  if (context.device) {
1246
1332
  const d = context.device;
@@ -1439,7 +1525,9 @@ function createFeedbackSink(options) {
1439
1525
  savePending();
1440
1526
  setTimeout(() => void drain(), 0);
1441
1527
  }
1442
- return async (envelope, meta) => {
1528
+ const sink = (envelope, meta) => runInBackgroundTask(options.backgroundTask, "deepdots-analytics", () => deliver(envelope, meta));
1529
+ return sink;
1530
+ async function deliver(envelope, meta) {
1443
1531
  if (meta?.resetSession) {
1444
1532
  feedbackSessionId = void 0;
1445
1533
  options.onSessionReset?.();
@@ -1460,7 +1548,7 @@ function createFeedbackSink(options) {
1460
1548
  }
1461
1549
  const retries = pending2.length ? drain() : null;
1462
1550
  await Promise.all([retries, send(batch, final, false)]);
1463
- };
1551
+ }
1464
1552
  }
1465
1553
 
1466
1554
  // src/analytics/suspended-session.ts
@@ -2056,6 +2144,36 @@ function clearPopupState(storage) {
2056
2144
  }
2057
2145
  }
2058
2146
 
2147
+ // src/platform/react-native-platform.ts
2148
+ var registered = null;
2149
+ function registerReactNativePlatform(platform) {
2150
+ registered = platform;
2151
+ }
2152
+ function getReactNativePlatform() {
2153
+ return registered;
2154
+ }
2155
+ function nativeModuleTask(mod) {
2156
+ let seq = 0;
2157
+ return (name) => {
2158
+ const token = `dd-${Date.now().toString(36)}-${(seq++).toString(36)}`;
2159
+ mod.begin(token, name);
2160
+ let ended = false;
2161
+ return () => {
2162
+ if (ended) return;
2163
+ ended = true;
2164
+ mod.end(token);
2165
+ };
2166
+ };
2167
+ }
2168
+ function resolveBackgroundTask(explicit, platform) {
2169
+ if (explicit) return explicit;
2170
+ const mod = platform?.backgroundTaskModule;
2171
+ if (platform?.os === "ios" && mod && typeof mod.begin === "function" && typeof mod.end === "function") {
2172
+ return nativeModuleTask(mod);
2173
+ }
2174
+ return void 0;
2175
+ }
2176
+
2059
2177
  // src/analytics/messaging.ts
2060
2178
  var MESSAGE_CHANNELS = ["push", "in_app"];
2061
2179
  function buildMessageParams(stage, o) {
@@ -2135,6 +2253,10 @@ var ANALYTICS_RESUME_WINDOW_MS = 6e4;
2135
2253
  var RESERVED_EVENT_PREFIX = "deepdots_";
2136
2254
  var CUSTOM_EVENT_PREFIX = "deepdots_event_";
2137
2255
  var MAX_PENDING_TRIGGERS = 20;
2256
+ function triggerDelayMs(delaySeconds) {
2257
+ const n = typeof delaySeconds === "number" ? delaySeconds : Number(delaySeconds);
2258
+ return Number.isFinite(n) && n > 0 ? Math.round(n * 1e3) : 0;
2259
+ }
2138
2260
  var DeepdotsPopups = class {
2139
2261
  constructor() {
2140
2262
  this.config = null;
@@ -2166,6 +2288,10 @@ var DeepdotsPopups = class {
2166
2288
  this.surveyToPopupId = /* @__PURE__ */ new Map();
2167
2289
  // surveyId -> popupId
2168
2290
  this.deferredExitTimers = [];
2291
+ /** Popups esperando su `delaySeconds` (uno por popup). */
2292
+ this.delayedPopups = /* @__PURE__ */ new Map();
2293
+ /** Última pantalla de `setScreen` (React Native). */
2294
+ this.currentScreen = null;
2169
2295
  this.baseUrl = "";
2170
2296
  this.env = "production";
2171
2297
  /** Si el SDK pinta el "modal" del popup (RN). Default true; false = el host lo envuelve. */
@@ -2211,6 +2337,8 @@ var DeepdotsPopups = class {
2211
2337
  this.lastEngagementAt = 0;
2212
2338
  /** Cuándo se ocultó la pestaña por última vez (ms epoch); null si está visible. */
2213
2339
  this.hiddenAt = null;
2340
+ /** Suscripción automática a AppState (React Native, `autoTrack.lifecycle`). */
2341
+ this.appStateSubscription = void 0;
2214
2342
  /**
2215
2343
  * Sesión suspendida por un `pagehide` (ms epoch y `deepdots_user_id`); null si no hay.
2216
2344
  * `openSession` la reanuda si sigue a tiempo (ver ANALYTICS_RESUME_WINDOW_MS).
@@ -2243,6 +2371,10 @@ var DeepdotsPopups = class {
2243
2371
  this.log("SDK already initialized");
2244
2372
  return;
2245
2373
  }
2374
+ const rn = getReactNativePlatform();
2375
+ if (!config.platform && (rn?.os === "ios" || rn?.os === "android")) {
2376
+ config = { ...config, platform: rn.os };
2377
+ }
2246
2378
  const env = resolveEnvironment(config.nodeEnv);
2247
2379
  this.baseUrl = env.apiBaseUrl;
2248
2380
  this.env = config.nodeEnv || "production";
@@ -2293,6 +2425,10 @@ var DeepdotsPopups = class {
2293
2425
  // persiste y se reenvía en el arranque siguiente. En web el cierre sale con
2294
2426
  // `keepalive` y varias pestañas compartirían el mismo storage.
2295
2427
  storage: (config.platform ?? "web") !== "web" ? storage : void 0,
2428
+ // iOS suspende la app con el POST de cierre en vuelo: el host puede darle
2429
+ // tiempo de background (DD-55). El reenvío del arranque siguiente sigue igual.
2430
+ // La del host o, en iOS, la del módulo nativo del paquete (autolinking).
2431
+ backgroundTask: resolveBackgroundTask(config.backgroundTask, rn),
2296
2432
  onSessionId: (id) => {
2297
2433
  this.analyticsFeedbackSessionId = id;
2298
2434
  this.notifyFeedbackSession(id, "open");
@@ -2350,6 +2486,7 @@ var DeepdotsPopups = class {
2350
2486
  }
2351
2487
  }
2352
2488
  this.initialized = true;
2489
+ this.installAutoLifecycle(rn, config);
2353
2490
  this.log("SDK initialized", this.config);
2354
2491
  if (this.renderer.init) this.renderer.init();
2355
2492
  this.awaitingPopups = Boolean(this.config.apiKey && this.baseUrl);
@@ -2520,6 +2657,11 @@ var DeepdotsPopups = class {
2520
2657
  * El host la llama en cada cambio de pantalla; emite `page_view` al salir de la anterior.
2521
2658
  */
2522
2659
  setScreen(name) {
2660
+ const screen2 = typeof name === "string" ? name.trim() : "";
2661
+ if (screen2) {
2662
+ this.cancelDelayedPopups("screen change", (entry) => entry.screen !== screen2);
2663
+ this.currentScreen = screen2;
2664
+ }
2523
2665
  if (!this.navObserver) return;
2524
2666
  if (!this.navStarted) {
2525
2667
  this.navObserver.begin(name);
@@ -2541,9 +2683,42 @@ var DeepdotsPopups = class {
2541
2683
  * Es la única señal disponible en móvil: el kill de la app (swipe) NO da callback.
2542
2684
  */
2543
2685
  onBackground() {
2686
+ this.cancelDelayedPopups("app to background");
2544
2687
  this.closeSession("background");
2545
2688
  this.engagement?.pause();
2546
2689
  }
2690
+ /**
2691
+ * App a `inactive` (RN, iOS: centro de control, llamada, app switcher, y SIEMPRE justo antes
2692
+ * de `background`). NO cierra la sesión (es transitorio), pero envía lo acumulado con un
2693
+ * `user_engagement` que lleva la pantalla en curso, como web al ocultar la pestaña: si el
2694
+ * lote de cierre de `background` no llega a salir (iOS suspende la app), el backend ya
2695
+ * tiene el tiempo activo y la última pantalla. El contador sigue en marcha.
2696
+ */
2697
+ onInactive() {
2698
+ if (this.sessionOpen) this.flushEngagement();
2699
+ this.flushAnalytics();
2700
+ }
2701
+ /**
2702
+ * Ciclo de vida automático en React Native (contrato de detección automática): el SDK escucha
2703
+ * AppState él mismo, así que el host no tiene que llamar a `onForeground`/`onInactive`/
2704
+ * `onBackground`. Si el host los llama además (integraciones anteriores), no se duplica nada:
2705
+ * abrir o cerrar una sesión ya abierta o cerrada no hace nada, y el engagement se consume.
2706
+ * `autoTrack.lifecycle: false` lo apaga.
2707
+ */
2708
+ installAutoLifecycle(rn, config) {
2709
+ if (config.autoTrack?.lifecycle === false) return;
2710
+ const appState = rn?.appState;
2711
+ if (!appState || typeof appState.addEventListener !== "function" || this.appStateSubscription) return;
2712
+ try {
2713
+ this.appStateSubscription = appState.addEventListener("change", (state) => {
2714
+ if (state === "active") this.onForeground();
2715
+ else if (state === "background") this.onBackground();
2716
+ else this.onInactive();
2717
+ });
2718
+ this.log("lifecycle \xB7 AppState wired automatically");
2719
+ } catch {
2720
+ }
2721
+ }
2547
2722
  /**
2548
2723
  * Cierre EXPLÍCITO de la sesión por parte del host (logout, fin de flujo…): emite
2549
2724
  * `session_end` y envía el último lote con `completed:true`.
@@ -2884,16 +3059,21 @@ var DeepdotsPopups = class {
2884
3059
  return;
2885
3060
  }
2886
3061
  const value = type === "time" && typeof trigger.value === "number" ? trigger.value * 1e3 : trigger.value;
2887
- derived.push({ type, value, surveyId: def.surveyId, popupId: def.id });
3062
+ derived.push({ type, value, surveyId: def.surveyId, popupId: def.id, delaySeconds: trigger.delaySeconds });
2888
3063
  });
2889
3064
  });
2890
3065
  if (derived.length) {
2891
3066
  this.configureTriggers(derived);
2892
3067
  }
2893
3068
  }
2894
- /** Lógica para evaluar condiciones antes de mostrar una encuesta */
2895
- triggerSurvey(surveyId, popupId) {
2896
- if (this.bufferIfAwaitingPopups({ kind: "survey", surveyId, popupId })) return;
3069
+ /**
3070
+ * Lógica para evaluar condiciones antes de mostrar una encuesta. `options.delaySeconds`
3071
+ * (lo pasan los triggers time/scroll/click con el "Delay" del Admin) espera ese tiempo y
3072
+ * vuelve a evaluar antes de mostrar; sin él, al momento como siempre.
3073
+ */
3074
+ triggerSurvey(surveyId, popupId, options) {
3075
+ const delaySeconds = options?.delaySeconds;
3076
+ if (this.bufferIfAwaitingPopups({ kind: "survey", surveyId, popupId, delaySeconds })) return;
2897
3077
  const def = this.findPopupDefinition(surveyId, popupId);
2898
3078
  if (!def) {
2899
3079
  this.debug("No popup definition for trigger", { surveyId, popupId });
@@ -2903,7 +3083,7 @@ var DeepdotsPopups = class {
2903
3083
  this.debug("Conditions prevented showing popup", def.id);
2904
3084
  return;
2905
3085
  }
2906
- this.showDefinition(def);
3086
+ this.showAfterDelay(def, delaySeconds);
2907
3087
  }
2908
3088
  /** Trigger popups configured with trigger.type = 'event' and matching trigger.value */
2909
3089
  triggerEvent(eventName) {
@@ -2920,9 +3100,9 @@ var DeepdotsPopups = class {
2920
3100
  }
2921
3101
  evaluateEvent(normalized) {
2922
3102
  const candidates = this.popupDefinitions.filter((def) => {
2923
- return def.triggers.some((trigger) => {
2924
- const triggerValue = String(trigger.value ?? "").trim();
2925
- return trigger.type === "event" && triggerValue === normalized;
3103
+ return def.triggers.some((trigger2) => {
3104
+ const triggerValue = String(trigger2.value ?? "").trim();
3105
+ return trigger2.type === "event" && triggerValue === normalized;
2926
3106
  });
2927
3107
  });
2928
3108
  if (!candidates.length) {
@@ -2934,7 +3114,69 @@ var DeepdotsPopups = class {
2934
3114
  this.debug("Event popup blocked by conditions/segments", { eventName: normalized });
2935
3115
  return;
2936
3116
  }
2937
- this.showDefinition(matched);
3117
+ const trigger = matched.triggers.find(
3118
+ (t) => t.type === "event" && String(t.value ?? "").trim() === normalized
3119
+ );
3120
+ this.showAfterDelay(matched, trigger?.delaySeconds);
3121
+ }
3122
+ /**
3123
+ * Muestra `def` ya, o tras su "Delay (seconds)" del Admin. Mientras espera:
3124
+ * - el mismo popup no se programa dos veces (el primer vencimiento manda);
3125
+ * - cambiar de ruta/pantalla o pasar a background lo cancela;
3126
+ * y al vencer se vuelve a evaluar todo (segmentos, idioma, cooldowns) como un disparo nuevo.
3127
+ * Si entonces hay otro popup abierto, `showDefinition` lo salta sin efectos, igual que hoy.
3128
+ */
3129
+ showAfterDelay(def, delaySeconds) {
3130
+ const delayMs = triggerDelayMs(delaySeconds);
3131
+ if (delayMs <= 0) {
3132
+ this.showDefinition(def);
3133
+ return;
3134
+ }
3135
+ if (this.delayedPopups.has(def.id)) {
3136
+ this.debug("Popup already waiting for its delay", def.id);
3137
+ return;
3138
+ }
3139
+ const entry = {
3140
+ popupId: def.id,
3141
+ timer: setTimeout(() => this.showDelayedPopup(def.id), delayMs),
3142
+ firedAt: Date.now(),
3143
+ href: this.currentHref(),
3144
+ screen: this.currentScreen
3145
+ };
3146
+ this.delayedPopups.set(def.id, entry);
3147
+ this.debug(`Popup delayed ${delayMs}ms`, def.id);
3148
+ }
3149
+ showDelayedPopup(popupId) {
3150
+ const entry = this.delayedPopups.get(popupId);
3151
+ if (!entry) return;
3152
+ this.delayedPopups.delete(popupId);
3153
+ const def = this.popupDefinitions.find((popup) => popup.id === popupId);
3154
+ if (!def) return;
3155
+ if (this.currentHref() !== entry.href || this.currentScreen !== entry.screen) {
3156
+ this.debug("Delayed popup dropped: route changed", popupId);
3157
+ return;
3158
+ }
3159
+ if (!this.shouldShow(def)) {
3160
+ this.debug("Delayed popup dropped by conditions at due time", popupId);
3161
+ return;
3162
+ }
3163
+ if ((this.lastShown.get(popupId) ?? 0) >= entry.firedAt) {
3164
+ this.debug("Delayed popup dropped: already shown while waiting", popupId);
3165
+ return;
3166
+ }
3167
+ this.showDefinition(def);
3168
+ }
3169
+ cancelDelayedPopups(reason, predicate = () => true) {
3170
+ this.delayedPopups.forEach((entry, popupId) => {
3171
+ if (!predicate(entry)) return;
3172
+ clearTimeout(entry.timer);
3173
+ this.delayedPopups.delete(popupId);
3174
+ this.debug(`Delayed popup cancelled (${reason})`, popupId);
3175
+ });
3176
+ }
3177
+ currentHref() {
3178
+ if (typeof window === "undefined" || !window.location) return "";
3179
+ return this.normalizeUrl(window.location.href || "");
2938
3180
  }
2939
3181
  /**
2940
3182
  * Guarda `trigger` si las definiciones aún no han llegado. Devuelve `true` si lo guardó (el
@@ -2967,7 +3209,7 @@ var DeepdotsPopups = class {
2967
3209
  this.debug("Replaying triggers received before popups loaded", replay.length);
2968
3210
  replay.forEach((trigger) => {
2969
3211
  if (trigger.kind === "event") this.evaluateEvent(trigger.name);
2970
- else this.triggerSurvey(trigger.surveyId, trigger.popupId);
3212
+ else this.triggerSurvey(trigger.surveyId, trigger.popupId, { delaySeconds: trigger.delaySeconds });
2971
3213
  });
2972
3214
  }
2973
3215
  showDefinition(def) {
@@ -2979,7 +3221,7 @@ var DeepdotsPopups = class {
2979
3221
  this.surveyToPopupId.set(def.surveyId, def.id);
2980
3222
  this.lastShown.set(def.id, Date.now());
2981
3223
  this.persistPopupState();
2982
- this.renderPopup(def.surveyId, def.productId, def.actions, def.style, def.title);
3224
+ this.renderPopup(def.surveyId, def.productId, def.actions, def.style, def.title, def.surveyFrontend?.sdkVersion);
2983
3225
  this.emitEvent("popup_shown", def.surveyId, { popupId: def.id });
2984
3226
  }
2985
3227
  shouldShow(def, pathUrl, skipPathCheck = false) {
@@ -3351,7 +3593,7 @@ var DeepdotsPopups = class {
3351
3593
  }
3352
3594
  }
3353
3595
  /** Render the popup UI */
3354
- renderPopup(surveyId, productId, actions, style, title) {
3596
+ renderPopup(surveyId, productId, actions, style, title, surveySdkVersion) {
3355
3597
  const userId = this.tracking?.getUserId() ?? this.config?.userId;
3356
3598
  const sessionId = this.tracking?.getSessionId() ?? void 0;
3357
3599
  const miniService = this.analytics?.getMiniService() ?? void 0;
@@ -3370,7 +3612,7 @@ var DeepdotsPopups = class {
3370
3612
  miniService,
3371
3613
  analyticsFeedbackSessionId,
3372
3614
  this.renderChrome,
3373
- { title, showProgressBar: this.showProgressBar, surveyCss: this.surveyCss, language: this.language, cspNonce: this.cspNonce }
3615
+ { title, showProgressBar: this.showProgressBar, surveyCss: this.surveyCss, language: this.language, cspNonce: this.cspNonce, surveySdkVersion, debug: this.config?.debug }
3374
3616
  );
3375
3617
  }
3376
3618
  /** Hide the popup */
@@ -3537,10 +3779,10 @@ var DeepdotsPopups = class {
3537
3779
  }
3538
3780
  normalizeTriggers(value) {
3539
3781
  const items = Array.isArray(value) ? value : value ? [value] : [];
3540
- return items.filter((trigger) => this.isPopupTrigger(trigger)).map((trigger) => ({
3541
- type: trigger.type,
3542
- value: trigger.value
3543
- }));
3782
+ return items.filter((trigger) => this.isPopupTrigger(trigger)).map((trigger) => {
3783
+ const delayMs = triggerDelayMs(trigger.delaySeconds);
3784
+ return delayMs > 0 ? { type: trigger.type, value: trigger.value, delaySeconds: delayMs / 1e3 } : { type: trigger.type, value: trigger.value };
3785
+ });
3544
3786
  }
3545
3787
  normalizeCooldown(value) {
3546
3788
  if (!Array.isArray(value)) return [];
@@ -3595,7 +3837,9 @@ function setupReactNative(sdk2, config, deps = {}) {
3595
3837
  const storage = deps.mmkv ? mmkvStorage(deps.mmkv) : config.storage;
3596
3838
  const device = deps.deviceInfo ? collectRnDevice(deps.deviceInfo) : config.device;
3597
3839
  const platform = deps.platform ?? config.platform;
3598
- sdk2.init({ ...config, storage, device, platform });
3840
+ const backgroundTask = config.backgroundTask ?? deps.backgroundTask ?? void 0;
3841
+ const autoTrack = deps.appState?.addEventListener ? { ...config.autoTrack, lifecycle: false } : config.autoTrack;
3842
+ sdk2.init({ ...config, storage, device, platform, backgroundTask, autoTrack });
3599
3843
  const errorUtils = deps.errorUtils ?? globalThis.ErrorUtils;
3600
3844
  if (errorUtils && typeof errorUtils.setGlobalHandler === "function") {
3601
3845
  sdk2.installReactNativeCrashHandler(errorUtils);
@@ -3605,7 +3849,7 @@ function setupReactNative(sdk2, config, deps = {}) {
3605
3849
  subscription = deps.appState.addEventListener("change", (state) => {
3606
3850
  if (state === "active") sdk2.onForeground();
3607
3851
  else if (state === "background") sdk2.onBackground();
3608
- else sdk2.flushAnalytics();
3852
+ else sdk2.onInactive();
3609
3853
  });
3610
3854
  }
3611
3855
  return () => {
@@ -3615,6 +3859,11 @@ function setupReactNative(sdk2, config, deps = {}) {
3615
3859
 
3616
3860
  // src/react-native/index.tsx
3617
3861
  import { jsx, jsxs } from "react/jsx-runtime";
3862
+ registerReactNativePlatform({
3863
+ os: Platform.OS,
3864
+ appState: AppState,
3865
+ backgroundTaskModule: NativeModules?.DeepdotsBackgroundTask ?? null
3866
+ });
3618
3867
  var sdk = new DeepdotsPopups();
3619
3868
  var DeepdotsContext = createContext(sdk);
3620
3869
  var useDeepdots = () => useContext(DeepdotsContext);