@signalwire/sdk 2.0.0 → 2.0.1

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 (75) hide show
  1. package/package.json +1 -1
  2. package/src/AgentBase.ts +113 -4
  3. package/src/AgentServer.ts +31 -4
  4. package/src/ContextBuilder.ts +33 -2
  5. package/src/DataMap.ts +30 -2
  6. package/src/FunctionResult.ts +40 -3
  7. package/src/PomBuilder.ts +29 -1
  8. package/src/SWMLService.ts +38 -6
  9. package/src/ServerlessAdapter.ts +20 -1
  10. package/src/SwmlBuilder.ts +26 -1
  11. package/src/TypeInference.ts +27 -9
  12. package/src/WebService.ts +27 -5
  13. package/src/index.ts +73 -7
  14. package/src/livewire/index.ts +343 -41
  15. package/src/prefabs/ConciergeAgent.ts +22 -0
  16. package/src/prefabs/FAQBotAgent.ts +32 -1
  17. package/src/prefabs/InfoGathererAgent.ts +41 -1
  18. package/src/prefabs/ReceptionistAgent.ts +30 -1
  19. package/src/prefabs/SurveyAgent.ts +26 -1
  20. package/src/relay/Action.ts +174 -6
  21. package/src/relay/Call.ts +459 -43
  22. package/src/relay/Deferred.ts +27 -4
  23. package/src/relay/Message.ts +54 -3
  24. package/src/relay/RelayClient.ts +167 -18
  25. package/src/relay/RelayError.ts +7 -1
  26. package/src/relay/RelayEvent.ts +52 -0
  27. package/src/rest/HttpClient.ts +61 -0
  28. package/src/rest/RestError.ts +14 -0
  29. package/src/rest/base/BaseResource.ts +16 -3
  30. package/src/rest/base/CrudResource.ts +52 -5
  31. package/src/rest/base/CrudWithAddresses.ts +12 -1
  32. package/src/rest/index.ts +30 -0
  33. package/src/rest/namespaces/addresses.ts +33 -1
  34. package/src/rest/namespaces/calling.ts +348 -1
  35. package/src/rest/namespaces/chat.ts +13 -2
  36. package/src/rest/namespaces/compat.ts +469 -9
  37. package/src/rest/namespaces/datasphere.ts +48 -5
  38. package/src/rest/namespaces/fabric.ts +197 -2
  39. package/src/rest/namespaces/imported-numbers.ts +13 -2
  40. package/src/rest/namespaces/logs.ts +68 -1
  41. package/src/rest/namespaces/lookup.ts +19 -2
  42. package/src/rest/namespaces/mfa.ts +35 -4
  43. package/src/rest/namespaces/number-groups.ts +35 -5
  44. package/src/rest/namespaces/phone-numbers.ts +35 -3
  45. package/src/rest/namespaces/project.ts +30 -1
  46. package/src/rest/namespaces/pubsub.ts +13 -2
  47. package/src/rest/namespaces/queues.ts +29 -4
  48. package/src/rest/namespaces/recordings.ts +26 -1
  49. package/src/rest/namespaces/registry.ts +100 -1
  50. package/src/rest/namespaces/short-codes.ts +27 -1
  51. package/src/rest/namespaces/sip-profile.ts +18 -3
  52. package/src/rest/namespaces/verified-callers.ts +22 -3
  53. package/src/rest/namespaces/video.ts +168 -1
  54. package/src/rest/pagination.ts +22 -8
  55. package/src/skills/SkillBase.ts +37 -2
  56. package/src/skills/SkillManager.ts +8 -4
  57. package/src/skills/builtin/api_ninjas_trivia.ts +5 -0
  58. package/src/skills/builtin/ask_claude.ts +5 -0
  59. package/src/skills/builtin/claude_skills.ts +5 -0
  60. package/src/skills/builtin/custom_skills.ts +15 -0
  61. package/src/skills/builtin/datasphere.ts +9 -0
  62. package/src/skills/builtin/datasphere_serverless.ts +8 -0
  63. package/src/skills/builtin/datetime.ts +7 -0
  64. package/src/skills/builtin/google_maps.ts +5 -0
  65. package/src/skills/builtin/info_gatherer.ts +10 -0
  66. package/src/skills/builtin/joke.ts +5 -0
  67. package/src/skills/builtin/math.ts +7 -0
  68. package/src/skills/builtin/mcp_gateway.ts +8 -0
  69. package/src/skills/builtin/native_vector_search.ts +9 -0
  70. package/src/skills/builtin/play_background_file.ts +9 -0
  71. package/src/skills/builtin/spider.ts +5 -0
  72. package/src/skills/builtin/swml_transfer.ts +10 -0
  73. package/src/skills/builtin/weather_api.ts +7 -0
  74. package/src/skills/builtin/web_search.ts +9 -0
  75. package/src/skills/builtin/wikipedia_search.ts +5 -0
