@jambonz/sdk 0.1.0 → 0.1.2

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.
Files changed (122) hide show
  1. package/dist/client/index.cjs +60 -13
  2. package/dist/client/index.cjs.map +1 -1
  3. package/dist/client/index.d.cts +36 -7
  4. package/dist/client/index.d.ts +36 -7
  5. package/dist/client/index.js +59 -13
  6. package/dist/client/index.js.map +1 -1
  7. package/dist/common-BSJZX7WO.d.cts +34 -0
  8. package/dist/common-BSJZX7WO.d.ts +34 -0
  9. package/dist/index.cjs +364 -32
  10. package/dist/index.cjs.map +1 -1
  11. package/dist/index.d.cts +8 -7
  12. package/dist/index.d.ts +8 -7
  13. package/dist/index.js +360 -32
  14. package/dist/index.js.map +1 -1
  15. package/dist/rest-BF9HKZrA.d.ts +136 -0
  16. package/dist/rest-v8weIueZ.d.cts +136 -0
  17. package/dist/session-DHc6G_9y.d.cts +112 -0
  18. package/dist/session-DHc6G_9y.d.ts +112 -0
  19. package/dist/types/index.d.cts +4 -3
  20. package/dist/types/index.d.ts +4 -3
  21. package/dist/{verb-builder-But-DJle.d.cts → verb-builder-Dg_IPC4I.d.ts} +35 -2
  22. package/dist/{verb-builder-CO_qoYxC.d.ts → verb-builder-DkHAJrk4.d.cts} +35 -2
  23. package/dist/{verbs-B_afNNUM.d.cts → verbs-fjJjfGEt.d.cts} +40 -14
  24. package/dist/{verbs-B_afNNUM.d.ts → verbs-fjJjfGEt.d.ts} +40 -14
  25. package/dist/webhook/index.cjs +68 -8
  26. package/dist/webhook/index.cjs.map +1 -1
  27. package/dist/webhook/index.d.cts +45 -3
  28. package/dist/webhook/index.d.ts +45 -3
  29. package/dist/webhook/index.js +68 -9
  30. package/dist/webhook/index.js.map +1 -1
  31. package/dist/websocket/index.cjs +291 -19
  32. package/dist/websocket/index.cjs.map +1 -1
  33. package/dist/websocket/index.d.cts +198 -4
  34. package/dist/websocket/index.d.ts +198 -4
  35. package/dist/websocket/index.js +290 -20
  36. package/dist/websocket/index.js.map +1 -1
  37. package/package.json +19 -6
  38. package/schema/callbacks/base.schema.json +29 -0
  39. package/schema/callbacks/call-status.schema.json +22 -0
  40. package/schema/callbacks/conference-status.schema.json +24 -0
  41. package/schema/callbacks/conference-wait.schema.json +11 -0
  42. package/schema/callbacks/conference.schema.json +11 -0
  43. package/schema/callbacks/dequeue.schema.json +19 -0
  44. package/schema/callbacks/dial-dtmf.schema.json +18 -0
  45. package/schema/callbacks/dial-hold.schema.json +22 -0
  46. package/schema/callbacks/dial-refer.schema.json +28 -0
  47. package/schema/callbacks/dial.schema.json +31 -0
  48. package/schema/callbacks/enqueue-wait.schema.json +17 -0
  49. package/schema/callbacks/enqueue.schema.json +27 -0
  50. package/schema/callbacks/gather-partial.schema.json +54 -0
  51. package/schema/callbacks/gather.schema.json +60 -0
  52. package/schema/callbacks/listen.schema.json +21 -0
  53. package/schema/callbacks/llm.schema.json +30 -0
  54. package/schema/callbacks/message.schema.json +35 -0
  55. package/schema/callbacks/play.schema.json +36 -0
  56. package/schema/callbacks/session-new.schema.json +143 -0
  57. package/schema/callbacks/session-reconnect.schema.json +9 -0
  58. package/schema/callbacks/session-redirect.schema.json +38 -0
  59. package/schema/callbacks/sip-refer-event.schema.json +20 -0
  60. package/schema/callbacks/sip-refer.schema.json +22 -0
  61. package/schema/callbacks/sip-request.schema.json +27 -0
  62. package/schema/callbacks/transcribe-translation.schema.json +24 -0
  63. package/schema/callbacks/transcribe.schema.json +46 -0
  64. package/schema/callbacks/verb-status.schema.json +57 -0
  65. package/schema/components/actionHook.schema.json +36 -0
  66. package/schema/components/actionHookDelayAction.schema.json +37 -0
  67. package/schema/components/amd.schema.json +68 -0
  68. package/schema/components/auth.schema.json +18 -0
  69. package/schema/components/bidirectionalAudio.schema.json +22 -0
  70. package/schema/components/fillerNoise.schema.json +25 -0
  71. package/schema/components/recognizer-assemblyAiOptions.schema.json +35 -0
  72. package/schema/components/recognizer-awsOptions.schema.json +52 -0
  73. package/schema/components/recognizer-azureOptions.schema.json +32 -0
  74. package/schema/components/recognizer-cobaltOptions.schema.json +34 -0
  75. package/schema/components/recognizer-customOptions.schema.json +27 -0
  76. package/schema/components/recognizer-deepgramOptions.schema.json +147 -0
  77. package/schema/components/recognizer-elevenlabsOptions.schema.json +39 -0
  78. package/schema/components/recognizer-gladiaOptions.schema.json +8 -0
  79. package/schema/components/recognizer-googleOptions.schema.json +35 -0
  80. package/schema/components/recognizer-houndifyOptions.schema.json +53 -0
  81. package/schema/components/recognizer-ibmOptions.schema.json +54 -0
  82. package/schema/components/recognizer-nuanceOptions.schema.json +150 -0
  83. package/schema/components/recognizer-nvidiaOptions.schema.json +39 -0
  84. package/schema/components/recognizer-openaiOptions.schema.json +59 -0
  85. package/schema/components/recognizer-sonioxOptions.schema.json +46 -0
  86. package/schema/components/recognizer-speechmaticsOptions.schema.json +91 -0
  87. package/schema/components/recognizer-verbioOptions.schema.json +46 -0
  88. package/schema/components/recognizer.schema.json +212 -0
  89. package/schema/components/synthesizer.schema.json +82 -0
  90. package/schema/components/target.schema.json +105 -0
  91. package/schema/components/vad.schema.json +48 -0
  92. package/schema/jambonz-app.schema.json +106 -0
  93. package/schema/verbs/alert.schema.json +20 -0
  94. package/schema/verbs/answer.schema.json +12 -0
  95. package/schema/verbs/conference.schema.json +43 -0
  96. package/schema/verbs/config.schema.json +170 -0
  97. package/schema/verbs/dequeue.schema.json +36 -0
  98. package/schema/verbs/dial.schema.json +153 -0
  99. package/schema/verbs/dtmf.schema.json +27 -0
  100. package/schema/verbs/dub.schema.json +52 -0
  101. package/schema/verbs/enqueue.schema.json +38 -0
  102. package/schema/verbs/gather.schema.json +145 -0
  103. package/schema/verbs/hangup.schema.json +29 -0
  104. package/schema/verbs/leave.schema.json +12 -0
  105. package/schema/verbs/listen.schema.json +109 -0
  106. package/schema/verbs/llm.schema.json +131 -0
  107. package/schema/verbs/message.schema.json +30 -0
  108. package/schema/verbs/pause.schema.json +26 -0
  109. package/schema/verbs/pipeline.schema.json +61 -0
  110. package/schema/verbs/play.schema.json +69 -0
  111. package/schema/verbs/redirect.schema.json +23 -0
  112. package/schema/verbs/say.schema.json +84 -0
  113. package/schema/verbs/sip-decline.schema.json +31 -0
  114. package/schema/verbs/sip-refer.schema.json +41 -0
  115. package/schema/verbs/sip-request.schema.json +33 -0
  116. package/schema/verbs/stream.schema.json +30 -0
  117. package/schema/verbs/tag.schema.json +21 -0
  118. package/schema/verbs/transcribe.schema.json +48 -0
  119. package/dist/common-Bsqv1Brz.d.cts +0 -69
  120. package/dist/common-Bsqv1Brz.d.ts +0 -69
  121. package/dist/rest-BV_FsqnH.d.cts +0 -97
  122. package/dist/rest-CthGXHnw.d.ts +0 -97
