@micdrop/telephony 0.1.0 → 0.2.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/README.md +16 -3
- package/dist/index.d.mts +810 -23
- package/dist/index.d.ts +810 -23
- package/dist/index.js +1794 -80
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1770 -79
- package/dist/index.mjs.map +1 -1
- package/package.json +6 -4
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/g711.ts","../src/xml.ts","../src/TelephonyTransport.ts","../src/plivo.ts","../src/telnyx.ts","../src/twilio.ts","../src/vonage.ts"],"sourcesContent":["export * from './g711'\nexport * from './plivo'\nexport * from './TelephonyTransport'\nexport * from './telnyx'\nexport * from './twilio'\nexport * from './vonage'\n","/**\n * G.711, the codec of the phone network: one byte per sample at 8 kHz, with a\n * logarithmic scale that keeps quiet speech as precise as loud speech.\n *\n * μ-law is the variant of North America and Japan, A-law that of the rest of\n * the world. Both take and give PCM16 mono, little endian.\n */\n\nconst MULAW_BIAS = 0x84\nconst MULAW_CLIP = 32635\n\n// Decoding is a table lookup, built once\nconst MULAW_TO_PCM = new Int16Array(256)\nconst ALAW_TO_PCM = new Int16Array(256)\nfor (let i = 0; i < 256; i++) {\n MULAW_TO_PCM[i] = decodeMulawSample(i)\n ALAW_TO_PCM[i] = decodeAlawSample(i)\n}\n\nfunction decodeMulawSample(byte: number): number {\n const value = ~byte & 0xff\n const sign = value & 0x80\n const exponent = (value >> 4) & 0x07\n const mantissa = value & 0x0f\n const magnitude = ((mantissa << 3) + MULAW_BIAS) << exponent\n return sign ? MULAW_BIAS - magnitude : magnitude - MULAW_BIAS\n}\n\nfunction encodeMulawSample(sample: number): number {\n const sign = sample < 0 ? 0x80 : 0\n let magnitude = Math.min(Math.abs(sample), MULAW_CLIP) + MULAW_BIAS\n let exponent = 7\n for (let mask = 0x4000; (magnitude & mask) === 0 && exponent > 0; mask >>= 1) {\n exponent--\n }\n const mantissa = (magnitude >> (exponent + 3)) & 0x0f\n return ~(sign | (exponent << 4) | mantissa) & 0xff\n}\n\nfunction decodeAlawSample(byte: number): number {\n const value = byte ^ 0x55\n const sign = value & 0x80\n const exponent = (value >> 4) & 0x07\n const mantissa = value & 0x0f\n let magnitude =\n exponent === 0\n ? (mantissa << 4) + 8\n : ((mantissa << 4) + 0x108) << (exponent - 1)\n return sign ? magnitude : -magnitude\n}\n\nfunction encodeAlawSample(sample: number): number {\n const sign = sample >= 0 ? 0x80 : 0\n let magnitude = Math.min(Math.abs(sample), 32767)\n let byte: number\n if (magnitude >= 256) {\n let exponent = 7\n for (let mask = 0x4000; (magnitude & mask) === 0; mask >>= 1) exponent--\n const mantissa = (magnitude >> (exponent + 3)) & 0x0f\n byte = (exponent << 4) | mantissa\n } else {\n byte = magnitude >> 4\n }\n return (byte | sign) ^ 0x55\n}\n\n/**\n * Decodes μ-law bytes\n * @param bytes - One byte per sample\n * @returns PCM16 mono, little endian\n */\nexport function mulawToPcm16(bytes: Uint8Array): Buffer {\n const pcm = Buffer.alloc(bytes.length * 2)\n for (let i = 0; i < bytes.length; i++) {\n pcm.writeInt16LE(MULAW_TO_PCM[bytes[i]], i * 2)\n }\n return pcm\n}\n\n/**\n * Encodes PCM16 as μ-law\n * @param pcm - PCM16 mono, little endian\n * @returns One byte per sample\n */\nexport function pcm16ToMulaw(pcm: Buffer): Buffer {\n const count = pcm.length >> 1\n const bytes = Buffer.alloc(count)\n for (let i = 0; i < count; i++) {\n bytes[i] = encodeMulawSample(pcm.readInt16LE(i * 2))\n }\n return bytes\n}\n\n/**\n * Decodes A-law bytes\n * @param bytes - One byte per sample\n * @returns PCM16 mono, little endian\n */\nexport function alawToPcm16(bytes: Uint8Array): Buffer {\n const pcm = Buffer.alloc(bytes.length * 2)\n for (let i = 0; i < bytes.length; i++) {\n pcm.writeInt16LE(ALAW_TO_PCM[bytes[i]], i * 2)\n }\n return pcm\n}\n\n/**\n * Encodes PCM16 as A-law\n * @param pcm - PCM16 mono, little endian\n * @returns One byte per sample\n */\nexport function pcm16ToAlaw(pcm: Buffer): Buffer {\n const count = pcm.length >> 1\n const bytes = Buffer.alloc(count)\n for (let i = 0; i < count; i++) {\n bytes[i] = encodeAlawSample(pcm.readInt16LE(i * 2))\n }\n return bytes\n}\n","/** Escapes a value for an XML attribute or text */\nexport function escapeXml(value: string): string {\n return value\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\n}\n","import {\n DEFAULT_SAMPLE_RATE,\n MicdropServerMessage,\n MicdropTransport,\n Pcm16Resampler,\n} from '@micdrop/server'\nimport type { RawData, WebSocket } from 'ws'\n\n/** What the provider says about the call, once its stream has started */\nexport interface TelephonyCall {\n /** Identifier of the call at the provider, to act on it with its API */\n callId?: string\n /** Identifier of the media stream at the provider */\n streamId?: string\n /** Number of the caller, when the provider passes it */\n from?: string\n /** Number called, when the provider passes it */\n to?: string\n}\n\n/**\n * How long a hang up waits for the goodbye to be played, at most. A provider\n * that never confirms the playback still sees the call end.\n */\nconst PLAYBACK_MAX_WAIT = 20000 // ms\n\n/**\n * How long a frame left incomplete waits for the rest of the answer before it\n * goes out padded with silence\n */\nconst FRAME_IDLE_FLUSH = 80 // ms\n\n/**\n * A phone call carried over the media stream WebSocket of a telephony\n * provider.\n *\n * The provider streams the caller as audio at the rate of the line, 8 kHz for\n * most, and plays back what it is sent, buffering it on its side. This class\n * does what all of them need: audio brought to 16 kHz for the server and to\n * the rate of the line for the provider, frames of a fixed duration when the\n * provider wants them, playback confirmed by marks, and a hang up once the\n * goodbye is played. Each provider writes and reads its own messages.\n *\n * A phone line has no client to find the turns: the server needs `vad`.\n */\nexport abstract class TelephonyTransport extends MicdropTransport {\n readonly clientTurns = false\n readonly hangsUp = true\n\n /** What the provider said about the call */\n public call: TelephonyCall = {}\n\n /**\n * Duration of the frames the provider wants, in ms. 0 sends the audio as it\n * comes, for the providers that take any size.\n */\n protected frameDuration = 20\n\n // The provider is ready for audio once its stream has started\n private ready = false\n private pendingWrites: (() => void)[] = []\n private inputResampler?: Pcm16Resampler\n private inputRate = 0\n private outputResampler?: Pcm16Resampler\n private outputRate = 0\n private frameRemainder = Buffer.alloc(0)\n private frameTimer?: ReturnType<typeof setTimeout>\n private markCounter = 0\n private playbackWaiters = new Map<string, () => void>()\n private closed = false\n\n /**\n * @param socket - The socket the provider opened, as the `ws` server hands it\n */\n constructor(public readonly socket: WebSocket) {\n super()\n socket.on('message', this.onSocketMessage)\n socket.on('close', this.onSocketClose)\n }\n\n /** Rate of the audio on the line, in Hz */\n protected abstract get lineRate(): number\n\n /**\n * Reads a message of the provider\n * @param data - The message, text or binary\n * @param isBinary - Whether it came as a binary frame\n */\n protected abstract onProviderMessage(data: Buffer, isBinary: boolean): void\n\n /**\n * Sends audio to be played\n * @param pcm - PCM16 mono at the rate of the line, one frame when\n * `frameDuration` is set\n */\n protected abstract writeAudio(pcm: Buffer): void\n\n /** Asks the provider to drop the audio it holds and not played yet */\n protected abstract writeClear(): void\n\n /**\n * Asks the provider to say when the audio sent so far has been played\n * @param name - What the provider sends back, given to `markPlayed()`\n */\n protected abstract writeMark(name: string): void\n\n get isOpen(): boolean {\n return !this.closed && (this.socket.readyState ?? 1) === 1\n }\n\n // A phone line has nobody to read the messages of the server\n send(message: MicdropServerMessage) {\n if (message.type === 'EndCall') this.log('The assistant ends the call')\n }\n\n sendAudio(audio: Buffer, sampleRate: number) {\n if (!this.isOpen) return\n const pcm = this.toLineRate(audio, sampleRate)\n if (pcm.length === 0) return\n\n if (!this.frameDuration) {\n this.whenReady(() => this.writeAudio(pcm))\n return\n }\n\n // Whole frames go now, the rest waits for the next chunk\n const frameBytes = this.frameBytes\n let data = Buffer.concat([this.frameRemainder, pcm])\n while (data.length >= frameBytes) {\n const frame = data.subarray(0, frameBytes)\n this.whenReady(() => this.writeAudio(frame))\n data = data.subarray(frameBytes)\n }\n this.frameRemainder = data\n this.scheduleFrameFlush()\n }\n\n clearAudio() {\n this.cancelFrameFlush()\n this.frameRemainder = Buffer.alloc(0)\n // Audio queued before the stream started never reached the provider\n this.pendingWrites = []\n if (this.ready && this.isOpen) this.writeClear()\n // What was waiting for its playback has been dropped instead\n this.resolvePlayback()\n }\n\n waitForPlayback(): Promise<void> {\n if (!this.isOpen) return Promise.resolve()\n this.flushFrame()\n const name = `micdrop-${++this.markCounter}`\n return new Promise<void>((resolve) => {\n const timer = setTimeout(() => {\n this.log('The provider never confirmed the playback')\n done()\n }, PLAYBACK_MAX_WAIT)\n const done = () => {\n clearTimeout(timer)\n this.playbackWaiters.delete(name)\n resolve()\n }\n this.playbackWaiters.set(name, done)\n this.whenReady(() => this.writeMark(name))\n })\n }\n\n /**\n * Ends the stream, and the call with it: closing the socket is enough for\n * the providers that end the call when nothing follows the stream, the\n * others hang up through their API in `hangUp()`\n */\n close(code = 1000, reason?: string) {\n if (this.closed) return\n this.cancelFrameFlush()\n this.hangUp().catch((error) => this.log('Hang up failed:', error))\n if ((this.socket.readyState ?? 1) <= 1) this.socket.close(code, reason)\n }\n\n /** Hangs up through the API of the provider, for those that need it */\n protected async hangUp(): Promise<void> {}\n\n /**\n * The stream has started: keeps what the provider said about the call and\n * sends the audio that waited for it\n * @param call - Identifiers and numbers of the call\n * @param params - Custom parameters of the call, if any\n */\n protected startStream(call: TelephonyCall, params?: any) {\n this.call = { ...this.call, ...call }\n this.log('Stream started', this.call)\n this.ready = true\n const writes = this.pendingWrites\n this.pendingWrites = []\n for (const write of writes) write()\n this.receiveParams(params ?? {})\n }\n\n /**\n * Hands audio of the caller to the server\n * @param pcm - PCM16 mono at the rate of the line\n */\n protected receiveAudio(pcm: Buffer) {\n if (pcm.length === 0) return\n const rate = this.lineRate\n if (rate !== this.inputRate) {\n this.inputRate = rate\n this.inputResampler = new Pcm16Resampler(rate, DEFAULT_SAMPLE_RATE)\n }\n const audio = this.inputResampler!.process(pcm)\n if (audio.length) this.emit('Audio', audio)\n }\n\n /** The provider played the audio sent before a mark */\n protected markPlayed(name: string) {\n this.playbackWaiters.get(name)?.()\n }\n\n /** A key was pressed on the keypad of the phone */\n protected receiveDtmf(digit: string) {\n this.log(`DTMF ${digit}`)\n this.emit('Dtmf', digit)\n }\n\n /** Bytes in one outgoing frame */\n protected get frameBytes(): number {\n return Math.round((this.lineRate * this.frameDuration) / 1000) * 2\n }\n\n private toLineRate(audio: Buffer, sampleRate: number): Buffer {\n const rate = this.lineRate\n if (sampleRate === rate) return audio\n if (sampleRate !== this.outputRate) {\n this.outputRate = sampleRate\n this.outputResampler = new Pcm16Resampler(sampleRate, rate)\n }\n return this.outputResampler!.process(audio)\n }\n\n private whenReady(write: () => void) {\n if (this.ready) write()\n else this.pendingWrites.push(write)\n }\n\n /** Sends the incomplete frame left, padded with silence */\n private flushFrame() {\n this.cancelFrameFlush()\n if (this.frameRemainder.length === 0) return\n const frame = Buffer.alloc(this.frameBytes)\n this.frameRemainder.copy(frame)\n this.frameRemainder = Buffer.alloc(0)\n this.whenReady(() => this.writeAudio(frame))\n }\n\n private scheduleFrameFlush() {\n this.cancelFrameFlush()\n if (this.frameRemainder.length === 0) return\n this.frameTimer = setTimeout(() => this.flushFrame(), FRAME_IDLE_FLUSH)\n }\n\n private cancelFrameFlush() {\n if (!this.frameTimer) return\n clearTimeout(this.frameTimer)\n this.frameTimer = undefined\n }\n\n private resolvePlayback() {\n for (const done of [...this.playbackWaiters.values()]) done()\n }\n\n private onSocketMessage = (data: RawData, isBinary: boolean) => {\n const buffer = Buffer.isBuffer(data)\n ? data\n : Array.isArray(data)\n ? Buffer.concat(data)\n : Buffer.from(data)\n try {\n this.onProviderMessage(buffer, isBinary)\n } catch (error) {\n this.log('Unreadable message from the provider:', error)\n }\n }\n\n private onSocketClose = (code?: number, reason?: Buffer) => {\n this.closed = true\n this.cancelFrameFlush()\n this.resolvePlayback()\n this.socket.off('message', this.onSocketMessage)\n this.socket.off('close', this.onSocketClose)\n this.emit('Close', code, reason?.toString() || undefined)\n }\n}\n\n/** Reads a JSON text message, or nothing when it is not one */\nexport function parseJson(data: Buffer): any {\n try {\n return JSON.parse(data.toString())\n } catch {\n return undefined\n }\n}\n","import { mulawToPcm16, pcm16ToMulaw } from './g711'\nimport { escapeXml } from './xml'\nimport { parseJson, TelephonyTransport } from './TelephonyTransport'\n\nexport interface PlivoTransportOptions {\n /**\n * Credentials of the account, to hang up through the API when the assistant\n * ends the call, whatever the XML says after the stream\n */\n authId?: string\n authToken?: string\n}\n\n/**\n * A call from Plivo, over a bidirectional audio stream.\n *\n * Plivo opens the WebSocket when the call reaches the `<Stream>` of its XML,\n * which {@link plivoStreamXml} writes. The caller comes in μ-law at 8 kHz, and\n * the assistant goes back the same way. The extra headers of the stream are\n * the parameters of the call.\n *\n * @see https://www.plivo.com/docs/voice-agents/audio-streaming/concepts/audio-streaming-reference\n */\nexport class PlivoTransport extends TelephonyTransport {\n /**\n * @param socket - The socket Plivo opened\n * @param options - Credentials to hang up with\n */\n constructor(\n socket: ConstructorParameters<typeof TelephonyTransport>[0],\n private options: PlivoTransportOptions = {}\n ) {\n super(socket)\n }\n\n protected get lineRate() {\n return 8000\n }\n\n protected onProviderMessage(data: Buffer) {\n const message = parseJson(data)\n switch (message?.event) {\n case 'start': {\n const start = message.start ?? {}\n this.startStream(\n {\n callId: start.callId,\n streamId: start.streamId,\n from: start.from,\n to: start.to,\n },\n parseExtraHeaders(message.extra_headers)\n )\n break\n }\n case 'media':\n if (message.media?.track && message.media.track !== 'inbound') return\n this.receiveAudio(\n mulawToPcm16(Buffer.from(message.media?.payload ?? '', 'base64'))\n )\n break\n case 'playedStream':\n this.markPlayed(message.name)\n break\n case 'dtmf':\n this.receiveDtmf(String(message.dtmf?.digit))\n break\n }\n }\n\n protected writeAudio(pcm: Buffer) {\n this.sendJson({\n event: 'playAudio',\n media: {\n contentType: 'audio/x-mulaw',\n sampleRate: 8000,\n payload: pcm16ToMulaw(pcm).toString('base64'),\n },\n })\n }\n\n protected writeClear() {\n this.sendJson({ event: 'clearAudio', streamId: this.call.streamId })\n }\n\n protected writeMark(name: string) {\n this.sendJson({ event: 'checkpoint', streamId: this.call.streamId, name })\n }\n\n protected async hangUp() {\n const { authId, authToken } = this.options\n const callId = this.call.callId\n if (!authId || !authToken || !callId) return\n const credentials = Buffer.from(`${authId}:${authToken}`).toString('base64')\n const response = await fetch(\n `https://api.plivo.com/v1/Account/${encodeURIComponent(authId)}/Call/${encodeURIComponent(callId)}/`,\n { method: 'DELETE', headers: { Authorization: `Basic ${credentials}` } }\n )\n if (!response.ok && response.status !== 404) {\n throw new Error(`Plivo answered ${response.status} to the hang up`)\n }\n }\n\n private sendJson(message: object) {\n if (this.isOpen) this.socket.send(JSON.stringify(message))\n }\n}\n\n/** Reads `key=value` pairs, separated by `;` or `,` */\nfunction parseExtraHeaders(headers: unknown): Record<string, string> {\n const params: Record<string, string> = {}\n if (typeof headers !== 'string') return params\n for (const pair of headers.split(/[;,]/)) {\n const index = pair.indexOf('=')\n if (index <= 0) continue\n params[pair.substring(0, index).trim()] = pair.substring(index + 1).trim()\n }\n return params\n}\n\nexport interface PlivoStreamOptions {\n /** Address of the WebSocket that runs the call */\n url: string\n /**\n * Parameters of the call, which `waitForParams` hands back. Plivo only\n * takes letters and digits in them, 512 bytes at most.\n */\n parameters?: Record<string, string | number>\n}\n\n/**\n * Writes the XML that connects a call to a Micdrop server, to answer the\n * answer URL of a Plivo application with\n * @returns The XML document\n */\nexport function plivoStreamXml({ url, parameters = {} }: PlivoStreamOptions) {\n const extraHeaders = Object.entries(parameters)\n .map(([name, value]) => `${name}=${value}`)\n .join(';')\n const extra = extraHeaders\n ? ` extraHeaders=\"${escapeXml(extraHeaders)}\"`\n : ''\n 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>`\n}\n","import { alawToPcm16, mulawToPcm16, pcm16ToAlaw, pcm16ToMulaw } from './g711'\nimport { parseJson, TelephonyTransport } from './TelephonyTransport'\n\nexport type TelnyxCodec = 'PCMU' | 'PCMA'\n\nexport interface TelnyxTransportOptions {\n /**\n * Codec of the stream, both ways, `PCMU` by default. It has to match the\n * `stream_codec` and `stream_bidirectional_codec` of the call.\n */\n codec?: TelnyxCodec\n /**\n * API key, to hang up when the assistant ends the call. Telnyx keeps a\n * call going when its stream closes, so without it the call stays on the\n * line until the caller hangs up.\n */\n apiKey?: string\n}\n\n/**\n * A call from Telnyx, streamed with bidirectional RTP media streaming.\n *\n * The call is answered with Call Control, with the stream options that\n * {@link telnyxStreamOptions} writes, and Telnyx opens the WebSocket. The\n * caller comes in G.711 at 8 kHz and the assistant goes back the same way.\n * The parameters of the call travel in its `client_state`.\n *\n * @see https://developers.telnyx.com/docs/voice/programmable-voice/media-streaming\n */\nexport class TelnyxTransport extends TelephonyTransport {\n private codec: TelnyxCodec\n\n /**\n * @param socket - The socket Telnyx opened\n * @param options - Codec of the stream and key to hang up with\n */\n constructor(\n socket: ConstructorParameters<typeof TelephonyTransport>[0],\n private options: TelnyxTransportOptions = {}\n ) {\n super(socket)\n this.codec = options.codec ?? 'PCMU'\n }\n\n protected get lineRate() {\n return 8000\n }\n\n protected onProviderMessage(data: Buffer) {\n const message = parseJson(data)\n switch (message?.event) {\n case 'start': {\n const start = message.start ?? {}\n const encoding = start.media_format?.encoding\n if (encoding === 'PCMU' || encoding === 'PCMA') this.codec = encoding\n this.startStream(\n {\n callId: start.call_control_id,\n streamId: message.stream_id,\n from: start.from,\n to: start.to,\n },\n readParams(start)\n )\n break\n }\n case 'media': {\n if (message.media?.track && message.media.track !== 'inbound') return\n const bytes = Buffer.from(message.media?.payload ?? '', 'base64')\n this.receiveAudio(\n this.codec === 'PCMA' ? alawToPcm16(bytes) : mulawToPcm16(bytes)\n )\n break\n }\n case 'mark':\n this.markPlayed(message.mark?.name)\n break\n case 'dtmf':\n this.receiveDtmf(String(message.dtmf?.digit))\n break\n case 'error':\n this.log('Telnyx error:', message.payload)\n break\n }\n }\n\n protected writeAudio(pcm: Buffer) {\n const bytes = this.codec === 'PCMA' ? pcm16ToAlaw(pcm) : pcm16ToMulaw(pcm)\n this.sendJson({ event: 'media', media: { payload: bytes.toString('base64') } })\n }\n\n protected writeClear() {\n this.sendJson({ event: 'clear' })\n }\n\n protected writeMark(name: string) {\n this.sendJson({ event: 'mark', mark: { name } })\n }\n\n protected async hangUp() {\n const { apiKey } = this.options\n const callId = this.call.callId\n if (!apiKey || !callId) return\n const response = await fetch(\n `https://api.telnyx.com/v2/calls/${encodeURIComponent(callId)}/actions/hangup`,\n {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: '{}',\n }\n )\n if (!response.ok) {\n throw new Error(`Telnyx answered ${response.status} to the hang up`)\n }\n }\n\n private sendJson(message: object) {\n if (this.isOpen) this.socket.send(JSON.stringify(message))\n }\n}\n\n/** The parameters of the call, from its client state or custom parameters */\nfunction readParams(start: any): any {\n const params: Record<string, any> = {}\n const custom = start.custom_parameters\n if (Array.isArray(custom)) {\n for (const { name, value } of custom) params[name] = value\n } else if (custom && typeof custom === 'object') {\n Object.assign(params, custom)\n }\n if (typeof start.client_state === 'string') {\n try {\n const state = JSON.parse(\n Buffer.from(start.client_state, 'base64').toString()\n )\n if (state && typeof state === 'object') Object.assign(params, state)\n } catch {\n // A client state the application wrote for itself\n }\n }\n return params\n}\n\nexport interface TelnyxStreamOptions {\n /** Address of the WebSocket that runs the call */\n url: string\n /** Parameters of the call, which `waitForParams` hands back */\n parameters?: Record<string, unknown>\n /** Codec of the stream, both ways, `PCMU` by default */\n codec?: TelnyxCodec\n}\n\n/**\n * Writes the stream options of a Call Control `answer`, `dial` or\n * `streaming_start` command, to merge into its body\n * @returns The fields to send to Telnyx\n */\nexport function telnyxStreamOptions({\n url,\n parameters,\n codec = 'PCMU',\n}: TelnyxStreamOptions) {\n return {\n stream_url: url,\n stream_track: 'inbound_track',\n stream_codec: codec,\n stream_bidirectional_mode: 'rtp',\n stream_bidirectional_codec: codec,\n ...(parameters\n ? {\n client_state: Buffer.from(JSON.stringify(parameters)).toString(\n 'base64'\n ),\n }\n : {}),\n }\n}\n","import { mulawToPcm16, pcm16ToMulaw } from './g711'\nimport { escapeXml } from './xml'\nimport { parseJson, TelephonyTransport } from './TelephonyTransport'\n\n/**\n * A call from Twilio, over a bidirectional Media Stream.\n *\n * Twilio opens the WebSocket when the call reaches the `<Connect><Stream>`\n * of its TwiML, which {@link twilioStreamTwiml} writes. The caller comes in\n * μ-law at 8 kHz, and the assistant goes back the same way. Closing the\n * socket ends the `<Connect>`, and the call with it when nothing follows.\n *\n * SignalWire speaks the same protocol, with its default `PCMU` codec.\n *\n * @see https://www.twilio.com/docs/voice/media-streams/websocket-messages\n */\nexport class TwilioTransport extends TelephonyTransport {\n // Twilio takes audio of any size, and buffers it\n protected frameDuration = 0\n\n protected get lineRate() {\n return 8000\n }\n\n protected onProviderMessage(data: Buffer) {\n const message = parseJson(data)\n switch (message?.event) {\n case 'start': {\n const start = message.start ?? {}\n this.startStream(\n {\n callId: start.callSid,\n streamId: start.streamSid ?? message.streamSid,\n },\n start.customParameters\n )\n break\n }\n case 'media':\n if (message.media?.track && message.media.track !== 'inbound') return\n this.receiveAudio(\n mulawToPcm16(Buffer.from(message.media?.payload ?? '', 'base64'))\n )\n break\n case 'mark':\n this.markPlayed(message.mark?.name)\n break\n case 'dtmf':\n this.receiveDtmf(String(message.dtmf?.digit))\n break\n case 'stop':\n this.log('Stream stopped')\n break\n }\n }\n\n protected writeAudio(pcm: Buffer) {\n this.sendJson({\n event: 'media',\n streamSid: this.call.streamId,\n media: { payload: pcm16ToMulaw(pcm).toString('base64') },\n })\n }\n\n protected writeClear() {\n this.sendJson({ event: 'clear', streamSid: this.call.streamId })\n }\n\n protected writeMark(name: string) {\n this.sendJson({ event: 'mark', streamSid: this.call.streamId, mark: { name } })\n }\n\n private sendJson(message: object) {\n if (this.isOpen) this.socket.send(JSON.stringify(message))\n }\n}\n\nexport interface TwilioStreamOptions {\n /** Address of the WebSocket that runs the call, `wss://` only */\n url: string\n /**\n * Parameters of the call, which `waitForParams` hands back. Twilio takes no\n * query string in the address, so this is how a call carries its context.\n */\n parameters?: Record<string, string | number | boolean>\n /** TwiML to say before the stream, for instance a recording notice */\n before?: string\n}\n\n/**\n * Writes the TwiML that connects a call to a Micdrop server, to answer the\n * voice webhook of a Twilio number with\n * @returns The TwiML document\n */\nexport function twilioStreamTwiml({\n url,\n parameters = {},\n before = '',\n}: TwilioStreamOptions): string {\n const params = Object.entries(parameters)\n .map(\n ([name, value]) =>\n `<Parameter name=\"${escapeXml(name)}\" value=\"${escapeXml(String(value))}\" />`\n )\n .join('')\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?><Response>${before}<Connect><Stream url=\"${escapeXml(url)}\">${params}</Stream></Connect></Response>`\n}\n","import { parseJson, TelephonyTransport } from './TelephonyTransport'\n\n// Keys of the headers that carry the call itself, set by vonageConnectNcco()\nconst CALL_HEADERS = {\n callId: 'micdropCallId',\n from: 'micdropFrom',\n to: 'micdropTo',\n} as const\n\n/**\n * A call from the Vonage Voice API, connected to a WebSocket by the\n * `connect` action of its NCCO, which {@link vonageConnectNcco} writes.\n *\n * Audio travels both ways as binary frames of 16 bits linear PCM, little\n * endian, at the rate of the `content-type` of the NCCO: 16 kHz by default,\n * twice the quality of a regular phone line. The NCCO headers are the\n * parameters of the call.\n *\n * @see https://developer.vonage.com/en/voice/voice-api/concepts/websockets\n */\nexport class VonageTransport extends TelephonyTransport {\n private rate: number\n\n /**\n * @param socket - The socket Vonage opened\n * @param options - The rate of the NCCO, read again from the first message\n */\n constructor(\n socket: ConstructorParameters<typeof TelephonyTransport>[0],\n options: { sampleRate?: number } = {}\n ) {\n super(socket)\n this.rate = options.sampleRate ?? 16000\n }\n\n protected get lineRate() {\n return this.rate\n }\n\n protected onProviderMessage(data: Buffer, isBinary: boolean) {\n if (isBinary) {\n this.receiveAudio(data)\n return\n }\n const message = parseJson(data)\n switch (message?.event) {\n case 'websocket:connected': {\n const { event, 'content-type': contentType, ...headers } = message\n const rate = /rate=(\\d+)/.exec(contentType ?? '')?.[1]\n if (rate) this.rate = Number(rate)\n const call = {\n callId: headers[CALL_HEADERS.callId],\n from: headers[CALL_HEADERS.from],\n to: headers[CALL_HEADERS.to],\n }\n for (const key of Object.values(CALL_HEADERS)) delete headers[key]\n delete headers.reconnect_attempt\n this.startStream(call, headers)\n break\n }\n case 'websocket:notify':\n this.markPlayed(message.payload?.micdropMark)\n break\n case 'websocket:dtmf':\n this.receiveDtmf(String(message.digit))\n break\n }\n }\n\n protected writeAudio(pcm: Buffer) {\n if (this.isOpen) this.socket.send(pcm)\n }\n\n protected writeClear() {\n this.sendJson({ action: 'clear' })\n }\n\n protected writeMark(name: string) {\n this.sendJson({ action: 'notify', payload: { micdropMark: name } })\n }\n\n private sendJson(message: object) {\n if (this.isOpen) this.socket.send(JSON.stringify(message))\n }\n}\n\nexport interface VonageConnectOptions {\n /** Address of the WebSocket that runs the call */\n url: string\n /** Parameters of the call, which `waitForParams` hands back */\n parameters?: Record<string, string | number | boolean>\n /**\n * The call, as the answer webhook describes it (`uuid`, `from`, `to`), so\n * the transport knows which call it carries\n */\n call?: { uuid?: string; from?: string; to?: string }\n /** Rate of the audio, 16000 by default */\n sampleRate?: 8000 | 16000 | 24000\n /** Where Vonage sends the events of the WebSocket leg */\n eventUrl?: string\n}\n\n/**\n * Writes the NCCO that connects a call to a Micdrop server, to answer the\n * answer webhook of a Vonage application with\n * @returns The NCCO, to send as JSON\n */\nexport function vonageConnectNcco({\n url,\n parameters = {},\n call,\n sampleRate = 16000,\n eventUrl,\n}: VonageConnectOptions): object[] {\n const headers: Record<string, string | number | boolean> = { ...parameters }\n if (call?.uuid) headers[CALL_HEADERS.callId] = call.uuid\n if (call?.from) headers[CALL_HEADERS.from] = call.from\n if (call?.to) headers[CALL_HEADERS.to] = call.to\n return [\n {\n action: 'connect',\n ...(eventUrl ? { eventUrl: [eventUrl] } : {}),\n endpoint: [\n {\n type: 'websocket',\n uri: url,\n 'content-type': `audio/l16;rate=${sampleRate}`,\n headers,\n },\n ],\n },\n ]\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACQA,IAAM,aAAa;AACnB,IAAM,aAAa;AAGnB,IAAM,eAAe,IAAI,WAAW,GAAG;AACvC,IAAM,cAAc,IAAI,WAAW,GAAG;AACtC,SAAS,IAAI,GAAG,IAAI,KAAK,KAAK;AAC5B,eAAa,CAAC,IAAI,kBAAkB,CAAC;AACrC,cAAY,CAAC,IAAI,iBAAiB,CAAC;AACrC;AAEA,SAAS,kBAAkB,MAAsB;AAC/C,QAAM,QAAQ,CAAC,OAAO;AACtB,QAAM,OAAO,QAAQ;AACrB,QAAM,WAAY,SAAS,IAAK;AAChC,QAAM,WAAW,QAAQ;AACzB,QAAM,aAAc,YAAY,KAAK,cAAe;AACpD,SAAO,OAAO,aAAa,YAAY,YAAY;AACrD;AAEA,SAAS,kBAAkB,QAAwB;AACjD,QAAM,OAAO,SAAS,IAAI,MAAO;AACjC,MAAI,YAAY,KAAK,IAAI,KAAK,IAAI,MAAM,GAAG,UAAU,IAAI;AACzD,MAAI,WAAW;AACf,WAAS,OAAO,QAAS,YAAY,UAAU,KAAK,WAAW,GAAG,SAAS,GAAG;AAC5E;AAAA,EACF;AACA,QAAM,WAAY,aAAc,WAAW,IAAM;AACjD,SAAO,EAAE,OAAQ,YAAY,IAAK,YAAY;AAChD;AAEA,SAAS,iBAAiB,MAAsB;AAC9C,QAAM,QAAQ,OAAO;AACrB,QAAM,OAAO,QAAQ;AACrB,QAAM,WAAY,SAAS,IAAK;AAChC,QAAM,WAAW,QAAQ;AACzB,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K,OAAO,KAAK,KAAK,UAAU,OAAO,CAAC;AAAA,EAC3D;AACF;AAuBO,SAAS,kBAAkB;AAAA,EAChC;AAAA,EACA,aAAa,CAAC;AAAA,EACd;AAAA,EACA,aAAa;AAAA,EACb;AACF,GAAmC;AACjC,QAAM,UAAqD,EAAE,GAAG,WAAW;AAC3E,MAAI,MAAM,KAAM,SAAQ,aAAa,MAAM,IAAI,KAAK;AACpD,MAAI,MAAM,KAAM,SAAQ,aAAa,IAAI,IAAI,KAAK;AAClD,MAAI,MAAM,GAAI,SAAQ,aAAa,EAAE,IAAI,KAAK;AAC9C,SAAO;AAAA,IACL;AAAA,MACE,QAAQ;AAAA,MACR,GAAI,WAAW,EAAE,UAAU,CAAC,QAAQ,EAAE,IAAI,CAAC;AAAA,MAC3C,UAAU;AAAA,QACR;AAAA,UACE,MAAM;AAAA,UACN,KAAK;AAAA,UACL,gBAAgB,kBAAkB,UAAU;AAAA,UAC5C;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/dtmf.ts","../src/g711.ts","../src/http.ts","../src/TelephonyTransport.ts","../src/xml.ts","../src/plivo.ts","../src/signatures.ts","../src/telnyx.ts","../src/twilio.ts","../src/vonage.ts","../src/TelephonyCalls.ts","../src/tools.ts","../src/voicemail.ts"],"sourcesContent":["export * from './dtmf'\nexport * from './g711'\nexport * from './http'\nexport * from './plivo'\nexport * from './signatures'\nexport * from './TelephonyCalls'\nexport * from './TelephonyTransport'\nexport * from './telnyx'\nexport * from './tools'\nexport * from './twilio'\nexport * from './voicemail'\nexport * from './vonage'\n","/** Keys a phone keypad sends, and the pauses providers accept between them */\nexport const DTMF_DIGITS = /^[0-9A-D*#wW]+$/\n\nconst ROWS = [697, 770, 852, 941]\nconst COLUMNS = [1209, 1336, 1477, 1633]\nconst KEYPAD = ['123A', '456B', '789C', '*0#D']\n\n// Long enough for any receiver, ITU-T Q.24 asks for 40 ms at least\nconst TONE = 120 // ms\nconst GAP = 80 // ms\n// Each of the two tones, about -9 dBm0 on a phone line\nconst AMPLITUDE = 0.25 * 32767\n\n/**\n * Checks keys to send, and fails loudly on anything a keypad cannot send\n * @param digits - Keys, with `w` for a pause of 0.5 s and `W` for 1 s\n */\nexport function checkDtmfDigits(digits: string): string {\n if (typeof digits !== 'string' || !DTMF_DIGITS.test(digits)) {\n throw new Error(\n `Invalid DTMF digits \"${digits}\": use 0-9, *, #, A-D, and w or W to pause`\n )\n }\n return digits\n}\n\n/**\n * Synthesizes keys as the dual tones of a keypad, for a line that carries\n * them in its audio\n * @param digits - Keys, with `w` for a pause of 0.5 s and `W` for 1 s\n * @param sampleRate - Rate of the audio, in Hz\n * @returns PCM16 mono\n */\nexport function dtmfTones(digits: string, sampleRate: number): Buffer {\n checkDtmfDigits(digits)\n const parts: Buffer[] = []\n const samples = (ms: number) => Math.round((sampleRate * ms) / 1000)\n for (const digit of digits) {\n if (digit === 'w' || digit === 'W') {\n parts.push(Buffer.alloc(samples(digit === 'w' ? 500 : 1000) * 2))\n continue\n }\n const row = KEYPAD.findIndex((keys) => keys.includes(digit))\n const column = KEYPAD[row].indexOf(digit)\n const low = ROWS[row]\n const high = COLUMNS[column]\n const count = samples(TONE)\n const tone = Buffer.alloc(count * 2)\n for (let i = 0; i < count; i++) {\n const t = i / sampleRate\n const value =\n AMPLITUDE *\n (Math.sin(2 * Math.PI * low * t) + Math.sin(2 * Math.PI * high * t))\n tone.writeInt16LE(Math.round(value), i * 2)\n }\n parts.push(tone, Buffer.alloc(samples(GAP) * 2))\n }\n return Buffer.concat(parts)\n}\n","/**\n * G.711, the codec of the phone network: one byte per sample at 8 kHz, with a\n * logarithmic scale that keeps quiet speech as precise as loud speech.\n *\n * μ-law is the variant of North America and Japan, A-law that of the rest of\n * the world. Both take and give PCM16 mono, little endian.\n */\n\nconst MULAW_BIAS = 0x84\nconst MULAW_CLIP = 32635\n\n// Decoding is a table lookup, built once\nconst MULAW_TO_PCM = new Int16Array(256)\nconst ALAW_TO_PCM = new Int16Array(256)\nfor (let i = 0; i < 256; i++) {\n MULAW_TO_PCM[i] = decodeMulawSample(i)\n ALAW_TO_PCM[i] = decodeAlawSample(i)\n}\n\nfunction decodeMulawSample(byte: number): number {\n const value = ~byte & 0xff\n const sign = value & 0x80\n const exponent = (value >> 4) & 0x07\n const mantissa = value & 0x0f\n const magnitude = ((mantissa << 3) + MULAW_BIAS) << exponent\n return sign ? MULAW_BIAS - magnitude : magnitude - MULAW_BIAS\n}\n\nfunction encodeMulawSample(sample: number): number {\n const sign = sample < 0 ? 0x80 : 0\n let magnitude = Math.min(Math.abs(sample), MULAW_CLIP) + MULAW_BIAS\n let exponent = 7\n for (\n let mask = 0x4000;\n (magnitude & mask) === 0 && exponent > 0;\n mask >>= 1\n ) {\n exponent--\n }\n const mantissa = (magnitude >> (exponent + 3)) & 0x0f\n return ~(sign | (exponent << 4) | mantissa) & 0xff\n}\n\nfunction decodeAlawSample(byte: number): number {\n const value = byte ^ 0x55\n const sign = value & 0x80\n const exponent = (value >> 4) & 0x07\n const mantissa = value & 0x0f\n let magnitude =\n exponent === 0\n ? (mantissa << 4) + 8\n : ((mantissa << 4) + 0x108) << (exponent - 1)\n return sign ? magnitude : -magnitude\n}\n\nfunction encodeAlawSample(sample: number): number {\n const sign = sample >= 0 ? 0x80 : 0\n let magnitude = Math.min(Math.abs(sample), 32767)\n let byte: number\n if (magnitude >= 256) {\n let exponent = 7\n for (let mask = 0x4000; (magnitude & mask) === 0; mask >>= 1) exponent--\n const mantissa = (magnitude >> (exponent + 3)) & 0x0f\n byte = (exponent << 4) | mantissa\n } else {\n byte = magnitude >> 4\n }\n return (byte | sign) ^ 0x55\n}\n\n/**\n * Decodes μ-law bytes\n * @param bytes - One byte per sample\n * @returns PCM16 mono, little endian\n */\nexport function mulawToPcm16(bytes: Uint8Array): Buffer {\n const pcm = Buffer.alloc(bytes.length * 2)\n for (let i = 0; i < bytes.length; i++) {\n pcm.writeInt16LE(MULAW_TO_PCM[bytes[i]], i * 2)\n }\n return pcm\n}\n\n/**\n * Encodes PCM16 as μ-law\n * @param pcm - PCM16 mono, little endian\n * @returns One byte per sample\n */\nexport function pcm16ToMulaw(pcm: Buffer): Buffer {\n const count = pcm.length >> 1\n const bytes = Buffer.alloc(count)\n for (let i = 0; i < count; i++) {\n bytes[i] = encodeMulawSample(pcm.readInt16LE(i * 2))\n }\n return bytes\n}\n\n/**\n * Decodes A-law bytes\n * @param bytes - One byte per sample\n * @returns PCM16 mono, little endian\n */\nexport function alawToPcm16(bytes: Uint8Array): Buffer {\n const pcm = Buffer.alloc(bytes.length * 2)\n for (let i = 0; i < bytes.length; i++) {\n pcm.writeInt16LE(ALAW_TO_PCM[bytes[i]], i * 2)\n }\n return pcm\n}\n\n/**\n * Encodes PCM16 as A-law\n * @param pcm - PCM16 mono, little endian\n * @returns One byte per sample\n */\nexport function pcm16ToAlaw(pcm: Buffer): Buffer {\n const count = pcm.length >> 1\n const bytes = Buffer.alloc(count)\n for (let i = 0; i < count; i++) {\n bytes[i] = encodeAlawSample(pcm.readInt16LE(i * 2))\n }\n return bytes\n}\n","/** A request to the API of a provider that did not succeed */\nexport class TelephonyApiError extends Error {\n constructor(\n message: string,\n public readonly status: number,\n public readonly body: string\n ) {\n super(message)\n this.name = 'TelephonyApiError'\n }\n}\n\n/**\n * Calls the API of a provider, and throws with what it answered when the\n * request fails\n * @param what - What the request does, for the error message\n * @returns The JSON body of the answer, or undefined when there is none\n */\nexport async function callApi(\n what: string,\n url: string,\n init: RequestInit\n): Promise<any> {\n const response = await fetch(url, init)\n const text = await response.text().catch(() => '')\n if (!response.ok) {\n throw new TelephonyApiError(\n `${what} failed: ${response.status} ${text.slice(0, 500)}`.trim(),\n response.status,\n text\n )\n }\n if (!text) return undefined\n try {\n return JSON.parse(text)\n } catch {\n return text\n }\n}\n\n/** Encodes fields as a form, for the APIs that read one */\nexport function formBody(fields: Record<string, unknown>): URLSearchParams {\n const body = new URLSearchParams()\n for (const [key, value] of Object.entries(fields)) {\n if (value === undefined || value === null) continue\n if (Array.isArray(value)) {\n for (const item of value) body.append(key, String(item))\n } else {\n body.append(key, String(value))\n }\n }\n return body\n}\n\n/** Waits for a while */\nexport function sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n/** Fails loudly when a credential the action needs is missing */\nexport function requireOption<T>(\n value: T | undefined | null | '',\n message: string\n): T {\n if (value === undefined || value === null || value === '') {\n throw new Error(message)\n }\n return value\n}\n","import {\n DEFAULT_SAMPLE_RATE,\n listenToWebSocket,\n MicdropServerMessage,\n MicdropTransport,\n MicdropTransportEvents,\n Pcm16Resampler,\n StandardWebSocket,\n} from '@micdrop/server'\nimport type { RawData, WebSocket } from 'ws'\nimport { checkDtmfDigits, dtmfTones } from './dtmf'\n\n/** What the provider says about the call, once its stream has started */\nexport interface TelephonyCall {\n /** Identifier of the call at the provider, to act on it with its API */\n callId?: string\n /** Identifier of the media stream at the provider */\n streamId?: string\n /** Number of the caller, when the provider passes it */\n from?: string\n /** Number called, when the provider passes it */\n to?: string\n /**\n * Whether the call came in or went out, when known: the outbound helpers\n * of this package mark the calls they make\n */\n direction?: 'inbound' | 'outbound'\n}\n\n/** Who picked up an outbound call, as the provider detected it */\nexport type AnsweredBy = 'human' | 'machine' | 'fax' | 'unknown'\n\n/** What the answering machine detection of the provider found */\nexport interface MachineDetection {\n /** Who picked up */\n answeredBy: AnsweredBy\n /**\n * Whether the greeting of the machine is over, the beep heard or the line\n * silent, so a message left now is recorded whole\n */\n greetingEnded: boolean\n /** What the provider sent, as it sent it */\n raw?: unknown\n}\n\n/** Where to send a call, and how */\nexport interface TransferOptions {\n /** Phone number in E.164 format, such as `+14155550100`, or a SIP URI */\n to: string\n /**\n * Number the person reached sees, one of your account. Each provider has\n * its own default, read on the page of its transport.\n */\n from?: string\n /** How long to let the phone ring, in seconds, 30 by default */\n timeout?: number\n}\n\n/** A transfer where the assistant reaches the person before the caller */\nexport interface WarmTransferOptions extends TransferOptions {\n /**\n * What the person reached hears before the caller joins them: who calls,\n * and what for. The voice of the provider speaks it.\n */\n briefing?: string\n}\n\n/** Why a warm transfer did not reach anybody */\nexport type WarmTransferFailure =\n 'busy' | 'no-answer' | 'voicemail' | 'failed' | 'hung-up'\n\nexport type WarmTransferResult =\n { transferred: true } | { transferred: false; reason: WarmTransferFailure }\n\nexport interface TelephonyTransportEvents extends MicdropTransportEvents {\n /** The answering machine detection of the provider found who picked up */\n MachineDetection: [MachineDetection]\n /** The call left the assistant for another destination */\n Transferred: [to: string]\n}\n\n/**\n * How long a hang up waits for the goodbye to be played, at most. A provider\n * that never confirms the playback still sees the call end.\n */\nconst PLAYBACK_MAX_WAIT = 20000 // ms\n\n/**\n * How long before the provider runs out of audio a frame left incomplete goes\n * out padded with silence. Until then it waits for the rest of the answer, so\n * no silence lands in the middle of a sentence.\n */\nconst FRAME_FLUSH_MARGIN = 40 // ms\n\n/** How long a frame left incomplete waits at least, when nothing plays */\nconst FRAME_MIN_WAIT = 20 // ms\n\n/**\n * A phone call carried over the media stream WebSocket of a telephony\n * provider.\n *\n * The provider streams the caller as audio at the rate of the line, 8 kHz for\n * most, and plays back what it is sent, buffering it on its side. This class\n * does what all of them need: audio brought to 16 kHz for the server and to\n * the rate of the line for the provider, frames of a fixed duration when the\n * provider wants them, playback confirmed by marks, and a hang up once the\n * goodbye is played. Each provider writes and reads its own messages.\n *\n * A phone line has no client to find the turns: the server needs `turns.vad`.\n */\nexport abstract class TelephonyTransport extends MicdropTransport<TelephonyTransportEvents> {\n readonly clientTurns = false\n readonly hangsUp = true\n\n /** What the provider said about the call */\n public call: TelephonyCall = {}\n\n /**\n * What the answering machine detection of the provider found, once it\n * reported, for the outbound calls that asked for it\n */\n public machineDetection?: MachineDetection\n\n /** Where the call was transferred, once it left the assistant */\n public transferredTo?: string\n\n /**\n * Duration of the frames the provider wants, in ms. 0 sends the audio as it\n * comes, for the providers that take any size.\n */\n protected frameDuration = 20\n\n // The provider is ready for audio once its stream has started\n private ready = false\n private pendingWrites: (() => void)[] = []\n private inputResampler?: Pcm16Resampler\n private inputRate = 0\n private outputResampler?: Pcm16Resampler\n private outputRate = 0\n private frameRemainder = Buffer.alloc(0)\n private frameTimer?: ReturnType<typeof setTimeout>\n // When the audio sent so far will be done playing, at the pace of the line\n private playoutEnd = 0\n private markCounter = 0\n private playbackWaiters = new Map<string, () => void>()\n private closed = false\n private handedOff = false\n\n /**\n * @param socket - The socket the provider opened, as the `ws` server hands\n * it, or a standard WebSocket, the server half of a Cloudflare\n * `WebSocketPair` for instance\n */\n constructor(public readonly socket: WebSocket | StandardWebSocket) {\n super()\n listenToWebSocket(socket, {\n message: this.onSocketMessage,\n close: this.onSocketClose,\n })\n }\n\n /** Rate of the audio on the line, in Hz */\n protected abstract get lineRate(): number\n\n /**\n * Reads a message of the provider\n * @param data - The message, text or binary\n * @param isBinary - Whether it came as a binary frame\n */\n protected abstract onProviderMessage(data: Buffer, isBinary: boolean): void\n\n /**\n * Sends audio to be played\n * @param pcm - PCM16 mono at the rate of the line, one frame when\n * `frameDuration` is set\n */\n protected abstract writeAudio(pcm: Buffer): void\n\n /** Asks the provider to drop the audio it holds and not played yet */\n protected abstract writeClear(): void\n\n /**\n * Asks the provider to say when the audio sent so far has been played\n * @param name - What the provider sends back, given to `markPlayed()`\n */\n protected abstract writeMark(name: string): void\n\n get isOpen(): boolean {\n return !this.closed && (this.socket.readyState ?? 1) === 1\n }\n\n // A phone line has nobody to read the messages of the server\n send(message: MicdropServerMessage) {\n if (message.type === 'EndCall') {\n this.logger.debug('The assistant ends the call')\n }\n }\n\n sendAudio(audio: Buffer, sampleRate: number) {\n if (!(sampleRate > 0) || !Number.isFinite(sampleRate)) {\n throw new Error(\n `${this.constructor.name}: invalid sample rate ${sampleRate} for the assistant voice`\n )\n }\n if (!this.isOpen) return\n const pcm = this.toLineRate(audio, sampleRate)\n if (pcm.length === 0) return\n\n if (!this.frameDuration) {\n this.whenReady(() => this.writePacedAudio(pcm))\n return\n }\n\n // Whole frames go now, the rest waits for the next chunk\n const frameBytes = this.frameBytes\n let data = Buffer.concat([this.frameRemainder, pcm])\n while (data.length >= frameBytes) {\n const frame = data.subarray(0, frameBytes)\n this.whenReady(() => this.writePacedAudio(frame))\n data = data.subarray(frameBytes)\n }\n this.frameRemainder = data\n this.scheduleFrameFlush()\n }\n\n clearAudio() {\n this.cancelFrameFlush()\n this.frameRemainder = Buffer.alloc(0)\n this.playoutEnd = 0\n // Audio queued before the stream started never reached the provider\n this.pendingWrites = []\n if (this.ready && this.isOpen) this.writeClear()\n // What was waiting for its playback has been dropped instead\n this.resolvePlayback()\n }\n\n waitForPlayback(): Promise<void> {\n if (!this.isOpen) return Promise.resolve()\n this.flushFrame()\n const name = `micdrop-${++this.markCounter}`\n return new Promise<void>((resolve) => {\n const timer = setTimeout(() => {\n this.logger.warn('The provider never confirmed the playback')\n done()\n }, PLAYBACK_MAX_WAIT)\n const done = () => {\n clearTimeout(timer)\n this.playbackWaiters.delete(name)\n resolve()\n }\n this.playbackWaiters.set(name, done)\n this.whenReady(() => this.writeMark(name))\n })\n }\n\n /**\n * Ends the stream, and the call with it: closing the socket is enough for\n * the providers that end the call when nothing follows the stream, the\n * others hang up through their API in `hangUp()`. A call transferred\n * elsewhere goes on without the assistant.\n */\n close(code = 1000, reason?: string) {\n if (this.closed) return\n this.cancelFrameFlush()\n if (!this.handedOff) {\n this.hangUp().catch((error) =>\n this.logger.error('Hang up failed', { error })\n )\n }\n if ((this.socket.readyState ?? 1) <= 1) this.socket.close(code, reason)\n }\n\n /**\n * Sends keys on the line, to navigate the menu of the phone system the\n * assistant called. Resolves once they have been sent.\n *\n * Providers that send keys through their API or their stream do it there.\n * The others carry them in the audio, as the dual tones of a keypad.\n *\n * @param digits - Keys among 0-9, *, # and A-D, with `w` for a pause of\n * 0.5 s and `W` for 1 s\n */\n async sendDtmf(digits: string): Promise<void> {\n checkDtmfDigits(digits)\n this.logger.debug('Sending DTMF in the audio', { digits })\n this.sendAudio(dtmfTones(digits, this.lineRate), this.lineRate)\n await this.waitForPlayback()\n }\n\n /**\n * Sends keys a piece at a time, waiting where they ask for a pause, for the\n * providers that take no pause in the keys they send\n * @param send - Sends keys without pauses\n */\n protected async sendDtmfWithPauses(\n digits: string,\n send: (keys: string) => Promise<void>\n ) {\n checkDtmfDigits(digits)\n for (const part of digits.split(/([wW]+)/)) {\n if (!part) continue\n if (/^[wW]+$/.test(part)) {\n let pause = 0\n for (const char of part) pause += char === 'w' ? 500 : 1000\n await new Promise((resolve) => setTimeout(resolve, pause))\n } else {\n await send(part)\n }\n }\n }\n\n /** The number of the account on the call, to call from in a transfer */\n protected get ownNumber(): string | undefined {\n return this.call.direction === 'outbound' ? this.call.from : this.call.to\n }\n\n /**\n * Sends the call to another number, and leaves it: the assistant is no\n * longer on the line once it resolves. Rejects when the provider refuses.\n *\n * @param options - Where to send the call\n */\n async transfer(options: TransferOptions): Promise<void> {\n throw new Error(\n `${this.constructor.name} cannot transfer calls (to ${options.to})`\n )\n }\n\n /**\n * Reaches a person first, tells them about the call, then connects the\n * caller to them and leaves. The assistant stays on the line with the\n * caller while the phone rings, and keeps it when nobody takes the call.\n *\n * @param options - Who to reach, and what to tell them\n * @returns Whether the caller was connected, or why not\n */\n async warmTransfer(\n options: WarmTransferOptions\n ): Promise<WarmTransferResult> {\n throw new Error(\n `${this.constructor.name} cannot make warm transfers (to ${options.to})`\n )\n }\n\n /**\n * Takes the result of the answering machine detection of the provider,\n * which reaches the server through a webhook for most of them.\n * `TelephonyCalls` routes the webhooks of a server to the right transport.\n */\n receiveMachineDetection(detection: MachineDetection) {\n // A greeting that ended belongs to the machine detected earlier\n const answeredBy =\n detection.answeredBy === 'unknown' && this.machineDetection\n ? this.machineDetection.answeredBy\n : detection.answeredBy\n this.machineDetection = { ...detection, answeredBy }\n this.logger.info('Machine detection', { ...this.machineDetection })\n this.emit('MachineDetection', this.machineDetection)\n }\n\n /**\n * Resolves with the result of the answering machine detection, as soon as\n * there is one, or undefined once `timeout` ms passed without any\n */\n waitForMachineDetection(\n timeout = 10000\n ): Promise<MachineDetection | undefined> {\n if (this.machineDetection) return Promise.resolve(this.machineDetection)\n return new Promise((resolve) => {\n const done = (detection?: MachineDetection) => {\n clearTimeout(timer)\n this.off('MachineDetection', done)\n this.off('Close', onClose)\n resolve(detection)\n }\n const onClose = () => done()\n const timer = setTimeout(done, timeout)\n this.on('MachineDetection', done)\n this.on('Close', onClose)\n })\n }\n\n /** Hangs up through the API of the provider, for those that need it */\n protected async hangUp(): Promise<void> {}\n\n /**\n * The call now goes on without the assistant: ends the stream without\n * hanging up\n * @param to - Where the call went\n */\n protected handOff(to: string) {\n this.logger.info('Call transferred', { to })\n this.handedOff = true\n this.transferredTo = to\n this.clearAudio()\n this.emit('Transferred', to)\n this.close(1000, 'Transferred')\n }\n\n /**\n * Ends the call on a misconfiguration that would leave it garbled or\n * silent, and says why where it cannot be missed\n * @param reason - What is wrong, and how to fix it\n */\n protected fail(reason: string) {\n this.logger.error('Misconfigured call', { reason })\n this.close(1011, reason.slice(0, 120))\n }\n\n /**\n * The stream has started: keeps what the provider said about the call and\n * sends the audio that waited for it\n * @param call - Identifiers and numbers of the call\n * @param params - Custom parameters of the call, if any\n */\n protected startStream(call: TelephonyCall, params?: any) {\n this.call = { ...this.call, ...call }\n this.logger.info('Stream started', { ...this.call })\n this.ready = true\n const writes = this.pendingWrites\n this.pendingWrites = []\n for (const write of writes) write()\n this.receiveParams(params ?? {})\n }\n\n /**\n * Hands audio of the caller to the server\n * @param pcm - PCM16 mono at the rate of the line\n */\n protected receiveAudio(pcm: Buffer) {\n if (pcm.length === 0) return\n const rate = this.lineRate\n if (rate !== this.inputRate) {\n this.inputRate = rate\n this.inputResampler = new Pcm16Resampler(rate, DEFAULT_SAMPLE_RATE)\n }\n const audio = this.inputResampler!.process(pcm)\n if (audio.length) this.emit('Audio', audio)\n }\n\n /** The provider played the audio sent before a mark */\n protected markPlayed(name: string) {\n this.playbackWaiters.get(name)?.()\n }\n\n /** A key was pressed on the keypad of the phone */\n protected receiveDtmf(digit: unknown) {\n const key = String(digit ?? '')\n if (!/^[0-9A-D*#]$/i.test(key)) {\n this.logger.warn('Unreadable DTMF digit ignored', { key })\n return\n }\n this.logger.debug('DTMF', { key })\n this.emit('Dtmf', key.toUpperCase())\n }\n\n /** Writes audio, keeping track of when the provider will be done playing it */\n private writePacedAudio(pcm: Buffer) {\n const duration = (pcm.length / 2 / this.lineRate) * 1000\n this.playoutEnd = Math.max(this.playoutEnd, Date.now()) + duration\n this.writeAudio(pcm)\n }\n\n /** Bytes in one outgoing frame */\n protected get frameBytes(): number {\n return Math.round((this.lineRate * this.frameDuration) / 1000) * 2\n }\n\n private toLineRate(audio: Buffer, sampleRate: number): Buffer {\n const rate = this.lineRate\n if (sampleRate === rate) return audio\n if (sampleRate !== this.outputRate) {\n this.outputRate = sampleRate\n this.outputResampler = new Pcm16Resampler(sampleRate, rate)\n }\n return this.outputResampler!.process(audio)\n }\n\n private whenReady(write: () => void) {\n if (this.ready) write()\n else this.pendingWrites.push(write)\n }\n\n /** Sends the incomplete frame left, padded with silence */\n private flushFrame() {\n this.cancelFrameFlush()\n if (this.frameRemainder.length === 0) return\n const frame = Buffer.alloc(this.frameBytes)\n this.frameRemainder.copy(frame)\n this.frameRemainder = Buffer.alloc(0)\n this.whenReady(() => this.writePacedAudio(frame))\n }\n\n /**\n * Sends the incomplete frame left once the provider is about to run out of\n * audio, if the rest of the answer has not come by then\n */\n private scheduleFrameFlush() {\n this.cancelFrameFlush()\n if (this.frameRemainder.length === 0) return\n const delay = Math.max(\n this.playoutEnd - Date.now() - FRAME_FLUSH_MARGIN,\n FRAME_MIN_WAIT\n )\n this.frameTimer = setTimeout(() => this.flushFrame(), delay)\n }\n\n private cancelFrameFlush() {\n if (!this.frameTimer) return\n clearTimeout(this.frameTimer)\n this.frameTimer = undefined\n }\n\n private resolvePlayback() {\n for (const done of [...this.playbackWaiters.values()]) done()\n }\n\n private onSocketMessage = (buffer: Buffer, isBinary: boolean | undefined) => {\n try {\n this.onProviderMessage(buffer, isBinary ?? false)\n } catch (error) {\n this.logger.warn('Unreadable message from the provider', { error })\n }\n }\n\n private onSocketClose = (\n code: number | undefined,\n reason: string | undefined\n ) => {\n this.closed = true\n this.cancelFrameFlush()\n this.resolvePlayback()\n this.emit('Close', code, reason)\n }\n}\n\n/** Reads a JSON text message, or nothing when it is not one */\nexport function parseJson(data: Buffer): any {\n try {\n return JSON.parse(data.toString())\n } catch {\n return undefined\n }\n}\n","/** Escapes a value for an XML attribute or text */\nexport function escapeXml(value: string): string {\n return value\n .replace(/&/g, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\n .replace(/'/g, ''')\n}\n","import { mulawToPcm16, pcm16ToMulaw } from './g711'\nimport { callApi, requireOption } from './http'\nimport {\n MachineDetection,\n parseJson,\n TelephonyTransport,\n TransferOptions,\n} from './TelephonyTransport'\nimport { escapeXml } from './xml'\n\n/** Credentials of a Plivo account, to act on calls through its API */\nexport interface PlivoCredentials {\n authId: string\n authToken: string\n}\n\nexport interface PlivoTransportOptions extends Partial<PlivoCredentials> {\n /**\n * Address of the XML that dials the destination of a transfer, as Plivo\n * only transfers a call to an XML it fetches. Given the transfer, it\n * returns the address of a route of your server that answers with\n * {@link plivoTransferXml}.\n */\n transferUrl?: (options: TransferOptions) => string\n}\n\nconst API = 'https://api.plivo.com/v1'\n// How long Plivo takes to play a key, a little more than its tone\nconst DTMF_KEY_DURATION = 250 // ms\n\n/**\n * A call from Plivo, over a bidirectional audio stream.\n *\n * Plivo opens the WebSocket when the call reaches the `<Stream>` of its XML,\n * which {@link plivoStreamXml} writes. The caller comes in μ-law at 8 kHz, and\n * the assistant goes back the same way. The extra headers of the stream are\n * the parameters of the call.\n *\n * @see https://www.plivo.com/docs/voice-agents/audio-streaming/concepts/audio-streaming-reference\n */\nexport class PlivoTransport extends TelephonyTransport {\n /**\n * @param socket - The socket Plivo opened\n * @param options - Credentials to hang up and transfer with\n */\n constructor(\n socket: ConstructorParameters<typeof TelephonyTransport>[0],\n private options: PlivoTransportOptions = {}\n ) {\n super(socket)\n }\n\n protected get lineRate() {\n return 8000\n }\n\n protected onProviderMessage(data: Buffer) {\n const message = parseJson(data)\n switch (message?.event) {\n case 'start': {\n const start = message.start ?? {}\n const format = start.mediaFormat\n if (\n format &&\n (format.encoding !== 'audio/x-mulaw' ||\n Number(format.sampleRate) !== 8000)\n ) {\n this.fail(\n `Plivo streams ${format.encoding} at ${format.sampleRate} Hz, PlivoTransport reads audio/x-mulaw at 8000 Hz: set the contentType of the <Stream>, as plivoStreamXml() does`\n )\n return\n }\n this.startStream(\n {\n callId: start.callId,\n streamId: start.streamId,\n from: start.from,\n to: start.to,\n },\n parseExtraHeaders(message.extra_headers)\n )\n break\n }\n case 'media':\n if (message.media?.track && message.media.track !== 'inbound') return\n this.receiveAudio(\n mulawToPcm16(Buffer.from(message.media?.payload ?? '', 'base64'))\n )\n break\n case 'playedStream':\n this.markPlayed(message.name)\n break\n case 'dtmf':\n this.receiveDtmf(message.dtmf?.digit)\n break\n }\n }\n\n protected writeAudio(pcm: Buffer) {\n this.sendJson({\n event: 'playAudio',\n media: {\n contentType: 'audio/x-mulaw',\n sampleRate: 8000,\n payload: pcm16ToMulaw(pcm).toString('base64'),\n },\n })\n }\n\n protected writeClear() {\n this.sendJson({ event: 'clearAudio', streamId: this.call.streamId })\n }\n\n protected writeMark(name: string) {\n this.sendJson({ event: 'checkpoint', streamId: this.call.streamId, name })\n }\n\n /** Sends the keys over the stream, which Plivo plays on the call */\n async sendDtmf(digits: string) {\n await this.sendDtmfWithPauses(digits, async (keys) => {\n this.sendJson({ event: 'sendDTMF', dtmf: keys })\n await new Promise((resolve) =>\n setTimeout(resolve, keys.length * DTMF_KEY_DURATION)\n )\n })\n }\n\n /**\n * Transfers the call to the XML at `transferUrl`, which dials the\n * destination and ends the stream\n */\n async transfer(options: TransferOptions) {\n const { authId, authToken, transferUrl } = this.options\n const callId = requireOption(\n this.call.callId,\n 'PlivoTransport: the stream has not started, the call is unknown'\n )\n const url = requireOption(\n transferUrl?.(options),\n 'PlivoTransport needs transferUrl, a route that answers with plivoTransferXml(), to transfer a call'\n )\n const api = plivoApi({\n authId: requireOption(\n authId,\n 'PlivoTransport needs authId and authToken to transfer a call'\n ),\n authToken: requireOption(\n authToken,\n 'PlivoTransport needs authId and authToken to transfer a call'\n ),\n })\n await api(\n 'Plivo transfer',\n 'POST',\n `/Call/${encodeURIComponent(callId)}/`,\n {\n legs: 'aleg',\n aleg_url: url,\n aleg_method: 'POST',\n }\n )\n this.handOff(options.to)\n }\n\n protected async hangUp() {\n const { authId, authToken } = this.options\n const callId = this.call.callId\n if (!authId || !authToken || !callId) return\n try {\n await plivoApi({ authId, authToken })(\n 'Plivo hang up',\n 'DELETE',\n `/Call/${encodeURIComponent(callId)}/`\n )\n } catch (error: any) {\n // The call ended already\n if (error?.status !== 404) throw error\n }\n }\n\n private sendJson(message: object) {\n if (this.isOpen) this.socket.send(JSON.stringify(message))\n }\n}\n\n/** Calls the API of a Plivo account */\nfunction plivoApi({ authId, authToken }: PlivoCredentials) {\n const authorization = `Basic ${Buffer.from(`${authId}:${authToken}`).toString('base64')}`\n return (what: string, method: string, path: string, body?: object) =>\n callApi(what, `${API}/Account/${encodeURIComponent(authId)}${path}`, {\n method,\n headers: {\n Authorization: authorization,\n ...(body ? { 'Content-Type': 'application/json' } : {}),\n },\n ...(body ? { body: JSON.stringify(body) } : {}),\n })\n}\n\n/** Reads `key=value` pairs, separated by `;` or `,` */\nfunction parseExtraHeaders(headers: unknown): Record<string, string> {\n const params: Record<string, string> = {}\n if (typeof headers !== 'string') return params\n for (const pair of headers.split(/[;,]/)) {\n const index = pair.indexOf('=')\n if (index <= 0) continue\n params[pair.substring(0, index).trim()] = pair.substring(index + 1).trim()\n }\n return params\n}\n\nexport interface PlivoStreamOptions {\n /** Address of the WebSocket that runs the call */\n url: string\n /**\n * Parameters of the call, which `waitForParams` hands back. Plivo only\n * takes letters and digits in them, 512 bytes at most.\n */\n parameters?: Record<string, string | number>\n}\n\n/**\n * Writes the XML that connects a call to a Micdrop server, to answer the\n * answer URL of a Plivo application with\n * @returns The XML document\n */\nexport function plivoStreamXml({ url, parameters = {} }: PlivoStreamOptions) {\n const extraHeaders = Object.entries(parameters)\n .map(([name, value]) => `${name}=${value}`)\n .join(';')\n const extra = extraHeaders ? ` extraHeaders=\"${escapeXml(extraHeaders)}\"` : ''\n 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>`\n}\n\n/**\n * Writes the XML that dials the destination of a transfer, for the route\n * `transferUrl` points to\n * @returns The XML document\n */\nexport function plivoTransferXml({ to, from, timeout }: TransferOptions) {\n const attributes = [\n from ? ` callerId=\"${escapeXml(from)}\"` : '',\n timeout ? ` timeout=\"${Math.round(timeout)}\"` : '',\n ].join('')\n const target = /^sips?:/i.test(to)\n ? `<User>${escapeXml(to)}</User>`\n : `<Number>${escapeXml(to.replace(/^\\+/, ''))}</Number>`\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?><Response><Dial${attributes}>${target}</Dial></Response>`\n}\n\nexport interface PlivoCallOptions extends PlivoCredentials {\n /** Number to call, in E.164 format */\n to: string\n /** Number of your account that calls */\n from: string\n /**\n * Address of the XML of the call once picked up, a route of your server\n * that answers with {@link plivoStreamXml}\n */\n answerUrl: string\n /** How long to let the phone ring, in seconds */\n timeout?: number\n /**\n * Detects whether a machine picked up, without holding the call: Plivo\n * posts the result to `machineDetectionUrl`. Hand the request to\n * `TelephonyCalls.plivoMachineDetection()`.\n */\n machineDetection?: boolean\n /** Where Plivo posts the result of the machine detection */\n machineDetectionUrl?: string\n}\n\n/**\n * Calls a number, and runs the XML of `answerUrl` once picked up\n * @returns The request UUID of the call, Plivo gives the call UUID to the\n * answer URL and to the stream\n * @see https://www.plivo.com/docs/voice/api/call/make-a-call\n */\nexport async function plivoCall(\n options: PlivoCallOptions\n): Promise<{ requestId: string }> {\n const { to, from, answerUrl, timeout, machineDetection } = options\n if (machineDetection && !options.machineDetectionUrl) {\n throw new Error(\n 'plivoCall: machineDetection needs machineDetectionUrl, where Plivo posts the result'\n )\n }\n const result = await plivoApi(options)(\n 'Plivo call creation',\n 'POST',\n '/Call/',\n {\n to: to.replace(/^\\+/, ''),\n from: from.replace(/^\\+/, ''),\n answer_url: answerUrl,\n answer_method: 'POST',\n ...(timeout ? { ring_timeout: Math.round(timeout) } : {}),\n ...(machineDetection\n ? {\n machine_detection: 'true',\n machine_detection_url: options.machineDetectionUrl,\n machine_detection_method: 'POST',\n }\n : {}),\n }\n )\n return { requestId: result?.request_uuid }\n}\n\n/**\n * Reads the result of the machine detection of Plivo, as it posts it to the\n * `machine_detection_url`\n * @param params - The fields of the request, parsed from its form body\n */\nexport function plivoMachineDetection(\n params: Record<string, any> | URLSearchParams\n): { callId: string; detection: MachineDetection } | undefined {\n const get = (key: string) =>\n params instanceof URLSearchParams ? params.get(key) : params[key]\n const callId = get('CallUUID')\n const machine = get('Machine')\n if (!callId || machine === undefined || machine === null) return undefined\n const raw = Object.fromEntries(\n params instanceof URLSearchParams ? params : Object.entries(params)\n )\n return {\n callId,\n detection: {\n answeredBy: String(machine) === 'true' ? 'machine' : 'human',\n greetingEnded: false,\n raw,\n },\n }\n}\n","import {\n createHash,\n createHmac,\n createPublicKey,\n timingSafeEqual,\n verify,\n} from 'node:crypto'\n\n/**\n * Checks of the signatures each provider puts on the requests it sends, so a\n * server only acts on webhooks that came from its provider. Each one takes\n * the request as the server received it: the address the provider called,\n * the raw body and the headers.\n */\n\n/** The fields of a form body, or of a query string */\nexport type SignedParams = Record<string, string | string[]> | URLSearchParams\n\nexport interface TwilioSignatureOptions {\n /** Auth token of the account */\n authToken: string\n /** The `X-Twilio-Signature` header */\n signature: string | null | undefined\n /**\n * The address Twilio called, query string included, as configured at\n * Twilio: `https://`, or `wss://` for the stream of a call\n */\n url: string\n /** The fields of the form body of a POST, none for a GET or a stream */\n params?: SignedParams\n}\n\n/**\n * Checks the `X-Twilio-Signature` of a request of Twilio: its voice webhooks,\n * status callbacks and the opening of a Media Stream.\n *\n * Tries the address with and without its default port, as the Twilio SDK\n * does, and with a trailing slash for a stream, as Twilio advises.\n *\n * @returns Whether Twilio signed the request\n * @see https://www.twilio.com/docs/usage/security#validating-requests\n */\nexport function validateTwilioSignature({\n authToken,\n signature,\n url,\n params,\n}: TwilioSignatureOptions): boolean {\n if (!authToken || !signature) return false\n const fields = entries(params)\n const data = [...new Set(fields.map(([key]) => key))]\n .sort()\n .map((key) =>\n [...new Set(fields.filter(([k]) => k === key).map(([, value]) => value))]\n .sort()\n .map((value) => key + value)\n .join('')\n )\n .join('')\n const urls = urlVariants(url)\n if (/^wss?:/i.test(url) && !new URL(url).pathname.endsWith('/')) {\n urls.push(...urlVariants(url.replace(/(\\?|$)/, '/$1')))\n }\n return urls.some((candidate) =>\n safeEqual(\n createHmac('sha1', authToken)\n .update(candidate + data)\n .digest('base64'),\n signature\n )\n )\n}\n\nexport interface TelnyxSignatureOptions {\n /** Public key of the account, in base64, as the portal shows it */\n publicKey: string\n /** The `telnyx-signature-ed25519` header */\n signature: string | null | undefined\n /** The `telnyx-timestamp` header */\n timestamp: string | null | undefined\n /** The raw body of the request, as received */\n body: string\n /** How old or early the timestamp may be, in seconds, 300 by default */\n tolerance?: number\n}\n\n// DER header of an Ed25519 public key, before its 32 bytes\nconst ED25519_SPKI_PREFIX = Buffer.from('302a300506032b6570032100', 'hex')\n\n/**\n * Checks the Ed25519 signature of a webhook of Telnyx, and that it is recent\n *\n * @returns Whether Telnyx signed the request in the last five minutes\n * @see https://developers.telnyx.com/docs/messaging/messages/receiving-webhooks\n */\nexport function validateTelnyxSignature({\n publicKey,\n signature,\n timestamp,\n body,\n tolerance = 300,\n}: TelnyxSignatureOptions): boolean {\n if (!publicKey || !signature || !timestamp) return false\n if (!/^\\d+$/.test(timestamp)) return false\n if (Math.abs(Date.now() / 1000 - Number(timestamp)) > tolerance) return false\n const raw = Buffer.from(publicKey, 'base64')\n if (raw.length !== 32) {\n throw new Error(\n 'validateTelnyxSignature: the public key must be the 32 bytes in base64 the Telnyx portal shows'\n )\n }\n const sig = Buffer.from(signature, 'base64')\n if (sig.length !== 64) return false\n try {\n const key = createPublicKey({\n key: Buffer.concat([ED25519_SPKI_PREFIX, raw]),\n format: 'der',\n type: 'spki',\n })\n return verify(null, Buffer.from(`${timestamp}|${body}`), key, sig)\n } catch {\n return false\n }\n}\n\nexport interface VonageSignatureOptions {\n /** Signature secret of the account, in the settings of the dashboard */\n signatureSecret: string\n /** The `Authorization` header, `Bearer <JWT>` */\n authorization: string | null | undefined\n /**\n * The raw body of the request, to check against the hash the token carries.\n * Left out or empty, only the token is checked.\n */\n body?: string\n /** How old the token may be, in seconds, 300 by default */\n tolerance?: number\n}\n\n/**\n * Checks the signed JWT Vonage puts on the webhooks of a Voice application:\n * HS256 with the signature secret of the account, and the SHA-256 of the\n * body in its `payload_hash` claim.\n *\n * Signed webhooks are on by default for the applications created since\n * Vonage introduced them, and turn on in the Voice settings of the others.\n *\n * @returns Whether Vonage signed the request\n * @see https://developer.vonage.com/en/getting-started/concepts/webhooks#decoding-signed-webhooks\n */\nexport function validateVonageSignature({\n signatureSecret,\n authorization,\n body,\n tolerance = 300,\n}: VonageSignatureOptions): boolean {\n if (!signatureSecret || !authorization) return false\n const token = authorization.replace(/^Bearer\\s+/i, '')\n const parts = token.split('.')\n if (parts.length !== 3) return false\n const [header, payload, signature] = parts\n const decode = (part: string) => {\n try {\n return JSON.parse(Buffer.from(part, 'base64url').toString())\n } catch {\n return undefined\n }\n }\n if (decode(header)?.alg !== 'HS256') return false\n const expected = createHmac('sha256', signatureSecret)\n .update(`${header}.${payload}`)\n .digest('base64url')\n if (!safeEqual(expected, signature)) return false\n const claims = decode(payload)\n if (!claims) return false\n const now = Date.now() / 1000\n if (typeof claims.exp === 'number' && claims.exp < now) return false\n if (typeof claims.iat === 'number' && now - claims.iat > tolerance) {\n return false\n }\n if (body && claims.payload_hash) {\n const hash = createHash('sha256').update(body).digest('hex')\n if (!safeEqual(hash, String(claims.payload_hash).toLowerCase())) {\n return false\n }\n }\n return true\n}\n\nexport interface PlivoSignatureOptions {\n /** Auth token of the account, or of the subaccount owning the number */\n authToken: string\n /** The `X-Plivo-Signature-V3` header, one signature per active token */\n signature: string | null | undefined\n /** The `X-Plivo-Signature-V3-Nonce` header */\n nonce: string | null | undefined\n /** The address Plivo called, query string included */\n url: string\n /** Method of the request */\n method: string\n /** The fields of the form body of a POST */\n params?: SignedParams\n}\n\n/**\n * Checks the V3 signature of a request of Plivo: its answer, hangup and\n * machine detection callbacks\n *\n * @returns Whether Plivo signed the request\n * @see https://www.plivo.com/docs/voice/concepts/signature-validation\n */\nexport function validatePlivoSignature({\n authToken,\n signature,\n nonce,\n url,\n method,\n params,\n}: PlivoSignatureOptions): boolean {\n if (!authToken || !signature || !nonce) return false\n const parsed = new URL(url)\n const base = `${parsed.protocol}//${parsed.host}${parsed.pathname}`\n const post = method.toUpperCase() === 'POST'\n // The fields of a GET are signed with those of its query string\n const query = sortedGroups([\n ...entries(parsed.searchParams),\n ...(post ? [] : entries(params)),\n ])\n .flatMap(([key, values]) => values.map((value) => `${key}=${value}`))\n .join('&')\n const fields = post ? entries(params) : []\n let data = query ? `${base}?${query}` : base\n if (fields.length) {\n data = `${base}?${query}${query ? '.' : ''}`\n data += sortedGroups(fields)\n .map(([key, values]) => values.map((value) => key + value).join(''))\n .join('')\n }\n const expected = createHmac('sha256', authToken)\n .update(`${data}.${nonce}`)\n .digest('base64')\n return signature\n .split(',')\n .some((candidate) => safeEqual(expected, candidate))\n}\n\n/** The pairs of fields, values as strings */\nfunction entries(params: SignedParams | undefined): [string, string][] {\n if (!params) return []\n if (params instanceof URLSearchParams) return [...params.entries()]\n return Object.entries(params).flatMap(([key, value]) =>\n Array.isArray(value)\n ? value.map((item): [string, string] => [key, String(item)])\n : [[key, String(value ?? '')]]\n )\n}\n\n/** The fields grouped by name, names and values sorted */\nfunction sortedGroups(fields: [string, string][]): [string, string[]][] {\n const groups = new Map<string, string[]>()\n for (const [key, value] of fields) {\n groups.set(key, [...(groups.get(key) ?? []), value])\n }\n return [...groups.keys()].sort().map((key) => [key, groups.get(key)!.sort()])\n}\n\n/** The address as given, without its default port and with it */\nfunction urlVariants(url: string): string[] {\n const parsed = new URL(url)\n const secure = /^(https|wss):$/.test(parsed.protocol)\n const port = parsed.port || (secure ? '443' : '80')\n const authority = (withPort: boolean) =>\n `${parsed.protocol}//${parsed.hostname}${withPort ? `:${port}` : ''}`\n const rest = url.replace(/^[a-z][a-z0-9+.-]*:\\/\\/[^/?#]*/i, '')\n return [...new Set([url, authority(false) + rest, authority(true) + rest])]\n}\n\n/** Compares two strings in constant time */\nfunction safeEqual(a: string, b: string): boolean {\n const left = Buffer.from(a)\n const right = Buffer.from(b)\n return left.length === right.length && timingSafeEqual(left, right)\n}\n","import { alawToPcm16, mulawToPcm16, pcm16ToAlaw, pcm16ToMulaw } from './g711'\nimport { callApi, requireOption } from './http'\nimport {\n MachineDetection,\n parseJson,\n TelephonyTransport,\n TransferOptions,\n WarmTransferFailure,\n WarmTransferOptions,\n WarmTransferResult,\n} from './TelephonyTransport'\n\nexport type TelnyxCodec = 'PCMU' | 'PCMA'\n\nexport interface TelnyxTransportOptions {\n /**\n * Codec of the stream, both ways, `PCMU` by default. It has to match the\n * `stream_codec` and `stream_bidirectional_codec` of the call.\n */\n codec?: TelnyxCodec\n /**\n * API key, to hang up when the assistant ends the call, transfer it and\n * send keys. Telnyx keeps a call going when its stream closes, so without\n * it the call stays on the line until the caller hangs up.\n */\n apiKey?: string\n /**\n * Call Control application that dials the person of a warm transfer. Its\n * webhooks have to reach `TelephonyCalls.telnyxWebhook()`.\n */\n connectionId?: string\n /**\n * Voice that speaks the briefing of a warm transfer, as Telnyx names it,\n * `AWS.Polly.Joanna-Neural` by default\n */\n briefingVoice?: string\n /** Language of the briefing, such as `en-US` */\n briefingLanguage?: string\n}\n\nconst API = 'https://api.telnyx.com/v2'\nconst DEFAULT_VOICE = 'AWS.Polly.Joanna-Neural'\nconst DEFAULT_RING_TIMEOUT = 30 // s\n// Keys of the client state that belong to this package, kept out of the params\nconst OUTBOUND_KEY = 'micdropOutbound'\nconst TRANSFER_KEY = 'micdropTransferOf'\n\n/** A Call Control event, as Telnyx posts it to the webhook of an application */\nexport interface TelnyxEvent {\n event_type: string\n payload: {\n call_control_id: string\n client_state?: string\n result?: string\n hangup_cause?: string\n [key: string]: any\n }\n}\n\n/** The warm transfer under way, waiting for the events of the person called */\ninterface PendingTransfer {\n personId: string\n briefing?: string\n resolve: (result: WarmTransferResult) => void\n reject: (error: Error) => void\n}\n\n/**\n * A call from Telnyx, streamed with bidirectional RTP media streaming.\n *\n * The call is answered with Call Control, with the stream options that\n * {@link telnyxStreamOptions} writes, and Telnyx opens the WebSocket. The\n * caller comes in G.711 at 8 kHz and the assistant goes back the same way.\n * The parameters of the call travel in its `client_state`.\n *\n * @see https://developers.telnyx.com/docs/voice/programmable-voice/media-streaming\n */\nexport class TelnyxTransport extends TelephonyTransport {\n private codec: TelnyxCodec\n private pendingTransfer?: PendingTransfer\n // Events of a transfer that came before Telnyx answered the dial\n private earlyTransferEvents: TelnyxEvent[] = []\n\n /**\n * @param socket - The socket Telnyx opened\n * @param options - Codec of the stream, and what Call Control needs\n */\n constructor(\n socket: ConstructorParameters<typeof TelephonyTransport>[0],\n private options: TelnyxTransportOptions = {}\n ) {\n super(socket)\n this.codec = options.codec ?? 'PCMU'\n }\n\n protected get lineRate() {\n return 8000\n }\n\n protected onProviderMessage(data: Buffer) {\n const message = parseJson(data)\n switch (message?.event) {\n case 'start': {\n const start = message.start ?? {}\n const format = start.media_format ?? {}\n const { encoding } = format\n if (encoding === 'PCMU' || encoding === 'PCMA') {\n this.codec = encoding\n } else if (encoding) {\n this.fail(\n `Telnyx streams ${encoding}, TelnyxTransport reads PCMU or PCMA: set stream_codec and stream_bidirectional_codec, as telnyxStreamOptions() does`\n )\n return\n }\n if (format.sample_rate && Number(format.sample_rate) !== 8000) {\n this.fail(\n `Telnyx streams at ${format.sample_rate} Hz, TelnyxTransport reads 8000 Hz: leave stream_bidirectional_sampling_rate at 8000`\n )\n return\n }\n const { params, outbound } = readParams(start)\n this.startStream(\n {\n callId: start.call_control_id,\n streamId: message.stream_id,\n from: start.from,\n to: start.to,\n ...(outbound ? { direction: 'outbound' as const } : {}),\n },\n params\n )\n break\n }\n case 'media': {\n if (message.media?.track && message.media.track !== 'inbound') return\n const bytes = Buffer.from(message.media?.payload ?? '', 'base64')\n this.receiveAudio(\n this.codec === 'PCMA' ? alawToPcm16(bytes) : mulawToPcm16(bytes)\n )\n break\n }\n case 'mark':\n this.markPlayed(message.mark?.name)\n break\n case 'dtmf':\n this.receiveDtmf(message.dtmf?.digit)\n break\n case 'error':\n this.logger.error('Telnyx error', { payload: message.payload })\n break\n }\n }\n\n protected writeAudio(pcm: Buffer) {\n const bytes = this.codec === 'PCMA' ? pcm16ToAlaw(pcm) : pcm16ToMulaw(pcm)\n this.sendJson({\n event: 'media',\n media: { payload: bytes.toString('base64') },\n })\n }\n\n protected writeClear() {\n this.sendJson({ event: 'clear' })\n }\n\n protected writeMark(name: string) {\n this.sendJson({ event: 'mark', mark: { name } })\n }\n\n protected async hangUp() {\n const { apiKey } = this.options\n const callId = this.call.callId\n if (!apiKey || !callId) return\n await this.action('hang up', callId, 'hangup', {})\n }\n\n /** Sends the keys with Call Control, or in the audio without an API key */\n async sendDtmf(digits: string) {\n if (!this.options.apiKey) return super.sendDtmf(digits)\n await this.action('send DTMF', this.requireCallId(), 'send_dtmf', {\n digits,\n })\n }\n\n /**\n * Transfers the call with Call Control, then stops the stream. `from`\n * defaults to the number the call was made to.\n */\n async transfer({ to, from, timeout }: TransferOptions) {\n const callId = this.requireCallId()\n await this.action('transfer the call', callId, 'transfer', {\n to,\n ...(from ? { from } : {}),\n ...(timeout ? { timeout_secs: Math.round(timeout) } : {}),\n })\n await this.stopStreaming(callId)\n this.handOff(to)\n }\n\n /**\n * Dials the person, speaks the briefing to them once they pick up, then\n * bridges the caller to them. Telnyx reports each step to the webhook of\n * the application only, so its events have to reach\n * `TelephonyCalls.telnyxWebhook()`.\n *\n * `from` defaults to the number of your account on the call.\n */\n async warmTransfer({\n to,\n from,\n timeout = DEFAULT_RING_TIMEOUT,\n briefing,\n }: WarmTransferOptions): Promise<WarmTransferResult> {\n const callId = this.requireCallId()\n const connectionId = requireOption(\n this.options.connectionId,\n 'TelnyxTransport needs connectionId, the Call Control application that dials, to make a warm transfer'\n )\n const callerId = requireOption(\n from ?? this.ownNumber,\n 'TelnyxTransport: set `from` to make a warm transfer'\n )\n if (this.pendingTransfer) {\n throw new Error('TelnyxTransport: a warm transfer is already under way')\n }\n this.earlyTransferEvents = []\n const response = await callApi(\n 'Telnyx dial',\n `${API}/calls`,\n this.request({\n connection_id: connectionId,\n to,\n from: callerId,\n timeout_secs: Math.round(timeout),\n link_to: callId,\n client_state: encodeState({ [TRANSFER_KEY]: callId }),\n })\n )\n const personId: string = response?.data?.call_control_id\n if (!personId) throw new Error('Telnyx dial returned no call_control_id')\n\n // Telnyx reports the answer within the timeout, or the end of the call\n const result = await new Promise<WarmTransferResult>((resolve, reject) => {\n const timer = setTimeout(\n () => {\n this.pendingTransfer = undefined\n this.action('hang up', personId, 'hangup', {}).catch(() => {})\n reject(\n new Error(\n 'TelnyxTransport: no event of the transfer reached the transport. Hand the webhooks of the application to TelephonyCalls.telnyxWebhook()'\n )\n )\n },\n (timeout + 60) * 1000\n )\n this.pendingTransfer = {\n personId,\n briefing,\n resolve: (result) => {\n clearTimeout(timer)\n this.pendingTransfer = undefined\n resolve(result)\n },\n reject: (error) => {\n clearTimeout(timer)\n this.pendingTransfer = undefined\n reject(error)\n },\n }\n const early = this.earlyTransferEvents\n this.earlyTransferEvents = []\n for (const event of early) this.receiveTelnyxEvent(event)\n })\n if (result.transferred) this.handOff(to)\n return result\n }\n\n /**\n * Takes a Call Control event about the person of a warm transfer, which\n * `TelephonyCalls.telnyxWebhook()` routes here\n */\n receiveTelnyxEvent(event: TelnyxEvent) {\n const transfer = this.pendingTransfer\n if (!transfer) {\n // The webhook can beat the answer of the dial\n this.earlyTransferEvents.push(event)\n return\n }\n if (event.payload?.call_control_id !== transfer.personId) return\n const step = async () => {\n switch (event.event_type) {\n case 'call.answered':\n if (transfer.briefing) {\n await this.action(\n 'speak the briefing',\n transfer.personId,\n 'speak',\n {\n payload: transfer.briefing,\n voice: this.options.briefingVoice ?? DEFAULT_VOICE,\n ...(this.options.briefingLanguage\n ? { language: this.options.briefingLanguage }\n : {}),\n }\n )\n } else {\n await this.bridgeTo(transfer)\n }\n break\n case 'call.speak.ended':\n await this.bridgeTo(transfer)\n break\n case 'call.hangup':\n transfer.resolve({\n transferred: false,\n reason: hangupReason(event.payload.hangup_cause),\n })\n break\n }\n }\n step().catch((error) => transfer.reject(error))\n }\n\n private async bridgeTo(transfer: PendingTransfer) {\n const callId = this.requireCallId()\n await this.stopStreaming(callId)\n await this.action('bridge the transfer', callId, 'bridge', {\n call_control_id: transfer.personId,\n })\n transfer.resolve({ transferred: true })\n }\n\n private async stopStreaming(callId: string) {\n await this.action('stop the stream', callId, 'streaming_stop', {\n ...(this.call.streamId ? { stream_id: this.call.streamId } : {}),\n }).catch((error) =>\n this.logger.warn('Stopping the stream failed', { error })\n )\n }\n\n private requireCallId(): string {\n return requireOption(\n this.call.callId,\n 'TelnyxTransport: the stream has not started, the call is unknown'\n )\n }\n\n private action(what: string, callId: string, name: string, body: object) {\n return callApi(\n `Telnyx ${what}`,\n `${API}/calls/${encodeURIComponent(callId)}/actions/${name}`,\n this.request(body, what)\n )\n }\n\n private request(body: object, what = 'act on the call'): RequestInit {\n const apiKey = requireOption(\n this.options.apiKey,\n `TelnyxTransport needs apiKey to ${what}`\n )\n return {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n }\n }\n\n private sendJson(message: object) {\n if (this.isOpen) this.socket.send(JSON.stringify(message))\n }\n}\n\nfunction hangupReason(cause?: string): WarmTransferFailure {\n switch (cause) {\n case 'user_busy':\n case 'busy':\n case 'call_rejected':\n return 'busy'\n case 'timeout':\n case 'no_answer':\n case 'originator_cancel':\n return 'no-answer'\n case 'normal_clearing':\n return 'hung-up'\n default:\n return 'failed'\n }\n}\n\nfunction encodeState(state: object): string {\n return Buffer.from(JSON.stringify(state)).toString('base64')\n}\n\n/** Reads a client state this package or the application wrote */\nexport function decodeTelnyxState(state: unknown): Record<string, any> {\n if (typeof state !== 'string') return {}\n try {\n const value = JSON.parse(Buffer.from(state, 'base64').toString())\n return value && typeof value === 'object' ? value : {}\n } catch {\n // A client state the application wrote for itself\n return {}\n }\n}\n\n/** The parameters of the call, from its client state or custom parameters */\nfunction readParams(start: any): { params: any; outbound: boolean } {\n const params: Record<string, any> = {}\n const custom = start.custom_parameters\n if (Array.isArray(custom)) {\n for (const { name, value } of custom) params[name] = value\n } else if (custom && typeof custom === 'object') {\n Object.assign(params, custom)\n }\n Object.assign(params, decodeTelnyxState(start.client_state))\n const outbound = !!params[OUTBOUND_KEY]\n delete params[OUTBOUND_KEY]\n return { params, outbound }\n}\n\nexport interface TelnyxStreamOptions {\n /** Address of the WebSocket that runs the call */\n url: string\n /** Parameters of the call, which `waitForParams` hands back */\n parameters?: Record<string, unknown>\n /** Codec of the stream, both ways, `PCMU` by default */\n codec?: TelnyxCodec\n}\n\n/**\n * Writes the stream options of a Call Control `answer`, `dial` or\n * `streaming_start` command, to merge into its body\n * @returns The fields to send to Telnyx\n */\nexport function telnyxStreamOptions({\n url,\n parameters,\n codec = 'PCMU',\n}: TelnyxStreamOptions) {\n return {\n stream_url: url,\n stream_track: 'inbound_track',\n stream_codec: codec,\n stream_bidirectional_mode: 'rtp',\n stream_bidirectional_codec: codec,\n ...(parameters ? { client_state: encodeState(parameters) } : {}),\n }\n}\n\nexport interface TelnyxCallOptions extends TelnyxStreamOptions {\n /** API key of the account */\n apiKey: string\n /** Call Control application that places the call */\n connectionId: string\n /** Number to call, in E.164 format, or a SIP URI */\n to: string\n /** Number of your account that calls */\n from: string\n /** How long to let the phone ring, in seconds, 30 by default */\n timeout?: number\n /**\n * Detects whether a person or a machine picked up, `greeting_end` to also\n * hear when the greeting of a machine ends. Telnyx posts the result to the\n * webhook of the application: hand it to `TelephonyCalls.telnyxWebhook()`.\n */\n machineDetection?: boolean | 'detect' | 'greeting_end' | 'premium'\n}\n\n/**\n * Calls a number, and streams the call to a Micdrop server once picked up\n * @returns The Call Control ID of the call, which the transport gets as\n * `call.callId`\n * @see https://developers.telnyx.com/api-reference/call-commands/dial\n */\nexport async function telnyxCall(\n options: TelnyxCallOptions\n): Promise<{ callId: string }> {\n const { apiKey, connectionId, to, from, timeout, machineDetection } = options\n const detection =\n machineDetection === true ? 'greeting_end' : machineDetection || undefined\n const response = await callApi('Telnyx dial', `${API}/calls`, {\n method: 'POST',\n headers: {\n Authorization: `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n connection_id: connectionId,\n to,\n from,\n ...(timeout ? { timeout_secs: Math.round(timeout) } : {}),\n ...(detection ? { answering_machine_detection: detection } : {}),\n ...telnyxStreamOptions({\n ...options,\n parameters: { ...options.parameters, [OUTBOUND_KEY]: true },\n }),\n }),\n })\n const callId = response?.data?.call_control_id\n if (!callId) throw new Error('Telnyx dial returned no call_control_id')\n return { callId }\n}\n\n/**\n * Reads a result of the machine detection of Telnyx from a webhook event\n * @param body - The JSON body of the webhook\n */\nexport function telnyxMachineDetection(\n body: any\n): { callId: string; detection: MachineDetection } | undefined {\n const data = body?.data ?? body\n const type: string | undefined = data?.event_type\n const payload = data?.payload\n if (!type || !payload?.call_control_id) return undefined\n const result: string | undefined = payload.result\n const callId: string = payload.call_control_id\n const detection = (\n answeredBy: MachineDetection['answeredBy'],\n greetingEnded = false\n ) => ({ callId, detection: { answeredBy, greetingEnded, raw: data } })\n\n switch (type) {\n case 'call.machine.detection.ended':\n if (result === 'human') return detection('human')\n if (result === 'machine') return detection('machine')\n return detection('unknown')\n case 'call.machine.premium.detection.ended':\n if (result === 'human_residence' || result === 'human_business') {\n return detection('human')\n }\n if (result === 'machine') return detection('machine')\n if (result === 'fax_detected') return detection('fax')\n return detection('unknown')\n case 'call.machine.greeting.ended':\n case 'call.machine.premium.greeting.ended':\n return detection('unknown', true)\n default:\n return undefined\n }\n}\n\n/**\n * Reads the call a webhook event belongs to: the call itself, or the call a\n * warm transfer was dialing the person for\n * @param body - The JSON body of the webhook\n */\nexport function telnyxEventTarget(\n body: any\n): { callId: string; event: TelnyxEvent; transfer: boolean } | undefined {\n const event = body?.data ?? body\n const callId = event?.payload?.call_control_id\n if (!event?.event_type || !callId) return undefined\n const transferOf = decodeTelnyxState(event.payload.client_state)[TRANSFER_KEY]\n return transferOf\n ? { callId: transferOf, event, transfer: true }\n : { callId, event, transfer: false }\n}\n","import { mulawToPcm16, pcm16ToMulaw } from './g711'\nimport { callApi, formBody, requireOption, sleep } from './http'\nimport {\n MachineDetection,\n parseJson,\n TelephonyTransport,\n TransferOptions,\n WarmTransferOptions,\n WarmTransferResult,\n} from './TelephonyTransport'\nimport { escapeXml } from './xml'\n\n/** Credentials of a Twilio account, to act on calls through its API */\nexport interface TwilioCredentials {\n /** SID of the account, `AC...` */\n accountSid: string\n /** Auth token of the account, or the secret of `apiKey` */\n authToken: string\n /** SID of an API key, `SK...`, to authenticate with it instead */\n apiKey?: string\n}\n\nexport interface TwilioTransportOptions extends Partial<TwilioCredentials> {\n /**\n * Plays to the caller while the person reached in a warm transfer hears\n * the briefing: the address of an audio file or TwiML, as the `waitUrl` of\n * a conference. Twilio plays its own hold music by default, `''` keeps the\n * line silent.\n */\n holdMusicUrl?: string\n /**\n * Said to the caller when the person reached in a warm transfer hangs up\n * before joining, as TwiML. An apology and a hang up by default.\n */\n transferFallbackTwiml?: string\n}\n\nconst API = 'https://api.twilio.com/2010-04-01'\nconst POLL_INTERVAL = 1000 // ms\nconst DEFAULT_RING_TIMEOUT = 30 // s\nconst DEFAULT_FALLBACK_TWIML =\n '<Response><Say>Sorry, nobody could take your call. Please call back later.</Say><Hangup/></Response>'\n\n/**\n * A call from Twilio, over a bidirectional Media Stream.\n *\n * Twilio opens the WebSocket when the call reaches the `<Connect><Stream>`\n * of its TwiML, which {@link twilioStreamTwiml} writes. The caller comes in\n * μ-law at 8 kHz, and the assistant goes back the same way. Closing the\n * socket ends the `<Connect>`, and the call with it when nothing follows.\n *\n * Transfers go through the API of Twilio, and need the credentials of the\n * account. Keys go in the audio, as the stream carries no other way to send\n * them.\n *\n * SignalWire speaks the same protocol, with its default `PCMU` codec.\n *\n * @see https://www.twilio.com/docs/voice/media-streams/websocket-messages\n */\nexport class TwilioTransport extends TelephonyTransport {\n // Twilio takes audio of any size, and buffers it\n protected frameDuration = 0\n\n /**\n * @param socket - The socket Twilio opened\n * @param options - Credentials of the account, for the transfers\n */\n constructor(\n socket: ConstructorParameters<typeof TelephonyTransport>[0],\n private options: TwilioTransportOptions = {}\n ) {\n super(socket)\n }\n\n protected get lineRate() {\n return 8000\n }\n\n protected onProviderMessage(data: Buffer) {\n const message = parseJson(data)\n switch (message?.event) {\n case 'start': {\n const start = message.start ?? {}\n const format = start.mediaFormat\n if (\n format &&\n (format.encoding !== 'audio/x-mulaw' || format.sampleRate !== 8000)\n ) {\n this.fail(\n `Twilio streams ${format.encoding} at ${format.sampleRate} Hz, TwilioTransport reads audio/x-mulaw at 8000 Hz`\n )\n return\n }\n this.startStream(\n {\n callId: start.callSid,\n streamId: start.streamSid ?? message.streamSid,\n },\n start.customParameters\n )\n break\n }\n case 'media':\n if (message.media?.track && message.media.track !== 'inbound') return\n this.receiveAudio(\n mulawToPcm16(Buffer.from(message.media?.payload ?? '', 'base64'))\n )\n break\n case 'mark':\n this.markPlayed(message.mark?.name)\n break\n case 'dtmf':\n this.receiveDtmf(message.dtmf?.digit)\n break\n case 'stop':\n this.logger.debug('Stream stopped')\n break\n }\n }\n\n protected writeAudio(pcm: Buffer) {\n this.sendJson({\n event: 'media',\n streamSid: this.call.streamId,\n media: { payload: pcm16ToMulaw(pcm).toString('base64') },\n })\n }\n\n protected writeClear() {\n this.sendJson({ event: 'clear', streamSid: this.call.streamId })\n }\n\n protected writeMark(name: string) {\n this.sendJson({\n event: 'mark',\n streamSid: this.call.streamId,\n mark: { name },\n })\n }\n\n /**\n * Sends the call to another number with a `<Dial>`, which ends the stream.\n * The caller ID stays that of the caller, unless `from` says otherwise.\n */\n async transfer({ to, from, timeout }: TransferOptions) {\n const api = this.api('transfer the call')\n const callId = this.requireCallId()\n const attributes = [\n from ? ` callerId=\"${escapeXml(from)}\"` : '',\n timeout ? ` timeout=\"${Math.round(timeout)}\"` : '',\n ].join('')\n await api.updateCall(\n callId,\n `<Response><Dial${attributes}>${dialTarget(to)}</Dial></Response>`\n )\n this.handOff(to)\n }\n\n /**\n * Calls the person with the briefing and a conference, then moves the\n * caller into that conference once they picked up. The caller hears the\n * hold music while the briefing plays, and the person joins right after.\n *\n * `from` defaults to the number of your account on the call.\n */\n async warmTransfer({\n to,\n from,\n timeout = DEFAULT_RING_TIMEOUT,\n briefing,\n }: WarmTransferOptions): Promise<WarmTransferResult> {\n const api = this.api('make a warm transfer')\n const callId = this.requireCallId()\n const room = `micdrop-${callId}`\n const callerId = from ?? ownNumber(await api.getCall(callId))\n if (!callerId) {\n throw new Error('TwilioTransport: set `from` to make a warm transfer')\n }\n\n const say = briefing ? `<Say>${escapeXml(briefing)}</Say>` : ''\n const person = await api.createCall({\n To: to,\n From: callerId,\n Timeout: Math.round(timeout),\n Twiml: `<Response>${say}<Dial><Conference startConferenceOnEnter=\"true\" endConferenceOnExit=\"true\" beep=\"false\">${room}</Conference></Dial></Response>`,\n })\n\n // Wait for the person to pick up, or for the call to fail\n const deadline = Date.now() + (timeout + 15) * 1000\n let status: string = person.status\n while (Date.now() < deadline && !this.isTransferOver(status)) {\n await sleep(POLL_INTERVAL)\n status = (await api.getCall(person.sid)).status\n }\n if (status !== 'in-progress') {\n if (!this.isTransferOver(status)) {\n await api.endCall(person.sid).catch(() => {})\n }\n return { transferred: false, reason: transferFailure(status) }\n }\n\n const { holdMusicUrl } = this.options\n const waitUrl =\n holdMusicUrl === undefined ? '' : ` waitUrl=\"${escapeXml(holdMusicUrl)}\"`\n await api.updateCall(\n callId,\n `<Response><Dial><Conference startConferenceOnEnter=\"false\" endConferenceOnExit=\"true\" beep=\"false\"${waitUrl}>${room}</Conference></Dial></Response>`\n )\n this.handOff(to)\n this.rescueIfAbandoned(api, callId, person.sid, room)\n return { transferred: true }\n }\n\n /**\n * Sends the caller the fallback when the person hangs up during the\n * briefing, before the conference started, so the caller does not wait for\n * nobody\n */\n private async rescueIfAbandoned(\n api: TwilioApi,\n callId: string,\n personId: string,\n room: string\n ) {\n const deadline = Date.now() + 5 * 60 * 1000\n try {\n while (Date.now() < deadline) {\n await sleep(POLL_INTERVAL * 2)\n if (await api.isConferenceStarted(room)) return\n const { status } = await api.getCall(personId)\n if (status === 'in-progress') continue\n if (await api.isConferenceStarted(room)) return\n this.logger.info(\n 'The person left before joining, the caller hears the fallback'\n )\n await api.updateCall(\n callId,\n this.options.transferFallbackTwiml ?? DEFAULT_FALLBACK_TWIML\n )\n return\n }\n } catch (error) {\n this.logger.error('Watching the transfer failed', { error })\n }\n }\n\n private isTransferOver(status: string) {\n return status !== 'queued' && status !== 'ringing' && status !== 'initiated'\n }\n\n private requireCallId(): string {\n return requireOption(\n this.call.callId,\n 'TwilioTransport: the stream has not started, the call is unknown'\n )\n }\n\n private api(action: string): TwilioApi {\n const { accountSid, authToken, apiKey } = this.options\n return new TwilioApi({\n accountSid: requireOption(\n accountSid,\n `TwilioTransport needs accountSid and authToken to ${action}`\n ),\n authToken: requireOption(\n authToken,\n `TwilioTransport needs accountSid and authToken to ${action}`\n ),\n apiKey,\n })\n }\n\n private sendJson(message: object) {\n if (this.isOpen) this.socket.send(JSON.stringify(message))\n }\n}\n\n/** The calls of a Twilio account, through its REST API */\nclass TwilioApi {\n private readonly base: string\n private readonly authorization: string\n\n constructor({ accountSid, authToken, apiKey }: TwilioCredentials) {\n this.base = `${API}/Accounts/${encodeURIComponent(accountSid)}`\n this.authorization = `Basic ${Buffer.from(\n `${apiKey ?? accountSid}:${authToken}`\n ).toString('base64')}`\n }\n\n createCall(fields: Record<string, unknown>): Promise<any> {\n return this.post('Twilio call creation', '/Calls.json', fields)\n }\n\n getCall(sid: string): Promise<any> {\n return callApi(\n 'Twilio call fetch',\n `${this.base}/Calls/${encodeURIComponent(sid)}.json`,\n { headers: { Authorization: this.authorization } }\n )\n }\n\n updateCall(sid: string, twiml: string): Promise<any> {\n return this.post(\n 'Twilio call update',\n `/Calls/${encodeURIComponent(sid)}.json`,\n { Twiml: twiml }\n )\n }\n\n endCall(sid: string): Promise<any> {\n return this.post(\n 'Twilio hang up',\n `/Calls/${encodeURIComponent(sid)}.json`,\n { Status: 'completed' }\n )\n }\n\n async isConferenceStarted(name: string): Promise<boolean> {\n const query = new URLSearchParams({\n FriendlyName: name,\n Status: 'in-progress',\n })\n const result = await callApi(\n 'Twilio conference fetch',\n `${this.base}/Conferences.json?${query}`,\n { headers: { Authorization: this.authorization } }\n )\n return (result?.conferences ?? []).length > 0\n }\n\n private post(what: string, path: string, fields: Record<string, unknown>) {\n return callApi(what, `${this.base}${path}`, {\n method: 'POST',\n headers: {\n Authorization: this.authorization,\n 'Content-Type': 'application/x-www-form-urlencoded',\n },\n body: formBody(fields),\n })\n }\n}\n\n/** The number of the account on a call: the one called, or the one calling */\nfunction ownNumber(call: any): string | undefined {\n return call?.direction === 'inbound' ? call?.to : call?.from\n}\n\nfunction dialTarget(to: string): string {\n return /^sips?:/i.test(to)\n ? `<Sip>${escapeXml(to)}</Sip>`\n : `<Number>${escapeXml(to)}</Number>`\n}\n\nfunction transferFailure(status: string) {\n switch (status) {\n case 'busy':\n return 'busy'\n case 'no-answer':\n case 'queued':\n case 'ringing':\n case 'initiated':\n return 'no-answer'\n case 'completed':\n return 'hung-up'\n default:\n return 'failed'\n }\n}\n\nexport interface TwilioStreamOptions {\n /** Address of the WebSocket that runs the call, `wss://` only */\n url: string\n /**\n * Parameters of the call, which `waitForParams` hands back. Twilio takes no\n * query string in the address, so this is how a call carries its context.\n */\n parameters?: Record<string, string | number | boolean>\n /** TwiML to say before the stream, for instance a recording notice */\n before?: string\n}\n\n/**\n * Writes the TwiML that connects a call to a Micdrop server, to answer the\n * voice webhook of a Twilio number with\n * @returns The TwiML document\n */\nexport function twilioStreamTwiml({\n url,\n parameters = {},\n before = '',\n}: TwilioStreamOptions): string {\n const params = Object.entries(parameters)\n .map(\n ([name, value]) =>\n `<Parameter name=\"${escapeXml(name)}\" value=\"${escapeXml(String(value))}\" />`\n )\n .join('')\n return `<?xml version=\"1.0\" encoding=\"UTF-8\"?><Response>${before}<Connect><Stream url=\"${escapeXml(url)}\">${params}</Stream></Connect></Response>`\n}\n\nexport interface TwilioCallOptions\n extends TwilioCredentials, TwilioStreamOptions {\n /** Number to call, in E.164 format, or a SIP URI */\n to: string\n /** Number of your account that calls */\n from: string\n /** How long to let the phone ring, in seconds, 30 by default */\n timeout?: number\n /**\n * Detects whether a person or a machine picked up, without holding the\n * call: the stream starts at once, and Twilio posts the result to\n * `machineDetectionUrl` when it has it, at the end of the greeting of a\n * machine. Hand the request to `TelephonyCalls.twilioMachineDetection()`.\n */\n machineDetection?: boolean\n /** Where Twilio posts the result of the machine detection */\n machineDetectionUrl?: string\n /** Where Twilio posts the status of the call as it goes */\n statusCallback?: string\n}\n\n/**\n * Calls a number, and streams the call to a Micdrop server once picked up\n * @returns The SID of the call, which the transport gets as `call.callId`\n * @see https://www.twilio.com/docs/voice/api/call-resource#create-a-call-resource\n */\nexport async function twilioCall(\n options: TwilioCallOptions\n): Promise<{ callId: string }> {\n const { to, from, timeout, machineDetection, machineDetectionUrl } = options\n if (machineDetection && !machineDetectionUrl) {\n throw new Error(\n 'twilioCall: machineDetection needs machineDetectionUrl, where Twilio posts the result'\n )\n }\n const api = new TwilioApi(options)\n const call = await api.createCall({\n To: to,\n From: from,\n Timeout: timeout === undefined ? undefined : Math.round(timeout),\n Twiml: twilioStreamTwiml(options),\n StatusCallback: options.statusCallback,\n ...(machineDetection\n ? {\n MachineDetection: 'DetectMessageEnd',\n AsyncAmd: 'true',\n AsyncAmdStatusCallback: machineDetectionUrl,\n }\n : {}),\n })\n return { callId: call.sid }\n}\n\n/**\n * Reads the result of the machine detection of Twilio, as it posts it to the\n * `AsyncAmdStatusCallback` or to the voice webhook\n * @param params - The fields of the request, parsed from its form body\n */\nexport function twilioMachineDetection(\n params: Record<string, any> | URLSearchParams\n): { callId: string; detection: MachineDetection } | undefined {\n const get = (key: string) =>\n params instanceof URLSearchParams ? params.get(key) : params[key]\n const callId = get('CallSid')\n const answeredBy = get('AnsweredBy')\n if (!callId || !answeredBy) return undefined\n const raw = Object.fromEntries(\n params instanceof URLSearchParams ? params : Object.entries(params)\n )\n if (answeredBy === 'human') {\n return {\n callId,\n detection: { answeredBy: 'human', greetingEnded: false, raw },\n }\n }\n if (answeredBy === 'fax') {\n return {\n callId,\n detection: { answeredBy: 'fax', greetingEnded: false, raw },\n }\n }\n if (String(answeredBy).startsWith('machine')) {\n return {\n callId,\n detection: {\n answeredBy: 'machine',\n greetingEnded: answeredBy !== 'machine_start',\n raw,\n },\n }\n }\n return {\n callId,\n detection: { answeredBy: 'unknown', greetingEnded: false, raw },\n }\n}\n","import { createSign, randomUUID } from 'node:crypto'\nimport { callApi, requireOption, sleep } from './http'\nimport {\n MachineDetection,\n parseJson,\n TelephonyTransport,\n TransferOptions,\n WarmTransferOptions,\n WarmTransferResult,\n} from './TelephonyTransport'\n\n// Keys of the headers that carry the call itself, set by vonageConnectNcco()\nconst CALL_HEADERS = {\n callId: 'micdropCallId',\n from: 'micdropFrom',\n to: 'micdropTo',\n direction: 'micdropDirection',\n ref: 'micdropRef',\n} as const\n\nconst API = 'https://api.nexmo.com/v1'\nconst POLL_INTERVAL = 1000 // ms\nconst DEFAULT_RING_TIMEOUT = 30 // s\nconst DEFAULT_FALLBACK =\n 'Sorry, nobody could take your call. Please call back later.'\n\n/**\n * Calls placed by `vonageCall()`, by the reference their NCCO carries: Vonage\n * gives the call its identifier only once created, after the NCCO is written\n */\nconst outboundCalls = new Map<string, string>()\n\n/** Credentials of a Vonage application, to act on calls through its API */\nexport interface VonageCredentials {\n /** ID of the Vonage application */\n applicationId: string\n /** Private key of the application, in PEM format */\n privateKey: string\n}\n\nexport interface VonageTransportOptions extends Partial<VonageCredentials> {\n /** The rate of the NCCO, read again from the first message */\n sampleRate?: number\n /**\n * Plays to the caller while the person reached in a warm transfer hears\n * the briefing, the address of an audio file. Silence by default.\n */\n holdMusicUrl?: string\n /**\n * Said to the caller when the person reached in a warm transfer hangs up\n * before joining\n */\n transferFallback?: string\n}\n\n/**\n * A call from the Vonage Voice API, connected to a WebSocket by the\n * `connect` action of its NCCO, which {@link vonageConnectNcco} writes.\n *\n * Audio travels both ways as binary frames of 16 bits linear PCM, little\n * endian, at the rate of the `content-type` of the NCCO: 16 kHz by default,\n * twice the quality of a regular phone line. The NCCO headers are the\n * parameters of the call.\n *\n * Transfers and keys go through the Voice API, and need the credentials of\n * the application.\n *\n * @see https://developer.vonage.com/en/voice/voice-api/concepts/websockets\n */\nexport class VonageTransport extends TelephonyTransport {\n private rate: number\n\n /**\n * @param socket - The socket Vonage opened\n * @param options - The rate of the NCCO, and the credentials of the\n * application for the transfers and keys\n */\n constructor(\n socket: ConstructorParameters<typeof TelephonyTransport>[0],\n private options: VonageTransportOptions = {}\n ) {\n super(socket)\n this.rate = options.sampleRate ?? 16000\n }\n\n protected get lineRate() {\n return this.rate\n }\n\n protected onProviderMessage(data: Buffer, isBinary: boolean) {\n if (isBinary) {\n this.receiveAudio(data)\n return\n }\n const message = parseJson(data)\n switch (message?.event) {\n case 'websocket:connected': {\n const { event, 'content-type': contentType, ...headers } = message\n if (contentType && !/^audio\\/l16/i.test(contentType)) {\n this.fail(\n `Vonage streams ${contentType}, VonageTransport reads audio/l16: set the content-type of the NCCO, as vonageConnectNcco() does`\n )\n return\n }\n const rate = /rate=(\\d+)/.exec(contentType ?? '')?.[1]\n if (rate) this.rate = Number(rate)\n const ref = headers[CALL_HEADERS.ref]\n const call = {\n callId: headers[CALL_HEADERS.callId] ?? outboundCalls.get(ref),\n from: headers[CALL_HEADERS.from],\n to: headers[CALL_HEADERS.to],\n direction: headers[CALL_HEADERS.direction],\n }\n if (ref) outboundCalls.delete(ref)\n for (const key of Object.values(CALL_HEADERS)) delete headers[key]\n delete headers.reconnect_attempt\n this.startStream(call, headers)\n break\n }\n case 'websocket:notify':\n this.markPlayed(message.payload?.micdropMark)\n break\n case 'websocket:dtmf':\n this.receiveDtmf(message.digit)\n break\n }\n }\n\n protected writeAudio(pcm: Buffer) {\n if (this.isOpen) this.socket.send(pcm)\n }\n\n protected writeClear() {\n this.sendJson({ action: 'clear' })\n }\n\n protected writeMark(name: string) {\n this.sendJson({ action: 'notify', payload: { micdropMark: name } })\n }\n\n /** Sends the keys with the Voice API, or in the audio without credentials */\n async sendDtmf(digits: string) {\n if (!this.options.applicationId || !this.options.privateKey) {\n return super.sendDtmf(digits)\n }\n const callId = this.requireCallId()\n await this.sendDtmfWithPauses(digits, (keys) =>\n this.api('send DTMF').request(\n 'Vonage DTMF',\n 'PUT',\n `/calls/${encodeURIComponent(callId)}/dtmf`,\n { digits: keys }\n )\n )\n }\n\n /**\n * Moves the call to an NCCO that connects it to the number. `from`\n * defaults to the number of your account on the call.\n */\n async transfer({ to, from, timeout }: TransferOptions) {\n const api = this.api('transfer the call')\n const callId = this.requireCallId()\n const callerId = requireOption(\n from ?? this.ownNumber,\n 'VonageTransport: set `from` to transfer the call'\n )\n await api.transfer(callId, [\n {\n action: 'connect',\n from: vonageNumber(callerId),\n ...(timeout ? { timeout: Math.round(timeout) } : {}),\n endpoint: [vonageEndpoint(to)],\n },\n ])\n this.handOff(to)\n }\n\n /**\n * Calls the person with the briefing and a named conversation, then moves\n * the caller into it once they picked up. The person joins right after the\n * briefing.\n *\n * `from` defaults to the number of your account on the call.\n */\n async warmTransfer({\n to,\n from,\n timeout = DEFAULT_RING_TIMEOUT,\n briefing,\n }: WarmTransferOptions): Promise<WarmTransferResult> {\n const api = this.api('make a warm transfer')\n const callId = this.requireCallId()\n const callerId = requireOption(\n from ?? this.ownNumber,\n 'VonageTransport: set `from` to make a warm transfer'\n )\n const room = `micdrop-${callId}`\n const person = await api.request('Vonage call creation', 'POST', '/calls', {\n to: [vonageEndpoint(to)],\n from: { type: 'phone', number: vonageNumber(callerId) },\n ringing_timer: Math.round(timeout),\n ncco: [\n ...(briefing ? [{ action: 'talk', text: briefing }] : []),\n {\n action: 'conversation',\n name: room,\n startOnEnter: true,\n endOnExit: true,\n },\n ],\n })\n\n // Wait for the person to pick up, or for the call to fail\n const deadline = Date.now() + (timeout + 15) * 1000\n let status: string = person?.status ?? 'started'\n while (Date.now() < deadline && isRinging(status)) {\n await sleep(POLL_INTERVAL)\n status = (await api.getCall(person.uuid)).status\n }\n if (status !== 'answered') {\n if (isRinging(status)) await api.hangUp(person.uuid).catch(() => {})\n return { transferred: false, reason: transferFailure(status) }\n }\n\n const { holdMusicUrl } = this.options\n await api.transfer(callId, [\n {\n action: 'conversation',\n name: room,\n startOnEnter: false,\n endOnExit: true,\n ...(holdMusicUrl ? { musicOnHoldUrl: [holdMusicUrl] } : {}),\n },\n ])\n this.handOff(to)\n this.rescueIfAbandoned(api, callId, person.uuid)\n return { transferred: true }\n }\n\n /**\n * Tells the caller nobody is there when the person hangs up during the\n * briefing: had they joined, their leaving would have ended the call\n */\n private async rescueIfAbandoned(\n api: VonageApi,\n callId: string,\n personId: string\n ) {\n const deadline = Date.now() + 5 * 60 * 1000\n try {\n while (Date.now() < deadline) {\n await sleep(POLL_INTERVAL * 2)\n if ((await api.getCall(personId)).status === 'answered') continue\n await sleep(3000)\n if ((await api.getCall(callId)).status !== 'answered') return\n this.logger.info(\n 'The person left before joining, the caller hears the fallback'\n )\n await api.transfer(callId, [\n {\n action: 'talk',\n text: this.options.transferFallback ?? DEFAULT_FALLBACK,\n },\n ])\n return\n }\n } catch (error) {\n this.logger.error('Watching the transfer failed', { error })\n }\n }\n\n private requireCallId(): string {\n return requireOption(\n this.call.callId,\n 'VonageTransport: the call is unknown, pass the answer webhook call to vonageConnectNcco() or place it with vonageCall()'\n )\n }\n\n private api(action: string): VonageApi {\n const message = `VonageTransport needs applicationId and privateKey to ${action}`\n return new VonageApi({\n applicationId: requireOption(this.options.applicationId, message),\n privateKey: requireOption(this.options.privateKey, message),\n })\n }\n\n private sendJson(message: object) {\n if (this.isOpen) this.socket.send(JSON.stringify(message))\n }\n}\n\n/** The calls of a Vonage application, through the Voice API */\nclass VonageApi {\n constructor(private credentials: VonageCredentials) {}\n\n request(what: string, method: string, path: string, body?: object) {\n return callApi(what, `${API}${path}`, {\n method,\n headers: {\n Authorization: `Bearer ${vonageJwt(this.credentials)}`,\n ...(body ? { 'Content-Type': 'application/json' } : {}),\n },\n ...(body ? { body: JSON.stringify(body) } : {}),\n })\n }\n\n getCall(uuid: string) {\n return this.request(\n 'Vonage call fetch',\n 'GET',\n `/calls/${encodeURIComponent(uuid)}`\n )\n }\n\n transfer(uuid: string, ncco: object[]) {\n return this.request(\n 'Vonage transfer',\n 'PUT',\n `/calls/${encodeURIComponent(uuid)}`,\n { action: 'transfer', destination: { type: 'ncco', ncco } }\n )\n }\n\n hangUp(uuid: string) {\n return this.request(\n 'Vonage hang up',\n 'PUT',\n `/calls/${encodeURIComponent(uuid)}`,\n { action: 'hangup' }\n )\n }\n}\n\nfunction isRinging(status: string) {\n return status === 'started' || status === 'ringing'\n}\n\nfunction transferFailure(status: string) {\n switch (status) {\n case 'busy':\n case 'rejected':\n return 'busy'\n case 'timeout':\n case 'unanswered':\n case 'cancelled':\n case 'started':\n case 'ringing':\n return 'no-answer'\n case 'machine':\n return 'voicemail'\n case 'completed':\n return 'hung-up'\n default:\n return 'failed'\n }\n}\n\n/** A number as Vonage writes it, digits only */\nfunction vonageNumber(number: string): string {\n return number.replace(/^\\+/, '')\n}\n\nfunction vonageEndpoint(to: string) {\n return /^sips?:/i.test(to)\n ? { type: 'sip', uri: to }\n : { type: 'phone', number: vonageNumber(to) }\n}\n\n/**\n * Signs the token the Voice API takes, valid 5 minutes\n * @see https://developer.vonage.com/en/getting-started/concepts/authentication\n */\nexport function vonageJwt({ applicationId, privateKey }: VonageCredentials) {\n const now = Math.floor(Date.now() / 1000)\n const encode = (value: object) =>\n Buffer.from(JSON.stringify(value)).toString('base64url')\n const unsigned = `${encode({ alg: 'RS256', typ: 'JWT' })}.${encode({\n application_id: applicationId,\n iat: now,\n nbf: now - 10,\n exp: now + 300,\n jti: randomUUID(),\n })}`\n const signature = createSign('RSA-SHA256')\n .update(unsigned)\n .sign(privateKey.replace(/\\\\n/g, '\\n'))\n .toString('base64url')\n return `${unsigned}.${signature}`\n}\n\nexport interface VonageConnectOptions {\n /** Address of the WebSocket that runs the call */\n url: string\n /** Parameters of the call, which `waitForParams` hands back */\n parameters?: Record<string, string | number | boolean>\n /**\n * The call, as the answer webhook describes it (`uuid`, `from`, `to`), so\n * the transport knows which call it carries\n */\n call?: { uuid?: string; from?: string; to?: string }\n /** Rate of the audio, 16000 by default */\n sampleRate?: 8000 | 16000 | 24000\n /** Where Vonage sends the events of the WebSocket leg */\n eventUrl?: string\n}\n\n/**\n * Writes the NCCO that connects a call to a Micdrop server, to answer the\n * answer webhook of a Vonage application with\n * @returns The NCCO, to send as JSON\n */\nexport function vonageConnectNcco({\n url,\n parameters = {},\n call,\n sampleRate = 16000,\n eventUrl,\n}: VonageConnectOptions): object[] {\n const headers: Record<string, string | number | boolean> = { ...parameters }\n if (call?.uuid) headers[CALL_HEADERS.callId] = call.uuid\n if (call?.from) headers[CALL_HEADERS.from] = call.from\n if (call?.to) headers[CALL_HEADERS.to] = call.to\n return [\n {\n action: 'connect',\n ...(eventUrl ? { eventUrl: [eventUrl] } : {}),\n endpoint: [\n {\n type: 'websocket',\n uri: url,\n 'content-type': `audio/l16;rate=${sampleRate}`,\n headers,\n },\n ],\n },\n ]\n}\n\nexport interface VonageCallOptions\n extends VonageCredentials, Omit<VonageConnectOptions, 'call'> {\n /** Number to call, in E.164 format, or a SIP URI */\n to: string\n /** Number of your application that calls */\n from: string\n /** How long to let the phone ring, in seconds, 30 by default */\n timeout?: number\n /**\n * Detects whether a person or a machine picked up, and when the beep of a\n * machine sounds. Vonage posts the result to `eventUrl`: hand it to\n * `TelephonyCalls.vonageEvent()`.\n */\n machineDetection?: boolean\n}\n\n/**\n * Calls a number, and streams the call to a Micdrop server once picked up.\n *\n * The transport learns the identifier of the call from this function, so the\n * WebSocket has to land on the same process.\n *\n * @returns The UUID of the call, which the transport gets as `call.callId`\n * @see https://developer.vonage.com/en/api/voice#createCall\n */\nexport async function vonageCall(\n options: VonageCallOptions\n): Promise<{ callId: string }> {\n const { to, from, timeout, machineDetection, eventUrl } = options\n if (machineDetection && !eventUrl) {\n throw new Error(\n 'vonageCall: machineDetection needs eventUrl, where Vonage posts the result'\n )\n }\n const ref = randomUUID()\n const ncco = vonageConnectNcco({ ...options, call: { from, to } })\n const headers = (ncco[0] as any).endpoint[0].headers\n headers[CALL_HEADERS.direction] = 'outbound'\n headers[CALL_HEADERS.ref] = ref\n const call = await new VonageApi(options).request(\n 'Vonage call creation',\n 'POST',\n '/calls',\n {\n to: [vonageEndpoint(to)],\n from: { type: 'phone', number: vonageNumber(from) },\n ncco,\n ...(timeout ? { ringing_timer: Math.round(timeout) } : {}),\n ...(eventUrl ? { event_url: [eventUrl] } : {}),\n ...(machineDetection\n ? {\n advanced_machine_detection: {\n behavior: 'continue',\n mode: 'detect_beep',\n },\n }\n : {}),\n }\n )\n const callId: string | undefined = call?.uuid\n if (!callId) throw new Error('Vonage returned no uuid for the call')\n outboundCalls.set(ref, callId)\n setTimeout(() => outboundCalls.delete(ref), 10 * 60 * 1000).unref?.()\n return { callId }\n}\n\n/**\n * Reads a result of the machine detection of Vonage from an event\n * @param body - The JSON body Vonage posted to the event URL\n */\nexport function vonageMachineDetection(\n body: any\n): { callId: string; detection: MachineDetection } | undefined {\n const callId = body?.call_uuid ?? body?.uuid\n const status = body?.status\n if (!callId || (status !== 'human' && status !== 'machine')) return undefined\n const subState = body?.sub_state\n if (subState === 'fax') {\n return {\n callId,\n detection: { answeredBy: 'fax', greetingEnded: false, raw: body },\n }\n }\n return {\n callId,\n detection: {\n answeredBy: status,\n greetingEnded: subState === 'beep_start' || subState === 'beep_timeout',\n raw: body,\n },\n }\n}\n","import { plivoMachineDetection } from './plivo'\nimport { MachineDetection, TelephonyTransport } from './TelephonyTransport'\nimport {\n telnyxEventTarget,\n telnyxMachineDetection,\n TelnyxTransport,\n} from './telnyx'\nimport { twilioMachineDetection } from './twilio'\nimport { vonageMachineDetection } from './vonage'\n\n/** How long a result that came before its stream waits for it */\nconst EARLY_RESULT_TTL = 2 * 60 * 1000 // ms\n\n/**\n * The calls a server runs, by the identifier the provider gave them, to hand\n * them what the provider reports to a webhook rather than to the stream: the\n * answering machine detection, and the steps of a warm transfer on Telnyx.\n *\n * One instance per server. Each transport joins it once created, and leaves\n * it when its call ends.\n *\n * ```ts\n * const calls = new TelephonyCalls()\n * // The stream\n * calls.add(new TwilioTransport(socket, credentials))\n * // The webhook\n * app.post('/twilio/amd', (request) => {\n * calls.twilioMachineDetection(request.body)\n * })\n * ```\n */\nexport class TelephonyCalls {\n private transports = new Map<string, TelephonyTransport>()\n private early = new Map<\n string,\n { detection: MachineDetection; timer: ReturnType<typeof setTimeout> }\n >()\n\n /**\n * Adds a call, known by its identifier once its stream started\n * @returns The transport, to chain on\n */\n add<Transport extends TelephonyTransport>(transport: Transport): Transport {\n const register = () => {\n const callId = transport.call.callId\n if (!callId) return\n this.transports.set(callId, transport)\n transport.once('Close', () => {\n if (this.transports.get(callId) === transport) {\n this.transports.delete(callId)\n }\n })\n const early = this.early.get(callId)\n if (early) {\n clearTimeout(early.timer)\n this.early.delete(callId)\n transport.receiveMachineDetection(early.detection)\n }\n }\n if (transport.call.callId) register()\n else transport.once('Params', register)\n return transport\n }\n\n /** The call with this identifier at the provider, while its stream runs */\n get(callId: string): TelephonyTransport | undefined {\n return this.transports.get(callId)\n }\n\n /** Number of calls under way */\n get size(): number {\n return this.transports.size\n }\n\n /**\n * Hands a result of machine detection to its call, or keeps it a while\n * for a stream that has not started yet\n * @returns Whether the call was found\n */\n machineDetected(callId: string, detection: MachineDetection): boolean {\n const transport = this.transports.get(callId)\n if (transport) {\n transport.receiveMachineDetection(detection)\n return true\n }\n const previous = this.early.get(callId)\n if (previous) clearTimeout(previous.timer)\n const timer = setTimeout(() => this.early.delete(callId), EARLY_RESULT_TTL)\n timer.unref?.()\n this.early.set(callId, { detection, timer })\n return false\n }\n\n /**\n * Reads the request Twilio posts to the `AsyncAmdStatusCallback` of a call\n * @param params - The fields of its form body\n * @returns Whether it carried a result\n */\n twilioMachineDetection(params: Record<string, any> | URLSearchParams) {\n const result = twilioMachineDetection(params)\n if (result) this.machineDetected(result.callId, result.detection)\n return !!result\n }\n\n /**\n * Reads a webhook event of a Telnyx Call Control application: the machine\n * detection of a call, and the steps of its warm transfer\n * @param body - The JSON body of the webhook\n * @returns Whether a call of this server had a use for it\n */\n telnyxWebhook(body: unknown): boolean {\n const target = telnyxEventTarget(body)\n if (!target) return false\n if (target.transfer) {\n const transport = this.transports.get(target.callId)\n if (!(transport instanceof TelnyxTransport)) return false\n transport.receiveTelnyxEvent(target.event)\n return true\n }\n const result = telnyxMachineDetection(body)\n if (!result) return false\n this.machineDetected(result.callId, result.detection)\n return true\n }\n\n /**\n * Reads an event Vonage posts to the event URL of a call\n * @param body - Its JSON body\n * @returns Whether it carried a result of machine detection\n */\n vonageEvent(body: unknown): boolean {\n const result = vonageMachineDetection(body)\n if (result) this.machineDetected(result.callId, result.detection)\n return !!result\n }\n\n /**\n * Reads the request Plivo posts to the `machine_detection_url` of a call\n * @param params - The fields of its form body\n * @returns Whether it carried a result\n */\n plivoMachineDetection(params: Record<string, any> | URLSearchParams) {\n const result = plivoMachineDetection(params)\n if (result) this.machineDetected(result.callId, result.detection)\n return !!result\n }\n}\n","import type { Agent, MicdropServer, Tool } from '@micdrop/server'\nimport { z } from 'zod'\nimport { DTMF_DIGITS } from './dtmf'\nimport { TelephonyTransport } from './TelephonyTransport'\nimport { leaveVoicemail } from './voicemail'\n\n/** A number or SIP address the agent can send the call to */\nexport interface TransferDestination {\n /** Name the model picks it by, such as `sales` */\n name: string\n /** Phone number in E.164 format, such as `+14155550100`, or a SIP URI */\n to: string\n /** When to choose it, for the model */\n description?: string\n}\n\nexport interface TransferCallToolOptions {\n /** The one destination, when there is only one */\n to?: string\n /** Destinations the model picks from, by name */\n destinations?: TransferDestination[]\n /**\n * `cold` hands the call over at once. `warm` reaches the person first and\n * briefs them with a summary the model writes, the caller staying with\n * the assistant until they pick up. `cold` by default.\n */\n mode?: 'cold' | 'warm'\n /** Number the person reached sees, one of your account */\n from?: string\n /** How long to let the phone ring, in seconds, 30 by default */\n timeout?: number\n /** Name of the tool, `transfer_call` by default */\n name?: string\n /** Tells the model when to transfer, in place of the default wording */\n description?: string\n}\n\nconst PHONE_OR_SIP = /^(\\+[1-9]\\d{5,14}|sips?:.+)$/\n\n/** The telephony transport of a call, or an error that says what is missing */\nfunction telephonyTransport(server: MicdropServer): TelephonyTransport {\n const transport = server.transport\n if (!(transport instanceof TelephonyTransport)) {\n throw new Error(\n `This tool acts on a phone call, and the call runs on ${transport?.constructor.name ?? 'nothing'}`\n )\n }\n return transport\n}\n\n/**\n * Lets the model send the call to a person or another line: once the words\n * that announce it have been played, the transport transfers the call\n * through the API of its provider, and the assistant leaves.\n *\n * In `warm` mode, the model writes a summary for the person, the provider\n * speaks it to them once they pick up, and the caller joins after. When\n * nobody picks up, the assistant stays on the line and the model hears why.\n *\n * The transport needs the credentials of its provider to transfer.\n */\nexport function transferCallTool(options: TransferCallToolOptions): Tool {\n const destinations: TransferDestination[] = options.destinations\n ? options.destinations\n : options.to\n ? [{ name: 'default', to: options.to }]\n : []\n if (destinations.length === 0) {\n throw new Error('transferCallTool needs `to` or `destinations`')\n }\n for (const destination of destinations) {\n if (!PHONE_OR_SIP.test(destination.to)) {\n throw new Error(\n `transferCallTool: \"${destination.to}\" is neither a phone number in E.164 format nor a SIP URI`\n )\n }\n }\n const warm = options.mode === 'warm'\n const several = destinations.length > 1 || !!options.destinations\n\n const shape: Record<string, z.ZodType> = {}\n if (several) {\n shape.destination = z\n .enum(destinations.map((d) => d.name) as [string, ...string[]])\n .describe(\n 'Where to send the call: ' +\n destinations\n .map((d) =>\n d.description ? `${d.name} (${d.description})` : d.name\n )\n .join(', ')\n )\n }\n if (warm) {\n shape.summary = z\n .string()\n .describe(\n 'What the person taking the call needs to know, spoken to them before the caller joins: who calls and what for, in one or two sentences'\n )\n }\n\n return {\n name: options.name ?? 'transfer_call',\n description:\n options.description ??\n (warm\n ? 'Call this tool when the user asks for a human, or needs help you cannot give. Tell the user you are getting someone and ask them to hold before calling it.'\n : 'Call this tool when the user asks for a human, or needs help you cannot give. Tell the user you are transferring them before calling it.'),\n inputSchema: z.object(shape),\n execute: (\n input: { destination?: string; summary?: string },\n agent: Agent\n ) => {\n const destination =\n destinations.find((d) => d.name === input.destination) ??\n destinations[0]\n const transfer = {\n to: destination.to,\n from: options.from,\n timeout: options.timeout,\n }\n agent.afterAnswer(async (server) => {\n const transport = telephonyTransport(server)\n try {\n if (!warm) {\n await transport.transfer(transfer)\n return\n }\n const result = await transport.warmTransfer({\n ...transfer,\n briefing: input.summary,\n })\n if (result.transferred) return\n server.addSystemMessage(\n `The transfer to ${destination.name} did not go through (${result.reason}). The user is still on the line with you: tell them, and offer another way to help.`\n )\n server.answer()\n } catch (error) {\n server.logger.error('Transfer failed', {\n tool: 'transferCall',\n error,\n })\n if (server.isEnded) return\n server.addSystemMessage(\n `The transfer to ${destination.name} failed. The user is still on the line with you: apologize, and offer another way to help.`\n )\n server.answer()\n }\n })\n return {\n status: warm ? 'calling' : 'transferring',\n destination: destination.name,\n }\n },\n }\n}\n\nexport interface SendDtmfToolOptions {\n /** Name of the tool, `send_dtmf` by default */\n name?: string\n /** Tells the model when to press keys, in place of the default wording */\n description?: string\n}\n\n/**\n * Lets the model press keys on the phone, to find its way through the menu of\n * the phone system it called. The keys go once the answer under way has been\n * played, and the model stays quiet meanwhile.\n */\nexport function sendDtmfTool(options: SendDtmfToolOptions = {}): Tool {\n return {\n name: options.name ?? 'send_dtmf',\n description:\n options.description ??\n 'Press keys on the phone keypad, to choose in an automated phone menu or enter a number it asks for. Only call it when you hear an automated system ask for a key.',\n skipAnswer: true,\n inputSchema: z.object({\n digits: z\n .string()\n .regex(DTMF_DIGITS)\n .describe(\n 'Keys to press: 0-9, * and #, with w for a half second pause'\n ),\n }),\n execute: (input, agent: Agent) => {\n const digits = String(input.digits)\n agent.afterAnswer((server) => telephonyTransport(server).sendDtmf(digits))\n return { pressed: digits }\n },\n }\n}\n\nexport interface VoicemailToolOptions {\n /**\n * Message to leave, the same for every call. Without it, the model words\n * it from the conversation.\n */\n message?: string\n /** Name of the tool, `leave_voicemail` by default */\n name?: string\n /** Tells the model when it reached a voicemail, in place of the default */\n description?: string\n}\n\n/**\n * Lets the model tell a voicemail from a person: once it hears a greeting,\n * it calls the tool, and the assistant waits for the greeting to end, leaves\n * the message and hangs up.\n *\n * It works on every provider, with or without their own detection, on what\n * the speech to text heard.\n */\nexport function voicemailTool(options: VoicemailToolOptions = {}): Tool {\n return {\n name: options.name ?? 'leave_voicemail',\n description:\n options.description ??\n 'Call this tool only if you hear an answering machine or a voicemail greeting instead of a person, such as \"leave a message after the tone\". Say nothing else.',\n skipAnswer: true,\n execute: (_input, agent: Agent) => {\n agent.afterAnswer((server) =>\n leaveVoicemail(server, { message: options.message })\n )\n return { status: 'leaving a message' }\n },\n }\n}\n","import type { MicdropServer } from '@micdrop/server'\nimport { MachineDetection, TelephonyTransport } from './TelephonyTransport'\n\nexport interface LeaveVoicemailOptions {\n /**\n * Message to leave. Without it, the agent words it from the conversation,\n * told it reached a voicemail.\n */\n message?: string\n /**\n * How long the line has to stay quiet for the greeting to count as over,\n * in ms, when the provider does not say when it ends. 1500 by default.\n */\n silence?: number\n /** How long to wait for the greeting to end at most, in ms, 20000 by default */\n maxWait?: number\n}\n\nconst DEFAULT_SILENCE = 1500 // ms\nconst DEFAULT_MAX_WAIT = 20000 // ms\nconst VOICEMAIL_NOTE =\n 'You reached a voicemail, and the recording has started. Leave a short message now, saying who you are and why you called, then say goodbye.'\n\n/**\n * Leaves a message on the voicemail that picked up, then hangs up.\n *\n * The assistant stops talking over the greeting, waits for its end, then\n * speaks the message and ends the call once it has been played. The end of\n * the greeting comes from the provider when its detection reports it (the\n * beep), from a pause of the line otherwise.\n *\n * @param server - The call\n * @param options - The message, and how to find the end of the greeting\n */\nexport async function leaveVoicemail(\n server: MicdropServer,\n options: LeaveVoicemailOptions = {}\n): Promise<void> {\n const transport = server.transport\n if (!transport || server.isEnded) return\n server.cancel()\n transport.clearAudio()\n await waitForGreetingEnd(server, options)\n if (server.isEnded) return\n if (options.message) {\n server.say(options.message)\n } else {\n server.addSystemMessage(VOICEMAIL_NOTE)\n server.answer()\n }\n server.endCall()\n}\n\n/** Resolves once the greeting of the machine is over */\nfunction waitForGreetingEnd(\n server: MicdropServer,\n options: LeaveVoicemailOptions\n): Promise<void> {\n const transport =\n server.transport instanceof TelephonyTransport\n ? server.transport\n : undefined\n const detected = transport?.machineDetection\n if (detected?.greetingEnded) return Promise.resolve()\n // The provider is listening for the beep: a pause in the greeting is not\n // its end yet, so the line has to stay quiet longer\n const silence =\n (options.silence ?? DEFAULT_SILENCE) *\n (detected?.answeredBy === 'machine' ? 2 : 1)\n const maxWait = options.maxWait ?? DEFAULT_MAX_WAIT\n\n return new Promise((resolve) => {\n let speaking = false\n let lastActivity = Date.now()\n const start = Date.now()\n const onStart = () => {\n speaking = true\n lastActivity = Date.now()\n }\n const onStop = () => {\n speaking = false\n lastActivity = Date.now()\n }\n const onDetection = (detection: MachineDetection) => {\n if (detection.greetingEnded) done()\n }\n const interval = setInterval(() => {\n const now = Date.now()\n if (server.isEnded || now - start >= maxWait) return done()\n if (!speaking && now - lastActivity >= silence) done()\n }, 100)\n function done() {\n clearInterval(interval)\n server.off('UserStartSpeaking', onStart)\n server.off('UserStopSpeaking', onStop)\n transport?.off('MachineDetection', onDetection)\n resolve()\n }\n server.on('UserStartSpeaking', onStart)\n server.on('UserStopSpeaking', onStop)\n transport?.on('MachineDetection', onDetection)\n })\n}\n\nexport interface AnsweringMachineOptions {\n /**\n * Message to leave on a voicemail, worded by the agent when left out, or\n * `false` to hang up without one\n */\n message?: string | false\n /** Options of {@link leaveVoicemail} */\n silence?: number\n maxWait?: number\n /** Called when the provider found a person on the line */\n onHuman?: (detection: MachineDetection) => void\n /**\n * Called when it found a machine or a fax, before anything is done.\n * Returning `false` leaves the call to the application.\n */\n onMachine?: (detection: MachineDetection) => void | boolean\n}\n\n/**\n * Acts on the answering machine detection of the provider, for an outbound\n * call placed with it: leaves a message on a voicemail and hangs up, hangs\n * up on a fax, and lets the conversation go on with a person.\n *\n * @param server - The call, over a telephony transport\n * @param options - What to do with a machine\n * @returns A function that stops listening\n */\nexport function answeringMachine(\n server: MicdropServer,\n options: AnsweringMachineOptions = {}\n): () => void {\n const transport = server.transport\n if (!(transport instanceof TelephonyTransport)) {\n throw new Error(\n `answeringMachine() needs a telephony transport, the call runs on ${transport?.constructor.name ?? 'nothing'}`\n )\n }\n let handled = false\n const onDetection = (detection: MachineDetection) => {\n if (handled || server.isEnded) return\n if (detection.answeredBy === 'human') {\n handled = true\n options.onHuman?.(detection)\n return\n }\n if (detection.answeredBy !== 'machine' && detection.answeredBy !== 'fax') {\n return\n }\n handled = true\n if (options.onMachine?.(detection) === false) return\n if (detection.answeredBy === 'fax' || options.message === false) {\n server.close('Answering machine')\n return\n }\n leaveVoicemail(server, {\n message: options.message,\n silence: options.silence,\n maxWait: options.maxWait,\n }).catch((error) =>\n server.logger.error('Leaving the message failed', { error })\n )\n }\n transport.on('MachineDetection', onDetection)\n if (transport.machineDetection) onDetection(transport.machineDetection)\n const stop = () => transport.off('MachineDetection', onDetection)\n server.on('End', stop)\n return stop\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCO,IAAM,cAAc;AAE3B,IAAM,OAAO,CAAC,KAAK,KAAK,KAAK,GAAG;AAChC,IAAM,UAAU,CAAC,MAAM,MAAM,MAAM,IAAI;AACvC,IAAM,SAAS,CAAC,QAAQ,QAAQ,QAAQ,MAAM;AAG9C,IAAM,OAAO;AACb,IAAM,MAAM;AAEZ,IAAM,YAAY,OAAO;AAMlB,SAAS,gBAAgB,QAAwB;AACtD,MAAI,OAAO,WAAW,YAAY,CAAC,YAAY,KAAK,MAAM,GAAG;AAC3D,UAAM,IAAI;AAAA,MACR,wBAAwB,MAAM;AAAA,IAChC;AAAA,EACF;AACA,SAAO;AACT;AASO,SAAS,UAAU,QAAgB,YAA4B;AACpE,kBAAgB,MAAM;AACtB,QAAM,QAAkB,CAAC;AACzB,QAAM,UAAU,CAAC,OAAe,KAAK,MAAO,aAAa,KAAM,GAAI;AACnE,aAAW,SAAS,QAAQ;AAC1B,QAAI,UAAU,OAAO,UAAU,KAAK;A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