@shotik/react-native 0.1.1 → 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.
Files changed (46) hide show
  1. package/CHANGELOG.md +16 -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 +96 -11
  6. package/dist/analytics/core.js +295 -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 +52 -2
  12. package/dist/analytics/rn.js +669 -62
  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 +314 -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 +620 -63
  38. package/src/analytics/wire.ts +99 -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
@@ -6,7 +6,7 @@ See how people really use your app (what they tap, where they get stuck, which s
6
6
  import { ShotikAnalytics, ShotikAnalyticsRoot, ShotikMask, useShotikExpoRouter } from '@shotik/react-native/analytics'
7
7
 
8
8
  ShotikAnalytics.init({ appKey: 'spk_…', serverUrl: 'https://…' }) // the same key as Support
9
- ShotikAnalytics.trackRevenueCat(Purchases) // optional: purchase start / done / cancel / fail
9
+ ShotikAnalytics.trackRevenueCat(Purchases) // optional: purchases, renewals and trial conversions
10
10
 
11
11
  export default function RootLayout() {
12
12
  useShotikExpoRouter() // React Navigation: ShotikAnalytics.trackNavigation(ref)
@@ -17,15 +17,19 @@ ShotikAnalytics.track('walk_started', { minutes: 10 }) // your own
17
17
  ShotikAnalytics.identify(user.id) // after sign-in; ShotikAnalytics.reset() on sign-out
18
18
  ```
19
19
 
20
- **What it captures on its own:** sessions, app open and close, screens (route patterns, never params), time on screen and scroll depth, taps with the element and position (for heatmaps), rage taps and taps that do nothing, JS errors and crashes, slow screens and JS stalls, purchases (RevenueCat) and, for 20% of sessions, wireframes of each screen.
20
+ **What it captures on its own:** sessions, app open and close, screens (route patterns, never params), time on screen and scroll depth, taps with the element and position (for heatmaps), rage taps, taps that do nothing and how fast each tap got a response, in-screen steps (a fingerprint of which buttons are on screen, so onboarding pagers and multi-step paywalls split into steps), how long people spend in each text field (never what they type), JS errors and crashes, failed and slow network requests (method, host and a templated path only), slow screens and JS stalls, purchases, renewals and trial conversions (RevenueCat, from its customerInfo listener), the release (app version, build, Expo update id and channel when expo-updates is installed) gestures (long press, swipe, pan, pinch) and where each scroll container settled (with the carousel page), and, for 20% of sessions, wireframes of each screen plus a wireframe replay. Every other session keeps the last 30 s of replay in memory and sends it only after a rage, dead, unresponsive or error tap, an error or a crash, so a calm session sends none. `replay: false` turns replay off; `replay: { wifiOnly: true }` sends it only on Wi-Fi (needs `@react-native-community/netinfo` or `expo-network`). Each session's last close carries what the SDK itself cost (p95 tap and walk ms, bytes sent).
21
21
 
22
22
  **Privacy by default:**
23
- - It never reads text input values.
24
- - Tap labels keep only short control text, with digits and emails masked.
23
+ - It never reads text input values. Field timing carries how long a field was focused, an edit count and whether it ended up filled.
24
+ - Tap labels are accessibility labels (or a name made from the testID) by default: `labels: 'visible'` also sends short visible control text, `labels: 'none'` sends none. Emails, phone numbers, long numbers, ids and tokens are redacted on the device, here and in error messages, custom props and request paths.
25
+ - Custom prop keys that look like personal data (`email`, `phone`, `name`, `token`, `password`, `address`) are dropped, with a warning in development.
26
+ - Replay is wireframes too: boxes, text bars and one box for inputs, masked views and web views; gestures and scrolls carry distances and offsets, never touch positions.
25
27
  - Wireframes are on for 20% of sessions by default (`snapshots: 0.2`; `snapshots: 0` turns them off). They hold boxes only (kind and position), draw text as bars with no characters, and contain no images.
26
- - `<ShotikMask>` hides a view from both.
28
+ - `<ShotikMask>` (or `shotikMask` on any view) hides it from labels, wireframes, replay and tap positions; secure text inputs are always masked. Masking can't be turned off: there is no option that unmasks inputs, and replay never reads text from any view, masked or not.
27
29
  - `init({ consent: 'pending' })` keeps events on the device until `ShotikAnalytics.setConsent('granted')`. `optOut()` drops them.
28
- - The server deletes an install's data on `POST /analytics/v1/forget`.
30
+ - `ShotikAnalytics.forget()` answers a user's data deletion request: it drops what is still on the device, has the server delete everything recorded for the install (events, wireframes, replay) and starts over as a new install. It resolves `false` when the server can't be reached; call it again to retry.
31
+
32
+ **What replay collects** (for the App Store privacy label, all under Product Interaction, not linked to the user, used for analytics): screen layouts as boxes (kind, position, size, background color, corner radius), the screen's route pattern, scroll offsets, gesture kinds with distances, and the session and install ids it belongs to. Never text, input values, images, web content or touch positions. Keyframes and diffs are kept 30 days unless an insight cites the session.
29
33
 
30
34
  **Footprint:** a single capture-phase touch listener, a 500 ms stall timer, and batched uploads (up to 300 events every 10 s and on background). Batches are dictionary-packed, and the queue persists offline. Nothing runs on the touch path except an O(depth) walk up the tree.
31
35
 
@@ -1,8 +1,11 @@
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
3
 
4
+ import { cleanProps, redact } from './privacy'
5
+ import { Replay } from './replay'
6
+ import type { ReplayWalk } from './replay'
4
7
  import { pack } from './wire'
5
- import type { DeviceContext, EventType, WireEvent, Wireframe } from './wire'
8
+ import type { DeviceContext, EventType, ReplayChunk, ReplayWhy, WireEvent, Wireframe } from './wire'
6
9
 
7
10
  export interface Storage {
8
11
  get(key: string): Promise<string | null>
@@ -21,28 +24,84 @@ export interface AnalyticsConfig {
21
24
  consent?: Consent
22
25
  // Share of sessions that record wireframes (0..1). Default 0.2.
23
26
  snapshots?: number
27
+ // Tap labels: 'a11y' (default) the accessibility label or a testID-derived name only, 'visible' also the visible text, 'none' no labels.
28
+ labels?: 'a11y' | 'visible' | 'none'
29
+ // Wireframe replay (PROTOCOL.md 4.7): on by default; false turns it off, wifiOnly holds uploads off Wi-Fi (wifi() answers).
30
+ replay?: false | { wifiOnly?: boolean }
31
+ wifi?: () => Promise<boolean>
24
32
  flushMs?: number
25
33
  sessionTimeoutMs?: number
26
34
  debug?: boolean
27
35
  fetch?: typeof fetch
28
36
  now?: () => number
37
+ // Every recorded event, as it is queued (the support widget's friction chip listens here, PROTOCOL.md §3.12).
38
+ onEvent?: (type: EventType, name: string | undefined, screen: string | undefined, props: Record<string, unknown> | undefined) => void
39
+ }
40
+
41
+ // masked: inside <ShotikMask> or a secure text input; x/y still feed rage detection but never leave the device.
42
+ type TapInput = { el: string; id?: string; label?: string; x: number; y: number; nx: number; ny: number; dead?: boolean; input?: boolean; masked?: boolean; ts?: number }
43
+
44
+ // An active store entitlement (RevenueCat customerInfo): product, its latest purchase and first purchase (ms), trial period.
45
+ export type Entitled = { product: string; at: number; first?: number; trial?: boolean }
46
+
47
+ // The newest tap waits for a response (a screen change or a request start) for up to RESP_MS, or until the next tap.
48
+ interface Held {
49
+ t: TapInput
50
+ ts: number
51
+ screen?: string
52
+ resp?: number
53
+ moved?: boolean
54
+ checked?: boolean
55
+ burst?: Held[]
29
56
  }
30
57
 
31
58
  interface Pending {
32
- el: string
33
- id?: string
34
- label?: string
35
59
  x: number
36
60
  y: number
37
61
  t: number
62
+ h: Held
38
63
  }
39
64
 
40
- const K = { anon: 'shotik.support.anon', state: 'shotik.analytics.state', queue: 'shotik.analytics.queue', consent: 'shotik.analytics.consent' }
65
+ 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' }
41
66
  const MAX_QUEUE = 2000
42
67
  const BATCH = 300
43
68
  const RAGE_N = 3
44
69
  const RAGE_MS = 800
45
70
  const RAGE_PT = 40
71
+ const RESP_MS = 1500
72
+ const NET_SLOW_MS = 3000
73
+ const ERRTAP_MS = 2000
74
+ const REPLAY_REQS = 8
75
+
76
+ export type Gesture = { k: 'long' | 'swipe' | 'pan' | 'pinch'; dir?: 'left' | 'right' | 'up' | 'down' | 'in' | 'out'; dx: number; dy: number; ms: number; el: string; id: string; sc?: number; ts?: number }
77
+ export type Scrolled = { el: string; id: string; off: number; len: number; vis: number; hz?: boolean; pg?: number; ts: number; screen?: string }
78
+
79
+ // The SDK's own cost this session (perf on close): the last 256 samples per path, bytes uploaded.
80
+ const costs = () => ({ tap: [] as number[], walk: [] as number[], fp: [] as number[], rb: 0, eb: 0 })
81
+ const p95 = (a: number[]) => {
82
+ if (!a.length) return undefined
83
+ const s = a.slice().sort((x, y) => x - y)
84
+ return Math.round(s[Math.ceil(s.length * 0.95) - 1] * 1000) / 1000
85
+ }
86
+
87
+ // Sent as `sdk: 'rn/<version>'` in the device context. Keep equal to package.json (a unit test checks it).
88
+ export const SDK_VERSION = '0.2.0'
89
+
90
+ // A request URL as host + path template: no scheme, credentials, query or fragment; ids, UUIDs, hex, digit runs, tokens
91
+ // of 8+ characters with 2+ digits, emails, anything redact() changes and percent-encoded or non-ASCII segments become :id
92
+ // (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.
93
+ export function netTarget(url: string): { host: string; path: string } {
94
+ const m = /^(?:[a-z][a-z0-9+.-]*:)?\/\/([^/?#]*)([^?#]*)/i.exec(url)
95
+ const host = (m ? m[1] : '').replace(/^.*@/, '').toLowerCase()
96
+ const raw = m ? m[2] : url.replace(/[?#].*$/, '')
97
+ const id = (s: string) => (/\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
98
+ const seg = (s: string) => {
99
+ const x = /^(.+)(\.[a-z0-9]{1,5})$/i.exec(s)
100
+ return x && id(x[1]) && !/@|%40/.test(s) ? ':id' + x[2] : id(s) ? ':id' : s
101
+ }
102
+ const path = raw.split('/').map(seg).join('/').slice(0, 120)
103
+ return { host, path: path || '/' }
104
+ }
46
105
 
47
106
  const rnd = () => Math.random().toString(36).slice(2, 10)
48
107
  const uid = () => Date.now().toString(36) + rnd() + rnd()
@@ -65,6 +124,11 @@ export class Analytics {
65
124
  private screenAt = 0
66
125
  private screenStats = { depth: 0, drag: 0, stalls: 0, maxStall: 0 }
67
126
  private taps: Pending[] = []
127
+ private held: Held | null = null
128
+ private waiting: Held[] = []
129
+ private states = false
130
+ private stateH: string | undefined
131
+ private marks: Record<string, { t: number; tr?: 1 }> = {}
68
132
  private snapped = new Set<string>()
69
133
  private timer: ReturnType<typeof setTimeout> | null = null
70
134
  private saveTimer: ReturnType<typeof setTimeout> | null = null
@@ -76,6 +140,9 @@ export class Analytics {
76
140
  private loaded = false
77
141
  private fresh = true
78
142
  private storeIssue: 'none' | 'error' | undefined
143
+ private replay = new Replay()
144
+ private cost = costs()
145
+ private lastTap: { ts: number; screen?: string } = { ts: -Infinity }
79
146
 
80
147
  constructor(cfg: AnalyticsConfig) {
81
148
  this.cfg = cfg
@@ -89,7 +156,7 @@ export class Analytics {
89
156
  const st = this.st
90
157
  if (st) {
91
158
  try {
92
- const [anon, raw, q, c] = await Promise.all([st.get(K.anon), st.get(K.state), st.get(K.queue), st.get(K.consent)])
159
+ 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)])
93
160
  this.anon = anon ?? ''
94
161
  const s = raw ? JSON.parse(raw) : null
95
162
  if (s) {
@@ -103,6 +170,12 @@ export class Analytics {
103
170
  }
104
171
  if (q) this.queue = (JSON.parse(q) as WireEvent[]).concat(this.queue).slice(-MAX_QUEUE)
105
172
  if (c === 'granted' || c === 'denied') this.consent = c
173
+ if (pm) this.marks = JSON.parse(pm) ?? {}
174
+ if (rp) {
175
+ const r = JSON.parse(rp) as { why?: ReplayWhy; chunks?: ReplayChunk[] }
176
+ if (Array.isArray(r?.chunks)) this.replay.restore(r.why ?? 'crash', r.chunks)
177
+ st.remove(K.replay).catch(() => {})
178
+ }
106
179
  } catch {
107
180
  this.storeIssue = 'error'
108
181
  }
@@ -137,6 +210,7 @@ export class Analytics {
137
210
  this.seq = 0
138
211
  this.sampled = Math.random() < (this.cfg.snapshots ?? 0.2)
139
212
  this.snapped.clear()
213
+ this.cost = costs()
140
214
  this.lastActive = t
141
215
  const props = { ...(first && { first: 1 }), ...(this.storeIssue && { store: this.storeIssue }) }
142
216
  this.push('session', undefined, Object.keys(props).length ? props : undefined, t)
@@ -144,11 +218,12 @@ export class Analytics {
144
218
  this.lastActive = t
145
219
  }
146
220
 
147
- private push(type: EventType, name?: string, props?: Record<string, unknown>, ts?: number): void {
221
+ private push(type: EventType, name?: string, props?: Record<string, unknown>, ts?: number, screen = this.screen): void {
148
222
  if (this.consent === 'denied') return
149
- this.queue.push({ seq: ++this.seq, ts: ts ?? this.now(), type, sessionId: this.sessionId, screen: this.screen, name, props })
223
+ this.queue.push({ seq: ++this.seq, ts: ts ?? this.now(), type, sessionId: this.sessionId, screen, name, props })
150
224
  if (this.queue.length > MAX_QUEUE) this.queue.splice(0, this.queue.length - MAX_QUEUE)
151
225
  if (this.cfg.debug) console.log('[shotik]', type, name ?? '', this.screen ?? '', props ?? '')
226
+ this.cfg.onEvent?.(type, name, this.screen, props)
152
227
  this.save()
153
228
  if (this.queue.length >= BATCH) this.flush()
154
229
  }
@@ -178,14 +253,27 @@ export class Analytics {
178
253
 
179
254
  // Public API
180
255
 
256
+ private get dev(): boolean {
257
+ return !!(this.cfg.debug || (globalThis as { __DEV__?: boolean }).__DEV__)
258
+ }
259
+
260
+ // A connection check: one test event, sent now. It goes through the same queue, key and route as everything else, flagged
261
+ // kind 'test', so the server shows "Test event received" and never counts it as a session, a user or a metric.
262
+ sendTestEvent(): Promise<void> {
263
+ if (this.consent === 'denied') return Promise.resolve()
264
+ this.queue.push({ seq: ++this.seq, ts: this.now(), type: 'custom', sessionId: this.sessionId || 'test_' + this.anon, name: 'shotik_test', kind: 'test' })
265
+ return this.flush()
266
+ }
267
+
268
+ // Personal-data keys are dropped and string values redacted on the device (privacy.ts).
181
269
  track(name: string, props?: Record<string, unknown>): void {
182
270
  this.touch()
183
- this.push('custom', name, props)
271
+ this.push('custom', redact(name), cleanProps(props, this.dev))
184
272
  }
185
273
 
186
274
  identify(userId: string | null, traits?: Record<string, unknown>): void {
187
275
  this.userId = userId
188
- this.push('identify', undefined, traits ? { traits } : undefined)
276
+ this.push('identify', undefined, traits ? { traits: cleanProps(traits, this.dev) } : undefined)
189
277
  }
190
278
 
191
279
  // Screen change: closes the previous screen with its time and scroll depth.
@@ -193,7 +281,10 @@ export class Analytics {
193
281
  if (name === this.screen) return
194
282
  this.touch()
195
283
  const from = this.screen
284
+ this.drain(true)
285
+ this.respond(true)
196
286
  this.leave()
287
+ this.stateH = undefined
197
288
  this.screen = name
198
289
  this.screenAt = this.now()
199
290
  this.push('screen', name, from ? { from } : undefined)
@@ -228,19 +319,148 @@ export class Analytics {
228
319
  if (ms > 1000) this.push('slow', this.screen, { ms: Math.round(ms), kind: 'stall' })
229
320
  }
230
321
 
231
- // A tap with its element identity. dead = nothing on the touched element handles presses.
232
- tap(t: { el: string; id?: string; label?: string; x: number; y: number; nx: number; ny: number; dead?: boolean; input?: boolean; ts?: number }): void {
322
+ // A tap with its element identity. dead = nothing on the touched element handles presses; it stays dead unless the
323
+ // screen changes within RESP_MS. The tap is queued once it is resolved: on its response, the next tap, or RESP_MS
324
+ // later (checked on every flush), with its own ts and screen. resp = ms to the first screen change or request start,
325
+ // 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.
326
+ tap(t: TapInput): void {
233
327
  this.touch()
234
328
  const now = t.ts ?? this.now()
235
- const p: Record<string, unknown> = { el: t.el, x: Math.round(t.x), y: Math.round(t.y), nx: t.nx, ny: t.ny }
329
+ this.release()
330
+ const h: Held = { t, ts: now, screen: this.screen }
331
+ this.lastTap = { ts: now, screen: this.screen }
332
+ this.taps = this.taps.filter((q) => now - q.t < RAGE_MS && Math.hypot(q.x - t.x, q.y - t.y) < RAGE_PT)
333
+ this.taps.push({ x: t.x, y: t.y, t: now, h })
334
+ if (this.taps.length === RAGE_N) h.burst = this.taps.map((q) => q.h)
335
+ this.held = h
336
+ }
337
+
338
+ private respond(screen: boolean): void {
339
+ const h = this.held
340
+ if (!h) return
341
+ const dt = this.now() - h.ts
342
+ if (dt > RESP_MS) return this.release()
343
+ h.resp ??= Math.max(0, Math.round(dt))
344
+ if (screen) {
345
+ h.moved = true
346
+ this.release()
347
+ }
348
+ }
349
+
350
+ private settle(all: boolean): void {
351
+ if (this.held && (all || this.now() - this.held.ts > RESP_MS)) this.release()
352
+ this.drain(all)
353
+ }
354
+
355
+ // While UI-state fingerprints run (uiState was called), a resolved tap with no response waits for the next walk.
356
+ private release(): void {
357
+ const h = this.held
358
+ if (!h) return
359
+ this.held = null
360
+ if (this.states && !h.checked && h.resp === undefined && !h.t.dead && !h.t.input) return void this.waiting.push(h)
361
+ this.emit(h)
362
+ }
363
+
364
+ private drain(all: boolean): void {
365
+ const now = this.now()
366
+ while (this.waiting.length && (all || now - this.waiting[0].ts > RESP_MS)) this.emit(this.waiting.shift()!)
367
+ }
368
+
369
+ private emit(h: Held): void {
370
+ const t = h.t
371
+ const dead = t.dead && !h.moved
372
+ if (dead) h.resp = undefined
373
+ const at = t.masked ? {} : { x: Math.round(t.x), y: Math.round(t.y) }
374
+ const p: Record<string, unknown> = { el: t.el, ...at, ...(!t.masked && { nx: t.nx, ny: t.ny }) }
236
375
  if (t.id) p.id = t.id
237
376
  if (t.label) p.label = t.label
238
- if (t.dead) p.dead = 1
377
+ if (dead) p.dead = 1
239
378
  if (t.input) p.input = 1
240
- this.push('tap', undefined, p, now)
241
- this.taps = this.taps.filter((q) => now - q.t < RAGE_MS && Math.hypot(q.x - t.x, q.y - t.y) < RAGE_PT)
242
- this.taps.push({ el: t.el, id: t.id, label: t.label, x: t.x, y: t.y, t: now })
243
- if (this.taps.length === RAGE_N) 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)
379
+ if (h.resp !== undefined) p.resp = h.resp
380
+ this.push('tap', undefined, p, h.ts, h.screen)
381
+ const rage = h.burst?.some((b) => b.resp === undefined)
382
+ if (rage) this.push('rage', undefined, { el: t.el, id: t.id, label: t.label, n: RAGE_N, ...at }, h.ts, h.screen)
383
+ if (rage || dead || (!t.input && h.resp === undefined)) this.signal(rage ? 'rage' : dead ? 'dead' : 'unresponsive')
384
+ }
385
+
386
+ // A replay signal (PROTOCOL.md 4.7): an unsampled session's ring of the last 30 s is released for upload.
387
+ private signal(why: ReplayWhy): void {
388
+ this.replay.signal(why, this.now())
389
+ }
390
+
391
+ // A UI-state fingerprint walk finished (h null: none possible). The first one on a screen is its baseline; a different h
392
+ // later on the same screen is a `state` event and the response of every tap waiting for this walk. quiet (after a
393
+ // vertical scroll) only moves the baseline.
394
+ uiState(h: string | null, n = 0, quiet = false): boolean {
395
+ this.states = true
396
+ const changed = h !== null && this.stateH !== undefined && h !== this.stateH && !quiet
397
+ if (h !== null) this.stateH = h
398
+ if (changed) {
399
+ const now = this.now()
400
+ for (const w of this.waiting) if (now - w.ts <= RESP_MS) w.resp = Math.round(now - w.ts)
401
+ this.respond(false)
402
+ }
403
+ if (this.held) this.held.checked = true
404
+ this.drain(true)
405
+ if (changed) this.push('state', undefined, { h, n })
406
+ return changed
407
+ }
408
+
409
+ // One focus span of a text input: ts = focus time, ms focused, edits (none for secure inputs), filled. Never a value or length.
410
+ field(f: { id: string; el: string; ts: number; ms: number; edits?: number; filled?: boolean; screen?: string }): void {
411
+ this.touch()
412
+ 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)
413
+ }
414
+
415
+ // A request started (wrapped fetch / XMLHttpRequest): a response to the newest tap.
416
+ netStart(): void {
417
+ this.respond(false)
418
+ }
419
+
420
+ // A finished request; only failures (status >= 400, 0 = network error) and slow calls (> 3 s) become `net` events.
421
+ net(method: string, url: string, status: number, ms: number): void {
422
+ if (status > 0 && status < 400 && ms <= NET_SLOW_MS) return
423
+ const { host, path } = netTarget(url)
424
+ this.push('net', undefined, { m: method.toUpperCase().slice(0, 10), host, path, s: status, ms: Math.round(ms) })
425
+ if ((status === 0 || status >= 400) && this.now() - this.lastTap.ts <= ERRTAP_MS && this.lastTap.screen === this.screen) this.signal('errtap')
426
+ }
427
+
428
+ // A touch that was neither a tap nor a scroll (PROTOCOL.md 4.1 touch classes). ts = the touch start.
429
+ gesture(g: Gesture): void {
430
+ this.touch()
431
+ 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)
432
+ }
433
+
434
+ // A container a touch scrolled settled at a new offset. ts = the touch end.
435
+ scrolled(s: Scrolled): void {
436
+ this.touch()
437
+ 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)
438
+ }
439
+
440
+ // Self-cost samples (ms) for perf on close: the touch-end handler, a replay capture, a fingerprint walk.
441
+ measure(kind: 'tap' | 'walk' | 'fp', ms: number): void {
442
+ const a = this.cost[kind]
443
+ a.push(ms)
444
+ if (a.length > 256) a.shift()
445
+ }
446
+
447
+ private perf(): Record<string, number | undefined> {
448
+ const c = this.cost
449
+ return { tap: p95(c.tap), walk: p95(c.walk), fp: p95(c.fp), rb: c.rb, eb: c.eb }
450
+ }
451
+
452
+ get replayOn(): boolean {
453
+ return this.cfg.replay !== false && this.loaded && this.active && this.consent !== 'denied' && !this.replay.off
454
+ }
455
+
456
+ // One replay capture (the walk of the current screen); true when it built a chunk (something changed).
457
+ replayFrame(w: ReplayWalk): boolean {
458
+ if (!this.replayOn) return false
459
+ return !!this.replay.frame(this.sessionId, this.sampled, w, this.now())
460
+ }
461
+
462
+ get replayBuffer(): Replay {
463
+ return this.replay
244
464
  }
245
465
 
246
466
  scroll(depth: number | null, drag: number): void {
@@ -255,13 +475,33 @@ export class Analytics {
255
475
  .split('\n')
256
476
  .slice(1, 6)
257
477
  .map((l) => l.trim().replace(/https?:\/\/[^\s)]+\//g, '').slice(0, 120))
258
- this.push('error', err.name, { msg: err.message.slice(0, 200), fatal: fatal ? 1 : undefined, stack })
259
- if (fatal) this.persist()
478
+ this.push('error', err.name, { msg: redact(err.message).slice(0, 200), fatal: fatal ? 1 : undefined, stack })
479
+ this.signal(fatal ? 'crash' : 'error')
480
+ if (!fatal) return
481
+ this.persist()
482
+ const out = this.replay.out
483
+ if (out.length) this.st?.set(K.replay, JSON.stringify({ a: this.anon, why: 'crash', chunks: out.map((b) => b.c) })).catch(() => {})
260
484
  }
261
485
 
262
- purchase(p: { product: string; status: 'start' | 'done' | 'cancel' | 'fail'; price?: number; currency?: string; store?: string; trial?: boolean }): void {
486
+ purchase(p: { product: string; status: 'start' | 'done' | 'cancel' | 'fail'; price?: number; currency?: string; store?: string; trial?: boolean; renew?: boolean; conv?: boolean; at?: number }): void {
263
487
  this.touch()
264
- 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 })
488
+ 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 })
489
+ }
490
+
491
+ // Store truth: each entitlement's latest purchase against a per-product watermark. A newer one is a done (renew unless it
492
+ // is the subscription's first purchase, conv on the first paid period after a trial this install saw). Purchases from
493
+ // before this install's first launch, and quiet ones (restores, the wrapped call's own done), only move the watermark.
494
+ entitled(list: Entitled[], quiet = false, store = 'revenuecat'): void {
495
+ if (!this.loaded) return void this.ready.then(() => this.entitled(list, quiet, store))
496
+ let dirty = false
497
+ for (const e of list) {
498
+ const m = this.marks[e.product]
499
+ if (!e.product || !(e.at > 0) || (m && m.t >= e.at)) continue
500
+ if (!quiet && e.at >= this.firstSeen) this.purchase({ product: e.product, status: 'done', store, trial: e.trial, renew: !!m || (e.first !== undefined && e.at - e.first > 60_000), conv: !!m?.tr && !e.trial, at: e.at })
501
+ this.marks[e.product] = e.trial ? { t: e.at, tr: 1 } : { t: e.at }
502
+ dirty = true
503
+ }
504
+ if (dirty) this.st?.set(K.purchases, JSON.stringify(this.marks)).catch(() => {})
265
505
  }
266
506
 
267
507
  // Wireframes are recorded once per screen per sampled session.
@@ -288,8 +528,9 @@ export class Analytics {
288
528
  }
289
529
 
290
530
  background(): void {
531
+ this.settle(true)
291
532
  this.leave()
292
- this.push('close')
533
+ this.push('close', undefined, { perf: this.perf() })
293
534
  this.active = false
294
535
  this.persist()
295
536
  this.flush()
@@ -301,6 +542,7 @@ export class Analytics {
301
542
  if (c === 'denied') {
302
543
  this.queue = []
303
544
  this.snaps = []
545
+ this.replay.clear()
304
546
  this.persist()
305
547
  } else if (c === 'granted') this.flush()
306
548
  }
@@ -313,6 +555,26 @@ export class Analytics {
313
555
  this.setConsent('granted')
314
556
  }
315
557
 
558
+ // Right to be forgotten (PROTOCOL.md 7): drops everything still on the device (queue, wireframes, replay ring and a
559
+ // crash-saved ring), asks the server to delete what it recorded for this install (POST /analytics/v1/forget: events,
560
+ // wireframes, replay) and, once it has, starts over as a new anonymous install. Works whatever the consent. Resolves
561
+ // false when the server could not be reached; the id is kept so calling again retries.
562
+ async forget(): Promise<boolean> {
563
+ await this.ready
564
+ this.queue = []
565
+ this.snaps = []
566
+ this.replay.clear()
567
+ this.persist()
568
+ await this.st?.remove(K.replay).catch(() => {})
569
+ await this.inflight?.catch(() => {})
570
+ const f = this.cfg.fetch ?? fetch
571
+ 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 }) })
572
+ .then((r) => r.ok)
573
+ .catch(() => false)
574
+ if (ok) await this.reset()
575
+ return ok
576
+ }
577
+
316
578
  // Sign-out: a new anonymous id and session, nothing of the old user kept.
317
579
  async reset(): Promise<void> {
318
580
  await this.flush()
@@ -332,7 +594,8 @@ export class Analytics {
332
594
 
333
595
  private async send(): Promise<void> {
334
596
  await this.ready
335
- if (this.sending || this.consent !== 'granted' || (!this.queue.length && !this.snaps.length)) return
597
+ this.settle(false)
598
+ if (this.sending || this.consent !== 'granted' || (!this.queue.length && !this.snaps.length && !this.replay.out.length)) return
336
599
  this.sending = true
337
600
  const events = this.queue.slice(0, BATCH)
338
601
  const snaps = this.snaps.splice(0, 4)
@@ -345,9 +608,15 @@ export class Analytics {
345
608
  if (!r.ok && r.status < 500 && r.status !== 429) {
346
609
  if (this.cfg.debug) console.warn('[shotik] dropped batch', r.status)
347
610
  } else if (!r.ok) throw new Error(String(r.status))
611
+ else this.cost.eb += body.length
348
612
  this.queue.splice(0, events.length)
349
613
  }
350
- for (const s of snaps) await f(this.cfg.serverUrl + '/analytics/v1/snapshots', { method: 'POST', headers, body: JSON.stringify({ anonymousId: this.anon, ...s }) })
614
+ while (snaps.length) {
615
+ const r = await f(this.cfg.serverUrl + '/analytics/v1/snapshots', { method: 'POST', headers, body: JSON.stringify({ anonymousId: this.anon, ...snaps[0] }) })
616
+ if (!r.ok && (r.status >= 500 || r.status === 429)) throw new Error(String(r.status))
617
+ snaps.shift()
618
+ }
619
+ await this.sendReplay(f, headers)
351
620
  this.backoff = 0
352
621
  this.persist()
353
622
  } catch {
@@ -359,7 +628,27 @@ export class Analytics {
359
628
  if (this.queue.length >= BATCH && !this.backoff) return this.send()
360
629
  }
361
630
 
631
+ // Replay chunks (PROTOCOL.md 4.7), up to 8 requests per flush. 403: replay is off or over quota for this app, so nothing
632
+ // more is captured or sent until the next launch. Wi-Fi only: held until wifi() says so.
633
+ private async sendReplay(f: typeof fetch, headers: Record<string, string>): Promise<void> {
634
+ const R = this.replay
635
+ if (!R.out.length || R.off) return
636
+ const opt = this.cfg.replay
637
+ if (opt && opt.wifiOnly && !(await (this.cfg.wifi?.() ?? Promise.resolve(false)).catch(() => false))) return
638
+ for (let n = 0; n < REPLAY_REQS; n++) {
639
+ const b = R.take()
640
+ if (!b) return
641
+ const body = '{"v":1,"a":' + JSON.stringify(this.anon) + ',"why":"' + b.why + '","chunks":[' + b.items.map((i) => i.s).join(',') + ']}'
642
+ const r = await f(this.cfg.serverUrl + '/analytics/v1/replay', { method: 'POST', headers, body })
643
+ if (r.status === 403) return R.clear(true)
644
+ if (!r.ok && (r.status >= 500 || r.status === 429)) throw new Error(String(r.status))
645
+ if (r.ok) this.cost.rb += body.length
646
+ R.done(b.items)
647
+ }
648
+ }
649
+
362
650
  stop(): void {
651
+ this.settle(true)
363
652
  this.active = false
364
653
  if (this.timer) clearTimeout(this.timer)
365
654
  if (this.saveTimer) clearTimeout(this.saveTimer)
@@ -0,0 +1,50 @@
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
+
4
+ const RULES: [RegExp, string | ((m: string) => string)][] = [
5
+ [/(\bhttps?:\/\/[^\s?#]*)[?#][^\s]*/gi, '$1'],
6
+ [/\?[\w.%-]+=[^\s]*/g, ''],
7
+ [/\b(Bearer|Basic)\s+[\w.~+/=-]+/gi, '$1 [token]'],
8
+ [/\beyJ[\w-]{4,}\.[\w-]{4,}(?:\.[\w-]+)?/g, '[token]'],
9
+ [/[^\s@<>()"',;:]+@[^\s@<>()"',;:]+/g, '[email]'],
10
+ [/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi, '[id]'],
11
+ [/\b(?=[0-9a-f]*\d)[0-9a-f]{16,}\b/gi, '[id]'],
12
+ [/\b(?=[\w-]*\d)(?=[\w-]*[a-z])[\w-]{24,}/gi, '[token]'],
13
+ [/\+?\(?\d[\d\s().-]{5,}\d/g, (m) => ((m.match(/\d/g)?.length ?? 0) < 7 ? m : /^\+|[()]|\d\s\d/.test(m) ? '[phone]' : '[n]')],
14
+ [/\d{4,}/g, '[n]']
15
+ ]
16
+
17
+ export function redact(s: string): string {
18
+ let out = s
19
+ for (const [re, to] of RULES) out = out.replace(re, to as string)
20
+ return out
21
+ }
22
+
23
+ export const PII_KEY = /email|phone|name|token|password|address/i
24
+
25
+ const warned = new Set<string>()
26
+
27
+ // Custom props and identify traits: personal-data keys dropped (one dev warning per key), string values redacted, 3 levels deep.
28
+ export function cleanProps(props: Record<string, unknown> | undefined, dev = false, depth = 0): Record<string, unknown> | undefined {
29
+ if (!props || typeof props !== 'object') return props
30
+ const out: Record<string, unknown> = {}
31
+ const val = (v: unknown): unknown => (typeof v === 'string' ? redact(v) : v && typeof v === 'object' ? (depth < 2 && !Array.isArray(v) ? cleanProps(v as Record<string, unknown>, dev, depth + 1) : undefined) : v)
32
+ for (const k in props) {
33
+ if (PII_KEY.test(k)) {
34
+ if (dev && !warned.has(k)) {
35
+ warned.add(k)
36
+ console.warn('[shotik] dropped the prop "' + k + '": keys like email, phone, name, token, password or address never leave the device')
37
+ }
38
+ continue
39
+ }
40
+ const v = props[k]
41
+ out[k] = Array.isArray(v) ? v.map(val) : val(v)
42
+ }
43
+ return out
44
+ }
45
+
46
+ // A testID as words for a label: startTrialButton, start-trial, plan_card.annual -> "Start trial button", "Start trial", "Plan card annual".
47
+ export function idWords(id: string): string {
48
+ const w = id.replace(/([a-z\d])([A-Z])/g, '$1 $2').replace(/[-_.:/#]+/g, ' ').replace(/\s+/g, ' ').trim().toLowerCase()
49
+ return w.charAt(0).toUpperCase() + w.slice(1)
50
+ }
@@ -98,7 +98,7 @@
98
98
  "dependencies",
99
99
  "@shotik/react-native"
100
100
  ],
101
- "value": "^0.1.0"
101
+ "value": "^0.2.0"
102
102
  }
103
103
  ],
104
104
  "run": {