react-native-voice-bot-sdk 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +57 -0
- package/LICENSE +21 -0
- package/README.md +438 -2
- package/android/build.gradle +15 -0
- package/android/src/main/AndroidManifest.xml +16 -0
- package/android/src/main/java/expo/modules/voicebot/VoiceBotAudioModule.kt +416 -0
- package/android/src/main/java/expo/modules/voicebot/VoiceBotMicService.kt +107 -0
- package/app.plugin.js +1 -0
- package/build/NativeAudio.d.ts +24 -0
- package/build/NativeAudio.js +1 -0
- package/build/VoiceBotClient.d.ts +231 -0
- package/build/VoiceBotClient.js +1 -0
- package/build/audio/noiseGate.d.ts +83 -0
- package/build/audio/noiseGate.js +1 -0
- package/build/base64.d.ts +6 -0
- package/build/base64.js +1 -0
- package/build/expo-router.d.ts +16 -0
- package/build/expo-router.js +1 -0
- package/build/index.d.ts +20 -0
- package/build/index.js +1 -0
- package/build/logger.d.ts +35 -0
- package/build/logger.js +1 -0
- package/build/navigation/callbackNavigation.d.ts +28 -0
- package/build/navigation/callbackNavigation.js +1 -0
- package/build/navigation/reactNavigation.d.ts +33 -0
- package/build/navigation/reactNavigation.js +1 -0
- package/build/navigation/state.d.ts +20 -0
- package/build/navigation/state.js +1 -0
- package/build/navigation/types.d.ts +27 -0
- package/build/navigation/types.js +1 -0
- package/build/protocol.d.ts +108 -0
- package/build/protocol.js +1 -0
- package/build/react/VoiceBotProvider.d.ts +52 -0
- package/build/react/VoiceBotProvider.js +1 -0
- package/build/react/VoiceBotWidget.d.ts +29 -0
- package/build/react/VoiceBotWidget.js +1 -0
- package/build/react/useVoiceBot.d.ts +17 -0
- package/build/react/useVoiceBot.js +1 -0
- package/docs/INTEGRATION.md +189 -0
- package/docs/PROTOCOL.md +271 -0
- package/expo-module.config.json +9 -0
- package/ios/VoiceBotAudio.podspec +25 -0
- package/ios/VoiceBotAudioModule.swift +219 -0
- package/package.json +76 -4
- package/plugin/withVoiceBot.js +137 -0
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
import { type NoiseGateOptions, type WhileSpeaking } from './audio/noiseGate';
|
|
2
|
+
import { type LogLevel } from './logger';
|
|
3
|
+
import type { NavigationAdapter } from './navigation/types';
|
|
4
|
+
import { type BotReply, type NavigateCommand, type NavigateResultMessage } from './protocol';
|
|
5
|
+
export type VoiceBotStatus = 'idle' | 'connecting' | 'connected' | 'listening';
|
|
6
|
+
export interface VoiceBotState {
|
|
7
|
+
status: VoiceBotStatus;
|
|
8
|
+
/** True while reply audio from the server is (estimated to be) playing. */
|
|
9
|
+
speaking: boolean;
|
|
10
|
+
sessionId: string | null;
|
|
11
|
+
/** Last transcript of what the user said (`question`). */
|
|
12
|
+
lastQuestion: string | null;
|
|
13
|
+
/** Last bot reply text (`output.prompt`). */
|
|
14
|
+
lastPrompt: string | null;
|
|
15
|
+
lastError: VoiceBotError | null;
|
|
16
|
+
/** The most recent JSON message from the server. */
|
|
17
|
+
lastMessage: Record<string, unknown> | null;
|
|
18
|
+
}
|
|
19
|
+
export interface VoiceBotError {
|
|
20
|
+
code: 'connect_failed' | 'connect_timeout' | 'not_connected' | 'mic_permission' | 'mic_failed' | 'native_missing' | 'socket_closed' | 'playback_failed';
|
|
21
|
+
message: string;
|
|
22
|
+
}
|
|
23
|
+
export interface ConnectOptions {
|
|
24
|
+
/** Voice server WebSocket URL, e.g. `wss://voice.example.com/demo`. */
|
|
25
|
+
url: string;
|
|
26
|
+
/** Socket is open and the connect message (session info + screens) was sent. */
|
|
27
|
+
onSuccess?(info: {
|
|
28
|
+
sessionId: string;
|
|
29
|
+
}): void;
|
|
30
|
+
/** Could not connect (or the socket failed before it opened). */
|
|
31
|
+
onFailure?(error: VoiceBotError): void;
|
|
32
|
+
/** The socket closed after a successful connect. */
|
|
33
|
+
onClose?(info: {
|
|
34
|
+
code: number;
|
|
35
|
+
reason: string;
|
|
36
|
+
}): void;
|
|
37
|
+
/** Every parsed reply from the server (after audio was queued for playback). */
|
|
38
|
+
onReply?(reply: BotReply): void;
|
|
39
|
+
/** Start streaming the mic right after connecting. Default `false`. */
|
|
40
|
+
autoStart?: boolean;
|
|
41
|
+
/** Uplink audio format. `binary` (default) = 640-byte BINARY frames. `base64` = `{type:"audio"}` TEXT frames. */
|
|
42
|
+
uplinkEncoding?: 'binary' | 'base64';
|
|
43
|
+
/** `domain_id` in the connect message: your domain / tenant id. Default `""`. */
|
|
44
|
+
domainId?: string;
|
|
45
|
+
/**
|
|
46
|
+
* `cookie_id` in the connect message: the visitor id. Default: a random id that the SDK saves on
|
|
47
|
+
* the device, so it stays the same across app launches (until the app is uninstalled or its data
|
|
48
|
+
* is cleared). Pass your own id to use that instead (e.g. your logged-in user's visitor id).
|
|
49
|
+
*/
|
|
50
|
+
cookieId?: string;
|
|
51
|
+
/** `deviceId` in the connect message. Default `1`. */
|
|
52
|
+
deviceId?: number;
|
|
53
|
+
/** Milliseconds to wait for the socket to open. Default 10000. */
|
|
54
|
+
connectTimeoutMs?: number;
|
|
55
|
+
/**
|
|
56
|
+
* Console log level: `debug` | `info` | `warn` | `error` | `none`. Same as `setLogLevel()`.
|
|
57
|
+
* Default `info` in development, `warn` in release.
|
|
58
|
+
*/
|
|
59
|
+
logLevel?: LogLevel;
|
|
60
|
+
/**
|
|
61
|
+
* Reconnect by itself when the socket drops (network change, server restart). The mic keeps
|
|
62
|
+
* running while it reconnects, and each reconnect is a new session (new `sessionId`, connect
|
|
63
|
+
* message sent again, `onSuccess` called again). Default `true`: retries with backoff
|
|
64
|
+
* 1 s, 2 s, 4 s ... up to 30 s, 20 attempts. `false` turns it off.
|
|
65
|
+
*/
|
|
66
|
+
autoReconnect?: boolean | {
|
|
67
|
+
maxAttempts?: number;
|
|
68
|
+
maxDelayMs?: number;
|
|
69
|
+
};
|
|
70
|
+
/** Called before each reconnect attempt. */
|
|
71
|
+
onReconnecting?(info: {
|
|
72
|
+
attempt: number;
|
|
73
|
+
delayMs: number;
|
|
74
|
+
}): void;
|
|
75
|
+
/**
|
|
76
|
+
* Android: keep listening while the app is in the background or the screen is off. While the
|
|
77
|
+
* mic is on, Android shows a notification (required for background mic use). Default `true`.
|
|
78
|
+
* Pass `{ title, text }` to change the notification text, or `false` to stop the mic from being
|
|
79
|
+
* used in the background. iOS: not supported yet.
|
|
80
|
+
*/
|
|
81
|
+
backgroundListening?: boolean | {
|
|
82
|
+
title?: string;
|
|
83
|
+
text?: string;
|
|
84
|
+
};
|
|
85
|
+
/**
|
|
86
|
+
* When a reply to a new question arrives while older reply audio is still playing, stop the old
|
|
87
|
+
* audio and play the new one. Parts of the same reply (same `question`) still play in order.
|
|
88
|
+
* Default `true`; `false` queues every reply after the previous one.
|
|
89
|
+
*/
|
|
90
|
+
interruptOnNewReply?: boolean;
|
|
91
|
+
/**
|
|
92
|
+
* Send silence instead of room noise when nobody is speaking near the phone, so the server can
|
|
93
|
+
* tell where a sentence ends. Adds `preRollMs` (300 ms) of delay. Default `true`; `false` sends
|
|
94
|
+
* the mic unchanged. Pass an object to tune it: `{ thresholdDb: 10, minLevelDb: -55,
|
|
95
|
+
* hangoverMs: 700, preRollMs: 300 }` (lower `thresholdDb` = more sensitive).
|
|
96
|
+
*/
|
|
97
|
+
noiseGate?: boolean | Omit<NoiseGateOptions, 'enabled' | 'whileSpeaking'>;
|
|
98
|
+
/**
|
|
99
|
+
* What the mic does while the bot is speaking. `'guard'` (default): only louder speech counts, so
|
|
100
|
+
* the bot's own voice coming back through the mic is ignored. `'mute'`: send silence (no
|
|
101
|
+
* barge-in). `'listen'`: same as any other time.
|
|
102
|
+
*/
|
|
103
|
+
whileSpeaking?: WhileSpeaking;
|
|
104
|
+
/** Stop the bot's reply when the user starts talking over it (about 200 ms of speech). Default `true`. */
|
|
105
|
+
bargeIn?: boolean;
|
|
106
|
+
/** During a phone call, stop the bot's audio and send silence until the call ends. Default `true`. */
|
|
107
|
+
pauseOnCall?: boolean;
|
|
108
|
+
/**
|
|
109
|
+
* Keep the same `sessionId` when the SDK reconnects after a drop, so the server can keep the
|
|
110
|
+
* conversation. Default `false`: every connection is a new session.
|
|
111
|
+
*/
|
|
112
|
+
keepSessionOnReconnect?: boolean;
|
|
113
|
+
}
|
|
114
|
+
type Listener = () => void;
|
|
115
|
+
type MessageListener = (message: Record<string, unknown>) => void;
|
|
116
|
+
/**
|
|
117
|
+
* The voice bot session. Use the shared instance `VoiceBot` (or `useVoiceBot()` in React).
|
|
118
|
+
*/
|
|
119
|
+
export declare class VoiceBotClient {
|
|
120
|
+
private ws;
|
|
121
|
+
private options;
|
|
122
|
+
private state;
|
|
123
|
+
private listeners;
|
|
124
|
+
private messageListeners;
|
|
125
|
+
private navigation;
|
|
126
|
+
private navUnsubscribe;
|
|
127
|
+
private lastSentScreen;
|
|
128
|
+
private screens;
|
|
129
|
+
private readonly runCookieId;
|
|
130
|
+
private savedCookieId;
|
|
131
|
+
private wantConnected;
|
|
132
|
+
private reconnectAttempt;
|
|
133
|
+
private reconnectTimer;
|
|
134
|
+
private reconnectDueAt;
|
|
135
|
+
private connectDeadline;
|
|
136
|
+
private onConnectDeadline;
|
|
137
|
+
private backgroundServiceOn;
|
|
138
|
+
constructor();
|
|
139
|
+
private stopMic;
|
|
140
|
+
private seq;
|
|
141
|
+
private speakingUntil;
|
|
142
|
+
private speakingTimer;
|
|
143
|
+
private connectTimer;
|
|
144
|
+
private connectStartedAt;
|
|
145
|
+
private micStartedAt;
|
|
146
|
+
private framesSent;
|
|
147
|
+
private framesDropped;
|
|
148
|
+
private replyCount;
|
|
149
|
+
private replyAudioSeconds;
|
|
150
|
+
private lastReplyRate;
|
|
151
|
+
private lastReplyNavKey;
|
|
152
|
+
/** `question` of the reply whose audio is playing (to tell new replies from more chunks). */
|
|
153
|
+
private playingQuestion;
|
|
154
|
+
/** Reply the user talked over: its remaining chunks are not played. */
|
|
155
|
+
private bargedQuestion;
|
|
156
|
+
private gate;
|
|
157
|
+
private inCall;
|
|
158
|
+
private lastSessionId;
|
|
159
|
+
private lastReplyNavAt;
|
|
160
|
+
getState: () => VoiceBotState;
|
|
161
|
+
/** Subscribe to state changes. Returns an unsubscribe function. */
|
|
162
|
+
subscribe: (listener: Listener) => (() => void);
|
|
163
|
+
/** Subscribe to every JSON message from the server (replies, navigate, custom). */
|
|
164
|
+
addMessageListener: (listener: MessageListener) => (() => void);
|
|
165
|
+
private setState;
|
|
166
|
+
get isConnected(): boolean;
|
|
167
|
+
get isListening(): boolean;
|
|
168
|
+
/** Opens the socket, sends the connect message (session info + screens), then calls `onSuccess`. */
|
|
169
|
+
connect: (options: ConnectOptions) => void;
|
|
170
|
+
private open;
|
|
171
|
+
private reconnectEnabled;
|
|
172
|
+
/** Waits (1 s, 2 s, 4 s ... max 30 s) and opens the socket again, keeping the mic running. */
|
|
173
|
+
private scheduleReconnect;
|
|
174
|
+
private reconnectNow;
|
|
175
|
+
private clearReconnectTimer;
|
|
176
|
+
/** Stops the mic and playback and closes the socket. */
|
|
177
|
+
disconnect: () => void;
|
|
178
|
+
private closeSocket;
|
|
179
|
+
private clearConnectTimer;
|
|
180
|
+
/** Called for every mic frame: runs deadlines that JS timers miss in the background. */
|
|
181
|
+
private tick;
|
|
182
|
+
private fail;
|
|
183
|
+
private sendJson;
|
|
184
|
+
private sendConnectMessage;
|
|
185
|
+
/** The SDK's own visitor id, saved on the device by the native module. */
|
|
186
|
+
private getSavedCookieId;
|
|
187
|
+
/** Sends the screen list again, only if it changed after the connect message. */
|
|
188
|
+
private sendScreensUpdate;
|
|
189
|
+
/**
|
|
190
|
+
* Starts streaming the mic. If the socket isn't open it reconnects with the last
|
|
191
|
+
* `connect()` options first. Resolves to true when the mic is streaming.
|
|
192
|
+
*/
|
|
193
|
+
start: () => Promise<boolean>;
|
|
194
|
+
/** Stops streaming the mic. The socket stays open. */
|
|
195
|
+
stop: () => void;
|
|
196
|
+
/** start() when idle, stop() when listening. */
|
|
197
|
+
toggle: () => Promise<void>;
|
|
198
|
+
private startBackground;
|
|
199
|
+
private stopRecording;
|
|
200
|
+
/** Every 20 ms mic frame from the native module. */
|
|
201
|
+
private onMicFrame;
|
|
202
|
+
private sendFrameBytes;
|
|
203
|
+
/** The user started talking over the bot: stop its reply. */
|
|
204
|
+
private bargeIn;
|
|
205
|
+
private stopSpeakingState;
|
|
206
|
+
private handleInterruption;
|
|
207
|
+
private handleText;
|
|
208
|
+
/**
|
|
209
|
+
* The server can ask for a screen inside a normal reply:
|
|
210
|
+
* output: { type: "navigation", intent: "navigate", screen: "index", class_name: "index", target: "index" }
|
|
211
|
+
* The screen is taken from `screen`, then `class_name`, then `target` (first non-empty one).
|
|
212
|
+
* `"back"` as the screen (or type `"back"`) goes back. Each request is acted on once, even when
|
|
213
|
+
* the reply arrives in several audio chunks.
|
|
214
|
+
*/
|
|
215
|
+
private navigateFromReply;
|
|
216
|
+
/** Queues a reply's audio: stops an older reply first, skips a reply the user talked over. */
|
|
217
|
+
private playReplyAudio;
|
|
218
|
+
/** Stops the audio of the previous reply so the reply to a new question plays right away. */
|
|
219
|
+
private interruptPlayback;
|
|
220
|
+
private markSpeaking;
|
|
221
|
+
/** Registers (or clears with `null`) the host app's navigation. */
|
|
222
|
+
setNavigation: (adapter: NavigationAdapter | null) => void;
|
|
223
|
+
private sendScreenChanged;
|
|
224
|
+
/** Finds a screen by full name, path, or unique last segment (case-insensitive). */
|
|
225
|
+
private resolveScreen;
|
|
226
|
+
/** Runs a navigate command (also usable by the host for testing). */
|
|
227
|
+
handleNavigate: (cmd: NavigateCommand) => Promise<NavigateResultMessage>;
|
|
228
|
+
}
|
|
229
|
+
/** Shared voice bot session. */
|
|
230
|
+
export declare const VoiceBot: VoiceBotClient;
|
|
231
|
+
export {};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{AppState as e}from"react-native";import*as t from"./NativeAudio";import{NoiseGate as s}from"./audio/noiseGate";import{base64ByteLength as n,base64ToBytes as i,bytesToBase64 as o}from"./base64";import{logger as a,preview as r,setLogLevel as c}from"./logger";import{BYTES_PER_SECOND as h,SAMPLE_RATE as l}from"./protocol";function d(){const e=new Uint8Array(16),t=globalThis.crypto;if(t?.getRandomValues)t.getRandomValues(e);else for(let t=0;t<16;t++)e[t]=Math.floor(256*Math.random());e[6]=15&e[6]|64,e[8]=63&e[8]|128;const s=Array.from(e,(e=>e.toString(16).padStart(2,"0"))).join("");return`${s.slice(0,8)}-${s.slice(8,12)}-${s.slice(12,16)}-${s.slice(16,20)}-${s.slice(20)}`}const p=new Uint8Array(640),u=e=>(e/h).toFixed(2),g={1e3:"normal",1001:"going away",1002:"protocol error",1003:"unsupported data",1006:"connection lost (no close frame)",1008:"policy violation",1009:"message too big",1011:"server error"};export class VoiceBotClient{constructor(){this.ws=null,this.options=null,this.state={status:"idle",speaking:!1,sessionId:null,lastQuestion:null,lastPrompt:null,lastError:null,lastMessage:null},this.listeners=new Set,this.messageListeners=new Set,this.navigation=null,this.navUnsubscribe=null,this.lastSentScreen=null,this.screens=[],this.runCookieId=d(),this.wantConnected=!1,this.reconnectAttempt=0,this.reconnectTimer=null,this.reconnectDueAt=0,this.connectDeadline=0,this.onConnectDeadline=null,this.backgroundServiceOn=!1,this.stopMic=null,this.seq=0,this.speakingUntil=0,this.speakingTimer=null,this.connectTimer=null,this.connectStartedAt=0,this.micStartedAt=0,this.framesSent=0,this.framesDropped=0,this.replyCount=0,this.replyAudioSeconds=0,this.lastReplyRate=l,this.lastReplyNavKey=null,this.playingQuestion=null,this.bargedQuestion=null,this.gate=null,this.inCall=!1,this.lastSessionId=null,this.lastReplyNavAt=0,this.getState=()=>this.state,this.subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)}),this.addMessageListener=e=>(this.messageListeners.add(e),()=>{this.messageListeners.delete(e)}),this.connect=e=>{this.options=e,e.logLevel&&c(e.logLevel),this.wantConnected=!0,this.reconnectAttempt=0,this.clearReconnectTimer(),this.open()},this.disconnect=()=>{this.wantConnected=!1,this.reconnectAttempt=0,this.clearReconnectTimer(),this.stopRecording(),t.stopPlayback(),this.playingQuestion=null,this.closeSocket(1e3,"User exited"),this.setState({status:"idle",sessionId:null,speaking:!1})},this.start=async()=>{if(this.isListening)return!0;if(!this.isConnected)return this.reconnectTimer?(this.reconnectNow(),!1):this.options?("connecting"!==this.state.status?this.connect({...this.options,autoStart:!0}):this.options={...this.options,autoStart:!0},!1):(this.fail({code:"not_connected",message:"Call VoiceBot.connect({ url }) before start()"}),!1);try{if(!await t.requestMicPermission())return a.warn("microphone permission denied"),this.setState({lastError:{code:"mic_permission",message:"Microphone permission denied"}}),!1;this.seq=0,this.framesSent=0,this.framesDropped=0,this.micStartedAt=Date.now();const e="base64"===this.options?.uplinkEncoding,n=this.options?.noiseGate??!0;return this.gate=new s({..."object"==typeof n?n:{},enabled:!1!==n,whileSpeaking:this.options?.whileSpeaking??"guard"}),this.inCall=!1,this.stopMic=await t.startRecording((t=>this.onMicFrame(t,e)),(e=>{a.error(`mic error: ${e}`),this.setState({lastError:{code:"mic_failed",message:e}})})),this.isConnected?(this.setState({status:"listening",lastError:null}),this.startBackground(),a.info(`mic started: PCM s16le ${l} Hz mono, 640-byte frames (20 ms), uplink=${e?"base64 TEXT":"BINARY"}, noise gate ${!1===n?"off":"on"}, while bot speaks: ${this.options?.whileSpeaking??"guard"}, barge-in `+(!1===this.options?.bargeIn?"off":"on")),!0):(this.stopRecording(),!1)}catch(e){return a.error(`mic failed to start: ${e?.message??String(e)}`),this.setState({lastError:{code:"mic_failed",message:e?.message??String(e)}}),!1}},this.stop=()=>{this.stopRecording(),this.isConnected&&this.setState({status:"connected"})},this.toggle=async()=>{this.isListening?this.stop():await this.start()},this.setNavigation=e=>{e!==this.navigation&&(this.navUnsubscribe?.(),this.navUnsubscribe=null,this.navigation=e,e&&(a.info(`navigation registered: ${e.kind}, ${e.getScreens().length} screens`),this.navUnsubscribe=e.subscribe((()=>this.sendScreenChanged())),this.isConnected&&this.state.sessionId&&(this.sendScreensUpdate(this.state.sessionId),this.lastSentScreen=null,this.sendScreenChanged())))},this.handleNavigate=async e=>{const t="back"===e.action,s={type:"navigate_result",sessionId:this.state.sessionId??"",screen:e.screen??null,action:t?"back":"open",className:null,status:"failed",message:"",requestId:e.requestId??null},n=(e,t="",n=s.className)=>{s.status=e,s.message=t,s.className=n;const i=`→ navigate_result: ${e} ${"back"===s.action?"back":`"${s.screen}"`}`+(n&&n!==s.screen?` → ${n}`:"")+(t?` (${t})`:"");return"failed"===e?a.error(i):"unknown_screen"===e||"not_supported"===e?a.warn(i):a.info(i),this.sendJson(s),s},i=this.navigation;if(!i)return n("not_supported","The app has no navigation registered with the voice bot");try{if(t){const e=i.getCurrentScreen();return await i.goBack()?n("went_back","",e):n("not_supported","Nothing to go back to",e)}if(!e.screen)return n("unknown_screen","No screen given");const s=this.resolveScreen(e.screen);if(!s)return n("unknown_screen",`Not in the screens list: ${e.screen}`,null);const o=e.params,a=i.getCurrentScreen();return a!==s.name||o?(i.getBackStack().includes(s.name)&&a!==s.name?await i.popTo(s,o):await i.push(s,o),n("opened","",s.name)):n("already_on_screen","",s.name)}catch(e){return n("failed",e?.message??String(e))}},t.onInterruption((e=>this.handleInterruption(e)));try{e.addEventListener("change",(e=>{"active"===e&&this.reconnectTimer&&(a.info("app is active again: reconnecting now"),this.reconnectNow())}))}catch{}}setState(e){this.state={...this.state,...e},this.listeners.forEach((e=>e()))}get isConnected(){return"connected"===this.state.status||"listening"===this.state.status}get isListening(){return"listening"===this.state.status}open(){const e=this.options;this.ws&&this.closeSocket(1e3,"Reconnecting");const{url:s}=e,n=this.reconnectAttempt>0;if(!t.isNativeAvailable())return void this.fail({code:"native_missing",message:t.NATIVE_MISSING_MESSAGE});this.setState({status:"connecting",lastError:null}),this.connectStartedAt=Date.now(),a.info(`connecting to ${s}`);let i=!1;const o=new WebSocket(s);o.binaryType="arraybuffer",this.ws=o;const r=e.connectTimeoutMs??1e4,c=()=>{i||this.ws!==o||(this.closeSocket(1e3,"Connect timeout"),n?this.scheduleReconnect(`timed out connecting to ${s}`):this.fail({code:"connect_timeout",message:`Timed out connecting to ${s}`}))};this.connectTimer=setTimeout(c,r),this.connectDeadline=Date.now()+r,this.onConnectDeadline=c,o.onopen=()=>{if(this.ws!==o)return;i=!0,this.clearConnectTimer();const t=n&&e.keepSessionOnReconnect&&this.lastSessionId?this.lastSessionId:d();this.lastSessionId=t,this.replyCount=0,this.lastReplyNavKey=null;const s=null!=this.stopMic;this.setState({status:s?"listening":"connected",sessionId:t,lastError:null}),a.info((n?`reconnected (attempt ${this.reconnectAttempt})`:"connected")+" in "+`${Date.now()-this.connectStartedAt} ms, session=${t}`+(n&&s?`, mic kept running (${this.framesDropped} frames dropped while offline)`:"")),this.reconnectAttempt=0,this.sendConnectMessage(t),this.lastSentScreen=null,this.sendScreenChanged(),e.onSuccess?.({sessionId:t}),e.autoStart&&this.start()},o.onmessage=e=>{this.ws===o&&("string"==typeof e.data?this.handleText(e.data):a.debug(`← RECV binary message ignored (${e.data?.byteLength??"?"} bytes)`))},o.onerror=e=>{this.ws===o&&(e?.message&&a.warn(`socket error: ${e.message}`),i||setTimeout((()=>{if(this.ws!==o)return;this.clearConnectTimer(),this.ws=null;const t=e?.message||`Could not connect to ${s}`;n?this.scheduleReconnect(t):this.fail({code:"connect_failed",message:t})}),500))},o.onclose=t=>{if(this.ws!==o)return;if(this.ws=null,this.clearConnectTimer(),!i){const e=t.reason||`Could not connect to ${s}`;let i="";return/trust anchor|certificate|CertPath|SSL|handshake/i.test(e)?i=" (TLS: the server certificate is not trusted by the phone, e.g. self-signed. Use a certificate from a public CA, or ws:// for testing)":/refused/i.test(e)?i=" (nothing listening on that host/port)":/timeout|timed out|unreachable|no route/i.test(e)?i=" (host not reachable from the phone)":/cleartext/i.test(e)&&(i=" (ws:// is blocked: set allowCleartextTraffic in the config plugin)"),n?void this.scheduleReconnect(e+i):(this.stopRecording(),void this.fail({code:"connect_failed",message:e+i}))}const r=t.code??1006,c=`socket closed: code=${r} (${g[r]??"unknown"})${t.reason?` reason="${t.reason}"`:""}`;if(1e3===r?a.info(c):a.warn(c),e.onClose?.({code:r,reason:t.reason??""}),1e3!==r&&this.wantConnected&&this.reconnectEnabled())return this.setState({sessionId:null}),void this.scheduleReconnect(c);this.stopRecording(),this.setState({status:"idle",sessionId:null})}}reconnectEnabled(){return!1!==this.options?.autoReconnect}scheduleReconnect(e){const t="object"==typeof this.options?.autoReconnect?this.options.autoReconnect:{},s=t.maxAttempts??20,n=t.maxDelayMs??3e4;if(!this.wantConnected)return;if(this.reconnectAttempt>=s)return a.error(`giving up after ${this.reconnectAttempt} reconnect attempts (${e})`),this.reconnectAttempt=0,this.stopRecording(),void this.fail({code:"connect_failed",message:`Reconnect failed: ${e}`});this.reconnectAttempt++;const i=Math.min(n,1e3*2**(this.reconnectAttempt-1));a.warn(`reconnecting in ${(i/1e3).toFixed(0)} s (attempt ${this.reconnectAttempt}/${s}): ${e}`),this.setState({status:"connecting",sessionId:null}),this.options?.onReconnecting?.({attempt:this.reconnectAttempt,delayMs:i}),this.clearReconnectTimer(),this.reconnectDueAt=Date.now()+i,this.reconnectTimer=setTimeout((()=>{this.reconnectTimer=null,this.reconnectDueAt=0,this.wantConnected&&this.open()}),i)}reconnectNow(){this.reconnectTimer&&(this.clearReconnectTimer(),this.wantConnected&&this.open())}clearReconnectTimer(){this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.reconnectTimer=null,this.reconnectDueAt=0}closeSocket(e,t){const s=this.ws;if(this.ws=null,this.clearConnectTimer(),s){a.info(`→ closing socket: code=${e} reason="${t}"`);try{s.close(e,t)}catch{}}}clearConnectTimer(){this.connectTimer&&clearTimeout(this.connectTimer),this.connectTimer=null,this.connectDeadline=0,this.onConnectDeadline=null}tick(){const e=Date.now();if(this.reconnectDueAt&&e>=this.reconnectDueAt)this.reconnectNow();else if(this.connectDeadline&&e>=this.connectDeadline){const e=this.onConnectDeadline;this.clearConnectTimer(),e?.()}}fail(e){a.error(`${e.code}: ${e.message}`),this.setState({status:"idle",sessionId:null,lastError:e}),this.options?.onFailure?.(e)}sendJson(e){if(this.ws&&this.ws.readyState===WebSocket.OPEN){const t=JSON.stringify(e);a.debug(`→ SEND ${r(t)}`),this.ws.send(t)}else a.warn(`not sent (socket not open): ${r(e,120)}`)}sendConnectMessage(e){this.screens=this.navigation?.getScreens()??[];const t={sessionId:e,domain_id:this.options?.domainId??"",cookie_id:this.options?.cookieId||this.getSavedCookieId()||this.runCookieId,type:"Buffer",deviceId:this.options?.deviceId??1,sampleRate:l,screens:this.screens.map((e=>e.name))};var s;a.info(`→ connect message: domain_id=${t.domain_id||'""'} cookie_id=${s=t.cookie_id,s?`${s.slice(0,8)}…`:"-"} deviceId=${t.deviceId} sampleRate=${t.sampleRate} screens(${t.screens.length})=${JSON.stringify(t.screens)}`),t.screens.length||a.warn("no screens sent: register navigation on <VoiceBotProvider navigation={...}> to enable voice navigation"),this.sendJson(t)}getSavedCookieId(){return void 0===this.savedCookieId&&(this.savedCookieId=t.getPersistentId("cookie_id")),this.savedCookieId}sendScreensUpdate(e){const t=this.screens.map((e=>e.name)).join("\n");this.screens=this.navigation?.getScreens()??[];const s=this.screens.map((e=>e.name));if(s.join("\n")===t)return;const n={type:"screens",sessionId:e,screens:s};a.info(`→ screens update (${s.length}): ${JSON.stringify(s)}`),this.sendJson(n)}async startBackground(){const e=this.options?.backgroundListening??!0;if(!1===e)return;const s="object"==typeof e&&e.title||"Voice assistant",n="object"==typeof e&&e.text||"Listening…",i=await t.startBackgroundService(s,n);!i||this.stopMic?(this.backgroundServiceOn=i,i&&a.info("background listening on (notification shown while the mic is on)")):t.stopBackgroundService()}stopRecording(){if(this.backgroundServiceOn&&(this.backgroundServiceOn=!1,t.stopBackgroundService()),this.stopMic){const e=this.gate?.flush()??[],s="base64"===this.options?.uplinkEncoding;e.forEach((e=>this.sendFrameBytes(e,s))),this.gate=null,t.stopRecording(),this.stopMic(),this.stopMic=null;const n=Date.now()-this.micStartedAt;a.info(`mic stopped after ${(n/1e3).toFixed(1)} s: sent ${this.framesSent} frames (${u(640*this.framesSent)} s of audio, ${640*this.framesSent} bytes)`+(this.framesDropped?`, dropped ${this.framesDropped} (socket not open)`:""))}}onMicFrame(e,t){this.tick();let s=i(e);if(this.inCall)s=p;else if(this.gate){const e=this.gate.process(s,this.state.speaking);void 0!==e.speechEvent&&a.debug(e.speechEvent?`🗣 speech started (level ${this.gate.levelDb.toFixed(0)} dBFS, room ${this.gate.noiseFloorDb.toFixed(0)} dBFS)`:"… speech ended"),e.bargeIn&&!1!==this.options?.bargeIn&&this.bargeIn(),s=e.out}s&&this.sendFrameBytes(s,t)}sendFrameBytes(e,t){const s=this.ws;if(!s||s.readyState!==WebSocket.OPEN)return this.framesDropped++,void(1===this.framesDropped&&a.warn("mic frame dropped: socket not open"));if(this.framesSent++,a.isEnabled("trace")&&a.trace(`→ SEND audio frame #${this.framesSent} (640 bytes, ${t?"base64 TEXT":"BINARY"})`),1===this.framesSent)a.info("→ first audio frame sent");else if(this.framesSent%250==0){const e=s.bufferedAmount??0,t=this.gate;a.info(`→ audio streaming: ${this.framesSent} frames (${u(640*this.framesSent)} s)`+(this.framesDropped?`, dropped ${this.framesDropped}`:"")+(t?`, speech ${(100*t.openRatio).toFixed(0)}% / silence ${(100-100*t.openRatio).toFixed(0)}%, room ${t.noiseFloorDb.toFixed(0)} dBFS`:"")+(this.inCall?", in a call (sending silence)":"")+(e>32e3?`, ${e} bytes waiting to send (slow network?)`:""))}t?s.send(JSON.stringify({type:"audio",sessionId:this.state.sessionId,seq:this.seq++,sampleRate:l,data:o(e)})):s.send(function(e){return 0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:e.slice().buffer}(e))}bargeIn(){this.state.speaking&&(t.stopPlayback(),a.info(`✋ barge-in: you started talking, stopped the reply to "${this.playingQuestion??""}"`),this.bargedQuestion=this.playingQuestion,this.stopSpeakingState())}stopSpeakingState(){this.speakingUntil=Date.now(),this.speakingTimer&&clearTimeout(this.speakingTimer),this.speakingTimer=null,this.playingQuestion=null,t.releaseAudioFocus(),this.state.speaking&&this.setState({speaking:!1})}handleInterruption(e){if("focus_lost"===e)this.state.speaking&&a.info("🔇 another app took the audio: stopped the bot's reply"),this.stopSpeakingState();else if("call_started"===e){if(!1===this.options?.pauseOnCall||!this.stopMic)return;this.inCall=!0,this.stopSpeakingState(),a.info("📞 phone call: bot audio stopped, the mic sends silence until the call ends")}else"call_ended"===e&&this.inCall&&(this.inCall=!1,a.info("📞 call ended: mic audio resumed"))}handleText(e){let t;try{t=JSON.parse(e)}catch{return void a.warn(`← non-JSON text ignored: ${r(e,120)}`)}if(a.debug(`← RECV ${r(e)}`),!t||"object"!=typeof t)return;if(this.messageListeners.forEach((e=>e(t))),this.setState({lastMessage:t}),"navigate"===t.type)return a.info("← navigate: "+("back"===t.action?"back":`screen="${t.screen}"`)+(t.params?` params=${JSON.stringify(t.params)}`:"")+(null!=t.requestId?` requestId=${t.requestId}`:"")),void this.handleNavigate(t);const s=t;if("string"==typeof s.output)try{s.output=JSON.parse(s.output)}catch{}this.replyCount++;const n=this.state.lastQuestion,i=this.state.lastPrompt;"string"==typeof s.buffer&&s.buffer.length>0&&this.playReplyAudio(s,s.buffer);const o={};"string"==typeof s.question&&s.question&&(o.lastQuestion=s.question);const c=s.output?.prompt;"string"==typeof c&&c&&(o.lastPrompt=c),o.lastQuestion&&o.lastQuestion!==n&&a.info(`← you said: "${o.lastQuestion}"`),o.lastPrompt&&o.lastPrompt!==i&&a.info(`← bot: "${o.lastPrompt}"`);const h=s.output?.error;h&&0!==h&&"0"!==h&&a.warn(`← server reported error: ${r(s.output,200)}`),s.buffer||o.lastQuestion||o.lastPrompt||a.info(`← message: ${r(t,200)}`),Object.keys(o).length&&this.setState(o),this.navigateFromReply(s),this.options?.onReply?.(s)}navigateFromReply(e){const t=e.output;if(!t||"object"!=typeof t)return;const s=e=>"string"==typeof e?e.trim():"",n=s(t.type).toLowerCase(),i=s(t.intent).toLowerCase(),o=s(t.screen)||s(t.class_name)||s(t.target),r="back"===n||/^(back|go_back|goback)$/i.test(o);if(!(r||o&&("navigation"===n||"navigate"===n||"navigate"===i||r||this.resolveScreen(o))))return;const c=`${e.question??""}|${r?"back":o}`,h=Date.now();c===this.lastReplyNavKey&&h-this.lastReplyNavAt<3e3||(this.lastReplyNavKey=c,this.lastReplyNavAt=h,a.info(`← reply asks for ${r?"back":`screen "${o}"`} (type="${s(t.type)}" intent="${s(t.intent)}" screen="${s(t.screen)}" class_name="${s(t.class_name)}" target="${s(t.target)}")`),this.handleNavigate(r?{type:"navigate",action:"back"}:{type:"navigate",screen:o}))}playReplyAudio(e,s){const i="string"==typeof e.question?e.question.trim():"";if(i&&i===this.bargedQuestion)a.debug(`← reply #${this.replyCount}: audio not played (you talked over "${i}")`);else{i&&(this.bargedQuestion=null);try{const o=n(s);i&&i!==this.playingQuestion&&(this.state.speaking&&!1!==this.options?.interruptOnNewReply&&this.interruptPlayback(i),this.playingQuestion=i,this.gate?.newReply()),o%2&&a.warn(`reply audio chunk has an odd byte count (${o}); last byte dropped`);const r=function(e){const t=e.output,s=Number(e.sample_rate??e.sampleRate??t?.sample_rate??t?.sampleRate);return Number.isFinite(s)&&s>=8e3&&s<=48e3?Math.round(s):l}(e);r!==this.lastReplyRate&&(a.info(`reply audio sample rate: ${r} Hz${r===l?" (default)":" (from the server)"}`),this.lastReplyRate=r),t.enqueuePlayback(s,r);const c=o/(2*r);a.debug(`← reply #${this.replyCount}: audio chunk ${o} bytes (${c.toFixed(2)} s at ${r} Hz) queued`),this.markSpeaking(c)}catch(e){a.error(`playback failed: ${e?.message??String(e)}`),this.setState({lastError:{code:"playback_failed",message:e?.message??String(e)}})}}}interruptPlayback(e){const s=Math.max(0,this.speakingUntil-Date.now())/1e3;t.stopPlayback(),a.info(`⏹ stopped old reply audio (${s.toFixed(1)} s left of "${this.playingQuestion??""}") for new reply to "${e}"`),this.speakingUntil=Date.now(),this.replyAudioSeconds=0}markSpeaking(e){const s=Date.now();this.speakingUntil=Math.max(this.speakingUntil,s)+1e3*e,this.state.speaking||(this.replyAudioSeconds=0,a.info("🔊 bot speaking (reply audio playing)"),this.setState({speaking:!0})),this.replyAudioSeconds+=e,this.speakingTimer&&clearTimeout(this.speakingTimer),this.speakingTimer=setTimeout((()=>{a.info(`🔇 bot finished speaking (${this.replyAudioSeconds.toFixed(2)} s of audio)`),this.playingQuestion=null,t.releaseAudioFocus(),this.setState({speaking:!1})}),this.speakingUntil-s+150)}sendScreenChanged(){if(!this.isConnected||!this.navigation||!this.state.sessionId)return;const e=this.navigation.getCurrentScreen();if(!e)return;const t=this.navigation.getBackStack(),s=`${e}|${t.join(",")}`;if(s===this.lastSentScreen)return;this.lastSentScreen=s;const n={type:"screen_changed",sessionId:this.state.sessionId,screen:e,backStack:t};a.info(`→ screen_changed: "${e}" backStack=${JSON.stringify(t)}`),this.sendJson(n)}resolveScreen(e){const t=this.screens.length?this.screens:this.navigation?.getScreens()??[],s=t.find((t=>t.name===e||t.path===e));if(s)return s;const n=e.replace(/^\//,"").toLowerCase(),i=t.filter((e=>e.name.toLowerCase()===n||e.path?.replace(/^\//,"").toLowerCase()===n));if(1===i.length)return i[0];const o=t.filter((e=>{const t=e.name.split("/").filter((e=>"index"!==e&&!/^\(.*\)$/.test(e))),s=(t[t.length-1]??"index").toLowerCase();return s===n||s.replace(/screen$/,"")===n.replace(/screen$/,"")}));return 1===o.length?o[0]:null}}export const VoiceBot=new VoiceBotClient;
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Speech detector + noise gate for the 20 ms mic frames (PCM s16le, 16 kHz, mono).
|
|
3
|
+
*
|
|
4
|
+
* Why: in a real room the gaps between commands are full of noise and other people talking, and the
|
|
5
|
+
* server's end-of-speech detection never sees a gap. The gate sends silence (zeros) instead of the
|
|
6
|
+
* room when nobody is speaking near the phone, so the server gets clean gaps. The stream keeps its
|
|
7
|
+
* shape: one 640-byte frame every 20 ms, in order.
|
|
8
|
+
*
|
|
9
|
+
* How:
|
|
10
|
+
* - Each frame's level (dBFS) is compared with a noise floor that follows the room (drops fast,
|
|
11
|
+
* rises slowly). A frame is "loud" when it is `thresholdDb` above the floor and above
|
|
12
|
+
* `minLevelDb`. Speech starts after `startFrames` loud frames in a row.
|
|
13
|
+
* - Frames go out `preRollMs` late, so the frames just before speech started can still be sent as
|
|
14
|
+
* audio (the first syllable isn't cut). After speech, audio keeps going for `hangoverMs`.
|
|
15
|
+
* - While the bot is speaking, `whileSpeaking: 'guard'` asks for `guardExtraDb` more, so the bot's
|
|
16
|
+
* own voice coming back through the mic (after echo cancellation) is not taken as speech.
|
|
17
|
+
* 'mute' sends silence while the bot speaks. 'listen' treats it like any other time.
|
|
18
|
+
* - Barge-in: during the first 500 ms of each reply the gate measures the sound level (the bot's
|
|
19
|
+
* own voice coming back through the mic, plus the room). After that, 300 ms in a row that are
|
|
20
|
+
* `bargeInDb` louder than that level (and loud enough to be speech) count as the user talking
|
|
21
|
+
* over the bot. So the bot's echo, or people already talking in the room, don't stop the reply.
|
|
22
|
+
*/
|
|
23
|
+
export type WhileSpeaking = 'guard' | 'mute' | 'listen';
|
|
24
|
+
export interface NoiseGateOptions {
|
|
25
|
+
/** Send silence instead of room noise. If false, frames pass unchanged (detection still runs). */
|
|
26
|
+
enabled?: boolean;
|
|
27
|
+
/** dB above the room's noise floor that counts as speech. Default 10. Lower = more sensitive. */
|
|
28
|
+
thresholdDb?: number;
|
|
29
|
+
/** Frames quieter than this (dBFS) are never speech. Default -55. */
|
|
30
|
+
minLevelDb?: number;
|
|
31
|
+
/** Audio kept after the last speech frame. Default 700 ms. */
|
|
32
|
+
hangoverMs?: number;
|
|
33
|
+
/** Audio kept before speech starts (adds this much delay to the stream). Default 300 ms. */
|
|
34
|
+
preRollMs?: number;
|
|
35
|
+
/** Extra dB needed while the bot is speaking, in 'guard' mode. Default 8. */
|
|
36
|
+
guardExtraDb?: number;
|
|
37
|
+
/** How much louder than the sound during the start of the reply the user must be to barge in. Default 6. */
|
|
38
|
+
bargeInDb?: number;
|
|
39
|
+
whileSpeaking?: WhileSpeaking;
|
|
40
|
+
}
|
|
41
|
+
export interface GateResult {
|
|
42
|
+
/** The frame to send now (the one from `preRollMs` ago, or silence), or null while filling up. */
|
|
43
|
+
out: Uint8Array | null;
|
|
44
|
+
/** True once when the user starts talking over the bot. */
|
|
45
|
+
bargeIn: boolean;
|
|
46
|
+
/** Speech started (true) or ended (false) on this frame; undefined if nothing changed. */
|
|
47
|
+
speechEvent?: boolean;
|
|
48
|
+
}
|
|
49
|
+
/** Level of one frame of PCM s16le in dBFS (-100 for digital silence). */
|
|
50
|
+
export declare function frameLevelDb(frame: Uint8Array): number;
|
|
51
|
+
export declare class NoiseGate {
|
|
52
|
+
private readonly o;
|
|
53
|
+
private readonly delayFrames;
|
|
54
|
+
private readonly hangFrames;
|
|
55
|
+
private readonly startFrames;
|
|
56
|
+
private readonly bargeInFrames;
|
|
57
|
+
private readonly baselineFrames;
|
|
58
|
+
private wasBotSpeaking;
|
|
59
|
+
private speakFrames;
|
|
60
|
+
private baselineSum;
|
|
61
|
+
private bargeRun;
|
|
62
|
+
private queue;
|
|
63
|
+
private index;
|
|
64
|
+
private lastSpeech;
|
|
65
|
+
private loudRun;
|
|
66
|
+
private floor;
|
|
67
|
+
private inSpeech;
|
|
68
|
+
private bargeInFired;
|
|
69
|
+
private framesOpen;
|
|
70
|
+
private framesOut;
|
|
71
|
+
private lastLevel;
|
|
72
|
+
constructor(options?: NoiseGateOptions);
|
|
73
|
+
get noiseFloorDb(): number;
|
|
74
|
+
get levelDb(): number;
|
|
75
|
+
/** Share of frames sent as audio (the rest went out as silence). */
|
|
76
|
+
get openRatio(): number;
|
|
77
|
+
get speaking(): boolean;
|
|
78
|
+
process(frame: Uint8Array, botSpeaking: boolean): GateResult;
|
|
79
|
+
/** A new reply started playing: measure its level again before barge-in can trigger. */
|
|
80
|
+
newReply(): void;
|
|
81
|
+
/** Frames still in the delay line (sent when the mic stops, so the end of speech isn't lost). */
|
|
82
|
+
flush(): Uint8Array[];
|
|
83
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e=new Uint8Array(640);export function frameLevelDb(e){const s=e.length>>1;if(!s)return-100;let t=0;for(let i=0;i<s;i++){let s=e[2*i]|e[2*i+1]<<8;32768&s&&(s-=65536),t+=s*s}const i=t/s;return i>0?10*Math.log10(i/1073741824):-100}export class NoiseGate{constructor(e={}){this.startFrames=3,this.bargeInFrames=15,this.baselineFrames=25,this.wasBotSpeaking=!1,this.speakFrames=0,this.baselineSum=0,this.bargeRun=0,this.queue=[],this.index=0,this.lastSpeech=-1e9,this.loudRun=0,this.floor=null,this.inSpeech=!1,this.bargeInFired=!1,this.framesOpen=0,this.framesOut=0,this.lastLevel=-100,this.o={enabled:e.enabled??!0,thresholdDb:e.thresholdDb??10,minLevelDb:e.minLevelDb??-55,hangoverMs:e.hangoverMs??700,preRollMs:e.preRollMs??300,guardExtraDb:e.guardExtraDb??8,bargeInDb:e.bargeInDb??6,whileSpeaking:e.whileSpeaking??"guard"},this.delayFrames=this.o.enabled?Math.max(0,Math.round(this.o.preRollMs/20)):0,this.hangFrames=Math.max(0,Math.round(this.o.hangoverMs/20))}get noiseFloorDb(){return this.floor??-100}get levelDb(){return this.lastLevel}get openRatio(){return this.framesOut?this.framesOpen/this.framesOut:0}get speaking(){return this.inSpeech}process(s,t){const i=frameLevelDb(s);this.lastLevel=i,null===this.floor?this.floor=i:i<this.floor?this.floor+=.3*(i-this.floor):this.floor+=.001*Math.min(i-this.floor,20);const h=t&&"mute"===this.o.whileSpeaking,a=t&&"guard"===this.o.whileSpeaking?this.o.guardExtraDb:0,r=!h&&i>this.o.minLevelDb+a&&i>this.floor+this.o.thresholdDb+a;this.loudRun=r?this.loudRun+1:0;const n=this.index++;let l;this.loudRun>=this.startFrames&&(this.lastSpeech=n);const o=n-this.lastSpeech<=this.hangFrames;o!==this.inSpeech&&(this.inSpeech=o,l=o);let u=!1;if(t&&!this.wasBotSpeaking&&(this.speakFrames=0,this.baselineSum=0,this.bargeRun=0,this.bargeInFired=!1),this.wasBotSpeaking=t,t&&!h)if(this.speakFrames++,this.speakFrames<=this.baselineFrames)this.baselineSum+=i;else if(!this.bargeInFired){const e=this.baselineSum/this.baselineFrames,s=r&&i>e+this.o.bargeInDb;this.bargeRun=s?this.bargeRun+1:0,this.bargeRun>=this.bargeInFrames&&(this.bargeInFired=!0,u=!0)}if(h)return this.queue=[],this.framesOut++,{out:e,bargeIn:u,speechEvent:l};if(this.queue.push(s),this.queue.length<=this.delayFrames)return{out:null,bargeIn:u,speechEvent:l};const b=this.queue.shift(),g=n-this.delayFrames,m=!this.o.enabled||this.lastSpeech>=g-this.hangFrames;return this.framesOut++,m&&this.framesOpen++,{out:m?b:e,bargeIn:u,speechEvent:l}}newReply(){this.speakFrames=0,this.baselineSum=0,this.bargeRun=0,this.bargeInFired=!1}flush(){const s=this.queue.map(((s,t)=>{const i=this.index-this.queue.length+t;return!this.o.enabled||this.lastSpeech>=i-this.hangFrames?s:e}));return this.queue=[],s}}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/** Decodes standard base64 into bytes (no dependency on atob/Buffer). */
|
|
2
|
+
export declare function base64ToBytes(b64: string): Uint8Array;
|
|
3
|
+
/** Number of bytes a base64 string decodes to, without decoding it. */
|
|
4
|
+
export declare function base64ByteLength(b64: string): number;
|
|
5
|
+
/** Encodes bytes as standard base64 (no dependency on btoa/Buffer). */
|
|
6
|
+
export declare function bytesToBase64(bytes: Uint8Array): string;
|
package/build/base64.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e=new Uint8Array(256);for(let r=0;r<64;r++)e[t.charCodeAt(r)]=r;export function base64ToBytes(t){const r=t.replace(/[^A-Za-z0-9+/]/g,""),n=r.length,o=new Uint8Array(Math.floor(3*n/4));let a=0;for(let t=0;t<n;t+=4){const c=e[r.charCodeAt(t)],h=e[r.charCodeAt(t+1)],s=t+2<n?e[r.charCodeAt(t+2)]:0,l=t+3<n?e[r.charCodeAt(t+3)]:0;o[a++]=c<<2|h>>4,t+2<n&&(o[a++]=(15&h)<<4|s>>2),t+3<n&&(o[a++]=(3&s)<<6|l)}return a===o.length?o:o.subarray(0,a)}export function base64ByteLength(t){const e=t.length;if(0===e)return 0;let r=0;return t.endsWith("==")?r=2:t.endsWith("=")&&(r=1),Math.floor(3*e/4)-r}export function bytesToBase64(e){let r="";const n=e.length;for(let o=0;o<n;o+=3){const a=e[o],c=o+1<n?e[o+1]:0,h=o+2<n?e[o+2]:0;r+=t[a>>2]+t[(3&a)<<4|c>>4],r+=o+1<n?t[(15&c)<<2|h>>6]:"=",r+=o+2<n?t[63&h]:"="}return r}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type SitemapType } from 'expo-router';
|
|
2
|
+
import type { ScreenInfo } from './protocol';
|
|
3
|
+
import type { NavigationAdapter } from './navigation/types';
|
|
4
|
+
export interface ExpoRouterNavigationOptions {
|
|
5
|
+
/** Route names to leave out (e.g. `['modal', 'settings/debug']`). */
|
|
6
|
+
exclude?: string[];
|
|
7
|
+
}
|
|
8
|
+
/** `./(tabs)/index.tsx` → `(tabs)/index`; `./product/[id].android.tsx` → `product/[id]`. */
|
|
9
|
+
export declare function routeNameFromContextKey(key: string): string;
|
|
10
|
+
/** `(tabs)/index` → `/`; `product/[id]` → `/product/[id]` (groups and `index` removed). */
|
|
11
|
+
export declare function routePathFromName(name: string): string;
|
|
12
|
+
/** Collects the screen routes (no layouts, no internal or generated routes) from the sitemap. */
|
|
13
|
+
export declare function screensFromSitemap(root: SitemapType | null, exclude?: string[]): ScreenInfo[];
|
|
14
|
+
/** Hook that returns a navigation adapter for Expo Router. Call it in your root `_layout.tsx`. */
|
|
15
|
+
export declare function useExpoRouterNavigation(options?: ExpoRouterNavigationOptions): NavigationAdapter;
|
|
16
|
+
export type { NavigationAdapter } from './navigation/types';
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{useMemo as e}from"react";import{router as t,useNavigationContainerRef as r,useSitemap as o}from"expo-router";import{flattenBackStack as n}from"./navigation/state";const a=/(^|\/)_layout$/;export function routeNameFromContextKey(e){return e.replace(/^\.\//,"").replace(/(\.(ios|android|web|native))?\.[jt]sx?$/,"")}export function routePathFromName(e){return"/"+e.split("/").filter((e=>e&&"index"!==e&&!/^\(.*\)$/.test(e))).join("/")}export function screensFromSitemap(e,t=[]){const r=new Map,o=new Set(t),n=e=>{const t=routeNameFromContextKey(e.contextKey),s=t.split("/").pop()??"";!!(a.test(t)||e.isInternal||e.isGenerated||s.startsWith("+")||s.startsWith("_"))||o.has(t)||r.has(t)||r.set(t,{name:t,path:routePathFromName(t)}),e.children.forEach(n)};return e&&n(e),[...r.values()].sort(((e,t)=>e.name.localeCompare(t.name)))}function s(e,t){const r="/"+e.name.split("/").filter((e=>"index"!==e)).join("/");return t&&Object.keys(t).length?{pathname:r,params:t}:r}export function useExpoRouterNavigation(a={}){const i=r(),c=o(),u=(a.exclude??[]).join("|");return e((()=>{const e=screensFromSitemap(c,a.exclude),r=()=>{return n(i?.isReady()?(e=i.getRootState())&&1===e.routes?.length&&"__root"===e.routes[0].name?e.routes[0].state:e:void 0,!0);var e};return{kind:"expo-router",getScreens:()=>e,getCurrentScreen:()=>{const e=r();return e.length?e[e.length-1]:null},getBackStack:r,push:(e,r)=>t.push(s(e,r)),popTo:(e,r)=>t.dismissTo(s(e,r)),goBack:()=>!!t.canGoBack()&&(t.back(),!0),subscribe:e=>i.addListener("state",(()=>e()))}}),[i,c,u])}
|
package/build/index.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export { VoiceBot, VoiceBotClient } from './VoiceBotClient';
|
|
2
|
+
export type { ConnectOptions, VoiceBotError, VoiceBotState, VoiceBotStatus } from './VoiceBotClient';
|
|
3
|
+
export { VoiceBotProvider } from './react/VoiceBotProvider';
|
|
4
|
+
export type { VoiceBotProviderProps } from './react/VoiceBotProvider';
|
|
5
|
+
export { VoiceBotWidget } from './react/VoiceBotWidget';
|
|
6
|
+
export type { VoiceBotWidgetProps } from './react/VoiceBotWidget';
|
|
7
|
+
export { useVoiceBot } from './react/useVoiceBot';
|
|
8
|
+
export type { UseVoiceBot } from './react/useVoiceBot';
|
|
9
|
+
export type { NavigationAdapter, NavParams } from './navigation/types';
|
|
10
|
+
export { createReactNavigationAdapter } from './navigation/reactNavigation';
|
|
11
|
+
export type { NavigationRefLike, ReactNavigationAdapterOptions } from './navigation/reactNavigation';
|
|
12
|
+
export { createCallbackNavigation } from './navigation/callbackNavigation';
|
|
13
|
+
export type { CallbackNavigationAdapter, CallbackNavigationOptions } from './navigation/callbackNavigation';
|
|
14
|
+
export { flattenBackStack } from './navigation/state';
|
|
15
|
+
export { isNativeAvailable } from './NativeAudio';
|
|
16
|
+
export { NoiseGate, frameLevelDb } from './audio/noiseGate';
|
|
17
|
+
export type { NoiseGateOptions, WhileSpeaking } from './audio/noiseGate';
|
|
18
|
+
export { setLogLevel, getLogLevel, setLogHandler } from './logger';
|
|
19
|
+
export type { LogLevel, LogHandler } from './logger';
|
|
20
|
+
export * from './protocol';
|
package/build/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{VoiceBot,VoiceBotClient}from"./VoiceBotClient";export{VoiceBotProvider}from"./react/VoiceBotProvider";export{VoiceBotWidget}from"./react/VoiceBotWidget";export{useVoiceBot}from"./react/useVoiceBot";export{createReactNavigationAdapter}from"./navigation/reactNavigation";export{createCallbackNavigation}from"./navigation/callbackNavigation";export{flattenBackStack}from"./navigation/state";export{isNativeAvailable}from"./NativeAudio";export{NoiseGate,frameLevelDb}from"./audio/noiseGate";export{setLogLevel,getLogLevel,setLogHandler}from"./logger";export*from"./protocol";
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Console logging for the SDK.
|
|
3
|
+
*
|
|
4
|
+
* Every line starts with `[VoiceBot]`, the time and a level, e.g.
|
|
5
|
+
* [VoiceBot] 14:41:41.512 INFO connected session=81185a05-…
|
|
6
|
+
*
|
|
7
|
+
* Levels, most to least detail: trace < debug < info < warn < error < none.
|
|
8
|
+
* - trace: also every single 640-byte audio frame (50 lines a second)
|
|
9
|
+
* - debug: every request and response in full (JSON), audio in 5 s summaries
|
|
10
|
+
* Default: `debug` in development builds, `warn` in release builds.
|
|
11
|
+
*/
|
|
12
|
+
export type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error' | 'none';
|
|
13
|
+
/** Your own log sink (e.g. to send SDK logs to a crash reporter). */
|
|
14
|
+
export type LogHandler = (level: Exclude<LogLevel, 'none'>, message: string, data?: unknown) => void;
|
|
15
|
+
/** Sets how much the SDK logs. `debug` logs every request and response; `trace` also every audio frame. */
|
|
16
|
+
export declare function setLogLevel(next: LogLevel): void;
|
|
17
|
+
export declare function getLogLevel(): LogLevel;
|
|
18
|
+
/**
|
|
19
|
+
* Sends SDK logs to your own function instead of the console. Pass `null` to log to the console
|
|
20
|
+
* again. The level set with `setLogLevel` still applies.
|
|
21
|
+
*/
|
|
22
|
+
export declare function setLogHandler(next: LogHandler | null): void;
|
|
23
|
+
export declare const logger: {
|
|
24
|
+
trace: (message: string, data?: unknown) => void;
|
|
25
|
+
debug: (message: string, data?: unknown) => void;
|
|
26
|
+
info: (message: string, data?: unknown) => void;
|
|
27
|
+
warn: (message: string, data?: unknown) => void;
|
|
28
|
+
error: (message: string, data?: unknown) => void;
|
|
29
|
+
isEnabled: (lvl: Exclude<LogLevel, "none">) => boolean;
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* JSON text for the log. Base64 audio (`buffer`, `data`) is replaced by its size so the console
|
|
33
|
+
* stays readable; everything else is kept in full unless `max` is given.
|
|
34
|
+
*/
|
|
35
|
+
export declare function preview(value: unknown, max?: number): string;
|
package/build/logger.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const e={trace:-1,debug:0,info:1,warn:2,error:3,none:4};let t="undefined"==typeof __DEV__||__DEV__?"debug":"warn",r=null;export function setLogLevel(e){t=e}export function getLogLevel(){return t}export function setLogHandler(e){r=e}function n(n,o,i){if(e[n]<e[t])return;if(r){try{r(n,o,i)}catch{}return}const c=`[VoiceBot] ${function(){const e=new Date,t=(e,t=2)=>String(e).padStart(t,"0");return`${t(e.getHours())}:${t(e.getMinutes())}:${t(e.getSeconds())}.${t(e.getMilliseconds(),3)}`}()} ${n.toUpperCase().padEnd(5)} ${o}`,s="error"===n?console.error:"warn"===n?console.warn:console.log;void 0===i?s(c):s(c,i)}export const logger={trace:(e,t)=>n("trace",e,t),debug:(e,t)=>n("debug",e,t),info:(e,t)=>n("info",e,t),warn:(e,t)=>n("warn",e,t),error:(e,t)=>n("error",e,t),isEnabled:r=>e[r]>=e[t]};export function preview(e,t=1/0){let r;try{if(r="string"==typeof e?e:JSON.stringify(e,((e,t)=>"string"==typeof t&&t.length>80&&("buffer"===e||"data"===e)?`<base64 ${t.length} chars = ${Math.floor(3*t.length/4)-(t.endsWith("==")?2:t.endsWith("=")?1:0)} bytes>`:t)),"string"==typeof e&&(r.includes('"buffer"')||r.includes('"data"')))try{r=preview(JSON.parse(r),t)}catch{}}catch{r=String(e)}return r.length>t?`${r.slice(0,t)}… (${r.length} chars)`:r}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { ScreenInfo } from '../protocol';
|
|
2
|
+
import type { NavigationAdapter, NavParams } from './types';
|
|
3
|
+
export interface CallbackNavigationOptions {
|
|
4
|
+
/** Screens the server may open (names, or `{ name, path }`). */
|
|
5
|
+
screens: (string | ScreenInfo)[];
|
|
6
|
+
/** The screen the app starts on. Defaults to the first screen. */
|
|
7
|
+
initialScreen?: string;
|
|
8
|
+
/**
|
|
9
|
+
* Called when the server asks to open a screen. `action` is `push` for a new screen
|
|
10
|
+
* and `popTo` when the screen is already in the back stack (remove the ones above it).
|
|
11
|
+
* Return or resolve `false` to report a failure.
|
|
12
|
+
*/
|
|
13
|
+
onNavigate(screen: ScreenInfo, info: {
|
|
14
|
+
action: 'push' | 'popTo';
|
|
15
|
+
params?: NavParams;
|
|
16
|
+
}): void | boolean | Promise<void | boolean>;
|
|
17
|
+
/** Called for `back`. Return false when there is nothing to go back to. Defaults to popping the SDK's stack. */
|
|
18
|
+
onBack?(): void | boolean | Promise<void | boolean>;
|
|
19
|
+
}
|
|
20
|
+
export interface CallbackNavigationAdapter extends NavigationAdapter {
|
|
21
|
+
/** Tell the SDK the user moved to `screen` by hand (tap, Back button). Same back stack rules. */
|
|
22
|
+
setCurrentScreen(screen: string): void;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* For apps with their own navigation (or none of the supported libraries): the SDK keeps
|
|
26
|
+
* the back stack and calls your `onNavigate` / `onBack` callbacks.
|
|
27
|
+
*/
|
|
28
|
+
export declare function createCallbackNavigation(options: CallbackNavigationOptions): CallbackNavigationAdapter;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export function createCallbackNavigation(e){const n=e.screens.map((e=>"string"==typeof e?{name:e}:e)),t=e.initialScreen??n[0]?.name;let a=t?[t]:[];const r=new Set,o=()=>r.forEach((e=>e())),c=e=>{const n=a.indexOf(e);a=n>=0?a.slice(0,n+1):[...a,e]};return{kind:"custom",getScreens:()=>n,getCurrentScreen:()=>a[a.length-1]??null,getBackStack:()=>[...a],async push(n,t){if(!1===await e.onNavigate(n,{action:"push",params:t}))throw new Error("Host refused to navigate");c(n.name),o()},async popTo(n,t){if(!1===await e.onNavigate(n,{action:"popTo",params:t}))throw new Error("Host refused to navigate");c(n.name),o()},async goBack(){if(e.onBack){if(!1===await e.onBack())return!1}else if(a.length<=1)return!1;return a.length>1&&(a=a.slice(0,-1)),o(),!0},setCurrentScreen(e){a[a.length-1]!==e&&(c(e),o())},subscribe:e=>(r.add(e),()=>r.delete(e))}}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { NavigationAdapter } from './types';
|
|
2
|
+
/** The parts of a React Navigation `NavigationContainerRef` the adapter uses. */
|
|
3
|
+
export interface NavigationRefLike {
|
|
4
|
+
isReady(): boolean;
|
|
5
|
+
getRootState(): any;
|
|
6
|
+
navigate(...args: any[]): void;
|
|
7
|
+
dispatch(action: any): void;
|
|
8
|
+
canGoBack(): boolean;
|
|
9
|
+
goBack(): void;
|
|
10
|
+
addListener(event: 'state', cb: (e: any) => void): () => void;
|
|
11
|
+
}
|
|
12
|
+
export interface ReactNavigationAdapterOptions {
|
|
13
|
+
/**
|
|
14
|
+
* Screens the server may open. Defaults to every route name found in the currently
|
|
15
|
+
* mounted navigators. List them here if some nested navigators mount lazily.
|
|
16
|
+
* Use `{ name, parents: ['Root', 'Tabs'] }` for screens inside nested navigators.
|
|
17
|
+
*/
|
|
18
|
+
screens?: (string | {
|
|
19
|
+
name: string;
|
|
20
|
+
parents?: string[];
|
|
21
|
+
})[];
|
|
22
|
+
/** Screen names to leave out of the list. */
|
|
23
|
+
exclude?: string[];
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Adapter for React Navigation (v7) using a navigation container ref:
|
|
27
|
+
*
|
|
28
|
+
* ```ts
|
|
29
|
+
* const navigationRef = createNavigationContainerRef();
|
|
30
|
+
* const navigation = createReactNavigationAdapter(navigationRef);
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
export declare function createReactNavigationAdapter(ref: NavigationRefLike, options?: ReactNavigationAdapterOptions): NavigationAdapter;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{flattenBackStack as e,focusedLeaf as t}from"./state";export function createReactNavigationAdapter(a,s={}){const n=new Map;for(const e of s.screens??[])"string"!=typeof e&&e.parents&&n.set(e.name,e.parents);const r=(e,t,a)=>{if(e){for(const s of e.routeNames??e.routes.map((e=>e.name)))a.has(s)||a.set(s,t);for(const s of e.routes)s.state&&Array.isArray(s.state.routes)&&r(s.state,[...t,s.name],a)}},o=()=>a.isReady()?a.getRootState():void 0;return{kind:"react-navigation",getScreens(){const e=new Set(s.exclude??[]);let t;if(s.screens)t=s.screens.map((e=>"string"==typeof e?e:e.name));else{const e=new Map;r(o(),[],e),e.forEach(((e,t)=>{n.has(t)||n.set(t,e)}));const a=new Set;e.forEach((e=>e.forEach((e=>a.add(e))))),t=[...e.keys()].filter((e=>!a.has(e)))}return[...new Set(t)].filter((t=>!e.has(t))).sort().map((e=>({name:e})))},getCurrentScreen:()=>t(o(),!1),getBackStack:()=>e(o(),!1),push(e,t){const s=n.get(e.name)??[];if(0===s.length)return void a.navigate(e.name,t);let r={screen:e.name,params:t};for(let e=s.length-1;e>0;e--)r={screen:s[e],params:r};a.navigate(s[0],r)},popTo(e,t){a.dispatch({type:"POP_TO",payload:{name:e.name,params:t}})},goBack:()=>!(!a.isReady()||!a.canGoBack()||(a.goBack(),0)),subscribe:e=>a.addListener("state",(()=>e()))}}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** Minimal shape of a React Navigation state (also used by Expo Router). */
|
|
2
|
+
export interface NavStateLike {
|
|
3
|
+
type?: string;
|
|
4
|
+
index?: number;
|
|
5
|
+
routes: {
|
|
6
|
+
name: string;
|
|
7
|
+
state?: NavStateLike | Partial<NavStateLike>;
|
|
8
|
+
}[];
|
|
9
|
+
routeNames?: string[];
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Flattens a navigation state into a bottom → top list of leaf screen names.
|
|
13
|
+
*
|
|
14
|
+
* - Stack navigators contribute every route up to the focused one.
|
|
15
|
+
* - Tab/drawer navigators contribute only their focused route (they have no back stack).
|
|
16
|
+
* - `nestedNames` true joins parent and child names (`(tabs)/index`), as Expo Router does.
|
|
17
|
+
*/
|
|
18
|
+
export declare function flattenBackStack(state: NavStateLike | undefined, nestedNames: boolean, prefix?: string): string[];
|
|
19
|
+
/** Name of the focused leaf screen. */
|
|
20
|
+
export declare function focusedLeaf(state: NavStateLike | undefined, nestedNames: boolean): string | null;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const t=(t,e,n)=>n&&t?`${t}/${e}`:e;export function flattenBackStack(e,n,r=""){if(!e||!Array.isArray(e.routes)||0===e.routes.length)return[];const a=Math.min(e.index??e.routes.length-1,e.routes.length-1),s=[];for(let o="stack"===e.type||null==e.type?0:a;o<=a;o++){const a=e.routes[o],u=t(r,a.name,n),c=a.state;c&&Array.isArray(c.routes)&&c.routes.length>0?s.push(...flattenBackStack(c,n,u)):s.push(u)}return s}export function focusedLeaf(t,e){const n=flattenBackStack(t,e);return n.length?n[n.length-1]:null}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { ScreenInfo } from '../protocol';
|
|
2
|
+
export type NavParams = Record<string, string | number>;
|
|
3
|
+
/**
|
|
4
|
+
* Bridge between the SDK and the host app's navigation library.
|
|
5
|
+
*
|
|
6
|
+
* The SDK decides *what* to do (push, pop back, back, already there) from the back stack
|
|
7
|
+
* rules; the adapter only performs the action. Ready-made adapters exist for Expo Router
|
|
8
|
+
* (`react-native-voice-bot-sdk/expo-router`), React Navigation, and a plain callback.
|
|
9
|
+
*/
|
|
10
|
+
export interface NavigationAdapter {
|
|
11
|
+
/** `expo-router`, `react-navigation`, `custom`, ... (sent to the server). */
|
|
12
|
+
readonly kind: string;
|
|
13
|
+
/** All navigable screens. Names only. */
|
|
14
|
+
getScreens(): ScreenInfo[];
|
|
15
|
+
/** Name of the visible screen, or null if navigation isn't ready yet. */
|
|
16
|
+
getCurrentScreen(): string | null;
|
|
17
|
+
/** Screen names bottom → top; the last item is the visible screen. */
|
|
18
|
+
getBackStack(): string[];
|
|
19
|
+
/** Open a screen that isn't in the back stack (push on top). */
|
|
20
|
+
push(screen: ScreenInfo, params?: NavParams): void | Promise<void>;
|
|
21
|
+
/** Go back to a screen that is already in the back stack (remove the screens above it). */
|
|
22
|
+
popTo(screen: ScreenInfo, params?: NavParams): void | Promise<void>;
|
|
23
|
+
/** Like the system Back button. Resolves false when there is nothing to go back to. */
|
|
24
|
+
goBack(): boolean | Promise<boolean>;
|
|
25
|
+
/** Calls `listener` whenever the visible screen or back stack may have changed. */
|
|
26
|
+
subscribe(listener: () => void): () => void;
|
|
27
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export{};
|