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