@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
@@ -1,28 +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,
11
+ SUBMIT_ERROR_JS,
9
12
  TrackingManager,
10
- __require,
11
13
  buildFontFaceCss,
12
14
  buildFontFamilyValue,
13
15
  buildSurveyIdentity,
16
+ chooseSurveySdkVersion,
14
17
  createDefaultStorage,
18
+ describeSurveySdkChoice,
15
19
  directionFor,
16
20
  getLabels,
17
21
  resolveActionLabels,
22
+ sdkLog,
18
23
  sdkWarn,
19
24
  setLogger,
20
- style_default
21
- } from "./chunk-VHTN5UXD.mjs";
25
+ style_default,
26
+ surveySdkCssUrls,
27
+ surveySdkUrls
28
+ } from "./chunk-EW2ARDEY.mjs";
29
+ import {
30
+ __require
31
+ } from "./chunk-BJTO5JO5.mjs";
22
32
 
23
33
  // src/react-native/index.tsx
24
34
  import { createContext, useContext, useEffect, useRef, useState } from "react";
25
- import { AppState, Modal, Platform, View } from "react-native";
35
+ import { AppState, Modal, NativeModules, Platform, View } from "react-native";
26
36
  import { WebView } from "react-native-webview";
27
37
 
28
38
  // src/types/index.ts
