Commit dfeda8c for jssip.net
commit dfeda8c8ddde715debd787594eb6a2d808d21c70
Author: José Luis Millán <jmillan@aliax.net>
Date: Wed Dec 2 12:16:19 2026 +0100
Documentation
Added documentation for the new .ts files.
diff --git a/.github/workflows/jssip.yaml b/.github/workflows/jssip.yaml
index 9b1dc32..43d21ab 100644
--- a/.github/workflows/jssip.yaml
+++ b/.github/workflows/jssip.yaml
@@ -58,3 +58,6 @@ jobs:
- name: npm run test
run: npm run test
+
+ - name: npm run docs:check
+ run: npm run docs:check
diff --git a/README.md b/README.md
index 4614e5e..2e56572 100644
--- a/README.md
+++ b/README.md
@@ -1,5 +1,6 @@
[![][npm-shield-jssip]][npm-jssip]
[![][github-actions-shield-jssip]][github-actions-jssip]
+[![][github-actions-shield-docs]][github-actions-docs]
<p align="center"><a href="https://jssip.net"><img src="https://jssip.net/images/jssip-banner-new.png"/></a></p>
@@ -10,13 +11,14 @@
* Audio/video calls ([WebRTC](https://jssip.net/documentation/misc/webrtc)) and instant messaging
* Lightweight!
* Easy to use and powerful user API
-* Works with Kamailio, Asterisk. Mobicents and repro (reSIProcate) servers ([more info](https://jssip.net/documentation/misc/interoperability))
+* Works with any SIP server supporting SIP over WebSockets.
* Written by the authors of [RFC 7118 "The WebSocket Protocol as a Transport for SIP"](https://tools.ietf.org/html/rfc7118) and [mediasoup](https://mediasoup.org)
## Website and Documentation
-[jssip.net](https://jssip.net/)
+* [jssip.net](https://jssip.net/)
+* [API documentation](https://versatica.github.io/JsSIP/)
## Install
@@ -69,11 +71,6 @@ var session = ua.call('sip:bob@example.com', options);
Want to see more? Check the full documentation at https://jssip.net/documentation/.
-## Online Demo
-
-[tryit.jssip.net](https://tryit.jssip.net)
-
-
## Support
* For questions or usage problems please use [Github discussions](https://github.com/versatica/JsSIP/discussions).
@@ -107,3 +104,5 @@ JsSIP is released under the [MIT license](https://jssip.net/license).
[npm-jssip]: https://npmjs.org/package/jssip
[github-actions-shield-jssip]: https://github.com/versatica/jssip/actions/workflows/jssip.yaml/badge.svg
[github-actions-jssip]: https://github.com/versatica/jssip/actions/workflows/jssip.yaml
+[github-actions-shield-docs]: https://github.com/versatica/jssip/actions/workflows/docs.yaml/badge.svg
+[github-actions-docs]: https://github.com/versatica/jssip/actions/workflows/docs.yaml
diff --git a/docs-assets/custom-styles.css b/docs-assets/custom-styles.css
index 0fe534a..b729c3c 100644
--- a/docs-assets/custom-styles.css
+++ b/docs-assets/custom-styles.css
@@ -1,21 +1,42 @@
-/* Remove ugly square in bottom-right corner when scroll shows up. */
-*::-webkit-scrollbar {
- width: 0px;
-}
-
-/* Add margin after code. */
+/**
+ * Add margin after code.
+ */
.tsd-comment {
margin-bottom: 2em;
}
-/* Avoid word wrapping when code doesn't fit into avaiable width. */
+/**
+ * Avoid word wrapping when code doesn't fit into avaiable width.
+ * Useful for SIP message examples.
+ */
.tsd-comment > pre {
white-space: pre;
- overflow: scroll;
+ overflow-x: auto;
}
-/* Remove ugly border radius in code. */
-.tsd-comment > pre,
-.tsd-comment > code {
+/**
+ * Remove ugly border radius in code.
+ */
+.tsd-comment pre,
+.tsd-comment code {
border-radius: 0px;
}
+
+/**
+ * Label the menu trigger (only shown by TypeDoc in mobile) so users know the
+ * API is there.
+ */
+#tsd-toolbar-menu-trigger {
+ width: auto;
+ padding: 0 0.5rem;
+}
+
+#tsd-toolbar-menu-trigger svg {
+ vertical-align: middle;
+}
+
+#tsd-toolbar-menu-trigger::after {
+ content: 'API';
+ margin-left: 0.4em;
+ font-weight: bold;
+}
diff --git a/src/Configuration.ts b/src/Configuration.ts
index 8516ea1..bec5f29 100644
--- a/src/Configuration.ts
+++ b/src/Configuration.ts
@@ -12,72 +12,251 @@ import type { WeightedSocket } from './Socket';
import { createRandomToken, isDecimal, isEmpty } from './Utils';
import URI = require('./URI');
+// TODO: `UA` mutates this object in ways this type cannot express: it deletes
+// `sockets`, adds `jssip_id` and `hostport_params`, and rewrites
+// `no_answer_timeout` from seconds into milliseconds. It should derive its own
+// value from this one instead of mutating it.
+
/**
- * The working configuration of a `UA`, as built from the defaults below and
- * the values given by the application.
+ * What a UA is configured with.
+ *
+ * Only {@link Configuration.uri} and {@link Configuration.sockets} are
+ * mandatory. Every other parameter falls back to the default documented on
+ * it.
*
- * TODO: `UA` then mutates this object in ways this type cannot express: it
- * deletes `sockets`, adds `jssip_id` and `hostport_params`, and rewrites
- * `no_answer_timeout` from seconds into milliseconds. It should derive its own
- * value from this one instead of mutating it.
+ * @example
+ * ```ts
+ * const ua = new JsSIP.UA({
+ * uri: 'sip:alice@example.com',
+ * sockets: new JsSIP.WebSocketInterface('wss://sip.example.com'),
+ * password: 'secret',
+ * });
+ * ```
*/
export type Configuration = {
- // SIP authentication.
+ /**
+ * Username used to authenticate, when it differs from the user part of
+ * {@link Configuration.uri}.
+ *
+ * @defaultValue `null`
+ */
authorization_user: string | null;
+ /**
+ * The plain SIP authentication password.
+ *
+ * @defaultValue `null`
+ *
+ * @remarks
+ * - It is deleted from memory after the first successful authentication,
+ * the resulting {@link Configuration.ha1} and {@link Configuration.realm}
+ * being stored instead.
+ */
password: string | null;
+ /**
+ * SIP authentication realm.
+ *
+ * @defaultValue `null`
+ *
+ * @remarks
+ * - Only useful when the plain {@link Configuration.password} is not
+ * given, in which case {@link Configuration.ha1} is required too.
+ */
realm: string | null;
+ /**
+ * `HA1` hash of the credentials, for Digest authentication.
+ *
+ * @defaultValue `null`
+ *
+ * @remarks
+ * - When given, and the plain {@link Configuration.password} is not,
+ * {@link Configuration.realm} is required too. Authentication is not
+ * feasible otherwise.
+ */
ha1: string | null;
+ /**
+ * Token used as authentication credential. Every outgoing request carries
+ * an Authorization header field with the Bearer scheme and this value.
+ *
+ * @defaultValue `null`
+ */
authorization_jwt: string | null;
- // SIP account.
/**
- * NOTE: A number because `UA` allows a `0` to be given, which it then turns
- * into '0'.
+ * Descriptive name shown to the called party when calling or sending
+ * messages.
+ *
+ * @defaultValue `null`
+ *
+ * @remarks
+ * - It must NOT be enclosed between double quotes, even when it contains
+ * multi-byte symbols. The library always encloses it.
+ * - A number is accepted because a `0` is a legitimate display name, which
+ * `UA` turns into `'0'`.
*/
display_name: string | number | null;
+ /**
+ * Address of record of the UA, so its SIP address. The only mandatory
+ * parameter together with {@link Configuration.sockets}.
+ *
+ * @defaultValue `null`
+ */
uri: URI | null;
+ /**
+ * URI to be used in the Contact header field.
+ *
+ * @defaultValue `null`
+ *
+ * @remarks
+ * - Its host becomes {@link Configuration.via_host}. When it is not given,
+ * the Contact is built out of `via_host` instead.
+ */
contact_uri: URI | null;
- // SIP instance id (GRUU).
+ /**
+ * UUID identifying this UA instance when using GRUU, announced in the
+ * `+sip.instance` Contact parameter.
+ *
+ * @defaultValue `null`
+ *
+ * @remarks
+ * - Accepted with or without the `uuid:` prefix.
+ * - A random UUID is used when it is not given.
+ */
instance_id: string | null;
- // Preloaded SIP Route header field.
+ /**
+ * Whether every initial request carries a Route header field with the SIP
+ * URI of the server. Some SIP outbound proxies require it.
+ *
+ * @defaultValue `false`
+ */
use_preloaded_route: boolean;
- // Session parameters.
+ /**
+ * Whether to run the session timers of
+ * [RFC 4028](https://datatracker.ietf.org/doc/html/rfc4028), which keep a
+ * session alive by refreshing it.
+ *
+ * @defaultValue `true`
+ */
session_timers: boolean;
+ /**
+ * Request method used to refresh a session, either `UPDATE` or `INVITE`.
+ *
+ * @defaultValue `'UPDATE'`
+ */
session_timers_refresh_method: string;
+ /**
+ * Whether to force being the refresher of the session timers of outgoing
+ * calls, which adds the `refresher=uac` parameter to the Session-Expires
+ * header field of the initial INVITE.
+ *
+ * @defaultValue `false`
+ */
session_timers_force_refresher: boolean;
+ /**
+ * Time (in seconds) after which an incoming call is rejected if not
+ * answered.
+ *
+ * @defaultValue `60`
+ */
no_answer_timeout: number;
- // Registration parameters.
+ /**
+ * Whether to register as soon as the UA starts.
+ *
+ * @defaultValue `true`
+ */
register: boolean;
+ /**
+ * How long (in seconds) a registration lasts before the UA refreshes it.
+ *
+ * @defaultValue `600`
+ */
register_expires: number;
+ /**
+ * Trail added to the tag of the From header field of each REGISTER
+ * request, either a static string or a function returning one.
+ *
+ * @defaultValue `''`
+ */
register_from_tag_trail: string | (() => string);
+ /**
+ * URI of the registrar, which must be a SIP URI without username.
+ *
+ * @defaultValue `null`
+ *
+ * @remarks
+ * - When not given it is taken from {@link Configuration.uri} by removing
+ * its username.
+ */
registrar_server: URI | null;
- // Connection options.
+ /**
+ * Transports the UA connects through. The only mandatory parameter
+ * together with {@link Configuration.uri}.
+ *
+ * @defaultValue `null`
+ *
+ * @remarks
+ * - A single {@link Socket}, an array of them, or an array of
+ * {@link WeightedSocket} to give each one a preference.
+ */
sockets: WeightedSocket[] | null;
+ /**
+ * Maximum interval (in seconds) between transport reconnection attempts.
+ *
+ * @defaultValue `30`
+ */
connection_recovery_max_interval: number;
+ /**
+ * Minimum interval (in seconds) between transport reconnection attempts.
+ *
+ * @defaultValue `2`
+ */
connection_recovery_min_interval: number;
- // Global extra headers, to be added to every request and response
+ /**
+ * Custom SIP header fields added to every request and response.
+ *
+ * @defaultValue `null`
+ */
extra_headers: string[] | null;
/**
- * Host address. Value to be set in Via sent_by and host part of Contact
- * FQDN.
+ * Host announced in the `sent-by` of the Via header field and in the host
+ * part of the Contact.
+ *
+ * @defaultValue A random `.invalid` host name
+ *
+ * @remarks
+ * - Overwritten by the host of {@link Configuration.contact_uri} when that
+ * one is given.
*/
via_host: string;
/**
- * NOTE: Optional because, unlike every other parameter, it has no default
- * below. It only exists once the application configures it.
+ * Value of the User-Agent header field present in SIP messages. By
+ * default `JsSIP` followed by the code version, as
+ * {@link Constants.USER_AGENT} gives it.
+ *
+ * @remarks
+ * - Optional because, unlike every other parameter, it has no default. It
+ * only exists once the application configures it.
*/
user_agent?: string;
};
-// Default values.
+/**
+ * The value every {@link Configuration} parameter takes when the application
+ * does not give one.
+ *
+ * @remarks
+ * - The defaults are documented on each parameter of {@link Configuration}.
+ * This object is the one `UA` starts from.
+ *
+ * @internal
+ */
export const DEFAULT_CONFIGURATION: Configuration = {
// SIP authentication.
authorization_user: null,
@@ -424,6 +603,20 @@ function assign<K extends keyof Configuration>(
(dst as Record<K, Configuration[K]>)[key] = value;
}
+/**
+ * Validate what the application configured and copy it into the working
+ * configuration of the UA.
+ *
+ * @param dst - The working configuration, which starts as a copy of
+ * {@link DEFAULT_CONFIGURATION} and is filled in place.
+ * @param src - What the application gave to the UA.
+ *
+ * @throws
+ * - `ConfigurationError` if a mandatory parameter is missing or any given
+ * parameter is invalid.
+ *
+ * @internal
+ */
export const load = (
dst: Configuration,
src: Record<string, unknown>
diff --git a/src/Constants.ts b/src/Constants.ts
index 93ac385..40ef7fe 100644
--- a/src/Constants.ts
+++ b/src/Constants.ts
@@ -4,44 +4,144 @@
// eslint-disable-next-line @typescript-eslint/no-require-imports
const pkg = require('../package.json') as { title: string; version: string };
+/**
+ * Value of the User-Agent header field of outgoing requests, unless the
+ * `user_agent` configuration parameter overrides it.
+ */
export const USER_AGENT = `${pkg.title} ${pkg.version}`;
-// SIP scheme.
+/**
+ * The `sip` URI scheme.
+ */
export const SIP = 'sip';
+
+/**
+ * The `sips` URI scheme, which asks for the request to travel over TLS.
+ */
export const SIPS = 'sips';
-// End and Failure causes.
+/**
+ * Why a session, a registration or a message ended or failed.
+ *
+ * Reported in the `cause` field of the `failed` and `ended` events, together
+ * with the `originator` telling which side caused it.
+ *
+ * @example
+ * ```ts
+ * session.on('failed', ({ cause }) => {
+ * if (cause === JsSIP.C.causes.BUSY) {
+ * console.log('the callee is busy');
+ * }
+ * });
+ * ```
+ */
export enum causes {
- // Generic error causes.
+ /**
+ * The transport could not be established or was lost.
+ */
CONNECTION_ERROR = 'Connection Error',
+ /**
+ * No response arrived before the transaction timed out.
+ */
REQUEST_TIMEOUT = 'Request Timeout',
+ /**
+ * A SIP failure response arrived that maps to no more specific cause.
+ */
SIP_FAILURE_CODE = 'SIP Failure Code',
+ /**
+ * The library failed to carry the operation out.
+ */
INTERNAL_ERROR = 'Internal Error',
- // SIP error causes.
+ /**
+ * The callee is busy. Reported for a 486 or 600 response.
+ */
BUSY = 'Busy',
+ /**
+ * The request was declined. Reported for a 403 or 603 response.
+ */
REJECTED = 'Rejected',
+ /**
+ * The callee moved. Reported for a 300, 301, 302, 305 or 380 response.
+ */
REDIRECTED = 'Redirected',
+ /**
+ * The callee is temporarily unreachable. Reported for a 408, 410, 430 or
+ * 480 response.
+ */
UNAVAILABLE = 'Unavailable',
+ /**
+ * The callee does not exist. Reported for a 404 or 604 response.
+ */
NOT_FOUND = 'Not Found',
+ /**
+ * The address is incomplete. Reported for a 424 or 484 response.
+ */
ADDRESS_INCOMPLETE = 'Address Incomplete',
+ /**
+ * The peers found no common media. Reported for a 488 or 606 response.
+ */
INCOMPATIBLE_SDP = 'Incompatible SDP',
+ /**
+ * A session description was expected in the message and it carried none.
+ */
MISSING_SDP = 'Missing SDP',
+ /**
+ * The credentials were rejected, or none were configured for a 401 or 407
+ * response.
+ */
AUTHENTICATION_ERROR = 'Authentication Error',
- // Session error causes.
+ /**
+ * The session was ended with a BYE.
+ */
BYE = 'Terminated',
+ /**
+ * The WebRTC stack failed, for instance while negotiating or while
+ * applying a session description.
+ */
WEBRTC_ERROR = 'WebRTC Error',
+ /**
+ * The session was cancelled by the local or the remote peer.
+ */
CANCELED = 'Canceled',
+ /**
+ * The incoming call was not answered within the time given by the
+ * `no_answer_timeout` configuration parameter.
+ */
NO_ANSWER = 'No Answer',
+ /**
+ * The incoming call carried an Expires header field and the local user did
+ * not answer within the time it gave.
+ */
EXPIRES = 'Expires',
+ /**
+ * The ACK to the 2xx response to the INVITE never arrived.
+ */
NO_ACK = 'No ACK',
+ /**
+ * An in-dialog request failed in a way that ends the dialog, so a 408 or
+ * 481 response to it.
+ */
DIALOG_ERROR = 'Dialog Error',
+ /**
+ * The user refused to grant access to the camera or the microphone.
+ */
USER_DENIED_MEDIA_ACCESS = 'User Denied Media Access',
+ /**
+ * The session description could not be parsed or applied.
+ */
BAD_MEDIA_DESCRIPTION = 'Bad Media Description',
+ /**
+ * The session ended due to loss of RTP.
+ */
RTP_TIMEOUT = 'RTP Timeout',
}
+/**
+ * The SIP response codes each {@link causes} member is reported for, indexed
+ * by the name of the cause.
+ */
export const SIP_ERROR_CAUSES: Record<string, number[]> = {
REDIRECTED: [300, 301, 302, 305, 380],
BUSY: [486, 600],
@@ -53,31 +153,93 @@ export const SIP_ERROR_CAUSES: Record<string, number[]> = {
AUTHENTICATION_ERROR: [401, 407],
};
-// SIP Methods.
+/**
+ * The ACK request method.
+ */
export const ACK = 'ACK';
+
+/**
+ * The BYE request method.
+ */
export const BYE = 'BYE';
+
+/**
+ * The CANCEL request method.
+ */
export const CANCEL = 'CANCEL';
+
+/**
+ * The INFO request method.
+ */
export const INFO = 'INFO';
+
+/**
+ * The INVITE request method.
+ */
export const INVITE = 'INVITE';
+
+/**
+ * The MESSAGE request method.
+ */
export const MESSAGE = 'MESSAGE';
+
+/**
+ * The NOTIFY request method.
+ */
export const NOTIFY = 'NOTIFY';
+
+/**
+ * The OPTIONS request method.
+ */
export const OPTIONS = 'OPTIONS';
+
+/**
+ * The REGISTER request method.
+ */
export const REGISTER = 'REGISTER';
+
+/**
+ * The REFER request method.
+ */
export const REFER = 'REFER';
+
+/**
+ * The UPDATE request method.
+ */
export const UPDATE = 'UPDATE';
+
+/**
+ * The SUBSCRIBE request method.
+ */
export const SUBSCRIBE = 'SUBSCRIBE';
-// DTMF transport methods.
+/**
+ * How DTMF tones are sent within a session.
+ *
+ * @example
+ * ```ts
+ * session.sendDTMF('1234', { transportType: JsSIP.C.DTMF_TRANSPORT.RFC2833 });
+ * ```
+ */
export enum DTMF_TRANSPORT {
+ /**
+ * In an INFO request carrying an `application/dtmf-relay` body.
+ */
// eslint-disable-next-line no-shadow
INFO = 'INFO',
+ /**
+ * In the media stream, as the RTP payload defined by
+ * [RFC 2833](https://datatracker.ietf.org/doc/html/rfc2833).
+ */
RFC2833 = 'RFC2833',
}
/**
- * SIP Response Reasons
- * DOC: https://www.iana.org/assignments/sip-parameters
- * Copied from https://github.com/versatica/OverSIP/blob/master/lib/oversip/sip/constants.rb#L7
+ * The reason phrase the library puts in a response, indexed by status code.
+ *
+ * @remarks
+ * - Taken from the
+ * [IANA SIP parameters registry](https://www.iana.org/assignments/sip-parameters).
*/
export const REASON_PHRASE: Record<number, string> = {
100: 'Trying',
@@ -154,11 +316,47 @@ export const REASON_PHRASE: Record<number, string> = {
606: 'Not Acceptable',
};
+/**
+ * Value of the Allow header field of outgoing messages, so the request
+ * methods the library accepts.
+ */
export const ALLOWED_METHODS =
'INVITE,ACK,CANCEL,BYE,UPDATE,MESSAGE,OPTIONS,REFER,INFO,NOTIFY,SUBSCRIBE';
+
+/**
+ * Value of the Accept header field of outgoing messages, so the body types
+ * the library accepts.
+ */
export const ACCEPTED_BODY_TYPES = 'application/sdp, application/dtmf-relay';
+
+/**
+ * Value of the Max-Forwards header field of outgoing requests.
+ */
export const MAX_FORWARDS = 69;
+
+/**
+ * Default session interval (in seconds) proposed in the Session-Expires
+ * header field, as defined by
+ * [RFC 4028](https://datatracker.ietf.org/doc/html/rfc4028).
+ */
export const SESSION_EXPIRES = 90;
+
+/**
+ * Lowest session interval (in seconds) the library accepts, announced in the
+ * Min-SE header field.
+ */
export const MIN_SESSION_EXPIRES = 60;
+
+/**
+ * Longest the UA waits (in seconds) before retrying a lost transport, unless
+ * the `connection_recovery_max_interval` configuration parameter overrides
+ * it.
+ */
export const CONNECTION_RECOVERY_MAX_INTERVAL = 30;
+
+/**
+ * Shortest the UA waits (in seconds) before retrying a lost transport, unless
+ * the `connection_recovery_min_interval` configuration parameter overrides
+ * it.
+ */
export const CONNECTION_RECOVERY_MIN_INTERVAL = 2;
diff --git a/src/Exceptions.ts b/src/Exceptions.ts
index 16e736e..a508508 100644
--- a/src/Exceptions.ts
+++ b/src/Exceptions.ts
@@ -1,10 +1,41 @@
+/**
+ * Error during UA configuration object load.
+ *
+ * @example
+ * ```ts
+ * try {
+ * const ua = new JsSIP.UA({ sockets: socket, uri: 'not a sip uri' });
+ * } catch (error) {
+ * if (error instanceof JsSIP.Exceptions.ConfigurationError) {
+ * console.error(error.parameter, error.value);
+ * }
+ * }
+ * ```
+ */
export class ConfigurationError extends Error {
+ /**
+ * Numeric identifier of this error, so that it can be told apart without
+ * relying on `instanceof`.
+ */
code = 1;
+ /**
+ * Always `CONFIGURATION_ERROR`.
+ */
override name = 'CONFIGURATION_ERROR';
+ /**
+ * Name of the offending configuration parameter.
+ */
parameter: string;
+ /**
+ * Value the application gave for it, `undefined` when it was missing.
+ */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
value: any;
+ /**
+ * @param parameter - Name of the offending configuration parameter.
+ * @param value - Value the application gave for it, if any.
+ */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
constructor(parameter: string, value?: any) {
super();
@@ -17,11 +48,27 @@ export class ConfigurationError extends Error {
}
}
+/**
+ * The object is in an unappropriate state to execute the given action.
+ */
export class InvalidStateError extends Error {
+ /**
+ * Numeric identifier of this error, so that it can be told apart without
+ * relying on `instanceof`.
+ */
code = 2;
+ /**
+ * Always `INVALID_STATE_ERROR`.
+ */
override name = 'INVALID_STATE_ERROR';
+ /**
+ * The state the object was in when the operation was requested.
+ */
status: number;
+ /**
+ * @param status - The state the object was in.
+ */
constructor(status: number) {
super();
@@ -30,10 +77,23 @@ export class InvalidStateError extends Error {
}
}
+/**
+ * The requested action is not supported.
+ */
export class NotSupportedError extends Error {
+ /**
+ * Numeric identifier of this error, so that it can be told apart without
+ * relying on `instanceof`.
+ */
code = 3;
+ /**
+ * Always `NOT_SUPPORTED_ERROR`.
+ */
override name = 'NOT_SUPPORTED_ERROR';
+ /**
+ * @param message - What is not supported.
+ */
constructor(message: string) {
super();
@@ -41,10 +101,23 @@ export class NotSupportedError extends Error {
}
}
+/**
+ * The UA is not ready to execute the given action.
+ */
export class NotReadyError extends Error {
+ /**
+ * Numeric identifier of this error, so that it can be told apart without
+ * relying on `instanceof`.
+ */
code = 4;
+ /**
+ * Always `NOT_READY_ERROR`.
+ */
override name = 'NOT_READY_ERROR';
+ /**
+ * @param message - Why the UA is not ready.
+ */
constructor(message: string) {
super();
diff --git a/src/NameAddrHeader.ts b/src/NameAddrHeader.ts
index 87953ce..417fab8 100644
--- a/src/NameAddrHeader.ts
+++ b/src/NameAddrHeader.ts
@@ -1,10 +1,39 @@
import * as Grammar from './Grammar';
import URI = require('./URI');
+/**
+ * Represents a `name-addr` or an `addr-spec` value as stated in the BNF
+ * grammar of [RFC 3261](https://datatracker.ietf.org/doc/html/rfc3261).
+ *
+ * A `name-addr` value is in the form `"display name" <URI>`. An `addr-spec`
+ * value is in the form `URI`.
+ *
+ * @remarks
+ * - Its parameters are those of the header field, not those of the URI. The
+ * latter live in the {@link URI} reachable through
+ * {@link NameAddrHeader.uri}.
+ *
+ * @example
+ * ```ts
+ * const uri = new JsSIP.URI('sip', 'alice', 'example.com');
+ * const from = new JsSIP.NameAddrHeader(uri, 'Alice');
+ *
+ * from.setParam('tag', '1928301774');
+ *
+ * from.toString(); // '"Alice" <sip:alice@example.com>;tag=1928301774'
+ * ```
+ */
class NameAddrHeader {
/**
- * Parse the given string and returns a NameAddrHeader instance or undefined if
- * it is an invalid NameAddrHeader.
+ * Parse the given string into a {@link NameAddrHeader}.
+ *
+ * @returns `undefined` if the string is not a valid name address header
+ * field value.
+ *
+ * @example
+ * ```ts
+ * const to = JsSIP.NameAddrHeader.parse('"Bob" <sip:bob@example.com>');
+ * ```
*/
static parse(name_addr_header: string): NameAddrHeader | undefined {
const parsed = Grammar.parse(name_addr_header, 'Name_Addr_Header') as
@@ -22,6 +51,15 @@ class NameAddrHeader {
#display_name?: string;
#parameters: URI.Parameters;
+ /**
+ * @param uri - Address the header field points at.
+ * @param display_name - Display name shown before the address, if any.
+ * @param parameters - Header field parameters, added through
+ * {@link NameAddrHeader.setParam}.
+ *
+ * @throws
+ * - `TypeError` if `uri` is not a {@link URI}.
+ */
constructor(
uri: URI,
display_name?: string,
@@ -44,18 +82,48 @@ class NameAddrHeader {
}
}
+ /**
+ * Address the header field points at.
+ *
+ * @remarks
+ * - Read only, but the {@link URI} itself can be modified.
+ */
get uri(): URI {
return this.#uri;
}
+ /**
+ * Display name shown before the address, `undefined` when the header field
+ * has none.
+ */
get display_name(): string | undefined {
return this.#display_name;
}
+ /**
+ * Set the display name, or remove it by giving `undefined`.
+ *
+ * @remarks
+ * - A number is accepted and converted into a string.
+ * - It is quoted and escaped by {@link NameAddrHeader.toString}, so it must
+ * be given unquoted.
+ */
set display_name(value: string | number | undefined) {
this.#display_name = value === 0 ? '0' : (value as string | undefined);
}
+ /**
+ * Set the given header field parameter.
+ *
+ * @param key - Parameter name, lowercased.
+ * @param value - Parameter value. A parameter with no value is set by
+ * giving `null` or nothing.
+ *
+ * @example
+ * ```ts
+ * nameAddrHeader.setParam('tag', '1928301774');
+ * ```
+ */
setParam(key: string, value?: string | number | null): void {
if (key) {
this.#parameters[key.toLowerCase()] =
@@ -65,6 +133,12 @@ class NameAddrHeader {
}
}
+ /**
+ * Get the value of the given header field parameter.
+ *
+ * @returns `null` if the parameter has no value, `undefined` if the header
+ * field does not have it.
+ */
getParam(key: string): string | null | undefined {
if (key) {
return this.#parameters[key.toLowerCase()];
@@ -73,6 +147,11 @@ class NameAddrHeader {
return undefined;
}
+ /**
+ * Whether the header field has the given parameter.
+ *
+ * @returns `undefined` if no parameter name is given.
+ */
hasParam(key: string): boolean | undefined {
if (key) {
return (
@@ -88,6 +167,12 @@ class NameAddrHeader {
return undefined;
}
+ /**
+ * Remove the given header field parameter.
+ *
+ * @returns The value it had, `null` if it had none, `undefined` if the
+ * header field did not have the parameter.
+ */
deleteParam(parameter: string): string | null | undefined {
parameter = parameter.toLowerCase();
if (Object.prototype.hasOwnProperty.call(this.#parameters, parameter)) {
@@ -101,10 +186,18 @@ class NameAddrHeader {
return undefined;
}
+ /**
+ * Remove every header field parameter.
+ */
clearParams(): void {
this.#parameters = {};
}
+ /**
+ * A copy of the header field value that shares nothing with it, its
+ * {@link URI} included, so that either can be modified without affecting
+ * the other.
+ */
clone(): NameAddrHeader {
return new NameAddrHeader(
this.#uri.clone(),
@@ -117,6 +210,17 @@ class NameAddrHeader {
return str.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
}
+ /**
+ * The header field value as it is written in a SIP message, with the
+ * display name quoted, the address between angle brackets and the
+ * parameters appended.
+ *
+ * @example
+ * ```ts
+ * nameAddrHeader.toString();
+ * // '"Alice" <sip:alice@example.com>;tag=1928301774'
+ * ```
+ */
toString(): string {
let body = this.#display_name
? `"${this.#quote(this.#display_name)}" `
diff --git a/src/SIPMessage.ts b/src/SIPMessage.ts
index 3aa0a2a..cf49b92 100644
--- a/src/SIPMessage.ts
+++ b/src/SIPMessage.ts
@@ -29,8 +29,18 @@ const logger = new Logger('SIPMessage');
* A single media description of a parsed SDP.
*/
export type SDPMediaDescription = {
+ /**
+ * Media type, such as `audio` or `video`.
+ */
type: string;
+ /**
+ * Direction attribute of the media description, such as `sendrecv` or
+ * `inactive`. Only set when the media description carries one.
+ */
direction?: string;
+ /**
+ * Every other attribute, as `sdp-transform` returns it.
+ */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[key: string]: any;
};
@@ -39,8 +49,18 @@ export type SDPMediaDescription = {
* An SDP as returned by `sdp-transform`'s `parse()`.
*/
export type SDP = {
+ /**
+ * Media descriptions of the session, one per `m=` line.
+ */
media: SDPMediaDescription[];
+ /**
+ * Direction attribute of the session, only set when the session level
+ * carries one.
+ */
direction?: string;
+ /**
+ * Every other attribute, as `sdp-transform` returns it.
+ */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[key: string]: any;
};
@@ -57,7 +77,14 @@ export type OutgoingHeaderValue = string | number;
* A header entry as stored by an `IncomingMessage`.
*/
export type IncomingHeader = {
+ /**
+ * Value of the header field, as it arrived on the wire.
+ */
raw: string;
+ /**
+ * Parsed value, only set once the header field has been read through
+ * {@link IncomingMessage.parseHeader}.
+ */
parsed?: Grammar.Grammar;
};
@@ -65,14 +92,42 @@ export type IncomingHeader = {
* Parameters that take priority over the `ua.configuration` ones.
*/
export type OutgoingRequestParams = {
+ /**
+ * Sequence number of the CSeq header field. A random one when not given.
+ */
cseq?: number;
+ /**
+ * Value of the Call-ID header field. A random one when not given.
+ */
call_id?: string;
+ /**
+ * Address of the From header field. The one the UA is configured with when
+ * not given.
+ */
from_uri?: URI;
+ /**
+ * Tag parameter of the From header field. A random one when not given.
+ */
from_tag?: string;
+ /**
+ * Display name of the From header field.
+ */
from_display_name?: string;
+ /**
+ * Address of the To header field. The Request-URI when not given.
+ */
to_uri?: URI;
+ /**
+ * Tag parameter of the To header field.
+ */
to_tag?: string;
+ /**
+ * Display name of the To header field.
+ */
to_display_name?: string;
+ /**
+ * Values of the Route header field, in the order they are written.
+ */
route_set?: OutgoingHeaderValue[];
};
@@ -89,6 +144,8 @@ export type OutgoingRequestParams = {
*
* TODO: Replace with `import type { InviteClientTransaction } from
* './Transactions'` once `Transactions` is ported to TypeScript.
+ *
+ * @internal
*/
export interface ClientTransactionLike {
cancel(reason?: string): void;
@@ -101,6 +158,8 @@ export interface ClientTransactionLike {
* union from './Transactions'. Only `state` is typed from there for now, since
* importing the classes themselves (and not just their types) would create a
* runtime require cycle.
+ *
+ * @internal
*/
export interface ServerTransactionLike extends EventEmitter {
state: TransactionStatus;
@@ -124,6 +183,8 @@ export interface ServerTransactionLike extends EventEmitter {
* TODO: The `configuration` shape below is `Config.Configuration` plus the
* `jssip_id` that `UA` adds, so it can only be replaced once `UA` is ported.
* Note it is not the `UAConfiguration` input type declared in `UA.d.ts`.
+ *
+ * @internal
*/
export interface UALike {
readonly configuration: {
@@ -143,25 +204,50 @@ export interface UALike {
}
/**
- * -param {String} method request method
- * -param {String} ruri request uri
- * -param {UA} ua
- * -param {Object} params parameters that will have priority over ua.configuration parameters:
- * <br>
- * - cseq, call_id, from_tag, from_uri, from_display_name, to_uri, to_tag, route_set
- * -param {Object} [headers] extra headers
- * -param {String} [body]
+ * Holds a SIP request to be sent.
*/
export class OutgoingRequest {
+ /**
+ * The UA that sends the request.
+ */
ua: UALike;
+ /**
+ * Header fields set by the library, indexed by their capitalized name. A
+ * header field may appear several times, hence the array.
+ */
headers: Record<string, OutgoingHeaderValue[]>;
+ /**
+ * Request method, such as `INVITE` or `BYE`.
+ */
method: string;
+ /**
+ * The request target URI.
+ */
ruri: URI;
+ /**
+ * Body of the request, `undefined` when it carries none.
+ */
body?: string;
+ /**
+ * Header fields the application added through the `extraHeaders` option,
+ * each a whole `Name: value` line written as given.
+ */
extraHeaders: string[];
+ /**
+ * Value of the To header field.
+ */
to: NameAddrHeader;
+ /**
+ * Value of the From header field.
+ */
from: NameAddrHeader;
+ /**
+ * Value of the Call-ID header field.
+ */
call_id: string;
+ /**
+ * The CSeq number.
+ */
cseq: number;
/**
@@ -172,8 +258,24 @@ export class OutgoingRequest {
* `Transactions` when the request is sent.
*/
declare sdp?: SDP;
+ /**
+ * Client transaction the request is sent over, assigned once it is sent.
+ */
declare transaction?: ClientTransactionLike | null;
+ /**
+ * @param method - Request method, such as `INVITE` or `BYE`.
+ * @param ruri - Request-URI, so the address the request is sent to.
+ * @param ua - The UA that sends the request.
+ * @param params - Values that take priority over the ones the UA is
+ * configured with.
+ * @param extraHeaders - Whole `Name: value` header field lines to add to
+ * the request.
+ * @param body - Body of the request, if any.
+ *
+ * @throws
+ * - `TypeError` if `method`, `ruri` or `ua` is not given.
+ */
constructor(
method: string,
ruri: URI,
@@ -268,9 +370,16 @@ export class OutgoingRequest {
}
/**
- * Replace the the given header by the given value.
- * -param {String} name header name
- * -param {String | Array} value header value
+ * Replace the given header field by the given value.
+ *
+ * @param name - Header field name, which gets capitalized as it is written
+ * in SIP messages.
+ * @param value - A single value or several of them, one per header field
+ * line.
+ *
+ * @remarks
+ * - Any header field of the same name previously added through the
+ * `extraHeaders` option is removed first.
*/
setHeader(
name: string,
@@ -289,9 +398,13 @@ export class OutgoingRequest {
}
/**
- * Get the value of the given header name at the given position.
- * -param {String} name header name
- * -returns {String|undefined} Returns the specified header, null if header doesn't exist.
+ * Get the value of the first header field of the given name.
+ *
+ * @returns `undefined` if the request has no such header field.
+ *
+ * @remarks
+ * - Looks in `extraHeaders` too when the library did not set the header
+ * field itself.
*/
getHeader(name: string): OutgoingHeaderValue | undefined {
const headers = this.headers[headerize(name)];
@@ -314,9 +427,9 @@ export class OutgoingRequest {
}
/**
- * Get the header/s of the given name.
- * -param {String} name header name
- * -returns {Array} Array with all the headers of the specified name.
+ * Get the values of every header field of the given name.
+ *
+ * @returns An empty array if the request has no such header field.
*/
getHeaders(name: string): OutgoingHeaderValue[] {
const headers = this.headers[headerize(name)];
@@ -342,9 +455,7 @@ export class OutgoingRequest {
}
/**
- * Verify the existence of the given header.
- * -param {String} name header name
- * -returns {boolean} true if header with given name exists, false otherwise
+ * Whether the request carries a header field of the given name.
*/
hasHeader(name: string): boolean {
if (this.headers[headerize(name)]) {
@@ -363,11 +474,10 @@ export class OutgoingRequest {
}
/**
- * Parse the current body as a SDP and store the resulting object
- * into this.sdp.
- * -param {Boolean} force: Parse even if this.sdp already exists.
+ * Parse the body of the request as a session description and cache the
+ * result in {@link OutgoingRequest.sdp}.
*
- * Returns this.sdp.
+ * @param force - Parse again even if the body was already parsed.
*/
parseSDP(force?: boolean): SDP {
if (!force && this.sdp) {
@@ -379,6 +489,9 @@ export class OutgoingRequest {
}
}
+ /**
+ * The request as it travels on the wire.
+ */
toString(): string {
let msg = `${this.method} ${this.ruri} SIP/2.0\r\n`;
@@ -442,6 +555,10 @@ export class OutgoingRequest {
return msg;
}
+ /**
+ * A copy of the request whose header fields can be modified without
+ * affecting the original.
+ */
clone(): OutgoingRequest {
const request = new OutgoingRequest(this.method, this.ruri, this.ua);
@@ -460,6 +577,10 @@ export class OutgoingRequest {
}
}
+/**
+ * Holds the INVITE request that starts an outgoing session, which can be
+ * cancelled before it is answered.
+ */
export class InitialOutgoingInviteRequest extends OutgoingRequest {
/**
* NOTE: Unlike in `OutgoingRequest`, declared normally, so every instance
@@ -477,10 +598,19 @@ export class InitialOutgoingInviteRequest extends OutgoingRequest {
super(JsSIP_C.INVITE, ruri, ua, params, extraHeaders, body);
}
+ /**
+ * Cancel the INVITE, so that the session is given up before the peer
+ * answers it.
+ *
+ * @param reason - Value of the Reason header field of the CANCEL.
+ */
cancel(reason?: string): void {
this.transaction!.cancel(reason);
}
+ /**
+ * A copy of the request that is bound to the same client transaction.
+ */
override clone(): InitialOutgoingInviteRequest {
const request = new InitialOutgoingInviteRequest(this.ruri, this.ua);
@@ -501,46 +631,130 @@ export class InitialOutgoingInviteRequest extends OutgoingRequest {
}
}
+/**
+ * The header fields of an `IncomingMessage`, indexed by their capitalized
+ * name. A header field may appear several times, hence the array.
+ */
export type IncomingHeaders = Record<string, IncomingHeader[]>;
/**
* Everything needed to build an `IncomingMessage`.
+ *
+ * @remarks
+ * - Every member that is optional is so because the corresponding header
+ * field may be missing or unparseable.
*/
export type IncomingMessageParams = {
+ /**
+ * The message as it arrived on the wire.
+ */
data: string;
+ /**
+ * Header fields of the message.
+ */
headers: IncomingHeaders;
+ /**
+ * Request method. For a response, the method of the request it answers.
+ */
method: string;
- // Undefined when the corresponding header field is missing or unparseable.
+ /**
+ * Value of the topmost Via header field.
+ */
via?: Grammar.ViaHeader;
+ /**
+ * Branch parameter of the topmost Via header field.
+ */
via_branch?: string;
+ /**
+ * Value of the Call-ID header field.
+ */
call_id?: string;
+ /**
+ * Sequence number of the CSeq header field.
+ */
cseq?: number;
+ /**
+ * Value of the From header field.
+ */
from: NameAddrHeader;
/**
- * NOTE: `null` when the tag parameter is present but valueless (`;tag`),
- * `undefined` when it is absent altogether.
+ * Tag parameter of the From header field.
+ *
+ * @remarks
+ * - `null` when the tag parameter is present but valueless (`;tag`),
+ * `undefined` when it is absent altogether.
*/
from_tag?: string | null;
+ /**
+ * Value of the To header field.
+ */
to: NameAddrHeader;
+ /**
+ * Tag parameter of the To header field, with the same distinction between
+ * `null` and `undefined` as {@link IncomingMessageParams.from_tag}.
+ */
to_tag?: string | null;
+ /**
+ * Body of the message, an empty string when it carries none.
+ */
body: string;
+ /**
+ * Interval (in seconds) of the Session-Expires header field.
+ */
session_expires?: number;
+ /**
+ * Refresher parameter of the Session-Expires header field.
+ */
session_expires_refresher?: string;
+ /**
+ * Value of the Refer-To header field.
+ */
refer_to?: Grammar.ReferToHeader;
+ /**
+ * Value of the Replaces header field.
+ */
replaces?: Grammar.ReplacesHeader;
+ /**
+ * Value of the Event header field.
+ */
event?: Grammar.EventHeader;
};
+/**
+ * Everything needed to build an `IncomingRequest`.
+ */
export type IncomingRequestParams = IncomingMessageParams & {
+ /**
+ * The UA that received the request.
+ */
ua: UALike;
+ /**
+ * Request-URI, so the address the request was sent to.
+ */
ruri: URI;
};
+/**
+ * Everything needed to build an `IncomingResponse`.
+ */
export type IncomingResponseParams = IncomingMessageParams & {
+ /**
+ * Status code of the response, between 100 and 699.
+ */
status_code: number;
+ /**
+ * Reason phrase of the response, as the peer wrote it.
+ */
reason_phrase: string;
};
+/**
+ * Holds a received SIP request or response.
+ *
+ * @remarks
+ * - The application gets an {@link IncomingRequest} or an
+ * {@link IncomingResponse} rather than this class.
+ */
export class IncomingMessage {
// Header store operations.
//
@@ -670,25 +884,86 @@ export class IncomingMessage {
}
}
+ /**
+ * The message as it arrived on the wire.
+ */
data: string;
+ /**
+ * Header fields of the message, indexed by their capitalized name. Each
+ * entry keeps the raw value and, once read, its parsed form.
+ */
headers: IncomingHeaders;
+ /**
+ * Method of the incoming SIP message. For a response, the method of the
+ * request it answers.
+ */
method: string;
+ /**
+ * Value of the topmost Via header field.
+ */
via?: Grammar.ViaHeader;
+ /**
+ * Branch parameter of the topmost Via header field, which identifies the
+ * transaction.
+ */
via_branch?: string;
+ /**
+ * Value of the Call-ID header field.
+ */
call_id?: string;
+ /**
+ * Sequence number of the CSeq header field.
+ */
cseq?: number;
+ /**
+ * Value of the From header field of the incoming SIP message.
+ */
from: NameAddrHeader;
+ /**
+ * Tag parameter of the From header field.
+ */
from_tag?: string | null;
+ /**
+ * Value of the To header field of the incoming SIP message.
+ */
to: NameAddrHeader;
+ /**
+ * Tag parameter of the To header field.
+ */
to_tag?: string | null;
+ /**
+ * Body of the SIP message, an empty string when it carries none.
+ */
body: string;
+ /**
+ * Body parsed as a session description, `null` until
+ * {@link IncomingMessage.parseSDP} is called.
+ */
sdp: SDP | null;
- // Only set when the corresponding header field is present.
+ /**
+ * Interval (in seconds) of the Session-Expires header field, only set when
+ * the message carries one.
+ */
session_expires?: number;
+ /**
+ * Refresher parameter of the Session-Expires header field, so which side
+ * refreshes the session. Only set when the message carries one.
+ */
session_expires_refresher?: string;
+ /**
+ * Value of the Refer-To header field, only set when the message carries
+ * one.
+ */
refer_to?: Grammar.ReferToHeader;
+ /**
+ * Value of the Replaces header field, only set when the message carries
+ * one.
+ */
replaces?: Grammar.ReplacesHeader;
+ /**
+ * Value of the Event header field, only set when the message carries one.
+ */
event?: Grammar.EventHeader;
constructor({
@@ -760,45 +1035,51 @@ export class IncomingMessage {
}
/**
- * Parse the given header on the given index.
- * -param {String} name header name
- * -param {Number} [idx=0] header index
- * -returns {Object|undefined} Parsed header object, undefined if the header
- * is not present or in case of a parsing error.
+ * Parse the header field of the given name at the given position.
+ *
+ * @param name - Header field name.
+ * @param idx - Position among the header fields of that name.
+ *
+ * @returns `undefined` if the message has no such header field or it
+ * cannot be parsed.
+ *
+ * @remarks
+ * - The result is cached, so parsing the same header field again is cheap.
+ *
+ * @example
+ * ```ts
+ * const event = message.parseHeader<EventHeader>('event');
+ * ```
*/
parseHeader<T = unknown>(name: string, idx = 0): T | undefined {
return IncomingMessage.parseHeader<T>(this.headers, name, idx);
}
/**
- * Message Header attribute selector. Alias of parseHeader.
- * -param {String} name header name
- * -param {Number} [idx=0] header index
- * -returns {Object|undefined} Parsed header object, undefined if the header
- * is not present or in case of a parsing error.
+ * Alias of {@link IncomingMessage.parseHeader}.
*
- * -example
- * message.s('via',3).port
+ * @example
+ * ```ts
+ * message.s('via', 3).port;
+ * ```
*/
s<T = unknown>(name: string, idx?: number): T | undefined {
return this.parseHeader<T>(name, idx);
}
/**
- * Replace the value of the given header by the value.
- * -param {String} name header name
- * -param {String} value header value
+ * Replace every header field of the given name by a single one with the
+ * given value.
*/
setHeader(name: string, value: string): void {
IncomingMessage.setHeader(this.headers, name, value);
}
/**
- * Parse the current body as a SDP and store the resulting object
- * into this.sdp.
- * -param {Boolean} force: Parse even if this.sdp already exists.
+ * Parse the body of the message as a session description and cache the
+ * result in {@link IncomingMessage.sdp}.
*
- * Returns this.sdp.
+ * @param force - Parse again even if the body was already parsed.
*/
parseSDP(force?: boolean): SDP {
if (!force && this.sdp) {
@@ -810,15 +1091,34 @@ export class IncomingMessage {
}
}
+ /**
+ * The message as it arrived on the wire.
+ */
toString(): string {
return this.data;
}
}
+/**
+ * Holds a received SIP request.
+ */
export class IncomingRequest extends IncomingMessage {
+ /**
+ * The UA that received the request.
+ */
ua: UALike;
+ /**
+ * Request URI of the SIP message.
+ */
ruri: URI;
+ /**
+ * Transport the request arrived through, `null` until the UA routes it.
+ */
transport: Transport | null;
+ /**
+ * Server transaction the request belongs to, `null` until the UA creates
+ * it.
+ */
server_transaction: ServerTransactionLike | null;
constructor({ ua, ruri, ...params }: IncomingRequestParams) {
@@ -831,13 +1131,26 @@ export class IncomingRequest extends IncomingMessage {
}
/**
- * Stateful reply.
- * -param {Number} code status code
- * -param {String} reason reason phrase
- * -param {Object} headers extra headers
- * -param {String} body body
- * -param {Function} [onSuccess] onSuccess callback
- * -param {Function} [onFailure] onFailure callback
+ * Answer the request through its server transaction, so that the response
+ * is retransmitted as the transaction requires.
+ *
+ * @param code - Status code of the response, between 100 and 699.
+ * @param reason - Reason phrase. The one
+ * {@link Constants.REASON_PHRASE} gives for the status code when not
+ * given.
+ * @param extraHeaders - Whole `Name: value` header field lines to add to
+ * the response.
+ * @param body - Body of the response, if any.
+ * @param onSuccess - Called once the response has been sent.
+ * @param onFailure - Called if the response could not be sent.
+ *
+ * @throws
+ * - `TypeError` if `code` is not between 100 and 699.
+ *
+ * @example
+ * ```ts
+ * request.reply(486); // Busy Here
+ * ```
*/
reply(
code: number,
@@ -970,9 +1283,20 @@ export class IncomingRequest extends IncomingMessage {
}
/**
- * Stateless reply.
- * -param {Number} code status code
- * -param {String} reason reason phrase
+ * Answer the request straight over the transport, without a server
+ * transaction, so the response is sent once and never retransmitted.
+ *
+ * @param code - Status code of the response, between 100 and 699.
+ * @param reason - Reason phrase. The one
+ * {@link Constants.REASON_PHRASE} gives for the status code when not
+ * given.
+ *
+ * @throws
+ * - `TypeError` if `code` is not between 100 and 699.
+ *
+ * @remarks
+ * - Used for requests the UA rejects before creating a transaction for
+ * them, such as those that fail the sanity checks.
*/
reply_sl(code: number | null = null, reason: string | null = null): void {
const vias = this.getHeaders('via');
@@ -1026,8 +1350,17 @@ export class IncomingRequest extends IncomingMessage {
}
}
+/**
+ * Holds a received SIP response.
+ */
export class IncomingResponse extends IncomingMessage {
+ /**
+ * Status code of the response, between 100 and 699.
+ */
status_code: number;
+ /**
+ * Reason phrase of the response, as the peer wrote it.
+ */
reason_phrase: string;
constructor({
diff --git a/src/Socket.ts b/src/Socket.ts
index 00047c1..07705f2 100644
--- a/src/Socket.ts
+++ b/src/Socket.ts
@@ -5,34 +5,125 @@ import * as Grammar from './Grammar';
const logger = new Logger('Socket');
/**
- * Interface documentation: https://jssip.net/documentation/$last_version/api/socket/
+ * Abstracts the library from the mechanism used to send and receive SIP
+ * traffic.
+ *
+ * Implementations must follow this interface in order to get the library
+ * working with the underlying transport mechanism, and are given to the UA in
+ * its `sockets` configuration parameter.
+ *
+ * @remarks
+ * - {@link WebSocketInterface} is the implementation shipped for browser
+ * environments.
+ *
+ * @example
+ * ```ts
+ * const socket = new JsSIP.WebSocketInterface('wss://sip.example.com');
+ * const ua = new JsSIP.UA({ sockets: socket, uri: 'sip:alice@example.com' });
+ * ```
*/
export interface Socket {
+ /**
+ * URI of the remote peer, as given to the implementation. Only used for
+ * logging.
+ */
readonly url: string;
-
+ /**
+ * SIP URI of the socket, used to build the Route header field of outgoing
+ * requests when the UA is configured with a preloaded route (for example
+ * `sip:sip.example.com:443;transport=ws`).
+ */
readonly sip_uri: string;
-
+ /**
+ * Transport protocol to announce in the Via header field of outgoing
+ * requests (for example `WSS`).
+ */
via_transport: string;
+ /**
+ * Called by the library when the socket availability for sending and
+ * receiving data is required.
+ *
+ * @remarks
+ * - {@link Socket.onconnect} must be called as soon as the socket is ready,
+ * or {@link Socket.ondisconnect} if it fails to connect or is not usable.
+ */
connect(): void;
+ /**
+ * Called by the library when the socket is no longer needed for now.
+ *
+ * @remarks
+ * - Event handlers called after this one are ignored.
+ */
disconnect(): void;
+ /**
+ * Called by the library when the given data needs to be sent.
+ *
+ * @returns `true` if the data was successfully sent, `false` otherwise.
+ */
send(message: string | ArrayBufferLike | Blob | ArrayBufferView): boolean;
+ /**
+ * Whether the transport is up and able to send.
+ */
isConnected(): boolean;
+ /**
+ * Whether the transport is in the middle of connecting.
+ */
isConnecting(): boolean;
+ /**
+ * Must be called when the socket becomes usable for sending and receiving
+ * data, after {@link Socket.connect} was called or an unsolicited
+ * disconnection occurred.
+ *
+ * @remarks
+ * - Assigned by the library. The application must not call it.
+ */
onconnect(): void;
+ /**
+ * Must be called when the socket becomes unusable for sending or receiving
+ * data.
+ *
+ * @param error - Whether the socket disconnected due to an error.
+ * @param code - Socket disconnection code, if any.
+ * @param reason - Socket disconnection reason, if any.
+ *
+ * @remarks
+ * - Assigned by the library. The application must not call it.
+ */
ondisconnect(error: boolean, code?: number, reason?: string): void;
+ /**
+ * Must be called when there is a full SIP message to be processed by the
+ * library.
+ *
+ * @remarks
+ * - Assigned by the library. The application must not call it.
+ */
ondata(data: string | ArrayBuffer): void;
}
+/**
+ * A {@link Socket} together with the preference the UA gives it. Accepted in
+ * the `sockets` configuration parameter to run several transports, so that the
+ * UA falls back to another one when a connection attempt fails.
+ */
export interface WeightedSocket {
+ /**
+ * The socket itself.
+ */
socket: Socket;
+ /**
+ * How much the UA prefers this socket over the others. The highest weight
+ * is tried first and sockets of equal weight are tried in random order.
+ *
+ * @defaultValue 0
+ */
weight?: number;
}
diff --git a/src/Transport.ts b/src/Transport.ts
index 9930da7..dba8272 100644
--- a/src/Transport.ts
+++ b/src/Transport.ts
@@ -69,10 +69,9 @@ export type TransportDataEvent = {
};
/**
- * Manages one or multiple JsSIP.Socket instances.
- * Is reponsible for transport recovery logic among all socket instances.
- *
- * @socket JsSIP::Socket instance
+ * Manages the {@link Socket} instances the UA is configured with and recovers
+ * the transport when the one in use goes down, falling back to the others by
+ * weight.
*/
export class Transport {
#status: number;
diff --git a/src/URI.ts b/src/URI.ts
index 730c0cc..b9ae1db 100644
--- a/src/URI.ts
+++ b/src/URI.ts
@@ -3,18 +3,33 @@ import { escapeUser, headerize } from './Utils';
import * as Grammar from './Grammar';
/**
- * -param {String} [scheme]
- * -param {String} [user]
- * -param {String} host
- * -param {String} [port]
- * -param {Object} [parameters]
- * -param {Object} [headers]
+ * Represents a SIP URI and provides a set of attributes and methods to
+ * retrieve and set the different parts of a URI.
*
+ * It can be represented in its full form, including parameters and headers,
+ * and in the AoR form. It can also be cloned, so a second URI can be formed
+ * from itself.
+ *
+ * @example
+ * ```ts
+ * const uri = new JsSIP.URI('sip', 'alice', 'example.com', 5060);
+ *
+ * uri.setParam('transport', 'ws');
+ *
+ * uri.toString(); // 'sip:alice@example.com:5060;transport=ws'
+ * uri.toAor(); // 'sip:alice@example.com'
+ * ```
*/
class URI {
/**
- * Parse the given string and returns a JsSIP.URI instance or undefined if
- * it is an invalid URI.
+ * Parse the given string into a {@link URI}.
+ *
+ * @returns `undefined` if the string is not a valid SIP URI.
+ *
+ * @example
+ * ```ts
+ * const uri = JsSIP.URI.parse('sip:alice@example.com');
+ * ```
*/
static parse(uri: string): URI | undefined {
const parsed = Grammar.parse(uri, 'SIP_URI') as URI | -1;
@@ -33,6 +48,17 @@ class URI {
#parameters: URI.Parameters;
#headers: URI.Headers;
+ /**
+ * @param scheme - URI scheme, `sip` when not given.
+ * @param user - User part of the URI, if any.
+ * @param host - Host part of the URI. The only mandatory one.
+ * @param port - Port of the URI, if any.
+ * @param parameters - URI parameters, added through {@link URI.setParam}.
+ * @param headers - URI headers, added through {@link URI.setHeader}.
+ *
+ * @throws
+ * - `TypeError` if `host` is not given.
+ */
constructor(
scheme: URI.URIScheme | undefined,
user: string | undefined,
@@ -68,38 +94,79 @@ class URI {
}
}
+ /**
+ * Scheme of the URI, usually `sip` or `sips`.
+ */
get scheme(): string {
return this.#scheme;
}
+ /**
+ * Set the scheme of the URI, lowercasing the given value.
+ */
set scheme(value: string) {
this.#scheme = value.toLowerCase();
}
+ /**
+ * User part of the URI, `undefined` when the URI has none.
+ */
get user(): string | undefined {
return this.#user;
}
+ /**
+ * Set the user part of the URI, or remove it by giving `undefined`.
+ */
set user(value: string | undefined) {
this.#user = value;
}
+ /**
+ * Host part of the URI, either a domain or an IP address.
+ */
get host(): string {
return this.#host;
}
+ /**
+ * Set the host part of the URI, lowercasing the given value.
+ */
set host(value: string) {
this.#host = value.toLowerCase();
}
+ /**
+ * Port of the URI, `null` when the URI has none.
+ */
get port(): number | null | undefined {
return this.#port;
}
+ /**
+ * Set the port of the URI.
+ *
+ * @remarks
+ * - A string is accepted and converted into a number. A value that is not
+ * a number becomes `null`.
+ */
set port(value: number | string | null | undefined) {
this.#port = value === 0 ? value : parseInt(String(value), 10) || null;
}
+ /**
+ * Set the given URI parameter.
+ *
+ * @param key - Parameter name, lowercased.
+ * @param value - Parameter value. A parameter with no value, such as the
+ * `lr` of a loose route, is set by giving `null` or nothing.
+ *
+ * @example
+ * ```ts
+ * uri.setParam('transport', 'ws');
+ * uri.setParam('lr');
+ * ```
+ */
setParam(key: string, value?: string | number | null): void {
if (key) {
this.#parameters[key.toLowerCase()] =
@@ -109,6 +176,12 @@ class URI {
}
}
+ /**
+ * Get the value of the given URI parameter.
+ *
+ * @returns `null` if the parameter has no value, `undefined` if the URI
+ * does not have it.
+ */
getParam(key: string): string | null | undefined {
if (key) {
return this.#parameters[key.toLowerCase()];
@@ -117,6 +190,11 @@ class URI {
return undefined;
}
+ /**
+ * Whether the URI has the given parameter.
+ *
+ * @returns `undefined` if no parameter name is given.
+ */
hasParam(key: string): boolean | undefined {
if (key) {
return (
@@ -132,6 +210,12 @@ class URI {
return undefined;
}
+ /**
+ * Remove the given URI parameter.
+ *
+ * @returns The value it had, `null` if it had none, `undefined` if the URI
+ * did not have the parameter.
+ */
deleteParam(parameter: string): string | null | undefined {
parameter = parameter.toLowerCase();
if (Object.prototype.hasOwnProperty.call(this.#parameters, parameter)) {
@@ -145,14 +229,29 @@ class URI {
return undefined;
}
+ /**
+ * Remove every URI parameter.
+ */
clearParams(): void {
this.#parameters = {};
}
+ /**
+ * Set the given URI header.
+ *
+ * @param name - Header field name, which gets capitalized as it is written
+ * in SIP messages.
+ * @param value - A single value or several of them.
+ */
setHeader(name: string, value: string | string[]): void {
this.#headers[headerize(name)] = Array.isArray(value) ? value : [value];
}
+ /**
+ * Get the values of the given URI header.
+ *
+ * @returns `undefined` if the URI does not have it.
+ */
getHeader(name: string): string[] | undefined {
if (name) {
return this.#headers[headerize(name)];
@@ -161,6 +260,11 @@ class URI {
return undefined;
}
+ /**
+ * Whether the URI has the given header.
+ *
+ * @returns `undefined` if no header name is given.
+ */
hasHeader(name: string): boolean | undefined {
if (name) {
return (
@@ -173,6 +277,12 @@ class URI {
return undefined;
}
+ /**
+ * Remove the given URI header.
+ *
+ * @returns The values it had, `undefined` if the URI did not have the
+ * header.
+ */
deleteHeader(header: string): string[] | undefined {
header = headerize(header);
if (Object.prototype.hasOwnProperty.call(this.#headers, header)) {
@@ -186,10 +296,17 @@ class URI {
return undefined;
}
+ /**
+ * Remove every URI header.
+ */
clearHeaders(): void {
this.#headers = {};
}
+ /**
+ * A copy of the URI that shares nothing with it, so that either can be
+ * modified without affecting the other.
+ */
clone(): URI {
return new URI(
this.#scheme,
@@ -201,6 +318,15 @@ class URI {
);
}
+ /**
+ * The URI as it is written in a SIP message, with its parameters and
+ * headers.
+ *
+ * @example
+ * ```ts
+ * uri.toString(); // 'sip:alice@example.com:5060;transport=ws'
+ * ```
+ */
toString(): string {
const headers = [];
@@ -239,6 +365,19 @@ class URI {
return uri;
}
+ /**
+ * The address of record of the URI, so its scheme, user and host without
+ * any parameter nor header.
+ *
+ * @param show_port - Whether to include the port, which is left out by
+ * default.
+ *
+ * @example
+ * ```ts
+ * uri.toAor(); // 'sip:alice@example.com'
+ * uri.toAor(true); // 'sip:alice@example.com:5060'
+ * ```
+ */
toAor(show_port?: boolean): string {
let aor = `${this.#scheme}:`;
@@ -260,10 +399,20 @@ class URI {
// reachable.
// eslint-disable-next-line @typescript-eslint/no-namespace
declare namespace URI {
+ /**
+ * Scheme of a SIP URI. `sip` and `sips` are the ones SIP defines, but the
+ * grammar accepts any other.
+ */
type URIScheme = 'sip' | string;
-
+ /**
+ * URI parameters, indexed by their lowercased name. A parameter with no
+ * value, such as the `lr` of a loose route, is held as `null`.
+ */
type Parameters = Record<string, string | null>;
-
+ /**
+ * URI headers, indexed by their capitalized name. A header may appear
+ * several times, hence the array.
+ */
type Headers = Record<string, string[]>;
}
diff --git a/src/WebSocketInterface.ts b/src/WebSocketInterface.ts
index 33d2315..9758578 100644
--- a/src/WebSocketInterface.ts
+++ b/src/WebSocketInterface.ts
@@ -4,21 +4,69 @@ import type { Socket } from './Socket';
const logger = new Logger('WebSocketInterface');
+/**
+ * Built-in {@link Socket} implementation for browser environments, as defined
+ * by [RFC 7118](https://datatracker.ietf.org/doc/html/rfc7118).
+ *
+ * @remarks
+ * - The underlying WebSocket is negotiated with the `sip` subprotocol, so the
+ * server must support it.
+ *
+ * @example
+ * ```ts
+ * const socket = new JsSIP.WebSocketInterface('wss://sip.example.com');
+ * const ua = new JsSIP.UA({ sockets: socket, uri: 'sip:alice@example.com' });
+ *
+ * ua.start();
+ * ```
+ */
export class WebSocketInterface implements Socket {
#url: string;
#sip_uri: string;
#via_transport: string;
#ws: WebSocket | null;
- // NOTE: These are assigned by `Transport` once the socket is in use.
+ /**
+ * Called once the WebSocket is open.
+ *
+ * @remarks
+ * - Assigned by the library. The application must not call it.
+ */
declare onconnect: () => void;
+
+ /**
+ * Called once the WebSocket is closed, cleanly or not.
+ *
+ * @remarks
+ * - Assigned by the library. The application must not call it.
+ */
declare ondisconnect: (
error: boolean,
code?: number,
reason?: string
) => void;
+
+ /**
+ * Called for every message received over the WebSocket.
+ *
+ * @remarks
+ * - Assigned by the library. The application must not call it.
+ */
declare ondata: (data: string | ArrayBuffer) => void;
+ /**
+ * @param url - WebSocket URI of the SIP server, whose scheme must be `ws`
+ * or `wss`.
+ *
+ * @throws
+ * - `TypeError` if the URI is malformed or its scheme is neither `ws` nor
+ * `wss`.
+ *
+ * @example
+ * ```ts
+ * const socket = new JsSIP.WebSocketInterface('wss://sip.example.com:8443/ws');
+ * ```
+ */
constructor(url: string) {
logger.debug('new() [url:"%s"]', url);
@@ -39,6 +87,12 @@ export class WebSocketInterface implements Socket {
}
}
+ /**
+ * The transport announced in the Via header field of outgoing requests,
+ * derived from the scheme of the given URI. Always uppercase.
+ *
+ * @example `WSS`
+ */
get via_transport(): string {
return this.#via_transport;
}
@@ -47,14 +101,29 @@ export class WebSocketInterface implements Socket {
this.#via_transport = value.toUpperCase();
}
+ /**
+ * The SIP URI of the server, derived from the host and port of the given
+ * WebSocket URI.
+ *
+ * @example `sip:sip.example.com:8443;transport=ws`
+ */
get sip_uri(): string {
return this.#sip_uri;
}
+ /**
+ * The WebSocket URI given to the constructor.
+ */
get url(): string {
return this.#url;
}
+ /**
+ * Open the WebSocket.
+ *
+ * @remarks
+ * - Does nothing if it is already open or opening.
+ */
connect(): void {
logger.debug('connect()');
@@ -88,6 +157,12 @@ export class WebSocketInterface implements Socket {
}
}
+ /**
+ * Close the WebSocket.
+ *
+ * @remarks
+ * - Does nothing if there is none open.
+ */
disconnect(): void {
logger.debug('disconnect()');
@@ -103,6 +178,12 @@ export class WebSocketInterface implements Socket {
}
}
+ /**
+ * Send a SIP message over the WebSocket.
+ *
+ * @returns Whether the message was handed to the WebSocket, so `false` if
+ * it is not open.
+ */
send(message: string | ArrayBufferLike | Blob | ArrayBufferView): boolean {
logger.debug('send()');
@@ -117,17 +198,21 @@ export class WebSocketInterface implements Socket {
}
}
+ /**
+ * Whether the WebSocket is open.
+ */
isConnected(): boolean {
return this.#ws !== null && this.#ws.readyState === this.#ws.OPEN;
}
+ /**
+ * Whether the WebSocket is still opening.
+ */
isConnecting(): boolean {
return this.#ws !== null && this.#ws.readyState === this.#ws.CONNECTING;
}
- /**
- * WebSocket Event Handlers
- */
+ // WebSocket event handlers.
#onOpen(): void {
logger.debug(`WebSocket ${this.#url} connected`);
diff --git a/src/public.ts b/src/public.ts
new file mode 100644
index 0000000..c72bb7e
--- /dev/null
+++ b/src/public.ts
@@ -0,0 +1,52 @@
+/**
+ * The JavaScript SIP library.
+ *
+ * ```ts
+ * import * as JsSIP from 'jssip';
+ * ```
+ *
+ * @remarks
+ * - This is the API reference generated from the sources. It currently covers
+ * the modules already ported to TypeScript. The rest are added here as the
+ * port advances.
+ *
+ * @packageDocumentation
+ */
+
+import NameAddrHeader = require('./NameAddrHeader');
+import URI = require('./URI');
+
+export { URI, NameAddrHeader };
+
+/**
+ * The SIP messages the library sends and receives, and the types they are
+ * built from.
+ *
+ * @remarks
+ * - These are not exported by the package. The application gets them in the
+ * events that report a message.
+ */
+export * as SIPMessage from './SIPMessage';
+
+export { type Socket, type WeightedSocket } from './Socket';
+
+export { WebSocketInterface } from './WebSocketInterface';
+
+export { type Configuration } from './Configuration';
+
+/**
+ * SIP constants, response reason phrases and the causes reported in the
+ * `failed` and `ended` events.
+ *
+ * @remarks
+ * - Reachable as `JsSIP.C` at runtime.
+ */
+export * as Constants from './Constants';
+
+/**
+ * The errors the library throws.
+ *
+ * @remarks
+ * - Reachable as `JsSIP.Exceptions` at runtime.
+ */
+export * as Exceptions from './Exceptions';
diff --git a/typedoc.config.mjs b/typedoc.config.mjs
index 56c02a0..a577849 100644
--- a/typedoc.config.mjs
+++ b/typedoc.config.mjs
@@ -1,16 +1,36 @@
/**
* Configuration for Typedoc.
+ *
+ * NOTE: The entry point is the source `src/public.ts` rather than the built
+ * `lib/JsSIP.d.ts`, so that the documentation is the one written inline in the
+ * sources and it can be generated without building first.
+ *
+ * NOTE: `validation.notDocumented` plus `treatWarningsAsErrors` make
+ * `npm run docs:check` fail when anything reachable from `src/public.ts` is
+ * undocumented. Modules are added to `src/public.ts` as they are ported to
+ * TypeScript and documented.
+ *
+ * NOTE: `intentionallyNotExported` silences `validation.notExported` for the
+ * types that public members refer to but that are not part of the public API.
+ * They are the structural shims the TypeScript migration needs, plus the
+ * modules that are not documented yet. Each entry goes away as the port
+ * advances.
+ *
+ * NOTE: `projectDocuments` is not set on purpose. With a single entry point it
+ * makes Typedoc keep a module wrapper, so every page ends up under the name of
+ * the entry file ('public.Socket.html' rather than 'Socket.html'). The README
+ * is already the landing page through `readme`.
*/
/** @type {Partial<import('typedoc').TypeDocOptions>} */
const config = {
- entryPoints: ['src/JsSIP.js'],
+ entryPoints: ['src/public.ts'],
out: 'docs',
skipErrorChecking: false,
- exclude: ['src/**/*.d.ts', 'src/test/**/test-*.ts'],
+ exclude: ['src/**/*.d.ts', 'src/test/**/*.ts'],
excludePrivate: true,
excludeProtected: true,
- excludeNotDocumented: true,
+ excludeNotDocumented: false,
excludeInternal: true,
excludeExternals: true,
includeVersion: true,
@@ -19,10 +39,34 @@ const config = {
treatWarningsAsErrors: true,
cacheBust: true,
categorizeByGroup: false,
- categoryOrder: ['Config', 'UA', 'RTCSession', '*'],
+ sort: ['kind', 'source-order'],
+ sortEntryPoints: false,
searchInComments: true,
readme: 'README.md',
- projectDocuments: ['README.md', 'LICENSE.md'],
+ intentionallyNotExported: [
+ // Ported but not documented yet.
+ 'Transport',
+ // Declared in the hand written `Grammar.d.ts`, which is excluded above.
+ 'Grammar',
+ 'ViaHeader',
+ 'ReplacesHeader',
+ 'EventHeader',
+ 'ReferToHeader',
+ ],
+ validation: {
+ notExported: true,
+ invalidLink: true,
+ invalidPath: true,
+ rewrittenLink: true,
+ notDocumented: true,
+ unusedMergeModuleWith: true,
+ },
+ navigation: {
+ includeCategories: false,
+ includeGroups: false,
+ includeFolders: true,
+ compactFolders: true,
+ },
navigationLinks: {
GitHub: 'https://github.com/versatica/jssip',
NPM: 'https://www.npmjs.com/package/jssip',