@magicfeedback/popup-sdk 1.18.0 → 1.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/MagicfeedbackPopupSdk.podspec +18 -0
  2. package/README.md +23 -0
  3. package/dist/2.2.38-CCK7SF4A.mjs +2343 -0
  4. package/dist/2.2.38-CCK7SF4A.mjs.map +1 -0
  5. package/dist/2.2.38-LGZRM7GX.mjs +2343 -0
  6. package/dist/2.2.38-LGZRM7GX.mjs.map +1 -0
  7. package/dist/2.2.39-BJJ3YRJ4.mjs +2344 -0
  8. package/dist/2.2.39-BJJ3YRJ4.mjs.map +1 -0
  9. package/dist/2.2.39-HPNDYUPP.mjs +2344 -0
  10. package/dist/2.2.39-HPNDYUPP.mjs.map +1 -0
  11. package/dist/assets/assets/style.css +107 -1
  12. package/dist/assets/assets/survey-css/2.2.38.css +2335 -0
  13. package/dist/assets/assets/survey-css/2.2.39.css +2336 -0
  14. package/dist/chunk-3QS3WKRC.mjs +31 -0
  15. package/dist/chunk-3QS3WKRC.mjs.map +1 -0
  16. package/dist/chunk-7ZQOAKXR.mjs +3335 -0
  17. package/dist/chunk-7ZQOAKXR.mjs.map +1 -0
  18. package/dist/chunk-BJTO5JO5.mjs +11 -0
  19. package/dist/chunk-BJTO5JO5.mjs.map +1 -0
  20. package/dist/{chunk-DNBFTJCA.mjs → chunk-EW2ARDEY.mjs} +496 -52
  21. package/dist/chunk-EW2ARDEY.mjs.map +1 -0
  22. package/dist/{chunk-7ZVOPIWE.mjs → chunk-XOEEBDBJ.mjs} +535 -11
  23. package/dist/chunk-XOEEBDBJ.mjs.map +1 -0
  24. package/dist/index.d.mts +152 -9
  25. package/dist/index.d.ts +152 -9
  26. package/dist/index.js +7139 -1511
  27. package/dist/index.js.map +1 -1
  28. package/dist/index.mjs +294 -38
  29. package/dist/index.mjs.map +1 -1
  30. package/dist/index.native.d.mts +1616 -0
  31. package/dist/index.native.d.ts +1616 -0
  32. package/dist/index.native.js +15853 -0
  33. package/dist/index.native.js.map +1 -0
  34. package/dist/index.native.mjs +3914 -0
  35. package/dist/index.native.mjs.map +1 -0
  36. package/dist/react-native.d.mts +98 -7
  37. package/dist/react-native.d.ts +98 -7
  38. package/dist/react-native.js +5725 -157
  39. package/dist/react-native.js.map +1 -1
  40. package/dist/react-native.mjs +289 -40
  41. package/dist/react-native.mjs.map +1 -1
  42. package/dist/renderPopup-2Y4QMWR7.mjs +3847 -0
  43. package/dist/renderPopup-2Y4QMWR7.mjs.map +1 -0
  44. package/dist/renderPopup-YDJUON42.mjs +3847 -0
  45. package/dist/renderPopup-YDJUON42.mjs.map +1 -0
  46. package/dist/{renderPopup-B6VIV4VS.mjs → renderPopup-ZHTRMFO2.mjs} +133 -6
  47. package/dist/renderPopup-ZHTRMFO2.mjs.map +1 -0
  48. package/ios/DeepdotsBackgroundTask.m +71 -0
  49. package/package.json +14 -5
  50. package/react-native.config.js +9 -0
  51. package/dist/chunk-7ZVOPIWE.mjs.map +0 -1
  52. package/dist/chunk-DNBFTJCA.mjs.map +0 -1
  53. package/dist/renderPopup-B6VIV4VS.mjs.map +0 -1
  54. package/dist/renderPopup-BKZPAZZG.mjs +0 -3682
  55. package/dist/renderPopup-BKZPAZZG.mjs.map +0 -1
