@figoailabs/figochat-react-native 0.0.0-stage → 1.0.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,417 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.FigoChatView = FigoChatView;
37
+ const jsx_runtime_1 = require("react/jsx-runtime");
38
+ const react_1 = require("react");
39
+ const react_native_1 = require("react-native");
40
+ const DocumentPicker = __importStar(require("expo-document-picker"));
41
+ const expo_audio_1 = require("expo-audio");
42
+ const FigoChat_1 = require("./FigoChat");
43
+ const client_1 = require("./client");
44
+ const realtime_1 = require("./realtime");
45
+ const colors_1 = require("./colors");
46
+ const icons_1 = require("./icons");
47
+ const messages_1 = require("./messages");
48
+ let idCounter = 0;
49
+ const newId = () => `${Date.now().toString(36)}-${(idCounter++).toString(36)}`;
50
+ const IMAGE_EXT = /\.(png|jpe?g|gif|webp|bmp|heic|heif)(\?|$)/i;
51
+ function FigoChatView({ onClose, showHeader = true, placeholder = 'Type a message', enableVoice = true, enableAttachments = true, keyboardVerticalOffset = 0, icons = {}, onError, style, }) {
52
+ const initialized = (0, react_1.useSyncExternalStore)(FigoChat_1.FigoChat.subscribe, FigoChat_1.FigoChat.isInitialized, FigoChat_1.FigoChat.isInitialized);
53
+ if (!initialized) {
54
+ return ((0, jsx_runtime_1.jsx)(react_native_1.View, { style: [styles.center, style], children: (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: styles.muted, children: "FigoChat is not initialized. Call FigoChat.initialize(...) first." }) }));
55
+ }
56
+ return ((0, jsx_runtime_1.jsx)(ChatScreen, { onClose: onClose, showHeader: showHeader, placeholder: placeholder, enableVoice: enableVoice, enableAttachments: enableAttachments, keyboardVerticalOffset: keyboardVerticalOffset, icons: icons, onError: onError, style: style }));
57
+ }
58
+ function ChatScreen(props) {
59
+ const config = FigoChat_1.FigoChat.getConfig();
60
+ const client = FigoChat_1.FigoChat.getClient();
61
+ const primary = config.primaryColor;
62
+ const onPrimary = (0, colors_1.contrastText)(primary);
63
+ const maxFiles = config.maxFiles ?? 5;
64
+ const maxBytes = (config.maxFileSizeMB ?? 10) * 1024 * 1024;
65
+ const welcome = (0, react_1.useMemo)(() => (config.welcomeMessage ? [{ id: 'welcome', role: 'assistant', text: config.welcomeMessage, createdAt: new Date() }] : []), [config.welcomeMessage]);
66
+ const [messages, setMessages] = (0, react_1.useState)(welcome);
67
+ const [input, setInput] = (0, react_1.useState)('');
68
+ const [pending, setPending] = (0, react_1.useState)([]);
69
+ const [waiting, setWaiting] = (0, react_1.useState)(false);
70
+ const [transcribing, setTranscribing] = (0, react_1.useState)(false);
71
+ const [threadId, setThreadId] = (0, react_1.useState)(() => FigoChat_1.FigoChat.getThreadId());
72
+ const mounted = (0, react_1.useRef)(true);
73
+ // set back to true on every (re)run: React re-runs effects in Strict Mode and on Fast Refresh, and a flag
74
+ // left false would make the view ignore every reply and keyboard event from then on
75
+ (0, react_1.useEffect)(() => {
76
+ mounted.current = true;
77
+ return () => {
78
+ mounted.current = false;
79
+ };
80
+ }, []);
81
+ const recorder = (0, expo_audio_1.useAudioRecorder)(expo_audio_1.RecordingPresets.HIGH_QUALITY);
82
+ const recorderState = (0, expo_audio_1.useAudioRecorderState)(recorder, 250);
83
+ const recording = recorderState.isRecording;
84
+ // kept in a ref so an inline onError prop doesn't re-create callbacks (and re-subscribe) on every render
85
+ const onErrorRef = (0, react_1.useRef)(props.onError);
86
+ onErrorRef.current = props.onError;
87
+ const reportError = (0, react_1.useCallback)((e) => {
88
+ const err = e instanceof client_1.FigoChatError ? e : new client_1.FigoChatError(String(e?.message ?? e), 'UNKNOWN');
89
+ onErrorRef.current?.(err);
90
+ return err;
91
+ }, []);
92
+ const addMessage = (m) => setMessages((prev) => [...prev, m]);
93
+ const patchMessage = (id, patch) => setMessages((prev) => prev.map((m) => (m.id === id ? { ...m, ...patch } : m)));
94
+ // Live agent messages: subscribe to the Pusher channel named after the thread id and show what arrives
95
+ // on the left, like an assistant reply. Re-subscribes when the thread changes and stops on unmount.
96
+ (0, react_1.useEffect)(() => {
97
+ if (!threadId)
98
+ return;
99
+ const subscription = new realtime_1.FigoRealtimeSubscription(FigoChat_1.FigoChat.getRealtimeStore(), threadId, (text) => {
100
+ if (mounted.current)
101
+ addMessage({ id: newId(), role: 'assistant', text, createdAt: new Date() });
102
+ }, (e) => reportError(e instanceof client_1.FigoChatError ? e : new client_1.FigoChatError('Live updates are unavailable.', 'REALTIME')));
103
+ subscription.start();
104
+ return () => subscription.stop();
105
+ }, [threadId, reportError]);
106
+ const ask = (0, react_1.useCallback)(async (userMessage) => {
107
+ setWaiting(true);
108
+ try {
109
+ const reply = await client.sendMessage(userMessage.text, (userMessage.attachments ?? []).map((a) => a.url));
110
+ if (!mounted.current)
111
+ return;
112
+ patchMessage(userMessage.id, { status: 'sent' });
113
+ if (reply.threadId)
114
+ setThreadId(reply.threadId);
115
+ // in live agent mode the API relays the message to the agent and answers with nothing;
116
+ // the agent's reply arrives on the thread channel instead
117
+ if (reply.answer) {
118
+ addMessage({ id: newId(), role: 'assistant', text: reply.answer, createdAt: new Date() });
119
+ }
120
+ else if (reply.threadMode !== 'liveagent') {
121
+ addMessage({ id: newId(), role: 'assistant', text: '…', createdAt: new Date() });
122
+ }
123
+ }
124
+ catch (e) {
125
+ if (!mounted.current)
126
+ return;
127
+ const err = reportError(e);
128
+ patchMessage(userMessage.id, { status: 'error' });
129
+ addMessage({ id: newId(), role: 'system', text: (0, messages_1.friendlyMessage)(err, 'chat'), createdAt: new Date() });
130
+ }
131
+ finally {
132
+ if (mounted.current)
133
+ setWaiting(false);
134
+ }
135
+ }, [client, reportError]);
136
+ const send = (0, react_1.useCallback)((textOverride) => {
137
+ const text = (textOverride ?? input).trim();
138
+ const ready = pending.filter((p) => p.status === 'done' && p.url);
139
+ if (waiting || (!text && ready.length === 0))
140
+ return;
141
+ if (pending.some((p) => p.status === 'uploading')) {
142
+ react_native_1.Alert.alert('Please wait', 'Your files are still uploading.');
143
+ return;
144
+ }
145
+ const attachments = ready.map((p) => ({
146
+ url: p.url,
147
+ name: p.file.name,
148
+ mimeType: p.file.mimeType,
149
+ localUri: p.file.uri,
150
+ }));
151
+ const message = {
152
+ id: newId(),
153
+ role: 'user',
154
+ text: text || (attachments.length > 1 ? 'Please review the attached files.' : 'Please review the attached file.'),
155
+ attachments,
156
+ createdAt: new Date(),
157
+ status: 'sending',
158
+ };
159
+ addMessage(message);
160
+ setInput('');
161
+ setPending([]);
162
+ ask(message);
163
+ }, [input, pending, waiting, ask]);
164
+ const retry = (m) => {
165
+ if (waiting)
166
+ return;
167
+ patchMessage(m.id, { status: 'sending' });
168
+ ask(m);
169
+ };
170
+ // ---------- files ----------
171
+ const pickFiles = async () => {
172
+ const room = maxFiles - pending.length;
173
+ if (room <= 0) {
174
+ react_native_1.Alert.alert('Limit reached', `You can attach up to ${maxFiles} files per message.`);
175
+ return;
176
+ }
177
+ const result = await DocumentPicker.getDocumentAsync({ multiple: true, copyToCacheDirectory: true, type: '*/*' });
178
+ if (result.canceled || !result.assets?.length)
179
+ return;
180
+ const tooBig = result.assets.filter((a) => (a.size ?? 0) > maxBytes);
181
+ if (tooBig.length) {
182
+ react_native_1.Alert.alert('File too large', `${tooBig.map((a) => a.name).join(', ')} is larger than ${config.maxFileSizeMB ?? 10} MB.`);
183
+ }
184
+ const accepted = result.assets.filter((a) => (a.size ?? 0) <= maxBytes).slice(0, room);
185
+ if (!accepted.length)
186
+ return;
187
+ const items = accepted.map((a) => ({
188
+ id: newId(),
189
+ file: { uri: a.uri, name: a.name, mimeType: a.mimeType ?? undefined, size: a.size ?? undefined },
190
+ status: 'uploading',
191
+ }));
192
+ setPending((prev) => [...prev, ...items]);
193
+ // one request per file so a failure only marks that file
194
+ await Promise.all(items.map(async (item) => {
195
+ try {
196
+ const [url] = await client.uploadFiles([item.file]);
197
+ if (mounted.current)
198
+ setPending((prev) => prev.map((p) => (p.id === item.id ? { ...p, url, status: 'done' } : p)));
199
+ }
200
+ catch (e) {
201
+ reportError(e);
202
+ if (mounted.current)
203
+ setPending((prev) => prev.map((p) => (p.id === item.id ? { ...p, status: 'error' } : p)));
204
+ }
205
+ }));
206
+ };
207
+ const removePending = (id) => setPending((prev) => prev.filter((p) => p.id !== id));
208
+ // ---------- voice ----------
209
+ const startRecording = async () => {
210
+ try {
211
+ const permission = await expo_audio_1.AudioModule.requestRecordingPermissionsAsync();
212
+ if (!permission.granted) {
213
+ react_native_1.Alert.alert('Microphone access', 'Allow microphone access in Settings to send voice messages.');
214
+ return;
215
+ }
216
+ await (0, expo_audio_1.setAudioModeAsync)({ playsInSilentMode: true, allowsRecording: true });
217
+ await recorder.prepareToRecordAsync();
218
+ recorder.record();
219
+ }
220
+ catch (e) {
221
+ const err = reportError(e);
222
+ react_native_1.Alert.alert('Recording failed', (0, messages_1.friendlyMessage)(err, 'recording'));
223
+ }
224
+ };
225
+ const stopRecording = async (discard = false) => {
226
+ const durationMs = recorderState.durationMillis ?? 0; // read before stop(), which resets the state
227
+ try {
228
+ await recorder.stop();
229
+ await (0, expo_audio_1.setAudioModeAsync)({ playsInSilentMode: true, allowsRecording: false });
230
+ }
231
+ catch (e) {
232
+ reportError(e);
233
+ }
234
+ const uri = recorder.uri;
235
+ if (discard || !uri)
236
+ return;
237
+ if (durationMs < 600)
238
+ return; // accidental tap
239
+ setTranscribing(true);
240
+ try {
241
+ const text = await client.transcribe({ uri, name: 'voice-note.m4a', mimeType: 'audio/mp4' });
242
+ if (!mounted.current)
243
+ return;
244
+ if (!text) {
245
+ react_native_1.Alert.alert('Nothing heard', 'We could not hear anything in that recording. Please try again.');
246
+ }
247
+ else if (config.autoSendVoice === false) {
248
+ setInput((prev) => (prev ? `${prev} ${text}` : text));
249
+ }
250
+ else {
251
+ send(text);
252
+ }
253
+ }
254
+ catch (e) {
255
+ const err = reportError(e);
256
+ if (mounted.current)
257
+ react_native_1.Alert.alert('Voice message failed', (0, messages_1.friendlyMessage)(err, 'voice'));
258
+ }
259
+ finally {
260
+ if (mounted.current)
261
+ setTranscribing(false);
262
+ }
263
+ };
264
+ const newConversation = () => {
265
+ if (waiting)
266
+ return;
267
+ FigoChat_1.FigoChat.resetConversation();
268
+ setThreadId(undefined);
269
+ setMessages(welcome);
270
+ setPending([]);
271
+ setInput('');
272
+ };
273
+ // ---------- keyboard (iOS) ----------
274
+ // Pads the bottom by exactly the part of this view the keyboard covers, measured in the window.
275
+ // KeyboardAvoidingView guesses this from offsets and gets it wrong inside a Modal or safe-area padding.
276
+ // Android resizes the window itself (adjustResize), so nothing is needed there.
277
+ const rootRef = (0, react_1.useRef)(null);
278
+ const [keyboardPad, setKeyboardPad] = (0, react_1.useState)(0);
279
+ const extraOffset = props.keyboardVerticalOffset;
280
+ (0, react_1.useEffect)(() => {
281
+ if (react_native_1.Platform.OS !== 'ios')
282
+ return;
283
+ const animate = (e) => react_native_1.LayoutAnimation.configureNext(react_native_1.LayoutAnimation.create(e?.duration || 250, react_native_1.LayoutAnimation.Types.keyboard, react_native_1.LayoutAnimation.Properties.opacity));
284
+ const onChange = (e) => {
285
+ rootRef.current?.measureInWindow((_x, y, _w, h) => {
286
+ if (!mounted.current)
287
+ return;
288
+ const overlap = Math.max(0, y + h - e.endCoordinates.screenY);
289
+ animate(e);
290
+ setKeyboardPad(overlap > 0 ? overlap + extraOffset : 0);
291
+ });
292
+ };
293
+ const onHide = (e) => {
294
+ animate(e);
295
+ setKeyboardPad(0);
296
+ };
297
+ const change = react_native_1.Keyboard.addListener('keyboardWillChangeFrame', onChange);
298
+ const hide = react_native_1.Keyboard.addListener('keyboardWillHide', onHide);
299
+ return () => {
300
+ change.remove();
301
+ hide.remove();
302
+ };
303
+ }, [extraOffset]);
304
+ // ---------- render ----------
305
+ const canSend = !waiting && (input.trim().length > 0 || pending.some((p) => p.status === 'done'));
306
+ const showMic = props.enableVoice && !canSend && input.trim().length === 0;
307
+ const data = (0, react_1.useMemo)(() => [...messages].reverse(), [messages]);
308
+ return ((0, jsx_runtime_1.jsxs)(react_native_1.View, { ref: rootRef, style: [styles.root, props.style, { paddingBottom: keyboardPad }], children: [props.showHeader && ((0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [styles.header, { backgroundColor: primary }], children: [(0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [styles.headerTitle, { color: onPrimary }], numberOfLines: 1, children: config.title ?? 'Chat' }), (0, jsx_runtime_1.jsx)(react_native_1.Pressable, { onPress: newConversation, hitSlop: 10, style: styles.headerButton, accessibilityLabel: "New conversation", children: props.icons.newChat ?? (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [styles.headerIcon, { color: onPrimary }], children: "\u21BB" }) }), props.onClose && ((0, jsx_runtime_1.jsx)(react_native_1.Pressable, { onPress: props.onClose, hitSlop: 10, style: styles.headerButton, accessibilityLabel: "Close chat", children: props.icons.close ?? (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [styles.headerIcon, { color: onPrimary }], children: "\u2715" }) }))] })), (0, jsx_runtime_1.jsx)(react_native_1.FlatList, { style: styles.list, contentContainerStyle: styles.listContent, data: data, inverted: true, keyExtractor: (m) => m.id, keyboardShouldPersistTaps: "handled", ListHeaderComponent: waiting ? (0, jsx_runtime_1.jsx)(TypingBubble, {}) : null, renderItem: ({ item }) => ((0, jsx_runtime_1.jsx)(MessageBubble, { message: item, primary: primary, onPrimary: onPrimary, onRetry: () => retry(item) })) }), pending.length > 0 && ((0, jsx_runtime_1.jsx)(react_native_1.View, { style: styles.pendingRow, children: pending.map((p) => ((0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [styles.pendingChip, p.status === 'error' && styles.pendingChipError], children: [p.status === 'uploading' && (0, jsx_runtime_1.jsx)(react_native_1.ActivityIndicator, { size: "small", color: primary, style: { marginRight: 6 } }), (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: styles.pendingName, numberOfLines: 1, children: p.status === 'error' ? `Failed: ${p.file.name}` : p.file.name }), (0, jsx_runtime_1.jsx)(react_native_1.Pressable, { onPress: () => removePending(p.id), hitSlop: 8, accessibilityLabel: `Remove ${p.file.name}`, children: (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: styles.pendingRemove, children: "\u00D7" }) })] }, p.id))) })), recording || transcribing ? ((0, jsx_runtime_1.jsxs)(react_native_1.View, { style: styles.inputRow, children: [(0, jsx_runtime_1.jsx)(react_native_1.View, { style: styles.recordingInfo, children: transcribing ? ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(react_native_1.ActivityIndicator, { size: "small", color: primary }), (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: styles.recordingText, children: "Processing your voice message\u2026" })] })) : ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(react_native_1.View, { style: styles.recordingDot }), (0, jsx_runtime_1.jsxs)(react_native_1.Text, { style: styles.recordingText, children: ["Recording ", formatDuration(recorderState.durationMillis ?? 0)] }), (0, jsx_runtime_1.jsx)(react_native_1.Pressable, { onPress: () => stopRecording(true), hitSlop: 8, style: { marginLeft: 'auto' }, children: (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: styles.cancelText, children: "Cancel" }) })] })) }), !transcribing && ((0, jsx_runtime_1.jsx)(react_native_1.Pressable, { onPress: () => stopRecording(false), style: [styles.roundButton, { backgroundColor: primary }], accessibilityLabel: "Stop recording and send", children: props.icons.stop ?? (0, jsx_runtime_1.jsx)(react_native_1.View, { style: [styles.stopSquare, { backgroundColor: onPrimary }] }) }))] })) : ((0, jsx_runtime_1.jsxs)(react_native_1.View, { style: styles.inputRow, children: [props.enableAttachments && ((0, jsx_runtime_1.jsx)(react_native_1.Pressable, { onPress: pickFiles, style: styles.iconButton, disabled: waiting, accessibilityLabel: "Attach files", children: props.icons.attach ?? (0, jsx_runtime_1.jsx)(icons_1.AttachIcon, { color: "#6B7280" }) })), (0, jsx_runtime_1.jsx)(react_native_1.TextInput, { style: styles.input, value: input, onChangeText: setInput, placeholder: props.placeholder, placeholderTextColor: "#8A8F98", multiline: true, maxLength: 4000 }), showMic ? ((0, jsx_runtime_1.jsx)(react_native_1.Pressable, { onPress: startRecording, style: [styles.roundButton, { backgroundColor: primary }], disabled: waiting, accessibilityLabel: "Record a voice message", children: props.icons.mic ?? (0, jsx_runtime_1.jsx)(icons_1.MicIcon, { color: onPrimary }) })) : ((0, jsx_runtime_1.jsx)(react_native_1.Pressable, { onPress: () => send(), disabled: !canSend, style: [styles.roundButton, { backgroundColor: primary, opacity: canSend ? 1 : 0.4 }], accessibilityLabel: "Send message", children: props.icons.send ?? (0, jsx_runtime_1.jsx)(icons_1.SendIcon, { color: onPrimary }) }))] }))] }));
309
+ }
310
+ function MessageBubble({ message, primary, onPrimary, onRetry, }) {
311
+ if (message.role === 'system') {
312
+ return ((0, jsx_runtime_1.jsx)(react_native_1.View, { style: styles.systemRow, children: (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: styles.systemText, children: message.text }) }));
313
+ }
314
+ const mine = message.role === 'user';
315
+ const textColor = mine ? onPrimary : '#1F2328';
316
+ return ((0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [styles.bubbleRow, mine ? styles.bubbleRowMine : styles.bubbleRowTheirs], children: [(0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [styles.bubble, mine ? { backgroundColor: primary, borderBottomRightRadius: 4 } : styles.bubbleTheirs], children: [message.attachments?.map((a) => ((0, jsx_runtime_1.jsx)(AttachmentView, { attachment: a, color: textColor }, a.url))), (0, jsx_runtime_1.jsx)(RichText, { text: message.text, color: textColor, linkColor: mine ? onPrimary : primary })] }), mine && message.status === 'sending' && (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: styles.status, children: "Sending\u2026" }), mine && message.status === 'error' && ((0, jsx_runtime_1.jsx)(react_native_1.Pressable, { onPress: onRetry, hitSlop: 6, children: (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [styles.status, styles.statusError], children: "Not sent. Tap to retry" }) }))] }));
317
+ }
318
+ function AttachmentView({ attachment, color }) {
319
+ const isImage = attachment.mimeType?.startsWith('image/') || IMAGE_EXT.test(attachment.name) || IMAGE_EXT.test(attachment.url);
320
+ const open = () => react_native_1.Linking.openURL(attachment.url).catch(() => undefined);
321
+ if (isImage) {
322
+ return ((0, jsx_runtime_1.jsx)(react_native_1.Pressable, { onPress: open, children: (0, jsx_runtime_1.jsx)(react_native_1.Image, { source: { uri: attachment.localUri ?? attachment.url }, style: styles.imageAttachment, resizeMode: "cover" }) }));
323
+ }
324
+ return ((0, jsx_runtime_1.jsx)(react_native_1.Pressable, { onPress: open, style: [styles.fileAttachment, { borderColor: color }], children: (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [styles.fileAttachmentText, { color }], numberOfLines: 1, children: attachment.name }) }));
325
+ }
326
+ /** Renders **bold** and tappable urls; everything else is plain text. */
327
+ function RichText({ text, color, linkColor }) {
328
+ const parts = (0, react_1.useMemo)(() => {
329
+ const tokens = [];
330
+ const re = /(\*\*[^*]+\*\*)|(https?:\/\/[^\s)]+)/g;
331
+ let last = 0;
332
+ let m;
333
+ while ((m = re.exec(text))) {
334
+ if (m.index > last)
335
+ tokens.push({ t: text.slice(last, m.index) });
336
+ if (m[1])
337
+ tokens.push({ t: m[1].slice(2, -2), bold: true });
338
+ else
339
+ tokens.push({ t: m[2], url: m[2] });
340
+ last = m.index + m[0].length;
341
+ }
342
+ if (last < text.length)
343
+ tokens.push({ t: text.slice(last) });
344
+ return tokens;
345
+ }, [text]);
346
+ return ((0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [styles.messageText, { color }], selectable: true, children: parts.map((p, i) => p.url ? ((0, jsx_runtime_1.jsx)(react_native_1.Text, { style: { color: linkColor, textDecorationLine: 'underline' }, onPress: () => react_native_1.Linking.openURL(p.url).catch(() => undefined), children: p.t }, i)) : ((0, jsx_runtime_1.jsx)(react_native_1.Text, { style: p.bold ? { fontWeight: '700' } : undefined, children: p.t }, i))) }));
347
+ }
348
+ function TypingBubble() {
349
+ const [dots, setDots] = (0, react_1.useState)(1);
350
+ (0, react_1.useEffect)(() => {
351
+ const t = setInterval(() => setDots((d) => (d % 3) + 1), 400);
352
+ return () => clearInterval(t);
353
+ }, []);
354
+ return ((0, jsx_runtime_1.jsx)(react_native_1.View, { style: [styles.bubbleRow, styles.bubbleRowTheirs], children: (0, jsx_runtime_1.jsx)(react_native_1.View, { style: [styles.bubble, styles.bubbleTheirs], children: (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [styles.messageText, { color: '#6B7280', width: 24 }], children: '•'.repeat(dots) }) }) }));
355
+ }
356
+ function formatDuration(ms) {
357
+ const s = Math.floor(ms / 1000);
358
+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
359
+ }
360
+ const styles = react_native_1.StyleSheet.create({
361
+ root: { flex: 1, backgroundColor: '#FFFFFF' },
362
+ center: { flex: 1, alignItems: 'center', justifyContent: 'center', padding: 24 },
363
+ muted: { color: '#6B7280', textAlign: 'center' },
364
+ header: { flexDirection: 'row', alignItems: 'center', paddingHorizontal: 16, paddingVertical: 14 },
365
+ headerTitle: { flex: 1, fontSize: 17, fontWeight: '600' },
366
+ headerButton: { marginLeft: 16 },
367
+ headerIcon: { fontSize: 18, fontWeight: '600' },
368
+ list: { flex: 1 },
369
+ listContent: { paddingHorizontal: 12, paddingVertical: 12 },
370
+ bubbleRow: { marginVertical: 4, maxWidth: '85%' },
371
+ bubbleRowMine: { alignSelf: 'flex-end', alignItems: 'flex-end' },
372
+ bubbleRowTheirs: { alignSelf: 'flex-start', alignItems: 'flex-start' },
373
+ bubble: { borderRadius: 18, paddingHorizontal: 14, paddingVertical: 10 },
374
+ bubbleTheirs: { backgroundColor: '#F1F3F5', borderBottomLeftRadius: 4 },
375
+ messageText: { fontSize: 15, lineHeight: 21 },
376
+ status: { fontSize: 11, color: '#8A8F98', marginTop: 3 },
377
+ statusError: { color: '#D93025' },
378
+ systemRow: { alignSelf: 'center', marginVertical: 6, paddingHorizontal: 12, paddingVertical: 6, borderRadius: 10, backgroundColor: '#FDECEA' },
379
+ systemText: { fontSize: 12, color: '#B3261E', textAlign: 'center' },
380
+ imageAttachment: { width: 200, height: 150, borderRadius: 12, marginBottom: 6, backgroundColor: '#00000010' },
381
+ fileAttachment: { borderWidth: react_native_1.StyleSheet.hairlineWidth, borderRadius: 10, paddingHorizontal: 10, paddingVertical: 8, marginBottom: 6, maxWidth: 240 },
382
+ fileAttachmentText: { fontSize: 13 },
383
+ pendingRow: { flexDirection: 'row', flexWrap: 'wrap', paddingHorizontal: 12, paddingTop: 8, gap: 6 },
384
+ pendingChip: { flexDirection: 'row', alignItems: 'center', backgroundColor: '#F1F3F5', borderRadius: 14, paddingHorizontal: 10, paddingVertical: 6, maxWidth: 220 },
385
+ pendingChipError: { backgroundColor: '#FDECEA' },
386
+ pendingName: { fontSize: 12, color: '#1F2328', flexShrink: 1 },
387
+ pendingRemove: { fontSize: 16, color: '#6B7280', marginLeft: 6 },
388
+ inputRow: {
389
+ flexDirection: 'row',
390
+ alignItems: 'flex-end',
391
+ paddingHorizontal: 10,
392
+ paddingVertical: 8,
393
+ borderTopWidth: react_native_1.StyleSheet.hairlineWidth,
394
+ borderTopColor: '#E5E7EB',
395
+ gap: 8,
396
+ },
397
+ iconButton: { width: 40, height: 40, alignItems: 'center', justifyContent: 'center' },
398
+ input: {
399
+ flex: 1,
400
+ minHeight: 40,
401
+ maxHeight: 120,
402
+ borderRadius: 20,
403
+ backgroundColor: '#F1F3F5',
404
+ paddingHorizontal: 14,
405
+ paddingTop: react_native_1.Platform.OS === 'ios' ? 10 : 8,
406
+ paddingBottom: react_native_1.Platform.OS === 'ios' ? 10 : 8,
407
+ fontSize: 15,
408
+ color: '#1F2328',
409
+ },
410
+ roundButton: { width: 40, height: 40, borderRadius: 20, alignItems: 'center', justifyContent: 'center' },
411
+ glyph: { fontSize: 18 },
412
+ stopSquare: { width: 14, height: 14, borderRadius: 2 },
413
+ recordingInfo: { flex: 1, flexDirection: 'row', alignItems: 'center', height: 40, paddingHorizontal: 6, gap: 8 },
414
+ recordingDot: { width: 10, height: 10, borderRadius: 5, backgroundColor: '#D93025' },
415
+ recordingText: { fontSize: 15, color: '#1F2328' },
416
+ cancelText: { fontSize: 15, color: '#6B7280' },
417
+ });
@@ -0,0 +1,49 @@
1
+ import type { FigoChatConfig, FigoChatReply, FigoLocalFile, FigoRealtimeConfig } from './types';
2
+ export declare const DEFAULT_BASE_URL = "https://api.figolabs.ai";
3
+ /** Error thrown by every SDK call. `code` is the API response code or the HTTP status. */
4
+ export declare class FigoChatError extends Error {
5
+ readonly code: string;
6
+ /** The underlying error (e.g. the fetch failure), when there is one. */
7
+ readonly cause?: unknown;
8
+ constructor(message: string, code: string, cause?: unknown);
9
+ }
10
+ /**
11
+ * Thin client over the Figo AI public REST APIs:
12
+ * - POST /api/v1/chat/assistant/{assistantId} chat with the assistant
13
+ * - POST /api/v1/stt speech to text (multipart, field `audio`)
14
+ * - POST /api/v1/cdn/upload/ocr/{assistantId} upload files to the CDN (images are OCR'd)
15
+ */
16
+ export declare class FigoChatClient {
17
+ private readonly config;
18
+ private threadId?;
19
+ private threadMode?;
20
+ constructor(config: FigoChatConfig);
21
+ /** Thread id of the current conversation, once the first reply has arrived. */
22
+ getThreadId(): string | undefined;
23
+ /** `ai` or `liveagent`. */
24
+ getThreadMode(): string | undefined;
25
+ /** Forget the current thread so the next message starts a new conversation. */
26
+ resetThread(): void;
27
+ /**
28
+ * Sends a message to the assistant. CDN urls of uploaded files are appended to the question
29
+ * so the assistant can read them (the API adds the OCR text of uploaded images).
30
+ */
31
+ sendMessage(text: string, attachmentUrls?: string[]): Promise<FigoChatReply>;
32
+ /** Transcribes a recorded audio file (e.g. the .m4a from the recorder) to text. */
33
+ transcribe(file: FigoLocalFile): Promise<string>;
34
+ /**
35
+ * Uploads files to the CDN. Images are OCR'd by the API, so sending their urls in a chat message
36
+ * lets the assistant read them. Returns one url per file, in order.
37
+ */
38
+ uploadFiles(files: FigoLocalFile[]): Promise<string[]>;
39
+ /** Public Pusher settings used to subscribe to the thread channel for live agent messages. */
40
+ getRealtimeConfig(): Promise<FigoRealtimeConfig>;
41
+ private request;
42
+ /** POSTs multipart form data with XMLHttpRequest and returns the status and body text. */
43
+ private upload;
44
+ private parse;
45
+ private parseRaw;
46
+ }
47
+ export declare function extensionOf(file: FigoLocalFile): string;
48
+ /** Reads a local file uri (file:// or content://) as raw base64, without a data: prefix. */
49
+ export declare function readAsBase64(uri: string): Promise<string>;