Commit 2a2e33c for jssip.net

commit 2a2e33c14eb8bfddada1c9e9282352858934ceec
Author: José Luis Millán <jmillan@aliax.net>
Date:   Thu Dec 3 12:13:03 2026 +0100

    TS: Registrator

diff --git a/src/Registrator.d.ts b/src/Registrator.d.ts
deleted file mode 100644
index 544ddd6..0000000
--- a/src/Registrator.d.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { UA } from './UA';
-import { Transport } from './Transport';
-
-export type ExtraContactParams = Record<string, string | number | boolean>;
-
-export class Registrator {
-	constructor(ua: UA, transport: Transport);
-
-	setExtraHeaders(extraHeaders: string[]): void;
-
-	setExtraContactParams(extraContactParams: ExtraContactParams): void;
-}
diff --git a/src/Registrator.js b/src/Registrator.js
deleted file mode 100644
index 44ca7a2..0000000
--- a/src/Registrator.js
+++ /dev/null
@@ -1,427 +0,0 @@
-const { Logger } = require('./Logger');
-const Utils = require('./Utils');
-const JsSIP_C = require('./Constants');
-const SIPMessage = require('./SIPMessage');
-const { RequestSender } = require('./RequestSender');
-
-const logger = new Logger('Registrator');
-
-const MIN_REGISTER_EXPIRES = 10; // In seconds.
-
-module.exports = class Registrator {
-	constructor(ua, transport) {
-		// Force reg_id to 1.
-		this._reg_id = 1;
-
-		this._ua = ua;
-		this._transport = transport;
-
-		this._registrar = ua.configuration.registrar_server;
-		this._expires = ua.configuration.register_expires;
-
-		// Call-ID and CSeq values RFC3261 10.2.
-		this._call_id = Utils.createRandomToken(22);
-		this._cseq = 0;
-
-		this._to_uri = ua.configuration.uri;
-
-		this._registrationTimer = null;
-
-		// Ongoing Register request.
-		this._registering = false;
-
-		// Set status.
-		this._registered = false;
-
-		// Contact header.
-		this._contact = this._ua.contact.toString();
-
-		// Sip.ice media feature tag (RFC 5768).
-		this._contact += ';+sip.ice';
-
-		// Custom headers for REGISTER and un-REGISTER.
-		this._extraHeaders = [];
-
-		// Custom Contact header params for REGISTER and un-REGISTER.
-		this._extraContactParams = '';
-
-		// Contents of the sip.instance Contact header parameter.
-		this._sipInstance = `"<urn:uuid:${this._ua.configuration.instance_id}>"`;
-
-		this._contact += `;reg-id=${this._reg_id}`;
-		this._contact += `;+sip.instance=${this._sipInstance}`;
-	}
-
-	get registered() {
-		return this._registered;
-	}
-
-	setExtraHeaders(extraHeaders) {
-		if (!Array.isArray(extraHeaders)) {
-			extraHeaders = [];
-		}
-
-		this._extraHeaders = extraHeaders.slice();
-	}
-
-	setExtraContactParams(extraContactParams) {
-		if (!(extraContactParams instanceof Object)) {
-			extraContactParams = {};
-		}
-
-		// Reset it.
-		this._extraContactParams = '';
-
-		for (const param_key in extraContactParams) {
-			if (Object.prototype.hasOwnProperty.call(extraContactParams, param_key)) {
-				const param_value = extraContactParams[param_key];
-
-				this._extraContactParams += `;${param_key}`;
-				if (param_value) {
-					this._extraContactParams += `=${param_value}`;
-				}
-			}
-		}
-	}
-
-	register() {
-		if (this._registering) {
-			logger.debug('Register request in progress...');
-
-			return;
-		}
-
-		const extraHeaders = Utils.cloneArray(this._extraHeaders);
-
-		let contactValue;
-
-		if (this._expires) {
-			contactValue = `${this._contact};expires=${this._expires}${this._extraContactParams}`;
-			extraHeaders.push(`Expires: ${this._expires}`);
-		} else {
-			contactValue = `${this._contact}${this._extraContactParams}`;
-		}
-
-		extraHeaders.push(`Contact: ${contactValue}`);
-
-		let fromTag = Utils.newTag();
-
-		if (this._ua.configuration.register_from_tag_trail) {
-			if (
-				typeof this._ua.configuration.register_from_tag_trail === 'function'
-			) {
-				fromTag += this._ua.configuration.register_from_tag_trail();
-			} else {
-				fromTag += this._ua.configuration.register_from_tag_trail;
-			}
-		}
-
-		const request = new SIPMessage.OutgoingRequest(
-			JsSIP_C.REGISTER,
-			this._registrar,
-			this._ua,
-			{
-				to_uri: this._to_uri,
-				call_id: this._call_id,
-				cseq: (this._cseq += 1),
-				from_tag: fromTag,
-			},
-			extraHeaders
-		);
-
-		const request_sender = new RequestSender(this._ua, request, {
-			onRequestTimeout: () => {
-				this._registrationFailure(null, JsSIP_C.causes.REQUEST_TIMEOUT);
-			},
-			onTransportError: () => {
-				this._registrationFailure(null, JsSIP_C.causes.CONNECTION_ERROR);
-			},
-			// Increase the CSeq on authentication.
-			onAuthenticated: () => {
-				this._cseq += 1;
-			},
-			onReceiveResponse: response => {
-				// Discard responses to older REGISTER/un-REGISTER requests.
-				if (response.cseq !== this._cseq) {
-					return;
-				}
-
-				// Clear registration timer.
-				if (this._registrationTimer !== null) {
-					clearTimeout(this._registrationTimer);
-					this._registrationTimer = null;
-				}
-
-				switch (true) {
-					case /^1[0-9]{2}$/.test(response.status_code): {
-						// Ignore provisional responses.
-						break;
-					}
-
-					case /^2[0-9]{2}$/.test(response.status_code): {
-						this._registering = false;
-
-						if (!response.hasHeader('Contact')) {
-							logger.debug(
-								'no Contact header in response to REGISTER, response ignored'
-							);
-
-							break;
-						}
-
-						const contacts = response.headers['Contact'].reduce(
-							(a, b) => a.concat(b.parsed),
-							[]
-						);
-
-						// Get the Contact pointing to us and update the expires value accordingly.
-						// Try to find a matching Contact using sip.instance and reg-id.
-						let contact = contacts.find(
-							element =>
-								this._sipInstance === element.getParam('+sip.instance') &&
-								this._reg_id === parseInt(element.getParam('reg-id'))
-						);
-
-						// If no match was found using the sip.instance try comparing the URIs.
-						if (!contact) {
-							contact = contacts.find(
-								element => element.uri.user === this._ua.contact.uri.user
-							);
-						}
-
-						if (!contact) {
-							logger.debug(
-								'no Contact header pointing to us, response ignored'
-							);
-
-							break;
-						}
-
-						let expires = contact.getParam('expires');
-
-						if (!expires && response.hasHeader('expires')) {
-							expires = response.getHeader('expires');
-						}
-
-						if (!expires) {
-							expires = this._expires;
-						}
-
-						expires = Number(expires);
-
-						// The binding lifetime the registrar granted, as given. The
-						// value below is clamped for the refresh timer only, so it
-						// may outlive the binding and must not be reported.
-						const granted_expires = expires;
-
-						if (expires < MIN_REGISTER_EXPIRES) {
-							expires = MIN_REGISTER_EXPIRES;
-						}
-
-						const timeout =
-							expires > 64
-								? (expires * 1000) / 2 +
-									Math.floor((expires / 2 - 32) * 1000 * Math.random())
-								: expires * 1000 - 5000;
-
-						// Re-Register or emit an event before the expiration interval has elapsed.
-						// For that, decrease the expires value. ie: 3 seconds.
-						this._registrationTimer = setTimeout(() => {
-							this._registrationTimer = null;
-							// If there are no listeners for registrationExpiring, renew registration.
-							// If there are listeners, let the function listening do the register call.
-							if (this._ua.listeners('registrationExpiring').length === 0) {
-								this.register();
-							} else {
-								this._ua.emit('registrationExpiring');
-							}
-						}, timeout);
-
-						// Save gruu values.
-						if (contact.hasParam('temp-gruu')) {
-							this._ua.contact.temp_gruu = contact
-								.getParam('temp-gruu')
-								.replace(/"/g, '');
-						}
-						if (contact.hasParam('pub-gruu')) {
-							this._ua.contact.pub_gruu = contact
-								.getParam('pub-gruu')
-								.replace(/"/g, '');
-						}
-
-						if (!this._registered) {
-							this._registered = true;
-							this._ua.registered({
-								response,
-								expires: granted_expires,
-							});
-						} else {
-							// The binding was renewed, not created.
-							this._ua.registrationRefreshed({
-								response,
-								expires: granted_expires,
-							});
-						}
-
-						break;
-					}
-
-					// Interval too brief RFC3261 10.2.8.
-					case /^423$/.test(response.status_code): {
-						if (response.hasHeader('min-expires')) {
-							// Increase our registration interval to the suggested minimum.
-							this._expires = Number(response.getHeader('min-expires'));
-
-							if (this._expires < MIN_REGISTER_EXPIRES) {
-								this._expires = MIN_REGISTER_EXPIRES;
-							}
-
-							// Assure register re-try with new expire.
-							this._registering = false;
-
-							// Attempt the registration again immediately.
-							this.register();
-						} else {
-							// This response MUST contain a Min-Expires header field.
-							logger.debug(
-								'423 response received for REGISTER without Min-Expires'
-							);
-
-							this._registrationFailure(
-								response,
-								JsSIP_C.causes.SIP_FAILURE_CODE
-							);
-						}
-
-						break;
-					}
-
-					default: {
-						const cause = Utils.sipErrorCause(response.status_code);
-
-						this._registrationFailure(response, cause);
-					}
-				}
-			},
-		});
-
-		this._registering = true;
-		request_sender.send();
-	}
-
-	unregister(options = {}) {
-		if (!this._registered) {
-			logger.debug('already unregistered');
-
-			return;
-		}
-
-		this._registered = false;
-
-		// Clear the registration timer.
-		if (this._registrationTimer !== null) {
-			clearTimeout(this._registrationTimer);
-			this._registrationTimer = null;
-		}
-
-		const extraHeaders = Utils.cloneArray(this._extraHeaders);
-
-		if (options.all) {
-			extraHeaders.push(`Contact: *${this._extraContactParams}`);
-		} else {
-			extraHeaders.push(
-				`Contact: ${this._contact};expires=0${this._extraContactParams}`
-			);
-		}
-
-		extraHeaders.push('Expires: 0');
-
-		const request = new SIPMessage.OutgoingRequest(
-			JsSIP_C.REGISTER,
-			this._registrar,
-			this._ua,
-			{
-				to_uri: this._to_uri,
-				call_id: this._call_id,
-				cseq: (this._cseq += 1),
-			},
-			extraHeaders
-		);
-
-		const request_sender = new RequestSender(this._ua, request, {
-			onRequestTimeout: () => {
-				this._unregistered(null, JsSIP_C.causes.REQUEST_TIMEOUT);
-			},
-			onTransportError: () => {
-				this._unregistered(null, JsSIP_C.causes.CONNECTION_ERROR);
-			},
-			// Increase the CSeq on authentication.
-			onAuthenticated: () => {
-				this._cseq += 1;
-			},
-			onReceiveResponse: response => {
-				switch (true) {
-					case /^1[0-9]{2}$/.test(response.status_code): {
-						// Ignore provisional responses.
-						break;
-					}
-					case /^2[0-9]{2}$/.test(response.status_code): {
-						this._unregistered(response);
-						break;
-					}
-					default: {
-						const cause = Utils.sipErrorCause(response.status_code);
-
-						this._unregistered(response, cause);
-					}
-				}
-			},
-		});
-
-		request_sender.send();
-	}
-
-	close() {
-		if (this._registered) {
-			this.unregister();
-		}
-	}
-
-	onTransportClosed() {
-		this._registering = false;
-		if (this._registrationTimer !== null) {
-			clearTimeout(this._registrationTimer);
-			this._registrationTimer = null;
-		}
-
-		if (this._registered) {
-			this._registered = false;
-			this._ua.unregistered({});
-		}
-	}
-
-	_registrationFailure(response, cause) {
-		this._registering = false;
-		this._ua.registrationFailed({
-			response: response || null,
-			cause,
-		});
-
-		if (this._registered) {
-			this._registered = false;
-			this._ua.unregistered({
-				response: response || null,
-				cause,
-			});
-		}
-	}
-
-	_unregistered(response, cause) {
-		this._registering = false;
-		this._registered = false;
-		this._ua.unregistered({
-			response: response || null,
-			cause: cause || null,
-		});
-	}
-};
diff --git a/src/Registrator.ts b/src/Registrator.ts
new file mode 100644
index 0000000..167d98c
--- /dev/null
+++ b/src/Registrator.ts
@@ -0,0 +1,560 @@
+import * as JsSIP_C from './Constants';
+import { Logger } from './Logger';
+import { RequestSender } from './RequestSender';
+import type { RequestSenderUA } from './RequestSender';
+import * as SIPMessage from './SIPMessage';
+import type { IncomingResponse } from './SIPMessage';
+import * as Utils from './Utils';
+import NameAddrHeader = require('./NameAddrHeader');
+import URI = require('./URI');
+
+const logger = new Logger('Registrator');
+
+// In seconds.
+const MIN_REGISTER_EXPIRES = 10;
+
+/**
+ * Contact header field parameters the application adds to the REGISTER and
+ * un-REGISTER requests.
+ */
+export type ExtraContactParams = Record<string, string | number | boolean>;
+
+/**
+ * Options accepted by `unregister()`.
+ */
+export type UnregisterOptions = {
+	/**
+	 * Whether to remove every binding of the address of record, rather than
+	 * just the one of this UA.
+	 *
+	 * @defaultValue `false`
+	 */
+	all?: boolean;
+};
+
+/**
+ * What the UA reports in its `registered` and `registrationRefreshed` events.
+ */
+export type RegisteredEvent = {
+	response: IncomingResponse;
+	expires: number;
+};
+
+/**
+ * What the UA reports in its `registrationFailed` and `unregistered` events.
+ */
+export type UnregisteredEvent = {
+	response: IncomingResponse | null;
+	cause?: JsSIP_C.causes | null;
+};
+
+/**
+ * The `UA` surface a registrator depends on.
+ *
+ * TODO: Replace with `import type { UA } from './UA'` once `UA` is ported to
+ * TypeScript.
+ */
+export interface RegistratorUA extends RequestSenderUA {
+	readonly configuration: RequestSenderUA['configuration'] & {
+		registrar_server: URI;
+		register_expires: number;
+		instance_id: string | null;
+		register_from_tag_trail: string | (() => string);
+	};
+	readonly contact: RequestSenderUA['contact'] & {
+		uri: URI;
+		toString(): string;
+	};
+
+	listeners(event: string): unknown[];
+	emit(event: string): boolean;
+
+	registered(data: RegisteredEvent): void;
+	registrationRefreshed(data: RegisteredEvent): void;
+	registrationFailed(data: UnregisteredEvent): void;
+	unregistered(data: UnregisteredEvent): void;
+}
+
+/**
+ * Manages the UA registration procedures.
+ *
+ * @remarks
+ * - Reachable through `ua.registrator`. Applications do not build one.
+ */
+export class Registrator {
+	#ua: RegistratorUA;
+	#registrar: URI;
+	#expires: number;
+	#call_id: string;
+	#cseq: number;
+	#to_uri: URI;
+	#registrationTimer: ReturnType<typeof setTimeout> | null;
+	#registering: boolean;
+	#registered: boolean;
+	#contact: string;
+	#extraHeaders: string[];
+	#extraContactParams: string;
+	#sipInstance: string;
+
+	// Forced to 1.
+	readonly #reg_id = 1;
+
+	constructor(ua: RegistratorUA) {
+		this.#ua = ua;
+
+		this.#registrar = ua.configuration.registrar_server;
+		this.#expires = ua.configuration.register_expires;
+
+		// Call-ID and CSeq values RFC3261 10.2.
+		this.#call_id = Utils.createRandomToken(22);
+		this.#cseq = 0;
+
+		this.#to_uri = ua.configuration.uri;
+
+		this.#registrationTimer = null;
+
+		// Ongoing Register request.
+		this.#registering = false;
+
+		// Set status.
+		this.#registered = false;
+
+		// Contact header.
+		this.#contact = this.#ua.contact.toString();
+
+		// Sip.ice media feature tag (RFC 5768).
+		this.#contact += ';+sip.ice';
+
+		// Custom headers for REGISTER and un-REGISTER.
+		this.#extraHeaders = [];
+
+		// Custom Contact header params for REGISTER and un-REGISTER.
+		this.#extraContactParams = '';
+
+		// Contents of the sip.instance Contact header parameter.
+		this.#sipInstance = `"<urn:uuid:${this.#ua.configuration.instance_id}>"`;
+
+		this.#contact += `;reg-id=${this.#reg_id}`;
+		this.#contact += `;+sip.instance=${this.#sipInstance}`;
+	}
+
+	/**
+	 * Whether the UA has a binding registered.
+	 */
+	get registered(): boolean {
+		return this.#registered;
+	}
+
+	/**
+	 * Append custom header fields to every REGISTER and un-REGISTER request.
+	 * They can be overriden at any time.
+	 *
+	 * @param extraHeaders - Whole `Name: value` header field lines. Anything
+	 *   that is not an array, `null` for instance, removes them.
+	 *
+	 * @example
+	 * ```ts
+	 * ua.registrator.setExtraHeaders(['X-Foo: bar']);
+	 * ```
+	 */
+	setExtraHeaders(extraHeaders: string[]): void {
+		if (!Array.isArray(extraHeaders)) {
+			extraHeaders = [];
+		}
+
+		this.#extraHeaders = extraHeaders.slice();
+	}
+
+	/**
+	 * Append custom parameters to the Contact header field of every REGISTER
+	 * and un-REGISTER request. They can be overriden at any time.
+	 *
+	 * @param extraContactParams - Parameters by name. A parameter whose value
+	 *   is falsy is added without one. Anything that is not an object, `null`
+	 *   for instance, removes them.
+	 *
+	 * @example
+	 * ```ts
+	 * ua.registrator.setExtraContactParams({ 'x-vendor': 'FooBar' });
+	 * // Adds ;x-vendor=FooBar
+	 * ```
+	 */
+	setExtraContactParams(extraContactParams: ExtraContactParams): void {
+		if (!(extraContactParams instanceof Object)) {
+			extraContactParams = {};
+		}
+
+		// Reset it.
+		this.#extraContactParams = '';
+
+		for (const param_key in extraContactParams) {
+			if (Object.prototype.hasOwnProperty.call(extraContactParams, param_key)) {
+				const param_value = extraContactParams[param_key];
+
+				this.#extraContactParams += `;${param_key}`;
+				if (param_value) {
+					this.#extraContactParams += `=${param_value}`;
+				}
+			}
+		}
+	}
+
+	/**
+	 * Send a REGISTER request, refreshing the binding before it expires.
+	 */
+	register(): void {
+		if (this.#registering) {
+			logger.debug('Register request in progress...');
+
+			return;
+		}
+
+		const extraHeaders = Utils.cloneArray(this.#extraHeaders);
+
+		let contactValue;
+
+		if (this.#expires) {
+			contactValue = `${this.#contact};expires=${this.#expires}${this.#extraContactParams}`;
+			extraHeaders.push(`Expires: ${this.#expires}`);
+		} else {
+			contactValue = `${this.#contact}${this.#extraContactParams}`;
+		}
+
+		extraHeaders.push(`Contact: ${contactValue}`);
+
+		let fromTag = Utils.newTag();
+
+		if (this.#ua.configuration.register_from_tag_trail) {
+			if (
+				typeof this.#ua.configuration.register_from_tag_trail === 'function'
+			) {
+				fromTag += this.#ua.configuration.register_from_tag_trail();
+			} else {
+				fromTag += this.#ua.configuration.register_from_tag_trail;
+			}
+		}
+
+		const request = new SIPMessage.OutgoingRequest(
+			JsSIP_C.REGISTER,
+			this.#registrar,
+			this.#ua,
+			{
+				to_uri: this.#to_uri,
+				call_id: this.#call_id,
+				cseq: (this.#cseq += 1),
+				from_tag: fromTag,
+			},
+			extraHeaders
+		);
+
+		const request_sender = new RequestSender(this.#ua, request, {
+			onRequestTimeout: () => {
+				this.#registrationFailure(null, JsSIP_C.causes.REQUEST_TIMEOUT);
+			},
+			onTransportError: () => {
+				this.#registrationFailure(null, JsSIP_C.causes.CONNECTION_ERROR);
+			},
+			// Increase the CSeq on authentication.
+			onAuthenticated: () => {
+				this.#cseq += 1;
+			},
+			onReceiveResponse: response => {
+				// Discard responses to older REGISTER/un-REGISTER requests.
+				if (response.cseq !== this.#cseq) {
+					return;
+				}
+
+				// Clear registration timer.
+				if (this.#registrationTimer !== null) {
+					clearTimeout(this.#registrationTimer);
+					this.#registrationTimer = null;
+				}
+
+				switch (true) {
+					case /^1[0-9]{2}$/.test(String(response.status_code)): {
+						// Ignore provisional responses.
+						break;
+					}
+
+					case /^2[0-9]{2}$/.test(String(response.status_code)): {
+						this.#registering = false;
+
+						if (!response.hasHeader('Contact')) {
+							logger.debug(
+								'no Contact header in response to REGISTER, response ignored'
+							);
+
+							break;
+						}
+
+						const contacts = (response.headers['Contact'] ?? []).reduce<
+							NameAddrHeader[]
+						>((a, b) => a.concat(b.parsed as NameAddrHeader), []);
+
+						// Get the Contact pointing to us and update the expires value accordingly.
+						// Try to find a matching Contact using sip.instance and reg-id.
+						let contact = contacts.find(
+							element =>
+								this.#sipInstance === element.getParam('+sip.instance') &&
+								this.#reg_id === parseInt(element.getParam('reg-id')!)
+						);
+
+						// If no match was found using the sip.instance try comparing the URIs.
+						if (!contact) {
+							contact = contacts.find(
+								element => element.uri.user === this.#ua.contact.uri.user
+							);
+						}
+
+						if (!contact) {
+							logger.debug(
+								'no Contact header pointing to us, response ignored'
+							);
+
+							break;
+						}
+
+						let expires: string | number | null | undefined =
+							contact.getParam('expires');
+
+						if (!expires && response.hasHeader('expires')) {
+							expires = response.getHeader('expires');
+						}
+
+						if (!expires) {
+							expires = this.#expires;
+						}
+
+						expires = Number(expires);
+
+						// The binding lifetime the registrar granted, as given. The
+						// value below is clamped for the refresh timer only, so it
+						// may outlive the binding and must not be reported.
+						const granted_expires = expires;
+
+						if (expires < MIN_REGISTER_EXPIRES) {
+							expires = MIN_REGISTER_EXPIRES;
+						}
+
+						const timeout =
+							expires > 64
+								? (expires * 1000) / 2 +
+									Math.floor((expires / 2 - 32) * 1000 * Math.random())
+								: expires * 1000 - 5000;
+
+						// Re-Register or emit an event before the expiration interval has elapsed.
+						// For that, decrease the expires value. ie: 3 seconds.
+						this.#registrationTimer = setTimeout(() => {
+							this.#registrationTimer = null;
+							// If there are no listeners for registrationExpiring, renew registration.
+							// If there are listeners, let the function listening do the register call.
+							if (this.#ua.listeners('registrationExpiring').length === 0) {
+								this.register();
+							} else {
+								this.#ua.emit('registrationExpiring');
+							}
+						}, timeout);
+
+						// Save gruu values.
+						if (contact.hasParam('temp-gruu')) {
+							this.#ua.contact.temp_gruu = contact
+								.getParam('temp-gruu')!
+								.replace(/"/g, '');
+						}
+						if (contact.hasParam('pub-gruu')) {
+							this.#ua.contact.pub_gruu = contact
+								.getParam('pub-gruu')!
+								.replace(/"/g, '');
+						}
+
+						if (!this.#registered) {
+							this.#registered = true;
+							this.#ua.registered({
+								response,
+								expires: granted_expires,
+							});
+						} else {
+							// The binding was renewed, not created.
+							this.#ua.registrationRefreshed({
+								response,
+								expires: granted_expires,
+							});
+						}
+
+						break;
+					}
+
+					// Interval too brief RFC3261 10.2.8.
+					case /^423$/.test(String(response.status_code)): {
+						if (response.hasHeader('min-expires')) {
+							// Increase our registration interval to the suggested minimum.
+							this.#expires = Number(response.getHeader('min-expires'));
+
+							if (this.#expires < MIN_REGISTER_EXPIRES) {
+								this.#expires = MIN_REGISTER_EXPIRES;
+							}
+
+							// Assure register re-try with new expire.
+							this.#registering = false;
+
+							// Attempt the registration again immediately.
+							this.register();
+						} else {
+							// This response MUST contain a Min-Expires header field.
+							logger.debug(
+								'423 response received for REGISTER without Min-Expires'
+							);
+
+							this.#registrationFailure(
+								response,
+								JsSIP_C.causes.SIP_FAILURE_CODE
+							);
+						}
+
+						break;
+					}
+
+					default: {
+						const cause = Utils.sipErrorCause(response.status_code);
+
+						this.#registrationFailure(response, cause);
+					}
+				}
+			},
+		});
+
+		this.#registering = true;
+		request_sender.send();
+	}
+
+	/**
+	 * Send an un-REGISTER request, removing the binding.
+	 */
+	unregister(options: UnregisterOptions = {}): void {
+		if (!this.#registered) {
+			logger.debug('already unregistered');
+
+			return;
+		}
+
+		this.#registered = false;
+
+		// Clear the registration timer.
+		if (this.#registrationTimer !== null) {
+			clearTimeout(this.#registrationTimer);
+			this.#registrationTimer = null;
+		}
+
+		const extraHeaders = Utils.cloneArray(this.#extraHeaders);
+
+		if (options.all) {
+			extraHeaders.push(`Contact: *${this.#extraContactParams}`);
+		} else {
+			extraHeaders.push(
+				`Contact: ${this.#contact};expires=0${this.#extraContactParams}`
+			);
+		}
+
+		extraHeaders.push('Expires: 0');
+
+		const request = new SIPMessage.OutgoingRequest(
+			JsSIP_C.REGISTER,
+			this.#registrar,
+			this.#ua,
+			{
+				to_uri: this.#to_uri,
+				call_id: this.#call_id,
+				cseq: (this.#cseq += 1),
+			},
+			extraHeaders
+		);
+
+		const request_sender = new RequestSender(this.#ua, request, {
+			onRequestTimeout: () => {
+				this.#unregistered(null, JsSIP_C.causes.REQUEST_TIMEOUT);
+			},
+			onTransportError: () => {
+				this.#unregistered(null, JsSIP_C.causes.CONNECTION_ERROR);
+			},
+			// Increase the CSeq on authentication.
+			onAuthenticated: () => {
+				this.#cseq += 1;
+			},
+			onReceiveResponse: response => {
+				switch (true) {
+					case /^1[0-9]{2}$/.test(String(response.status_code)): {
+						// Ignore provisional responses.
+						break;
+					}
+					case /^2[0-9]{2}$/.test(String(response.status_code)): {
+						this.#unregistered(response);
+						break;
+					}
+					default: {
+						const cause = Utils.sipErrorCause(response.status_code);
+
+						this.#unregistered(response, cause);
+					}
+				}
+			},
+		});
+
+		request_sender.send();
+	}
+
+	/**
+	 * Un-register when the UA is stopped.
+	 */
+	close(): void {
+		if (this.#registered) {
+			this.unregister();
+		}
+	}
+
+	/**
+	 * Give the binding up when the transport goes down.
+	 */
+	onTransportClosed(): void {
+		this.#registering = false;
+		if (this.#registrationTimer !== null) {
+			clearTimeout(this.#registrationTimer);
+			this.#registrationTimer = null;
+		}
+
+		if (this.#registered) {
+			this.#registered = false;
+			this.#ua.unregistered({ response: null });
+		}
+	}
+
+	#registrationFailure(
+		response: IncomingResponse | null,
+		cause: JsSIP_C.causes
+	): void {
+		this.#registering = false;
+		this.#ua.registrationFailed({
+			response: response || null,
+			cause,
+		});
+
+		if (this.#registered) {
+			this.#registered = false;
+			this.#ua.unregistered({
+				response: response || null,
+				cause,
+			});
+		}
+	}
+
+	#unregistered(
+		response: IncomingResponse | null,
+		cause?: JsSIP_C.causes
+	): void {
+		this.#registering = false;
+		this.#registered = false;
+		this.#ua.unregistered({
+			response: response || null,
+			cause: cause || null,
+		});
+	}
+}
diff --git a/src/UA.js b/src/UA.js
index 3afaf7a..6c6f3bd 100644
--- a/src/UA.js
+++ b/src/UA.js
@@ -3,7 +3,7 @@
 const EventEmitter = require('events').EventEmitter;
 const { Logger } = require('./Logger');
 const JsSIP_C = require('./Constants');
-const Registrator = require('./Registrator');
+const { Registrator } = require('./Registrator');
 const RTCSession = require('./RTCSession');
 const Subscriber = require('./Subscriber');
 const Notifier = require('./Notifier');