package/dist/index.d.mts CHANGED
@@ -1,3 +1,36 @@
1
+ /**
2
+ * Tiempo de ejecución en segundo plano para los envíos de analytics (DD-55).
3
+ *
4
+ * En iOS la app se suspende pocos segundos después de pasar a background. Si el POST con el
5
+ * cierre de la sesión sigue en vuelo, no termina hasta que el usuario vuelve a abrir la app
6
+ * (medido en producción con React Native, nov 2026: una de cada tres sesiones iOS se cerraba tarde o nunca, frente
7
+ * a ~2 % en Android). iOS concede más tiempo si la app lo pide (`beginBackgroundTask`), pero
8
+ * eso es una API nativa: el SDK es JS puro, así que el host le pasa una función que la abre.
9
+ *
10
+ * Contrato (igual que `beginBackgroundTask` del SDK nativo): `begin(name)` abre una tarea y
11
+ * devuelve la función que la cierra. Puede llamarse varias veces a la vez.
12
+ */
13
+ type BackgroundTaskRunner = (name: string) => () => void;
14
+ /**
15
+ * Techo de una tarea abierta por el SDK. iOS da ~30 s; el POST ya se da por fallido a los
16
+ * 20 s (`POST_TIMEOUT_MS`), así que esto solo cubre un `end` que no llegue nunca.
17
+ */
18
+ declare const BACKGROUND_TASK_MAX_MS = 25000;
19
+ /** Forma mínima de `react-native-background-timer` (`BackgroundTimer` por defecto). */
20
+ interface BackgroundTimerLike {
21
+ start(delay?: number): unknown;
22
+ stop(): unknown;
23
+ }
24
+ /**
25
+ * Adaptador sobre `react-native-background-timer`. En iOS su `start()` abre UNA background
26
+ * task (`beginBackgroundTaskWithName`, y cierra la anterior) y `stop()` la cierra, así que aquí
27
+ * se cuentan las tareas abiertas: `start` con la primera y `stop` cuando se cierra la última.
28
+ *
29
+ * Úsalo solo en iOS: en Android `start()` toma un wakelock (permiso `WAKE_LOCK`) que no hace
30
+ * falta, porque Android no suspende la app al pasar a background.
31
+ */
32
+ declare function backgroundTimerTask(timer: BackgroundTimerLike): BackgroundTaskRunner;
33
+
1
34
  /**
2
35
  * Identidad + sesión para el tracking de navegación (Fase 1).
3
36
  * Implementa el "Contrato común Web+KMP".
@@ -81,6 +114,8 @@ interface AnalyticsEnvelope {
81
114
  sessionId: string | null;
82
115
  context: {
83
116
  platform: string;
117
+ /** SDK que produce la analítica, `<plataforma>@<versión>` (`deepdots_sdk`). */
118
+ sdk?: string;
84
119
  language?: string;
85
120
  /** Info de dispositivo (Technology #11–13). */
86
121
  device?: DeviceInfo;
@@ -130,7 +165,7 @@ type AnalyticsSink = (payload: AnalyticsEnvelope, meta?: AnalyticsFlushMeta) =>
130
165
  * `feedback.finished` se queda siempre en `false` (no es la señal de cierre acordada).
131
166
  *
132
167
  * Encoding:
133
- * - todo va en `feedback.metadata`: contexto (user_id, session_id, platform…) + eventos
168
+ * - todo va en `feedback.metadata`: contexto (user_id, session_id, platform, sdk…) + eventos
134
169
  * - cada entrada usa `value: string[]` (array de un elemento)
135
170
  * - eventos: {key: nombre_evento, value: [JSON(timestamp + params)]}
136
171
  * - identidad (user_id) → `profile` como `external-user-id`
