@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
package/dist/index.d.ts CHANGED
@@ -146,6 +146,12 @@ interface AnalyticsFlushMeta {
146
146
  * registro nuevo, igual que tras `sessionEnd`, pero sin POST.
147
147
  */
148
148
  resetSession?: boolean;
149
+ /**
150
+ * `true` cuando el lote puede ser lo último que salga de la sesión sin cerrarla (app a
151
+ * background en RN: la sesión queda suspendida). El sink lo guarda ANTES de enviarlo, como
152
+ * el lote de cierre, para reenviarlo en el arranque siguiente si el SO mata la app.
153
+ */
154
+ persist?: boolean;
149
155
  }
150
156
  /**
151
157
  * Envío del lote. Si devuelve una promesa que **rechaza**, el manager re-encola los
@@ -308,6 +314,12 @@ interface FeedbackSession {
308
314
  interface AutoTrackOptions {
309
315
  /** React Native: listen to `AppState` for session start/end. Default `true`. */
310
316
  lifecycle?: boolean;
317
+ /**
318
+ * Uncaught errors: `window` `error`/`unhandledrejection` (web), `ErrorUtils` and promise
319
+ * rejections without `catch` under Hermes (React Native). Default `true`. Handlers installed
320
+ * by other tools (Sentry, Crashlytics) keep receiving everything.
321
+ */
322
+ errors?: boolean;
311
323
  }
