@shotik/react-native 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/LICENSE +26 -0
  3. package/README.md +36 -1
  4. package/README.ru.md +37 -1
  5. package/dist/analytics/core.d.ts +96 -11
  6. package/dist/analytics/core.js +295 -22
  7. package/dist/analytics/privacy.d.ts +4 -0
  8. package/dist/analytics/privacy.js +46 -0
  9. package/dist/analytics/replay.d.ts +41 -0
  10. package/dist/analytics/replay.js +192 -0
  11. package/dist/analytics/rn.d.ts +52 -2
  12. package/dist/analytics/rn.js +669 -62
  13. package/dist/analytics/wire.d.ts +54 -2
  14. package/dist/analytics/wire.js +44 -4
  15. package/dist/client.d.ts +93 -0
  16. package/dist/client.js +247 -9
  17. package/dist/flow.d.ts +48 -0
  18. package/dist/flow.js +56 -0
  19. package/dist/index.d.ts +4 -4
  20. package/dist/index.js +2 -2
  21. package/dist/parts.d.ts +42 -1
  22. package/dist/parts.js +72 -14
  23. package/dist/react.d.ts +24 -3
  24. package/dist/react.js +42 -15
  25. package/dist/sheet.d.ts +2 -1
  26. package/dist/sheet.js +206 -15
  27. package/dist/support.js +2 -2
  28. package/dist/theme.d.ts +43 -0
  29. package/dist/theme.js +88 -2
  30. package/package.json +15 -2
  31. package/recipe.json +1 -1
  32. package/src/analytics/README.md +10 -6
  33. package/src/analytics/core.ts +314 -25
  34. package/src/analytics/privacy.ts +50 -0
  35. package/src/analytics/recipe.json +1 -1
  36. package/src/analytics/replay.ts +190 -0
  37. package/src/analytics/rn.tsx +620 -63
  38. package/src/analytics/wire.ts +99 -8
  39. package/src/client.ts +334 -9
  40. package/src/flow.ts +100 -0
  41. package/src/index.ts +4 -4
  42. package/src/parts.tsx +102 -14
  43. package/src/react.tsx +57 -16
  44. package/src/sheet.tsx +422 -19
  45. package/src/support.ts +2 -2
  46. package/src/theme.ts +88 -2
package/CHANGELOG.md ADDED
@@ -0,0 +1,16 @@
1
+ ## 0.2.0
2
+
3
+ Analytics
4
+ - Release context on every session: app version, build and OTA update id (optional peer expo-updates), channel, runtime, SDK id ('rn/<version>'), UTC offset, and a dev flag in __DEV__.
5
+ - Taps carry the response time to the next screen change or request; rage taps fire only when a tap in the burst got no response. Fixes a bug where an ancestor such as GestureHandlerRootView or a ScrollView counted as the press handler, so taps were never dead.
6
+ - New events: gesture (long press, swipe, pan, pinch), settled scroll, field timing, UI-state fingerprints, net (failed or slow requests only), and close perf.
7
+ - Session replay: sampled streaming plus a 30 s on-device ring released by a rage, dead, unresponsive or error tap, an error or a crash, uploaded to /analytics/v1/replay. Optional peers @react-native-community/netinfo and expo-network enable the Wi-Fi-only check. Inputs and masked views never leave the device.
8
+ - Privacy: redact(), a labels option (default a11y), masked taps drop their coordinates, shotikMask on any view, and ShotikAnalytics.forget() wipes the device and starts a new anonymous install.
9
+ - Store-truth purchases from RevenueCat (renewals are not new purchases). The iOS inactive state no longer closes a visit; snapshot upload retries on 5xx and 429.
10
+ - sendTestEvent for checking an install from the app.
11
+
12
+ Support (v1.1 and v2 widget)
13
+ - AI consent line, subscription context, action buttons in messages, the friction chip, "Did this help?" and review moments.
14
+ - Subscription screen with honest cancel (one reason, at most one founder alternative, Cancel in the store on the same screen), a help-first refund screen and a Rate row.
15
+ - Delete my data: wipes the device and the analytics install, then asks the server to erase.
16
+ - A send that hits a network error, 5xx or 429 now waits quietly (shipped in 0.1.1); only a 4xx shows Not sent.
package/LICENSE CHANGED
@@ -19,3 +19,29 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
19
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
20
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
21
  SOFTWARE.
