@shotik/react-native 0.1.1 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/CHANGELOG.md +20 -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 +111 -12
  6. package/dist/analytics/core.js +303 -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 +53 -2
  12. package/dist/analytics/rn.js +687 -63
  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 +324 -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 +636 -64
  38. package/src/analytics/wire.ts +101 -8
  39. package/src/client.ts +334 -9
  40. package/src/flow.ts +100 -0
  41. package/src/index.ts +4 -4
  42. package/src/parts.tsx +102 -14
  43. package/src/react.tsx +57 -16
  44. package/src/sheet.tsx +422 -19
  45. package/src/support.ts +2 -2
  46. package/src/theme.ts +88 -2
@@ -6,7 +6,7 @@
6
6
  export const WIRE_VERSION = 1
7
7
 
8
8
  // Event types. Codes are the array position, so append only.
9
- export const TYPES = ['session', 'open', 'close', 'screen', 'leave', 'tap', 'rage', 'scroll', 'error', 'slow', 'purchase', 'custom', 'identify', 'snapshot'] as const
9
+ export const TYPES = ['session', 'open', 'close', 'screen', 'leave', 'tap', 'rage', 'scroll', 'error', 'slow', 'purchase', 'custom', 'identify', 'snapshot', 'net', 'field', 'state', 'gesture'] as const
10
10
  export type EventType = (typeof TYPES)[number]
11
11
 
12
12
  export interface DeviceContext {
@@ -19,16 +19,33 @@ export interface DeviceContext {
19
19
  tz?: string
20
20
  w?: number
21
21
  h?: number
22
+ // Release context (additive, 2026-11-29): the running OTA update id (absent on the embedded bundle), its channel, the
23
+ // runtime version, the SDK as '<platform sdk>/<version>' (e.g. 'rn/0.2.0'), the UTC offset in minutes (east positive,
24
+ // UTC+8 = 480), and dev: 1 in development builds.
25
+ ota?: string
26
+ ch?: string
27
+ rt?: string
28
+ sdk?: string
29
+ tzo?: number
30
+ dev?: 1
22
31
  }
23
32
 
24
33
  // Props by type (all optional, short keys keep batches small):
25
34
  // session { first: 1 on the first session of this install, store: 'none' | 'error' when the id can't persist }
26
35
  // screen { from, ms (ready time) } leave { dur, depth (0..1), drag (pt), stalls, maxStall }
27
- // tap { el, id, label, x, y, nx, ny (0..1000), dead: 1, input: 1 } rage { el, id, label, n, x, y }
28
- // id is the stable element key (testID, nativeID or a structural hash); el and label are for display
36
+ // tap { el, x, y, nx, ny (0..1000), id, label, dead: 1, input: 1, resp (ms to the first response) } rage { el, id, label, n, x, y }
37
+ // id is the stable element key (testID, nativeID or a structural hash); el and label are for display; x, y, nx, ny absent when masked
29
38
  // error { msg, fatal: 1, stack (top frames, no values) } slow { ms, kind: 'ready' | 'stall' }
30
- // purchase { product, price, currency, status: start | done | cancel | fail, store, trial: 1 }
39
+ // purchase { product, status: start | shown | done | cancel | pending | fail | not_shown, price, currency, store, trial: 1, renew: 1, conv: 1, at (store purchase ms),
40
+ // ps (the store's localized price string as shown, <= 32), code (error code on fail / not_shown, <= 40), sf (storefront country, ISO 3166 alpha-2 or alpha-3) }
41
+ // shown = the store sheet was presented; done = confirmed; cancel = the user cancelled; pending = Ask to Buy / SCA; not_shown = the product didn't load, so no sheet
31
42
  // custom free-form (no PII by contract) identify { traits }
43
+ // net { m (method), host, path (template, no query), s (status, 0 = network error), ms }: failures and slow calls only
44
+ // field { id, el, ms (focused), edits (<= 20, none on secure inputs), filled: 1 }: one per focus span, never a value or length
45
+ // state { h (32-bit hash, 8 hex chars), n }: the visible interactive element set changed on the same screen
46
+ // gesture { k: long | swipe | pan | pinch, dir: left | right | up | down | in | out, dx, dy (pt), ms, el, id, sc (pinch scale) }: never a position
47
+ // scroll { el, id, off, len, vis (pt), hz: 1, pg (pager page) }: a container settled at a new offset after a touch scrolled it
48
+ // close { perf: { tap, walk, fp (p95 ms), rb, eb (replay / event bytes sent this session) } }
32
49
  export interface WireEvent {
33
50
  seq: number
34
51
  ts: number
@@ -37,6 +54,9 @@ export interface WireEvent {
37
54
  name?: string
38
55
  screen?: string
39
56
  props?: Record<string, unknown>
57
+ // 'test': a connection check (ShotikAnalytics.sendTestEvent, Shotik's "Send test event"). The server keeps test events apart,
58
+ // so they prove the key and the path work and never count as a user, a session or a metric.
59
+ kind?: 'test'
40
60
  }
41
61
 
42
62
  export interface Batch {
@@ -48,7 +68,8 @@ export interface Batch {
48
68
  }
49
69
 
50
70
  // [dt, type, seq, session, screen, name, props]; string slots are dictionary indexes, -1 = absent.
51
- export type PackedEvent = [number, number, number, number, number, number, Record<string, unknown> | 0]
71
+ // The optional 8th slot is 1 for a test event; older servers ignore it.
72
+ export type PackedEvent = [number, number, number, number, number, number, Record<string, unknown> | 0, 1?]
52
73
  export interface PackedBatch {
53
74
  v: 1
54
75
  a: string
@@ -89,7 +110,9 @@ export function pack(b: Batch): PackedBatch {
89
110
  p[k] = PACKED_PROPS.includes(k) && typeof v === 'string' ? s(v) : v
90
111
  }
91
112
  }
92
- return [dt, TYPES.indexOf(ev.type), ev.seq, s(ev.sessionId), s(ev.screen), s(ev.name), p]
113
+ const row: PackedEvent = [dt, TYPES.indexOf(ev.type), ev.seq, s(ev.sessionId), s(ev.screen), s(ev.name), p]
114
+ if (ev.kind === 'test') row.push(1)
115
+ return row
93
116
  })
94
117
  return { v: 1, a: b.anonymousId, u: b.userId ?? null, f: b.firstSeen, c: b.device, t0, d, e }
95
118
  }
