@shotik/react-native 0.1.1 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/LICENSE +26 -0
  3. package/README.md +36 -1
  4. package/README.ru.md +37 -1
  5. package/dist/analytics/core.d.ts +111 -12
  6. package/dist/analytics/core.js +303 -22
  7. package/dist/analytics/privacy.d.ts +4 -0
  8. package/dist/analytics/privacy.js +46 -0
  9. package/dist/analytics/replay.d.ts +41 -0
  10. package/dist/analytics/replay.js +192 -0
  11. package/dist/analytics/rn.d.ts +53 -2
  12. package/dist/analytics/rn.js +687 -63
  13. package/dist/analytics/wire.d.ts +54 -2
  14. package/dist/analytics/wire.js +44 -4
  15. package/dist/client.d.ts +93 -0
  16. package/dist/client.js +247 -9
  17. package/dist/flow.d.ts +48 -0
  18. package/dist/flow.js +56 -0
  19. package/dist/index.d.ts +4 -4
  20. package/dist/index.js +2 -2
  21. package/dist/parts.d.ts +42 -1
  22. package/dist/parts.js +72 -14
  23. package/dist/react.d.ts +24 -3
  24. package/dist/react.js +42 -15
  25. package/dist/sheet.d.ts +2 -1
  26. package/dist/sheet.js +206 -15
  27. package/dist/support.js +2 -2
  28. package/dist/theme.d.ts +43 -0
  29. package/dist/theme.js +88 -2
  30. package/package.json +15 -2
  31. package/recipe.json +1 -1
  32. package/src/analytics/README.md +10 -6
  33. package/src/analytics/core.ts +324 -25
  34. package/src/analytics/privacy.ts +50 -0
  35. package/src/analytics/recipe.json +1 -1
  36. package/src/analytics/replay.ts +190 -0
  37. package/src/analytics/rn.tsx +636 -64
  38. package/src/analytics/wire.ts +101 -8
  39. package/src/client.ts +334 -9
  40. package/src/flow.ts +100 -0
  41. package/src/index.ts +4 -4
  42. package/src/parts.tsx +102 -14
  43. package/src/react.tsx +57 -16
  44. package/src/sheet.tsx +422 -19
  45. package/src/support.ts +2 -2
  46. package/src/theme.ts +88 -2
@@ -1,12 +1,44 @@
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
+ export const SHEET_STATUS = { shown: 'shown', confirmed: 'done', cancelled: 'cancel', failed: 'fail', pending: 'pending', not_shown: 'not_shown' };
7
+ 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
8
  const MAX_QUEUE = 2000;
6
9
  const BATCH = 300;
7
10
  const RAGE_N = 3;
8
11
  const RAGE_MS = 800;
9
12
  const RAGE_PT = 40;
