@magicfeedback/popup-sdk 1.18.0 → 1.20.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-BJTO5JO5.mjs +11 -0
  17. package/dist/chunk-BJTO5JO5.mjs.map +1 -0
  18. package/dist/{chunk-DNBFTJCA.mjs → chunk-FROREHRG.mjs} +516 -52
  19. package/dist/chunk-FROREHRG.mjs.map +1 -0
  20. package/dist/{chunk-7ZVOPIWE.mjs → chunk-OPR5I7WO.mjs} +557 -11
  21. package/dist/chunk-OPR5I7WO.mjs.map +1 -0
  22. package/dist/chunk-ZJ5HG3QF.mjs +3357 -0
  23. package/dist/chunk-ZJ5HG3QF.mjs.map +1 -0
  24. package/dist/index.d.mts +217 -9
  25. package/dist/index.d.ts +217 -9
  26. package/dist/index.js +7253 -1519
  27. package/dist/index.js.map +1 -1
  28. package/dist/index.mjs +389 -49
  29. package/dist/index.mjs.map +1 -1
  30. package/dist/index.native.d.mts +1681 -0
  31. package/dist/index.native.d.ts +1681 -0
  32. package/dist/index.native.js +15972 -0
  33. package/dist/index.native.js.map +1 -0
  34. package/dist/index.native.mjs +4011 -0
  35. package/dist/index.native.mjs.map +1 -0
  36. package/dist/react-native.d.mts +113 -7
  37. package/dist/react-native.d.ts +113 -7
  38. package/dist/react-native.js +5846 -162
  39. package/dist/react-native.js.map +1 -1
  40. package/dist/react-native.mjs +396 -51
  41. package/dist/react-native.mjs.map +1 -1
  42. package/dist/{renderPopup-B6VIV4VS.mjs → renderPopup-I6CPIR75.mjs} +133 -6
  43. package/dist/renderPopup-I6CPIR75.mjs.map +1 -0
  44. package/dist/renderPopup-RUY3OBYV.mjs +3847 -0
  45. package/dist/renderPopup-RUY3OBYV.mjs.map +1 -0
  46. package/dist/renderPopup-XNVNP2ZU.mjs +3847 -0
  47. package/dist/renderPopup-XNVNP2ZU.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-FROREHRG.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-I6CPIR75.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-I6CPIR75.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
@@ -1882,6 +1970,8 @@ var CrashReporter = class {
1882
1970
  this.windowInstalled = false;
1883
1971
  /** ErrorUtils ya enganchados: engancharlos dos veces capturaría cada error dos veces. */
1884
1972
  this.hookedErrorUtils = /* @__PURE__ */ new Set();
1973
+ /** Fuentes de rejections ya enganchadas (idempotente, como ErrorUtils). */
1974
+ this.hookedRejections = /* @__PURE__ */ new Set();
1885
1975
  this.options = options;
1886
1976
  this.now = options.now ?? (() => Date.now());
1887
1977
  }
@@ -1981,6 +2071,18 @@ var CrashReporter = class {
1981
2071
  previous?.(error, isFatal);
1982
2072
  });
1983
2073
  }
2074
+ /**
2075
+ * Promesas rechazadas sin `catch` en React Native: como el `unhandledrejection` de web, se
2076
+ * persisten y se reenvían en el arranque siguiente. La fuente encadena al tracker del host.
2077
+ * Idempotente por fuente.
2078
+ */
2079
+ installPromiseRejections(source) {
2080
+ if (this.hookedRejections.has(source)) return;
2081
+ this.hookedRejections.add(source);
2082
+ source.addUnhandledListener((error) => {
2083
+ if (this.isEnabled()) this.captureUnhandled(error ?? "unhandledrejection");
2084
+ });
2085
+ }
1984
2086
  /** @internal Test seam: ejercita el camino de persistencia (window handlers no son testeables en vitest). */
1985
2087
  _persistForTest(error) {
1986
2088
  this.captureUnhandled(error);
@@ -2056,6 +2158,81 @@ function clearPopupState(storage) {
2056
2158
  }
2057
2159
  }
2058
2160
 
