@magicfeedback/popup-sdk 1.19.0 → 1.21.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 (34) hide show
  1. package/dist/{chunk-EW2ARDEY.mjs → chunk-BWYWXAIQ.mjs} +23 -3
  2. package/dist/chunk-BWYWXAIQ.mjs.map +1 -0
  3. package/dist/{chunk-7ZQOAKXR.mjs → chunk-H434NTBB.mjs} +26 -4
  4. package/dist/chunk-H434NTBB.mjs.map +1 -0
  5. package/dist/{chunk-XOEEBDBJ.mjs → chunk-UBUY6G6Z.mjs} +26 -4
  6. package/dist/chunk-UBUY6G6Z.mjs.map +1 -0
  7. package/dist/index.d.mts +105 -10
  8. package/dist/index.d.ts +105 -10
  9. package/dist/index.js +186 -37
  10. package/dist/index.js.map +1 -1
  11. package/dist/index.mjs +163 -36
  12. package/dist/index.mjs.map +1 -1
  13. package/dist/index.native.d.mts +105 -10
  14. package/dist/index.native.d.ts +105 -10
  15. package/dist/index.native.js +204 -42
  16. package/dist/index.native.js.map +1 -1
  17. package/dist/index.native.mjs +181 -41
  18. package/dist/index.native.mjs.map +1 -1
  19. package/dist/react-native.d.mts +47 -8
  20. package/dist/react-native.d.ts +47 -8
  21. package/dist/react-native.js +200 -41
  22. package/dist/react-native.js.map +1 -1
  23. package/dist/react-native.mjs +180 -41
  24. package/dist/react-native.mjs.map +1 -1
  25. package/dist/{renderPopup-2Y4QMWR7.mjs → renderPopup-HNSFPFVT.mjs} +2 -2
  26. package/dist/{renderPopup-ZHTRMFO2.mjs → renderPopup-VXKWSZ4E.mjs} +2 -2
  27. package/dist/{renderPopup-YDJUON42.mjs → renderPopup-WNF67H5T.mjs} +2 -2
  28. package/package.json +1 -1
  29. package/dist/chunk-7ZQOAKXR.mjs.map +0 -1
  30. package/dist/chunk-EW2ARDEY.mjs.map +0 -1
  31. package/dist/chunk-XOEEBDBJ.mjs.map +0 -1
  32. /package/dist/{renderPopup-2Y4QMWR7.mjs.map → renderPopup-HNSFPFVT.mjs.map} +0 -0
  33. /package/dist/{renderPopup-ZHTRMFO2.mjs.map → renderPopup-VXKWSZ4E.mjs.map} +0 -0
  34. /package/dist/{renderPopup-YDJUON42.mjs.map → renderPopup-WNF67H5T.mjs.map} +0 -0