@@ -10,13 +10,31 @@ import { fileURLToPath } from 'url';
10
10
  var COMPONENT_SCHEMAS = [
11
11
  "auth",
12
12
  "actionHook",
13
- "synthesizer",
14
- "recognizer",
15
- "target",
16
- "vad",
13
+ "actionHookDelayAction",
14
+ "amd",
17
15
  "bidirectionalAudio",
18
16
  "fillerNoise",
19
- "actionHookDelayAction"
17
+ "recognizer",
18
+ "recognizer-assemblyAiOptions",
19
+ "recognizer-awsOptions",
20
+ "recognizer-azureOptions",
21
+ "recognizer-cobaltOptions",
22
+ "recognizer-customOptions",
23
+ "recognizer-deepgramOptions",
24
+ "recognizer-elevenlabsOptions",
25
+ "recognizer-gladiaOptions",
26
+ "recognizer-googleOptions",
27
+ "recognizer-houndifyOptions",
28
+ "recognizer-ibmOptions",
29
+ "recognizer-nuanceOptions",
30
+ "recognizer-nvidiaOptions",
31
+ "recognizer-openaiOptions",
32
+ "recognizer-sonioxOptions",
33
+ "recognizer-speechmaticsOptions",
34
+ "recognizer-verbioOptions",
35
+ "synthesizer",
36
+ "target",
37
+ "vad"
20
38
  ];