2161
+ // src/platform/react-native-platform.ts
2162
+ var registered = null;
2163
+ function registerReactNativePlatform(platform) {
2164
+ registered = platform;
2165
+ }
2166
+ function getReactNativePlatform() {
2167
+ return registered;
2168
+ }
2169
+ function nativeModuleTask(mod) {
2170
+ let seq = 0;
2171
+ return (name) => {
2172
+ const token = `dd-${Date.now().toString(36)}-${(seq++).toString(36)}`;
2173
+ mod.begin(token, name);
2174
+ let ended = false;
2175
+ return () => {
2176
+ if (ended) return;
2177
+ ended = true;
2178
+ mod.end(token);
2179
+ };
2180
+ };
2181
+ }
2182
+ function resolveBackgroundTask(explicit, platform) {
2183
+ if (explicit) return explicit;
2184
+ const mod = platform?.backgroundTaskModule;
2185
+ if (platform?.os === "ios" && mod && typeof mod.begin === "function" && typeof mod.end === "function") {
2186
+ return nativeModuleTask(mod);
2187
+ }
2188
+ return void 0;
2189
+ }
2190
+ var DEFAULT_REJECTION_WHITELIST = [ReferenceError, TypeError, RangeError];
2191
+ function createHermesRejectionHub(hermes, options) {
2192
+ if (!hermes || typeof hermes.enablePromiseRejectionTracker !== "function") return null;
2193
+ const original = hermes.enablePromiseRejectionTracker.bind(hermes);
2194
+ const listeners = /* @__PURE__ */ new Set();
2195
+ let hostOptions = null;
2196
+ let active = false;
2197
+ const forwardsToHost = (error) => !!hostOptions?.onUnhandled && (hostOptions.allRejections === true || DEFAULT_REJECTION_WHITELIST.some((type) => error instanceof type));
2198
+ const apply = () => {
2199
+ original({
2200
+ allRejections: true,
2201
+ onUnhandled: (id, error) => {
2202
+ listeners.forEach((listener) => {
2203
+ try {
2204
+ listener(error);
2205
+ } catch {
2206
+ }
2207
+ });
2208
+ if (hostOptions?.onUnhandled) {
2209
+ if (forwardsToHost(error)) hostOptions.onUnhandled(id, error);
2210
+ } else if (options.dev) {
2211
+ console.warn(`Possible unhandled promise rejection (id: ${id}):`, error);
2212
+ }
2213
+ },
2214
+ onHandled: (id, error) => hostOptions?.onHandled?.(id, error)
2215
+ });
2216
+ };
2217
+ hermes.enablePromiseRejectionTracker = (next) => {
2218
+ hostOptions = next ?? null;
2219
+ if (active) apply();
2220
+ else original(next);
2221
+ };
2222
+ return {
2223
+ addUnhandledListener(listener) {
2224
+ listeners.add(listener);
2225
+ if (!active) {
2226
+ active = true;
2227
+ apply();
2228
+ }
2229
+ return () => {
2230
+ listeners.delete(listener);
2231
+ };
2232
+ }
2233
+ };
2234
+ }
2235
+
2059
2236
  // src/analytics/messaging.ts
2060
2237
  var MESSAGE_CHANNELS = ["push", "in_app"];
