@micdrop/telephony 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,673 @@
1
+ // src/g711.ts
2
+ var MULAW_BIAS = 132;
3
+ var MULAW_CLIP = 32635;
4
+ var MULAW_TO_PCM = new Int16Array(256);
5
+ var ALAW_TO_PCM = new Int16Array(256);
6
+ for (let i = 0; i < 256; i++) {
7
+ MULAW_TO_PCM[i] = decodeMulawSample(i);
8
+ ALAW_TO_PCM[i] = decodeAlawSample(i);
9
+ }
10
+ function decodeMulawSample(byte) {
11
+ const value = ~byte & 255;
12
+ const sign = value & 128;
13
+ const exponent = value >> 4 & 7;
14
+ const mantissa = value & 15;
15
+ const magnitude = (mantissa << 3) + MULAW_BIAS << exponent;
16
+ return sign ? MULAW_BIAS - magnitude : magnitude - MULAW_BIAS;
17
+ }
18
+ function encodeMulawSample(sample) {
19
+ const sign = sample < 0 ? 128 : 0;
20
+ let magnitude = Math.min(Math.abs(sample), MULAW_CLIP) + MULAW_BIAS;
21
+ let exponent = 7;
22
+ for (let mask = 16384; (magnitude & mask) === 0 && exponent > 0; mask >>= 1) {
23
+ exponent--;
24
+ }
25
+ const mantissa = magnitude >> exponent + 3 & 15;
26
+ return ~(sign | exponent << 4 | mantissa) & 255;
27
+ }
28
+ function decodeAlawSample(byte) {
29
+ const value = byte ^ 85;
30
+ const sign = value & 128;
31
+ const exponent = value >> 4 & 7;
32
+ const mantissa = value & 15;
33
+ let magnitude = exponent === 0 ? (mantissa << 4) + 8 : (mantissa << 4) + 264 << exponent - 1;
34
+ return sign ? magnitude : -magnitude;
35
+ }
36
+ function encodeAlawSample(sample) {
37
+ const sign = sample >= 0 ? 128 : 0;
38
+ let magnitude = Math.min(Math.abs(sample), 32767);
39
+ let byte;
40
+ if (magnitude >= 256) {
41
+ let exponent = 7;
42
+ for (let mask = 16384; (magnitude & mask) === 0; mask >>= 1) exponent--;
43
+ const mantissa = magnitude >> exponent + 3 & 15;
44
+ byte = exponent << 4 | mantissa;
45
+ } else {
46
+ byte = magnitude >> 4;
47
+ }
48
+ return (byte | sign) ^ 85;
49
+ }
50
+ function mulawToPcm16(bytes) {
51
+ const pcm = Buffer.alloc(bytes.length * 2);
52
+ for (let i = 0; i < bytes.length; i++) {
53
+ pcm.writeInt16LE(MULAW_TO_PCM[bytes[i]], i * 2);
54
+ }
55
+ return pcm;
56
+ }
57
+ function pcm16ToMulaw(pcm) {
58
+ const count = pcm.length >> 1;
59
+ const bytes = Buffer.alloc(count);
60
+ for (let i = 0; i < count; i++) {
61
+ bytes[i] = encodeMulawSample(pcm.readInt16LE(i * 2));
62
+ }
63
+ return bytes;
64
+ }
65
+ function alawToPcm16(bytes) {
66
+ const pcm = Buffer.alloc(bytes.length * 2);
67
+ for (let i = 0; i < bytes.length; i++) {
68
+ pcm.writeInt16LE(ALAW_TO_PCM[bytes[i]], i * 2);
69
+ }
70
+ return pcm;
71
+ }
72
+ function pcm16ToAlaw(pcm) {
73
+ const count = pcm.length >> 1;
74
+ const bytes = Buffer.alloc(count);
75
+ for (let i = 0; i < count; i++) {
76
+ bytes[i] = encodeAlawSample(pcm.readInt16LE(i * 2));
77
+ }
78
+ return bytes;
79
+ }
80
+
81
+ // src/xml.ts
82
+ function escapeXml(value) {
83
+ return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
84
+ }
85
+
86
+ // src/TelephonyTransport.ts
87
+ import {
88
+ DEFAULT_SAMPLE_RATE,
89
+ MicdropTransport,
90
+ Pcm16Resampler
91
+ } from "@micdrop/server";
92
+ var PLAYBACK_MAX_WAIT = 2e4;
93
+ var FRAME_IDLE_FLUSH = 80;
94
+ var TelephonyTransport = class extends MicdropTransport {
95
+ /**
96
+ * @param socket - The socket the provider opened, as the `ws` server hands it
97
+ */
98
+ constructor(socket) {
99
+ super();
100
+ this.socket = socket;
101
+ this.clientTurns = false;
102
+ this.hangsUp = true;
103
+ /** What the provider said about the call */
104
+ this.call = {};
105
+ /**
106
+ * Duration of the frames the provider wants, in ms. 0 sends the audio as it
107
+ * comes, for the providers that take any size.
108
+ */
109
+ this.frameDuration = 20;
110
+ // The provider is ready for audio once its stream has started
111
+ this.ready = false;
112
+ this.pendingWrites = [];
113
+ this.inputRate = 0;
114
+ this.outputRate = 0;
115
+ this.frameRemainder = Buffer.alloc(0);
116
+ this.markCounter = 0;
117
+ this.playbackWaiters = /* @__PURE__ */ new Map();
118
+ this.closed = false;
119
+ this.onSocketMessage = (data, isBinary) => {
120
+ const buffer = Buffer.isBuffer(data) ? data : Array.isArray(data) ? Buffer.concat(data) : Buffer.from(data);
121
+ try {
122
+ this.onProviderMessage(buffer, isBinary);
123
+ } catch (error) {
124
+ this.log("Unreadable message from the provider:", error);
125
+ }
126
+ };
127
+ this.onSocketClose = (code, reason) => {
128
+ this.closed = true;
129
+ this.cancelFrameFlush();
130
+ this.resolvePlayback();
131
+ this.socket.off("message", this.onSocketMessage);
132
+ this.socket.off("close", this.onSocketClose);
133
+ this.emit("Close", code, reason?.toString() || void 0);
134
+ };
135
+ socket.on("message", this.onSocketMessage);
136
+ socket.on("close", this.onSocketClose);
137
+ }
138
+ get isOpen() {
139
+ return !this.closed && (this.socket.readyState ?? 1) === 1;
140
+ }
141
+ // A phone line has nobody to read the messages of the server
142
+ send(message) {
143
+ if (message.type === "EndCall") this.log("The assistant ends the call");
144
+ }
145
+ sendAudio(audio, sampleRate) {
146
+ if (!this.isOpen) return;
147
+ const pcm = this.toLineRate(audio, sampleRate);
148
+ if (pcm.length === 0) return;
149
+ if (!this.frameDuration) {
150
+ this.whenReady(() => this.writeAudio(pcm));
151
+ return;
152
+ }
153
+ const frameBytes = this.frameBytes;
154
+ let data = Buffer.concat([this.frameRemainder, pcm]);
155
+ while (data.length >= frameBytes) {
156
+ const frame = data.subarray(0, frameBytes);
157
+ this.whenReady(() => this.writeAudio(frame));
158
+ data = data.subarray(frameBytes);
159
+ }
160
+ this.frameRemainder = data;
161
+ this.scheduleFrameFlush();
162
+ }
163
+ clearAudio() {
164
+ this.cancelFrameFlush();
165
+ this.frameRemainder = Buffer.alloc(0);
166
+ this.pendingWrites = [];
167
+ if (this.ready && this.isOpen) this.writeClear();
168
+ this.resolvePlayback();
169
+ }
170
+ waitForPlayback() {
171
+ if (!this.isOpen) return Promise.resolve();
172
+ this.flushFrame();
173
+ const name = `micdrop-${++this.markCounter}`;
174
+ return new Promise((resolve) => {
175
+ const timer = setTimeout(() => {
176
+ this.log("The provider never confirmed the playback");
177
+ done();
178
+ }, PLAYBACK_MAX_WAIT);
179
+ const done = () => {
180
+ clearTimeout(timer);
181
+ this.playbackWaiters.delete(name);
182
+ resolve();
183
+ };
184
+ this.playbackWaiters.set(name, done);
185
+ this.whenReady(() => this.writeMark(name));
186
+ });
187
+ }
188
+ /**
189
+ * Ends the stream, and the call with it: closing the socket is enough for
190
+ * the providers that end the call when nothing follows the stream, the
191
+ * others hang up through their API in `hangUp()`
192
+ */
193
+ close(code = 1e3, reason) {
194
+ if (this.closed) return;
195
+ this.cancelFrameFlush();
196
+ this.hangUp().catch((error) => this.log("Hang up failed:", error));
197
+ if ((this.socket.readyState ?? 1) <= 1) this.socket.close(code, reason);
198
+ }
199
+ /** Hangs up through the API of the provider, for those that need it */
200
+ async hangUp() {
201
+ }
202
+ /**
203
+ * The stream has started: keeps what the provider said about the call and
204
+ * sends the audio that waited for it
205
+ * @param call - Identifiers and numbers of the call
206
+ * @param params - Custom parameters of the call, if any
207
+ */
208
+ startStream(call, params) {
209
+ this.call = { ...this.call, ...call };
210
+ this.log("Stream started", this.call);
211
+ this.ready = true;
212
+ const writes = this.pendingWrites;
213
+ this.pendingWrites = [];
214
+ for (const write of writes) write();
215
+ this.receiveParams(params ?? {});
216
+ }
217
+ /**
218
+ * Hands audio of the caller to the server
219
+ * @param pcm - PCM16 mono at the rate of the line
220
+ */
221
+ receiveAudio(pcm) {
222
+ if (pcm.length === 0) return;
223
+ const rate = this.lineRate;
224
+ if (rate !== this.inputRate) {
225
+ this.inputRate = rate;
226
+ this.inputResampler = new Pcm16Resampler(rate, DEFAULT_SAMPLE_RATE);
227
+ }
228
+ const audio = this.inputResampler.process(pcm);
229
+ if (audio.length) this.emit("Audio", audio);
230
+ }
231
+ /** The provider played the audio sent before a mark */
232
+ markPlayed(name) {
233
+ this.playbackWaiters.get(name)?.();
234
+ }
235
+ /** A key was pressed on the keypad of the phone */
236
+ receiveDtmf(digit) {
237
+ this.log(`DTMF ${digit}`);
238
+ this.emit("Dtmf", digit);
239
+ }
240
+ /** Bytes in one outgoing frame */
241
+ get frameBytes() {
242
+ return Math.round(this.lineRate * this.frameDuration / 1e3) * 2;
243
+ }
244
+ toLineRate(audio, sampleRate) {
245
+ const rate = this.lineRate;
246
+ if (sampleRate === rate) return audio;
247
+ if (sampleRate !== this.outputRate) {
248
+ this.outputRate = sampleRate;
249
+ this.outputResampler = new Pcm16Resampler(sampleRate, rate);
250
+ }
251
+ return this.outputResampler.process(audio);
252
+ }
253
+ whenReady(write) {
254
+ if (this.ready) write();
255
+ else this.pendingWrites.push(write);
256
+ }
257
+ /** Sends the incomplete frame left, padded with silence */
258
+ flushFrame() {
259
+ this.cancelFrameFlush();
260
+ if (this.frameRemainder.length === 0) return;
261
+ const frame = Buffer.alloc(this.frameBytes);
262
+ this.frameRemainder.copy(frame);
263
+ this.frameRemainder = Buffer.alloc(0);
264
+ this.whenReady(() => this.writeAudio(frame));
265
+ }
266
+ scheduleFrameFlush() {
267
+ this.cancelFrameFlush();
268
+ if (this.frameRemainder.length === 0) return;
269
+ this.frameTimer = setTimeout(() => this.flushFrame(), FRAME_IDLE_FLUSH);
270
+ }
271
+ cancelFrameFlush() {
272
+ if (!this.frameTimer) return;
273
+ clearTimeout(this.frameTimer);
274
+ this.frameTimer = void 0;
275
+ }
276
+ resolvePlayback() {
277
+ for (const done of [...this.playbackWaiters.values()]) done();
278
+ }
279
+ };
280
+ function parseJson(data) {
281
+ try {
282
+ return JSON.parse(data.toString());
283
+ } catch {
284
+ return void 0;
285
+ }
286
+ }
287
+
288
+ // src/plivo.ts
289
+ var PlivoTransport = class extends TelephonyTransport {
290
+ /**
291
+ * @param socket - The socket Plivo opened
292
+ * @param options - Credentials to hang up with
293
+ */
294
+ constructor(socket, options = {}) {
295
+ super(socket);
296
+ this.options = options;
297
+ }
298
+ get lineRate() {
299
+ return 8e3;
300
+ }
301
+ onProviderMessage(data) {
302
+ const message = parseJson(data);
303
+ switch (message?.event) {
304
+ case "start": {
305
+ const start = message.start ?? {};
306
+ this.startStream(
307
+ {
308
+ callId: start.callId,
309
+ streamId: start.streamId,
310
+ from: start.from,
311
+ to: start.to
312
+ },
313
+ parseExtraHeaders(message.extra_headers)
314
+ );
315
+ break;
316
+ }
317
+ case "media":
318
+ if (message.media?.track && message.media.track !== "inbound") return;
319
+ this.receiveAudio(
320
+ mulawToPcm16(Buffer.from(message.media?.payload ?? "", "base64"))
321
+ );
322
+ break;
323
+ case "playedStream":
324
+ this.markPlayed(message.name);
325
+ break;
326
+ case "dtmf":
327
+ this.receiveDtmf(String(message.dtmf?.digit));
328
+ break;
329
+ }
330
+ }
331
+ writeAudio(pcm) {
332
+ this.sendJson({
333
+ event: "playAudio",
334
+ media: {
335
+ contentType: "audio/x-mulaw",
336
+ sampleRate: 8e3,
337
+ payload: pcm16ToMulaw(pcm).toString("base64")
338
+ }
339
+ });
340
+ }
341
+ writeClear() {
342
+ this.sendJson({ event: "clearAudio", streamId: this.call.streamId });
343
+ }
344
+ writeMark(name) {
345
+ this.sendJson({ event: "checkpoint", streamId: this.call.streamId, name });
346
+ }
347
+ async hangUp() {
348
+ const { authId, authToken } = this.options;
349
+ const callId = this.call.callId;
350
+ if (!authId || !authToken || !callId) return;
351
+ const credentials = Buffer.from(`${authId}:${authToken}`).toString("base64");
352
+ const response = await fetch(
353
+ `https://api.plivo.com/v1/Account/${encodeURIComponent(authId)}/Call/${encodeURIComponent(callId)}/`,
354
+ { method: "DELETE", headers: { Authorization: `Basic ${credentials}` } }
355
+ );
356
+ if (!response.ok && response.status !== 404) {
357
+ throw new Error(`Plivo answered ${response.status} to the hang up`);
358
+ }
359
+ }
360
+ sendJson(message) {
361
+ if (this.isOpen) this.socket.send(JSON.stringify(message));
362
+ }
363
+ };
364
+ function parseExtraHeaders(headers) {
365
+ const params = {};
366
+ if (typeof headers !== "string") return params;
367
+ for (const pair of headers.split(/[;,]/)) {
368
+ const index = pair.indexOf("=");
369
+ if (index <= 0) continue;
370
+ params[pair.substring(0, index).trim()] = pair.substring(index + 1).trim();
371
+ }
372
+ return params;
373
+ }
374
+ function plivoStreamXml({ url, parameters = {} }) {
375
+ const extraHeaders = Object.entries(parameters).map(([name, value]) => `${name}=${value}`).join(";");
376
+ const extra = extraHeaders ? ` extraHeaders="${escapeXml(extraHeaders)}"` : "";
377
+ return `<?xml version="1.0" encoding="UTF-8"?><Response><Stream bidirectional="true" keepCallAlive="true" contentType="audio/x-mulaw;rate=8000"${extra}>${escapeXml(url)}</Stream></Response>`;
378
+ }
379
+
380
+ // src/telnyx.ts
381
+ var TelnyxTransport = class extends TelephonyTransport {
382
+ /**
383
+ * @param socket - The socket Telnyx opened
384
+ * @param options - Codec of the stream and key to hang up with
385
+ */
386
+ constructor(socket, options = {}) {
387
+ super(socket);
388
+ this.options = options;
389
+ this.codec = options.codec ?? "PCMU";
390
+ }
391
+ get lineRate() {
392
+ return 8e3;
393
+ }
394
+ onProviderMessage(data) {
395
+ const message = parseJson(data);
396
+ switch (message?.event) {
397
+ case "start": {
398
+ const start = message.start ?? {};
399
+ const encoding = start.media_format?.encoding;
400
+ if (encoding === "PCMU" || encoding === "PCMA") this.codec = encoding;
401
+ this.startStream(
402
+ {
403
+ callId: start.call_control_id,
404
+ streamId: message.stream_id,
405
+ from: start.from,
406
+ to: start.to
407
+ },
408
+ readParams(start)
409
+ );
410
+ break;
411
+ }
412
+ case "media": {
413
+ if (message.media?.track && message.media.track !== "inbound") return;
414
+ const bytes = Buffer.from(message.media?.payload ?? "", "base64");
415
+ this.receiveAudio(
416
+ this.codec === "PCMA" ? alawToPcm16(bytes) : mulawToPcm16(bytes)
417
+ );
418
+ break;
419
+ }
420
+ case "mark":
421
+ this.markPlayed(message.mark?.name);
422
+ break;
423
+ case "dtmf":
424
+ this.receiveDtmf(String(message.dtmf?.digit));
425
+ break;
426
+ case "error":
427
+ this.log("Telnyx error:", message.payload);
428
+ break;
429
+ }
430
+ }
431
+ writeAudio(pcm) {
432
+ const bytes = this.codec === "PCMA" ? pcm16ToAlaw(pcm) : pcm16ToMulaw(pcm);
433
+ this.sendJson({ event: "media", media: { payload: bytes.toString("base64") } });
434
+ }
435
+ writeClear() {
436
+ this.sendJson({ event: "clear" });
437
+ }
438
+ writeMark(name) {
439
+ this.sendJson({ event: "mark", mark: { name } });
440
+ }
441
+ async hangUp() {
442
+ const { apiKey } = this.options;
443
+ const callId = this.call.callId;
444
+ if (!apiKey || !callId) return;
445
+ const response = await fetch(
446
+ `https://api.telnyx.com/v2/calls/${encodeURIComponent(callId)}/actions/hangup`,
447
+ {
448
+ method: "POST",
449
+ headers: {
450
+ Authorization: `Bearer ${apiKey}`,
451
+ "Content-Type": "application/json"
452
+ },
453
+ body: "{}"
454
+ }
455
+ );
456
+ if (!response.ok) {
457
+ throw new Error(`Telnyx answered ${response.status} to the hang up`);
458
+ }
459
+ }
460
+ sendJson(message) {
461
+ if (this.isOpen) this.socket.send(JSON.stringify(message));
462
+ }
463
+ };
464
+ function readParams(start) {
465
+ const params = {};
466
+ const custom = start.custom_parameters;
467
+ if (Array.isArray(custom)) {
468
+ for (const { name, value } of custom) params[name] = value;
469
+ } else if (custom && typeof custom === "object") {
470
+ Object.assign(params, custom);
471
+ }
472
+ if (typeof start.client_state === "string") {
473
+ try {
474
+ const state = JSON.parse(
475
+ Buffer.from(start.client_state, "base64").toString()
476
+ );
477
+ if (state && typeof state === "object") Object.assign(params, state);
478
+ } catch {
479
+ }
480
+ }
481
+ return params;
482
+ }
483
+ function telnyxStreamOptions({
484
+ url,
485
+ parameters,
486
+ codec = "PCMU"
487
+ }) {
488
+ return {
489
+ stream_url: url,
490
+ stream_track: "inbound_track",
491
+ stream_codec: codec,
492
+ stream_bidirectional_mode: "rtp",
493
+ stream_bidirectional_codec: codec,
494
+ ...parameters ? {
495
+ client_state: Buffer.from(JSON.stringify(parameters)).toString(
496
+ "base64"
497
+ )
498
+ } : {}
499
+ };
500
+ }
501
+
502
+ // src/twilio.ts
503
+ var TwilioTransport = class extends TelephonyTransport {
504
+ constructor() {
505
+ super(...arguments);
506
+ // Twilio takes audio of any size, and buffers it
507
+ this.frameDuration = 0;
508
+ }
509
+ get lineRate() {
510
+ return 8e3;
511
+ }
512
+ onProviderMessage(data) {
513
+ const message = parseJson(data);
514
+ switch (message?.event) {
515
+ case "start": {
516
+ const start = message.start ?? {};
517
+ this.startStream(
518
+ {
519
+ callId: start.callSid,
520
+ streamId: start.streamSid ?? message.streamSid
521
+ },
522
+ start.customParameters
523
+ );
524
+ break;
525
+ }
526
+ case "media":
527
+ if (message.media?.track && message.media.track !== "inbound") return;
528
+ this.receiveAudio(
529
+ mulawToPcm16(Buffer.from(message.media?.payload ?? "", "base64"))
530
+ );
531
+ break;
532
+ case "mark":
533
+ this.markPlayed(message.mark?.name);
534
+ break;
535
+ case "dtmf":
536
+ this.receiveDtmf(String(message.dtmf?.digit));
537
+ break;
538
+ case "stop":
539
+ this.log("Stream stopped");
540
+ break;
541
+ }
542
+ }
543
+ writeAudio(pcm) {
544
+ this.sendJson({
545
+ event: "media",
546
+ streamSid: this.call.streamId,
547
+ media: { payload: pcm16ToMulaw(pcm).toString("base64") }
548
+ });
549
+ }
550
+ writeClear() {
551
+ this.sendJson({ event: "clear", streamSid: this.call.streamId });
552
+ }
553
+ writeMark(name) {
554
+ this.sendJson({ event: "mark", streamSid: this.call.streamId, mark: { name } });
555
+ }
556
+ sendJson(message) {
557
+ if (this.isOpen) this.socket.send(JSON.stringify(message));
558
+ }
559
+ };
560
+ function twilioStreamTwiml({
561
+ url,
562
+ parameters = {},
563
+ before = ""
564
+ }) {
565
+ const params = Object.entries(parameters).map(
566
+ ([name, value]) => `<Parameter name="${escapeXml(name)}" value="${escapeXml(String(value))}" />`
567
+ ).join("");
568
+ return `<?xml version="1.0" encoding="UTF-8"?><Response>${before}<Connect><Stream url="${escapeXml(url)}">${params}</Stream></Connect></Response>`;
569
+ }
570
+
571
+ // src/vonage.ts
572
+ var CALL_HEADERS = {
573
+ callId: "micdropCallId",
574
+ from: "micdropFrom",
575
+ to: "micdropTo"
576
+ };
577
+ var VonageTransport = class extends TelephonyTransport {
578
+ /**
579
+ * @param socket - The socket Vonage opened
580
+ * @param options - The rate of the NCCO, read again from the first message
581
+ */
582
+ constructor(socket, options = {}) {
583
+ super(socket);
584
+ this.rate = options.sampleRate ?? 16e3;
585
+ }
586
+ get lineRate() {
587
+ return this.rate;
588
+ }
589
+ onProviderMessage(data, isBinary) {
590
+ if (isBinary) {
591
+ this.receiveAudio(data);
592
+ return;
593
+ }
594
+ const message = parseJson(data);
595
+ switch (message?.event) {
596
+ case "websocket:connected": {
597
+ const { event, "content-type": contentType, ...headers } = message;
598
+ const rate = /rate=(\d+)/.exec(contentType ?? "")?.[1];
599
+ if (rate) this.rate = Number(rate);
600
+ const call = {
601
+ callId: headers[CALL_HEADERS.callId],
602
+ from: headers[CALL_HEADERS.from],
603
+ to: headers[CALL_HEADERS.to]
604
+ };
605
+ for (const key of Object.values(CALL_HEADERS)) delete headers[key];
606
+ delete headers.reconnect_attempt;
607
+ this.startStream(call, headers);
608
+ break;
609
+ }
610
+ case "websocket:notify":
611
+ this.markPlayed(message.payload?.micdropMark);
612
+ break;
613
+ case "websocket:dtmf":
614
+ this.receiveDtmf(String(message.digit));
615
+ break;
616
+ }
617
+ }
618
+ writeAudio(pcm) {
619
+ if (this.isOpen) this.socket.send(pcm);
620
+ }
621
+ writeClear() {
622
+ this.sendJson({ action: "clear" });
623
+ }
624
+ writeMark(name) {
625
+ this.sendJson({ action: "notify", payload: { micdropMark: name } });
626
+ }
627
+ sendJson(message) {
628
+ if (this.isOpen) this.socket.send(JSON.stringify(message));
629
+ }
630
+ };
631
+ function vonageConnectNcco({
632
+ url,
633
+ parameters = {},
634
+ call,
635
+ sampleRate = 16e3,
636
+ eventUrl
637
+ }) {
638
+ const headers = { ...parameters };
639
+ if (call?.uuid) headers[CALL_HEADERS.callId] = call.uuid;
640
+ if (call?.from) headers[CALL_HEADERS.from] = call.from;
641
+ if (call?.to) headers[CALL_HEADERS.to] = call.to;
642
+ return [
643
+ {
644
+ action: "connect",
645
+ ...eventUrl ? { eventUrl: [eventUrl] } : {},
646
+ endpoint: [
647
+ {
648
+ type: "websocket",
649
+ uri: url,
650
+ "content-type": `audio/l16;rate=${sampleRate}`,
651
+ headers
652
+ }
653
+ ]
654
+ }
655
+ ];
656
+ }
657
+ export {
658
+ PlivoTransport,
659
+ TelephonyTransport,
660
+ TelnyxTransport,
661
+ TwilioTransport,
662
+ VonageTransport,
663
+ alawToPcm16,
664
+ mulawToPcm16,
665
+ parseJson,
666
+ pcm16ToAlaw,
667
+ pcm16ToMulaw,
668
+ plivoStreamXml,
669
+ telnyxStreamOptions,
670
+ twilioStreamTwiml,
671
+ vonageConnectNcco
672
+ };
673
+ //# sourceMappingURL=index.mjs.map