diff --git a/types/node/crypto.d.ts b/types/node/crypto.d.ts index b15ba39ff072b3..c628382fb3022f 100644 --- a/types/node/crypto.d.ts +++ b/types/node/crypto.d.ts @@ -3633,7 +3633,7 @@ declare module "node:crypto" { hash: HashAlgorithmIdentifier; length?: number; } - interface KangarooTwelveParams { + interface KangarooTwelveParams extends Algorithm { customization?: NodeJS.BufferSource; outputLength: number; } @@ -3706,7 +3706,7 @@ declare module "node:crypto" { interface RsaPssParams extends Algorithm { saltLength: number; } - interface TurboShakeParams { + interface TurboShakeParams extends Algorithm { domainSeparation?: number; outputLength: number; } diff --git a/types/node/dgram.d.ts b/types/node/dgram.d.ts index 09ce7856c6707e..ca8586a3af8780 100644 --- a/types/node/dgram.d.ts +++ b/types/node/dgram.d.ts @@ -284,7 +284,7 @@ declare module "node:dgram" { * and the `'connect'` event is emitted on the next tick. Trying to call * `connectSync()` on an already connected socket throws an * `ERR_SOCKET_DGRAM_IS_CONNECTED` exception, and calling it while an - * asynchronous [`socket.bind()`][] is still in progress throws an + * asynchronous `socket.bind()` is still in progress throws an * `ERR_SOCKET_ALREADY_BOUND` exception. * * `address` must be a numeric IP literal; `connectSync()` never performs DNS diff --git a/types/node/v24/async_hooks.d.ts b/types/node/v24/async_hooks.d.ts index 2377689f865bf2..e654686123047d 100644 --- a/types/node/v24/async_hooks.d.ts +++ b/types/node/v24/async_hooks.d.ts @@ -123,37 +123,31 @@ declare module "async_hooks" { function triggerAsyncId(): number; interface HookCallbacks { /** - * Called when a class is constructed that has the possibility to emit an asynchronous event. - * @param asyncId A unique ID for the async resource - * @param type The type of the async resource - * @param triggerAsyncId The unique ID of the async resource in whose execution context this async resource was created - * @param resource Reference to the resource representing the async operation, needs to be released during destroy + * The [`init` callback](https://nodejs.org/docs/latest-v24.x/api/async_hooks.html#initasyncid-type-triggerasyncid-resource). */ init?(asyncId: number, type: string, triggerAsyncId: number, resource: object): void; /** - * When an asynchronous operation is initiated or completes a callback is called to notify the user. - * The before callback is called just before said callback is executed. - * @param asyncId the unique identifier assigned to the resource about to execute the callback. + * The [`before` callback](https://nodejs.org/docs/latest-v24.x/api/async_hooks.html#beforeasyncid). */ before?(asyncId: number): void; /** - * Called immediately after the callback specified in `before` is completed. - * - * If an uncaught exception occurs during execution of the callback, then `after` will run after the `'uncaughtException'` event is emitted or a `domain`'s handler runs. - * @param asyncId the unique identifier assigned to the resource which has executed the callback. + * The [`after` callback](https://nodejs.org/docs/latest-v24.x/api/async_hooks.html#afterasyncid). */ after?(asyncId: number): void; /** - * Called when a promise has resolve() called. This may not be in the same execution id - * as the promise itself. - * @param asyncId the unique id for the promise that was resolve()d. + * The [`promiseResolve` callback](https://nodejs.org/docs/latest-v24.x/api/async_hooks.html#promiseresolveasyncid). */ promiseResolve?(asyncId: number): void; /** - * Called after the resource corresponding to asyncId is destroyed - * @param asyncId a unique ID for the async resource + * The [`destroy` callback](https://nodejs.org/docs/latest-v24.x/api/async_hooks.html#destroyasyncid). */ destroy?(asyncId: number): void; + /** + * Whether the hook should track `Promise`s. Cannot be `false` if + * `promiseResolve` is set. + * @default true + */ + trackPromises?: boolean | undefined; } interface AsyncHook { /** @@ -174,7 +168,8 @@ declare module "async_hooks" { * * All callbacks are optional. For example, if only resource cleanup needs to * be tracked, then only the `destroy` callback needs to be passed. The - * specifics of all functions that can be passed to `callbacks` is in the `Hook Callbacks` section. + * specifics of all functions that can be passed to `callbacks` is in the + * [Hook Callbacks](https://nodejs.org/docs/latest-v24.x/api/async_hooks.html#hook-callbacks) section. * * ```js * import { createHook } from 'node:async_hooks'; @@ -202,12 +197,13 @@ declare module "async_hooks" { * ``` * * Because promises are asynchronous resources whose lifecycle is tracked - * via the async hooks mechanism, the `init()`, `before()`, `after()`, and`destroy()` callbacks _must not_ be async functions that return promises. + * via the async hooks mechanism, the `init()`, `before()`, `after()`, and + * `destroy()` callbacks _must not_ be async functions that return promises. * @since v8.1.0 - * @param callbacks The `Hook Callbacks` to register - * @return Instance used for disabling and enabling hooks + * @param options The [Hook Callbacks](https://nodejs.org/docs/latest-v24.x/api/async_hooks.html#hook-callbacks) to register + * @returns Instance used for disabling and enabling hooks */ - function createHook(callbacks: HookCallbacks): AsyncHook; + function createHook(options: HookCallbacks): AsyncHook; interface AsyncResourceOptions { /** * The ID of the execution context that created this async event. diff --git a/types/node/v24/buffer.buffer.d.ts b/types/node/v24/buffer.buffer.d.ts index 8823deeb4b6754..e86fb880cbccf9 100644 --- a/types/node/v24/buffer.buffer.d.ts +++ b/types/node/v24/buffer.buffer.d.ts @@ -316,11 +316,11 @@ declare module "buffer" { * such `Buffer` instances with zeroes. * * When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, - * allocations under 4 KiB are sliced from a single pre-allocated `Buffer`. This - * allows applications to avoid the garbage collection overhead of creating many - * individually allocated `Buffer` instances. This approach improves both - * performance and memory usage by eliminating the need to track and clean up as - * many individual `ArrayBuffer` objects. + * allocations less than `Buffer.poolSize >>> 1` (32KiB when default poolSize is used) are sliced + * from a single pre-allocated `Buffer`. This allows applications to avoid the + * garbage collection overhead of creating many individually allocated `Buffer` + * instances. This approach improves both performance and memory usage by + * eliminating the need to track and clean up as many individual `ArrayBuffer` objects. * * However, in the case where a developer may need to retain a small chunk of * memory from a pool for an indeterminate amount of time, it may be appropriate @@ -469,4 +469,9 @@ declare module "buffer" { new(size: number): Buffer; prototype: Buffer; }; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type BufferView = T extends NodeJS.ArrayBufferView ? Buffer : never; } diff --git a/types/node/v24/buffer.d.ts b/types/node/v24/buffer.d.ts index 9a62ccf97737d6..785df1ca2a19ef 100644 --- a/types/node/v24/buffer.d.ts +++ b/types/node/v24/buffer.d.ts @@ -204,6 +204,13 @@ declare module "buffer" { * @since v16.7.0 */ stream(): WebReadableStream; + /** + * Returns a new `ReadableStream` that allows the content of the `Blob` to be read + * as a stream of UTF-8 decoded strings. It is equivalent to piping + * `blob.stream()` through a `TextDecoderStream` set up with UTF-8. + * @since v24.19.0 + */ + textStream(): WebReadableStream; } export interface FileOptions { /** diff --git a/types/node/v24/child_process.d.ts b/types/node/v24/child_process.d.ts index 51cb12e8dfeb9b..dc49457f56b386 100644 --- a/types/node/v24/child_process.d.ts +++ b/types/node/v24/child_process.d.ts @@ -220,6 +220,11 @@ declare module "child_process" { /** * The `subprocess.exitCode` property indicates the exit code of the child process. * If the child process is still running, the field will be `null`. + * + * When the child process is terminated by a signal, `subprocess.exitCode` will be + * `null` and `subprocess.signalCode` will be set. To get the corresponding + * POSIX exit code, use + * `util.convertProcessSignalToExitCode(subprocess.signalCode)`. */ readonly exitCode: number | null; /** @@ -281,7 +286,6 @@ declare module "child_process" { * new process in a shell or with the use of the `shell` option of `ChildProcess`: * * ```js - * 'use strict'; * import { spawn } from 'node:child_process'; * * const subprocess = spawn( diff --git a/types/node/v24/crypto.d.ts b/types/node/v24/crypto.d.ts index 886379fa442f60..98d87fa3704daa 100644 --- a/types/node/v24/crypto.d.ts +++ b/types/node/v24/crypto.d.ts @@ -615,30 +615,24 @@ declare module "crypto" { */ asymmetricKeyDetails?: AsymmetricKeyDetails; /** - * For symmetric keys, the following encoding options can be used: - * - * For public keys, the following encoding options can be used: - * - * For private keys, the following encoding options can be used: - * * The result type depends on the selected encoding format, when PEM the * result is a string, when DER it will be a buffer containing the data - * encoded as DER, when [JWK](https://tools.ietf.org/html/rfc7517) it will be an object. - * - * When [JWK](https://tools.ietf.org/html/rfc7517) encoding format was selected, all other encoding options are - * ignored. + * encoded as DER, when [JWK](https://tools.ietf.org/html/rfc7517) it will be an object. Raw formats return a + * `Buffer` containing the raw key material. * - * PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of - * the `cipher` and `format` options. The PKCS#8 `type` can be used with any`format` to encrypt any key algorithm (RSA, EC, or DH) by specifying a`cipher`. PKCS#1 and SEC1 can only be - * encrypted by specifying a `cipher`when the PEM `format` is used. For maximum compatibility, use PKCS#8 for - * encrypted private keys. Since PKCS#8 defines its own - * encryption mechanism, PEM-level encryption is not supported when encrypting - * a PKCS#8 key. See [RFC 5208](https://www.rfc-editor.org/rfc/rfc5208.txt) for PKCS#8 encryption and [RFC 1421](https://www.rfc-editor.org/rfc/rfc1421.txt) for - * PKCS#1 and SEC1 encryption. + * Private keys can be encrypted by specifying a `cipher` and `passphrase`. + * The PKCS#8 `type` supports encryption with both PEM and DER `format` for any + * key algorithm. PKCS#1 and SEC1 can only be encrypted when the PEM `format` is + * used. For maximum compatibility, use PKCS#8 for encrypted private keys. Since + * PKCS#8 defines its own encryption mechanism, PEM-level encryption is not + * supported when encrypting a PKCS#8 key. See [RFC 5208](https://www.rfc-editor.org/rfc/rfc5208.txt) for PKCS#8 encryption + * and [RFC 1421](https://www.rfc-editor.org/rfc/rfc1421.txt) for PKCS#1 and SEC1 encryption. * @since v11.6.0 */ export(options: KeyExportOptions<"pem">): string | NonSharedBuffer; - export(options?: KeyExportOptions<"der">): NonSharedBuffer; + export( + options?: KeyExportOptions<"der"> | { format: "raw-public" | "raw-private" | "raw-seed" }, + ): NonSharedBuffer; export(options?: JwkKeyExportOptions): JsonWebKey; /** * Returns `true` or `false` depending on whether the keys have exactly the same @@ -1203,17 +1197,29 @@ declare module "crypto" { } interface PrivateKeyInput { key: string | Buffer; - format?: KeyFormat | undefined; + format?: "pem" | "der" | undefined; type?: "pkcs1" | "pkcs8" | "sec1" | undefined; passphrase?: string | Buffer | undefined; encoding?: string | undefined; } + interface RawPrivateKeyInput { + key: Buffer; + format: "raw-private" | "raw-seed"; + asymmetricKeyType: KeyType; + namedCurve?: string | undefined; + } interface PublicKeyInput { key: string | Buffer; - format?: KeyFormat | undefined; + format?: "pem" | "der" | undefined; type?: "pkcs1" | "spki" | undefined; encoding?: string | undefined; } + interface RawPublicKeyInput { + key: Buffer; + format: "raw-public"; + asymmetricKeyType: KeyType; + namedCurve?: string | undefined; + } /** * Asynchronously generates a new random secret key of the given `length`. The `type` will determine which validations will be performed on the `length`. * @@ -1275,7 +1281,14 @@ declare module "crypto" { * of the passphrase is limited to 1024 bytes. * @since v11.6.0 */ - function createPrivateKey(key: PrivateKeyInput | string | Buffer | JsonWebKeyInput): KeyObject; + function createPrivateKey( + key: + | PrivateKeyInput + | RawPrivateKeyInput + | JsonWebKeyInput + | string + | NodeJS.ArrayBufferView, + ): KeyObject; /** * Creates and returns a new key object containing a public key. If `key` is a * string or `Buffer`, `format` is assumed to be `'pem'`; if `key` is a `KeyObject` with type `'private'`, the public key is derived from the given private key; @@ -1290,7 +1303,15 @@ declare module "crypto" { * and it will be impossible to extract the private key from the returned object. * @since v11.6.0 */ - function createPublicKey(key: PublicKeyInput | string | Buffer | KeyObject | JsonWebKeyInput): KeyObject; + function createPublicKey( + key: + | PublicKeyInput + | RawPublicKeyInput + | JsonWebKeyInput + | string + | NodeJS.ArrayBufferView + | KeyObject, + ): KeyObject; /** * Creates and returns a new key object containing a secret key for symmetric * encryption or `Hmac`. @@ -1324,15 +1345,17 @@ declare module "crypto" { context?: ArrayBuffer | NodeJS.ArrayBufferView | undefined; } interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions {} + interface SignRawPrivateKeyInput extends RawPrivateKeyInput, SigningOptions {} + interface SignJsonWebKeyInput extends JsonWebKeyInput, SigningOptions {} interface SignKeyObjectInput extends SigningOptions { key: KeyObject; } - interface SignJsonWebKeyInput extends JsonWebKeyInput, SigningOptions {} interface VerifyPublicKeyInput extends PublicKeyInput, SigningOptions {} + interface VerifyRawPublicKeyInput extends RawPublicKeyInput, SigningOptions {} + interface VerifyJsonWebKeyInput extends JsonWebKeyInput, SigningOptions {} interface VerifyKeyObjectInput extends SigningOptions { key: KeyObject; } - interface VerifyJsonWebKeyInput extends JsonWebKeyInput, SigningOptions {} type KeyLike = string | Buffer | KeyObject; /** * The `Sign` class is a utility for generating signatures. It can be used in one @@ -1423,9 +1446,21 @@ declare module "crypto" { * called. Multiple calls to `sign.sign()` will result in an error being thrown. * @since v0.1.92 */ - sign(privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput): NonSharedBuffer; sign( - privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput | SignJsonWebKeyInput, + privateKey: + | KeyLike + | SignKeyObjectInput + | SignPrivateKeyInput + | SignRawPrivateKeyInput + | SignJsonWebKeyInput, + ): NonSharedBuffer; + sign( + privateKey: + | KeyLike + | SignKeyObjectInput + | SignPrivateKeyInput + | SignRawPrivateKeyInput + | SignJsonWebKeyInput, outputFormat: BinaryToTextEncoding, ): string; } @@ -1472,9 +1507,9 @@ declare module "crypto" { update(data: BinaryLike): Verify; update(data: string, inputEncoding: Encoding): Verify; /** - * Verifies the provided data using the given `object` and `signature`. + * Verifies the provided data using the given `key` and `signature`. * - * If `object` is not a `KeyObject`, this function behaves as if `object` had been passed to {@link createPublicKey}. If it is an + * If `key` is not a `KeyObject`, this function behaves as if `key` had been passed to {@link createPublicKey}. If it is an * object, the following additional properties can be passed: * * The `signature` argument is the previously calculated signature for the data, in @@ -1491,13 +1526,23 @@ declare module "crypto" { * @since v0.1.92 */ verify( - object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + key: + | KeyLike + | VerifyKeyObjectInput + | VerifyPublicKeyInput + | VerifyRawPublicKeyInput + | VerifyJsonWebKeyInput, signature: NodeJS.ArrayBufferView, ): boolean; verify( - object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + object: + | KeyLike + | VerifyKeyObjectInput + | VerifyPublicKeyInput + | VerifyRawPublicKeyInput + | VerifyJsonWebKeyInput, signature: string, - signature_format?: BinaryToTextEncoding, + signatureEncoding?: BinaryToTextEncoding, ): boolean; } /** @@ -1577,8 +1622,10 @@ declare module "crypto" { * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. * * This function is a thin wrapper around [`DH_generate_key()`](https://www.openssl.org/docs/man3.0/man3/DH_generate_key.html). In particular, - * once a private key has been generated or set, calling this function only updates - * the public key but does not generate a new private key. + * once a private key has been generated or set, calling this function only + * recomputes the public key from the existing private key. Since the public key is + * determined by the private key, the result will be the same unless the private key + * has been changed via `diffieHellman.setPrivateKey()`. * @since v0.5.0 * @param encoding The `encoding` of the return value. */ @@ -2496,7 +2543,7 @@ declare module "crypto" { | "slh-dsa-shake-256s" | "x25519" | "x448"; - type KeyFormat = "pem" | "der" | "jwk"; + type KeyFormat = "pem" | "der" | "jwk" | "raw-public" | "raw-private" | "raw-seed"; interface BasePrivateKeyEncodingOptions { format: T; cipher?: string | undefined; @@ -3859,11 +3906,11 @@ declare module "crypto" { * @since v24.7.0 */ function decapsulate( - key: KeyLike | PrivateKeyInput | JsonWebKeyInput, + key: KeyLike | PrivateKeyInput | RawPrivateKeyInput | JsonWebKeyInput, ciphertext: ArrayBuffer | NodeJS.ArrayBufferView, ): NonSharedBuffer; function decapsulate( - key: KeyLike | PrivateKeyInput | JsonWebKeyInput, + key: KeyLike | PrivateKeyInput | RawPrivateKeyInput | JsonWebKeyInput, ciphertext: ArrayBuffer | NodeJS.ArrayBufferView, callback: (err: Error, sharedKey: NonSharedBuffer) => void, ): void; @@ -3875,9 +3922,11 @@ declare module "crypto" { * If the `callback` function is provided this function uses libuv's threadpool. * @since v13.9.0, v12.17.0 */ - function diffieHellman(options: { privateKey: KeyObject; publicKey: KeyObject }): NonSharedBuffer; function diffieHellman( - options: { privateKey: KeyObject; publicKey: KeyObject }, + options: { privateKey: KeyLike | PrivateKeyInput; publicKey: KeyLike | PublicKeyInput }, + ): NonSharedBuffer; + function diffieHellman( + options: { privateKey: KeyLike | PrivateKeyInput; publicKey: KeyLike | PublicKeyInput }, callback: (err: Error | null, secret: NonSharedBuffer) => void, ): void; /** @@ -3900,10 +3949,10 @@ declare module "crypto" { * @since v24.7.0 */ function encapsulate( - key: KeyLike | PublicKeyInput | JsonWebKeyInput, + key: KeyLike | PublicKeyInput | RawPublicKeyInput | JsonWebKeyInput, ): { sharedKey: NonSharedBuffer; ciphertext: NonSharedBuffer }; function encapsulate( - key: KeyLike | PublicKeyInput | JsonWebKeyInput, + key: KeyLike | PublicKeyInput | RawPublicKeyInput | JsonWebKeyInput, callback: (err: Error, result: { sharedKey: NonSharedBuffer; ciphertext: NonSharedBuffer }) => void, ): void; interface OneShotDigestOptions { @@ -4127,6 +4176,7 @@ declare module "crypto" { */ disableEntropyCache?: boolean | undefined; } + interface RandomUUIDV7Options extends RandomUUIDOptions {} type UUID = `${string}-${string}-${string}-${string}-${string}`; /** * Generates a random [RFC 4122](https://www.rfc-editor.org/rfc/rfc4122.txt) version 4 UUID. The UUID is generated using a @@ -4134,6 +4184,14 @@ declare module "crypto" { * @since v15.6.0, v14.17.0 */ function randomUUID(options?: RandomUUIDOptions): UUID; + /** + * Generates a random [RFC 9562](https://www.rfc-editor.org/rfc/rfc9562.txt) version 7 UUID. The UUID contains a millisecond + * precision Unix timestamp in the most significant 48 bits, followed by + * cryptographically secure random bits for the remaining fields, making it + * suitable for use as a database key with time-based sorting. + * @since v24.16.0 + */ + function randomUUIDv7(options?: RandomUUIDV7Options): UUID; interface X509CheckOptions { /** * @default 'always' @@ -4639,7 +4697,6 @@ declare module "crypto" { * ``` * @since v24.7.0 * @param algorithm Variant of Argon2, one of `"argon2d"`, `"argon2i"` or `"argon2id"`. - * @experimental */ function argon2( algorithm: Argon2Algorithm, @@ -4679,7 +4736,6 @@ declare module "crypto" { * console.log(derivedKey.toString('hex')); // 'af91dad...9520f15' * ``` * @since v24.7.0 - * @experimental */ function argon2Sync(algorithm: Argon2Algorithm, parameters: Argon2Parameters): NonSharedBuffer; /** @@ -4758,7 +4814,7 @@ declare module "crypto" { interface CShakeParams extends Algorithm { customization?: BufferSource; functionName?: BufferSource; - length: number; + outputLength: number; } interface ContextParams extends Algorithm { context?: BufferSource; @@ -4795,6 +4851,10 @@ declare module "crypto" { hash: HashAlgorithmIdentifier; length?: number; } + interface KangarooTwelveParams extends Algorithm { + customization?: BufferSource; + outputLength: number; + } interface JsonWebKey { alg?: string; crv?: string; @@ -4829,7 +4889,7 @@ declare module "crypto" { } interface KmacParams extends Algorithm { customization?: BufferSource; - length: number; + outputLength: number; } interface Pbkdf2Params extends Algorithm { hash: HashAlgorithmIdentifier; @@ -4864,6 +4924,10 @@ declare module "crypto" { interface RsaPssParams extends Algorithm { saltLength: number; } + interface TurboShakeParams extends Algorithm { + domainSeparation?: number; + outputLength: number; + } /** * Importing the `webcrypto` object (`import { webcrypto } from 'node:crypto'`) gives an instance of the `Crypto` class. * `Crypto` is a singleton that provides access to the remainder of the crypto API. @@ -4997,7 +5061,7 @@ declare module "crypto" { ciphertext: BufferSource, sharedKeyAlgorithm: AlgorithmIdentifier | HmacImportParams | AesDerivedKeyParams | KmacImportParams, extractable: boolean, - usages: KeyUsage[], + keyUsages: KeyUsage[], ): Promise; /** * Using the method and parameters specified in `algorithm` and the keying material provided by `key`, @@ -5095,7 +5159,10 @@ declare module "crypto" { * If `algorithm` is provided as an ``, it must have a `name` property whose value is one of the above. * @since v15.0.0 */ - digest(algorithm: AlgorithmIdentifier | CShakeParams, data: BufferSource): Promise; + digest( + algorithm: AlgorithmIdentifier | CShakeParams | TurboShakeParams | KangarooTwelveParams, + data: BufferSource, + ): Promise; /** * Uses a message recipient's asymmetric public key to encrypt a temporary symmetric key. * This encrypted key is the "encapsulated key" represented as `EncapsulatedBits`. @@ -5130,7 +5197,7 @@ declare module "crypto" { encapsulationKey: CryptoKey, sharedKeyAlgorithm: AlgorithmIdentifier | HmacImportParams | AesDerivedKeyParams | KmacImportParams, extractable: boolean, - usages: KeyUsage[], + keyUsages: KeyUsage[], ): Promise; /** * Using the method and parameters specified by `algorithm` and the keying material provided by `key`, diff --git a/types/node/v24/dgram.d.ts b/types/node/v24/dgram.d.ts index bc69f0b48e1a5a..d84fdcdf870404 100644 --- a/types/node/v24/dgram.d.ts +++ b/types/node/v24/dgram.d.ts @@ -42,6 +42,10 @@ declare module "dgram" { exclusive?: boolean | undefined; fd?: number | undefined; } + interface BindSyncOptions { + port?: number | undefined; + address?: string | undefined; + } type SocketType = "udp4" | "udp6"; interface SocketOptions extends Abortable { type: SocketType; @@ -137,10 +141,12 @@ declare module "dgram" { * messages on a named `port` and optional `address`. If `port` is not * specified or is `0`, the operating system will attempt to bind to a * random port. If `address` is not specified, the operating system will - * attempt to listen on all addresses. Once binding is complete, a `'listening'` event is emitted and the optional `callback` function is + * attempt to listen on all addresses. Once binding is complete, a + * `'listening'` event is emitted and the optional `callback` function is * called. * - * Specifying both a `'listening'` event listener and passing a `callback` to the `socket.bind()` method is not harmful but not very + * Specifying both a `'listening'` event listener and passing a + * `callback` to the `socket.bind()` method is not harmful but not very * useful. * * A bound datagram socket keeps the Node.js process running to receive @@ -177,9 +183,82 @@ declare module "dgram" { * @param callback with no parameters. Called when binding is complete. */ bind(port?: number, address?: string, callback?: () => void): this; - bind(port?: number, callback?: () => void): this; - bind(callback?: () => void): this; + bind(port: number, callback: () => void): this; + bind(callback: () => void): this; + /** + * For UDP sockets, causes the `dgram.Socket` to listen for datagram + * messages on a named `port` and optional `address` that are passed as + * properties of an `options` object passed as the first argument. If + * `port` is not specified or is `0`, the operating system will attempt + * to bind to a random port. If `address` is not specified, the operating + * system will attempt to listen on all addresses. Once binding is + * complete, a `'listening'` event is emitted and the optional `callback` + * function is called. + * + * The `options` object may contain a `fd` property. When a `fd` greater + * than `0` is set, it will wrap around an existing socket with the given + * file descriptor. In this case, the properties of `port` and `address` + * will be ignored. + * + * Specifying both a `'listening'` event listener and passing a + * `callback` to the `socket.bind()` method is not harmful but not very + * useful. + * + * The `options` object may contain an additional `exclusive` property that is + * used when using `dgram.Socket` objects with the [`cluster`](https://nodejs.org/docs/latest-v24.x/api/cluster.html) module. When + * `exclusive` is set to `false` (the default), cluster workers will use the same + * underlying socket handle allowing connection handling duties to be shared. + * When `exclusive` is `true`, however, the handle is not shared and attempted + * port sharing results in an error. Creating a `dgram.Socket` with the `reusePort` + * option set to `true` causes `exclusive` to always be `true` when `socket.bind()` + * is called. + * + * A bound datagram socket keeps the Node.js process running to receive + * datagram messages. + * + * If binding fails, an `'error'` event is generated. In rare case (e.g. + * attempting to bind with a closed socket), an `Error` may be thrown. + * + * An example socket listening on an exclusive port is shown below. + * + * ```js + * socket.bind({ + * address: 'localhost', + * port: 8000, + * exclusive: true, + * }); + * ``` + * @since v0.11.14 + * @param options Required. Supports the following properties: + */ bind(options: BindOptions, callback?: () => void): this; + /** + * The synchronous counterpart of `socket.bind()`. `bind(2)` is a local, + * non-blocking system call, so the bind is performed inline and the resolved + * address is returned immediately, including the operating-system-assigned + * ephemeral port when `port` is `0`: + * + * ```js + * const dgram = require('node:dgram'); + * + * const socket = dgram.createSocket('udp4'); + * const address = socket.bindSync({ address: '0.0.0.0', port: 0 }); + * console.log(address); // e.g. { address: '0.0.0.0', family: 'IPv4', port: 53124 } + * ``` + * + * A bind failure such as `EADDRINUSE` is thrown synchronously rather than emitted + * as an `'error'` event. After `bindSync()` returns, `socket.address()` is + * valid synchronously and the `'listening'` event is emitted on the next tick. + * + * `address` must be a numeric IP literal; `bindSync()` never performs DNS + * resolution (asynchronous name resolution being the only genuinely blocking part + * of binding). Incoming datagrams continue to be delivered asynchronously via the + * `'message'` event. `bindSync()` always binds the socket's own handle and + * does not participate in [`cluster`](https://nodejs.org/docs/latest-v24.x/api/cluster.html) handle sharing. + * @since v24.19.0 + * @returns The bound address as returned by `socket.address()`. + */ + bindSync(options?: BindSyncOptions): AddressInfo; /** * Close the underlying socket and stop listening for data on it. If a callback is * provided, it is added as a listener for the `'close'` event. @@ -202,6 +281,42 @@ declare module "dgram" { */ connect(port: number, address?: string, callback?: () => void): void; connect(port: number, callback: () => void): void; + /** + * The synchronous counterpart of `socket.connect()`. For a UDP socket + * `connect(2)` only records the default peer address and is a local, non-blocking + * system call, so the association is performed inline. Any error raised by the + * call itself (for example `EAFNOSUPPORT` for a mismatched address family) is + * thrown synchronously rather than reported via the `'error'` event. Because + * `connect(2)` does not probe reachability, errors such as `ECONNREFUSED` are + * still surfaced asynchronously on a later send or receive, exactly as for + * `socket.connect()`: + * + * ```js + * const dgram = require('node:dgram'); + * + * const socket = dgram.createSocket('udp4'); + * socket.connectSync(41234, '127.0.0.1'); + * console.log(socket.remoteAddress()); // { address: '127.0.0.1', family: 'IPv4', port: 41234 } + * ``` + * + * If the socket is still unbound it is bound synchronously first. After + * `connectSync()` returns, `socket.remoteAddress()` is valid synchronously + * and the `'connect'` event is emitted on the next tick. Trying to call + * `connectSync()` on an already connected socket throws an + * `ERR_SOCKET_DGRAM_IS_CONNECTED` exception, and calling it while an + * asynchronous `socket.bind()` is still in progress throws an + * `ERR_SOCKET_ALREADY_BOUND` exception. + * + * `address` must be a numeric IP literal; `connectSync()` never performs DNS + * resolution (asynchronous name resolution being the only genuinely blocking part + * of connecting). + * @since v24.19.0 + * @param address A numeric IP address to connect to. Unlike + * `socket.connect()`, no DNS resolution is performed, so a host name is not + * accepted. If omitted, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for + * `udp6` sockets) is used. + */ + connectSync(port: number, address?: string): void; /** * A synchronous function that disassociates a connected `dgram.Socket` from * its remote address. Trying to call `disconnect()` on an unbound or already diff --git a/types/node/v24/dns.d.ts b/types/node/v24/dns.d.ts index ba0d122131db78..327f7f5a54092e 100644 --- a/types/node/v24/dns.d.ts +++ b/types/node/v24/dns.d.ts @@ -81,7 +81,7 @@ declare module "dns" { */ all?: boolean | undefined; /** - * When `verbatim`, the resolved addresses are return unsorted. When `ipv4first`, the resolved addresses are sorted + * When `verbatim`, the resolved addresses are returned unsorted. When `ipv4first`, the resolved addresses are sorted * by placing IPv4 addresses before IPv6 addresses. When `ipv6first`, the resolved addresses are sorted by placing IPv6 * addresses before IPv4 addresses. Default value is configurable using * {@link setDefaultResultOrder} or [`--dns-result-order`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--dns-result-orderorder). @@ -539,7 +539,7 @@ declare module "dns" { * regexp: '', * replacement: '_sip._udp.example.com', * order: 30, - * preference: 100 + * preference: 100, * } * ``` * @since v0.9.12 @@ -596,7 +596,7 @@ declare module "dns" { * refresh: 10000, * retry: 2400, * expire: 604800, - * minttl: 3600 + * minttl: 3600, * } * ``` * @since v0.11.10 @@ -622,7 +622,7 @@ declare module "dns" { * priority: 10, * weight: 5, * port: 21223, - * name: 'service.example.com' + * name: 'service.example.com', * } * ``` * @since v0.1.27 @@ -649,7 +649,7 @@ declare module "dns" { * certUsage: 3, * selector: 1, * match: 1, - * data: [ArrayBuffer] + * data: [ArrayBuffer], * } * ``` * @since v23.9.0, v22.15.0 @@ -699,7 +699,7 @@ declare module "dns" { * refresh: 900, * retry: 900, * expire: 1800, - * minttl: 60 } ] + * minttl: 60 } ]; * ``` * * DNS server operators may choose not to respond to `ANY` queries. It may be better to call individual methods like {@link resolve4}, {@link resolveMx}, and so on. For more details, see diff --git a/types/node/v24/dns/promises.d.ts b/types/node/v24/dns/promises.d.ts index efb9fbfdf42585..e9b7def1abe84e 100644 --- a/types/node/v24/dns/promises.d.ts +++ b/types/node/v24/dns/promises.d.ts @@ -189,7 +189,7 @@ declare module "dns/promises" { * refresh: 900, * retry: 900, * expire: 1800, - * minttl: 60 } ] + * minttl: 60 } ]; * ``` * @since v10.6.0 */ @@ -232,7 +232,7 @@ declare module "dns/promises" { * regexp: '', * replacement: '_sip._udp.example.com', * order: 30, - * preference: 100 + * preference: 100, * } * ``` * @since v10.6.0 @@ -271,7 +271,7 @@ declare module "dns/promises" { * refresh: 10000, * retry: 2400, * expire: 604800, - * minttl: 3600 + * minttl: 3600, * } * ``` * @since v10.6.0 @@ -291,7 +291,7 @@ declare module "dns/promises" { * priority: 10, * weight: 5, * port: 21223, - * name: 'service.example.com' + * name: 'service.example.com', * } * ``` * @since v10.6.0 @@ -312,7 +312,7 @@ declare module "dns/promises" { * certUsage: 3, * selector: 1, * match: 1, - * data: [ArrayBuffer] + * data: [ArrayBuffer], * } * ``` * @since v23.9.0, v22.15.0 diff --git a/types/node/v24/events.d.ts b/types/node/v24/events.d.ts index 023348e02f3690..6990e74345aa2e 100644 --- a/types/node/v24/events.d.ts +++ b/types/node/v24/events.d.ts @@ -278,23 +278,17 @@ declare module "events" { options?: StaticEventEmitterIteratorOptions, ): NodeJS.AsyncIterator; /** - * A class method that returns the number of listeners for the given `eventName` registered on the given `emitter`. + * Returns the number of registered listeners for the event named `eventName`. * - * ```js - * import { EventEmitter, listenerCount } from 'node:events'; + * For `EventEmitter`s this behaves exactly the same as calling `.listenerCount` + * on the emitter. * - * const myEmitter = new EventEmitter(); - * myEmitter.on('event', () => {}); - * myEmitter.on('event', () => {}); - * console.log(listenerCount(myEmitter, 'event')); - * // Prints: 2 - * ``` + * For `EventTarget`s this is the only way to obtain the listener count. This can + * be useful for debugging and diagnostic purposes. * @since v0.9.12 - * @deprecated Since v3.2.0 - Use `listenerCount` instead. - * @param emitter The emitter to query - * @param eventName The event name */ - static listenerCount(emitter: NodeJS.EventEmitter, eventName: string | symbol): number; + static listenerCount(emitter: EventEmitter, eventName: string | symbol): number; + static listenerCount(emitter: EventTarget, eventName: string): number; /** * Returns a copy of the array of listeners for the event named `eventName`. * @@ -386,15 +380,12 @@ declare module "events" { * import { addAbortListener } from 'node:events'; * * function example(signal) { - * let disposable; - * try { - * signal.addEventListener('abort', (e) => e.stopImmediatePropagation()); - * disposable = addAbortListener(signal, (e) => { - * // Do something when signal is aborted. - * }); - * } finally { - * disposable?.[Symbol.dispose](); - * } + * signal.addEventListener('abort', (e) => e.stopImmediatePropagation()); + * // addAbortListener() returns a disposable, so the `using` keyword ensures + * // the abort listener is automatically removed when this scope exits. + * using _ = addAbortListener(signal, (e) => { + * // Do something when signal is aborted. + * }); * } * ``` * @since v20.5.0 diff --git a/types/node/v24/fs.d.ts b/types/node/v24/fs.d.ts index 24f37dcfd79bc7..c79738dfc5282e 100644 --- a/types/node/v24/fs.d.ts +++ b/types/node/v24/fs.d.ts @@ -19,7 +19,7 @@ * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/fs.js) */ declare module "fs" { - import { NonSharedBuffer } from "node:buffer"; + import { BufferView, NonSharedBuffer } from "node:buffer"; import * as stream from "node:stream"; import { Abortable, EventEmitter } from "node:events"; import { URL } from "node:url"; @@ -147,6 +147,8 @@ declare module "fs" { bavail: T; /** Total file nodes in file system. */ files: T; + /** Fundamental file system block size. */ + frsize: T; /** Free file nodes in file system. */ ffree: T; } @@ -422,7 +424,8 @@ declare module "fs" { prependOnceListener(event: "error", listener: (error: Error) => void): this; } /** - * Instances of `fs.ReadStream` are created and returned using the {@link createReadStream} function. + * Instances of `fs.ReadStream` cannot be constructed directly. They are created and + * returned using the `fs.createReadStream()` function. * @since v0.1.93 */ export class ReadStream extends stream.Readable { @@ -717,9 +720,8 @@ declare module "fs" { unpipe: (src: stream.Readable) => void; } & CustomEvents; /** - * * Extends `stream.Writable` - * - * Instances of `fs.WriteStream` are created and returned using the {@link createWriteStream} function. + * Instances of `fs.WriteStream` cannot be constructed directly. They are created and + * returned using the `fs.createWriteStream()` function. * @since v0.1.93 */ export class WriteStream extends stream.Writable { @@ -1180,6 +1182,7 @@ declare module "fs" { options: | (StatOptions & { bigint?: false | undefined; + throwIfNoEntry?: true | undefined; }) | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, @@ -1188,13 +1191,32 @@ declare module "fs" { path: PathLike, options: StatOptions & { bigint: true; + throwIfNoEntry?: true | undefined; }, callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, ): void; + export function stat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + throwIfNoEntry: false; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | undefined) => void, + ): void; + export function stat( + path: PathLike, + options: StatOptions & { + bigint: true; + throwIfNoEntry: false; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats | undefined) => void, + ): void; export function stat( path: PathLike, options: StatOptions | undefined, - callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats | undefined) => void, ): void; export namespace stat { /** @@ -1205,15 +1227,31 @@ declare module "fs" { path: PathLike, options?: StatOptions & { bigint?: false | undefined; + throwIfNoEntry?: true | undefined; }, ): Promise; function __promisify__( path: PathLike, options: StatOptions & { bigint: true; + throwIfNoEntry?: true | undefined; }, ): Promise; - function __promisify__(path: PathLike, options?: StatOptions): Promise; + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + throwIfNoEntry: false; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + throwIfNoEntry: false; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; } export interface StatSyncFn extends Function { (path: PathLike, options?: undefined): Stats; @@ -2965,6 +3003,21 @@ declare module "fs" { * If no `options` object is specified, it will default with the above values. */ export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, opts?: ReadOptions): number; + export interface ReadFileOptions extends Abortable { + encoding?: BufferEncoding | null | undefined; + flag?: OpenMode | undefined; + } + export interface ReadFileOptionsWithStringEncoding extends ReadFileOptions { + encoding: BufferEncoding; + } + export interface ReadFileOptionsWithBufferEncoding extends ReadFileOptions { + encoding?: null | undefined; + } + export interface ReadFileOptionsWithBuffer + extends ReadFileOptionsWithBufferEncoding + { + buffer: T | ((size: number) => T); + } /** * Asynchronously reads the entire contents of a file. * @@ -2982,6 +3035,11 @@ declare module "fs" { * * If no encoding is specified, then the raw buffer is returned. * + * If `buffer` is provided and no encoding is specified, the returned `Buffer` is + * a view over the supplied buffer containing only the bytes read. If the + * supplied buffer is too small to contain the entire file, the callback is + * called with an error. + * * If `options` is a string, then it specifies the encoding: * * ```js @@ -2990,7 +3048,8 @@ declare module "fs" { * readFile('/etc/passwd', 'utf8', callback); * ``` * - * When the path is a directory, the behavior of `fs.readFile()` and {@link readFileSync} is platform-specific. On macOS, Linux, and Windows, an + * When the path is a directory, the behavior of `fs.readFile()` and + * `fs.readFileSync()` is platform-specific. On macOS, Linux, and Windows, an * error will be returned. On FreeBSD, a representation of the directory's contents * will be returned. * @@ -3028,60 +3087,56 @@ declare module "fs" { * * Aborting an ongoing request does not abort individual operating * system requests but rather the internal buffering `fs.readFile` performs. + * + * An example using the `buffer` option with a pre-allocated buffer: + * + * ```js + * import { Buffer } from 'node:buffer'; + * import { readFile } from 'node:fs'; + * + * const buf = Buffer.alloc(16384); + * readFile('/path/to/file', { buffer: buf }, (err, data) => { + * if (err) throw err; + * console.log(data); // A view over `buf` containing only the bytes read + * }); + * ``` + * + * An example using the `buffer` option with a function returning a buffer: + * + * ```js + * import { Buffer } from 'node:buffer'; + * import { readFile } from 'node:fs'; + * + * readFile('/path/to/file', { + * buffer: (size) => Buffer.alloc(size), + * }, (err, data) => { + * if (err) throw err; + * console.log(data); + * }); + * ``` * @since v0.1.29 * @param path filename or file descriptor */ + export function readFile( + path: PathOrFileDescriptor, + options: ReadFileOptionsWithBuffer, + callback: (err: NodeJS.ErrnoException | null, data: BufferView) => void, + ): void; export function readFile( path: PathOrFileDescriptor, - options: - | ({ - encoding?: null | undefined; - flag?: string | undefined; - } & Abortable) - | undefined - | null, + options: ReadFileOptionsWithBufferEncoding | null | undefined, callback: (err: NodeJS.ErrnoException | null, data: NonSharedBuffer) => void, ): void; - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ export function readFile( path: PathOrFileDescriptor, - options: - | ({ - encoding: BufferEncoding; - flag?: string | undefined; - } & Abortable) - | BufferEncoding, + options: ReadFileOptionsWithStringEncoding | BufferEncoding, callback: (err: NodeJS.ErrnoException | null, data: string) => void, ): void; - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ export function readFile( path: PathOrFileDescriptor, - options: - | (ObjectEncodingOptions & { - flag?: string | undefined; - } & Abortable) - | BufferEncoding - | undefined - | null, + options: ReadFileOptions | BufferEncoding | null | undefined, callback: (err: NodeJS.ErrnoException | null, data: string | NonSharedBuffer) => void, ): void; - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - */ export function readFile( path: PathOrFileDescriptor, callback: (err: NodeJS.ErrnoException | null, data: NonSharedBuffer) => void, @@ -3136,16 +3191,37 @@ declare module "fs" { | null, ): Promise; } + export interface ReadFileSyncOptions { + encoding?: BufferEncoding | null | undefined; + flag?: OpenMode | undefined; + } + export interface ReadFileSyncOptionsWithStringEncoding extends ReadFileSyncOptions { + encoding: BufferEncoding; + } + export interface ReadFileSyncOptionsWithBufferEncoding extends ReadFileSyncOptions { + encoding?: null | undefined; + } + export interface ReadFileSyncOptionsWithBuffer + extends ReadFileSyncOptionsWithBufferEncoding + { + buffer: T | ((size: number) => T); + } /** * Returns the contents of the `path`. * * For detailed information, see the documentation of the asynchronous version of - * this API: {@link readFile}. + * this API: `fs.readFile()`. * * If the `encoding` option is specified then this function returns a * string. Otherwise it returns a buffer. * - * Similar to {@link readFile}, when the path is a directory, the behavior of `fs.readFileSync()` is platform-specific. + * If `buffer` is provided and no encoding is specified, the returned {Buffer} is + * a view over the supplied buffer containing only the bytes read. If the + * supplied buffer is too small to contain the entire file, an error will be + * thrown. + * + * Similar to `fs.readFile()`, when the path is a directory, the behavior of + * `fs.readFileSync()` is platform-specific. * * ```js * import { readFileSync } from 'node:fs'; @@ -3160,45 +3236,19 @@ declare module "fs" { * @since v0.1.8 * @param path filename or file descriptor */ + export function readFileSync( + path: PathOrFileDescriptor, + options: ReadFileSyncOptionsWithBuffer, + ): BufferView; export function readFileSync( path: PathOrFileDescriptor, - options?: { - encoding?: null | undefined; - flag?: string | undefined; - } | null, + options?: ReadFileSyncOptionsWithBufferEncoding | null, ): NonSharedBuffer; - /** - * Synchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ export function readFileSync( path: PathOrFileDescriptor, - options: - | { - encoding: BufferEncoding; - flag?: string | undefined; - } - | BufferEncoding, + options: ReadFileSyncOptionsWithStringEncoding | BufferEncoding, ): string; - /** - * Synchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a file descriptor is provided, the underlying file will _not_ be closed automatically. - * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ - export function readFileSync( - path: PathOrFileDescriptor, - options?: - | (ObjectEncodingOptions & { - flag?: string | undefined; - }) - | BufferEncoding - | null, - ): string | NonSharedBuffer; + export function readFileSync(path: PathOrFileDescriptor, options: ReadFileSyncOptions): string | NonSharedBuffer; export type WriteFileOptions = | ( & ObjectEncodingOptions @@ -3594,10 +3644,12 @@ declare module "fs" { */ export function unwatchFile(filename: PathLike, listener?: StatsListener): void; export function unwatchFile(filename: PathLike, listener?: BigIntStatsListener): void; + type WatchIgnorePredicate = string | RegExp | ((filename: string) => boolean); export interface WatchOptions extends Abortable { encoding?: BufferEncoding | "buffer" | undefined; persistent?: boolean | undefined; recursive?: boolean | undefined; + ignore?: WatchIgnorePredicate | readonly WatchIgnorePredicate[] | undefined; } export interface WatchOptionsWithBufferEncoding extends WatchOptions { encoding: "buffer"; @@ -4520,10 +4572,9 @@ declare module "fs" { } export interface StatOptions { bigint?: boolean | undefined; - } - export interface StatSyncOptions extends StatOptions { throwIfNoEntry?: boolean | undefined; } + export interface StatSyncOptions extends StatOptions {} interface CopyOptionsBase { /** * Dereference symlinks @@ -4620,12 +4671,6 @@ declare module "fs" { * @default process.cwd() */ cwd?: string | URL | undefined; - /** - * `true` if the glob should return paths as `Dirent`s, `false` otherwise. - * @default false - * @since v22.2.0 - */ - withFileTypes?: boolean | undefined; /** * Function to filter out files/directories or a * list of glob patterns to be excluded. If a function is provided, return @@ -4636,6 +4681,18 @@ declare module "fs" { * @default undefined */ exclude?: ((fileName: T) => boolean) | readonly string[] | undefined; + /** + * When `true`, symbolic links to directories are + * followed while expanding `**` patterns. + * @default false + */ + followSymlinks?: boolean | undefined; + /** + * `true` if the glob should return paths as `Dirent`s, `false` otherwise. + * @default false + * @since v22.2.0 + */ + withFileTypes?: boolean | undefined; } export interface GlobOptions extends _GlobOptions {} export interface GlobOptionsWithFileTypes extends _GlobOptions { @@ -4648,6 +4705,9 @@ declare module "fs" { /** * Retrieves the files matching the specified pattern. * + * When `followSymlinks` is enabled, detected symbolic link cycles are not + * traversed recursively. + * * ```js * import { glob } from 'node:fs'; * @@ -4687,6 +4747,9 @@ declare module "fs" { ) => void, ): void; /** + * When `followSymlinks` is enabled, detected symbolic link cycles are not + * traversed recursively. + * * ```js * import { globSync } from 'node:fs'; * diff --git a/types/node/v24/fs/promises.d.ts b/types/node/v24/fs/promises.d.ts index 237b1f2ef51379..5640fc12654ebe 100644 --- a/types/node/v24/fs/promises.d.ts +++ b/types/node/v24/fs/promises.d.ts @@ -9,9 +9,8 @@ * @since v10.0.0 */ declare module "fs/promises" { - import { NonSharedBuffer } from "node:buffer"; + import { BufferView, NonSharedBuffer } from "node:buffer"; import { Abortable } from "node:events"; - import { Stream } from "node:stream"; import { ReadableStream } from "node:stream/web"; import { BigIntStats, @@ -31,6 +30,10 @@ declare module "fs/promises" { OpenDirOptions, OpenMode, PathLike, + ReadFileOptions, + ReadFileOptionsWithBuffer, + ReadFileOptionsWithBufferEncoding, + ReadFileOptionsWithStringEncoding, ReadOptions, ReadOptionsWithBuffer, ReadPosition, @@ -281,39 +284,61 @@ declare module "fs/promises" { * * If `options` is a string, then it specifies the `encoding`. * + * If `buffer` is provided and no encoding is specified, the returned {Buffer} is + * a view over the supplied buffer containing only the bytes read. If the + * supplied buffer is too small to contain the entire file, the operation will + * fail. + * * The `FileHandle` has to support reading. * - * If one or more `filehandle.read()` calls are made on a file handle and then a `filehandle.readFile()` call is made, the data will be read from the current + * If one or more `filehandle.read()` calls are made on a file handle and then a + * `filehandle.readFile()` call is made, the data will be read from the current * position till the end of the file. It doesn't always read from the beginning * of the file. + * + * An example using the `buffer` option with a pre-allocated buffer: + * + * ```js + * import { Buffer } from 'node:buffer'; + * import { open } from 'node:fs/promises'; + * + * const file = await open('./some/file/to/read'); + * try { + * const buf = Buffer.alloc(16384); + * const contents = await file.readFile({ buffer: buf }); + * console.log(contents); // A view over `buf` containing only the bytes read + * } finally { + * await file.close(); + * } + * ``` + * + * An example using the `buffer` option with a function returning a buffer: + * + * ```js + * import { Buffer } from 'node:buffer'; + * import { open } from 'node:fs/promises'; + * + * const file = await open('./some/file/to/read'); + * try { + * const contents = await file.readFile({ + * buffer: (size) => Buffer.alloc(size), + * }); + * console.log(contents); + * } finally { + * await file.close(); + * } + * ``` * @since v10.0.0 - * @return Fulfills upon a successful read with the contents of the file. If no encoding is specified (using `options.encoding`), the data is returned as a {Buffer} object. Otherwise, the - * data will be a string. + * @returns Fulfills upon a successful read with the contents of the + * file. If no encoding is specified (using `options.encoding`), the data is + * returned as a `Buffer` object. Otherwise, the data will be a string. */ - readFile( - options?: - | ({ encoding?: null | undefined } & Abortable) - | null, - ): Promise; - /** - * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. - * The `FileHandle` must have been opened for reading. - */ - readFile( - options: - | ({ encoding: BufferEncoding } & Abortable) - | BufferEncoding, - ): Promise; - /** - * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. - * The `FileHandle` must have been opened for reading. - */ - readFile( - options?: - | (ObjectEncodingOptions & Abortable) - | BufferEncoding - | null, - ): Promise; + readFile( + options: Omit, "flag">, + ): Promise>; + readFile(options?: Omit | null): Promise; + readFile(options: Omit | BufferEncoding): Promise; + readFile(options: Omit | BufferEncoding | null): Promise; /** * Convenience method to create a `readline` interface and stream over the file. * See `filehandle.createReadStream()` for the options. @@ -337,14 +362,28 @@ declare module "fs/promises" { stat( opts?: StatOptions & { bigint?: false | undefined; + throwIfNoEntry?: true | undefined; }, ): Promise; stat( opts: StatOptions & { bigint: true; + throwIfNoEntry?: true | undefined; }, ): Promise; - stat(opts?: StatOptions): Promise; + stat( + opts?: StatOptions & { + bigint?: false | undefined; + throwIfNoEntry: false; + }, + ): Promise; + stat( + opts: StatOptions & { + bigint: true; + throwIfNoEntry: false; + }, + ): Promise; + stat(opts?: StatOptions): Promise; /** * Truncates the file. * @@ -1172,50 +1211,21 @@ declare module "fs/promises" { * @param path filename or `FileHandle` * @return Fulfills with the contents of the file. */ + function readFile( + path: PathLike | FileHandle, + options: ReadFileOptionsWithBuffer, + ): Promise>; function readFile( path: PathLike | FileHandle, - options?: - | ({ - encoding?: null | undefined; - flag?: OpenMode | undefined; - } & Abortable) - | null, + options?: ReadFileOptionsWithBufferEncoding | null, ): Promise; - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ function readFile( path: PathLike | FileHandle, - options: - | ({ - encoding: BufferEncoding; - flag?: OpenMode | undefined; - } & Abortable) - | BufferEncoding, + options: ReadFileOptionsWithStringEncoding | BufferEncoding, ): Promise; - /** - * Asynchronously reads the entire contents of a file. - * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. - * @param options An object that may contain an optional flag. - * If a flag is not provided, it defaults to `'r'`. - */ function readFile( path: PathLike | FileHandle, - options?: - | ( - & ObjectEncodingOptions - & Abortable - & { - flag?: OpenMode | undefined; - } - ) - | BufferEncoding - | null, + options: ReadFileOptions | BufferEncoding | null, ): Promise; /** * Asynchronously open a directory for iterative scanning. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for more detail. @@ -1312,6 +1322,9 @@ declare module "fs/promises" { */ function cp(source: string | URL, destination: string | URL, opts?: CopyOptions): Promise; /** + * When `followSymlinks` is enabled, detected symbolic link cycles are not + * traversed recursively. + * * ```js * import { glob } from 'node:fs/promises'; * diff --git a/types/node/v24/http.d.ts b/types/node/v24/http.d.ts index 5b4cf59bff75ab..ecfe54fb8aa04a 100644 --- a/types/node/v24/http.d.ts +++ b/types/node/v24/http.d.ts @@ -216,6 +216,7 @@ declare module "http" { headers?: OutgoingHttpHeaders | readonly string[] | undefined; host?: string | null | undefined; hostname?: string | null | undefined; + httpValidation?: "strict" | "relaxed" | "insecure" | undefined; insecureHTTPParser?: boolean | undefined; localAddress?: string | undefined; localPort?: number | undefined; @@ -265,7 +266,7 @@ declare module "http" { * The number of milliseconds of inactivity a server needs to wait for additional incoming data, * after it has finished writing the last response, before a socket will be destroyed. * @see Server.keepAliveTimeout for more information. - * @default 5000 + * @default 65000 * @since v18.0.0 */ keepAliveTimeout?: number | undefined; @@ -295,6 +296,21 @@ declare module "http" { * @since v20.1.0 */ highWaterMark?: number | undefined; + /** + * Controls HTTP header value validation strictness + * for incoming requests. Accepted values are: + * * `'strict'`: Strictest validation; rejects any non-ASCII or control + * characters in header values. + * * `'relaxed'`: Allows a limited set of non-ASCII characters in header + * values, aligning with the + * [Fetch specification](https://fetch.spec.whatwg.org/). + * * `'insecure'`: Disables all header value validation (equivalent to + * `insecureHTTPParser: true`). + * + * Cannot be used together with `insecureHTTPParser`. **Default:** `'strict'`. + * @since v24.19.0 + */ + httpValidation?: "strict" | "relaxed" | "insecure" | undefined; /** * Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. * Using the insecure parser should be avoided. @@ -324,7 +340,7 @@ declare module "http" { requireHostHeader?: boolean | undefined; /** * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, - * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. + * similarly on what is done in `socket.setKeepAlive()`. * @default false * @since v16.5.0 */ @@ -956,6 +972,36 @@ declare module "http" { headers?: OutgoingHttpHeaders | OutgoingHttpHeader[], ): this; writeHead(statusCode: number, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; + /** + * Sends an arbitrary HTTP/1.1 1xx informational response to the client. This + * is a generic equivalent of `response.writeContinue()`, + * `response.writeProcessing()` and `response.writeEarlyHints()`, and + * can be called multiple times before the final response. After the final + * response headers have been sent (via `response.writeHead()` or an + * implicit header), calling this method throws `ERR_HTTP_HEADERS_SENT`. + * + * Clients receive these responses via the [`'information'`](https://nodejs.org/docs/latest-v24.x/api/http.html#event-information) + * event on `http.ClientRequest`. + * + * ```js + * response.writeInformation(110, { 'X-Progress': '50%' }); + * ``` + * @since v24.18.0 + * @param statusCode An HTTP 1xx informational status code, between `100` + * and `199` inclusive, excluding `101` (Switching Protocols) which is only + * available through the [`'upgrade'`](https://nodejs.org/docs/latest-v24.x/api/http.html#event-upgrade) event. + * @param headers An optional set of headers to send with the + * informational response. Accepts the same shapes as + * `response.writeHead()`. + * @param callback Optional, called once the message has been written + * to the socket. + */ + writeInformation( + statusCode: number, + headers?: OutgoingHttpHeaders | readonly string[], + callback?: () => void, + ): void; + writeInformation(statusCode: number, callback: () => void): void; /** * Sends a HTTP/1.1 102 Processing message to the client, indicating that * the request body should be sent. @@ -1411,6 +1457,31 @@ declare module "http" { * @since v0.5.9 */ setTimeout(msecs: number, callback?: () => void): this; + /** + * An `AbortSignal` that is aborted when the underlying socket closes or the + * request is destroyed. The signal is created lazily on first access — no + * `AbortController` is allocated for requests that never use this property. + * + * This is useful for cancelling downstream asynchronous work such as database + * queries or `fetch` calls when a client disconnects mid-request. + * + * ```js + * import http from 'node:http'; + * + * http.createServer(async (req, res) => { + * try { + * const data = await fetch('https://example.com/api', { signal: req.signal }); + * res.end(JSON.stringify(await data.json())); + * } catch (err) { + * if (err.name === 'AbortError') return; + * res.statusCode = 500; + * res.end('Internal Server Error'); + * } + * }).listen(3000); + * ``` + * @since v24.16.0 + */ + readonly signal: AbortSignal; /** * **Only valid for request obtained from {@link Server}.** * @@ -2123,6 +2194,27 @@ declare module "http" { * @param [max=1000] */ function setMaxIdleHTTPParsers(max: number): void; + /** + * Dynamically resets the global configurations to enable built-in proxy support for + * `fetch()` and `http.request()`/`https.request()` at runtime, as an alternative + * to using the `--use-env-proxy` flag or `NODE_USE_ENV_PROXY` environment variable. + * It can also be used to override settings configured from the environment variables. + * + * As this function resets the global configurations, any previously configured + * `http.globalAgent`, `https.globalAgent` or undici global dispatcher would be + * overridden after this function is invoked. It's recommended to invoke it before any + * requests are made and avoid invoking it in the middle of any requests. + * + * See [Built-in Proxy Support](https://nodejs.org/docs/latest-v24.x/api/http.html#built-in-proxy-support) for details on proxy URL formats and `NO_PROXY` + * syntax. + * @since v24.14.0 + * @param proxyEnv An object containing proxy configuration. This accepts the + * same options as the `proxyEnv` option accepted by {@link Agent}. **Default:** + * `process.env`. + * @returns A function that restores the original agent and dispatcher + * settings to the state before this `http.setGlobalProxyFromEnv()` is invoked. + */ + function setGlobalProxyFromEnv(proxyEnv?: ProxyEnv): () => void; /** * Global instance of `Agent` which is used as the default for all HTTP client * requests. Diverges from a default `Agent` configuration by having `keepAlive` diff --git a/types/node/v24/http2.d.ts b/types/node/v24/http2.d.ts index 84b78fb6e22859..34b4aa911e72e5 100644 --- a/types/node/v24/http2.d.ts +++ b/types/node/v24/http2.d.ts @@ -206,7 +206,10 @@ declare module "http2" { addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; addListener(event: "streamClosed", listener: (code: number) => void): this; addListener(event: "timeout", listener: () => void): this; - addListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + addListener( + event: "trailers", + listener: (trailers: IncomingHttpHeaders, flags: number, rawHeaders: string[]) => void, + ): this; addListener(event: "wantTrailers", listener: () => void): this; addListener(event: string | symbol, listener: (...args: any[]) => void): this; emit(event: "aborted"): boolean; @@ -221,7 +224,7 @@ declare module "http2" { emit(event: "unpipe", src: stream.Readable): boolean; emit(event: "streamClosed", code: number): boolean; emit(event: "timeout"): boolean; - emit(event: "trailers", trailers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "trailers", trailers: IncomingHttpHeaders, flags: number, rawHeaders: string[]): boolean; emit(event: "wantTrailers"): boolean; emit(event: string | symbol, ...args: any[]): boolean; on(event: "aborted", listener: () => void): this; @@ -236,7 +239,10 @@ declare module "http2" { on(event: "unpipe", listener: (src: stream.Readable) => void): this; on(event: "streamClosed", listener: (code: number) => void): this; on(event: "timeout", listener: () => void): this; - on(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + on( + event: "trailers", + listener: (trailers: IncomingHttpHeaders, flags: number, rawHeaders: string[]) => void, + ): this; on(event: "wantTrailers", listener: () => void): this; on(event: string | symbol, listener: (...args: any[]) => void): this; once(event: "aborted", listener: () => void): this; @@ -251,7 +257,10 @@ declare module "http2" { once(event: "unpipe", listener: (src: stream.Readable) => void): this; once(event: "streamClosed", listener: (code: number) => void): this; once(event: "timeout", listener: () => void): this; - once(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + once( + event: "trailers", + listener: (trailers: IncomingHttpHeaders, flags: number, rawHeaders: string[]) => void, + ): this; once(event: "wantTrailers", listener: () => void): this; once(event: string | symbol, listener: (...args: any[]) => void): this; prependListener(event: "aborted", listener: () => void): this; @@ -269,7 +278,10 @@ declare module "http2" { prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; prependListener(event: "streamClosed", listener: (code: number) => void): this; prependListener(event: "timeout", listener: () => void): this; - prependListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependListener( + event: "trailers", + listener: (trailers: IncomingHttpHeaders, flags: number, rawHeaders: string[]) => void, + ): this; prependListener(event: "wantTrailers", listener: () => void): this; prependListener(event: string | symbol, listener: (...args: any[]) => void): this; prependOnceListener(event: "aborted", listener: () => void): this; @@ -287,7 +299,10 @@ declare module "http2" { prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; prependOnceListener(event: "streamClosed", listener: (code: number) => void): this; prependOnceListener(event: "timeout", listener: () => void): this; - prependOnceListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener( + event: "trailers", + listener: (trailers: IncomingHttpHeaders, flags: number, rawHeaders: string[]) => void, + ): this; prependOnceListener(event: "wantTrailers", listener: () => void): this; prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; } @@ -301,7 +316,10 @@ declare module "http2" { rawHeaders: string[], ) => void, ): this; - addListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + addListener( + event: "push", + listener: (headers: IncomingHttpHeaders, flags: number, rawHeaders: string[]) => void, + ): this; addListener( event: "response", listener: ( @@ -318,7 +336,7 @@ declare module "http2" { flags: number, rawHeaders: string[], ): boolean; - emit(event: "push", headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "push", headers: IncomingHttpHeaders, flags: number, rawHeaders: string[]): boolean; emit( event: "response", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, @@ -335,7 +353,7 @@ declare module "http2" { rawHeaders: string[], ) => void, ): this; - on(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "push", listener: (headers: IncomingHttpHeaders, flags: number, rawHeaders: string[]) => void): this; on( event: "response", listener: ( @@ -354,7 +372,10 @@ declare module "http2" { rawHeaders: string[], ) => void, ): this; - once(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + once( + event: "push", + listener: (headers: IncomingHttpHeaders, flags: number, rawHeaders: string[]) => void, + ): this; once( event: "response", listener: ( @@ -373,7 +394,10 @@ declare module "http2" { rawHeaders: string[], ) => void, ): this; - prependListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener( + event: "push", + listener: (headers: IncomingHttpHeaders, flags: number, rawHeaders: string[]) => void, + ): this; prependListener( event: "response", listener: ( @@ -392,7 +416,10 @@ declare module "http2" { rawHeaders: string[], ) => void, ): this; - prependOnceListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener( + event: "push", + listener: (headers: IncomingHttpHeaders, flags: number, rawHeaders: string[]) => void, + ): this; prependOnceListener( event: "response", listener: ( @@ -531,7 +558,7 @@ declare module "http2" { * * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event * will be emitted immediately after queuing the last chunk of payload data to be - * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * sent. The `http2stream.sendTrailers()` method can then be used to send trailing * header fields to the peer. * * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically @@ -646,7 +673,7 @@ declare module "http2" { * * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event * will be emitted immediately after queuing the last chunk of payload data to be - * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * sent. The `http2stream.sendTrailers()` method can then be used to send trailing * header fields to the peer. * * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically @@ -988,9 +1015,12 @@ declare module "http2" { * HTTP/2 request to the connected server. * * When a `ClientHttp2Session` is first created, the socket may not yet be - * connected. if `clienthttp2session.request()` is called during this time, the + * connected. If `clienthttp2session.request()` is called during this time, the * actual request will be deferred until the socket is ready to go. - * If the `session` is closed before the actual request be executed, an `ERR_HTTP2_GOAWAY_SESSION` is thrown. + * + * If the session becomes unavailable before the request can be created, the + * returned stream will emit `ERR_HTTP2_GOAWAY_SESSION` or + * `ERR_HTTP2_INVALID_SESSION` asynchronously. * * This method is only available if `http2session.type` is equal to `http2.constants.NGHTTP2_SESSION_CLIENT`. * @@ -1355,6 +1385,11 @@ declare module "http2" { * @default 128 */ maxHeaderListPairs?: number | undefined; + /** + * Sets the maximum number of uniq origin the sever + * can send via ORIGIN frames. **Default:** `128`. + */ + maxOriginSetSize?: number | undefined; /** * Sets the maximum number of outstanding, unacknowledged pings. * @default 10 @@ -1435,10 +1470,14 @@ declare module "http2" { maxSessionInvalidFrames?: number | undefined; streamResetBurst?: number | undefined; streamResetRate?: number | undefined; + /** @deprecated Use `http1Options.IncomingMessage` instead. */ Http1IncomingMessage?: Http1Request | undefined; + /** @deprecated Use `http1Options.ServerResponse` instead. */ Http1ServerResponse?: Http1Response | undefined; + http1Options?: Http1Options | undefined; Http2ServerRequest?: Http2Request | undefined; Http2ServerResponse?: Http2Response | undefined; + strictSingleValueFields?: boolean | undefined; } export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions {} export interface SecureServerSessionOptions< @@ -1462,6 +1501,14 @@ declare module "http2" { allowHTTP1?: boolean | undefined; origins?: string[] | undefined; } + interface Http1Options< + Request extends typeof IncomingMessage, + Response extends typeof ServerResponse>, + > { + IncomingMessage?: Request | undefined; + ServerResponse?: Response | undefined; + keepAliveTimeout?: number | undefined; + } interface HTTP2ServerCommon { setTimeout(msec?: number, callback?: () => void): this; /** @@ -1964,8 +2011,8 @@ declare module "http2" { * * Then `request.url` will be: * - * ```js - * '/status?name=ryan' + * ```json + * "/status?name=ryan" * ``` * * To parse the url into its parts, `new URL()` can be used: diff --git a/types/node/v24/inspector.d.ts b/types/node/v24/inspector.d.ts index dd0b888890c900..dfc26111e03631 100644 --- a/types/node/v24/inspector.d.ts +++ b/types/node/v24/inspector.d.ts @@ -48,7 +48,8 @@ declare module "inspector" { */ function open(port?: number, host?: string, wait?: boolean): Disposable; /** - * Deactivate the inspector. Blocks until there are no active connections. + * Deactivates the inspector. If there are active connections, they are forcibly + * terminated. Blocks until the inspector server has fully stopped. */ function close(): void; /** @@ -218,6 +219,51 @@ declare module "inspector" { */ function put(url: string, data: string): void; } + namespace DOMStorage { + /** + * This feature is only available with the + * `--experimental-storage-inspection` flag enabled. + * + * Broadcasts the `DOMStorage.domStorageItemAdded` event to connected frontends. + * This event indicates that a new item has been added to the storage. + * @since v24.16.0 + */ + function domStorageItemAdded(params: DomStorageItemAddedEventDataType): void; + /** + * This feature is only available with the + * `--experimental-storage-inspection` flag enabled. + * + * Broadcasts the `DOMStorage.domStorageItemRemoved` event to connected frontends. + * This event indicates that an item has been removed from the storage. + * @since v24.16.0 + */ + function domStorageItemRemoved(params: DomStorageItemRemovedEventDataType): void; + /** + * This feature is only available with the + * `--experimental-storage-inspection` flag enabled. + + * Broadcasts the `DOMStorage.domStorageItemUpdated` event to connected frontends. + * This event indicates that a storage item has been updated. + * @since v24.16.0 + */ + function domStorageItemUpdated(params: DomStorageItemUpdatedEventDataType): void; + /** + * This feature is only available with the + * `--experimental-storage-inspection` flag enabled. + * + * Broadcasts the `DOMStorage.domStorageItemsCleared` event to connected + * frontends. This event indicates that all items have been cleared from the + * storage. + * @since v24.16.0 + */ + function domStorageItemsCleared(params: DomStorageItemsClearedEventDataType): void; + /** + * This feature is only available with the + * `--experimental-storage-inspection` flag enabled. + * @since v24.16.0 + */ + function registerStorage(params: unknown): void; + } } /** diff --git a/types/node/v24/inspector.generated.d.ts b/types/node/v24/inspector.generated.d.ts index d7d3a55c6af1d1..c8951060b4c439 100644 --- a/types/node/v24/inspector.generated.d.ts +++ b/types/node/v24/inspector.generated.d.ts @@ -2035,6 +2035,9 @@ declare module "inspector" { autoAttach: boolean; waitForDebuggerOnStart: boolean; } + interface GetTargetsReturnType { + targetInfos: TargetInfo[]; + } interface TargetCreatedEventDataType { targetInfo: TargetInfo; } @@ -2044,6 +2047,75 @@ declare module "inspector" { waitingForDebugger: boolean; } } + namespace DOMStorage { + type SerializedStorageKey = string; + /** + * DOM Storage identifier. + */ + interface StorageId { + /** + * Security origin for the storage. + */ + securityOrigin?: string | undefined; + /** + * Represents a key by which DOM Storage keys its CachedStorageAreas + */ + storageKey?: SerializedStorageKey | undefined; + /** + * Whether the storage is local storage (not session storage). + */ + isLocalStorage: boolean; + } + /** + * DOM Storage item. + */ + type Item = string[]; + interface ClearParameterType { + storageId: StorageId; + } + interface GetDOMStorageItemsParameterType { + storageId: StorageId; + } + interface RemoveDOMStorageItemParameterType { + storageId: StorageId; + key: string; + } + interface SetDOMStorageItemParameterType { + storageId: StorageId; + key: string; + value: string; + } + interface GetDOMStorageItemsReturnType { + entries: Item[]; + } + interface DomStorageItemAddedEventDataType { + storageId: StorageId; + key: string; + newValue: string; + } + interface DomStorageItemRemovedEventDataType { + storageId: StorageId; + key: string; + } + interface DomStorageItemUpdatedEventDataType { + storageId: StorageId; + key: string; + oldValue: string; + newValue: string; + } + interface DomStorageItemsClearedEventDataType { + storageId: StorageId; + } + } + namespace Storage { + type SerializedStorageKey = string; + interface GetStorageKeyParameterType { + frameId?: string | undefined; + } + interface GetStorageKeyReturnType { + storageKey: SerializedStorageKey; + } + } interface Session { /** * Posts a message to the inspector back-end. `callback` will be notified when @@ -2437,8 +2509,34 @@ declare module "inspector" { */ post(method: "NodeWorker.detach", params?: NodeWorker.DetachParameterType, callback?: (err: Error | null) => void): void; post(method: "NodeWorker.detach", callback?: (err: Error | null) => void): void; + post(method: "Target.getTargets", callback?: (err: Error | null, params: Target.GetTargetsReturnType) => void): void; post(method: "Target.setAutoAttach", params?: Target.SetAutoAttachParameterType, callback?: (err: Error | null) => void): void; post(method: "Target.setAutoAttach", callback?: (err: Error | null) => void): void; + post(method: "DOMStorage.clear", params?: DOMStorage.ClearParameterType, callback?: (err: Error | null) => void): void; + post(method: "DOMStorage.clear", callback?: (err: Error | null) => void): void; + /** + * Disables storage tracking, prevents storage events from being sent to the client. + */ + post(method: "DOMStorage.disable", callback?: (err: Error | null) => void): void; + /** + * Enables storage tracking, storage events will now be delivered to the client. + */ + post(method: "DOMStorage.enable", callback?: (err: Error | null) => void): void; + post( + method: "DOMStorage.getDOMStorageItems", + params?: DOMStorage.GetDOMStorageItemsParameterType, + callback?: (err: Error | null, params: DOMStorage.GetDOMStorageItemsReturnType) => void + ): void; + post(method: "DOMStorage.getDOMStorageItems", callback?: (err: Error | null, params: DOMStorage.GetDOMStorageItemsReturnType) => void): void; + post(method: "DOMStorage.removeDOMStorageItem", params?: DOMStorage.RemoveDOMStorageItemParameterType, callback?: (err: Error | null) => void): void; + post(method: "DOMStorage.removeDOMStorageItem", callback?: (err: Error | null) => void): void; + post(method: "DOMStorage.setDOMStorageItem", params?: DOMStorage.SetDOMStorageItemParameterType, callback?: (err: Error | null) => void): void; + post(method: "DOMStorage.setDOMStorageItem", callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: "Storage.getStorageKey", params?: Storage.GetStorageKeyParameterType, callback?: (err: Error | null, params: Storage.GetStorageKeyReturnType) => void): void; + post(method: "Storage.getStorageKey", callback?: (err: Error | null, params: Storage.GetStorageKeyReturnType) => void): void; addListener(event: string, listener: (...args: any[]) => void): this; /** * Emitted when any notification from the V8 Inspector is received. @@ -2574,6 +2672,10 @@ declare module "inspector" { addListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; addListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; addListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + addListener(event: "DOMStorage.domStorageItemAdded", listener: (message: InspectorNotification) => void): this; + addListener(event: "DOMStorage.domStorageItemRemoved", listener: (message: InspectorNotification) => void): this; + addListener(event: "DOMStorage.domStorageItemUpdated", listener: (message: InspectorNotification) => void): this; + addListener(event: "DOMStorage.domStorageItemsCleared", listener: (message: InspectorNotification) => void): this; emit(event: string | symbol, ...args: any[]): boolean; emit(event: "inspectorNotification", message: InspectorNotification): boolean; emit(event: "Runtime.executionContextCreated", message: InspectorNotification): boolean; @@ -2613,6 +2715,10 @@ declare module "inspector" { emit(event: "NodeWorker.receivedMessageFromWorker", message: InspectorNotification): boolean; emit(event: "Target.targetCreated", message: InspectorNotification): boolean; emit(event: "Target.attachedToTarget", message: InspectorNotification): boolean; + emit(event: "DOMStorage.domStorageItemAdded", message: InspectorNotification): boolean; + emit(event: "DOMStorage.domStorageItemRemoved", message: InspectorNotification): boolean; + emit(event: "DOMStorage.domStorageItemUpdated", message: InspectorNotification): boolean; + emit(event: "DOMStorage.domStorageItemsCleared", message: InspectorNotification): boolean; on(event: string, listener: (...args: any[]) => void): this; /** * Emitted when any notification from the V8 Inspector is received. @@ -2748,6 +2854,10 @@ declare module "inspector" { on(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; on(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; on(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + on(event: "DOMStorage.domStorageItemAdded", listener: (message: InspectorNotification) => void): this; + on(event: "DOMStorage.domStorageItemRemoved", listener: (message: InspectorNotification) => void): this; + on(event: "DOMStorage.domStorageItemUpdated", listener: (message: InspectorNotification) => void): this; + on(event: "DOMStorage.domStorageItemsCleared", listener: (message: InspectorNotification) => void): this; once(event: string, listener: (...args: any[]) => void): this; /** * Emitted when any notification from the V8 Inspector is received. @@ -2883,6 +2993,10 @@ declare module "inspector" { once(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; once(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; once(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + once(event: "DOMStorage.domStorageItemAdded", listener: (message: InspectorNotification) => void): this; + once(event: "DOMStorage.domStorageItemRemoved", listener: (message: InspectorNotification) => void): this; + once(event: "DOMStorage.domStorageItemUpdated", listener: (message: InspectorNotification) => void): this; + once(event: "DOMStorage.domStorageItemsCleared", listener: (message: InspectorNotification) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; /** * Emitted when any notification from the V8 Inspector is received. @@ -3018,6 +3132,10 @@ declare module "inspector" { prependListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; prependListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; prependListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + prependListener(event: "DOMStorage.domStorageItemAdded", listener: (message: InspectorNotification) => void): this; + prependListener(event: "DOMStorage.domStorageItemRemoved", listener: (message: InspectorNotification) => void): this; + prependListener(event: "DOMStorage.domStorageItemUpdated", listener: (message: InspectorNotification) => void): this; + prependListener(event: "DOMStorage.domStorageItemsCleared", listener: (message: InspectorNotification) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; /** * Emitted when any notification from the V8 Inspector is received. @@ -3153,6 +3271,10 @@ declare module "inspector" { prependOnceListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; prependOnceListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; prependOnceListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "DOMStorage.domStorageItemAdded", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "DOMStorage.domStorageItemRemoved", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "DOMStorage.domStorageItemUpdated", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "DOMStorage.domStorageItemsCleared", listener: (message: InspectorNotification) => void): this; } } declare module "inspector/promises" { @@ -3169,6 +3291,8 @@ declare module "inspector/promises" { NodeTracing, NodeWorker, Target, + DOMStorage, + Storage, } from 'inspector'; } declare module "inspector/promises" { @@ -3186,6 +3310,8 @@ declare module "inspector/promises" { NodeTracing, NodeWorker, Target, + DOMStorage, + Storage, } from "inspector"; /** * The `inspector.Session` is used for dispatching messages to the V8 inspector @@ -3520,7 +3646,24 @@ declare module "inspector/promises" { * Detached from the worker with given sessionId. */ post(method: "NodeWorker.detach", params?: NodeWorker.DetachParameterType): Promise; + post(method: "Target.getTargets"): Promise; post(method: "Target.setAutoAttach", params?: Target.SetAutoAttachParameterType): Promise; + post(method: "DOMStorage.clear", params?: DOMStorage.ClearParameterType): Promise; + /** + * Disables storage tracking, prevents storage events from being sent to the client. + */ + post(method: "DOMStorage.disable"): Promise; + /** + * Enables storage tracking, storage events will now be delivered to the client. + */ + post(method: "DOMStorage.enable"): Promise; + post(method: "DOMStorage.getDOMStorageItems", params?: DOMStorage.GetDOMStorageItemsParameterType): Promise; + post(method: "DOMStorage.removeDOMStorageItem", params?: DOMStorage.RemoveDOMStorageItemParameterType): Promise; + post(method: "DOMStorage.setDOMStorageItem", params?: DOMStorage.SetDOMStorageItemParameterType): Promise; + /** + * @experimental + */ + post(method: "Storage.getStorageKey", params?: Storage.GetStorageKeyParameterType): Promise; addListener(event: string, listener: (...args: any[]) => void): this; /** * Emitted when any notification from the V8 Inspector is received. @@ -3656,6 +3799,10 @@ declare module "inspector/promises" { addListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; addListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; addListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + addListener(event: "DOMStorage.domStorageItemAdded", listener: (message: InspectorNotification) => void): this; + addListener(event: "DOMStorage.domStorageItemRemoved", listener: (message: InspectorNotification) => void): this; + addListener(event: "DOMStorage.domStorageItemUpdated", listener: (message: InspectorNotification) => void): this; + addListener(event: "DOMStorage.domStorageItemsCleared", listener: (message: InspectorNotification) => void): this; emit(event: string | symbol, ...args: any[]): boolean; emit(event: "inspectorNotification", message: InspectorNotification): boolean; emit(event: "Runtime.executionContextCreated", message: InspectorNotification): boolean; @@ -3695,6 +3842,10 @@ declare module "inspector/promises" { emit(event: "NodeWorker.receivedMessageFromWorker", message: InspectorNotification): boolean; emit(event: "Target.targetCreated", message: InspectorNotification): boolean; emit(event: "Target.attachedToTarget", message: InspectorNotification): boolean; + emit(event: "DOMStorage.domStorageItemAdded", message: InspectorNotification): boolean; + emit(event: "DOMStorage.domStorageItemRemoved", message: InspectorNotification): boolean; + emit(event: "DOMStorage.domStorageItemUpdated", message: InspectorNotification): boolean; + emit(event: "DOMStorage.domStorageItemsCleared", message: InspectorNotification): boolean; on(event: string, listener: (...args: any[]) => void): this; /** * Emitted when any notification from the V8 Inspector is received. @@ -3830,6 +3981,10 @@ declare module "inspector/promises" { on(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; on(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; on(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + on(event: "DOMStorage.domStorageItemAdded", listener: (message: InspectorNotification) => void): this; + on(event: "DOMStorage.domStorageItemRemoved", listener: (message: InspectorNotification) => void): this; + on(event: "DOMStorage.domStorageItemUpdated", listener: (message: InspectorNotification) => void): this; + on(event: "DOMStorage.domStorageItemsCleared", listener: (message: InspectorNotification) => void): this; once(event: string, listener: (...args: any[]) => void): this; /** * Emitted when any notification from the V8 Inspector is received. @@ -3965,6 +4120,10 @@ declare module "inspector/promises" { once(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; once(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; once(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + once(event: "DOMStorage.domStorageItemAdded", listener: (message: InspectorNotification) => void): this; + once(event: "DOMStorage.domStorageItemRemoved", listener: (message: InspectorNotification) => void): this; + once(event: "DOMStorage.domStorageItemUpdated", listener: (message: InspectorNotification) => void): this; + once(event: "DOMStorage.domStorageItemsCleared", listener: (message: InspectorNotification) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; /** * Emitted when any notification from the V8 Inspector is received. @@ -4100,6 +4259,10 @@ declare module "inspector/promises" { prependListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; prependListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; prependListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + prependListener(event: "DOMStorage.domStorageItemAdded", listener: (message: InspectorNotification) => void): this; + prependListener(event: "DOMStorage.domStorageItemRemoved", listener: (message: InspectorNotification) => void): this; + prependListener(event: "DOMStorage.domStorageItemUpdated", listener: (message: InspectorNotification) => void): this; + prependListener(event: "DOMStorage.domStorageItemsCleared", listener: (message: InspectorNotification) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; /** * Emitted when any notification from the V8 Inspector is received. @@ -4235,5 +4398,9 @@ declare module "inspector/promises" { prependOnceListener(event: "NodeWorker.receivedMessageFromWorker", listener: (message: InspectorNotification) => void): this; prependOnceListener(event: "Target.targetCreated", listener: (message: InspectorNotification) => void): this; prependOnceListener(event: "Target.attachedToTarget", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "DOMStorage.domStorageItemAdded", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "DOMStorage.domStorageItemRemoved", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "DOMStorage.domStorageItemUpdated", listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: "DOMStorage.domStorageItemsCleared", listener: (message: InspectorNotification) => void): this; } } diff --git a/types/node/v24/module.d.ts b/types/node/v24/module.d.ts index 889e2ddb60b796..6cca257d20e913 100644 --- a/types/node/v24/module.d.ts +++ b/types/node/v24/module.d.ts @@ -219,6 +219,7 @@ declare module "module" { * This feature requires `--allow-worker` if used with the * [Permission Model](https://nodejs.org/docs/latest-v24.x/api/permissions.html#permission-model). * @since v20.6.0, v18.19.0 + * @deprecated Use `module.registerHooks()` instead. * @param specifier Customization hooks to be registered; this should be * the same string that would be passed to `import()`, except that if it is * relative, it is resolved relative to `parentURL`. diff --git a/types/node/v24/net.d.ts b/types/node/v24/net.d.ts index f03f9802b71f4d..d2ad14a4924837 100644 --- a/types/node/v24/net.d.ts +++ b/types/node/v24/net.d.ts @@ -38,6 +38,8 @@ declare module "net" { keepAlive?: boolean | undefined; keepAliveInitialDelay?: number | undefined; blockList?: BlockList | undefined; + typeOfService?: number | undefined; + handle?: BoundSocket | undefined; } interface OnReadOpts { buffer: Uint8Array | (() => Uint8Array); @@ -70,6 +72,12 @@ declare module "net" { } type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts; type SocketReadyState = "opening" | "open" | "readOnly" | "writeOnly" | "closed"; + interface SetKeepAliveOptions { + enable?: boolean | undefined; + initialDelay?: number | undefined; + interval?: number | undefined; + count?: number | undefined; + } /** * This class is an abstraction of a TCP socket or a streaming `IPC` endpoint * (uses named pipes on Windows, and Unix domain sockets otherwise). It is also @@ -201,25 +209,58 @@ declare module "net" { */ setNoDelay(noDelay?: boolean): this; /** - * Enable/disable keep-alive functionality, and optionally set the initial - * delay before the first keepalive probe is sent on an idle socket. + * Configure keep-alive using an options object. See `socket.setKeepAlive()` + * for a description of each property. * - * Set `initialDelay` (in milliseconds) to set the delay between the last - * data packet received and the first keepalive probe. Setting `0` for`initialDelay` will leave the value unchanged from the default - * (or previous) setting. + * ```js + * socket.setKeepAlive({ enable: true, initialDelay: 1000, interval: 1000, count: 10 }); + * ``` + * @since v24.19.0 + * @returns The socket itself. + */ + setKeepAlive(options: SetKeepAliveOptions): this; + /** + * Configure keep-alive using positional arguments. See + * `socket.setKeepAlive()` for a description of each argument. + * @since v0.1.92 + * @param enable **Default:** `false` + * @param initialDelay **Default:** `0` + * @param interval **Default:** `1000` + * @param count **Default:** `10` + * @returns The socket itself. + */ + setKeepAlive(enable?: boolean, initialDelay?: number, interval?: number, count?: number): this; + /** + * Returns the current Type of Service (TOS) field for IPv4 packets or Traffic + * Class for IPv6 packets for this socket. * - * Enabling the keep-alive functionality will set the following socket options: + * `setTypeOfService()` may be called before the socket is connected; the value + * will be cached and applied when the socket establishes a connection. + * `getTypeOfService()` will return the currently set value even before connection. * - * * `SO_KEEPALIVE=1` - * * `TCP_KEEPIDLE=initialDelay` - * * `TCP_KEEPCNT=10` - * * `TCP_KEEPINTVL=1` - * @since v0.1.92 - * @param [enable=false] - * @param [initialDelay=0] - * @return The socket itself. + * On some platforms (e.g., Linux), certain TOS/ECN bits may be masked or ignored, + * and behavior can differ between IPv4 and IPv6 or dual-stack sockets. Callers + * should verify platform-specific semantics. + * @since v24.15.0 + * @returns The current TOS value. + */ + getTypeOfService(): number; + /** + * Sets the Type of Service (TOS) field for IPv4 packets or Traffic Class for IPv6 + * Packets sent from this socket. This can be used to prioritize network traffic. + * + * `setTypeOfService()` may be called before the socket is connected; the value + * will be cached and applied when the socket establishes a connection. + * `getTypeOfService()` will return the currently set value even before connection. + * + * On some platforms (e.g., Linux), certain TOS/ECN bits may be masked or ignored, + * and behavior can differ between IPv4 and IPv6 or dual-stack sockets. Callers + * should verify platform-specific semantics. + * @since v24.15.0 + * @param tos The TOS value to set (0-255). + * @returns The socket itself. */ - setKeepAlive(enable?: boolean, initialDelay?: number): this; + setTypeOfService(tos: number): this; /** * Returns the bound `address`, the address `family` name and `port` of the * socket as reported by the operating system:`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` @@ -509,9 +550,92 @@ declare module "net" { prependOnceListener(event: "ready", listener: () => void): this; prependOnceListener(event: "timeout", listener: () => void): this; } + interface BoundSocketOptions { + /** + * Local address to bind. Must be a numeric IP literal; no DNS + * resolution is performed. **Default:** `'0.0.0.0'`, or `'::'` when + * `ipv6Only` is `true`. + */ + host?: string | undefined; + /** + * Local port. `0` requests an OS-assigned ephemeral port. + * **Default:** `0`. + */ + port?: number | undefined; + /** + * Sets `IPV6_V6ONLY`, disabling dual-stack support so the + * socket binds IPv6 only. Only meaningful for IPv6 binds. **Default:** + * `false`. + */ + ipv6Only?: boolean | undefined; + /** + * Sets `SO_REUSEPORT`, allowing multiple sockets to bind + * the same address and port for kernel-level load balancing. Support is + * platform-dependent. **Default:** `false`. + */ + reusePort?: boolean | undefined; + } + /** + * Allows for the synchronous creation of a pre-bound socket, that can be passed + * to `listen()` or `new net.Socket()` later on. For `listen()` this enables + * synchronous port reservation, while for `new net.Socket()`, it allows control + * over the local egress port/IP, via `bind(2)` semantics. + * + * Adoption transfers ownership of the socket; afterwards `address()` and `close()` + * throw `ERR_SOCKET_HANDLE_ADOPTED`. A handle that is never adopted must be + * closed to avoid leaking the socket. + * + * ```js + * import net from 'node:net'; + * + * const bound = new net.BoundSocket(); + * const { port } = bound.address(); + * console.log(`Reserved port ${port} for server`); + * + * const server = net.createServer(); + * server.listen(bound); // Adopt as a server, or pass to new net.Socket() instead. + * ``` + * @since v24.19.0 + */ + class BoundSocket { + /** + * @since v26.4.0 + */ + constructor(options?: BoundSocketOptions); + /** + * Returns the bound local address. When bound with `port: 0`, `port` is the + * OS-assigned ephemeral port. + * @since v24.19.0 + * @returns An object with `address`, `family`, and `port` properties, + * as `server.address()` returns. + */ + address(): AddressInfo; + /** + * Returns the file descriptor of the bound socket. Ownership remains with the + * `BoundSocket`, so the descriptor must not be closed by the caller. The + * descriptor is only available before the handle is adopted; afterwards it belongs + * to the adopting `net.Server` or `net.Socket` and `fd()` throws + * `ERR_SOCKET_HANDLE_ADOPTED`. + * @since v24.19.0 + * @returns The underlying OS file descriptor, or `-1` on platforms + * that do not expose one for sockets (such as Windows). + */ + fd(): number; + /** + * Releases the bound socket. Only needed when the handle is never adopted. + * @since v24.19.0 + */ + close(): void; + /** + * Closes the handle if it has not been adopted or closed; otherwise a no-op. + * @since v24.19.0 + */ + [Symbol.dispose](): void; + } interface ListenOptions extends Abortable { backlog?: number | undefined; exclusive?: boolean | undefined; + handle?: BoundSocket | undefined; host?: string | undefined; /** * @default false diff --git a/types/node/v24/os.d.ts b/types/node/v24/os.d.ts index 505f5b44d6495f..9534d01c883382 100644 --- a/types/node/v24/os.d.ts +++ b/types/node/v24/os.d.ts @@ -131,7 +131,7 @@ declare module "os" { * irq: 20, * }, * }, - * ] + * ]; * ``` * * `nice` values are POSIX-only. On Windows, the `nice` values of all processors @@ -176,44 +176,44 @@ declare module "os" { * * The properties available on the assigned network address object include: * - * ```js + * ```json * { - * lo: [ + * "lo": [ * { - * address: '127.0.0.1', - * netmask: '255.0.0.0', - * family: 'IPv4', - * mac: '00:00:00:00:00:00', - * internal: true, - * cidr: '127.0.0.1/8' + * "address:": "127.0.0.1", + * "netmask:": "255.0.0.0", + * "family:": "IPv4", + * "mac:": "00:00:00:00:00:00", + * "internal:": true, + * "cidr:": "127.0.0.1/8" * }, * { - * address: '::1', - * netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', - * family: 'IPv6', - * mac: '00:00:00:00:00:00', - * scopeid: 0, - * internal: true, - * cidr: '::1/128' + * "address:": "::1", + * "netmask:": "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff", + * "family:": "IPv6", + * "mac:": "00:00:00:00:00:00", + * "scopeid:": 0, + * "internal:": true, + * "cidr:": "::1/128" * } * ], - * eth0: [ + * "eth0": [ * { - * address: '192.168.1.108', - * netmask: '255.255.255.0', - * family: 'IPv4', - * mac: '01:02:03:0a:0b:0c', - * internal: false, - * cidr: '192.168.1.108/24' + * "address:": "192.168.1.108", + * "netmask:": "255.255.255.0", + * "family:": "IPv4", + * "mac:": "01:02:03:0a:0b:0c", + * "internal:": false, + * "cidr:": "192.168.1.108/24" * }, * { - * address: 'fe80::a00:27ff:fe4e:66a1', - * netmask: 'ffff:ffff:ffff:ffff::', - * family: 'IPv6', - * mac: '01:02:03:0a:0b:0c', - * scopeid: 1, - * internal: false, - * cidr: 'fe80::a00:27ff:fe4e:66a1/64' + * "address:": "fe80::a00:27ff:fe4e:66a1", + * "netmask:": "ffff:ffff:ffff:ffff::", + * "family:": "IPv6", + * "mac:": "01:02:03:0a:0b:0c", + * "scopeid:": 1, + * "internal:": false, + * "cidr:": "fe80::a00:27ff:fe4e:66a1/64" * } * ] * } diff --git a/types/node/v24/package.json b/types/node/v24/package.json index f2a19aa487f838..bdfa5208e7d268 100644 --- a/types/node/v24/package.json +++ b/types/node/v24/package.json @@ -1,7 +1,7 @@ { "private": true, "name": "@types/node", - "version": "24.13.9999", + "version": "24.19.9999", "nonNpm": "conflict", "nonNpmDescription": "Node.js", "projects": [ @@ -18,7 +18,7 @@ } }, "dependencies": { - "undici-types": "~7.18.0" + "undici-types": ">=7.24.0 <7.24.7" }, "devDependencies": { "@types/node": "workspace:." diff --git a/types/node/v24/perf_hooks.d.ts b/types/node/v24/perf_hooks.d.ts index 7393c5245fe765..ca30dff6be880d 100644 --- a/types/node/v24/perf_hooks.d.ts +++ b/types/node/v24/perf_hooks.d.ts @@ -670,6 +670,7 @@ declare module "perf_hooks" { namespace constants { const NODE_PERFORMANCE_GC_MAJOR: number; const NODE_PERFORMANCE_GC_MINOR: number; + const NODE_PERFORMANCE_GC_MINOR_MARK_SWEEP: number; const NODE_PERFORMANCE_GC_INCREMENTAL: number; const NODE_PERFORMANCE_GC_WEAKCB: number; const NODE_PERFORMANCE_GC_FLAGS_NO: number; @@ -683,9 +684,14 @@ declare module "perf_hooks" { const performance: Performance; interface EventLoopMonitorOptions { /** - * The sampling rate in milliseconds. - * Must be greater than zero. - * @default 10 + * When `true`, samples are taken once per + * event loop iteration. **Default:** `false`. + */ + samplePerIteration?: boolean | undefined; + /** + * The sampling rate in milliseconds for interval-based + * sampling. Must be greater than zero. This option is ignored when + * `samplePerIteration` is `true`. **Default:** `10`. */ resolution?: number | undefined; } @@ -769,21 +775,25 @@ declare module "perf_hooks" { */ readonly stddev: number; } - interface IntervalHistogram extends Histogram { + /** + * A `Histogram` that records event loop delay, returned by + * `perf_hooks.monitorEventLoopDelay()`. + */ + interface ELDHistogram extends Histogram { /** - * Enables the update interval timer. Returns `true` if the timer was - * started, `false` if it was already started. + * Disables event loop delay sampling. Returns `true` if sampling was + * stopped, `false` if it was already stopped. * @since v11.10.0 */ - enable(): boolean; + disable(): boolean; /** - * Disables the update interval timer. Returns `true` if the timer was - * stopped, `false` if it was already stopped. + * Enables event loop delay sampling. Returns `true` if sampling was + * started, `false` if it was already started. * @since v11.10.0 */ - disable(): boolean; + enable(): boolean; /** - * Disables the update interval timer when the histogram is disposed. + * Disables event loop delay sampling when the histogram is disposed. * * ```js * const { monitorEventLoopDelay } = require('node:perf_hooks'); @@ -895,14 +905,16 @@ declare module "perf_hooks" { /** * _This property is an extension by Node.js. It is not available in Web browsers._ * - * Creates an `IntervalHistogram` object that samples and reports the event loop - * delay over time. The delays will be reported in nanoseconds. + * Creates a histogram object that samples and reports the event loop delay over + * time. The delays will be reported in nanoseconds. * - * Using a timer to detect approximate event loop delay works because the - * execution of timers is tied specifically to the lifecycle of the libuv - * event loop. That is, a delay in the loop will cause a delay in the execution - * of the timer, and those delays are specifically what this API is intended to - * detect. + * By default, the histogram is updated by a timer using the configured + * `resolution`. When `samplePerIteration` is `true`, samples are taken once per + * event loop iteration using `uv_prepare_t` and `uv_check_t` hooks. In that mode, + * the histogram does not keep the loop alive or force additional iterations when + * the application is idle. + * The two sampling modes produce significantly different results and should not + * be compared directly. * * ```js * import { monitorEventLoopDelay } from 'node:perf_hooks'; @@ -920,7 +932,7 @@ declare module "perf_hooks" { * ``` * @since v11.10.0 */ - function monitorEventLoopDelay(options?: EventLoopMonitorOptions): IntervalHistogram; + function monitorEventLoopDelay(options?: EventLoopMonitorOptions): ELDHistogram; /** * _This property is an extension by Node.js. It is not available in Web browsers._ * diff --git a/types/node/v24/process.d.ts b/types/node/v24/process.d.ts index 7b69dd5459c634..0ac4405c9ccdd7 100644 --- a/types/node/v24/process.d.ts +++ b/types/node/v24/process.d.ts @@ -668,14 +668,14 @@ declare module "process" { * * Results in `process.execArgv`: * - * ```js + * ```json * ["--icu-data-dir=./foo", "--require", "./bar.js"] * ``` * * And `process.argv`: * - * ```js - * ['/usr/local/bin/node', 'script.js', '--version'] + * ```json + * ["/usr/local/bin/node", "script.js", "--version"] * ``` * * Refer to `Worker constructor` for the detailed behavior of worker @@ -687,8 +687,8 @@ declare module "process" { * The `process.execPath` property returns the absolute pathname of the executable * that started the Node.js process. Symbolic links, if any, are resolved. * - * ```js - * '/usr/local/bin/node' + * ```json + * "/usr/local/bin/node" * ``` * @since v0.1.100 */ @@ -849,18 +849,18 @@ declare module "process" { * * An example of this object looks like: * - * ```js + * ```json * { - * TERM: 'xterm-256color', - * SHELL: '/usr/local/bin/bash', - * USER: 'maciej', - * PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', - * PWD: '/Users/maciej', - * EDITOR: 'vim', - * SHLVL: '1', - * HOME: '/Users/maciej', - * LOGNAME: 'maciej', - * _: '/usr/local/bin/node' + * "TERM": "xterm-256color", + * "SHELL": "/usr/local/bin/bash", + * "USER": "maciej", + * "PATH": "~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin", + * "PWD": "/Users/maciej", + * "EDITOR": "vim", + * "SHLVL": "1", + * "HOME": "/Users/maciej", + * "LOGNAME": "maciej", + * "_": "/usr/local/bin/node" * } * ``` * @@ -1389,29 +1389,28 @@ declare module "process" { * * An example of the possible output looks like: * - * ```js + * ```json * { - * target_defaults: - * { cflags: [], - * default_configuration: 'Release', - * defines: [], - * include_dirs: [], - * libraries: [] }, - * variables: + * "target_defaults": + * { "cflags": [], + * "default_configuration": "Release", + * "defines": [], + * "include_dirs": [], + * "libraries": [] }, + * "variables": * { - * host_arch: 'x64', - * napi_build_version: 5, - * node_install_npm: 'true', - * node_prefix: '', - * node_shared_cares: 'false', - * node_shared_http_parser: 'false', - * node_shared_libuv: 'false', - * node_shared_zlib: 'false', - * node_use_openssl: 'true', - * node_shared_openssl: 'false', - * strict_aliasing: 'true', - * target_arch: 'x64', - * v8_use_snapshot: 1 + * "host_arch": "x64", + * "napi_build_version": 5, + * "node_install_npm": "true", + * "node_prefix": "", + * "node_shared_cares": "false", + * "node_shared_http_parser": "false", + * "node_shared_libuv": "false", + * "node_shared_zlib": "false", + * "node_use_openssl": "true", + * "node_shared_openssl": "false", + * "target_arch": "x64", + * "v8_use_snapshot": 1 * } * } * ``` @@ -1725,13 +1724,13 @@ declare module "process" { * * `process.release` contains the following properties: * - * ```js + * ```json * { - * name: 'node', - * lts: 'Hydrogen', - * sourceUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0.tar.gz', - * headersUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0-headers.tar.gz', - * libUrl: 'https://nodejs.org/download/release/v18.12.0/win-x64/node.lib' + * "name": "node", + * "lts": "Hydrogen", + * "sourceUrl": "https://nodejs.org/download/release/v18.12.0/node-v18.12.0.tar.gz", + * "headersUrl": "https://nodejs.org/download/release/v18.12.0/node-v18.12.0-headers.tar.gz", + * "libUrl": "https://nodejs.org/download/release/v18.12.0/win-x64/node.lib" * } * ``` * diff --git a/types/node/v24/sqlite.d.ts b/types/node/v24/sqlite.d.ts index 43112d4164aca1..1a872e05d5d589 100644 --- a/types/node/v24/sqlite.d.ts +++ b/types/node/v24/sqlite.d.ts @@ -126,6 +126,29 @@ declare module "node:sqlite" { * @default true */ defensive?: boolean | undefined; + /** + * Configuration for various SQLite limits. These limits + * can be used to prevent excessive resource consumption when handling + * potentially malicious input. See [Run-Time Limits](https://www.sqlite.org/c3ref/c_limit_attached.html) and [Limit Constants](https://www.sqlite.org/c3ref/limit.html) + * in the SQLite documentation for details. Default values are determined by + * SQLite's compile-time defaults and may vary depending on how SQLite was + * built. The following properties are supported: + * @since v24.15.0 + */ + limits?: NodeJS.PartialOptions | undefined; + } + interface DatabaseLimits { + length: number; + sqlLength: number; + column: number; + exprDepth: number; + compoundSelect: number; + vdbeOp: number; + functionArg: number; + attach: number; + likePatternLength: number; + variableNumber: number; + triggerDepth: number; } interface CreateSessionOptions { /** @@ -143,8 +166,12 @@ declare module "node:sqlite" { } interface ApplyChangesetOptions { /** - * Skip changes that, when targeted table name is supplied to this function, return a truthy value. - * By default, all changes are attempted. + * for each table affected by at least + * one change in the changeset, the `filter` callback is invoked with the + * table name as the first argument. If the return value is falsy, then no + * attempt is made to apply any changes to the table. + * Otherwise, if the return value is truthy or no `filter` callback is provided, + * all changes related to the table are attempted. * @since v22.12.0 */ filter?: ((tableName: string) => boolean) | undefined; @@ -174,6 +201,13 @@ declare module "node:sqlite" { */ onConflict?: ((conflictType: number) => number) | undefined; } + interface DeserializeOptions { + /** + * Name of the database to deserialize into. + * @default 'main' + */ + dbName?: string | undefined; + } interface FunctionOptions { /** * If `true`, the [`SQLITE_DETERMINISTIC`](https://www.sqlite.org/c3ref/c_deterministic.html) flag is @@ -228,6 +262,28 @@ declare module "node:sqlite" { */ inverse?: ((accumulator: T, ...args: SQLOutputValue[]) => T) | undefined; } + interface PrepareOptions { + /** + * If `true`, integer fields are read as `BigInt`s. + * @since v24.14.0 + */ + readBigInts?: boolean | undefined; + /** + * If `true`, results are returned as arrays. + * @since v24.14.0 + */ + returnArrays?: boolean | undefined; + /** + * If `true`, allows binding named parameters without the prefix character. + * @since v24.14.0 + */ + allowBareNamedParameters?: boolean | undefined; + /** + * If `true`, unknown named parameters are ignored. + * @since v24.14.0 + */ + allowUnknownNamedParameters?: boolean | undefined; + } /** * This class represents a single [connection](https://www.sqlite.org/c3ref/sqlite3.html) to a SQLite database. All APIs * exposed by this class execute synchronously. @@ -285,10 +341,23 @@ declare module "node:sqlite" { * Loads a shared library into the database connection. This method is a wrapper * around [`sqlite3_load_extension()`](https://www.sqlite.org/c3ref/load_extension.html). It is required to enable the * `allowExtension` option when constructing the `DatabaseSync` instance. + * + * ```js + * import { DatabaseSync } from 'node:sqlite'; + * const database = new DatabaseSync(':memory:', { allowExtension: true }); + * + * // Load using the entry point derived from the filename. + * database.loadExtension('./decimal.dylib'); + * + * // Override the entry point when the derived name does not match. + * database.loadExtension('./base64.dylib', 'sqlite3_base64_init'); * @since v22.13.0 * @param path The path to the shared library to load. + * @param entryPoint The name of the extension's entry-point function. When + * omitted, SQLite derives the entry point from the shared library's filename; + * pass this argument explicitly when the derived name does not match. */ - loadExtension(path: string): void; + loadExtension(path: string, entryPoint?: string): void; /** * Enables or disables the `loadExtension` SQL function, and the `loadExtension()` * method. When `allowExtension` is `false` when constructing, you cannot enable @@ -330,18 +399,17 @@ declare module "node:sqlite" { * @since v22.13.0 * @param name The name of the SQLite function to create. * @param options Optional configuration settings for the function. - * @param func The JavaScript function to call when the SQLite - * function is invoked. The return value of this function should be a valid - * SQLite data type: see - * [Type conversion between JavaScript and SQLite](https://nodejs.org/docs/latest-v24.x/api/sqlite.html#type-conversion-between-javascript-and-sqlite). - * The result defaults to `NULL` if the return value is `undefined`. + * @param fn The JavaScript function to call when the SQLite function is + * invoked. The return value of this function should be a valid SQLite data type: + * see [Type conversion between JavaScript and SQLite](https://nodejs.org/docs/latest-v24.x/api/sqlite.html#type-conversion-between-javascript-and-sqlite). The result defaults to + * `NULL` if the return value is `undefined`. */ function( name: string, options: FunctionOptions, - func: (...args: SQLOutputValue[]) => SQLInputValue, + fn: (...args: SQLOutputValue[]) => SQLInputValue, ): void; - function(name: string, func: (...args: SQLOutputValue[]) => SQLInputValue): void; + function(name: string, fn: (...args: SQLOutputValue[]) => SQLInputValue): void; /** * Sets an authorizer callback that SQLite will invoke whenever it attempts to * access data or modify the database schema through prepared statements. @@ -411,20 +479,94 @@ declare module "node:sqlite" { * @since v24.0.0 */ readonly isTransaction: boolean; + /** + * An object for getting and setting SQLite database limits at runtime. + * Each property corresponds to an SQLite limit and can be read or written. + * + * ```js + * const db = new DatabaseSync(':memory:'); + * + * // Read current limit + * console.log(db.limits.length); + * + * // Set a new limit + * db.limits.sqlLength = 100000; + * + * // Reset a limit to its compile-time maximum + * db.limits.sqlLength = Infinity; + * ``` + * + * Available properties: `length`, `sqlLength`, `column`, `exprDepth`, + * `compoundSelect`, `vdbeOp`, `functionArg`, `attach`, `likePatternLength`, + * `variableNumber`, `triggerDepth`. + * + * Setting a property to `Infinity` resets the limit to its compile-time maximum value. + * @since v24.15.0 + */ + readonly limits: DatabaseLimits; /** * Opens the database specified in the `path` argument of the `DatabaseSync`constructor. This method should only be used when the database is not opened via * the constructor. An exception is thrown if the database is already open. * @since v22.5.0 */ open(): void; + /** + * Serializes the database into a binary representation, returned as a + * `Uint8Array`. This is useful for saving, cloning, or transferring an in-memory + * database. This method is a wrapper around [`sqlite3_serialize()`](https://sqlite.org/c3ref/serialize.html). + * + * ```js + * import { DatabaseSync } from 'node:sqlite'; + * + * const db = new DatabaseSync(':memory:'); + * db.exec('CREATE TABLE t(key INTEGER PRIMARY KEY, value TEXT)'); + * db.exec("INSERT INTO t VALUES (1, 'hello')"); + * const buffer = db.serialize(); + * console.log(buffer.length); // Prints the byte length of the database + * ``` + * @since v24.16.0 + * @param dbName Name of the database to serialize. This can be `'main'` + * (the default primary database) or any other database that has been added with + * [`ATTACH DATABASE`](https://www.sqlite.org/lang_attach.html). **Default:** `'main'`. + * @returns A binary representation of the database. + */ + serialize(dbName?: string): NodeJS.NonSharedUint8Array; + /** + * Loads a serialized database into this connection, replacing the current + * database. The deserialized database is writable. Existing prepared statements + * are finalized before deserialization is attempted, even if the operation + * subsequently fails. This method is a wrapper around + * [`sqlite3_deserialize()`](https://sqlite.org/c3ref/deserialize.html). + * + * ```js + * import { DatabaseSync } from 'node:sqlite'; + * + * const original = new DatabaseSync(':memory:'); + * original.exec('CREATE TABLE t(key INTEGER PRIMARY KEY, value TEXT)'); + * original.exec("INSERT INTO t VALUES (1, 'hello')"); + * const buffer = original.serialize(); + * original.close(); + * + * const clone = new DatabaseSync(':memory:'); + * clone.deserialize(buffer); + * console.log(clone.prepare('SELECT value FROM t').get()); + * // Prints: { value: 'hello' } + * ``` + * @since v24.16.0 + * @param buffer A binary representation of a database, such as the + * output of `database.serialize()`. + * @param options Optional configuration for the deserialization. + */ + deserialize(buffer: Uint8Array, options?: DeserializeOptions): void; /** * Compiles a SQL statement into a [prepared statement](https://www.sqlite.org/c3ref/stmt.html). This method is a wrapper * around [`sqlite3_prepare_v2()`](https://www.sqlite.org/c3ref/prepare.html). * @since v22.5.0 * @param sql A SQL string to compile to a prepared statement. + * @param options Optional configuration for the prepared statement. * @return The prepared statement. */ - prepare(sql: string): StatementSync; + prepare(sql: string, options?: PrepareOptions): StatementSync; /** * Creates a new {@link SQLTagStore}, which is a Least Recently Used (LRU) cache * for storing prepared statements. This allows for the efficient reuse of diff --git a/types/node/v24/stream.d.ts b/types/node/v24/stream.d.ts index 0aec9a2ae97ba4..955132737c9a9e 100644 --- a/types/node/v24/stream.d.ts +++ b/types/node/v24/stream.d.ts @@ -89,6 +89,7 @@ declare module "stream" { streamReadable: Readable, options?: { strategy?: streamWeb.QueuingStrategy | undefined; + type?: "bytes" | undefined; }, ): streamWeb.ReadableStream; /** @@ -1122,7 +1123,7 @@ declare module "stream" { * A utility method for creating a web `ReadableStream` and `WritableStream` from a `Duplex`. * @since v17.0.0 */ - static toWeb(streamDuplex: Duplex): { + static toWeb(streamDuplex: Duplex, options?: { readableType?: "bytes" | undefined }): { readable: streamWeb.ReadableStream; writable: streamWeb.WritableStream; }; diff --git a/types/node/v24/stream/consumers.d.ts b/types/node/v24/stream/consumers.d.ts index 05db0257d276a5..4dd81a50a2de6f 100644 --- a/types/node/v24/stream/consumers.d.ts +++ b/types/node/v24/stream/consumers.d.ts @@ -21,6 +21,13 @@ declare module "stream/consumers" { * @returns Fulfills with a `Buffer` containing the full contents of the stream. */ function buffer(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable): Promise; + /** + * @since v24.14.0 + * @returns Fulfills with a `Uint8Array` containing the full contents of the stream. + */ + function bytes( + stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable, + ): Promise; /** * @since v16.7.0 * @returns Fulfills with the contents of the stream parsed as a diff --git a/types/node/v24/stream/web.d.ts b/types/node/v24/stream/web.d.ts index 9aaf2c37b18159..a5cee6547580b7 100644 --- a/types/node/v24/stream/web.d.ts +++ b/types/node/v24/stream/web.d.ts @@ -259,6 +259,25 @@ declare module "stream/web" { prototype: ReadableStreamDefaultController; new(): ReadableStreamDefaultController; }; + /** + * Runs the WHATWG `ReadableStreamTee` abstract operation on `stream`. + * + * This differs from `readableStream.tee()` only when `cloneForBranch2` is + * `true`. The `tee()` method always passes `false`, while other web platform + * specifications, such as Fetch body cloning, pass `true` so that the second + * branch receives cloned chunks and consumption of one branch cannot mutate chunks + * seen by the other. + * @since v24.19.0 + * @experimental + * @param cloneForBranch2 When `true`, chunks enqueued into the second + * branch are cloned from chunks enqueued into the first branch. **Default:** + * `false`. + * @returns Two `ReadableStream` branches. + */ + function ReadableStreamTee( + stream: ReadableStream, + cloneForBranch2?: boolean, + ): [ReadableStream, ReadableStream]; interface Transformer { flush?: TransformerFlushCallback; readableType?: undefined; diff --git a/types/node/v24/test.d.ts b/types/node/v24/test.d.ts index 848f4ca1c5687a..4ba475eb3fcea6 100644 --- a/types/node/v24/test.d.ts +++ b/types/node/v24/test.d.ts @@ -79,7 +79,7 @@ * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/test.js) */ declare module "node:test" { - import { AssertMethodNames } from "node:assert"; + import { AssertMethodNames, AssertPredicate } from "node:assert"; import { Readable } from "node:stream"; import { URL } from "node:url"; import TestFn = test.TestFn; @@ -190,6 +190,16 @@ declare module "node:test" { function only(name?: string, fn?: SuiteFn): Promise; function only(options?: TestOptions, fn?: SuiteFn): Promise; function only(fn?: SuiteFn): Promise; + /** + * This flips the pass/fail reporting for a specific test or suite: a flagged test + * case must throw in order to pass, and a flagged test case that does not throw + * fails. + * @since v24.15.0 + */ + function expectFailure(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function expectFailure(name?: string, fn?: SuiteFn): Promise; + function expectFailure(options?: TestOptions, fn?: SuiteFn): Promise; + function expectFailure(fn?: SuiteFn): Promise; } /** * Shorthand for skipping a test. This is the same as calling {@link test} with `options.skip` set to `true`. @@ -215,6 +225,11 @@ declare module "node:test" { function only(name?: string, fn?: TestFn): Promise; function only(options?: TestOptions, fn?: TestFn): Promise; function only(fn?: TestFn): Promise; + // added in v25.5.0, undocumented + function expectFailure(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function expectFailure(name?: string, fn?: TestFn): Promise; + function expectFailure(options?: TestOptions, fn?: TestFn): Promise; + function expectFailure(fn?: TestFn): Promise; /** * The type of a function passed to {@link test}. The first argument to this function is a {@link TestContext} object. * If the test uses callbacks, the callback function is passed as the second argument. @@ -328,6 +343,15 @@ declare module "node:test" { * @since v22.1.0 */ testSkipPatterns?: string | RegExp | ReadonlyArray | undefined; + /** + * A tag name, or an array of tag names, + * used to filter tests by their declared tags. Tests must contain every + * listed tag to run. Equivalent to passing `--experimental-test-tag-filter` + * on the command line. See [Test tags](https://nodejs.org/docs/latest-v24.x/api/test.html#test-tags). + * @default undefined + * @since v24.19.0 + */ + testTagFilters?: string | readonly string[] | undefined; /** * The number of milliseconds after which the test execution will fail. * If unspecified, subtests inherit this value from their parent. @@ -344,6 +368,20 @@ declare module "node:test" { * @default undefined */ shard?: TestShard | undefined; + /** + * Randomize execution order for test files and queued tests. + * This option is not supported with `watch: true`. + * @since v24.16.0 + * @default false + */ + randomize?: boolean | undefined; + /** + * Seed used when randomizing execution order. If this + * option is set, runs can replay the same randomized order deterministically, + * and setting this option also enables randomization. The value must be an + * integer between `0` and `4294967295`. + */ + randomSeed?: number | undefined; /** * A file path where the test runner will * store the state of the tests to allow rerunning only the failed tests on a next run. @@ -398,6 +436,14 @@ declare module "node:test" { * @default 0 */ functionCoverage?: number | undefined; + /** + * Specify environment variables to be passed along to the test process. + * This option is not compatible with `isolation='none'`. These variables will override + * those from the main process, and are not merged with `process.env`. + * @since v24.14.0 + * @default process.env + */ + env?: NodeJS.ProcessEnv | undefined; } /** * A successful call to `run()` will return a new `TestsStream` object, streaming a series of events representing the execution of the tests. @@ -412,6 +458,7 @@ declare module "node:test" { addListener(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; addListener(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; addListener(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + addListener(event: "test:interrupted", listener: (data: EventData.TestInterrupted) => void): this; addListener(event: "test:pass", listener: (data: EventData.TestPass) => void): this; addListener(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; addListener(event: "test:start", listener: (data: EventData.TestStart) => void): this; @@ -427,6 +474,7 @@ declare module "node:test" { emit(event: "test:diagnostic", data: EventData.TestDiagnostic): boolean; emit(event: "test:enqueue", data: EventData.TestEnqueue): boolean; emit(event: "test:fail", data: EventData.TestFail): boolean; + emit(event: "test:interrupted", data: EventData.TestInterrupted): boolean; emit(event: "test:pass", data: EventData.TestPass): boolean; emit(event: "test:plan", data: EventData.TestPlan): boolean; emit(event: "test:start", data: EventData.TestStart): boolean; @@ -442,6 +490,7 @@ declare module "node:test" { on(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; on(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; on(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + on(event: "test:interrupted", listener: (data: EventData.TestInterrupted) => void): this; on(event: "test:pass", listener: (data: EventData.TestPass) => void): this; on(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; on(event: "test:start", listener: (data: EventData.TestStart) => void): this; @@ -457,6 +506,7 @@ declare module "node:test" { once(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; once(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; once(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + once(event: "test:interrupted", listener: (data: EventData.TestInterrupted) => void): this; once(event: "test:pass", listener: (data: EventData.TestPass) => void): this; once(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; once(event: "test:start", listener: (data: EventData.TestStart) => void): this; @@ -472,6 +522,7 @@ declare module "node:test" { prependListener(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; prependListener(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; prependListener(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + prependListener(event: "test:interrupted", listener: (data: EventData.TestInterrupted) => void): this; prependListener(event: "test:pass", listener: (data: EventData.TestPass) => void): this; prependListener(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; prependListener(event: "test:start", listener: (data: EventData.TestStart) => void): this; @@ -487,6 +538,7 @@ declare module "node:test" { prependOnceListener(event: "test:diagnostic", listener: (data: EventData.TestDiagnostic) => void): this; prependOnceListener(event: "test:enqueue", listener: (data: EventData.TestEnqueue) => void): this; prependOnceListener(event: "test:fail", listener: (data: EventData.TestFail) => void): this; + prependOnceListener(event: "test:interrupted", listener: (data: EventData.TestInterrupted) => void): this; prependOnceListener(event: "test:pass", listener: (data: EventData.TestPass) => void): this; prependOnceListener(event: "test:plan", listener: (data: EventData.TestPlan) => void): this; prependOnceListener(event: "test:start", listener: (data: EventData.TestStart) => void): this; @@ -729,6 +781,24 @@ declare module "node:test" { * The nesting level of the test. */ nesting: number; + /** + * The `testId` of the enclosing test, or + * `undefined` for top-level tests. Lets custom reporters track lineage + * when concurrent siblings at the same nesting level interleave. + */ + parentId: number | undefined; + /** + * The flattened lowercased tags declared on the test + * and its ancestor suites, in declaration order. Empty for untagged tests. + * See [Test tags](https://nodejs.org/docs/latest-v24.x/api/test.html#test-tags). + */ + tags: string[]; + /** + * A numeric identifier for this test instance, unique + * within the test file's process. Consistent across all events for the same + * test instance, enabling reliable correlation in custom reporters. + */ + testId: number; /** * The ordinal number of the test. */ @@ -751,6 +821,24 @@ declare module "node:test" { * The nesting level of the test. */ nesting: number; + /** + * The `testId` of the enclosing test, or + * `undefined` for top-level tests. Lets custom reporters track lineage + * when concurrent siblings at the same nesting level interleave. + */ + parentId: number | undefined; + /** + * The flattened lowercased tags declared on the test + * and its ancestor suites, in declaration order. Empty for untagged tests. + * See [Test tags](https://nodejs.org/docs/latest-v24.x/api/test.html#test-tags). + */ + tags: string[]; + /** + * A numeric identifier for this test instance, unique + * within the test file's process. Consistent across all events for the same + * test instance, enabling reliable correlation in custom reporters. + */ + testId: number; /** * The test type. Either `'suite'` or `'test'`. * @since v22.15.0 @@ -766,6 +854,24 @@ declare module "node:test" { * The nesting level of the test. */ nesting: number; + /** + * The `testId` of the enclosing test, or + * `undefined` for top-level tests. Lets custom reporters track lineage + * when concurrent siblings at the same nesting level interleave. + */ + parentId: number | undefined; + /** + * The flattened lowercased tags declared on the test + * and its ancestor suites, in declaration order. Empty for untagged tests. + * See [Test tags](https://nodejs.org/docs/latest-v24.x/api/test.html#test-tags). + */ + tags: string[]; + /** + * A numeric identifier for this test instance, unique + * within the test file's process. Consistent across all events for the same + * test instance, enabling reliable correlation in custom reporters. + */ + testId: number; /** * The test type. Either `'suite'` or `'test'`. * @since v22.15.0 @@ -805,6 +911,24 @@ declare module "node:test" { * The nesting level of the test. */ nesting: number; + /** + * The `testId` of the enclosing test, or + * `undefined` for top-level tests. Lets custom reporters track lineage + * when concurrent siblings at the same nesting level interleave. + */ + parentId: number | undefined; + /** + * The flattened lowercased tags declared on the test + * and its ancestor suites, in declaration order. Empty for untagged tests. + * See [Test tags](https://nodejs.org/docs/latest-v24.x/api/test.html#test-tags). + */ + tags: string[]; + /** + * A numeric identifier for this test instance, unique + * within the test file's process. Consistent across all events for the same + * test instance, enabling reliable correlation in custom reporters. + */ + testId: number; /** * The ordinal number of the test. */ @@ -818,6 +942,13 @@ declare module "node:test" { */ skip?: string | boolean; } + interface TestInterrupted { + /** + * An array of objects containing information about the + * interrupted tests. + */ + tests: TestStart[]; + } interface TestPass extends LocationInfo { /** * Additional execution metadata. @@ -853,6 +984,24 @@ declare module "node:test" { * The nesting level of the test. */ nesting: number; + /** + * The `testId` of the enclosing test, or + * `undefined` for top-level tests. Lets custom reporters track lineage + * when concurrent siblings at the same nesting level interleave. + */ + parentId: number | undefined; + /** + * The flattened lowercased tags declared on the test + * and its ancestor suites, in declaration order. Empty for untagged tests. + * See [Test tags](https://nodejs.org/docs/latest-v24.x/api/test.html#test-tags). + */ + tags: string[]; + /** + * A numeric identifier for this test instance, unique + * within the test file's process. Consistent across all events for the same + * test instance, enabling reliable correlation in custom reporters. + */ + testId: number; /** * The ordinal number of the test. */ @@ -885,6 +1034,24 @@ declare module "node:test" { * The nesting level of the test. */ nesting: number; + /** + * The `testId` of the enclosing test, or + * `undefined` for top-level tests. Lets custom reporters track lineage + * when concurrent siblings at the same nesting level interleave. + */ + parentId: number | undefined; + /** + * The flattened lowercased tags declared on the test + * and its ancestor suites, in declaration order. Empty for untagged tests. + * See [Test tags](https://nodejs.org/docs/latest-v24.x/api/test.html#test-tags). + */ + tags: string[]; + /** + * A numeric identifier for this test instance, unique + * within the test file's process. Consistent across all events for the same + * test instance, enabling reliable correlation in custom reporters. + */ + testId: number; } interface TestStderr { /** @@ -958,6 +1125,39 @@ declare module "node:test" { success: boolean; } } + /** + * Returns the {@link TestContext} or {@link SuiteContext} object associated with the + * currently executing test or suite, or `undefined` if called outside of a test or + * suite. This function can be used to access context information from within the + * test or suite function or any async operations within them. + + * ```js + * import { getTestContext } from 'node:test'; + * + * test('example test', async () => { + * const ctx = getTestContext(); + * console.log(`Running test: ${ctx.name}`); + * }); + * + * describe('example suite', () => { + * const ctx = getTestContext(); + * console.log(`Running suite: ${ctx.name}`); + * }); + * ``` + * + * When called from a test, returns a `TestContext`. + * When called from a suite, returns a `SuiteContext`. + * + * If called from outside a test or suite (e.g., at the top level of a module or in + * a setTimeout callback after execution has completed), this function returns + * `undefined`. + * + * When called from within a hook (before, beforeEach, after, afterEach), this + * function returns the context of the test or suite that the hook is associated + * with. + * @since v24.19.0 + */ + function getTestContext(): TestContext | SuiteContext | undefined; /** * An instance of `TestContext` is passed to each test function in order to * interact with the test runner. However, the `TestContext` constructor is not @@ -989,6 +1189,41 @@ declare module "node:test" { */ readonly assert: TestContextAssert; readonly attempt: number; + /** + * A frozen array of the test's flattened lowercased tags, in declaration + * order, including any tags inherited from ancestor suites. Empty when the + * test has no tags. See [Test tags](https://nodejs.org/docs/latest-v24.x/api/test.html#test-tags). + * @since v24.19.0 + */ + readonly tags: readonly string[]; + /** + * The unique identifier of the worker running the current test file. This value is + * derived from the `NODE_TEST_WORKER_ID` environment variable. When running tests + * with `--test-isolation=process` (the default), each test file runs in a separate + * child process and is assigned a worker ID from 1 to N, where N is the number of + * concurrent workers. When running with `--test-isolation=none`, all tests run in + * the same process and the worker ID is always 1. This value is `undefined` when + * not running in a test context. + * + * This property is useful for splitting resources (like database connections or + * server ports) across concurrent test files: + * + * ```js + * import { test } from 'node:test'; + * import { process } from 'node:process'; + * + * test('database operations', async (t) => { + * // Worker ID is available via context + * console.log(`Running in worker ${t.workerId}`); + * + * // Or via environment variable (available at import time) + * const workerId = process.env.NODE_TEST_WORKER_ID; + * // Use workerId to allocate separate resources per worker + * }); + * ``` + * @since v24.15.0 + */ + readonly workerId: number | undefined; /** * This function is used to create a hook running before subtest of the current test. * @param fn The hook function. The first argument to this function is a `TestContext` object. @@ -1320,6 +1555,31 @@ declare module "node:test" { * @since v18.7.0, v16.17.0 */ readonly signal: AbortSignal; + /** + * Indicates whether the suite and all of its subtests have passed. + * @since v24.16.0 + */ + readonly passed: boolean; + /** + * The current attempt number of the suite. Used in conjunction with the + * `--test-rerun-failures` option to determine the attempt number of the current + * run. + * @since v24.16.0 + */ + readonly attempt: number; + /** + * Output a diagnostic message. This is typically used for logging information + * about the current suite or its tests. + * + * ```js + * test.describe('my suite', (suite) => { + * suite.diagnostic('Suite diagnostic message'); + * }); + * ``` + * @since v24.16.0 + * @param message A diagnostic message to output. + */ + diagnostic(message: string): void; } interface TestOptions { /** @@ -1331,6 +1591,17 @@ declare module "node:test" { * @default false */ concurrency?: number | boolean | undefined; + /** + * If truthy, the test is expected to fail. If a non-empty string is provided, that string is displayed + * in the test results as the reason why the test is expected to fail. If a + * `RegExp`, `Function`, `Object`, or `Error` is provided directly (without wrapping in `{ match: … }`), the test passes + * only if the thrown error matches, following the behavior of + * `assert.throws`. To provide both a reason and validation, pass an object + * with `label` (string) and `match` (RegExp, Function, Object, or Error). + * @since v24.15.0 + * @default false + */ + expectFailure?: boolean | string | AssertPredicate | undefined; /** * If truthy, and the test context is configured to run `only` tests, then this test will be * run. Otherwise, the test is skipped. @@ -1348,6 +1619,15 @@ declare module "node:test" { * @default false */ skip?: boolean | string | undefined; + /** + * An array of string labels associated with the test. + * Used together with `--experimental-test-tag-filter` to filter which + * tests run. Tags inherit from suites to nested tests by union. See + * [Test tags](https://nodejs.org/docs/latest-v24.x/api/test.html#test-tags). + * @default [] + * @since v24.19.0 + */ + tags?: readonly string[] | undefined; /** * A number of milliseconds the test will fail after. If unspecified, subtests inherit this * value from their parent. @@ -1494,19 +1774,40 @@ declare module "node:test" { */ cache?: boolean | undefined; /** - * The value to use as the mocked module's default export. - * - * If this value is not provided, ESM mocks do not include a default export. - * If the mock is a CommonJS or builtin module, this setting is used as the value of `module.exports`. - * If this value is not provided, CJS and builtin mocks use an empty object as the value of `module.exports`. + * Optional mocked exports. The `default` property, if + * provided, is used as the mocked module's default export. All other own + * enumerable properties are used as named exports. + * **This option cannot be used with `defaultExport` or `namedExports`.** + * * If the mock is a CommonJS or builtin module, `exports.default` is used as + * the value of `module.exports`. + * * If `exports.default` is not provided for a CommonJS or builtin mock, + * `module.exports` defaults to an empty object. + * * If named exports are provided with a non-object default export, the mock + * throws an exception when used as a CommonJS or builtin module. + */ + exports?: object | undefined; + /** + * An optional value used as the mocked module's default + * export. If this value is not provided, ESM mocks do not include a default + * export. If the mock is a CommonJS or builtin module, this setting is used as + * the value of `module.exports`. If this value is not provided, CJS and builtin + * mocks use an empty object as the value of `module.exports`. + * **This option cannot be used with `options.exports`.** + * This option is deprecated and will be removed in a later version. + * Prefer `options.exports.default`. + * @deprecated */ defaultExport?: any; /** - * An object whose keys and values are used to create the named exports of the mock module. - * - * If the mock is a CommonJS or builtin module, these values are copied onto `module.exports`. - * Therefore, if a mock is created with both named exports and a non-object default export, - * the mock will throw an exception when used as a CJS or builtin module. + * An optional object whose keys and values are used to + * create the named exports of the mock module. If the mock is a CommonJS or + * builtin module, these values are copied onto `module.exports`. Therefore, if a + * mock is created with both named exports and a non-object default export, the + * mock will throw an exception when used as a CJS or builtin module. + * **This option cannot be used with `options.exports`.** + * This option is deprecated and will be removed in a later version. + * Prefer `options.exports`. + * @deprecated */ namedExports?: object | undefined; } @@ -1681,14 +1982,19 @@ declare module "node:test" { * [`--experimental-test-module-mocks`](https://nodejs.org/docs/latest-v24.x/api/cli.html#--experimental-test-module-mocks) * command-line flag. * + * **Note**: [module customization hooks](https://nodejs.org/docs/latest-v24.x/api/module.html#customization-hooks) registered via the **synchronous** API effect resolution of + * the `specifier` provided to `mock.module`. Customization hooks registered via the **asynchronous** + * API are currently ignored (because the test runner's loader is synchronous, and node does not + * support multi-chain / cross-chain loading). + * * The following example demonstrates how a mock is created for a module. * * ```js * test('mocks a builtin module in both module systems', async (t) => { - * // Create a mock of 'node:readline' with a named export named 'fn', which + * // Create a mock of 'node:readline' with a named export named 'foo', which * // does not exist in the original 'node:readline' module. * const mock = t.mock.module('node:readline', { - * namedExports: { fn() { return 42; } }, + * exports: { foo: () => 42 }, * }); * * let esmImpl = await import('node:readline'); @@ -2295,6 +2601,7 @@ declare module "node:test/reporters" { | { type: "test:diagnostic"; data: EventData.TestDiagnostic } | { type: "test:enqueue"; data: EventData.TestEnqueue } | { type: "test:fail"; data: EventData.TestFail } + | { type: "test:interrupted"; data: EventData.TestInterrupted } | { type: "test:pass"; data: EventData.TestPass } | { type: "test:plan"; data: EventData.TestPlan } | { type: "test:start"; data: EventData.TestStart } diff --git a/types/node/v24/test/async_hooks.ts b/types/node/v24/test/async_hooks.ts index 588825e35c4fc3..99c96b5a31e21e 100644 --- a/types/node/v24/test/async_hooks.ts +++ b/types/node/v24/test/async_hooks.ts @@ -16,6 +16,7 @@ import { after() {}, destroy() {}, promiseResolve() {}, + trackPromises: true, }; const asyncHook = createHook(hooks); diff --git a/types/node/v24/test/buffer.ts b/types/node/v24/test/buffer.ts index 3356f2d4046bfd..1d0952945d6668 100644 --- a/types/node/v24/test/buffer.ts +++ b/types/node/v24/test/buffer.ts @@ -565,6 +565,7 @@ declare class NodeFile implements File { arrayBuffer(): Promise; bytes(): Promise; text(): Promise; + textStream(): ReadableStream; } { diff --git a/types/node/v24/test/crypto.ts b/types/node/v24/test/crypto.ts index 99205d51865bab..c5064e621af03a 100644 --- a/types/node/v24/test/crypto.ts +++ b/types/node/v24/test/crypto.ts @@ -1128,7 +1128,7 @@ import { promisify } from "node:util"; format: "der", }); crypto.createPrivateKey({ - key: "asd", + key: {}, format: "jwk", }); } @@ -1560,6 +1560,13 @@ import { promisify } from "node:util"; crypto.randomUUID(); } +{ + crypto.randomUUIDv7({}); + crypto.randomUUIDv7({ disableEntropyCache: true }); + crypto.randomUUIDv7({ disableEntropyCache: false }); + crypto.randomUUIDv7(); +} + { const cert = new crypto.X509Certificate("dummy"); cert.ca; // $ExpectType boolean @@ -1892,3 +1899,33 @@ import { promisify } from "node:util"; const publicKey = crypto.decapsulate(privateKey, Buffer.from("the quick brown fox jumped over the lazy dog")); const { sharedKey, ciphertext } = crypto.encapsulate(publicKey); } + +// Raw key format export/import +{ + const { publicKey, privateKey } = crypto.generateKeyPairSync("ed25519"); + + // Export with raw formats + const rawPublic = publicKey.export({ format: "raw-public" }); + rawPublic; // $ExpectType NonSharedBuffer + const rawPrivate = privateKey.export({ format: "raw-private" }); + rawPrivate; // $ExpectType NonSharedBuffer + const rawSeed = privateKey.export({ format: "raw-seed" }); + rawSeed; // $ExpectType NonSharedBuffer + + // Import with raw formats + const importedPublic = crypto.createPublicKey({ + key: rawPublic, + format: "raw-public", + asymmetricKeyType: "ed25519", + }); + const importedPrivate = crypto.createPrivateKey({ + key: rawPrivate, + format: "raw-private", + asymmetricKeyType: "ed25519", + }); + + // @ts-expect-error + crypto.createPublicKey({ key: rawPrivate, format: "raw-private" }); + // @ts-expect-error + crypto.createPrivateKey({ key: rawPublic, format: "raw-public" }); +} diff --git a/types/node/v24/test/dgram.ts b/types/node/v24/test/dgram.ts index 41cb9c02ae3016..4f801b94d1315b 100644 --- a/types/node/v24/test/dgram.ts +++ b/types/node/v24/test/dgram.ts @@ -157,12 +157,18 @@ sock.bind(8000, "192.0.2.1", () => undefined); sock.bind({}, () => undefined); sock.bind({ port: 8000, address: "192.0.2.1", exclusive: true }); sock.bind({ fd: 7, exclusive: true }); +sock.bindSync(); // $ExpectType AddressInfo +sock.bindSync({}); // $ExpectType AddressInfo +sock.bindSync({ address: "192.0.2.1" }); // $ExpectType AddressInfo +sock.bindSync({ address: "192.0.2.1", port: 8000 }); // $ExpectType AddressInfo sock.close(); sock.close(() => undefined); sock.connect(8000); sock.connect(8000, "192.0.2.1"); sock.connect(8000, () => undefined); sock.connect(8000, "192.0.2.1", () => undefined); +sock.connectSync(8000); +sock.connectSync(8000, "192.0.2.1"); sock.disconnect(); sock.dropMembership("233.252.0.0"); sock.dropMembership("233.252.0.0", "192.0.2.1"); diff --git a/types/node/v24/test/events.ts b/types/node/v24/test/events.ts index 00afd3e1a5fe3d..269aac8dfc52bc 100644 --- a/types/node/v24/test/events.ts +++ b/types/node/v24/test/events.ts @@ -24,7 +24,8 @@ declare const any: any; let result: number; result = events.EventEmitter.defaultMaxListeners; - result = events.EventEmitter.listenerCount(emitter, event); // deprecated + result = events.EventEmitter.listenerCount(emitter, event); + result = events.listenerCount(new EventTarget(), "event"); const promise: Promise = events.once(new events.EventEmitter(), "error"); diff --git a/types/node/v24/test/fs.ts b/types/node/v24/test/fs.ts index 9969856523ac75..bed249153f255b 100644 --- a/types/node/v24/test/fs.ts +++ b/types/node/v24/test/fs.ts @@ -100,6 +100,19 @@ import { CopyOptions, CopySyncOptions, cp, cpSync, glob, globSync } from "fs"; fs.readFile("testfile", { encoding: nullEncoding }, (err, data) => stringOrBuffer = data); fs.readFile("testfile", { flag: "r" }, (err, data) => buffer = data); + + fs.readFile("testfile", { buffer: new Uint8Array(16) }, (err, data) => { + data; // $ExpectType Buffer || Buffer + }); + fs.readFile("testfile", { buffer: new Uint8Array(new SharedArrayBuffer(16)) }, (err, data) => { + data; // $ExpectType Buffer || Buffer + }); + fs.readFile("testfile", { buffer }, (err, data) => { + data; // $ExpectType Buffer || Buffer + }); + fs.readFile("testfile", { buffer: (size) => new Uint8Array(size) }, (err, data) => { + data; // $ExpectType Buffer || Buffer + }); } { @@ -269,6 +282,7 @@ async function testPromisify() { persistent: true, encoding: "utf8", signal: new AbortSignal(), + ignore: (filename) => filename.startsWith("_"), }, (event, filename) => { console.log(event, filename); }); @@ -812,8 +826,8 @@ async function testStat( path: string, fd: number, opts: fs.StatOptions, - bigintMaybeFalse: fs.StatOptions & { bigint: false } | undefined, - bigIntMaybeTrue: fs.StatOptions & { bigint: true } | undefined, + bigintMaybeFalse: { bigint: false } | undefined, + bigIntMaybeTrue: { bigint: true } | undefined, maybe?: fs.StatOptions, ) { /* Need to test these variants: @@ -863,7 +877,7 @@ async function testStat( fs.fstat(fd, { bigint: true }, (err, st: fs.BigIntStats) => {}); fs.stat(path, bigIntMaybeTrue, (err, st) => { - st; // $ExpectType Stats | BigIntStats + st; // $ExpectType Stats | BigIntStats | undefined }); fs.lstat(path, bigIntMaybeTrue, (err, st) => { st; // $ExpectType Stats | BigIntStats @@ -873,7 +887,7 @@ async function testStat( }); fs.stat(path, opts, (err, st) => { - st; // $ExpectType Stats | BigIntStats + st; // $ExpectType Stats | BigIntStats | undefined }); fs.lstat(path, opts, (err, st) => { @@ -940,11 +954,11 @@ async function testStat( util.promisify(fs.lstat)(path, { bigint: true }); // $ExpectType Promise util.promisify(fs.fstat)(fd, { bigint: true }); // $ExpectType Promise - util.promisify(fs.stat)(path, bigIntMaybeTrue); // $ExpectType Promise + util.promisify(fs.stat)(path, bigIntMaybeTrue); // $ExpectType Promise util.promisify(fs.lstat)(path, bigIntMaybeTrue); // $ExpectType Promise util.promisify(fs.fstat)(fd, bigIntMaybeTrue); // $ExpectType Promise - util.promisify(fs.stat)(path, opts); // $ExpectType Promise + util.promisify(fs.stat)(path, opts); // $ExpectType Promise util.promisify(fs.lstat)(path, opts); // $ExpectType Promise util.promisify(fs.fstat)(fd, opts); // $ExpectType Promise @@ -972,11 +986,11 @@ async function testStat( fs.promises.stat(path, bigIntMaybeTrue); // $ExpectType Promise fs.promises.lstat(path, bigIntMaybeTrue); // $ExpectType Promise - fh.stat(bigIntMaybeTrue); // $ExpectType Promise + fh.stat(bigIntMaybeTrue); // $ExpectType Promise fs.promises.stat(path, opts); // $ExpectType Promise fs.promises.lstat(path, opts); // $ExpectType Promise - fh.stat(opts); // $ExpectType Promise + fh.stat(opts); // $ExpectType Promise } const bigStats: fs.BigIntStats = fs.statSync(".", { bigint: true }); @@ -1150,7 +1164,7 @@ const anyStatFs: fs.StatsFs | fs.BigIntStatsFs = fs.statfsSync(".", { bigint: Ma glob("**/*.js", (err, matches) => { matches; // $ExpectType string[] }); - glob("**/*.js", { cwd: new URL("") }, (err, matches) => { + glob("**/*.js", { cwd: new URL(""), followSymlinks: true }, (err, matches) => { matches; // $ExpectType string[] }); glob("**/*.js", { withFileTypes: true }, (err, matches) => { @@ -1203,7 +1217,7 @@ const anyStatFs: fs.StatsFs | fs.BigIntStatsFs = fs.statfsSync(".", { bigint: Ma }); globSync("**/*.js"); // $ExpectType string[] - globSync("**/*.js", { cwd: "/" }); // $ExpectType string[] + globSync("**/*.js", { cwd: "/", followSymlinks: true }); // $ExpectType string[] globSync("**/*.js", { withFileTypes: true }); // $ExpectType Dirent[] globSync("**/*.js", { withFileTypes: Math.random() > 0.5 }); // $ExpectType string[] | Dirent[] @@ -1247,6 +1261,9 @@ const anyStatFs: fs.StatsFs | fs.BigIntStatsFs = fs.statfsSync(".", { bigint: Ma fd.readFile({ signal: new AbortSignal(), encoding: "utf-8" }); // @ts-expect-error fd.readFile({ encoding: "utf-8", flag: "r" }); + + await fd.readFile({ buffer: new Uint8Array(256) }); // $ExpectType Buffer || Buffer + await fd.readFile({ buffer: (size) => new Uint8Array(size) }); // $ExpectType Buffer || Buffer }); { diff --git a/types/node/v24/test/http.ts b/types/node/v24/test/http.ts index 9c4e01f666f660..423883db803d3d 100644 --- a/types/node/v24/test/http.ts +++ b/types/node/v24/test/http.ts @@ -32,6 +32,7 @@ import * as url from "node:url"; server = http.createServer({ ServerResponse: MyServerResponse }, reqListener); // TODO: add test for all remaining options server = http.createServer({ + httpValidation: "insecure", insecureHTTPParser: true, keepAlive: true, keepAliveInitialDelay: 1000, @@ -224,6 +225,8 @@ import * as url from "node:url"; incoming.pause(); incoming.resume(); + incoming.signal; // $ExpectType AbortSignal + // response const res: http.ServerResponse = new http.ServerResponse(incoming); @@ -274,6 +277,12 @@ import * as url from "node:url"; res.writeHead(200, ["Transfer-Encoding", "chunked"]); res.writeHead(200); + // writeInformation + res.writeInformation(110); + res.writeInformation(110, () => {}); + res.writeInformation(110, { "X-Progress": "50%" }); + res.writeInformation(110, { "X-Progress": "50%" }, () => {}); + // writeProcessing res.writeProcessing(); res.writeProcessing(() => {}); @@ -740,6 +749,11 @@ import * as url from "node:url"; http.validateHeaderValue("Location", "/"); http.setMaxIdleHTTPParsers(1337); + + // $ExpectType () => void + http.setGlobalProxyFromEnv(); + // $ExpectType () => void + http.setGlobalProxyFromEnv(process.env); } { diff --git a/types/node/v24/test/http2.ts b/types/node/v24/test/http2.ts index 25bae7efe4a45b..9e2b249ec96188 100644 --- a/types/node/v24/test/http2.ts +++ b/types/node/v24/test/http2.ts @@ -1,3 +1,4 @@ +import { IncomingMessage, ServerResponse } from "node:http"; import { ClientHttp2Session, ClientHttp2Stream, @@ -269,6 +270,7 @@ import { URL } from "node:url"; maxDeflateDynamicTableSize: 0, maxSettings: 32, maxSessionMemory: 10, + maxOriginSetSize: 128, maxHeaderListPairs: 128, maxOutstandingPings: 10, maxSendHeaderBlockLength: 0, @@ -280,6 +282,7 @@ import { URL } from "node:url"; streamResetBurst: 1000, streamResetRate: 33, strictFieldWhitespaceValidation: false, + strictSingleValueFields: true, }; const secureServerOptions: SecureServerOptions = { ...serverOptions, ca: "..." }; const onRequestHandler = (request: Http2ServerRequest, response: Http2ServerResponse) => { @@ -440,6 +443,62 @@ import { URL } from "node:url"; settings = getUnpackedSettings(Uint8Array.from([])); } +// Http1IncomingMessage, Http1ServerResponse +{ + class MyHttp1ServerRequest extends IncomingMessage { + foo!: number; + } + + class MyHttp1ServerResponse extends ServerResponse { + bar!: string; + } + + // $ExpectType Http2Server + createServer({ + http1Options: { + IncomingMessage: MyHttp1ServerRequest, + ServerResponse: MyHttp1ServerResponse, + keepAliveTimeout: 500, + }, + }); + + // $ExpectType Http2SecureServer + createSecureServer({ + allowHTTP1: true, + http1Options: { + IncomingMessage: MyHttp1ServerRequest, + ServerResponse: MyHttp1ServerResponse, + keepAliveTimeout: 500, + }, + }); + + // $ExpectType Http2Server + createServer({ + http1Options: { keepAliveTimeout: 500 }, + }); + + // $ExpectType Http2SecureServer + createSecureServer({ + allowHTTP1: true, + http1Options: { keepAliveTimeout: 500 }, + }); + + // Deprecated + // $ExpectType Http2Server + createServer({ + Http1IncomingMessage: MyHttp1ServerRequest, + Http1ServerResponse: MyHttp1ServerResponse, + }); + + // Deprecated + // $ExpectType Http2SecureServer + createSecureServer({ + allowHTTP1: true, + Http1IncomingMessage: MyHttp1ServerRequest, + Http1ServerResponse: MyHttp1ServerResponse, + }); +} + // Http2ServerRequest, Http2ServerResponse, { class MyHttp2ServerRequest extends Http2ServerRequest { diff --git a/types/node/v24/test/net.ts b/types/node/v24/test/net.ts index 8dad4405eef55d..10513ad5fb36de 100644 --- a/types/node/v24/test/net.ts +++ b/types/node/v24/test/net.ts @@ -64,6 +64,7 @@ import * as net from "node:net"; keepAliveInitialDelay: 1000, noDelay: false, blockList: new net.BlockList(), + typeOfService: 0b00000111, }); let bool: boolean; @@ -78,7 +79,9 @@ import * as net from "node:net"; _socket = _socket.setTimeout(500); _socket = _socket.setNoDelay(true); - _socket = _socket.setKeepAlive(true, 10); + _socket = _socket.setKeepAlive(true); + _socket = _socket.setKeepAlive(true, 1000, 5000, 5); + _socket = _socket.setKeepAlive({ enable: true, initialDelay: 500 }); _socket = _socket.setEncoding("utf8"); _socket = _socket.resume(); _socket = _socket.resetAndDestroy(); @@ -491,6 +494,16 @@ import * as net from "node:net"; }); } +{ + const socket = new net.Socket(); + + // $ExpectType number + socket.getTypeOfService(); + + // $ExpectType Socket + socket.setTypeOfService(0b00000111); +} + { const sockAddr: net.SocketAddress = new net.SocketAddress({ address: "123.123.123.123", @@ -517,3 +530,16 @@ import * as net from "node:net"; bl.toJSON(); // $ExpectType readonly string[] net.BlockList.isBlockList(bl); // $ExpectType boolean } + +{ + using boundSocket = new net.BoundSocket({ + host: "1234:5678::1", + port: 8080, + ipv6Only: false, + reusePort: false, + }); + boundSocket.address(); // $ExpectType AddressInfo + boundSocket.fd(); // $ExpectType number + + new net.Socket({ handle: new net.BoundSocket() }); +} diff --git a/types/node/v24/test/perf_hooks.ts b/types/node/v24/test/perf_hooks.ts index 8e43f485bb3a3d..cd1557494cacfd 100644 --- a/types/node/v24/test/perf_hooks.ts +++ b/types/node/v24/test/perf_hooks.ts @@ -1,8 +1,8 @@ import { createHistogram, + ELDHistogram, EntryType, eventLoopUtilization, - IntervalHistogram, monitorEventLoopDelay, performance as NodePerf, PerformanceEntry, @@ -46,7 +46,7 @@ obs.observe({ buffered: true, }); -const monitor: IntervalHistogram = monitorEventLoopDelay({ +const monitor: ELDHistogram = monitorEventLoopDelay({ resolution: 42, }); diff --git a/types/node/v24/test/sqlite.ts b/types/node/v24/test/sqlite.ts index 9433903ef6604b..e867fe5d9610d4 100644 --- a/types/node/v24/test/sqlite.ts +++ b/types/node/v24/test/sqlite.ts @@ -1,4 +1,4 @@ -import { backup, constants, DatabaseSync, StatementSync } from "node:sqlite"; +import { backup, constants, DatabaseLimits, DatabaseSync, StatementSync } from "node:sqlite"; import { TextEncoder } from "node:util"; { @@ -42,6 +42,9 @@ import { TextEncoder } from "node:util"; }, ); + database.deserialize(database.serialize()); + database.deserialize(database.serialize("db"), { dbName: "db" }); + const insert = database.prepare("INSERT INTO types (key, int, double, text, buf) VALUES (?, ?, ?, ?, ?)"); insert.setReadBigInts(true); insert.setAllowBareNamedParameters(true); @@ -73,19 +76,31 @@ import { TextEncoder } from "node:util"; } { - new DatabaseSync(":memory:", { + const db = new DatabaseSync(":memory:", { timeout: 10_000, readBigInts: true, returnArrays: true, allowBareNamedParameters: false, allowUnknownNamedParameters: true, }); + + const stmt = db.prepare("SELECT 1", { + readBigInts: true, + returnArrays: true, + allowBareNamedParameters: false, + allowUnknownNamedParameters: true, + }); + + // $ExpectType SQLOutputValue + stmt.get()![0]; } { const database = new DatabaseSync(":memory:", { allowExtension: true }); database.enableDefensive(true); // $ExpectType void database.loadExtension("/path/to/extension.so"); // $ExpectType void + database.loadExtension("./decimal.dylib"); + database.loadExtension("./base64.dylib", "sqlite3_base64_init"); database.enableLoadExtension(false); // $ExpectType void } @@ -175,3 +190,13 @@ import { TextEncoder } from "node:util"; return constants.SQLITE_OK; }); } + +{ + const db = new DatabaseSync(":memory:", { + limits: { attach: 10, column: 2000, compoundSelect: 500 }, + }); + + let k!: keyof DatabaseLimits; + db.limits[k]; // $ExpectType number + db.limits[k] = 100; +} diff --git a/types/node/v24/test/stream-web.ts b/types/node/v24/test/stream-web.ts index 044fd3c069a34a..b1be3765c2bbbc 100644 --- a/types/node/v24/test/stream-web.ts +++ b/types/node/v24/test/stream-web.ts @@ -1,5 +1,5 @@ import assert from "node:assert"; -import { ReadableStream, TransformStream, WritableStream } from "node:stream/web"; +import { ReadableStream, ReadableStreamTee, TransformStream, WritableStream } from "node:stream/web"; import type { QueuingStrategySize } from "node:stream/web"; async function readResultHasRequiredValueProperty() { @@ -101,3 +101,18 @@ async function queuingStrategySizeReceivesTheChunk() { assert.deepStrictEqual(result, { done: false, value: "size" }); assert.deepStrictEqual(sizeChunks, ["size"]); } + +{ + const stream = new ReadableStream({ + pull(controller) { + controller.enqueue(Math.random()); + }, + }); + + const [stream1, stream2] = ReadableStreamTee(stream); + + stream1; // $ExpectType ReadableStream + stream2; // $ExpectType ReadableStream + + ReadableStreamTee(stream, true); +} diff --git a/types/node/v24/test/stream.ts b/types/node/v24/test/stream.ts index c021751a2bceef..848113c9bea4d6 100644 --- a/types/node/v24/test/stream.ts +++ b/types/node/v24/test/stream.ts @@ -510,6 +510,8 @@ async function testConsumers() { await consumers.blob(consumable); // $ExpectType NonSharedBuffer await consumers.buffer(consumable); + // $ExpectType NonSharedUint8Array + await consumers.bytes(consumable); // $ExpectType unknown await consumers.json(consumable); // $ExpectType string @@ -603,6 +605,9 @@ addAbortSignal(new AbortSignal(), new Readable()); }, }, }); + + // $ExpectType ReadableStream + Readable.toWeb(readable, { type: "bytes" }); } { @@ -645,6 +650,8 @@ addAbortSignal(new AbortSignal(), new Readable()); const duplex = new Duplex(); // $ExpectType { readable: ReadableStream; writable: WritableStream; } Duplex.toWeb(duplex); + // $ExpectType { readable: ReadableStream; writable: WritableStream; } + Duplex.toWeb(duplex, { readableType: "bytes" }); } { diff --git a/types/node/v24/test/test.ts b/types/node/v24/test/test.ts index 0e178a317882b8..62fcd8f390a582 100644 --- a/types/node/v24/test/test.ts +++ b/types/node/v24/test/test.ts @@ -6,6 +6,8 @@ import { before, beforeEach, describe, + expectFailure, + getTestContext, it, Mock, mock, @@ -49,6 +51,7 @@ run({ isolation: "process", testNamePatterns: ["executed", /^core-/], testSkipPatterns: ["excluded", /^lib-/], + testTagFilters: ["tag1", "tag2"], only: true, setup: (reporter) => { // $ExpectType TestsStream @@ -67,7 +70,12 @@ run({ lineCoverage: 70, branchCoverage: 50, functionCoverage: 80, + randomize: true, + randomSeed: 1029384756, rerunFailuresFilePath: "/path/to/file.json", + env: { + MY_TEST_PATH: "/path/to/tests", + }, }); // TestsStream should be a NodeJS.ReadableStream @@ -167,6 +175,10 @@ test(undefined, undefined, t => { t.mock; // $ExpectType number t.attempt; + // $ExpectType readonly string[] + t.tags; + // $ExpectType number | undefined + t.workerId; }); // Test the subtest approach. @@ -218,6 +230,7 @@ describe("options with values", { skip: "reason for skip", timeout: Infinity, todo: "reason for todo", + expectFailure: true, }); it("options with values", { @@ -227,6 +240,7 @@ it("options with values", { skip: "reason for skip", timeout: Infinity, todo: "reason for todo", + expectFailure: true, }); describe("options with booleans", { @@ -337,6 +351,46 @@ it.only("only shorthand", { timeout: Infinity, }); +expectFailure("x", { + concurrency: 1, + only: true, + signal: new AbortController().signal, + timeout: Infinity, +}); +expectFailure((t, cb) => { + // $ExpectType TestContext + t; + // $ExpectType (result?: any) => void + cb; + // $ExpectType void + cb({ x: "anything" }); +}); +test.expectFailure("x", { + concurrency: 1, + only: true, + signal: new AbortController().signal, + timeout: Infinity, +}); +describe.expectFailure("x", { + concurrency: 1, + only: true, + signal: new AbortController().signal, + timeout: Infinity, +}); +it.expectFailure("x", { + concurrency: 1, + only: true, + signal: new AbortController().signal, + timeout: Infinity, +}); + +// expectFailure predicates +test({ expectFailure: "message" }); +test({ expectFailure: Error }); +test({ expectFailure: /error/ }); +test({ expectFailure: { code: "ERR_INVALID_ARG_TYPE" } }); +test({ expectFailure: (err) => err instanceof TypeError }); + // Test with suite context describe(s => { // $ExpectType SuiteContext @@ -466,6 +520,20 @@ suite("foo", (context) => { context.name; // $ExpectType AbortSignal context.signal; + // $ExpectType boolean + context.passed; + // $ExpectType number + context.attempt; + + context.diagnostic("diagnostic"); +}); + +suite("test tags", () => { + describe("database", { tags: ["db"] }, () => { + it("reads a row"); // tags: ['db'] + it("writes a row", { tags: ["integration"] }); // tags: ['db', 'integration'] + it("reconnects after disconnect", { tags: ["flaky"] }); // tags: ['db', 'flaky'] + }); }); // Hooks @@ -801,15 +869,12 @@ test("mocks a module", (t) => { // module specifier as a string // $ExpectType MockModuleContext const mock = t.mock.module("node:readline", { - namedExports: { - fn() { - return 42; - }, - }, - defaultExport: { + exports: { + default: class Exported {}, foo() { - return "bar"; + return 42; }, + bar: 42, }, cache: true, }); @@ -939,6 +1004,14 @@ class TestReporter extends Transform { ); break; } + case "test:interrupted": { + const { tests } = event.data; + callback( + null, + tests.map((test) => `${test.name}/${test.nesting}/${test.file}/${test.column}/${test.line}`), + ); + break; + } case "test:pass": { const { file, column, line, details, name, nesting, testNumber, skip, todo } = event.data; callback( @@ -1071,6 +1144,8 @@ test("planning with streams", (t: TestContext, done) => { }); }); +getTestContext(); // $ExpectType TestContext | SuiteContext | undefined + // Test custom assertion functions. { test.assert.register("isOdd", (n: number) => { diff --git a/types/node/v24/test/tls.ts b/types/node/v24/test/tls.ts index 0ef3979f32b6f3..ae190b48c011e8 100644 --- a/types/node/v24/test/tls.ts +++ b/types/node/v24/test/tls.ts @@ -11,6 +11,7 @@ import { DEFAULT_MIN_VERSION, EphemeralKeyInfo, getCACertificates, + getCertificateCompressionAlgorithms, getCiphers, PeerCertificate, rootCertificates, @@ -41,6 +42,7 @@ import { }; }, requestOCSP: true, + certificateCompression: ["zlib"], }; const tlsSocket = connect(connOpts); @@ -65,6 +67,7 @@ import { const caCertificates: string[] = getCACertificates("default"); const ciphers: string[] = getCiphers(); + const certificateCompressionAlgorithms: string[] = getCertificateCompressionAlgorithms(); const curve: string = DEFAULT_ECDH_CURVE; const maxVersion: string = DEFAULT_MAX_VERSION; const minVersion: string = DEFAULT_MIN_VERSION; diff --git a/types/node/v24/test/util.ts b/types/node/v24/test/util.ts index 828fd8e7c63a31..2291758c8b1a79 100644 --- a/types/node/v24/test/util.ts +++ b/types/node/v24/test/util.ts @@ -89,6 +89,10 @@ console.log( console.log( util.styleText("yellow", "text", { stream: process.stdout }), ); +// 6-digit hex color +console.log(util.styleText("#ff5733", "Orange text")); +// 3-digit hex color (shorthand) +console.log(util.styleText("#f00", "Red text")); // util.callbackify class callbackifyTest { @@ -534,3 +538,10 @@ util.setTraceSigInt(true); console.log(`Column Number: ${callSite.columnNumber}`); }); } + +{ + // $ExpectType number + util.convertProcessSignalToExitCode("SIGABRT"); + // @ts-expect-error + util.convertProcessSignalToExitCode("INVALID"); +} diff --git a/types/node/v24/tls.d.ts b/types/node/v24/tls.d.ts index 658c0135e85498..d17a87e97bf4f9 100644 --- a/types/node/v24/tls.d.ts +++ b/types/node/v24/tls.d.ts @@ -273,11 +273,19 @@ declare module "tls" { */ getCipher(): CipherNameAndProtocol; /** - * Returns an object representing the type, name, and size of parameter of - * an ephemeral key exchange in `perfect forward secrecy` on a client - * connection. It returns an empty object when the key exchange is not - * ephemeral. As this is only supported on a client socket; `null` is returned - * if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The `name` property is available only when type is `'ECDH'`. + * Returns an object describing ephemeral key agreement in [perfect forward + * secrecy](https://nodejs.org/docs/latest-v26.x/api/tls.html#perfect-forward-secrecy) on a client connection. It returns an empty object when the key + * agreement is not ephemeral. As this is only supported on a client socket; + * `null` is returned if called on a server socket. The supported types are `'DH'`, + * `'ECDH'`, and `'TLSGroup'`. For `'DH'` and `'ECDH'`, the object describes peer + * temporary key parameters. For `'TLSGroup'`, the object identifies the negotiated + * TLS Supported Group used for key agreement when a peer temporary key object is + * not available. + * + * The `name` property is available only when type is `'ECDH'` or `'TLSGroup'`. The + * `size` property is not available when type is `'TLSGroup'`. For `'TLSGroup'`, + * `name` is the negotiated TLS Supported Group name. Standardized TLS group names + * and code points are listed in the [IANA TLS Supported Groups registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-8). * * For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`. * @since v5.0.0 @@ -832,6 +840,7 @@ declare module "tls" { prependOnceListener(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: TLSSocket) => void): this; } type SecureVersion = "TLSv1.3" | "TLSv1.2" | "TLSv1.1" | "TLSv1"; + type CertificateCompressionAlgorithm = "zlib" | "brotli" | "zstd"; interface SecureContextOptions { /** * If set, this will be called when a client opens a connection using the ALPN extension. @@ -868,6 +877,15 @@ declare module "tls" { * able to validate the certificate, and the handshake will fail. */ cert?: string | Buffer | Array | undefined; + /** + * An array of supported certificate + * compression algorithm names, in preference order. Supported values are + * `'zlib'`, `'brotli'`, and `'zstd'`. When set, enables TLS certificate + * compression ([RFC 8879](https://tools.ietf.org/html/rfc8879)) which compresses certificates during the TLS + * handshake, reducing handshake size. Only effective with TLSv1.3. + * **Default:** `[]` (disabled). + */ + certificateCompression?: readonly CertificateCompressionAlgorithm[] | undefined; /** * Colon-separated list of supported signature algorithms. The list * can contain digest algorithms (SHA256, MD5 etc.), public key @@ -898,13 +916,16 @@ declare module "tls" { */ dhparam?: string | Buffer | undefined; /** - * A string describing a named curve or a colon separated list of curve - * NIDs or names, for example P-521:P-384:P-256, to use for ECDH key - * agreement. Set to auto to select the curve automatically. Use - * crypto.getCurves() to obtain a list of available curve names. On - * recent releases, openssl ecparam -list_curves will also display the - * name and description of each available elliptic curve. Default: - * tls.DEFAULT_ECDH_CURVE. + * A string describing a named curve, TLS group, or + * colon-separated list of named curves or TLS groups to use for key agreement, + * for example `P-521:P-384:P-256`, `X25519`, or `X25519MLKEM768`. The + * historical name of this option refers to ECDH key agreement in TLSv1.2 and + * below. In TLSv1.3, this option configures the TLS Supported Groups and + * key share groups offered or accepted by the TLS stack. Set to `auto` to + * select the group automatically. Use `crypto.getCurves()` to obtain a + * list of available elliptic curve names. For TLS group names, use + * `openssl list -tls-groups` or consult the [IANA TLS Supported Groups + * registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-8). */ ecdhCurve?: string | undefined; /** @@ -1196,6 +1217,20 @@ declare module "tls" { * @since v0.10.2 */ function getCiphers(): string[]; + /** + * Returns an array with the names of the RFC 8879 certificate compression + * algorithms supported by the current OpenSSL build, suitable for use in the + * `certificateCompression` option of `tls.createSecureContext()`. Possible + * values include `'zlib'`, `'brotli'`, and `'zstd'`. + * + * The array is empty when certificate compression is unavailable. + * + * ```js + * console.log(tls.getCertificateCompressionAlgorithms()); // ['zlib', 'brotli', 'zstd'] + * ``` + * @since v24.19.0 + */ + function getCertificateCompressionAlgorithms(): CertificateCompressionAlgorithm[]; /** * Sets the default CA certificates used by Node.js TLS clients. If the provided * certificates are parsed successfully, they will become the default CA @@ -1229,9 +1264,9 @@ declare module "tls" { */ function setDefaultCACertificates(certs: ReadonlyArray): void; /** - * The default curve name to use for ECDH key agreement in a tls server. - * The default value is `'auto'`. See `{@link createSecureContext()}` for further - * information. + * The default named curve or TLS group list to use for key agreement in a TLS + * server. The default value is `'auto'`. See `tls.createSecureContext()` for + * further information. * @since v0.11.13 */ let DEFAULT_ECDH_CURVE: string; diff --git a/types/node/v24/ts5.6/buffer.buffer.d.ts b/types/node/v24/ts5.6/buffer.buffer.d.ts index a5f67d7c9306ed..012a30262ba8d0 100644 --- a/types/node/v24/ts5.6/buffer.buffer.d.ts +++ b/types/node/v24/ts5.6/buffer.buffer.d.ts @@ -465,4 +465,9 @@ declare module "buffer" { new(size: number): Buffer; prototype: Buffer; }; + /** + * @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports + * TypeScript versions earlier than 5.7. + */ + type BufferView = Buffer; } diff --git a/types/node/v24/tty.d.ts b/types/node/v24/tty.d.ts index 602324ab905f2d..d6e28322367a11 100644 --- a/types/node/v24/tty.d.ts +++ b/types/node/v24/tty.d.ts @@ -53,10 +53,11 @@ declare module "tty" { * Allows configuration of `tty.ReadStream` so that it operates as a raw device. * * When in raw mode, input is always available character-by-character, not - * including modifiers. Additionally, all special processing of characters by the - * terminal is disabled, including echoing input + * including modifiers. Additionally, all special processing of input characters + * by the terminal is disabled, including echoing input * characters. Ctrl+C will no longer cause a `SIGINT` when - * in this mode. + * in this mode. This mode does not affect terminal output processing, such as + * newline translation on Unix terminals. * @since v0.7.7 * @param mode If `true`, configures the `tty.ReadStream` to operate as a raw device. If `false`, configures the `tty.ReadStream` to operate in its default mode. The `readStream.isRaw` * property will be set to the resulting mode. diff --git a/types/node/v24/url.d.ts b/types/node/v24/url.d.ts index abf5796c5c5017..262066030b1029 100644 --- a/types/node/v24/url.d.ts +++ b/types/node/v24/url.d.ts @@ -238,9 +238,31 @@ declare module "url" { * * `result` is returned. * @since v0.1.25 * @legacy Use the WHATWG URL API instead. - * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). */ - function format(urlObject: UrlObject | string): string; + function format(urlObject: UrlObject): string; + /** + * `url.format(urlString)` is shorthand for `url.format(url.parse(urlString))`. + * + * Because it invokes the deprecated `url.parse()` internally, passing a string argument + * to `url.format()` is itself deprecated. + * + * Canonicalizing a URL string can be performed using the WHATWG URL API, by + * constructing a new URL object and calling `url.toString()`. + * + * ```js + * import { URL } from 'node:url'; + * + * const unformatted = 'http://[fe80:0:0:0:0:0:0:1]:/a/b?a=b#abc'; + * const formatted = new URL(unformatted).toString(); + * + * console.log(formatted); // Prints: http://[fe80::1]/a/b?a=b#abc + * ``` + * @since v0.1.25 + * @deprecated Use the WHATWG URL API instead. + * @param urlString A string that will be passed to `url.parse()` and then formatted. + */ + function format(urlString: string): string; /** * The `url.resolve()` method resolves a target URL relative to a base URL in a * manner similar to that of a web browser resolving an anchor tag. @@ -252,6 +274,8 @@ declare module "url" { * url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' * ``` * + * Because it invokes the deprecated `url.parse()` internally, `url.resolve()` is itself deprecated. + * * To achieve the same result using the WHATWG URL API: * * ```js @@ -270,7 +294,7 @@ declare module "url" { * resolve('http://example.com/one', '/two'); // 'http://example.com/two' * ``` * @since v0.1.25 - * @legacy Use the WHATWG URL API instead. + * @deprecated Use the WHATWG URL API instead. * @param from The base URL to use if `to` is a relative URL. * @param to The target URL to resolve. */ diff --git a/types/node/v24/util.d.ts b/types/node/v24/util.d.ts index 304d44ff143a56..58c884b5cc6088 100644 --- a/types/node/v24/util.d.ts +++ b/types/node/v24/util.d.ts @@ -707,6 +707,28 @@ declare module "util" { * @legacy Use ES2015 class syntax and `extends` keyword instead. */ export function inherits(constructor: unknown, superConstructor: unknown): void; + /** + * The `util.convertProcessSignalToExitCode()` method converts a signal name to its + * corresponding POSIX exit code. Following the POSIX standard, the exit code + * for a process terminated by a signal is calculated as `128 + signal number`. + * + * If `signal` is not a valid signal name, then an error will be thrown. See + * [`signal(7)`](https://man7.org/linux/man-pages/man7/signal.7.html) for a list of valid signals. + * + * ```js + * import { convertProcessSignalToExitCode } from 'node:util'; + * + * console.log(convertProcessSignalToExitCode('SIGTERM')); // 143 (128 + 15) + * console.log(convertProcessSignalToExitCode('SIGKILL')); // 137 (128 + 9) + * ``` + * + * This is particularly useful when working with processes to determine + * the exit code based on the signal that terminated the process. + * @since v24.14.0 + * @param signal A signal name (e.g. `'SIGTERM'`) + * @returns The exit code corresponding to `signal` + */ + export function convertProcessSignalToExitCode(signal: NodeJS.Signals): number; export type DebugLoggerFunction = (msg: string, ...param: unknown[]) => void; export interface DebugLogger extends DebugLoggerFunction { /** @@ -929,6 +951,8 @@ declare module "util" { * `reason`. * * ```js + * import util from 'node:util'; + * * function fn() { * return Promise.reject(null); * } @@ -1256,8 +1280,23 @@ declare module "util" { * * The special format value `none` applies no additional styling to the text. * + * In addition to predefined color names, `util.styleText()` supports hex color + * strings using ANSI TrueColor (24-bit) escape sequences. Hex colors can be + * specified in either 3-digit (`#RGB`) or 6-digit (`#RRGGBB`) format: + * + * ```js + * import { styleText } from 'node:util'; + * + * // 6-digit hex color + * console.log(styleText('#ff5733', 'Orange text')); + * + * // 3-digit hex color (shorthand) + * console.log(styleText('#f00', 'Red text')); + * ``` + * * The full list of formats can be found in [modifiers](https://nodejs.org/docs/latest-v24.x/api/util.html#modifiers). - * @param format A text format or an Array of text formats defined in `util.inspect.colors`. + * @param format A text format or an Array of text formats defined in `util.inspect.colors`, or a hex color in `#RGB` + * or `#RRGGBB` form. * @param text The text to to be formatted. * @since v20.12.0 */ @@ -1266,7 +1305,8 @@ declare module "util" { | ForegroundColors | BackgroundColors | Modifiers - | Array, + | Array + | `#${string}`, text: string, options?: StyleTextOptions, ): string; diff --git a/types/node/v24/v8.d.ts b/types/node/v24/v8.d.ts index e57f970d8fb5ea..3cc78e200f33a4 100644 --- a/types/node/v24/v8.d.ts +++ b/types/node/v24/v8.d.ts @@ -71,7 +71,37 @@ declare module "v8" { /** * Returns an object with the following properties: * - * `does_zap_garbage` is a 0/1 boolean, which signifies whether the `--zap_code_space` option is enabled or not. This makes V8 overwrite heap + * `total_heap_size` The value of total\_heap\_size is the number of bytes V8 has + * allocated for the heap. This can grow if used\_heap needs more memory. + * + * `total_heap_size_executable` The value of total\_heap\_size\_executable is the + * portion of the heap that can contain executable code, in bytes. This includes + * memory used by JIT-compiled code and any memory that must be kept executable. + * + * `total_physical_size` The value of total\_physical\_size is the actual physical memory + * used by the V8 heap, in bytes. This is the amount of memory that is committed + * (or in use) rather than reserved. + * + * `total_available_size` The value of total\_available\_size is the number of + * bytes of memory available to the V8 heap. This value represents how much + * more memory V8 can use before it exceeds the heap limit. + * + * `used_heap_size` The value of used\_heap\_size is number of bytes currently + * being used by V8’s JavaScript objects. This is the actual memory in use and + * does not include memory that has been allocated but not yet used. + * + * `heap_size_limit` The value of heap\_size\_limit is the maximum size of the V8 + * heap, in bytes (either the default limit, determined by system resources, or + * the value passed to the `--max_old_space_size` option). + * + * `malloced_memory` The value of malloced\_memory is the number of bytes allocated + * through `malloc` by V8. + * + * `peak_malloced_memory` The value of peak\_malloced\_memory is the peak number of + * bytes allocated through `malloc` by V8 during the lifetime of the process. + * + * `does_zap_garbage` is a 0/1 boolean, which signifies whether the + * `--zap_code_space` option is enabled or not. This makes V8 overwrite heap * garbage with a bit pattern. The RSS footprint (resident set size) gets bigger * because it continuously touches all heap pages and that makes them less likely * to get swapped out by the operating system. @@ -93,22 +123,22 @@ declare module "v8" { * `external_memory` The value of external\_memory is the memory size of array * buffers and external strings. * - * ```js + * ```json * { - * total_heap_size: 7326976, - * total_heap_size_executable: 4194304, - * total_physical_size: 7326976, - * total_available_size: 1152656, - * used_heap_size: 3476208, - * heap_size_limit: 1535115264, - * malloced_memory: 16384, - * peak_malloced_memory: 1127496, - * does_zap_garbage: 0, - * number_of_native_contexts: 1, - * number_of_detached_contexts: 0, - * total_global_handles_size: 8192, - * used_global_handles_size: 3296, - * external_memory: 318824 + * "total_heap_size": 7326976, + * "total_heap_size_executable": 4194304, + * "total_physical_size": 7326976, + * "total_available_size": 1152656, + * "used_heap_size": 3476208, + * "heap_size_limit": 1535115264, + * "malloced_memory": 16384, + * "peak_malloced_memory": 1127496, + * "does_zap_garbage": 0, + * "number_of_native_contexts": 1, + * "number_of_detached_contexts": 0, + * "total_global_handles_size": 8192, + * "used_global_handles_size": 3296, + * "external_memory": 318824 * } * ``` * @since v1.0.0 @@ -389,12 +419,12 @@ declare module "v8" { * V8 [`GetHeapCodeAndMetadataStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#a6079122af17612ef54ef3348ce170866) API. Returns an object with the * following properties: * - * ```js + * ```json * { - * code_and_metadata_size: 212208, - * bytecode_and_metadata_size: 161368, - * external_script_source_size: 1410794, - * cpu_profiler_metadata_size: 0, + * "code_and_metadata_size": 212208, + * "bytecode_and_metadata_size": 161368, + * "external_script_source_size": 1410794, + * "cpu_profiler_metadata_size": 0 * } * ``` * @since v12.8.0 @@ -883,8 +913,6 @@ declare module "v8" { * For example, if the `entry.js` contains the following script: * * ```js - * 'use strict'; - * * import fs from 'node:fs'; * import zlib from 'node:zlib'; * import path from 'node:path'; diff --git a/types/node/v24/vm.d.ts b/types/node/v24/vm.d.ts index e56db1f581e040..d088defd95ccef 100644 --- a/types/node/v24/vm.d.ts +++ b/types/node/v24/vm.d.ts @@ -238,16 +238,16 @@ declare module "vm" { * The globals are contained in the `context` object. * * ```js - * import vm from 'node:vm'; + * import { createContext, Script } from 'node:vm'; * * const context = { * animal: 'cat', * count: 2, * }; * - * const script = new vm.Script('count += 1; name = "kitty";'); + * const script = new Script('count += 1; name = "kitty";'); * - * vm.createContext(context); + * createContext(context); * for (let i = 0; i < 10; ++i) { * script.runInContext(context); * } @@ -281,9 +281,9 @@ declare module "vm" { * contained within each individual `context`. * * ```js - * const vm = require('node:vm'); + * import { constants, Script } from 'node:vm'; * - * const script = new vm.Script('globalVar = "set"'); + * const script = new Script('globalVar = "set"'); * * const contexts = [{}, {}, {}]; * contexts.forEach((context) => { @@ -294,10 +294,10 @@ declare module "vm" { * // Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }] * * // This would throw if the context is created from a contextified object. - * // vm.constants.DONT_CONTEXTIFY allows creating contexts with ordinary + * // constants.DONT_CONTEXTIFY allows creating contexts with ordinary * // global objects that can be frozen. - * const freezeScript = new vm.Script('Object.freeze(globalThis); globalThis;'); - * const frozenContext = freezeScript.runInNewContext(vm.constants.DONT_CONTEXTIFY); + * const freezeScript = new Script('Object.freeze(globalThis); globalThis;'); + * const frozenContext = freezeScript.runInNewContext(constants.DONT_CONTEXTIFY); * ``` * @since v0.3.1 * @param contextObject Either `vm.constants.DONT_CONTEXTIFY` or an object that will be contextified. @@ -316,11 +316,11 @@ declare module "vm" { * executes that code multiple times: * * ```js - * import vm from 'node:vm'; + * import { Script } from 'node:vm'; * * global.globalVar = 0; * - * const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' }); + * const script = new Script('globalVar += 1', { filename: 'myfile.vm' }); * * for (let i = 0; i < 1000; ++i) { * script.runInThisContext(); @@ -409,14 +409,14 @@ declare module "vm" { * variables will remain unchanged. * * ```js - * const vm = require('node:vm'); + * import { createContext, runInContext } from 'node:vm'; * * global.globalVar = 3; * * const context = { globalVar: 1 }; - * vm.createContext(context); + * createContext(context); * - * vm.runInContext('globalVar *= 2;', context); + * runInContext('globalVar *= 2;', context); * * console.log(context); * // Prints: { globalVar: 2 } @@ -467,13 +467,13 @@ declare module "vm" { * The following example compiles and executes different scripts using a single `contextified` object: * * ```js - * import vm from 'node:vm'; + * import { createContext, runInContext } from 'node:vm'; * * const contextObject = { globalVar: 1 }; - * vm.createContext(contextObject); + * createContext(contextObject); * * for (let i = 0; i < 10; ++i) { - * vm.runInContext('globalVar *= 2;', contextObject); + * runInContext('globalVar *= 2;', contextObject); * } * console.log(contextObject); * // Prints: { globalVar: 1024 } @@ -504,21 +504,24 @@ declare module "vm" { * variable and sets a new one. These globals are contained in the `contextObject`. * * ```js - * const vm = require('node:vm'); + * import { runInNewContext, constants } from 'node:vm'; * * const contextObject = { * animal: 'cat', * count: 2, * }; * - * vm.runInNewContext('count += 1; name = "kitty"', contextObject); + * runInNewContext('count += 1; name = "kitty"', contextObject); * console.log(contextObject); * // Prints: { animal: 'cat', count: 3, name: 'kitty' } * * // This would throw if the context is created from a contextified object. * // vm.constants.DONT_CONTEXTIFY allows creating contexts with ordinary global objects that * // can be frozen. - * const frozenContext = vm.runInNewContext('Object.freeze(globalThis); globalThis;', vm.constants.DONT_CONTEXTIFY); + * const frozenContext = runInNewContext( + * 'Object.freeze(globalThis); globalThis;', + * constants.DONT_CONTEXTIFY, + * ); * ``` * @since v0.3.1 * @param code The JavaScript code to compile and run. @@ -542,10 +545,10 @@ declare module "vm" { * the JavaScript [`eval()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) function to run the same code: * * ```js - * import vm from 'node:vm'; + * import { runInThisContext } from 'node:vm'; * let localVar = 'initial value'; * - * const vmResult = vm.runInThisContext('localVar = "vm";'); + * const vmResult = runInThisContext('localVar = "vm";'); * console.log(`vmResult: '${vmResult}', localVar: '${localVar}'`); * // Prints: vmResult: 'vm', localVar: 'initial value' * @@ -557,38 +560,6 @@ declare module "vm" { * Because `vm.runInThisContext()` does not have access to the local scope, `localVar` is unchanged. In contrast, * [`eval()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval) _does_ have access to the * local scope, so the value `localVar` is changed. In this way `vm.runInThisContext()` is much like an [indirect `eval()` call](https://es5.github.io/#x10.4.2), e.g.`(0,eval)('code')`. - * - * ## Example: Running an HTTP server within a VM - * - * When using either `script.runInThisContext()` or {@link runInThisContext}, the code is executed within the current V8 global - * context. The code passed to this VM context will have its own isolated scope. - * - * In order to run a simple web server using the `node:http` module the code passed - * to the context must either import `node:http` on its own, or have a - * reference to the `node:http` module passed to it. For instance: - * - * ```js - * 'use strict'; - * import vm from 'node:vm'; - * - * const code = ` - * ((require) => { - * const http = require('node:http'); - * - * http.createServer((request, response) => { - * response.writeHead(200, { 'Content-Type': 'text/plain' }); - * response.end('Hello World\\n'); - * }).listen(8124); - * - * console.log('Server running at http://127.0.0.1:8124/'); - * })`; - * - * vm.runInThisContext(code)(require); - * ``` - * - * The `require()` in the above case shares the state with the context it is - * passed from. This may introduce risks when untrusted code is executed, e.g. - * altering objects in the context in unwanted ways. * @since v0.3.1 * @param code The JavaScript code to compile and run. * @return the result of the very last statement executed in the script. @@ -620,44 +591,32 @@ declare module "vm" { * the memory occupied by each heap space in the current V8 instance. * * ```js - * import vm from 'node:vm'; + * import { createContext, measureMemory } from 'node:vm'; * // Measure the memory used by the main context. - * vm.measureMemory({ mode: 'summary' }) + * measureMemory({ mode: 'summary' }) * // This is the same as vm.measureMemory() * .then((result) => { * // The current format is: * // { - * // total: { - * // jsMemoryEstimate: 2418479, jsMemoryRange: [ 2418479, 2745799 ] - * // } + * // total: { jsMemoryEstimate: 1601828, jsMemoryRange: [1601828, 5275288] }, + * // WebAssembly: { code: 0, metadata: 33962 }, * // } * console.log(result); * }); * - * const context = vm.createContext({ a: 1 }); - * vm.measureMemory({ mode: 'detailed', execution: 'eager' }) - * .then((result) => { - * // Reference the context here so that it won't be GC'ed - * // until the measurement is complete. - * console.log(context.a); - * // { - * // total: { - * // jsMemoryEstimate: 2574732, - * // jsMemoryRange: [ 2574732, 2904372 ] - * // }, - * // current: { - * // jsMemoryEstimate: 2438996, - * // jsMemoryRange: [ 2438996, 2768636 ] - * // }, - * // other: [ - * // { - * // jsMemoryEstimate: 135736, - * // jsMemoryRange: [ 135736, 465376 ] - * // } - * // ] - * // } - * console.log(result); - * }); + * const context = createContext({ a: 1 }); + * measureMemory({ mode: 'detailed', execution: 'eager' }).then((result) => { + * // Reference the context here so that it won't be GC'ed + * // until the measurement is complete. + * console.log('Context:', context.a); + * // { + * // total: { jsMemoryEstimate: 1767100, jsMemoryRange: [1767100, 5440560] }, + * // WebAssembly: { code: 0, metadata: 33962 }, + * // current: { jsMemoryEstimate: 1601828, jsMemoryRange: [1601828, 5275288] }, + * // other: [{ jsMemoryEstimate: 165272, jsMemoryRange: [Array] }], + * // } + * console.log(result); + * }); * ``` * @since v13.10.0 * @experimental @@ -819,8 +778,8 @@ declare module "vm" { */ status: ModuleStatus; /** - * Evaluate the module and its depenendencies. Corresponds to the [Evaluate() concrete method](https://tc39.es/ecma262/#sec-moduleevaluation) - * field of [Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records)s in the ECMAScript specification. + * Evaluate the module and its dependencies. Corresponds to the [Evaluate() concrete method](https://tc39.es/ecma262/#sec-moduleevaluation) field of + * [Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records)s in the ECMAScript specification. * * If the module is a `vm.SourceTextModule`, `evaluate()` must be called after the module has been instantiated; * otherwise `evaluate()` will return a rejected promise. @@ -1117,15 +1076,21 @@ declare module "vm" { * module graphs. * * ```js - * import vm from 'node:vm'; + * import { SyntheticModule } from 'node:vm'; * * const source = '{ "a": 1 }'; - * const module = new vm.SyntheticModule(['default'], function() { + * const syntheticModule = new SyntheticModule(['default'], function() { * const obj = JSON.parse(source); * this.setExport('default', obj); * }); * - * // Use `module` in linking... + * // Use `syntheticModule` in linking + * (async () => { + * await syntheticModule.link(() => {}); + * await syntheticModule.evaluate(); + * + * console.log('Default export:', syntheticModule.namespace.default); + * })(); * ``` * @since v13.0.0, v12.16.0 * @experimental diff --git a/types/node/v24/zlib.d.ts b/types/node/v24/zlib.d.ts index d73af0435a24f1..51316318fe7b1b 100644 --- a/types/node/v24/zlib.d.ts +++ b/types/node/v24/zlib.d.ts @@ -125,6 +125,13 @@ declare module "zlib" { * @default buffer.kMaxLength */ maxOutputLength?: number | undefined; + /** + * If `true`, decompression fails when + * trailing input is detected after the end of the compressed stream. This + * includes unreadable bytes and, when decompressing gzip, additional gzip + * members following the first member. **Default:** `false` + */ + rejectGarbageAfterEnd?: boolean | undefined; } interface BrotliOptions { /** @@ -156,6 +163,11 @@ declare module "zlib" { * If `true`, returns an object with `buffer` and `engine`. */ info?: boolean | undefined; + /** + * If `true`, decompression fails when + * input remains after the first complete compressed stream. **Default:** `false` + */ + rejectGarbageAfterEnd?: boolean | undefined; } interface ZstdOptions { /** @@ -191,6 +203,11 @@ declare module "zlib" { * @since v24.6.0 */ dictionary?: NodeJS.ArrayBufferView | undefined; + /** + * If `true`, decompression fails when + * input remains after the first complete compressed stream. **Default:** `false` + */ + rejectGarbageAfterEnd?: boolean | undefined; } interface Zlib { readonly bytesWritten: number; diff --git a/types/office-js-preview/index.d.ts b/types/office-js-preview/index.d.ts index 9118bec253c5a6..bff5c6d5656424 100644 --- a/types/office-js-preview/index.d.ts +++ b/types/office-js-preview/index.d.ts @@ -11194,7 +11194,7 @@ declare namespace Office { * **Important**: To use the sensitivity label feature in your add-in, you must have a Microsoft 365 E5 subscription. * * To learn more about how to manage sensitivity labels in your add-in, see - * {@link https://learn.microsoft.com/office/dev/add-ins/outlook/sensitivity-label | Manage the sensitivity label of your message or appointment in compose mode}. + * {@link https://learn.microsoft.com/office/dev/add-ins/develop/sensitivity-label | Manage sensitivity labels in Office Add-ins}. */ sensitivityLabel: SensitivityLabel; /** @@ -16586,7 +16586,7 @@ declare namespace Office { * - Only the `getAsync` method of the SensitivityLabel object is supported. * * To learn more about how to manage sensitivity labels in your add-in, see - * {@link https://learn.microsoft.com/office/dev/add-ins/outlook/sensitivity-label | Manage the sensitivity label of your message or appointment in compose mode}. + * {@link https://learn.microsoft.com/office/dev/add-ins/develop/sensitivity-label | Manage sensitivity labels in Office Add-ins}. */ sensitivityLabel: SensitivityLabel; /** @@ -20040,7 +20040,7 @@ declare namespace Office { * **Important**: To use the sensitivity label feature in your add-in, you must have a Microsoft 365 E5 subscription. * * To learn more about how to manage sensitivity labels in your add-in, see - * {@link https://learn.microsoft.com/office/dev/add-ins/outlook/sensitivity-label | Manage the sensitivity label of your message or appointment in compose mode}. + * {@link https://learn.microsoft.com/office/dev/add-ins/develop/sensitivity-label | Manage sensitivity labels in Office Add-ins}. */ sensitivityLabel: SensitivityLabel; /** @@ -24645,7 +24645,7 @@ declare namespace Office { * **Important**: To use the sensitivity label feature in your add-in, you must have a Microsoft 365 E5 subscription. * * To learn more about how to manage sensitivity labels in your add-in, see - * {@link https://learn.microsoft.com/office/dev/add-ins/outlook/sensitivity-label | Manage the sensitivity label of your message or appointment in compose mode}. + * {@link https://learn.microsoft.com/office/dev/add-ins/develop/sensitivity-label | Manage sensitivity labels in Office Add-ins}. */ interface SensitivityLabel { /** @@ -24661,7 +24661,7 @@ declare namespace Office { * **Important**: To use the sensitivity label feature in your add-in, you must have a Microsoft 365 E5 subscription. * * To learn more about how to manage sensitivity labels in your add-in, see - * {@link https://learn.microsoft.com/office/dev/add-ins/outlook/sensitivity-label | Manage the sensitivity label of your message or appointment in compose mode}. + * {@link https://learn.microsoft.com/office/dev/add-ins/develop/sensitivity-label | Manage sensitivity labels in Office Add-ins}. * * @param options - An object literal that contains one or more of the following properties:- * `asyncContext`: Developers can provide any object they wish to access in the callback function. @@ -24683,7 +24683,7 @@ declare namespace Office { * **Important**: To use the sensitivity label feature in your add-in, you must have a Microsoft 365 E5 subscription. * * To learn more about how to manage sensitivity labels in your add-in, see - * {@link https://learn.microsoft.com/office/dev/add-ins/outlook/sensitivity-label | Manage the sensitivity label of your message or appointment in compose mode}. + * {@link https://learn.microsoft.com/office/dev/add-ins/develop/sensitivity-label | Manage sensitivity labels in Office Add-ins}. * * @param callback - When the method completes, the function passed in the `callback` parameter is called with a single parameter, `asyncResult`, * which is an `Office.AsyncResult` object. The sensitivity label's GUID is returned in the @@ -24710,7 +24710,7 @@ declare namespace Office { * **Tip**: To determine the sensitivity labels available for use, call the `Office.context.sensitivityLabelsCatalog.getAsync` method. * * To learn more about how to manage sensitivity labels in your add-in, see - * {@link https://learn.microsoft.com/office/dev/add-ins/outlook/sensitivity-label | Manage the sensitivity label of your message or appointment in compose mode}. + * {@link https://learn.microsoft.com/office/dev/add-ins/develop/sensitivity-label | Manage sensitivity labels in Office Add-ins}. * * @param sensitivityLabel - The sensitivity label to be applied to the message or appointment being composed. The parameter value can be a sensitivity label's * unique identifier (GUID) or a {@link Office.SensitivityLabelDetails | SensitivityLabelDetails} object. @@ -24740,7 +24740,7 @@ declare namespace Office { * **Tip**: To determine the sensitivity labels available for use, call the `Office.context.sensitivityLabelsCatalog.getAsync` method. * * To learn more about how to manage sensitivity labels in your add-in, see - * {@link https://learn.microsoft.com/office/dev/add-ins/outlook/sensitivity-label | Manage the sensitivity label of your message or appointment in compose mode}. + * {@link https://learn.microsoft.com/office/dev/add-ins/develop/sensitivity-label | Manage sensitivity labels in Office Add-ins}. * * @param sensitivityLabel - The sensitivity label to be applied to the message or appointment being composed. The parameter value can be a sensitivity label's * unique identifier (GUID) or a {@link Office.SensitivityLabelDetails | SensitivityLabelDetails} object. @@ -24759,7 +24759,7 @@ declare namespace Office { * **Important**: To use the sensitivity label feature in your add-in, you must have a Microsoft 365 E5 subscription. * * To learn more about how to manage sensitivity labels in your add-in, see - * {@link https://learn.microsoft.com/office/dev/add-ins/outlook/sensitivity-label | Manage the sensitivity label of your message or appointment in compose mode}. + * {@link https://learn.microsoft.com/office/dev/add-ins/develop/sensitivity-label | Manage sensitivity labels in Office Add-ins}. */ export interface SensitivityLabelChangedEventArgs { /** @@ -24783,7 +24783,7 @@ declare namespace Office { * **Important**: To use the sensitivity label feature in your add-in, you must have a Microsoft 365 E5 subscription. * * To learn more about how to manage sensitivity labels in your add-in, see - * {@link https://learn.microsoft.com/office/dev/add-ins/outlook/sensitivity-label | Manage the sensitivity label of your message or appointment in compose mode}. + * {@link https://learn.microsoft.com/office/dev/add-ins/develop/sensitivity-label | Manage sensitivity labels in Office Add-ins}. */ interface SensitivityLabelDetails { /** @@ -24822,7 +24822,7 @@ declare namespace Office { * **Important**: To use the sensitivity label feature in your add-in, you must have a Microsoft 365 E5 subscription. * * To learn more about how to manage sensitivity labels in your add-in, see - * {@link https://learn.microsoft.com/office/dev/add-ins/outlook/sensitivity-label | Manage the sensitivity label of your message or appointment in compose mode}. + * {@link https://learn.microsoft.com/office/dev/add-ins/develop/sensitivity-label | Manage sensitivity labels in Office Add-ins}. */ export interface SensitivityLabelsCatalog { /** @@ -24840,7 +24840,7 @@ declare namespace Office { * **Recommended**: To determine whether the catalog of sensitivity labels is enabled in Outlook, call `getIsEnabledAsync` before using `getAsync`. * * To learn more about how to manage sensitivity labels in your add-in, see - * {@link https://learn.microsoft.com/office/dev/add-ins/outlook/sensitivity-label | Manage the sensitivity label of your message or appointment in compose mode}. + * {@link https://learn.microsoft.com/office/dev/add-ins/develop/sensitivity-label | Manage sensitivity labels in Office Add-ins}. * * @param options - An object literal that contains one or more of the following properties:- * `asyncContext`: Developers can provide any object they wish to access in the callback function. @@ -24864,7 +24864,7 @@ declare namespace Office { * **Recommended**: To determine whether the catalog of sensitivity labels is enabled in Outlook, call `getIsEnabledAsync` before using `getAsync`. * * To learn more about how to manage sensitivity labels in your add-in, see - * {@link https://learn.microsoft.com/office/dev/add-ins/outlook/sensitivity-label | Manage the sensitivity label of your message or appointment in compose mode}. + * {@link https://learn.microsoft.com/office/dev/add-ins/develop/sensitivity-label | Manage sensitivity labels in Office Add-ins}. * * @param callback - When the method completes, the function passed in the `callback` parameter is called with a single parameter, `asyncResult`, * which is an `Office.AsyncResult` object. The available sensitivity labels and their properties are returned in the @@ -24887,7 +24887,7 @@ declare namespace Office { * **Important**: To use the sensitivity label feature in your add-in, you must have a Microsoft 365 E5 subscription. * * To learn more about how to manage sensitivity labels in your add-in, see - * {@link https://learn.microsoft.com/office/dev/add-ins/outlook/sensitivity-label | Manage the sensitivity label of your message or appointment in compose mode}. + * {@link https://learn.microsoft.com/office/dev/add-ins/develop/sensitivity-label | Manage sensitivity labels in Office Add-ins}. * * @param options - An object literal that contains one or more of the following properties:- * `asyncContext`: Developers can provide any object they wish to access in the callback function. @@ -24911,7 +24911,7 @@ declare namespace Office { * **Important**: To use the sensitivity label feature in your add-in, you must have a Microsoft 365 E5 subscription. * * To learn more about how to manage sensitivity labels in your add-in, see - * {@link https://learn.microsoft.com/office/dev/add-ins/outlook/sensitivity-label | Manage the sensitivity label of your message or appointment in compose mode}. + * {@link https://learn.microsoft.com/office/dev/add-ins/develop/sensitivity-label | Manage sensitivity labels in Office Add-ins}. * * @param callback - When the method completes, the function passed in the `callback` parameter is called with a single parameter, `asyncResult`, * which is an `Office.AsyncResult` object. The status of the catalog of sensitivity labels is returned in the `asyncResult.value` property. diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 3846ee5ba9beee..1fb44bc072ae14 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -11123,7 +11123,7 @@ declare namespace Office { * **Important**: To use the sensitivity label feature in your add-in, you must have a Microsoft 365 E5 subscription. * * To learn more about how to manage sensitivity labels in your add-in, see - * {@link https://learn.microsoft.com/office/dev/add-ins/outlook/sensitivity-label | Manage the sensitivity label of your message or appointment in compose mode}. + * {@link https://learn.microsoft.com/office/dev/add-ins/develop/sensitivity-label | Manage sensitivity labels in Office Add-ins}. */ sensitivityLabel: SensitivityLabel; /** @@ -16315,7 +16315,7 @@ declare namespace Office { * - Only the `getAsync` method of the SensitivityLabel object is supported. * * To learn more about how to manage sensitivity labels in your add-in, see - * {@link https://learn.microsoft.com/office/dev/add-ins/outlook/sensitivity-label | Manage the sensitivity label of your message or appointment in compose mode}. + * {@link https://learn.microsoft.com/office/dev/add-ins/develop/sensitivity-label | Manage sensitivity labels in Office Add-ins}. */ sensitivityLabel: SensitivityLabel; /** @@ -19743,7 +19743,7 @@ declare namespace Office { * **Important**: To use the sensitivity label feature in your add-in, you must have a Microsoft 365 E5 subscription. * * To learn more about how to manage sensitivity labels in your add-in, see - * {@link https://learn.microsoft.com/office/dev/add-ins/outlook/sensitivity-label | Manage the sensitivity label of your message or appointment in compose mode}. + * {@link https://learn.microsoft.com/office/dev/add-ins/develop/sensitivity-label | Manage sensitivity labels in Office Add-ins}. */ sensitivityLabel: SensitivityLabel; /** @@ -24209,7 +24209,7 @@ declare namespace Office { * **Important**: To use the sensitivity label feature in your add-in, you must have a Microsoft 365 E5 subscription. * * To learn more about how to manage sensitivity labels in your add-in, see - * {@link https://learn.microsoft.com/office/dev/add-ins/outlook/sensitivity-label | Manage the sensitivity label of your message or appointment in compose mode}. + * {@link https://learn.microsoft.com/office/dev/add-ins/develop/sensitivity-label | Manage sensitivity labels in Office Add-ins}. */ interface SensitivityLabel { /** @@ -24225,7 +24225,7 @@ declare namespace Office { * **Important**: To use the sensitivity label feature in your add-in, you must have a Microsoft 365 E5 subscription. * * To learn more about how to manage sensitivity labels in your add-in, see - * {@link https://learn.microsoft.com/office/dev/add-ins/outlook/sensitivity-label | Manage the sensitivity label of your message or appointment in compose mode}. + * {@link https://learn.microsoft.com/office/dev/add-ins/develop/sensitivity-label | Manage sensitivity labels in Office Add-ins}. * * @param options - An object literal that contains one or more of the following properties:- * `asyncContext`: Developers can provide any object they wish to access in the callback function. @@ -24247,7 +24247,7 @@ declare namespace Office { * **Important**: To use the sensitivity label feature in your add-in, you must have a Microsoft 365 E5 subscription. * * To learn more about how to manage sensitivity labels in your add-in, see - * {@link https://learn.microsoft.com/office/dev/add-ins/outlook/sensitivity-label | Manage the sensitivity label of your message or appointment in compose mode}. + * {@link https://learn.microsoft.com/office/dev/add-ins/develop/sensitivity-label | Manage sensitivity labels in Office Add-ins}. * * @param callback - When the method completes, the function passed in the `callback` parameter is called with a single parameter, `asyncResult`, * which is an `Office.AsyncResult` object. The sensitivity label's GUID is returned in the @@ -24274,7 +24274,7 @@ declare namespace Office { * **Tip**: To determine the sensitivity labels available for use, call the `Office.context.sensitivityLabelsCatalog.getAsync` method. * * To learn more about how to manage sensitivity labels in your add-in, see - * {@link https://learn.microsoft.com/office/dev/add-ins/outlook/sensitivity-label | Manage the sensitivity label of your message or appointment in compose mode}. + * {@link https://learn.microsoft.com/office/dev/add-ins/develop/sensitivity-label | Manage sensitivity labels in Office Add-ins}. * * @param sensitivityLabel - The sensitivity label to be applied to the message or appointment being composed. The parameter value can be a sensitivity label's * unique identifier (GUID) or a {@link Office.SensitivityLabelDetails | SensitivityLabelDetails} object. @@ -24304,7 +24304,7 @@ declare namespace Office { * **Tip**: To determine the sensitivity labels available for use, call the `Office.context.sensitivityLabelsCatalog.getAsync` method. * * To learn more about how to manage sensitivity labels in your add-in, see - * {@link https://learn.microsoft.com/office/dev/add-ins/outlook/sensitivity-label | Manage the sensitivity label of your message or appointment in compose mode}. + * {@link https://learn.microsoft.com/office/dev/add-ins/develop/sensitivity-label | Manage sensitivity labels in Office Add-ins}. * * @param sensitivityLabel - The sensitivity label to be applied to the message or appointment being composed. The parameter value can be a sensitivity label's * unique identifier (GUID) or a {@link Office.SensitivityLabelDetails | SensitivityLabelDetails} object. @@ -24323,7 +24323,7 @@ declare namespace Office { * **Important**: To use the sensitivity label feature in your add-in, you must have a Microsoft 365 E5 subscription. * * To learn more about how to manage sensitivity labels in your add-in, see - * {@link https://learn.microsoft.com/office/dev/add-ins/outlook/sensitivity-label | Manage the sensitivity label of your message or appointment in compose mode}. + * {@link https://learn.microsoft.com/office/dev/add-ins/develop/sensitivity-label | Manage sensitivity labels in Office Add-ins}. */ export interface SensitivityLabelChangedEventArgs { /** @@ -24347,7 +24347,7 @@ declare namespace Office { * **Important**: To use the sensitivity label feature in your add-in, you must have a Microsoft 365 E5 subscription. * * To learn more about how to manage sensitivity labels in your add-in, see - * {@link https://learn.microsoft.com/office/dev/add-ins/outlook/sensitivity-label | Manage the sensitivity label of your message or appointment in compose mode}. + * {@link https://learn.microsoft.com/office/dev/add-ins/develop/sensitivity-label | Manage sensitivity labels in Office Add-ins}. */ interface SensitivityLabelDetails { /** @@ -24386,7 +24386,7 @@ declare namespace Office { * **Important**: To use the sensitivity label feature in your add-in, you must have a Microsoft 365 E5 subscription. * * To learn more about how to manage sensitivity labels in your add-in, see - * {@link https://learn.microsoft.com/office/dev/add-ins/outlook/sensitivity-label | Manage the sensitivity label of your message or appointment in compose mode}. + * {@link https://learn.microsoft.com/office/dev/add-ins/develop/sensitivity-label | Manage sensitivity labels in Office Add-ins}. */ export interface SensitivityLabelsCatalog { /** @@ -24404,7 +24404,7 @@ declare namespace Office { * **Recommended**: To determine whether the catalog of sensitivity labels is enabled in Outlook, call `getIsEnabledAsync` before using `getAsync`. * * To learn more about how to manage sensitivity labels in your add-in, see - * {@link https://learn.microsoft.com/office/dev/add-ins/outlook/sensitivity-label | Manage the sensitivity label of your message or appointment in compose mode}. + * {@link https://learn.microsoft.com/office/dev/add-ins/develop/sensitivity-label | Manage sensitivity labels in Office Add-ins}. * * @param options - An object literal that contains one or more of the following properties:- * `asyncContext`: Developers can provide any object they wish to access in the callback function. @@ -24428,7 +24428,7 @@ declare namespace Office { * **Recommended**: To determine whether the catalog of sensitivity labels is enabled in Outlook, call `getIsEnabledAsync` before using `getAsync`. * * To learn more about how to manage sensitivity labels in your add-in, see - * {@link https://learn.microsoft.com/office/dev/add-ins/outlook/sensitivity-label | Manage the sensitivity label of your message or appointment in compose mode}. + * {@link https://learn.microsoft.com/office/dev/add-ins/develop/sensitivity-label | Manage sensitivity labels in Office Add-ins}. * * @param callback - When the method completes, the function passed in the `callback` parameter is called with a single parameter, `asyncResult`, * which is an `Office.AsyncResult` object. The available sensitivity labels and their properties are returned in the @@ -24451,7 +24451,7 @@ declare namespace Office { * **Important**: To use the sensitivity label feature in your add-in, you must have a Microsoft 365 E5 subscription. * * To learn more about how to manage sensitivity labels in your add-in, see - * {@link https://learn.microsoft.com/office/dev/add-ins/outlook/sensitivity-label | Manage the sensitivity label of your message or appointment in compose mode}. + * {@link https://learn.microsoft.com/office/dev/add-ins/develop/sensitivity-label | Manage sensitivity labels in Office Add-ins}. * * @param options - An object literal that contains one or more of the following properties:- * `asyncContext`: Developers can provide any object they wish to access in the callback function. @@ -24475,7 +24475,7 @@ declare namespace Office { * **Important**: To use the sensitivity label feature in your add-in, you must have a Microsoft 365 E5 subscription. * * To learn more about how to manage sensitivity labels in your add-in, see - * {@link https://learn.microsoft.com/office/dev/add-ins/outlook/sensitivity-label | Manage the sensitivity label of your message or appointment in compose mode}. + * {@link https://learn.microsoft.com/office/dev/add-ins/develop/sensitivity-label | Manage sensitivity labels in Office Add-ins}. * * @param callback - When the method completes, the function passed in the `callback` parameter is called with a single parameter, `asyncResult`, * which is an `Office.AsyncResult` object. The status of the catalog of sensitivity labels is returned in the `asyncResult.value` property.