From 054e11811ca982a3989fd9da6ffb6f5af38d82ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ren=C3=A9?= Date: Thu, 24 Apr 2025 21:13:41 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=A4=96=20Merge=20PR=20#72580=20[node]=20U?= =?UTF-8?q?pdate=20typings=20to=20v22.15.0=20by=20@Renegade334?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Jacob Smith <3012099+JakobJingleheimer@users.noreply.github.com> --- types/node/assert.d.ts | 55 +------ types/node/async_hooks.d.ts | 2 - types/node/crypto.d.ts | 17 +-- types/node/fs/promises.d.ts | 12 +- types/node/http2.d.ts | 7 +- types/node/inspector.d.ts | 36 +++++ types/node/module.d.ts | 25 +++ types/node/package.json | 2 +- types/node/process.d.ts | 22 +++ types/node/readline.d.ts | 7 +- types/node/sqlite.d.ts | 49 ++++-- types/node/test.d.ts | 60 +++++++- types/node/test/http2.ts | 12 +- types/node/test/module.ts | 3 + types/node/test/process.ts | 10 ++ types/node/test/sqlite.ts | 7 + types/node/test/test.ts | 6 + types/node/test/tls.ts | 2 + types/node/test/util.ts | 9 ++ types/node/test/v8.ts | 1 + types/node/test/zlib.ts | 34 +++++ types/node/tls.d.ts | 25 +++ types/node/util.d.ts | 295 +++++++++++++++++++++++++----------- types/node/v8.d.ts | 81 ++++++++++ types/node/zlib.d.ts | 203 ++++++++++++++++++++----- 25 files changed, 757 insertions(+), 225 deletions(-) diff --git a/types/node/assert.d.ts b/types/node/assert.d.ts index 5a4d61edb38fcd..c340ef66714ae3 100644 --- a/types/node/assert.d.ts +++ b/types/node/assert.d.ts @@ -957,55 +957,14 @@ declare module "assert" { */ function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void; /** - * `assert.partialDeepStrictEqual()` Asserts the equivalence between the `actual` and `expected` parameters through a - * deep comparison, ensuring that all properties in the `expected` parameter are - * present in the `actual` parameter with equivalent values, not allowing type coercion. - * The main difference with `assert.deepStrictEqual()` is that `assert.partialDeepStrictEqual()` does not require - * all properties in the `actual` parameter to be present in the `expected` parameter. - * This method should always pass the same test cases as `assert.deepStrictEqual()`, behaving as a super set of it. - * - * ```js - * import assert from 'node:assert'; - * - * assert.partialDeepStrictEqual({ a: 1, b: 2 }, { a: 1, b: 2 }); - * // OK - * - * assert.partialDeepStrictEqual({ a: { b: { c: 1 } } }, { a: { b: { c: 1 } } }); - * // OK - * - * assert.partialDeepStrictEqual({ a: 1, b: 2, c: 3 }, { a: 1, b: 2 }); - * // OK - * - * assert.partialDeepStrictEqual(new Set(['value1', 'value2']), new Set(['value1', 'value2'])); - * // OK - * - * assert.partialDeepStrictEqual(new Map([['key1', 'value1']]), new Map([['key1', 'value1']])); - * // OK - * - * assert.partialDeepStrictEqual(new Uint8Array([1, 2, 3]), new Uint8Array([1, 2, 3])); - * // OK - * - * assert.partialDeepStrictEqual(/abc/, /abc/); - * // OK - * - * assert.partialDeepStrictEqual([{ a: 5 }, { b: 5 }], [{ a: 5 }]); - * // OK - * - * assert.partialDeepStrictEqual(new Set([{ a: 1 }, { b: 1 }]), new Set([{ a: 1 }])); - * // OK - * - * assert.partialDeepStrictEqual(new Date(0), new Date(0)); - * // OK - * - * assert.partialDeepStrictEqual({ a: 1 }, { a: 1, b: 2 }); - * // AssertionError - * - * assert.partialDeepStrictEqual({ a: 1, b: '2' }, { a: 1, b: 2 }); - * // AssertionError + * Tests for partial deep equality between the `actual` and `expected` parameters. + * "Deep" equality means that the enumerable "own" properties of child objects + * are recursively evaluated also by the following rules. "Partial" equality means + * that only properties that exist on the `expected` parameter are going to be + * compared. * - * assert.partialDeepStrictEqual({ a: { b: 2 } }, { a: { b: '2' } }); - * // AssertionError - * ``` + * This method always passes the same test cases as `assert.deepStrictEqual()`, + * behaving as a super set of it. * @since v22.13.0 */ function partialDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; diff --git a/types/node/async_hooks.d.ts b/types/node/async_hooks.d.ts index 4d6df8150cb297..cffce43d9ea8f1 100644 --- a/types/node/async_hooks.d.ts +++ b/types/node/async_hooks.d.ts @@ -372,7 +372,6 @@ declare module "async_hooks" { /** * Binds the given function to the current execution context. * @since v19.8.0 - * @experimental * @param fn The function to bind to the current execution context. * @return A new function that calls `fn` within the captured execution context. */ @@ -403,7 +402,6 @@ declare module "async_hooks" { * console.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123 * ``` * @since v19.8.0 - * @experimental * @return A new function with the signature `(fn: (...args) : R, ...args) : R`. */ static snapshot(): (fn: (...args: TArgs) => R, ...args: TArgs) => R; diff --git a/types/node/crypto.d.ts b/types/node/crypto.d.ts index facdb06eb62b8f..55f25de1ee642c 100644 --- a/types/node/crypto.d.ts +++ b/types/node/crypto.d.ts @@ -4221,9 +4221,13 @@ declare module "crypto" { * - `'PBKDF2'` * @since v15.0.0 */ - deriveBits(algorithm: EcdhKeyDeriveParams, baseKey: CryptoKey, length: number | null): Promise; deriveBits( - algorithm: AlgorithmIdentifier | HkdfParams | Pbkdf2Params, + algorithm: EcdhKeyDeriveParams, + baseKey: CryptoKey, + length?: number | null, + ): Promise; + deriveBits( + algorithm: EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, length: number, ): Promise; @@ -4245,14 +4249,9 @@ declare module "crypto" { * @since v15.0.0 */ deriveKey( - algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, + algorithm: EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, - derivedKeyAlgorithm: - | AlgorithmIdentifier - | AesDerivedKeyParams - | HmacImportParams - | HkdfParams - | Pbkdf2Params, + derivedKeyAlgorithm: AlgorithmIdentifier | HmacImportParams | AesDerivedKeyParams, extractable: boolean, keyUsages: readonly KeyUsage[], ): Promise; diff --git a/types/node/fs/promises.d.ts b/types/node/fs/promises.d.ts index 2dc296cf780498..870eac0c3500c9 100644 --- a/types/node/fs/promises.d.ts +++ b/types/node/fs/promises.d.ts @@ -87,13 +87,6 @@ declare module "fs/promises" { highWaterMark?: number | undefined; flush?: boolean | undefined; } - interface ReadableWebStreamOptions { - /** - * Whether to open a normal or a `'bytes'` stream. - * @since v20.0.0 - */ - type?: "bytes" | undefined; - } // TODO: Add `EventEmitter` close interface FileHandle { /** @@ -244,7 +237,8 @@ declare module "fs/promises" { ): Promise>; read(options?: FileReadOptions): Promise>; /** - * Returns a `ReadableStream` that may be used to read the files data. + * Returns a byte-oriented `ReadableStream` that may be used to read the file's + * contents. * * An error will be thrown if this method is called more than once or is called * after the `FileHandle` is closed or closing. @@ -267,7 +261,7 @@ declare module "fs/promises" { * @since v17.0.0 * @experimental */ - readableWebStream(options?: ReadableWebStreamOptions): ReadableStream; + readableWebStream(): ReadableStream; /** * Asynchronously reads the entire contents of a file. * diff --git a/types/node/http2.d.ts b/types/node/http2.d.ts index b74e1a6b2d4e84..18b35274e1f647 100644 --- a/types/node/http2.d.ts +++ b/types/node/http2.d.ts @@ -1252,6 +1252,8 @@ declare module "http2" { Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, > extends SessionOptions { + streamResetBurst?: number | undefined; + streamResetRate?: number | undefined; Http1IncomingMessage?: Http1Request | undefined; Http1ServerResponse?: Http1Response | undefined; Http2ServerRequest?: Http2Request | undefined; @@ -1269,10 +1271,7 @@ declare module "http2" { Http1Response extends typeof ServerResponse> = typeof ServerResponse, Http2Request extends typeof Http2ServerRequest = typeof Http2ServerRequest, Http2Response extends typeof Http2ServerResponse> = typeof Http2ServerResponse, - > extends ServerSessionOptions { - streamResetBurst?: number | undefined; - streamResetRate?: number | undefined; - } + > extends ServerSessionOptions {} export interface SecureServerOptions< Http1Request extends typeof IncomingMessage = typeof IncomingMessage, Http1Response extends typeof ServerResponse> = typeof ServerResponse, diff --git a/types/node/inspector.d.ts b/types/node/inspector.d.ts index 32d9ba4aa8b69a..6682448131d2ce 100644 --- a/types/node/inspector.d.ts +++ b/types/node/inspector.d.ts @@ -1720,6 +1720,38 @@ declare module 'inspector' { * Monotonically increasing time in seconds since an arbitrary point in the past. */ type MonotonicTime = number; + /** + * Information about the request initiator. + */ + interface Initiator { + /** + * Type of this initiator. + */ + type: string; + /** + * Initiator JavaScript stack trace, set for Script only. + * Requires the Debugger domain to be enabled. + */ + stack?: Runtime.StackTrace | undefined; + /** + * Initiator URL, set for Parser type or for Script type (when script is importing module) or for SignedExchange type. + */ + url?: string | undefined; + /** + * Initiator line number, set for Parser type or for Script type (when script is importing + * module) (0-based). + */ + lineNumber?: number | undefined; + /** + * Initiator column number, set for Parser type or for Script type (when script is importing + * module) (0-based). + */ + columnNumber?: number | undefined; + /** + * Set if another request triggered this request (e.g. preflight). + */ + requestId?: RequestId | undefined; + } /** * HTTP request data. */ @@ -1751,6 +1783,10 @@ declare module 'inspector' { * Request data. */ request: Request; + /** + * Request initiator. + */ + initiator: Initiator; /** * Timestamp. */ diff --git a/types/node/module.d.ts b/types/node/module.d.ts index a5896661a5b113..9b89fe898e519e 100644 --- a/types/node/module.d.ts +++ b/types/node/module.d.ts @@ -220,6 +220,31 @@ declare module "module" { options?: RegisterOptions, ): void; function register(specifier: string | URL, options?: RegisterOptions): void; + interface RegisterHooksOptions { + /** + * See [load hook](https://nodejs.org/docs/latest-v22.x/api/module.html#loadurl-context-nextload). + * @default undefined + */ + load?: LoadHook | undefined; + /** + * See [resolve hook](https://nodejs.org/docs/latest-v22.x/api/module.html#resolvespecifier-context-nextresolve). + * @default undefined + */ + resolve?: ResolveHook | undefined; + } + interface ModuleHooks { + /** + * Deregister the hook instance. + */ + deregister(): void; + } + /** + * Register [hooks](https://nodejs.org/docs/latest-v22.x/api/module.html#customization-hooks) + * that customize Node.js module resolution and loading behavior. + * @since v22.15.0 + * @experimental + */ + function registerHooks(options: RegisterHooksOptions): ModuleHooks; interface StripTypeScriptTypesOptions { /** * Possible values are: diff --git a/types/node/package.json b/types/node/package.json index be30ab0f4b5553..854ea664df2d8d 100644 --- a/types/node/package.json +++ b/types/node/package.json @@ -1,7 +1,7 @@ { "private": true, "name": "@types/node", - "version": "22.14.9999", + "version": "22.15.9999", "nonNpm": "conflict", "nonNpmDescription": "Node.js", "projects": [ diff --git a/types/node/process.d.ts b/types/node/process.d.ts index 63b6525878620b..10330cf8a7fa8a 100644 --- a/types/node/process.d.ts +++ b/types/node/process.d.ts @@ -1938,6 +1938,28 @@ declare module "process" { * @param maybeRefable An object that may be "unref'd". */ unref(maybeRefable: any): void; + /** + * Replaces the current process with a new process. + * + * This is achieved by using the `execve` POSIX function and therefore no memory or other + * resources from the current process are preserved, except for the standard input, + * standard output and standard error file descriptor. + * + * All other resources are discarded by the system when the processes are swapped, without triggering + * any exit or close events and without running any cleanup handler. + * + * This function will never return, unless an error occurred. + * + * This function is not available on Windows or IBM i. + * @since v22.15.0 + * @experimental + * @param file The name or path of the executable file to run. + * @param args List of string arguments. No argument can contain a null-byte (`\u0000`). + * @param env Environment key-value pairs. + * No key or value can contain a null-byte (`\u0000`). + * **Default:** `process.env`. + */ + execve?(file: string, args?: readonly string[], env?: ProcessEnv): never; /* EventEmitter */ addListener(event: "beforeExit", listener: BeforeExitListener): this; addListener(event: "disconnect", listener: DisconnectListener): this; diff --git a/types/node/readline.d.ts b/types/node/readline.d.ts index a1f304fde77417..338972e78e9481 100644 --- a/types/node/readline.d.ts +++ b/types/node/readline.d.ts @@ -51,7 +51,7 @@ declare module "readline" { * and is read from, the `input` stream. * @since v0.1.104 */ - export class Interface extends EventEmitter { + export class Interface extends EventEmitter implements Disposable { readonly terminal: boolean; /** * The current input data being processed by node. @@ -208,6 +208,11 @@ declare module "readline" { * @since v0.1.98 */ close(): void; + /** + * Alias for `rl.close()`. + * @since v22.15.0 + */ + [Symbol.dispose](): void; /** * The `rl.write()` method will write either `data` or a key sequence identified * by `key` to the `output`. The `key` argument is supported only if `output` is diff --git a/types/node/sqlite.d.ts b/types/node/sqlite.d.ts index 1c05935080033b..af0470be3ab188 100644 --- a/types/node/sqlite.d.ts +++ b/types/node/sqlite.d.ts @@ -158,9 +158,10 @@ declare module "node:sqlite" { */ useBigIntArguments?: boolean | undefined; /** - * If `true`, `function` can accept a variable number of - * arguments. If `false`, `function` must be invoked with exactly - * `function.length` arguments. + * If `true`, `function` may be invoked with any number of + * arguments (between zero and + * [`SQLITE_MAX_FUNCTION_ARG`](https://www.sqlite.org/limits.html#max_function_arg)). If `false`, + * `function` must be invoked with exactly `function.length` arguments. * @default false */ varargs?: boolean | undefined; @@ -170,16 +171,16 @@ declare module "node:sqlite" { * exposed by this class execute synchronously. * @since v22.5.0 */ - class DatabaseSync { + class DatabaseSync implements Disposable { /** * Constructs a new `DatabaseSync` instance. - * @param location The location of the database. + * @param path The path of the database. * A SQLite database can be stored in a file or completely [in memory](https://www.sqlite.org/inmemorydb.html). - * To use a file-backed database, the location should be a file path. - * To use an in-memory database, the location should be the special name `':memory:'`. + * To use a file-backed database, the path should be a file path. + * To use an in-memory database, the path should be the special name `':memory:'`. * @param options Configuration options for the database connection. */ - constructor(location: string, options?: DatabaseSyncOptions); + constructor(path: string | Buffer | URL, options?: DatabaseSyncOptions); /** * Closes the database connection. An exception is thrown if the database is not * open. This method is a wrapper around [`sqlite3_close_v2()`](https://www.sqlite.org/c3ref/close.html). @@ -217,16 +218,24 @@ declare module "node:sqlite" { * @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. + * 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-v22.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: SupportedValueType[]) => SupportedValueType, + func: (...args: SQLOutputValue[]) => SQLInputValue, ): void; - function(name: string, func: (...args: SupportedValueType[]) => SupportedValueType): void; + function(name: string, func: (...args: SQLOutputValue[]) => SQLInputValue): void; /** - * Opens the database specified in the `location` argument of the `DatabaseSync`constructor. This method should only be used when the database is not opened via + * Whether the database is currently open or not. + * @since v22.15.0 + */ + readonly isOpen: boolean; + /** + * 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 */ @@ -272,10 +281,17 @@ declare module "node:sqlite" { * ``` * @param changeset A binary changeset or patchset. * @param options The configuration options for how the changes will be applied. - * @returns Whether the changeset was applied succesfully without being aborted. + * @returns Whether the changeset was applied successfully without being aborted. * @since v22.12.0 */ applyChangeset(changeset: Uint8Array, options?: ApplyChangesetOptions): boolean; + /** + * Closes the database connection. If the database connection is already closed + * then this is a no-op. + * @since v22.15.0 + * @experimental + */ + [Symbol.dispose](): void; } /** * @since v22.12.0 @@ -424,6 +440,13 @@ declare module "node:sqlite" { * @param enabled Enables or disables support for binding named parameters without the prefix character. */ setAllowBareNamedParameters(enabled: boolean): void; + /** + * By default, if an unknown name is encountered while binding parameters, an + * exception is thrown. This method allows unknown named parameters to be ignored. + * @since v22.15.0 + * @param enabled Enables or disables support for unknown named parameters. + */ + setAllowUnknownNamedParameters(enabled: boolean): void; /** * When reading from the database, SQLite `INTEGER`s are mapped to JavaScript * numbers by default. However, SQLite `INTEGER`s can store values larger than diff --git a/types/node/test.d.ts b/types/node/test.d.ts index fc8e72c9b9faf2..a40b9eeb8860f6 100644 --- a/types/node/test.d.ts +++ b/types/node/test.d.ts @@ -648,11 +648,12 @@ declare module "node:test" { */ readonly name: string; /** - * Used to set the number of assertions and subtests that are expected to run within the test. - * If the number of assertions and subtests that run does not match the expected count, the test will fail. + * This function is used to set the number of assertions and subtests that are expected to run + * within the test. If the number of assertions and subtests that run does not match the + * expected count, the test will fail. + * + * > Note: To make sure assertions are tracked, `t.assert` must be used instead of `assert` directly. * - * To make sure assertions are tracked, the assert functions on `context.assert` must be used, - * instead of importing from the `node:assert` module. * ```js * test('top level test', (t) => { * t.plan(2); @@ -661,7 +662,9 @@ declare module "node:test" { * }); * ``` * - * When working with asynchronous code, the `plan` function can be used to ensure that the correct number of assertions are run: + * When working with asynchronous code, the `plan` function can be used to ensure that the + * correct number of assertions are run: + * * ```js * test('planning with streams', (t, done) => { * function* generate() { @@ -675,14 +678,35 @@ declare module "node:test" { * stream.on('data', (chunk) => { * t.assert.strictEqual(chunk, expected.shift()); * }); + * * stream.on('end', () => { * done(); * }); * }); * ``` + * + * When using the `wait` option, you can control how long the test will wait for the expected assertions. + * For example, setting a maximum wait time ensures that the test will wait for asynchronous assertions + * to complete within the specified timeframe: + * + * ```js + * test('plan with wait: 2000 waits for async assertions', (t) => { + * t.plan(1, { wait: 2000 }); // Waits for up to 2 seconds for the assertion to complete. + * + * const asyncActivity = () => { + * setTimeout(() => { + * * t.assert.ok(true, 'Async assertion completed within the wait time'); + * }, 1000); // Completes after 1 second, within the 2-second wait time. + * }; + * + * asyncActivity(); // The test will pass because the assertion is completed in time. + * }); + * ``` + * + * Note: If a `wait` timeout is specified, it begins counting down only after the test function finishes executing. * @since v22.2.0 */ - plan(count: number): void; + plan(count: number, options?: TestContextPlanOptions): void; /** * If `shouldRunOnlyTests` is truthy, the test context will only run tests that * have the `only` option set. Otherwise, all tests are run. If Node.js was not @@ -858,6 +882,20 @@ declare module "node:test" { */ serializers?: ReadonlyArray<(value: any) => any> | undefined; } + interface TestContextPlanOptions { + /** + * The wait time for the plan: + * * If `true`, the plan waits indefinitely for all assertions and subtests to run. + * * If `false`, the plan performs an immediate check after the test function completes, + * without waiting for any pending assertions or subtests. + * Any assertions or subtests that complete after this check will not be counted towards the plan. + * * If a number, it specifies the maximum wait time in milliseconds + * before timing out while waiting for expected assertions and subtests to be matched. + * If the timeout is reached, the test will fail. + * @default false + */ + wait?: boolean | number | undefined; + } interface TestContextWaitForOptions { /** * The number of milliseconds to wait after an unsuccessful @@ -1971,6 +2009,11 @@ interface TestDequeue extends TestLocationInfo { * The nesting level of the test. */ nesting: number; + /** + * The test type. Either `'suite'` or `'test'`. + * @since v22.15.0 + */ + type: "suite" | "test"; } interface TestEnqueue extends TestLocationInfo { /** @@ -1981,6 +2024,11 @@ interface TestEnqueue extends TestLocationInfo { * The nesting level of the test. */ nesting: number; + /** + * The test type. Either `'suite'` or `'test'`. + * @since v22.15.0 + */ + type: "suite" | "test"; } interface TestFail extends TestLocationInfo { /** diff --git a/types/node/test/http2.ts b/types/node/test/http2.ts index 3cfb70e1a71a08..af3e43f4f3a928 100644 --- a/types/node/test/http2.ts +++ b/types/node/test/http2.ts @@ -264,11 +264,11 @@ import { URL } from "node:url"; peerMaxConcurrentStreams: 0, selectPadding: (frameLen: number, maxFrameLen: number) => 0, settings, + streamResetBurst: 1000, + streamResetRate: 33, unknownProtocolTimeout: 123, }; - // tslint:disable-next-line prefer-object-spread (ts2.1 feature) - const secureServerOptions: SecureServerOptions = Object.assign({}, serverOptions); - secureServerOptions.ca = ""; + const secureServerOptions: SecureServerOptions = { ...serverOptions, ca: "..." }; const onRequestHandler = (request: Http2ServerRequest, response: Http2ServerResponse) => { // Http2ServerRequest @@ -384,9 +384,7 @@ import { URL } from "node:url"; selectPadding: (frameLen: number, maxFrameLen: number) => 0, settings, }; - // tslint:disable-next-line prefer-object-spread (ts2.1 feature) - const secureClientSessionOptions: SecureClientSessionOptions = Object.assign({}, clientSessionOptions); - secureClientSessionOptions.ca = ""; + const secureClientSessionOptions: SecureClientSessionOptions = { ...clientSessionOptions, ca: "..." }; const onConnectHandler = (session: Http2Session, socket: Socket) => {}; const serverHttp2Session: ServerHttp2Session = {} as any; @@ -481,8 +479,6 @@ import { URL } from "node:url"; peerMaxConcurrentStreams: 0, selectPadding: (frameLen: number, maxFrameLen: number) => 0, settings, - streamResetBurst: 1000, - streamResetRate: 33, unknownProtocolTimeout: 123, }; diff --git a/types/node/test/module.ts b/types/node/test/module.ts index 44ab7b99f6aa86..b86e5000b088ca 100644 --- a/types/node/test/module.ts +++ b/types/node/test/module.ts @@ -206,6 +206,9 @@ Module.Module === Module; return nextLoad(url); }; + + const moduleHooks = Module.registerHooks({ load, resolve }); + moduleHooks.deregister(); } // Compile cache diff --git a/types/node/test/process.ts b/types/node/test/process.ts index d7bb969f692f02..96abf142049fb7 100644 --- a/types/node/test/process.ts +++ b/types/node/test/process.ts @@ -250,3 +250,13 @@ process.env.TZ = "test"; process.ref(timeout); process.unref(timeout); } + +{ + // @ts-expect-error + process.execve("/bin/true"); + + assert(process.execve); + process.execve("/bin/true"); // $ExpectType never + process.execve("/bin/true", ["arg1", "arg2"]); // $ExpectType never + process.execve("/bin/true", [], { ...process.env, ENV1: "foo", ENV2: "bar" }); // $ExpectType never +} diff --git a/types/node/test/sqlite.ts b/types/node/test/sqlite.ts index 2bed5b6fa1463f..81d1b843453419 100644 --- a/types/node/test/sqlite.ts +++ b/types/node/test/sqlite.ts @@ -4,6 +4,7 @@ import { TextEncoder } from "node:util"; { const database = new DatabaseSync(":memory:", { open: false }); database.open(); + database.isOpen; // $ExpectType boolean database.exec(` CREATE TABLE data( @@ -23,6 +24,7 @@ import { TextEncoder } from "node:util"; const insert = database.prepare("INSERT INTO types (key, int, double, text, buf) VALUES (?, ?, ?, ?, ?)"); insert.setReadBigInts(true); insert.setAllowBareNamedParameters(true); + insert.setAllowUnknownNamedParameters(true); insert.run(1, 42, 3.14159, "foo", new TextEncoder().encode("a☃b☃c")); insert.run(2, null, null, null, null); insert.run(3, Number(8), Number(2.718), String("bar"), Buffer.from("x☃y☃")); @@ -42,6 +44,11 @@ import { TextEncoder } from "node:util"; database.close(); } +{ + new DatabaseSync(Buffer.from(":memory:")); + new DatabaseSync(new URL("file:///var/lib/sqlite3/db")); +} + { const database = new DatabaseSync(":memory:", { allowExtension: true }); database.loadExtension("/path/to/extension.so"); diff --git a/types/node/test/test.ts b/types/node/test/test.ts index f9ca3f998c6c3f..dccc2671a60834 100644 --- a/types/node/test/test.ts +++ b/types/node/test/test.ts @@ -1004,6 +1004,12 @@ test("waitFor()", (t) => { t.waitFor(async () => true); }); +test("test plan options", (t) => { + t.plan(1, { wait: true }); + t.plan(1, { wait: false }); + t.plan(1, { wait: 1000 }); +}); + // @ts-expect-error Should not be able to instantiate a TestContext const invalidTestContext = new TestContext(); diff --git a/types/node/test/tls.ts b/types/node/test/tls.ts index e76e2ab54e9907..9bfbe67421233c 100644 --- a/types/node/test/tls.ts +++ b/types/node/test/tls.ts @@ -10,6 +10,7 @@ import { DEFAULT_MAX_VERSION, DEFAULT_MIN_VERSION, EphemeralKeyInfo, + getCACertificates, getCiphers, PeerCertificate, rootCertificates, @@ -59,6 +60,7 @@ import { tlsSocket.encrypted; // $ExpectType true + const caCertificates: string[] = getCACertificates("default"); const ciphers: string[] = getCiphers(); const curve: string = DEFAULT_ECDH_CURVE; const maxVersion: string = DEFAULT_MAX_VERSION; diff --git a/types/node/test/util.ts b/types/node/test/util.ts index cc585df2a150db..75e8706fc8710a 100644 --- a/types/node/test/util.ts +++ b/types/node/test/util.ts @@ -54,6 +54,15 @@ util.inspect({ ((options?: util.InspectOptions) => util.inspect({}, options)); ((showHidden?: boolean) => util.inspect({}, showHidden)); +{ + util.diff("abc", "acb"); + util.diff(["a", "b", "c"], ["a", "c", "b"]); + + const diffEntry = util.diff([], [])[0]; + diffEntry[0]; // $ExpectType -1 | 0 | 1 + diffEntry[1]; // $ExpectType string +} + util.format("%s:%s", "foo"); util.format("%s:%s", "foo", "bar", "baz"); util.format(1, 2, 3); diff --git a/types/node/test/v8.ts b/types/node/test/v8.ts index 622443e92601d4..1ed8c90414535d 100644 --- a/types/node/test/v8.ts +++ b/types/node/test/v8.ts @@ -6,6 +6,7 @@ import * as zlib from "node:zlib"; const heapStats = v8.getHeapStatistics(); const numOfDetached = heapStats.number_of_detached_contexts; const heapSpaceStats = v8.getHeapSpaceStatistics(); +const cppHeapStats = v8.getCppHeapStatistics("detailed"); const zapsGarbage: number = heapStats.does_zap_garbage; diff --git a/types/node/test/zlib.ts b/types/node/test/zlib.ts index 4cb1c56bc9c05b..c9761c80e61b92 100644 --- a/types/node/test/zlib.ts +++ b/types/node/test/zlib.ts @@ -10,6 +10,8 @@ import { crc32, createBrotliCompress, createBrotliDecompress, + createZstdCompress, + createZstdDecompress, deflate, deflateRaw, deflateRawSync, @@ -24,6 +26,10 @@ import { inflateSync, unzip, unzipSync, + zstdCompress, + zstdCompressSync, + zstdDecompress, + zstdDecompressSync, } from "node:zlib"; const compressMe = new Buffer("some data"); @@ -149,6 +155,26 @@ brotliDecompress( (err: Error | null, result: Buffer) => result, ); +// zstd +createZstdCompress(); // $ExpectType ZstdCompress +createZstdCompress({ chunkSize: 1024 }); // $ExpectType ZstdCompress +createZstdDecompress(); // $ExpectType ZstdDecompress +createZstdDecompress({ chunkSize: 1024 }); // $ExpectType ZstdDecompress + +zstdCompress(compressMe, (err: Error | null, result: Buffer) => result); +zstdCompress(compressMe, { finishFlush: constants.ZSTD_e_end }, (err: Error | null, result: Buffer) => result); +zstdCompressSync(compressMe); // $ExpectType Buffer || Buffer +zstdCompressSync(compressMe, { finishFlush: constants.ZSTD_e_end }); // $ExpectType Buffer || Buffer + +zstdDecompress(compressMe, (err: Error | null, result: Buffer) => result); +zstdDecompress( + compressMe, + { params: { [constants.ZSTD_d_windowLogMax]: 100 } }, + (err: Error | null, result: Buffer) => result, +); +zstdDecompressSync(compressMe); // $ExpectType Buffer || Buffer +zstdDecompressSync(compressMe, { params: { [constants.ZSTD_d_windowLogMax]: 100 } }); // $ExpectType Buffer || Buffer + { // $ExpectType (buffer: InputType, options?: BrotliOptions | undefined) => Promise || (buffer: InputType, options?: BrotliOptions | undefined) => Promise> const pBrotliCompress = promisify(brotliCompress); @@ -168,6 +194,10 @@ brotliDecompress( const pInflateRaw = promisify(inflateRaw); // $ExpectType (buffer: InputType, options?: ZlibOptions | undefined) => Promise || (buffer: InputType, options?: ZlibOptions | undefined) => Promise> const pUnzip = promisify(unzip); + // $ExpectType (buffer: InputType, options?: ZstdOptions | undefined) => Promise || (buffer: InputType, options?: ZstdOptions | undefined) => Promise> + const pZstdCompress = promisify(zstdCompress); + // $ExpectType (buffer: InputType, options?: ZstdOptions | undefined) => Promise || (buffer: InputType, options?: ZstdOptions | undefined) => Promise> + const pZstdDecompress = promisify(zstdDecompress); (async () => { await pBrotliCompress(Buffer.from("buf")); // $ExpectType Buffer || Buffer @@ -188,6 +218,10 @@ brotliDecompress( await pInflateRaw(Buffer.from("buf"), { flush: constants.Z_NO_FLUSH }); // $ExpectType Buffer || Buffer await pUnzip(Buffer.from("buf")); // $ExpectType Buffer || Buffer await pUnzip(Buffer.from("buf"), { flush: constants.Z_NO_FLUSH }); // $ExpectType Buffer || Buffer + await pZstdCompress(Buffer.from("buf")); // $ExpectType Buffer || Buffer + await pZstdCompress(Buffer.from("buf"), { flush: constants.ZSTD_e_flush }); // $ExpectType Buffer || Buffer + await pZstdDecompress(Buffer.from("buf")); // $ExpectType Buffer || Buffer + await pZstdDecompress(Buffer.from("buf"), { flush: constants.ZSTD_e_flush }); // $ExpectType Buffer || Buffer })(); } diff --git a/types/node/tls.d.ts b/types/node/tls.d.ts index ba37f066533a09..2eada6e71262f1 100644 --- a/types/node/tls.d.ts +++ b/types/node/tls.d.ts @@ -1158,6 +1158,31 @@ declare module "tls" { * @since v0.11.13 */ function createSecureContext(options?: SecureContextOptions): SecureContext; + /** + * Returns an array containing the CA certificates from various sources, depending on `type`: + * + * * `"default"`: return the CA certificates that will be used by the Node.js TLS clients by default. + * * When `--use-bundled-ca` is enabled (default), or `--use-openssl-ca` is not enabled, + * this would include CA certificates from the bundled Mozilla CA store. + * * When `--use-system-ca` is enabled, this would also include certificates from the system's + * trusted store. + * * When `NODE_EXTRA_CA_CERTS` is used, this would also include certificates loaded from the specified + * file. + * * `"system"`: return the CA certificates that are loaded from the system's trusted store, according + * to rules set by `--use-system-ca`. This can be used to get the certificates from the system + * when `--use-system-ca` is not enabled. + * * `"bundled"`: return the CA certificates from the bundled Mozilla CA store. This would be the same + * as `tls.rootCertificates`. + * * `"extra"`: return the CA certificates loaded from `NODE_EXTRA_CA_CERTS`. It's an empty array if + * `NODE_EXTRA_CA_CERTS` is not set. + * @since v22.15.0 + * @param type The type of CA certificates that will be returned. Valid values + * are `"default"`, `"system"`, `"bundled"` and `"extra"`. + * **Default:** `"default"`. + * @returns An array of PEM-encoded certificates. The array may contain duplicates + * if the same certificate is repeatedly stored in multiple sources. + */ + function getCACertificates(type?: "default" | "system" | "bundled" | "extra"): string[]; /** * Returns an array with the names of the supported TLS ciphers. The names are * lower-case for historical reasons, but must be uppercased to be used in diff --git a/types/node/util.d.ts b/types/node/util.d.ts index ff3413bfa813c7..408c36a2bb37d6 100644 --- a/types/node/util.d.ts +++ b/types/node/util.d.ts @@ -133,6 +133,58 @@ declare module "util" { */ columnNumber: number; } + export type DiffEntry = [operation: -1 | 0 | 1, value: string]; + /** + * `util.diff()` compares two string or array values and returns an array of difference entries. + * It uses the Myers diff algorithm to compute minimal differences, which is the same algorithm + * used internally by assertion error messages. + * + * If the values are equal, an empty array is returned. + * + * ```js + * const { diff } = require('node:util'); + * + * // Comparing strings + * const actualString = '12345678'; + * const expectedString = '12!!5!7!'; + * console.log(diff(actualString, expectedString)); + * // [ + * // [0, '1'], + * // [0, '2'], + * // [1, '3'], + * // [1, '4'], + * // [-1, '!'], + * // [-1, '!'], + * // [0, '5'], + * // [1, '6'], + * // [-1, '!'], + * // [0, '7'], + * // [1, '8'], + * // [-1, '!'], + * // ] + * // Comparing arrays + * const actualArray = ['1', '2', '3']; + * const expectedArray = ['1', '3', '4']; + * console.log(diff(actualArray, expectedArray)); + * // [ + * // [0, '1'], + * // [1, '2'], + * // [0, '3'], + * // [-1, '4'], + * // ] + * // Equal values return empty array + * console.log(diff('same', 'same')); + * // [] + * ``` + * @since v22.15.0 + * @experimental + * @param actual The first value to compare + * @param expected The second value to compare + * @returns An array of difference entries. Each entry is an array with two elements: + * * Index 0: `number` Operation code: `-1` for delete, `0` for no-op/unchanged, `1` for insert + * * Index 1: `string` The value associated with the operation + */ + export function diff(actual: string | readonly string[], expected: string | readonly string[]): DiffEntry[]; /** * The `util.format()` method returns a formatted string using the first argument * as a `printf`-like format string which can contain zero or more format @@ -203,10 +255,10 @@ declare module "util" { * the caller function. * * ```js - * const util = require('node:util'); + * import { getCallSites } from 'node:util'; * * function exampleFunction() { - * const callSites = util.getCallSites(); + * const callSites = getCallSites(); * * console.log('Call Sites:'); * callSites.forEach((callSite, index) => { @@ -245,13 +297,13 @@ declare module "util" { * `sourceMap` will be true by default. * * ```ts - * import util from 'node:util'; + * import { getCallSites } from 'node:util'; * * interface Foo { * foo: string; * } * - * const callSites = util.getCallSites({ sourceMap: true }); + * const callSites = getCallSites({ sourceMap: true }); * * // With sourceMap: * // Function Name: '' @@ -308,8 +360,8 @@ declare module "util" { * * ```js * fs.access('file/that/does/not/exist', (err) => { - * const name = util.getSystemErrorMessage(err.errno); - * console.error(name); // no such file or directory + * const message = util.getSystemErrorMessage(err.errno); + * console.error(message); // no such file or directory * }); * ``` * @since v22.12.0 @@ -339,7 +391,6 @@ declare module "util" { * Creates and returns an `AbortController` instance whose `AbortSignal` is marked * as transferable and can be used with `structuredClone()` or `postMessage()`. * @since v18.11.0 - * @experimental * @returns A transferable AbortController */ export function transferableAbortController(): AbortController; @@ -352,7 +403,6 @@ declare module "util" { * channel.port2.postMessage(signal, [signal]); * ``` * @since v18.11.0 - * @experimental * @param signal The AbortSignal * @returns The same AbortSignal */ @@ -394,7 +444,8 @@ declare module "util" { * The `util.inspect()` method returns a string representation of `object` that is * intended for debugging. The output of `util.inspect` may change at any time * and should not be depended upon programmatically. Additional `options` may be - * passed that alter the result. `util.inspect()` will use the constructor's name and/or `@@toStringTag` to make + * passed that alter the result. + * `util.inspect()` will use the constructor's name and/or `@@toStringTag` to make * an identifiable tag for an inspected value. * * ```js @@ -442,7 +493,7 @@ declare module "util" { * The following example highlights the effect of the `compact` option: * * ```js - * import util from 'node:util'; + * import { inspect } from 'node:util'; * * const o = { * a: [1, 2, [[ @@ -452,7 +503,7 @@ declare module "util" { * 'foo']], 4], * b: new Map([['za', 1], ['zb', 'test']]), * }; - * console.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 })); + * console.log(inspect(o, { compact: true, depth: 5, breakLength: 80 })); * * // { a: * // [ 1, @@ -464,7 +515,7 @@ declare module "util" { * // b: Map(2) { 'za' => 1, 'zb' => 'test' } } * * // Setting `compact` to false or an integer creates more reader friendly output. - * console.log(util.inspect(o, { compact: false, depth: 5, breakLength: 80 })); + * console.log(inspect(o, { compact: false, depth: 5, breakLength: 80 })); * * // { * // a: [ @@ -491,11 +542,10 @@ declare module "util" { * // single line. * ``` * - * The `showHidden` option allows [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) and - * [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) entries to be + * The `showHidden` option allows `WeakMap` and `WeakSet` entries to be * inspected. If there are more entries than `maxArrayLength`, there is no - * guarantee which entries are displayed. That means retrieving the same [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) entries twice may - * result in different output. Furthermore, entries + * guarantee which entries are displayed. That means retrieving the same + * `WeakSet` entries twice may result in different output. Furthermore, entries * with no remaining strong references may be garbage collected at any time. * * ```js @@ -543,10 +593,10 @@ declare module "util" { * ```js * import { inspect } from 'node:util'; * - * const thousand = 1_000; - * const million = 1_000_000; - * const bigNumber = 123_456_789n; - * const bigDecimal = 1_234.123_45; + * const thousand = 1000; + * const million = 1000000; + * const bigNumber = 123456789n; + * const bigDecimal = 1234.12345; * * console.log(inspect(thousand, { numericSeparator: true })); * // 1_000 @@ -667,19 +717,23 @@ declare module "util" { */ export function isError(object: unknown): object is Error; /** - * Usage of `util.inherits()` is discouraged. Please use the ES6 `class` and `extends` keywords to get language level inheritance support. Also note + * Usage of `util.inherits()` is discouraged. Please use the ES6 `class` and + * `extends` keywords to get language level inheritance support. Also note * that the two styles are [semantically incompatible](https://github.com/nodejs/node/issues/4179). * - * Inherit the prototype methods from one [constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor) into another. The - * prototype of `constructor` will be set to a new object created from `superConstructor`. + * Inherit the prototype methods from one + * [constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor) into another. The + * prototype of `constructor` will be set to a new object created from + * `superConstructor`. * - * This mainly adds some input validation on top of`Object.setPrototypeOf(constructor.prototype, superConstructor.prototype)`. + * This mainly adds some input validation on top of + * `Object.setPrototypeOf(constructor.prototype, superConstructor.prototype)`. * As an additional convenience, `superConstructor` will be accessible * through the `constructor.super_` property. * * ```js - * import util from 'node:util'; - * import EventEmitter from 'node:events'; + * const util = require('node:util'); + * const EventEmitter = require('node:events'); * * function MyStream() { * EventEmitter.call(this); @@ -726,18 +780,42 @@ declare module "util" { export function inherits(constructor: unknown, superConstructor: unknown): void; export type DebugLoggerFunction = (msg: string, ...param: unknown[]) => void; export interface DebugLogger extends DebugLoggerFunction { + /** + * The `util.debuglog().enabled` getter is used to create a test that can be used + * in conditionals based on the existence of the `NODE_DEBUG` environment variable. + * If the `section` name appears within the value of that environment variable, + * then the returned value will be `true`. If not, then the returned value will be + * `false`. + * + * ```js + * import { debuglog } from 'node:util'; + * const enabled = debuglog('foo').enabled; + * if (enabled) { + * console.log('hello from foo [%d]', 123); + * } + * ``` + * + * If this program is run with `NODE_DEBUG=foo` in the environment, then it will + * output something like: + * + * ```console + * hello from foo [123] + * ``` + */ enabled: boolean; } /** * The `util.debuglog()` method is used to create a function that conditionally - * writes debug messages to `stderr` based on the existence of the `NODE_DEBUG`environment variable. If the `section` name appears within the value of that - * environment variable, then the returned function operates similar to `console.error()`. If not, then the returned function is a no-op. + * writes debug messages to `stderr` based on the existence of the `NODE_DEBUG` + * environment variable. If the `section` name appears within the value of that + * environment variable, then the returned function operates similar to + * `console.error()`. If not, then the returned function is a no-op. * * ```js - * import util from 'node:util'; - * const debuglog = util.debuglog('foo'); + * import { debuglog } from 'node:util'; + * const log = debuglog('foo'); * - * debuglog('hello from foo [%d]', 123); + * log('hello from foo [%d]', 123); * ``` * * If this program is run with `NODE_DEBUG=foo` in the environment, then @@ -753,10 +831,10 @@ declare module "util" { * The `section` supports wildcard also: * * ```js - * import util from 'node:util'; - * const debuglog = util.debuglog('foo-bar'); + * import { debuglog } from 'node:util'; + * const log = debuglog('foo'); * - * debuglog('hi there, it\'s foo-bar [%d]', 2333); + * log('hi there, it\'s foo-bar [%d]', 2333); * ``` * * if it is run with `NODE_DEBUG=foo*` in the environment, then it will output @@ -766,18 +844,19 @@ declare module "util" { * FOO-BAR 3257: hi there, it's foo-bar [2333] * ``` * - * Multiple comma-separated `section` names may be specified in the `NODE_DEBUG`environment variable: `NODE_DEBUG=fs,net,tls`. + * Multiple comma-separated `section` names may be specified in the `NODE_DEBUG` + * environment variable: `NODE_DEBUG=fs,net,tls`. * * The optional `callback` argument can be used to replace the logging function * with a different function that doesn't have any initialization or * unnecessary wrapping. * * ```js - * import util from 'node:util'; - * let debuglog = util.debuglog('internals', (debug) => { + * import { debuglog } from 'node:util'; + * let log = debuglog('internals', (debug) => { * // Replace with a logging function that optimizes out * // testing if the section is enabled - * debuglog = debug; + * log = debug; * }); * ``` * @since v0.11.3 @@ -786,7 +865,7 @@ declare module "util" { * @return The logging function */ export function debuglog(section: string, callback?: (fn: DebugLoggerFunction) => void): DebugLogger; - export const debug: typeof debuglog; + export { debuglog as debug }; /** * Returns `true` if the given `object` is a `Boolean`. Otherwise, returns `false`. * @@ -1003,14 +1082,15 @@ declare module "util" { * such a way that it is marked as deprecated. * * ```js - * import util from 'node:util'; + * import { deprecate } from 'node:util'; * - * exports.obsoleteFunction = util.deprecate(() => { + * export const obsoleteFunction = deprecate(() => { * // Do something here. * }, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.'); * ``` * - * When called, `util.deprecate()` will return a function that will emit a `DeprecationWarning` using the `'warning'` event. The warning will + * When called, `util.deprecate()` will return a function that will emit a + * `DeprecationWarning` using the `'warning'` event. The warning will * be emitted and printed to `stderr` the first time the returned function is * called. After the warning is emitted, the wrapped function is called without * emitting a warning. @@ -1019,16 +1099,24 @@ declare module "util" { * the warning will be emitted only once for that `code`. * * ```js - * import util from 'node:util'; + * import { deprecate } from 'node:util'; * - * const fn1 = util.deprecate(someFunction, someMessage, 'DEP0001'); - * const fn2 = util.deprecate(someOtherFunction, someOtherMessage, 'DEP0001'); + * const fn1 = deprecate( + * () => 'a value', + * 'deprecation message', + * 'DEP0001', + * ); + * const fn2 = deprecate( + * () => 'a different value', + * 'other dep message', + * 'DEP0001', + * ); * fn1(); // Emits a deprecation warning with code DEP0001 * fn2(); // Does not emit a deprecation warning because it has the same code * ``` * * If either the `--no-deprecation` or `--no-warnings` command-line flags are - * used, or if the `process.noDeprecation` property is set to `true`_prior_ to + * used, or if the `process.noDeprecation` property is set to `true` _prior_ to * the first deprecation warning, the `util.deprecate()` method does nothing. * * If the `--trace-deprecation` or `--trace-warnings` command-line flags are set, @@ -1036,10 +1124,13 @@ declare module "util" { * stack trace are printed to `stderr` the first time the deprecated function is * called. * - * If the `--throw-deprecation` command-line flag is set, or the `process.throwDeprecation` property is set to `true`, then an exception will be + * If the `--throw-deprecation` command-line flag is set, or the + * `process.throwDeprecation` property is set to `true`, then an exception will be * thrown when the deprecated function is called. * - * The `--throw-deprecation` command-line flag and `process.throwDeprecation` property take precedence over `--trace-deprecation` and `process.traceDeprecation`. + * The `--throw-deprecation` command-line flag and `process.throwDeprecation` + * property take precedence over `--trace-deprecation` and + * `process.traceDeprecation`. * @since v0.8.0 * @param fn The function that is being deprecated. * @param msg A warning message to display when the deprecated function is invoked. @@ -1070,15 +1161,16 @@ declare module "util" { * Takes an `async` function (or a function that returns a `Promise`) and returns a * function following the error-first callback style, i.e. taking * an `(err, value) => ...` callback as the last argument. In the callback, the - * first argument will be the rejection reason (or `null` if the `Promise` resolved), and the second argument will be the resolved value. + * first argument will be the rejection reason (or `null` if the `Promise` + * resolved), and the second argument will be the resolved value. * * ```js - * import util from 'node:util'; + * import { callbackify } from 'node:util'; * * async function fn() { * return 'hello world'; * } - * const callbackFunction = util.callbackify(fn); + * const callbackFunction = callbackify(fn); * * callbackFunction((err, ret) => { * if (err) throw err; @@ -1093,11 +1185,13 @@ declare module "util" { * ``` * * The callback is executed asynchronously, and will have a limited stack trace. - * If the callback throws, the process will emit an `'uncaughtException'` event, and if not handled will exit. + * If the callback throws, the process will emit an `'uncaughtException'` + * event, and if not handled will exit. * * Since `null` has a special meaning as the first argument to a callback, if a * wrapped function rejects a `Promise` with a falsy value as a reason, the value - * is wrapped in an `Error` with the original value stored in a field named `reason`. + * is wrapped in an `Error` with the original value stored in a field named + * `reason`. * * ```js * function fn() { @@ -1108,7 +1202,7 @@ declare module "util" { * callbackFunction((err, ret) => { * // When the Promise was rejected with `null` it is wrapped with an Error and * // the original value is stored in `reason`. - * err && Object.hasOwn(err, 'reason') && err.reason === null; // true + * err && Object.hasOwn(err, 'reason') && err.reason === null; // true * }); * ``` * @since v8.2.0 @@ -1199,11 +1293,11 @@ declare module "util" { * that returns promises. * * ```js - * import util from 'node:util'; - * import fs from 'node:fs'; + * import { promisify } from 'node:util'; + * import { stat } from 'node:fs'; * - * const stat = util.promisify(fs.stat); - * stat('.').then((stats) => { + * const promisifiedStat = promisify(stat); + * promisifiedStat('.').then((stats) => { * // Do something with `stats` * }).catch((error) => { * // Handle the error. @@ -1213,23 +1307,25 @@ declare module "util" { * Or, equivalently using `async function`s: * * ```js - * import util from 'node:util'; - * import fs from 'node:fs'; + * import { promisify } from 'node:util'; + * import { stat } from 'node:fs'; * - * const stat = util.promisify(fs.stat); + * const promisifiedStat = promisify(stat); * * async function callStat() { - * const stats = await stat('.'); + * const stats = await promisifiedStat('.'); * console.log(`This directory is owned by ${stats.uid}`); * } * * callStat(); * ``` * - * If there is an `original[util.promisify.custom]` property present, `promisify` will return its value, see `Custom promisified functions`. + * If there is an `original[util.promisify.custom]` property present, `promisify` + * will return its value, see [Custom promisified functions](https://nodejs.org/docs/latest-v22.x/api/util.html#custom-promisified-functions). * * `promisify()` assumes that `original` is a function taking a callback as its - * final argument in all cases. If `original` is not a function, `promisify()` will throw an error. If `original` is a function but its last argument is not + * final argument in all cases. If `original` is not a function, `promisify()` + * will throw an error. If `original` is a function but its last argument is not * an error-first callback, it will still be passed an error-first * callback as its last argument. * @@ -1237,7 +1333,7 @@ declare module "util" { * work as expected unless handled specially: * * ```js - * import util from 'node:util'; + * import { promisify } from 'node:util'; * * class Foo { * constructor() { @@ -1251,8 +1347,8 @@ declare module "util" { * * const foo = new Foo(); * - * const naiveBar = util.promisify(foo.bar); - * // TypeError: Cannot read property 'a' of undefined + * const naiveBar = promisify(foo.bar); + * // TypeError: Cannot read properties of undefined (reading 'a') * // naiveBar().then(a => console.log(a)); * * naiveBar.call(foo).then((a) => console.log(a)); // '42' @@ -1371,15 +1467,29 @@ declare module "util" { | "strikethrough" | "underline"; /** - * This function returns a formatted text considering the `format` passed. + * This function returns a formatted text considering the `format` passed + * for printing in a terminal. It is aware of the terminal's capabilities + * and acts according to the configuration set via `NO_COLORS`, + * `NODE_DISABLE_COLORS` and `FORCE_COLOR` environment variables. * * ```js * import { styleText } from 'node:util'; - * const errorMessage = styleText('red', 'Error! Error!'); - * console.log(errorMessage); + * import { stderr } from 'node:process'; + * + * const successMessage = styleText('green', 'Success!'); + * console.log(successMessage); + * + * const errorMessage = styleText( + * 'red', + * 'Error! Error!', + * // Validate if process.stderr has TTY + * { stream: stderr }, + * ); + * console.error(errorMessage); * ``` * - * `util.inspect.colors` also provides text formats such as `italic`, and `underline` and you can combine both: + * `util.inspect.colors` also provides text formats such as `italic`, and + * `underline` and you can combine both: * * ```js * console.log( @@ -1387,8 +1497,8 @@ declare module "util" { * ); * ``` * - * When passing an array of formats, the order of the format applied is left to right so the following style - * might overwrite the previous one. + * When passing an array of formats, the order of the format applied + * is left to right so the following style might overwrite the previous one. * * ```js * console.log( @@ -1768,7 +1878,6 @@ declare module "util" { * components. When parsed, a `MIMEType` object is returned containing * properties for each of these components. * @since v19.1.0, v18.13.0 - * @experimental */ export class MIMEType { /** @@ -2067,7 +2176,9 @@ declare module "util/types" { * A native `External` value is a special type of object that contains a * raw C++ pointer (`void*`) for access from native code, and has no other * properties. Such objects are created either by Node.js internals or native - * addons. In JavaScript, they are [frozen](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) objects with a`null` prototype. + * addons. In JavaScript, they are + * [frozen](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) objects with a + * `null` prototype. * * ```c * #include @@ -2075,7 +2186,7 @@ declare module "util/types" { * napi_value result; * static napi_value MyNapi(napi_env env, napi_callback_info info) { * int* raw = (int*) malloc(1024); - * napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result); + * napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result); * if (status != napi_ok) { * napi_throw_error(env, NULL, "napi_create_external failed"); * return NULL; @@ -2088,14 +2199,17 @@ declare module "util/types" { * ``` * * ```js - * const native = require('napi_addon.node'); + * import native from 'napi_addon.node'; + * import { types } from 'node:util'; + * * const data = native.myNapi(); - * util.types.isExternal(data); // returns true - * util.types.isExternal(0); // returns false - * util.types.isExternal(new String('foo')); // returns false + * types.isExternal(data); // returns true + * types.isExternal(0); // returns false + * types.isExternal(new String('foo')); // returns false * ``` * - * For further information on `napi_create_external`, refer to `napi_create_external()`. + * For further information on `napi_create_external`, refer to + * [`napi_create_external()`](https://nodejs.org/docs/latest-v22.x/api/n-api.html#napi_create_external). * @since v10.0.0 */ function isExternal(object: unknown): boolean; @@ -2219,7 +2333,8 @@ declare module "util/types" { */ function isModuleNamespaceObject(value: unknown): boolean; /** - * Returns `true` if the value was returned by the constructor of a [built-in `Error` type](https://tc39.es/ecma262/#sec-error-objects). + * Returns `true` if the value was returned by the constructor of a + * [built-in `Error` type](https://tc39.es/ecma262/#sec-error-objects). * * ```js * console.log(util.types.isNativeError(new Error())); // true @@ -2234,14 +2349,18 @@ declare module "util/types" { * console.log(util.types.isNativeError(new MyError())); // true * ``` * - * A value being `instanceof` a native error class is not equivalent to `isNativeError()` returning `true` for that value. `isNativeError()` returns `true` for errors - * which come from a different [realm](https://tc39.es/ecma262/#realm) while `instanceof Error` returns `false` for these errors: + * A value being `instanceof` a native error class is not equivalent to `isNativeError()` + * returning `true` for that value. `isNativeError()` returns `true` for errors + * which come from a different [realm](https://tc39.es/ecma262/#realm) while `instanceof Error` returns `false` + * for these errors: * * ```js - * import vm from 'node:vm'; - * const context = vm.createContext({}); - * const myError = vm.runInContext('new Error()', context); - * console.log(util.types.isNativeError(myError)); // true + * import { createContext, runInContext } from 'node:vm'; + * import { types } from 'node:util'; + * + * const context = createContext({}); + * const myError = runInContext('new Error()', context); + * console.log(types.isNativeError(myError)); // true * console.log(myError instanceof Error); // false * ``` * diff --git a/types/node/v8.d.ts b/types/node/v8.d.ts index 9676a81ef2f8a4..b476033595ab3e 100644 --- a/types/node/v8.d.ts +++ b/types/node/v8.d.ts @@ -113,6 +113,87 @@ declare module "v8" { * @since v1.0.0 */ function getHeapStatistics(): HeapInfo; + /** + * It returns an object with a structure similar to the + * [`cppgc::HeapStatistics`](https://v8docs.nodesource.com/node-22.4/d7/d51/heap-statistics_8h_source.html) + * object. See the [V8 documentation](https://v8docs.nodesource.com/node-22.4/df/d2f/structcppgc_1_1_heap_statistics.html) + * for more information about the properties of the object. + * + * ```js + * // Detailed + * ({ + * committed_size_bytes: 131072, + * resident_size_bytes: 131072, + * used_size_bytes: 152, + * space_statistics: [ + * { + * name: 'NormalPageSpace0', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'NormalPageSpace1', + * committed_size_bytes: 131072, + * resident_size_bytes: 131072, + * used_size_bytes: 152, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'NormalPageSpace2', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'NormalPageSpace3', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * { + * name: 'LargePageSpace', + * committed_size_bytes: 0, + * resident_size_bytes: 0, + * used_size_bytes: 0, + * page_stats: [{}], + * free_list_stats: {}, + * }, + * ], + * type_names: [], + * detail_level: 'detailed', + * }); + * ``` + * + * ```js + * // Brief + * ({ + * committed_size_bytes: 131072, + * resident_size_bytes: 131072, + * used_size_bytes: 128864, + * space_statistics: [], + * type_names: [], + * detail_level: 'brief', + * }); + * ``` + * @since v22.15.0 + * @param detailLevel **Default:** `'detailed'`. Specifies the level of detail in the returned statistics. + * Accepted values are: + * * `'brief'`: Brief statistics contain only the top-level + * allocated and used + * memory statistics for the entire heap. + * * `'detailed'`: Detailed statistics also contain a break + * down per space and page, as well as freelist statistics + * and object type histograms. + */ + function getCppHeapStatistics(detailLevel?: "brief" | "detailed"): object; /** * Returns statistics about the V8 heap spaces, i.e. the segments which make up * the V8 heap. Neither the ordering of heap spaces, nor the availability of a diff --git a/types/node/zlib.d.ts b/types/node/zlib.d.ts index 26983801158c9e..b71d553fe76cf9 100644 --- a/types/node/zlib.d.ts +++ b/types/node/zlib.d.ts @@ -148,6 +148,31 @@ declare module "zlib" { */ maxOutputLength?: number | undefined; } + interface ZstdOptions { + /** + * @default constants.ZSTD_e_continue + */ + flush?: number | undefined; + /** + * @default constants.ZSTD_e_end + */ + finishFlush?: number | undefined; + /** + * @default 16 * 1024 + */ + chunkSize?: number | undefined; + /** + * Key-value object containing indexed + * [Zstd parameters](https://nodejs.org/docs/latest-v22.x/api/zlib.html#zstd-constants). + */ + params?: { [key: number]: number | boolean } | undefined; + /** + * Limits output size when using + * [convenience methods](https://nodejs.org/docs/latest-v22.x/api/zlib.html#convenience-methods). + * @default buffer.kMaxLength + */ + maxOutputLength?: number | undefined; + } interface Zlib { /** @deprecated Use bytesWritten instead. */ readonly bytesRead: number; @@ -172,6 +197,16 @@ declare module "zlib" { interface DeflateRaw extends stream.Transform, Zlib, ZlibReset, ZlibParams {} interface InflateRaw extends stream.Transform, Zlib, ZlibReset {} interface Unzip extends stream.Transform, Zlib {} + /** + * @since v22.15.0 + * @experimental + */ + interface ZstdCompress extends stream.Transform, Zlib {} + /** + * @since v22.15.0 + * @experimental + */ + interface ZstdDecompress extends stream.Transform, Zlib {} /** * Computes a 32-bit [Cyclic Redundancy Check](https://en.wikipedia.org/wiki/Cyclic_redundancy_check) checksum of `data`. * If `value` is specified, it is used as the starting value of the checksum, otherwise, 0 is used as the starting value. @@ -233,6 +268,16 @@ declare module "zlib" { * @since v0.5.8 */ function createUnzip(options?: ZlibOptions): Unzip; + /** + * Creates and returns a new `ZstdCompress` object. + * @since v22.15.0 + */ + function createZstdCompress(options?: ZstdOptions): ZstdCompress; + /** + * Creates and returns a new `ZstdDecompress` object. + * @since v22.15.0 + */ + function createZstdDecompress(options?: ZstdOptions): ZstdDecompress; type InputType = string | ArrayBuffer | NodeJS.ArrayBufferView; type CompressCallback = (error: Error | null, result: Buffer) => void; /** @@ -352,6 +397,36 @@ declare module "zlib" { * @since v0.11.12 */ function unzipSync(buf: InputType, options?: ZlibOptions): Buffer; + /** + * @since v22.15.0 + * @experimental + */ + function zstdCompress(buf: InputType, callback: CompressCallback): void; + function zstdCompress(buf: InputType, options: ZstdOptions, callback: CompressCallback): void; + namespace zstdCompress { + function __promisify__(buffer: InputType, options?: ZstdOptions): Promise; + } + /** + * Compress a chunk of data with `ZstdCompress`. + * @since v22.15.0 + * @experimental + */ + function zstdCompressSync(buf: InputType, options?: ZstdOptions): Buffer; + /** + * @since v22.15.0 + * @experimental + */ + function zstdDecompress(buf: InputType, callback: CompressCallback): void; + function zstdDecompress(buf: InputType, options: ZstdOptions, callback: CompressCallback): void; + namespace zstdDecompress { + function __promisify__(buffer: InputType, options?: ZstdOptions): Promise; + } + /** + * Decompress a chunk of data with `ZstdDecompress`. + * @since v22.15.0 + * @experimental + */ + function zstdDecompressSync(buf: InputType, options?: ZstdOptions): Buffer; namespace constants { const BROTLI_DECODE: number; const BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: number; @@ -423,50 +498,106 @@ declare module "zlib" { const INFLATE: number; const INFLATERAW: number; const UNZIP: number; - // Allowed flush values. - const Z_NO_FLUSH: number; - const Z_PARTIAL_FLUSH: number; - const Z_SYNC_FLUSH: number; - const Z_FULL_FLUSH: number; - const Z_FINISH: number; + const ZLIB_VERNUM: number; + const ZSTD_CLEVEL_DEFAULT: number; + const ZSTD_COMPRESS: number; + const ZSTD_DECOMPRESS: number; + const ZSTD_btlazy2: number; + const ZSTD_btopt: number; + const ZSTD_btultra: number; + const ZSTD_btultra2: number; + const ZSTD_c_chainLog: number; + const ZSTD_c_checksumFlag: number; + const ZSTD_c_compressionLevel: number; + const ZSTD_c_contentSizeFlag: number; + const ZSTD_c_dictIDFlag: number; + const ZSTD_c_enableLongDistanceMatching: number; + const ZSTD_c_hashLog: number; + const ZSTD_c_jobSize: number; + const ZSTD_c_ldmBucketSizeLog: number; + const ZSTD_c_ldmHashLog: number; + const ZSTD_c_ldmHashRateLog: number; + const ZSTD_c_ldmMinMatch: number; + const ZSTD_c_minMatch: number; + const ZSTD_c_nbWorkers: number; + const ZSTD_c_overlapLog: number; + const ZSTD_c_searchLog: number; + const ZSTD_c_strategy: number; + const ZSTD_c_targetLength: number; + const ZSTD_c_windowLog: number; + const ZSTD_d_windowLogMax: number; + const ZSTD_dfast: number; + const ZSTD_e_continue: number; + const ZSTD_e_end: number; + const ZSTD_e_flush: number; + const ZSTD_error_GENERIC: number; + const ZSTD_error_checksum_wrong: number; + const ZSTD_error_corruption_detected: number; + const ZSTD_error_dictionaryCreation_failed: number; + const ZSTD_error_dictionary_corrupted: number; + const ZSTD_error_dictionary_wrong: number; + const ZSTD_error_dstBuffer_null: number; + const ZSTD_error_dstSize_tooSmall: number; + const ZSTD_error_frameParameter_unsupported: number; + const ZSTD_error_frameParameter_windowTooLarge: number; + const ZSTD_error_init_missing: number; + const ZSTD_error_literals_headerWrong: number; + const ZSTD_error_maxSymbolValue_tooLarge: number; + const ZSTD_error_maxSymbolValue_tooSmall: number; + const ZSTD_error_memory_allocation: number; + const ZSTD_error_noForwardProgress_destFull: number; + const ZSTD_error_noForwardProgress_inputEmpty: number; + const ZSTD_error_no_error: number; + const ZSTD_error_parameter_combination_unsupported: number; + const ZSTD_error_parameter_outOfBound: number; + const ZSTD_error_parameter_unsupported: number; + const ZSTD_error_prefix_unknown: number; + const ZSTD_error_srcSize_wrong: number; + const ZSTD_error_stabilityCondition_notRespected: number; + const ZSTD_error_stage_wrong: number; + const ZSTD_error_tableLog_tooLarge: number; + const ZSTD_error_version_unsupported: number; + const ZSTD_error_workSpace_tooSmall: number; + const ZSTD_fast: number; + const ZSTD_greedy: number; + const ZSTD_lazy: number; + const ZSTD_lazy2: number; + const Z_BEST_COMPRESSION: number; + const Z_BEST_SPEED: number; const Z_BLOCK: number; - const Z_TREES: number; - // Return codes for the compression/decompression functions. - // Negative values are errors, positive values are used for special but normal events. - const Z_OK: number; - const Z_STREAM_END: number; - const Z_NEED_DICT: number; - const Z_ERRNO: number; - const Z_STREAM_ERROR: number; - const Z_DATA_ERROR: number; - const Z_MEM_ERROR: number; const Z_BUF_ERROR: number; - const Z_VERSION_ERROR: number; - // Compression levels. - const Z_NO_COMPRESSION: number; - const Z_BEST_SPEED: number; - const Z_BEST_COMPRESSION: number; + const Z_DATA_ERROR: number; + const Z_DEFAULT_CHUNK: number; const Z_DEFAULT_COMPRESSION: number; - // Compression strategy. - const Z_FILTERED: number; - const Z_HUFFMAN_ONLY: number; - const Z_RLE: number; - const Z_FIXED: number; + const Z_DEFAULT_LEVEL: number; + const Z_DEFAULT_MEMLEVEL: number; const Z_DEFAULT_STRATEGY: number; const Z_DEFAULT_WINDOWBITS: number; - - const Z_MIN_WINDOWBITS: number; - const Z_MAX_WINDOWBITS: number; - const Z_MIN_CHUNK: number; + const Z_ERRNO: number; + const Z_FILTERED: number; + const Z_FINISH: number; + const Z_FIXED: number; + const Z_FULL_FLUSH: number; + const Z_HUFFMAN_ONLY: number; const Z_MAX_CHUNK: number; - const Z_DEFAULT_CHUNK: number; - const Z_MIN_MEMLEVEL: number; + const Z_MAX_LEVEL: number; const Z_MAX_MEMLEVEL: number; - const Z_DEFAULT_MEMLEVEL: number; + const Z_MAX_WINDOWBITS: number; + const Z_MEM_ERROR: number; + const Z_MIN_CHUNK: number; const Z_MIN_LEVEL: number; - const Z_MAX_LEVEL: number; - const Z_DEFAULT_LEVEL: number; - const ZLIB_VERNUM: number; + const Z_MIN_MEMLEVEL: number; + const Z_MIN_WINDOWBITS: number; + const Z_NEED_DICT: number; + const Z_NO_COMPRESSION: number; + const Z_NO_FLUSH: number; + const Z_OK: number; + const Z_PARTIAL_FLUSH: number; + const Z_RLE: number; + const Z_STREAM_END: number; + const Z_STREAM_ERROR: number; + const Z_SYNC_FLUSH: number; + const Z_VERSION_ERROR: number; } // Allowed flush values. /** @deprecated Use `constants.Z_NO_FLUSH` */