@@ -59,7 +69,7 @@ function setupTrigger(popups, trigger) {
59
69
  function setupTimeTrigger(popups, trigger) {
60
70
  const delay = toNumericValue(trigger.value, 5e3);
61
71
  setTimeout(() => {
62
- popups.triggerSurvey(trigger.surveyId, trigger.popupId);
72
+ popups.triggerSurvey(trigger.surveyId, trigger.popupId, { delaySeconds: trigger.delaySeconds });
63
73
  }, delay);
64
74
  popups.debug(`Time trigger set for ${delay}ms`);
65
75
  }
@@ -68,7 +78,7 @@ function setupScrollTrigger(popups, trigger) {
68
78
  const handler = () => {
69
79
  const scrollPercentage = window.scrollY / (document.documentElement.scrollHeight - window.innerHeight) * 100;
70
80
  if (scrollPercentage >= threshold) {
71
- popups.triggerSurvey(trigger.surveyId, trigger.popupId);
81
+ popups.triggerSurvey(trigger.surveyId, trigger.popupId, { delaySeconds: trigger.delaySeconds });
72
82
  window.removeEventListener("scroll", handler);
73
83
  }
74
84
  };
@@ -77,7 +87,7 @@ function setupScrollTrigger(popups, trigger) {
77
87
  }
78
88
  function setupExitTrigger(popups, trigger) {
79
89
  if (typeof window === "undefined") return;
80
- const delaySeconds = parseExitDelaySeconds(trigger.value);
90
+ const delaySeconds = typeof trigger.delaySeconds === "number" && trigger.delaySeconds > 0 ? trigger.delaySeconds : parseExitDelaySeconds(trigger.value);
81
91
  const historyRef = window.history;
82
92
  const originalPushState = historyRef.pushState.bind(historyRef);
83
93
  const originalReplaceState = historyRef.replaceState.bind(historyRef);
@@ -188,7 +198,7 @@ function setupClickTrigger(popups, trigger) {
188
198
  }
189
199
  const handler = (e) => {
190
200
  if (e.defaultPrevented) return;
191
- popups.triggerSurvey(trigger.surveyId, trigger.popupId);
201
+ popups.triggerSurvey(trigger.surveyId, trigger.popupId, { delaySeconds: trigger.delaySeconds });
192
202
  el.removeEventListener("click", handler);
193
203
  };
194
204
  el.addEventListener("click", handler);
@@ -256,8 +266,9 @@ function trimmedOrNull(value) {
256
266
  }
257
267
  function buildSurveyHtml(opts) {
258
268
  const env = opts.env === "development" ? "dev" : "prod";
259
- const version = opts.version ?? "2.2.33";
260
- 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);
261
272
  const sid = jsonForScript(opts.surveyId);
262
273
  const pid = jsonForScript(opts.productId);
263
274
  const profileJson = jsonForScript(opts.profile ?? []);
@@ -309,8 +320,10 @@ function buildSurveyHtml(opts) {
309
320
  return `<!DOCTYPE html><html><head>
310
321
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
311
322
  <meta name="color-scheme" content="${colorScheme}"/>
312
- <style>
323
+ <style id="dd-survey-css">
313
324
  ${style_default}
325
+ </style>
326
+ <style>
314
327
  ${fontFaceCss}
315
328
  html,body{margin:0;padding:0;height:100%;font-family:${fontFamilyValue}}
316
329
  /* Apertura diferida: ni la tarjeta ni el velo se pintan hasta que el survey est\xE1 listo
@@ -428,6 +441,7 @@ ${customCss}
428
441
  (function(){
429
442
  function emit(s){ try{ if(window.ReactNativeWebView){ window.ReactNativeWebView.postMessage(s); } }catch(e){} }
430
443
  function emitJSON(n,p){ try{ emit(JSON.stringify({name:n,payload:p||{}})); }catch(e){} }
444
+ var ddLastReportedError=null;
431
445
  window.DeepdotsClose = function(){ emitJSON('popup_close'); };
432
446
  var chromeOn=${chrome ? "true" : "false"};
433
447
 
@@ -608,6 +622,7 @@ ${customCss}
608
622
 
609
623
  ${PRIMARY_COLOR_JS}
610
624
  ${BUSY_JS}
625
+ ${SUBMIT_ERROR_JS}
611
626
  ${REVEAL_JS}
612
627
  // Foco en la primera pregunta si es de escribir. Al navegar lo pone @magicfeedback/native
613
628
  // (autofocus:'navigation'); la apertura la decide el popup, que es quien sabe cu\xE1ndo se revela.
@@ -759,18 +774,23 @@ ${REVEAL_JS}
759
774
  emitJSON('before_submit');
760
775
  },
761
776
  afterSubmitEvent:function(p){
762
- var error=p && p.error ? (typeof p.error==='string' ? p.error : String(p.error)) : '';
763
- if(error){
777
+ if(p && p.error){
764
778
  setLoading(false);
765
- if(error.toLowerCase().indexOf('no response')!==-1){
779
+ var ddErr=ddClassifySubmitError(p.error);
780
+ if(ddErr.reason==='required' || ddErr.reason==='invalid_email'){
766
781
  // La p\xE1gina no ha cambiado: el estado de navegaci\xF3n se queda como estaba.
767
- errorHint.textContent=DD_LABELS_ACTIVE.errorRequired;
782
+ errorHint.textContent=ddErr.reason==='invalid_email' ? DD_LABELS_ACTIVE.errorInvalidEmail : DD_LABELS_ACTIVE.errorRequired;
768
783
  errorHint.style.display='block';
769
784
  updateNavButtons();
770
785
  return;
771
786
  }
772
787
  errorHint.textContent=DD_LABELS_ACTIVE.errorSubmit;
773
788
  errorHint.style.display='block';
789
+ // Un solo aviso por fallo: native repite el mismo objeto al cerrar el survey.
790
+ if(p.error!==ddLastReportedError){
791
+ ddLastReportedError=p.error;
792
+ emitJSON('survey_error', ddErr);
793
+ }
774
794
  return;
775
795
  }
776
796
  errorHint.style.display='none';
@@ -800,10 +820,46 @@ ${REVEAL_JS}
800
820
  }catch(e){ ddShowLoadError('error:exception', e); }
801
821
  return true;
802
822
  }
803
- var s=document.createElement('script'); s.src=${JSON.stringify(cdn)}; s.async=true;
804
- s.onload=function(){ initMF(); };
805
- s.onerror=function(){ ddShowLoadError('error:load', 'survey script failed to load'); };
806
- 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
+ }
807
863
  var tries=0, t=setInterval(function(){ if(initMF()||++tries>40){ clearInterval(t); } },150);
808
864
  })();
809
865
  </script>
@@ -832,9 +888,12 @@ var ReactNativePopupRenderer = class {
832
888
  this.readyEmitted = false;
833
889
  this.armReadyFallback(surveyId);
834
890
  const { profile, metadata } = buildSurveyIdentity(userId ?? null, sessionId ?? null, miniService ?? null, analyticsFeedbackSessionId ?? null);
891
+ const surveySdk = chooseSurveySdkVersion(options?.surveySdkVersion);
892
+ logRnSurveySdkChoice(surveySdk, options?.debug);
835
893
  const html = buildSurveyHtml({
836
894
  surveyId,
837
895
  productId,
896
+ version: surveySdk.version,
838
897
  env,
839
898
  profile,
840
899
  metadata,
@@ -893,8 +952,9 @@ var ReactNativePopupRenderer = class {
893
952
  const surveyId = this.currentSurveyId;
894
953
  if (!surveyId || !this.emitFn) return;
895
954
  let name;
955
+ let payload;
896
956
  try {
897
- name = JSON.parse(raw).name;
957
+ ({ name, payload } = JSON.parse(raw));
898
958
  } catch {
899
959
  name = raw;
900
960
  }
@@ -915,6 +975,9 @@ var ReactNativePopupRenderer = class {
915
975
  case "survey_completed":
916
976
  this.emitFn("survey_completed", surveyId);
917
977
  break;
978
+ case "survey_error":
979
+ this.emitFn("survey_error", surveyId, { reason: payload?.reason, message: payload?.message });
980
+ break;
918
981
  case "popup_close":
919
982
  this.onCloseFn?.();
920
983
  break;
@@ -930,9 +993,14 @@ function isReactNativeEnv() {
930
993
  function createReactNativeRenderer() {
931
994
  return new ReactNativePopupRenderer();
932
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
+ }
933
1001
 
934
1002
  // src/ui/preload.ts
935
- var defaultLoader = () => import("./renderPopup-L2Q3KJAZ.mjs");
1003
+ var defaultLoader = () => import("./renderPopup-ZHTRMFO2.mjs");
936
1004
  var pending = null;
937
1005
  function preloadRenderPopup(loader = defaultLoader) {
938
1006
  if (pending) return pending;
@@ -1005,7 +1073,7 @@ var BrowserPopupRenderer = class {
1005
1073
  if (!this.container) return;
1006
1074
  this.visible = true;
1007
1075
  const container = this.container;
1008
- void import("./renderPopup-L2Q3KJAZ.mjs").then(
1076
+ void import("./renderPopup-ZHTRMFO2.mjs").then(
1009
1077
  ({ renderPopup }) => {
1010
1078
  renderPopup(container, surveyId, productId, actions, emit, onClose, env, userId, style, sessionId, miniService, analyticsFeedbackSessionId, options);
1011
1079
  },
@@ -1169,6 +1237,7 @@ var AnalyticsManager = class {
1169
1237
  sessionId: identity.sessionId,
1170
1238
  context: {
1171
1239
  platform: this.platform,
1240
+ sdk: SDK_IDENTIFIER,
1172
1241
  language: this.language,
1173
1242
  device: this.device,
1174
1243
  attributes: { ...this.attributes },
@@ -1216,6 +1285,34 @@ var AnalyticsManager = class {
1216
1285
  }
1217
1286
  };
1218
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
+
1219
1316
  // src/analytics/feedback-payload.ts
1220
1317
  function pushKV(list, key, value) {
1221
1318
  if (value === void 0 || value === null || value === "") return;
@@ -1229,6 +1326,7 @@ function buildAnalyticsFeedbackBody(envelope, keys, feedbackSessionId, options)
1229
1326
  pushKV(metadata, "deepdots_user_id", envelope.userId);
1230
1327
  pushKV(metadata, "deepdots_session_id", envelope.sessionId);
1231
1328
  pushKV(metadata, "deepdots_platform", context.platform);
1329
+ pushKV(metadata, "deepdots_sdk", context.sdk);
1232
1330
  pushKV(metadata, "deepdots_language", context.language);
1233
1331
  if (context.device) {
1234
1332
  const d = context.device;
@@ -1427,7 +1525,9 @@ function createFeedbackSink(options) {
1427
1525
  savePending();
1428
1526
  setTimeout(() => void drain(), 0);
1429
1527
  }
1430
- 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) {
1431
1531
  if (meta?.resetSession) {
1432
1532
  feedbackSessionId = void 0;
1433
1533
  options.onSessionReset?.();
@@ -1448,7 +1548,7 @@ function createFeedbackSink(options) {
1448
1548
  }
1449
1549
  const retries = pending2.length ? drain() : null;
1450
1550
  await Promise.all([retries, send(batch, final, false)]);
1451
- };
1551
+ }
1452
1552
  }
1453
1553
 
1454
1554
  // src/analytics/suspended-session.ts
@@ -2044,6 +2144,36 @@ function clearPopupState(storage) {
2044
2144
  }
2045
2145
  }
2046
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
+
2047
2177
  // src/analytics/messaging.ts
2048
2178
  var MESSAGE_CHANNELS = ["push", "in_app"];
2049
2179
  function buildMessageParams(stage, o) {
@@ -2123,6 +2253,10 @@ var ANALYTICS_RESUME_WINDOW_MS = 6e4;
2123
2253
  var RESERVED_EVENT_PREFIX = "deepdots_";
2124
2254
  var CUSTOM_EVENT_PREFIX = "deepdots_event_";
2125
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
+ }
2126
2260
  var DeepdotsPopups = class {
2127
2261
  constructor() {
2128
2262
  this.config = null;
@@ -2154,6 +2288,10 @@ var DeepdotsPopups = class {
2154
2288
  this.surveyToPopupId = /* @__PURE__ */ new Map();
2155
2289
  // surveyId -> popupId
2156
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;
2157
2295
  this.baseUrl = "";
2158
2296
  this.env = "production";
2159
2297
  /** Si el SDK pinta el "modal" del popup (RN). Default true; false = el host lo envuelve. */
@@ -2199,6 +2337,8 @@ var DeepdotsPopups = class {
2199
2337
  this.lastEngagementAt = 0;
2200
2338
  /** Cuándo se ocultó la pestaña por última vez (ms epoch); null si está visible. */
2201
2339
  this.hiddenAt = null;
2340
+ /** Suscripción automática a AppState (React Native, `autoTrack.lifecycle`). */
2341
+ this.appStateSubscription = void 0;
2202
2342
  /**
2203
2343
  * Sesión suspendida por un `pagehide` (ms epoch y `deepdots_user_id`); null si no hay.
2204
2344
  * `openSession` la reanuda si sigue a tiempo (ver ANALYTICS_RESUME_WINDOW_MS).
@@ -2231,6 +2371,10 @@ var DeepdotsPopups = class {
2231
2371
  this.log("SDK already initialized");
2232
2372
  return;
2233
2373
  }
2374
+ const rn = getReactNativePlatform();
2375
+ if (!config.platform && (rn?.os === "ios" || rn?.os === "android")) {
2376
+ config = { ...config, platform: rn.os };
2377
+ }
2234
2378
  const env = resolveEnvironment(config.nodeEnv);
2235
2379
  this.baseUrl = env.apiBaseUrl;
2236
2380
  this.env = config.nodeEnv || "production";
@@ -2281,6 +2425,10 @@ var DeepdotsPopups = class {
2281
2425
  // persiste y se reenvía en el arranque siguiente. En web el cierre sale con
2282
2426
  // `keepalive` y varias pestañas compartirían el mismo storage.
2283
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),
2284
2432
  onSessionId: (id) => {
2285
2433
  this.analyticsFeedbackSessionId = id;
2286
2434
  this.notifyFeedbackSession(id, "open");
@@ -2338,6 +2486,7 @@ var DeepdotsPopups = class {
2338
2486
  }
2339
2487
  }
2340
2488
  this.initialized = true;
2489
+ this.installAutoLifecycle(rn, config);
2341
2490
  this.log("SDK initialized", this.config);
2342
2491
  if (this.renderer.init) this.renderer.init();
2343
2492
  this.awaitingPopups = Boolean(this.config.apiKey && this.baseUrl);
@@ -2508,6 +2657,11 @@ var DeepdotsPopups = class {
2508
2657
  * El host la llama en cada cambio de pantalla; emite `page_view` al salir de la anterior.
2509
2658
  */
2510
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
+ }
2511
2665
  if (!this.navObserver) return;
2512
2666
  if (!this.navStarted) {
2513
2667
  this.navObserver.begin(name);
@@ -2529,9 +2683,42 @@ var DeepdotsPopups = class {
2529
2683
  * Es la única señal disponible en móvil: el kill de la app (swipe) NO da callback.
2530
2684
  */
2531
2685
  onBackground() {
2686
+ this.cancelDelayedPopups("app to background");
2532
2687
  this.closeSession("background");
2533
2688
  this.engagement?.pause();
2534
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
+ }
2535
2722
  /**
2536
2723
  * Cierre EXPLÍCITO de la sesión por parte del host (logout, fin de flujo…): emite
2537
2724
  * `session_end` y envía el último lote con `completed:true`.
@@ -2872,16 +3059,21 @@ var DeepdotsPopups = class {
2872
3059
  return;
2873
3060
  }
2874
3061
  const value = type === "time" && typeof trigger.value === "number" ? trigger.value * 1e3 : trigger.value;
2875
- derived.push({ type, value, surveyId: def.surveyId, popupId: def.id });
3062
+ derived.push({ type, value, surveyId: def.surveyId, popupId: def.id, delaySeconds: trigger.delaySeconds });
2876
3063
  });
2877
3064
  });
2878
3065
  if (derived.length) {
2879
3066
  this.configureTriggers(derived);
2880
3067
  }
2881
3068
  }
2882
- /** Lógica para evaluar condiciones antes de mostrar una encuesta */
2883
- triggerSurvey(surveyId, popupId) {
2884
- 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;
2885
3077
  const def = this.findPopupDefinition(surveyId, popupId);
2886
3078
  if (!def) {
2887
3079
  this.debug("No popup definition for trigger", { surveyId, popupId });
@@ -2891,7 +3083,7 @@ var DeepdotsPopups = class {
2891
3083
  this.debug("Conditions prevented showing popup", def.id);
2892
3084
  return;
2893
3085
  }
2894
- this.showDefinition(def);
3086
+ this.showAfterDelay(def, delaySeconds);
2895
3087
  }
2896
3088
  /** Trigger popups configured with trigger.type = 'event' and matching trigger.value */
2897
3089
  triggerEvent(eventName) {
@@ -2908,9 +3100,9 @@ var DeepdotsPopups = class {
2908
3100
  }
2909
3101
  evaluateEvent(normalized) {
2910
3102
  const candidates = this.popupDefinitions.filter((def) => {
2911
- return def.triggers.some((trigger) => {
2912
- const triggerValue = String(trigger.value ?? "").trim();
2913
- 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;
2914
3106
  });
2915
3107
  });
2916
3108
  if (!candidates.length) {
@@ -2922,7 +3114,69 @@ var DeepdotsPopups = class {
2922
3114
  this.debug("Event popup blocked by conditions/segments", { eventName: normalized });
2923
3115
  return;
2924
3116
  }
2925
- 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 || "");
2926
3180
  }
2927
3181
  /**
2928
3182
  * Guarda `trigger` si las definiciones aún no han llegado. Devuelve `true` si lo guardó (el
@@ -2955,7 +3209,7 @@ var DeepdotsPopups = class {
2955
3209
  this.debug("Replaying triggers received before popups loaded", replay.length);
2956
3210
  replay.forEach((trigger) => {
2957
3211
  if (trigger.kind === "event") this.evaluateEvent(trigger.name);
2958
- else this.triggerSurvey(trigger.surveyId, trigger.popupId);
3212
+ else this.triggerSurvey(trigger.surveyId, trigger.popupId, { delaySeconds: trigger.delaySeconds });
2959
3213
  });
2960
3214
  }
2961
3215
  showDefinition(def) {
@@ -2967,7 +3221,7 @@ var DeepdotsPopups = class {
2967
3221
  this.surveyToPopupId.set(def.surveyId, def.id);
2968
3222
  this.lastShown.set(def.id, Date.now());
2969
3223
  this.persistPopupState();
2970
- 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);
2971
3225
  this.emitEvent("popup_shown", def.surveyId, { popupId: def.id });
2972
3226
  }
2973
3227
  shouldShow(def, pathUrl, skipPathCheck = false) {
@@ -3339,7 +3593,7 @@ var DeepdotsPopups = class {
3339
3593
  }
3340
3594
  }
3341
3595
  /** Render the popup UI */
3342
- renderPopup(surveyId, productId, actions, style, title) {
3596
+ renderPopup(surveyId, productId, actions, style, title, surveySdkVersion) {
3343
3597
  const userId = this.tracking?.getUserId() ?? this.config?.userId;
3344
3598
  const sessionId = this.tracking?.getSessionId() ?? void 0;
3345
3599
  const miniService = this.analytics?.getMiniService() ?? void 0;
@@ -3358,7 +3612,7 @@ var DeepdotsPopups = class {
3358
3612
  miniService,
3359
3613
  analyticsFeedbackSessionId,
3360
3614
  this.renderChrome,
3361
- { 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 }
3362
3616
  );
3363
3617
  }
3364
3618
  /** Hide the popup */
@@ -3369,6 +3623,15 @@ var DeepdotsPopups = class {
3369
3623
  emitEvent(type, surveyId, data) {
3370
3624
  const event = { type, surveyId, timestamp: Date.now(), data };
3371
3625
  this.log("Event emitted", event);
3626
+ if (type === "survey_error") {
3627
+ const popupId = data?.popupId || this.surveyToPopupId.get(surveyId);
3628
+ this.track("deepdots_survey_error", {
3629
+ survey_id: surveyId,
3630
+ ...popupId ? { popup_id: popupId } : {},
3631
+ reason: data?.reason,
3632
+ message: data?.message
3633
+ });
3634
+ }
3372
3635
  const isPartialClick = type === "popup_clicked" && data?.action === "partial";
3373
3636
  if (isPartialClick) {
3374
3637
  this.markSurveyProgress(surveyId, "PARTIAL");
@@ -3516,10 +3779,10 @@ var DeepdotsPopups = class {
3516
3779
  }
3517
3780
  normalizeTriggers(value) {
3518
3781
  const items = Array.isArray(value) ? value : value ? [value] : [];
3519
- return items.filter((trigger) => this.isPopupTrigger(trigger)).map((trigger) => ({
3520
- type: trigger.type,
3521
- value: trigger.value
3522
- }));
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
+ });
3523
3786
  }
3524
3787
  normalizeCooldown(value) {
3525
3788
  if (!Array.isArray(value)) return [];
@@ -3574,7 +3837,9 @@ function setupReactNative(sdk2, config, deps = {}) {
3574
3837
  const storage = deps.mmkv ? mmkvStorage(deps.mmkv) : config.storage;
3575
3838
  const device = deps.deviceInfo ? collectRnDevice(deps.deviceInfo) : config.device;
3576
3839
  const platform = deps.platform ?? config.platform;
3577
- 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 });
3578
3843
  const errorUtils = deps.errorUtils ?? globalThis.ErrorUtils;
3579
3844
  if (errorUtils && typeof errorUtils.setGlobalHandler === "function") {
3580
3845
  sdk2.installReactNativeCrashHandler(errorUtils);
@@ -3584,7 +3849,7 @@ function setupReactNative(sdk2, config, deps = {}) {
3584
3849
  subscription = deps.appState.addEventListener("change", (state) => {
3585
3850
  if (state === "active") sdk2.onForeground();
3586
3851
  else if (state === "background") sdk2.onBackground();
3587
- else sdk2.flushAnalytics();
3852
+ else sdk2.onInactive();
3588
3853
  });
3589
3854
  }
3590
3855
  return () => {
@@ -3594,6 +3859,11 @@ function setupReactNative(sdk2, config, deps = {}) {
3594
3859
 
3595
3860
  // src/react-native/index.tsx
3596
3861
  import { jsx, jsxs } from "react/jsx-runtime";
3862
+ registerReactNativePlatform({
3863
+ os: Platform.OS,
3864
+ appState: AppState,
3865
+ backgroundTaskModule: NativeModules?.DeepdotsBackgroundTask ?? null
3866
+ });
3597
3867
  var sdk = new DeepdotsPopups();
3598
3868
  var DeepdotsContext = createContext(sdk);
3599
3869
  var useDeepdots = () => useContext(DeepdotsContext);