@shotik/react-native 0.0.0-stage → 0.1.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.
package/src/client.ts ADDED
@@ -0,0 +1,685 @@
1
+ // Shotik Support client: the platform-free core of the SDK. Identify (anonymous id persisted, merged on sign-in),
2
+ // conversations and messages over HTTP, live replies over the /support/v1/stream WebSocket with reconnect and backoff,
3
+ // an offline send queue with optimistic messages, and a pull for anything missed. No React Native imports, so it runs
4
+ // (and is tested) under plain Node as well as in the app.
5
+
6
+ export type Author = 'user' | 'ai' | 'founder' | 'system'
7
+ export type ConversationStatus = 'open' | 'needs_human' | 'resolved' | 'closed' | string
8
+ export type Status = 'idle' | 'identifying' | 'connecting' | 'live' | 'offline' | 'error'
9
+
10
+ export interface Conversation {
11
+ id: string
12
+ status: ConversationStatus
13
+ subject: string | null
14
+ lastMessageAt: number
15
+ lastPreview: string | null
16
+ lastAuthor: Author | null
17
+ createdAt: number
18
+ // User messages the founder has not read yet; 0 means everything you sent was seen.
19
+ founderUnread?: number
20
+ }
21
+
22
+ // A picked photo or screenshot before upload (uri: file:// or data:), and the uploaded form in message meta.
23
+ export interface LocalAttachment {
24
+ uri: string
25
+ type?: string
26
+ name?: string
27
+ width?: number
28
+ height?: number
29
+ }
30
+
31
+ export interface Attachment {
32
+ id: string
33
+ type: string
34
+ size: number
35
+ width: number | null
36
+ height: number | null
37
+ path: string
38
+ }
39
+
40
+ export type Receipt = 'sending' | 'queued' | 'failed' | 'sent' | 'delivered' | 'seen'
41
+ export type Typing = 'ai' | 'founder'
42
+
43
+ export interface Message {
44
+ id: string
45
+ conversationId: string
46
+ author: Author
47
+ body: string
48
+ createdAt: number
49
+ meta?: Record<string, unknown> | null
50
+ // When the message reached the other side (Shotik for yours, the device for replies).
51
+ deliveredAt?: number | null
52
+ localId?: string
53
+ pending?: 'sending' | 'failed'
54
+ }
55
+
56
+ export interface UserInfo {
57
+ userId?: string
58
+ name?: string
59
+ email?: string
60
+ attributes?: Record<string, unknown>
61
+ }
62
+
63
+ export interface DeviceInfo {
64
+ platform?: string
65
+ osVersion?: string
66
+ model?: string
67
+ appVersion?: string
68
+ build?: string
69
+ locale?: string
70
+ timezone?: string
71
+ }
72
+
73
+ export interface KeyValueStorage {
74
+ get(key: string): Promise<string | null>
75
+ set(key: string, value: string): Promise<void>
76
+ remove(key: string): Promise<void>
77
+ }
78
+
79
+ export interface SupportConfig {
80
+ appKey: string
81
+ serverUrl: string
82
+ storage?: KeyValueStorage
83
+ device?: () => DeviceInfo | Promise<DeviceInfo>
84
+ }
85
+
86
+ export interface SupportState {
87
+ status: Status
88
+ userId: string | null
89
+ conversations: Conversation[]
90
+ messages: Record<string, Message[]>
91
+ unread: number
92
+ unreadBy: Record<string, number>
93
+ open: boolean
94
+ activeConversationId: string | null
95
+ error: string | null
96
+ // Who is typing in each conversation right now (the AI drafting or the founder in Shotik).
97
+ typing: Record<string, Typing>
98
+ }
99
+
100
+ interface QueueItem {
101
+ localId: string
102
+ conversationId: string
103
+ body: string
104
+ createdAt: number
105
+ attempts: number
106
+ attachments?: (LocalAttachment & { remote?: Attachment })[]
107
+ }
108
+
109
+ // Receipt for one of your messages: sending -> sent -> delivered (reached Shotik) -> seen (the founder read it).
110
+ // queued = waiting for the network.
111
+ export function receiptOf(m: Message, list: Message[], conv: Conversation | undefined, offline = false): Receipt | null {
112
+ if (m.author !== 'user') return null
113
+ if (m.pending === 'failed') return 'failed'
114
+ if (m.pending) return offline ? 'queued' : 'sending'
115
+ const unseen = conv?.founderUnread ?? null
116
+ if (unseen !== null) {
117
+ const mine = list.filter((x) => x.author === 'user' && !x.pending)
118
+ if (mine.indexOf(m) < mine.length - unseen) return 'seen'
119
+ }
120
+ return m.deliveredAt ? 'delivered' : 'sent'
121
+ }
122
+
123
+ export const attachmentsOf = (m: Message): (Partial<Attachment> & { uri?: string })[] => (Array.isArray(m.meta?.['attachments']) ? (m.meta['attachments'] as Attachment[]) : [])
124
+
125
+ interface Session {
126
+ userToken: string
127
+ userId: string
128
+ externalId: string | null
129
+ }
130
+
131
+ export class HttpError extends Error {
132
+ status: number
133
+ constructor(status: number, message: string) {
134
+ super(message)
135
+ this.status = status
136
+ }
137
+ }
138
+
139
+ const K = { anon: 'shotik.support.anon', session: 'shotik.support.session', queue: 'shotik.support.queue', read: 'shotik.support.read', push: 'shotik.support.push' }
140
+ const LOCAL_CONV = 'local_conv_'
141
+ const AUTO_RETRIES = 3
142
+
143
+ export function memoryStorage(): KeyValueStorage {
144
+ const m = new Map<string, string>()
145
+ return {
146
+ get: async (k) => m.get(k) ?? null,
147
+ set: async (k, v) => void m.set(k, v),
148
+ remove: async (k) => void m.delete(k)
149
+ }
150
+ }
151
+
152
+ const isReactNative = () => typeof navigator !== 'undefined' && (navigator as { product?: string }).product === 'ReactNative'
153
+
154
+ function localId(prefix: string): string {
155
+ return prefix + Date.now().toString(36) + Math.random().toString(36).slice(2, 10)
156
+ }
157
+
158
+ export class SupportClient {
159
+ readonly config: SupportConfig
160
+ private storage: KeyValueStorage
161
+ private listeners = new Set<(s: SupportState) => void>()
162
+ private state: SupportState = { status: 'idle', userId: null, conversations: [], messages: {}, unread: 0, unreadBy: {}, open: false, activeConversationId: null, error: null, typing: {} }
163
+ private typingTimers = new Map<string, ReturnType<typeof setTimeout>>()
164
+ private session: Session | null = null
165
+ private anonId: string | null = null
166
+ private user: UserInfo = {}
167
+ private queue: QueueItem[] = []
168
+ private readAt: Record<string, number> = {}
169
+ private pushToken: { token: string; platform: string } | null = null
170
+ private ws: WebSocket | null = null
171
+ private backoffStep = 0
172
+ private reconnectTimer: ReturnType<typeof setTimeout> | null = null
173
+ private flushTimer: ReturnType<typeof setTimeout> | null = null
174
+ private ping: ReturnType<typeof setInterval> | null = null
175
+ private flushing: Promise<void> | null = null
176
+ private identifying: Promise<void> | null = null
177
+ private loaded: Promise<void> | null = null
178
+ private full = new Set<string>()
179
+ private stopped = false
180
+
181
+ constructor(config: SupportConfig) {
182
+ this.config = { ...config, serverUrl: config.serverUrl.replace(/\/+$/, '') }
183
+ this.storage = config.storage ?? memoryStorage()
184
+ }
185
+
186
+ getState = (): SupportState => this.state
187
+
188
+ subscribe = (fn: (s: SupportState) => void): (() => void) => {
189
+ this.listeners.add(fn)
190
+ return () => void this.listeners.delete(fn)
191
+ }
192
+
193
+ private set(p: Partial<SupportState>): void {
194
+ const next = { ...this.state, ...p }
195
+ next.unreadBy = this.countUnread(next)
196
+ next.unread = Object.values(next.unreadBy).reduce((a, b) => a + b, 0)
197
+ this.state = next
198
+ for (const fn of this.listeners) fn(next)
199
+ }
200
+
201
+ private countUnread(s: SupportState): Record<string, number> {
202
+ const out: Record<string, number> = {}
203
+ for (const c of s.conversations) {
204
+ const seen = this.readAt[c.id] ?? 0
205
+ const msgs = s.messages[c.id]
206
+ const n = msgs ? msgs.filter((m) => m.author !== 'user' && m.createdAt > seen).length : c.lastAuthor && c.lastAuthor !== 'user' && c.lastMessageAt > seen ? 1 : 0
207
+ if (n) out[c.id] = n
208
+ }
209
+ return out
210
+ }
211
+
212
+ private load(): Promise<void> {
213
+ this.loaded ??= (async () => {
214
+ 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)))
215
+ this.anonId = anon ?? localId('anon_')
216
+ if (!anon) await this.storage.set(K.anon, this.anonId).catch(() => {})
217
+ this.session = session ? (JSON.parse(session) as Session) : null
218
+ this.queue = queue ? (JSON.parse(queue) as QueueItem[]) : []
219
+ this.readAt = read ? (JSON.parse(read) as Record<string, number>) : {}
220
+ this.pushToken = push ? (JSON.parse(push) as { token: string; platform: string }) : null
221
+ if (this.queue.length) {
222
+ const messages = { ...this.state.messages }
223
+ for (const q of this.queue) messages[q.conversationId] = [...(messages[q.conversationId] ?? []), this.optimistic(q, 'sending')]
224
+ this.set({ messages, conversations: this.withLocalConversations(this.state.conversations, messages) })
225
+ }
226
+ })()
227
+ return this.loaded
228
+ }
229
+
230
+ private persist(key: string, value: unknown): void {
231
+ this.storage.set(key, JSON.stringify(value)).catch(() => {})
232
+ }
233
+
234
+ async request<T>(method: 'GET' | 'POST', path: string, body?: unknown): Promise<T> {
235
+ const form = typeof FormData !== 'undefined' && body instanceof FormData
236
+ const headers: Record<string, string> = { 'x-shotik-key': this.config.appKey }
237
+ if (!form) headers['content-type'] = 'application/json'
238
+ if (this.session) headers['x-shotik-user'] = this.session.userToken
239
+ const url = this.config.serverUrl + path
240
+ // Expo replaces the global fetch with one that can't send React Native's { uri, type, name } file parts, so uploads
241
+ // go through XMLHttpRequest, which uses React Native's own networking.
242
+ const res: { status: number; text: string } =
243
+ form && isReactNative()
244
+ ? await new Promise((resolve, reject) => {
245
+ const x = new XMLHttpRequest()
246
+ x.open(method, url)
247
+ for (const [k, v] of Object.entries(headers)) x.setRequestHeader(k, v)
248
+ x.onload = () => resolve({ status: x.status, text: x.responseText })
249
+ x.onerror = () => reject(new TypeError('Network request failed'))
250
+ x.send(body as FormData)
251
+ })
252
+ : await fetch(url, { method, headers, body: body === undefined ? undefined : form ? (body as FormData) : JSON.stringify(body) }).then(async (r) => ({ status: r.status, text: await r.text().catch(() => '') }))
253
+ let json = {} as T & { error?: string }
254
+ try {
255
+ json = JSON.parse(res.text)
256
+ } catch {}
257
+ if (res.status < 200 || res.status >= 300) throw new HttpError(res.status, json.error ?? 'HTTP ' + res.status)
258
+ return json
259
+ }
260
+
261
+ // Identify the app user. Without a userId the persisted anonymous id is used; with one, the anonymous user's
262
+ // conversations move to the signed-in user on the server.
263
+ identify(user: UserInfo = {}): Promise<void> {
264
+ this.user = { ...this.user, ...user }
265
+ const run = async () => {
266
+ await this.load()
267
+ this.set({ status: this.state.status === 'live' ? 'live' : 'identifying', error: null })
268
+ const device = await Promise.resolve(this.config.device?.()).catch(() => undefined)
269
+ const r = await this.request<{ user: { id: string }; userToken: string; conversations: Conversation[] }>('POST', '/support/v1/identify', {
270
+ anonymousId: this.anonId,
271
+ userId: this.user.userId,
272
+ name: this.user.name,
273
+ email: this.user.email,
274
+ attributes: this.user.attributes,
275
+ device: device ?? undefined,
276
+ appVersion: device?.appVersion ? device.appVersion + (device.build ? ' (' + device.build + ')' : '') : undefined,
277
+ locale: device?.locale
278
+ })
279
+ const changed = this.session?.userId !== r.user.id
280
+ this.session = { userToken: r.userToken, userId: r.user.id, externalId: this.user.userId ?? null }
281
+ this.persist(K.session, this.session)
282
+ this.set({ userId: r.user.id, conversations: this.withLocalConversations(r.conversations) })
283
+ if (this.pushToken) await this.sendPushToken().catch(() => {})
284
+ if (changed || !this.ws) this.connect(true)
285
+ this.scheduleFlush(0)
286
+ }
287
+ const p = (this.identifying ?? Promise.resolve()).then(run, run)
288
+ this.identifying = p.catch((e: Error) => {
289
+ if (e instanceof HttpError && e.status === 401) return this.set({ status: 'error', error: e.message })
290
+ this.set({ status: 'offline', error: e.message })
291
+ this.scheduleReconnect()
292
+ })
293
+ return p
294
+ }
295
+
296
+ // Identify anonymously unless the app already did.
297
+ ensureIdentified(): Promise<void> {
298
+ return this.identifying ? this.identifying : this.identify()
299
+ }
300
+
301
+ async setPushToken(token: string | null, platform = 'ios'): Promise<void> {
302
+ await this.load()
303
+ this.pushToken = token ? { token, platform } : null
304
+ this.persist(K.push, this.pushToken)
305
+ if (this.session) await this.sendPushToken()
306
+ }
307
+
308
+ private sendPushToken(): Promise<unknown> {
309
+ return this.request('POST', '/support/v1/push-token', this.pushToken ?? { token: null })
310
+ }
311
+
312
+ open(conversationId?: string | null): void {
313
+ this.set({ open: true, activeConversationId: conversationId === undefined ? this.state.activeConversationId : conversationId })
314
+ if (conversationId) this.select(conversationId)
315
+ }
316
+
317
+ close(): void {
318
+ this.set({ open: false })
319
+ }
320
+
321
+ // Show one thread (or the list with null), load its messages and mark it read.
322
+ select(conversationId: string | null): void {
323
+ this.set({ activeConversationId: conversationId })
324
+ if (!conversationId) return
325
+ this.markRead(conversationId)
326
+ if (!conversationId.startsWith(LOCAL_CONV)) this.loadMessages(conversationId).catch(() => {})
327
+ }
328
+
329
+ markRead(conversationId: string): void {
330
+ const msgs = this.state.messages[conversationId] ?? []
331
+ const conv = this.state.conversations.find((c) => c.id === conversationId)
332
+ this.readAt[conversationId] = Math.max(conv?.lastMessageAt ?? 0, ...msgs.filter((m) => !m.pending).map((m) => m.createdAt))
333
+ this.persist(K.read, this.readAt)
334
+ this.set({})
335
+ if (!conversationId.startsWith(LOCAL_CONV) && this.state.userId) this.request('POST', '/support/v1/conversations/' + conversationId + '/read', {}).catch(() => {})
336
+ }
337
+
338
+ async loadMessages(conversationId: string): Promise<Message[]> {
339
+ const have = (this.state.messages[conversationId] ?? []).filter((m) => !m.pending)
340
+ const after = this.full.has(conversationId) && have.length ? have[have.length - 1].createdAt - 1 : 0
341
+ const r = await this.request<{ messages: Message[] }>('GET', '/support/v1/conversations/' + conversationId + '/messages?after=' + after)
342
+ this.full.add(conversationId)
343
+ this.mergeMessages(conversationId, r.messages)
344
+ if (this.state.open && this.state.activeConversationId === conversationId) this.markRead(conversationId)
345
+ return this.state.messages[conversationId] ?? []
346
+ }
347
+
348
+ // Send a message. Without a conversation id (or with a local one) a new conversation is started. The message shows
349
+ // at once; the queue delivers it now or once the server is reachable again.
350
+ send(body: string, conversationId?: string | null, attachments: LocalAttachment[] = []): Message | null {
351
+ const text = body.trim()
352
+ if (!text && !attachments.length) return null
353
+ const convId = conversationId || this.state.activeConversationId || LOCAL_CONV + localId('')
354
+ const item: QueueItem = { localId: localId('local_'), conversationId: convId, body: text, createdAt: Date.now(), attempts: 0, ...(attachments.length ? { attachments: attachments.slice(0, 4) } : {}) }
355
+ this.queue.push(item)
356
+ this.persist(K.queue, this.queue)
357
+ const msg = this.optimistic(item, 'sending')
358
+ const messages = { ...this.state.messages, [convId]: [...(this.state.messages[convId] ?? []), msg] }
359
+ this.set({
360
+ messages,
361
+ conversations: this.withLocalConversations(this.state.conversations, messages),
362
+ activeConversationId: this.state.open ? convId : this.state.activeConversationId
363
+ })
364
+ this.scheduleFlush(0)
365
+ return msg
366
+ }
367
+
368
+ // Retry a failed message now.
369
+ retry(localMessageId: string): void {
370
+ let item = this.queue.find((q) => q.localId === localMessageId)
371
+ if (!item) {
372
+ const m = Object.values(this.state.messages).flat().find((x) => x.localId === localMessageId && x.pending === 'failed')
373
+ if (!m) return
374
+ const atts = attachmentsOf(m).filter((a) => a.uri).map((a) => ({ uri: a.uri!, type: a.type, width: a.width ?? undefined, height: a.height ?? undefined }))
375
+ item = { localId: localMessageId, conversationId: m.conversationId, body: m.body, createdAt: m.createdAt, attempts: 0, ...(atts.length ? { attachments: atts } : {}) }
376
+ this.queue.push(item)
377
+ this.persist(K.queue, this.queue)
378
+ }
379
+ item.attempts = 0
380
+ this.markPending(item, 'sending')
381
+ this.scheduleFlush(0)
382
+ }
383
+
384
+ get pendingCount(): number {
385
+ return this.queue.length
386
+ }
387
+
388
+ // Deliver queued messages in order. Network errors and 5xx keep them queued with backoff; a 4xx fails the message.
389
+ flush(): Promise<void> {
390
+ this.flushing ??= (async () => {
391
+ try {
392
+ await this.load()
393
+ if (!this.session) return
394
+ while (this.queue.length && !this.stopped) {
395
+ const item = this.queue[0]
396
+ try {
397
+ await this.deliver(item)
398
+ this.queue.shift()
399
+ this.persist(K.queue, this.queue)
400
+ } catch (e) {
401
+ const status = e instanceof HttpError ? e.status : 0
402
+ if (status === 401) {
403
+ this.session = null
404
+ this.identify().catch(() => {})
405
+ return
406
+ }
407
+ if (status >= 400 && status < 500) {
408
+ this.queue.shift()
409
+ this.persist(K.queue, this.queue)
410
+ this.markPending(item, 'failed')
411
+ continue
412
+ }
413
+ item.attempts++
414
+ this.persist(K.queue, this.queue)
415
+ if (item.attempts >= AUTO_RETRIES) this.markPending(item, 'failed')
416
+ this.set({ status: this.ws ? this.state.status : 'offline', error: (e as Error).message })
417
+ this.scheduleFlush(Math.min(30_000, 500 * 2 ** item.attempts))
418
+ return
419
+ }
420
+ }
421
+ } finally {
422
+ this.flushing = null
423
+ }
424
+ })()
425
+ return this.flushing
426
+ }
427
+
428
+ private scheduleFlush(ms: number): void {
429
+ if (this.flushTimer) clearTimeout(this.flushTimer)
430
+ this.flushTimer = setTimeout(() => {
431
+ this.flushTimer = null
432
+ this.flush().catch(() => {})
433
+ }, ms)
434
+ }
435
+
436
+ // Uploads each picked image once (the result is kept on the queue item, so a retry does not upload again).
437
+ private async upload(item: QueueItem): Promise<Attachment[]> {
438
+ const out: Attachment[] = []
439
+ for (const a of item.attachments ?? []) {
440
+ if (!a.remote) {
441
+ const form = new FormData()
442
+ const type = a.type ?? 'image/jpeg'
443
+ const name = a.name ?? 'image.' + (type.split('/')[1] ?? 'jpg')
444
+ if (isReactNative()) form.append('file', { uri: a.uri, type, name } as unknown as Blob)
445
+ else form.append('file', new Blob([await (await fetch(a.uri)).arrayBuffer()], { type }), name)
446
+ if (a.width) form.append('width', String(a.width))
447
+ if (a.height) form.append('height', String(a.height))
448
+ a.remote = (await this.request<{ attachment: Attachment }>('POST', '/support/v1/attachments', form)).attachment
449
+ this.persist(K.queue, this.queue)
450
+ }
451
+ out.push(a.remote)
452
+ }
453
+ return out
454
+ }
455
+
456
+ // A server path (attachment) as a full URL.
457
+ url(path: string): string {
458
+ return /^[a-z]+:/i.test(path) ? path : this.config.serverUrl + path
459
+ }
460
+
461
+ // "Talk to a person": the conversation goes to the founder's Needs-human list and the AI stops answering it.
462
+ async handoff(conversationId: string): Promise<void> {
463
+ if (conversationId.startsWith(LOCAL_CONV)) return
464
+ const r = await this.request<{ conversation: Conversation }>('POST', '/support/v1/conversations/' + conversationId + '/handoff', {})
465
+ this.upsertConversation(r.conversation)
466
+ this.loadMessages(conversationId).catch(() => {})
467
+ }
468
+
469
+ private setTyping(conversationId: string, who: Typing | null, ttl = 0): void {
470
+ const t = this.typingTimers.get(conversationId)
471
+ if (t) clearTimeout(t)
472
+ this.typingTimers.delete(conversationId)
473
+ const typing = { ...this.state.typing }
474
+ if (who && ttl > 0) {
475
+ typing[conversationId] = who
476
+ this.typingTimers.set(conversationId, setTimeout(() => this.setTyping(conversationId, null), ttl))
477
+ } else {
478
+ if (!typing[conversationId]) return
479
+ delete typing[conversationId]
480
+ }
481
+ this.set({ typing })
482
+ }
483
+
484
+ private async deliver(item: QueueItem): Promise<void> {
485
+ const meta: Record<string, unknown> = { localId: item.localId }
486
+ if (item.attachments?.length) meta['attachments'] = (await this.upload(item)).map((a) => ({ id: a.id }))
487
+ if (item.conversationId.startsWith(LOCAL_CONV)) {
488
+ const r = await this.request<{ conversation: Conversation; message: Message }>('POST', '/support/v1/conversations', { body: item.body, meta })
489
+ this.remapConversation(item.conversationId, r.conversation)
490
+ this.mergeMessages(r.conversation.id, [r.message])
491
+ return
492
+ }
493
+ const r = await this.request<{ message: Message }>('POST', '/support/v1/conversations/' + item.conversationId + '/messages', { body: item.body, meta })
494
+ this.mergeMessages(item.conversationId, [r.message])
495
+ }
496
+
497
+ private remapConversation(from: string, conv: Conversation): void {
498
+ for (const q of this.queue) if (q.conversationId === from) q.conversationId = conv.id
499
+ this.persist(K.queue, this.queue)
500
+ const messages = { ...this.state.messages }
501
+ messages[conv.id] = (messages[from] ?? []).map((m) => ({ ...m, conversationId: conv.id }))
502
+ delete messages[from]
503
+ this.full.add(conv.id)
504
+ this.readAt[conv.id] = conv.lastMessageAt
505
+ const conversations = this.state.conversations.filter((c) => c.id !== from && c.id !== conv.id)
506
+ this.set({ messages, conversations: this.sortConvs([conv, ...conversations]), activeConversationId: this.state.activeConversationId === from ? conv.id : this.state.activeConversationId })
507
+ }
508
+
509
+ private optimistic(q: QueueItem, pending: 'sending' | 'failed'): Message {
510
+ const meta = q.attachments?.length ? { attachments: q.attachments.map((a) => ({ uri: a.uri, width: a.width ?? null, height: a.height ?? null, type: a.type ?? 'image/jpeg' })) } : null
511
+ return { id: q.localId, localId: q.localId, conversationId: q.conversationId, author: 'user', body: q.body, createdAt: q.createdAt, pending, meta }
512
+ }
513
+
514
+ private markPending(item: QueueItem, pending: 'sending' | 'failed'): void {
515
+ const list = this.state.messages[item.conversationId] ?? []
516
+ this.set({ messages: { ...this.state.messages, [item.conversationId]: list.map((m) => (m.localId === item.localId ? { ...m, pending } : m)) } })
517
+ }
518
+
519
+ private withLocalConversations(server: Conversation[], messages = this.state.messages): Conversation[] {
520
+ const local = Object.keys(messages)
521
+ .filter((id) => id.startsWith(LOCAL_CONV) && !server.some((c) => c.id === id))
522
+ .map((id): Conversation => {
523
+ const msgs = messages[id]
524
+ const last = msgs[msgs.length - 1]
525
+ return { id, status: 'open', subject: msgs[0]?.body.slice(0, 80) ?? null, lastMessageAt: last?.createdAt ?? Date.now(), lastPreview: last?.body ?? null, lastAuthor: 'user', createdAt: msgs[0]?.createdAt ?? Date.now() }
526
+ })
527
+ return this.sortConvs([...local, ...server])
528
+ }
529
+
530
+ private sortConvs(list: Conversation[]): Conversation[] {
531
+ return [...list].sort((a, b) => b.lastMessageAt - a.lastMessageAt)
532
+ }
533
+
534
+ private mergeMessages(conversationId: string, incoming: Message[]): void {
535
+ if (!incoming.length) return
536
+ const list = [...(this.state.messages[conversationId] ?? [])]
537
+ for (const m of incoming) {
538
+ const lid = typeof m.meta?.['localId'] === 'string' ? (m.meta['localId'] as string) : null
539
+ const at = list.findIndex((x) => x.id === m.id || (lid !== null && x.localId === lid))
540
+ const msg: Message = { ...m, ...(lid ? { localId: lid } : {}) }
541
+ const local = at >= 0 ? attachmentsOf(list[at]) : []
542
+ if (local.some((a) => a.uri)) msg.meta = { ...msg.meta, attachments: attachmentsOf(msg).map((a, i) => ({ ...a, uri: local[i]?.uri })) }
543
+ if (at >= 0) list[at] = msg
544
+ else list.push(msg)
545
+ }
546
+ list.sort((a, b) => a.createdAt - b.createdAt)
547
+ this.set({ messages: { ...this.state.messages, [conversationId]: list } })
548
+ }
549
+
550
+ private upsertConversation(conv: Conversation): void {
551
+ this.set({ conversations: this.sortConvs([conv, ...this.state.conversations.filter((c) => c.id !== conv.id)]) })
552
+ }
553
+
554
+ // Catch up after a reconnect or when the app comes to the foreground.
555
+ async pull(): Promise<void> {
556
+ if (!this.session) return
557
+ const r = await this.request<{ conversations: Conversation[] }>('GET', '/support/v1/conversations')
558
+ this.set({ conversations: this.withLocalConversations(r.conversations) })
559
+ const ids = new Set(Object.keys(this.state.messages).filter((id) => !id.startsWith(LOCAL_CONV)))
560
+ if (this.state.activeConversationId && !this.state.activeConversationId.startsWith(LOCAL_CONV)) ids.add(this.state.activeConversationId)
561
+ await Promise.all([...ids].map((id) => this.loadMessages(id).catch(() => [])))
562
+ }
563
+
564
+ // App came back to the foreground: reconnect now, deliver the queue and fetch what was missed.
565
+ foreground(): void {
566
+ if (this.stopped || !this.session) {
567
+ if (!this.stopped && this.state.status !== 'identifying') this.identify().catch(() => {})
568
+ return
569
+ }
570
+ if (!this.ws) this.connect(true)
571
+ else this.pull().catch(() => {})
572
+ this.scheduleFlush(0)
573
+ }
574
+
575
+ private connect(resetBackoff = false): void {
576
+ if (this.stopped || !this.session) return
577
+ if (resetBackoff) this.backoffStep = 0
578
+ if (this.reconnectTimer) clearTimeout(this.reconnectTimer)
579
+ this.reconnectTimer = null
580
+ const old = this.ws
581
+ this.ws = null
582
+ old?.close()
583
+ const url = this.config.serverUrl.replace(/^http/, 'ws') + '/support/v1/stream?key=' + encodeURIComponent(this.config.appKey) + '&user=' + encodeURIComponent(this.session.userToken)
584
+ let ws: WebSocket
585
+ try {
586
+ ws = new WebSocket(url)
587
+ } catch (e) {
588
+ this.set({ status: 'offline', error: (e as Error).message })
589
+ return this.scheduleReconnect()
590
+ }
591
+ this.ws = ws
592
+ if (this.state.status !== 'live') this.set({ status: 'connecting' })
593
+ ws.onmessage = (ev) => {
594
+ if (this.ws !== ws || ev.data === 'pong') return
595
+ let m: { t: string; message?: Message; conversation?: Conversation; conversationId?: string; who?: Typing; ttl?: number }
596
+ try {
597
+ m = JSON.parse(String(ev.data))
598
+ } catch {
599
+ return
600
+ }
601
+ if (m.t === 'ready') {
602
+ this.backoffStep = 0
603
+ this.set({ status: 'live', error: null })
604
+ if (this.ping) clearInterval(this.ping)
605
+ this.ping = setInterval(() => ws.readyState === 1 && ws.send('ping'), 25_000)
606
+ this.pull().catch(() => {})
607
+ this.scheduleFlush(0)
608
+ } else if (m.t === 'typing' && m.conversationId) {
609
+ this.setTyping(m.conversationId, m.who ?? 'founder', m.ttl ?? 0)
610
+ } else if (m.t === 'message' && m.message) {
611
+ if (m.message.author !== 'user') this.setTyping(m.message.conversationId, null)
612
+ this.mergeMessages(m.message.conversationId, [m.message])
613
+ const conv = this.state.conversations.find((c) => c.id === m.message!.conversationId)
614
+ if (conv) this.upsertConversation({ ...conv, lastMessageAt: Math.max(conv.lastMessageAt, m.message.createdAt), lastPreview: m.message.body.slice(0, 140), lastAuthor: m.message.author })
615
+ if (this.state.open && this.state.activeConversationId === m.message.conversationId) this.markRead(m.message.conversationId)
616
+ } else if (m.t === 'conversation' && m.conversation) {
617
+ this.upsertConversation(m.conversation)
618
+ }
619
+ }
620
+ ws.onclose = (ev) => {
621
+ if (this.ws !== ws) return
622
+ this.ws = null
623
+ if (this.ping) clearInterval(this.ping)
624
+ this.ping = null
625
+ if (this.stopped) return
626
+ if (ev.code === 4003) {
627
+ this.session = null
628
+ this.set({ status: 'error', error: 'unauthorized' })
629
+ return void this.identify().catch(() => {})
630
+ }
631
+ this.set({ status: 'offline' })
632
+ this.scheduleReconnect()
633
+ }
634
+ ws.onerror = () => {
635
+ if (this.ws === ws) this.set({ error: 'cannot reach ' + this.config.serverUrl })
636
+ }
637
+ }
638
+
639
+ private scheduleReconnect(): void {
640
+ if (this.stopped || this.reconnectTimer) return
641
+ const delay = Math.min(30_000, 500 * 2 ** this.backoffStep++) * (0.8 + Math.random() * 0.4)
642
+ this.reconnectTimer = setTimeout(() => {
643
+ this.reconnectTimer = null
644
+ if (this.session) this.connect()
645
+ else this.identify().catch(() => {})
646
+ }, delay)
647
+ }
648
+
649
+ get reconnectAttempts(): number {
650
+ return this.backoffStep
651
+ }
652
+
653
+ // Drop the live socket without stopping (tests, and the app going to the background).
654
+ disconnect(): void {
655
+ const ws = this.ws
656
+ this.ws = null
657
+ if (this.ping) clearInterval(this.ping)
658
+ this.ping = null
659
+ ws?.close()
660
+ if (!this.stopped) this.set({ status: 'offline' })
661
+ }
662
+
663
+ stop(): void {
664
+ this.stopped = true
665
+ for (const t of [this.reconnectTimer, this.flushTimer, ...this.typingTimers.values()]) if (t) clearTimeout(t)
666
+ this.typingTimers.clear()
667
+ this.reconnectTimer = this.flushTimer = null
668
+ this.disconnect()
669
+ this.set({ status: 'idle' })
670
+ }
671
+
672
+ // Sign-out: forget the identified user and start over as a new anonymous user.
673
+ async reset(): Promise<void> {
674
+ await this.load()
675
+ this.disconnect()
676
+ this.session = null
677
+ this.user = {}
678
+ this.queue = []
679
+ this.readAt = {}
680
+ this.full.clear()
681
+ 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: {} })
684
+ }
685
+ }