@siphon-project/control 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +155 -0
- package/dist/index.cjs +970 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +588 -0
- package/dist/index.d.ts +588 -0
- package/dist/index.js +943 -0
- package/dist/index.js.map +1 -0
- package/package.json +67 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,943 @@
|
|
|
1
|
+
import WebSocket, { WebSocketServer } from 'ws';
|
|
2
|
+
|
|
3
|
+
// src/errors.ts
|
|
4
|
+
var ControlError = class _ControlError extends Error {
|
|
5
|
+
/** The classification of this error. */
|
|
6
|
+
kind;
|
|
7
|
+
/** The stable wire code, present only for a `command` rejection. */
|
|
8
|
+
code;
|
|
9
|
+
/** The HTTP status of a rejected upgrade, present only for `unauthorized`. */
|
|
10
|
+
status;
|
|
11
|
+
constructor(kind, message, options) {
|
|
12
|
+
super(message);
|
|
13
|
+
this.name = "ControlError";
|
|
14
|
+
this.kind = kind;
|
|
15
|
+
this.code = options?.code;
|
|
16
|
+
this.status = options?.status;
|
|
17
|
+
Object.setPrototypeOf(this, _ControlError.prototype);
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* True when this is a server-side `unsupported_verb` rejection — the state a
|
|
21
|
+
* media verb (`playFile`/`dtmf`/…) lands in until the server implements it.
|
|
22
|
+
*/
|
|
23
|
+
isUnsupportedVerb() {
|
|
24
|
+
return this.kind === "command" && this.code === "unsupported_verb";
|
|
25
|
+
}
|
|
26
|
+
/** A server `status:"error"` reply. */
|
|
27
|
+
static command(code, message) {
|
|
28
|
+
return new _ControlError("command", `control command rejected (${code}): ${message}`, {
|
|
29
|
+
code
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
/** The WebSocket upgrade was rejected before it opened (bad/missing token). */
|
|
33
|
+
static unauthorized(status) {
|
|
34
|
+
return new _ControlError(
|
|
35
|
+
"unauthorized",
|
|
36
|
+
`unauthorized: the control token was rejected (HTTP ${status})`,
|
|
37
|
+
{ status }
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
/** The `hello` handshake (or subprotocol negotiation) failed. */
|
|
41
|
+
static handshake(detail) {
|
|
42
|
+
return new _ControlError("handshake", `handshake failed: ${detail}`);
|
|
43
|
+
}
|
|
44
|
+
/** The connection is closed (or was never established). */
|
|
45
|
+
static closed() {
|
|
46
|
+
return new _ControlError("closed", "control connection is closed");
|
|
47
|
+
}
|
|
48
|
+
/** A command was sent but no reply arrived within the configured window. */
|
|
49
|
+
static timeout(timeoutMs) {
|
|
50
|
+
return new _ControlError("timeout", `timed out awaiting a reply after ${timeoutMs}ms`);
|
|
51
|
+
}
|
|
52
|
+
/** A transport-level WebSocket error. */
|
|
53
|
+
static websocket(detail) {
|
|
54
|
+
return new _ControlError("websocket", `websocket error: ${detail}`);
|
|
55
|
+
}
|
|
56
|
+
/** A configuration value was invalid (bad URL, bad listen address, …). */
|
|
57
|
+
static config(detail) {
|
|
58
|
+
return new _ControlError("config", `configuration error: ${detail}`);
|
|
59
|
+
}
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
// src/protocol.ts
|
|
63
|
+
var SUBPROTOCOL = "siphon-control.v1";
|
|
64
|
+
var PROTOCOL_VERSION = 1;
|
|
65
|
+
var MODULE_SIP = "sip";
|
|
66
|
+
var MODULE_SMPP = "smpp";
|
|
67
|
+
var MODULE_SS7 = "ss7";
|
|
68
|
+
var HELLO = "hello";
|
|
69
|
+
var RESYNC = "resync";
|
|
70
|
+
var DESCRIBE = "describe";
|
|
71
|
+
var SET_VAR = "set_var";
|
|
72
|
+
var GET_VAR = "get_var";
|
|
73
|
+
function encodeCommand(id, module, verb, target, args) {
|
|
74
|
+
const frame = { id, type: "command" };
|
|
75
|
+
if (module != null) {
|
|
76
|
+
frame.module = module;
|
|
77
|
+
}
|
|
78
|
+
frame.verb = verb;
|
|
79
|
+
frame.target = target ?? null;
|
|
80
|
+
frame.args = args ?? null;
|
|
81
|
+
return JSON.stringify(frame);
|
|
82
|
+
}
|
|
83
|
+
function parseInboundFrame(text) {
|
|
84
|
+
let value;
|
|
85
|
+
try {
|
|
86
|
+
value = JSON.parse(text);
|
|
87
|
+
} catch {
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
if (typeof value !== "object" || value === null) {
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
const frameType = value.type;
|
|
94
|
+
if (frameType === "reply") {
|
|
95
|
+
return value;
|
|
96
|
+
}
|
|
97
|
+
if (frameType === "event") {
|
|
98
|
+
return value;
|
|
99
|
+
}
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
var SipVerb = {
|
|
103
|
+
Answer: "answer",
|
|
104
|
+
Progress: "progress",
|
|
105
|
+
Reject: "reject",
|
|
106
|
+
Hangup: "hangup",
|
|
107
|
+
Refer: "refer",
|
|
108
|
+
SetHeader: "set_header",
|
|
109
|
+
GetHeader: "get_header",
|
|
110
|
+
RemoveHeader: "remove_header",
|
|
111
|
+
AcceptRefer: "accept_refer",
|
|
112
|
+
RejectRefer: "reject_refer",
|
|
113
|
+
Play: "play",
|
|
114
|
+
Dtmf: "dtmf"
|
|
115
|
+
};
|
|
116
|
+
function sipEventKind(name) {
|
|
117
|
+
return name;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// src/internal.ts
|
|
121
|
+
var AsyncQueue = class {
|
|
122
|
+
items = [];
|
|
123
|
+
waiters = [];
|
|
124
|
+
closed = false;
|
|
125
|
+
/** Enqueue an item (or hand it directly to a waiting consumer). */
|
|
126
|
+
push(item) {
|
|
127
|
+
if (this.closed) {
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
const waiter = this.waiters.shift();
|
|
131
|
+
if (waiter) {
|
|
132
|
+
waiter(item);
|
|
133
|
+
} else {
|
|
134
|
+
this.items.push(item);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
/** Await the next item, or `null` once the queue is closed and drained. */
|
|
138
|
+
next() {
|
|
139
|
+
if (this.items.length > 0) {
|
|
140
|
+
return Promise.resolve(this.items.shift());
|
|
141
|
+
}
|
|
142
|
+
if (this.closed) {
|
|
143
|
+
return Promise.resolve(null);
|
|
144
|
+
}
|
|
145
|
+
return new Promise((resolve) => this.waiters.push(resolve));
|
|
146
|
+
}
|
|
147
|
+
/** Close the queue: pending and future `next()` calls resolve with `null`. */
|
|
148
|
+
close() {
|
|
149
|
+
if (this.closed) {
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
this.closed = true;
|
|
153
|
+
for (const waiter of this.waiters.splice(0)) {
|
|
154
|
+
waiter(null);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
/** Async-iterate the queue until it closes. */
|
|
158
|
+
async *[Symbol.asyncIterator]() {
|
|
159
|
+
for (; ; ) {
|
|
160
|
+
const item = await this.next();
|
|
161
|
+
if (item === null) {
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
yield item;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
function sleep(ms) {
|
|
169
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// src/session.ts
|
|
173
|
+
var Session = class {
|
|
174
|
+
constructor(socket, nextId, replyTimeoutMs, eventSink) {
|
|
175
|
+
this.socket = socket;
|
|
176
|
+
this.nextId = nextId;
|
|
177
|
+
this.replyTimeoutMs = replyTimeoutMs;
|
|
178
|
+
this.eventSink = eventSink;
|
|
179
|
+
socket.on("message", (data) => this.onMessage(data.toString()));
|
|
180
|
+
socket.on("close", () => this.markClosed());
|
|
181
|
+
socket.on("error", () => this.markClosed());
|
|
182
|
+
}
|
|
183
|
+
socket;
|
|
184
|
+
nextId;
|
|
185
|
+
replyTimeoutMs;
|
|
186
|
+
eventSink;
|
|
187
|
+
pending = /* @__PURE__ */ new Map();
|
|
188
|
+
closed = false;
|
|
189
|
+
closeWaiters = [];
|
|
190
|
+
/**
|
|
191
|
+
* Send a command and await its correlated reply. Maps a `status:"error"`
|
|
192
|
+
* reply to a rejected {@link ControlError} carrying the wire code.
|
|
193
|
+
*/
|
|
194
|
+
command(module, verb, target, args) {
|
|
195
|
+
if (this.closed) {
|
|
196
|
+
return Promise.reject(ControlError.closed());
|
|
197
|
+
}
|
|
198
|
+
const id = `c-${this.nextId.value++}`;
|
|
199
|
+
const text = encodeCommand(id, module, verb, target, args);
|
|
200
|
+
return new Promise((resolve, reject) => {
|
|
201
|
+
const timer = setTimeout(() => {
|
|
202
|
+
this.pending.delete(id);
|
|
203
|
+
reject(ControlError.timeout(this.replyTimeoutMs));
|
|
204
|
+
}, this.replyTimeoutMs);
|
|
205
|
+
this.pending.set(id, { resolve, reject, timer });
|
|
206
|
+
try {
|
|
207
|
+
this.socket.send(text);
|
|
208
|
+
} catch (error) {
|
|
209
|
+
this.pending.delete(id);
|
|
210
|
+
clearTimeout(timer);
|
|
211
|
+
reject(ControlError.websocket(String(error)));
|
|
212
|
+
}
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
onMessage(text) {
|
|
216
|
+
const frame = parseInboundFrame(text);
|
|
217
|
+
if (frame === null) {
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
if (frame.type === "reply") {
|
|
221
|
+
const pending = this.pending.get(frame.id);
|
|
222
|
+
if (!pending) {
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
this.pending.delete(frame.id);
|
|
226
|
+
clearTimeout(pending.timer);
|
|
227
|
+
if (frame.status === "ok") {
|
|
228
|
+
pending.resolve(frame.result ?? null);
|
|
229
|
+
} else {
|
|
230
|
+
const code = frame.error?.code ?? "protocol_error";
|
|
231
|
+
const message = frame.error?.message ?? "error reply without an error body";
|
|
232
|
+
pending.reject(ControlError.command(code, message));
|
|
233
|
+
}
|
|
234
|
+
} else {
|
|
235
|
+
this.eventSink(frame);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
/** Explicitly close the connection. */
|
|
239
|
+
close() {
|
|
240
|
+
try {
|
|
241
|
+
this.socket.close();
|
|
242
|
+
} catch {
|
|
243
|
+
}
|
|
244
|
+
this.markClosed();
|
|
245
|
+
}
|
|
246
|
+
markClosed() {
|
|
247
|
+
if (this.closed) {
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
this.closed = true;
|
|
251
|
+
for (const pending of this.pending.values()) {
|
|
252
|
+
clearTimeout(pending.timer);
|
|
253
|
+
pending.reject(ControlError.closed());
|
|
254
|
+
}
|
|
255
|
+
this.pending.clear();
|
|
256
|
+
for (const waiter of this.closeWaiters.splice(0)) {
|
|
257
|
+
waiter();
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
isClosed() {
|
|
261
|
+
return this.closed;
|
|
262
|
+
}
|
|
263
|
+
/** Resolve once the connection is closed. */
|
|
264
|
+
waitClosed() {
|
|
265
|
+
if (this.closed) {
|
|
266
|
+
return Promise.resolve();
|
|
267
|
+
}
|
|
268
|
+
return new Promise((resolve) => this.closeWaiters.push(resolve));
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
|
|
272
|
+
// src/client.ts
|
|
273
|
+
function resolveConfig(config) {
|
|
274
|
+
return {
|
|
275
|
+
url: config.url,
|
|
276
|
+
app: config.app,
|
|
277
|
+
token: config.token,
|
|
278
|
+
protocol: config.protocol ?? PROTOCOL_VERSION,
|
|
279
|
+
replyTimeoutMs: config.replyTimeoutMs ?? 1e4,
|
|
280
|
+
reconnectBackoffMs: config.reconnectBackoffMs ?? 1e3
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
var EventStream = class {
|
|
284
|
+
constructor(queue) {
|
|
285
|
+
this.queue = queue;
|
|
286
|
+
}
|
|
287
|
+
queue;
|
|
288
|
+
/** Await the next event. `null` once the client shuts down. */
|
|
289
|
+
next() {
|
|
290
|
+
return this.queue.next();
|
|
291
|
+
}
|
|
292
|
+
[Symbol.asyncIterator]() {
|
|
293
|
+
return this.queue[Symbol.asyncIterator]();
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
var ControlClient = class _ControlClient {
|
|
297
|
+
config;
|
|
298
|
+
nextId = { value: 1 };
|
|
299
|
+
current = null;
|
|
300
|
+
eventCallback = null;
|
|
301
|
+
shutdownRequested = false;
|
|
302
|
+
shutdownWaiters = [];
|
|
303
|
+
constructor(config) {
|
|
304
|
+
this.config = resolveConfig(config);
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Connect + `hello`. A bad token surfaces as a {@link ControlError} of kind
|
|
308
|
+
* `unauthorized` (the upgrade is rejected 401 before the socket opens).
|
|
309
|
+
*/
|
|
310
|
+
static async connect(config) {
|
|
311
|
+
const client = new _ControlClient(config);
|
|
312
|
+
client.current = await client.connectAndHandshake();
|
|
313
|
+
return client;
|
|
314
|
+
}
|
|
315
|
+
/**
|
|
316
|
+
* Register a callback for every event (pushed events + reconnect reattach).
|
|
317
|
+
* Overwrites any previous callback / stream. Facades set this internally.
|
|
318
|
+
*/
|
|
319
|
+
onEvent(callback) {
|
|
320
|
+
this.eventCallback = callback;
|
|
321
|
+
}
|
|
322
|
+
/** A pull-style stream of every event. Overwrites any previous callback. */
|
|
323
|
+
events() {
|
|
324
|
+
const queue = new AsyncQueue();
|
|
325
|
+
this.eventCallback = (event) => queue.push(event);
|
|
326
|
+
return new EventStream(queue);
|
|
327
|
+
}
|
|
328
|
+
/**
|
|
329
|
+
* Send a raw command on the current session and return the reply's `result`.
|
|
330
|
+
* The generic primitive every facade is built on.
|
|
331
|
+
*/
|
|
332
|
+
async command(module, verb, target, args) {
|
|
333
|
+
const session = this.current;
|
|
334
|
+
if (!session || session.isClosed()) {
|
|
335
|
+
throw ControlError.closed();
|
|
336
|
+
}
|
|
337
|
+
return session.command(module, verb, target, args);
|
|
338
|
+
}
|
|
339
|
+
/** Fetch the registered adapters' verb/event schema (`describe`). */
|
|
340
|
+
async describe() {
|
|
341
|
+
return this.command(null, DESCRIBE, null, null);
|
|
342
|
+
}
|
|
343
|
+
/** Re-enumerate the channels this connection owns (`resync`). */
|
|
344
|
+
async resync() {
|
|
345
|
+
const value = await this.command(null, RESYNC, null, null);
|
|
346
|
+
return value?.channels ?? [];
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* A {@link CommandTransport} that routes to the client's *current* session (so
|
|
350
|
+
* a facade handle keeps working across reconnects). Used by {@link SipClient}.
|
|
351
|
+
*/
|
|
352
|
+
commander() {
|
|
353
|
+
return {
|
|
354
|
+
command: (module, verb, target, args) => this.command(module, verb, target, args)
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* Drive the client: keep the connection alive, reconnecting with backoff and
|
|
359
|
+
* re-attaching owned channels (`resync`, delivered as `reattach` events) after
|
|
360
|
+
* each reconnect. Resolves on {@link ControlClient.shutdown}, or rejects on a
|
|
361
|
+
* fatal error (token revoked → `unauthorized`).
|
|
362
|
+
*/
|
|
363
|
+
async run() {
|
|
364
|
+
for (; ; ) {
|
|
365
|
+
let session = this.current;
|
|
366
|
+
if (!session || session.isClosed()) {
|
|
367
|
+
if (this.shutdownRequested) {
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
try {
|
|
371
|
+
session = await this.connectAndHandshake();
|
|
372
|
+
} catch (error) {
|
|
373
|
+
if (error instanceof ControlError && error.kind === "unauthorized") {
|
|
374
|
+
throw error;
|
|
375
|
+
}
|
|
376
|
+
await Promise.race([sleep(this.config.reconnectBackoffMs), this.shutdownSignal()]);
|
|
377
|
+
if (this.shutdownRequested) {
|
|
378
|
+
return;
|
|
379
|
+
}
|
|
380
|
+
continue;
|
|
381
|
+
}
|
|
382
|
+
this.current = session;
|
|
383
|
+
await this.resyncAndReattach(session);
|
|
384
|
+
}
|
|
385
|
+
await Promise.race([session.waitClosed(), this.shutdownSignal()]);
|
|
386
|
+
if (this.shutdownRequested) {
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
389
|
+
this.current = null;
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
/** Stop the client: close the current session and unblock {@link ControlClient.run}. */
|
|
393
|
+
shutdown() {
|
|
394
|
+
this.shutdownRequested = true;
|
|
395
|
+
for (const waiter of this.shutdownWaiters.splice(0)) {
|
|
396
|
+
waiter();
|
|
397
|
+
}
|
|
398
|
+
if (this.current) {
|
|
399
|
+
this.current.close();
|
|
400
|
+
this.current = null;
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
shutdownSignal() {
|
|
404
|
+
if (this.shutdownRequested) {
|
|
405
|
+
return Promise.resolve();
|
|
406
|
+
}
|
|
407
|
+
return new Promise((resolve) => this.shutdownWaiters.push(resolve));
|
|
408
|
+
}
|
|
409
|
+
emit(event) {
|
|
410
|
+
this.eventCallback?.(event);
|
|
411
|
+
}
|
|
412
|
+
async connectAndHandshake() {
|
|
413
|
+
const socket = await this.openSocket();
|
|
414
|
+
const session = new Session(
|
|
415
|
+
socket,
|
|
416
|
+
this.nextId,
|
|
417
|
+
this.config.replyTimeoutMs,
|
|
418
|
+
(frame) => this.emit({ type: "event", frame })
|
|
419
|
+
);
|
|
420
|
+
const result = await session.command(null, HELLO, null, {
|
|
421
|
+
app: this.config.app,
|
|
422
|
+
protocol: this.config.protocol
|
|
423
|
+
});
|
|
424
|
+
if (!result || result.subprotocol !== SUBPROTOCOL) {
|
|
425
|
+
session.close();
|
|
426
|
+
throw ControlError.handshake(
|
|
427
|
+
`server negotiated subprotocol ${JSON.stringify(result?.subprotocol)}, expected ${JSON.stringify(SUBPROTOCOL)}`
|
|
428
|
+
);
|
|
429
|
+
}
|
|
430
|
+
return session;
|
|
431
|
+
}
|
|
432
|
+
openSocket() {
|
|
433
|
+
return new Promise((resolve, reject) => {
|
|
434
|
+
const socket = new WebSocket(this.config.url, [SUBPROTOCOL], {
|
|
435
|
+
headers: { Authorization: `Bearer ${this.config.token}` }
|
|
436
|
+
});
|
|
437
|
+
let settled = false;
|
|
438
|
+
const settle = () => {
|
|
439
|
+
settled = true;
|
|
440
|
+
socket.off("open", onOpen);
|
|
441
|
+
socket.off("unexpected-response", onUnexpected);
|
|
442
|
+
};
|
|
443
|
+
const onOpen = () => {
|
|
444
|
+
settle();
|
|
445
|
+
resolve(socket);
|
|
446
|
+
};
|
|
447
|
+
const onUnexpected = (request, response) => {
|
|
448
|
+
settle();
|
|
449
|
+
request.destroy();
|
|
450
|
+
reject(ControlError.unauthorized(response.statusCode ?? 0));
|
|
451
|
+
};
|
|
452
|
+
const onError = (error) => {
|
|
453
|
+
if (!settled) {
|
|
454
|
+
settle();
|
|
455
|
+
reject(ControlError.websocket(error.message));
|
|
456
|
+
}
|
|
457
|
+
};
|
|
458
|
+
socket.on("open", onOpen);
|
|
459
|
+
socket.on("unexpected-response", onUnexpected);
|
|
460
|
+
socket.on("error", onError);
|
|
461
|
+
});
|
|
462
|
+
}
|
|
463
|
+
async resyncAndReattach(session) {
|
|
464
|
+
try {
|
|
465
|
+
const value = await session.command(null, RESYNC, null, null);
|
|
466
|
+
for (const snapshot of value?.channels ?? []) {
|
|
467
|
+
this.emit({ type: "reattach", snapshot });
|
|
468
|
+
}
|
|
469
|
+
} catch {
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
};
|
|
473
|
+
var ControlServer = class _ControlServer {
|
|
474
|
+
constructor(config, wss) {
|
|
475
|
+
this.config = config;
|
|
476
|
+
this.wss = wss;
|
|
477
|
+
wss.on("connection", (socket, request) => this.onConnection(socket, request));
|
|
478
|
+
wss.on("close", () => this.markClosed());
|
|
479
|
+
}
|
|
480
|
+
config;
|
|
481
|
+
wss;
|
|
482
|
+
nextId = { value: 1 };
|
|
483
|
+
eventSink = null;
|
|
484
|
+
closeWaiters = [];
|
|
485
|
+
sockets = /* @__PURE__ */ new Set();
|
|
486
|
+
closed = false;
|
|
487
|
+
/** Bind the listener (so the assigned port is known before accepting). */
|
|
488
|
+
static bind(config) {
|
|
489
|
+
const token = config.token;
|
|
490
|
+
return new Promise((resolve, reject) => {
|
|
491
|
+
const wss = new WebSocketServer({
|
|
492
|
+
host: config.host,
|
|
493
|
+
port: config.port,
|
|
494
|
+
// Echo the subprotocol siphon offers on the dial (required — the client
|
|
495
|
+
// rejects the handshake otherwise).
|
|
496
|
+
handleProtocols: (protocols) => protocols.has(SUBPROTOCOL) ? SUBPROTOCOL : false,
|
|
497
|
+
// Verify the bearer token siphon presents (the app's own policy).
|
|
498
|
+
verifyClient: ({ req }, done) => {
|
|
499
|
+
const ok = req.headers["authorization"] === `Bearer ${token}`;
|
|
500
|
+
done(ok, 401, "unauthorized");
|
|
501
|
+
}
|
|
502
|
+
});
|
|
503
|
+
const onError = (error) => {
|
|
504
|
+
wss.off("listening", onListening);
|
|
505
|
+
reject(ControlError.config(`bind ${config.host}:${config.port}: ${error.message}`));
|
|
506
|
+
};
|
|
507
|
+
const onListening = () => {
|
|
508
|
+
wss.off("error", onError);
|
|
509
|
+
resolve(new _ControlServer(config, wss));
|
|
510
|
+
};
|
|
511
|
+
wss.once("listening", onListening);
|
|
512
|
+
wss.once("error", onError);
|
|
513
|
+
});
|
|
514
|
+
}
|
|
515
|
+
/** The actual bound address (useful when binding to port 0 in tests). */
|
|
516
|
+
localAddr() {
|
|
517
|
+
const address = this.wss.address();
|
|
518
|
+
if (typeof address === "string" || address === null) {
|
|
519
|
+
throw ControlError.config("server is not bound to a TCP address");
|
|
520
|
+
}
|
|
521
|
+
return address;
|
|
522
|
+
}
|
|
523
|
+
/** Register the sink for `(event, connection-commander)` pairs. Facades set this internally. */
|
|
524
|
+
onConnectionEvent(sink) {
|
|
525
|
+
this.eventSink = sink;
|
|
526
|
+
}
|
|
527
|
+
/** Resolve once the server has been closed (`run` resolves at the same time). */
|
|
528
|
+
run() {
|
|
529
|
+
if (this.closed) {
|
|
530
|
+
return Promise.resolve();
|
|
531
|
+
}
|
|
532
|
+
return new Promise((resolve) => this.closeWaiters.push(resolve));
|
|
533
|
+
}
|
|
534
|
+
/** Stop accepting dials, drop live connections, and close the listener. */
|
|
535
|
+
close() {
|
|
536
|
+
for (const socket of this.sockets) {
|
|
537
|
+
socket.terminate();
|
|
538
|
+
}
|
|
539
|
+
this.sockets.clear();
|
|
540
|
+
return new Promise((resolve) => {
|
|
541
|
+
this.wss.close(() => {
|
|
542
|
+
this.markClosed();
|
|
543
|
+
resolve();
|
|
544
|
+
});
|
|
545
|
+
});
|
|
546
|
+
}
|
|
547
|
+
markClosed() {
|
|
548
|
+
if (this.closed) {
|
|
549
|
+
return;
|
|
550
|
+
}
|
|
551
|
+
this.closed = true;
|
|
552
|
+
for (const waiter of this.closeWaiters.splice(0)) {
|
|
553
|
+
waiter();
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
onConnection(socket, _request) {
|
|
557
|
+
this.sockets.add(socket);
|
|
558
|
+
socket.on("close", () => this.sockets.delete(socket));
|
|
559
|
+
let session;
|
|
560
|
+
const sink = (frame) => {
|
|
561
|
+
this.eventSink?.(frame, session);
|
|
562
|
+
};
|
|
563
|
+
session = new Session(socket, this.nextId, this.config.replyTimeoutMs ?? 1e4, sink);
|
|
564
|
+
}
|
|
565
|
+
};
|
|
566
|
+
|
|
567
|
+
// src/sip.ts
|
|
568
|
+
function callEventFromFrame(frame) {
|
|
569
|
+
return { kind: sipEventKind(frame.event), payload: frame.payload ?? null, frame };
|
|
570
|
+
}
|
|
571
|
+
function responseArgs(options) {
|
|
572
|
+
const args = {};
|
|
573
|
+
if (options.code !== void 0) {
|
|
574
|
+
args.code = options.code;
|
|
575
|
+
}
|
|
576
|
+
if (options.reason !== void 0) {
|
|
577
|
+
args.reason = options.reason;
|
|
578
|
+
}
|
|
579
|
+
if (options.body !== void 0) {
|
|
580
|
+
args.body = options.body;
|
|
581
|
+
}
|
|
582
|
+
if (options.contentType !== void 0) {
|
|
583
|
+
args.content_type = options.contentType;
|
|
584
|
+
}
|
|
585
|
+
return args;
|
|
586
|
+
}
|
|
587
|
+
function stringValue(result) {
|
|
588
|
+
if (typeof result === "object" && result !== null) {
|
|
589
|
+
const value = result.value;
|
|
590
|
+
if (typeof value === "string") {
|
|
591
|
+
return value;
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
return null;
|
|
595
|
+
}
|
|
596
|
+
var Call = class {
|
|
597
|
+
constructor(transport, channelId, callId, sipCallId, app, payload, reattached, eventQueue) {
|
|
598
|
+
this.transport = transport;
|
|
599
|
+
this.channelId = channelId;
|
|
600
|
+
this.callId = callId;
|
|
601
|
+
this.sipCallId = sipCallId;
|
|
602
|
+
this.app = app;
|
|
603
|
+
this.payload = payload;
|
|
604
|
+
this.reattached = reattached;
|
|
605
|
+
this.eventQueue = eventQueue;
|
|
606
|
+
}
|
|
607
|
+
transport;
|
|
608
|
+
channelId;
|
|
609
|
+
callId;
|
|
610
|
+
sipCallId;
|
|
611
|
+
app;
|
|
612
|
+
payload;
|
|
613
|
+
reattached;
|
|
614
|
+
eventQueue;
|
|
615
|
+
target() {
|
|
616
|
+
return { channel: this.channelId };
|
|
617
|
+
}
|
|
618
|
+
sip(verb, args) {
|
|
619
|
+
return this.transport.command(MODULE_SIP, verb, this.target(), args);
|
|
620
|
+
}
|
|
621
|
+
substrate(verb, args) {
|
|
622
|
+
return this.transport.command(null, verb, this.target(), args);
|
|
623
|
+
}
|
|
624
|
+
// --- SIP verbs (mirror the in-process scripting API) -------------------
|
|
625
|
+
/** Send a UAS 2xx to the parked A-leg (default `200 OK`). */
|
|
626
|
+
async answer(options) {
|
|
627
|
+
await this.sip(SipVerb.Answer, options ? responseArgs(options) : {});
|
|
628
|
+
}
|
|
629
|
+
/** Send a UAS 1xx / early media (default `183 Session Progress`). */
|
|
630
|
+
async progress(options) {
|
|
631
|
+
await this.sip(SipVerb.Progress, options ? responseArgs(options) : {});
|
|
632
|
+
}
|
|
633
|
+
/** Send a final non-2xx and tear the call down. */
|
|
634
|
+
async reject(code, reason) {
|
|
635
|
+
const args = { code };
|
|
636
|
+
if (reason !== void 0) {
|
|
637
|
+
args.reason = reason;
|
|
638
|
+
}
|
|
639
|
+
await this.sip(SipVerb.Reject, args);
|
|
640
|
+
}
|
|
641
|
+
/**
|
|
642
|
+
* Tear the call down: BYE an answered call (full teardown funnel), or reject
|
|
643
|
+
* an unanswered one. Mirrors the in-process `call.terminate()`.
|
|
644
|
+
*/
|
|
645
|
+
async terminate(reason) {
|
|
646
|
+
await this.sip(SipVerb.Hangup, reason !== void 0 ? { reason } : {});
|
|
647
|
+
}
|
|
648
|
+
/** Alias for {@link Call.terminate}. */
|
|
649
|
+
async hangup(reason) {
|
|
650
|
+
await this.terminate(reason);
|
|
651
|
+
}
|
|
652
|
+
/** Send an in-dialog REFER on the A-leg (blind transfer). */
|
|
653
|
+
async refer(to) {
|
|
654
|
+
await this.sip(SipVerb.Refer, { to });
|
|
655
|
+
}
|
|
656
|
+
/** Blind-transfer alias for {@link Call.refer}. */
|
|
657
|
+
async transfer(to) {
|
|
658
|
+
await this.refer(to);
|
|
659
|
+
}
|
|
660
|
+
/** Attended transfer — REFER with a `Replaces` triple (RFC 3891). */
|
|
661
|
+
async referReplaces(to, replaces) {
|
|
662
|
+
await this.sip(SipVerb.Refer, {
|
|
663
|
+
to,
|
|
664
|
+
replaces: {
|
|
665
|
+
call_id: replaces.callId,
|
|
666
|
+
from_tag: replaces.fromTag,
|
|
667
|
+
to_tag: replaces.toTag,
|
|
668
|
+
early_only: replaces.earlyOnly ?? false
|
|
669
|
+
}
|
|
670
|
+
});
|
|
671
|
+
}
|
|
672
|
+
/**
|
|
673
|
+
* Accept an inbound REFER on this tracked call. **Not implemented server-side
|
|
674
|
+
* in Phase 1** — resolves to a {@link ControlError} with `code ===
|
|
675
|
+
* "unsupported_verb"` until the server adds it.
|
|
676
|
+
*/
|
|
677
|
+
async acceptRefer(options) {
|
|
678
|
+
const args = {};
|
|
679
|
+
if (options?.target !== void 0) {
|
|
680
|
+
args.target = options.target;
|
|
681
|
+
}
|
|
682
|
+
if (options?.nextHop !== void 0) {
|
|
683
|
+
args.next_hop = options.nextHop;
|
|
684
|
+
}
|
|
685
|
+
if (options?.mode !== void 0) {
|
|
686
|
+
args.mode = options.mode;
|
|
687
|
+
}
|
|
688
|
+
await this.sip(SipVerb.AcceptRefer, args);
|
|
689
|
+
}
|
|
690
|
+
/**
|
|
691
|
+
* Reject an inbound REFER on this tracked call. **Not implemented server-side
|
|
692
|
+
* in Phase 1** — see {@link Call.acceptRefer}.
|
|
693
|
+
*/
|
|
694
|
+
async rejectRefer(code, reason) {
|
|
695
|
+
const args = { code };
|
|
696
|
+
if (reason !== void 0) {
|
|
697
|
+
args.reason = reason;
|
|
698
|
+
}
|
|
699
|
+
await this.sip(SipVerb.RejectRefer, args);
|
|
700
|
+
}
|
|
701
|
+
/** Set a header on the stored A-leg INVITE. */
|
|
702
|
+
async setHeader(name, value) {
|
|
703
|
+
await this.sip(SipVerb.SetHeader, { name, value });
|
|
704
|
+
}
|
|
705
|
+
/** Read a header from the stored A-leg INVITE (`null` when absent). */
|
|
706
|
+
async getHeader(name) {
|
|
707
|
+
const result = await this.sip(SipVerb.GetHeader, { name });
|
|
708
|
+
return stringValue(result);
|
|
709
|
+
}
|
|
710
|
+
/**
|
|
711
|
+
* Remove a header from the stored A-leg INVITE. **Not implemented server-side
|
|
712
|
+
* in Phase 1** — resolves to a {@link ControlError} with `code ===
|
|
713
|
+
* "unsupported_verb"` until the server adds it.
|
|
714
|
+
*/
|
|
715
|
+
async removeHeader(name) {
|
|
716
|
+
await this.sip(SipVerb.RemoveHeader, { name });
|
|
717
|
+
}
|
|
718
|
+
// --- per-call variables (substrate verbs, no module) -------------------
|
|
719
|
+
/** Set a per-call variable (survives a reconnect via `resync`). */
|
|
720
|
+
async setVar(key, value) {
|
|
721
|
+
await this.substrate(SET_VAR, { key, value });
|
|
722
|
+
}
|
|
723
|
+
/** Read a per-call variable (`null` when unset). */
|
|
724
|
+
async getVar(key) {
|
|
725
|
+
const result = await this.substrate(GET_VAR, { key });
|
|
726
|
+
return stringValue(result);
|
|
727
|
+
}
|
|
728
|
+
// --- media (server answers `unsupported_verb` today) -------------------
|
|
729
|
+
/**
|
|
730
|
+
* Play an announcement. **Not yet implemented server-side** — resolves to a
|
|
731
|
+
* {@link ControlError} with `code === "unsupported_verb"` until the media
|
|
732
|
+
* backend lands.
|
|
733
|
+
*/
|
|
734
|
+
async playFile(file) {
|
|
735
|
+
await this.sip(SipVerb.Play, { file });
|
|
736
|
+
}
|
|
737
|
+
/** Send DTMF. **Not yet implemented server-side** — see {@link Call.playFile}. */
|
|
738
|
+
async dtmf(digits) {
|
|
739
|
+
await this.sip(SipVerb.Dtmf, { digits });
|
|
740
|
+
}
|
|
741
|
+
// --- escape hatch + events --------------------------------------------
|
|
742
|
+
/** Send an arbitrary SIP-adapter verb + args and return the raw result. */
|
|
743
|
+
async command(verb, args) {
|
|
744
|
+
return this.sip(verb, args ?? {});
|
|
745
|
+
}
|
|
746
|
+
/**
|
|
747
|
+
* Await the next event for this call (`ChannelStateChange`,
|
|
748
|
+
* `ChannelHangupRequest`, `StasisEnd`). `null` once the stream closes.
|
|
749
|
+
*/
|
|
750
|
+
nextEvent() {
|
|
751
|
+
return this.eventQueue.next();
|
|
752
|
+
}
|
|
753
|
+
/** Async-iterate this call's events until the stream closes. */
|
|
754
|
+
events() {
|
|
755
|
+
return this.eventQueue[Symbol.asyncIterator]();
|
|
756
|
+
}
|
|
757
|
+
};
|
|
758
|
+
var CallStream = class {
|
|
759
|
+
constructor(queue) {
|
|
760
|
+
this.queue = queue;
|
|
761
|
+
}
|
|
762
|
+
queue;
|
|
763
|
+
/** Await the next handed-over call. `null` once the client/server shuts down. */
|
|
764
|
+
next() {
|
|
765
|
+
return this.queue.next();
|
|
766
|
+
}
|
|
767
|
+
[Symbol.asyncIterator]() {
|
|
768
|
+
return this.queue[Symbol.asyncIterator]();
|
|
769
|
+
}
|
|
770
|
+
};
|
|
771
|
+
var SipFacade = class {
|
|
772
|
+
handler = null;
|
|
773
|
+
callQueue = null;
|
|
774
|
+
channels = /* @__PURE__ */ new Map();
|
|
775
|
+
setHandler(handler) {
|
|
776
|
+
this.handler = handler;
|
|
777
|
+
}
|
|
778
|
+
setStream() {
|
|
779
|
+
const queue = new AsyncQueue();
|
|
780
|
+
this.callQueue = queue;
|
|
781
|
+
return new CallStream(queue);
|
|
782
|
+
}
|
|
783
|
+
handleClientEvent(event, transport) {
|
|
784
|
+
if (event.type === "event") {
|
|
785
|
+
this.handleEvent(event.frame, transport);
|
|
786
|
+
} else {
|
|
787
|
+
this.reattach(event.snapshot, transport);
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
handleEvent(frame, transport) {
|
|
791
|
+
const kind = sipEventKind(frame.event);
|
|
792
|
+
if (kind === "StasisStart") {
|
|
793
|
+
if (!frame.channel) {
|
|
794
|
+
return;
|
|
795
|
+
}
|
|
796
|
+
const queue = new AsyncQueue();
|
|
797
|
+
this.channels.set(frame.channel, queue);
|
|
798
|
+
const call = new Call(
|
|
799
|
+
transport,
|
|
800
|
+
frame.channel,
|
|
801
|
+
frame.call_id ?? null,
|
|
802
|
+
frame.sip_call_id ?? null,
|
|
803
|
+
frame.app ?? null,
|
|
804
|
+
frame.payload ?? null,
|
|
805
|
+
false,
|
|
806
|
+
queue
|
|
807
|
+
);
|
|
808
|
+
this.dispatch(call);
|
|
809
|
+
} else if (kind === "StasisEnd") {
|
|
810
|
+
if (frame.channel) {
|
|
811
|
+
this.route(frame.channel, callEventFromFrame(frame));
|
|
812
|
+
const queue = this.channels.get(frame.channel);
|
|
813
|
+
queue?.close();
|
|
814
|
+
this.channels.delete(frame.channel);
|
|
815
|
+
}
|
|
816
|
+
} else if (frame.channel) {
|
|
817
|
+
this.route(frame.channel, callEventFromFrame(frame));
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
reattach(snapshot, transport) {
|
|
821
|
+
const queue = new AsyncQueue();
|
|
822
|
+
this.channels.set(snapshot.channel, queue);
|
|
823
|
+
const call = new Call(
|
|
824
|
+
transport,
|
|
825
|
+
snapshot.channel,
|
|
826
|
+
snapshot.call_id,
|
|
827
|
+
snapshot.sip_call_id,
|
|
828
|
+
null,
|
|
829
|
+
snapshot,
|
|
830
|
+
true,
|
|
831
|
+
queue
|
|
832
|
+
);
|
|
833
|
+
this.dispatch(call);
|
|
834
|
+
}
|
|
835
|
+
route(channel, event) {
|
|
836
|
+
this.channels.get(channel)?.push(event);
|
|
837
|
+
}
|
|
838
|
+
dispatch(call) {
|
|
839
|
+
if (this.handler) {
|
|
840
|
+
const handler = this.handler;
|
|
841
|
+
void Promise.resolve().then(() => handler(call)).catch((error) => {
|
|
842
|
+
});
|
|
843
|
+
} else if (this.callQueue) {
|
|
844
|
+
this.callQueue.push(call);
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
};
|
|
848
|
+
var SipClient = class _SipClient {
|
|
849
|
+
constructor(client) {
|
|
850
|
+
this.client = client;
|
|
851
|
+
const commander = client.commander();
|
|
852
|
+
client.onEvent((event) => this.facade.handleClientEvent(event, commander));
|
|
853
|
+
}
|
|
854
|
+
client;
|
|
855
|
+
facade = new SipFacade();
|
|
856
|
+
/** Connect + `hello`, then install the SIP event router. */
|
|
857
|
+
static async connect(config) {
|
|
858
|
+
const client = await ControlClient.connect(config);
|
|
859
|
+
return new _SipClient(client);
|
|
860
|
+
}
|
|
861
|
+
/** Wrap an already-connected generic client with the SIP facade. */
|
|
862
|
+
static wrap(client) {
|
|
863
|
+
return new _SipClient(client);
|
|
864
|
+
}
|
|
865
|
+
/** The underlying generic client (for raw `command` on any module). */
|
|
866
|
+
get controlClient() {
|
|
867
|
+
return this.client;
|
|
868
|
+
}
|
|
869
|
+
/** Register a call handler (does not block). */
|
|
870
|
+
setCallHandler(handler) {
|
|
871
|
+
this.facade.setHandler(handler);
|
|
872
|
+
}
|
|
873
|
+
/**
|
|
874
|
+
* Register a call handler **and drive the client to completion** (the
|
|
875
|
+
* supervised reconnect + resync loop).
|
|
876
|
+
*/
|
|
877
|
+
onCall(handler) {
|
|
878
|
+
this.setCallHandler(handler);
|
|
879
|
+
return this.client.run();
|
|
880
|
+
}
|
|
881
|
+
/** A pull-style stream of handed-over calls (alternative to a handler). */
|
|
882
|
+
calls() {
|
|
883
|
+
return this.facade.setStream();
|
|
884
|
+
}
|
|
885
|
+
/** Drive the supervised connection loop (reconnect + resync). */
|
|
886
|
+
run() {
|
|
887
|
+
return this.client.run();
|
|
888
|
+
}
|
|
889
|
+
/** Fetch the registered adapters' schema (`describe`). */
|
|
890
|
+
describe() {
|
|
891
|
+
return this.client.describe();
|
|
892
|
+
}
|
|
893
|
+
/** Send a raw command on any module (the generic escape hatch). */
|
|
894
|
+
command(module, verb, target, args) {
|
|
895
|
+
return this.client.command(module, verb, target, args);
|
|
896
|
+
}
|
|
897
|
+
/** Stop the client. */
|
|
898
|
+
shutdown() {
|
|
899
|
+
this.client.shutdown();
|
|
900
|
+
}
|
|
901
|
+
};
|
|
902
|
+
var SipServer = class _SipServer {
|
|
903
|
+
constructor(server) {
|
|
904
|
+
this.server = server;
|
|
905
|
+
server.onConnectionEvent((frame, transport) => this.facade.handleEvent(frame, transport));
|
|
906
|
+
}
|
|
907
|
+
server;
|
|
908
|
+
facade = new SipFacade();
|
|
909
|
+
/** Bind the listener and install the SIP event router. */
|
|
910
|
+
static async bind(config) {
|
|
911
|
+
const server = await ControlServer.bind(config);
|
|
912
|
+
return new _SipServer(server);
|
|
913
|
+
}
|
|
914
|
+
/** The actual bound address (useful when binding to port 0 in tests). */
|
|
915
|
+
localAddr() {
|
|
916
|
+
return this.server.localAddr();
|
|
917
|
+
}
|
|
918
|
+
/** Register a call handler (does not block). */
|
|
919
|
+
setCallHandler(handler) {
|
|
920
|
+
this.facade.setHandler(handler);
|
|
921
|
+
}
|
|
922
|
+
/** A pull-style stream of dialed-in calls (alternative to a handler). */
|
|
923
|
+
calls() {
|
|
924
|
+
return this.facade.setStream();
|
|
925
|
+
}
|
|
926
|
+
/** Register a call handler **and run the accept loop** to completion. */
|
|
927
|
+
onCall(handler) {
|
|
928
|
+
this.setCallHandler(handler);
|
|
929
|
+
return this.server.run();
|
|
930
|
+
}
|
|
931
|
+
/** Accept siphon's per-call dials until the server is closed. */
|
|
932
|
+
run() {
|
|
933
|
+
return this.server.run();
|
|
934
|
+
}
|
|
935
|
+
/** Stop accepting dials and close the listener. */
|
|
936
|
+
close() {
|
|
937
|
+
return this.server.close();
|
|
938
|
+
}
|
|
939
|
+
};
|
|
940
|
+
|
|
941
|
+
export { Call, CallStream, ControlClient, ControlError, ControlServer, DESCRIBE, EventStream, GET_VAR, HELLO, MODULE_SIP, MODULE_SMPP, MODULE_SS7, PROTOCOL_VERSION, RESYNC, SET_VAR, SUBPROTOCOL, SipClient, SipServer, SipVerb, encodeCommand, parseInboundFrame, sipEventKind };
|
|
942
|
+
//# sourceMappingURL=index.js.map
|
|
943
|
+
//# sourceMappingURL=index.js.map
|