@@ -97,14 +120,14 @@ export function pack(b: Batch): PackedBatch {
97
120
  export function unpack(p: PackedBatch): Batch {
98
121
  const str = (i: number) => (i >= 0 && i < p.d.length ? p.d[i] : undefined)
99
122
  let ts = p.t0
100
- const events = p.e.map(([dt, type, seq, sess, screen, name, props]): WireEvent => {
123
+ const events = p.e.map(([dt, type, seq, sess, screen, name, props, test]): WireEvent => {
101
124
  ts += dt
102
125
  let pr: Record<string, unknown> | undefined
103
126
  if (props) {
104
127
  pr = {}
105
128
  for (const k in props) pr[k] = PACKED_PROPS.includes(k) && typeof props[k] === 'number' ? str(props[k] as number) : props[k]
106
129
  }
107
- return { seq, ts, type: TYPES[type] ?? 'custom', sessionId: str(sess) ?? '', screen: str(screen), name: str(name), props: pr }
130
+ return { seq, ts, type: TYPES[type] ?? 'custom', sessionId: str(sess) ?? '', screen: str(screen), name: str(name), props: pr, ...(test === 1 && { kind: 'test' as const }) }
108
131
  })
109
132
  return { anonymousId: p.a, userId: p.u ?? null, firstSeen: p.f, device: p.c, events }
110
133
  }
@@ -121,3 +144,73 @@ export interface Wireframe {
121
144
  dark?: boolean
122
145
  nodes: WireNode[]
123
146
  }
147
+
148
+ // Wireframe replay (PROTOCOL.md 4.7): POST /analytics/v1/replay. A keyframe per screen, then diffs of changed nodes keyed by
149
+ // a stable key (base36 FNV-1a of kind + host index path). KeyedNode: [key, kind, x, y, w, h, fill?, radius?, in?]; with in
150
+ // (a scroll container's key) x, y are in that container's content space. Kinds as WireNode plus w (web view).
151
+ export type KeyedNode = [string, string, number, number, number, number, (string | null)?, (number | null)?, (string | null)?]
152
+ export interface ReplayScroll {
153
+ node: string
154
+ y: number
155
+ x?: number
156
+ }
157
+ export interface ReplayRun {
158
+ after: string | null
159
+ nodes: KeyedNode[]
160
+ }
161
+ export interface ReplayChunk {
162
+ sess: string
163
+ seq: number
164
+ t: number
165
+ keyframe?: { screen: string; w: number; h: number; nodes: KeyedNode[] }
166
+ diff?: { add?: ReplayRun[]; rm?: string[]; mv?: [string, number, number][] }
167
+ scroll?: ReplayScroll[]
168
+ }
169
+ export type ReplayWhy = 'sample' | 'rage' | 'dead' | 'unresponsive' | 'errtap' | 'error' | 'crash'
170
+ export interface ReplayUpload {
171
+ v: 1
172
+ a: string
173
+ why: ReplayWhy
174
+ chunks: ReplayChunk[]
175
+ }
176
+
177
+ // The picture after applying a chunk to the previous one (PROTOCOL.md 4.7): draw-ordered nodes and scroll offsets. Shared
178
+ // by the SDK tests and the server's player.
179
+ export interface ReplayPicture {
180
+ screen: string
181
+ w: number
182
+ h: number
183
+ nodes: KeyedNode[]
184
+ scroll: Record<string, { x: number; y: number }>
185
+ }
186
+
187
+ export function applyChunk(prev: ReplayPicture | null, c: ReplayChunk): ReplayPicture | null {
188
+ let pic: ReplayPicture | null
189
+ if (c.keyframe) pic = { screen: c.keyframe.screen, w: c.keyframe.w, h: c.keyframe.h, nodes: c.keyframe.nodes.slice(), scroll: {} }
190
+ else if (prev) pic = { ...prev, nodes: prev.nodes.slice(), scroll: { ...prev.scroll } }
191
+ else return null
192
+ const d = c.diff
193
+ if (d) {
194
+ const gone = new Set(d.rm ?? [])
195
+ for (const r of d.add ?? []) for (const n of r.nodes) gone.add(n[0])
196
+ let nodes = pic.nodes.filter((n) => !gone.has(n[0]))
197
+ for (const r of d.add ?? []) {
198
+ const i = r.after === null ? 0 : nodes.findIndex((n) => n[0] === r.after) + 1
199
+ nodes = nodes.slice(0, i).concat(r.nodes, nodes.slice(i))
200
+ }
201
+ if (d.mv?.length) {
202
+ const mv = new Map(d.mv.map((m) => [m[0], m]))
203
+ nodes = nodes.map((n) => {
204
+ const m = mv.get(n[0])
205
+ if (!m) return n
206
+ const k = n.slice() as KeyedNode
207
+ k[2] = m[1]
208
+ k[3] = m[2]
209
+ return k
210
+ })
211
+ }
212
+ pic.nodes = nodes
213
+ }
214
+ for (const s of c.scroll ?? []) pic.scroll[s.node] = { x: s.x ?? 0, y: s.y }
215
+ return pic
216
+ }
package/src/client.ts CHANGED
@@ -3,6 +3,17 @@
3
3
  // an offline send queue with optimistic messages, and a pull for anything missed. No React Native imports, so it runs
4
4
  // (and is tested) under plain Node as well as in the app.
5
5
 
6
+ // What one install shares between Support and Analytics: Delete my data erases both. ShotikAnalytics.init registers
7
+ // itself here, so the widget's row reaches it without the host wiring anything.
8
+ export interface ErasableAnalytics {
9
+ forget(): Promise<boolean>
10
+ reset(): Promise<void> | void
11
+ }
12
+ let installAnalytics: ErasableAnalytics | null = null
13
+ export function registerAnalytics(a: ErasableAnalytics | null): void {
14
+ installAnalytics = a
15
+ }
16
+
6
17
  export type Author = 'user' | 'ai' | 'founder' | 'system'
7
18
  export type ConversationStatus = 'open' | 'needs_human' | 'resolved' | 'closed' | string
8
19
  export type Status = 'idle' | 'identifying' | 'connecting' | 'live' | 'offline' | 'error'
@@ -17,7 +28,63 @@ export interface Conversation {
17
28
  createdAt: number
18
29
  // User messages the founder has not read yet; 0 means everything you sent was seen.
19
30
  founderUnread?: number
31
+ // "Did this help?" answer once the conversation was resolved: 1, -1, or null (not asked or not answered yet).
32
+ csat?: 1 | -1 | null
33
+ }
34
+
35
+ // The user's subscription as the host app knows it (StoreKit 2, RevenueCat, Play Billing), PROTOCOL.md §3.8.
36
+ export interface Subscription {
37
+ status: 'trial' | 'active' | 'grace' | 'billing_retry' | 'cancelled' | 'expired' | 'refunded' | 'none'
38
+ product?: string | null
39
+ period?: 'P1W' | 'P1M' | 'P3M' | 'P6M' | 'P1Y' | 'lifetime' | null
40
+ price?: string | null
41
+ renewsAt?: number | null
42
+ expiresAt?: number | null
43
+ trialEndsAt?: number | null
44
+ willRenew?: boolean | null
45
+ store?: 'app_store' | 'play' | 'stripe' | null
46
+ }
47
+
48
+ // A native button under a founder or AI message (PROTOCOL.md §3.9).
49
+ export type ActionKind = 'manage_subscription' | 'restore' | 'redeem_code' | 'change_plan' | 'request_refund' | 'open_url' | 'write_review' | 'custom'
50
+ export interface SupportAction {
51
+ id: string
52
+ kind: ActionKind
53
+ label: string
54
+ value?: string | null
55
+ }
56
+ export type ActionResult = 'done' | 'cancelled' | 'failed'
57
+ export const actionsOf = (m: Message): SupportAction[] => (Array.isArray(m.meta?.['actions']) ? (m.meta['actions'] as SupportAction[]).filter((a) => a && typeof a.kind === 'string' && typeof a.label === 'string').slice(0, 3) : [])
58
+
59
+ export type CancelReason = 'too_expensive' | 'not_using' | 'bug' | 'mistake' | 'other'
60
+ // A save offer as the device sees it: the founder's words only. askForOffer() asks the founder, whose click sends the
61
+ // code or the plan change (nothing that touches money reaches the user without it).
62
+ export interface Offer {
63
+ kind: 'chat'
64
+ label: string
65
+ }
66
+ // The founder's widget settings for this user (GET /support/v1/config): one save offer per cancel reason (empty while
67
+ // this user is inside the offer cooldown), review rules, screens where the friction chip stays quiet, custom actions.
68
+ export interface WidgetConfig {
69
+ offers: Partial<Record<CancelReason, Offer>>
70
+ offerEligible: boolean
71
+ review: { moments: Record<string, number>; minDaysSinceInstall: number; maxPerYear: number; quietDaysAfterFriction: number; quietDaysAfterRefundOrCancel: number }
72
+ quietScreens: string[]
73
+ customActions: { id: string; label: string }[]
74
+ }
75
+
76
+ // What the friction chip offers help for (PROTOCOL.md §3.12).
77
+ export interface Friction {
78
+ kind: 'purchase_fail' | 'rage' | 'error'
79
+ screen?: string | null
80
+ element?: string | null
20
81
  }
82
+ // Why a conversation started: the friction chip, or a save offer the user asked for (element = the cancel reason).
83
+ export type Trigger = Friction | { kind: 'offer'; screen?: null; element: CancelReason }
84
+
85
+ export type SupportEventKind =
86
+ | 'action' | 'cancel_started' | 'cancel_reason' | 'offer_shown' | 'offer_accepted' | 'cancel_continued' | 'refund_help' | 'refund_requested'
87
+ | 'review_prompt' | 'friction_shown' | 'friction_opened' | 'friction_dismissed'
21
88
 
22
89
  // A picked photo or screenshot before upload (uri: file:// or data:), and the uploaded form in message meta.
23
90
  export interface LocalAttachment {
@@ -81,6 +148,18 @@ export interface SupportConfig {
81
148
  serverUrl: string
82
149
  storage?: KeyValueStorage
83
150
  device?: () => DeviceInfo | Promise<DeviceInfo>
151
+ // Consent the host app already collected for AI-drafted replies (Apple 5.1.2(i)); the widget asks when it's unset.
152
+ aiConsent?: boolean
153
+ // Runs an action tapped under a message (StoreKit, RevenueCat or the app's own code). Return the outcome; without a
154
+ // handler the URL fallbacks open through openUrl (Manage subscription, refund, redeem code, review, links).
155
+ onAction?: (action: SupportAction) => ActionResult | void | Promise<ActionResult | void>
156
+ openUrl?: (url: string) => unknown
157
+ // The native review prompt (StoreKit requestReview / Play In-App Review). Called only by reviewMoment() when every rule passes.
158
+ requestReview?: () => unknown
159
+ // The App Store id (numbers only), for the write-review and redeem-code links.
160
+ appStoreId?: string
161
+ // The install's analytics, erased with Delete my data. Defaults to ShotikAnalytics once it is initialized.
162
+ analytics?: ErasableAnalytics | null
84
163
  }
85
164
 
86
165
  export interface SupportState {
@@ -95,6 +174,12 @@ export interface SupportState {
95
174
  error: string | null
96
175
  // Who is typing in each conversation right now (the AI drafting or the founder in Shotik).
97
176
  typing: Record<string, Typing>
177
+ // AI-drafted replies: allowed, refused ("only a person"), or not asked yet (null).
178
+ aiConsent: boolean | null
179
+ subscription: Subscription | null
180
+ widget: WidgetConfig | null
181
+ // The friction chip to show now, or null.
182
+ friction: Friction | null
98
183
  }
99
184
 
100
185
  interface QueueItem {
@@ -104,6 +189,7 @@ interface QueueItem {
104
189
  createdAt: number
105
190
  attempts: number
106
191
  attachments?: (LocalAttachment & { remote?: Attachment })[]
192
+ trigger?: Trigger
107
193
  }
108
194
 
109
195
  // Receipt for one of your messages: sending -> sent -> delivered (reached Shotik) -> seen (the founder read it).
@@ -136,7 +222,21 @@ export class HttpError extends Error {
136
222
  }
137
223
  }
138
224
 
139
- const K = { anon: 'shotik.support.anon', session: 'shotik.support.session', queue: 'shotik.support.queue', read: 'shotik.support.read', push: 'shotik.support.push' }
225
+ const K = { anon: 'shotik.support.anon', session: 'shotik.support.session', queue: 'shotik.support.queue', read: 'shotik.support.read', push: 'shotik.support.push', consent: 'shotik.support.aiConsent', review: 'shotik.support.review', erase: 'shotik.support.erase' }
226
+ const DAY = 86_400_000
227
+ const FRICTION_N = 3
228
+ const FRICTION_QUIET_MS = 7 * DAY
229
+
230
+ // Review prompt ledger, kept on the device (PROTOCOL.md §3.11).
231
+ interface ReviewLedger {
232
+ installAt: number
233
+ counts: Record<string, number>
234
+ prompts: number[]
235
+ versions: string[]
236
+ frictionAt: number
237
+ refundOrCancelAt: number
238
+ frictionDismissedAt: number
239
+ }
140
240
  const LOCAL_CONV = 'local_conv_'
141
241
 
142
242
  export function memoryStorage(): KeyValueStorage {
@@ -158,7 +258,14 @@ export class SupportClient {
158
258
  readonly config: SupportConfig
159
259
  private storage: KeyValueStorage
160
260
  private listeners = new Set<(s: SupportState) => void>()
161
- private state: SupportState = { status: 'idle', userId: null, conversations: [], messages: {}, unread: 0, unreadBy: {}, open: false, activeConversationId: null, error: null, typing: {} }
261
+ private state: SupportState = { status: 'idle', userId: null, conversations: [], messages: {}, unread: 0, unreadBy: {}, open: false, activeConversationId: null, error: null, typing: {}, aiConsent: null, subscription: null, widget: null, friction: null }
262
+ private subscriptionSet = false
263
+ private ledger: ReviewLedger = { installAt: Date.now(), counts: {}, prompts: [], versions: [], frictionAt: 0, refundOrCancelAt: 0, frictionDismissedAt: 0 }
264
+ private session_ = { friction: false, chipShown: false, counts: new Map<string, number>() }
265
+ private pendingTrigger: Trigger | null = null
266
+ private offerShown: CancelReason | null = null
267
+ private eraseTimer: ReturnType<typeof setTimeout> | null = null
268
+ private eraseStep = 0
162
269
  private typingTimers = new Map<string, ReturnType<typeof setTimeout>>()
163
270
  private session: Session | null = null
164
271
  private anonId: string | null = null
@@ -210,7 +317,11 @@ export class SupportClient {
210
317
 
211
318
  private load(): Promise<void> {
212
319
  this.loaded ??= (async () => {
213
- const [anon, session, queue, read, push] = await Promise.all([K.anon, K.session, K.queue, K.read, K.push].map((k) => this.storage.get(k).catch(() => null)))
320
+ const [anon, session, queue, read, push, consent, review] = await Promise.all([K.anon, K.session, K.queue, K.read, K.push, K.consent, K.review].map((k) => this.storage.get(k).catch(() => null)))
321
+ const aiConsent = consent === 'true' ? true : consent === 'false' ? false : (this.config.aiConsent ?? null)
322
+ if (aiConsent !== this.state.aiConsent) this.set({ aiConsent })
323
+ if (review) this.ledger = { ...this.ledger, ...(JSON.parse(review) as Partial<ReviewLedger>) }
324
+ else this.persist(K.review, this.ledger)
214
325
  this.anonId = anon ?? localId('anon_')
215
326
  if (!anon) await this.storage.set(K.anon, this.anonId).catch(() => {})
216
327
  this.session = session ? (JSON.parse(session) as Session) : null
@@ -222,6 +333,7 @@ export class SupportClient {
222
333
  for (const q of this.queue) messages[q.conversationId] = [...(messages[q.conversationId] ?? []), this.optimistic(q, q.attempts ? 'waiting' : 'sending')]
223
334
  this.set({ messages, conversations: this.withLocalConversations(this.state.conversations, messages) })
224
335
  }
336
+ if ((await this.erasing()).length) void this.flushErase()
225
337
  })()
226
338
  return this.loaded
227
339
  }
@@ -265,6 +377,7 @@ export class SupportClient {
265
377
  await this.load()
266
378
  this.set({ status: this.state.status === 'live' ? 'live' : 'identifying', error: null })
267
379
  const device = await Promise.resolve(this.config.device?.()).catch(() => undefined)
380
+ this.platform = device?.platform?.toLowerCase() ?? null
268
381
  const r = await this.request<{ user: { id: string }; userToken: string; conversations: Conversation[] }>('POST', '/support/v1/identify', {
269
382
  anonymousId: this.anonId,
270
383
  userId: this.user.userId,
@@ -273,7 +386,9 @@ export class SupportClient {
273
386
  attributes: this.user.attributes,
274
387
  device: device ?? undefined,
275
388
  appVersion: device?.appVersion ? device.appVersion + (device.build ? ' (' + device.build + ')' : '') : undefined,
276
- locale: device?.locale
389
+ locale: device?.locale,
390
+ aiConsent: this.state.aiConsent ?? undefined,
391
+ subscription: this.subscriptionSet ? this.state.subscription : undefined
277
392
  })
278
393
  const changed = this.session?.userId !== r.user.id
279
394
  this.session = { userToken: r.userToken, userId: r.user.id, externalId: this.user.userId ?? null }
@@ -282,6 +397,7 @@ export class SupportClient {
282
397
  if (this.pushToken) await this.sendPushToken().catch(() => {})
283
398
  if (changed || !this.ws) this.connect(true)
284
399
  this.scheduleFlush(0)
400
+ this.loadWidget().catch(() => {})
285
401
  }
286
402
  const p = (this.identifying ?? Promise.resolve()).then(run, run)
287
403
  this.identifying = p.catch((e: Error) => {
@@ -297,6 +413,158 @@ export class SupportClient {
297
413
  return this.identifying ? this.identifying : this.identify()
298
414
  }
299
415
 
416
+ // AI-drafted replies (Apple 5.1.2(i)): true lets the founder's AI draft answers, false keeps the chat person-only.
417
+ setAiConsent(allowed: boolean): Promise<void> {
418
+ this.storage.set(K.consent, String(allowed)).catch(() => {})
419
+ this.set({ aiConsent: allowed })
420
+ return this.session ? this.identify() : Promise.resolve()
421
+ }
422
+
423
+ // The subscription the founder sees next to the chat and the widget's Subscription screen shows (null: none).
424
+ setSubscription(sub: Subscription | null): Promise<void> {
425
+ this.subscriptionSet = true
426
+ this.set({ subscription: sub })
427
+ return this.session ? this.identify() : Promise.resolve()
428
+ }
429
+
430
+ private async loadWidget(): Promise<void> {
431
+ const w = await this.request<WidgetConfig>('GET', '/support/v1/config')
432
+ this.set({ widget: w })
433
+ }
434
+
435
+ // Reports what the user did in the widget; with a conversation it shows in the founder's timeline. Best effort.
436
+ track(kind: SupportEventKind, data: Record<string, string | number | boolean> = {}, conversationId?: string | null): void {
437
+ if (kind === 'refund_requested' || kind === 'cancel_continued') this.ledgerSet({ refundOrCancelAt: Date.now() })
438
+ if (kind === 'offer_shown') this.offerShown = data['reason'] as CancelReason
439
+ if (kind === 'offer_shown' && this.state.widget) this.set({ widget: { ...this.state.widget, offers: {}, offerEligible: false } })
440
+ this.ensureIdentified()
441
+ .then(() => this.request('POST', '/support/v1/events', { kind, data, conversationId: conversationId && !conversationId.startsWith(LOCAL_CONV) ? conversationId : undefined }))
442
+ .catch(() => {})
443
+ }
444
+
445
+ // Runs an action from a message: the host's onAction, else the store URL fallbacks. The founder sees the outcome.
446
+ async runAction(action: SupportAction, conversationId?: string | null): Promise<ActionResult> {
447
+ let result: ActionResult = 'failed'
448
+ try {
449
+ const r = this.config.onAction ? await this.config.onAction(action) : undefined
450
+ result = r ?? (this.config.onAction && action.kind === 'custom' ? 'done' : this.openFallback(action))
451
+ } catch {
452
+ result = 'failed'
453
+ }
454
+ this.track('action', { actionId: action.id, action: action.kind, label: action.label, result }, conversationId)
455
+ return result
456
+ }
457
+
458
+ // The store pages that do the job when the host has no handler (iOS first; Android goes to Play's subscriptions).
459
+ fallbackUrl(action: Pick<SupportAction, 'kind' | 'value'>): string | null {
460
+ const android = this.platform === 'android'
461
+ const id = this.config.appStoreId
462
+ switch (action.kind) {
463
+ case 'manage_subscription':
464
+ return android ? 'https://play.google.com/store/account/subscriptions' : 'https://apps.apple.com/account/subscriptions'
465
+ case 'request_refund':
466
+ return android ? null : 'https://reportaproblem.apple.com'
467
+ case 'redeem_code':
468
+ return !android && id && action.value ? 'https://apps.apple.com/redeem?ctx=offercodes&id=' + id + '&code=' + encodeURIComponent(action.value) : null
469
+ case 'write_review':
470
+ return !android && id ? 'https://apps.apple.com/app/id' + id + '?action=write-review' : null
471
+ case 'open_url':
472
+ return action.value && /^https:\/\//.test(action.value) ? action.value : null
473
+ default:
474
+ return null
475
+ }
476
+ }
477
+
478
+ private openFallback(action: SupportAction): ActionResult {
479
+ const url = this.fallbackUrl(action)
480
+ if (!url || !this.config.openUrl) return 'failed'
481
+ this.config.openUrl(url)
482
+ return 'done'
483
+ }
484
+
485
+ // "Did this help?" on a resolved conversation (CSAT): 1 or -1 and an optional line.
486
+ async rate(conversationId: string, score: 1 | -1, comment?: string): Promise<void> {
487
+ this.set({ conversations: this.state.conversations.map((c) => (c.id === conversationId ? { ...c, csat: score } : c)) })
488
+ await this.request('POST', '/support/v1/conversations/' + conversationId + '/rating', { score, comment })
489
+ }
490
+
491
+ // A success moment in the app (a goal reached, a streak, a finished lesson). Asks the store's review prompt only when
492
+ // the founder's rules pass: enough of this moment, days since install, not yet in this version, under the yearly cap,
493
+ // and no friction in this session or the quiet days after friction, a refund or a cancel. Returns whether it asked.
494
+ async reviewMoment(name: string): Promise<boolean> {
495
+ await this.load()
496
+ const counts = { ...this.ledger.counts, [name]: (this.ledger.counts[name] ?? 0) + 1 }
497
+ this.ledgerSet({ counts })
498
+ const rules = this.state.widget?.review
499
+ const need = rules?.moments[name]
500
+ if (!rules || !need || !this.config.requestReview) return false
501
+ const now = Date.now()
502
+ const version = (await Promise.resolve(this.config.device?.()).catch(() => undefined))?.appVersion ?? ''
503
+ const ok =
504
+ counts[name]! >= need &&
505
+ now - this.ledger.installAt >= rules.minDaysSinceInstall * DAY &&
506
+ !this.ledger.versions.includes(version) &&
507
+ this.ledger.prompts.filter((t) => now - t < 365 * DAY).length < rules.maxPerYear &&
508
+ !this.session_.friction &&
509
+ now - this.ledger.frictionAt >= rules.quietDaysAfterFriction * DAY &&
510
+ now - this.ledger.refundOrCancelAt >= rules.quietDaysAfterRefundOrCancel * DAY
511
+ if (!ok) return false
512
+ this.ledgerSet({ prompts: [...this.ledger.prompts, now].slice(-10), versions: [...this.ledger.versions, version].slice(-20) })
513
+ await Promise.resolve(this.config.requestReview()).catch(() => {})
514
+ this.track('review_prompt', { moment: name, version })
515
+ return true
516
+ }
517
+
518
+ // Friction from the app (analytics onEvent, or the host directly): a failed purchase opens the help chip at once;
519
+ // rage taps on one element or the same error three times in a session do too. Once per session, never on quiet screens,
520
+ // and not for a week after the user tapped "Not now".
521
+ friction(f: Friction): void {
522
+ const now = Date.now()
523
+ this.session_.friction = true
524
+ this.ledgerSet({ frictionAt: now })
525
+ const key = f.kind + '|' + (f.element ?? '') + '|' + (f.kind === 'rage' ? '' : (f.screen ?? ''))
526
+ const n = (this.session_.counts.get(key) ?? 0) + 1
527
+ this.session_.counts.set(key, n)
528
+ if (n < (f.kind === 'error' ? FRICTION_N : 1)) return
529
+ if (this.session_.chipShown || now - this.ledger.frictionDismissedAt < FRICTION_QUIET_MS) return
530
+ if (f.screen && this.state.widget?.quietScreens.includes(f.screen)) return
531
+ this.session_.chipShown = true
532
+ this.set({ friction: f })
533
+ this.track('friction_shown', { friction: f.kind, screen: f.screen ?? '', element: f.element ?? '' })
534
+ }
535
+
536
+ // The user tapped the chip: the next message starts a conversation that carries what happened.
537
+ openFriction(): void {
538
+ const f = this.state.friction
539
+ if (!f) return
540
+ this.pendingTrigger = f
541
+ this.track('friction_opened', { friction: f.kind })
542
+ this.set({ friction: null, open: true, activeConversationId: null })
543
+ }
544
+
545
+ // The user took the save offer for this cancel reason: the widget opens on a new conversation that goes to the founder.
546
+ // Showing the offer empties widget.offers for the cooldown, so the reason shown on screen still counts.
547
+ askForOffer(reason: CancelReason): void {
548
+ if (!this.state.widget?.offers[reason] && this.offerShown !== reason) return
549
+ this.pendingTrigger = { kind: 'offer', element: reason }
550
+ this.track('offer_accepted', { reason })
551
+ this.set({ open: true, activeConversationId: null })
552
+ }
553
+
554
+ dismissFriction(): void {
555
+ if (!this.state.friction) return
556
+ this.ledgerSet({ frictionDismissedAt: Date.now() })
557
+ this.track('friction_dismissed', { friction: this.state.friction.kind })
558
+ this.set({ friction: null })
559
+ }
560
+
561
+ private ledgerSet(p: Partial<ReviewLedger>): void {
562
+ this.ledger = { ...this.ledger, ...p }
563
+ this.persist(K.review, this.ledger)
564
+ }
565
+
566
+ private platform: string | null = null
567
+
300
568
  async setPushToken(token: string | null, platform = 'ios'): Promise<void> {
301
569
  await this.load()
302
570
  this.pushToken = token ? { token, platform } : null
@@ -350,7 +618,9 @@ export class SupportClient {
350
618
  const text = body.trim()
351
619
  if (!text && !attachments.length) return null
352
620
  const convId = conversationId || this.state.activeConversationId || LOCAL_CONV + localId('')
353
- const item: QueueItem = { localId: localId('local_'), conversationId: convId, body: text, createdAt: Date.now(), attempts: 0, ...(attachments.length ? { attachments: attachments.slice(0, 4) } : {}) }
621
+ const trigger = convId.startsWith(LOCAL_CONV) && this.pendingTrigger ? this.pendingTrigger : null
622
+ this.pendingTrigger = null
623
+ const item: QueueItem = { localId: localId('local_'), conversationId: convId, body: text, createdAt: Date.now(), attempts: 0, ...(attachments.length ? { attachments: attachments.slice(0, 4) } : {}), ...(trigger ? { trigger } : {}) }
354
624
  this.queue.push(item)
355
625
  this.persist(K.queue, this.queue)
356
626
  const msg = this.optimistic(item, 'sending')
@@ -484,6 +754,7 @@ export class SupportClient {
484
754
  private async deliver(item: QueueItem): Promise<void> {
485
755
  const meta: Record<string, unknown> = { localId: item.localId }
486
756
  if (item.attachments?.length) meta['attachments'] = (await this.upload(item)).map((a) => ({ id: a.id }))
757
+ if (item.trigger) meta['trigger'] = item.trigger
487
758
  if (item.conversationId.startsWith(LOCAL_CONV)) {
488
759
  const r = await this.request<{ conversation: Conversation; message: Message }>('POST', '/support/v1/conversations', { body: item.body, meta })
489
760
  this.remapConversation(item.conversationId, r.conversation)
@@ -570,6 +841,7 @@ export class SupportClient {
570
841
  if (!this.ws) this.connect(true)
571
842
  else this.pull().catch(() => {})
572
843
  this.scheduleFlush(0)
844
+ if (this.eraseTimer) void this.flushErase()
573
845
  }
574
846
 
575
847
  private connect(resetBackoff = false): void {
@@ -662,13 +934,65 @@ export class SupportClient {
662
934
 
663
935
  stop(): void {
664
936
  this.stopped = true
665
- for (const t of [this.reconnectTimer, this.flushTimer, ...this.typingTimers.values()]) if (t) clearTimeout(t)
937
+ for (const t of [this.reconnectTimer, this.flushTimer, this.eraseTimer, ...this.typingTimers.values()]) if (t) clearTimeout(t)
666
938
  this.typingTimers.clear()
667
- this.reconnectTimer = this.flushTimer = null
939
+ this.reconnectTimer = this.flushTimer = this.eraseTimer = null
668
940
  this.disconnect()
669
941
  this.set({ status: 'idle' })
670
942
  }
671
943
 
944
+ // Delete my data (Apple 5.1.1(v), GDPR erase; PROTOCOL.md §3.13). The device forgets at once: conversations, queue,
945
+ // ids, the review ledger and the install's analytics (config.analytics, else ShotikAnalytics). Then the server erases
946
+ // what this install's support and analytics recorded. Offline, the request waits on the device and is retried with
947
+ // backoff, after an app restart too. Resolves 'done' once the server confirmed, 'pending' while it waits to retry.
948
+ async deleteMyData(): Promise<'done' | 'pending'> {
949
+ await this.load()
950
+ const token = this.session?.userToken
951
+ if (token) {
952
+ const list = await this.erasing()
953
+ if (!list.includes(token)) await this.storage.set(K.erase, JSON.stringify([...list, token])).catch(() => {})
954
+ }
955
+ await this.reset()
956
+ this.ledger = { installAt: Date.now(), counts: {}, prompts: [], versions: [], frictionAt: 0, refundOrCancelAt: 0, frictionDismissedAt: 0 }
957
+ this.pushToken = null
958
+ await Promise.all([this.storage.remove(K.review), this.storage.remove(K.push)]).catch(() => {})
959
+ const a = this.config.analytics === undefined ? installAnalytics : this.config.analytics
960
+ if (a && !(await a.forget().catch(() => false))) await Promise.resolve(a.reset()).catch(() => {})
961
+ this.anonId = (await this.storage.get(K.anon).catch(() => null)) ?? this.anonId
962
+ return this.flushErase()
963
+ }
964
+
965
+ private async erasing(): Promise<string[]> {
966
+ try {
967
+ return JSON.parse((await this.storage.get(K.erase)) ?? '[]') as string[]
968
+ } catch {
969
+ return []
970
+ }
971
+ }
972
+
973
+ private async flushErase(): Promise<'done' | 'pending'> {
974
+ if (this.eraseTimer) clearTimeout(this.eraseTimer)
975
+ this.eraseTimer = null
976
+ let left = await this.erasing()
977
+ for (const token of left) {
978
+ const status = await fetch(this.config.serverUrl + '/support/v1/erase', { method: 'POST', headers: { 'x-shotik-key': this.config.appKey, 'x-shotik-user': token, 'content-type': 'application/json' }, body: '{}' })
979
+ .then((r) => r.status)
980
+ .catch(() => 0)
981
+ if (status === 0 || status === 429 || status >= 500) continue
982
+ left = left.filter((t) => t !== token)
983
+ }
984
+ await (left.length ? this.storage.set(K.erase, JSON.stringify(left)) : this.storage.remove(K.erase)).catch(() => {})
985
+ if (!left.length) {
986
+ this.eraseStep = 0
987
+ return 'done'
988
+ }
989
+ if (!this.stopped) {
990
+ this.eraseTimer = setTimeout(() => void this.flushErase(), Math.min(300_000, 2_000 * 2 ** this.eraseStep++))
991
+ ;(this.eraseTimer as { unref?: () => void }).unref?.()
992
+ }
993
+ return 'pending'
994
+ }
995
+
672
996
  // Sign-out: forget the identified user and start over as a new anonymous user.
673
997
  async reset(): Promise<void> {
674
998
  await this.load()
@@ -679,7 +1003,8 @@ export class SupportClient {
679
1003
  this.readAt = {}
680
1004
  this.full.clear()
681
1005
  this.anonId = localId('anon_')
682
- await Promise.all([this.storage.set(K.anon, this.anonId), this.storage.remove(K.session), this.storage.remove(K.queue), this.storage.remove(K.read)]).catch(() => {})
683
- this.set({ userId: null, conversations: [], messages: {}, activeConversationId: null, status: 'idle', error: null, typing: {} })
1006
+ this.subscriptionSet = false
1007
+ await Promise.all([this.storage.set(K.anon, this.anonId), this.storage.remove(K.session), this.storage.remove(K.queue), this.storage.remove(K.read), this.storage.remove(K.consent)]).catch(() => {})
1008
+ this.set({ userId: null, conversations: [], messages: {}, activeConversationId: null, status: 'idle', error: null, typing: {}, aiConsent: this.config.aiConsent ?? null, subscription: null, friction: null })
684
1009
  }
685
1010
  }