ahadi-ai 0.0.0-stage → 0.9.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/LICENSE ADDED
@@ -0,0 +1,28 @@
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2026, Ahadi Mental Health
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package/README.md CHANGED
@@ -1,3 +1,231 @@
1
- # Temporary Holding Version
1
+ # ahadi-ai
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The AHADI AI helpline for React Native apps: text chat and voice.
4
+
5
+ If your organisation already runs a helpline on AHADI AI, this package lets you put the same helpline inside your Android or iOS app. People can type or talk to your AI agent, take check-ins, and get your crisis numbers exactly as they would on your website.
6
+
7
+ You don't configure the chat in code. Colours, greeting, languages, privacy and the agent all come from the **Widget** page in your AHADI AI dashboard, and the app picks up changes the moment you save them. Your app only needs to know which chat to open.
8
+
9
+ Text chat is plain TypeScript with no native modules, so it works in Expo Go and bare React Native projects alike. Voice is optional and comes as a separate import, because it needs the phone's microphone and audio (see [Voice](#voice)).
10
+
11
+ ## Before you start
12
+
13
+ You need two things from the dashboard:
14
+
15
+ 1. **Your widget key.** Open **Widget** in the dashboard. The **Mobile apps** panel shows the key, along with a code snippet you can copy.
16
+ 2. **Permission for your app.** In the same page, add your app's ID to **Your apps**. That's the Android package name or iOS bundle ID, for example `org.upendowellness.app`. If the two are different, add both.
17
+
18
+ While the widget is still in test mode it accepts any app, so you can try things out before adding your ID. Once it goes live, only the apps on that list can connect.
19
+
20
+ ## Installation
21
+
22
+ ```bash
23
+ npm install ahadi-ai
24
+ ```
25
+
26
+ It needs React 18 or newer and React Native 0.72 or newer.
27
+
28
+ To keep the chat between app launches you'll also want a storage library. AsyncStorage (`@react-native-async-storage/async-storage`) works, and so do MMKV and Expo SecureStore. Anything with `getItem` and `setItem` will do.
29
+
30
+ ## Adding the chat
31
+
32
+ `AhadiChat` is a complete screen. Render it wherever you want the chat to appear:
33
+
34
+ ```tsx
35
+ import AsyncStorage from "@react-native-async-storage/async-storage";
36
+ import { AhadiChat } from "ahadi-ai";
37
+
38
+ export function HelplineScreen({ navigation }) {
39
+ return (
40
+ <AhadiChat
41
+ widgetKey="YOUR-WIDGET-KEY"
42
+ server="https://helpline.ahadimentalhealth.org"
43
+ appId="org.upendowellness.app"
44
+ storage={AsyncStorage}
45
+ onClose={() => navigation.goBack()}
46
+ />
47
+ );
48
+ }
49
+ ```
50
+
51
+ The chat connects when the component mounts and disconnects when it unmounts.
52
+
53
+ ### Props
54
+
55
+ | Prop | Description |
56
+ |---|---|
57
+ | `widgetKey` | The key from your Widget page. Required. |
58
+ | `server` | Your AHADI AI address. Required. |
59
+ | `appId` | Your app's ID, as listed under **Your apps**. Required. |
60
+ | `language` | `"sw"` or `"en"`. Leave it out to use the organisation's default, or whatever the person picked last time. |
61
+ | `storage` | Where the chat remembers the session between launches. Without it, every launch starts a new chat. |
62
+ | `onClose` | Shows a close button in the header and calls this when it's pressed. |
63
+ | `hideHeader` | Hides the built-in header, for when your navigator already shows a title. |
64
+ | `style` | Style for the outer container. |
65
+
66
+ ## Building your own UI
67
+
68
+ If the built-in screen doesn't fit your design, the `useAhadiChat` hook gives you the same chat as state, and you draw it however you like.
69
+
70
+ ```tsx
71
+ import { useAhadiChat } from "ahadi-ai";
72
+
73
+ function MyChat() {
74
+ const { state, client } = useAhadiChat({
75
+ widgetKey: "YOUR-WIDGET-KEY",
76
+ server: "https://helpline.ahadimentalhealth.org",
77
+ appId: "org.upendowellness.app",
78
+ storage: AsyncStorage,
79
+ });
80
+
81
+ // state.messages the conversation so far
82
+ // state.config the organisation's settings: color, title, greeting, ai_only, privacy
83
+ // state.typing true while the AI is writing
84
+ // state.connection "connecting", "online", "reconnecting", "error" or "closed"
85
+
86
+ // client.send("Hello")
87
+ // client.setLanguage("sw")
88
+ }
89
+ ```
90
+
91
+ Each message has a `from` field: `"me"`, `"ai"`, `"person"` for a counsellor or someone on the team, or `"status"` for short notices from the chat itself. While a reply is still arriving, `streaming` is true and `text` keeps growing.
92
+
93
+ Some messages carry a `card` instead of plain text. Cards are check-ins: an offer to start one, a question with answer options, or the result. When the person taps an option or button, pass it back:
94
+
95
+ ```tsx
96
+ client.tap({ id: option.id, label: option.label }, message.id);
97
+ ```
98
+
99
+ Only the newest card has `active: true`. Older ones should be shown but not tappable.
100
+
101
+ The hook is a thin wrapper around `AhadiClient`, which has no React imports at all. If you're not using React, you can create an `AhadiClient` yourself and call `subscribe()` to hear about changes.
102
+
103
+ ## Voice
104
+
105
+ Voice adds a **Talk** button to the chat header, shown when the organisation has turned on **Voice on your website** in its Widget page. It needs four extra packages with native code:
106
+
107
+ ```bash
108
+ npx expo install livekit-client @livekit/react-native @livekit/react-native-webrtc expo-audio
109
+ ```
110
+
111
+ In a bare React Native app, install the same packages with npm and run `npx pod-install`. Because they include native code, voice doesn't run in Expo Go; use a development build (`npx expo run:ios` or `npx expo run:android`).
112
+
113
+ Your app also has to say why it needs the microphone. With Expo, add this to `app.json`:
114
+
115
+ ```json
116
+ {
117
+ "expo": {
118
+ "ios": { "infoPlist": { "NSMicrophoneUsageDescription": "To talk with the helpline by voice." } },
119
+ "android": { "permissions": ["RECORD_AUDIO", "MODIFY_AUDIO_SETTINGS", "BLUETOOTH_CONNECT"] }
120
+ }
121
+ }
122
+ ```
123
+
124
+ Then pass the phone's voice to the chat:
125
+
126
+ ```tsx
127
+ import { AhadiChat } from "ahadi-ai";
128
+ import { deviceVoice } from "ahadi-ai/voice";
129
+
130
+ <AhadiChat widgetKey="…" server="…" appId="…" voice={deviceVoice} />
131
+ ```
132
+
133
+ Talking works in three ways, and the chat moves between them on its own:
134
+
135
+ 1. **A live call.** The person talks with the AI agent as on a phone call, and can interrupt it. While it's going they see a moving shape that follows both voices, a timer, and buttons for mute, speaker, hang up, captions and typing.
136
+ 2. **Voice notes.** If the connection is too weak for a call, or drops in the middle, the screen switches to a record button. The person records a short note, it's understood and answered, and the answer is read aloud.
137
+ 3. **Text.** Always there underneath. If even a voice note can't get through, the person is told and can type.
138
+
139
+ A call and the chat are the same conversation, so the helpline's team sees one record whichever way the person used.
140
+
141
+ The chat asks for the microphone the first time someone taps Talk, not when the app starts.
142
+
143
+ ### A voice-first app
144
+
145
+ If voice is the main thing your app does, show the call screen directly:
146
+
147
+ ```tsx
148
+ import { AhadiVoiceCall, deviceVoice } from "ahadi-ai/voice";
149
+
150
+ <AhadiVoiceCall
151
+ widgetKey="YOUR-WIDGET-KEY"
152
+ server="https://helpline.ahadimentalhealth.org"
153
+ appId="org.upendowellness.app"
154
+ device={deviceVoice}
155
+ onClose={() => navigation.goBack()}
156
+ />
157
+ ```
158
+
159
+ It starts the call as soon as it mounts. Pass `startWith="notes"` to start with voice notes instead, which is a good choice for areas with weak connections.
160
+
161
+ ### Your own voice screen
162
+
163
+ `AhadiVoice` is the voice controller without any UI:
164
+
165
+ ```tsx
166
+ import { AhadiVoice, deviceVoice } from "ahadi-ai/voice";
167
+
168
+ const voice = new AhadiVoice(client, deviceVoice); // client: from useAhadiChat
169
+ voice.subscribe((state) => { /* state.mode, state.status, state.captions, state.message */ });
170
+
171
+ await voice.startCall();
172
+ voice.levels(); // { me, agent }, 0 to 1, for your own animation
173
+ await voice.setMuted(true);
174
+ await voice.setSpeaker(false);
175
+ await voice.hangUp();
176
+
177
+ await voice.startNotes();
178
+ await voice.startRecording();
179
+ await voice.stopRecording(); // sends the note; the reply is read aloud
180
+ ```
181
+
182
+ The call, the recorder and the player are separate pieces, so you can replace any of them by passing your own object in place of `deviceVoice`.
183
+
184
+ ## When the connection is poor
185
+
186
+ People write in from all kinds of networks, so the chat is built not to lose anything:
187
+
188
+ - A message written while the connection is down is kept, marked "Sending…", and goes as soon as the connection is back.
189
+ - Every message carries its own ID, so if it has to be sent twice the helpline still answers it once.
190
+ - If a message really can't be sent (someone types very fast, for example), it's marked "Not sent. Tap to try again."
191
+ - Phones close connections when an app goes to the background. When the person comes back, the chat checks the connection at once and reconnects if needed, rather than waiting.
192
+
193
+ `AhadiChat` and `AhadiVoiceCall` handle the background case for you. If you build your own screen, call `client.resume()` when the app becomes active again (React Native's `AppState`).
194
+
195
+ ## Privacy
196
+
197
+ Each organisation chooses what happens to a chat when the person leaves. You'll find the setting in `state.config.privacy`:
198
+
199
+ - `"keep"`: the chat is saved and comes back the next time they open it.
200
+ - `"private"`: nothing is saved on the phone, and the conversation is deleted from the server when the chat closes.
201
+ - `"choose"`: the person decides. The built-in screen shows a Private button. In your own UI, call `client.setPrivate(true)`.
202
+
203
+ If the person leaves without closing the chat properly (the app is killed, say), the server deletes a quiet private chat on its own after 30 minutes.
204
+
205
+ If the organisation runs an AI-only helpline (`config.ai_only`), the chat never suggests that a counsellor will join.
206
+
207
+ ## Troubleshooting
208
+
209
+ **"This app isn't allowed to use this chat yet."** Your app ID isn't on the **Your apps** list, and the widget is live. Add it in the dashboard and press Try again.
210
+
211
+ **"Couldn't connect."** Check the `server` address, and that the phone can reach it. On Android, plain `http://` addresses (for example a local test server) need `android:usesCleartextTraffic="true"` in your manifest. On iOS they need an App Transport Security exception.
212
+
213
+ **The chat starts fresh every time.** Pass a `storage` prop. Without it, nothing is remembered between launches.
214
+
215
+ ## Not supported yet
216
+
217
+ Offline check-ins are only available in the website chat for now.
218
+
219
+ ## Development
220
+
221
+ ```bash
222
+ npm install
223
+ npm test # builds, then runs the chat and voice tests against a fake server and a simulated phone
224
+ ```
225
+
226
+ To try a real conversation against a running AHADI AI server:
227
+
228
+ ```bash
229
+ npm run build
230
+ AHADI_SERVER=http://localhost:8000 AHADI_KEY=<widget key> node test/live.js
231
+ ```
@@ -0,0 +1,16 @@
1
+ import { type StyleProp, type ViewStyle } from "react-native";
2
+ import type { ChatOptions } from "./types";
3
+ import type { VoiceDevice } from "./voice/transport";
4
+ export interface AhadiChatProps extends ChatOptions {
5
+ /** Show a close button in the header and call this when it's pressed. */
6
+ onClose?: () => void;
7
+ /** Hide the built-in header (when your app has its own). */
8
+ hideHeader?: boolean;
9
+ style?: StyleProp<ViewStyle>;
10
+ /** Turns on voice (the Talk button, when the organisation has voice on):
11
+ * `import { deviceVoice } from "ahadi-ai/voice"`. */
12
+ voice?: VoiceDevice;
13
+ }
14
+ /** The full chat screen: header, messages, check-in cards and the message box, in the organisation's
15
+ * colours and texts (from its Widget page; changes there show here straight away). */
16
+ export declare function AhadiChat({ onClose, hideHeader, style, voice: device, ...options }: AhadiChatProps): import("react/jsx-runtime").JSX.Element;
@@ -0,0 +1,112 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AhadiChat = AhadiChat;
4
+ const jsx_runtime_1 = require("react/jsx-runtime");
5
+ const react_1 = require("react");
6
+ const react_native_1 = require("react-native");
7
+ const strings_1 = require("./strings");
8
+ const useAhadiChat_1 = require("./useAhadiChat");
9
+ const AhadiVoiceCall_1 = require("./voice/AhadiVoiceCall");
10
+ const voice_1 = require("./voice/voice");
11
+ const LIGHT = { bg: "#ffffff", fg: "#16222a", muted: "#4a5a63", soft: "#f3f6f7", bubble: "#eef2f3", line: "#e3e8ea" };
12
+ const DARK = { bg: "#10222a", fg: "#e8f0f2", muted: "#a9bcc2", soft: "#162e37", bubble: "#1d3842", line: "#24424d" };
13
+ /** The full chat screen: header, messages, check-in cards and the message box, in the organisation's
14
+ * colours and texts (from its Widget page; changes there show here straight away). */
15
+ function AhadiChat({ onClose, hideHeader, style, voice: device, ...options }) {
16
+ const { state, client } = (0, useAhadiChat_1.useAhadiChat)(options);
17
+ const voice = (0, react_1.useMemo)(() => (device ? new voice_1.AhadiVoice(client, device) : null), [client, device]);
18
+ const [talking, setTalking] = (0, react_1.useState)(false);
19
+ (0, react_1.useEffect)(() => () => voice?.dispose(), [voice]);
20
+ (0, react_1.useEffect)(() => {
21
+ // phones drop connections in the background: check it the moment the app is back
22
+ const sub = react_native_1.AppState.addEventListener("change", (s) => s === "active" && client.resume());
23
+ return () => sub.remove();
24
+ }, [client]);
25
+ const scheme = (0, react_native_1.useColorScheme)();
26
+ const [draft, setDraft] = (0, react_1.useState)("");
27
+ const [showResults, setShowResults] = (0, react_1.useState)(false);
28
+ const list = (0, react_1.useRef)(null);
29
+ const { config, language: lang } = state;
30
+ const t = (k) => (0, strings_1.text)(lang, k);
31
+ const theme = config?.theme ?? "auto";
32
+ const c = theme === "dark" || (theme === "auto" && scheme === "dark") ? DARK : LIGHT;
33
+ const brand = config?.color ?? "#0B5D63";
34
+ const onBrand = (0, strings_1.onColor)(brand);
35
+ const title = config?.title?.[lang] || config?.name || "AHADI AI";
36
+ const choosePrivate = config?.privacy === "choose";
37
+ const canTalk = !!voice && config?.voice === true && state.connection !== "error";
38
+ const canSend = state.connection === "online" || state.connection === "reconnecting";
39
+ (0, react_1.useEffect)(() => {
40
+ const id = setTimeout(() => list.current?.scrollToEnd({ animated: true }), 50);
41
+ return () => clearTimeout(id);
42
+ }, [state.messages, state.typing]);
43
+ const submit = () => {
44
+ if (client.send(draft))
45
+ setDraft("");
46
+ };
47
+ const note = [t(config?.ai_only ? "ai_only" : "ai"), state.private ? t("private_on") : ""].filter(Boolean).join(" ");
48
+ const status = state.connection === "connecting" ? t("connecting") : state.connection === "reconnecting" ? t("reconnecting") : "";
49
+ return ((0, jsx_runtime_1.jsxs)(react_native_1.KeyboardAvoidingView, { style: [styles.fill, { backgroundColor: c.bg }, style], behavior: react_native_1.Platform.OS === "ios" ? "padding" : undefined, children: [!hideHeader && ((0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [styles.header, { backgroundColor: brand }], children: [(0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [styles.title, { color: onBrand }], numberOfLines: 1, accessibilityRole: "header", children: title }), canTalk && (0, jsx_runtime_1.jsx)(HeaderButton, { label: `🎙 ${t("talk")}`, color: onBrand, onPress: () => setTalking(true) }), choosePrivate && ((0, jsx_runtime_1.jsx)(HeaderButton, { label: `🔒 ${t("private")}`, color: onBrand, pressed: state.private, onPress: () => void client.setPrivate(!state.private) })), state.results.length > 0 && !state.private && ((0, jsx_runtime_1.jsx)(HeaderButton, { label: t("my_results"), color: onBrand, pressed: showResults, onPress: () => setShowResults((v) => !v) })), (config?.languages?.length ?? 0) > 1 && ((0, jsx_runtime_1.jsx)(HeaderButton, { label: t("lang"), color: onBrand, onPress: () => client.setLanguage(lang === "sw" ? "en" : "sw") })), onClose && (0, jsx_runtime_1.jsx)(HeaderButton, { label: "\u2715", color: onBrand, accessibilityLabel: t("close"), onPress: onClose })] })), (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [styles.note, { backgroundColor: c.soft, color: c.muted }], children: note }), state.connection === "error" ? ((0, jsx_runtime_1.jsxs)(react_native_1.View, { style: styles.center, children: [(0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [styles.errorText, { color: c.fg }], children: t(state.error === "not_allowed" ? "not_allowed" : "error") }), (0, jsx_runtime_1.jsx)(react_native_1.Pressable, { accessibilityRole: "button", onPress: () => void client.retry(), style: [styles.primary, { backgroundColor: brand }], children: (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: { color: onBrand, fontWeight: "600" }, children: t("retry") }) })] })) : showResults ? ((0, jsx_runtime_1.jsx)(Results, { rows: state.results, c: c, t: t, brand: brand, onBack: () => setShowResults(false) })) : ((0, jsx_runtime_1.jsx)(react_native_1.FlatList, { ref: list, style: styles.fill, contentContainerStyle: styles.list, data: state.messages, keyExtractor: (m) => m.id, renderItem: ({ item }) => ((0, jsx_runtime_1.jsx)(Row, { m: item, c: c, brand: brand, onBrand: onBrand, t: t, onTap: (a) => client.tap(a, item.id), onRetry: () => client.resend(item.id) })), ListFooterComponent: state.typing ? (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [styles.typing, { color: c.muted }], children: t("typing") }) : status ? ((0, jsx_runtime_1.jsxs)(react_native_1.View, { style: styles.statusRow, children: [(0, jsx_runtime_1.jsx)(react_native_1.ActivityIndicator, { size: "small", color: c.muted }), (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: { color: c.muted, fontSize: 12 }, children: status })] })) : null })), (0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [styles.composer, { borderTopColor: c.line }], children: [(0, jsx_runtime_1.jsx)(react_native_1.TextInput, { style: [styles.input, { color: c.fg, borderColor: c.line, backgroundColor: c.bg }], value: draft, onChangeText: setDraft, placeholder: t("placeholder"), placeholderTextColor: c.muted, multiline: true, maxLength: 2000, accessibilityLabel: t("placeholder"), onSubmitEditing: submit, blurOnSubmit: false }), (0, jsx_runtime_1.jsx)(react_native_1.Pressable, { accessibilityRole: "button", disabled: !canSend || !draft.trim(), onPress: submit, style: ({ pressed }) => [styles.send, { backgroundColor: brand, opacity: !canSend || !draft.trim() ? 0.5 : pressed ? 0.85 : 1 }], children: (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: { color: onBrand, fontWeight: "600" }, children: t("send") }) })] }), config?.show_badge !== false && (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [styles.badge, { color: c.muted }], children: t("badge") }), talking && voice && ((0, jsx_runtime_1.jsx)(react_native_1.View, { style: react_native_1.StyleSheet.absoluteFill, children: (0, jsx_runtime_1.jsx)(AhadiVoiceCall_1.AhadiVoiceCall, { voice: voice, onClose: () => setTalking(false) }) }))] }));
50
+ }
51
+ function HeaderButton({ label, color, pressed, onPress, accessibilityLabel }) {
52
+ return ((0, jsx_runtime_1.jsx)(react_native_1.Pressable, { accessibilityRole: "button", accessibilityLabel: accessibilityLabel ?? label, accessibilityState: pressed === undefined ? undefined : { selected: pressed }, onPress: onPress, hitSlop: 6, style: [styles.hbtn, pressed ? { backgroundColor: "rgba(255,255,255,0.2)" } : null], children: (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: { color, fontSize: 13, fontWeight: "600" }, children: label }) }));
53
+ }
54
+ function Row({ m, c, brand, onBrand, t, onTap, onRetry }) {
55
+ if (m.card)
56
+ return (0, jsx_runtime_1.jsx)(CardView, { m: m, c: c, brand: brand, onBrand: onBrand, onTap: onTap });
57
+ if (m.from === "status")
58
+ return (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [styles.status, { color: c.muted }], children: m.text });
59
+ const mine = m.from === "me";
60
+ const bubble = ((0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [styles.bubble, mine ? [styles.mine, { backgroundColor: brand }] : { backgroundColor: c.bubble }, m.delivery === "failed" ? { opacity: 0.6 } : null], children: [m.from === "person" && (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [styles.who, { color: c.muted }], children: t("person") }), (0, jsx_runtime_1.jsxs)(react_native_1.Text, { style: { color: mine ? onBrand : c.fg, fontSize: 15, lineHeight: 21 }, children: [m.text, m.streaming ? " ▍" : ""] })] }));
61
+ if (!mine || !m.delivery || m.delivery === "sent")
62
+ return bubble;
63
+ return ((0, jsx_runtime_1.jsxs)(react_native_1.View, { children: [bubble, m.delivery === "failed" ? ((0, jsx_runtime_1.jsx)(react_native_1.Pressable, { accessibilityRole: "button", onPress: onRetry, hitSlop: 8, style: styles.deliveryRow, children: (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: styles.failed, children: t("failed_msg") }) })) : ((0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [styles.sending, { color: c.muted }], children: t("sending_msg") }))] }));
64
+ }
65
+ function CardView({ m, c, brand, onBrand, onTap }) {
66
+ const card = m.card;
67
+ const active = !!m.active;
68
+ const button = (a) => ((0, jsx_runtime_1.jsx)(react_native_1.Pressable, { accessibilityRole: "button", disabled: !active, onPress: () => onTap(a), style: ({ pressed }) => [styles.cbtn, a.primary ? { backgroundColor: brand } : { borderColor: c.line, borderWidth: 1 }, { opacity: !active ? 0.5 : pressed ? 0.85 : 1 }], children: (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: { color: a.primary ? onBrand : c.fg, fontWeight: "600" }, children: a.label }) }, a.id));
69
+ return ((0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [styles.card, { backgroundColor: c.bg, borderColor: c.line, opacity: active || card.type === "checkin_result" ? 1 : 0.8 }], children: [(0, jsx_runtime_1.jsxs)(react_native_1.View, { style: styles.chead, children: [(0, jsx_runtime_1.jsx)(react_native_1.Text, { style: { fontSize: card.type === "checkin_offer" ? 26 : 18 }, children: card.emoji }), (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [styles.cname, { color: c.fg }], children: card.name }), card.type === "checkin_question" && (0, jsx_runtime_1.jsxs)(react_native_1.Text, { style: { color: c.muted, fontSize: 12 }, children: [(card.index ?? 0) + 1, "/", card.total ?? 1] })] }), card.type === "checkin_offer" && ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [!!(card.intro || card.summary) && (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: { color: c.fg }, children: card.intro || card.summary }), !!card.meta && (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: { color: c.muted, fontSize: 12 }, children: card.meta }), (0, jsx_runtime_1.jsx)(react_native_1.View, { style: styles.cbtns, children: (card.actions ?? []).map(button) })] })), card.type === "checkin_question" && ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [(0, jsx_runtime_1.jsx)(react_native_1.View, { style: styles.steps, children: Array.from({ length: card.total ?? 1 }, (_, i) => ((0, jsx_runtime_1.jsx)(react_native_1.View, { style: [styles.step, { backgroundColor: i <= (card.index ?? 0) ? brand : c.line }] }, i))) }), !!card.cheer && (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: { color: brand, fontSize: 12, fontWeight: "600" }, children: card.cheer }), !!card.recall && (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: { color: c.muted, fontSize: 13 }, children: card.recall }), (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [styles.cq, { color: c.fg }], children: card.text }), (card.options ?? []).map((o, i) => {
70
+ const label = `${o.emoji ? `${o.emoji} ` : ""}${o.label}`;
71
+ const picked = m.picked === label;
72
+ return ((0, jsx_runtime_1.jsxs)(react_native_1.Pressable, { accessibilityRole: "button", accessibilityState: { selected: picked, disabled: !active }, disabled: !active, onPress: () => onTap({ id: o.id, label }), style: ({ pressed }) => [styles.opt, { borderColor: picked ? brand : c.line, backgroundColor: picked ? c.soft : c.bg, opacity: !active && !picked ? 0.55 : pressed ? 0.85 : 1 }], children: [(0, jsx_runtime_1.jsx)(react_native_1.Text, { style: { color: c.fg, flex: 1 }, children: label }), (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: { color: c.muted, fontSize: 12 }, children: i + 1 })] }, o.id));
73
+ }), card.stop && active && (0, jsx_runtime_1.jsx)(react_native_1.Pressable, { accessibilityRole: "button", onPress: () => onTap(card.stop), children: (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: { color: c.muted, fontSize: 13, textAlign: "center", paddingVertical: 6 }, children: card.stop.label }) })] })), card.type === "checkin_result" && ((0, jsx_runtime_1.jsxs)(jsx_runtime_1.Fragment, { children: [!!card.message && (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: { color: c.fg, fontSize: 15 }, children: card.message }), !!card.result && ((0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [styles.chip, { borderColor: strings_1.SEVERITY[card.severity ?? ""] ?? brand }], children: [(0, jsx_runtime_1.jsx)(react_native_1.View, { style: [styles.dot, { backgroundColor: strings_1.SEVERITY[card.severity ?? ""] ?? brand }] }), (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: { color: c.fg, fontWeight: "600" }, children: card.result })] })), !!card.outro && (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: { color: c.fg }, children: card.outro }), !!card.disclaimer && (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: { color: c.muted, fontSize: 12 }, children: card.disclaimer }), !!card.screening && (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: { color: c.muted, fontSize: 12 }, children: card.screening }), (0, jsx_runtime_1.jsx)(react_native_1.View, { style: styles.cbtns, children: (card.actions ?? []).map(button) })] }))] }));
74
+ }
75
+ function Results({ rows, c, t, brand, onBack }) {
76
+ return ((0, jsx_runtime_1.jsx)(react_native_1.FlatList, { style: styles.fill, contentContainerStyle: styles.list, data: rows, keyExtractor: (r) => `${r.slug}-${r.at}`, ListHeaderComponent: (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: { color: c.muted, fontSize: 12, marginBottom: 8 }, children: t("results_note") }), ListEmptyComponent: (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: { color: c.muted }, children: t("no_results") }), renderItem: ({ item }) => ((0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [styles.card, { backgroundColor: c.bg, borderColor: c.line }], children: [(0, jsx_runtime_1.jsxs)(react_native_1.View, { style: styles.chead, children: [(0, jsx_runtime_1.jsx)(react_native_1.Text, { style: { fontSize: 18 }, children: item.emoji }), (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: [styles.cname, { color: c.fg }], children: item.name }), (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: { color: c.muted, fontSize: 12 }, children: new Date(item.at).toLocaleDateString() })] }), (0, jsx_runtime_1.jsxs)(react_native_1.View, { style: [styles.chip, { borderColor: strings_1.SEVERITY[item.severity] ?? brand }], children: [(0, jsx_runtime_1.jsx)(react_native_1.View, { style: [styles.dot, { backgroundColor: strings_1.SEVERITY[item.severity] ?? brand }] }), (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: { color: c.fg, fontWeight: "600" }, children: item.result })] }), !!item.message && (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: { color: c.fg }, children: item.message })] })), ListFooterComponent: (0, jsx_runtime_1.jsx)(react_native_1.Pressable, { accessibilityRole: "button", onPress: onBack, style: [styles.cbtn, { borderColor: c.line, borderWidth: 1, marginTop: 8 }], children: (0, jsx_runtime_1.jsx)(react_native_1.Text, { style: { color: c.fg, fontWeight: "600" }, children: t("back") }) }) }));
77
+ }
78
+ const styles = react_native_1.StyleSheet.create({
79
+ fill: { flex: 1 },
80
+ header: { flexDirection: "row", alignItems: "center", gap: 4, paddingHorizontal: 14, paddingVertical: 12 },
81
+ title: { flex: 1, fontSize: 17, fontWeight: "700" },
82
+ hbtn: { paddingHorizontal: 8, paddingVertical: 6, borderRadius: 8 },
83
+ note: { fontSize: 12, paddingHorizontal: 14, paddingVertical: 8 },
84
+ list: { padding: 12, gap: 8 },
85
+ bubble: { maxWidth: "85%", alignSelf: "flex-start", paddingHorizontal: 13, paddingVertical: 9, borderRadius: 16 },
86
+ mine: { alignSelf: "flex-end" },
87
+ who: { fontSize: 11, fontWeight: "600", marginBottom: 2 },
88
+ status: { alignSelf: "center", fontSize: 12, textAlign: "center", paddingHorizontal: 12 },
89
+ typing: { fontSize: 13, fontStyle: "italic", paddingVertical: 4 },
90
+ statusRow: { flexDirection: "row", alignItems: "center", gap: 6, justifyContent: "center", paddingVertical: 6 },
91
+ composer: { flexDirection: "row", alignItems: "flex-end", gap: 8, padding: 10, borderTopWidth: react_native_1.StyleSheet.hairlineWidth },
92
+ input: { flex: 1, minHeight: 44, maxHeight: 120, borderWidth: 1, borderRadius: 12, paddingHorizontal: 12, paddingTop: 11, paddingBottom: 11, fontSize: 15 },
93
+ send: { minHeight: 44, paddingHorizontal: 16, borderRadius: 12, alignItems: "center", justifyContent: "center" },
94
+ badge: { textAlign: "center", fontSize: 11, paddingBottom: 8 },
95
+ center: { flex: 1, alignItems: "center", justifyContent: "center", gap: 14, padding: 24 },
96
+ errorText: { textAlign: "center", fontSize: 15 },
97
+ primary: { paddingHorizontal: 18, paddingVertical: 11, borderRadius: 12 },
98
+ card: { borderWidth: 1, borderRadius: 16, padding: 12, gap: 8, alignSelf: "stretch" },
99
+ chead: { flexDirection: "row", alignItems: "center", gap: 8 },
100
+ cname: { flex: 1, fontWeight: "700", fontSize: 15 },
101
+ cbtns: { flexDirection: "row", flexWrap: "wrap", gap: 8 },
102
+ cbtn: { minHeight: 44, paddingHorizontal: 14, borderRadius: 12, alignItems: "center", justifyContent: "center" },
103
+ steps: { flexDirection: "row", gap: 3 },
104
+ step: { flex: 1, height: 4, borderRadius: 2 },
105
+ cq: { fontSize: 16, fontWeight: "600", lineHeight: 22 },
106
+ opt: { minHeight: 44, flexDirection: "row", alignItems: "center", borderWidth: 1, borderRadius: 12, paddingHorizontal: 12, paddingVertical: 10 },
107
+ chip: { flexDirection: "row", alignItems: "center", gap: 6, alignSelf: "flex-start", borderWidth: 1, borderRadius: 999, paddingHorizontal: 10, paddingVertical: 4 },
108
+ dot: { width: 8, height: 8, borderRadius: 4 },
109
+ deliveryRow: { alignSelf: "flex-end", paddingVertical: 4 },
110
+ failed: { color: "#C8372D", fontSize: 12, fontWeight: "600" },
111
+ sending: { alignSelf: "flex-end", fontSize: 11, marginTop: 3 },
112
+ });
@@ -0,0 +1,84 @@
1
+ import type { Card, ChatOptions, ChatState, Lang } from "./types";
2
+ type Listener = (state: ChatState) => void;
3
+ export declare function isCard(x: unknown): x is Card;
4
+ export declare class AhadiClient {
5
+ private readonly opts;
6
+ private state;
7
+ private readonly listeners;
8
+ private readonly server;
9
+ private token;
10
+ private ws;
11
+ private attempt;
12
+ private ping;
13
+ private retryTimer;
14
+ private readonly replies;
15
+ private seq;
16
+ private started;
17
+ private ended;
18
+ private readonly cids;
19
+ private lastHeard;
20
+ private watchdog;
21
+ constructor(opts: ChatOptions);
22
+ getState(): ChatState;
23
+ /** Called with the new state after every change. Returns a function that stops listening. */
24
+ subscribe(listener: Listener): () => void;
25
+ /** Open the chat: restore the session (unless it was private), load the settings and connect. */
26
+ start(): Promise<void>;
27
+ /** After an error: try to start again. */
28
+ retry(): Promise<void>;
29
+ /** Send what the person typed. While the connection is down the message waits (shown as sending) and
30
+ * goes as soon as it's back; the helpline answers it once, even if it had to be sent twice. Returns
31
+ * false only when there is no chat to send to (not started, ended, or failed to start). */
32
+ send(message: string): boolean;
33
+ /** Send a message again after it failed (for example the person sent too many too fast). */
34
+ resend(rowId: string): void;
35
+ /** The app came back to the foreground: phones close connections in the background, so check the
36
+ * connection now and reconnect at once if it's gone. AhadiChat calls this for you (AppState); call it
37
+ * yourself if you build your own screen. */
38
+ resume(): void;
39
+ /** The chat's session, shared with voice calls and voice notes so they're one conversation. */
40
+ get sessionToken(): string;
41
+ /** An address on the helpline for this chat, e.g. endpoint("voice/"). */
42
+ endpoint(path: string): string;
43
+ get serverAddress(): string;
44
+ /** The headers that identify this app to the helpline. */
45
+ get appHeaders(): Record<string, string>;
46
+ get http(): typeof fetch;
47
+ /** A voice note was understood and sent as the person's message: show it like something they typed. */
48
+ noteSent(transcript: string): void;
49
+ /** A short line in the chat from the chat itself (used by the voice module). */
50
+ notice(text: string): void;
51
+ private transmit;
52
+ private flush;
53
+ private rowForCid;
54
+ /** A button on a check-in card was tapped (an answer, "start", "continue", ...). */
55
+ tap(action: {
56
+ id: string;
57
+ label: string;
58
+ }, cardRowId?: string): boolean;
59
+ setLanguage(language: Lang): void;
60
+ /** Turn private chat on or off (when the organisation lets the person choose). A fresh chat starts;
61
+ * a private one is erased. */
62
+ setPrivate(on: boolean): Promise<void>;
63
+ /** The person closed the chat: a private chat is erased now; the connection closes. Call this when
64
+ * the chat screen goes away (AhadiChat does it for you). */
65
+ end(): Promise<void>;
66
+ private openSession;
67
+ private connect;
68
+ private dropped;
69
+ private handle;
70
+ private forget;
71
+ private closeSocket;
72
+ private stopPing;
73
+ private socketOpen;
74
+ private keep;
75
+ private withGreeting;
76
+ private push;
77
+ private update;
78
+ private nextId;
79
+ private set;
80
+ private key;
81
+ private load;
82
+ private save;
83
+ }
84
+ export {};