@@ -151,6 +151,12 @@ interface FeedbackSession {
151
151
  interface AutoTrackOptions {
152
152
  /** React Native: listen to `AppState` for session start/end. Default `true`. */
153
153
  lifecycle?: boolean;
154
+ /**
155
+ * Uncaught errors: `window` `error`/`unhandledrejection` (web), `ErrorUtils` and promise
156
+ * rejections without `catch` under Hermes (React Native). Default `true`. Handlers installed
157
+ * by other tools (Sentry, Crashlytics) keep receiving everything.
158
+ */
159
+ errors?: boolean;
154
160
  }
155
161
  interface DeepdotsInitParams {
156
162
  /** API key for authentication */
@@ -532,6 +538,8 @@ declare class DeepdotsPopups {
532
538
  private lastEngagementAt;
533
539
  /** Cuándo se ocultó la pestaña por última vez (ms epoch); null si está visible. */
534
540
  private hiddenAt;
541
+ /** `init({ autoTrack: { errors } })`: captura automática de errores. Activa por defecto. */
542
+ private autoTrackErrors;
535
543
  /** Suscripción automática a AppState (React Native, `autoTrack.lifecycle`). */
536
544
  private appStateSubscription;
537
545
  /**
@@ -630,14 +638,21 @@ declare class DeepdotsPopups {
630
638
  * El host la llama en cada cambio de pantalla; emite `page_view` al salir de la anterior.
631
639
  */
632
640
  setScreen(name: string): void;
633
- /** App a foreground (RN: AppState 'active'): reanuda el engagement time y abre sesión nueva. */
641
+ /**
642
+ * App a foreground (RN: AppState 'active'): reanuda el engagement time. Si la app estuvo en
643
+ * background menos de ANALYTICS_BACKGROUND_RESUME_WINDOW_MS sigue en la misma sesión
644
+ * (`deepdots_session_resume`); si no, abre una nueva (`session_start` `foreground`).
645
+ */
634
646
  onForeground(): void;
635
647
  /**
636
- * App a background (RN: AppState 'background'): FIN DE SESIÓN. Cierra pantalla actual
637
- * (page_view), mini-services (mini_service_exit), emite engagement + `session_end` y
638
- * envía el último lote con `completed:true`.
639
- *
640
- * Es la única señal disponible en móvil: el kill de la app (swipe) NO da callback.
648
+ * App a background (RN: AppState 'background'): SUSPENDE la sesión. Cierra la pantalla
649
+ * actual (page_view), los mini-services (mini_service_exit) y envía lo acumulado con un
650
+ * `deepdots_session_suspend` (`reason: background`) y SIN `completed`:
651
+ * - si la app vuelve dentro de ANALYTICS_BACKGROUND_RESUME_WINDOW_MS, `onForeground` sigue
652
+ * en el mismo registro;
653
+ * - si no vuelve (o la matan: el swipe NO da callback), el backend la cierra pasados unos
654
+ * minutos con un `session_end` `background` a la hora de la suspensión.
655
+ * Si aún no se conoce el registro (el primer POST sigue en vuelo), FIN DE SESIÓN como antes.
641
656
  */
642
657
  onBackground(): void;
643
658
  /**
@@ -666,6 +681,13 @@ declare class DeepdotsPopups {
666
681
  * anterior (`session_end` con `reason: 'user_change'` + `completed:true`), cambia la
667
682
  * identidad y abre una sesión nueva. Sin `userId` vuelve al id anónimo del SDK.
668
683
  *
684
+ * Anónimo → identificado (la app arranca sin `userId` y lo pone al hacer login) es la MISMA
685
+ * persona, no otra: el `session_start` de la sesión nueva lleva `identified: true`,
686
+ * `previous_user_id` (el id anónimo) y `previous_session_id` (el registro que se acaba de
687
+ * cerrar), para que el backend una las dos sin adivinar; y el estado de popups (mostrados,
688
+ * respondidos, protecciones de mensajes) se conserva. Sin esto, cada persona que se registra
689
+ * contaba dos veces: una que "abandona" en el login y otra registrada nueva.
690
+ *
669
691
  * Equivale a llamar a `init()` otra vez con otro `userId`.
670
692
  */
671
693
  setUserId(userId?: string): void;
@@ -702,6 +724,7 @@ declare class DeepdotsPopups {
702
724
  flushAnalytics(options?: {
703
725
  final?: boolean;
704
726
  sessionEnd?: boolean;
727
+ persist?: boolean;
705
728
  }): void;
706
729
  /**
707
730
  * Emite un evento `user_engagement` con el tiempo activo acumulado (#8) y la pantalla en
@@ -737,8 +760,12 @@ declare class DeepdotsPopups {
737
760
  * - si la página vuelve a cargar en esta pestaña, `init()` sigue en el mismo registro;
738
761
  * - si la pestaña se cerró, el backend lo cierra a los pocos minutos sin otro lote.
739
762
  *
763
+ * En React Native (`background`) la suspensión vive en memoria: la app sigue viva en
764
+ * background y, si el SO la mata, el arranque siguiente es otra sesión (`cold_start`).
765
+ *
740
766
  * Devuelve false cuando no se puede suspender — aún no se conoce el registro (el primer
741
- * POST sigue en vuelo) o no hay `sessionStorage` — y entonces el caller cierra como antes.
767
+ * POST sigue en vuelo) o, en web, no hay `sessionStorage` — y entonces el caller cierra
768
+ * como antes.
742
769
  */
743
770
  private suspendSession;
744
771
  /**
@@ -749,11 +776,23 @@ declare class DeepdotsPopups {
749
776
  private readResumableSession;
750
777
  /**
751
778
  * Consume la sesión suspendida al abrir: los ms que estuvo suspendida si se puede seguir en
752
- * ella (mismo usuario, dentro de ANALYTICS_RESUME_WINDOW_MS); null si no había o ya no toca.
779
+ * ella (mismo usuario, dentro de su ventana: ANALYTICS_RESUME_WINDOW_MS tras un `pagehide`,
780
+ * ANALYTICS_BACKGROUND_RESUME_WINDOW_MS tras un background); null si no había o ya no toca.
753
781
  * En ese caso se olvida su registro sin enviar nada: lo cierra el backend, y la sesión que
754
782
  * se abre ahora va a uno nuevo.
755
783
  */
756
784
  private takeSuspendedSession;
785
+ /**
786
+ * `pagehide` de una pestaña que llevaba oculta más de ANALYTICS_SESSION_TIMEOUT_MS: la
787
+ * misma regla que `onDocumentVisible`. Suspenderla mandaba un lote más al registro viejo
788
+ * (page_view + session_suspend) aunque el backend ya lo hubiera cerrado por inactividad:
789
+ * el backend lo volvía a montar y las acciones de FEEDBACK_DONE (el aviso de Slack de
790
+ * #platform-visitors) salían otra vez, horas después. Pasó con una pestaña oculta 7 h.
791
+ * - Oculta menos de ANALYTICS_SESSION_DISCARD_MS: se cierra con `idle_timeout`.
792
+ * - Más: el backend ya la cerró → se descarta sin enviar nada.
793
+ * Devuelve false si la pestaña no llevaba tanto oculta (el caller suspende como siempre).
794
+ */
795
+ private closeStaleHiddenSession;
757
796
  /** Olvida la sesión abierta sin enviar nada (ver onDocumentVisible). */
758
797
  private discardSession;
759
798
  /**
@@ -151,6 +151,12 @@ interface FeedbackSession {
151
151
  interface AutoTrackOptions {
152
152
  /** React Native: listen to `AppState` for session start/end. Default `true`. */
153
153
  lifecycle?: boolean;
154
+ /**
155
+ * Uncaught errors: `window` `error`/`unhandledrejection` (web), `ErrorUtils` and promise
156
+ * rejections without `catch` under Hermes (React Native). Default `true`. Handlers installed
157
+ * by other tools (Sentry, Crashlytics) keep receiving everything.
158
+ */
159
+ errors?: boolean;
154
160
  }
155
161
  interface DeepdotsInitParams {
156
162
  /** API key for authentication */
@@ -532,6 +538,8 @@ declare class DeepdotsPopups {
532
538
  private lastEngagementAt;
533
539
  /** Cuándo se ocultó la pestaña por última vez (ms epoch); null si está visible. */
534
540
  private hiddenAt;
541
+ /** `init({ autoTrack: { errors } })`: captura automática de errores. Activa por defecto. */
542
+ private autoTrackErrors;
535
543
  /** Suscripción automática a AppState (React Native, `autoTrack.lifecycle`). */
536
544
  private appStateSubscription;
537
545
  /**
@@ -630,14 +638,21 @@ declare class DeepdotsPopups {
630
638
  * El host la llama en cada cambio de pantalla; emite `page_view` al salir de la anterior.
631
639
  */
632
640
  setScreen(name: string): void;
633
- /** App a foreground (RN: AppState 'active'): reanuda el engagement time y abre sesión nueva. */
641
+ /**
642
+ * App a foreground (RN: AppState 'active'): reanuda el engagement time. Si la app estuvo en
643
+ * background menos de ANALYTICS_BACKGROUND_RESUME_WINDOW_MS sigue en la misma sesión
644
+ * (`deepdots_session_resume`); si no, abre una nueva (`session_start` `foreground`).
645
+ */
634
646
  onForeground(): void;
635
647
  /**
636
- * App a background (RN: AppState 'background'): FIN DE SESIÓN. Cierra pantalla actual
637
- * (page_view), mini-services (mini_service_exit), emite engagement + `session_end` y
638
- * envía el último lote con `completed:true`.
639
- *
640
- * Es la única señal disponible en móvil: el kill de la app (swipe) NO da callback.
648
+ * App a background (RN: AppState 'background'): SUSPENDE la sesión. Cierra la pantalla
649
+ * actual (page_view), los mini-services (mini_service_exit) y envía lo acumulado con un
650
+ * `deepdots_session_suspend` (`reason: background`) y SIN `completed`:
651
+ * - si la app vuelve dentro de ANALYTICS_BACKGROUND_RESUME_WINDOW_MS, `onForeground` sigue
652
+ * en el mismo registro;
653
+ * - si no vuelve (o la matan: el swipe NO da callback), el backend la cierra pasados unos
654
+ * minutos con un `session_end` `background` a la hora de la suspensión.
655
+ * Si aún no se conoce el registro (el primer POST sigue en vuelo), FIN DE SESIÓN como antes.
641
656
  */
642
657
  onBackground(): void;
643
658
  /**
@@ -666,6 +681,13 @@ declare class DeepdotsPopups {
666
681
  * anterior (`session_end` con `reason: 'user_change'` + `completed:true`), cambia la
667
682
  * identidad y abre una sesión nueva. Sin `userId` vuelve al id anónimo del SDK.
668
683
  *
684
+ * Anónimo → identificado (la app arranca sin `userId` y lo pone al hacer login) es la MISMA
685
+ * persona, no otra: el `session_start` de la sesión nueva lleva `identified: true`,
686
+ * `previous_user_id` (el id anónimo) y `previous_session_id` (el registro que se acaba de
687
+ * cerrar), para que el backend una las dos sin adivinar; y el estado de popups (mostrados,
688
+ * respondidos, protecciones de mensajes) se conserva. Sin esto, cada persona que se registra
689
+ * contaba dos veces: una que "abandona" en el login y otra registrada nueva.
690
+ *
669
691
  * Equivale a llamar a `init()` otra vez con otro `userId`.
670
692
  */
671
693
  setUserId(userId?: string): void;
@@ -702,6 +724,7 @@ declare class DeepdotsPopups {
702
724
  flushAnalytics(options?: {
703
725
  final?: boolean;
704
726
  sessionEnd?: boolean;
727
+ persist?: boolean;
705
728
  }): void;
706
729
  /**
707
730
  * Emite un evento `user_engagement` con el tiempo activo acumulado (#8) y la pantalla en
@@ -737,8 +760,12 @@ declare class DeepdotsPopups {
737
760
  * - si la página vuelve a cargar en esta pestaña, `init()` sigue en el mismo registro;
738
761
  * - si la pestaña se cerró, el backend lo cierra a los pocos minutos sin otro lote.
739
762
  *
763
+ * En React Native (`background`) la suspensión vive en memoria: la app sigue viva en
764
+ * background y, si el SO la mata, el arranque siguiente es otra sesión (`cold_start`).
765
+ *
740
766
  * Devuelve false cuando no se puede suspender — aún no se conoce el registro (el primer
741
- * POST sigue en vuelo) o no hay `sessionStorage` — y entonces el caller cierra como antes.
767
+ * POST sigue en vuelo) o, en web, no hay `sessionStorage` — y entonces el caller cierra
768
+ * como antes.
742
769
  */
743
770
  private suspendSession;
744
771
  /**
@@ -749,11 +776,23 @@ declare class DeepdotsPopups {
749
776
  private readResumableSession;
750
777
  /**
751
778
  * Consume la sesión suspendida al abrir: los ms que estuvo suspendida si se puede seguir en
752
- * ella (mismo usuario, dentro de ANALYTICS_RESUME_WINDOW_MS); null si no había o ya no toca.
779
+ * ella (mismo usuario, dentro de su ventana: ANALYTICS_RESUME_WINDOW_MS tras un `pagehide`,
780
+ * ANALYTICS_BACKGROUND_RESUME_WINDOW_MS tras un background); null si no había o ya no toca.
753
781
  * En ese caso se olvida su registro sin enviar nada: lo cierra el backend, y la sesión que
754
782
  * se abre ahora va a uno nuevo.
755
783
  */
756
784
  private takeSuspendedSession;
785
+ /**
786
+ * `pagehide` de una pestaña que llevaba oculta más de ANALYTICS_SESSION_TIMEOUT_MS: la
787
+ * misma regla que `onDocumentVisible`. Suspenderla mandaba un lote más al registro viejo
788
+ * (page_view + session_suspend) aunque el backend ya lo hubiera cerrado por inactividad:
789
+ * el backend lo volvía a montar y las acciones de FEEDBACK_DONE (el aviso de Slack de
790
+ * #platform-visitors) salían otra vez, horas después. Pasó con una pestaña oculta 7 h.
791
+ * - Oculta menos de ANALYTICS_SESSION_DISCARD_MS: se cierra con `idle_timeout`.
792
+ * - Más: el backend ya la cerró → se descarta sin enviar nada.
793
+ * Devuelve false si la pestaña no llevaba tanto oculta (el caller suspende como siempre).
794
+ */
795
+ private closeStaleHiddenSession;
757
796
  /** Olvida la sesión abierta sin enviar nada (ver onDocumentVisible). */
758
797
  private discardSession;
759
798
  /**
@@ -38,7 +38,7 @@ var SDK_VERSION, SDK_IDENTIFIER, POPUP_CHANNEL;
38
38
  var init_version = __esm({
39
39
  "src/version.ts"() {
40
40
  "use strict";
41
- SDK_VERSION = "1.19.0";
41
+ SDK_VERSION = "1.21.0";
42
42
  SDK_IDENTIFIER = `${"react-native"}@${SDK_VERSION}`;
43
43
  POPUP_CHANNEL = "popup";
44
44
  }
@@ -307,6 +307,8 @@ function resolveLocale(lang) {
307
307
  return "sk";
308
308
  case "sl":
309
309
  return "sl";
310
+ case "ca":
311
+ return "ca";
310
312
  default:
311
313
  return "en";
312
314
  }
@@ -334,7 +336,7 @@ function resolveActionLabels(actions, lang) {
334
336
  back: pick(actions?.back?.label, labels.back)
335
337
  };
336
338
  }
337
- var EN, ES, DA, NO, SV, FI, DE, FR, PT, AR, BN, ZH_CN, BG, CS, EL, ET, GA, HR, HU, IT, LT, LV, MT, NL, PL, RO, SK, SL, LABELS, RTL_LOCALES, RESOLVE_LOCALE_JS;
339
+ var EN, ES, DA, NO, SV, FI, DE, FR, PT, AR, BN, ZH_CN, BG, CS, EL, ET, GA, HR, HU, IT, LT, LV, MT, NL, PL, RO, SK, SL, CA, LABELS, RTL_LOCALES, RESOLVE_LOCALE_JS;
338
340
  var init_labels = __esm({
339
341
  "src/i18n/labels.ts"() {
340
342
  "use strict";
@@ -786,6 +788,22 @@ var init_labels = __esm({
786
788
  errorSubmit: "Pri po\u0161iljanju je pri\u0161lo do napake. Poskusite znova ali zaprite okno.",
787
789
  errorLoad: "Ankete ni bilo mogo\u010De nalo\u017Eiti."
788
790
  };
791
+ CA = {
792
+ accept: "Envia",
793
+ decline: "Cancel\xB7la",
794
+ start: "Comen\xE7a l'enquesta",
795
+ complete: "Completa l'enquesta",
796
+ back: "Enrere",
797
+ question: "Pregunta",
798
+ of: "de",
799
+ followUp: "Seguiment",
800
+ closeAria: "Tanca la finestra emergent",
801
+ loadingAria: "S'est\xE0 carregant l'enquesta",
802
+ errorRequired: "Respon la pregunta obligat\xF2ria per continuar.",
803
+ errorInvalidEmail: "Introdueix una adre\xE7a de correu electr\xF2nic v\xE0lida.",
804
+ errorSubmit: "S'ha produ\xEFt un error en enviar. Torna-ho a provar o tanca la finestra.",
805
+ errorLoad: "No s'ha pogut carregar l'enquesta."
806
+ };
789
807
  LABELS = {
790
808
  en: EN,
791
809
  es: ES,
@@ -814,7 +832,8 @@ var init_labels = __esm({
814
832
  pl: PL,
815
833
  ro: RO,
816
834
  sk: SK,
817
- sl: SL
835
+ sl: SL,
836
+ ca: CA
818
837
  };
819
838
  RTL_LOCALES = ["ar"];
820
839
  RESOLVE_LOCALE_JS = `function ddResolveLocale(lang){
@@ -850,6 +869,7 @@ var init_labels = __esm({
850
869
  if(p==='ro') return 'ro';
851
870
  if(p==='sk') return 'sk';
852
871
  if(p==='sl') return 'sl';
872
+ if(p==='ca') return 'ca';
853
873
  return 'en';
854
874
  }`;
855
875
  }
@@ -10539,9 +10559,11 @@ function createFeedbackSink(options) {
10539
10559
  const body = buildAnalyticsFeedbackBody(envelope, options.keys, feedbackSessionId, { sessionEnd });
10540
10560
  options.log?.("[DeepdotsAnalytics] POST /sdk/feedback \u2192", body);
10541
10561
  const batch = { body, at: now() };
10542
- if (sessionEnd) {
10543
- feedbackSessionId = void 0;
10544
- options.onSessionReset?.();
10562
+ if (sessionEnd || meta?.persist) {
10563
+ if (sessionEnd) {
10564
+ feedbackSessionId = void 0;
10565
+ options.onSessionReset?.();
10566
+ }
10545
10567
  addPending(batch);
10546
10568
  await drain();
10547
10569
  return;
@@ -10971,6 +10993,8 @@ var CrashReporter = class {
10971
10993
  this.windowInstalled = false;
10972
10994
  /** ErrorUtils ya enganchados: engancharlos dos veces capturaría cada error dos veces. */
10973
10995
  this.hookedErrorUtils = /* @__PURE__ */ new Set();
10996
+ /** Fuentes de rejections ya enganchadas (idempotente, como ErrorUtils). */
10997
+ this.hookedRejections = /* @__PURE__ */ new Set();
10974
10998
  this.options = options;
10975
10999
  this.now = options.now ?? (() => Date.now());
10976
11000
  }
@@ -11070,6 +11094,18 @@ var CrashReporter = class {
11070
11094
  previous?.(error, isFatal);
11071
11095
  });
11072
11096
  }
11097
+ /**
11098
+ * Promesas rechazadas sin `catch` en React Native: como el `unhandledrejection` de web, se
11099
+ * persisten y se reenvían en el arranque siguiente. La fuente encadena al tracker del host.
11100
+ * Idempotente por fuente.
11101
+ */
11102
+ installPromiseRejections(source) {
11103
+ if (this.hookedRejections.has(source)) return;
11104
+ this.hookedRejections.add(source);
11105
+ source.addUnhandledListener((error) => {
11106
+ if (this.isEnabled()) this.captureUnhandled(error ?? "unhandledrejection");
11107
+ });
11108
+ }
11073
11109
  /** @internal Test seam: ejercita el camino de persistencia (window handlers no son testeables en vitest). */
11074
11110
  _persistForTest(error) {
11075
11111
  this.captureUnhandled(error);
@@ -11177,6 +11213,51 @@ function resolveBackgroundTask(explicit, platform) {
11177
11213
  }
11178
11214
  return void 0;
11179
11215
  }
11216
+ var DEFAULT_REJECTION_WHITELIST = [ReferenceError, TypeError, RangeError];
11217
+ function createHermesRejectionHub(hermes, options) {
11218
+ if (!hermes || typeof hermes.enablePromiseRejectionTracker !== "function") return null;
11219
+ const original = hermes.enablePromiseRejectionTracker.bind(hermes);
11220
+ const listeners = /* @__PURE__ */ new Set();
11221
+ let hostOptions = null;
11222
+ let active2 = false;
11223
+ const forwardsToHost = (error) => !!hostOptions?.onUnhandled && (hostOptions.allRejections === true || DEFAULT_REJECTION_WHITELIST.some((type) => error instanceof type));
11224
+ const apply = () => {
11225
+ original({
11226
+ allRejections: true,
11227
+ onUnhandled: (id, error) => {
11228
+ listeners.forEach((listener) => {
11229
+ try {
11230
+ listener(error);
11231
+ } catch {
11232
+ }
11233
+ });
11234
+ if (hostOptions?.onUnhandled) {
11235
+ if (forwardsToHost(error)) hostOptions.onUnhandled(id, error);
11236
+ } else if (options.dev) {
11237
+ console.warn(`Possible unhandled promise rejection (id: ${id}):`, error);
11238
+ }
11239
+ },
11240
+ onHandled: (id, error) => hostOptions?.onHandled?.(id, error)
11241
+ });
11242
+ };
11243
+ hermes.enablePromiseRejectionTracker = (next) => {
11244
+ hostOptions = next ?? null;
11245
+ if (active2) apply();
11246
+ else original(next);
11247
+ };
11248
+ return {
11249
+ addUnhandledListener(listener) {
11250
+ listeners.add(listener);
11251
+ if (!active2) {
11252
+ active2 = true;
11253
+ apply();
11254
+ }
11255
+ return () => {
11256
+ listeners.delete(listener);
11257
+ };
11258
+ }
11259
+ };
11260
+ }
11180
11261
 
11181
11262
  // src/analytics/messaging.ts
11182
11263
  var MESSAGE_CHANNELS = ["push", "in_app"];
@@ -11254,6 +11335,7 @@ var ANALYTICS_SESSION_TIMEOUT_MS = 30 * 6e4;
11254
11335
  var ANALYTICS_SERVER_IDLE_MS = 60 * 6e4;
11255
11336
  var ANALYTICS_SESSION_DISCARD_MS = ANALYTICS_SERVER_IDLE_MS - 10 * 6e4;
11256
11337
  var ANALYTICS_RESUME_WINDOW_MS = 6e4;
11338
+ var ANALYTICS_BACKGROUND_RESUME_WINDOW_MS = 5 * 6e4;
11257
11339
  var RESERVED_EVENT_PREFIX = "deepdots_";
11258
11340
  var CUSTOM_EVENT_PREFIX = "deepdots_event_";
11259
11341
  var MAX_PENDING_TRIGGERS = 20;
@@ -11341,6 +11423,8 @@ var DeepdotsPopups = class {
11341
11423
  this.lastEngagementAt = 0;
11342
11424
  /** Cuándo se ocultó la pestaña por última vez (ms epoch); null si está visible. */
11343
11425
  this.hiddenAt = null;
11426
+ /** `init({ autoTrack: { errors } })`: captura automática de errores. Activa por defecto. */
11427
+ this.autoTrackErrors = true;
11344
11428
  /** Suscripción automática a AppState (React Native, `autoTrack.lifecycle`). */
11345
11429
  this.appStateSubscription = void 0;
11346
11430
  /**
@@ -11387,6 +11471,7 @@ var DeepdotsPopups = class {
11387
11471
  this.surveyCss = config.surveyCss;
11388
11472
  this.cspNonce = config.cspNonce;
11389
11473
  this.onFeedbackSession = config.onFeedbackSession;
11474
+ this.autoTrackErrors = config.autoTrack?.errors !== false;
11390
11475
  this.config = {
11391
11476
  apiKey: config.apiKey || void 0,
11392
11477
  debug: config.debug || false,
@@ -11418,7 +11503,7 @@ var DeepdotsPopups = class {
11418
11503
  const resumable = this.readResumableSession();
11419
11504
  if (resumable) {
11420
11505
  this.analyticsFeedbackSessionId = resumable.sessionId;
11421
- this.suspended = { at: resumable.at, userId: resumable.userId };
11506
+ this.suspended = { at: resumable.at, userId: resumable.userId, windowMs: ANALYTICS_RESUME_WINDOW_MS };
11422
11507
  }
11423
11508
  const analyticsSink = config.analytics ? createFeedbackSink({
11424
11509
  baseUrl: this.baseUrl,
@@ -11585,11 +11670,14 @@ var DeepdotsPopups = class {
11585
11670
  */
11586
11671
  installCrashHandlers() {
11587
11672
  if (!this.crashReporter || !this.tracking?.isTrackingEnabled()) return;
11588
- this.crashReporter.install();
11589
- const errorUtils = this.rnErrorUtils ?? globalThis.ErrorUtils;
11673
+ const auto = this.autoTrackErrors;
11674
+ if (auto) this.crashReporter.install();
11675
+ const errorUtils = this.rnErrorUtils ?? (auto ? globalThis.ErrorUtils : void 0);
11590
11676
  if (errorUtils && typeof errorUtils.setGlobalHandler === "function") {
11591
11677
  this.crashReporter.installReactNative(errorUtils);
11592
11678
  }
11679
+ const rejections = auto ? getReactNativePlatform()?.promiseRejections : null;
11680
+ if (rejections) this.crashReporter.installPromiseRejections(rejections);
11593
11681
  }
11594
11682
  /**
11595
11683
  * Info interna del usuario que solo conoce el host (idioma, edad, plan…), persistida en el
@@ -11674,21 +11762,28 @@ var DeepdotsPopups = class {
11674
11762
  this.navObserver.visit(name);
11675
11763
  }
11676
11764
  }
11677
- /** App a foreground (RN: AppState 'active'): reanuda el engagement time y abre sesión nueva. */
11765
+ /**
11766
+ * App a foreground (RN: AppState 'active'): reanuda el engagement time. Si la app estuvo en
11767
+ * background menos de ANALYTICS_BACKGROUND_RESUME_WINDOW_MS sigue en la misma sesión
11768
+ * (`deepdots_session_resume`); si no, abre una nueva (`session_start` `foreground`).
11769
+ */
11678
11770
  onForeground() {
11679
11771
  this.engagement?.resume();
11680
11772
  this.openSession("foreground");
11681
11773
  }
11682
11774
  /**
11683
- * App a background (RN: AppState 'background'): FIN DE SESIÓN. Cierra pantalla actual
11684
- * (page_view), mini-services (mini_service_exit), emite engagement + `session_end` y
11685
- * envía el último lote con `completed:true`.
11686
- *
11687
- * Es la única señal disponible en móvil: el kill de la app (swipe) NO da callback.
11775
+ * App a background (RN: AppState 'background'): SUSPENDE la sesión. Cierra la pantalla
11776
+ * actual (page_view), los mini-services (mini_service_exit) y envía lo acumulado con un
11777
+ * `deepdots_session_suspend` (`reason: background`) y SIN `completed`:
11778
+ * - si la app vuelve dentro de ANALYTICS_BACKGROUND_RESUME_WINDOW_MS, `onForeground` sigue
11779
+ * en el mismo registro;
11780
+ * - si no vuelve (o la matan: el swipe NO da callback), el backend la cierra pasados unos
11781
+ * minutos con un `session_end` `background` a la hora de la suspensión.
11782
+ * Si aún no se conoce el registro (el primer POST sigue en vuelo), FIN DE SESIÓN como antes.
11688
11783
  */
11689
11784
  onBackground() {
11690
11785
  this.cancelDelayedPopups("app to background");
11691
- this.closeSession("background");
11786
+ if (!this.suspendSession("background")) this.closeSession("background");
11692
11787
  this.engagement?.pause();
11693
11788
  }
11694
11789
  /**
@@ -11735,11 +11830,24 @@ var DeepdotsPopups = class {
11735
11830
  * anterior (`session_end` con `reason: 'user_change'` + `completed:true`), cambia la
11736
11831
  * identidad y abre una sesión nueva. Sin `userId` vuelve al id anónimo del SDK.
11737
11832
  *
11833
+ * Anónimo → identificado (la app arranca sin `userId` y lo pone al hacer login) es la MISMA
11834
+ * persona, no otra: el `session_start` de la sesión nueva lleva `identified: true`,
11835
+ * `previous_user_id` (el id anónimo) y `previous_session_id` (el registro que se acaba de
11836
+ * cerrar), para que el backend una las dos sin adivinar; y el estado de popups (mostrados,
11837
+ * respondidos, protecciones de mensajes) se conserva. Sin esto, cada persona que se registra
11838
+ * contaba dos veces: una que "abandona" en el login y otra registrada nueva.
11839
+ *
11738
11840
  * Equivale a llamar a `init()` otra vez con otro `userId`.
11739
11841
  */
11740
11842
  setUserId(userId) {
11741
11843
  const next = userId || void 0;
11742
11844
  if (!this.initialized || !this.config || next === this.config.userId) return;
11845
+ const identifying = !this.config.userId && !!next;
11846
+ const previous = identifying ? {
11847
+ identified: true,
11848
+ previous_user_id: this.tracking?.getUserId() ?? void 0,
11849
+ previous_session_id: this.analyticsFeedbackSessionId
11850
+ } : void 0;
11743
11851
  this.closeSession("user_change");
11744
11852
  const enabled = this.tracking?.isTrackingEnabled() ?? true;
11745
11853
  const storage = this.storage ?? createDefaultStorage();
@@ -11752,13 +11860,18 @@ var DeepdotsPopups = class {
11752
11860
  post: (body) => this.postContact(body)
11753
11861
  }) : null;
11754
11862
  this.analytics?.resetUserScope();
11755
- this.messageGuard.reset();
11756
- this.lastShown.clear();
11757
- this.surveyProgress.clear();
11758
- this.answeredSurveys.clear();
11759
- clearPopupState(storage);
11760
- this.log("tracking \xB7 user_change \xB7 user_id:", this.tracking.getUserId());
11761
- this.openSession("user_change");
11863
+ if (!identifying) {
11864
+ this.messageGuard.reset();
11865
+ this.lastShown.clear();
11866
+ this.surveyProgress.clear();
11867
+ this.answeredSurveys.clear();
11868
+ clearPopupState(storage);
11869
+ }
11870
+ this.log(
11871
+ identifying ? "tracking \xB7 user identified \xB7 user_id:" : "tracking \xB7 user_change \xB7 user_id:",
11872
+ this.tracking.getUserId()
11873
+ );
11874
+ this.openSession("user_change", previous);
11762
11875
  }
11763
11876
  /**
11764
11877
  * Cierra la sesión actual: vuelca todo lo que quedaba abierto y envía el último lote
@@ -11794,14 +11907,14 @@ var DeepdotsPopups = class {
11794
11907
  * - `bfcache_restore`: vuelta desde la bfcache fuera de la ventana de reanudación.
11795
11908
  * Si hay una sesión suspendida a tiempo emite `deepdots_session_resume` en su lugar, sin reason.
11796
11909
  */
11797
- openSession(reason) {
11910
+ openSession(reason, extra) {
11798
11911
  if (this.sessionOpen) return;
11799
11912
  if (!this.tracking?.isTrackingEnabled()) return;
11800
11913
  const suspendedMs = this.takeSuspendedSession();
11801
11914
  this.sessionOpen = true;
11802
11915
  this.lastEngagementAt = Date.now();
11803
11916
  if (suspendedMs === null) {
11804
- this.track("deepdots_session_start", { reason });
11917
+ this.track("deepdots_session_start", { reason, ...extra });
11805
11918
  } else {
11806
11919
  this.track("deepdots_session_resume", { suspended_ms: suspendedMs });
11807
11920
  this.log("tracking \xB7 session resumed after", suspendedMs, "ms:", this.analyticsFeedbackSessionId);
@@ -11895,27 +12008,37 @@ var DeepdotsPopups = class {
11895
12008
  * - si la página vuelve a cargar en esta pestaña, `init()` sigue en el mismo registro;
11896
12009
  * - si la pestaña se cerró, el backend lo cierra a los pocos minutos sin otro lote.
11897
12010
  *
12011
+ * En React Native (`background`) la suspensión vive en memoria: la app sigue viva en
12012
+ * background y, si el SO la mata, el arranque siguiente es otra sesión (`cold_start`).
12013
+ *
11898
12014
  * Devuelve false cuando no se puede suspender — aún no se conoce el registro (el primer
11899
- * POST sigue en vuelo) o no hay `sessionStorage` — y entonces el caller cierra como antes.
12015
+ * POST sigue en vuelo) o, en web, no hay `sessionStorage` — y entonces el caller cierra
12016
+ * como antes.
11900
12017
  */
11901
- suspendSession() {
12018
+ suspendSession(reason) {
11902
12019
  if (!this.sessionOpen || !this.tracking?.isTrackingEnabled()) return false;
11903
12020
  const sessionId = this.analyticsFeedbackSessionId;
11904
12021
  const integration = this.analyticsIntegration;
11905
- const storage = getSessionStorage();
11906
- if (!sessionId || !integration || !storage) return false;
12022
+ if (!sessionId || !integration) return false;
11907
12023
  const at = Date.now();
11908
12024
  const userId = this.tracking.getUserId();
11909
- if (!writeSuspendedSession(storage, { sessionId, integration, userId, at })) return false;
12025
+ if (reason === "page_hide") {
12026
+ const storage = getSessionStorage();
12027
+ if (!storage || !writeSuspendedSession(storage, { sessionId, integration, userId, at })) return false;
12028
+ }
11910
12029
  this.sessionOpen = false;
11911
- this.suspended = { at, userId };
12030
+ this.suspended = {
12031
+ at,
12032
+ userId,
12033
+ windowMs: reason === "page_hide" ? ANALYTICS_RESUME_WINDOW_MS : ANALYTICS_BACKGROUND_RESUME_WINDOW_MS
12034
+ };
11912
12035
  this.navObserver?.stop();
11913
12036
  this.navStarted = false;
11914
12037
  this.analytics?.exitAllMiniServices();
11915
12038
  this.flushEngagement();
11916
12039
  this.engagement?.pause();
11917
- this.track("deepdots_session_suspend", { reason: "page_hide" });
11918
- this.flushAnalytics({ final: true });
12040
+ this.track("deepdots_session_suspend", { reason });
12041
+ this.flushAnalytics(reason === "page_hide" ? { final: true } : { persist: true });
11919
12042
  this.log("tracking \xB7 session suspended:", sessionId);
11920
12043
  return true;
11921
12044
  }
@@ -11937,7 +12060,8 @@ var DeepdotsPopups = class {
11937
12060
  }
11938
12061
  /**
11939
12062
  * Consume la sesión suspendida al abrir: los ms que estuvo suspendida si se puede seguir en
11940
- * ella (mismo usuario, dentro de ANALYTICS_RESUME_WINDOW_MS); null si no había o ya no toca.
12063
+ * ella (mismo usuario, dentro de su ventana: ANALYTICS_RESUME_WINDOW_MS tras un `pagehide`,
12064
+ * ANALYTICS_BACKGROUND_RESUME_WINDOW_MS tras un background); null si no había o ya no toca.
11941
12065
  * En ese caso se olvida su registro sin enviar nada: lo cierra el backend, y la sesión que
11942
12066
  * se abre ahora va a uno nuevo.
11943
12067
  */
@@ -11948,7 +12072,7 @@ var DeepdotsPopups = class {
11948
12072
  const storage = getSessionStorage();
11949
12073
  if (storage) clearSuspendedSession(storage);
11950
12074
  const suspendedMs = Math.max(0, Date.now() - suspended.at);
11951
- if (this.analyticsFeedbackSessionId && suspendedMs <= ANALYTICS_RESUME_WINDOW_MS && suspended.userId === (this.tracking?.getUserId() ?? null)) {
12075
+ if (this.analyticsFeedbackSessionId && suspendedMs <= suspended.windowMs && suspended.userId === (this.tracking?.getUserId() ?? null)) {
11952
12076
  return suspendedMs;
11953
12077
  }
11954
12078
  this.analytics?.discardSession(this.analyticsIdentity());
@@ -11956,6 +12080,27 @@ var DeepdotsPopups = class {
11956
12080
  this.tracking?.setSessionId(null);
11957
12081
  return null;
11958
12082
  }
12083
+ /**
12084
+ * `pagehide` de una pestaña que llevaba oculta más de ANALYTICS_SESSION_TIMEOUT_MS: la
12085
+ * misma regla que `onDocumentVisible`. Suspenderla mandaba un lote más al registro viejo
12086
+ * (page_view + session_suspend) aunque el backend ya lo hubiera cerrado por inactividad:
12087
+ * el backend lo volvía a montar y las acciones de FEEDBACK_DONE (el aviso de Slack de
12088
+ * #platform-visitors) salían otra vez, horas después. Pasó con una pestaña oculta 7 h.
12089
+ * - Oculta menos de ANALYTICS_SESSION_DISCARD_MS: se cierra con `idle_timeout`.
12090
+ * - Más: el backend ya la cerró → se descarta sin enviar nada.
12091
+ * Devuelve false si la pestaña no llevaba tanto oculta (el caller suspende como siempre).
12092
+ */
12093
+ closeStaleHiddenSession() {
12094
+ if (!this.sessionOpen || this.hiddenAt === null) return false;
12095
+ const hiddenFor = Date.now() - this.hiddenAt;
12096
+ if (hiddenFor < ANALYTICS_SESSION_TIMEOUT_MS) return false;
12097
+ if (hiddenFor < ANALYTICS_SESSION_DISCARD_MS) {
12098
+ this.closeSession("idle_timeout");
12099
+ } else {
12100
+ this.discardSession();
12101
+ }
12102
+ return true;
12103
+ }
11959
12104
  /** Olvida la sesión abierta sin enviar nada (ver onDocumentVisible). */
11960
12105
  discardSession() {
11961
12106
  this.sessionOpen = false;
@@ -12004,7 +12149,8 @@ var DeepdotsPopups = class {
12004
12149
  if (typeof document === "undefined" || typeof window === "undefined") return;
12005
12150
  window.addEventListener("pagehide", () => {
12006
12151
  clearInterval(this.analyticsFlushTimer);
12007
- if (!this.suspendSession()) this.closeSession("page_hide");
12152
+ if (this.closeStaleHiddenSession()) return;
12153
+ if (!this.suspendSession("page_hide")) this.closeSession("page_hide");
12008
12154
  });
12009
12155
  window.addEventListener("pageshow", (event) => {
12010
12156
  if (!event.persisted) return;
@@ -12861,13 +13007,26 @@ function setupReactNative(sdk2, config, deps = {}) {
12861
13007
  };
12862
13008
  }
12863
13009
 
13010
+ // src/platform/react-native-defaults.ts
13011
+ var hub;
13012
+ function registerReactNativeDefaults(rn) {
13013
+ if (hub === void 0) {
13014
+ hub = getReactNativePlatform()?.promiseRejections ?? createHermesRejectionHub(
13015
+ globalThis.HermesInternal,
13016
+ { dev: typeof __DEV__ !== "undefined" && !!__DEV__ }
13017
+ );
13018
+ }
13019
+ registerReactNativePlatform({
13020
+ os: rn.Platform.OS,
13021
+ appState: rn.AppState,
13022
+ backgroundTaskModule: rn.NativeModules?.DeepdotsBackgroundTask ?? null,
13023
+ promiseRejections: hub
13024
+ });
13025
+ }
13026
+
12864
13027
  // src/react-native/index.tsx
12865
13028
  var import_jsx_runtime = require("react/jsx-runtime");
12866
- registerReactNativePlatform({
12867
- os: import_react_native.Platform.OS,
12868
- appState: import_react_native.AppState,
12869
- backgroundTaskModule: import_react_native.NativeModules?.DeepdotsBackgroundTask ?? null
12870
- });
13029
+ registerReactNativeDefaults({ AppState: import_react_native.AppState, NativeModules: import_react_native.NativeModules, Platform: import_react_native.Platform });
12871
13030
  var sdk = new DeepdotsPopups();
12872
13031
  var DeepdotsContext = (0, import_react.createContext)(sdk);
12873
13032
  var useDeepdots = () => (0, import_react.useContext)(DeepdotsContext);