@shotik/react-native 0.1.0 → 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 +39 -3
  4. package/README.ru.md +40 -3
  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 +94 -1
  16. package/dist/client.js +254 -17
  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 +207 -16
  27. package/dist/support.js +2 -2
  28. package/dist/theme.d.ts +43 -0
  29. package/dist/theme.js +90 -4
  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 +344 -19
  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 +423 -20
  45. package/src/support.ts +2 -2
  46. package/src/theme.ts +90 -4
package/dist/client.js CHANGED
@@ -2,15 +2,20 @@
2
2
  // conversations and messages over HTTP, live replies over the /support/v1/stream WebSocket with reconnect and backoff,
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
+ let installAnalytics = null;
6
+ export function registerAnalytics(a) {
7
+ installAnalytics = a;
8
+ }
9
+ export const actionsOf = (m) => (Array.isArray(m.meta?.['actions']) ? m.meta['actions'].filter((a) => a && typeof a.kind === 'string' && typeof a.label === 'string').slice(0, 3) : []);
5
10
  // Receipt for one of your messages: sending -> sent -> delivered (reached Shotik) -> seen (the founder read it).
6
- // queued = waiting for the network.
11
+ // queued = waiting to send: offline, or the last attempt hit a network error, 5xx or 429 (it goes out on its own).
7
12
  export function receiptOf(m, list, conv, offline = false) {
8
13
  if (m.author !== 'user')
9
14
  return null;
10
15
  if (m.pending === 'failed')
11
16
  return 'failed';
12
17
  if (m.pending)
13
- return offline ? 'queued' : 'sending';
18
+ return offline || m.pending === 'waiting' ? 'queued' : 'sending';
14
19
  const unseen = conv?.founderUnread ?? null;
15
20
  if (unseen !== null) {
16
21
  const mine = list.filter((x) => x.author === 'user' && !x.pending);
@@ -26,9 +31,11 @@ export class HttpError extends Error {
26
31
  this.status = status;
27
32
  }
28
33
  }
29
- const K = { anon: 'shotik.support.anon', session: 'shotik.support.session', queue: 'shotik.support.queue', read: 'shotik.support.read', push: 'shotik.support.push' };
34
+ 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' };
35
+ const DAY = 86400000;
36
+ const FRICTION_N = 3;
37
+ const FRICTION_QUIET_MS = 7 * DAY;
30
38
  const LOCAL_CONV = 'local_conv_';
31
- const AUTO_RETRIES = 3;
32
39
  export function memoryStorage() {
33
40
  const m = new Map();
34
41
  return {
@@ -44,7 +51,14 @@ function localId(prefix) {
44
51
  export class SupportClient {
45
52
  constructor(config) {
46
53
  this.listeners = new Set();
47
- this.state = { status: 'idle', userId: null, conversations: [], messages: {}, unread: 0, unreadBy: {}, open: false, activeConversationId: null, error: null, typing: {} };
54
+ this.state = { status: 'idle', userId: null, conversations: [], messages: {}, unread: 0, unreadBy: {}, open: false, activeConversationId: null, error: null, typing: {}, aiConsent: null, subscription: null, widget: null, friction: null };
55
+ this.subscriptionSet = false;
56
+ this.ledger = { installAt: Date.now(), counts: {}, prompts: [], versions: [], frictionAt: 0, refundOrCancelAt: 0, frictionDismissedAt: 0 };
57
+ this.session_ = { friction: false, chipShown: false, counts: new Map() };
58
+ this.pendingTrigger = null;
59
+ this.offerShown = null;
60
+ this.eraseTimer = null;
61
+ this.eraseStep = 0;
48
62
  this.typingTimers = new Map();
49
63
  this.session = null;
50
64
  this.anonId = null;
@@ -67,6 +81,7 @@ export class SupportClient {
67
81
  this.listeners.add(fn);
68
82
  return () => void this.listeners.delete(fn);
69
83
  };
84
+ this.platform = null;
70
85
  this.config = { ...config, serverUrl: config.serverUrl.replace(/\/+$/, '') };
71
86
  this.storage = config.storage ?? memoryStorage();
72
87
  }
@@ -91,7 +106,14 @@ export class SupportClient {
91
106
  }
92
107
  load() {
93
108
  this.loaded ?? (this.loaded = (async () => {
94
- 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)));
109
+ 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)));
110
+ const aiConsent = consent === 'true' ? true : consent === 'false' ? false : (this.config.aiConsent ?? null);
111
+ if (aiConsent !== this.state.aiConsent)
112
+ this.set({ aiConsent });
113
+ if (review)
114
+ this.ledger = { ...this.ledger, ...JSON.parse(review) };
115
+ else
116
+ this.persist(K.review, this.ledger);
95
117
  this.anonId = anon ?? localId('anon_');
96
118
  if (!anon)
97
119
  await this.storage.set(K.anon, this.anonId).catch(() => { });
@@ -102,9 +124,11 @@ export class SupportClient {
102
124
  if (this.queue.length) {
103
125
  const messages = { ...this.state.messages };
104
126
  for (const q of this.queue)
105
- messages[q.conversationId] = [...(messages[q.conversationId] ?? []), this.optimistic(q, 'sending')];
127
+ messages[q.conversationId] = [...(messages[q.conversationId] ?? []), this.optimistic(q, q.attempts ? 'waiting' : 'sending')];
106
128
  this.set({ messages, conversations: this.withLocalConversations(this.state.conversations, messages) });
107
129
  }
130
+ if ((await this.erasing()).length)
131
+ void this.flushErase();
108
132
  })());
109
133
  return this.loaded;
110
134
  }