2061
2238
  function buildMessageParams(stage, o) {
@@ -2135,6 +2312,10 @@ var ANALYTICS_RESUME_WINDOW_MS = 6e4;
2135
2312
  var RESERVED_EVENT_PREFIX = "deepdots_";
2136
2313
  var CUSTOM_EVENT_PREFIX = "deepdots_event_";
2137
2314
  var MAX_PENDING_TRIGGERS = 20;
2315
+ function triggerDelayMs(delaySeconds) {
2316
+ const n = typeof delaySeconds === "number" ? delaySeconds : Number(delaySeconds);
2317
+ return Number.isFinite(n) && n > 0 ? Math.round(n * 1e3) : 0;
2318
+ }
2138
2319
  var DeepdotsPopups = class {
2139
2320
  constructor() {
2140
2321
  this.config = null;
@@ -2166,6 +2347,10 @@ var DeepdotsPopups = class {
2166
2347
  this.surveyToPopupId = /* @__PURE__ */ new Map();
2167
2348
  // surveyId -> popupId
2168
2349
  this.deferredExitTimers = [];
2350
+ /** Popups esperando su `delaySeconds` (uno por popup). */
2351
+ this.delayedPopups = /* @__PURE__ */ new Map();
2352
+ /** Última pantalla de `setScreen` (React Native). */
2353
+ this.currentScreen = null;
2169
2354
  this.baseUrl = "";
2170
2355
  this.env = "production";
2171
2356
  /** Si el SDK pinta el "modal" del popup (RN). Default true; false = el host lo envuelve. */
@@ -2211,6 +2396,10 @@ var DeepdotsPopups = class {
2211
2396
  this.lastEngagementAt = 0;
2212
2397
  /** Cuándo se ocultó la pestaña por última vez (ms epoch); null si está visible. */
2213
2398
  this.hiddenAt = null;
2399
+ /** `init({ autoTrack: { errors } })`: captura automática de errores. Activa por defecto. */
2400
+ this.autoTrackErrors = true;
2401
+ /** Suscripción automática a AppState (React Native, `autoTrack.lifecycle`). */
2402
+ this.appStateSubscription = void 0;
2214
2403
  /**
2215
2404
  * Sesión suspendida por un `pagehide` (ms epoch y `deepdots_user_id`); null si no hay.
2216
2405
  * `openSession` la reanuda si sigue a tiempo (ver ANALYTICS_RESUME_WINDOW_MS).
@@ -2243,6 +2432,10 @@ var DeepdotsPopups = class {
2243
2432
  this.log("SDK already initialized");
2244
2433
  return;
2245
2434
  }
2435
+ const rn = getReactNativePlatform();
2436
+ if (!config.platform && (rn?.os === "ios" || rn?.os === "android")) {
2437
+ config = { ...config, platform: rn.os };
2438
+ }
2246
2439
  const env = resolveEnvironment(config.nodeEnv);
2247
2440
  this.baseUrl = env.apiBaseUrl;
2248
2441
  this.env = config.nodeEnv || "production";
@@ -2251,6 +2444,7 @@ var DeepdotsPopups = class {
2251
2444
  this.surveyCss = config.surveyCss;
2252
2445
  this.cspNonce = config.cspNonce;
2253
2446
  this.onFeedbackSession = config.onFeedbackSession;
2447
+ this.autoTrackErrors = config.autoTrack?.errors !== false;
2254
2448
  this.config = {
2255
2449
  apiKey: config.apiKey || void 0,
2256
2450
  debug: config.debug || false,
@@ -2293,6 +2487,10 @@ var DeepdotsPopups = class {
2293
2487
  // persiste y se reenvía en el arranque siguiente. En web el cierre sale con
2294
2488
  // `keepalive` y varias pestañas compartirían el mismo storage.
2295
2489
  storage: (config.platform ?? "web") !== "web" ? storage : void 0,
2490
+ // iOS suspende la app con el POST de cierre en vuelo: el host puede darle
2491
+ // tiempo de background (DD-55). El reenvío del arranque siguiente sigue igual.
2492
+ // La del host o, en iOS, la del módulo nativo del paquete (autolinking).
2493
+ backgroundTask: resolveBackgroundTask(config.backgroundTask, rn),
2296
2494
  onSessionId: (id) => {
2297
2495
  this.analyticsFeedbackSessionId = id;
2298
2496
  this.notifyFeedbackSession(id, "open");
@@ -2350,6 +2548,7 @@ var DeepdotsPopups = class {
2350
2548
  }
2351
2549
  }
2352
2550
  this.initialized = true;
2551
+ this.installAutoLifecycle(rn, config);
2353
2552
  this.log("SDK initialized", this.config);
2354
2553
  if (this.renderer.init) this.renderer.init();
2355
2554
  this.awaitingPopups = Boolean(this.config.apiKey && this.baseUrl);
@@ -2444,11 +2643,14 @@ var DeepdotsPopups = class {
2444
2643
  */
2445
2644
  installCrashHandlers() {
2446
2645
  if (!this.crashReporter || !this.tracking?.isTrackingEnabled()) return;
2447
- this.crashReporter.install();
2448
- const errorUtils = this.rnErrorUtils ?? globalThis.ErrorUtils;
2646
+ const auto = this.autoTrackErrors;
2647
+ if (auto) this.crashReporter.install();
2648
+ const errorUtils = this.rnErrorUtils ?? (auto ? globalThis.ErrorUtils : void 0);
2449
2649
  if (errorUtils && typeof errorUtils.setGlobalHandler === "function") {
2450
2650
  this.crashReporter.installReactNative(errorUtils);
2451
2651
  }
2652
+ const rejections = auto ? getReactNativePlatform()?.promiseRejections : null;
2653
+ if (rejections) this.crashReporter.installPromiseRejections(rejections);
2452
2654
  }
2453
2655
  /**
2454
2656
  * Info interna del usuario que solo conoce el host (idioma, edad, plan…), persistida en el
@@ -2520,6 +2722,11 @@ var DeepdotsPopups = class {
2520
2722
  * El host la llama en cada cambio de pantalla; emite `page_view` al salir de la anterior.
2521
2723
  */
2522
2724
  setScreen(name) {
2725
+ const screen2 = typeof name === "string" ? name.trim() : "";
2726
+ if (screen2) {
2727
+ this.cancelDelayedPopups("screen change", (entry) => entry.screen !== screen2);
2728
+ this.currentScreen = screen2;
2729
+ }
2523
2730
  if (!this.navObserver) return;
2524
2731
  if (!this.navStarted) {
2525
2732
  this.navObserver.begin(name);
@@ -2541,9 +2748,42 @@ var DeepdotsPopups = class {
2541
2748
  * Es la única señal disponible en móvil: el kill de la app (swipe) NO da callback.
2542
2749
  */
2543
2750
  onBackground() {
2751
+ this.cancelDelayedPopups("app to background");
2544
2752
  this.closeSession("background");
2545
2753
  this.engagement?.pause();
2546
2754
  }
2755
+ /**
2756
+ * App a `inactive` (RN, iOS: centro de control, llamada, app switcher, y SIEMPRE justo antes
2757
+ * de `background`). NO cierra la sesión (es transitorio), pero envía lo acumulado con un
2758
+ * `user_engagement` que lleva la pantalla en curso, como web al ocultar la pestaña: si el
2759
+ * lote de cierre de `background` no llega a salir (iOS suspende la app), el backend ya
2760
+ * tiene el tiempo activo y la última pantalla. El contador sigue en marcha.
2761
+ */
2762
+ onInactive() {
2763
+ if (this.sessionOpen) this.flushEngagement();
2764
+ this.flushAnalytics();
2765
+ }
2766
+ /**
2767
+ * Ciclo de vida automático en React Native (contrato de detección automática): el SDK escucha
2768
+ * AppState él mismo, así que el host no tiene que llamar a `onForeground`/`onInactive`/
2769
+ * `onBackground`. Si el host los llama además (integraciones anteriores), no se duplica nada:
2770
+ * abrir o cerrar una sesión ya abierta o cerrada no hace nada, y el engagement se consume.
2771
+ * `autoTrack.lifecycle: false` lo apaga.
2772
+ */
2773
+ installAutoLifecycle(rn, config) {
2774
+ if (config.autoTrack?.lifecycle === false) return;
2775
+ const appState = rn?.appState;
2776
+ if (!appState || typeof appState.addEventListener !== "function" || this.appStateSubscription) return;
2777
+ try {
2778
+ this.appStateSubscription = appState.addEventListener("change", (state) => {
2779
+ if (state === "active") this.onForeground();
2780
+ else if (state === "background") this.onBackground();
2781
+ else this.onInactive();
2782
+ });
2783
+ this.log("lifecycle \xB7 AppState wired automatically");
2784
+ } catch {
2785
+ }
2786
+ }
2547
2787
  /**
2548
2788
  * Cierre EXPLÍCITO de la sesión por parte del host (logout, fin de flujo…): emite
2549
2789
  * `session_end` y envía el último lote con `completed:true`.
@@ -2556,11 +2796,24 @@ var DeepdotsPopups = class {
2556
2796
  * anterior (`session_end` con `reason: 'user_change'` + `completed:true`), cambia la
2557
2797
  * identidad y abre una sesión nueva. Sin `userId` vuelve al id anónimo del SDK.
2558
2798
  *
2799
+ * Anónimo → identificado (la app arranca sin `userId` y lo pone al hacer login) es la MISMA
2800
+ * persona, no otra: el `session_start` de la sesión nueva lleva `identified: true`,
2801
+ * `previous_user_id` (el id anónimo) y `previous_session_id` (el registro que se acaba de
2802
+ * cerrar), para que el backend una las dos sin adivinar; y el estado de popups (mostrados,
2803
+ * respondidos, protecciones de mensajes) se conserva. Sin esto, cada persona que se registra
2804
+ * contaba dos veces: una que "abandona" en el login y otra registrada nueva.
2805
+ *
2559
2806
  * Equivale a llamar a `init()` otra vez con otro `userId`.
2560
2807
  */
2561
2808
  setUserId(userId) {
2562
2809
  const next = userId || void 0;
2563
2810
  if (!this.initialized || !this.config || next === this.config.userId) return;
2811
+ const identifying = !this.config.userId && !!next;
2812
+ const previous = identifying ? {
2813
+ identified: true,
2814
+ previous_user_id: this.tracking?.getUserId() ?? void 0,
2815
+ previous_session_id: this.analyticsFeedbackSessionId
2816
+ } : void 0;
2564
2817
  this.closeSession("user_change");
2565
2818
  const enabled = this.tracking?.isTrackingEnabled() ?? true;
2566
2819
  const storage = this.storage ?? createDefaultStorage();
@@ -2573,13 +2826,18 @@ var DeepdotsPopups = class {
2573
2826
  post: (body) => this.postContact(body)
2574
2827
  }) : null;
2575
2828
  this.analytics?.resetUserScope();
2576
- this.messageGuard.reset();
2577
- this.lastShown.clear();
2578
- this.surveyProgress.clear();
2579
- this.answeredSurveys.clear();
2580
- clearPopupState(storage);
2581
- this.log("tracking \xB7 user_change \xB7 user_id:", this.tracking.getUserId());
2582
- this.openSession("user_change");
2829
+ if (!identifying) {
2830
+ this.messageGuard.reset();
2831
+ this.lastShown.clear();
2832
+ this.surveyProgress.clear();
2833
+ this.answeredSurveys.clear();
2834
+ clearPopupState(storage);
2835
+ }
2836
+ this.log(
2837
+ identifying ? "tracking \xB7 user identified \xB7 user_id:" : "tracking \xB7 user_change \xB7 user_id:",
2838
+ this.tracking.getUserId()
2839
+ );
2840
+ this.openSession("user_change", previous);
2583
2841
  }
2584
2842
  /**
2585
2843
  * Cierra la sesión actual: vuelca todo lo que quedaba abierto y envía el último lote
@@ -2615,14 +2873,14 @@ var DeepdotsPopups = class {
2615
2873
  * - `bfcache_restore`: vuelta desde la bfcache fuera de la ventana de reanudación.
2616
2874
  * Si hay una sesión suspendida a tiempo emite `deepdots_session_resume` en su lugar, sin reason.
2617
2875
  */
2618
- openSession(reason) {
2876
+ openSession(reason, extra) {
2619
2877
  if (this.sessionOpen) return;
2620
2878
  if (!this.tracking?.isTrackingEnabled()) return;
2621
2879
  const suspendedMs = this.takeSuspendedSession();
2622
2880
  this.sessionOpen = true;
2623
2881
  this.lastEngagementAt = Date.now();
2624
2882
  if (suspendedMs === null) {
2625
- this.track("deepdots_session_start", { reason });
2883
+ this.track("deepdots_session_start", { reason, ...extra });
2626
2884
  } else {
2627
2885
  this.track("deepdots_session_resume", { suspended_ms: suspendedMs });
2628
2886
  this.log("tracking \xB7 session resumed after", suspendedMs, "ms:", this.analyticsFeedbackSessionId);
@@ -2884,16 +3142,21 @@ var DeepdotsPopups = class {
2884
3142
  return;
2885
3143
  }
2886
3144
  const value = type === "time" && typeof trigger.value === "number" ? trigger.value * 1e3 : trigger.value;
2887
- derived.push({ type, value, surveyId: def.surveyId, popupId: def.id });
3145
+ derived.push({ type, value, surveyId: def.surveyId, popupId: def.id, delaySeconds: trigger.delaySeconds });
2888
3146
  });
2889
3147
  });
2890
3148
  if (derived.length) {
2891
3149
  this.configureTriggers(derived);
2892
3150
  }
2893
3151
  }
2894
- /** Lógica para evaluar condiciones antes de mostrar una encuesta */
2895
- triggerSurvey(surveyId, popupId) {
2896
- if (this.bufferIfAwaitingPopups({ kind: "survey", surveyId, popupId })) return;
3152
+ /**
3153
+ * Lógica para evaluar condiciones antes de mostrar una encuesta. `options.delaySeconds`
3154
+ * (lo pasan los triggers time/scroll/click con el "Delay" del Admin) espera ese tiempo y
3155
+ * vuelve a evaluar antes de mostrar; sin él, al momento como siempre.
3156
+ */
3157
+ triggerSurvey(surveyId, popupId, options) {
3158
+ const delaySeconds = options?.delaySeconds;
3159
+ if (this.bufferIfAwaitingPopups({ kind: "survey", surveyId, popupId, delaySeconds })) return;
2897
3160
  const def = this.findPopupDefinition(surveyId, popupId);
2898
3161
  if (!def) {
2899
3162
  this.debug("No popup definition for trigger", { surveyId, popupId });
@@ -2903,7 +3166,7 @@ var DeepdotsPopups = class {
2903
3166
  this.debug("Conditions prevented showing popup", def.id);
2904
3167
  return;
2905
3168
  }
2906
- this.showDefinition(def);
3169
+ this.showAfterDelay(def, delaySeconds);
2907
3170
  }
2908
3171
  /** Trigger popups configured with trigger.type = 'event' and matching trigger.value */
2909
3172
  triggerEvent(eventName) {
@@ -2920,9 +3183,9 @@ var DeepdotsPopups = class {
2920
3183
  }
2921
3184
  evaluateEvent(normalized) {
2922
3185
  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;
3186
+ return def.triggers.some((trigger2) => {
3187
+ const triggerValue = String(trigger2.value ?? "").trim();
3188
+ return trigger2.type === "event" && triggerValue === normalized;
2926
3189
  });
2927
3190
  });
2928
3191
  if (!candidates.length) {
@@ -2934,7 +3197,69 @@ var DeepdotsPopups = class {
2934
3197
  this.debug("Event popup blocked by conditions/segments", { eventName: normalized });
2935
3198
  return;
2936
3199
  }
2937
- this.showDefinition(matched);
3200
+ const trigger = matched.triggers.find(
3201
+ (t) => t.type === "event" && String(t.value ?? "").trim() === normalized
3202
+ );
3203
+ this.showAfterDelay(matched, trigger?.delaySeconds);
3204
+ }
3205
+ /**
3206
+ * Muestra `def` ya, o tras su "Delay (seconds)" del Admin. Mientras espera:
3207
+ * - el mismo popup no se programa dos veces (el primer vencimiento manda);
3208
+ * - cambiar de ruta/pantalla o pasar a background lo cancela;
3209
+ * y al vencer se vuelve a evaluar todo (segmentos, idioma, cooldowns) como un disparo nuevo.
3210
+ * Si entonces hay otro popup abierto, `showDefinition` lo salta sin efectos, igual que hoy.
3211
+ */
3212
+ showAfterDelay(def, delaySeconds) {
3213
+ const delayMs = triggerDelayMs(delaySeconds);
3214
+ if (delayMs <= 0) {
3215
+ this.showDefinition(def);
3216
+ return;
3217
+ }
3218
+ if (this.delayedPopups.has(def.id)) {
3219
+ this.debug("Popup already waiting for its delay", def.id);
3220
+ return;
3221
+ }
3222
+ const entry = {
3223
+ popupId: def.id,
3224
+ timer: setTimeout(() => this.showDelayedPopup(def.id), delayMs),
3225
+ firedAt: Date.now(),
3226
+ href: this.currentHref(),
3227
+ screen: this.currentScreen
3228
+ };
3229
+ this.delayedPopups.set(def.id, entry);
3230
+ this.debug(`Popup delayed ${delayMs}ms`, def.id);
3231
+ }
3232
+ showDelayedPopup(popupId) {
3233
+ const entry = this.delayedPopups.get(popupId);
3234
+ if (!entry) return;
3235
+ this.delayedPopups.delete(popupId);
3236
+ const def = this.popupDefinitions.find((popup) => popup.id === popupId);
3237
+ if (!def) return;
3238
+ if (this.currentHref() !== entry.href || this.currentScreen !== entry.screen) {
3239
+ this.debug("Delayed popup dropped: route changed", popupId);
3240
+ return;
3241
+ }
3242
+ if (!this.shouldShow(def)) {
3243
+ this.debug("Delayed popup dropped by conditions at due time", popupId);
3244
+ return;
3245
+ }
3246
+ if ((this.lastShown.get(popupId) ?? 0) >= entry.firedAt) {
3247
+ this.debug("Delayed popup dropped: already shown while waiting", popupId);
3248
+ return;
3249
+ }
3250
+ this.showDefinition(def);
3251
+ }
3252
+ cancelDelayedPopups(reason, predicate = () => true) {
3253
+ this.delayedPopups.forEach((entry, popupId) => {
3254
+ if (!predicate(entry)) return;
3255
+ clearTimeout(entry.timer);
3256
+ this.delayedPopups.delete(popupId);
3257
+ this.debug(`Delayed popup cancelled (${reason})`, popupId);
3258
+ });
3259
+ }
3260
+ currentHref() {
3261
+ if (typeof window === "undefined" || !window.location) return "";
3262
+ return this.normalizeUrl(window.location.href || "");
2938
3263
  }
2939
3264
  /**
2940
3265
  * Guarda `trigger` si las definiciones aún no han llegado. Devuelve `true` si lo guardó (el
@@ -2967,7 +3292,7 @@ var DeepdotsPopups = class {
2967
3292
  this.debug("Replaying triggers received before popups loaded", replay.length);
2968
3293
  replay.forEach((trigger) => {
2969
3294
  if (trigger.kind === "event") this.evaluateEvent(trigger.name);
2970
- else this.triggerSurvey(trigger.surveyId, trigger.popupId);
3295
+ else this.triggerSurvey(trigger.surveyId, trigger.popupId, { delaySeconds: trigger.delaySeconds });
2971
3296
  });
2972
3297
  }
2973
3298
  showDefinition(def) {
@@ -2979,7 +3304,7 @@ var DeepdotsPopups = class {
2979
3304
  this.surveyToPopupId.set(def.surveyId, def.id);
2980
3305
  this.lastShown.set(def.id, Date.now());
2981
3306
  this.persistPopupState();
2982
- this.renderPopup(def.surveyId, def.productId, def.actions, def.style, def.title);
3307
+ this.renderPopup(def.surveyId, def.productId, def.actions, def.style, def.title, def.surveyFrontend?.sdkVersion);
2983
3308
  this.emitEvent("popup_shown", def.surveyId, { popupId: def.id });
2984
3309
  }
2985
3310
  shouldShow(def, pathUrl, skipPathCheck = false) {
@@ -3351,7 +3676,7 @@ var DeepdotsPopups = class {
3351
3676
  }
3352
3677
  }
3353
3678
  /** Render the popup UI */
3354
- renderPopup(surveyId, productId, actions, style, title) {
3679
+ renderPopup(surveyId, productId, actions, style, title, surveySdkVersion) {
3355
3680
  const userId = this.tracking?.getUserId() ?? this.config?.userId;
3356
3681
  const sessionId = this.tracking?.getSessionId() ?? void 0;
3357
3682
  const miniService = this.analytics?.getMiniService() ?? void 0;
@@ -3370,7 +3695,7 @@ var DeepdotsPopups = class {
3370
3695
  miniService,
3371
3696
  analyticsFeedbackSessionId,
3372
3697
  this.renderChrome,
3373
- { title, showProgressBar: this.showProgressBar, surveyCss: this.surveyCss, language: this.language, cspNonce: this.cspNonce }
3698
+ { title, showProgressBar: this.showProgressBar, surveyCss: this.surveyCss, language: this.language, cspNonce: this.cspNonce, surveySdkVersion, debug: this.config?.debug }
3374
3699
  );
3375
3700
  }
3376
3701
  /** Hide the popup */
@@ -3537,10 +3862,10 @@ var DeepdotsPopups = class {
3537
3862
  }
3538
3863
  normalizeTriggers(value) {
3539
3864
  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
- }));
3865
+ return items.filter((trigger) => this.isPopupTrigger(trigger)).map((trigger) => {
3866
+ const delayMs = triggerDelayMs(trigger.delaySeconds);
3867
+ return delayMs > 0 ? { type: trigger.type, value: trigger.value, delaySeconds: delayMs / 1e3 } : { type: trigger.type, value: trigger.value };
3868
+ });
3544
3869
  }
3545
3870
  normalizeCooldown(value) {
3546
3871
  if (!Array.isArray(value)) return [];
@@ -3595,7 +3920,9 @@ function setupReactNative(sdk2, config, deps = {}) {
3595
3920
  const storage = deps.mmkv ? mmkvStorage(deps.mmkv) : config.storage;
3596
3921
  const device = deps.deviceInfo ? collectRnDevice(deps.deviceInfo) : config.device;
3597
3922
  const platform = deps.platform ?? config.platform;
3598
- sdk2.init({ ...config, storage, device, platform });
3923
+ const backgroundTask = config.backgroundTask ?? deps.backgroundTask ?? void 0;
3924
+ const autoTrack = deps.appState?.addEventListener ? { ...config.autoTrack, lifecycle: false } : config.autoTrack;
3925
+ sdk2.init({ ...config, storage, device, platform, backgroundTask, autoTrack });
3599
3926
  const errorUtils = deps.errorUtils ?? globalThis.ErrorUtils;
3600
3927
  if (errorUtils && typeof errorUtils.setGlobalHandler === "function") {
3601
3928
  sdk2.installReactNativeCrashHandler(errorUtils);
@@ -3605,7 +3932,7 @@ function setupReactNative(sdk2, config, deps = {}) {
3605
3932
  subscription = deps.appState.addEventListener("change", (state) => {
3606
3933
  if (state === "active") sdk2.onForeground();
3607
3934
  else if (state === "background") sdk2.onBackground();
3608
- else sdk2.flushAnalytics();
3935
+ else sdk2.onInactive();
3609
3936
  });
3610
3937
  }
3611
3938
  return () => {
@@ -3613,8 +3940,26 @@ function setupReactNative(sdk2, config, deps = {}) {
3613
3940
  };
3614
3941
  }
3615
3942
 
3943
+ // src/platform/react-native-defaults.ts
3944
+ var hub;
3945
+ function registerReactNativeDefaults(rn) {
3946
+ if (hub === void 0) {
3947
+ hub = getReactNativePlatform()?.promiseRejections ?? createHermesRejectionHub(
3948
+ globalThis.HermesInternal,
3949
+ { dev: typeof __DEV__ !== "undefined" && !!__DEV__ }
3950
+ );
3951
+ }
3952
+ registerReactNativePlatform({
3953
+ os: rn.Platform.OS,
3954
+ appState: rn.AppState,
3955
+ backgroundTaskModule: rn.NativeModules?.DeepdotsBackgroundTask ?? null,
3956
+ promiseRejections: hub
3957
+ });
3958
+ }
3959
+
3616
3960
  // src/react-native/index.tsx
3617
3961
  import { jsx, jsxs } from "react/jsx-runtime";
3962
+ registerReactNativeDefaults({ AppState, NativeModules, Platform });
3618
3963
  var sdk = new DeepdotsPopups();
3619
3964
  var DeepdotsContext = createContext(sdk);
3620
3965
  var useDeepdots = () => useContext(DeepdotsContext);