@shotik/mcp 0.0.0-stage → 0.1.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.
Files changed (39) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +40 -2
  3. package/README.ru.md +40 -0
  4. package/data/PROTOCOL.md +386 -0
  5. package/data/flutter/INTEGRATION.md +197 -0
  6. package/data/flutter/README.md +112 -0
  7. package/data/flutter/README.ru.md +165 -0
  8. package/data/flutter/guide.json +190 -0
  9. package/data/flutter/recipe.json +364 -0
  10. package/data/react-native/README.md +194 -0
  11. package/data/react-native/README.ru.md +192 -0
  12. package/data/react-native/guide.json +136 -0
  13. package/data/react-native/recipe.json +263 -0
  14. package/data/react-native/src/analytics/README.md +32 -0
  15. package/data/react-native/src/analytics/recipe.json +263 -0
  16. package/data/storecheck/packs/ai.json +1 -0
  17. package/data/storecheck/packs/dating.json +1 -0
  18. package/data/storecheck/packs/education.json +1 -0
  19. package/data/storecheck/packs/finance.json +1 -0
  20. package/data/storecheck/packs/fitness.json +1 -0
  21. package/data/storecheck/packs/health.json +1 -0
  22. package/data/storecheck/packs/kids.json +1 -0
  23. package/data/storecheck/packs/language.json +1 -0
  24. package/data/storecheck/packs/mindfulness.json +1 -0
  25. package/data/storecheck/packs/music.json +1 -0
  26. package/data/storecheck/packs/nutrition.json +1 -0
  27. package/data/storecheck/packs/photo-video.json +1 -0
  28. package/data/storecheck/packs/productivity.json +1 -0
  29. package/data/storecheck/packs/spirituality.json +1 -0
  30. package/data/storecheck/packs/taxonomy.json +1 -0
  31. package/data/storecheck/packs/utilities.json +1 -0
  32. package/data/storecheck/storecheck.browser.js +314 -0
  33. package/data/swift/README.md +327 -0
  34. package/data/swift/README.ru.md +333 -0
  35. package/data/swift/guide.json +189 -0
  36. package/data/swift/recipe.json +506 -0
  37. package/package.json +42 -4
  38. package/server.mjs +144 -0
  39. package/sources.json +86 -0