22
+
23
+ ---
24
+
25
+ The icon paths in src/parts.tsx come from the Pikaicons free pack (@pikaicons/core-free, https://pikaicons.com/free-icons):
26
+
27
+ MIT License
28
+
29
+ Copyright (c) 2026 Pikaicons
30
+
31
+ Permission is hereby granted, free of charge, to any person obtaining a copy
32
+ of this software and associated documentation files (the "Software"), to deal
33
+ in the Software without restriction, including without limitation the rights
34
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
35
+ copies of the Software, and to permit persons to whom the Software is
36
+ furnished to do so, subject to the following conditions:
37
+
38
+ The above copyright notice and this permission notice shall be included in all
39
+ copies or substantial portions of the Software.
40
+
41
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
42
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
43
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
44
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
45
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
46
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
47
+ SOFTWARE.
package/README.md CHANGED
@@ -92,7 +92,7 @@ Images upload to the Shotik server (8 MB cap) and show in your Shotik inbox.
92
92
 
93
93
  ### Icons (optional)
94
94
 
95
- With `react-native-svg` installed (Expo apps usually have it), the widget draws its icons from the Hugeicons set.
95
+ With `react-native-svg` installed (Expo apps usually have it), the widget draws its icons from the Pikaicons free pack (MIT).
96
96
  Without it, simple built-in shapes stand in.
97
97
 
98
98
  ## 3. Open it
@@ -153,6 +153,41 @@ const { conversations, messages, unread, unreadBy, typing, status, open, send, r
153
153
  | `receiptOf(message, list, conversation, offline?)` | `sending · queued · failed · sent · delivered · seen` for your messages. Delivered = reached Shotik; seen = you read it there. |
154
154
  | `SupportClient` (`@shotik/react-native/client`) | The platform-free core, usable outside React. |
155
155
 
156
+ ### Consent, actions, subscription and rating (protocol v1.1)
157
+
158
+ ```tsx
159
+ ShotikSupport.configure({
160
+ appKey: 'spk_…',
161
+ serverUrl: 'https://support.example.com',
162
+ appStoreId: '1234567890', // write-review and store links
163
+ onAction: async (a) => { // buttons under messages and the Subscription screen
164
+ if (a.kind === 'restore') return (await Purchases.restorePurchases()) ? 'done' : 'failed'
165
+ // return nothing to fall back to the store pages (Manage subscription, refund, review, https links)
166
+ }
167
+ })
168
+ ShotikSupport.client?.setSubscription({ status: 'active', product: 'Pro yearly', price: '$39.99', renewsAt, willRenew: true, store: 'app_store' })
169
+ ```
170
+
171
+ - **AI consent.** Until the user picks, one line above the composer says "Replies may be drafted by AI and checked by the
172
+ team." with Allow / Only a person (`setAiConsent`). Pass `aiConsent` to `configure` if your app already asked.
173
+ - **Action buttons.** Founder and AI replies can carry up to 3 buttons. A tap runs `onAction`, or the store page when
174
+ there is no handler. While it runs the button shows progress, then a tick or a failed mark.
175
+ - **Subscription.** With `setSubscription`, the widget home shows a Subscription row. It opens Manage subscription,
176
+ Restore purchases and Redeem code (each only when it can run), Request a refund and Cancel subscription. Cancel asks one
177
+ optional reason and keeps "Cancel in App Store" on the same screen. If you set an alternative for that reason in
178
+ Shotik, it shows once, next to "Continue to cancel" at the same size. Taking it opens a chat to you, and your reply
179
+ sends the code. "Subscribed by mistake" goes straight to the refund screen, which offers Restore and Chat first and
180
+ keeps Request a refund in view.
181
+ - **Rate {app}.** A home row opens the store's write-review page. Pass `appName` to the provider for the label.
182
+ - **Friction chip.** After `friction(…)` (a failed purchase, rage taps, a repeated error) the widget shows "Something
183
+ wrong? Write to us". Place it yourself with `<SupportFrictionChip style={…}/>` and `frictionChip={false}` on the
184
+ provider.
185
+ - **Rating.** A resolved conversation asks "Did this help?" once (Yes / No, then an optional line after No).
186
+ - **Delete my data** (Apple 5.1.1(v), GDPR). The last home row, always there. After a confirm it calls `deleteMyData()`:
187
+ the device forgets at once (chats, queue, ids, analytics), and the server erases the rest. Offline it says it will
188
+ finish once the device is back online and retries on its own. Call `ShotikSupport.client?.deleteMyData()` from your
189
+ own settings too.
190
+
156
191
  Conversation status `needs_human` shows a "A person will reply" strip above the composer. Replies are labelled **AI** or
157
192
  with `teamName`. After an AI answer the thread offers its quick replies (from the answer, or the defaults you set in
158
193
  Shotik as `support.quickReplies:<appId>`) and "Talk to a person".
package/README.ru.md CHANGED
@@ -89,7 +89,7 @@ export default function RootLayout() {
89
89
 
90
90
  ### Иконки (необязательно)
91
91
 
92
- С `react-native-svg` (в Expo-приложениях он обычно есть) виджет рисует иконки из набора Hugeicons. Без него — простые
92
+ С `react-native-svg` (в Expo-приложениях он обычно есть) виджет рисует иконки из бесплатного набора Pikaicons (MIT). Без него — простые
93
93
  встроенные формы.
94
94
 
95
95
  ## 3. Откройте чат
@@ -150,6 +150,42 @@ const { conversations, messages, unread, unreadBy, typing, status, open, send, r
150
150
  | `receiptOf(message, list, conversation, offline?)` | `sending · queued · failed · sent · delivered · seen` для ваших сообщений. Доставлено = дошло до Shotik; прочитано = вы открыли его там. |
151
151
  | `SupportClient` (`@shotik/react-native/client`) | Ядро без привязки к платформе, работает и вне React. |
152
152
 
153
+ ### Согласие, кнопки, подписка и оценка (протокол v1.1)
154
+
155
+ ```tsx
156
+ ShotikSupport.configure({
157
+ appKey: 'spk_…',
158
+ serverUrl: 'https://support.example.com',
159
+ appStoreId: '1234567890', // ссылки на отзыв и в магазин
160
+ onAction: async (a) => { // кнопки под сообщениями и экран «Подписка»
161
+ if (a.kind === 'restore') return (await Purchases.restorePurchases()) ? 'done' : 'failed'
162
+ // ничего не вернули: откроется страница магазина (подписки, возврат, отзыв, https-ссылки)
163
+ }
164
+ })
165
+ ShotikSupport.client?.setSubscription({ status: 'active', product: 'Pro yearly', price: '$39.99', renewsAt, willRenew: true, store: 'app_store' })
166
+ ```
167
+
168
+ - **Согласие на ИИ.** Пока пользователь не выбрал, над полем ввода стоит строка «Ответы может готовить ИИ, команда их
169
+ проверяет.» с кнопками «Разрешить» и «Только человек» (`setAiConsent`). Если приложение уже спросило, передайте
170
+ `aiConsent` в `configure`.
171
+ - **Кнопки в сообщениях.** Ответ команды или ИИ может нести до 3 кнопок. Нажатие вызывает `onAction`, а без него открывает
172
+ страницу магазина. Пока действие идёт, на кнопке видно, что идёт работа, потом появляется галочка или знак ошибки.
173
+ - **Подписка.** После `setSubscription` на главной виджета появляется строка «Подписка». В ней «Управлять подпиской»,
174
+ «Восстановить покупки» и «Ввести код» (каждая, только когда её можно выполнить), «Запросить возврат» и «Отменить
175
+ подписку». Отмена задаёт один необязательный вопрос о причине, и «Отменить в App Store» остаётся на том же экране. Если
176
+ для этой причины в Shotik задан другой вариант, он показывается один раз рядом с «Продолжить отмену» в том же размере.
177
+ Выбор открывает чат с вами, а код приходит в вашем ответе. «Подписка оформлена по ошибке» сразу ведёт на экран
178
+ возврата: там сначала «Восстановить покупки» и «Написать нам», а «Запросить возврат» видно без прокрутки.
179
+ - **Оценить {app}.** Строка на главной открывает страницу отзыва в магазине. Для подписи передайте провайдеру `appName`.
180
+ - **Подсказка при проблеме.** После `friction(…)` (неудачная покупка, гневные нажатия, повторная ошибка) виджет
181
+ показывает «Что-то не так? Напишите нам». Чтобы разместить её самостоятельно, используйте
182
+ `<SupportFrictionChip style={…}/>` и `frictionChip={false}` у провайдера.
183
+ - **Оценка.** Решённый разговор один раз спрашивает «Это помогло?»: «Да» или «Нет», после «Нет» можно оставить строку.
184
+ - **Удалить мои данные** (Apple 5.1.1(v), GDPR). Последняя строка на главной, видна всегда. После подтверждения вызывает
185
+ `deleteMyData()`: устройство сразу всё забывает (переписки, очередь, id, аналитику), а сервер стирает остальное. Без
186
+ сети виджет говорит, что удаление завершится, когда появится связь, и повторяет запрос сам. Из своих настроек
187
+ вызывайте `ShotikSupport.client?.deleteMyData()`.
188
+
153
189
  ## Аналитика
154
190
 
155
191
  В том же пакете есть аналитика: `@shotik/react-native/analytics`, с тем же ключом.
@@ -1,4 +1,6 @@
1
- import type { DeviceContext, Wireframe } from './wire';
1
+ import { Replay } from './replay';
2
+ import type { ReplayWalk } from './replay';
3
+ import type { DeviceContext, EventType, Wireframe } from './wire';
2
4
  export interface Storage {
3
5
  get(key: string): Promise<string | null>;
4
6
  set(key: string, value: string): Promise<void>;
@@ -12,12 +14,64 @@ export interface AnalyticsConfig {
12
14
  device?: () => DeviceContext;
13
15
  consent?: Consent;
14
16
  snapshots?: number;
17
+ labels?: 'a11y' | 'visible' | 'none';
18
+ replay?: false | {
19
+ wifiOnly?: boolean;
20
+ };
21
+ wifi?: () => Promise<boolean>;
15
22
  flushMs?: number;
16
23
  sessionTimeoutMs?: number;
17
24
  debug?: boolean;
18
25
  fetch?: typeof fetch;
19
26
  now?: () => number;
27
+ onEvent?: (type: EventType, name: string | undefined, screen: string | undefined, props: Record<string, unknown> | undefined) => void;
20
28
  }
29
+ type TapInput = {
30
+ el: string;
31
+ id?: string;
32
+ label?: string;
33
+ x: number;
34
+ y: number;
35
+ nx: number;
36
+ ny: number;
37
+ dead?: boolean;
38
+ input?: boolean;
39
+ masked?: boolean;
40
+ ts?: number;
41
+ };
42
+ export type Entitled = {
43
+ product: string;
44
+ at: number;
45
+ first?: number;
46
+ trial?: boolean;
47
+ };
48
+ export type Gesture = {
49
+ k: 'long' | 'swipe' | 'pan' | 'pinch';
50
+ dir?: 'left' | 'right' | 'up' | 'down' | 'in' | 'out';
51
+ dx: number;
52
+ dy: number;
53
+ ms: number;
54
+ el: string;
55
+ id: string;
56
+ sc?: number;
57
+ ts?: number;
58
+ };
59
+ export type Scrolled = {
60
+ el: string;
61
+ id: string;
62
+ off: number;
63
+ len: number;
64
+ vis: number;
65
+ hz?: boolean;
66
+ pg?: number;
67
+ ts: number;
68
+ screen?: string;
69
+ };
70
+ export declare const SDK_VERSION = "0.2.0";
71
+ export declare function netTarget(url: string): {
72
+ host: string;
73
+ path: string;
74
+ };
21
75
  export declare class Analytics {
22
76
  readonly cfg: AnalyticsConfig;
23
77
  private st;
@@ -36,6 +90,11 @@ export declare class Analytics {
36
90
  private screenAt;
37
91
  private screenStats;
38
92
  private taps;
93
+ private held;
94
+ private waiting;
95
+ private states;
96
+ private stateH;
97
+ private marks;
39
98
  private snapped;
40
99
  private timer;
41
100
  private saveTimer;
@@ -47,6 +106,9 @@ export declare class Analytics {
47
106
  private loaded;
48
107
  private fresh;
49
108
  private storeIssue;
109
+ private replay;
110
+ private cost;
111
+ private lastTap;
50
112
  constructor(cfg: AnalyticsConfig);
51
113
  private load;
52
114
  private touch;
@@ -54,6 +116,8 @@ export declare class Analytics {
54
116
  private save;
55
117
  private persist;
56
118
  private schedule;
119
+ private get dev();
120
+ sendTestEvent(): Promise<void>;
57
121
  track(name: string, props?: Record<string, unknown>): void;
58
122
  identify(userId: string | null, traits?: Record<string, unknown>): void;
59
123
  screenView(name: string): void;
@@ -61,18 +125,32 @@ export declare class Analytics {
61
125
  get currentScreen(): string | undefined;
62
126
  screenReady(ms: number): void;
63
127
  stall(ms: number): void;
64
- tap(t: {
128
+ tap(t: TapInput): void;
129
+ private respond;
130
+ private settle;
131
+ private release;
132
+ private drain;
133
+ private emit;
134
+ private signal;
135
+ uiState(h: string | null, n?: number, quiet?: boolean): boolean;
136
+ field(f: {
137
+ id: string;
65
138
  el: string;
66
- id?: string;
67
- label?: string;
68
- x: number;
69
- y: number;
70
- nx: number;
71
- ny: number;
72
- dead?: boolean;
73
- input?: boolean;
74
- ts?: number;
139
+ ts: number;
140
+ ms: number;
141
+ edits?: number;
142
+ filled?: boolean;
143
+ screen?: string;
75
144
  }): void;
145
+ netStart(): void;
146
+ net(method: string, url: string, status: number, ms: number): void;
147
+ gesture(g: Gesture): void;
148
+ scrolled(s: Scrolled): void;
149
+ measure(kind: 'tap' | 'walk' | 'fp', ms: number): void;
150
+ private perf;
151
+ get replayOn(): boolean;
152
+ replayFrame(w: ReplayWalk): boolean;
153
+ get replayBuffer(): Replay;
76
154
  scroll(depth: number | null, drag: number): void;
77
155
  error(e: unknown, fatal?: boolean): void;
78
156
  purchase(p: {
@@ -82,7 +160,11 @@ export declare class Analytics {
82
160
  currency?: string;
83
161
  store?: string;
84
162
  trial?: boolean;
163
+ renew?: boolean;
164
+ conv?: boolean;
165
+ at?: number;
85
166
  }): void;
167
+ entitled(list: Entitled[], quiet?: boolean, store?: string): void;
86
168
  wantsSnapshot(screen: string): boolean;
87
169
  snapshot(w: Omit<Wireframe, 'sessionId' | 'ts'>): void;
88
170
  foreground(): void;
@@ -90,9 +172,11 @@ export declare class Analytics {
90
172
  setConsent(c: Consent): void;
91
173
  optOut(): void;
92
174
  optIn(): void;
175
+ forget(): Promise<boolean>;
93
176
  reset(): Promise<void>;
94
177
  flush(): Promise<void>;
95
178
  private send;
179
+ private sendReplay;
96
180
  stop(): void;
97
181
  get ids(): {
98
182
  anonymousId: string;
@@ -102,3 +186,4 @@ export declare class Analytics {
102
186
  get pending(): number;
103
187
  whenReady(): Promise<void>;
104
188
  }
189
+ export {};