@@ -4,16 +4,32 @@
4
4
  * Uses a manual promise constructor for Node 18+ compatibility.
5
5
  */
6
6
 
7
+ /**
8
+ * A promise with externalised `resolve`/`reject` and a `settled` flag,
9
+ * used by the RELAY client to bridge server-push events back to in-flight
10
+ * JSON-RPC request callers.
11
+ */
7
12
  export interface Deferred<T> {
13
+ /** The wrapped promise. */
8
14
  promise: Promise<T>;
15
+ /** Resolve the promise idempotently (later calls are ignored). */
9
16
  resolve: (value: T | PromiseLike<T>) => void;
17
+ /** Reject the promise idempotently (later calls are ignored). */
10
18
  reject: (reason?: unknown) => void;
19
+ /** True once either `resolve` or `reject` has been called. */
11
20
  readonly settled: boolean;
12
21
  }
13
22
 
14
23
  /**
15
- * Create a Deferred<T> with externalized resolve/reject and a settled flag.
16
- * The `settled` property is true once resolve() or reject() has been called.
24
+ * Create a {@link Deferred} with externalised `resolve` / `reject` and a
25
+ * `settled` flag.
26
+ *
27
+ * The returned object exposes the promise plus its resolve and reject
28
+ * functions so callers outside the executor can settle it. Later calls to
29
+ * `resolve` or `reject` are idempotent.
30
+ *
31
+ * @typeParam T - Resolution value type of the wrapped promise.
32
+ * @returns A fresh `Deferred<T>` in pending state.
17
33
  */