13
+ const RESP_MS = 1500;
14
+ const NET_SLOW_MS = 3000;
15
+ const ERRTAP_MS = 2000;
16
+ const REPLAY_REQS = 8;
17
+ // The SDK's own cost this session (perf on close): the last 256 samples per path, bytes uploaded.
18
+ const costs = () => ({ tap: [], walk: [], fp: [], rb: 0, eb: 0 });
19
+ const p95 = (a) => {
20
+ if (!a.length)
21
+ return undefined;
22
+ const s = a.slice().sort((x, y) => x - y);
23
+ return Math.round(s[Math.ceil(s.length * 0.95) - 1] * 1000) / 1000;
24
+ };
25
+ // Sent as `sdk: 'rn/<version>'` in the device context. Keep equal to package.json (a unit test checks it).
26
+ export const SDK_VERSION = '0.2.2';
27
+ // A request URL as host + path template: no scheme, credentials, query or fragment; ids, UUIDs, hex, digit runs, tokens
28
+ // of 8+ characters with 2+ digits, emails, anything redact() changes and percent-encoded or non-ASCII segments become :id
29
+ // (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.
30
+ export function netTarget(url) {
31
+ const m = /^(?:[a-z][a-z0-9+.-]*:)?\/\/([^/?#]*)([^?#]*)/i.exec(url);
32
+ const host = (m ? m[1] : '').replace(/^.*@/, '').toLowerCase();
33
+ const raw = m ? m[2] : url.replace(/[?#].*$/, '');
34
+ 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;
35
+ const seg = (s) => {
36
+ const x = /^(.+)(\.[a-z0-9]{1,5})$/i.exec(s);
37
+ return x && id(x[1]) && !/@|%40/.test(s) ? ':id' + x[2] : id(s) ? ':id' : s;
38
+ };
39
+ const path = raw.split('/').map(seg).join('/').slice(0, 120);
40
+ return { host, path: path || '/' };
41
+ }
10
42
  const rnd = () => Math.random().toString(36).slice(2, 10);
11
43
  const uid = () => Date.now().toString(36) + rnd() + rnd();
12
44
  export class Analytics {
@@ -23,6 +55,10 @@ export class Analytics {
23
55
  this.screenAt = 0;
24
56
  this.screenStats = { depth: 0, drag: 0, stalls: 0, maxStall: 0 };
25
57
  this.taps = [];
58
+ this.held = null;
59
+ this.waiting = [];
60
+ this.states = false;
61
+ this.marks = {};
26
62
  this.snapped = new Set();
27
63
  this.timer = null;
28
64
  this.saveTimer = null;
@@ -32,6 +68,9 @@ export class Analytics {
32
68
  this.active = true;
33
69
  this.loaded = false;
34
70
  this.fresh = true;
71
+ this.replay = new Replay();
72
+ this.cost = costs();
73
+ this.lastTap = { ts: -Infinity };
35
74
  this.cfg = cfg;
36
75
  this.st = cfg.storage ?? null;
37
76
  this.now = cfg.now ?? Date.now;
@@ -42,7 +81,7 @@ export class Analytics {
42
81
  const st = this.st;
43
82
  if (st) {
44
83
  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)]);
84
+ 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
85
  this.anon = anon ?? '';
47
86
  const s = raw ? JSON.parse(raw) : null;
48
87
  if (s) {
@@ -58,6 +97,14 @@ export class Analytics {
58
97
  this.queue = JSON.parse(q).concat(this.queue).slice(-MAX_QUEUE);
59
98
  if (c === 'granted' || c === 'denied')
60
99
  this.consent = c;
100
+ if (pm)
101
+ this.marks = JSON.parse(pm) ?? {};
102
+ if (rp) {
103
+ const r = JSON.parse(rp);
104
+ if (Array.isArray(r?.chunks))
105
+ this.replay.restore(r.why ?? 'crash', r.chunks);
106
+ st.remove(K.replay).catch(() => { });
107
+ }
61
108
  }
62
109
  catch {
63
110
  this.storeIssue = 'error';
@@ -98,20 +145,22 @@ export class Analytics {
98
145
  this.seq = 0;
99
146
  this.sampled = Math.random() < (this.cfg.snapshots ?? 0.2);
100
147
  this.snapped.clear();
148
+ this.cost = costs();
101
149
  this.lastActive = t;
102
150
  const props = { ...(first && { first: 1 }), ...(this.storeIssue && { store: this.storeIssue }) };
103
151
  this.push('session', undefined, Object.keys(props).length ? props : undefined, t);
104
152
  }
105
153
  this.lastActive = t;
106
154
  }
107
- push(type, name, props, ts) {
155
+ push(type, name, props, ts, screen = this.screen) {
108
156
  if (this.consent === 'denied')
109
157
  return;
110
- this.queue.push({ seq: ++this.seq, ts: ts ?? this.now(), type, sessionId: this.sessionId, screen: this.screen, name, props });
158
+ this.queue.push({ seq: ++this.seq, ts: ts ?? this.now(), type, sessionId: this.sessionId, screen, name, props });
111
159
  if (this.queue.length > MAX_QUEUE)
112
160
  this.queue.splice(0, this.queue.length - MAX_QUEUE);
113
161
  if (this.cfg.debug)
114
162
  console.log('[shotik]', type, name ?? '', this.screen ?? '', props ?? '');
163
+ this.cfg.onEvent?.(type, name, this.screen, props);
115
164
  this.save();
116
165
  if (this.queue.length >= BATCH)
117
166
  this.flush();
@@ -140,13 +189,25 @@ export class Analytics {
140
189
  }, (this.cfg.flushMs ?? 10000) * Math.pow(2, this.backoff));
141
190
  }
142
191
  // Public API
192
+ get dev() {
193
+ return !!(this.cfg.debug || globalThis.__DEV__);
194
+ }
195
+ // A connection check: one test event, sent now. It goes through the same queue, key and route as everything else, flagged
196
+ // kind 'test', so the server shows "Test event received" and never counts it as a session, a user or a metric.
197
+ sendTestEvent() {
198
+ if (this.consent === 'denied')
199
+ return Promise.resolve();
200
+ this.queue.push({ seq: ++this.seq, ts: this.now(), type: 'custom', sessionId: this.sessionId || 'test_' + this.anon, name: 'shotik_test', kind: 'test' });
201
+ return this.flush();
202
+ }
203
+ // Personal-data keys are dropped and string values redacted on the device (privacy.ts).
143
204
  track(name, props) {
144
205
  this.touch();
145
- this.push('custom', name, props);
206
+ this.push('custom', redact(name), cleanProps(props, this.dev));
146
207
  }
147
208
  identify(userId, traits) {
148
209
  this.userId = userId;
149
- this.push('identify', undefined, traits ? { traits } : undefined);
210
+ this.push('identify', undefined, traits ? { traits: cleanProps(traits, this.dev) } : undefined);
150
211
  }
151
212
  // Screen change: closes the previous screen with its time and scroll depth.
152
213
  screenView(name) {
@@ -154,7 +215,10 @@ export class Analytics {
154
215
  return;
155
216
  this.touch();
156
217
  const from = this.screen;
218
+ this.drain(true);
219
+ this.respond(true);
157
220
  this.leave();
221
+ this.stateH = undefined;
158
222
  this.screen = name;
159
223
  this.screenAt = this.now();
160
224
  this.push('screen', name, from ? { from } : undefined);
@@ -189,24 +253,155 @@ export class Analytics {
189
253
  if (ms > 1000)
190
254
  this.push('slow', this.screen, { ms: Math.round(ms), kind: 'stall' });
191
255
  }
192
- // A tap with its element identity. dead = nothing on the touched element handles presses.
256
+ // A tap with its element identity. dead = nothing on the touched element handles presses; it stays dead unless the
257
+ // screen changes within RESP_MS. The tap is queued once it is resolved: on its response, the next tap, or RESP_MS
258
+ // later (checked on every flush), with its own ts and screen. resp = ms to the first screen change or request start,
259
+ // 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
260
  tap(t) {
194
261
  this.touch();
195
262
  const now = t.ts ?? this.now();
196
- const p = { el: t.el, x: Math.round(t.x), y: Math.round(t.y), nx: t.nx, ny: t.ny };
263
+ this.release();
264
+ const h = { t, ts: now, screen: this.screen };
265
+ this.lastTap = { ts: now, screen: this.screen };
266
+ this.taps = this.taps.filter((q) => now - q.t < RAGE_MS && Math.hypot(q.x - t.x, q.y - t.y) < RAGE_PT);
267
+ this.taps.push({ x: t.x, y: t.y, t: now, h });
268
+ if (this.taps.length === RAGE_N)
269
+ h.burst = this.taps.map((q) => q.h);
270
+ this.held = h;
271
+ }
272
+ respond(screen) {
273
+ const h = this.held;
274
+ if (!h)
275
+ return;
276
+ const dt = this.now() - h.ts;
277
+ if (dt > RESP_MS)
278
+ return this.release();
279
+ h.resp ?? (h.resp = Math.max(0, Math.round(dt)));
280
+ if (screen) {
281
+ h.moved = true;
282
+ this.release();
283
+ }
284
+ }
285
+ settle(all) {
286
+ if (this.held && (all || this.now() - this.held.ts > RESP_MS))
287
+ this.release();
288
+ this.drain(all);
289
+ }
290
+ // While UI-state fingerprints run (uiState was called), a resolved tap with no response waits for the next walk.
291
+ release() {
292
+ const h = this.held;
293
+ if (!h)
294
+ return;
295
+ this.held = null;
296
+ if (this.states && !h.checked && h.resp === undefined && !h.t.dead && !h.t.input)
297
+ return void this.waiting.push(h);
298
+ this.emit(h);
299
+ }
300
+ drain(all) {
301
+ const now = this.now();
302
+ while (this.waiting.length && (all || now - this.waiting[0].ts > RESP_MS))
303
+ this.emit(this.waiting.shift());
304
+ }
305
+ emit(h) {
306
+ const t = h.t;
307
+ const dead = t.dead && !h.moved;
308
+ if (dead)
309
+ h.resp = undefined;
310
+ const at = t.masked ? {} : { x: Math.round(t.x), y: Math.round(t.y) };
311
+ const p = { el: t.el, ...at, ...(!t.masked && { nx: t.nx, ny: t.ny }) };
197
312
  if (t.id)
198
313
  p.id = t.id;
199
314
  if (t.label)
200
315
  p.label = t.label;
201
- if (t.dead)
316
+ if (dead)
202
317
  p.dead = 1;
203
318
  if (t.input)
204
319
  p.input = 1;
205
- this.push('tap', undefined, p, now);
206
- this.taps = this.taps.filter((q) => now - q.t < RAGE_MS && Math.hypot(q.x - t.x, q.y - t.y) < RAGE_PT);
207
- this.taps.push({ el: t.el, id: t.id, label: t.label, x: t.x, y: t.y, t: now });
208
- if (this.taps.length === RAGE_N)
209
- this.push('rage', undefined, { el: t.el, id: t.id, label: t.label, n: RAGE_N, x: Math.round(t.x), y: Math.round(t.y) }, now);
320
+ if (h.resp !== undefined)
321
+ p.resp = h.resp;
322
+ this.push('tap', undefined, p, h.ts, h.screen);
323
+ const rage = h.burst?.some((b) => b.resp === undefined);
324
+ if (rage)
325
+ this.push('rage', undefined, { el: t.el, id: t.id, label: t.label, n: RAGE_N, ...at }, h.ts, h.screen);
326
+ if (rage || dead || (!t.input && h.resp === undefined))
327
+ this.signal(rage ? 'rage' : dead ? 'dead' : 'unresponsive');
328
+ }
329
+ // A replay signal (PROTOCOL.md 4.7): an unsampled session's ring of the last 30 s is released for upload.
330
+ signal(why) {
331
+ this.replay.signal(why, this.now());
332
+ }
333
+ // A UI-state fingerprint walk finished (h null: none possible). The first one on a screen is its baseline; a different h
334
+ // later on the same screen is a `state` event and the response of every tap waiting for this walk. quiet (after a
335
+ // vertical scroll) only moves the baseline.
336
+ uiState(h, n = 0, quiet = false) {
337
+ this.states = true;
338
+ const changed = h !== null && this.stateH !== undefined && h !== this.stateH && !quiet;
339
+ if (h !== null)
340
+ this.stateH = h;
341
+ if (changed) {
342
+ const now = this.now();
343
+ for (const w of this.waiting)
344
+ if (now - w.ts <= RESP_MS)
345
+ w.resp = Math.round(now - w.ts);
346
+ this.respond(false);
347
+ }
348
+ if (this.held)
349
+ this.held.checked = true;
350
+ this.drain(true);
351
+ if (changed)
352
+ this.push('state', undefined, { h, n });
353
+ return changed;
354
+ }
355
+ // One focus span of a text input: ts = focus time, ms focused, edits (none for secure inputs), filled. Never a value or length.
356
+ field(f) {
357
+ this.touch();
358
+ 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);
359
+ }
360
+ // A request started (wrapped fetch / XMLHttpRequest): a response to the newest tap.
361
+ netStart() {
362
+ this.respond(false);
363
+ }
364
+ // A finished request; only failures (status >= 400, 0 = network error) and slow calls (> 3 s) become `net` events.
365
+ net(method, url, status, ms) {
366
+ if (status > 0 && status < 400 && ms <= NET_SLOW_MS)
367
+ return;
368
+ const { host, path } = netTarget(url);
369
+ this.push('net', undefined, { m: method.toUpperCase().slice(0, 10), host, path, s: status, ms: Math.round(ms) });
370
+ if ((status === 0 || status >= 400) && this.now() - this.lastTap.ts <= ERRTAP_MS && this.lastTap.screen === this.screen)
371
+ this.signal('errtap');
372
+ }
373
+ // A touch that was neither a tap nor a scroll (PROTOCOL.md 4.1 touch classes). ts = the touch start.
374
+ gesture(g) {
375
+ this.touch();
376
+ 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);
377
+ }
378
+ // A container a touch scrolled settled at a new offset. ts = the touch end.
379
+ scrolled(s) {
380
+ this.touch();
381
+ 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);
382
+ }
383
+ // Self-cost samples (ms) for perf on close: the touch-end handler, a replay capture, a fingerprint walk.
384
+ measure(kind, ms) {
385
+ const a = this.cost[kind];
386
+ a.push(ms);
387
+ if (a.length > 256)
388
+ a.shift();
389
+ }
390
+ perf() {
391
+ const c = this.cost;
392
+ return { tap: p95(c.tap), walk: p95(c.walk), fp: p95(c.fp), rb: c.rb, eb: c.eb };
393
+ }
394
+ get replayOn() {
395
+ return this.cfg.replay !== false && this.loaded && this.active && this.consent !== 'denied' && !this.replay.off;
396
+ }
397
+ // One replay capture (the walk of the current screen); true when it built a chunk (something changed).
398
+ replayFrame(w) {
399
+ if (!this.replayOn)
400
+ return false;
401
+ return !!this.replay.frame(this.sessionId, this.sampled, w, this.now());
402
+ }
403
+ get replayBuffer() {
404
+ return this.replay;
210
405
  }
211
406
  scroll(depth, drag) {
212
407
  const s = this.screenStats;
@@ -220,13 +415,44 @@ export class Analytics {
220
415
  .split('\n')
221
416
  .slice(1, 6)
222
417
  .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
- if (fatal)
225
- this.persist();
418
+ this.push('error', err.name, { msg: redact(err.message).slice(0, 200), fatal: fatal ? 1 : undefined, stack });
419
+ this.signal(fatal ? 'crash' : 'error');
420
+ if (!fatal)
421
+ return;
422
+ this.persist();
423
+ const out = this.replay.out;
424
+ if (out.length)
425
+ this.st?.set(K.replay, JSON.stringify({ a: this.anon, why: 'crash', chunks: out.map((b) => b.c) })).catch(() => { });
226
426
  }
227
427
  purchase(p) {
228
428
  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 });
429
+ 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, ps: p.ps?.slice(0, 32), code: p.code?.slice(0, 40), sf: p.sf?.slice(0, 3) });
430
+ }
431
+ // What happened at the store's purchase sheet for one buy tap; outcomes map onto the purchase statuses.
432
+ sheet(p) {
433
+ const status = SHEET_STATUS[p.outcome];
434
+ if (!status)
435
+ return;
436
+ this.purchase({ product: p.product, status, currency: p.currency, store: p.store, ps: p.priceString, code: p.code, sf: p.storefront });
437
+ }
438
+ // Store truth: each entitlement's latest purchase against a per-product watermark. A newer one is a done (renew unless it
439
+ // is the subscription's first purchase, conv on the first paid period after a trial this install saw). Purchases from
440
+ // before this install's first launch, and quiet ones (restores, the wrapped call's own done), only move the watermark.
441
+ entitled(list, quiet = false, store = 'revenuecat') {
442
+ if (!this.loaded)
443
+ return void this.ready.then(() => this.entitled(list, quiet, store));
444
+ let dirty = false;
445
+ for (const e of list) {
446
+ const m = this.marks[e.product];
447
+ if (!e.product || !(e.at > 0) || (m && m.t >= e.at))
448
+ continue;
449
+ if (!quiet && e.at >= this.firstSeen)
450
+ 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 });
451
+ this.marks[e.product] = e.trial ? { t: e.at, tr: 1 } : { t: e.at };
452
+ dirty = true;
453
+ }
454
+ if (dirty)
455
+ this.st?.set(K.purchases, JSON.stringify(this.marks)).catch(() => { });
230
456
  }
231
457
  // Wireframes are recorded once per screen per sampled session.
232
458
  wantsSnapshot(screen) {
@@ -250,8 +476,9 @@ export class Analytics {
250
476
  this.schedule();
251
477
  }
252
478
  background() {
479
+ this.settle(true);
253
480
  this.leave();
254
- this.push('close');
481
+ this.push('close', undefined, { perf: this.perf() });
255
482
  this.active = false;
256
483
  this.persist();
257
484
  this.flush();
@@ -262,6 +489,7 @@ export class Analytics {
262
489
  if (c === 'denied') {
263
490
  this.queue = [];
264
491
  this.snaps = [];
492
+ this.replay.clear();
265
493
  this.persist();
266
494
  }
267
495
  else if (c === 'granted')
@@ -273,6 +501,26 @@ export class Analytics {
273
501
  optIn() {
274
502
  this.setConsent('granted');
275
503
  }
504
+ // Right to be forgotten (PROTOCOL.md 7): drops everything still on the device (queue, wireframes, replay ring and a
505
+ // crash-saved ring), asks the server to delete what it recorded for this install (POST /analytics/v1/forget: events,
506
+ // wireframes, replay) and, once it has, starts over as a new anonymous install. Works whatever the consent. Resolves
507
+ // false when the server could not be reached; the id is kept so calling again retries.
508
+ async forget() {
509
+ await this.ready;
510
+ this.queue = [];
511
+ this.snaps = [];
512
+ this.replay.clear();
513
+ this.persist();
514
+ await this.st?.remove(K.replay).catch(() => { });
515
+ await this.inflight?.catch(() => { });
516
+ const f = this.cfg.fetch ?? fetch;
517
+ 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 }) })
518
+ .then((r) => r.ok)
519
+ .catch(() => false);
520
+ if (ok)
521
+ await this.reset();
522
+ return ok;
523
+ }
276
524
  // Sign-out: a new anonymous id and session, nothing of the old user kept.
277
525
  async reset() {
278
526
  await this.flush();
@@ -291,7 +539,8 @@ export class Analytics {
291
539
  }
292
540
  async send() {
293
541
  await this.ready;
294
- if (this.sending || this.consent !== 'granted' || (!this.queue.length && !this.snaps.length))
542
+ this.settle(false);
543
+ if (this.sending || this.consent !== 'granted' || (!this.queue.length && !this.snaps.length && !this.replay.out.length))
295
544
  return;
296
545
  this.sending = true;
297
546
  const events = this.queue.slice(0, BATCH);
@@ -308,10 +557,17 @@ export class Analytics {
308
557
  }
309
558
  else if (!r.ok)
310
559
  throw new Error(String(r.status));
560
+ else
561
+ this.cost.eb += body.length;
311
562
  this.queue.splice(0, events.length);
312
563
  }
313
- for (const s of snaps)
314
- await f(this.cfg.serverUrl + '/analytics/v1/snapshots', { method: 'POST', headers, body: JSON.stringify({ anonymousId: this.anon, ...s }) });
564
+ while (snaps.length) {
565
+ const r = await f(this.cfg.serverUrl + '/analytics/v1/snapshots', { method: 'POST', headers, body: JSON.stringify({ anonymousId: this.anon, ...snaps[0] }) });
566
+ if (!r.ok && (r.status >= 500 || r.status === 429))
567
+ throw new Error(String(r.status));
568
+ snaps.shift();
569
+ }
570
+ await this.sendReplay(f, headers);
315
571
  this.backoff = 0;
316
572
  this.persist();
317
573
  }
@@ -325,7 +581,32 @@ export class Analytics {
325
581
  if (this.queue.length >= BATCH && !this.backoff)
326
582
  return this.send();
327
583
  }
584
+ // Replay chunks (PROTOCOL.md 4.7), up to 8 requests per flush. 403: replay is off or over quota for this app, so nothing
585
+ // more is captured or sent until the next launch. Wi-Fi only: held until wifi() says so.
586
+ async sendReplay(f, headers) {
587
+ const R = this.replay;
588
+ if (!R.out.length || R.off)
589
+ return;
590
+ const opt = this.cfg.replay;
591
+ if (opt && opt.wifiOnly && !(await (this.cfg.wifi?.() ?? Promise.resolve(false)).catch(() => false)))
592
+ return;
593
+ for (let n = 0; n < REPLAY_REQS; n++) {
594
+ const b = R.take();
595
+ if (!b)
596
+ return;
597
+ const body = '{"v":1,"a":' + JSON.stringify(this.anon) + ',"why":"' + b.why + '","chunks":[' + b.items.map((i) => i.s).join(',') + ']}';
598
+ const r = await f(this.cfg.serverUrl + '/analytics/v1/replay', { method: 'POST', headers, body });
599
+ if (r.status === 403)
600
+ return R.clear(true);
601
+ if (!r.ok && (r.status >= 500 || r.status === 429))
602
+ throw new Error(String(r.status));
603
+ if (r.ok)
604
+ this.cost.rb += body.length;
605
+ R.done(b.items);
606
+ }
607
+ }
328
608
  stop() {
609
+ this.settle(true);
329
610
  this.active = false;
330
611
  if (this.timer)
331
612
  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
+ }