@shotik/mcp 0.1.2 → 0.2.1

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.
@@ -0,0 +1,126 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { dirname, join } from 'node:path'
3
+ import { fileURLToPath } from 'node:url'
4
+
5
+ const here = dirname(fileURLToPath(import.meta.url))
6
+ const SEVERITIES = ['high', 'medium', 'low']
7
+ const AREAS = ['onboarding', 'paywall', 'purchase', 'apple-rule']
8
+ const PLATFORMS = ['ios', 'android', 'both']
9
+ const EVIDENCE_RE = /^brain:[a-z0-9-]+\/[A-Za-z0-9._-]+$/
10
+ const SECRET_FILE_RE = /(^|\/)(\.env[^/]*|[^/]*\.(pem|p8|key|p12|keystore|jks))$/i
11
+ const SECRET_TEXT_RE = /sk-[A-Za-z0-9]{8,}|AKIA[0-9A-Z]{8,}|-----BEGIN/
12
+ const CODE_RE = /^[A-Za-z0-9]{6,8}$/
13
+
14
+ export const base = () => (process.env.SHOTIK_WEB || 'https://shotik.app').replace(/\/+$/, '')
15
+
16
+ export function loadChecklist() {
17
+ return JSON.parse(readFileSync(join(here, 'checklist.json'), 'utf8'))
18
+ }
19
+
20
+ const stackKey = (s) => String(s).toLowerCase().replace(/[\s_]+/g, '-').replace(/^(rn|reactnative)$/, 'react-native').replace(/^jetpack-compose$|^android$/, 'kotlin').replace(/^ios$/, 'swift')
21
+
22
+ export function checklistText(stack) {
23
+ const c = loadChecklist()
24
+ const wanted = [stack ?? []].flat().map(stackKey).filter((s) => c.stacks.includes(s))
25
+ const stacks = wanted.length ? wanted : c.stacks
26
+ const lookFor = (look, s) => look[s] ?? look[c.fallback?.[s]]
27
+ const out = ['# Shotik audit checklist (' + c.schema + ')', 'Stacks: ' + stacks.join(', '), '', 'Walk every item against the app code. Report only what you found in a real file and line, with the item\'s evidence ref.', '']
28
+ out.push('## Where to look', ...stacks.map((s) => '- ' + s + ': purchases via ' + c.benchmarks[s].purchases.join(' or ') + '; read ' + c.benchmarks[s].look.join(', ')), '')
29
+ for (const area of c.areas) {
30
+ out.push('## ' + area)
31
+ for (const i of c.items.filter((x) => x.area === area)) {
32
+ out.push('', '### ' + i.id + ' [' + i.severity + '] ' + i.title)
33
+ for (const s of stacks) if (lookFor(i.look, s)) out.push('- look (' + s + '): ' + lookFor(i.look, s))
34
+ out.push('- why it costs money: ' + i.why, '- evidence: ' + i.evidence, '- fix (' + i.fix.stack + '):', '```', i.fix.code, '```')
35
+ }
36
+ out.push('')
37
+ }
38
+ return out.join('\n')
39
+ }
40
+
41
+ export const SCHEMA_TEXT = [
42
+ 'POST <base>/api/session/<code>/findings with JSON:',
43
+ '{ "app": { "name": string <=100, "platform": "ios"|"android"|"both", "stack": string[1..8] },',
44
+ ' "findings": [ { "severity": "high"|"medium"|"low", "area": "onboarding"|"paywall"|"purchase"|"apple-rule",',
45
+ ' "file": repo-relative path (no leading /, no .., no .env/.pem/.p8/.key/.p12/.keystore/.jks), "line": integer >= 1,',
46
+ ' "title": string <=120, "why": string <=600, "evidence"?: "brain:<topic>/<id>", "diff"?: string <=20 lines and <=2000 chars } ] (1..60),',
47
+ ' "done"?: boolean }',
48
+ 'Never include secrets (sk-..., AKIA..., -----BEGIN) or whole files. Send app on the first post; set done:true on the last.',
49
+ ].join('\n')
50
+
51
+ export function validateFindings(body, first) {
52
+ const bad = (error, field) => ({ error: { error, field } })
53
+ if (!body || typeof body !== 'object' || Array.isArray(body)) return bad('bad_json')
54
+ let app = null
55
+ if (body.app !== undefined) {
56
+ const a = body.app
57
+ if (!a || typeof a !== 'object' || Array.isArray(a)) return bad('bad_schema', 'app')
58
+ if (typeof a.name !== 'string' || !a.name.trim() || a.name.length > 100) return bad('bad_schema', 'app.name')
59
+ if (!PLATFORMS.includes(a.platform)) return bad('bad_schema', 'app.platform')
60
+ if (!Array.isArray(a.stack) || a.stack.length < 1 || a.stack.length > 8 || a.stack.some((s) => typeof s !== 'string' || !s || s.length > 40)) return bad('bad_schema', 'app.stack')
61
+ app = { name: a.name.trim(), platform: a.platform, stack: a.stack }
62
+ } else if (first) return bad('bad_schema', 'app')
63
+ if (!Array.isArray(body.findings) || body.findings.length < 1) return bad('bad_schema', 'findings')
64
+ if (body.findings.length > 60) return bad('too_many', 'findings')
65
+ if (body.done !== undefined && typeof body.done !== 'boolean') return bad('bad_schema', 'done')
66
+ const findings = []
67
+ for (let i = 0; i < body.findings.length; i++) {
68
+ const f = body.findings[i]
69
+ const at = (k) => 'findings[' + i + '].' + k
70
+ if (!f || typeof f !== 'object' || Array.isArray(f)) return bad('bad_schema', 'findings[' + i + ']')
71
+ if (!SEVERITIES.includes(f.severity)) return bad('bad_schema', at('severity'))
72
+ if (!AREAS.includes(f.area)) return bad('bad_schema', at('area'))
73
+ if (typeof f.file !== 'string' || !f.file || f.file.length > 200 || f.file.startsWith('/') || f.file.split(/[\\/]/).includes('..') || /^[A-Za-z]:/.test(f.file) || SECRET_FILE_RE.test(f.file)) return bad('bad_schema', at('file'))
74
+ if (!Number.isInteger(f.line) || f.line < 1 || f.line > 1000000) return bad('bad_schema', at('line'))
75
+ if (typeof f.title !== 'string' || !f.title.trim() || f.title.length > 120) return bad('bad_schema', at('title'))
76
+ if (typeof f.why !== 'string' || !f.why.trim() || f.why.length > 600) return bad('bad_schema', at('why'))
77
+ if (f.evidence !== undefined && (typeof f.evidence !== 'string' || !EVIDENCE_RE.test(f.evidence))) return bad('bad_schema', at('evidence'))
78
+ if (f.diff !== undefined) {
79
+ if (typeof f.diff !== 'string') return bad('bad_schema', at('diff'))
80
+ if (f.diff.length > 2000 || f.diff.split('\n').length > 20) return bad('diff_too_long', at('diff'))
81
+ if (SECRET_TEXT_RE.test(f.diff)) return bad('secret_in_diff', at('diff'))
82
+ }
83
+ if (SECRET_TEXT_RE.test(f.why) || SECRET_TEXT_RE.test(f.title)) return bad('secret_in_diff', at('why'))
84
+ const out = { severity: f.severity, area: f.area, file: f.file, line: f.line, title: f.title.trim(), why: f.why.trim() }
85
+ if (f.evidence) out.evidence = f.evidence
86
+ if (f.diff) out.diff = f.diff
87
+ findings.push(out)
88
+ }
89
+ return { app, findings, done: body.done === true }
90
+ }
91
+
92
+ function codeOf(code) {
93
+ if (typeof code !== 'string' || !CODE_RE.test(code.trim())) throw new Error('Pass the audit code from shotik.app/start (6-8 letters and digits).')
94
+ return code.trim().toUpperCase()
95
+ }
96
+
97
+ async function post(path, body) {
98
+ let res
99
+ try {
100
+ res = await fetch(base() + path, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })
101
+ } catch (e) {
102
+ throw new Error("Couldn't reach " + base() + ': ' + e.message)
103
+ }
104
+ const data = await res.json().catch(() => ({}))
105
+ if (res.status === 404) throw new Error('Unknown or expired audit code. Start a new audit at ' + base() + '/start.')
106
+ if (!res.ok) throw new Error('Shotik refused the request (' + res.status + '): ' + (data.error || 'error') + (data.field ? ' at ' + data.field : ''))
107
+ return data
108
+ }
109
+
110
+ export async function hello(code) {
111
+ return post('/api/session/' + codeOf(code) + '/hello', {})
112
+ }
113
+
114
+ export async function auditChecklist(a = {}) {
115
+ await hello(a.code)
116
+ return checklistText(a.stack) + '\n## Publish\n' + SCHEMA_TEXT + '\nThen call shotik_publish_findings with code ' + codeOf(a.code) + '.'
117
+ }
118
+
119
+ export async function publishFindings(a = {}) {
120
+ const code = codeOf(a.code)
121
+ const v = validateFindings({ app: a.app, findings: a.findings, done: a.done }, true)
122
+ if (v.error) throw new Error('Invalid findings: ' + v.error.error + (v.error.field ? ' at ' + v.error.field : ''))
123
+ const r = await post('/api/session/' + code + '/findings', { app: v.app, findings: v.findings, done: v.done })
124
+ const url = base() + r.projectUrl
125
+ return { accepted: r.accepted, total: r.total, status: r.status, url, say: 'Project: ' + url + '. Download Shotik to watch 40 personas walk your real build.' }
126
+ }
package/data/PROTOCOL.md CHANGED
@@ -42,6 +42,20 @@ Contents: 1 Transport and auth · 2 Identity · 3 Support · 4 Analytics · 5 St
42
42
  - **Backoff.** Reconnect delay = `min(30 s, 500 ms × 2^n) × uniform(0.8, 1.2)`, n = consecutive failures, reset to 0 on