21
39
  var VERB_SCHEMAS = [
22
40
  "answer",
@@ -54,9 +72,9 @@ function findSchemaDir() {
54
72
  const currentDir = typeof __dirname !== "undefined" ? __dirname : dirname(fileURLToPath(import.meta.url));
55
73
  const candidates = [
56
74
  resolve(currentDir, "../../schema"),
57
- // from src/
58
- resolve(currentDir, "../../../schema")
59
- // from dist/
75
+ // from typescript/src/
76
+ resolve(currentDir, "../schema")
77
+ // from dist/ (tsup bundles to package-root/dist/)
60
78
  ];
61
79
  for (const candidate of candidates) {
62
80
  try {
@@ -119,6 +137,9 @@ function formatErrors(errors) {
119
137
  var VerbBuilder = class {
120
138
  verbs = [];
121
139
  validator;
140
+ /**
141
+ * @param opts - Options for validation and schema directory.
142
+ */
122
143
  constructor(opts) {
123
144
  if (opts?.validate === false) {
124
145
  this.validator = null;
@@ -127,85 +148,111 @@ var VerbBuilder = class {
127
148
  }
128
149
  }
129
150
  // --- Audio & Speech ---
151
+ /** Speak text using TTS. Supports SSML, multiple voices, and streaming. */
130
152
  say(opts) {
131
153
  return this.addVerb({ verb: "say", ...opts });
132
154
  }
155
+ /** Play an audio file from a URL. */
133
156
  play(opts) {
134
157
  return this.addVerb({ verb: "play", ...opts });
135
158
  }
159
+ /** Collect speech (STT) and/or DTMF input from the caller. */
136
160
  gather(opts) {
137
161
  return this.addVerb({ verb: "gather", ...opts });
138
162
  }
139
163
  // --- AI & Real-time ---
164
+ /** Connect the caller to an LLM for real-time voice conversation. */
140
165
  llm(opts) {
141
166
  return this.addVerb({ verb: "llm", ...opts });
142
167
  }
168
+ /** Voice AI pipeline with integrated turn detection. */
143
169
  pipeline(opts) {
144
170
  return this.addVerb({ verb: "pipeline", ...opts });
145
171
  }
172
+ /** Stream real-time call audio to a WebSocket endpoint. Supports bidirectional audio. */
146
173
  listen(opts) {
147
174
  return this.addVerb({ verb: "listen", ...opts });
148
175
  }
176
+ /** Stream real-time call audio to a WebSocket endpoint. Synonym for {@link listen}. */
149
177
  stream(opts) {
150
178
  return this.addVerb({ verb: "stream", ...opts });
151
179
  }
180
+ /** Real-time call transcription sent to a webhook. */
152
181
  transcribe(opts) {
153
182
  return this.addVerb({ verb: "transcribe", ...opts });
154
183
  }
155
184
  // --- Call Control ---
185
+ /** Place an outbound call and bridge it to the current caller. */
156
186
  dial(opts) {
157
187
  return this.addVerb({ verb: "dial", ...opts });
158
188
  }
189
+ /** Join or create a multi-party conference room. */
159
190
  conference(opts) {
160
191
  return this.addVerb({ verb: "conference", ...opts });
161
192
  }
193
+ /** Place the caller into a named queue. */
162
194
  enqueue(opts) {
163
195
  return this.addVerb({ verb: "enqueue", ...opts });
164
196
  }
197
+ /** Remove a caller from a queue and bridge them. */
165
198
  dequeue(opts) {
166
199
  return this.addVerb({ verb: "dequeue", ...opts });
167
200
  }
201
+ /** End the call. */
168
202
  hangup(opts) {
169
203
  return this.addVerb({ verb: "hangup", ...opts });
170
204
  }
205
+ /** Transfer control to a different webhook URL. */
171
206
  redirect(opts) {
172
207
  return this.addVerb({ verb: "redirect", ...opts });
173
208
  }
209
+ /** Wait for a specified duration before continuing. */
174
210
  pause(opts) {
175
211
  return this.addVerb({ verb: "pause", ...opts });
176
212
  }
213
+ /** Leave a conference or queue. */
177
214
  leave(opts) {
178
215
  return this.addVerb({ verb: "leave", ...opts });
179
216
  }
180
217
  // --- SIP ---
218
+ /** Reject an incoming call with a SIP error response. */
181
219
  sipDecline(opts) {
182
220
  return this.addVerb({ verb: "sip:decline", ...opts });
183
221
  }
222
+ /** Send a SIP INFO or other request within the dialog. */
184
223
  sipRequest(opts) {
185
224
  return this.addVerb({ verb: "sip:request", ...opts });
186
225
  }
226
+ /** Transfer the call via SIP REFER. */
187
227
  sipRefer(opts) {
188
228
  return this.addVerb({ verb: "sip:refer", ...opts });
189
229
  }
190
230
  // --- Utility ---
231
+ /** Set session-level defaults (TTS vendor/voice, STT vendor, VAD, etc.). */
191
232
  config(opts) {
192
233
  return this.addVerb({ verb: "config", ...opts });
193
234
  }
235
+ /** Explicitly answer the call (sends a 200 OK). */
194
236
  answer(opts) {
195
237
  return this.addVerb({ verb: "answer", ...opts });
196
238
  }
239
+ /** Send a SIP 180 Ringing with optional Alert-Info header. */
197
240
  alert(opts) {
198
241
  return this.addVerb({ verb: "alert", ...opts });
199
242
  }
243
+ /** Attach metadata to the call for tracking or routing. */
200
244
  tag(opts) {
201
245
  return this.addVerb({ verb: "tag", ...opts });
202
246
  }
247
+ /** Send DTMF tones into the call. */
203
248
  dtmf(opts) {
204
249
  return this.addVerb({ verb: "dtmf", ...opts });
205
250
  }
251
+ /** Mix an auxiliary audio track into the call. */
206
252
  dub(opts) {
207
253
  return this.addVerb({ verb: "dub", ...opts });
208
254
  }
255
+ /** Send an SMS or MMS message. */
209
256
  message(opts) {
210
257
  return this.addVerb({ verb: "message", ...opts });
211
258
  }
@@ -254,8 +301,23 @@ var VerbBuilder = class {
254
301
 
255
302
  // src/websocket/session.ts
256
303
  var Session = class extends EventEmitter {
304
+ /** Unique call identifier. */
257
305
  callSid;
306
+ /** Caller phone number or SIP URI. */
307
+ from;
308
+ /** Called phone number or SIP URI. */
309
+ to;
310
+ /** Call direction. */
311
+ direction;
312
+ /** Account identifier. */
313
+ accountSid;
314
+ /** Application identifier. */
315
+ applicationSid;
316
+ /** SIP Call-ID. */
317
+ callId;
318
+ /** Distributed trace header (B3 format), if present. */
258
319
  b3;
320
+ /** Full call session data from jambonz (includes env_vars, SIP headers, etc.). */
259
321
  data;
260
322
  /** Application-specific storage that persists for the session. */
261
323
  locals = {};
@@ -267,14 +329,21 @@ var Session = class extends EventEmitter {
267
329
  commandQueue = [];
268
330
  ttsCounter = 0;
269
331
  ttsPaused = false;
332
+ /** @internal */
270
333
  constructor(opts) {
271
334
  super();
272
335
  this.ws = opts.ws;
273
336
  this.logger = opts.logger;
274
337
  this.msgid = opts.msg.msgid;
275
- this.callSid = opts.msg.data?.call_sid ?? opts.msg.call_sid ?? "";
276
- this.b3 = opts.msg.b3;
277
338
  this.data = opts.msg.data ?? {};
339
+ this.callSid = this.data.call_sid ?? opts.msg.call_sid ?? "";
340
+ this.from = this.data.from ?? "";
341
+ this.to = this.data.to ?? "";
342
+ this.direction = this.data.direction ?? "inbound";
343
+ this.accountSid = this.data.account_sid ?? "";
344
+ this.applicationSid = this.data.application_sid ?? "";
345
+ this.callId = this.data.call_id ?? "";
346
+ this.b3 = opts.msg.b3;
278
347
  this.builder = new VerbBuilder({
279
348
  validate: opts.validate,
280
349
  schemaDir: opts.schemaDir
@@ -292,106 +361,132 @@ var Session = class extends EventEmitter {
292
361
  // ---------------------------------------------------------------------------
293
362
  // Verb builder delegation — same API as VerbBuilder
294
363
  // ---------------------------------------------------------------------------
364
+ /** Speak text using TTS. Supports SSML, multiple voices, and streaming. */
295
365
  say(opts) {
296
366
  this.builder.say(opts);
297
367
  return this;
298
368
  }
369
+ /** Play an audio file from a URL. */
299
370
  play(opts) {
300
371
  this.builder.play(opts);
301
372
  return this;
302
373
  }
374
+ /** Collect speech (STT) and/or DTMF input from the caller. */
303
375
  gather(opts) {
304
376
  this.builder.gather(opts);
305
377
  return this;
306
378
  }
379
+ /** Connect the caller to an LLM for real-time voice conversation. */
307
380
  llm(opts) {
308
381
  this.builder.llm(opts);
309
382
  return this;
310
383
  }
384
+ /** Voice AI pipeline with integrated turn detection. */
311
385
  pipeline(opts) {
312
386
  this.builder.pipeline(opts);
313
387
  return this;
314
388
  }
389
+ /** Stream real-time call audio to a WebSocket endpoint. Supports bidirectional audio. */
315
390
  listen(opts) {
316
391
  this.builder.listen(opts);
317
392
  return this;
318
393
  }
394
+ /** Stream real-time call audio to a WebSocket endpoint. Synonym for {@link listen}. */
319
395
  stream(opts) {
320
396
  this.builder.stream(opts);
321
397
  return this;
322
398
  }
399
+ /** Real-time call transcription sent to a webhook. */
323
400
  transcribe(opts) {
324
401
  this.builder.transcribe(opts);
325
402
  return this;
326
403
  }
404
+ /** Place an outbound call and bridge it to the current caller. */
327
405
  dial(opts) {
328
406
  this.builder.dial(opts);
329
407
  return this;
330
408
  }
409
+ /** Join or create a multi-party conference room. */
331
410
  conference(opts) {
332
411
  this.builder.conference(opts);
333
412
  return this;
334
413
  }
414
+ /** Place the caller into a named queue. */
335
415
  enqueue(opts) {
336
416
  this.builder.enqueue(opts);
337
417
  return this;
338
418
  }
419
+ /** Remove a caller from a queue and bridge them. */
339
420
  dequeue(opts) {
340
421
  this.builder.dequeue(opts);
341
422
  return this;
342
423
  }
424
+ /** End the call. */
343
425
  hangup(opts) {
344
426
  this.builder.hangup(opts);
345
427
  return this;
346
428
  }
429
+ /** Transfer control to a different webhook URL. */
347
430
  redirect(opts) {
348
431
  this.builder.redirect(opts);
349
432
  return this;
350
433
  }
434
+ /** Wait for a specified duration before continuing. */
351
435
  pause(opts) {
352
436
  this.builder.pause(opts);
353
437
  return this;
354
438
  }
439
+ /** Leave a conference or queue. */
355
440
  leave(opts) {
356
441
  this.builder.leave(opts);
357
442
  return this;
358
443
  }
444
+ /** Reject an incoming call with a SIP error response. */
359
445
  sipDecline(opts) {
360
446
  this.builder.sipDecline(opts);
361
447
  return this;
362
448
  }
449
+ /** Send a SIP INFO or other request within the dialog. */
363
450
  sipRequest(opts) {
364
451
  this.builder.sipRequest(opts);
365
452
  return this;
366
453
  }
454
+ /** Transfer the call via SIP REFER. */
367
455
  sipRefer(opts) {
368
456
  this.builder.sipRefer(opts);
369
457
  return this;
370
458
  }
459
+ /** Set session-level defaults (TTS vendor/voice, STT vendor, VAD, etc.). */
371
460
  config(opts) {
372
461
  this.builder.config(opts);
373
462
  return this;
374
463
  }
464
+ /** Explicitly answer the call (sends a 200 OK). */
375
465
  answer(opts) {
376
466
  this.builder.answer(opts);
377
467
  return this;
378
468
  }
469
+ /** Send a SIP 180 Ringing with optional Alert-Info header. */
379
470
  alert(opts) {
380
471
  this.builder.alert(opts);
381
472
  return this;
382
473
  }
474
+ /** Attach metadata to the call for tracking or routing. */
383
475
  tag(opts) {
384
476
  this.builder.tag(opts);
385
477
  return this;
386
478
  }
479
+ /** Send DTMF tones into the call. */
387
480
  dtmf(opts) {
388
481
  this.builder.dtmf(opts);
389
482
  return this;
390
483
  }
484
+ /** Mix an auxiliary audio track into the call. */
391
485
  dub(opts) {
392
486
  this.builder.dub(opts);
393
487
  return this;
394
488
  }
489
+ /** Send an SMS or MMS message. */
395
490
  message(opts) {
396
491
  this.builder.message(opts);
397
492
  return this;
@@ -445,18 +540,30 @@ var Session = class extends EventEmitter {
445
540
  this.wsSend(response);
446
541
  }
447
542
  // ---------------------------------------------------------------------------
543
+ // Verb status events
544
+ // ---------------------------------------------------------------------------
545
+ /**
546
+ * Enable real-time verb status events for this session.
547
+ * Once enabled, the session emits 'verb:status' events for verb lifecycle
548
+ * changes (starting, finished, start-playback, stop-playback, etc.).
549
+ *
550
+ * This is a convenience for `.config({ notifyEvents: true })` — it can be
551
+ * chained into the initial verb sequence or called at any time.
552
+ */
553
+ notifyEvents(enabled = true) {
554
+ this.builder.config({ notifyEvents: enabled });
555
+ return this;
556
+ }
557
+ // ---------------------------------------------------------------------------
448
558
  // Inject commands (immediate execution, bypass verb queue)
449
559
  // ---------------------------------------------------------------------------
450
560
  /** Send an inject command for immediate execution. */
451
561
  injectCommand(command, data, callSid) {
452
562
  this.wsSend({
453
563
  type: "command",
454
- command: "inject",
455
- data: {
456
- command,
457
- ...typeof data === "object" && data !== null ? data : {},
458
- ...callSid ? { call_sid: callSid } : {}
459
- }
564
+ command,
565
+ ...callSid ? { callSid } : {},
566
+ data: typeof data === "object" && data !== null ? data : {}
460
567
  });
461
568
  }
462
569
  /** Redirect call execution to a new webhook. */
@@ -465,7 +572,8 @@ var Session = class extends EventEmitter {
465
572
  }
466
573
  /** Inject a whisper verb (say/play) to one party on the call. */
467
574
  injectWhisper(verb, callSid) {
468
- this.injectCommand("whisper", Array.isArray(verb) ? verb : [verb], callSid);
575
+ const whisper = Array.isArray(verb) ? verb : [verb];
576
+ this.injectCommand("whisper", { whisper }, callSid);
469
577
  }
470
578
  /** Mute or unmute the call. */
471
579
  injectMute(status, callSid) {
@@ -641,6 +749,9 @@ var Session = class extends EventEmitter {
641
749
  } else if (data?.event_type === "user_interruption") {
642
750
  this.handleUserInterruption();
643
751
  }
752
+ if (data?.event_type) {
753
+ this.emit(`tts:${data.event_type}`, data);
754
+ }
644
755
  this.emit("tts:streaming-event", data);
645
756
  break;
646
757
  case "tts:tokens-result":
@@ -716,6 +827,132 @@ var WsClient = class extends EventEmitter {
716
827
  }
717
828
  }
718
829
  };
830
+ var AudioStream = class extends EventEmitter {
831
+ metadata;
832
+ callSid;
833
+ sampleRate;
834
+ ws;
835
+ logger;
836
+ constructor(ws, metadata, logger) {
837
+ super();
838
+ this.ws = ws;
839
+ this.logger = logger;
840
+ this.metadata = metadata;
841
+ this.callSid = metadata.callSid;
842
+ this.sampleRate = metadata.sampleRate;
843
+ ws.on("message", (data, isBinary) => {
844
+ if (isBinary) {
845
+ this.emit("audio", Buffer.from(data));
846
+ } else {
847
+ this.onTextMessage(data);
848
+ }
849
+ });
850
+ ws.on("close", (code, reason) => {
851
+ this.emit("close", code, reason.toString());
852
+ });
853
+ ws.on("error", (err) => {
854
+ this.emit("error", err);
855
+ });
856
+ }
857
+ /** Send raw L16 PCM audio back to the caller (streaming mode). */
858
+ sendAudio(pcm) {
859
+ if (this.ws.readyState === 1) {
860
+ this.ws.send(pcm);
861
+ }
862
+ }
863
+ /** Send a playAudio command with base64-encoded audio (non-streaming mode). */
864
+ playAudio(audioContent, opts) {
865
+ this.sendJson({
866
+ type: "playAudio",
867
+ data: {
868
+ audioContent,
869
+ audioContentType: opts?.audioContentType ?? "raw",
870
+ sampleRate: opts?.sampleRate ?? this.sampleRate,
871
+ ...opts?.id !== void 0 ? { id: opts.id } : {},
872
+ ...opts?.queuePlay !== void 0 ? { queuePlay: opts.queuePlay } : {}
873
+ }
874
+ });
875
+ }
876
+ /** Stop any currently playing audio and flush the buffer. */
877
+ killAudio() {
878
+ this.sendJson({ type: "killAudio" });
879
+ }
880
+ /** Tell jambonz to close the connection and end the listen verb. */
881
+ disconnect() {
882
+ this.sendJson({ type: "disconnect" });
883
+ }
884
+ /** Insert a synchronization marker. */
885
+ sendMark(name) {
886
+ this.sendJson({ type: "mark", data: { name } });
887
+ }
888
+ /** Clear all pending markers. */
889
+ clearMarks() {
890
+ this.sendJson({ type: "clearMarks" });
891
+ }
892
+ /** Close the WebSocket connection. */
893
+ close() {
894
+ this.ws.close();
895
+ }
896
+ onTextMessage(raw) {
897
+ try {
898
+ const str = typeof raw === "string" ? raw : Buffer.from(raw).toString("utf-8");
899
+ const msg = JSON.parse(str);
900
+ if (msg.event === "dtmf") {
901
+ this.emit("dtmf", { digit: msg.dtmf, duration: msg.duration });
902
+ return;
903
+ }
904
+ switch (msg.type) {
905
+ case "playDone":
906
+ this.emit("playDone", msg.data ?? {});
907
+ break;
908
+ case "mark":
909
+ this.emit("mark", msg.data ?? {});
910
+ break;
911
+ default:
912
+ this.logger.debug({ msg }, "AudioStream: unhandled text message");
913
+ }
914
+ } catch (err) {
915
+ this.logger.info({ err }, "AudioStream: error parsing text message");
916
+ }
917
+ }
918
+ sendJson(msg) {
919
+ if (this.ws.readyState === 1) {
920
+ this.ws.send(JSON.stringify(msg));
921
+ }
922
+ }
923
+ };
924
+
925
+ // src/websocket/audio-client.ts
926
+ var AudioClient = class extends EventEmitter {
927
+ logger;
928
+ path;
929
+ constructor(logger, path) {
930
+ super();
931
+ this.logger = logger;
932
+ this.path = path;
933
+ }
934
+ /** Handle a new audio WebSocket connection. */
935
+ handle(ws, req) {
936
+ const onFirstMessage = (data, isBinary) => {
937
+ ws.removeListener("message", onFirstMessage);
938
+ if (isBinary) {
939
+ this.logger.info("AudioClient: expected JSON metadata as first message, got binary");
940
+ ws.close();
941
+ return;
942
+ }
943
+ try {
944
+ const raw = typeof data === "string" ? data : Buffer.from(data).toString("utf-8");
945
+ const metadata = JSON.parse(raw);
946
+ const stream = new AudioStream(ws, metadata, this.logger);
947
+ this.emit("connection", stream, req);
948
+ } catch (err) {
949
+ this.logger.info({ err }, "AudioClient: error parsing initial metadata");
950
+ ws.close();
951
+ }
952
+ };
953
+ ws.on("message", onFirstMessage);
954
+ }
955
+ };
719
956
 
720
957
  // src/websocket/router.ts
721
958
  var WsRouter = class {
@@ -753,6 +990,7 @@ var WsRouter = class {
753
990
 
754
991
  // src/websocket/endpoint.ts
755
992
  var WS_PROTOCOL = "ws.jambonz.org";
993
+ var AUDIO_PROTOCOL = "audio.drachtio.org";
756
994
  var defaultLogger = {
757
995
  info: () => {
758
996
  },
@@ -762,7 +1000,7 @@ var defaultLogger = {
762
1000
  }
763
1001
  };
764
1002
  function createEndpoint(opts) {
765
- const { server, port, logger = defaultLogger, middlewares = [] } = opts;
1003
+ const { server, port, logger = defaultLogger, middlewares = [], envVars } = opts;
766
1004
  const router = new WsRouter();
767
1005
  const wss = new WebSocketServer({
768
1006
  noServer: true,
@@ -771,6 +1009,23 @@ function createEndpoint(opts) {
771
1009
  return false;
772
1010
  }
773
1011
  });
1012
+ const audioWss = new WebSocketServer({
1013
+ noServer: true,
1014
+ handleProtocols: (protocols) => {
1015
+ if (protocols.has(AUDIO_PROTOCOL)) return AUDIO_PROTOCOL;
1016
+ return false;
1017
+ }
1018
+ });
1019
+ const audioRoutes = /* @__PURE__ */ new Map();
1020
+ server.on("request", (req, res) => {
1021
+ if (req.method === "OPTIONS" && envVars) {
1022
+ res.writeHead(200, { "Content-Type": "application/json" });
1023
+ res.end(JSON.stringify(envVars));
1024
+ return;
1025
+ }
1026
+ res.writeHead(426, { "Content-Type": "text/plain" });
1027
+ res.end("Upgrade Required");
1028
+ });
774
1029
  server.on("upgrade", (req, socket, head) => {
775
1030
  const fakeRes = new http.ServerResponse(req);
776
1031
  runMiddlewares(middlewares, req, fakeRes, (err) => {
@@ -779,6 +1034,14 @@ function createEndpoint(opts) {
779
1034
  socket.destroy();
780
1035
  return;
781
1036
  }
1037
+ const pathname = req.url?.split("?")[0] ?? "/";
1038
+ const audioClient = audioRoutes.get(pathname);
1039
+ if (audioClient) {
1040
+ audioWss.handleUpgrade(req, socket, head, (ws) => {
1041
+ audioClient.handle(ws, req);
1042
+ });
1043
+ return;
1044
+ }
782
1045
  const client = router.route(req);
783
1046
  if (!client) {
784
1047
  logger.debug({ url: req.url }, "Endpoint: no route for WebSocket upgrade");
@@ -793,11 +1056,18 @@ function createEndpoint(opts) {
793
1056
  if (port && !server.listening) {
794
1057
  server.listen(port);
795
1058
  }
796
- return function makeService({ path }) {
1059
+ const makeService = function makeService2({ path }) {
797
1060
  const client = new WsClient(logger, path);
798
1061
  router.use(path, client);
799
1062
  return client;
800
1063
  };
1064
+ makeService.audio = function audio({ path }) {
1065
+ const normalized = path.startsWith("/") ? path : `/${path}`;
1066
+ const client = new AudioClient(logger, normalized);
1067
+ audioRoutes.set(normalized, client);
1068
+ return client;
1069
+ };
1070
+ return makeService;
801
1071
  }
802
1072
  function runMiddlewares(middlewares, req, res, done) {
803
1073
  let i = 0;
@@ -817,6 +1087,6 @@ function runMiddlewares(middlewares, req, res, done) {
817
1087
  next();
818
1088
  }
819
1089
 
820
- export { Session, WsClient, WsRouter, createEndpoint };
1090
+ export { AudioClient, AudioStream, Session, WsClient, WsRouter, createEndpoint };
821
1091
  //# sourceMappingURL=index.js.map
822
1092
  //# sourceMappingURL=index.js.map