Commit d2884a6 for jssip.net

commit d2884a65ebfbe29b059eef762edc731d754a0b5b
Author: José Luis Millán <jmillan@aliax.net>
Date:   Thu Dec 3 13:53:19 2026 +0100

    TS Notifier

diff --git a/src/Notifier.d.ts b/src/Notifier.d.ts
deleted file mode 100644
index 85d2bbb..0000000
--- a/src/Notifier.d.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import { EventEmitter } from 'events';
-import { IncomingRequest } from './SIPMessage';
-import { UA } from './UA';
-
-declare enum NotifierTerminationReason {
-	NOTIFY_RESPONSE_TIMEOUT = 0,
-	NOTIFY_TRANSPORT_ERROR = 1,
-	NOTIFY_NON_OK_RESPONSE = 2,
-	NOTIFY_AUTHENTICATION_FAILED = 3,
-	FINAL_NOTIFY_SENT = 4,
-	UNSUBSCRIBE_RECEIVED = 5,
-	SUBSCRIPTION_EXPIRED = 6,
-}
-
-export interface MessageEventMap {
-	terminated: [terminationCode: NotifierTerminationReason];
-	subscribe: [
-		isUnsubscribe: boolean,
-		request: IncomingRequest,
-		body: string | undefined,
-		contentType: string | undefined,
-	];
-	expired: [];
-}
-
-interface NotifierOptions {
-	extraHeaders?: string[];
-	allowEvents?: string;
-	pending?: boolean;
-	defaultExpires?: number;
-}
-
-export class Notifier extends EventEmitter<MessageEventMap> {
-	constructor(
-		ua: UA,
-		subscribe: IncomingRequest,
-		contentType: string,
-		options: NotifierOptions
-	);
-	start(): void;
-	setActiveState(): void;
-	notify(body?: string): void;
-	terminate(body?: string, reason?: string, retryAfter?: number): void;
-	get state(): string;
-	get id(): string;
-	// eslint-disable-next-line @typescript-eslint/no-explicit-any
-	set data(_data: any);
-	// eslint-disable-next-line @typescript-eslint/no-explicit-any
-	get data(): any;
-	static get C(): typeof NotifierTerminationReason;
-	get C(): typeof NotifierTerminationReason;
-}
diff --git a/src/Notifier.js b/src/Notifier.js
deleted file mode 100644
index 716fa70..0000000
--- a/src/Notifier.js
+++ /dev/null
@@ -1,437 +0,0 @@
-const EventEmitter = require('events').EventEmitter;
-const Exceptions = require('./Exceptions');
-const { Logger } = require('./Logger');
-const JsSIP_C = require('./Constants');
-const Utils = require('./Utils');
-const { Dialog } = require('./Dialog');
-
-const logger = new Logger('Notifier');
-
-/**
- * Termination codes.
- */
-const C = {
-	// Termination codes.
-	NOTIFY_RESPONSE_TIMEOUT: 0,
-	NOTIFY_TRANSPORT_ERROR: 1,
-	NOTIFY_NON_OK_RESPONSE: 2,
-	NOTIFY_AUTHENTICATION_FAILED: 3,
-	FINAL_NOTIFY_SENT: 4,
-	UNSUBSCRIBE_RECEIVED: 5,
-	SUBSCRIPTION_EXPIRED: 6,
-
-	// Notifer states.
-	STATE_PENDING: 0,
-	STATE_ACTIVE: 1,
-	STATE_TERMINATED: 2,
-
-	// RFC 6665 3.1.1, default expires value.
-	DEFAULT_EXPIRES_SEC: 900,
-};
-
-/**
- * RFC 6665 Notifier implementation.
- */
-module.exports = class Notifier extends EventEmitter {
-	/**
-	 * Expose C object.
-	 */
-	static get C() {
-		return C;
-	}
-
-	static init_incoming(request, callback) {
-		try {
-			Notifier.checkSubscribe(request);
-		} catch (error) {
-			logger.warn(
-				'Notifier.init_incoming: invalid request. Error: ',
-				error.message
-			);
-
-			request.reply(405);
-
-			return;
-		}
-
-		callback();
-	}
-
-	static checkSubscribe(subscribe) {
-		if (!subscribe) {
-			throw new TypeError('Not enough arguments. Missing subscribe request');
-		}
-		if (subscribe.method !== JsSIP_C.SUBSCRIBE) {
-			throw new TypeError('Invalid method for Subscribe request');
-		}
-		if (!subscribe.hasHeader('contact')) {
-			throw new TypeError('Missing Contact header in subscribe request');
-		}
-		if (!subscribe.hasHeader('event')) {
-			throw new TypeError('Missing Event header in subscribe request');
-		}
-		const expires = subscribe.getHeader('expires');
-
-		if (expires) {
-			const parsed_expires = parseInt(expires);
-
-			if (!Utils.isDecimal(parsed_expires) || parsed_expires < 0) {
-				throw new TypeError(
-					'Invalid Expires header field in subscribe request'
-				);
-			}
-		}
-	}
-
-	/**
-	 * @param {UA} ua - JsSIP User Agent instance.
-	 * @param {IncomingRequest} subscribe - Subscribe request.
-	 * @param {string} contentType - Content-Type header value.
-	 * @param {NotifierOptions} options - Optional parameters.
-	 *   @param {Array<string>}  extraHeaders - Additional SIP headers.
-	 *   @param {string} allowEvents - Allow-Events header value.
-	 *   @param {boolean} pending - Set initial dialog state as "pending".
-	 *   @param {number} defaultExpires - Default expires value (seconds).
-	 */
-	constructor(
-		ua,
-		subscribe,
-		contentType,
-		{ extraHeaders, allowEvents, pending, defaultExpires }
-	) {
-		logger.debug('new');
-
-		super();
-
-		if (!contentType) {
-			throw new TypeError('Not enough arguments. Missing contentType');
-		}
-
-		Notifier.checkSubscribe(subscribe);
-
-		const eventName = subscribe.getHeader('event');
-
-		this._ua = ua;
-		this._initial_subscribe = subscribe;
-		this._expires_timestamp = null;
-		this._expires_timer = null;
-		this._defaultExpires = defaultExpires || C.DEFAULT_EXPIRES_SEC;
-
-		// Notifier state: pending, active, terminated.
-		this._state = pending ? C.STATE_PENDING : C.STATE_ACTIVE;
-
-		this._content_type = contentType;
-		this._headers = Utils.cloneArray(extraHeaders);
-		this._headers.push(`Event: ${eventName}`);
-
-		// Use contact from extraHeaders or create it.
-		this._contact = this._headers.find(header => header.startsWith('Contact'));
-		if (!this._contact) {
-			this._contact = `Contact: ${this._ua._contact.toString()}`;
-
-			this._headers.push(this._contact);
-		}
-
-		if (allowEvents) {
-			this._headers.push(`Allow-Events: ${allowEvents}`);
-		}
-
-		this._target = subscribe.from.uri.user;
-		subscribe.to_tag = Utils.newTag();
-
-		// Custom session empty object for high level use.
-		this._data = {};
-	}
-
-	// Expose Notifier constants as a property of the Notifier instance.
-	get C() {
-		return C;
-	}
-
-	/**
-	 * Get dialog state.
-	 */
-	get state() {
-		return this._state;
-	}
-
-	/**
-	 * Get dialog id.
-	 */
-	get id() {
-		return this._dialog ? this._dialog.id : null;
-	}
-
-	get data() {
-		return this._data;
-	}
-
-	set data(_data) {
-		this._data = _data;
-	}
-
-	/**
-	 * Dialog callback.
-	 * Called also for initial subscribe.
-	 * Supported RFC 6665 4.4.3: initial fetch subscribe (with expires: 0).
-	 */
-	receiveRequest(request) {
-		if (request.method !== JsSIP_C.SUBSCRIBE) {
-			request.reply(405);
-
-			return;
-		}
-
-		this._setExpires(request);
-
-		// Create dialog for normal and fetch-subscribe.
-		if (!this._dialog) {
-			try {
-				this._dialog = Dialog.Create(this, request, 'UAS');
-			} catch {
-				// The SUBSCRIBE cannot establish a dialog.
-				request.reply(400);
-
-				return;
-			}
-		}
-
-		request.reply(200, null, [`Expires: ${this._expires}`, `${this._contact}`]);
-
-		const body = request.body;
-		const content_type = request.getHeader('content-type');
-		const is_unsubscribe = this._expires === 0;
-
-		if (!is_unsubscribe) {
-			this._setExpiresTimer();
-		}
-
-		logger.debug('emit "subscribe"');
-
-		this.emit('subscribe', is_unsubscribe, request, body, content_type);
-
-		if (is_unsubscribe) {
-			this._terminateDialog(C.UNSUBSCRIBE_RECEIVED);
-		}
-	}
-
-	/**
-	 * User API
-	 */
-
-	/**
-	 * Call this method after creating the Notifier instance and setting the event handlers.
-	 */
-	start() {
-		logger.debug('start()');
-
-		if (this._state === C.STATE_TERMINATED) {
-			throw new Exceptions.InvalidStateError(this._state);
-		}
-
-		this.receiveRequest(this._initial_subscribe);
-	}
-
-	/**
-	 * Switch pending dialog state to active.
-	 */
-	setActiveState() {
-		logger.debug('setActiveState()');
-
-		if (this._state === C.STATE_TERMINATED) {
-			throw new Exceptions.InvalidStateError(this._state);
-		}
-
-		if (this._state === C.STATE_PENDING) {
-			this._state = C.STATE_ACTIVE;
-		}
-	}
-
-	/**
-	 *  Send the initial and subsequent notify request.
-	 *  @param {string} body - notify request body.
-	 */
-	notify(body = null) {
-		logger.debug('notify()');
-
-		if (this._state === C.STATE_TERMINATED) {
-			throw new Exceptions.InvalidStateError(this._state);
-		}
-
-		const expires = Math.floor(
-			(this._expires_timestamp - new Date().getTime()) / 1000
-		);
-
-		// expires_timer is about to trigger. Clean up the timer and terminate.
-		if (expires <= 0) {
-			if (!this._expires_timer) {
-				logger.error('expires timer is not set');
-			}
-
-			clearTimeout(this._expires_timer);
-
-			this.terminate(body, 'timeout');
-		} else {
-			this._sendNotify([`;expires=${expires}`], body);
-		}
-	}
-
-	/**
-	 *  Terminate. (Send the final NOTIFY request).
-	 *
-	 * @param {string} body - Notify message body.
-	 * @param {string} reason - Set Subscription-State reason parameter.
-	 * @param {number} retryAfter - Set Subscription-State retry-after parameter.
-	 */
-	terminate(body = null, reason = null, retryAfter = null) {
-		logger.debug('terminate()');
-
-		if (this._state === C.STATE_TERMINATED) {
-			return;
-		}
-
-		const subsStateParameters = [];
-
-		if (reason) {
-			subsStateParameters.push(`;reason=${reason}`);
-		}
-
-		if (retryAfter !== null) {
-			subsStateParameters.push(`;retry-after=${retryAfter}`);
-		}
-
-		this._sendNotify(subsStateParameters, body, null, 'terminated');
-
-		this._terminateDialog(
-			reason === 'timeout' ? C.SUBSCRIPTION_EXPIRED : C.FINAL_NOTIFY_SENT
-		);
-	}
-
-	/**
-	 * Private API
-	 */
-
-	_terminateDialog(termination_code) {
-		if (this._state === C.STATE_TERMINATED) {
-			return;
-		}
-		this._state = C.STATE_TERMINATED;
-
-		clearTimeout(this._expires_timer);
-		if (this._dialog) {
-			this._dialog.terminate();
-			this._dialog = null;
-		}
-		logger.debug(`emit "terminated" code=${termination_code}`);
-
-		this.emit('terminated', termination_code);
-	}
-
-	_setExpires(request) {
-		if (request.hasHeader('expires')) {
-			this._expires = parseInt(request.getHeader('expires'));
-		} else {
-			this._expires = this._defaultExpires;
-			logger.debug(
-				`missing Expires header field, default value set: ${this._expires}`
-			);
-		}
-	}
-
-	/**
-	 * @param {Array<string>} subsStateParams subscription state parameters.
-	 * @param {String} body Notify body
-	 * @param {Array<string>} extraHeaders
-	 */
-	_sendNotify(
-		subsStateParameters,
-		body = null,
-		extraHeaders = null,
-		state = null
-	) {
-		// Prevent send notify after final notify.
-		if (this._state === C.STATE_TERMINATED) {
-			logger.warn('final notify already sent');
-
-			return;
-		}
-
-		// Build Subscription-State header with parameters.
-		let subsState = `Subscription-State: ${state || this._parseState()}`;
-
-		for (const param of subsStateParameters) {
-			subsState += param;
-		}
-
-		let headers = Utils.cloneArray(this._headers);
-
-		headers.push(subsState);
-
-		if (extraHeaders) {
-			headers = headers.concat(extraHeaders);
-		}
-
-		if (body) {
-			headers.push(`Content-Type: ${this._content_type}`);
-		}
-
-		this._dialog.sendRequest(JsSIP_C.NOTIFY, {
-			body,
-			extraHeaders: headers,
-			eventHandlers: {
-				onRequestTimeout: () => {
-					this._terminateDialog(C.NOTIFY_RESPONSE_TIMEOUT);
-				},
-				onTransportError: () => {
-					this._terminateDialog(C.NOTIFY_TRANSPORT_ERROR);
-				},
-				onErrorResponse: response => {
-					if (response.status_code === 401 || response.status_code === 407) {
-						this._terminateDialog(C.NOTIFY_AUTHENTICATION_FAILED);
-					} else {
-						this._terminateDialog(C.NOTIFY_NON_OK_RESPONSE);
-					}
-				},
-				onDialogError: () => {
-					this._terminateDialog(C.NOTIFY_NON_OK_RESPONSE);
-				},
-			},
-		});
-	}
-
-	_setExpiresTimer() {
-		this._expires_timestamp = new Date().getTime() + this._expires * 1000;
-
-		clearTimeout(this._expires_timer);
-		this._expires_timer = setTimeout(() => {
-			if (this._state === C.STATE_TERMINATED) {
-				return;
-			}
-
-			logger.debug('emit "expired"');
-
-			// Client can hook into the 'expired' event and call terminate to send a custom notify.
-			this.emit('expired');
-
-			// This will be no-op if the client already called `terminate()`.
-			this.terminate(null, 'timeout');
-		}, this._expires * 1000);
-	}
-
-	_parseState() {
-		switch (this._state) {
-			case C.STATE_PENDING: {
-				return 'pending';
-			}
-			case C.STATE_ACTIVE: {
-				return 'active';
-			}
-			case C.STATE_TERMINATED: {
-				return 'terminated';
-			}
-			default: {
-				throw new TypeError('wrong state value');
-			}
-		}
-	}
-};
diff --git a/src/Notifier.ts b/src/Notifier.ts
new file mode 100644
index 0000000..27de3a7
--- /dev/null
+++ b/src/Notifier.ts
@@ -0,0 +1,618 @@
+import { EventEmitter } from 'events';
+
+import * as JsSIP_C from './Constants';
+import { Dialog } from './Dialog';
+import type { DialogId, DialogOwner, DialogUA } from './Dialog';
+import { InvalidStateError } from './Exceptions';
+import { Logger } from './Logger';
+import type { IncomingRequest } from './SIPMessage';
+import * as Utils from './Utils';
+
+const logger = new Logger('Notifier');
+
+/**
+ * Why the notifier stopped, as reported by the `terminated` event.
+ */
+export enum TerminationCode {
+	NOTIFY_RESPONSE_TIMEOUT = 0,
+	NOTIFY_TRANSPORT_ERROR = 1,
+	NOTIFY_NON_OK_RESPONSE = 2,
+	NOTIFY_AUTHENTICATION_FAILED = 3,
+	FINAL_NOTIFY_SENT = 4,
+	UNSUBSCRIBE_RECEIVED = 5,
+	SUBSCRIPTION_EXPIRED = 6,
+}
+
+/**
+ * State of the subscription, which the Subscription-State header field of
+ * every NOTIFY reports.
+ */
+export enum State {
+	PENDING = 0,
+	ACTIVE = 1,
+	TERMINATED = 2,
+}
+
+/**
+ * The constants the notifier exposes, both as a static and as an instance
+ * member.
+ *
+ * @remarks
+ * - {@link TerminationCode} and {@link State} hold the same values under
+ *   shorter names, and are what the notifier itself is typed with.
+ */
+export const C = {
+	// Termination codes.
+	NOTIFY_RESPONSE_TIMEOUT: TerminationCode.NOTIFY_RESPONSE_TIMEOUT,
+	NOTIFY_TRANSPORT_ERROR: TerminationCode.NOTIFY_TRANSPORT_ERROR,
+	NOTIFY_NON_OK_RESPONSE: TerminationCode.NOTIFY_NON_OK_RESPONSE,
+	NOTIFY_AUTHENTICATION_FAILED: TerminationCode.NOTIFY_AUTHENTICATION_FAILED,
+	FINAL_NOTIFY_SENT: TerminationCode.FINAL_NOTIFY_SENT,
+	UNSUBSCRIBE_RECEIVED: TerminationCode.UNSUBSCRIBE_RECEIVED,
+	SUBSCRIPTION_EXPIRED: TerminationCode.SUBSCRIPTION_EXPIRED,
+
+	// Notifer states.
+	STATE_PENDING: State.PENDING,
+	STATE_ACTIVE: State.ACTIVE,
+	STATE_TERMINATED: State.TERMINATED,
+
+	// RFC 6665 3.1.1, default expires value.
+	DEFAULT_EXPIRES_SEC: 900,
+};
+
+/**
+ * The events a {@link Notifier} emits.
+ */
+export type NotifierEventMap = {
+	/**
+	 * A SUBSCRIBE arrived, the initial one included. `isUnsubscribe` tells a
+	 * refresh from the `Expires: 0` that ends the subscription.
+	 */
+	subscribe: [
+		isUnsubscribe: boolean,
+		request: IncomingRequest,
+		body: string,
+		contentType: string | undefined,
+	];
+	/**
+	 * The subscription ran out. A listener may send a last body by calling
+	 * `terminate()`, which the notifier does itself otherwise.
+	 */
+	expired: [];
+	/**
+	 * The final NOTIFY went out, so the notifier is of no further use.
+	 */
+	terminated: [terminationCode: TerminationCode];
+};
+
+/**
+ * Options accepted by the constructor.
+ */
+export type NotifierOptions = {
+	/**
+	 * Whole `Name: value` header field lines to add to every NOTIFY. A
+	 * `Contact` among them replaces the one the UA would use.
+	 */
+	extraHeaders?: string[] | null;
+	/**
+	 * Value of the Allow-Events header field.
+	 */
+	allowEvents?: string;
+	/**
+	 * Whether the subscription starts out pending rather than active.
+	 *
+	 * @defaultValue `false`
+	 */
+	pending?: boolean;
+	/**
+	 * How long (in seconds) the subscription lasts when the SUBSCRIBE carries
+	 * no Expires header field.
+	 *
+	 * @defaultValue {@link C.DEFAULT_EXPIRES_SEC}
+	 */
+	defaultExpires?: number;
+};
+
+/**
+ * The `UA` surface a notifier depends on.
+ *
+ * TODO: Replace with `import type { UA } from './UA'` once `UA` is ported to
+ * TypeScript.
+ */
+export interface NotifierUA extends DialogUA {
+	readonly contact: DialogUA['contact'] & {
+		toString(): string;
+	};
+}
+
+/**
+ * Accepts a subscription and reports the event the peer asked about, per
+ * [RFC 6665](https://datatracker.ietf.org/doc/html/rfc6665).
+ *
+ * @remarks
+ * - Applications get one from `UA.notify()`, in reaction to the UA's
+ *   `newSubscribe` event.
+ * - Register the listeners first and call {@link Notifier.start} last, since
+ *   `start()` reports the SUBSCRIBE that created the notifier.
+ */
+export class Notifier
+	extends EventEmitter<NotifierEventMap>
+	implements DialogOwner
+{
+	/**
+	 * Answer a SUBSCRIBE the UA cannot dispatch to an existing dialog,
+	 * invoking the callback when it is one a notifier could serve.
+	 *
+	 * @remarks
+	 * - Called by the `UA`. The application must not call it.
+	 * - A SUBSCRIBE that does not pass {@link Notifier.checkSubscribe} is
+	 *   answered 405 and the callback is not invoked.
+	 */
+	static init_incoming(request: IncomingRequest, callback: () => void): void {
+		try {
+			Notifier.checkSubscribe(request);
+		} catch (error) {
+			logger.warn(
+				'Notifier.init_incoming: invalid request. Error: ',
+				(error as Error).message
+			);
+
+			request.reply(405);
+
+			return;
+		}
+
+		callback();
+	}
+
+	/**
+	 * Check that the given request is a SUBSCRIBE a notifier can be built on.
+	 *
+	 * @throws
+	 * - `TypeError` if the request is missing, is not a SUBSCRIBE, carries no
+	 *   Contact or Event header field, or its Expires header field is not a
+	 *   non negative number.
+	 */
+	static checkSubscribe(subscribe: IncomingRequest): void {
+		if (!subscribe) {
+			throw new TypeError('Not enough arguments. Missing subscribe request');
+		}
+		if (subscribe.method !== JsSIP_C.SUBSCRIBE) {
+			throw new TypeError('Invalid method for Subscribe request');
+		}
+		if (!subscribe.hasHeader('contact')) {
+			throw new TypeError('Missing Contact header in subscribe request');
+		}
+		if (!subscribe.hasHeader('event')) {
+			throw new TypeError('Missing Event header in subscribe request');
+		}
+		const expires = subscribe.getHeader('expires');
+
+		if (expires) {
+			const parsed_expires = parseInt(expires);
+
+			if (!Utils.isDecimal(parsed_expires) || parsed_expires < 0) {
+				throw new TypeError(
+					'Invalid Expires header field in subscribe request'
+				);
+			}
+		}
+	}
+
+	/**
+	 * The constants above, reachable without the instance.
+	 */
+	static get C(): typeof C {
+		return C;
+	}
+
+	/**
+	 * The UA the notifier belongs to.
+	 *
+	 * @internal
+	 */
+	readonly _ua: NotifierUA;
+
+	#initial_subscribe: IncomingRequest;
+	#dialog: Dialog | null = null;
+	#expires: number = 0;
+	#expires_timestamp: number | null = null;
+	#expires_timer: ReturnType<typeof setTimeout> | null = null;
+	#defaultExpires: number;
+	#state: State;
+	#content_type: string;
+	#headers: string[];
+	#contact: string;
+	#data: unknown = {};
+
+	/**
+	 * @param ua - The UA that received the SUBSCRIBE.
+	 * @param subscribe - The SUBSCRIBE to accept.
+	 * @param contentType - Value of the Content-Type header field of every
+	 *   NOTIFY that carries a body.
+	 *
+	 * @throws
+	 * - `TypeError` if `contentType` is not given, or if the SUBSCRIBE does
+	 *   not pass {@link Notifier.checkSubscribe}.
+	 */
+	constructor(
+		ua: NotifierUA,
+		subscribe: IncomingRequest,
+		contentType: string,
+		{ extraHeaders, allowEvents, pending, defaultExpires }: NotifierOptions = {}
+	) {
+		logger.debug('new');
+
+		super();
+
+		if (!contentType) {
+			throw new TypeError('Not enough arguments. Missing contentType');
+		}
+
+		Notifier.checkSubscribe(subscribe);
+
+		const eventName = subscribe.getHeader('event');
+
+		this._ua = ua;
+		this.#initial_subscribe = subscribe;
+		this.#defaultExpires = defaultExpires || C.DEFAULT_EXPIRES_SEC;
+
+		// Notifier state: pending, active, terminated.
+		this.#state = pending ? State.PENDING : State.ACTIVE;
+
+		this.#content_type = contentType;
+		this.#headers = Utils.cloneArray(extraHeaders);
+		this.#headers.push(`Event: ${eventName}`);
+
+		// Use contact from extraHeaders or create it.
+		const contact = this.#headers.find(header => header.startsWith('Contact'));
+
+		if (contact) {
+			this.#contact = contact;
+		} else {
+			this.#contact = `Contact: ${this._ua.contact.toString()}`;
+
+			this.#headers.push(this.#contact);
+		}
+
+		if (allowEvents) {
+			this.#headers.push(`Allow-Events: ${allowEvents}`);
+		}
+
+		subscribe.to_tag = Utils.newTag();
+	}
+
+	/**
+	 * The constants above.
+	 */
+	get C(): typeof C {
+		return C;
+	}
+
+	/**
+	 * State of the subscription.
+	 */
+	get state(): State {
+		return this.#state;
+	}
+
+	/**
+	 * Id of the dialog the subscription runs in, or `null` until
+	 * {@link Notifier.start} creates it.
+	 */
+	get id(): DialogId | null {
+		return this.#dialog ? this.#dialog.id : null;
+	}
+
+	/**
+	 * Anything the application wants to keep along with the notifier.
+	 */
+	get data(): unknown {
+		return this.#data;
+	}
+
+	/**
+	 * Replaces whatever was kept along with the notifier.
+	 */
+	set data(_data: unknown) {
+		this.#data = _data;
+	}
+
+	/**
+	 * Take over a request the dialog received.
+	 *
+	 * @remarks
+	 * - Called by the `Dialog`, and by {@link Notifier.start} for the initial
+	 *   SUBSCRIBE. The application must not call it.
+	 * - Anything other than a SUBSCRIBE is answered 405.
+	 * - Covers the fetch subscribe of
+	 *   [RFC 6665 Section 4.4.3](https://datatracker.ietf.org/doc/html/rfc6665#section-4.4.3),
+	 *   an initial SUBSCRIBE with `Expires: 0`.
+	 */
+	receiveRequest(request: IncomingRequest): void {
+		if (request.method !== JsSIP_C.SUBSCRIBE) {
+			request.reply(405);
+
+			return;
+		}
+
+		this.#setExpires(request);
+
+		// Create dialog for normal and fetch-subscribe.
+		if (!this.#dialog) {
+			try {
+				this.#dialog = Dialog.Create(this, request, 'UAS');
+			} catch {
+				// The SUBSCRIBE cannot establish a dialog.
+				request.reply(400);
+
+				return;
+			}
+		}
+
+		request.reply(200, null, [`Expires: ${this.#expires}`, `${this.#contact}`]);
+
+		const body = request.body;
+		const content_type = request.getHeader('content-type');
+		const is_unsubscribe = this.#expires === 0;
+
+		if (!is_unsubscribe) {
+			this.#setExpiresTimer();
+		}
+
+		logger.debug('emit "subscribe"');
+
+		this.emit('subscribe', is_unsubscribe, request, body, content_type);
+
+		if (is_unsubscribe) {
+			this.#terminateDialog(TerminationCode.UNSUBSCRIBE_RECEIVED);
+		}
+	}
+
+	/**
+	 * Accept the subscription, which answers the SUBSCRIBE that created the
+	 * notifier and reports it through the `subscribe` event.
+	 *
+	 * @throws
+	 * - {@link InvalidStateError} if the notifier has already terminated.
+	 *
+	 * @remarks
+	 * - Call it once the listeners are registered, or the initial
+	 *   `subscribe` event is missed.
+	 */
+	start(): void {
+		logger.debug('start()');
+
+		if (this.#state === State.TERMINATED) {
+			throw new InvalidStateError(this.#state);
+		}
+
+		this.receiveRequest(this.#initial_subscribe);
+	}
+
+	/**
+	 * Move a pending subscription to active, which the next NOTIFY reports.
+	 *
+	 * @throws
+	 * - {@link InvalidStateError} if the notifier has already terminated.
+	 */
+	setActiveState(): void {
+		logger.debug('setActiveState()');
+
+		if (this.#state === State.TERMINATED) {
+			throw new InvalidStateError(this.#state);
+		}
+
+		if (this.#state === State.PENDING) {
+			this.#state = State.ACTIVE;
+		}
+	}
+
+	/**
+	 * Report the event to the subscriber, by sending a NOTIFY.
+	 *
+	 * @param body - Body of the NOTIFY, sent with the content type the
+	 *   notifier was built with.
+	 *
+	 * @throws
+	 * - {@link InvalidStateError} if the notifier has already terminated.
+	 *
+	 * @remarks
+	 * - When the subscription has run out, this sends the final NOTIFY with
+	 *   the given body instead, as {@link Notifier.terminate} would.
+	 */
+	notify(body: string | null = null): void {
+		logger.debug('notify()');
+
+		if (this.#state === State.TERMINATED) {
+			throw new InvalidStateError(this.#state);
+		}
+
+		const expires = Math.floor(
+			(this.#expires_timestamp! - new Date().getTime()) / 1000
+		);
+
+		// expires_timer is about to trigger. Clean up the timer and terminate.
+		if (expires <= 0) {
+			if (!this.#expires_timer) {
+				logger.error('expires timer is not set');
+			}
+
+			clearTimeout(this.#expires_timer!);
+
+			this.terminate(body, 'timeout');
+		} else {
+			this.#sendNotify([`;expires=${expires}`], body);
+		}
+	}
+
+	/**
+	 * End the subscription, by sending the final NOTIFY.
+	 *
+	 * @param body - Body of the NOTIFY.
+	 * @param reason - Value of the `reason` parameter of the
+	 *   Subscription-State header field.
+	 * @param retryAfter - Value of its `retry-after` parameter, in seconds.
+	 *
+	 * @remarks
+	 * - Does nothing once the notifier has terminated, so a listener of
+	 *   `expired` can call it without checking.
+	 */
+	terminate(
+		body: string | null = null,
+		reason: string | null = null,
+		retryAfter: number | null = null
+	): void {
+		logger.debug('terminate()');
+
+		if (this.#state === State.TERMINATED) {
+			return;
+		}
+
+		const subsStateParameters = [];
+
+		if (reason) {
+			subsStateParameters.push(`;reason=${reason}`);
+		}
+
+		if (retryAfter !== null) {
+			subsStateParameters.push(`;retry-after=${retryAfter}`);
+		}
+
+		this.#sendNotify(subsStateParameters, body, null, 'terminated');
+
+		this.#terminateDialog(
+			reason === 'timeout'
+				? TerminationCode.SUBSCRIPTION_EXPIRED
+				: TerminationCode.FINAL_NOTIFY_SENT
+		);
+	}
+
+	#terminateDialog(termination_code: TerminationCode): void {
+		if (this.#state === State.TERMINATED) {
+			return;
+		}
+		this.#state = State.TERMINATED;
+
+		clearTimeout(this.#expires_timer!);
+		if (this.#dialog) {
+			this.#dialog.terminate();
+			this.#dialog = null;
+		}
+		logger.debug(`emit "terminated" code=${termination_code}`);
+
+		this.emit('terminated', termination_code);
+	}
+
+	#setExpires(request: IncomingRequest): void {
+		if (request.hasHeader('expires')) {
+			this.#expires = parseInt(request.getHeader('expires')!);
+		} else {
+			this.#expires = this.#defaultExpires;
+			logger.debug(
+				`missing Expires header field, default value set: ${this.#expires}`
+			);
+		}
+	}
+
+	/**
+	 * @param subsStateParameters - Parameters of the Subscription-State
+	 *   header field, each written with its leading semicolon.
+	 * @param body - Body of the NOTIFY.
+	 * @param extraHeaders - Whole header field lines to add on top of the
+	 *   ones every NOTIFY carries.
+	 * @param state - Value of the Subscription-State header field. Taken
+	 *   from the notifier state when not given.
+	 */
+	#sendNotify(
+		subsStateParameters: string[],
+		body: string | null = null,
+		extraHeaders: string[] | null = null,
+		state: string | null = null
+	): void {
+		// Prevent send notify after final notify.
+		if (this.#state === State.TERMINATED) {
+			logger.warn('final notify already sent');
+
+			return;
+		}
+
+		// Build Subscription-State header with parameters.
+		let subsState = `Subscription-State: ${state || this.#parseState()}`;
+
+		for (const param of subsStateParameters) {
+			subsState += param;
+		}
+
+		let headers = Utils.cloneArray(this.#headers);
+
+		headers.push(subsState);
+
+		if (extraHeaders) {
+			headers = headers.concat(extraHeaders);
+		}
+
+		if (body) {
+			headers.push(`Content-Type: ${this.#content_type}`);
+		}
+
+		this.#dialog!.sendRequest(JsSIP_C.NOTIFY, {
+			body,
+			extraHeaders: headers,
+			eventHandlers: {
+				onRequestTimeout: () => {
+					this.#terminateDialog(TerminationCode.NOTIFY_RESPONSE_TIMEOUT);
+				},
+				onTransportError: () => {
+					this.#terminateDialog(TerminationCode.NOTIFY_TRANSPORT_ERROR);
+				},
+				onErrorResponse: response => {
+					if (response.status_code === 401 || response.status_code === 407) {
+						this.#terminateDialog(TerminationCode.NOTIFY_AUTHENTICATION_FAILED);
+					} else {
+						this.#terminateDialog(TerminationCode.NOTIFY_NON_OK_RESPONSE);
+					}
+				},
+				onDialogError: () => {
+					this.#terminateDialog(TerminationCode.NOTIFY_NON_OK_RESPONSE);
+				},
+			},
+		});
+	}
+
+	#setExpiresTimer(): void {
+		this.#expires_timestamp = new Date().getTime() + this.#expires * 1000;
+
+		clearTimeout(this.#expires_timer!);
+		this.#expires_timer = setTimeout(() => {
+			if (this.#state === State.TERMINATED) {
+				return;
+			}
+
+			logger.debug('emit "expired"');
+
+			// Client can hook into the 'expired' event and call terminate to send a custom notify.
+			this.emit('expired');
+
+			// This will be no-op if the client already called `terminate()`.
+			this.terminate(null, 'timeout');
+		}, this.#expires * 1000);
+	}
+
+	#parseState(): string {
+		switch (this.#state) {
+			case State.PENDING: {
+				return 'pending';
+			}
+			case State.ACTIVE: {
+				return 'active';
+			}
+			case State.TERMINATED: {
+				return 'terminated';
+			}
+			default: {
+				throw new TypeError('wrong state value');
+			}
+		}
+	}
+}
diff --git a/src/UA.d.ts b/src/UA.d.ts
index 9254189..9726f01 100644
--- a/src/UA.d.ts
+++ b/src/UA.d.ts
@@ -16,7 +16,7 @@ import {
 import { Message, SendMessageOptions } from './Message';
 import { Options, SendOptionsOptions } from './Options';
 import { Registrator } from './Registrator';
-import { Notifier } from './Notifier';
+import { Notifier, NotifierOptions } from './Notifier';
 import { Subscriber } from './Subscriber';
 import URI = require('./URI');
 import { causes } from './Constants';
@@ -220,11 +220,7 @@ export interface SubscriberOptions {
 	extraHeaders?: string[];
 }

-export interface NotifierOptions {
-	allowEvents?: string;
-	extraHeaders?: string[];
-	pending?: boolean;
-}
+export { NotifierOptions };

 declare enum UAStatus {
 	// UA status codes.
diff --git a/src/UA.js b/src/UA.js
index 5049dd3..1a1685a 100644
--- a/src/UA.js
+++ b/src/UA.js
@@ -6,7 +6,7 @@ const JsSIP_C = require('./Constants');
 const { Registrator } = require('./Registrator');
 const RTCSession = require('./RTCSession');
 const Subscriber = require('./Subscriber');
-const Notifier = require('./Notifier');
+const { Notifier } = require('./Notifier');
 const { Message } = require('./Message');
 const { Options } = require('./Options');
 const Transactions = require('./Transactions');