43
43
  `ready`. Send retry delay = `min(30 s, 500 ms × 2^attempts)`. Analytics flush interval = `flushMs × 2^backoff`, backoff
44
44
  capped at 5 (10 s → 320 s), reset after a successful upload.
45
+ - **Default endpoint and plain http (added for RAH-267 (APPC-20), additive).** `serverUrl` is optional on every
46
+ platform. Without it the SDK uses one exported constant, `DEFAULT_SERVER = 'https://ingest.shotik.app'` (RN:
47
+ `src/client.ts`, imported by support and analytics), defined in exactly one place per port; an empty value makes the SDK
48
+ send nothing and warn once. In a release build (RN: `__DEV__ === false` and `debug` off; Swift: not DEBUG; Flutter:
49
+ `kReleaseMode`) an `http://` base URL is used only when its host is loopback (`localhost`, `*.localhost`, 127/8, `::1`),
50
+ `*.local`, 10/8, 172.16/12, 192.168/16, 169.254/16 or IPv6 ULA fc00::/7. Any other `http://` host: the SDK sends
51
+ nothing (no analytics, replay, snapshots, support or WebSocket), keeps its queues on the device and logs one warning.
52
+ `https://` is always allowed; development builds allow anything.
53
+ - **Retry-After (added for RAH-267 (APPC-20), additive).** A 429 or 503 with `Retry-After` (delay-seconds or an
54
+ HTTP-date) holds that client's requests for at least that long, capped at 1 h: analytics events, snapshots and replay
55
+ (the whole flush), and support sends and identify. The server sends seconds (≤ 3600) with 429 `quota_*` /
56
+ `rate_limited` and 503 `queue_full`. Without the header the backoff below applies; with it the next retry is
57
+ `max(backoff, Retry-After)`.
58
+ - **413.** The server answers 413 above its body limits (events 1 MB, replay 2 MB, snapshots 256 KB); see 4.2 and 4.7.
45
59
  - **CORS.** `/support/v1/*` answers OPTIONS with 204 and `access-control-allow-headers: content-type, x-shotik-key,
46
60
  x-shotik-user`, so a web build works too.
