Commit 049b672 for jssip.net
commit 049b6725ee8d09dcedf4d39da84d43551f59a565
Author: José Luis Millán <jmillan@aliax.net>
Date: Thu Dec 3 12:25:11 2026 +0100
TS: Message
diff --git a/src/Constants.ts b/src/Constants.ts
index 40ef7fe..20c7b7e 100644
--- a/src/Constants.ts
+++ b/src/Constants.ts
@@ -20,6 +20,19 @@ export const SIP = 'sip';
*/
export const SIPS = 'sips';
+/**
+ * Which side caused what an event reports.
+ *
+ * @remarks
+ * - `system` is the library itself, for instance when a request times out.
+ */
+export type Originator = 'local' | 'remote' | 'system';
+
+/**
+ * Whether a session or a message was received or sent.
+ */
+export type Direction = 'incoming' | 'outgoing';
+
/**
* Why a session, a registration or a message ended or failed.
*
diff --git a/src/Message.d.ts b/src/Message.d.ts
deleted file mode 100644
index 7b18260..0000000
--- a/src/Message.d.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import { EventEmitter } from 'events';
-
-import {
- ExtraHeaders,
- Originator,
- OutgoingListener,
- SessionDirection,
- TerminateOptions,
-} from './RTCSession';
-import { IncomingResponse } from './SIPMessage';
-import NameAddrHeader = require('./NameAddrHeader');
-import { causes } from './Constants';
-
-export interface AcceptOptions extends ExtraHeaders {
- body?: string;
-}
-
-export interface MessageFailedEvent {
- originator: Originator;
- response: IncomingResponse;
- cause?: causes;
-}
-
-export type MessageFailedListener = (event: MessageFailedEvent) => void;
-
-export interface MessageEventMap {
- succeeded: OutgoingListener;
- failed: MessageFailedListener;
-}
-
-export interface SendMessageOptions extends ExtraHeaders {
- contentType?: string;
- eventHandlers?: Partial<MessageEventMap>;
- fromUserName?: string;
- fromDisplayName?: string;
-}
-
-export class Message extends EventEmitter {
- get direction(): SessionDirection;
-
- get local_identity(): NameAddrHeader;
-
- get remote_identity(): NameAddrHeader;
-
- send(target: string, body: string, options?: SendMessageOptions): void;
-
- accept(options: AcceptOptions): void;
-
- reject(options: TerminateOptions): void;
-
- on<T extends keyof MessageEventMap>(
- type: T,
- listener: MessageEventMap[T]
- ): this;
-}
diff --git a/src/Message.js b/src/Message.js
deleted file mode 100644
index 94b94b9..0000000
--- a/src/Message.js
+++ /dev/null
@@ -1,272 +0,0 @@
-const EventEmitter = require('events').EventEmitter;
-const { Logger } = require('./Logger');
-const JsSIP_C = require('./Constants');
-const SIPMessage = require('./SIPMessage');
-const Utils = require('./Utils');
-const { RequestSender } = require('./RequestSender');
-const Exceptions = require('./Exceptions');
-const URI = require('./URI');
-
-const logger = new Logger('Message');
-
-module.exports = class Message extends EventEmitter {
- constructor(ua) {
- super();
-
- this._ua = ua;
- this._request = null;
- this._closed = false;
-
- this._direction = null;
- this._local_identity = null;
- this._remote_identity = null;
-
- // Whether an incoming message has been replied.
- this._is_replied = false;
-
- // Custom message empty object for high level use.
- this._data = {};
- }
-
- get direction() {
- return this._direction;
- }
-
- get local_identity() {
- return this._local_identity;
- }
-
- get remote_identity() {
- return this._remote_identity;
- }
-
- send(target, body, options = {}) {
- const originalTarget = target;
-
- if (target === undefined || body === undefined) {
- throw new TypeError('Not enough arguments');
- }
-
- // Check target validity.
- target = this._ua.normalizeTarget(target);
- if (!target) {
- throw new TypeError(`Invalid target: ${originalTarget}`);
- }
-
- // Get call options.
- const extraHeaders = Utils.cloneArray(options.extraHeaders);
- const eventHandlers = Utils.cloneObject(options.eventHandlers);
- const contentType = options.contentType || 'text/plain';
-
- const requestParams = {};
-
- if (options.fromUserName) {
- requestParams.from_uri = new URI(
- 'sip',
- options.fromUserName,
- this._ua.configuration.uri.host
- );
-
- extraHeaders.push(
- `P-Preferred-Identity: ${this._ua.configuration.uri.toString()}`
- );
- }
-
- if (options.fromDisplayName) {
- requestParams.from_display_name = options.fromDisplayName;
- }
-
- // Set event handlers.
- for (const event in eventHandlers) {
- if (Object.prototype.hasOwnProperty.call(eventHandlers, event)) {
- this.on(event, eventHandlers[event]);
- }
- }
-
- extraHeaders.push(`Content-Type: ${contentType}`);
-
- this._request = new SIPMessage.OutgoingRequest(
- JsSIP_C.MESSAGE,
- target,
- this._ua,
- requestParams,
- extraHeaders
- );
-
- if (body) {
- this._request.body = body;
- }
-
- const request_sender = new RequestSender(this._ua, this._request, {
- onRequestTimeout: () => {
- this._onRequestTimeout();
- },
- onTransportError: () => {
- this._onTransportError();
- },
- onReceiveResponse: response => {
- this._receiveResponse(response);
- },
- });
-
- this._newMessage('local', this._request);
-
- request_sender.send();
- }
-
- init_incoming(request) {
- this._request = request;
-
- this._newMessage('remote', request);
-
- // Reply with a 200 OK if the user didn't reply.
- if (!this._is_replied) {
- this._is_replied = true;
- request.reply(200);
- }
-
- this._close();
- }
-
- /**
- * Accept the incoming Message
- * Only valid for incoming Messages
- */
- accept(options = {}) {
- const extraHeaders = Utils.cloneArray(options.extraHeaders);
- const body = options.body;
-
- if (this._direction !== 'incoming') {
- throw new Exceptions.NotSupportedError(
- '"accept" not supported for outgoing Message'
- );
- }
-
- if (this._is_replied) {
- throw new Error('incoming Message already replied');
- }
-
- this._is_replied = true;
- this._request.reply(200, null, extraHeaders, body);
- }
-
- /**
- * Reject the incoming Message
- * Only valid for incoming Messages
- */
- reject(options = {}) {
- const status_code = options.status_code || 480;
- const reason_phrase = options.reason_phrase;
- const extraHeaders = Utils.cloneArray(options.extraHeaders);
- const body = options.body;
-
- if (this._direction !== 'incoming') {
- throw new Exceptions.NotSupportedError(
- '"reject" not supported for outgoing Message'
- );
- }
-
- if (this._is_replied) {
- throw new Error('incoming Message already replied');
- }
-
- if (status_code < 300 || status_code >= 700) {
- throw new TypeError(`Invalid status_code: ${status_code}`);
- }
-
- this._is_replied = true;
- this._request.reply(status_code, reason_phrase, extraHeaders, body);
- }
-
- _receiveResponse(response) {
- if (this._closed) {
- return;
- }
- switch (true) {
- case /^1[0-9]{2}$/.test(response.status_code): {
- // Ignore provisional responses.
- break;
- }
-
- case /^2[0-9]{2}$/.test(response.status_code): {
- this._succeeded('remote', response);
- break;
- }
-
- default: {
- const cause = Utils.sipErrorCause(response.status_code);
-
- this._failed('remote', response, cause);
- break;
- }
- }
- }
-
- _onRequestTimeout() {
- if (this._closed) {
- return;
- }
- this._failed('system', null, JsSIP_C.causes.REQUEST_TIMEOUT);
- }
-
- _onTransportError() {
- if (this._closed) {
- return;
- }
- this._failed('system', null, JsSIP_C.causes.CONNECTION_ERROR);
- }
-
- _close() {
- this._closed = true;
- this._ua.destroyMessage(this);
- }
-
- /**
- * Internal Callbacks
- */
-
- _newMessage(originator, request) {
- if (originator === 'remote') {
- this._direction = 'incoming';
- this._local_identity = request.to;
- this._remote_identity = request.from;
- } else if (originator === 'local') {
- this._direction = 'outgoing';
- this._local_identity = request.from;
- this._remote_identity = request.to;
- }
-
- this._ua.newMessage(this, {
- originator,
- message: this,
- request,
- });
- }
-
- _failed(originator, response, cause) {
- logger.debug('MESSAGE failed');
-
- this._close();
-
- logger.debug('emit "failed"');
-
- this.emit('failed', {
- originator,
- response: response || null,
- cause,
- });
- }
-
- _succeeded(originator, response) {
- logger.debug('MESSAGE succeeded');
-
- this._close();
-
- logger.debug('emit "succeeded"');
-
- this.emit('succeeded', {
- originator,
- response,
- });
- }
-};
diff --git a/src/Message.ts b/src/Message.ts
new file mode 100644
index 0000000..a6fb323
--- /dev/null
+++ b/src/Message.ts
@@ -0,0 +1,493 @@
+import { EventEmitter } from 'events';
+
+import * as JsSIP_C from './Constants';
+import type { Direction, Originator } from './Constants';
+import { NotSupportedError } from './Exceptions';
+import { Logger } from './Logger';
+import { RequestSender } from './RequestSender';
+import type { RequestSenderUA } from './RequestSender';
+import * as SIPMessage from './SIPMessage';
+import type {
+ IncomingRequest,
+ IncomingResponse,
+ OutgoingRequestParams,
+} from './SIPMessage';
+import * as Utils from './Utils';
+import NameAddrHeader = require('./NameAddrHeader');
+import URI = require('./URI');
+
+const logger = new Logger('Message');
+
+/**
+ * Reported when the MESSAGE got a 2xx response.
+ */
+export type MessageSucceededEvent = {
+ originator: Originator;
+ response: IncomingResponse;
+};
+
+/**
+ * Reported when the MESSAGE could not be delivered.
+ */
+export type MessageFailedEvent = {
+ originator: Originator;
+ response: IncomingResponse | null;
+ cause: JsSIP_C.causes;
+};
+
+/**
+ * The events a {@link Message} emits.
+ */
+export type MessageEventMap = {
+ succeeded: [event: MessageSucceededEvent];
+ failed: [event: MessageFailedEvent];
+};
+
+/**
+ * The listeners the application registers through the `eventHandlers` option
+ * of `send()`.
+ */
+export type MessageEventHandlers = {
+ [K in keyof MessageEventMap]: (...args: MessageEventMap[K]) => void;
+};
+
+/**
+ * Options accepted by `send()`.
+ */
+export type SendMessageOptions = {
+ /**
+ * Whole `Name: value` header field lines to add to the MESSAGE.
+ */
+ extraHeaders?: string[] | null;
+ /**
+ * Value of the Content-Type header field.
+ *
+ * @defaultValue `'text/plain'`
+ */
+ contentType?: string;
+ /**
+ * Listeners registered before the MESSAGE is sent, so that no event is
+ * missed.
+ */
+ eventHandlers?: Partial<MessageEventHandlers> | null;
+ /**
+ * User part of the From header field, which also adds a
+ * P-Preferred-Identity header field with the configured address.
+ */
+ fromUserName?: string;
+ /**
+ * Display name of the From header field.
+ */
+ fromDisplayName?: string;
+};
+
+/**
+ * Options accepted by `accept()`.
+ */
+export type AcceptOptions = {
+ extraHeaders?: string[] | null;
+ body?: string;
+};
+
+/**
+ * Options accepted by `reject()`.
+ */
+export type RejectOptions = {
+ extraHeaders?: string[] | null;
+ body?: string;
+ /**
+ * Status code of the response, between 300 and 699.
+ *
+ * @defaultValue `480`
+ */
+ status_code?: number;
+ /**
+ * Reason phrase of the response.
+ */
+ reason_phrase?: string;
+};
+
+/**
+ * The `UA` surface a message depends on.
+ *
+ * TODO: Replace with `import type { UA } from './UA'` once `UA` is ported to
+ * TypeScript.
+ */
+export interface MessageUA extends RequestSenderUA {
+ normalizeTarget(target: string | URI): URI | undefined;
+
+ newMessage(
+ message: Message,
+ data: {
+ originator: Originator;
+ message: Message;
+ request: SIPMessage.OutgoingRequest | IncomingRequest;
+ }
+ ): void;
+ destroyMessage(message: Message): void;
+}
+
+/**
+ * Sends and receives SIP MESSAGE requests, so instant messages outside of a
+ * session.
+ *
+ * @example
+ * ```ts
+ * ua.sendMessage('sip:bob@example.com', 'Hello there', {
+ * eventHandlers: {
+ * succeeded: () => console.log('delivered'),
+ * failed: ({ cause }) => console.log('not delivered', cause),
+ * },
+ * });
+ * ```
+ */
+export class Message extends EventEmitter<MessageEventMap> {
+ #ua: MessageUA;
+ #request: SIPMessage.OutgoingRequest | IncomingRequest | null;
+ #closed: boolean;
+ #direction: Direction | null;
+ #local_identity: NameAddrHeader | null;
+ #remote_identity: NameAddrHeader | null;
+
+ // Whether an incoming message has been replied.
+ #is_replied: boolean;
+
+ // Custom message empty object for high level use.
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ #data: any;
+
+ constructor(ua: MessageUA) {
+ super();
+
+ this.#ua = ua;
+ this.#request = null;
+ this.#closed = false;
+
+ this.#direction = null;
+ this.#local_identity = null;
+ this.#remote_identity = null;
+
+ this.#is_replied = false;
+
+ this.#data = {};
+ }
+
+ /**
+ * Whether the message was sent or received.
+ */
+ get direction(): Direction | null {
+ return this.#direction;
+ }
+
+ /**
+ * Custom object for high level use, empty to begin with.
+ */
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ get data(): any {
+ return this.#data;
+ }
+
+ /**
+ * Set the custom object for high level use.
+ */
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ set data(data: any) {
+ this.#data = data;
+ }
+
+ /**
+ * Address of the local peer.
+ */
+ get local_identity(): NameAddrHeader | null {
+ return this.#local_identity;
+ }
+
+ /**
+ * Address of the remote peer.
+ */
+ get remote_identity(): NameAddrHeader | null {
+ return this.#remote_identity;
+ }
+
+ /**
+ * Send a MESSAGE request to the given target.
+ *
+ * @param target - Address of the remote peer.
+ * @param body - Content of the message.
+ *
+ * @throws
+ * - `TypeError` if `target` or `body` is not given, or if `target` cannot
+ * be turned into a valid SIP URI.
+ */
+ send(
+ target: string | URI,
+ body: string,
+ options: SendMessageOptions = {}
+ ): void {
+ const originalTarget = target;
+
+ if (target === undefined || body === undefined) {
+ throw new TypeError('Not enough arguments');
+ }
+
+ // Check target validity.
+ const uri = this.#ua.normalizeTarget(target);
+
+ if (!uri) {
+ throw new TypeError(`Invalid target: ${originalTarget.toString()}`);
+ }
+
+ // Get call options.
+ const extraHeaders = Utils.cloneArray(options.extraHeaders);
+ const eventHandlers = Utils.cloneObject(options.eventHandlers);
+ const contentType = options.contentType || 'text/plain';
+
+ const requestParams: OutgoingRequestParams = {};
+
+ if (options.fromUserName) {
+ requestParams.from_uri = new URI(
+ 'sip',
+ options.fromUserName,
+ this.#ua.configuration.uri.host
+ );
+
+ extraHeaders.push(
+ `P-Preferred-Identity: ${this.#ua.configuration.uri.toString()}`
+ );
+ }
+
+ if (options.fromDisplayName) {
+ requestParams.from_display_name = options.fromDisplayName;
+ }
+
+ // Set event handlers. They are registered one by one, rather than by
+ // iterating the object, so that each listener keeps the signature of the
+ // event it is registered for.
+ if (eventHandlers.succeeded) {
+ this.on('succeeded', eventHandlers.succeeded);
+ }
+
+ if (eventHandlers.failed) {
+ this.on('failed', eventHandlers.failed);
+ }
+
+ extraHeaders.push(`Content-Type: ${contentType}`);
+
+ const request = new SIPMessage.OutgoingRequest(
+ JsSIP_C.MESSAGE,
+ uri,
+ this.#ua,
+ requestParams,
+ extraHeaders
+ );
+
+ this.#request = request;
+
+ if (body) {
+ request.body = body;
+ }
+
+ const request_sender = new RequestSender(this.#ua, request, {
+ onRequestTimeout: () => {
+ this.#onRequestTimeout();
+ },
+ onTransportError: () => {
+ this.#onTransportError();
+ },
+ onReceiveResponse: response => {
+ this.#receiveResponse(response);
+ },
+ });
+
+ this.#newMessage('local', request);
+
+ request_sender.send();
+ }
+
+ /**
+ * Take over a received MESSAGE request.
+ *
+ * @remarks
+ * - Called by the `UA`. The application must not call it.
+ */
+ init_incoming(request: IncomingRequest): void {
+ this.#request = request;
+
+ this.#newMessage('remote', request);
+
+ // Reply with a 200 OK if the user didn't reply.
+ if (!this.#is_replied) {
+ this.#is_replied = true;
+ request.reply(200);
+ }
+
+ this.#close();
+ }
+
+ /**
+ * Accept the incoming message, answering it with a 200.
+ *
+ * @throws
+ * - {@link NotSupportedError} if the message is outgoing.
+ * - `Error` if the message was already replied.
+ */
+ accept(options: AcceptOptions = {}): void {
+ const extraHeaders = Utils.cloneArray(options.extraHeaders);
+ const body = options.body;
+
+ if (this.#direction !== 'incoming') {
+ throw new NotSupportedError(
+ '"accept" not supported for outgoing Message'
+ );
+ }
+
+ if (this.#is_replied) {
+ throw new Error('incoming Message already replied');
+ }
+
+ this.#is_replied = true;
+ this.#incomingRequest().reply(200, null, extraHeaders, body);
+ }
+
+ /**
+ * Reject the incoming message.
+ *
+ * @throws
+ * - {@link NotSupportedError} if the message is outgoing.
+ * - `Error` if the message was already replied.
+ * - `TypeError` if `status_code` is not between 300 and 699.
+ */
+ reject(options: RejectOptions = {}): void {
+ const status_code = options.status_code || 480;
+ const reason_phrase = options.reason_phrase;
+ const extraHeaders = Utils.cloneArray(options.extraHeaders);
+ const body = options.body;
+
+ if (this.#direction !== 'incoming') {
+ throw new NotSupportedError(
+ '"reject" not supported for outgoing Message'
+ );
+ }
+
+ if (this.#is_replied) {
+ throw new Error('incoming Message already replied');
+ }
+
+ if (status_code < 300 || status_code >= 700) {
+ throw new TypeError(`Invalid status_code: ${status_code}`);
+ }
+
+ this.#is_replied = true;
+ this.#incomingRequest().reply(
+ status_code,
+ reason_phrase,
+ extraHeaders,
+ body
+ );
+ }
+
+ /**
+ * The received request, which `accept()` and `reject()` reply to once they
+ * have checked that the message is an incoming one.
+ */
+ #incomingRequest(): IncomingRequest {
+ return this.#request as IncomingRequest;
+ }
+
+ #receiveResponse(response: IncomingResponse): void {
+ if (this.#closed) {
+ return;
+ }
+ switch (true) {
+ case /^1[0-9]{2}$/.test(String(response.status_code)): {
+ // Ignore provisional responses.
+ break;
+ }
+
+ case /^2[0-9]{2}$/.test(String(response.status_code)): {
+ this.#succeeded('remote', response);
+ break;
+ }
+
+ default: {
+ const cause = Utils.sipErrorCause(response.status_code);
+
+ this.#failed('remote', response, cause);
+ break;
+ }
+ }
+ }
+
+ #onRequestTimeout(): void {
+ if (this.#closed) {
+ return;
+ }
+ this.#failed('system', null, JsSIP_C.causes.REQUEST_TIMEOUT);
+ }
+
+ #onTransportError(): void {
+ if (this.#closed) {
+ return;
+ }
+ this.#failed('system', null, JsSIP_C.causes.CONNECTION_ERROR);
+ }
+
+ #close(): void {
+ this.#closed = true;
+ this.#ua.destroyMessage(this);
+ }
+
+ // Internal callbacks.
+
+ #newMessage(
+ originator: Originator,
+ request: SIPMessage.OutgoingRequest | IncomingRequest
+ ): void {
+ if (originator === 'remote') {
+ this.#direction = 'incoming';
+ this.#local_identity = request.to;
+ this.#remote_identity = request.from;
+ } else if (originator === 'local') {
+ this.#direction = 'outgoing';
+ this.#local_identity = request.from;
+ this.#remote_identity = request.to;
+ }
+
+ this.#ua.newMessage(this, {
+ originator,
+ message: this,
+ request,
+ });
+ }
+
+ #failed(
+ originator: Originator,
+ response: IncomingResponse | null,
+ cause: JsSIP_C.causes
+ ): void {
+ logger.debug('MESSAGE failed');
+
+ this.#close();
+
+ logger.debug('emit "failed"');
+
+ this.emit('failed', {
+ originator,
+ response: response || null,
+ cause,
+ });
+ }
+
+ #succeeded(originator: Originator, response: IncomingResponse): void {
+ logger.debug('MESSAGE succeeded');
+
+ this.#close();
+
+ logger.debug('emit "succeeded"');
+
+ this.emit('succeeded', {
+ originator,
+ response,
+ });
+ }
+}
diff --git a/src/UA.js b/src/UA.js
index 6c6f3bd..1eeb728 100644
--- a/src/UA.js
+++ b/src/UA.js
@@ -7,7 +7,7 @@ const { Registrator } = require('./Registrator');
const RTCSession = require('./RTCSession');
const Subscriber = require('./Subscriber');
const Notifier = require('./Notifier');
-const Message = require('./Message');
+const { Message } = require('./Message');
const Options = require('./Options');
const Transactions = require('./Transactions');
const { Transport } = require('./Transport');
diff --git a/src/test/test-Message.ts b/src/test/test-Message.ts
new file mode 100644
index 0000000..7f36914
--- /dev/null
+++ b/src/test/test-Message.ts
@@ -0,0 +1,214 @@
+import { setTimeout as delay } from 'timers/promises';
+
+import './include/common';
+import {
+ body,
+ buildRequest,
+ buildResponse,
+ header,
+} from './include/sipMessage';
+import TestSocket from './include/TestSocket';
+import { startUA, stopUA } from './include/ua';
+
+import { causes } from '../Constants';
+import { NotSupportedError } from '../Exceptions';
+import type { Message, MessageFailedEvent } from '../Message';
+import type { IncomingMessageEvent } from '../UA';
+import { UA } from '../JsSIP';
+
+const AOR = 'sip:alice@example.com';
+const TARGET = 'sip:bob@example.com';
+const TEXT = 'Hello there';
+
+// Answers every MESSAGE the UA sends with the given status code.
+class AnsweringSocket extends TestSocket {
+ constructor(private readonly status: number) {
+ super();
+ }
+
+ protected override onRequest(request: string): void {
+ this.receive(buildResponse(request, this.status, { toTag: 'remotetag' }));
+ }
+}
+
+// What the UA made of an outgoing MESSAGE.
+type Sent = {
+ outcome: 'succeeded' | 'failed';
+ cause?: causes;
+ // The MESSAGE as it left the UA.
+ request: string;
+};
+
+/**
+ * Sends a MESSAGE and resolves once the UA reports its outcome.
+ */
+async function sendMessage(status: number): Promise<Sent> {
+ const socket = new AnsweringSocket(status);
+ const ua = new UA({ sockets: socket, uri: AOR, register: false });
+
+ await startUA(ua);
+
+ const outcome = await new Promise<Omit<Sent, 'request'>>(resolve => {
+ ua.sendMessage(TARGET, TEXT, {
+ eventHandlers: {
+ succeeded: () => resolve({ outcome: 'succeeded' }),
+ failed: ({ cause }: MessageFailedEvent) =>
+ resolve({ outcome: 'failed', cause }),
+ },
+ });
+ });
+
+ await stopUA(ua);
+
+ return { ...outcome, request: socket.requests('MESSAGE')[0]! };
+}
+
+describe('outgoing MESSAGE', () => {
+ test('a 200 reports "succeeded"', async () => {
+ const sent = await sendMessage(200);
+
+ expect(sent.outcome).toBe('succeeded');
+ });
+
+ test('the request carries the body and the default content type', async () => {
+ const sent = await sendMessage(200);
+
+ expect(body(sent.request)).toBe(TEXT);
+ expect(header(sent.request, 'Content-Type')).toBe('text/plain');
+ });
+
+ test('a 404 reports "failed" with the mapped cause', async () => {
+ const sent = await sendMessage(404);
+
+ expect(sent.outcome).toBe('failed');
+ expect(sent.cause).toBe(causes.NOT_FOUND);
+ });
+
+ test('a 486 reports "failed" with the mapped cause', async () => {
+ const sent = await sendMessage(486);
+
+ expect(sent.outcome).toBe('failed');
+ expect(sent.cause).toBe(causes.BUSY);
+ });
+
+ test('accept() and reject() are refused on an outgoing message', async () => {
+ const socket = new AnsweringSocket(200);
+ const ua = new UA({ sockets: socket, uri: AOR, register: false });
+
+ await startUA(ua);
+
+ const message = ua.sendMessage(TARGET, TEXT);
+
+ expect(() => message.accept()).toThrow(NotSupportedError);
+ expect(() => message.reject()).toThrow(NotSupportedError);
+
+ await stopUA(ua);
+ });
+
+ /* NOTE: `normalizeTarget()` coerces most strings into a SIP URI by taking
+ * them as the user part, so a target only fails when the result cannot be
+ * parsed, such as one with an empty host.
+ */
+ test('a target that is not a valid SIP URI is refused', async () => {
+ const socket = new AnsweringSocket(200);
+ const ua = new UA({ sockets: socket, uri: AOR, register: false });
+
+ await startUA(ua);
+
+ expect(() => ua.sendMessage('bob@', TEXT)).toThrow(TypeError);
+ expect(() => ua.sendMessage('', TEXT)).toThrow(TypeError);
+
+ await stopUA(ua);
+ });
+});
+
+// A socket that only records what the UA writes.
+class PlainSocket extends TestSocket {}
+
+/**
+ * Feeds the UA a MESSAGE and returns the status code it is answered with,
+ * letting the application react through `newMessage` first.
+ */
+async function receiveMessage(
+ onNewMessage?: (message: Message) => void
+): Promise<{ status: number | undefined; seen?: string; error?: unknown }> {
+ const callId = 'the-call-id';
+ const socket = new PlainSocket();
+ const ua = new UA({ sockets: socket, uri: AOR, register: false });
+
+ let seen: string | undefined;
+ let error: unknown;
+
+ /* NOTE: The listener runs synchronously within the transport callback, so
+ * anything it throws would escape into a timer instead of reaching the
+ * test. Catch it here and report it back.
+ */
+ ua.on('newMessage', ({ message, request }: IncomingMessageEvent) => {
+ seen = request.body;
+
+ try {
+ onNewMessage?.(message);
+ } catch (caught) {
+ error = caught;
+ }
+ });
+
+ await startUA(ua);
+
+ socket.receive(
+ buildRequest('MESSAGE', AOR, {
+ from: `<${TARGET}>;tag=remotetag`,
+ to: `<${AOR}>`,
+ callId,
+ cseq: 1,
+ contentType: 'text/plain',
+ body: TEXT,
+ })
+ );
+
+ await delay(50);
+ await stopUA(ua);
+
+ return { status: socket.statusFor(callId), seen, error };
+}
+
+describe('incoming MESSAGE', () => {
+ test('is reported through "newMessage" with its body', async () => {
+ const received = await receiveMessage();
+
+ expect(received.seen).toBe(TEXT);
+ });
+
+ test('is answered 200 when the application does not reply', async () => {
+ const received = await receiveMessage();
+
+ expect(received.status).toBe(200);
+ });
+
+ test('reject() answers with the given status code', async () => {
+ const received = await receiveMessage(message =>
+ message.reject({ status_code: 603 })
+ );
+
+ expect(received.status).toBe(603);
+ });
+
+ test('accept() answers 200', async () => {
+ const received = await receiveMessage(message => message.accept());
+
+ expect(received.status).toBe(200);
+ });
+
+ test('replying twice is refused', async () => {
+ const received = await receiveMessage(message => {
+ message.accept();
+ message.accept();
+ });
+
+ expect(received.error).toBeInstanceOf(Error);
+ expect(received.error).toHaveProperty(
+ 'message',
+ 'incoming Message already replied'
+ );
+ });
+});