@@ -205,6 +240,12 @@ interface FeedbackSinkOptions {
205
240
  storage?: KeyValueStorage;
206
241
  /** Reloj inyectable (tests). */
207
242
  now?: () => number;
243
+ /**
244
+ * Abre una background task nativa mientras dura cada envío (iOS: `beginBackgroundTask`), para
245
+ * que el POST de cierre termine aunque la app pase a background. Sin él, iOS suele suspender
246
+ * la app con el POST en vuelo y el cierre llega al volver a abrirla (ver `background-task.ts`).
247
+ */
248
+ backgroundTask?: BackgroundTaskRunner;
208
249
  /** Callback invocado cuando la API acepta el primer lote de una sesión (registro abierto). */
209
250
  onSessionId?: (id: string) => void;
210
251
  /** Callback invocado al cerrar la sesión (`completed:true`): el sessionId cacheado se olvida. */
@@ -239,10 +280,6 @@ interface FeedbackSinkOptions {
239
280
  */
240
281
  declare function createFeedbackSink(options: FeedbackSinkOptions): AnalyticsSink;
241
282
 
242
- /**
243
- * Configuration options for initializing the DeepdotsPopups SDK
244
- */
245
-
246
283
  /**
247
284
  * Custom logger to receive the SDK's debug output instead of the console.
248
285
  * Only `log` is required; `warn`/`error`/`info` fall back to `log` when omitted.
@@ -267,6 +304,11 @@ interface FeedbackSession {
267
304
  sessionId: string;
268
305
  status: 'open' | 'closed';
269
306
  }
307
+ /** Signals the SDK detects on its own (see `DeepdotsInitParams.autoTrack`). */
308
+ interface AutoTrackOptions {
309
+ /** React Native: listen to `AppState` for session start/end. Default `true`. */
310
+ lifecycle?: boolean;
311
+ }
270
312
  interface DeepdotsInitParams {
271
313
  /** API key for authentication */
272
314
  apiKey?: string;
@@ -296,6 +338,24 @@ interface DeepdotsInitParams {
296
338
  language?: string;
297
339
  /** Injectable device info (RN: from react-native-device-info). If missing, it is derived from the browser. */
298
340
  device?: DeviceInfo;
341
+ /**
342
+ * React Native (iOS): opens a native background task while each analytics request is in
343
+ * flight, so the session's closing request finishes after the app goes to background
344
+ * instead of when the user opens the app again. `begin(name)` starts the task and returns
345
+ * the function that ends it (iOS `beginBackgroundTask` / `endBackgroundTask`). The SDK ends
346
+ * it when the request settles, or after 25 s. Use `backgroundTimerTask(BackgroundTimer)`
347
+ * for `react-native-background-timer`, iOS only. Without it, nothing changes: a closing
348
+ * request that does not finish is stored and sent on the next launch.
349
+ */
350
+ backgroundTask?: BackgroundTaskRunner;
351
+ /**
352
+ * What the SDK detects on its own. Everything is on by default; set a signal to `false` to
353
+ * turn it off. `lifecycle` (React Native): the SDK listens to `AppState` itself
354
+ * (`active` → session start, `inactive` → send pending data, `background` → session end), so
355
+ * the host does not need to call `onForeground` / `onInactive` / `onBackground`. Calling them
356
+ * as well is harmless: nothing is sent twice.
357
+ */
358
+ autoTrack?: AutoTrackOptions;
299
359
  /**
300
360
  * Analytics channel keys (`POST /sdk/feedback`). If provided, analytics is SENT
301
361
  * to the configured integration; if missing, it stays in dry-run mode: nothing is sent, and the payload is only
@@ -379,6 +439,11 @@ interface TriggerConfig {
379
439
  surveyId: string;
380
440
  /** Optional popup definition id (used to disambiguate repeated survey ids) */
381
441
  popupId?: string;
442
+ /**
443
+ * Seconds to wait once the trigger fires before showing the popup ("Delay" in the Admin).
444
+ * For `exit` it is the wait on the next route. 0 or missing = at once.
445
+ */
446
+ delaySeconds?: number;
382
447
  }
383
448
  /**
384
449
  * Event types emitted by the SDK
@@ -445,6 +510,11 @@ interface PopupTriggerCondition {
445
510
  interface PopupTrigger {
446
511
  type: PopupTriggerType;
447
512
  value: number | string;
513
+ /**
514
+ * "Delay (seconds)" in the Admin: wait this long after the trigger fires before showing the
515
+ * popup. 0 or missing = at once. For `exit` the Admin stores the delay here and `value` is 0.
516
+ */
517
+ delaySeconds?: number;
448
518
  }
449
519
  /** Accept action (open survey) */
450
520
  interface PopupActionAccept {
@@ -518,6 +588,21 @@ interface PopupDefinition {
518
588
  productId: string;
519
589
  style?: PopupStyle;
520
590
  segments?: PopupSegments;
591
+ /**
592
+ * Versión del survey asignada en el Admin (latest o fijada) y su survey SDK (DD-70). La manda
593
+ * la API desde DD-70; con APIs anteriores falta y se usa el survey SDK empaquetado.
594
+ */
595
+ surveyFrontend?: PopupSurveyFrontend | null;
596
+ }
597
+ /** `surveyFrontend` de `GET /sdk/{publicKey}/popups` (DD-70). */
598
+ interface PopupSurveyFrontend {
599
+ /** Versión de MagicSurvey resuelta (X.Y.Z). */
600
+ version?: string;
601
+ /** "latest" o la X.Y.Z fijada. */
602
+ preference?: string;
603
+ status?: string;
604
+ /** `@magicfeedback/native` con el que se construyó esa versión; null si no se conoce. */
605
+ sdkVersion?: string | null;
521
606
  }
522
607
 
523
608
  /**
@@ -546,6 +631,13 @@ interface PopupRenderOptions {
546
631
  * la hoja del survey. No aplica a React Native (el survey vive en su propio WebView).
547
632
  */
548
633
  cspNonce?: string;
634
+ /**
635
+ * `surveyFrontend.sdkVersion` del popup (DD-70): versión de `@magicfeedback/native` asignada
636
+ * al survey en el Admin. Se usa si está en el rango soportado y carga; si no, la empaquetada.
637
+ */
638
+ surveySdkVersion?: string | null;
639
+ /** `init({debug})`, para el log de la versión de survey SDK elegida. */
640
+ debug?: boolean;
549
641
  }
550
642
  interface PopupRenderer {
551
643
  /** Preparar recursos si aplica */
@@ -797,6 +889,10 @@ declare class DeepdotsPopups {
797
889
  private lastShown;
798
890
  private surveyToPopupId;
799
891
  private deferredExitTimers;
892
+ /** Popups esperando su `delaySeconds` (uno por popup). */
893
+ private delayedPopups;
894
+ /** Última pantalla de `setScreen` (React Native). */
895
+ private currentScreen;
800
896
  private baseUrl;
801
897
  private env;
802
898
  /** Si el SDK pinta el "modal" del popup (RN). Default true; false = el host lo envuelve. */
@@ -842,6 +938,8 @@ declare class DeepdotsPopups {
842
938
  private lastEngagementAt;
843
939
  /** Cuándo se ocultó la pestaña por última vez (ms epoch); null si está visible. */
844
940
  private hiddenAt;
941
+ /** Suscripción automática a AppState (React Native, `autoTrack.lifecycle`). */
942
+ private appStateSubscription;
845
943
  /**
846
944
  * Sesión suspendida por un `pagehide` (ms epoch y `deepdots_user_id`); null si no hay.
847
945
  * `openSession` la reanuda si sigue a tiempo (ver ANALYTICS_RESUME_WINDOW_MS).
@@ -948,6 +1046,22 @@ declare class DeepdotsPopups {
948
1046
  * Es la única señal disponible en móvil: el kill de la app (swipe) NO da callback.
949
1047
  */
950
1048
  onBackground(): void;
1049
+ /**
1050
+ * App a `inactive` (RN, iOS: centro de control, llamada, app switcher, y SIEMPRE justo antes
1051
+ * de `background`). NO cierra la sesión (es transitorio), pero envía lo acumulado con un
1052
+ * `user_engagement` que lleva la pantalla en curso, como web al ocultar la pestaña: si el
1053
+ * lote de cierre de `background` no llega a salir (iOS suspende la app), el backend ya
1054
+ * tiene el tiempo activo y la última pantalla. El contador sigue en marcha.
1055
+ */
1056
+ onInactive(): void;
1057
+ /**
1058
+ * Ciclo de vida automático en React Native (contrato de detección automática): el SDK escucha
1059
+ * AppState él mismo, así que el host no tiene que llamar a `onForeground`/`onInactive`/
1060
+ * `onBackground`. Si el host los llama además (integraciones anteriores), no se duplica nada:
1061
+ * abrir o cerrar una sesión ya abierta o cerrada no hace nada, y el engagement se consume.
1062
+ * `autoTrack.lifecycle: false` lo apaga.
1063
+ */
1064
+ private installAutoLifecycle;
951
1065
  /**
952
1066
  * Cierre EXPLÍCITO de la sesión por parte del host (logout, fin de flujo…): emite
953
1067
  * `session_end` y envía el último lote con `completed:true`.
@@ -1067,11 +1181,28 @@ declare class DeepdotsPopups {
1067
1181
  configureTriggers(triggers: TriggerConfig[]): void;
1068
1182
  /** Deriva triggers desde las definiciones de popup */
1069
1183
  private configureTriggersFromDefinitions;
1070
- /** Lógica para evaluar condiciones antes de mostrar una encuesta */
1071
- triggerSurvey(surveyId: string, popupId?: string): void;
1184
+ /**
1185
+ * Lógica para evaluar condiciones antes de mostrar una encuesta. `options.delaySeconds`
1186
+ * (lo pasan los triggers time/scroll/click con el "Delay" del Admin) espera ese tiempo y
1187
+ * vuelve a evaluar antes de mostrar; sin él, al momento como siempre.
1188
+ */
1189
+ triggerSurvey(surveyId: string, popupId?: string, options?: {
1190
+ delaySeconds?: number;
1191
+ }): void;
1072
1192
  /** Trigger popups configured with trigger.type = 'event' and matching trigger.value */
1073
1193
  triggerEvent(eventName: string): void;
1074
1194
  private evaluateEvent;
1195
+ /**
1196
+ * Muestra `def` ya, o tras su "Delay (seconds)" del Admin. Mientras espera:
1197
+ * - el mismo popup no se programa dos veces (el primer vencimiento manda);
1198
+ * - cambiar de ruta/pantalla o pasar a background lo cancela;
1199
+ * y al vencer se vuelve a evaluar todo (segmentos, idioma, cooldowns) como un disparo nuevo.
1200
+ * Si entonces hay otro popup abierto, `showDefinition` lo salta sin efectos, igual que hoy.
1201
+ */
1202
+ private showAfterDelay;
1203
+ private showDelayedPopup;
1204
+ private cancelDelayedPopups;
1205
+ private currentHref;
1075
1206
  /**
1076
1207
  * Guarda `trigger` si las definiciones aún no han llegado. Devuelve `true` si lo guardó (el
1077
1208
  * llamador no debe evaluarlo ahora) y `false` si no hay carga en vuelo (se evalúa ya, como
@@ -1282,6 +1413,11 @@ interface BuildSurveyHtmlOptions {
1282
1413
  env?: string;
1283
1414
  profile?: IdentityAnswer[];
1284
1415
  metadata?: IdentityAnswer[];
1416
+ /**
1417
+ * Versión de `@magicfeedback/native` a cargar (DD-70: la asignada al survey ya elegida con
1418
+ * `chooseSurveySdkVersion`). Por defecto la empaquetada. Con otra, el HTML trae su hoja
1419
+ * vendorizada y su JS; si cualquiera falla, la hoja y la JS empaquetadas.
1420
+ */
1285
1421
  version?: string;
1286
1422
  font?: PopupFont;
1287
1423
  theme?: 'light' | 'dark';
@@ -1352,7 +1488,7 @@ declare const REVEAL_TIMEOUT_MS = 1200;
1352
1488
  * resolución, para que las tres rutas (popup DOM web, WebView de RN y Compose) digan lo mismo.
1353
1489
  */
1354
1490
  /** Locales con traducción propia. Cualquier otro idioma cae a `en`. */
1355
- type PopupLocale = 'en' | 'es' | 'da' | 'no' | 'sv' | 'fi' | 'de' | 'fr' | 'pt' | 'ar' | 'bn' | 'zh-CN';
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';
1356
1492
  interface PopupLabels {
1357
1493
  /** Acción principal: enviar la respuesta. */
1358
1494
  accept: string;
@@ -1376,6 +1512,8 @@ interface PopupLabels {
1376
1512
  loadingAria: string;
1377
1513
  /** Aviso al intentar avanzar con una pregunta obligatoria sin responder. */
1378
1514
  errorRequired: string;
1515
+ /** Aviso al intentar avanzar con un email que no es una dirección válida (`INVALID_EMAIL`). */
1516
+ errorInvalidEmail: string;
1379
1517
  /** Aviso cuando el envío falla. */
1380
1518
  errorSubmit: string;
1381
1519
  /** Aviso cuando el survey no ha podido cargar (el popup solo ofrece cerrarlo). */
@@ -1458,6 +1596,11 @@ interface ReactNativeSetupDeps {
1458
1596
  renderer?: PopupRenderer;
1459
1597
  /** `global.ErrorUtils` de RN (para capturar errores JS no manejados). Default: `globalThis.ErrorUtils`. */
1460
1598
  errorUtils?: ReactNativeErrorUtils | null;
1599
+ /**
1600
+ * Background task nativa para los envíos (iOS, DD-55). Si `config.backgroundTask` viene, gana
1601
+ * ese. Para `react-native-background-timer`: `backgroundTimerTask(BackgroundTimer)`.
1602
+ */
1603
+ backgroundTask?: BackgroundTaskRunner | null;
1461
1604
  }
1462
1605
  /** Adaptador KeyValueStorage (síncrono) sobre una instancia de MMKV. */
1463
1606
  declare function mmkvStorage(mmkv: MmkvLike): KeyValueStorage;
@@ -1470,4 +1613,4 @@ declare function collectRnDevice(d: DeviceInfoLike): DeviceInfo;
1470
1613
  */
1471
1614
  declare function setupReactNative(sdk: DeepdotsPopups, config: DeepdotsInitParams, deps?: ReactNativeSetupDeps): () => void;
1472
1615
 
1473
- export { type AnalyticsFeedbackBody, type AnalyticsKeys, type AppStateLike, 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, buildAnalyticsFeedbackBody, buildMessageParams, buildSurveyHtml, collectRnDevice, crashRecordToParams, createDefaultRenderer, createFeedbackSink, directionFor, getLabels, isRtlLanguage, mmkvStorage, resolveActionLabels, resolveLocale, setupReactNative };
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 };
package/dist/index.d.ts CHANGED
@@ -1,3 +1,36 @@
1
+ /**
2
+ * Tiempo de ejecución en segundo plano para los envíos de analytics (DD-55).
3
+ *
4
+ * En iOS la app se suspende pocos segundos después de pasar a background. Si el POST con el
5
+ * cierre de la sesión sigue en vuelo, no termina hasta que el usuario vuelve a abrir la app
6
+ * (medido en producción con React Native, nov 2026: una de cada tres sesiones iOS se cerraba tarde o nunca, frente
7
+ * a ~2 % en Android). iOS concede más tiempo si la app lo pide (`beginBackgroundTask`), pero
8
+ * eso es una API nativa: el SDK es JS puro, así que el host le pasa una función que la abre.
9
+ *
10
+ * Contrato (igual que `beginBackgroundTask` del SDK nativo): `begin(name)` abre una tarea y
11
+ * devuelve la función que la cierra. Puede llamarse varias veces a la vez.
12
+ */
13
+ type BackgroundTaskRunner = (name: string) => () => void;
14
+ /**
15
+ * Techo de una tarea abierta por el SDK. iOS da ~30 s; el POST ya se da por fallido a los
16
+ * 20 s (`POST_TIMEOUT_MS`), así que esto solo cubre un `end` que no llegue nunca.
17
+ */
18
+ declare const BACKGROUND_TASK_MAX_MS = 25000;
19
+ /** Forma mínima de `react-native-background-timer` (`BackgroundTimer` por defecto). */
20
+ interface BackgroundTimerLike {
21
+ start(delay?: number): unknown;
22
+ stop(): unknown;
23
+ }
24
+ /**
25
+ * Adaptador sobre `react-native-background-timer`. En iOS su `start()` abre UNA background
26
+ * task (`beginBackgroundTaskWithName`, y cierra la anterior) y `stop()` la cierra, así que aquí
27
+ * se cuentan las tareas abiertas: `start` con la primera y `stop` cuando se cierra la última.
28
+ *
29
+ * Úsalo solo en iOS: en Android `start()` toma un wakelock (permiso `WAKE_LOCK`) que no hace
30
+ * falta, porque Android no suspende la app al pasar a background.
31
+ */
32
+ declare function backgroundTimerTask(timer: BackgroundTimerLike): BackgroundTaskRunner;
33
+
1
34
  /**
2
35
  * Identidad + sesión para el tracking de navegación (Fase 1).
3
36
  * Implementa el "Contrato común Web+KMP".
@@ -81,6 +114,8 @@ interface AnalyticsEnvelope {
81
114
  sessionId: string | null;
82
115
  context: {
83
116
  platform: string;
117
+ /** SDK que produce la analítica, `<plataforma>@<versión>` (`deepdots_sdk`). */
118
+ sdk?: string;
84
119
  language?: string;
85
120
  /** Info de dispositivo (Technology #11–13). */
86
121
  device?: DeviceInfo;
@@ -130,7 +165,7 @@ type AnalyticsSink = (payload: AnalyticsEnvelope, meta?: AnalyticsFlushMeta) =>
130
165
  * `feedback.finished` se queda siempre en `false` (no es la señal de cierre acordada).
131
166
  *
132
167
  * Encoding:
133
- * - todo va en `feedback.metadata`: contexto (user_id, session_id, platform…) + eventos
168
+ * - todo va en `feedback.metadata`: contexto (user_id, session_id, platform, sdk…) + eventos
134
169
  * - cada entrada usa `value: string[]` (array de un elemento)
135
170
  * - eventos: {key: nombre_evento, value: [JSON(timestamp + params)]}
136
171
  * - identidad (user_id) → `profile` como `external-user-id`
@@ -205,6 +240,12 @@ interface FeedbackSinkOptions {
205
240
  storage?: KeyValueStorage;
206
241
  /** Reloj inyectable (tests). */
207
242
  now?: () => number;
243
+ /**
244
+ * Abre una background task nativa mientras dura cada envío (iOS: `beginBackgroundTask`), para
245
+ * que el POST de cierre termine aunque la app pase a background. Sin él, iOS suele suspender
246
+ * la app con el POST en vuelo y el cierre llega al volver a abrirla (ver `background-task.ts`).
247
+ */
248
+ backgroundTask?: BackgroundTaskRunner;
208
249
  /** Callback invocado cuando la API acepta el primer lote de una sesión (registro abierto). */
209
250
  onSessionId?: (id: string) => void;
210
251
  /** Callback invocado al cerrar la sesión (`completed:true`): el sessionId cacheado se olvida. */
@@ -239,10 +280,6 @@ interface FeedbackSinkOptions {
239
280
  */
240
281
  declare function createFeedbackSink(options: FeedbackSinkOptions): AnalyticsSink;
241
282
 
242
- /**
243
- * Configuration options for initializing the DeepdotsPopups SDK
244
- */
245
-
246
283
  /**
247
284
  * Custom logger to receive the SDK's debug output instead of the console.
248
285
  * Only `log` is required; `warn`/`error`/`info` fall back to `log` when omitted.
@@ -267,6 +304,11 @@ interface FeedbackSession {
267
304
  sessionId: string;
268
305
  status: 'open' | 'closed';
269
306
  }
307
+ /** Signals the SDK detects on its own (see `DeepdotsInitParams.autoTrack`). */
308
+ interface AutoTrackOptions {
309
+ /** React Native: listen to `AppState` for session start/end. Default `true`. */
310
+ lifecycle?: boolean;
311
+ }
270
312
  interface DeepdotsInitParams {
271
313
  /** API key for authentication */
272
314
  apiKey?: string;
@@ -296,6 +338,24 @@ interface DeepdotsInitParams {
296
338
  language?: string;
297
339
  /** Injectable device info (RN: from react-native-device-info). If missing, it is derived from the browser. */
298
340
  device?: DeviceInfo;
341
+ /**
342
+ * React Native (iOS): opens a native background task while each analytics request is in
343
+ * flight, so the session's closing request finishes after the app goes to background
344
+ * instead of when the user opens the app again. `begin(name)` starts the task and returns
345
+ * the function that ends it (iOS `beginBackgroundTask` / `endBackgroundTask`). The SDK ends
346
+ * it when the request settles, or after 25 s. Use `backgroundTimerTask(BackgroundTimer)`
347
+ * for `react-native-background-timer`, iOS only. Without it, nothing changes: a closing
348
+ * request that does not finish is stored and sent on the next launch.
349
+ */
350
+ backgroundTask?: BackgroundTaskRunner;
351
+ /**
352
+ * What the SDK detects on its own. Everything is on by default; set a signal to `false` to
353
+ * turn it off. `lifecycle` (React Native): the SDK listens to `AppState` itself
354
+ * (`active` → session start, `inactive` → send pending data, `background` → session end), so
355
+ * the host does not need to call `onForeground` / `onInactive` / `onBackground`. Calling them
356
+ * as well is harmless: nothing is sent twice.
357
+ */
358
+ autoTrack?: AutoTrackOptions;
299
359
  /**
300
360
  * Analytics channel keys (`POST /sdk/feedback`). If provided, analytics is SENT
301
361
  * to the configured integration; if missing, it stays in dry-run mode: nothing is sent, and the payload is only
@@ -379,6 +439,11 @@ interface TriggerConfig {
379
439
  surveyId: string;
380
440
  /** Optional popup definition id (used to disambiguate repeated survey ids) */
381
441
  popupId?: string;
442
+ /**
443
+ * Seconds to wait once the trigger fires before showing the popup ("Delay" in the Admin).
444
+ * For `exit` it is the wait on the next route. 0 or missing = at once.
445
+ */
446
+ delaySeconds?: number;
382
447
  }
383
448
  /**
384
449
  * Event types emitted by the SDK
@@ -445,6 +510,11 @@ interface PopupTriggerCondition {
445
510
  interface PopupTrigger {
446
511
  type: PopupTriggerType;
447
512
  value: number | string;
513
+ /**
514
+ * "Delay (seconds)" in the Admin: wait this long after the trigger fires before showing the
515
+ * popup. 0 or missing = at once. For `exit` the Admin stores the delay here and `value` is 0.
516
+ */
517
+ delaySeconds?: number;
448
518
  }
449
519
  /** Accept action (open survey) */
450
520
  interface PopupActionAccept {
@@ -518,6 +588,21 @@ interface PopupDefinition {
518
588
  productId: string;
519
589
  style?: PopupStyle;
520
590
  segments?: PopupSegments;
591
+ /**
592
+ * Versión del survey asignada en el Admin (latest o fijada) y su survey SDK (DD-70). La manda
593
+ * la API desde DD-70; con APIs anteriores falta y se usa el survey SDK empaquetado.
594
+ */
595
+ surveyFrontend?: PopupSurveyFrontend | null;
596
+ }
597
+ /** `surveyFrontend` de `GET /sdk/{publicKey}/popups` (DD-70). */
598
+ interface PopupSurveyFrontend {
599
+ /** Versión de MagicSurvey resuelta (X.Y.Z). */
600
+ version?: string;
601
+ /** "latest" o la X.Y.Z fijada. */
602
+ preference?: string;
603
+ status?: string;
604
+ /** `@magicfeedback/native` con el que se construyó esa versión; null si no se conoce. */
605
+ sdkVersion?: string | null;
521
606
  }
522
607
 
523
608
  /**
@@ -546,6 +631,13 @@ interface PopupRenderOptions {
546
631
  * la hoja del survey. No aplica a React Native (el survey vive en su propio WebView).
547
632
  */
548
633
  cspNonce?: string;
634
+ /**
635
+ * `surveyFrontend.sdkVersion` del popup (DD-70): versión de `@magicfeedback/native` asignada
636
+ * al survey en el Admin. Se usa si está en el rango soportado y carga; si no, la empaquetada.
637
+ */
638
+ surveySdkVersion?: string | null;
639
+ /** `init({debug})`, para el log de la versión de survey SDK elegida. */
640
+ debug?: boolean;
549
641
  }
550
642
  interface PopupRenderer {
551
643
  /** Preparar recursos si aplica */
@@ -797,6 +889,10 @@ declare class DeepdotsPopups {
797
889
  private lastShown;
798
890
  private surveyToPopupId;
799
891
  private deferredExitTimers;
892
+ /** Popups esperando su `delaySeconds` (uno por popup). */
893
+ private delayedPopups;
894
+ /** Última pantalla de `setScreen` (React Native). */
895
+ private currentScreen;
800
896
  private baseUrl;
801
897
  private env;
802
898
  /** Si el SDK pinta el "modal" del popup (RN). Default true; false = el host lo envuelve. */
@@ -842,6 +938,8 @@ declare class DeepdotsPopups {
842
938
  private lastEngagementAt;
843
939
  /** Cuándo se ocultó la pestaña por última vez (ms epoch); null si está visible. */
844
940
  private hiddenAt;
941
+ /** Suscripción automática a AppState (React Native, `autoTrack.lifecycle`). */
942
+ private appStateSubscription;
845
943
  /**
846
944
  * Sesión suspendida por un `pagehide` (ms epoch y `deepdots_user_id`); null si no hay.
847
945
  * `openSession` la reanuda si sigue a tiempo (ver ANALYTICS_RESUME_WINDOW_MS).
@@ -948,6 +1046,22 @@ declare class DeepdotsPopups {
948
1046
  * Es la única señal disponible en móvil: el kill de la app (swipe) NO da callback.
949
1047
  */
950
1048
  onBackground(): void;
1049
+ /**
1050
+ * App a `inactive` (RN, iOS: centro de control, llamada, app switcher, y SIEMPRE justo antes
1051
+ * de `background`). NO cierra la sesión (es transitorio), pero envía lo acumulado con un
1052
+ * `user_engagement` que lleva la pantalla en curso, como web al ocultar la pestaña: si el
1053
+ * lote de cierre de `background` no llega a salir (iOS suspende la app), el backend ya
1054
+ * tiene el tiempo activo y la última pantalla. El contador sigue en marcha.
1055
+ */
1056
+ onInactive(): void;
1057
+ /**
1058
+ * Ciclo de vida automático en React Native (contrato de detección automática): el SDK escucha
1059
+ * AppState él mismo, así que el host no tiene que llamar a `onForeground`/`onInactive`/
1060
+ * `onBackground`. Si el host los llama además (integraciones anteriores), no se duplica nada:
1061
+ * abrir o cerrar una sesión ya abierta o cerrada no hace nada, y el engagement se consume.
1062
+ * `autoTrack.lifecycle: false` lo apaga.
1063
+ */
1064
+ private installAutoLifecycle;
951
1065
  /**
952
1066
  * Cierre EXPLÍCITO de la sesión por parte del host (logout, fin de flujo…): emite
953
1067
  * `session_end` y envía el último lote con `completed:true`.
@@ -1067,11 +1181,28 @@ declare class DeepdotsPopups {
1067
1181
  configureTriggers(triggers: TriggerConfig[]): void;
1068
1182
  /** Deriva triggers desde las definiciones de popup */
1069
1183
  private configureTriggersFromDefinitions;
1070
- /** Lógica para evaluar condiciones antes de mostrar una encuesta */
1071
- triggerSurvey(surveyId: string, popupId?: string): void;
1184
+ /**
1185
+ * Lógica para evaluar condiciones antes de mostrar una encuesta. `options.delaySeconds`
1186
+ * (lo pasan los triggers time/scroll/click con el "Delay" del Admin) espera ese tiempo y
1187
+ * vuelve a evaluar antes de mostrar; sin él, al momento como siempre.
1188
+ */
1189
+ triggerSurvey(surveyId: string, popupId?: string, options?: {
1190
+ delaySeconds?: number;
1191
+ }): void;
1072
1192
  /** Trigger popups configured with trigger.type = 'event' and matching trigger.value */
1073
1193
  triggerEvent(eventName: string): void;
1074
1194
  private evaluateEvent;
1195
+ /**
1196
+ * Muestra `def` ya, o tras su "Delay (seconds)" del Admin. Mientras espera:
1197
+ * - el mismo popup no se programa dos veces (el primer vencimiento manda);
1198
+ * - cambiar de ruta/pantalla o pasar a background lo cancela;
1199
+ * y al vencer se vuelve a evaluar todo (segmentos, idioma, cooldowns) como un disparo nuevo.
1200
+ * Si entonces hay otro popup abierto, `showDefinition` lo salta sin efectos, igual que hoy.
1201
+ */
1202
+ private showAfterDelay;
1203
+ private showDelayedPopup;
1204
+ private cancelDelayedPopups;
1205
+ private currentHref;
1075
1206
  /**
1076
1207
  * Guarda `trigger` si las definiciones aún no han llegado. Devuelve `true` si lo guardó (el
1077
1208
  * llamador no debe evaluarlo ahora) y `false` si no hay carga en vuelo (se evalúa ya, como
@@ -1282,6 +1413,11 @@ interface BuildSurveyHtmlOptions {
1282
1413
  env?: string;
1283
1414
  profile?: IdentityAnswer[];
1284
1415
  metadata?: IdentityAnswer[];
1416
+ /**
1417
+ * Versión de `@magicfeedback/native` a cargar (DD-70: la asignada al survey ya elegida con
1418
+ * `chooseSurveySdkVersion`). Por defecto la empaquetada. Con otra, el HTML trae su hoja
1419
+ * vendorizada y su JS; si cualquiera falla, la hoja y la JS empaquetadas.
1420
+ */
1285
1421
  version?: string;
1286
1422
  font?: PopupFont;
1287
1423
  theme?: 'light' | 'dark';
@@ -1352,7 +1488,7 @@ declare const REVEAL_TIMEOUT_MS = 1200;
1352
1488
  * resolución, para que las tres rutas (popup DOM web, WebView de RN y Compose) digan lo mismo.
1353
1489
  */
1354
1490
  /** Locales con traducción propia. Cualquier otro idioma cae a `en`. */
1355
- type PopupLocale = 'en' | 'es' | 'da' | 'no' | 'sv' | 'fi' | 'de' | 'fr' | 'pt' | 'ar' | 'bn' | 'zh-CN';
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';
1356
1492
  interface PopupLabels {
1357
1493
  /** Acción principal: enviar la respuesta. */
1358
1494
  accept: string;
@@ -1376,6 +1512,8 @@ interface PopupLabels {
1376
1512
  loadingAria: string;
1377
1513
  /** Aviso al intentar avanzar con una pregunta obligatoria sin responder. */
1378
1514
  errorRequired: string;
1515
+ /** Aviso al intentar avanzar con un email que no es una dirección válida (`INVALID_EMAIL`). */
1516
+ errorInvalidEmail: string;
1379
1517
  /** Aviso cuando el envío falla. */
1380
1518
  errorSubmit: string;
1381
1519
  /** Aviso cuando el survey no ha podido cargar (el popup solo ofrece cerrarlo). */
@@ -1458,6 +1596,11 @@ interface ReactNativeSetupDeps {
1458
1596
  renderer?: PopupRenderer;
1459
1597
  /** `global.ErrorUtils` de RN (para capturar errores JS no manejados). Default: `globalThis.ErrorUtils`. */
1460
1598
  errorUtils?: ReactNativeErrorUtils | null;
1599
+ /**
1600
+ * Background task nativa para los envíos (iOS, DD-55). Si `config.backgroundTask` viene, gana
1601
+ * ese. Para `react-native-background-timer`: `backgroundTimerTask(BackgroundTimer)`.
1602
+ */
1603
+ backgroundTask?: BackgroundTaskRunner | null;
1461
1604
  }
1462
1605
  /** Adaptador KeyValueStorage (síncrono) sobre una instancia de MMKV. */
1463
1606
  declare function mmkvStorage(mmkv: MmkvLike): KeyValueStorage;
@@ -1470,4 +1613,4 @@ declare function collectRnDevice(d: DeviceInfoLike): DeviceInfo;
1470
1613
  */
1471
1614
  declare function setupReactNative(sdk: DeepdotsPopups, config: DeepdotsInitParams, deps?: ReactNativeSetupDeps): () => void;
1472
1615
 
1473
- export { type AnalyticsFeedbackBody, type AnalyticsKeys, type AppStateLike, 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, buildAnalyticsFeedbackBody, buildMessageParams, buildSurveyHtml, collectRnDevice, crashRecordToParams, createDefaultRenderer, createFeedbackSink, directionFor, getLabels, isRtlLanguage, mmkvStorage, resolveActionLabels, resolveLocale, setupReactNative };
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 };