47
61
 
@@ -405,8 +419,13 @@ travel on their own route, `POST /analytics/v1/replay` (4.7), never inside event
405
419
 
406
420
  - Queue limit **2000** events (oldest dropped). Batch size **300**. Flush every **10 s** (`flushMs`), at 300 queued, on
407
421
  background, and on `flush()`. One upload at a time; while the queue holds ≥ 300 after a success, flush again at once.
408
- - Status: 2xx → remove the sent events. 5xx, 429, network → keep, back off. Other 4xx → drop that batch (it is malformed
409
- and would fail forever).
422
+ - Status: 2xx → remove the sent events. 5xx, 429, network → keep, back off (honouring `Retry-After`, 1). Other 4xx →
423
+ drop that batch (it is malformed and would fail forever).
424
+ - **413 (added for RAH-267 (APPC-20), additive).** A 413 on `/events` keeps the batch and halves the batch size for the
425
+ next attempt, which follows at once (300 → 150 → … → 1). A batch of one event that still gets 413 drops that event.
426
+ After a success the batch size is 300 again. Snapshots and replay chunks that get 413 are dropped like any other 4xx.
427
+ A replay 403 (`replay_off`, `replay_quota`) drops the held chunks and stops replay until the next launch (4.7);
428
+ events are unaffected.
410
429
  - Wireframes: `POST /analytics/v1/snapshots` body `{ anonymousId, sessionId, screen, ts, w, h, dark?, nodes }`, at most 4
411
430
  per flush, after the events.
412
431
  - Consent: `granted` (default) uploads; `pending` keeps events on the device until granted; `denied` drops the queue and
@@ -640,6 +659,21 @@ Every platform's widget follows the reference's design, refs and copy so a found
640
659
  numbers (7+ digits with a leading `+`, parentheses or space-separated groups) → `[phone]`; any other run of 7+
641
660
  digits with separators, and every digit run of 4+ → `[n]`. Labels then turn each remaining digit into `#` (as before).
642
661
  Stacks are code, not user data, and keep only the URL stripping.
662
+ - **Health filter (added for RAH-267 (APPC-20), additive).** After the redaction and before queueing, every tap and
663
+ rage label (anything that takes the label path) that contains a health term becomes `[health]`. Matching is
664
+ case-insensitive on the lowercased label and starts at a word start (the previous character is not a letter, digit or
665
+ `_`, Latin or Cyrillic). A term ending in `*` is a prefix; any other term must end at a word end, an English `-s` /
666
+ `-es` plural included; multi-word terms allow any whitespace between words. The built-in lexicon
667
+ (sdk/react-native/src/analytics/privacy.ts `HEALTH_TERMS`, copied verbatim by the ports) covers English and Russian:
668
+ symptoms and pain (pain, ache*, symptom*, injur*, боль/болит*, симптом*, травм*), diagnoses and conditions
669
+ (diagnos*, disease*, medical condition*, health condition*, chronic*, fasciitis, arthritis, diabet*, диагноз*, болезн*), medication (medic*, pill, dose,
670
+ prescription*, лекарств*, таблет*), vitals and body measures (heart rate, pulse, blood, glucose, insulin, blood
671
+ pressure, weight, bmi, пульс*, давлен*, вес and its case forms), reproductive health (pregnan*, menstrua*, period pain, ovulat*,
672
+ fertil*, беремен*, месячные and its case forms), mental health (anxiety, depress*, therapy, тревог*, депресс*) and
673
+ body parts (heel, foot, feet, arch, ankle, knee, hip, back pain, lower back, upper back, spine, пятк*, стопа and its case forms, колен*, спин*).
674
+ Words that are also UI words (Back, Billing period, Terms and Conditions) are listed only as health phrases, and Russian stems that would also hit everyday words (больше, весь, стоп, месячная подписка) are listed as whole word
675
+ forms instead. `healthTerms?: string[]` adds app terms under the same rules. The filter can't be turned off; element
676
+ ids (`id`, `el`) are unaffected; digits are still turned into `#`.
643
677
  - **Labels** (`labels` option, default `'a11y'`): `'a11y'` sends the element's accessibility label, else a name derived
644
678
  from its testID (`startTrialButton`, `start-trial` → `Start trial button`, `Start trial`), else nothing; `'visible'`
645
679
  also falls back to the visible text under the pressed element (the pre-2026-11-29 behaviour, ≤ 40 characters);
@@ -6,7 +6,7 @@ optional. Get the public key (`spk_…`) from Shotik → Support → SDK. It is
6
6
  ## 1. Add the package
7
7
 
8
8
  ```sh
9
- flutter pub add shotik # in pubspec.yaml: shotik: ^0.1.0
9
+ flutter pub add shotik # in pubspec.yaml: shotik: ^0.2.0
10
10
  flutter config --enable-swift-package-manager # once per machine; the iOS part is a Swift package
11
11
  ```
12
12
 