@@ -149,6 +173,7 @@ export class SupportClient {
149
173
  await this.load();
150
174
  this.set({ status: this.state.status === 'live' ? 'live' : 'identifying', error: null });
151
175
  const device = await Promise.resolve(this.config.device?.()).catch(() => undefined);
176
+ this.platform = device?.platform?.toLowerCase() ?? null;
152
177
  const r = await this.request('POST', '/support/v1/identify', {
153
178
  anonymousId: this.anonId,
154
179
  userId: this.user.userId,
@@ -157,7 +182,9 @@ export class SupportClient {
157
182
  attributes: this.user.attributes,
158
183
  device: device ?? undefined,
159
184
  appVersion: device?.appVersion ? device.appVersion + (device.build ? ' (' + device.build + ')' : '') : undefined,
160
- locale: device?.locale
185
+ locale: device?.locale,
186
+ aiConsent: this.state.aiConsent ?? undefined,
187
+ subscription: this.subscriptionSet ? this.state.subscription : undefined
161
188
  });
162
189
  const changed = this.session?.userId !== r.user.id;
163
190
  this.session = { userToken: r.userToken, userId: r.user.id, externalId: this.user.userId ?? null };
@@ -168,6 +195,7 @@ export class SupportClient {
168
195
  if (changed || !this.ws)
169
196
  this.connect(true);
170
197
  this.scheduleFlush(0);
198
+ this.loadWidget().catch(() => { });
171
199
  };
172
200
  const p = (this.identifying ?? Promise.resolve()).then(run, run);
173
201
  this.identifying = p.catch((e) => {
@@ -182,6 +210,154 @@ export class SupportClient {
182
210
  ensureIdentified() {
183
211
  return this.identifying ? this.identifying : this.identify();
184
212
  }
213
+ // AI-drafted replies (Apple 5.1.2(i)): true lets the founder's AI draft answers, false keeps the chat person-only.
214
+ setAiConsent(allowed) {
215
+ this.storage.set(K.consent, String(allowed)).catch(() => { });
216
+ this.set({ aiConsent: allowed });
217
+ return this.session ? this.identify() : Promise.resolve();
218
+ }
219
+ // The subscription the founder sees next to the chat and the widget's Subscription screen shows (null: none).
220
+ setSubscription(sub) {
221
+ this.subscriptionSet = true;
222
+ this.set({ subscription: sub });
223
+ return this.session ? this.identify() : Promise.resolve();
224
+ }
225
+ async loadWidget() {
226
+ const w = await this.request('GET', '/support/v1/config');
227
+ this.set({ widget: w });
228
+ }
229
+ // Reports what the user did in the widget; with a conversation it shows in the founder's timeline. Best effort.
230
+ track(kind, data = {}, conversationId) {
231
+ if (kind === 'refund_requested' || kind === 'cancel_continued')
232
+ this.ledgerSet({ refundOrCancelAt: Date.now() });
233
+ if (kind === 'offer_shown')
234
+ this.offerShown = data['reason'];
235
+ if (kind === 'offer_shown' && this.state.widget)
236
+ this.set({ widget: { ...this.state.widget, offers: {}, offerEligible: false } });
237
+ this.ensureIdentified()
238
+ .then(() => this.request('POST', '/support/v1/events', { kind, data, conversationId: conversationId && !conversationId.startsWith(LOCAL_CONV) ? conversationId : undefined }))
239
+ .catch(() => { });
240
+ }
241
+ // Runs an action from a message: the host's onAction, else the store URL fallbacks. The founder sees the outcome.
242
+ async runAction(action, conversationId) {
243
+ let result = 'failed';
244
+ try {
245
+ const r = this.config.onAction ? await this.config.onAction(action) : undefined;
246
+ result = r ?? (this.config.onAction && action.kind === 'custom' ? 'done' : this.openFallback(action));
247
+ }
248
+ catch {
249
+ result = 'failed';
250
+ }
251
+ this.track('action', { actionId: action.id, action: action.kind, label: action.label, result }, conversationId);
252
+ return result;
253
+ }
254
+ // The store pages that do the job when the host has no handler (iOS first; Android goes to Play's subscriptions).
255
+ fallbackUrl(action) {
256
+ const android = this.platform === 'android';
257
+ const id = this.config.appStoreId;
258
+ switch (action.kind) {
259
+ case 'manage_subscription':
260
+ return android ? 'https://play.google.com/store/account/subscriptions' : 'https://apps.apple.com/account/subscriptions';
261
+ case 'request_refund':
262
+ return android ? null : 'https://reportaproblem.apple.com';
263
+ case 'redeem_code':
264
+ return !android && id && action.value ? 'https://apps.apple.com/redeem?ctx=offercodes&id=' + id + '&code=' + encodeURIComponent(action.value) : null;
265
+ case 'write_review':
266
+ return !android && id ? 'https://apps.apple.com/app/id' + id + '?action=write-review' : null;
267
+ case 'open_url':
268
+ return action.value && /^https:\/\//.test(action.value) ? action.value : null;
269
+ default:
270
+ return null;
271
+ }
272
+ }
273
+ openFallback(action) {
274
+ const url = this.fallbackUrl(action);
275
+ if (!url || !this.config.openUrl)
276
+ return 'failed';
277
+ this.config.openUrl(url);
278
+ return 'done';
279
+ }
280
+ // "Did this help?" on a resolved conversation (CSAT): 1 or -1 and an optional line.
281
+ async rate(conversationId, score, comment) {
282
+ this.set({ conversations: this.state.conversations.map((c) => (c.id === conversationId ? { ...c, csat: score } : c)) });
283
+ await this.request('POST', '/support/v1/conversations/' + conversationId + '/rating', { score, comment });
284
+ }
285
+ // A success moment in the app (a goal reached, a streak, a finished lesson). Asks the store's review prompt only when
286
+ // the founder's rules pass: enough of this moment, days since install, not yet in this version, under the yearly cap,
287
+ // and no friction in this session or the quiet days after friction, a refund or a cancel. Returns whether it asked.
288
+ async reviewMoment(name) {
289
+ await this.load();
290
+ const counts = { ...this.ledger.counts, [name]: (this.ledger.counts[name] ?? 0) + 1 };
291
+ this.ledgerSet({ counts });
292
+ const rules = this.state.widget?.review;
293
+ const need = rules?.moments[name];
294
+ if (!rules || !need || !this.config.requestReview)
295
+ return false;
296
+ const now = Date.now();
297
+ const version = (await Promise.resolve(this.config.device?.()).catch(() => undefined))?.appVersion ?? '';
298
+ const ok = counts[name] >= need &&
299
+ now - this.ledger.installAt >= rules.minDaysSinceInstall * DAY &&
300
+ !this.ledger.versions.includes(version) &&
301
+ this.ledger.prompts.filter((t) => now - t < 365 * DAY).length < rules.maxPerYear &&
302
+ !this.session_.friction &&
303
+ now - this.ledger.frictionAt >= rules.quietDaysAfterFriction * DAY &&
304
+ now - this.ledger.refundOrCancelAt >= rules.quietDaysAfterRefundOrCancel * DAY;
305
+ if (!ok)
306
+ return false;
307
+ this.ledgerSet({ prompts: [...this.ledger.prompts, now].slice(-10), versions: [...this.ledger.versions, version].slice(-20) });
308
+ await Promise.resolve(this.config.requestReview()).catch(() => { });
309
+ this.track('review_prompt', { moment: name, version });
310
+ return true;
311
+ }
312
+ // Friction from the app (analytics onEvent, or the host directly): a failed purchase opens the help chip at once;
313
+ // rage taps on one element or the same error three times in a session do too. Once per session, never on quiet screens,
314
+ // and not for a week after the user tapped "Not now".
315
+ friction(f) {
316
+ const now = Date.now();
317
+ this.session_.friction = true;
318
+ this.ledgerSet({ frictionAt: now });
319
+ const key = f.kind + '|' + (f.element ?? '') + '|' + (f.kind === 'rage' ? '' : (f.screen ?? ''));
320
+ const n = (this.session_.counts.get(key) ?? 0) + 1;
321
+ this.session_.counts.set(key, n);
322
+ if (n < (f.kind === 'error' ? FRICTION_N : 1))
323
+ return;
324
+ if (this.session_.chipShown || now - this.ledger.frictionDismissedAt < FRICTION_QUIET_MS)
325
+ return;
326
+ if (f.screen && this.state.widget?.quietScreens.includes(f.screen))
327
+ return;
328
+ this.session_.chipShown = true;
329
+ this.set({ friction: f });
330
+ this.track('friction_shown', { friction: f.kind, screen: f.screen ?? '', element: f.element ?? '' });
331
+ }
332
+ // The user tapped the chip: the next message starts a conversation that carries what happened.
333
+ openFriction() {
334
+ const f = this.state.friction;
335
+ if (!f)
336
+ return;
337
+ this.pendingTrigger = f;
338
+ this.track('friction_opened', { friction: f.kind });
339
+ this.set({ friction: null, open: true, activeConversationId: null });
340
+ }
341
+ // The user took the save offer for this cancel reason: the widget opens on a new conversation that goes to the founder.
342
+ // Showing the offer empties widget.offers for the cooldown, so the reason shown on screen still counts.
343
+ askForOffer(reason) {
344
+ if (!this.state.widget?.offers[reason] && this.offerShown !== reason)
345
+ return;
346
+ this.pendingTrigger = { kind: 'offer', element: reason };
347
+ this.track('offer_accepted', { reason });
348
+ this.set({ open: true, activeConversationId: null });
349
+ }
350
+ dismissFriction() {
351
+ if (!this.state.friction)
352
+ return;
353
+ this.ledgerSet({ frictionDismissedAt: Date.now() });
354
+ this.track('friction_dismissed', { friction: this.state.friction.kind });
355
+ this.set({ friction: null });
356
+ }
357
+ ledgerSet(p) {
358
+ this.ledger = { ...this.ledger, ...p };
359
+ this.persist(K.review, this.ledger);
360
+ }
185
361
  async setPushToken(token, platform = 'ios') {
186
362
  await this.load();
187
363
  this.pushToken = token ? { token, platform } : null;
@@ -235,7 +411,9 @@ export class SupportClient {
235
411
  if (!text && !attachments.length)
236
412
  return null;
237
413
  const convId = conversationId || this.state.activeConversationId || LOCAL_CONV + localId('');
238
- const item = { localId: localId('local_'), conversationId: convId, body: text, createdAt: Date.now(), attempts: 0, ...(attachments.length ? { attachments: attachments.slice(0, 4) } : {}) };
414
+ const trigger = convId.startsWith(LOCAL_CONV) && this.pendingTrigger ? this.pendingTrigger : null;
415
+ this.pendingTrigger = null;
416
+ const item = { localId: localId('local_'), conversationId: convId, body: text, createdAt: Date.now(), attempts: 0, ...(attachments.length ? { attachments: attachments.slice(0, 4) } : {}), ...(trigger ? { trigger } : {}) };
239
417
  this.queue.push(item);
240
418
  this.persist(K.queue, this.queue);
241
419
  const msg = this.optimistic(item, 'sending');
@@ -267,7 +445,8 @@ export class SupportClient {
267
445
  get pendingCount() {
268
446
  return this.queue.length;
269
447
  }
270
- // Deliver queued messages in order. Network errors and 5xx keep them queued with backoff; a 4xx fails the message.
448
+ // Deliver queued messages in order. Network errors, 5xx and 429 keep them queued as 'waiting' with backoff; another 4xx
449
+ // fails the message.
271
450
  flush() {
272
451
  this.flushing ?? (this.flushing = (async () => {
273
452
  try {
@@ -288,7 +467,7 @@ export class SupportClient {
288
467
  this.identify().catch(() => { });
289
468
  return;
290
469
  }
291
- if (status >= 400 && status < 500) {
470
+ if (status >= 400 && status < 500 && status !== 429) {
292
471
  this.queue.shift();
293
472
  this.persist(K.queue, this.queue);
294
473
  this.markPending(item, 'failed');
@@ -296,8 +475,7 @@ export class SupportClient {
296
475
  }
297
476
  item.attempts++;
298
477
  this.persist(K.queue, this.queue);
299
- if (item.attempts >= AUTO_RETRIES)
300
- this.markPending(item, 'failed');
478
+ this.markPending(item, 'waiting');
301
479
  this.set({ status: this.ws ? this.state.status : 'offline', error: e.message });
302
480
  this.scheduleFlush(Math.min(30000, 500 * 2 ** item.attempts));
303
481
  return;
@@ -374,6 +552,8 @@ export class SupportClient {
374
552
  const meta = { localId: item.localId };
375
553
  if (item.attachments?.length)
376
554
  meta['attachments'] = (await this.upload(item)).map((a) => ({ id: a.id }));
555
+ if (item.trigger)
556
+ meta['trigger'] = item.trigger;
377
557
  if (item.conversationId.startsWith(LOCAL_CONV)) {
378
558
  const r = await this.request('POST', '/support/v1/conversations', { body: item.body, meta });
379
559
  this.remapConversation(item.conversationId, r.conversation);
@@ -462,6 +642,8 @@ export class SupportClient {
462
642
  else
463
643
  this.pull().catch(() => { });
464
644
  this.scheduleFlush(0);
645
+ if (this.eraseTimer)
646
+ void this.flushErase();
465
647
  }
466
648
  connect(resetBackoff = false) {
467
649
  if (this.stopped || !this.session)
@@ -572,14 +754,68 @@ export class SupportClient {
572
754
  }
573
755
  stop() {
574
756
  this.stopped = true;
575
- for (const t of [this.reconnectTimer, this.flushTimer, ...this.typingTimers.values()])
757
+ for (const t of [this.reconnectTimer, this.flushTimer, this.eraseTimer, ...this.typingTimers.values()])
576
758
  if (t)
577
759
  clearTimeout(t);
578
760
  this.typingTimers.clear();
579
- this.reconnectTimer = this.flushTimer = null;
761
+ this.reconnectTimer = this.flushTimer = this.eraseTimer = null;
580
762
  this.disconnect();
581
763
  this.set({ status: 'idle' });
582
764
  }
765
+ // Delete my data (Apple 5.1.1(v), GDPR erase; PROTOCOL.md §3.13). The device forgets at once: conversations, queue,
766
+ // ids, the review ledger and the install's analytics (config.analytics, else ShotikAnalytics). Then the server erases
767
+ // what this install's support and analytics recorded. Offline, the request waits on the device and is retried with
768
+ // backoff, after an app restart too. Resolves 'done' once the server confirmed, 'pending' while it waits to retry.
769
+ async deleteMyData() {
770
+ await this.load();
771
+ const token = this.session?.userToken;
772
+ if (token) {
773
+ const list = await this.erasing();
774
+ if (!list.includes(token))
775
+ await this.storage.set(K.erase, JSON.stringify([...list, token])).catch(() => { });
776
+ }
777
+ await this.reset();
778
+ this.ledger = { installAt: Date.now(), counts: {}, prompts: [], versions: [], frictionAt: 0, refundOrCancelAt: 0, frictionDismissedAt: 0 };
779
+ this.pushToken = null;
780
+ await Promise.all([this.storage.remove(K.review), this.storage.remove(K.push)]).catch(() => { });
781
+ const a = this.config.analytics === undefined ? installAnalytics : this.config.analytics;
782
+ if (a && !(await a.forget().catch(() => false)))
783
+ await Promise.resolve(a.reset()).catch(() => { });
784
+ this.anonId = (await this.storage.get(K.anon).catch(() => null)) ?? this.anonId;
785
+ return this.flushErase();
786
+ }
787
+ async erasing() {
788
+ try {
789
+ return JSON.parse((await this.storage.get(K.erase)) ?? '[]');
790
+ }
791
+ catch {
792
+ return [];
793
+ }
794
+ }
795
+ async flushErase() {
796
+ if (this.eraseTimer)
797
+ clearTimeout(this.eraseTimer);
798
+ this.eraseTimer = null;
799
+ let left = await this.erasing();
800
+ for (const token of left) {
801
+ 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: '{}' })
802
+ .then((r) => r.status)
803
+ .catch(() => 0);
804
+ if (status === 0 || status === 429 || status >= 500)
805
+ continue;
806
+ left = left.filter((t) => t !== token);
807
+ }
808
+ await (left.length ? this.storage.set(K.erase, JSON.stringify(left)) : this.storage.remove(K.erase)).catch(() => { });
809
+ if (!left.length) {
810
+ this.eraseStep = 0;
811
+ return 'done';
812
+ }
813
+ if (!this.stopped) {
814
+ this.eraseTimer = setTimeout(() => void this.flushErase(), Math.min(300000, 2000 * 2 ** this.eraseStep++));
815
+ this.eraseTimer.unref?.();
816
+ }
817
+ return 'pending';
818
+ }
583
819
  // Sign-out: forget the identified user and start over as a new anonymous user.
584
820
  async reset() {
585
821
  await this.load();
@@ -590,7 +826,8 @@ export class SupportClient {
590
826
  this.readAt = {};
591
827
  this.full.clear();
592
828
  this.anonId = localId('anon_');
593
- 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(() => { });
594
- this.set({ userId: null, conversations: [], messages: {}, activeConversationId: null, status: 'idle', error: null, typing: {} });
829
+ this.subscriptionSet = false;
830
+ 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(() => { });
831
+ this.set({ userId: null, conversations: [], messages: {}, activeConversationId: null, status: 'idle', error: null, typing: {}, aiConsent: this.config.aiConsent ?? null, subscription: null, friction: null });
595
832
  }
596
833
  }
package/dist/flow.d.ts ADDED
@@ -0,0 +1,48 @@
1
+ import type { ActionResult, CancelReason, Conversation, Offer, Subscription, SupportEventKind } from './client';
2
+ import type { Copy } from './theme';
3
+ export type Screen = 'sub' | 'reason' | 'offer' | 'refund';
4
+ export interface CancelFlow {
5
+ screen: Screen | null;
6
+ reason: CancelReason | null;
7
+ offer: Offer | null;
8
+ offered: boolean;
9
+ from: Screen | null;
10
+ }
11
+ export declare const startFlow: CancelFlow;
12
+ export declare const cancelReasons: CancelReason[];
13
+ export type FlowEvent = {
14
+ type: 'open';
15
+ } | {
16
+ type: 'cancel';
17
+ } | {
18
+ type: 'refund';
19
+ } | {
20
+ type: 'pick';
21
+ reason: CancelReason | null;
22
+ } | {
23
+ type: 'store';
24
+ } | {
25
+ type: 'accept';
26
+ } | {
27
+ type: 'continue';
28
+ } | {
29
+ type: 'requestRefund';
30
+ } | {
31
+ type: 'back';
32
+ };
33
+ export type FlowRun = 'manage_subscription' | 'request_refund' | 'offer' | null;
34
+ export interface FlowStep {
35
+ flow: CancelFlow;
36
+ track: [SupportEventKind, Record<string, string>][];
37
+ run: FlowRun;
38
+ }
39
+ export declare function stepFlow(f: CancelFlow, e: FlowEvent, offers: Partial<Record<CancelReason, Offer>>): FlowStep;
40
+ export declare const canCancel: (sub: Subscription) => boolean;
41
+ export declare const storeName: (sub: Subscription | null, android: boolean) => string;
42
+ export declare function subscriptionSummary(sub: Subscription, t: Copy, date: (ms: number) => string): {
43
+ plan: string;
44
+ detail: string;
45
+ };
46
+ export declare function csatPrompt(conv: Conversation | null | undefined, ratedHere: boolean): 'ask' | 'thanks' | null;
47
+ export type RunState = 'pending' | 'done' | 'failed';
48
+ export declare const runState: (r: ActionResult) => RunState | null;
package/dist/flow.js ADDED
@@ -0,0 +1,56 @@
1
+ // The widget's v1.1 logic without React Native imports, so server/test runs it under plain Node: the honest cancel flow
2
+ // (PROTOCOL.md §3.10), the subscription summary, the CSAT prompt (§3.12) and action button states (§3.9).
3
+ import { fill } from './theme';
4
+ export const startFlow = { screen: null, reason: null, offer: null, offered: false, from: null };
5
+ export const cancelReasons = ['too_expensive', 'not_using', 'bug', 'mistake', 'other'];
6
+ export function stepFlow(f, e, offers) {
7
+ const to = (p, track = [], run = null) => ({ flow: { ...f, ...p }, track, run });
8
+ const toStore = [['cancel_continued', {}]];
9
+ switch (e.type) {
10
+ case 'open':
11
+ return to({ screen: 'sub', from: null });
12
+ case 'cancel':
13
+ return to({ screen: 'reason', reason: null }, [['cancel_started', {}]]);
14
+ case 'refund':
15
+ return to({ screen: 'refund', from: f.screen ?? 'sub' }, [['refund_help', {}]]);
16
+ case 'pick': {
17
+ const r = e.reason;
18
+ const said = r ? [['cancel_reason', { reason: r }]] : [];
19
+ if (r === 'mistake')
20
+ return to({ reason: r, screen: 'refund', from: 'reason' }, [...said, ['refund_help', {}]]);
21
+ const offer = r && !f.offered ? offers[r] : undefined;
22
+ if (r && offer)
23
+ return to({ reason: r, screen: 'offer', offer, offered: true }, [...said, ['offer_shown', { reason: r }]]);
24
+ return to({ reason: r, screen: 'sub' }, [...said, ...toStore], 'manage_subscription');
25
+ }
26
+ case 'store':
27
+ case 'continue':
28
+ return to({ screen: 'sub' }, toStore, 'manage_subscription');
29
+ case 'accept':
30
+ return to({ screen: null }, [], f.offer && f.reason ? 'offer' : null);
31
+ case 'requestRefund':
32
+ return to({ screen: 'sub' }, [['refund_requested', {}]], 'request_refund');
33
+ case 'back':
34
+ return to({ screen: f.screen === 'offer' ? 'reason' : f.screen === 'reason' ? 'sub' : f.screen === 'refund' ? f.from : null });
35
+ }
36
+ }
37
+ // Only a renewing plan can be cancelled; lifetime purchases and ended plans can't.
38
+ export const canCancel = (sub) => (sub.status === 'trial' || sub.status === 'active' || sub.status === 'grace' || sub.status === 'billing_retry') && sub.willRenew !== false && sub.period !== 'lifetime';
39
+ export const storeName = (sub, android) => (sub?.store === 'play' || (!sub?.store && android) ? 'Google Play' : 'App Store');
40
+ // The Subscription row: plan, then price and the next date that matters.
41
+ export function subscriptionSummary(sub, t, date) {
42
+ const when = sub.status === 'expired' || sub.status === 'refunded' ? t.ended
43
+ : sub.status === 'trial' && sub.trialEndsAt ? fill(t.trialEnds, { date: date(sub.trialEndsAt) })
44
+ : sub.status === 'cancelled' || sub.willRenew === false ? (sub.expiresAt ? fill(t.ends, { date: date(sub.expiresAt) }) : '')
45
+ : sub.renewsAt ? fill(t.renews, { date: date(sub.renewsAt) })
46
+ : '';
47
+ return { plan: sub.product || t.subscription, detail: [sub.price, when].filter(Boolean).join(' · ') };
48
+ }
49
+ // "Did this help?" once a conversation is resolved and not rated yet; "Thanks" right after the user rated it.
50
+ export function csatPrompt(conv, ratedHere) {
51
+ if (ratedHere)
52
+ return 'thanks';
53
+ return conv?.status === 'resolved' && (conv.csat ?? null) === null ? 'ask' : null;
54
+ }
55
+ // A cancelled action (the user closed the store sheet) goes back to its idle look.
56
+ export const runState = (r) => (r === 'cancelled' ? null : r);
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  export { ShotikSupport } from './support';
2
- export { ShotikSupportProvider, SupportRoute, SupportSheet, SupportWidget, useSupport } from './react';
3
- export type { ProviderProps, SheetViewProps, SupportApi, WidgetProps } from './react';
4
- export { SupportClient, HttpError, memoryStorage, receiptOf, attachmentsOf } from './client';
5
- export type { Attachment, Author, Conversation, ConversationStatus, DeviceInfo, KeyValueStorage, LocalAttachment, Message, Receipt, Status, SupportConfig, SupportState, Typing, UserInfo } from './client';
2
+ export { ShotikSupportProvider, SupportFrictionChip, SupportRoute, SupportSheet, SupportWidget, useSupport } from './react';
3
+ export type { FrictionChipProps, ProviderProps, SheetViewProps, SupportApi, WidgetProps } from './react';
4
+ export { SupportClient, HttpError, memoryStorage, receiptOf, attachmentsOf, actionsOf } from './client';
5
+ export type { ActionKind, ActionResult, Attachment, Author, CancelReason, Conversation, ConversationStatus, DeviceInfo, Friction, KeyValueStorage, LocalAttachment, Message, Offer, Receipt, Status, Subscription, SupportAction, SupportConfig, SupportEventKind, SupportState, Trigger, Typing, UserInfo, WidgetConfig } from './client';
6
6
  export type { Colors, Copy, SupportTheme } from './theme';
7
7
  export { catalogs } from './theme';
8
8
  export { nativeDevice, nativeStorage } from './native';
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // @shotik/react-native: in-app support chat for React Native and Expo, backed by a Shotik workspace.
2
2
  export { ShotikSupport } from './support';
3
- export { ShotikSupportProvider, SupportRoute, SupportSheet, SupportWidget, useSupport } from './react';
4
- export { SupportClient, HttpError, memoryStorage, receiptOf, attachmentsOf } from './client';
3
+ export { ShotikSupportProvider, SupportFrictionChip, SupportRoute, SupportSheet, SupportWidget, useSupport } from './react';
4
+ export { SupportClient, HttpError, memoryStorage, receiptOf, attachmentsOf, actionsOf } from './client';
5
5
  export { catalogs } from './theme';
6
6
  export { nativeDevice, nativeStorage } from './native';
package/dist/parts.d.ts CHANGED
@@ -20,6 +20,10 @@ export declare const motion: {
20
20
  period: number;
21
21
  gap: number;
22
22
  };
23
+ reveal: {
24
+ duration: number;
25
+ y: number;
26
+ };
23
27
  };
24
28
  export declare function useReduceMotion(): boolean;
25
29
  export declare const font: (c: Resolved, bold?: boolean) => TextStyle;
@@ -44,8 +48,45 @@ export declare function Plus({ color }: {
44
48
  export declare function ArrowUp({ color }: {
45
49
  color: string;
46
50
  }): import("react").JSX.Element;
47
- export declare function Clock({ color }: {
51
+ export declare function Clock({ color, size }: {
52
+ color: string;
53
+ size?: number;
54
+ }): import("react").JSX.Element;
55
+ export declare function Forward({ color }: {
56
+ color: string;
57
+ }): import("react").JSX.Element;
58
+ export declare function Tick({ color, size }: {
48
59
  color: string;
60
+ size?: number;
61
+ }): import("react").JSX.Element;
62
+ export declare function Alert({ color, size }: {
63
+ color: string;
64
+ size?: number;
65
+ }): import("react").JSX.Element;
66
+ export declare function Trash({ color, size }: {
67
+ color: string;
68
+ size?: number;
69
+ }): import("react").JSX.Element;
70
+ export declare function Thumb({ up, color }: {
71
+ up: boolean;
72
+ color: string;
73
+ }): import("react").JSX.Element | null;
74
+ export declare function LoadingBar({ color, reduce }: {
75
+ color: string;
76
+ reduce: boolean;
77
+ }): import("react").JSX.Element;
78
+ export declare function Reveal({ reduce, style, children }: {
79
+ reduce: boolean;
80
+ style?: StyleProp<ViewStyle>;
81
+ children?: ReactNode;
82
+ }): import("react").JSX.Element;
83
+ export declare function FrictionChip({ c, t, reduce, onOpen, onClose, style }: {
84
+ c: Resolved;
85
+ t: Copy;
86
+ reduce: boolean;
87
+ onOpen: () => void;
88
+ onClose: () => void;
89
+ style?: StyleProp<ViewStyle>;
49
90
  }): import("react").JSX.Element;
50
91
  export declare function Spark({ color, size }: {
51
92
  color: string;