@@ -0,0 +1,197 @@
1
+ # Integrating Shotik into a Flutter app
2
+
3
+ Eight steps, each a few lines. Steps 1 to 4 give you a working support chat and automatic analytics; the rest are
4
+ optional. Get the public key (`spk_…`) from Shotik → Support → SDK. It is a public app key, so it is safe to ship.
5
+
6
+ ## 1. Add the package
7
+
8
+ ```sh
9
+ flutter pub add shotik # in pubspec.yaml: shotik: ^0.1.0
10
+ flutter config --enable-swift-package-manager # once per machine; the iOS part is a Swift package
11
+ ```
12
+
13
+ There is nothing to add to `ios/` or `android/`: Flutter links the plugin (`ShotikPlugin`) itself. CocoaPods is not
14
+ needed. An app that still uses CocoaPods for other plugins keeps working; Flutter mixes both. `ios/shotik.podspec`
15
+ stays as a fallback for apps that have not enabled SwiftPM; with SwiftPM on, Flutter uses `ios/shotik/Package.swift`.
16
+
17
+ ## 2. Configure and wrap the root
18
+
19
+ ```dart
20
+ import 'package:shotik/shotik.dart';
21
+
22
+ const shotikKey = String.fromEnvironment('SHOTIK_APP_KEY');
23
+ const shotikUrl = String.fromEnvironment('SHOTIK_SERVER_URL');
24
+
25
+ void main() {
26
+ Shotik.configure(appKey: shotikKey, serverUrl: shotikUrl);
27
+ runApp(const ShotikRoot(child: MyApp()));
28
+ }
29
+ ```
30
+
31
+ `configure` does no I/O: it stores the two values and returns (the sample measures it; see "Configure cost" below).
32
+ The client, storage and device info load on the next event-loop turn. Calling it again with the same values is a no-op.
33
+
34
+ `ShotikRoot` goes around your `MaterialApp` / `CupertinoApp` / `MaterialApp.router`, once. It routes deep links to
35
+ Shotik, gives the widget a boundary for screenshots and is the root taps are described against. Taps are read from
36
+ Flutter's pointer router (a global route, no widget and no gesture arena entry, so it never steals taps), and the
37
+ target is described on pointer down, before your handler navigates away.
38
+
39
+ ## 3. Add the widget and the observer
40
+
41
+ ```dart
42
+ MaterialApp(
43
+ navigatorObservers: [ShotikAnalytics.navigatorObserver],
44
+ builder: ShotikSupportWidget.builder(
45
+ title: 'Walkito',
46
+ teamName: 'Rahim',
47
+ quickReplies: const ['Billing', 'Report a bug'],
48
+ theme: const ShotikSupportTheme(accent: Color(0xFFFF5A1F), radius: 18, fontFamily: 'Inter'),
49
+ ),
50
+ home: const Home(),
51
+ )
52
+ ```
53
+
54
+ If your app already has a `builder:`, nest it: `builder: (context, child) => ShotikSupportWidget(child: yourBuilder(context, child))`.
55
+
56
+ GoRouter: `GoRouter(observers: [ShotikAnalytics.navigatorObserver], ...)`, and one more in every `ShellRoute(observers: [...])`.
57
+ Each read of `navigatorObserver` returns a new observer, so one per navigator is right.
58
+
59
+ Screen names are the route's `settings.name` as written (`/paywall`); routes without a name are not reported. Name a
60
+ screen yourself where routes have no name or one route holds several screens (tabs, a PageView); `ShotikScreen` wins
61
+ over the route name:
62
+
63
+ ```dart
64
+ ShotikScreen(name: 'Paywall', child: PaywallView())
65
+ ```
66
+
67
+ ## 4. Open it from Help
68
+
69
+ ```dart
70
+ ListTile(title: const Text('Help'), onTap: () => ShotikSupport.open());
71
+ ```
72
+
73
+ Or pass `launcher: true` to the builder for a floating button with the unread badge. It sits at the bottom end, 20 pt
74
+ above the home indicator. If your screens have a bottom call to action or a tab bar, lift it with `launcherBottom`, the
75
+ distance above the bottom safe area: `ShotikSupportWidget.builder(launcher: true, launcherBottom: 132)` clears two
76
+ stacked 46 pt buttons with 20 pt padding. Without a bottom button anywhere, leave it out.
77
+
78
+ Deep link: add a URL scheme (iOS `CFBundleURLTypes` in `ios/Runner/Info.plist`, Android an intent filter) and
79
+ `myapp://support` opens the chat over the current screen; `ShotikRoot` catches it before your router sees it. With
80
+ your own link handler (app_links, a push tap), call `ShotikSupport.handleLink(uri)`; it returns true when it opened the
81
+ sheet.
82
+
83
+ ## 5. Identify after your own sign-in
84
+
85
+ ```dart
86
+ ShotikSupport.identify(userId: user.id, email: user.email, name: user.name, attributes: {'plan': 'pro'});
87
+ ShotikAnalytics.identify(user.id, {'plan': 'pro'});
88
+
89
+ // sign-out
90
+ ShotikSupport.reset();
91
+ ShotikAnalytics.reset();
92
+ ```
93
+
94
+ Safe anywhere, including an auth listener that fires before `runApp`: calls are held until configure. Anonymous users
95
+ keep their chats after sign-in. Every identify sends the device context (platform, OS, model, app version and build,
96
+ locale, time zone).
97
+
98
+ ## 6. Push
99
+
100
+ ```dart
101
+ final token = await FirebaseMessaging.instance.getToken(); // or getAPNSToken()
102
+ await ShotikSupport.setPushToken(token, platform: Platform.isIOS ? 'ios' : 'android');
103
+ ```
104
+
105
+ Every founder or AI reply is recorded as a push-ready event with the user's token and a preview. Open the chat from a
106
+ notification tap with `ShotikSupport.open(conversationId)` or `handleLink`.
107
+
108
+ ## 7. Masking, consent, purchases
109
+
110
+ **Masking.** Text fields (anything built on `EditableText`) are always masked: their taps carry no label and their
111
+ wireframe is an empty box. Wrap anything else private:
112
+
113
+ ```dart
114
+ ShotikMask(child: CardNumberView(card))
115
+ ```
116
+
117
+ Wireframes never contain characters in any case: text is drawn as grey bars sized like the line, and images as boxes.
118
+
119
+ **Consent.** Analytics starts granted. To wait for the user's answer:
120
+
121
+ ```dart
122
+ ShotikAnalytics.enable(consent: Consent.pending); // before or after configure; events are held on the device
123
+ ShotikAnalytics.optIn(); // sends what was held
124
+ ShotikAnalytics.optOut(); // drops the queue and stops recording
125
+ ```
126
+
127
+ The answer is remembered across launches.
128
+
129
+ **Purchases with in_app_purchase.** One line where you set up the store:
130
+
131
+ ```dart
132
+ ShotikAnalytics.watchPurchases(InAppPurchase.instance.purchaseStream, products: productDetails);
133
+ ```
134
+
135
+ It reads `productID`, `status` (pending → `start`, purchased → `done`, canceled → `cancel`, error → `fail`) and, from `products`, `rawPrice` and `currencyCode` by name, so the SDK does not depend
136
+ on the package. Other stores (RevenueCat, your own server): call
137
+ `ShotikAnalytics.purchase(product: 'pro.annual', status: 'start' | 'done' | 'fail' | 'cancel', price: 39.99, currency: 'USD', trial: true)`.
138
+
139
+ ## 8. Attachments (optional)
140
+
141
+ "Screenshot" in the attach menu works out of the box: the sheet steps aside, the app is captured and encoded to JPEG
142
+ natively. For "Photo", give the SDK your picker (any plugin you already use):
143
+
144
+ ```dart
145
+ ShotikSupport.attachmentPicker = () async {
146
+ final x = await ImagePicker().pickImage(source: ImageSource.gallery, maxWidth: 2048);
147
+ if (x == null) return null;
148
+ return LocalAttachment(bytes: await x.readAsBytes(), type: x.mimeType ?? 'image/jpeg', name: x.name);
149
+ };
150
+ ```
151
+
152
+ ## How taps are identified (debug vs release)
153
+
154
+ A tap is recorded with an element path like `PlanCard>Btn#annual`, the developer key on its own as `id` (`annual`), and
155
+ a label like `Start trial # days` (digits become `#`). Rage taps carry the same `el`, `id` and `label`. The pieces come from different places, and they don't all survive every build:
156
+
157
+ | Piece | Source | debug / profile / release | release with `--obfuscate` |
158
+ |---|---|---|---|
159
+ | Widget names (`PlanCard>Btn`) | `runtimeType` of the two nearest app widgets above the tap handler | kept | minified, so skipped |
160
+ | `#annual` | `ValueKey('annual')` on or near the target, else `Semantics(identifier: 'annual')` | kept | kept |
161
+ | Label | `Semantics(label:)`, else the visible text under the target | kept | kept |
162
+ | Dead tap | no tap or long-press handler on the hit path | kept | kept |
163
+
164
+ So with `--obfuscate` an element reads `Button#annual` (or `View` for a dead tap). Give the taps you care about
165
+ (paywall buttons, onboarding steps) a `ValueKey` or `Semantics(identifier:)`, and the funnel reads the same in every
166
+ build. Framework widgets (Container, GestureDetector, InkWell, Padding, Scaffold, Material, ScrollNotificationObserver…)
167
+ and private classes are never used as names, so a Help row reads `Settings>SampleScreen#help`.
168
+
169
+ While the Support sheet is open, Analytics counts it as a screen named `Support`: taps in it carry that screen, and
170
+ closing it records a `leave` for Support and returns to the screen underneath without a new screen view.
171
+
172
+ ## Configure cost
173
+
174
+ The sample prints `[shotik] configure N us` and shows it on its settings screen. `test/perf_test.dart` measures 20
175
+ calls in `flutter test` (JIT, asserts on): the first call stays under the 5 ms budget, and later calls take tens of
176
+ microseconds. A release (AOT) build is faster than both.
177
+
178
+ ## Troubleshooting
179
+
180
+ - **The header says Offline.** The phone can't reach `serverUrl`. A simulator reaches the Mac at `http://127.0.0.1:<port>`;
181
+ an Android emulator at `http://10.0.2.2:<port>`; a device needs the Mac's LAN address or an HTTPS deployment. Check
182
+ with `curl <serverUrl>/health`.
183
+ - **"unknown app key" / status error.** The key doesn't belong to this server. Create it again in Shotik.
184
+ - **`http://` blocked.** iOS App Transport Security and Android's cleartext policy allow only HTTPS by default. Use
185
+ HTTPS, or add a development-only exception (`NSAllowsLocalNetworking`, `android:usesCleartextTraffic` in debug).
186
+ - **"No route defined for /support".** Something consumed the link before `ShotikRoot`: make sure `ShotikRoot` wraps the
187
+ app (it must be above `MaterialApp`), or call `ShotikSupport.handleLink` from your own handler.
188
+ - **iOS build asks for CocoaPods or can't find ShotikPlugin.** Run `flutter config --enable-swift-package-manager`, then
189
+ `flutter clean && flutter build ios`.
190
+ - **No taps in Analytics.** Run with `Shotik.configure(..., debug: true)`: every recorded event prints as
191
+ `[shotik] tap …`, and a skipped one prints why (`multi-touch`, `moved`, `long press`, `no ShotikRoot`).
192
+ - **No screens in Analytics.** The observer is missing on that navigator (GoRouter shells need their own), or routes
193
+ have no names: add `ShotikScreen(name:)`.
194
+ - **Messages show "Will send when you're back online".** They are waiting for the server (offline, unreachable, 5xx
195
+ or 429) and go out on their own once it is reachable. Only a 4xx answer shows "Not sent · Retry".
196
+ - **Nothing persists between launches on a test device.** The anonymous id and queue live in Application Support; a
197
+ reinstall clears them, which is expected.
@@ -0,0 +1,112 @@
1
+ # shotik (Flutter)
2
+
3
+ Shotik's Support chat and Analytics for Flutter apps. Users write from your app and the conversation lands in Shotik's
4
+ Support inbox on your Mac, where you or the AI answer; replies arrive live. Analytics records sessions, screens, taps
5
+ (with rage and dead taps), scroll depth, errors, stalls, purchases and your own events, packed in the same wire format
6
+ as the React Native and Swift SDKs.
7
+
8
+ - Zero third-party dependencies: `flutter` only. HTTP and WebSocket use `dart:io`; the session token lives in the
9
+ Keychain (iOS) or private app storage (Android) through a small native plugin.
10
+ - `Shotik.configure` does no I/O. It stores the key and URL and returns; the modules start on the next event-loop turn.
11
+ Calls made before it (an auth listener at startup, a push token on launch) are held and replayed in order.
12
+ - Import only what you use: `package:shotik/support.dart` (client), `support_ui.dart` (client + widget),
13
+ `analytics.dart`, or `shotik.dart` for everything.
14
+ - Support: anonymous id that moves to the user on sign-in, optimistic sends with an offline queue that survives
15
+ restarts, a live stream with backoff, receipts (sending, queued, sent, delivered, seen, failed), typing, quick
16
+ replies, "Talk to a person", photos and screenshots, unread counts, push token.
17
+ - The widget: a bottom sheet built from plain Flutter widgets (no Material or Cupertino look), a spring open and drag to
18
+ dismiss, an optional launcher with an unread badge, light and dark, text scaling, semantics labels, RTL, English and
19
+ Russian copy from the device locale.
20
+ - Analytics: screens from a `NavigatorObserver` (MaterialApp, CupertinoApp, GoRouter), taps identified by widget names,
21
+ keys and `Semantics(identifier:)`, wireframes that never contain characters, `ShotikMask` for anything private,
22
+ consent, one-line `in_app_purchase` wiring.
23
+ - Flutter 3.24+ and Dart 3.5+. iOS 13+ as a Swift package (no CocoaPods); Android minSdk 21.
24
+
25
+ The full walkthrough, with troubleshooting, is in [INTEGRATION.md](INTEGRATION.md). Русская версия: [README.ru.md](README.ru.md).
26
+
27
+ ## Quick start
28
+
29
+ ```yaml
30
+ # flutter pub add shotik
31
+ dependencies:
32
+ shotik: ^0.1.0
33
+ ```
34
+
35
+ ```dart
36
+ import 'package:shotik/shotik.dart';
37
+
38
+ void main() {
39
+ Shotik.configure(appKey: 'spk_…', serverUrl: 'https://support.example.com');
40
+ runApp(const ShotikRoot(child: MyApp()));
41
+ }
42
+
43
+ class MyApp extends StatelessWidget {
44
+ const MyApp({super.key});
45
+
46
+ @override
47
+ Widget build(BuildContext context) => MaterialApp(
48
+ navigatorObservers: [ShotikAnalytics.navigatorObserver],
49
+ builder: ShotikSupportWidget.builder(title: 'Walkito', quickReplies: const ['Billing', 'Report a bug']),
50
+ home: const Home(),
51
+ );
52
+ }
53
+
54
+ // Help row
55
+ onTap: () => ShotikSupport.open(),
56
+
57
+ // After your own sign-in / on sign-out
58
+ ShotikSupport.identify(userId: user.id, email: user.email, name: user.name);
59
+ ShotikAnalytics.identify(user.id);
60
+ ShotikSupport.reset();
61
+ ShotikAnalytics.reset();
62
+ ```
63
+
64
+ The iOS app needs Swift Package Manager support enabled once on the machine that builds it:
65
+ `flutter config --enable-swift-package-manager`.
66
+
67
+ ## API
68
+
69
+ | | |
70
+ |---|---|
71
+ | `Shotik.configure(appKey:, serverUrl:, debug:)` | Once, as early as you like. No I/O on the calling isolate. |
72
+ | `ShotikRoot(child:)` | Wrap the app once (around `MaterialApp`). Deep links, the screenshot boundary, the root that taps are described against, and the scroll layer. |
73
+ | `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`. |
74
+ | `ShotikSupport.open([conversationId])`, `close()` | Show or hide the sheet. |
75
+ | `ShotikSupport.identify(userId:, name:, email:, attributes:)`, `reset()` | Signed-in user / sign-out (new anonymous id). |
76
+ | `ShotikSupport.setPushToken(token, platform:)` | APNs or FCM token; `null` clears it. |
77
+ | `ShotikSupport.handleLink(uri)` | `<scheme>://support` opens the sheet. `ShotikRoot` already routes platform links here. |
78
+ | `ShotikSupport.attachmentPicker` | Your image picker; with it set the attach menu offers "Photo". "Screenshot" needs nothing. |
79
+ | `ShotikSupport.client`, `clientListenable` | The `SupportClient`: `state` (conversations, messages, unread, typing, status), `send`, `retry`, `handoff`. |
80
+ | `ShotikAnalytics.navigatorObserver` | One per navigator. Starts analytics. |
81
+ | `ShotikScreen(name:, child:)` | Names a screen explicitly (tabs, pages without a route name). |
82
+ | `ShotikMask(child:)` | Hidden from tap labels and wireframes. Text fields are always masked. |
83
+ | `ShotikAnalytics.track(name, props)`, `screen(name)`, `identify(userId, traits)` | Custom events, manual screens, the user. |
84
+ | `ShotikAnalytics.purchase(...)`, `watchPurchases(stream, products:)` | Purchases, by hand or from `in_app_purchase`. |
85
+ | `ShotikAnalytics.enable(consent:, snapshots:, flushMs:, sessionTimeoutMs:, debug:)` | Options; `optIn()` / `optOut()` / `setConsent()`. |
86
+ | `ShotikAnalytics.flush()`, `reset()`, `ids` | Send now, new anonymous id, current ids. |
87
+
88
+ | `ShotikSupportTheme` | Default | |
89
+ |---|---|---|
90
+ | `accent` | iOS blue | Your bubbles, send button, launcher, links |
91
+ | `onAccent` | white | Text and glyphs on the accent |
92
+ | `radius` | `18` | Bubble radius; the sheet, chips and field follow it |
93
+ | `fontFamily`, `fontFamilyBold` | system | Regular and semibold families |
94
+ | `brightness` | platform | Force light or dark |
95
+ | `light`, `dark` | | `ShotikColors` overrides |
96
+
97
+ ## Sample
98
+
99
+ `example/` is "Shotik Sample" (bundle id `ai.shotik.sample.flutter`, URL scheme `shotiksampleflutter`). See
100
+ [example/README.md](example/README.md).
101
+
102
+ ## Tests
103
+
104
+ ```sh
105
+ flutter analyze
106
+ flutter test
107
+ ```
108
+
109
+ 50 tests: the PROTOCOL.md section 9 conformance cases against a fake Shotik server, the packed batch compared byte for
110
+ byte with the reference `wire.ts` output, the sheet (open, optimistic send, receipts, typing, quick replies, light and
111
+ dark, 2x text, Russian copy), tap identity and wireframes, and `[perf]` timings for configure, batch encoding and tap
112
+ description.
@@ -0,0 +1,165 @@
1
+ # shotik (Flutter)
2
+
3
+ Чат поддержки и аналитика Shotik для приложений на Flutter. Пользователь пишет прямо из приложения, разговор попадает
4
+ во входящие Support в Shotik на вашем Mac, а отвечаете вы или ИИ. Ответы приходят сразу. Аналитика записывает сессии,
5
+ экраны, тапы (включая «яростные» и «мёртвые»), глубину прокрутки, ошибки, подвисания, покупки и ваши собственные
6
+ события в том же формате, что и SDK для React Native и Swift.
7
+
8
+ - Никаких сторонних зависимостей, только `flutter`. HTTP и WebSocket работают через `dart:io`, токен сессии хранится в
9
+ Keychain (iOS) или в закрытом хранилище приложения (Android) через небольшой нативный плагин.
10
+ - `Shotik.configure` не делает ввода-вывода: сохраняет ключ и адрес и сразу возвращается, модули стартуют на следующем
11
+ витке цикла событий. Вызовы, сделанные раньше (слушатель авторизации при запуске, push-токен), придерживаются и
12
+ выполняются по порядку.
13
+ - Подключайте только нужное: `package:shotik/support.dart` (клиент), `support_ui.dart` (клиент и виджет),
14
+ `analytics.dart` или `shotik.dart` целиком.
15
+ - Поддержка: анонимный id, который переходит к пользователю после входа; сообщения появляются сразу и ждут в очереди
16
+ без сети (очередь переживает перезапуск); живой поток с переподключением; статусы (отправляется, в очереди,
17
+ отправлено, доставлено, прочитано, не отправлено); «печатает…»; быстрые ответы; «Позвать человека»; фото и снимки
18
+ экрана; счётчики непрочитанного; push-токен.
19
+ - Виджет: нижняя шторка из обычных виджетов Flutter (без вида Material или Cupertino), открывается пружиной, закрывается
20
+ свайпом вниз; по желанию плавающая кнопка со счётчиком; светлая и тёмная темы, крупный шрифт, подписи для
21
+ VoiceOver/TalkBack, RTL, тексты на английском и русском по языку устройства.
22
+ - Аналитика: экраны через `NavigatorObserver` (MaterialApp, CupertinoApp, GoRouter), тапы по именам виджетов, ключам и
23
+ `Semantics(identifier:)`, вайрфреймы без единого символа текста, `ShotikMask` для всего личного, согласие
24
+ пользователя, подключение `in_app_purchase` одной строкой.
25
+ - Flutter 3.24+ и Dart 3.5+. iOS 13+ как Swift-пакет (без CocoaPods), Android minSdk 21.
26
+
27
+ ## 1. Подключите пакет
28
+
29
+ ```sh
30
+ flutter pub add shotik # в pubspec.yaml: shotik: ^0.1.0
31
+ flutter config --enable-swift-package-manager # один раз на машине: iOS-часть собрана как Swift-пакет
32
+ ```
33
+
34
+ В `ios/` и `android/` ничего добавлять не нужно: Flutter сам подключит плагин `ShotikPlugin`. CocoaPods не нужен.
35
+
36
+ ## 2. Настройте и оберните корень
37
+
38
+ ```dart
39
+ import 'package:shotik/shotik.dart';
40
+
41
+ void main() {
42
+ Shotik.configure(appKey: 'spk_…', serverUrl: 'https://support.example.com');
43
+ runApp(const ShotikRoot(child: MyApp()));
44
+ }
45
+ ```
46
+
47
+ Публичный ключ (`spk_…`) берётся в Shotik → Support → SDK, его можно держать в сборке. `ShotikRoot` ставится один раз
48
+ вокруг `MaterialApp` / `CupertinoApp` / `MaterialApp.router`: он перехватывает диплинки, даёт виджету границу для
49
+ снимка экрана и держит слой записи тапов (один `Listener`, в арену жестов не входит и тапы не крадёт).
50
+
51
+ ## 3. Виджет и обсервер
52
+
53
+ ```dart
54
+ MaterialApp(
55
+ navigatorObservers: [ShotikAnalytics.navigatorObserver],
56
+ builder: ShotikSupportWidget.builder(
57
+ title: 'Walkito',
58
+ teamName: 'Рахим',
59
+ quickReplies: const ['Оплата', 'Сообщить об ошибке'],
60
+ theme: const ShotikSupportTheme(accent: Color(0xFFFF5A1F), radius: 18, fontFamily: 'Inter'),
61
+ ),
62
+ home: const Home(),
63
+ )
64
+ ```
65
+
66
+ Если у приложения уже есть `builder:`, вложите его: `builder: (context, child) => ShotikSupportWidget(child: yourBuilder(context, child))`.
67
+ GoRouter: `GoRouter(observers: [ShotikAnalytics.navigatorObserver], ...)` и ещё по одному в каждом `ShellRoute`.
68
+
69
+ Имя экрана берётся из `settings.name` маршрута как есть (`/paywall`); безымянные маршруты не попадают в отчёт. Там, где
70
+ имени нет или один маршрут показывает несколько экранов (вкладки, PageView), задайте его сами:
71
+ `ShotikScreen(name: 'Paywall', child: PaywallView())`.
72
+
73
+ ## 4. Откройте чат из «Помощи»
74
+
75
+ ```dart
76
+ ListTile(title: const Text('Помощь'), onTap: () => ShotikSupport.open());
77
+ ```
78
+
79
+ Или передайте `launcher: true`, чтобы показать плавающую кнопку со счётчиком. Если внизу экранов есть кнопка действия
80
+ или таб-бар, поднимите её через `launcherBottom` — отступ от нижней безопасной зоны, например
81
+ `ShotikSupportWidget.builder(launcher: true, launcherBottom: 132)`. Диплинк `myapp://support` (схема в
82
+ `CFBundleURLTypes` в `ios/Runner/Info.plist` или intent-filter на Android) открывает чат поверх текущего экрана.
83
+ Из своего обработчика ссылок или тапа по пушу вызывайте `ShotikSupport.handleLink(uri)`.
84
+
85
+ ## 5. Идентификация после входа
86
+
87
+ ```dart
88
+ ShotikSupport.identify(userId: user.id, email: user.email, name: user.name, attributes: {'plan': 'pro'});
89
+ ShotikAnalytics.identify(user.id, {'plan': 'pro'});
90
+
91
+ // выход
92
+ ShotikSupport.reset();
93
+ ShotikAnalytics.reset();
94
+ ```
95
+
96
+ Вызывать можно где угодно, даже до `runApp`. Анонимные чаты остаются у пользователя после входа. Вместе с identify
97
+ уходит контекст устройства: платформа, версия ОС, модель, версия и сборка приложения, язык и часовой пояс.
98
+
99
+ ## 6. Push
100
+
101
+ ```dart
102
+ final token = await FirebaseMessaging.instance.getToken();
103
+ await ShotikSupport.setPushToken(token, platform: Platform.isIOS ? 'ios' : 'android');
104
+ ```
105
+
106
+ Каждый ответ ваш или ИИ записывается как событие для пуша с токеном пользователя и превью.
107
+
108
+ ## 7. Маскирование, согласие, покупки
109
+
110
+ **Маскирование.** Текстовые поля (всё, что построено на `EditableText`) скрыты всегда: у их тапов нет подписи, а в
111
+ вайрфрейме это пустой прямоугольник. Всё остальное личное оберните в `ShotikMask(child: ...)`. Символов в вайрфреймах
112
+ не бывает вообще: текст рисуется серыми полосками размером со строку.
113
+
114
+ **Согласие.** По умолчанию аналитика включена. Чтобы дождаться ответа пользователя:
115
+
116
+ ```dart
117
+ ShotikAnalytics.enable(consent: Consent.pending); // события копятся на устройстве
118
+ ShotikAnalytics.optIn(); // отправит накопленное
119
+ ShotikAnalytics.optOut(); // очистит очередь и перестанет записывать
120
+ ```
121
+
122
+ Ответ запоминается между запусками.
123
+
124
+ **Покупки через in_app_purchase** одной строкой:
125
+
126
+ ```dart
127
+ ShotikAnalytics.watchPurchases(InAppPurchase.instance.purchaseStream, products: productDetails);
128
+ ```
129
+
130
+ Другие магазины (RevenueCat, свой сервер): `ShotikAnalytics.purchase(product: 'pro.annual', status: 'done', price: 39.99, currency: 'USD')`,
131
+ где `status` — `start`, `done`, `fail` или `cancel`.
132
+
133
+ ## 8. Вложения (по желанию)
134
+
135
+ «Снимок экрана» работает сразу. Для «Фото» передайте SDK свой выбор картинки (любой плагин, который у вас уже есть):
136
+ `ShotikSupport.attachmentPicker = () async => LocalAttachment(bytes: ..., type: 'image/jpeg')`.
137
+
138
+ ## Как опознаются тапы в debug и release
139
+
140
+ Тап записывается с путём элемента вроде `PlanCard>Btn#annual`, ключом разработчика отдельно в `id` (`annual`) и
141
+ подписью вроде `Start trial # days` (цифры заменяются на `#`). Имена виджетов берутся из `runtimeType` и сохраняются в debug, profile и release. В release с `--obfuscate`
142
+ они минифицируются и пропускаются, и элемент читается как `Button#annual`. `ValueKey`, `Semantics(identifier:)`,
143
+ подпись и признак «мёртвого» тапа сохраняются во всех сборках. Дайте важным кнопкам (пейвол, шаги онбординга)
144
+ `ValueKey` или `Semantics(identifier:)`, и воронка будет одинаковой в любой сборке. Служебные виджеты фреймворка
145
+ (Scaffold, Material, ScrollNotificationObserver…) в имена не попадают. Пока открыта шторка поддержки, аналитика считает её
146
+ экраном `Support`; после закрытия записывается `leave` и текущим снова становится экран под ней.
147
+
148
+ ## Если что-то не так
149
+
150
+ - **В шапке «Нет сети».** Телефон не видит `serverUrl`. Симулятор достаёт до Mac по `http://127.0.0.1:<порт>`, эмулятор
151
+ Android по `http://10.0.2.2:<порт>`, устройству нужен адрес Mac в локальной сети или HTTPS. Проверка:
152
+ `curl <serverUrl>/health`.
153
+ - **«unknown app key».** Ключ не от этого сервера. Создайте его заново в Shotik.
154
+ - **`http://` заблокирован.** iOS ATS и Android по умолчанию пускают только HTTPS. Используйте HTTPS или исключение
155
+ только для разработки.
156
+ - **«No route defined for /support».** Ссылку перехватили раньше `ShotikRoot`: он должен стоять выше `MaterialApp`.
157
+ - **iOS просит CocoaPods или не находит ShotikPlugin.** `flutter config --enable-swift-package-manager`, затем
158
+ `flutter clean && flutter build ios`.
159
+ - **В аналитике нет тапов.** Включите `Shotik.configure(..., debug: true)`: каждое событие печатается в лог как
160
+ `[shotik] tap …`, а пропущенный тап — с причиной.
161
+ - **В аналитике нет экранов.** На этом навигаторе нет обсервера (у ShellRoute в GoRouter свой) или у маршрутов нет имён.
162
+ - **Под сообщениями «Отправим, когда появится связь».** Они ждут сервер (нет сети, сервер недоступен, 5xx или 429)
163
+ и уйдут сами, когда он станет доступен. «Не отправлено · Повторить» появляется только при ответе 4xx.
164
+
165
+ Подробная версия на английском: [INTEGRATION.md](INTEGRATION.md).
@@ -0,0 +1,190 @@
1
+ {
2
+ "schema": "shotik.guide/1",
3
+ "sdk": "shotik",
4
+ "variables": [
5
+ "APP_KEY",
6
+ "SERVER_URL"
7
+ ],
8
+ "steps": [
9
+ {
10
+ "id": "install",
11
+ "title": "Add the SDK",
12
+ "body": "From pub.dev. iOS builds it as a Swift package, so no CocoaPods.",
13
+ "title_ru": "Подключите SDK",
14
+ "body_ru": "Из pub.dev. На iOS собирается как Swift-пакет, без CocoaPods.",
15
+ "code": {
16
+ "lang": "sh",
17
+ "file": "terminal",
18
+ "snippet": "flutter pub add shotik\n\n# once per Mac: flutter config --enable-swift-package-manager"
19
+ },
20
+ "check": {
21
+ "kind": "dependency",
22
+ "value": "shotik"
23
+ }
24
+ },
25
+ {
26
+ "id": "configure",
27
+ "title": "Configure and wrap",
28
+ "body": "Before runApp. No I/O, under 5 ms.",
29
+ "title_ru": "Настройте и оберните",
30
+ "body_ru": "До runApp. Без ввода-вывода, быстрее 5 мс.",
31
+ "code": {
32
+ "lang": "dart",
33
+ "file": "lib/main.dart",
34
+ "snippet": "import 'package:shotik/shotik.dart';\n\nvoid main() {\n Shotik.configure(appKey: '{{APP_KEY}}', serverUrl: '{{SERVER_URL}}');\n runApp(const ShotikRoot(child: MyApp()));\n}"
35
+ },
36
+ "check": {
37
+ "kind": "file-contains",
38
+ "value": "Shotik.configure("
39
+ }
40
+ },
41
+ {
42
+ "id": "widget",
43
+ "title": "Add the chat and screens",
44
+ "body": "The builder renders the sheet; the observer records screens and taps.",
45
+ "title_ru": "Добавьте чат и экраны",
46
+ "body_ru": "Builder рисует шторку чата, обсервер записывает экраны и тапы.",
47
+ "code": {
48
+ "lang": "dart",
49
+ "file": "lib/app.dart",
50
+ "snippet": "MaterialApp(\n navigatorObservers: [ShotikAnalytics.navigatorObserver],\n builder: ShotikSupportWidget.builder(title: 'My App'),\n home: const Home(),\n)"
51
+ },
52
+ "check": {
53
+ "kind": "file-contains",
54
+ "value": "ShotikSupportWidget"
55
+ }
56
+ },
57
+ {
58
+ "id": "brand",
59
+ "title": "Match your brand",
60
+ "body": "Accent, radius and font. Light, dark and Russian come built in.",
61
+ "title_ru": "Под ваш бренд",
62
+ "body_ru": "Акцент, скругление и шрифт. Светлая, тёмная тема и русский уже внутри.",
63
+ "code": {
64
+ "lang": "dart",
65
+ "file": "lib/app.dart",
66
+ "snippet": "ShotikSupportWidget.builder(\n title: 'My App',\n launcher: true,\n theme: const ShotikSupportTheme(accent: Color(0xFFFF5A1F), radius: 18),\n quickReplies: const ['Billing', 'Report a bug'],\n)"
67
+ },
68
+ "check": {
69
+ "kind": "file-contains",
70
+ "value": "ShotikSupportTheme("
71
+ },
72
+ "optional": true
73
+ },
74
+ {
75
+ "id": "help",
76
+ "title": "Open from Help",
77
+ "body": "Point your Help or Contact row at the chat.",
78
+ "title_ru": "Откройте из «Помощи»",
79
+ "body_ru": "Направьте строку «Помощь» или «Связаться» в чат.",
80
+ "code": {
81
+ "lang": "dart",
82
+ "file": "settings screen",
83
+ "snippet": "ListTile(\n title: const Text('Help'),\n onTap: () => ShotikSupport.open(),\n)"
84
+ },
85
+ "check": {
86
+ "kind": "file-contains",
87
+ "value": "ShotikSupport.open("
88
+ }
89
+ },
90
+ {
91
+ "id": "route",
92
+ "title": "Deep link",
93
+ "body": "myapp://support opens the chat (push taps too). Add the URL scheme.",
94
+ "title_ru": "Диплинк",
95
+ "body_ru": "myapp://support открывает чат, в том числе из пуша. Добавьте URL-схему.",
96
+ "code": {
97
+ "lang": "xml",
98
+ "file": "ios/Runner/Info.plist",
99
+ "snippet": "<key>CFBundleURLTypes</key>\n<array>\n <dict>\n <key>CFBundleURLSchemes</key>\n <array><string>myapp</string></array>\n </dict>\n</array>"
100
+ },
101
+ "check": {
102
+ "kind": "file-contains",
103
+ "value": "CFBundleURLSchemes"
104
+ }
105
+ },
106
+ {
107
+ "id": "identify",
108
+ "title": "Identify after sign-in",
109
+ "body": "Anonymous chats move to the user.",
110
+ "title_ru": "Идентификация после входа",
111
+ "body_ru": "Анонимные чаты переходят к пользователю.",
112
+ "code": {
113
+ "lang": "dart",
114
+ "file": "auth listener",
115
+ "snippet": "ShotikSupport.identify(userId: user.id, email: user.email, name: user.name);\nShotikAnalytics.identify(user.id);\n// on sign-out\nShotikSupport.reset();\nShotikAnalytics.reset();"
116
+ },
117
+ "check": {
118
+ "kind": "file-contains",
119
+ "value": "ShotikSupport.identify("
120
+ }
121
+ },
122
+ {
123
+ "id": "push",
124
+ "title": "Forward the push token",
125
+ "body": "Replies reach users who closed the app.",
126
+ "title_ru": "Передайте push-токен",
127
+ "body_ru": "Ответы дойдут и до тех, кто закрыл приложение.",
128
+ "code": {
129
+ "lang": "dart",
130
+ "file": "notifications",
131
+ "snippet": "final token = await FirebaseMessaging.instance.getToken();\nShotikSupport.setPushToken(token, platform: Platform.isIOS ? 'ios' : 'android');"
132
+ },
133
+ "check": {
134
+ "kind": "push-token",
135
+ "value": "any user of this app"
136
+ },
137
+ "optional": true
138
+ },
139
+ {
140
+ "id": "purchases",
141
+ "title": "Purchases",
142
+ "body": "One line with in_app_purchase.",
143
+ "title_ru": "Покупки",
144
+ "body_ru": "Одна строка с in_app_purchase.",
145
+ "code": {
146
+ "lang": "dart",
147
+ "file": "store setup",
148
+ "snippet": "ShotikAnalytics.watchPurchases(\n InAppPurchase.instance.purchaseStream,\n products: productDetails,\n);"
149
+ },
150
+ "check": {
151
+ "kind": "file-contains",
152
+ "value": "ShotikAnalytics.watchPurchases("
153
+ },
154
+ "optional": true
155
+ },
156
+ {
157
+ "id": "mask",
158
+ "title": "Hide private views",
159
+ "body": "Text fields are masked already.",
160
+ "title_ru": "Скройте личное",
161
+ "body_ru": "Текстовые поля скрыты и так.",
162
+ "code": {
163
+ "lang": "dart",
164
+ "file": "any screen",
165
+ "snippet": "ShotikMask(child: CardNumber(card))"
166
+ },
167
+ "check": {
168
+ "kind": "file-contains",
169
+ "value": "ShotikMask("
170
+ },
171
+ "optional": true
172
+ },
173
+ {
174
+ "id": "test",
175
+ "title": "Send a test message",
176
+ "body": "Open Help in the app and say hi.",
177
+ "title_ru": "Отправьте тестовое сообщение",
178
+ "body_ru": "Откройте «Помощь» в приложении и поздоровайтесь.",
179
+ "code": {
180
+ "lang": "sh",
181
+ "file": "terminal",
182
+ "snippet": "flutter run --dart-define SHOTIK_APP_KEY={{APP_KEY}}"
183
+ },
184
+ "check": {
185
+ "kind": "first-message",
186
+ "value": "a conversation from this app"
187
+ }
188
+ }
189
+ ]
190
+ }