@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
package/dist/index.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import {
2
+ BUNDLED_SURVEY_SDK_VERSION,
2
3
  BUSY_JS,
3
4
  InMemoryStorage,
4
5
  LABELS,
@@ -6,6 +7,7 @@ import {
6
7
  RESOLVE_LOCALE_JS,
7
8
  REVEAL_TIMEOUT_MS,
8
9
  RTL_LOCALES,
10
+ SDK_IDENTIFIER,
9
11
  STORAGE_KEYS,
10
12
  SUBMIT_ERROR_JS,
11
13
  SUPPORTED_LANGUAGES,
@@ -13,16 +15,22 @@ import {
13
15
  buildFontFaceCss,
14
16
  buildFontFamilyValue,
15
17
  buildSurveyIdentity,
18
+ chooseSurveySdkVersion,
16
19
  createDefaultStorage,
20
+ describeSurveySdkChoice,
17
21
  directionFor,
18
22
  getLabels,
19
23
  isRtlLanguage,
20
24
  resolveActionLabels,
21
25
  resolveLocale,
26
+ sdkLog,
22
27
  sdkWarn,
23
28
  setLogger,
24
- style_default
25
- } from "./chunk-DNBFTJCA.mjs";
29
+ style_default,
30
+ surveySdkCssUrls,
31
+ surveySdkUrls
32
+ } from "./chunk-XOEEBDBJ.mjs";
33
+ import "./chunk-3QS3WKRC.mjs";
26
34
 
27
35
  // src/types/index.ts
28
36
  var POPUP_TRIGGER_CONDITION_STATUSES = [
@@ -58,7 +66,7 @@ function setupTrigger(popups, trigger) {
58
66
  function setupTimeTrigger(popups, trigger) {
59
67
  const delay = toNumericValue(trigger.value, 5e3);
60
68
  setTimeout(() => {
61
- popups.triggerSurvey(trigger.surveyId, trigger.popupId);
69
+ popups.triggerSurvey(trigger.surveyId, trigger.popupId, { delaySeconds: trigger.delaySeconds });
62
70
  }, delay);
63
71
  popups.debug(`Time trigger set for ${delay}ms`);
64
72
  }
@@ -67,7 +75,7 @@ function setupScrollTrigger(popups, trigger) {
67
75
  const handler = () => {
68
76
  const scrollPercentage = window.scrollY / (document.documentElement.scrollHeight - window.innerHeight) * 100;
69
77
  if (scrollPercentage >= threshold) {
70
- popups.triggerSurvey(trigger.surveyId, trigger.popupId);
78
+ popups.triggerSurvey(trigger.surveyId, trigger.popupId, { delaySeconds: trigger.delaySeconds });
71
79
  window.removeEventListener("scroll", handler);
72
80
  }
73
81
  };
@@ -76,7 +84,7 @@ function setupScrollTrigger(popups, trigger) {
76
84
  }
77
85
  function setupExitTrigger(popups, trigger) {
78
86
  if (typeof window === "undefined") return;
79
- const delaySeconds = parseExitDelaySeconds(trigger.value);
87
+ const delaySeconds = typeof trigger.delaySeconds === "number" && trigger.delaySeconds > 0 ? trigger.delaySeconds : parseExitDelaySeconds(trigger.value);
80
88
  const historyRef = window.history;
81
89
  const originalPushState = historyRef.pushState.bind(historyRef);
82
90
  const originalReplaceState = historyRef.replaceState.bind(historyRef);
@@ -187,7 +195,7 @@ function setupClickTrigger(popups, trigger) {
187
195
  }
188
196
  const handler = (e) => {
189
197
  if (e.defaultPrevented) return;
190
- popups.triggerSurvey(trigger.surveyId, trigger.popupId);
198
+ popups.triggerSurvey(trigger.surveyId, trigger.popupId, { delaySeconds: trigger.delaySeconds });
191
199
  el.removeEventListener("click", handler);
192
200
  };
193
201
  el.addEventListener("click", handler);
@@ -255,8 +263,9 @@ function trimmedOrNull(value) {
255
263
  }
256
264
  function buildSurveyHtml(opts) {
257
265
  const env = opts.env === "development" ? "dev" : "prod";
258
- const version = opts.version ?? "2.2.37";
259
- const cdn = `https://cdn.jsdelivr.net/npm/@magicfeedback/native@${version}/dist/magicfeedback-sdk.browser.js`;
266
+ const version = opts.version ?? BUNDLED_SURVEY_SDK_VERSION;
267
+ const assigned = version !== BUNDLED_SURVEY_SDK_VERSION ? { version, css: surveySdkCssUrls(version), js: surveySdkUrls(version) } : null;
268
+ const bundledJs = surveySdkUrls(BUNDLED_SURVEY_SDK_VERSION);
260
269
  const sid = jsonForScript(opts.surveyId);
261
270
  const pid = jsonForScript(opts.productId);
262
271
  const profileJson = jsonForScript(opts.profile ?? []);
@@ -308,8 +317,10 @@ function buildSurveyHtml(opts) {
308
317
  return `<!DOCTYPE html><html><head>
309
318
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
310
319
  <meta name="color-scheme" content="${colorScheme}"/>
311
- <style>
320
+ <style id="dd-survey-css">
312
321
  ${style_default}
322
+ </style>
323
+ <style>
313
324
  ${fontFaceCss}
314
325
  html,body{margin:0;padding:0;height:100%;font-family:${fontFamilyValue}}
315
326
  /* Apertura diferida: ni la tarjeta ni el velo se pintan hasta que el survey est\xE1 listo
@@ -763,9 +774,9 @@ ${REVEAL_JS}
763
774
  if(p && p.error){
764
775
  setLoading(false);
765
776
  var ddErr=ddClassifySubmitError(p.error);
766
- if(ddErr.reason==='required'){
777
+ if(ddErr.reason==='required' || ddErr.reason==='invalid_email'){
767
778
  // La p\xE1gina no ha cambiado: el estado de navegaci\xF3n se queda como estaba.
768
- errorHint.textContent=DD_LABELS_ACTIVE.errorRequired;
779
+ errorHint.textContent=ddErr.reason==='invalid_email' ? DD_LABELS_ACTIVE.errorInvalidEmail : DD_LABELS_ACTIVE.errorRequired;
769
780
  errorHint.style.display='block';
770
781
  updateNavButtons();
771
782
  return;
@@ -806,10 +817,46 @@ ${REVEAL_JS}
806
817
  }catch(e){ ddShowLoadError('error:exception', e); }
807
818
  return true;
808
819
  }
809
- var s=document.createElement('script'); s.src=${JSON.stringify(cdn)}; s.async=true;
810
- s.onload=function(){ initMF(); };
811
- s.onerror=function(){ ddShowLoadError('error:load', 'survey script failed to load'); };
812
- document.head.appendChild(s);
820
+ // DD-70: versi\xF3n asignada (hoja + JS) y, si algo falla, la empaquetada (hoja + JS).
821
+ var ddAssigned=${jsonForScript(assigned)}, ddBundledJs=${jsonForScript(bundledJs)};
822
+ var ddCssEl=document.getElementById('dd-survey-css'), ddBundledCss=ddCssEl?ddCssEl.textContent:'';
823
+ function ddMark(v){ try{ document.documentElement.setAttribute('data-survey-sdk', v); }catch(_){} }
824
+ function ddLoadScripts(urls, i, onFail){
825
+ if(i>=urls.length){ onFail(); return; }
826
+ var s=document.createElement('script'); s.src=urls[i]; s.async=true;
827
+ s.onload=function(){ initMF(); };
828
+ s.onerror=function(){
829
+ try{ console.warn('[Deepdots] survey SDK failed from '+urls[i]); }catch(_){}
830
+ ddLoadScripts(urls, i+1, onFail);
831
+ };
832
+ document.head.appendChild(s);
833
+ }
834
+ function ddLoadBundled(){
835
+ if(ddCssEl){ ddCssEl.textContent=ddBundledCss; }
836
+ ddMark(${jsonForScript(BUNDLED_SURVEY_SDK_VERSION + " bundled")});
837
+ ddLoadScripts(ddBundledJs, 0, function(){ ddShowLoadError('error:load', 'survey script failed to load'); });
838
+ }
839
+ function ddFetchCss(urls, i, ok, fail){
840
+ if(i>=urls.length || typeof fetch!=='function'){ fail(); return; }
841
+ fetch(urls[i]).then(function(r){ if(!r.ok) throw new Error('HTTP '+r.status); return r.text(); })
842
+ .then(function(css){ if(!css) throw new Error('empty'); ok(css); })
843
+ .catch(function(){ ddFetchCss(urls, i+1, ok, fail); });
844
+ }
845
+ if(ddAssigned){
846
+ ddFetchCss(ddAssigned.css, 0, function(css){
847
+ if(ddCssEl){ ddCssEl.textContent=css; }
848
+ ddMark(ddAssigned.version+' assigned');
849
+ ddLoadScripts(ddAssigned.js, 0, function(){
850
+ try{ console.warn('[Deepdots] survey SDK '+ddAssigned.version+' failed, using bundled'); }catch(_){}
851
+ ddLoadBundled();
852
+ });
853
+ }, function(){
854
+ try{ console.warn('[Deepdots] survey CSS '+ddAssigned.version+' failed, using bundled'); }catch(_){}
855
+ ddLoadBundled();
856
+ });
857
+ } else {
858
+ ddLoadBundled();
859
+ }
813
860
  var tries=0, t=setInterval(function(){ if(initMF()||++tries>40){ clearInterval(t); } },150);
814
861
  })();
815
862
  <\/script>
@@ -838,9 +885,12 @@ var ReactNativePopupRenderer = class {
838
885
  this.readyEmitted = false;
839
886
  this.armReadyFallback(surveyId);
840
887
  const { profile, metadata } = buildSurveyIdentity(userId ?? null, sessionId ?? null, miniService ?? null, analyticsFeedbackSessionId ?? null);
888
+ const surveySdk = chooseSurveySdkVersion(options?.surveySdkVersion);
889
+ logRnSurveySdkChoice(surveySdk, options?.debug);
841
890
  const html = buildSurveyHtml({
842
891
  surveyId,
843
892
  productId,
893
+ version: surveySdk.version,
844
894
  env,
845
895
  profile,
846
896
  metadata,
@@ -940,9 +990,14 @@ function isReactNativeEnv() {
940
990
  function createReactNativeRenderer() {
941
991
  return new ReactNativePopupRenderer();
942
992
  }
993
+ function logRnSurveySdkChoice(choice, debug) {
994
+ const problem = choice.source === "bundled" && choice.reason === "invalid";
995
+ if (problem) sdkWarn(`[Deepdots] ${describeSurveySdkChoice(choice)}`);
996
+ else if (debug) sdkLog(`[Deepdots] ${describeSurveySdkChoice(choice)}`);
997
+ }
943
998
 
944
999
  // src/ui/preload.ts
945
- var defaultLoader = () => import("./renderPopup-BKZPAZZG.mjs");
1000
+ var defaultLoader = () => import("./renderPopup-2Y4QMWR7.mjs");
946
1001
  var pending = null;
947
1002
  function preloadRenderPopup(loader = defaultLoader) {
948
1003
  if (pending) return pending;
@@ -1015,7 +1070,7 @@ var BrowserPopupRenderer = class {
1015
1070
  if (!this.container) return;
1016
1071
  this.visible = true;
1017
1072
  const container = this.container;
1018
- void import("./renderPopup-BKZPAZZG.mjs").then(
1073
+ void import("./renderPopup-2Y4QMWR7.mjs").then(
1019
1074
  ({ renderPopup }) => {
1020
1075
  renderPopup(container, surveyId, productId, actions, emit, onClose, env, userId, style, sessionId, miniService, analyticsFeedbackSessionId, options);
1021
1076
  },
@@ -1179,6 +1234,7 @@ var AnalyticsManager = class {
1179
1234
  sessionId: identity.sessionId,
1180
1235
  context: {
1181
1236
  platform: this.platform,
1237
+ sdk: SDK_IDENTIFIER,
1182
1238
  language: this.language,
1183
1239
  device: this.device,
1184
1240
  attributes: { ...this.attributes },
@@ -1226,6 +1282,48 @@ var AnalyticsManager = class {
1226
1282
  }
1227
1283
  };
1228
1284
 
1285
+ // src/analytics/background-task.ts
1286
+ var BACKGROUND_TASK_MAX_MS = 25e3;
1287
+ async function runInBackgroundTask(begin, name, work, maxMs = BACKGROUND_TASK_MAX_MS) {
1288
+ let end;
1289
+ try {
1290
+ end = begin?.(name);
1291
+ } catch {
1292
+ end = void 0;
1293
+ }
1294
+ if (typeof end !== "function") return work();
1295
+ let ended = false;
1296
+ const finish = () => {
1297
+ if (ended) return;
1298
+ ended = true;
1299
+ clearTimeout(timer);
1300
+ try {
1301
+ end();
1302
+ } catch {
1303
+ }
1304
+ };
1305
+ const timer = setTimeout(finish, maxMs);
1306
+ try {
1307
+ return await work();
1308
+ } finally {
1309
+ finish();
1310
+ }
1311
+ }
1312
+ function backgroundTimerTask(timer) {
1313
+ let open = 0;
1314
+ return () => {
1315
+ if (open === 0) timer.start(0);
1316
+ open++;
1317
+ let closed = false;
1318
+ return () => {
1319
+ if (closed) return;
1320
+ closed = true;
1321
+ open--;
1322
+ if (open === 0) timer.stop();
1323
+ };
1324
+ };
1325
+ }
1326
+
1229
1327
  // src/analytics/feedback-payload.ts
1230
1328
  function pushKV(list, key, value) {
1231
1329
  if (value === void 0 || value === null || value === "") return;
@@ -1239,6 +1337,7 @@ function buildAnalyticsFeedbackBody(envelope, keys, feedbackSessionId, options)
1239
1337
  pushKV(metadata, "deepdots_user_id", envelope.userId);
1240
1338
  pushKV(metadata, "deepdots_session_id", envelope.sessionId);
1241
1339
  pushKV(metadata, "deepdots_platform", context.platform);
1340
+ pushKV(metadata, "deepdots_sdk", context.sdk);
1242
1341
  pushKV(metadata, "deepdots_language", context.language);
1243
1342
  if (context.device) {
1244
1343
  const d = context.device;
@@ -1437,7 +1536,9 @@ function createFeedbackSink(options) {
1437
1536
  savePending();
1438
1537
  setTimeout(() => void drain(), 0);
1439
1538
  }
1440
- return async (envelope, meta) => {
1539
+ const sink = (envelope, meta) => runInBackgroundTask(options.backgroundTask, "deepdots-analytics", () => deliver(envelope, meta));
1540
+ return sink;
1541
+ async function deliver(envelope, meta) {
1441
1542
  if (meta?.resetSession) {
1442
1543
  feedbackSessionId = void 0;
1443
1544
  options.onSessionReset?.();
@@ -1458,7 +1559,7 @@ function createFeedbackSink(options) {
1458
1559
  }
1459
1560
  const retries = pending2.length ? drain() : null;
1460
1561
  await Promise.all([retries, send(batch, final, false)]);
1461
- };
1562
+ }
1462
1563
  }
1463
1564
 
1464
1565
  // src/analytics/suspended-session.ts
@@ -2054,6 +2155,33 @@ function clearPopupState(storage) {
2054
2155
  }
2055
2156
  }
2056
2157
 
2158
+ // src/platform/react-native-platform.ts
2159
+ var registered = null;
2160
+ function getReactNativePlatform() {
2161
+ return registered;
2162
+ }
2163
+ function nativeModuleTask(mod) {
2164
+ let seq = 0;
2165
+ return (name) => {
2166
+ const token = `dd-${Date.now().toString(36)}-${(seq++).toString(36)}`;
2167
+ mod.begin(token, name);
2168
+ let ended = false;
2169
+ return () => {
2170
+ if (ended) return;
2171
+ ended = true;
2172
+ mod.end(token);
2173
+ };
2174
+ };
2175
+ }
2176
+ function resolveBackgroundTask(explicit, platform) {
2177
+ if (explicit) return explicit;
2178
+ const mod = platform?.backgroundTaskModule;
2179
+ if (platform?.os === "ios" && mod && typeof mod.begin === "function" && typeof mod.end === "function") {
2180
+ return nativeModuleTask(mod);
2181
+ }
2182
+ return void 0;
2183
+ }
2184
+
2057
2185
  // src/analytics/messaging.ts
2058
2186
  var MESSAGE_CHANNELS = ["push", "in_app"];
2059
2187
  function buildMessageParams(stage, o) {
@@ -2133,6 +2261,10 @@ var ANALYTICS_RESUME_WINDOW_MS = 6e4;
2133
2261
  var RESERVED_EVENT_PREFIX = "deepdots_";
2134
2262
  var CUSTOM_EVENT_PREFIX = "deepdots_event_";
2135
2263
  var MAX_PENDING_TRIGGERS = 20;
2264
+ function triggerDelayMs(delaySeconds) {
2265
+ const n = typeof delaySeconds === "number" ? delaySeconds : Number(delaySeconds);
2266
+ return Number.isFinite(n) && n > 0 ? Math.round(n * 1e3) : 0;
2267
+ }
2136
2268
  var DeepdotsPopups = class {
2137
2269
  constructor() {
2138
2270
  this.config = null;
@@ -2164,6 +2296,10 @@ var DeepdotsPopups = class {
2164
2296
  this.surveyToPopupId = /* @__PURE__ */ new Map();
2165
2297
  // surveyId -> popupId
2166
2298
  this.deferredExitTimers = [];
2299
+ /** Popups esperando su `delaySeconds` (uno por popup). */
2300
+ this.delayedPopups = /* @__PURE__ */ new Map();
2301
+ /** Última pantalla de `setScreen` (React Native). */
2302
+ this.currentScreen = null;
2167
2303
  this.baseUrl = "";
2168
2304
  this.env = "production";
2169
2305
  /** Si el SDK pinta el "modal" del popup (RN). Default true; false = el host lo envuelve. */
@@ -2209,6 +2345,8 @@ var DeepdotsPopups = class {
2209
2345
  this.lastEngagementAt = 0;
2210
2346
  /** Cuándo se ocultó la pestaña por última vez (ms epoch); null si está visible. */
2211
2347
  this.hiddenAt = null;
2348
+ /** Suscripción automática a AppState (React Native, `autoTrack.lifecycle`). */
2349
+ this.appStateSubscription = void 0;
2212
2350
  /**
2213
2351
  * Sesión suspendida por un `pagehide` (ms epoch y `deepdots_user_id`); null si no hay.
2214
2352
  * `openSession` la reanuda si sigue a tiempo (ver ANALYTICS_RESUME_WINDOW_MS).
@@ -2241,6 +2379,10 @@ var DeepdotsPopups = class {
2241
2379
  this.log("SDK already initialized");
2242
2380
  return;
2243
2381
  }
2382
+ const rn = getReactNativePlatform();
2383
+ if (!config.platform && (rn?.os === "ios" || rn?.os === "android")) {
2384
+ config = { ...config, platform: rn.os };
2385
+ }
2244
2386
  const env = resolveEnvironment(config.nodeEnv);
2245
2387
  this.baseUrl = env.apiBaseUrl;
2246
2388
  this.env = config.nodeEnv || "production";
@@ -2291,6 +2433,10 @@ var DeepdotsPopups = class {
2291
2433
  // persiste y se reenvía en el arranque siguiente. En web el cierre sale con
2292
2434
  // `keepalive` y varias pestañas compartirían el mismo storage.
2293
2435
  storage: (config.platform ?? "web") !== "web" ? storage : void 0,
2436
+ // iOS suspende la app con el POST de cierre en vuelo: el host puede darle
2437
+ // tiempo de background (DD-55). El reenvío del arranque siguiente sigue igual.
2438
+ // La del host o, en iOS, la del módulo nativo del paquete (autolinking).
2439
+ backgroundTask: resolveBackgroundTask(config.backgroundTask, rn),
2294
2440
  onSessionId: (id) => {
2295
2441
  this.analyticsFeedbackSessionId = id;
2296
2442
  this.notifyFeedbackSession(id, "open");
@@ -2348,6 +2494,7 @@ var DeepdotsPopups = class {
2348
2494
  }
2349
2495
  }
2350
2496
  this.initialized = true;
2497
+ this.installAutoLifecycle(rn, config);
2351
2498
  this.log("SDK initialized", this.config);
2352
2499
  if (this.renderer.init) this.renderer.init();
2353
2500
  this.awaitingPopups = Boolean(this.config.apiKey && this.baseUrl);
@@ -2518,6 +2665,11 @@ var DeepdotsPopups = class {
2518
2665
  * El host la llama en cada cambio de pantalla; emite `page_view` al salir de la anterior.
2519
2666
  */
2520
2667
  setScreen(name) {
2668
+ const screen2 = typeof name === "string" ? name.trim() : "";
2669
+ if (screen2) {
2670
+ this.cancelDelayedPopups("screen change", (entry) => entry.screen !== screen2);
2671
+ this.currentScreen = screen2;
2672
+ }
2521
2673
  if (!this.navObserver) return;
2522
2674
  if (!this.navStarted) {
2523
2675
  this.navObserver.begin(name);
@@ -2539,9 +2691,42 @@ var DeepdotsPopups = class {
2539
2691
  * Es la única señal disponible en móvil: el kill de la app (swipe) NO da callback.
2540
2692
  */
2541
2693
  onBackground() {
2694
+ this.cancelDelayedPopups("app to background");
2542
2695
  this.closeSession("background");
2543
2696
  this.engagement?.pause();
2544
2697
  }
2698
+ /**
2699
+ * App a `inactive` (RN, iOS: centro de control, llamada, app switcher, y SIEMPRE justo antes
2700
+ * de `background`). NO cierra la sesión (es transitorio), pero envía lo acumulado con un
2701
+ * `user_engagement` que lleva la pantalla en curso, como web al ocultar la pestaña: si el
2702
+ * lote de cierre de `background` no llega a salir (iOS suspende la app), el backend ya
2703
+ * tiene el tiempo activo y la última pantalla. El contador sigue en marcha.
2704
+ */
2705
+ onInactive() {
2706
+ if (this.sessionOpen) this.flushEngagement();
2707
+ this.flushAnalytics();
2708
+ }
2709
+ /**
2710
+ * Ciclo de vida automático en React Native (contrato de detección automática): el SDK escucha
2711
+ * AppState él mismo, así que el host no tiene que llamar a `onForeground`/`onInactive`/
2712
+ * `onBackground`. Si el host los llama además (integraciones anteriores), no se duplica nada:
2713
+ * abrir o cerrar una sesión ya abierta o cerrada no hace nada, y el engagement se consume.
2714
+ * `autoTrack.lifecycle: false` lo apaga.
2715
+ */
2716
+ installAutoLifecycle(rn, config) {
2717
+ if (config.autoTrack?.lifecycle === false) return;
2718
+ const appState = rn?.appState;
2719
+ if (!appState || typeof appState.addEventListener !== "function" || this.appStateSubscription) return;
2720
+ try {
2721
+ this.appStateSubscription = appState.addEventListener("change", (state) => {
2722
+ if (state === "active") this.onForeground();
2723
+ else if (state === "background") this.onBackground();
2724
+ else this.onInactive();
2725
+ });
2726
+ this.log("lifecycle \xB7 AppState wired automatically");
2727
+ } catch {
2728
+ }
2729
+ }
2545
2730
  /**
2546
2731
  * Cierre EXPLÍCITO de la sesión por parte del host (logout, fin de flujo…): emite
2547
2732
  * `session_end` y envía el último lote con `completed:true`.
@@ -2882,16 +3067,21 @@ var DeepdotsPopups = class {
2882
3067
  return;
2883
3068
  }
2884
3069
  const value = type === "time" && typeof trigger.value === "number" ? trigger.value * 1e3 : trigger.value;
2885
- derived.push({ type, value, surveyId: def.surveyId, popupId: def.id });
3070
+ derived.push({ type, value, surveyId: def.surveyId, popupId: def.id, delaySeconds: trigger.delaySeconds });
2886
3071
  });
2887
3072
  });
2888
3073
  if (derived.length) {
2889
3074
  this.configureTriggers(derived);
2890
3075
  }
2891
3076
  }
2892
- /** Lógica para evaluar condiciones antes de mostrar una encuesta */
2893
- triggerSurvey(surveyId, popupId) {
2894
- if (this.bufferIfAwaitingPopups({ kind: "survey", surveyId, popupId })) return;
3077
+ /**
3078
+ * Lógica para evaluar condiciones antes de mostrar una encuesta. `options.delaySeconds`
3079
+ * (lo pasan los triggers time/scroll/click con el "Delay" del Admin) espera ese tiempo y
3080
+ * vuelve a evaluar antes de mostrar; sin él, al momento como siempre.
3081
+ */
3082
+ triggerSurvey(surveyId, popupId, options) {
3083
+ const delaySeconds = options?.delaySeconds;
3084
+ if (this.bufferIfAwaitingPopups({ kind: "survey", surveyId, popupId, delaySeconds })) return;
2895
3085
  const def = this.findPopupDefinition(surveyId, popupId);
2896
3086
  if (!def) {
2897
3087
  this.debug("No popup definition for trigger", { surveyId, popupId });
@@ -2901,7 +3091,7 @@ var DeepdotsPopups = class {
2901
3091
  this.debug("Conditions prevented showing popup", def.id);
2902
3092
  return;
2903
3093
  }
2904
- this.showDefinition(def);
3094
+ this.showAfterDelay(def, delaySeconds);
2905
3095
  }
2906
3096
  /** Trigger popups configured with trigger.type = 'event' and matching trigger.value */
2907
3097
  triggerEvent(eventName) {
@@ -2918,9 +3108,9 @@ var DeepdotsPopups = class {
2918
3108
  }
2919
3109
  evaluateEvent(normalized) {
2920
3110
  const candidates = this.popupDefinitions.filter((def) => {
2921
- return def.triggers.some((trigger) => {
2922
- const triggerValue = String(trigger.value ?? "").trim();
2923
- return trigger.type === "event" && triggerValue === normalized;
3111
+ return def.triggers.some((trigger2) => {
3112
+ const triggerValue = String(trigger2.value ?? "").trim();
3113
+ return trigger2.type === "event" && triggerValue === normalized;
2924
3114
  });
2925
3115
  });
2926
3116
  if (!candidates.length) {
@@ -2932,7 +3122,69 @@ var DeepdotsPopups = class {
2932
3122
  this.debug("Event popup blocked by conditions/segments", { eventName: normalized });
2933
3123
  return;
2934
3124
  }
2935
- this.showDefinition(matched);
3125
+ const trigger = matched.triggers.find(
3126
+ (t) => t.type === "event" && String(t.value ?? "").trim() === normalized
3127
+ );
3128
+ this.showAfterDelay(matched, trigger?.delaySeconds);
3129
+ }
3130
+ /**
3131
+ * Muestra `def` ya, o tras su "Delay (seconds)" del Admin. Mientras espera:
3132
+ * - el mismo popup no se programa dos veces (el primer vencimiento manda);
3133
+ * - cambiar de ruta/pantalla o pasar a background lo cancela;
3134
+ * y al vencer se vuelve a evaluar todo (segmentos, idioma, cooldowns) como un disparo nuevo.
3135
+ * Si entonces hay otro popup abierto, `showDefinition` lo salta sin efectos, igual que hoy.
3136
+ */
3137
+ showAfterDelay(def, delaySeconds) {
3138
+ const delayMs = triggerDelayMs(delaySeconds);
3139
+ if (delayMs <= 0) {
3140
+ this.showDefinition(def);
3141
+ return;
3142
+ }
3143
+ if (this.delayedPopups.has(def.id)) {
3144
+ this.debug("Popup already waiting for its delay", def.id);
3145
+ return;
3146
+ }
3147
+ const entry = {
3148
+ popupId: def.id,
3149
+ timer: setTimeout(() => this.showDelayedPopup(def.id), delayMs),
3150
+ firedAt: Date.now(),
3151
+ href: this.currentHref(),
3152
+ screen: this.currentScreen
3153
+ };
3154
+ this.delayedPopups.set(def.id, entry);
3155
+ this.debug(`Popup delayed ${delayMs}ms`, def.id);
3156
+ }
3157
+ showDelayedPopup(popupId) {
3158
+ const entry = this.delayedPopups.get(popupId);
3159
+ if (!entry) return;
3160
+ this.delayedPopups.delete(popupId);
3161
+ const def = this.popupDefinitions.find((popup) => popup.id === popupId);
3162
+ if (!def) return;
3163
+ if (this.currentHref() !== entry.href || this.currentScreen !== entry.screen) {
3164
+ this.debug("Delayed popup dropped: route changed", popupId);
3165
+ return;
3166
+ }
3167
+ if (!this.shouldShow(def)) {
3168
+ this.debug("Delayed popup dropped by conditions at due time", popupId);
3169
+ return;
3170
+ }
3171
+ if ((this.lastShown.get(popupId) ?? 0) >= entry.firedAt) {
3172
+ this.debug("Delayed popup dropped: already shown while waiting", popupId);
3173
+ return;
3174
+ }
3175
+ this.showDefinition(def);
3176
+ }
3177
+ cancelDelayedPopups(reason, predicate = () => true) {
3178
+ this.delayedPopups.forEach((entry, popupId) => {
3179
+ if (!predicate(entry)) return;
3180
+ clearTimeout(entry.timer);
3181
+ this.delayedPopups.delete(popupId);
3182
+ this.debug(`Delayed popup cancelled (${reason})`, popupId);
3183
+ });
3184
+ }
3185
+ currentHref() {
3186
+ if (typeof window === "undefined" || !window.location) return "";
3187
+ return this.normalizeUrl(window.location.href || "");
2936
3188
  }
2937
3189
  /**
2938
3190
  * Guarda `trigger` si las definiciones aún no han llegado. Devuelve `true` si lo guardó (el
@@ -2965,7 +3217,7 @@ var DeepdotsPopups = class {
2965
3217
  this.debug("Replaying triggers received before popups loaded", replay.length);
2966
3218
  replay.forEach((trigger) => {
2967
3219
  if (trigger.kind === "event") this.evaluateEvent(trigger.name);
2968
- else this.triggerSurvey(trigger.surveyId, trigger.popupId);
3220
+ else this.triggerSurvey(trigger.surveyId, trigger.popupId, { delaySeconds: trigger.delaySeconds });
2969
3221
  });
2970
3222
  }
2971
3223
  showDefinition(def) {
@@ -2977,7 +3229,7 @@ var DeepdotsPopups = class {
2977
3229
  this.surveyToPopupId.set(def.surveyId, def.id);
2978
3230
  this.lastShown.set(def.id, Date.now());
2979
3231
  this.persistPopupState();
2980
- this.renderPopup(def.surveyId, def.productId, def.actions, def.style, def.title);
3232
+ this.renderPopup(def.surveyId, def.productId, def.actions, def.style, def.title, def.surveyFrontend?.sdkVersion);
2981
3233
  this.emitEvent("popup_shown", def.surveyId, { popupId: def.id });
2982
3234
  }
2983
3235
  shouldShow(def, pathUrl, skipPathCheck = false) {
@@ -3349,7 +3601,7 @@ var DeepdotsPopups = class {
3349
3601
  }
3350
3602
  }
3351
3603
  /** Render the popup UI */
3352
- renderPopup(surveyId, productId, actions, style, title) {
3604
+ renderPopup(surveyId, productId, actions, style, title, surveySdkVersion) {
3353
3605
  const userId = this.tracking?.getUserId() ?? this.config?.userId;
3354
3606
  const sessionId = this.tracking?.getSessionId() ?? void 0;
3355
3607
  const miniService = this.analytics?.getMiniService() ?? void 0;
@@ -3368,7 +3620,7 @@ var DeepdotsPopups = class {
3368
3620
  miniService,
3369
3621
  analyticsFeedbackSessionId,
3370
3622
  this.renderChrome,
3371
- { title, showProgressBar: this.showProgressBar, surveyCss: this.surveyCss, language: this.language, cspNonce: this.cspNonce }
3623
+ { title, showProgressBar: this.showProgressBar, surveyCss: this.surveyCss, language: this.language, cspNonce: this.cspNonce, surveySdkVersion, debug: this.config?.debug }
3372
3624
  );
3373
3625
  }
3374
3626
  /** Hide the popup */
@@ -3535,10 +3787,10 @@ var DeepdotsPopups = class {
3535
3787
  }
3536
3788
  normalizeTriggers(value) {
3537
3789
  const items = Array.isArray(value) ? value : value ? [value] : [];
3538
- return items.filter((trigger) => this.isPopupTrigger(trigger)).map((trigger) => ({
3539
- type: trigger.type,
3540
- value: trigger.value
3541
- }));
3790
+ return items.filter((trigger) => this.isPopupTrigger(trigger)).map((trigger) => {
3791
+ const delayMs = triggerDelayMs(trigger.delaySeconds);
3792
+ return delayMs > 0 ? { type: trigger.type, value: trigger.value, delaySeconds: delayMs / 1e3 } : { type: trigger.type, value: trigger.value };
3793
+ });
3542
3794
  }
3543
3795
  normalizeCooldown(value) {
3544
3796
  if (!Array.isArray(value)) return [];
@@ -3593,7 +3845,9 @@ function setupReactNative(sdk, config, deps = {}) {
3593
3845
  const storage = deps.mmkv ? mmkvStorage(deps.mmkv) : config.storage;
3594
3846
  const device = deps.deviceInfo ? collectRnDevice(deps.deviceInfo) : config.device;
3595
3847
  const platform = deps.platform ?? config.platform;
3596
- sdk.init({ ...config, storage, device, platform });
3848
+ const backgroundTask = config.backgroundTask ?? deps.backgroundTask ?? void 0;
3849
+ const autoTrack = deps.appState?.addEventListener ? { ...config.autoTrack, lifecycle: false } : config.autoTrack;
3850
+ sdk.init({ ...config, storage, device, platform, backgroundTask, autoTrack });
3597
3851
  const errorUtils = deps.errorUtils ?? globalThis.ErrorUtils;
3598
3852
  if (errorUtils && typeof errorUtils.setGlobalHandler === "function") {
3599
3853
  sdk.installReactNativeCrashHandler(errorUtils);
@@ -3603,7 +3857,7 @@ function setupReactNative(sdk, config, deps = {}) {
3603
3857
  subscription = deps.appState.addEventListener("change", (state) => {
3604
3858
  if (state === "active") sdk.onForeground();
3605
3859
  else if (state === "background") sdk.onBackground();
3606
- else sdk.flushAnalytics();
3860
+ else sdk.onInactive();
3607
3861
  });
3608
3862
  }
3609
3863
  return () => {
@@ -3611,6 +3865,7 @@ function setupReactNative(sdk, config, deps = {}) {
3611
3865
  };
3612
3866
  }
3613
3867
  export {
3868
+ BACKGROUND_TASK_MAX_MS,
3614
3869
  BrowserPopupRenderer,
3615
3870
  ContactManager,
3616
3871
  CrashReporter,
@@ -3627,6 +3882,7 @@ export {
3627
3882
  RTL_LOCALES,
3628
3883
  ReactNativePopupRenderer,
3629
3884
  SUPPORTED_LANGUAGES,
3885
+ backgroundTimerTask,
3630
3886
  buildAnalyticsFeedbackBody,
3631
3887
  buildMessageParams,
3632
3888
  buildSurveyHtml,