@magicfeedback/popup-sdk 1.18.0 → 1.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/MagicfeedbackPopupSdk.podspec +18 -0
- package/README.md +23 -0
- package/dist/2.2.38-CCK7SF4A.mjs +2343 -0
- package/dist/2.2.38-CCK7SF4A.mjs.map +1 -0
- package/dist/2.2.38-LGZRM7GX.mjs +2343 -0
- package/dist/2.2.38-LGZRM7GX.mjs.map +1 -0
- package/dist/2.2.39-BJJ3YRJ4.mjs +2344 -0
- package/dist/2.2.39-BJJ3YRJ4.mjs.map +1 -0
- package/dist/2.2.39-HPNDYUPP.mjs +2344 -0
- package/dist/2.2.39-HPNDYUPP.mjs.map +1 -0
- package/dist/assets/assets/style.css +107 -1
- package/dist/assets/assets/survey-css/2.2.38.css +2335 -0
- package/dist/assets/assets/survey-css/2.2.39.css +2336 -0
- package/dist/chunk-3QS3WKRC.mjs +31 -0
- package/dist/chunk-3QS3WKRC.mjs.map +1 -0
- package/dist/chunk-BJTO5JO5.mjs +11 -0
- package/dist/chunk-BJTO5JO5.mjs.map +1 -0
- package/dist/{chunk-DNBFTJCA.mjs → chunk-FROREHRG.mjs} +516 -52
- package/dist/chunk-FROREHRG.mjs.map +1 -0
- package/dist/{chunk-7ZVOPIWE.mjs → chunk-OPR5I7WO.mjs} +557 -11
- package/dist/chunk-OPR5I7WO.mjs.map +1 -0
- package/dist/chunk-ZJ5HG3QF.mjs +3357 -0
- package/dist/chunk-ZJ5HG3QF.mjs.map +1 -0
- package/dist/index.d.mts +217 -9
- package/dist/index.d.ts +217 -9
- package/dist/index.js +7253 -1519
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +389 -49
- package/dist/index.mjs.map +1 -1
- package/dist/index.native.d.mts +1681 -0
- package/dist/index.native.d.ts +1681 -0
- package/dist/index.native.js +15972 -0
- package/dist/index.native.js.map +1 -0
- package/dist/index.native.mjs +4011 -0
- package/dist/index.native.mjs.map +1 -0
- package/dist/react-native.d.mts +113 -7
- package/dist/react-native.d.ts +113 -7
- package/dist/react-native.js +5846 -162
- package/dist/react-native.js.map +1 -1
- package/dist/react-native.mjs +396 -51
- package/dist/react-native.mjs.map +1 -1
- package/dist/{renderPopup-B6VIV4VS.mjs → renderPopup-I6CPIR75.mjs} +133 -6
- package/dist/renderPopup-I6CPIR75.mjs.map +1 -0
- package/dist/renderPopup-RUY3OBYV.mjs +3847 -0
- package/dist/renderPopup-RUY3OBYV.mjs.map +1 -0
- package/dist/renderPopup-XNVNP2ZU.mjs +3847 -0
- package/dist/renderPopup-XNVNP2ZU.mjs.map +1 -0
- package/ios/DeepdotsBackgroundTask.m +71 -0
- package/package.json +14 -5
- package/react-native.config.js +9 -0
- package/dist/chunk-7ZVOPIWE.mjs.map +0 -1
- package/dist/chunk-DNBFTJCA.mjs.map +0 -1
- package/dist/renderPopup-B6VIV4VS.mjs.map +0 -1
- package/dist/renderPopup-BKZPAZZG.mjs +0 -3682
- package/dist/renderPopup-BKZPAZZG.mjs.map +0 -1
|
@@ -0,0 +1,1681 @@
|
|
|
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
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Identidad + sesión para el tracking de navegación (Fase 1).
|
|
36
|
+
* Implementa el "Contrato común Web+KMP".
|
|
37
|
+
*
|
|
38
|
+
* Modelo: el SDK gestiona el `user_id` (persistente). El `session_id` es propiedad
|
|
39
|
+
* del BACKEND: llega en la respuesta de `POST /sdk/popups` y se cachea; el backend
|
|
40
|
+
* cose sesiones por `user_id` + ventana. El SDK NO genera ni expira sesiones.
|
|
41
|
+
*
|
|
42
|
+
* Sin dependencias de DOM: recibe el storage y (opcionalmente) el reloj y el
|
|
43
|
+
* generador de uuid por inyección. El binding a `localStorage` vive en `createDefaultStorage`.
|
|
44
|
+
*/
|
|
45
|
+
/** Store clave/valor mínimo (espejo conceptual del `KeyValueStorage` de KMP). */
|
|
46
|
+
interface KeyValueStorage {
|
|
47
|
+
getItem(key: string): string | null;
|
|
48
|
+
setItem(key: string, value: string): void;
|
|
49
|
+
removeItem(key: string): void;
|
|
50
|
+
}
|
|
51
|
+
/** Impl en memoria — usada en tests y como fallback sin `localStorage`. */
|
|
52
|
+
declare class InMemoryStorage implements KeyValueStorage {
|
|
53
|
+
private map;
|
|
54
|
+
getItem(key: string): string | null;
|
|
55
|
+
setItem(key: string, value: string): void;
|
|
56
|
+
removeItem(key: string): void;
|
|
57
|
+
}
|
|
58
|
+
/** Par clave/valor con el formato `NativeAnswer` que espera `@magicfeedback/native`. */
|
|
59
|
+
interface IdentityAnswer {
|
|
60
|
+
key: string;
|
|
61
|
+
value: string[];
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Device info para el context de analytics (Technology #11–13).
|
|
66
|
+
*
|
|
67
|
+
* En Web enviamos `device_type` + `user_agent` crudo y dejamos que el backend
|
|
68
|
+
* derive OS/navegador del UA (como hace GA). Los campos adicionales (timezone,
|
|
69
|
+
* referrer, viewport, etc.) se recogen de las APIs del navegador sin permisos.
|
|
70
|
+
* `country`/`city` se rellenan de forma asíncrona (ver geo-info.ts).
|
|
71
|
+
* En KMP las APIs nativas dan os_version/device_model reales.
|
|
72
|
+
*/
|
|
73
|
+
interface DeviceInfo {
|
|
74
|
+
device_type: 'mobile' | 'tablet' | 'desktop';
|
|
75
|
+
os_version?: string;
|
|
76
|
+
device_model?: string;
|
|
77
|
+
app_version?: string;
|
|
78
|
+
user_agent?: string;
|
|
79
|
+
timezone?: string;
|
|
80
|
+
referrer?: string;
|
|
81
|
+
viewport_size?: string;
|
|
82
|
+
screen_resolution?: string;
|
|
83
|
+
pixel_ratio?: number;
|
|
84
|
+
entry_type?: string;
|
|
85
|
+
page_load_ms?: number;
|
|
86
|
+
connection_type?: string;
|
|
87
|
+
country?: string;
|
|
88
|
+
city?: string;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Capa de Analytics (eventos GA-style) — canal SEPARADO del feedback de survey.
|
|
93
|
+
*
|
|
94
|
+
* El feedback de survey se envía con `magicfeedback.send()`. La analítica de
|
|
95
|
+
* navegación/comportamiento (page views, mini-services, tasks/funnels, meaningful
|
|
96
|
+
* interactions, findability…) va por un ENDPOINT PROPIO, vinculada por `user_id`.
|
|
97
|
+
*
|
|
98
|
+
* De momento NO se hace la llamada: el `sink` por defecto hace `console.log` del
|
|
99
|
+
* payload exacto que se enviaría (dry-run), para poder verificarlo. Cuando el
|
|
100
|
+
* endpoint exista, se sustituye el sink por un POST.
|
|
101
|
+
*/
|
|
102
|
+
|
|
103
|
+
interface AnalyticsEvent {
|
|
104
|
+
name: string;
|
|
105
|
+
timestamp: number;
|
|
106
|
+
params?: Record<string, unknown>;
|
|
107
|
+
}
|
|
108
|
+
interface AnalyticsEnvelope {
|
|
109
|
+
/** Clave pública del cliente (auth). */
|
|
110
|
+
publicKey?: string;
|
|
111
|
+
/** Id que vincula la analítica al usuario (el backend cose por aquí). */
|
|
112
|
+
userId: string | null;
|
|
113
|
+
/** Session id del backend si ya se conoce (puede ir null). */
|
|
114
|
+
sessionId: string | null;
|
|
115
|
+
context: {
|
|
116
|
+
platform: string;
|
|
117
|
+
/** SDK que produce la analítica, `<plataforma>@<versión>` (`deepdots_sdk`). */
|
|
118
|
+
sdk?: string;
|
|
119
|
+
language?: string;
|
|
120
|
+
/** Info de dispositivo (Technology #11–13). */
|
|
121
|
+
device?: DeviceInfo;
|
|
122
|
+
/** User attributes del cliente, usados para breakdowns (registration_status, pass_type, …). */
|
|
123
|
+
attributes: Record<string, string>;
|
|
124
|
+
/** Métricas del host: valores medibles persistentes → van en `feedback.metrics` del body. */
|
|
125
|
+
metrics?: Record<string, string>;
|
|
126
|
+
};
|
|
127
|
+
events: AnalyticsEvent[];
|
|
128
|
+
}
|
|
129
|
+
/** Contexto del flush, para que el sink pueda adaptar el transporte. */
|
|
130
|
+
interface AnalyticsFlushMeta {
|
|
131
|
+
/**
|
|
132
|
+
* `true` cuando el flush ocurre porque la página/app se está cerrando. El sink debe usar
|
|
133
|
+
* un transporte que sobreviva al unload (`fetch` con `keepalive`) y no puede esperar
|
|
134
|
+
* respuestas.
|
|
135
|
+
*/
|
|
136
|
+
final?: boolean;
|
|
137
|
+
/**
|
|
138
|
+
* `true` cuando este es el ÚLTIMO lote de la sesión (cierre de página, app a background,
|
|
139
|
+
* cambio de usuario, tracking desactivado). El sink lo envía con `completed:true` y olvida
|
|
140
|
+
* el `sessionId`, para que el lote siguiente abra un registro nuevo.
|
|
141
|
+
*/
|
|
142
|
+
sessionEnd?: boolean;
|
|
143
|
+
/**
|
|
144
|
+
* `true` para olvidar la sesión SIN enviar nada (el payload llega vacío): el backend ya la
|
|
145
|
+
* cerró por inactividad. El sink descarta su `sessionId` para que el lote siguiente abra un
|
|
146
|
+
* registro nuevo, igual que tras `sessionEnd`, pero sin POST.
|
|
147
|
+
*/
|
|
148
|
+
resetSession?: boolean;
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Envío del lote. Si devuelve una promesa que **rechaza**, el manager re-encola los
|
|
152
|
+
* eventos para reintentarlos en el siguiente flush (fallo transitorio: red o 5xx).
|
|
153
|
+
* Resolver = lote entregado o descartado definitivamente (no se reintenta).
|
|
154
|
+
*/
|
|
155
|
+
type AnalyticsSink = (payload: AnalyticsEnvelope, meta?: AnalyticsFlushMeta) => void | Promise<void>;
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Mapeo del envelope de analytics → body de `POST /sdk/feedback`.
|
|
159
|
+
*
|
|
160
|
+
* La analítica se envía como un Feedback del modelo del Surveys SDK, agrupado por una
|
|
161
|
+
* INTEGRACIÓN creada en la plataforma. Se manda en streaming con `completed:false`; el
|
|
162
|
+
* backend agrupa los lotes por `sessionId`, que genera el SDK al abrir cada sesión. El
|
|
163
|
+
* ÚLTIMO lote de una sesión (cierre de página, app a background, cambio de usuario) va con
|
|
164
|
+
* `completed:true`: cierra el registro y el lote siguiente abre otro con un sessionId nuevo.
|
|
165
|
+
* `feedback.finished` se queda siempre en `false` (no es la señal de cierre acordada).
|
|
166
|
+
*
|
|
167
|
+
* Encoding:
|
|
168
|
+
* - todo va en `feedback.metadata`: contexto (user_id, session_id, platform, sdk…) + eventos
|
|
169
|
+
* - cada entrada usa `value: string[]` (array de un elemento)
|
|
170
|
+
* - eventos: {key: nombre_evento, value: [JSON(timestamp + params)]}
|
|
171
|
+
* - identidad (user_id) → `profile` como `external-user-id`
|
|
172
|
+
* - métricas del host (setMetric) → `feedback.metrics` (mismo shape que metadata, sin prefijo)
|
|
173
|
+
* - `answers` vacío
|
|
174
|
+
* - `text` vacío
|
|
175
|
+
*/
|
|
176
|
+
|
|
177
|
+
interface AnalyticsKeys {
|
|
178
|
+
publicKey: string;
|
|
179
|
+
integration: string;
|
|
180
|
+
}
|
|
181
|
+
interface FeedbackKV {
|
|
182
|
+
key: string;
|
|
183
|
+
value: string[];
|
|
184
|
+
}
|
|
185
|
+
interface AnalyticsFeedbackBody {
|
|
186
|
+
feedback: {
|
|
187
|
+
text: string;
|
|
188
|
+
answers: FeedbackKV[];
|
|
189
|
+
metrics: FeedbackKV[];
|
|
190
|
+
metadata: FeedbackKV[];
|
|
191
|
+
profile: FeedbackKV[];
|
|
192
|
+
finished: boolean;
|
|
193
|
+
};
|
|
194
|
+
publicKey: string;
|
|
195
|
+
integration: string;
|
|
196
|
+
completed: boolean;
|
|
197
|
+
finished?: boolean;
|
|
198
|
+
/** sessionId de la sesión (lo genera el SDK): el backend agrupa todos sus lotes en un solo registro. */
|
|
199
|
+
sessionId?: string;
|
|
200
|
+
}
|
|
201
|
+
interface BuildBodyOptions {
|
|
202
|
+
/**
|
|
203
|
+
* `true` en el último lote de la sesión → `completed:true` (cierra el registro en backend).
|
|
204
|
+
* El body lleva el `sessionId` de la sesión que se cierra; el lote siguiente abre otro
|
|
205
|
+
* registro con un sessionId nuevo.
|
|
206
|
+
*/
|
|
207
|
+
sessionEnd?: boolean;
|
|
208
|
+
}
|
|
209
|
+
declare function buildAnalyticsFeedbackBody(envelope: AnalyticsEnvelope, keys: AnalyticsKeys, feedbackSessionId?: string, options?: BuildBodyOptions): AnalyticsFeedbackBody;
|
|
210
|
+
interface FeedbackSinkOptions {
|
|
211
|
+
/** Base URL del backend (api(.|-dev.)deepdots.com) ya resuelta por el entorno. */
|
|
212
|
+
baseUrl: string;
|
|
213
|
+
keys: AnalyticsKeys;
|
|
214
|
+
/** Logger opcional (gated por debug). */
|
|
215
|
+
log?: (...args: unknown[]) => void;
|
|
216
|
+
/** fetch inyectable (tests / RN). */
|
|
217
|
+
fetchImpl?: typeof fetch;
|
|
218
|
+
/**
|
|
219
|
+
* @deprecated Se ignora. El flush final salía por `sendBeacon`, que va SIEMPRE con
|
|
220
|
+
* credenciales; contra la API (`Access-Control-Allow-Origin: *` + `Allow-Credentials:
|
|
221
|
+
* true`) el preflight fallaba y el lote de cierre, el único con `completed:true`, no
|
|
222
|
+
* llegaba nunca. Ahora sale por `fetch` con `keepalive`. Se mantiene en el tipo para no
|
|
223
|
+
* romper a quien lo pase.
|
|
224
|
+
*/
|
|
225
|
+
sendBeaconImpl?: (url: string, body: Blob | string) => boolean;
|
|
226
|
+
/**
|
|
227
|
+
* Registro en el que seguir desde el primer lote: el de una sesión suspendida por un
|
|
228
|
+
* `pagehide` y reanudada tras recargar la página (ver `suspended-session.ts`).
|
|
229
|
+
*/
|
|
230
|
+
initialSessionId?: string;
|
|
231
|
+
/**
|
|
232
|
+
* Genera el sessionId de cada sesión (default: UUID v4). Inyectable para tests.
|
|
233
|
+
*/
|
|
234
|
+
newSessionId?: () => string;
|
|
235
|
+
/**
|
|
236
|
+
* Persistencia de los lotes pendientes (React Native: MMKV). Con él, el lote de cierre se
|
|
237
|
+
* guarda antes de enviarse y cualquier lote que falle sobrevive a que la app muera: el sink
|
|
238
|
+
* del arranque siguiente lo reenvía a su registro. Sin él, los pendientes viven en memoria.
|
|
239
|
+
*/
|
|
240
|
+
storage?: KeyValueStorage;
|
|
241
|
+
/** Reloj inyectable (tests). */
|
|
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;
|
|
249
|
+
/** Callback invocado cuando la API acepta el primer lote de una sesión (registro abierto). */
|
|
250
|
+
onSessionId?: (id: string) => void;
|
|
251
|
+
/** Callback invocado al cerrar la sesión (`completed:true`): el sessionId cacheado se olvida. */
|
|
252
|
+
onSessionReset?: () => void;
|
|
253
|
+
/**
|
|
254
|
+
* Callback invocado cuando el backend acepta el lote de cierre, con el sessionId del
|
|
255
|
+
* registro cerrado. Ese registro se convierte en Feedback en segundos.
|
|
256
|
+
*/
|
|
257
|
+
onSessionClosed?: (id: string) => void;
|
|
258
|
+
}
|
|
259
|
+
/**
|
|
260
|
+
* Sink real: transforma el envelope y hace `POST {baseUrl}/sdk/feedback`.
|
|
261
|
+
*
|
|
262
|
+
* El `sessionId` de cada sesión lo genera el SDK (UUID) y va en TODOS sus lotes, desde el
|
|
263
|
+
* primero. La API guarda cada lote bajo el sessionId que recibe, así que una sesión es un
|
|
264
|
+
* registro aunque no llegue ninguna respuesta. Antes lo asignaba la API en la respuesta del
|
|
265
|
+
* primer POST: si esa respuesta se perdía (la app pasaba a background con el POST en vuelo),
|
|
266
|
+
* el resto de la sesión acababa en otro registro.
|
|
267
|
+
*
|
|
268
|
+
* Garantías de entrega:
|
|
269
|
+
* - un lote que falla de forma transitoria (red, 5xx, 408, 429, sin respuesta en
|
|
270
|
+
* POST_TIMEOUT_MS) se guarda TAL CUAL —con su sessionId y su `completed`— y se reenvía
|
|
271
|
+
* antes del lote siguiente. Nunca vuelve al buffer del manager: allí se mezclaba con la
|
|
272
|
+
* sesión siguiente y viajaba con su registro. La promesa del sink no rechaza;
|
|
273
|
+
* - con `storage` (React Native) los pendientes sobreviven a que la app muera: el lote de
|
|
274
|
+
* cierre se guarda ANTES de enviarse y el sink del arranque siguiente lo reenvía. La API
|
|
275
|
+
* descarta los eventos repetidos de una misma sesión al ensamblarla;
|
|
276
|
+
* - `keepalive` para que el navegador no cancele el POST al navegar fuera ni al cerrar la
|
|
277
|
+
* página (sin `sendBeacon`: ver `sendBeaconImpl`);
|
|
278
|
+
* - sin credenciales, que es lo único que pasa el CORS de la API (`Allow-Origin: *`);
|
|
279
|
+
* - un 4xx se loguea y se descarta.
|
|
280
|
+
*/
|
|
281
|
+
declare function createFeedbackSink(options: FeedbackSinkOptions): AnalyticsSink;
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* Custom logger to receive the SDK's debug output instead of the console.
|
|
285
|
+
* Only `log` is required; `warn`/`error`/`info` fall back to `log` when omitted.
|
|
286
|
+
* Lets the host pipe debug output to a file, Firebase, etc. `console` satisfies this shape.
|
|
287
|
+
*/
|
|
288
|
+
interface DeepdotsLogger {
|
|
289
|
+
log: (...args: unknown[]) => void;
|
|
290
|
+
warn?: (...args: unknown[]) => void;
|
|
291
|
+
error?: (...args: unknown[]) => void;
|
|
292
|
+
info?: (...args: unknown[]) => void;
|
|
293
|
+
}
|
|
294
|
+
/**
|
|
295
|
+
* A session of the analytics channel as the Deepdots API sees it. Every session becomes ONE
|
|
296
|
+
* feedback, and `sessionId` is what the API stores as `sdkSessionId` on it: the value to look
|
|
297
|
+
* that feedback up with (`GET /feedbacks?filter={"where":{"sdkSessionId":"<sessionId>"}}`).
|
|
298
|
+
* A session that closes again keeps that one feedback: the API updates it.
|
|
299
|
+
* - `open`: the API acknowledged the session's first batch; its events keep accumulating.
|
|
300
|
+
* - `closed`: the API acknowledged the session's closing batch (`completed: true`); the
|
|
301
|
+
* feedback is created from it within seconds.
|
|
302
|
+
*/
|
|
303
|
+
interface FeedbackSession {
|
|
304
|
+
sessionId: string;
|
|
305
|
+
status: 'open' | 'closed';
|
|
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
|
+
/**
|
|
312
|
+
* Uncaught errors: `window` `error`/`unhandledrejection` (web), `ErrorUtils` and promise
|
|
313
|
+
* rejections without `catch` under Hermes (React Native). Default `true`. Handlers installed
|
|
314
|
+
* by other tools (Sentry, Crashlytics) keep receiving everything.
|
|
315
|
+
*/
|
|
316
|
+
errors?: boolean;
|
|
317
|
+
}
|
|
318
|
+
interface DeepdotsInitParams {
|
|
319
|
+
/** API key for authentication */
|
|
320
|
+
apiKey?: string;
|
|
321
|
+
/** Node environment: 'development' or 'production' */
|
|
322
|
+
nodeEnv?: 'development' | 'production';
|
|
323
|
+
/** Enable debug logging */
|
|
324
|
+
debug?: boolean;
|
|
325
|
+
/** Custom logger for debug output. When set (and `debug` is true), the SDK routes its logs here instead of `console`. Default: `console`. */
|
|
326
|
+
logger?: DeepdotsLogger;
|
|
327
|
+
/** Optional user id to send with popup events */
|
|
328
|
+
userId?: string;
|
|
329
|
+
/** Starts tracking enabled (default) or disabled (e.g. until consent is granted). Equivalent to calling `setTrackingEnabled` after init. */
|
|
330
|
+
trackingEnabled?: boolean;
|
|
331
|
+
/** Host app version (for analytics device info / Technology #11). */
|
|
332
|
+
appVersion?: string;
|
|
333
|
+
/** Injectable persistent storage (RN: adapter over AsyncStorage). If missing, uses localStorage/in-memory. */
|
|
334
|
+
storage?: KeyValueStorage;
|
|
335
|
+
/** Platform used in the analytics envelope. Default is 'web'; in RN pass 'android'/'ios'. */
|
|
336
|
+
platform?: 'web' | 'android' | 'ios';
|
|
337
|
+
/**
|
|
338
|
+
* BCP-47 language tag (e.g. 'es-ES') used for the analytics context AND for popup
|
|
339
|
+
* language segmentation (`segments.lang`). If omitted, the SDK auto-detects:
|
|
340
|
+
* `navigator.language` on web, or the `Intl` locale as a fallback (works in
|
|
341
|
+
* React Native with Hermes, where `navigator.language` is absent). If no source
|
|
342
|
+
* resolves a language, popups with `segments.lang` cannot be filtered and are shown.
|
|
343
|
+
*/
|
|
344
|
+
language?: string;
|
|
345
|
+
/** Injectable device info (RN: from react-native-device-info). If missing, it is derived from the browser. */
|
|
346
|
+
device?: DeviceInfo;
|
|
347
|
+
/**
|
|
348
|
+
* React Native (iOS): opens a native background task while each analytics request is in
|
|
349
|
+
* flight, so the session's closing request finishes after the app goes to background
|
|
350
|
+
* instead of when the user opens the app again. `begin(name)` starts the task and returns
|
|
351
|
+
* the function that ends it (iOS `beginBackgroundTask` / `endBackgroundTask`). The SDK ends
|
|
352
|
+
* it when the request settles, or after 25 s. Use `backgroundTimerTask(BackgroundTimer)`
|
|
353
|
+
* for `react-native-background-timer`, iOS only. Without it, nothing changes: a closing
|
|
354
|
+
* request that does not finish is stored and sent on the next launch.
|
|
355
|
+
*/
|
|
356
|
+
backgroundTask?: BackgroundTaskRunner;
|
|
357
|
+
/**
|
|
358
|
+
* What the SDK detects on its own. Everything is on by default; set a signal to `false` to
|
|
359
|
+
* turn it off. `lifecycle` (React Native): the SDK listens to `AppState` itself
|
|
360
|
+
* (`active` → session start, `inactive` → send pending data, `background` → session end), so
|
|
361
|
+
* the host does not need to call `onForeground` / `onInactive` / `onBackground`. Calling them
|
|
362
|
+
* as well is harmless: nothing is sent twice.
|
|
363
|
+
*/
|
|
364
|
+
autoTrack?: AutoTrackOptions;
|
|
365
|
+
/**
|
|
366
|
+
* Analytics channel keys (`POST /sdk/feedback`). If provided, analytics is SENT
|
|
367
|
+
* to the configured integration; if missing, it stays in dry-run mode: nothing is sent, and the payload is only
|
|
368
|
+
* logged when `debug` is true.
|
|
369
|
+
*/
|
|
370
|
+
analytics?: AnalyticsKeys;
|
|
371
|
+
/**
|
|
372
|
+
* Called when the analytics channel opens or closes a session (needs `analytics`), with the
|
|
373
|
+
* id the Deepdots API stores as `sdkSessionId` on the feedback the session becomes: send it
|
|
374
|
+
* to your backend to attach data to that feedback later. A session whose only batch is the
|
|
375
|
+
* closing one reports just `closed`. `closed` does not come when the page unloads before the
|
|
376
|
+
* closing request returns, for a session dropped after 30 min hidden, nor when the closing
|
|
377
|
+
* request fails (the API closes those itself, later): their id already came with `open`. Key
|
|
378
|
+
* by `sessionId`, not by order: the next session's `open` can arrive before the previous
|
|
379
|
+
* one's `closed`. Same value as `getFeedbackSessionId()` while the session is open.
|
|
380
|
+
*/
|
|
381
|
+
onFeedbackSession?: (session: FeedbackSession) => void;
|
|
382
|
+
/**
|
|
383
|
+
* IP geolocation (country/city) added to analytics. Default `true`. The lookup calls
|
|
384
|
+
* third-party services (ipapi.co, then ipwho.is, then ipinfo.io as fallbacks, 3 s timeout
|
|
385
|
+
* each) and only runs when `analytics` is configured, tracking is enabled and the 30-day
|
|
386
|
+
* cache is missing or expired. Set `false` to never call them nor attach country/city.
|
|
387
|
+
*/
|
|
388
|
+
geolocation?: boolean;
|
|
389
|
+
/**
|
|
390
|
+
* Internal user attributes known only by the host (language, age, plan, ...), sent
|
|
391
|
+
* to the backend Contact for segmentation/targeting. Requires `userId`. Equivalent to calling
|
|
392
|
+
* `setContactAttributes` after init (sends only when values changed from the last sync).
|
|
393
|
+
*/
|
|
394
|
+
contactAttributes?: Record<string, string | number | boolean>;
|
|
395
|
+
/**
|
|
396
|
+
* Whether the SDK renders the popup "modal" (card + backdrop + positioning) around the survey.
|
|
397
|
+
* Default `true`. Only affects React Native (the survey WebView HTML); the web DOM popup is
|
|
398
|
+
* unaffected. With `false` the survey is delivered transparent and edge-to-edge so the host
|
|
399
|
+
* mounts its own Modal/container and controls the styling — avoids the "double modal" when the
|
|
400
|
+
* host already wraps the WebView. The survey stays fully functional (bridge, form, nav buttons,
|
|
401
|
+
* close). Ver `ReactNativePopupRenderer`.
|
|
402
|
+
*/
|
|
403
|
+
renderChrome?: boolean;
|
|
404
|
+
/**
|
|
405
|
+
* Barra de progreso ("Question X of Y" + barra) en la cabecera del popup. Si se omite,
|
|
406
|
+
* manda el `showProgressBar` que la plataforma configura en el estilo del survey; `true` o
|
|
407
|
+
* `false` lo fuerzan desde el host. Solo se pinta con más de una página, fuera de la
|
|
408
|
+
* pantalla de inicio y antes de completar, igual que en la web de surveys.
|
|
409
|
+
*/
|
|
410
|
+
showProgressBar?: boolean;
|
|
411
|
+
/**
|
|
412
|
+
* CSS propio del host, inyectado como último bloque de estilos del popup: gana en cascada
|
|
413
|
+
* sobre el del SDK y sobre el de `@magicfeedback/native` sin tener que tocar ninguno. Es la
|
|
414
|
+
* vía para reestilar el área de preguntas (enunciados, opciones, escalas) por integración,
|
|
415
|
+
* en vez de cambiar los defaults que comparten todos los clientes.
|
|
416
|
+
*/
|
|
417
|
+
surveyCss?: string;
|
|
418
|
+
/**
|
|
419
|
+
* Nonce de la Content-Security-Policy de la página, para hosts con una CSP estricta
|
|
420
|
+
* (`style-src 'nonce-…'` sin `'unsafe-inline'`). El popup lo pone en cada `<style>` que
|
|
421
|
+
* inyecta en el `<head>` (hoja del survey, spinner, responsive, `surveyCss`, `@font-face`);
|
|
422
|
+
* sin él el navegador las bloquea y el survey sale sin estilos. Debe ser el MISMO nonce de
|
|
423
|
+
* la cabecera CSP de esa respuesta (en Angular, el token `CSP_NONCE`). Solo web: en React
|
|
424
|
+
* Native el survey vive en su propio WebView y no le afecta la CSP del host.
|
|
425
|
+
*/
|
|
426
|
+
cspNonce?: string;
|
|
427
|
+
}
|
|
428
|
+
interface DeepdotsConfig {
|
|
429
|
+
/** API key for authentication */
|
|
430
|
+
apiKey?: string;
|
|
431
|
+
/** Enable debug logging */
|
|
432
|
+
debug?: boolean;
|
|
433
|
+
/** Optional user id to send with popup events */
|
|
434
|
+
userId?: string;
|
|
435
|
+
}
|
|
436
|
+
/**
|
|
437
|
+
* Options for configuring survey triggers
|
|
438
|
+
*/
|
|
439
|
+
interface TriggerConfig {
|
|
440
|
+
/** Trigger type: 'time' (delay), 'scroll' (scroll percentage), 'exit' (route exit), 'click' (element id), 'event' (host event) */
|
|
441
|
+
type: 'time' | 'scroll' | 'exit' | 'click' | 'event';
|
|
442
|
+
/** Value for the trigger (milliseconds for time, percentage for scroll, seconds for exit, element id for click, event name for event) */
|
|
443
|
+
value?: number | string;
|
|
444
|
+
/** Survey ID to show when triggered */
|
|
445
|
+
surveyId: string;
|
|
446
|
+
/** Optional popup definition id (used to disambiguate repeated survey ids) */
|
|
447
|
+
popupId?: string;
|
|
448
|
+
/**
|
|
449
|
+
* Seconds to wait once the trigger fires before showing the popup ("Delay" in the Admin).
|
|
450
|
+
* For `exit` it is the wait on the next route. 0 or missing = at once.
|
|
451
|
+
*/
|
|
452
|
+
delaySeconds?: number;
|
|
453
|
+
}
|
|
454
|
+
/**
|
|
455
|
+
* Event types emitted by the SDK
|
|
456
|
+
*/
|
|
457
|
+
type DeepdotsEventType = 'popup_shown' | 'popup_clicked' | 'survey_completed'
|
|
458
|
+
/**
|
|
459
|
+
* Fallo al enviar una página del survey (el popup enseña `errorSubmit`). `data`:
|
|
460
|
+
* `{reason: 'send_failed' | 'no_page' | 'unknown', message}`. No es interacción del
|
|
461
|
+
* usuario: no marca el popup como PARTIAL. También va a analítica como `deepdots_survey_error`.
|
|
462
|
+
*/
|
|
463
|
+
| 'survey_error';
|
|
464
|
+
/**
|
|
465
|
+
* Event payload structure
|
|
466
|
+
*/
|
|
467
|
+
interface DeepdotsEvent {
|
|
468
|
+
type: DeepdotsEventType;
|
|
469
|
+
surveyId: string;
|
|
470
|
+
timestamp: number;
|
|
471
|
+
data?: Record<string, unknown>;
|
|
472
|
+
}
|
|
473
|
+
/**
|
|
474
|
+
* Event listener callback
|
|
475
|
+
*/
|
|
476
|
+
type EventListener = (event: DeepdotsEvent) => void;
|
|
477
|
+
/**
|
|
478
|
+
* Motivo del `deepdots_session_end` (último lote de la sesión, enviado con `completed:true`):
|
|
479
|
+
* - `page_hide`: la página web se cierra o se navega fuera (`pagehide`).
|
|
480
|
+
* - `background`: la app pasa a background (RN/nativo). Única señal disponible en móvil:
|
|
481
|
+
* el kill de la app por el usuario o el SO NO produce ningún callback.
|
|
482
|
+
* - `user_change`: `setUserId()` o un `init()` con otro `userId` (login/logout del host).
|
|
483
|
+
* - `tracking_disabled`: `setTrackingEnabled(false)` (consentimiento revocado).
|
|
484
|
+
* - `manual`: `endSession()` llamado por el host.
|
|
485
|
+
* - `idle_timeout`: la pestaña vuelve a verse tras más de 30 min oculta (web). La sesión
|
|
486
|
+
* anterior se cierra y se abre otra, como hace GA con su timeout de sesión.
|
|
487
|
+
*/
|
|
488
|
+
type SessionEndReason = 'page_hide' | 'background' | 'user_change' | 'tracking_disabled' | 'manual' | 'idle_timeout';
|
|
489
|
+
/**
|
|
490
|
+
* Motivo del `deepdots_session_start` (param `reason`): por qué EMPIEZA la sesión. Permite a
|
|
491
|
+
* analytics separar una carga/arranque real de una vuelta desde background ("Started here").
|
|
492
|
+
* Mismos valores que el SDK nativo donde el significado coincide:
|
|
493
|
+
* - `cold_start`: `init()` (carga de la página / arranque de la app RN) sin sesión suspendida
|
|
494
|
+
* que reanudar. Una recarga en menos de 1 min no emite `session_start` sino
|
|
495
|
+
* `deepdots_session_resume`.
|
|
496
|
+
* - `foreground`: `onForeground()` (RN, AppState 'active') tras un cierre (`onBackground()`
|
|
497
|
+
* o `endSession()`). Con la sesión abierta no emite nada.
|
|
498
|
+
* - `tracking_enabled`: `setTrackingEnabled(true)` (consentimiento concedido).
|
|
499
|
+
* - `user_change`: `setUserId()` o un `init()` con otro `userId`, tras cerrar la del anterior.
|
|
500
|
+
* - `idle_timeout`: la pestaña vuelve a verse tras más de 30 min oculta (web): la sesión
|
|
501
|
+
* anterior se cerró (o se descartó) y empieza otra.
|
|
502
|
+
* - `bfcache_restore`: la página vuelve de la bfcache (botón atrás, `pageshow` con
|
|
503
|
+
* `persisted`) fuera de la ventana de reanudación (web).
|
|
504
|
+
*/
|
|
505
|
+
type SessionStartReason = 'cold_start' | 'foreground' | 'tracking_enabled' | 'user_change' | 'idle_timeout' | 'bfcache_restore';
|
|
506
|
+
/** Trigger type used by remote popup definitions */
|
|
507
|
+
type PopupTriggerType = 'time_on_page' | 'scroll' | 'exit' | 'click' | 'event';
|
|
508
|
+
type PopupTriggerConditionStatus = 'SHOWED' | 'PARTIAL' | 'COMPLETED';
|
|
509
|
+
declare const POPUP_TRIGGER_CONDITION_STATUSES: PopupTriggerConditionStatus[];
|
|
510
|
+
/** Extra condition used to activate the popup */
|
|
511
|
+
interface PopupTriggerCondition {
|
|
512
|
+
answered: PopupTriggerConditionStatus;
|
|
513
|
+
cooldownDays: number;
|
|
514
|
+
}
|
|
515
|
+
/** Trigger attached to the popup definition */
|
|
516
|
+
interface PopupTrigger {
|
|
517
|
+
type: PopupTriggerType;
|
|
518
|
+
value: number | string;
|
|
519
|
+
/**
|
|
520
|
+
* "Delay (seconds)" in the Admin: wait this long after the trigger fires before showing the
|
|
521
|
+
* popup. 0 or missing = at once. For `exit` the Admin stores the delay here and `value` is 0.
|
|
522
|
+
*/
|
|
523
|
+
delaySeconds?: number;
|
|
524
|
+
}
|
|
525
|
+
/** Accept action (open survey) */
|
|
526
|
+
interface PopupActionAccept {
|
|
527
|
+
label: string;
|
|
528
|
+
surveyId: string;
|
|
529
|
+
}
|
|
530
|
+
/** Decline action */
|
|
531
|
+
interface PopupActionDecline {
|
|
532
|
+
label: string;
|
|
533
|
+
cooldownDays?: number;
|
|
534
|
+
}
|
|
535
|
+
/** Start Surveys Action */
|
|
536
|
+
interface PopupActionStart {
|
|
537
|
+
label: string;
|
|
538
|
+
}
|
|
539
|
+
/** Complete action (accept and auto-complete survey) */
|
|
540
|
+
interface PopupActionComplete {
|
|
541
|
+
label: string;
|
|
542
|
+
surveyId: string;
|
|
543
|
+
autoCompleteParams: Record<string, unknown>;
|
|
544
|
+
cooldownDays?: number;
|
|
545
|
+
}
|
|
546
|
+
/** Set of actions available in the popup */
|
|
547
|
+
interface PopupActions {
|
|
548
|
+
accept?: PopupActionAccept;
|
|
549
|
+
decline?: PopupActionDecline;
|
|
550
|
+
complete?: PopupActionComplete;
|
|
551
|
+
start?: PopupActionStart;
|
|
552
|
+
back?: PopupActionDecline;
|
|
553
|
+
}
|
|
554
|
+
/** Fuente personalizable del popup + survey (viene de la API por popup) */
|
|
555
|
+
interface PopupFont {
|
|
556
|
+
/** Nombre de la familia. Ej: "Inter" (nombre limpio, NO un stack). */
|
|
557
|
+
family: string;
|
|
558
|
+
/** Opcional: URL a un archivo de fuente (woff2/ttf/otf) para armar un @font-face. */
|
|
559
|
+
url?: string;
|
|
560
|
+
}
|
|
561
|
+
/** Configurable popup styles */
|
|
562
|
+
interface PopupStyle {
|
|
563
|
+
theme: 'light' | 'dark';
|
|
564
|
+
position: 'bottom' | 'bottom-right' | 'bottom-left' | 'top' | 'top-right' | 'top-left' | 'center';
|
|
565
|
+
/** @deprecated Not used by the SDK; kept only for API compatibility */
|
|
566
|
+
imageUrl?: string | null;
|
|
567
|
+
/** Fuente personalizada. Si falta, se mantiene el comportamiento actual. */
|
|
568
|
+
font?: PopupFont;
|
|
569
|
+
}
|
|
570
|
+
/** Segments/targeting rules for showing the popup */
|
|
571
|
+
interface PopupSegments {
|
|
572
|
+
lang?: string[];
|
|
573
|
+
path?: string[];
|
|
574
|
+
/**
|
|
575
|
+
* App routes where it must NOT be shown. Wins over `path`: a route listed here
|
|
576
|
+
* blocks the popup even if `path` matches it (so `path: ['/']` +
|
|
577
|
+
* `excludedPaths: ['/cart']` = everywhere but the cart).
|
|
578
|
+
* Same matching rules as `path`: an absolute URL matches the full href, an entry
|
|
579
|
+
* starting with `/` matches any href containing it (this is what covers hash
|
|
580
|
+
* routes like `/#/cart`), anything else matches the pathname exactly.
|
|
581
|
+
*/
|
|
582
|
+
excludedPaths?: string[];
|
|
583
|
+
[key: string]: unknown;
|
|
584
|
+
}
|
|
585
|
+
/** Full popup definition */
|
|
586
|
+
interface PopupDefinition {
|
|
587
|
+
id: string;
|
|
588
|
+
title: string;
|
|
589
|
+
message: string;
|
|
590
|
+
triggers: PopupTrigger[];
|
|
591
|
+
cooldown?: PopupTriggerCondition[];
|
|
592
|
+
actions?: PopupActions;
|
|
593
|
+
surveyId: string;
|
|
594
|
+
productId: string;
|
|
595
|
+
style?: PopupStyle;
|
|
596
|
+
segments?: PopupSegments;
|
|
597
|
+
/**
|
|
598
|
+
* Versión del survey asignada en el Admin (latest o fijada) y su survey SDK (DD-70). La manda
|
|
599
|
+
* la API desde DD-70; con APIs anteriores falta y se usa el survey SDK empaquetado.
|
|
600
|
+
*/
|
|
601
|
+
surveyFrontend?: PopupSurveyFrontend | null;
|
|
602
|
+
}
|
|
603
|
+
/** `surveyFrontend` de `GET /sdk/{publicKey}/popups` (DD-70). */
|
|
604
|
+
interface PopupSurveyFrontend {
|
|
605
|
+
/** Versión de MagicSurvey resuelta (X.Y.Z). */
|
|
606
|
+
version?: string;
|
|
607
|
+
/** "latest" o la X.Y.Z fijada. */
|
|
608
|
+
preference?: string;
|
|
609
|
+
status?: string;
|
|
610
|
+
/** `@magicfeedback/native` con el que se construyó esa versión; null si no se conoce. */
|
|
611
|
+
sdkVersion?: string | null;
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
/**
|
|
615
|
+
* Ajustes de presentación que no vienen del estilo del popup. Van agrupados para no seguir
|
|
616
|
+
* alargando la lista posicional de `show`, que ya arrastra doce parámetros.
|
|
617
|
+
*/
|
|
618
|
+
interface PopupRenderOptions {
|
|
619
|
+
/**
|
|
620
|
+
* Título de la cabecera: el `title` de la definición del popup, tal cual llega de la API.
|
|
621
|
+
* Varía por popup y vacío es un valor válido (la cabecera se queda solo con la X).
|
|
622
|
+
*/
|
|
623
|
+
title?: string;
|
|
624
|
+
/** Barra de progreso: `undefined` deja decidir a la plataforma, `true`/`false` la fuerzan. */
|
|
625
|
+
showProgressBar?: boolean;
|
|
626
|
+
/** CSS del host, inyectado el último: gana sobre el del SDK y el de `@magicfeedback/native`. */
|
|
627
|
+
surveyCss?: string;
|
|
628
|
+
/**
|
|
629
|
+
* Idioma con el que arranca el chrome del popup (botones, progreso, aria-labels, errores).
|
|
630
|
+
* Es el idioma resuelto en `init()` (host > navigator > Intl). Lo pisa el idioma del survey
|
|
631
|
+
* (`formData.lang[0]`) en cuanto este carga, y ambos los pisa `actions.*.label` de la API.
|
|
632
|
+
*/
|
|
633
|
+
language?: string;
|
|
634
|
+
/**
|
|
635
|
+
* Nonce de la Content-Security-Policy del host (`DeepdotsInitParams.cspNonce`). Se pone en
|
|
636
|
+
* cada `<style>` que inyecta el popup DOM; sin él, una CSP con `style-src 'nonce-…'` bloquea
|
|
637
|
+
* la hoja del survey. No aplica a React Native (el survey vive en su propio WebView).
|
|
638
|
+
*/
|
|
639
|
+
cspNonce?: string;
|
|
640
|
+
/**
|
|
641
|
+
* `surveyFrontend.sdkVersion` del popup (DD-70): versión de `@magicfeedback/native` asignada
|
|
642
|
+
* al survey en el Admin. Se usa si está en el rango soportado y carga; si no, la empaquetada.
|
|
643
|
+
*/
|
|
644
|
+
surveySdkVersion?: string | null;
|
|
645
|
+
/** `init({debug})`, para el log de la versión de survey SDK elegida. */
|
|
646
|
+
debug?: boolean;
|
|
647
|
+
}
|
|
648
|
+
interface PopupRenderer {
|
|
649
|
+
/** Preparar recursos si aplica */
|
|
650
|
+
init?(): void;
|
|
651
|
+
/**
|
|
652
|
+
* Traer por adelantado lo que la apertura necesitará, en idle. Opcional: solo lo implementan
|
|
653
|
+
* los renderers cuyo coste de apertura se paga delante del usuario.
|
|
654
|
+
*/
|
|
655
|
+
preload?(): void;
|
|
656
|
+
/** Mostrar popup */
|
|
657
|
+
show(surveyId: string, productId: string, actions: PopupActions | undefined, emit: (type: DeepdotsEventType, surveyId: string, data?: Record<string, unknown>) => void, onClose: () => void, env?: string, userId?: string, style?: PopupStyle, sessionId?: string, miniService?: string, analyticsFeedbackSessionId?: string, renderChrome?: boolean, options?: PopupRenderOptions): void;
|
|
658
|
+
/** Ocultar popup */
|
|
659
|
+
hide(): void;
|
|
660
|
+
/**
|
|
661
|
+
* ¿Hay un popup a la vista ahora mismo? Opcional. Con él, el core no da por mostrado un popup
|
|
662
|
+
* que el renderer no va a pintar (porque ya hay otro abierto): ni `popup_shown`, ni SHOWED, ni
|
|
663
|
+
* cooldown gastado. Sin él (renderers del host, RN), el core se comporta como siempre.
|
|
664
|
+
*/
|
|
665
|
+
isShowing?(): boolean;
|
|
666
|
+
}
|
|
667
|
+
/** Renderer que no hace nada (SSR / entornos sin DOM) */
|
|
668
|
+
declare class NoopPopupRenderer implements PopupRenderer {
|
|
669
|
+
show(): void;
|
|
670
|
+
hide(): void;
|
|
671
|
+
}
|
|
672
|
+
/** Renderer para navegadores usando la implementación actual basada en renderPopup */
|
|
673
|
+
declare class BrowserPopupRenderer implements PopupRenderer {
|
|
674
|
+
private container;
|
|
675
|
+
private visible;
|
|
676
|
+
init(): void;
|
|
677
|
+
/**
|
|
678
|
+
* Descarga el chunk de `renderPopup` antes de que ningún trigger dispare, para que abrir el
|
|
679
|
+
* popup no empiece por esperar ~238 KB de JS.
|
|
680
|
+
*/
|
|
681
|
+
preload(): void;
|
|
682
|
+
show(surveyId: string, productId: string, actions: PopupActions | undefined, emit: (type: DeepdotsEventType, surveyId: string, data?: Record<string, unknown>) => void, onClose: () => void, env?: string, userId?: string, style?: PopupStyle, sessionId?: string, miniService?: string, analyticsFeedbackSessionId?: string, _renderChrome?: boolean, // solo aplica a RN (WebView); el popup DOM web siempre lleva su chrome
|
|
683
|
+
options?: PopupRenderOptions): void;
|
|
684
|
+
isShowing(): boolean;
|
|
685
|
+
hide(): void;
|
|
686
|
+
}
|
|
687
|
+
/** Factoría para obtener renderer por defecto */
|
|
688
|
+
declare function createDefaultRenderer(): PopupRenderer;
|
|
689
|
+
|
|
690
|
+
/** Valor de un atributo de contact (info interna del usuario que solo conoce el host). */
|
|
691
|
+
type ContactAttributeValue = string | number | boolean;
|
|
692
|
+
type ContactAttributes = Record<string, ContactAttributeValue>;
|
|
693
|
+
/** Body de `POST /sdk/popups/contact`. */
|
|
694
|
+
interface ContactBody {
|
|
695
|
+
publicKey: string;
|
|
696
|
+
userId: string;
|
|
697
|
+
userAttributes: ContactAttributes;
|
|
698
|
+
}
|
|
699
|
+
interface ContactManagerOptions {
|
|
700
|
+
storage: KeyValueStorage;
|
|
701
|
+
publicKey: string;
|
|
702
|
+
userId: string;
|
|
703
|
+
/**
|
|
704
|
+
* Envío real (inyectable para tests): hace el `POST /sdk/popups/contact`. Tiene que
|
|
705
|
+
* RECHAZAR si la API no acepta el envío (sin red o respuesta no-2xx): solo así se sabe
|
|
706
|
+
* que no hay que guardar la caché y que la llamada siguiente debe reintentar.
|
|
707
|
+
*/
|
|
708
|
+
post: (body: ContactBody) => Promise<void>;
|
|
709
|
+
}
|
|
710
|
+
/**
|
|
711
|
+
* Gestiona los atributos de contact del usuario identificado (`userId` del init).
|
|
712
|
+
* Solo envía cuando cambian respecto a lo último persistido en storage, para ahorrar
|
|
713
|
+
* peticiones (el host puede llamar `setAttributes` en cada identificación sin miedo).
|
|
714
|
+
*/
|
|
715
|
+
declare class ContactManager {
|
|
716
|
+
private readonly storage;
|
|
717
|
+
private readonly publicKey;
|
|
718
|
+
private readonly userId;
|
|
719
|
+
private readonly post;
|
|
720
|
+
constructor(options: ContactManagerOptions);
|
|
721
|
+
/**
|
|
722
|
+
* Envía los atributos si cambiaron respecto a lo último enviado. La caché solo se guarda
|
|
723
|
+
* cuando la API acepta el envío; si falla, la llamada siguiente reintenta. Nunca rechaza.
|
|
724
|
+
* @returns `true` si se envió, `false` si no hubo cambios o el envío falló.
|
|
725
|
+
*/
|
|
726
|
+
setAttributes(attributes: ContactAttributes): Promise<boolean>;
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
/**
|
|
730
|
+
* Crash & error reporting (Stability #14–17) — captura de errores GESTIONADOS.
|
|
731
|
+
*
|
|
732
|
+
* - `reportError()`: API pública para el host (app viva) → emite `deepdots_app_crash` ya.
|
|
733
|
+
* - handlers de `window` (errores no capturados): persisten a disco y se reenvían
|
|
734
|
+
* en el siguiente arranque (el proceso puede morir antes del flush normal).
|
|
735
|
+
*
|
|
736
|
+
* El contexto de device/sesión se captura EN EL MOMENTO del crash y se guarda en el
|
|
737
|
+
* record — no se lee del envelope en el replay (el replay puede ocurrir en otra
|
|
738
|
+
* app_version/OS). Las dims OS/device en Web suelen ir vacías (se derivan del UA en backend).
|
|
739
|
+
*/
|
|
740
|
+
|
|
741
|
+
type CrashSeverity = 'fatal' | 'error' | 'warning';
|
|
742
|
+
interface CrashRecord {
|
|
743
|
+
crashedAt: number;
|
|
744
|
+
crashType: string;
|
|
745
|
+
message: string;
|
|
746
|
+
stack: string;
|
|
747
|
+
fatal: boolean;
|
|
748
|
+
handled: boolean;
|
|
749
|
+
severity: CrashSeverity;
|
|
750
|
+
sessionId: string | null;
|
|
751
|
+
appVersion?: string;
|
|
752
|
+
osVersion?: string;
|
|
753
|
+
deviceModel?: string;
|
|
754
|
+
context?: Record<string, string>;
|
|
755
|
+
}
|
|
756
|
+
interface ReportErrorOptions {
|
|
757
|
+
severity?: CrashSeverity;
|
|
758
|
+
handled?: boolean;
|
|
759
|
+
context?: Record<string, unknown>;
|
|
760
|
+
}
|
|
761
|
+
interface DeviceSnapshot {
|
|
762
|
+
appVersion?: string;
|
|
763
|
+
osVersion?: string;
|
|
764
|
+
deviceModel?: string;
|
|
765
|
+
}
|
|
766
|
+
/** Forma mínima de `global.ErrorUtils` de React Native. */
|
|
767
|
+
interface ReactNativeErrorUtils {
|
|
768
|
+
getGlobalHandler?(): ((error: unknown, isFatal?: boolean) => void) | undefined;
|
|
769
|
+
setGlobalHandler(handler: (error: unknown, isFatal?: boolean) => void): void;
|
|
770
|
+
}
|
|
771
|
+
/** Fuente de promesas rechazadas sin `catch` (en RN, el hub del tracker de Hermes). */
|
|
772
|
+
interface UnhandledRejectionSource {
|
|
773
|
+
addUnhandledListener(listener: (error: unknown) => void): () => void;
|
|
774
|
+
}
|
|
775
|
+
interface CrashReporterOptions {
|
|
776
|
+
storage: KeyValueStorage;
|
|
777
|
+
/** Emite un evento deepdots_app_crash AHORA (app viva). */
|
|
778
|
+
emit: (params: Record<string, unknown>) => void;
|
|
779
|
+
/** Snapshot de device en el momento del crash. */
|
|
780
|
+
device: () => DeviceSnapshot;
|
|
781
|
+
/** session_id en el momento del crash. */
|
|
782
|
+
sessionId: () => string | null;
|
|
783
|
+
now?: () => number;
|
|
784
|
+
/** Kill-switch de consentimiento. */
|
|
785
|
+
enabled?: () => boolean;
|
|
786
|
+
}
|
|
787
|
+
/** Convierte un CrashRecord en los params del evento `deepdots_app_crash` (omite undefined). */
|
|
788
|
+
declare function crashRecordToParams(r: CrashRecord): Record<string, unknown>;
|
|
789
|
+
declare class CrashReporter {
|
|
790
|
+
private options;
|
|
791
|
+
private now;
|
|
792
|
+
/** Los handlers de `window` ya están puestos: `install()` es idempotente. */
|
|
793
|
+
private windowInstalled;
|
|
794
|
+
/** ErrorUtils ya enganchados: engancharlos dos veces capturaría cada error dos veces. */
|
|
795
|
+
private hookedErrorUtils;
|
|
796
|
+
/** Fuentes de rejections ya enganchadas (idempotente, como ErrorUtils). */
|
|
797
|
+
private hookedRejections;
|
|
798
|
+
constructor(options: CrashReporterOptions);
|
|
799
|
+
private isEnabled;
|
|
800
|
+
/** Construye un CrashRecord capturando contexto en el momento del crash. */
|
|
801
|
+
private buildRecord;
|
|
802
|
+
/** API pública del host: reporta un error (app viva) → emite el evento ya. */
|
|
803
|
+
reportError(error: unknown, options?: ReportErrorOptions): void;
|
|
804
|
+
/** Captura un error no manejado (fatal) → persiste a disco para replay en el siguiente arranque. */
|
|
805
|
+
captureUnhandled(error: unknown): void;
|
|
806
|
+
/** Persiste un crash no capturado a disco para reenviarlo en el siguiente arranque. */
|
|
807
|
+
private persist;
|
|
808
|
+
/** Lee y vacía la cola de crashes pendientes (llamado en init para el replay). */
|
|
809
|
+
drainPendingCrashes(): CrashRecord[];
|
|
810
|
+
/** Instala los handlers globales de errores no capturados (no-op sin `window`). Idempotente. */
|
|
811
|
+
install(): void;
|
|
812
|
+
/** Engancha `global.ErrorUtils` de RN (no hay `window`): persiste y encadena al handler previo. Idempotente por instancia de ErrorUtils. */
|
|
813
|
+
installReactNative(errorUtils: ReactNativeErrorUtils): void;
|
|
814
|
+
/**
|
|
815
|
+
* Promesas rechazadas sin `catch` en React Native: como el `unhandledrejection` de web, se
|
|
816
|
+
* persisten y se reenvían en el arranque siguiente. La fuente encadena al tracker del host.
|
|
817
|
+
* Idempotente por fuente.
|
|
818
|
+
*/
|
|
819
|
+
installPromiseRejections(source: UnhandledRejectionSource): void;
|
|
820
|
+
/** @internal Test seam: ejercita el camino de persistencia (window handlers no son testeables en vitest). */
|
|
821
|
+
_persistForTest(error: unknown): void;
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
/**
|
|
825
|
+
* Messaging (#18–22): tracking de notificaciones del host (push / in-app).
|
|
826
|
+
* Un único evento reservado `deepdots_message` con un campo `stage` discriminador;
|
|
827
|
+
* el funnel se correlaciona por `message_id` y se agrupa por `message_title`.
|
|
828
|
+
*/
|
|
829
|
+
type MessageStage = 'delivered' | 'clicked' | 'converted';
|
|
830
|
+
/** Canales válidos. Un mensaje tiene UN canal: se valida en runtime porque el host puede no ser TS. */
|
|
831
|
+
declare const MESSAGE_CHANNELS: readonly ["push", "in_app"];
|
|
832
|
+
type MessageChannel = (typeof MESSAGE_CHANNELS)[number];
|
|
833
|
+
interface TrackMessageOptions {
|
|
834
|
+
/** Identificador del mensaje/notificación — correlaciona el funnel delivered→clicked→converted. */
|
|
835
|
+
id: string;
|
|
836
|
+
/** Título del mensaje — dimensión de agrupación de #18–22. */
|
|
837
|
+
title: string;
|
|
838
|
+
/** Canal de entrega. */
|
|
839
|
+
channel: MessageChannel;
|
|
840
|
+
/** Nombre de la campaña (opcional). */
|
|
841
|
+
campaign?: string;
|
|
842
|
+
/** Valor de conversión (opcional, típico en `stage: 'converted'`). */
|
|
843
|
+
value?: number;
|
|
844
|
+
currency?: string;
|
|
845
|
+
/** Parámetros libres adicionales. */
|
|
846
|
+
params?: Record<string, unknown>;
|
|
847
|
+
}
|
|
848
|
+
/** Construye los params del evento `deepdots_message` (omite opcionales ausentes). */
|
|
849
|
+
declare function buildMessageParams(stage: MessageStage, o: TrackMessageOptions): Record<string, unknown>;
|
|
850
|
+
/** Techo de `message_id` vigilados por sesión; los más antiguos se evictan (memoria acotada). */
|
|
851
|
+
declare const MAX_TRACKED_MESSAGES = 500;
|
|
852
|
+
type MessageRejectionReason = 'invalid_channel' | 'duplicate_stage' | 'channel_conflict';
|
|
853
|
+
type MessageGuardVerdict = {
|
|
854
|
+
emit: true;
|
|
855
|
+
} | {
|
|
856
|
+
emit: false;
|
|
857
|
+
reason: MessageRejectionReason;
|
|
858
|
+
detail: string;
|
|
859
|
+
};
|
|
860
|
+
/**
|
|
861
|
+
* Protege el funnel de Messaging de las formas imposibles que el host puede producir por error
|
|
862
|
+
* (visto en producción: CTR > 100% por falta de `delivered` + el mismo `message_id` reportado en
|
|
863
|
+
* dos canales). Tres reglas, todas dentro de la sesión (se reinicia en cada `init()`):
|
|
864
|
+
*
|
|
865
|
+
* 1. `channel` fuera de `MESSAGE_CHANNELS` → se descarta el evento.
|
|
866
|
+
* 2. Un `(message_id, stage)` ya emitido → se emite una sola vez.
|
|
867
|
+
* 3. Un `message_id` ya visto en un canal → se descartan los eventos de otro canal.
|
|
868
|
+
*
|
|
869
|
+
* Los eventos rechazados NO mutan el estado: un rechazo nunca "consume" el stage bueno.
|
|
870
|
+
* Lo que el SDK no puede arreglar es la ausencia de `delivered`: eso lo instrumenta el host.
|
|
871
|
+
*/
|
|
872
|
+
declare class MessageGuard {
|
|
873
|
+
private maxTrackedMessages;
|
|
874
|
+
/** message_id → canal fijado + stages ya emitidos. El orden de inserción marca la eviction. */
|
|
875
|
+
private seen;
|
|
876
|
+
constructor(maxTrackedMessages?: number);
|
|
877
|
+
evaluate(stage: MessageStage, options: TrackMessageOptions): MessageGuardVerdict;
|
|
878
|
+
/** Olvida todo lo vigilado (nueva sesión). */
|
|
879
|
+
reset(): void;
|
|
880
|
+
private remember;
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
/**
|
|
884
|
+
* Main class for managing survey popups
|
|
885
|
+
*/
|
|
886
|
+
declare class DeepdotsPopups {
|
|
887
|
+
private config;
|
|
888
|
+
private listeners;
|
|
889
|
+
private triggers;
|
|
890
|
+
private initialized;
|
|
891
|
+
private renderer;
|
|
892
|
+
/** Logger para el output de debug. Default `console`; el host puede inyectar el suyo en init(). */
|
|
893
|
+
private logger;
|
|
894
|
+
private popupDefinitions;
|
|
895
|
+
private popupsLoaded;
|
|
896
|
+
/**
|
|
897
|
+
* `true` mientras el `GET /sdk/{apiKey}/popups` de `init()` está en vuelo. En esa ventana los
|
|
898
|
+
* disparos del host (`triggerEvent`, `triggerSurvey`) no tienen contra qué evaluarse, así que
|
|
899
|
+
* se guardan en `pendingTriggers` y se reproducen al cargar. Click, scroll, time y exit no
|
|
900
|
+
* hacen falta: son listeners que `autoLaunch` instala ya con las definiciones cargadas.
|
|
901
|
+
*/
|
|
902
|
+
private awaitingPopups;
|
|
903
|
+
private pendingTriggers;
|
|
904
|
+
private pendingAutoLaunch;
|
|
905
|
+
private answeredSurveys;
|
|
906
|
+
private surveyProgress;
|
|
907
|
+
private lastShown;
|
|
908
|
+
private surveyToPopupId;
|
|
909
|
+
private deferredExitTimers;
|
|
910
|
+
/** Popups esperando su `delaySeconds` (uno por popup). */
|
|
911
|
+
private delayedPopups;
|
|
912
|
+
/** Última pantalla de `setScreen` (React Native). */
|
|
913
|
+
private currentScreen;
|
|
914
|
+
private baseUrl;
|
|
915
|
+
private env;
|
|
916
|
+
/** Si el SDK pinta el "modal" del popup (RN). Default true; false = el host lo envuelve. */
|
|
917
|
+
private renderChrome;
|
|
918
|
+
/** Barra de progreso. undefined = la decide la plataforma (style.showProgressBar). */
|
|
919
|
+
private showProgressBar;
|
|
920
|
+
/** CSS del host inyectado al final de los estilos del popup. */
|
|
921
|
+
private surveyCss;
|
|
922
|
+
private cspNonce;
|
|
923
|
+
/** Identidad + sesión (Fase 1 tracking). Null hasta init(). */
|
|
924
|
+
private tracking;
|
|
925
|
+
/** Capa de analytics (canal separado del feedback). Null hasta init(). */
|
|
926
|
+
private analytics;
|
|
927
|
+
/** feedbackSessionId cacheado del canal de analytics (devuelto por POST /sdk/feedback). */
|
|
928
|
+
private analyticsFeedbackSessionId;
|
|
929
|
+
/** `init({ onFeedbackSession })`: avisa al host al abrir y cerrar cada registro. */
|
|
930
|
+
private onFeedbackSession;
|
|
931
|
+
/** Timer del flush periódico de analytics (cada ANALYTICS_FLUSH_INTERVAL_MS). */
|
|
932
|
+
private analyticsFlushTimer;
|
|
933
|
+
/** Crash & error reporting (#14–17). Null hasta init(). */
|
|
934
|
+
private crashReporter;
|
|
935
|
+
/** ErrorUtils de RN recibido del host (o del Provider); se engancha en cuanto haya consentimiento. */
|
|
936
|
+
private rnErrorUtils;
|
|
937
|
+
/** Protecciones del funnel de Messaging (#18–22). Vigencia de sesión: se reinicia en init(). */
|
|
938
|
+
private messageGuard;
|
|
939
|
+
/** Observador de navegación (Fase 2): emite page_view por el canal de analytics. */
|
|
940
|
+
private navObserver;
|
|
941
|
+
/** Tiempo activo (engagement time, #8). */
|
|
942
|
+
private engagement;
|
|
943
|
+
/** Atributos internos del usuario identificado → POST /sdk/popups/contact. Null si no hay userId. */
|
|
944
|
+
private contact;
|
|
945
|
+
/** Storage resuelto en init() (inyectado por el host o localStorage). Reusado al cambiar de usuario. */
|
|
946
|
+
private storage;
|
|
947
|
+
/** Marca si ya se inició la navegación manual (setScreen) — para RN sin History API. */
|
|
948
|
+
private navStarted;
|
|
949
|
+
/**
|
|
950
|
+
* `true` entre `session_start` y `session_end`. Hace idempotente tanto la apertura como
|
|
951
|
+
* el cierre (p. ej. `visibilitychange` + `pagehide` seguidos) y permite abrir una sesión
|
|
952
|
+
* nueva al volver a foreground o al conceder el consentimiento más tarde.
|
|
953
|
+
*/
|
|
954
|
+
private sessionOpen;
|
|
955
|
+
/** Último `user_engagement` emitido (ms epoch): marca el latido. */
|
|
956
|
+
private lastEngagementAt;
|
|
957
|
+
/** Cuándo se ocultó la pestaña por última vez (ms epoch); null si está visible. */
|
|
958
|
+
private hiddenAt;
|
|
959
|
+
/** `init({ autoTrack: { errors } })`: captura automática de errores. Activa por defecto. */
|
|
960
|
+
private autoTrackErrors;
|
|
961
|
+
/** Suscripción automática a AppState (React Native, `autoTrack.lifecycle`). */
|
|
962
|
+
private appStateSubscription;
|
|
963
|
+
/**
|
|
964
|
+
* Sesión suspendida por un `pagehide` (ms epoch y `deepdots_user_id`); null si no hay.
|
|
965
|
+
* `openSession` la reanuda si sigue a tiempo (ver ANALYTICS_RESUME_WINDOW_MS).
|
|
966
|
+
*/
|
|
967
|
+
private suspended;
|
|
968
|
+
/** Integración de analytics del init: la sesión suspendida solo la hereda la misma. */
|
|
969
|
+
private analyticsIntegration;
|
|
970
|
+
/**
|
|
971
|
+
* Idioma resuelto en init() (explícito > navigator.language > Intl). Única fuente de
|
|
972
|
+
* verdad para el context de analytics Y para la segmentación por idioma de los popups.
|
|
973
|
+
*/
|
|
974
|
+
private language;
|
|
975
|
+
/** `geolocation` del init: si es false no se usa ni la caché ni el lookup. */
|
|
976
|
+
private geoEnabled;
|
|
977
|
+
/** Solo se consulta a terceros si el país/ciudad se va a enviar (analytics configurado). */
|
|
978
|
+
private geoWanted;
|
|
979
|
+
/** Evita más de un lookup por instancia (el consentimiento puede ir y venir). */
|
|
980
|
+
private geoLookupStarted;
|
|
981
|
+
/** Initialize the SDK with configuration */
|
|
982
|
+
init(config: DeepdotsInitParams): void;
|
|
983
|
+
/** User id actual (generado por el SDK o provisto por el cliente). Null si tracking off. */
|
|
984
|
+
getUserId(): string | null;
|
|
985
|
+
/** Session id de navegación actual. Null si tracking off. */
|
|
986
|
+
getSessionId(): string | null;
|
|
987
|
+
/**
|
|
988
|
+
* Id del registro de analytics abierto: el `sessionId` que devolvió `POST /sdk/feedback`,
|
|
989
|
+
* que la API guarda como `sdkSessionId` en el Feedback en que se convierte la sesión. No es
|
|
990
|
+
* `getSessionId()`. Null hasta que el backend acepta el primer lote y de nuevo al cerrar la
|
|
991
|
+
* sesión: para saber también qué registro se cerró, usa `init({ onFeedbackSession })`.
|
|
992
|
+
*/
|
|
993
|
+
getFeedbackSessionId(): string | null;
|
|
994
|
+
/** Avisa al host del registro abierto o cerrado; un fallo del host no corta el envío. */
|
|
995
|
+
private notifyFeedbackSession;
|
|
996
|
+
/** Activa/desactiva el tracking (identidad + sesión + analytics). Kill-switch del contrato §7bis. */
|
|
997
|
+
setTrackingEnabled(enabled: boolean): void;
|
|
998
|
+
/** Registra un evento de analítica (modelo GA: nombre + params). No-op si tracking off. */
|
|
999
|
+
track(name: string, params?: Record<string, unknown>): void;
|
|
1000
|
+
/** User attributes para breakdowns (registration_status, pass_type, sector, pass_status…). */
|
|
1001
|
+
setUserAttributes(attributes: Record<string, string | number | boolean>): void;
|
|
1002
|
+
/**
|
|
1003
|
+
* Registra/actualiza una métrica (valor medible) → `feedback.metrics` del body.
|
|
1004
|
+
* Persistente y sobrescribe por key. No-op si tracking off.
|
|
1005
|
+
*/
|
|
1006
|
+
setMetric(key: string, value: string | number | boolean): void;
|
|
1007
|
+
/** Reporta un error del host (manejado o no) → evento `deepdots_app_crash`. No-op si tracking off. */
|
|
1008
|
+
reportError(error: unknown, options?: ReportErrorOptions): void;
|
|
1009
|
+
/**
|
|
1010
|
+
* Engancha `global.ErrorUtils` de RN para capturar errores JS no manejados. Con tracking off
|
|
1011
|
+
* se recuerda y se engancha cuando se conceda el consentimiento (`setTrackingEnabled(true)`).
|
|
1012
|
+
*/
|
|
1013
|
+
installReactNativeCrashHandler(errorUtils: ReactNativeErrorUtils): void;
|
|
1014
|
+
/**
|
|
1015
|
+
* Pone los handlers de errores no capturados: `window` en web y `ErrorUtils` en RN (el que
|
|
1016
|
+
* pasó el host o, si no pasó ninguno, `globalThis.ErrorUtils`, para que un `init()` sin
|
|
1017
|
+
* `setupReactNative` también capture). Solo con consentimiento; idempotente, así que se
|
|
1018
|
+
* llama en `init()` y cada vez que se activa el tracking.
|
|
1019
|
+
*/
|
|
1020
|
+
private installCrashHandlers;
|
|
1021
|
+
/**
|
|
1022
|
+
* Info interna del usuario que solo conoce el host (idioma, edad, plan…), persistida en el
|
|
1023
|
+
* Contact del backend para segmentación/targeting de popups. Identificada por el `userId` del
|
|
1024
|
+
* init. Solo envía si los atributos cambiaron (diff en storage). No-op si tracking off o sin userId.
|
|
1025
|
+
* @returns `true` si se envió al backend, `false` si no hubo cambios o está deshabilitado.
|
|
1026
|
+
*/
|
|
1027
|
+
setContactAttributes(attributes: ContactAttributes): Promise<boolean>;
|
|
1028
|
+
/** Marca el inicio de un mini-service; etiqueta los eventos siguientes. No-op si tracking off. */
|
|
1029
|
+
enterMiniService(name: string, entryPointType?: string): void;
|
|
1030
|
+
/** Cierra el mini-service `name` (emite `mini_service_exit` con duración, #27). No-op si tracking off o si ese no está activo. */
|
|
1031
|
+
exitMiniService(name: string): void;
|
|
1032
|
+
/** Findability (#31/#35): registra una búsqueda. `has_results` se deriva de `resultsCount`. */
|
|
1033
|
+
trackSearch(query: string, resultsCount: number, params?: Record<string, unknown>): void;
|
|
1034
|
+
/** Findability friction (#34/#35): señal de fricción con su `friction_topic`. */
|
|
1035
|
+
trackFindabilityFriction(frictionTopic: string, params?: Record<string, unknown>): void;
|
|
1036
|
+
/** Funnel: un paso del embudo, correlacionado por `taskId`. El backend reconstruye conversión/drop-off/tiempo. */
|
|
1037
|
+
trackFunnelStep(funnel: string, step: string, taskId: string, params?: Record<string, unknown>): void;
|
|
1038
|
+
/**
|
|
1039
|
+
* Product Effectiveness: una interacción significativa del usuario (`interaction_type` es la
|
|
1040
|
+
* dimensión de agrupación, p. ej. `get_help`, `homepage`, `contact_support`).
|
|
1041
|
+
*
|
|
1042
|
+
* Existe como evento RESERVADO para que la convención no la invente cada host: un `track()`
|
|
1043
|
+
* custom acaba como `deepdots_event_…` y no lo cuenta la analítica de effectiveness.
|
|
1044
|
+
* Un `interactionType` vacío se descarta con warning (no aporta dato agrupable).
|
|
1045
|
+
*/
|
|
1046
|
+
trackMeaningfulInteraction(interactionType: string, params?: Record<string, unknown>): void;
|
|
1047
|
+
/**
|
|
1048
|
+
* Messaging (#18–22): registra una etapa del funnel de una notificación (push/in-app).
|
|
1049
|
+
* No-op si tracking off. El evento se descarta (con warning) si el `channel` no es válido,
|
|
1050
|
+
* si ese `(message_id, stage)` ya se emitió en la sesión, o si el `message_id` ya se reportó
|
|
1051
|
+
* en otro canal — ver `MessageGuard`.
|
|
1052
|
+
*/
|
|
1053
|
+
trackMessage(stage: MessageStage, options: TrackMessageOptions): void;
|
|
1054
|
+
/**
|
|
1055
|
+
* Navegación MANUAL (entornos sin History API, p. ej. React Native con React Navigation).
|
|
1056
|
+
* El host la llama en cada cambio de pantalla; emite `page_view` al salir de la anterior.
|
|
1057
|
+
*/
|
|
1058
|
+
setScreen(name: string): void;
|
|
1059
|
+
/** App a foreground (RN: AppState 'active'): reanuda el engagement time y abre sesión nueva. */
|
|
1060
|
+
onForeground(): void;
|
|
1061
|
+
/**
|
|
1062
|
+
* App a background (RN: AppState 'background'): FIN DE SESIÓN. Cierra pantalla actual
|
|
1063
|
+
* (page_view), mini-services (mini_service_exit), emite engagement + `session_end` y
|
|
1064
|
+
* envía el último lote con `completed:true`.
|
|
1065
|
+
*
|
|
1066
|
+
* Es la única señal disponible en móvil: el kill de la app (swipe) NO da callback.
|
|
1067
|
+
*/
|
|
1068
|
+
onBackground(): void;
|
|
1069
|
+
/**
|
|
1070
|
+
* App a `inactive` (RN, iOS: centro de control, llamada, app switcher, y SIEMPRE justo antes
|
|
1071
|
+
* de `background`). NO cierra la sesión (es transitorio), pero envía lo acumulado con un
|
|
1072
|
+
* `user_engagement` que lleva la pantalla en curso, como web al ocultar la pestaña: si el
|
|
1073
|
+
* lote de cierre de `background` no llega a salir (iOS suspende la app), el backend ya
|
|
1074
|
+
* tiene el tiempo activo y la última pantalla. El contador sigue en marcha.
|
|
1075
|
+
*/
|
|
1076
|
+
onInactive(): void;
|
|
1077
|
+
/**
|
|
1078
|
+
* Ciclo de vida automático en React Native (contrato de detección automática): el SDK escucha
|
|
1079
|
+
* AppState él mismo, así que el host no tiene que llamar a `onForeground`/`onInactive`/
|
|
1080
|
+
* `onBackground`. Si el host los llama además (integraciones anteriores), no se duplica nada:
|
|
1081
|
+
* abrir o cerrar una sesión ya abierta o cerrada no hace nada, y el engagement se consume.
|
|
1082
|
+
* `autoTrack.lifecycle: false` lo apaga.
|
|
1083
|
+
*/
|
|
1084
|
+
private installAutoLifecycle;
|
|
1085
|
+
/**
|
|
1086
|
+
* Cierre EXPLÍCITO de la sesión por parte del host (logout, fin de flujo…): emite
|
|
1087
|
+
* `session_end` y envía el último lote con `completed:true`.
|
|
1088
|
+
*/
|
|
1089
|
+
endSession(): void;
|
|
1090
|
+
/**
|
|
1091
|
+
* Cambio de usuario (login / logout / cambio de cuenta). Cierra la sesión del usuario
|
|
1092
|
+
* anterior (`session_end` con `reason: 'user_change'` + `completed:true`), cambia la
|
|
1093
|
+
* identidad y abre una sesión nueva. Sin `userId` vuelve al id anónimo del SDK.
|
|
1094
|
+
*
|
|
1095
|
+
* Anónimo → identificado (la app arranca sin `userId` y lo pone al hacer login) es la MISMA
|
|
1096
|
+
* persona, no otra: el `session_start` de la sesión nueva lleva `identified: true`,
|
|
1097
|
+
* `previous_user_id` (el id anónimo) y `previous_session_id` (el registro que se acaba de
|
|
1098
|
+
* cerrar), para que el backend una las dos sin adivinar; y el estado de popups (mostrados,
|
|
1099
|
+
* respondidos, protecciones de mensajes) se conserva. Sin esto, cada persona que se registra
|
|
1100
|
+
* contaba dos veces: una que "abandona" en el login y otra registrada nueva.
|
|
1101
|
+
*
|
|
1102
|
+
* Equivale a llamar a `init()` otra vez con otro `userId`.
|
|
1103
|
+
*/
|
|
1104
|
+
setUserId(userId?: string): void;
|
|
1105
|
+
/**
|
|
1106
|
+
* Cierra la sesión actual: vuelca todo lo que quedaba abierto y envía el último lote
|
|
1107
|
+
* marcado con `completed:true`, para que el backend cierre el registro. El `sessionId`
|
|
1108
|
+
* cacheado se olvida → el lote siguiente abre un registro nuevo.
|
|
1109
|
+
*
|
|
1110
|
+
* Idempotente: dos cierres seguidos (p. ej. `visibilitychange` + `pagehide`) no duplican
|
|
1111
|
+
* el `session_end`.
|
|
1112
|
+
*/
|
|
1113
|
+
private closeSession;
|
|
1114
|
+
/**
|
|
1115
|
+
* Abre sesión (`session_start`) si no hay una abierta y el tracking está activo. Idempotente.
|
|
1116
|
+
* El `reason` dice por qué empieza (ver `SessionStartReason`):
|
|
1117
|
+
* - `cold_start`: init() (carga de la página / arranque de la app RN).
|
|
1118
|
+
* - `foreground`: onForeground() tras un cierre (RN).
|
|
1119
|
+
* - `tracking_enabled`: setTrackingEnabled(true).
|
|
1120
|
+
* - `user_change`: setUserId() o init() con otro userId.
|
|
1121
|
+
* - `idle_timeout`: la pestaña vuelve a verse tras más de 30 min oculta.
|
|
1122
|
+
* - `bfcache_restore`: vuelta desde la bfcache fuera de la ventana de reanudación.
|
|
1123
|
+
* Si hay una sesión suspendida a tiempo emite `deepdots_session_resume` en su lugar, sin reason.
|
|
1124
|
+
*/
|
|
1125
|
+
private openSession;
|
|
1126
|
+
/** Web: si la pestaña se ve. Sin `document` (RN) manda AppState vía onForeground/onBackground. */
|
|
1127
|
+
private isDocumentVisible;
|
|
1128
|
+
/** Payload que se ENVIARÍA al endpoint de analytics (no envía ni vacía el buffer). */
|
|
1129
|
+
previewAnalytics(): AnalyticsEnvelope;
|
|
1130
|
+
/**
|
|
1131
|
+
* Envía el lote acumulado de analytics y vacía el buffer.
|
|
1132
|
+
* `final: true` (cierre de página/app): el lote no espera al primer POST en vuelo, porque
|
|
1133
|
+
* el documento se muere; un lote que falle por red o 5xx se re-encola para el siguiente flush.
|
|
1134
|
+
*/
|
|
1135
|
+
flushAnalytics(options?: {
|
|
1136
|
+
final?: boolean;
|
|
1137
|
+
sessionEnd?: boolean;
|
|
1138
|
+
}): void;
|
|
1139
|
+
/**
|
|
1140
|
+
* Emite un evento `user_engagement` con el tiempo activo acumulado (#8) y la pantalla en
|
|
1141
|
+
* curso: `screen` y `path` (los mismos que llevará su `page_view`) y `screen_seconds` (lo
|
|
1142
|
+
* que lleva en ella, medido como el `duration_seconds` del `page_view`).
|
|
1143
|
+
*
|
|
1144
|
+
* El `page_view` sale al SALIR de la pantalla; si el cierre no llega nunca (pestaña dormida
|
|
1145
|
+
* y descartada al volver, pestaña o app matada en segundo plano), la última pantalla de la
|
|
1146
|
+
* sesión se perdía y una visita de una sola pantalla se quedaba sin ninguna. Con la pantalla
|
|
1147
|
+
* en el latido y en el engagement de ocultar la pestaña, el backend la reconstruye.
|
|
1148
|
+
*
|
|
1149
|
+
* En los cierres (`closeSession`, `suspendSession`) el observador ya emitió el `page_view`
|
|
1150
|
+
* y no tiene pantalla, así que ese engagement va sin `screen`: nunca se cuenta dos veces.
|
|
1151
|
+
* Tampoco se emite un `page_view` aquí, por lo mismo.
|
|
1152
|
+
*/
|
|
1153
|
+
private flushEngagement;
|
|
1154
|
+
/** Tick del flush periódico: latido de engagement si toca, y envío de lo acumulado. */
|
|
1155
|
+
private onAnalyticsFlushTick;
|
|
1156
|
+
/**
|
|
1157
|
+
* La pestaña vuelve a verse. Tras más de ANALYTICS_SESSION_TIMEOUT_MS oculta, la sesión
|
|
1158
|
+
* anterior termina y empieza otra: seguir con el mismo sessionId mezclaba dos visitas y,
|
|
1159
|
+
* si el backend ya la había cerrado por inactividad, la partía en dos feedbacks.
|
|
1160
|
+
* - Oculta menos de ANALYTICS_SESSION_DISCARD_MS: el backend aún la tiene abierta → se
|
|
1161
|
+
* cierra con normalidad (page_view de la pantalla, session_end `idle_timeout`, completed).
|
|
1162
|
+
* - Más: ya la cerró el backend → se descarta sin enviar nada.
|
|
1163
|
+
*/
|
|
1164
|
+
private onDocumentVisible;
|
|
1165
|
+
/**
|
|
1166
|
+
* `pagehide` en web: SUSPENDE la sesión en vez de cerrarla, porque el navegador lo lanza
|
|
1167
|
+
* igual al recargar que al cerrar la pestaña. Vuelca lo pendiente (page_view de la
|
|
1168
|
+
* pantalla, mini-services, engagement) con un `deepdots_session_suspend` y SIN
|
|
1169
|
+
* `completed`, y deja el registro en `sessionStorage` (ver `suspended-session.ts`):
|
|
1170
|
+
* - si la página vuelve a cargar en esta pestaña, `init()` sigue en el mismo registro;
|
|
1171
|
+
* - si la pestaña se cerró, el backend lo cierra a los pocos minutos sin otro lote.
|
|
1172
|
+
*
|
|
1173
|
+
* Devuelve false cuando no se puede suspender — aún no se conoce el registro (el primer
|
|
1174
|
+
* POST sigue en vuelo) o no hay `sessionStorage` — y entonces el caller cierra como antes.
|
|
1175
|
+
*/
|
|
1176
|
+
private suspendSession;
|
|
1177
|
+
/**
|
|
1178
|
+
* Recoge la sesión que dejó suspendida la carga anterior de esta pestaña (ver
|
|
1179
|
+
* `suspendSession`). Solo con analytics configurado y el tracking activo: sin ellos no hay
|
|
1180
|
+
* registro en el que seguir.
|
|
1181
|
+
*/
|
|
1182
|
+
private readResumableSession;
|
|
1183
|
+
/**
|
|
1184
|
+
* Consume la sesión suspendida al abrir: los ms que estuvo suspendida si se puede seguir en
|
|
1185
|
+
* ella (mismo usuario, dentro de ANALYTICS_RESUME_WINDOW_MS); null si no había o ya no toca.
|
|
1186
|
+
* En ese caso se olvida su registro sin enviar nada: lo cierra el backend, y la sesión que
|
|
1187
|
+
* se abre ahora va a uno nuevo.
|
|
1188
|
+
*/
|
|
1189
|
+
private takeSuspendedSession;
|
|
1190
|
+
/** Olvida la sesión abierta sin enviar nada (ver onDocumentVisible). */
|
|
1191
|
+
private discardSession;
|
|
1192
|
+
/**
|
|
1193
|
+
* Geolocalización por IP (país/ciudad para analytics). La caché persistente es local y se
|
|
1194
|
+
* aplica siempre que `geolocation` no esté desactivado. El lookup a terceros (ipapi.co →
|
|
1195
|
+
* ipwho.is → ipinfo.io, fallback con timeout) solo se hace si el dato se va a ENVIAR:
|
|
1196
|
+
* analytics configurado + tracking activo + caché ausente o caducada. Una vez por instancia.
|
|
1197
|
+
*/
|
|
1198
|
+
private resolveGeo;
|
|
1199
|
+
private analyticsIdentity;
|
|
1200
|
+
/** Flush automático al ocultar/cerrar la página (no perder el lote pendiente). */
|
|
1201
|
+
private setupAnalyticsFlush;
|
|
1202
|
+
private startAnalyticsFlushTimer;
|
|
1203
|
+
/** Enable auto-launch functionality with configured triggers */
|
|
1204
|
+
autoLaunch(): void;
|
|
1205
|
+
/** Inicia los triggers configurados */
|
|
1206
|
+
private startTriggers;
|
|
1207
|
+
/** Configure triggers for auto-launching popups (manual) */
|
|
1208
|
+
configureTriggers(triggers: TriggerConfig[]): void;
|
|
1209
|
+
/** Deriva triggers desde las definiciones de popup */
|
|
1210
|
+
private configureTriggersFromDefinitions;
|
|
1211
|
+
/**
|
|
1212
|
+
* Lógica para evaluar condiciones antes de mostrar una encuesta. `options.delaySeconds`
|
|
1213
|
+
* (lo pasan los triggers time/scroll/click con el "Delay" del Admin) espera ese tiempo y
|
|
1214
|
+
* vuelve a evaluar antes de mostrar; sin él, al momento como siempre.
|
|
1215
|
+
*/
|
|
1216
|
+
triggerSurvey(surveyId: string, popupId?: string, options?: {
|
|
1217
|
+
delaySeconds?: number;
|
|
1218
|
+
}): void;
|
|
1219
|
+
/** Trigger popups configured with trigger.type = 'event' and matching trigger.value */
|
|
1220
|
+
triggerEvent(eventName: string): void;
|
|
1221
|
+
private evaluateEvent;
|
|
1222
|
+
/**
|
|
1223
|
+
* Muestra `def` ya, o tras su "Delay (seconds)" del Admin. Mientras espera:
|
|
1224
|
+
* - el mismo popup no se programa dos veces (el primer vencimiento manda);
|
|
1225
|
+
* - cambiar de ruta/pantalla o pasar a background lo cancela;
|
|
1226
|
+
* y al vencer se vuelve a evaluar todo (segmentos, idioma, cooldowns) como un disparo nuevo.
|
|
1227
|
+
* Si entonces hay otro popup abierto, `showDefinition` lo salta sin efectos, igual que hoy.
|
|
1228
|
+
*/
|
|
1229
|
+
private showAfterDelay;
|
|
1230
|
+
private showDelayedPopup;
|
|
1231
|
+
private cancelDelayedPopups;
|
|
1232
|
+
private currentHref;
|
|
1233
|
+
/**
|
|
1234
|
+
* Guarda `trigger` si las definiciones aún no han llegado. Devuelve `true` si lo guardó (el
|
|
1235
|
+
* llamador no debe evaluarlo ahora) y `false` si no hay carga en vuelo (se evalúa ya, como
|
|
1236
|
+
* siempre: tras cargar, tras un fallo o sin apiKey).
|
|
1237
|
+
*/
|
|
1238
|
+
private bufferIfAwaitingPopups;
|
|
1239
|
+
/** La carga falló: sin definiciones no hay nada que reproducir, se descarta todo. */
|
|
1240
|
+
private dropPendingTriggers;
|
|
1241
|
+
/** Reproduce en orden por la evaluación normal (segmentos, cooldowns y condiciones de AHORA). */
|
|
1242
|
+
private replayPendingTriggers;
|
|
1243
|
+
private showDefinition;
|
|
1244
|
+
private shouldShow;
|
|
1245
|
+
private matchesSegmentsLang;
|
|
1246
|
+
/** `segments.path`: rutas donde el popup PUEDE mostrarse. Sin lista, en todas. */
|
|
1247
|
+
private matchesSegmentsPath;
|
|
1248
|
+
/**
|
|
1249
|
+
* `segments.excludedPaths`: rutas donde el popup NO debe mostrarse. Gana sobre
|
|
1250
|
+
* `segments.path` (`path: ['/']` + `excludedPaths: ['/cart']` = en todas menos el
|
|
1251
|
+
* carrito) y se aplica también cuando no hay `path` (= en todas menos las excluidas).
|
|
1252
|
+
*/
|
|
1253
|
+
private isPathExcluded;
|
|
1254
|
+
/**
|
|
1255
|
+
* Compara UN candidato de `segments.path`/`segments.excludedPaths` con la ruta
|
|
1256
|
+
* actual. Mismas reglas para incluir y para excluir:
|
|
1257
|
+
* - URL absoluta → href completo exacto
|
|
1258
|
+
* - empieza por / → subcadena del href (así entran las rutas con hash: `/#/home`)
|
|
1259
|
+
* - resto → pathname exacto
|
|
1260
|
+
* Ignora entradas que no sean string: el backend puede colar un `null` en la lista
|
|
1261
|
+
* y no puede tumbar la evaluación del trigger entero (mismo fallo que hubo con
|
|
1262
|
+
* `segments.lang`).
|
|
1263
|
+
*/
|
|
1264
|
+
private matchesPathCandidate;
|
|
1265
|
+
/** href + pathname normalizados de la ruta a evaluar, o null si no hay `window.location`. */
|
|
1266
|
+
private resolveCurrentLocation;
|
|
1267
|
+
private evaluateCooldown;
|
|
1268
|
+
private evaluateLegacyCondition;
|
|
1269
|
+
private hasCooldownElapsed;
|
|
1270
|
+
/** Marcar encuesta como contestada externamente */
|
|
1271
|
+
markSurveyAnswered(surveyId: string): void;
|
|
1272
|
+
/** Queue an exit popup so it can render after navigation */
|
|
1273
|
+
queueExitPopup(surveyId: string, delaySeconds: number, sourceUrl?: string, popupId?: string): void;
|
|
1274
|
+
private processDeferredExitQueue;
|
|
1275
|
+
private scheduleDeferredExitPopup;
|
|
1276
|
+
private tryShowDeferredExitPopup;
|
|
1277
|
+
private findPopupDefinition;
|
|
1278
|
+
private removeDeferredExitPopup;
|
|
1279
|
+
private getDeferredExitQueue;
|
|
1280
|
+
private setDeferredExitQueue;
|
|
1281
|
+
/** Fetch al servidor para obtener popups. `null` si la carga falló (red, no-2xx, payload inválido). */
|
|
1282
|
+
private fetchPopupsFromServer;
|
|
1283
|
+
/**
|
|
1284
|
+
* Envía los atributos de contact a la API (`POST /sdk/popups/contact`). Rechaza si no se
|
|
1285
|
+
* pudo enviar (sin red o respuesta no-2xx), para que `ContactManager` no guarde la caché
|
|
1286
|
+
* y la llamada siguiente reintente.
|
|
1287
|
+
*/
|
|
1288
|
+
private postContact;
|
|
1289
|
+
/** Notifica eventos de popup a la API */
|
|
1290
|
+
private postPopupEvent;
|
|
1291
|
+
/** Add an event listener */
|
|
1292
|
+
on(eventType: DeepdotsEventType, listener: EventListener): void;
|
|
1293
|
+
/** Remove an event listener */
|
|
1294
|
+
off(eventType: DeepdotsEventType, listener: EventListener): void;
|
|
1295
|
+
/** Render the popup UI */
|
|
1296
|
+
private renderPopup;
|
|
1297
|
+
/** Hide the popup */
|
|
1298
|
+
private hidePopup;
|
|
1299
|
+
/** Emit an event */
|
|
1300
|
+
private emitEvent;
|
|
1301
|
+
/** Log debug messages */
|
|
1302
|
+
private log;
|
|
1303
|
+
/** External debug method for triggers */
|
|
1304
|
+
debug(...args: unknown[]): void;
|
|
1305
|
+
/** Set a custom renderer */
|
|
1306
|
+
setRenderer(renderer: PopupRenderer): void;
|
|
1307
|
+
private normalizeUrl;
|
|
1308
|
+
private safeParseUrl;
|
|
1309
|
+
private mapPopupTriggerType;
|
|
1310
|
+
private markSurveyProgress;
|
|
1311
|
+
/**
|
|
1312
|
+
* Fusiona el estado de redisplay del storage con el de memoria: por cada popup/survey gana
|
|
1313
|
+
* la entrada MÁS RECIENTE. Fusionar y no sustituir es lo que hace convivir a varias
|
|
1314
|
+
* pestañas sobre el mismo `localStorage`: se llama en el `init()`, antes de cada decisión
|
|
1315
|
+
* de mostrar y antes de cada escritura. `answeredSurveys` se reconstruye desde las
|
|
1316
|
+
* entradas COMPLETED: es exactamente lo que persiste `markSurveyAnswered`.
|
|
1317
|
+
*/
|
|
1318
|
+
private loadPopupState;
|
|
1319
|
+
/**
|
|
1320
|
+
* Vuelca el estado de redisplay al storage. Sin storage (o bloqueado) degrada a memoria.
|
|
1321
|
+
* Fusiona antes de escribir: escribir solo la foto en memoria borraba lo que otra pestaña
|
|
1322
|
+
* hubiese guardado desde nuestro `init()`.
|
|
1323
|
+
*/
|
|
1324
|
+
private persistPopupState;
|
|
1325
|
+
private isPopupDefinition;
|
|
1326
|
+
private isPopupTrigger;
|
|
1327
|
+
private isPopupTriggerType;
|
|
1328
|
+
private isPopupTriggerCondition;
|
|
1329
|
+
private isLegacyPopupTriggerCondition;
|
|
1330
|
+
private normalizeTriggers;
|
|
1331
|
+
private normalizeCooldown;
|
|
1332
|
+
private normalizeLegacyConditions;
|
|
1333
|
+
private normalizePopupDefinition;
|
|
1334
|
+
private validatePopupDefinitions;
|
|
1335
|
+
}
|
|
1336
|
+
|
|
1337
|
+
/**
|
|
1338
|
+
* Margen que el aviso nativo de "listo" deja por detrás del techo que ya lleva el HTML. El
|
|
1339
|
+
* WebView se revela solo a `REVEAL_TIMEOUT_MS`; este respaldo solo debe entrar cuando el WebView
|
|
1340
|
+
* no llega ni a ejecutar el HTML (motor que no arranca, documento que no carga), que es el único
|
|
1341
|
+
* caso en el que el host se quedaría esperando para siempre.
|
|
1342
|
+
*/
|
|
1343
|
+
declare const NATIVE_READY_GRACE_MS = 500;
|
|
1344
|
+
type EmitFn = (type: DeepdotsEventType, surveyId: string, data?: Record<string, unknown>) => void;
|
|
1345
|
+
/** Payload que recibe el host para montar el WebView del survey. */
|
|
1346
|
+
interface ReactNativeSurveyPayload {
|
|
1347
|
+
surveyId: string;
|
|
1348
|
+
productId: string;
|
|
1349
|
+
/** HTML autocontenido para `<WebView source={{ html }}>`. */
|
|
1350
|
+
html: string;
|
|
1351
|
+
}
|
|
1352
|
+
interface ReactNativeRendererOptions {
|
|
1353
|
+
/** Se llama al mostrar un popup: monta el WebView con `payload.html`. */
|
|
1354
|
+
onShow?: (payload: ReactNativeSurveyPayload) => void;
|
|
1355
|
+
/** Se llama al cerrar el popup: desmonta el WebView. */
|
|
1356
|
+
onHide?: () => void;
|
|
1357
|
+
/**
|
|
1358
|
+
* Se llama cuando el survey ya está pintado dentro del WebView, o pasado el techo de espera.
|
|
1359
|
+
*
|
|
1360
|
+
* Sirve para no enseñar un WebView en blanco: monta el WebView en cuanto llegue `onShow` (fuera
|
|
1361
|
+
* de pantalla o transparente) y ábrelo al recibir `onReady`. El HTML se revela solo de todas
|
|
1362
|
+
* formas, así que el host que no lo use sigue funcionando igual.
|
|
1363
|
+
*/
|
|
1364
|
+
onReady?: (payload: {
|
|
1365
|
+
surveyId: string;
|
|
1366
|
+
}) => void;
|
|
1367
|
+
}
|
|
1368
|
+
/**
|
|
1369
|
+
* Renderer de React Native: el SDK no puede pintar componentes RN, así que entrega el
|
|
1370
|
+
* HTML del survey al host (que lo monta en `react-native-webview`) y traduce los
|
|
1371
|
+
* mensajes del WebView a eventos de popup del SDK (→ `POST /sdk/popups`, Messaging #18–22).
|
|
1372
|
+
*
|
|
1373
|
+
* Uso: monta el WebView con `onShow` y enséñalo con `onReady`, para que el usuario no vea el
|
|
1374
|
+
* WebView arrancando en blanco (motor + bundle del CDN + fetch del survey).
|
|
1375
|
+
* ```tsx
|
|
1376
|
+
* const renderer = new ReactNativePopupRenderer({
|
|
1377
|
+
* onShow: (p) => setSurvey({ ...p, ready: false }),
|
|
1378
|
+
* onReady: () => setSurvey((s) => (s ? { ...s, ready: true } : s)),
|
|
1379
|
+
* onHide: () => setSurvey(null),
|
|
1380
|
+
* });
|
|
1381
|
+
* sdk.setRenderer(renderer);
|
|
1382
|
+
* // …
|
|
1383
|
+
* // ⚠️ Con `<Modal visible={survey.ready}>` esto NO funciona: React Native no monta los hijos
|
|
1384
|
+
* // de un Modal cerrado, así que el WebView no empezaría a cargar y `ready` no llegaría nunca.
|
|
1385
|
+
* // El WebView tiene que estar montado y solo invisible.
|
|
1386
|
+
* {survey ? (
|
|
1387
|
+
* <View style={[StyleSheet.absoluteFill, { opacity: survey.ready ? 1 : 0 }]}
|
|
1388
|
+
* pointerEvents={survey.ready ? 'auto' : 'none'}>
|
|
1389
|
+
* <WebView source={{ html: survey.html }}
|
|
1390
|
+
* onMessage={(e) => renderer.handleMessage(e.nativeEvent.data)} />
|
|
1391
|
+
* </View>
|
|
1392
|
+
* ) : null}
|
|
1393
|
+
* ```
|
|
1394
|
+
*
|
|
1395
|
+
* Quien prefiera no complicarse puede ignorar `onReady` y abrir su Modal en `onShow`: el HTML se
|
|
1396
|
+
* revela solo igualmente, así que el usuario verá el contenedor del host unos cientos de ms antes
|
|
1397
|
+
* que la tarjeta, pero nunca el spinner.
|
|
1398
|
+
*/
|
|
1399
|
+
declare class ReactNativePopupRenderer implements PopupRenderer {
|
|
1400
|
+
private options;
|
|
1401
|
+
private emitFn;
|
|
1402
|
+
private onCloseFn;
|
|
1403
|
+
private currentSurveyId;
|
|
1404
|
+
private partialEmitted;
|
|
1405
|
+
private readyEmitted;
|
|
1406
|
+
private readyTimer;
|
|
1407
|
+
constructor(options?: ReactNativeRendererOptions);
|
|
1408
|
+
init(): void;
|
|
1409
|
+
show(surveyId: string, productId: string, actions: PopupActions | undefined, emit: EmitFn, onClose: () => void, env?: string, userId?: string, style?: PopupStyle, sessionId?: string, miniService?: string, analyticsFeedbackSessionId?: string, renderChrome?: boolean, options?: PopupRenderOptions): void;
|
|
1410
|
+
hide(): void;
|
|
1411
|
+
/** Respaldo del aviso de listo por si el WebView no llega a ejecutar el HTML. */
|
|
1412
|
+
private armReadyFallback;
|
|
1413
|
+
private clearReadyFallback;
|
|
1414
|
+
/** Idempotente: el WebView puede avisar a la vez que vence el respaldo. */
|
|
1415
|
+
private emitReady;
|
|
1416
|
+
/**
|
|
1417
|
+
* El host la conecta al `onMessage` del WebView. Traduce los mensajes del survey a
|
|
1418
|
+
* eventos del SDK: primera interacción → `popup_clicked` (PARTIAL), completado →
|
|
1419
|
+
* `survey_completed` (COMPLETED) y cierra el popup.
|
|
1420
|
+
*/
|
|
1421
|
+
handleMessage(raw: string): void;
|
|
1422
|
+
}
|
|
1423
|
+
|
|
1424
|
+
/**
|
|
1425
|
+
* Construye un HTML autocontenido que renderiza el popup (chrome + survey de
|
|
1426
|
+
* `@magicfeedback/native`) dentro de un WebView (React Native). Es el equivalente RN de
|
|
1427
|
+
* `renderPopup.ts` (DOM real, solo navegador): mismo header con botón cerrar, spinner,
|
|
1428
|
+
* footer con back/start/send, gate "Start survey" y colores/logo desde `formData.style`.
|
|
1429
|
+
* Carga el bundle del survey desde CDN, crea el form con la identidad inyectada
|
|
1430
|
+
* (`profile`/`metadata`) y reenvía los eventos al host vía el puente de
|
|
1431
|
+
* react-native-webview: `window.ReactNativeWebView.postMessage`.
|
|
1432
|
+
*
|
|
1433
|
+
* Mensajes emitidos (JSON `{name, payload}`): `loaded`, `ready`, `before_submit`,
|
|
1434
|
+
* `after_submit`, `survey_completed`, `back`, `popup_close`, y `error:load` / `error:init` /
|
|
1435
|
+
* `error:exception` (con `{message}`) cuando el survey no ha podido cargar.
|
|
1436
|
+
*/
|
|
1437
|
+
interface BuildSurveyHtmlOptions {
|
|
1438
|
+
surveyId: string;
|
|
1439
|
+
productId: string;
|
|
1440
|
+
env?: string;
|
|
1441
|
+
profile?: IdentityAnswer[];
|
|
1442
|
+
metadata?: IdentityAnswer[];
|
|
1443
|
+
/**
|
|
1444
|
+
* Versión de `@magicfeedback/native` a cargar (DD-70: la asignada al survey ya elegida con
|
|
1445
|
+
* `chooseSurveySdkVersion`). Por defecto la empaquetada. Con otra, el HTML trae su hoja
|
|
1446
|
+
* vendorizada y su JS; si cualquiera falla, la hoja y la JS empaquetadas.
|
|
1447
|
+
*/
|
|
1448
|
+
version?: string;
|
|
1449
|
+
font?: PopupFont;
|
|
1450
|
+
theme?: 'light' | 'dark';
|
|
1451
|
+
position?: 'bottom' | 'bottom-right' | 'bottom-left' | 'top' | 'top-right' | 'top-left' | 'center';
|
|
1452
|
+
actions?: PopupActions;
|
|
1453
|
+
/**
|
|
1454
|
+
* Renderiza el "modal" del popup (tarjeta con fondo/sombra/bordes + overlay + posicionamiento).
|
|
1455
|
+
* Default `true`. Con `false` el HTML es transparente y llena el contenedor: el host monta su
|
|
1456
|
+
* propio Modal/tarjeta y controla el estilo. El survey sigue siendo funcional (bridge, form,
|
|
1457
|
+
* botones y botón de cerrar). Pensado para React Native cuando el host gestiona el contenedor.
|
|
1458
|
+
*/
|
|
1459
|
+
chrome?: boolean;
|
|
1460
|
+
/**
|
|
1461
|
+
* Título de la cabecera, a la izquierda del botón de cerrar. Es el `title` de la definición
|
|
1462
|
+
* del popup (`GET /sdk/{publicKey}/popups`), así que cambia de un popup a otro. Vacío es un
|
|
1463
|
+
* valor legítimo: la cabecera se queda solo con la X. NO cae al título del survey.
|
|
1464
|
+
*/
|
|
1465
|
+
title?: string;
|
|
1466
|
+
/**
|
|
1467
|
+
* Barra de progreso ("Question X of Y" + barra) bajo la cabecera. `undefined` respeta el
|
|
1468
|
+
* `showProgressBar` que configure la plataforma en el estilo del survey; `true`/`false` lo
|
|
1469
|
+
* fuerzan desde el host. Solo se pinta con más de una página y fuera de la pantalla de inicio.
|
|
1470
|
+
*/
|
|
1471
|
+
showProgressBar?: boolean;
|
|
1472
|
+
/**
|
|
1473
|
+
* CSS del host, inyectado como último bloque de estilos: gana en cascada sobre el del SDK
|
|
1474
|
+
* y sobre el de `@magicfeedback/native` sin tener que tocar ninguno de los dos. Es la vía
|
|
1475
|
+
* para reestilar el área de preguntas (enunciados, opciones, escalas) por integración.
|
|
1476
|
+
*/
|
|
1477
|
+
surveyCss?: string;
|
|
1478
|
+
/**
|
|
1479
|
+
* Idioma con el que arranca el chrome (botones, progreso, aria-labels, errores). Es el
|
|
1480
|
+
* idioma resuelto en `init()`. Dentro del WebView lo pisa el idioma del survey
|
|
1481
|
+
* (`formData.lang[0]`), y ambos los pisa `actions.*.label` de la API.
|
|
1482
|
+
*/
|
|
1483
|
+
language?: string;
|
|
1484
|
+
}
|
|
1485
|
+
declare function buildSurveyHtml(opts: BuildSurveyHtmlOptions): string;
|
|
1486
|
+
|
|
1487
|
+
/**
|
|
1488
|
+
* Apertura diferida del popup: el chrome se monta invisible y se enseña cuando el survey ya
|
|
1489
|
+
* está pintado, en vez de enseñar un spinner girando mientras se espera.
|
|
1490
|
+
*
|
|
1491
|
+
* Vive en su propio módulo porque lo comparten las dos rutas de render y `renderPopup` arrastra
|
|
1492
|
+
* `@magicfeedback/native`: importar la constante desde allí metería el survey entero en el bundle
|
|
1493
|
+
* de React Native. La ruta del WebView (`surveyHtml`) hornea el valor en el HTML y lleva su
|
|
1494
|
+
* propio espejo del algoritmo en ES5, porque ese código corre dentro del WebView.
|
|
1495
|
+
*/
|
|
1496
|
+
/**
|
|
1497
|
+
* Techo de la espera. Pasado este tiempo el popup se abre igualmente (con spinner, el
|
|
1498
|
+
* comportamiento de siempre), para que una red mala retrase la apertura pero nunca la impida.
|
|
1499
|
+
*
|
|
1500
|
+
* 1200 ms sale de medir contra producción: el `GET .../info` del survey tarda unos 250 ms de
|
|
1501
|
+
* mediana desde Europa, pero con el servicio frío se han visto 775 ms. El techo tiene que quedar
|
|
1502
|
+
* por encima de esa cola: si cayera justo encima, el popup se abriría con el spinner para
|
|
1503
|
+
* quitarlo 30 ms después, que es peor que cualquiera de las dos opciones.
|
|
1504
|
+
*/
|
|
1505
|
+
declare const REVEAL_TIMEOUT_MS = 1200;
|
|
1506
|
+
|
|
1507
|
+
/**
|
|
1508
|
+
* Textos que pinta el SDK alrededor del survey (botones del footer, barra de progreso,
|
|
1509
|
+
* aria-labels y avisos de error). NO son textos del survey: las preguntas, placeholders y
|
|
1510
|
+
* opciones las localiza `@magicfeedback/native` con `formData.lang[0]`, el idioma configurado
|
|
1511
|
+
* en la integración. Este módulo existe para que el chrome del popup hable ese mismo idioma
|
|
1512
|
+
* en lugar de quedarse siempre en inglés.
|
|
1513
|
+
*
|
|
1514
|
+
* Espejo del `i18n/DefaultLabels.kt` del SDK nativo (KMP): mismos locales y mismas reglas de
|
|
1515
|
+
* resolución, para que las tres rutas (popup DOM web, WebView de RN y Compose) digan lo mismo.
|
|
1516
|
+
*/
|
|
1517
|
+
/** Locales con traducción propia. Cualquier otro idioma cae a `en`. */
|
|
1518
|
+
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';
|
|
1519
|
+
interface PopupLabels {
|
|
1520
|
+
/** Acción principal: enviar la respuesta. */
|
|
1521
|
+
accept: string;
|
|
1522
|
+
/** Acción de descarte. */
|
|
1523
|
+
decline: string;
|
|
1524
|
+
/** Botón de la pantalla de bienvenida. */
|
|
1525
|
+
start: string;
|
|
1526
|
+
/** Botón de la pantalla final. */
|
|
1527
|
+
complete: string;
|
|
1528
|
+
/** Volver a la pregunta anterior. */
|
|
1529
|
+
back: string;
|
|
1530
|
+
/** Sustantivo del contador de progreso ("Question" en `Question 2 of 5`). */
|
|
1531
|
+
question: string;
|
|
1532
|
+
/** Separador del contador de progreso ("of" en `Question 2 of 5`). */
|
|
1533
|
+
of: string;
|
|
1534
|
+
/** Distintivo de las preguntas de seguimiento dinámicas. */
|
|
1535
|
+
followUp: string;
|
|
1536
|
+
/** aria-label del botón de cerrar. */
|
|
1537
|
+
closeAria: string;
|
|
1538
|
+
/** aria-label del spinner mientras carga el survey. */
|
|
1539
|
+
loadingAria: string;
|
|
1540
|
+
/** Aviso al intentar avanzar con una pregunta obligatoria sin responder. */
|
|
1541
|
+
errorRequired: string;
|
|
1542
|
+
/** Aviso al intentar avanzar con un email que no es una dirección válida (`INVALID_EMAIL`). */
|
|
1543
|
+
errorInvalidEmail: string;
|
|
1544
|
+
/** Aviso cuando el envío falla. */
|
|
1545
|
+
errorSubmit: string;
|
|
1546
|
+
/** Aviso cuando el survey no ha podido cargar (el popup solo ofrece cerrarlo). */
|
|
1547
|
+
errorLoad: string;
|
|
1548
|
+
}
|
|
1549
|
+
/** Tabla completa de traducciones, indexada por locale. */
|
|
1550
|
+
declare const LABELS: Record<PopupLocale, PopupLabels>;
|
|
1551
|
+
/** Locales con traducción propia del SDK. */
|
|
1552
|
+
declare const SUPPORTED_LANGUAGES: PopupLocale[];
|
|
1553
|
+
/**
|
|
1554
|
+
* Normaliza un tag BCP-47 al locale con traducción. Reglas (idénticas a KMP):
|
|
1555
|
+
* - el prefijo de idioma manda, sin importar región ni caja (`da`, `da-DK`, `da_DK` → `da`);
|
|
1556
|
+
* - las variantes noruegas (`nb`, `nn`) colapsan en `no`;
|
|
1557
|
+
* - las variantes chinas (`zh`, `zh-Hans`, `zh-CN`, `zh-TW`) colapsan en `zh-CN`;
|
|
1558
|
+
* - `pt-BR` y `pt-PT` comparten juego, igual que `de-AT`/`de-CH` o `fr-CA`;
|
|
1559
|
+
* - cualquier otra cosa, incluido un valor no-string del backend, cae a `en`.
|
|
1560
|
+
*/
|
|
1561
|
+
declare function resolveLocale(lang?: string | null): PopupLocale;
|
|
1562
|
+
/**
|
|
1563
|
+
* Locales que se escriben de derecha a izquierda. Espejo de `RTL_LANGUAGES` de
|
|
1564
|
+
* `@magicfeedback/native` (2.2.22), que estampa `dir="rtl"` en el contenedor del survey para
|
|
1565
|
+
* esos idiomas: el chrome del popup tiene que voltear con él o media tarjeta queda mirando a
|
|
1566
|
+
* un lado y media al otro.
|
|
1567
|
+
*/
|
|
1568
|
+
declare const RTL_LOCALES: PopupLocale[];
|
|
1569
|
+
/** Si el chrome debe pintarse de derecha a izquierda para `lang`. */
|
|
1570
|
+
declare function isRtlLanguage(lang?: string | null): boolean;
|
|
1571
|
+
/** Valor del atributo `dir` del chrome para `lang`. Siempre explícito: nunca se hereda del host. */
|
|
1572
|
+
declare function directionFor(lang?: string | null): 'rtl' | 'ltr';
|
|
1573
|
+
/** Textos del chrome del popup para `lang`. Cae a inglés si el idioma no está soportado. */
|
|
1574
|
+
declare function getLabels(lang?: string | null): PopupLabels;
|
|
1575
|
+
/** Etiquetas de los cuatro botones del footer, ya resueltas. */
|
|
1576
|
+
interface ResolvedActionLabels {
|
|
1577
|
+
accept: string;
|
|
1578
|
+
decline: string;
|
|
1579
|
+
start: string;
|
|
1580
|
+
complete: string;
|
|
1581
|
+
back: string;
|
|
1582
|
+
}
|
|
1583
|
+
/**
|
|
1584
|
+
* Resuelve las etiquetas de los botones con la prioridad acordada: lo que configure la
|
|
1585
|
+
* plataforma por popup (`actions.*.label`) gana siempre; si falta o viene en blanco, se usa
|
|
1586
|
+
* la traducción del SDK para `lang`.
|
|
1587
|
+
*/
|
|
1588
|
+
declare function resolveActionLabels(actions: PopupActions | undefined, lang?: string | null): ResolvedActionLabels;
|
|
1589
|
+
|
|
1590
|
+
/**
|
|
1591
|
+
* Auto-wiring de React Native: concentra TODA la configuración en el SDK para que el
|
|
1592
|
+
* host solo tenga que envolver su app en un `<DeepdotsProvider config={...}>`.
|
|
1593
|
+
*
|
|
1594
|
+
* No importa React ni librerías nativas: el host (o el Provider) le pasa los módulos
|
|
1595
|
+
* nativos que tenga instalados (MMKV, device-info, AppState). Todo es opcional y degrada
|
|
1596
|
+
* con elegancia (sin MMKV → in-memory; sin device-info → sin device info).
|
|
1597
|
+
*/
|
|
1598
|
+
|
|
1599
|
+
/** Forma mínima de `react-native-mmkv` (instancia MMKV). */
|
|
1600
|
+
interface MmkvLike {
|
|
1601
|
+
getString(key: string): string | undefined | null;
|
|
1602
|
+
set(key: string, value: string): void;
|
|
1603
|
+
delete(key: string): void;
|
|
1604
|
+
}
|
|
1605
|
+
/** Forma mínima de `react-native-device-info`. */
|
|
1606
|
+
interface DeviceInfoLike {
|
|
1607
|
+
isTablet?: () => boolean;
|
|
1608
|
+
getSystemVersion?: () => string;
|
|
1609
|
+
getDeviceId?: () => string;
|
|
1610
|
+
getVersion?: () => string;
|
|
1611
|
+
}
|
|
1612
|
+
/** Forma mínima de `AppState` de react-native. */
|
|
1613
|
+
interface AppStateLike {
|
|
1614
|
+
addEventListener(type: 'change', listener: (state: string) => void): {
|
|
1615
|
+
remove: () => void;
|
|
1616
|
+
} | void;
|
|
1617
|
+
}
|
|
1618
|
+
interface ReactNativeSetupDeps {
|
|
1619
|
+
mmkv?: MmkvLike | null;
|
|
1620
|
+
deviceInfo?: DeviceInfoLike | null;
|
|
1621
|
+
appState?: AppStateLike | null;
|
|
1622
|
+
platform?: 'web' | 'android' | 'ios';
|
|
1623
|
+
renderer?: PopupRenderer;
|
|
1624
|
+
/** `global.ErrorUtils` de RN (para capturar errores JS no manejados). Default: `globalThis.ErrorUtils`. */
|
|
1625
|
+
errorUtils?: ReactNativeErrorUtils | null;
|
|
1626
|
+
/**
|
|
1627
|
+
* Background task nativa para los envíos (iOS, DD-55). Si `config.backgroundTask` viene, gana
|
|
1628
|
+
* ese. Para `react-native-background-timer`: `backgroundTimerTask(BackgroundTimer)`.
|
|
1629
|
+
*/
|
|
1630
|
+
backgroundTask?: BackgroundTaskRunner | null;
|
|
1631
|
+
}
|
|
1632
|
+
/** Adaptador KeyValueStorage (síncrono) sobre una instancia de MMKV. */
|
|
1633
|
+
declare function mmkvStorage(mmkv: MmkvLike): KeyValueStorage;
|
|
1634
|
+
/** Recoge device info desde react-native-device-info (Technology #11–13). */
|
|
1635
|
+
declare function collectRnDevice(d: DeviceInfoLike): DeviceInfo;
|
|
1636
|
+
/**
|
|
1637
|
+
* Configura el SDK para React Native en una sola llamada: storage persistente (MMKV),
|
|
1638
|
+
* device info, platform, init y lifecycle (AppState → onForeground/onBackground).
|
|
1639
|
+
* Devuelve una función de limpieza (quita el listener de AppState).
|
|
1640
|
+
*/
|
|
1641
|
+
declare function setupReactNative(sdk: DeepdotsPopups, config: DeepdotsInitParams, deps?: ReactNativeSetupDeps): () => void;
|
|
1642
|
+
|
|
1643
|
+
/**
|
|
1644
|
+
* Lo que el SDK necesita de React Native para detectar solo el ciclo de vida y el tiempo de
|
|
1645
|
+
* background (DD-55, contrato de detección automática). El core no importa `react-native` (se
|
|
1646
|
+
* usa también en web): lo registra la entrada de React Native del paquete
|
|
1647
|
+
* (`src/index.native.ts`, que Metro elige por la condición `react-native`) y el Provider.
|
|
1648
|
+
*/
|
|
1649
|
+
|
|
1650
|
+
/** Opciones de `HermesInternal.enablePromiseRejectionTracker` (las mismas que `promise/rejection-tracking`). */
|
|
1651
|
+
interface RejectionTrackingOptions {
|
|
1652
|
+
allRejections?: boolean;
|
|
1653
|
+
onUnhandled?: (id: number, error: unknown) => void;
|
|
1654
|
+
onHandled?: (id: number, error?: unknown) => void;
|
|
1655
|
+
}
|
|
1656
|
+
/** Lo que el SDK necesita de `global.HermesInternal`. */
|
|
1657
|
+
interface HermesRejectionTrackerLike {
|
|
1658
|
+
enablePromiseRejectionTracker?: (options?: RejectionTrackingOptions) => void;
|
|
1659
|
+
}
|
|
1660
|
+
interface PromiseRejectionHub {
|
|
1661
|
+
/** Avisa de cada promesa rechazada sin `catch`. Devuelve la función que lo quita. */
|
|
1662
|
+
addUnhandledListener(listener: (error: unknown) => void): () => void;
|
|
1663
|
+
}
|
|
1664
|
+
/**
|
|
1665
|
+
* Promesas rechazadas sin `catch` en React Native (contrato de detección automática, paso 2).
|
|
1666
|
+
*
|
|
1667
|
+
* Hermes solo admite UN tracker (`enablePromiseRejectionTracker` sustituye al anterior) y no deja
|
|
1668
|
+
* leer el que hay. Para no quitarle las rejections a Sentry/Crashlytics, la entrada de React
|
|
1669
|
+
* Native envuelve la función al importarse el paquete, que es antes de que el código de la app
|
|
1670
|
+
* llame a `Sentry.init()` (los imports se evalúan primero): lo que instale después cualquiera se
|
|
1671
|
+
* compone con lo nuestro en vez de sustituirlo. Antes del import solo lo pudo instalar React
|
|
1672
|
+
* Native, y solo en desarrollo (el aviso "Possible unhandled promise rejection"), que se mantiene
|
|
1673
|
+
* con `dev`. Mientras el SDK no se engancha, la función envuelta pasa todo tal cual a Hermes.
|
|
1674
|
+
*
|
|
1675
|
+
* Devuelve null sin Hermes o sin el tracker (JSC): el SDK sigue sin capturarlas, como antes.
|
|
1676
|
+
*/
|
|
1677
|
+
declare function createHermesRejectionHub(hermes: HermesRejectionTrackerLike | null | undefined, options: {
|
|
1678
|
+
dev: boolean;
|
|
1679
|
+
}): PromiseRejectionHub | null;
|
|
1680
|
+
|
|
1681
|
+
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 };
|