@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.
@@ -0,0 +1,413 @@
1
+ // React Native glue for Shotik analytics: automatic capture with no native code. Taps come from one capture-phase
2
+ // touch listener on a root View (element identity from the React fiber of the touched view), screens from React
3
+ // Navigation / Expo Router state, app open and close from AppState, crashes from the global error handler, stalls
4
+ // from a 500 ms timer's drift, purchases from RevenueCat, and wireframes from the host tree's DOM API.
5
+ // Every handler is O(depth) and allocation-light; uploads happen off the touch path.
6
+ import { Component, createElement, useEffect } from 'react';
7
+ import { AppState, Dimensions, Linking, Platform, StyleSheet, View } from 'react-native';
8
+ import { Analytics } from './core';
9
+ let client = null;
10
+ const off = [];
11
+ const opt = (load) => {
12
+ try {
13
+ return load();
14
+ }
15
+ catch {
16
+ return null;
17
+ }
18
+ };
19
+ // Optional native modules: Metro only treats a require() as optional when it sits directly inside a try block.
20
+ function storage() {
21
+ let a = null;
22
+ try {
23
+ const m = require('@react-native-async-storage/async-storage');
24
+ a = m?.default ?? m;
25
+ }
26
+ catch { }
27
+ if (a?.getItem)
28
+ return { get: (k) => a.getItem(k), set: (k, v) => a.setItem(k, v), remove: (k) => a.removeItem(k) };
29
+ let mm = null;
30
+ try {
31
+ const m = require('react-native-mmkv');
32
+ mm = m.createMMKV ? m.createMMKV({ id: 'shotik' }) : new m.MMKV({ id: 'shotik' });
33
+ }
34
+ catch { }
35
+ if (mm?.getString)
36
+ return { get: async (k) => mm.getString(k) ?? null, set: async (k, v) => mm.set(k, v), remove: async (k) => void (mm.remove ?? mm.delete).call(mm, k) };
37
+ // The keychain is a last resort: small values only, and it throws in unsigned simulator builds (reported as store: 'error').
38
+ let s = null;
39
+ try {
40
+ s = require('expo-secure-store');
41
+ }
42
+ catch { }
43
+ if (s?.getItemAsync)
44
+ return { get: (k) => s.getItemAsync(k), set: (k, v) => s.setItemAsync(k, v), remove: (k) => s.deleteItemAsync(k) };
45
+ return undefined;
46
+ }
47
+ function device() {
48
+ let d = null;
49
+ let a = null;
50
+ try {
51
+ d = require('expo-device');
52
+ }
53
+ catch { }
54
+ try {
55
+ a = require('expo-application');
56
+ }
57
+ catch { }
58
+ const o = Intl.DateTimeFormat().resolvedOptions();
59
+ const { width, height } = Dimensions.get('window');
60
+ return { platform: Platform.OS, os: d?.osVersion ?? String(Platform.Version), model: d?.modelName ?? undefined, app: a?.nativeApplicationVersion ?? undefined, build: a?.nativeBuildVersion ?? undefined, locale: o.locale, tz: o.timeZone, w: Math.round(width), h: Math.round(height) };
61
+ }
62
+ // Fiber helpers
63
+ const nameOf = (t) => {
64
+ if (!t || typeof t === 'string')
65
+ return null;
66
+ const o = t;
67
+ return o.displayName || o.name || o.render?.displayName || o.render?.name || (o.type ? nameOf(o.type) : null);
68
+ };
69
+ const GENERIC = /^(View|Text|Image|Animated.*|AnimatedComponent.*|Pressable|Touchable.*|TouchableOpacity|Fragment|Memo|ForwardRef|Unknown|ScrollView|SafeAreaView|.{0,2}|.*Provider|.*Context|Screen.*|Navigation.*|Stack.*|Route.*|ShotikMask|ShotikAnalyticsRoot)$/;
70
+ const PRESS = /Button|Touchable|Pressable|Link|Gesture|Swipeable/;
71
+ const INPUT = /TextInput/;
72
+ const handles = (p) => !!(p.onPress || p.onPressIn || p.onLongPress || p.onClick || p.onResponderRelease || p.onValueChange || p.accessibilityRole === 'button' || p.role === 'button' || p.accessibilityRole === 'link');
73
+ function textUnder(f, max = 40) {
74
+ const out = [];
75
+ let n = 0;
76
+ const walk = (x) => {
77
+ while (x && n++ < 60 && out.join(' ').length < max) {
78
+ if (x.tag === 6 && typeof x.memoizedProps === 'string')
79
+ out.push(x.memoizedProps);
80
+ else if (typeof x.memoizedProps === 'object' && x.memoizedProps && typeof x.memoizedProps.children === 'string' && x.type === 'RCTText')
81
+ out.push(x.memoizedProps.children);
82
+ walk(x.child);
83
+ x = x.sibling;
84
+ }
85
+ };
86
+ walk(f?.child ?? null);
87
+ return out.join(' ').replace(/\s+/g, ' ').trim().slice(0, max);
88
+ }
89
+ const hash = (s) => {
90
+ let h = 0x811c9dc5;
91
+ for (let i = 0; i < s.length; i++)
92
+ h = Math.imul(h ^ s.charCodeAt(i), 0x01000193);
93
+ return (h >>> 0).toString(36);
94
+ };
95
+ const scrub = (s) => s.replace(/[^\s@]+@[^\s@]+/g, '[email]').replace(/\d/g, '#');
96
+ // id: testID, else nativeID, else a hash of the fiber index path from the pressable up (list rows collapse to one id).
97
+ // It ignores labels and component names, so it survives locale switches and minified release builds.
98
+ export function describeTarget(target) {
99
+ let f = target;
100
+ let handler = null;
101
+ let tid;
102
+ let a11y;
103
+ let nid;
104
+ let path = [];
105
+ let masked = false;
106
+ let input = false;
107
+ let scroll = null;
108
+ const names = [];
109
+ for (let d = 0; f && d < 80; d++, f = f.return) {
110
+ const p = (typeof f.memoizedProps === 'object' && f.memoizedProps) || {};
111
+ const name = nameOf(f.type);
112
+ if (f.type === ShotikMask || p.shotikMask)
113
+ masked = true;
114
+ if ((name && INPUT.test(name)) || (typeof f.type === 'string' && /TextInput/.test(f.type)))
115
+ input = true;
116
+ if (!scroll && f.stateNode?._scrollMetrics)
117
+ scroll = f;
118
+ if (!handler && (handles(p) || (name && PRESS.test(name))))
119
+ (handler = f), (path = []);
120
+ path.push('cellKey' in p && 'item' in p ? '*' : f.index);
121
+ if (!handler || handler === f) {
122
+ if (!tid && typeof p.testID === 'string' && !p.testID.startsWith('shotik-mask'))
123
+ tid = p.testID;
124
+ if (!nid && typeof p.nativeID === 'string' && p.nativeID !== 'shotik-mask')
125
+ nid = p.nativeID;
126
+ if (!a11y && typeof (p.accessibilityLabel ?? p['aria-label']) === 'string')
127
+ a11y = String(p.accessibilityLabel ?? p['aria-label']);
128
+ }
129
+ if (handler && name && names.length < 2 && !GENERIC.test(name))
130
+ names.push(name);
131
+ }
132
+ const raw = masked || input ? '' : a11y || textUnder(handler ?? target);
133
+ const label = raw ? scrub(raw) : undefined;
134
+ const el = (names.reverse().join('>') || (handler ? nameOf(handler.type) || 'Pressable' : 'View')) + (tid ? '#' + tid : '');
135
+ return { el: input ? 'TextInput' : el, id: tid ?? nid ?? 'h' + hash(path.join('.')), label, dead: !handler && !input, input, scroll };
136
+ }
137
+ function wireframe(root) {
138
+ if (!root?.getBoundingClientRect || !root.children)
139
+ return null;
140
+ const out = [];
141
+ const { width: W, height: H } = Dimensions.get('window');
142
+ const visit = (el) => {
143
+ if (out.length >= 450)
144
+ return;
145
+ const r = el.getBoundingClientRect?.();
146
+ if (!r || r.width < 2 || r.height < 2 || r.y > H || r.y + r.height < 0 || r.x > W || r.x + r.width < 0)
147
+ return;
148
+ const fib = el.__internalInstanceHandle;
149
+ const p = (fib && typeof fib.memoizedProps === 'object' && fib.memoizedProps) || {};
150
+ const st = (StyleSheet.flatten(p.style) ?? {});
151
+ const tag = el.tagName ?? '';
152
+ const box = (k, fill, rad) => [k, Math.round(r.x), Math.round(r.y), Math.round(r.width), Math.round(r.height), typeof fill === 'string' ? fill : undefined, typeof rad === 'number' ? rad : undefined];
153
+ if (p.nativeID === 'shotik-mask')
154
+ return void out.push(box('m'));
155
+ if (/Text$/.test(tag) && !/Input/.test(tag))
156
+ return void out.push(box('t', st.color));
157
+ if (/Input/.test(tag))
158
+ return void out.push(box('n', st.backgroundColor, st.borderRadius));
159
+ if (/Image/.test(tag))
160
+ return void out.push(box('i', undefined, st.borderRadius));
161
+ const kind = handles(p) ? 'b' : /Scroll/.test(tag) ? 's' : 'v';
162
+ if (kind !== 'v' || st.backgroundColor || st.borderWidth)
163
+ out.push(box(kind, st.backgroundColor ?? st.borderColor, st.borderRadius));
164
+ const kids = el.children;
165
+ if (kids)
166
+ for (let i = 0; i < kids.length; i++)
167
+ visit(kids[i]);
168
+ };
169
+ visit(root);
170
+ return out;
171
+ }
172
+ export class ShotikAnalyticsRoot extends Component {
173
+ constructor() {
174
+ super(...arguments);
175
+ this.root = null;
176
+ this.start = null;
177
+ this.snapTimer = null;
178
+ this.unsub = null;
179
+ this.onStart = (e) => {
180
+ const t = e.nativeEvent.touches?.length ?? 1;
181
+ if (t > 1)
182
+ return void (this.start = null);
183
+ this.start = { x: e.nativeEvent.pageX, y: e.nativeEvent.pageY, t: Date.now(), dy: 0 };
184
+ };
185
+ this.onEnd = (e) => {
186
+ const s = this.start;
187
+ this.start = null;
188
+ if (!client || !s)
189
+ return;
190
+ const { pageX: x, pageY: y } = e.nativeEvent;
191
+ const moved = Math.hypot(x - s.x, y - s.y);
192
+ const target = (e._targetInst ?? e.target?.__internalInstanceHandle ?? null);
193
+ if (moved > 12) {
194
+ const sc = target && describeTarget(target).scroll;
195
+ const m = sc?.stateNode?._scrollMetrics;
196
+ client.scroll(m && m.contentLength > 0 ? (m.offset + m.visibleLength) / m.contentLength : null, y - s.y);
197
+ return;
198
+ }
199
+ if (Date.now() - s.t > 1500)
200
+ return;
201
+ const d = describeTarget(target);
202
+ const { width, height } = Dimensions.get('window');
203
+ const tap = { el: d.el, id: d.id, label: d.label, x, y, nx: Math.round((x / width) * 1000), ny: Math.round((y / height) * 1000), input: d.input, ts: Date.now() };
204
+ if (!d.dead)
205
+ return client.tap(tap);
206
+ // Dead-tap candidate: nothing handles presses here. Confirm that the screen didn't change within a second.
207
+ const screen = client.currentScreen;
208
+ setTimeout(() => client?.tap({ ...tap, dead: client.currentScreen === screen }), 1000);
209
+ };
210
+ }
211
+ componentDidMount() {
212
+ this.unsub = onScreen((s) => this.queueSnapshot(s));
213
+ }
214
+ componentWillUnmount() {
215
+ this.unsub?.();
216
+ if (this.snapTimer)
217
+ clearTimeout(this.snapTimer);
218
+ }
219
+ queueSnapshot(screen) {
220
+ if (!client?.wantsSnapshot(screen))
221
+ return;
222
+ if (this.snapTimer)
223
+ clearTimeout(this.snapTimer);
224
+ const idle = globalThis.requestIdleCallback ?? ((f) => setTimeout(f, 0));
225
+ this.snapTimer = setTimeout(() => {
226
+ idle(() => {
227
+ if (!client || client.currentScreen !== screen || !this.root)
228
+ return;
229
+ const nodes = opt(() => wireframe(this.root));
230
+ if (!nodes?.length)
231
+ return;
232
+ const { width, height } = Dimensions.get('window');
233
+ client.snapshot({ screen, w: Math.round(width), h: Math.round(height), nodes });
234
+ });
235
+ }, 900);
236
+ }
237
+ render() {
238
+ return createElement(View, {
239
+ style: { flex: 1 },
240
+ collapsable: false,
241
+ ref: (r) => void (this.root = r),
242
+ onTouchStartCapture: this.onStart,
243
+ onTouchEndCapture: this.onEnd
244
+ }, this.props.children);
245
+ }
246
+ }
247
+ // Hides what's inside from tap labels and wireframes (one grey block).
248
+ export function ShotikMask({ children, style }) {
249
+ return createElement(View, { nativeID: 'shotik-mask', style: style }, children);
250
+ }
251
+ // Screen listeners (wireframe trigger).
252
+ const screenSubs = new Set();
253
+ function onScreen(fn) {
254
+ screenSubs.add(fn);
255
+ return () => screenSubs.delete(fn);
256
+ }
257
+ function screen(name) {
258
+ if (!client || name === client.currentScreen)
259
+ return;
260
+ const t0 = Date.now();
261
+ client.screenView(name);
262
+ for (const fn of screenSubs)
263
+ fn(name);
264
+ requestAnimationFrame(() => requestAnimationFrame(() => client?.screenReady(Date.now() - t0)));
265
+ }
266
+ const routePath = (s) => {
267
+ const parts = [];
268
+ while (s?.routes?.length) {
269
+ const r = s.routes[s.index ?? s.routes.length - 1];
270
+ parts.push(r.name);
271
+ s = r.state;
272
+ }
273
+ return parts.filter((p) => p !== '__root').join('/');
274
+ };
275
+ function trackNavigation(ref) {
276
+ const now = () => {
277
+ const p = routePath(ref.getRootState?.());
278
+ if (p)
279
+ screen(p);
280
+ };
281
+ if (ref.isReady?.())
282
+ now();
283
+ const un = ref.addListener('state', (e) => {
284
+ const p = routePath(e.data?.state ?? ref.getRootState?.());
285
+ if (p)
286
+ screen(p);
287
+ });
288
+ off.push(un);
289
+ return un;
290
+ }
291
+ // Expo Router: call once in the root layout.
292
+ let expoRouter = null;
293
+ try {
294
+ expoRouter = require('expo-router');
295
+ }
296
+ catch { }
297
+ export function useShotikExpoRouter() {
298
+ const ref = expoRouter?.useNavigationContainerRef?.();
299
+ useEffect(() => (ref ? trackNavigation(ref) : undefined), [ref]);
300
+ }
301
+ export function useShotikScreen(name) {
302
+ useEffect(() => screen(name), [name]);
303
+ }
304
+ function trackRevenueCat(P) {
305
+ for (const m of ['purchasePackage', 'purchaseStoreProduct', 'purchaseProduct', 'purchaseSubscriptionOption']) {
306
+ const orig = P[m];
307
+ if (typeof orig !== 'function' || orig.__shotik)
308
+ continue;
309
+ const w = async (...a) => {
310
+ const it = a[0];
311
+ const prod = (typeof it === 'object' && (it.product ?? it)) || {};
312
+ const info = { product: String(prod.identifier ?? it ?? 'unknown'), price: prod.price, currency: prod.currencyCode, store: 'revenuecat', trial: !!prod.introPrice };
313
+ client?.purchase({ ...info, status: 'start' });
314
+ try {
315
+ const r = await orig.apply(P, a);
316
+ client?.purchase({ ...info, status: 'done' });
317
+ return r;
318
+ }
319
+ catch (e) {
320
+ client?.purchase({ ...info, status: e?.userCancelled ? 'cancel' : 'fail' });
321
+ throw e;
322
+ }
323
+ };
324
+ w.__shotik = 1;
325
+ P[m] = w;
326
+ }
327
+ }
328
+ function hookErrors() {
329
+ const EU = globalThis.ErrorUtils;
330
+ if (EU) {
331
+ const prev = EU.getGlobalHandler();
332
+ EU.setGlobalHandler((e, fatal) => {
333
+ client?.error(e, !!fatal);
334
+ prev(e, fatal);
335
+ });
336
+ }
337
+ const H = globalThis.HermesInternal;
338
+ if (!globalThis.__DEV__)
339
+ H?.enablePromiseRejectionTracker?.({ allRejections: true, onUnhandled: (_, r) => client?.error(r) });
340
+ }
341
+ function hookAppState() {
342
+ let state = AppState.currentState;
343
+ const sub = AppState.addEventListener('change', (next) => {
344
+ if (next === state)
345
+ return;
346
+ if (next === 'active') {
347
+ client?.foreground();
348
+ stalls(true);
349
+ }
350
+ else if (state === 'active') {
351
+ stalls(false);
352
+ client?.background();
353
+ }
354
+ state = next;
355
+ });
356
+ off.push(() => sub.remove());
357
+ }
358
+ let stallTimer = null;
359
+ function stalls(on) {
360
+ if (stallTimer)
361
+ clearInterval(stallTimer);
362
+ stallTimer = null;
363
+ if (!on)
364
+ return;
365
+ let last = Date.now();
366
+ stallTimer = setInterval(() => {
367
+ const now = Date.now();
368
+ const drift = now - last - 500;
369
+ last = now;
370
+ if (drift > 300 && drift < 60000)
371
+ client?.stall(drift);
372
+ }, 500);
373
+ }
374
+ export const ShotikAnalytics = {
375
+ init(cfg) {
376
+ if (client)
377
+ return client;
378
+ client = new Analytics({ ...cfg, storage: cfg.storage ?? storage(), device });
379
+ hookErrors();
380
+ hookAppState();
381
+ // Dev builds only: <scheme>://…?shotik-analytics=new-user starts a fresh install identity (test runs on one device).
382
+ if (globalThis.__DEV__) {
383
+ const sub = Linking.addEventListener('url', ({ url }) => {
384
+ if (url.includes('shotik-analytics=new-user'))
385
+ void client?.reset();
386
+ });
387
+ off.push(() => sub.remove());
388
+ }
389
+ client.foreground();
390
+ stalls(true);
391
+ return client;
392
+ },
393
+ get client() {
394
+ return client;
395
+ },
396
+ track: (name, props) => client?.track(name, props),
397
+ screen,
398
+ identify: (userId, traits) => client?.identify(userId, traits),
399
+ purchase: (p) => client?.purchase(p),
400
+ setConsent: (c) => client?.setConsent(c),
401
+ optOut: () => client?.optOut(),
402
+ optIn: () => client?.optIn(),
403
+ reset: () => client?.reset(),
404
+ flush: () => client?.flush(),
405
+ trackNavigation,
406
+ trackRevenueCat,
407
+ stop() {
408
+ stalls(false);
409
+ off.splice(0).forEach((f) => f());
410
+ client?.stop();
411
+ client = null;
412
+ }
413
+ };
@@ -0,0 +1,53 @@
1
+ export declare const WIRE_VERSION = 1;
2
+ export declare const TYPES: readonly ["session", "open", "close", "screen", "leave", "tap", "rage", "scroll", "error", "slow", "purchase", "custom", "identify", "snapshot"];
3
+ export type EventType = (typeof TYPES)[number];
4
+ export interface DeviceContext {
5
+ platform?: string;
6
+ os?: string;
7
+ model?: string;
8
+ app?: string;
9
+ build?: string;
10
+ locale?: string;
11
+ tz?: string;
12
+ w?: number;
13
+ h?: number;
14
+ }
15
+ export interface WireEvent {
16
+ seq: number;
17
+ ts: number;
18
+ type: EventType;
19
+ sessionId: string;
20
+ name?: string;
21
+ screen?: string;
22
+ props?: Record<string, unknown>;
23
+ }
24
+ export interface Batch {
25
+ anonymousId: string;
26
+ userId?: string | null;
27
+ firstSeen?: number;
28
+ device?: DeviceContext;
29
+ events: WireEvent[];
30
+ }
31
+ export type PackedEvent = [number, number, number, number, number, number, Record<string, unknown> | 0];
32
+ export interface PackedBatch {
33
+ v: 1;
34
+ a: string;
35
+ u?: string | null;
36
+ f?: number;
37
+ c?: DeviceContext;
38
+ t0: number;
39
+ d: string[];
40
+ e: PackedEvent[];
41
+ }
42
+ export declare function pack(b: Batch): PackedBatch;
43
+ export declare function unpack(p: PackedBatch): Batch;
44
+ export type WireNode = [string, number, number, number, number, string?, number?];
45
+ export interface Wireframe {
46
+ sessionId: string;
47
+ screen: string;
48
+ ts: number;
49
+ w: number;
50
+ h: number;
51
+ dark?: boolean;
52
+ nodes: WireNode[];
53
+ }
@@ -0,0 +1,56 @@
1
+ // Shotik analytics wire format, shared by the SDK and the server (imported there as wire.ts). No imports, no platform
2
+ // code. A batch is dictionary-packed: every repeated string (screen, element, event name, session id) is sent once per
3
+ // batch and referenced by index, timestamps are deltas, and props keep short keys. React Native has no gzip without
4
+ // native code, so this is the compression: about 6x smaller than plain JSON on tap-heavy batches.
5
+ export const WIRE_VERSION = 1;
6
+ // Event types. Codes are the array position, so append only.
7
+ export const TYPES = ['session', 'open', 'close', 'screen', 'leave', 'tap', 'rage', 'scroll', 'error', 'slow', 'purchase', 'custom', 'identify', 'snapshot'];
8
+ const PACKED_PROPS = ['el', 'label', 'from'];
9
+ export function pack(b) {
10
+ const d = [];
11
+ const ix = new Map();
12
+ const s = (v) => {
13
+ if (typeof v !== 'string')
14
+ return -1;
15
+ let i = ix.get(v);
16
+ if (i === undefined) {
17
+ i = d.length;
18
+ d.push(v);
19
+ ix.set(v, i);
20
+ }
21
+ return i;
22
+ };
23
+ const t0 = b.events.length ? b.events[0].ts : 0;
24
+ let prev = t0;
25
+ const e = b.events.map((ev) => {
26
+ const dt = ev.ts - prev;
27
+ prev = ev.ts;
28
+ let p = 0;
29
+ if (ev.props) {
30
+ p = {};
31
+ for (const k in ev.props) {
32
+ const v = ev.props[k];
33
+ if (v === undefined)
34
+ continue;
35
+ p[k] = PACKED_PROPS.includes(k) && typeof v === 'string' ? s(v) : v;
36
+ }
37
+ }
38
+ return [dt, TYPES.indexOf(ev.type), ev.seq, s(ev.sessionId), s(ev.screen), s(ev.name), p];
39
+ });
40
+ return { v: 1, a: b.anonymousId, u: b.userId ?? null, f: b.firstSeen, c: b.device, t0, d, e };
41
+ }
42
+ export function unpack(p) {
43
+ const str = (i) => (i >= 0 && i < p.d.length ? p.d[i] : undefined);
44
+ let ts = p.t0;
45
+ const events = p.e.map(([dt, type, seq, sess, screen, name, props]) => {
46
+ ts += dt;
47
+ let pr;
48
+ if (props) {
49
+ pr = {};
50
+ for (const k in props)
51
+ pr[k] = PACKED_PROPS.includes(k) && typeof props[k] === 'number' ? str(props[k]) : props[k];
52
+ }
53
+ return { seq, ts, type: TYPES[type] ?? 'custom', sessionId: str(sess) ?? '', screen: str(screen), name: str(name), props: pr };
54
+ });
55
+ return { anonymousId: p.a, userId: p.u ?? null, firstSeen: p.f, device: p.c, events };
56
+ }
@@ -0,0 +1,153 @@
1
+ export type Author = 'user' | 'ai' | 'founder' | 'system';
2
+ export type ConversationStatus = 'open' | 'needs_human' | 'resolved' | 'closed' | string;
3
+ export type Status = 'idle' | 'identifying' | 'connecting' | 'live' | 'offline' | 'error';
4
+ export interface Conversation {
5
+ id: string;
6
+ status: ConversationStatus;
7
+ subject: string | null;
8
+ lastMessageAt: number;
9
+ lastPreview: string | null;
10
+ lastAuthor: Author | null;
11
+ createdAt: number;
12
+ founderUnread?: number;
13
+ }
14
+ export interface LocalAttachment {
15
+ uri: string;
16
+ type?: string;
17
+ name?: string;
18
+ width?: number;
19
+ height?: number;
20
+ }
21
+ export interface Attachment {
22
+ id: string;
23
+ type: string;
24
+ size: number;
25
+ width: number | null;
26
+ height: number | null;
27
+ path: string;
28
+ }
29
+ export type Receipt = 'sending' | 'queued' | 'failed' | 'sent' | 'delivered' | 'seen';
30
+ export type Typing = 'ai' | 'founder';
31
+ export interface Message {
32
+ id: string;
33
+ conversationId: string;
34
+ author: Author;
35
+ body: string;
36
+ createdAt: number;
37
+ meta?: Record<string, unknown> | null;
38
+ deliveredAt?: number | null;
39
+ localId?: string;
40
+ pending?: 'sending' | 'failed';
41
+ }
42
+ export interface UserInfo {
43
+ userId?: string;
44
+ name?: string;
45
+ email?: string;
46
+ attributes?: Record<string, unknown>;
47
+ }
48
+ export interface DeviceInfo {
49
+ platform?: string;
50
+ osVersion?: string;
51
+ model?: string;
52
+ appVersion?: string;
53
+ build?: string;
54
+ locale?: string;
55
+ timezone?: string;
56
+ }
57
+ export interface KeyValueStorage {
58
+ get(key: string): Promise<string | null>;
59
+ set(key: string, value: string): Promise<void>;
60
+ remove(key: string): Promise<void>;
61
+ }
62
+ export interface SupportConfig {
63
+ appKey: string;
64
+ serverUrl: string;
65
+ storage?: KeyValueStorage;
66
+ device?: () => DeviceInfo | Promise<DeviceInfo>;
67
+ }
68
+ export interface SupportState {
69
+ status: Status;
70
+ userId: string | null;
71
+ conversations: Conversation[];
72
+ messages: Record<string, Message[]>;
73
+ unread: number;
74
+ unreadBy: Record<string, number>;
75
+ open: boolean;
76
+ activeConversationId: string | null;
77
+ error: string | null;
78
+ typing: Record<string, Typing>;
79
+ }
80
+ export declare function receiptOf(m: Message, list: Message[], conv: Conversation | undefined, offline?: boolean): Receipt | null;
81
+ export declare const attachmentsOf: (m: Message) => (Partial<Attachment> & {
82
+ uri?: string;
83
+ })[];
84
+ export declare class HttpError extends Error {
85
+ status: number;
86
+ constructor(status: number, message: string);
87
+ }
88
+ export declare function memoryStorage(): KeyValueStorage;
89
+ export declare class SupportClient {
90
+ readonly config: SupportConfig;
91
+ private storage;
92
+ private listeners;
93
+ private state;
94
+ private typingTimers;
95
+ private session;
96
+ private anonId;
97
+ private user;
98
+ private queue;
99
+ private readAt;
100
+ private pushToken;
101
+ private ws;
102
+ private backoffStep;
103
+ private reconnectTimer;
104
+ private flushTimer;
105
+ private ping;
106
+ private flushing;
107
+ private identifying;
108
+ private loaded;
109
+ private full;
110
+ private stopped;
111
+ constructor(config: SupportConfig);
112
+ getState: () => SupportState;
113
+ subscribe: (fn: (s: SupportState) => void) => (() => void);
114
+ private set;
115
+ private countUnread;
116
+ private load;
117
+ private persist;
118
+ request<T>(method: 'GET' | 'POST', path: string, body?: unknown): Promise<T>;
119
+ identify(user?: UserInfo): Promise<void>;
120
+ ensureIdentified(): Promise<void>;
121
+ setPushToken(token: string | null, platform?: string): Promise<void>;
122
+ private sendPushToken;
123
+ open(conversationId?: string | null): void;
124
+ close(): void;
125
+ select(conversationId: string | null): void;
126
+ markRead(conversationId: string): void;
127
+ loadMessages(conversationId: string): Promise<Message[]>;
128
+ send(body: string, conversationId?: string | null, attachments?: LocalAttachment[]): Message | null;
129
+ retry(localMessageId: string): void;
130
+ get pendingCount(): number;
131
+ flush(): Promise<void>;
132
+ private scheduleFlush;
133
+ private upload;
134
+ url(path: string): string;
135
+ handoff(conversationId: string): Promise<void>;
136
+ private setTyping;
137
+ private deliver;
138
+ private remapConversation;
139
+ private optimistic;
140
+ private markPending;
141
+ private withLocalConversations;
142
+ private sortConvs;
143
+ private mergeMessages;
144
+ private upsertConversation;
145
+ pull(): Promise<void>;
146
+ foreground(): void;
147
+ private connect;
148
+ private scheduleReconnect;
149
+ get reconnectAttempts(): number;
150
+ disconnect(): void;
151
+ stop(): void;
152
+ reset(): Promise<void>;
153
+ }