@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.
- package/CHANGELOG.md +20 -0
- package/LICENSE +26 -0
- package/README.md +36 -1
- package/README.ru.md +37 -1
- package/dist/analytics/core.d.ts +111 -12
- package/dist/analytics/core.js +303 -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 +53 -2
- package/dist/analytics/rn.js +687 -63
- package/dist/analytics/wire.d.ts +54 -2
- package/dist/analytics/wire.js +44 -4
- package/dist/client.d.ts +93 -0
- package/dist/client.js +247 -9
- 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 +206 -15
- package/dist/support.js +2 -2
- package/dist/theme.d.ts +43 -0
- package/dist/theme.js +88 -2
- package/package.json +15 -2
- package/recipe.json +1 -1
- package/src/analytics/README.md +10 -6
- package/src/analytics/core.ts +324 -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 +636 -64
- package/src/analytics/wire.ts +101 -8
- package/src/client.ts +334 -9
- 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 +422 -19
- package/src/support.ts +2 -2
- package/src/theme.ts +88 -2
package/src/analytics/README.md
CHANGED
|
@@ -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:
|
|
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
|
|
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
|
|
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>`
|
|
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
|
-
-
|
|
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
|
|
package/src/analytics/core.ts
CHANGED
|
@@ -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,87 @@ 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
|
-
|
|
65
|
+
export type SheetOutcome = 'shown' | 'confirmed' | 'cancelled' | 'failed' | 'pending' | 'not_shown'
|
|
66
|
+
export const SHEET_STATUS: Record<SheetOutcome, 'shown' | 'done' | 'cancel' | 'fail' | 'pending' | 'not_shown'> = { shown: 'shown', confirmed: 'done', cancelled: 'cancel', failed: 'fail', pending: 'pending', not_shown: 'not_shown' }
|
|
67
|
+
|
|
68
|
+
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
69
|
const MAX_QUEUE = 2000
|
|
42
70
|
const BATCH = 300
|
|
43
71
|
const RAGE_N = 3
|
|
44
72
|
const RAGE_MS = 800
|
|
45
73
|
const RAGE_PT = 40
|
|
74
|
+
const RESP_MS = 1500
|
|
75
|
+
const NET_SLOW_MS = 3000
|
|
76
|
+
const ERRTAP_MS = 2000
|
|
77
|
+
const REPLAY_REQS = 8
|
|
78
|
+
|
|
79
|
+
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 }
|
|
80
|
+
export type Scrolled = { el: string; id: string; off: number; len: number; vis: number; hz?: boolean; pg?: number; ts: number; screen?: string }
|
|
81
|
+
|
|
82
|
+
// The SDK's own cost this session (perf on close): the last 256 samples per path, bytes uploaded.
|
|
83
|
+
const costs = () => ({ tap: [] as number[], walk: [] as number[], fp: [] as number[], rb: 0, eb: 0 })
|
|
84
|
+
const p95 = (a: number[]) => {
|
|
85
|
+
if (!a.length) return undefined
|
|
86
|
+
const s = a.slice().sort((x, y) => x - y)
|
|
87
|
+
return Math.round(s[Math.ceil(s.length * 0.95) - 1] * 1000) / 1000
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// Sent as `sdk: 'rn/<version>'` in the device context. Keep equal to package.json (a unit test checks it).
|
|
91
|
+
export const SDK_VERSION = '0.2.2'
|
|
92
|
+
|
|
93
|
+
// A request URL as host + path template: no scheme, credentials, query or fragment; ids, UUIDs, hex, digit runs, tokens
|
|
94
|
+
// of 8+ characters with 2+ digits, emails, anything redact() changes and percent-encoded or non-ASCII segments become :id
|
|
95
|
+
// (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.
|
|
96
|
+
export function netTarget(url: string): { host: string; path: string } {
|
|
97
|
+
const m = /^(?:[a-z][a-z0-9+.-]*:)?\/\/([^/?#]*)([^?#]*)/i.exec(url)
|
|
98
|
+
const host = (m ? m[1] : '').replace(/^.*@/, '').toLowerCase()
|
|
99
|
+
const raw = m ? m[2] : url.replace(/[?#].*$/, '')
|
|
100
|
+
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
|
|
101
|
+
const seg = (s: string) => {
|
|
102
|
+
const x = /^(.+)(\.[a-z0-9]{1,5})$/i.exec(s)
|
|
103
|
+
return x && id(x[1]) && !/@|%40/.test(s) ? ':id' + x[2] : id(s) ? ':id' : s
|
|
104
|
+
}
|
|
105
|
+
const path = raw.split('/').map(seg).join('/').slice(0, 120)
|
|
106
|
+
return { host, path: path || '/' }
|
|
107
|
+
}
|
|
46
108
|
|
|
47
109
|
const rnd = () => Math.random().toString(36).slice(2, 10)
|
|
48
110
|
const uid = () => Date.now().toString(36) + rnd() + rnd()
|
|
@@ -65,6 +127,11 @@ export class Analytics {
|
|
|
65
127
|
private screenAt = 0
|
|
66
128
|
private screenStats = { depth: 0, drag: 0, stalls: 0, maxStall: 0 }
|
|
67
129
|
private taps: Pending[] = []
|
|
130
|
+
private held: Held | null = null
|
|
131
|
+
private waiting: Held[] = []
|
|
132
|
+
private states = false
|
|
133
|
+
private stateH: string | undefined
|
|
134
|
+
private marks: Record<string, { t: number; tr?: 1 }> = {}
|
|
68
135
|
private snapped = new Set<string>()
|
|
69
136
|
private timer: ReturnType<typeof setTimeout> | null = null
|
|
70
137
|
private saveTimer: ReturnType<typeof setTimeout> | null = null
|
|
@@ -76,6 +143,9 @@ export class Analytics {
|
|
|
76
143
|
private loaded = false
|
|
77
144
|
private fresh = true
|
|
78
145
|
private storeIssue: 'none' | 'error' | undefined
|
|
146
|
+
private replay = new Replay()
|
|
147
|
+
private cost = costs()
|
|
148
|
+
private lastTap: { ts: number; screen?: string } = { ts: -Infinity }
|
|
79
149
|
|
|
80
150
|
constructor(cfg: AnalyticsConfig) {
|
|
81
151
|
this.cfg = cfg
|
|
@@ -89,7 +159,7 @@ export class Analytics {
|
|
|
89
159
|
const st = this.st
|
|
90
160
|
if (st) {
|
|
91
161
|
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)])
|
|
162
|
+
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
163
|
this.anon = anon ?? ''
|
|
94
164
|
const s = raw ? JSON.parse(raw) : null
|
|
95
165
|
if (s) {
|
|
@@ -103,6 +173,12 @@ export class Analytics {
|
|
|
103
173
|
}
|
|
104
174
|
if (q) this.queue = (JSON.parse(q) as WireEvent[]).concat(this.queue).slice(-MAX_QUEUE)
|
|
105
175
|
if (c === 'granted' || c === 'denied') this.consent = c
|
|
176
|
+
if (pm) this.marks = JSON.parse(pm) ?? {}
|
|
177
|
+
if (rp) {
|
|
178
|
+
const r = JSON.parse(rp) as { why?: ReplayWhy; chunks?: ReplayChunk[] }
|
|
179
|
+
if (Array.isArray(r?.chunks)) this.replay.restore(r.why ?? 'crash', r.chunks)
|
|
180
|
+
st.remove(K.replay).catch(() => {})
|
|
181
|
+
}
|
|
106
182
|
} catch {
|
|
107
183
|
this.storeIssue = 'error'
|
|
108
184
|
}
|
|
@@ -137,6 +213,7 @@ export class Analytics {
|
|
|
137
213
|
this.seq = 0
|
|
138
214
|
this.sampled = Math.random() < (this.cfg.snapshots ?? 0.2)
|
|
139
215
|
this.snapped.clear()
|
|
216
|
+
this.cost = costs()
|
|
140
217
|
this.lastActive = t
|
|
141
218
|
const props = { ...(first && { first: 1 }), ...(this.storeIssue && { store: this.storeIssue }) }
|
|
142
219
|
this.push('session', undefined, Object.keys(props).length ? props : undefined, t)
|
|
@@ -144,11 +221,12 @@ export class Analytics {
|
|
|
144
221
|
this.lastActive = t
|
|
145
222
|
}
|
|
146
223
|
|
|
147
|
-
private push(type: EventType, name?: string, props?: Record<string, unknown>, ts?: number): void {
|
|
224
|
+
private push(type: EventType, name?: string, props?: Record<string, unknown>, ts?: number, screen = this.screen): void {
|
|
148
225
|
if (this.consent === 'denied') return
|
|
149
|
-
this.queue.push({ seq: ++this.seq, ts: ts ?? this.now(), type, sessionId: this.sessionId, screen
|
|
226
|
+
this.queue.push({ seq: ++this.seq, ts: ts ?? this.now(), type, sessionId: this.sessionId, screen, name, props })
|
|
150
227
|
if (this.queue.length > MAX_QUEUE) this.queue.splice(0, this.queue.length - MAX_QUEUE)
|
|
151
228
|
if (this.cfg.debug) console.log('[shotik]', type, name ?? '', this.screen ?? '', props ?? '')
|
|
229
|
+
this.cfg.onEvent?.(type, name, this.screen, props)
|
|
152
230
|
this.save()
|
|
153
231
|
if (this.queue.length >= BATCH) this.flush()
|
|
154
232
|
}
|
|
@@ -178,14 +256,27 @@ export class Analytics {
|
|
|
178
256
|
|
|
179
257
|
// Public API
|
|
180
258
|
|
|
259
|
+
private get dev(): boolean {
|
|
260
|
+
return !!(this.cfg.debug || (globalThis as { __DEV__?: boolean }).__DEV__)
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// A connection check: one test event, sent now. It goes through the same queue, key and route as everything else, flagged
|
|
264
|
+
// kind 'test', so the server shows "Test event received" and never counts it as a session, a user or a metric.
|
|
265
|
+
sendTestEvent(): Promise<void> {
|
|
266
|
+
if (this.consent === 'denied') return Promise.resolve()
|
|
267
|
+
this.queue.push({ seq: ++this.seq, ts: this.now(), type: 'custom', sessionId: this.sessionId || 'test_' + this.anon, name: 'shotik_test', kind: 'test' })
|
|
268
|
+
return this.flush()
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// Personal-data keys are dropped and string values redacted on the device (privacy.ts).
|
|
181
272
|
track(name: string, props?: Record<string, unknown>): void {
|
|
182
273
|
this.touch()
|
|
183
|
-
this.push('custom', name, props)
|
|
274
|
+
this.push('custom', redact(name), cleanProps(props, this.dev))
|
|
184
275
|
}
|
|
185
276
|
|
|
186
277
|
identify(userId: string | null, traits?: Record<string, unknown>): void {
|
|
187
278
|
this.userId = userId
|
|
188
|
-
this.push('identify', undefined, traits ? { traits } : undefined)
|
|
279
|
+
this.push('identify', undefined, traits ? { traits: cleanProps(traits, this.dev) } : undefined)
|
|
189
280
|
}
|
|
190
281
|
|
|
191
282
|
// Screen change: closes the previous screen with its time and scroll depth.
|
|
@@ -193,7 +284,10 @@ export class Analytics {
|
|
|
193
284
|
if (name === this.screen) return
|
|
194
285
|
this.touch()
|
|
195
286
|
const from = this.screen
|
|
287
|
+
this.drain(true)
|
|
288
|
+
this.respond(true)
|
|
196
289
|
this.leave()
|
|
290
|
+
this.stateH = undefined
|
|
197
291
|
this.screen = name
|
|
198
292
|
this.screenAt = this.now()
|
|
199
293
|
this.push('screen', name, from ? { from } : undefined)
|
|
@@ -228,19 +322,148 @@ export class Analytics {
|
|
|
228
322
|
if (ms > 1000) this.push('slow', this.screen, { ms: Math.round(ms), kind: 'stall' })
|
|
229
323
|
}
|
|
230
324
|
|
|
231
|
-
// A tap with its element identity. dead = nothing on the touched element handles presses
|
|
232
|
-
|
|
325
|
+
// A tap with its element identity. dead = nothing on the touched element handles presses; it stays dead unless the
|
|
326
|
+
// screen changes within RESP_MS. The tap is queued once it is resolved: on its response, the next tap, or RESP_MS
|
|
327
|
+
// later (checked on every flush), with its own ts and screen. resp = ms to the first screen change or request start,
|
|
328
|
+
// 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.
|
|
329
|
+
tap(t: TapInput): void {
|
|
233
330
|
this.touch()
|
|
234
331
|
const now = t.ts ?? this.now()
|
|
235
|
-
|
|
332
|
+
this.release()
|
|
333
|
+
const h: Held = { t, ts: now, screen: this.screen }
|
|
334
|
+
this.lastTap = { ts: now, screen: this.screen }
|
|
335
|
+
this.taps = this.taps.filter((q) => now - q.t < RAGE_MS && Math.hypot(q.x - t.x, q.y - t.y) < RAGE_PT)
|
|
336
|
+
this.taps.push({ x: t.x, y: t.y, t: now, h })
|
|
337
|
+
if (this.taps.length === RAGE_N) h.burst = this.taps.map((q) => q.h)
|
|
338
|
+
this.held = h
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
private respond(screen: boolean): void {
|
|
342
|
+
const h = this.held
|
|
343
|
+
if (!h) return
|
|
344
|
+
const dt = this.now() - h.ts
|
|
345
|
+
if (dt > RESP_MS) return this.release()
|
|
346
|
+
h.resp ??= Math.max(0, Math.round(dt))
|
|
347
|
+
if (screen) {
|
|
348
|
+
h.moved = true
|
|
349
|
+
this.release()
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
private settle(all: boolean): void {
|
|
354
|
+
if (this.held && (all || this.now() - this.held.ts > RESP_MS)) this.release()
|
|
355
|
+
this.drain(all)
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
// While UI-state fingerprints run (uiState was called), a resolved tap with no response waits for the next walk.
|
|
359
|
+
private release(): void {
|
|
360
|
+
const h = this.held
|
|
361
|
+
if (!h) return
|
|
362
|
+
this.held = null
|
|
363
|
+
if (this.states && !h.checked && h.resp === undefined && !h.t.dead && !h.t.input) return void this.waiting.push(h)
|
|
364
|
+
this.emit(h)
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
private drain(all: boolean): void {
|
|
368
|
+
const now = this.now()
|
|
369
|
+
while (this.waiting.length && (all || now - this.waiting[0].ts > RESP_MS)) this.emit(this.waiting.shift()!)
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
private emit(h: Held): void {
|
|
373
|
+
const t = h.t
|
|
374
|
+
const dead = t.dead && !h.moved
|
|
375
|
+
if (dead) h.resp = undefined
|
|
376
|
+
const at = t.masked ? {} : { x: Math.round(t.x), y: Math.round(t.y) }
|
|
377
|
+
const p: Record<string, unknown> = { el: t.el, ...at, ...(!t.masked && { nx: t.nx, ny: t.ny }) }
|
|
236
378
|
if (t.id) p.id = t.id
|
|
237
379
|
if (t.label) p.label = t.label
|
|
238
|
-
if (
|
|
380
|
+
if (dead) p.dead = 1
|
|
239
381
|
if (t.input) p.input = 1
|
|
240
|
-
|
|
241
|
-
this.
|
|
242
|
-
|
|
243
|
-
if (
|
|
382
|
+
if (h.resp !== undefined) p.resp = h.resp
|
|
383
|
+
this.push('tap', undefined, p, h.ts, h.screen)
|
|
384
|
+
const rage = h.burst?.some((b) => b.resp === undefined)
|
|
385
|
+
if (rage) this.push('rage', undefined, { el: t.el, id: t.id, label: t.label, n: RAGE_N, ...at }, h.ts, h.screen)
|
|
386
|
+
if (rage || dead || (!t.input && h.resp === undefined)) this.signal(rage ? 'rage' : dead ? 'dead' : 'unresponsive')
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
// A replay signal (PROTOCOL.md 4.7): an unsampled session's ring of the last 30 s is released for upload.
|
|
390
|
+
private signal(why: ReplayWhy): void {
|
|
391
|
+
this.replay.signal(why, this.now())
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
// A UI-state fingerprint walk finished (h null: none possible). The first one on a screen is its baseline; a different h
|
|
395
|
+
// later on the same screen is a `state` event and the response of every tap waiting for this walk. quiet (after a
|
|
396
|
+
// vertical scroll) only moves the baseline.
|
|
397
|
+
uiState(h: string | null, n = 0, quiet = false): boolean {
|
|
398
|
+
this.states = true
|
|
399
|
+
const changed = h !== null && this.stateH !== undefined && h !== this.stateH && !quiet
|
|
400
|
+
if (h !== null) this.stateH = h
|
|
401
|
+
if (changed) {
|
|
402
|
+
const now = this.now()
|
|
403
|
+
for (const w of this.waiting) if (now - w.ts <= RESP_MS) w.resp = Math.round(now - w.ts)
|
|
404
|
+
this.respond(false)
|
|
405
|
+
}
|
|
406
|
+
if (this.held) this.held.checked = true
|
|
407
|
+
this.drain(true)
|
|
408
|
+
if (changed) this.push('state', undefined, { h, n })
|
|
409
|
+
return changed
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
// One focus span of a text input: ts = focus time, ms focused, edits (none for secure inputs), filled. Never a value or length.
|
|
413
|
+
field(f: { id: string; el: string; ts: number; ms: number; edits?: number; filled?: boolean; screen?: string }): void {
|
|
414
|
+
this.touch()
|
|
415
|
+
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)
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
// A request started (wrapped fetch / XMLHttpRequest): a response to the newest tap.
|
|
419
|
+
netStart(): void {
|
|
420
|
+
this.respond(false)
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
// A finished request; only failures (status >= 400, 0 = network error) and slow calls (> 3 s) become `net` events.
|
|
424
|
+
net(method: string, url: string, status: number, ms: number): void {
|
|
425
|
+
if (status > 0 && status < 400 && ms <= NET_SLOW_MS) return
|
|
426
|
+
const { host, path } = netTarget(url)
|
|
427
|
+
this.push('net', undefined, { m: method.toUpperCase().slice(0, 10), host, path, s: status, ms: Math.round(ms) })
|
|
428
|
+
if ((status === 0 || status >= 400) && this.now() - this.lastTap.ts <= ERRTAP_MS && this.lastTap.screen === this.screen) this.signal('errtap')
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
// A touch that was neither a tap nor a scroll (PROTOCOL.md 4.1 touch classes). ts = the touch start.
|
|
432
|
+
gesture(g: Gesture): void {
|
|
433
|
+
this.touch()
|
|
434
|
+
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)
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
// A container a touch scrolled settled at a new offset. ts = the touch end.
|
|
438
|
+
scrolled(s: Scrolled): void {
|
|
439
|
+
this.touch()
|
|
440
|
+
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)
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// Self-cost samples (ms) for perf on close: the touch-end handler, a replay capture, a fingerprint walk.
|
|
444
|
+
measure(kind: 'tap' | 'walk' | 'fp', ms: number): void {
|
|
445
|
+
const a = this.cost[kind]
|
|
446
|
+
a.push(ms)
|
|
447
|
+
if (a.length > 256) a.shift()
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
private perf(): Record<string, number | undefined> {
|
|
451
|
+
const c = this.cost
|
|
452
|
+
return { tap: p95(c.tap), walk: p95(c.walk), fp: p95(c.fp), rb: c.rb, eb: c.eb }
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
get replayOn(): boolean {
|
|
456
|
+
return this.cfg.replay !== false && this.loaded && this.active && this.consent !== 'denied' && !this.replay.off
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
// One replay capture (the walk of the current screen); true when it built a chunk (something changed).
|
|
460
|
+
replayFrame(w: ReplayWalk): boolean {
|
|
461
|
+
if (!this.replayOn) return false
|
|
462
|
+
return !!this.replay.frame(this.sessionId, this.sampled, w, this.now())
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
get replayBuffer(): Replay {
|
|
466
|
+
return this.replay
|
|
244
467
|
}
|
|
245
468
|
|
|
246
469
|
scroll(depth: number | null, drag: number): void {
|
|
@@ -255,13 +478,40 @@ export class Analytics {
|
|
|
255
478
|
.split('\n')
|
|
256
479
|
.slice(1, 6)
|
|
257
480
|
.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
|
-
|
|
481
|
+
this.push('error', err.name, { msg: redact(err.message).slice(0, 200), fatal: fatal ? 1 : undefined, stack })
|
|
482
|
+
this.signal(fatal ? 'crash' : 'error')
|
|
483
|
+
if (!fatal) return
|
|
484
|
+
this.persist()
|
|
485
|
+
const out = this.replay.out
|
|
486
|
+
if (out.length) this.st?.set(K.replay, JSON.stringify({ a: this.anon, why: 'crash', chunks: out.map((b) => b.c) })).catch(() => {})
|
|
260
487
|
}
|
|
261
488
|
|
|
262
|
-
purchase(p: { product: string; status: 'start' | 'done' | 'cancel' | 'fail'; price?: number; currency?: string; store?: string; trial?: boolean }): void {
|
|
489
|
+
purchase(p: { product: string; status: 'start' | 'done' | 'cancel' | 'fail' | 'shown' | 'pending' | 'not_shown'; price?: number; currency?: string; store?: string; trial?: boolean; renew?: boolean; conv?: boolean; at?: number; ps?: string; code?: string; sf?: string }): void {
|
|
263
490
|
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 })
|
|
491
|
+
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) })
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
// What happened at the store's purchase sheet for one buy tap; outcomes map onto the purchase statuses.
|
|
495
|
+
sheet(p: { product: string; outcome: SheetOutcome; priceString?: string; currency?: string; code?: string; storefront?: string; store?: string }): void {
|
|
496
|
+
const status = SHEET_STATUS[p.outcome]
|
|
497
|
+
if (!status) return
|
|
498
|
+
this.purchase({ product: p.product, status, currency: p.currency, store: p.store, ps: p.priceString, code: p.code, sf: p.storefront })
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
// Store truth: each entitlement's latest purchase against a per-product watermark. A newer one is a done (renew unless it
|
|
502
|
+
// is the subscription's first purchase, conv on the first paid period after a trial this install saw). Purchases from
|
|
503
|
+
// before this install's first launch, and quiet ones (restores, the wrapped call's own done), only move the watermark.
|
|
504
|
+
entitled(list: Entitled[], quiet = false, store = 'revenuecat'): void {
|
|
505
|
+
if (!this.loaded) return void this.ready.then(() => this.entitled(list, quiet, store))
|
|
506
|
+
let dirty = false
|
|
507
|
+
for (const e of list) {
|
|
508
|
+
const m = this.marks[e.product]
|
|
509
|
+
if (!e.product || !(e.at > 0) || (m && m.t >= e.at)) continue
|
|
510
|
+
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 })
|
|
511
|
+
this.marks[e.product] = e.trial ? { t: e.at, tr: 1 } : { t: e.at }
|
|
512
|
+
dirty = true
|
|
513
|
+
}
|
|
514
|
+
if (dirty) this.st?.set(K.purchases, JSON.stringify(this.marks)).catch(() => {})
|
|
265
515
|
}
|
|
266
516
|
|
|
267
517
|
// Wireframes are recorded once per screen per sampled session.
|
|
@@ -288,8 +538,9 @@ export class Analytics {
|
|
|
288
538
|
}
|
|
289
539
|
|
|
290
540
|
background(): void {
|
|
541
|
+
this.settle(true)
|
|
291
542
|
this.leave()
|
|
292
|
-
this.push('close')
|
|
543
|
+
this.push('close', undefined, { perf: this.perf() })
|
|
293
544
|
this.active = false
|
|
294
545
|
this.persist()
|
|
295
546
|
this.flush()
|
|
@@ -301,6 +552,7 @@ export class Analytics {
|
|
|
301
552
|
if (c === 'denied') {
|
|
302
553
|
this.queue = []
|
|
303
554
|
this.snaps = []
|
|
555
|
+
this.replay.clear()
|
|
304
556
|
this.persist()
|
|
305
557
|
} else if (c === 'granted') this.flush()
|
|
306
558
|
}
|
|
@@ -313,6 +565,26 @@ export class Analytics {
|
|
|
313
565
|
this.setConsent('granted')
|
|
314
566
|
}
|
|
315
567
|
|
|
568
|
+
// Right to be forgotten (PROTOCOL.md 7): drops everything still on the device (queue, wireframes, replay ring and a
|
|
569
|
+
// crash-saved ring), asks the server to delete what it recorded for this install (POST /analytics/v1/forget: events,
|
|
570
|
+
// wireframes, replay) and, once it has, starts over as a new anonymous install. Works whatever the consent. Resolves
|
|
571
|
+
// false when the server could not be reached; the id is kept so calling again retries.
|
|
572
|
+
async forget(): Promise<boolean> {
|
|
573
|
+
await this.ready
|
|
574
|
+
this.queue = []
|
|
575
|
+
this.snaps = []
|
|
576
|
+
this.replay.clear()
|
|
577
|
+
this.persist()
|
|
578
|
+
await this.st?.remove(K.replay).catch(() => {})
|
|
579
|
+
await this.inflight?.catch(() => {})
|
|
580
|
+
const f = this.cfg.fetch ?? fetch
|
|
581
|
+
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 }) })
|
|
582
|
+
.then((r) => r.ok)
|
|
583
|
+
.catch(() => false)
|
|
584
|
+
if (ok) await this.reset()
|
|
585
|
+
return ok
|
|
586
|
+
}
|
|
587
|
+
|
|
316
588
|
// Sign-out: a new anonymous id and session, nothing of the old user kept.
|
|
317
589
|
async reset(): Promise<void> {
|
|
318
590
|
await this.flush()
|
|
@@ -332,7 +604,8 @@ export class Analytics {
|
|
|
332
604
|
|
|
333
605
|
private async send(): Promise<void> {
|
|
334
606
|
await this.ready
|
|
335
|
-
|
|
607
|
+
this.settle(false)
|
|
608
|
+
if (this.sending || this.consent !== 'granted' || (!this.queue.length && !this.snaps.length && !this.replay.out.length)) return
|
|
336
609
|
this.sending = true
|
|
337
610
|
const events = this.queue.slice(0, BATCH)
|
|
338
611
|
const snaps = this.snaps.splice(0, 4)
|
|
@@ -345,9 +618,15 @@ export class Analytics {
|
|
|
345
618
|
if (!r.ok && r.status < 500 && r.status !== 429) {
|
|
346
619
|
if (this.cfg.debug) console.warn('[shotik] dropped batch', r.status)
|
|
347
620
|
} else if (!r.ok) throw new Error(String(r.status))
|
|
621
|
+
else this.cost.eb += body.length
|
|
348
622
|
this.queue.splice(0, events.length)
|
|
349
623
|
}
|
|
350
|
-
|
|
624
|
+
while (snaps.length) {
|
|
625
|
+
const r = await f(this.cfg.serverUrl + '/analytics/v1/snapshots', { method: 'POST', headers, body: JSON.stringify({ anonymousId: this.anon, ...snaps[0] }) })
|
|
626
|
+
if (!r.ok && (r.status >= 500 || r.status === 429)) throw new Error(String(r.status))
|
|
627
|
+
snaps.shift()
|
|
628
|
+
}
|
|
629
|
+
await this.sendReplay(f, headers)
|
|
351
630
|
this.backoff = 0
|
|
352
631
|
this.persist()
|
|
353
632
|
} catch {
|
|
@@ -359,7 +638,27 @@ export class Analytics {
|
|
|
359
638
|
if (this.queue.length >= BATCH && !this.backoff) return this.send()
|
|
360
639
|
}
|
|
361
640
|
|
|
641
|
+
// Replay chunks (PROTOCOL.md 4.7), up to 8 requests per flush. 403: replay is off or over quota for this app, so nothing
|
|
642
|
+
// more is captured or sent until the next launch. Wi-Fi only: held until wifi() says so.
|
|
643
|
+
private async sendReplay(f: typeof fetch, headers: Record<string, string>): Promise<void> {
|
|
644
|
+
const R = this.replay
|
|
645
|
+
if (!R.out.length || R.off) return
|
|
646
|
+
const opt = this.cfg.replay
|
|
647
|
+
if (opt && opt.wifiOnly && !(await (this.cfg.wifi?.() ?? Promise.resolve(false)).catch(() => false))) return
|
|
648
|
+
for (let n = 0; n < REPLAY_REQS; n++) {
|
|
649
|
+
const b = R.take()
|
|
650
|
+
if (!b) return
|
|
651
|
+
const body = '{"v":1,"a":' + JSON.stringify(this.anon) + ',"why":"' + b.why + '","chunks":[' + b.items.map((i) => i.s).join(',') + ']}'
|
|
652
|
+
const r = await f(this.cfg.serverUrl + '/analytics/v1/replay', { method: 'POST', headers, body })
|
|
653
|
+
if (r.status === 403) return R.clear(true)
|
|
654
|
+
if (!r.ok && (r.status >= 500 || r.status === 429)) throw new Error(String(r.status))
|
|
655
|
+
if (r.ok) this.cost.rb += body.length
|
|
656
|
+
R.done(b.items)
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
|
|
362
660
|
stop(): void {
|
|
661
|
+
this.settle(true)
|
|
363
662
|
this.active = false
|
|
364
663
|
if (this.timer) clearTimeout(this.timer)
|
|
365
664
|
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
|
+
}
|