@sinch/functions-runtime 0.5.10 → 0.5.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin/sinch-runtime.js +6 -4
- package/dist/bin/sinch-runtime.js.map +1 -1
- package/dist/{chunk-LU5JRQ64.js → chunk-IRSTA74R.js} +293 -62
- package/dist/chunk-IRSTA74R.js.map +1 -0
- package/dist/chunk-X44DQ6CI.js +52 -0
- package/dist/chunk-X44DQ6CI.js.map +1 -0
- package/dist/index.d.ts +67 -19
- package/dist/index.js +2 -1
- package/dist/voice/v2.d.ts +1597 -0
- package/dist/voice/v2.js +1259 -0
- package/dist/voice/v2.js.map +1 -0
- package/package.json +7 -2
- package/dist/chunk-LU5JRQ64.js.map +0 -1
package/dist/voice/v2.js
ADDED
|
@@ -0,0 +1,1259 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __sinchCreateRequire } from 'node:module';
|
|
3
|
+
const require = __sinchCreateRequire(import.meta.url);
|
|
4
|
+
import "../chunk-X44DQ6CI.js";
|
|
5
|
+
|
|
6
|
+
// ../voice-v2-preview/dist/core/redaction.js
|
|
7
|
+
var REDACTED = "[redacted]";
|
|
8
|
+
function redactCredentials(body) {
|
|
9
|
+
return redactValue(body);
|
|
10
|
+
}
|
|
11
|
+
function redactValue(value) {
|
|
12
|
+
if (Array.isArray(value)) {
|
|
13
|
+
return value.map(redactValue);
|
|
14
|
+
}
|
|
15
|
+
if (value === null || typeof value !== "object") {
|
|
16
|
+
return value;
|
|
17
|
+
}
|
|
18
|
+
const out = {};
|
|
19
|
+
for (const [key, item] of Object.entries(value)) {
|
|
20
|
+
out[key] = key === "credentials" && typeof item === "string" ? REDACTED : redactValue(item);
|
|
21
|
+
}
|
|
22
|
+
return out;
|
|
23
|
+
}
|
|
24
|
+
function scrubCredentials(text, body) {
|
|
25
|
+
let out = text;
|
|
26
|
+
for (const secret of collectCredentials(body)) {
|
|
27
|
+
for (const fragment of [secret, ...secret.split(":")]) {
|
|
28
|
+
if (fragment.length >= 8) {
|
|
29
|
+
out = out.split(fragment).join(REDACTED);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
function collectCredentials(value, found = /* @__PURE__ */ new Set()) {
|
|
36
|
+
if (Array.isArray(value)) {
|
|
37
|
+
for (const item of value) {
|
|
38
|
+
collectCredentials(item, found);
|
|
39
|
+
}
|
|
40
|
+
return found;
|
|
41
|
+
}
|
|
42
|
+
if (value === null || typeof value !== "object") {
|
|
43
|
+
return found;
|
|
44
|
+
}
|
|
45
|
+
for (const [key, item] of Object.entries(value)) {
|
|
46
|
+
if (key === "credentials" && typeof item === "string" && item.length > 0) {
|
|
47
|
+
found.add(item);
|
|
48
|
+
} else {
|
|
49
|
+
collectCredentials(item, found);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return found;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// ../voice-v2-preview/dist/wire/http.js
|
|
56
|
+
var DEFAULT_HOST = "https://voice.api.sinch.com";
|
|
57
|
+
var FETCH_TIMEOUT_MS = 1e4;
|
|
58
|
+
var HttpTransport = class {
|
|
59
|
+
projectId;
|
|
60
|
+
keyId;
|
|
61
|
+
keySecret;
|
|
62
|
+
host;
|
|
63
|
+
fetchImpl;
|
|
64
|
+
constructor(options) {
|
|
65
|
+
this.projectId = options.projectId;
|
|
66
|
+
this.keyId = options.keyId;
|
|
67
|
+
this.keySecret = options.keySecret;
|
|
68
|
+
this.host = (options.host ?? DEFAULT_HOST).replace(/\/$/, "");
|
|
69
|
+
this.fetchImpl = options.fetch ?? globalThis.fetch;
|
|
70
|
+
}
|
|
71
|
+
async createCall(body) {
|
|
72
|
+
const response = await this.request("POST", "calls", body);
|
|
73
|
+
return response;
|
|
74
|
+
}
|
|
75
|
+
async patchCall(target, commands2) {
|
|
76
|
+
const path = "callId" in target ? `calls/${encodeURIComponent(target.callId)}` : `sessions/${encodeURIComponent(target.sessionId)}/calls/${encodeURIComponent(target.callName)}`;
|
|
77
|
+
await this.request("PATCH", path, { commands: commands2 });
|
|
78
|
+
}
|
|
79
|
+
get authHeaders() {
|
|
80
|
+
const token = Buffer.from(`${this.keyId}:${this.keySecret}`).toString("base64");
|
|
81
|
+
return { Authorization: `Basic ${token}`, "Content-Type": "application/json" };
|
|
82
|
+
}
|
|
83
|
+
async request(method, path, body) {
|
|
84
|
+
if (!this.projectId || !this.keyId || !this.keySecret) {
|
|
85
|
+
throw new Error("Voice API v2 needs PROJECT_ID, PROJECT_ID_API_KEY and PROJECT_ID_API_SECRET (the project Access Key pair, not the v1 application key).");
|
|
86
|
+
}
|
|
87
|
+
const url = `${this.host}/v2/projects/${encodeURIComponent(this.projectId)}/${path}`;
|
|
88
|
+
const response = await this.fetchImpl(url, {
|
|
89
|
+
method,
|
|
90
|
+
headers: this.authHeaders,
|
|
91
|
+
body: JSON.stringify(body),
|
|
92
|
+
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS)
|
|
93
|
+
});
|
|
94
|
+
if (!response.ok) {
|
|
95
|
+
const error = scrubCredentials(await response.text(), body);
|
|
96
|
+
throw new Error(`Voice API v2 error: ${response.status} - ${error}`);
|
|
97
|
+
}
|
|
98
|
+
return response.status === 204 || response.status === 202 ? void 0 : response.json();
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
// ../voice-v2-preview/dist/core/endpoints.js
|
|
103
|
+
var DEFAULT_SAMPLE_RATE = 16e3;
|
|
104
|
+
var DEFAULT_VOICE = "Emma";
|
|
105
|
+
var DEFAULT_STT_LANGUAGE = "en-US";
|
|
106
|
+
var STREAM_PROTOCOL_VERSION = 1;
|
|
107
|
+
function defaultStreamOptions(sampleRate = DEFAULT_SAMPLE_RATE) {
|
|
108
|
+
return { version: STREAM_PROTOCOL_VERSION, codec: "PCM", sampleRate };
|
|
109
|
+
}
|
|
110
|
+
function dialPhone(number) {
|
|
111
|
+
return { type: "PHONE", phone: { number: number.replace(/[\s-]/g, "") } };
|
|
112
|
+
}
|
|
113
|
+
function dialSip(address, options = {}) {
|
|
114
|
+
const callHeaders = toCallHeaders(options.headers);
|
|
115
|
+
return {
|
|
116
|
+
type: "SIP",
|
|
117
|
+
sip: {
|
|
118
|
+
endpoint: address,
|
|
119
|
+
...options.transport && { transport: options.transport },
|
|
120
|
+
...callHeaders && { callHeaders }
|
|
121
|
+
}
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
function dialStream(endpoint, options = {}) {
|
|
125
|
+
const callHeaders = toCallHeaders(options.headers);
|
|
126
|
+
return {
|
|
127
|
+
type: "STREAM",
|
|
128
|
+
stream: {
|
|
129
|
+
endpoint,
|
|
130
|
+
streamOptions: defaultStreamOptions(options.sampleRate),
|
|
131
|
+
...callHeaders && { callHeaders }
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
function dialRelay(endpoint, options = {}) {
|
|
136
|
+
const callHeaders = toCallHeaders(options.headers);
|
|
137
|
+
return {
|
|
138
|
+
type: "VOICE_RELAY",
|
|
139
|
+
voiceRelay: {
|
|
140
|
+
endpoint,
|
|
141
|
+
...options.enableInterruptions !== void 0 && {
|
|
142
|
+
enableInterruptions: options.enableInterruptions
|
|
143
|
+
},
|
|
144
|
+
ttsVoice: options.ttsVoice ?? DEFAULT_VOICE,
|
|
145
|
+
sttLanguage: options.sttLanguage ?? DEFAULT_STT_LANGUAGE,
|
|
146
|
+
...callHeaders && { callHeaders }
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
function toEndpoint(destination) {
|
|
151
|
+
if (typeof destination !== "string") {
|
|
152
|
+
return destination;
|
|
153
|
+
}
|
|
154
|
+
if (/^sips?:/i.test(destination)) {
|
|
155
|
+
return { type: "SIP", sip: { endpoint: destination } };
|
|
156
|
+
}
|
|
157
|
+
if (/^wss?:\/\//i.test(destination)) {
|
|
158
|
+
return {
|
|
159
|
+
type: "STREAM",
|
|
160
|
+
stream: { endpoint: destination, streamOptions: defaultStreamOptions() }
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
if (/^\+?\d[\d\s-]*$/.test(destination)) {
|
|
164
|
+
return { type: "PHONE", phone: { number: destination.replace(/[\s-]/g, "") } };
|
|
165
|
+
}
|
|
166
|
+
throw new Error(`Cannot interpret '${destination}' as a call destination. Use an E.164 number, a sip: URI, a ws:// URL, or an endpoint object.`);
|
|
167
|
+
}
|
|
168
|
+
function toOrigin(origin) {
|
|
169
|
+
const endpoint = toEndpoint(origin);
|
|
170
|
+
if (endpoint.type === "STREAM" || endpoint.type === "VOICE_RELAY") {
|
|
171
|
+
throw new Error("A call cannot originate from a STREAM or VOICE_RELAY endpoint. Use a phone number or SIP URI.");
|
|
172
|
+
}
|
|
173
|
+
if (endpoint.type === "SIP") {
|
|
174
|
+
const sip = endpoint.sip;
|
|
175
|
+
if (sip.transport !== void 0 || sip.callHeaders !== void 0) {
|
|
176
|
+
throw new Error("A SIP origin takes only an endpoint and a displayName \u2014 transport and callHeaders belong on the destination, and the API rejects them on `from`.");
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return endpoint;
|
|
180
|
+
}
|
|
181
|
+
function toCallHeaders(headers) {
|
|
182
|
+
if (!headers) {
|
|
183
|
+
return void 0;
|
|
184
|
+
}
|
|
185
|
+
const list = Array.isArray(headers) ? headers : Object.entries(headers).map(([key, value]) => ({ key, value }));
|
|
186
|
+
return list.length > 0 ? list : void 0;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// ../voice-v2-preview/dist/core/commands.js
|
|
190
|
+
function resolveFlow(flow) {
|
|
191
|
+
let list;
|
|
192
|
+
if (typeof flow === "function") {
|
|
193
|
+
const builder = commands();
|
|
194
|
+
list = (flow(builder) ?? builder).build();
|
|
195
|
+
} else if (Array.isArray(flow)) {
|
|
196
|
+
list = flow;
|
|
197
|
+
} else {
|
|
198
|
+
list = flow.build();
|
|
199
|
+
}
|
|
200
|
+
if (list.length === 0) {
|
|
201
|
+
throw new Error("Voice v2 flow is empty. Every nested command list needs at least one command \u2014 add say(), play(), dial(), hangup() or answer().");
|
|
202
|
+
}
|
|
203
|
+
return list;
|
|
204
|
+
}
|
|
205
|
+
var FAILURE_KEYS = ["onBusy", "onReject", "onTimeout", "onFailure"];
|
|
206
|
+
var EVENT_KEYS = ["onAnswer", "onHangup", ...FAILURE_KEYS];
|
|
207
|
+
var AMD_EVENT_KEYS = ["onHuman", "onMachine", "onBeep", "onUnknown"];
|
|
208
|
+
function namesAnyEvent(keys, events) {
|
|
209
|
+
return keys.some((key) => events[key] !== void 0);
|
|
210
|
+
}
|
|
211
|
+
function completeEvents(events, topology = {}) {
|
|
212
|
+
if (!namesAnyEvent(EVENT_KEYS, events)) {
|
|
213
|
+
if (topology.endOnHangup !== void 0 || topology.endOnFailure !== void 0) {
|
|
214
|
+
throw new Error("Voice v2 dial: endOnHangup and endOnFailure are emitted inside the `events` block, and this dial names no event \u2014 they would have been dropped silently. Name onAnswer (plus any outcome you want handled inline), or drop them and let the service webhook end the legs.");
|
|
215
|
+
}
|
|
216
|
+
return void 0;
|
|
217
|
+
}
|
|
218
|
+
const onNeverConnected = [
|
|
219
|
+
{ command: "hangup", ...topology.endOnFailure && { callName: topology.endOnFailure } }
|
|
220
|
+
];
|
|
221
|
+
const block = {};
|
|
222
|
+
if (events.onAnswer !== void 0) {
|
|
223
|
+
block.onAnswer = resolveFlow(events.onAnswer);
|
|
224
|
+
}
|
|
225
|
+
for (const key of FAILURE_KEYS) {
|
|
226
|
+
const supplied = events[key];
|
|
227
|
+
block[key] = supplied !== void 0 ? resolveFlow(supplied) : onNeverConnected;
|
|
228
|
+
}
|
|
229
|
+
if (events.onHangup !== void 0) {
|
|
230
|
+
block.onHangup = resolveFlow(events.onHangup);
|
|
231
|
+
} else if (topology.endOnHangup) {
|
|
232
|
+
block.onHangup = [{ command: "hangup", callName: topology.endOnHangup }];
|
|
233
|
+
}
|
|
234
|
+
if (block.onAnswer === void 0) {
|
|
235
|
+
throw new Error("Voice v2 dial: naming any event detaches the service webhook from all six outcomes, so an `events` block without onAnswer leaves an answered leg with no commands \u2014 silence until maxCallDurationSeconds. Add onAnswer, or name no events at all and let the service webhook answer the leg.");
|
|
236
|
+
}
|
|
237
|
+
return block;
|
|
238
|
+
}
|
|
239
|
+
function completeAmdEvents(events) {
|
|
240
|
+
if (!namesAnyEvent(AMD_EVENT_KEYS, events)) {
|
|
241
|
+
return void 0;
|
|
242
|
+
}
|
|
243
|
+
const block = {};
|
|
244
|
+
for (const key of AMD_EVENT_KEYS) {
|
|
245
|
+
const flow = events[key];
|
|
246
|
+
block[key] = flow !== void 0 ? resolveFlow(flow) : [];
|
|
247
|
+
}
|
|
248
|
+
return block;
|
|
249
|
+
}
|
|
250
|
+
function buildDial(to, options = {}) {
|
|
251
|
+
const carriesCli = to.type !== "STREAM" && to.type !== "VOICE_RELAY";
|
|
252
|
+
const from = carriesCli && options.from ? toOrigin(options.from) : void 0;
|
|
253
|
+
const events = completeEvents(options, options);
|
|
254
|
+
return {
|
|
255
|
+
command: "dial",
|
|
256
|
+
...options.callName && { callName: options.callName },
|
|
257
|
+
...from && { from },
|
|
258
|
+
to,
|
|
259
|
+
...options.timeout !== void 0 && { dialTimeoutDurationSeconds: options.timeout },
|
|
260
|
+
...options.maxDuration !== void 0 && { maxCallDurationSeconds: options.maxDuration },
|
|
261
|
+
...events && { events }
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
function toCredentials(credentials) {
|
|
265
|
+
if (typeof credentials === "string") {
|
|
266
|
+
return credentials;
|
|
267
|
+
}
|
|
268
|
+
const parts = [credentials.accessKeyId, credentials.secretAccessKey, credentials.region];
|
|
269
|
+
if (parts.some((part) => part.includes(":"))) {
|
|
270
|
+
throw new Error("Voice v2 startRecording credentials are joined with colons, so no component may contain one. Pass the pre-joined string instead if your storage service needs a different format.");
|
|
271
|
+
}
|
|
272
|
+
return parts.join(":");
|
|
273
|
+
}
|
|
274
|
+
function toRecordingOptions(options) {
|
|
275
|
+
const transcribing = options.transcribe !== void 0 || options.transcriptionLocale !== void 0;
|
|
276
|
+
return {
|
|
277
|
+
...options.format && { format: options.format },
|
|
278
|
+
...options.recordingType && { recordingType: options.recordingType },
|
|
279
|
+
destination: options.destination ?? "AWS",
|
|
280
|
+
destinationUrl: options.destinationUrl,
|
|
281
|
+
credentials: toCredentials(options.credentials),
|
|
282
|
+
...transcribing && {
|
|
283
|
+
transcriptionOptions: {
|
|
284
|
+
isEnabled: options.transcribe ?? true,
|
|
285
|
+
...options.transcriptionLocale && { locale: options.transcriptionLocale }
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
var PromptBuilder = class {
|
|
291
|
+
messages = [];
|
|
292
|
+
barge;
|
|
293
|
+
/**
|
|
294
|
+
* Speak text.
|
|
295
|
+
*
|
|
296
|
+
* @param text - Text to synthesise, or an SSML document when `format` is `SSML`
|
|
297
|
+
* @param options - Voice and format overrides
|
|
298
|
+
*/
|
|
299
|
+
say(text, options = {}) {
|
|
300
|
+
this.messages.push(sayMessage(text, options));
|
|
301
|
+
return this;
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
304
|
+
* Play an audio file.
|
|
305
|
+
*
|
|
306
|
+
* @param url - Publicly reachable URL of the audio file
|
|
307
|
+
*/
|
|
308
|
+
play(url) {
|
|
309
|
+
this.messages.push({ type: "PLAY", play: { url } });
|
|
310
|
+
return this;
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* Let input interrupt the prompt instead of waiting for it to finish. Emits
|
|
314
|
+
* `allowBargeIn`, which the platform defaults to `true`.
|
|
315
|
+
*
|
|
316
|
+
* @param enabled - Pass `false` to state the opposite explicitly
|
|
317
|
+
*/
|
|
318
|
+
bargeIn(enabled = true) {
|
|
319
|
+
this.barge = enabled;
|
|
320
|
+
return this;
|
|
321
|
+
}
|
|
322
|
+
/** Emit the prompt. @throws If nothing was queued to play */
|
|
323
|
+
build() {
|
|
324
|
+
if (this.messages.length === 0) {
|
|
325
|
+
throw new Error("Voice v2 menu prompt is empty. Call say() or play() on it.");
|
|
326
|
+
}
|
|
327
|
+
return {
|
|
328
|
+
messages: [...this.messages],
|
|
329
|
+
...this.barge !== void 0 && { allowBargeIn: this.barge }
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
};
|
|
333
|
+
function resolvePrompt(prompt) {
|
|
334
|
+
if (typeof prompt === "string") {
|
|
335
|
+
return new PromptBuilder().say(prompt).build();
|
|
336
|
+
}
|
|
337
|
+
if (typeof prompt === "function") {
|
|
338
|
+
const builder = new PromptBuilder();
|
|
339
|
+
return (prompt(builder) ?? builder).build();
|
|
340
|
+
}
|
|
341
|
+
return prompt.build();
|
|
342
|
+
}
|
|
343
|
+
var MenuItemBuilder = class {
|
|
344
|
+
item = {};
|
|
345
|
+
matchOrder = [];
|
|
346
|
+
matches = {};
|
|
347
|
+
/**
|
|
348
|
+
* Prompt played when the menu is entered.
|
|
349
|
+
*
|
|
350
|
+
* @param prompt - Plain text, a {@link PromptBuilder}, or a callback receiving one
|
|
351
|
+
*/
|
|
352
|
+
prompt(prompt) {
|
|
353
|
+
this.item.prompt = resolvePrompt(prompt);
|
|
354
|
+
return this;
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* Prompt played on each retry. Falls back to `prompt` when unset.
|
|
358
|
+
*
|
|
359
|
+
* @param prompt - Plain text, a {@link PromptBuilder}, or a callback receiving one
|
|
360
|
+
*/
|
|
361
|
+
repeatPrompt(prompt) {
|
|
362
|
+
this.item.repeatPrompt = resolvePrompt(prompt);
|
|
363
|
+
return this;
|
|
364
|
+
}
|
|
365
|
+
/**
|
|
366
|
+
* How long to wait for input before repeating.
|
|
367
|
+
*
|
|
368
|
+
* @param seconds - Seconds of silence that count as no input
|
|
369
|
+
*/
|
|
370
|
+
inputTimeout(seconds) {
|
|
371
|
+
this.item.inputTimeoutDurationSeconds = seconds;
|
|
372
|
+
return this;
|
|
373
|
+
}
|
|
374
|
+
/**
|
|
375
|
+
* How many times the prompt repeats before `onFail` runs.
|
|
376
|
+
*
|
|
377
|
+
* @param times - Repeat count
|
|
378
|
+
*/
|
|
379
|
+
repeatCount(times) {
|
|
380
|
+
this.item.repeatCount = times;
|
|
381
|
+
return this;
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* Fewest input characters collected before the menu evaluates them. Emits
|
|
385
|
+
* `minimumInputLength`. 1-100, default 1.
|
|
386
|
+
*
|
|
387
|
+
* @param count - Minimum input length
|
|
388
|
+
*/
|
|
389
|
+
minLength(count) {
|
|
390
|
+
this.item.minimumInputLength = count;
|
|
391
|
+
return this;
|
|
392
|
+
}
|
|
393
|
+
/**
|
|
394
|
+
* Input character count that triggers evaluation. Emits `maximumInputLength`. 1-100,
|
|
395
|
+
* default 1.
|
|
396
|
+
*
|
|
397
|
+
* @param count - Maximum input length
|
|
398
|
+
*/
|
|
399
|
+
maxLength(count) {
|
|
400
|
+
this.item.maximumInputLength = count;
|
|
401
|
+
return this;
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* Character sequence that ends input and triggers evaluation immediately, e.g. `#`.
|
|
405
|
+
*
|
|
406
|
+
* The pair to {@link maxLength}: with a range of accepted lengths, this is how a shorter
|
|
407
|
+
* entry is submitted without waiting out `inputTimeout`. The sequence itself is part of
|
|
408
|
+
* the input the `matches` keys see.
|
|
409
|
+
*
|
|
410
|
+
* @param sequence - Digits, `*` and `#` only, up to 10 characters
|
|
411
|
+
*/
|
|
412
|
+
terminatedBy(sequence) {
|
|
413
|
+
this.item.terminatingSequence = sequence;
|
|
414
|
+
return this;
|
|
415
|
+
}
|
|
416
|
+
/**
|
|
417
|
+
* What one input does.
|
|
418
|
+
*
|
|
419
|
+
* Keys may be literal digits or regular expressions, and the platform evaluates them in
|
|
420
|
+
* definition order with first match winning — so the order these are written in is part of
|
|
421
|
+
* the behaviour, not decoration. {@link build} refuses to emit a menu whose keys JSON
|
|
422
|
+
* cannot carry in that order; see the error it throws.
|
|
423
|
+
*
|
|
424
|
+
* @param pattern - Digits, or a regular expression source
|
|
425
|
+
* @param flow - Commands to run on a match
|
|
426
|
+
*/
|
|
427
|
+
match(pattern, flow) {
|
|
428
|
+
if (!(pattern in this.matches)) {
|
|
429
|
+
this.matchOrder.push(pattern);
|
|
430
|
+
}
|
|
431
|
+
this.matches[pattern] = resolveFlow(flow);
|
|
432
|
+
return this;
|
|
433
|
+
}
|
|
434
|
+
/**
|
|
435
|
+
* Commands to run once the caller is out of attempts.
|
|
436
|
+
*
|
|
437
|
+
* @param flow - Commands to run
|
|
438
|
+
*/
|
|
439
|
+
onFail(flow) {
|
|
440
|
+
this.item.onFail = resolveFlow(flow);
|
|
441
|
+
return this;
|
|
442
|
+
}
|
|
443
|
+
/**
|
|
444
|
+
* Emit the menu.
|
|
445
|
+
*
|
|
446
|
+
* @throws If the `matches` keys cannot be serialised in the order they were written
|
|
447
|
+
*/
|
|
448
|
+
build() {
|
|
449
|
+
const item = { ...this.item };
|
|
450
|
+
if (this.matchOrder.length > 0) {
|
|
451
|
+
const emitted = Object.keys(this.matches);
|
|
452
|
+
const reordered = emitted.some((key, index) => key !== this.matchOrder[index]);
|
|
453
|
+
if (reordered) {
|
|
454
|
+
throw new Error(`Voice v2 menu matches are evaluated in definition order, but JSON cannot carry these keys in the order they were written (${this.matchOrder.join(", ")} would be sent as ${emitted.join(", ")}). Numeric keys always sort first, ascending. Write them in ascending numeric order, or use a regular-expression key such as '^1$'.`);
|
|
455
|
+
}
|
|
456
|
+
item.matches = { ...this.matches };
|
|
457
|
+
}
|
|
458
|
+
return item;
|
|
459
|
+
}
|
|
460
|
+
};
|
|
461
|
+
var CommandBuilder = class {
|
|
462
|
+
list = [];
|
|
463
|
+
pending = [];
|
|
464
|
+
/**
|
|
465
|
+
* Speak text on the call.
|
|
466
|
+
*
|
|
467
|
+
* @param text - Text to synthesise, or an SSML document when `format` is `SSML`
|
|
468
|
+
* @param options - Voice and format overrides
|
|
469
|
+
*/
|
|
470
|
+
say(text, options = {}) {
|
|
471
|
+
this.pending.push(sayMessage(text, options));
|
|
472
|
+
return this;
|
|
473
|
+
}
|
|
474
|
+
/**
|
|
475
|
+
* Play an audio file on the call.
|
|
476
|
+
*
|
|
477
|
+
* @param url - Publicly reachable URL of the audio file
|
|
478
|
+
*/
|
|
479
|
+
play(url) {
|
|
480
|
+
this.pending.push({ type: "PLAY", play: { url } });
|
|
481
|
+
return this;
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* End the call at this point in the sequence.
|
|
485
|
+
*
|
|
486
|
+
* Messages queued before it still play in full — and end the call whether they finish or
|
|
487
|
+
* fail, since a failed playback would otherwise leave the call with nothing to do.
|
|
488
|
+
* Anything queued after it is emitted after it, and on a live call is never reached.
|
|
489
|
+
*
|
|
490
|
+
* @param callName - Leg to end. Ends the current leg when omitted.
|
|
491
|
+
*/
|
|
492
|
+
hangup(callName) {
|
|
493
|
+
const command = () => ({ command: "hangup", ...callName && { callName } });
|
|
494
|
+
if (this.pending.length > 0) {
|
|
495
|
+
this.list.push({
|
|
496
|
+
command: "messages",
|
|
497
|
+
messages: this.pending.splice(0),
|
|
498
|
+
// Both outcomes, for the same reason a `dial`'s events block is completed: `messages`
|
|
499
|
+
// models `onFinish` *and* `onFailure`, and a playback that fails — an audio URL the
|
|
500
|
+
// platform cannot fetch — would otherwise reach neither this list nor the service
|
|
501
|
+
// webhook, leaving the call sitting with no next command.
|
|
502
|
+
events: { onFinish: [command()], onFailure: [command()] }
|
|
503
|
+
});
|
|
504
|
+
} else {
|
|
505
|
+
this.list.push(command());
|
|
506
|
+
}
|
|
507
|
+
return this;
|
|
508
|
+
}
|
|
509
|
+
/** Explicitly answer an inbound leg. */
|
|
510
|
+
answer() {
|
|
511
|
+
return this.push({ command: "answer" });
|
|
512
|
+
}
|
|
513
|
+
/**
|
|
514
|
+
* Add the current leg to a named bridge, creating the bridge on first reference.
|
|
515
|
+
*
|
|
516
|
+
* @param bridgeName - Bridge name (1-32 chars, no whitespace)
|
|
517
|
+
*/
|
|
518
|
+
bridgeCall(bridgeName) {
|
|
519
|
+
return this.push({ command: "bridgeCall", bridgeName });
|
|
520
|
+
}
|
|
521
|
+
/**
|
|
522
|
+
* Dial another leg. Non-blocking — two dials in one list ring two legs in parallel.
|
|
523
|
+
*
|
|
524
|
+
* @param to - Who to call
|
|
525
|
+
* @param options - Dial settings, named events and leg topology
|
|
526
|
+
*/
|
|
527
|
+
dial(to, options = {}) {
|
|
528
|
+
return this.push(buildDial(toEndpoint(to), options));
|
|
529
|
+
}
|
|
530
|
+
/**
|
|
531
|
+
* Collect DTMF input against a named menu. Blocking.
|
|
532
|
+
*
|
|
533
|
+
* Consecutive `menu()` calls extend one `menu` command, so a multi-level IVR is written as
|
|
534
|
+
* a run of them and `gotoMenu` jumps between the names. The first one names `startMenu`.
|
|
535
|
+
* Anything written between two menus (a `say`, a `dial`) breaks the run, and the next
|
|
536
|
+
* `menu()` starts a second command — the list stays in the order it was written.
|
|
537
|
+
*
|
|
538
|
+
* @param name - Menu name, referenced by {@link gotoMenu} and reported on `call.menu`
|
|
539
|
+
* @param define - Callback receiving the {@link MenuItemBuilder} for this menu
|
|
540
|
+
*
|
|
541
|
+
* @example
|
|
542
|
+
* ```typescript
|
|
543
|
+
* commands().menu('main', (m) =>
|
|
544
|
+
* m
|
|
545
|
+
* .prompt((p) => p.say('Press 1 for sales or 2 for support').bargeIn())
|
|
546
|
+
* .match('1', (c) => c.dial(sales))
|
|
547
|
+
* .match('2', (c) => c.dial(support))
|
|
548
|
+
* .onFail((c) => c.say('Sorry, goodbye').hangup())
|
|
549
|
+
* );
|
|
550
|
+
* ```
|
|
551
|
+
*/
|
|
552
|
+
menu(name, define) {
|
|
553
|
+
this.flush();
|
|
554
|
+
const builder = new MenuItemBuilder();
|
|
555
|
+
const item = (define(builder) ?? builder).build();
|
|
556
|
+
const last = this.list[this.list.length - 1];
|
|
557
|
+
if (last && last.command === "menu") {
|
|
558
|
+
last.menus[name] = item;
|
|
559
|
+
return this;
|
|
560
|
+
}
|
|
561
|
+
const command = { command: "menu", startMenu: name, menus: { [name]: item } };
|
|
562
|
+
this.list.push(command);
|
|
563
|
+
return this;
|
|
564
|
+
}
|
|
565
|
+
/**
|
|
566
|
+
* Jump to another menu in the enclosing `menu` command. Legal only inside menu execution.
|
|
567
|
+
*
|
|
568
|
+
* @param menuName - Menu to enter
|
|
569
|
+
*/
|
|
570
|
+
gotoMenu(menuName) {
|
|
571
|
+
return this.push({ command: "gotoMenu", menuName });
|
|
572
|
+
}
|
|
573
|
+
/**
|
|
574
|
+
* Wait before running the next command. Blocking.
|
|
575
|
+
*
|
|
576
|
+
* The call stays connected and audio is unaffected — this delays the *script*, not the
|
|
577
|
+
* media. So it is the way to let a non-blocking command get somewhere before the next one
|
|
578
|
+
* runs: a beat after `amd` reports a beep, before the message that leaves the voicemail.
|
|
579
|
+
*
|
|
580
|
+
* @param durationMilliseconds - How long to wait, in milliseconds. Minimum 1.
|
|
581
|
+
* @throws If the duration is below the schema's minimum of 1
|
|
582
|
+
*/
|
|
583
|
+
pause(durationMilliseconds) {
|
|
584
|
+
if (!Number.isInteger(durationMilliseconds) || durationMilliseconds < 1) {
|
|
585
|
+
throw new Error(`Voice v2 pause takes a whole number of milliseconds, at least 1 (got ${durationMilliseconds}).`);
|
|
586
|
+
}
|
|
587
|
+
return this.push({ command: "pause", durationMilliseconds });
|
|
588
|
+
}
|
|
589
|
+
/**
|
|
590
|
+
* Stop a named `messages` sequence. Non-blocking.
|
|
591
|
+
*
|
|
592
|
+
* Targets a sequence by the `messagesName` it was started under, so it is only reachable
|
|
593
|
+
* from a later command list — a `PATCH` on a live call, or a `dial` event — never from the
|
|
594
|
+
* same list that queued the messages.
|
|
595
|
+
*
|
|
596
|
+
* @param messagesName - Sequence to stop (1-32 chars, no whitespace)
|
|
597
|
+
* @param flags - `ONLY_PLAYING` cancels the current message and lets the queue continue.
|
|
598
|
+
* Omitted, the platform applies `ALL_FROM_NOW_ON` and the whole queue goes.
|
|
599
|
+
*/
|
|
600
|
+
stopMessages(messagesName, flags) {
|
|
601
|
+
return this.push({ command: "stopMessages", messagesName, ...flags && { flags } });
|
|
602
|
+
}
|
|
603
|
+
/**
|
|
604
|
+
* Run answering machine detection on the call. Non-blocking.
|
|
605
|
+
*
|
|
606
|
+
* Detection runs in parallel with the rest of the list; the verdict arrives on one of the
|
|
607
|
+
* four events, or — with no events named — as a `call.amd.*` webhook.
|
|
608
|
+
*
|
|
609
|
+
* These four are the AMD *result* outcomes, so none of them gets a hangup default the way a
|
|
610
|
+
* `dial`'s never-connected outcomes do. They do follow `dial`'s all-or-nothing rule: naming
|
|
611
|
+
* any one of them detaches the service webhook from all four, so this emits a **complete**
|
|
612
|
+
* block once any is named, with the rest as empty lists. Confirmed in `calling-ng` — see
|
|
613
|
+
* {@link AmdEventOptions}.
|
|
614
|
+
*
|
|
615
|
+
* @param events - Commands to run per detection outcome. Omit entirely for webhook mode.
|
|
616
|
+
*
|
|
617
|
+
* @example
|
|
618
|
+
* ```typescript
|
|
619
|
+
* commands()
|
|
620
|
+
* .amd({
|
|
621
|
+
* onHuman: (c) => c.say('Hi, do you have a moment?'),
|
|
622
|
+
* onMachine: (c) => c.say('Sorry we missed you.').hangup(),
|
|
623
|
+
* onBeep: (c) => c.pause(500).say('Sorry we missed you.').hangup(),
|
|
624
|
+
* onUnknown: (c) => c.say('Hi, do you have a moment?'),
|
|
625
|
+
* })
|
|
626
|
+
* .say('Connecting you now.');
|
|
627
|
+
*
|
|
628
|
+
* // Naming none of them leaves all four to the service webhook as `call.amd.*`.
|
|
629
|
+
* commands().amd();
|
|
630
|
+
* ```
|
|
631
|
+
*/
|
|
632
|
+
amd(events = {}) {
|
|
633
|
+
const block = completeAmdEvents(events);
|
|
634
|
+
return this.push({ command: "amd", ...block && { events: block } });
|
|
635
|
+
}
|
|
636
|
+
/**
|
|
637
|
+
* Ask the application what to do next. **Blocking** — the call waits for the response.
|
|
638
|
+
*
|
|
639
|
+
* The event is delivered as `call.webhook.<webhookName>`, so `webhookName: 'escalate'`
|
|
640
|
+
* arrives as `'call.webhook.escalate'`. `Client.onCall` routes those by name to a handler
|
|
641
|
+
* registered under `webhooks`, and to `manage` when no name matches.
|
|
642
|
+
*
|
|
643
|
+
* @param webhookName - Name for this event (1-64 chars, no whitespace)
|
|
644
|
+
* @param url - URL to call. The platform allows it 5 seconds to answer.
|
|
645
|
+
* @param options - Fallback URL
|
|
646
|
+
*
|
|
647
|
+
* @example
|
|
648
|
+
* ```typescript
|
|
649
|
+
* commands().say('One moment.').webhook('escalate', 'https://acme.com/voice');
|
|
650
|
+
*
|
|
651
|
+
* export const handler = voice.onCall({
|
|
652
|
+
* webhooks: { escalate: () => commands().dial('+15550001111') },
|
|
653
|
+
* });
|
|
654
|
+
* ```
|
|
655
|
+
*/
|
|
656
|
+
webhook(webhookName, url, options = {}) {
|
|
657
|
+
return this.push({
|
|
658
|
+
command: "webhook",
|
|
659
|
+
webhookName,
|
|
660
|
+
url,
|
|
661
|
+
...options.fallbackUrl && { fallbackUrl: options.fallbackUrl }
|
|
662
|
+
});
|
|
663
|
+
}
|
|
664
|
+
/**
|
|
665
|
+
* Start recording the call. Non-blocking.
|
|
666
|
+
*
|
|
667
|
+
* **The credential is a long-lived storage secret carried inside the command body** — the
|
|
668
|
+
* schema requires it and offers no short-lived alternative. See {@link RecordingCredentials}
|
|
669
|
+
* before logging anything a `startRecording` is part of.
|
|
670
|
+
*
|
|
671
|
+
* @param options - Destination, credentials, encoding, transcription and outcome events
|
|
672
|
+
* @throws If a structured credential component contains a colon
|
|
673
|
+
*
|
|
674
|
+
* @example
|
|
675
|
+
* ```typescript
|
|
676
|
+
* commands().startRecording({
|
|
677
|
+
* recordingName: 'support',
|
|
678
|
+
* destinationUrl: 's3://voice-recordings-prod/calls',
|
|
679
|
+
* credentials: {
|
|
680
|
+
* accessKeyId: process.env.RECORDING_KEY_ID!,
|
|
681
|
+
* secretAccessKey: process.env.RECORDING_SECRET!,
|
|
682
|
+
* region: 'eu-central-1',
|
|
683
|
+
* },
|
|
684
|
+
* transcribe: true,
|
|
685
|
+
* });
|
|
686
|
+
* ```
|
|
687
|
+
*/
|
|
688
|
+
startRecording(options) {
|
|
689
|
+
const events = {};
|
|
690
|
+
if (options.onFinish !== void 0) {
|
|
691
|
+
events.onFinish = resolveFlow(options.onFinish);
|
|
692
|
+
}
|
|
693
|
+
if (options.onFailure !== void 0) {
|
|
694
|
+
events.onFailure = resolveFlow(options.onFailure);
|
|
695
|
+
}
|
|
696
|
+
return this.push({
|
|
697
|
+
command: "startRecording",
|
|
698
|
+
...options.recordingName && { recordingName: options.recordingName },
|
|
699
|
+
recordingOptions: toRecordingOptions(options),
|
|
700
|
+
...Object.keys(events).length > 0 && { events }
|
|
701
|
+
});
|
|
702
|
+
}
|
|
703
|
+
/**
|
|
704
|
+
* Stop a named recording. Non-blocking.
|
|
705
|
+
*
|
|
706
|
+
* A recording started without a `recordingName` cannot be targeted at all — it ends when
|
|
707
|
+
* the call disconnects and not before.
|
|
708
|
+
*
|
|
709
|
+
* @param recordingName - Recording to stop (1-32 chars, no whitespace)
|
|
710
|
+
*/
|
|
711
|
+
stopRecording(recordingName) {
|
|
712
|
+
return this.push({ command: "stopRecording", recordingName });
|
|
713
|
+
}
|
|
714
|
+
/**
|
|
715
|
+
* Append a hand-built command — the escape hatch for anything not modelled here.
|
|
716
|
+
*
|
|
717
|
+
* @param commands - Commands to append, in order
|
|
718
|
+
*/
|
|
719
|
+
add(...commands2) {
|
|
720
|
+
return this.push(...commands2);
|
|
721
|
+
}
|
|
722
|
+
/**
|
|
723
|
+
* Emit the command list.
|
|
724
|
+
*
|
|
725
|
+
* Repeatable and non-consuming: the builder is a description of a flow, not a one-shot
|
|
726
|
+
* handle, so the same one can be sent twice or nested in two places.
|
|
727
|
+
*/
|
|
728
|
+
build() {
|
|
729
|
+
const out = [...this.list];
|
|
730
|
+
if (this.pending.length > 0) {
|
|
731
|
+
out.push({ command: "messages", messages: [...this.pending] });
|
|
732
|
+
}
|
|
733
|
+
return out;
|
|
734
|
+
}
|
|
735
|
+
push(...commands2) {
|
|
736
|
+
this.flush();
|
|
737
|
+
this.list.push(...commands2);
|
|
738
|
+
return this;
|
|
739
|
+
}
|
|
740
|
+
flush() {
|
|
741
|
+
if (this.pending.length > 0) {
|
|
742
|
+
const messages = { command: "messages", messages: this.pending.splice(0) };
|
|
743
|
+
this.list.push(messages);
|
|
744
|
+
}
|
|
745
|
+
}
|
|
746
|
+
};
|
|
747
|
+
function commands() {
|
|
748
|
+
return new CommandBuilder();
|
|
749
|
+
}
|
|
750
|
+
function sayMessage(text, options) {
|
|
751
|
+
return {
|
|
752
|
+
type: "SAY",
|
|
753
|
+
say: {
|
|
754
|
+
text,
|
|
755
|
+
voiceName: options.voiceName ?? DEFAULT_VOICE,
|
|
756
|
+
...options.format && { format: options.format }
|
|
757
|
+
}
|
|
758
|
+
};
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
// ../voice-v2-preview/dist/core/plan.js
|
|
762
|
+
function toCallRequest(plan) {
|
|
763
|
+
assertCommands(plan);
|
|
764
|
+
return { commands: plan.commands };
|
|
765
|
+
}
|
|
766
|
+
function toWebhookResponse(plan) {
|
|
767
|
+
assertCommands(plan);
|
|
768
|
+
const response = { commands: plan.commands };
|
|
769
|
+
if (plan.callName) {
|
|
770
|
+
response.callName = plan.callName;
|
|
771
|
+
}
|
|
772
|
+
if (plan.onHangup && plan.onHangup.length > 0) {
|
|
773
|
+
response.events = { onHangup: plan.onHangup };
|
|
774
|
+
}
|
|
775
|
+
return response;
|
|
776
|
+
}
|
|
777
|
+
function assertCommands(plan) {
|
|
778
|
+
if (!plan.commands || plan.commands.length === 0) {
|
|
779
|
+
throw new Error("Voice v2 plan requires at least one command. Build one with commands() \u2014 say(), play(), dial(), answer() or hangup() \u2014 or use call()/callWithStream()/bridge() on the client.");
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
// ../voice-v2-preview/dist/core/transfer.js
|
|
784
|
+
var DEFAULT_BRIDGE_NAME = "bridge";
|
|
785
|
+
var DEFAULT_TRANSFER_LEG = "transfer";
|
|
786
|
+
var DEFAULT_TRANSFER_TIMEOUT = 30;
|
|
787
|
+
function buildTransferCommands(to, options = {}) {
|
|
788
|
+
const bridgeName = options.bridgeName ?? DEFAULT_BRIDGE_NAME;
|
|
789
|
+
return commands().dial(to, {
|
|
790
|
+
callName: options.callName ?? DEFAULT_TRANSFER_LEG,
|
|
791
|
+
...options.from !== void 0 && { from: options.from },
|
|
792
|
+
timeout: options.timeout ?? DEFAULT_TRANSFER_TIMEOUT,
|
|
793
|
+
onAnswer: (c) => c.bridgeCall(bridgeName),
|
|
794
|
+
// Two legs, so both defaults are leg-aware rather than a bare hangup of this one.
|
|
795
|
+
...options.endLeg !== void 0 && {
|
|
796
|
+
endOnHangup: options.endLeg,
|
|
797
|
+
endOnFailure: options.endLeg
|
|
798
|
+
}
|
|
799
|
+
}).build();
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
// ../voice-v2-preview/dist/core/client.js
|
|
803
|
+
var ORIGIN_LEG = "origin";
|
|
804
|
+
var STREAM_LEG = "stream";
|
|
805
|
+
var RELAY_LEG = "relay";
|
|
806
|
+
var EVENT_MAP = {
|
|
807
|
+
"call.incoming": "incoming",
|
|
808
|
+
"call.answered": "answered",
|
|
809
|
+
"call.menu": "manage",
|
|
810
|
+
"call.hangup": "completed",
|
|
811
|
+
"call.failed": "completed"
|
|
812
|
+
};
|
|
813
|
+
function resolveHandlerKey(event) {
|
|
814
|
+
const name = stripLegacyPrefix(event);
|
|
815
|
+
if (name.startsWith(WEBHOOK_EVENT_PREFIX)) {
|
|
816
|
+
return "manage";
|
|
817
|
+
}
|
|
818
|
+
return EVENT_MAP[name];
|
|
819
|
+
}
|
|
820
|
+
var WEBHOOK_EVENT_PREFIX = "call.webhook.";
|
|
821
|
+
function stripLegacyPrefix(event) {
|
|
822
|
+
return event.startsWith("webhook.") ? event.slice("webhook.".length) : event;
|
|
823
|
+
}
|
|
824
|
+
function resolveWebhookName(event) {
|
|
825
|
+
const name = stripLegacyPrefix(event);
|
|
826
|
+
return name.startsWith(WEBHOOK_EVENT_PREFIX) ? name.slice(WEBHOOK_EVENT_PREFIX.length) || void 0 : void 0;
|
|
827
|
+
}
|
|
828
|
+
var Client = class {
|
|
829
|
+
publicUrl;
|
|
830
|
+
/**
|
|
831
|
+
* The lower layer, reached only through the interface this half of the module owns.
|
|
832
|
+
*
|
|
833
|
+
* This field and the `new HttpTransport` below are the whole coupling between the
|
|
834
|
+
* command builder and the network. When `@sinch/voice@2` ships, an adapter over the
|
|
835
|
+
* SDK replaces that one expression and nothing else in this file moves.
|
|
836
|
+
*/
|
|
837
|
+
transport;
|
|
838
|
+
/**
|
|
839
|
+
* @param context - Function context, used for env and for the public host
|
|
840
|
+
* @param options - Explicit overrides for anything the context cannot supply
|
|
841
|
+
*/
|
|
842
|
+
constructor(context, options = {}) {
|
|
843
|
+
const env = context?.env ?? process.env;
|
|
844
|
+
this.publicUrl = toWebSocketBase(options.publicUrl ?? context?.host);
|
|
845
|
+
this.transport = new HttpTransport({
|
|
846
|
+
projectId: options.projectId ?? env.PROJECT_ID ?? context?.config?.projectId ?? "",
|
|
847
|
+
keyId: options.keyId ?? env.PROJECT_ID_API_KEY ?? "",
|
|
848
|
+
keySecret: options.keySecret ?? env.PROJECT_ID_API_SECRET ?? "",
|
|
849
|
+
...options.host !== void 0 && { host: options.host },
|
|
850
|
+
...options.fetch !== void 0 && { fetch: options.fetch }
|
|
851
|
+
});
|
|
852
|
+
}
|
|
853
|
+
/**
|
|
854
|
+
* Place an outbound call.
|
|
855
|
+
*
|
|
856
|
+
* Name the events you want handled inline and they are sent as a **complete** block, with
|
|
857
|
+
* busy, rejected, timed-out and failed defaulting to hangup. Name none and no `events` key
|
|
858
|
+
* is sent at all, which is what hands the call to the service webhook.
|
|
859
|
+
*
|
|
860
|
+
* There is no half-way house, and that is the platform's rule rather than this client's:
|
|
861
|
+
* `events` present means the service webhook is attached to *none* of the six lists, so a
|
|
862
|
+
* lone `onAnswer` would silently stop busy and hangup from being handled by anything.
|
|
863
|
+
*
|
|
864
|
+
* @param to - Who to call
|
|
865
|
+
* @param options - Dial settings and named events
|
|
866
|
+
* @throws If the API rejects the request
|
|
867
|
+
*
|
|
868
|
+
* @example
|
|
869
|
+
* ```typescript
|
|
870
|
+
* // Inline: say a line and hang up, failures end the call
|
|
871
|
+
* await voice.call('+15559876543', {
|
|
872
|
+
* from: '+15551234567',
|
|
873
|
+
* onAnswer: (c) => c.say('Your appointment is confirmed.').hangup(),
|
|
874
|
+
* });
|
|
875
|
+
*
|
|
876
|
+
* // A flow built once and reused
|
|
877
|
+
* const greeting = commands().say('One moment').bridgeCall('support');
|
|
878
|
+
* await voice.call('+15559876543', { onAnswer: greeting });
|
|
879
|
+
*
|
|
880
|
+
* // Service-webhook mode: no events named, so `call.answered` fires
|
|
881
|
+
* await voice.call('+15559876543', { from: '+15551234567' });
|
|
882
|
+
* ```
|
|
883
|
+
*/
|
|
884
|
+
call(to, options = {}) {
|
|
885
|
+
return this.raw(toCallRequest(this.planCall(to, options)));
|
|
886
|
+
}
|
|
887
|
+
/**
|
|
888
|
+
* Build the {@link call} flow without sending it.
|
|
889
|
+
*
|
|
890
|
+
* @param to - Who to call
|
|
891
|
+
* @param options - Dial settings and named events
|
|
892
|
+
*/
|
|
893
|
+
planCall(to, options = {}) {
|
|
894
|
+
return {
|
|
895
|
+
commands: [
|
|
896
|
+
buildDial(toEndpoint(to), { ...options, callName: options.callName ?? ORIGIN_LEG })
|
|
897
|
+
]
|
|
898
|
+
};
|
|
899
|
+
}
|
|
900
|
+
/**
|
|
901
|
+
* Call a destination and put a WebSocket audio stream on the same call.
|
|
902
|
+
*
|
|
903
|
+
* Dials the destination as leg `origin`; on answer that leg joins a bridge and a
|
|
904
|
+
* second leg is dialled to the STREAM endpoint, which joins the same bridge.
|
|
905
|
+
* Either leg hanging up ends the other.
|
|
906
|
+
*
|
|
907
|
+
* `streamOptions` is always sent in full — the platform defaults to 44100 Hz
|
|
908
|
+
* when the object is omitted and to 8000 Hz when it is partially supplied.
|
|
909
|
+
*
|
|
910
|
+
* Both endpoints are positional, mirroring {@link bridge}: this dials two things and
|
|
911
|
+
* bridges them, and neither of them has a sensible default. In particular there is no
|
|
912
|
+
* honest default path for the audio leg — the runtime neither serves nor owns one — so
|
|
913
|
+
* the socket URL is as required as the number.
|
|
914
|
+
*
|
|
915
|
+
* @param to - Who to call
|
|
916
|
+
* @param stream - WebSocket endpoint for the audio leg. Either a full `ws://`/`wss://`
|
|
917
|
+
* URL or an absolute path, resolved against this function's public URL.
|
|
918
|
+
* @param options - Headers, sample rate, bridge name and dial settings
|
|
919
|
+
* @throws If the stream path cannot be resolved, or if the API rejects the request
|
|
920
|
+
*
|
|
921
|
+
* @example
|
|
922
|
+
* ```typescript
|
|
923
|
+
* // Relative path, resolved against the function's public host
|
|
924
|
+
* await voice.callWithStream('+15559876543', '/media', {
|
|
925
|
+
* from: '+15551234567',
|
|
926
|
+
* headers: { 'x-contact-id': 'abc123' },
|
|
927
|
+
* });
|
|
928
|
+
*
|
|
929
|
+
* // Full URL, 8 kHz to match a PSTN-only path
|
|
930
|
+
* await voice.callWithStream('+15559876543', 'wss://example.com/audio', {
|
|
931
|
+
* from: '+15551234567',
|
|
932
|
+
* sampleRate: 8000,
|
|
933
|
+
* });
|
|
934
|
+
* ```
|
|
935
|
+
*/
|
|
936
|
+
callWithStream(to, stream, options) {
|
|
937
|
+
return this.raw(toCallRequest(this.planStreamCall(to, stream, options)));
|
|
938
|
+
}
|
|
939
|
+
/**
|
|
940
|
+
* Build the {@link callWithStream} flow without sending it.
|
|
941
|
+
*
|
|
942
|
+
* @param to - Who to call
|
|
943
|
+
* @param stream - WebSocket endpoint for the audio leg, as a URL or an absolute path
|
|
944
|
+
* @param options - Headers, sample rate, bridge name and dial settings
|
|
945
|
+
* @throws If the stream path cannot be resolved
|
|
946
|
+
*/
|
|
947
|
+
planStreamCall(to, stream, options = {}) {
|
|
948
|
+
const headers = toCallHeaders(options.headers);
|
|
949
|
+
const streamEndpoint = {
|
|
950
|
+
type: "STREAM",
|
|
951
|
+
stream: {
|
|
952
|
+
endpoint: this.resolveStreamEndpoint(stream),
|
|
953
|
+
streamOptions: defaultStreamOptions(options.sampleRate),
|
|
954
|
+
...headers && { callHeaders: headers }
|
|
955
|
+
}
|
|
956
|
+
};
|
|
957
|
+
return this.planBridged(toEndpoint(to), streamEndpoint, STREAM_LEG, options);
|
|
958
|
+
}
|
|
959
|
+
/**
|
|
960
|
+
* Call a destination and put the Voice Relay service on the same call.
|
|
961
|
+
*
|
|
962
|
+
* Same topology as {@link callWithStream} — dial the human, bridge a second leg — but the
|
|
963
|
+
* second leg is a VOICE_RELAY endpoint rather than a raw audio socket: Sinch runs STT and
|
|
964
|
+
* TTS, and the application exchanges text. The trade is that the application never owns
|
|
965
|
+
* the TTS stream, which rules the relay out for anything that needs its own voice or
|
|
966
|
+
* needs to inject filler speech while an LLM thinks.
|
|
967
|
+
*
|
|
968
|
+
* The relay socket is positional and required: the `voiceRelay` schema (spec line 2946)
|
|
969
|
+
* requires `endpoint`, so there is no relay leg without one.
|
|
970
|
+
*
|
|
971
|
+
* @param to - Who to call
|
|
972
|
+
* @param relay - WebSocket endpoint the relay connects to. Either a full `ws://`/`wss://`
|
|
973
|
+
* URL or an absolute path, resolved against this function's public URL.
|
|
974
|
+
* @param options - Voice, transcription language, barge-in, bridge name and dial settings
|
|
975
|
+
* @throws If the API rejects the request
|
|
976
|
+
*/
|
|
977
|
+
callWithRelay(to, relay, options) {
|
|
978
|
+
return this.raw(toCallRequest(this.planRelayCall(to, relay, options)));
|
|
979
|
+
}
|
|
980
|
+
/**
|
|
981
|
+
* Build the {@link callWithRelay} flow without sending it.
|
|
982
|
+
*
|
|
983
|
+
* @param to - Who to call
|
|
984
|
+
* @param relay - WebSocket endpoint the relay connects to, as a URL or an absolute path
|
|
985
|
+
* @param options - Voice, transcription language, barge-in, bridge name and dial settings
|
|
986
|
+
*/
|
|
987
|
+
planRelayCall(to, relay, options = {}) {
|
|
988
|
+
const relayEndpoint = dialRelay(this.resolveStreamEndpoint(relay), {
|
|
989
|
+
...options.ttsVoice && { ttsVoice: options.ttsVoice },
|
|
990
|
+
...options.sttLanguage && { sttLanguage: options.sttLanguage },
|
|
991
|
+
...options.enableInterruptions !== void 0 && {
|
|
992
|
+
enableInterruptions: options.enableInterruptions
|
|
993
|
+
},
|
|
994
|
+
...options.headers && { headers: options.headers }
|
|
995
|
+
});
|
|
996
|
+
return this.planBridged(toEndpoint(to), relayEndpoint, RELAY_LEG, options);
|
|
997
|
+
}
|
|
998
|
+
/**
|
|
999
|
+
* Call two destinations and bridge them together.
|
|
1000
|
+
*
|
|
1001
|
+
* @param a - First party, dialled as leg `origin`
|
|
1002
|
+
* @param b - Second party, dialled once `a` answers
|
|
1003
|
+
* @param options - Dial settings and bridge name
|
|
1004
|
+
*
|
|
1005
|
+
* @example
|
|
1006
|
+
* ```typescript
|
|
1007
|
+
* await voice.bridge('+15551110000', '+15552220000', { from: '+15551234567' });
|
|
1008
|
+
* ```
|
|
1009
|
+
*/
|
|
1010
|
+
bridge(a, b, options = {}) {
|
|
1011
|
+
return this.raw(toCallRequest(this.planBridge(a, b, options)));
|
|
1012
|
+
}
|
|
1013
|
+
/**
|
|
1014
|
+
* Build the {@link bridge} flow without sending it.
|
|
1015
|
+
*
|
|
1016
|
+
* @param a - First party, dialled as leg `origin`
|
|
1017
|
+
* @param b - Second party, dialled once `a` answers
|
|
1018
|
+
* @param options - Dial settings and bridge name
|
|
1019
|
+
*/
|
|
1020
|
+
planBridge(a, b, options = {}) {
|
|
1021
|
+
return this.planBridged(toEndpoint(a), toEndpoint(b), "destination", options);
|
|
1022
|
+
}
|
|
1023
|
+
/**
|
|
1024
|
+
* End one or more legs of a live call.
|
|
1025
|
+
*
|
|
1026
|
+
* @param target - The live call, addressed by `callId` or by `sessionId` + `callName`
|
|
1027
|
+
* @param callNames - Legs to end. Ends the addressed leg when omitted.
|
|
1028
|
+
*
|
|
1029
|
+
* @example
|
|
1030
|
+
* ```typescript
|
|
1031
|
+
* await voice.hangup({ sessionId }, 'origin', 'stream');
|
|
1032
|
+
* ```
|
|
1033
|
+
*/
|
|
1034
|
+
hangup(target, ...callNames) {
|
|
1035
|
+
return this.patch(target, this.planHangup(...callNames));
|
|
1036
|
+
}
|
|
1037
|
+
/**
|
|
1038
|
+
* Build the {@link hangup} command list without sending it.
|
|
1039
|
+
*
|
|
1040
|
+
* @param callNames - Legs to end. Ends the addressed leg when omitted.
|
|
1041
|
+
*/
|
|
1042
|
+
planHangup(...callNames) {
|
|
1043
|
+
const flow = commands();
|
|
1044
|
+
if (callNames.length > 0) {
|
|
1045
|
+
for (const callName of callNames) {
|
|
1046
|
+
flow.hangup(callName);
|
|
1047
|
+
}
|
|
1048
|
+
} else {
|
|
1049
|
+
flow.hangup();
|
|
1050
|
+
}
|
|
1051
|
+
return flow.build();
|
|
1052
|
+
}
|
|
1053
|
+
/**
|
|
1054
|
+
* Run commands against a live call — the escalation path.
|
|
1055
|
+
*
|
|
1056
|
+
* @param target - The live call, addressed by `callId` or by `sessionId` + `callName`
|
|
1057
|
+
* @param flow - Commands to execute in the context of the addressed leg, in any
|
|
1058
|
+
* {@link Flow} spelling
|
|
1059
|
+
* @throws If the API rejects the request
|
|
1060
|
+
*
|
|
1061
|
+
* @example
|
|
1062
|
+
* ```typescript
|
|
1063
|
+
* // Pull a human agent into an in-progress streamed call
|
|
1064
|
+
* await voice.patch({ sessionId, callName: 'origin' }, (c) =>
|
|
1065
|
+
* c.bridgeCall('escalation').dial('+15550001111', {
|
|
1066
|
+
* callName: 'agent',
|
|
1067
|
+
* onAnswer: (a) => a.bridgeCall('escalation'),
|
|
1068
|
+
* endOnFailure: 'origin',
|
|
1069
|
+
* })
|
|
1070
|
+
* );
|
|
1071
|
+
* ```
|
|
1072
|
+
*/
|
|
1073
|
+
async patch(target, flow) {
|
|
1074
|
+
await this.transport.patchCall(target, resolveFlow(flow));
|
|
1075
|
+
}
|
|
1076
|
+
/**
|
|
1077
|
+
* Dial a party into a live call's bridge — the transfer v1 has no equivalent of.
|
|
1078
|
+
*
|
|
1079
|
+
* The named sugar over {@link patch}: it sends exactly
|
|
1080
|
+
* `patch(target, buildTransferCommands(to, options))`, and the value is entirely in what
|
|
1081
|
+
* that builder puts around the dial. See {@link buildTransferCommands} for why every
|
|
1082
|
+
* non-answer outcome has to end another leg.
|
|
1083
|
+
*
|
|
1084
|
+
* ### Why both a target and a bridge name
|
|
1085
|
+
*
|
|
1086
|
+
* They address different things and neither is redundant. {@link PatchTarget} pins the
|
|
1087
|
+
* **session** — by `callId`, or by `sessionId` plus the leg the commands run in the context
|
|
1088
|
+
* of. `bridgeName` then resolves **within** that session, because `bridgeCall` joins the
|
|
1089
|
+
* current call to a bridge "in the same session". That scoping is also what makes the
|
|
1090
|
+
* default safe: two unrelated calls both using `bridge` are in two different sessions, so
|
|
1091
|
+
* they cannot meet.
|
|
1092
|
+
*
|
|
1093
|
+
* The one genuinely ambiguous case is inside a single session: reuse a name for what you
|
|
1094
|
+
* meant as two bridges and you get one bridge, because joining a name that already exists
|
|
1095
|
+
* is documented to join it rather than create a second.
|
|
1096
|
+
*
|
|
1097
|
+
* @param target - The live call, addressed by `callId` or by `sessionId` + `callName`
|
|
1098
|
+
* @param to - Party to dial: an E.164 number, a `sip:` URI, or an endpoint object
|
|
1099
|
+
* @param options - Bridge, caller id, dial timeout, leg names
|
|
1100
|
+
* @throws If the API rejects the request
|
|
1101
|
+
*
|
|
1102
|
+
* @example
|
|
1103
|
+
* ```typescript
|
|
1104
|
+
* // A call placed by this client with default options: the bridge is already known
|
|
1105
|
+
* await voice.transfer({ sessionId, callName: 'origin' }, '+15550001111', {
|
|
1106
|
+
* endLeg: 'origin',
|
|
1107
|
+
* });
|
|
1108
|
+
*
|
|
1109
|
+
* // A call whose bridge was named, or one this package did not place
|
|
1110
|
+
* await voice.transfer({ callId }, 'sip:agent@pbx.example.com', {
|
|
1111
|
+
* bridgeName: 'agent',
|
|
1112
|
+
* endLeg: 'stream',
|
|
1113
|
+
* });
|
|
1114
|
+
* ```
|
|
1115
|
+
*/
|
|
1116
|
+
transfer(target, to, options = {}) {
|
|
1117
|
+
return this.patch(target, buildTransferCommands(to, options));
|
|
1118
|
+
}
|
|
1119
|
+
/**
|
|
1120
|
+
* Post a call-create body verbatim — the escape hatch for anything this client
|
|
1121
|
+
* does not model.
|
|
1122
|
+
*
|
|
1123
|
+
* The body type is deliberately permissive rather than the `callRequest` shape: the wire
|
|
1124
|
+
* command types are internal to this module, so anything hand-built here is unchecked by
|
|
1125
|
+
* design. Use {@link toCallRequest} on a plan when you want the shape validated.
|
|
1126
|
+
*
|
|
1127
|
+
* @param body - A `callRequest` body, or any object the API accepts
|
|
1128
|
+
* @throws If the API rejects the request
|
|
1129
|
+
*/
|
|
1130
|
+
raw(body) {
|
|
1131
|
+
return this.transport.createCall(body);
|
|
1132
|
+
}
|
|
1133
|
+
/**
|
|
1134
|
+
* Build a webhook dispatcher over the v2 call lifecycle.
|
|
1135
|
+
*
|
|
1136
|
+
* Handlers may return a plan, a command builder, a bare command array, or nothing.
|
|
1137
|
+
* Nothing means "no commands" and yields `undefined`, which a handler should
|
|
1138
|
+
* turn into a `204`.
|
|
1139
|
+
*
|
|
1140
|
+
* @param handlers - Handlers keyed by lifecycle stage
|
|
1141
|
+
* @returns A function that maps a webhook payload to a response body
|
|
1142
|
+
*
|
|
1143
|
+
* @example
|
|
1144
|
+
* ```typescript
|
|
1145
|
+
* export const handleVoiceWebhook = voice.onCall({
|
|
1146
|
+
* incoming: () => commands().answer().say('Thanks for calling').hangup(),
|
|
1147
|
+
* completed: (event) => {
|
|
1148
|
+
* console.log('call ended', event.call.callId);
|
|
1149
|
+
* },
|
|
1150
|
+
* });
|
|
1151
|
+
* ```
|
|
1152
|
+
*/
|
|
1153
|
+
onCall(handlers) {
|
|
1154
|
+
return async (event) => {
|
|
1155
|
+
const webhookName = resolveWebhookName(event.event);
|
|
1156
|
+
const key = resolveHandlerKey(event.event);
|
|
1157
|
+
const handler = webhookName && handlers.webhooks?.[webhookName] || key && handlers[key] || handlers.fallback;
|
|
1158
|
+
if (!handler) {
|
|
1159
|
+
return void 0;
|
|
1160
|
+
}
|
|
1161
|
+
const result = await handler(event);
|
|
1162
|
+
if (!result) {
|
|
1163
|
+
return void 0;
|
|
1164
|
+
}
|
|
1165
|
+
const plan = Array.isArray(result) || result instanceof CommandBuilder ? { commands: resolveFlow(result) } : result;
|
|
1166
|
+
return toWebhookResponse(plan);
|
|
1167
|
+
};
|
|
1168
|
+
}
|
|
1169
|
+
// ============================================
|
|
1170
|
+
// Internals
|
|
1171
|
+
// ============================================
|
|
1172
|
+
/**
|
|
1173
|
+
* The bridged shape: dial one leg, and on answer join a bridge and dial the second into it.
|
|
1174
|
+
*
|
|
1175
|
+
* The leg-aware defaults live here because this is where the topology is known. The second
|
|
1176
|
+
* leg names the first in both `endOnHangup` and `endOnFailure` — every way it can fail ends
|
|
1177
|
+
* the first one too, or `callWithStream` strands the human on a bridge with nothing on the
|
|
1178
|
+
* other side, and a stream-first plan leaves an answered WebSocket leg (with its billed
|
|
1179
|
+
* STT/TTS/LLM sockets) running to the platform's 14400-second ceiling talking to nobody.
|
|
1180
|
+
*
|
|
1181
|
+
* The first leg names the second in `endOnHangup` only. Its failure events fire *before*
|
|
1182
|
+
* the second leg has been dialled, so naming it there would target a leg that does not
|
|
1183
|
+
* exist; a bare hangup is the leg-aware answer for the first leg of a call.
|
|
1184
|
+
*/
|
|
1185
|
+
planBridged(first, second, secondLeg, options) {
|
|
1186
|
+
const bridgeName = options.bridgeName ?? DEFAULT_BRIDGE_NAME;
|
|
1187
|
+
const secondDial = buildDial(second, {
|
|
1188
|
+
...options,
|
|
1189
|
+
callName: secondLeg,
|
|
1190
|
+
onAnswer: (c) => c.bridgeCall(bridgeName),
|
|
1191
|
+
endOnHangup: ORIGIN_LEG,
|
|
1192
|
+
endOnFailure: ORIGIN_LEG
|
|
1193
|
+
});
|
|
1194
|
+
const originDial = buildDial(first, {
|
|
1195
|
+
...options,
|
|
1196
|
+
callName: ORIGIN_LEG,
|
|
1197
|
+
onAnswer: (c) => c.bridgeCall(bridgeName).add(secondDial),
|
|
1198
|
+
endOnHangup: secondLeg
|
|
1199
|
+
});
|
|
1200
|
+
return { commands: [originDial] };
|
|
1201
|
+
}
|
|
1202
|
+
resolveStreamEndpoint(stream) {
|
|
1203
|
+
if (/^wss?:\/\//i.test(stream)) {
|
|
1204
|
+
return stream;
|
|
1205
|
+
}
|
|
1206
|
+
if (!stream.startsWith("/")) {
|
|
1207
|
+
throw new Error(`Stream endpoint '${stream}' must be a ws:// or wss:// URL, or an absolute path such as '/stream'.`);
|
|
1208
|
+
}
|
|
1209
|
+
if (!this.publicUrl) {
|
|
1210
|
+
throw new Error(`Cannot resolve stream path '${stream}' \u2014 this function's public URL is unknown. Pass a full wss:// URL, or set the publicUrl option (context.host is only present in production).`);
|
|
1211
|
+
}
|
|
1212
|
+
return `${this.publicUrl}${stream}`;
|
|
1213
|
+
}
|
|
1214
|
+
};
|
|
1215
|
+
function createClient(context, options) {
|
|
1216
|
+
return new Client(context, options);
|
|
1217
|
+
}
|
|
1218
|
+
function toWebSocketBase(base) {
|
|
1219
|
+
if (!base) {
|
|
1220
|
+
return void 0;
|
|
1221
|
+
}
|
|
1222
|
+
const trimmed = base.replace(/\/$/, "");
|
|
1223
|
+
if (/^wss?:\/\//i.test(trimmed)) {
|
|
1224
|
+
return trimmed;
|
|
1225
|
+
}
|
|
1226
|
+
if (/^https:\/\//i.test(trimmed)) {
|
|
1227
|
+
return `wss://${trimmed.slice("https://".length)}`;
|
|
1228
|
+
}
|
|
1229
|
+
if (/^http:\/\//i.test(trimmed)) {
|
|
1230
|
+
return `ws://${trimmed.slice("http://".length)}`;
|
|
1231
|
+
}
|
|
1232
|
+
return `wss://${trimmed}`;
|
|
1233
|
+
}
|
|
1234
|
+
export {
|
|
1235
|
+
Client,
|
|
1236
|
+
CommandBuilder,
|
|
1237
|
+
DEFAULT_BRIDGE_NAME,
|
|
1238
|
+
DEFAULT_HOST,
|
|
1239
|
+
DEFAULT_SAMPLE_RATE,
|
|
1240
|
+
DEFAULT_STT_LANGUAGE,
|
|
1241
|
+
DEFAULT_TRANSFER_LEG,
|
|
1242
|
+
DEFAULT_VOICE,
|
|
1243
|
+
MenuItemBuilder,
|
|
1244
|
+
PromptBuilder,
|
|
1245
|
+
REDACTED,
|
|
1246
|
+
buildTransferCommands,
|
|
1247
|
+
commands,
|
|
1248
|
+
createClient,
|
|
1249
|
+
dialPhone,
|
|
1250
|
+
dialRelay,
|
|
1251
|
+
dialSip,
|
|
1252
|
+
dialStream,
|
|
1253
|
+
redactCredentials,
|
|
1254
|
+
resolveHandlerKey,
|
|
1255
|
+
resolveWebhookName,
|
|
1256
|
+
toCallRequest,
|
|
1257
|
+
toWebhookResponse
|
|
1258
|
+
};
|
|
1259
|
+
//# sourceMappingURL=v2.js.map
|