@guava-ai/guava-sdk 0.37.0 → 0.38.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/src/sip.ts ADDED
@@ -0,0 +1,62 @@
1
+ // Characters allowed unescaped in each component beyond RFC 3261's `unreserved`,
2
+ // which encodeURIComponent already leaves alone. See RFC 3261 section 25.1.
3
+ const USER_SAFE = "&=+$,;?/";
4
+ const PARAM_SAFE = "[]/:&+$";
5
+ const HEADER_SAFE = "[]/?:+$";
6
+
7
+ function sipEscape(value: string, safe: string): string {
8
+ return encodeURIComponent(value).replace(/%[0-9A-F]{2}/g, (escaped) => {
9
+ // Not decodeURIComponent, which throws on single bytes of multibyte UTF-8 sequences.
10
+ const char = String.fromCharCode(Number.parseInt(escaped.slice(1), 16));
11
+ return safe.includes(char) ? char : escaped;
12
+ });
13
+ }
14
+
15
+ export class SipUri {
16
+ host: string;
17
+ user?: string;
18
+ /** A `null` value renders as a valueless param, e.g. `;lr`. */
19
+ uriParams: Record<string, string | null>;
20
+ /** A `null` value renders as a valueless header, e.g. `?X-Foo=`. */
21
+ headers: Record<string, string | null>;
22
+
23
+ constructor(args: {
24
+ host: string;
25
+ user?: string;
26
+ uriParams?: Record<string, string | null>;
27
+ headers?: Record<string, string | null>;
28
+ }) {
29
+ this.host = args.host;
30
+ this.user = args.user;
31
+ this.uriParams = args.uriParams ?? {};
32
+ this.headers = args.headers ?? {};
33
+ }
34
+
35
+ toString(): string {
36
+ let url = "sip:";
37
+ if (this.user !== undefined) {
38
+ url += `${sipEscape(this.user, USER_SAFE)}@`;
39
+ }
40
+ url += this.host;
41
+
42
+ for (const [name, value] of Object.entries(this.uriParams)) {
43
+ url += `;${sipEscape(name, PARAM_SAFE)}`;
44
+ if (value !== null) {
45
+ url += `=${sipEscape(value, PARAM_SAFE)}`;
46
+ }
47
+ }
48
+
49
+ // Headers always need an "=", so a null value renders as "name=".
50
+ const headers = Object.entries(this.headers);
51
+ if (headers.length > 0) {
52
+ url += `?${headers
53
+ .map(
54
+ ([name, value]) =>
55
+ `${sipEscape(name, HEADER_SAFE)}=${sipEscape(value === null ? "" : String(value), HEADER_SAFE)}`,
56
+ )
57
+ .join("&")}`;
58
+ }
59
+
60
+ return url;
61
+ }
62
+ }
package/src/version.ts CHANGED
@@ -1 +1 @@
1
- export const SDK_VERSION = "0.37.0";
1
+ export const SDK_VERSION = "0.38.0";
@@ -0,0 +1,372 @@
1
+ import { type ConnectingTone, JingleTone } from "./tones.ts";
2
+
3
+ export { type ConnectingTone, JingleTone, RingbackTone } from "./tones.ts";
4
+
5
+ export type CallState =
6
+ | "not-started" // start() hasn't been called yet.
7
+ | "starting" // Starting the call. Do not play a Ringback yet.
8
+ | "waiting-for-permission" // We're waiting for the Microphone permission prompt. You may show a reminder UI here.
9
+ | "connecting" // The call is now connection to the remote. This is where you can play a ringback or other connecting tone.
10
+ | "connected" // The call is now connected and the audio channel is established.
11
+ | "ended"; // The call has ended.
12
+
13
+ export type CallErrorCode =
14
+ | "MICROPHONE_ACCESS_FAILED"
15
+ | "CONNECTION_FAILED"
16
+ | "AUTHENTICATION_FAILED"
17
+ | "PROTOCOL_ERROR" // The server sent an unexpected message.
18
+ | "SERVER_ERROR" // The server sent an error message.
19
+ | "REMOTE_HANGUP"; // The remote hung up before the call connected.
20
+
21
+ export class CallError extends Error {
22
+ readonly code: CallErrorCode;
23
+
24
+ constructor(code: CallErrorCode, message: string, options?: ErrorOptions) {
25
+ super(message, options);
26
+ this.name = "CallError";
27
+ this.code = code;
28
+ }
29
+ }
30
+
31
+ // Used if the server doesn't send ICE servers with the auth reply.
32
+ const DEFAULT_ICE_SERVERS: RTCIceServer[] = [
33
+ { urls: ["stun:stun.l.google.com:19302", "stun:stun.sipgate.net:10000"] },
34
+ ];
35
+
36
+ const SOCKET_PROTOCOLS: Record<string, string> = {
37
+ "http:": "ws:",
38
+ "https:": "wss:",
39
+ "ws:": "ws:",
40
+ "wss:": "wss:",
41
+ };
42
+
43
+ // Messages received on the signaling socket. See junkswitch/junkswitch/webrtcsocket.py.
44
+ type SignalingMessage =
45
+ | {
46
+ type: "auth";
47
+ body: "OK" | "FAIL";
48
+ reason?: string;
49
+ ice_servers?: RTCIceServer[];
50
+ }
51
+ | { type: "desc"; body: RTCSessionDescriptionInit }
52
+ | { type: "candidate"; body: RTCIceCandidateInit }
53
+ | { type: "hangup" }
54
+ | { type: "error"; body?: string }
55
+ | { type: "transfer" };
56
+
57
+ export class Call {
58
+ private _state: CallState = "not-started";
59
+ private _error?: CallError;
60
+ private readonly _stateHandlers = new Set<(state: CallState) => void>();
61
+ private readonly _remoteStreamHandlers = new Set<(stream: MediaStream) => void>();
62
+ private readonly _webrtcCode: string;
63
+ private readonly _sockUrl: URL;
64
+ private readonly _remoteAudio: HTMLAudioElement;
65
+ private readonly _connectingTone?: ConnectingTone;
66
+ private _sock?: WebSocket;
67
+ private _localStream?: MediaStream;
68
+ private _peerConnection?: RTCPeerConnection;
69
+ private _remoteStream?: MediaStream;
70
+ private _iceServers?: RTCIceServer[];
71
+ // Settles the promise returned by start().
72
+ private _pendingStart?: { resolve: () => void; reject: (error: CallError) => void };
73
+
74
+ constructor({
75
+ webrtcCode,
76
+ baseUrl = "https://app.goguava.ai/",
77
+ connectingTone = new JingleTone(),
78
+ }: {
79
+ webrtcCode: string;
80
+ baseUrl?: string;
81
+ // Played while the call is in the "connecting" state.
82
+ connectingTone?: ConnectingTone | "disabled";
83
+ }) {
84
+ this._webrtcCode = webrtcCode;
85
+ if (connectingTone !== "disabled") {
86
+ this._connectingTone = connectingTone;
87
+ }
88
+
89
+ this._sockUrl = new URL("/webrtc/", baseUrl);
90
+ const sockProtocol = SOCKET_PROTOCOLS[this._sockUrl.protocol];
91
+ if (sockProtocol === undefined) {
92
+ throw new Error(`Unsupported baseUrl protocol: ${this._sockUrl.protocol}`);
93
+ }
94
+ this._sockUrl.protocol = sockProtocol;
95
+
96
+ this._remoteAudio = document.createElement("audio");
97
+ this._remoteAudio.autoplay = true;
98
+ }
99
+
100
+ get state(): CallState {
101
+ return this._state;
102
+ }
103
+
104
+ // Set if the call ended due to a failure.
105
+ get error(): CallError | undefined {
106
+ return this._error;
107
+ }
108
+
109
+ // Set once the remote audio track arrives, which happens before the call reaches "connected".
110
+ get remoteStream(): MediaStream | undefined {
111
+ return this._remoteStream;
112
+ }
113
+
114
+ // Returns a function that unregisters the handler.
115
+ onStateChange(handler: (state: CallState) => void): () => void {
116
+ this._stateHandlers.add(handler);
117
+ return () => {
118
+ this._stateHandlers.delete(handler);
119
+ };
120
+ }
121
+
122
+ // Fires whenever the remote stream is replaced, including the first time it arrives.
123
+ // Returns a function that unregisters the handler.
124
+ onRemoteStream(handler: (stream: MediaStream) => void): () => void {
125
+ this._remoteStreamHandlers.add(handler);
126
+ return () => {
127
+ this._remoteStreamHandlers.delete(handler);
128
+ };
129
+ }
130
+
131
+ private _setState(state: CallState) {
132
+ if (state === this._state) {
133
+ return;
134
+ }
135
+ this._state = state;
136
+ if (state === "connecting") {
137
+ this._connectingTone?.start();
138
+ } else {
139
+ this._connectingTone?.stop();
140
+ }
141
+ for (const handler of this._stateHandlers) {
142
+ handler(state);
143
+ }
144
+ }
145
+
146
+ async start() {
147
+ if (this._state !== "not-started") {
148
+ throw new Error(`start() was already called.`);
149
+ }
150
+ this._setState("starting");
151
+
152
+ // Add the audio element.
153
+ document.body.appendChild(this._remoteAudio);
154
+
155
+ // We start by requesting device permissions first. The idea is that, after permission has been granted,
156
+ // it makes sence to play a ringback, but it doesn't make sense to do so during the permission prompt.
157
+
158
+ const permissionTimer = setTimeout(() => {
159
+ this._setState("waiting-for-permission");
160
+ }, 500);
161
+
162
+ try {
163
+ this._localStream = await navigator.mediaDevices.getUserMedia({ audio: true, video: false });
164
+ } catch (error) {
165
+ const callError = new CallError("MICROPHONE_ACCESS_FAILED", "Failed to access microphone.", {
166
+ cause: error,
167
+ });
168
+ this._end(callError);
169
+ throw callError;
170
+ } finally {
171
+ clearTimeout(permissionTimer);
172
+ }
173
+
174
+ // hangup() was called during the permission prompt.
175
+ if (this.state === "ended") {
176
+ this._teardown();
177
+ return;
178
+ }
179
+
180
+ // Now open and authenticate the signaling socket.
181
+ this._setState("connecting"); // UI can start playing rinback tones here.
182
+ const started = new Promise<void>((resolve, reject) => {
183
+ this._pendingStart = { resolve, reject };
184
+ });
185
+
186
+ this._sock = new WebSocket(this._sockUrl);
187
+ this._sock.onopen = () => {
188
+ this._send({ type: "auth", body: this._webrtcCode });
189
+ };
190
+ this._sock.onmessage = (event) => {
191
+ this._onMessage(JSON.parse(event.data) as SignalingMessage);
192
+ };
193
+ this._sock.onclose = () => {
194
+ this._end(new CallError("CONNECTION_FAILED", "Signaling connection closed."));
195
+ };
196
+
197
+ await started;
198
+ }
199
+
200
+ async hangup() {
201
+ if (this._state === "not-started") {
202
+ throw new Error(`hangup() called before start().`);
203
+ }
204
+ if (this._state === "ended") {
205
+ return;
206
+ }
207
+ this._send({ type: "hangup" });
208
+ this._end();
209
+ }
210
+
211
+ private _send(message: { type: string; body?: unknown }) {
212
+ if (this._sock !== undefined && this._sock.readyState === WebSocket.OPEN) {
213
+ this._sock.send(JSON.stringify(message));
214
+ }
215
+ }
216
+
217
+ private _onMessage(message: SignalingMessage) {
218
+ switch (message.type) {
219
+ case "auth":
220
+ if (message.body !== "OK") {
221
+ this._end(
222
+ new CallError("AUTHENTICATION_FAILED", message.reason || "Authentication failed."),
223
+ );
224
+ return;
225
+ }
226
+ this._iceServers = message.ice_servers;
227
+ this._send({ type: "connect", body: {} });
228
+ void this._connectPeer();
229
+ break;
230
+ case "desc":
231
+ if (!this._peerConnection) {
232
+ this._end(
233
+ new CallError(
234
+ "PROTOCOL_ERROR",
235
+ "Received desc before the peer connection was created.",
236
+ ),
237
+ );
238
+ return;
239
+ }
240
+ this._peerConnection.setRemoteDescription(message.body).catch((error) => {
241
+ this._end(
242
+ new CallError("CONNECTION_FAILED", "Failed to set remote description.", {
243
+ cause: error,
244
+ }),
245
+ );
246
+ });
247
+ break;
248
+ case "candidate":
249
+ if (!this._peerConnection) {
250
+ this._end(
251
+ new CallError(
252
+ "PROTOCOL_ERROR",
253
+ "Received candidate before the peer connection was created.",
254
+ ),
255
+ );
256
+ return;
257
+ }
258
+ this._peerConnection.addIceCandidate(message.body).catch((error) => {
259
+ console.warn("Failed to add ICE candidate:", error);
260
+ });
261
+ break;
262
+ case "hangup":
263
+ if (this._state === "connected") {
264
+ this._end();
265
+ } else {
266
+ this._end(
267
+ new CallError("REMOTE_HANGUP", "The remote hung up before the call connected."),
268
+ );
269
+ }
270
+ break;
271
+ case "error":
272
+ this._end(new CallError("SERVER_ERROR", message.body || "Unknown server error."));
273
+ break;
274
+ case "transfer":
275
+ this._end(new CallError("PROTOCOL_ERROR", "Transfers are not supported."));
276
+ break;
277
+ default:
278
+ console.warn("Unknown signaling message:", message);
279
+ }
280
+ }
281
+
282
+ private async _connectPeer() {
283
+ if (!this._localStream) {
284
+ return;
285
+ }
286
+ this._peerConnection = new RTCPeerConnection({
287
+ iceServers: this._iceServers ?? DEFAULT_ICE_SERVERS,
288
+ });
289
+ this._peerConnection.onicecandidate = (event) => {
290
+ if (event.candidate) {
291
+ this._send({ type: "candidate", body: event.candidate });
292
+ }
293
+ };
294
+ this._peerConnection.ontrack = (event) => {
295
+ this._remoteStream = new MediaStream([event.track]);
296
+ this._remoteAudio.srcObject = this._remoteStream;
297
+ for (const handler of this._remoteStreamHandlers) {
298
+ handler(this._remoteStream);
299
+ }
300
+ };
301
+ this._peerConnection.onconnectionstatechange = () => {
302
+ if (this._peerConnection === undefined) {
303
+ return;
304
+ }
305
+ // "disconnected" is often transient, so wait for "failed" before ending the call.
306
+ if (this._peerConnection.connectionState === "connected") {
307
+ this._setState("connected");
308
+ if (this._pendingStart !== undefined) {
309
+ this._pendingStart.resolve();
310
+ this._pendingStart = undefined;
311
+ }
312
+ } else if (this._peerConnection.connectionState === "failed") {
313
+ this._end(new CallError("CONNECTION_FAILED", "Peer connection failed."));
314
+ }
315
+ };
316
+ for (const track of this._localStream.getAudioTracks()) {
317
+ this._peerConnection.addTrack(track);
318
+ }
319
+
320
+ try {
321
+ await this._peerConnection.setLocalDescription();
322
+ } catch (error) {
323
+ this._end(new CallError("CONNECTION_FAILED", "Failed to create offer.", { cause: error }));
324
+ return;
325
+ }
326
+
327
+ // The call may have ended while creating the offer.
328
+ if (this.state === "ended") {
329
+ return;
330
+ }
331
+ this._send({ type: "desc", body: this._peerConnection.localDescription });
332
+ }
333
+
334
+ private _end(error?: CallError) {
335
+ if (this._state === "ended") {
336
+ return;
337
+ }
338
+ this._error = error;
339
+ this._teardown();
340
+ this._setState("ended");
341
+
342
+ // If start() is still pending, it rejects on failure and resolves on hangup().
343
+ if (this._pendingStart !== undefined) {
344
+ if (error) {
345
+ this._pendingStart.reject(error);
346
+ } else {
347
+ this._pendingStart.resolve();
348
+ }
349
+ this._pendingStart = undefined;
350
+ }
351
+ }
352
+
353
+ private _teardown() {
354
+ if (this._sock) {
355
+ // Don't fire close handlers for a socket we closed ourselves.
356
+ this._sock.onclose = null;
357
+ this._sock.close();
358
+ this._sock = undefined;
359
+ }
360
+ if (this._peerConnection !== undefined) {
361
+ this._peerConnection.close();
362
+ this._peerConnection = undefined;
363
+ }
364
+ for (const track of this._localStream?.getTracks() ?? []) {
365
+ track.stop();
366
+ }
367
+ this._localStream = undefined;
368
+ this._remoteStream = undefined;
369
+ this._remoteAudio.srcObject = null;
370
+ this._remoteAudio.remove();
371
+ }
372
+ }
@@ -0,0 +1,200 @@
1
+ // Seconds from the start of bar 0 to the given 0-indexed beat.
2
+ function beatTime(beat: number, bpm: number): number {
3
+ return beat * (60 / bpm);
4
+ }
5
+
6
+ export interface ConnectingTone {
7
+ start(): void;
8
+ stop(): void;
9
+ }
10
+
11
+ // North American ringback: 440 + 480 Hz, 2s on, 4s off.
12
+ export class RingbackTone implements ConnectingTone {
13
+ private context: AudioContext | null = null;
14
+ private intervalId: ReturnType<typeof setInterval> | null = null;
15
+
16
+ private readonly volume = 0.15;
17
+ private readonly onSeconds = 2;
18
+ private readonly periodSeconds = 6;
19
+ // Delay before the first ring, so near-instant connections stay silent.
20
+ private readonly startDelay = 0.3;
21
+
22
+ start(): void {
23
+ if (this.context) return;
24
+
25
+ const context = new AudioContext();
26
+ const gain = context.createGain();
27
+ gain.gain.value = 0;
28
+ gain.connect(context.destination);
29
+
30
+ for (const frequency of [440, 480]) {
31
+ const oscillator = context.createOscillator();
32
+ oscillator.frequency.value = frequency;
33
+ oscillator.connect(gain);
34
+ oscillator.start();
35
+ }
36
+
37
+ let nextRing = context.currentTime + this.startDelay;
38
+ const ring = () => {
39
+ gain.gain.setValueAtTime(this.volume, nextRing);
40
+ gain.gain.setValueAtTime(0, nextRing + this.onSeconds);
41
+ nextRing += this.periodSeconds;
42
+ };
43
+ ring();
44
+ this.intervalId = setInterval(ring, this.periodSeconds * 1000);
45
+ this.context = context;
46
+ }
47
+
48
+ stop(): void {
49
+ if (!this.context) return;
50
+
51
+ if (this.intervalId) {
52
+ clearInterval(this.intervalId);
53
+ this.intervalId = null;
54
+ }
55
+ // Closing the context stops the oscillators.
56
+ void this.context.close();
57
+ this.context = null;
58
+ }
59
+ }
60
+
61
+ export class JingleTone implements ConnectingTone {
62
+ private context: AudioContext | null = null;
63
+ private masterGain: GainNode | null = null;
64
+ private intervalId: ReturnType<typeof setInterval> | null = null;
65
+ private running = false;
66
+ private pulseCount = 0;
67
+ // Audio-clock time of the next bar to schedule.
68
+ private nextBarStart = 0;
69
+
70
+ // Configuration
71
+ private readonly volume = 0.25;
72
+ private readonly bpm = 120;
73
+ private readonly beatsPerBar = 4;
74
+ // Delay before the first note, so near-instant connections stay silent.
75
+ private readonly startDelay = 0.3;
76
+
77
+ start(): void {
78
+ if (this.running) return;
79
+
80
+ this.running = true;
81
+ this.pulseCount = 0;
82
+ this.context = new AudioContext();
83
+ this.masterGain = this.context.createGain();
84
+ this.masterGain.gain.value = this.volume;
85
+ this.masterGain.connect(this.context.destination);
86
+ this.nextBarStart = this.context.currentTime + this.startDelay;
87
+
88
+ // Stay one bar ahead so timer jitter doesn't shift the beat.
89
+ this.playPulse();
90
+ this.playPulse();
91
+
92
+ const barLength = beatTime(this.beatsPerBar, this.bpm);
93
+ this.intervalId = setInterval(() => {
94
+ this.playPulse();
95
+ }, barLength * 1000);
96
+ }
97
+
98
+ private noteToFrequency(note: string): number {
99
+ const match = note.match(/^([A-G])(#|b)?(-?\d+)$/);
100
+
101
+ if (!match) {
102
+ throw new Error(`Invalid note: ${note}`);
103
+ }
104
+
105
+ const [, name, accidental, octave] = match;
106
+
107
+ const semitones: Record<string, number> = {
108
+ C: 0,
109
+ D: 2,
110
+ E: 4,
111
+ F: 5,
112
+ G: 7,
113
+ A: 9,
114
+ B: 11,
115
+ };
116
+
117
+ const offset = accidental === "#" ? 1 : accidental === "b" ? -1 : 0;
118
+ const midi = (Number(octave) + 1) * 12 + semitones[name] + offset;
119
+
120
+ return 440 * Math.pow(2, (midi - 69) / 12);
121
+ }
122
+
123
+ stop(): void {
124
+ if (!this.running) return;
125
+
126
+ this.running = false;
127
+
128
+ if (this.intervalId) {
129
+ clearInterval(this.intervalId);
130
+ this.intervalId = null;
131
+ }
132
+
133
+ const context = this.context;
134
+ const gain = this.masterGain;
135
+
136
+ if (!context || !gain) return;
137
+
138
+ // Smooth fade-out
139
+ const now = context.currentTime;
140
+ gain.gain.setValueAtTime(gain.gain.value, now);
141
+ gain.gain.linearRampToValueAtTime(0, now + 0.15);
142
+
143
+ setTimeout(() => {
144
+ void context.close();
145
+ }, 200);
146
+
147
+ this.context = null;
148
+ this.masterGain = null;
149
+ }
150
+
151
+ private playPulse(): void {
152
+ if (!this.context || !this.masterGain) return;
153
+
154
+ const bar = this.nextBarStart;
155
+ const beat = (n: number) => bar + beatTime(n, this.bpm);
156
+ const beatLength = beatTime(1, this.bpm);
157
+
158
+ // Notes on beats 1-3, silence on beat 4.
159
+ if (this.pulseCount % 4 === 0 || this.pulseCount % 4 === 2) {
160
+ this.playNote("C5", beat(0), beatLength);
161
+ this.playNote("E5", beat(0.5), beatLength);
162
+ this.playNote("G4", beat(1), beatLength);
163
+ } else if (this.pulseCount % 4 === 3) {
164
+ this.playNote("E5", beat(0), beatLength);
165
+ this.playNote("G5", beat(0.5), beatLength);
166
+ this.playNote("C5", beat(1), beatLength);
167
+ } else {
168
+ this.playNote("E5", beat(0), beatLength);
169
+ this.playNote("G4", beat(0.5), beatLength);
170
+ this.playNote("C5", beat(1), beatLength);
171
+ }
172
+ this.pulseCount++;
173
+ this.nextBarStart = beat(this.beatsPerBar);
174
+ }
175
+
176
+ private playNote(note: string, startTime: number, duration: number): void {
177
+ if (!this.context || !this.masterGain) return;
178
+
179
+ const oscillator = this.context.createOscillator();
180
+ const envelope = this.context.createGain();
181
+
182
+ oscillator.type = "sine";
183
+ oscillator.frequency.value = this.noteToFrequency(note);
184
+
185
+ envelope.gain.setValueAtTime(0, startTime);
186
+ envelope.gain.linearRampToValueAtTime(0.7, startTime + 0.05);
187
+ envelope.gain.exponentialRampToValueAtTime(0.001, startTime + duration);
188
+
189
+ oscillator.connect(envelope);
190
+ envelope.connect(this.masterGain);
191
+
192
+ oscillator.start(startTime);
193
+ oscillator.stop(startTime + duration + 0.01);
194
+
195
+ oscillator.onended = () => {
196
+ oscillator.disconnect();
197
+ envelope.disconnect();
198
+ };
199
+ }
200
+ }