@@ -47,7 +47,7 @@ The full walkthrough, with troubleshooting, is in [INTEGRATION.md](INTEGRATION.m
47
47
  ```yaml
48
48
  # flutter pub add shotik
49
49
  dependencies:
50
- shotik: ^0.1.0
50
+ shotik: ^0.2.0
51
51
  ```
52
52
 
53
53
  ```dart
@@ -86,7 +86,8 @@ The iOS app needs Swift Package Manager support enabled once on the machine that
86
86
 
87
87
  | | |
88
88
  |---|---|
89
- | `Shotik.configure(appKey:, serverUrl:, debug:)` | Once, as early as you like. No I/O on the calling isolate. |
89
+ | `Shotik.configure(appKey:, serverUrl:, debug:)` | Once, as early as you like. No I/O on the calling isolate. `serverUrl` is optional and defaults to `DEFAULT_SERVER` (`https://ingest.shotik.app`). In release builds plain http is allowed only for private networks (loopback, `*.local`, 10/8, 172.16/12, 192.168/16, 169.254/16, fc00::/7); anything else sends nothing and warns once. |
90
+ | `ShotikAnalytics.enable(healthTerms:)` | Extra health terms (stems, en or ru). Tap and rage labels containing a built-in or app term are sent as `[health]`; the filter cannot be turned off. 429/503 `Retry-After` and 413 batch halving are handled for you. |
90
91
  | `ShotikRoot(child:)` | Wrap the app once (around `MaterialApp`). Deep links, the screenshot boundary, the root that taps are described against, and the scroll layer. |
91
92
  | `ShotikSupportWidget.builder(...)` | For `MaterialApp` / `CupertinoApp` / `WidgetsApp` `builder:`. `title`, `teamName`, `theme`, `launcher`, `launcherBottom` (distance above the bottom safe area, to clear a bottom button or tab bar), `quickReplies`, `locale`, `appName` (for "Rate {app}"), `frictionChip` (default `true`). |
92
93
  | `ShotikFrictionChip(theme:, locale:)` | The "Something wrong? Write to us" chip on its own, for apps that place it (set `frictionChip: false` on the widget). |
@@ -48,7 +48,7 @@
48
48
  ## 1. Подключите пакет
49
49
 
50
50
  ```sh
51
- flutter pub add shotik # в pubspec.yaml: shotik: ^0.1.0
51
+ flutter pub add shotik # в pubspec.yaml: shotik: ^0.2.0
52
52
  flutter config --enable-swift-package-manager # один раз на машине: iOS-часть собрана как Swift-пакет
53
53
  ```
54
54
 
@@ -106,7 +106,7 @@
106
106
  "dependencies",
107
107
  "shotik"
108
108
  ],
109
- "value": "^0.1.0"
109
+ "value": "^0.2.0"
110
110
  }
111
111
  ],