18
34
  export function createDeferred<T>(): Deferred<T> {
19
35
  let _resolve!: (value: T | PromiseLike<T>) => void;
@@ -44,8 +60,15 @@ export function createDeferred<T>(): Deferred<T> {
44
60
  }
45
61
 
46
62
  /**
47
- * Race a promise against a timeout. Rejects with an Error if the timeout
48
- * expires before the promise settles.
63
+ * Race a promise against a timeout.
64
+ *
65
+ * @typeParam T - Resolution value type of the input promise.
66
+ * @param promise - Promise to race against the timeout.
67
+ * @param ms - Timeout in milliseconds.
68
+ * @param label - Label used in the timeout error message. Defaults to
69
+ * `"Operation"`.
70
+ * @returns A new promise that resolves with `promise`'s value if it settles
71
+ * before the timeout, and rejects with a timeout `Error` otherwise.
49
72
  */
50
73
  export function withTimeout<T>(
51
74
  promise: Promise<T>,
@@ -14,17 +14,47 @@ import type { CompletedCallback, EventHandler } from './types.js';
14
14
 
15
15
  const logger = getLogger('relay_message');
16
16
 
17
+ /**
18
+ * SMS/MMS message in the RELAY messaging namespace.
19
+ *
20
+ * Outbound messages progress through `queued` → `initiated` → `sent` → `delivered`
21
+ * (or `undelivered` / `failed`). Inbound messages arrive with state `received`.
22
+ * Call {@link Message.wait} to await a terminal state.
23
+ *
24
+ * @example Wait for delivery confirmation
25
+ * ```ts
26
+ * const msg = await client.sendMessage({
27
+ * to: '+15551234567',
28
+ * from: '+15557654321',
29
+ * body: 'Your code is 4242',
30
+ * });
31
+ *
32
+ * const final = await msg.wait(30); // seconds
33
+ * console.log('Final state:', final.params.message_state);
34
+ * ```
35
+ */
17
36
  export class Message {
37
+ /** Unique message identifier assigned by the platform. */
18
38
  messageId: string;
39
+ /** RELAY context the message belongs to. */
19
40
  context: string;
41
+ /** `"inbound"` or `"outbound"`. */
20
42
  direction: string;
43
+ /** Sender phone number in E.164 format. */
21
44
  fromNumber: string;
45
+ /** Destination phone number in E.164 format. */
22
46
  toNumber: string;
47
+ /** Plain-text message body. */
23
48
  body: string;
49
+ /** Media URLs attached to the message (MMS). */
24
50
  media: string[];
51
+ /** Number of segments the carrier split the message into. */
25
52
  segments: number;
53
+ /** Current message state (e.g. `"sent"`, `"delivered"`, `"failed"`). */
26
54
  state: string;
55
+ /** Failure / undelivery reason when `state` is non-successful. */
27
56
  reason: string;
57
+ /** Opaque tags attached to the message. */
28
58
  tags: string[];
29
59
 
30
60
  private _done: Deferred<RelayEvent>;
@@ -58,10 +88,12 @@ export class Message {
58
88
  this._done = createDeferred<RelayEvent>();
59
89
  }
60
90
 
91
+ /** True once the message has reached a terminal state. */
61
92
  get isDone(): boolean {
62
93
  return this._done.settled;
63
94
  }
64
95
 
96
+ /** Final event that terminated the message, or `null` if still in-flight. */
65
97
  get result(): RelayEvent | null {
66
98
  // We can't synchronously get the result from a promise, so we track it
67
99
  return this._result ?? null;
@@ -69,14 +101,27 @@ export class Message {
69
101
 
70
102
  private _result: RelayEvent | undefined;
71
103
 
72
- /** Register an event listener for state changes on this message. */
104
+ /**
105
+ * Register an event listener for state changes on this message.
106
+ *
107
+ * The handler fires every time the server emits a `messaging.state` event
108
+ * for this message (multiple listeners are supported). Listener errors are
109
+ * logged but do not disrupt dispatch.
110
+ *
111
+ * @param handler - Callback invoked for each state-change event.
112
+ */
73
113
  on(handler: EventHandler): void {
74
114
  this._listeners.push(handler);
75
115
  }
76
116
 
77
117
  /**
78
- * Wait for the message to reach a terminal state.
79
- * @param timeout - Maximum time to wait in seconds (matches Python SDK convention).
118
+ * Wait for the message to reach a terminal state (`delivered`, `failed`,
119
+ * `undelivered`, etc.).
120
+ *
121
+ * @param timeout - Maximum time to wait in **seconds** (matches the Python
122
+ * SDK convention — not milliseconds).
123
+ * @returns The final `messaging.state` {@link RelayEvent}.
124
+ * @throws {Error} When the optional timeout elapses before a terminal state.
80
125
  */
81
126
  async wait(timeout?: number): Promise<RelayEvent> {
82
127
  if (timeout != null) {
@@ -142,6 +187,12 @@ export class Message {
142
187
  }
143
188
  }
144
189
 
190
+ /**
191
+ * Return a human-readable diagnostic string.
192
+ *
193
+ * @returns `Message(id=..., direction=..., state=..., from=..., to=...)` —
194
+ * handy for log output.
195
+ */
145
196
  toString(): string {
146
197
  return `Message(id=${this.messageId}, direction=${this.direction}, state=${this.state}, from=${this.fromNumber}, to=${this.toNumber})`;
147
198
  }
@@ -84,11 +84,57 @@ type WsLike = {
84
84
  ping?(data?: any, mask?: boolean, cb?: (err: Error) => void): void;
85
85
  };
86
86
 
87
+ /**
88
+ * Real-time WebSocket client for SignalWire RELAY.
89
+ *
90
+ * One instance = one persistent JSON-RPC 2.0 WebSocket connection. Lets you
91
+ * place / receive calls and SMS, play/record media, run TTS, conference calls
92
+ * together, and subscribe to platform events — all without HTTP polling.
93
+ *
94
+ * Authentication supports either a project/token pair or a JWT.
95
+ *
96
+ * @example Inbound-call handler
97
+ * ```ts
98
+ * import { RelayClient } from '@signalwire/sdk';
99
+ *
100
+ * const client = new RelayClient({
101
+ * project: process.env.SIGNALWIRE_PROJECT_ID!,
102
+ * token: process.env.SIGNALWIRE_API_TOKEN!,
103
+ * host: 'example.signalwire.com',
104
+ * contexts: ['office'],
105
+ * });
106
+ *
107
+ * client.onCall(async (call) => {
108
+ * await call.answer();
109
+ * await call.playTTS({ text: 'Thanks for calling!' });
110
+ * await call.hangup();
111
+ * });
112
+ *
113
+ * await client.connect();
114
+ * ```
115
+ *
116
+ * @example Outbound dial + SMS
117
+ * ```ts
118
+ * await client.connect();
119
+ * const call = await client.dial({
120
+ * devices: [[{ type: 'phone', to: '+15551234567', from: '+15557654321' }]],
121
+ * });
122
+ * await client.sendMessage({ to: '+15551234567', from: '+15557654321', body: 'Hi!' });
123
+ * ```
124
+ *
125
+ * @see {@link Call}
126
+ * @see {@link Message}
127
+ */
87
128
  export class RelayClient {
129
+ /** Project ID used for Basic Auth. */
88
130
  readonly project: string;
131
+ /** API token used for Basic Auth. */
89
132
  readonly token: string;
133
+ /** JWT used instead of project/token if provided. */
90
134
  readonly jwtToken: string;
135
+ /** Hostname of the RELAY endpoint (e.g. `example.signalwire.com`). */
91
136
  readonly host: string;
137
+ /** Contexts this client subscribes to for inbound events. */
92
138
  readonly contexts: string[];
93
139
 
94
140
  private _ws: WsLike | null = null;
@@ -127,6 +173,12 @@ export class RelayClient {
127
173
  */
128
174
  _wsFactory: ((url: string) => WsLike) | null = null;
129
175
 
176
+ /**
177
+ * Create a new RELAY client.
178
+ * Credentials fall back to the `SIGNALWIRE_PROJECT_ID`, `SIGNALWIRE_API_TOKEN`,
179
+ * `SIGNALWIRE_JWT_TOKEN`, and `SIGNALWIRE_SPACE` env vars when omitted.
180
+ * @param options - Optional client configuration.
181
+ */
130
182
  constructor(options: RelayClientOptions = {}) {
131
183
  this.project = options.project ?? process.env.SIGNALWIRE_PROJECT_ID ?? '';
132
184
  this.token = options.token ?? process.env.SIGNALWIRE_API_TOKEN ?? '';
@@ -158,6 +210,7 @@ export class RelayClient {
158
210
  }
159
211
  }
160
212
 
213
+ /** The protocol name the server assigned to this client after `connect()`. */
161
214
  get relayProtocol(): string {
162
215
  return this._relayProtocol;
163
216
  }
@@ -185,13 +238,32 @@ export class RelayClient {
185
238
 
186
239
  // ─── Handler Registration ──────────────────────────────────────
187
240
 
188
- /** Register the inbound call handler. Returns the handler to support decorator usage. */
241
+ /**
242
+ * Register the inbound call handler.
243
+ *
244
+ * The handler is invoked once per inbound call, with a fully-formed
245
+ * {@link Call} already in state `"created"`. Answer, reject, or forward
246
+ * the call from inside the handler.
247
+ *
248
+ * @param handler - Callback invoked for each inbound call. May return a
249
+ * promise; errors are logged but do not tear down the client.
250
+ * @returns The same handler, to support decorator-style usage.
251
+ */
189
252
  onCall(handler: CallHandler): CallHandler {
190
253
  this._onCallHandler = handler;
191
254
  return handler;
192
255
  }
193
256
 
194
- /** Register the inbound message handler. Returns the handler to support decorator usage. */
257
+ /**
258
+ * Register the inbound message handler.
259
+ *
260
+ * The handler is invoked once per inbound SMS/MMS delivered to a subscribed
261
+ * context, with a {@link Message} already in state `"received"`.
262
+ *
263
+ * @param handler - Callback invoked for each inbound message. May return a
264
+ * promise; errors are logged but do not tear down the client.
265
+ * @returns The same handler, to support decorator-style usage.
266
+ */
195
267
  onMessage(handler: MessageHandler): MessageHandler {
196
268
  this._onMessageHandler = handler;
197
269
  return handler;
@@ -199,7 +271,18 @@ export class RelayClient {
199
271
 
200
272
  // ─── Connection Lifecycle ──────────────────────────────────────
201
273
 
202
- /** Connect to RELAY and authenticate. */
274
+ /**
275
+ * Connect to RELAY and authenticate.
276
+ *
277
+ * Opens the WebSocket, runs the JSON-RPC `signalwire.connect` handshake,
278
+ * and starts the client-side ping loop. Safe to call again after a
279
+ * `disconnect()` to reconnect; the process-wide concurrent-connection limit
280
+ * is enforced here.
281
+ *
282
+ * @returns Resolves once the client is connected and authenticated.
283
+ * @throws {Error} When the process-wide connection limit is reached,
284
+ * authentication fails, or the WebSocket cannot be opened.
285
+ */
203
286
  async connect(): Promise<void> {
204
287
  // Guard against connection leaks — enforce per-process limit.
205
288
  // Don't count ourselves (allows reconnect without double-counting).
@@ -318,7 +401,15 @@ export class RelayClient {
318
401
  logger.debug(`Auth response: protocol=${this._relayProtocol} identity=${this._identity}`);
319
402
  }
320
403
 
321
- /** Cleanly close the connection. */
404
+ /**
405
+ * Cleanly close the connection.
406
+ *
407
+ * Stops the ping loop, drops the WebSocket, rejects every pending request
408
+ * and dial with a `Connection closed` {@link RelayError}, and removes the
409
+ * client from the process-wide active set. Safe to call repeatedly.
410
+ *
411
+ * @returns Resolves once all resources have been released.
412
+ */
322
413
  async disconnect(): Promise<void> {
323
414
  this._closing = true;
324
415
  this._connected = false;
@@ -361,18 +452,40 @@ export class RelayClient {
361
452
 
362
453
  // ─── Public RPC Interface ──────────────────────────────────────
363
454
 
364
- /** Send a JSON-RPC request and await the response. */
455
+ /**
456
+ * Send a JSON-RPC request and await the response.
457
+ *
458
+ * This is the low-level escape hatch for calling RELAY methods that don't
459
+ * yet have a higher-level helper on this class. Queued if the client is
460
+ * currently disconnected; sent immediately otherwise.
461
+ *
462
+ * @param method - Fully-qualified JSON-RPC method name (e.g. `"calling.play"`).
463
+ * @param params - Method-specific params object.
464
+ * @returns The `result` field of the JSON-RPC response.
465
+ * @throws {RelayError} When the server returns a non-2xx code.
466
+ */
365
467
  async execute(method: string, params: Record<string, unknown>): Promise<Record<string, unknown>> {
366
468
  return this._sendRequest(method, params);
367
469
  }
368
470
 
369
471
  /**
370
- * Initiate an outbound call. Returns a Call when answered.
472
+ * Initiate an outbound call.
371
473
  *
372
- * @param devices - Array of device lists (serial/parallel dial).
373
- * @param options.tag - Client-provided tag for event correlation. Auto-generated if not supplied.
374
- * @param options.maxDuration - Optional max call duration in minutes.
375
- * @param options.dialTimeout - How long (seconds) to wait for the dial to complete. Defaults to 120.
474
+ * Accepts a "dial plan" — an outer array of serial groups, each containing
475
+ * an inner array of devices dialled in parallel. Resolves when any device
476
+ * answers; rejects if no device answers within `dialTimeout`.
477
+ *
478
+ * @param devices - Serial/parallel dial plan. `[[A], [B, C]]` dials A first,
479
+ * then B and C in parallel.
480
+ * @param options - Optional dial behaviour overrides.
481
+ * @param options.tag - Client-provided tag for event correlation.
482
+ * Auto-generated (UUID) when omitted.
483
+ * @param options.maxDuration - Maximum call duration in minutes.
484
+ * @param options.dialTimeout - Seconds to wait for the dial to complete.
485
+ * Defaults to `120`.
486
+ * @returns A {@link Call} representing the answered leg.
487
+ * @throws {Error} When the dial times out.
488
+ * @throws {RelayError} When the server rejects the dial request.
376
489
  */
377
490
  async dial(
378
491
  devices: Record<string, unknown>[][],
@@ -423,16 +536,25 @@ export class RelayClient {
423
536
  }
424
537
 
425
538
  /**
426
- * Send an outbound SMS/MMS message. Returns a Message.
539
+ * Send an outbound SMS / MMS message.
540
+ *
541
+ * The method returns as soon as the server has accepted the send; track the
542
+ * message's terminal state with {@link Message.wait} or the `onCompleted`
543
+ * callback.
427
544
  *
545
+ * @param options - Send parameters.
428
546
  * @param options.toNumber - Destination phone number in E.164 format.
429
547
  * @param options.fromNumber - Sender phone number in E.164 format.
430
- * @param options.context - Context for receiving state events. Defaults to the relay protocol.
548
+ * @param options.context - Context for receiving state events. Defaults to
549
+ * the negotiated relay protocol.
431
550
  * @param options.body - Text body of the message.
432
551
  * @param options.media - List of media URLs for MMS.
433
- * @param options.tags - Optional tags for the message.
434
- * @param options.region - Optional origination region.
435
- * @param options.onCompleted - Optional callback fired when a terminal state is reached.
552
+ * @param options.tags - Tags attached to the message for correlation.
553
+ * @param options.region - Origination region override.
554
+ * @param options.onCompleted - Optional callback fired when the message
555
+ * reaches a terminal state (delivered / failed / undelivered).
556
+ * @returns A {@link Message} tracking the outbound send.
557
+ * @throws {RelayError} When the server rejects the send request.
436
558
  */
437
559
  async sendMessage(options: {
438
560
  toNumber: string;
@@ -483,14 +605,30 @@ export class RelayClient {
483
605
  return message;
484
606
  }
485
607
 
486
- /** Subscribe to additional contexts. */
608
+ /**
609
+ * Subscribe to additional RELAY contexts on an already-connected client.
610
+ *
611
+ * Inbound calls and messages on any of the listed contexts will be delivered
612
+ * to the `onCall` / `onMessage` handlers. A no-op when `contexts` is empty.
613
+ *
614
+ * @param contexts - Context names to subscribe to.
615
+ * @returns Resolves once the server has confirmed the subscription.
616
+ * @throws {RelayError} When the server rejects the subscribe request.
617
+ */
487
618
  async receive(contexts: string[]): Promise<void> {
488
619
  if (!contexts.length) return;
489
620
  await this._sendRequest(METHOD_SIGNALWIRE_RECEIVE, { contexts });
490
621
  logger.info(`Subscribed to contexts: ${contexts}`);
491
622
  }
492
623
 
493
- /** Unsubscribe from contexts. */
624
+ /**
625
+ * Unsubscribe from contexts previously passed to {@link receive} (or the
626
+ * constructor). A no-op when `contexts` is empty.
627
+ *
628
+ * @param contexts - Context names to unsubscribe from.
629
+ * @returns Resolves once the server has confirmed the unsubscribe.
630
+ * @throws {RelayError} When the server rejects the unsubscribe request.
631
+ */
494
632
  async unreceive(contexts: string[]): Promise<void> {
495
633
  if (!contexts.length) return;
496
634
  await this._sendRequest(METHOD_SIGNALWIRE_UNRECEIVE, { contexts });
@@ -499,7 +637,18 @@ export class RelayClient {
499
637
 
500
638
  // ─── Run (auto-reconnect loop) ────────────────────────────────
501
639
 
502
- /** Blocking entry point — connects and maintains connection with auto-reconnect. */
640
+ /**
641
+ * Blocking entry point — connects and maintains the connection with
642
+ * auto-reconnect, returning only after a clean shutdown (Ctrl+C, SIGTERM,
643
+ * or {@link disconnect} from another scope).
644
+ *
645
+ * Installs `SIGINT` / `SIGTERM` handlers, so typically only one `RelayClient`
646
+ * per process should call `run()`.
647
+ *
648
+ * @returns Resolves once a shutdown has been requested and cleanup completes.
649
+ * @throws {Error} Only on unrecoverable startup failures — normal
650
+ * disconnects are handled internally by the reconnect loop.
651
+ */
503
652
  async run(): Promise<void> {
504
653
  this._closing = false;
505
654
  this._shutdownDeferred = createDeferred<void>();
@@ -1,11 +1,17 @@
1
1
  /**
2
2
  * Custom error class for RELAY protocol errors.
3
3
  *
4
- * Mirrors the Python SDK signature: `RelayError(code, message)`.
4
+ * Thrown when the server returns a non-2xx JSON-RPC result code. Mirrors the
5
+ * Python SDK signature: `RelayError(code, message)`.
5
6
  */
6
7
  export class RelayError extends Error {
8
+ /** Numeric RELAY result code returned by the server. */
7
9
  readonly code: number;
8
10
 
11
+ /**
12
+ * @param code - Numeric RELAY result code (e.g. `404`, `503`).
13
+ * @param message - Human-readable error message from the server.
14
+ */
9
15
  constructor(code: number, message: string) {
10
16
  super(`RELAY error ${code}: ${message}`);
11
17
  this.name = 'RelayError';
@@ -9,12 +9,30 @@
9
9
 
10
10
  // ─── Base Event ──────────────────────────────────────────────────────
11
11
 
12
+ /**
13
+ * Base class for all typed RELAY events.
14
+ *
15
+ * Raw events arrive as `signalwire.event` JSON-RPC notifications; the client
16
+ * looks up the correct subclass in {@link EVENT_CLASS_MAP} and invokes
17
+ * {@link RelayEvent.fromPayload} to build a typed wrapper. Handlers receive
18
+ * this wrapper; they can always read the original dict from `params`.
19
+ */
12
20
  export class RelayEvent {
21
+ /** Fully-qualified event type (e.g. `"calling.call.state"`). */
13
22
  readonly eventType: string;
23
+ /** Raw params dict from the RELAY notification. */
14
24
  readonly params: Record<string, any>;
25
+ /** Call ID associated with the event, or `""` for non-call events. */
15
26
  readonly callId: string;
27
+ /** Server timestamp (epoch seconds) at which the event was emitted. */
16
28
  readonly timestamp: number;
17
29
 
30
+ /**
31
+ * @param eventType - Fully-qualified event type.
32
+ * @param params - Raw event params dict.
33
+ * @param callId - Call ID (if applicable).
34
+ * @param timestamp - Server-side event timestamp.
35
+ */
18
36
  constructor(
19
37
  eventType: string,
20
38
  params: Record<string, any>,
@@ -27,6 +45,12 @@ export class RelayEvent {
27
45
  this.timestamp = timestamp;
28
46
  }
29
47
 
48
+ /**
49
+ * Factory that builds a typed event from a raw `signalwire.event` payload.
50
+ * Subclasses override this to populate their specialised fields; the base
51
+ * implementation returns a minimal `RelayEvent` used as the fallback for
52
+ * unrecognised event types.
53
+ */
30
54
  static fromPayload(payload: Record<string, any>): RelayEvent {
31
55
  const eventType = payload.event_type ?? '';
32
56
  const params = payload.params ?? {};
@@ -54,6 +78,7 @@ function baseFields(payload: Record<string, any>) {
54
78
 
55
79
  // ─── Call Events ─────────────────────────────────────────────────────
56
80
 
81
+ /** `calling.call.state` — fires on every lifecycle transition (created, ringing, answered, ending, ended). */
57
82
  export class CallStateEvent extends RelayEvent {
58
83
  readonly callState: string;
59
84
  readonly endReason: string;
@@ -89,6 +114,7 @@ export class CallStateEvent extends RelayEvent {
89
114
  }
90
115
  }
91
116
 
117
+ /** `calling.call.receive` — fires when an inbound call arrives on a subscribed context. */
92
118
  export class CallReceiveEvent extends RelayEvent {
93
119
  readonly callState: string;
94
120
  readonly direction: string;
@@ -140,6 +166,7 @@ export class CallReceiveEvent extends RelayEvent {
140
166
  }
141
167
  }
142
168
 
169
+ /** `calling.call.play` — play-media action state change (`playing`, `paused`, `finished`, `error`). */
143
170
  export class PlayEvent extends RelayEvent {
144
171
  readonly controlId: string;
145
172
  readonly state: string;
@@ -167,6 +194,7 @@ export class PlayEvent extends RelayEvent {
167
194
  }
168
195
  }
169
196
 
197
+ /** `calling.call.record` — recording state change with final URL, duration, and size when finished. */
170
198
  export class RecordEvent extends RelayEvent {
171
199
  readonly controlId: string;
172
200
  readonly state: string;
@@ -211,6 +239,7 @@ export class RecordEvent extends RelayEvent {
211
239
  }
212
240
  }
213
241
 
242
+ /** `calling.call.collect` — caller input (DTMF or speech) collected by a collect action. */
214
243
  export class CollectEvent extends RelayEvent {
215
244
  readonly controlId: string;
216
245
  readonly state: string;
@@ -246,6 +275,7 @@ export class CollectEvent extends RelayEvent {
246
275
  }
247
276
  }
248
277
 
278
+ /** `calling.call.connect` — state transition when one call connects to another (dialplan/bridge). */
249
279
  export class ConnectEvent extends RelayEvent {
250
280
  readonly connectState: string;
251
281
  readonly peer: Record<string, any>;
@@ -273,6 +303,7 @@ export class ConnectEvent extends RelayEvent {
273
303
  }
274
304
  }
275
305
 
306
+ /** `calling.call.detect` — answering-machine / fax / DTMF detection result. */
276
307
  export class DetectEvent extends RelayEvent {
277
308
  readonly controlId: string;
278
309
  readonly detect: Record<string, any>;
@@ -300,6 +331,7 @@ export class DetectEvent extends RelayEvent {
300
331
  }
301
332
  }
302
333
 
334
+ /** `calling.call.fax` — fax send/receive progress update. */
303
335
  export class FaxEvent extends RelayEvent {
304
336
  readonly controlId: string;
305
337
  readonly fax: Record<string, any>;
@@ -327,6 +359,7 @@ export class FaxEvent extends RelayEvent {
327
359
  }
328
360
  }
329
361
 
362
+ /** `calling.call.tap` — media tap state change (audio mirror to an external endpoint). */
330
363
  export class TapEvent extends RelayEvent {
331
364
  readonly controlId: string;
332
365
  readonly state: string;
@@ -362,6 +395,7 @@ export class TapEvent extends RelayEvent {
362
395
  }
363
396
  }
364
397
 
398
+ /** `calling.call.stream` — outbound media stream state change (e.g. RTMP/WebSocket streaming). */
365
399
  export class StreamEvent extends RelayEvent {
366
400
  readonly controlId: string;
367
401
  readonly state: string;
@@ -397,6 +431,7 @@ export class StreamEvent extends RelayEvent {
397
431
  }
398
432
  }
399
433
 
434
+ /** `calling.call.send_digits` — progress update for DTMF digits sent out on a call. */
400
435
  export class SendDigitsEvent extends RelayEvent {
401
436
  readonly controlId: string;
402
437
  readonly state: string;
@@ -424,6 +459,7 @@ export class SendDigitsEvent extends RelayEvent {
424
459
  }
425
460
  }
426
461
 
462
+ /** `calling.call.dial` — outbound dial progress (answered, failed, no-answer, etc.). */
427
463
  export class DialEvent extends RelayEvent {
428
464
  readonly tag: string;
429
465
  readonly dialState: string;
@@ -455,6 +491,7 @@ export class DialEvent extends RelayEvent {
455
491
  }
456
492
  }
457
493
 
494
+ /** `calling.call.refer` — SIP REFER result (off-platform transfer response codes). */
458
495
  export class ReferEvent extends RelayEvent {
459
496
  readonly state: string;
460
497
  readonly sipReferTo: string;
@@ -490,6 +527,7 @@ export class ReferEvent extends RelayEvent {
490
527
  }
491
528
  }
492
529
 
530
+ /** `calling.call.denoise` — noise-reduction on/off confirmation. */
493
531
  export class DenoiseEvent extends RelayEvent {
494
532
  readonly denoised: boolean;
495
533
 
@@ -513,6 +551,7 @@ export class DenoiseEvent extends RelayEvent {
513
551
  }
514
552
  }
515
553
 
554
+ /** `calling.call.pay` — PCI-compliant payment collection progress update. */
516
555
  export class PayEvent extends RelayEvent {
517
556
  readonly controlId: string;
518
557
  readonly state: string;
@@ -540,6 +579,7 @@ export class PayEvent extends RelayEvent {
540
579
  }
541
580
  }
542
581
 
582
+ /** `calling.call.queue` — call-queue position update (queued, waiting, member answered, timed out). */
543
583
  export class QueueEvent extends RelayEvent {
544
584
  readonly controlId: string;
545
585
  readonly status: string;
@@ -583,6 +623,7 @@ export class QueueEvent extends RelayEvent {
583
623
  }
584
624
  }
585
625
 
626
+ /** `calling.call.echo` — test/diagnostic echo reflection from the server. */
586
627
  export class EchoEvent extends RelayEvent {
587
628
  readonly state: string;
588
629
 
@@ -606,6 +647,7 @@ export class EchoEvent extends RelayEvent {
606
647
  }
607
648
  }
608
649
 
650
+ /** `calling.call.transcribe` — transcription state change and final URL/duration when finished. */
609
651
  export class TranscribeEvent extends RelayEvent {
610
652
  readonly controlId: string;
611
653
  readonly state: string;
@@ -649,6 +691,7 @@ export class TranscribeEvent extends RelayEvent {
649
691
  }
650
692
  }
651
693
 
694
+ /** `calling.call.hold` — hold/unhold state change on the call. */
652
695
  export class HoldEvent extends RelayEvent {
653
696
  readonly state: string;
654
697
 
@@ -672,6 +715,7 @@ export class HoldEvent extends RelayEvent {
672
715
  }
673
716
  }
674
717
 
718
+ /** `calling.conference` — conference lifecycle change (created, active, ended). */
675
719
  export class ConferenceEvent extends RelayEvent {
676
720
  readonly conferenceId: string;
677
721
  readonly name: string;
@@ -703,6 +747,7 @@ export class ConferenceEvent extends RelayEvent {
703
747
  }
704
748
  }
705
749
 
750
+ /** `calling.error` — platform-emitted error against the calling namespace. */
706
751
  export class CallingErrorEvent extends RelayEvent {
707
752
  readonly code: string;
708
753
  readonly message: string;
@@ -732,6 +777,7 @@ export class CallingErrorEvent extends RelayEvent {
732
777
 
733
778
  // ─── Messaging Events ────────────────────────────────────────────────
734
779
 
780
+ /** `messaging.receive` — inbound SMS/MMS received on a subscribed context. */
735
781
  export class MessageReceiveEvent extends RelayEvent {
736
782
  readonly messageId: string;
737
783
  readonly context: string;
@@ -791,6 +837,7 @@ export class MessageReceiveEvent extends RelayEvent {
791
837
  }
792
838
  }
793
839
 
840
+ /** `messaging.state` — state change for an outbound message (queued → sent → delivered/failed). */
794
841
  export class MessageStateEvent extends RelayEvent {
795
842
  readonly messageId: string;
796
843
  readonly context: string;
@@ -856,8 +903,13 @@ export class MessageStateEvent extends RelayEvent {
856
903
 
857
904
  // ─── Event Class Map & Parser ────────────────────────────────────────
858
905
 
906
+ /** Structural type for an event class that exposes a `fromPayload` factory. */
859
907
  export type EventClass = { fromPayload(payload: Record<string, any>): RelayEvent };
860
908
 
909
+ /**
910
+ * Maps RELAY `event_type` strings to the typed event subclass that builds
911
+ * its wrapper. Used by {@link parseEvent} to dispatch raw payloads.
912
+ */
861
913
  export const EVENT_CLASS_MAP: Record<string, EventClass> = {
862
914
  'calling.call.state': CallStateEvent,
863
915
  'calling.call.receive': CallReceiveEvent,