312
324
  interface DeepdotsInitParams {
313
325
  /** API key for authentication */
@@ -762,6 +774,10 @@ interface ReactNativeErrorUtils {
762
774
  getGlobalHandler?(): ((error: unknown, isFatal?: boolean) => void) | undefined;
763
775
  setGlobalHandler(handler: (error: unknown, isFatal?: boolean) => void): void;
764
776
  }
777
+ /** Fuente de promesas rechazadas sin `catch` (en RN, el hub del tracker de Hermes). */
778
+ interface UnhandledRejectionSource {
779
+ addUnhandledListener(listener: (error: unknown) => void): () => void;
780
+ }
765
781
  interface CrashReporterOptions {
766
782
  storage: KeyValueStorage;
767
783
  /** Emite un evento deepdots_app_crash AHORA (app viva). */
@@ -783,6 +799,8 @@ declare class CrashReporter {
783
799
  private windowInstalled;
784
800
  /** ErrorUtils ya enganchados: engancharlos dos veces capturaría cada error dos veces. */
785
801
  private hookedErrorUtils;
802
+ /** Fuentes de rejections ya enganchadas (idempotente, como ErrorUtils). */
803
+ private hookedRejections;
786
804
  constructor(options: CrashReporterOptions);
787
805
  private isEnabled;
788
806
  /** Construye un CrashRecord capturando contexto en el momento del crash. */
@@ -799,6 +817,12 @@ declare class CrashReporter {
799
817
  install(): void;
800
818
  /** Engancha `global.ErrorUtils` de RN (no hay `window`): persiste y encadena al handler previo. Idempotente por instancia de ErrorUtils. */
801
819
  installReactNative(errorUtils: ReactNativeErrorUtils): void;
820
+ /**
821
+ * Promesas rechazadas sin `catch` en React Native: como el `unhandledrejection` de web, se
822
+ * persisten y se reenvían en el arranque siguiente. La fuente encadena al tracker del host.
823
+ * Idempotente por fuente.
824
+ */
825
+ installPromiseRejections(source: UnhandledRejectionSource): void;
802
826
  /** @internal Test seam: ejercita el camino de persistencia (window handlers no son testeables en vitest). */
803
827
  _persistForTest(error: unknown): void;
804
828
  }
@@ -938,6 +962,8 @@ declare class DeepdotsPopups {
938
962
  private lastEngagementAt;
939
963
  /** Cuándo se ocultó la pestaña por última vez (ms epoch); null si está visible. */
940
964
  private hiddenAt;
965
+ /** `init({ autoTrack: { errors } })`: captura automática de errores. Activa por defecto. */
966
+ private autoTrackErrors;
941
967
  /** Suscripción automática a AppState (React Native, `autoTrack.lifecycle`). */
942
968
  private appStateSubscription;
943
969
  /**
@@ -1036,14 +1062,21 @@ declare class DeepdotsPopups {
1036
1062
  * El host la llama en cada cambio de pantalla; emite `page_view` al salir de la anterior.
1037
1063
  */
1038
1064
  setScreen(name: string): void;
1039
- /** App a foreground (RN: AppState 'active'): reanuda el engagement time y abre sesión nueva. */
1065
+ /**
1066
+ * App a foreground (RN: AppState 'active'): reanuda el engagement time. Si la app estuvo en
1067
+ * background menos de ANALYTICS_BACKGROUND_RESUME_WINDOW_MS sigue en la misma sesión
1068
+ * (`deepdots_session_resume`); si no, abre una nueva (`session_start` `foreground`).
1069
+ */
1040
1070
  onForeground(): void;
1041
1071
  /**
1042
- * App a background (RN: AppState 'background'): FIN DE SESIÓN. Cierra pantalla actual
1043
- * (page_view), mini-services (mini_service_exit), emite engagement + `session_end` y
1044
- * envía el último lote con `completed:true`.
1045
- *
1046
- * Es la única señal disponible en móvil: el kill de la app (swipe) NO da callback.
1072
+ * App a background (RN: AppState 'background'): SUSPENDE la sesión. Cierra la pantalla
1073
+ * actual (page_view), los mini-services (mini_service_exit) y envía lo acumulado con un
1074
+ * `deepdots_session_suspend` (`reason: background`) y SIN `completed`:
1075
+ * - si la app vuelve dentro de ANALYTICS_BACKGROUND_RESUME_WINDOW_MS, `onForeground` sigue
1076
+ * en el mismo registro;
1077
+ * - si no vuelve (o la matan: el swipe NO da callback), el backend la cierra pasados unos
1078
+ * minutos con un `session_end` `background` a la hora de la suspensión.
1079
+ * Si aún no se conoce el registro (el primer POST sigue en vuelo), FIN DE SESIÓN como antes.
1047
1080
  */
1048
1081
  onBackground(): void;
1049
1082
  /**
@@ -1072,6 +1105,13 @@ declare class DeepdotsPopups {
1072
1105
  * anterior (`session_end` con `reason: 'user_change'` + `completed:true`), cambia la
1073
1106
  * identidad y abre una sesión nueva. Sin `userId` vuelve al id anónimo del SDK.
1074
1107
  *
1108
+ * Anónimo → identificado (la app arranca sin `userId` y lo pone al hacer login) es la MISMA
1109
+ * persona, no otra: el `session_start` de la sesión nueva lleva `identified: true`,
1110
+ * `previous_user_id` (el id anónimo) y `previous_session_id` (el registro que se acaba de
1111
+ * cerrar), para que el backend una las dos sin adivinar; y el estado de popups (mostrados,
1112
+ * respondidos, protecciones de mensajes) se conserva. Sin esto, cada persona que se registra
1113
+ * contaba dos veces: una que "abandona" en el login y otra registrada nueva.
1114
+ *
1075
1115
  * Equivale a llamar a `init()` otra vez con otro `userId`.
1076
1116
  */
1077
1117
  setUserId(userId?: string): void;
@@ -1108,6 +1148,7 @@ declare class DeepdotsPopups {
1108
1148
  flushAnalytics(options?: {
1109
1149
  final?: boolean;
1110
1150
  sessionEnd?: boolean;
1151
+ persist?: boolean;
1111
1152
  }): void;
1112
1153
  /**
1113
1154
  * Emite un evento `user_engagement` con el tiempo activo acumulado (#8) y la pantalla en
@@ -1143,8 +1184,12 @@ declare class DeepdotsPopups {
1143
1184
  * - si la página vuelve a cargar en esta pestaña, `init()` sigue en el mismo registro;
1144
1185
  * - si la pestaña se cerró, el backend lo cierra a los pocos minutos sin otro lote.
1145
1186
  *
1187
+ * En React Native (`background`) la suspensión vive en memoria: la app sigue viva en
1188
+ * background y, si el SO la mata, el arranque siguiente es otra sesión (`cold_start`).
1189
+ *
1146
1190
  * Devuelve false cuando no se puede suspender — aún no se conoce el registro (el primer
1147
- * POST sigue en vuelo) o no hay `sessionStorage` — y entonces el caller cierra como antes.
1191
+ * POST sigue en vuelo) o, en web, no hay `sessionStorage` — y entonces el caller cierra
1192
+ * como antes.
1148
1193
  */
1149
1194
  private suspendSession;
1150
1195
  /**
@@ -1155,11 +1200,23 @@ declare class DeepdotsPopups {
1155
1200
  private readResumableSession;
1156
1201
  /**
1157
1202
  * Consume la sesión suspendida al abrir: los ms que estuvo suspendida si se puede seguir en
1158
- * ella (mismo usuario, dentro de ANALYTICS_RESUME_WINDOW_MS); null si no había o ya no toca.
1203
+ * ella (mismo usuario, dentro de su ventana: ANALYTICS_RESUME_WINDOW_MS tras un `pagehide`,
1204
+ * ANALYTICS_BACKGROUND_RESUME_WINDOW_MS tras un background); null si no había o ya no toca.
1159
1205
  * En ese caso se olvida su registro sin enviar nada: lo cierra el backend, y la sesión que
1160
1206
  * se abre ahora va a uno nuevo.
1161
1207
  */
1162
1208
  private takeSuspendedSession;
1209
+ /**
1210
+ * `pagehide` de una pestaña que llevaba oculta más de ANALYTICS_SESSION_TIMEOUT_MS: la
1211
+ * misma regla que `onDocumentVisible`. Suspenderla mandaba un lote más al registro viejo
1212
+ * (page_view + session_suspend) aunque el backend ya lo hubiera cerrado por inactividad:
1213
+ * el backend lo volvía a montar y las acciones de FEEDBACK_DONE (el aviso de Slack de
1214
+ * #platform-visitors) salían otra vez, horas después. Pasó con una pestaña oculta 7 h.
1215
+ * - Oculta menos de ANALYTICS_SESSION_DISCARD_MS: se cierra con `idle_timeout`.
1216
+ * - Más: el backend ya la cerró → se descarta sin enviar nada.
1217
+ * Devuelve false si la pestaña no llevaba tanto oculta (el caller suspende como siempre).
1218
+ */
1219
+ private closeStaleHiddenSession;
1163
1220
  /** Olvida la sesión abierta sin enviar nada (ver onDocumentVisible). */
1164
1221
  private discardSession;
1165
1222
  /**
@@ -1488,7 +1545,7 @@ declare const REVEAL_TIMEOUT_MS = 1200;
1488
1545
  * resolución, para que las tres rutas (popup DOM web, WebView de RN y Compose) digan lo mismo.
1489
1546
  */
1490
1547
  /** Locales con traducción propia. Cualquier otro idioma cae a `en`. */
1491
- type PopupLocale = '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';
1548
+ type PopupLocale = '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';
1492
1549
  interface PopupLabels {
1493
1550
  /** Acción principal: enviar la respuesta. */
1494
1551
  accept: string;
@@ -1613,4 +1670,42 @@ declare function collectRnDevice(d: DeviceInfoLike): DeviceInfo;
1613
1670
  */
1614
1671
  declare function setupReactNative(sdk: DeepdotsPopups, config: DeepdotsInitParams, deps?: ReactNativeSetupDeps): () => void;
1615
1672
 
1616
- export { type AnalyticsFeedbackBody, type AnalyticsKeys, type AppStateLike, type AutoTrackOptions, BACKGROUND_TASK_MAX_MS, type BackgroundTaskRunner, type BackgroundTimerLike, BrowserPopupRenderer, type BuildBodyOptions, type ContactAttributeValue, type ContactAttributes, type ContactBody, ContactManager, type CrashRecord, CrashReporter, type CrashSeverity, type DeepdotsConfig, type DeepdotsEvent, type DeepdotsEventType, type DeepdotsInitParams, type DeepdotsLogger, DeepdotsPopups, type DeviceInfo, type DeviceInfoLike, type DeviceSnapshot, type EventListener, type FeedbackKV, type FeedbackSession, InMemoryStorage, type KeyValueStorage, LABELS, MAX_TRACKED_MESSAGES, MESSAGE_CHANNELS, type MessageChannel, MessageGuard, type MessageGuardVerdict, type MessageRejectionReason, type MessageStage, type MmkvLike, NATIVE_READY_GRACE_MS, NoopPopupRenderer, POPUP_TRIGGER_CONDITION_STATUSES, type PopupDefinition, type PopupLabels, type PopupLocale, type PopupRenderer, type PopupTrigger, type PopupTriggerCondition, type PopupTriggerConditionStatus, REVEAL_TIMEOUT_MS, RTL_LOCALES, type ReactNativeErrorUtils, ReactNativePopupRenderer, type ReactNativeRendererOptions, type ReactNativeSetupDeps, type ReactNativeSurveyPayload, type ReportErrorOptions, type ResolvedActionLabels, SUPPORTED_LANGUAGES, type SessionEndReason, type SessionStartReason, type TrackMessageOptions, type TriggerConfig, backgroundTimerTask, buildAnalyticsFeedbackBody, buildMessageParams, buildSurveyHtml, collectRnDevice, crashRecordToParams, createDefaultRenderer, createFeedbackSink, directionFor, getLabels, isRtlLanguage, mmkvStorage, resolveActionLabels, resolveLocale, setupReactNative };
1673
+ /**
1674
+ * Lo que el SDK necesita de React Native para detectar solo el ciclo de vida y el tiempo de
1675
+ * background (DD-55, contrato de detección automática). El core no importa `react-native` (se
1676
+ * usa también en web): lo registra la entrada de React Native del paquete
1677
+ * (`src/index.native.ts`, que Metro elige por la condición `react-native`) y el Provider.
1678
+ */
1679
+
1680
+ /** Opciones de `HermesInternal.enablePromiseRejectionTracker` (las mismas que `promise/rejection-tracking`). */
1681
+ interface RejectionTrackingOptions {
1682
+ allRejections?: boolean;
1683
+ onUnhandled?: (id: number, error: unknown) => void;
1684
+ onHandled?: (id: number, error?: unknown) => void;
1685
+ }
1686
+ /** Lo que el SDK necesita de `global.HermesInternal`. */
1687
+ interface HermesRejectionTrackerLike {
1688
+ enablePromiseRejectionTracker?: (options?: RejectionTrackingOptions) => void;
1689
+ }
1690
+ interface PromiseRejectionHub {
1691
+ /** Avisa de cada promesa rechazada sin `catch`. Devuelve la función que lo quita. */
1692
+ addUnhandledListener(listener: (error: unknown) => void): () => void;
1693
+ }
1694
+ /**
1695
+ * Promesas rechazadas sin `catch` en React Native (contrato de detección automática, paso 2).
1696
+ *
1697
+ * Hermes solo admite UN tracker (`enablePromiseRejectionTracker` sustituye al anterior) y no deja
1698
+ * leer el que hay. Para no quitarle las rejections a Sentry/Crashlytics, la entrada de React
1699
+ * Native envuelve la función al importarse el paquete, que es antes de que el código de la app
1700
+ * llame a `Sentry.init()` (los imports se evalúan primero): lo que instale después cualquiera se
1701
+ * compone con lo nuestro en vez de sustituirlo. Antes del import solo lo pudo instalar React
1702
+ * Native, y solo en desarrollo (el aviso "Possible unhandled promise rejection"), que se mantiene
1703
+ * con `dev`. Mientras el SDK no se engancha, la función envuelta pasa todo tal cual a Hermes.
1704
+ *
1705
+ * Devuelve null sin Hermes o sin el tracker (JSC): el SDK sigue sin capturarlas, como antes.
1706
+ */
1707
+ declare function createHermesRejectionHub(hermes: HermesRejectionTrackerLike | null | undefined, options: {
1708
+ dev: boolean;
1709
+ }): PromiseRejectionHub | null;
1710
+
1711
+ export { type AnalyticsFeedbackBody, type AnalyticsKeys, type AppStateLike, type AutoTrackOptions, BACKGROUND_TASK_MAX_MS, type BackgroundTaskRunner, type BackgroundTimerLike, BrowserPopupRenderer, type BuildBodyOptions, type ContactAttributeValue, type ContactAttributes, type ContactBody, ContactManager, type CrashRecord, CrashReporter, type CrashSeverity, type DeepdotsConfig, type DeepdotsEvent, type DeepdotsEventType, type DeepdotsInitParams, type DeepdotsLogger, DeepdotsPopups, type DeviceInfo, type DeviceInfoLike, type DeviceSnapshot, type EventListener, type FeedbackKV, type FeedbackSession, type HermesRejectionTrackerLike, InMemoryStorage, type KeyValueStorage, LABELS, MAX_TRACKED_MESSAGES, MESSAGE_CHANNELS, type MessageChannel, MessageGuard, type MessageGuardVerdict, type MessageRejectionReason, type MessageStage, type MmkvLike, NATIVE_READY_GRACE_MS, NoopPopupRenderer, POPUP_TRIGGER_CONDITION_STATUSES, type PopupDefinition, type PopupLabels, type PopupLocale, type PopupRenderer, type PopupTrigger, type PopupTriggerCondition, type PopupTriggerConditionStatus, type PromiseRejectionHub, REVEAL_TIMEOUT_MS, RTL_LOCALES, type ReactNativeErrorUtils, ReactNativePopupRenderer, type ReactNativeRendererOptions, type ReactNativeSetupDeps, type ReactNativeSurveyPayload, type RejectionTrackingOptions, type ReportErrorOptions, type ResolvedActionLabels, SUPPORTED_LANGUAGES, type SessionEndReason, type SessionStartReason, type TrackMessageOptions, type TriggerConfig, backgroundTimerTask, buildAnalyticsFeedbackBody, buildMessageParams, buildSurveyHtml, collectRnDevice, crashRecordToParams, createDefaultRenderer, createFeedbackSink, createHermesRejectionHub, directionFor, getLabels, isRtlLanguage, mmkvStorage, resolveActionLabels, resolveLocale, setupReactNative };
package/dist/index.js CHANGED
@@ -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 = `${"web"}@${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, SUPPORTED_LANGUAGES, 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, SUPPORTED_LANGUAGES, 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
  SUPPORTED_LANGUAGES = [
820
839
  // Los 11 idiomas que la plataforma ofrece para un survey, más zh-CN (que el SDK nativo ya
@@ -849,7 +868,9 @@ var init_labels = __esm({
849
868
  "pl",
850
869
  "ro",
851
870
  "sk",
852
- "sl"
871
+ "sl",
872
+ // Catalán (no oficial de la UE).
873
+ "ca"
853
874
  ];
854
875
  RTL_LOCALES = ["ar"];
855
876
  RESOLVE_LOCALE_JS = `function ddResolveLocale(lang){
@@ -885,6 +906,7 @@ var init_labels = __esm({
885
906
  if(p==='ro') return 'ro';
886
907
  if(p==='sk') return 'sk';
887
908
  if(p==='sl') return 'sl';
909
+ if(p==='ca') return 'ca';
888
910
  return 'en';
889
911
  }`;
890
912
  }
@@ -11969,6 +11991,7 @@ __export(index_exports, {
11969
11991
  crashRecordToParams: () => crashRecordToParams,
11970
11992
  createDefaultRenderer: () => createDefaultRenderer,
11971
11993
  createFeedbackSink: () => createFeedbackSink,
11994
+ createHermesRejectionHub: () => createHermesRejectionHub,
11972
11995
  directionFor: () => directionFor,
11973
11996
  getLabels: () => getLabels,
11974
11997
  isRtlLanguage: () => isRtlLanguage,
@@ -13516,9 +13539,11 @@ function createFeedbackSink(options) {
13516
13539
  const body = buildAnalyticsFeedbackBody(envelope, options.keys, feedbackSessionId, { sessionEnd });
13517
13540
  options.log?.("[DeepdotsAnalytics] POST /sdk/feedback \u2192", body);
13518
13541
  const batch = { body, at: now() };
13519
- if (sessionEnd) {
13520
- feedbackSessionId = void 0;
13521
- options.onSessionReset?.();
13542
+ if (sessionEnd || meta?.persist) {
13543
+ if (sessionEnd) {
13544
+ feedbackSessionId = void 0;
13545
+ options.onSessionReset?.();
13546
+ }
13522
13547
  addPending(batch);
13523
13548
  await drain();
13524
13549
  return;
@@ -13948,6 +13973,8 @@ var CrashReporter = class {
13948
13973
  this.windowInstalled = false;
13949
13974
  /** ErrorUtils ya enganchados: engancharlos dos veces capturaría cada error dos veces. */
13950
13975
  this.hookedErrorUtils = /* @__PURE__ */ new Set();
13976
+ /** Fuentes de rejections ya enganchadas (idempotente, como ErrorUtils). */
13977
+ this.hookedRejections = /* @__PURE__ */ new Set();
13951
13978
  this.options = options;
13952
13979
  this.now = options.now ?? (() => Date.now());
13953
13980
  }
@@ -14047,6 +14074,18 @@ var CrashReporter = class {
14047
14074
  previous?.(error, isFatal);
14048
14075
  });
14049
14076
  }
14077
+ /**
14078
+ * Promesas rechazadas sin `catch` en React Native: como el `unhandledrejection` de web, se
14079
+ * persisten y se reenvían en el arranque siguiente. La fuente encadena al tracker del host.
14080
+ * Idempotente por fuente.
14081
+ */
14082
+ installPromiseRejections(source) {
14083
+ if (this.hookedRejections.has(source)) return;
14084
+ this.hookedRejections.add(source);
14085
+ source.addUnhandledListener((error) => {
14086
+ if (this.isEnabled()) this.captureUnhandled(error ?? "unhandledrejection");
14087
+ });
14088
+ }
14050
14089
  /** @internal Test seam: ejercita el camino de persistencia (window handlers no son testeables en vitest). */
14051
14090
  _persistForTest(error) {
14052
14091
  this.captureUnhandled(error);
@@ -14151,6 +14190,51 @@ function resolveBackgroundTask(explicit, platform) {
14151
14190
  }
14152
14191
  return void 0;
14153
14192
  }
14193
+ var DEFAULT_REJECTION_WHITELIST = [ReferenceError, TypeError, RangeError];
14194
+ function createHermesRejectionHub(hermes, options) {
14195
+ if (!hermes || typeof hermes.enablePromiseRejectionTracker !== "function") return null;
14196
+ const original = hermes.enablePromiseRejectionTracker.bind(hermes);
14197
+ const listeners = /* @__PURE__ */ new Set();
14198
+ let hostOptions = null;
14199
+ let active2 = false;
14200
+ const forwardsToHost = (error) => !!hostOptions?.onUnhandled && (hostOptions.allRejections === true || DEFAULT_REJECTION_WHITELIST.some((type) => error instanceof type));
14201
+ const apply = () => {
14202
+ original({
14203
+ allRejections: true,
14204
+ onUnhandled: (id, error) => {
14205
+ listeners.forEach((listener) => {
14206
+ try {
14207
+ listener(error);
14208
+ } catch {
14209
+ }
14210
+ });
14211
+ if (hostOptions?.onUnhandled) {
14212
+ if (forwardsToHost(error)) hostOptions.onUnhandled(id, error);
14213
+ } else if (options.dev) {
14214
+ console.warn(`Possible unhandled promise rejection (id: ${id}):`, error);
14215
+ }
14216
+ },
14217
+ onHandled: (id, error) => hostOptions?.onHandled?.(id, error)
14218
+ });
14219
+ };
14220
+ hermes.enablePromiseRejectionTracker = (next) => {
14221
+ hostOptions = next ?? null;
14222
+ if (active2) apply();
14223
+ else original(next);
14224
+ };
14225
+ return {
14226
+ addUnhandledListener(listener) {
14227
+ listeners.add(listener);
14228
+ if (!active2) {
14229
+ active2 = true;
14230
+ apply();
14231
+ }
14232
+ return () => {
14233
+ listeners.delete(listener);
14234
+ };
14235
+ }
14236
+ };
14237
+ }
14154
14238
 
14155
14239
  // src/analytics/messaging.ts
14156
14240
  var MESSAGE_CHANNELS = ["push", "in_app"];
@@ -14228,6 +14312,7 @@ var ANALYTICS_SESSION_TIMEOUT_MS = 30 * 6e4;
14228
14312
  var ANALYTICS_SERVER_IDLE_MS = 60 * 6e4;
14229
14313
  var ANALYTICS_SESSION_DISCARD_MS = ANALYTICS_SERVER_IDLE_MS - 10 * 6e4;
14230
14314
  var ANALYTICS_RESUME_WINDOW_MS = 6e4;
14315
+ var ANALYTICS_BACKGROUND_RESUME_WINDOW_MS = 5 * 6e4;
14231
14316
  var RESERVED_EVENT_PREFIX = "deepdots_";
14232
14317
  var CUSTOM_EVENT_PREFIX = "deepdots_event_";
14233
14318
  var MAX_PENDING_TRIGGERS = 20;
@@ -14315,6 +14400,8 @@ var DeepdotsPopups = class {
14315
14400
  this.lastEngagementAt = 0;
14316
14401
  /** Cuándo se ocultó la pestaña por última vez (ms epoch); null si está visible. */
14317
14402
  this.hiddenAt = null;
14403
+ /** `init({ autoTrack: { errors } })`: captura automática de errores. Activa por defecto. */
14404
+ this.autoTrackErrors = true;
14318
14405
  /** Suscripción automática a AppState (React Native, `autoTrack.lifecycle`). */
14319
14406
  this.appStateSubscription = void 0;
14320
14407
  /**
@@ -14361,6 +14448,7 @@ var DeepdotsPopups = class {
14361
14448
  this.surveyCss = config.surveyCss;
14362
14449
  this.cspNonce = config.cspNonce;
14363
14450
  this.onFeedbackSession = config.onFeedbackSession;
14451
+ this.autoTrackErrors = config.autoTrack?.errors !== false;
14364
14452
  this.config = {
14365
14453
  apiKey: config.apiKey || void 0,
14366
14454
  debug: config.debug || false,
@@ -14392,7 +14480,7 @@ var DeepdotsPopups = class {
14392
14480
  const resumable = this.readResumableSession();
14393
14481
  if (resumable) {
14394
14482
  this.analyticsFeedbackSessionId = resumable.sessionId;
14395
- this.suspended = { at: resumable.at, userId: resumable.userId };
14483
+ this.suspended = { at: resumable.at, userId: resumable.userId, windowMs: ANALYTICS_RESUME_WINDOW_MS };
14396
14484
  }
14397
14485
  const analyticsSink = config.analytics ? createFeedbackSink({
14398
14486
  baseUrl: this.baseUrl,
@@ -14559,11 +14647,14 @@ var DeepdotsPopups = class {
14559
14647
  */
14560
14648
  installCrashHandlers() {
14561
14649
  if (!this.crashReporter || !this.tracking?.isTrackingEnabled()) return;
14562
- this.crashReporter.install();
14563
- const errorUtils = this.rnErrorUtils ?? globalThis.ErrorUtils;
14650
+ const auto = this.autoTrackErrors;
14651
+ if (auto) this.crashReporter.install();
14652
+ const errorUtils = this.rnErrorUtils ?? (auto ? globalThis.ErrorUtils : void 0);
14564
14653
  if (errorUtils && typeof errorUtils.setGlobalHandler === "function") {
14565
14654
  this.crashReporter.installReactNative(errorUtils);
14566
14655
  }
14656
+ const rejections = auto ? getReactNativePlatform()?.promiseRejections : null;
14657
+ if (rejections) this.crashReporter.installPromiseRejections(rejections);
14567
14658
  }
14568
14659
  /**
14569
14660
  * Info interna del usuario que solo conoce el host (idioma, edad, plan…), persistida en el
@@ -14648,21 +14739,28 @@ var DeepdotsPopups = class {
14648
14739
  this.navObserver.visit(name);
14649
14740
  }
14650
14741
  }
14651
- /** App a foreground (RN: AppState 'active'): reanuda el engagement time y abre sesión nueva. */
14742
+ /**
14743
+ * App a foreground (RN: AppState 'active'): reanuda el engagement time. Si la app estuvo en
14744
+ * background menos de ANALYTICS_BACKGROUND_RESUME_WINDOW_MS sigue en la misma sesión
14745
+ * (`deepdots_session_resume`); si no, abre una nueva (`session_start` `foreground`).
14746
+ */
14652
14747
  onForeground() {
14653
14748
  this.engagement?.resume();
14654
14749
  this.openSession("foreground");
14655
14750
  }
14656
14751
  /**
14657
- * App a background (RN: AppState 'background'): FIN DE SESIÓN. Cierra pantalla actual
14658
- * (page_view), mini-services (mini_service_exit), emite engagement + `session_end` y
14659
- * envía el último lote con `completed:true`.
14660
- *
14661
- * Es la única señal disponible en móvil: el kill de la app (swipe) NO da callback.
14752
+ * App a background (RN: AppState 'background'): SUSPENDE la sesión. Cierra la pantalla
14753
+ * actual (page_view), los mini-services (mini_service_exit) y envía lo acumulado con un
14754
+ * `deepdots_session_suspend` (`reason: background`) y SIN `completed`:
14755
+ * - si la app vuelve dentro de ANALYTICS_BACKGROUND_RESUME_WINDOW_MS, `onForeground` sigue
14756
+ * en el mismo registro;
14757
+ * - si no vuelve (o la matan: el swipe NO da callback), el backend la cierra pasados unos
14758
+ * minutos con un `session_end` `background` a la hora de la suspensión.
14759
+ * Si aún no se conoce el registro (el primer POST sigue en vuelo), FIN DE SESIÓN como antes.
14662
14760
  */
14663
14761
  onBackground() {
14664
14762
  this.cancelDelayedPopups("app to background");
14665
- this.closeSession("background");
14763
+ if (!this.suspendSession("background")) this.closeSession("background");
14666
14764
  this.engagement?.pause();
14667
14765
  }
14668
14766
  /**
@@ -14709,11 +14807,24 @@ var DeepdotsPopups = class {
14709
14807
  * anterior (`session_end` con `reason: 'user_change'` + `completed:true`), cambia la
14710
14808
  * identidad y abre una sesión nueva. Sin `userId` vuelve al id anónimo del SDK.
14711
14809
  *
14810
+ * Anónimo → identificado (la app arranca sin `userId` y lo pone al hacer login) es la MISMA
14811
+ * persona, no otra: el `session_start` de la sesión nueva lleva `identified: true`,
14812
+ * `previous_user_id` (el id anónimo) y `previous_session_id` (el registro que se acaba de
14813
+ * cerrar), para que el backend una las dos sin adivinar; y el estado de popups (mostrados,
14814
+ * respondidos, protecciones de mensajes) se conserva. Sin esto, cada persona que se registra
14815
+ * contaba dos veces: una que "abandona" en el login y otra registrada nueva.
14816
+ *
14712
14817
  * Equivale a llamar a `init()` otra vez con otro `userId`.
14713
14818
  */
14714
14819
  setUserId(userId) {
14715
14820
  const next = userId || void 0;
14716
14821
  if (!this.initialized || !this.config || next === this.config.userId) return;
14822
+ const identifying = !this.config.userId && !!next;
14823
+ const previous = identifying ? {
14824
+ identified: true,
14825
+ previous_user_id: this.tracking?.getUserId() ?? void 0,
14826
+ previous_session_id: this.analyticsFeedbackSessionId
14827
+ } : void 0;
14717
14828
  this.closeSession("user_change");
14718
14829
  const enabled = this.tracking?.isTrackingEnabled() ?? true;
14719
14830
  const storage = this.storage ?? createDefaultStorage();
@@ -14726,13 +14837,18 @@ var DeepdotsPopups = class {
14726
14837
  post: (body) => this.postContact(body)
14727
14838
  }) : null;
14728
14839
  this.analytics?.resetUserScope();
14729
- this.messageGuard.reset();
14730
- this.lastShown.clear();
14731
- this.surveyProgress.clear();
14732
- this.answeredSurveys.clear();
14733
- clearPopupState(storage);
14734
- this.log("tracking \xB7 user_change \xB7 user_id:", this.tracking.getUserId());
14735
- this.openSession("user_change");
14840
+ if (!identifying) {
14841
+ this.messageGuard.reset();
14842
+ this.lastShown.clear();
14843
+ this.surveyProgress.clear();
14844
+ this.answeredSurveys.clear();
14845
+ clearPopupState(storage);
14846
+ }
14847
+ this.log(
14848
+ identifying ? "tracking \xB7 user identified \xB7 user_id:" : "tracking \xB7 user_change \xB7 user_id:",
14849
+ this.tracking.getUserId()
14850
+ );
14851
+ this.openSession("user_change", previous);
14736
14852
  }
14737
14853
  /**
14738
14854
  * Cierra la sesión actual: vuelca todo lo que quedaba abierto y envía el último lote
@@ -14768,14 +14884,14 @@ var DeepdotsPopups = class {
14768
14884
  * - `bfcache_restore`: vuelta desde la bfcache fuera de la ventana de reanudación.
14769
14885
  * Si hay una sesión suspendida a tiempo emite `deepdots_session_resume` en su lugar, sin reason.
14770
14886
  */
14771
- openSession(reason) {
14887
+ openSession(reason, extra) {
14772
14888
  if (this.sessionOpen) return;
14773
14889
  if (!this.tracking?.isTrackingEnabled()) return;
14774
14890
  const suspendedMs = this.takeSuspendedSession();
14775
14891
  this.sessionOpen = true;
14776
14892
  this.lastEngagementAt = Date.now();
14777
14893
  if (suspendedMs === null) {
14778
- this.track("deepdots_session_start", { reason });
14894
+ this.track("deepdots_session_start", { reason, ...extra });
14779
14895
  } else {
14780
14896
  this.track("deepdots_session_resume", { suspended_ms: suspendedMs });
14781
14897
  this.log("tracking \xB7 session resumed after", suspendedMs, "ms:", this.analyticsFeedbackSessionId);
@@ -14869,27 +14985,37 @@ var DeepdotsPopups = class {
14869
14985
  * - si la página vuelve a cargar en esta pestaña, `init()` sigue en el mismo registro;
14870
14986
  * - si la pestaña se cerró, el backend lo cierra a los pocos minutos sin otro lote.
14871
14987
  *
14988
+ * En React Native (`background`) la suspensión vive en memoria: la app sigue viva en
14989
+ * background y, si el SO la mata, el arranque siguiente es otra sesión (`cold_start`).
14990
+ *
14872
14991
  * Devuelve false cuando no se puede suspender — aún no se conoce el registro (el primer
14873
- * POST sigue en vuelo) o no hay `sessionStorage` — y entonces el caller cierra como antes.
14992
+ * POST sigue en vuelo) o, en web, no hay `sessionStorage` — y entonces el caller cierra
14993
+ * como antes.
14874
14994
  */
14875
- suspendSession() {
14995
+ suspendSession(reason) {
14876
14996
  if (!this.sessionOpen || !this.tracking?.isTrackingEnabled()) return false;
14877
14997
  const sessionId = this.analyticsFeedbackSessionId;
14878
14998
  const integration = this.analyticsIntegration;
14879
- const storage = getSessionStorage();
14880
- if (!sessionId || !integration || !storage) return false;
14999
+ if (!sessionId || !integration) return false;
14881
15000
  const at = Date.now();
14882
15001
  const userId = this.tracking.getUserId();
14883
- if (!writeSuspendedSession(storage, { sessionId, integration, userId, at })) return false;
15002
+ if (reason === "page_hide") {
15003
+ const storage = getSessionStorage();
15004
+ if (!storage || !writeSuspendedSession(storage, { sessionId, integration, userId, at })) return false;
15005
+ }
14884
15006
  this.sessionOpen = false;
14885
- this.suspended = { at, userId };
15007
+ this.suspended = {
15008
+ at,
15009
+ userId,
15010
+ windowMs: reason === "page_hide" ? ANALYTICS_RESUME_WINDOW_MS : ANALYTICS_BACKGROUND_RESUME_WINDOW_MS
15011
+ };
14886
15012
  this.navObserver?.stop();
14887
15013
  this.navStarted = false;
14888
15014
  this.analytics?.exitAllMiniServices();
14889
15015
  this.flushEngagement();
14890
15016
  this.engagement?.pause();
14891
- this.track("deepdots_session_suspend", { reason: "page_hide" });
14892
- this.flushAnalytics({ final: true });
15017
+ this.track("deepdots_session_suspend", { reason });
15018
+ this.flushAnalytics(reason === "page_hide" ? { final: true } : { persist: true });
14893
15019
  this.log("tracking \xB7 session suspended:", sessionId);
14894
15020
  return true;
14895
15021
  }
@@ -14911,7 +15037,8 @@ var DeepdotsPopups = class {
14911
15037
  }
14912
15038
  /**
14913
15039
  * Consume la sesión suspendida al abrir: los ms que estuvo suspendida si se puede seguir en
14914
- * ella (mismo usuario, dentro de ANALYTICS_RESUME_WINDOW_MS); null si no había o ya no toca.
15040
+ * ella (mismo usuario, dentro de su ventana: ANALYTICS_RESUME_WINDOW_MS tras un `pagehide`,
15041
+ * ANALYTICS_BACKGROUND_RESUME_WINDOW_MS tras un background); null si no había o ya no toca.
14915
15042
  * En ese caso se olvida su registro sin enviar nada: lo cierra el backend, y la sesión que
14916
15043
  * se abre ahora va a uno nuevo.
14917
15044
  */
@@ -14922,7 +15049,7 @@ var DeepdotsPopups = class {
14922
15049
  const storage = getSessionStorage();
14923
15050
  if (storage) clearSuspendedSession(storage);
14924
15051
  const suspendedMs = Math.max(0, Date.now() - suspended.at);
14925
- if (this.analyticsFeedbackSessionId && suspendedMs <= ANALYTICS_RESUME_WINDOW_MS && suspended.userId === (this.tracking?.getUserId() ?? null)) {
15052
+ if (this.analyticsFeedbackSessionId && suspendedMs <= suspended.windowMs && suspended.userId === (this.tracking?.getUserId() ?? null)) {
14926
15053
  return suspendedMs;
14927
15054
  }
14928
15055
  this.analytics?.discardSession(this.analyticsIdentity());
@@ -14930,6 +15057,27 @@ var DeepdotsPopups = class {
14930
15057
  this.tracking?.setSessionId(null);
14931
15058
  return null;
14932
15059
  }
15060
+ /**
15061
+ * `pagehide` de una pestaña que llevaba oculta más de ANALYTICS_SESSION_TIMEOUT_MS: la
15062
+ * misma regla que `onDocumentVisible`. Suspenderla mandaba un lote más al registro viejo
15063
+ * (page_view + session_suspend) aunque el backend ya lo hubiera cerrado por inactividad:
15064
+ * el backend lo volvía a montar y las acciones de FEEDBACK_DONE (el aviso de Slack de
15065
+ * #platform-visitors) salían otra vez, horas después. Pasó con una pestaña oculta 7 h.
15066
+ * - Oculta menos de ANALYTICS_SESSION_DISCARD_MS: se cierra con `idle_timeout`.
15067
+ * - Más: el backend ya la cerró → se descarta sin enviar nada.
15068
+ * Devuelve false si la pestaña no llevaba tanto oculta (el caller suspende como siempre).
15069
+ */
15070
+ closeStaleHiddenSession() {
15071
+ if (!this.sessionOpen || this.hiddenAt === null) return false;
15072
+ const hiddenFor = Date.now() - this.hiddenAt;
15073
+ if (hiddenFor < ANALYTICS_SESSION_TIMEOUT_MS) return false;
15074
+ if (hiddenFor < ANALYTICS_SESSION_DISCARD_MS) {
15075
+ this.closeSession("idle_timeout");
15076
+ } else {
15077
+ this.discardSession();
15078
+ }
15079
+ return true;
15080
+ }
14933
15081
  /** Olvida la sesión abierta sin enviar nada (ver onDocumentVisible). */
14934
15082
  discardSession() {
14935
15083
  this.sessionOpen = false;
@@ -14978,7 +15126,8 @@ var DeepdotsPopups = class {
14978
15126
  if (typeof document === "undefined" || typeof window === "undefined") return;
14979
15127
  window.addEventListener("pagehide", () => {
14980
15128
  clearInterval(this.analyticsFlushTimer);
14981
- if (!this.suspendSession()) this.closeSession("page_hide");
15129
+ if (this.closeStaleHiddenSession()) return;
15130
+ if (!this.suspendSession("page_hide")) this.closeSession("page_hide");
14982
15131
  });
14983
15132
  window.addEventListener("pageshow", (event) => {
14984
15133
  if (!event.persisted) return;