@shotik/react-native 0.1.0 → 0.2.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/CHANGELOG.md +16 -0
- package/LICENSE +26 -0
- package/README.md +39 -3
- package/README.ru.md +40 -3
- package/dist/analytics/core.d.ts +96 -11
- package/dist/analytics/core.js +295 -22
- package/dist/analytics/privacy.d.ts +4 -0
- package/dist/analytics/privacy.js +46 -0
- package/dist/analytics/replay.d.ts +41 -0
- package/dist/analytics/replay.js +192 -0
- package/dist/analytics/rn.d.ts +52 -2
- package/dist/analytics/rn.js +669 -62
- package/dist/analytics/wire.d.ts +54 -2
- package/dist/analytics/wire.js +44 -4
- package/dist/client.d.ts +94 -1
- package/dist/client.js +254 -17
- package/dist/flow.d.ts +48 -0
- package/dist/flow.js +56 -0
- package/dist/index.d.ts +4 -4
- package/dist/index.js +2 -2
- package/dist/parts.d.ts +42 -1
- package/dist/parts.js +72 -14
- package/dist/react.d.ts +24 -3
- package/dist/react.js +42 -15
- package/dist/sheet.d.ts +2 -1
- package/dist/sheet.js +207 -16
- package/dist/support.js +2 -2
- package/dist/theme.d.ts +43 -0
- package/dist/theme.js +90 -4
- package/package.json +15 -2
- package/recipe.json +1 -1
- package/src/analytics/README.md +10 -6
- package/src/analytics/core.ts +314 -25
- package/src/analytics/privacy.ts +50 -0
- package/src/analytics/recipe.json +1 -1
- package/src/analytics/replay.ts +190 -0
- package/src/analytics/rn.tsx +620 -63
- package/src/analytics/wire.ts +99 -8
- package/src/client.ts +344 -19
- package/src/flow.ts +100 -0
- package/src/index.ts +4 -4
- package/src/parts.tsx +102 -14
- package/src/react.tsx +57 -16
- package/src/sheet.tsx +423 -20
- package/src/support.ts +2 -2
- package/src/theme.ts +90 -4
package/dist/analytics/core.js
CHANGED
|
@@ -1,12 +1,43 @@
|
|
|
1
1
|
// Shotik analytics core: sessions, screens and time on screen, taps with rage detection, scroll depth, stalls, the
|
|
2
2
|
// offline queue and batched upload. Platform-free (no React Native imports), so it runs and is tested under plain Node.
|
|
3
|
+
import { cleanProps, redact } from './privacy';
|
|
4
|
+
import { Replay } from './replay';
|
|
3
5
|
import { pack } from './wire';
|
|
4
|
-
const K = { anon: 'shotik.support.anon', state: 'shotik.analytics.state', queue: 'shotik.analytics.queue', consent: 'shotik.analytics.consent' };
|
|
6
|
+
const K = { anon: 'shotik.support.anon', state: 'shotik.analytics.state', queue: 'shotik.analytics.queue', consent: 'shotik.analytics.consent', purchases: 'shotik.analytics.purchases', replay: 'shotik.analytics.replay' };
|
|
5
7
|
const MAX_QUEUE = 2000;
|
|
6
8
|
const BATCH = 300;
|
|
7
9
|
const RAGE_N = 3;
|
|
8
10
|
const RAGE_MS = 800;
|
|
9
11
|
const RAGE_PT = 40;
|
|
12
|
+
const RESP_MS = 1500;
|
|
13
|
+
const NET_SLOW_MS = 3000;
|
|
14
|
+
const ERRTAP_MS = 2000;
|
|
15
|
+
const REPLAY_REQS = 8;
|
|
16
|
+
// The SDK's own cost this session (perf on close): the last 256 samples per path, bytes uploaded.
|
|
17
|
+
const costs = () => ({ tap: [], walk: [], fp: [], rb: 0, eb: 0 });
|
|
18
|
+
const p95 = (a) => {
|
|
19
|
+
if (!a.length)
|
|
20
|
+
return undefined;
|
|
21
|
+
const s = a.slice().sort((x, y) => x - y);
|
|
22
|
+
return Math.round(s[Math.ceil(s.length * 0.95) - 1] * 1000) / 1000;
|
|
23
|
+
};
|
|
24
|
+
// Sent as `sdk: 'rn/<version>'` in the device context. Keep equal to package.json (a unit test checks it).
|
|
25
|
+
export const SDK_VERSION = '0.2.0';
|
|
26
|
+
// A request URL as host + path template: no scheme, credentials, query or fragment; ids, UUIDs, hex, digit runs, tokens
|
|
27
|
+
// of 8+ characters with 2+ digits, emails, anything redact() changes and percent-encoded or non-ASCII segments become :id
|
|
28
|
+
// (a file extension stays). A plain-word segment (a username) can't be detected and stays. Plain string work, because React Native's URL polyfill lacks host/pathname.
|
|
29
|
+
export function netTarget(url) {
|
|
30
|
+
const m = /^(?:[a-z][a-z0-9+.-]*:)?\/\/([^/?#]*)([^?#]*)/i.exec(url);
|
|
31
|
+
const host = (m ? m[1] : '').replace(/^.*@/, '').toLowerCase();
|
|
32
|
+
const raw = m ? m[2] : url.replace(/[?#].*$/, '');
|
|
33
|
+
const id = (s) => (/\d/.test(s) && (/^[\d.,_-]+$/.test(s) || /^[0-9a-f-]{16,}$/i.test(s))) || (s.length >= 8 && /^[\w-]+$/.test(s) && /\d.*\d/.test(s)) || /@|%[0-9a-f]{2}|[^\x00-\x7f]/i.test(s) || redact(s) !== s;
|
|
34
|
+
const seg = (s) => {
|
|
35
|
+
const x = /^(.+)(\.[a-z0-9]{1,5})$/i.exec(s);
|
|
36
|
+
return x && id(x[1]) && !/@|%40/.test(s) ? ':id' + x[2] : id(s) ? ':id' : s;
|
|
37
|
+
};
|
|
38
|
+
const path = raw.split('/').map(seg).join('/').slice(0, 120);
|
|
39
|
+
return { host, path: path || '/' };
|
|
40
|
+
}
|
|
10
41
|
const rnd = () => Math.random().toString(36).slice(2, 10);
|
|
11
42
|
const uid = () => Date.now().toString(36) + rnd() + rnd();
|
|
12
43
|
export class Analytics {
|
|
@@ -23,6 +54,10 @@ export class Analytics {
|
|
|
23
54
|
this.screenAt = 0;
|
|
24
55
|
this.screenStats = { depth: 0, drag: 0, stalls: 0, maxStall: 0 };
|
|
25
56
|
this.taps = [];
|
|
57
|
+
this.held = null;
|
|
58
|
+
this.waiting = [];
|
|
59
|
+
this.states = false;
|
|
60
|
+
this.marks = {};
|
|
26
61
|
this.snapped = new Set();
|
|
27
62
|
this.timer = null;
|
|
28
63
|
this.saveTimer = null;
|
|
@@ -32,6 +67,9 @@ export class Analytics {
|
|
|
32
67
|
this.active = true;
|
|
33
68
|
this.loaded = false;
|
|
34
69
|
this.fresh = true;
|
|
70
|
+
this.replay = new Replay();
|
|
71
|
+
this.cost = costs();
|
|
72
|
+
this.lastTap = { ts: -Infinity };
|
|
35
73
|
this.cfg = cfg;
|
|
36
74
|
this.st = cfg.storage ?? null;
|
|
37
75
|
this.now = cfg.now ?? Date.now;
|
|
@@ -42,7 +80,7 @@ export class Analytics {
|
|
|
42
80
|
const st = this.st;
|
|
43
81
|
if (st) {
|
|
44
82
|
try {
|
|
45
|
-
const [anon, raw, q, c] = await Promise.all([st.get(K.anon), st.get(K.state), st.get(K.queue), st.get(K.consent)]);
|
|
83
|
+
const [anon, raw, q, c, pm, rp] = await Promise.all([st.get(K.anon), st.get(K.state), st.get(K.queue), st.get(K.consent), st.get(K.purchases), st.get(K.replay)]);
|
|
46
84
|
this.anon = anon ?? '';
|
|
47
85
|
const s = raw ? JSON.parse(raw) : null;
|
|
48
86
|
if (s) {
|
|
@@ -58,6 +96,14 @@ export class Analytics {
|
|
|
58
96
|
this.queue = JSON.parse(q).concat(this.queue).slice(-MAX_QUEUE);
|
|
59
97
|
if (c === 'granted' || c === 'denied')
|
|
60
98
|
this.consent = c;
|
|
99
|
+
if (pm)
|
|
100
|
+
this.marks = JSON.parse(pm) ?? {};
|
|
101
|
+
if (rp) {
|
|
102
|
+
const r = JSON.parse(rp);
|
|
103
|
+
if (Array.isArray(r?.chunks))
|
|
104
|
+
this.replay.restore(r.why ?? 'crash', r.chunks);
|
|
105
|
+
st.remove(K.replay).catch(() => { });
|
|
106
|
+
}
|
|
61
107
|
}
|
|
62
108
|
catch {
|
|
63
109
|
this.storeIssue = 'error';
|
|
@@ -98,20 +144,22 @@ export class Analytics {
|
|
|
98
144
|
this.seq = 0;
|
|
99
145
|
this.sampled = Math.random() < (this.cfg.snapshots ?? 0.2);
|
|
100
146
|
this.snapped.clear();
|
|
147
|
+
this.cost = costs();
|
|
101
148
|
this.lastActive = t;
|
|
102
149
|
const props = { ...(first && { first: 1 }), ...(this.storeIssue && { store: this.storeIssue }) };
|
|
103
150
|
this.push('session', undefined, Object.keys(props).length ? props : undefined, t);
|
|
104
151
|
}
|
|
105
152
|
this.lastActive = t;
|
|
106
153
|
}
|
|
107
|
-
push(type, name, props, ts) {
|
|
154
|
+
push(type, name, props, ts, screen = this.screen) {
|
|
108
155
|
if (this.consent === 'denied')
|
|
109
156
|
return;
|
|
110
|
-
this.queue.push({ seq: ++this.seq, ts: ts ?? this.now(), type, sessionId: this.sessionId, screen
|
|
157
|
+
this.queue.push({ seq: ++this.seq, ts: ts ?? this.now(), type, sessionId: this.sessionId, screen, name, props });
|
|
111
158
|
if (this.queue.length > MAX_QUEUE)
|
|
112
159
|
this.queue.splice(0, this.queue.length - MAX_QUEUE);
|
|
113
160
|
if (this.cfg.debug)
|
|
114
161
|
console.log('[shotik]', type, name ?? '', this.screen ?? '', props ?? '');
|
|
162
|
+
this.cfg.onEvent?.(type, name, this.screen, props);
|
|
115
163
|
this.save();
|
|
116
164
|
if (this.queue.length >= BATCH)
|
|
117
165
|
this.flush();
|
|
@@ -140,13 +188,25 @@ export class Analytics {
|
|
|
140
188
|
}, (this.cfg.flushMs ?? 10000) * Math.pow(2, this.backoff));
|
|
141
189
|
}
|
|
142
190
|
// Public API
|
|
191
|
+
get dev() {
|
|
192
|
+
return !!(this.cfg.debug || globalThis.__DEV__);
|
|
193
|
+
}
|
|
194
|
+
// A connection check: one test event, sent now. It goes through the same queue, key and route as everything else, flagged
|
|
195
|
+
// kind 'test', so the server shows "Test event received" and never counts it as a session, a user or a metric.
|
|
196
|
+
sendTestEvent() {
|
|
197
|
+
if (this.consent === 'denied')
|
|
198
|
+
return Promise.resolve();
|
|
199
|
+
this.queue.push({ seq: ++this.seq, ts: this.now(), type: 'custom', sessionId: this.sessionId || 'test_' + this.anon, name: 'shotik_test', kind: 'test' });
|
|
200
|
+
return this.flush();
|
|
201
|
+
}
|
|
202
|
+
// Personal-data keys are dropped and string values redacted on the device (privacy.ts).
|
|
143
203
|
track(name, props) {
|
|
144
204
|
this.touch();
|
|
145
|
-
this.push('custom', name, props);
|
|
205
|
+
this.push('custom', redact(name), cleanProps(props, this.dev));
|
|
146
206
|
}
|
|
147
207
|
identify(userId, traits) {
|
|
148
208
|
this.userId = userId;
|
|
149
|
-
this.push('identify', undefined, traits ? { traits } : undefined);
|
|
209
|
+
this.push('identify', undefined, traits ? { traits: cleanProps(traits, this.dev) } : undefined);
|
|
150
210
|
}
|
|
151
211
|
// Screen change: closes the previous screen with its time and scroll depth.
|
|
152
212
|
screenView(name) {
|
|
@@ -154,7 +214,10 @@ export class Analytics {
|
|
|
154
214
|
return;
|
|
155
215
|
this.touch();
|
|
156
216
|
const from = this.screen;
|
|
217
|
+
this.drain(true);
|
|
218
|
+
this.respond(true);
|
|
157
219
|
this.leave();
|
|
220
|
+
this.stateH = undefined;
|
|
158
221
|
this.screen = name;
|
|
159
222
|
this.screenAt = this.now();
|
|
160
223
|
this.push('screen', name, from ? { from } : undefined);
|
|
@@ -189,24 +252,155 @@ export class Analytics {
|
|
|
189
252
|
if (ms > 1000)
|
|
190
253
|
this.push('slow', this.screen, { ms: Math.round(ms), kind: 'stall' });
|
|
191
254
|
}
|
|
192
|
-
// A tap with its element identity. dead = nothing on the touched element handles presses
|
|
255
|
+
// A tap with its element identity. dead = nothing on the touched element handles presses; it stays dead unless the
|
|
256
|
+
// screen changes within RESP_MS. The tap is queued once it is resolved: on its response, the next tap, or RESP_MS
|
|
257
|
+
// later (checked on every flush), with its own ts and screen. resp = ms to the first screen change or request start,
|
|
258
|
+
// attributed to the newest tap only; a tap that stays dead carries none (a request it can't have caused). Rage needs 3 taps within 800 ms and 40 pt, at least one of them without a resp.
|
|
193
259
|
tap(t) {
|
|
194
260
|
this.touch();
|
|
195
261
|
const now = t.ts ?? this.now();
|
|
196
|
-
|
|
262
|
+
this.release();
|
|
263
|
+
const h = { t, ts: now, screen: this.screen };
|
|
264
|
+
this.lastTap = { ts: now, screen: this.screen };
|
|
265
|
+
this.taps = this.taps.filter((q) => now - q.t < RAGE_MS && Math.hypot(q.x - t.x, q.y - t.y) < RAGE_PT);
|
|
266
|
+
this.taps.push({ x: t.x, y: t.y, t: now, h });
|
|
267
|
+
if (this.taps.length === RAGE_N)
|
|
268
|
+
h.burst = this.taps.map((q) => q.h);
|
|
269
|
+
this.held = h;
|
|
270
|
+
}
|
|
271
|
+
respond(screen) {
|
|
272
|
+
const h = this.held;
|
|
273
|
+
if (!h)
|
|
274
|
+
return;
|
|
275
|
+
const dt = this.now() - h.ts;
|
|
276
|
+
if (dt > RESP_MS)
|
|
277
|
+
return this.release();
|
|
278
|
+
h.resp ?? (h.resp = Math.max(0, Math.round(dt)));
|
|
279
|
+
if (screen) {
|
|
280
|
+
h.moved = true;
|
|
281
|
+
this.release();
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
settle(all) {
|
|
285
|
+
if (this.held && (all || this.now() - this.held.ts > RESP_MS))
|
|
286
|
+
this.release();
|
|
287
|
+
this.drain(all);
|
|
288
|
+
}
|
|
289
|
+
// While UI-state fingerprints run (uiState was called), a resolved tap with no response waits for the next walk.
|
|
290
|
+
release() {
|
|
291
|
+
const h = this.held;
|
|
292
|
+
if (!h)
|
|
293
|
+
return;
|
|
294
|
+
this.held = null;
|
|
295
|
+
if (this.states && !h.checked && h.resp === undefined && !h.t.dead && !h.t.input)
|
|
296
|
+
return void this.waiting.push(h);
|
|
297
|
+
this.emit(h);
|
|
298
|
+
}
|
|
299
|
+
drain(all) {
|
|
300
|
+
const now = this.now();
|
|
301
|
+
while (this.waiting.length && (all || now - this.waiting[0].ts > RESP_MS))
|
|
302
|
+
this.emit(this.waiting.shift());
|
|
303
|
+
}
|
|
304
|
+
emit(h) {
|
|
305
|
+
const t = h.t;
|
|
306
|
+
const dead = t.dead && !h.moved;
|
|
307
|
+
if (dead)
|
|
308
|
+
h.resp = undefined;
|
|
309
|
+
const at = t.masked ? {} : { x: Math.round(t.x), y: Math.round(t.y) };
|
|
310
|
+
const p = { el: t.el, ...at, ...(!t.masked && { nx: t.nx, ny: t.ny }) };
|
|
197
311
|
if (t.id)
|
|
198
312
|
p.id = t.id;
|
|
199
313
|
if (t.label)
|
|
200
314
|
p.label = t.label;
|
|
201
|
-
if (
|
|
315
|
+
if (dead)
|
|
202
316
|
p.dead = 1;
|
|
203
317
|
if (t.input)
|
|
204
318
|
p.input = 1;
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
this.
|
|
208
|
-
|
|
209
|
-
|
|
319
|
+
if (h.resp !== undefined)
|
|
320
|
+
p.resp = h.resp;
|
|
321
|
+
this.push('tap', undefined, p, h.ts, h.screen);
|
|
322
|
+
const rage = h.burst?.some((b) => b.resp === undefined);
|
|
323
|
+
if (rage)
|
|
324
|
+
this.push('rage', undefined, { el: t.el, id: t.id, label: t.label, n: RAGE_N, ...at }, h.ts, h.screen);
|
|
325
|
+
if (rage || dead || (!t.input && h.resp === undefined))
|
|
326
|
+
this.signal(rage ? 'rage' : dead ? 'dead' : 'unresponsive');
|
|
327
|
+
}
|
|
328
|
+
// A replay signal (PROTOCOL.md 4.7): an unsampled session's ring of the last 30 s is released for upload.
|
|
329
|
+
signal(why) {
|
|
330
|
+
this.replay.signal(why, this.now());
|
|
331
|
+
}
|
|
332
|
+
// A UI-state fingerprint walk finished (h null: none possible). The first one on a screen is its baseline; a different h
|
|
333
|
+
// later on the same screen is a `state` event and the response of every tap waiting for this walk. quiet (after a
|
|
334
|
+
// vertical scroll) only moves the baseline.
|
|
335
|
+
uiState(h, n = 0, quiet = false) {
|
|
336
|
+
this.states = true;
|
|
337
|
+
const changed = h !== null && this.stateH !== undefined && h !== this.stateH && !quiet;
|
|
338
|
+
if (h !== null)
|
|
339
|
+
this.stateH = h;
|
|
340
|
+
if (changed) {
|
|
341
|
+
const now = this.now();
|
|
342
|
+
for (const w of this.waiting)
|
|
343
|
+
if (now - w.ts <= RESP_MS)
|
|
344
|
+
w.resp = Math.round(now - w.ts);
|
|
345
|
+
this.respond(false);
|
|
346
|
+
}
|
|
347
|
+
if (this.held)
|
|
348
|
+
this.held.checked = true;
|
|
349
|
+
this.drain(true);
|
|
350
|
+
if (changed)
|
|
351
|
+
this.push('state', undefined, { h, n });
|
|
352
|
+
return changed;
|
|
353
|
+
}
|
|
354
|
+
// One focus span of a text input: ts = focus time, ms focused, edits (none for secure inputs), filled. Never a value or length.
|
|
355
|
+
field(f) {
|
|
356
|
+
this.touch();
|
|
357
|
+
this.push('field', undefined, { id: f.id, el: f.el, ms: Math.max(0, Math.round(f.ms)), edits: f.edits === undefined ? undefined : Math.min(20, f.edits), filled: f.filled ? 1 : undefined }, f.ts, f.screen);
|
|
358
|
+
}
|
|
359
|
+
// A request started (wrapped fetch / XMLHttpRequest): a response to the newest tap.
|
|
360
|
+
netStart() {
|
|
361
|
+
this.respond(false);
|
|
362
|
+
}
|
|
363
|
+
// A finished request; only failures (status >= 400, 0 = network error) and slow calls (> 3 s) become `net` events.
|
|
364
|
+
net(method, url, status, ms) {
|
|
365
|
+
if (status > 0 && status < 400 && ms <= NET_SLOW_MS)
|
|
366
|
+
return;
|
|
367
|
+
const { host, path } = netTarget(url);
|
|
368
|
+
this.push('net', undefined, { m: method.toUpperCase().slice(0, 10), host, path, s: status, ms: Math.round(ms) });
|
|
369
|
+
if ((status === 0 || status >= 400) && this.now() - this.lastTap.ts <= ERRTAP_MS && this.lastTap.screen === this.screen)
|
|
370
|
+
this.signal('errtap');
|
|
371
|
+
}
|
|
372
|
+
// A touch that was neither a tap nor a scroll (PROTOCOL.md 4.1 touch classes). ts = the touch start.
|
|
373
|
+
gesture(g) {
|
|
374
|
+
this.touch();
|
|
375
|
+
this.push('gesture', undefined, { k: g.k, dir: g.dir, dx: Math.round(g.dx), dy: Math.round(g.dy), ms: Math.round(g.ms), el: g.el, id: g.id, sc: g.sc === undefined ? undefined : Math.round(g.sc * 100) / 100 }, g.ts);
|
|
376
|
+
}
|
|
377
|
+
// A container a touch scrolled settled at a new offset. ts = the touch end.
|
|
378
|
+
scrolled(s) {
|
|
379
|
+
this.touch();
|
|
380
|
+
this.push('scroll', undefined, { el: s.el, id: s.id, off: Math.round(s.off), len: Math.round(s.len), vis: Math.round(s.vis), hz: s.hz ? 1 : undefined, pg: s.pg }, s.ts, s.screen);
|
|
381
|
+
}
|
|
382
|
+
// Self-cost samples (ms) for perf on close: the touch-end handler, a replay capture, a fingerprint walk.
|
|
383
|
+
measure(kind, ms) {
|
|
384
|
+
const a = this.cost[kind];
|
|
385
|
+
a.push(ms);
|
|
386
|
+
if (a.length > 256)
|
|
387
|
+
a.shift();
|
|
388
|
+
}
|
|
389
|
+
perf() {
|
|
390
|
+
const c = this.cost;
|
|
391
|
+
return { tap: p95(c.tap), walk: p95(c.walk), fp: p95(c.fp), rb: c.rb, eb: c.eb };
|
|
392
|
+
}
|
|
393
|
+
get replayOn() {
|
|
394
|
+
return this.cfg.replay !== false && this.loaded && this.active && this.consent !== 'denied' && !this.replay.off;
|
|
395
|
+
}
|
|
396
|
+
// One replay capture (the walk of the current screen); true when it built a chunk (something changed).
|
|
397
|
+
replayFrame(w) {
|
|
398
|
+
if (!this.replayOn)
|
|
399
|
+
return false;
|
|
400
|
+
return !!this.replay.frame(this.sessionId, this.sampled, w, this.now());
|
|
401
|
+
}
|
|
402
|
+
get replayBuffer() {
|
|
403
|
+
return this.replay;
|
|
210
404
|
}
|
|
211
405
|
scroll(depth, drag) {
|
|
212
406
|
const s = this.screenStats;
|
|
@@ -220,13 +414,37 @@ export class Analytics {
|
|
|
220
414
|
.split('\n')
|
|
221
415
|
.slice(1, 6)
|
|
222
416
|
.map((l) => l.trim().replace(/https?:\/\/[^\s)]+\//g, '').slice(0, 120));
|
|
223
|
-
this.push('error', err.name, { msg: err.message.slice(0, 200), fatal: fatal ? 1 : undefined, stack });
|
|
224
|
-
|
|
225
|
-
|
|
417
|
+
this.push('error', err.name, { msg: redact(err.message).slice(0, 200), fatal: fatal ? 1 : undefined, stack });
|
|
418
|
+
this.signal(fatal ? 'crash' : 'error');
|
|
419
|
+
if (!fatal)
|
|
420
|
+
return;
|
|
421
|
+
this.persist();
|
|
422
|
+
const out = this.replay.out;
|
|
423
|
+
if (out.length)
|
|
424
|
+
this.st?.set(K.replay, JSON.stringify({ a: this.anon, why: 'crash', chunks: out.map((b) => b.c) })).catch(() => { });
|
|
226
425
|
}
|
|
227
426
|
purchase(p) {
|
|
228
427
|
this.touch();
|
|
229
|
-
this.push('purchase', p.product, { product: p.product, status: p.status, price: p.price, currency: p.currency, store: p.store, trial: p.trial ? 1 : undefined });
|
|
428
|
+
this.push('purchase', p.product, { product: p.product, status: p.status, price: p.price, currency: p.currency, store: p.store, trial: p.trial ? 1 : undefined, renew: p.renew ? 1 : undefined, conv: p.conv ? 1 : undefined, at: p.at });
|
|
429
|
+
}
|
|
430
|
+
// Store truth: each entitlement's latest purchase against a per-product watermark. A newer one is a done (renew unless it
|
|
431
|
+
// is the subscription's first purchase, conv on the first paid period after a trial this install saw). Purchases from
|
|
432
|
+
// before this install's first launch, and quiet ones (restores, the wrapped call's own done), only move the watermark.
|
|
433
|
+
entitled(list, quiet = false, store = 'revenuecat') {
|
|
434
|
+
if (!this.loaded)
|
|
435
|
+
return void this.ready.then(() => this.entitled(list, quiet, store));
|
|
436
|
+
let dirty = false;
|
|
437
|
+
for (const e of list) {
|
|
438
|
+
const m = this.marks[e.product];
|
|
439
|
+
if (!e.product || !(e.at > 0) || (m && m.t >= e.at))
|
|
440
|
+
continue;
|
|
441
|
+
if (!quiet && e.at >= this.firstSeen)
|
|
442
|
+
this.purchase({ product: e.product, status: 'done', store, trial: e.trial, renew: !!m || (e.first !== undefined && e.at - e.first > 60000), conv: !!m?.tr && !e.trial, at: e.at });
|
|
443
|
+
this.marks[e.product] = e.trial ? { t: e.at, tr: 1 } : { t: e.at };
|
|
444
|
+
dirty = true;
|
|
445
|
+
}
|
|
446
|
+
if (dirty)
|
|
447
|
+
this.st?.set(K.purchases, JSON.stringify(this.marks)).catch(() => { });
|
|
230
448
|
}
|
|
231
449
|
// Wireframes are recorded once per screen per sampled session.
|
|
232
450
|
wantsSnapshot(screen) {
|
|
@@ -250,8 +468,9 @@ export class Analytics {
|
|
|
250
468
|
this.schedule();
|
|
251
469
|
}
|
|
252
470
|
background() {
|
|
471
|
+
this.settle(true);
|
|
253
472
|
this.leave();
|
|
254
|
-
this.push('close');
|
|
473
|
+
this.push('close', undefined, { perf: this.perf() });
|
|
255
474
|
this.active = false;
|
|
256
475
|
this.persist();
|
|
257
476
|
this.flush();
|
|
@@ -262,6 +481,7 @@ export class Analytics {
|
|
|
262
481
|
if (c === 'denied') {
|
|
263
482
|
this.queue = [];
|
|
264
483
|
this.snaps = [];
|
|
484
|
+
this.replay.clear();
|
|
265
485
|
this.persist();
|
|
266
486
|
}
|
|
267
487
|
else if (c === 'granted')
|
|
@@ -273,6 +493,26 @@ export class Analytics {
|
|
|
273
493
|
optIn() {
|
|
274
494
|
this.setConsent('granted');
|
|
275
495
|
}
|
|
496
|
+
// Right to be forgotten (PROTOCOL.md 7): drops everything still on the device (queue, wireframes, replay ring and a
|
|
497
|
+
// crash-saved ring), asks the server to delete what it recorded for this install (POST /analytics/v1/forget: events,
|
|
498
|
+
// wireframes, replay) and, once it has, starts over as a new anonymous install. Works whatever the consent. Resolves
|
|
499
|
+
// false when the server could not be reached; the id is kept so calling again retries.
|
|
500
|
+
async forget() {
|
|
501
|
+
await this.ready;
|
|
502
|
+
this.queue = [];
|
|
503
|
+
this.snaps = [];
|
|
504
|
+
this.replay.clear();
|
|
505
|
+
this.persist();
|
|
506
|
+
await this.st?.remove(K.replay).catch(() => { });
|
|
507
|
+
await this.inflight?.catch(() => { });
|
|
508
|
+
const f = this.cfg.fetch ?? fetch;
|
|
509
|
+
const ok = await f(this.cfg.serverUrl + '/analytics/v1/forget', { method: 'POST', headers: { 'content-type': 'application/json', 'x-shotik-key': this.cfg.appKey }, body: JSON.stringify({ anonymousId: this.anon }) })
|
|
510
|
+
.then((r) => r.ok)
|
|
511
|
+
.catch(() => false);
|
|
512
|
+
if (ok)
|
|
513
|
+
await this.reset();
|
|
514
|
+
return ok;
|
|
515
|
+
}
|
|
276
516
|
// Sign-out: a new anonymous id and session, nothing of the old user kept.
|
|
277
517
|
async reset() {
|
|
278
518
|
await this.flush();
|
|
@@ -291,7 +531,8 @@ export class Analytics {
|
|
|
291
531
|
}
|
|
292
532
|
async send() {
|
|
293
533
|
await this.ready;
|
|
294
|
-
|
|
534
|
+
this.settle(false);
|
|
535
|
+
if (this.sending || this.consent !== 'granted' || (!this.queue.length && !this.snaps.length && !this.replay.out.length))
|
|
295
536
|
return;
|
|
296
537
|
this.sending = true;
|
|
297
538
|
const events = this.queue.slice(0, BATCH);
|
|
@@ -308,10 +549,17 @@ export class Analytics {
|
|
|
308
549
|
}
|
|
309
550
|
else if (!r.ok)
|
|
310
551
|
throw new Error(String(r.status));
|
|
552
|
+
else
|
|
553
|
+
this.cost.eb += body.length;
|
|
311
554
|
this.queue.splice(0, events.length);
|
|
312
555
|
}
|
|
313
|
-
|
|
314
|
-
await f(this.cfg.serverUrl + '/analytics/v1/snapshots', { method: 'POST', headers, body: JSON.stringify({ anonymousId: this.anon, ...
|
|
556
|
+
while (snaps.length) {
|
|
557
|
+
const r = await f(this.cfg.serverUrl + '/analytics/v1/snapshots', { method: 'POST', headers, body: JSON.stringify({ anonymousId: this.anon, ...snaps[0] }) });
|
|
558
|
+
if (!r.ok && (r.status >= 500 || r.status === 429))
|
|
559
|
+
throw new Error(String(r.status));
|
|
560
|
+
snaps.shift();
|
|
561
|
+
}
|
|
562
|
+
await this.sendReplay(f, headers);
|
|
315
563
|
this.backoff = 0;
|
|
316
564
|
this.persist();
|
|
317
565
|
}
|
|
@@ -325,7 +573,32 @@ export class Analytics {
|
|
|
325
573
|
if (this.queue.length >= BATCH && !this.backoff)
|
|
326
574
|
return this.send();
|
|
327
575
|
}
|
|
576
|
+
// Replay chunks (PROTOCOL.md 4.7), up to 8 requests per flush. 403: replay is off or over quota for this app, so nothing
|
|
577
|
+
// more is captured or sent until the next launch. Wi-Fi only: held until wifi() says so.
|
|
578
|
+
async sendReplay(f, headers) {
|
|
579
|
+
const R = this.replay;
|
|
580
|
+
if (!R.out.length || R.off)
|
|
581
|
+
return;
|
|
582
|
+
const opt = this.cfg.replay;
|
|
583
|
+
if (opt && opt.wifiOnly && !(await (this.cfg.wifi?.() ?? Promise.resolve(false)).catch(() => false)))
|
|
584
|
+
return;
|
|
585
|
+
for (let n = 0; n < REPLAY_REQS; n++) {
|
|
586
|
+
const b = R.take();
|
|
587
|
+
if (!b)
|
|
588
|
+
return;
|
|
589
|
+
const body = '{"v":1,"a":' + JSON.stringify(this.anon) + ',"why":"' + b.why + '","chunks":[' + b.items.map((i) => i.s).join(',') + ']}';
|
|
590
|
+
const r = await f(this.cfg.serverUrl + '/analytics/v1/replay', { method: 'POST', headers, body });
|
|
591
|
+
if (r.status === 403)
|
|
592
|
+
return R.clear(true);
|
|
593
|
+
if (!r.ok && (r.status >= 500 || r.status === 429))
|
|
594
|
+
throw new Error(String(r.status));
|
|
595
|
+
if (r.ok)
|
|
596
|
+
this.cost.rb += body.length;
|
|
597
|
+
R.done(b.items);
|
|
598
|
+
}
|
|
599
|
+
}
|
|
328
600
|
stop() {
|
|
601
|
+
this.settle(true);
|
|
329
602
|
this.active = false;
|
|
330
603
|
if (this.timer)
|
|
331
604
|
clearTimeout(this.timer);
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export declare function redact(s: string): string;
|
|
2
|
+
export declare const PII_KEY: RegExp;
|
|
3
|
+
export declare function cleanProps(props: Record<string, unknown> | undefined, dev?: boolean, depth?: number): Record<string, unknown> | undefined;
|
|
4
|
+
export declare function idWords(id: string): string;
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
// On-device redaction shared by tap labels, error messages, custom props and network paths (PROTOCOL.md §7). Runs before
|
|
2
|
+
// anything is queued. Platform-free; the Swift and Flutter ports copy the rules and their order.
|
|
3
|
+
const RULES = [
|
|
4
|
+
[/(\bhttps?:\/\/[^\s?#]*)[?#][^\s]*/gi, '$1'],
|
|
5
|
+
[/\?[\w.%-]+=[^\s]*/g, ''],
|
|
6
|
+
[/\b(Bearer|Basic)\s+[\w.~+/=-]+/gi, '$1 [token]'],
|
|
7
|
+
[/\beyJ[\w-]{4,}\.[\w-]{4,}(?:\.[\w-]+)?/g, '[token]'],
|
|
8
|
+
[/[^\s@<>()"',;:]+@[^\s@<>()"',;:]+/g, '[email]'],
|
|
9
|
+
[/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi, '[id]'],
|
|
10
|
+
[/\b(?=[0-9a-f]*\d)[0-9a-f]{16,}\b/gi, '[id]'],
|
|
11
|
+
[/\b(?=[\w-]*\d)(?=[\w-]*[a-z])[\w-]{24,}/gi, '[token]'],
|
|
12
|
+
[/\+?\(?\d[\d\s().-]{5,}\d/g, (m) => ((m.match(/\d/g)?.length ?? 0) < 7 ? m : /^\+|[()]|\d\s\d/.test(m) ? '[phone]' : '[n]')],
|
|
13
|
+
[/\d{4,}/g, '[n]']
|
|
14
|
+
];
|
|
15
|
+
export function redact(s) {
|
|
16
|
+
let out = s;
|
|
17
|
+
for (const [re, to] of RULES)
|
|
18
|
+
out = out.replace(re, to);
|
|
19
|
+
return out;
|
|
20
|
+
}
|
|
21
|
+
export const PII_KEY = /email|phone|name|token|password|address/i;
|
|
22
|
+
const warned = new Set();
|
|
23
|
+
// Custom props and identify traits: personal-data keys dropped (one dev warning per key), string values redacted, 3 levels deep.
|
|
24
|
+
export function cleanProps(props, dev = false, depth = 0) {
|
|
25
|
+
if (!props || typeof props !== 'object')
|
|
26
|
+
return props;
|
|
27
|
+
const out = {};
|
|
28
|
+
const val = (v) => (typeof v === 'string' ? redact(v) : v && typeof v === 'object' ? (depth < 2 && !Array.isArray(v) ? cleanProps(v, dev, depth + 1) : undefined) : v);
|
|
29
|
+
for (const k in props) {
|
|
30
|
+
if (PII_KEY.test(k)) {
|
|
31
|
+
if (dev && !warned.has(k)) {
|
|
32
|
+
warned.add(k);
|
|
33
|
+
console.warn('[shotik] dropped the prop "' + k + '": keys like email, phone, name, token, password or address never leave the device');
|
|
34
|
+
}
|
|
35
|
+
continue;
|
|
36
|
+
}
|
|
37
|
+
const v = props[k];
|
|
38
|
+
out[k] = Array.isArray(v) ? v.map(val) : val(v);
|
|
39
|
+
}
|
|
40
|
+
return out;
|
|
41
|
+
}
|
|
42
|
+
// A testID as words for a label: startTrialButton, start-trial, plan_card.annual -> "Start trial button", "Start trial", "Plan card annual".
|
|
43
|
+
export function idWords(id) {
|
|
44
|
+
const w = id.replace(/([a-z\d])([A-Z])/g, '$1 $2').replace(/[-_.:/#]+/g, ' ').replace(/\s+/g, ' ').trim().toLowerCase();
|
|
45
|
+
return w.charAt(0).toUpperCase() + w.slice(1);
|
|
46
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import type { KeyedNode, ReplayChunk, ReplayScroll, ReplayWhy } from './wire';
|
|
2
|
+
export interface ReplayWalk {
|
|
3
|
+
screen: string;
|
|
4
|
+
w: number;
|
|
5
|
+
h: number;
|
|
6
|
+
nodes: KeyedNode[];
|
|
7
|
+
scroll: ReplayScroll[];
|
|
8
|
+
}
|
|
9
|
+
export interface Built {
|
|
10
|
+
c: ReplayChunk;
|
|
11
|
+
s: string;
|
|
12
|
+
key: boolean;
|
|
13
|
+
why: ReplayWhy;
|
|
14
|
+
}
|
|
15
|
+
export declare const RING_MS = 30000;
|
|
16
|
+
export declare const MAX_BYTES: number;
|
|
17
|
+
export declare class Replay {
|
|
18
|
+
out: Built[];
|
|
19
|
+
off: boolean;
|
|
20
|
+
private ring;
|
|
21
|
+
private why;
|
|
22
|
+
private sess;
|
|
23
|
+
private seq;
|
|
24
|
+
private prev;
|
|
25
|
+
private screen;
|
|
26
|
+
private offsets;
|
|
27
|
+
private lastKey;
|
|
28
|
+
private tail;
|
|
29
|
+
frame(sess: string, sampled: boolean, w: ReplayWalk, t: number): ReplayChunk | null;
|
|
30
|
+
signal(why: ReplayWhy, t: number): void;
|
|
31
|
+
private trimRing;
|
|
32
|
+
private cap;
|
|
33
|
+
get ringBytes(): number;
|
|
34
|
+
take(): {
|
|
35
|
+
why: ReplayWhy;
|
|
36
|
+
items: Built[];
|
|
37
|
+
} | null;
|
|
38
|
+
done(items: Built[]): void;
|
|
39
|
+
restore(why: ReplayWhy, chunks: ReplayChunk[]): void;
|
|
40
|
+
clear(stop?: boolean): void;
|
|
41
|
+
}
|