112
112
  "run": {
@@ -41,7 +41,7 @@ import { ShotikSupportProvider } from '@shotik/react-native'
41
41
  export default function RootLayout() {
42
42
  return (
43
43
  <GestureHandlerRootView style={{ flex: 1 }}>
44
- <ShotikSupportProvider appKey="spk_…" serverUrl="https://support.example.com">
44
+ <ShotikSupportProvider appKey="spk_…">
45
45
  <Stack />
46
46
  </ShotikSupportProvider>
47
47
  </GestureHandlerRootView>
@@ -53,6 +53,14 @@ The provider identifies the user anonymously, keeps the live stream open while t
53
53
  renders `<SupportWidget/>`, a bottom sheet that mounts on the first open. Pass `widget={false}` to place
54
54
  `<SupportWidget/>` yourself; it takes the same props.
55
55
 
56
+ **Server.** `serverUrl` is optional: without it the SDK talks to Shotik's ingest, `DEFAULT_SERVER`
57
+ (`https://ingest.shotik.app`, exported from the package). Pass `serverUrl` to use your own server, for example the Mac
58
+ during development (`http://127.0.0.1:4590` on the simulator, `http://<mac>.local:4590` or its LAN address on a
59
+ device). Release builds (`__DEV__` false, no `debug`) only use plain `http://` for loopback, `*.local` and private
60
+ network addresses (10/8, 172.16/12, 192.168/16, 169.254/16, IPv6 fc00::/7); any other `http://` host sends nothing
61
+ and logs one warning, so use `https://` for a public server. When the server answers 429 or 503 with `Retry-After`, the
62
+ SDK waits that long (at most an hour) before sending again; queued messages and events are kept meanwhile.
63
+
56
64
  ### Brand it
57
65
 
58
66
  ```tsx
@@ -41,7 +41,7 @@ import { ShotikSupportProvider } from '@shotik/react-native'
41
41
  export default function RootLayout() {
42
42
  return (
43
43
  <GestureHandlerRootView style={{ flex: 1 }}>
44
- <ShotikSupportProvider appKey="spk_…" serverUrl="https://support.example.com">
44
+ <ShotikSupportProvider appKey="spk_…">
45
45
  <Stack />
46
46
  </ShotikSupportProvider>
47
47
  </GestureHandlerRootView>
@@ -53,6 +53,14 @@ export default function RootLayout() {
53
53
  `<SupportWidget/>` — нижний лист, который монтируется при первом открытии. С `widget={false}` вы ставите
54
54
  `<SupportWidget/>` сами, пропсы те же.
55
55
 
56
+ **Сервер.** `serverUrl` можно не передавать: тогда SDK шлёт в ingest Shotik, `DEFAULT_SERVER`
57
+ (`https://ingest.shotik.app`, экспортируется из пакета). Свой сервер задаёт `serverUrl`, например Mac при разработке
58
+ (`http://127.0.0.1:4590` в симуляторе, `http://<mac>.local:4590` или LAN-адрес на устройстве). В релизных сборках
59
+ (`__DEV__` false, без `debug`) обычный `http://` разрешён только для loopback, `*.local` и частных сетей (10/8,
60
+ 172.16/12, 192.168/16, 169.254/16, IPv6 fc00::/7); с любым другим `http://`-хостом SDK ничего не отправляет и один
61
+ раз пишет предупреждение, так что для публичного сервера нужен `https://`. На 429 или 503 с `Retry-After` SDK ждёт
62
+ указанное время (не больше часа) и только потом шлёт снова; очередь сообщений и событий при этом сохраняется.
63
+
56
64
  ### Фирменный вид
57
65
 
58
66
  ```tsx
@@ -193,7 +201,7 @@ ShotikSupport.client?.setSubscription({ status: 'active', product: 'Pro yearly',
193
201
  ```tsx
194
202
  import { ShotikAnalytics, ShotikAnalyticsRoot, useShotikExpoRouter } from '@shotik/react-native/analytics'
195
203
 
196
- ShotikAnalytics.init({ appKey: 'spk_…', serverUrl: 'https://…' })
204
+ ShotikAnalytics.init({ appKey: 'spk_…' }) // serverUrl по умолчанию — DEFAULT_SERVER
197
205
 
198
206
  export default function RootLayout() {
199
207
  useShotikExpoRouter()
@@ -110,7 +110,7 @@
110
110
  "dependencies",
111
111
  "@shotik/react-native"
112
112
  ],
113
- "value": "^0.2.0"
113
+ "value": "^0.3.0"
114
114
  }
115
115
  ],
116
116
  "run": {
@@ -5,7 +5,7 @@ See how people really use your app (what they tap, where they get stuck, which s
5
5
  ```tsx
6
6
  import { ShotikAnalytics, ShotikAnalyticsRoot, ShotikMask, useShotikExpoRouter } from '@shotik/react-native/analytics'
7
7
 
8
- ShotikAnalytics.init({ appKey: 'spk_…', serverUrl: 'https://…' }) // the same key as Support
8
+ ShotikAnalytics.init({ appKey: 'spk_…' }) // the same key as Support; serverUrl defaults to DEFAULT_SERVER
9
9
  ShotikAnalytics.trackRevenueCat(Purchases) // optional: purchases, renewals and trial conversions
10
10
 
11
11
  export default function RootLayout() {
@@ -22,10 +22,12 @@ ShotikAnalytics.identify(user.id) // after s
22
22
  **Privacy by default:**
23
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
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
+ - Health never leaves in a label: a tap or rage label that mentions a symptom, diagnosis, medication, vital, reproductive or mental health, or a body part (English and Russian, e.g. "Heel pain", "Пульс") is sent as `[health]`. `healthTerms: ['plantar', 'orthot*']` adds your own words (a trailing `*` matches any ending). The filter can't be turned off; element ids are unaffected.
25
26
  - Custom prop keys that look like personal data (`email`, `phone`, `name`, `token`, `password`, `address`) are dropped, with a warning in development.
26
27
  - 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.
27
28
  - 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.
28
29
  - `<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.
30
+ - `serverUrl` is optional (default `DEFAULT_SERVER`, `https://ingest.shotik.app`). Release builds send nothing over plain `http://` except to loopback, `*.local` and private network addresses.
29
31
  - `init({ consent: 'pending' })` keeps events on the device until `ShotikAnalytics.setConsent('granted')`. `optOut()` drops them.
30
32
  - `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
33
 
@@ -98,7 +98,7 @@
98
98
  "dependencies",
99
99
  "@shotik/react-native"
100
100
  ],
101
- "value": "^0.2.0"
101
+ "value": "^0.3.0"
102
102
  }
103
103
  ],
104
104
  "run": {
@@ -17,22 +17,22 @@ screens, taps, scroll depth, stalls, crashes and purchases, and draws wireframes
17
17
 
18
18
  ## 1. Install
19
19
 
20
- **Xcode project.** Go to File → Add Package Dependencies…, paste `https://github.com/rahimwws/shotik-app` into the search field, keep
21
- "Up to Next Major Version" from `0.1.0`, then add the libraries you want to your app target. Most apps want
20
+ **Xcode project.** Go to File → Add Package Dependencies…, paste `https://github.com/rahimwws/shotik-swift` into the search field, keep
21
+ "Up to Next Major Version" from `0.1.1`, then add the libraries you want to your app target. Most apps want
22
22
  `ShotikAnalytics`, `ShotikSupport` and `ShotikSupportUI`.
23
23
 
24
24
  **Swift package.** In your own `Package.swift`:
25
25
 
26
26
  ```swift
27
- dependencies: [.package(url: "https://github.com/rahimwws/shotik-app", from: "0.1.0")],
27
+ dependencies: [.package(url: "https://github.com/rahimwws/shotik-swift", from: "0.2.0")],
28
28
  targets: [.target(name: "App", dependencies: [
29
- .product(name: "ShotikSupportUI", package: "shotik-app"),
30
- .product(name: "ShotikAnalytics", package: "shotik-app"),
29
+ .product(name: "ShotikSupportUI", package: "shotik-swift"),
30
+ .product(name: "ShotikAnalytics", package: "shotik-swift"),
31
31
  ])]
32
32
  ```
33
33
 
34
34
  The package lives in the Shotik repo: its `Package.swift` sits at the repo root and builds `sdk/swift/Sources`.
35
- Releases are the repo's bare semver tags (`0.1.0`).
35
+ Releases are the repo's bare semver tags (`0.1.1`).
36
36
 
37
37
  | You link | You get |
38
38
  |---|---|
@@ -74,7 +74,14 @@ func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options: UIS
74
74
  }
75
75
  ```
76
76
 
77
- `ShotikConfig` has more options: `Shotik.configure(ShotikConfig(appKey:serverUrl:consent:snapshots:flushMs:sessionTimeoutMs:autoCapture:debug:))`.
77
+ `ShotikConfig` has more options: `Shotik.configure(ShotikConfig(appKey:serverUrl:consent:snapshots:flushMs:sessionTimeoutMs:autoCapture:debug:labels:replay:replayWifiOnly:healthTerms:))`.
78
+
79
+ **Cloud rules.**
80
+ - `serverUrl` is optional and defaults to `DEFAULT_SERVER` (`https://ingest.shotik.app`). An empty URL sends nothing and warns once.
81
+ - In release builds plain `http` is allowed only for loopback, `*.local`, 10/8, 172.16/12, 192.168/16, 169.254/16 and fc00::/7; any other `http` host sends nothing and warns once. `https` is always allowed, and debug builds allow anything.
82
+ - A 429 or 503 with `Retry-After` (seconds or an HTTP date) is waited out, at most one hour; without the header the usual backoff applies.
83
+ - A 413 on events halves the next batch (300, 150, … 1); a single event that still gets 413 is dropped, and the batch returns to 300 after a success.
84
+ - After redaction, a tap or rage label that contains a health term (built-in English and Russian lexicon) is sent as `[health]`. `healthTerms: ["tarot"]` adds your own terms; the filter cannot be turned off.
78
85
 
79
86
  | Option | Default | |
80
87
  |---|---|---|
@@ -82,8 +89,11 @@ func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options: UIS
82
89
  | `snapshots` | `0.2` | Share of sessions that record wireframes (0…1) |
83
90
  | `flushMs` | `10000` | Analytics upload interval while active |
84
91
  | `sessionTimeoutMs` | 30 min | Inactivity that starts a new session |
85
- | `autoCapture` | `true` | Taps, screens, stalls, crashes, StoreKit. Manual calls work either way |
92
+ | `autoCapture` | `true` | Taps, screens, stalls, crashes, StoreKit, network. Manual calls work either way |
86
93
  | `debug` | `false` | Prints every event to the console |
94
+ | `labels` | `.a11y` | Tap labels: `.a11y` the element's own accessibility label or its identifier as words, `.visible` also its visible text, `.none` no labels (see 5.4) |
95
+ | `replay` | `true` | Wireframe replay (see 5.1). `false` captures and sends none |
96
+ | `replayWifiOnly` | `false` | Holds replay uploads while the device isn't on Wi-Fi or Ethernet (`NWPathMonitor`) |
87
97
 
88
98
  Every call made before `configure` (identify, push token, track) is held and replayed in order once it runs. Analytics
89
99
  holds up to 500 calls.
@@ -103,6 +113,13 @@ indicator while the AI drafts or you type in Shotik, quick-reply chips, "Talk to
103
113
  as attachments. It supports light and dark, Dynamic Type, VoiceOver and RTL. Copy is English or Russian, picked from the
104
114
  device locale. The widget's views are built on the first open, so nothing exists before then except the launcher.
105
115
 
116
+ It also covers retention and refunds (PROTOCOL.md §3.7-3.13). A consent line above the composer asks whether AI may draft
117
+ replies. Buttons under your replies show pending, done and failed. "Did this help?" appears once a conversation is resolved.
118
+ A "Something wrong? Write to us" chip shows after friction. The home rows are Subscription, Rate {app} and Delete my data.
119
+ Subscription leads to an honest cancel: one optional reason with Skip, "Cancel in App Store" on the same screen, then at
120
+ most one alternative of yours at equal weight. It also leads to a help-first refund screen with "Request a refund" in view.
121
+ "Subscribed by mistake" goes straight to the refund screen. Every element traces to a row in [REFS.md](REFS.md).
122
+
106
123
  Add `.shotikSupportLauncher()` to a view for a floating button with the unread badge. For a badge on your own Help row:
107
124
 
108
125
  ```swift
@@ -120,10 +137,14 @@ RootView().shotikSupportSheet(SupportWidgetOptions(
120
137
  teamName: "Rahim", // label above your replies (default "Team" / "Команда")
121
138
  quickReplies: ["Billing", "Report a bug"], // chips on a new conversation
122
139
  theme: SupportTheme(accent: "#FF5A1F", radius: 18, font: "Inter-Regular", fontBold: "Inter-SemiBold"),
123
- locale: "ru" // default: the device locale; en is the fallback
140
+ locale: "ru", // default: the device locale; en is the fallback
141
+ appName: "Walkito" // the "Rate Walkito" row (default "Rate the app")
124
142
  ))
125
143
  ```
126
144
 
145
+ `frictionChip: false` hides the friction chip, so you can place `ShotikSupportFrictionChip(options)` yourself (UIKit apps
146
+ host it in a `UIHostingController`).
147
+
127
148
  | `SupportTheme` | Default | |
128
149
  |---|---|---|
129
150
  | `accent` | iOS blue | Your bubbles, the send button, the launcher, links |
@@ -185,6 +206,17 @@ rest. `SupportClient` is the platform-free core and is what the tests drive.
185
206
  | `ShotikSupport.observe(_:)` | State on the main queue; the first call delivers the current state |
186
207
  | `receiptOf(_:in:conversation:offline:)` | `sending · queued · failed · sent · delivered · seen` for the user's messages |
187
208
  | `ShotikImage.attachment(from:)` | A JPEG `LocalAttachment` (max 2048 px) from image data, for your own picker |
209
+ | `ShotikSupport.configure(appKey:serverUrl:options:)` | `SupportOptions(aiConsent:appStoreId:storeKitSubscription:onAction:openUrl:requestReview:analytics:)`. Hooks run on main; nil ones use the StoreKit built-ins (Manage subscriptions, `AppStore.sync`, offer code sheet, refund request, `SubscriptionStoreView` for `change_plan` on iOS 17+, `AppStore.requestReview`). `storeKitSubscription` (default `false`) reads the subscription from StoreKit 2 |
210
+ | `ShotikSupport.setAiConsent(_:)` | AI-drafted replies allowed (`true`) or person only (`false`); `state.aiConsent` is `nil` until the user picks |
211
+ | `ShotikSupport.setSubscription(_:)` | `SupportSubscription(status:product:period:price:renewsAt:expiresAt:trialEndsAt:willRenew:store:)` from your billing, shown to you next to the chat; `nil` for none |
212
+ | `ShotikSupport.runAction(_:conversationId:_:)` | Runs a button under a message (`message.actions`): `onAction`, else the store link. Reports `done · cancelled · failed` to you |
213
+ | `ShotikSupport.canRun(_:value:)` | Whether an action can run here: your `onAction` runs every kind; the built-ins run the store kinds, and `write_review` needs `appStoreId`. The widget shows only the rows that can run |
214
+ | `ShotikSupport.track(_:_:conversationId:)` | Widget events: `cancelStarted`, `cancelReason`, `offerShown`, `offerAccepted`, `cancelContinued`, `refundHelp`, `refundRequested` |
215
+ | `ShotikSupport.reviewMoment(_:)` | A success moment; asks for a review only when your review rules pass. Never call it from a button |
216
+ | `ShotikSupport.friction(_:)`, `openFriction()`, `dismissFriction()` | A failed purchase, rage tap or repeated error shows `state.friction` ("Something wrong? Write to us"), once per session |
217
+ | `ShotikSupport.rate(_:score:comment:)` | "Did this help?" on a resolved conversation: `1` or `-1`; `Conversation.csat` keeps it |
218
+ | `ShotikSupport.askForOffer(_:)` | The user took the save offer for a cancel reason (`state.widget.offers`, a label only, never the code): a new conversation that goes to you, not the AI. Your reply sends the code or the plan change |
219
+ | `await ShotikSupport.deleteMyData()` | Delete my data (Apple 5.1.1(v), GDPR): wipes the device at once (conversations, queue, ids, AI consent, review ledger, push token) and the install's analytics (`options.analytics`, else ShotikAnalytics), then has the server erase the install. `.pending` while offline: the request waits on the device and retries with backoff, after a restart too |
188
220
 
189
221
  ## 5. Analytics
190
222
 
@@ -200,13 +232,23 @@ with backoff while offline, and the queue survives restarts.
200
232
  | Screens and time on screen | The top view controller after each transition, named by `.shotikScreen()`, the navigation title, or the class |
201
233
  | Taps, dead taps, rage taps | One passive gesture recognizer per window (`cancelsTouchesInView = false`, it never recognizes). On touch end it only queues the point, the time, the current screen and the `.shotikTag` under the finger; the element is resolved right after. **UIKit:** automatic, from the hit-test chain: the control's `accessibilityIdentifier` (sent as `id` and as `#id` on `el`), its label and class. **SwiftUI:** the tap, its position, screen and rage are automatic, but the element is only named where you add `.shotikTag` (see 5.3); without it the tap is `el: "View"` with no label and no id, and it is never called dead. Taps in the Support widget count on a "Support" screen |
202
234
  | Scroll depth | Sampled from the scroll view under a drag when the finger lifts |
235
+ | Gestures (`gesture`) | The same recognizer follows each touch to its last finger: a still press over 0.5 s is `long`, a move with no scroll view on its axis a `swipe` (fast) or `pan`, two fingers a `pinch` with its scale. Deltas and durations only, never a position |
236
+ | Settled scrolls (`scroll`) | A drag on a `UIScrollView` (SwiftUI's `ScrollView` and `List` included) is read once its offset settles after the momentum: offset, content and visible length, `hz: 1` for horizontal ones and the page of a paging one |
237
+ | Replay | Keyframe and diff wireframes of the key window after screen changes, taps, gestures, settled scrolls and state changes (at most one walk per second, never while a finger is down; the diff is built off the main thread). Boxes only: text is a bar, images and web views boxes, inputs, secure fields and masked views one box with nothing inside read. Sampled sessions (`snapshots`) upload as they go; every other session keeps the last 30 s in memory (at most 1 MB) and uploads it only after a rage tap, a dead or unresponsive tap, a failed request right after a tap, an error or a crash (saved and sent on the next launch). A 403 from the server stops replay until the next launch |
238
+ | SDK cost | Every `close` carries `perf`: p95 ms of the touch handling, the replay capture and the UI-state walk, and the replay and event bytes uploaded |
203
239
  | Stalls, slow screens | A background watchdog pings the main queue every 500 ms |
204
240
  | Crashes | `NSSetUncaughtExceptionHandler`, chained to the previous handler |
205
- | Purchases | StoreKit 2 `Transaction.updates` and a scan of `Transaction.all` on foreground |
241
+ | Tap response (`resp`) | Milliseconds from a tap to the next screen change or request start, within 1.5 s. A rage burst where every tap got a response is not rage |
242
+ | Failed and slow requests (`net`) | A `URLProtocol` the SDK registers for `URLSession.shared`: status ≥ 400, network errors and calls over 3 s, as method, host, a templated path (`/users/:id`), status and duration. No bodies, headers, query strings or credentials; requests to your Shotik server are skipped. Sessions with their own configuration are not seen |
243
+ | UI state (`state`) | A walk of the key window's interactive UIKit views about 0.4 s after a tap (never while a finger is down, at most once per second), hashed into 8 hex characters, so one screen with several steps (a pager, a multi-step paywall) splits into steps. A changed state also counts as the tap's response. SwiftUI counts where UIKit views back it |
244
+ | Fields (`field`) | The begin, change and end editing notifications of `UITextField` and `UITextView`: time focused, an edit count (none for secure fields) and whether the field holds text. Never the text or its length |
245
+ | Purchases | StoreKit 2 `Transaction.updates` and a scan of `Transaction.all` on foreground. Subscription renewals are `done` with `renew: 1` (revenue, not a new purchase), the first paid period after a trial adds `conv: 1`, and every `done` carries the store's purchase time as `at`. `trial` comes from the bought transaction's offer |
246
+ | Release | `sdk` (`swift/<version>`), `tzo` (UTC offset in minutes) and `dev: 1` in Debug builds, next to the app version and build |
206
247
  | Wireframes | A view hierarchy walk on the sampled sessions, encoded off the main thread |
207
248
 
208
- **Limits of swizzle-free capture.** Scroll depth is sampled when a drag ends, so momentum after the finger lifts is not
209
- counted, and programmatic scrolling is not tracked at all. Screens are checked after touches end and on scene
249
+ **Limits of swizzle-free capture.** Scroll depth and settled scrolls start from a drag, so programmatic scrolling is not
250
+ tracked at all. Replay sees SwiftUI only through the UIKit views it is made of (scroll views, lists, platform views, colored
251
+ backgrounds); content SwiftUI draws in layers alone doesn't appear. Screens are checked after touches end and on scene
210
252
  activation, so a screen pushed by code without a touch is named on the next touch. Use `.shotikScreen()` or
211
253
  `ShotikAnalytics.screen` for exact names. Swift runtime traps (`fatalError`, force unwraps) are not Objective-C
212
254
  exceptions, so they stay with your crash reporter.
@@ -238,13 +280,23 @@ it only reaches the SDK while an assistive technology is running.
238
280
  ### 5.4 Masking
239
281
 
240
282
  Inputs never send their value. Taps on text fields and secure fields carry `input: 1` and no label, and wireframes draw
241
- them as empty boxes. To hide anything else from tap labels and wireframes:
283
+ them as empty boxes. Taps inside a mask or on a secure field also leave out their position (`x`, `y`, `nx`, `ny`). Labels
284
+ follow the `labels` option: by default a button sends its own accessibility label or its `accessibilityIdentifier` as
285
+ words (`startTrial` → "Start trial"), never its visible text. A UIKit label equal to the element's own text counts as
286
+ text. Labels, error messages, custom event names and string props are redacted on the device (emails, phone numbers,
287
+ ids, tokens, long numbers and query strings). To hide anything else from tap labels, wireframes and replay:
242
288
 
243
289
  ```swift
244
290
  BalanceView().shotikMask() // SwiftUI
245
- cardView.shotikMasked = true // UIKit
291
+ cardView.shotikMasked = true // UIKit, on any view
246
292
  ```
247
293
 
294
+ Masking is on by default and can't be turned off: no option unmasks inputs, and replay never reads text from any view,
295
+ masked or not. **What replay collects**, for the App Store privacy label (Product Interaction, not linked to the user,
296
+ analytics): screen layouts as boxes (kind, position, size, background color, corner radius), the screen name, scroll
297
+ offsets, gesture kinds with distances, and the session and install ids. Never text, input values, images, web content
298
+ or touch positions. The server keeps replay 30 days unless an insight cites the session.
299
+
248
300
  ### 5.5 Custom events
249
301
 
250
302
  ```swift
@@ -252,7 +304,9 @@ ShotikAnalytics.track("Plan selected", ["plan": "annual", "step": 3])
252
304
  ShotikAnalytics.error(error) // a handled error, with the top stack frames
253
305
  ```
254
306
 
255
- Custom props are free-form. Never put personal data in them (names, emails, free text the user typed).
307
+ Custom props and identify traits whose key contains `email`, `phone`, `name`, `token`, `password` or `address` are
308
+ dropped on the device (with a console line in Debug builds), so `plan_name` is dropped too: call it `plan`. String values
309
+ are redacted. Still, never put personal data in props (names, emails, free text the user typed).
256
310
 
257
311
  ### 5.6 Purchases
258
312
 
@@ -275,6 +329,11 @@ ShotikAnalytics.optOut() // .denied: drop the queue and record nothing
275
329
 
276
330
  The choice is persisted, so later launches can omit `consent`. Support is not affected by analytics consent.
277
331
 
332
+ For a user's data deletion request, `await ShotikAnalytics.forget()` drops what is still on the device (queue,
333
+ wireframes, replay, a crash-saved replay), has the server delete everything recorded for the install and starts over as
334
+ a new anonymous install. It returns `false` when the server can't be reached and keeps the id, so call it again to retry.
335
+ Consent doesn't gate it.
336
+
278
337
  ## 6. Performance and size
279
338
 
280
339
  | Budget (PROTOCOL.md §8) | Measured |
@@ -319,7 +378,9 @@ cd sdk/swift && swift test
319
378
 
320
379
  The suite covers every conformance case in PROTOCOL.md §9 with a manual clock, a fake transport and fake sockets. That
321
380
  includes the packed wire example byte for byte, the outbox, backoff, the 4003 re-identify, receipts, typing, consent and
322
- the network budget. The live test runs against a real Shotik server when `SHOTIK_LIVE_URL`, `SHOTIK_LIVE_KEY` and
381
+ the network budget. WidgetFlowTests mirrors server/test/support-widget.test.ts: the cancel flow, the subscription row,
382
+ CSAT, action states and the en/ru copy. The replay privacy gate (no typed value in any replay frame or upload) and the mask flag tests
383
+ need UIKit, so they run only on an iOS simulator destination (`xcodebuild test`), not under `swift test` on macOS. The live test runs against a real Shotik server when `SHOTIK_LIVE_URL`, `SHOTIK_LIVE_KEY` and
323
384
  `SHOTIK_LIVE_TOKEN` are set:
324
385
 
325
386
  ```sh